blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
201
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 7
100
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 260
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 11.4k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 80
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 8
9.86M
| extension
stringclasses 52
values | content
stringlengths 8
9.86M
| authors
sequencelengths 1
1
| author
stringlengths 0
119
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7a5b27cc8aeefb3b49e1f3dfee406d6eacd3be5d | b4826dd67114c5282b769fc9d658c9c55617a96d | /DataStructuresLearningSoftware/DataStructuresLearningSoftware/LinkedList1.h | 8e8862c2bea61d946a490efe5f799bfe565ad7be | [] | no_license | Kethavath9199/Data-Structures-Software-Learning | c7d5ed7efaab9baf0ee014311c7727ccbbea0208 | 990512de73234a9f7c348bdca4b38f529ff72a3f | refs/heads/master | 2022-11-26T21:11:32.731210 | 2020-08-06T15:17:04 | 2020-08-06T15:17:04 | 285,603,091 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,123 | h | #pragma once
#include "LinkedList_Introduction.h"
#include "LinkedList_Insertion.h"
#include "LinkedList_Deletion.h"
#include "LinkedList_Traversal.h"
#include "Quiz.h"
#include "DiscussionForum.h"
namespace DataStructuresLearningSoftware {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
/// <summary>
/// Summary for LinkedList1
/// </summary>
public ref class LinkedList1 : public System::Windows::Forms::Form
{
public:
LinkedList1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~LinkedList1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Panel^ panel1;
protected:
private: System::Windows::Forms::Panel^ panel2;
private: System::Windows::Forms::Panel^ MainPanel;
private: System::Windows::Forms::Button^ btnTraversal;
private: System::Windows::Forms::Button^ btnDeletion;
private: System::Windows::Forms::Button^ btnInsertion;
private: System::Windows::Forms::Button^ btnIntroduction;
private: System::Windows::Forms::Button^ btnQuiz;
private: System::Windows::Forms::Button^ btnHome;
private: System::Windows::Forms::Button^ btnNext;
private: System::Windows::Forms::Button^ btnBack;
private: System::Windows::Forms::Label^ lblWelcome;
private: System::Windows::Forms::Button^ button1;
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container ^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)
{
System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(LinkedList1::typeid));
this->panel1 = (gcnew System::Windows::Forms::Panel());
this->btnQuiz = (gcnew System::Windows::Forms::Button());
this->btnTraversal = (gcnew System::Windows::Forms::Button());
this->btnDeletion = (gcnew System::Windows::Forms::Button());
this->btnInsertion = (gcnew System::Windows::Forms::Button());
this->btnIntroduction = (gcnew System::Windows::Forms::Button());
this->panel2 = (gcnew System::Windows::Forms::Panel());
this->button1 = (gcnew System::Windows::Forms::Button());
this->lblWelcome = (gcnew System::Windows::Forms::Label());
this->btnHome = (gcnew System::Windows::Forms::Button());
this->btnNext = (gcnew System::Windows::Forms::Button());
this->btnBack = (gcnew System::Windows::Forms::Button());
this->MainPanel = (gcnew System::Windows::Forms::Panel());
this->panel1->SuspendLayout();
this->panel2->SuspendLayout();
this->SuspendLayout();
//
// panel1
//
this->panel1->BackColor = System::Drawing::Color::AliceBlue;
this->panel1->Controls->Add(this->btnQuiz);
this->panel1->Controls->Add(this->btnTraversal);
this->panel1->Controls->Add(this->btnDeletion);
this->panel1->Controls->Add(this->btnInsertion);
this->panel1->Controls->Add(this->btnIntroduction);
this->panel1->Location = System::Drawing::Point(0, 0);
this->panel1->Name = L"panel1";
this->panel1->Size = System::Drawing::Size(175, 720);
this->panel1->TabIndex = 0;
//
// btnQuiz
//
this->btnQuiz->Cursor = System::Windows::Forms::Cursors::Hand;
this->btnQuiz->FlatAppearance->BorderSize = 0;
this->btnQuiz->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->btnQuiz->Font = (gcnew System::Drawing::Font(L"Comic Sans MS", 11.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->btnQuiz->Location = System::Drawing::Point(0, 210);
this->btnQuiz->Name = L"btnQuiz";
this->btnQuiz->Size = System::Drawing::Size(175, 40);
this->btnQuiz->TabIndex = 4;
this->btnQuiz->Text = L"Quiz Time";
this->btnQuiz->UseVisualStyleBackColor = true;
this->btnQuiz->Click += gcnew System::EventHandler(this, &LinkedList1::btnQuiz_Click);
//
// btnTraversal
//
this->btnTraversal->Cursor = System::Windows::Forms::Cursors::Hand;
this->btnTraversal->FlatAppearance->BorderSize = 0;
this->btnTraversal->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->btnTraversal->Font = (gcnew System::Drawing::Font(L"Comic Sans MS", 11.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->btnTraversal->Location = System::Drawing::Point(0, 170);
this->btnTraversal->Name = L"btnTraversal";
this->btnTraversal->Size = System::Drawing::Size(175, 40);
this->btnTraversal->TabIndex = 3;
this->btnTraversal->Text = L"Traversal";
this->btnTraversal->UseVisualStyleBackColor = true;
this->btnTraversal->Click += gcnew System::EventHandler(this, &LinkedList1::btnTraversal_Click);
//
// btnDeletion
//
this->btnDeletion->Cursor = System::Windows::Forms::Cursors::Hand;
this->btnDeletion->FlatAppearance->BorderSize = 0;
this->btnDeletion->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->btnDeletion->Font = (gcnew System::Drawing::Font(L"Comic Sans MS", 11.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->btnDeletion->Location = System::Drawing::Point(0, 130);
this->btnDeletion->Name = L"btnDeletion";
this->btnDeletion->Size = System::Drawing::Size(175, 40);
this->btnDeletion->TabIndex = 2;
this->btnDeletion->Text = L"Deletion";
this->btnDeletion->UseVisualStyleBackColor = true;
this->btnDeletion->Click += gcnew System::EventHandler(this, &LinkedList1::btnDeletion_Click);
//
// btnInsertion
//
this->btnInsertion->Cursor = System::Windows::Forms::Cursors::Hand;
this->btnInsertion->FlatAppearance->BorderSize = 0;
this->btnInsertion->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->btnInsertion->Font = (gcnew System::Drawing::Font(L"Comic Sans MS", 11.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->btnInsertion->Location = System::Drawing::Point(0, 90);
this->btnInsertion->Name = L"btnInsertion";
this->btnInsertion->Size = System::Drawing::Size(175, 40);
this->btnInsertion->TabIndex = 1;
this->btnInsertion->Text = L"Insertion";
this->btnInsertion->UseVisualStyleBackColor = true;
this->btnInsertion->Click += gcnew System::EventHandler(this, &LinkedList1::btnInsertion_Click);
//
// btnIntroduction
//
this->btnIntroduction->Cursor = System::Windows::Forms::Cursors::Hand;
this->btnIntroduction->FlatAppearance->BorderSize = 0;
this->btnIntroduction->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->btnIntroduction->Font = (gcnew System::Drawing::Font(L"Comic Sans MS", 11.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->btnIntroduction->Location = System::Drawing::Point(0, 50);
this->btnIntroduction->Name = L"btnIntroduction";
this->btnIntroduction->Size = System::Drawing::Size(175, 40);
this->btnIntroduction->TabIndex = 0;
this->btnIntroduction->Text = L"Introduction";
this->btnIntroduction->UseVisualStyleBackColor = true;
this->btnIntroduction->Click += gcnew System::EventHandler(this, &LinkedList1::btnIntroduction_Click);
//
// panel2
//
this->panel2->BackColor = System::Drawing::Color::AliceBlue;
this->panel2->Controls->Add(this->button1);
this->panel2->Controls->Add(this->lblWelcome);
this->panel2->Controls->Add(this->btnHome);
this->panel2->Controls->Add(this->btnNext);
this->panel2->Controls->Add(this->btnBack);
this->panel2->Location = System::Drawing::Point(175, 0);
this->panel2->Name = L"panel2";
this->panel2->Size = System::Drawing::Size(1105, 50);
this->panel2->TabIndex = 1;
//
// button1
//
this->button1->BackColor = System::Drawing::Color::CornflowerBlue;
this->button1->FlatAppearance->BorderSize = 0;
this->button1->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->button1->Font = (gcnew System::Drawing::Font(L"Comic Sans MS", 11.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->button1->Location = System::Drawing::Point(50, 10);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(150, 30);
this->button1->TabIndex = 0;
this->button1->Text = L"Discussion Forum";
this->button1->UseVisualStyleBackColor = false;
this->button1->Click += gcnew System::EventHandler(this, &LinkedList1::button1_Click);
//
// lblWelcome
//
this->lblWelcome->Font = (gcnew System::Drawing::Font(L"Comic Sans MS", 11.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->lblWelcome->ForeColor = System::Drawing::Color::Firebrick;
this->lblWelcome->Location = System::Drawing::Point(206, 15);
this->lblWelcome->Name = L"lblWelcome";
this->lblWelcome->Size = System::Drawing::Size(749, 20);
this->lblWelcome->TabIndex = 4;
this->lblWelcome->Text = L"label1";
this->lblWelcome->TextAlign = System::Drawing::ContentAlignment::MiddleRight;
//
// btnHome
//
this->btnHome->Cursor = System::Windows::Forms::Cursors::Hand;
this->btnHome->FlatAppearance->BorderSize = 0;
this->btnHome->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->btnHome->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"btnHome.Image")));
this->btnHome->Location = System::Drawing::Point(1055, 0);
this->btnHome->Name = L"btnHome";
this->btnHome->Size = System::Drawing::Size(50, 50);
this->btnHome->TabIndex = 2;
this->btnHome->UseVisualStyleBackColor = true;
this->btnHome->Click += gcnew System::EventHandler(this, &LinkedList1::btnHome_Click);
//
// btnNext
//
this->btnNext->Cursor = System::Windows::Forms::Cursors::Hand;
this->btnNext->FlatAppearance->BorderSize = 0;
this->btnNext->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->btnNext->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"btnNext.Image")));
this->btnNext->Location = System::Drawing::Point(1005, 0);
this->btnNext->Name = L"btnNext";
this->btnNext->Size = System::Drawing::Size(50, 50);
this->btnNext->TabIndex = 1;
this->btnNext->UseVisualStyleBackColor = true;
this->btnNext->Click += gcnew System::EventHandler(this, &LinkedList1::btnNext_Click);
//
// btnBack
//
this->btnBack->Cursor = System::Windows::Forms::Cursors::Hand;
this->btnBack->FlatAppearance->BorderSize = 0;
this->btnBack->FlatStyle = System::Windows::Forms::FlatStyle::Popup;
this->btnBack->Image = (cli::safe_cast<System::Drawing::Image^ >(resources->GetObject(L"btnBack.Image")));
this->btnBack->Location = System::Drawing::Point(0, 0);
this->btnBack->Name = L"btnBack";
this->btnBack->Size = System::Drawing::Size(50, 50);
this->btnBack->TabIndex = 0;
this->btnBack->UseVisualStyleBackColor = true;
this->btnBack->Click += gcnew System::EventHandler(this, &LinkedList1::btnBack_Click);
//
// MainPanel
//
this->MainPanel->AutoScroll = true;
this->MainPanel->Location = System::Drawing::Point(175, 50);
this->MainPanel->Name = L"MainPanel";
this->MainPanel->Size = System::Drawing::Size(1105, 670);
this->MainPanel->TabIndex = 2;
//
// LinkedList1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->BackColor = System::Drawing::SystemColors::Control;
this->ClientSize = System::Drawing::Size(1280, 720);
this->Controls->Add(this->MainPanel);
this->Controls->Add(this->panel2);
this->Controls->Add(this->panel1);
this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::None;
this->Name = L"LinkedList1";
this->StartPosition = System::Windows::Forms::FormStartPosition::CenterScreen;
this->Text = L"LinkedList1";
this->Load += gcnew System::EventHandler(this, &LinkedList1::LinkedList1_Load);
this->panel1->ResumeLayout(false);
this->panel2->ResumeLayout(false);
this->ResumeLayout(false);
}
#pragma endregion
public: String ^username;
int moduleId;
String ^fullname;
int modulesCompleted;
private: System::Void btnIntroduction_Click(System::Object^ sender, System::EventArgs^ e) {
OleDb::OleDbConnection ^ DB_Connection = gcnew OleDb::OleDbConnection();
DB_Connection->ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+IO::Path::GetDirectoryName(Application::StartupPath)+"\\Database.accdb";
DB_Connection->Open();
String ^readString = "SELECT * FROM Users WHERE UserName='"+username+"'";
OleDbCommand ^ cmd = gcnew OleDbCommand(readString, DB_Connection);
OleDbDataReader ^ reader = cmd->ExecuteReader();
if(reader->Read()){
modulesCompleted = reader->GetInt32(10);
}
DB_Connection->Close();
if(modulesCompleted < 0){ // 0 is module ID of Introduction
MessageBox::Show("Complete the previous module to unlock this module");
}
else{
moduleId = 0;
display();
}
}
private: System::Void btnInsertion_Click(System::Object^ sender, System::EventArgs^ e) {
OleDb::OleDbConnection ^ DB_Connection = gcnew OleDb::OleDbConnection();
DB_Connection->ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+IO::Path::GetDirectoryName(Application::StartupPath)+"\\Database.accdb";
DB_Connection->Open();
String ^readString = "SELECT * FROM Users WHERE UserName='"+username+"'";
OleDbCommand ^ cmd = gcnew OleDbCommand(readString, DB_Connection);
OleDbDataReader ^ reader = cmd->ExecuteReader();
if(reader->Read()){
modulesCompleted = reader->GetInt32(10);
}
DB_Connection->Close();
if(modulesCompleted < 1){ // 1 is module ID of Insertion
MessageBox::Show("Complete the previous module to unlock this module");
}
else{
moduleId = 1;
display();
}
}
private: System::Void btnDeletion_Click(System::Object^ sender, System::EventArgs^ e) {
OleDb::OleDbConnection ^ DB_Connection = gcnew OleDb::OleDbConnection();
DB_Connection->ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+IO::Path::GetDirectoryName(Application::StartupPath)+"\\Database.accdb";
DB_Connection->Open();
String ^readString = "SELECT * FROM Users WHERE UserName='"+username+"'";
OleDbCommand ^ cmd = gcnew OleDbCommand(readString, DB_Connection);
OleDbDataReader ^ reader = cmd->ExecuteReader();
if(reader->Read()){
modulesCompleted = reader->GetInt32(10);
}
DB_Connection->Close();
if(modulesCompleted < 2){ // 2 is module ID of Deletion
MessageBox::Show("Complete the previous module to unlock this module");
}
else{
moduleId = 2;
display();
}
}
private: System::Void btnTraversal_Click(System::Object^ sender, System::EventArgs^ e) {
OleDb::OleDbConnection ^ DB_Connection = gcnew OleDb::OleDbConnection();
DB_Connection->ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+IO::Path::GetDirectoryName(Application::StartupPath)+"\\Database.accdb";
DB_Connection->Open();
String ^readString = "SELECT * FROM Users WHERE UserName='"+username+"'";
OleDbCommand ^ cmd = gcnew OleDbCommand(readString, DB_Connection);
OleDbDataReader ^ reader = cmd->ExecuteReader();
if(reader->Read()){
modulesCompleted = reader->GetInt32(10);
}
DB_Connection->Close();
if(modulesCompleted < 3){ // 3 is module ID of Traversal
MessageBox::Show("Complete the previous module to unlock this module");
}
else{
moduleId = 3;
display();
}
}
private: System::Void btnQuiz_Click(System::Object^ sender, System::EventArgs^ e) {
OleDb::OleDbConnection ^ DB_Connection = gcnew OleDb::OleDbConnection();
DB_Connection->ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+IO::Path::GetDirectoryName(Application::StartupPath)+"\\Database.accdb";
DB_Connection->Open();
String ^readString = "SELECT * FROM Users WHERE UserName='"+username+"'";
OleDbCommand ^ cmd = gcnew OleDbCommand(readString, DB_Connection);
OleDbDataReader ^ reader = cmd->ExecuteReader();
if(reader->Read()){
modulesCompleted = reader->GetInt32(10);
}
DB_Connection->Close();
if(modulesCompleted < 3){ // 4 is module ID of Quiz
MessageBox::Show("Complete the previous module to unlock this module");
}
else{
moduleId = 4;
display();
}
}
private: System::Void LinkedList1_Load(System::Object^ sender, System::EventArgs^ e) {
moduleId = 0;
OleDb::OleDbConnection ^ DB_Connection = gcnew OleDb::OleDbConnection();
DB_Connection->ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+IO::Path::GetDirectoryName(Application::StartupPath)+"\\Database.accdb";
DB_Connection->Open();
String ^readString = "SELECT * FROM Users WHERE UserName='"+username+"'";
OleDbCommand ^ cmd = gcnew OleDbCommand(readString, DB_Connection);
OleDbDataReader ^ reader = cmd->ExecuteReader();
if(reader->Read()){
fullname = reader->GetString(2);
modulesCompleted = reader->GetInt32(10);
}
DB_Connection->Close();
lblWelcome->Text = "Welcome, "+fullname;
display();
}
public: void display(){
if(modulesCompleted == 0){
btnIntroduction->BackColor = Color::IndianRed;
btnInsertion->BackColor = Color::IndianRed;
btnDeletion->BackColor = Color::IndianRed;
btnTraversal->BackColor = Color::IndianRed;
btnQuiz->BackColor = Color::IndianRed;
}
else if(modulesCompleted == 1){
btnIntroduction->BackColor = Color::MediumSeaGreen;
btnInsertion->BackColor = Color::IndianRed;
btnDeletion->BackColor = Color::IndianRed;
btnTraversal->BackColor = Color::IndianRed;
btnQuiz->BackColor = Color::IndianRed;
}
else if(modulesCompleted == 2){
btnIntroduction->BackColor = Color::MediumSeaGreen;
btnInsertion->BackColor = Color::MediumSeaGreen;
btnDeletion->BackColor = Color::IndianRed;
btnTraversal->BackColor = Color::IndianRed;
btnQuiz->BackColor = Color::IndianRed;
}
else if(modulesCompleted == 3){
btnIntroduction->BackColor = Color::MediumSeaGreen;
btnInsertion->BackColor = Color::MediumSeaGreen;
btnDeletion->BackColor = Color::MediumSeaGreen;
btnTraversal->BackColor = Color::IndianRed;
btnQuiz->BackColor = Color::IndianRed;
}
else if(modulesCompleted == 4){
btnIntroduction->BackColor = Color::MediumSeaGreen;
btnInsertion->BackColor = Color::MediumSeaGreen;
btnDeletion->BackColor = Color::MediumSeaGreen;
btnTraversal->BackColor = Color::MediumSeaGreen;
btnQuiz->BackColor = Color::IndianRed;
}
else if(modulesCompleted == 5){
btnIntroduction->BackColor = Color::MediumSeaGreen;
btnInsertion->BackColor = Color::MediumSeaGreen;
btnDeletion->BackColor = Color::MediumSeaGreen;
btnTraversal->BackColor = Color::MediumSeaGreen;
btnQuiz->BackColor = Color::MediumSeaGreen;
}
if(moduleId == 0){
btnIntroduction->BackColor = Color::CornflowerBlue;
btnBack->Hide();
btnNext->Show();
MainPanel->Controls->Clear();
LinkedList_Introduction ^newUserControl = gcnew LinkedList_Introduction();
newUserControl->username = username;
MainPanel->Controls->Add(newUserControl);
}
else if(moduleId == 1){
btnInsertion->BackColor = Color::CornflowerBlue;
btnBack->Show();
btnNext->Show();
MainPanel->Controls->Clear();
LinkedList_Insertion ^newUserControl = gcnew LinkedList_Insertion();
newUserControl->username = username;
MainPanel->Controls->Add(newUserControl);
}
else if(moduleId == 2){
btnDeletion->BackColor = Color::CornflowerBlue;
btnBack->Show();
btnNext->Show();
MainPanel->Controls->Clear();
LinkedList_Deletion ^newUserControl = gcnew LinkedList_Deletion();
newUserControl->username = username;
MainPanel->Controls->Add(newUserControl);
}
else if(moduleId == 3){
btnTraversal->BackColor = Color::CornflowerBlue;
btnBack->Show();
btnNext->Show();
MainPanel->Controls->Clear();
LinkedList_Traversal ^newUserControl = gcnew LinkedList_Traversal();
newUserControl->username = username;
MainPanel->Controls->Add(newUserControl);
}
else if(moduleId == 4){
btnQuiz->BackColor = Color::CornflowerBlue;
btnNext->Hide();
btnBack->Show();
MainPanel->Controls->Clear();
Quiz ^newUserControl = gcnew Quiz();
newUserControl->username = username;
newUserControl->ds_id = 1;
MainPanel->Controls->Add(newUserControl);
}
}
private: System::Void btnBack_Click(System::Object^ sender, System::EventArgs^ e) {
OleDb::OleDbConnection ^ DB_Connection = gcnew OleDb::OleDbConnection();
DB_Connection->ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+IO::Path::GetDirectoryName(Application::StartupPath)+"\\Database.accdb";
DB_Connection->Open();
String ^readString = "SELECT * FROM Users WHERE UserName='"+username+"'";
OleDbCommand ^ cmd = gcnew OleDbCommand(readString, DB_Connection);
OleDbDataReader ^ reader = cmd->ExecuteReader();
if(reader->Read()){
modulesCompleted = reader->GetInt32(10);
}
DB_Connection->Close();
if(moduleId-1 > modulesCompleted){
MessageBox::Show("Complete the previous module to unlock this module");
}
else{
moduleId--;
display();
}
}
private: System::Void btnNext_Click(System::Object^ sender, System::EventArgs^ e) {
OleDb::OleDbConnection ^ DB_Connection = gcnew OleDb::OleDbConnection();
DB_Connection->ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+IO::Path::GetDirectoryName(Application::StartupPath)+"\\Database.accdb";
DB_Connection->Open();
String ^readString = "SELECT * FROM Users WHERE UserName='"+username+"'";
OleDbCommand ^ cmd = gcnew OleDbCommand(readString, DB_Connection);
OleDbDataReader ^ reader = cmd->ExecuteReader();
if(reader->Read()){
modulesCompleted = reader->GetInt32(10);
}
DB_Connection->Close();
if(moduleId+1 > modulesCompleted){
MessageBox::Show("Complete the previous module to unlock this module");
}
else{
moduleId++;
display();
}
}
private: System::Void btnHome_Click(System::Object^ sender, System::EventArgs^ e) {
OleDb::OleDbConnection ^ DB_Connection = gcnew OleDb::OleDbConnection();
DB_Connection->ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+IO::Path::GetDirectoryName(Application::StartupPath)+"\\Database.accdb";
DB_Connection->Open();
String ^readString = "SELECT * FROM Users WHERE UserName='"+username+"'";
OleDbCommand ^ cmd = gcnew OleDbCommand(readString, DB_Connection);
OleDbDataReader ^ reader = cmd->ExecuteReader();
if(reader->Read()){
modulesCompleted = reader->GetInt32(10);
}
this->Close();
}
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
MainPanel->Controls->Clear();
DiscussionForum ^ discuss = gcnew DiscussionForum;
discuss->username=username;
discuss->module="Linked List";
MainPanel->Controls->Add(discuss);
}
};
}
| [
"[email protected]"
] | |
d81591d29dce1bc6281bcb4828e3df2c238eaa31 | 3ded37602d6d303e61bff401b2682f5c2b52928c | /toy/0503/Classes/Model/MiniGameManager.h | 4e20e6c102df74b97976b50ff848db9697b3cbbc | [] | no_license | CristinaBaby/Demo_CC | 8ce532dcf016f21b442d8b05173a7d20c03d337e | 6f6a7ff132e93271b8952b8da6884c3634f5cb59 | refs/heads/master | 2021-05-02T14:58:52.900119 | 2018-02-09T11:48:02 | 2018-02-09T11:48:02 | 120,727,659 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,500 | h | //
// MiniGameManager.h
// BedtimeStory
//
// Created by maxiang on 8/31/15.
//
//
#ifndef __BedtimeStory__MiniGameManager__
#define __BedtimeStory__MiniGameManager__
#include "cocos2d.h"
#include "AppConfigs.h"
class BaseGameData
{
public:
BaseGameData() :
index(-1),
resPath(""),
logo("")
{};
public:
int index;
std::string resPath;
std::string logo;
};
#pragma mark- Spot Game Data
class SpotGameData : public BaseGameData
{
public:
SpotGameData() :
tmxFileName(""),
textureFileName(""),
textureFilePlist("")
{};
public:
std::string tmxFileName;
std::string textureFileName;
std::string textureFilePlist;
};
#pragma mark- Jigsaw Game Data
class JigsawConfig
{
public:
JigsawConfig():
rows(0),
columns(0),
totalWidth(0.0),
totalHeight(0.0)
{};
struct JigsawTileInfo
{
float offsetx;
float offsety;
float width;
float height;
std::string tilePath;
};
public:
int rows;
int columns;
float totalWidth;
float totalHeight;
void init(const std::string& csvfile);
std::vector<JigsawTileInfo> jigsawTilesVector;
};
class JigsawGameData : public BaseGameData
{
public:
JigsawGameData() :
textureFileName(""),
config(nullptr)
{};
~JigsawGameData()
{
if (config != nullptr)
{
delete config;
}
};
public:
JigsawConfig *config;
std::string textureFileName;
};
#pragma mark- ColorBook Game Data
class ColorBookGameData : public BaseGameData
{
public:
ColorBookGameData() :
pictureFileName(""),
maskFileName("")
{};
public:
std::string pictureFileName;
std::string maskFileName;
};
struct Pen
{
std::string penLogo;
GLuint R;
GLuint G;
GLuint B;
GLuint A;
int index;
};
struct Pattern
{
std::string patternLogo;
std::string pattern;
int index;
};
enum class PensType
{
PensType_None = 0,
PensType_Pen1,
PensType_Pen2,
PensType_Pattern,
};
#pragma mark- Record Game Data
class RecordGameData : public BaseGameData //this data struct used to show logo
{
public:
RecordGameData():
leftStoryImageFile(""),
rightStoryImageFile("")
{};
~RecordGameData()
{
};
public:
std::string leftStoryImageFile;
std::string rightStoryImageFile;
};
struct RecordInfo //this data struct used to store record info
{
int index;
int recordTime;
bool isSelected;
std::string recordFilePath;
std::string recordDate;
};
#pragma mark- Game Manager
enum class GameType
{
None = 0,
Spot,
Jigsaw,
ColorBook,
Story,
Record
};
class MiniGameManager
{
public:
static MiniGameManager* getInstance();
MiniGameManager();
~MiniGameManager();
void initSpotData();
void initJigsawData();
//for color book game
void initColorBookData();
void setupPens(const std::string& path);
void setupPatterns(const std::string& path);
std::vector<Pen> *getPens(){return &_pensVector;};
std::vector<Pattern> *getPatterns(){return &_patternsVector;};
CC_SYNTHESIZE(PensType, _currentPensType, CurrentPensType);
//for record data
void initRecordData();
void saveRecordInfo();
void addRecordInfo(const int storyIndex, RecordInfo *info);
void deleteRecordInfo(const int storyIndex, RecordInfo *info);
std::vector<RecordInfo*>* getRecordInfoVector(const int storyIndex);
void destroySpotGameData();
void destroyJigsawGameData();
void destroyColorBookGameData();
void destroyRecordDataVector();
CC_SYNTHESIZE_READONLY_PASS_BY_REF(std::vector<SpotGameData*>, _spotDataVector, SpotDataVector);
CC_SYNTHESIZE_READONLY_PASS_BY_REF(std::vector<JigsawGameData*>, _jigsawDataVector, JigsawDataVector);
CC_SYNTHESIZE_READONLY_PASS_BY_REF(std::vector<ColorBookGameData*>, _colorBookDataVector, ColorBookDataVector);
CC_SYNTHESIZE_READONLY_PASS_BY_REF(std::vector<RecordGameData*>, _recordDataVector, RecordDataVector);
protected:
std::vector<Pen> _pensVector;
std::vector<Pattern> _patternsVector;
//key->story index, value->RecordInfo sturct, used to store records
std::unordered_map<std::string, std::vector<RecordInfo*>> _recordInfoMap;
cocos2d::ValueVector _recordInfoV;
};
#endif /* defined(__BedtimeStory__MiniGameManager__) */
| [
"[email protected]"
] | |
fe1e4d7b7dbc225bb7231a7cc2942dba348f76f2 | 5be91d95c7c0e3ecd2f6da2cd1f73018f444e0d1 | /ProjetoPOO/Virus.cpp | ff6720161016b4d1a2e02323012ef59f9adb77bc | [
"MIT"
] | permissive | DiogoTojal7/ProjetoPOO- | 8d336ad5ef642efb87376cf15f1e4ab2a4822564 | 5990806a191cbf6f02c7a6b9119ba8c7bd38226b | refs/heads/main | 2023-01-20T19:13:35.422856 | 2020-11-20T18:32:13 | 2020-11-20T18:32:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 111 | cpp | #include "Virus.h"
#include "Pessoa.h"
Virus::Virus(string c1)
{
//ctor
}
Virus::~Virus()
{
//dtor
}
| [
"[email protected]"
] | |
b7fc7bea72bfb0f94f28ccb853e7ddd8a7345818 | c60fe551e358a9c7b3340c9bc8551817f5c6732e | /src/calculate.hpp | 8a0ebe91d8480df15addbc6eaa50f546f5aac1ce | [] | no_license | callumacrae/cpp-calculator | 45b9cd3e70d3a3d01cc518e75e41a26d477d4b29 | 8b80db9895e31906b9e9ba43b7f84bd1cb2854dc | refs/heads/main | 2023-06-04T06:10:34.752871 | 2021-06-29T18:06:01 | 2021-06-29T18:06:01 | 377,284,658 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 154 | hpp | //
// calculate.hpp
// calculator
//
// Created by Callum Macrae on 15/06/2021.
//
#pragma once
float calculate(const std::string_view &mathString);
| [
"[email protected]"
] | |
268cb90fe62680f45851e8bc3359d815e22dd90e | 00692ba81551905b594279fc37ee8e3ca3a4f8eb | /List.cpp | 235115b0fad04a08e1ac76a2c1ed46d9d45554fe | [] | no_license | zhan81776075/Cplusplus-Primer | a52bd0ea62bedf248cc9b72e5915e01930b97460 | 9b4103138c94728a4f9ec541a05ae6835fcf5a41 | refs/heads/master | 2020-05-17T09:16:13.259039 | 2019-06-15T14:16:30 | 2019-06-15T14:16:30 | 183,628,642 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,692 | cpp | #include<iostream>
#include<list>
#include <utility> // std::move std::swap
#include <vector> // std::vector
#include <string> // std::string
int main()
{
/*list::assign
std::list<int> first;
std::list<int> second;
//void assign (size_type n, const value_type& val);
first.assign(7, 100);
//void assign(InputIterator first, InputIterator last);
second.assign(first.begin(), first.end());
//assigning from array
int myints[] = { 1776,7,3 };
first.assign(myints, myints + 3);
std::cout << "Size of first: " << int(first.size()) << '\n';
std::cout << "Size of second: " << int(second.size()) << '\n';
return 0;
*/
/*list::back
std::list<int> mylist;
mylist.push_back(10);
while (mylist.back() != 0)
{
mylist.push_back(mylist.back() - 1);
}
std::cout << "mylist contains:";
for (std::list<int>::iterator it = mylist.begin(); it != mylist.end(); ++it) {
std::cout << ' ' << *it;
}
std::cout << '\n';
return 0;
*/
/*list::begin
int myints[] = { 75,23,65,42,13 };
std::list<int> mylist(myints, myints + 5);
std::cout << "mylist contains:";
for (std::list<int>::iterator it = mylist.begin(); it != mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
*/
/* std::move
std::string foo = "foo-string";
std::string bar = "bar-string";
std::vector<std::string> myvector;
myvector.push_back(foo); // copies
myvector.push_back(std::move(bar)); // moves
std::cout << "myvector contains:";
for (std::string& x : myvector) std::cout << ' ' << x;
std::cout << '\n';
std::cout <<"foo_value:"<< foo << std::endl;
std::cout <<"bar_value:"<< bar << std::endl;
return 0;
*/
} | [
"[email protected]"
] | |
17193755eff1d1ca8964065139151f426bb1bd9f | 163782f0b7be7540fc24223a1065335cfd6e15d1 | /MyForm1.cpp | feb2b92ab01a7b6aa7aa49df11f064981156081a | [] | no_license | pragati0308/FS-Project-Olympics-Management-System | a1f1522976bb6406fb5f1865faa72fd24a679cba | ad2e36295d9f3ac4ead49e3273aa46129e6f67af | refs/heads/main | 2023-06-28T01:55:57.059328 | 2021-08-03T09:24:28 | 2021-08-03T09:24:28 | 392,259,640 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 430 | cpp | #include "MyForm1.h"
#include "MyForm2.h"
#include "MyForm3.h"
#include "MyForm4.h"
#include "MyForm5.h"
#include "MyForm6.h"
#include "MyForm7.h"
using namespace System;
using namespace System::Windows::Forms;
[STAThreadAttribute]
void Main(array<String^>^ args) {
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
Project1::MyForm1 form1;
Application::Run(% form1);
}
| [
"[email protected]"
] | |
63dad212574f3af5756aa197847489d271350ca0 | ce6fc44470dcb5fca78cdd3349a7be70d75f2e3a | /AtCoder/Beginner 134/E.cpp | 92279d0207e0a3f476b32c278259073843f69a42 | [] | no_license | cormackikkert/competitive-programming | f3fa287fcb74248ba218ecd763f8f6df31d57424 | 3a1200b8ff9b6941c422371961a127d7be8f2e00 | refs/heads/master | 2022-12-17T02:02:40.892608 | 2020-09-20T11:47:15 | 2020-09-20T11:47:15 | 266,775,265 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,473 | cpp | #include <bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
using ll = long long;
ll INF = LLONG_MAX;
using vc = vector<char>;
using vi = vector<int>;
using pii = pair<int, int>;
vector<pii> tree;
void modify(int i, pii v) {
i += tree.size()/2;
tree[i] = v;
for (i /= 2; i >= 1; i /= 2) tree[i] = min(tree[2*i], tree[2*i+1]);
}
pii query(int a, int b) {
a += tree.size() / 2; b += tree.size() / 2;
pii s = {1e9+1,1e9+1};
while (a <= b) {
if (a % 2 == 1) s = min(s, tree[a++]);
if (b % 2 == 0) s = min(s, tree[b--]);
a /= 2; b /= 2;
}
return s;
}
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int N; cin >> N;
tree.resize(2*N);
F0R(i, N) {
int val; cin >> val;
modify(i, pii {val, i});
}
int operations = 0;
while (true) {
pii res = query(0, N-1);
if (res.first == 1e9+1) break;
++operations;
int pos = res.second + 1;
while (pos && res.first < 1e9+1) {
if (query(pos, pos).first <= res.first) {++pos; continue;}
modify(pos, pii {1e9+1, 1e9+1});
res = query(res.second + 1, N-1);
}
if (res.first < 1e9+1) modify(res.second, pii {1e9+1, 1e9+1});
}
cout << operations << endl;
} | [
"[email protected]"
] | |
8a29594b18a3bfd282cf2f54d6f903ed3dfc9d31 | 6d3a70abecb8d5f706673ba7068bcd2b941fc84d | /Libraries/Dicom/dcm_value_ul.cpp | 092320c3804318edf9f29b470ceecdd69521ba0d | [] | no_license | MarcoTestDVTk/TestDVTk | 352ab93c0d1ed154985fbad83ed6982029da66d1 | c9202041090d6f68f5cdfd23db904592440fb365 | refs/heads/master | 2021-01-09T20:30:38.405636 | 2016-06-15T08:52:41 | 2016-06-15T08:52:41 | 61,128,764 | 0 | 1 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,399 | cpp | // ------------------------------------------------------
// DVTk - The Healthcare Validation Toolkit (www.dvtk.org)
// Copyright © 2009 DVTk
// ------------------------------------------------------
// This file is part of DVTk.
//
// DVTk is free software; you can redistribute it and/or modify it under the terms of the GNU
// Lesser General Public License as published by the Free Software Foundation; either version 3.0
// of the License, or (at your option) any later version.
//
// DVTk is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
// General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License along with this
// library; if not, see <http://www.gnu.org/licenses/>
//*****************************************************************************
// EXTERNAL DECLARATIONS
//*****************************************************************************
#include "dcm_value_ul.h"
//>>===========================================================================
DCM_VALUE_UL_CLASS::DCM_VALUE_UL_CLASS()
// DESCRIPTION : Constructor.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
// constructor activities
identifierM = "";
}
//>>===========================================================================
DCM_VALUE_UL_CLASS::~DCM_VALUE_UL_CLASS()
// DESCRIPTION : Destructor.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
// destructor activities
}
//>>===========================================================================
bool DCM_VALUE_UL_CLASS::operator = (DCM_VALUE_UL_CLASS& source)
// DESCRIPTION : Equal operator.
// PRECONDITIONS :
// POSTCONDITIONS :
// EXCEPTIONS :
// NOTES :
//<<===========================================================================
{
// copy all members
identifierM = source.identifierM;
UINT32 value;
source.Get(value);
Set(value);
return true;
}
| [
"[email protected]"
] | |
32a996f23bb99a5d1b454fb92cfa81929c3b20cb | 2b089f87cb277c5f40eb0b89ca593fd6cd96b725 | /Graph/bridge_2.cpp | c776d6da84a129d60314860261a5b3e0443f7efe | [] | no_license | ryuat/algorithm | f78d0ab8758bb40a24be4508cf8054d75336ad7c | 2b8dc909a96cb6cbacc46b421ccde92ae40eeacc | refs/heads/master | 2021-07-02T18:46:31.083472 | 2019-02-22T05:43:55 | 2019-02-22T05:43:55 | 134,426,459 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,686 | cpp | /*
다리 만들기 2번째 방법
*/
#include <iostream>
#include <utility>
#include <queue>
int a[100][100]; // (1:육지 2:바다)
int g[100][100]; // 그룹
int d[100][100]; // 거리
int dx[] = {0, 0, -1, 1};
int dy[] = {-1, 1, 0, 0};
using namespace std;
int main(){
int n;
scanf("%d", &n);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
scanf("%d", &a[i][j]);
g[i][j] = 0; // 그룹 초기화
d[i][j] = -1; // 거리 초기화
}
}
// 육지의 그룹 번호 저장
int grp = 0; //그룹번호
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(a[i][j] == 1 && g[i][j] == 0){ // 육지이고 탐색하지 않았다면
queue<pair<int,int>> q;
q.push(make_pair(i,j));
g[i][j] = ++grp; // 다음 그룹
while(!q.empty()){
int x = q.front().first;
int y = q.front().second;
//printf("%dx%d node 호출\n", x,y);
q.pop();
for(int k=0;k<4;k++){
int nx = x+dx[k];
int ny = y+dy[k];
if(0<=nx && nx < n && 0 <= ny && ny < n){ // 인덱스 존재
if(a[nx][ny] == 1 && g[nx][ny]==0){ // 육지이면서 방문 안했다면
q.push(make_pair(nx,ny));
g[nx][ny] = grp; // 현재 grp
}
}
}
}
}
}
}
// dist 계산 + 그룹 채우기
// start node
queue<pair<int,int>> q;
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(a[i][j] == 1 && d[i][j] == -1){ // 육지 노드 & 방문 x 를 모두 start로,
q.push(make_pair(i,j)); // start 노드들 = 육지
d[i][j] = 0;
}
}
}
while(!q.empty()){
int x = q.front().first;
int y = q.front().second;
q.pop();
for(int k=0;k<4;k++){
int nx = x+dx[k];
int ny = y+dy[k];
if(0<=nx && nx < n && 0 <= ny && ny < n){
if(d[nx][ny] == -1){ // 방문 x
d[nx][ny] = d[x][y]+1;
g[nx][ny] = g[x][y];
q.push(make_pair(nx,ny));
}
}
}
}
int ans = n*20*n; // 임의의 큰 수
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
for(int k=0;k<4;k++){ // 인접노드
int nx = i + dx[k];
int ny = j + dy[k];
if(0<=nx && nx < n && 0 <= ny && ny < n){
if(g[nx][ny] != g[i][j]){ //인접노드의 그룹이 다를 경우
if(ans > d[i][j] + d[nx][ny]){ // 인접노드 거리의 합을 구하고
//printf("%dx%d - %dx%d\n",i,j ,nx,ny);
ans = d[i][j] + d[nx][ny]; // 최소값 저장
}
}
}
}
}
}
/*
printf("그룹\n");
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
printf("%2d", g[i][j]);
}
printf("\n");
}
printf("거리\n");
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
printf("%2d", d[i][j]);
}
printf("\n");
}*/
printf("%d\n", ans);
return 0;
}
/*
1. 그룹 저장
2. dist 계산 + 바다 그룹 채우기
3. 서로 다른 그룹이 인접한 바다 중 최소 dist
*/
| [
"[email protected]"
] | |
07f865db53e262c036668795ee294b1f38f15157 | 03d01d133062e1ee483b685b834a76a7bfff6cd4 | /src/ofApp.h | 904a6251f333097b4be8af32d8536c2cea5a0679 | [] | no_license | AgnesChavez/XTrees_2020 | 0a99c22836d29dabd466919756e522f4d4413543 | 3722b643aabf9e2d62f5967e4edab0c868565e4c | refs/heads/master | 2023-05-15T08:05:52.785686 | 2021-06-02T19:10:03 | 2021-06-02T19:10:03 | 296,460,159 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,445 | h | #pragma once
#include "ofMain.h"
//#include "ofxControlPanel.h"
#include "TreesManager.h"
#include "InteractiveAudio.h"
//#include "ofxApp.h"
#include "XTreeButton.h"
#include "AlphaRect.h"
#include "TwitterLayer.h"
#include "LeavesLayer.h"
#include "LinesLayer.h"
#include "TwitterStream.h"
class ofApp :
//public ofxApp{
public ofBaseApp{
public:
ofApp();
~ofApp();
void setup();
void update();
void draw();
void exit();
void mousePressed(ofMouseEventArgs& args);
void mouseMoved(ofMouseEventArgs& args);
void mouseDragged(ofMouseEventArgs& args);
void keyPressed(ofKeyEventArgs& args);
void keyReleased(int key);
void windowResized(int w, int h);
#if USE_PDLIB
void audioReceived(float * input, int bufferSize, int nChannels);
void audioRequested(float * output, int bufferSize, int nChannels);
#endif
vector<ofNode> nodes;
// AlphaRect m_fadeRectangle;
ofSoundPlayer soundtrack;
// FlowersLayer* m_flowersLayer;
ofImage background;
bool use_background;
int backgroundOpacity;
void setFromWindowSize();
private:
void start();
void stop();
void goClicked(bool& do_);
void resetClicked(bool& do_);
// void controlChanged(guiCallbackData & data);
void updateSimulationState();
enum GuiState {
STATE_SETUP,
STATE_GUI,
STATE_SIMULATION
};
enum TimelineStates {
TIME_GROWING, // starts growing trees
TIME_LEAVES, // stop trees, start leaves
TIME_LINES_TRANS, // wait some more time after leaves have fallen
TIME_LINES, // starts the lines
TIME_LEAVESFALLING_TRANS, // stops for N seconds with all the leaves in place
TIME_LEAVESFALLING, // leaves fall,
TIME_LINES_FAST, // when no leaves are anymore present, accelerate lines
TIME_STOP_LINES, // stop
TIME_REGENERATE, // regenerate
TIME_GROWING_TRANS, // wait some time before restarting
};
GuiState m_state;
std::shared_ptr<TreesManager> m_treesLayer = nullptr;
std::shared_ptr<TwitterLayer> m_twitterLayer = nullptr;
std::shared_ptr<LinesLayer> m_linesLayer = nullptr;
std::shared_ptr<LeavesLayer> m_leavesLayer = nullptr;
std::unique_ptr<XTreeButton> m_goBtn = nullptr;
std::unique_ptr<XTreeButton> m_resetBtn = nullptr;
ofColor m_layerObfuscationColor;
// simpleFileLister m_backgroundsLister;
// simpleFileLister m_soundtracksLister;
bool m_internetOk;
int m_backgroundFadeTime;
int m_back1, m_back2;
float m_maxThreads;
bool m_screenshot;
TimelineStates m_simulationState;
unsigned int m_simulationTimer;
unsigned int m_numberOfIterations;
bool m_clearFBO;
string toString(GuiState s) {
switch(s){
case STATE_SETUP : return "STATE_SETUP";
case STATE_GUI : return "STATE_GUI";
case STATE_SIMULATION : return "STATE_SIMULATION";
}
return "";
}
string toString(TimelineStates s) {
switch(s)
{
case TIME_GROWING: return "TIME_GROWING";
case TIME_LEAVES: return "TIME_LEAVES";
case TIME_LINES_TRANS: return "TIME_LINES_TRANS";
case TIME_LINES: return "TIME_LINES";
case TIME_LEAVESFALLING_TRANS: return "TIME_LEAVESFALLING_TRANS";
case TIME_LEAVESFALLING: return "TIME_LEAVESFALLING";
case TIME_LINES_FAST: return "TIME_LINES_FAST";
case TIME_STOP_LINES: return "TIME_STOP_LINES";
case TIME_REGENERATE: return "TIME_REGENERATE";
case TIME_GROWING_TRANS: return "TIME_GROWING_TRANS";
}
return "";
}
bool bDrawStatesInfo = false;
bool bDebug = false;
bool bDrawGui = false;
};
| [
"[email protected]"
] | |
dcf579f490db38b49bd90c24f58bfa07bf5dc9f5 | 7e79799ffb2b32666ed6bce1c3223f4d4e39c7db | /03_C_plusplus/096_Remove_Element/01_Remove_Element.cpp | 89c136e94e49d8941290bdebf8610f18a58e9274 | [] | no_license | daegukdo/TIL | c24fef4b0c694dd5db0a48cc041960b9cb8ede34 | f3ad8d802e0bf55896d97d5d70fd08a1f7736a79 | refs/heads/master | 2022-05-10T12:26:53.270934 | 2022-05-05T13:30:24 | 2022-05-05T13:30:24 | 200,057,564 | 0 | 3 | null | null | null | null | UHC | C++ | false | false | 2,259 | cpp | /*
@ LeetCode
Remove Element
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example 1:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2,
Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
Note that the order of those five elements can be arbitrary.
It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeElement(nums, val);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
ref : https://leetcode.com/explore/learn/card/array-and-string/205/array-two-pointer-technique/1151/
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
// index 저장소 정의
vector<int> removeIndexVct;
// 오름차순 정렬
sort(nums.begin(), nums.end());
// 찾아서 삭제
for(int i = 0; i < nums.size(); i++){
if(nums[i] == val){
removeIndexVct.push_back(i);
}
}
for(int i = removeIndexVct.size() - 1; i > -1; i--){
nums.erase(nums.begin() + removeIndexVct[i]);
}
return nums.size();
}
};
int main() {
int numsArr[4] = {3,2,2,3};
vector<int> nums(numsArr, *(&numsArr + 1));
int val = 3;
Solution s;
int r = s.removeElement(nums, val);
return 0;
}
| [
"[email protected]"
] | |
d848543165c911d67f18f6fc3dd2334212dc102b | ca0f494b45522eab05d0342f25b1f0907ce1d720 | /sources/services/sysmgr/srv/src/NetRpc.cpp | b7e345feb207fa06a82510d93df6159d639466a5 | [] | no_license | hackboxguy/brbox | 9f79f21097685464c9c9a429603e586e034f8cae | ba3850807067b7f623ead5f65dad9c0bf0b3ec2d | refs/heads/master | 2023-07-21T15:38:07.666015 | 2023-07-10T11:51:00 | 2023-07-10T11:51:00 | 32,072,062 | 26 | 9 | null | null | null | null | UTF-8 | C++ | false | false | 13,846 | cpp | #include "NetRpc.h"
#include "ADSysInfo.hpp"
//#include "SysmgrJsonDef.h"
/* ------------------------------------------------------------------------- */
NetRpc:: NetRpc(std::string rpcName,int myIndex,bool emu,bool log,SYSMGR_CMN_DATA_CACHE *pData):ADJsonRpcMgrConsumer(rpcName,myIndex,emu,log)
{
pDataCache=pData;
}
/* ------------------------------------------------------------------------- */
NetRpc::~ NetRpc()
{
}
/* ------------------------------------------------------------------------- */
int NetRpc::MapJsonToBinary(JsonDataCommObj* pReq,int index)
{
//printf("NetRpc::MapJsonToBinary called\n");
EJSON_SYSMGR_RPC_TYPES command =(EJSON_SYSMGR_RPC_TYPES)index;
switch(command)
{
case EJSON_SYSMGR_RPC_GET_MAC_ADDR :return json_to_bin_get_mac_addr(pReq);
case EJSON_SYSMGR_RPC_SET_MAC_ADDR :return json_to_bin_set_mac_addr(pReq);
case EJSON_SYSMGR_RPC_GET_ETH_COUNT:return json_to_bin_get_eth_count(pReq);
case EJSON_SYSMGR_RPC_GET_ETH_NAME :return json_to_bin_get_eth_name(pReq);
case EJSON_SYSMGR_RPC_GET_IP_ADDR :return json_to_bin_get_ip_addr(pReq);
case EJSON_SYSMGR_RPC_SET_IP_ADDR :return json_to_bin_set_ip_addr(pReq);
case EJSON_SYSMGR_RPC_GET_NETMASK :return json_to_bin_get_netmask(pReq);
case EJSON_SYSMGR_RPC_SET_NETMASK :return json_to_bin_set_netmask(pReq);
}
return -1;//0;
}
/* ------------------------------------------------------------------------- */
int NetRpc::MapBinaryToJson(JsonDataCommObj* pReq,int index)
{
//printf("NetRpc::MapBinaryToJson called\n");
EJSON_SYSMGR_RPC_TYPES command =(EJSON_SYSMGR_RPC_TYPES)index;
switch(command)
{
case EJSON_SYSMGR_RPC_GET_MAC_ADDR :return bin_to_json_get_mac_addr(pReq);
case EJSON_SYSMGR_RPC_SET_MAC_ADDR :return bin_to_json_set_mac_addr(pReq);
case EJSON_SYSMGR_RPC_GET_ETH_COUNT:return bin_to_json_get_eth_count(pReq);
case EJSON_SYSMGR_RPC_GET_ETH_NAME :return bin_to_json_get_eth_name(pReq);
case EJSON_SYSMGR_RPC_GET_IP_ADDR :return bin_to_json_get_ip_addr(pReq);
case EJSON_SYSMGR_RPC_SET_IP_ADDR :return bin_to_json_set_ip_addr(pReq);
case EJSON_SYSMGR_RPC_GET_NETMASK :return bin_to_json_get_netmask(pReq);
case EJSON_SYSMGR_RPC_SET_NETMASK :return bin_to_json_set_netmask(pReq);
}
return -1;
}
/* ------------------------------------------------------------------------- */
int NetRpc::ProcessWork(JsonDataCommObj* pReq,int index,ADJsonRpcMgrProducer* pObj)
{
//printf("NetRpc::ProcessWork called\n");
EJSON_SYSMGR_RPC_TYPES command =(EJSON_SYSMGR_RPC_TYPES)index;
switch(command)
{
case EJSON_SYSMGR_RPC_GET_MAC_ADDR :return process_get_mac_addr(pReq);
case EJSON_SYSMGR_RPC_SET_MAC_ADDR :return process_set_mac_addr(pReq);
case EJSON_SYSMGR_RPC_GET_ETH_COUNT:return process_get_eth_count(pReq);
case EJSON_SYSMGR_RPC_GET_ETH_NAME :return process_get_eth_name(pReq);
case EJSON_SYSMGR_RPC_GET_IP_ADDR :return process_get_ip_addr(pReq);
case EJSON_SYSMGR_RPC_SET_IP_ADDR :return process_set_ip_addr(pReq);
case EJSON_SYSMGR_RPC_GET_NETMASK :return process_get_netmask(pReq);
case EJSON_SYSMGR_RPC_SET_NETMASK :return process_set_netmask(pReq);
}
return 0;
}
/* ------------------------------------------------------------------------- */
RPC_SRV_RESULT NetRpc::ProcessWorkAsync(int index,unsigned char* pWorkData)
{
RPC_SRV_RESULT ret_val=RPC_SRV_RESULT_FAIL;
return ret_val;
}
/* ------------------------------------------------------------------------- */
int NetRpc::json_to_bin_get_mac_addr(JsonDataCommObj* pReq)
{
SYSMGR_MAC_ADDR_PACKET* pPanelCmdObj=NULL;
PREPARE_JSON_REQUEST(RPC_SRV_REQ,SYSMGR_MAC_ADDR_PACKET,RPC_SRV_ACT_READ,EJSON_SYSMGR_RPC_GET_MAC_ADDR);
//after assigning pointer to pPanelReq->dataRef, modify cmd-req-obj with correct client arguments
//JSON_STRING_TO_ENUM(SYSMGR_RPC_MAC_ADDR_ARG_IFACE,SYSMGR_RPC_MAC_ADDR_ARG_IFACE_TABL,EJSON_SYSMGR_IFACE_TYPE,EJSON_SYSMGR_IFACE_TYPE_UNKNOWN,pPanelCmdObj->eth_type);
JSON_STRING_TO_STRING(SYSMGR_RPC_IP_ADDR_ARG_IFACE,pPanelCmdObj->eth_name);//changed from fixed enum list to string
return 0;
}
int NetRpc::bin_to_json_get_mac_addr(JsonDataCommObj* pReq)
{
PREPARE_JSON_RESP_STRING(RPC_SRV_REQ,SYSMGR_MAC_ADDR_PACKET,SYSMGR_RPC_MAC_ADDR_ARG,mac_addr);
return 0;
}
int NetRpc::process_get_mac_addr(JsonDataCommObj* pReq)
{
ADSysInfo SysInfo;//lib-class for reading cpu-info and system-info
char ip[512];char netmask[512];
RPC_SRV_REQ *pPanelReq=NULL;
pPanelReq=(RPC_SRV_REQ *)pReq->pDataObj;
SYSMGR_MAC_ADDR_PACKET* pPacket;
pPacket=(SYSMGR_MAC_ADDR_PACKET*)pPanelReq->dataRef;
const char *table[] = SYSMGR_RPC_MAC_ADDR_ARG_IFACE_TABL;
//if network is connected,then read details from SysInfo
//if(SysInfo.read_network_info((char*)table[pPacket->eth_type],pPacket->mac_addr,ip,netmask)==0)
if(SysInfo.read_network_info(pPacket->eth_name,pPacket->mac_addr,ip,netmask)==0)
pPanelReq->result=RPC_SRV_RESULT_SUCCESS;
else
{
//if network is not connected, use ifconfig method
//if(SysInfo.read_network_info_ifconfig((char*)table[pPacket->eth_type],pPacket->mac_addr,ip,netmask)==0)
if(SysInfo.read_network_info_ifconfig(pPacket->eth_name,pPacket->mac_addr,ip,netmask)==0)
pPanelReq->result=RPC_SRV_RESULT_SUCCESS;
else
pPanelReq->result=RPC_SRV_RESULT_FAIL;
}
return 0;
}
/* ------------------------------------------------------------------------- */
int NetRpc::json_to_bin_set_mac_addr(JsonDataCommObj* pReq)
{
SYSMGR_MAC_ADDR_PACKET* pPanelCmdObj=NULL;
PREPARE_JSON_REQUEST(RPC_SRV_REQ,SYSMGR_MAC_ADDR_PACKET,RPC_SRV_ACT_WRITE,EJSON_SYSMGR_RPC_SET_MAC_ADDR);
//after assigning pointer to pPanelReq->dataRef, modify cmd-req-obj with correct client arguments
JSON_STRING_TO_ENUM(SYSMGR_RPC_MAC_ADDR_ARG_IFACE,SYSMGR_RPC_MAC_ADDR_ARG_IFACE_TABL,EJSON_SYSMGR_IFACE_TYPE,EJSON_SYSMGR_IFACE_TYPE_UNKNOWN,pPanelCmdObj->eth_type);
return 0;
}
int NetRpc::bin_to_json_set_mac_addr(JsonDataCommObj* pReq)
{
PREPARE_JSON_RESP(RPC_SRV_REQ,SYSMGR_MAC_ADDR_PACKET);
return 0;
}
int NetRpc::process_set_mac_addr(JsonDataCommObj* pReq)
{
//TODO:dont supprt mac writing yet
RPC_SRV_REQ *pPanelReq=NULL;
pPanelReq=(RPC_SRV_REQ *)pReq->pDataObj;
pPanelReq->result=RPC_SRV_RESULT_FEATURE_UNSUPPORTED;
return 0;
}
/* ------------------------------------------------------------------------- */
int NetRpc::json_to_bin_get_eth_count(JsonDataCommObj* pReq)
{
SYSMGR_ETH_COUNT_PACKET* pPanelCmdObj=NULL;
PREPARE_JSON_REQUEST(RPC_SRV_REQ,SYSMGR_ETH_COUNT_PACKET,RPC_SRV_ACT_READ,EJSON_SYSMGR_RPC_GET_ETH_COUNT);
return 0;
}
int NetRpc::bin_to_json_get_eth_count(JsonDataCommObj* pReq)
{
PREPARE_JSON_RESP_INT(RPC_SRV_REQ,SYSMGR_MAC_ADDR_PACKET,SYSMGR_RPC_ETH_COUNT_ARG,EthCountIndx);
return 0;
}
int NetRpc::process_get_eth_count(JsonDataCommObj* pReq)
{
RPC_SRV_REQ *pPanelReq=NULL;
pPanelReq=(RPC_SRV_REQ *)pReq->pDataObj;
SYSMGR_ETH_COUNT_PACKET* pPacket;
pPacket=(SYSMGR_ETH_COUNT_PACKET*)pPanelReq->dataRef;
pPacket->EthCountIndx=0;
ADSysInfo SysInfo;
pPanelReq->result=SysInfo.get_total_eth_count(pPacket->EthCountIndx);
return 0;
}
/* ------------------------------------------------------------------------- */
int NetRpc::json_to_bin_get_eth_name(JsonDataCommObj* pReq)
{
SYSMGR_ETH_NAME_PACKET* pPanelCmdObj=NULL;
PREPARE_JSON_REQUEST(RPC_SRV_REQ,SYSMGR_ETH_NAME_PACKET,RPC_SRV_ACT_READ,EJSON_SYSMGR_RPC_GET_ETH_NAME);
JSON_STRING_TO_INT(SYSMGR_RPC_ETH_NAME_ARG_INDEX,pPanelCmdObj->EthCountIndx);
return 0;
}
int NetRpc::bin_to_json_get_eth_name(JsonDataCommObj* pReq)
{
PREPARE_JSON_RESP_STRING(RPC_SRV_REQ,SYSMGR_ETH_NAME_PACKET,SYSMGR_RPC_ETH_NAME_ARG,eth_name);
return 0;
}
int NetRpc::process_get_eth_name(JsonDataCommObj* pReq)
{
RPC_SRV_REQ *pPanelReq=NULL;
pPanelReq=(RPC_SRV_REQ *)pReq->pDataObj;
SYSMGR_ETH_COUNT_PACKET* pPacket;
pPacket=(SYSMGR_ETH_COUNT_PACKET*)pPanelReq->dataRef;
//pPacket->EthCountIndx=0;
//TODO:
ADSysInfo SysInfo;int tmpCount;
pPanelReq->result=SysInfo.get_total_eth_count(tmpCount);
if(pPanelReq->result!=RPC_SRV_RESULT_SUCCESS)
return 0;
if(tmpCount==0)
{
pPanelReq->result=RPC_SRV_RESULT_FAIL;//no eth interfaces are available
return 0;
}
//zero based index must be passed by the client
if(pPacket->EthCountIndx > (tmpCount-1) )
{
pPanelReq->result=RPC_SRV_RESULT_ARG_ERROR;
return 0;
}
pPanelReq->result=SysInfo.get_nth_eth_name(pPacket->EthCountIndx+1,pPacket->eth_name);
return 0;
}
/* ------------------------------------------------------------------------- */
int NetRpc::json_to_bin_get_ip_addr(JsonDataCommObj* pReq)
{
SYSMGR_NET_INFO_PACKET* pPanelCmdObj=NULL;
PREPARE_JSON_REQUEST(RPC_SRV_REQ,SYSMGR_NET_INFO_PACKET,RPC_SRV_ACT_READ,EJSON_SYSMGR_RPC_GET_IP_ADDR);
//after assigning pointer to pPanelReq->dataRef, modify cmd-req-obj with correct client arguments
//JSON_STRING_TO_ENUM(SYSMGR_RPC_IP_ADDR_ARG_IFACE,SYSMGR_RPC_IP_ADDR_ARG_IFACE_TABL,EJSON_SYSMGR_IFACE_TYPE,EJSON_SYSMGR_IFACE_TYPE_UNKNOWN,pPanelCmdObj->eth_type);
JSON_STRING_TO_STRING(SYSMGR_RPC_IP_ADDR_ARG_IFACE,pPanelCmdObj->eth_name);//changed from fixed enum list to string
return 0;
}
int NetRpc::bin_to_json_get_ip_addr(JsonDataCommObj* pReq)
{
PREPARE_JSON_RESP_STRING(RPC_SRV_REQ,SYSMGR_NET_INFO_PACKET,SYSMGR_RPC_IP_ADDR_ARG,addr);
return 0;
}
int NetRpc::process_get_ip_addr(JsonDataCommObj* pReq)
{
ADSysInfo SysInfo;//lib-class for reading cpu-info and system-info
char netmask[512];char mac[512];
RPC_SRV_REQ *pPanelReq=NULL;
pPanelReq=(RPC_SRV_REQ *)pReq->pDataObj;
SYSMGR_NET_INFO_PACKET* pPacket;
pPacket=(SYSMGR_NET_INFO_PACKET*)pPanelReq->dataRef;
const char *table[] = SYSMGR_RPC_MAC_ADDR_ARG_IFACE_TABL;
//if network is connected,then read details from SysInfo
//if(SysInfo.read_network_info((char*)table[pPacket->eth_type],mac,pPacket->addr,netmask)==0)
if(SysInfo.read_network_info(pPacket->eth_name,mac,pPacket->addr,netmask)==0)
pPanelReq->result=RPC_SRV_RESULT_SUCCESS;
else
{
//if network is not connected, use ifconfig method
//if(SysInfo.read_network_info_ifconfig((char*)table[pPacket->eth_type],mac,pPacket->addr,netmask)==0)
if(SysInfo.read_network_info_ifconfig(pPacket->eth_name,mac,pPacket->addr,netmask)==0)
pPanelReq->result=RPC_SRV_RESULT_SUCCESS;
else
pPanelReq->result=RPC_SRV_RESULT_FAIL;
}
return 0;
}
int NetRpc::json_to_bin_set_ip_addr(JsonDataCommObj* pReq)
{
SYSMGR_NET_INFO_PACKET* pPanelCmdObj=NULL;
PREPARE_JSON_REQUEST(RPC_SRV_REQ,SYSMGR_NET_INFO_PACKET,RPC_SRV_ACT_WRITE,EJSON_SYSMGR_RPC_SET_IP_ADDR);
//after assigning pointer to pPanelReq->dataRef, modify cmd-req-obj with correct client arguments
JSON_STRING_TO_ENUM(SYSMGR_RPC_IP_ADDR_ARG_IFACE,SYSMGR_RPC_IP_ADDR_ARG_IFACE_TABL,EJSON_SYSMGR_IFACE_TYPE,EJSON_SYSMGR_IFACE_TYPE_UNKNOWN,pPanelCmdObj->eth_type);
return 0;
}
int NetRpc::bin_to_json_set_ip_addr(JsonDataCommObj* pReq)
{
PREPARE_JSON_RESP(RPC_SRV_REQ,SYSMGR_NET_INFO_PACKET);
return 0;
}
int NetRpc::process_set_ip_addr(JsonDataCommObj* pReq)
{
//TODO:dont supprt mac writing yet
RPC_SRV_REQ *pPanelReq=NULL;
pPanelReq=(RPC_SRV_REQ *)pReq->pDataObj;
pPanelReq->result=RPC_SRV_RESULT_FEATURE_UNSUPPORTED;
return 0;
}
/* ------------------------------------------------------------------------- */
int NetRpc::json_to_bin_get_netmask(JsonDataCommObj* pReq)
{
SYSMGR_NET_INFO_PACKET* pPanelCmdObj=NULL;
PREPARE_JSON_REQUEST(RPC_SRV_REQ,SYSMGR_NET_INFO_PACKET,RPC_SRV_ACT_READ,EJSON_SYSMGR_RPC_GET_NETMASK);
//after assigning pointer to pPanelReq->dataRef, modify cmd-req-obj with correct client arguments
//JSON_STRING_TO_ENUM(SYSMGR_RPC_NETMASK_ARG_IFACE,SYSMGR_RPC_NETMASK_ARG_IFACE_TABL,EJSON_SYSMGR_IFACE_TYPE,EJSON_SYSMGR_IFACE_TYPE_UNKNOWN,pPanelCmdObj->eth_type);
JSON_STRING_TO_STRING(SYSMGR_RPC_IP_ADDR_ARG_IFACE,pPanelCmdObj->eth_name);//changed from fixed enum list to string
return 0;
}
int NetRpc::bin_to_json_get_netmask(JsonDataCommObj* pReq)
{
PREPARE_JSON_RESP_STRING(RPC_SRV_REQ,SYSMGR_NET_INFO_PACKET,SYSMGR_RPC_NETMASK_ARG,addr);
return 0;
}
int NetRpc::process_get_netmask(JsonDataCommObj* pReq)
{
ADSysInfo SysInfo;//lib-class for reading cpu-info and system-info
char ip[512];char mac[512];
RPC_SRV_REQ *pPanelReq=NULL;
pPanelReq=(RPC_SRV_REQ *)pReq->pDataObj;
SYSMGR_NET_INFO_PACKET* pPacket;
pPacket=(SYSMGR_NET_INFO_PACKET*)pPanelReq->dataRef;
const char *table[] = SYSMGR_RPC_MAC_ADDR_ARG_IFACE_TABL;
//if network is connected,then read details from SysInfo
//if(SysInfo.read_network_info((char*)table[pPacket->eth_type],mac,ip,pPacket->addr)==0)
if(SysInfo.read_network_info(pPacket->eth_name,mac,ip,pPacket->addr)==0)
pPanelReq->result=RPC_SRV_RESULT_SUCCESS;
else
{
//if network is not connected, use ifconfig method
//if(SysInfo.read_network_info_ifconfig((char*)table[pPacket->eth_type],mac,ip,pPacket->addr)==0)
if(SysInfo.read_network_info_ifconfig(pPacket->eth_name,mac,ip,pPacket->addr)==0)
pPanelReq->result=RPC_SRV_RESULT_SUCCESS;
else
pPanelReq->result=RPC_SRV_RESULT_FAIL;
}
return 0;
}
int NetRpc::json_to_bin_set_netmask(JsonDataCommObj* pReq)
{
SYSMGR_NET_INFO_PACKET* pPanelCmdObj=NULL;
PREPARE_JSON_REQUEST(RPC_SRV_REQ,SYSMGR_NET_INFO_PACKET,RPC_SRV_ACT_WRITE,EJSON_SYSMGR_RPC_SET_NETMASK);
//after assigning pointer to pPanelReq->dataRef, modify cmd-req-obj with correct client arguments
JSON_STRING_TO_ENUM(SYSMGR_RPC_NETMASK_ARG_IFACE,SYSMGR_RPC_NETMASK_ARG_IFACE_TABL,EJSON_SYSMGR_IFACE_TYPE,EJSON_SYSMGR_IFACE_TYPE_UNKNOWN,pPanelCmdObj->eth_type);
return 0;
}
int NetRpc::bin_to_json_set_netmask(JsonDataCommObj* pReq)
{
PREPARE_JSON_RESP(RPC_SRV_REQ,SYSMGR_NET_INFO_PACKET);
return 0;
}
int NetRpc::process_set_netmask(JsonDataCommObj* pReq)
{
//TODO:dont supprt mac writing yet
RPC_SRV_REQ *pPanelReq=NULL;
pPanelReq=(RPC_SRV_REQ *)pReq->pDataObj;
pPanelReq->result=RPC_SRV_RESULT_FEATURE_UNSUPPORTED;
return 0;
}
/* ------------------------------------------------------------------------- */
| [
"[email protected]"
] | |
b4771a67b824c59573db7b52440bca76c5b0b212 | 6ced41da926682548df646099662e79d7a6022c5 | /aws-cpp-sdk-drs/source/model/DeleteJobResult.cpp | 60c099c98cc79b83f6be170ce28bb65fce0eb780 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | irods/aws-sdk-cpp | 139104843de529f615defa4f6b8e20bc95a6be05 | 2c7fb1a048c96713a28b730e1f48096bd231e932 | refs/heads/main | 2023-07-25T12:12:04.363757 | 2022-08-26T15:33:31 | 2022-08-26T15:33:31 | 141,315,346 | 0 | 1 | Apache-2.0 | 2022-08-26T17:45:09 | 2018-07-17T16:24:06 | C++ | UTF-8 | C++ | false | false | 787 | cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/drs/model/DeleteJobResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::drs::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
DeleteJobResult::DeleteJobResult()
{
}
DeleteJobResult::DeleteJobResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
DeleteJobResult& DeleteJobResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
AWS_UNREFERENCED_PARAM(result);
return *this;
}
| [
"[email protected]"
] | |
3a7ef778fda72ff154a433928e69d9ef8cd0402e | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /iss/src/v20230517/model/ListRecordBackupPlanDevicesResponse.cpp | 6d46a2f38f705174039b0c0c7a1be1bb2606e58b | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 4,149 | cpp | /*
* 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.
*/
#include <tencentcloud/iss/v20230517/model/ListRecordBackupPlanDevicesResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Iss::V20230517::Model;
using namespace std;
ListRecordBackupPlanDevicesResponse::ListRecordBackupPlanDevicesResponse() :
m_dataHasBeenSet(false)
{
}
CoreInternalOutcome ListRecordBackupPlanDevicesResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Core::Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("Data") && !rsp["Data"].IsNull())
{
if (!rsp["Data"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Data` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_data.Deserialize(rsp["Data"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_dataHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
string ListRecordBackupPlanDevicesResponse::ToJsonString() const
{
rapidjson::Document value;
value.SetObject();
rapidjson::Document::AllocatorType& allocator = value.GetAllocator();
if (m_dataHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Data";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_data.ToJsonObject(value[key.c_str()], allocator);
}
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
value.Accept(writer);
return buffer.GetString();
}
ListRecordBackupPlanDevicesData ListRecordBackupPlanDevicesResponse::GetData() const
{
return m_data;
}
bool ListRecordBackupPlanDevicesResponse::DataHasBeenSet() const
{
return m_dataHasBeenSet;
}
| [
"[email protected]"
] | |
7635f0b820925c78502746b914a9d79081d1655a | 26ee37a92336ac6268b6d23f965d1b54d5594a7b | /src/consistency/traditional_ssp_consistency.cc | 18a5488af0b656f9fa57bcb03b6484a53d75e523 | [] | no_license | CaryLorrk/woops | 9494082f9a90926a63299462075e83e49d9688b9 | 66d10b9f93f275f2d2e4aaa71acfa09a3cefa862 | refs/heads/master | 2020-05-23T18:30:05.316492 | 2018-09-18T04:08:45 | 2018-09-18T04:08:45 | 95,071,315 | 0 | 1 | null | 2017-10-13T05:09:41 | 2017-06-22T03:36:56 | C++ | UTF-8 | C++ | false | false | 1,609 | cc | #include "traditional_ssp_consistency.h"
#include "lib.h"
namespace woops
{
TraditionalSSPConsistency::TraditionalSSPConsistency(Iteration staleness): SSPConsistency(staleness) {}
void TraditionalSSPConsistency::BeforeClock(Iteration iteration) {
auto&& tables = Lib::Client().GetTables();
for (auto&& kv: tables) {
Tableid id = kv.first;
auto&& table = *kv.second;
Iteration min;
{
std::lock_guard<std::mutex> lock(table.mu);
min = std::min_element(
table.iterations.begin(), table.iterations.end(),
[](ClientTable::Iterations::value_type& l,
ClientTable::Iterations::value_type& r) -> bool {
return l.second < r.second;
})->second;
}
if (min < iteration - staleness_) {
// push to server
auto&& partitions = Lib::Placement().GetPartitions(id);
std::map<Hostid, Bytes> server_to_bytes;
{
std::lock_guard<std::mutex> lock(table.mu);
server_to_bytes = table.transmit_buffer->Encode(partitions);
}
for (auto&& kv: partitions) {
auto&& server = kv.first;
auto&& bytes = server_to_bytes[server];
Lib::Comm().ClientPush(server, id, iteration, std::move(bytes));
}
// pull from server
for (auto&& kv: partitions) {
Lib::Comm().ClientPull(kv.first, id, iteration);
}
}
}
}
} /* woops */
| [
"[email protected]"
] | |
d33bfa4018a480130c2d6f65c12a4c968874e7ee | 9c875e2e2a425a62ee0ffb148e701342c142a029 | /src/Saurobyte/AudioStream.hpp | 8a10bfebf72696ed124bf8a1847071851aa433ce | [
"MIT"
] | permissive | Symphonym/Saurobyte | 4b80e587517d8108a7ac4d60f17ec7518a693c48 | c4bc5afd4ac4353ed6cd9a201454fd14aa3aced2 | refs/heads/master | 2016-08-05T13:26:18.701701 | 2014-07-13T00:46:06 | 2014-07-13T00:46:06 | 17,995,418 | 19 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,919 | hpp | /*
The MIT License (MIT)
Copyright (c) 2014 by Jakob Larsson
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 SAUROBYTE_AUDIOSTREAM_HPP
#define SAUROBYTE_AUDIOSTREAM_HPP
#include <Saurobyte/AudioSource.hpp>
#include <array>
#include <thread>
namespace Saurobyte
{
class AudioStream : public AudioSource
{
public:
explicit AudioStream(AudioSource::AudioFilePtr audioPtr, std::uint32_t newSource);
~AudioStream();
virtual void play();
virtual void pause();
virtual void stop();
virtual void setLooping(bool looping);
virtual void setOffset(Time offset);
virtual Time getOffset() const;
virtual bool isLooping() const;
private:
bool m_loop;
bool m_requestStop;
Time m_playingOffset;
std::thread m_thread;
// Array of OpenAL buffer handles
std::array<AudioSource::BufferWrapper, 3> m_buffers;
void processStream();
void prepareStreaming();
};
};
#endif | [
"[email protected]"
] | |
0af9d676ad79790b86e906672ea473f80ec9a7af | 2e26bbbbe3801eccf026fdb44fa16497c51de5fd | /bank.h | c450f1df3f77f324144666771185a46671a03a86 | [] | no_license | Mordequess/a6 | aad3b3e28c81d56f723eda692573260193b13aeb | 0bc869505fb9b30584d817f584063b9f446ce65e | refs/heads/master | 2021-01-10T15:49:35.695324 | 2015-12-07T02:09:30 | 2015-12-07T02:09:30 | 47,424,905 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 446 | h | #ifndef BANK_H
#define BANK_H
#include <vector>
_Monitor Bank {
uCondition insufficientFunds; // waiting on deposits
unsigned int waiters; // number of people waiting
std::vector<unsigned int> studentAccounts; // the student accounts
public:
Bank( unsigned int numStudents );
void deposit( unsigned int id, unsigned int amount );
void withdraw( unsigned int id, unsigned int amount );
};
#endif
| [
"[email protected]"
] | |
8273697452a4cd52b5d38eb345d7ba3879e280b6 | 45014139581f1211a43b6415a6ee32d442c29fc0 | /src/content/renderer/render_thread_impl.h | e13f73a1ef631d9e482e2e878bd5c79c8b7f0790 | [
"BSD-3-Clause"
] | permissive | webosose/chromium91 | a31b847e64391c3de98ca5b6dac3ac247d393e78 | b28e2ae83ee2e4907a36a49a4c0f054aa386dbfa | refs/heads/master | 2022-12-12T09:32:30.580155 | 2022-09-01T09:02:15 | 2022-09-18T23:58:11 | 460,692,960 | 1 | 5 | null | 2022-10-05T07:19:39 | 2022-02-18T03:16:04 | null | UTF-8 | C++ | false | false | 24,434 | h | // Copyright (c) 2012 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_RENDERER_RENDER_THREAD_IMPL_H_
#define CONTENT_RENDERER_RENDER_THREAD_IMPL_H_
#include <stddef.h>
#include <stdint.h>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/cancelable_callback.h"
#include "base/clang_profiling_buildflags.h"
#include "base/containers/unique_ptr_adapters.h"
#include "base/macros.h"
#include "base/memory/discardable_memory_allocator.h"
#include "base/memory/memory_pressure_listener.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/user_metrics_action.h"
#include "base/observer_list.h"
#include "base/optional.h"
#include "base/time/time.h"
#include "base/types/pass_key.h"
#include "build/build_config.h"
#include "cc/mojom/render_frame_metadata.mojom.h"
#include "content/child/child_thread_impl.h"
#include "content/common/agent_scheduling_group.mojom.h"
#include "content/common/content_export.h"
#include "content/common/frame.mojom.h"
#include "content/common/render_message_filter.mojom.h"
#include "content/common/renderer.mojom.h"
#include "content/common/renderer_host.mojom.h"
#include "content/public/renderer/render_thread.h"
#include "content/renderer/compositor/compositor_dependencies.h"
#include "content/renderer/discardable_memory_utils.h"
#include "gpu/ipc/client/gpu_channel_host.h"
#include "ipc/ipc_sync_channel.h"
#include "media/media_buildflags.h"
#include "mojo/public/cpp/bindings/associated_receiver.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
#include "mojo/public/cpp/bindings/pending_associated_receiver.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "net/base/network_change_notifier.h"
#include "net/nqe/effective_connection_type.h"
#include "services/network/public/mojom/url_loader_factory.mojom.h"
#include "services/viz/public/mojom/compositing/compositing_mode_watcher.mojom.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "third_party/blink/public/common/user_agent/user_agent_metadata.h"
#include "third_party/blink/public/platform/scheduler/web_rail_mode_observer.h"
#include "third_party/blink/public/platform/scheduler/web_thread_scheduler.h"
#include "third_party/blink/public/platform/url_loader_throttle_provider.h"
#include "third_party/blink/public/platform/web_connection_type.h"
#include "third_party/blink/public/web/web_memory_statistics.h"
#include "ui/gfx/native_widget_types.h"
///@name USE_NEVA_APPRUNTIME
///@{
#include "third_party/blink/public/platform/web_scoped_page_pauser.h"
///@}
#if defined(USE_NEVA_MEDIA) || defined(USE_NEVA_SUSPEND_MEDIA_CAPTURE)
// Mix-in for neva
#include "content/renderer/neva/render_thread_impl.h"
#endif
class SkBitmap;
namespace blink {
class WebResourceRequestSenderDelegate;
class WebVideoCaptureImplManager;
}
namespace base {
class SingleThreadTaskRunner;
class Thread;
}
namespace cc {
class TaskGraphRunner;
}
namespace gfx {
class RenderingPipeline;
}
namespace gpu {
class GpuChannelHost;
}
namespace media {
class DecoderFactory;
class GpuVideoAcceleratorFactories;
}
namespace mojo {
class BinderMap;
}
namespace viz {
class ContextProviderCommandBuffer;
class Gpu;
class RasterContextProvider;
} // namespace viz
namespace content {
class AgentSchedulingGroup;
class CategorizedWorkerPool;
class GpuVideoAcceleratorFactoriesImpl;
class MediaInterfaceFactory;
class RenderFrameImpl;
class RenderThreadObserver;
class RendererBlinkPlatformImpl;
class VariationsRenderThreadObserver;
#if defined(OS_ANDROID)
class StreamTextureFactory;
#endif
// The RenderThreadImpl class represents the main thread, where RenderView
// instances live. The RenderThread supports an API that is used by its
// consumer to talk indirectly to the RenderViews and supporting objects.
// Likewise, it provides an API for the RenderViews to talk back to the main
// process (i.e., their corresponding WebContentsImpl).
//
// Most of the communication occurs in the form of IPC messages. They are
// routed to the RenderThread according to the routing IDs of the messages.
// The routing IDs correspond to RenderView instances.
class CONTENT_EXPORT RenderThreadImpl
: public RenderThread,
public ChildThreadImpl,
public mojom::Renderer,
#if defined(USE_NEVA_MEDIA) || defined(USE_NEVA_SUSPEND_MEDIA_CAPTURE)
public neva::RenderThreadImpl<RenderThreadImpl>,
#endif
public viz::mojom::CompositingModeWatcher,
public CompositorDependencies {
public:
static RenderThreadImpl* current();
static mojom::RenderMessageFilter* current_render_message_filter();
static RendererBlinkPlatformImpl* current_blink_platform_impl();
static void SetRenderMessageFilterForTesting(
mojom::RenderMessageFilter* render_message_filter);
static void SetRendererBlinkPlatformImplForTesting(
RendererBlinkPlatformImpl* blink_platform_impl);
// Returns the task runner for the main thread where the RenderThread lives.
static scoped_refptr<base::SingleThreadTaskRunner>
DeprecatedGetMainTaskRunner();
RenderThreadImpl(
base::RepeatingClosure quit_closure,
std::unique_ptr<blink::scheduler::WebThreadScheduler> scheduler);
RenderThreadImpl(
const InProcessChildThreadParams& params,
int32_t client_id,
std::unique_ptr<blink::scheduler::WebThreadScheduler> scheduler);
~RenderThreadImpl() override;
void Shutdown() override;
bool ShouldBeDestroyed() override;
// When initializing WebKit, ensure that any schemes needed for the content
// module are registered properly. Static to allow sharing with tests.
static void RegisterSchemes();
// RenderThread implementation:
IPC::SyncChannel* GetChannel() override;
std::string GetLocale() override;
IPC::SyncMessageFilter* GetSyncMessageFilter() override;
void AddRoute(int32_t routing_id, IPC::Listener* listener) override;
void AttachTaskRunnerToRoute(
int32_t routing_id,
scoped_refptr<base::SingleThreadTaskRunner> task_runner) override;
void RemoveRoute(int32_t routing_id) override;
int GenerateRoutingID() override;
bool GenerateFrameRoutingID(
int32_t& routing_id,
blink::LocalFrameToken& frame_token,
base::UnguessableToken& devtools_frame_token) override;
void AddFilter(IPC::MessageFilter* filter) override;
void RemoveFilter(IPC::MessageFilter* filter) override;
void AddObserver(RenderThreadObserver* observer) override;
void RemoveObserver(RenderThreadObserver* observer) override;
void SetResourceRequestSenderDelegate(
blink::WebResourceRequestSenderDelegate* delegate) override;
blink::WebResourceRequestSenderDelegate* GetResourceRequestSenderDelegate() {
return resource_request_sender_delegate_;
}
void RegisterExtension(std::unique_ptr<v8::Extension> extension) override;
int PostTaskToAllWebWorkers(base::RepeatingClosure closure) override;
base::WaitableEvent* GetShutdownEvent() override;
int32_t GetClientId() override;
void SetRendererProcessType(
blink::scheduler::WebRendererProcessType type) override;
blink::WebString GetUserAgent() override;
const blink::UserAgentMetadata& GetUserAgentMetadata() override;
bool IsUseZoomForDSF() override;
// IPC::Listener implementation via ChildThreadImpl:
void OnAssociatedInterfaceRequest(
const std::string& name,
mojo::ScopedInterfaceEndpointHandle handle) override;
// ChildThread implementation via ChildThreadImpl:
scoped_refptr<base::SingleThreadTaskRunner> GetIOTaskRunner() override;
// CompositorDependencies implementation.
bool IsUseZoomForDSFEnabled() override;
blink::scheduler::WebThreadScheduler* GetWebMainThreadScheduler() override;
cc::TaskGraphRunner* GetTaskGraphRunner() override;
std::unique_ptr<cc::UkmRecorderFactory> CreateUkmRecorderFactory() override;
gfx::RenderingPipeline* GetMainThreadPipeline() override;
gfx::RenderingPipeline* GetCompositorThreadPipeline() override;
bool IsLcdTextEnabled();
bool IsElasticOverscrollEnabled();
bool IsScrollAnimatorEnabled();
// TODO(crbug.com/1111231): The `enable_scroll_animator` flag is currently
// being passed as part of `CreateViewParams`, despite it looking like a
// global setting. It should probably be moved to some `mojom::Renderer` API
// and this method should be removed.
void SetScrollAnimatorEnabled(bool enable_scroll_animator,
base::PassKey<AgentSchedulingGroup>);
bool IsThreadedAnimationEnabled();
// viz::mojom::CompositingModeWatcher implementation.
void CompositingModeFallbackToSoftware() override;
// Whether gpu compositing is being used or is disabled for software
// compositing. Clients of the compositor should give resources that match
// the appropriate mode.
bool IsGpuCompositingDisabled() { return is_gpu_compositing_disabled_; }
// Synchronously establish a channel to the GPU plugin if not previously
// established or if it has been lost (for example if the GPU plugin crashed).
// If there is a pending asynchronous request, it will be completed by the
// time this routine returns.
scoped_refptr<gpu::GpuChannelHost> EstablishGpuChannelSync();
gpu::GpuMemoryBufferManager* GetGpuMemoryBufferManager();
blink::AssociatedInterfaceRegistry* GetAssociatedInterfaceRegistry();
base::DiscardableMemoryAllocator* GetDiscardableMemoryAllocatorForTest()
const {
return discardable_memory_allocator_.get();
}
RendererBlinkPlatformImpl* blink_platform_impl() const {
DCHECK(blink_platform_impl_);
return blink_platform_impl_.get();
}
// Returns the task runner on the compositor thread.
//
// Will be null if threaded compositing has not been enabled.
scoped_refptr<base::SingleThreadTaskRunner> compositor_task_runner() const {
return compositor_task_runner_;
}
const std::vector<std::string> cors_exempt_header_list() const {
return cors_exempt_header_list_;
}
blink::URLLoaderThrottleProvider* url_loader_throttle_provider() const {
return url_loader_throttle_provider_.get();
}
#if defined(OS_ANDROID)
scoped_refptr<StreamTextureFactory> GetStreamTexureFactory();
bool EnableStreamTextureCopy();
#endif
blink::WebVideoCaptureImplManager* video_capture_impl_manager() const {
return vc_manager_.get();
}
mojom::RenderMessageFilter* render_message_filter();
// Get the GPU channel. Returns NULL if the channel is not established or
// has been lost.
gpu::GpuChannelHost* GetGpuChannel();
// Returns a SingleThreadTaskRunner instance corresponding to the message loop
// of the thread on which media operations should be run. Must be called
// on the renderer's main thread.
scoped_refptr<base::SingleThreadTaskRunner> GetMediaThreadTaskRunner();
// A TaskRunner instance that runs tasks on the raster worker pool.
base::TaskRunner* GetWorkerTaskRunner();
// Creates a ContextProvider if yet created, and returns it to be used for
// video frame compositing. The ContextProvider given as an argument is
// one that has been lost, and is a hint to the RenderThreadImpl to clear
// it's |video_frame_compositor_context_provider_| if it matches.
scoped_refptr<viz::RasterContextProvider>
GetVideoFrameCompositorContextProvider(
scoped_refptr<viz::RasterContextProvider>);
// Returns a worker context provider that will be bound on the compositor
// thread.
scoped_refptr<viz::RasterContextProvider>
SharedCompositorWorkerContextProvider(bool try_gpu_rasterization);
media::GpuVideoAcceleratorFactories* GetGpuFactories();
media::DecoderFactory* GetMediaDecoderFactory();
scoped_refptr<viz::ContextProviderCommandBuffer>
SharedMainThreadContextProvider();
// For producing custom V8 histograms. Custom histograms are produced if all
// RenderViews share the same host, and the host is in the pre-specified set
// of hosts we want to produce custom diagrams for. The name for a custom
// diagram is the name of the corresponding generic diagram plus a
// host-specific suffix.
class CONTENT_EXPORT HistogramCustomizer {
public:
HistogramCustomizer();
~HistogramCustomizer();
// Called when a top frame of a RenderView navigates. This function updates
// RenderThreadImpl's information about whether all RenderViews are
// displaying a page from the same host. |host| is the host where a
// RenderView navigated, and |view_count| is the number of RenderViews in
// this process.
void RenderViewNavigatedToHost(const std::string& host, size_t view_count);
// Used for customizing some histograms if all RenderViews share the same
// host. Returns the current custom histogram name to use for
// |histogram_name|, or |histogram_name| if it shouldn't be customized.
std::string ConvertToCustomHistogramName(const char* histogram_name) const;
private:
FRIEND_TEST_ALL_PREFIXES(RenderThreadImplUnittest,
IdentifyAlexaTop10NonGoogleSite);
friend class RenderThreadImplUnittest;
// Converts a host name to a suffix for histograms
std::string HostToCustomHistogramSuffix(const std::string& host);
// Helper function to identify a certain set of top pages
bool IsAlexaTop10NonGoogleSite(const std::string& host);
// Used for updating the information on which is the common host which all
// RenderView's share (if any). If there is no common host, this function is
// called with an empty string.
void SetCommonHost(const std::string& host);
// The current common host of the RenderViews; empty string if there is no
// common host.
std::string common_host_;
// The corresponding suffix.
std::string common_host_histogram_suffix_;
// Set of histograms for which we want to produce a custom histogram if
// possible.
std::set<std::string> custom_histograms_;
DISALLOW_COPY_AND_ASSIGN(HistogramCustomizer);
};
HistogramCustomizer* histogram_customizer() {
return &histogram_customizer_;
}
void RegisterPendingFrameCreate(
int routing_id,
mojo::PendingReceiver<mojom::Frame> frame);
mojom::RendererHost* GetRendererHost();
struct RendererMemoryMetrics {
size_t partition_alloc_kb;
size_t blink_gc_kb;
size_t malloc_mb;
size_t discardable_kb;
size_t v8_main_thread_isolate_mb;
size_t total_allocated_mb;
size_t non_discardable_total_allocated_mb;
size_t total_allocated_per_render_view_mb;
};
bool GetRendererMemoryMetrics(RendererMemoryMetrics* memory_metrics) const;
void RecordMetricsForBackgroundedRendererPurge();
// Sets the current pipeline rendering color space.
void SetRenderingColorSpace(const gfx::ColorSpace& color_space);
gfx::ColorSpace GetRenderingColorSpace();
scoped_refptr<base::SingleThreadTaskRunner>
CreateVideoFrameCompositorTaskRunner();
// In the case of kOnDemand, we wont be using the task_runner created in
// CreateVideoFrameCompositorTaskRunner.
// TODO(https://crbug/901513): Remove once kOnDemand is removed.
void SetVideoFrameCompositorTaskRunner(
scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
video_frame_compositor_task_runner_ = task_runner;
}
private:
friend class RenderThreadImplBrowserTest;
friend class AgentSchedulingGroup;
void OnProcessFinalRelease() override;
// IPC::Listener
void OnChannelError() override;
// ChildThread
bool OnControlMessageReceived(const IPC::Message& msg) override;
void RecordAction(const base::UserMetricsAction& action) override;
void RecordComputedAction(const std::string& action) override;
bool IsMainThread();
void Init();
void InitializeCompositorThread();
void InitializeWebKit(mojo::BinderMap* binders);
void OnTransferBitmap(const SkBitmap& bitmap, int resource_id);
void OnGetAccessibilityTree();
// mojom::Renderer:
void CreateAgentSchedulingGroup(
mojo::PendingReceiver<IPC::mojom::ChannelBootstrap> bootstrap,
mojo::PendingRemote<blink::mojom::BrowserInterfaceBroker> broker_remote)
override;
void CreateAssociatedAgentSchedulingGroup(
mojo::PendingAssociatedReceiver<mojom::AgentSchedulingGroup>
agent_scheduling_group,
mojo::PendingRemote<blink::mojom::BrowserInterfaceBroker> broker_remote)
override;
void OnNetworkConnectionChanged(
net::NetworkChangeNotifier::ConnectionType type,
double max_bandwidth_mbps) override;
void OnNetworkQualityChanged(net::EffectiveConnectionType type,
base::TimeDelta http_rtt,
base::TimeDelta transport_rtt,
double bandwidth_kbps) override;
void SetWebKitSharedTimersSuspended(bool suspend) override;
void SetUserAgent(const std::string& user_agent) override;
void SetUserAgentMetadata(const blink::UserAgentMetadata& metadata) override;
void SetCorsExemptHeaderList(const std::vector<std::string>& list) override;
void UpdateScrollbarTheme(
mojom::UpdateScrollbarThemeParamsPtr params) override;
void OnSystemColorsChanged(int32_t aqua_color_variant,
const std::string& highlight_text_color,
const std::string& highlight_color) override;
void UpdateSystemColorInfo(
mojom::UpdateSystemColorInfoParamsPtr params) override;
void PurgePluginListCache(bool reload_pages) override;
void SetProcessState(mojom::RenderProcessBackgroundState background_state,
mojom::RenderProcessVisibleState visible_state) override;
void SetSchedulerKeepActive(bool keep_active) override;
///@name USE_NEVA_APPRUNTIME
///@{
void ProcessResume() override;
void ProcessSuspend() override;
void OnSystemMemoryPressureLevelChanged(
base::MemoryPressureListener::MemoryPressureLevel level) override;
///@}
void SetIsLockedToSite() override;
#if BUILDFLAG(CLANG_PROFILING_INSIDE_SANDBOX)
void WriteClangProfilingProfile(
WriteClangProfilingProfileCallback callback) override;
#endif
void SetIsCrossOriginIsolated(bool value) override;
void OnMemoryPressure(
base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
bool RendererIsHidden() const;
void OnRendererHidden();
void OnRendererVisible();
bool RendererIsBackgrounded() const;
void OnRendererBackgrounded();
void OnRendererForegrounded();
void RecordMemoryUsageAfterBackgrounded(const char* suffix,
int foregrounded_count);
void OnRecordMetricsForBackgroundedRendererPurgeTimerExpired(
const char* suffix,
int foregrounded_count_when_purged);
void ReleaseFreeMemory();
void OnSyncMemoryPressure(
base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
void OnRendererInterfaceReceiver(
mojo::PendingAssociatedReceiver<mojom::Renderer> receiver);
scoped_refptr<discardable_memory::ClientDiscardableSharedMemoryManager>
discardable_memory_allocator_;
// These objects live solely on the render thread.
std::unique_ptr<blink::scheduler::WebThreadScheduler> main_thread_scheduler_;
std::unique_ptr<RendererBlinkPlatformImpl> blink_platform_impl_;
std::unique_ptr<blink::URLLoaderThrottleProvider>
url_loader_throttle_provider_;
std::vector<std::string> cors_exempt_header_list_;
// Used on the render thread.
std::unique_ptr<blink::WebVideoCaptureImplManager> vc_manager_;
// Used to keep track of the renderer's backgrounded and visibility state.
// Updated via an IPC from the browser process. If nullopt, the browser
// process has yet to send an update and the state is unknown.
base::Optional<mojom::RenderProcessBackgroundState> background_state_;
base::Optional<mojom::RenderProcessVisibleState> visible_state_;
blink::WebString user_agent_;
blink::UserAgentMetadata user_agent_metadata_;
// Sticky once true, indicates that compositing is done without Gpu, so
// resources given to the compositor or to the viz service should be
// software-based.
bool is_gpu_compositing_disabled_ = false;
// Utility class to provide GPU functionalities to media.
// TODO(dcastagna): This should be just one scoped_ptr once
// http://crbug.com/580386 is fixed.
// NOTE(dcastagna): At worst this accumulates a few bytes per context lost.
std::vector<std::unique_ptr<GpuVideoAcceleratorFactoriesImpl>> gpu_factories_;
// Utility classes to allow WebRTC to create video decoders.
std::unique_ptr<MediaInterfaceFactory> media_interface_factory_;
std::unique_ptr<media::DecoderFactory> media_decoder_factory_;
// Thread for running multimedia operations (e.g., video decoding).
std::unique_ptr<base::Thread> media_thread_;
std::unique_ptr<gfx::RenderingPipeline> main_thread_pipeline_;
std::unique_ptr<gfx::RenderingPipeline> compositor_thread_pipeline_;
// Will point to appropriate task runner after initialization,
// regardless of whether |compositor_thread_| is overriden.
scoped_refptr<base::SingleThreadTaskRunner> compositor_task_runner_;
// Task to run the VideoFrameCompositor on.
scoped_refptr<base::SingleThreadTaskRunner>
video_frame_compositor_task_runner_;
// Pool of workers used for raster operations (e.g., tile rasterization).
scoped_refptr<CategorizedWorkerPool> categorized_worker_pool_;
#if defined(OS_ANDROID)
scoped_refptr<StreamTextureFactory> stream_texture_factory_;
#endif
scoped_refptr<viz::ContextProviderCommandBuffer> shared_main_thread_contexts_;
base::ObserverList<RenderThreadObserver>::Unchecked observers_;
scoped_refptr<viz::RasterContextProvider>
video_frame_compositor_context_provider_;
scoped_refptr<viz::RasterContextProvider> shared_worker_context_provider_;
HistogramCustomizer histogram_customizer_;
std::unique_ptr<base::MemoryPressureListener> memory_pressure_listener_;
std::unique_ptr<viz::Gpu> gpu_;
std::unique_ptr<VariationsRenderThreadObserver> variations_observer_;
// Compositor settings.
int gpu_rasterization_msaa_sample_count_;
bool is_lcd_text_enabled_;
bool is_zero_copy_enabled_;
bool is_gpu_memory_buffer_compositor_resources_enabled_;
bool is_partial_raster_enabled_;
bool is_elastic_overscroll_enabled_;
bool is_zoom_for_dsf_enabled_;
bool is_threaded_animation_enabled_;
bool is_scroll_animator_enabled_;
// Target rendering ColorSpace.
gfx::ColorSpace rendering_color_space_;
// Used when AddRoute() is called and the RenderFrameImpl hasn't been created
// yet.
std::map<int, mojo::PendingReceiver<mojom::Frame>> pending_frames_;
mojo::AssociatedRemote<mojom::RendererHost> renderer_host_;
blink::AssociatedInterfaceRegistry associated_interfaces_;
mojo::AssociatedReceiver<mojom::Renderer> renderer_receiver_{this};
mojo::AssociatedRemote<mojom::RenderMessageFilter> render_message_filter_;
std::set<std::unique_ptr<AgentSchedulingGroup>, base::UniquePtrComparator>
agent_scheduling_groups_;
RendererMemoryMetrics purge_and_suspend_memory_metrics_;
int process_foregrounded_count_;
int32_t client_id_;
#if defined(USE_NEVA_MEDIA)
template <typename original_t>
friend class neva::RenderThreadImpl;
#endif
#if defined(USE_NEVA_APPRUNTIME)
unsigned suspension_count_ = 0;
#endif
// A mojo connection to the CompositingModeReporter service.
mojo::Remote<viz::mojom::CompositingModeReporter> compositing_mode_reporter_;
// The class is a CompositingModeWatcher, which is bound to mojo through
// this member.
mojo::Receiver<viz::mojom::CompositingModeWatcher>
compositing_mode_watcher_receiver_{this};
///@name USE_NEVA_APPRUNTIME
///@{
std::unique_ptr<blink::WebScopedPagePauser> page_pauser_;
///@}
// Delegate is expected to live as long as requests may be sent.
blink::WebResourceRequestSenderDelegate* resource_request_sender_delegate_ =
nullptr;
base::WeakPtrFactory<RenderThreadImpl> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(RenderThreadImpl);
};
} // namespace content
#endif // CONTENT_RENDERER_RENDER_THREAD_IMPL_H_
| [
"[email protected]"
] | |
250e5032beba9460f90c3cc33ec46827b7f3e3de | 154c3822e32c3fc707e775531d3973834345d270 | /114_ejercicio.cpp | b59e0627b9701b1b01e40ef04761e007357a84d1 | [] | no_license | MEng-Alejandro-Nieto/Learning-cpp | f2da6a4f46eb1f86d472d8a1469bd885eb99287c | 3d17d451cb534afdf9ea79e2fcb8e5495dc8a6d7 | refs/heads/master | 2020-07-30T13:08:22.122242 | 2019-12-05T23:20:48 | 2019-12-05T23:20:48 | 210,244,804 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 867 | cpp | /*
Comprobar si un numero es par o impar, y senalar la posicion de memoria
donde se esta guardando el numero con punteros.
*/
#include <iostream>
using std::cin; using std::cout; using std::endl;
///////////////////////////////////////////////////////////////////
int n{0},*dir_n=&n;
///////////////////////////////////////////////////////////////////
void pregunta();
void par(int);
///////////////////////////////////////////////////////////////////
int main(){
pregunta();
par(n);
return 0;
}
///////////////////////////////////////////////////////////////////
void pregunta(){
cout<<"Ingrese un numero para comprobar si es par: "; cin>>n;
}
void par(int n){
if(*dir_n%2==0){
cout<<"El numero "<<*&n<< " es par y esta ubicado en "<<&n;
}
else{
cout<<"El numero "<<*&n<< " es impar y esta ubicado en "<<&n;
}
} | [
"[email protected]"
] | |
694c62cad032361e5bc6d8f3ca915112cc8794a4 | 1fdbb7e551cf8b52b43359cf406bedd969b5f59f | /source/driversdk/driverupdate/MainTask.cpp | e16935b052868f2c5aa2acc8bc62981af02f2147 | [] | no_license | trigrass2/eview-server | 1292958416ebe772ff4ce0b1f1639c65ca13ce92 | a5e452016a730af79a1d402a3d918403eb6073aa | refs/heads/master | 2023-06-17T09:38:25.004889 | 2021-07-15T09:45:56 | 2021-07-15T09:45:56 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,135 | cpp | /**************************************************************
* Filename: RecvThread.cpp
* Copyright: Shanghai Peak InfoTech Co., Ltd.
*
* Description: 接收消息线程.
*
* @author: liuqifeng
* @version 04/13/2009 liuqifeng Initial Version
**************************************************************/
// RecvThread.cpp: implementation of the CRecvThread class.
//
//////////////////////////////////////////////////////////////////////
#include <ace/INET_Addr.h>
#include <ace/Log_Msg.h>
#include "ClientSockHandler.h"
#include "ace/Select_Reactor.h"
#include "ace/OS_NS_strings.h"
#include "MainTask.h"
#include "SystemConfig.h"
#include "common/pklog.h"
#include "SystemConfig.h"
#include "ace/SOCK_Connector.h"
extern CPKLog PKLog;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
//ACE_DLL g_dllforwardaccessor;
//PFN_ReadAllTagsInfo g_pfnReadAllTagsInfo = NULL;
//PFN_ReadAllTagsData g_pfnReadAllTagsData = NULL;
//PFN_ReleaseAllTagsInfo g_pfnReleaseAllTagsInfo = NULL;
#define DLLNAME_FORWARDACCESSOR "forwardaccessor"
CMainTask::CMainTask():m_cycleReader(this)
{
ACE_Select_Reactor *pSelectReactor = new ACE_Select_Reactor();
m_pReactor = new ACE_Reactor(pSelectReactor, 1);
reactor(m_pReactor);
}
CMainTask::~CMainTask()
{
if (m_pReactor != NULL)
{
delete m_pReactor;
m_pReactor = NULL;
}
}
//线程服务
int CMainTask::svc()
{
//long nErr = g_dllforwardaccessor.open(DLLNAME_FORWARDACCESSOR);
//if (nErr == 0)
//{
// PKLog.LogMessage(PK_LOGLEVEL_NOTICE, " load Module %s 成功", DLLNAME_FORWARDACCESSOR);
//}
//else
// PKLog.LogMessage(PK_LOGLEVEL_ERROR, " load Module %s 失败", DLLNAME_FORWARDACCESSOR);
//// 导入初始化函数
//g_pfnReadAllTagsInfo = (PFN_ReadAllTagsInfo)g_dllforwardaccessor.symbol("ReadAllTagsInfo");
//if(g_pfnReadAllTagsInfo == NULL)
//{
// PKLog.LogMessage(PK_LOGLEVEL_ERROR, " 从%s 获取导出函数%s失败",g_dllforwardaccessor.dll_name_, "ReadAllTagsInfo");
//}
//g_pfnReadAllTagsData = (PFN_ReadAllTagsData)g_dllforwardaccessor.symbol("ReadAllTagsData");
//if(g_pfnReadAllTagsData == NULL)
//{
// PKLog.LogMessage(PK_LOGLEVEL_ERROR, " 从%s 获取导出函数%s失败",g_dllforwardaccessor.dll_name_, "ReadAllTagsData");
//}
//g_pfnReleaseAllTagsInfo = (PFN_ReleaseAllTagsInfo)g_dllforwardaccessor.symbol("ReleaseAllTagsInfo");
//if(g_pfnReleaseAllTagsInfo == NULL)
//{
// PKLog.LogMessage(PK_LOGLEVEL_ERROR, " 从%s 获取导出函数%s失败",g_dllforwardaccessor.dll_name_, "ReleaseAllTagsInfo");
//}
this->reactor()->owner(ACE_OS::thr_self ());
m_cycleReader.m_nPollRate = SYSTEM_CONFIG->m_nCycleMS;
m_cycleReader.StartTimer();
this->reactor()->reset_reactor_event_loop();
this->reactor()->run_reactor_event_loop();
m_cycleReader.StopTimer();
return 0;
}
void CMainTask::Stop()
{
// 发出关闭响应起得请求
this->reactor()->end_reactor_event_loop();
// 等待响应器关闭后退出
this->wait();
}
int CMainTask::Start()
{
return this->activate();
}
| [
"[email protected]"
] | |
74fab5f8cb799a4218a67b6a2de342d93740dd2a | dd80a584130ef1a0333429ba76c1cee0eb40df73 | /ndk/sources/cxx-stl/llvm-libc++/libcxx/include/__debug | 0d631bf043861e545592bab8ec955585b5071ef1 | [
"MIT",
"NCSA"
] | permissive | karunmatharu/Android-4.4-Pay-by-Data | 466f4e169ede13c5835424c78e8c30ce58f885c1 | fcb778e92d4aad525ef7a995660580f948d40bc9 | refs/heads/master | 2021-03-24T13:33:01.721868 | 2017-02-18T17:48:49 | 2017-02-18T17:48:49 | 81,847,777 | 0 | 2 | MIT | 2020-03-09T00:02:12 | 2017-02-13T16:47:00 | null | UTF-8 | C++ | false | false | 5,259 | // -*- C++ -*-
//===--------------------------- __debug ----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef _LIBCPP_DEBUG_H
#define _LIBCPP_DEBUG_H
#if _LIBCPP_DEBUG_LEVEL >= 1
# include <cstdlib>
# include <cstdio>
# include <cstddef>
# ifndef _LIBCPP_ASSERT
# define _LIBCPP_ASSERT(x, m) ((x) ? (void)0 : (_VSTD::printf("%s\n", m), _VSTD::abort()))
# endif
#endif
#if _LIBCPP_DEBUG_LEVEL >= 2
_LIBCPP_BEGIN_NAMESPACE_STD
struct _LIBCPP_TYPE_VIS __c_node;
struct _LIBCPP_TYPE_VIS __i_node
{
void* __i_;
__i_node* __next_;
__c_node* __c_;
__i_node(const __i_node&) = delete;
__i_node& operator=(const __i_node&) = delete;
_LIBCPP_INLINE_VISIBILITY
__i_node(void* __i, __i_node* __next, __c_node* __c)
: __i_(__i), __next_(__next), __c_(__c) {}
~__i_node();
};
struct _LIBCPP_TYPE_VIS __c_node
{
void* __c_;
__c_node* __next_;
__i_node** beg_;
__i_node** end_;
__i_node** cap_;
__c_node(const __c_node&) = delete;
__c_node& operator=(const __c_node&) = delete;
_LIBCPP_INLINE_VISIBILITY
__c_node(void* __c, __c_node* __next)
: __c_(__c), __next_(__next), beg_(nullptr), end_(nullptr), cap_(nullptr) {}
virtual ~__c_node();
virtual bool __dereferenceable(const void*) const = 0;
virtual bool __decrementable(const void*) const = 0;
virtual bool __addable(const void*, ptrdiff_t) const = 0;
virtual bool __subscriptable(const void*, ptrdiff_t) const = 0;
void __add(__i_node* __i);
_LIBCPP_HIDDEN void __remove(__i_node* __i);
};
template <class _Cont>
struct _C_node
: public __c_node
{
_C_node(void* __c, __c_node* __n)
: __c_node(__c, __n) {}
virtual bool __dereferenceable(const void*) const;
virtual bool __decrementable(const void*) const;
virtual bool __addable(const void*, ptrdiff_t) const;
virtual bool __subscriptable(const void*, ptrdiff_t) const;
};
template <class _Cont>
bool
_C_node<_Cont>::__dereferenceable(const void* __i) const
{
typedef typename _Cont::const_iterator iterator;
const iterator* __j = static_cast<const iterator*>(__i);
_Cont* _Cp = static_cast<_Cont*>(__c_);
return _Cp->__dereferenceable(__j);
}
template <class _Cont>
bool
_C_node<_Cont>::__decrementable(const void* __i) const
{
typedef typename _Cont::const_iterator iterator;
const iterator* __j = static_cast<const iterator*>(__i);
_Cont* _Cp = static_cast<_Cont*>(__c_);
return _Cp->__decrementable(__j);
}
template <class _Cont>
bool
_C_node<_Cont>::__addable(const void* __i, ptrdiff_t __n) const
{
typedef typename _Cont::const_iterator iterator;
const iterator* __j = static_cast<const iterator*>(__i);
_Cont* _Cp = static_cast<_Cont*>(__c_);
return _Cp->__addable(__j, __n);
}
template <class _Cont>
bool
_C_node<_Cont>::__subscriptable(const void* __i, ptrdiff_t __n) const
{
typedef typename _Cont::const_iterator iterator;
const iterator* __j = static_cast<const iterator*>(__i);
_Cont* _Cp = static_cast<_Cont*>(__c_);
return _Cp->__subscriptable(__j, __n);
}
class _LIBCPP_TYPE_VIS __libcpp_db
{
__c_node** __cbeg_;
__c_node** __cend_;
size_t __csz_;
__i_node** __ibeg_;
__i_node** __iend_;
size_t __isz_;
__libcpp_db();
public:
__libcpp_db(const __libcpp_db&) = delete;
__libcpp_db& operator=(const __libcpp_db&) = delete;
~__libcpp_db();
class __db_c_iterator;
class __db_c_const_iterator;
class __db_i_iterator;
class __db_i_const_iterator;
__db_c_const_iterator __c_end() const;
__db_i_const_iterator __i_end() const;
template <class _Cont>
_LIBCPP_INLINE_VISIBILITY
void __insert_c(_Cont* __c)
{
__c_node* __n = __insert_c(static_cast<void*>(__c));
::new(__n) _C_node<_Cont>(__n->__c_, __n->__next_);
}
void __insert_i(void* __i);
__c_node* __insert_c(void* __c);
void __erase_c(void* __c);
void __insert_ic(void* __i, const void* __c);
void __iterator_copy(void* __i, const void* __i0);
void __erase_i(void* __i);
void* __find_c_from_i(void* __i) const;
void __invalidate_all(void* __c);
__c_node* __find_c_and_lock(void* __c) const;
__c_node* __find_c(void* __c) const;
void unlock() const;
void swap(void* __c1, void* __c2);
bool __dereferenceable(const void* __i) const;
bool __decrementable(const void* __i) const;
bool __addable(const void* __i, ptrdiff_t __n) const;
bool __subscriptable(const void* __i, ptrdiff_t __n) const;
bool __comparable(const void* __i, const void* __j) const;
private:
_LIBCPP_HIDDEN
__i_node* __insert_iterator(void* __i);
_LIBCPP_HIDDEN
__i_node* __find_iterator(const void* __i) const;
friend _LIBCPP_FUNC_VIS __libcpp_db* __get_db();
};
_LIBCPP_FUNC_VIS __libcpp_db* __get_db();
_LIBCPP_FUNC_VIS const __libcpp_db* __get_const_db();
_LIBCPP_END_NAMESPACE_STD
#endif
#endif // _LIBCPP_DEBUG_H
| [
"[email protected]"
] | ||
f3824b4bac7b5187c5b567a08ac775f2bc9b0271 | 286a310a00923d5e2cec35d9630aedb34dafcdb9 | /swagger/sdrangel/code/qt5/client/SWGBladeRF2InputReport.cpp | 5f3e7d89eb985f9fc54af21f59ed1bf7f715a35b | [] | no_license | agrawalharshit/sdrangel | a98b6565db7484324786898d59ca9c6f1bb6f19b | 13eae0d8fe6119397177871b8c66ab073255a9d7 | refs/heads/master | 2020-04-14T22:10:24.515807 | 2019-01-01T17:57:41 | 2019-01-01T17:57:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,153 | cpp | /**
* SDRangel
* This is the web REST/JSON API of SDRangel SDR software. SDRangel is an Open Source Qt5/OpenGL 3.0+ (4.3+ in Windows) GUI and server Software Defined Radio and signal analyzer in software. It supports Airspy, BladeRF, HackRF, LimeSDR, PlutoSDR, RTL-SDR, SDRplay RSP1 and FunCube --- Limitations and specifcities: * In SDRangel GUI the first Rx device set cannot be deleted. Conversely the server starts with no device sets and its number of device sets can be reduced to zero by as many calls as necessary to /sdrangel/deviceset with DELETE method. * Preset import and export from/to file is a server only feature. * Device set focus is a GUI only feature. * The following channels are not implemented (status 501 is returned): ATV and DATV demodulators, Channel Analyzer NG, LoRa demodulator * The device settings and report structures contains only the sub-structure corresponding to the device type. The DeviceSettings and DeviceReport structures documented here shows all of them but only one will be or should be present at a time * The channel settings and report structures contains only the sub-structure corresponding to the channel type. The ChannelSettings and ChannelReport structures documented here shows all of them but only one will be or should be present at a time ---
*
* OpenAPI spec version: 4.3.0
* Contact: [email protected]
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "SWGBladeRF2InputReport.h"
#include "SWGHelpers.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QObject>
#include <QDebug>
namespace SWGSDRangel {
SWGBladeRF2InputReport::SWGBladeRF2InputReport(QString* json) {
init();
this->fromJson(*json);
}
SWGBladeRF2InputReport::SWGBladeRF2InputReport() {
frequency_range = nullptr;
m_frequency_range_isSet = false;
sample_rate_range = nullptr;
m_sample_rate_range_isSet = false;
bandwidth_range = nullptr;
m_bandwidth_range_isSet = false;
global_gain_range = nullptr;
m_global_gain_range_isSet = false;
gain_modes = nullptr;
m_gain_modes_isSet = false;
}
SWGBladeRF2InputReport::~SWGBladeRF2InputReport() {
this->cleanup();
}
void
SWGBladeRF2InputReport::init() {
frequency_range = new SWGFrequencyRange();
m_frequency_range_isSet = false;
sample_rate_range = new SWGRange();
m_sample_rate_range_isSet = false;
bandwidth_range = new SWGRange();
m_bandwidth_range_isSet = false;
global_gain_range = new SWGRange();
m_global_gain_range_isSet = false;
gain_modes = new QList<SWGNamedEnum*>();
m_gain_modes_isSet = false;
}
void
SWGBladeRF2InputReport::cleanup() {
if(frequency_range != nullptr) {
delete frequency_range;
}
if(sample_rate_range != nullptr) {
delete sample_rate_range;
}
if(bandwidth_range != nullptr) {
delete bandwidth_range;
}
if(global_gain_range != nullptr) {
delete global_gain_range;
}
if(gain_modes != nullptr) {
auto arr = gain_modes;
for(auto o: *arr) {
delete o;
}
delete gain_modes;
}
}
SWGBladeRF2InputReport*
SWGBladeRF2InputReport::fromJson(QString &json) {
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
return this;
}
void
SWGBladeRF2InputReport::fromJsonObject(QJsonObject &pJson) {
::SWGSDRangel::setValue(&frequency_range, pJson["frequencyRange"], "SWGFrequencyRange", "SWGFrequencyRange");
::SWGSDRangel::setValue(&sample_rate_range, pJson["sampleRateRange"], "SWGRange", "SWGRange");
::SWGSDRangel::setValue(&bandwidth_range, pJson["bandwidthRange"], "SWGRange", "SWGRange");
::SWGSDRangel::setValue(&global_gain_range, pJson["globalGainRange"], "SWGRange", "SWGRange");
::SWGSDRangel::setValue(&gain_modes, pJson["gainModes"], "QList", "SWGNamedEnum");
}
QString
SWGBladeRF2InputReport::asJson ()
{
QJsonObject* obj = this->asJsonObject();
QJsonDocument doc(*obj);
QByteArray bytes = doc.toJson();
delete obj;
return QString(bytes);
}
QJsonObject*
SWGBladeRF2InputReport::asJsonObject() {
QJsonObject* obj = new QJsonObject();
if((frequency_range != nullptr) && (frequency_range->isSet())){
toJsonValue(QString("frequencyRange"), frequency_range, obj, QString("SWGFrequencyRange"));
}
if((sample_rate_range != nullptr) && (sample_rate_range->isSet())){
toJsonValue(QString("sampleRateRange"), sample_rate_range, obj, QString("SWGRange"));
}
if((bandwidth_range != nullptr) && (bandwidth_range->isSet())){
toJsonValue(QString("bandwidthRange"), bandwidth_range, obj, QString("SWGRange"));
}
if((global_gain_range != nullptr) && (global_gain_range->isSet())){
toJsonValue(QString("globalGainRange"), global_gain_range, obj, QString("SWGRange"));
}
if(gain_modes->size() > 0){
toJsonArray((QList<void*>*)gain_modes, obj, "gainModes", "SWGNamedEnum");
}
return obj;
}
SWGFrequencyRange*
SWGBladeRF2InputReport::getFrequencyRange() {
return frequency_range;
}
void
SWGBladeRF2InputReport::setFrequencyRange(SWGFrequencyRange* frequency_range) {
this->frequency_range = frequency_range;
this->m_frequency_range_isSet = true;
}
SWGRange*
SWGBladeRF2InputReport::getSampleRateRange() {
return sample_rate_range;
}
void
SWGBladeRF2InputReport::setSampleRateRange(SWGRange* sample_rate_range) {
this->sample_rate_range = sample_rate_range;
this->m_sample_rate_range_isSet = true;
}
SWGRange*
SWGBladeRF2InputReport::getBandwidthRange() {
return bandwidth_range;
}
void
SWGBladeRF2InputReport::setBandwidthRange(SWGRange* bandwidth_range) {
this->bandwidth_range = bandwidth_range;
this->m_bandwidth_range_isSet = true;
}
SWGRange*
SWGBladeRF2InputReport::getGlobalGainRange() {
return global_gain_range;
}
void
SWGBladeRF2InputReport::setGlobalGainRange(SWGRange* global_gain_range) {
this->global_gain_range = global_gain_range;
this->m_global_gain_range_isSet = true;
}
QList<SWGNamedEnum*>*
SWGBladeRF2InputReport::getGainModes() {
return gain_modes;
}
void
SWGBladeRF2InputReport::setGainModes(QList<SWGNamedEnum*>* gain_modes) {
this->gain_modes = gain_modes;
this->m_gain_modes_isSet = true;
}
bool
SWGBladeRF2InputReport::isSet(){
bool isObjectUpdated = false;
do{
if(frequency_range != nullptr && frequency_range->isSet()){ isObjectUpdated = true; break;}
if(sample_rate_range != nullptr && sample_rate_range->isSet()){ isObjectUpdated = true; break;}
if(bandwidth_range != nullptr && bandwidth_range->isSet()){ isObjectUpdated = true; break;}
if(global_gain_range != nullptr && global_gain_range->isSet()){ isObjectUpdated = true; break;}
if(gain_modes->size() > 0){ isObjectUpdated = true; break;}
}while(false);
return isObjectUpdated;
}
}
| [
"[email protected]"
] | |
26f3cabdbf00c6736e2e8b401a5599c6e2390cfb | cefd6c17774b5c94240d57adccef57d9bba4a2e9 | /WebKit/Source/WebCore/platform/graphics/ca/win/CACFLayerTreeHost.cpp | 5e5411a49d6620f22bfb1f32486953b769aa88c9 | [
"BSL-1.0",
"BSD-2-Clause",
"LGPL-2.0-only",
"LGPL-2.1-only"
] | permissive | adzhou/oragle | 9c054c25b24ff0a65cb9639bafd02aac2bcdce8b | 5442d418b87d0da161429ffa5cb83777e9b38e4d | refs/heads/master | 2022-11-01T05:04:59.368831 | 2014-03-12T15:50:08 | 2014-03-12T15:50:08 | 17,238,063 | 0 | 1 | BSL-1.0 | 2022-10-18T04:23:53 | 2014-02-27T05:39:44 | C++ | UTF-8 | C++ | false | false | 10,237 | cpp | /*
* Copyright (C) 2009, 2013 Apple Inc. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "CACFLayerTreeHost.h"
#include "CACFLayerTreeHostClient.h"
#include "DefWndProcWindowClass.h"
#include "LayerChangesFlusher.h"
#include "LegacyCACFLayerTreeHost.h"
#include "PlatformCALayerWin.h"
#include "WKCACFViewLayerTreeHost.h"
#include "WebCoreInstanceHandle.h"
#include <limits.h>
#include <QuartzCore/CABase.h>
#include <wtf/CurrentTime.h>
#include <wtf/StdLibExtras.h>
#include <wtf/win/GDIObject.h>
#ifdef DEBUG_ALL
#pragma comment(lib, "QuartzCore_debug")
#else
#pragma comment(lib, "QuartzCore")
#endif
inline static CGRect winRectToCGRect(RECT rc)
{
return CGRectMake(rc.left, rc.top, (rc.right - rc.left), (rc.bottom - rc.top));
}
inline static CGRect winRectToCGRect(RECT rc, RECT relativeToRect)
{
return CGRectMake(rc.left, (relativeToRect.bottom-rc.bottom), (rc.right - rc.left), (rc.bottom - rc.top));
}
namespace WebCore {
bool CACFLayerTreeHost::acceleratedCompositingAvailable()
{
static bool available;
static bool tested;
if (tested)
return available;
tested = true;
// Initialize available to true since this function will be called from a
// propagation within createRenderer(). We want to be able to return true
// when that happens so that the test can continue.
available = true;
HMODULE library = LoadLibrary(TEXT("d3d9.dll"));
if (!library) {
available = false;
return available;
}
FreeLibrary(library);
#ifdef DEBUG_ALL
library = LoadLibrary(TEXT("QuartzCore_debug.dll"));
#else
library = LoadLibrary(TEXT("QuartzCore.dll"));
#endif
if (!library) {
available = false;
return available;
}
FreeLibrary(library);
// Make a dummy HWND.
HWND testWindow = ::CreateWindow(defWndProcWindowClassName(), L"CoreAnimationTesterWindow", WS_POPUP, -500, -500, 20, 20, 0, 0, 0, 0);
if (!testWindow) {
available = false;
return available;
}
RefPtr<CACFLayerTreeHost> host = CACFLayerTreeHost::create();
host->setWindow(testWindow);
available = host->createRenderer();
host->setWindow(0);
::DestroyWindow(testWindow);
return available;
}
PassRefPtr<CACFLayerTreeHost> CACFLayerTreeHost::create()
{
if (!acceleratedCompositingAvailable())
return 0;
RefPtr<CACFLayerTreeHost> host = WKCACFViewLayerTreeHost::create();
if (!host)
host = LegacyCACFLayerTreeHost::create();
host->initialize();
return host.release();
}
CACFLayerTreeHost::CACFLayerTreeHost()
: m_client(0)
, m_rootLayer(PlatformCALayerWin::create(PlatformCALayer::LayerTypeRootLayer, 0))
, m_window(0)
, m_shouldFlushPendingGraphicsLayerChanges(false)
, m_isFlushingLayerChanges(false)
#if !ASSERT_DISABLED
, m_state(WindowNotSet)
#endif
{
}
void CACFLayerTreeHost::initialize()
{
// Point the CACFContext to this
initializeContext(this, m_rootLayer.get());
// Under the root layer, we have a clipping layer to clip the content,
// that contains a scroll layer that we use for scrolling the content.
// The root layer is the size of the client area of the window.
// The clipping layer is the size of the WebView client area (window less the scrollbars).
// The scroll layer is the size of the root child layer.
// Resizing the window will change the bounds of the rootLayer and the clip layer and will not
// cause any repositioning.
// Scrolling will affect only the position of the scroll layer without affecting the bounds.
m_rootLayer->setName("CACFLayerTreeHost rootLayer");
m_rootLayer->setAnchorPoint(FloatPoint3D(0, 0, 0));
m_rootLayer->setGeometryFlipped(true);
#ifndef NDEBUG
CGColorRef debugColor = CGColorCreateGenericRGB(1, 0, 0, 0.8);
m_rootLayer->setBackgroundColor(debugColor);
CGColorRelease(debugColor);
#endif
}
CACFLayerTreeHost::~CACFLayerTreeHost()
{
ASSERT_WITH_MESSAGE(m_state != WindowSet, "Must call setWindow(0) before destroying CACFLayerTreeHost");
}
void CACFLayerTreeHost::setWindow(HWND window)
{
if (window == m_window)
return;
#if !ASSERT_DISABLED
switch (m_state) {
case WindowNotSet:
ASSERT_ARG(window, window);
ASSERT(!m_window);
m_state = WindowSet;
break;
case WindowSet:
ASSERT_ARG(window, !window);
ASSERT(m_window);
m_state = WindowCleared;
break;
case WindowCleared:
ASSERT_NOT_REACHED();
break;
}
#endif
if (m_window)
destroyRenderer();
m_window = window;
}
PlatformCALayer* CACFLayerTreeHost::rootLayer() const
{
return m_rootLayer.get();
}
void CACFLayerTreeHost::addPendingAnimatedLayer(PassRefPtr<PlatformCALayer> layer)
{
m_pendingAnimatedLayers.add(layer);
}
void CACFLayerTreeHost::setRootChildLayer(PlatformCALayer* layer)
{
m_rootLayer->removeAllSublayers();
m_rootChildLayer = layer;
if (m_rootChildLayer)
m_rootLayer->appendSublayer(m_rootChildLayer.get());
}
void CACFLayerTreeHost::layerTreeDidChange()
{
if (m_isFlushingLayerChanges) {
// The layer tree is changing as a result of flushing GraphicsLayer changes to their
// underlying PlatformCALayers. We'll flush those changes to the context as part of that
// process, so there's no need to schedule another flush here.
return;
}
// The layer tree is changing as a result of someone modifying a PlatformCALayer that doesn't
// have a corresponding GraphicsLayer. Schedule a flush since we won't schedule one through the
// normal GraphicsLayer mechanisms.
LayerChangesFlusher::shared().flushPendingLayerChangesSoon(this);
}
void CACFLayerTreeHost::destroyRenderer()
{
m_rootLayer = 0;
m_rootChildLayer = 0;
LayerChangesFlusher::shared().cancelPendingFlush(this);
}
static void getDirtyRects(HWND window, Vector<CGRect>& outRects)
{
ASSERT_ARG(outRects, outRects.isEmpty());
RECT clientRect;
if (!GetClientRect(window, &clientRect))
return;
auto region = adoptGDIObject(::CreateRectRgn(0, 0, 0, 0));
int regionType = GetUpdateRgn(window, region.get(), false);
if (regionType != COMPLEXREGION) {
RECT dirtyRect;
if (GetUpdateRect(window, &dirtyRect, false))
outRects.append(winRectToCGRect(dirtyRect, clientRect));
return;
}
DWORD dataSize = ::GetRegionData(region.get(), 0, 0);
auto regionDataBuffer = std::make_unique<unsigned char[]>(dataSize);
RGNDATA* regionData = reinterpret_cast<RGNDATA*>(regionDataBuffer.get());
if (!::GetRegionData(region.get(), dataSize, regionData))
return;
outRects.resize(regionData->rdh.nCount);
RECT* rect = reinterpret_cast<RECT*>(regionData->Buffer);
for (size_t i = 0; i < outRects.size(); ++i, ++rect)
outRects[i] = winRectToCGRect(*rect, clientRect);
}
void CACFLayerTreeHost::paint()
{
Vector<CGRect> dirtyRects;
getDirtyRects(m_window, dirtyRects);
render(dirtyRects);
}
void CACFLayerTreeHost::flushPendingGraphicsLayerChangesSoon()
{
m_shouldFlushPendingGraphicsLayerChanges = true;
LayerChangesFlusher::shared().flushPendingLayerChangesSoon(this);
}
void CACFLayerTreeHost::setShouldInvertColors(bool)
{
}
void CACFLayerTreeHost::flushPendingLayerChangesNow()
{
// Calling out to the client could cause our last reference to go away.
RefPtr<CACFLayerTreeHost> protector(this);
m_isFlushingLayerChanges = true;
// Flush changes stored up in GraphicsLayers to their underlying PlatformCALayers, if
// requested.
if (m_client && m_shouldFlushPendingGraphicsLayerChanges) {
m_shouldFlushPendingGraphicsLayerChanges = false;
m_client->flushPendingGraphicsLayerChanges();
}
// Flush changes stored up in PlatformCALayers to the context so they will be rendered.
flushContext();
m_isFlushingLayerChanges = false;
}
void CACFLayerTreeHost::contextDidChange()
{
// All pending animations will have been started with the flush. Fire the animationStarted calls.
notifyAnimationsStarted();
}
void CACFLayerTreeHost::notifyAnimationsStarted()
{
// Send currentTime to the pending animations. This function is called by CACF in a callback
// which occurs after the drawInContext calls. So currentTime is very close to the time
// the animations actually start
double currentTime = monotonicallyIncreasingTime();
HashSet<RefPtr<PlatformCALayer> >::iterator end = m_pendingAnimatedLayers.end();
for (HashSet<RefPtr<PlatformCALayer> >::iterator it = m_pendingAnimatedLayers.begin(); it != end; ++it)
(*it)->animationStarted(currentTime);
m_pendingAnimatedLayers.clear();
}
CGRect CACFLayerTreeHost::bounds() const
{
RECT clientRect;
GetClientRect(m_window, &clientRect);
return winRectToCGRect(clientRect);
}
}
| [
"[email protected]"
] | |
ee7c17de38bfae05742667e6de587c9006096b3f | a82facec4d7111825c59c67a859825074823e6f7 | /IGC/VectorCompiler/lib/Utils/GenX/Printf.cpp | 4a9981337f5708584d19238c73ebf9cea20f1f24 | [
"MIT"
] | permissive | mfkiwl/intel-graphics-compiler-dp4a | f6f85313f1f62ffc86786fc7d3239d5366a015d1 | 9d3ddd2a85278b225930dac964427a0395c39c58 | refs/heads/master | 2023-04-02T17:24:52.035704 | 2021-05-21T02:17:42 | 2021-05-21T04:03:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,791 | cpp | /*========================== begin_copyright_notice ============================
Copyright (C) 2021 Intel Corporation
SPDX-License-Identifier: MIT
============================= end_copyright_notice ===========================*/
#include "vc/Utils/GenX/Printf.h"
#include <llvm/GenXIntrinsics/GenXIntrinsics.h>
#include <llvm/ADT/Optional.h>
#include <llvm/ADT/STLExtras.h>
#include <llvm/ADT/StringRef.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/Operator.h>
#include <llvm/IR/Value.h>
#include <llvm/Support/Casting.h>
#include <algorithm>
#include <iterator>
#include <regex>
#include <string>
#include "Probe/Assertion.h"
using namespace llvm;
using namespace vc;
// extracts underlying c-string from provided constant
static StringRef extractCStr(const Constant &CStrConst) {
if (isa<ConstantDataArray>(CStrConst))
return cast<ConstantDataArray>(CStrConst).getAsCString();
IGC_ASSERT(isa<ConstantAggregateZero>(CStrConst));
return "";
}
Optional<StringRef> vc::getConstStringFromOperandOptional(const Value &Op) {
IGC_ASSERT_MESSAGE(Op.getType()->isPointerTy(),
"wrong argument: pointer was expected");
IGC_ASSERT_MESSAGE(Op.getType()->getPointerElementType()->isIntegerTy(8),
"wrong argument: i8* value was expected");
if (!isa<GEPOperator>(Op))
return {};
auto *StrConst = cast<GEPOperator>(Op).getPointerOperand();
if (!isa<GlobalVariable>(StrConst))
return {};
return extractCStr(*cast<GlobalVariable>(StrConst)->getInitializer());
}
StringRef vc::getConstStringFromOperand(const Value &Op) {
auto FmtStr = getConstStringFromOperandOptional(Op);
IGC_ASSERT_MESSAGE(FmtStr.hasValue(),
"couldn't reach constexpr string through pointer operand");
return FmtStr.getValue();
}
using SRefMatch = std::match_results<StringRef::iterator>;
using SRefRegExIterator = std::regex_iterator<StringRef::iterator>;
// Given that \p ArgDesc describes integer conversion with signedness equal to
// \p IsSigned, defines which particular integer type is provided.
static PrintfArgInfo parseIntLengthModifier(StringRef ArgDesc, bool IsSigned) {
std::string Suffix{1u, ArgDesc.back()};
if (ArgDesc.endswith("hh" + Suffix))
return {PrintfArgInfo::Char, IsSigned};
if (ArgDesc.endswith("h" + Suffix))
return {PrintfArgInfo::Short, IsSigned};
if (ArgDesc.endswith("ll" + Suffix))
// TOTHINK: maybe we need a separate type ID for long long.
return {PrintfArgInfo::Long, IsSigned};
if (ArgDesc.endswith("l" + Suffix))
return {PrintfArgInfo::Long, IsSigned};
return {PrintfArgInfo::Int, IsSigned};
}
static StringRef toStringRef(SRefMatch Match) {
IGC_ASSERT_MESSAGE(!Match.empty(),
"wrong argument: matched string is expected");
return {Match[0].first, static_cast<std::size_t>(Match[0].length())};
}
// \p ArgDescMatch is a format string conversion specifier matched by a regex
// (some string that starts with % and ends with d,i,f,...).
static PrintfArgInfo parseArgDesc(SRefMatch ArgDescMatch) {
StringRef ArgDesc = toStringRef(ArgDescMatch);
if (ArgDesc.endswith("c"))
// FIXME: support %lc
return {PrintfArgInfo::Int, /* IsSigned */ true};
if (ArgDesc.endswith("s"))
// FIXME: support %ls
return {PrintfArgInfo::String, /* IsSigned */ false};
if (ArgDesc.endswith("d") || ArgDesc.endswith("i"))
return parseIntLengthModifier(ArgDesc, /* IsSigned */ true);
if (ArgDesc.endswith("o") || ArgDesc.endswith("u") ||
ArgDesc.endswith_lower("x"))
return parseIntLengthModifier(ArgDesc, /* IsSigned */ false);
if (ArgDesc.endswith_lower("f") || ArgDesc.endswith_lower("e") ||
ArgDesc.endswith_lower("a") || ArgDesc.endswith_lower("g"))
return {PrintfArgInfo::Double, /* IsSigned */ true};
IGC_ASSERT_MESSAGE(ArgDesc.endswith("p"), "unexpected conversion specifier");
return {PrintfArgInfo::Pointer, /* IsSigned */ false};
}
PrintfArgInfoSeq vc::parseFormatString(StringRef FmtStr) {
PrintfArgInfoSeq Args;
std::regex ArgDescRegEx{"%(?:%|.*?[csdioxXufFeEaAgGp])"};
auto &&ArgDescs = make_filter_range(
make_range(SRefRegExIterator{FmtStr.begin(), FmtStr.end(), ArgDescRegEx},
SRefRegExIterator{}),
[](SRefMatch ArgDesc) { return toStringRef(ArgDesc) != "%%"; });
transform(ArgDescs, std::back_inserter(Args),
[](SRefMatch ArgDesc) { return parseArgDesc(ArgDesc); });
return Args;
}
bool vc::isPrintFormatIndex(const User &Usr) {
return GenXIntrinsic::getGenXIntrinsicID(&Usr) ==
GenXIntrinsic::genx_print_format_index;
}
static bool isLegalPrintFormatIndexGEPImpl(const User &GEP) {
IGC_ASSERT_MESSAGE(
isa<GEPOperator>(GEP),
"wrong argument: gep instruction or gep constexpr are expected");
if (GEP.user_empty())
return false;
return std::all_of(GEP.user_begin(), GEP.user_end(),
[](const User *Usr) { return isPrintFormatIndex(*Usr); });
}
bool vc::isLegalPrintFormatIndexGEP(const GetElementPtrInst &GEP) {
return isLegalPrintFormatIndexGEPImpl(GEP);
}
bool vc::isLegalPrintFormatIndexGEP(const Value &V) {
if (isa<GetElementPtrInst>(V))
return isLegalPrintFormatIndexGEPImpl(cast<User>(V));
if (isa<ConstantExpr>(V) &&
cast<ConstantExpr>(V).getOpcode() == Instruction::GetElementPtr)
return isLegalPrintFormatIndexGEPImpl(cast<User>(V));
return false;
}
bool vc::isPrintFormatIndexGEP(const GEPOperator &GEP) {
return std::any_of(GEP.user_begin(), GEP.user_end(),
[](const User *Usr) { return isPrintFormatIndex(*Usr); });
}
bool vc::isPrintFormatIndexGEP(const User &Usr) {
if (!isa<GEPOperator>(Usr))
return false;
return isPrintFormatIndexGEP(cast<GEPOperator>(Usr));
}
| [
"[email protected]"
] | |
5fe58ea5c94898f78cec3ab075f98b3946bd3d09 | 7a2425190626dd2e75dd6cbca9fe47727afbad42 | /cxxrt-source/testsuite/cxxrt.conformance/loc-22-1-1-1-2.exp | 6e7811bbb191abfa7c380b7b675f544801d11e31 | [] | no_license | dietmarkuehl/kuhllib | fadd4073c9b09992479e92112ef34c367cb90fad | 482ddc2b910870398a9a2bcaa0a77a145e081f78 | refs/heads/main | 2023-08-31T22:13:02.079530 | 2023-08-21T22:14:14 | 2023-08-21T22:14:14 | 3,148,966 | 71 | 7 | null | 2023-08-21T22:14:15 | 2012-01-10T21:49:09 | C++ | UTF-8 | C++ | false | false | 2,304 | exp | #!/usr/local/bin/expect
# -*-C++-*- loc-22-1-1-1-2.exp -- C++ is actually a lie but it helps
# --------------------------------------------------------------------------
# Copyright (c) 2002 Dietmar Kuehl
# 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.
# --------------------------------------------------------------------------
# Author: Dietmar Kuehl <http://www.dietmar-kuehl.de/>
# Title: Class locale::facet
# Version: $Id: loc-22-1-1-1-2.exp,v 1.1.1.1 2002/06/05 01:02:57 dietmar_kuehl Exp $
# --------------------------------------------------------------------------
inline_compile {
#include <iostream>
#include <locale>
#include <cstdlib>
#if !defined(_CXXRT_STD_NAME)
# define STD std::
#else
# define STD _CXXRT_STD_NAME::
#endif
class facet: public STD locale::facet
{
public:
static STD locale::id id;
facet(): STD locale::facet(), refs(0) {}
explicit facet(STD size_t r): STD locale::facet(r), refs(r) {}
~facet() { STD cout << "dtor: " << static_cast<int>(refs) << "\n"; }
private:
STD size_t refs;
};
STD locale::id facet::id;
int main(int, char *[])
{
STD locale l;
STD locale l1(l, new facet);
STD locale l2(l, new facet(1));
return 0;
}
}
simple_test "locale::facet refcount" "" {
dtor: 0
}
| [
"[email protected]"
] | |
453d8030070ac2115102ea4e30bdd990c79f9063 | 1e5c93564f82e6b069504a38c7048c1e9e1e47a6 | /2017.1/algorithms-review/t235.cpp | 0e82403c82d77c8a9e29c1b4f5158cb1b47da69b | [
"MIT"
] | permissive | Forec/learn | d3a28209b73f4ffa9026dd232b4914f2e19f7b8d | 38ef91d1310f82713e7a04c45c7e99e3929df813 | refs/heads/master | 2021-01-17T02:33:31.201367 | 2017-10-18T15:44:17 | 2017-10-18T15:44:17 | 39,928,290 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,496 | cpp | #include <iostream>
#include <unordered_map>
#include <vector>
#include <unordered_set>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution1 {
private:
unordered_set<TreeNode*> vis;
unordered_map<TreeNode*, TreeNode*> par;
TreeNode *pn, *qn;
TreeNode *res;
TreeNode * find(TreeNode *u){
return par[u] == u ? u : find(par[u]);
}
void init(TreeNode * root){
if (root == NULL)
return;
par[root] = root;
init(root->left);
init(root->right);
}
void tarjan(TreeNode * root){
if (root == NULL)
return;
vis.insert(root);
if (root == pn || root == qn){
if (root == pn && vis.count(qn) >= 1)
res = find(qn);
if (root == qn && vis.count(pn) >= 1)
res = find(pn);
}
if (root->left != NULL && vis.count(root->left) == 0){
tarjan(root->left);
par[root->left] = root;
}
if (root->right != NULL && vis.count(root->right) == 0){
tarjan(root->right);
par[root->right] = root;
}
}
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
res = NULL;
pn = p; qn = q;
vis.clear();
par.clear();
init(root);
tarjan(root);
return res;
}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while ((root->val - p->val) * (root->val - q->val) > 0) {
root = p->val > root->val ? root->right : root->left;
}
return root;
}
};
int main(){
TreeNode * n6 = new TreeNode(6);
TreeNode * n2 = new TreeNode(2);
TreeNode * n8 = new TreeNode(8);
TreeNode * n0 = new TreeNode(0);
TreeNode * n4 = new TreeNode(4);
TreeNode * n7 = new TreeNode(7);
TreeNode * n9 = new TreeNode(9);
TreeNode * n3 = new TreeNode(3);
TreeNode * n5 = new TreeNode(5);
n6->left = n2; n6->right = n8;
n2->left = n0; n2->right = n4;
n4->left = n3; n4->right = n5;
n8->left = n7; n8->right = n9;
Solution sol;
TreeNode * ans1 = sol.lowestCommonAncestor(n6, n2, n8);
cout << (ans1 != NULL && 6 == ans1->val) << endl;
TreeNode * ans2 = sol.lowestCommonAncestor(n6, n2, n4);
cout << (ans2 != NULL && 2 == ans2->val) << endl;
TreeNode * ans3 = sol.lowestCommonAncestor(n6, n0, n5);
cout << (ans3 != NULL && 2 == ans3->val) << endl;
return 0;
}
| [
"[email protected]"
] | |
3142093627ae4033a8b5ff12d61960a38bac28ed | 26dbe4913ffb77fad2eafb6ba466233e956ef68e | /debugformat/debugformat-example.cpp | faa0b58f92568a4925f7f58555a1557a89a5c209 | [] | no_license | retdec-build/retdec-build-system-tests | c1fd970b2237c5e3369d35cde46f4c234c4f0dd9 | dc5882c340d7640e207e63e43723e3304257506b | refs/heads/master | 2023-01-20T18:07:58.232114 | 2020-07-21T09:55:37 | 2020-07-21T09:55:37 | 467,175,156 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 157 | cpp |
#include <iostream>
#include <retdec/debugformat/debugformat.h>
int main(int argc, char* argv[])
{
retdec::debugformat::DebugFormat debug;
return 0;
}
| [
"[email protected]"
] | |
c05247070a7d6efdb85211d709a7bdaa7b5322ed | 4b055f9c18ad613f10c0e281873b800f3ff515ff | /Minigin/Renderer.cpp | bbf67f609ae66d97ae9e10e8016be455e0dd1735 | [] | no_license | minoarno/MidestinyEngine | 982508e7ac0197fc49649c1bec362ad5ba113469 | 68e88f2f3dc537cf4add9fe474004681a90e8a84 | refs/heads/main | 2023-07-16T06:31:24.398267 | 2021-08-23T04:40:14 | 2021-08-23T04:40:14 | 337,725,203 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,959 | cpp | #include "MiniginPCH.h"
#include "Renderer.h"
#include <SDL.h>
#include "SceneManager.h"
#include "Texture2D.h"
bool dae::Renderer::m_ShowDemo = true;
void dae::Renderer::Init(SDL_Window * window)
{
m_Window = window;
m_Renderer = SDL_CreateRenderer(window, GetOpenGLDriverIndex(), SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (m_Renderer == nullptr)
{
throw std::runtime_error(std::string("SDL_CreateRenderer Error: ") + SDL_GetError());
}
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGui_ImplSDL2_InitForOpenGL(window, SDL_GL_GetCurrentContext());
ImGui_ImplOpenGL2_Init();
}
int dae::Renderer::GetOpenGLDriverIndex()
{
auto openglIndex = -1;
const int driverCount = SDL_GetNumRenderDrivers();
for (int i = 0; i < driverCount; i++)
{
SDL_RendererInfo info;
if (!SDL_GetRenderDriverInfo(i, &info))
{
if (!strcmp(info.name, "opengl"))
{
openglIndex = i;
}
}
}
return openglIndex;
}
void dae::Renderer::Render() const
{
SDL_RenderClear(m_Renderer);
SceneManager::GetInstance().Render();
ImGui_ImplOpenGL2_NewFrame();
ImGui_ImplSDL2_NewFrame(m_Window);
ImGui::NewFrame();
if (m_ShowDemo)
{
ImGui::ShowDemoWindow(&m_ShowDemo);
}
ImGui::Render();
ImGui_ImplOpenGL2_RenderDrawData(ImGui::GetDrawData());
SDL_RenderPresent(m_Renderer);
}
void dae::Renderer::Destroy()
{
ImGui_ImplOpenGL2_Shutdown();
ImGui_ImplSDL2_Shutdown();
ImGui::DestroyContext();
if (m_Renderer != nullptr)
{
SDL_DestroyRenderer(m_Renderer);
m_Renderer = nullptr;
}
}
void dae::Renderer::RenderTexture(const Texture2D* pTexture, const float x, const float y) const
{
SDL_Rect dst{};
dst.x = static_cast<int>(x);
dst.y = static_cast<int>(y);
SDL_QueryTexture(pTexture->GetSDLTexture(), nullptr, nullptr, &dst.w, &dst.h);
SDL_RenderCopy(GetSDLRenderer(), pTexture->GetSDLTexture(), nullptr, &dst);
}
void dae::Renderer::RenderTexture(const Texture2D* pTexture, const float x, const float y, const float width, const float height) const
{
SDL_Rect dst{};
dst.x = static_cast<int>(x);
dst.y = static_cast<int>(y);
dst.w = static_cast<int>(width);
dst.h = static_cast<int>(height);
SDL_RenderCopy(GetSDLRenderer(), pTexture->GetSDLTexture(), nullptr, &dst);
}
void dae::Renderer::RenderTexture(const Texture2D* pTexture, SDL_Rect srcRect,const float x, const float y, const float width, const float height) const
{
SDL_Rect dst{};
dst.x = static_cast<int>(x);
dst.y = static_cast<int>(y);
dst.w = static_cast<int>(width);
dst.h = static_cast<int>(height);
SDL_RenderCopy(GetSDLRenderer(), pTexture->GetSDLTexture(), &srcRect, &dst);
}
void dae::Renderer::RenderTexture(const Texture2D* pTexture, SDL_Rect srcRect, const float x, const float y) const
{
SDL_Rect dst{};
dst.x = static_cast<int>(x);
dst.y = static_cast<int>(y);
SDL_QueryTexture(pTexture->GetSDLTexture(), nullptr, nullptr, &dst.w, &dst.h);
SDL_RenderCopy(GetSDLRenderer(), pTexture->GetSDLTexture(), &srcRect, &dst);
}
| [
"[email protected]"
] | |
4139dcc5944bb511e85e4d5887d1305b0588320f | 51318bac6c32d5d298e277bad94511bcf3de42cf | /message.cpp | 48be0a2767d3b162eb4227e69fc0d8ffd1607fd3 | [] | no_license | xxmicloxx/GSPlayerQT | 8d66a5ac6ce6a597aa6347faf4b3692d60bd8030 | 83e5f6ed0ef7f1d66e5503a6e9b94602d842996e | refs/heads/master | 2021-01-17T05:30:07.205693 | 2014-01-01T21:05:35 | 2014-01-01T21:05:35 | 4,930,092 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,204 | cpp | #include "message.h"
#include "ui_message.h"
#include <QTimer>
Message::Message(QWidget *parent) :
QWidget(parent),
ui(new Ui::Message)
{
ui->setupUi(this);
opacity = new QGraphicsOpacityEffect(this);
opacity->setOpacity(0.0);
this->setGraphicsEffect(opacity);
blendIn = new QPropertyAnimation(opacity, "opacity");
blendOut = new QPropertyAnimation(opacity, "opacity");
moveUp = new QPropertyAnimation(this, "geometry");
moveUp->setDuration(1000);
blendIn->setDuration(500);
blendOut->setDuration(500);
blendIn->setStartValue(0.0);
blendOut->setStartValue(0.75);
blendIn->setEndValue(0.75);
blendOut->setEndValue(0.0);
this->setAttribute(Qt::WA_TransparentForMouseEvents);
connect(blendIn, SIGNAL(finished()), this, SLOT(blendedIn()));
}
Message::~Message()
{
delete ui;
delete blendIn;
delete blendOut;
delete moveUp;
}
void Message::blendedIn() {
QTimer* timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), blendOut, SLOT(start()));
timer->setSingleShot(true);
timer->start(1500);
}
void Message::setText(std::string text) {
ui->lblMessage->setText(QString::fromStdString(text));
}
| [
"[email protected]"
] | |
c36c9d7e02d6cc3785e5dcb5c7146f18d9599bdc | 7e72fd8bd7faf8a311439b43fa7574c16daafc92 | /src/Graph.hpp | 2d80f6089dbb5b2d6438d5cc32a446d7fa171d5f | [] | no_license | stryitg/csp_lab1 | 20d8973c1fa422efecefc76a4f39627a756eeb6f | 7d75ee5146a60e3026fd07c870d45540564ff907 | refs/heads/master | 2023-02-07T07:52:34.326155 | 2020-12-19T17:24:41 | 2020-12-19T17:24:41 | 305,174,489 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 90 | hpp | #pragma once
#include <vector>
using AdjacmentMatrix = std::vector<std::vector<double>>; | [
"[email protected]"
] | |
dd5a3f7f5f30d778882add63e5e6f5456d399c77 | 681dd06d092fb9af9639fdc2d9be897ffc260645 | /Source/JCVoronoiPlugin/Private/JCVValueGenerator.cpp | 83ee3f966e32942e4d7e89a0594724aa79286207 | [
"MIT"
] | permissive | mengdada/JCVoronoiPlugin | 5934675540a9307cbfc3f6613e231e9a00dd4839 | 25b309759160d52f44604f013e4551c6e597fa19 | refs/heads/master | 2020-05-15T23:07:18.883778 | 2019-04-03T22:15:20 | 2019-04-03T22:15:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,001 | cpp | ////////////////////////////////////////////////////////////////////////////////
//
// MIT License
//
// Copyright (c) 2018-2019 Nuraga Wiswakarma
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////
//
#include "JCVValueGenerator.h"
#include "JCVDiagramAccessor.h"
int32 FJCVValueGenerator::MarkFeature(FJCVDiagramMap& Map, TQueue<FJCVCell*>& cellQ, TSet<FJCVCell*>& ExclusionSet, FJCVCell& c, int32 i, const FJCVCellTraits& cond)
{
int32 count = 0;
cellQ.Enqueue(&c);
ExclusionSet.Emplace(&c);
while (! cellQ.IsEmpty())
{
FJCVCell* cell;
cellQ.Dequeue(cell);
FJCVEdge* g = cell->GetEdge();
check(g);
if (cond.HasValidFeature(*cell))
{
cell->SetType(cond.FeatureType, i);
++count;
}
else
continue;
do
{
FJCVCell* n = Map.GetCellNeighbour(g);
if (! n) continue;
if (ExclusionSet.Contains(n)) continue;
if (cond.HasValidFeature(*n))
{
ExclusionSet.Emplace(n);
cellQ.Enqueue(n);
}
}
while ((g = g->next) != nullptr);
}
return count;
}
void FJCVValueGenerator::AddRadialFill0(FJCVDiagramMap& Map, FRandomStream& Rand, FJCVCell& OriginCell, const FJCVRadialFill& FillParams)
{
check(Map.IsValidIndex(OriginCell.GetIndex()));
float BaseValue = FillParams.Value;
const float Radius = FillParams.Radius;
const float Sharpness = FillParams.Sharpness;
const bool bRadial = FillParams.bRadialDegrade;
const bool bFilterBorder = FillParams.bFilterBorder;
const bool bUseSharpness = Sharpness > KINDA_SMALL_NUMBER;
TQueue<FJCVCell*> cellQ;
TSet<FJCVCell*> ExclusionSet;
OriginCell.Value = FMath::Min(OriginCell.Value+BaseValue, 1.f);
ExclusionSet.Reserve(Map.Num());
ExclusionSet.Emplace(&OriginCell);
cellQ.Enqueue(&OriginCell);
while (! cellQ.IsEmpty() && BaseValue > .01f)
{
FJCVCell* cell;
cellQ.Dequeue(cell);
if (bRadial)
{
BaseValue = cell->Value;
}
BaseValue *= Radius;
FJCVEdge* g = cell->GetEdge();
check(g);
do
{
FJCVCell* n = Map.GetCellNeighbour(g);
// Skip invalid or already visited cells
if (! n || ExclusionSet.Contains(n))
{
continue;
}
ExclusionSet.Emplace(n);
cellQ.Enqueue(n);
// Zero border cell values if required
if (bFilterBorder && n->IsBorder())
{
n->Value = 0.f;
continue;
}
// Calculate new cell value
float SharpnessModifier = 1.f;
if (bUseSharpness)
{
SharpnessModifier = Rand.GetFraction() * Sharpness + 1.1f - Sharpness;
}
float CellValue = n->Value + BaseValue * SharpnessModifier;
CellValue = FMath::Min(CellValue, 1.f);
if (n->Value < CellValue)
{
n->Value = CellValue;
}
}
while ((g = g->next) != nullptr);
}
}
void FJCVValueGenerator::AddRadialFill(FJCVDiagramMap& Map, FRandomStream& Rand, FJCVCell& OriginCell, const FJCVRadialFill& FillParams)
{
if (FillParams.Radius < KINDA_SMALL_NUMBER)
{
return;
}
check(Map.IsValidIndex(OriginCell.GetIndex()));
const FVector2D OriginPosition = OriginCell.ToVector2D();
const float Radius = FillParams.Radius;
const float RadiusSq = Radius * Radius;
const float InvRadius = 1.f / Radius;
const bool bFilterBorder = FillParams.bFilterBorder;
const UCurveFloat* ValueCurve = FillParams.ValueCurve;
float BaseValue = FillParams.Value;
// Cell queue and visited cell set
TQueue<FJCVCell*> cellQ;
TSet<FJCVCell*> cellS;
// Assign base value to origin cell
OriginCell.Value = BaseValue;
cellS.Reserve(Map.Num());
cellS.Emplace(&OriginCell);
cellQ.Enqueue(&OriginCell);
while (! cellQ.IsEmpty())
{
FJCVCell* cell;
cellQ.Dequeue(cell);
FJCVEdge* g = cell->GetEdge();
check(g);
do
{
FJCVCell* n = Map.GetCellNeighbour(g);
// Skip invalid or already visited cells
if (! n || cellS.Contains(n))
{
continue;
}
cellS.Emplace(n);
float DistToOriginSq = (n->ToVector2D()-OriginPosition).SizeSquared();
// Skip cells outside of radius
if (DistToOriginSq > RadiusSq)
{
continue;
}
cellQ.Enqueue(n);
// Set border cell value to zero if filter is set
if (bFilterBorder && n->IsBorder())
{
n->Value = 0.f;
continue;
}
// Calculate new cell value
float ValueRatio = (1.f - FMath::Sqrt(DistToOriginSq) * InvRadius);
if (ValueCurve)
{
ValueRatio = ValueCurve->GetFloatValue(ValueRatio);
}
n->Value = BaseValue * ValueRatio;
}
while ((g = g->next) != nullptr);
}
}
void FJCVValueGenerator::MarkFeatures(FJCVDiagramMap& Map, const FJCVCellTraits& Cond, FJCVCellSet& ExclusionSet)
{
if (Map.IsEmpty())
{
return;
}
TQueue<FJCVCell*> cellQ;
const int32 cellN = Map.Num();
int32 f = 0;
int32 n;
do
{
FJCVCell* c = nullptr;
n = 0;
// Find single unmarked cell
for (int32 i=0; i<cellN; ++i)
if (Cond.HasUndefinedType(Map.GetCell(i)))
c = &Map.GetCell(i);
if (c)
n = MarkFeature(Map, cellQ, ExclusionSet, *c, f++, Cond);
}
// Loop until there is no undefined cell left or no conversion made
while (n > 0);
}
void FJCVValueGenerator::MarkFeatures(FJCVDiagramMap& Map, const FJCVSite& Seed, const FJCVCellTraits& Cond, int32 FeatureIndex, FJCVCellSet& ExclusionSet)
{
if (Map.IsEmpty())
{
return;
}
const FJCVSite* s = &Seed;
FJCVCell* c = Map.GetCell(s);
if (c)
{
TQueue<FJCVCell*> cellQ;
MarkFeature(Map, cellQ, ExclusionSet, *c, FeatureIndex, Cond);
}
}
float FJCVValueGenerator::GetClosestDistanceFromCellSq(
FJCVDiagramMap& Map,
const FJCVCell& OriginCell,
uint8 FeatureType,
int32 FeatureIndex,
bool bAgainstAnyType
)
{
check(Map.HasFeatureType(FeatureType));
check(Map.IsValidCell(&OriginCell));
const FVector2D Origin = OriginCell.ToVector2D();
float DistanceToFeatureSq = BIG_NUMBER;
TFunctionRef<void(FJCVCell& Cell)> CellCallback(
[&](FJCVCell& Cell)
{
const FVector2D CellPoint = Cell.ToVector2D();
const float CellDistSq = (CellPoint-Origin).SizeSquared();
if (CellDistSq < DistanceToFeatureSq)
{
DistanceToFeatureSq = CellDistSq;
}
} );
if (bAgainstAnyType)
{
Map.VisitCells(CellCallback, &OriginCell);
}
else
{
Map.VisitFeatureCells(CellCallback, FeatureType, FeatureIndex);
}
return DistanceToFeatureSq;
}
float FJCVValueGenerator::GetFurthestDistanceFromCellSq(
FJCVDiagramMap& Map,
const FJCVCell& OriginCell,
uint8 FeatureType,
int32 FeatureIndex,
bool bAgainstAnyType
)
{
check(Map.HasFeatureType(FeatureType));
check(Map.IsValidCell(&OriginCell));
const FVector2D Origin = OriginCell.ToVector2D();
float DistanceToFeatureSq = TNumericLimits<float>::Min();
TFunctionRef<void(FJCVCell& Cell)> CellCallback(
[&](FJCVCell& Cell)
{
const FVector2D CellPoint = Cell.ToVector2D();
const float CellDistSq = (CellPoint-Origin).SizeSquared();
if (CellDistSq > DistanceToFeatureSq)
{
DistanceToFeatureSq = CellDistSq;
}
} );
if (bAgainstAnyType)
{
Map.VisitCells(CellCallback, &OriginCell);
}
else
{
Map.VisitFeatureCells(CellCallback, FeatureType, FeatureIndex);
}
return DistanceToFeatureSq;
}
void FJCVValueGenerator::MapNormalizedDistanceFromCell(
FJCVDiagramMap& Map,
const FJCVCell& OriginCell,
uint8 FeatureType,
int32 FeatureIndex,
bool bAgainstAnyType
)
{
check(Map.HasFeatureType(FeatureType));
check(Map.IsValidCell(&OriginCell));
const FVector2D Origin = OriginCell.ToVector2D();
const float FurthestDistanceFromCell = GetFurthestDistanceFromCell(Map, OriginCell, FeatureType, FeatureIndex, bAgainstAnyType);
const float InvDistanceFromCell = 1.f / FMath::Max(FurthestDistanceFromCell, KINDA_SMALL_NUMBER);
TFunctionRef<void(FJCVCell&)> CellCallback(
[&](FJCVCell& Cell)
{
const FVector2D CellPoint = Cell.ToVector2D();
const float CellDist = (CellPoint-Origin).Size();
Cell.SetValue(CellDist * InvDistanceFromCell);
} );
if (bAgainstAnyType)
{
Map.VisitCells(CellCallback, &OriginCell);
}
else
{
Map.VisitFeatureCells(CellCallback, FeatureType, FeatureIndex);
}
}
void UJCVValueUtilityLibrary::SetCellValues(UJCVDiagramAccessor* Accessor, float Value)
{
if (! IsValid(Accessor))
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillAtPosition() ABORTED, INVALID ACCESSOR"));
return;
}
if (! Accessor->HasValidMap())
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillAtPosition() ABORTED, INVALID ACCESOR MAP"));
return;
}
FJCVDiagramMap& Map(Accessor->GetMap());
const int32 CellCount = Map.Num();
for (int32 i=0; i<CellCount; ++i)
{
Map.GetCell(i).SetValue(Value);
}
}
void UJCVValueUtilityLibrary::AddRadialFillAtPosition(UJCVDiagramAccessor* Accessor, int32 Seed, const FVector2D& Position, FJCVRadialFill FillParams)
{
if (! IsValid(Accessor))
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillAtPosition() ABORTED, INVALID ACCESSOR"));
return;
}
if (! Accessor->HasValidMap())
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillAtPosition() ABORTED, INVALID ACCESOR MAP"));
return;
}
FJCVDiagramMap& Map(Accessor->GetMap());
FJCVCell* OriginCell = Map.GetCell(Map->Find(Position));
if (OriginCell)
{
FJCVValueGenerator::AddRadialFill(Map, Seed, *OriginCell, FillParams);
}
}
void UJCVValueUtilityLibrary::AddRadialFillAtCell(UJCVDiagramAccessor* Accessor, int32 Seed, FJCVCellRef OriginCellRef, FJCVRadialFill FillParams)
{
if (! IsValid(Accessor))
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillAtCell() ABORTED, INVALID ACCESSOR"));
return;
}
if (! Accessor->HasValidMap())
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillAtCell() ABORTED, INVALID ACCESOR MAP"));
return;
}
if (! Accessor->IsValidCell(OriginCellRef))
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillAtCell() ABORTED, INVALID ORIGIN CELL"));
return;
}
FJCVDiagramMap& Map(Accessor->GetMap());
FJCVCell& OriginCell(Map.GetCell(OriginCellRef.Data->GetIndex()));
FJCVValueGenerator::AddRadialFill(Map, Seed, OriginCell, FillParams);
}
void UJCVValueUtilityLibrary::AddRadialFillByIndex(UJCVDiagramAccessor* Accessor, int32 Seed, int32 CellIndex, FJCVRadialFill FillParams)
{
if (! IsValid(Accessor))
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillByIndex() ABORTED, INVALID ACCESSOR"));
return;
}
if (! Accessor->HasValidMap())
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillByIndex() ABORTED, INVALID ACCESOR MAP"));
return;
}
FJCVDiagramMap& Map(Accessor->GetMap());
if (Map.IsValidIndex(CellIndex))
{
FJCVCell& OriginCell(Map.GetCell(CellIndex));
FJCVValueGenerator::AddRadialFill(Map, Seed, OriginCell, FillParams);
}
}
void UJCVValueUtilityLibrary::AddRadialFillNum(UJCVDiagramAccessor* Accessor, int32 Seed, int32 PointCount, FJCVRadialFill FillParams, float Padding, float ValueThreshold, int32 MaxPlacementTest)
{
if (! IsValid(Accessor))
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillNum() ABORTED, INVALID ACCESSOR"));
return;
}
if (! Accessor->HasValidMap())
{
UE_LOG(LogJCV,Error, TEXT("UJCVValueUtilityLibrary::AddRadialFillNum() ABORTED, INVALID ACCESOR MAP"));
return;
}
if (PointCount < 1)
{
return;
}
FJCVDiagramMap& Map(Accessor->GetMap());
FRandomStream Rand(Seed);
const float tMin = FMath::Clamp(ValueThreshold, 0.f, 1.f);
const float tMax = 1.f-tMin;
const int32 CellCount = Map.Num();
Padding = FMath::Clamp(Padding, 0.f, 1.f);
FBox2D Bounds(Accessor->GetBounds());
FBox2D BoundsExpand(Bounds.Min*Padding, Bounds.Max*(1.f-Padding));
for (int32 it=0; it<PointCount; ++it)
{
for (int32 i=0; i<MaxPlacementTest; ++i)
{
int32 CellIdx = Rand.RandHelper(CellCount);
FJCVCell& OriginCell(Map.GetCell(CellIdx));
if (OriginCell.Value < tMin && BoundsExpand.IsInside(OriginCell.ToVector2D()))
{
FillParams.Value *= tMax*Rand.GetFraction();
FillParams.Value += tMin;
FJCVValueGenerator::AddRadialFill(Map, Rand, OriginCell, FillParams);
break;
}
}
}
}
| [
"[email protected]"
] | |
c0ba5e02dbe26de3c9ba7dd4817d85064b84f00f | 06bf3efc9b3b8f5968509e279ec0dd5285f19537 | /test/utilities/testUtils.hpp | b57f2f54778971f5f4e5686033f37afcd5cdfece | [
"BSD-3-Clause"
] | permissive | jiridanek/Strongtalk | 0a87c0eb5281702df6d8c3a927403dc2a7402f72 | ee19957341abe4b2113378394806b18ed329bc07 | refs/heads/master | 2021-05-30T14:09:38.537071 | 2016-01-10T10:34:47 | 2016-01-10T10:34:47 | 42,392,327 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 157 | hpp |
#define as_large_integer(value) \
byteArrayPrimitives::largeIntegerFromSmallInteger(as_smiOop(value), klassOop(Universe::find_global("LargeInteger")))
| [
"[email protected]"
] | |
9e48c2d5e1dd5377ade75545a1450f5d49a47873 | 0e1693c18bb5897e2242549b2512d34555a0a266 | /Libraries/Prim.cpp | e189788adc2ea9ff796b9f20d05d0fb773bca2b1 | [] | no_license | AngelFA04/algoritmos | b3c9cef7b37fb500f05cc463677a99564cefe847 | bbc16d8e492872d6d3cd2f6f0586d3ee9e5590d3 | refs/heads/master | 2022-12-02T02:27:06.874755 | 2020-08-19T15:49:21 | 2020-08-19T15:49:21 | 287,777,577 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,567 | cpp | #include <iostream>
#include <limits.h>
#include "Prim.h"
using namespace std;
Prim::Prim(int numeroNodos, int **matrizAdj){
this->numeroNodos = numeroNodos;
this->matrizAdj = matrizAdj;
arbol = new int[numeroNodos];
visitados = new bool[numeroNodos];
}
void Prim::inicializarValores(){
for(int i = 0; i < numeroNodos; i++){
arbol[i] = -1;
visitados[i] = false;
}
arbol[0] = 0;
visitados[0] = true;
}
bool Prim::noVisiteTodos(){
for(int i = 0; i < numeroNodos; i++){
if(!visitados[i]){
return true;
}
}
return false;
}
void Prim::imprimirSolucion(){
cout << "[ ";
for(int i = 0; i < numeroNodos - 1; i++){
cout << arbol[i] << ", ";
}
cout << arbol[numeroNodos - 1] << " ]" << endl;
}
void Prim::calcularAEM(){
inicializarValores();
while(noVisiteTodos()){
int minPeso = INT_MAX;
int minIndex;
int padre;
for(int i = 0; i < numeroNodos; i++){
if(arbol[i] != -1){
for(int j = 0; j < numeroNodos; j++){
if(visitados[j] || matrizAdj[i][j] == 0) continue;
if(matrizAdj[i][j] < minPeso){
minPeso = matrizAdj[i][j];
minIndex = j;
padre = i;
}
}
}
}
arbol[minIndex] = padre + 1;
visitados[minIndex] = true;
}
imprimirSolucion();
}
| [
"[email protected]"
] | |
8023c3c92b9261ac91719046e7ff43d1c456bd8c | ea401c3e792a50364fe11f7cea0f35f99e8f4bde | /hackathon/hanchuan/sscope/FlyCapture2/src/FlyCapture2GUI/Format7DrawingArea.cpp | 96b0a471f48323af694a71c83e972ababdde511d | [
"MIT"
] | permissive | Vaa3D/vaa3d_tools | edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9 | e6974d5223ae70474efaa85e1253f5df1814fae8 | refs/heads/master | 2023-08-03T06:12:01.013752 | 2023-08-02T07:26:01 | 2023-08-02T07:26:01 | 50,527,925 | 107 | 86 | MIT | 2023-05-22T23:43:48 | 2016-01-27T18:19:17 | C++ | WINDOWS-1252 | C++ | false | false | 18,920 | cpp | //=============================================================================
// Copyright © 2008 Point Grey Research, Inc. All Rights Reserved.
//
// This software is the confidential and proprietary information of Point
// Grey Research, Inc. ("Confidential Information"). You shall not
// disclose such Confidential Information and shall use it only in
// accordance with the terms of the license agreement you entered into
// with PGR.
//
// PGR MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
// SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE, OR NON-INFRINGEMENT. PGR SHALL NOT BE LIABLE FOR ANY DAMAGES
// SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
// THIS SOFTWARE OR ITS DERIVATIVES.
//=============================================================================
//=============================================================================
// $Id: Format7DrawingArea.cpp,v 1.27 2010/08/05 22:16:18 soowei Exp $
//=============================================================================
#include "Precompiled.h"
#include "Format7DrawingArea.h"
#include <vector>
namespace FlyCapture2
{
Format7DrawingArea::Format7DrawingArea( BaseObjectType* cobject, const Glib::RefPtr<Gnome::Glade::Xml>& /*refGlade*/ )
: Gtk::DrawingArea(cobject),
m_moveCursor( Gdk::FLEUR )
{
Gdk::EventMask mask =
Gdk::BUTTON_PRESS_MASK |
Gdk::BUTTON_RELEASE_MASK |
Gdk::BUTTON1_MOTION_MASK |
Gdk::POINTER_MOTION_MASK;
set_events( mask );
m_leftMBHeld = false;
m_rightMBHeld = false;
m_left = 0;
m_top = 0;
m_width = 0;
m_height = 0;
m_lastFiredLeft = 0;
m_lastFiredTop = 0;
m_lastFiredWidth = 0;
m_lastFiredHeight = 0;
m_maxWidth = 0;
m_maxHeight = 0;
m_offsetHStepSize = 0;
m_offsetVStepSize = 0;
m_imageHStepSize = 0;
m_imageVStepSize = 0;
m_startX = 0;
m_startY = 0;
m_offsetX = 0;
m_offsetY = 0;
m_currX = 0;
m_currY = 0;
m_imageSizeChanged = false;
}
Format7DrawingArea::~Format7DrawingArea()
{
}
sigc::signal<void, unsigned int, unsigned int, unsigned int, unsigned int> Format7DrawingArea::signal_image_size_changed()
{
return m_signal_image_size_changed;
}
bool Format7DrawingArea::on_expose_event( GdkEventExpose* event )
{
Glib::RefPtr<Gdk::Window> window = get_window();
if( window == NULL)
{
return true;
}
Cairo::RefPtr<Cairo::Context> refCairo = window->create_cairo_context();
// clip to the area indicated by the expose event so that we only redraw
// the portion of the window that needs to be redrawn
refCairo->rectangle(
event->area.x,
event->area.y,
event->area.width,
event->area.height);
refCairo->clip();
// Get width / height of widget
int width;
int height;
window->get_size( width, height );
// Figure out which scale to use (horizontal or vertical)
const float horzScale = m_maxWidth / (float)width;
const float vertScale = m_maxHeight / (float)height;
m_previewScale = (horzScale < vertScale) ? vertScale : horzScale;
Gtk::AspectFrame* pFrame = (Gtk::AspectFrame*)get_parent();
float fRatio = m_maxWidth / (float)m_maxHeight;
if ( fRatio != pFrame->property_ratio())
{
pFrame->set( 0.0, 0.0, fRatio, false );
}
unsigned int scaledLeft = static_cast<unsigned int>(ToScaled( m_left ));
unsigned int scaledTop = static_cast<unsigned int>(ToScaled( m_top ));
unsigned int scaledWidth = static_cast<unsigned int>(ToScaled( m_width ));
unsigned int scaledHeight = static_cast<unsigned int>(ToScaled( m_height ));
// Fill the background with the PGR color
FillBackground(
refCairo,
event->area.x,
event->area.y,
event->area.width,
event->area.height);
// Draw the data on top of the filled background
DrawRectangle( refCairo, scaledLeft, scaledTop, scaledWidth, scaledHeight );
DrawDashedLines( refCairo, scaledLeft, scaledTop, scaledWidth, scaledHeight );
DrawImageDimensionsText( refCairo, m_left, m_top, m_width, m_height );
DrawCurrentCursorPositionText( refCairo, m_currX, m_currY );
if ( m_imageSizeChanged == true )
{
if ( m_left != m_lastFiredLeft ||
m_top != m_lastFiredTop ||
m_width != m_lastFiredWidth ||
m_height != m_lastFiredHeight )
{
m_signal_image_size_changed( m_left, m_top, m_width, m_height );
m_lastFiredLeft = m_left;
m_lastFiredTop = m_top;
m_lastFiredWidth = m_width;
m_lastFiredHeight = m_height;
}
m_imageSizeChanged = false;
}
return true;
}
void Format7DrawingArea::FillBackground(
Cairo::RefPtr<Cairo::Context> refCairo,
unsigned int left, unsigned int top, unsigned int width, unsigned int height )
{
refCairo->save();
refCairo->rectangle(
left,
top,
width,
height );
const double divisor = 255.0;
const double red = 157.0 / divisor;
const double green = 184.0 / divisor;
const double blue = 210.0 / divisor;
refCairo->set_source_rgb( red, green, blue );
refCairo->fill();
refCairo->restore();
}
void Format7DrawingArea::DrawRectangle(
Cairo::RefPtr<Cairo::Context> refCairo,
unsigned int left, unsigned int top, unsigned int width, unsigned int height )
{
refCairo->save();
// Set draw color
refCairo->set_source_rgb(1.0, 0.0, 0.0);
// Set line width
refCairo->set_line_width(1.0);
// Draw the image rectangle
refCairo->rectangle(
left,
top,
width,
height );
refCairo->stroke();
refCairo->restore();
}
void Format7DrawingArea::DrawDashedLines(
Cairo::RefPtr<Cairo::Context> refCairo,
unsigned int left, unsigned int top, unsigned int width, unsigned int height )
{
refCairo->save();
// Get width / height of widget
int windowWidth;
int windowHeight;
get_window()->get_size( windowWidth, windowHeight );
// Set the dash parameters
std::vector<double> dash_vector(2);
dash_vector[0] = 4.0;
dash_vector[1] = 2.0;
refCairo->set_dash( dash_vector, 0.0 );
// Set draw color
refCairo->set_source_rgb(0.0, 0.0, 0.0);
// Set line width
refCairo->set_line_width(1.0);
refCairo->move_to( left, top );
refCairo->line_to( left, 0 );
refCairo->move_to( left, top );
refCairo->line_to( 0, top );
refCairo->move_to( left + width, top + height );
refCairo->line_to( left + width, windowHeight );
refCairo->move_to( left + width, top + height );
refCairo->line_to( windowWidth, top + height );
refCairo->stroke();
refCairo->restore();
}
void Format7DrawingArea::DrawImageDimensionsText(
Cairo::RefPtr<Cairo::Context> refCairo,
unsigned int left, unsigned int top, unsigned int width, unsigned int height )
{
refCairo->save();
// Set the font parameters
refCairo->select_font_face(
"monospace",
Cairo::FONT_SLANT_NORMAL,
Cairo::FONT_WEIGHT_BOLD );
refCairo->set_font_size( 10 );
// Set draw color to black
refCairo->set_source_rgb(0.0, 0.0, 0.0);
// Get width / height of widget
int widgetWidth = 0;
int widgetHeight = 0;
get_window()->get_size( widgetWidth, widgetHeight );
// Create text for image offset
char imageOffsets[128];
sprintf(
imageOffsets,
"Start: (%d,%d) End: (%d,%d)",
left,
top,
left + width,
top + height );
Cairo::TextExtents offsetExtents;
refCairo->get_text_extents(imageOffsets, offsetExtents);
// Draw the offset text
refCairo->move_to(
(widgetWidth/2) - (offsetExtents.width/2),
(widgetHeight/2) - offsetExtents.height - (offsetExtents.height/2));
refCairo->show_text( imageOffsets );
// Create text for image dimensions
char imageDimensions[128];
sprintf(
imageDimensions,
"Dimensions: %d x %d",
width,
height);
Cairo::TextExtents dimensionsExtents;
refCairo->get_text_extents(imageDimensions, dimensionsExtents);
// Draw the dimensions text
refCairo->move_to(
(widgetWidth/2) - (dimensionsExtents.width/2),
(widgetHeight/2) + dimensionsExtents.height + (dimensionsExtents.height/2));
refCairo->show_text( imageDimensions );
refCairo->restore();
}
void Format7DrawingArea::DrawCurrentCursorPositionText(
Cairo::RefPtr<Cairo::Context> refCairo,
unsigned int currX, unsigned int currY )
{
refCairo->save();
// Set the font parameters
refCairo->select_font_face(
"monospace",
Cairo::FONT_SLANT_NORMAL,
Cairo::FONT_WEIGHT_BOLD );
refCairo->set_font_size( 10 );
// Set draw color to black
refCairo->set_source_rgb(0.0, 0.0, 0.0);
// Print current cursor position
char cursorPosition[128];
sprintf(
cursorPosition,
"Cursor: (%d, %d)",
currX,
currY );
// Get width / height of widget
int width;
int height;
get_window()->get_size( width, height );
Cairo::TextExtents textExtents;
refCairo->get_text_extents( cursorPosition, textExtents );
refCairo->move_to( (width / 2) - (textExtents.width / 2), (height * 0.9) - (textExtents.height / 2) );
refCairo->show_text( cursorPosition );
refCairo->restore();
}
bool Format7DrawingArea::on_button_press_event( GdkEventButton* event )
{
gdouble startX = event->x;
gdouble startY = event->y;
ClipPoint( &startX, &startY );
unsigned int startXOrig = ToOriginal( (float)startX );
unsigned int startYOrig = ToOriginal( (float)startY );
switch ( event->button )
{
case 1:
// Store the start point
m_startX = startXOrig;
m_startY = startYOrig;
m_leftMBHeld = true;
break;
case 3:
get_window()->set_cursor( m_moveCursor );
// Store the difference between the start point and the left/top
m_offsetX = m_left - startXOrig;
m_offsetY = m_top - startYOrig;
m_rightMBHeld = true;
break;
}
return true;
}
bool Format7DrawingArea::on_button_release_event( GdkEventButton* event )
{
gdouble endX = event->x;
gdouble endY = event->y;
ClipPoint( &endX, &endY );
const unsigned int endXOrig = ToOriginal( (float)endX );
const unsigned int endYOrig = ToOriginal( (float)endY );
switch ( event->button )
{
case 1:
m_left = std::min(m_startX, endXOrig);
m_top = std::min(m_startY, endYOrig);
m_width = std::max(m_startX, endXOrig) - m_left;
m_height = std::max(m_startY, endYOrig) - m_top;
ClampAllValues();
m_imageSizeChanged = true;
m_leftMBHeld = false;
break;
case 3:
get_window()->set_cursor();
m_rightMBHeld = false;
break;
}
queue_draw();
return true;
}
bool Format7DrawingArea::on_motion_notify_event( GdkEventMotion* event )
{
gdouble currX = event->x;
gdouble currY = event->y;
// This may actually be negative if the mouse is dragged to the
// left or top of the image, so ints should be used instead of
// unsigned ints to prevent overflow
int currXOrig = 0;
int currYOrig = 0;
if ( m_leftMBHeld == true )
{
ClipPoint( &currX, &currY );
currXOrig = ToOriginal( static_cast<float>(currX) );
currYOrig = ToOriginal( static_cast<float>(currY) );
if ( currXOrig <= static_cast<int>(m_startX) )
{
m_left = currXOrig;
m_width = m_startX - m_left;
}
else
{
m_left = m_startX;
m_width = currXOrig - m_left;
}
if ( currYOrig <= static_cast<int>(m_startY) )
{
m_top = currYOrig;
m_height = m_startY - m_top;
}
else
{
m_top = m_startY;
m_height = currYOrig - m_top;
}
ClampAllValues();
m_imageSizeChanged = true;
}
else if ( m_rightMBHeld == true )
{
currXOrig = ToOriginal( static_cast<float>(currX) );
currYOrig = ToOriginal( static_cast<float>(currY) );
// Perform some initial calculations to make sure that the
// left and top values are not overflowing
if ( currXOrig + m_offsetX < 0 )
{
m_left = 0;
}
else
{
m_left = currXOrig + m_offsetX;
}
if ( currYOrig + m_offsetY < 0 )
{
m_top = 0;
}
else
{
m_top = currYOrig + m_offsetY;
}
ClampAllValues();
// Ensure we are still within the boundaries
if ( m_left + m_width > m_maxWidth )
{
m_left = m_maxWidth - m_width;
}
else if ( m_left + m_width < m_width )
{
m_left = 0;
}
if ( m_top + m_height > m_maxHeight )
{
m_top = m_maxHeight - m_height;
}
else if ( m_top + m_height < m_height )
{
m_top = 0;
}
m_imageSizeChanged = true;
}
else
{
ClipPoint( &currX, &currY );
currXOrig = ToOriginal( static_cast<float>(currX) );
currYOrig = ToOriginal( static_cast<float>(currY) );
}
// Store the current cursor coordinates
m_currX = currXOrig;
m_currY = currYOrig;
queue_draw();
return true;
}
void Format7DrawingArea::UpdateSettings( Format7Info* pFmt7Info, Format7ImageSettings* pImageSettings )
{
// Maximum resolution
m_maxWidth = pFmt7Info->maxWidth;
m_maxHeight = pFmt7Info->maxHeight;
// Step sizes
m_offsetHStepSize = pFmt7Info->offsetHStepSize;
m_offsetVStepSize = pFmt7Info->offsetVStepSize;
m_imageHStepSize = pFmt7Info->imageHStepSize;
m_imageVStepSize = pFmt7Info->imageVStepSize;
m_left = pImageSettings->offsetX;
m_top = pImageSettings->offsetY;
m_width = pImageSettings->width;
m_height = pImageSettings->height;
queue_draw();
}
void Format7DrawingArea::UpdateSettings( GigEImageSettingsInfo* pImageInfo, GigEImageSettings* pImageSettings )
{
// Maximum resolution
m_maxWidth = pImageInfo->maxWidth;
m_maxHeight = pImageInfo->maxHeight;
// Step sizes
m_offsetHStepSize = pImageInfo->offsetHStepSize;
m_offsetVStepSize = pImageInfo->offsetVStepSize;
m_imageHStepSize = pImageInfo->imageHStepSize;
m_imageVStepSize = pImageInfo->imageVStepSize;
m_left = pImageSettings->offsetX;
m_top = pImageSettings->offsetY;
m_width = pImageSettings->width;
m_height = pImageSettings->height;
queue_draw();
}
unsigned int Format7DrawingArea::ClampValue( unsigned int inputVal, unsigned int stepSize )
{
if ( inputVal % stepSize != 0 )
{
return inputVal - (inputVal % stepSize);
}
else
{
return inputVal;
}
}
void Format7DrawingArea::ClampAllValues()
{
m_left = ClampValue( m_left, m_offsetHStepSize );
m_top = ClampValue( m_top, m_offsetVStepSize );
m_width = ClampValue( m_width, m_imageHStepSize );
m_height = ClampValue( m_height, m_imageVStepSize );
}
void Format7DrawingArea::ClipPoint( gdouble* x, gdouble* y )
{
// Get window size
int width;
int height;
get_window()->get_size( width, height );
if ( *x < 0 )
{
*x = 0;
}
else if ( *x > width )
{
*x = width;
}
if ( *y < 0 )
{
*y = 0;
}
else if ( *y > height )
{
*y = height;
}
}
float Format7DrawingArea::ToScaled( int original )
{
return original / m_previewScale;
}
int Format7DrawingArea::ToOriginal( float scaled )
{
return static_cast<int>(scaled * m_previewScale);
}
}
| [
"[email protected]"
] | |
013e5d9fcf18c0d83a43c6e0b9c0e65ed2e0ea1f | 9e6844d984c81fcd002c81452b5648585b90abaa | /tests/test.cpp | a5560119ab97c0066169990afc3d87d4bf7e9579 | [] | no_license | siriusbetta/cpp_connector | 5cc0edd8388dc74af9b48e4f7086ca1d54f9521d | ea13cfd9993b2d087ed443472af5c5355db760a1 | refs/heads/master | 2021-07-03T18:04:44.967981 | 2017-09-26T14:33:33 | 2017-09-26T14:33:33 | 104,113,909 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 375 | cpp | #define CATCH_CONFIG_MAIN
#include <../include/Catch/include/catch.hpp>
unsigned int Factorial( unsigned int number)
{
return number <= 1 ? number : Factorial(number - 1) * number;
}
TEST_CASE( "Factorial are computed", "[factorial]")
{
REQUIRE( Factorial(1) == 1 );
REQUIRE( Factorial(2) == 2 );
REQUIRE( Factorial(3) == 6 );
REQUIRE( Factorial(10) == 3628800);
}
| [
"[email protected]"
] | |
513eede9c8b5ce0e2cb0c3edec392634932be424 | 4a6e20a36f5b6b7fa34fdb2c465969e3425d67c0 | /VulkanProject/Utilities.h | c0f12445ccfee201ee77de1edc8dc2f3880e0224 | [] | no_license | axsaucedo/VulkanWrapper | 0aec4b4839357bb3667f8dddb05f3c9a19cdddd1 | 42a244db8fef3fdf99ea7a5b80a5420881194bff | refs/heads/master | 2022-11-23T18:43:14.420896 | 2020-07-28T08:16:34 | 2020-07-28T08:16:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,747 | h | #pragma once
#include <fstream>
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
const int MAX_FRAME_DRAWS = 2;
const int MAX_OBJECTS = 20;
const std::vector<const char*> deviceExtensions = {
VK_KHR_SWAPCHAIN_EXTENSION_NAME
};
struct Vertex
{
glm::vec3 pos; // Vertex position (x, y, z)
glm::vec3 col; // Vertex colour (r, g, b)
glm::vec2 tex; // Texture coords (u, v)
};
// Indices (locations) of queue families (if they exist at all)
struct QueueFamilyIndices {
int graphicsFamily = -1; // Location of Graphics Queue Family
int presentationFamily = -1; // Location of presentation queue family
// Check if queue families are valid
bool isValid() {
return graphicsFamily >= 0 && presentationFamily >= 0;
}
};
struct SwapchainDetails {
VkSurfaceCapabilitiesKHR surfaceCapabilities; // Surface properties, e.g. image size/extent
std::vector<VkSurfaceFormatKHR> formats; // Surface image formats e.g. RGBA and size of each color
std::vector<VkPresentModeKHR> presentationModes; // How images should be presented to screen
};
struct SwapchainImage {
VkImage image;
VkImageView imageView;
};
static std::vector<char> readFile(const std::string& filename) {
// OPen stream from given file
// std::ios::binary telsl stream to read file as binary
// std::ios::ate tells stream to start reading from end of file
std::ifstream file(filename, std::ios::binary | std::ios::ate);
// Check if file stream successfully opened
if (!file.is_open()) {
throw std::runtime_error("Failed to open a file!");
}
// Get current read position and use to resize file buffer
size_t fileSize = (size_t)file.tellg();
std::vector<char> fileBuffer(fileSize);
// Move read position (seek to) the start of the file
file.seekg(0);
// Read the file data into the buffer (stream "filesize" in total)
file.read(fileBuffer.data(), fileSize);
// Close stream
file.close();
return fileBuffer;
}
static uint32_t findMemoryTypeIndex(VkPhysicalDevice physicalDevice, uint32_t allowedTypes, VkMemoryPropertyFlags properties)
{
// Get properties of physical device memory
VkPhysicalDeviceMemoryProperties memoryProperties;
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memoryProperties);
for (uint32_t i = 0; i < memoryProperties.memoryTypeCount; i++) {
// Currently we are checking if we are aligned to the current allowed type
// ie 1 would be 0001 and if i is 2, then we'd see the 1 shifted into 0100
// This means that we would be comparing the specific allowed type with the current one
if ((allowedTypes & (1 << i)) // Index of memory type must match corresponding bit in allowed types
&& (memoryProperties.memoryTypes[i].propertyFlags & properties) == properties) // Desired property flags are exactly the same as properties flag
{
// This memory type is valid so return its index
return i;
}
}
throw std::runtime_error("No memory type index found");
}
static void createBuffer(
VkPhysicalDevice physicalDevice,
VkDevice device,
VkDeviceSize bufferSize,
VkBufferUsageFlags bufferUsage,
VkMemoryPropertyFlags bufferProperties,
VkBuffer* buffer,
VkDeviceMemory* bufferMemory) {
// -- Create Vertex buffer
// Information to create a buffer (doesn't include assigning memory)
VkBufferCreateInfo bufferInfo = {};
bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
bufferInfo.size = bufferSize; // Size of buffer (size of 1 vertex * number of vertices)
bufferInfo.usage = bufferUsage; // Multiple types of buffers possible
bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; // Similar to sawp chain images, can share vertex buffers
VkResult result = vkCreateBuffer(device, &bufferInfo, nullptr, buffer);
if (result != VK_SUCCESS) {
throw std::runtime_error("Failed to create a vertex buffer");
}
// Get buffer memory requirements
VkMemoryRequirements memRequirements;
vkGetBufferMemoryRequirements(device, *buffer, &memRequirements);
// Allocate memory to buffer
VkMemoryAllocateInfo memoryAllocInfo = {};
memoryAllocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
memoryAllocInfo.allocationSize = memRequirements.size;
memoryAllocInfo.memoryTypeIndex = findMemoryTypeIndex(physicalDevice, memRequirements.memoryTypeBits, // Index of memory type on physical device that has required bit flags
bufferProperties); // VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT: CPU can interact with memory. VK_MEMORY_PROERTY_HOST_COHERENT_BIT: allows placement of data straight into buffer after mapping (otherwise would have to specify manually)
// Allocate memory to vkDeviceMemory
result = vkAllocateMemory(device, &memoryAllocInfo, nullptr, bufferMemory);
if (result != VK_SUCCESS) {
throw std::runtime_error("Failed to allocate vertext buffer memory");
}
// Bind the buffer into the memory to given vertex buffer
vkBindBufferMemory(device, *buffer, *bufferMemory, 0);
}
static VkCommandBuffer beginCommandBuffer(VkDevice device, VkCommandPool commandPool) {
// Command buffer to hold trasnfer commands
VkCommandBuffer commandBuffer;
// Command buffer details
VkCommandBufferAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandPool = commandPool;
allocInfo.commandBufferCount = 1;
// Allocate command buffer from pool
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
// Info to begin the command buffer recod
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; // We're only use the comand buffer once, so set i for one time submt
// Begin recording transfer commands
vkBeginCommandBuffer(commandBuffer, &beginInfo);
return commandBuffer;
}
static void endAndSubmitCommandBuffer(VkDevice device, VkCommandPool commandPool, VkQueue queue, VkCommandBuffer commandBuffer) {
// End commands
vkEndCommandBuffer(commandBuffer);
// Queue submission information
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
// Submit transfer command
// Because we don't have many meshes we can have a simple wait for queue to be done (instead of setting the fences/semaphores)
vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE);
vkQueueWaitIdle(queue);
// Free temporary command buffer back to pool
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
static void copyBuffer(
VkDevice device,
VkQueue transferQueue,
VkCommandPool transferCommandPool,
VkBuffer srcBuffer,
VkBuffer dstBuffer,
VkDeviceSize bufferSize)
{
// Create buffer
VkCommandBuffer transferCommandBuffer = beginCommandBuffer(device, transferCommandPool);
// Region of data to copy from and to
VkBufferCopy bufferCopyRegion = {};
bufferCopyRegion.srcOffset = 0; // Copy everything from the start of the first buffer
bufferCopyRegion.dstOffset = 0; // Copy everything to the start of the second buffer
bufferCopyRegion.size = bufferSize;
// Command to copy src buffer to dst buffer
vkCmdCopyBuffer(transferCommandBuffer, srcBuffer, dstBuffer, 1, &bufferCopyRegion);
// End and submit buffer to dst buffer
endAndSubmitCommandBuffer(device, transferCommandPool, transferQueue, transferCommandBuffer);
}
static void copyImageBuffer(VkDevice device, VkQueue transferQueue, VkCommandPool transferCommandPool,
VkBuffer srcBuffer, VkImage dstImage, uint32_t width, uint32_t height) {
// Create buffer
VkCommandBuffer transferCommandBuffer = beginCommandBuffer(device, transferCommandPool);
VkBufferImageCopy imageRegion = {};
imageRegion.bufferOffset = 0; // Offset into data
imageRegion.bufferRowLength = 0; // Row length of data to calculate data spacing
imageRegion.bufferImageHeight = 0; // Image height to calculate data spacing
imageRegion.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; // Which aspect of image to copy
imageRegion.imageSubresource.mipLevel = 0; // Mipmap level to copy
imageRegion.imageSubresource.baseArrayLayer = 0; // Starting array layer if there is array
imageRegion.imageSubresource.layerCount = 1; // Number of layers to start copy starting at baseArrayLayer
imageRegion.imageOffset = { 0, 0, 0 }; // Offset into image as opposed to raw data in bufferOffset
imageRegion.imageExtent = { width, height, 1 };
// Copy buffer to given image
vkCmdCopyBufferToImage(transferCommandBuffer, srcBuffer, dstImage,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &imageRegion);
// End and submit buffer to dst buffer
endAndSubmitCommandBuffer(device, transferCommandPool, transferQueue, transferCommandBuffer);
}
static void transitionImageLayout(VkDevice device, VkQueue queue,
VkCommandPool commandPool, VkImage image, VkImageLayout oldLayout, VkImageLayout newLayout) {
// Create buffer
VkCommandBuffer commandBuffer = beginCommandBuffer(device, commandPool);
VkImageMemoryBarrier imageMemoryBarrier = {};
imageMemoryBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
imageMemoryBarrier.oldLayout = oldLayout; // Layout to transition from
imageMemoryBarrier.newLayout = newLayout; // Layout to transition to
imageMemoryBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; // Queue family to trans
imageMemoryBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
imageMemoryBarrier.image = image;
imageMemoryBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; // ASpect of image being altered
imageMemoryBarrier.subresourceRange.baseMipLevel = 0; // Firsst mip level to start alteations on
imageMemoryBarrier.subresourceRange.levelCount = 1; // Number of mip levels to start from base
imageMemoryBarrier.subresourceRange.baseArrayLayer = 0; // First layer to start alterations on
imageMemoryBarrier.subresourceRange.layerCount = 1; // Number of layers to alter starting from baseArrayLayer
VkPipelineStageFlags srcStage;
VkPipelineStageFlags dstStage;
// If transitioning from new image to image ready to receive data do the following if statement
if (oldLayout == VK_IMAGE_LAYOUT_UNDEFINED && newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) {
imageMemoryBarrier.srcAccessMask = 0; // Memory stage transition must happen after this stage (currently set to 0 meaning it doens't matter)
imageMemoryBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; // THis is the access mask that we want to ensure the transition happens before
srcStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
dstStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
}
// If transitioning from transfer detination to shader readable
else if (oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL && newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) {
imageMemoryBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
imageMemoryBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
srcStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
dstStage = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
}
vkCmdPipelineBarrier(
commandBuffer,
srcStage, dstStage, // pipeline stages (match to src and dst access masks just above)
0, // Dependency flags
0, nullptr, // Memory barrier count + data
0, nullptr, // Buffer memory barrier count + data
1, &imageMemoryBarrier // Image memory barrier count + data
);
// End and submit buffer to dst buffer
endAndSubmitCommandBuffer(device, commandPool, queue, commandBuffer);
}
| [
"[email protected]"
] | |
61b9d2a7d8ec3cc44a705922c59a4a5e05adfe49 | 050b2e7566af61eba7983e2a38a32c34c48b07bb | /balancer/service/center/src/handle/server/SyncServiceRsp.cc | ee65a35499c3935512e916a4dba2418003760d5a | [] | no_license | coolulu/balancer | 2e4084f57ad57c9613e5bc96f3d550d84360d9be | 2d214dcefb149ba60622b035e280b2ee7a2958bb | refs/heads/master | 2021-06-26T20:43:30.713616 | 2019-02-13T13:49:20 | 2019-02-13T13:49:20 | 132,157,585 | 1 | 0 | null | 2018-07-22T02:40:28 | 2018-05-04T15:28:11 | C++ | UTF-8 | C++ | false | false | 1,214 | cc | #include "SyncServiceRsp.h"
#include "log/Log.h"
SyncServiceRsp::SyncServiceRsp(Proc& proc,
const muduo::net::TcpConnectionPtr& conn,
PacketPtr& packet_ptr,
muduo::Timestamp time)
: _proc(proc),
_conn(conn),
_packet_ptr(packet_ptr),
_time(time)
{
}
SyncServiceRsp::~SyncServiceRsp()
{
}
void SyncServiceRsp::handle(const center::CenterMsg& msg)
{
const center::SyncServiceReq& req = msg.sync_service_req();
B_LOG_INFO << "conf_update_time=" << req.conf_update_time();
std::string conf_json;
unsigned long long update_time = _proc._sc.get_config_derivative().update_time;
if(update_time != req.conf_update_time())
{
conf_json = _proc._sc.map_to_json();
B_LOG_INFO << "update update_time=" << update_time
<< ", conf_json=" << conf_json;
}
else
{
B_LOG_INFO << "not update conf_json";
}
PacketPtr packet_ptr_rsp(new Packet(_packet_ptr->_from_service_id, 0, _packet_ptr->_app_id, _packet_ptr->_app_version, _packet_ptr->_conn_seq_id, _packet_ptr->_msg_seq_id));
CenterStack::SyncServiceRsp(packet_ptr_rsp->_body,
common::SUCCESS,
"",
update_time,
conf_json);
_proc._tcp_server.send_msg(_conn, packet_ptr_rsp);
}
| [
"[email protected]"
] | |
5c5cd8e873b497912a17077f1049a73930ace82a | 898c4e7e2c2e4024f7376da729fec0c9aa694e02 | /C_Algorithm/chapter01/Q18.cpp | 25d52a990dbf25cb8ddb6510d2ee876c6fd319b8 | [] | no_license | blue-monkey0/C | f847088563947ff305ce01736d85a385b8f1903f | 8b859b26c0d5f7d68cc01eec18d17579fa4521a9 | refs/heads/main | 2023-02-23T16:27:01.242229 | 2021-01-29T00:29:16 | 2021-01-29T00:29:16 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 402 | cpp | #include <stdio.h>
void nrpira(int n) {
int i, j;
for (i = 1; i <= n; i++) {
for (j = 1; j <= i - 1; j++)
putchar(' ');
for (j = 1; j <= (n - i) * 2 + 1; j++)
printf("%d", i % 10);
putchar('\n');
}
}
int main(void) {
int n;
puts("n단의 숫자 피라미드를 출력하겠습니다.");
do {
printf("몇 단? : "); scanf_s("%d", &n);
} while (n <= 0);
nrpira(n);
return 0;
} | [
"[email protected]"
] | |
372cda4d3001bc77956d7874d8c9b11ca960ecc4 | 82886772b5b5a201979112790fe38b93755f810b | /src/Grid.cpp | 918f1c06a83e19e9e4a3a18e9dd540ced8b1baa5 | [] | no_license | wnguatem/Simple3DViewer | 49fbcd8d2d1f749a06ea1db6c926b2863e9d72c1 | 87b2ff8fa357bc11272c50c9f9ccdeceb157b996 | refs/heads/master | 2021-01-18T22:33:33.447227 | 2016-02-04T16:54:38 | 2016-02-04T16:54:38 | 32,938,923 | 5 | 1 | null | 2016-06-01T17:50:14 | 2015-03-26T16:27:54 | C++ | UTF-8 | C++ | false | false | 4,351 | cpp | #include "Grid.h"
#include "Game.h"
#include "GameException.h"
#include "Camera.h"
#include "ColorHelper.h"
#include "VectorHelper.h"
#include "Utility.h"
#include "VertexDeclarations.h"
using namespace glm;
namespace Library
{
//RTTI_DEFINITIONS(Grid)
const GLuint Grid::DefaultSize = 50;
const GLuint Grid::DefaultScale = 500;
const vec4 Grid::DefaultColor = vec4(0.961f, 0.871f, 0.702f, 1.0f);
Grid::Grid(Game& game, Camera& camera)
: DrawableGameComponent(game), mVertexArrayObject(0), mVertexBuffer(0),
mPosition(Vector3Helper::Zero), mSize(DefaultSize), mScale(DefaultScale), mColor(DefaultColor),
mWorldMatrix(), mVertexCount(0), mContentFolder(game.getGameContentFolder())
{
mCamera = &camera;
}
Grid::Grid(Game& game, Camera& camera, GLuint size, GLuint scale, const vec4& color)
: DrawableGameComponent(game), mVertexArrayObject(0), mVertexBuffer(0),
mPosition(Vector3Helper::Zero), mSize(size), mScale(scale), mColor(color), mWorldMatrix(), mContentFolder(game.getGameContentFolder())
{
mCamera = &camera;
}
Grid::~Grid()
{
glDeleteBuffers(1, &mVertexBuffer);
glDeleteVertexArrays(1, &mVertexArrayObject);
}
const vec3& Grid::Position() const
{
return mPosition;
}
const vec4& Grid::Color() const
{
return mColor;
}
const GLuint Grid::Size() const
{
return mSize;
}
const GLuint Grid::Scale() const
{
return mScale;
}
void Grid::SetPosition(const vec3& position)
{
mPosition = position;
mWorldMatrix = translate(mat4(), mPosition);
}
void Grid::SetPosition(float x, float y, float z)
{
mPosition = vec3(x, y, z);
mWorldMatrix = translate(mat4(), mPosition);
}
void Grid::SetColor(const vec4& color)
{
mColor = color;
InitializeGrid();
}
void Grid::SetSize(GLuint size)
{
mSize = size;
InitializeGrid();
}
void Grid::SetScale(GLuint scale)
{
mScale = scale;
InitializeGrid();
}
void Grid::Initialize()
{
//SetCurrentDirectory(Utility::ExecutableDirectory().c_str());
// Build the shader program
std::vector<ShaderDefinition> shaders;
shaders.push_back(ShaderDefinition(GL_VERTEX_SHADER, mContentFolder + "/BasicEffect.vert"));
shaders.push_back(ShaderDefinition(GL_FRAGMENT_SHADER, mContentFolder + "/BasicEffect.frag"));
mShaderProgram.BuildProgram(shaders);
InitializeGrid();
// Create the vertex array object
glGenVertexArrays(1, &mVertexArrayObject);
mShaderProgram.Initialize(mVertexArrayObject);
glBindVertexArray(0);
}
void Grid::Draw(const GameTime& gameTime)
{
glBindVertexArray(mVertexArrayObject);
glBindBuffer(GL_ARRAY_BUFFER, mVertexBuffer);
mShaderProgram.Use();
mat4 wvp = mCamera->ViewProjectionMatrix() * mWorldMatrix;
mShaderProgram.WorldViewProjection() << wvp;
glLineWidth(4);
glDrawArrays(GL_LINES, 0, mVertexCount);
glBindVertexArray(0);
}
void Grid::InitializeGrid()
{
mVertexCount = (mSize + 1) * 4;
//std::unique_ptr<VertexPositionColor> vertexData(new VertexPositionColor[mVertexCount]);
//VertexPositionColor* vertices = vertexData.get();
//VertexPositionColor rrr[mVertexCount];
//VertexPositionColor *vertices = new VertexPositionColor();
//std::vector<VertexPositionColor> vertices(mVertexCount);
std::vector<VertexPositionColor> vertices(mVertexCount);
float adjustedScale = mScale * 0.1f;
float maxPosition = mSize * adjustedScale / 2;
for (unsigned int i = 0, j = 0; i < mSize + 1; i++, j = 4 * i)
{
float position = maxPosition - (i * adjustedScale);
// Vertical line
vertices[j] = VertexPositionColor(vec4(position, 0.0f, maxPosition, 1.0f), mColor);
vertices[j + 1] = VertexPositionColor(vec4(position, 0.0f, -maxPosition, 1.0f), mColor);
// Horizontal line
vertices[j + 2] = VertexPositionColor(vec4(maxPosition, 0.0f, position, 1.0f), mColor);
vertices[j + 3] = VertexPositionColor(vec4(-maxPosition, 0.0f, position, 1.0f), mColor);
}
glDeleteBuffers(1, &mVertexBuffer);
mShaderProgram.CreateVertexBuffer(reinterpret_cast<VertexPositionColor*> (vertices.data()), mVertexCount, mVertexBuffer);
// mShaderProgram.CreateVertexBuffer(vertices, mVertexCount, mVertexBuffer);
// glDeleteBuffers(1, &mVertexBuffer);s
//delete vertices;
}
} | [
"[email protected]"
] | |
a8a67ec51302ad45b4f4eb4106a419e95b7cb259 | 220529721e151c6cc088ebecf4d3c19fd4716df3 | /AtCoder/abc157/C.cpp | 7f0a5afc11a610f215b9c0373fcd6b498f835b68 | [
"MIT"
] | permissive | jahid-coder/competitive-programming | baa2311796e3ffad3ded4789e43f4f37b95673ef | e7878de2445019c916404238180959dc9308ed4a | refs/heads/master | 2023-08-26T10:13:57.816451 | 2021-10-18T04:26:32 | 2021-10-18T04:26:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,307 | cpp | /****************************************************
* Template for coding contests *
* Author : Sanjeev Sharma *
* Email : [email protected] *
*****************************************************/
#pragma GCC optimize ("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize ("unroll-loops")
#pragma GCC optimize("no-stack-protector,fast-math")
#pragma GCC target ("sse4")
#pragma comment(linker, "/stack:200000000")
#include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#define deb(x) cout << #x << " is " << x << "\n";
using namespace std;
using namespace __gnu_pbds;
const double PI = 2 * acos(0.0);
const long long INF = 1e18L + 5;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, m, s, c;
cin >> n >> m;
vector<int> num(n, -1);
while (m--) {
cin >> s >> c;
if (num[--s] != -1 && num[s] != c || n > 1 && !s && !c) {
cout << -1 << '\n';
return 0;
}
num[s] = c;
}
for (int i = 0; i < n; ++i)
cout << (num[i] == -1 ? (n > 1 && !i) : num[i]);
cout << '\n';
return 0;
}
| [
"[email protected]"
] | |
bc1fd59320df8de2825bb16f58c4b2428e93270d | 5e6637b14fa372049196b4fdbea0bd03ef6180cb | /oj题目/其他人/李春阳/P1058(S9789).cpp | 22593aa107f91cdb768df60558a128a8085ee91f | [] | no_license | dangfugui/note-C | de1d9ad34b7ad5e804f41093a6fade408ac56ef5 | 0cfce2b3f06749312ef22e965bf29f6ed1783f0a | refs/heads/master | 2020-06-23T13:41:00.370822 | 2016-09-10T14:24:26 | 2016-09-10T14:24:26 | 67,228,867 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 606 | cpp | #include"iostream"
using namespace std;
#include"cstring"
int main ()
{
int a,b;
cin>>a>>b;
string x[10002];
string y[1002];
for(int i=0;i<a;i++)
{
cin>>x[i];
}
for(int j=0;j<b;j++)
{
cin>>y[j];
}
for(int k=0;k<b;k++)
{
int q=0;
for(int l=0;l<a;l++)
{
if(y[k]==x[l])
{
cout<<"YES"<<endl;
break;
}
else
q++;
if(q==a)
cout<<"NO"<<endl;
}
}
return 0;
}
| [
"[email protected]"
] | |
0d8e2320247f371fe294586c45ef7084544ba93e | 7eae27dba7482faa734cfaea2b566f40ee938e86 | /PostMidsemLab_3/Black_White.cpp | 4976366c2c07f252d8bd63261211a54fb7bb84f7 | [] | no_license | anshumankr001/CS204 | a4da12e984f61df5bba5bebb1c79db8714530ec5 | efe611277e79fdd15daff1512b98dcff51f855af | refs/heads/master | 2020-06-28T20:34:20.914439 | 2019-11-14T04:51:43 | 2019-11-14T04:51:43 | 200,335,114 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,959 | cpp | #include <bits/stdc++.h>
#define f(i, a, b) for(int i=a; i<b; i++)
using namespace std;
int visited[10000][10000];
int input[10000][10000];
int COUNT;
bool is_valid(int, int, int, int, int);
void BFS(int, int, int, int, int, int);
void reset_visited(int, int);
void func(int, int);
int main()
{
int n, m, k, a, b;
cin>>n>>m>>k;
while(k--)
{
cin>>a>>b;
input[a-1][b-1] = 1;
}
func(n, m);
return 0;
}
bool is_valid(int x, int y, int c, int n, int m)
{
if (x < n && y < m && x >= 0 && y >= 0)
{
if (visited[x][y] == false && input[x][y] == c) return true;
else return false;
}
else return false;
}
void BFS(int x, int y, int i, int j, int n, int m)
{
if (x != y) return;
visited[i][j] = 1;
COUNT++;
int x_move[] = { 0, 0, 1, -1 };
int y_move[] = { 1, -1, 0, 0 };
f(u, 0, 4)
if (is_valid(i + y_move[u], j + x_move[u], x, n, m))
BFS(x, y, i + y_move[u], j + x_move[u], n, m);
}
void reset_visited(int n, int m)
{
f(i, 0, n)
{
f(j, 0, m) visited[i][j] = 0;
}
}
void func(int n, int m)
{
int current_max = INT_MIN, x;
f(i, 0, n)
{
f(j, 0, m)
{
if(input[i][j] == 1)
{
reset_visited(n, m);
COUNT = 0;
if (j + 1 < m) BFS(input[i][j], input[i][j + 1], i, j, n, m);
if (COUNT >= current_max)
{
current_max = COUNT;
x = input[i][j];
}
reset_visited(n, m);
COUNT = 0;
if (i + 1 < n) BFS(input[i][j], input[i + 1][j], i, j, n, m);
if (COUNT >= current_max)
{
current_max = COUNT;
x = input[i][j];
}
}
}
}
if(current_max == 0) current_max++;
cout<<current_max<<endl;
}
| [
"[email protected]"
] | |
6e1dd40574260400141e45f94645e47eb64b3d86 | d1f3fd80b11190ac54f0dbcb5366c05e855d2d61 | /ameba_tools_macosx/tools/macosx/src/postbuild_img2_arduino_macosx.cpp | 8a5a7dd8fa2f2e6725e583dbd2b081e5545f78c1 | [] | no_license | DistyDevice/Arduino | 14c5f1dfd03d096ad29f6f221776d00eca845c18 | cf5a864ee9011da6c294bebbf38167b2ded6dc50 | refs/heads/master | 2022-04-06T06:38:53.801243 | 2020-03-03T03:42:24 | 2020-03-03T03:42:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,092 | cpp | /*
Compile command:
g++ -o postbuild_img2_arduino_macosx tools/macosx/src/postbuild_img2_arduino_macosx.cpp
*/
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <unistd.h>
#include <vector>
using namespace std;
int main(int argc, char *argv[]) {
int ret = 0;
stringstream cmdss;
string cmd, line, msg;
vector<string> lines;
vector<string>::iterator iter;
string path_tool;
string path_arm_none_eabi_gcc;
string path_symbol_black_list;
string bksym;
ifstream fin;
bool has_sdram = false;
string sram_start_st = "", sram_end_st = "", sdram_start_st = "", sdram_end_st = "";
unsigned int sram_start = 0, sram_end = 0, sdram_start = 0, sdram_end = 0;
size_t pos;
// 0. change work folder
chdir(argv[1]);
// 1. copy elf application.axf to current folder
cmdss.clear();
cmdss << "cp " << argv[2] << " ./";
getline(cmdss, cmd);
cout << cmd << endl;
system(cmd.c_str());
// 2. remove previous files
cmd = "rm -f application.map";
cout << cmd << endl;
system(cmd.c_str());
cmd = "rm -f application.asm";
cout << cmd << endl;
system(cmd.c_str());
cmd = "rm -f *.bin";
cout << cmd << endl;
system(cmd.c_str());
// 3. generate information files
path_arm_none_eabi_gcc.assign(argv[3]);
cmdss.clear();
cmdss << path_arm_none_eabi_gcc << "arm-none-eabi-nm --numeric-sort application.axf > application.map";
getline(cmdss, cmd);
cout << cmd << endl;
system(cmd.c_str());
fin.open("application.map");
while( getline(fin, line) ) {
lines.push_back(line);
}
fin.close();
cmdss.clear();
cmdss << path_arm_none_eabi_gcc << "arm-none-eabi-objdump -d application.axf > application.asm";
getline(cmdss, cmd);
cout << cmd << endl;
system(cmd.c_str());
// 3.1 check if any forbidden symbols
path_symbol_black_list.assign(argv[4]);
fin.open(path_symbol_black_list.c_str(), ifstream::in);
cout << path_symbol_black_list << endl;
ret = 0;
if (fin) {
while ( !fin.eof() && ret == 0) {
fin >> bksym;
getline(fin, msg);
// check if this symbole appears in the map file
for (iter = lines.begin(); iter != lines.end(); ++iter) {
if ( (iter->find(bksym)) != string::npos ) {
cerr << endl << "ERROR: " << msg << endl << endl;
ret = -1;
break;
}
}
}
}
fin.close();
if (ret != 0) {
return -1;
}
// 4. grep sram and sdram information
for (iter = lines.begin(); iter != lines.end(); ++iter) {
line = *iter;
pos = line.find("__ram_image2_text_start__");
if ( pos != string::npos ) {
sram_start_st = line.substr(0, pos-3);
sram_start = strtol(sram_start_st.c_str(), NULL, 16);
}
pos = line.find("__ram_image2_text_end__");
if ( pos != string::npos ) {
sram_end_st = line.substr(0, pos-3);
sram_end = strtol(sram_end_st.c_str(), NULL, 16);
}
pos = line.find("__sdram_data_start__");
if ( pos != string::npos ) {
sdram_start_st = line.substr(0, pos-3);
sdram_start = strtol(sdram_start_st.c_str(), NULL, 16);
}
pos = line.find("__sdram_data_end__");
if ( pos != string::npos ) {
sdram_end_st = line.substr(0, pos-3);
sdram_end = strtol(sdram_end_st.c_str(), NULL, 16);
}
}
if (sdram_start > 0 && sdram_end > 0) {
has_sdram = true;
}
cout << "sram " << sram_start_st << " ~ " << sram_end_st << endl;
if (has_sdram) {
cout << "sdram " << sdram_start_st << " ~ " << sdram_end_st << endl;
}
// 5. generate image 2 and image 3
cmdss.clear();
cmdss << path_arm_none_eabi_gcc << "arm-none-eabi-objcopy -j .image2.start.table -j .ram_image2.text -j .ram.data -Obinary ./application.axf ./ram_2.bin";
getline(cmdss, cmd);
cout << cmd << endl;
system(cmd.c_str());
if (has_sdram) {
cmdss.clear();
cmdss << path_arm_none_eabi_gcc << "arm-none-eabi-objcopy -j .image3 -j .sdr_data -Obinary ./application.axf ./sdram.bin";
getline(cmdss, cmd);
cout << cmd << endl;
system(cmd.c_str());
}
// 6. fulfill header
cmdss.clear();
cmdss << "./tools/macosx/pick " << sram_start << " " << sram_end << " ram_2.bin ram_2.p.bin body+reset_offset+sig";
getline(cmdss, cmd);
cout << cmd << endl;
system(cmd.c_str());
cmdss.clear();
cmdss << "./tools/macosx/pick " << sram_start << " " << sram_end << " ram_2.bin ram_2.ns.bin body+reset_offset";
getline(cmdss, cmd);
cout << cmd << endl;
system(cmd.c_str());
if (has_sdram) {
cmdss.clear();
cmdss << "./tools/macosx/pick " << sdram_start << " " << sdram_end << " sdram.bin ram_3.p.bin body+reset_offset";
getline(cmdss, cmd);
cout << cmd << endl;
system(cmd.c_str());
}
// 7. prepare image 1
cmd = "cp bsp/image/ram_1.p.bin ./";
cout << cmd << endl;
system(cmd.c_str());
cmd = "./tools/macosx/padding 44k 0xFF ram_1.p.bin";
cout << cmd << endl;
system(cmd.c_str());
// 8. generate ram_all.bin
if (has_sdram) {
cmd = "cat ram_1.p.bin ram_2.p.bin ram_3.p.bin > ram_all.bin";
cout << cmd << endl;
system(cmd.c_str());
cmd = "cat ram_2.ns.bin ram_3.p.bin > ota.bin";
cout << cmd << endl;
system(cmd.c_str());
} else {
cmd = "cat ram_1.p.bin ram_2.p.bin > ram_all.bin";
cout << cmd << endl;
system(cmd.c_str());
cmd = "cat ram_2.ns.bin > ota.bin";
cout << cmd << endl;
system(cmd.c_str());
}
// 9. add checksum
cmd = "./tools/macosx/checksum ota.bin";
cout << cmd << endl;
system(cmd.c_str());
return 0;
}
| [
"[email protected]"
] | |
bb8402d568064b70e1536b152e54c902578f2699 | d7c94f4a713aaf0fbb3dbb9b56c9f6945e0479c1 | /URI Online Judge/uri2309.cpp | e78d5b4d834b7ec294a5f7027494c2e143a8f265 | [] | no_license | fonte-nele/Competitive-Programming | 2dabb4aab6ce2e6dc552885464fefdd485f9218c | faf0c6077ae0115f121968f7b70f4d68f9ce922b | refs/heads/master | 2021-06-28T09:24:07.708562 | 2020-12-27T14:45:15 | 2020-12-27T14:45:15 | 193,268,717 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 870 | cpp | #include <cstdio>
int getValue(int n)
{
switch (n)
{
case 4: return 0;
case 5: return 1;
case 6: return 2;
case 7: return 3;
case 12: return 4;
case 11: return 5;
case 13: return 6;
case 1: return 7;
case 2: return 8;
case 3: return 9;
}
}
bool wins(int a, int b)
{
return getValue(a) >= getValue(b);
}
int main()
{
int n;
scanf("%d", &n);
int a = 0;
int b = 0;
while (n--)
{
int _a = 0;
int _b = 0;
int p, q, r;
int x, y, z;
scanf("%d %d %d %d %d %d", &p, &q, &r, &x, &y, &z);
if (wins(p, x)) _a++; else _b++;
if (wins(q, y)) _a++; else _b++;
if (wins(r, z)) _a++; else _b++;
if (_a > _b) a++;
else b++;
}
printf("%d %d\n", a, b);
return 0;
} | [
"[email protected]"
] | |
7652f2ba92279e36fdf58beeedadbfc28dee8181 | b77326e5dd7afd7ca08019958c924aee6bcba550 | /iBeacon/iBeacon.ino | 00c23bf876b72c7bebfb50fef22f0d468d862d4a | [] | no_license | tmatz/bean-experiments | 950bfe218510214f609140e78cc8640316899993 | 5171b2294ff643d2ed2038b1c49ae348793d8db7 | refs/heads/master | 2021-01-17T15:46:56.502055 | 2016-10-10T08:09:40 | 2016-10-10T08:09:40 | 69,889,562 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 212 | ino | void setup() {
Bean.enableConfigSave(false);
Bean.setAdvertisingInterval(1000);
Bean.setBeaconParameters(0xDEAD, 0xBEEF, 0xCAFE);
Bean.setBeaconEnable(true);
}
void loop() {
Bean.sleep(0xFFFFFFFF);
}
| [
"[email protected]"
] | |
4e3f4b20ee8c0cda628457b83582e40577e02ee7 | 2962f164cecb440ecd905ab9f3cc569c03a01ad5 | /RtspPlayer/assemblies/sunell/include/MultiTripWireAbility.h | 107116e9f0e55f2c5bdb42e2db36d19be682d7f6 | [] | 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 | 28,790 | h | #ifndef _MULTITRIPWIREABILITY_H_
#define _MULTITRIPWIREABILITY_H_
#include "SNPlatOS.h"
#include "DomainConst.h"
#include <string>
/**********************************************************************/
//此处用于控制文件编译字节对齐,拷贝时两行注释间内容需一起拷贝,
//结束处的“#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 MultiTripWireAbility
{
public:
MultiTripWireAbility();
~MultiTripWireAbility();
MultiTripWireAbility& operator=(const MultiTripWireAbility& p_objMultiTripWireAbility);
/***********************************************************************
* 概述:设置提供双绊线(MultiTripWire)功能的智能库的ID
* 输入:
* p_nLibId :智能库ID
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 输入的智能库ID需要跟能力列表的库ID匹配,不然将视为非法的ID,
* 功能无法正常启用。
************************************************************************/
void setLibId(const int p_nLibId);
/***********************************************************************
* 概述:获取提供双绊线(MultiTripWire)功能的智能库的ID
* 输入:
* 无
* 输出:
* 无
* 返回值:
* const int : 当前提供该功能的智能库ID
* 功能正文:
* 返回的库ID是当前设备提供该智能分析功能的库ID
************************************************************************/
const int getLibId() const;
/***********************************************************************
* 概述:设置分析区域能力是否支持
* 输入:
* p_bRegionEnable :是否支持该项能力
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 输入为true : 支持该项能力;
* 输入为false : 不支持该项能力。
************************************************************************/
void setRegionEnable(const bool p_bRegionEnable);
/***********************************************************************
* 概述:获取分析区域能力是否支持
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool : 如果启用,返回true;
* 如果不启用,返回false。
* 功能正文:
* 无
************************************************************************/
const bool getRegionEnable() const;
/***********************************************************************
* 概述:设置支持的分析区域个数
* 输入:
* p_nEdgeNum :分析区域个数
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setEdgeNum(const int p_nEdgeNum);
/***********************************************************************
* 概述:获取支持的分析区域个数
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 支持的分析区域个数
* 功能正文:
* 无
************************************************************************/
const int getEdgeNum() const;
/***********************************************************************
* 概述:设置最多支持的分析区域个数
* 输入:
* p_nMaxRegionNum :最多支持的分析区域个数
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setMaxRegionNum(const int p_nMaxRegionNum);
/***********************************************************************
* 概述:获取最多支持的分析区域个数
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 最多支持的分析区域个数
* 功能正文:
* 无
************************************************************************/
const int getMaxRegionNum() const;
/***********************************************************************
* 概述:设置是否获取详细信息的能力是否支持
* 输入:
* p_bDetailGetEnable :是否支持该能力
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 输入true,支持;
* 输入false,不支持。
************************************************************************/
void setDetailGetEnable(const bool p_bDetailGetEnable);
/***********************************************************************
* 概述:获取是否获取详细信息的能力的是否支持
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool : 如果支持,返回true;
* 如果不支持,返回false。
* 功能正文:
* 无
************************************************************************/
const bool getDetailGetEnable() const;
/***********************************************************************
* 概述:设置双绊线(MultiTripWire)能力是否支持
* 输入:
* p_bEnable :是否支持该项能力
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 输入为true : 支持该项能力;
* 输入为false : 不支持该项能力。
************************************************************************/
void setEnable(const bool p_bEnable);
/***********************************************************************
* 概述:获取双绊线(MultiTripWire)能力是否支持
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool : 如果支持,返回true;
* 如果不支持,返回false。
* 功能正文:
* 无
************************************************************************/
const bool getEnable() const;
/***********************************************************************
* 概述:设置是否支持目标最大尺寸
* 输入:
* p_bMaxTargetSizeEnable :是否支持
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setMaxTargetSizeEnable(const bool p_bMaxTargetSizeEnable);
/***********************************************************************
* 概述:获取是否支持目标最大尺寸
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool :返回true,支持;
* 返回false,不支持。
* 功能正文:
* 无
************************************************************************/
const bool getMaxTargetSizeEnable() const;
/***********************************************************************
* 概述:设置目标最大尺寸的最大值
* 输入:
* p_nMaxTargetSizeMax :目标最大尺寸的最大值
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setMaxTargetSizeMax(const int p_nMaxTargetSizeMax);
/***********************************************************************
* 概述:获取目标最大尺寸的最大值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int :目标最大尺寸的最大值
* 功能正文:
* 无
************************************************************************/
const int getMaxTargetSizeMax() const;
/***********************************************************************
* 概述:设置目标最大尺寸的最小值
* 输入:
* p_nMaxTargetSizeMin :目标最大尺寸的最小值
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setMaxTargetSizeMin(const int p_nMaxTargetSizeMin);
/***********************************************************************
* 概述:获取目标最大尺寸的最小值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int :目标最大尺寸的最小值
* 功能正文:
* 无
************************************************************************/
const int getMaxTargetSizeMin() const;
/***********************************************************************
* 概述:设置目标最大尺寸的单位
* 输入:
* p_pMaxTargetSizeUnit :目标最大尺寸的单位
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
bool setMaxTargetSizeUnit(const char* p_pMaxTargetSizeUnit);
/***********************************************************************
* 概述:获取目标最大尺寸的单位
* 输入:
* 无
* 输出:
* 无
* 返回值:
* string :目标最大尺寸的单位
* 功能正文:
* 无
************************************************************************/
const char* getMaxTargetSizeUnit() const;
/***********************************************************************
* 概述:设置是否支持目标最小尺寸
* 输入:
* p_bMinTargetSizeEnable :是否支持
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setMinTargetSizeEnable(const bool p_bMinTargetSizeEnable);
/***********************************************************************
* 概述:获取是否支持目标最小尺寸
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool :返回true,支持;
* 返回false,不支持。
* 功能正文:
* 无
************************************************************************/
const bool getMinTargetSizeEnable() const;
/***********************************************************************
* 概述:设置目标最小尺寸的最大值
* 输入:
* p_nMinTargetSizeMax :目标最小尺寸的最大值
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setMinTargetSizeMax(const int p_nMinTargetSizeMax);
/***********************************************************************
* 概述:获取目标最小尺寸的最大值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int :目标最小尺寸的最大值
* 功能正文:
* 无
************************************************************************/
const int getMinTargetSizeMax() const;
/***********************************************************************
* 概述:设置目标最小尺寸的最小值
* 输入:
* p_nMinTargetSizeMin :目标最小尺寸的最小值
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setMinTargetSizeMin(const int p_nMinTargetSizeMin);
/***********************************************************************
* 概述:获取目标最小尺寸的最小值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int :目标最小尺寸的最小值
* 功能正文:
* 无
************************************************************************/
const int getMinTargetSizeMin() const;
/***********************************************************************
* 概述:设置目标最小尺寸的单位
* 输入:
* p_pMinTargetSizeUnit :目标最小尺寸的单位
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
bool setMinTargetSizeUnit(const char* p_pMinTargetSizeUnit);
/***********************************************************************
* 概述:获取目标最小尺寸的单位
* 输入:
* 无
* 输出:
* 无
* 返回值:
* string :目标最小尺寸的单位
* 功能正文:
* 无
************************************************************************/
const char* getMinTargetSizeUnit() const;
/***********************************************************************
* 概述:设置是否限定目标大小的能力的支持与否
* 输入:
* p_bTargetSizeConstrainEnable :是否支持该功能
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setTargetSizeConstrainEnable(const bool p_bTargetSizeConstrainEnable);
/***********************************************************************
* 概述:获取是否限定目标大小的能力的支持与否
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool : 支持,返回true;
* 不支持,返回false。
* 功能正文:
* 无
************************************************************************/
const bool getTargetSizeConstrainEnable() const;
/***********************************************************************
* 概述:设置限定目标大小的最大值
* 输入:
* p_nTargetSizeConstrainMin :限定目标大小的最大值
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setTargetSizeConstrainMax(const int p_nTargetSizeConstrainMax);
/***********************************************************************
* 概述:获取限定目标大小的最大值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 限定目标大小的最大值
* 功能正文:
* 无
************************************************************************/
const int getTargetSizeConstrainMax() const;
/***********************************************************************
* 概述:设置限定目标大小的最小值
* 输入:
* p_nTargetSizeConstrainMin :限定目标大小的最小值
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setTargetSizeConstrainMin(const int p_nTargetSizeConstrainMin);
/***********************************************************************
* 概述:获取限定目标大小的最小值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 限定目标大小的最小值
* 功能正文:
* 无
************************************************************************/
const int getTargetSizeConstrainMin() const;
/***********************************************************************
* 概述:设置限定目标大小的单位
* 输入:
* p_nTargetSizeConstrainMin :限定目标大小的单位
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
bool setTargetSizeConstrainUnit(const char* p_pTargetSizeConstrainUnit);
/***********************************************************************
* 概述:获取限定目标大小的单位
* 输入:
* 无
* 输出:
* 无
* 返回值:
* string :限定目标大小的单位
* 功能正文:
* 无
************************************************************************/
const char* getTargetSizeConstrainUnit() const;
/***********************************************************************
* 概述:设置限定目标类型的能力的支持与否
* 输入:
* p_bTargetTypeConstrainEnable :是否支持该能力
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 目标类型指人、车等。
* 如果支持,表示只侦测设置的类型(如人、车等)
************************************************************************/
void setTargetTypeConstrainEnable(const bool p_bTargetTypeConstrainEnable);
/***********************************************************************
* 概述:获取是否支持限定目标类型
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool : 如果支持,返回true;
* 如果不支持,返回false。
* 功能正文:
* 目标类型指人、车等。
************************************************************************/
const bool getTargetTypeConstrainEnable() const;
/***********************************************************************
* 概述:设置目标类型的最大尺寸
* 输入:
* p_nTargetTypeConstrainMin :目标类型的最大尺寸
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 目标类型指人、车等。
************************************************************************/
void setTargetTypeConstrainMax(const int p_nTargetTypeConstrainMax);
/***********************************************************************
* 概述:获取目标类型的最大尺寸
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 目标类型的最大尺寸
* 功能正文:
* 目标类型指人、车等。
************************************************************************/
const int getTargetTypeConstrainMax() const;
/***********************************************************************
* 概述:设置目标类型的最小尺寸
* 输入:
* p_nTargetTypeConstrainMin :目标类型的最小尺寸
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 目标类型指人、车等。
************************************************************************/
void setTargetTypeConstrainMin(const int p_nTargetTypeConstrainMin);
/***********************************************************************
* 概述:获取目标类型的最小尺寸
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 目标类型的最小尺寸
* 功能正文:
* 目标类型指人、车等。
************************************************************************/
const int getTargetTypeConstrainMin() const;
/***********************************************************************
* 概述:设置目标类型尺寸的单位
* 输入:
* p_pTargetTypeConstrainUnit :目标类型尺寸的单位
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 目标类型指人、车等。
************************************************************************/
bool setTargetTypeConstrainUnit(const char* p_pTargetTypeConstrainUnit);
/***********************************************************************
* 概述:设置目标类型尺寸的单位
* 输入:
* 无
* 输出:
* 无
* 返回值:
* string : 目标类型尺寸的单位
* 功能正文:
* 目标类型指人、车等。
************************************************************************/
const char* getTargetTypeConstrainUnit() const;
/***********************************************************************
* 概述:设置限定类型能力的支持与否
* 输入:
* p_bTargetTypeEnable :是否支持限定类型能力
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 支持限定类型,表示支持限定人、车等类型的能力。
************************************************************************/
void setTargetTypeEnable(const bool p_bTargetTypeEnable);
/***********************************************************************
* 概述:获取限定类型能力的支持与否
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool : 返回true,支持该能力;
* 返回false,不支持。
* 功能正文:
* 支持限定类型,表示支持限定人、车等类型的能力。
************************************************************************/
const bool getTargetTypeEnable() const;
/***********************************************************************
* 概述:设置限定类型的尺寸的最大值
* 输入:
* p_nTargetTypeMax :限定类型的尺寸的最大值
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 支持限定类型,表示支持限定人、车等类型的能力。
************************************************************************/
void setTargetTypeMax(const int p_nTargetTypeMax);
/***********************************************************************
* 概述:获取限定类型的尺寸的最大值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 限定类型的尺寸的最大值
* 功能正文:
* 支持限定类型,表示支持限定人、车等类型的能力。
************************************************************************/
const int getTargetTypeMax() const;
/***********************************************************************
* 概述:设置限定类型的尺寸的最小值
* 输入:
* p_nTargetTypeMin :限定类型的尺寸的最小值
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 支持限定类型,表示支持限定人、车等类型的能力。
************************************************************************/
void setTargetTypeMin(const int p_nTargetTypeMin);
/***********************************************************************
* 概述:获取限定类型的尺寸的最小值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 限定类型的尺寸的最小值
* 功能正文:
* 支持限定类型,表示支持限定人、车等类型的能力。
************************************************************************/
const int getTargetTypeMin() const;
/***********************************************************************
* 概述:设置限定类型的尺寸的单位
* 输入:
* p_pTargetTypeUnit :限定类型的尺寸的单位
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 支持限定类型,表示支持限定人、车等类型的能力。
************************************************************************/
bool setTargetTypeUnit(const char* p_pTargetTypeUnit);
/***********************************************************************
* 概述:获取限定类型的尺寸的单位
* 输入:
* 无
* 输出:
* 无
* 返回值:
* string : 限定类型的尺寸的单位
* 功能正文:
* 支持限定类型,表示支持限定人、车等类型的能力。
************************************************************************/
const char* getTargetTypeUnit() const;
/***********************************************************************
* 概述:设置是否支持双绊线的时间间隔的功能
* 输入:
* p_bTimeIntervalEnable :是否支持该项功能。
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setTimeIntervalEnable(const bool p_bTimeIntervalEnable);
/***********************************************************************
* 概述:获取是否支持双绊线的时间间隔的功能
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool : 返回true,支持;
* 返回false,不支持。
* 功能正文:
* 无
************************************************************************/
const bool getTimeIntervalEnable() const;
/***********************************************************************
* 概述:设置双绊线的时间间隔的最小值
* 输入:
* p_nTimeIntervalMin :双绊线的时间间隔的最小值。
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setTimeIntervalMin(const int p_nTimeIntervalMin);
/***********************************************************************
* 概述:获取双绊线的时间间隔的最小值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 双绊线的时间间隔的最小值
* 功能正文:
* 无
************************************************************************/
const int getTimeIntervalMin() const;
/***********************************************************************
* 概述:设置双绊线的时间间隔的最大值
* 输入:
* p_nTimeIntervalMin :双绊线的时间间隔的最大值。
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setTimeIntervalMax(const int p_nTimeIntervalMax);
/***********************************************************************
* 概述:获取双绊线的时间间隔的最大值
* 输入:
* 无
* 输出:
* 无
* 返回值:
* int : 双绊线的时间间隔的最大值
* 功能正文:
* 无
************************************************************************/
const int getTimeIntervalMax() const;
/***********************************************************************
* 概述:设置双绊线的时间间隔的单位
* 输入:
* p_pTimeIntervalUnit :双绊线的时间间隔的单位。
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
bool setTimeIntervalUnit(const char* p_pTimeIntervalUnit);
/***********************************************************************
* 概述:获取双绊线的时间间隔的单位
* 输入:
* 无
* 输出:
* 无
* 返回值:
* string : 双绊线的时间间隔的单位
* 功能正文:
* 无
************************************************************************/
const char* getTimeIntervalUnit() const;
/***********************************************************************
* 概述:设置是否支持双绊线的触发方向设置的功能
* 输入:
* p_bTimeIntervalEnable :是否支持该项功能。
* 输出:
* 无
* 返回值:
* 无
* 功能正文:
* 无
************************************************************************/
void setTriggerDirectionEnable(const bool p_bTriggerDirectionEnable);
/***********************************************************************
* 概述:获取是否支持双绊线的触发方向设置的功能
* 输入:
* 无
* 输出:
* 无
* 返回值:
* bool : 返回true,支持;
* 返回false,不支持。
* 功能正文:
* 无
************************************************************************/
const bool getTriggerDirectionEnable() const;
private:
int m_nLibId;
bool m_bRegionEnable;
int m_nEdgeNum;
int m_nMaxRegionNum;
bool m_bDetailGetEnable;
bool m_bEnable;
bool m_bMaxTargetSizeEnable;
int m_nMaxTargetSizeMax;
int m_nMaxTargetSizeMin;
bool m_bMinTargetSizeEnable;
int m_nMinTargetSizeMax;
int m_nMinTargetSizeMin;
bool m_bTargetSizeConstrainEnable;
int m_nTargetSizeConstrainMax;
int m_nTargetSizeConstrainMin;
bool m_bTargetTypeConstrainEnable;
int m_nTargetTypeConstrainMax;
int m_nTargetTypeConstrainMin;
bool m_bTargetTypeEnable;
int m_nTargetTypeMax;
int m_nTargetTypeMin;
bool m_bTimeIntervalEnable;
int m_nTimeIntervalMin;
int m_nTimeIntervalMax;
bool m_bTriggerDirectionEnable;
char m_pMaxTargetSizeUnit[CONST_INTELLIGENCE_ANALYSE_UNIT_LEN + 1];
char m_pMinTargetSizeUnit[CONST_INTELLIGENCE_ANALYSE_UNIT_LEN + 1];
char m_pTargetSizeConstrainUnit[CONST_INTELLIGENCE_ANALYSE_UNIT_LEN + 1];
char m_pTargetTypeConstrainUnit[CONST_INTELLIGENCE_ANALYSE_UNIT_LEN + 1];
char m_pTargetTypeUnit[CONST_INTELLIGENCE_ANALYSE_UNIT_LEN + 1];
char m_pTimeIntervalUnit[CONST_INTELLIGENCE_ANALYSE_UNIT_LEN + 1];
}_PACKED_1_;
/**********************************************************************/
#ifdef PRAGMA_PACK
#ifdef WIN32
#pragma pack(pop)
#endif
#endif
/**********************************************************************/
#endif //_MULTITRIPWIREABILITY_H_
| [
"[email protected]"
] | |
288e65b6ec463dc190bbb58e70db91ada6ee9663 | 10587620d1875a32090a9145a9f4cf6ed83d54e2 | /天气预报查询系统/WeatherQuery/keybutton.cpp | 2eb1299a21790c9f62434d585849e598e64d86e4 | [] | no_license | zhengzebin525/LINUX-Environmental-programming | 2eab34cfdcc959e92224b2eda696d20907f68fef | 18952913a36e73a3352b4af3dcf8494eac83029a | refs/heads/master | 2020-04-16T04:08:35.759680 | 2019-07-07T14:20:00 | 2019-07-07T14:20:00 | 165,257,064 | 4 | 11 | null | null | null | null | UTF-8 | C++ | false | false | 721 | cpp | #include "keybutton.h"
#include <QApplication>
#include <QKeyEvent>
KeyButton::KeyButton(QWidget *parent):QPushButton(parent)
{
//当按下自己的时候,给自己发一个信号 ,至此自己类中的click_buton()函数
connect(this,SIGNAL(clicked(bool)),this,SLOT(click_button()));
}
void KeyButton::click_button()
{
//整个文件就算俺就本身,所以只要获取自身text,就算所在按钮的text
QString str = this->text();
char keyvale = str.at(0).toLatin1();
//定义按钮事件
QKeyEvent *key = new QKeyEvent(QKeyEvent::KeyPress,keyvale,Qt::NoModifier,str);
//发送事件
QApplication::postEvent(QApplication::focusWidget(),key);
}
| [
"[email protected]"
] | |
20357a8d46bbc68fc3857cc400c07cb69f883b62 | fbc4da93b078c320b064f413ee3721a3f24277af | /OfficeVol2/OptionDlgModule.cpp | 72d42a5839251625842b4bb60ddea540ce5a9b5c | [] | no_license | wyrover/LazyVol | f97f696d12f7f2053a18a81c130afc9f8eee303c | 925df4b1eb1a2405d570a0b59ec58aeb3c1d3c60 | refs/heads/master | 2021-01-20T08:00:16.257356 | 2013-04-24T06:59:35 | 2013-04-24T06:59:35 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 14,927 | cpp | #include "MainHead.h"
#include "OfficeVolModule.h"
#include "OptionDlgModule.h"
OptionDlgModule::OptionDlgModule(HWND parent_hwnd):mParentHwnd(parent_hwnd)
{
}
OptionDlgModule::~OptionDlgModule(void)
{
}
LPCTSTR OptionDlgModule::GetWindowClassName() const
{
return _T("ScanMainForm");
};
void OptionDlgModule::OnFinalMessage(HWND /*hWnd*/)
{
delete this;
};
void OptionDlgModule::Init()
{
CKeyEditUI* tmpEdit = static_cast<CKeyEditUI*>(m_pm.FindControl(_T("OFF_VOLUP")));
assert(tmpEdit);
std::string configStr;
OfficeVolModule::GetInstance()->GetConfigStr("OFF_VOLUP", configStr);
tmpEdit->SetKey(configStr.c_str());
tmpEdit->SetText(configStr.c_str());
mKeyEditVec.push_back(tmpEdit);
tmpEdit = static_cast<CKeyEditUI*>(m_pm.FindControl(_T("OFF_VOLDOWN")));
assert(tmpEdit);
OfficeVolModule::GetInstance()->GetConfigStr("OFF_VOLDOWN", configStr);
tmpEdit->SetKey(configStr.c_str());
tmpEdit->SetText(configStr.c_str());
mKeyEditVec.push_back(tmpEdit);
tmpEdit = static_cast<CKeyEditUI*>(m_pm.FindControl(_T("OFF_VOLON")));
assert(tmpEdit);
OfficeVolModule::GetInstance()->GetConfigStr("OFF_VOLON", configStr);
tmpEdit->SetKey(configStr.c_str());
tmpEdit->SetText(configStr.c_str());
mKeyEditVec.push_back(tmpEdit);
tmpEdit = static_cast<CKeyEditUI*>(m_pm.FindControl(_T("OFF_VOLOFF")));
assert(tmpEdit);
OfficeVolModule::GetInstance()->GetConfigStr("OFF_VOLOFF", configStr);
tmpEdit->SetKey(configStr.c_str());
tmpEdit->SetText(configStr.c_str());
mKeyEditVec.push_back(tmpEdit);
tmpEdit = static_cast<CKeyEditUI*>(m_pm.FindControl(_T("OFF_VOLSELECT_MASTER")));
assert(tmpEdit);
OfficeVolModule::GetInstance()->GetConfigStr("OFF_VOLSELECT_MASTER", configStr);
tmpEdit->SetKey(configStr.c_str());
tmpEdit->SetText(configStr.c_str());
mKeyEditVec.push_back(tmpEdit);
tmpEdit = static_cast<CKeyEditUI*>(m_pm.FindControl(_T("OFF_VOLSELECT_WAVE")));
assert(tmpEdit);
OfficeVolModule::GetInstance()->GetConfigStr("OFF_VOLSELECT_WAVE", configStr);
tmpEdit->SetKey(configStr.c_str());
tmpEdit->SetText(configStr.c_str());
mKeyEditVec.push_back(tmpEdit);
tmpEdit = static_cast<CKeyEditUI*>(m_pm.FindControl(_T("OFF_VOLSELECT_MIC")));
assert(tmpEdit);
OfficeVolModule::GetInstance()->GetConfigStr("OFF_VOLSELECT_MIC", configStr);
tmpEdit->SetKey(configStr.c_str());
tmpEdit->SetText(configStr.c_str());
mKeyEditVec.push_back(tmpEdit);
tmpEdit = static_cast<CKeyEditUI*>(m_pm.FindControl(_T("OFF_OPTION")));
assert(tmpEdit);
OfficeVolModule::GetInstance()->GetConfigStr("OFF_OPTION", configStr);
tmpEdit->SetKey(configStr.c_str());
tmpEdit->SetText(configStr.c_str());
mKeyEditVec.push_back(tmpEdit);
tmpEdit = static_cast<CKeyEditUI*>(m_pm.FindControl(_T("OFF_QUIT")));
assert(tmpEdit);
OfficeVolModule::GetInstance()->GetConfigStr("OFF_QUIT", configStr);
tmpEdit->SetKey(configStr.c_str());
tmpEdit->SetText(configStr.c_str());
mKeyEditVec.push_back(tmpEdit);
mWinStartOpt = static_cast<COptionUI*>(m_pm.FindControl(_T("OFF_WINSTART")));
assert(mWinStartOpt);
OfficeVolModule::GetInstance()->GetConfigStr("OFF_WINSTART", configStr);
if(configStr == "ON")
{
mWinStartOpt->Selected(true);
}
else
{
mWinStartOpt->Selected(false);
}
}
void OptionDlgModule::Notify(TNotifyUI& msg)
{
if(msg.sType == _T("click"))
{
if( msg.pSender->GetName() == _T("cancelbtn") ||
msg.pSender->GetName() == _T("exitbtn"))
{
Close();
return;
}
if( msg.pSender->GetName() == _T("okBtn") )
{
UpdateConfig();
Close();
return;
}
if( msg.pSender->GetName() == _T("applyBtn") )
{
UpdateConfig();
return;
}
}
else if (_tcsicmp(msg.sType, _T("selectchanged")) == 0)
{
CTabLayoutUI* pTabControl = static_cast<CTabLayoutUI*>(m_pm.FindControl(kMainTabCtrl));
CTabLayoutUI* pGTabControl = static_cast<CTabLayoutUI*>(m_pm.FindControl(kGeneralTableCtrl));
if (_tcsicmp(msg.pSender->GetName(), kTabGeneral) == 0)
{
if (pTabControl && pTabControl->GetCurSel() != 0)
{
pTabControl->SelectItem(0);
}
}
else if (_tcsicmp(msg.pSender->GetName(), kTabAbout) == 0)
{
if (pTabControl && pTabControl->GetCurSel() != 1)
{
pTabControl->SelectItem(1);
}
}
else if (_tcsicmp(msg.pSender->GetName(), kGTabKeyboard) == 0)
{
if (pGTabControl && pGTabControl->GetCurSel() != 0)
{
pGTabControl->SelectItem(0);
}
}
else if (_tcsicmp(msg.pSender->GetName(), kGTabCommon) == 0)
{
if (pGTabControl && pGTabControl->GetCurSel() != 1)
{
pGTabControl->SelectItem(1);
}
}
}
}
LRESULT OptionDlgModule::OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
//LONG styleValue = ::GetWindowLong(*this, GWL_STYLE);
//styleValue &= ~WS_CAPTION;
//::SetWindowLong(*this, GWL_STYLE, styleValue | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
m_pm.Init(m_hWnd);
//m_pm.SetTransparent(100);
CDialogBuilder builder;
CControlUI* pRoot = builder.Create(_T("OpSkin.xml"), (UINT)0, this, &m_pm);
ASSERT(pRoot && "Failed to parse XML");
m_pm.AttachDialog(pRoot);
m_pm.AddNotifier(this);
Init();
return 0;
}
LRESULT OptionDlgModule::OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = FALSE;
return 0;
}
LRESULT OptionDlgModule::OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
if(mParentHwnd)
::PostMessage(mParentHwnd, MSG_DISMISS_OPTION, wParam, lParam);
bHandled = FALSE;
return 0;
}
LRESULT OptionDlgModule::OnNcActivate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
if( ::IsIconic(*this) ) bHandled = FALSE;
return (wParam == 0) ? TRUE : FALSE;
}
LRESULT OptionDlgModule::OnNcCalcSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
return 0;
}
LRESULT OptionDlgModule::OnNcPaint(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
return 0;
}
LRESULT OptionDlgModule::OnNcHitTest(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
#if 1
POINT pt; pt.x = GET_X_LPARAM(lParam); pt.y = GET_Y_LPARAM(lParam);
::ScreenToClient(*this, &pt);
RECT rcClient;
::GetClientRect(*this, &rcClient);
if( !::IsZoomed(*this) ) {
RECT rcSizeBox = m_pm.GetSizeBox();
if( pt.y < rcClient.top + rcSizeBox.top ) {
if( pt.x < rcClient.left + rcSizeBox.left ) return HTTOPLEFT;
if( pt.x > rcClient.right - rcSizeBox.right ) return HTTOPRIGHT;
return HTTOP;
}
else if( pt.y > rcClient.bottom - rcSizeBox.bottom ) {
if( pt.x < rcClient.left + rcSizeBox.left ) return HTBOTTOMLEFT;
if( pt.x > rcClient.right - rcSizeBox.right ) return HTBOTTOMRIGHT;
return HTBOTTOM;
}
if( pt.x < rcClient.left + rcSizeBox.left ) return HTLEFT;
if( pt.x > rcClient.right - rcSizeBox.right ) return HTRIGHT;
}
RECT rcCaption = m_pm.GetCaptionRect();
if( pt.x >= rcClient.left + rcCaption.left && pt.x < rcClient.right - rcCaption.right \
&& pt.y >= rcCaption.top && pt.y < rcCaption.bottom ) {
CControlUI* pControl = static_cast<CControlUI*>(m_pm.FindControl(pt));
if( pControl && _tcscmp(pControl->GetClass(), _T("ButtonUI")) != 0 &&
_tcscmp(pControl->GetClass(), _T("OptionUI")) != 0 &&
_tcscmp(pControl->GetClass(), _T("TextUI")) != 0 )
return HTCAPTION;
}
#endif
return HTCLIENT;
}
LRESULT OptionDlgModule::OnSize(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
SIZE szRoundCorner = m_pm.GetRoundCorner();
if( !::IsIconic(*this) && (szRoundCorner.cx != 0 || szRoundCorner.cy != 0) ) {
CDuiRect rcWnd;
::GetWindowRect(*this, &rcWnd);
rcWnd.Offset(-rcWnd.left, -rcWnd.top);
rcWnd.right++; rcWnd.bottom++;
RECT rc = { rcWnd.left, rcWnd.top + szRoundCorner.cx, rcWnd.right, rcWnd.bottom };
HRGN hRgn1 = ::CreateRectRgnIndirect( &rc );
HRGN hRgn2 = ::CreateRoundRectRgn(rcWnd.left, rcWnd.top, rcWnd.right, rcWnd.bottom - szRoundCorner.cx, szRoundCorner.cx, szRoundCorner.cy);
::CombineRgn( hRgn1, hRgn1, hRgn2, RGN_OR );
::SetWindowRgn(*this, hRgn1, TRUE);
::DeleteObject(hRgn1);
::DeleteObject(hRgn2);
}
bHandled = FALSE;
return 0;
}
LRESULT OptionDlgModule::OnMove(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
RECT rcWnd = { 0 };
::GetWindowRect(m_hWnd, &rcWnd );
::SetWindowPos(m_hWnd, HWND_TOPMOST, rcWnd.left, rcWnd.top, rcWnd.right -rcWnd.left,
rcWnd.bottom -rcWnd.top, SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER);
bHandled = FALSE;
return 0;
}
LRESULT OptionDlgModule::OnGetMinMaxInfo(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
#if 0
MONITORINFO oMonitor = {};
oMonitor.cbSize = sizeof(oMonitor);
::GetMonitorInfo(::MonitorFromWindow(*this, MONITOR_DEFAULTTOPRIMARY), &oMonitor);
CDuiRect rcWork = oMonitor.rcWork;
rcWork.Offset(-oMonitor.rcMonitor.left, -oMonitor.rcMonitor.top);
LPMINMAXINFO lpMMI = (LPMINMAXINFO) lParam;
lpMMI->ptMaxPosition.x = rcWork.left;
lpMMI->ptMaxPosition.y = rcWork.top;
lpMMI->ptMaxSize.x = rcWork.right;
lpMMI->ptMaxSize.y = rcWork.bottom;
bHandled = FALSE;
#endif
return 0;
}
LRESULT OptionDlgModule::OnSysCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
#if 0
// 有时会在收到WM_NCDESTROY后收到wParam为SC_CLOSE的WM_SYSCOMMAND
if( wParam == SC_CLOSE ) {
::PostQuitMessage(0L);
bHandled = TRUE;
return 0;
}
BOOL bZoomed = ::IsZoomed(*this);
LRESULT lRes = CWindowWnd::HandleMessage(uMsg, wParam, lParam);
if( ::IsZoomed(*this) != bZoomed ) {
if( !bZoomed ) {
CControlUI* pControl = static_cast<CControlUI*>(m_pm.FindControl(_T("maxbtn")));
if( pControl ) pControl->SetVisible(false);
pControl = static_cast<CControlUI*>(m_pm.FindControl(_T("restorebtn")));
if( pControl ) pControl->SetVisible(true);
}
else {
CControlUI* pControl = static_cast<CControlUI*>(m_pm.FindControl(_T("maxbtn")));
if( pControl ) pControl->SetVisible(true);
pControl = static_cast<CControlUI*>(m_pm.FindControl(_T("restorebtn")));
if( pControl ) pControl->SetVisible(false);
}
}
return lRes;
#endif
return 0;
}
LRESULT OptionDlgModule::HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
LRESULT lRes = 0;
BOOL bHandled = TRUE;
switch( uMsg ) {
case WM_MOVE:
Off_DegMsg("sdfsdfddddddddd");
break;
case WM_CREATE: lRes = OnCreate(uMsg, wParam, lParam, bHandled); break;
case WM_CLOSE: lRes = OnClose(uMsg, wParam, lParam, bHandled); break;
case WM_DESTROY: lRes = OnDestroy(uMsg, wParam, lParam, bHandled); break;
//case WM_NCACTIVATE: lRes = OnNcActivate(uMsg, wParam, lParam, bHandled); break;
//case WM_NCCALCSIZE: lRes = OnNcCalcSize(uMsg, wParam, lParam, bHandled); break;
//case WM_NCPAINT: lRes = OnNcPaint(uMsg, wParam, lParam, bHandled); break;
//case WM_NCHITTEST: lRes = OnNcHitTest(uMsg, wParam, lParam, bHandled); break;
case WM_SIZE: lRes = OnSize(uMsg, wParam, lParam, bHandled); break;
//case WM_MOVE: lRes = OnMove(uMsg, wParam, lParam, bHandled); break;
//case WM_GETMINMAXINFO: lRes = OnGetMinMaxInfo(uMsg, wParam, lParam, bHandled); break;
case WM_SYSCOMMAND: lRes = OnSysCommand(uMsg, wParam, lParam, bHandled); break;
default:
bHandled = FALSE;
}
if( bHandled ) return lRes;
if( m_pm.MessageHandler(uMsg, wParam, lParam, lRes) ) return lRes;
return CWindowWnd::HandleMessage(uMsg, wParam, lParam);
}
CControlUI* OptionDlgModule::CreateControl(LPCTSTR pstrClass)
{
std::string strname(pstrClass);
if(strname == "KEdit")
return new CKeyEditUI;
return NULL;
}
LRESULT OptionDlgModule::UpdateConfig()
{
std::vector<CKeyEditUI*>::iterator iter;
LRESULT ret = 0;
std::string old_config;
for(iter=mKeyEditVec.begin(); iter != mKeyEditVec.end(); ++iter)
{
CKeyEditUI* tmpCtrl = *iter;
assert(tmpCtrl);
ret = OfficeVolModule::GetInstance()->GetConfigStr((LPCTSTR)tmpCtrl->GetName(), old_config);
if(ret)
{
char str[1024] = {0};
_snprintf(str, 1024, "获取配置错误 %s", (LPCTSTR)tmpCtrl->GetName());
Off_Msg(str);
}
if(old_config != tmpCtrl->GetKey())
{
ret = OfficeVolModule::GetInstance()->SetConfigStr(OFF_KEY_UPDATE,
(LPCTSTR)tmpCtrl->GetName(),
tmpCtrl->GetKey());
if(ret)
{
char str[1024] = {0};
_snprintf(str, 1024, "配置错误 %s:%s", (LPCTSTR)tmpCtrl->GetName(),
tmpCtrl->GetKey().c_str());
Off_Msg(str);
}
}
}
ret = OfficeVolModule::GetInstance()->GetConfigStr((LPCTSTR)mWinStartOpt->GetName(), old_config);
if(ret)
{
char str[1024] = {0};
_snprintf(str, 1024, "获取配置错误 %s", (LPCTSTR)mWinStartOpt->GetName());
Off_Msg(str);
ReadConfig();
return OFF_ERROR;
}
if(old_config == "OFF" && mWinStartOpt->IsSelected())
{
ret = OfficeVolModule::GetInstance()->SetConfigStr(OFF_WIN_START,
(LPCTSTR)mWinStartOpt->GetName(),
"ON");
if(ret)
{
char str[1024] = {0};
_snprintf(str, 1024, "配置错误 %s:%s", (LPCTSTR)mWinStartOpt->GetName(),
"ON");
Off_Msg(str);
}
}
else if(old_config == "ON" && !mWinStartOpt->IsSelected())
{
ret = OfficeVolModule::GetInstance()->SetConfigStr(OFF_WIN_START,
(LPCTSTR)mWinStartOpt->GetName(),
"OFF");
if(ret)
{
char str[1024] = {0};
_snprintf(str, 1024, "配置错误 %s:%s", (LPCTSTR)mWinStartOpt->GetName(),
"OFF");
Off_Msg(str);
}
}
ReadConfig();
return 0;
}
LRESULT OptionDlgModule::ReadConfig()
{
std::vector<CKeyEditUI*>::iterator iter;
LRESULT ret = 0;
std::string configStr;
for(iter=mKeyEditVec.begin(); iter != mKeyEditVec.end(); ++iter)
{
CKeyEditUI* tmpCtrl = *iter;
assert(tmpCtrl);
ret = OfficeVolModule::GetInstance()->GetConfigStr((LPCTSTR)tmpCtrl->GetName(), configStr);
if(ret)
{
char str[1024] = {0};
_snprintf(str, 1024, "获取配置错误 %s", (LPCTSTR)tmpCtrl->GetName());
Off_Msg(str);
}
tmpCtrl->SetKey(configStr.c_str());
tmpCtrl->SetText(configStr.c_str());
}
return 0;
}
| [
"[email protected]"
] | |
cb1eb0501767f445c5a99cafa187d820ac86107c | 9be246df43e02fba30ee2595c8cec14ac2b355d1 | /public/inetgraph.h | 50a5fd4c00f793ee08e615c4e9724d9d2e46509d | [] | no_license | Clepoy3/LeakNet | 6bf4c5d5535b3824a350f32352f457d8be87d609 | 8866efcb9b0bf9290b80f7263e2ce2074302640a | refs/heads/master | 2020-05-30T04:53:22.193725 | 2019-04-12T16:06:26 | 2019-04-12T16:06:26 | 189,544,338 | 18 | 5 | null | 2019-05-31T06:59:39 | 2019-05-31T06:59:39 | null | UTF-8 | C++ | false | false | 1,602 | h | //======== (C) Copyright 1999, 2000 Valve, L.L.C. All rights reserved. ========
//
// The copyright to the contents herein is the property of Valve, L.L.C.
// The contents may be used and/or copied only with the written permission of
// Valve, L.L.C., or in accordance with the terms and conditions stipulated in
// the agreement/contract under which the contents have been supplied.
//
// Purpose:
//
// $Workfile: $
// $Date: $
//
//-----------------------------------------------------------------------------
// $Log: $
//
// $NoKeywords: $
//=============================================================================
#if !defined( INETGRAPH_H )
#define INETGRAPH_H
#ifdef _WIN32
#pragma once
#endif
class INetGraph
{
public:
virtual int GetOutgoingSequence( void ) = 0;
virtual int GetIncomingSequence( void ) = 0;
virtual int GetUpdateWindowSize( void ) = 0;
virtual int GetUpdateWindowMask( void ) = 0;
virtual bool IsFrameValid( int frame_number ) = 0;
virtual float GetFrameReceivedTime( int frame_number ) = 0;
virtual float GetFrameLatency( int frame_number ) = 0;
virtual int GetFrameBytes( int frame_number, const char *fieldName ) = 0;
virtual void GetAverageDataFlow( float *incoming, float *outgoing ) = 0;
virtual float GetCommandInterpolationAmount( int command_number ) = 0;
virtual bool GetCommandSent( int command_number ) = 0;
virtual int GetCommandSize( int command_number ) = 0;
};
extern INetGraph *netgraph;
#define VNETGRAPH_INTERFACE_VERSION "VNETGRAPH001"
#endif // INETGRAPH_H | [
"[email protected]"
] | |
9c10235056bb6e516ead4ea4784b251664b39ca4 | 19ad5c2df2a3950cc5dbe837df2e7be2e1d21081 | /Warehouse.cpp | fac34f11842a7fcd77247e70fe8e97e8d87f5a34 | [] | no_license | frederik1904/kattis | 8cd593367b6e4f74c0c3530d643f9c75d6757863 | a6846c5d7176e904b2e43d7f515c18f5abe7786c | refs/heads/master | 2021-07-15T04:09:44.442471 | 2021-07-03T18:08:04 | 2021-07-03T18:08:04 | 195,087,312 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,635 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct nameValue {
int amount = 0;
string name;
} ;
bool compareName(const nameValue &a, const nameValue &b) {
if (a.amount == b.amount) {
int minLen = a.name.length() < b.name.length() ?
a.name.length() : b.name.length();
for (int i = 0; i < minLen; i++) {
if (a.name.at(i) != b.name.at(i)) {
return a.name.at(i) < b.name.at(i);
}
}
return a.name.length() < b.name.length();
} else {
return a.amount > b.amount;
}
}
int main(int argc, char *argv[]) {
int testCases, products, value;
string str;
cin >> testCases;
for (int j = 0; j < testCases; j++) {
vector<nameValue> names;
cin >> products;
for (int k = 0; k < products; k++) {
cin >> str >> value;
bool found = false;
for (int i = 0; i < names.size(); i++) {
if (names.at(i).name.compare(str) == 0) {
names.at(i).amount += value;
found = true;
break;
}
}
if (!found) {
nameValue n;
n.name = str;
n.amount = value;
names.push_back(n);
}
}
sort(names.begin(), names.end(), compareName);
cout << names.size() << endl;
for (int i = 0; i < names.size(); i++) {
cout << names.at(i).name << " " << names.at(i).amount << endl;
}
}
} | [
"[email protected]"
] | |
6f75536e6246c3b93555f011b8d775dc85e1a6ca | 4fc1e78d401305cb8bf91e58566e29d526a58cfe | /Josephus/JosephusUsingLinkedList.cpp | 1f119929251190dfeaaa8d69d162777101ab9344 | [] | no_license | peterloos/Cpp_Josephus | ab2224a8cdca11d2796119e7e2e82e764498a25a | e8f7769ae380d995d05fa136bb32ce0c21c62179 | refs/heads/master | 2021-01-20T19:42:29.669315 | 2016-06-14T19:44:30 | 2016-06-14T19:44:30 | 61,150,987 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,519 | cpp | #include <iostream>
using namespace std;
#include "Soldier.h"
#include "Josephus.h"
namespace SolutionUsingLinkedList
{
// c'tor(s), d'tor
Josephus::Josephus()
: m_count(41), m_alive(41), m_lastEliminated(0)
{
m_passby = Josephus::DefaultPassBy;
CreateLinkedList();
}
Josephus::Josephus(int count)
: m_count(count), m_alive(count), m_lastEliminated(0)
{
m_passby = Josephus::DefaultPassBy;
CreateLinkedList();
}
Josephus::~Josephus()
{
Soldier* soldier = m_root;
// delete each single element
do
{
// store current node pointer
Soldier* current = soldier;
// advance to next node
soldier = soldier -> m_next;
// delete 'current' node pointer
delete current;
}
while (soldier != m_root);
}
// public interface
bool Josephus::EliminateNextSoldier()
{
// more than one soldier?
if (m_alive == 1)
return false;
// locate next soldier
for (int i = 0; i < m_passby - 1; i ++)
m_current = m_current -> m_next;
// remove soldier from list
Soldier* node = m_current -> m_next;
m_current -> m_next = node -> m_next;
// take care, if root object is removed
if (m_root == node)
m_root = m_root -> m_next;
m_lastEliminated = node -> m_number;
delete node;
m_alive --;
return true;
}
void Josephus::EliminateAll()
{
while (EliminateNextSoldier())
;
}
// private helper methods
void Josephus::CreateLinkedList()
{
// create first soldier
m_root = new Soldier(1);
m_current = m_root;
for (int i = 1; i < m_count; i ++)
{
Soldier* s = new Soldier(i + 1);
// link previous Soldier with current one
m_current -> m_next = s;
m_current = s;
}
// link last soldier with first one
m_current -> m_next = m_root;
}
// output
ostream& operator<< (ostream& os, const Josephus& j)
{
os << '[';
Soldier* tmp = j.m_root;
do
{
os << *tmp;
if (tmp -> m_next != j.m_root)
os << ',';
tmp = tmp -> m_next;
}
while (tmp != j.m_root);
os << ']';
return os;
}
}
| [
"[email protected]"
] | |
1dd9effec90db8470018ad373bef8187e3c7d5f2 | d37d17465820b6fbddac3d322e1cdbc4492a7a01 | /URI 1009/Main.cpp | 77e8e72fbcd7767826a5d7f10d781652d5ddb925 | [] | no_license | nafis195/URI | 97b0c590921c7d84b57ff560196db3134ac4a6e3 | 10f0470719d321b0a3eaee2675fa05aadb3fa948 | refs/heads/master | 2020-11-28T04:23:52.107445 | 2020-01-11T06:55:17 | 2020-01-11T06:55:17 | 229,702,347 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 634 | cpp | // Bismillahir Rahmanir Rahim
// URI_1009
// Salary with bonus
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
double totalSalary (string firstName, double salary, double salesValue)
{
double total;
total = salary + (salesValue * .15);
return total;
}
int main ()
{
string firstName;
double sellerSalary, salesTotal;
cin >> firstName;
cin >> sellerSalary;
cin >> salesTotal;
std::cout << std::fixed;
std::cout << std::setprecision (2);
cout << "TOTAL = R$ " << totalSalary (firstName, sellerSalary, salesTotal);
cout << endl;
system ("pause");
return 0;
} | [
"[email protected]"
] | |
dc877522d25d314a1da9c17db8cffa56a5988df4 | 77ee3feb0f82773760bffd9c287910c5865d5a80 | /src/GM/TexCUBE.cpp | b94bbfc9e85ad5b2fee558ae22eb8dd07b5f894f | [] | no_license | cecilietlandersen/OpenGL | 2fa8caf7dbfeb868c6098e4e88979da7b5ad8002 | 0223782c7241a36af3c9ee0ed6a05ef39b9a5a4d | refs/heads/master | 2021-01-15T22:02:27.021912 | 2012-10-31T12:52:02 | 2012-10-31T12:52:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,911 | cpp | #include "TexCUBE.h"
using namespace GM;
TexCUBE::TexCUBE(const TexCUBEParams &tex_params)
: faces_set(6)
{
#ifdef GL_TEXTURE_CUBE_MAP_SEAMLESS
glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
#endif
glGenTextures(1, &handle);
bind();
for(unsigned int i = 0; i < tex_params.params.size(); i++)
{
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X+i,
0, tex_params.params[i].internal_format, tex_params.params[i].w, tex_params.params[i].h,
0, tex_params.params[i].format, tex_params.params[i].type, tex_params.params[i].data);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
}
TexCUBE::TexCUBE()
: faces_set(0)
{
#ifdef GL_TEXTURE_CUBE_MAP_SEAMLESS
glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
#endif
glGenTextures(1, &handle);
bind();
}
TexCUBE::~TexCUBE()
{
glDeleteTextures(1, &handle);
}
void TexCUBE::setFace(unsigned int side, const T2DTexParams ¶m)
{
glTexImage2D(side,
0, param.internal_format, param.w, param.h,
0, param.format, param.type, param.data);
faces_set++;
}
void TexCUBE::finished()
{
if(faces_set != 6)
return;
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
}
void TexCUBE::bind()
{
glBindTexture(GL_TEXTURE_CUBE_MAP, handle);
}
void TexCUBE::unbind()
{
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
}
| [
"[email protected]"
] | |
ce78da355c11b0593d68e2259e3862ddc5809de6 | 5b70406792ce4203c6895a13948e282fb909d1d9 | /SaveTheGoozesSolution/SaveTheGoozesLib/SaveTheGoozesLib.cpp | 64d0eeb4a47dc13efc629e90fa997db624da6425 | [] | no_license | Rivaus/Save-The-Goozes-Game | 918f673c863f0495bab732cea0d3b76409a70de6 | faaf4098fb728f46daa3b80fd0fbc120ef64eead | refs/heads/master | 2020-05-30T12:14:31.010619 | 2019-07-02T21:54:27 | 2019-07-02T21:54:27 | 189,728,024 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 836 | cpp | // SaveTheGoozesLib.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
int main()
{
std::cout << "Hello World!\n";
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| [
"[email protected]"
] | |
86ced8b916a05bfbe0a2505c10335a536190ea4b | 2ba7eac6d92fd7a9ddfe29a66cf099b30a86b9c4 | /Project2/P2-1/gtest.cpp | c776e6539dbc1be7fe764ed52fa696a3baed1eb6 | [] | no_license | LiaoJJ/COP6726-Database-System-Implementation | 746b82c7c8b3a3f9d8d530fab8fac05dbc1a7698 | 36770a6ab09cf924a98fb9ed393ddb0c5aaa82f2 | refs/heads/main | 2023-04-20T23:19:34.491291 | 2021-04-25T18:55:40 | 2021-04-25T18:55:40 | 332,445,285 | 6 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 4,403 | cpp | #include "gtest/gtest.h"
#include <iostream>
#include "Record.h"
#include "DBFile.h"
#include "DBFile.cc"
#include "BigQ.h"
#include "BigQ.cc"
#include <stdlib.h>
using namespace std;
class BigQTest : public ::testing::Test {
protected:
BigQTest() {
// You can do set-up work for each test here.
}
~BigQTest() override {
// You can do clean-up work that doesn't throw exceptions here.
}
void SetUp() override {
// Code here will be called immediately after the constructor (right
// before each test).
// file.Open(1, "localTest/region.bin");
}
void TearDown() override {
// Code here will be called immediately after each test (right
// before the destructor).
// file.Close();
}
// File file;
char* regionFileName = "localTest/region.bin";
char* lineitemFileName = "localTest/lineitem.bin";
char* testFileName = "localTest/test.bin";
};
TEST_F(BigQTest, UpdateTopRecordForRunTest) {
// RecordComparer* comparer = new RecordComparer(new OrderMaker);
File file;
file.Open(1, regionFileName);
class Run* run = new class Run(&file, 0, 1);
Page bufferPage;
file.GetPage(&bufferPage, 0);
Record tempRecord;
bufferPage.GetFirst(&tempRecord);
while (bufferPage.GetFirst(&tempRecord) == 1) {
EXPECT_EQ(run->UpdateTopRecord(), 1);
}
EXPECT_EQ(run->UpdateTopRecord(), 0);
file.Close();
}
TEST_F(BigQTest, RecordComparerTest) {
File file;
file.Open(1, regionFileName);
//Initiate the proority queue for recard comparer
Schema* scheme = new Schema("catalog", "region");
OrderMaker* order = new OrderMaker(scheme);
priority_queue<Record*, vector<Record*>, RecordComparer> recordQueue (order);
ComparisonEngine comparisonEngine;
//Puting records into comparer based priority queue
Page bufferPage;
file.GetPage(&bufferPage, 0);
Record* readindRecord = new Record;
while (bufferPage.GetFirst(readindRecord)) {
recordQueue.push(readindRecord);
readindRecord = new Record;
}
bufferPage.EmptyItOut();
file.GetPage(&bufferPage, 0);
Record rec[2];
Record *last = NULL, *prev = NULL;
int i = 0;
while (bufferPage.GetFirst(&rec[i%2]) == 1) {
prev = last;
last = &rec[i%2];
if (prev && last) {
EXPECT_EQ(comparisonEngine.Compare(prev, last, order), -1);
}
i++;
}
file.Close();
}
TEST_F(BigQTest, RunComparerTest) {
//Initiate the proority queue for recard comparer
File file;
file.Open(1, lineitemFileName);
Schema* scheme = new Schema("catalog", "lineitem");
OrderMaker* order = new OrderMaker(scheme);
priority_queue<class Run*, vector<class Run*>, RunComparer> runQueue (order);
ComparisonEngine comparisonEngine;
class Run* run1 = new class Run(&file, 0, 1);
class Run* run2 = new class Run(&file, 1, 1);
runQueue.push(run1);
runQueue.push(run2);
//Take top record from two different run
Record one, two;
one.Copy(runQueue.top()->topRecord);
runQueue.pop();
two.Copy(runQueue.top()->topRecord);
runQueue.pop();
EXPECT_EQ(comparisonEngine.Compare(&one, &two, order), -1);
file.Close();
}
TEST_F(BigQTest, recordToRunTest) {
//Reading records from file to queue
File file;
file.Open(1, regionFileName);
Schema* scheme = new Schema("catalog", "region");
OrderMaker* order = new OrderMaker(scheme);
priority_queue<Record*, vector<Record*>, RecordComparer> recordQueue (order);
ComparisonEngine comparisonEngine;
Page bufferPage;
file.GetPage(&bufferPage, 0);
Record* readindRecord = new Record;
while (bufferPage.GetFirst(readindRecord)) {
recordQueue.push(readindRecord);
readindRecord = new Record;
}
//Writing records from queue to run
File testFile;
testFile.Open(0, testFileName);
Page testPage;
//Initiate the proority queue for recard comparer
int pageIndex = 0;
priority_queue<class Run*, vector<class Run*>, RunComparer> runQueue (order);
recordQueueToRun(recordQueue, runQueue, file, bufferPage, pageIndex);
EXPECT_EQ(recordQueue.size(), 0);
EXPECT_EQ(runQueue.size(), 1);
file.Close();
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| [
"[email protected]"
] | |
3b4e8279d5c5b7ae1ff1af1c32edca63a35d3869 | c6062b3748f6f4aa8c088a181109cebfa4d99bf3 | /Bots/BotAIController.h | b58a1394e7b71589f27d5f0687aec5ee353b9440 | [] | no_license | qipa/UE4-RPG-Demo | c543c16e0813c29c0d7cb8151dbb88abdd4941ed | b0cc148bea228ffcc8c7d368e721a4e1a5239498 | refs/heads/master | 2021-05-29T21:08:37.036409 | 2015-11-08T08:41:44 | 2015-11-08T08:41:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 427 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "AIController.h"
#include "BotAIController.generated.h"
class UBehaviorTreeComponent;
class UBlackboardComponent;
UCLASS()
class RPGDEMO_API ABotAIController : public AAIController
{
GENERATED_BODY()
public:
bool GetRandomPointInRadius(UNavigationSystem* navSys, FVector origin, float radius, FVector& location);
};
| [
"[email protected]"
] | |
855909cedafd1b6249f8324f15b5ab4856ed4df8 | 27d32027fc88567ae7fce89cef561747acbe25ad | /hackerrank/Algorithms/Implementation/Angry Professor.cpp | 663e2c418cf77f2a62a2c2ad6fd898baedfdd700 | [] | no_license | jayantsurana/competitiveCoding | ff12aa9ef1cc59701609a400856c9b4f5ee416c6 | e4d5ba5132f9f5a4dad4a2f87a831b845ed364de | refs/heads/master | 2021-07-20T16:31:18.661792 | 2020-04-25T12:38:25 | 2020-04-25T12:38:25 | 144,750,103 | 0 | 0 | null | 2019-02-19T12:18:19 | 2018-08-14T17:11:07 | C++ | UTF-8 | C++ | false | false | 1,920 | cpp | #include <bits/stdc++.h>
using namespace std;
vector<string> split_string(string);
// Complete the angryProfessor function below.
string angryProfessor(int k, vector<int> a) {
int earlyontime=0;
string s;
for(int i=0; i<a.size(); i++){
if(a[i]<=0)
earlyontime++;
}
if(k<=earlyontime)
s="NO";
else
s="YES";
return s;
}//By Jayant Surana.
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
int t;
cin >> t;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int t_itr = 0; t_itr < t; t_itr++) {
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 a_temp_temp;
getline(cin, a_temp_temp);
vector<string> a_temp = split_string(a_temp_temp);
vector<int> a(n);
for (int i = 0; i < n; i++) {
int a_item = stoi(a_temp[i]);
a[i] = a_item;
}
string result = angryProfessor(k, a);
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]"
] | |
4e4c1614bd9650cdf9cff4d6a92716dffb2fb73b | 01c029e89f2cec46f093e2766c3856339be022f2 | /TSLS_Edit_Distance.cpp | 52c5fce7144a010a01dfb0e2cf4f831f308b6e28 | [] | no_license | XiaoXiaoLui/LeetCode | f16c6213aa88b0454fb919cdf460fec74bb8ba60 | f0c3c2f654571655075a21e0b02465a02caf7cb3 | refs/heads/master | 2021-01-11T02:08:42.353447 | 2016-10-26T09:28:49 | 2016-10-26T09:28:49 | 70,828,096 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,364 | cpp | /******************************************************************************************
Edit Distance
******************************************************************************************/
#include <iostream>
#include <cstdio>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <string>
#include <cmath>
#include <cstring>
#include <queue>
#include <ctime>
using namespace std;
#define pii pair<int, int>
#define mp make_pair
typedef long long ll;
class Solution {
public:
int minDistance(string word1, string word2) {
dp.clear();
return solve(word1, word2, 0, 0);
}
int solve(const string &s1, const string &s2, int i, int j)
{
if (i >= s1.size())
{
return s2.size() - j;
}
if (j >= s2.size())
{
return s1.size() - i;
}
map<pii, int>::iterator iter;
if ((iter = dp.find(mp(i, j))) != dp.end())
{
return iter->second;
}
int res = 0;
if (s1[i] == s2[j])
{
res = solve(s1, s2, i + 1, j + 1);
}
else
{
res = solve(s1, s2, i + 1, j + 1) + 1; // modify
res = min(res, solve(s1, s2, i, j + 1) + 1); // insert
res = min(res, solve(s1, s2, i + 1, j) + 1); // erase
}
dp[mp(i, j)] = res;
return res;
}
map<pii, int> dp;
};
int main()
{
Solution S;
return 0;
} | [
"[email protected]"
] | |
83d80275e20bba40aeba4e1eb06fbd4a3d048151 | 7975777cfd2500a845c0075ea12f7033596f2e38 | /Minecraft/root_widget.h | c4a42a87a5965b5ed099eba656733d9c8b8efb70 | [] | no_license | TracyCR7/-MineCraft | 7c1d71b1d8388aec1afd5bfc2b4ea46165aa94ef | f97f66b63ded1b203c0a4e6acae4ac0aa006d984 | refs/heads/master | 2021-04-06T06:50:57.915649 | 2018-03-13T11:14:38 | 2018-03-13T11:14:38 | 124,719,439 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 296 | h | #pragma once
#include <QWidget>
#include <QResizeEvent>
#include <QSize>
#include "utils.h"
class ROOT_WIDGET : public QWidget {
Q_OBJECT
public:
ROOT_WIDGET(QWidget* parent);
protected:
void resizeEvent(QResizeEvent *event) override;
signals:
void change_size(QSize);
}; | [
"[email protected]"
] | |
3283b34a9cffd4258704a7e96dc41ae88fec5108 | c444b63016a742bccc9515f5fc2d38f9a3c3c760 | /Reco.h | 31dd0e09ccda36ebf93c407e7b4f24f52fbd983e | [] | no_license | vbashkirov/DataFormat-v44 | d38a4eeaa10924fc04b5285141813f3b0bbca8de | b583107f04b63aee64273fbee2c60fd0f5877184 | refs/heads/master | 2021-01-22T12:57:01.595679 | 2015-02-24T21:23:26 | 2015-02-24T21:23:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,413 | h | // Andriy Zatserklyaniy, April 17, 2014: production release
#ifndef Reco_h
#define Reco_h
#include "DataFormat.h"
#include "Track.h"
#include "Sensor.h"
#include "Geometry.h"
#include <iostream>
#include <vector>
#include <map>
#include <list>
using std::cout; using std::endl;
ClassImp(Hit2D);
ClassImp(SensorHit);
ClassImp(CRay2D);
//ClassImp(CRay);
ClassImp(Track2D);
//ClassImp(Track);
ClassImp(SuperTrack2D);
ClassImp(SuperTrack);
class Reco {
public:
Bool_t debug_;
Float_t deltaT_;
const Geometry* geometry_;
PCTSensors* pCTSensors_;
const BeamSpot* beamSpotIn_;
const BeamSpot* beamSpotOut_;
const PCTEvent* pCTEvent_;
Int_t event_;
std::list<const Track2D*> tin_;
std::list<const Track2D*> tout_;
std::list<const Track2D*> vin_;
std::list<const Track2D*> vout_;
std::list<const SuperTrack2D*> vSuperTracks_;
std::list<const SuperTrack2D*> tSuperTracks_;
std::list<const SuperTrack*> superTracks_;
static TClonesArray* poolTrack2D_; //->
static TClonesArray* poolSuperTrack2D_; //->
static TClonesArray* poolSuperTrack_; //->
// additional info
Int_t nhitv_[4];
Int_t nhitt_[4];
std::list<const SensorHit*> firstHitv_;
std::list<const SensorHit*> firstHitt_;
public:
Reco(const Geometry* geometry, PCTSensors* pCTSensors, const BeamSpot* beamSpotIn, const BeamSpot* beamSpotOut, const PCTEvent* pCTEvent, Int_t event, bool debug=kFALSE): debug_(debug)
, geometry_(geometry), pCTSensors_(pCTSensors), beamSpotIn_(beamSpotIn), beamSpotOut_(beamSpotOut), pCTEvent_(pCTEvent)
, event_(event)
{
//cout<< "Reco::Reco" <<endl;
deltaT_ = pCTEvent_->deltaT;
//cout<< "Reco::Reco: create pool" <<endl;
//Sensor::CreateHitPool();
Sensor::ClearPool();
if (!poolTrack2D_) poolTrack2D_ = new TClonesArray("Track2D", 1024);
if (!poolSuperTrack2D_) poolSuperTrack2D_ = new TClonesArray("SuperTrack2D", 128);
if (!poolSuperTrack_) poolSuperTrack_ = new TClonesArray("SuperTrack", 16);
//cout<< "Sensor::poolSensorHit_->GetLast()+1 = " << Sensor::poolSensorHit_->GetLast()+1 <<endl;
//cout<< "poolTrack2D_->GetLast()+1 = " << poolTrack2D_->GetLast()+1 <<endl;
//cout<< "poolSuperTrack2D_->GetLast()+1 = " << poolSuperTrack2D_->GetLast()+1 <<endl;
//cout<< "poolSuperTrack_->GetLast()+1 = " << poolSuperTrack_->GetLast()+1 <<endl;
//----------- pCTSensors_ = new PCTSensors();
pCTSensors_->clear();
for (int ilayer=0; ilayer<4; ++ilayer) {
nhitv_[ilayer] = 0;
nhitt_[ilayer] = 0;
}
// get hits for this event
for (int iFPGA=0; iFPGA<12; ++iFPGA)
{
const TrackerFPGA& trackerFPGA = pCTEvent_->trackerFPGA[iFPGA];
for (unsigned int ichip=0; ichip<trackerFPGA.numChips; ++ichip)
{
TrackerChip* trackerChip = (TrackerChip*) trackerFPGA.chips->At(ichip);
for (int icluster=0; icluster<trackerChip->numClust; ++icluster) {
if (debug_) {
Int_t strip = 64*trackerChip->address + (63-trackerChip->nfirst[icluster]);
cout<< event_ << "\t iFPGA = " << std::setw(2) << iFPGA
<< " trackerChip->address = " << std::setw(2) << (unsigned) trackerChip->address
<< " nstrips[" << icluster << "] = " << (unsigned) trackerChip->nstrips[icluster]
<< " nfirst[" << icluster << "] = " << (unsigned) trackerChip->nfirst[icluster]
<< " strip = " << strip <<endl;
// printf("%-8d iFPGA = %2d trackerChip->address = %2d nstrips[%d] = %d nfirst[%d] = %d strip = %d\n",
// event,iFPGA,(unsigned) trackerChip->address,icluster,(unsigned) trackerChip->nstrips[icluster],icluster,(unsigned) trackerChip->nfirst[icluster],strip);
}
pCTSensors_->AddCluster(iFPGA, trackerChip->address, trackerChip->nfirst[icluster], trackerChip->nstrips[icluster]);
}
}
}
pCTSensors_->GetHits();
const SensorHit* first_v = 0;
Int_t n_v_hits = 0;
for (unsigned ilayer=0; ilayer<4; ++ilayer) {
n_v_hits += pCTSensors_->v_hits[ilayer].size();
nhitv_[ilayer] += pCTSensors_->v_hits[ilayer].size();
if (!first_v && pCTSensors_->v_hits[ilayer].size() > 0) {
first_v = pCTSensors_->v_hits[ilayer].front();
firstHitv_.push_back(first_v);
}
}
const SensorHit* first_t = 0;
Int_t n_t_hits = 0;
for (unsigned ilayer=0; ilayer<4; ++ilayer) {
n_t_hits += pCTSensors_->t_hits[ilayer].size();
nhitt_[ilayer] = pCTSensors_->t_hits[ilayer].size();
if (!first_t && pCTSensors_->t_hits[ilayer].size() > 0) {
first_t = pCTSensors_->t_hits[ilayer].front();
firstHitt_.push_back(first_t);
}
}
if (debug_) cout<< "n_v_hits = " << n_v_hits << " n_t_hits = " << n_t_hits <<endl;
}
~Reco() {
//cout<< "Reco::~Reco" <<endl;
//for (std::list<const Track2D*>::const_iterator it=tin_.begin(); it!=tin_.end(); ++it) delete *it;
//for (std::list<const Track2D*>::const_iterator it=tout_.begin(); it!=tout_.end(); ++it) delete *it;
//for (std::list<const Track2D*>::const_iterator it=vin_.begin(); it!=vin_.end(); ++it) delete *it;
//for (std::list<const Track2D*>::const_iterator it=vout_.begin(); it!=vout_.end(); ++it) delete *it;
if (poolTrack2D_) poolTrack2D_->Clear();
if (poolTrack2D_) poolSuperTrack2D_->Clear();
if (poolTrack2D_) poolSuperTrack_->Clear();
//for (std::list<const SuperTrack2D*>::const_iterator it=vSuperTracks_.begin(); it!=vSuperTracks_.end(); ++it) delete *it;
//for (std::list<const SuperTrack2D*>::const_iterator it=tSuperTracks_.begin(); it!=tSuperTracks_.end(); ++it) delete *it;
//for (std::list<const SuperTrack*>::const_iterator it=superTracks_.begin(); it!=superTracks_.end(); ++it) delete *it;
//------------ delete pCTSensors_;
}
void Tracking()
{
// sanity checks
if (pCTSensors_->t_hits[0].size() + pCTSensors_->t_hits[1].size() == 0) return;
if (pCTSensors_->t_hits[2].size() + pCTSensors_->t_hits[3].size() == 0) return;
if (pCTSensors_->v_hits[0].size() + pCTSensors_->v_hits[1].size() == 0) return;
if (pCTSensors_->v_hits[2].size() + pCTSensors_->v_hits[3].size() == 0) return;
if (false
|| pCTSensors_->t_hits[0].size() > 3
|| pCTSensors_->t_hits[1].size() > 3
|| pCTSensors_->t_hits[2].size() > 3
|| pCTSensors_->t_hits[3].size() > 3
|| pCTSensors_->v_hits[0].size() > 3
|| pCTSensors_->v_hits[1].size() > 3
|| pCTSensors_->v_hits[2].size() > 3
|| pCTSensors_->v_hits[3].size() > 3
) return;
GenerateTracks2D();
if (tin_.size() && tout_.size() && vin_.size() && vout_.size()) GenerateSuperTracks2D();
if (vSuperTracks_.size() && tSuperTracks_.size()) GenerateSuperTracks();
if (superTracks_.size() > 0) {
Corrections();
return; // seems to be fine event
}
// try to recover gap hits
Int_t n_t_hits[4]; // initial number of the hits before adding of the gap hits
for (int ilayer=0; ilayer<4; ++ilayer) n_t_hits[ilayer] = pCTSensors_->t_hits[ilayer].size();
Int_t n_v_hits[4]; // initial number of the hits before adding of the gap hits
for (int ilayer=0; ilayer<4; ++ilayer) n_v_hits[ilayer] = pCTSensors_->v_hits[ilayer].size();
// input telescope
RecoverHits(0, beamSpotIn_);
// output telescope
RecoverHits(2, beamSpotOut_);
// redo the track reconstruction
GenerateTracks2D();
if (!tin_.size() || !tout_.size() || !vin_.size() || !vout_.size()) return;
if (tin_.size() && tout_.size() && vin_.size() && vout_.size()) GenerateSuperTracks2D();
if (vSuperTracks_.size() && tSuperTracks_.size()) GenerateSuperTracks();
if (debug_) cout<< "Reco::Tracking: superTracks_.size() = " << superTracks_.size() <<endl;
if (superTracks_.size() > 0) Corrections();
}
void Corrections()
{
if (debug_) cout<< "Reco::Corrections: superTracks_.size() = " << superTracks_.size() <<endl;
if (superTracks_.size() == 0) return;
//-- Double_t tilt = 2.94e-3; // radians
Double_t tilt = 2.50e-3; // radians // after Robert's corrections
for (std::list<const SuperTrack*>::iterator it=superTracks_.begin(); it!=superTracks_.end(); ++it) {
const SuperTrack* superTrack = *it;
Track2D* otrack_t = const_cast<Track2D*>(superTrack->tTrack_->otrack2D_);
Track2D* otrack_v = const_cast<Track2D*>(superTrack->vTrack_->otrack2D_);
Double_t v0 = otrack_v->x_;
Double_t t0 = otrack_t->x_;
//--AZ-- otrack_t->x_ -= v0*tilt - 0.030;
//--AZ-- otrack_v->x_ += (t0 - 150.)*tilt - 0.15;
otrack_t->x_ -= (v0 - 12.)*tilt;
otrack_v->x_ += t0*tilt;
// otrack_t->x_ -= (v0 - 10.)*tilt;
// otrack_v->x_ += (t0 - 170.)*tilt;
}
}
void RecoverHits(Int_t layerToStart, const BeamSpot* beamSpot)
{
Int_t n_t_hits[4]; // initial number of the hits before adding of the gap hits
for (int ilayer=0; ilayer<4; ++ilayer) n_t_hits[ilayer] = pCTSensors_->t_hits[ilayer].size();
Int_t n_v_hits[4]; // initial number of the hits before adding of the gap hits
for (int ilayer=0; ilayer<4; ++ilayer) n_v_hits[ilayer] = pCTSensors_->v_hits[ilayer].size();
SensorHit vertexHit_t(0, 0, 0, beamSpot->u_, beamSpot->t_); // vertex hit for recovery of the t-hits
SensorHit vertexHit_v(0, 0, 0, beamSpot->u_, beamSpot->v_); // vertex hit for recovery of the v-hits
Int_t layer1 = layerToStart;
Int_t layer2 = layer1 + 1;
//-- Double_t distance_max = 1. + 5.*beamSpot->r_*(geometry_->ut_[1]-geometry_->ut_[0])/(geometry_->ut_[0] - beamSpot->u_);
Double_t distance_max = 1. + 5.*beamSpot->r_*(geometry_->ut_[layer2]-geometry_->ut_[layer1])/(geometry_->ut_[layer1] - beamSpot->u_);
for (int ilayer=layerToStart; ilayer<=layerToStart+1; ++ilayer)
{
for (int ihit=0; ihit<n_t_hits[ilayer]; ++ihit) // loop over "real" t-hits
{
const SensorHit* hit = pCTSensors_->t_hits[ilayer][ihit];
Track2D vertex_track(&vertexHit_t, hit);
Int_t layerTo = (ilayer == layerToStart)? layerToStart+1: layerToStart;
Double_t pos = vertex_track.at(geometry_->ut_[layerTo]); // position of the t-hit. Will be used for both t- and v-recovery
// look at t-gaps for t-hits recovery
for (int igap=0; igap<3; ++igap)
{
//------------- if (TMath::Abs(pos - pCTSensors_->gap_.tgap_[layerTo][igap]) < distance_max)
if (TMath::Abs(pos - pCTSensors_->gap_.tgap_[layerTo][igap]) < pCTSensors_->gap_.width_)
{
// create a gap hit
//-----------------
// Double_t sigma_vertex = beamSpot->r_*(geometry_->ut_[layer2] - geometry_->ut_[layer1])/(geometry_->ut_[layerTo]-beamSpot->u_);
// Double_t sigma_gap = 1./TMath::Sqrt(12.);
// Double_t w_vertex = 1./(sigma_vertex*sigma_vertex);
// Double_t w_gap = 1./(sigma_gap*sigma_gap);
// Double_t pos_mean = (w_vertex*pos + w_gap*pCTSensors_->gap_.tgap_[layerTo][igap]) / (w_vertex + w_gap);
Double_t pos_mean = pCTSensors_->gap_.tgap_[layerTo][igap];
//-----------------
Int_t nstrips_gap = pCTSensors_->gap_.width_/geometry_->pitch_;
Int_t sensorId = -(20 + layerTo);
//-- SensorHit* gapHit = new ((*Sensor::poolSensorHit_)[Sensor::poolSensorHit_->GetLast()+1])
//-- SensorHit(sensorId, 0, nstrips_gap, geometry_->ut_[layerTo], pCTSensors_->gap_.tgap_[layerTo][igap]);
SensorHit* gapHit = new ((*Sensor::poolSensorHit_)[Sensor::poolSensorHit_->GetLast()+1])
SensorHit(sensorId, 0, nstrips_gap, geometry_->ut_[layerTo], pos_mean);
// add it to the common place
pCTSensors_->t_hits[layerTo].push_back(gapHit);
if (debug_) cout<< " added t hit " << *gapHit <<endl;
}
}
// look at v-gaps for v-hits recovery
for (int igap=0; igap<3; ++igap)
{
//------------ if (TMath::Abs(pos - pCTSensors_->gap_.vgap_[layerTo][igap]) < distance_max)
if (TMath::Abs(pos - pCTSensors_->gap_.vgap_[layerTo][igap]) < pCTSensors_->gap_.width_)
{
// create a gap hit for V
Int_t nstrips_gap = pCTSensors_->gap_.width_/geometry_->pitch_;
// project all v-hits
for (int ihit_v=0; ihit_v<n_v_hits[ilayer]; ++ihit_v)
{
const SensorHit* hit_v = pCTSensors_->v_hits[ilayer][ihit]; // current v-hit
Track2D vertex_track_v(&vertexHit_v, hit_v); // vertex track for fcurrent v-hit
Int_t sensorId = -(10 + layerTo);
SensorHit* gapHit = new ((*Sensor::poolSensorHit_)[Sensor::poolSensorHit_->GetLast()+1])
SensorHit(sensorId, 0, nstrips_gap, geometry_->uv_[layerTo], vertex_track_v.at(geometry_->uv_[layerTo])); // create v-hit at projection of v vertex track
// add it to the common place
pCTSensors_->v_hits[layerTo].push_back(gapHit);
if (debug_) cout<< " added v hit " << *gapHit <<endl;
}
}
}
}
}
}
void GenerateTracks2D()
{
tin_.clear();
tout_.clear();
vin_.clear();
vout_.clear();
// T-sensors
for (unsigned ihit1=0; ihit1<pCTSensors_->t_hits[0].size(); ++ihit1) {
const SensorHit* hit1 = pCTSensors_->t_hits[0][ihit1];
if (debug_) cout<< "hit1: " << *hit1 <<endl;
for (unsigned ihit2=0; ihit2<pCTSensors_->t_hits[1].size(); ++ihit2) {
const SensorHit* hit2 = pCTSensors_->t_hits[1][ihit2];
if (debug_) cout<< "hit2: " << *hit2 <<endl;
if (hit1->sensorId_ < 0 && hit2->sensorId_ < 0) continue; // at least one of the hits should be "real"
Track2D* cRay2d = new ((*poolTrack2D_)[poolTrack2D_->GetLast()+1]) Track2D(hit1, hit2);
tin_.push_back(cRay2d);
}
}
for (unsigned ihit1=0; ihit1<pCTSensors_->t_hits[2].size(); ++ihit1) {
const SensorHit* hit1 = pCTSensors_->t_hits[2][ihit1];
if (debug_) cout<< "hit1: " << *hit1 <<endl;
for (unsigned ihit2=0; ihit2<pCTSensors_->t_hits[3].size(); ++ihit2) {
const SensorHit* hit2 = pCTSensors_->t_hits[3][ihit2];
if (debug_) cout<< "hit2: " << *hit2 <<endl;
if (hit1->sensorId_ < 0 && hit2->sensorId_ < 0) continue; // at least one of the hits should be "real"
Track2D* cRay2d = new ((*poolTrack2D_)[poolTrack2D_->GetLast()+1]) Track2D(hit1, hit2);
tout_.push_back(cRay2d);
}
}
if (debug_) {
cout<< "tin_" <<endl;
for (std::list<const Track2D*>::const_iterator it=tin_.begin(); it!=tin_.end(); ++it) {
cout<< "it->x_ = " << (*it)->x_ <<endl;
}
}
if (debug_) {
cout<< "tout_" <<endl;
for (std::list<const Track2D*>::const_iterator it=tout_.begin(); it!=tout_.end(); ++it) {
cout<< "it->x_ = " << (*it)->x_ <<endl;
}
}
// V-sensors
for (unsigned ihit1=0; ihit1<pCTSensors_->v_hits[0].size(); ++ihit1) {
SensorHit* hit1 = pCTSensors_->v_hits[0][ihit1];
if (debug_) cout<< "hit1: " << *hit1 <<endl;
for (unsigned ihit2=0; ihit2<pCTSensors_->v_hits[1].size(); ++ihit2) {
SensorHit* hit2 = pCTSensors_->v_hits[1][ihit2];
if (debug_) cout<< "hit2: " << *hit2 <<endl;
if (hit1->sensorId_ < 0 && hit2->sensorId_ < 0) continue; // at least one of the hits should be "real"
Track2D* cRay2d = new ((*poolTrack2D_)[poolTrack2D_->GetLast()+1]) Track2D(hit1, hit2);
vin_.push_back(cRay2d);
}
}
for (unsigned ihit1=0; ihit1<pCTSensors_->v_hits[2].size(); ++ihit1) {
SensorHit* hit1 = pCTSensors_->v_hits[2][ihit1];
if (debug_) cout<< "hit1: " << *hit1 <<endl;
for (unsigned ihit2=0; ihit2<pCTSensors_->v_hits[3].size(); ++ihit2) {
SensorHit* hit2 = pCTSensors_->v_hits[3][ihit2];
if (debug_) cout<< "hit2: " << *hit2 <<endl;
if (hit1->sensorId_ < 0 && hit2->sensorId_ < 0) continue; // at least one of the hits should be "real"
Track2D* cRay2d = new ((*poolTrack2D_)[poolTrack2D_->GetLast()+1]) Track2D(hit1, hit2);
vout_.push_back(cRay2d);
}
}
if (debug_) {
cout<< "vin_" <<endl;
for (std::list<const Track2D*>::const_iterator it=vin_.begin(); it!=vin_.end(); ++it) {
cout<< "it->x_ = " << (*it)->x_ <<endl;
}
}
if (debug_) {
cout<< "vout_" <<endl;
for (std::list<const Track2D*>::const_iterator it=vout_.begin(); it!=vout_.end(); ++it) {
cout<< "it->x_ = " << (*it)->x_ <<endl;
}
}
}
void GenerateVSuperTracks2D(Double_t rmax=10.)
{
vSuperTracks_.clear();
// start from V-senosors: as a max we can reconstruct two tracks and only if they are from different V-sensors
for (std::list<const Track2D*>::const_iterator it=vin_.begin(); it!=vin_.end(); ++it) {
const Track2D* itrack = *it;
for (std::list<const Track2D*>::const_iterator ot=vout_.begin(); ot!=vout_.end(); ++ot) {
const Track2D* otrack = *ot;
//-- SuperTrack2D* superTrack = new SuperTrack2D(itrack, otrack);
SuperTrack2D* superTrack = new ((*poolSuperTrack2D_)[poolSuperTrack2D_->GetLast()+1]) SuperTrack2D(itrack, otrack);
vSuperTracks_.push_back(superTrack);
}
}
// apply filter on the distance between the hits in the plane u = 0
std::map<Double_t, const SuperTrack2D*> mapCloseTracks; // for the filter on the distance in the plane u = 0
for (std::list<const SuperTrack2D*>::const_iterator it=vSuperTracks_.begin(); it!=vSuperTracks_.end(); ++it) {
const SuperTrack2D* superTrack = *it;
mapCloseTracks[superTrack->Distance()] = superTrack;
}
if (debug_) cout<< "GenerateSuperTracks2D: vSuperTracks_.size() = " << vSuperTracks_.size() <<endl;
if (debug_) {
cout<< "resulting distance map from SuperTracks2D for V-board" <<endl;
for (std::map<Double_t, const SuperTrack2D*>::const_iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end(); ++it) {
Double_t distance = it->first;
cout<< std::distance<std::map<Double_t, const SuperTrack2D*>::const_iterator>(mapCloseTracks.begin(), it) << "\t distance = " << distance <<endl;
}
}
// 1) loop over map to remove the tracks with higher distance
// 2) check for hits overlap in the (small number) of passed tracks
if (debug_) cout<< "loop over the map to remove tracks with distance above the rmax = " << rmax <<endl;
//--const-- for (std::map<Double_t, const SuperTrack2D*>::const_iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end();)
for (std::map<Double_t, const SuperTrack2D*>::iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end();)
{
if (it->first < rmax) ++it;
else {
if (debug_) cout<< "remove track with distance " << it->first <<endl;
vSuperTracks_.remove(it->second);
//-- it = mapCloseTracks.erase(it);
mapCloseTracks.erase(it++);
}
}
if (debug_) cout<< "GenerateSuperTracks2D: vSuperTracks_.size() = " << vSuperTracks_.size() <<endl;
// make sure that the rest of tracks do not share the same hits
//--const-- for (std::map<Double_t, const SuperTrack2D*>::const_iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end(); ++it)
for (std::map<Double_t, const SuperTrack2D*>::iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end(); ++it)
{
//--const-- std::map<Double_t, const SuperTrack2D*>::const_iterator next = it;
std::map<Double_t, const SuperTrack2D*>::iterator next = it;
++next;
while (next != mapCloseTracks.end()) {
if (next->second->SharedHits(it->second)) {
vSuperTracks_.remove(next->second);
//-- next = mapCloseTracks.erase(next);
mapCloseTracks.erase(next++);
}
else ++next;
}
}
}
void GenerateTSuperTracks2D(Double_t rmax=10.)
{
tSuperTracks_.clear();
for (std::list<const Track2D*>::const_iterator it=tin_.begin(); it!=tin_.end(); ++it) {
const Track2D* itrack2D = *it;
for (std::list<const Track2D*>::const_iterator ot=tout_.begin(); ot!=tout_.end(); ++ot) {
const Track2D* otrack2D = *ot;
//-- SuperTrack2D* superTrack2D = new SuperTrack2D(itrack2D, otrack2D);
SuperTrack2D* superTrack2D = new ((*poolSuperTrack2D_)[poolSuperTrack2D_->GetLast()+1]) SuperTrack2D(itrack2D, otrack2D);
tSuperTracks_.push_back(superTrack2D);
}
}
// apply filter on the distance between the hits in the plane u = 0
std::map<Double_t, const SuperTrack2D*> mapCloseTracks; // for the filter on the distance in the plane u = 0
for (std::list<const SuperTrack2D*>::const_iterator it=tSuperTracks_.begin(); it!=tSuperTracks_.end(); ++it) {
const SuperTrack2D* superTrack = *it;
mapCloseTracks[superTrack->Distance()] = superTrack;
}
if (debug_) cout<< "GenerateSuperTracks2D: tSuperTracks_.size() = " << tSuperTracks_.size() <<endl;
if (debug_) {
cout<< "resulting distance map from SuperTracks2D for T-board" <<endl;
for (std::map<Double_t, const SuperTrack2D*>::const_iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end(); ++it) {
Double_t distance = it->first;
cout<< std::distance<std::map<Double_t, const SuperTrack2D*>::const_iterator>(mapCloseTracks.begin(), it) << "\t distance = " << distance <<endl;
}
}
// 1) loop over map to remove the tracks with higher distance
// 2) check for hits overlap in the (small number) of passed tracks
if (debug_) cout<< "loop over the map to remove tracks with distance above the rmax = " << rmax <<endl;
//--const-- for (std::map<Double_t, const SuperTrack2D*>::const_iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end();)
for (std::map<Double_t, const SuperTrack2D*>::iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end();)
{
if (it->first < rmax) ++it;
else {
if (debug_) cout<< "remove track with distance " << it->first <<endl;
tSuperTracks_.remove(it->second);
//-- it = mapCloseTracks.erase(it);
mapCloseTracks.erase(it++);
}
}
if (debug_) cout<< "GenerateSuperTracks2D: tSuperTracks_.size() = " << tSuperTracks_.size() <<endl;
// make sure that the rest of tracks do not share the same hits
//--const-- for (std::map<Double_t, const SuperTrack2D*>::const_iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end(); ++it)
for (std::map<Double_t, const SuperTrack2D*>::iterator it=mapCloseTracks.begin(); it!=mapCloseTracks.end(); ++it)
{
//--const-- std::map<Double_t, const SuperTrack2D*>::const_iterator next = it;
std::map<Double_t, const SuperTrack2D*>::iterator next = it;
++next;
while (next != mapCloseTracks.end()) {
if (next->second->SharedHits(it->second)) {
tSuperTracks_.remove(next->second);
//-- next = mapCloseTracks.erase(next);
mapCloseTracks.erase(next++);
}
else ++next;
}
}
}
void GenerateSuperTracks2D(Double_t rmax=10.) {
GenerateVSuperTracks2D(rmax);
// if (vSuperTracks_.size() > 2) return;
// else if (vSuperTracks_.size() == 2) {
// // check halves
// }
GenerateTSuperTracks2D(rmax);
}
void GenerateSuperTracks()
{
superTracks_.clear();
if (debug_) cout<< "GenerateSuperTracks: vSuperTracks_.size() = " << vSuperTracks_.size() << " tSuperTracks_.size() = " << tSuperTracks_.size() <<endl;
// inspect the number of T-super tracks 2D: maximum number is 2
if (tSuperTracks_.size() > 2) return;
// inspect the number of V-super tracks 2D: maximum number is 2.
// In case of 2 tracks they should be from different halves of the V-board (at least in one layer)
if (vSuperTracks_.size() > 2) return;
if (vSuperTracks_.size() == 2) {
const SuperTrack2D* track1 = vSuperTracks_.front();
const SuperTrack2D* track2 = vSuperTracks_.back();
bool same = true
&& track1->itrack2D_->hit1_->sensorId_ == track2->itrack2D_->hit1_->sensorId_
&& track1->itrack2D_->hit2_->sensorId_ == track2->itrack2D_->hit2_->sensorId_
&& track1->otrack2D_->hit1_->sensorId_ == track2->otrack2D_->hit1_->sensorId_
&& track1->otrack2D_->hit2_->sensorId_ == track2->otrack2D_->hit2_->sensorId_
;
if (same) {
if (debug_) cout<< "GenerateSuperTracks: same = " << same <<endl;
return;
}
}
// at this point we have as max two t-superTracks and no more than v-superTracks
// in principle, we should combine them to match V-board halves with the t-tracks
//
// leave that for future
//
if (vSuperTracks_.size() != 1) return;
if (tSuperTracks_.size() != 1) return;
// match the halves
//-- SuperTrack* superTrack = new SuperTrack(vSuperTracks_.front(), tSuperTracks_.front());
SuperTrack* superTrack = new ((*poolSuperTrack_)[poolSuperTrack_->GetLast()+1]) SuperTrack(vSuperTracks_.front(), tSuperTracks_.front());
superTracks_.push_back(superTrack);
}
};
class RecoEvent: public TObject {
public:
Bool_t ok; // error flag
Float_t deltaT;
TClonesArray* track; //->
Int_t nt; // the number of super tracks
Float_t a[5]; // Energy detector channels
Float_t ped[5];
Float_t sample[5][16]; // to plot e.g. channel 1: r->Draw("sample[1][]:Iteration$","Entry$==0")
Float_t wepl;
// additional info
Int_t nhit;
Int_t nhitv[4];
Int_t nhitt[4];
Int_t nhit_reco;
Int_t nhitv_reco[4];
Int_t nhitt_reco[4];
TClonesArray* firstHitv; //->
TClonesArray* firstHitt; //->
RecoEvent(): TObject(), ok(kTRUE), nt(0) {
track = new TClonesArray("SuperTrack");
firstHitv = new TClonesArray("SensorHit", 1);
firstHitt = new TClonesArray("SensorHit", 1);
}
~RecoEvent() {
delete track;
delete firstHitv;
delete firstHitt;
}
void clear() {
deltaT = 0;
track->Clear();
firstHitv->Clear();
firstHitt->Clear();
nt = 0;
for (int i=0; i<5; ++i) {
a[i] = 0;
ped[i] = 0;
}
for (int ichan=0; ichan<5; ++ichan) for (int isample=0; isample<16; ++isample) sample[ichan][isample] = 0;
wepl = -2000.;
}
Float_t SampleSum(Int_t chan, Int_t nfront, Int_t ntail, Double_t pedestal) const {
if (chan < 0 || chan > 4) return 0;
// find a position of the maximum
Int_t imax = 0;
// assumes that the number of samples is 16
Float_t sum = sample[chan][imax];
for (int isample=0; isample<16; ++isample) {
sum += sample[chan][isample];
if (sample[chan][isample] > sample[chan][imax]) {
imax = isample;
}
}
if (sum == 0) return 0; // there are no samples in this event
Int_t n1 = imax - nfront;
if (n1 < 0) n1 = 0;
Int_t n2 = imax + ntail;
if (n2 > 15) n2 = 15;
sum = 0;
for (int isample=n1; isample<=n2; ++isample) sum += sample[chan][isample];
sum -= (n2 - n1 + 1)*pedestal;
return sum;
}
void Extract(const Reco& reco) {
clear();
nhit = 0;
for (int ilayer=0; ilayer<4; ++ilayer) {
nhitv[ilayer] = reco.nhitv_[ilayer];
nhitt[ilayer] = reco.nhitt_[ilayer];
nhit += (nhitv[ilayer] + nhitt[ilayer]);
nhitv_reco[ilayer] = 0;
nhitt_reco[ilayer] = 0;
nhit_reco = 0;
}
for (std::list<const SensorHit*>::const_iterator it=reco.firstHitv_.begin(); it!=reco.firstHitv_.end(); ++it) {
const SensorHit* hit = *it;
new ((*firstHitv)[firstHitv->GetLast()+1]) SensorHit(*hit);
}
for (std::list<const SensorHit*>::const_iterator it=reco.firstHitt_.begin(); it!=reco.firstHitt_.end(); ++it) {
const SensorHit* hit = *it;
new ((*firstHitt)[firstHitt->GetLast()+1]) SensorHit(*hit);
}
deltaT = reco.deltaT_;
for (std::list<const SuperTrack*>::const_iterator it=reco.superTracks_.begin(); it!=reco.superTracks_.end(); ++it) {
const SuperTrack* superTrack = *it;
new ((*track)[track->GetLast()+1]) SuperTrack(*superTrack);
++nt;
if (superTrack->vTrack_->itrack2D_->hit1_->sensorId_ < 0) ++nhitv_reco[0];
if (superTrack->vTrack_->itrack2D_->hit2_->sensorId_ < 0) ++nhitv_reco[1];
if (superTrack->vTrack_->otrack2D_->hit1_->sensorId_ < 0) ++nhitv_reco[2];
if (superTrack->vTrack_->otrack2D_->hit2_->sensorId_ < 0) ++nhitv_reco[3];
if (superTrack->tTrack_->itrack2D_->hit1_->sensorId_ < 0) ++nhitt_reco[0];
if (superTrack->tTrack_->itrack2D_->hit2_->sensorId_ < 0) ++nhitt_reco[1];
if (superTrack->tTrack_->otrack2D_->hit1_->sensorId_ < 0) ++nhitt_reco[2];
if (superTrack->tTrack_->otrack2D_->hit2_->sensorId_ < 0) ++nhitt_reco[3];
}
nhit_reco = 0;
for (int ilayer=0; ilayer<4; ++ilayer) {
nhit_reco += nhitv_reco[ilayer];
nhit_reco += nhitt_reco[ilayer];
}
// Energy detector
//a[0] = reco.pCTEvent_->energyBoard[0].pulse[0];
//a[1] = reco.pCTEvent_->energyBoard[0].pulse[1];
//a[2] = reco.pCTEvent_->energyBoard[0].pulse[2];
//a[3] = reco.pCTEvent_->energyBoard[1].pulse[0];
//a[4] = reco.pCTEvent_->energyBoard[1].pulse[1];
/////////////////////////////
int brd=0;
///// //--orig int enrgTag0= thisEvent->Event->Board[0].enrgTag;
///// //--orig int enrgTag1= thisEvent->Event->Board[1].enrgTag;
///// // if (enrgTag0 != enrgTag1) cout << "enrg tag mismatch: " << enrgTag0 << " vs " << enrgTag1;
if (reco.pCTEvent_->energyBoard[brd].numChan>0 || reco.pCTEvent_->energyBoard[brd].numSamples>0) {
///// // if (thisEvent->Event->Board[brd].enrgTag != evtNum % 4) cout << "tag mismatch, energy tag=" << thisEvent->Event->Board[brd].enrgTag << "\n";
if (reco.pCTEvent_->energyBoard[brd].reduced) {
a[0] = reco.pCTEvent_->energyBoard[brd].pulse[0]; ped[0] = reco.pCTEvent_->energyBoard[brd].pedestal[0];
a[1] = reco.pCTEvent_->energyBoard[brd].pulse[1]; ped[1] = reco.pCTEvent_->energyBoard[brd].pedestal[1];
a[2] = reco.pCTEvent_->energyBoard[brd].pulse[2]; ped[2] = reco.pCTEvent_->energyBoard[brd].pedestal[2];
} else {
a[0] = 0.; a[1] = 0.; a[2] = 0.;
/// enrgSamp *thisSamp = thisEvent->Event->Board[brd].firstSample;
//EnergySample* energySample = (EnergySample*) reco.pCTEvent_->energyBoard[brd].samples->At(0);
//if (thisSamp != 0)
if (reco.pCTEvent_->energyBoard[brd].samples->GetLast()+1 > 0)
{
EnergySample* energySample0 = (EnergySample*) reco.pCTEvent_->energyBoard[brd].samples->At(0);
sample[0][0] = energySample0->pulse[0]; // assign the first sample of the RecoEvent::sample for the first energy board
sample[1][0] = energySample0->pulse[1];
sample[2][0] = energySample0->pulse[2];
int ped0 = energySample0->pulse[0]; ped[0] = ped0;
int ped1 = energySample0->pulse[1]; ped[1] = ped1;
int ped2 = energySample0->pulse[2]; ped[2] = ped2;
//while (thisSamp != 0)
for (int isample=1; isample<reco.pCTEvent_->energyBoard[brd].samples->GetLast()+1; ++isample)
{
EnergySample* energySample = (EnergySample*) reco.pCTEvent_->energyBoard[brd].samples->At(isample);
sample[0][isample] = energySample->pulse[0]; // assign the rest of 16 samples of the RecoEvent::sample for the first energy board
sample[1][isample] = energySample->pulse[1];
sample[2][isample] = energySample->pulse[2];
a[0] = a[0] + energySample->pulse[0] - ped0;
a[1] = a[1] + energySample->pulse[1] - ped1;
a[2] = a[2] + energySample->pulse[2] - ped2;
}
}
}
} else {
a[0] = 0; ped[0] = 0;
a[1] = 0; ped[1] = 0;
a[2] = 0; ped[2] = 0;
}
brd=1;
if (reco.pCTEvent_->energyBoard[brd].numChan>0 || reco.pCTEvent_->energyBoard[brd].numSamples>0) {
///// // if (thisEvent->Event->Board[brd].enrgTag != evtNum % 4) cout << "tag mismatch, energy tag=" << thisEvent->Event->Board[brd].enrgTag << "\n";
if (reco.pCTEvent_->energyBoard[brd].reduced) {
a[3] = reco.pCTEvent_->energyBoard[brd].pulse[0]; ped[3] = reco.pCTEvent_->energyBoard[brd].pedestal[0];
a[4] = reco.pCTEvent_->energyBoard[brd].pulse[1]; ped[4] = reco.pCTEvent_->energyBoard[brd].pedestal[1];
//--no such channel-- PhCh5 = reco.pCTEvent_->energyBoard[brd].pulse[2];
} else {
a[3] = 0.; a[4] = 0.; //--no such channel-- PhCh5 = 0.;
int ped3 = 0; int ped4 = 0; int ped5 = 0;
/// enrgSamp *thisSamp = thisEvent->Event->Board[brd].firstSample;
//EnergySample* energySample = (EnergySample*) reco.pCTEvent_->energyBoard[brd].samples->At(0);
//if (thisSamp != 0)
if (reco.pCTEvent_->energyBoard[brd].samples->GetLast()+1 > 0)
{
EnergySample* energySample0 = (EnergySample*) reco.pCTEvent_->energyBoard[brd].samples->At(0);
sample[3][0] = energySample0->pulse[0]; // assign the first sample of the RecoEvent::sample for the second energy board
sample[4][0] = energySample0->pulse[1];
ped3 = energySample0->pulse[0]; ped[3] = ped3;
ped4 = energySample0->pulse[1]; ped[4] = ped4;
ped5 = energySample0->pulse[2];
//while (thisSamp != 0)
for (int isample=1; isample<reco.pCTEvent_->energyBoard[brd].samples->GetLast()+1; ++isample)
{
EnergySample* energySample = (EnergySample*) reco.pCTEvent_->energyBoard[brd].samples->At(isample);
sample[3][isample] = energySample->pulse[0]; // assign the rest of 16 samples of the RecoEvent::sample for the second energy board
sample[4][isample] = energySample->pulse[1];
a[3] = a[3] + energySample->pulse[0] - ped3;
a[4] = a[4] + energySample->pulse[1] - ped4;
//--no such channel-- PhCh5 = PhCh5 + energySample->pulse[2] - ped5;
}
}
}
} else {
a[3] = 0; ped[3] = 0;
a[4] = 0; ped[4] = 0;
//--no such channel-- PhCh5 = 0;
}
/////////////////////////////
}
ClassDef(RecoEvent, 10);
};
#ifdef __MAKECINT__
#pragma link C++ class RecoEvent;
#endif
#endif // Reco_h
| [
"[email protected]"
] | |
0f49bdd721aa93feaf4cd2f6ebaf1ce787a1518a | e25b7bb3fd43f763f4e5dcb09cdda35b9a3f30a0 | /net/third_party/quic/test_tools/crypto_test_utils_test.cc | ede4a833f74c10c53b6ef0f83a99a0062d8cf383 | [
"BSD-3-Clause"
] | permissive | trustcrypto/chromium | 281ff06e944b1ff7da7a5005e41173ccc78eb2cd | 6e3be4ab657ddd91505753ab67801efcf8541367 | refs/heads/master | 2023-03-08T03:58:49.920358 | 2018-12-26T20:55:44 | 2018-12-26T20:55:44 | 163,217,833 | 1 | 0 | NOASSERTION | 2018-12-26T21:07:41 | 2018-12-26T21:07:40 | null | UTF-8 | C++ | false | false | 7,065 | cc | // Copyright (c) 2012 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 "net/third_party/quic/test_tools/crypto_test_utils.h"
#include "net/test/gtest_util.h"
#include "net/third_party/quic/core/proto/crypto_server_config.pb.h"
#include "net/third_party/quic/core/quic_utils.h"
#include "net/third_party/quic/core/tls_server_handshaker.h"
#include "net/third_party/quic/platform/api/quic_ptr_util.h"
#include "net/third_party/quic/platform/api/quic_test.h"
#include "net/third_party/quic/platform/api/quic_text_utils.h"
#include "net/third_party/quic/test_tools/mock_clock.h"
namespace quic {
namespace test {
class ShloVerifier {
public:
ShloVerifier(
QuicCryptoServerConfig* crypto_config,
QuicSocketAddress server_addr,
QuicSocketAddress client_addr,
const QuicClock* clock,
QuicReferenceCountedPointer<QuicSignedServerConfig> signed_config,
QuicCompressedCertsCache* compressed_certs_cache)
: crypto_config_(crypto_config),
server_addr_(server_addr),
client_addr_(client_addr),
clock_(clock),
signed_config_(signed_config),
compressed_certs_cache_(compressed_certs_cache),
params_(new QuicCryptoNegotiatedParameters) {}
class ValidateClientHelloCallback : public ValidateClientHelloResultCallback {
public:
explicit ValidateClientHelloCallback(ShloVerifier* shlo_verifier)
: shlo_verifier_(shlo_verifier) {}
void Run(QuicReferenceCountedPointer<
ValidateClientHelloResultCallback::Result> result,
std::unique_ptr<ProofSource::Details> /* details */) override {
shlo_verifier_->ValidateClientHelloDone(result);
}
private:
ShloVerifier* shlo_verifier_;
};
std::unique_ptr<ValidateClientHelloCallback>
GetValidateClientHelloCallback() {
return QuicMakeUnique<ValidateClientHelloCallback>(this);
}
private:
void ValidateClientHelloDone(
const QuicReferenceCountedPointer<
ValidateClientHelloResultCallback::Result>& result) {
result_ = result;
crypto_config_->ProcessClientHello(
result_, /*reject_only=*/false,
/*connection_id=*/QuicConnectionIdFromUInt64(1), server_addr_,
client_addr_, AllSupportedVersions().front(), AllSupportedVersions(),
/*use_stateless_rejects=*/true,
/*server_designated_connection_id=*/EmptyQuicConnectionId(), clock_,
QuicRandom::GetInstance(), compressed_certs_cache_, params_,
signed_config_, /*total_framing_overhead=*/50, kDefaultMaxPacketSize,
GetProcessClientHelloCallback());
}
class ProcessClientHelloCallback : public ProcessClientHelloResultCallback {
public:
explicit ProcessClientHelloCallback(ShloVerifier* shlo_verifier)
: shlo_verifier_(shlo_verifier) {}
void Run(
QuicErrorCode error,
const QuicString& error_details,
std::unique_ptr<CryptoHandshakeMessage> message,
std::unique_ptr<DiversificationNonce> diversification_nonce,
std::unique_ptr<ProofSource::Details> proof_source_details) override {
shlo_verifier_->ProcessClientHelloDone(std::move(message));
}
private:
ShloVerifier* shlo_verifier_;
};
std::unique_ptr<ProcessClientHelloCallback> GetProcessClientHelloCallback() {
return QuicMakeUnique<ProcessClientHelloCallback>(this);
}
void ProcessClientHelloDone(std::unique_ptr<CryptoHandshakeMessage> message) {
// Verify output is a SHLO.
EXPECT_EQ(message->tag(), kSHLO)
<< "Fail to pass validation. Get " << message->DebugString();
}
QuicCryptoServerConfig* crypto_config_;
QuicSocketAddress server_addr_;
QuicSocketAddress client_addr_;
const QuicClock* clock_;
QuicReferenceCountedPointer<QuicSignedServerConfig> signed_config_;
QuicCompressedCertsCache* compressed_certs_cache_;
QuicReferenceCountedPointer<QuicCryptoNegotiatedParameters> params_;
QuicReferenceCountedPointer<ValidateClientHelloResultCallback::Result>
result_;
};
class CryptoTestUtilsTest : public QuicTest {};
TEST_F(CryptoTestUtilsTest, TestGenerateFullCHLO) {
MockClock clock;
QuicCryptoServerConfig crypto_config(
QuicCryptoServerConfig::TESTING, QuicRandom::GetInstance(),
crypto_test_utils::ProofSourceForTesting(), KeyExchangeSource::Default(),
TlsServerHandshaker::CreateSslCtx());
QuicSocketAddress server_addr;
QuicSocketAddress client_addr(QuicIpAddress::Loopback4(), 1);
QuicReferenceCountedPointer<QuicSignedServerConfig> signed_config(
new QuicSignedServerConfig);
QuicCompressedCertsCache compressed_certs_cache(
QuicCompressedCertsCache::kQuicCompressedCertsCacheSize);
CryptoHandshakeMessage full_chlo;
QuicCryptoServerConfig::ConfigOptions old_config_options;
old_config_options.id = "old-config-id";
delete crypto_config.AddDefaultConfig(QuicRandom::GetInstance(), &clock,
old_config_options);
QuicCryptoServerConfig::ConfigOptions new_config_options;
std::unique_ptr<QuicServerConfigProtobuf> primary_config(
crypto_config.GenerateConfig(QuicRandom::GetInstance(), &clock,
new_config_options));
primary_config->set_primary_time(clock.WallNow().ToUNIXSeconds());
std::unique_ptr<CryptoHandshakeMessage> msg(
crypto_config.AddConfig(std::move(primary_config), clock.WallNow()));
QuicStringPiece orbit;
ASSERT_TRUE(msg->GetStringPiece(kORBT, &orbit));
QuicString nonce;
CryptoUtils::GenerateNonce(
clock.WallNow(), QuicRandom::GetInstance(),
QuicStringPiece(reinterpret_cast<const char*>(orbit.data()),
sizeof(orbit.size())),
&nonce);
QuicString nonce_hex = "#" + QuicTextUtils::HexEncode(nonce);
char public_value[32];
memset(public_value, 42, sizeof(public_value));
QuicString pub_hex =
"#" + QuicTextUtils::HexEncode(public_value, sizeof(public_value));
QuicTransportVersion version(AllSupportedTransportVersions().front());
CryptoHandshakeMessage inchoate_chlo = crypto_test_utils::CreateCHLO(
{{"PDMD", "X509"},
{"AEAD", "AESG"},
{"KEXS", "C255"},
{"COPT", "SREJ"},
{"PUBS", pub_hex},
{"NONC", nonce_hex},
{"VER\0",
QuicVersionLabelToString(QuicVersionToQuicVersionLabel(version))}},
kClientHelloMinimumSize);
crypto_test_utils::GenerateFullCHLO(
inchoate_chlo, &crypto_config, server_addr, client_addr, version, &clock,
signed_config, &compressed_certs_cache, &full_chlo);
// Verify that full_chlo can pass crypto_config's verification.
ShloVerifier shlo_verifier(&crypto_config, server_addr, client_addr, &clock,
signed_config, &compressed_certs_cache);
crypto_config.ValidateClientHello(
full_chlo, client_addr.host(), server_addr, version, &clock,
signed_config, shlo_verifier.GetValidateClientHelloCallback());
}
} // namespace test
} // namespace quic
| [
"[email protected]"
] | |
fb9500ab979c18b3d332614585aa4fafaa74ed60 | ea99679b342d457b22832672e61eecb18512b25d | /src/core_write.cpp | 8579ee84c9ffc42bc5b2eadd18107897fdac16bf | [
"MIT"
] | permissive | eletaNetwork/eletaNetwork | ab5cb586c8ce13380eba1eaa58327e3ecb9ec755 | c589089d189215d83a34534c82878d39b7cdda96 | refs/heads/master | 2020-03-08T19:27:51.153812 | 2018-04-13T06:01:43 | 2018-04-13T06:01:43 | 128,353,833 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,565 | cpp | // Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "core_io.h"
#include "base58.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "script/standard.h"
#include "serialize.h"
#include "streams.h"
#include <univalue.h>
#include "util.h"
#include "utilmoneystr.h"
#include "utilstrencodings.h"
#include <boost/assign/list_of.hpp>
#include <boost/foreach.hpp>
using namespace std;
string FormatScript(const CScript& script)
{
string ret;
CScript::const_iterator it = script.begin();
opcodetype op;
while (it != script.end()) {
CScript::const_iterator it2 = it;
vector<unsigned char> vch;
if (script.GetOp2(it, op, &vch)) {
if (op == OP_0) {
ret += "0 ";
continue;
} else if ((op >= OP_1 && op <= OP_16) || op == OP_1NEGATE) {
ret += strprintf("%i ", op - OP_1NEGATE - 1);
continue;
} else if (op >= OP_NOP && op <= OP_NOP10) {
string str(GetOpName(op));
if (str.substr(0, 3) == string("OP_")) {
ret += str.substr(3, string::npos) + " ";
continue;
}
}
if (vch.size() > 0) {
ret += strprintf("0x%x 0x%x ", HexStr(it2, it - vch.size()), HexStr(it - vch.size(), it));
} else {
ret += strprintf("0x%x ", HexStr(it2, it));
}
continue;
}
ret += strprintf("0x%x ", HexStr(it2, script.end()));
break;
}
return ret.substr(0, ret.size() - 1);
}
const map<unsigned char, string> mapSigHashTypes =
boost::assign::map_list_of
(static_cast<unsigned char>(SIGHASH_ALL), string("ALL"))
(static_cast<unsigned char>(SIGHASH_ALL|SIGHASH_ANYONECANPAY), string("ALL|ANYONECANPAY"))
(static_cast<unsigned char>(SIGHASH_NONE), string("NONE"))
(static_cast<unsigned char>(SIGHASH_NONE|SIGHASH_ANYONECANPAY), string("NONE|ANYONECANPAY"))
(static_cast<unsigned char>(SIGHASH_SINGLE), string("SINGLE"))
(static_cast<unsigned char>(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY), string("SINGLE|ANYONECANPAY"))
;
/**
* Create the assembly string representation of a CScript object.
* @param[in] script CScript object to convert into the asm string representation.
* @param[in] fAttemptSighashDecode Whether to attempt to decode sighash types on data within the script that matches the format
* of a signature. Only pass true for scripts you believe could contain signatures. For example,
* pass false, or omit the this argument (defaults to false), for scriptPubKeys.
*/
string ScriptToAsmStr(const CScript& script, const bool fAttemptSighashDecode)
{
string str;
opcodetype opcode;
vector<unsigned char> vch;
CScript::const_iterator pc = script.begin();
while (pc < script.end()) {
if (!str.empty()) {
str += " ";
}
if (!script.GetOp(pc, opcode, vch)) {
str += "[error]";
return str;
}
if (0 <= opcode && opcode <= OP_PUSHDATA4) {
if (vch.size() <= static_cast<vector<unsigned char>::size_type>(4)) {
str += strprintf("%d", CScriptNum(vch, false).getint());
} else {
// the IsUnspendable check makes sure not to try to decode OP_RETURN data that may match the format of a signature
if (fAttemptSighashDecode && !script.IsUnspendable()) {
string strSigHashDecode;
// goal: only attempt to decode a defined sighash type from data that looks like a signature within a scriptSig.
// this won't decode correctly formatted public keys in Pubkey or Multisig scripts due to
// the restrictions on the pubkey formats (see IsCompressedOrUncompressedPubKey) being incongruous with the
// checks in CheckSignatureEncoding.
if (CheckSignatureEncoding(vch, SCRIPT_VERIFY_STRICTENC, NULL)) {
const unsigned char chSigHashType = vch.back();
if (mapSigHashTypes.count(chSigHashType)) {
strSigHashDecode = "[" + mapSigHashTypes.find(chSigHashType)->second + "]";
vch.pop_back(); // remove the sighash type byte. it will be replaced by the decode.
}
}
str += HexStr(vch) + strSigHashDecode;
} else {
str += HexStr(vch);
}
}
} else {
str += GetOpName(opcode);
}
}
return str;
}
string EncodeHexTx(const CTransaction& tx)
{
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
return HexStr(ssTx.begin(), ssTx.end());
}
void ScriptPubKeyToUniv(const CScript& scriptPubKey,
UniValue& out, bool fIncludeHex)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.pushKV("asm", ScriptToAsmStr(scriptPubKey));
if (fIncludeHex)
out.pushKV("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {
out.pushKV("type", GetTxnOutputType(type));
return;
}
out.pushKV("reqSigs", nRequired);
out.pushKV("type", GetTxnOutputType(type));
UniValue a(UniValue::VARR);
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CEletaCoinAddress(addr).ToString());
out.pushKV("addresses", a);
}
void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry)
{
entry.pushKV("txid", tx.GetHash().GetHex());
entry.pushKV("version", tx.nVersion);
entry.pushKV("locktime", (int64_t)tx.nLockTime);
UniValue vin(UniValue::VARR);
BOOST_FOREACH(const CTxIn& txin, tx.vin) {
UniValue in(UniValue::VOBJ);
if (tx.IsCoinBase())
in.pushKV("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
else {
in.pushKV("txid", txin.prevout.hash.GetHex());
in.pushKV("vout", (int64_t)txin.prevout.n);
UniValue o(UniValue::VOBJ);
o.pushKV("asm", ScriptToAsmStr(txin.scriptSig, true));
o.pushKV("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
in.pushKV("scriptSig", o);
}
in.pushKV("sequence", (int64_t)txin.nSequence);
vin.push_back(in);
}
entry.pushKV("vin", vin);
UniValue vout(UniValue::VARR);
for (unsigned int i = 0; i < tx.vout.size(); i++) {
const CTxOut& txout = tx.vout[i];
UniValue out(UniValue::VOBJ);
UniValue outValue(UniValue::VNUM, FormatMoney(txout.nValue));
out.pushKV("value", outValue);
out.pushKV("n", (int64_t)i);
UniValue o(UniValue::VOBJ);
ScriptPubKeyToUniv(txout.scriptPubKey, o, true);
out.pushKV("scriptPubKey", o);
vout.push_back(out);
}
entry.pushKV("vout", vout);
if (!hashBlock.IsNull())
entry.pushKV("blockhash", hashBlock.GetHex());
entry.pushKV("hex", EncodeHexTx(tx)); // the hex-encoded transaction. used the name "hex" to be consistent with the verbose output of "getrawtransaction".
}
| [
"[email protected]"
] | |
9c125f406393c4a12f5ca023356aaee03d52f126 | 56b65fbf1880a8323ab7dc15c9694d5975d2cd2c | /src/crypto/sha256.h | d5c89a6da03ec1759045af8679e45059f00a6d7d | [
"MIT"
] | permissive | btclambo/BitcoinLambo | 3e4043e9486ea42401f7d38fc5d5ebbbb38b005e | fc823516765338f06bce5ad8c7e3a5d6fe90f22b | refs/heads/master | 2020-03-06T18:31:07.897658 | 2018-03-27T15:34:49 | 2018-03-27T15:34:49 | 127,008,721 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 836 | h | // Copyright (c) 2014-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOINLAMBO_CRYPTO_SHA256_H
#define BITCOINLAMBO_CRYPTO_SHA256_H
#include <stdint.h>
#include <stdlib.h>
#include <string>
/** A hasher class for SHA-256. */
class CSHA256
{
private:
uint32_t s[8];
unsigned char buf[64];
uint64_t bytes;
public:
static const size_t OUTPUT_SIZE = 32;
CSHA256();
CSHA256& Write(const unsigned char* data, size_t len);
void Finalize(unsigned char hash[OUTPUT_SIZE]);
CSHA256& Reset();
};
/** Autodetect the best available SHA256 implementation.
* Returns the name of the implementation.
*/
std::string SHA256AutoDetect();
#endif // BITCOINLAMBO_CRYPTO_SHA256_H
| [
"[email protected]"
] | |
8b620a29dcb24dbb05d38ad71a6517f2eb01d1ed | 2851759f8e9b36197858e9ae5307ea6239da5e2e | /system/ulib/fbl/include/fbl/unique_fd.h | d9e5b771e1ad96121de7e9468d57fe79181b6a28 | [
"BSD-3-Clause",
"MIT"
] | permissive | Allegra42/zircon | a1a809f005c04d4cf2af672c47a2f13161848ca0 | 50d20f11275ecdd47faa393e3ff6465cee07a670 | refs/heads/master | 2020-04-05T08:02:40.558430 | 2018-12-29T00:28:46 | 2018-12-29T23:42:27 | 156,698,935 | 1 | 1 | NOASSERTION | 2018-11-08T11:48:25 | 2018-11-08T11:48:24 | null | UTF-8 | C++ | false | false | 1,936 | h | // Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <stdlib.h>
#include <unistd.h>
#include <fbl/macros.h>
#include <fbl/type_support.h>
namespace fbl {
// A scoped file descriptor that automatically closes when it goes
// out of scope.
class unique_fd {
public:
constexpr unique_fd() : fd_(InvalidValue()) {}
explicit unique_fd(int fd) : fd_(fd) { }
static constexpr int InvalidValue() { return -1; }
~unique_fd() {
reset();
}
unique_fd(unique_fd&& o) : fd_(o.release()) {}
unique_fd& operator=(unique_fd&& o) {
reset(o.release());
return *this;
}
// Comparison against raw file descriptors (of the form fd == unique_fd)
bool operator==(int fd) const { return (fd_ == fd); }
bool operator!=(int fd) const { return (fd_ != fd); }
// Comparison against other unique_fd's.
bool operator==(const unique_fd& o) const { return fd_ == o.fd_; }
bool operator!=(const unique_fd& o) const { return fd_ != o.fd_; }
// move semantics only
DISALLOW_COPY_AND_ASSIGN_ALLOW_MOVE(unique_fd);
fbl::unique_fd duplicate() {
return fbl::unique_fd(dup(fd_));
}
int release() {
int t = fd_;
fd_ = InvalidValue();
return t;
}
void reset(int t = InvalidValue()) {
if (fd_ != InvalidValue()) {
close(fd_);
}
fd_ = t;
}
void swap(unique_fd& other) {
int t = fd_;
fd_ = other.fd_;
other.fd_ = t;
}
int get() const {
return fd_;
}
bool is_valid() const {
return fd_ != InvalidValue();
}
explicit operator bool() const {
return is_valid();
}
explicit operator int() const {
return fd_;
}
private:
int fd_;
};
} // namespace fbl
| [
"[email protected]"
] | |
898dcd49d9c180ed6870b8798b7d8230765e71e9 | 42e6482f57a8d3506987621607b5e9d2719c903e | /bo2k/scr/commandloop.cpp | 059fd317b2eaa3f6a8e3293e9bd28fdce003df58 | [] | no_license | baiyfcu/BO2K | 216ce061bea7cd2f5ad01e2eed3fb703adc5a3b4 | c9df1bf1def0005640ccd879d1a7c720ac237bf2 | refs/heads/master | 2020-03-21T19:29:52.886208 | 2018-03-01T16:48:53 | 2018-03-01T16:48:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,965 | cpp | /* Back Orifice 2000 - Remote Administration Suite
Copyright (C) 1999, Cult Of The Dead Cow
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
The author of this program may be contacted at [email protected]. */
#include<windows.h>
#include<auth.h>
#include<iohandler.h>
#include<encryption.h>
#include<bocomreg.h>
#include<commnet.h>
#include<commandloop.h>
#include<config.h>
// ---------------- Global variables ----------------
CIOHandler *g_pIOHandler;
CEncryptionHandler *g_pEncryptionHandler;
CAuthHandler *g_pAuthHandler;
CAuthSocket *g_pCommSock[MAX_COMMAND_SOCKETS];
CAuthSocket *g_pConnSock[MAX_COMMAND_CONNECTIONS];
int g_nCommCount, g_nConnCount;
#ifdef NDEBUG
char g_szStartupOptions[]= "<**CFG**>Startup\0"
"S[8]:Init Cmd Net Type=TCPIO\0\0\0\0"
"S[48]:Init Cmd Bind Str=\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"S[8]:Init Cmd Encryption=XOR\0\0\0\0\0\0"
"S[8]:Init Cmd Auth=NULLAUTH\0"
"N[0,5000000]:Idle Timeout (ms)=60000\0\0";
#else
char g_szStartupOptions[]= "<**CFG**>Startup\0"
"S[8]:Init Cmd Net Type=TCPIO\0\0\0\0"
"S[48]:Init Cmd Bind Str=54320\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
"S[8]:Init Cmd Encryption=XOR\0\0\0\0\0\0"
"S[8]:Init Cmd Auth=NULLAUTH\0"
"N[0,5000000]:Idle Timeout (ms)=60000\0\0";
#endif
BOOL g_bBO2KFinished; // Set this to -TRUE- when you want to exit BO2K
// ---------------- Function implementations --------------------
BOOL StartupCommandHandlers(void)
{
char svParam[256];
// Initialize primary command socket
g_nCommCount=0;
g_nConnCount=0;
svParam[0]='\0';
// Don't even start up unless user has configured a port to talk on.
// This keeps the 31337 phenomena from happening.
char *bindstr=GetCfgStr(g_szStartupOptions,"Init Cmd Bind Str");
if(bindstr==NULL) return FALSE;
if(bindstr[0]=='\0') {
return FALSE;
}
CAuthSocket *cas;
do {
cas=ListenAuthSocket(NULL,0,NULL,
bindstr,
GetCfgStr(g_szStartupOptions,"Init Cmd Net Type"),
GetCfgStr(g_szStartupOptions,"Init Cmd Encryption"),
GetCfgStr(g_szStartupOptions,"Init Cmd Auth"));
if(cas!=NULL && cas!=(CAuthSocket *)0xFFFFFFFF) {
g_pCommSock[g_nCommCount]=cas;
g_nCommCount++;
return TRUE;
}
Sleep(100);
} while(cas!=NULL && cas!=(CAuthSocket *)0xFFFFFFFF);
return FALSE;
}
void ShutdownCommandHandlers(void)
{
int i;
// Close all connections
for(i=0;i<g_nConnCount;i++) {
g_pConnSock[i]->Close();
delete g_pConnSock[i];
}
// Terminate all bound sockets
for(i=0;i<g_nCommCount;i++) {
g_pCommSock[i]->Close();
delete g_pCommSock[i];
}
}
void CommandHandlerLoop(void)
{
BYTE *buffer;
int buflen,ret,i,j;
DWORD dwLastTime,dwTimeout;
BOOL bIdle;
// Start the command handlers
if(StartupCommandHandlers()==FALSE) return;
// Lower Thread Priority
SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_NORMAL);
// Command handler loop
g_bBO2KFinished=FALSE;
dwLastTime=GetTickCount();
dwTimeout=GetCfgNum(g_szStartupOptions,"Idle Timeout (ms)");
bIdle=FALSE;
while(!g_bBO2KFinished) {
if(dwTimeout!=0) {
if(!bIdle && ((GetTickCount()-dwLastTime)>dwTimeout)) {
SetPriorityClass(GetCurrentProcess(),IDLE_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_IDLE);
bIdle=TRUE;
}
}
// Sift through bound sockets looking for connections
for(i=0; i<g_nCommCount; i++) {
CAuthSocket *cas;
cas=g_pCommSock[i]->Accept();
if(cas!=NULL) {
if(g_nConnCount<MAX_COMMAND_CONNECTIONS) {
dwLastTime=GetTickCount();
if(bIdle) {
SetPriorityClass(GetCurrentProcess(),NORMAL_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_NORMAL);
bIdle=FALSE;
}
g_pConnSock[g_nConnCount]=cas;
g_nConnCount++;
} else {
cas->Close();
delete cas;
}
}
}
// Sift through active connections pulling commands
// and removing dead connections
for(i=(g_nConnCount-1);i>=0;i--) {
ret=g_pConnSock[i]->Recv(&buffer,&buflen);
if(ret<0) {
// Must be dead. Kill.
g_pConnSock[i]->Close();
delete g_pConnSock[i];
for(j=i;j<(g_nConnCount-1);j++) {
g_pConnSock[j]=g_pConnSock[j+1];
}
g_pConnSock[j]=NULL;
g_nConnCount--;
}
else if(ret==0) {
// Nothing here, move along
}
else {
dwLastTime=GetTickCount();
if(bIdle) {
SetPriorityClass(GetCurrentProcess(),NORMAL_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread(),THREAD_PRIORITY_LOWEST);
bIdle=FALSE;
}
// Command received
int cmdlen,command,comid,nArg1;
char *svArg2,*svArg3;
BreakDownCommand(buffer, &cmdlen, &command, &comid, &nArg1, &svArg2, &svArg3);
if(cmdlen==buflen) {
DispatchCommand(command, g_pConnSock[i],comid,nArg1,svArg2,svArg3);
}
// Free command memory
g_pConnSock[i]->Free(buffer);
}
}
Sleep(20);
}
// Terminate command handlers
ShutdownCommandHandlers();
} | [
"[email protected]"
] | |
84d9589d708a257955fab86f2cd369d54fa8ce4f | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/c8/4c9d4860e87ead/main.cpp | f321f1de55152b95fdbf5c1b212e75d9f769aaa0 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 517 | cpp | #include <iostream>
#include <vector>
#include <map>
using namespace std;
typedef vector<int> PrefList;
typedef map<int, PrefList> PrefMap;
typedef multimap<int, int> Matching;
map<int, int> CHcapacity ={{1,1},{2,1},{3,1}};
PrefMap PrefCHLists = {{1,{5,4,6}},{2,{4,6,5}},{3,{4,5,6}}};
PrefMap PrefONLists = {{4,{2,1,3}},{5,{3,1,2}},{6,{1,3,2}}};
int main()
{
Matching match={{1,4},{2,5},{3,6}};
Matching final=RVV(match);
}
Matching RVV(Matching m){
Matching mT=m;
map<int, int> S;
return mT;
}
| [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
043a3853907dc3f6acecf6f7952a034ca8eaff94 | efd9e3980a2e8a131c1f1ab64a2f856b9d1bee6a | /libraries/ros_lib/diagnostic_msgs/KeyValue.h | 3c9e64edb91ec9c770dddbbb01ecf4bba842385d | [] | no_license | limhyon/arduimu | b520688a7132c147eb403473566a42dac719db50 | b6725463c98a77d3f912de3464921dd5483f8673 | refs/heads/master | 2021-01-19T06:06:33.769806 | 2012-07-24T06:40:21 | 2012-07-24T06:40:21 | 5,151,087 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,736 | h | #ifndef _ROS_diagnostic_msgs_KeyValue_h
#define _ROS_diagnostic_msgs_KeyValue_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros/msg.h"
namespace diagnostic_msgs
{
class KeyValue : public ros::Msg
{
public:
char * key;
char * value;
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
uint32_t * length_key = (uint32_t *)(outbuffer + offset);
*length_key = strlen( (const char*) this->key);
offset += 4;
memcpy(outbuffer + offset, this->key, *length_key);
offset += *length_key;
uint32_t * length_value = (uint32_t *)(outbuffer + offset);
*length_value = strlen( (const char*) this->value);
offset += 4;
memcpy(outbuffer + offset, this->value, *length_value);
offset += *length_value;
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
uint32_t length_key = *(uint32_t *)(inbuffer + offset);
offset += 4;
for(unsigned int k= offset; k< offset+length_key; ++k){
inbuffer[k-1]=inbuffer[k];
}
inbuffer[offset+length_key-1]=0;
this->key = (char *)(inbuffer + offset-1);
offset += length_key;
uint32_t length_value = *(uint32_t *)(inbuffer + offset);
offset += 4;
for(unsigned int k= offset; k< offset+length_value; ++k){
inbuffer[k-1]=inbuffer[k];
}
inbuffer[offset+length_value-1]=0;
this->value = (char *)(inbuffer + offset-1);
offset += length_value;
return offset;
}
const char * getType(){ return "diagnostic_msgs/KeyValue"; };
const char * getMD5(){ return "cf57fdc6617a881a88c16e768132149c"; };
};
}
#endif | [
"[email protected]"
] | |
b0371dbaf93a6e2ff33dcb6900bc8b6073b20fed | 8447d06d0d5da3db2b3aae926ec66409b38fb140 | /3rdPartLib/g2o/g2o/examples/slam2d/main_window.cpp | 0ad4e0d898354b1ea8b789f6efba1ee3a10d1379 | [
"GPL-3.0-or-later",
"LGPL-3.0-or-later",
"BSD-3-Clause",
"GPL-1.0-or-later",
"BSD-2-Clause"
] | permissive | HKPolyU-UAV/FLVIS | 60d0fecac6e10eb19a131d589a5c0ddf89198157 | 4ad31bbe5191ae2763c70a641c31337b1e06c9e2 | refs/heads/master | 2023-07-21T11:11:05.885918 | 2023-07-12T14:26:32 | 2023-07-12T14:26:32 | 197,144,164 | 145 | 37 | BSD-2-Clause | 2021-06-07T08:45:04 | 2019-07-16T07:33:55 | C++ | UTF-8 | C++ | false | false | 3,766 | cpp | // g2o - General Graph Optimization
// Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard
//
// This file is part of g2o.
//
// g2o is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// g2o is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with g2o. If not, see <http://www.gnu.org/licenses/>.
#include "main_window.h"
//#include "moc_main_window.cpp"
#include "g2o/core/sparse_optimizer.h"
#include "g2o/core/estimate_propagator.h"
#include <QFileDialog>
#include <fstream>
#include <iostream>
using namespace std;
MainWindow::MainWindow(QWidget * parent, Qt::WindowFlags flags) :
QMainWindow(parent, flags)
{
setupUi(this);
}
MainWindow::~MainWindow()
{
}
void MainWindow::on_actionLoad_triggered(bool)
{
viewer->graph->clear();
QString filename = QFileDialog::getOpenFileName(this, "Load g2o file", "", "g2o files (*.g2o);;All Files (*)");
if (! filename.isNull()) {
ifstream ifs(filename.toStdString().c_str());
viewer->graph->load(ifs);
cerr << "Graph loaded with " << viewer->graph->vertices().size() << " vertices and "
<< viewer->graph->edges().size() << " measurments" << endl;
}
viewer->update();
fixGraph();
}
void MainWindow::on_actionSave_triggered(bool)
{
QString filename = QFileDialog::getSaveFileName(this, "Save g2o file", "", "g2o files (*.g2o)");
if (! filename.isNull()) {
ofstream fout(filename.toStdString().c_str());
viewer->graph->save(fout);
if (fout.good())
cerr << "Saved " << filename.toStdString() << endl;
else
cerr << "Error while saving file" << endl;
}
}
void MainWindow::on_actionQuit_triggered(bool)
{
close();
}
void MainWindow::on_btnOptimize_clicked()
{
if (viewer->graph->vertices().size() == 0 || viewer->graph->edges().size() == 0) {
cerr << "Graph has no vertices / egdes" << endl;
return;
}
viewer->graph->initializeOptimization();
if (rbGauss->isChecked())
viewer->graph->setAlgorithm(solverGaussNewton);
else if (rbLevenberg->isChecked())
viewer->graph->setAlgorithm(solverLevenberg);
else
viewer->graph->setAlgorithm(solverGaussNewton);
int maxIterations = spIterations->value();
int iter = viewer->graph->optimize(maxIterations);
if (maxIterations > 0 && !iter){
cerr << "Optimization failed, result might be invalid" << endl;
}
if (cbCovariances->isChecked()) {
// TODO
//viewer->graph->solver()->computeMarginals();
}
viewer->drawCovariance = cbCovariances->isChecked();
viewer->update();
}
void MainWindow::on_btnInitialGuess_clicked()
{
viewer->graph->computeInitialGuess();
viewer->drawCovariance = false;
viewer->update();
}
void MainWindow::fixGraph()
{
if (viewer->graph->vertices().size() == 0 || viewer->graph->edges().size() == 0) {
return;
}
// check for vertices to fix to remove DoF
bool gaugeFreedom = viewer->graph->gaugeFreedom();
g2o::OptimizableGraph::Vertex* gauge = viewer->graph->findGauge();
if (gaugeFreedom) {
if (! gauge) {
cerr << "cannot find a vertex to fix in this thing" << endl;
return;
} else {
cerr << "graph is fixed by node " << gauge->id() << endl;
gauge->setFixed(true);
}
} else {
cerr << "graph is fixed by priors" << endl;
}
viewer->graph->setVerbose(true);
viewer->graph->computeActiveErrors();
}
| [
"[email protected]"
] | |
dc3c3dbaaa7ce3efd8d3e50bca316d84ccbd7a33 | 3047545349bf224a182b2c33bf1f110aef1ce9b6 | /Transims60/GridData/Write_Summary.cpp | 9eed25f328727f3dde90b319e5bf9567f94864f1 | [] | no_license | qingswu/Transim | 585afe71d9666557cff53f6683cf54348294954c | f182d1639a4db612dd7b43a379a3fa344c2de9ea | refs/heads/master | 2021-01-10T21:04:50.576267 | 2015-04-08T19:07:28 | 2015-04-08T19:07:28 | 35,232,171 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,573 | cpp | //*********************************************************
// Write_Summary.cpp - Write the New Summary File
//*********************************************************
#include "GridData.hpp"
//---------------------------------------------------------
// Write_Summary
//---------------------------------------------------------
void GridData::Write_Summary ()
{
int i, j, count;
Summary_Itr sum_itr;
Range_Array_Itr range_itr;
Dbls_Itr dbls_itr;
Dbl_Itr data_itr;
count = 0;
Show_Message (2, String ("Writing %s -- Record") % summary_file.File_Type ());
Set_Progress ();
for (sum_itr = summary_array.begin (); sum_itr != summary_array.end (); sum_itr++) {
Show_Progress ();
summary_file.Put_Field (0, sum_itr->group);
summary_file.Put_Field (1, sum_itr->field_name);
dbls_itr = sum_itr->data_array.begin ();
for (i=0, range_itr = sum_itr->select_values.begin (); range_itr != sum_itr->select_values.end (); range_itr++, dbls_itr++, i++) {
summary_file.Put_Field (2, range_itr->Low ());
summary_file.Put_Field (3, range_itr->High ());
summary_file.Put_Field (4, sum_itr->grid_counts [i]);
for (j=data_offset, data_itr = dbls_itr->begin (); data_itr != dbls_itr->end (); data_itr++, j++) {
summary_file.Put_Field (j, *data_itr);
}
if (!summary_file.Write ()) {
Error (String ("Writing %s") % summary_file.File_Type ());
}
count++;
}
}
End_Progress ();
summary_file.Close ();
Print (1);
Write (1, "Number of Summary Records Written = ") << count;
}
| [
"davidroden@7728d46c-9721-0410-b1ea-f014b4b56054"
] | davidroden@7728d46c-9721-0410-b1ea-f014b4b56054 |
2c2c448a1761a7c240a35e6418b63c42d0432e29 | 556f83e394cd722ec5cc852e69adb12d2a0c78d1 | /code/TimePredef.hpp | a937e3b194a031c85bb48b95452398a2cd876d61 | [
"MIT"
] | permissive | BiEchi/Programming-Assignment-1 | aee2b506483fe34c242ff3468af7a48d88705edc | 1d340ee27d7177062215e60dc4666ee72cb91dd2 | refs/heads/main | 2023-04-26T02:14:54.398342 | 2021-05-27T10:58:33 | 2021-05-27T10:58:33 | 368,122,637 | 1 | 0 | MIT | 2021-05-17T09:07:25 | 2021-05-17T09:07:24 | null | UTF-8 | C++ | false | false | 266 | hpp | //
// TimePredef.hpp
// code
//
// Created by Jack's Macbook Pro on 2021/3/25.
//
#ifndef TimePredef_hpp
#define TimePredef_hpp
#include <iostream>
#include <cstring>
#include <ctime>
using namespace std;
extern time_t startTime;
#endif /* TimePredef_hpp */
| [
"[email protected]"
] | |
73bf4e0f6fbdf976be867badea6ddbefe469dacc | f69cec4bcba5618871d0eb21c94f62070e6208f1 | /Exams/2021.2.09/C.cpp | 526a6a18ab153d275821994e858a87b70d50a986 | [] | no_license | accoder666/temp | 10204075f7081b7e25bd858df3b9f7d258779d7b | b38dcb9a45282503541c5fdb79d2f066ce2736c1 | refs/heads/main | 2023-07-02T17:14:37.053741 | 2021-08-11T03:31:44 | 2021-08-11T03:31:44 | 394,850,718 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,808 | cpp | #include <cctype>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1000010, sigma_size = 26;
struct node {
int len, link;
int nxt[sigma_size];
};
node t[maxn << 1];
int cnt, last;
int siz[maxn << 1];
struct edge {
int to, nxt;
};
edge G[maxn << 1];
int head[maxn << 1], Gcnt;
long long dfs(const int&);
int main() {
freopen("sub.in", "r", stdin);
freopen("sub.out", "w", stdout);
t[0].len = 0, t[0].link = -1, last = 0;
char ch = getchar();
while (!islower(ch)) ch = getchar();
int cur, u, v, c;
while (islower(ch)) {
t[cur = ++cnt].len = t[last].len + 1;
siz[cur] = 1;
u = last;
while (u != -1 && !t[u].nxt[ch - 'a']) t[u].nxt[ch - 'a'] = cur, u = t[u].link;
if (u == -1)
t[cur].link = 0;
else {
v = t[u].nxt[ch - 'a'];
if (t[u].len + 1 == t[v].len)
t[cur].link = v;
else {
c = ++cnt;
t[c].len = t[u].len + 1;
t[c].link = t[v].link;
memcpy(t[c].nxt, t[v].nxt, sizeof(t[c].nxt));
while (u != -1 && t[u].nxt[ch - 'a'] == v) t[u].nxt[ch - 'a'] = c, u = t[u].link;
t[v].link = t[cur].link = c;
}
}
last = cur;
ch = getchar();
}
for (int i = 1; i <= cnt; i++) G[++Gcnt] = { i, head[t[i].link] }, head[t[i].link] = Gcnt;
printf("%lld\n", dfs(0));
return 0;
}
long long dfs(const int& u) {
long long ret = 0, tmp;
for (int i = head[u]; i; i = G[i].nxt) {
if ((tmp = dfs(G[i].to)) > ret)
ret = tmp;
siz[u] += siz[G[i].to];
}
if (siz[u] != 1 && ret < (long long)siz[u] * t[u].len)
ret = (long long)siz[u] * t[u].len;
return ret;
}
| [
"[email protected]"
] | |
501844de141de05c90c316318bcc0518f613db88 | 4122acc5bd9ee517fdfd1307bf8a04cc7c95599c | /mindspore/lite/src/ops/populate/common_populate.cc | 8255473969877758af39d56eb1260e012a3b3039 | [
"Apache-2.0",
"MIT",
"Libpng",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.1-only",
"AGPL-3.0-only",
"MPL-2.0-no-copyleft-exception",
"IJG",
"Zlib",
"MPL-1.1",
"BSD-3-Clause",
"BSD-3-Clause-Open-MPI",
"MPL-1.0",
"GPL-2.0-only",
"MPL-2.0",
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | limberc/mindspore | 655bb4fc582a85711e70c31e12f611cf1a0f422e | e294acdffc9246cb6d77ea18ea00d08244d30c59 | refs/heads/master | 2023-02-18T20:10:22.588348 | 2021-01-23T15:33:01 | 2021-01-23T15:33:01 | 322,821,027 | 0 | 0 | Apache-2.0 | 2021-01-18T14:07:45 | 2020-12-19T10:27:43 | null | UTF-8 | C++ | false | false | 1,248 | cc | /**
* Copyright 2019-2020 Huawei Technologies Co., Ltd
*
* 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 "src/ops/primitive_c.h"
#include "src/ops/populate/populate_register.h"
namespace mindspore {
namespace lite {
OpParameter *PopulateCommonParameter(const mindspore::lite::PrimitiveC *primitive) {
auto *common_parameter = reinterpret_cast<OpParameter *>(malloc(sizeof(OpParameter)));
if (common_parameter == nullptr) {
MS_LOG(ERROR) << "malloc OpParameter failed.";
return nullptr;
}
memset(common_parameter, 0, sizeof(OpParameter));
return common_parameter;
}
Registry ZerosLikeParameterRegistry(schema::PrimitiveType_ZerosLike, PopulateCommonParameter);
} // namespace lite
} // namespace mindspore
| [
"[email protected]"
] | |
1d5d9ed7db6942bd48206e99fe56c4dc4ad4c19d | e5f57aae37a480cf40180d0a5664aaab5a0c0341 | /vaca/Component.cpp | a5ec932ebb891f3811b06b8dfed1d899b11ca0bc | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | TheLightWay/vaca | 6ddabf0cd12a46583b03cddc99d2b13da87a4e41 | 95728e6a5c41d9fe2c731f7767b7334b623f41ed | refs/heads/master | 2023-06-10T09:47:28.085286 | 2023-04-12T02:52:15 | 2023-04-12T02:52:15 | 149,952,301 | 0 | 0 | MIT | 2018-09-23T05:56:48 | 2018-09-23T05:56:48 | null | UTF-8 | C++ | false | false | 1,609 | cpp | // Vaca - Visual Application Components Abstraction
// Copyright (c) 2005-2010 David Capello
//
// This file is distributed under the terms of the MIT license,
// please read LICENSE.txt for more information.
#include "vaca/Component.h"
#include "vaca/SharedPtr.h"
#include "vaca/Property.h"
#include "vaca/Debug.h"
using namespace vaca;
/**
Creates a new component.
With the debug version of the library, you will get in the
@ref page_debug_log a line specifying when the component
was created.
*/
Component::Component()
{
VACA_TRACE("new Component (%p)\n", this);
}
/**
Destroys the component.
With the debug version of the library, you will get in the
@ref page_debug_log a line specifying when the component
was destroyed.
*/
Component::~Component()
{
VACA_TRACE("delete Component (%p)\n", this);
}
PropertyPtr Component::getProperty(const String& name)
{
Properties::iterator it = m_properties.find(name);
if (it != m_properties.end())
return it->second;
else
return PropertyPtr();
}
void Component::setProperty(PropertyPtr property)
{
m_properties[property->getName()] = property;
}
bool Component::hasProperty(const String& name)
{
Properties::iterator it = m_properties.find(name);
return it != m_properties.end();
}
void Component::removeProperty(const String& name)
{
Properties::iterator it = m_properties.find(name);
if (it != m_properties.end())
m_properties.erase(it);
}
const Component::Properties& Component::getProperties() const
{
return m_properties;
}
| [
"[email protected]"
] | |
923877562aab22dd4dee8024f595fac6143df562 | 834abb946ce963e5922f1b683ac027fa4c6d9fe2 | /Project2/JeffGrockowskiProject2.cpp | fab5df755ebf54a7bc1f244e5b30e66e669c13f1 | [] | no_license | JeffGrock/BMI_calculator | 1cb1f082bf41d7650258b4d7dd614e4ac17f8d4e | 6e0b3a67d5c8c60d7fad2472611003732ce8fb35 | refs/heads/main | 2023-03-12T05:00:00.642667 | 2021-02-25T18:11:06 | 2021-02-25T18:11:06 | 342,336,090 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,087 | cpp | // Author: Jeff Grockowski
// Date: 06/10/2019
// CSCI 121 project 2
// Program allows user to calculate BMI, and the amount chocolate they can eat.
#include <iostream>
#include <string>
using namespace std;
int main() {
int const chocolateBarCal(230);
int weight, height, age;
double BMR, cBarsPerBMI;
string gender("A"), repeat("Y");
while((repeat == "Y") || (repeat == "y")) // While loop for entire program,
{ // allows user to repeat program until user changes the "repeat" variable through input at the end of the program
cout << "Welcome to my BMR calculator!\n";
cout << "Gender (M or F):";
cin >> gender;
while ((gender != "F") && (gender != "M") && (gender != "m") && (gender != "f")) // loop to ensure user entry matches one of the two BMI equations
{
cout << "invalid gender.\n";
cout << "Gender (M or F):";
cin >> gender;
}
cout << "Age (In years):"; // this block obtains the rest of the variables for BMR equation,
cin >> age; // this information pertains to both genders
cout << "Weight (in pounds):";
cin >> weight;
cout << "Height (In inches):";
cin >> height;
cout << endl;
if ((gender == "M") || (gender == "m")) // if else structure calculates the BMR and tells user the result based on gender input
{ // the else block is the female calculation
BMR = 66 + (6.3 * weight) + (12.9 * height) - (6.8 * age);
cBarsPerBMI = BMR / chocolateBarCal;
cout << "He needs " << BMR << " calories to maintain his weight.\n";
}
else
{
BMR = 655 + (4.3 * weight) + (4.7 * height) - (4.7 * age);
cBarsPerBMI = BMR / chocolateBarCal;
cout << "She needs " << BMR << " calories to maintain her weight.\n";
}
cout << "that is about " << cBarsPerBMI << " Chocolate bar's calories!\n"; // this block tells user the chocolate bars worth of BMI
cout << "would you like to do another calculation? (Y or N): "; // also confirms if user would like to recalculate.
cin >> repeat;
cout << endl;
}
cout << "Thanks for using my BMR calculator, Good Bye!\n";
return 0;
} | [
"[email protected]"
] | |
8562389987847c12a04e6b03c90970f9e416eded | cfa83be88b6725d9c88d780e08b6392a346f2e15 | /cs4290/lab2/memory.h | d1d3f0371b21e842b8d23fe36cdd3dcab1048860 | [] | no_license | eugene-voronkov/architecture_projects | 63a04babd711ecc4c5ce7eb7d79604282b162f3c | bb3d5c97ca93affdb471c4ac03509792ff3004c0 | refs/heads/master | 2021-01-21T08:09:06.740624 | 2016-01-05T17:06:34 | 2016-01-05T17:06:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,609 | h | #ifndef MEMORY_H
#define MEMORY_H
#include<list>
#include<queue>
#include "knob.h"
#include "all_knobs.h"
typedef enum Mem_Req_State_enum {
MEM_INV,
MEM_NEW,
MEM_DRAM_IN,
MEM_DRAM_SCH,
MEM_DRAM_DONE,
MEM_DRAM_OUT,
MEM_MAX_REQ_STATE,
} Mem_Req_State;
typedef enum Mem_Req_Type_enum {
MRT_IFETCH,
MRT_DFETCH,
MRT_DSTORE,
MRT_IPRF,
MRT_DPRF,
MRT_WB,
MRT_SW_DPRF,
MAX_MEM_REQ_TYPE,
} Mem_Req_Type;
typedef struct mem_req_s {
Mem_Req_State m_state; /**< memory request state */
Mem_Req_Type m_type; /**< request type */
ADDRINT m_addr; /**< request address */
uint8_t m_size; /**< request size */
uint64_t m_rdy_cycle; /**< request ready cycle */
bool m_dirty; /**< wb request? */
bool m_done; /**< request done flag */
uint64_t m_id; /**< unique request id */
} mem_req_s;
typedef struct m_mshr_entry_s {
mem_req_s *m_mem_req;
bool valid;
UINT64 insert_time;
list<Op*> req_ops; /* array to hold request ops */
}m_mshr_entry_s;
typedef struct m_dram_s {
int m_bank_num;
int *m_row_id;
int *m_rdy_cycle;
}m_dram_s;
class memory_c {
public:
list <m_mshr_entry_s *> m_mshr; // mshr is an array of mshr_entries
list <m_mshr_entry_s *> m_mshr_free_list; // a collection of free mshr_entries
int m_mshr_size;
int m_dram_bank_num;
int m_block_size;
uint64_t m_unique_m_count;
list <mem_req_s *> dram_in_queue; /* in to DRAM */
list <mem_req_s *> dram_out_queue; /*out from DRAM */
/* dram structure */
list <mem_req_s *>* dram_bank_sch_queue; /* scheduler buffer for each DRAM bank */
int *dram_bank_open_row;
int *dram_bank_rdy_cycle;
m_mshr_entry_s * allocate_new_mshr_entry(void);
mem_req_s *get_new_mem_req(void);
void run_a_cycle(void);
void send_bus_in_queue(void);
void dram_schedule(void);
void push_dram_sch_queue(void);
void send_bus_out_queue(void);
void fill_queue(void);
void init_mem();
bool insert_mshr(Op *op);
void free_mshr_entry(m_mshr_entry_s *entry);
m_mshr_entry_s *search_matching_mshr(ADDRINT addr);
list<m_mshr_entry_s*>::iterator search_matching_mshr_itr(ADDRINT addr);
bool check_piggyback(Op *op);
bool store_load_forwarding(Op *op);
void dprint_queues(void);
void dprint_dram_banks(void);
};
extern KnobsContainer *g_knobsContainer; /* < knob container > */
extern all_knobs_c *g_knobs; /* < all knob variables > */
#endif // MEMORY_H
| [
"[email protected]"
] | |
5b0beb00db96cfd62ad6b017f92a9c5a0ee268d5 | 2de8f5ba729a846f8ad5630272dd5b1f3b7b6e44 | /src/Core/Gpackets/SS/GCSkillToTileOK3.h | 9a747d26de9e96edf4d3f383d9b0bb936842e1c3 | [] | no_license | najosky/darkeden-v2-serverfiles | dc0f90381404953e3716bf71320a619eb10c3825 | 6e0015f5b8b658697228128543ea145a1fc4c559 | refs/heads/master | 2021-10-09T13:01:42.843224 | 2018-12-24T15:01:52 | 2018-12-24T15:01:52 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 4,894 | h | //////////////////////////////////////////////////////////////////////
//
// Filename : GCSkillToTileOK3.h
// Written By : [email protected]
// Description : 기술 사용자는 볼수 있고, 당한자는 볼 수 없는 패킷
//
//////////////////////////////////////////////////////////////////////
#ifndef __GC_SKILL_TO_TILE_OK_3_H__
#define __GC_SKILL_TO_TILE_OK_3_H__
// include files
#include "Types.h"
#include "Exception.h"
#include "Packet.h"
#include "PacketFactory.h"
//////////////////////////////////////////////////////////////////////
//
// class GCSkillToTileOK3;
//
// 게임서버에서 클라이언트로 자신의 기술이 성공을 알려주기 위한 클래스
//
//////////////////////////////////////////////////////////////////////
class GCSkillToTileOK3 : public Packet {
public :
// constructor
GCSkillToTileOK3() throw();
// destructor
~GCSkillToTileOK3() throw();
public :
// 입력스트림(버퍼)으로부터 데이타를 읽어서 패킷을 초기화한다.
void read(SocketInputStream & iStream) throw(ProtocolException, Error);
// 출력스트림(버퍼)으로 패킷의 바이너리 이미지를 보낸다.
void write(SocketOutputStream & oStream) const throw(ProtocolException, Error);
// execute packet's handler
void execute(Player* pPlayer) throw(ProtocolException, Error);
// get packet id
PacketID_t getPacketID() const throw() { return PACKET_GC_SKILL_TO_TILE_OK_3; }
// get packet's body size
// 최적화시, 미리 계산된 정수를 사용한다.
// PacketSize_t getPacketSize() const throw() { return szSkillType + szObjectID +(szCoord* 2)
// + szDuration + szBYTE + szObjectID* m_CListNum; }
PacketSize_t getPacketSize() const throw() { return szSkillType + szObjectID +(szCoord* 2) + szBYTE;}
// get packet's name
string getPacketName() const throw() { return "GCSkillToTileOK3"; }
// get packet's debug string
string toString() const throw();
// get / set ObjectID
CEffectID_t getObjectID() const throw() { return m_ObjectID; }
void setObjectID(ObjectID_t ObjectID) throw() { m_ObjectID = ObjectID; }
// get / set SkillType
SkillType_t getSkillType() const throw() { return m_SkillType; }
void setSkillType(SkillType_t SkillType) throw() { m_SkillType = SkillType; }
// get / set Duration
// Duration_t getDuration() const throw() { return m_Duration; }
// void setDuration(Duration_t Duration) throw() { m_Duration = Duration; }
// get / set X, Y
Coord_t getX() { return m_X; }
void setX(Coord_t X) { m_X = X; }
Coord_t getY() { return m_Y; }
void setY(Coord_t Y) { m_Y = Y; }
// get / set Creature List Number
// BYTE getCListNum() const throw() { return m_CListNum; }
// void setCListNum(BYTE CListNum) throw() { m_CListNum = CListNum; }
// add / delete Creature List
// void addCListElement(ObjectID_t ObjectID) throw();
// Clear CreatureList
// void clearCList() throw() { m_CList.clear(); m_CListNum = 0; }
// pop front Element in Status List
// ObjectID_t popCListElement() throw() { ObjectID_t CreatureList = m_CList.front(); m_CList.pop_front(); return CreatureList; }
BYTE getGrade() const { return m_Grade; }
void setGrade( BYTE grade ) { m_Grade = grade; }
private :
// CEffectID
ObjectID_t m_ObjectID;
// SkillType
SkillType_t m_SkillType;
// Duration
// Duration_t m_Duration;
// X, Y Position
Coord_t m_X;
Coord_t m_Y;
// CreatureList Element Number
// BYTE m_CListNum;
// Creature List
// list<ObjectID_t> m_CList;
BYTE m_Grade;
};
//////////////////////////////////////////////////////////////////////
//
// class GCSkillToTileOK3Factory;
//
// Factory for GCSkillToTileOK3
//
//////////////////////////////////////////////////////////////////////
class GCSkillToTileOK3Factory : public PacketFactory {
public :
// constructor
GCSkillToTileOK3Factory() throw() {}
// destructor
virtual ~GCSkillToTileOK3Factory() throw() {}
public :
// create packet
Packet* createPacket() throw() { return new GCSkillToTileOK3(); }
// get packet name
string getPacketName() const throw() { return "GCSkillToTileOK3"; }
// get packet id
PacketID_t getPacketID() const throw() { return Packet::PACKET_GC_SKILL_TO_TILE_OK_3; }
// get Packet Max Size
// PacketSize_t getPacketMaxSize() const throw() { return szSkillType + szObjectID +(szCoord* 2)
// + szDuration + szBYTE + szObjectID + 255; }
// get Packet Max Size
PacketSize_t getPacketMaxSize() const throw() { return szSkillType + szObjectID +(szCoord* 2) + szBYTE; }
};
//////////////////////////////////////////////////////////////////////
//
// class GCSkillToTileOK3Handler;
//
//////////////////////////////////////////////////////////////////////
class GCSkillToTileOK3Handler {
public :
// execute packet's handler
static void execute(GCSkillToTileOK3* pGCSkillToTileOK3, Player* pPlayer) throw(Error);
};
#endif
| [
"[email protected]"
] | |
d20ba589794b48efbaef3d6c5034d2548ae2dee6 | aead066f3cfa3491e1c3d4b6b4189a7e08868ff6 | /src/socket/Connection.h | f92c747469761752a08cca5c9daccba19bb1a132 | [] | no_license | thushear/AsyncWebServer | e0547954189d1911fd0f37c7a9bdd9a5ed507ebf | 05f02f73fb45a85a83659515b8e78b602beef103 | refs/heads/master | 2021-01-18T23:52:48.480570 | 2015-06-02T08:51:42 | 2015-06-02T08:51:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,658 | h | //
// Created by plter on 5/21/15.
//
#pragma once
#include <boost/asio/ip/tcp.hpp>
#include "ConnectionManager.h"
#include "Buffer.h"
namespace aws {
class ConnectionManager;
class OnSocketListener;
class Connection :public std::enable_shared_from_this<aws::Connection>{
friend class ServerSocket;
friend class ConnectionManager;
public:
typedef std::shared_ptr<aws::Connection> ConnectionPtr;
typedef std::function<void(ConnectionPtr socket,aws::InputBuffer & buffer,std::size_t bytes_transferred)> OnReceiveHandler;
private:
Connection(std::shared_ptr<boost::asio::ip::tcp::socket> asioSocket);
static std::shared_ptr<aws::Connection> create(std::shared_ptr<boost::asio::ip::tcp::socket> asioSocket_);
public:
virtual ~Connection();
public:
std::shared_ptr<boost::asio::ip::tcp::socket> getAsioSocket();
void start();
void close();
inline bool isClosed(){
return !running_;
}
public://set/get functions
inline void setConnectionManager(std::shared_ptr<aws::ConnectionManager> manager){
connection_manager_ = manager;
}
inline std::shared_ptr<aws::ConnectionManager> getConnectionManager(){
return connection_manager_;
}
inline void setOnCloseHandler(std::function<void(std::shared_ptr<aws::Connection> socket)> handler){
onCloseHandler_ = handler;
}
inline std::function<void(std::shared_ptr<aws::Connection> socket)> getOnCloseHandler(){
return onCloseHandler_;
}
inline void setOnConnectHandler(std::function<void(std::shared_ptr<aws::Connection> socket)> handler){
onConnectHandler_ = handler;
}
inline std::function<void(std::shared_ptr<aws::Connection> socket)> getOnConnectHandler(){
return onConnectHandler_;
}
inline void setOnReceiveHandler(OnReceiveHandler handler){
onReceiveHandler_ = handler;
}
inline OnReceiveHandler getOnReceiveHandler(){
return onReceiveHandler_;
}
protected:
void onClose();
void onConnect();
private:
void do_receive();
private:
std::shared_ptr<boost::asio::ip::tcp::socket> asioSocket_;
aws::InputBuffer buffer_;
std::shared_ptr<aws::ConnectionManager> connection_manager_;
bool running_;
std::function<void(ConnectionPtr socket)> onCloseHandler_;
std::function<void(ConnectionPtr socket)> onConnectHandler_;
OnReceiveHandler onReceiveHandler_;
};
}
| [
"[email protected]"
] | |
da17ec3176d8e7c8124f6fcf644569f7dda673f1 | a42195c736f18bec131f719288994d849d49593a | /packed_sphere.cpp | 80e44f1d12d56014524ed03e4a17b280c9925370 | [
"MIT"
] | permissive | rishus/fat-spaces-in-sphere-arrangement | 20966c3bd01435d2b2a83853553ba91863d3d5bf | 6ef5b6dc22fdcb724226bcb23a5c1649b39a6bdb | refs/heads/master | 2021-08-18T19:58:25.737951 | 2017-11-23T18:36:32 | 2017-11-23T18:36:32 | 111,831,860 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 374 | cpp | #include <iostream>
#include <math.h>
using namespace std;
int main()
{
int side = 4;
for(int i = 0; i < side; ++i)
{
for(int j = 0; j < side; ++j)
{
for(int k = 0; k < side; ++k)
{
double x = 2 * i + j%2 + k%2;
double y = sqrt(3.0) * (j + ((1.0/3.0) * (k%2)));
double z = (2 * sqrt(6))/3.0 * k;
cout<<x<<" "<<y<<" "<<z<<endl;
}
}
}
}
| [
"[email protected]"
] | |
0f2cca11331527142c6a81af499eab6dc7be0635 | 776426915cb19273095dc9d8ad583d6847add5d4 | /robot.cpp | aed800642b344117c1036f7ff20b3031aef98f1b | [] | no_license | imharsh94/ALGO-DS | 28832c9f843ee5a22463557c3493976399ad33cc | b9c131a2248c86da10f8df23606fdaef509c2d10 | refs/heads/master | 2020-08-11T21:22:37.082594 | 2019-10-12T10:37:32 | 2019-10-12T10:37:32 | 214,629,394 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 734 | cpp | // codeforces educational round 53
#include<bits/stdc++.h>
using namespace std;
char s[200008];
int sx[200008],sy[200008];
int main()
{
int n,i,j,x,y,k;
cin>>n;
scanf("%s",s+1);
cin>>x>>y;
if(abs(x)+abs(y) > n ||(n+x+y)&1)
{
cout<<-1<<'\n';
return 0;
}
for(int i=1; i<=n; i++)
{
sx[i] = sx[i-1] + (s[i]=='L'?-1:(s[i]=='R'?1:0));
sy[i] = sy[i-1] + (s[i]=='D'?-1:(s[i]=='U'?1:0));
}
int ans = 1<<30;
for(int i=0,j=0; i<=n; i++)
{
while(j<=n && abs(sx[i]+sx[n]-sx[j]-x)+abs(sy[i]+sy[n]-sy[j]-y)>j-i)
j++;
if(j<=n)
ans = min(ans,j-i);
else
break;
}
cout<<ans<<endl;
return 0;
} | [
"[email protected]"
] | |
bfb7ae2786f011cc2fd99384f16177aee94ff618 | 6ce4add532471bb49d199ea632ed4af377735e38 | /blif_solve_lib/log.h | fa5bf5edd6cca5ca7459ce83e78115a458214950 | [
"MIT"
] | permissive | appu226/FactorGraph | 398688f188876eba27a67f327f97e8f0002f856d | b7cf6025339247b0d89740540a813097ca32774e | refs/heads/master | 2023-08-17T15:07:21.512438 | 2023-06-18T17:22:11 | 2023-06-18T17:22:11 | 164,322,621 | 0 | 1 | MIT | 2023-02-12T21:49:24 | 2019-01-06T15:59:51 | C++ | UTF-8 | C++ | false | false | 2,199 | h | /*
Copyright 2019 Parakram Majumdar
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.
*/
#pragma once
#include <iostream>
#include <ctime>
namespace blif_solve {
// Verbosity for logging
enum Verbosity {
QUIET,
ERROR,
WARNING,
INFO,
DEBUG
};
Verbosity getVerbosity();
void setVerbosity(Verbosity verbosity);
Verbosity parseVerbosity(const std::string & verbosity_string);
#define blif_solve_log(verbosity, message) \
if (blif_solve::getVerbosity() >= blif_solve::verbosity) \
{ \
std::cout << "[" << #verbosity << "] " << message << std::endl; \
}
#define blif_solve_log_bdd(verbosity, message, ddm, bdd) \
if (blif_solve::getVerbosity() >= blif_solve::verbosity) \
{ \
std::cout << "[" << #verbosity << "] " << message << std::endl; \
bdd_print_minterms(ddm, bdd); \
}
// ****** Function *******
// duration
// takes a start and end chrono time
// and returns the duration in seconds as a double
// ***********************
template<typename T>
double duration(T const & start)
{
return static_cast<double>(std::clock() - start)/CLOCKS_PER_SEC;
}
inline auto now()
{
return std::clock();
}
} // end namespace blif_solve
| [
"[email protected]"
] | |
d5fa083e493cb7915d62f1634c4714ae1d76e8a8 | 48070285a8c93a24b4e568c3a45eade50838e6d2 | /Example/Lua/BindAbstract.cpp | 9975360a71a909180dd2603519c656878b8a9059 | [
"MIT"
] | permissive | ternence-li/LightInkLLM | 8a3c54d4664e0cf64a454c7f8bd22fb4c434adff | b4387398b4ce45be0bc2d79ea38d93b81609f7c8 | refs/heads/master | 2021-09-21T23:23:09.357179 | 2018-09-02T17:27:49 | 2018-09-02T17:27:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,043 | cpp |
/* Copyright ChenDong(Wilbur), email <[email protected]>. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "LuaEngine/LuaEngine.h"
class CppClassAbs
{
public:
CppClassAbs() { LogMessage("new CppClassAbs"); }
virtual ~CppClassAbs() { LogMessage("delete CppClassAbs"); }
virtual void test_abstract() = 0;
};
class CppClassAbsInherit : public CppClassAbs
{
public:
CppClassAbsInherit() { LogMessage("new CppClassAbsInherit"); }
virtual ~CppClassAbsInherit() { LogMessage("delete CppClassAbsInherit"); }
virtual void test_abstract() { LogMessage("call --> virtual void CppClassAbsInherit.test_abstract()"); }
static LightInk::SharedPtrTS<CppClassAbs>::type get_shared() { return LightInk::SharedPtrTS<CppClassAbs>::type(static_cast<CppClassAbs *>(new CppClassAbsInherit)); }
static void check_shared(LightInk::SharedPtrTS<CppClassAbs>::type sp) { LogMessage("SharedPtrTS Use Count = {}", sp.use_count()); }
static int show_class_name(lua_State * L) { LogMessage("ClassName = {}", LightInk::LuaEngine::get_class_name(L, 1)); return 0; }
};
static void bind_cppclass(lua_State * lua)
{
LightInk::LuaModule(lua, "CppClassList")
[
LightInk::LuaRegisterAbstract<CppClassAbs>(lua, "CppClassAbs")
.def(&CppClassAbs::test_abstract, "test_abstract")
];
LightInk::LuaModule(lua, "CppClassList")
[
LightInk::LuaRegister<CppClassAbsInherit, void()>(lua, "CppClassAbsInherit", LightInk::BaseClassStrategy<CppClassAbs>())
.def(CppClassAbsInherit::get_shared, "get_shared")
.def(CppClassAbsInherit::check_shared, "check_shared")
.def(CppClassAbsInherit::show_class_name, "show_class_name")
];
}
void test_bind_abstract()
{
LogDebug("start...call...test_bind_abstract()");
LightInk::LuaEngine le;
le.init();
le.register_module(bind_cppclass);
le.add_package_path("../../Example/Lua/?.lua");
le.require_file("BindAbstract");
LogDebug("over...call...test_bind_abstract()");
} | [
"[email protected]"
] | |
b12965d715e6284202ba24cf0b677891f1f54dfc | 12154201c2c4dc8968b690fa8237ebfe1932f60a | /SWEA/1232.cpp | 2338641229460152f36e0dd2c7ef0b68a8baaa42 | [] | no_license | heon24500/PS | 9cc028de3d9b1a26543b5bd498cfd5134d3d6de4 | df901f6fc71f8c9d659b4c5397d44de9a2031a9d | refs/heads/master | 2023-02-20T17:06:30.065944 | 2021-01-25T12:43:48 | 2021-01-25T12:43:48 | 268,433,390 | 2 | 0 | null | null | null | null | UHC | C++ | false | false | 1,359 | cpp | /* 1232. [S/W 문제해결 기본] 9일차 - 사칙연산 */
#include <iostream>
#include <string>
#include <stack>
using namespace std;
const int N = 1001;
int tree[N][2];
string ops[N];
stack<int> s;
void init()
{
for (int i = 0; i < N; i++) {
tree[i][0] = 0;
tree[i][1] = 0;
ops[i] = "";
}
while (!s.empty()) {
s.pop();
}
}
bool isOperator(string str)
{
char ch = str[0];
if (ch == '+' || ch == '-' || ch == '*' || ch == '/') return true;
else return false;
}
int calc(string str)
{
char ch = str[0];
int b = s.top();
s.pop();
int a = s.top();
s.pop();
if (ch == '+') {
return a + b;
}
else if (ch == '-') {
return a - b;
}
else if (ch == '*') {
return a * b;
}
else if (ch == '/') {
return a / b;
}
}
void postorder(int t)
{
if (t == 0) return;
postorder(tree[t][0]);
postorder(tree[t][1]);
string str = ops[t];
int result;
if (isOperator(str)) result = calc(str);
else result = stoi(str);
s.push(result);
}
int main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
for (int t = 1; t <= 10; t++) {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
int num;
cin >> num;
cin >> ops[num];
if (isOperator(ops[num])) {
cin >> tree[num][0] >> tree[num][1];
}
}
postorder(1);
cout << "#" << t << " " << s.top() << '\n';
init();
}
return 0;
} | [
"[email protected]"
] | |
811f9d505b013c247c52a12ed78859c1477c84e1 | d47bcf95da7cf618d826abbdafd55d15610d3bd9 | /switch.cpp | 65d1cabd4e4fa57bc0cdfca0fe6f9b927c149696 | [] | no_license | gchacaltana/Sintaxis-C-CPP-A-Search-Algorithm | d6f03ac7421717dd52f7d40b71e7a5692aa7d818 | a694538d0aa18d5ed0a16fe22b920dccfa12bd5f | refs/heads/master | 2020-08-22T18:00:18.503785 | 2019-10-21T03:17:39 | 2019-10-21T03:17:39 | 216,453,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,320 | cpp | #include <iostream>
#include <string>
using namespace std;
char mostrar_opciones(string, string, string);
int main()
{
char r1, r2;
r1 = mostrar_opciones("¿Cómo es la tasa de producción de lágrimas?","[R]educida","[N]ormal");
switch(r1)
{
case 'R':
r2 = mostrar_opciones("¿Tiene astigmatismo?","[S]í","[N]o");
switch(r2)
{
case 'S':
cout << "Tipo de lentes: suaves"; break;
case 'N':
cout << "Tipo de lentes: rígidos"; break;
default:
cout << "Fin";
}
break;
case 'N':
cout << "Tipo de lentes: no requiere"; break;
default:
cout << "Fin";
}
return 0;
}
char mostrar_opciones(string pregunta, string opcion_A, string opcion_B)
{
char respuesta;
char r_a = opcion_A[1];
char r_b = opcion_B[1];
do{
cout << pregunta << endl;
cout << opcion_A << endl;
cout << opcion_B << endl;
cout << "Salir [x]" << endl;
cin >> respuesta;
}
while(respuesta != r_a && respuesta != r_b && respuesta != 'x');
return respuesta;
}
| [
"[email protected]"
] | |
19685e5b5a22d7397dc9a822a611b3ff326ebeaa | fa85329dbe03772df56547375154c5437ff2b076 | /Zero_L/alfa/Mapa.h | fcb75d70277662fc2f59fdca83186436e309b06b | [
"Apache-2.0"
] | permissive | Ninefrm/Unsingned | 9597f3c3cf1c422adbbcbf36a41d0b97aa71aa9a | cf051f6aa6c9d93f8582539b2d36c64a41447a58 | refs/heads/master | 2021-08-24T05:07:38.657326 | 2017-12-08T05:12:47 | 2017-12-08T05:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,119 | h | #ifndef _MAPA_H_
#define _MAPA_H_
#include <vector>
#include <random>
#include <curses.h>
#include <ctime>
#include "Obj.h"
#include "Wall.h"
#include "Character.h"
#include "Enemy.h"
#include "Sword.h"
class Mapa{
public:
Mapa();
Mapa(Character* , std::vector<Wall>, int, int);
bool wall_colision() const;//Verifica si el jugador colisiona con alguo de los muros
bool wall_colision(int, int) const;//Verifica si la posicion (x, y) colisiona con alguno de los muros
bool outside() const;
bool enemys_colision();
bool enemys_colision(const Obj&, int);
bool enemys_colision(const Sword espada);
void generate_enemy();
void move_enemys();
void move_agresive();
void draw_walls();//Dibuja los muros
void draw_enemys();
private:
int rows;
int cols;
std::mt19937 motor;
std::uniform_int_distribution<int> rand_x;
std::uniform_int_distribution<int> rand_y;
std::uniform_int_distribution<int> rand_mov;
std::vector<Wall> walls;
Character* player;
Enemy enemys;
bool inside;
};
#endif
| [
"[email protected]"
] | |
f1fad2bbbe0c6384744e3e4d8b6a39763f25265e | 8352ca72d4f1e8e8ebbbb7d6b07a4e0963be7f41 | /DataServer/DataServer_TIP/TA_BASE/transactive/app/dataserver/CFDServer/src/SyncMarketDataForCFD.h | 9693e02c5a07a2cd8b5f126f5e638848b1dda5f0 | [] | no_license | radtek/slin_code | 114f61695fc1a23a018da727452c3c42f64ebe39 | a0073e52d600839f7836c2b7673b45b4266259e2 | refs/heads/master | 2020-06-04T15:03:56.618177 | 2015-04-27T10:27:47 | 2015-04-27T10:27:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,429 | h | #ifndef __CLASS_SYNC_MARKET_DATA_FOR_CFD_H__
#define __CLASS_SYNC_MARKET_DATA_FOR_CFD_H__
#include "CFDServerCommonData.h"
#include "BarCalculator.h"
#include "CFDRequest.h"
NS_BEGIN(TA_Base_App)
class CCFDServerUtilityFun;
class CCFDInstrumentBarInfo;
class CSyncMarketDataForCFD
{
public:
enum enSynType
{
SynType_BEGIN,
SynType_EQUAL,
SynType_SMALL,
SynType_BIGGER,
SynType_END,
};
enum enNextWorkType
{
NextWorkType_BEGIN,
NextWorkType_UseNewFirst_UseNewSecond,
NextWorkType_UseNewFirst_ReUseSecond,
NextWorkType_ReUseFirst_UseNewSecond,
NextWorkType_END,
};
public:
typedef std::list<CCFDInstrumentBarInfo*> LstCFDBarInfoT;
typedef std::list<CCFDInstrumentBarInfo*>::iterator LstCFDBarInfoIterT;
typedef std::list<MarketData*> LstBarInfoT;
typedef std::list<MarketData*>::iterator LstBarInfoIterT;
public:
CSyncMarketDataForCFD(const CCFDRequest& cfdRequest);
~CSyncMarketDataForCFD(void);
public:
void setCFDRequest(const CCFDRequest& cfdRequest);
int syncSingleCFDBarInfo(
const MarketData& nBarInfoFirst,
const MarketData& nBarInfoSecond,
LstCFDBarInfoT& lstCFDbarInfo,
enNextWorkType& nNextWorkType);
int clearCFDBarInfoList(LstCFDBarInfoT& lstCFDbarInfo);
private:
int _SyncSingleBarInfo(
const MarketData& nBarInfoFirst,
const MarketData& nBarInfoSecond,
LstBarInfoT& lstBarInfoFirst,
LstBarInfoT& lstBarInfoSecond,
enNextWorkType& nNextWorkType);
int _ClearBarInfoList(LstBarInfoT& lstBarInfo);
private:
int _SyncLstCFDBarInfo(LstBarInfoT& lstBarInfoFirst, LstBarInfoT& lstBarInfoSecond, LstCFDBarInfoT& lstCFDBarInfo);
int _SyncSingleBarInfoSynType( enSynType nSynType, const MarketData& nBarInfoFirst, const MarketData& nBarInfoSecond, LstBarInfoT& lstBarInfoFirst, LstBarInfoT& lstBarInfoSecond);
int _SyncSingleBarInfoSynTypeEqual( enSynType nSynType, const MarketData& nBarInfoFirst, const MarketData& nBarInfoSecond, LstBarInfoT& lstBarInfoFirst, LstBarInfoT& lstBarInfoSecond);
int _SyncSingleBarInfoSynTypeSmall( enSynType nSynType, const MarketData& nBarInfoFirst, const MarketData& nBarInfoSecond, LstBarInfoT& lstBarInfoFirst, LstBarInfoT& lstBarInfoSecond);
private:
CCFDServerUtilityFun* m_pUtilityFun;
CCFDRequest m_CFDRequest;
};
NS_END(TA_Base_App)
#endif // __CLASS_SYNC_MARKET_DATA_FOR_CFD_H__
| [
"[email protected]"
] | |
cb3a5e079c958bd59ae282cd6932723fa1a3975e | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/shell/ext/timewarp/util.cpp | 979e0bc3df4d8aa6f3a602d7b2a4ddb2afec932c | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 9,065 | cpp | #include "precomp.hxx"
#pragma hdrstop
#include <winnlsp.h> // NORM_STOP_ON_NULL
#include "resource.h"
#include "timewarp.h"
#include "util.h"
DWORD FormatString(LPWSTR *ppszResult, HINSTANCE hInstance, LPCWSTR pszFormat, ...)
{
DWORD dwResult;
va_list args;
LPWSTR pszFormatAlloc = NULL;
if (IS_INTRESOURCE(pszFormat))
{
if (LoadStringAlloc(&pszFormatAlloc, hInstance, PtrToUlong(pszFormat)))
{
pszFormat = pszFormatAlloc;
}
else
{
return 0;
}
}
va_start(args, pszFormat);
dwResult = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_STRING,
pszFormat,
0,
0,
(LPWSTR)ppszResult,
1,
&args);
va_end(args);
LocalFree(pszFormatAlloc);
return dwResult;
}
HRESULT FormatFriendlyDateName(LPWSTR *ppszResult, LPCWSTR pszName, const FILETIME UNALIGNED *pft, DWORD dwDateFlags)
{
WCHAR szDate[MAX_PATH];
SHFormatDateTime(pft, &dwDateFlags, szDate, ARRAYSIZE(szDate));
if (!FormatString(ppszResult, g_hInstance, MAKEINTRESOURCE(IDS_FOLDER_TITLE_FORMAT), pszName, szDate))
{
DWORD dwErr = GetLastError();
return HRESULT_FROM_WIN32(dwErr);
}
return S_OK;
}
void EliminateGMTPathSegment(LPWSTR pszPath)
{
LPWSTR pszGMT = wcsstr(pszPath, SNAPSHOT_MARKER);
if (pszGMT)
{
ASSERT(pszGMT >= pszPath && pszGMT < (pszPath + lstrlenW(pszPath)));
// It's tempting to just say "pszGMT + SNAPSHOT_NAME_LENGTH" here, but
// we might miss an intervening '\0' on a malformed path.
LPWSTR pszSeparator = wcschr(pszGMT, L'\\');
if (pszSeparator)
{
ASSERT(pszSeparator == pszGMT + SNAPSHOT_NAME_LENGTH);
ASSERT(pszSeparator < (pszGMT + lstrlenW(pszGMT)));
pszSeparator++; // skip '\\'
MoveMemory(pszGMT, pszSeparator, (lstrlenW(pszSeparator)+1)*sizeof(WCHAR));
}
else
{
// Truncate here
*pszGMT = L'\0';
// Remove the previous separator if we can
PathRemoveBackslashW(pszPath);
}
}
}
void EliminatePathPrefix(LPWSTR pszPath)
{
// Note that sometimes the "\\?\" is not at the beginning of the
// path. See CTimeWarpProp::_OnView in twprop.cpp.
LPWSTR pszPrefix = wcsstr(pszPath, L"\\\\?\\");
if (pszPrefix)
{
LPWSTR pszDest;
LPWSTR pszSrc;
ASSERT(pszPrefix >= pszPath && pszPrefix < (pszPath + lstrlenW(pszPath)));
if (CSTR_EQUAL == CompareStringW(LOCALE_SYSTEM_DEFAULT,
SORT_STRINGSORT | NORM_IGNORECASE | NORM_STOP_ON_NULL,
pszPrefix+4, 4,
L"UNC\\", 4))
{
// UNC case: preserve the 2 leading backslashes
pszDest = pszPrefix + 2;
pszSrc = pszPrefix + 8;
}
else
{
pszDest = pszPrefix;
pszSrc = pszPrefix + 4;
}
ASSERT(pszDest >= pszPath && pszSrc > pszDest && pszSrc <= (pszPath + lstrlenW(pszPath)));
MoveMemory(pszDest, pszSrc, (lstrlenW(pszSrc)+1)*sizeof(WCHAR));
}
}
HRESULT GetFSIDListFromTimeWarpPath(PIDLIST_ABSOLUTE *ppidlTarget, LPCWSTR pszPath, DWORD dwFileAttributes)
{
HRESULT hr;
LPWSTR pszDup;
hr = SHStrDup(pszPath, &pszDup);
if (SUCCEEDED(hr))
{
// Note that SHSimpleIDListFromPath (which is exported from shell32)
// is not good enough here. It always uses 0 for attributes, but
// we usually need FILE_ATTRIBUTE_DIRECTORY here.
EliminateGMTPathSegment(pszDup);
hr = SimpleIDListFromAttributes(pszDup, dwFileAttributes, ppidlTarget);
LocalFree(pszDup);
}
return hr;
}
class CFileSysBindData : public IFileSystemBindData
{
public:
CFileSysBindData();
// *** IUnknown methods ***
STDMETHODIMP QueryInterface(REFIID riid, void **ppvObj);
STDMETHODIMP_(ULONG) AddRef(void);
STDMETHODIMP_(ULONG) Release(void);
// IFileSystemBindData
STDMETHODIMP SetFindData(const WIN32_FIND_DATAW *pfd);
STDMETHODIMP GetFindData(WIN32_FIND_DATAW *pfd);
private:
~CFileSysBindData();
LONG _cRef;
WIN32_FIND_DATAW _fd;
};
CFileSysBindData::CFileSysBindData() : _cRef(1)
{
ZeroMemory(&_fd, sizeof(_fd));
}
CFileSysBindData::~CFileSysBindData()
{
}
HRESULT CFileSysBindData::QueryInterface(REFIID riid, void **ppv)
{
static const QITAB qit[] = {
QITABENT(CFileSysBindData, IFileSystemBindData), // IID_IFileSystemBindData
{ 0 },
};
return QISearch(this, qit, riid, ppv);
}
STDMETHODIMP_(ULONG) CFileSysBindData::AddRef(void)
{
return InterlockedIncrement(&_cRef);
}
STDMETHODIMP_(ULONG) CFileSysBindData::Release()
{
ASSERT( 0 != _cRef );
ULONG cRef = InterlockedDecrement(&_cRef);
if ( 0 == cRef )
{
delete this;
}
return cRef;
}
HRESULT CFileSysBindData::SetFindData(const WIN32_FIND_DATAW *pfd)
{
_fd = *pfd;
return S_OK;
}
HRESULT CFileSysBindData::GetFindData(WIN32_FIND_DATAW *pfd)
{
*pfd = _fd;
return S_OK;
}
STDAPI SHCreateFileSysBindCtx(const WIN32_FIND_DATAW *pfd, IBindCtx **ppbc)
{
HRESULT hres;
IFileSystemBindData *pfsbd = new CFileSysBindData();
if (pfsbd)
{
if (pfd)
{
pfsbd->SetFindData(pfd);
}
hres = CreateBindCtx(0, ppbc);
if (SUCCEEDED(hres))
{
BIND_OPTS bo = {sizeof(bo)}; // Requires size filled in.
bo.grfMode = STGM_CREATE;
(*ppbc)->SetBindOptions(&bo);
(*ppbc)->RegisterObjectParam(STR_FILE_SYS_BIND_DATA, pfsbd);
}
pfsbd->Release();
}
else
{
*ppbc = NULL;
hres = E_OUTOFMEMORY;
}
return hres;
}
STDAPI SHSimpleIDListFromFindData(LPCWSTR pszPath, const WIN32_FIND_DATAW *pfd, PIDLIST_ABSOLUTE *ppidl)
{
*ppidl = NULL;
IBindCtx *pbc;
HRESULT hr = SHCreateFileSysBindCtx(pfd, &pbc);
if (SUCCEEDED(hr))
{
hr = SHParseDisplayName(pszPath, pbc, ppidl, 0, NULL);
pbc->Release();
}
return hr;
}
STDAPI SimpleIDListFromAttributes(LPCWSTR pszPath, DWORD dwAttributes, PIDLIST_ABSOLUTE *ppidl)
{
WIN32_FIND_DATAW fd = {0};
fd.dwFileAttributes = dwAttributes;
// SHCreateFSIDList(pszPath, &fd, ppidl);
return SHSimpleIDListFromFindData(pszPath, &fd, ppidl);
}
//*************************************************************
//
// SizeofStringResource
//
// Purpose: Find the length (in chars) of a string resource
//
// Parameters: HINSTANCE hInstance - module containing the string
// UINT idStr - ID of string
//
//
// Return: UINT - # of chars in string, not including NULL
//
// Notes: Based on code from user32.
//
//*************************************************************
UINT
SizeofStringResource(HINSTANCE hInstance, UINT idStr)
{
UINT cch = 0;
HRSRC hRes = FindResource(hInstance, (LPTSTR)((LONG_PTR)(((USHORT)idStr >> 4) + 1)), RT_STRING);
if (NULL != hRes)
{
HGLOBAL hStringSeg = LoadResource(hInstance, hRes);
if (NULL != hStringSeg)
{
LPWSTR psz = (LPWSTR)LockResource(hStringSeg);
if (NULL != psz)
{
idStr &= 0x0F;
while(true)
{
cch = *psz++;
if (idStr-- == 0)
break;
psz += cch;
}
}
}
}
return cch;
}
//*************************************************************
//
// LoadStringAlloc
//
// Purpose: Loads a string resource into an alloc'd buffer
//
// Parameters: ppszResult - string resource returned here
// hInstance - module to load string from
// idStr - string resource ID
//
// Return: same as LoadString
//
// Notes: On successful return, the caller must
// LocalFree *ppszResult
//
//*************************************************************
int
LoadStringAlloc(LPWSTR *ppszResult, HINSTANCE hInstance, UINT idStr)
{
int nResult = 0;
UINT cch = SizeofStringResource(hInstance, idStr);
if (cch)
{
cch++; // for NULL
*ppszResult = (LPWSTR)LocalAlloc(LPTR, cch * sizeof(WCHAR));
if (*ppszResult)
nResult = LoadString(hInstance, idStr, *ppszResult, cch);
}
return nResult;
}
| [
"[email protected]"
] | |
d41cee16d53ba621cc3ee717d9856782a1494c4a | dc9c6f34e15ae60cdecd503117334f5db2276ecd | /065_LC_76_minimumWindowSubstring.cpp | 1dc93d6013584627bd685f0e98f479aa08130792 | [] | no_license | z2z23n0/Algorithm | 43c669958972b73dab95adf8314bbf219690c4d2 | 6582688bd387b2bb04eb39bafa58e0180f665bb4 | refs/heads/master | 2022-06-09T22:43:25.914800 | 2020-05-07T16:27:03 | 2020-05-08T16:27:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,360 | cpp | //
// Created by Zeno on 2020/5/2.
//
class Solution {
public:
string minWindow(string s, string t) {
int start = 0; // record the beginning of the minium substring
int minLen = INT_MAX;
int left = 0, right = 0;
int match = 0; // record the match number between window and needs
unordered_map<char, int> window;
unordered_map<char, int> needs;
for (char c : t) {
needs[c]++;
}
// first, move right to very right
// if match == needs.size(), move left to right until match < needs.size()
while (right < s.size()) {
char c1 = s[right];
if (needs.count(c1)) {
window[c1]++;
if (window[c1] == needs[c1]) {
match++;
}
}
right++;
while (match == needs.size()) {
if (right - left < minLen) {
start = left;
minLen = right - left;
}
char c2 = s[left];
if (needs.count(c2)) {
window[c2]--;
if (window[c2] < needs[c2])
match--;
}
left++;
}
}
return minLen == INT_MAX ? "" : s.substr(start, minLen);
}
}; | [
"[email protected]"
] | |
39b97ce9f5501590918e6b55e5e29616e6b88809 | bbe7671fd0218f4f53082aa29eaf8d4137d1b505 | /cpp/hello/main.cpp | bbce233c482568dafe9aa3a06261570c71b8c916 | [] | no_license | b4rb4tron/projecten | da8650a694860b1e259fafd423eb249f7b2625cf | 59f6a94a3b253ec1e9ac63d8ce31cbf493be887f | refs/heads/master | 2021-07-06T07:22:11.864197 | 2018-10-25T09:51:43 | 2018-10-25T09:51:43 | 133,808,041 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 144 | cpp | #include <iostream>
#include "test.h"
using namespace std;
int main()
{
cout << "Hello world!" << endl;
test newtest;
return 0;
}
| [
"[email protected]"
] | |
c502dd86625144c3753bcfca74e13a6eaa6a8977 | 5cf90b2be2f265e7f02144192dba4a26cef15756 | /skia/tests/TessellatingPathRendererTests.cpp | 9af45ee51e8d70b41d0fe0dc35cb4c618a578be3 | [
"BSD-3-Clause",
"MIT"
] | permissive | jiangkang/renderer-dog | b73f1d1d0d5d61ea9a5da81983eeb536d6d791da | 8081732e2b4dbdb97c8d1f5e23f9e52c6362ff85 | refs/heads/master | 2021-07-07T21:49:57.293616 | 2020-09-13T16:31:34 | 2020-09-13T16:31:34 | 174,357,799 | 0 | 0 | MIT | 2020-09-13T11:08:16 | 2019-03-07T14:18:53 | C++ | UTF-8 | C++ | false | false | 31,181 | cpp | /*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "GrClip.h"
#include "GrContext.h"
#include "GrContextPriv.h"
#include "GrShape.h"
#include "GrStyle.h"
#include "SkGradientShader.h"
#include "SkPath.h"
#include "SkShaderBase.h"
#include "effects/GrPorterDuffXferProcessor.h"
#include "ops/GrTessellatingPathRenderer.h"
/*
* These tests pass by not crashing, hanging or asserting in Debug.
*/
// Tests active edges made inactive by splitting.
// Also tests active edge list forced into an invalid ordering by
// splitting (mopped up in cleanup_active_edges()).
static SkPath create_path_0() {
SkPath path;
path.moveTo(229.127044677734375f, 67.34100341796875f);
path.lineTo(187.8097381591796875f, -6.7729740142822265625f);
path.lineTo(171.411407470703125f, 50.94266510009765625f);
path.lineTo(245.5253753662109375f, 9.6253643035888671875f);
path.moveTo(208.4683990478515625f, 30.284009933471679688f);
path.lineTo(171.411407470703125f, 50.94266510009765625f);
path.lineTo(187.8097381591796875f, -6.7729740142822265625f);
return path;
}
// Intersections which fall exactly on the current vertex, and require
// a restart of the intersection checking.
static SkPath create_path_1() {
SkPath path;
path.moveTo(314.483551025390625f, 486.246002197265625f);
path.lineTo(385.41949462890625f, 532.8087158203125f);
path.lineTo(373.232879638671875f, 474.05938720703125f);
path.lineTo(326.670166015625f, 544.995361328125f);
path.moveTo(349.951507568359375f, 509.52734375f);
path.lineTo(373.232879638671875f, 474.05938720703125f);
path.lineTo(385.41949462890625f, 532.8087158203125f);
return path;
}
// Tests active edges which are removed by splitting.
static SkPath create_path_2() {
SkPath path;
path.moveTo(343.107391357421875f, 613.62176513671875f);
path.lineTo(426.632415771484375f, 628.5740966796875f);
path.lineTo(392.3460693359375f, 579.33544921875f);
path.lineTo(377.39373779296875f, 662.86041259765625f);
path.moveTo(384.869873046875f, 621.097900390625f);
path.lineTo(392.3460693359375f, 579.33544921875f);
path.lineTo(426.632415771484375f, 628.5740966796875f);
return path;
}
// Collinear edges merged in set_top().
// Also, an intersection between left and right enclosing edges which
// falls above the current vertex.
static SkPath create_path_3() {
SkPath path;
path.moveTo(545.95751953125f, 791.69854736328125f);
path.lineTo(612.05816650390625f, 738.494140625f);
path.lineTo(552.4056396484375f, 732.0460205078125f);
path.lineTo(605.61004638671875f, 798.14666748046875f);
path.moveTo(579.00787353515625f, 765.0963134765625f);
path.lineTo(552.4056396484375f, 732.0460205078125f);
path.lineTo(612.05816650390625f, 738.494140625f);
return path;
}
// Tests active edges which are made inactive by set_top().
static SkPath create_path_4() {
SkPath path;
path.moveTo(819.2725830078125f, 751.77447509765625f);
path.lineTo(820.70904541015625f, 666.933837890625f);
path.lineTo(777.57049560546875f, 708.63592529296875f);
path.lineTo(862.4111328125f, 710.0723876953125f);
path.moveTo(819.99078369140625f, 709.3541259765625f);
path.lineTo(777.57049560546875f, 708.63592529296875f);
path.lineTo(820.70904541015625f, 666.933837890625f);
return path;
}
static SkPath create_path_5() {
SkPath path;
path.moveTo(823.33209228515625f, 749.052734375f);
path.lineTo(823.494873046875f, 664.20013427734375f);
path.lineTo(780.9871826171875f, 706.5450439453125f);
path.lineTo(865.8397216796875f, 706.70782470703125f);
path.moveTo(823.4134521484375f, 706.6263427734375f);
path.lineTo(780.9871826171875f, 706.5450439453125f);
path.lineTo(823.494873046875f, 664.20013427734375f);
return path;
}
static SkPath create_path_6() {
SkPath path;
path.moveTo(954.862548828125f, 562.8349609375f);
path.lineTo(899.32818603515625f, 498.679443359375f);
path.lineTo(895.017578125f, 558.52435302734375f);
path.lineTo(959.17315673828125f, 502.990081787109375f);
path.moveTo(927.0953369140625f, 530.7572021484375f);
path.lineTo(895.017578125f, 558.52435302734375f);
path.lineTo(899.32818603515625f, 498.679443359375f);
return path;
}
static SkPath create_path_7() {
SkPath path;
path.moveTo(958.5330810546875f, 547.35516357421875f);
path.lineTo(899.93109130859375f, 485.989013671875f);
path.lineTo(898.54901123046875f, 545.97308349609375f);
path.lineTo(959.9151611328125f, 487.37109375f);
path.moveTo(929.2320556640625f, 516.67205810546875f);
path.lineTo(898.54901123046875f, 545.97308349609375f);
path.lineTo(899.93109130859375f, 485.989013671875f);
return path;
}
static SkPath create_path_8() {
SkPath path;
path.moveTo(389.8609619140625f, 369.326873779296875f);
path.lineTo(470.6290283203125f, 395.33697509765625f);
path.lineTo(443.250030517578125f, 341.9478759765625f);
path.lineTo(417.239959716796875f, 422.7159423828125f);
path.moveTo(430.244964599609375f, 382.3319091796875f);
path.lineTo(443.250030517578125f, 341.9478759765625f);
path.lineTo(470.6290283203125f, 395.33697509765625f);
return path;
}
static SkPath create_path_9() {
SkPath path;
path.moveTo(20, 20);
path.lineTo(50, 80);
path.lineTo(20, 80);
path.moveTo(80, 50);
path.lineTo(50, 50);
path.lineTo(20, 50);
return path;
}
static SkPath create_path_10() {
SkPath path;
path.moveTo(257.19439697265625f, 320.876617431640625f);
path.lineTo(190.113037109375f, 320.58978271484375f);
path.lineTo(203.64404296875f, 293.8145751953125f);
path.moveTo(203.357177734375f, 360.896026611328125f);
path.lineTo(216.88824462890625f, 334.120819091796875f);
path.lineTo(230.41925048828125f, 307.345611572265625f);
return path;
}
// A degenerate segments case, where both upper and lower segments of
// a split edge must remain active.
static SkPath create_path_11() {
SkPath path;
path.moveTo(231.9331207275390625f, 306.2012939453125f);
path.lineTo(191.4859161376953125f, 306.04547119140625f);
path.lineTo(231.0659332275390625f, 300.2642822265625f);
path.moveTo(189.946807861328125f, 302.072265625f);
path.lineTo(179.79705810546875f, 294.859771728515625f);
path.lineTo(191.0016021728515625f, 296.165679931640625f);
path.moveTo(150.8942108154296875f, 304.900146484375f);
path.lineTo(179.708892822265625f, 297.849029541015625f);
path.lineTo(190.4742279052734375f, 299.11895751953125f);
return path;
}
// Handle the case where edge.dist(edge.fTop) != 0.0.
static SkPath create_path_12() {
SkPath path;
path.moveTo( 0.0f, 400.0f);
path.lineTo( 138.0f, 202.0f);
path.lineTo( 0.0f, 202.0f);
path.moveTo( 12.62693023681640625f, 250.57464599609375f);
path.lineTo( 8.13896942138671875f, 254.556884765625f);
path.lineTo(-18.15641021728515625f, 220.40203857421875f);
path.lineTo(-15.986493110656738281f, 219.6513519287109375f);
path.moveTo( 36.931194305419921875f, 282.485504150390625f);
path.lineTo( 15.617521286010742188f, 261.2901611328125f);
path.lineTo( 10.3829498291015625f, 252.565765380859375f);
path.lineTo(-16.165292739868164062f, 222.646026611328125f);
return path;
}
// A degenerate segments case which exercises inactive edges being
// made active by splitting.
static SkPath create_path_13() {
SkPath path;
path.moveTo(690.62127685546875f, 509.25555419921875f);
path.lineTo(99.336181640625f, 511.71405029296875f);
path.lineTo(708.362548828125f, 512.4349365234375f);
path.lineTo(729.9940185546875f, 516.3114013671875f);
path.lineTo(738.708984375f, 518.76995849609375f);
path.lineTo(678.3463134765625f, 510.0819091796875f);
path.lineTo(681.21795654296875f, 504.81378173828125f);
path.moveTo(758.52764892578125f, 521.55963134765625f);
path.lineTo(719.1549072265625f, 514.50372314453125f);
path.lineTo(689.59063720703125f, 512.0628662109375f);
path.lineTo(679.78216552734375f, 507.447845458984375f);
return path;
}
// Tests vertices which become "orphaned" (ie., no connected edges)
// after simplification.
static SkPath create_path_14() {
SkPath path;
path.moveTo(217.326019287109375f, 166.4752960205078125f);
path.lineTo(226.279266357421875f, 170.929473876953125f);
path.lineTo(234.3973388671875f, 177.0623626708984375f);
path.lineTo(262.0921630859375f, 188.746124267578125f);
path.moveTo(196.23638916015625f, 174.0722198486328125f);
path.lineTo(416.15277099609375f, 180.138214111328125f);
path.lineTo(192.651947021484375f, 304.0228271484375f);
return path;
}
static SkPath create_path_15() {
SkPath path;
path.moveTo( 0.0f, 0.0f);
path.lineTo(10000.0f, 0.0f);
path.lineTo( 0.0f, -1.0f);
path.lineTo(10000.0f, 0.000001f);
path.lineTo( 0.0f, -30.0f);
return path;
}
// Reduction of Nebraska-StateSeal.svg. Floating point error causes the
// same edge to be added to more than one poly on the same side.
static SkPath create_path_16() {
SkPath path;
path.moveTo(170.8199920654296875, 491.86700439453125);
path.lineTo(173.7649993896484375, 489.7340087890625);
path.lineTo(174.1450958251953125, 498.545989990234375);
path.lineTo( 171.998992919921875, 500.88201904296875);
path.moveTo(168.2922515869140625, 498.66265869140625);
path.lineTo(169.8589935302734375, 497.94500732421875);
path.lineTo( 172, 500.88299560546875);
path.moveTo( 169.555267333984375, 490.70111083984375);
path.lineTo(173.7649993896484375, 489.7340087890625);
path.lineTo( 170.82000732421875, 491.86700439453125);
return path;
}
// A simple concave path. Test this with a non-invertible matrix.
static SkPath create_path_17() {
SkPath path;
path.moveTo(20, 20);
path.lineTo(80, 20);
path.lineTo(30, 30);
path.lineTo(20, 80);
return path;
}
// A shape with a vertex collinear to the right hand edge.
// This messes up find_enclosing_edges.
static SkPath create_path_18() {
SkPath path;
path.moveTo(80, 20);
path.lineTo(80, 60);
path.lineTo(20, 60);
path.moveTo(80, 50);
path.lineTo(80, 80);
path.lineTo(20, 80);
return path;
}
// Exercises the case where an edge becomes collinear with *two* of its
// adjacent neighbour edges after splitting.
// This is a reduction from
// http://mooooo.ooo/chebyshev-sine-approximation/horner_ulp.svg
static SkPath create_path_19() {
SkPath path;
path.moveTo( 351.99298095703125, 348.23046875);
path.lineTo( 351.91876220703125, 347.33984375);
path.lineTo( 351.91876220703125, 346.1953125);
path.lineTo( 351.90313720703125, 347.734375);
path.lineTo( 351.90313720703125, 346.1328125);
path.lineTo( 351.87579345703125, 347.93359375);
path.lineTo( 351.87579345703125, 345.484375);
path.lineTo( 351.86407470703125, 347.7890625);
path.lineTo( 351.86407470703125, 346.2109375);
path.lineTo( 351.84844970703125, 347.63763427734375);
path.lineTo( 351.84454345703125, 344.19232177734375);
path.lineTo( 351.78204345703125, 346.9483642578125);
path.lineTo( 351.758636474609375, 347.18310546875);
path.lineTo( 351.75469970703125, 346.75);
path.lineTo( 351.75469970703125, 345.46875);
path.lineTo( 352.5546875, 345.46875);
path.lineTo( 352.55078125, 347.01953125);
path.lineTo( 351.75079345703125, 347.02313232421875);
path.lineTo( 351.74688720703125, 346.15203857421875);
path.lineTo( 351.74688720703125, 347.646148681640625);
path.lineTo( 352.5390625, 346.94140625);
path.lineTo( 351.73907470703125, 346.94268798828125);
path.lineTo( 351.73516845703125, 344.48565673828125);
path.lineTo( 352.484375, 346.73828125);
path.lineTo( 351.68438720703125, 346.7401123046875);
path.lineTo( 352.4765625, 346.546875);
path.lineTo( 351.67657470703125, 346.54937744140625);
path.lineTo( 352.47265625, 346.75390625);
path.lineTo( 351.67266845703125, 346.756622314453125);
path.lineTo( 351.66876220703125, 345.612091064453125);
return path;
}
// An intersection above the first vertex in the mesh.
// Reduction from http://crbug.com/730687
static SkPath create_path_20() {
SkPath path;
path.moveTo( 2822128.5, 235.026336669921875);
path.lineTo( 2819349.25, 235.3623504638671875);
path.lineTo( -340558688, 23.83478546142578125);
path.lineTo( -340558752, 25.510419845581054688);
path.lineTo( -340558720, 27.18605804443359375);
return path;
}
// An intersection whose result is NaN (due to rounded-to-inf endpoint).
static SkPath create_path_21() {
SkPath path;
path.moveTo(1.7889142061167663539e+38, 39338463358011572224.0);
path.lineTo( 1647.4193115234375, -522.603515625);
path.lineTo( 1677.74560546875, -529.0028076171875);
path.lineTo( 1678.29541015625, -528.7847900390625);
path.lineTo( 1637.5167236328125, -519.79266357421875);
path.lineTo( 1647.4193115234375, -522.603515625);
return path;
}
// A path which contains out-of-range colinear intersections.
static SkPath create_path_23() {
SkPath path;
path.moveTo( 0, 63.39080047607421875);
path.lineTo(-0.70804601907730102539, 63.14350128173828125);
path.lineTo(-7.8608899287380243391e-17, 64.14080047607421875);
path.moveTo( 0, 64.14080047607421875);
path.lineTo(44.285900115966796875, 64.14080047607421875);
path.lineTo( 0, 62.64080047607421875);
path.moveTo(21.434900283813476562, -0.24732701480388641357);
path.lineTo(-0.70804601907730102539, 63.14350128173828125);
path.lineTo(0.70804601907730102539, 63.6381988525390625);
return path;
}
// A path which results in infs and nans when conics are converted to quads.
static SkPath create_path_24() {
SkPath path;
path.moveTo(-2.20883e+37f, -1.02892e+37f);
path.conicTo(-2.00958e+38f, -9.36107e+37f, -1.7887e+38f, -8.33215e+37f, 0.707107f);
path.conicTo(-1.56782e+38f, -7.30323e+37f, 2.20883e+37f, 1.02892e+37f, 0.707107f);
path.conicTo(2.00958e+38f, 9.36107e+37f, 1.7887e+38f, 8.33215e+37f, 0.707107f);
path.conicTo(1.56782e+38f, 7.30323e+37f, -2.20883e+37f, -1.02892e+37f, 0.707107f);
return path;
}
// An edge collapse event which also collapses a neighbour, requiring
// its event to be removed.
static SkPath create_path_25() {
SkPath path;
path.moveTo( 43.44110107421875, 148.15106201171875);
path.lineTo( 44.64471435546875, 148.16748046875);
path.lineTo( 46.35009765625, 147.403076171875);
path.lineTo( 46.45404052734375, 148.34906005859375);
path.lineTo( 45.0400390625, 148.54205322265625);
path.lineTo( 44.624053955078125, 148.9810791015625);
path.lineTo( 44.59405517578125, 149.16107177734375);
path.lineTo( 44.877044677734375, 149.62005615234375);
path.lineTo(144.373016357421875, 68.8070068359375);
return path;
}
// An edge collapse event causes an edge to become collinear, requiring
// its event to be removed.
static SkPath create_path_26() {
SkPath path;
path.moveTo( 43.44110107421875, 148.15106201171875);
path.lineTo( 44.64471435546875, 148.16748046875);
path.lineTo( 46.35009765625, 147.403076171875);
path.lineTo( 46.45404052734375, 148.34906005859375);
path.lineTo( 45.0400390625, 148.54205322265625);
path.lineTo( 44.624053955078125, 148.9810791015625);
path.lineTo( 44.59405517578125, 149.16107177734375);
path.lineTo( 44.877044677734375, 149.62005615234375);
path.lineTo(144.373016357421875, 68.8070068359375);
return path;
}
// A path which results in non-finite points when stroked and bevelled for AA.
static SkPath create_path_27() {
SkPath path;
path.moveTo(8.5027233009104409507e+37, 1.7503381025241130639e+37);
path.lineTo(7.0923661737711584874e+37, 1.4600074517285415699e+37);
path.lineTo(7.0848733446033294691e+37, 1.4584649744781838604e+37);
path.lineTo(-2.0473916115129349496e+37, -4.2146796450364162012e+36);
path.lineTo(2.0473912312177548811e+37, 4.2146815465123165435e+36);
return path;
}
// AA stroking this path produces intersection failures on bevelling.
// This should skip the point, but not assert.
static SkPath create_path_28() {
SkPath path;
path.moveTo(-7.5952312625177475154e+21, -2.6819185100266674911e+24);
path.lineTo( 1260.3787841796875, 1727.7947998046875);
path.lineTo( 1260.5567626953125, 1728.0386962890625);
path.lineTo(1.1482511310557754163e+21, 4.054538502765980051e+23);
path.lineTo(-7.5952312625177475154e+21, -2.6819185100266674911e+24);
return path;
}
// A quad which generates a huge number of points (>2B) when uniformly
// linearized. This should not hang or OOM.
static SkPath create_path_29() {
SkPath path;
path.moveTo(10, 0);
path.lineTo(0, 0);
path.quadTo(10, 0, 0, 8315084722602508288);
return path;
}
// A path which hangs during simplification. It produces an edge which is
// to the left of its own endpoints, which causes an infinte loop in the
// right-enclosing-edge splitting.
static SkPath create_path_30() {
SkPath path;
path.moveTo(0.75001740455627441406, 23.051967620849609375);
path.lineTo(5.8471612930297851562, 22.731662750244140625);
path.lineTo(10.749670028686523438, 22.253145217895507812);
path.lineTo(13.115868568420410156, 22.180681228637695312);
path.lineTo(15.418928146362304688, 22.340015411376953125);
path.lineTo( 17.654022216796875, 22.82159423828125);
path.lineTo(19.81632232666015625, 23.715869903564453125);
path.lineTo(40, 0);
path.lineTo(5.5635203441547955577e-15, 0);
path.lineTo(5.5635203441547955577e-15, 47);
path.lineTo(-1.4210854715202003717e-14, 21.713298797607421875);
path.lineTo(0.75001740455627441406, 21.694292068481445312);
path.lineTo(0.75001740455627441406, 23.051967620849609375);
return path;
}
// A path with vertices which become infinite on AA stroking. Should not crash or assert.
static SkPath create_path_31() {
SkPath path;
path.moveTo(2.0257809259190991347e+36, -1244080640);
path.conicTo(2.0257809259190991347e+36, -1244080640,
2.0257809259190991347e+36, 0.10976474732160568237, 0.70710676908493041992);
path.lineTo(-10036566016, -1954718402215936);
path.conicTo(-1.1375507718551896064e+20, -1954721086570496,
10036566016, -1954721086570496, 0.70710676908493041992);
return path;
}
// Reduction from skbug.com/7911 that causes a crash due to splitting a
// zombie edge.
static SkPath create_path_32() {
SkPath path;
path.moveTo( 0, 1.0927740941146660348e+24);
path.lineTo(2.9333931225865729333e+32, 16476101);
path.lineTo(1.0927731573659435417e+24, 1.0927740941146660348e+24);
path.lineTo(1.0927740941146660348e+24, 3.7616281094287041715e-37);
path.lineTo(1.0927740941146660348e+24, 1.0927740941146660348e+24);
path.lineTo(1.3061803026169399536e-33, 1.0927740941146660348e+24);
path.lineTo(4.7195362919941370727e-16, -8.4247545146051822591e+32);
return path;
}
// From crbug.com/844873. Crashes trying to merge a zombie edge.
static SkPath create_path_33() {
SkPath path;
path.moveTo( 316.000579833984375, -4338355948977389568);
path.lineTo(1.5069369808623501312e+20, 75180972320904708096.0);
path.lineTo(1.5069369808623501312e+20, 75180972320904708096.0);
path.lineTo( 771.21014404296875, -4338355948977389568.0);
path.lineTo( 316.000579833984375, -4338355948977389568.0);
path.moveTo( 354.208984375, -4338355948977389568.0);
path.lineTo( 773.00177001953125, -4338355948977389568.0);
path.lineTo(1.5069369808623501312e+20, 75180972320904708096.0);
path.lineTo(1.5069369808623501312e+20, 75180972320904708096.0);
path.lineTo( 354.208984375, -4338355948977389568.0);
return path;
}
// From crbug.com/844873. Hangs repeatedly splitting alternate vertices.
static SkPath create_path_34() {
SkPath path;
path.moveTo(10, -1e+20f);
path.lineTo(11, 25000);
path.lineTo(10, 25000);
path.lineTo(11, 25010);
return path;
}
// Reduction from circular_arcs_stroke_and_fill_round GM which
// repeatedly splits on the opposite edge from case 34 above.
static SkPath create_path_35() {
SkPath path;
path.moveTo( 16.25, 26.495191574096679688);
path.lineTo(32.420825958251953125, 37.377376556396484375);
path.lineTo(25.176382064819335938, 39.31851959228515625);
path.moveTo( 20, 20);
path.lineTo(28.847436904907226562, 37.940830230712890625);
path.lineTo(25.17638397216796875, 39.31851959228515625);
return path;
}
// Reduction from crbug.com/843135 where an intersection is found
// below the bottom of both intersected edges.
static SkPath create_path_36() {
SkPath path;
path.moveTo(-2791476679359332352, 2608107002026524672);
path.lineTo( 0, 11.95427703857421875);
path.lineTo(-2781824066779086848, 2599088532777598976);
path.lineTo( -7772.6875, 7274);
return path;
}
// Reduction from crbug.com/843135. Exercises a case where an intersection is missed.
// This causes bad ordering in the active edge list.
static SkPath create_path_37() {
SkPath path;
path.moveTo(-1.0662557646016024569e+23, 9.9621425197286319718e+22);
path.lineTo( -121806400, 113805032);
path.lineTo( -120098872, 112209680);
path.lineTo( 6.2832999862817380468e-36, 2.9885697364807128906);
return path;
}
// Reduction from crbug.com/851914.
static SkPath create_path_38() {
SkPath path;
path.moveTo(14.400531768798828125, 17.711114883422851562);
path.lineTo(14.621990203857421875, 171563104293879808);
path.lineTo(14.027951240539550781, 872585759381520384);
path.lineTo( 14.0216827392578125, 872665817571917824);
path.lineTo(7.699314117431640625, -3417320793833472);
path.moveTo(11.606547355651855469, 17.40966796875);
path.lineTo( 7642114886926860288, 21.08358001708984375);
path.lineTo(11.606547355651855469, 21.08358001708984375);
return path;
}
// Reduction from crbug.com/851409. Exercises collinear last vertex.
static SkPath create_path_39() {
SkPath path;
path.moveTo(2072553216, 0);
path.lineTo(2072553216, 1);
path.lineTo(2072553472, -13.5);
path.lineTo(2072553216, 0);
path.lineTo(2072553472, -6.5);
return path;
}
// Another reduction from crbug.com/851409. Exercises two sequential collinear edges.
static SkPath create_path_40() {
SkPath path;
path.moveTo(2072553216, 0);
path.lineTo(2072553216, 1);
path.lineTo(2072553472, -13);
path.lineTo(2072553216, 0);
path.lineTo(2072553472, -6);
path.lineTo(2072553472, -13);
return path;
}
// Reduction from crbug.com/860453. Tests a case where a "missing" intersection
// requires the active edge list to go out-of-order.
static SkPath create_path_41() {
SkPath path;
path.moveTo(72154931603311689728.0, 330.95965576171875);
path.lineTo(24053266013925408768.0, 78.11376953125);
path.lineTo(1.2031099003292404941e+20, 387.168731689453125);
path.lineTo(68859835992355373056.0, 346.55047607421875);
path.lineTo(76451708695451009024.0, 337.780029296875);
path.moveTo(-20815817797613387776.0, 18065700622522384384.0);
path.lineTo(-72144121204987396096.0, 142.855804443359375);
path.lineTo(72144121204987396096.0, 325.184783935546875);
path.lineTo(1.2347242901040791552e+20, 18065700622522384384.0);
return path;
}
// Reduction from crbug.com/860655. Cause is three collinear edges discovered during
// sanitize_contours pass, before the vertices have been found coincident.
static SkPath create_path_42() {
SkPath path;
path.moveTo( 32572426382475264, -3053391034974208);
path.lineTo( 521289856, -48865776);
path.lineTo( 130322464, -12215873);
path.moveTo( 32572426382475264, -3053391034974208);
path.lineTo( 521289856, -48865776);
path.lineTo( 130322464, -12215873);
path.moveTo( 32572426382475264, -3053391034974208);
path.lineTo( 32114477642022912, -3010462031544320);
path.lineTo( 32111784697528320, -3010209702215680);
return path;
}
// Reduction from crbug.com/866319. Cause is edges that are collinear when tested from
// one side, but non-collinear when tested from the other.
static SkPath create_path_43() {
SkPath path;
path.moveTo( 307316821852160, -28808363114496);
path.lineTo( 307165222928384, -28794154909696);
path.lineTo( 307013691113472, -28779948802048);
path.lineTo( 306862159298560, -28765744791552);
path.lineTo( 306870313025536, -28766508154880);
path.lineTo( 307049695019008, -28783327313920);
path.lineTo( 307408660332544, -28816974020608);
return path;
}
static std::unique_ptr<GrFragmentProcessor> create_linear_gradient_processor(GrContext* ctx) {
SkPoint pts[2] = { {0, 0}, {1, 1} };
SkColor colors[2] = { SK_ColorGREEN, SK_ColorBLUE };
sk_sp<SkShader> shader = SkGradientShader::MakeLinear(
pts, colors, nullptr, SK_ARRAY_COUNT(colors), SkShader::kClamp_TileMode);
GrColorSpaceInfo colorSpaceInfo(nullptr, kRGBA_8888_GrPixelConfig);
GrFPArgs args(ctx, &SkMatrix::I(), SkFilterQuality::kLow_SkFilterQuality, &colorSpaceInfo);
return as_SB(shader)->asFragmentProcessor(args);
}
using AATypeFlags = GrPathRenderer::AATypeFlags;
static void test_path(GrContext* ctx,
GrRenderTargetContext* renderTargetContext,
const SkPath& path,
const SkMatrix& matrix = SkMatrix::I(),
AATypeFlags aaTypeFlags = AATypeFlags::kNone,
std::unique_ptr<GrFragmentProcessor> fp = nullptr) {
GrTessellatingPathRenderer tess;
GrPaint paint;
paint.setXPFactory(GrPorterDuffXPFactory::Get(SkBlendMode::kSrc));
if (fp) {
paint.addColorFragmentProcessor(std::move(fp));
}
GrNoClip noClip;
SkIRect clipConservativeBounds = SkIRect::MakeWH(renderTargetContext->width(),
renderTargetContext->height());
GrStyle style(SkStrokeRec::kFill_InitStyle);
GrShape shape(path, style);
GrPathRenderer::DrawPathArgs args{ctx,
std::move(paint),
&GrUserStencilSettings::kUnused,
renderTargetContext,
&noClip,
&clipConservativeBounds,
&matrix,
&shape,
aaTypeFlags,
false};
tess.drawPath(args);
}
DEF_GPUTEST_FOR_ALL_CONTEXTS(TessellatingPathRendererTests, reporter, ctxInfo) {
GrContext* ctx = ctxInfo.grContext();
const GrBackendFormat format =
ctx->priv().caps()->getBackendFormatFromColorType(kRGBA_8888_SkColorType);
sk_sp<GrRenderTargetContext> rtc(ctx->priv().makeDeferredRenderTargetContext(
format, SkBackingFit::kApprox, 800, 800, kRGBA_8888_GrPixelConfig, nullptr, 1,
GrMipMapped::kNo, kTopLeft_GrSurfaceOrigin));
if (!rtc) {
return;
}
ctx->flush();
// Adding discard to appease vulkan validation warning about loading uninitialized data on draw
rtc->discard();
test_path(ctx, rtc.get(), create_path_0());
test_path(ctx, rtc.get(), create_path_1());
test_path(ctx, rtc.get(), create_path_2());
test_path(ctx, rtc.get(), create_path_3());
test_path(ctx, rtc.get(), create_path_4());
test_path(ctx, rtc.get(), create_path_5());
test_path(ctx, rtc.get(), create_path_6());
test_path(ctx, rtc.get(), create_path_7());
test_path(ctx, rtc.get(), create_path_8());
test_path(ctx, rtc.get(), create_path_9());
test_path(ctx, rtc.get(), create_path_10());
test_path(ctx, rtc.get(), create_path_11());
test_path(ctx, rtc.get(), create_path_12());
test_path(ctx, rtc.get(), create_path_13());
test_path(ctx, rtc.get(), create_path_14());
test_path(ctx, rtc.get(), create_path_15());
test_path(ctx, rtc.get(), create_path_16());
SkMatrix nonInvertibleMatrix = SkMatrix::MakeScale(0, 0);
std::unique_ptr<GrFragmentProcessor> fp(create_linear_gradient_processor(ctx));
test_path(ctx, rtc.get(), create_path_17(), nonInvertibleMatrix, AATypeFlags::kCoverage,
std::move(fp));
test_path(ctx, rtc.get(), create_path_18());
test_path(ctx, rtc.get(), create_path_19());
test_path(ctx, rtc.get(), create_path_20(), SkMatrix(), AATypeFlags::kCoverage);
test_path(ctx, rtc.get(), create_path_21(), SkMatrix(), AATypeFlags::kCoverage);
test_path(ctx, rtc.get(), create_path_23());
test_path(ctx, rtc.get(), create_path_24());
test_path(ctx, rtc.get(), create_path_25(), SkMatrix(), AATypeFlags::kCoverage);
test_path(ctx, rtc.get(), create_path_26(), SkMatrix(), AATypeFlags::kCoverage);
test_path(ctx, rtc.get(), create_path_27(), SkMatrix(), AATypeFlags::kCoverage);
test_path(ctx, rtc.get(), create_path_28(), SkMatrix(), AATypeFlags::kCoverage);
test_path(ctx, rtc.get(), create_path_29());
test_path(ctx, rtc.get(), create_path_30());
test_path(ctx, rtc.get(), create_path_31(), SkMatrix(), AATypeFlags::kCoverage);
test_path(ctx, rtc.get(), create_path_32());
test_path(ctx, rtc.get(), create_path_33());
test_path(ctx, rtc.get(), create_path_34());
test_path(ctx, rtc.get(), create_path_35());
test_path(ctx, rtc.get(), create_path_36());
test_path(ctx, rtc.get(), create_path_37());
test_path(ctx, rtc.get(), create_path_38(), SkMatrix(), AATypeFlags::kCoverage);
test_path(ctx, rtc.get(), create_path_39());
test_path(ctx, rtc.get(), create_path_40());
test_path(ctx, rtc.get(), create_path_41(), SkMatrix(), AATypeFlags::kCoverage);
test_path(ctx, rtc.get(), create_path_42());
test_path(ctx, rtc.get(), create_path_43(), SkMatrix(), AATypeFlags::kCoverage);
}
| [
"[email protected]"
] | |
c40cec2855a8e1024a089444ba834a4497a6b87e | 74fc7c5d39baa6c30aa929e629ff60bf40500c61 | /test/unit-tests/mbr/abr_manager_mock.h | 7d72e0e7df2540c2a133c41a74fcdd4bdfbd12c3 | [
"BSD-3-Clause"
] | permissive | jhyunleehi/poseidonos | e472be680d0e85dc62f0e2c0d7356dbee74a3bd6 | 1d90e4320855d61742ff37af8c0148da579d95d4 | refs/heads/develop | 2023-07-13T03:37:29.754509 | 2021-08-23T15:26:08 | 2021-08-23T15:26:08 | 393,203,347 | 0 | 0 | BSD-3-Clause | 2021-08-20T00:04:14 | 2021-08-06T00:30:35 | C | UTF-8 | C++ | false | false | 754 | h | #include <gmock/gmock.h>
#include <list>
#include <string>
#include <vector>
#include "src/mbr/abr_manager.h"
namespace pos
{
class MockAbrManager : public AbrManager
{
public:
using AbrManager::AbrManager;
MOCK_METHOD(int, LoadAbr, (string arrayName, ArrayMeta& meta), (override));
MOCK_METHOD(int, SaveAbr, (string arrayName, ArrayMeta& meta), (override));
MOCK_METHOD(bool, GetMfsInit, (string arrayName), (override));
MOCK_METHOD(int, SetMfsInit, (string arrayName, bool value), (override));
MOCK_METHOD(int, CreateAbr, (string arrayName, ArrayMeta& meta), (override));
MOCK_METHOD(int, DeleteAbr, (string arrayName, ArrayMeta& meta), (override));
MOCK_METHOD(int, ResetMbr, (), (override));
};
} // namespace pos
| [
"[email protected]"
] | |
2013508685c406f26f59797369c25eab0f2a0d9f | cae8f9912d24273fa747f4f791989f1f6f12f247 | /sketch_apr02a.ino | fe5d5df7452a0f7ae5a8a29c13e258d9eb96c716 | [] | no_license | vasudevgrover/Working-with-GSM-module-Arduino- | ae873f57e68d5b132fb093e64068f77b0f28b6e5 | de6d2fbd860a8b16818449abe5d4b56ddd334f81 | refs/heads/master | 2020-12-24T20:42:52.744017 | 2016-04-12T16:32:15 | 2016-04-12T16:32:15 | 56,079,703 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 999 | ino | #include <SoftwareSerial.h>
SoftwareSerial mySerial(9, 10);
void setup()
{
mySerial.begin(9600); //baud rate of GSM Module
Serial.begin(9600); //baud rate of Serial Monitor (Arduino)
delay(100);
}
void loop()
{
if (Serial.available()>0)
switch(Serial.read())
{
case 's':
SendMessage();
break;
case 'r':
RecieveMessage();
break;
}
if (mySerial.available()>0)
Serial.write(mySerial.read());
}
void SendMessage()
{
mySerial.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode
delay(1000); // Delay of 1000 milli seconds or 1 second
mySerial.println("AT+CMGS=\"+91xxxxxxxxxx\"\r"); // Replace x with mobile number
delay(1000);
mySerial.println("SMS from GSM Module");// The SMS text you want to send
delay(100);
mySerial.println((char)26);// ASCII code of CTRL+Z
delay(1000);
}
void RecieveMessage()
{
mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
delay(1000);
}
| [
"[email protected]"
] | |
cc5d35422b45c75f8146e02297f99e09fdcbddeb | 82646fb7fe40db6dcdf238548128f7b633de94c0 | /workspace/P65/src/32.cpp | 9583afe2df05015dcd324b3057ed4780060bbe17 | [] | no_license | jtahstu/iCode | a7873618fe98e502c1e0e2fd0769d71b3adac756 | 42d0899945dbc1bab98092d21a1d946137a1795e | refs/heads/master | 2021-01-10T22:55:47.677615 | 2016-10-23T12:42:38 | 2016-10-23T12:42:38 | 70,316,051 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 582 | cpp | /*
* 32.cpp
* Created on: 2015年4月4日
* Author: jtahstu
*/
//32列出真分数序列
//按递增顺序依次列出所有分母为40,分子小于40的最简分数。
//
//*运行结果
//The fraction serials with demominator 40 is:
//1/40 3/40 7/40 9/40 11/40 13/40 17/40 19/40
//21/40 23/40 27/40 29/40 31/40 33/40 37/40 39/40
#include<iostream>
#include<cstdio>
using namespace std;
int gcd32(int a,int b){
return b==0?a:gcd32(b,a%b);
}
int main32()
{
for(int i=1;i<40;i++)
{if(gcd32(40,i)==1)
cout<<i<<"/40"<<" ";
}
return 0;
}
| [
"[email protected]"
] | |
b5589fb337feef68645274585eb809249bd12867 | ef91f0c61520391ad25692c6adebff4aebe8dd09 | /ServerNet/Sources/VMIMEMessage.cpp | 8d1b73eef7e85b122df90ba1f9b7731956adf56e | [] | no_license | StephaneH/core-XToolbox | 77462b758dfae86f86aafb8a9c9e5b34215259c7 | c166b76bbd1dfba27c7863f203b158212028222e | refs/heads/master | 2021-01-19T06:52:37.703070 | 2014-11-17T13:35:24 | 2014-11-17T13:35:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,340 | cpp | /*
* This file is part of Wakanda software, licensed by 4D under
* (i) the GNU General Public License version 3 (GNU GPL v3), or
* (ii) the Affero General Public License version 3 (AGPL v3) or
* (iii) a commercial license.
* This file remains the exclusive property of 4D and/or its licensors
* and is protected by national and international legislations.
* In any event, Licensee's compliance with the terms and conditions
* of the applicable license constitutes a prerequisite to any use of this file.
* Except as otherwise expressly stated in the applicable license,
* such license does not include any other license or rights on this file,
* 4D's and/or its licensors' trademarks and/or other proprietary rights.
* Consequently, no title, copyright or other proprietary rights
* other than those specified in the applicable license is granted.
*/
#include "VServerNetPrecompiled.h"
#include "VMIMEMessage.h"
#include "VNameValueCollection.h"
#include "VHTTPHeader.h"
#include "HTTPTools.h"
#include "VMIMEReader.h"
BEGIN_TOOLBOX_NAMESPACE
USING_TOOLBOX_NAMESPACE
using namespace HTTPTools;
//--------------------------------------------------------------------------------------------------
VMIMEMessage::VMIMEMessage()
: fEncoding (CONST_MIME_MESSAGE_ENCODING_URL)
{
}
VMIMEMessage::~VMIMEMessage()
{
Clear();
}
void VMIMEMessage::Clear()
{
fMIMEParts.clear();
}
void VMIMEMessage::_AddTextPart (const XBOX::VString& inName, bool inIsInline, const XBOX::VString& inContentType, const XBOX::VString& inContentID, XBOX::VPtrStream& inStream)
{
VMIMEMessagePart *partSource = new VMIMEMessagePart();
if (NULL != partSource)
{
partSource->SetName (inName);
partSource->SetIsInline(inIsInline);
partSource->SetMediaType (inContentType);
partSource->SetContentID(inContentID);
if (XBOX::VE_OK == inStream.OpenReading())
partSource->PutData (inStream.GetDataPtr(), inStream.GetDataSize());
inStream.CloseReading();
fMIMEParts.push_back (partSource);
partSource->Release();
}
}
void VMIMEMessage::_AddFilePart (const XBOX::VString& inName, const XBOX::VString& inFileName, bool inIsInline, const XBOX::VString& inContentType, const XBOX::VString& inContentID, XBOX::VPtrStream& inStream)
{
VMIMEMessagePart *partSource = new VMIMEMessagePart();
if (NULL != partSource)
{
partSource->SetName (inName);
partSource->SetFileName (inFileName);
partSource->SetIsInline(inIsInline);
partSource->SetMediaType (inContentType);
partSource->SetContentID(inContentID);
if (XBOX::VE_OK == inStream.OpenReading())
partSource->PutData (inStream.GetDataPtr(), inStream.GetDataSize());
inStream.CloseReading();
fMIMEParts.push_back (partSource);
partSource->Release();
}
}
void VMIMEMessage::_AddValuePair (const XBOX::VString& inName, const XBOX::VString& inContentType, void *inData, const XBOX::VSize inDataSize)
{
VMIMEMessagePart *partSource = new VMIMEMessagePart();
if (NULL != partSource)
{
partSource->SetName (inName);
partSource->SetMediaType (inContentType);
partSource->PutData (inData, inDataSize);
fMIMEParts.push_back (partSource);
partSource->Release();
}
}
void VMIMEMessage::Load (bool inFromPOST, const XBOX::VString& inContentType, const XBOX::VString& inURLQuery, const XBOX::VStream& inStream)
{
Clear();
if (inFromPOST)
{
XBOX::VNameValueCollection params;
VHTTPHeader::SplitParameters (inContentType, fEncoding, params);
if (HTTPTools::EqualASCIIVString (fEncoding, CONST_MIME_MESSAGE_ENCODING_MULTIPART))
{
fBoundary = params.Get (CONST_MIME_MESSAGE_BOUNDARY);
_ReadMultipart (inStream);
}
else
{
_ReadUrl (inStream);
}
}
else
{
_ReadUrl (inURLQuery);
}
}
void VMIMEMessage::LoadMail (const VMIMEMailHeader *inHeader, VMemoryBufferStream &inStream)
{
xbox_assert(inHeader != NULL);
if (inHeader->fIsMultiPart) {
fBoundary = inHeader->fBoundary;
_ReadMultiPartMail(inStream);
} else
_ReadSinglePartMail(inHeader, inStream);
}
void VMIMEMessage::_ReadUrl (const XBOX::VStream& inStream)
{
XBOX::VStream& stream = const_cast<XBOX::VStream&>(inStream);
if (XBOX::VE_OK == stream.OpenReading())
{
XBOX::VString urlString;
XBOX::StErrorContextInstaller filter (XBOX::VE_STREAM_TEXT_CONVERSION_FAILURE, XBOX::VE_STREAM_EOF, XBOX::VE_OK); // YT 28-Mar-2013 - ACI0081219
if (XBOX::VE_OK == stream.GetText (urlString))
_ReadUrl (urlString);
stream.CloseReading();
}
}
void VMIMEMessage::_ReadUrl (const XBOX::VString& inString)
{
if (!inString.IsEmpty())
{
const UniChar *stringPtr = inString.GetCPointer();
UniChar ch = *stringPtr;
while (ch != '\0')
{
XBOX::VString name;
XBOX::VString value;
while (ch != '\0' && ch != CHAR_EQUALS_SIGN && ch != CHAR_AMPERSAND)
{
if (ch == CHAR_PLUS_SIGN) ch = CHAR_SPACE;
name.AppendUniChar (ch);
ch = *(++stringPtr);
}
if (ch == CHAR_EQUALS_SIGN)
{
ch = *(++stringPtr);
while (ch != '\0' && ch != CHAR_AMPERSAND)
{
if (ch == CHAR_PLUS_SIGN) ch = CHAR_SPACE;
value.AppendUniChar (ch);
ch = *(++stringPtr);
}
}
XBOX::VString decodedName (name);
XBOX::VString decodedValue (value);
XBOX::VURL::Decode (decodedName);
XBOX::VURL::Decode (decodedValue);
XBOX::StStringConverter<char> buffer (decodedValue, XBOX::VTC_UTF_8);
_AddValuePair (decodedName, CONST_TEXT_PLAIN_UTF_8, (void *)buffer.GetCPointer(), buffer.GetLength());
if (ch == CHAR_AMPERSAND) ch = *(++stringPtr);
}
}
}
void VMIMEMessage::_ReadMultipart (const XBOX::VStream& inStream)
{
XBOX::VStream& stream = const_cast<XBOX::VStream&>(inStream);
VMIMEReader reader (fBoundary, stream);
while (reader.HasNextPart())
{
VHTTPMessage message;
if (!reader.GetNextPart (message))
break;
XBOX::VString dispositionValue;
XBOX::VNameValueCollection params;
if (message.GetHeaders().IsHeaderSet (STRING_HEADER_CONTENT_DISPOSITION))
{
XBOX::VString contentDispositionHeaderValue;
message.GetHeaders().GetHeaderValue (STRING_HEADER_CONTENT_DISPOSITION, contentDispositionHeaderValue);
VHTTPHeader::SplitParameters (contentDispositionHeaderValue, dispositionValue, params, true); // YT 25-Jan-2012 - ACI0075142
}
if (params.Has (CONST_MIME_PART_FILENAME))
{
XBOX::VString fileName;
XBOX::VString name;
XBOX::VString contentType;
XBOX::VString contentID;
message.GetHeaders().GetHeaderValue (STRING_HEADER_CONTENT_TYPE, contentType);
fileName = params.Get (CONST_MIME_PART_FILENAME);
name = params.Get (CONST_MIME_PART_NAME);
// Default as "attachment", not "inline".
_AddFilePart (name, fileName, false, contentType, contentID, message.GetBody());
}
else
{
XBOX::VString nameString = params.Get (CONST_MIME_PART_NAME);
XBOX::VURL::Decode (nameString);
_AddValuePair (nameString, CONST_TEXT_PLAIN, message.GetBody().GetDataPtr(), message.GetBody().GetDataSize());
}
XBOX::VTask::Yield(); // YT 14-Oct-2013 - ACI0084474
}
}
void VMIMEMessage::_ReadMultiPartMail (const XBOX::VStream &inStream)
{
XBOX::VStream &stream = const_cast<XBOX::VStream&>(inStream);
VMIMEReader reader(fBoundary, stream);
while (reader.HasNextPart()) {
XBOX::VHTTPMessage message;
reader.GetNextPart(message);
// Parse header of part.
XBOX::VHTTPHeader header = message.GetHeaders();
const XBOX::VNameValueCollection &headerList = header.GetHeaderList();
XBOX::VNameValueCollection::ConstIterator it;
XBOX::VString name, fileName, contentType, contentID;
bool isInline, isBase64, isQuotedPrintable;
isInline = isBase64 = isQuotedPrintable = false;
for (it = headerList.begin(); it != headerList.end(); it++) {
XBOX::VString value;
XBOX::VNameValueCollection params;
if (HTTPTools::EqualASCIIVString(it->first, "Content-Type", false)) {
header.GetHeaderValue(it->first, contentType);
VHTTPHeader::SplitParameters(contentType, value, params);
if (params.Has("name")) {
name = params.Get("name");
_UnQuote(&name, '"', '"');
}
} else if (HTTPTools::EqualASCIIVString(it->first, "Content-Disposition", false)) {
XBOX::VString disposition;
header.GetHeaderValue(it->first, value);
VHTTPHeader::SplitParameters(value, disposition, params);
isInline = HTTPTools::EqualASCIIVString(disposition, "inline");
if (params.Has("filename")) {
fileName = params.Get("filename");
_UnQuote(&fileName, '"', '"');
}
} else if (HTTPTools::EqualASCIIVString(it->first, "Content-Transfer-Encoding", false)) {
XBOX::VString encoding;
header.GetHeaderValue(it->first, value);
VHTTPHeader::SplitParameters(value, encoding, params);
if (!(isBase64 = HTTPTools::EqualASCIIVString(encoding, "base64")))
isQuotedPrintable = HTTPTools::EqualASCIIVString(encoding, "quoted-printable");
} else if (HTTPTools::EqualASCIIVString(it->first, "Content-ID", false)) {
header.GetHeaderValue(it->first, value);
VHTTPHeader::SplitParameters(value, contentID, params);
_UnQuote(&contentID, '<', '>');
} else {
// Ignore unknown fields.
}
}
// Get body of part, decode it if need.
XBOX::VMemoryBuffer<> decodedData;
XBOX::VPtrStream decodedBody;
XBOX::VPtrStream *body = message.GetBodyPtr();
if (isBase64) {
XBOX::Base64Coder::Decode(body->GetDataPtr(), body->GetDataSize(), decodedData);
decodedBody.SetDataPtr(decodedData.GetDataPtr(), decodedData.GetDataSize());
decodedData.ForgetData();
body = &decodedBody;
} else if (isQuotedPrintable) {
VMIMEReader::DecodeQuotedPrintable (body->GetDataPtr(), body->GetDataSize(), &decodedData);
decodedBody.SetDataPtr(decodedData.GetDataPtr(), decodedData.GetDataSize());
decodedData.ForgetData();
body = &decodedBody;
}
if (fileName.IsEmpty())
_AddTextPart(name, isInline, contentType, contentID, *body);
else
_AddFilePart(name, fileName, isInline, contentType, contentID, *body);
decodedBody.Clear();
XBOX::VTask::Yield(); // YT 14-Oct-2013 - ACI0084474
}
}
void VMIMEMessage::_ReadSinglePartMail (const VMIMEMailHeader *inHeader, VStream &inStream)
{
xbox_assert(inHeader != NULL);
// Read header information.
XBOX::VString name, fileName, contentType, contentID;
bool isInline, isBase64, isQuotedPrintable;
isInline = isBase64 = isQuotedPrintable = false;
XBOX::VString string;
XBOX::VNameValueCollection params;
if (!inHeader->fContentType.IsEmpty()) {
contentType = inHeader->fContentType;
VHTTPHeader::SplitParameters(inHeader->fContentType, string, params);
if (params.Has("name")) {
name = params.Get("name");
_UnQuote(&name, '"', '"');
}
}
if (!inHeader->fContentDisposition.IsEmpty()) {
VHTTPHeader::SplitParameters(inHeader->fContentDisposition, string, params);
isInline = HTTPTools::EqualASCIIVString(string, "inline");
if (params.Has("filename")) {
fileName = params.Get("filename");
_UnQuote(&fileName, '"', '"');
}
}
if (!inHeader->fContentTransferEncoding.IsEmpty()) {
VHTTPHeader::SplitParameters(inHeader->fContentTransferEncoding, string, params);
if (!(isBase64 = HTTPTools::EqualASCIIVString(string, "base64")))
isQuotedPrintable = HTTPTools::EqualASCIIVString(string, "quoted-printable");
}
// Read body (a single part). Must be bigger than 5 bytes because of the ending "\r\n.\r\n" sequence.
XBOX::VError error;
VSize size;
if ((error = inStream.OpenReading()) != XBOX::VE_OK)
XBOX::vThrowError(error);
else if ((size = (VSize) inStream.GetSize()) > 5) {
uBYTE *buffer;
size -= 5;
if ((buffer = new uBYTE[size]) == NULL)
XBOX::vThrowError(XBOX::VE_MEMORY_FULL);
else {
XBOX::VMemoryBuffer<> decodedData;
XBOX::VPtrStream decodedBody;
inStream.GetData(buffer, size);
if (isBase64) {
XBOX::Base64Coder::Decode(buffer, size, decodedData);
decodedBody.SetDataPtr(decodedData.GetDataPtr(), decodedData.GetDataSize());
decodedData.ForgetData();
} else if (isQuotedPrintable) {
VMIMEReader::DecodeQuotedPrintable(buffer, size, &decodedData);
decodedBody.SetDataPtr(decodedData.GetDataPtr(), decodedData.GetDataSize());
decodedData.ForgetData();
} else
decodedBody.SetDataPtr(buffer, size);
inStream.CloseReading();
if (fileName.IsEmpty())
_AddTextPart(name, isInline, contentType, contentID, decodedBody);
else
_AddFilePart(name, fileName, isInline, contentType, contentID, decodedBody);
if (isBase64 || isQuotedPrintable)
decodedBody.Clear();
else
decodedBody.StealData(); // Prevent VPtrStream from freeing buffer.
delete[] buffer;
}
} else
inStream.CloseReading();
}
XBOX::VError VMIMEMessage::ToStream (XBOX::VStream& outStream, sLONG inEncoding) const
{
XBOX::VError error = XBOX::VE_OK;
if (XBOX::VE_OK == outStream.OpenWriting())
{
outStream.SetCarriageReturnMode(eCRM_CRLF);
if (!fMIMEParts.empty())
{
XBOX::VString string;
XBOX::VString charsetName;
bool bEncodeBody; // Encode using base64.
for (XBOX::VectorOfMIMEPart::const_iterator it = fMIMEParts.begin(); it != fMIMEParts.end(); ++it)
{
outStream.PutPrintf ("\r\n--%S\r\n", &fBoundary);
string.FromCString ("Content-Type: ");
string.AppendString ((*it)->GetMediaType());
if (!(*it)->GetFileName().IsEmpty())
{
string.AppendCString ("; name=\"");
if (!(*it)->GetName().IsEmpty())
string.AppendString ((*it)->GetName());
else
string.AppendString ((*it)->GetFileName());
string.AppendCString("\"\r\nContent-Disposition: ");
string.AppendCString((*it)->IsInline() ? "inline; " : "attachment; ");
string.AppendCString("filename=\"");
string.AppendString ((*it)->GetFileName());
string.AppendCString ("\"\r\n");
if (inEncoding == ENCODING_BINARY) {
string.AppendCString ("Content-Transfer-Encoding: 8bit\r\n");
bEncodeBody = false;
} else {
if ((inEncoding == ENCODING_BINARY_ONLY) && ((*it)->GetMediaTypeKind() == MIMETYPE_TEXT))
{
bEncodeBody = false;
}
else
{
string.AppendCString ("Content-Transfer-Encoding: base64\r\n");
bEncodeBody = true;
}
}
}
else
{
if ((*it)->GetMediaTypeCharSet() != XBOX::VTC_UNKNOWN)
{
string.AppendCString ("; charset=\"");
XBOX::VTextConverters::Get()->GetNameFromCharSet ((*it)->GetMediaTypeCharSet(), charsetName);
string.AppendString (charsetName);
string.AppendCString ("\"");
}
if (!(*it)->GetName().IsEmpty()) {
string.AppendCString("; name=\"");
string.AppendString((*it)->GetName());
string.AppendCString("\"");
}
string.AppendCString ("\r\n");
if ((*it)->IsInline())
string.AppendCString("Content-Disposition: inline\r\n");
if (inEncoding == ENCODING_7BIT || ((inEncoding == ENCODING_BINARY_ONLY) && ((*it)->GetMediaTypeKind() != MIMETYPE_TEXT))) {
string.AppendCString ("Content-Transfer-Encoding: base64\r\n");
bEncodeBody = true;
} else {
string.AppendCString("Content-Transfer-Encoding: 8bit\r\n");
bEncodeBody = false;
}
}
if ((*it)->GetContentID().GetLength()) {
string.AppendCString("Content-ID: <");
string.AppendString((*it)->GetContentID());
string.AppendCString(">\r\n");
}
string.AppendCString ("\r\n");
outStream.PutText (string);
if (bEncodeBody)
{
XBOX::VMemoryBuffer<> buffer;
if (XBOX::Base64Coder::Encode ((*it)->GetData().GetDataPtr(), (*it)->GetData().GetDataSize(), buffer, kBASE64_QUADS_PER_LINE))
{
outStream.PutData (buffer.GetDataPtr(), buffer.GetDataSize());
}
}
else
{
outStream.PutData ((*it)->GetData().GetDataPtr(), (*it)->GetData().GetDataSize());
}
}
outStream.PutPrintf ("\r\n--%S--\r\n", &fBoundary);
}
outStream.CloseWriting();
}
return error;
}
void VMIMEMessage::_UnQuote (XBOX::VString *ioString, UniChar inStartQuote, UniChar inEndQuote)
{
xbox_assert(ioString != NULL);
if (ioString->GetLength() >= 2
&& ioString->GetUniChar(1) == inStartQuote
&& ioString->GetUniChar(ioString->GetLength()) == inEndQuote)
ioString->SubString(2, ioString->GetLength() - 2);
}
END_TOOLBOX_NAMESPACE
| [
"[email protected]"
] | |
3f69c1177031469f39583381efe7b985bc198426 | 9f81d77e028503dcbb6d7d4c0c302391b8fdd50c | /google/cloud/retail/v2/internal/model_auth_decorator.h | 8bf2a926c99f9d1b8275b51fab4742fd4cb0c5d1 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | googleapis/google-cloud-cpp | b96a6ee50c972371daa8b8067ddd803de95f54ba | 178d6581b499242c52f9150817d91e6c95b773a5 | refs/heads/main | 2023-08-31T09:30:11.624568 | 2023-08-31T03:29:11 | 2023-08-31T03:29:11 | 111,860,063 | 450 | 351 | Apache-2.0 | 2023-09-14T21:52:02 | 2017-11-24T00:19:31 | C++ | UTF-8 | C++ | false | false | 3,784 | h | // Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/cloud/retail/v2/model_service.proto
#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_RETAIL_V2_INTERNAL_MODEL_AUTH_DECORATOR_H
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_RETAIL_V2_INTERNAL_MODEL_AUTH_DECORATOR_H
#include "google/cloud/retail/v2/internal/model_stub.h"
#include "google/cloud/internal/unified_grpc_credentials.h"
#include "google/cloud/version.h"
#include <google/longrunning/operations.grpc.pb.h>
#include <memory>
#include <set>
#include <string>
namespace google {
namespace cloud {
namespace retail_v2_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
class ModelServiceAuth : public ModelServiceStub {
public:
~ModelServiceAuth() override = default;
ModelServiceAuth(
std::shared_ptr<google::cloud::internal::GrpcAuthenticationStrategy> auth,
std::shared_ptr<ModelServiceStub> child);
future<StatusOr<google::longrunning::Operation>> AsyncCreateModel(
google::cloud::CompletionQueue& cq,
std::shared_ptr<grpc::ClientContext> context,
google::cloud::retail::v2::CreateModelRequest const& request) override;
StatusOr<google::cloud::retail::v2::Model> GetModel(
grpc::ClientContext& context,
google::cloud::retail::v2::GetModelRequest const& request) override;
StatusOr<google::cloud::retail::v2::Model> PauseModel(
grpc::ClientContext& context,
google::cloud::retail::v2::PauseModelRequest const& request) override;
StatusOr<google::cloud::retail::v2::Model> ResumeModel(
grpc::ClientContext& context,
google::cloud::retail::v2::ResumeModelRequest const& request) override;
Status DeleteModel(
grpc::ClientContext& context,
google::cloud::retail::v2::DeleteModelRequest const& request) override;
StatusOr<google::cloud::retail::v2::ListModelsResponse> ListModels(
grpc::ClientContext& context,
google::cloud::retail::v2::ListModelsRequest const& request) override;
StatusOr<google::cloud::retail::v2::Model> UpdateModel(
grpc::ClientContext& context,
google::cloud::retail::v2::UpdateModelRequest const& request) override;
future<StatusOr<google::longrunning::Operation>> AsyncTuneModel(
google::cloud::CompletionQueue& cq,
std::shared_ptr<grpc::ClientContext> context,
google::cloud::retail::v2::TuneModelRequest const& request) override;
future<StatusOr<google::longrunning::Operation>> AsyncGetOperation(
google::cloud::CompletionQueue& cq,
std::shared_ptr<grpc::ClientContext> context,
google::longrunning::GetOperationRequest const& request) override;
future<Status> AsyncCancelOperation(
google::cloud::CompletionQueue& cq,
std::shared_ptr<grpc::ClientContext> context,
google::longrunning::CancelOperationRequest const& request) override;
private:
std::shared_ptr<google::cloud::internal::GrpcAuthenticationStrategy> auth_;
std::shared_ptr<ModelServiceStub> child_;
};
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace retail_v2_internal
} // namespace cloud
} // namespace google
#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_RETAIL_V2_INTERNAL_MODEL_AUTH_DECORATOR_H
| [
"[email protected]"
] | |
9244c0f202281ff985344b06fe77ae7f77e05ce6 | 847e5c2984a5d5d425e6a47565a9fb57d15dbe13 | /Libraries/LibJS/Lexer.cpp | 75ec759f3f9c56a742e6aa56e3a4932e0a2b88b0 | [
"BSD-2-Clause"
] | permissive | rizzrackguy/serenity | 7616511a187d22b64c65e19a6f5e6cb57e0dc64d | dd00175ae2d6f23b08cb803eb86fc0108c393971 | refs/heads/master | 2022-04-15T01:14:30.855454 | 2020-04-12T17:22:42 | 2020-04-12T17:23:39 | 255,151,103 | 0 | 0 | BSD-2-Clause | 2020-04-12T19:04:07 | 2020-04-12T19:04:07 | null | UTF-8 | C++ | false | false | 15,213 | cpp | /*
* Copyright (c) 2020, Stephan Unverwerth <[email protected]>
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "Lexer.h"
#include <AK/HashMap.h>
#include <AK/StringBuilder.h>
#include <ctype.h>
#include <stdio.h>
namespace JS {
HashMap<String, TokenType> Lexer::s_keywords;
HashMap<String, TokenType> Lexer::s_three_char_tokens;
HashMap<String, TokenType> Lexer::s_two_char_tokens;
HashMap<char, TokenType> Lexer::s_single_char_tokens;
Lexer::Lexer(StringView source)
: m_source(source)
, m_current_token(TokenType::Eof, StringView(nullptr), StringView(nullptr), 0, 0)
{
if (s_keywords.is_empty()) {
s_keywords.set("await", TokenType::Await);
s_keywords.set("break", TokenType::Break);
s_keywords.set("case", TokenType::Case);
s_keywords.set("catch", TokenType::Catch);
s_keywords.set("class", TokenType::Class);
s_keywords.set("const", TokenType::Const);
s_keywords.set("continue", TokenType::Continue);
s_keywords.set("default", TokenType::Default);
s_keywords.set("delete", TokenType::Delete);
s_keywords.set("do", TokenType::Do);
s_keywords.set("else", TokenType::Else);
s_keywords.set("false", TokenType::BoolLiteral);
s_keywords.set("finally", TokenType::Finally);
s_keywords.set("for", TokenType::For);
s_keywords.set("function", TokenType::Function);
s_keywords.set("if", TokenType::If);
s_keywords.set("in", TokenType::In);
s_keywords.set("instanceof", TokenType::Instanceof);
s_keywords.set("interface", TokenType::Interface);
s_keywords.set("let", TokenType::Let);
s_keywords.set("new", TokenType::New);
s_keywords.set("null", TokenType::NullLiteral);
s_keywords.set("return", TokenType::Return);
s_keywords.set("switch", TokenType::Switch);
s_keywords.set("throw", TokenType::Throw);
s_keywords.set("true", TokenType::BoolLiteral);
s_keywords.set("try", TokenType::Try);
s_keywords.set("typeof", TokenType::Typeof);
s_keywords.set("var", TokenType::Var);
s_keywords.set("void", TokenType::Void);
s_keywords.set("while", TokenType::While);
s_keywords.set("yield", TokenType::Yield);
}
if (s_three_char_tokens.is_empty()) {
s_three_char_tokens.set("===", TokenType::EqualsEqualsEquals);
s_three_char_tokens.set("!==", TokenType::ExclamationMarkEqualsEquals);
s_three_char_tokens.set("**=", TokenType::AsteriskAsteriskEquals);
s_three_char_tokens.set("<<=", TokenType::ShiftLeftEquals);
s_three_char_tokens.set(">>=", TokenType::ShiftRightEquals);
s_three_char_tokens.set(">>>", TokenType::UnsignedShiftRight);
}
if (s_two_char_tokens.is_empty()) {
s_two_char_tokens.set("=>", TokenType::Arrow);
s_two_char_tokens.set("+=", TokenType::PlusEquals);
s_two_char_tokens.set("-=", TokenType::MinusEquals);
s_two_char_tokens.set("*=", TokenType::AsteriskEquals);
s_two_char_tokens.set("/=", TokenType::SlashEquals);
s_two_char_tokens.set("%=", TokenType::PercentEquals);
s_two_char_tokens.set("&=", TokenType::AmpersandEquals);
s_two_char_tokens.set("|=", TokenType::PipeEquals);
s_two_char_tokens.set("&&", TokenType::DoubleAmpersand);
s_two_char_tokens.set("||", TokenType::DoublePipe);
s_two_char_tokens.set("??", TokenType::DoubleQuestionMark);
s_two_char_tokens.set("**", TokenType::DoubleAsterisk);
s_two_char_tokens.set("==", TokenType::EqualsEquals);
s_two_char_tokens.set("<=", TokenType::LessThanEquals);
s_two_char_tokens.set(">=", TokenType::GreaterThanEquals);
s_two_char_tokens.set("!=", TokenType::ExclamationMarkEquals);
s_two_char_tokens.set("--", TokenType::MinusMinus);
s_two_char_tokens.set("++", TokenType::PlusPlus);
s_two_char_tokens.set("<<", TokenType::ShiftLeft);
s_two_char_tokens.set(">>", TokenType::ShiftRight);
s_two_char_tokens.set("?.", TokenType::QuestionMarkPeriod);
}
if (s_single_char_tokens.is_empty()) {
s_single_char_tokens.set('&', TokenType::Ampersand);
s_single_char_tokens.set('*', TokenType::Asterisk);
s_single_char_tokens.set('[', TokenType::BracketOpen);
s_single_char_tokens.set(']', TokenType::BracketClose);
s_single_char_tokens.set('^', TokenType::Caret);
s_single_char_tokens.set(':', TokenType::Colon);
s_single_char_tokens.set(',', TokenType::Comma);
s_single_char_tokens.set('{', TokenType::CurlyOpen);
s_single_char_tokens.set('}', TokenType::CurlyClose);
s_single_char_tokens.set('=', TokenType::Equals);
s_single_char_tokens.set('!', TokenType::ExclamationMark);
s_single_char_tokens.set('-', TokenType::Minus);
s_single_char_tokens.set('(', TokenType::ParenOpen);
s_single_char_tokens.set(')', TokenType::ParenClose);
s_single_char_tokens.set('%', TokenType::Percent);
s_single_char_tokens.set('.', TokenType::Period);
s_single_char_tokens.set('|', TokenType::Pipe);
s_single_char_tokens.set('+', TokenType::Plus);
s_single_char_tokens.set('?', TokenType::QuestionMark);
s_single_char_tokens.set(';', TokenType::Semicolon);
s_single_char_tokens.set('/', TokenType::Slash);
s_single_char_tokens.set('~', TokenType::Tilde);
s_single_char_tokens.set('<', TokenType::LessThan);
s_single_char_tokens.set('>', TokenType::GreaterThan);
}
consume();
}
void Lexer::consume()
{
if (m_position >= m_source.length()) {
m_position = m_source.length() + 1;
m_current_char = EOF;
return;
}
if (m_current_char == '\n') {
m_line_number++;
m_line_column = 1;
} else {
m_line_column++;
}
m_current_char = m_source[m_position++];
}
void Lexer::consume_exponent()
{
consume();
if (m_current_char == '-' || m_current_char == '+')
consume();
while (isdigit(m_current_char)) {
consume();
}
}
bool Lexer::is_eof() const
{
return m_current_char == EOF;
}
bool Lexer::is_identifier_start() const
{
return isalpha(m_current_char) || m_current_char == '_' || m_current_char == '$';
}
bool Lexer::is_identifier_middle() const
{
return is_identifier_start() || isdigit(m_current_char);
}
bool Lexer::is_line_comment_start() const
{
return m_current_char == '/' && m_position < m_source.length() && m_source[m_position] == '/';
}
bool Lexer::is_block_comment_start() const
{
return m_current_char == '/' && m_position < m_source.length() && m_source[m_position] == '*';
}
bool Lexer::is_block_comment_end() const
{
return m_current_char == '*' && m_position < m_source.length() && m_source[m_position] == '/';
}
bool Lexer::is_numeric_literal_start() const
{
return isdigit(m_current_char) || (m_current_char == '.' && m_position < m_source.length() && isdigit(m_source[m_position]));
}
void Lexer::syntax_error(const char* msg)
{
m_has_errors = true;
if (m_log_errors)
fprintf(stderr, "Syntax Error: %s (line: %zu, column: %zu)\n", msg, m_line_number, m_line_column);
}
Token Lexer::next()
{
size_t trivia_start = m_position;
// consume whitespace and comments
while (true) {
if (isspace(m_current_char)) {
do {
consume();
} while (isspace(m_current_char));
} else if (is_line_comment_start()) {
consume();
do {
consume();
} while (!is_eof() && m_current_char != '\n');
} else if (is_block_comment_start()) {
consume();
do {
consume();
} while (!is_eof() && !is_block_comment_end());
consume(); // consume *
consume(); // consume /
} else {
break;
}
}
size_t value_start = m_position;
auto token_type = TokenType::Invalid;
if (is_identifier_start()) {
// identifier or keyword
do {
consume();
} while (is_identifier_middle());
StringView value = m_source.substring_view(value_start - 1, m_position - value_start);
auto it = s_keywords.find(value);
if (it == s_keywords.end()) {
token_type = TokenType::Identifier;
} else {
token_type = it->value;
}
} else if (is_numeric_literal_start()) {
if (m_current_char == '0') {
consume();
if (m_current_char == '.') {
// decimal
consume();
while (isdigit(m_current_char)) {
consume();
}
if (m_current_char == 'e' || m_current_char == 'E') {
consume_exponent();
}
} else if (m_current_char == 'e' || m_current_char == 'E') {
consume_exponent();
} else if (m_current_char == 'o' || m_current_char == 'O') {
// octal
consume();
while (m_current_char >= '0' && m_current_char <= '7') {
consume();
}
} else if (m_current_char == 'b' || m_current_char == 'B') {
// binary
consume();
while (m_current_char == '0' || m_current_char == '1') {
consume();
}
} else if (m_current_char == 'x' || m_current_char == 'X') {
// hexadecimal
consume();
while (isxdigit(m_current_char)) {
consume();
}
} else if (isdigit(m_current_char)) {
// octal without 'O' prefix. Forbidden in 'strict mode'
// FIXME: We need to make sure this produces a syntax error when in strict mode
do {
consume();
} while (isdigit(m_current_char));
}
} else {
// 1...9 or period
while (isdigit(m_current_char)) {
consume();
}
if (m_current_char == '.') {
consume();
while (isdigit(m_current_char)) {
consume();
}
}
if (m_current_char == 'e' || m_current_char == 'E') {
consume_exponent();
}
}
token_type = TokenType::NumericLiteral;
} else if (m_current_char == '"' || m_current_char == '\'') {
char stop_char = m_current_char;
consume();
while (m_current_char != stop_char && m_current_char != '\n' && !is_eof()) {
if (m_current_char == '\\') {
consume();
}
consume();
}
if (m_current_char != stop_char) {
syntax_error("unterminated string literal");
token_type = TokenType::UnterminatedStringLiteral;
} else {
consume();
token_type = TokenType::StringLiteral;
}
} else if (m_current_char == EOF) {
token_type = TokenType::Eof;
} else {
// There is only one four-char operator: >>>=
bool found_four_char_token = false;
if (m_position + 2 < m_source.length()) {
if (m_current_char == '>'
&& m_source[m_position] == '>'
&& m_source[m_position + 1] == '>'
&& m_source[m_position + 2] == '=') {
found_four_char_token = true;
consume();
consume();
consume();
consume();
token_type = TokenType::UnsignedShiftRightEquals;
}
}
bool found_three_char_token = false;
if (!found_four_char_token && m_position + 1 < m_source.length()) {
char second_char = m_source[m_position];
char third_char = m_source[m_position + 1];
char three_chars[] { (char)m_current_char, second_char, third_char, 0 };
auto it = s_three_char_tokens.find(three_chars);
if (it != s_three_char_tokens.end()) {
found_three_char_token = true;
consume();
consume();
consume();
token_type = it->value;
}
}
bool found_two_char_token = false;
if (!found_four_char_token && !found_three_char_token && m_position < m_source.length()) {
char second_char = m_source[m_position];
char two_chars[] { (char)m_current_char, second_char, 0 };
auto it = s_two_char_tokens.find(two_chars);
if (it != s_two_char_tokens.end()) {
found_two_char_token = true;
consume();
consume();
token_type = it->value;
}
}
bool found_one_char_token = false;
if (!found_four_char_token && !found_three_char_token && !found_two_char_token) {
auto it = s_single_char_tokens.find(m_current_char);
if (it != s_single_char_tokens.end()) {
found_one_char_token = true;
consume();
token_type = it->value;
}
}
if (!found_four_char_token && !found_three_char_token && !found_two_char_token && !found_one_char_token) {
consume();
token_type = TokenType::Invalid;
}
}
m_current_token = Token(
token_type,
m_source.substring_view(trivia_start - 1, value_start - trivia_start),
m_source.substring_view(value_start - 1, m_position - value_start),
m_line_number,
m_line_column - m_position + value_start);
return m_current_token;
}
}
| [
"[email protected]"
] | |
ec09caed19965ed57a38708dc834a6201362759b | 492976adfdf031252c85de91a185bfd625738a0c | /src/Game/AI/Action/actionFreeMove.h | bdc2e801fa992746fe8831104b400403dea4acd7 | [] | no_license | zeldaret/botw | 50ccb72c6d3969c0b067168f6f9124665a7f7590 | fd527f92164b8efdb746cffcf23c4f033fbffa76 | refs/heads/master | 2023-07-21T13:12:24.107437 | 2023-07-01T20:29:40 | 2023-07-01T20:29:40 | 288,736,599 | 1,350 | 117 | null | 2023-09-03T14:45:38 | 2020-08-19T13:16:30 | C++ | UTF-8 | C++ | false | false | 1,059 | h | #pragma once
#include "KingSystem/ActorSystem/actAiAction.h"
namespace uking::action {
class FreeMove : public ksys::act::ai::Action {
SEAD_RTTI_OVERRIDE(FreeMove, ksys::act::ai::Action)
public:
explicit FreeMove(const InitArg& arg);
~FreeMove() override;
bool init_(sead::Heap* heap) override;
void enter_(ksys::act::ai::InlineParamPack* params) override;
void leave_() override;
void loadParams_() override;
protected:
void calc_() override;
// FIXME: remove this
u8 pad_0x20[0x40];
// static_param at offset 0x60
const float* mSpeed_s{};
// static_param at offset 0x68
const float* mSpeedAddRate_s{};
// static_param at offset 0x70
const float* mAngleSpeed_s{};
// static_param at offset 0x78
const bool* mIsChangeable_s{};
// static_param at offset 0x80
const bool* mIsIgnoreSameAS_s{};
// static_param at offset 0x88
const bool* mAllowPitchRotation_s{};
// static_param at offset 0x90
sead::SafeString mASKeyName_s{};
};
} // namespace uking::action
| [
"[email protected]"
] | |
58514e92995664918b86be20b589c90f7830c54f | cc7b87b6315b53d7682fd1d05481b929363014be | /C++/Volume C/P10042.cpp | 964c6ece8fcd3684c2937d98e40627c7a3089872 | [] | no_license | ptargino/uvaOnlineJudge | b6d02a3c8cc084547247686da82ea0977c55f4af | b8922626122b013d8e668c6521504fce85958a7b | refs/heads/master | 2020-05-19T16:19:34.010520 | 2012-06-30T21:21:06 | 2012-06-30T21:21:06 | 2,787,653 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,127 | cpp | #include <math.h>
#include <iostream>
using namespace std;
bool isPrime(long int n) {
int root = (int) sqrt(n);
for (int i = 3; i < root; i += 2)
if (!(n % i))
return false;
return true;
}
int sumDigits(long n) {
int sum = 0;
while (n) {
sum += n % 10;
n /= 10;
}
return sum;
}
int main() {
long int n, root, i, j;
const long SIZE = 100000;
int MAX_ROOT = (int) sqrt(SIZE);
bool *prime = new bool[SIZE];
memset(prime, true, SIZE);
for (i = 3; i <= MAX_ROOT; i += 2)
if (isPrime(i))
for (j = 2 * i; j < SIZE; j += i)
prime[j] = false;
int sumA, sumB;
int t;
scanf("%d", &t);
for (; t; t--) {
scanf("%ld", &n);
n++;
while (true) {
long num = n;
sumA = 0;
sumB = sumDigits(n);
while (num % 2 == 0) {
sumA += 2;
num /= 2;
}
i = 3;
while (i <= num && num != 1) {
if (prime[i])
while (num % i == 0) {
sumA += sumDigits(i);
num /= i;
}
i += 2;
}
printf("%ld\n", n);
if (sumA == sumB) {
printf("%ld\n", n);
break;
} else {
n++;
}
}
}
}
| [
"[email protected]"
] | |
b9b828d0818d1e36db7998a54d1ba8f7a219905b | a9d13a7251696bc70471792765a6e3b46af40490 | /cpp/21.cpp | bc8d296e2e70f9104e0849ec2216a8347e15015f | [] | no_license | Yesol222/Algorithm | 529e895eb0aa154633f85ae215d41cc74cd5b33e | a8d632935a5bc0413aa097b5ebac435fbf24486a | refs/heads/master | 2023-03-24T23:58:39.799405 | 2021-03-23T06:59:56 | 2021-03-23T06:59:56 | 334,355,839 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 694 | cpp | #include <stdio.h>
int main(){
freopen("input.txt.","rt",stdin);
int i, A[10],B[10],as=0,bs=0,lw=0;
for(i=0;i<10;i++){
scanf("%d",&A[i]);
}
for(i=0;i<10;i++){
scanf("%d",&B[i]);
}
for(i=0;i<10;i++){
if(A[i]>B[i]){
as+=3;
lw=1;
}
else if(A[i]<B[i]){
bs+=3;
lw=2;
}
else{
as+=1;
bs+=1;
}
}
printf("%d %d", as, bs);
if(as==bs){
if(lw==0) printf("D\n");
else if(lw==1) printf("A\n");
else printf("B\n");
}
else if(as>bs) printf("A\n");
else printf("B\n");
return 0;
} | [
"[email protected]"
] | |
1476fd99cb70e74cee533d2ef3d0c0c40cce338e | 309647935d0f8f507207ecf48d124102c1d7197f | /Utility/memory_parser/Password.h | 1f4901f9aa1b7a159acdd5477f26e8dba5bfa642 | [
"MIT"
] | permissive | ThomasChevalier/passwordWallet | 6b59d8afd48c1bbdc89348798beebfa6ced87e7e | 115dbde3e32f2be65071e6f298c4f03ddfe19b09 | refs/heads/master | 2021-03-27T20:00:34.594894 | 2020-04-19T17:03:49 | 2020-04-19T17:03:49 | 71,448,410 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 318 | h | #ifndef PASSWORD_HEADER_THOMAS_CHEVALIER
#define PASSWORD_HEADER_THOMAS_CHEVALIER
#include <cstdint>
#include <string>
struct Password
{
typedef uint8_t id_t;
Password();
id_t id;
uint16_t counter;
std::string name;
std::string password;
std::string userName;
};
#endif // PASSWORD_HEADER_THOMAS_CHEVALIER | [
"[email protected]"
] | |
9bfcdbdbf8f938745730cec44cd6b9b2b078490d | 5932c483784240c78a493cbc349d955c63d3ba9b | /SimpleTfIdfDocument.h | d304ec08a598e5c0f895acc42111f71830ed6a60 | [
"MIT"
] | permissive | UCSB-CS32-F15/cs32-f15-lab07-start | cfb00b221f947271bf666335d84b454f477dc02b | bbb7ba5068329cfb0b5a102c4319ee96308f1821 | refs/heads/master | 2021-01-10T15:20:42.441640 | 2018-02-07T04:30:24 | 2018-02-07T04:30:24 | 46,363,265 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 572 | h | #ifndef SIMPLE_TFIDF_DOCUMENT_H
#define SIMPLE_TFIDF_DOCUMENT_H
#include "GenericTfIdfDocument.h"
class SimpleTfIdfDocument: public GenericTfIdfDocument
{
public:
SimpleTfIdfDocument(std::string id,
std::string text,
std::string metadata="") :
id(id),
text(text),
metadata(metadata) {}
std::string getId() { return this->id;}
std::string getText() { return "stub";} // @@@ DO THE RIGHT THING
std::string getMetadata() { return this->metadata;}
private:
std::string id;
std::string text;
std::string metadata;
};
#endif
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.