blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6e3711b87c97fa3272c56fc9ab4313a9c2f0044d | 3c7e9921abd987e45bb034027717a515943cabe9 | /code/minerx64/Ethminer/libethashseal/GenesisInfo.h | ea25fadefc58babe303ab5234eee3b3d0402b413 | [] | no_license | zhuanbao/gxzb | 2f07380e3b27acb86d46d8d1c77f838593fc98b8 | a40bc93fad5f40bfc410619c5d4265a1bce099d4 | refs/heads/master | 2021-01-12T01:28:53.383633 | 2020-04-22T05:13:44 | 2020-04-22T05:13:44 | 78,386,221 | 2 | 2 | null | 2020-01-26T22:35:49 | 2017-01-09T02:24:32 | C++ | UTF-8 | C++ | false | false | 1,815 | h | /*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file GenesisInfo.h
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#pragma once
#include <string>
#include <libdevcore/FixedHash.h>
#include <libethcore/Common.h>
namespace dev
{
namespace eth
{
/// The network id.
enum class Network
{
//Olympic = 0, ///< Normal Olympic chain.
MainNetwork = 1, ///< Normal Frontier/Homestead/DAO/EIP150/EIP158 chain.
//Morden = 2, ///< Normal Morden chain.
Ropsten = 3, ///< New Ropsten Test Network
TransitionnetTest = 70, ///< Normal Frontier/Homestead/DAO/EIP150/EIP158 chain without all the premine.
FrontierTest = 71, ///< Just test the Frontier-era characteristics "forever" (no Homestead portion).
HomesteadTest = 72, ///< Just test the Homestead-era characteristics "forever" (no Frontier portion).
EIP150Test = 73, ///< Homestead + EIP150 Rules active from block 0 For BlockchainTests
EIP158Test = 74, ///< Homestead + EIP150 + EIP158 Rules active from block 0
Special = 0xff ///< Something else.
};
std::string const& genesisInfo(Network _n);
h256 const& genesisStateRoot(Network _n);
}
}
| [
"ethminer@163.com"
] | ethminer@163.com |
d5b62a4c16cb560e9c2ec27de6b3fef226ab7cf4 | 0979d4b3f1629ddc41a59af107044320bd09f924 | /Save&Load-Handout2/Motor2D/j1App.cpp | 11b277763b49aae3898cf765828d756844f302f7 | [] | no_license | vsRushy/Game_Development | 3667bd3f6883237fbdd392a8d3dcca89039bd506 | 3e538804822547c02fd3c4771ad81c83b724e7d6 | refs/heads/master | 2020-03-29T10:23:12.040431 | 2018-11-30T11:15:25 | 2018-11-30T11:15:25 | 149,802,733 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,049 | cpp | #include <iostream>
#include <sstream>
#include "p2Defs.h"
#include "p2Log.h"
#include "j1Window.h"
#include "j1Input.h"
#include "j1Render.h"
#include "j1Textures.h"
#include "j1Audio.h"
#include "j1Scene.h"
#include "j1App.h"
// Constructor
j1App::j1App(int argc, char* args[]) : argc(argc), args(args)
{
frames = 0;
input = new j1Input();
win = new j1Window();
render = new j1Render();
tex = new j1Textures();
audio = new j1Audio();
scene = new j1Scene();
// Ordered for awake / Start / Update
// Reverse order of CleanUp
AddModule(input);
AddModule(win);
AddModule(tex);
AddModule(audio);
AddModule(scene);
// render last to swap buffer
AddModule(render);
}
// Destructor
j1App::~j1App()
{
// release modules
p2List_item<j1Module*>* item = modules.end;
while(item != NULL)
{
RELEASE(item->data);
item = item->prev;
}
modules.clear();
config_file.reset();
}
void j1App::AddModule(j1Module* module)
{
module->Init();
modules.add(module);
}
// Called before render is available
bool j1App::Awake()
{
bool ret = LoadConfig();
// self-config
title.create(app_config.child("title").child_value());
organization.create(app_config.child("organization").child_value());
if(ret == true)
{
p2List_item<j1Module*>* item;
item = modules.start;
while(item != NULL && ret == true)
{
ret = item->data->Awake(config.child(item->data->name.GetString()));
item = item->next;
}
}
return ret;
}
// Called before the first frame
bool j1App::Start()
{
bool ret = true;
p2List_item<j1Module*>* item;
item = modules.start;
while(item != NULL && ret == true)
{
ret = item->data->Start();
item = item->next;
}
return ret;
}
// Called each loop iteration
bool j1App::Update()
{
bool ret = true;
PrepareUpdate();
if(input->GetWindowEvent(WE_QUIT) == true)
ret = false;
if(ret == true)
ret = PreUpdate();
if(ret == true)
ret = DoUpdate();
if(ret == true)
ret = PostUpdate();
FinishUpdate();
return ret;
}
// ---------------------------------------------
bool j1App::LoadConfig()
{
bool ret = true;
pugi::xml_parse_result result = config_file.load_file("config.xml");
if(result == NULL)
{
LOG("Could not load map xml file config.xml. pugi error: %s", result.description());
ret = false;
}
else
{
config = config_file.child("config");
app_config = config.child("app");
}
return ret;
}
// ---------------------------------------------
void j1App::PrepareUpdate()
{
}
// ---------------------------------------------
void j1App::FinishUpdate()
{
// TODO 1: This is a good place to call load / Save functions
if (wants_save)
{
RealSave();
}
if (wants_load)
{
RealLoad();
}
}
// Call modules before each loop iteration
bool j1App::PreUpdate()
{
bool ret = true;
p2List_item<j1Module*>* item;
item = modules.start;
j1Module* pModule = NULL;
for(item = modules.start; item != NULL && ret == true; item = item->next)
{
pModule = item->data;
if(pModule->active == false) {
continue;
}
ret = item->data->PreUpdate();
}
return ret;
}
// Call modules on each loop iteration
bool j1App::DoUpdate()
{
bool ret = true;
p2List_item<j1Module*>* item;
item = modules.start;
j1Module* pModule = NULL;
for(item = modules.start; item != NULL && ret == true; item = item->next)
{
pModule = item->data;
if(pModule->active == false) {
continue;
}
ret = item->data->Update(dt);
}
return ret;
}
// Call modules after each loop iteration
bool j1App::PostUpdate()
{
bool ret = true;
p2List_item<j1Module*>* item;
j1Module* pModule = NULL;
for(item = modules.start; item != NULL && ret == true; item = item->next)
{
pModule = item->data;
if(pModule->active == false) {
continue;
}
ret = item->data->PostUpdate();
}
return ret;
}
// Called before quitting
bool j1App::CleanUp()
{
bool ret = true;
p2List_item<j1Module*>* item;
item = modules.end;
while(item != NULL && ret == true)
{
ret = item->data->CleanUp();
item = item->prev;
}
return ret;
}
//----------------------------------------
// TODO 1
void j1App::SaveGame() const
{
wants_save = true;
}
void j1App::LoadGame()
{
wants_load = true;
}
// ---------------------------------------
int j1App::GetArgc() const
{
return argc;
}
// ---------------------------------------
const char* j1App::GetArgv(int index) const
{
if(index < argc)
return args[index];
else
return NULL;
}
// ---------------------------------------
const char* j1App::GetTitle() const
{
return title.GetString();
}
// ---------------------------------------
const char* j1App::GetOrganization() const
{
return organization.GetString();
}
// TODO 4: Create a simulation of the xml file to read
// TODO 5: Create a method to actually load an xml file
// then call all the modules to load themselves
bool j1App::RealLoad()
{
LOG("Loading...");
bool ret = false;
pugi::xml_document data;
pugi::xml_node node;
pugi::xml_parse_result result = data.load_file("Saving.xml");
if (result != NULL)
{
node = data.child("save");
p2List_item<j1Module*>* item = modules.start;
ret = true;
while (item != NULL && ret == true)
{
ret = item->data->Load(node.child(item->data->name.GetString()));
item = item->next;
}
data.reset();
if (ret == true)
LOG("LOADING COMPLETE.");
else
LOG("-----LOADING ERROR-----");
}
else
{
LOG("COULDN'T READ THE .XML FILE... %s", result.description());
}
wants_load = false;
return ret;
}
// TODO 7: Create a method to save the current state
bool j1App::RealSave() const
{
LOG("Saving...");
bool ret = true;
pugi::xml_document data;
pugi::xml_node node;
node = data.append_child("save");
p2List_item<j1Module*>* item;
item = modules.start;
while (item != NULL && ret == true)
{
ret = item->data->Save(node.append_child(item->data->name.GetString()));
item = item->next;
}
if (ret == true)
{
data.save_file("Saving.xml");
LOG("SAVING COMPLETE.");
}
else
LOG("-----SAVING ERROR-----");
data.reset();
wants_save = false;
return ret;
}
| [
"gerardmarcosfreixasgmail.com"
] | gerardmarcosfreixasgmail.com |
846bfb20a1c57e5f185d5827c774bfa8383b6ea2 | 8bb6488244fdb1b32c6d64d6f4c1429d34dda05d | /Projects/Editor/Source/GUI/Controls/CWindow.h | 010be4a501cd2c95db9b5b43a66e9ac38a19fe8d | [
"MIT"
] | permissive | amyvmiwei/skylicht-engine | be6e6c3205996b68bcb5fd3fe4cbafde9e65d397 | 54f9d1d02bdc9aa1f785569f62abbdb8ae106361 | refs/heads/master | 2023-06-30T07:07:23.124407 | 2021-08-05T02:53:10 | 2021-08-05T02:53:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,467 | h | /*
!@
MIT License
Copyright (c) 2020 Skylicht Technology CO., LTD
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.
This file is part of the "Skylicht Engine".
https://github.com/skylicht-lab/skylicht-engine
!#
*/
#pragma once
#include "GUI/Controls/CBase.h"
#include "GUI/Controls/CLabel.h"
#include "GUI/Controls/CIcon.h"
#include "GUI/Controls/CIconButton.h"
#include "GUI/Controls/CResizableControl.h"
namespace Skylicht
{
namespace Editor
{
namespace GUI
{
class CWindow : public CResizableControl
{
protected:
CDragger* m_titleBar;
CLabel* m_title;
CIcon* m_icon;
CIconButton* m_close;
bool m_childStyle;
public:
CWindow(CBase* parent, float x, float y, float w, float h);
virtual ~CWindow();
virtual void onCloseWindow();
virtual void renderUnder();
virtual void touch();
virtual void onChildTouched(CBase* child);
void setStyleChild(bool b);
void setCaption(const std::wstring& text)
{
m_title->setString(text);
}
const std::wstring& getCaption()
{
return m_title->getString();
}
inline void showIcon(bool b)
{
m_icon->setHidden(!b);
}
void setIcon(ESystemIcon icon)
{
m_icon->setIcon(icon);
m_icon->setHidden(false);
}
inline void showCloseButton(bool b)
{
m_close->setHidden(!b);
}
void dragMoveCommand(const SPoint& mouseOffset);
protected:
void onCloseButtonPress(CBase* sender);
};
}
}
} | [
"hongduc.pr@gmail.com"
] | hongduc.pr@gmail.com |
cd2d18e4fbaf1b03172539551dc39924abfdc3de | 1f4e87741d1638a30dc5a41370d212c8125881a1 | /src/Temp.h | 33eabedb027a892159c24d3444daf649d1386ab7 | [] | no_license | aquatack/TempSensor | 8cfdb6427b21c2c9f41cab86cbdb5c490fd37621 | 3eb1a20c9b8022a33b549ef5b46a4e002e363765 | refs/heads/master | 2021-04-15T10:15:55.335722 | 2018-03-21T23:46:51 | 2018-03-21T23:46:51 | 126,237,079 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 94 | h | class Temp
{
const int inputPin;
public:
Temp(int input);
float getTempDegC();
};
| [
"jez@kingjez.com"
] | jez@kingjez.com |
163a73944363b30bf6c8a956ddb692011fa8357c | 03781c98597e3cc175a4c0ae25951167f7c41e6a | /51nod/1135.cpp | 1faaedffa22f2ad0b2a527aa4e255227dd3ba4d3 | [] | no_license | Liuchenlong/acm | e4ea0d59739d05ae808a45c4164decf91f2087ff | d52dc289d836874dd30f4d8a5a2002398a0639e8 | refs/heads/master | 2020-04-03T22:06:28.611879 | 2019-09-28T14:08:27 | 2019-09-28T14:08:27 | 59,131,382 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,140 | cpp | #include<cstdio>
#include<cmath>
#include<stdlib.h>
#include<map>
#include<set>
#include<time.h>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
long long qpow(long long x,long long k,long long mod)
{
long long ans=1;
while(k)
{
if(k&1)
ans=ans*x%mod;
k>>=1;
x=x*x%mod;
}
return ans;
}
//求原根
vector<long long>a;
bool g_test(long long g,long long p)
{
for(long long i=0;i<a.size();i++)
{
if(qpow(g,(p-1)/a[i],p)==1)
return 0;
}
return 1;
}
long long primitive_root(long long p)
{
long long tmp=p-1;
a.clear();
for(long long i=2;i<=tmp/i;i++)
{
if(tmp%i==0)
{
a.push_back(i);
while(tmp%i==0)
tmp/=i;
}
}
if(tmp!=1)
a.push_back(tmp);
long long g=1;
while(true)
{
if(g_test(g,p))
return g;
g++;
}
}
int main()
{
long long x;
scanf("%I64d",&x);
printf("%I64d\n",primitive_root(x));
return 0;
}
| [
"lcl.maopao@gmail.com"
] | lcl.maopao@gmail.com |
da1177ddec99ada4cd9eb7bca707f1d21f04a3f0 | af92ce76e202ef6a1110a77a2221e0bf7b590360 | /WinMain.cpp | f299b2dbe39f6e45e1c7581666901f9b5495aaf3 | [] | no_license | KoreaRifle/FBX | 7d8dacaa15d0bd81f3cde09c1dfcf805b5924189 | 9004c0570bd73c461f4c6728c120cd69db4462b0 | refs/heads/master | 2021-05-14T10:12:14.458178 | 2018-01-25T12:22:03 | 2018-01-25T12:22:03 | 116,346,170 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 538 | cpp | #include "stdafx.h"
#include "GameMain.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdParam, int nCmdShow)
{
srand((UINT)time(NULL));
D3DInfo info;
info.appName = L"DirectX Game";
info.instance = hInstance;
info.isFullScreen = false;
info.isVsync = true;
info.mainHandle = NULL;
info.screenWidth = 1280;
info.screenHeight = 720;
info.clearColor = D3DXCOLOR(0.5f, 0.5f, 0.5f, 1.0f);
D3D::SetInfo(info);
GameMain* gameMain = new GameMain();
gameMain->Run();
delete gameMain;
return 0;
} | [
"hey5847@naver.com"
] | hey5847@naver.com |
9121c40e19538e910314e733a09fba312fdd55f7 | e065ff43fa081c349732adc2520c172760fc16ce | /Department.h | 0478bfaa84b3d5ef63f36c5f42ea1c51a4a467dc | [] | no_license | pn1137/University-Administration-System | e67fe5e99543a5973056d21300041747bb07148a | f0b794bfe4ecae72a91246b550567b13ab071a8c | refs/heads/main | 2023-06-21T00:28:16.213952 | 2021-07-26T19:26:59 | 2021-07-26T19:26:59 | 389,742,662 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,903 | h | /*
* C++ class that represents a university department
* Patrick Naugle : 22 November 2016
*/
#ifndef DEPARTMENT_H
#define DEPARTMENT_H
#include <vector>
#include <string>
// Forward declarations
class Student;
class Assistant;
class Teacher;
class Course;
class Department
{
private:
std::string departmentName; // Name of the department
std::vector<Student *> studentList; // List of students in the department
std::vector<Assistant *> assistantList; // List of assistants in the department
std::vector<Teacher *> teacherList; // List of teachers in the department
std::vector<Course *> courseList; // List of courses in the department
public:
Department(std::string departmentTitle); // Constructor to create a department
~Department(); // Destructor to destroy a department
void addStudent(Student *student); // Add a student to the department
void addAssistant(Assistant *assistant); // Add an assistant to the department
void addTeacher(Teacher *teacher); // Add a teacher to the department
void addCourse(Course *course); // Add a course to the department
std::string getDepartmentName(); // Returns the department name
void removeStudent(Student *student); // Remove a student from the department
void removeAssistant(Assistant *assistant); // Remove an assistant from the department
void removeTeacher(Teacher *teacher); // Remove a teacher from the department
void removeCourse(Course *course); // Remove a course from the department
void printStudentList(); // Output the students in the department
void printTeacherList(); // Output the teachers and assistants
// in the department
void printCourseList(); // Output the courses in the department
};
#endif | [
"noreply@github.com"
] | pn1137.noreply@github.com |
381f2da9721b0e40db97ee7be015018e44a012af | 18c86636ee70c1495cb9a2dc0c139789bf9c01ec | /src/mmserve.cpp | 2daf35f144c18ec69c4c386db536e653b0873097 | [
"MIT"
] | permissive | icare4mm/mastermind-strategy | 6358ff4e28cc6a45c0a3345b701b4dc9a7c85091 | c9331276deabc31e7466e06e3a36fd83d27967c2 | refs/heads/master | 2021-01-20T00:58:16.122735 | 2016-01-24T17:07:10 | 2016-01-24T17:07:10 | 34,733,920 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,217 | cpp | /* mmserve.cpp - Mastermind codemaker */
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include "Mastermind.hpp"
using namespace Mastermind;
struct Constraint
{
Codeword guess;
Feedback response;
Constraint() { }
Constraint(const Codeword &_guess, const Feedback &_response)
: guess(_guess), response(_response) { }
};
class Analyst
{
Engine e;
// List of all codewords.
CodewordList all;
// Stack of remaining possibilities corresponding to each constraint.
std::vector<CodewordRange> _secrets;
// Stack of constraints.
std::vector<Constraint> _constraints;
public:
explicit Analyst(const Rules &rules)
: e(rules), all(e.generateCodewords())
{
_secrets.push_back(CodewordRange(all));
}
#if 0
FeedbackFrequencyTable
void partition(const Codeword &guess)
{
FeedbackFrequencyTable freq = e.partition(_remaining, guess);
}
#endif
Engine& engine() { return e; }
void push_constraint(const Codeword &guess, const Feedback &response)
{
// Partition the remaining possibilities.
CodewordRange remaining = _secrets.back();
CodewordPartition cells = e.partition(remaining, guess);
remaining = cells[response.value()];
// Update internal state.
_constraints.push_back(Constraint(guess, response));
_secrets.push_back(remaining);
}
void pop_constraint()
{
assert(!_constraints.empty());
_constraints.pop_back();
_secrets.pop_back();
}
/// Returns a list of remaining possibilities.
CodewordConstRange possibilities() const
{
return _secrets.back();
}
/// Returns a list of constraints.
util::range<std::vector<Constraint>::const_iterator> constraints() const
{
return util::range<std::vector<Constraint>::const_iterator>
(_constraints.begin(), _constraints.end());
}
};
/// Displays help screen for player mode.
static void help()
{
std::cout <<
"Input your guess (e.g. 1234) or type one of the following commands:\n"
" !,cheat show the secret\n"
" h,help display this help screen\n"
" l,list list remaining possibilities\n"
" q,quit quit the program\n"
" r,recap display guesses and responses so far\n"
"";
}
/// Displays remaining possibilities.
static void list(CodewordConstRange secrets)
{
for (CodewordConstIterator it = secrets.begin(); it != secrets.end(); ++it)
{
std::cout << *it << ' ';
}
std::cout << std::endl;
}
/// Displays current constraints.
static void recap(const Analyst &game)
{
if (game.constraints().empty())
{
std::cout << "You haven't made any guess yet!\n";
}
else
{
for (size_t i = 0; i < game.constraints().size(); ++i)
{
const Constraint &c = game.constraints()[i];
std::cout << c.guess << " " << c.response << std::endl;
}
}
}
/// Enters interactive player mode. This starts a prompt for user commands,
/// until either the user enter "quit" or reveals the secret.
/// Important output are put to STDOUT.
/// Informational messages are put to STDOUT.
static int serve(const Engine *e, bool verbose, const Codeword &given_secret)
{
Analyst game(e->rules());
// Generate all codewords.
CodewordList all = e->generateCodewords();
if (verbose)
{
std::cout << "There are " << all.size() << " codewords. "
<< "Please make guesses or type help for help." << std::endl;
}
// Generate a random secret if one is not specified.
Codeword secret = given_secret;
if (secret.IsEmpty())
{
srand((unsigned int)time(NULL));
rand();
int i = rand() % all.size();
secret = all[i];
}
for (;;)
{
// Display prompt.
if (verbose)
{
std::cout << "> ";
std::flush(std::cout);
}
// Read a line of command.
std::string line;
std::getline(std::cin, line);
std::istringstream ss(line);
// Read command.
std::string cmd;
if (!(ss >> cmd))
break;
// If we're in interactive mode, we would accept a command.
if (verbose)
{
if (cmd == "!" || cmd == "cheat")
{
if (verbose)
std::cout << "Secret is ";
std::cout << secret << std::endl;
continue;
}
if (cmd == "h" || cmd == "help")
{
help();
continue;
}
if (cmd == "l" || cmd == "list")
{
list(game.possibilities());
continue;
}
if (cmd == "q" || cmd == "quit")
{
break;
}
if (cmd == "r" || cmd == "recap")
{
recap(game);
continue;
}
}
// Now we expect a guess from the input.
Codeword guess;
std::istringstream ss2(cmd);
if (!(ss2 >> setrules(e->rules()) >> guess))
{
std::cout << "Invalid command or guess: " << cmd << std::endl;
continue;
}
// Compute the response and display it.
Feedback response = e->compare(guess, secret);
if (verbose)
std::cout << guess << " ";
std::cout << response << std::endl;
game.push_constraint(guess, response);
if (response == Feedback::perfectValue(e->rules()))
break;
}
return 0;
}
/// Displays command line usage information.
static void usage()
{
std::cerr <<
"Usage: mmserve [-r rules] [options]\n"
"Serve as a codemaker for a Mastermind game.\n"
"Rules: 'p' pegs 'c' colors 'r'|'n'\n"
" mm,p4c6r [default] Mastermind (4 pegs, 6 colors, with repetition)\n"
" bc,p4c10n Bulls and Cows (4 pegs, 10 colors, no repetition)\n"
" lg,p5c8r Logik (5 pegs, 8 colors, with repetition)\n"
"Options:\n"
" -h display this help screen and exit\n"
" -i interactive mode; display instructions\n"
" -u secret use the given secret instead of generating a random one\n"
" -v displays version and exit\n"
"";
}
/// Displays version information.
static void version()
{
std::cout <<
"Mastermind Strategies Version " << MM_VERSION_MAJOR << "."
<< MM_VERSION_MINOR << "." << MM_VERSION_TWEAK << std::endl
<< "Configured with max " << MM_MAX_PEGS << " pegs and "
<< MM_MAX_COLORS << " colors.\n"
"Visit http://code.google.com/p/mastermind-strategy/ for updates.\n"
"";
}
#define USAGE_ERROR(msg) do { \
std::cerr << "Error: " << msg << ". Type -h for help." << std::endl; \
return 1; \
} while (0)
#define USAGE_REQUIRE(cond,msg) do { \
if (!(cond)) USAGE_ERROR(msg); \
} while (0)
int main(int argc, char* argv[])
{
Rules rules(4, 6, true);
bool verbose = false;
Codeword secret;
// Parse command line arguments.
for (int i = 1; i < argc; i++)
{
std::string s = argv[i];
if (s == "-h")
{
usage();
return 0;
}
else if (s == "-i")
{
verbose = true;
}
else if (s == "-u")
{
USAGE_REQUIRE(++i < argc, "missing argument for option -u");
std::string arg(argv[i]);
std::istringstream ss(arg);
USAGE_REQUIRE(ss >> setrules(rules) >> secret, "expecting secret after -u");
}
else if (s == "-v")
{
version();
return 0;
}
else
{
USAGE_ERROR("unknown option: " << s);
}
}
// Create an algorithm engine and begin the game.
Engine engine(rules);
serve(&engine, verbose, secret);
return 0;
}
| [
"fancitron@gmail.com"
] | fancitron@gmail.com |
2d376a96b366c820554bbd10b33d9697b9f99e50 | b449f16bf8a945eb25336ff9b40514984f647863 | /ProjectHP/StrongSpell.h | da38cc9d57f90fc3fc32f1920b67a929e6045aa6 | [] | no_license | vino333/HarryPotter | 89004d8b9b6669a9504352be6e007b133458aa34 | cecc2fd940de9b645193a160bd71e5034673cffe | refs/heads/master | 2020-08-06T00:10:55.502945 | 2019-10-04T11:01:02 | 2019-10-04T11:01:02 | 212,765,606 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 212 | h | #pragma once
#include "Spell.h"
#include "General.h"
class StrongSpell :
public Spell
{
public:
StrongSpell(sf::Vector2f pos, sf::Vector2f direction);
~StrongSpell();
private:
static bool m_registerit;
};
| [
"yonadav333@gmail.com"
] | yonadav333@gmail.com |
43cac87ee3cbbbabd0b7ce50a9fef8ad95c820d2 | 023b1734ab09079bda1627b17f3619e318cbf35e | /code/example/ltgen.cpp | cbfcdd50a90def4308b5afd230ba1758683f56de | [
"MIT"
] | permissive | GeeLaw/vecole-redux | c28a64ce29553fe43406d883e846c5f4127c86df | b82182df31416af8d4f8a559cef69bfda3e63145 | refs/heads/master | 2020-12-02T19:31:51.901587 | 2017-11-11T23:40:23 | 2017-11-11T23:40:23 | 96,355,462 | 0 | 1 | null | 2017-10-03T20:04:17 | 2017-07-05T19:46:19 | C++ | UTF-8 | C++ | false | false | 6,160 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include"../library/luby.hpp"
#include"../library/erasure.hpp"
#include"../library/cryptography.hpp"
#include<random>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<algorithm>
using namespace Encoding::Erasure;
using namespace Encoding::LubyTransform;
constexpr unsigned SmallSampleSize = 500;
constexpr unsigned LargeSampleSize = 20000;
typedef Cryptography::Z<4294967291u> Zp;
typedef std::mt19937 RNG;
char const *ofn;
unsigned w;
double c = 0.5;
unsigned v, vErased;
bool *boolArray;
Zp *plain, *encoded, *decoded;
RNG rng((unsigned)time(nullptr));
std::uniform_int_distribution<uint32_t> UZp(0u, 4294967290u);
bool ParseCommandLine(int const argc, char ** const argv);
void PrintUsage();
double TestLTCode(LTCode<> const &code, unsigned const count);
int main(int argc, char **argv)
{
if (!ParseCommandLine(argc, argv))
{
PrintUsage();
return -1;
}
RobustSolitonDistribution rsd;
rsd.InputSymbolSize = w;
rsd.Delta = 0.01;
rsd.C = c;
for (rsd.InvalidateCache();
rsd.OutputSymbolSizeCached <= v;
rsd.C += 1e-5, rsd.InvalidateCache())
;
for (; rsd.OutputSymbolSizeCached > v;
rsd.C -= 1e-5, rsd.InvalidateCache())
;
fprintf(stderr, "Found c = %f giving v = %zu.\n",
rsd.C, rsd.OutputSymbolSizeCached);
LTCode<> code;
double bestSuccessRate = 0.0;
char outputFileName[40];
unsigned candidateIndex = 0u;
while (true)
{
CreateLTCode(rsd, code, rng);
std::sort(code.Bins.data(), code.Bins.data() + code.Bins.size());
double successRate = TestLTCode(code, SmallSampleSize);
if (successRate < 0)
return -1;
if (successRate <= bestSuccessRate)
continue;
fprintf(stderr, "\nFound a good candidate (%f%%, sample size = %u), testing more.\n", successRate * 100, SmallSampleSize);
successRate = TestLTCode(code, LargeSampleSize);
if (successRate < 0)
return -1;
if (successRate <= bestSuccessRate)
{
fputs("Further test finished: discarded.\n", stderr);
continue;
}
fprintf(stderr, "Further test finished: saving (%f%%, sample size = %u).\n", successRate * 100, LargeSampleSize);
sprintf(outputFileName, "%s.%03u.luby", ofn, candidateIndex++);
FILE *fp = fopen(outputFileName, "w");
if (!fp)
{
fprintf(stderr, "Could not open %s for writing.\n", outputFileName);
return -1;
}
code.SaveTo(fp);
fclose(fp);
fputs("Further test finished: saved.\n", stderr);
bestSuccessRate = successRate;
}
return 0;
}
bool ParseUInt(char const *arg, char const *name, unsigned *p, unsigned mini, unsigned maxi)
{
if (sscanf(arg, "%u", p) != 1)
{
fprintf(stderr, "The format for %s is incorrect.\n", name);
return false;
}
if (*p < mini || *p > maxi)
{
fprintf(stderr, "The allowed range of %s is [%u, %u].\n", name, mini, maxi);
return false;
}
return true;
}
bool ParseCommandLine(int const argc, char ** const argv)
{
if (argc < 4 || argc > 5)
return false;
ofn = argv[1];
if (ofn[0] == '\0'
|| ofn[1] == '\0'
|| ofn[2] == '\0')
{
fputs("The minimal length of ofn is 3.\n", stderr);
return false;
}
for (char const *i = ofn; *i; ++i)
if (!((*i >= '0' && *i <= '9')
|| (*i >= 'a' && *i <= 'z')
|| (*i >= 'A' && *i <= 'Z')
|| *i == '_'))
{
fputs("The allowed characters for ofn are 0-9, a-z, A-Z and _.\n", stderr);
return false;
}
else if (i - ofn > 20)
{
fputs("The maximal length of ofn is 20.\n", stderr);
return false;
}
if (!ParseUInt(argv[2], "w", &w, 5000, 40000))
return false;
if (!ParseUInt(argv[3], "v", &v, 2 * w, 4 * w))
return false;
if (argc >= 5)
{
if (sscanf(argv[4], "%lf", &c) != 1)
{
fputs("The format for c is incorrect.\n", stderr);
return false;
}
if (c < 0.5 || c > 20)
{
fputs("The allowed range of c is [0.5, 20].\n", stderr);
return false;
}
}
vErased = v / 4;
boolArray = new bool[w + v];
plain = new Zp[w];
encoded = new Zp[v];
decoded = new Zp[w];
return true;
}
void PrintUsage()
{
fputs
(
"Usage: ltgen ofn w v [c]\n\n"
" ofn: the prefix of output file.\n"
" w: the number of inputs to LT code (10000 for k = 182, 20000 for k = 240).\n"
" v: the number of outputs from LT code (33124 for k = 182, 57600 for k = 240).\n"
" c: optional, minimum c in LT code, defaults to 0.5.",
stderr
);
}
double TestLTCode(LTCode<> const &code, unsigned const count)
{
LTCode<> surrogate;
unsigned success = 0u;
for (unsigned i = 0u; i != count; ++i)
{
memset(boolArray, false, w * sizeof(bool));
memset(boolArray + w, true, v * sizeof(bool));
for (unsigned j = 0u; j != w; ++j)
plain[j] = UZp(rng);
EraseSubsetExact(boolArray + w, boolArray + w + v, vErased, rng);
for (unsigned j = 0u; j != v; ++j)
encoded[j] = 0;
code.Encode(encoded, (bool const *)boolArray + w, (Zp const *)plain);
surrogate = code;
if (!surrogate.DecodeDestructive
(
boolArray, boolArray + w,
decoded,
boolArray + w, boolArray + w + v,
encoded, encoded + v
))
continue;
for (unsigned j = 0u; j != w; ++j)
if (decoded[j] != plain[j])
{
fputs("There is a mistake in Luby Transform algorithm.\n", stderr);
fprintf(stderr, "Index %u: was %u, decoded to %u.\n", j, (unsigned)plain[j], (unsigned)decoded[j]);
return -1.0;
}
++success;
}
return (double)success / count;
}
| [
"geelaw@outlook.com"
] | geelaw@outlook.com |
f2aa7b751f839972a6e75d5d2c59068a324d6068 | 451711a9d6735482d0d7b6ebeb797f00f2f08b7d | /openVideo.cpp | 1338cfa56b8a32cb6498fbafea1afcc5214049ab | [] | no_license | t20134297/reverse_video | 3b3ff83dfaceebc06e4fa3ecf018af6302172bad | e8c72a4e5701a85cef6cbd58a2024903d8d9d549 | refs/heads/master | 2021-05-04T15:58:03.404500 | 2018-02-05T01:46:28 | 2018-02-05T01:46:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,261 | cpp | #include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int* video2image(string videoname)
{
int* inf=new int[4];
VideoCapture capture(videoname);
if (!capture.isOpened())
{
cout<<"failede open video"<<endl;
return 0;
}
string image_name;
Mat frame;
int frame_number = capture.get(CV_CAP_PROP_FRAME_COUNT);
int frame_fps = capture.get(CV_CAP_PROP_FPS);
int frame_width = capture.get(CV_CAP_PROP_FRAME_WIDTH);
int frame_height = capture.get(CV_CAP_PROP_FRAME_HEIGHT);
inf[0]=frame_number;
inf[1]=frame_fps;
inf[2]=frame_width;
inf[3]=frame_height;
int count=1;
for(count=1;count<=frame_number;count++)
{
capture>>frame;
image_name="./photos/"+to_string(count)+".jpg";
imwrite(image_name,frame);
}
return inf;
}
int image2video(int* inf,string name)
{
VideoWriter writer;
int isColor=1;
int count=inf[0];
int frame_fps=inf[1];
int frame_width=inf[2];
int frame_height=inf[3];
string photo_name;
Mat image;
string videoname=name;
writer = VideoWriter(videoname,CV_FOURCC('M','P','E','G'),frame_fps,Size(frame_width,frame_height),isColor);
while(count>0)
{
photo_name="./photos/"+to_string(count)+".jpg";
image=imread(photo_name);
if(!image.data)
{
cout<<"couldn't load image"<<endl;
}
if(!image.empty())
{
imshow("image to video",image);
waitKey(10);
}
writer.write(image);
--count;
}
return 1;
}
int video_from_camera(string name)
{
VideoCapture capture(1);
if(!capture.isOpened())
{
cout<<"open camera failed"<<endl;
return 0;
}
VideoWriter writer;
int isColor=1;
int frame_fps=30;
int frame_width=capture.get(CV_CAP_PROP_FRAME_WIDTH);
int frame_height=capture.get(CV_CAP_PROP_FRAME_HEIGHT);
Mat image;
string videoname=name;
writer = VideoWriter(videoname,CV_FOURCC('M','P','E','G'),frame_fps,Size(frame_width,frame_height),isColor);
while(true)
{
capture>>image;
writer.write(image);
imshow("camera show",image);
if(waitKey(5)==27)
break;
}
return 0;
}
int main()
{
int* inf=new int[4];
inf = video2image("youyisi.mpeg");
image2video(inf,"water.mpeg");
return 0;
}
| [
"haha@jaha.com"
] | haha@jaha.com |
adc9a9037ef5e8a98fa935cd9a6f18361f1de725 | 1eec93a33b1e9bc389234261c7e801516cf61a92 | /Object/CCharacter.h | ddcb5b0bfea878dd0702fe927a84fd51d7b41144 | [] | no_license | hello158910/OpenGL | 94782d463ca67ed440fd2e3934e19f98698e4501 | bd3cdae8235dad1329fa09f408a07206642d46ff | refs/heads/master | 2021-03-16T05:05:55.542758 | 2019-06-10T16:16:16 | 2019-06-10T16:16:16 | 91,534,595 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,202 | h | #ifndef CCHARACTER_H
#define CCHARACTER_H
#include "../header/Angel.h"
#include "../Common/CQuad.h"
#include "../Common/CPentagon.h"
#include "CBullet.h"
#include <list>
typedef Angel::vec4 color4;
typedef Angel::vec4 point4;
#define QUAD_NUM 6 // 3 faces, 3 triangles/face
#define SHIELD_NUM 3
#define BULLET_NUM 1
#define STA_NORMAL 0
#define STA_HURT 1
#define STA_DYING 2
class CCharacter
{
private:
int _planeStatus;
CBullet *_bullets;
CQuad *_plane;
CQuad *_shield[SHIELD_NUM];
vec3 _planeT = (5.2f,5.2f,0);
float _shieldT[SHIELD_NUM][3] = { 0 };
mat4 _mxPlaneT, _mxShieldT[SHIELD_NUM];
mat4 _mxPlaneR, _mxShieldR[SHIELD_NUM];
mat4 _mxModelView;
mat4 _mxIdentity;
vec4 _color = vec4(0.3f, 0.6f, 0.9f, 1.0f);
GLfloat _shieldAngle = 0;
GLfloat _Tx = 0, _Ty = 0; // motion
float _count = 0;
// bullet
std::list<CBullet*> _freeList;
std::list<CBullet*> _inUsedList;
int _freeNum;
int _usedNum;
public:
CCharacter(mat4 Projection);
~CCharacter();
void createShield(mat4 Projection);
void GL_Display();
void onFrameMove(float dt);
// void UpdateMatrix();
void Move(float x ,float y);
void Fire();
void SetPlaneStatus(int x);
void reset();
};
#endif | [
"hello158910@gmail.com"
] | hello158910@gmail.com |
6a6e9bcc968cb670dcd697060abeddeab690559d | c83c0527e80703c44ea3da969a9f5cf85d48fea1 | /apps/deferred-renderer-01-geometry-pass/Application.hpp | 323f2a1002611096d8ff130a28aab0ea9f3135aa | [] | no_license | KrisNumber24/opengl-avance | b0638cab797a5fa9208d5a9fadcd302a32d1efbd | 7ce67af9c67fafd5cb38a8723f5b41548d51f3a6 | refs/heads/master | 2021-04-29T04:39:21.897626 | 2017-01-18T11:04:33 | 2017-01-18T11:04:33 | 77,993,986 | 0 | 0 | null | 2017-01-04T07:53:23 | 2017-01-04T07:53:23 | null | UTF-8 | C++ | false | false | 3,544 | hpp | #pragma once
#include <glmlv/filesystem.hpp>
#include <glmlv/GLFWHandle.hpp>
#include <glmlv/GLProgram.hpp>
#include <glmlv/ViewController.hpp>
#include <glmlv/simple_geometry.hpp>
#include <glm/glm.hpp>
#include <limits>
class Application
{
public:
Application(int argc, char** argv);
int run();
private:
void initScene();
void initShadersData();
static glm::vec3 computeDirectionVector(float phiRadians, float thetaRadians)
{
const auto cosPhi = glm::cos(phiRadians);
const auto sinPhi = glm::sin(phiRadians);
const auto sinTheta = glm::sin(thetaRadians);
return glm::vec3(sinPhi * sinTheta, glm::cos(thetaRadians), cosPhi * sinTheta);
}
const size_t m_nWindowWidth = 1280;
const size_t m_nWindowHeight = 720;
glmlv::GLFWHandle m_GLFWHandle{ m_nWindowWidth, m_nWindowHeight, "Template" }; // Note: the handle must be declared before the creation of any object managing OpenGL resource (e.g. GLProgram, GLShader)
const glmlv::fs::path m_AppPath;
const std::string m_AppName;
const std::string m_ImGuiIniFilename;
const glmlv::fs::path m_ShadersRootPath;
const glmlv::fs::path m_AssetsRootPath;
// GBuffer:
enum GBufferTextureType
{
GPosition = 0,
GNormal,
GAmbient,
GDiffuse,
GGlossyShininess,
GDepth,
GBufferTextureCount
};
const char * m_GBufferTexNames[GBufferTextureCount] = { "position", "normal", "ambient", "diffuse", "glossyShininess", "depth" };
const GLenum m_GBufferTextureFormat[GBufferTextureCount] = { GL_RGB32F, GL_RGB32F, GL_RGB32F, GL_RGB32F, GL_RGBA32F, GL_DEPTH_COMPONENT32F };
GLuint m_GBufferTextures[GBufferTextureCount];
GLuint m_GBufferFBO; // Framebuffer object
GBufferTextureType m_CurrentlyDisplayed = GDiffuse;
// Scene data in GPU:
GLuint m_SceneVBO = 0;
GLuint m_SceneIBO = 0;
GLuint m_SceneVAO = 0;
// Required data about the scene in CPU in order to send draw calls
struct ShapeInfo
{
uint32_t indexCount; // Number of indices
uint32_t indexOffset; // Offset in GPU index buffer
int materialID = -1;
};
std::vector<ShapeInfo> m_shapes; // For each shape of the scene, its number of indices
float m_SceneSize = 0.f; // Used for camera speed and projection matrix parameters
struct PhongMaterial
{
glm::vec3 Ka = glm::vec3(0); // Ambient multiplier
glm::vec3 Kd = glm::vec3(0); // Diffuse multiplier
glm::vec3 Ks = glm::vec3(0); // Glossy multiplier
float shininess = 1.f; // Glossy exponent
// OpenGL texture ids:
GLuint KaTextureId = 0;
GLuint KdTextureId = 0;
GLuint KsTextureId = 0;
GLuint shininessTextureId = 0;
};
GLuint m_WhiteTexture; // A white 1x1 texture
PhongMaterial m_DefaultMaterial;
std::vector<PhongMaterial> m_SceneMaterials;
GLuint m_textureSampler = 0; // Only one sampler object since we will use the same sampling parameters for all textures
glmlv::GLProgram m_geometryPassProgram;
glmlv::ViewController m_viewController{ m_GLFWHandle.window(), 3.f };
GLint m_uModelViewProjMatrixLocation;
GLint m_uModelViewMatrixLocation;
GLint m_uNormalMatrixLocation;
GLint m_uKaLocation;
GLint m_uKdLocation;
GLint m_uKsLocation;
GLint m_uShininessLocation;
GLint m_uKaSamplerLocation;
GLint m_uKdSamplerLocation;
GLint m_uKsSamplerLocation;
GLint m_uShininessSamplerLocation;
}; | [
"laurent.noel.c2ba@gmail.com"
] | laurent.noel.c2ba@gmail.com |
8ce31ad634106da97327e286964bb4119240b8b7 | 0283771f37d346768c0c2573b449f618562758b3 | /src/boot/x86/.svn/text-base/DebuggerUtilsX86.cpp.svn-base | ec41b6f96d6e0576e165fcc502b0f24f0378e889 | [
"BSD-3-Clause"
] | permissive | andyvand/macosxbootloader | e3bfa88a8f6450d9aaa8140fba6d4fbdd8259e64 | c7fdd8deaccb80f5bcf9c7401adcb27a44539700 | refs/heads/master | 2021-01-21T09:02:52.726888 | 2019-12-08T02:13:29 | 2019-12-08T02:13:29 | 27,282,237 | 17 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 21,771 | //********************************************************************
// created: 6:11:2009 20:18
// filename: DebuggerUtils.cpp
// author: tiamo
// purpose: debugger routine
//********************************************************************
#include "stdafx.h"
#include "BootDebuggerPrivate.h"
KPCR* BdPcr = nullptr;
KPRCB* BdPrcb = nullptr;
UINT64 BdPcrPhysicalAddress = 0;
//
// debug breakpoint
//
VOID __declspec(naked) BOOTAPI DbgBreakPoint()
{
__asm
{
int 3
retn
}
}
//
// debug service
//
VOID __declspec(naked) BOOTAPI DbgService(UINTN serviceType, UINTN info1, UINTN info2, UINTN info3, UINTN info4)
{
__asm
{
push ebp
mov ebp, esp
push ecx
push ebx
push edi
mov eax, [ebp + 0x08]
mov ecx, [ebp + 0x0c]
mov edx, [ebp + 0x10]
mov ebx, [ebp + 0x14]
mov edi, [ebp + 0x18]
int 0x2d
int 3
pop edi
pop ebx
leave
retn
}
}
//
// debug service
//
VOID __declspec(naked) BOOTAPI DbgService(VOID* info1, VOID* info2, UINTN serviceType)
{
__asm
{
push ebp
mov ebp, esp
mov eax, [ebp + 0x10]
mov ecx, [ebp + 0x08]
mov edx, [ebp + 0x0c]
int 0x2d
int 3
leave
retn
}
}
//
// return from exception handler
//
STATIC VOID __declspec(naked) BdpTrapExit()
{
__asm
{
lea esp, [ebp+30h]
pop gs
pop es
pop ds
pop edx
pop ecx
pop eax
add esp, 8 // skip exception list and previous previous mode
pop fs
pop edi
pop esi
pop ebx
pop ebp
add esp, 4 // skip error code
iretd
}
}
//
// common dispatch
//
STATIC VOID __declspec(naked) BdpTrapDispatch()
{
__asm
{
sub esp, size EXCEPTION_RECORD // sizeof(EXCEPTION_RECORD) = 0x50
mov [esp + EXCEPTION_RECORD.ExceptionCode], eax // ExceptionCode
xor eax, eax
mov [esp + EXCEPTION_RECORD.ExceptionFlags], eax // ExceptionFlags
mov [esp + EXCEPTION_RECORD.ExceptionRecord], eax // ExceptionRecord
mov [esp + EXCEPTION_RECORD.ExceptionAddress], ebx // ExceptionAddress
mov [esp + EXCEPTION_RECORD.NumberParameters], ecx // NumberParameters
mov [esp + EXCEPTION_RECORD.ExceptionInformation], edx // ExceptionInformation0
mov [esp + EXCEPTION_RECORD.ExceptionInformation + 4], edi // ExceptionInformation1
mov [esp + EXCEPTION_RECORD.ExceptionInformation + 8], esi // ExceptionInformation2
mov eax, dr0
mov [ebp + KTRAP_FRAME.Dr0], eax // dr0
mov eax, dr1
mov [ebp + KTRAP_FRAME.Dr1], eax // dr1
mov eax, dr2
mov [ebp + KTRAP_FRAME.Dr2], eax // dr2
mov eax, dr3
mov [ebp + KTRAP_FRAME.Dr3], eax // dr3
mov eax, dr6
mov [ebp + KTRAP_FRAME.Dr6], eax // dr6
mov eax, dr7
mov [ebp + KTRAP_FRAME.Dr7], eax // dr7
mov ax, ss
mov [ebp + KTRAP_FRAME.TempSegCs], eax // TempSegCs
mov [ebp + KTRAP_FRAME.TempEsp], ebp // TempEsp
add dword ptr [ebp + KTRAP_FRAME.TempEsp], 0x74 // 0x74 = FIELD_OFFSET(KTRAP_FRAME,HardwareEsp)
mov ecx, esp
push ebp // trap frame
push 0 // kernel mode
push ecx // exception record
call BdDebugTrap
add esp, size EXCEPTION_RECORD + 0x0c
retn
}
}
//
// single step exception
//
VOID __declspec(naked) BdTrap01()
{
__asm
{
push 0 // dummy error code
push ebp
push ebx
push esi
push edi
push fs
push 0ffffffffh // ExceptionList
push 0ffffffffh // PreviousPreviousMode
push eax
push ecx
push edx
push ds
push es
push gs
sub esp, 30h // KTRAP_FRAME.SegGs
mov ebp, esp
cld
and dword ptr [ebp + KTRAP_FRAME.EFlags], 0fffffeffh // clear single step flag
mov eax, 80000004h // EXCEPTION_SINGLE_STEP
mov ebx, [ebp+KTRAP_FRAME.Eip] // exception address = Eip
xor ecx, ecx // param count = 0
call BdpTrapDispatch
jmp BdpTrapExit
}
}
//
// breakpoint exception
//
VOID __declspec(naked) BdTrap03()
{
__asm
{
push 0
push ebp
push ebx
push esi
push edi
push fs
push 0ffffffffh
push 0ffffffffh
push eax
push ecx
push edx
push ds
push es
push gs
sub esp, 30h
mov ebp, esp
cld
dec dword ptr [ebp + KTRAP_FRAME.Eip] // point to breakpoint instruction
mov eax, 80000003h // EXCEPTION_BREAKPOINT
mov ebx, [ebp + KTRAP_FRAME.Eip] // exception address = Eip
mov ecx,0 // param count
xor edx, edx
call BdpTrapDispatch
jmp BdpTrapExit
}
}
//
// general protection
//
VOID __declspec(naked) BdTrap0d()
{
__asm
{
push ebp
push ebx
push esi
push edi
push fs
push 0ffffffffh
push 0ffffffffh
push eax
push ecx
push edx
push ds
push es
push gs
sub esp, 30h
mov ebp, esp
cld
loop_forever:
mov eax, 0c0000005h // EXCEPTION_ACCESS_VIOLATION
mov ebx, [ebp + KTRAP_FRAME.Eip] // exception address = eip
mov ecx, 1 // param count = 1
mov edx, [ebp + KTRAP_FRAME.ErrCode] // hardware error code
and edx, 0ffffh
call BdpTrapDispatch
jmp loop_forever
}
}
//
// page fault
//
VOID __declspec(naked) BdTrap0e()
{
__asm
{
push ebp
push ebx
push esi
push edi
push fs
push 0ffffffffh
push 0ffffffffh
push eax
push ecx
push edx
push ds
push es
push gs
sub esp, 30h
mov ebp, esp
cld
loop_forever:
mov eax, 0c0000005h // EXCEPTION_ACCESS_VIOLATION
mov ebx, [ebp + KTRAP_FRAME.Eip] // exception address = eip
mov ecx, 3 // param count = 3
mov edx, [ebp + KTRAP_FRAME.ErrCode] // hardware error code
and edx, 2 // read or write
mov edi, cr2 // reference memory location
xor esi,esi
call BdpTrapDispatch
jmp loop_forever
}
}
//
// debug service
//
VOID __declspec(naked) BdTrap2d()
{
__asm
{
push 0
push ebp
push ebx
push esi
push edi
push fs
push 0ffffffffh
push 0ffffffffh
push eax
push ecx
push edx
push ds
push es
push gs
sub esp, 30h
mov ebp, esp
cld
mov eax, 80000003h // EXCEPTION_BREAKPOINT
mov ebx, [ebp + KTRAP_FRAME.Eip] // exception address = eip
mov ecx, 3 // param count = 3
xor edx, edx
mov edx, [ebp + KTRAP_FRAME.Eax] // edx = eax = debug service type
mov edi, [ebp + KTRAP_FRAME.Ecx] // edi = ecx = debug service param1
mov esi, [ebp + KTRAP_FRAME.Edx] // esi = edx = debug service param2
call BdpTrapDispatch
jmp BdpTrapExit
}
}
//
// save processor context
//
STATIC VOID __declspec(naked) BOOTAPI BdpSaveProcessorControlState(KPROCESSOR_STATE* processorState)
{
__asm
{
mov edx, [esp + 4]
xor ecx, ecx
mov eax, cr0
mov [edx + KPROCESSOR_STATE.SpecialRegisters.Cr0], eax
mov eax, cr2
mov [edx + KPROCESSOR_STATE.SpecialRegisters.Cr2], eax
mov eax, cr3
mov [edx + KPROCESSOR_STATE.SpecialRegisters.Cr3], eax
mov [edx + KPROCESSOR_STATE.SpecialRegisters.Cr4], ecx
mov eax, dr0
mov [edx + KPROCESSOR_STATE.SpecialRegisters.KernelDr0], eax
mov eax, dr1
mov [edx + KPROCESSOR_STATE.SpecialRegisters.KernelDr1], eax
mov eax, dr2
mov [edx + KPROCESSOR_STATE.SpecialRegisters.KernelDr2], eax
mov eax, dr3
mov [edx + KPROCESSOR_STATE.SpecialRegisters.KernelDr3], eax
mov eax, dr6
mov [edx + KPROCESSOR_STATE.SpecialRegisters.KernelDr6], eax
mov eax, dr7
mov dr7, ecx
mov [edx + KPROCESSOR_STATE.SpecialRegisters.KernelDr7], eax
sgdt fword ptr [edx + KPROCESSOR_STATE.SpecialRegisters.Gdtr.Limit]
sidt fword ptr [edx + KPROCESSOR_STATE.SpecialRegisters.Idtr.Limit]
str word ptr [edx + KPROCESSOR_STATE.SpecialRegisters.Tr]
sldt word ptr [edx + KPROCESSOR_STATE.SpecialRegisters.Ldtr]
retn
}
}
//
// save trapframe
//
STATIC VOID BdpSaveKframe(KTRAP_FRAME* trapFrame, CONTEXT* contextRecord)
{
contextRecord->Ebp = trapFrame->Ebp;
contextRecord->Eip = trapFrame->Eip;
contextRecord->SegCs = trapFrame->SegCs;
contextRecord->EFlags = trapFrame->EFlags;
contextRecord->Esp = trapFrame->TempEsp;
contextRecord->SegSs = trapFrame->TempSegCs;
contextRecord->SegDs = trapFrame->SegDs;
contextRecord->SegEs = trapFrame->SegEs;
contextRecord->SegFs = trapFrame->SegFs;
contextRecord->SegGs = trapFrame->SegGs;
contextRecord->Eax = trapFrame->Eax;
contextRecord->Ebx = trapFrame->Ebx;
contextRecord->Ecx = trapFrame->Ecx;
contextRecord->Edx = trapFrame->Edx;
contextRecord->Edi = trapFrame->Edi;
contextRecord->Esi = trapFrame->Esi;
contextRecord->Dr0 = trapFrame->Dr0;
contextRecord->Dr1 = trapFrame->Dr1;
contextRecord->Dr2 = trapFrame->Dr2;
contextRecord->Dr3 = trapFrame->Dr3;
contextRecord->Dr6 = trapFrame->Dr6;
contextRecord->Dr7 = trapFrame->Dr7;
BdpSaveProcessorControlState(&BdPrcb->ProcessorState);
}
//
// restore processor context
//
STATIC VOID __declspec(naked) BOOTAPI BdpRestoreProcessorControlState(KPROCESSOR_STATE* processorState)
{
__asm
{
mov edx, [esp + 4]
mov eax, [edx + KPROCESSOR_STATE.SpecialRegisters.Cr0]
mov cr0, eax
mov eax, [edx + KPROCESSOR_STATE.SpecialRegisters.Cr2]
mov cr2, eax
mov eax, [edx + KPROCESSOR_STATE.SpecialRegisters.Cr3]
mov cr3, eax
mov eax, [edx + KPROCESSOR_STATE.SpecialRegisters.KernelDr0]
mov dr0, eax
mov eax, [edx + KPROCESSOR_STATE.SpecialRegisters.KernelDr1]
mov dr1, eax
mov eax, [edx + KPROCESSOR_STATE.SpecialRegisters.KernelDr2]
mov dr2, eax
mov eax, [edx + KPROCESSOR_STATE.SpecialRegisters.KernelDr3]
mov dr3, eax
mov eax, [edx + KPROCESSOR_STATE.SpecialRegisters.KernelDr6]
mov dr6, eax
mov eax, [edx + KPROCESSOR_STATE.SpecialRegisters.KernelDr7]
mov dr7, eax
lgdt fword ptr [edx + KPROCESSOR_STATE.SpecialRegisters.Gdtr.Limit]
lidt fword ptr [edx + KPROCESSOR_STATE.SpecialRegisters.Idtr.Limit]
lldt word ptr [edx + KPROCESSOR_STATE.SpecialRegisters.Ldtr]
retn
}
}
//
// restore trap frame
//
STATIC VOID BdpRestoreKframe(KTRAP_FRAME* trapFrame, CONTEXT* contextRecord)
{
trapFrame->Ebp = contextRecord->Ebp;
trapFrame->Eip = contextRecord->Eip;
trapFrame->SegCs = contextRecord->SegCs;
trapFrame->EFlags = contextRecord->EFlags;
trapFrame->SegDs = contextRecord->SegDs;
trapFrame->SegEs = contextRecord->SegEs;
trapFrame->SegFs = contextRecord->SegFs;
trapFrame->SegGs = contextRecord->SegGs;
trapFrame->Edi = contextRecord->Edi;
trapFrame->Esi = contextRecord->Esi;
trapFrame->Eax = contextRecord->Eax;
trapFrame->Ebx = contextRecord->Ebx;
trapFrame->Ecx = contextRecord->Ecx;
trapFrame->Edx = contextRecord->Edx;
BdpRestoreProcessorControlState(&BdPrcb->ProcessorState);
}
#pragma optimize("",off)
//
// debug routine used when debugger is enabled
//
BOOLEAN BdTrap(EXCEPTION_RECORD* exceptionRecord, struct _KEXCEPTION_FRAME* exceptionFrame, KTRAP_FRAME* trapFrame)
{
BdPrcb->ProcessorState.ContextFrame.ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
if(exceptionRecord->ExceptionCode != STATUS_BREAKPOINT || exceptionRecord->ExceptionInformation[0] == BREAKPOINT_BREAK)
{
BdpSaveKframe(trapFrame, &BdPrcb->ProcessorState.ContextFrame);
BdReportExceptionStateChange(exceptionRecord, &BdPrcb->ProcessorState.ContextFrame);
BdpRestoreKframe(trapFrame, &BdPrcb->ProcessorState.ContextFrame);
BdControlCPressed = FALSE;
return TRUE;
}
UINT32 debugServiceType = exceptionRecord->ExceptionInformation[0];
switch(debugServiceType)
{
case BREAKPOINT_PRINT:
{
STRING printString;
printString.Length = static_cast<UINT16>(exceptionRecord->ExceptionInformation[2]);
printString.Buffer = ArchConvertAddressToPointer(exceptionRecord->ExceptionInformation[1], CHAR8*);
if(BdDebuggerNotPresent)
trapFrame->Eax = static_cast<UINT32>(STATUS_DEVICE_NOT_CONNECTED);
else
trapFrame->Eax = BdPrintString(&printString) ? STATUS_BREAKPOINT : STATUS_SUCCESS;
trapFrame->Eip += sizeof(KDP_BREAKPOINT_TYPE);
}
break;
case BREAKPOINT_PROMPT:
{
STRING inputString;
inputString.Length = static_cast<UINT16>(exceptionRecord->ExceptionInformation[2]);
inputString.Buffer = ArchConvertAddressToPointer(exceptionRecord->ExceptionInformation[1], CHAR8*);
STRING outputString;
outputString.MaximumLength = static_cast<UINT16>(trapFrame->Edi);
outputString.Buffer = ArchConvertAddressToPointer(trapFrame->Ebx, CHAR8*);
while(BdPromptString(&inputString, &outputString)) {}
trapFrame->Eax = outputString.Length;
trapFrame->Eip += sizeof(KDP_BREAKPOINT_TYPE);
}
break;
case BREAKPOINT_LOAD_SYMBOLS:
case BREAKPOINT_UNLOAD_SYMBOLS:
{
BdpSaveKframe(trapFrame, &BdPrcb->ProcessorState.ContextFrame);
UINT32 savedContextEip = BdPrcb->ProcessorState.ContextFrame.Eip;
if(!BdDebuggerNotPresent)
{
STRING* moduleName = ArchConvertAddressToPointer(exceptionRecord->ExceptionInformation[1], STRING*);
KD_SYMBOLS_INFO* symbolsInfo = ArchConvertAddressToPointer(exceptionRecord->ExceptionInformation[2], KD_SYMBOLS_INFO*);
BOOLEAN unloadSymbols = debugServiceType == BREAKPOINT_UNLOAD_SYMBOLS;
BdReportLoadSymbolsStateChange(moduleName, symbolsInfo, unloadSymbols, &BdPrcb->ProcessorState.ContextFrame);
}
if(savedContextEip == BdPrcb->ProcessorState.ContextFrame.Eip)
BdPrcb->ProcessorState.ContextFrame.Eip += sizeof(KDP_BREAKPOINT_TYPE);
BdpRestoreKframe(trapFrame, &BdPrcb->ProcessorState.ContextFrame);
}
break;
default:
return FALSE;
break;
}
return TRUE;
}
#pragma optimize("",on)
//
// extract continuation control data from Manipulate_State message
//
VOID BdGetStateChange(DBGKD_MANIPULATE_STATE64* manipulateState, CONTEXT* contextRecord)
{
if(!NT_SUCCESS(manipulateState->Continue2.ContinueStatus))
return;
//
// the debugger is doing a continue, and it makes sense to apply control changes.
//
if(manipulateState->Continue2.ControlSet.TraceFlag == 1)
contextRecord->EFlags |= 0x100;
else
contextRecord->EFlags &= ~0x100;
BdPrcb->ProcessorState.SpecialRegisters.KernelDr7 = manipulateState->Continue2.ControlSet.Dr7;
BdPrcb->ProcessorState.SpecialRegisters.KernelDr6 = 0;
}
//
// set context state
//
VOID BdSetContextState(DBGKD_WAIT_STATE_CHANGE64* waitStateChange, CONTEXT* contextRecord)
{
waitStateChange->ControlReport.Dr6 = BdPrcb->ProcessorState.SpecialRegisters.KernelDr6;
waitStateChange->ControlReport.Dr7 = BdPrcb->ProcessorState.SpecialRegisters.KernelDr7;
waitStateChange->ControlReport.EFlags = contextRecord->EFlags;
waitStateChange->ControlReport.SegCs = static_cast<UINT16>(contextRecord->SegCs);
waitStateChange->ControlReport.SegDs = static_cast<UINT16>(contextRecord->SegDs);
waitStateChange->ControlReport.SegEs = static_cast<UINT16>(contextRecord->SegEs);
waitStateChange->ControlReport.SegFs = static_cast<UINT16>(contextRecord->SegFs);
waitStateChange->ControlReport.ReportFlags = REPORT_INCLUDES_SEGS;
}
//
// read control space
//
VOID BdReadControlSpace(DBGKD_MANIPULATE_STATE64* manipulateState, STRING* additionalData, CONTEXT* contextRecord)
{
STRING messageHeader;
DBGKD_READ_MEMORY64* readMemory = &manipulateState->ReadMemory;
messageHeader.Length = sizeof(DBGKD_MANIPULATE_STATE64);
messageHeader.Buffer = static_cast<CHAR8*>(static_cast<VOID*>(manipulateState));
UINT32 readLength = readMemory->TransferCount;
if(readMemory->TransferCount > PACKET_MAX_SIZE - sizeof(DBGKD_MANIPULATE_STATE64))
readLength = PACKET_MAX_SIZE - sizeof(DBGKD_MANIPULATE_STATE64);
if(static_cast<UINT32>(readMemory->TargetBaseAddress) + readLength <= sizeof(KPROCESSOR_STATE))
{
VOID* readAddress = Add2Ptr(&BdPrcb->ProcessorState.ContextFrame.ContextFlags, static_cast<UINT32>(readMemory->TargetBaseAddress), VOID*);
readLength = BdMoveMemory(additionalData->Buffer, readAddress, readLength);
additionalData->Length = static_cast<UINT16>(readLength);
manipulateState->ReturnStatus = STATUS_SUCCESS;
readMemory->ActualBytesRead = readLength;
}
else
{
additionalData->Length = 0;
manipulateState->ReturnStatus = STATUS_UNSUCCESSFUL;
readMemory->ActualBytesRead = 0;
}
BdSendPacket(PACKET_TYPE_KD_STATE_MANIPULATE, &messageHeader, additionalData);
}
//
// write control space
//
VOID BdWriteControlSpace(DBGKD_MANIPULATE_STATE64* manipulateState, STRING* additionalData, CONTEXT* contextRecord)
{
STRING messageHeader;
DBGKD_WRITE_MEMORY64* writeMemory = &manipulateState->WriteMemory;
UINT32 writeLength = writeMemory->TransferCount;
messageHeader.Length = sizeof(DBGKD_MANIPULATE_STATE64);
messageHeader.Buffer = static_cast<CHAR8*>(static_cast<VOID*>(manipulateState));
if(writeLength >= additionalData->Length)
writeLength = additionalData->Length;
if(static_cast<UINT32>(writeMemory->TargetBaseAddress) + writeLength <= sizeof(KPROCESSOR_STATE))
{
VOID* writeAddress = Add2Ptr(&BdPrcb->ProcessorState.ContextFrame.ContextFlags, static_cast<UINT32>(writeMemory->TargetBaseAddress), VOID*);
writeLength = BdMoveMemory(writeAddress, additionalData->Buffer, writeLength);
manipulateState->ReturnStatus = STATUS_SUCCESS;
writeMemory->ActualBytesWritten = writeLength;
}
else
{
manipulateState->ReturnStatus = STATUS_UNSUCCESSFUL;
writeMemory->ActualBytesWritten = 0;
}
BdSendPacket(PACKET_TYPE_KD_STATE_MANIPULATE, &messageHeader, nullptr);
}
//
// set common state
//
VOID BdSetCommonState(UINT32 newState, CONTEXT* contextRecord, DBGKD_WAIT_STATE_CHANGE64* waitStateChange)
{
//
// sign extend
//
waitStateChange->ProgramCounter = static_cast<UINT64>(static_cast<INT32>(contextRecord->Eip));
waitStateChange->NewState = newState;
waitStateChange->NumberProcessors = 1;
waitStateChange->Thread = 0;
waitStateChange->Processor = 0;
waitStateChange->ProcessorLevel = 0;
memset(&waitStateChange->ControlReport, 0, sizeof(waitStateChange->ControlReport));
//
// copy instructions
//
VOID* dstBuffer = waitStateChange->ControlReport.InstructionStream;
VOID* srcBuffer = ArchConvertAddressToPointer(contextRecord->Eip, VOID*);
waitStateChange->ControlReport.InstructionCount = static_cast<UINT16>(BdMoveMemory(dstBuffer, srcBuffer, DBGKD_MAXSTREAM));
//
// delete breakpoint in this range
// there were any breakpoints cleared, recopy the area without them
//
if(BdDeleteBreakpointRange(contextRecord->Eip, waitStateChange->ControlReport.InstructionCount + contextRecord->Eip - 1))
BdMoveMemory(waitStateChange->ControlReport.InstructionStream, ArchConvertAddressToPointer(contextRecord->Eip, VOID*), waitStateChange->ControlReport.InstructionCount);
}
//
// transfer physical address
//
VOID* BdTranslatePhysicalAddress(UINT64 phyAddress)
{
return ArchConvertAddressToPointer(phyAddress, VOID*);
}
//
// initialize arch
//
EFI_STATUS BdArchInitialize()
{
BdPcrPhysicalAddress = 4 * 1024 * 1024 * 1024ULL - 1;
BdPcr = static_cast<KPCR*>(MmAllocatePages(AllocateMaxAddress, EfiBootServicesData, EFI_SIZE_TO_PAGES(sizeof(KPCR)), &BdPcrPhysicalAddress));
if(!BdPcr)
{
BdPcrPhysicalAddress = 0;
return EFI_OUT_OF_RESOURCES;
}
BdPrcb = &BdPcr->PrcbData;
KDESCRIPTOR idtr;
ArchGetIdtRegister(&idtr);
UINT32 segCs = ArchGetSegCs();
ArchSetIdtEntry(idtr.Base, 0x01, segCs, &BdTrap01, 0x8e00);
ArchSetIdtEntry(idtr.Base, 0x03, segCs, &BdTrap03, 0x8e00);
ArchSetIdtEntry(idtr.Base, 0x0d, segCs, &BdTrap0d, 0x8e00);
ArchSetIdtEntry(idtr.Base, 0x0e, segCs, &BdTrap0e, 0x8e00);
ArchSetIdtEntry(idtr.Base, 0x2d, segCs, &BdTrap2d, 0x8e00);
ArchSetIdtRegister(&idtr);
BdArchBlockDebuggerOperation = FALSE;
return EFI_SUCCESS;
}
//
// destroy arch
//
EFI_STATUS BdArchDestroy()
{
if(BdPcrPhysicalAddress)
MmFreePages(BdPcrPhysicalAddress);
BdPcrPhysicalAddress = 0;
BdArchBlockDebuggerOperation = TRUE;
return EFI_SUCCESS;
} | [
"PikerAlpha@yahoo.com"
] | PikerAlpha@yahoo.com | |
cc7cae1d32f6a15fe07bdb6510fe77d86987e669 | 720c9ba19ce0b3404e1d7fd10011d2e58507efdd | /Assignments/Project 1/Week 5/HomeworkEveryone/mainwindow.cpp | f91ff9e3b9b86bd3e6c8c5d3a03d1d051b232f59 | [
"MIT"
] | permissive | reederward1285/Computer_Graphics_SoSe_2021 | df692173226973d95e2fee21842ac6bb91bc561a | dbfada7a27ad935ce06265ed2d12e3c2f787dc5f | refs/heads/main | 2023-06-17T12:05:47.289263 | 2021-07-16T11:47:47 | 2021-07-16T11:47:47 | 358,215,163 | 1 | 1 | MIT | 2021-05-10T15:15:03 | 2021-04-15T10:15:52 | Makefile | UTF-8 | C++ | false | false | 449 | cpp | /**
* @file mainwindow.cpp
*
* @author Majbrit Schoettner
* Contact: mshoettner@stud.hs-bremen.de
* @author Reeder Ward
* Contact: rward@stud.hs-bremen.de
* @author David Melamed
* Contact: dmelamed@stud.hs-bremen.de
*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
| [
"reederward2@gmail.com"
] | reederward2@gmail.com |
85840d295ca6e96d62c24e1cc7f638e44a11b3bf | ec238b46f55c73f8be22315d45df590ae252dc79 | /Amethyst/Source/Editor/ImGui/Implementation/imgui_impl_sdl.h | 44ae808c6f8f142ac3ee730816576eb12dfdeb1b | [] | no_license | xRiveria/Amethyst | 9c2ca3b8b142d1cb8e826cf216ea1c3c86888401 | ac9acb726e9d4361b5cf4e2976448fd8d98bf7f6 | refs/heads/master | 2023-06-03T10:29:25.689304 | 2021-06-13T15:15:17 | 2021-06-13T15:15:17 | 339,117,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,833 | h | // dear imgui: Platform Backend for SDL2
// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
// (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.)
// Implemented features:
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
// [X] Platform: Clipboard support.
// [X] Platform: Keyboard arrays indexed using SDL_SCANCODE_* codes, e.g. ImGui::IsKeyPressed(SDL_SCANCODE_SPACE).
// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// [X] Platform: Multi-viewport support (multiple windows). Enable with 'io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable'.
// Missing features:
// [ ] Platform: SDL2 handling of IME under Windows appears to be broken and it explicitly disable the regular Windows IME. You can restore Windows IME by compiling SDL with SDL_DISABLE_WINDOWS_IME.
// [ ] Platform: Multi-viewport + Minimized windows seems to break mouse wheel events (at least under Windows).
// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
#pragma once
#include "../Source/imgui.h" // IMGUI_IMPL_API
struct SDL_Window;
typedef union SDL_Event SDL_Event;
namespace Amethyst { class Context; }
IMGUI_IMPL_API bool ImGui_ImplSDL2_Init(SDL_Window* window);
IMGUI_IMPL_API void ImGui_ImplSDL2_Shutdown();
IMGUI_IMPL_API void ImGui_ImplSDL2_NewFrame(Amethyst::Context* context);
IMGUI_IMPL_API bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event);
| [
"ryan-wende@outlook.com"
] | ryan-wende@outlook.com |
3603039acdc102084bfc943aa51fc400625be7b5 | 3c5c1e3836edf3e9627a64600785503d1814df51 | /build/Android/Debug/app/src/main/include/Uno.Graphics.VideoTexture.h | da5ccb7c154ab368920115a4cc2493050c2e23c6 | [] | no_license | fypwyt/wytcarpool | 70a0c9ca12d0f2981187f2ea21a8a02ee4cbcbd4 | 4fbdeedf261ee8ecd563260816991741ec701432 | refs/heads/master | 2021-09-08T10:32:17.612628 | 2018-03-09T05:24:54 | 2018-03-09T05:24:54 | 124,490,692 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,459 | h | // This file was generated based on C:/Users/Brian/AppData/Local/Fusetools/Packages/UnoCore/1.6.0/Source/Uno/Graphics/VideoTexture.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.IDisposable.h>
#include <Uno.Object.h>
namespace g{namespace Uno{namespace Graphics{struct VideoTexture;}}}
namespace g{
namespace Uno{
namespace Graphics{
// public intrinsic sealed class VideoTexture :9
// {
struct VideoTexture_type : uType
{
::g::Uno::IDisposable interface0;
};
VideoTexture_type* VideoTexture_typeof();
void VideoTexture__ctor__fn(VideoTexture* __this, uint32_t* handle);
void VideoTexture__Dispose_fn(VideoTexture* __this);
void VideoTexture__get_GLTextureHandle_fn(VideoTexture* __this, uint32_t* __retval);
void VideoTexture__set_GLTextureHandle_fn(VideoTexture* __this, uint32_t* value);
void VideoTexture__get_IsDisposed_fn(VideoTexture* __this, bool* __retval);
void VideoTexture__set_IsDisposed_fn(VideoTexture* __this, bool* value);
void VideoTexture__New1_fn(uint32_t* handle, VideoTexture** __retval);
struct VideoTexture : uObject
{
bool IsMipmap;
bool IsPow2;
uint32_t _GLTextureHandle;
bool _IsDisposed;
void ctor_(uint32_t handle);
void Dispose();
uint32_t GLTextureHandle();
void GLTextureHandle(uint32_t value);
bool IsDisposed();
void IsDisposed(bool value);
static VideoTexture* New1(uint32_t handle);
};
// }
}}} // ::g::Uno::Graphics
| [
"s1141120@studentdmn.ouhk.edu.hk"
] | s1141120@studentdmn.ouhk.edu.hk |
cc8d017be2e1b02160934ce911d73a5b96fd32a2 | 332297e5b7277ad48ec867933bd2c88bf49e8ff4 | /chrome/browser/previews/previews_lite_page_decider.cc | 3e720daaa2fe2af8269360edb4a506804e641788 | [
"BSD-3-Clause"
] | permissive | chorman0773/chromium | 3b4147a24e41dab4abe82cde84b9a6f52dd7ee67 | ba837a33fd29823d60e8119daf0d5b8113384ca6 | refs/heads/master | 2022-11-29T21:39:15.228897 | 2018-11-13T15:42:24 | 2018-11-13T15:42:24 | 157,396,636 | 1 | 0 | NOASSERTION | 2018-11-13T15:42:25 | 2018-11-13T14:52:16 | null | UTF-8 | C++ | false | false | 13,508 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/previews/previews_lite_page_decider.h"
#include <vector>
#include "base/callback.h"
#include "base/memory/ptr_util.h"
#include "base/rand_util.h"
#include "base/time/default_tick_clock.h"
#include "build/build_config.h"
#include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h"
#include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h"
#include "chrome/browser/previews/previews_lite_page_infobar_delegate.h"
#include "chrome/browser/previews/previews_lite_page_navigation_throttle.h"
#include "chrome/browser/previews/previews_service.h"
#include "chrome/browser/previews/previews_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_metrics.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_service.h"
#include "components/data_reduction_proxy/core/common/data_reduction_proxy_params.h"
#include "components/data_use_measurement/core/data_use_user_data.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/prefs/pref_service.h"
#include "components/previews/core/previews_experiments.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/navigation_throttle.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_user_data.h"
#include "net/base/net_errors.h"
namespace {
const char kUserNeedsNotification[] =
"previews.litepage.user-needs-notification";
const char kHostBlacklist[] = "previews.litepage.host-blacklist";
const size_t kMaxBlacklistEntries = 30;
// Cleans up the given host blacklist by removing all stale (expiry has passed)
// entries. If after removing all stale entries, the blacklist is still over
// capacity, then remove the entry with the closest expiration.
void RemoveStaleEntries(base::DictionaryValue* dict) {
std::vector<std::string> keys_to_delete;
base::Time min_value = base::Time::Max();
std::string min_key;
for (const auto& iter : dict->DictItems()) {
base::Time value = base::Time::FromDoubleT(iter.second.GetDouble());
// Delete all stale entries.
if (value <= base::Time::Now()) {
keys_to_delete.push_back(iter.first);
continue;
}
// Record the closest expiration in case we need it later on.
if (value < min_value) {
min_value = value;
min_key = iter.first;
}
}
// Remove all expired entries.
for (const std::string& key : keys_to_delete)
dict->RemoveKey(key);
// Remove the closest expiration if needed.
if (dict->DictSize() > kMaxBlacklistEntries)
dict->RemoveKey(min_key);
DCHECK_GE(kMaxBlacklistEntries, dict->DictSize());
}
} // namespace
// This WebContentsObserver watches the rest of the current navigation shows a
// notification to the user that this preview now exists and will be used on
// future eligible page loads. This is only done if the navigations finishes on
// the same URL as the one when it began. After finishing the navigation, |this|
// will be removed as an observer.
class UserNotificationWebContentsObserver
: public content::WebContentsObserver,
public content::WebContentsUserData<UserNotificationWebContentsObserver> {
public:
void SetUIShownCallback(base::OnceClosure callback) {
ui_shown_callback_ = std::move(callback);
}
private:
friend class content::WebContentsUserData<
UserNotificationWebContentsObserver>;
explicit UserNotificationWebContentsObserver(
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents) {}
void DestroySelf() {
content::WebContents* old_web_contents = web_contents();
Observe(nullptr);
old_web_contents->RemoveUserData(UserDataKey());
// DO NOT add code past this point. |this| is destroyed.
}
void DidRedirectNavigation(
content::NavigationHandle* navigation_handle) override {
DestroySelf();
// DO NOT add code past this point. |this| is destroyed.
}
void DidFinishNavigation(content::NavigationHandle* handle) override {
if (ui_shown_callback_ && handle->GetNetErrorCode() == net::OK) {
PreviewsLitePageInfoBarDelegate::Create(web_contents());
std::move(ui_shown_callback_).Run();
}
DestroySelf();
// DO NOT add code past this point. |this| is destroyed.
}
base::OnceClosure ui_shown_callback_;
};
PreviewsLitePageDecider::PreviewsLitePageDecider(
content::BrowserContext* browser_context)
: clock_(base::DefaultTickClock::GetInstance()),
page_id_(base::RandUint64()),
drp_settings_(nullptr),
pref_service_(nullptr),
host_blacklist_(std::make_unique<base::DictionaryValue>()) {
if (!browser_context)
return;
DataReductionProxyChromeSettings* drp_settings =
DataReductionProxyChromeSettingsFactory::GetForBrowserContext(
browser_context);
if (!drp_settings)
return;
DCHECK(!browser_context->IsOffTheRecord());
Profile* profile = Profile::FromBrowserContext(browser_context);
pref_service_ = profile->GetPrefs();
DCHECK(pref_service_);
host_blacklist_ =
pref_service_->GetDictionary(kHostBlacklist)->CreateDeepCopy();
// Add |this| as an observer to DRP, but if DRP is already initialized, check
// the prefs now.
drp_settings_ = drp_settings;
drp_settings_->AddDataReductionProxySettingsObserver(this);
if (drp_settings_->Config()) {
OnSettingsInitialized();
OnProxyRequestHeadersChanged(drp_settings->GetProxyRequestHeaders());
}
}
PreviewsLitePageDecider::~PreviewsLitePageDecider() = default;
// static
void PreviewsLitePageDecider::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
registry->RegisterBooleanPref(kUserNeedsNotification, true);
registry->RegisterDictionaryPref(kHostBlacklist,
std::make_unique<base::DictionaryValue>());
}
// static
std::unique_ptr<content::NavigationThrottle>
PreviewsLitePageDecider::MaybeCreateThrottleFor(
content::NavigationHandle* handle) {
DCHECK(handle);
DCHECK(handle->GetWebContents());
DCHECK(handle->GetWebContents()->GetBrowserContext());
content::BrowserContext* browser_context =
handle->GetWebContents()->GetBrowserContext();
PreviewsService* previews_service = PreviewsServiceFactory::GetForProfile(
Profile::FromBrowserContext(browser_context));
if (!previews_service)
return nullptr;
DCHECK(!browser_context->IsOffTheRecord());
PreviewsLitePageDecider* decider =
previews_service->previews_lite_page_decider();
DCHECK(decider);
// TODO(crbug/898557): Replace this logic with PreviewsState.
bool drp_enabled = decider->drp_settings_->IsDataReductionProxyEnabled();
bool preview_enabled = previews::params::ArePreviewsAllowed() &&
previews::params::IsLitePageServerPreviewsEnabled();
if (drp_enabled && preview_enabled) {
return std::make_unique<PreviewsLitePageNavigationThrottle>(handle,
decider);
}
return nullptr;
}
void PreviewsLitePageDecider::OnProxyRequestHeadersChanged(
const net::HttpRequestHeaders& headers) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// This is done so that successive page ids cannot be used to track users
// across sessions. These sessions are contained in the chrome-proxy header.
page_id_ = base::RandUint64();
}
void PreviewsLitePageDecider::OnSettingsInitialized() {
// The notification only needs to be shown if the user has never seen it
// before, and is an existing Data Saver user.
if (!pref_service_->GetBoolean(kUserNeedsNotification)) {
need_to_show_notification_ = false;
} else if (drp_settings_->IsDataReductionProxyEnabled()) {
need_to_show_notification_ = true;
} else {
need_to_show_notification_ = false;
pref_service_->SetBoolean(kUserNeedsNotification, false);
}
}
void PreviewsLitePageDecider::Shutdown() {
if (drp_settings_)
drp_settings_->RemoveDataReductionProxySettingsObserver(this);
}
void PreviewsLitePageDecider::SetClockForTesting(const base::TickClock* clock) {
clock_ = clock;
}
void PreviewsLitePageDecider::SetDRPSettingsForTesting(
data_reduction_proxy::DataReductionProxySettings* drp_settings) {
drp_settings_ = drp_settings;
drp_settings_->AddDataReductionProxySettingsObserver(this);
}
void PreviewsLitePageDecider::ClearBlacklist() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
host_blacklist_->Clear();
if (pref_service_)
pref_service_->Set(kHostBlacklist, *host_blacklist_);
}
void PreviewsLitePageDecider::ClearStateForTesting() {
single_bypass_.clear();
host_blacklist_->Clear();
}
void PreviewsLitePageDecider::SetUserHasSeenUINotification() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(pref_service_);
need_to_show_notification_ = false;
pref_service_->SetBoolean(kUserNeedsNotification, false);
}
void PreviewsLitePageDecider::SetServerUnavailableFor(
base::TimeDelta retry_after) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
base::TimeTicks retry_at = clock_->NowTicks() + retry_after;
if (!retry_at_.has_value() || retry_at > retry_at_)
retry_at_ = retry_at;
}
bool PreviewsLitePageDecider::IsServerUnavailable() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!retry_at_.has_value())
return false;
bool server_loadshedding = retry_at_ > clock_->NowTicks();
if (!server_loadshedding)
retry_at_.reset();
return server_loadshedding;
}
void PreviewsLitePageDecider::AddSingleBypass(std::string url) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Garbage collect any old entries while looking for the one for |url|.
auto entry = single_bypass_.end();
for (auto iter = single_bypass_.begin(); iter != single_bypass_.end();
/* no increment */) {
if (iter->second < clock_->NowTicks()) {
iter = single_bypass_.erase(iter);
continue;
}
if (iter->first == url)
entry = iter;
++iter;
}
// Update the entry for |url|.
const base::TimeTicks ttl =
clock_->NowTicks() + base::TimeDelta::FromMinutes(5);
if (entry == single_bypass_.end()) {
single_bypass_.emplace(url, ttl);
return;
}
entry->second = ttl;
}
bool PreviewsLitePageDecider::CheckSingleBypass(std::string url) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
auto entry = single_bypass_.find(url);
if (entry == single_bypass_.end())
return false;
return entry->second >= clock_->NowTicks();
}
uint64_t PreviewsLitePageDecider::GeneratePageID() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return ++page_id_;
}
void PreviewsLitePageDecider::ReportDataSavings(int64_t network_bytes,
int64_t original_bytes,
const std::string& host) {
if (!drp_settings_ || !drp_settings_->data_reduction_proxy_service())
return;
drp_settings_->data_reduction_proxy_service()->UpdateDataUseForHost(
network_bytes, original_bytes, host);
drp_settings_->data_reduction_proxy_service()->UpdateContentLengths(
network_bytes, original_bytes, true /* data_reduction_proxy_enabled */,
data_reduction_proxy::DataReductionProxyRequestType::
VIA_DATA_REDUCTION_PROXY,
"text/html", true /* is_user_traffic */,
data_use_measurement::DataUseUserData::DataUseContentType::
MAIN_FRAME_HTML,
0);
}
bool PreviewsLitePageDecider::NeedsToNotifyUser() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return need_to_show_notification_;
}
void PreviewsLitePageDecider::NotifyUser(content::WebContents* web_contents) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(need_to_show_notification_);
DCHECK(!UserNotificationWebContentsObserver::FromWebContents(web_contents));
UserNotificationWebContentsObserver::CreateForWebContents(web_contents);
UserNotificationWebContentsObserver* observer =
UserNotificationWebContentsObserver::FromWebContents(web_contents);
// base::Unretained is safe here because |this| outlives |web_contents|.
observer->SetUIShownCallback(
base::BindOnce(&PreviewsLitePageDecider::SetUserHasSeenUINotification,
base::Unretained(this)));
}
void PreviewsLitePageDecider::BlacklistHost(const std::string& host,
base::TimeDelta duration) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// If there is an existing entry, intentionally update it.
host_blacklist_->SetKey(
host, base::Value((base::Time::Now() + duration).ToDoubleT()));
RemoveStaleEntries(host_blacklist_.get());
if (pref_service_)
pref_service_->Set(kHostBlacklist, *host_blacklist_);
}
bool PreviewsLitePageDecider::HostBlacklisted(const std::string& host) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
base::Value* value = host_blacklist_->FindKey(host);
if (!value)
return false;
DCHECK(value->is_double());
base::Time expiry = base::Time::FromDoubleT(value->GetDouble());
return expiry > base::Time::Now();
}
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
0d59ff22f41710e02363e4e0d15f89f0dea62685 | 12ac0673d43abcc55c9b7d7a81d0f47848386a6f | /src/OI.cpp | 278164e386a7fdbf610a22e1a764250287530567 | [] | no_license | plahera/RobotTestNew | c7e425584626a18aaf8240c429fef2fef06109d9 | d2ed375aca7ed8f57c08f9fce88137e9e17bfebb | refs/heads/master | 2021-01-10T06:21:28.745492 | 2016-03-04T01:48:27 | 2016-03-04T01:48:27 | 52,684,882 | 0 | 1 | null | 2016-03-04T01:48:28 | 2016-02-27T19:32:55 | C++ | UTF-8 | C++ | false | false | 3,803 | cpp | // RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// C++ from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
#include "OI.h"
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=INCLUDES
#include "SmartDashboard/SmartDashboard.h"
#include "Commands/AutonomousCommand.h"
#include "Commands/DriveNormal.h"
#include "Commands/DriveStraight.h"
#include "Commands/Intake.h"
#include "Commands/Shoot.h"
#include "Commands/moveServos.h"
#include "Commands/moveArm.h"
#include "Commands/WinchUp.h"
#include "Commands/LiftGripper.h"
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=INCLUDES
OI::OI() {
// Process operator interface input here.
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
driveJoy.reset(new Joystick(0));
otherJoy.reset(new Joystick(1));
moveArmButton.reset(new JoystickButton(otherJoy.get(), 1));
moveArmButton->WhileHeld(new moveArm());
liftGripperButton.reset(new JoystickButton(otherJoy.get(), 3));
liftGripperButton->WhileHeld(new LiftGripper());
winchUpButton.reset(new JoystickButton(otherJoy.get(), 2));
winchUpButton->WhileHeld(new WinchUp());
moveServoButton.reset(new JoystickButton(driveJoy.get(), 3));
moveServoButton->WhileHeld(new moveServos());
shootButton.reset(new JoystickButton(driveJoy.get(), 5));
shootButton->WhileHeld(new Shoot());
intakeButton.reset(new JoystickButton(driveJoy.get(), 6));
intakeButton->WhileHeld(new Intake());
//changed intake button to override and use the same button as the other thing, if it doesn't work again check that out because that was the issue sometimes
driveStraightButton.reset(new JoystickButton(driveJoy.get(), 2));
driveStraightButton->WhileHeld(new DriveStraight());
driveNormalButton.reset(new JoystickButton(driveJoy.get(), 1));
driveNormalButton->WhileHeld(new DriveNormal());
// SmartDashboard Buttons
SmartDashboard::PutData("moveArm", new moveArm());
SmartDashboard::PutData("WinchUp", new WinchUp());
SmartDashboard::PutData("LiftGripper", new LiftGripper());
SmartDashboard::PutData("AutonomousCommand", new AutonomousCommand());
SmartDashboard::PutData("Shoot", new Shoot());
SmartDashboard::PutData("Intake", new Intake());
SmartDashboard::PutData("DriveStraight", new DriveStraight());
SmartDashboard::PutData("DriveNormal", new DriveNormal());
SmartDashboard::PutData("moveServos", new moveServos());
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
}
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS
std::shared_ptr<Joystick> OI::getDriveJoy() {
return driveJoy;
}
std::shared_ptr<Joystick> OI::getOtherJoy() {
return otherJoy;
}
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=FUNCTIONS
float OI::GetDriveY() {
return driveJoy->GetRawAxis(1);
}
float OI::GetDriveX() {
return driveJoy->GetRawAxis(0);
}
float OI::GetIntakeY() {
return driveJoy->GetRawAxis(5);
//right num now??
}
float OI::GetThrot() {
return driveJoy->GetRawAxis(2);
}
float OI::GetThrot2() {
return driveJoy->GetRawAxis(3);
}
float OI::GetOtherY1() {
return otherJoy->GetRawAxis(1);
}
float OI::GetOtherY2() {
return otherJoy->GetRawAxis(5);
//before got the joysticks from the wrong joystick oops. may have been the error
}
float OI::GetOtherX1() {
return otherJoy->GetRawAxis(0);
}
float OI::GetOtherX2() {
return otherJoy->GetRawAxis(0);
}
| [
"plahera1@hwemail.com"
] | plahera1@hwemail.com |
d60ccf82fda408b4e99d0b590f37dd788e597171 | 1634d4f09e2db354cf9befa24e5340ff092fd9db | /Wonderland/Wonderland/Editor/Modules/VulkanWrapper/Resource/Resource Backup/VWResourceCache.cpp | b1dc655e08fa159dd23799b47b9d7ef45850a2c4 | [
"MIT"
] | permissive | RodrigoHolztrattner/Wonderland | cd5a977bec96fda1851119a8de47b40b74bd85b7 | ffb71d47c1725e7cd537e2d1380962b5dfdc3d75 | refs/heads/master | 2021-01-10T15:29:21.940124 | 2017-10-01T17:12:57 | 2017-10-01T17:12:57 | 84,469,251 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 392 | cpp | ////////////////////////////////////////////////////////////////////////////////
// Filename: FluxMyWrapper.cpp
////////////////////////////////////////////////////////////////////////////////
#include "VWResourceCache.h"
#include "..\VWContext.h"
VulkanWrapper::VWResourceCache::VWResourceCache()
{
// Set the initial data
// ...
}
VulkanWrapper::VWResourceCache::~VWResourceCache()
{
}
| [
"rodrigoholztrattner@gmail.com"
] | rodrigoholztrattner@gmail.com |
9b327fc1e2fc05b1314dcd75294f795cbaf22f03 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/curl/gumtree/curl_patch_hunk_1102.cpp | 4f5f6c849ead2a84589509e39dc2901210668543 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,449 | cpp | "\n"
, stdout);
fputs(
" --proto-default https ftp.mozilla.org\n"
" https://ftp.mozilla.org\n"
"\n"
-" An unknown or unsupported protocol causes error CURLE_UNSUPPORTED_PRO-\n"
+" An unknown or unsupported protocol causes error CURLE_UNSUPPORTED_PRO-\n"
" TOCOL.\n"
"\n"
" This option does not change the default proxy protocol (http).\n"
"\n"
-" Without this option curl would make a guess based on the host, see\n"
+" Without this option curl would make a guess based on the host, see\n"
" --url for details.\n"
"\n"
" (Added in 7.45.0)\n"
"\n"
" --proto-redir <protocols>\n"
, stdout);
fputs(
-" Tells curl to use the listed protocols on redirect. See --proto\n"
+" Tells curl to use the listed protocols on redirect. See --proto\n"
" for how protocols are represented.\n"
"\n"
" Example:\n"
"\n"
" --proto-redir -all,http,https\n"
" Allow only HTTP and HTTPS on redirect.\n"
"\n"
-" By default curl will allow all protocols on redirect except several\n"
-" disabled for security reasons: Since 7.19.4 FILE and SCP are disabled,\n"
+" By default curl will allow all protocols on redirect except several\n"
+" disabled for security reasons: Since 7.19.4 FILE and SCP are disabled,\n"
" and since 7.40.0 SMB and SMBS are also disabled. Specifying all or +all\n"
, stdout);
fputs(
-" enables all protocols on redirect, including those disabled for secu-\n"
+" enables all protocols on redirect, including those disabled for secu-\n"
" rity.\n"
"\n"
" (Added in 7.20.2)\n"
"\n"
" --proxy-anyauth\n"
-" Tells curl to pick a suitable authentication method when commu-\n"
-" nicating with the given proxy. This might cause an extra\n"
+" Tells curl to pick a suitable authentication method when commu-\n"
+" nicating with the given proxy. This might cause an extra\n"
" request/response round-trip. (Added in 7.13.2)\n"
"\n"
" --proxy-basic\n"
-" Tells curl to use HTTP Basic authentication when communicating\n"
+" Tells curl to use HTTP Basic authentication when communicating\n"
, stdout);
fputs(
" with the given proxy. Use --basic for enabling HTTP Basic with a\n"
-" remote host. Basic is the default authentication method curl\n"
+" remote host. Basic is the default authentication method curl\n"
" uses with proxies.\n"
"\n"
" --proxy-digest\n"
-" Tells curl to use HTTP Digest authentication when communicating\n"
+" Tells curl to use HTTP Digest authentication when communicating\n"
" with the given proxy. Use --digest for enabling HTTP Digest with\n"
" a remote host.\n"
"\n"
" --proxy-negotiate\n"
, stdout);
fputs(
-" Tells curl to use HTTP Negotiate (SPNEGO) authentication when\n"
+" Tells curl to use HTTP Negotiate (SPNEGO) authentication when\n"
" communicating with the given proxy. Use --negotiate for enabling\n"
" HTTP Negotiate (SPNEGO) with a remote host. (Added in 7.17.1)\n"
"\n"
" --proxy-ntlm\n"
-" Tells curl to use HTTP NTLM authentication when communicating\n"
+" Tells curl to use HTTP NTLM authentication when communicating\n"
" with the given proxy. Use --ntlm for enabling NTLM with a remote\n"
" host.\n"
"\n"
" --proxy-service-name <servicename>\n"
, stdout);
fputs(
-" This option allows you to change the service name for proxy\n"
+" This option allows you to change the service name for proxy\n"
" negotiation.\n"
"\n"
-" Examples: --proxy-negotiate proxy-name --proxy-service-name\n"
+" Examples: --proxy-negotiate proxy-name --proxy-service-name\n"
" sockd would use sockd/proxy-name. (Added in 7.43.0).\n"
"\n"
" --proxy1.0 <proxyhost[:port]>\n"
-" Use the specified HTTP 1.0 proxy. If the port number is not\n"
+" Use the specified HTTP 1.0 proxy. If the port number is not\n"
" specified, it is assumed at port 1080.\n"
"\n"
, stdout);
fputs(
-" The only difference between this and the HTTP proxy option (-x,\n"
+" The only difference between this and the HTTP proxy option (-x,\n"
" --proxy), is that attempts to use CONNECT through the proxy will\n"
" specify an HTTP 1.0 protocol instead of the default HTTP 1.1.\n"
"\n"
" --pubkey <key>\n"
-" (SSH) Public key file name. Allows you to provide your public\n"
+" (SSH) Public key file name. Allows you to provide your public\n"
" key in this separate file.\n"
"\n"
" If this option is used several times, the last one will be used.\n"
, stdout);
fputs(
" (As of 7.39.0, curl attempts to automatically extract the public\n"
-" key from the private key file, so passing this option is gener-\n"
+" key from the private key file, so passing this option is gener-\n"
" ally not required. Note that this public key extraction requires\n"
-" libcurl to be linked against a copy of libssh2 1.2.8 or higher\n"
+" libcurl to be linked against a copy of libssh2 1.2.8 or higher\n"
" that is itself linked against OpenSSL.)\n"
"\n"
" -q, --disable\n"
-" If used as the first parameter on the command line, the curlrc\n"
+" If used as the first parameter on the command line, the curlrc\n"
, stdout);
fputs(
-" config file will not be read and used. See the -K, --config for\n"
+" config file will not be read and used. See the -K, --config for\n"
" details on the default config file search path.\n"
"\n"
" -Q, --quote <command>\n"
-" (FTP/SFTP) Send an arbitrary command to the remote FTP or SFTP\n"
-" server. Quote commands are sent BEFORE the transfer takes place\n"
-" (just after the initial PWD command in an FTP transfer, to be\n"
+" (FTP/SFTP) Send an arbitrary command to the remote FTP or SFTP\n"
+" server. Quote commands are sent BEFORE the transfer takes place\n"
+" (just after the initial PWD command in an FTP transfer, to be\n"
" exact). To make commands take place after a successful transfer,\n"
, stdout);
fputs(
-" prefix them with a dash '-'. To make commands be sent after\n"
+" prefix them with a dash '-'. To make commands be sent after\n"
" curl has changed the working directory, just before the transfer\n"
-" command(s), prefix the command with a '+' (this is only sup-\n"
-" ported for FTP). You may specify any number of commands. If the\n"
+" command(s), prefix the command with a '+' (this is only sup-\n"
+" ported for FTP). You may specify any number of commands. If the\n"
" server returns failure for one of the commands, the entire oper-\n"
-" ation will be aborted. You must send syntactically correct FTP\n"
+" ation will be aborted. You must send syntactically correct FTP\n"
, stdout);
fputs(
-" commands as RFC 959 defines to FTP servers, or one of the com-\n"
-" mands listed below to SFTP servers. This option can be used\n"
-" multiple times. When speaking to an FTP server, prefix the com-\n"
+" commands as RFC 959 defines to FTP servers, or one of the com-\n"
+" mands listed below to SFTP servers. This option can be used\n"
+" multiple times. When speaking to an FTP server, prefix the com-\n"
" mand with an asterisk (*) to make curl continue even if the com-\n"
" mand fails as by default curl will stop at first failure.\n"
"\n"
-" SFTP is a binary protocol. Unlike for FTP, curl interprets SFTP\n"
+" SFTP is a binary protocol. Unlike for FTP, curl interprets SFTP\n"
, stdout);
fputs(
-" quote commands itself before sending them to the server. File\n"
+" quote commands itself before sending them to the server. File\n"
" names may be quoted shell-style to embed spaces or special char-\n"
-" acters. Following is the list of all supported SFTP quote com-\n"
+" acters. Following is the list of all supported SFTP quote com-\n"
" mands:\n"
"\n"
" chgrp group file\n"
-" The chgrp command sets the group ID of the file named by\n"
-" the file operand to the group ID specified by the group\n"
+" The chgrp command sets the group ID of the file named by\n"
+" the file operand to the group ID specified by the group\n"
, stdout);
fputs(
" operand. The group operand is a decimal integer group ID.\n"
"\n"
" chmod mode file\n"
-" The chmod command modifies the file mode bits of the\n"
+" The chmod command modifies the file mode bits of the\n"
" specified file. The mode operand is an octal integer mode\n"
" number.\n"
"\n"
" chown user file\n"
" The chown command sets the owner of the file named by the\n"
-" file operand to the user ID specified by the user oper-\n"
+" file operand to the user ID specified by the user oper-\n"
, stdout);
fputs(
" and. The user operand is a decimal integer user ID.\n"
"\n"
" ln source_file target_file\n"
" The ln and symlink commands create a symbolic link at the\n"
-" target_file location pointing to the source_file loca-\n"
+" target_file location pointing to the source_file loca-\n"
" tion.\n"
"\n"
" mkdir directory_name\n"
-" The mkdir command creates the directory named by the\n"
+" The mkdir command creates the directory named by the\n"
" directory_name operand.\n"
"\n"
, stdout);
fputs(
" pwd The pwd command returns the absolute pathname of the cur-\n"
" rent working directory.\n"
"\n"
" rename source target\n"
" The rename command renames the file or directory named by\n"
-" the source operand to the destination path named by the\n"
+" the source operand to the destination path named by the\n"
" target operand.\n"
"\n"
" rm file\n"
" The rm command removes the file specified by the file op-\n"
" erand.\n"
"\n"
, stdout);
fputs(
" rmdir directory\n"
-" The rmdir command removes the directory entry specified\n"
+" The rmdir command removes the directory entry specified\n"
" by the directory operand, provided it is empty.\n"
"\n"
" symlink source_file target_file\n"
" See ln.\n"
"\n"
" -r, --range <range>\n"
-" (HTTP/FTP/SFTP/FILE) Retrieve a byte range (i.e a partial docu-\n"
-" ment) from a HTTP/1.1, FTP or SFTP server or a local FILE.\n"
+" (HTTP/FTP/SFTP/FILE) Retrieve a byte range (i.e a partial docu-\n"
+" ment) from a HTTP/1.1, FTP or SFTP server or a local FILE.\n"
" Ranges can be specified in a number of ways.\n"
"\n"
, stdout);
fputs(
" 0-499 specifies the first 500 bytes\n"
"\n"
| [
"993273596@qq.com"
] | 993273596@qq.com |
96857422adf8d56902e769322d1f263f4bda4a3a | 4c23be1a0ca76f68e7146f7d098e26c2bbfb2650 | /ic8h18/0.005/CC5H11 | 59493f5f3bd558f8a1379890c7d178c305ee8c57 | [] | no_license | labsandy/OpenFOAM_workspace | a74b473903ddbd34b31dc93917e3719bc051e379 | 6e0193ad9dabd613acf40d6b3ec4c0536c90aed4 | refs/heads/master | 2022-02-25T02:36:04.164324 | 2019-08-23T02:27:16 | 2019-08-23T02:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 838 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.005";
object CC5H11;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField uniform 4.26124e-12;
boundaryField
{
boundary
{
type empty;
}
}
// ************************************************************************* //
| [
"jfeatherstone123@gmail.com"
] | jfeatherstone123@gmail.com | |
8793913cc46e3c4697faf2aab3948574dcc4e28a | 5263a39e6f44853ed9b3fce883612d7ceeec994a | /src/io/base.hpp | d544002b0a7119da480f72350395eb9b96e30842 | [] | no_license | PlumpMath/indecorous | 5e8f295c5fb2b5c0bf5f6f88c948310808e4612e | f71a4d254daa1ad334719adccb89ce6edf1d89f9 | refs/heads/master | 2021-01-20T09:54:36.549029 | 2016-09-27T19:56:15 | 2016-09-27T19:56:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 469 | hpp | #ifndef IO_BASE_HPP_
#define IO_BASE_HPP_
#include <cstddef>
namespace indecorous {
class waitable_t;
class read_stream_t {
public:
virtual ~read_stream_t() { }
virtual void read(void *buf, size_t count) = 0;
virtual size_t read_until(char delim, void *buf, size_t count) = 0;
};
class write_stream_t {
public:
virtual ~write_stream_t() { }
virtual void write(void *buf, size_t count) = 0;
};
} // namespace indecorous
#endif // IO_BASE_HPP_
| [
"marc@rethinkdb.com"
] | marc@rethinkdb.com |
b3ad13e9017ff8aa712674ae726fa7938b770b04 | d9806fece7a4ec9519db65d65d7859ad2629a2a5 | /FormatterLib/VerilogFormatterLib/astyle_main.cpp | 5bfa614d811111027c6f02c1e4d4949e0bfe9d47 | [] | no_license | akof1314/CoolFormat | 9eb654cf795425088d2e7ac4c432b3ea0f666be5 | f107a0ff38e2de24c91adbf59c9caaf1d40909a2 | refs/heads/develop | 2022-08-09T22:53:44.437725 | 2018-05-28T13:24:13 | 2018-05-28T13:24:13 | 27,533,937 | 570 | 154 | null | 2021-04-05T10:54:28 | 2014-12-04T09:50:49 | C++ | UTF-8 | C++ | false | false | 26,273 | cpp | // $Id: astyle_main.cpp,v 1.9 2004/02/06 09:37:36 devsolar Exp $
// --------------------------------------------------------------------------
//
// Copyright (c) 1998,1999,2000,2001,2002 Tal Davidson. All rights reserved.
//
// compiler_defines.h
// by Tal Davidson (davidsont@bigfoot.com)
//
// This file is a part of "Artistic Style" - an indentater and reformatter
// of C, C++, C# and Java source files.
//
// --------------------------------------------------------------------------
//
// 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.
//
// --------------------------------------------------------------------------
#include "compiler_defines.h"
#include "astyle_main.h"
#include "astyle.h"
#include <iostream>
#include <fstream>
#include <cstring>
#include <iterator>
#include <sstream>
#include <stdlib.h>
#ifdef WIN32
#include <Windows.h>
#endif
#define IS_PARAM_OPTION(arg,op) ((arg).length() < strlen(op) ? 0 : (arg).COMPARE(0, strlen(op), string(op))==0)
#define IS_PARAM_OPTIONS(arg,a,b) (IS_PARAM_OPTION((arg),(a)) || IS_PARAM_OPTION((arg),(b)))
#define GET_PARAM(arg,op) ((arg).substr(strlen(op)))
#define GET_PARAMS(arg,a,b) (IS_PARAM_OPTION((arg),(a)) ? GET_PARAM((arg),(a)) : GET_PARAM((arg),(b)))
#ifdef USES_NAMESPACE
using namespace std;
using namespace istyle;
#endif
#ifndef ASTYLE_LIB
// default options:
ostream *_err = &cerr;
string _suffix = ".orig";
const string _version = "1.21";
bool shouldBackupFile = true;
// --------------------------------------------------------------------------
// Helper Functions
// --------------------------------------------------------------------------
void SetColor(unsigned short ForeColor=3,unsigned short BackGroundColor=0)
{
#ifdef WIN32
HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hCon,ForeColor|(BackGroundColor*16));
#endif
}
void error(const char *why, const char* what)
{
SetColor(12,0);
(*_err) << why << ' ' << what <<'\n';
SetColor(7,0);
exit(1);
}
#endif // ASTYLE_LIB
bool parseOption(ASFormatter &formatter, const string &arg, const string &/*errorInfo*/)
{
#ifndef ASTYLE_LIB
if ( ( arg == "n" ) || ( arg == "suffix=none" ) )
{
shouldBackupFile = false;
}
else if ( IS_PARAM_OPTION(arg, "suffix=") )
{
string suffixParam = GET_PARAM(arg, "suffix=");
if (suffixParam.length() > 0)
_suffix = suffixParam;
}
else
#endif // ASTYLE_LIB
if ( arg == "style=ansi" )
{
formatter.setBracketIndent(false);
formatter.setSpaceIndentation(4);
formatter.setBracketFormatMode(BREAK_MODE);
formatter.setSwitchIndent(false);
}
else if ( arg == "style=gnu" )
{
formatter.setBlockIndent(true);
formatter.setSpaceIndentation(2);
formatter.setBracketFormatMode(BREAK_MODE);
formatter.setSwitchIndent(false);
}
else if ( arg == "style=kr" )
{
formatter.setBracketIndent(false);
formatter.setSpaceIndentation(4);
formatter.setBracketFormatMode(ATTACH_MODE);
formatter.setSwitchIndent(false);
}
else if (IS_PARAM_OPTION(arg, "A"))
{
int style = 0;
string styleParam = GET_PARAM(arg, "A");
if (styleParam.length() > 0)
style = atoi(styleParam.c_str());
if (style == 1)//Ansi
{
formatter.setBracketIndent(false);
formatter.setSpaceIndentation(4);
formatter.setBracketFormatMode(BREAK_MODE);
formatter.setSwitchIndent(false);
}
else if (style == 2)//KR
{
formatter.setBracketIndent(false);
formatter.setSpaceIndentation(4);
formatter.setBracketFormatMode(ATTACH_MODE);
formatter.setSwitchIndent(false);
}
else if (style == 3)
{
formatter.setBlockIndent(true);
formatter.setSpaceIndentation(2);
formatter.setBracketFormatMode(BREAK_MODE);
formatter.setSwitchIndent(false);
}
}
else if ( IS_PARAM_OPTIONS(arg, "t", "indent=tab=") )
{
int spaceNum = 4;
string spaceNumParam = GET_PARAMS(arg, "t", "indent=tab=");
if (spaceNumParam.length() > 0)
{
spaceNum = atoi(spaceNumParam.c_str());
if(spaceNum==0)
{
//(*_err) << errorInfo << arg << endl;
return false; // unknown option
}
}
formatter.setTabIndentation(spaceNum, false);
}
else if ( IS_PARAM_OPTIONS(arg, "T", "force-indent=tab=") )
{
int spaceNum = 4;
string spaceNumParam = GET_PARAMS(arg, "T", "force-indent=tab=");
if (spaceNumParam.length() > 0)
{
spaceNum = atoi(spaceNumParam.c_str());
if(spaceNum==0)
{
//(*_err) << errorInfo << arg << endl;
return false; // unknown option
}
}
formatter.setTabIndentation(spaceNum, true);
}
else if ( IS_PARAM_OPTION(arg, "indent=tab") )
{
formatter.setTabIndentation(4);
}
else if ( IS_PARAM_OPTIONS(arg, "s", "indent=spaces=") )
{
int spaceNum = 4;
string spaceNumParam = GET_PARAMS(arg, "s", "indent=spaces=");
if (spaceNumParam.length() > 0)
{
spaceNum = atoi(spaceNumParam.c_str());
if(spaceNum==0)
{
//(*_err) << errorInfo << arg << endl;
return false; // unknown option
}
}
formatter.setSpaceIndentation(spaceNum);
}
else if ( IS_PARAM_OPTION(arg, "indent=spaces") )
{
formatter.setSpaceIndentation(4);
}
else if ( IS_PARAM_OPTIONS(arg, "M", "max-instatement-indent=") )
{
int maxIndent = 40;
string maxIndentParam = GET_PARAMS(arg, "M", "max-instatement-indent=");
if (maxIndentParam.length() > 0)
maxIndent = atoi(maxIndentParam.c_str());
if (maxIndent < 40)
{
return false; // unknown option
}
if (maxIndent > 120)
{
return false; // unknown option
}
formatter.setMaxInStatementIndentLength(maxIndent);
}
else if ( IS_PARAM_OPTIONS(arg, "m", "min-conditional-indent=") )
{
int minIndent = 0;
string minIndentParam = GET_PARAMS(arg, "m", "min-conditional-indent=");
if (minIndentParam.length() > 0)
{
minIndent = atoi(minIndentParam.c_str());
if(minIndent > 20)
{
return false; // unknown option
}
}
formatter.setMinConditionalIndentLength(minIndent);
}
else if (IS_PARAM_OPTIONS(arg, "B", "indent-brackets"))
{
formatter.setBracketIndent(true);
}
else if (IS_PARAM_OPTIONS(arg, "G", "indent-blocks"))
{
formatter.setBlockIndent(true);
}
else if (IS_PARAM_OPTIONS(arg, "b", "brackets=break"))
{
formatter.setBracketFormatMode(BREAK_MODE);
}
else if (IS_PARAM_OPTIONS(arg, "a", "brackets=attach"))
{
formatter.setBracketFormatMode(ATTACH_MODE);
}
else if (IS_PARAM_OPTIONS(arg, "O", "one-line=keep-blocks"))
{
formatter.setBreakOneLineBlocksMode(false);
}
else if (IS_PARAM_OPTIONS(arg, "o", "one-line=keep-statements"))
{
formatter.setSingleStatementsMode(false);
}
else if (IS_PARAM_OPTIONS(arg, "L", "pad=paren"))
{
formatter.setParenthesisPaddingMode(true);
}
else if (IS_PARAM_OPTIONS(arg, "l", "pad=block"))
{
formatter.setBlockPaddingMode(true);
}
else if (IS_PARAM_OPTIONS(arg, "P", "pad=all"))
{
formatter.setOperatorPaddingMode(true);
formatter.setParenthesisPaddingMode(true);
formatter.setBlockPaddingMode(true);
}
else if (IS_PARAM_OPTIONS(arg, "p", "pad=oper"))
{
formatter.setOperatorPaddingMode(true);
}
else if (IS_PARAM_OPTIONS(arg, "E", "fill-empty-lines"))
{
formatter.setEmptyLineFill(true);
}
else if (IS_PARAM_OPTIONS(arg, "w", "indent-preprocessor"))
{
formatter.setPreprocessorIndent(true);
}
else if (IS_PARAM_OPTIONS(arg, "c", "convert-tabs"))
{
formatter.setTabSpaceConversionMode(true);
}
else if (IS_PARAM_OPTIONS(arg, "F", "break-blocks=all"))
{
formatter.setBreakBlocksMode(true);
formatter.setBreakClosingHeaderBlocksMode(true);
}
else if (IS_PARAM_OPTIONS(arg, "f", "break-blocks"))
{
formatter.setBreakBlocksMode(true);
}
else if (IS_PARAM_OPTIONS(arg, "e", "break-elseifs"))
{
formatter.setBreakElseIfsMode(true);
}
else if ( (arg == "X") || (arg == "errors-to-standard-output") )
{
//_err = &cout;
}
else if ( (arg == "v") || (arg == "version") )
{
//(*_err) << "iStyle " << _version << endl;
}
else
{
//(*_err) << errorInfo << arg << endl;
return false; // unknown option
}
return true; //o.k.
}
void importOptions(istream &in, vector<string> &optionsVector)
{
char ch;
string currentToken;
while (in)
{
currentToken = "";
do
{
in.get(ch);
if (in.eof())
break;
// treat '#' as line comments
if (ch == '#')
while (in)
{
in.get(ch);
if (ch == '\n' || ch == '\r')
break;
}
// break options on spaces, tabs or new-lines
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r')
break;
else
currentToken.append(1, ch);
}
while (in);
if (currentToken.length() != 0)
optionsVector.push_back(currentToken);
}
}
template<class ITER>
bool parseOptions(ASFormatter &formatter,
const ITER &optionsBegin,
const ITER &optionsEnd,
const string &errorInfo)
{
ITER option;
bool ok = true;
string arg, subArg;
for (option = optionsBegin; option != optionsEnd; ++option)
{
arg = *option; //string(*option);
if (arg.COMPARE(0, 2, string("--")) == 0)
ok &= parseOption(formatter, arg.substr(2), errorInfo);
else if (arg[0] == '-')
{
int i;
for (i=1; i < (int)arg.length(); ++i)
{
if (isalpha(arg[i]) && i > 1)
{
ok &= parseOption(formatter, subArg, errorInfo);
subArg = "";
}
subArg.append(1, arg[i]);
}
ok &= parseOption(formatter, subArg, errorInfo);
subArg = "";
}
else
{
ok &= parseOption(formatter, arg, errorInfo);
subArg = "";
}
}
return ok;
}
#ifndef ASTYLE_LIB
void printHelpTitle()
{
cout << endl;
SetColor(10,0);
cout << "iStyle " << _version;
SetColor(2,0);
cout << " (Fast and Free Automatic Formatter for Verilog Source Code)\n";
cout << " (Created by haimag, Report Bugs: haimag@gmail.com)\n";
cout << " (Thanks to Tal Davidson & Astyle)\n";
cout << endl;
SetColor(7,0);
//~ cout << endl;
}
void printHelpSimple(int isGetchar=0)
{
SetColor(14,0);
cout << endl;
cout << "Usage : iStyle [options] Foo.v B*r.v [...]\n";
cout << endl;
SetColor(7,0);
cout << "For help on options, type 'iStyle -h'" ;
if(isGetchar ==1 )
{
cout << ", Press ENTER to exit." << endl;
getchar();
}
else
{
cout<<"."<<endl;
}
//~ cout << endl;
}
void printHelpFull()
{
SetColor(14,0);
cout << endl;
cout << "Usage : iStyle [options] Foo.v B*r.v [...]\n";
cout << endl;
SetColor(7,0);
cout << "When indenting a specific file, the resulting indented file RETAINS the\n";
cout << "original file-name. The original pre-indented file is renamed, with a\n";
cout << "suffix of \".orig\" added to the original filename. \n";
cout << endl;
cout << "By default, iStyle is set up to indent Verilog files, with 4 spaces per \n" ;
cout << "indent, a maximal indentation of 40 spaces inside continuous statements,\n";
cout << "and NO formatting.\n";
cout << endl;
SetColor(14,0);
cout << "Option's Format:\n";
SetColor(7,0);
cout << "----------------\n";
cout << " Long options (starting with '--') must be written one at a time.\n";
cout << " Short options (starting with '-') may be appended together.\n";
cout << " Thus, -bps4 is the same as -b -p -s4.\n";
cout << endl;
SetColor(14,0);
cout << "Predefined Styling options:\n";
SetColor(7,0);
cout << "---------------------------\n";
cout << " --style=ansi\n";
cout << " ANSI style formatting/indenting.\n";
cout << endl;
cout << " --style=kr\n";
cout << " Kernighan&Ritchie style formatting/indenting.\n";
cout << endl;
cout << " --style=gnu\n";
cout << " GNU style formatting/indenting.\n";
cout << endl;
SetColor(14,0);
cout << "Indentation options:\n";
cout << "--------------------\n";
SetColor(7,0);
cout << " -s OR -s# OR --indent=spaces=#\n";
cout << " Indent using # spaces per indent. Not specifying #\n" ;
cout << " will result in a default of 4 spacec per indent.\n" ;
cout << endl;
cout << " -t OR -t# OR --indent=tab=#\n";
cout << " Indent using tab characters, assuming that each\n";
cout << " tab is # spaces long. Not specifying # will result\n";
cout << " in a default assumption of 4 spaces per tab.\n" ;
cout << endl;
cout << " -T# OR --force-indent=tab=#\n";
cout << " Indent using tab characters, assuming that each\n";
cout << " tab is # spaces long. Force tabs to be used in areas\n";
cout << " iStyle would prefer to use spaces.\n" ;
cout << endl;
cout << " -B OR --indent-brackets\n";
cout << " Add extra indentation to 'begin' and 'end' block brackets.\n";
cout << endl;
cout << " -G OR --indent-blocks\n";
cout << " Add extra indentation entire blocks (including brackets).\n";
cout << endl;
cout << " -m# OR --min-conditional-indent=#\n";
cout << " Indent a minimal # spaces in a continuous conditional\n";
cout << " belonging to a conditional header.\n";
cout << endl;
cout << " -M# OR --max-instatement-indent=#\n";
cout << " Indent a maximal # spaces in a continuous statement,\n";
cout << " relatively to the previous line.\n";
cout << endl;
cout << " -E OR --fill-empty-lines\n";
cout << " Fill empty lines with the white space of their\n";
cout << " previous lines.\n";
cout << endl;
cout << " --indent-preprocessor\n";
cout << " Indent multi-line #define statements\n";
cout << endl;
SetColor(14,0);
cout << "Formatting options:\n";
SetColor(7,0);
cout << "-------------------\n";
cout << " -b OR --brackets=break\n";
cout << " Break brackets from pre-block code (i.e. ANSI C/C++ style).\n";
cout << endl;
cout << " -a OR --brackets=attach\n";
cout << " Attach brackets to pre-block code (i.e. Java/K&R style).\n";
cout << endl;
cout << " -o OR --one-line=keep-statements\n";
cout << " Don't break lines containing multiple statements into\n";
cout << " multiple single-statement lines.\n";
cout << endl;
cout << " -O OR --one-line=keep-blocks\n";
cout << " Don't break blocks residing completely on one line\n";
cout << endl;
cout << " -p OR --pad=oper\n";
cout << " Insert space paddings around operators only.\n";
cout << endl;
cout << " --pad=paren\n";
cout << " Insert space paddings around parenthesies only.\n";
cout << " -l OR --pad=block\n";
cout << " Enclose one statement in a begin-end only for keyword if/else/while/for.\n";
cout << endl;
cout << " -P OR --pad=all\n";
cout << " Insert space paddings around operators AND parenthesies.\n";
cout << endl;
cout << " --convert-tabs\n";
cout << " Convert tabs to spaces.\n";
cout << endl;
cout << " --break-blocks\n";
cout << " Insert empty lines around unrelated blocks, labels, ...\n";
cout << endl;
cout << " --break-blocks=all\n";
cout << " Like --break-blocks, except also insert empty lines \n";
cout << " around closing headers (e.g. 'else', ...).\n";
cout << endl;
cout << " --break-elseifs\n";
cout << " Break 'else if()' statements into two different lines.\n";
cout << endl;
SetColor(14,0);
cout << "Other options:\n";
SetColor(7,0);
cout << "-------------\n";
cout << " --suffix=####\n";
cout << " Append the suffix #### instead of '.orig' to original filename.\n";
cout << endl;
cout << " -n OR --suffix=none" << endl;
cout << " Tells Astyle not to keep backups of the original source files." << endl;
cout << " WARNING: Use this option with care, as Astyle comes with NO WARRANTY..." << endl;
cout << endl;
cout << " -X OR --errors-to-standard-output\n";
cout << " Print errors and help information to standard-output rather than\n";
cout << " to standard-error.\n";
cout << endl;
cout << " -v OR --version\n";
cout << " Print version number\n";
cout << endl;
cout << " -h OR -? OR --help\n";
cout << " Print this help message\n";
cout << endl;
cout << " --options=#### OR --options=none\n";
cout << " Parse used the specified options file: ####, options=none, none\n";
cout << " parse options file, and not looks for parse options files\n";
cout << endl;
SetColor(14,0);
cout << "Default options file:\n";
SetColor(7,0);
cout << "---------------------\n";
cout << " iStyle looks for a default options file in the following order:\n";
cout << " 1. The contents of the ISTYLE_OPTIONS environment\n";
cout << " variable if it exists.\n";
cout << " 2. The file called .iStylerc in the directory pointed to by the\n";
cout << " HOME environment variable ( i.e. $HOME/.iStylerc ).\n";
cout << " 3. The file called .iStylerc in the directory pointed to by the\n";
cout << " HOMEPATH environment variable ( i.e. %HOMEPATH%\\.iStylerc ).\n";
cout << " If a default options file is found, the options in this file\n";
cout << " will be parsed BEFORE the command-line options.\n";
cout << " Options within the default option file may be written without\n";
cout << " the preliminary '-' or '--'.\n";
SetColor(7,0);
cout << endl;
}
bool isWriteable( char const * const filename )
{
std::ifstream in(filename);
if (!in)
{
//(*_err) << "File '" << filename << "' does not exist." << endl;
return false;
}
in.close();
std::ofstream out(filename, std::ios_base::app);
if (!out)
{
//(*_err) << "File '" << filename << "' is not writeable." << endl;
return false;
}
out.close();
return true;
}
#endif // ASTYLE_LIB
#ifdef ASTYLE_LIB
bool VerilogTidyMain(const char* pSourceIn, const char* pOptions, std::string &strOut, std::string &strErr)
{
if (pSourceIn == NULL)
{
strErr = "No pointer to source input.";
return false;
}
if (pOptions == NULL)
{
strErr = "No pointer to AStyle options.";
return false;
}
ASFormatter formatter;
vector<string> optionsVector;
istringstream opt(pOptions);
importOptions(opt, optionsVector);
bool ok = parseOptions(formatter,
optionsVector.begin(),
optionsVector.end(),
string("Unknown command line option: "));
if (!ok)
strErr = "Unknown command line option: ";
istringstream in(pSourceIn);
ASStreamIterator streamIterator(&in);
ostringstream out;
formatter.init(&streamIterator);
while (formatter.hasMoreLines())
{
out << formatter.nextLine();
if (formatter.hasMoreLines())
out << "\n";
}
strOut = out.str();
return true;
}
#elif !defined(ASTYLECON_LIB)
int main(int argc, char *argv[])
{
ASFormatter formatter;
vector<string> fileNameVector;
vector<string> optionsVector;
string optionsFileName = "";
string arg;
bool ok = true;
bool shouldPrintHelp = false;
bool shouldParseOptionsFile = true;
_err = &cerr;
_suffix = ".orig";
printHelpTitle();
// manage flags
for (int i=1; i<argc; i++)
{
arg = string(argv[i]);
if ( IS_PARAM_OPTION(arg ,"--options=none") )
{
shouldParseOptionsFile = false;
}
else if ( IS_PARAM_OPTION(arg ,"--options=") )
{
optionsFileName = GET_PARAM(arg, "--options=");
}
else if ( (arg == "-h") || (arg == "--help") || (arg == "-?") )
{
shouldPrintHelp = true;
}
else if (arg[0] == '-')
{
optionsVector.push_back(arg);
}
else // file-name
{
fileNameVector.push_back(arg);
}
}
// parse options file
if (shouldParseOptionsFile)
{
if (optionsFileName.compare("") == 0)
{
char* env = getenv("ISTYLE_OPTIONS");
if (env != NULL)
optionsFileName = string(env);
}
if (optionsFileName.compare("") == 0)
{
char* env = getenv("HOME");
if (env != NULL)
optionsFileName = string(env) + string("/.iStylerc");
}
if (optionsFileName.compare("") == 0)
{
char* drive = getenv("HOMEDRIVE");
char* path = getenv("HOMEPATH");
if (path != NULL)
optionsFileName = string(drive) + string(path) + string("/.iStylerc");
}
if (!optionsFileName.empty())
{
ifstream optionsIn(optionsFileName.c_str());
if (optionsIn)
{
vector<string> fileOptionsVector;
// reading (whitespace seperated) strings from file into string vector
importOptions(optionsIn, fileOptionsVector);
ok = parseOptions(formatter,
fileOptionsVector.begin(),
fileOptionsVector.end(),
string("Unknown option in default options file: "));
}
optionsIn.close();
if (!ok)
{
printHelpSimple();
}
}
}
// parse options from command line
ok = parseOptions(formatter,
optionsVector.begin(),
optionsVector.end(),
string("Unknown command line option: "));
if (!ok)
{
printHelpSimple();
exit(1);
}
if (shouldPrintHelp)
{
printHelpFull();
exit(1);
}
// if no files have been given, use cin for input and cout for output
if (fileNameVector.empty() )
{
printHelpSimple(1);
}
else
{
// indent the given files
for (int i=0; i<fileNameVector.size(); i++)
{
string originalFileName = fileNameVector[i];
string inFileName = originalFileName + _suffix;
if ( ! isWriteable(originalFileName.c_str()) )
{
error(string("Error: File '" + originalFileName ).c_str() ,
"' does not exist, or is read-only.");
continue;
}
remove(inFileName.c_str());
if ( rename(originalFileName.c_str(), inFileName.c_str()) < 0)
{
error(string("Error: Could not rename " + originalFileName).c_str() ,
string(" to " + inFileName).c_str());
exit(1);
}
ifstream in(inFileName.c_str());
if (!in)
{
error("Could not open input file", inFileName.c_str());
exit(1);
}
ofstream out(originalFileName.c_str());
if (!out)
{
error("Could not open output file", originalFileName.c_str());
exit(1);
}
formatter.init( new ASStreamIterator(&in) );
while (formatter.hasMoreLines() )
{
out << formatter.nextLine();
if (formatter.hasMoreLines())
out << endl;
}
out.flush();
out.close();
in.close();
if ( ! shouldBackupFile )
{
remove( inFileName.c_str() );
}
// print
SetColor(3,0);
cout <<"Indented file -- " <<originalFileName << "."<< endl;
SetColor(7,0);
}
}
SetColor(7,0);
return 0;
}
#endif // ASTYLE_LIB | [
"kof1234@sina.com"
] | kof1234@sina.com |
767396f3011b24bb30e3e87198b1d987e09e9a8a | 071c45eeaa4ee0d181cf51f492fbe0f10b148c7c | /CourseRegistration.cpp | 3919582ca69a079105070b0f6cdcf02eca93d2fc | [] | no_license | DineshBS44/Course-Allocation | ce7a158678bcb724a94fd582fcee4fef8855dc3e | f260f5d555ef89dbc29e935219aafb2a7c2f9e81 | refs/heads/master | 2023-07-21T15:04:20.797476 | 2021-08-28T10:29:55 | 2021-08-28T10:29:55 | 400,757,208 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,167 | cpp | #include<bits/stdc++.h>
using namespace std;
const int MAX_N = 2e3 + 5;
vector<vector<int>> courseGraph(MAX_N); // Graph storing the courses and its connections
int n;
map<string, int> days;
map<string, int> courseInd;
map<string, int> studentsInd;
int interactions;
int studentsCount;
class Course {
public:
string name;
int capacity;
int availability;
int day;
int timeStartInMins;
int timeEndInMins;
set<string> registeredStudents; // Set is used to keep track of the registered students for a course
queue<string> waitingList; // Queue is used for maintaining the waiting list for a particular course
};
class Student {
public:
string regNo;
set<int> registeredCourses; // Set is used to keep a list of registered courses
};
void precompute() {
days["Mon"] = 0, days["Tue"] = 1, days["Wed"] = 2, days["Thu"] = 3;
days["Fri"] = 4, days["Sat"] = 5, days["Sun"] = 6;
}
vector<int> findTimeOfDayInMins(string timeslot) {
vector<int> time(2, 0);
int i = 0, sz = timeslot.size();
while (i < sz && timeslot[i] != ' ') {
i++;
}
i++;
string startHour = "";
while (i < sz && timeslot[i] != ':') {
startHour += timeslot[i];
i++;
}
i++;
string startMins = "";
int startMorning = 1;
while (i < sz && timeslot[i] >= '0' && timeslot[i] <= '9') {
startMins += timeslot[i];
i++;
}
if (timeslot[i] == 'p') {
startMorning = 0;
}
time[0] = (stoi(startHour) % 12) * 60 + stoi(startMins);
if (!startMorning) {
time[0] += 12 * 60; // Adding 12 hours to the time in "pm" for the startTime
}
while (i < sz && timeslot[i] != '-') {
i++;
}
i++;
string endHour = "";
while (i < sz && timeslot[i] != ':') {
endHour += timeslot[i];
i++;
}
i++;
string endMins = "";
int isMorning = 1;
while (i < sz && timeslot[i] >= '0' && timeslot[i] <= '9') {
endMins += timeslot[i];
i++;
}
if (timeslot[i] == 'p') {
isMorning = 0;
}
time[1] = (stoi(endHour) % 12) * 60 + stoi(endMins);
if (!isMorning) {
time[1] += 12 * 60; // Adding 12 hours to the time in "pm" for the endTime
}
return time;
}
int main() {
precompute();
cout << "* * * * * Course Registration * * * * *\n";
cout << "Enter the number of courses\n";
cin >> n;
vector<Course> courses(n);
for (int i = 0; i < n; i++) {
string timeslot;
cout << "Enter the name of the course " << (i + 1) << " in camelCase(Eg: OperatingSystems)\n";
string courseName;
cin >> courseName;
courses[i].name = courseName;
courseInd[courses[i].name] = i + 1;
cout << "Enter the course capacity\n";
cin >> courses[i].capacity;
cout << "Enter the available seats\n";
cin >> courses[i].availability;
cout << "Enter the timeslot for the course(Eg: \"Monday 4:30pm-5:30pm\")\n";
cin.ignore();
getline(cin, timeslot);
courses[i].day = days[timeslot.substr(0, 3)];
vector<int> timeInMins = findTimeOfDayInMins(timeslot);
courses[i].timeStartInMins = timeInMins[0];
courses[i].timeStartInMins += 24 * courses[i].day;
courses[i].timeEndInMins = timeInMins[1];
courses[i].timeEndInMins += 24 * courses[i].day;
cout << "\n";
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (!(courses[i].timeEndInMins <= courses[j].timeStartInMins ||
courses[j].timeEndInMins <= courses[i].timeStartInMins)) {
courseGraph[i].push_back(j);
courseGraph[j].push_back(i);
}
}
}
cout << "Enter the number of students that can participate in the registration\n";
cin >> studentsCount;
vector<Student> students(studentsCount);
for (int i = 0; i < studentsCount; i++) {
cout << "Enter registration number of student " + i + 1 << "\n";
cin >> students[i].regNo;
studentsInd[students[i].regNo] = i + 1;
}
cout << "\n";
cout << "Course Registration begins\n";
cout << "Enter the number of interactions by the students in order\n";
cin >> interactions;
for (int i = 0; i < interactions; i++) {
string regNo;
cout << "Enter student's registration number\n";
cin >> regNo;
if (studentsInd[regNo] == 0) {
cout << "This student is not allowed to take part in the registration process\n";
cout << "\n";
continue;
}
int studentIndex = studentsInd[regNo] - 1;
cout << "1. Register for a course\n2. Delete a course\n";
cout << "Enter interaction type:";
int type;
cin >> type;
if (type == 1) {
cout << "Enter the name of the course in camelCase(Eg: OperatingSystems)\n";
string name;
cin >> name;
if (courseInd[name] == 0) {
cout << "Course doesn't exist\n";
cout << "\n";
continue;
}
int courseIndex = courseInd[name] - 1;
if (courses[courseIndex].registeredStudents.find(regNo) != courses[courseIndex].registeredStudents.end()) {
cout << "Course is already registered by the student\n";
cout << "\n";
continue;
}
bool canRegister = true;
for (auto i: courseGraph[courseIndex]) {
if (students[studentIndex].registeredCourses.find(i) !=
students[studentIndex].registeredCourses.end()) {
canRegister = false;
break;
}
}
if (!canRegister) {
cout << "This course clashes with other registered course(s) and hence registration is unsuccessful\n";
cout << "\n";
continue;
}
if (courses[courseIndex].registeredStudents.size() == courses[courseIndex].availability) {
cout << "This course has no seats left. The student is added to the waiting list";
courses[courseIndex].waitingList.push(regNo);
} else {
courses[courseIndex].registeredStudents.insert(regNo);
students[studentIndex].registeredCourses.insert(courseIndex);
cout << "Course is successfully registered\n";
}
} else if (type == 2) {
cout << "Enter the name of the course in camelCase(Eg: OperatingSystems)\n";
string name;
cin >> name;
if (courseInd[name] == 0) {
cout << "Course doesn't exist\n";
cout << "\n";
continue;
}
int courseIndex = courseInd[name] - 1;
if (courses[courseIndex].registeredStudents.find(regNo) == courses[courseIndex].registeredStudents.end()) {
cout << "Course is not registered by the student\n";
cout << "\n";
continue;
}
courses[courseIndex].registeredStudents.erase(courses[courseIndex].registeredStudents.find(regNo));
students[studentIndex].registeredCourses.erase(students[studentIndex].registeredCourses.find(courseIndex));
if (courses[courseIndex].registeredStudents.size() ==
courses[courseIndex].availability - 1) { // Handling of waiting list
if (courses[courseIndex].waitingList.size() > 0) {
courses[courseIndex].registeredStudents.insert(courses[courseIndex].waitingList.front());
students[studentsInd[courses[courseIndex].waitingList.front()] - 1].registeredCourses.insert(
courseIndex);
courses[courseIndex].waitingList.pop();
}
}
cout << "Course is successfully deleted\n";
} else {
cout << "Invalid choice by the student\n";
}
cout << "\n";
}
return 0;
}
| [
"dineshbs444@gmail.com"
] | dineshbs444@gmail.com |
7dadedf22cbbb32204d15e1aa1a5bb2e1e7f9061 | 032d37b703b99336bc5223b7853f1391d49080df | /Data Structures and Algorithm (C++)/Program and Codes/1_to_14_Programming_Topics_and_Questions/8_Jumps_in_loop_Break-Continue.cpp | 7c2fb28d41df1c78c4418b49b798c10009ec6023 | [] | no_license | DOOMSTERR/My_DSA_Learning | 59d2406c912f7ebeed36cc0791694c7a4cce06c2 | d2e4101bc2556c0580ea9439346621bf17bc0f9f | refs/heads/master | 2023-07-30T02:38:35.323114 | 2021-09-13T11:25:43 | 2021-09-13T11:25:43 | 405,940,485 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 642 | cpp | # include<iostream>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("Input.txt", "r", stdin);
freopen("Output.txt", "w", stdout);
#endif
int pocketMoney=3000;
for(int date=1; date<=30; date++){
if(date%2==0){
continue; // if exetution hits 'continue' next line will no be executed, will be skipped to next ilteration of the loop.
}
if(pocketMoney==0){
cout<<"No Money"<<endl;
break;
}
cout<<"Go out Today"<<date<<endl;
cout<<pocketMoney<<endl;
pocketMoney=pocketMoney-500;
}
} | [
"abhihsek_kumar_007@yahoo.com"
] | abhihsek_kumar_007@yahoo.com |
22f25714ba834a4ab64dae4c25a7176fe8d4d6c9 | c14ee30aa4f0cea75a92f793e0812c81db60d384 | /Classes/GameScene.h | 1d85f869329d0ef34c570da5c6db7b0870d9b742 | [] | no_license | Zaka/yap | b0b39cb8e391c321e72bbf8589ea5e1ec9ee59c3 | 074aae9eb2135dda1b674358bf1e0f69e5d4c2ed | refs/heads/master | 2020-03-27T04:24:18.870512 | 2014-03-06T23:38:58 | 2014-03-06T23:38:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 197 | h | #ifndef __GAMESCENE_H__
#define __GAMESCENE_H__
#include "cocos2d.h"
class GameScene : public cocos2d::Scene
{
public:
GameScene();
//CREATE_FUNC(GameScene);
};
#endif //__GAMESCENE_H__
| [
"zakaelab@gmail.com"
] | zakaelab@gmail.com |
c3d1c2e9a97bcf02498f6eb3ec2776ad33d707ae | 65c18b48d1488508c1cc1ae07df29d999ffd20d1 | /src/lib/pre_processor.h | 315469ebeb1420a6621ee4512d9928471fadb8be | [] | no_license | xJustesen/NA63-2018 | 9afcd1dcfedde9122bcc4ecf73f87a80b5ad5a57 | 072dbf3f733b4548a31e984bf055e298dfc0f46b | refs/heads/master | 2020-03-25T04:51:22.203319 | 2019-03-22T12:50:52 | 2019-03-22T12:50:52 | 143,416,896 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 811 | h | #ifndef PREPROCESSOR_H
#define PREPROCESSOR_H
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include "auxillary_functions.h"
using namespace std;
struct CONFIG
{
double BeamEnergy, CrystalThickness, cut_lb_x, cut_ub_x, cut_lb_y, cut_ub_y;
std::string runno, BeamProfile, CrystalType, DataPath, TheorySpectrum, OutputDataFilename, OutputEventFilename, InputDatafile;
int IncludeBG, NEvents, Simulation;
};
class PreProcessor
{
public:
vector<double> z_;
CONFIG config_;
PreProcessor(string config_file);
private:
vector<string> legal_input_;
void InitializeInputVariables(std::string file_name);
void InitializeInputVariablesHelper(std::string, std::string);
int SearchLegalInput(std::string key);
void LoadConfigFile(const string &configfile);
};
#endif | [
"jensbojustesen@gmail.com"
] | jensbojustesen@gmail.com |
21967bc9a79e1516b044c15600d2de7b8f945733 | 5cb81364945560e44999d1dcd0d6a27bc734ad24 | /RevolutionTheGame/RevolutionTheGame/RenderElement.cpp | dcd3946037da9a0bb6678751ee9b59b836ea1eea | [] | no_license | stack-overflow/gfx | 2d745807ace5b2760f222105687b23f1006b2866 | 7f3206f79ffb704a4dd30ec0403a6eb320ff7006 | refs/heads/master | 2021-01-10T20:26:47.123351 | 2014-02-14T19:23:14 | 2014-02-14T19:23:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 62 | cpp | #include "RenderElement.h"
RenderElement::RenderElement()
{}
| [
"uberthrash@gmail.com"
] | uberthrash@gmail.com |
bf1a80d5e66a2c8500a5416bcde7139b26c46bec | a248529715b5ab9b922085873b41b7b691a1ddda | /RouteSelector/router/dijkstraListCFile2.cc | 86bb529ed4564a0880574f3094158c7c8e932cf1 | [] | no_license | JaumeFigueras/tfmBackend | cba6a0f6440268b0429d9f322d1a9ff8a0efc2ad | 9e259c7a7b984f75e759dbdcdfff2428ea5f6c2c | refs/heads/master | 2022-01-22T04:58:48.004724 | 2019-07-10T19:16:27 | 2019-07-10T19:16:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,966 | cc | // C / C++ program for Dijkstra's shortest path algorithm for adjacency
// list representation of graph
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include<string.h>
#define MAX 3007
int nodes[MAX];
int vehicles[MAX][3];
bool final[MAX];
struct PrecNodeDist
{
int pred[4];
double cost[4];
double costu[4];
int vehicle[4];
double rampPos[4];
double rampNeg[4];
double dist[4];
};
PrecNodeDist pred[MAX];
int numNode=0;
int srcG=0;
// A structure to represent a node in adjacency list
struct AdjListNode
{
int dest;
double walkingCost;
double CarCost;
double BRPCost;
double AllTerrainCost;
struct AdjListNode* next;
double rampPos;
double rampNeg;
double dist;
};
// A structure to represent an adjacency liat
struct AdjList
{
struct AdjListNode *head; // pointer to head node of list
};
// A structure to represent a graph. A graph is an array of adjacency lists.
// Size of array will be V (number of vertices in graph)
struct Graph
{
int V;
struct AdjList* array;
};
// A utility function to create a new adjacency list node
struct AdjListNode* newAdjListNode(int dest, double walkingCost,double CarCost,double BRPCost,double AllTerrainCost,double rampPos, double rampNeg, double dist)
{
struct AdjListNode* newNode =
(struct AdjListNode*) malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->walkingCost = walkingCost;
newNode->CarCost = CarCost;
newNode->BRPCost = BRPCost;
newNode->AllTerrainCost = AllTerrainCost;
newNode->rampPos=rampPos;
newNode->rampNeg=rampNeg;
newNode->dist=dist;
newNode->next = NULL;
return newNode;
}
// A utility function that creates a graph of V vertices
struct Graph* createGraph(int V)
{
struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
graph->V = V;
// Create an array of adjacency lists. Size of array will be V
graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));
for (int i = 0; i < V; ++i){
graph->array[i].head = NULL;
nodes[i]=0;
final[i]=false;
vehicles[i][0]=vehicles[i][1]=vehicles[i][2]=0;
}
return graph;
}
// Adds an edge to an undirected graph
void addEdge(struct Graph* graph, int src, int dest, double walkingCost,double CarCost,double BRPCost,double AllTerrainCost,double rampPos, double rampNeg, double dist)
{
srcG=src;
// Add an edge from src to dest. A new node is added to the adjacency
// list of src. The node is added at the begining
struct AdjListNode* newNode = newAdjListNode(dest, walkingCost, CarCost, BRPCost, AllTerrainCost, rampPos, rampNeg, dist);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
// Since graph is undirected, add an edge from dest to src also
/*
newNode = newAdjListNode(src, weight);
newNode->next = graph->array[dest].head;
graph->array[dest].head = newNode;*/
}
// Structure to represent a min heap node
struct MinHeapNode
{
int v;
double dist;
};
// Structure to represent a min heap
struct MinHeap
{
int size; // Number of heap nodes present currently
int capacity; // Capacity of min heap
int *pos; // This is needed for decreaseKey()
struct MinHeapNode **array;
};
// A utility function to create a new Min Heap Node
struct MinHeapNode* newMinHeapNode(int v, double dist)
{
struct MinHeapNode* minHeapNode =
(struct MinHeapNode*) malloc(sizeof(struct MinHeapNode));
minHeapNode->v = v;
minHeapNode->dist = dist;
return minHeapNode;
}
// A utility function to create a Min Heap
struct MinHeap* createMinHeap(int capacity)
{
struct MinHeap* minHeap =
(struct MinHeap*) malloc(sizeof(struct MinHeap));
minHeap->pos = (int *)malloc(capacity * sizeof(int));
minHeap->size = 0;
minHeap->capacity = capacity;
minHeap->array =
(struct MinHeapNode**) malloc(capacity * sizeof(struct MinHeapNode*));
return minHeap;
}
// A utility function to swap two nodes of min heap. Needed for min heapify
void swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b)
{
struct MinHeapNode* t = *a;
*a = *b;
*b = t;
}
// A standard function to heapify at given idx
// This function also updates position of nodes when they are swapped.
// Position is needed for decreaseKey()
void minHeapify(struct MinHeap* minHeap, int idx)
{
int smallest, left, right;
smallest = idx;
left = 2 * idx + 1;
right = 2 * idx + 2;
if (left < minHeap->size &&
minHeap->array[left]->dist < minHeap->array[smallest]->dist )
smallest = left;
if (right < minHeap->size &&
minHeap->array[right]->dist < minHeap->array[smallest]->dist )
smallest = right;
if (smallest != idx)
{
// The nodes to be swapped in min heap
MinHeapNode *smallestNode = minHeap->array[smallest];
MinHeapNode *idxNode = minHeap->array[idx];
// Swap positions
minHeap->pos[smallestNode->v] = idx;
minHeap->pos[idxNode->v] = smallest;
// Swap nodes
swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]);
minHeapify(minHeap, smallest);
}
}
// A utility function to check if the given minHeap is ampty or not
int isEmpty(struct MinHeap* minHeap)
{
return minHeap->size == 0;
}
// Standard function to extract minimum node from heap
struct MinHeapNode* extractMin(struct MinHeap* minHeap)
{
if (isEmpty(minHeap))
return NULL;
// Store the root node
struct MinHeapNode* root = minHeap->array[0];
// Replace root node with last node
struct MinHeapNode* lastNode = minHeap->array[minHeap->size - 1];
minHeap->array[0] = lastNode;
// Update position of last node
minHeap->pos[root->v] = minHeap->size-1;
minHeap->pos[lastNode->v] = 0;
// Reduce heap size and heapify root
--minHeap->size;
minHeapify(minHeap, 0);
return root;
}
// Function to decreasy dist value of a given vertex v. This function
// uses pos[] of min heap to get the current index of node in min heap
void decreaseKey(struct MinHeap* minHeap, int v, double dist)
{
// Get the index of v in heap array
int i = minHeap->pos[v];
// Get the node and update its dist value
minHeap->array[i]->dist = dist;
// Travel up while the complete tree is not hepified.
// This is a O(Logn) loop
while (i && minHeap->array[i]->dist < minHeap->array[(i - 1) / 2]->dist)
{
// Swap this node with its parent
minHeap->pos[minHeap->array[i]->v] = (i-1)/2;
minHeap->pos[minHeap->array[(i-1)/2]->v] = i;
swapMinHeapNode(&minHeap->array[i], &minHeap->array[(i - 1) / 2]);
// move to parent index
i = (i - 1) / 2;
}
}
// A utility function to check if a given vertex
// 'v' is in min heap or not
bool isInMinHeap(struct MinHeap *minHeap, int v)
{
if (minHeap->pos[v] < minHeap->size)
return true;
return false;
}
// A utility function used to print the solution
void printArr(double dist[], int n)
{
printf("Vertex Distance from Source\n");
for (int i = 0; i < n; ++i)
printf("%d \t\t %f\n", i, dist[i]);
}
// The main function that calulates distances of shortest paths from src to all
// vertices. It is a O(ELogV) function
void dijkstra(struct Graph* graph, int src, int vehicle)
{
int V = graph->V;// Get the number of vertices in graph
double dist[V]; // dist values used to pick minimum weight edge in cut
int trobat=0;
// minHeap represents set E
struct MinHeap* minHeap = createMinHeap(V);
// Initialize min heap with all vertices. dist value of all vertices
for (int v = 0; v < V; ++v)
{
dist[v]= INT_MAX;
minHeap->array[v] = newMinHeapNode(v, dist[v]);
minHeap->pos[v] = v;
}
// Make dist value of src vertex as 0 so that it is extracted first
minHeap->array[src] = newMinHeapNode(src, dist[src]);
minHeap->pos[src] = src;
dist[src]= 0;
decreaseKey(minHeap, src, dist[src]);
pred[src].cost[vehicle]=0.0;
pred[src].vehicle[vehicle]=vehicle;
// Initially size of min heap is equal to V
minHeap->size = V;
// In the followin loop, min heap contains all nodes
// whose shortest distance is not yet finalized.
while (!isEmpty(minHeap))
{
// Extract the vertex with minimum distance value
struct MinHeapNode* minHeapNode = extractMin(minHeap);
int u = minHeapNode->v; // Store the extracted vertex number
// Traverse through all adjacent vertices of u (the extracted
// vertex) and update their distance values
struct AdjListNode* pCrawl = graph->array[u].head;
while (pCrawl != NULL)
{
int v = pCrawl->dest;
// If shortest distance to v is not finalized yet, and distance to v
// through u is less than its previously calculated distance
if (vehicle==0 && isInMinHeap(minHeap, v) && dist[u] != INT_MAX &&
pCrawl->walkingCost + dist[u] < dist[v])
{
dist[v] = dist[u] + pCrawl->walkingCost;
pred[v].pred[0] = u;
pred[v].cost[0]=dist[u] +pCrawl->walkingCost;
pred[v].costu[0]=pCrawl->walkingCost;
pred[v].vehicle[0]=pred[src].vehicle[0];
pred[v].rampPos[0]=pCrawl->rampPos;
pred[v].rampNeg[0]=pCrawl->rampNeg;
pred[v].dist[0]=pCrawl->dist;
// update distance value in min heap also
decreaseKey(minHeap, v, dist[v]);
}
if (vehicle==1 && isInMinHeap(minHeap, v) && dist[u] != INT_MAX &&
pCrawl->CarCost + dist[u] < dist[v])
{
dist[v] = dist[u] + pCrawl->CarCost;
pred[v].pred[1] = u;
pred[v].cost[1] = dist[u] +pCrawl->CarCost;
pred[v].costu[1] = pCrawl->CarCost;
pred[v].vehicle[1]=pred[src].vehicle[1];
pred[v].rampPos[1]=pCrawl->rampPos;
pred[v].rampNeg[1]=pCrawl->rampNeg;
pred[v].dist[1]=pCrawl->dist;
// update distance value in min heap also
decreaseKey(minHeap, v, dist[v]);
}
if (vehicle==2 && isInMinHeap(minHeap, v) && dist[u] != INT_MAX &&
pCrawl->BRPCost + dist[u] < dist[v])
{
dist[v] = dist[u] + pCrawl->BRPCost;
pred[v].pred[2] = u;
pred[v].cost[2] = dist[u] +pCrawl->BRPCost;
pred[v].costu[2] = pCrawl->BRPCost;
pred[v].vehicle[2]=pred[src].vehicle[2];
pred[v].rampPos[2]=pCrawl->rampPos;
pred[v].rampNeg[2]=pCrawl->rampNeg;
pred[v].dist[2]=pCrawl->dist;
// update distance value in min heap also
decreaseKey(minHeap, v, dist[v]);
}
if (vehicle==3 && isInMinHeap(minHeap, v) && dist[u] != INT_MAX &&
pCrawl->AllTerrainCost + dist[u] < dist[v])
{
dist[v] = dist[u] + pCrawl->AllTerrainCost;
pred[v].pred[3] = u;
pred[v].cost[3]=dist[u] +pCrawl->AllTerrainCost;
pred[v].costu[3]=pCrawl->AllTerrainCost;
pred[v].vehicle[3]=pred[src].vehicle[3];
pred[v].rampPos[3]=pCrawl->rampPos;
pred[v].rampNeg[3]=pCrawl->rampNeg;
pred[v].dist[3]=pCrawl->dist;
// update distance value in min heap also
decreaseKey(minHeap, v, dist[v]);
}
pCrawl = pCrawl->next;
}
}
// print the calculated shortest distances
//printArr(dist, V);
}
/*
extern "C" void memorize(char file[]);
extern "C" int *routing(int end, int start);*/
struct Graph* globalGraph;
extern "C" void inizializeGraph(int V);
extern "C" int findKey(int nodeId);
extern "C" int *findPredecesor(int key,int vehicle);
extern "C" double *findPredecesorValues(int key,int vehicle);
extern "C" void solve(int start, int vehicle);
extern "C" void inicializeEdge(int nodeKey1,int nodeKey2, double walkingCost,double CarCost,double BRPCost,double AllTerrainCost,double rampPos, double rampNeg, double dist);
extern "C" int addNode(int nodeKey);
extern "C" void addVehicle(int type, int node);
extern "C" void delateVehicles();
extern "C" double getMaxValue();
double getMaxValue(){
return INT_MAX;
}
/*
for (int i = 0; i < V; ++i){
graph->array[i].head = NULL;
nodes[i]=0;
final[i]=false;
*/
void delateVehicles(){
for (int v = 0; v < MAX; ++v)
{
vehicles[v][0]=vehicles[v][1]=vehicles[v][2]=0;
}
}
void addVehicle(int type, int node) {
int nodekey = -1;
for(int i =0; i<numNode;++i){
if(nodes[i]==node){
nodekey=i;
}
}
if(nodekey>-1)
++vehicles[nodekey][type-1];
}
void inizializeGraph(int V){
globalGraph = createGraph(V);
}
int addNode(int nodeKey){
nodes[numNode]=nodeKey;
++numNode;
return numNode-1;
}
void inicializeEdge(int nodeKey1,int nodeKey2, double walkingCost,double CarCost,double BRPCost,double AllTerrainCost, double rampPos, double rampNeg, double dist){
int node1;
int node2;
for(int i =0; i<numNode;++i){
if(nodes[i]==nodeKey1){
node1=i;
}
if(nodes[i]==nodeKey2){
node2=i;
}
}
addEdge(globalGraph, node1, node2, walkingCost, CarCost, BRPCost, AllTerrainCost, rampPos, rampNeg, dist);
}
void solve(int start, int vehicle){
for(int i =0; i<numNode;++i){
if(nodes[i]==start){
start=i;
}
}
dijkstra(globalGraph, start,vehicle);
}
int *findPredecesor(int key,int vehicle){
int * returnValue =(int *) malloc(sizeof(int) * 3);
if(vehicle>0){
if(pred[key].cost[0]<pred[key].cost[vehicle] && (pred[key].pred[0]!=pred[key].pred[vehicle]|| pred[key].costu[0]<pred[key].costu[vehicle])){
double minDiff=pred[key].cost[0];
bool canvia=true;
int keyu= pred[key].pred[vehicle];
double minsum=pred[key].costu[vehicle];
//printf("%d %d %d c%f v%f c%f v%f\n",key,pred[key].pred[0],pred[key].pred[vehicle],pred[key].cost[0],pred[key].cost[vehicle],pred[key].costu[0],pred[key].costu[vehicle]);
int k=0;
while(pred[keyu].costu[vehicle]<99998 && pred[keyu].pred[vehicle]!=srcG && k<srcG){
if(minDiff>minsum+pred[keyu].cost[0]){
canvia=false;
}
minsum+=pred[keyu].costu[vehicle];
keyu= pred[keyu].pred[vehicle];
++k;
}
if(canvia){
vehicle=0;
}
}
}
if(vehicle==0){
if(vehicles[key][0] && pred[key].cost[0]>pred[key].cost[1]){
vehicle=1;
}
if(vehicles[key][1] && pred[key].cost[0]>pred[key].cost[2]){
vehicle=2;
}
if(vehicles[key][2] && pred[key].cost[0]>pred[key].cost[3]){
vehicle=3;
}
}
returnValue[0]=pred[key].pred[vehicle];
returnValue[1]=nodes[pred[key].pred[vehicle]];
returnValue[2]=vehicle;
return returnValue;
}
double *findPredecesorValues(int key,int vehicle){
/*
double rampPos[4];
double rampNeg[4];
double dist[4];*/
double * returnValue =(double *) malloc(sizeof(double) * 3);
returnValue[0]=pred[key].rampPos[vehicle];
returnValue[1]=pred[key].rampNeg[vehicle];
returnValue[2]=pred[key].dist[vehicle];
return returnValue;
}
int findKey(int nodeId){
int value=-1;
for(int i =0; i<numNode;++i){
if(nodes[i]==nodeId){
value=i;
}
}
return value;
}
/*
// Driver program to test above functions
int main()
{
// create the graph given in above fugure
int V = MAX;
struct Graph* graph = createGraph(V);
FILE * fp;
char * line = NULL;
char * idtoAll = NULL;
char * idtoParse = NULL;
char * idtoRest = NULL;
char * id=NULL;
int node1=0;
int node2=0;
int start=-172242;
int ends[6]={-47998,-83910,-53840,-136928,-74118,-103972};
//void addEdge(struct Graph* graph, int src, int dest, int weight)
int numNode=0;
size_t len = 0;
ssize_t read;
printf("FILE\n");
fp = fopen("./connexioGRAPH2.osm", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1) {
if(strstr(line,"<node")!=NULL){
idtoAll=strstr(line,"id='");
idtoParse=strstr(idtoAll,"-");
idtoRest=strstr(idtoParse,"' ");
idtoRest[0]='\0';
nodes[numNode]=atoi(idtoParse);
++numNode;
//<node id='-122474' action='modify' lat='41.55136910003' lon='1.78672119968' >
}
if(strstr(line,"<way")!=NULL){
while(strstr(line,"<nd")==NULL){
read = getline(&line, &len, fp);
}
idtoAll=strstr(line,"ref='");
idtoParse=strstr(idtoAll,"-");
idtoRest=strstr(idtoParse,"' ");
idtoRest[0]='\0';
node1=atoi(idtoParse);
read = getline(&line, &len, fp);
while(strstr(line,"<nd")==NULL){
read = getline(&line, &len, fp);
}
idtoAll=strstr(line,"ref='");
idtoParse=strstr(idtoAll,"-");
idtoRest=strstr(idtoParse,"' ");
idtoRest[0]='\0';
node2=atoi(idtoParse);
for(int i =0; i<numNode;++i){
if(nodes[i]==node1){
node1=i;
}
if(nodes[i]==node2){
node2=i;
}
}
read = getline(&line, &len, fp);
while(strstr(line,"k='Distance_From_")==NULL){
read = getline(&line, &len, fp);
}
idtoAll=strstr(line,"v='");
memmove(idtoAll, idtoAll+3, strlen(idtoAll));
idtoRest=strstr(idtoAll,"' ");
idtoRest[0]='\0';
//if(atof(idtoAll)!=0.0)
//G[node1][node2] = G[node2][node1] = atof(idtoAll);
addEdge(graph, node1, node2, atof(idtoAll));
}
}
printf("file readed\n");
for(int i =0; i<numNode;++i){
if(nodes[i]==start){
final[i]=false;
start=i;
}
else if(nodes[i]==ends[0]){
final[i]=true;
ends[0]=i;
}
else if(nodes[i]==ends[1]){
final[i]=true;
ends[1]=i;
}
else if(nodes[i]==ends[2]){
final[i]=true;
ends[2]=i;
}
else if(nodes[i]==ends[3]){
final[i]=true;
ends[3]=i;
}
else if(nodes[i]==ends[4]){
final[i]=true;
ends[4]=i;
}
else if(nodes[i]==ends[5]){
final[i]=true;
ends[5]=i;
}
else{
final[i]=false;
}
}
printf("dijkstra\n");
int numFinals = (sizeof(ends)/sizeof(*ends));
dijkstra(graph, start,numFinals);
printf("search\n");
for (int i=0; i<numFinals; ++i){
int end=ends[i];
int k=0;
int j=end;
printf("%d",nodes[end]);
do
{
++k;
j=pred[j].pred;
printf("<-%d",nodes[j]);
//route[k]=nodes[j];
//printf("G %f",G[ends[i]][start]);
}while(j!=start);
printf("<--%d\nnum Nodes %d;\n\n",nodes[start],k);
}
printf("end\n");
return 0;
}*/ | [
"francescdepuig@gmail.com"
] | francescdepuig@gmail.com |
e5795ebc94cba7e4b953cbb7e7b1a06afda48788 | ced1f7a18c7ef746218ca2c521db0c043ae1df59 | /tp2/moos-ivp-extend/src/uJoystick/Joystick.h | 280a6df11729bd0ad4d0e8d6aceafce748f69f6c | [] | no_license | neelakanthuk/td-moos-ivp | 0227d81050f78f4d0c1288f8fe2227daba60f071 | 2f2df31898e26ccf6b47b27a3068e9c3cfe734e8 | refs/heads/master | 2021-05-31T08:21:02.998952 | 2016-04-21T16:40:57 | 2016-04-21T16:40:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 991 | h | /************************************************************/
/* NAME: Vincent Drevelle, Simon Rohou */
/* ORGN: MIT */
/* FILE: Joystick.h */
/* DATE: December 29th, 1963 */
/************************************************************/
#ifndef Joystick_HEADER
#define Joystick_HEADER
#include "MOOS/libMOOS/Thirdparty/AppCasting/AppCastingMOOSApp.h"
class Joystick : public AppCastingMOOSApp
{
public:
Joystick();
~Joystick() {};
protected: // Standard MOOSApp functions to overload
bool OnNewMail(MOOSMSG_LIST &NewMail);
bool Iterate();
bool OnConnectToServer();
bool OnStartUp();
protected: // Standard AppCastingMOOSApp function to overload
bool buildReport();
protected:
void registerVariables();
private: // Configuration variables
private: // State variables
};
#endif
| [
"simon.rohou@gmail.com"
] | simon.rohou@gmail.com |
1fdabc6b380f49a70951b941600880267530ecaf | c2bc339753e08d2249c7eea412c3d6739048a76f | /FractalX/DxSupport/CartesianConversionType.h | 5b7fbf36d5dfbf533d14ba9d389985c2fa549ff5 | [] | no_license | sjr213/fractalx | 071680481de9f805d44543f33e48354fd9a61b76 | 4e7837bc9b8edf08b5eaf0eeb05fcbefc5ff7c98 | refs/heads/master | 2022-02-05T14:27:34.587816 | 2022-01-08T21:45:27 | 2022-01-08T21:45:27 | 144,908,700 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 434 | h | #pragma once
namespace DXF
{
enum class CartesianConversionType
{
StandardConversion = 1,
CartesianConvertAltX1 = 2,
CartesianConvertAltX2 = 3,
CartesianConvertAltY1 = 4,
CartesianConvertAltZ1 = 5
};
int CartesianConversionTypeToInt(CartesianConversionType fractalType);
CartesianConversionType CartesianConversionTypeFromInt(int type);
CString CartesianConversionTypeString(CartesianConversionType fractalType);
} | [
"sjrobles@yahoo.com"
] | sjrobles@yahoo.com |
301737d5d1e5b3fa37c5461f2be4f036e0200cfa | c6a624ffc2b6165d8e1f1c85a45ae1fa1c2baee4 | /OJ/刷题/小乌龟.cpp | 8b35d244dc3406ba8d898db4d7f3ea723a304b91 | [
"Unlicense"
] | permissive | JuChunChen/Algorithm | 41be8f8b9fd0543ef4d3e2297c3a0be81fc1433d | 8291a7ed498a0a9d763e7e50fffacf78db101a7e | refs/heads/master | 2023-04-02T21:25:08.227053 | 2021-04-10T07:57:55 | 2021-04-10T07:58:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 605 | cpp | #include<bits/stdc++.h>
using namespace std;
const int maxn = 1e3+5;
struct MyData{
int Pos,Val;
}Ac[maxn];
int Dp[maxn];
int main(){
int T,M,N,TPos,TVal;
while(~scanf("%d",&T)){
while(T--){
int R=0;
memset(Dp,0,sizeof(Dp));
memset(Ac,0,sizeof(Ac));
scanf("%d%d",&M,&N);
while(N--){
scanf("%d%d",&TPos,&TVal);
TPos*=2;
if(TPos<=M){
Ac[R++]=MyData{TPos,TVal};
}
}
for(int i=0;i<R;++i){
for(int j=M;j>=Ac[i].Pos;j--){
Dp[j]=max(Dp[j],Dp[j-Ac[i].Pos]+Ac[i].Val);
}
}
printf("%d\n",Dp[M]);
}
}
return 0;
}
| [
"simon@tomotoes.com"
] | simon@tomotoes.com |
34a57f67b5fd324b6d46f85af48c29c443c725b5 | b816f8eaa33e1e74b201e4e1c729cb2e54c82298 | /riegeli/bytes/pullable_reader.cc | 2de99c137802287fac6565dabe382219ea0ec4ab | [
"Apache-2.0"
] | permissive | google/riegeli | b47af9d6705ba7fc4d13d60f66f506e528fa0879 | c2f4362609db7c961c7de53387931f0901daf842 | refs/heads/master | 2023-08-17T16:54:54.694997 | 2023-08-11T13:33:07 | 2023-08-11T13:36:05 | 116,150,035 | 366 | 59 | Apache-2.0 | 2023-04-09T21:13:32 | 2018-01-03T15:05:56 | C++ | UTF-8 | C++ | false | false | 24,435 | cc | // Copyright 2019 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
//
// 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 "riegeli/bytes/pullable_reader.h"
#include <stddef.h>
#include <cstring>
#include <limits>
#include <memory>
#include <utility>
#include "absl/base/optimization.h"
#include "absl/functional/function_ref.h"
#include "absl/status/status.h"
#include "absl/strings/cord.h"
#include "absl/strings/cord_buffer.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "riegeli/base/arithmetic.h"
#include "riegeli/base/assert.h"
#include "riegeli/base/buffer.h"
#include "riegeli/base/buffering.h"
#include "riegeli/base/chain.h"
#include "riegeli/base/sized_shared_buffer.h"
#include "riegeli/base/types.h"
#include "riegeli/bytes/backward_writer.h"
#include "riegeli/bytes/reader.h"
#include "riegeli/bytes/writer.h"
namespace riegeli {
void PullableReader::Done() {
if (ABSL_PREDICT_FALSE(scratch_used()) && !ScratchEnds()) {
if (!SupportsRandomAccess()) {
// Seeking back is not feasible.
Reader::Done();
scratch_.reset();
return;
}
const Position new_pos = pos();
SyncScratch();
Seek(new_pos);
}
DoneBehindScratch();
Reader::Done();
scratch_.reset();
}
void PullableReader::DoneBehindScratch() {
RIEGELI_ASSERT(!scratch_used())
<< "Failed precondition of PullableReader::DoneBehindScratch(): "
"scratch used";
SyncBehindScratch(SyncType::kFromObject);
}
inline void PullableReader::SyncScratch() {
RIEGELI_ASSERT(scratch_used())
<< "Failed precondition of PullableReader::SyncScratch(): "
"scratch not used";
RIEGELI_ASSERT(start() == scratch_->buffer.data())
<< "Failed invariant of PullableReader: "
"scratch used but buffer pointers do not point to scratch";
RIEGELI_ASSERT_EQ(start_to_limit(), scratch_->buffer.size())
<< "Failed invariant of PullableReader: "
"scratch used but buffer pointers do not point to scratch";
ClearScratch();
}
inline void PullableReader::ClearScratch() {
scratch_->buffer.ClearAndShrink();
set_buffer(scratch_->original_start, scratch_->original_start_to_limit,
scratch_->original_start_to_cursor);
move_limit_pos(available());
}
inline bool PullableReader::ScratchEnds() {
RIEGELI_ASSERT(scratch_used())
<< "Failed precondition of PullableReader::ScratchEnds(): "
"scratch not used";
const size_t available_length = available();
if (scratch_->original_start_to_cursor >= available_length) {
SyncScratch();
set_cursor(cursor() - available_length);
return true;
}
return false;
}
bool PullableReader::PullSlow(size_t min_length, size_t recommended_length) {
RIEGELI_ASSERT_LT(available(), min_length)
<< "Failed precondition of Reader::PullSlow(): "
"enough data available, use Pull() instead";
if (ABSL_PREDICT_TRUE(min_length == 1)) {
if (ABSL_PREDICT_FALSE(scratch_used())) {
SyncScratch();
if (available() > 0) return true;
}
return PullBehindScratch(recommended_length);
}
if (scratch_used() && ScratchEnds() && available() >= min_length) return true;
if (available() == 0) {
RIEGELI_ASSERT(!scratch_used())
<< "Scratch should have ended but is still used";
if (ABSL_PREDICT_FALSE(!PullBehindScratch(recommended_length))) {
return false;
}
if (available() >= min_length) return true;
}
size_t remaining_min_length = min_length;
recommended_length = UnsignedMax(min_length, recommended_length);
std::unique_ptr<Scratch> new_scratch;
if (ABSL_PREDICT_FALSE(scratch_ == nullptr)) {
new_scratch = std::make_unique<Scratch>();
} else {
new_scratch = std::move(scratch_);
if (!new_scratch->buffer.empty()) {
// Scratch is used but it does not have enough data after the cursor.
new_scratch->buffer.RemovePrefix(start_to_cursor());
new_scratch->buffer.Shrink(recommended_length);
remaining_min_length -= new_scratch->buffer.size();
recommended_length -= new_scratch->buffer.size();
set_buffer(new_scratch->original_start,
new_scratch->original_start_to_limit,
new_scratch->original_start_to_cursor);
move_limit_pos(available());
}
}
const absl::Span<char> flat_buffer = new_scratch->buffer.AppendBuffer(
remaining_min_length, recommended_length);
char* dest = flat_buffer.data();
char* const min_limit = flat_buffer.data() + remaining_min_length;
char* const recommended_limit = flat_buffer.data() + recommended_length;
char* const max_limit = flat_buffer.data() + flat_buffer.size();
do {
const size_t length =
UnsignedMin(available(), PtrDistance(dest, max_limit));
// `std::memcpy(_, nullptr, 0)` is undefined.
if (length > 0) {
std::memcpy(dest, cursor(), length);
move_cursor(length);
dest += length;
if (dest >= min_limit) break;
}
if (ABSL_PREDICT_FALSE(scratch_used())) {
SyncScratch();
if (available() > 0) continue;
}
} while (PullBehindScratch(PtrDistance(dest, recommended_limit)));
new_scratch->buffer.RemoveSuffix(PtrDistance(dest, max_limit));
set_limit_pos(pos());
new_scratch->original_start = start();
new_scratch->original_start_to_limit = start_to_limit();
new_scratch->original_start_to_cursor = start_to_cursor();
scratch_ = std::move(new_scratch);
set_buffer(scratch_->buffer.data(), scratch_->buffer.size());
return available() >= min_length;
}
bool PullableReader::ReadBehindScratch(size_t length, char* dest) {
RIEGELI_ASSERT_LT(available(), length)
<< "Failed precondition of PullableReader::ReadBehindScratch(char*): "
"enough data available, use Read(char*) instead";
RIEGELI_ASSERT(!scratch_used())
<< "Failed precondition of PullableReader::ReadBehindScratch(char*): "
"scratch used";
do {
const size_t available_length = available();
// `std::memcpy(_, nullptr, 0)` is undefined.
if (available_length > 0) {
std::memcpy(dest, cursor(), available_length);
move_cursor(available_length);
dest += available_length;
length -= available_length;
}
if (ABSL_PREDICT_FALSE(!PullBehindScratch(length))) return false;
} while (length > available());
std::memcpy(dest, cursor(), length);
move_cursor(length);
return true;
}
bool PullableReader::ReadBehindScratch(size_t length, Chain& dest) {
RIEGELI_ASSERT_LT(UnsignedMin(available(), kMaxBytesToCopy), length)
<< "Failed precondition of PullableReader::ReadBehindScratch(Chain&): "
"enough data available, use Read(Chain&) instead";
RIEGELI_ASSERT_LE(length, std::numeric_limits<size_t>::max() - dest.size())
<< "Failed precondition of PullableReader::ReadBehindScratch(Chain&): "
"Chain size overflow";
RIEGELI_ASSERT(!scratch_used())
<< "Failed precondition of PullableReader::ReadBehindScratch(Chain&): "
"scratch used";
do {
const absl::Span<char> buffer = dest.AppendBuffer(1, length, length);
size_t length_read;
if (ABSL_PREDICT_FALSE(!Read(buffer.size(), buffer.data(), &length_read))) {
dest.RemoveSuffix(buffer.size() - length_read);
return false;
}
length -= length_read;
} while (length > 0);
return true;
}
// `absl::Cord::GetCustomAppendBuffer()` was introduced after Abseil LTS version
// 20220623. Use it if available, with fallback code if not.
namespace {
template <typename T, typename Enable = void>
struct HasGetCustomAppendBuffer : std::false_type {};
template <typename T>
struct HasGetCustomAppendBuffer<
T, absl::void_t<decltype(std::declval<T&>().GetCustomAppendBuffer(
std::declval<size_t>(), std::declval<size_t>(),
std::declval<size_t>()))>> : std::true_type {};
template <
typename DependentCord = absl::Cord,
std::enable_if_t<HasGetCustomAppendBuffer<DependentCord>::value, int> = 0>
inline bool ReadBehindScratchToCord(Reader& src, size_t length,
DependentCord& dest) {
static constexpr size_t kCordBufferBlockSize =
UnsignedMin(kDefaultMaxBlockSize, absl::CordBuffer::kCustomLimit);
absl::CordBuffer buffer =
dest.GetCustomAppendBuffer(kCordBufferBlockSize, length, 1);
absl::Span<char> span = buffer.available_up_to(length);
if (buffer.capacity() < kDefaultMinBlockSize && length > span.size()) {
absl::CordBuffer new_buffer = absl::CordBuffer::CreateWithCustomLimit(
kCordBufferBlockSize, buffer.length() + length);
std::memcpy(new_buffer.data(), buffer.data(), buffer.length());
new_buffer.SetLength(buffer.length());
buffer = std::move(new_buffer);
span = buffer.available_up_to(length);
}
for (;;) {
size_t length_read;
const bool read_ok = src.Read(span.size(), span.data(), &length_read);
buffer.IncreaseLengthBy(length_read);
dest.Append(std::move(buffer));
if (ABSL_PREDICT_FALSE(!read_ok)) return false;
length -= length_read;
if (length == 0) return true;
buffer =
absl::CordBuffer::CreateWithCustomLimit(kCordBufferBlockSize, length);
span = buffer.available_up_to(length);
}
}
template <
typename DependentCord = absl::Cord,
std::enable_if_t<!HasGetCustomAppendBuffer<DependentCord>::value, int> = 0>
inline bool ReadBehindScratchToCord(Reader& src, size_t length,
DependentCord& dest) {
Buffer buffer;
do {
buffer.Reset(UnsignedMin(length, kDefaultMaxBlockSize));
const size_t length_to_read = UnsignedMin(length, buffer.capacity());
size_t length_read;
const bool read_ok = src.Read(length_to_read, buffer.data(), &length_read);
const char* const data = buffer.data();
std::move(buffer).AppendSubstrTo(data, length_read, dest);
if (ABSL_PREDICT_FALSE(!read_ok)) return false;
length -= length_read;
} while (length > 0);
return true;
}
} // namespace
bool PullableReader::ReadBehindScratch(size_t length, absl::Cord& dest) {
RIEGELI_ASSERT_LT(UnsignedMin(available(), kMaxBytesToCopy), length)
<< "Failed precondition of PullableReader::ReadBehindScratch(Cord&): "
"enough data available, use Read(Cord&) instead";
RIEGELI_ASSERT_LE(length, std::numeric_limits<size_t>::max() - dest.size())
<< "Failed precondition of PullableReader::ReadBehindScratch(Cord&): "
"Cord size overflow";
RIEGELI_ASSERT(!scratch_used())
<< "Failed precondition of PullableReader::ReadBehindScratch(Cord&): "
"scratch used";
return ReadBehindScratchToCord(*this, length, dest);
}
bool PullableReader::CopyBehindScratch(Position length, Writer& dest) {
RIEGELI_ASSERT_LT(UnsignedMin(available(), kMaxBytesToCopy), length)
<< "Failed precondition of PullableReader::CopyBehindScratch(Writer&): "
"enough data available, use Copy(Writer&) instead";
RIEGELI_ASSERT(!scratch_used())
<< "Failed precondition of PullableReader::CopyBehindScratch(Writer&): "
"scratch used";
while (length > available()) {
const absl::string_view data(cursor(), available());
move_cursor(data.size());
if (ABSL_PREDICT_FALSE(!dest.Write(data))) return false;
length -= data.size();
if (ABSL_PREDICT_FALSE(!PullBehindScratch(length))) return false;
}
const absl::string_view data(cursor(), IntCast<size_t>(length));
move_cursor(IntCast<size_t>(length));
return dest.Write(data);
}
bool PullableReader::CopyBehindScratch(size_t length, BackwardWriter& dest) {
RIEGELI_ASSERT_LT(UnsignedMin(available(), kMaxBytesToCopy), length)
<< "Failed precondition of "
"PullableReader::CopyBehindScratch(BackwardWriter&): "
"enough data available, use Copy(BackwardWriter&) instead";
RIEGELI_ASSERT(!scratch_used())
<< "Failed precondition of "
"PullableReader::CopyBehindScratch(BackwardWriter&): "
"scratch used";
if (length <= available()) {
const absl::string_view data(cursor(), length);
move_cursor(length);
return dest.Write(data);
}
if (length <= kMaxBytesToCopy) {
if (ABSL_PREDICT_FALSE(!dest.Push(length))) return false;
dest.move_cursor(length);
if (ABSL_PREDICT_FALSE(!ReadBehindScratch(length, dest.cursor()))) {
dest.set_cursor(dest.cursor() + length);
return false;
}
return true;
}
Chain data;
if (ABSL_PREDICT_FALSE(!ReadBehindScratch(length, data))) return false;
return dest.Write(std::move(data));
}
bool PullableReader::ReadSomeDirectlyBehindScratch(
size_t max_length, absl::FunctionRef<char*(size_t&)> get_dest) {
RIEGELI_ASSERT_GT(max_length, 0u)
<< "Failed precondition of "
"PullableReader::ReadSomeDirectlyBehindScratch(): "
"nothing to read, use ReadSomeDirectly() instead";
RIEGELI_ASSERT_EQ(available(), 0u)
<< "Failed precondition of "
"PullableReader::ReadSomeDirectlyBehindScratch(): "
"some data available, use ReadSomeDirectly() instead";
RIEGELI_ASSERT(!scratch_used())
<< "Failed precondition of "
"PullableReader::ReadSomeDirectlyBehindScratch(): "
"scratch used";
PullBehindScratch(max_length);
return false;
}
void PullableReader::ReadHintBehindScratch(size_t min_length,
size_t recommended_length) {
RIEGELI_ASSERT_LT(available(), min_length)
<< "Failed precondition of PullableReader::ReadHintBehindScratch(): "
"enough data available, use ReadHint() instead";
RIEGELI_ASSERT(!scratch_used())
<< "Failed precondition of PullableReader::ReadHintBehindScratch(): "
"scratch used";
}
bool PullableReader::SyncBehindScratch(SyncType sync_type) {
RIEGELI_ASSERT(!scratch_used())
<< "Failed precondition of PullableReader::SyncBehindScratch(): "
"scratch used";
return ok();
}
bool PullableReader::SeekBehindScratch(Position new_pos) {
RIEGELI_ASSERT(new_pos < start_pos() || new_pos > limit_pos())
<< "Failed precondition of PullableReader::SeekBehindScratch(): "
"position in the buffer, use Seek() instead";
RIEGELI_ASSERT(!scratch_used())
<< "Failed precondition of PullableReader::SeekBehindScratch(): "
"scratch used";
if (ABSL_PREDICT_FALSE(new_pos <= limit_pos())) {
return Fail(
absl::UnimplementedError("Reader::Seek() backwards not supported"));
}
// Seeking forwards.
do {
move_cursor(available());
if (ABSL_PREDICT_FALSE(!PullBehindScratch(0))) return false;
} while (new_pos > limit_pos());
const Position available_length = limit_pos() - new_pos;
RIEGELI_ASSERT_LE(available_length, start_to_limit())
<< "PullableReader::PullBehindScratch() skipped some data";
set_cursor(limit() - available_length);
return true;
}
bool PullableReader::ReadSlow(size_t length, char* dest) {
RIEGELI_ASSERT_LT(available(), length)
<< "Failed precondition of Reader::ReadSlow(char*): "
"enough data available, use Read(char*) instead";
if (ABSL_PREDICT_FALSE(scratch_used())) {
if (!ScratchEnds()) {
const size_t length_to_read = available();
std::memcpy(dest, cursor(), length_to_read);
dest += length_to_read;
length -= length_to_read;
move_cursor(length_to_read);
SyncScratch();
}
if (available() >= length) {
// `std::memcpy(nullptr, _, 0)` and `std::memcpy(_, nullptr, 0)` are
// undefined.
if (ABSL_PREDICT_TRUE(length > 0)) {
std::memcpy(dest, cursor(), length);
move_cursor(length);
}
return true;
}
}
return ReadBehindScratch(length, dest);
}
bool PullableReader::ReadSlow(size_t length, Chain& dest) {
RIEGELI_ASSERT_LT(UnsignedMin(available(), kMaxBytesToCopy), length)
<< "Failed precondition of Reader::ReadSlow(Chain&): "
"enough data available, use Read(Chain&) instead";
RIEGELI_ASSERT_LE(length, std::numeric_limits<size_t>::max() - dest.size())
<< "Failed precondition of Reader::ReadSlow(Chain&): "
"Chain size overflow";
if (ABSL_PREDICT_FALSE(scratch_used())) {
if (!ScratchEnds()) {
if (available() >= length) {
dest.Append(scratch_->buffer.Substr(cursor(), length));
move_cursor(length);
return true;
}
length -= available();
dest.Append(std::move(scratch_->buffer).Substr(cursor(), available()));
ClearScratch();
}
if (available() >= length && length <= kMaxBytesToCopy) {
dest.Append(absl::string_view(cursor(), length));
move_cursor(length);
return true;
}
}
return ReadBehindScratch(length, dest);
}
bool PullableReader::ReadSlow(size_t length, absl::Cord& dest) {
RIEGELI_ASSERT_LT(UnsignedMin(available(), kMaxBytesToCopy), length)
<< "Failed precondition of Reader::ReadSlow(Cord&): "
"enough data available, use Read(Cord&) instead";
RIEGELI_ASSERT_LE(length, std::numeric_limits<size_t>::max() - dest.size())
<< "Failed precondition of Reader::ReadSlow(Cord&): "
"Cord size overflow";
if (ABSL_PREDICT_FALSE(scratch_used())) {
if (!ScratchEnds()) {
if (available() >= length) {
scratch_->buffer.Substr(cursor(), length).AppendTo(dest);
move_cursor(length);
return true;
}
length -= available();
std::move(scratch_->buffer).Substr(cursor(), available()).AppendTo(dest);
ClearScratch();
}
if (available() >= length && length <= kMaxBytesToCopy) {
dest.Append(absl::string_view(cursor(), length));
move_cursor(length);
return true;
}
}
return ReadBehindScratch(length, dest);
}
bool PullableReader::CopySlow(Position length, Writer& dest) {
RIEGELI_ASSERT_LT(UnsignedMin(available(), kMaxBytesToCopy), length)
<< "Failed precondition of Reader::CopySlow(Writer&): "
"enough data available, use Copy(Writer&) instead";
if (ABSL_PREDICT_FALSE(scratch_used())) {
if (!ScratchEnds()) {
if (available() >= length) {
const bool write_ok =
length <= kMaxBytesToCopy || dest.PrefersCopying()
? dest.Write(absl::string_view(cursor(), length))
: dest.Write(Chain(scratch_->buffer.Substr(cursor(), length)));
move_cursor(length);
return write_ok;
}
length -= available();
const bool write_ok =
available() <= kMaxBytesToCopy || dest.PrefersCopying()
? dest.Write(absl::string_view(cursor(), available()))
: dest.Write(Chain(
std::move(scratch_->buffer).Substr(cursor(), available())));
ClearScratch();
if (ABSL_PREDICT_FALSE(!write_ok)) return false;
}
if (available() >= length && length <= kMaxBytesToCopy) {
const absl::string_view data(cursor(), IntCast<size_t>(length));
move_cursor(IntCast<size_t>(length));
return dest.Write(data);
}
}
return CopyBehindScratch(length, dest);
}
bool PullableReader::CopySlow(size_t length, BackwardWriter& dest) {
RIEGELI_ASSERT_LT(UnsignedMin(available(), kMaxBytesToCopy), length)
<< "Failed precondition of Reader::CopySlow(BackwardWriter&): "
"enough data available, use Copy(BackwardWriter&) instead";
if (ABSL_PREDICT_FALSE(scratch_used())) {
Chain from_scratch;
if (!ScratchEnds()) {
if (available() >= length) {
const bool write_ok =
length <= kMaxBytesToCopy || dest.PrefersCopying()
? dest.Write(absl::string_view(cursor(), length))
: dest.Write(Chain(scratch_->buffer.Substr(cursor(), length)));
move_cursor(length);
return write_ok;
}
length -= available();
from_scratch =
Chain(std::move(scratch_->buffer).Substr(cursor(), available()));
ClearScratch();
}
if (available() >= length && length <= kMaxBytesToCopy) {
const absl::string_view data(cursor(), length);
move_cursor(length);
if (ABSL_PREDICT_FALSE(!dest.Write(data))) return false;
} else {
if (ABSL_PREDICT_FALSE(!CopyBehindScratch(length, dest))) return false;
}
return dest.Write(std::move(from_scratch));
}
return CopyBehindScratch(length, dest);
}
bool PullableReader::ReadSomeDirectlySlow(
size_t max_length, absl::FunctionRef<char*(size_t&)> get_dest) {
RIEGELI_ASSERT_GT(max_length, 0u)
<< "Failed precondition of Reader::ReadSomeDirectlySlow(): "
"nothing to read, use ReadSomeDirectly() instead";
RIEGELI_ASSERT_EQ(available(), 0u)
<< "Failed precondition of Reader::ReadSomeDirectlySlow(): "
"some data available, use ReadSomeDirectly() instead";
if (ABSL_PREDICT_FALSE(scratch_used())) {
SyncScratch();
if (available() > 0) return false;
}
return ReadSomeDirectlyBehindScratch(max_length, get_dest);
}
void PullableReader::ReadHintSlow(size_t min_length,
size_t recommended_length) {
RIEGELI_ASSERT_LT(available(), min_length)
<< "Failed precondition of Reader::ReadHintSlow(): "
"enough data available, use ReadHint() instead";
if (ABSL_PREDICT_FALSE(scratch_used())) {
if (!ScratchEnds()) {
recommended_length = UnsignedMax(recommended_length, min_length);
min_length -= available();
recommended_length -= available();
BehindScratch behind_scratch(this);
if (available() < min_length) {
ReadHintBehindScratch(min_length, recommended_length);
}
return;
}
if (available() >= min_length) return;
}
ReadHintBehindScratch(min_length, recommended_length);
}
bool PullableReader::SyncImpl(SyncType sync_type) {
if (ABSL_PREDICT_FALSE(scratch_used()) && !ScratchEnds()) {
if (!SupportsRandomAccess()) {
// Seeking back is not feasible.
return ok();
}
const Position new_pos = pos();
SyncScratch();
Seek(new_pos);
}
return SyncBehindScratch(sync_type);
}
bool PullableReader::SeekSlow(Position new_pos) {
RIEGELI_ASSERT(new_pos < start_pos() || new_pos > limit_pos())
<< "Failed precondition of Reader::SeekSlow(): "
"position in the buffer, use Seek() instead";
if (ABSL_PREDICT_FALSE(scratch_used())) {
SyncScratch();
if (new_pos >= start_pos() && new_pos <= limit_pos()) {
set_cursor(limit() - (limit_pos() - new_pos));
return true;
}
}
return SeekBehindScratch(new_pos);
}
void PullableReader::BehindScratch::Enter() {
RIEGELI_ASSERT(context_->scratch_used())
<< "Failed precondition of PullableReader::BehindScratch::Enter(): "
"scratch not used";
RIEGELI_ASSERT(context_->start() == context_->scratch_->buffer.data())
<< "Failed invariant of PullableReader: "
"scratch used but buffer pointers do not point to scratch";
RIEGELI_ASSERT_EQ(context_->start_to_limit(),
context_->scratch_->buffer.size())
<< "Failed invariant of PullableReader: "
"scratch used but buffer pointers do not point to scratch";
scratch_ = std::move(context_->scratch_);
read_from_scratch_ = context_->start_to_cursor();
context_->set_buffer(scratch_->original_start,
scratch_->original_start_to_limit,
scratch_->original_start_to_cursor);
context_->move_limit_pos(context_->available());
}
void PullableReader::BehindScratch::Leave() {
RIEGELI_ASSERT(scratch_ != nullptr)
<< "Failed precondition of PullableReader::BehindScratch::Leave(): "
"scratch not used";
context_->set_limit_pos(context_->pos());
scratch_->original_start = context_->start();
scratch_->original_start_to_limit = context_->start_to_limit();
scratch_->original_start_to_cursor = context_->start_to_cursor();
context_->set_buffer(scratch_->buffer.data(), scratch_->buffer.size(),
read_from_scratch_);
context_->scratch_ = std::move(scratch_);
}
} // namespace riegeli
| [
"qrczak@google.com"
] | qrczak@google.com |
d2169ca1711967816639eb336faf61f7ca55a055 | ce82b0b72d5f9d642229b103bc7fc2af0da2b1a8 | /TPs/ParallelProgrammingTP/contrib/opencv-3.4.7/build/modules/core/mean.simd_declarations.hpp | 1b5154435603e2133503c83991beccb1afd462df | [
"BSD-3-Clause"
] | permissive | jgratien/ParallelProgrammingCourse | 74864c517e6d7d442b6186f164ca12aa0ec5b603 | 325b1968a95a1aa8531012484cabd2dcd3fd3d20 | refs/heads/master | 2023-01-28T14:43:58.138090 | 2023-01-16T21:37:08 | 2023-01-16T21:37:08 | 247,676,029 | 6 | 4 | null | 2021-11-07T18:06:54 | 2020-03-16T10:41:30 | C++ | UTF-8 | C++ | false | false | 339 | hpp | #define CV_CPU_SIMD_FILENAME "/work/irlin355_1/gratienj/ParallelProgrammingCourse/ParallelProgrammingTP/contrib/opencv-3.4.7/modules/core/src/mean.simd.hpp"
#define CV_CPU_DISPATCH_MODE AVX2
#include "opencv2/core/private/cv_cpu_include_simd_declarations.hpp"
#define CV_CPU_DISPATCH_MODES_ALL AVX2, BASELINE
#undef CV_CPU_SIMD_FILENAME
| [
"jean-marc.gratien@ifpen.fr"
] | jean-marc.gratien@ifpen.fr |
888ab0e802eb3a60feccd28791404308d118a215 | 1ea441985dd6982977eee204a4677b1c8bb64df1 | /GPIO_Programming__7-seg_/GPIO_Programming__7-seg_.ino | d054db283b386b8ad4a8cbcc72678ee3d0e4dc76 | [] | no_license | kaiwen98/cg1112practice | bec08edfe92cb685c6fc619d4aa9d17e3ba5dc40 | 82178f12db3927c5dd94632403c44113e50a3f79 | refs/heads/master | 2021-02-08T15:03:30.869587 | 2020-03-01T14:51:43 | 2020-03-01T14:51:43 | 244,163,834 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 839 | ino | #include "Arduino.h"
#define delayTime 1000
#define A (1)
#define B (1<<1)
#define C (1<<2)
#define D (1<<3)
#define LT (1<<4)
#define RBI (1<<5)
void setup()
{
DDRD = LT|A | B | C | D;
int count;
}
void loop()
{
int count = 0;
//PORTD |= LT | RBI;
while(PORTD < 10){
PORTD++;
delay(delayTime);
}
PORTD = 00000000;
/*if((PIND) == 0) {
PORTB |= LED13;
delay(delayTime);
PORTB &= ~LED13;
PORTB |= LED12;
delay(delayTime);
PORTB &= ~LED12;
PORTB |= LED11;
delay(delayTime);
PORTB &= ~LED11;
PORTB |= LED10;
delay(delayTime);
PORTB &= ~LED10;
}
if(SP6 & PIND) PORTB |= LED12;
else PORTB &= ~LED12;
if(SP5 & PIND) PORTB |= LED11;
else PORTB &= ~LED11;
if(SP4 & PIND) PORTB |= LED10;
else PORTB &= ~LED10;
*/
//PORTB = LED10 | LED11 | LED12 | LED13;
}
| [
"kaiwen98@gmail.com"
] | kaiwen98@gmail.com |
9fff07e4a25f5b8de8fcb61c2e82bc80e847bd18 | bd0dbe0d1efb0a72e5323a8d974ac94d5d6f6451 | /node_modules/opencv-build/opencv/build/modules/imgproc/accum.simd_declarations.hpp | 7528b561dd82679f74eb6acd727210818523881c | [
"BSD-3-Clause"
] | permissive | apppleblue/dissertation | d8260838539794b4f978ce56e8ddc51e01e72ff7 | 2eedab7f12a9c7e0de22e30bc5725351ed709536 | refs/heads/master | 2022-12-16T05:34:57.137565 | 2020-08-06T18:20:06 | 2020-08-06T18:20:06 | 232,809,733 | 0 | 0 | null | 2022-12-13T11:46:20 | 2020-01-09T12:59:19 | JavaScript | UTF-8 | C++ | false | false | 537 | hpp | #define CV_CPU_SIMD_FILENAME "C:/Users/Uzzy/Desktop/dist/node_modules/opencv-build/opencv/opencv/modules/imgproc/src/accum.simd.hpp"
#define CV_CPU_DISPATCH_MODE SSE4_1
#include "opencv2/core/private/cv_cpu_include_simd_declarations.hpp"
#define CV_CPU_DISPATCH_MODE AVX
#include "opencv2/core/private/cv_cpu_include_simd_declarations.hpp"
#define CV_CPU_DISPATCH_MODE AVX2
#include "opencv2/core/private/cv_cpu_include_simd_declarations.hpp"
#define CV_CPU_DISPATCH_MODES_ALL AVX2, AVX, SSE4_1, BASELINE
#undef CV_CPU_SIMD_FILENAME
| [
"47538583+apppleblue@users.noreply.github.com"
] | 47538583+apppleblue@users.noreply.github.com |
17e8ccc7cb2e01549000cc411f1ade55c78cbbab | 0c75a3674e3e8ed0eee9ab89f6ed1e1155543e3b | /C++/cosc2430.hw2/ArgumentManager.h | 381046db71011011ba7257ef8fe423207e88c8ec | [] | no_license | markchristian1337/Data-Structures---Algoritms | e283af5c3cc38b8747522afeb46f46115727904a | 76baae3afeb35327a13bfbe1d47743e43d8e9f68 | refs/heads/master | 2020-04-27T18:12:04.517125 | 2019-03-12T18:19:47 | 2019-03-12T18:19:47 | 174,558,763 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,874 | h | #include <map>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
// This is a class that can parse the commnad line arguments we use in COSC 2430 homework.
class ArgumentManager {
private:
map<string, string> m_argumentMap;
public:
ArgumentManager() { }
ArgumentManager(int argc, char *argv[], char delimiter=';');
ArgumentManager(string rawArguments, char delimiter=';');
void parse(int argc, char *argv[], char delimiter=';');
void parse(string rawArguments, char delimiter=';');
string get(string argumentName);
string toString();
friend ostream& operator << (ostream &out, ArgumentManager &am);
};
void ArgumentManager::parse(string rawArguments, char delimiter) {
stringstream currentArgumentName;
stringstream currentArgumentValue;
bool argumentNameFinished = false;
for (unsigned int i=0; i<=rawArguments.length(); i++) {
if (i == rawArguments.length() || rawArguments[i] == delimiter) {
if (currentArgumentName.str() != "") {
m_argumentMap[currentArgumentName.str()] = currentArgumentValue.str();
}
// reset
currentArgumentName.str("");
currentArgumentValue.str("");
argumentNameFinished = false;
}
else if (rawArguments[i] == '=') {
argumentNameFinished = true;
}
else {
if (argumentNameFinished) {
currentArgumentValue << rawArguments[i];
}
else {
// ignore any spaces in argument names.
if (rawArguments[i] == ' ')
continue;
currentArgumentName << rawArguments[i];
}
}
}
}
void ArgumentManager::parse(int argc, char *argv[], char delimiter) {
if (argc > 1) {
for (int i=1; i<argc; i++) {
parse(argv[i], delimiter);
}
}
}
ArgumentManager::ArgumentManager(int argc, char *argv[], char delimiter) {
parse(argc, argv, delimiter);
}
ArgumentManager::ArgumentManager(string rawArguments, char delimiter) {
parse(rawArguments, delimiter);
}
string ArgumentManager::get(string argumentName) {
map<string, string>::iterator iter = m_argumentMap.find(argumentName);
//If the argument is not found, return a blank string.
if (iter == m_argumentMap.end()) {
return "";
}
else {
return iter->second;
}
}
string ArgumentManager::toString() {
stringstream ss;
for (map<string, string>::iterator iter = m_argumentMap.begin(); iter != m_argumentMap.end(); iter++) {
ss << "Argument name: " << iter->first << endl;
ss << "Argument value: " << iter->second << endl;
}
return ss.str();
}
ostream& operator << (ostream &out, ArgumentManager &am) {
out << am.toString();
return out;
}
| [
"markchristian1337@gmail.com"
] | markchristian1337@gmail.com |
2233523368a28d0ba964b41fb58ff227e26fe4e2 | 7bb34b9837b6304ceac6ab45ce482b570526ed3c | /external/webkit/Tools/TestWebKitAPI/Tests/WebKit2/win/ResizeViewWhileHidden.cpp | 9ebfc2ca5e8e8343fa711b5e7adc88df40dc34ac | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.1-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft"
] | permissive | ghsecuritylab/android_platform_sony_nicki | 7533bca5c13d32a8d2a42696344cc10249bd2fd8 | 526381be7808e5202d7865aa10303cb5d249388a | refs/heads/master | 2021-02-28T20:27:31.390188 | 2013-10-15T07:57:51 | 2013-10-15T07:57:51 | 245,730,217 | 0 | 0 | Apache-2.0 | 2020-03-08T00:59:27 | 2020-03-08T00:59:26 | null | UTF-8 | C++ | false | false | 4,537 | cpp | /*
* Copyright (C) 2011 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. AND ITS 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 APPLE INC. OR ITS 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 "Test.h"
#include "PlatformUtilities.h"
#include "PlatformWebView.h"
#include <WebKit2/WKRetainPtr.h>
namespace TestWebKitAPI {
static bool didFinishLoad;
static void didFinishLoadForFrame(WKPageRef, WKFrameRef, WKTypeRef, const void*)
{
didFinishLoad = true;
}
static void setPageLoaderClient(WKPageRef page)
{
WKPageLoaderClient loaderClient;
memset(&loaderClient, 0, sizeof(loaderClient));
loaderClient.version = 0;
loaderClient.didFinishLoadForFrame = didFinishLoadForFrame;
WKPageSetPageLoaderClient(page, &loaderClient);
}
static void flushMessages(WKPageRef page)
{
// In order to ensure all pending messages have been handled by the UI and web processes, we
// load a URL and wait for the load to finish.
setPageLoaderClient(page);
WKPageLoadURL(page, adoptWK(Util::createURLForResource("simple", "html")).get());
Util::run(&didFinishLoad);
didFinishLoad = false;
WKPageSetPageLoaderClient(page, 0);
}
static bool timerFired;
static void CALLBACK timerCallback(HWND hwnd, UINT, UINT_PTR timerID, DWORD)
{
::KillTimer(hwnd, timerID);
timerFired = true;
}
static void runForDuration(double seconds)
{
::SetTimer(0, 0, seconds * 1000, timerCallback);
Util::run(&timerFired);
timerFired = false;
}
static void waitForBackingStoreUpdate(WKPageRef page)
{
// Wait for the web process to handle the changes we just made, to perform a display (which
// happens on a timer), and to tell the UI process about the display (which updates the backing
// store).
// FIXME: It would be much less fragile (and maybe faster) to have an explicit way to wait
// until the backing store is updated.
runForDuration(0.5);
flushMessages(page);
}
TEST(WebKit2, ResizeViewWhileHidden)
{
WKRetainPtr<WKContextRef> context(AdoptWK, WKContextCreate());
PlatformWebView webView(context.get());
HWND window = WKViewGetWindow(webView.platformView());
RECT originalRect;
::GetClientRect(window, &originalRect);
RECT newRect = originalRect;
::InflateRect(&newRect, 1, 1);
// Show the WKView and resize it so that the WKView's backing store will be created. Ideally
// we'd have some more explicit way of forcing the backing store to be created.
::ShowWindow(window, SW_SHOW);
webView.resizeTo(newRect.right - newRect.left, newRect.bottom - newRect.top);
waitForBackingStoreUpdate(webView.page());
// Resize the window while hidden and show it again so that it will update its backing store at
// the new size.
::ShowWindow(window, SW_HIDE);
webView.resizeTo(originalRect.right - originalRect.left, originalRect.bottom - originalRect.top);
::ShowWindow(window, SW_SHOW);
// Force the WKView to paint to try to trigger <http://webkit.org/b/54142>.
::SendMessage(window, WM_PAINT, 0, 0);
// In Debug builds without the fix for <http://webkit.org/b/54141>, the web process will assert
// at this point.
// FIXME: It would be good to have a way to check that our behavior is correct in Release
// builds, too!
waitForBackingStoreUpdate(webView.page());
}
} // namespace TestWebKitAPI
| [
"gahlotpercy@gmail.com"
] | gahlotpercy@gmail.com |
6aabee8cf535fae8976e6e449b38a255bf158082 | be4952850ad6a8b0abe50de671c495c6add9fae7 | /codeforce/CF_893A.cpp | 72101cc09cd21f5752157a2a3f0cd6f2a79bfb09 | [] | no_license | ss5ssmi/OJ | 296cb936ecf7ef292e91f24178c9c08bd2d241b5 | 267184cef5f1bc1f222950a71fe705bbc5f0bb3e | refs/heads/master | 2022-10-29T18:15:14.290028 | 2022-10-12T04:42:47 | 2022-10-12T04:42:47 | 103,818,651 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 305 | cpp | #include<bits/stdc++.h>
using namespace std;
int main() {
int n,a[100],p1=1,p2=2,w=3;
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
for(int i=0;i<n;i++){
if(a[i]==p1){
swap(p2,w);
}else if(a[i]==p2){
swap(p1,w);
}else{
printf("NO\n");
return 0;
}
}
printf("YES\n");
return 0;
}
| [
"imss5ss@outlook.com"
] | imss5ss@outlook.com |
bfd583a6d1b96dda43a132f1f6e7a74cfe3474a3 | 98ab7fbbd73f0115f6a939f40ccff9273396f31b | /tinyBrowser/WHedit.h | 521dad3205e19ccda4fd5fbaa18871b2b3abfc57 | [] | no_license | hua3505/tinyBrowser | ec78b365fe6402fdbd79224d694e477b27684786 | 130ee2238e6e00e844728ae4b34d3ec4a7e1e099 | refs/heads/master | 2016-09-10T10:52:30.038527 | 2016-02-23T06:56:52 | 2016-02-23T06:56:52 | 18,792,361 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 784 | h | #pragma once
#include <bkwin/bkimage.h>
#include <bkwin/bkskin.h>
class CWHEdit
: public CWindowImpl<CWHEdit, CEdit>
{
public:
CWHEdit()
: m_crBg(CLR_DEFAULT),mBrush(NULL)
{
}
~CWHEdit()
{
if(mBrush != NULL)
{
DeleteObject(mBrush);
mBrush = NULL;
}
}
void SetBkColor(COLORREF crBg)
{
m_crBg = crBg;
Invalidate(TRUE);
}
protected:
COLORREF m_crBg;
HBRUSH mBrush;
HBRUSH OnReflectedCtlColor(CDCHandle dc, HWND /*hWnd*/)
{
if (CLR_DEFAULT == m_crBg)
{
SetMsgHandled(FALSE);
return NULL;
}
dc.SetBkColor(m_crBg);
if(mBrush == NULL)
mBrush = ::CreateSolidBrush(m_crBg);
return mBrush;
}
public:
BEGIN_MSG_MAP(CWHEdit)
MSG_OCM_CTLCOLORSTATIC(OnReflectedCtlColor)
MSG_OCM_CTLCOLOREDIT(OnReflectedCtlColor)
END_MSG_MAP()
}; | [
"959547664@qq.com"
] | 959547664@qq.com |
c22970bfbe93158f399445053e5a2c89139773e2 | 5a150bc779bda65e5fb01a1eefe2b289a0702728 | /duilib/Control/UITreeView.cpp | a6d5896dd427ef8ac1b2ce23b146eda65267a5d6 | [] | no_license | debuking1225/ppcw | a4ca74797e1db6b0fa08cba42b99b4d947b558ff | 39e736b8ba35e7af18b892bf23d33b5473aa8def | refs/heads/main | 2023-06-26T10:37:19.434004 | 2021-07-29T11:18:48 | 2021-07-29T11:18:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 42,075 | cpp | #include "../StdAfx.h"
#include "UITreeView.h"
#pragma warning( disable: 4251 )
namespace DuiLib
{
IMPLEMENT_DUICONTROL(CTreeNodeUI)
//************************************
// 函数名称: CTreeNodeUI
// 返回类型:
// 参数信息: CTreeNodeUI * _ParentNode
// 函数说明:
//************************************
CTreeNodeUI::CTreeNodeUI( CTreeNodeUI* _ParentNode /*= NULL*/ )
{
m_dwItemTextColor = 0x00000000;
m_dwItemHotTextColor = 0;
m_dwSelItemTextColor = 0;
m_dwSelItemHotTextColor = 0;
pTreeView = NULL;
m_iTreeLavel = 0;
m_bIsVisable = TRUE;
m_bIsCheckBox = FALSE;
pParentTreeNode = NULL;
pHoriz = new CHorizontalLayoutUI();
pFolderButton = new CCheckBoxUI();
pDottedLine = new CLabelUI();
pCheckBox = new CCheckBoxUI();
pItemButton = new COptionUI();
this->SetFixedHeight(18);
this->SetFixedWidth(250);
pFolderButton->SetFixedWidth(GetFixedHeight());
pDottedLine->SetFixedWidth(2);
pCheckBox->SetFixedWidth(GetFixedHeight());
pItemButton->SetAttribute(_T("align"),_T("left"));
pDottedLine->SetVisible(FALSE);
pCheckBox->SetVisible(FALSE);
pItemButton->SetMouseEnabled(FALSE);
if(_ParentNode) {
if (_tcsicmp(_ParentNode->GetClass(), _T("TreeNodeUI")) != 0) return;
pDottedLine->SetVisible(_ParentNode->IsVisible());
pDottedLine->SetFixedWidth(_ParentNode->GetDottedLine()->GetFixedWidth()+16);
this->SetParentNode(_ParentNode);
}
pHoriz->SetChildVAlign(DT_VCENTER);
pHoriz->Add(pDottedLine);
pHoriz->Add(pFolderButton);
pHoriz->Add(pCheckBox);
pHoriz->Add(pItemButton);
Add(pHoriz);
}
//************************************
// 函数名称: ~CTreeNodeUI
// 返回类型:
// 参数信息: void
// 函数说明:
//************************************
CTreeNodeUI::~CTreeNodeUI( void )
{
}
//************************************
// 函数名称: GetClass
// 返回类型: LPCTSTR
// 函数说明:
//************************************
LPCTSTR CTreeNodeUI::GetClass() const
{
return _T("TreeNodeUI");
}
//************************************
// 函数名称: GetInterface
// 返回类型: LPVOID
// 参数信息: LPCTSTR pstrName
// 函数说明:
//************************************
LPVOID CTreeNodeUI::GetInterface( LPCTSTR pstrName )
{
if( _tcsicmp(pstrName, _T("TreeNode")) == 0 )
return static_cast<CTreeNodeUI*>(this);
return CListContainerElementUI::GetInterface(pstrName);
}
//************************************
// 函数名称: DoEvent
// 返回类型: void
// 参数信息: TEventUI & event
// 函数说明:
//************************************
void CTreeNodeUI::DoEvent( TEventUI& event )
{
if( !IsMouseEnabled() && event.Type > UIEVENT__MOUSEBEGIN && event.Type < UIEVENT__MOUSEEND ) {
if( m_pOwner != NULL ) m_pOwner->DoEvent(event);
else CContainerUI::DoEvent(event);
return;
}
CListContainerElementUI::DoEvent(event);
if (event.Type == UIEVENT_CONTEXTMENU)
{
if (IsContextMenuUsed()) {
m_pManager->SendNotify(this, DUI_MSGTYPE_MENU, event.wParam, event.lParam);
return;
}
}
if( event.Type == UIEVENT_DBLCLICK ) {
if( IsEnabled() ) {
m_pManager->SendNotify(this, DUI_MSGTYPE_TREEITEMDBCLICK);
Invalidate();
}
return;
}
if( event.Type == UIEVENT_MOUSEENTER ) {
if( IsEnabled()) {
if(m_bSelected && GetSelItemHotTextColor())
pItemButton->SetTextColor(GetSelItemHotTextColor());
else
pItemButton->SetTextColor(GetItemHotTextColor());
}
else
pItemButton->SetTextColor(pItemButton->GetDisabledTextColor());
return;
}
if( event.Type == UIEVENT_MOUSELEAVE ) {
if( IsEnabled()) {
if(m_bSelected && GetSelItemTextColor())
pItemButton->SetTextColor(GetSelItemTextColor());
else if(!m_bSelected)
pItemButton->SetTextColor(GetItemTextColor());
}
else
pItemButton->SetTextColor(pItemButton->GetDisabledTextColor());
return;
}
}
//************************************
// 函数名称: Invalidate
// 返回类型: void
// 函数说明:
//************************************
void CTreeNodeUI::Invalidate()
{
if( !IsVisible() )
return;
if( GetParent() ) {
CContainerUI* pParentContainer = static_cast<CContainerUI*>(GetParent()->GetInterface(_T("Container")));
if( pParentContainer ) {
RECT rc = pParentContainer->GetPos();
RECT rcInset = pParentContainer->GetInset();
rc.left += rcInset.left;
rc.top += rcInset.top;
rc.right -= rcInset.right;
rc.bottom -= rcInset.bottom;
CScrollBarUI* pVerticalScrollBar = pParentContainer->GetVerticalScrollBar();
if( pVerticalScrollBar && pVerticalScrollBar->IsVisible() ) rc.right -= pVerticalScrollBar->GetFixedWidth();
CScrollBarUI* pHorizontalScrollBar = pParentContainer->GetHorizontalScrollBar();
if( pHorizontalScrollBar && pHorizontalScrollBar->IsVisible() ) rc.bottom -= pHorizontalScrollBar->GetFixedHeight();
RECT invalidateRc = m_rcItem;
if( !::IntersectRect(&invalidateRc, &m_rcItem, &rc) )
return;
CControlUI* pParent = GetParent();
RECT rcTemp;
RECT rcParent;
while( pParent = pParent->GetParent() ) {
rcTemp = invalidateRc;
rcParent = pParent->GetPos();
if( !::IntersectRect(&invalidateRc, &rcTemp, &rcParent) )
return;
}
if( m_pManager != NULL ) m_pManager->Invalidate(invalidateRc);
}
else {
CContainerUI::Invalidate();
}
}
else {
CContainerUI::Invalidate();
}
}
//************************************
// 函数名称: Select
// 返回类型: bool
// 参数信息: bool bSelect
// 函数说明:
//************************************
bool CTreeNodeUI::Select( bool bSelect /*= true*/ )
{
bool nRet = CListContainerElementUI::Select(bSelect);
if(m_bSelected)
pItemButton->SetTextColor(GetSelItemTextColor());
else
pItemButton->SetTextColor(GetItemTextColor());
return nRet;
}
bool CTreeNodeUI::SelectMulti(bool bSelect)
{
bool nRet = CListContainerElementUI::SelectMulti(bSelect);
if(m_bSelected)
pItemButton->SetTextColor(GetSelItemTextColor());
else
pItemButton->SetTextColor(GetItemTextColor());
return nRet;
}
//************************************
// 函数名称: Add
// 返回类型: bool
// 参数信息: CControlUI * _pTreeNodeUI
// 函数说明: 通过节点对象添加节点
//************************************
bool CTreeNodeUI::Add( CControlUI* _pTreeNodeUI )
{
if (NULL != static_cast<CTreeNodeUI*>(_pTreeNodeUI->GetInterface(_T("TreeNode"))))
return AddChildNode((CTreeNodeUI*)_pTreeNodeUI);
return CListContainerElementUI::Add(_pTreeNodeUI);
}
//************************************
// 函数名称: AddAt
// 返回类型: bool
// 参数信息: CControlUI * pControl
// 参数信息: int iIndex 该参数仅针对当前节点下的兄弟索引,并非列表视图索引
// 函数说明:
//************************************
bool CTreeNodeUI::AddAt( CControlUI* pControl, int iIndex )
{
if(NULL == static_cast<CTreeNodeUI*>(pControl->GetInterface(_T("TreeNode"))))
return FALSE;
CTreeNodeUI* pIndexNode = static_cast<CTreeNodeUI*>(mTreeNodes.GetAt(iIndex));
if(!pIndexNode){
if(!mTreeNodes.Add(pControl))
return FALSE;
}
else if(pIndexNode && !mTreeNodes.InsertAt(iIndex,pControl))
return FALSE;
if(!pIndexNode && pTreeView && pTreeView->GetItemAt(GetTreeIndex()+1))
pIndexNode = static_cast<CTreeNodeUI*>(pTreeView->GetItemAt(GetTreeIndex()+1)->GetInterface(_T("TreeNode")));
pControl = CalLocation((CTreeNodeUI*)pControl);
if(pTreeView && pIndexNode)
return pTreeView->AddAt((CTreeNodeUI*)pControl,pIndexNode);
else
return pTreeView->Add((CTreeNodeUI*)pControl);
return TRUE;
}
//************************************
// 函数名称: Remove
// 返回类型: bool
// 参数信息: CControlUI * pControl
// 函数说明:
//************************************
bool CTreeNodeUI::Remove( CControlUI* pControl )
{
return RemoveAt((CTreeNodeUI*)pControl);
}
//************************************
// 函数名称: SetVisibleTag
// 返回类型: void
// 参数信息: bool _IsVisible
// 函数说明:
//************************************
void CTreeNodeUI::SetVisibleTag( bool _IsVisible )
{
m_bIsVisable = _IsVisible;
}
//************************************
// 函数名称: GetVisibleTag
// 返回类型: bool
// 函数说明:
//************************************
bool CTreeNodeUI::GetVisibleTag()
{
return m_bIsVisable;
}
//************************************
// 函数名称: SetItemText
// 返回类型: void
// 参数信息: LPCTSTR pstrValue
// 函数说明:
//************************************
void CTreeNodeUI::SetItemText( LPCTSTR pstrValue )
{
pItemButton->SetText(pstrValue);
}
//************************************
// 函数名称: GetItemText
// 返回类型: DuiLib::CDuiString
// 函数说明:
//************************************
CDuiString CTreeNodeUI::GetItemText()
{
return pItemButton->GetText();
}
//************************************
// 函数名称: CheckBoxSelected
// 返回类型: void
// 参数信息: bool _Selected
// 函数说明:
//************************************
void CTreeNodeUI::CheckBoxSelected( bool _Selected )
{
pCheckBox->Selected(_Selected);
}
//************************************
// 函数名称: IsCheckBoxSelected
// 返回类型: bool
// 函数说明:
//************************************
bool CTreeNodeUI::IsCheckBoxSelected() const
{
return pCheckBox->IsSelected();
}
//************************************
// 函数名称: IsHasChild
// 返回类型: bool
// 函数说明:
//************************************
bool CTreeNodeUI::IsHasChild() const
{
return !mTreeNodes.IsEmpty();
}
//************************************
// 函数名称: AddChildNode
// 返回类型: bool
// 参数信息: CTreeNodeUI * _pTreeNodeUI
// 函数说明:
//************************************
bool CTreeNodeUI::AddChildNode( CTreeNodeUI* _pTreeNodeUI )
{
if (!_pTreeNodeUI)
return FALSE;
if (NULL == static_cast<CTreeNodeUI*>(_pTreeNodeUI->GetInterface(_T("TreeNode"))))
return FALSE;
_pTreeNodeUI = CalLocation(_pTreeNodeUI);
bool nRet = TRUE;
if(pTreeView){
CTreeNodeUI* pNode = static_cast<CTreeNodeUI*>(mTreeNodes.GetAt(mTreeNodes.GetSize()-1));
if(!pNode || !pNode->GetLastNode())
nRet = pTreeView->AddAt(_pTreeNodeUI,GetTreeIndex()+1) >= 0;
else nRet = pTreeView->AddAt(_pTreeNodeUI,pNode->GetLastNode()->GetTreeIndex()+1) >= 0;
}
if(nRet)
mTreeNodes.Add(_pTreeNodeUI);
return nRet;
}
void CTreeNodeUI::RemoveAll() {
while (GetCountChild()) {
CTreeNodeUI* tmp = GetChildNode(0);
RemoveAt(tmp);
}
}
//************************************
// 函数名称: RemoveAt
// 返回类型: bool
// 参数信息: CTreeNodeUI * _pTreeNodeUI
// 函数说明:
//************************************
bool CTreeNodeUI::RemoveAt( CTreeNodeUI* _pTreeNodeUI )
{
int nIndex = mTreeNodes.Find(_pTreeNodeUI);
CTreeNodeUI* pNode = static_cast<CTreeNodeUI*>(mTreeNodes.GetAt(nIndex));
if(pNode && pNode == _pTreeNodeUI)
{
while(pNode->IsHasChild())
pNode->RemoveAt(static_cast<CTreeNodeUI*>(pNode->mTreeNodes.GetAt(0)));
mTreeNodes.Remove(nIndex);
if(pTreeView)
pTreeView->Remove(_pTreeNodeUI);
return TRUE;
}
return FALSE;
}
//************************************
// 函数名称: SetParentNode
// 返回类型: void
// 参数信息: CTreeNodeUI * _pParentTreeNode
// 函数说明:
//************************************
void CTreeNodeUI::SetParentNode( CTreeNodeUI* _pParentTreeNode )
{
pParentTreeNode = _pParentTreeNode;
}
//************************************
// 函数名称: GetParentNode
// 返回类型: CTreeNodeUI*
// 函数说明:
//************************************
CTreeNodeUI* CTreeNodeUI::GetParentNode()
{
return pParentTreeNode;
}
//************************************
// 函数名称: GetCountChild
// 返回类型: long
// 函数说明:
//************************************
long CTreeNodeUI::GetCountChild()
{
return mTreeNodes.GetSize();
}
//************************************
// 函数名称: SetTreeView
// 返回类型: void
// 参数信息: CTreeViewUI * _CTreeViewUI
// 函数说明:
//************************************
void CTreeNodeUI::SetTreeView( CTreeViewUI* _CTreeViewUI )
{
pTreeView = _CTreeViewUI;
}
//************************************
// 函数名称: GetTreeView
// 返回类型: CTreeViewUI*
// 函数说明:
//************************************
CTreeViewUI* CTreeNodeUI::GetTreeView()
{
return pTreeView;
}
//************************************
// 函数名称: SetAttribute
// 返回类型: void
// 参数信息: LPCTSTR pstrName
// 参数信息: LPCTSTR pstrValue
// 函数说明:
//************************************
void CTreeNodeUI::SetAttribute( LPCTSTR pstrName, LPCTSTR pstrValue )
{
if(_tcsicmp(pstrName, _T("text")) == 0 )
pItemButton->SetText(pstrValue);
else if(_tcsicmp(pstrName, _T("horizattr")) == 0 )
pHoriz->ApplyAttributeList(pstrValue);
else if(_tcsicmp(pstrName, _T("dotlineattr")) == 0 )
pDottedLine->ApplyAttributeList(pstrValue);
else if(_tcsicmp(pstrName, _T("folderattr")) == 0 )
pFolderButton->ApplyAttributeList(pstrValue);
else if(_tcsicmp(pstrName, _T("checkboxattr")) == 0 )
pCheckBox->ApplyAttributeList(pstrValue);
else if(_tcsicmp(pstrName, _T("itemattr")) == 0 )
pItemButton->ApplyAttributeList(pstrValue);
else if(_tcsicmp(pstrName, _T("itemtextcolor")) == 0 ){
if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
LPTSTR pstr = NULL;
DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
SetItemTextColor(clrColor);
}
else if(_tcsicmp(pstrName, _T("itemhottextcolor")) == 0 ){
if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
LPTSTR pstr = NULL;
DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
SetItemHotTextColor(clrColor);
}
else if(_tcsicmp(pstrName, _T("selitemtextcolor")) == 0 ){
if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
LPTSTR pstr = NULL;
DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
SetSelItemTextColor(clrColor);
}
else if(_tcsicmp(pstrName, _T("selitemhottextcolor")) == 0 ){
if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
LPTSTR pstr = NULL;
DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
SetSelItemHotTextColor(clrColor);
}
else CListContainerElementUI::SetAttribute(pstrName,pstrValue);
}
//************************************
// 函数名称: GetTreeNodes
// 返回类型: DuiLib::CStdPtrArray
// 函数说明:
//************************************
CStdPtrArray CTreeNodeUI::GetTreeNodes()
{
return mTreeNodes;
}
//************************************
// 函数名称: GetChildNode
// 返回类型: CTreeNodeUI*
// 参数信息: int _nIndex
// 函数说明:
//************************************
CTreeNodeUI* CTreeNodeUI::GetChildNode( int _nIndex )
{
return static_cast<CTreeNodeUI*>(mTreeNodes.GetAt(_nIndex));
}
//************************************
// 函数名称: SetVisibleFolderBtn
// 返回类型: void
// 参数信息: bool _IsVisibled
// 函数说明:
//************************************
void CTreeNodeUI::SetVisibleFolderBtn( bool _IsVisibled )
{
pFolderButton->SetVisible(_IsVisibled);
}
//************************************
// 函数名称: GetVisibleFolderBtn
// 返回类型: bool
// 函数说明:
//************************************
bool CTreeNodeUI::GetVisibleFolderBtn()
{
return pFolderButton->IsVisible();
}
//************************************
// 函数名称: SetVisibleCheckBtn
// 返回类型: void
// 参数信息: bool _IsVisibled
// 函数说明:
//************************************
void CTreeNodeUI::SetVisibleCheckBtn( bool _IsVisibled )
{
pCheckBox->SetVisible(_IsVisibled);
}
//************************************
// 函数名称: GetVisibleCheckBtn
// 返回类型: bool
// 函数说明:
//************************************
bool CTreeNodeUI::GetVisibleCheckBtn()
{
return pCheckBox->IsVisible();
}
//************************************
// 函数名称: GetNodeIndex
// 返回类型: int
// 函数说明: 取得全局树视图的索引
//************************************
int CTreeNodeUI::GetTreeIndex()
{
if(!pTreeView)
return -1;
for(int nIndex = 0;nIndex < pTreeView->GetCount();nIndex++){
if(this == pTreeView->GetItemAt(nIndex))
return nIndex;
}
return -1;
}
//************************************
// 函数名称: GetNodeIndex
// 返回类型: int
// 函数说明: 取得相对于兄弟节点的当前索引
//************************************
int CTreeNodeUI::GetNodeIndex()
{
if(!GetParentNode() && !pTreeView)
return -1;
if(!GetParentNode() && pTreeView)
return GetTreeIndex();
return GetParentNode()->GetTreeNodes().Find(this);
}
//************************************
// 函数名称: GetLastNode
// 返回类型: CTreeNodeUI*
// 函数说明:
//************************************
CTreeNodeUI* CTreeNodeUI::GetLastNode( )
{
if(!IsHasChild()) return this;
CTreeNodeUI* nRetNode = NULL;
for(int nIndex = 0;nIndex < GetTreeNodes().GetSize();nIndex++){
CTreeNodeUI* pNode = static_cast<CTreeNodeUI*>(GetTreeNodes().GetAt(nIndex));
if(!pNode) continue;
if(pNode->IsHasChild())
nRetNode = pNode->GetLastNode();
else
nRetNode = pNode;
}
return nRetNode;
}
//************************************
// 函数名称: CalLocation
// 返回类型: CTreeNodeUI*
// 参数信息: CTreeNodeUI * _pTreeNodeUI
// 函数说明: 缩进计算
//************************************
CTreeNodeUI* CTreeNodeUI::CalLocation( CTreeNodeUI* _pTreeNodeUI )
{
_pTreeNodeUI->GetDottedLine()->SetVisible(TRUE);
_pTreeNodeUI->GetDottedLine()->SetFixedWidth(pDottedLine->GetFixedWidth()+16);
_pTreeNodeUI->SetParentNode(this);
_pTreeNodeUI->GetItemButton()->SetGroup(pItemButton->GetGroup());
_pTreeNodeUI->SetTreeView(pTreeView);
return _pTreeNodeUI;
}
//************************************
// 函数名称: SetTextColor
// 返回类型: void
// 参数信息: DWORD _dwTextColor
// 函数说明:
//************************************
void CTreeNodeUI::SetItemTextColor( DWORD _dwItemTextColor )
{
m_dwItemTextColor = _dwItemTextColor;
pItemButton->SetTextColor(m_dwItemTextColor);
}
//************************************
// 函数名称: GetTextColor
// 返回类型: DWORD
// 函数说明:
//************************************
DWORD CTreeNodeUI::GetItemTextColor() const
{
return m_dwItemTextColor;
}
//************************************
// 函数名称: SetTextHotColor
// 返回类型: void
// 参数信息: DWORD _dwTextHotColor
// 函数说明:
//************************************
void CTreeNodeUI::SetItemHotTextColor( DWORD _dwItemHotTextColor )
{
m_dwItemHotTextColor = _dwItemHotTextColor;
Invalidate();
}
//************************************
// 函数名称: GetTextHotColor
// 返回类型: DWORD
// 函数说明:
//************************************
DWORD CTreeNodeUI::GetItemHotTextColor() const
{
return m_dwItemHotTextColor;
}
//************************************
// 函数名称: SetSelItemTextColor
// 返回类型: void
// 参数信息: DWORD _dwSelItemTextColor
// 函数说明:
//************************************
void CTreeNodeUI::SetSelItemTextColor( DWORD _dwSelItemTextColor )
{
m_dwSelItemTextColor = _dwSelItemTextColor;
Invalidate();
}
//************************************
// 函数名称: GetSelItemTextColor
// 返回类型: DWORD
// 函数说明:
//************************************
DWORD CTreeNodeUI::GetSelItemTextColor() const
{
return m_dwSelItemTextColor;
}
//************************************
// 函数名称: SetSelHotItemTextColor
// 返回类型: void
// 参数信息: DWORD _dwSelHotItemTextColor
// 函数说明:
//************************************
void CTreeNodeUI::SetSelItemHotTextColor( DWORD _dwSelHotItemTextColor )
{
m_dwSelItemHotTextColor = _dwSelHotItemTextColor;
Invalidate();
}
//************************************
// 函数名称: GetSelHotItemTextColor
// 返回类型: DWORD
// 函数说明:
//************************************
DWORD CTreeNodeUI::GetSelItemHotTextColor() const
{
return m_dwSelItemHotTextColor;
}
/*****************************************************************************/
/*****************************************************************************/
/*****************************************************************************/
IMPLEMENT_DUICONTROL(CTreeViewUI)
//************************************
// 函数名称: CTreeViewUI
// 返回类型:
// 参数信息: void
// 函数说明:
//************************************
CTreeViewUI::CTreeViewUI( void ) : m_bVisibleFolderBtn(TRUE),m_bVisibleCheckBtn(FALSE),m_uItemMinWidth(0)
{
this->GetHeader()->SetVisible(FALSE);
}
//************************************
// 函数名称: ~CTreeViewUI
// 返回类型:
// 参数信息: void
// 函数说明:
//************************************
CTreeViewUI::~CTreeViewUI( void )
{
}
//************************************
// 函数名称: GetClass
// 返回类型: LPCTSTR
// 函数说明:
//************************************
LPCTSTR CTreeViewUI::GetClass() const
{
return _T("TreeViewUI");
}
UINT CTreeViewUI::GetListType()
{
return LT_TREE;
}
//************************************
// 函数名称: GetInterface
// 返回类型: LPVOID
// 参数信息: LPCTSTR pstrName
// 函数说明:
//************************************
LPVOID CTreeViewUI::GetInterface( LPCTSTR pstrName )
{
if( _tcsicmp(pstrName, _T("TreeView")) == 0 ) return static_cast<CTreeViewUI*>(this);
return CListUI::GetInterface(pstrName);
}
//************************************
// 函数名称: Add
// 返回类型: bool
// 参数信息: CTreeNodeUI * pControl
// 函数说明:
//************************************
bool CTreeViewUI::Add( CTreeNodeUI* pControl )
{
if (!pControl) return false;
if (NULL == static_cast<CTreeNodeUI*>(pControl->GetInterface(_T("TreeNode")))) return false;
pControl->OnNotify += MakeDelegate(this,&CTreeViewUI::OnDBClickItem);
pControl->GetFolderButton()->OnNotify += MakeDelegate(this,&CTreeViewUI::OnFolderChanged);
pControl->GetCheckBox()->OnNotify += MakeDelegate(this,&CTreeViewUI::OnCheckBoxChanged);
pControl->SetVisibleFolderBtn(m_bVisibleFolderBtn);
pControl->SetVisibleCheckBtn(m_bVisibleCheckBtn);
if(m_uItemMinWidth > 0)
pControl->SetMinWidth(m_uItemMinWidth);
CListUI::Add(pControl);
if(pControl->GetCountChild() > 0) {
int nCount = pControl->GetCountChild();
for(int nIndex = 0;nIndex < nCount;nIndex++) {
CTreeNodeUI* pNode = pControl->GetChildNode(nIndex);
if(pNode) Add(pNode);
}
}
pControl->SetTreeView(this);
return true;
}
//************************************
// 函数名称: AddAt
// 返回类型: long
// 参数信息: CTreeNodeUI * pControl
// 参数信息: int iIndex
// 函数说明: 该方法不会将待插入的节点进行缩位处理,若打算插入的节点为非根节点,请使用AddAt(CTreeNodeUI* pControl,CTreeNodeUI* _IndexNode) 方法
//************************************
long CTreeViewUI::AddAt( CTreeNodeUI* pControl, int iIndex )
{
if (!pControl) return -1;
if (NULL == static_cast<CTreeNodeUI*>(pControl->GetInterface(_T("TreeNode")))) return -1;
pControl->OnNotify += MakeDelegate(this,&CTreeViewUI::OnDBClickItem);
pControl->GetFolderButton()->OnNotify += MakeDelegate(this,&CTreeViewUI::OnFolderChanged);
pControl->GetCheckBox()->OnNotify += MakeDelegate(this,&CTreeViewUI::OnCheckBoxChanged);
pControl->SetVisibleFolderBtn(m_bVisibleFolderBtn);
pControl->SetVisibleCheckBtn(m_bVisibleCheckBtn);
if(m_uItemMinWidth > 0) {
pControl->SetMinWidth(m_uItemMinWidth);
}
CListUI::AddAt(pControl, iIndex);
if(pControl->GetCountChild() > 0) {
int nCount = pControl->GetCountChild();
for(int nIndex = 0; nIndex < nCount; nIndex++) {
CTreeNodeUI* pNode = pControl->GetChildNode(nIndex);
if(pNode)
return AddAt(pNode,iIndex+1);
}
}
else {
return iIndex + 1;
}
return -1;
}
//************************************
// 函数名称: AddAt
// 返回类型: bool
// 参数信息: CTreeNodeUI * pControl
// 参数信息: CTreeNodeUI * _IndexNode
// 函数说明:
//************************************
bool CTreeViewUI::AddAt( CTreeNodeUI* pControl, CTreeNodeUI* _IndexNode )
{
if(!_IndexNode && !pControl)
return FALSE;
int nItemIndex = -1;
for(int nIndex = 0;nIndex < GetCount();nIndex++) {
if(_IndexNode == GetItemAt(nIndex)) {
nItemIndex = nIndex;
break;
}
}
if(nItemIndex == -1)
return FALSE;
return AddAt(pControl,nItemIndex) >= 0;
}
//************************************
// 函数名称: Remove
// 返回类型: bool
// 参数信息: CTreeNodeUI * pControl
// 函数说明: pControl 对象以及下的所有节点将被一并移除
//************************************
bool CTreeViewUI::Remove( CTreeNodeUI* pControl )
{
if(pControl->GetCountChild() > 0) {
int nCount = pControl->GetCountChild();
for(int nIndex = nCount - 1; nIndex >= 0; nIndex--) {
CTreeNodeUI* pNode = pControl->GetChildNode(nIndex);
if(pNode){
pControl->Remove(pNode);
}
}
}
CListUI::Remove(pControl);
return TRUE;
}
//************************************
// 函数名称: RemoveAt
// 返回类型: bool
// 参数信息: int iIndex
// 函数说明: iIndex 索引以及下的所有节点将被一并移除
//************************************
bool CTreeViewUI::RemoveAt( int iIndex )
{
CTreeNodeUI* pItem = (CTreeNodeUI*)GetItemAt(iIndex);
if(pItem->GetCountChild())
Remove(pItem);
return TRUE;
}
void CTreeViewUI::RemoveAll()
{
CListUI::RemoveAll();
}
//************************************
// 函数名称: Notify
// 返回类型: void
// 参数信息: TNotifyUI & msg
// 函数说明:
//************************************
void CTreeViewUI::Notify( TNotifyUI& msg )
{
}
//************************************
// 函数名称: OnCheckBoxChanged
// 返回类型: bool
// 参数信息: void * param
// 函数说明:
//************************************
bool CTreeViewUI::OnCheckBoxChanged( void* param )
{
TNotifyUI* pMsg = (TNotifyUI*)param;
if(pMsg->sType == DUI_MSGTYPE_SELECTCHANGED)
{
CCheckBoxUI* pCheckBox = (CCheckBoxUI*)pMsg->pSender;
CTreeNodeUI* pItem = (CTreeNodeUI*)pCheckBox->GetParent()->GetParent();
SetItemCheckBox(pCheckBox->GetCheck(),pItem);
return TRUE;
}
return TRUE;
}
//************************************
// 函数名称: OnFolderChanged
// 返回类型: bool
// 参数信息: void * param
// 函数说明:
//************************************
bool CTreeViewUI::OnFolderChanged( void* param )
{
TNotifyUI* pMsg = (TNotifyUI*)param;
if(pMsg->sType == DUI_MSGTYPE_SELECTCHANGED) {
CCheckBoxUI* pFolder = (CCheckBoxUI*)pMsg->pSender;
CTreeNodeUI* pItem = (CTreeNodeUI*)pFolder->GetParent()->GetParent();
pItem->SetVisibleTag(!pFolder->GetCheck());
SetItemExpand(!pFolder->GetCheck(),pItem);
return TRUE;
}
return TRUE;
}
//************************************
// 函数名称: OnDBClickItem
// 返回类型: bool
// 参数信息: void * param
// 函数说明:
//************************************
bool CTreeViewUI::OnDBClickItem( void* param )
{
TNotifyUI* pMsg = (TNotifyUI*)param;
if(_tcsicmp(pMsg->sType, DUI_MSGTYPE_TREEITEMDBCLICK) == 0) {
CTreeNodeUI* pItem = static_cast<CTreeNodeUI*>(pMsg->pSender);
CCheckBoxUI* pFolder = pItem->GetFolderButton();
pFolder->Selected(!pFolder->IsSelected());
pItem->SetVisibleTag(!pFolder->GetCheck());
SetItemExpand(!pFolder->GetCheck(),pItem);
return TRUE;
}
return FALSE;
}
//************************************
// 函数名称: SetItemCheckBox
// 返回类型: bool
// 参数信息: bool _Selected
// 参数信息: CTreeNodeUI * _TreeNode
// 函数说明:
//************************************
bool CTreeViewUI::SetItemCheckBox( bool _Selected,CTreeNodeUI* _TreeNode /*= NULL*/ )
{
if(_TreeNode) {
if(_TreeNode->GetCountChild() > 0) {
int nCount = _TreeNode->GetCountChild();
for(int nIndex = 0;nIndex < nCount;nIndex++) {
CTreeNodeUI* pItem = _TreeNode->GetChildNode(nIndex);
pItem->GetCheckBox()->Selected(_Selected);
if(pItem->GetCountChild())
SetItemCheckBox(_Selected,pItem);
}
}
return TRUE;
}
else {
int nIndex = 0;
int nCount = GetCount();
while(nIndex < nCount) {
CTreeNodeUI* pItem = (CTreeNodeUI*)GetItemAt(nIndex);
pItem->GetCheckBox()->Selected(_Selected);
if(pItem->GetCountChild())
SetItemCheckBox(_Selected,pItem);
nIndex++;
}
return TRUE;
}
return FALSE;
}
//************************************
// 函数名称: SetItemExpand
// 返回类型: void
// 参数信息: bool _Expanded
// 参数信息: CTreeNodeUI * _TreeNode
// 函数说明:
//************************************
void CTreeViewUI::SetItemExpand( bool _Expanded,CTreeNodeUI* _TreeNode /*= NULL*/ )
{
if(_TreeNode) {
if(_TreeNode->GetCountChild() > 0) {
int nCount = _TreeNode->GetCountChild();
for(int nIndex = 0;nIndex < nCount;nIndex++) {
CTreeNodeUI* pItem = _TreeNode->GetChildNode(nIndex);
pItem->SetVisible(_Expanded);
if(pItem->GetCountChild() && !pItem->GetFolderButton()->IsSelected()) {
SetItemExpand(_Expanded,pItem);
}
}
}
}
else {
int nIndex = 0;
int nCount = GetCount();
while(nIndex < nCount) {
CTreeNodeUI* pItem = (CTreeNodeUI*)GetItemAt(nIndex);
pItem->SetVisible(_Expanded);
if(pItem->GetCountChild() && !pItem->GetFolderButton()->IsSelected()) {
SetItemExpand(_Expanded,pItem);
}
nIndex++;
}
}
}
//************************************
// 函数名称: SetVisibleFolderBtn
// 返回类型: void
// 参数信息: bool _IsVisibled
// 函数说明:
//************************************
void CTreeViewUI::SetVisibleFolderBtn( bool _IsVisibled )
{
m_bVisibleFolderBtn = _IsVisibled;
int nCount = this->GetCount();
for(int nIndex = 0; nIndex < nCount; nIndex++) {
CTreeNodeUI* pItem = static_cast<CTreeNodeUI*>(this->GetItemAt(nIndex));
pItem->GetFolderButton()->SetVisible(m_bVisibleFolderBtn);
}
}
//************************************
// 函数名称: GetVisibleFolderBtn
// 返回类型: bool
// 函数说明:
//************************************
bool CTreeViewUI::GetVisibleFolderBtn()
{
return m_bVisibleFolderBtn;
}
//************************************
// 函数名称: SetVisibleCheckBtn
// 返回类型: void
// 参数信息: bool _IsVisibled
// 函数说明:
//************************************
void CTreeViewUI::SetVisibleCheckBtn( bool _IsVisibled )
{
m_bVisibleCheckBtn = _IsVisibled;
int nCount = this->GetCount();
for(int nIndex = 0; nIndex < nCount; nIndex++) {
CTreeNodeUI* pItem = static_cast<CTreeNodeUI*>(this->GetItemAt(nIndex));
pItem->GetCheckBox()->SetVisible(m_bVisibleCheckBtn);
}
}
//************************************
// 函数名称: GetVisibleCheckBtn
// 返回类型: bool
// 函数说明:
//************************************
bool CTreeViewUI::GetVisibleCheckBtn()
{
return m_bVisibleCheckBtn;
}
//************************************
// 函数名称: SetItemMinWidth
// 返回类型: void
// 参数信息: UINT _ItemMinWidth
// 函数说明:
//************************************
void CTreeViewUI::SetItemMinWidth( UINT _ItemMinWidth )
{
m_uItemMinWidth = _ItemMinWidth;
for(int nIndex = 0;nIndex < GetCount();nIndex++){
CTreeNodeUI* pTreeNode = static_cast<CTreeNodeUI*>(GetItemAt(nIndex));
if(pTreeNode) {
pTreeNode->SetMinWidth(GetItemMinWidth());
}
}
Invalidate();
}
//************************************
// 函数名称: GetItemMinWidth
// 返回类型: UINT
// 函数说明:
//************************************
UINT CTreeViewUI::GetItemMinWidth()
{
return m_uItemMinWidth;
}
//************************************
// 函数名称: SetItemTextColor
// 返回类型: void
// 参数信息: DWORD _dwItemTextColor
// 函数说明:
//************************************
void CTreeViewUI::SetItemTextColor( DWORD _dwItemTextColor )
{
for(int nIndex = 0;nIndex < GetCount();nIndex++){
CTreeNodeUI* pTreeNode = static_cast<CTreeNodeUI*>(GetItemAt(nIndex));
if(pTreeNode) {
pTreeNode->SetItemTextColor(_dwItemTextColor);
}
}
}
//************************************
// 函数名称: SetItemHotTextColor
// 返回类型: void
// 参数信息: DWORD _dwItemHotTextColor
// 函数说明:
//************************************
void CTreeViewUI::SetItemHotTextColor( DWORD _dwItemHotTextColor )
{
for(int nIndex = 0;nIndex < GetCount();nIndex++){
CTreeNodeUI* pTreeNode = static_cast<CTreeNodeUI*>(GetItemAt(nIndex));
if(pTreeNode) {
pTreeNode->SetItemHotTextColor(_dwItemHotTextColor);
}
}
}
//************************************
// 函数名称: SetSelItemTextColor
// 返回类型: void
// 参数信息: DWORD _dwSelItemTextColor
// 函数说明:
//************************************
void CTreeViewUI::SetSelItemTextColor( DWORD _dwSelItemTextColor )
{
for(int nIndex = 0;nIndex < GetCount();nIndex++){
CTreeNodeUI* pTreeNode = static_cast<CTreeNodeUI*>(GetItemAt(nIndex));
if(pTreeNode) {
pTreeNode->SetSelItemTextColor(_dwSelItemTextColor);
}
}
}
//************************************
// 函数名称: SetSelItemHotTextColor
// 返回类型: void
// 参数信息: DWORD _dwSelHotItemTextColor
// 函数说明:
//************************************
void CTreeViewUI::SetSelItemHotTextColor( DWORD _dwSelHotItemTextColor )
{
for(int nIndex = 0;nIndex < GetCount();nIndex++){
CTreeNodeUI* pTreeNode = static_cast<CTreeNodeUI*>(GetItemAt(nIndex));
if(pTreeNode) {
pTreeNode->SetSelItemHotTextColor(_dwSelHotItemTextColor);
}
}
}
//************************************
// 函数名称: SetAttribute
// 返回类型: void
// 参数信息: LPCTSTR pstrName
// 参数信息: LPCTSTR pstrValue
// 函数说明:
//************************************
void CTreeViewUI::SetAttribute( LPCTSTR pstrName, LPCTSTR pstrValue )
{
if(_tcsicmp(pstrName,_T("visiblefolderbtn")) == 0)
SetVisibleFolderBtn(_tcsicmp(pstrValue,_T("TRUE")) == 0);
else if(_tcsicmp(pstrName,_T("visiblecheckbtn")) == 0)
SetVisibleCheckBtn(_tcsicmp(pstrValue,_T("TRUE")) == 0);
else if(_tcsicmp(pstrName,_T("itemminwidth")) == 0)
SetItemMinWidth(_ttoi(pstrValue));
else if(_tcsicmp(pstrName, _T("itemtextcolor")) == 0 ){
if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
LPTSTR pstr = NULL;
DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
SetItemTextColor(clrColor);
}
else if(_tcsicmp(pstrName, _T("itemhottextcolor")) == 0 ){
if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
LPTSTR pstr = NULL;
DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
SetItemHotTextColor(clrColor);
}
else if(_tcsicmp(pstrName, _T("selitemtextcolor")) == 0 ){
if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
LPTSTR pstr = NULL;
DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
SetSelItemTextColor(clrColor);
}
else if(_tcsicmp(pstrName, _T("selitemhottextcolor")) == 0 ){
if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue);
LPTSTR pstr = NULL;
DWORD clrColor = _tcstoul(pstrValue, &pstr, 16);
SetSelItemHotTextColor(clrColor);
}
else CListUI::SetAttribute(pstrName,pstrValue);
}
} | [
"noreply@github.com"
] | debuking1225.noreply@github.com |
134287169befca574857a2148412e95114f206a0 | 1b74084c36db7ce99a50e95282bc950a700d30e9 | /MFCApp.h | 38513a7db000a5d2cf46bfd91d1213504f4cf135 | [] | no_license | STONE-SAMA/ImageProcessDemo | b4db9c77811aecef0d44e3c6952392a44e799f7b | 041b36beeefa83aa98c87681bf4ef9eb31e55542 | refs/heads/master | 2023-04-19T09:23:12.901358 | 2021-05-11T12:37:59 | 2021-05-11T12:37:59 | 360,359,565 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 515 | h |
// MFCApp.h: PROJECT_NAME 应用程序的主头文件
//
#pragma once
#ifndef __AFXWIN_H__
#error "在包含此文件之前包含 'pch.h' 以生成 PCH"
#endif
#include "resource.h" // 主符号
// CMFCAppApp:
// 有关此类的实现,请参阅 MFCApp.cpp
//
class CMFCAppApp : public CWinApp
{
public:
CMFCAppApp();
// 重写
public:
virtual BOOL InitInstance();
// 实现
DECLARE_MESSAGE_MAP()
afx_msg void OnBnClickedButton2();
};
extern CMFCAppApp theApp;
| [
"shihanrui99@qq.com"
] | shihanrui99@qq.com |
ff659c319005163e7f1103556a45273d3feca7d8 | da20767ea53bcad6ae8e03174b44a96422c29f6d | /EyeSpy1_4.ino | ebeeae53a85d5704da028e6e7b8db615ded0b3b9 | [] | no_license | ThierrydeGroot/akkoord | 26bd3888cdfe348ce3ebf2c0b688cf9396929fd4 | e60d583e9256f7a204f2b8ddb23c08ba4c283da2 | refs/heads/master | 2021-09-05T10:45:51.241895 | 2018-01-26T14:55:35 | 2018-01-26T14:55:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,190 | ino | #include <NewPing.h>
#include <elapsedMillis.h>
#include <Wire.h>
#include <SoftwareSerial.h> // use the software uart
#define BAT_PIN A0
#define LDR_PIN A1
#define VIBRATE_PIN 13 // Vibration feature for kpt. Ernst's mum.
#define TRIGGER_PIN0 12 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN0 11 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define TRIGGER_PIN1 5 // Arduino pin tied to trigger pin on the other ultrasonic sensor.
#define ECHO_PIN1 6 // Arduino pin tied to echo pin on the other ultrasonic sensor.
#define DIR_PIN 2 // The direction of the stepper motor.
#define STEP_PIN 3 // The amount of steps of the stepper motor.
#define BUTTON_PIN 4
#define LED_PIN 10
#define BUZZ_PIN 9
SoftwareSerial bluetooth(2, 4); // RX, TX
//variables
char data = 0;
int MAX_DISTANCE = 250; // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.
int buttonState = 0;
int minLight = 40;
int sensorValue = 0;
int timer = 1;
int minVal = 265;
int maxVal = 402;
int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;
float minVoltage = 7.0;
boolean stopLoop = false;
boolean vibrated = false;
boolean rotatedLeft = false;
boolean rotatedRight = false;
elapsedMillis timeElapsedUltrasonic;
elapsedMillis timeElapsedOrientation;
elapsedMillis timeElapsedBattery;
elapsedMillis timeElapsedLight;
elapsedMillis timeElapsedRotated;
NewPing sonar0(TRIGGER_PIN0, ECHO_PIN0, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
NewPing sonar1(TRIGGER_PIN1, ECHO_PIN1, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
unsigned long previousMillis = 0; // will store last time
const long interval = 500; // interval at which to delay
static uint32_t tmp; // increment this
//SoftwareSerial bluetoothSerial(bluetoothReceivePin, bluetoothTransmitPin);
void setup() {
Wire.begin();
Wire.beginTransmission(0x68);
Wire.write(0x6B);
Wire.write(0);
Wire.endTransmission(true);
pinMode(BUTTON_PIN, INPUT);
pinMode(VIBRATE_PIN, OUTPUT);
pinMode(LED_PIN, OUTPUT);
pinMode(BUZZ_PIN, OUTPUT);
Serial.begin(115200); //9600
}
void loop() {
buttonState = digitalRead(BUTTON_PIN);
if (buttonState == HIGH) alarmMode();
if (bluetooth.available()) { // check if anything in UART buffer
if (bluetooth.read() == '1') turnLeft();
if (bluetooth.read() == '2') turnRight();
}
if (rotatedLeft == true)
{
if (timeElapsedRotated >= 1000)
{
Serial.println("go right to starting position");
rotateDeg(-22.5, .3);
rotatedLeft = false;
timeElapsedRotated = 0;
}
} else if (rotatedRight == true)
{
if (timeElapsedRotated >= 1000)
{
Serial.println("go left to starting position");
rotateDeg(22.5, .3);
rotatedRight = false;
timeElapsedRotated = 0;
}
}
if (timeElapsedUltrasonic >= 30) measureDistance(); // Wait 30ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
if (timeElapsedOrientation >= 1000) measureOrientation();
if (timeElapsedBattery >= 5000) measureBattery();
if (timeElapsedLight >= 5000) measureLight();
}
void alarmMode() {
while (stopLoop == false) {
Serial.println("loop start");
digitalWrite(BUZZ_PIN, HIGH);
digitalWrite(LED_PIN, HIGH);
delay(200);
buttonState = digitalRead(BUTTON_PIN);
if (buttonState == HIGH)
{
stopLoop = true;
Serial.println("first check");
}
digitalWrite(BUZZ_PIN, LOW);
digitalWrite(LED_PIN, LOW);
delay(200);
buttonState = digitalRead(BUTTON_PIN);
if (buttonState == HIGH)
{
stopLoop = true;
Serial.println("second check");
}
}
stopLoop = false;
Serial.println("loop end");
}
void measureDistance() {
Serial.println(timeElapsedUltrasonic);
Serial.print(sonar0.ping_cm(), DEC); // Send ping, get distance in cm and print result (0 = outside set distance range)
Serial.print("\t");
Serial.println(sonar1.ping_cm(), DEC); // Secondary ping.
if (sonar0.ping_cm() <= 70 && sonar0.ping_cm() >= 1 || sonar1.ping_cm() <= 70 && sonar1.ping_cm() >= 1) {
Serial.println("object detected!11");
digitalWrite(VIBRATE_PIN, HIGH);
} else {
digitalWrite(VIBRATE_PIN, LOW);
}
timeElapsedUltrasonic = 0;
}
void measureOrientation() {
Wire.beginTransmission(0x68);
Wire.write(0x3B);
Wire.endTransmission(false);
Wire.requestFrom(0x68, 14, true);
AcX = Wire.read() << 8 | Wire.read();
AcY = Wire.read() << 8 | Wire.read();
AcZ = Wire.read() << 8 | Wire.read();
int xAng = map(AcX, minVal, maxVal, -90, 90);
int yAng = map(AcY, minVal, maxVal, -90, 90);
int zAng = map(AcZ, minVal, maxVal, -90, 90);
double calc_X = RAD_TO_DEG * (atan2(-yAng, -zAng) + PI);
double calc_Y = RAD_TO_DEG * (atan2(-xAng, -zAng) + PI);
double calc_Z = RAD_TO_DEG * (atan2(-yAng, -xAng) + PI);
if (calc_X <= 195 && calc_X >= 150 )
{
//als de gyroscope ondersteboven(onderzijde van chip ligt rechtop) is print die shutdown.
Serial.print("shut down functions");
Serial.print("DegX= "); Serial.println(calc_X);
} else
{
Serial.print("DegX= "); Serial.println(calc_X);
}
if (calc_X >= 357 && calc_X <= 360)
{
if (timer == 5)
{
Serial.print("shut down");
timer = 1;
} else
{
delay(1000);
timer++;
Serial.print(timer);
}
}
if (calc_X <= 355)
timer = 1;
Serial.println("-----------------------------------------");
delay(450);
timeElapsedOrientation = 0;
}
void measureBattery() { //measure the battery voltage
int sensorValue = analogRead(A0);
float voltage = (sensorValue * (5.0 / 1024.0) * 10);
//Serial.println(voltage);
if ( voltage < minVoltage) {
if (vibrated == false) {
for (int i = 0; i < 3; i++) {
digitalWrite(VIBRATE_PIN, HIGH);
delay(500);
digitalWrite(VIBRATE_PIN, LOW);
delay(500);
}
vibrated = true;
}
}
elapsedMillis timeElapsedBattery;
}
void measureLight() { //measure the value of the LDR-resistor
sensorValue = analogRead(LDR_PIN);
//Serial.println(sensorValue);
if (sensorValue <= minLight) {
digitalWrite(LED_PIN, HIGH);
}
if (sensorValue > 35) {
digitalWrite(LED_PIN, LOW);
}
elapsedMillis timeElapsedLight;
}
void turnLeft() {
Serial.println("go left");
rotateDeg(22.5, .3);
rotatedLeft = true;
timeElapsedRotated = 0;
}
void turnRight() {
Serial.println("go right");
rotateDeg(-22.5, .3);
rotatedRight = true;
timeElapsedRotated = 0;
}
void rotateDeg(float deg, float speed) { //rotate a specific number of degrees (negitive for reverse movement) //speed is any number from .01 -> 1 with 1 being fastest – Slower is stronger
int dir = (deg > 0) ? HIGH : LOW;
digitalWrite(DIR_PIN, dir);
int steps = abs(deg) * (1 / 0.225);
float usDelay = (1 / speed) * 70;
for (int i = 0; i < steps; i++) {
digitalWrite(STEP_PIN, HIGH);
delayMicroseconds(usDelay);
digitalWrite(STEP_PIN, LOW);
delayMicroseconds(usDelay);
}
}
| [
"noreply@github.com"
] | ThierrydeGroot.noreply@github.com |
c2b7f533dd4b34538ac68823a04932bb4adf41ac | f259d6b3d11ff7f11b32f1903b73032812d6c502 | /recursion/sum_till_n.cpp | 34a3e1c88ba4943f432941736b6a3b34b0643c29 | [] | no_license | nimitsajal/DSA_practice | cbf040865e0d431a1146ee110dea26e47ab157f2 | 5c56ec5b03521ecceb5294b2aadd75fd4475d60d | refs/heads/master | 2023-07-03T22:59:16.402104 | 2021-08-08T02:02:43 | 2021-08-08T02:02:43 | 386,630,279 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 291 | cpp | #include<iostream>
using namespace std;
int sum(int n){
if(n == 0){
return 0; //when adding, return 0 (so as to not make any update to previous csalculations)
}
return n + sum(n-1);
}
int main(){
int n;
cin >> n;
cout << sum(n) << endl;
return 0;
} | [
"nimit.cs18@bmsce.ac.in"
] | nimit.cs18@bmsce.ac.in |
554f92c0f126b5c85f7ca23e61471c0a8c91f1cb | 54d991040a390628d5b4363eebf3d466d9f61087 | /ArenaProject/ArenaV2PlayerController.cpp | 0a156cb3f90c37123000c759a6d4528d5f9ec262 | [] | no_license | LuGMaC/UnrealProjects-ArenaIllusions | e2d244aa9de10e501d10899da27572ffef70f826 | 4d9197f79cb13b3515220f31e4316296251388b9 | refs/heads/main | 2023-03-29T12:40:23.768700 | 2021-04-05T18:32:00 | 2021-04-05T18:32:00 | 354,933,248 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 124 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "ArenaV2PlayerController.h"
| [
"noreply@github.com"
] | LuGMaC.noreply@github.com |
e8ef1cf34e0fcbefc387831ff3f0d45c81d9f3c8 | d4240a19b3a97e8c4a39a7925e8046ead6642d19 | /2016/Enceladus/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_NonSerializedAttribute399263003.h | 99bbcd4890e97fb8b394e13e4319cbbf051e6d76 | [] | no_license | mgoadric/csci370 | 05561a24a8a6c3ace4d9ab673b20c03fc40686e9 | 9ffd5d0e373c8a415cd23799fc29a6f6d83c08af | refs/heads/master | 2023-03-17T18:51:45.095212 | 2023-03-13T19:45:59 | 2023-03-13T19:45:59 | 81,270,581 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 533 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_Attribute542643598.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.NonSerializedAttribute
struct NonSerializedAttribute_t399263003 : public Attribute_t542643598
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"goadrich@hendrix.edu"
] | goadrich@hendrix.edu |
bc60c48d951b0842306aed505b51a2aa6cc3dc32 | db935bfe3fb738923012d03c678051a5162d7c2c | /25_07/both_namespace_local.cpp | fb974e6bc45596af6177f505792d383e0a0e0ce3 | [] | no_license | MayankPeter/cpp | 3475ece28a14682c3966ca23201db4543defa11f | a654b71d64d73977af0a5622afb77aecd1fdc527 | refs/heads/master | 2020-06-26T02:26:40.244945 | 2019-09-08T06:50:10 | 2019-09-08T06:50:10 | 199,497,568 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 304 | cpp | #include<iostream>
using namespace std;
namespace first
{
int x = 10;
void display()
{
cout << "first display" << endl;
}
}
namespace second
{
int x = 20;
void display()
{
cout << "second display" << endl;
}
}
int main()
{
using namespace first;
using namespace second;
cout << x << endl;
display();
}
| [
"MayankPeter@abc.com"
] | MayankPeter@abc.com |
678f3a7475e67d971cf0a6337d0b450df4086f1e | 4a761d25954a9dd9aafbcac677a62e83e6785ba3 | /src/chain.h | c8c89db012c65535869829dff60462881a66d453 | [
"MIT"
] | permissive | CONCRETE-Project/CONCRETE | 4dce6c776857d0fccef094f29aae1228796bd03c | f446b5335bff7f7a6a1ffeba97777339539263b0 | refs/heads/master | 2022-12-02T16:07:03.999082 | 2020-08-24T21:25:18 | 2020-08-24T21:25:18 | 256,929,363 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,417 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2011-2013 The PPCoin developers
// Copyright (c) 2013-2014 The NovaCoin Developers
// Copyright (c) 2014-2018 The BlackCoin Developers
// Copyright (c) 2015-2019 The PIVX Core Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_CHAIN_H
#define BITCOIN_CHAIN_H
#include "chainparams.h"
#include "pow.h"
#include "primitives/block.h"
#include "timedata.h"
#include "tinyformat.h"
#include "uint256.h"
#include "util.h"
#include "libzerocoin/Denominations.h"
#include <vector>
class CBlockFileInfo
{
public:
unsigned int nBlocks; //!< number of blocks stored in file
unsigned int nSize; //!< number of used bytes of block file
unsigned int nUndoSize; //!< number of used bytes in the undo file
unsigned int nHeightFirst; //!< lowest height of block in file
unsigned int nHeightLast; //!< highest height of block in file
uint64_t nTimeFirst; //!< earliest time of block in file
uint64_t nTimeLast; //!< latest time of block in file
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(VARINT(nBlocks));
READWRITE(VARINT(nSize));
READWRITE(VARINT(nUndoSize));
READWRITE(VARINT(nHeightFirst));
READWRITE(VARINT(nHeightLast));
READWRITE(VARINT(nTimeFirst));
READWRITE(VARINT(nTimeLast));
}
void SetNull()
{
nBlocks = 0;
nSize = 0;
nUndoSize = 0;
nHeightFirst = 0;
nHeightLast = 0;
nTimeFirst = 0;
nTimeLast = 0;
}
CBlockFileInfo()
{
SetNull();
}
std::string ToString() const;
/** update statistics (does not update nSize) */
void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn)
{
if (nBlocks == 0 || nHeightFirst > nHeightIn)
nHeightFirst = nHeightIn;
if (nBlocks == 0 || nTimeFirst > nTimeIn)
nTimeFirst = nTimeIn;
nBlocks++;
if (nHeightIn > nHeightLast)
nHeightLast = nHeightIn;
if (nTimeIn > nTimeLast)
nTimeLast = nTimeIn;
}
};
struct CDiskBlockPos {
int nFile;
unsigned int nPos;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(VARINT(nFile));
READWRITE(VARINT(nPos));
}
CDiskBlockPos()
{
SetNull();
}
CDiskBlockPos(int nFileIn, unsigned int nPosIn)
{
nFile = nFileIn;
nPos = nPosIn;
}
friend bool operator==(const CDiskBlockPos& a, const CDiskBlockPos& b)
{
return (a.nFile == b.nFile && a.nPos == b.nPos);
}
friend bool operator!=(const CDiskBlockPos& a, const CDiskBlockPos& b)
{
return !(a == b);
}
void SetNull()
{
nFile = -1;
nPos = 0;
}
bool IsNull() const { return (nFile == -1); }
};
enum BlockStatus {
//! Unused.
BLOCK_VALID_UNKNOWN = 0,
//! Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
BLOCK_VALID_HEADER = 1,
//! All parent headers found, difficulty matches, timestamp >= median previous, checkpoint. Implies all parents
//! are also at least TREE.
BLOCK_VALID_TREE = 2,
/**
* Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids,
* sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all
* parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set.
*/
BLOCK_VALID_TRANSACTIONS = 3,
//! Outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30.
//! Implies all parents are also at least CHAIN.
BLOCK_VALID_CHAIN = 4,
//! Scripts & signatures ok. Implies all parents are also at least SCRIPTS.
BLOCK_VALID_SCRIPTS = 5,
//! All validity bits.
BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS |
BLOCK_VALID_CHAIN |
BLOCK_VALID_SCRIPTS,
BLOCK_HAVE_DATA = 8, //! full block available in blk*.dat
BLOCK_HAVE_UNDO = 16, //! undo data available in rev*.dat
BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO,
BLOCK_FAILED_VALID = 32, //! stage after last reached validness failed
BLOCK_FAILED_CHILD = 64, //! descends from failed block
BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD,
};
// BlockIndex flags
enum {
BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
};
/** The block chain is a tree shaped structure starting with the
* genesis block at the root, with each block potentially having multiple
* candidates to be the next block. A blockindex may have multiple pprev pointing
* to it, but at most one of them can be part of the currently active branch.
*/
class CBlockIndex
{
public:
//! pointer to the hash of the block, if any. memory is owned by this CBlockIndex
const uint256* phashBlock{nullptr};
//! pointer to the index of the predecessor of this block
CBlockIndex* pprev{nullptr};
//! pointer to the index of some further predecessor of this block
CBlockIndex* pskip{nullptr};
//! height of the entry in the chain. The genesis block has height 0
int nHeight{0};
//! Which # file this block is stored in (blk?????.dat)
int nFile{0};
//! Byte offset within blk?????.dat where this block's data is stored
unsigned int nDataPos{0};
//! Byte offset within rev?????.dat where this block's undo data is stored
unsigned int nUndoPos{0};
//! (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
uint256 nChainWork{};
//! Number of transactions in this block.
//! Note: in a potential headers-first mode, this number cannot be relied upon
unsigned int nTx{0};
//! (memory only) Number of transactions in the chain up to and including this block.
//! This value will be non-zero only if and only if transactions for this block and all its parents are available.
//! Change to 64-bit type when necessary; won't happen before 2030
unsigned int nChainTx{0};
//! Verification status of this block. See enum BlockStatus
unsigned int nStatus{0};
// proof-of-stake specific fields
// char vector holding the stake modifier bytes. It is empty for PoW blocks.
// Modifier V1 is 64 bit while modifier V2 is 256 bit.
std::vector<unsigned char> vStakeModifier{};
unsigned int nFlags{0};
//! block header
int nVersion{0};
uint256 hashMerkleRoot{};
unsigned int nTime{0};
unsigned int nBits{0};
unsigned int nNonce{0};
uint256 nAccumulatorCheckpoint{};
//! (memory only) Sequential id assigned to distinguish order in which blocks are received.
uint32_t nSequenceId{0};
CBlockIndex() {}
CBlockIndex(const CBlock& block);
std::string ToString() const;
CDiskBlockPos GetBlockPos() const;
CDiskBlockPos GetUndoPos() const;
CBlockHeader GetBlockHeader() const;
uint256 GetBlockHash() const { return *phashBlock; }
int64_t GetBlockTime() const { return (int64_t)nTime; }
int64_t GetMedianTimePast() const;
int64_t MaxFutureBlockTime() const;
int64_t MinPastBlockTime() const;
bool IsProofOfStake() const { return (nFlags & BLOCK_PROOF_OF_STAKE); }
bool IsProofOfWork() const { return !IsProofOfStake(); }
void SetProofOfStake() { nFlags |= BLOCK_PROOF_OF_STAKE; }
// Stake Modifier
unsigned int GetStakeEntropyBit() const;
bool SetStakeEntropyBit(unsigned int nEntropyBit);
bool GeneratedStakeModifier() const { return (nFlags & BLOCK_STAKE_MODIFIER); }
void SetStakeModifier(const uint64_t nStakeModifier, bool fGeneratedStakeModifier);
void SetNewStakeModifier(); // generates and sets new v1 modifier
void SetStakeModifier(const uint256& nStakeModifier);
void SetNewStakeModifier(const uint256& prevoutId); // generates and sets new v2 modifier
uint64_t GetStakeModifierV1() const;
uint256 GetStakeModifierV2() const;
//! Check whether this block index entry is valid up to the passed validity level.
bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const;
//! Raise the validity level of this block index entry.
//! Returns true if the validity was changed.
bool RaiseValidity(enum BlockStatus nUpTo);
//! Build the skiplist pointer for this entry.
void BuildSkip();
//! Efficiently find an ancestor of this block.
CBlockIndex* GetAncestor(int height);
const CBlockIndex* GetAncestor(int height) const;
};
/** Used to marshal pointers into hashes for db storage. */
// New serialization introduced with 1.0.1
static const int DBI_OLD_SER_VERSION = 1000000;
static const int DBI_SER_VERSION_NO_ZC = 1000100; // removes mapZerocoinSupply, nMoneySupply
class CDiskBlockIndex : public CBlockIndex
{
public:
uint256 hashPrev;
CDiskBlockIndex()
{
hashPrev = UINT256_ZERO;
}
explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex)
{
hashPrev = (pprev ? pprev->GetBlockHash() : UINT256_ZERO);
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nSerVersion)
{
if (!(nType & SER_GETHASH))
READWRITE(VARINT(nSerVersion));
READWRITE(VARINT(nHeight));
READWRITE(VARINT(nStatus));
READWRITE(VARINT(nTx));
if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
READWRITE(VARINT(nFile));
if (nStatus & BLOCK_HAVE_DATA)
READWRITE(VARINT(nDataPos));
if (nStatus & BLOCK_HAVE_UNDO)
READWRITE(VARINT(nUndoPos));
if (nSerVersion >= DBI_SER_VERSION_NO_ZC) {
// Serialization with CLIENT_VERSION = 1000100+
READWRITE(nFlags);
READWRITE(this->nVersion);
READWRITE(vStakeModifier);
READWRITE(hashPrev);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
if(this->nVersion > 3 && this->nVersion < 7)
READWRITE(nAccumulatorCheckpoint);
} else if (nSerVersion > DBI_OLD_SER_VERSION && ser_action.ForRead()) {
// Serialization with CLIENT_VERSION = 1000000
std::map<libzerocoin::CoinDenomination, int64_t> mapZerocoinSupply;
int64_t nMoneySupply = 0;
READWRITE(nMoneySupply);
READWRITE(nFlags);
READWRITE(this->nVersion);
READWRITE(vStakeModifier);
READWRITE(hashPrev);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
if(this->nVersion > 3) {
READWRITE(mapZerocoinSupply);
if(this->nVersion < 7) READWRITE(nAccumulatorCheckpoint);
}
} else if (ser_action.ForRead()) {
// Serialization with CLIENT_VERSION < 1000000
int64_t nMint = 0;
uint256 hashNext{};
int64_t nMoneySupply = 0;
READWRITE(nMint);
READWRITE(nMoneySupply);
READWRITE(nFlags);
if (nHeight < Params().GetConsensus().height_start_StakeModifierV2) {
uint64_t nStakeModifier = 0;
READWRITE(nStakeModifier);
this->SetStakeModifier(nStakeModifier, this->GeneratedStakeModifier());
} else {
uint256 nStakeModifierV2;
READWRITE(nStakeModifierV2);
this->SetStakeModifier(nStakeModifierV2);
}
if (IsProofOfStake()) {
COutPoint prevoutStake;
unsigned int nStakeTime = 0;
READWRITE(prevoutStake);
READWRITE(nStakeTime);
}
READWRITE(this->nVersion);
READWRITE(hashPrev);
READWRITE(hashNext);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
if(this->nVersion > 3) {
std::map<libzerocoin::CoinDenomination, int64_t> mapZerocoinSupply;
std::vector<libzerocoin::CoinDenomination> vMintDenominationsInBlock;
READWRITE(nAccumulatorCheckpoint);
READWRITE(mapZerocoinSupply);
READWRITE(vMintDenominationsInBlock);
}
}
}
uint256 GetBlockHash() const
{
CBlockHeader block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrev;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
if (nVersion > 3 && nVersion < 7)
block.nAccumulatorCheckpoint = nAccumulatorCheckpoint;
return block.GetHash();
}
std::string ToString() const
{
std::string str = "CDiskBlockIndex(";
str += CBlockIndex::ToString();
str += strprintf("\n hashBlock=%s, hashPrev=%s)",
GetBlockHash().ToString(),
hashPrev.ToString());
return str;
}
};
/** Legacy block index - used to retrieve old serializations */
class CLegacyBlockIndex : public CBlockIndex
{
public:
std::map<libzerocoin::CoinDenomination, int64_t> mapZerocoinSupply{};
int64_t nMint = 0;
uint256 hashNext{};
uint256 hashPrev{};
uint64_t nStakeModifier = 0;
uint256 nStakeModifierV2{};
COutPoint prevoutStake{};
unsigned int nStakeTime = 0;
std::vector<libzerocoin::CoinDenomination> vMintDenominationsInBlock;
int64_t nMoneySupply = 0;
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nSerVersion)
{
if (!(nType & SER_GETHASH))
READWRITE(VARINT(nSerVersion));
if (nSerVersion >= DBI_SER_VERSION_NO_ZC) {
// no extra serialized field
return;
}
if (!ser_action.ForRead()) {
// legacy block index shouldn't be used to write
return;
}
READWRITE(VARINT(nHeight));
READWRITE(VARINT(nStatus));
READWRITE(VARINT(nTx));
if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
READWRITE(VARINT(nFile));
if (nStatus & BLOCK_HAVE_DATA)
READWRITE(VARINT(nDataPos));
if (nStatus & BLOCK_HAVE_UNDO)
READWRITE(VARINT(nUndoPos));
if (nSerVersion > DBI_OLD_SER_VERSION) {
// Serialization with CLIENT_VERSION = 1000100+
READWRITE(nMoneySupply);
READWRITE(nFlags);
READWRITE(this->nVersion);
READWRITE(vStakeModifier);
READWRITE(hashPrev);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
if(this->nVersion > 3) {
READWRITE(mapZerocoinSupply);
if(this->nVersion < 7) READWRITE(nAccumulatorCheckpoint);
}
} else {
// Serialization with CLIENT_VERSION <= 1000000
READWRITE(nMint);
READWRITE(nMoneySupply);
READWRITE(nFlags);
if (nHeight < Params().GetConsensus().height_start_StakeModifierV2) {
READWRITE(nStakeModifier);
} else {
READWRITE(nStakeModifierV2);
}
if (IsProofOfStake()) {
READWRITE(prevoutStake);
READWRITE(nStakeTime);
}
READWRITE(this->nVersion);
READWRITE(hashPrev);
READWRITE(hashNext);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
if(this->nVersion > 3) {
READWRITE(nAccumulatorCheckpoint);
READWRITE(mapZerocoinSupply);
READWRITE(vMintDenominationsInBlock);
}
}
}
};
/** An in-memory indexed chain of blocks. */
class CChain
{
private:
std::vector<CBlockIndex*> vChain;
public:
/** Returns the index entry for the genesis block of this chain, or NULL if none. */
CBlockIndex* Genesis() const
{
return vChain.size() > 0 ? vChain[0] : NULL;
}
/** Returns the index entry for the tip of this chain, or NULL if none. */
CBlockIndex* Tip(bool fProofOfStake = false) const
{
if (vChain.size() < 1)
return NULL;
CBlockIndex* pindex = vChain[vChain.size() - 1];
if (fProofOfStake) {
while (pindex && pindex->pprev && !pindex->IsProofOfStake())
pindex = pindex->pprev;
}
return pindex;
}
/** Returns the index entry at a particular height in this chain, or NULL if no such height exists. */
CBlockIndex* operator[](int nHeight) const
{
if (nHeight < 0 || nHeight >= (int)vChain.size())
return NULL;
return vChain[nHeight];
}
/** Compare two chains efficiently. */
friend bool operator==(const CChain& a, const CChain& b)
{
return a.vChain.size() == b.vChain.size() &&
a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1];
}
/** Efficiently check whether a block is present in this chain. */
bool Contains(const CBlockIndex* pindex) const
{
return (*this)[pindex->nHeight] == pindex;
}
/** Find the successor of a block in this chain, or NULL if the given index is not found or is the tip. */
CBlockIndex* Next(const CBlockIndex* pindex) const
{
if (Contains(pindex))
return (*this)[pindex->nHeight + 1];
else
return NULL;
}
/** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */
int Height() const
{
return vChain.size() - 1;
}
/** Set/initialize a chain with a given tip. */
void SetTip(CBlockIndex* pindex);
/** Return a CBlockLocator that refers to a block in this chain (by default the tip). */
CBlockLocator GetLocator(const CBlockIndex* pindex = NULL) const;
/** Find the last common block between this chain and a block index entry. */
const CBlockIndex* FindFork(const CBlockIndex* pindex) const;
/** Check if new message signatures are active **/
bool NewSigsActive() { return Params().GetConsensus().IsMessSigV2(Height()); }
};
#endif // BITCOIN_CHAIN_H
| [
"ziofabry@hotmail.com"
] | ziofabry@hotmail.com |
98af3275238ed2f43f0fa4440701cac249e9b4d5 | 6bc3f5955699fcdac540823c51354bc21919fb06 | /Quera/CodeCup 3/Elimination/C.cpp | 977b7a7803a9f7f453fcb8cbad527ab2baf1ecad | [] | no_license | soroush-tabesh/Competitive-Programming | e1a265e2224359962088c74191b7dc87bbf314bf | a677578c2a0e21c0510258933548a251970d330d | refs/heads/master | 2021-09-24T06:36:43.037300 | 2018-10-04T14:12:00 | 2018-10-04T14:12:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 611 | cpp | //In The Name of Allah
//Fri 14/7/96
#include <bits/stdc++.h>
using namespace std;
const int MN = 1e6+100 , inf=1e9+100 ;
#define int long long
#define pb push_back
#define F first
#define S second
set<char>s1,s2;
string st,t;
int n;
int32_t main()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin>>n>>t;
for(char c:t){
s1.insert(c);
}
for(int i=0;i<n;i++){
s2.clear();
cin>>st;
for(char c:st){
s2.insert(c);
}
if(s1==s2){
cout<<"Yes"<<endl;
}else{
cout<<"No"<<endl;
}
}
}
| [
"sorooshtabesh@yahoo.com"
] | sorooshtabesh@yahoo.com |
db3c66324738900ad63851c59e797378d3e77379 | 334ee6d53289383cc778de4bb4867ffd129b2331 | /cxx/src/qbus_config.h | 601998a92303ad6352d735bad2015c57f3329c58 | [] | no_license | flyyi/kafkabridge | 9ea28e2c8fad89cff7e925c9987068bd3f0a3dad | 62fc1972406d744a171011403ef940a7179a7218 | refs/heads/master | 2020-04-01T00:42:54.444937 | 2018-10-12T06:13:50 | 2018-10-12T06:13:50 | 152,709,788 | 1 | 0 | null | 2018-10-12T07:17:12 | 2018-10-12T07:17:12 | null | UTF-8 | C++ | false | false | 1,027 | h | #ifndef QBUS_CONFIG_H
#define QBUS_CONFIG_H
#include <string>
#include <boost/property_tree/ptree.hpp>
#include "thirdparts/librdkafka/src/rdkafka.h"
namespace pt = boost::property_tree;
namespace qbus {
class QbusConfigLoader {
public:
enum ConfigType {
CT_CONSUMER = 0,
CT_PRODUCER,
};
QbusConfigLoader() {
}
void LoadConfig(const std::string& path);
void LoadRdkafkaConfig(rd_kafka_conf_t* rd_kafka_conf,
rd_kafka_topic_conf_t* rd_kafka_topic_conf);
bool IsSetConfig(const std::string& config_name, bool is_topic_config) const;
std::string GetSdkConfig(const std::string& config_name, const std::string& default_value) const;
private:
pt::ptree root_tree_;
pt::ptree set_global_config_items_;
pt::ptree set_topic_config_items_;
pt::ptree set_sdk_configs_;
private:
QbusConfigLoader(const QbusConfigLoader&);
QbusConfigLoader& operator=(const QbusConfigLoader&);
};//QbusConfigLoader
}//namespace qbus
#endif//#define QBUS_CONFIG_H
| [
"zhangkuo@atlasdev002v.ops.corp.qihoo.net"
] | zhangkuo@atlasdev002v.ops.corp.qihoo.net |
720c698f9a0184f162055505abca339622f68387 | 35b7aca2f5eb70481ab3a50501d416c2a65d2cd7 | /Project1/SphereTracking.cpp | 2a662f8ff534fd64228497c226200428f687b441 | [] | no_license | ankithmanju/Passive-marker-detection-using-opencv | 908201c8e99d364d88c7341c961c6b60833ba178 | e9257c3de6f6b82a041328dc18ff0d43b2ddb674 | refs/heads/master | 2021-01-10T13:54:51.961826 | 2016-03-13T14:48:31 | 2016-03-13T14:48:31 | 53,789,599 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,939 | cpp | #include "SphereTracking.h"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/types_c.h"
#include<iostream>
#include <fstream>
#include <math.h>
#include <cmath>
using namespace cv;
using namespace std;
Mat SphereDetection::inRange_cal(Mat imgHSV,int HueL,int HueH,int Satl,int Sath,int Vall,int Valh)
{
Mat tempThreshold;
inRange(imgHSV,Scalar(HueL,Satl,Vall),Scalar(HueH,Sath,Valh),tempThreshold);
return tempThreshold;
}
Mat SphereDetection::morphologicalOperations(Mat Inputimage)
{
erode(Inputimage,Inputimage,getStructuringElement(MORPH_ELLIPSE,Size(5,5)));
dilate( Inputimage,Inputimage,getStructuringElement(MORPH_ELLIPSE,Size(5,5)));
dilate(Inputimage,Inputimage,getStructuringElement(MORPH_ELLIPSE,Size(5,5))); //morphological closing (removes small holes from the foreground)
erode(Inputimage, Inputimage,getStructuringElement(MORPH_ELLIPSE,Size(5,5)));
return Inputimage;
}
Mat SphereDetection::moments_calulator(Mat inputimage,int color_flag)
{
Mat temp_imgLines=Mat::zeros(inputimage.size(),CV_8UC3);;
Moments oMoments=moments(inputimage);
double dM01=oMoments.m01;
double dM10=oMoments.m10;
double dArea=oMoments.m00;
double posX=dM10/dArea; //calculate the position of the ball
double posY=dM01/dArea;
circle(temp_imgLines,Point(posX,posY),100,Scalar(255,0,255),1,8,0);
return temp_imgLines;
}
double* SphereDetection::coordinates_marker(Mat inputimage,int color_flag)
{
Moments oMoments=moments(inputimage);
double dM01=oMoments.m01;
double dM10=oMoments.m10;
double dArea=oMoments.m00;
double posX,posY;
static double pos[2]={};
if((dArea>=0.00000001))
{
posX=dM10/dArea; //calculate the position of the ball
posY=dM01/dArea;
pos[0]=posX;
pos[1]=posY;
return pos;
}
else
pos[0]=-1;
pos[1]=-1;
return pos;
}
float* SphereDetection::SerialDataParse(string stdstring)
{
static float coordinates[3]={};
std::size_t found = stdstring.find(",");
stdstring.erase(0,found+1);
found = stdstring.find(","); //extract the x coordinates
std::string xcoordinate = stdstring.substr (0,found);
float x=stof(xcoordinate);
stdstring.erase(0,found+1);
cout<<xcoordinate<<endl; //Display x coordinate
found = stdstring.find(","); //extract the y coordinates
std::string ycoordinate = stdstring.substr (0,found);
float y=stof(ycoordinate);
stdstring.erase(0,found+1);
cout<<ycoordinate<<endl; //Display y coordinate
found = stdstring.find(","); //extract the z coordinates
std::string zcoordinate = stdstring.substr (0,found);
float z=stof(zcoordinate);
stdstring.erase(0,found+1);
cout<<zcoordinate<<endl; //Display z coordinate
coordinates[0]=x;
coordinates[1]=y;
coordinates[2]=z;
return coordinates;
}
| [
"ankith0073@gmail.com"
] | ankith0073@gmail.com |
b3ef540968c5d0793399496fa8dea0cf628a3b38 | 790cb25a90e7413b996de3af6e1d23d219c066cc | /栈和队列/用两个栈实现队列.cpp | 79c232180d9c390e162a3c1ec3b738cc6e0c8f35 | [] | no_license | ichbinhandsome/sword-to-offer | 84e2d5f2391c49d1586fd3377ffb168acfa58700 | 656f788e1c3654636ea09553510a498f1ca9f211 | refs/heads/master | 2022-11-28T00:51:27.585278 | 2020-08-10T20:06:16 | 2020-08-10T20:06:16 | 267,159,669 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,632 | cpp | /*
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例 1:
输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]
示例 2:
输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]
提示:
1 <= values <= 10000
最多会对 appendTail、deleteHead 进行 10000 次调用
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof
*/
class CQueue {
//stack1: insert value
//stack2: delete value and return deleted value
stack<int> stack1, stack2;
public:
CQueue() {
//初始化 stack1 stack2 全为空
while (!stack1.empty()) stack1.pop();
while (!stack2.empty()) stack2.pop();
}
void appendTail(int value) {
stack1.push(value);
}
int deleteHead() {
if (stack2.empty()){
if (stack1.empty()) return -1;
else{
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
}
}
int d = stack2.top();
stack2.pop();
return d;
}
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/ | [
"wangruixiang07@outlook.com"
] | wangruixiang07@outlook.com |
3c0d093d12b4ea6cb73f71d0bf30bb23d3a700b7 | 2ba94892764a44d9c07f0f549f79f9f9dc272151 | /Engine/Source/ThirdParty/PhysX/APEX-1.3/module/emitter_legacy/src/ApexEmitterAssetParameters_0p6.cpp | 91a72620f14fbaec164624ce9d8ca0a97af8b059 | [
"BSD-2-Clause",
"LicenseRef-scancode-proprietary-license"
] | permissive | PopCap/GameIdea | 934769eeb91f9637f5bf205d88b13ff1fc9ae8fd | 201e1df50b2bc99afc079ce326aa0a44b178a391 | refs/heads/master | 2021-01-25T00:11:38.709772 | 2018-09-11T03:38:56 | 2018-09-11T03:38:56 | 37,818,708 | 0 | 0 | BSD-2-Clause | 2018-09-11T03:39:05 | 2015-06-21T17:36:44 | null | UTF-8 | C++ | false | false | 45,468 | cpp | /*
* Copyright (c) 2008-2015, NVIDIA CORPORATION. All rights reserved.
*
* NVIDIA CORPORATION and its licensors retain all intellectual property
* and proprietary rights in and to this software, related documentation
* and any modifications thereto. Any use, reproduction, disclosure or
* distribution of this software and related documentation without an express
* license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
// This file was generated by NxParameterized/scripts/GenParameterized.pl
// Created: 2015.06.02 04:12:11
#include "ApexEmitterAssetParameters_0p6.h"
#include <string.h>
#include <stdlib.h>
using namespace NxParameterized;
namespace physx
{
namespace apex
{
using namespace ApexEmitterAssetParameters_0p6NS;
const char* const ApexEmitterAssetParameters_0p6Factory::vptr =
NxParameterized::getVptr<ApexEmitterAssetParameters_0p6, ApexEmitterAssetParameters_0p6::ClassAlignment>();
const physx::PxU32 NumParamDefs = 35;
static NxParameterized::DefinitionImpl* ParamDefTable; // now allocated in buildTree [NumParamDefs];
static const size_t ParamLookupChildrenTable[] =
{
1, 4, 7, 10, 13, 16, 17, 25, 26, 27, 28, 29, 30, 31, 2, 3, 5, 6, 8, 9, 11, 12, 14,
15, 18, 19, 20, 21, 22, 23, 24, 32, 33, 34,
};
#define TENUM(type) physx::##type
#define CHILDREN(index) &ParamLookupChildrenTable[index]
static const NxParameterized::ParamLookupNode ParamLookupTable[NumParamDefs] =
{
{ TYPE_STRUCT, false, 0, CHILDREN(0), 14 },
{ TYPE_STRUCT, false, (size_t)(&((ParametersStruct*)0)->densityRange), CHILDREN(14), 2 }, // densityRange
{ TYPE_F32, false, (size_t)(&((rangeStructF32_Type*)0)->min), NULL, 0 }, // densityRange.min
{ TYPE_F32, false, (size_t)(&((rangeStructF32_Type*)0)->max), NULL, 0 }, // densityRange.max
{ TYPE_STRUCT, false, (size_t)(&((ParametersStruct*)0)->rateRange), CHILDREN(16), 2 }, // rateRange
{ TYPE_F32, false, (size_t)(&((rangeStructF32_Type*)0)->min), NULL, 0 }, // rateRange.min
{ TYPE_F32, false, (size_t)(&((rangeStructF32_Type*)0)->max), NULL, 0 }, // rateRange.max
{ TYPE_STRUCT, false, (size_t)(&((ParametersStruct*)0)->lifetimeRange), CHILDREN(18), 2 }, // lifetimeRange
{ TYPE_F32, false, (size_t)(&((rangeStructF32_Type*)0)->min), NULL, 0 }, // lifetimeRange.min
{ TYPE_F32, false, (size_t)(&((rangeStructF32_Type*)0)->max), NULL, 0 }, // lifetimeRange.max
{ TYPE_STRUCT, false, (size_t)(&((ParametersStruct*)0)->velocityRange), CHILDREN(20), 2 }, // velocityRange
{ TYPE_VEC3, false, (size_t)(&((rangeStructVec3_Type*)0)->min), NULL, 0 }, // velocityRange.min
{ TYPE_VEC3, false, (size_t)(&((rangeStructVec3_Type*)0)->max), NULL, 0 }, // velocityRange.max
{ TYPE_STRUCT, false, (size_t)(&((ParametersStruct*)0)->temperatureRange), CHILDREN(22), 2 }, // temperatureRange
{ TYPE_F32, false, (size_t)(&((rangeStructF32_Type*)0)->min), NULL, 0 }, // temperatureRange.min
{ TYPE_F32, false, (size_t)(&((rangeStructF32_Type*)0)->max), NULL, 0 }, // temperatureRange.max
{ TYPE_U32, false, (size_t)(&((ParametersStruct*)0)->maxSamples), NULL, 0 }, // maxSamples
{ TYPE_STRUCT, false, (size_t)(&((ParametersStruct*)0)->lodParamDesc), CHILDREN(24), 7 }, // lodParamDesc
{ TYPE_U32, false, (size_t)(&((emitterLodParamDesc_Type*)0)->version), NULL, 0 }, // lodParamDesc.version
{ TYPE_F32, false, (size_t)(&((emitterLodParamDesc_Type*)0)->maxDistance), NULL, 0 }, // lodParamDesc.maxDistance
{ TYPE_F32, false, (size_t)(&((emitterLodParamDesc_Type*)0)->distanceWeight), NULL, 0 }, // lodParamDesc.distanceWeight
{ TYPE_F32, false, (size_t)(&((emitterLodParamDesc_Type*)0)->speedWeight), NULL, 0 }, // lodParamDesc.speedWeight
{ TYPE_F32, false, (size_t)(&((emitterLodParamDesc_Type*)0)->lifeWeight), NULL, 0 }, // lodParamDesc.lifeWeight
{ TYPE_F32, false, (size_t)(&((emitterLodParamDesc_Type*)0)->separationWeight), NULL, 0 }, // lodParamDesc.separationWeight
{ TYPE_F32, false, (size_t)(&((emitterLodParamDesc_Type*)0)->bias), NULL, 0 }, // lodParamDesc.bias
{ TYPE_REF, false, (size_t)(&((ParametersStruct*)0)->iofxAssetName), NULL, 0 }, // iofxAssetName
{ TYPE_REF, false, (size_t)(&((ParametersStruct*)0)->iosAssetName), NULL, 0 }, // iosAssetName
{ TYPE_REF, false, (size_t)(&((ParametersStruct*)0)->geometryType), NULL, 0 }, // geometryType
{ TYPE_F32, false, (size_t)(&((ParametersStruct*)0)->emitterDuration), NULL, 0 }, // emitterDuration
{ TYPE_F32, false, (size_t)(&((ParametersStruct*)0)->emitterVelocityScale), NULL, 0 }, // emitterVelocityScale
{ TYPE_U32, false, (size_t)(&((ParametersStruct*)0)->minSamplingFPS), NULL, 0 }, // minSamplingFPS
{ TYPE_ARRAY, true, (size_t)(&((ParametersStruct*)0)->rateVsTimeCurvePoints), CHILDREN(31), 1 }, // rateVsTimeCurvePoints
{ TYPE_STRUCT, false, 1 * sizeof(rateVsTimeCurvePoint_Type), CHILDREN(32), 2 }, // rateVsTimeCurvePoints[]
{ TYPE_F32, false, (size_t)(&((rateVsTimeCurvePoint_Type*)0)->x), NULL, 0 }, // rateVsTimeCurvePoints[].x
{ TYPE_F32, false, (size_t)(&((rateVsTimeCurvePoint_Type*)0)->y), NULL, 0 }, // rateVsTimeCurvePoints[].y
};
bool ApexEmitterAssetParameters_0p6::mBuiltFlag = false;
NxParameterized::MutexType ApexEmitterAssetParameters_0p6::mBuiltFlagMutex;
ApexEmitterAssetParameters_0p6::ApexEmitterAssetParameters_0p6(NxParameterized::Traits* traits, void* buf, PxI32* refCount) :
NxParameters(traits, buf, refCount)
{
//mParameterizedTraits->registerFactory(className(), &ApexEmitterAssetParameters_0p6FactoryInst);
if (!buf) //Do not init data if it is inplace-deserialized
{
initDynamicArrays();
initStrings();
initReferences();
initDefaults();
}
}
ApexEmitterAssetParameters_0p6::~ApexEmitterAssetParameters_0p6()
{
freeStrings();
freeReferences();
freeDynamicArrays();
}
void ApexEmitterAssetParameters_0p6::destroy()
{
// We cache these fields here to avoid overwrite in destructor
bool doDeallocateSelf = mDoDeallocateSelf;
NxParameterized::Traits* traits = mParameterizedTraits;
physx::PxI32* refCount = mRefCount;
void* buf = mBuffer;
this->~ApexEmitterAssetParameters_0p6();
NxParameters::destroy(this, traits, doDeallocateSelf, refCount, buf);
}
const NxParameterized::DefinitionImpl* ApexEmitterAssetParameters_0p6::getParameterDefinitionTree(void)
{
if (!mBuiltFlag) // Double-checked lock
{
NxParameterized::MutexType::ScopedLock lock(mBuiltFlagMutex);
if (!mBuiltFlag)
{
buildTree();
}
}
return(&ParamDefTable[0]);
}
const NxParameterized::DefinitionImpl* ApexEmitterAssetParameters_0p6::getParameterDefinitionTree(void) const
{
ApexEmitterAssetParameters_0p6* tmpParam = const_cast<ApexEmitterAssetParameters_0p6*>(this);
if (!mBuiltFlag) // Double-checked lock
{
NxParameterized::MutexType::ScopedLock lock(mBuiltFlagMutex);
if (!mBuiltFlag)
{
tmpParam->buildTree();
}
}
return(&ParamDefTable[0]);
}
NxParameterized::ErrorType ApexEmitterAssetParameters_0p6::getParameterHandle(const char* long_name, Handle& handle) const
{
ErrorType Ret = NxParameters::getParameterHandle(long_name, handle);
if (Ret != ERROR_NONE)
{
return(Ret);
}
size_t offset;
void* ptr;
getVarPtr(handle, ptr, offset);
if (ptr == NULL)
{
return(ERROR_INDEX_OUT_OF_RANGE);
}
return(ERROR_NONE);
}
NxParameterized::ErrorType ApexEmitterAssetParameters_0p6::getParameterHandle(const char* long_name, Handle& handle)
{
ErrorType Ret = NxParameters::getParameterHandle(long_name, handle);
if (Ret != ERROR_NONE)
{
return(Ret);
}
size_t offset;
void* ptr;
getVarPtr(handle, ptr, offset);
if (ptr == NULL)
{
return(ERROR_INDEX_OUT_OF_RANGE);
}
return(ERROR_NONE);
}
void ApexEmitterAssetParameters_0p6::getVarPtr(const Handle& handle, void*& ptr, size_t& offset) const
{
ptr = getVarPtrHelper(&ParamLookupTable[0], const_cast<ApexEmitterAssetParameters_0p6::ParametersStruct*>(¶meters()), handle, offset);
}
/* Dynamic Handle Indices */
void ApexEmitterAssetParameters_0p6::freeParameterDefinitionTable(NxParameterized::Traits* traits)
{
if (!traits)
{
return;
}
if (!mBuiltFlag) // Double-checked lock
{
return;
}
NxParameterized::MutexType::ScopedLock lock(mBuiltFlagMutex);
if (!mBuiltFlag)
{
return;
}
for (physx::PxU32 i = 0; i < NumParamDefs; ++i)
{
ParamDefTable[i].~DefinitionImpl();
}
traits->free(ParamDefTable);
mBuiltFlag = false;
}
#define PDEF_PTR(index) (&ParamDefTable[index])
void ApexEmitterAssetParameters_0p6::buildTree(void)
{
physx::PxU32 allocSize = sizeof(NxParameterized::DefinitionImpl) * NumParamDefs;
ParamDefTable = (NxParameterized::DefinitionImpl*)(mParameterizedTraits->alloc(allocSize));
memset(static_cast<void*>(ParamDefTable), 0, allocSize);
for (physx::PxU32 i = 0; i < NumParamDefs; ++i)
{
NX_PARAM_PLACEMENT_NEW(ParamDefTable + i, NxParameterized::DefinitionImpl)(*mParameterizedTraits);
}
// Initialize DefinitionImpl node: nodeIndex=0, longName=""
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[0];
ParamDef->init("", TYPE_STRUCT, "STRUCT", true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("longDescription", "This class contains the parameters for the APEX Emitter asset. The APEX Emitter is sometimes described\nas a shaped APEX Emitter because it contains the box, sphere, and sphere shell shapes. It also\nincludes an explicit shape that allows for preauthored particles positions and velocities and runtime\nparticle injections.\n", true);
HintTable[1].init("shortDescription", "APEX Emitter Asset Parameters", true);
ParamDefTable[0].setHints((const NxParameterized::Hint**)HintPtrTable, 2);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=1, longName="densityRange"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[1];
ParamDef->init("densityRange", TYPE_STRUCT, "rangeStructF32", true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("tweakable", "true", true);
ParamDefTable[1].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#else
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("longDescription", "For an explicit emitter, the density is actually a spawn probability. For the shaped emitters, it represents the density of the particles per unit volume.\n", true);
HintTable[1].init("shortDescription", "Desired density of spawned particles per unit of volume.", true);
HintTable[2].init("tweakable", "true", true);
ParamDefTable[1].setHints((const NxParameterized::Hint**)HintPtrTable, 3);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=2, longName="densityRange.min"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[2];
ParamDef->init("min", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Helpful documentation goes here", true);
ParamDefTable[2].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=3, longName="densityRange.max"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[3];
ParamDef->init("max", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Helpful documentation goes here", true);
ParamDefTable[3].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=4, longName="rateRange"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[4];
ParamDef->init("rateRange", TYPE_STRUCT, "rangeStructF32", true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("tweakable", "true", true);
ParamDefTable[4].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#else
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("longDescription", "The emitter actor will use the maximum rate in the range if it is a rate-based shape, but it will back off to the minimum density if the actor is LOD resource limited.\n", true);
HintTable[1].init("shortDescription", "min if LOD limited / max if rate-based shape", true);
HintTable[2].init("tweakable", "true", true);
ParamDefTable[4].setHints((const NxParameterized::Hint**)HintPtrTable, 3);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=5, longName="rateRange.min"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[5];
ParamDef->init("min", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Helpful documentation goes here", true);
ParamDefTable[5].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=6, longName="rateRange.max"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[6];
ParamDef->init("max", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Helpful documentation goes here", true);
ParamDefTable[6].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=7, longName="lifetimeRange"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[7];
ParamDef->init("lifetimeRange", TYPE_STRUCT, "rangeStructF32", true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("tweakable", "true", true);
ParamDefTable[7].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#else
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("longDescription", "The emitter actor will create particles with a random lifetime (in seconds) within the lifetime range.\n", true);
HintTable[1].init("shortDescription", "Range (in sec) of particle lifetime", true);
HintTable[2].init("tweakable", "true", true);
ParamDefTable[7].setHints((const NxParameterized::Hint**)HintPtrTable, 3);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=8, longName="lifetimeRange.min"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[8];
ParamDef->init("min", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Helpful documentation goes here", true);
ParamDefTable[8].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=9, longName="lifetimeRange.max"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[9];
ParamDef->init("max", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Helpful documentation goes here", true);
ParamDefTable[9].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=10, longName="velocityRange"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[10];
ParamDef->init("velocityRange", TYPE_STRUCT, "rangeStructVec3", true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("gameScale", "true", true);
HintTable[1].init("tweakable", "true", true);
ParamDefTable[10].setHints((const NxParameterized::Hint**)HintPtrTable, 2);
#else
static HintImpl HintTable[4];
static Hint* HintPtrTable[4] = { &HintTable[0], &HintTable[1], &HintTable[2], &HintTable[3], };
HintTable[0].init("gameScale", "true", true);
HintTable[1].init("longDescription", "The emitter actor will create particles with a random velocity within the velocity range.\n", true);
HintTable[2].init("shortDescription", "Random velocity given within range", true);
HintTable[3].init("tweakable", "true", true);
ParamDefTable[10].setHints((const NxParameterized::Hint**)HintPtrTable, 4);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=11, longName="velocityRange.min"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[11];
ParamDef->init("min", TYPE_VEC3, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Helpful documentation goes here", true);
ParamDefTable[11].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=12, longName="velocityRange.max"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[12];
ParamDef->init("max", TYPE_VEC3, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Helpful documentation goes here", true);
ParamDefTable[12].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=13, longName="temperatureRange"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[13];
ParamDef->init("temperatureRange", TYPE_STRUCT, "rangeStructF32", true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("tweakable", "true", true);
ParamDefTable[13].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#else
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("longDescription", "The emitter actor will create particles with a random temperature within the temperature range.\n", true);
HintTable[1].init("shortDescription", "Range of particle temperatures", true);
HintTable[2].init("tweakable", "true", true);
ParamDefTable[13].setHints((const NxParameterized::Hint**)HintPtrTable, 3);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=14, longName="temperatureRange.min"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[14];
ParamDef->init("min", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Helpful documentation goes here", true);
ParamDefTable[14].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=15, longName="temperatureRange.max"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[15];
ParamDef->init("max", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Helpful documentation goes here", true);
ParamDefTable[15].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=16, longName="maxSamples"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[16];
ParamDef->init("maxSamples", TYPE_U32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("defaultValue", physx::PxU64(0), true);
HintTable[1].init("min", physx::PxU64(0), true);
ParamDefTable[16].setHints((const NxParameterized::Hint**)HintPtrTable, 2);
#else
static HintImpl HintTable[4];
static Hint* HintPtrTable[4] = { &HintTable[0], &HintTable[1], &HintTable[2], &HintTable[3], };
HintTable[0].init("defaultValue", physx::PxU64(0), true);
HintTable[1].init("longDescription", "For an explicit emitter, Max Samples is ignored. For shaped emitters, it is the maximum number of particles spawned in a step.\n", true);
HintTable[2].init("min", physx::PxU64(0), true);
HintTable[3].init("shortDescription", "Shaped emitter only. Max particles spawned each step.", true);
ParamDefTable[16].setHints((const NxParameterized::Hint**)HintPtrTable, 4);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=17, longName="lodParamDesc"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[17];
ParamDef->init("lodParamDesc", TYPE_STRUCT, "emitterLodParamDesc", true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("tweakable", "true", true);
ParamDefTable[17].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("shortDescription", "Bias given to this emitter when sharing IOS with another emitter", true);
HintTable[1].init("tweakable", "true", true);
ParamDefTable[17].setHints((const NxParameterized::Hint**)HintPtrTable, 2);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=18, longName="lodParamDesc.version"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[18];
ParamDef->init("version", TYPE_U32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("defaultValue", physx::PxU64(0), true);
ParamDefTable[18].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("defaultValue", physx::PxU64(0), true);
HintTable[1].init("shortDescription", "Helpful documentation goes here", true);
ParamDefTable[18].setHints((const NxParameterized::Hint**)HintPtrTable, 2);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=19, longName="lodParamDesc.maxDistance"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[19];
ParamDef->init("maxDistance", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("defaultValue", physx::PxU64(0), true);
HintTable[1].init("min", physx::PxU64(0), true);
ParamDefTable[19].setHints((const NxParameterized::Hint**)HintPtrTable, 2);
#else
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("defaultValue", physx::PxU64(0), true);
HintTable[1].init("min", physx::PxU64(0), true);
HintTable[2].init("shortDescription", "Objects greater than this distance from the player will be culled more aggressively", true);
ParamDefTable[19].setHints((const NxParameterized::Hint**)HintPtrTable, 3);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=20, longName="lodParamDesc.distanceWeight"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[20];
ParamDef->init("distanceWeight", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("defaultValue", physx::PxU64(1), true);
HintTable[1].init("max", physx::PxU64(1), true);
HintTable[2].init("min", physx::PxU64(0), true);
ParamDefTable[20].setHints((const NxParameterized::Hint**)HintPtrTable, 3);
#else
static HintImpl HintTable[4];
static Hint* HintPtrTable[4] = { &HintTable[0], &HintTable[1], &HintTable[2], &HintTable[3], };
HintTable[0].init("defaultValue", physx::PxU64(1), true);
HintTable[1].init("max", physx::PxU64(1), true);
HintTable[2].init("min", physx::PxU64(0), true);
HintTable[3].init("shortDescription", "Weight given to distance parameter in LOD function", true);
ParamDefTable[20].setHints((const NxParameterized::Hint**)HintPtrTable, 4);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=21, longName="lodParamDesc.speedWeight"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[21];
ParamDef->init("speedWeight", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("defaultValue", physx::PxU64(0), true);
HintTable[1].init("max", physx::PxU64(1), true);
HintTable[2].init("min", physx::PxU64(0), true);
ParamDefTable[21].setHints((const NxParameterized::Hint**)HintPtrTable, 3);
#else
static HintImpl HintTable[4];
static Hint* HintPtrTable[4] = { &HintTable[0], &HintTable[1], &HintTable[2], &HintTable[3], };
HintTable[0].init("defaultValue", physx::PxU64(0), true);
HintTable[1].init("max", physx::PxU64(1), true);
HintTable[2].init("min", physx::PxU64(0), true);
HintTable[3].init("shortDescription", "Weight given to velocity parameter in LOD function", true);
ParamDefTable[21].setHints((const NxParameterized::Hint**)HintPtrTable, 4);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=22, longName="lodParamDesc.lifeWeight"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[22];
ParamDef->init("lifeWeight", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("defaultValue", physx::PxU64(0), true);
HintTable[1].init("max", physx::PxU64(1), true);
HintTable[2].init("min", physx::PxU64(0), true);
ParamDefTable[22].setHints((const NxParameterized::Hint**)HintPtrTable, 3);
#else
static HintImpl HintTable[4];
static Hint* HintPtrTable[4] = { &HintTable[0], &HintTable[1], &HintTable[2], &HintTable[3], };
HintTable[0].init("defaultValue", physx::PxU64(0), true);
HintTable[1].init("max", physx::PxU64(1), true);
HintTable[2].init("min", physx::PxU64(0), true);
HintTable[3].init("shortDescription", "Weight given to life remain parameter in LOD function", true);
ParamDefTable[22].setHints((const NxParameterized::Hint**)HintPtrTable, 4);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=23, longName="lodParamDesc.separationWeight"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[23];
ParamDef->init("separationWeight", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("defaultValue", physx::PxU64(0), true);
HintTable[1].init("max", physx::PxU64(1), true);
HintTable[2].init("min", physx::PxU64(0), true);
ParamDefTable[23].setHints((const NxParameterized::Hint**)HintPtrTable, 3);
#else
static HintImpl HintTable[4];
static Hint* HintPtrTable[4] = { &HintTable[0], &HintTable[1], &HintTable[2], &HintTable[3], };
HintTable[0].init("defaultValue", physx::PxU64(0), true);
HintTable[1].init("max", physx::PxU64(1), true);
HintTable[2].init("min", physx::PxU64(0), true);
HintTable[3].init("shortDescription", "Weight given to separation parameter in LOD function", true);
ParamDefTable[23].setHints((const NxParameterized::Hint**)HintPtrTable, 4);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=24, longName="lodParamDesc.bias"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[24];
ParamDef->init("bias", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("defaultValue", physx::PxU64(1), true);
HintTable[1].init("min", physx::PxU64(0), true);
ParamDefTable[24].setHints((const NxParameterized::Hint**)HintPtrTable, 2);
#else
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("defaultValue", physx::PxU64(1), true);
HintTable[1].init("min", physx::PxU64(0), true);
HintTable[2].init("shortDescription", "Bias given to objects spawned by this emitter, relative to other emitters in the same IOS", true);
ParamDefTable[24].setHints((const NxParameterized::Hint**)HintPtrTable, 3);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=25, longName="iofxAssetName"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[25];
ParamDef->init("iofxAssetName", TYPE_REF, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("DISPLAY_NAME", "Graphics Effect (IOFX)", true);
ParamDefTable[25].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("DISPLAY_NAME", "Graphics Effect (IOFX)", true);
HintTable[1].init("shortDescription", "The name of the instanced object effects asset that will render particles", true);
ParamDefTable[25].setHints((const NxParameterized::Hint**)HintPtrTable, 2);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
static const char* const RefVariantVals[] = { "IOFX" };
ParamDefTable[25].setRefVariantVals((const char**)RefVariantVals, 1);
}
// Initialize DefinitionImpl node: nodeIndex=26, longName="iosAssetName"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[26];
ParamDef->init("iosAssetName", TYPE_REF, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("DISPLAY_NAME", "Particle Simulation (IOS)", true);
ParamDefTable[26].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("DISPLAY_NAME", "Particle Simulation (IOS)", true);
HintTable[1].init("shortDescription", "The asset name of the IOS and the type of IOS that will simulate particles", true);
ParamDefTable[26].setHints((const NxParameterized::Hint**)HintPtrTable, 2);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
static const char* const RefVariantVals[] = { "NxFluidIosAsset", "NxBasicIosAsset", "ParticleIosAsset" };
ParamDefTable[26].setRefVariantVals((const char**)RefVariantVals, 3);
}
// Initialize DefinitionImpl node: nodeIndex=27, longName="geometryType"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[27];
ParamDef->init("geometryType", TYPE_REF, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("INCLUDED", physx::PxU64(1), true);
ParamDefTable[27].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#else
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("INCLUDED", physx::PxU64(1), true);
HintTable[1].init("longDescription", "Specifies the geometry type of the emitter", true);
HintTable[2].init("shortDescription", "Geometry Type", true);
ParamDefTable[27].setHints((const NxParameterized::Hint**)HintPtrTable, 3);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
static const char* const RefVariantVals[] = { "EmitterGeomBoxParams", "EmitterGeomSphereParams", "EmitterGeomSphereShellParams", "EmitterGeomCylinderParams", "EmitterGeomExplicitParams" };
ParamDefTable[27].setRefVariantVals((const char**)RefVariantVals, 5);
}
// Initialize DefinitionImpl node: nodeIndex=28, longName="emitterDuration"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[28];
ParamDef->init("emitterDuration", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("min", physx::PxU64(0), true);
ParamDefTable[28].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#else
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("longDescription", "Specifies a duration (in seconds) that the emitter will emit for after being enabled.\nAfter the specified duration, the emitter will turn off, unless it has already been explicitly turned off via an API call.\nThe special value 0.0f means there is no duration, and the emitter will remain on until explicitly turned off.", true);
HintTable[1].init("min", physx::PxU64(0), true);
HintTable[2].init("shortDescription", "Emitter duration time (in seconds)", true);
ParamDefTable[28].setHints((const NxParameterized::Hint**)HintPtrTable, 3);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=29, longName="emitterVelocityScale"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[29];
ParamDef->init("emitterVelocityScale", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("longDescription", "Scaling value to control how much the velocity of the emitter affects the velocity of the particles.\nA value of 0 means no effect (legacy mode). A value of 1 will add the emitter actor velocity to the velocity produced by velocityRange.", true);
HintTable[1].init("shortDescription", "Scaling value to control how much the velocity of the emitter affects the velocity of the particles.", true);
ParamDefTable[29].setHints((const NxParameterized::Hint**)HintPtrTable, 2);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=30, longName="minSamplingFPS"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[30];
ParamDef->init("minSamplingFPS", TYPE_U32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("defaultValue", physx::PxU64(0), true);
HintTable[1].init("min", physx::PxU64(0), true);
ParamDefTable[30].setHints((const NxParameterized::Hint**)HintPtrTable, 2);
#else
static HintImpl HintTable[4];
static Hint* HintPtrTable[4] = { &HintTable[0], &HintTable[1], &HintTable[2], &HintTable[3], };
HintTable[0].init("defaultValue", physx::PxU64(0), true);
HintTable[1].init("longDescription", "It is used to reduce discontinuity in case of fast moving Emitters, by limiting particles generation step max. time by inverse of this value.\n", true);
HintTable[2].init("min", physx::PxU64(0), true);
HintTable[3].init("shortDescription", "Defines minimum FPS at which particles are generating (0-value means no limit in FPS)", true);
ParamDefTable[30].setHints((const NxParameterized::Hint**)HintPtrTable, 4);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=31, longName="rateVsTimeCurvePoints"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[31];
ParamDef->init("rateVsTimeCurvePoints", TYPE_ARRAY, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[4];
static Hint* HintPtrTable[4] = { &HintTable[0], &HintTable[1], &HintTable[2], &HintTable[3], };
HintTable[0].init("DISPLAY_NAME", "rateVsEmitterDurationCurvePoints", true);
HintTable[1].init("editorCurve", physx::PxU64(1), true);
HintTable[2].init("xAxisLabel", "Emitter Duration", true);
HintTable[3].init("yAxisLabel", "Rate", true);
ParamDefTable[31].setHints((const NxParameterized::Hint**)HintPtrTable, 4);
#else
static HintImpl HintTable[5];
static Hint* HintPtrTable[5] = { &HintTable[0], &HintTable[1], &HintTable[2], &HintTable[3], &HintTable[4], };
HintTable[0].init("DISPLAY_NAME", "rateVsEmitterDurationCurvePoints", true);
HintTable[1].init("editorCurve", physx::PxU64(1), true);
HintTable[2].init("shortDescription", "Control points for rate vs emitter duration curve", true);
HintTable[3].init("xAxisLabel", "Emitter Duration", true);
HintTable[4].init("yAxisLabel", "Rate", true);
ParamDefTable[31].setHints((const NxParameterized::Hint**)HintPtrTable, 5);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
ParamDef->setArraySize(-1);
}
// Initialize DefinitionImpl node: nodeIndex=32, longName="rateVsTimeCurvePoints[]"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[32];
ParamDef->init("rateVsTimeCurvePoints", TYPE_STRUCT, "rateVsTimeCurvePoint", true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[4];
static Hint* HintPtrTable[4] = { &HintTable[0], &HintTable[1], &HintTable[2], &HintTable[3], };
HintTable[0].init("DISPLAY_NAME", "rateVsEmitterDurationCurvePoints", true);
HintTable[1].init("editorCurve", physx::PxU64(1), true);
HintTable[2].init("xAxisLabel", "Emitter Duration", true);
HintTable[3].init("yAxisLabel", "Rate", true);
ParamDefTable[32].setHints((const NxParameterized::Hint**)HintPtrTable, 4);
#else
static HintImpl HintTable[5];
static Hint* HintPtrTable[5] = { &HintTable[0], &HintTable[1], &HintTable[2], &HintTable[3], &HintTable[4], };
HintTable[0].init("DISPLAY_NAME", "rateVsEmitterDurationCurvePoints", true);
HintTable[1].init("editorCurve", physx::PxU64(1), true);
HintTable[2].init("shortDescription", "Control points for rate vs emitter duration curve", true);
HintTable[3].init("xAxisLabel", "Emitter Duration", true);
HintTable[4].init("yAxisLabel", "Rate", true);
ParamDefTable[32].setHints((const NxParameterized::Hint**)HintPtrTable, 5);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=33, longName="rateVsTimeCurvePoints[].x"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[33];
ParamDef->init("x", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
static HintImpl HintTable[2];
static Hint* HintPtrTable[2] = { &HintTable[0], &HintTable[1], };
HintTable[0].init("max", physx::PxU64(1), true);
HintTable[1].init("min", physx::PxU64(0), true);
ParamDefTable[33].setHints((const NxParameterized::Hint**)HintPtrTable, 2);
#else
static HintImpl HintTable[3];
static Hint* HintPtrTable[3] = { &HintTable[0], &HintTable[1], &HintTable[2], };
HintTable[0].init("max", physx::PxU64(1), true);
HintTable[1].init("min", physx::PxU64(0), true);
HintTable[2].init("shortDescription", "Time", true);
ParamDefTable[33].setHints((const NxParameterized::Hint**)HintPtrTable, 3);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// Initialize DefinitionImpl node: nodeIndex=34, longName="rateVsTimeCurvePoints[].y"
{
NxParameterized::DefinitionImpl* ParamDef = &ParamDefTable[34];
ParamDef->init("y", TYPE_F32, NULL, true);
#ifdef NX_PARAMETERIZED_HIDE_DESCRIPTIONS
#else
static HintImpl HintTable[1];
static Hint* HintPtrTable[1] = { &HintTable[0], };
HintTable[0].init("shortDescription", "Rate", true);
ParamDefTable[34].setHints((const NxParameterized::Hint**)HintPtrTable, 1);
#endif /* NX_PARAMETERIZED_HIDE_DESCRIPTIONS */
}
// SetChildren for: nodeIndex=0, longName=""
{
static Definition* Children[14];
Children[0] = PDEF_PTR(1);
Children[1] = PDEF_PTR(4);
Children[2] = PDEF_PTR(7);
Children[3] = PDEF_PTR(10);
Children[4] = PDEF_PTR(13);
Children[5] = PDEF_PTR(16);
Children[6] = PDEF_PTR(17);
Children[7] = PDEF_PTR(25);
Children[8] = PDEF_PTR(26);
Children[9] = PDEF_PTR(27);
Children[10] = PDEF_PTR(28);
Children[11] = PDEF_PTR(29);
Children[12] = PDEF_PTR(30);
Children[13] = PDEF_PTR(31);
ParamDefTable[0].setChildren(Children, 14);
}
// SetChildren for: nodeIndex=1, longName="densityRange"
{
static Definition* Children[2];
Children[0] = PDEF_PTR(2);
Children[1] = PDEF_PTR(3);
ParamDefTable[1].setChildren(Children, 2);
}
// SetChildren for: nodeIndex=4, longName="rateRange"
{
static Definition* Children[2];
Children[0] = PDEF_PTR(5);
Children[1] = PDEF_PTR(6);
ParamDefTable[4].setChildren(Children, 2);
}
// SetChildren for: nodeIndex=7, longName="lifetimeRange"
{
static Definition* Children[2];
Children[0] = PDEF_PTR(8);
Children[1] = PDEF_PTR(9);
ParamDefTable[7].setChildren(Children, 2);
}
// SetChildren for: nodeIndex=10, longName="velocityRange"
{
static Definition* Children[2];
Children[0] = PDEF_PTR(11);
Children[1] = PDEF_PTR(12);
ParamDefTable[10].setChildren(Children, 2);
}
// SetChildren for: nodeIndex=13, longName="temperatureRange"
{
static Definition* Children[2];
Children[0] = PDEF_PTR(14);
Children[1] = PDEF_PTR(15);
ParamDefTable[13].setChildren(Children, 2);
}
// SetChildren for: nodeIndex=17, longName="lodParamDesc"
{
static Definition* Children[7];
Children[0] = PDEF_PTR(18);
Children[1] = PDEF_PTR(19);
Children[2] = PDEF_PTR(20);
Children[3] = PDEF_PTR(21);
Children[4] = PDEF_PTR(22);
Children[5] = PDEF_PTR(23);
Children[6] = PDEF_PTR(24);
ParamDefTable[17].setChildren(Children, 7);
}
// SetChildren for: nodeIndex=31, longName="rateVsTimeCurvePoints"
{
static Definition* Children[1];
Children[0] = PDEF_PTR(32);
ParamDefTable[31].setChildren(Children, 1);
}
// SetChildren for: nodeIndex=32, longName="rateVsTimeCurvePoints[]"
{
static Definition* Children[2];
Children[0] = PDEF_PTR(33);
Children[1] = PDEF_PTR(34);
ParamDefTable[32].setChildren(Children, 2);
}
mBuiltFlag = true;
}
void ApexEmitterAssetParameters_0p6::initStrings(void)
{
}
void ApexEmitterAssetParameters_0p6::initDynamicArrays(void)
{
rateVsTimeCurvePoints.buf = NULL;
rateVsTimeCurvePoints.isAllocated = true;
rateVsTimeCurvePoints.elementSize = sizeof(rateVsTimeCurvePoint_Type);
rateVsTimeCurvePoints.arraySizes[0] = 0;
}
void ApexEmitterAssetParameters_0p6::initDefaults(void)
{
freeStrings();
freeReferences();
freeDynamicArrays();
densityRange.min = 1.0f;
densityRange.max = 1.0f;
rateRange.min = 1.0f;
rateRange.max = 1.0f;
lifetimeRange.min = 1.0f;
lifetimeRange.max = 1.0f;
velocityRange.max.y = 0.0f;
velocityRange.min.x = 0.0f;
velocityRange.min.y = 0.0f;
velocityRange.max.z = 0.0f;
velocityRange.max.x = 0.0f;
velocityRange.min.z = 0.0f;
temperatureRange.min = 1.0f;
temperatureRange.max = 1.0f;
maxSamples = physx::PxU32(0);
lodParamDesc.version = physx::PxU32(0);
lodParamDesc.maxDistance = physx::PxF32(0);
lodParamDesc.distanceWeight = physx::PxF32(1);
lodParamDesc.speedWeight = physx::PxF32(0);
lodParamDesc.lifeWeight = physx::PxF32(0);
lodParamDesc.separationWeight = physx::PxF32(0);
lodParamDesc.bias = physx::PxF32(1);
emitterDuration = physx::PxF32(PX_MAX_F32);
emitterVelocityScale = physx::PxF32(0);
minSamplingFPS = physx::PxU32(0);
initDynamicArrays();
initStrings();
initReferences();
}
void ApexEmitterAssetParameters_0p6::initReferences(void)
{
iofxAssetName = NULL;
iosAssetName = NULL;
geometryType = NULL;
}
void ApexEmitterAssetParameters_0p6::freeDynamicArrays(void)
{
if (rateVsTimeCurvePoints.isAllocated && rateVsTimeCurvePoints.buf)
{
mParameterizedTraits->free(rateVsTimeCurvePoints.buf);
}
}
void ApexEmitterAssetParameters_0p6::freeStrings(void)
{
}
void ApexEmitterAssetParameters_0p6::freeReferences(void)
{
if (iofxAssetName)
{
iofxAssetName->destroy();
}
if (iosAssetName)
{
iosAssetName->destroy();
}
if (geometryType)
{
geometryType->destroy();
}
}
} // namespace apex
} // namespace physx
| [
"dkroell@acm.org"
] | dkroell@acm.org |
d85ef9ffac57e36c33869949b7336a032656a537 | 20a209dc3d68447bfb2ebcd32165627097ed7f68 | /src/plugins/FindCommand/FindPlugin.h | 8b5058a045962aa708277ec24a509f3143841929 | [] | no_license | refaqtor/ProjectConceptor | f25512176518b05d64554b95a8cd7412c5fee7e0 | 4f481d5a53a341b9ac194293a62bbd28ad2dcfad | refs/heads/master | 2022-04-21T16:10:44.538439 | 2020-04-16T07:39:09 | 2020-04-16T07:39:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 681 | h | #ifndef FIND_PLUGIN_H
#define FIND_PLUGIN_H
/*
* @author Paradoxon powered by Jesus Christ
*/
#include "BasePlugin.h"
#include "Find.h"
class FindPlugin : public BasePlugin
{
public:
FindPlugin(image_id id);
//++++++++++++++++BasePlugin
virtual uint32 GetType(){return P_C_COMMANDO_PLUGIN_TYPE;};
virtual char* GetVersionsString(void){return "0.01preAlpha";};
virtual char* GetAutor(void){return "Paradoxon";};
virtual char* GetName(void){return "Find";};
virtual char* GetDescription(void){return "This is a simple Find Command for ProjectConceptor with basic funktionality";};
virtual void* GetNewObject(void *value){return new Find();};
};
#endif
| [
"paradoxon@f08798fa-4112-0410-b753-e4f865caae7a"
] | paradoxon@f08798fa-4112-0410-b753-e4f865caae7a |
012aadb784fa909a81885e18c7cfdf11fb18ef14 | ad4a9153905ceb08944123442a71f2dfbd591de9 | /prores_encoder2.gen/sources_1/bd/design_1/ip/design_1_axi_smc_0/sim/design_1_axi_smc_0_sc.cpp | 88e9de641b765b0cbface5772eee98ce4a706cd1 | [] | no_license | y38y38/verilog_prores_encoder | 750db4ad10e1bee24e429ae343e71816f7a93d07 | 511968ae6858d5dc3f2454e11ce52f52fed11c8f | refs/heads/main | 2023-08-21T13:18:44.876714 | 2021-09-29T21:11:34 | 2021-09-29T21:11:34 | 411,826,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,430 | cpp | // (c) Copyright 1995-2021 Xilinx, Inc. All rights reserved.
//
// This file contains confidential and proprietary information
// of Xilinx, Inc. and is protected under U.S. and
// international copyright and other intellectual property
// laws.
//
// DISCLAIMER
// This disclaimer is not a license and does not grant any
// rights to the materials distributed herewith. Except as
// otherwise provided in a valid license issued to you by
// Xilinx, and to the maximum extent permitted by applicable
// law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
// WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
// AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
// BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
// INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
// (2) Xilinx shall not be liable (whether in contract or tort,
// including negligence, or under any other theory of
// liability) for any loss or damage of any kind or nature
// related to, arising under or in connection with these
// materials, including for any direct, or any indirect,
// special, incidental, or consequential loss or damage
// (including loss of data, profits, goodwill, or any type of
// loss or damage suffered as a result of any action brought
// by a third party) even if such damage or loss was
// reasonably foreseeable or Xilinx had been advised of the
// possibility of the same.
//
// CRITICAL APPLICATIONS
// Xilinx products are not designed or intended to be fail-
// safe, or for use in any application requiring fail-safe
// performance, such as life-support or safety devices or
// systems, Class III medical devices, nuclear facilities,
// applications related to the deployment of airbags, or any
// other applications that could lead to death, personal
// injury, or severe property or environmental damage
// (individually and collectively, "Critical
// Applications"). Customer assumes the sole risk and
// liability of any use of Xilinx products in Critical
// Applications, subject only to applicable laws and
// regulations governing limitations on product liability.
//
// THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
// PART OF THIS FILE AT ALL TIMES.
//
// DO NOT MODIFY THIS FILE.
#include "design_1_axi_smc_0_sc.h"
#include "smartconnect.h"
#include <map>
#include <string>
design_1_axi_smc_0_sc::design_1_axi_smc_0_sc(const sc_core::sc_module_name& nm) : sc_core::sc_module(nm), mp_impl(NULL)
{
// configure connectivity manager
xsc::utils::xsc_sim_manager::addInstance("design_1_axi_smc_0", this);
// initialize module
xsc::common_cpp::properties model_param_props;
model_param_props.addLong("HAS_RESET", "1");
model_param_props.addString("TLM_COMPONENT_NAME", "design_1_axi_smc_0");
mp_impl = new smartconnect("inst", model_param_props);
// initialize AXI sockets
S00_AXI_tlm_aximm_read_socket = mp_impl->S00_AXI_tlm_aximm_read_socket;
S00_AXI_tlm_aximm_write_socket = mp_impl->S00_AXI_tlm_aximm_write_socket;
M00_AXI_tlm_aximm_read_socket = mp_impl->M00_AXI_tlm_aximm_read_socket;
M00_AXI_tlm_aximm_write_socket = mp_impl->M00_AXI_tlm_aximm_write_socket;
M01_AXI_tlm_aximm_read_socket = mp_impl->M01_AXI_tlm_aximm_read_socket;
M01_AXI_tlm_aximm_write_socket = mp_impl->M01_AXI_tlm_aximm_write_socket;
}
design_1_axi_smc_0_sc::~design_1_axi_smc_0_sc()
{
xsc::utils::xsc_sim_manager::clean();
delete mp_impl;
}
| [
"y38y38@gmail.com"
] | y38y38@gmail.com |
8d70158d351478639a1d8ab55fd6d1ac51e29cd0 | 837c4978ebabe3f0101007d16f16798b849d8403 | /chapter08/8.10.cpp | 5857efd4dfc8031e17d5a469df64ab893f9f9e1d | [] | no_license | plugn/Cpp-Primer | 924904e153e2b75aa63d16d2127058f43beb7b42 | 42f414fc7fecbb4548ca42c9215290286008b94f | refs/heads/master | 2020-12-09T13:04:58.925614 | 2020-01-10T19:51:34 | 2020-01-10T19:51:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 990 | cpp | /*
* Exercise 8.10: Write a program to store each line from a file in a
* vector<string>. Now use an istringstream to read each element from the
* vector a word at a time.
*
* By Faisal Saadatmand
*/
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
std::istream &printWords(std::istream &);
std::istream &printWords(std::istream &is)
{
std::string word;
while (is >> word)
std::cout << word << '\n';
is.clear();
return is;
}
int main(int argc, char **argv)
{
if (argc != 2) {
std::cerr << "Usage: " + std::string(*argv) + " file\n";
return -1;
}
auto p = argv + 1;
std::ifstream infile(*p);
if (!infile) {
std::cerr << "Couldn't open " + std::string(*p) << '\n';
return -1;
}
std::string line;
std::vector<std::string> content;
while (infile >> line)
content.push_back(line);
std::string word;
for (const auto &element : content) {
std::istringstream word(element);
printWords(word);
}
return 0;
}
| [
"cdude996@gmail.com"
] | cdude996@gmail.com |
b7b8072928d7600fe1350dc782aaf6159f4f9ba9 | 83f461519bff4467a1a175ca686ad06a2a7e257b | /src/mlpack/methods/range_search/range_search_main.cpp | 4b6abc3d5b22ec300c7177cbd7276e39f1a524e3 | [] | no_license | Yashwants19/RcppMLPACK | 3af64c6b1327e895b99637649591d1671adf53a5 | 2d256c02058aa7a183d182079acff9037a80b662 | refs/heads/master | 2022-12-04T05:06:17.578747 | 2020-07-22T12:45:42 | 2020-07-22T12:45:42 | 252,217,735 | 9 | 0 | null | 2020-08-18T06:15:14 | 2020-04-01T15:41:38 | C++ | UTF-8 | C++ | false | false | 12,449 | cpp | /**
* @file methods/range_search/range_search_main.cpp
* @author Ryan Curtin
* @author Matthew Amidon
*
* Implementation of the RangeSearch executable. Allows some number of standard
* options.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#include <mlpack/prereqs.hpp>
#include <mlpack/core/util/io.hpp>
#include <mlpack/core/util/mlpack_main.hpp>
#include <mlpack/core/metrics/lmetric.hpp>
#include <mlpack/core/tree/cover_tree.hpp>
#include "range_search.hpp"
#include "rs_model.hpp"
using namespace std;
using namespace mlpack;
using namespace mlpack::range;
using namespace mlpack::tree;
using namespace mlpack::metric;
using namespace mlpack::util;
// Information about the program itself.
PROGRAM_INFO("Range Search",
// Short description.
"An implementation of range search with single-tree and dual-tree "
"algorithms. Given a set of reference points and a set of query points and"
" a range, this can find the set of reference points within the desired "
"range for each query point, and any trees built during the computation can"
" be saved for reuse with future range searches.",
// Long description.
"This program implements range search with a Euclidean distance metric. "
"For a given query point, a given range, and a given set of reference "
"points, the program will return all of the reference points with distance "
"to the query point in the given range. This is performed for an entire "
"set of query points. You may specify a separate set of reference and query"
" points, or only a reference set -- which is then used as both the "
"reference and query set. The given range is taken to be inclusive (that "
"is, points with a distance exactly equal to the minimum and maximum of the"
" range are included in the results).",
// Example.
"For example, the following will calculate the points within the range [2, "
"5] of each point in "+ PRINT_DATASET("input") + " and store the"
" distances in" + PRINT_DATASET("distances") + " and the neighbors in "
+ PRINT_DATASET("neighbors") +
"\n\n" +
PRINT_CALL("range_search", "min", 2, "max", 5, "distances_file", "input",
"distances_file", "distances", "neighbors_file", "neighbors") +
"\n\n"
"The output files are organized such that line i corresponds to the points "
"found for query point i. Because sometimes 0 points may be found in the "
"given range, lines of the output files may be empty. The points are not "
"ordered in any specific manner."
"\n\n"
"Because the number of points returned for each query point may differ, the"
" resultant CSV-like files may not be loadable by many programs. However, "
"at this time a better way to store this non-square result is not known. "
"As a result, any output files will be written as CSVs in this manner, "
"regardless of the given extension.",
SEE_ALSO("@knn", "#knn"),
SEE_ALSO("Range searching on Wikipedia",
"https://en.wikipedia.org/wiki/Range_searching"),
SEE_ALSO("Tree-independent dual-tree algorithms (pdf)",
"http://proceedings.mlr.press/v28/curtin13.pdf"),
SEE_ALSO("mlpack::range::RangeSearch C++ class documentation",
"@doxygen/classmlpack_1_1range_1_1RangeSearch.html"));
// Define our input parameters that this program will take.
PARAM_MATRIX_IN("reference", "Matrix containing the reference dataset.", "r");
PARAM_STRING_OUT("distances_file", "File to output distances into.", "d");
PARAM_STRING_OUT("neighbors_file", "File to output neighbors into.", "n");
// The option exists to load or save models.
PARAM_MODEL_IN(RSModel, "input_model", "File containing pre-trained range "
"search model.", "m");
PARAM_MODEL_OUT(RSModel, "output_model", "If specified, the range search model "
"will be saved to the given file.", "M");
// The user may specify a query file of query points and a range to search for.
PARAM_MATRIX_IN("query", "File containing query points (optional).", "q");
PARAM_DOUBLE_IN("max", "Upper bound in range (if not specified, +inf will be "
"used.", "U", 0.0);
PARAM_DOUBLE_IN("min", "Lower bound in range.", "L", 0.0);
// The user may specify the type of tree to use, and a few parameters for tree
// building.
PARAM_STRING_IN("tree_type", "Type of tree to use: 'kd', 'vp', 'rp', 'max-rp', "
"'ub', 'cover', 'r', 'r-star', 'x', 'ball', 'hilbert-r', 'r-plus', "
"'r-plus-plus', 'oct'.", "t", "kd");
PARAM_INT_IN("leaf_size", "Leaf size for tree building (used for kd-trees, "
"vp trees, random projection trees, UB trees, R trees, R* trees, X trees, "
"Hilbert R trees, R+ trees, R++ trees, and octrees).", "l", 20);
PARAM_FLAG("random_basis", "Before tree-building, project the data onto a "
"random orthogonal basis.", "R");
PARAM_INT_IN("seed", "Random seed (if 0, std::time(NULL) is used).", "s", 0);
// Search settings.
PARAM_FLAG("naive", "If true, O(n^2) naive mode is used for computation.", "N");
PARAM_FLAG("single_mode", "If true, single-tree search is used (as opposed to "
"dual-tree search).", "S");
static void mlpackMain()
{
if (IO::GetParam<int>("seed") != 0)
math::RandomSeed((size_t) IO::GetParam<int>("seed"));
else
math::RandomSeed((size_t) std::time(NULL));
// A user cannot specify both reference data and a model.
RequireOnlyOnePassed({ "reference", "input_model" }, true);
ReportIgnoredParam({{ "input_model", true }}, "tree_type");
ReportIgnoredParam({{ "input_model", true }}, "random_basis");
ReportIgnoredParam({{ "input_model", true }}, "leaf_size");
ReportIgnoredParam({{ "input_model", true }}, "naive");
// The user must give something to do...
RequireAtLeastOnePassed({ "min", "max", "output_model" }, false, "no results "
"will be saved");
// If the user specifies a range but not output files, they should be warned.
if (IO::HasParam("min") || IO::HasParam("max"))
{
RequireAtLeastOnePassed({ "neighbors_file", "distances_file" }, false,
"no range search results will be saved");
}
if (!IO::HasParam("min") && !IO::HasParam("max"))
{
ReportIgnoredParam("neighbors_file", "no range is specified for searching");
ReportIgnoredParam("distances_file", "no range is specified for searching");
}
if (IO::HasParam("input_model") &&
(IO::HasParam("min") || IO::HasParam("max")))
{
RequireAtLeastOnePassed({ "query" }, true, "query set must be passed if "
"searching is to be done");
}
// Sanity check on leaf size.
int lsInt = IO::GetParam<int>("leaf_size");
RequireParamValue<int>("leaf_size", [](int x) { return x > 0; }, true,
"leaf size must be greater than 0");
// We either have to load the reference data, or we have to load the model.
RSModel* rs;
const bool naive = IO::HasParam("naive");
const bool singleMode = IO::HasParam("single_mode");
if (IO::HasParam("reference"))
{
// Get all the parameters.
const string treeType = IO::GetParam<string>("tree_type");
RequireParamInSet<string>("tree_type", { "kd", "cover", "r", "r-star",
"ball", "x", "hilbert-r", "r-plus", "r-plus-plus", "vp", "rp", "max-rp",
"ub", "oct" }, true, "unknown tree type");
const bool randomBasis = IO::HasParam("random_basis");
rs = new RSModel();
RSModel::TreeTypes tree = RSModel::KD_TREE;
if (treeType == "kd")
tree = RSModel::KD_TREE;
else if (treeType == "cover")
tree = RSModel::COVER_TREE;
else if (treeType == "r")
tree = RSModel::R_TREE;
else if (treeType == "r-star")
tree = RSModel::R_STAR_TREE;
else if (treeType == "ball")
tree = RSModel::BALL_TREE;
else if (treeType == "x")
tree = RSModel::X_TREE;
else if (treeType == "hilbert-r")
tree = RSModel::HILBERT_R_TREE;
else if (treeType == "r-plus")
tree = RSModel::R_PLUS_TREE;
else if (treeType == "r-plus-plus")
tree = RSModel::R_PLUS_PLUS_TREE;
else if (treeType == "vp")
tree = RSModel::VP_TREE;
else if (treeType == "rp")
tree = RSModel::RP_TREE;
else if (treeType == "max-rp")
tree = RSModel::MAX_RP_TREE;
else if (treeType == "ub")
tree = RSModel::UB_TREE;
else if (treeType == "oct")
tree = RSModel::OCTREE;
rs->TreeType() = tree;
rs->RandomBasis() = randomBasis;
Log::Info << "Using reference data from "
<< IO::GetPrintableParam<arma::mat>("reference") << "." << endl;
arma::mat referenceSet = std::move(IO::GetParam<arma::mat>("reference"));
const size_t leafSize = size_t(lsInt);
rs->BuildModel(std::move(referenceSet), leafSize, naive, singleMode);
}
else
{
// Load the model from file.
rs = IO::GetParam<RSModel*>("input_model");
Log::Info << "Using range search model from '"
<< IO::GetPrintableParam<RSModel*>("input_model") << "' ("
<< "trained on " << rs->Dataset().n_rows << "x" << rs->Dataset().n_cols
<< " dataset)." << endl;
// Adjust singleMode and naive if necessary.
rs->SingleMode() = IO::HasParam("single_mode");
rs->Naive() = IO::HasParam("naive");
rs->LeafSize() = size_t(lsInt);
}
// Perform search, if desired.
if (IO::HasParam("min") || IO::HasParam("max"))
{
const double min = IO::GetParam<double>("min");
const double max = IO::HasParam("max") ? IO::GetParam<double>("max") :
DBL_MAX;
math::Range r(min, max);
arma::mat queryData;
if (IO::HasParam("query"))
{
Log::Info << "Using query data from "
<< IO::GetPrintableParam<arma::mat>("query") << "." << endl;
queryData = std::move(IO::GetParam<arma::mat>("query"));
}
// Naive mode overrides single mode.
if (singleMode && naive)
Log::Warn << PRINT_PARAM_STRING("single_mode") << " ignored because "
<< PRINT_PARAM_STRING("naive") << " is present." << endl;
// Now run the search.
vector<vector<size_t>> neighbors;
vector<vector<double>> distances;
if (IO::HasParam("query"))
rs->Search(std::move(queryData), r, neighbors, distances);
else
rs->Search(r, neighbors, distances);
Log::Info << "Search complete." << endl;
// Save output, if desired. We have to do this by hand.
if (IO::HasParam("distances_file"))
{
const string distancesFile = IO::GetParam<string>("distances_file");
fstream distancesStr(distancesFile.c_str(), fstream::out);
if (!distancesStr.is_open())
{
Log::Warn << "Cannot open file '" << distancesFile << "' to save output"
<< " distances to!" << endl;
}
else
{
// Loop over each point.
for (size_t i = 0; i < distances.size(); ++i)
{
// Store the distances of each point. We may have 0 points to store,
// so we must account for that possibility.
for (size_t j = 0; j + 1 < distances[i].size(); ++j)
distancesStr << distances[i][j] << ", ";
if (distances[i].size() > 0)
distancesStr << distances[i][distances[i].size() - 1];
distancesStr << endl;
}
distancesStr.close();
}
}
if (IO::HasParam("neighbors_file"))
{
const string neighborsFile = IO::GetParam<string>("neighbors_file");
fstream neighborsStr(neighborsFile.c_str(), fstream::out);
if (!neighborsStr.is_open())
{
Log::Warn << "Cannot open file '" << neighborsFile << "' to save output"
<< " neighbor indices to!" << endl;
}
else
{
// Loop over each point.
for (size_t i = 0; i < neighbors.size(); ++i)
{
// Store the neighbors of each point. We may have 0 points to store,
// so we must account for that possibility.
for (size_t j = 0; j + 1 < neighbors[i].size(); ++j)
neighborsStr << neighbors[i][j] << ", ";
if (neighbors[i].size() > 0)
neighborsStr << neighbors[i][neighbors[i].size() - 1];
neighborsStr << endl;
}
neighborsStr.close();
}
}
}
// Save the output model.
IO::GetParam<RSModel*>("output_model") = rs;
}
| [
"yashwantsingh.sngh@gmail.com"
] | yashwantsingh.sngh@gmail.com |
06a6d4af12534fd3adcf91cd9f8c9c7914d728bb | ca6ee448acfe0f94ab51b8070ecd8f5b8713c00c | /src/SimpleModel.h | 84380e3220749ee7561fd1cc749886e8257d967c | [] | no_license | sm1f/genClSim | fbd8afcbc90ca643baf4273ea981364997b082e5 | b8d8b2a8cd9e9407577df476872b458660b16ae6 | refs/heads/master | 2020-06-15T12:33:48.075727 | 2019-07-06T02:58:18 | 2019-07-06T02:58:18 | 195,300,380 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 282 | h | // CopyRight Stephen Morrisson 2019
// All rights reserved.
#ifndef __SIMPLE_MODEL_H__
#define __SIMPLE_MODEL_H__
#include "common.h"
#include "SemBase.h"
class SimpleModel : public SemBase
{
public:
SimpleModel();
virtual bool setup();
};
#endif // __SIMPLE_MODEL_H__
| [
"stephen_morrisson@yahoo.com"
] | stephen_morrisson@yahoo.com |
7bac50d9f4f4027920581fe277b0f82444284f1b | aea065a58ac82c28e5d5967e8dfc962591adc281 | /16-Fibonacci-Series-and-Prime-no.cpp | 47842097e1b05c5d2c68b1e73caaefdd35a1bd5e | [] | no_license | VA-007/CP-Code | d03bfeb941a48ab7a8204b72079b7dcb36f9919d | e59d0a6d3fd4fac152e9c40472aff0b33d6064a7 | refs/heads/master | 2023-08-02T09:51:33.812560 | 2021-09-30T07:21:38 | 2021-09-30T07:21:38 | 326,954,982 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 636 | cpp | #include <iostream>
using namespace std;
int main()
{
// Fibonacci
// long double f1 = 0, f2 = 1, f3;
// int n, k;
// cin>>n;
// cout<<f1<<"\n"<<f2<<"\n";
// k = 2;
// while(k<n)
// {
// f3 = f1 + f2;
// f1 = f2;
// f2 = f3;
// cout<<f3<<"\n";
// k++;
// }
// Prime Number
// int n, t = 2;
// cin >> n;
// for (size_t i = 2; i <= n / 2; i++)
// {
// if (n % i == 0)
// {
// t++;
// }
// }
// if (t == 2)
// {
// cout << "Prime";
// }
// else
// {
// cout << "Not Prime";
// }
return 0;
}
| [
"noreply@github.com"
] | VA-007.noreply@github.com |
73fac84f59e6bbbd083cb231e0ba9365d3254b39 | ee76147a967e323b8f2858996815d7fa5ed37419 | /source/loonyland2/title.cpp | 1ea0b357ecccf4af2812216d918a15ac9a63c1b7 | [
"MIT"
] | permissive | glennneiger/HamSandwich | 4622bffdfaa1911fd051029264a43b61e018a91f | bc1878de81797a72c18d476ad2d274e7fd604244 | refs/heads/master | 2020-05-31T14:05:37.106953 | 2019-06-04T23:30:36 | 2019-06-04T23:30:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,570 | cpp | #include "title.h"
#include "game.h"
#include "jamulfmv.h"
#include "pause.h"
#include "options.h"
#include "pause.h"
#include "credits.h"
#include "music.h"
#include "achieve.h"
#include "gallery.h"
#include "leveldef.h"
#include "lsdir.h"
#if __linux__
#include <unistd.h>
#endif
#ifdef DIRECTORS
#define VERSION_NO "Version 1.2CE"
#else
#define VERSION_NO "Version 1.0O"
#endif
typedef struct save_t
{
char name[16];
byte realNum;
byte newbie;
byte level;
byte madcap;
dword playtime;
float percentage;
byte mod[3];
char campName[64];
} save_t;
static byte oldc=0;
static byte saveMod[3];
byte gameToLoad;
static word timeToCred;
static byte cursor,submode,subcursor,curChar,numChars;
byte *backScr;
int numRuns;
static int ofsX;
char saveName[16];
static byte whoToDelete,helpTime;
#ifndef DIRECTORS
char menuChoices[MENU_CHOICES][16]={
"Play",
"Erase Character",
"Achievements",
"Game Options",
"Exit",
};
#else
char menuChoices[MENU_CHOICES][16]={
"Play",
"Erase Character",
"Achievements",
"Gallery",
"Editor",
"Game Options",
"Exit",
};
#endif
typedef struct addon_t
{
char filename[12];
char dispName[34];
} addon_t;
word addOnCount=0,addOnChoice=0;
addon_t *addOnList=NULL;
save_t save[MAX_CHARS];
char *FetchAddOnName(void)
{
return addOnList[addOnChoice].filename;
}
void ClearAddOns(void)
{
if(addOnList!=NULL)
{
free(addOnList);
addOnList=NULL;
addOnCount=0;
}
}
void GetAddOn(char *name,int spot)
{
FILE *f;
char line[256];
int pos;
if(spot>=addOnCount || spot<0)
return;
addOnList[spot].dispName[0]='\0';
addOnList[spot].filename[0]='\0';
sprintf(line,"addons/%s",name);
f=fopen(line,"rt");
if(!f)
{
return;
}
if(fscanf(f,"%[^\n]\n",line)!=EOF)
{
strncpy(addOnList[spot].dispName,line,32);
addOnList[spot].dispName[32]='\0';
pos=strcspn(name,".");
name[pos]='\0';
pos=strcspn(name,"_");
if(strlen(&name[pos+1])>10)
{
addOnList[spot].dispName[0]='\0';
addOnList[spot].filename[0]='\0';
}
else
strcpy(addOnList[spot].filename,&name[pos+1]);
}
fclose(f);
}
void GetAddOns(void)
{
int done;
// count up how many there are to deal with
ClearAddOns();
for (const char* name : filterdir("addons", ".txt"))
{
if (strncmp(name, "lvl_", 4))
continue;
addOnCount++;
}
addOnCount++;
addOnList=(addon_t *)malloc(sizeof(addon_t)*addOnCount);
strcpy(addOnList[0].dispName,"Original");
addOnList[0].filename[0]='\0';
done=1;
for (char* name : filterdir("addons", ".txt"))
{
if (strncmp(name, "lvl_", 4))
continue;
GetAddOn(name, done);
done++;
}
}
void GetSavesForMenu(void)
{
FILE *f;
int i,n,hole,j;
char txt[64];
player_t p;
curChar=0;
n=0;
hole=-1;
for(i=0;i<MAX_CHARS;i++)
{
sprintf(txt,"profiles/char%02d.loony",i+1);
f=fopen(txt,"rb");
if(!f && hole==-1)
{
hole=i;
}
else if(f)
{
fread(&p,sizeof(player_t),1,f);
fclose(f);
save[n].percentage=CalcPercent(&p);
save[n].newbie=0;
save[n].realNum=i;
save[n].playtime=p.playClock;
save[n].level=p.level;
save[n].madcap=p.var[VAR_MADCAP];
save[n].mod[0]=p.var[VAR_MODIFIER+0];
save[n].mod[1]=p.var[VAR_MODIFIER+1];
save[n].mod[2]=p.var[VAR_MODIFIER+2];
strcpy(save[n].name,p.profile);
save[n].campName[0]='\0';
for(j=1;j<addOnCount;j++)
if(!strcmp(p.addonName,addOnList[j].filename))
strcpy(save[n].campName,addOnList[j].dispName);
n++;
}
}
if(hole!=-1)
{
save[n].percentage=0.0;
strcpy(save[n].name,"Loony");
save[n].newbie=1;
save[n].mod[0]=0;
save[n].mod[1]=0;
save[n].mod[2]=0;
save[n].realNum=(byte)hole;
save[n].campName[0]='\0';
n++;
}
numChars=n;
}
void InitMainMenu(MGLDraw *mgl)
{
int i;
timeToCred=0;
GetAddOns();
GetSavesForMenu();
helpTime=0;
saveName[0]='\0';
ofsX=0;
submode=0;
subcursor=0;
cursor=0;
mgl->LoadBMP(TITLEBMP);
mgl->LastKeyPressed();
GetTaps();
oldc=255;
ApplyControlSettings();
JamulSoundVolume(opt.sound*2);
SetMusicVolume(opt.music*2);
backScr=(byte *)malloc(640*480);
if(!backScr)
FatalError("Out of memory!");
curChar=0;
for(i=0;i<numChars;i++)
if(save[i].realNum==opt.lastProfile)
{
curChar=i;
whoToDelete=i;
}
for(i=0;i<480;i++)
memcpy(&backScr[i*640],mgl->GetScreen()+mgl->GetWidth()*i,640);
}
char *ModifierList(byte n)
{
static char s[64];
int i;
i=0;
s[0]='\0';
if(save[n].mod[0])
{
i++;
strcat(s,ModifierName(save[n].mod[0]));
}
if(save[n].mod[1])
{
if(i>0)
strcat(s,", ");
i++;
strcat(s,ModifierName(save[n].mod[1]));
}
if(save[n].mod[2])
{
if(i>0)
strcat(s,", ");
i++;
strcat(s,ModifierName(save[n].mod[2]));
}
if(save[n].madcap)
{
if(i>0)
strcat(s,", ");
i++;
strcat(s,"MADCAP!");
}
if(i==0)
strcat(s,"No Modifiers");
return s;
}
void ShowCharacter(int x,int y,byte n,byte on,MGLDraw *mgl)
{
char s[32];
int yy;
x-=125;
if(save[n].newbie)
{
if(on)
PauseBox(x-4,y-4,x+250+4,y+100+4,5*32+16);
PauseBox(x,y,x+250,y+100,234-5);
CenterPrintGlow(x+125,y+8,"New Character",0,0);
}
else
{
if(on)
PauseBox(x-4,y-4,x+250+4,y+100+4,5*32+16);
PauseBox(x,y,x+250,y+100,234);
CenterPrintGlow(x+125,y+2,save[n].name,0,0);
CenterPrintGlow(x+125,y+28,ModifierList(n),0,1);
yy=y+53;
if(save[n].campName[0]!='\0')
{
CenterPrintGlow(x+125,y+42,save[n].campName,0,1);
}
sprintf(s,"Level %d",save[n].level);
CenterPrintGlow(x+125,yy,s,0,0);
sprintf(s,"%d:%02d",save[n].playtime/(60*60*30),(save[n].playtime/(60*30))%60);
PrintGlow(x+8,yy+22,s,0,0);
if(save[n].madcap)
sprintf(s,"*%03.0f%%",save[n].percentage);
else
sprintf(s,"%03.0f%%",save[n].percentage);
RightPrintGlow(x+250-8,yy+22,s,0,0);
}
}
void CharaList(MGLDraw *mgl)
{
int i;
byte n;
int x,y;
for(i=5;i>0;i--)
{
n=curChar+i;
if(n<numChars)
{
x=320+ofsX+i*100;
y=200+((320-x)*(320-x))/800;
ShowCharacter(x,y,n,0,mgl);
}
n=curChar-i;
if(n<numChars)
{
x=320+ofsX-i*100;
y=200+((320-x)*(320-x))/800;
ShowCharacter(x,y,n,0,mgl);
}
}
ShowCharacter(320+ofsX,200+abs(ofsX)/4,curChar,1,mgl);
}
void EraseCharDisplay(MGLDraw *mgl)
{
char s[32];
int x,y;
x=-70;
y=180;
PauseBox(x+180,y+80,x+600,y+240,234);
sprintf(s,"Really erase '%s'?",save[curChar].name);
CenterPrintGlow(x+390,y+100,s,0,0);
if(subcursor==0)
PauseBox(x+250,y+200,x+380,y+235,32*5+16);
else
PauseBox(x+250,y+200,x+380,y+235,240);
CenterPrintDark(x+315,y+204,"Yes",0);
if(subcursor==1)
PauseBox(x+400,y+200,x+530,y+235,32*5+16);
else
PauseBox(x+400,y+200,x+530,y+235,240);
CenterPrintDark(x+465,y+204,"No",0);
}
void NewCharButton(int x,int y,byte on,char *s,MGLDraw *mgl)
{
if(on)
PauseBox(x,y,x+100,y+35,32*5+16);
else
PauseBox(x,y,x+100,y+35,234+6);
CenterPrintDark(x+50,y+5,s,0);
}
void NewCharDisplay(MGLDraw *mgl)
{
static byte flip=0;
flip=1-flip;
PauseBox(120,50,520,400,234);
CenterPrintGlow(320,58,"New Game",0,0);
NewCharButton(125,100,(subcursor==0),"Name",mgl);
NewCharButton(125,140,(subcursor==1),"Mod1",mgl);
PrintDark(250,145,ModifierName(save[curChar].mod[0]),0);
NewCharButton(125,180,(subcursor==2),"Mod2",mgl);
PrintDark(250,185,ModifierName(save[curChar].mod[1]),0);
NewCharButton(125,220,(subcursor==3),"Mod3",mgl);
PrintDark(250,225,ModifierName(save[curChar].mod[2]),0);
switch(subcursor)
{
case 0:
PrintRectBlack2(125,265,515,350,"Type in a name for this profile. Up and Down will select other options.",14,1);
break;
case 1:
case 2:
case 3:
PrintRectBlack2(125,265,515,320,"Press Left or Right to flip through Modifiers. You may apply up to 3 Modifiers to your game. You'll unlock more as you play.",14,1);
PrintRectBlack2(125,320,515,355,ModifierDesc(save[curChar].mod[subcursor-1]),14,1);
break;
case 4:
#ifdef DIRECTORS
PrintRectBlack2(125,265,515,350,"Press Left or Right to choose which campaign to play. \"Original\" is the normal game. Any other campaign is at your own risk! Press Fire to start playing!! Or ESC to cancel.",14,1);
#else
PrintRectBlack2(125,265,515,350,"Press Fire to start playing!! Or ESC to cancel.",14,1);
#endif
break;
}
PrintDark(250,105,save[curChar].name,0);
if(flip && subcursor==0)
PrintDark(250+GetStrLength(save[curChar].name,0),105,"_",0);
NewCharButton(125,355,(subcursor==4),"Go!",mgl);
#ifdef DIRECTORS
PrintDark(230,360,"Campaign to play:",1);
PrintDark(230,376,addOnList[addOnChoice].dispName,1);
#endif
}
void MainMenuDisplay(MGLDraw *mgl)
{
int i;
char s[96];
for(i=0;i<480;i++)
memcpy(mgl->GetScreen()+mgl->GetWidth()*i,&backScr[i*640],640);
// version #:
RightPrint(638,3,VERSION_NO,1,1);
RightPrint(637,2,VERSION_NO,0,1);
// Copyright:
strcpy(s,"Copyright 2007, Hamumu Software");
Print(2-1,467-1,s,0,1);
Print(2+1,467+1,s,0,1);
Print(2+1,467-1,s,0,1);
Print(2-1,467+1,s,0,1);
PrintDark(2,467,s,1);
CenterPrint(320,4,LevelError(),0,1);
if(submode==0 && helpTime>90)
{
strcpy(s,"Left & Right to change profile, Up & Down to select options, Fire or Enter to go!");
CenterPrint(320-1,170-1,s,0,1);
CenterPrint(320+1,170+1,s,0,1);
CenterPrint(320+1,170-1,s,0,1);
CenterPrint(320-1,170+1,s,0,1);
CenterPrintDark(320,170,s,1);
}
CharaList(mgl);
for(i=0;i<MENU_CHOICES;i++)
{
#ifdef DIRECTORS
if(cursor==i)
{
CenterPrintDark(320+1,310+1+i*24,menuChoices[i],0);
CenterPrintDark(320-1,310-1+i*24,menuChoices[i],0);
CenterPrint(320,310+i*24,menuChoices[i],0,0);
}
else
{
CenterPrintDark(320,310+i*24,menuChoices[i],0);
}
#else
if(cursor==i)
{
CenterPrintDark(320+1,320+1+i*33,menuChoices[i],0);
CenterPrintDark(320-1,320-1+i*33,menuChoices[i],0);
CenterPrint(320,320+i*33,menuChoices[i],0,0);
}
else
{
CenterPrintDark(320,320+i*33,menuChoices[i],0);
}
#endif
}
if(submode==1) // erase char
EraseCharDisplay(mgl);
if(submode==2) // new char
NewCharDisplay(mgl);
}
void DeleteCharacter(void)
{
char s[64];
sprintf(s,"profiles/char%02d.loony",save[whoToDelete].realNum+1);
unlink(s); // delete that file
GetSavesForMenu();
curChar=0;
}
byte MainMenuUpdate(int *lastTime,MGLDraw *mgl)
{
byte c,k;
static byte reptCounter=0;
if(*lastTime>TIME_PER_FRAME*30)
*lastTime=TIME_PER_FRAME*30;
while(*lastTime>=TIME_PER_FRAME)
{
if(submode==0)
helpTime++;
if(ofsX<0)
ofsX+=10;
if(ofsX>0)
ofsX-=10;
timeToCred++;
// now real updating
c=GetControls()|GetArrows();
k=mgl->LastKeyPressed();
if(c!=0 || k!=0)
timeToCred=0;
if(submode==0) // normal menu
{
if((c&CONTROL_UP) && !(oldc&CONTROL_UP))
{
cursor--;
if(cursor>=MENU_CHOICES)
cursor=MENU_CHOICES-1;
MakeNormalSound(SND_MENUCLICK);
}
if((c&CONTROL_DN) && !(oldc&CONTROL_DN))
{
cursor++;
if(cursor>=MENU_CHOICES)
cursor=0;
MakeNormalSound(SND_MENUCLICK);
}
if((c&CONTROL_LF) && ofsX==0 && curChar>0) //!(oldc&CONTROL_LF))
{
curChar--;
if(curChar>=numChars)
curChar=numChars-1;
whoToDelete=curChar;
ofsX=-100;
MakeNormalSound(SND_MENUCLICK);
}
if((c&CONTROL_RT) && ofsX==0 && curChar<numChars-1) //!(oldc&CONTROL_RT))
{
curChar++;
ofsX=100;
if(curChar>=numChars)
curChar=0;
whoToDelete=curChar;
MakeNormalSound(SND_MENUCLICK);
}
if((c&(CONTROL_B1|CONTROL_B2)) && !(oldc&(CONTROL_B1|CONTROL_B2)))
{
switch(cursor)
{
case MM_PLAY: // play
if(save[curChar].newbie)
{
MakeNormalSound(SND_MENUSELECT);
gameToLoad=save[curChar].realNum;
opt.lastProfile=gameToLoad;
submode=2;
subcursor=0;
}
else
{
MakeNormalSound(SND_MENUSELECT);
gameToLoad=save[curChar].realNum;
opt.lastProfile=gameToLoad;
return MENU_PLAY;
}
break;
case MM_ERASE: // erase guy
if(save[curChar].newbie==0)
{
MakeNormalSound(SND_MENUSELECT);
submode=1;
subcursor=1;
}
else
MakeNormalSound(SND_MENUCANCEL);
break;
case MM_ACHIEVE:
AchieveMenu(mgl,backScr);
break;
#ifdef DIRECTORS
case MM_GALLERY:
if(HaveGallery())
Gallery(mgl);
else
MakeNormalSound(SND_MENUCANCEL);
break;
case MM_EDITOR:
return MENU_EDITOR;
break;
#endif
case MM_OPTIONS: // options
OptionsMenu(mgl,backScr);
break;
case MM_QUIT: // exit
MakeNormalSound(SND_MENUSELECT);
return MENU_EXIT;
break;
}
}
if(k==27)
return MENU_EXIT;
#ifdef _DEBUG
if(k=='e' || k=='E')
return MENU_EDITOR;
#endif
}
else if(submode==1) // sure you want to delete?
{
if((c&CONTROL_LF) && !(oldc&CONTROL_LF))
{
subcursor=1-subcursor;
MakeNormalSound(SND_MENUCLICK);
}
if((c&CONTROL_RT) && !(oldc&CONTROL_RT))
{
subcursor=1-subcursor;
MakeNormalSound(SND_MENUCLICK);
}
if((c&(CONTROL_B1)) && !(oldc&(CONTROL_B1)))
{
switch(subcursor)
{
case 0: // yep, slice him up
MakeNormalSound(SND_MENUSELECT);
DeleteCharacter();
whoToDelete=0;
subcursor=0;
submode=0;
cursor=0;
break;
case 1: // nevermind
MakeNormalSound(SND_MENUSELECT);
subcursor=0;
submode=0;
cursor=0;
break;
}
}
if((c&(CONTROL_B2)) && !(oldc&(CONTROL_B2)))
{
// nevermind
MakeNormalSound(SND_MENUCANCEL);
subcursor=0;
submode=0;
cursor=0;
}
if(k==27)
{
MakeNormalSound(SND_MENUCANCEL);
subcursor=0;
submode=0;
cursor=0;
}
}
else if(submode==2) // make a new char
{
if((c&CONTROL_UP) && !(oldc&CONTROL_UP))
{
subcursor--;
if(subcursor>4)
subcursor=4;
MakeNormalSound(SND_MENUCLICK);
}
if((c&CONTROL_DN) && !(oldc&CONTROL_DN))
{
subcursor++;
if(subcursor>4)
subcursor=0;
MakeNormalSound(SND_MENUCLICK);
}
if((c&CONTROL_LF) && !(oldc&CONTROL_LF))
{
if(subcursor>=1 && subcursor<=3)
{
AdjustModifier(&save[curChar].mod[subcursor-1],subcursor-1,-1,save[curChar].mod);
MakeNormalSound(SND_MENUCLICK);
}
#ifdef DIRECTORS
if(subcursor==4)
{
addOnChoice--;
while(addOnChoice<0 || addOnChoice>=addOnCount || (addOnList[addOnChoice].filename[0]=='\0' && addOnChoice!=0))
addOnChoice--;
}
#endif
}
if((c&CONTROL_RT) && !(oldc&CONTROL_RT))
{
if(subcursor>=1 && subcursor<=3)
{
AdjustModifier(&save[curChar].mod[subcursor-1],subcursor-1,1,save[curChar].mod);
MakeNormalSound(SND_MENUCLICK);
}
#ifdef DIRECTORS
if(subcursor==4)
{
addOnChoice++;
while(addOnChoice<0 || addOnChoice>=addOnCount || (addOnList[addOnChoice].filename[0]=='\0' && addOnChoice!=0))
addOnChoice++;
}
#endif
}
if((c&(CONTROL_B1)) && !(oldc&(CONTROL_B1)))
{
switch(subcursor)
{
case 0: // don't do anything, just enter that name
break;
case 1: // modifiers
case 2:
case 3:
break;
case 4: // go!
MakeNormalSound(SND_MENUSELECT);
gameToLoad=save[curChar].realNum;
strcpy(saveName,save[curChar].name);
saveMod[0]=save[curChar].mod[0];
saveMod[1]=save[curChar].mod[1];
saveMod[2]=save[curChar].mod[2];
return MENU_NEWCHAR;
break;
}
}
if(k==27)
{
MakeNormalSound(SND_MENUCANCEL);
subcursor=0;
submode=0;
cursor=0;
}
if(k==8 && subcursor==0)
{
// backspace
if(strlen(save[curChar].name)>0)
{
save[curChar].name[strlen(save[curChar].name)-1]='\0';
MakeNormalSound(SND_MENUCLICK);
}
}
if(k==13 && subcursor==0)
{
MakeNormalSound(SND_MENUCLICK);
subcursor=1;
}
if((k>='a' && k<='z') || (k>='A' && k<='Z') || (k>='0' && k<='9') && subcursor==0)
{
if(strlen(save[curChar].name)<10)
{
MakeNormalSound(SND_MENUCLICK);
save[curChar].name[strlen(save[curChar].name)+1]='\0';
save[curChar].name[strlen(save[curChar].name)]=k;
}
else
MakeNormalSound(SND_MENUCANCEL);
}
}
oldc=c;
*lastTime-=TIME_PER_FRAME;
numRuns++;
}
return 0;
}
byte MainMenu(MGLDraw *mgl)
{
byte b=0;
int lastTime=1;
InitMainMenu(mgl);
while(b==0)
{
lastTime+=TimeLength();
StartClock();
b=MainMenuUpdate(&lastTime,mgl);
MainMenuDisplay(mgl);
mgl->Flip();
if(!mgl->Process())
{
free(backScr);
return 255;
}
EndClock();
if(timeToCred>30*20)
{
timeToCred=0;
Credits(mgl,0);
}
}
free(backScr);
return b;
}
char *GetSavedName(void)
{
return saveName;
}
byte GetSavedMod(byte n)
{
return saveMod[n];
}
| [
"tad@platymuus.com"
] | tad@platymuus.com |
0a2b9a5eed2dc647fe7ec298b2bba6d2e7c9488f | 0bc1c87b5fb2262d2e9466ca88270cbfd59b037b | /WerkstueckSortieranlage/Timer.cpp | d4611d0afdc26ab62250bdae3373558d55b097a7 | [] | no_license | TeamSE2/SE2 | 6b4b65e23e004ae2dd776f5effd24af2546294d6 | 6d9453d87e9aafc79088062a558196ce72689ceb | refs/heads/master | 2021-01-01T15:35:17.629079 | 2014-01-09T11:43:35 | 2014-01-09T11:43:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,768 | cpp | /**
* @file Timer.cpp
* @date 10.12.2013
* @author Ruben Christian Buhl
* @brief Datei_Beschreibung_Kurz
*/
#include <time.h>
#include <stdint.h>
#include "Timer.h"
#include "Dispatcher.h"
//timespec Timer::times[TIMES_LENGTH] = {{1, 612753596}, {0, 404938420}, {1, 118647801}, {0, 383941633}, {0, 470109467}, {0, 928220000}, {0, 928220000}, {0, 464110385}, {1, 856440000}, {0, 928220000}};
timespec Timer::times[TIMES_LENGTH] = {{1, 846717952}, {0, 394940108}, {1, 43659434}, {0, 392940414}, {0, 201150624}, {0, 756247000}, {0, 756247000}, {0, 378123543}, {1, 512494000}, {0, 756247000}};
long Timer::new_id = 1;
timermap Timer::timer;
bool Timer::running = true;
bool Timer::slow = false;
Timer::Timer(timespec time)
{
id = new_id;
new_id++;
memset(&timerspec, 0, sizeof(timerspec));
memset(&event, 0, sizeof(event));
timerspec.it_value = time;
initial_timerspec = timerspec;
// dispatcherConnectionID = ConnectAttach(0, 0, Dispatcher::getInstance().getDispatcherChannelID(), _NTO_SIDE_CHANNEL, 0);
dispatcherConnectionID = HAL::getInstance().getInterruptController()->getSignalConnectionID();
if(dispatcherConnectionID == -1)
{
perror("Timer: dispatcherConnectionID ConnectAttach fehlgeschlagen");
exit(EXIT_FAILURE);
}
PulsNachricht nachricht;
int *val = NULL;
nachricht.iq = id;
val = (int*)(&nachricht);
SIGEV_PULSE_INIT(&event, dispatcherConnectionID, SIGEV_PULSE_PRIO_INHERIT, TIMER_PULSE_CODE, id);
timer_create(CLOCK_REALTIME, &event, &timerID);
timer_settime(timerID, 0, &timerspec, NULL);
if(slow)
{
langsam();
}
if(!running)
{
anhalten();
}
}
Timer::~Timer()
{
anhalten();
if(ConnectDetach(dispatcherConnectionID) == -1)
{
perror("Timer: dispatcherConnectionID ConnectDetach fehlgeschlagen");
}
}
int Timer::starten(timespec time)
{
Timer* new_timer = new Timer(time);
timer[new_timer->getID()] = new_timer;
return new_timer->getID();
}
void Timer::stoppen(int id)
{
delete timer[id];
timer.erase(id);
}
void Timer::alle_anhalten()
{
if(running)
{
for(timermap::iterator timerIterator = timer.begin(); timerIterator != timer.end(); timerIterator++)
{
timerIterator->second->anhalten();
}
running = false;
}
}
void Timer::alle_fortsetzen()
{
if(!running)
{
for(timermap::iterator timerIterator = timer.begin(); timerIterator != timer.end(); timerIterator++)
{
timerIterator->second->fortsetzen();
}
running = true;
}
}
void Timer::alle_langsam()
{
if(!slow)
{
for(timermap::iterator timerIterator = timer.begin(); timerIterator != timer.end(); timerIterator++)
{
timerIterator->second->langsam();
}
slow = true;
}
}
void Timer::alle_normal()
{
if(slow)
{
for(timermap::iterator timerIterator = timer.begin(); timerIterator != timer.end(); timerIterator++)
{
timerIterator->second->normal();
}
slow = false;
}
}
timespec Timer::gettime(int id)
{
return timer[id]->gettime();
}
timespec Timer::getelapsedtime(int id)
{
return timer[id]->getelapsedtime();
}
void Timer::anhalten()
{
timerspec.it_value = gettime();
timer_delete(timerID);
}
void Timer::fortsetzen()
{
timer_create(CLOCK_REALTIME, &event, &timerID);
timer_settime(timerID, 0, &timerspec, NULL);
}
void Timer::langsam()
{
timerspec.it_value = multiplizieren(gettime(), double_to_timespec(LANGSAM_MULTIPLIKATOR));
timer_delete(timerID);
timer_create(CLOCK_REALTIME, &event, &timerID);
timer_settime(timerID, 0, &timerspec, NULL);
}
void Timer::normal()
{
timerspec.it_value = dividieren(gettime(), double_to_timespec(LANGSAM_MULTIPLIKATOR));
timer_delete(timerID);
timer_create(CLOCK_REALTIME, &event, &timerID);
timer_settime(timerID, 0, &timerspec, NULL);
}
long Timer::getID()
{
return id;
}
double Timer::timespec_to_double(timespec time)
{
return time.tv_sec + (time.tv_nsec / 1000000000.0);
}
timespec Timer::double_to_timespec(double time)
{
timespec temp;
long time_mikrosekunden = time * 1000000;
temp.tv_sec = time;
temp.tv_nsec = (time_mikrosekunden % 1000000) * 1000;
return temp;
}
timespec Timer::gettime()
{
timer_gettime(timerID, &timerspec);
return timerspec.it_value;
}
timespec Timer::getelapsedtime()
{
itimerspec elapsed_timerspec;
timer_gettime(timerID, &elapsed_timerspec);
elapsed_timerspec.it_value.tv_sec = initial_timerspec.it_value.tv_sec - elapsed_timerspec.it_value.tv_sec;
elapsed_timerspec.it_value.tv_nsec = initial_timerspec.it_value.tv_nsec - elapsed_timerspec.it_value.tv_nsec;
if(elapsed_timerspec.it_value.tv_nsec < 0)
{
elapsed_timerspec.it_value.tv_sec = elapsed_timerspec.it_value.tv_sec - 1;
elapsed_timerspec.it_value.tv_nsec = elapsed_timerspec.it_value.tv_nsec + 1000000000;
}
return elapsed_timerspec.it_value;
}
timespec Timer::addieren(timespec operand1, timespec operand2)
{
timespec ergebnis;
long nsec = operand1.tv_nsec + operand2.tv_nsec;
ergebnis.tv_sec = operand1.tv_sec + operand2.tv_sec;
if(nsec > 1000000000)
{
ergebnis.tv_sec = ergebnis.tv_sec + 1;
nsec = nsec - 1000000000;
}
ergebnis.tv_nsec = nsec;
return ergebnis;
}
timespec Timer::subtrahieren(timespec operand1, timespec operand2)
{
timespec ergebnis;
long nsec = operand1.tv_nsec - operand2.tv_nsec;
ergebnis.tv_sec = operand1.tv_sec - operand2.tv_sec;
if(nsec < 0)
{
ergebnis.tv_sec = ergebnis.tv_sec - 1;
nsec = nsec + 1000000000;
}
ergebnis.tv_nsec = nsec;
return ergebnis;
}
timespec Timer::multiplizieren(timespec operand1, timespec operand2)
{
timespec ergebnis;
double operand1_sekunden = operand1.tv_sec + (operand1.tv_nsec / 1000000000.0);
double operand2_sekunden = operand2.tv_sec + (operand2.tv_nsec / 1000000000.0);
double ergebnis_sekunden = operand1_sekunden * operand2_sekunden;
long ergebnis_mikrosekunden = ergebnis_sekunden * 1000000;
ergebnis.tv_sec = ergebnis_sekunden;
ergebnis.tv_nsec = (ergebnis_mikrosekunden % 1000000) * 1000;
return ergebnis;
}
timespec Timer::dividieren(timespec operand1, timespec operand2)
{
timespec ergebnis;
double operand1_mikrosekunden = (operand1.tv_sec * 1000000) + (operand1.tv_nsec / 1000.0);
double operand2_mikrosekunden = (operand2.tv_sec * 1000000) + (operand2.tv_nsec / 1000.0);
double ergebnis_sekunden = operand1_mikrosekunden / operand2_mikrosekunden;
long ergebnis_mikrosekunden = ergebnis_sekunden * 1000000;
ergebnis.tv_sec = ergebnis_sekunden;
ergebnis.tv_nsec = (ergebnis_mikrosekunden % 1000000) * 1000;
return ergebnis;
}
| [
"Pascal.Borchert@haw-hamburg.de"
] | Pascal.Borchert@haw-hamburg.de |
944111f10b94ae7db7c20b03326abce0c0cce3ed | 62cfb3670073a31cf4b74c5e6d37a06573159f6f | /src/ArduinoJson/src/ArduinoJson/Polyfills/type_traits/remove_reference.hpp | d669bad884c1c1f04c567619473d1ca68cc0460b | [
"MIT"
] | permissive | martinius96/hladinomer-studna-scripty | c7e2b0febc429e83fdaf4c1f4cc06022b3dcee22 | 55ba0bed6035b3349417705dfb5a1c28b4321649 | refs/heads/master | 2023-09-06T02:59:26.366414 | 2023-08-29T16:07:22 | 2023-08-29T16:07:22 | 212,859,833 | 14 | 1 | MIT | 2021-03-21T00:07:54 | 2019-10-04T16:37:23 | C++ | UTF-8 | C++ | false | false | 449 | hpp | // ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2020
// MIT License
#pragma once
#include <ArduinoJson/Namespace.hpp>
namespace ARDUINOJSON_NAMESPACE {
// A meta-function that return the type T without the reference modifier.
template <typename T>
struct remove_reference {
typedef T type;
};
template <typename T>
struct remove_reference<T&> {
typedef T type;
};
} // namespace ARDUINOJSON_NAMESPACE
| [
"noreply@github.com"
] | martinius96.noreply@github.com |
a854f041f633dcb039ec28426690b133044f3761 | bc4ec20837654d5a9885377f702f562897b5c863 | /Personal Lecture Notes/L20-L22/vecmap.h | edcac9b1fdd1da60b506d123a8e0613477871f12 | [] | no_license | SarMbk/CS106B | 2fad516ad2a4b2f02441398f9e8b316a6ee5a2b1 | 496efc9a3dbd3f7b4677a3afcfde06b886633b57 | refs/heads/master | 2020-03-27T14:09:52.446281 | 2018-08-31T15:13:01 | 2018-08-31T15:13:01 | 146,647,589 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 500 | h | #ifndef VECMAP_H
#define VECMAP_H
#include <iostream>
#include <string>
#include "vector.h"
#include "error.h"
using namespace std;
template <typename elemtype>
class vecmap
{
public:
vecmap();
~vecmap();
void add(string key, elemtype val);
elemtype getValue(string key);
void printAll();
private:
struct pairT{
string key;
elemtype val;
};
Vector <pairT> entries;
int findIndexforKey(string key);
};
#include "vecmap.cpp"
#endif // VECMAP_H
| [
"smanarbek@microdesk.com"
] | smanarbek@microdesk.com |
3007493183fe90b3b09b0c89a46b7f321258df5b | c5aa0e8aeccdda764049e44f6eb166706ea33cdf | /LoggerProcessor.cpp | 5251cbc018be5b27162963f0f1586579da5bea54 | [] | no_license | guisoares2011/queue-processor | 375953956e1bb630619dfb184948569763e1a297 | 820dba88f5f7d26af60ad9e2df2178672ee6e450 | refs/heads/master | 2021-01-17T17:13:50.277226 | 2016-09-23T01:59:10 | 2016-09-23T01:59:10 | 68,676,293 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 227 | cpp | #include "LoggerProcessor.hpp"
#include <iostream>
#include <Windows.h>
void LoggerProcessor::onProcess(int workerID, const std::string& data)
{
//std::cout << workerID << " : " << data << " ; " << std::endl;
Sleep(2000);
};
| [
"guisoares80@gmail.com"
] | guisoares80@gmail.com |
0625724d66456119f8c7c468fcbf78ec47b3c81d | 7d92591c60d0ae55684f620e4e7b17d9e379436e | /Protobuf/Source/Protobuf/Public/Helper/ProtobufHelper.h | c187ced4f01d3b3d14495ca8ae3c90faef382510 | [] | no_license | GlorySL/UE4Plugins | 90d53b6ba4696156c5461ebfc3ed7b1fa237d574 | e9efcb61ffe899bbe0602dd47c5b51f5fc6c0f4c | refs/heads/master | 2022-12-29T17:24:17.066336 | 2020-10-21T04:27:33 | 2020-10-21T04:27:33 | 305,724,982 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 427 | h | /**
* Author: LiuShuang
* Date: 2020.10.19
*/
#pragma once
#include "CoreMinimal.h"
#include "ProtobufHelper.generated.h"
/** Helper */
UCLASS(BlueprintType, Blueprintable)
class UProtobufHelper : public UObject
{
GENERATED_UCLASS_BODY()
public:
virtual ~UProtobufHelper();
public:
/** UObject - PropertySetter */
UFUNCTION(BlueprintCallable, Category = "ProtobufHelper")
static bool Hello_ProtobufHelper();
};
| [
"191369782@users.noreply.github.com"
] | 191369782@users.noreply.github.com |
3287fad4b13cdb5bf9d976cc6721f1863fe0098a | c58267bda383f2572b27a602e8d6a57c2021b43b | /src/pcl/polygon_mesh.cpp | 87131cf3f3348342557f07391fe7beb8e7e414b2 | [] | no_license | Sadaku1993/depthimage_creater | c930685b7e1d853f15289b7fdff500cf6ae73ccb | 86ee83eacafec65008a3f28fdf5b4a3ac9a00f17 | refs/heads/master | 2020-04-06T14:11:59.583051 | 2019-01-10T10:41:44 | 2019-01-10T10:41:44 | 157,531,749 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,409 | cpp | #include <ros/ros.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/features/normal_3d_omp.h>
#include <pcl/surface/gp3.h>
#include <pcl/io/vtk_io.h>
#include <iostream>
#include <depthimage_creater/plane_equataion.h>
#include <depthimage_creater/check_area.h>
class PolygonMesh{
private:
ros::NodeHandle nh;
std::string LOAD_PATH;
std::string SAVE_PATH;
std::string PCD_FILE;
std::string OUTPUT_FILE;
std::string VTK_FILE;
double search_radius;
double gp3_serach_radius;
double gp3_K;
public:
PolygonMesh();
void load(pcl::PointCloud<pcl::PointXYZ>::Ptr& cloud);
void save(pcl::PointCloud<pcl::PointXYZINormal>::Ptr cloud,
pcl::PolygonMesh polygonmesh);
void normal_estimation(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud,
pcl::PointCloud<pcl::PointXYZINormal>::Ptr& cloud_normal);
void polygon_mesh(pcl::PointCloud<pcl::PointXYZINormal>::Ptr cloud,
pcl::PolygonMesh& triangles);
void main();
};
PolygonMesh::PolygonMesh()
: nh("~")
{
nh.getParam("search_radius", search_radius);
nh.getParam("load_path" , LOAD_PATH);
nh.getParam("save_path" , SAVE_PATH);
nh.getParam("pcd_file" , PCD_FILE);
nh.getParam("vtk_file" , VTK_FILE);
nh.getParam("output_file" , OUTPUT_FILE);
nh.getParam("gp3_serach_radius", gp3_serach_radius);
nh.getParam("gp3_K", gp3_K);
}
void PolygonMesh::load(pcl::PointCloud<pcl::PointXYZ>::Ptr& cloud)
{
std::string file_name = LOAD_PATH + "/" + PCD_FILE;
std::cout<<"-----Load :" <<file_name<<std::endl;
if (pcl::io::loadPCDFile<pcl::PointXYZ> (file_name, *cloud) == -1) //* load the file
{
PCL_ERROR ("-----Couldn't read file\n");
}
}
void PolygonMesh::save(pcl::PointCloud<pcl::PointXYZINormal>::Ptr cloud,
pcl::PolygonMesh polygonmesh)
{
pcl::PointCloud<pcl::PointXYZINormal>::Ptr save_cloud(new pcl::PointCloud<pcl::PointXYZINormal>);
pcl::copyPointCloud(*cloud, *save_cloud);
save_cloud->width = 1;
save_cloud->height = save_cloud->points.size();
std::string file_name=SAVE_PATH+"/"+OUTPUT_FILE;
std::string vtk_name=SAVE_PATH+"/"+VTK_FILE;
pcl::io::savePCDFileASCII(file_name, *save_cloud);
pcl::io::saveVTKFile(vtk_name, polygonmesh);
std::cout<<"-----Save :" <<file_name <<std::endl;
}
void PolygonMesh::normal_estimation(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud,
pcl::PointCloud<pcl::PointXYZINormal>::Ptr& cloud_normal)
{
std::cout<<"-----Normal Estimation"<<std::endl;
pcl::NormalEstimationOMP<pcl::PointXYZ, pcl::Normal> ne;
ne.setInputCloud(cloud);
pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ> ());
ne.setSearchMethod (tree);
pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>);
ne.setRadiusSearch (search_radius);
ne.compute(*normals);
pcl::PointXYZINormal tmp;
for(size_t i=0;i<cloud->points.size();i++)
{
tmp.x = cloud->points[i].x;
tmp.y = cloud->points[i].y;
tmp.z = cloud->points[i].z;
// tmp.r = cloud->points[i].r;
// tmp.g = cloud->points[i].g;
// tmp.b = cloud->points[i].b;
if(!std::isnan(normals->points[i].normal_x)){
tmp.normal_x = normals->points[i].normal_x;
}
else{
tmp.normal_x = 0.0;
}
if(!std::isnan(normals->points[i].normal_y)){
tmp.normal_y = normals->points[i].normal_y;
}
else{
tmp.normal_y = 0.0;
}
if(!std::isnan(normals->points[i].normal_z)){
tmp.normal_z = normals->points[i].normal_z;
}
else{
tmp.normal_z = 0.0;
}
if(!std::isnan(normals->points[i].curvature)){
tmp.curvature = normals->points[i].curvature;
}
else{
tmp.curvature = 0.0;
}
cloud_normal->points.push_back(tmp);
}
}
void PolygonMesh::polygon_mesh(pcl::PointCloud<pcl::PointXYZINormal>::Ptr cloud,
pcl::PolygonMesh& triangles)
{
std::cout<<"-----Polygon Mesh"<<std::endl;
pcl::search::KdTree<pcl::PointXYZINormal>::Ptr tree2 (new pcl::search::KdTree<pcl::PointXYZINormal>);
tree2->setInputCloud (cloud);
pcl::GreedyProjectionTriangulation<pcl::PointXYZINormal> gp3;
gp3.setSearchRadius (gp3_serach_radius);
gp3.setMu (2.5);
gp3.setMaximumNearestNeighbors (gp3_K);
gp3.setMaximumSurfaceAngle(M_PI/4);
gp3.setMinimumAngle(M_PI/18);
gp3.setMaximumAngle(2*M_PI/3);
gp3.setNormalConsistency(false);
gp3.setInputCloud (cloud);
gp3.setSearchMethod (tree2);
gp3.reconstruct (triangles);
std::vector<int> parts = gp3.getPartIDs();
std::vector<int> states = gp3.getPointStates();
}
void PolygonMesh::main()
{
pcl::PointCloud<pcl::PointXYZ>::Ptr load_cloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::PointCloud<pcl::PointXYZINormal>::Ptr normal_cloud(new pcl::PointCloud<pcl::PointXYZINormal>);
load(load_cloud);
normal_estimation(load_cloud, normal_cloud);
pcl::PolygonMesh triangles;
polygon_mesh(normal_cloud, triangles);
for(size_t i=0;i<triangles.polygons.size();i++){
// std::cout<<"polygon:"<<i<<std::endl;
// std::cout<<" 0-->"<<triangles.polygons[i].vertices[0]<<" "<<normal_cloud->points[triangles.polygons[i].vertices[0]]<<std::endl;
// std::cout<<" 1-->"<<triangles.polygons[i].vertices[1]<<" "<<normal_cloud->points[triangles.polygons[i].vertices[1]]<<std::endl;
// std::cout<<" 2-->"<<triangles.polygons[i].vertices[2]<<" "<<normal_cloud->points[triangles.polygons[i].vertices[2]]<<std::endl;
pcl::PointXYZINormal p0, p1, p2;
p0 = normal_cloud->points[triangles.polygons[i].vertices[0]];
p1 = normal_cloud->points[triangles.polygons[i].vertices[1]];
p2 = normal_cloud->points[triangles.polygons[i].vertices[2]];
Vector3D v0(p0.x, p0.y, p0.z);
Vector3D v1(p1.x, p1.y, p1.z);
Vector3D v2(p2.x, p2.y, p2.z);
Plane plane = CreatePlaneFromPolygon(v0, v1, v2);
// std::cout<<"a:"<<plane.a<<" "
// <<"b:"<<plane.b<<" "
// <<"c:"<<plane.c<<" "
// <<"d:"<<plane.d<<std::endl;
double result;
result = plane.a * p0.x + plane.b * p0.y + plane.c * p0.z;
// std::cout<<"result:"<<result<<std::endl;
// std::cout<<"d:"<<plane.d<<std::endl;
VectorXD x0, x1, x2;
x0.x = p0.x; x0.y = p0.y; x0.z = p0.z;
x1.x = p1.x; x1.y = p1.y; x1.z = p1.z;
x2.x = p2.x; x2.y = p2.y; x2.z = p2.z;
int check = hittest_point_polygon_3d(x0, x1, x2, x0);
// 三角形の内側に点がある場合:1, ない場合:0
// std::cout<<check<<std::endl;
Eigen::Vector3f centroid;
centroid[0] = (p0.x+p1.x+p2.x)/3.0;
centroid[1] = (p0.y+p1.y+p2.y)/3.0;
centroid[2] = (p0.z+p1.z+p2.z)/3.0;
// std::cout<<"centroid:"<<std::endl;
// std::cout<<centroid<<std::endl;
std::vector<double> vec_x(3), vec_y(3), vec_z(3);
vec_x[0] = p0.x; vec_x[1] = p1.x; vec_x[2] = p2.x;
vec_y[0] = p0.y; vec_y[1] = p1.y; vec_y[2] = p2.y;
vec_z[0] = p0.z; vec_z[1] = p1.z; vec_z[2] = p2.z;
double min_x = *std::min_element(vec_x.begin(), vec_x.end());
double min_y = *std::min_element(vec_y.begin(), vec_y.end());
double min_z = *std::min_element(vec_z.begin(), vec_z.end());
double max_x = *std::max_element(vec_x.begin(), vec_x.end());
double max_y = *std::max_element(vec_y.begin(), vec_y.end());
double max_z = *std::max_element(vec_z.begin(), vec_z.end());
// std::cout<<"min_x:"<<min_x<<" "
// <<"min_y:"<<min_y<<" "
// <<"min_z:"<<min_z<<" "
// <<"max_x:"<<max_x<<" "
// <<"max_y:"<<max_y<<" "
// <<"max_z:"<<max_z<<std::endl;
pcl::PointXYZINormal point;
point.x = centroid[0]; point.y = centroid[1]; point.z = centroid[2];
normal_cloud->points.push_back(point);
}
save(normal_cloud, triangles);
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "polygon_mesh");
PolygonMesh ne;
ne.main();
return 0;
}
| [
"36195395+Sadaku1993@users.noreply.github.com"
] | 36195395+Sadaku1993@users.noreply.github.com |
05eb37f622cd58ad92cf90c2a7397f6a51ae8145 | e9d25873a3ad52f77938bae1789bb2f95a877bce | /indra/libpathing/llphysicsextensions.h | 4bd6d7929a0b787d905686ace7f46fac7169f241 | [] | no_license | Shyotl/SingularityViewer | e9267237a93a13f68c7c6f538a59990f08ddc332 | ab5bce69ee11b116e4e57639532d8c0a49af23fd | refs/heads/master | 2021-01-17T05:59:12.026799 | 2020-05-17T03:52:08 | 2020-05-17T03:52:08 | 1,090,174 | 14 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 160 | h | #ifndef LLPYHSICS_EXTENSIONS_H
#define LLPYHSICS_EXTENSIONS_H
class LLPhysicsExtensions
{
public:
static void quitSystem();
bool isFunctional();
};
#endif
| [
"siana.sg@live.de"
] | siana.sg@live.de |
b056aebddde3e812ec399795fd8dc99916611627 | 5367b19700fe588f4b3c14e5d89b7ac769ebdbff | /Project13/Project13/Class_Linked_List.cpp | b85e7a8c8bb5d5ff1dfa113158c4e37fb6409eb6 | [] | no_license | MoKwangYun/Cpp | 67e640f29fecbdb6b694d44f4bdc78288d2150a5 | 6efd91d6d687910681c3004269c4cb30945b8976 | refs/heads/main | 2023-08-17T15:12:57.190285 | 2021-09-14T14:35:36 | 2021-09-14T14:35:36 | 386,206,539 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,979 | cpp | #include<iostream>
using namespace std;
//클래스로 Linked List 구현
class CListNode {
public:
CListNode() :
m_pNext(NULL),
m_pPrev(NULL)
{
}
~CListNode() {
}
int m_iData;
CListNode* m_pNext;
CListNode* m_pPrev;
};
class CList {
public:
CList(){
m_pBegin = new CListNode;
m_pEnd = new CListNode;
m_pBegin->m_pNext = m_pEnd;
m_pEnd->m_pPrev = m_pBegin;
m_iSize = 0;
}
~CList() {
clear(); //동적할당 해제
delete m_pBegin;
delete m_pEnd;
}
private:
CListNode* m_pBegin;
CListNode* m_pEnd;
int m_iSize;
public:
void push_back(int iData) {//End노드 바로 앞에 노드 추가하는 함수
CListNode* pNode = new CListNode;
pNode->m_iData = iData;
CListNode* PREV = m_pEnd->m_pPrev;
PREV->m_pNext = pNode;
pNode->m_pPrev = PREV;
pNode->m_pNext = m_pEnd;
m_pEnd->m_pPrev = pNode;
++m_iSize;
}
bool empty() { //m_iSize == 0이면 true , m_iSize != 0 이면 false 리턴
return m_iSize == 0;
}
void clear() {
CListNode* pNode = m_pBegin->m_pNext;
while (pNode != m_pEnd) {
CListNode* NEXT = pNode->m_pNext;
delete pNode;
pNode = NEXT;
}
//Begin과 End 사이 노드 전부 삭제 후 Begin과 End 밖에 안 남았기 때문에 둘 연결
m_pBegin->m_pNext = m_pEnd;
m_pEnd->m_pPrev = m_pBegin;
m_iSize = 0;
}
int pop_back() {//맨마지막 같을 지우고 값을 리턴
CListNode* PREV = m_pEnd->m_pPrev;
if (PREV == m_pBegin) { //End와 Begin노드 사이 노드가 없을 경우
return INT_MAX;
}
int iData = PREV->m_iData;
PREV->m_pPrev->m_pNext = m_pEnd;
m_pEnd->m_pPrev = PREV->m_pPrev; //PREV노드 이전 다음 노드 연겨ㅓㄹ
--m_iSize;
delete PREV;
return iData;
}
};
int main() {
CList list;
for (int i = 0; i < 100; i++) {
list.push_back(i);
}
while (!list.empty()) {//list가 비어있으면 true리턴 -> !와 만나 false 가 됨 --> whlie문 탈출
cout << list.pop_back() << endl;
}
return 0;
} | [
"mo980427@naver.com"
] | mo980427@naver.com |
4bab403529e86a33fb748ce4bc15b539b32bca04 | 7a17d90d655482898c6777c101d3ab6578ccc6ba | /SDK/PUBG_DmgType_BleedOut_classes.hpp | a727eb606d7022b0f4ec17c3af9c51bfab183282 | [] | no_license | Chordp/PUBG-SDK | 7625f4a419d5b028f7ff5afa5db49e18fcee5de6 | 1b23c750ec97cb842bf5bc2b827da557e4ff828f | refs/heads/master | 2022-08-25T10:07:15.641579 | 2022-08-14T14:12:48 | 2022-08-14T14:12:48 | 245,409,493 | 17 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 701 | hpp | #pragma once
// PUBG (9.1.5.3) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_DmgType_BleedOut_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass DmgType_BleedOut.DmgType_BleedOut_C
// 0x0000 (0x0108 - 0x0108)
class UDmgType_BleedOut_C : public UTslDamageType
{
public:
static UClass* StaticClass()
{
static UClass* ptr;
if(!ptr)
ptr = UObject::FindClass(_xor_("BlueprintGeneratedClass DmgType_BleedOut.DmgType_BleedOut_C"));
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"1263178881@qq.com"
] | 1263178881@qq.com |
b76d6aa995d0fb86c528f69d4527aa22c9ebbc35 | a8b457da0f2f327320b27a5f0bffe7a55685de7c | /src/rpcdump.cpp | 3340906031baef4e3c60f6a331bea9b1bd8fc8ef | [
"MIT"
] | permissive | pineplatform/protcoin | 6ea97b3923b26f85f47983ce6ab3d1865340a496 | 1e3dbf298fd9bbba5eb729ab1a93a21b948c78fd | refs/heads/master | 2020-06-21T07:40:46.604718 | 2019-07-28T03:06:25 | 2019-07-28T03:06:25 | 197,385,055 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 18,897 | cpp | // Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bip38.h"
#include "init.h"
#include "main.h"
#include "rpcserver.h"
#include "script/script.h"
#include "script/standard.h"
#include "sync.h"
#include "util.h"
#include "utilstrencodings.h"
#include "utiltime.h"
#include "wallet.h"
#include <fstream>
#include <secp256k1.h>
#include <stdint.h>
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <openssl/aes.h>
#include <openssl/sha.h>
#include <univalue.h>
using namespace std;
void EnsureWalletIsUnlocked();
std::string static EncodeDumpTime(int64_t nTime)
{
return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
}
int64_t static DecodeDumpTime(const std::string& str)
{
static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0);
static const std::locale loc(std::locale::classic(),
new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ"));
std::istringstream iss(str);
iss.imbue(loc);
boost::posix_time::ptime ptime(boost::date_time::not_a_date_time);
iss >> ptime;
if (ptime.is_not_a_date_time())
return 0;
return (ptime - epoch).total_seconds();
}
std::string static EncodeDumpString(const std::string& str)
{
std::stringstream ret;
BOOST_FOREACH (unsigned char c, str) {
if (c <= 32 || c >= 128 || c == '%') {
ret << '%' << HexStr(&c, &c + 1);
} else {
ret << c;
}
}
return ret.str();
}
std::string DecodeDumpString(const std::string& str)
{
std::stringstream ret;
for (unsigned int pos = 0; pos < str.length(); pos++) {
unsigned char c = str[pos];
if (c == '%' && pos + 2 < str.length()) {
c = (((str[pos + 1] >> 6) * 9 + ((str[pos + 1] - '0') & 15)) << 4) |
((str[pos + 2] >> 6) * 9 + ((str[pos + 2] - '0') & 15));
pos += 2;
}
ret << c;
}
return ret.str();
}
UniValue importprivkey(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"importprivkey \"protprivkey\" ( \"label\" rescan )\n"
"\nAdds a private key (as returned by dumpprivkey) to your wallet.\n"
"\nArguments:\n"
"1. \"protprivkey\" (string, required) The private key (see dumpprivkey)\n"
"2. \"label\" (string, optional, default=\"\") An optional label\n"
"3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
"\nNote: This call can take minutes to complete if rescan is true.\n"
"\nExamples:\n"
"\nDump a private key\n" +
HelpExampleCli("dumpprivkey", "\"myaddress\"") +
"\nImport the private key with rescan\n" + HelpExampleCli("importprivkey", "\"mykey\"") +
"\nImport using a label and without rescan\n" + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") +
"\nAs a JSON-RPC call\n" + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false"));
EnsureWalletIsUnlocked();
string strSecret = params[0].get_str();
string strLabel = "";
if (params.size() > 1)
strLabel = params[1].get_str();
// Whether to perform rescan after import
bool fRescan = true;
if (params.size() > 2)
fRescan = params[2].get_bool();
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strSecret);
if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
CKey key = vchSecret.GetKey();
if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
CPubKey pubkey = key.GetPubKey();
assert(key.VerifyPubKey(pubkey));
CKeyID vchAddress = pubkey.GetID();
{
pwalletMain->MarkDirty();
pwalletMain->SetAddressBook(vchAddress, strLabel, "receive");
// Don't throw error in case a key is already there
if (pwalletMain->HaveKey(vchAddress))
return NullUniValue;
pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1;
if (!pwalletMain->AddKeyPubKey(key, pubkey))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
// whenever a key is imported, we need to scan the whole chain
pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value'
if (fRescan) {
pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true);
}
}
return NullUniValue;
}
UniValue importaddress(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"importaddress \"address\" ( \"label\" rescan )\n"
"\nAdds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend.\n"
"\nArguments:\n"
"1. \"address\" (string, required) The address\n"
"2. \"label\" (string, optional, default=\"\") An optional label\n"
"3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
"\nNote: This call can take minutes to complete if rescan is true.\n"
"\nExamples:\n"
"\nImport an address with rescan\n" +
HelpExampleCli("importaddress", "\"myaddress\"") +
"\nImport using a label without rescan\n" + HelpExampleCli("importaddress", "\"myaddress\" \"testing\" false") +
"\nAs a JSON-RPC call\n" + HelpExampleRpc("importaddress", "\"myaddress\", \"testing\", false"));
CScript script;
CBitcoinAddress address(params[0].get_str());
if (address.IsValid()) {
script = GetScriptForDestination(address.Get());
} else if (IsHex(params[0].get_str())) {
std::vector<unsigned char> data(ParseHex(params[0].get_str()));
script = CScript(data.begin(), data.end());
} else {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid PROT address or script");
}
string strLabel = "";
if (params.size() > 1)
strLabel = params[1].get_str();
// Whether to perform rescan after import
bool fRescan = true;
if (params.size() > 2)
fRescan = params[2].get_bool();
{
if (::IsMine(*pwalletMain, script) == ISMINE_SPENDABLE)
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
// add to address book or update label
if (address.IsValid())
pwalletMain->SetAddressBook(address.Get(), strLabel, "receive");
// Don't throw error in case an address is already there
if (pwalletMain->HaveWatchOnly(script))
return NullUniValue;
pwalletMain->MarkDirty();
if (!pwalletMain->AddWatchOnly(script))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
if (fRescan) {
pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true);
pwalletMain->ReacceptWalletTransactions();
}
}
return NullUniValue;
}
UniValue importwallet(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"importwallet \"filename\"\n"
"\nImports keys from a wallet dump file (see dumpwallet).\n"
"\nArguments:\n"
"1. \"filename\" (string, required) The wallet file\n"
"\nExamples:\n"
"\nDump the wallet\n" +
HelpExampleCli("dumpwallet", "\"test\"") +
"\nImport the wallet\n" + HelpExampleCli("importwallet", "\"test\"") +
"\nImport using the json rpc call\n" + HelpExampleRpc("importwallet", "\"test\""));
EnsureWalletIsUnlocked();
ifstream file;
file.open(params[0].get_str().c_str(), std::ios::in | std::ios::ate);
if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
int64_t nTimeBegin = chainActive.Tip()->GetBlockTime();
bool fGood = true;
int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg());
file.seekg(0, file.beg);
pwalletMain->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI
while (file.good()) {
pwalletMain->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100))));
std::string line;
std::getline(file, line);
if (line.empty() || line[0] == '#')
continue;
std::vector<std::string> vstr;
boost::split(vstr, line, boost::is_any_of(" "));
if (vstr.size() < 2)
continue;
CBitcoinSecret vchSecret;
if (!vchSecret.SetString(vstr[0]))
continue;
CKey key = vchSecret.GetKey();
CPubKey pubkey = key.GetPubKey();
assert(key.VerifyPubKey(pubkey));
CKeyID keyid = pubkey.GetID();
if (pwalletMain->HaveKey(keyid)) {
LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString());
continue;
}
int64_t nTime = DecodeDumpTime(vstr[1]);
std::string strLabel;
bool fLabel = true;
for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {
if (boost::algorithm::starts_with(vstr[nStr], "#"))
break;
if (vstr[nStr] == "change=1")
fLabel = false;
if (vstr[nStr] == "reserve=1")
fLabel = false;
if (boost::algorithm::starts_with(vstr[nStr], "label=")) {
strLabel = DecodeDumpString(vstr[nStr].substr(6));
fLabel = true;
}
}
LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString());
if (!pwalletMain->AddKeyPubKey(key, pubkey)) {
fGood = false;
continue;
}
pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime;
if (fLabel)
pwalletMain->SetAddressBook(keyid, strLabel, "receive");
nTimeBegin = std::min(nTimeBegin, nTime);
}
file.close();
pwalletMain->ShowProgress("", 100); // hide progress dialog in GUI
CBlockIndex* pindex = chainActive.Tip();
while (pindex && pindex->pprev && pindex->GetBlockTime() > nTimeBegin - 7200)
pindex = pindex->pprev;
if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey)
pwalletMain->nTimeFirstKey = nTimeBegin;
LogPrintf("Rescanning last %i blocks\n", chainActive.Height() - pindex->nHeight + 1);
pwalletMain->ScanForWalletTransactions(pindex);
pwalletMain->MarkDirty();
if (!fGood)
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet");
return NullUniValue;
}
UniValue dumpprivkey(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"dumpprivkey \"protaddress\"\n"
"\nReveals the private key corresponding to 'protaddress'.\n"
"Then the importprivkey can be used with this output\n"
"\nArguments:\n"
"1. \"protaddress\" (string, required) The prot address for the private key\n"
"\nResult:\n"
"\"key\" (string) The private key\n"
"\nExamples:\n" +
HelpExampleCli("dumpprivkey", "\"myaddress\"") + HelpExampleCli("importprivkey", "\"mykey\"") + HelpExampleRpc("dumpprivkey", "\"myaddress\""));
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
CBitcoinAddress address;
if (!address.SetString(strAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid PROT address");
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
CKey vchSecret;
if (!pwalletMain->GetKey(keyID, vchSecret))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
return CBitcoinSecret(vchSecret).ToString();
}
UniValue dumpwallet(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"dumpwallet \"filename\"\n"
"\nDumps all wallet keys in a human-readable format.\n"
"\nArguments:\n"
"1. \"filename\" (string, required) The filename\n"
"\nExamples:\n" +
HelpExampleCli("dumpwallet", "\"test\"") + HelpExampleRpc("dumpwallet", "\"test\""));
EnsureWalletIsUnlocked();
ofstream file;
file.open(params[0].get_str().c_str());
if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
std::map<CKeyID, int64_t> mapKeyBirth;
std::set<CKeyID> setKeyPool;
pwalletMain->GetKeyBirthTimes(mapKeyBirth);
pwalletMain->GetAllReserveKeys(setKeyPool);
// sort time/key pairs
std::vector<std::pair<int64_t, CKeyID> > vKeyBirth;
for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) {
vKeyBirth.push_back(std::make_pair(it->second, it->first));
}
mapKeyBirth.clear();
std::sort(vKeyBirth.begin(), vKeyBirth.end());
// produce output
file << strprintf("# Wallet dump created by Protcoin %s (%s)\n", CLIENT_BUILD, CLIENT_DATE);
file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()));
file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString());
file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->GetBlockTime()));
file << "\n";
for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
const CKeyID& keyid = it->second;
std::string strTime = EncodeDumpTime(it->first);
std::string strAddr = CBitcoinAddress(keyid).ToString();
CKey key;
if (pwalletMain->GetKey(keyid, key)) {
if (pwalletMain->mapAddressBook.count(keyid)) {
file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid].name), strAddr);
} else if (setKeyPool.count(keyid)) {
file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr);
} else {
file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr);
}
}
}
file << "\n";
file << "# End of dump\n";
file.close();
return NullUniValue;
}
UniValue bip38encrypt(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"bip38encrypt \"protaddress\"\n"
"\nEncrypts a private key corresponding to 'protaddress'.\n"
"\nArguments:\n"
"1. \"protaddress\" (string, required) The prot address for the private key (you must hold the key already)\n"
"2. \"passphrase\" (string, required) The passphrase you want the private key to be encrypted with - Valid special chars: !#$%&'()*+,-./:;<=>?`{|}~ \n"
"\nResult:\n"
"\"key\" (string) The encrypted private key\n"
"\nExamples:\n");
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strPassphrase = params[1].get_str();
CBitcoinAddress address;
if (!address.SetString(strAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid PROT address");
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
CKey vchSecret;
if (!pwalletMain->GetKey(keyID, vchSecret))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
uint256 privKey = vchSecret.GetPrivKey_256();
string encryptedOut = BIP38_Encrypt(strAddress, strPassphrase, privKey, vchSecret.IsCompressed());
UniValue result(UniValue::VOBJ);
result.push_back(Pair("Addess", strAddress));
result.push_back(Pair("Encrypted Key", encryptedOut));
return result;
}
UniValue bip38decrypt(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"bip38decrypt \"protaddress\"\n"
"\nDecrypts and then imports password protected private key.\n"
"\nArguments:\n"
"1. \"encryptedkey\" (string, required) The encrypted private key\n"
"2. \"passphrase\" (string, required) The passphrase you want the private key to be encrypted with\n"
"\nResult:\n"
"\"key\" (string) The decrypted private key\n"
"\nExamples:\n");
EnsureWalletIsUnlocked();
/** Collect private key and passphrase **/
string strKey = params[0].get_str();
string strPassphrase = params[1].get_str();
uint256 privKey;
bool fCompressed;
if (!BIP38_Decrypt(strPassphrase, strKey, privKey, fCompressed))
throw JSONRPCError(RPC_WALLET_ERROR, "Failed To Decrypt");
UniValue result(UniValue::VOBJ);
result.push_back(Pair("privatekey", HexStr(privKey)));
CKey key;
key.Set(privKey.begin(), privKey.end(), fCompressed);
if (!key.IsValid())
throw JSONRPCError(RPC_WALLET_ERROR, "Private Key Not Valid");
CPubKey pubkey = key.GetPubKey();
pubkey.IsCompressed();
assert(key.VerifyPubKey(pubkey));
result.push_back(Pair("Address", CBitcoinAddress(pubkey.GetID()).ToString()));
CKeyID vchAddress = pubkey.GetID();
{
pwalletMain->MarkDirty();
pwalletMain->SetAddressBook(vchAddress, "", "receive");
// Don't throw error in case a key is already there
if (pwalletMain->HaveKey(vchAddress))
throw JSONRPCError(RPC_WALLET_ERROR, "Key already held by wallet");
pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1;
if (!pwalletMain->AddKeyPubKey(key, pubkey))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
// whenever a key is imported, we need to scan the whole chain
pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value'
pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true);
}
return result;
}
| [
"hrrrrr@naver.com"
] | hrrrrr@naver.com |
e44c9d60168c9b2979237815eec2ce5bd51da5f5 | 1b38af12a5cc0493efc96d791e0b0ea5cb98389b | /KindMap/KindMapView.cpp | f392aca2afbf88d2b61a27711d18a616c4138235 | [] | no_license | shenyczz/KLibrary | efce0689d496f2097d00da7faf46fb73f5102eb7 | 98eab1108f650253d243795222044989432c4d0e | refs/heads/master | 2022-12-14T10:05:58.636127 | 2020-09-18T02:05:17 | 2020-09-18T02:05:17 | 296,487,674 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 13,513 | cpp |
// KindMapView.cpp : CKindMapView 类的实现
//
#include "stdafx.h"
// SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的
// ATL 项目中进行定义,并允许与该项目共享文档代码。
#ifndef SHARED_HANDLERS
#include "KindMap.h"
#endif
#include "MainFrm.h"
#include "KindMapDoc.h"
#include "KindMapView.h"
#include "KTest.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CKindMapView
IMPLEMENT_DYNCREATE(CKindMapView, KGisView)
BEGIN_MESSAGE_MAP(CKindMapView, KGisView)
// 标准打印命令
ON_COMMAND(ID_FILE_PRINT, &KGisView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, &KGisView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, &CKindMapView::OnFilePrintPreview)
ON_WM_RBUTTONUP()
//ON_WM_CONTEXTMENU() // 屏蔽
ON_COMMAND(ID_KINDMAP_TEST, &CKindMapView::OnKindmapTest)
ON_UPDATE_COMMAND_UI(ID_KINDMAP_TEST,&CKindMapView::OnUpdateKindmapTest)
END_MESSAGE_MAP()
// CKindMapView 构造/析构
CKindMapView::CKindMapView()
{
// TODO: 在此处添加构造代码
}
CKindMapView::~CKindMapView()
{
}
BOOL CKindMapView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: 在此处通过修改
// CREATESTRUCT cs 来修改窗口类或样式
return KGisView::PreCreateWindow(cs);
}
// CKindMapView 绘制
void CKindMapView::OnDraw(CDC* pDC)
{
CKindMapDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: 在此处为本机数据添加绘制代码
KGisView::OnDraw(pDC);
//-----------------------------------------------------
HDC hDC = pDC->GetSafeHdc();
RECT rect;
::GetClientRect(this->GetSafeHwnd(),&rect);
// 解决拖动时的显示混乱
if(!this->IsMouseDraging())
{
//-----------------------------
// 这里可以显示不属于图层的信息
//pDC->TextOut(0,0,_T("这里可以显示不属于图层的信息"));
//-----------------------------
}
KDib* pDib = pDoc->GetDib();
pDib->AttachHBITMAP(pDoc->GetMapEngine()->GetHBitmap());
if(0)
{
Graphics* pGraphics = Graphics::FromHDC(hDC);
HDC hBufDC = ::CreateCompatibleDC(hDC);
HBITMAP hBitmap = ::CreateCompatibleBitmap(hDC, rect.right, rect.bottom);
HBITMAP hOldBitmap = (HBITMAP)::SelectObject(hBufDC,hBitmap);
::BitBlt(hBufDC,0,0,rect.right, rect.bottom,hDC,0,0,SRCCOPY);
pDib->AttachHBITMAP(hBitmap);
KImage* pImage = (KImage*)Bitmap::FromHBITMAP(hBitmap,NULL);
//pImage->Save(_T("e:\\temp\\321.png"),KImage::ImageType::png); // OK
::SelectObject(hBufDC,hOldBitmap);
::DeleteObject(hBitmap);
::DeleteDC(hBufDC);
_delete(pImage);
_delete(pGraphics);
}
//-----------------------------------------------------
}
// CKindMapView 打印
void CKindMapView::OnFilePrintPreview()
{
#ifndef SHARED_HANDLERS
//AFXPrintPreview(this);
#endif
//AFXPrintPreview(this);
KGisView::OnFilePrintPreview();
}
BOOL CKindMapView::OnPreparePrinting(CPrintInfo* pInfo)
{
// 默认准备
//return DoPreparePrinting(pInfo);
return KGisView::OnPreparePrinting(pInfo);
}
void CKindMapView::OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo)
{
// TODO: 添加额外的打印前进行的初始化过程
KGisView::OnBeginPrinting(pDC, pInfo);
}
void CKindMapView::OnEndPrinting(CDC* pDC, CPrintInfo* pInfo)
{
// TODO: 添加打印后进行的清理过程
KGisView::OnEndPrinting(pDC, pInfo);
}
void CKindMapView::OnRButtonUp(UINT nFlags, CPoint point)
{
KGisView::OnRButtonUp(nFlags, point);
//ClientToScreen(&point);
//OnContextMenu(this, point);
}
void CKindMapView::OnContextMenu(CWnd* pWnd, CPoint point)
{
#ifndef SHARED_HANDLERS
theApp.GetContextMenuManager()->ShowPopupMenu(IDR_POPUP_EDIT, point.x, point.y, this, TRUE);
#endif
//KGisView::OnContextMenu(pWnd, point);
}
// CKindMapView 诊断
#ifdef _DEBUG
void CKindMapView::AssertValid() const
{
KGisView::AssertValid();
}
void CKindMapView::Dump(CDumpContext& dc) const
{
KGisView::Dump(dc);
}
CKindMapDoc* CKindMapView::GetDocument() const // 非调试版本是内联的
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CKindMapDoc)));
return (CKindMapDoc*)m_pDocument;
}
#endif //_DEBUG
// CKindMapView 消息处理程序
void CKindMapView::OnKindmapTest()
{
//-----------------------------------------------------
//ftp://172.18.152.243/Yaogan/地市级业务软件/
//ftp://172.18.152.243/Yaogan/%B5%D8%CA%D0%BC%B6%D2%B5%CE%F1%C8%ED%BC%FE/
//-----------------------------------------------------
//AGMRS_PRODUCT_CODE_VIX_NDVI
agmrsProductGenerate_Vix(AGMRS_PRODUCT_CODE_VIX_RVI);
//agmrsProductGenerate_Vix(AGMRS_PRODUCT_CODE_VIX_DVI);
//agmrsProductGenerate_Vix(AGMRS_PRODUCT_CODE_VIX_LAI);
//agmrsProductGenerate_Lst(0);
//MessageBox(_T("OnKindmapTest"));
return;
}
void CKindMapView::OnUpdateKindmapTest(CCmdUI* pCmdUI)
{
pCmdUI->SetCheck(m_iGisTool == GisTool_Misce_Landmark_Calibrate);
}
void CKindMapView::agmrsProductGenerate_Lst(int iMethod)
{
//-----------------------------------------------------
CMainFrame* pMainFrame = (CMainFrame*)AfxGetMainWnd();
KLayerDockablePane* pLayerWnd = (KLayerDockablePane*)pMainFrame->GetLayerWnd();
KLayer* pLayer = pLayerWnd->GetSelectedLayer();
if(!pLayer)
{
AfxMessageBox(_T("没有选择数据图层"));
return;
}
// 数据提供者
KProvider* pProvider = pLayer->GetProvider();
if(!pProvider)
return;
// 数据对象
KAgmrsData* pAgmrsData = (KAgmrsData*)pProvider->GetDataObject();
if(!pAgmrsData)
return;
//-----------------------------------------------------
// 进度参数
ProgressParam* pProgressParam = new ProgressParam();
pProgressParam->iFlag = 0;
pProgressParam->indexPaneProgress = 1;
pProgressParam->indexPaneText = 2;
pProgressParam->SetInfo(_T("地表温度反演..."));
// 注册进度显示
pAgmrsData->RegiestCallbackFunc(KCallbackFunc::ShowProgressCallback,pProgressParam,TRUE);
//-----------------------------------------------------
// 地表温度反演处理
if(!pAgmrsData->Lst(iMethod))
{
// 复位进度显示
CMFCStatusBar* pMFCStatusBar = (CMFCStatusBar*)((KWinAppEx*)AfxGetApp())->GetStatusBar();
if(pMFCStatusBar)
{
pMFCStatusBar->SetPaneText(pProgressParam->indexPaneText,_T(""));
pMFCStatusBar->EnablePaneProgressBar(pProgressParam->indexPaneProgress,-1);
}
return;
}
// 复位进度显示
CMFCStatusBar* pMFCStatusBar = (CMFCStatusBar*)((KWinAppEx*)AfxGetApp())->GetStatusBar();
if(pMFCStatusBar)
{
pMFCStatusBar->SetPaneText(pProgressParam->indexPaneText,_T(""));
pMFCStatusBar->EnablePaneProgressBar(pProgressParam->indexPaneProgress,-1);
}
// 产品数据与产品数据信息
KAgmrsDataProcessor* pAgmrsDataProcessor = (KAgmrsDataProcessor*)pAgmrsData->GetDataProcessor();
PFLOAT* ppfProduct = pAgmrsDataProcessor->GetProductData();
KDataInfo* pProductDataInfo = pAgmrsData->GetProductDataInfo();
// 构造文件名
TCHAR szFile[MAX_PATH] = _T("");
_stprintf(szFile,_T("C:\\TopPath\\Lst\\%s"),pAgmrsData->NameProduct(AGMRS_PRODUCT_CODE_MISC_LST));
// 调色板
KPalette* pPalette = NULL;
if(pPalette)
{
// 设置调色板透明色
pPalette->HasTransparentColor() = FALSE;
pPalette->TransparentColor() = RGB(0,0,0);
}
// 保存文件
if(!KAxinData::CreateFile(szFile,*ppfProduct,pProductDataInfo,pPalette))
{
CString strFile;
strFile.Format(_T("创建文件错误 - %s"),szFile);
AfxMessageBox(strFile);
}
else
{
// 导出 ENVI 文件头
CString sf=szFile;
sf.Replace(_T("axd"),_T("hdr"));
KGridImageData gid;
gid.LoadData(szFile);
gid.ExportEnviHdr(sf);
// 打开文件
theApp.OpenDocumentFile(szFile);
}
return;
}
void CKindMapView::agmrsProductGenerate_Vix(int iProductID)
{
//-----------------------------------------------------
CMainFrame* pMainFrame = (CMainFrame*)AfxGetMainWnd();
KLayerDockablePane* pLayerWnd = (KLayerDockablePane*)pMainFrame->GetLayerWnd();
KLayer* pLayer = pLayerWnd->GetSelectedLayer();
if(!pLayer)
{
AfxMessageBox(_T("没有选择数据图层"));
return;
}
// 图层类型
LayerType eLayerType = (LayerType)pLayer->GetType();
// 是否是农业遥感数据
BOOL bAgmrsDataLayer = FALSE
|| eLayerType == LayerType_Avhrr
|| eLayerType == LayerType_Modis
|| eLayerType == LayerType_Mersi
|| eLayerType == LayerType_Virr
;
// 图层类型
if(!bAgmrsDataLayer)
{
AfxMessageBox(_T("没有选择正确的图层。\n\n可能需要选择干数据图层..."));
return;
}
// 数据提供者
KProvider* pProvider = pLayer->GetProvider();
if(!pProvider)
return;
// 数据对象
KAgmrsData* pAgmrsData = (KAgmrsData*)pProvider->GetDataObject();
if(!pAgmrsData)
return;
//-----------------------------------------------------
// 进度参数
ProgressParam* pProgressParam = new ProgressParam();
pProgressParam->iFlag = 0;
pProgressParam->indexPaneProgress = 1;
pProgressParam->indexPaneText = 2;
pProgressParam->SetInfo(_T("植被指数反演..."));
// 注册进度显示
pAgmrsData->RegiestCallbackFunc(KCallbackFunc::ShowProgressCallback,pProgressParam,TRUE);
//-----------------------------------------------------
// 干旱指数反演处理
KStringArray sa;
sa.Add(_T("0501"));
KAgmrsAlgorithm* pAgmrsAlgorithm = (KAgmrsAlgorithm*)pAgmrsData->GetDataProcessor()->GetDataAlgorithm();
pAgmrsAlgorithm->SetLaiConfig(sa);
if(!pAgmrsData->Vix(iProductID))
{
// 复位进度显示
CMFCStatusBar* pMFCStatusBar = (CMFCStatusBar*)((KWinAppEx*)AfxGetApp())->GetStatusBar();
if(pMFCStatusBar)
{
pMFCStatusBar->SetPaneText(pProgressParam->indexPaneText,_T(""));
pMFCStatusBar->EnablePaneProgressBar(pProgressParam->indexPaneProgress,-1);
}
return;
}
// 复位进度显示
CMFCStatusBar* pMFCStatusBar = (CMFCStatusBar*)((KWinAppEx*)AfxGetApp())->GetStatusBar();
if(pMFCStatusBar)
{
pMFCStatusBar->SetPaneText(pProgressParam->indexPaneText,_T(""));
pMFCStatusBar->EnablePaneProgressBar(pProgressParam->indexPaneProgress,-1);
}
// 取得产品数据与产品数据信息
KAgmrsDataProcessor* pAgmrsDataProcessor = (KAgmrsDataProcessor*)pAgmrsData->GetDataProcessor();
PFLOAT* ppfProduct = pAgmrsDataProcessor->GetProductData();
KDataInfo* pProductDataInfo = pAgmrsData->GetProductDataInfo();
// 构造文件名
TCHAR szFile[MAX_PATH] = _T("");
_stprintf(szFile,_T("C:\\TopPath\\Vix\\%s"),pAgmrsData->NameProduct(iProductID));
// 调色板
KPalette* pPalette = NULL;
pPalette = KAgmrsData::GetAgmrsProductPalette(iProductID);
if(pPalette)
{
// 设置调色板透明色
pPalette->HasTransparentColor() = FALSE;
pPalette->TransparentColor() = RGB(0,0,0);
}
// 保存文件
if(!KAxinData::CreateFile(szFile,*ppfProduct,pProductDataInfo,pPalette))
{
CString strFile;
strFile.Format(_T("创建文件错误 - %s"),szFile);
AfxMessageBox(strFile);
}
else
{
// 打开文件
theApp.OpenDocumentFile(szFile);
}
return;
}
void CKindMapView::agmrsProductGenerate_Misc(int iProductID)
{
//-----------------------------------------------------
CMainFrame* pMainFrame = (CMainFrame*)AfxGetMainWnd();
KLayerDockablePane* pLayerWnd = (KLayerDockablePane*)pMainFrame->GetLayerWnd();
KLayer* pLayer = pLayerWnd->GetSelectedLayer();
if(!pLayer)
{
AfxMessageBox(_T("没有选择数据图层"));
return;
}
// 图层类型
const int iLayerType = pLayer->GetType();
if( TRUE
&& iLayerType != LayerType_Avhrr
&& iLayerType != LayerType_Modis
&& iLayerType != LayerType_Mersi
&& iLayerType != LayerType_Virr
)
{
AfxMessageBox(_T("没有选择正确的图层。\n\n可能需要选择遥感数据图层..."));
return;
}
// 数据提供者
KProvider* pProvider = pLayer->GetProvider();
if(!pProvider)
return;
// 数据对象
KAgmrsData* pAgmrsData = (KAgmrsData*)pProvider->GetDataObject();
if(!pAgmrsData)
return;
pAgmrsData->GetDataProcessor()->SetFlag(1);
//-----------------------------------------------------
// 进度参数
ProgressParam* pProgressParam = new ProgressParam();
pProgressParam->iFlag = 0;
pProgressParam->indexPaneProgress = 1;
pProgressParam->indexPaneText = 2;
pProgressParam->SetInfo(_T("其他检测项目..."));
// 注册进度显示
pAgmrsData->RegiestCallbackFunc(KCallbackFunc::ShowProgressCallback,pProgressParam,TRUE);
//-----------------------------------------------------
// 杂项检测处理
if(!pAgmrsData->Sim(iProductID))
{
// 复位进度显示
CMFCStatusBar* pMFCStatusBar = (CMFCStatusBar*)((KWinAppEx*)AfxGetApp())->GetStatusBar();
if(pMFCStatusBar)
{
pMFCStatusBar->SetPaneText(pProgressParam->indexPaneText,_T(""));
pMFCStatusBar->EnablePaneProgressBar(pProgressParam->indexPaneProgress,-1);
}
return;
}
//-----------------------------------------------------
// 复位进度显示
CMFCStatusBar* pMFCStatusBar = (CMFCStatusBar*)((KWinAppEx*)AfxGetApp())->GetStatusBar();
if(pMFCStatusBar)
{
pMFCStatusBar->SetPaneText(pProgressParam->indexPaneText,_T(""));
pMFCStatusBar->EnablePaneProgressBar(pProgressParam->indexPaneProgress,-1);
}
// 产品数据与产品数据信息
KAgmrsDataProcessor* pAgmrsDataProcessor = (KAgmrsDataProcessor*)pAgmrsData->GetDataProcessor();
PFLOAT* ppfProduct = pAgmrsDataProcessor->GetProductData();
KDataInfo* pProductDataInfo = pAgmrsData->GetProductDataInfo(); // 产品信息
FirePointVector* pFirePointVector = pAgmrsDataProcessor->GetFirePointVector(); // 火点集合
//-----------------------------------------------------
CString strFireCount;
strFireCount.Format(_T("火点数量 - %d"),pFirePointVector->size());
AfxMessageBox(strFireCount);
//-----------------------------------------------------
return;
}
| [
"shenyczz@163.com"
] | shenyczz@163.com |
d09f681c5b0e0dada9abecfcda452752b43c0339 | b99dfe8f25f1092b38af1423c23b08e10891fde5 | /CloudDynamicFlexTaskLoop.cpp | 75dd84fcc3ba84563b37c91b5cc9fd805a28d6cb | [] | no_license | 15831944/linux-cloud | f085a5f3c21f9bc9dd93c94de6478d6e6ba12dd7 | 0360a5cd3fa8eaa12d018be375b709b4422b5759 | refs/heads/master | 2021-12-09T12:31:45.103716 | 2016-05-17T06:10:53 | 2016-05-17T06:10:53 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 99,260 | cpp | #include <time.h>
#include <map>
#include <iostream>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include "CloudDynamicFlexTaskLoop.h"
#include "CheckPoint.h"
#include <boost/typeof/typeof.hpp>
#include <boost/lexical_cast.hpp>
#include "json/json.h"
namespace BM35
{
// 获取bolname,域名信息
/*void CloudDynamicFlexTaskLoop::recordHostBaseInfo()
{
bmco_debug(theLogger, "recordHostBaseInfo()");
std::string bolName;
//std::string domainName;
MetaBolConfigOp* c = dynamic_cast<MetaBolConfigOp*>(ctlOper->getObjectPtr(MetaBolConfigOp::getObjName()));
MetaBolConfigInfo::Ptr cfgpayload(new MetaBolConfigInfo("info.bol_name"));
if (c->Query(cfgpayload))
{
bolName = cfgpayload->_strval.c_str();
}
else
{
return;
}
m_sessionContent.sessionBolName = bolName;
bmco_information_f3(theLogger, "%s|%s|bolName=%s",
std::string("0"),std::string(__FUNCTION__),
m_sessionContent.sessionBolName);
}*/
// 获取/status/kpi 下面所有bol的指标信息
void CloudDynamicFlexTaskLoop::recordParentKPIPath()
{
Bmco::Util::AbstractConfiguration& config = Bmco::Util::Application::instance().config();
std::string bolName = g_sessionData.getBolName();
// std::string domainName = m_sessionContent.sessionDomainName.c_str();
std::string KPIInfoPath = ZNODE_ZOOKEEPER_STATUS_KPI + "/bol";
if (!CloudDatabaseHandler::instance()->nodeExist(KPIInfoPath))
{
return;
}
std::vector<std::string> childrenVec;
childrenVec.clear();
// 获取当前bol的指标信息,如果有指标,应该是多个BOL目录
if (!CloudDatabaseHandler::instance()->GetChildrenNode(KPIInfoPath, childrenVec))
{
bmco_error_f3(theLogger, "%s|%s|GetChildrenNode [%s] failed", std::string("0"),std::string(__FUNCTION__), KPIInfoPath);
return;
}
// 没有指标
if (0 == childrenVec.size())
{
return;
}
std::vector<std::string>::iterator it;
std::string cmdString;
std::vector<struct kpiinfo> tmpVec;
// m_sessionContent.sessionKpiInfo.clear();
// 收集的是各个bolname
for (it = childrenVec.begin();it != childrenVec.end();it++)
{
recordKPIInfo(*it, tmpVec);
}
g_sessionData.setKpiInfo(tmpVec);
bmco_debug(theLogger, "recordParentKPIPath successfully");
}
// 获取记录某个BOL的指标信息
void CloudDynamicFlexTaskLoop::recordKPIInfo(std::string bolName,
std::vector<struct kpiinfo> &tmpVec)
{
bmco_debug(theLogger, "recordKPIInfo()");
std::string KPIInfoPath = "/status/kpi/bol/" + bolName;
std::string cloudConfigStr;
try
{
if (!CloudDatabaseHandler::instance()->nodeExist(KPIInfoPath))
{
bmco_error_f3(theLogger, "%s|%s|%s is disappeared when download!",
std::string("0"),std::string(__FUNCTION__), KPIInfoPath);
return;
}
bool isChanged = false;
if (!CloudDatabaseHandler::instance()->getNodeChangedFlag(KPIInfoPath, isChanged))
{
bmco_error_f3(theLogger, "%s|%s|%s is getNodeChangedFlag failed!",
std::string("0"),std::string(__FUNCTION__), KPIInfoPath);
return;
}
// 节点内容没有变化不处理
if (!isChanged)
{
return;
}
Json::Value root;
Json::Reader jsonReader;
if (0 != CloudDatabaseHandler::instance()->getNodeData(KPIInfoPath, cloudConfigStr))
{
bmco_error_f3(theLogger, "%s|%s|data error at %s", std::string("0"),std::string(__FUNCTION__), KPIInfoPath);
return;
}
if (cloudConfigStr.empty())
{
bmco_information_f3(theLogger, "%s|%s|no data in %s", std::string("0"),std::string(__FUNCTION__), KPIInfoPath);
return;
}
if (!jsonReader.parse(cloudConfigStr, root))
{
return;
}
if (!root.isMember("record"))
{
bmco_error_f2(theLogger, "%s|%s|no record",std::string("0"),std::string(__FUNCTION__));
return;
}
Json::Value valueArray = root["record"];
for (int index = 0; index < valueArray.size(); ++index)
{
Json::Value value = valueArray[index];
if (!value.isMember("kpi_id"))
{
bmco_error_f2(theLogger, "%s|%s|no kpi_id",std::string("0"),std::string(__FUNCTION__));
return;
}
if (!value.isMember("bol_name"))
{
bmco_error_f2(theLogger, "%s|%s|no bol_name",std::string("0"),std::string(__FUNCTION__));
return;
}
if (!value.isMember("kpi_value"))
{
bmco_error_f2(theLogger, "%s|%s|no kpi_value",std::string("0"),std::string(__FUNCTION__));
return;
}
struct kpiinfo tmpKpiInfo;
tmpKpiInfo.kpi_id = value["kpi_id"].asString();
tmpKpiInfo.bol_cloud_name = value["seq_no"].asString();
tmpKpiInfo.bol_cloud_name = value["bol_name"].asString();
tmpKpiInfo.kpi_value = value["kpi_value"].asString();
tmpVec.push_back(tmpKpiInfo);
}
}
catch (boost::bad_lexical_cast &e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),std::string(e.what()));
return;
}
catch(Bmco::Exception &e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),e.displayText());
return;
}
catch(std::exception& e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),std::string(e.what()));
return;
}
catch(...)
{
bmco_error_f2(theLogger,"%s|%s|unknown exception occured when recordKPIInfo!",
std::string("0"),std::string(__FUNCTION__));
return;
}
bmco_information_f1(theLogger, "recordKPIInfo [%s] successfully", KPIInfoPath);
}
// 获取记录bol配置信息
// 包括bolid bolname,ipaddr,user_pwd_id,nideid,auto_flex_flag
void CloudDynamicFlexTaskLoop::recordBOLInfo()
{
bmco_debug(theLogger, "recordBOLInfo()");
Bmco::Util::AbstractConfiguration& config = Bmco::Util::Application::instance().config();
std::string NodeInfoPath = ZNODE_ZOOKEEPER_CLUSTER + "/node";
std::string BolInfoPath = ZNODE_ZOOKEEPER_CLUSTER + "/bolcfg";
std::string cloudNodeConfigStr;
std::string cloudBolConfigStr;
try
{
if (0 != CloudDatabaseHandler::instance()->getNodeData(NodeInfoPath, cloudNodeConfigStr))
{
bmco_error_f3(theLogger, "%s|%s|data error at %s", std::string("0"),std::string(__FUNCTION__), NodeInfoPath);
return;
}
if (cloudNodeConfigStr.empty())
{
bmco_error_f3(theLogger, "%s|%s|no data in %s", std::string("0"),std::string(__FUNCTION__), NodeInfoPath);
return;
}
if (0 != CloudDatabaseHandler::instance()->getNodeData(BolInfoPath, cloudBolConfigStr))
{
bmco_error_f3(theLogger, "%s|%s|data error at %s", std::string("0"),std::string(__FUNCTION__), BolInfoPath);
return;
}
if (cloudBolConfigStr.empty())
{
bmco_error_f3(theLogger, "%s|%s|no data in %s", std::string("0"),std::string(__FUNCTION__), BolInfoPath);
return;
}
Json::Value pNodeRootNode;
Json::Value pBolRootNode;
Json::Reader jsonNodeReader;
Json::Reader jsonBolReader;
if (!jsonNodeReader.parse(cloudNodeConfigStr, pNodeRootNode))
{
return;
}
if (!jsonBolReader.parse(cloudBolConfigStr, pBolRootNode))
{
return;
}
std::string bolName = g_sessionData.getBolName();
if (!pNodeRootNode.isMember("record"))
{
bmco_error_f2(theLogger, "%s|%s|no record",std::string("0"),std::string(__FUNCTION__));
return;
}
if (!pBolRootNode.isMember("record"))
{
bmco_error_f2(theLogger, "%s|%s|no record",std::string("0"),std::string(__FUNCTION__));
return;
}
Json::Value valueNodeArray = pNodeRootNode["record"];
Json::Value valueBolArray = pBolRootNode["record"];
struct bolinfo tmpBolInfo;
std::vector<struct bolinfo> tmpVec;
for (int indexNode = 0; indexNode < valueNodeArray.size(); ++indexNode)
{
Json::Value valueNode = valueNodeArray[indexNode];
if (!valueNode.isMember("node_id"))
{
bmco_error_f2(theLogger, "%s|%s|no node_id",std::string("0"),std::string(__FUNCTION__));
return;
}
if (!valueNode.isMember("node_name"))
{
bmco_error_f2(theLogger, "%s|%s|no node_name",std::string("0"),std::string(__FUNCTION__));
return;
}
if (!valueNode.isMember("hostname"))
{
bmco_error_f2(theLogger, "%s|%s|no hostname",std::string("0"),std::string(__FUNCTION__));
return;
}
if (!valueNode.isMember("ip_addr"))
{
bmco_error_f2(theLogger, "%s|%s|no ip_addr",std::string("0"),std::string(__FUNCTION__));
return;
}
for (int indexBol = 0; indexBol < valueBolArray.size(); ++indexBol)
{
Json::Value valueBol = valueBolArray[indexBol];
if (!valueBol.isMember("node_id"))
{
bmco_error_f2(theLogger, "%s|%s|no node_id",std::string("0"),std::string(__FUNCTION__));
return;
}
if (!valueBol.isMember("bol_id"))
{
bmco_error_f2(theLogger, "%s|%s|no bol_id",std::string("0"),std::string(__FUNCTION__));
return;
}
if (!valueBol.isMember("bol_name"))
{
bmco_error_f2(theLogger, "%s|%s|no bol_name",std::string("0"),std::string(__FUNCTION__));
return;
}
if (!valueBol.isMember("bol_dir"))
{
bmco_error_f2(theLogger, "%s|%s|no bol_dir",std::string("0"),std::string(__FUNCTION__));
return;
}
if (!valueBol.isMember("auto_flex_flag"))
{
bmco_error_f2(theLogger, "%s|%s|no auto_flex_flag",std::string("0"),std::string(__FUNCTION__));
return;
}
if (!valueBol.isMember("master_flag"))
{
bmco_error_f2(theLogger, "%s|%s|no master_flag",std::string("0"),std::string(__FUNCTION__));
return;
}
if (!valueBol.isMember("subsys_type"))
{
bmco_error_f2(theLogger, "%s|%s|no subsys_type",std::string("0"),std::string(__FUNCTION__));
return;
}
if (!valueBol.isMember("domain_type"))
{
bmco_error_f2(theLogger, "%s|%s|no domain_type",std::string("0"),std::string(__FUNCTION__));
return;
}
if (!valueBol.isMember("user_name"))
{
bmco_error_f2(theLogger, "%s|%s|no user_name",std::string("0"),std::string(__FUNCTION__));
return;
}
if (valueNode["node_id"].asString()
== valueBol["node_id"].asString())
{
if (0 == bolName.compare(valueBol["bol_name"].asString()))
{
g_sessionData.setSubSys(valueBol["subsys_type"].asString());
g_sessionData.setDomainName(valueBol["domain_type"].asString());
}
tmpBolInfo.bol_id = valueBol["bol_id"].asString();
tmpBolInfo.bol_cloud_name = valueBol["bol_name"].asString();
tmpBolInfo.nedir = valueBol["bol_dir"].asString();
tmpBolInfo.node_id = valueNode["node_id"].asString();
tmpBolInfo.node_name = valueNode["node_name"].asString();
tmpBolInfo.hostname = valueNode["hostname"].asString();
tmpBolInfo.ip_addr = valueNode["ip_addr"].asString();
tmpBolInfo.auto_flex_flag = valueBol["auto_flex_flag"].asString();
tmpBolInfo.master_flag = valueBol["master_flag"].asString();
tmpBolInfo.subsys = valueBol["subsys_type"].asString();
tmpBolInfo.domainName = valueBol["domain_type"].asString();
tmpBolInfo.userName = valueBol["user_name"].asString();
tmpVec.push_back(tmpBolInfo);
}
}
}
g_sessionData.setBolInfo(tmpVec);
}
catch (boost::bad_lexical_cast &e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),std::string(e.what()));
return;
}
catch(Bmco::Exception &e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),e.displayText());
return;
}
catch(std::exception& e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),std::string(e.what()));
return;
}
catch(...)
{
bmco_error_f2(theLogger,"%s|%s|unknown exception occured when recordBOLInfo!",
std::string("0"),std::string(__FUNCTION__));
return;
}
bmco_information(theLogger, "recordBOLInfo successfully");
}
void CloudDynamicFlexTaskLoop::recordFlexInfo()
{
// 在zookeeper上获取规则表信息
Bmco::Util::AbstractConfiguration& config = Bmco::Util::Application::instance().config();
std::string nodePath(ZNODE_ZOOKEEPER_FlEX);
std::string cloudConfigStr;
if (!CloudDatabaseHandler::instance()->nodeExist(nodePath))
{
bmco_information_f3(theLogger, "%s|%s|node:%s does not exist",std::string("0"),std::string(__FUNCTION__),
nodePath);
return;
}
try
{
if (0 != CloudDatabaseHandler::instance()->getNodeData(nodePath, cloudConfigStr))
{
bmco_error_f3(theLogger, "%s|%s|data error at %s", std::string("0"),std::string(__FUNCTION__), nodePath);
return;
}
if (cloudConfigStr.empty())
{
bmco_information_f3(theLogger, "%s|%s|no data in %s", std::string("0"),std::string(__FUNCTION__), nodePath);
return;
}
Json::Value root;
Json::Reader jsonReader;
if (!jsonReader.parse(cloudConfigStr, root))
{
return;
}
if (!root.isMember("record"))
{
bmco_error_f2(theLogger, "%s|%s|no record",std::string("0"),std::string(__FUNCTION__));
return;
}
Json::Value valueArray = root["record"];
std::vector<struct flexinfo> tmpVec;
for (int index = 0; index < valueArray.size(); ++index)
{
Json::Value value = valueArray[index];
struct flexinfo tmpFlexInfo;
tmpFlexInfo.rule_id = value["rule_id"].asString();
tmpFlexInfo.subsys_type = value["subsys_type"].asString();
tmpFlexInfo.domain_type = value["domain_type"].asString();
tmpFlexInfo.rule_name = value["rule_name"].asString();
tmpFlexInfo.rule_desc = value["rule_desc"].asString();
tmpFlexInfo.rule_type = value["rule_type"].asString();
tmpFlexInfo.kpi_name_str = value["kpi_name_str"].asString();
tmpFlexInfo.value_str = value["value_str"].asString();
tmpFlexInfo.status = value["status"].asString();
tmpFlexInfo.create_date = value["create_date"].asString();
tmpFlexInfo.modi_date = value["modi_date"].asString();
tmpVec.push_back(tmpFlexInfo);
}
g_sessionData.setFlexInfo(tmpVec);
}
catch (boost::bad_lexical_cast &e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),std::string(e.what()));
return;
}
catch(Bmco::Exception &e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),e.displayText());
return;
}
catch(std::exception& e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),std::string(e.what()));
return;
}
catch(...)
{
bmco_error_f2(theLogger,"%s|%s|unknown exception occured when recordFlexInfo!",
std::string("0"),std::string(__FUNCTION__));
return;
}
bmco_information(theLogger, "recordFlexInfo successfully");
}
void CloudDynamicFlexTaskLoop::recordDictInfo()
{
// 在zookeeper上获取规则表信息
Bmco::Util::AbstractConfiguration& config = Bmco::Util::Application::instance().config();
std::string nodePath(ZNODE_ZOOKEEPER_DICT);
std::string cloudConfigStr;
if (!CloudDatabaseHandler::instance()->nodeExist(nodePath))
{
bmco_information_f3(theLogger, "%s|%s|node:%s does not exist",std::string("0"),std::string(__FUNCTION__),
nodePath);
return;
}
try
{
if (0 != CloudDatabaseHandler::instance()->getNodeData(nodePath, cloudConfigStr))
{
bmco_error_f3(theLogger, "%s|%s|data error at %s", std::string("0"),std::string(__FUNCTION__), nodePath);
return;
}
if (cloudConfigStr.empty())
{
bmco_information_f3(theLogger, "%s|%s|no data in %s", std::string("0"),std::string(__FUNCTION__), nodePath);
return;
}
Json::Value root;
Json::Reader jsonReader;
if (!jsonReader.parse(cloudConfigStr, root))
{
return;
}
if (!root.isMember("record"))
{
bmco_error_f2(theLogger, "%s|%s|no record",std::string("0"),std::string(__FUNCTION__));
return;
}
Json::Value valueArray = root["record"];
std::vector<struct dictinfo> tmpVec;
for (int index = 0; index < valueArray.size(); ++index)
{
Json::Value value = valueArray[index];
struct dictinfo tmpDictInfo;
tmpDictInfo.id = value["id"].asString();
tmpDictInfo.type = value["type"].asString();
tmpDictInfo.key = value["key"].asString();
tmpDictInfo.value = value["value"].asString();
tmpDictInfo.desc = value["desc"].asString();
tmpDictInfo.begin_date = value["begin_date"].asString();
tmpDictInfo.end_date = value["end_date"].asString();
tmpVec.push_back(tmpDictInfo);
}
g_sessionData.setDictInfo(tmpVec);
}
catch (boost::bad_lexical_cast &e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),std::string(e.what()));
return;
}
catch(Bmco::Exception &e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),e.displayText());
return;
}
catch(std::exception& e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),std::string(e.what()));
return;
}
catch(...)
{
bmco_error_f2(theLogger,"%s|%s|unknown exception occured when recordDictInfo!",
std::string("0"),std::string(__FUNCTION__));
return;
}
bmco_information(theLogger, "recordDictInfo successfully");
}
/*void CloudDynamicFlexTaskLoop::recordMQDefInfo()
{
// 在zookeeper上获取消息队列定义表信息
Bmco::Util::AbstractConfiguration& config = Bmco::Util::Application::instance().config();
std::string nodePath(ZNODE_ZOOKEEPER_MQ_MQ);
std::string cloudConfigStr;
if (!CloudDatabaseHandler::instance()->nodeExist(nodePath))
{
bmco_information_f3(theLogger, "%s|%s|node:%s does not exist",std::string("0"),std::string(__FUNCTION__),
nodePath);
return;
}
try
{
if (0 != CloudDatabaseHandler::instance()->getNodeData(nodePath, cloudConfigStr))
{
bmco_error_f3(theLogger, "%s|%s|data error at %s", std::string("0"),std::string(__FUNCTION__), nodePath);
return;
}
std::istringstream istr(cloudConfigStr);
Bmco::AutoPtr<IniFileConfigurationNew> pConf = new IniFileConfigurationNew(istr);
int nodeNum = pConf->getInt(TABLE_PREFIX_LIST[1] + ".recordnum");
for (int i = 1; i <= nodeNum; i++)
{
std::string ruleCheckStr = pConf->getString(TABLE_PREFIX_LIST[1] + ".record." + Bmco::NumberFormatter::format(i));
bmco_information_f3(theLogger, "%s|%s|ruleCheckStr: %s",
std::string("0"),std::string(__FUNCTION__),ruleCheckStr);
Bmco::StringTokenizer tokensRuleStr(ruleCheckStr, "|", Bmco::StringTokenizer::TOK_TRIM);
Bmco::StringTokenizer tokensDefStr(tokensRuleStr[3], ",", Bmco::StringTokenizer::TOK_TRIM);
m_brokerlist = tokensDefStr[0];
}
}
catch(Bmco::Exception &e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),e.displayText());
return;
}
catch(...)
{
bmco_error_f2(theLogger,"%s|%s|unknown exception occured when recordMQDefInfo!",
std::string("0"),std::string(__FUNCTION__));
return;
}
m_zookeeperlist = config.getString("zkConf.zookeeper.host");
bmco_information(theLogger, "recordMQDefInfo successfully");
}*/
bool CloudDynamicFlexTaskLoop::recordTopicInfo(std::string currTopicName,
std::string &domainName)
{
MetaMQTopicOp *tmpTopicPtr = NULL;
tmpTopicPtr = dynamic_cast<MetaMQTopicOp*>(ctlOper->getObjectPtr(MetaMQTopicOp::getObjName()));
std::vector<MetaMQTopic> vecTopicInfo;
Bmco::UInt32 partitionNum = 0;
std::string topicName;
if (!tmpTopicPtr->getAllMQTopic(vecTopicInfo))
{
bmco_error_f2(theLogger, "%s|%s|Failed to execute getAllMQTopic on MetaShmTopicInfoTable",std::string("0"),std::string(__FUNCTION__));
return false;
}
m_topicInfoMap.clear();
std::vector<MetaMQTopic>::iterator it;
std::map<std::string, Bmco::UInt32>::iterator itMap;
for (it = vecTopicInfo.begin();it != vecTopicInfo.end();it++)
{
topicName = it->Topic_name.c_str();
partitionNum = it->Partition_number;
if (0 == currTopicName.compare(topicName))
{
domainName = it->domain_type.c_str();
}
itMap = m_topicInfoMap.find(topicName);
if (itMap == m_topicInfoMap.end())
{
m_topicInfoMap.insert(std::pair<std::string, Bmco::UInt32>(topicName, partitionNum));
}
else
{
m_topicInfoMap[topicName] = partitionNum;
}
}
return true;
}
bool CloudDynamicFlexTaskLoop::recordRelaInfo()
{
MetaMQRelaOp *tmpRelaPtr = NULL;
std::vector<MetaMQRela> vecRelaInfo;
tmpRelaPtr = dynamic_cast<MetaMQRelaOp*>(ctlOper->getObjectPtr(MetaMQRelaOp::getObjName()));
m_relaInfoVec.clear();
// 获取消息队列关系信息
if (!tmpRelaPtr->getAllMQRela(m_relaInfoVec))
{
bmco_error_f2(theLogger, "%s|%s|Failed to execute getAllMQRela on MetaShmRelaInfoTable",std::string("0"),std::string(__FUNCTION__));
return false;
}
return true;
}
// 远程启动bol,一定要将新启动的bol的云代理同时启动
bool CloudDynamicFlexTaskLoop::launchBolNode(const std::string bolName)
{
char cBuf[1024];
memset(cBuf, 0, sizeof(cBuf));
Bmco::Int32 ret = -999;
std::string des_ipaddr;
std::string des_dir;
std::string des_user;
std::vector<struct bolinfo> sessionBolInfo;
g_sessionData.getBolInfo(sessionBolInfo);
std::vector<struct bolinfo>::iterator it;
for (it = sessionBolInfo.begin();
it != sessionBolInfo.end();it++)
{
if (0 == bolName.compare(it->bol_cloud_name))
{
des_ipaddr = it->ip_addr;
des_dir = it->nedir;
des_user = it->userName;
}
}
try
{
HTTPClientSession cs(des_ipaddr.c_str(), 8040);
Json::Value head(Json::objectValue);
Json::Value content(Json::objectValue);
Json::Value rootReq(Json::objectValue);
Bmco::Timestamp now;
LocalDateTime dtNow(now);
std::string stNow = DateTimeFormatter::format(dtNow, DateTimeFormat::SORTABLE_FORMAT);
head["processcode"] = "doprocess";
head["reqseq"] = "012014120101";
head["reqtime"] = stNow;
content["username"] = des_user;
content["path"] = des_dir;
content["cmd"] = "bolstart.sh";
rootReq["head"] = head;
rootReq["content"] = content;
Json::FastWriter jfw;
std::string oss = jfw.write(rootReq);
//HTTPRequest request("POST", "/echoBody");
HTTPRequest request;
request.setContentLength((int) oss.length());
request.setContentType("text/plain");
cs.sendRequest(request) << oss;
HTTPResponse response;
std::string rbody;
cs.receiveResponse(response) >> rbody;
Json::Value rootRsp;
Json::Reader jsonReader;
if (!jsonReader.parse(rbody, rootRsp))
{
bmco_error_f2(theLogger, "%s|%s|Failed to execute jsonReader",std::string("0"),std::string(__FUNCTION__));
return false;
}
if (!rootRsp.isMember("content"))
{
bmco_error_f2(theLogger, "%s|%s|no content",std::string("0"),std::string(__FUNCTION__));
return false;
}
Json::Value value = rootRsp["content"];
std::string cmd_result = value["cmd_result"].asString();
std::string respcode = value["respcode"].asString();
if (respcode != "0")
{
bmco_error_f2(theLogger, "%s|%s|respcode not success",std::string("0"),std::string(__FUNCTION__));
return false;
}
}
catch(Bmco::Exception &e)
{
return false;
}
return true;
}
// 判断当前的cloudagent是否作为Master进行工作
bool CloudDynamicFlexTaskLoop::isMasterCloudAgent()
{
bool isMasterFlag = false;
std::string masterName;
std::vector<std::string> nodes;
std::string nodePath = ZNODE_ZOOKEEPER_SLAVE_DIR;
std::string curPath = g_sessionData.getBolName();
std::string bolMemberStr = nodePath + "/" + curPath;
// 检查当前临时节点是否存在
if (!CloudDatabaseHandler::instance()->nodeExist(bolMemberStr))
{
bmco_information_f1(theLogger, "%s has disappeared!", bolMemberStr);
if (!CloudDatabaseHandler::instance()->createNode(bolMemberStr, ZOO_EPHEMERAL))
{
bmco_error_f1(theLogger, "Faild to createNode bolMemberStr %s", bolMemberStr);
return false;
}
}
// 获取当前存在的节点
if (!CloudDatabaseHandler::instance()->GetChildrenNode(nodePath, nodes))
{
bmco_information_f2(theLogger, "%s|%s|GetChildrenNode failed, return.",std::string("0"),std::string(__FUNCTION__));
return false;
}
std::sort(nodes.begin(), nodes.end());
std::vector<struct bolinfo>::iterator itBol;
std::vector<struct bolinfo> sessionBolInfo;
g_sessionData.getBolInfo(sessionBolInfo);
for (int i = 0;i < nodes.size();i++)
{
for (itBol = sessionBolInfo.begin();
itBol != sessionBolInfo.end(); itBol++)
{
std::string ccBol = itBol->bol_cloud_name;
std::string ccflag = itBol->master_flag;
// 按顺序找到第一个运行态的标志位为1的,即为当前的Master
if (0 == nodes[i].compare(itBol->bol_cloud_name)
&& ("1" == itBol->master_flag))
{
isMasterFlag = true;
masterName = itBol->bol_cloud_name;
break;
}
}
if (isMasterFlag)
{
break;
}
}
if (masterName.empty())
{
bmco_warning_f2(theLogger, "%s|%s|no master work, please check it",std::string("0"),std::string(__FUNCTION__));
}
// else
// {
// bmco_information_f3(theLogger, "%s|%s|master is %s",std::string("0"),std::string(__FUNCTION__), masterName);
// }
if (!isMasterFlag)
{
// bmco_information_f2(theLogger, "%s|%s|Is not global agent, return.",std::string("0"),std::string(__FUNCTION__));
return false;
}
// Master选取规则,以存在的节点名称排序,第一个作为Master
if (0 != Bmco::icompare(curPath, masterName))
{
return false;
}
// 上报Master的Bol信息到zookeeper
if (!refreshMasterInfo(curPath))
{
return false;
}
bmco_information_f2(theLogger, "%s|%s|I am the master",std::string("0"),std::string(__FUNCTION__));
return true;
}
bool CloudDynamicFlexTaskLoop::refreshMasterInfo(std::string MasterBol)
{
std::string MasterInfoPath = "/status/master";
bmco_debug_f1(theLogger, "MasterBol=%s", MasterBol);
if (!CloudDatabaseHandler::instance()->nodeExist(MasterInfoPath))
{
bmco_warning_f1(theLogger, "need to create new node: %s", MasterInfoPath);
if (!CloudDatabaseHandler::instance()->createNode(MasterInfoPath))
{
bmco_error_f1(theLogger, "Faild to createNode: %s", MasterInfoPath);
return false;
}
}
Json::Value root(Json::objectValue);
Json::Value field(Json::objectValue);
Json::Value record(Json::objectValue);
field["bol_name"] = "bolname";
record["bol_name"] = MasterBol;
root["name"] = "c_info_master";
root["desc"] = "Master信息";
root["field"] = field;
root["record"] = record;
Json::FastWriter jfw;
std::string oss = jfw.write(root);
if (!CloudDatabaseHandler::instance()->setNodeData(MasterInfoPath, oss))
{
return false;
}
return true;
}
// 除了本bol是否还有其他的bol处理此topic
bool CloudDynamicFlexTaskLoop::isTheOnlyBolForTheTopic(std::string topicName,
std::string bolName)
{
bmco_debug(theLogger, "isTheOnlyBolForTheTopic()");
std::string tmpBolName;
std::string tmpTopicName;
std::vector<MetaMQRela>::iterator itRela;
for (itRela = m_relaInfoVec.begin();itRela != m_relaInfoVec.end();itRela++)
{
tmpBolName = itRela->BOL_CLOUD_NAME.c_str();
tmpTopicName = itRela->IN_TOPIC_NAME.c_str();
if (0 == topicName.compare(tmpTopicName))
{
if (0 != bolName.compare(tmpBolName))
{
bmco_information_f3(theLogger,
"%s|%s|is Not TheOnlyBolForTheTopic include %s",
std::string("0"),std::string(__FUNCTION__),tmpBolName);
return false;
}
}
}
bmco_information_f3(theLogger,
"%s|%s|%s isTheOnlyBolForTheTopic",
std::string("0"),std::string(__FUNCTION__),bolName);
return true;
}
bool CloudDynamicFlexTaskLoop::chooseSuitAbleBolForLaunch
(std::string domainName, std::string &launchBol)
{
bmco_debug(theLogger, "chooseSuitAbleBolForLaunch()");
bmco_information_f1(theLogger, "domainName = %s", domainName);
std::string bolName;
std::string curDomainName;
bool hasMaintainsBol = false;
std::vector<struct kpiinfo> sessionKpiInfo;
g_sessionData.getKpiInfo(sessionKpiInfo);
std::vector<struct kpiinfo>::iterator itKpi;
for (itKpi = sessionKpiInfo.begin();
itKpi != sessionKpiInfo.end();itKpi++)
{
if ("1001" == itKpi->kpi_id
&& "1" == itKpi->kpi_value)
//&& (0 == domainName.compare(itKpi->domian_type)
//|| (0 == itKpi->domian_type.compare("flex"))))
{
// 没有KPI上报的BOL,继续查找
if (!g_sessionData.getBolDomain(itKpi->bol_cloud_name, curDomainName))
{
continue;
}
// 对应域或者动态伸缩域的可以支持
if ((0 == curDomainName.compare(domainName))
|| curDomainName.compare("flex"))
{
bolName = itKpi->bol_cloud_name;
hasMaintainsBol = true;
break;
}
}
}
// 如果存在维保态的bol,先用维保态的bol
if (hasMaintainsBol)
{
launchBol = bolName;
bmco_information_f3(theLogger, "%s|%s|launchBolNode %s successfully",
std::string("0"), std::string(__FUNCTION__), bolName);
return true;
}
std::vector<std::string> nodes;
std::string nodePath = ZNODE_ZOOKEEPER_SLAVE_DIR;
// 获取当前存在的节点
if (!CloudDatabaseHandler::instance()->GetChildrenNode(nodePath, nodes))
{
bmco_information_f2(theLogger, "%s|%s|GetChildrenNode failed, return.",std::string("0"),std::string(__FUNCTION__));
return false;
}
std::vector<struct bolinfo> sessionBolInfo;
g_sessionData.getBolInfo(sessionBolInfo);
std::vector<struct bolinfo>::iterator itSession;
std::vector<std::string>::iterator itNode;
for (itSession = sessionBolInfo.begin();
itSession != sessionBolInfo.end();itSession++)
{
// 非动态伸缩的bol
if (0 != itSession->auto_flex_flag.compare("1"))
{
continue;
}
// 不是可伸缩域的bol
if (0 != itSession->domainName.compare(domainName)
&& (0 != itSession->domainName.compare("flex")))
{
continue;
}
bmco_information_f3(theLogger, "%s|%s|%s accord with the conditions",
std::string("0"), std::string(__FUNCTION__), itSession->bol_cloud_name);
itNode = find(nodes.begin(), nodes.end(), itSession->bol_cloud_name);
// 目前没有启动的可伸缩bol
if (itNode == nodes.end())
{
bolName = itSession->bol_cloud_name;
bmco_information_f3(theLogger, "%s|%s|try to launchBolNode %s",
std::string("0"), std::string(__FUNCTION__), bolName);
if (launchBolNode(bolName))
{
launchBol = bolName;
bmco_information_f3(theLogger, "%s|%s|launchBolNode %s successfully",
std::string("0"), std::string(__FUNCTION__), bolName);
return true;
}
}
}
bmco_error_f2(theLogger, "%s|%s|launchBolNode failed",std::string("0"),std::string(__FUNCTION__));
return false;
}
// 判断是否符合n+1或者n-1的规则
void CloudDynamicFlexTaskLoop::doRuleCheckDynamicFlex()
{
// Master的工作
//if (!isMasterCloudAgent())
//{
// return ;
//}
if (!recordRelaInfo())
{
return;
}
// 获取距离上次获取指标的时间间隔
Bmco::Timespan intervalTime;
getIntervalTime(intervalTime);
// 收集各个主题的消息堆积数
std::map<std::string, Bmco::Int64> topicMessageNumMap;
std::map<std::string, mqCalcOffsetData> TopicUpDownOffsetVec;
if (!accumulateMessageNum(intervalTime, topicMessageNumMap, TopicUpDownOffsetVec))
{
return ;
}
// 刷新本次获取结束时间
setLastTimeStamp();
// 打印各个主题堆积的消息数
std::map<std::string, Bmco::Int64>::iterator itTopicMap;
for (itTopicMap = topicMessageNumMap.begin();
itTopicMap != topicMessageNumMap.end();itTopicMap++)
{
bmco_information_f4(theLogger, "%s|%s|topic %s messageNum %?d\n",
std::string("0"), std::string(__FUNCTION__),
itTopicMap->first, itTopicMap->second);
}
refreshKPIInfoByMaster(topicMessageNumMap, TopicUpDownOffsetVec);
if (0 == topicMessageNumMap.size())
{
bmco_information_f2(theLogger, "%s|%s|all topic are empty\n",
std::string("0"), std::string(__FUNCTION__));
return;
}
std::string kpi_name;
std::string kpi_value;
std::string topicName;
std::vector<struct flexinfo> sessionFlexInfo;
g_sessionData.getFlexInfo(sessionFlexInfo);
std::map<std::string, Bmco::Int64>::iterator it;
// 根据配置的规则表进行判断是否有需要动态伸缩及宕机的处理
std::vector<struct flexinfo>::iterator itFlex;
for (itFlex = sessionFlexInfo.begin();
itFlex != sessionFlexInfo.end();itFlex++)
{
// 配置规则表无效
if (Bmco::NumberParser::parse(itFlex->status) == 0)
{
bmco_information_f1(theLogger, "flex %s status is invalid",
itFlex->rule_name);
continue;
}
Bmco::StringTokenizer tokensKpiName(itFlex->kpi_name_str, "~", Bmco::StringTokenizer::TOK_TRIM);
Bmco::StringTokenizer tokensKpiValue(itFlex->value_str, "~", Bmco::StringTokenizer::TOK_TRIM);
bmco_information_f3(theLogger, "%s|%s|%s",
itFlex->rule_type, itFlex->kpi_name_str, itFlex->value_str);
bmco_information_f4(theLogger, "topic:%s ruleid:%s interval:%s kpivalue:%s", tokensKpiName[0],
tokensKpiName[1], tokensKpiValue[0], tokensKpiValue[1]);
// n+1逻辑
if (Bmco::NumberParser::parse(itFlex->rule_type) == 1)
{
doExtendOperationOrNot(tokensKpiName[0],
tokensKpiName[1], tokensKpiValue[0], tokensKpiValue[1],
topicMessageNumMap);
}
// n-1逻辑
else if (Bmco::NumberParser::parse(itFlex->rule_type) == 2)
{
doShrinkOperationOrNot(tokensKpiName[0],
tokensKpiName[1], tokensKpiValue[0], tokensKpiValue[1],
topicMessageNumMap);
}
// 宕机处理逻辑
else if (Bmco::NumberParser::parse(itFlex->rule_type) == 3)
{
doBrokenDownBolOperation();
}
}
}
// n+1逻辑处理
// 监视的主题名称topicName 监视的类型代号code
// 监视的时间间隔interval 监视的阀值value
// 主题与堆积消息数的映射topicMessageNumMap
void CloudDynamicFlexTaskLoop::doExtendOperationOrNot
(std::string topicName, std::string code,
std::string interval, std::string value,
std::map<std::string, Bmco::Int64> topicMessageNumMap)
{
bmco_information_f2(theLogger, "%s|%s|CloudDynamicFlexTaskLoop::doExtendOperationOrNot", std::string("0"),std::string(__FUNCTION__));
Bmco::Timestamp now;
Bmco::Int64 monitorInteval = 0;
std::map<std::string, Bmco::Int64>::iterator it;
// 根据消息堆积数进行判断
if ("1002" == code)
{
bmco_information_f2(theLogger, "%s|%s|CloudDynamicFlexTaskLoop::has 1002", std::string("0"),std::string(__FUNCTION__));
// 监视间隔
// monitorInteval = Bmco::NumberParser::parse(interval)*60*60*1000000;
// test
monitorInteval = Bmco::NumberParser::parse(interval)*1000000;
for (it = topicMessageNumMap.begin();it != topicMessageNumMap.end();it++)
{
// 需要监视的topic
if (0 != topicName.compare(it->first))
{
continue;
}
// 该主题的消息堆积消息数小于阀值,刷新记录时间
if (it->second < Bmco::NumberParser::parse(value))
{
m_exLatestMonitorTime.update();
m_needExtendFlex = false;
bmco_information_f3(theLogger, "%s|%s|topic %s m_exLatestMonitorTime.update()",
std::string("0"), std::string(__FUNCTION__), topicName);
}
// 该主题的消息堆积消息数大于阀值,不过在监控时间内,
// 如果有小于的情况,还可以改掉
else
{
// 新的监控周期第一次超过阀值,记录时刻
if (!m_needExtendFlex)
{
m_exLatestMonitorTime.update();
m_needExtendFlex = true;
}
}
break;
}
// 在监控的时间范围内,还不能确定是否要伸缩
if (m_exLatestMonitorTime + monitorInteval > now)
{
bmco_information_f3(theLogger, "%s|%s|topic %s is being monitored!",
std::string("0"), std::string(__FUNCTION__), topicName);
}
// 已经超出范围,可以进行判断是否要n+1
else
{
// 需要n+1的情况
if (m_needExtendFlex)
{
bmco_information_f3(theLogger, "%s|%s|topic %s need extend",
std::string("0"), std::string(__FUNCTION__), topicName);
if (!extendPartitionAndBolFlow(topicName))
{
bmco_information_f3(theLogger,
"%s|%s|extend topic %s failed",
std::string("0"), std::string(__FUNCTION__),
topicName);
}
else
{
bmco_information_f3(theLogger,
"%s|%s|extend topic %s succesfully",
std::string("0"), std::string(__FUNCTION__),topicName);
}
m_needExtendFlex = false;
// test
m_testControl = false;
}
m_exLatestMonitorTime.update();
}
}
}
// n-1逻辑处理
void CloudDynamicFlexTaskLoop::doShrinkOperationOrNot
(std::string topicName, std::string code,
std::string interval, std::string value,
std::map<std::string, Bmco::Int64> topicMessageNumMap)
{
Bmco::Timestamp now;
Bmco::Int64 monitorInteval = 0;
std::map<std::string, Bmco::Int64>::iterator it;
// 根据消息堆积数进行判断
if ("1002" == code)
{
// 监视间隔
monitorInteval = Bmco::NumberParser::parse(interval)*60*60*1000000;
for (it = topicMessageNumMap.begin();it != topicMessageNumMap.end();it++)
{
// 需要监视的topic
if (0 != topicName.compare(it->first))
{
continue;
}
// 该主题的消息堆积消息数大于阀值,刷新记录时间
if (it->second > Bmco::NumberParser::parse(value))
{
m_shLatestMonitorTime.update();
m_needShrinkFlex = false;
bmco_information_f3(theLogger, "%s|%s|topic %s m_shLatestMonitorTime.update()",
std::string("0"), std::string(__FUNCTION__), topicName);
}
// 该主题的消息堆积消息数大于阀值,不过在监控时间内,
// 如果有大于的情况,还可以改掉
else
{
if (!m_needShrinkFlex)
{
m_shLatestMonitorTime.update();
m_needShrinkFlex = true;
}
}
break;
}
// 在监控的时间范围内,还不能确定是否要伸缩
if (m_shLatestMonitorTime + monitorInteval > now)
{
bmco_information_f3(theLogger, "%s|%s|topic %s is being monitored if shrink or not",
std::string("0"), std::string(__FUNCTION__), topicName);
}
// 已经超出范围,可以进行判断是否要n-1
else
{
// 需要n-1的情况
if (m_needShrinkFlex)
{
bmco_information_f3(theLogger, "%s|%s|topic %s need shrink",
std::string("0"), std::string(__FUNCTION__), topicName);
if (!shrinkPartitionAndBolFlow(topicName))
{
bmco_information_f3(theLogger,
"%s|%s|shrink topic %s failed", std::string("0"), std::string(__FUNCTION__), topicName);
}
else
{
bmco_information_f3(theLogger,
"%s|%s|shrink topic %s succesfully", std::string("0"), std::string(__FUNCTION__), topicName);
}
m_needShrinkFlex = false;
}
m_shLatestMonitorTime.update();
}
}
}
bool CloudDynamicFlexTaskLoop::getFirstStartInstanceId(std::string processName,
Bmco::UInt32 &instanceId)
{
instanceId = 0;
MetaProgramDefOp *proPtr = dynamic_cast<MetaProgramDefOp *>(ctlOper->getObjectPtr(MetaProgramDefOp::getObjName()));
std::vector<MetaProgramDef> proVec;
if (!proPtr->queryAll(proVec))
{
bmco_error_f2(theLogger, "%s|%s|get queryAll failed!", std::string("0"),std::string(__FUNCTION__));
return false;
}
bmco_information(theLogger, "firstStep");
std::string exeName;
Bmco::UInt32 proId = 0;
std::vector<MetaProgramDef>::iterator itPro;
for (itPro = proVec.begin();itPro != proVec.end();itPro++)
{
exeName = itPro->ExeName.c_str();
if (0 == exeName.compare(processName))
{
proId = itPro->ID;
break;
}
}
if (0 == proId)
{
bmco_error_f3(theLogger, "%s|%s|no program named %s",
std::string("0"),std::string(__FUNCTION__), processName);
}
bmco_information(theLogger, "secondStep");
MetaBpcbInfoOp *bpcbPtr = dynamic_cast<MetaBpcbInfoOp *>(ctlOper->getObjectPtr(MetaBpcbInfoOp::getObjName()));
std::vector<MetaBpcbInfo> bpcbVec;
if (!bpcbPtr->getBpcbInfoByProgramID(proId, bpcbVec))
{
bmco_error_f2(theLogger, "%s|%s|get getBpcbInfoByProgramID failed!", std::string("0"),std::string(__FUNCTION__));
return false;
}
instanceId = bpcbVec[0].m_iInstanceID;
bmco_information_f3(theLogger, "%s|%s|start with instanceId %?d",
std::string("0"),std::string(__FUNCTION__), instanceId);
return true;
}
bool CloudDynamicFlexTaskLoop::extendPartitionAndBolFlow(std::string topicName)
{
bmco_information(theLogger, "extendPartitionAndBolFlow()");
std::string domainName;
if (!recordTopicInfo(topicName, domainName))
{
return false;
}
/*std::set<std::string> relaSet;
std::vector<MetaMQRela>::iterator itRela;
for (itRela = vecRelaInfo.begin();itRela != vecRelaInfo.end();itRela++)
{
if (0 == topicName.compare(itRela->IN_TOPIC_NAME.c_str()))
{
relaSet.insert(std::string(itRela->PROCESS_NAME.c_str()));
}
}*/
// 启动Bol,通过启动bol的规则,得到bol的名称launchBol
std::string launchBol;
if (!chooseSuitAbleBolForLaunch(domainName, launchBol))
{
return false;
}
// test
// std::string launchBol = "bol_89";
// 建立新启动的bol的进程实例与上下游的topic的对应关系
std::vector<MetaMQRela>::iterator itRela;
relaInfo relainfo;
std::vector<relaInfo> relaVec;
Bmco::UInt32 inPartitionNum = 0;
Bmco::UInt32 outPartitionNum = 0;
Bmco::UInt32 startInstanceId = 0;
std::string loggerStr;
for (itRela = m_relaInfoVec.begin();itRela != m_relaInfoVec.end();itRela++)
{
// 选择其中一条关系记录
if (0 == topicName.compare(itRela->IN_TOPIC_NAME.c_str()))
{
relainfo.flowId = itRela->Flow_ID.c_str();
relainfo.processName = itRela->PROCESS_NAME.c_str();
// 新启动的bol,实例号为0
relainfo.bolName = launchBol;
if (!getFirstStartInstanceId(relainfo.processName, startInstanceId))
{
return false;
}
// relainfo.instanceId = "0";
relainfo.instanceId = startInstanceId;
relainfo.inTopicName = itRela->IN_TOPIC_NAME.c_str();
relainfo.outTopicName = itRela->OUT_TOPIC_NAME.c_str();
// 获取当前需要建立分区的topic的partiton个数,也是需要
// 增加的分区号的数字
if (!getPartitionCount(relainfo.inTopicName, inPartitionNum))
{
return false;
}
if (!getPartitionCount(relainfo.outTopicName, outPartitionNum))
{
return false;
}
// 消费关系新增的分区 与 生产关系新增分区的关系
relainfo.inPartitionName = Bmco::format("%?d", inPartitionNum);
relainfo.outPartitionName = Bmco::format("%?d", outPartitionNum);
relainfo.inMqName = itRela->IN_MQ_NAME.c_str();
relainfo.outMqName = itRela->OUT_MQ_NAME.c_str();
relainfo.subsys = itRela->subsys_type.c_str();
relainfo.domain = itRela->domain_type.c_str();
relaVec.push_back(relainfo);
loggerStr = Bmco::format("%s|%s|%s|%s|%s|%s|",
relainfo.flowId, relainfo.processName,
relainfo.bolName, relainfo.instanceId,
relainfo.inTopicName, relainfo.outTopicName);
loggerStr += Bmco::format("%s|%s|%s|%s|%s|%s",
relainfo.inPartitionName, relainfo.outPartitionName,
relainfo.inMqName, relainfo.outMqName,
relainfo.subsys, relainfo.domain);
bmco_information_f3(theLogger, "%s|%s|extend relainfo %s",
std::string("0"), std::string(__FUNCTION__), loggerStr);
break;
}
}
// 没有这样的关系,是异常的
if (0 == relaVec.size())
{
bmco_information_f2(theLogger, "%s|%s|no such relation, don't need extend",std::string("0"),std::string(__FUNCTION__));
return true;
}
std::vector<relaInfo>::iterator it;
for (it = relaVec.begin();it != relaVec.end();it++)
{
// 启动bol对应的实例,只启动一个
// test
if (!launchInstanceReq(launchBol, it->processName))
{
bmco_error_f2(theLogger, "%s|%s|launchInstanceReq failed!",std::string("0"),std::string(__FUNCTION__));
return false;
}
// 修改上游topic定义表,创建一个partition
if (!setPartitionCount(it->inTopicName, Bmco::NumberParser::parse(it->inPartitionName)+1))
{
bmco_error_f3(theLogger, "%s|%s|setPartitionCount in %s failed!",
std::string("0"),std::string(__FUNCTION__), it->inTopicName);
return false;
}
// 修改下游topic定义表,创建一个partition
if (!setPartitionCount(it->outTopicName, Bmco::NumberParser::parse(it->outPartitionName)+1))
{
bmco_error_f3(theLogger, "%s|%s|setPartitionCount out %s failed!",
std::string("0"),std::string(__FUNCTION__), it->outTopicName);
return false;
}
// 保存到关系记录中,最后统一写入zookeeper
// 递归创建本主题前面所有的关系
if (!buildRelationBeforeNewBol(it->inTopicName))
{
bmco_error_f3(theLogger, "%s|%s|buildRelationBeforeNewBol %s failed!",
std::string("0"),std::string(__FUNCTION__), it->inTopicName);
return false;
}
// 创建本主题的关系
//m_relaBuildVec.insert(m_relaBuildVec.end(), relaVec.begin(), relaVec.end());
m_relaBuildVec.push_back(*it);
// 递归创建本主题后面所有的关系
if (!buildRelationAfterNewBol(it->outTopicName))
{
bmco_error_f3(theLogger, "%s|%s|buildRelationAfterNewBol %s failed!",
std::string("0"),std::string(__FUNCTION__), it->outTopicName);
return false;
}
}
// 将所有变动的主题表更行到zookeeper
if (!modifyMQTopicTable())
{
return false;
}
// 将所有变动的关系表更行到zookeeper
if (!modifyMQRelaTable())
{
return false;
}
return true;
}
// 启动对应bol的进程实例
bool CloudDynamicFlexTaskLoop::launchInstanceReq(std::string bolName,
std::string processName)
{
std::string cloudStatusStr;
std::string bpcbInfoPath = "/conf/cluster/" + bolName + "/regular";
if (!CloudDatabaseHandler::instance()->nodeExist(bpcbInfoPath))
{
bmco_error_f3(theLogger, "%s|%s|%s not exist!",
std::string("0"),std::string(__FUNCTION__),bpcbInfoPath);
return false;
}
try
{
if (0 != CloudDatabaseHandler::instance()->getNodeData(bpcbInfoPath, cloudStatusStr))
{
bmco_error_f3(theLogger, "%s|%s|data error at %s",
std::string("0"),std::string(__FUNCTION__), bpcbInfoPath);
return false;
}
if (cloudStatusStr.empty())
{
cloudStatusStr = "{}";
}
Json::Value root;
Json::Reader jsonReader;
if (!jsonReader.parse(cloudStatusStr, root))
{
return false;
}
MetaProgramDefOp *proPtr = dynamic_cast<MetaProgramDefOp *>(ctlOper->getObjectPtr(MetaProgramDefOp::getObjName()));
std::vector<MetaProgramDef> vecProgramDef;
if (!proPtr->queryAll(vecProgramDef))
{
bmco_error_f2(theLogger, "%s|%s|get vecProgramDef failed!",std::string("0"),std::string(__FUNCTION__));
return false;
}
std::vector<MetaProgramDef>::iterator itPro;
std::string tmpExeName;
Bmco::UInt32 tmpProId = 0;
for (itPro = vecProgramDef.begin(); itPro != vecProgramDef.end();itPro++)
{
tmpExeName = itPro->ExeName.c_str();
if (0 == tmpExeName.compare(processName))
{
tmpProId = itPro->ID;
}
}
// 没有找到相应的程序名称
if (0 == tmpProId)
{
bmco_error_f2(theLogger, "%s|%s|no such processName!",std::string("0"),std::string(__FUNCTION__));
return false;
}
if (!root.isMember("record"))
{
bmco_error_f2(theLogger, "%s|%s|no record",std::string("0"),std::string(__FUNCTION__));
return -1;
}
Json::Value valueNewArray;
Json::Value valueArray = root["record"];
for (int index = 0; index < valueArray.size(); ++index)
{
Json::Value value = valueArray[index];
if (tmpProId == Bmco::NumberParser::parseUnsigned(value["program_id"].asString()))
{
value["is_valid"] = "1";
}
valueNewArray[index] = value;
/*pColumnNode = it->second; //first为空
if (tmpProId != Bmco::NumberParser::parseUnsigned(pColumnNode.get<std::string>("program_id")))
{
pRecordNewNode.push_back(std::make_pair("", pColumnNode));
}
else
{
pColumnNode.put<std::string>("is_valid", "true");
pRecordNewNode.push_back(std::make_pair("", pColumnNode));
}*/
}
root["record"] = valueNewArray;
Json::FastWriter jfw;
std::string oss = jfw.write(root);
if (!CloudDatabaseHandler::instance()->setNodeData(bpcbInfoPath, oss))
{
bmco_error(theLogger, "Faild to write MetaBpcbInfo");
return false;
}
else
{
bmco_information(theLogger, "***Set jour successfully***");
}
}
catch(Bmco::Exception &e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),e.displayText());
return false;
}
catch(...)
{
bmco_error_f2(theLogger,"%s|%s|unknown exception occured when recordHostBaseInfo!",
std::string("0"),std::string(__FUNCTION__));
return false;
}
return true;
}
// 创建相应topicName的partitionNum
/*bool CloudDynamicFlexTaskLoop::modifyMQTopicTable(std::string topicName,
Bmco::Int32 partitionNum)
{
Bmco::Util::AbstractConfiguration& config = Bmco::Util::Application::instance().config();
// 增加一个分区
std::string zookeeperList = CloudKafkaMessageHandler::instance(m_brokerlist, m_zookeeperlist)->getZookeeperList();
std::string kafkaPath = config.getString("kafka.operation.path");
// 建立一个partiton
std::string buildPartitonScript = kafkaPath + "/kafka-topics.sh --alter --topic ["
+ topicName + "] --zookeeper ["
+ zookeeperList + "] --partitions ["
+ inNumStr + "]";
char cBuf[1024];
memset(cBuf, 0, sizeof(cBuf));
Bmco::Int32 ret = -999;
ret = RunScript2(buildPartitonScript.c_str(), cBuf, 1023);
bmco_information_f3(theLogger, "%s|%s|build partition[%s] result ret=%d, cBuf=[%s]", buildPartitonScript, ret, std::string(cBuf));
if (0 != ret)
{
return false;
}
// 修改相应主题定义表,增加一个分区
std::string inNumStr = Bmco::format("%?d", partitionNum+1);
std::string cloudConfigStr;
std::string nodePath = ZNODE_ZOOKEEPER_MQ_TOPIC;
try
{
CloudDatabaseHandler::instance()->getNodeData(nodePath, cloudConfigStr);
std::istringstream iss(cloudConfigStr);
Bmco::AutoPtr<IniFileConfigurationNew> pConf = new Bmco::Util::IniFileConfigurationNew(iss);
int topicNum = pConf->getInt(TABLE_PREFIX_LIST[1] + ".recordnum");
Bmco::Util::AbstractConfiguration *view = pConf->createView("Table.Table.1.record");
for (int i = 0; i < topicNum; i++)
{
std::string record = view->getString(Bmco::NumberFormatter::format(i + 1));
std::vector<std::string> fields;
boost::algorithm::split(fields, record, boost::algorithm::is_any_of("|"));
if (0 == topicName.compare(fields[1]))
{
fields[4] = inNumStr;
std::string newRecord = boost::algorithm::join(fields, "|");
bmco_information_f3(theLogger, "%s|%s|topic new record: %s",
std::string("0"), std::string(__FUNCTION__), newRecord);
view->setString(Bmco::NumberFormatter::format(i + 1), newRecord);
}
}
std::ostringstream oss;
pConf->save(oss);
if (!CloudDatabaseHandler::instance()->setNodeData(nodePath, oss.str()))
{
bmco_error_f2(theLogger, "%s|%s|Faild to write topic Info",std::string("0"),std::string(__FUNCTION__));
return false;
}
}
catch(Bmco::Exception &e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),e.displayText());
return false;
}
catch(...)
{
bmco_error_f2(theLogger,"%s|%s|unknown exception occured when recordHostBaseInfo!",
std::string("0"),std::string(__FUNCTION__));
return false;
}
return true;
}*/
bool CloudDynamicFlexTaskLoop::modifyMQTopicTable()
{
// 修改相应主题定义表,增加一个分区
std::string cloudConfigStr;
std::string nodePath = ZNODE_ZOOKEEPER_MQ_TOPIC;
std::string topicName;
if (!CloudDatabaseHandler::instance()->nodeExist(nodePath))
{
bmco_error(theLogger, "need to createNode ZNODE_ZOOKEEPER_MQ_TOPIC");
return false;
}
try
{
if (0 != CloudDatabaseHandler::instance()->getNodeData(nodePath, cloudConfigStr))
{
bmco_error_f3(theLogger, "%s|%s|data error at %s",
std::string("0"),std::string(__FUNCTION__), nodePath);
return false;
}
if (cloudConfigStr.empty())
{
cloudConfigStr = "{}";
}
Json::Value root;
Json::Reader jsonReader;
if (!jsonReader.parse(cloudConfigStr, root))
{
return false;
}
std::map<std::string, Bmco::UInt32>::iterator itTopic;
Json::Value valueNewArray;
Json::Value valueArray = root["record"];
for (int index = 0; index < valueArray.size(); ++index)
{
Json::Value value = valueArray[index];
topicName = value["topic_name"].asString();
itTopic = m_topicInfoMap.find(topicName);
if (itTopic != m_topicInfoMap.end())
{
value["partition_number"] = Bmco::format("%?d", itTopic->second);
}
valueNewArray[index] = value;
/*if (itTopic == m_topicInfoMap.end())
{
pRecordNewNode.push_back(std::make_pair("", pColumnNode));
}
else
{
pColumnNode.put<Bmco::UInt64>("partition_number", itTopic->second);
pRecordNewNode.push_back(std::make_pair("", pColumnNode));
}*/
}
root["record"] = valueNewArray;
Json::FastWriter jfw;
std::string oss = jfw.write(root);
if (!CloudDatabaseHandler::instance()->setNodeData(nodePath, oss))
{
bmco_error(theLogger, "Faild to write MetaTopicInfo");
return false;
}
else
{
bmco_information(theLogger, "***Set topic successfully***");
}
}
catch(Bmco::Exception &e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),e.displayText());
return false;
}
catch(...)
{
bmco_error_f2(theLogger,"%s|%s|unknown exception occured when recordHostBaseInfo!",
std::string("0"),std::string(__FUNCTION__));
return false;
}
m_topicInfoMap.clear();
return true;
}
bool CloudDynamicFlexTaskLoop::modifyMQRelaTable()
{
std::string cloudStatusStr;
std::string nodePath = ZNODE_ZOOKEEPER_MQ_RELAION;
if (!CloudDatabaseHandler::instance()->nodeExist(nodePath))
{
bmco_error_f1(theLogger, "need to create new node: %s", nodePath);
return false;
}
try
{
if (0 != CloudDatabaseHandler::instance()->getNodeData(nodePath, cloudStatusStr))
{
bmco_error_f3(theLogger, "%s|%s|data error at %s",
std::string("0"),std::string(__FUNCTION__), nodePath);
return false;
}
if (cloudStatusStr.empty())
{
cloudStatusStr = "{}";
}
Json::Value root;
Json::Reader jsonReader;
if (!jsonReader.parse(cloudStatusStr, root))
{
return false;
}
Json::Value valueArray = root["record"];
int msgNum = valueArray.size();
Bmco::Timestamp now;
LocalDateTime dtNow(now);
std::string stNow = DateTimeFormatter::format(dtNow, DateTimeFormat::SORTABLE_FORMAT);
std::vector<relaInfo>::iterator it;
for (it = m_relaBuildVec.begin();it != m_relaBuildVec.end();it++)
{
Json::Value array(Json::objectValue);
array["seq_id"] = Bmco::format("%?d", ++msgNum);
array["flow_id"] = it->flowId;
array["program_name"] = it->processName;
array["instance_id"] = it->instanceId;
array["bol_name"] = it->bolName;
array["in_partition_name"] = it->inPartitionName;
array["in_topic_name"] = it->inTopicName;
array["in_mq_name"] = it->inMqName;
array["out_partition_name"] = it->outPartitionName;
array["out_topic_name"] = it->outTopicName;
array["out_mq_name"] = it->outMqName;
array["status"] = "1";
array["create_date"] = stNow;
array["modi_date"] = stNow;
array["subsys_type"] = it->subsys;
array["domain_type"] = it->domain;
array["operator_id"] = "";
array["reserve1"] = "";
array["reserve2"] = "";
valueArray[msgNum] = array;
}
root["record"] = valueArray;
Json::FastWriter jfw;
std::string oss = jfw.write(root);
if (!CloudDatabaseHandler::instance()->setNodeData(nodePath, oss))
{
bmco_error(theLogger, "Faild to write MetaRelaInfo");
return false;
}
else
{
bmco_information(theLogger, "***Set rela successfully***");
}
}
catch(Bmco::Exception &e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),e.displayText());
return false;
}
catch(...)
{
bmco_error_f2(theLogger,"%s|%s|unknown exception occured when recordHostBaseInfo!",
std::string("0"),std::string(__FUNCTION__));
return false;
}
m_relaBuildVec.clear();
return true;
}
bool CloudDynamicFlexTaskLoop::setPartitionCount(std::string topicName,
const Bmco::UInt32 &partitionNum)
{
std::map<std::string, Bmco::UInt32>::iterator it;
it = m_topicInfoMap.find(topicName);
if (it == m_topicInfoMap.end())
{
bmco_information_f3(theLogger,"%s|%s|no such topicName: %s ",
std::string("0"), std::string(__FUNCTION__), topicName);
return false;
}
else
{
m_topicInfoMap[topicName] = partitionNum;
}
return true;
}
bool CloudDynamicFlexTaskLoop::getPartitionCount(std::string topicName,
Bmco::UInt32 &partitionNum)
{
std::map<std::string, Bmco::UInt32>::iterator it;
it = m_topicInfoMap.find(topicName);
if (it == m_topicInfoMap.end())
{
bmco_information_f3(theLogger,"%s|%s|no such topicName: %s ",
std::string("0"), std::string(__FUNCTION__), topicName);
return false;
}
else
{
partitionNum = it->second;
}
return true;
}
/*bool CloudDynamicFlexTaskLoop::getPartitionCount(std::string topicName,
Bmco::UInt32 &partitionNum)
{
partitionNum = 0;
std::string cloudConfigStr;
std::string zNodePath;
zNodePath.assign(ZNODE_ZOOKEEPER_MQ_TOPIC);
if(!CloudDatabaseHandler::instance()->nodeExist(zNodePath))
{
bmco_information_f3(theLogger,"%s|%s|node:%s does not exist",std::string("0"),std::string(__FUNCTION__),
zNodePath);
return false;
}
try
{
CloudDatabaseHandler::instance()->getNodeData(zNodePath, cloudConfigStr);
std::istringstream issNew(cloudConfigStr);
Bmco::AutoPtr<Bmco::Util::AbstractConfiguration> pConf = new Bmco::Util::IniFileConfiguration(issNew);
int recordNum = pConf->getInt(TABLE_PREFIX_LIST[1] + ".recordnum");
for (int j = 1; j <= recordNum; j++)
{
std::string record = pConf->getString(Bmco::format("%s.record.%?d",TABLE_PREFIX_LIST[1],j));
Bmco::StringTokenizer tokens(record, "|", Bmco::StringTokenizer::TOK_TRIM);
if (tokens[1] == topicName)
{
partitionNum = Bmco::NumberParser::parseUnsigned(tokens[4]);
break;
}
}
}
catch(Bmco::Exception &e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),e.displayText());
return false;
}
catch(...)
{
bmco_error_f2(theLogger,"%s|%s|unknown exception occured when recordHostBaseInfo!",
std::string("0"),std::string(__FUNCTION__));
return false;
}
bmco_information_f4(theLogger,"%s|%s|topicName: %s partitionNum: %?d",
std::string("0"), std::string(__FUNCTION__), topicName, partitionNum);
return true;
}*/
bool CloudDynamicFlexTaskLoop::buildRelationAfterNewBol(std::string topicName)
{
bmco_information_f3(theLogger, "%s|%s|buildRelationAfterNewBol outtopicName:%s",
std::string("0"),std::string(__FUNCTION__),topicName);
// 获取当前需要建立分区的topic的partiton个数
Bmco::UInt32 CurrPartNum = 0;
//test
/*CurrPartNum = CloudKafkaMessageHandler::instance(m_brokerlist)->getPartitionCount(topicName);
if (0 == CurrPartNum)
{
return false;
}*/
// CurrPartNum = 4;
if (!getPartitionCount(topicName, CurrPartNum))
{
return false;
}
Bmco::UInt32 outPartNum = 0;
std::vector<MetaMQRela>::iterator itRela;
relaInfo relainfo;
std::vector<relaInfo> relaVec;
std::string tmpInTopicName;
Bmco::UInt16 tmpInstanceId = 0;
std::string tmpBolName;
std::string loggerStr;
bolInstance ansBolInstance;
if (!chooseInstanceBuildRela(topicName, ansBolInstance, DM_After))
{
return false;
}
if (ansBolInstance.bolName.empty())
{
bmco_information_f2(theLogger, "%s|%s|return from bottom!",std::string("0"),std::string(__FUNCTION__));
return true;
}
for (itRela = m_relaInfoVec.begin();itRela != m_relaInfoVec.end();itRela++)
{
tmpInTopicName = itRela->IN_TOPIC_NAME.c_str();
tmpBolName = itRela->BOL_CLOUD_NAME.c_str();
tmpInstanceId = itRela->Instance_id;
if (0 == topicName.compare(tmpInTopicName)
&& (ansBolInstance.instanceId == tmpInstanceId)
&& (0 == ansBolInstance.bolName.compare(tmpBolName)))
{
relainfo.flowId = itRela->Flow_ID.c_str();
relainfo.processName = itRela->PROCESS_NAME.c_str();
relainfo.bolName = itRela->BOL_CLOUD_NAME.c_str();
relainfo.instanceId = Bmco::format("%?d", ansBolInstance.instanceId);
relainfo.inTopicName = itRela->IN_TOPIC_NAME.c_str();
relainfo.outTopicName = itRela->OUT_TOPIC_NAME.c_str();
// 获取当前需要建立分区的topic的partiton个数
// test
/*outPartNum = CloudKafkaMessageHandler::instance(m_brokerlist)->getPartitionCount(relainfo.outTopicName);
if (0 == outPartNum)
{
return false;
}*/
// outPartNum = 3;
if (!getPartitionCount(relainfo.outTopicName, outPartNum))
{
return false;
}
// 消费关系新增的分区 与 生产关系新增分区的关系
relainfo.inPartitionName = Bmco::format("%?d", CurrPartNum-1);
relainfo.outPartitionName = Bmco::format("%?d", outPartNum);
relainfo.inMqName = itRela->IN_MQ_NAME.c_str();
relainfo.outMqName = itRela->OUT_MQ_NAME.c_str();
relainfo.subsys = itRela->subsys_type.c_str();
relainfo.domain = itRela->domain_type.c_str();
relaVec.push_back(relainfo);
loggerStr = Bmco::format("%s|%s|%s|%s|%s|%s|",
relainfo.flowId, relainfo.processName,
relainfo.bolName, relainfo.instanceId,
relainfo.inTopicName, relainfo.outTopicName);
loggerStr += Bmco::format("%s|%s|%s|%s|%s|%s",
relainfo.inPartitionName, relainfo.outPartitionName,
relainfo.inMqName, relainfo.outMqName,
relainfo.subsys, relainfo.domain);
bmco_information_f3(theLogger, "%s|%s|extend relainfo %s",
std::string("0"), std::string(__FUNCTION__), loggerStr);
}
}
if (0 == relaVec.size())
{
return true;
}
std::vector<relaInfo>::iterator it;
for (it = relaVec.begin();it != relaVec.end();it++)
{
if (!setPartitionCount(it->outTopicName, Bmco::NumberParser::parse(it->outPartitionName)+1))
{
bmco_error_f3(theLogger, "%s|%s|setPartitionCount in %s failed!",
std::string("0"),std::string(__FUNCTION__), it->outTopicName);
return false;
}
// 保存到关系记录中,最后统一写入zookeeper
//m_relaBuildVec.insert(m_relaBuildVec.end(), relaVec.begin(), relaVec.end());
m_relaBuildVec.push_back(*it);
if (!buildRelationAfterNewBol(it->outTopicName))
{
bmco_error_f3(theLogger, "%s|%s|buildRelationAfterNewBol %s failed!",
std::string("0"),std::string(__FUNCTION__), it->outTopicName);
return false;
}
}
return true;
}
bool CloudDynamicFlexTaskLoop::buildRelationBeforeNewBol(std::string topicName)
{
bmco_information_f3(theLogger, "%s|%s|buildRelationBeforeNewBol intopicName:%s",
std::string("0"),std::string(__FUNCTION__),topicName);
// 获取当前需要建立分区的topic的partiton个数
Bmco::UInt32 CurrPartNum = 0;
// test
//CurrPartNum = CloudKafkaMessageHandler::instance(m_brokerlist)->getPartitionCount(topicName);
// CurrPartNum = 4;
if (!getPartitionCount(topicName, CurrPartNum))
{
return false;
}
if (0 == CurrPartNum)
{
bmco_error_f2(theLogger, "%s|%s|buildRelationBeforeNewBol CurrPartNum is zero!",std::string("0"),std::string(__FUNCTION__));
return false;
}
Bmco::UInt32 inPartNum = 0;
std::vector<MetaMQRela>::iterator itRela;
relaInfo relainfo;
std::vector<relaInfo> relaVec;
std::string tmpOutTopicName;
Bmco::UInt16 tmpInstanceId = 0;
std::string tmpBolName;
std::string loggerStr;
bolInstance ansBolInstance;
if (!chooseInstanceBuildRela(topicName, ansBolInstance, DM_Before))
{
return false;
}
for (itRela = m_relaInfoVec.begin();itRela != m_relaInfoVec.end();itRela++)
{
tmpOutTopicName = itRela->OUT_TOPIC_NAME.c_str();
tmpBolName = itRela->BOL_CLOUD_NAME.c_str();
tmpInstanceId = itRela->Instance_id;
if (0 == topicName.compare(tmpOutTopicName)
&& (ansBolInstance.instanceId == tmpInstanceId)
&& (0 == ansBolInstance.bolName.compare(tmpBolName)))
{
relainfo.flowId = itRela->Flow_ID.c_str();
relainfo.processName = itRela->PROCESS_NAME.c_str();
relainfo.bolName = itRela->BOL_CLOUD_NAME.c_str();
relainfo.instanceId = Bmco::format("%?d", ansBolInstance.instanceId);
relainfo.inTopicName = itRela->IN_TOPIC_NAME.c_str();
relainfo.outTopicName = itRela->OUT_TOPIC_NAME.c_str();
// 获取当前需要建立分区的topic的partiton个数
// test
/*inPartNum = CloudKafkaMessageHandler::instance(m_brokerlist)->getPartitionCount(relainfo.inTopicName);
if (0 == inPartNum)
{
return false;
}*/
//inPartNum = 3;
if (!relainfo.inTopicName.empty())
{
if (!getPartitionCount(relainfo.inTopicName, inPartNum))
{
return false;
}
// 需要新增的partition号码为inPartNum
relainfo.inPartitionName = Bmco::format("%?d", inPartNum);
}
else
{
relainfo.inPartitionName = "";
}
// 消费关系新增的分区 与 生产关系新增分区的关系
// 已经新增了partition,号码为CurrPartNum-1
relainfo.outPartitionName = Bmco::format("%?d", CurrPartNum-1);
relainfo.inMqName = itRela->IN_MQ_NAME.c_str();
relainfo.outMqName = itRela->OUT_MQ_NAME.c_str();
relainfo.subsys = itRela->subsys_type.c_str();
relainfo.domain = itRela->domain_type.c_str();
relaVec.push_back(relainfo);
loggerStr = Bmco::format("%s|%s|%s|%s|%s|%s|",
relainfo.flowId, relainfo.processName,
relainfo.bolName, relainfo.instanceId,
relainfo.inTopicName, relainfo.outTopicName);
loggerStr += Bmco::format("%s|%s|%s|%s|%s|%s",
relainfo.inPartitionName, relainfo.outPartitionName,
relainfo.inMqName, relainfo.outMqName,
relainfo.subsys, relainfo.domain);
bmco_information_f3(theLogger, "%s|%s|extend relainfo %s",
std::string("0"), std::string(__FUNCTION__), loggerStr);
// break;
}
}
// 递归到尽头了,出口
if (0 == relaVec.size())
{
bmco_information_f2(theLogger, "%s|%s|return from bottom!",std::string("0"),std::string(__FUNCTION__));
return true;
}
std::vector<relaInfo>::iterator it;
for (it = relaVec.begin();it != relaVec.end();it++)
{
// 递归到尽头了,出口
if (it->inTopicName.empty())
{
m_relaBuildVec.insert(m_relaBuildVec.end(), relaVec.begin(), relaVec.end());
bmco_information_f2(theLogger, "%s|%s|return from top!",std::string("0"),std::string(__FUNCTION__));
return true;
}
if (!setPartitionCount(it->inTopicName, Bmco::NumberParser::parse(it->inPartitionName)+1))
{
bmco_error_f3(theLogger, "%s|%s|setPartitionCount in %s failed!",
std::string("0"),std::string(__FUNCTION__), it->inTopicName);
return false;
}
// 保存到关系记录中,最后统一写入zookeeper
//m_relaBuildVec.insert(m_relaBuildVec.end(), relaVec.begin(), relaVec.end());
m_relaBuildVec.push_back(*it);
if (!buildRelationBeforeNewBol(it->inTopicName))
{
bmco_error_f3(theLogger, "%s|%s|buildRelationBeforeNewBol %s failed!",
std::string("0"),std::string(__FUNCTION__), it->inTopicName);
return false;
}
}
return true;
}
// 查询挂载分区最少的bol的实例号,前提是同一进程的实例
bool CloudDynamicFlexTaskLoop::chooseInstanceBuildRela(std::string topicName,
bolInstance &ansBolInstance, enum directionMark mark)
{
std::vector<MetaMQRela>::iterator itRela;
relaInfo relainfo;
std::vector<relaInfo> relaVec;
std::string tmpTopicName;
bolInstance tmpBolInstance;
std::map<bolInstance, Bmco::UInt32> instanceRelaNumMap;
std::map<bolInstance, Bmco::UInt32>::iterator itMap;
instanceRelaNumMap.clear();
ansBolInstance.bolName = "";
for (itRela = m_relaInfoVec.begin();itRela != m_relaInfoVec.end();itRela++)
{
if (DM_Before == mark)
{
tmpTopicName = itRela->OUT_TOPIC_NAME.c_str();
}
else if (DM_After == mark)
{
tmpTopicName = itRela->IN_TOPIC_NAME.c_str();
}
else
{
bmco_error_f2(theLogger, "%s|%s|no such mark",
std::string("0"),std::string(__FUNCTION__));
return false;
}
if (0 == topicName.compare(tmpTopicName))
{
tmpBolInstance.instanceId = itRela->Instance_id;
tmpBolInstance.bolName = itRela->BOL_CLOUD_NAME.c_str();
itMap = instanceRelaNumMap.find(tmpBolInstance);
if (itMap != instanceRelaNumMap.end())
{
instanceRelaNumMap[tmpBolInstance]++;
}
else
{
instanceRelaNumMap.insert
(std::pair<bolInstance, Bmco::UInt32>(tmpBolInstance, 1));
}
}
}
if (0 == instanceRelaNumMap.size())
{
if (DM_After == mark)
{
bmco_information_f2(theLogger, "%s|%s|reach the bottom topic",
std::string("0"),std::string(__FUNCTION__));
return true;
}
else
{
bmco_error_f2(theLogger, "%s|%s|instanceRelaNumMap is empty",
std::string("0"),std::string(__FUNCTION__));
return false;
}
}
itMap = instanceRelaNumMap.begin();
Bmco::UInt16 ansInstance = itMap->second;
ansBolInstance.bolName = itMap->first.bolName;
ansBolInstance.instanceId = itMap->first.instanceId;
itMap++;
for (;itMap!= instanceRelaNumMap.end();itMap++)
{
if (ansInstance > itMap->second)
{
ansInstance = itMap->second;
ansBolInstance.bolName = itMap->first.bolName;
ansBolInstance.instanceId = itMap->first.instanceId;
}
}
bmco_information_f4(theLogger, "%s|%s|instanceId = %?d, bolName = %s",
std::string("0"),std::string(__FUNCTION__), ansBolInstance.instanceId,
ansBolInstance.bolName);
return true;
}
bool CloudDynamicFlexTaskLoop::shrinkPartitionAndBolFlow(std::string topicName)
{
bmco_information(theLogger, "shrinkPartitionAndBolFlow()");
// 获取可以停掉的bol
std::string ShrinkBol;
if (!chooseSuitAbleBolForStop(topicName, ShrinkBol))
{
bmco_error_f2(theLogger, "%s|%s|no SuitAbleBolForStop",std::string("0"),std::string(__FUNCTION__));
return false;
}
// 如果只有ShrinkBol处理本topic,则不可以n-1
if (isTheOnlyBolForTheTopic(topicName, ShrinkBol))
{
bmco_error_f4(theLogger, "%s|%s|Only %s doWithTheTopic %s can't do shrink",
std::string("0"),std::string(__FUNCTION__),ShrinkBol,topicName);
return false;
}
if (!setRemoteBolStatus(ShrinkBol, BOL_MAINTAIN))
{
bmco_error_f2(theLogger, "%s|%s|setBolMaintains failed",std::string("0"),std::string(__FUNCTION__));
return false;
}
if (!hasStoppedALLHLAProcessTimeOut(ShrinkBol))
{
return false;
}
// 将该bol消息关系置为失效
std::vector<MetaMQRela>::iterator itRela;
std::vector<Bmco::UInt32> seqNoVec;
for (itRela = m_relaInfoVec.begin();itRela != m_relaInfoVec.end();itRela++)
{
if (0 == ShrinkBol.compare(itRela->BOL_CLOUD_NAME.c_str()))
{
seqNoVec.push_back(itRela->SEQ_ID);
}
}
if (!setBolMessageRelaInvalid(seqNoVec))
{
bmco_error_f2(theLogger, "%s|%s|setBolMessageRelaInvalid failed",std::string("0"),std::string(__FUNCTION__));
return false;
}
if (!setRelaWithConsumeBolInstance(topicName, ShrinkBol))
{
bmco_error_f2(theLogger, "%s|%s|setRelaWithConsumeBolInstance failed",std::string("0"),std::string(__FUNCTION__));
return false;
}
if (!modifyMQRelaTable())
{
bmco_error_f2(theLogger, "%s|%s|modifyMQRelaTable failed",std::string("0"),std::string(__FUNCTION__));
return false;
}
return true;
}
bool CloudDynamicFlexTaskLoop::chooseSuitAbleBolForStop(std::string topicName,
std::string &ShrinkBol)
{
// 获取所有消费本主题的bol名称
std::set<std::string> bolNameSet;
std::vector<MetaMQRela>::iterator itRela;
for (itRela = m_relaInfoVec.begin();itRela != m_relaInfoVec.end();itRela++)
{
if (0 == topicName.compare(itRela->IN_TOPIC_NAME.c_str()))
{
bolNameSet.insert(std::string(itRela->BOL_CLOUD_NAME.c_str()));
}
}
std::vector<struct bolinfo> sessionBolInfo;
g_sessionData.getBolInfo(sessionBolInfo);
std::set<std::string>::iterator itSet;
std::vector<struct bolinfo>::iterator itSession;
for (itSet = bolNameSet.begin();itSet != bolNameSet.end();itSet++)
{
std::vector<std::string>::iterator itNode;
for (itSession = sessionBolInfo.begin();
itSession != sessionBolInfo.end();itSession++)
{
// 找出一个可以用于动态伸缩的bol
if (0 == itSession->bol_cloud_name.compare(*itSet)
&& ("1" == itSession->auto_flex_flag))
{
ShrinkBol = itSession->bol_cloud_name;
bmco_information_f3(theLogger, "%s|%s|shrink bol : %s",
std::string("0"), std::string(__FUNCTION__), ShrinkBol);
return true;
}
}
}
ShrinkBol = "";
bmco_information_f2(theLogger, "%s|%s|no bol can be shrinked",
std::string("0"), std::string(__FUNCTION__));
return false;
}
// 将指定的bol改变状态
bool CloudDynamicFlexTaskLoop::setRemoteBolStatus(std::string bolName,
BolStatus status)
{
std::string des_ipaddr;
//std::string des_dir;
//std::string des_user;
std::vector<struct bolinfo> sessionBolInfo;
g_sessionData.getBolInfo(sessionBolInfo);
std::vector<struct bolinfo>::iterator it;
for (it = sessionBolInfo.begin();
it != sessionBolInfo.end();it++)
{
if (0 == bolName.compare(it->bol_cloud_name))
{
des_ipaddr = it->ip_addr;
//des_dir = it->nedir;
//des_user = it->userName;
}
}
std::string outStr;
Timestamp now;
LocalDateTime dt;
std::string nowStr;
dt = now;
nowStr = DateTimeFormatter::format(dt, DateTimeFormat::SORTABLE_FORMAT);
MetaBolInfo::Ptr ptr = new MetaBolInfo(BOL_NORMAL, "", "");
MetaBolInfoOp *p = dynamic_cast<MetaBolInfoOp *>
(ctlOper->getObjectPtr(MetaBolInfoOp::getObjName()));
BolStatus tmpStatus = BOL_NORMAL;
Bmco::UInt32 tmpCrc32CheckSum = 0;
if (!p->Query(tmpStatus, tmpCrc32CheckSum))
{
return false;
}
if (tmpStatus == status)
{
bmco_information_f3(theLogger, "%s|%s|status %?d has been set",
std::string("0"),std::string(__FUNCTION__),status);
return true;
}
try
{
HTTPClientSession cs(des_ipaddr.c_str(), 9090);
Json::Value head(Json::objectValue);
Json::Value content(Json::objectValue);
Json::Value rootReq(Json::objectValue);
Bmco::Timestamp now;
LocalDateTime dtNow(now);
std::string stNow = DateTimeFormatter::format(dtNow, DateTimeFormat::SORTABLE_FORMAT);
head["processcode"] = "changebolstatus";
head["reqseq"] = "012014120101";
head["reqtime"] = stNow;
content["bol_name"] = bolName;
content["old_status"] = tmpStatus;
content["new_status"] = status;
rootReq["head"] = head;
rootReq["content"] = content;
Json::FastWriter jfw;
std::string oss = jfw.write(rootReq);
//HTTPRequest request("POST", "/echoBody");
HTTPRequest request;
request.setContentLength((int) oss.length());
request.setContentType("text/plain");
cs.sendRequest(request) << oss;
HTTPResponse response;
std::string rbody;
cs.receiveResponse(response) >> rbody;
Json::Value rootRsp;
Json::Reader jsonReader;
if (!jsonReader.parse(rbody, rootRsp))
{
bmco_error_f2(theLogger, "%s|%s|Failed to execute jsonReader",std::string("0"),std::string(__FUNCTION__));
return false;
}
if (!rootRsp.isMember("content"))
{
bmco_error_f2(theLogger, "%s|%s|no content",std::string("0"),std::string(__FUNCTION__));
return false;
}
Json::Value value = rootRsp["content"];
std::string respcode = value["respcode"].asString();
if (respcode != "0")
{
return false;
}
}
catch(Bmco::Exception &e)
{
return false;
}
return true;
}
bool CloudDynamicFlexTaskLoop::hasStoppedALLHLAProcessTimeOut(std::string ShrinkBol)
{
Bmco::Timestamp recordTime;
Bmco::Timestamp now;
// 默认等待4秒
Bmco::Int64 timeOut = 4000000;
std::vector<struct dictinfo> sessionDictInfo;
g_sessionData.getDictInfo(sessionDictInfo);
std::vector<struct dictinfo>::iterator itDict;
for (itDict = sessionDictInfo.begin();
itDict != sessionDictInfo.end();itDict++)
{
// 在zookeeper字典路径下找到超时时间
if ((0 == itDict->key.compare("WaitTimeForStopHLA"))
&& (0 == itDict->id.compare("1000")))
{
timeOut = Bmco::NumberParser::parse(itDict->value);
break;
}
}
bool stopAllHLAProecss = false;
// 在超时时间内
while (now - recordTime < timeOut)
{
if (defineHLAProcessShutdownAlready(ShrinkBol))
{
bmco_information_f2(theLogger, "%s|%s|all HLA process has stopped",std::string("0"),std::string(__FUNCTION__));
stopAllHLAProecss = true;
break;
}
now.update();
}
if (!stopAllHLAProecss)
{
bmco_error_f2(theLogger, "%s|%s|some HLA process has not stop",std::string("0"),std::string(__FUNCTION__));
if (!setRemoteBolStatus(ShrinkBol, BOL_NORMAL))
{
bmco_error_f2(theLogger, "%s|%s|set remote bol normal failed",std::string("0"),std::string(__FUNCTION__));
}
return false;
}
return true;
}
// 确认bol的HLA进程已经停止完毕
bool CloudDynamicFlexTaskLoop::defineHLAProcessShutdownAlready(
std::string bolName)
{
bmco_debug(theLogger, "defineHLAProcessShutdownAlready()");
std::string bpcbInfoPath = "/status/bpcb/" + bolName;
std::string cloudConfigStr;
try
{
if (!CloudDatabaseHandler::instance()->nodeExist(bpcbInfoPath))
{
bmco_error_f3(theLogger,"%s|%s|node:%s has been stopped!",std::string("0"),std::string(__FUNCTION__),
bpcbInfoPath);
return false;
}
if (0 != CloudDatabaseHandler::instance()->getNodeData(bpcbInfoPath, cloudConfigStr))
{
bmco_error_f3(theLogger, "%s|%s|data error at %s", std::string("0"),std::string(__FUNCTION__), bpcbInfoPath);
return false;
}
Json::Value root;
Json::Reader jsonReader;
if (!jsonReader.parse(cloudConfigStr, root))
{
return false;
}
if (!root.isMember("record"))
{
bmco_error_f2(theLogger, "%s|%s|no record",std::string("0"),std::string(__FUNCTION__));
return false;
}
Json::Value valueArray = root["record"];
Bmco::UInt64 bpcbid;
Bmco::UInt64 status;
std::vector<struct flexinfo> tmpVec;
for (int index = 0; index < valueArray.size(); ++index)
{
Json::Value value = valueArray[index];
bpcbid = boost::lexical_cast<Bmco::UInt64>(value["bpcb_id"].asString());
status = boost::lexical_cast<Bmco::UInt64>(value["status"].asString());
if ((999 < bpcbid)
&& (1 == status))
{
bmco_information_f3(theLogger, "%s|%s|bpcbid %?d",
std::string("0"),std::string(__FUNCTION__), bpcbid);
return false;
}
}
}
catch(Bmco::Exception &e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),e.displayText());
return false;
}
catch(...)
{
bmco_error_f2(theLogger,"%s|%s|unknown exception occured when recordHostBaseInfo!",
std::string("0"),std::string(__FUNCTION__));
return false;
}
return true;
}
// 修改消息关系表,将主键在seqNoVec中的记录失效
bool CloudDynamicFlexTaskLoop::setBolMessageRelaInvalid
(std::vector<Bmco::UInt32> seqNoVec)
{
std::string seqNoZKStr;
std::string seqNoVCStr;
std::string cloudConfigStr;
std::string nodePath = ZNODE_ZOOKEEPER_MQ_RELAION;
if (!CloudDatabaseHandler::instance()->nodeExist(nodePath))
{
bmco_error_f1(theLogger, "need to create %s!", nodePath);
return false;
}
try
{
if (0 != CloudDatabaseHandler::instance()->getNodeData(nodePath, cloudConfigStr))
{
bmco_error_f3(theLogger, "%s|%s|data error at %s",
std::string("0"),std::string(__FUNCTION__), nodePath);
return false;
}
if (cloudConfigStr.empty())
{
cloudConfigStr = "{}";
}
Json::Value root;
Json::Reader jsonReader;
if (!jsonReader.parse(cloudConfigStr, root))
{
return false;
}
std::vector<Bmco::UInt32>::iterator itSeq;
Json::Value valueNewArray;
Json::Value valueArray = root["record"];
for (int index = 0; index < valueArray.size(); ++index)
{
Json::Value value = valueArray[index];
for (itSeq = seqNoVec.begin();itSeq != seqNoVec.end();itSeq++)
{
seqNoVCStr = Bmco::format("%?d", *itSeq);
seqNoZKStr = value["seq_id"].asString();
if (seqNoVCStr == seqNoZKStr)
{
value["status"] = "0";
}
valueNewArray[index] = value;
/*if (seqNoVCStr != seqNoZKStr)
{
pRecordNewNode.push_back(std::make_pair("", pColumnNode));
}
else
{
pColumnNode.put<std::string>("status", "0");
pRecordNewNode.push_back(std::make_pair("", pColumnNode));
}*/
}
// pRecordNode = pRecordNewNode;
}
root["record"] = valueNewArray;
Json::FastWriter jfw;
std::string oss = jfw.write(root);
if (!CloudDatabaseHandler::instance()->setNodeData(nodePath, oss))
{
bmco_error(theLogger, "Faild to Set rela invalid");
return false;
}
else
{
bmco_information(theLogger, "***Set rela invalid successfully***");
}
}
catch(Bmco::Exception &e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),e.displayText());
return false;
}
catch(...)
{
bmco_error_f2(theLogger,"%s|%s|unknown exception occured when recordHostBaseInfo!",
std::string("0"),std::string(__FUNCTION__));
return false;
}
return true;
}
bool CloudDynamicFlexTaskLoop::setRelaWithConsumeBolInstance
(std::string topicName,
std::string ShrinkBol)
{
relaInfo relainfo;
std::vector<relaInfo> relaVec;
Bmco::Int32 inPartitionNum = 0;
Bmco::Int32 outPartitionNum = 0;
std::string loggerStr;
bolInstance ansBolInstance;
std::vector<MetaMQRela>::iterator itRela;
for (itRela = m_relaInfoVec.begin();itRela != m_relaInfoVec.end();itRela++)
{
// 是需要重新建立关系的topic和消费的bol
if (0 == topicName.compare(itRela->IN_TOPIC_NAME.c_str())
&& 0 == ShrinkBol.compare(itRela->BOL_CLOUD_NAME.c_str()))
{
// 确定失效的分区新的挂载实例
if (!chooseInstanceBuildRela(topicName, ansBolInstance, DM_After))
{
return false;
}
relainfo.flowId = itRela->Flow_ID.c_str();
relainfo.processName = itRela->PROCESS_NAME.c_str();
// 新bol和实例号
relainfo.bolName = ansBolInstance.bolName;
relainfo.instanceId = Bmco::format("%?d",ansBolInstance.instanceId);
relainfo.inTopicName = itRela->IN_TOPIC_NAME.c_str();
relainfo.outTopicName = itRela->OUT_TOPIC_NAME.c_str();
relainfo.inPartitionName = itRela->IN_PARTITION_NAME.c_str();
relainfo.outPartitionName = itRela->OUT_PARTITION_NAME.c_str();
relainfo.inMqName = itRela->IN_MQ_NAME.c_str();
relainfo.outMqName = itRela->OUT_MQ_NAME.c_str();
relainfo.subsys = itRela->subsys_type.c_str();
relainfo.domain = itRela->domain_type.c_str();
relaVec.push_back(relainfo);
loggerStr = Bmco::format("%s|%s|%s|%s|%s|%s",
relainfo.flowId, relainfo.processName,
relainfo.bolName, relainfo.instanceId,
relainfo.inTopicName, relainfo.outTopicName);
loggerStr += Bmco::format("%s|%s|%s|%s|%s|%s",
relainfo.inPartitionName, relainfo.outPartitionName,
relainfo.inMqName, relainfo.outMqName,
relainfo.subsys, relainfo.domain);
bmco_information_f3(theLogger, "%s|%s|shrink new relainfo %s", std::string("0"),std::string(__FUNCTION__), loggerStr);
}
}
// 保存到关系记录中,最后统一写入zookeeper
m_relaBuildVec.insert(m_relaBuildVec.end(), relaVec.begin(), relaVec.end());
return true;
}
// 获取消息堆积数
bool CloudDynamicFlexTaskLoop::accumulateMessageNum(const Bmco::Timespan &intervalTime,
std::map<std::string, Bmco::Int64> &TopicAccumulateNumVec,
std::map<std::string, mqCalcOffsetData> &TopicUpDownOffsetVec)
{
bmco_debug(theLogger, "accumulateMessageNum()");
std::vector<MetaMQTopic>::iterator itTopic;
std::vector<MetaMQRela>::iterator itRela;
std::string inTopicName;
std::string inPartition;
std::string inMqname;
std::string outTopicName;
std::string outPartition;
std::string outMqName;
// 每一个分区的消息积压数
Bmco::Int64 accumulateBypartition = 0;
mqCalcOffsetData result;
TopicAccumulateNumVec.clear();
std::map<std::string, Bmco::Int64>::iterator itAccu;
for (itRela = m_relaInfoVec.begin();itRela != m_relaInfoVec.end();itRela++)
{
inPartition = itRela->IN_PARTITION_NAME.c_str();
inTopicName = itRela->IN_TOPIC_NAME.c_str();
inMqname = itRela->IN_MQ_NAME.c_str();
outTopicName = itRela->OUT_TOPIC_NAME.c_str();
outPartition = itRela->OUT_PARTITION_NAME.c_str();
outMqName = itRela->OUT_MQ_NAME.c_str();
if (inPartition.empty()
|| inTopicName.empty()
|| inMqname.empty()
|| outTopicName.empty()
|| outPartition.empty()
|| outMqName.empty())
{
bmco_information(theLogger, "this is the head of the flow or not kafka, neglect it!\n");
continue;
}
// 通过上下游的关系计算
if (!getMessageAccumuNumByPatition(inTopicName,
inPartition, inMqname, outTopicName,
outPartition, outMqName,
accumulateBypartition, result))
{
bmco_error_f1(theLogger, "%s getOffsetError Skip it", inTopicName);
continue;
//return false;
}
// 将partition维度的统计加入
TopicAccumulateNumVec.insert(std::pair<std::string, Bmco::Int64>(inTopicName+"#"+inPartition, accumulateBypartition));
// 对同一主题的堆积消息数进行累加
itAccu = TopicAccumulateNumVec.find(inTopicName);
if (itAccu != TopicAccumulateNumVec.end())
{
TopicAccumulateNumVec[inTopicName] += accumulateBypartition;
}
else
{
TopicAccumulateNumVec.insert(std::pair<std::string, Bmco::Int64>(inTopicName, accumulateBypartition));
}
mqCalcOffsetData calcResult;
calcRWSpeed(inTopicName+"#"+inPartition, intervalTime, result, calcResult);
TopicUpDownOffsetVec.insert(std::pair<std::string, mqCalcOffsetData>(inTopicName+"#"+inPartition, calcResult));
}
updateLastAccumulateNumMap();
return true;
}
bool CloudDynamicFlexTaskLoop::getMessageAccumuNumByPatition(std::string inTopicName,
std::string inPartitionName, std::string inMqName,
std::string outTopicName, std::string outPartitionName,
std::string outMqName, Bmco::Int64 &accumulateNum, mqCalcOffsetData &result)
{
Bmco::Int64 upStreamOffset = 0;
Bmco::Int64 downStreamOffset = 0;
MetaMQDef::Ptr pMQDef = new MetaMQDef("", "", "", "", "", 0, 0);
if (!m_DefPtr->getMQDefByDefName(inMqName, pMQDef))
{
bmco_error(theLogger, "no such mqname!!!");
accumulateNum = 0;
return false;
}
m_brokerlist = pMQDef->Broker_list1.c_str();
if (2 == pMQDef->mq_type)
{
bmco_information(theLogger, "this is acct service mq, neglect it!");
accumulateNum = 0;
return false;
}
if (!CloudKafkaMessageHandler::instance(m_brokerlist)->calcuMessageGrossByPartition(inTopicName, inPartitionName, upStreamOffset))
{
return false;
}
if (!m_DefPtr->getMQDefByDefName(outMqName, pMQDef))
{
bmco_error(theLogger, "no such mqname!!!");
accumulateNum = 0;
return false;
}
if (2 == pMQDef->mq_type)
{
bmco_information(theLogger, "this is acct service mq, neglect it!");
accumulateNum = 0;
return false;
}
m_brokerlist = pMQDef->Broker_list1.c_str();
if (!CloudKafkaMessageHandler::instance(m_brokerlist)->calcuReadMessageOffsetByPartition(outTopicName, outPartitionName, downStreamOffset))
{
return false;
}
accumulateNum = upStreamOffset - downStreamOffset;
accumulateNum = (0 > accumulateNum) ? 0 : accumulateNum;
result.upStreamOffset = upStreamOffset;
result.downStreamOffset = downStreamOffset;
std::string logStr = Bmco::format("topic %s partition %s"
" upStreamOffset = %?d, downStreamOffset = %?d, accumulateNum = %?d",
inTopicName, inPartitionName, upStreamOffset, downStreamOffset, accumulateNum);
bmco_information_f1(theLogger, "%s\n", logStr);
return true;
}
void CloudDynamicFlexTaskLoop::doBrokenDownBolOperation()
{
bmco_debug(theLogger, "doBrokenDownBolOperation()");
std::string brokenBolName;
// 检查是否有bol宕机
if (!checkIfExistBolBrokenDown(brokenBolName))
{
bmco_information(theLogger, "all bol do well");
return;
}
std::vector<MetaMQRela>::iterator itRela;
std::vector<Bmco::UInt32> seqNoVec;
std::set<std::string> topicSet;
for (itRela = m_relaInfoVec.begin();itRela != m_relaInfoVec.end();itRela++)
{
if (0 == brokenBolName.compare(itRela->BOL_CLOUD_NAME.c_str()))
{
// 需要将该bol消息关系置为失效
seqNoVec.push_back(itRela->SEQ_ID);
// 需要托管由该bol处理的topic分区
topicSet.insert(itRela->IN_TOPIC_NAME.c_str());
}
}
// 将该bol消息关系置为失效
if (!setBolMessageRelaInvalid(seqNoVec))
{
bmco_error_f2(theLogger, "%s|%s|setBolMessageRelaInvalid failed",std::string("0"),std::string(__FUNCTION__));
return;
}
std::set<std::string>::iterator itSet;
std::string topicName;
// 对于宕掉的bol的所有消费关系的topic进行关系处理
for (itSet = topicSet.begin();itSet != topicSet.end();itSet++)
{
topicName = *itSet;
// 如果只有ShrinkBol处理本topic,则需要发送严重警告
if (isTheOnlyBolForTheTopic(topicName, brokenBolName))
{
bmco_warning_f4(theLogger, "%s|%s|Only %s doWithTheTopic %s core down seriously",
std::string("0"),std::string(__FUNCTION__),brokenBolName,topicName);
return;
}
// 托管宕掉的bol的主题关系到其他bol的实例
if (!setRelaWithConsumeBolInstance(topicName, brokenBolName))
{
bmco_error_f2(theLogger, "%s|%s|setRelaWithConsumeBolInstance failed",std::string("0"),std::string(__FUNCTION__));
return;
}
}
// 修改zookeeper上的消息队列关系表
if (!modifyMQRelaTable())
{
bmco_error_f2(theLogger, "%s|%s|modifyMQRelaTable failed",std::string("0"),std::string(__FUNCTION__));
return;
}
}
// 是否有bol宕机了,返回宕机的bol名称,每次只检查一个
bool CloudDynamicFlexTaskLoop::checkIfExistBolBrokenDown(std::string &brokenBolName)
{
Bmco::Util::AbstractConfiguration& config = Bmco::Util::Application::instance().config();
std::vector<std::string> nodes;
std::string nodePath = ZNODE_ZOOKEEPER_SLAVE_DIR;
// 获取当前存在的节点
if (!CloudDatabaseHandler::instance()->GetChildrenNode(nodePath, nodes))
{
bmco_information_f2(theLogger, "%s|%s|GetChildrenNode failed, return.",std::string("0"),std::string(__FUNCTION__));
return false;
}
std::vector<struct kpiinfo> sessionKpiInfo;
g_sessionData.getKpiInfo(sessionKpiInfo);
std::vector<std::string>::iterator itNode;
std::vector<struct kpiinfo>::iterator itKpi;
for (itKpi = sessionKpiInfo.begin();
itKpi != sessionKpiInfo.end();itKpi++)
{
// 各个节点上报的状态正常的bol,但是临时节点已经消失
// 被认为是宕机的bol
if ("1001" == itKpi->kpi_id
&& "0" == itKpi->kpi_value)
{
itNode = find(nodes.begin(), nodes.end(), itKpi->bol_cloud_name);
// 记录宕机的bol名称
if (itNode == nodes.end())
{
brokenBolName = itKpi->bol_cloud_name;
bmco_warning_f3(theLogger, "%s|%s|%s has broken!!!",
std::string("0"), std::string(__FUNCTION__), brokenBolName);
return true;
}
}
}
return false;
}
// 获取Common的指标信息同步到ZooKeeper
void CloudDynamicFlexTaskLoop::refreshKPIInfoByMaster(std::map<std::string, Bmco::Int64> topicMessageNumMap,
std::map<std::string, mqCalcOffsetData> TopicUpDownOffsetVec)
{
bmco_debug(theLogger, "refreshKPIInfoByMaster()");
MetaKPIInfoOp *tmpKPIPtr = NULL;
std::vector<MetaKPIInfo> vecKPIInfo;
tmpKPIPtr = dynamic_cast<MetaKPIInfoOp*>(ctlOper->getObjectPtr(MetaKPIInfoOp::getObjName()));
if (!tmpKPIPtr->getAllKPIInfo(vecKPIInfo))
{
bmco_error(theLogger, "Failed to execute getAllKPIInfo on MetaShmKPIInfoTable");
}
std::string cloudKPIStr;
std::string KPIInfoPath = "/status/kpi/common";
bmco_debug_f1(theLogger, "KPIInfoPath=%s", KPIInfoPath);
try
{
if (!CloudDatabaseHandler::instance()->nodeExist(KPIInfoPath))
{
if (!CloudDatabaseHandler::instance()->createNode(KPIInfoPath))
{
bmco_error_f1(theLogger, "Faild to createNode: %s", KPIInfoPath);
return;
}
}
if (0 != CloudDatabaseHandler::instance()->getNodeData(KPIInfoPath, cloudKPIStr))
{
bmco_error_f3(theLogger, "%s|%s|data error at %s",
std::string("0"),std::string(__FUNCTION__), KPIInfoPath);
return;
}
if (cloudKPIStr.empty())
{
cloudKPIStr = "{}";
}
Json::Value root(Json::objectValue);
Json::Value field(Json::objectValue);
Json::Value record(Json::arrayValue);
field["kpi_id"] = "指标编号";
field["seq_no"] = "Topic+Partition";
field["bol_name"] = "bol名称";
field["kpi_value"] = "指标值";
field["kpi_value2"] = "指标值2";
field["status_time"] = "变更时间";
Bmco::UInt32 msgNum = 0;
Bmco::Timestamp now;
LocalDateTime dtNow(now);
std::string stNow = DateTimeFormatter::format(dtNow, DateTimeFormat::SORTABLE_FORMAT);
std::map<std::string, Bmco::Int64>::iterator it;
for (it = topicMessageNumMap.begin();it != topicMessageNumMap.end();it++)
{
Json::Value array(Json::objectValue);
array["kpi_id"] = "1002";
array["seq_no"] = it->first;
array["bol_name"] = "";
array["kpi_value"] = Bmco::format("%?d", it->second);
array["kpi_value2"] = "";
array["status_time"] = stNow;
record[msgNum++] = array;
}
std::map<std::string, mqCalcOffsetData>::iterator itOff;
for (itOff = TopicUpDownOffsetVec.begin();itOff != TopicUpDownOffsetVec.end();itOff++)
{
{
Json::Value array(Json::objectValue);
array["kpi_id"] = "1013";
array["seq_no"] = itOff->first;
array["bol_name"] = "";
array["kpi_value"] = Bmco::format("%0.2f", itOff->second.upStreamOffset);
array["kpi_value2"] = "";
array["status_time"] = stNow;
record[msgNum++] = array;
}
{
Json::Value array(Json::objectValue);
array["kpi_id"] = "1014";
array["seq_no"] = itOff->first;
array["bol_name"] = "";
array["kpi_value"] = Bmco::format("%0.2f", itOff->second.downStreamOffset);
array["kpi_value2"] = "";
array["status_time"] = stNow;
record[msgNum++] = array;
}
}
for (int i = 0; i < vecKPIInfo.size(); i++)
{
if (1003 == vecKPIInfo[i].KPI_ID)
{
continue;
}
LocalDateTime dt(vecKPIInfo[i].Create_date);
std::string stCreateTime = DateTimeFormatter::format(dt, DateTimeFormat::SORTABLE_FORMAT);
dt = vecKPIInfo[i].Modi_date;
std::string stModityTime = DateTimeFormatter::format(dt, DateTimeFormat::SORTABLE_FORMAT);
Json::Value array(Json::objectValue);
array["kpi_id"] = Bmco::format("%?d", vecKPIInfo[i].KPI_ID);
array["seq_no"] = std::string(vecKPIInfo[i].Seq_No.c_str());
array["bol_cloud_name"] = std::string(vecKPIInfo[i].Bol_Cloud_Name.c_str());
array["kpi_value"] = std::string(vecKPIInfo[i].KPI_Value.c_str());
array["kpi_value2"] = std::string("");
array["status_time"] = stModityTime;
record[msgNum++] = array;
}
root["name"] = "c_info_kpi";
root["desc"] = "指标信息";
root["field"] = field;
root["record"] = record;
Json::FastWriter jfw;
std::string oss = jfw.write(root);
if (!CloudDatabaseHandler::instance()->setNodeData(KPIInfoPath, oss))
{
bmco_error(theLogger, "Faild to write KPIInfo");
}
else
{
bmco_debug(theLogger, "Set Master KPI info successfully.");
}
}
catch (boost::bad_lexical_cast &e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),std::string(e.what()));
return;
}
catch(Bmco::Exception &e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),e.displayText());
return;
}
catch(std::exception& e)
{
bmco_error_f3(theLogger,"%s|%s|%s",std::string("0"),std::string(__FUNCTION__),std::string(e.what()));
return;
}
catch(...)
{
bmco_error_f2(theLogger,"%s|%s|unknown exception occured when recordHostBaseInfo!",
std::string("0"),std::string(__FUNCTION__));
return;
}
}
void CloudDynamicFlexTaskLoop::calcRWSpeed(std::string fullname,
const Bmco::Timespan &intervalTime,
const mqCalcOffsetData &result, mqCalcOffsetData &calcResult)
{
std::map<std::string, mqCalcOffsetData>::iterator itAgo;
itAgo = m_LastAccumulateNumMap.find(fullname);
if (m_LastAccumulateNumMap.end() != itAgo)
{
int interval = intervalTime.totalSeconds();
calcResult.upStreamOffset = (result.upStreamOffset - itAgo->second.upStreamOffset)/interval;
calcResult.downStreamOffset = (result.downStreamOffset - itAgo->second.downStreamOffset)/interval;
std::string logStr = Bmco::format("upStreamOffset %f %f"
"downStreamOffset %f %f totalSeconds = %?d",
result.upStreamOffset, itAgo->second.upStreamOffset, result.downStreamOffset, itAgo->second.downStreamOffset, interval);
logStr += Bmco::format("calcResult %f %f", calcResult.upStreamOffset, calcResult.downStreamOffset);
bmco_information_f1(theLogger, "%s\n", logStr);
calcResult.upStreamOffset = (0 > calcResult.upStreamOffset) ? 0.00 : calcResult.upStreamOffset;
calcResult.downStreamOffset = (0 > calcResult.downStreamOffset) ? 0.00 : calcResult.downStreamOffset;
}
// 第一次统计速度
else
{
//calcResult.upStreamOffset = result.upStreamOffset;
//calcResult.downStreamOffset = result.upStreamOffset;
calcResult.upStreamOffset = 0.0;
calcResult.downStreamOffset = 0.0;
}
m_CurrAccumulateNumMap.insert(std::pair<std::string, mqCalcOffsetData>(fullname, result));
}
void CloudDynamicFlexTaskLoop::updateLastAccumulateNumMap()
{
m_LastAccumulateNumMap.clear();
m_LastAccumulateNumMap.swap(m_CurrAccumulateNumMap);
m_CurrAccumulateNumMap.clear();
}
void CloudDynamicFlexTaskLoop::setLastTimeStamp()
{
_lastTimeStamp.update();
}
void CloudDynamicFlexTaskLoop::getIntervalTime(Bmco::Timespan& timeCost)
{
timeCost = _lastTimeStamp.elapsed();
}
}
| [
"317190991@qq.com"
] | 317190991@qq.com |
f31957a27f57ee0c5dce2040c16d90fd4c072f73 | 9a0c53d50c410f9b34387a730b34591589a1fafb | /ENCM339/Lab 8/exA/hydro.cpp | b5a9ab5a6e12b5dd7409abf8c0b981c073f27939 | [] | no_license | ConflictingTheories/university_labs | a228c164111aef5b52263e4dd9a8c88218d0bc67 | 4d030be7407bfdc10e61dd8a9d06ee2fd410f1b3 | refs/heads/master | 2020-07-30T12:29:52.985437 | 2019-09-23T01:27:47 | 2019-09-23T01:27:47 | 210,233,518 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,358 | cpp | /*
* hydro.cpp
*
* Created on: Nov 24, 2011
* Author: Kyle Derby MacInnis and Eric Sobkowicz
* Lab: B05
* Group: 82
*/
#include "hydro.h"
void displayHeader() {
cout << "HEF Hydropower Studies - Fall 2011\n" << "Program: Flow Studies\n"
<< "Version: 1.0\n" << "Lab section: B05\n"
<< "Instructor : Dr. Garousi\n"
<< "Produced by: Kyle Derby MacInnis and Eric Sobkowicz\n";
pressEnter();
}
int readData(FlowList& list) {
//Declare Variables
char year[10], flow[20], ch;
int i, ycount, fcount;
bool newline = false, yeardone = false;
//Make Temporary List
struct ListItem List;
ifstream file;
file.open("flow.dat");
if (file == NULL) {
cerr << "File Could Not Be Opened!";
getchar();
exit(1);
}
//Read through file line by line
for (i = 0; !file.eof(); i++) {
ycount = 0;
fcount = 0;
newline = false;
yeardone = false;
while (!newline) {
file.get(ch);
//If working on year characters
if (!yeardone) {
if (ch == ' ' || ch == '\t') {
yeardone = true;
} else if (ch == '\n') {
newline = true;
} else {
year[ycount] = ch;
ycount++;
}
}
//If working on flow characters
else if (yeardone) {
if (ch == ' ' || ch == '\t') {
continue;
} else if (ch == '\n') {
newline = true;
} else {
flow[fcount] = ch;
fcount++;
}
}
}
//Finalize string and Convert to Numbers
year[ycount] = '\0';
flow[fcount] = '\0';
List.year = atoi(year);
List.flow = atof(flow);
//If valid list item, insert data
if (ycount != 0 && fcount != 0)
list.insert(List);
}
file.close();
return i;
}
int menu() {
int choice;
//Show Menu and Prompt user for choice
cout << "\n\nPlease select on the following operations\n"
<< "1. Display data.\n" << "2. Add data.\n"
<< "3. Save data into the file\n" << "4. Remove data\n"
<< "5. Quit\n\n" << "Enter your choice (1, 2, 3, 4 or 5):";
cin >> choice;
if (choice <= 0 || choice > 5) {
cout << "\n\nPlease enter a valid input.";
choice = menu();
}
cleanStandardInputStream();
return choice;
}
void display(FlowList& list) {
//Declare Variables
double smallest, sumFlow = 0;
int index, count = list.count();
double temprecord[count];
struct ListItem item;
//Set To beginning of List
list.reset();
//Read List Items one by one
cout << "\nYear\t\tFlow (in Billions of Cubic Meters)\n";
for (int i = 0; i < count; i++) {
if (list.isOn()) {
//Print values to screen
item = list.getItem();
cout << "\n" << item.year << "\t\t\t" << item.flow;
//Make an array of flow values and update sum
sumFlow += item.flow;
temprecord[i] = item.flow;
list.forward();
} else {
cerr << "\n\nError: List is Empty";
return;
}
}
cout << "\n\nThe Annual Average of the Flow is: " << sumFlow / count << " in Billions Cubic Meter.";
//Sort Flows into non-decreasing order
for (int i = 0; i < count; i++) {
smallest = temprecord[i];
for (int j = i + 1; j < count; j++) {
if (smallest > temprecord[j]) {
smallest = temprecord[j];
index = j;
}
}
temprecord[index] = temprecord[i];
temprecord[i] = smallest;
}
//Find Median of the flows
if (count % 2 == 0)
cout << "\n\nThe Median Flow is " << (temprecord[((count) / 2) - 1]
+ (temprecord[(count) / 2])) / 2 << " in Billions Cubic Meter.";
else if (count % 2 == 1)
cout << "\n\nThe Median Flow is " << temprecord[((count) / 2)] << " in Billions Cubic Meter.";
pressEnter();
}
void addData(FlowList& list, int *num_records) {
struct ListItem item;
//Prompt for Data
cout << "Please enter the year: ";
cin >> item.year;
cout << "Please enter the flow: ";
cin >> item.flow;
//Insert Data and Update Records
list.insert(item);
(*num_records)++;
cleanStandardInputStream();
}
void removeData(FlowList& list, int *num_records) {
int year;
cout << "Please enter the year to be removed: ";
cin >> year;
list.remove(year);
cleanStandardInputStream();
}
void saveData(FlowList& list) {
ofstream file;
struct ListItem item;
file.open("flow.dat");
list.reset();
while (list.isOn()) {
item = list.getItem();
file << item.year << "\t\t" << item.flow << "\n";
list.forward();
}
cout << "\nData has been saved to file.";
file.close();
}
void pressEnter() {
cout << "\n\n<<<Press Enter to Continue>>>";
getchar();
}
void cleanStandardInputStream() {
int i;
do {
i = fgetc(stdin);
} while (i != '\n' && i != EOF);
}
void clearScreen() {
system("cls");
}
int main() {
//Declare Flowlist Object and other variables
FlowList flows;
int numRecords;
int quit = 0;
//Display Header and Read Data from File
displayHeader();
numRecords = readData(flows);
while (1) {
switch (menu()) {
//Display Data
case 1:
clearScreen();
display(flows);
break;
//Add New Data
case 2:
clearScreen();
addData(flows, &numRecords);
pressEnter();
break;
//Save Data to File
case 3:
clearScreen();
saveData(flows);
pressEnter();
break;
//Remove Data
case 4:
clearScreen();
removeData(flows, &numRecords);
pressEnter();
break;
//Exit Program
case 5:
clearScreen();
cout << "\nProgram terminated!\n\n";
quit = 1;
break;
default:
clearScreen();
cout << "\nNot a valid input.\n";
pressEnter();
}
if (quit == 1)
break;
}
return 0;
}
| [
"kderbyma@localhost.localdomain"
] | kderbyma@localhost.localdomain |
2197b5afb9efd7ede6661b74e293a919f20da2d1 | e97a04695cce28a4208a7dddd3d47bd42ce3ff83 | /Backend/Source/CmPreProcess.cpp | 9a242f6626b9d31d96ad7b6a9c4be82107098179 | [] | no_license | pymagda/openCV_project | 896b242a9f92c48cadbc0538aa550da63eba5bff | 6dc5c45be40e06810d2d8d0988d861ba4b32c594 | refs/heads/master | 2021-01-21T23:04:57.783718 | 2017-06-23T06:15:44 | 2017-06-23T06:15:44 | 95,189,104 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,779 | cpp | #include "Backend/Include/CmPreProcess.h"
#include <list>
#include <queue>
#define CHK_IND(p) ((p).x >= 0 && (p).x < _w && (p).y >= 0 && (p).y < _h)
typedef vector<double> vecD;
typedef vector<int> vecI;
using namespace cv;
using namespace std;
extern Point const DIRECTION8[9];
const double EPS = 1e-200;
typedef const Mat CMat;
#define ForPoints2(pnt, xS, yS, xE, yE) for (Point pnt(0, (yS)); pnt.y != (yE); pnt.y++) for (pnt.x = (xS); pnt.x != (xE); pnt.x++)
Point const DIRECTION8[9] = {
Point(1, 0),
Point(1, 1),
Point(0, 1),
Point(-1, 1),
Point(-1, 0),
Point(-1,-1),
Point(0, -1),
Point(1, -1),
Point(0, 0),
};
Rect CmPreProcess::GetMaskRange(CMat &mask1u, int ext, int thresh)
{
int maxX = INT_MIN, maxY = INT_MIN, minX = INT_MAX, minY = INT_MAX, rows = mask1u.rows, cols = mask1u.cols;
for (int r = 0; r < rows; r++) {
const unsigned char* data = mask1u.ptr<unsigned char>(r);
for (int c = 0; c < cols; c++)
if (data[c] > thresh) {
maxX = max(maxX, c);
minX = min(minX, c);
maxY = max(maxY, r);
minY = min(minY, r);
}
}
maxX = maxX + ext + 1 < cols ? maxX + ext + 1 : cols;
maxY = maxY + ext + 1 < rows ? maxY + ext + 1 : rows;
minX = minX - ext > 0 ? minX - ext : 0;
minY = minY - ext > 0 ? minY - ext : 0;
return Rect(minX, minY, maxX - minX, maxY - minY);
}
int CmPreProcess::GetNZRegions(const Mat_<unsigned char> &label1u, Mat_<int> ®Idx1i, vecI &idxSum)
{
vector<pair<int, int>> counterIdx;
int _w = label1u.cols, _h = label1u.rows, maxIdx = -1;
regIdx1i.create(label1u.size());
regIdx1i = -1;
for (int y = 0; y < _h; y++){
int *regIdx = regIdx1i.ptr<int>(y);
const unsigned char *label = label1u.ptr<unsigned char>(y);
for (int x = 0; x < _w; x++) {
if (regIdx[x] != -1 || label[x] == 0)
continue;
pair <int,int> counterReg = std::make_pair(0,++maxIdx);
Point pt(x, y);
queue<Point, list<Point>> neighbs;
regIdx[x] = maxIdx;
neighbs.push(pt);
while(neighbs.size()){
pt = neighbs.front();
neighbs.pop();
counterReg.first += label1u(pt);
Point nPt(pt.x, pt.y - 1);
if (nPt.y >= 0 && regIdx1i(nPt) == -1 && label1u(nPt) > 0){
regIdx1i(nPt) = maxIdx;
neighbs.push(nPt);
}
nPt.y = pt.y + 1; // lower
if (nPt.y < _h && regIdx1i(nPt) == -1 && label1u(nPt) > 0){
regIdx1i(nPt) = maxIdx;
neighbs.push(nPt);
}
nPt.y = pt.y, nPt.x = pt.x - 1; // Left
if (nPt.x >= 0 && regIdx1i(nPt) == -1 && label1u(nPt) > 0){
regIdx1i(nPt) = maxIdx;
neighbs.push(nPt);
}
nPt.x = pt.x + 1; // Right
if (nPt.x < _w && regIdx1i(nPt) == -1 && label1u(nPt) > 0) {
regIdx1i(nPt) = maxIdx;
neighbs.push(nPt);
}
}
// Add current region to regions
counterIdx.push_back(counterReg);
}
}
sort(counterIdx.begin(), counterIdx.end(), greater<pair<int, int>>());
int idxNum = (int)counterIdx.size();
vector<int> newIdx(idxNum);
idxSum.resize(idxNum);
for (int i = 0; i < idxNum; i++){
idxSum[i] = counterIdx[i].first;
newIdx[counterIdx[i].second] = i;
}
for (int y = 0; y < _h; y++){
int *regIdx = regIdx1i.ptr<int>(y);
for (int x = 0; x < _w; x++)
if (regIdx[x] >= 0)
regIdx[x] = newIdx[regIdx[x]];
}
return idxNum;
}
Mat CmPreProcess::GetNZRegionsLS(CMat &mask1u, double ignoreRatio)
{
CV_Assert(mask1u.type() == CV_8UC1 && mask1u.data != NULL);
ignoreRatio *= mask1u.rows * mask1u.cols * 255;
Mat_<int> regIdx1i;
vecI idxSum;
Mat resMask;
CmPreProcess::GetNZRegions(mask1u, regIdx1i, idxSum);
if (idxSum.size() >= 1 && idxSum[0] > ignoreRatio)
compare(regIdx1i, 0, resMask, CMP_EQ);
return resMask;
}
| [
"magdapeksa@gmail.com"
] | magdapeksa@gmail.com |
b583d3e9c02ad15813e4831912a7e76d7f36256c | 28533865ec76b3223acf2e9ae40c378a64550b8a | /CSPong/AppSource/Game/Particles/ParticleEffectComponentFactory.h | 4d0c89abee7f4274d71dc0cfbff187c2243accbb | [
"MIT"
] | permissive | angelahnicole/Benchmarking-CSPong | ebfc76e1dc178af56d933de7abf80257861b9bd5 | 7efa0913410919291ea8de9ee4d0c4993b5d761e | refs/heads/master | 2021-01-17T18:36:16.684660 | 2016-03-29T22:53:00 | 2016-03-29T22:53:00 | 49,687,255 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,034 | h | //
// ParticleEffectComponentFactory.h
// CSPong
// Created by Angela Gross on 12/01/2016.
//
// The MIT License (MIT)
//
// Copyright (c) 2016 Tag Games Limited
//
// 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 _APPSOURCE_GAME_PARTICLES_PARTICLEEFFECTCOMPONENTFACTORY_H_
#define _APPSOURCE_GAME_PARTICLES_PARTICLEEFFECTCOMPONENTFACTORY_H_
#include <ForwardDeclarations.h>
#include <Game/Physics/DynamicBodyComponent.h>
#include <ChilliSource/Core/System.h>
#include <ChilliSource/Core/Event.h>
namespace CSPong
{
//------------------------------------------------------------
/// Creates different particle effects- instant/looping or on
/// collision. And, since it is an app system, these effects
/// will be able to be chosen during other game states.
///
/// @author Angela Gross
//------------------------------------------------------------
class ParticleEffectComponentFactory final : public CSCore::AppSystem
{
public:
CS_DECLARE_NAMEDTYPE(ParticleEffectComponentFactory);
//------------------------------------------------------------
/// An enum that describes the different types of particle
/// effects that have been created for the game.
///
/// @author Angela Gross
//------------------------------------------------------------
enum class ParticleType
{
k_blueMagmaBurst,
k_yellowMagmaBurst,
k_blueIceCreamBurst,
k_pinkIceCreamBurst,
k_beamStream,
k_smokeStream,
k_sparksStream
};
//------------------------------------------------------------
/// Creates a new instance of the system.
///
/// @author Angela Gross
///
/// @return The new instance.
//------------------------------------------------------------
static ParticleEffectComponentFactoryUPtr Create();
//------------------------------------------------------------
/// Essentially a destructor- will reset collision connections
/// and empty the member vector.
///
/// @author Angela Gross
//------------------------------------------------------------
void OnDestroy() override;
//------------------------------------------------------------
/// @author Angela Gross
///
/// @param Comparison Type
///
/// @return Whether the class matches the comparison type
//------------------------------------------------------------
bool IsA(CSCore::InterfaceIDType in_interfaceId) const override;
//------------------------------------------------------------
/// Manually resets collision connection pointers and clears
/// the collision connection vector.
///
/// @author Angela Gross
//------------------------------------------------------------
void ReleaseCollisionConnections();
//------------------------------------------------------------
/// Creates a particle effect component based on the given
/// particle type. If the given particle type is invalid, then
/// it creates a smoke stream.
///
/// @author Angela Gross
///
/// @param The type of particle effect to create.
/// @param Whether or not the particle effect should loop.
///
/// @return The new particle effect component.
//------------------------------------------------------------
CSRendering::ParticleEffectComponentUPtr CreateParticleEffectComponent(const ParticleType in_particleType, const bool in_looping) const;
//------------------------------------------------------------
/// Creates a particle effect component that will play when
/// the given collision event is triggered based on the given
/// particle type. If the given particle type is invalid, then
/// it creates a smoke stream. (Note that this means the
/// particle effect will not loop and will only play on
/// collision. Also, a SHARED pointer is returned because
/// of the delgate using the particle effect)
///
/// @author Angela Gross
///
/// @param The type of particle effect to create.
/// @param The collision delegate event used to trigger the
/// collision you want to play the particle effect during.
///
/// @return The new particle effect component.
//------------------------------------------------------------
CSRendering::ParticleEffectComponentSPtr CreateOnCollisionParticleEffectComponent(const ParticleType in_particleType, CSCore::IConnectableEvent<DynamicBodyComponent::CollisionDelegate>& in_collisionEvent);
//------------------------------------------------------------
/// Creates and adds particle components to the player entity
/// according to the k_gameParticles and m_particlesChosen
/// arrays. It plays these particles on collision.
///
/// @author Angela Gross
///
/// @param The entity that represents the player
/// @param The collision delegate event used to trigger the
/// collision you want to play the particle effect during.
//------------------------------------------------------------
void AddPlayerParticlesOnCollision(CSCore::EntitySPtr in_playerEntity, CSCore::IConnectableEvent<DynamicBodyComponent::CollisionDelegate>& in_collisionEvent);
//------------------------------------------------------------
/// Creates and adds particle components to the opponent entity
/// according to the k_gameParticles and m_particlesChosen
/// arrays. It plays these particles on collision.
///
/// @author Angela Gross
///
/// @param The entity that represents the opponent
//------------------------------------------------------------
void AddOpponentParticlesOnCollision(CSCore::EntitySPtr in_opponentEntity, CSCore::IConnectableEvent<DynamicBodyComponent::CollisionDelegate>& in_collisionEvent);
//------------------------------------------------------------
/// Creates and adds particle components to the ball entity
/// according to the k_gameParticles and m_particlesChosen
/// arrays.
///
/// @author Angela Gross
///
/// @param The entity that represents the ball
//------------------------------------------------------------
void AddBallParticles(CSCore::EntitySPtr in_ballEntity);
//------------------------------------------------------------
/// Sets the player particles that were chosen by the user
/// in m_particlesChosen.
///
/// @author Angela Gross
///
/// @param Whether or not the magma particles will be added
/// @param Whether or not the ice cream particles will be
/// added
//------------------------------------------------------------
void SetPlayerParticles(const bool in_magmaUsed, const bool in_iceCreamUsed);
//------------------------------------------------------------
/// Sets the opponent particles that were chosen by the user
/// in m_particlesChosen.
///
/// @author Angela Gross
///
/// @param Whether or not the magma particles will be added
/// @param Whether or not the ice cream particles will be
/// added
//------------------------------------------------------------
void SetOpponentParticles(const bool in_magmaUsed, const bool in_iceCreamUsed);
//------------------------------------------------------------
/// Sets the ball particles that were chosen by the user
/// in m_particlesChosen.
///
/// @author Angela Gross
///
/// @param Whether or not the smoke particles will be added
/// @param Whether or not the beam particles will be added
//------------------------------------------------------------
void SetBallParticles(const bool in_smokeUsed, const bool in_beamUsed);
private:
//----------------------------------------------------------
/// Private constructor to enforce use of factory method.
///
/// @author Angela Gross
//----------------------------------------------------------
ParticleEffectComponentFactory();
const int k_playerParticlesIx = 0;
const int k_opponentParticlesIx = 2;
const int k_ballParticlesIx = 4;
const static ParticleEffectComponentFactory::ParticleType k_gameParticles[];
bool m_particlesChosen[6];
std::vector<CSCore::EventConnectionSPtr> m_collisionConnections;
};
}
#endif | [
"angelangross@gmail.com"
] | angelangross@gmail.com |
de9c4f73909ab30e9b012c661a09299359e0f983 | 632a260c17d402528d2637d31e19484ed2dc7781 | /required_packages/DP-GMM/src/LogConcaveFunction.h | 0d4112bd2eca2053780cd1070c1ada2828e524d6 | [] | no_license | Mijan/LFNS | ab355b3a73d9943f66926420066068f8bfdab7a9 | fa84cc7c90e9e706c006eaf8ff506dc15cba8f6e | refs/heads/publishable | 2023-06-24T02:32:05.874735 | 2023-06-09T20:56:08 | 2023-06-09T20:56:08 | 184,099,871 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,587 | h | /*
* LogConcaveFunction.h
*
* Created on: Jul 30, 2013
* Author: jan
*/
#ifndef DP_GMM2_LOGCONCAVEFUNCTION_H_
#define DP_GMM2_LOGCONCAVEFUNCTION_H_
#include <math.h>
#include <float.h>
#include <iostream>
#include <sstream>
#include <stdexcept>
namespace DP_GMM {
class LogConcaveFunction {
public:
LogConcaveFunction() :
_scale(0), _min_log_range(0), _max_log_range(0), _min_bound_val(
MIN_BOUND_VAL), _max_bound_val(MAX_BOUND_VAL), _max_computed_log_val(), _max_computed_log_pt() {
}
virtual ~LogConcaveFunction() {
}
virtual double operator()(double x) = 0;
double getMinRange() {
return LEFT_TRANFORMED_BOUND;
}
double getMaxRange() {
return RIGHT_TRANFORMED_BOUND;
}
double getMinRangeVal() {
return _logEvaluate(_min_log_range);
}
double getMaxRangeVal() {
return _logEvaluate(_max_log_range);
}
double _transformInput(double input) {
return LEFT_TRANFORMED_BOUND
+ ((input - _min_log_range) / (_max_log_range - _min_log_range))
* (RIGHT_TRANFORMED_BOUND - LEFT_TRANFORMED_BOUND);
}
double _inverseTransformInput(double input) {
return _min_log_range
+ ((input - LEFT_TRANFORMED_BOUND)
/ (RIGHT_TRANFORMED_BOUND - LEFT_TRANFORMED_BOUND))
* (_max_log_range - _min_log_range);
}
bool isPointMass() {
return (exp(_max_log_range) - exp(_min_log_range))
/ (0.5 * (exp(_max_log_range) + exp(_min_log_range))) <= TOL;
}
protected:
virtual double _logEvaluate(double x) const = 0;
void _setRange(double feasible_pt, double min_range_tmp,
double max_range_tmp) {
_max_computed_log_pt = feasible_pt;
_min_log_range = min_range_tmp;
_max_log_range = max_range_tmp;
do {
_scale = 0.0;
_setBounds(_max_computed_log_pt, _min_log_range, _max_log_range);
_setScale();
} while (!_range_properly_set());
}
bool _range_properly_set() {
return _min_bound_val >= _max_computed_log_val + MIN_BOUND_VAL;
}
void _setBounds(double feasible_pt, double min_range_tmp,
double max_range_tmp) {
double feasible_val = _logEvaluate(feasible_pt);
if (feasible_val <= -DBL_MAX || feasible_val >= DBL_MAX
|| feasible_val != feasible_val) {
double min_val = _logEvaluate(min_range_tmp);
double max_val = _logEvaluate(max_range_tmp);
std::ostringstream os;
os
<< "Could not sample from log concave function, since at feasible point "
<< feasible_pt << " it is " << feasible_val << std::endl;
throw std::runtime_error(os.str());
}
_max_computed_log_val = feasible_val;
_max_computed_log_pt = feasible_pt;
double min_val = _logEvaluate(min_range_tmp);
_updateMaxPt(min_val, min_range_tmp);
double max_val = _logEvaluate(max_range_tmp);
_updateMaxPt(max_val, max_range_tmp);
_min_bound_val = feasible_val + MIN_BOUND_VAL;
_max_bound_val = feasible_val + MAX_BOUND_VAL;
if (min_val < _min_bound_val) {
_min_log_range = _findSmallesFeasiblePoint(min_range_tmp,
feasible_pt);
} else {
_min_log_range = min_range_tmp;
}
if (max_val < _min_bound_val) {
_max_log_range = _findSmallesFeasiblePoint(max_range_tmp,
feasible_pt);
} else {
_max_log_range = max_range_tmp;
}
}
double _findSmallesFeasiblePoint(double infeasible_pt, double feasible_pt) {
double m_pt = (infeasible_pt + feasible_pt) / 2.0;
double m_val = _logEvaluate(m_pt);
_updateMaxPt(m_val, m_pt);
if (m_val > _min_bound_val) {
if (m_val <= _max_bound_val) {
return m_pt;
} else {
return _findSmallesFeasiblePoint(infeasible_pt, m_pt);
}
} else {
return _findSmallesFeasiblePoint(m_pt, feasible_pt);
}
}
void _setScale() {
_scale = 0.0;
double scale = -DBL_MAX;
double new_scale = 0.0;
double x = _min_log_range;
while (x <= _max_log_range) {
new_scale = _logEvaluate(x);
if (new_scale > scale) {
scale = new_scale;
_updateMaxPt(scale, x);
}
x += (_max_log_range - _min_log_range) / 100;
}
_scale = scale;
}
double _scale;
private:
void _updateMaxPt(double new_val, double new_pt) {
if (new_val > _max_computed_log_val) {
_max_computed_log_val = new_val;
_max_computed_log_pt = new_pt;
}
}
double _min_log_range;
double _max_log_range;
double _min_bound_val;
double _max_bound_val;
double _max_computed_log_val;
double _max_computed_log_pt;
static constexpr double TOL = 0.1;
static constexpr double MIN_BOUND_VAL = -7;
static constexpr double MAX_BOUND_VAL = -5;
static constexpr double LEFT_TRANFORMED_BOUND = 0;
static constexpr double RIGHT_TRANFORMED_BOUND = 100;
};
} /* namespace DP_GMM2 */
#endif /* DP_GMM2_LOGCONCAVEFUNCTION_H_ */
| [
"jan.mikelson@bsse.ethz.ch"
] | jan.mikelson@bsse.ethz.ch |
dd5a2bfd0bd8d72dfb3173b9a8dedab354f89a8d | 952685810657b346710a1fecab915ebe69ad6c63 | /Src/server/SyncQueue.hpp | 6e1530e8686182ddd9e3a16df8863a98bc55bc88 | [] | no_license | liuhangyang/StormDB | 68631cba14f1d04673b0b0a33dae8f31d9d2af73 | aa2b200571aa8627f39a41f4967d8437ad538571 | refs/heads/master | 2021-01-12T07:50:46.063383 | 2017-02-01T09:09:39 | 2017-02-01T09:09:39 | 77,040,451 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,733 | hpp | //
// Created by yang on 16-8-11.
//
#include <list>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <iostream>
#include<utility>
template <typename T>
class SyncQueue {
public:
SyncQueue(int maxSize) {
m_maxSize = maxSize;
m_needStop = false;
}
void Put(const T &x) {
Add(x);
}
void Put(T &&x) {
Add(std::forward<T>(x));
}
void Take(std::list<T> &list) {
std::unique_lock<std::mutex> locker(m_mutex);
m_notEmpty.wait(locker, [this] { return m_needStop || NotEmpty(); });
if (m_needStop) {
return;
}
list = std::move(m_queue);
m_notFull.notify_one();
}
void Take(T &t) {
std::unique_lock<std::mutex> locker(m_mutex);
m_notEmpty.wait(locker, [this] { return m_needStop || NotEmpty(); });
if (m_needStop) {
return;
}
t = m_queue.front();
m_queue.pop_front();
m_notFull.notify_one();
}
void Stop() {
{
std::lock_guard<std::mutex> locker(m_mutex);
m_needStop = true;
}
m_notFull.notify_all();
m_notEmpty.notify_all();
}
bool Empty() {
std::lock_guard<std::mutex> locker(m_mutex);
return m_queue.empty();
}
bool Full() {
std::lock_guard<std::mutex> locker(m_mutex);
return m_queue.size() == m_maxSize;
}
size_t Size() {
std::lock_guard<std::mutex> locker(m_mutex);
return m_queue.size();
};
int Count() {
return m_queue.size();
}
private:
bool NotFull() const {
bool full = m_queue.size() >= m_maxSize;
if (full) {
std::cout << "缓冲区满了,需要等待...." << std::endl;
}
return !full;
}
bool NotEmpty() const {
bool empty = m_queue.empty();
if (empty) {
std::cout << "缓冲区空了,需要等待...,异步层的线程ID:" << std::this_thread::get_id() << std::endl;
}
return !empty;
}
template <typename F>
void Add(F &&x) {
std::unique_lock<std::mutex> locker(m_mutex);
m_notFull.wait(locker, [this] { return m_needStop || NotFull(); });
if (m_needStop) {
return;
}
m_queue.push_back(std::forward<F>(x));
m_notEmpty.notify_one();
}
private:
std::list<T> m_queue; /*任务队列*/
std::mutex m_mutex; /*互斥锁*/
std::condition_variable m_notEmpty; /*不为空的条件变量*/
std::condition_variable m_notFull; /*不为满的条件变量*/
int m_maxSize; /*同步表队列的最大size*/
bool m_needStop; /*停止的标志*/
};
| [
"yanglongfei22@gmail.com"
] | yanglongfei22@gmail.com |
6d58c20268ce6ddd00583dd457e9a42f8f04a550 | 5d98b36145a6c20d0e50233452a7c3515d0c9563 | /FLOW002.cpp | 01fd6dcf00830ef9687a713d93ff647ac36147be | [] | no_license | rajeeb7341/CodeChef | 666a08a5836fa2f6ddda6fcebb976a1cbaecfbb7 | b10f3b4b4dcce049b70e42bd5c61bfe4e4dbb3ef | refs/heads/master | 2020-03-27T21:42:22.133428 | 2018-09-03T08:21:37 | 2018-09-03T08:21:37 | 147,169,235 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 178 | cpp | #include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int a,b;
while(n--)
{
cin>>a>>b;
cout<<a%b<<endl;
}
return 0;
}
| [
"noreply@github.com"
] | rajeeb7341.noreply@github.com |
367e3a4a73e8cf89c9262f6016d955bb13489b63 | c857f603d91cfded23a5f7793dbba6d3c8b2c9ac | /qtango/qtcreator/plugin/.moc/release-shared/moc_qtangowidgetplugin.cpp | a8e9d847fecc0074101971a381a5f3b74e12de20 | [] | no_license | dropsni/qtango | f78bedfec7601546fd04780280ce25ccdeab179d | cbf9aa0ff9d0bfb0c91d9cbb0bed7f29173ee50d | refs/heads/master | 2023-07-07T15:50:39.716550 | 2021-08-12T13:05:27 | 2021-08-12T13:05:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,516 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'qtangowidgetplugin.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.6.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../qtangowidgetplugin.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#include <QtCore/qplugin.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'qtangowidgetplugin.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.6.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_QTangoWidget__Internal__QTangoWidgetPlugin_t {
QByteArrayData data[3];
char stringdata0[58];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_QTangoWidget__Internal__QTangoWidgetPlugin_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_QTangoWidget__Internal__QTangoWidgetPlugin_t qt_meta_stringdata_QTangoWidget__Internal__QTangoWidgetPlugin = {
{
QT_MOC_LITERAL(0, 0, 42), // "QTangoWidget::Internal::QTang..."
QT_MOC_LITERAL(1, 43, 13), // "triggerAction"
QT_MOC_LITERAL(2, 57, 0) // ""
},
"QTangoWidget::Internal::QTangoWidgetPlugin\0"
"triggerAction\0"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_QTangoWidget__Internal__QTangoWidgetPlugin[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 19, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void,
0 // eod
};
void QTangoWidget::Internal::QTangoWidgetPlugin::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
QTangoWidgetPlugin *_t = static_cast<QTangoWidgetPlugin *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->triggerAction(); break;
default: ;
}
}
Q_UNUSED(_a);
}
const QMetaObject QTangoWidget::Internal::QTangoWidgetPlugin::staticMetaObject = {
{ &ExtensionSystem::IPlugin::staticMetaObject, qt_meta_stringdata_QTangoWidget__Internal__QTangoWidgetPlugin.data,
qt_meta_data_QTangoWidget__Internal__QTangoWidgetPlugin, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *QTangoWidget::Internal::QTangoWidgetPlugin::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *QTangoWidget::Internal::QTangoWidgetPlugin::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_QTangoWidget__Internal__QTangoWidgetPlugin.stringdata0))
return static_cast<void*>(const_cast< QTangoWidgetPlugin*>(this));
return ExtensionSystem::IPlugin::qt_metacast(_clname);
}
int QTangoWidget::Internal::QTangoWidgetPlugin::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = ExtensionSystem::IPlugin::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 1)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 1;
}
return _id;
}
QT_PLUGIN_METADATA_SECTION const uint qt_section_alignment_dummy = 42;
#ifdef QT_NO_DEBUG
QT_PLUGIN_METADATA_SECTION
static const unsigned char qt_pluginMetaData[] = {
'Q', 'T', 'M', 'E', 'T', 'A', 'D', 'A', 'T', 'A', ' ', ' ',
'q', 'b', 'j', 's', 0x01, 0x00, 0x00, 0x00,
'`', 0x02, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00,
'L', 0x02, 0x00, 0x00, 0x1b, 0x03, 0x00, 0x00,
0x03, 0x00, 'I', 'I', 'D', 0x00, 0x00, 0x00,
'!', 0x00, 'o', 'r', 'g', '.', 'q', 't',
'-', 'p', 'r', 'o', 'j', 'e', 'c', 't',
'.', 'Q', 't', '.', 'Q', 't', 'C', 'r',
'e', 'a', 't', 'o', 'r', 'P', 'l', 'u',
'g', 'i', 'n', 0x00, 0x9b, 0x09, 0x00, 0x00,
0x09, 0x00, 'c', 'l', 'a', 's', 's', 'N',
'a', 'm', 'e', 0x00, 0x12, 0x00, 'Q', 'T',
'a', 'n', 'g', 'o', 'W', 'i', 'd', 'g',
'e', 't', 'P', 'l', 'u', 'g', 'i', 'n',
0x1a, 0xc0, 0xa0, 0x00, 0x07, 0x00, 'v', 'e',
'r', 's', 'i', 'o', 'n', 0x00, 0x00, 0x00,
0x11, 0x00, 0x00, 0x00, 0x05, 0x00, 'd', 'e',
'b', 'u', 'g', 0x00, 0x95, 0x11, 0x00, 0x00,
0x08, 0x00, 'M', 'e', 't', 'a', 'D', 'a',
't', 'a', 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00,
0x13, 0x00, 0x00, 0x00, 0x9c, 0x01, 0x00, 0x00,
0x1b, 0x03, 0x00, 0x00, 0x04, 0x00, 'N', 'a',
'm', 'e', 0x00, 0x00, 0x0c, 0x00, 'Q', 'T',
'a', 'n', 'g', 'o', 'W', 'i', 'd', 'g',
'e', 't', 0x00, 0x00, 0x1b, 0x07, 0x00, 0x00,
0x07, 0x00, 'V', 'e', 'r', 's', 'i', 'o',
'n', 0x00, 0x00, 0x00, 0x05, 0x00, '0', '.',
'0', '.', '1', 0x00, 0x9b, 0x0a, 0x00, 0x00,
0x0d, 0x00, 'C', 'o', 'm', 'p', 'a', 't',
'V', 'e', 'r', 's', 'i', 'o', 'n', 0x00,
0x05, 0x00, '0', '.', '0', '.', '1', 0x00,
0x1b, 0x0d, 0x00, 0x00, 0x06, 0x00, 'V', 'e',
'n', 'd', 'o', 'r', 0x02, 0x00, 'G', 'S',
0x9b, 0x0f, 0x00, 0x00, 0x09, 0x00, 'C', 'o',
'p', 'y', 'r', 'i', 'g', 'h', 't', 0x00,
0x17, 0x00, '(', 'C', ')', ' ', 'G', 'i',
'a', 'c', 'o', 'm', 'o', ' ', 'S', 't',
'r', 'a', 'n', 'g', 'o', 'l', 'i', 'n',
'o', 0x00, 0x00, 0x00, 0x1b, 0x15, 0x00, 0x00,
0x07, 0x00, 'L', 'i', 'c', 'e', 'n', 's',
'e', 0x00, 0x00, 0x00, '!', 0x00, 'P', 'u',
't', ' ', 'y', 'o', 'u', 'r', ' ', 'l',
'i', 'c', 'e', 'n', 's', 'e', ' ', 'i',
'n', 'f', 'o', 'r', 'm', 'a', 't', 'i',
'o', 'n', ' ', 'h', 'e', 'r', 'e', 0x00,
0x1b, 0x1c, 0x00, 0x00, 0x0b, 0x00, 'D', 'e',
's', 'c', 'r', 'i', 'p', 't', 'i', 'o',
'n', 0x00, 0x00, 0x00, '+', 0x00, 'P', 'u',
't', ' ', 'a', ' ', 's', 'h', 'o', 'r',
't', ' ', 'd', 'e', 's', 'c', 'r', 'i',
'p', 't', 'i', 'o', 'n', ' ', 'o', 'f',
' ', 'y', 'o', 'u', 'r', ' ', 'p', 'l',
'u', 'g', 'i', 'n', ' ', 'h', 'e', 'r',
'e', 0x00, 0x00, 0x00, 0x9b, '#', 0x00, 0x00,
0x03, 0x00, 'U', 'r', 'l', 0x00, 0x00, 0x00,
0x18, 0x00, 'h', 't', 't', 'p', ':', '/',
'/', 'w', 'w', 'w', '.', 'm', 'y', 'c',
'o', 'm', 'p', 'a', 'n', 'y', '.', 'c',
'o', 'm', 0x00, 0x00, 0x94, ')', 0x00, 0x00,
0x0c, 0x00, 'D', 'e', 'p', 'e', 'n', 'd',
'e', 'n', 'c', 'i', 'e', 's', 0x00, 0x00,
'P', 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
'L', 0x00, 0x00, 0x00, '@', 0x00, 0x00, 0x00,
0x05, 0x00, 0x00, 0x00, '8', 0x00, 0x00, 0x00,
0x1b, 0x03, 0x00, 0x00, 0x04, 0x00, 'N', 'a',
'm', 'e', 0x00, 0x00, 0x04, 0x00, 'C', 'o',
'r', 'e', 0x00, 0x00, 0x1b, 0x06, 0x00, 0x00,
0x07, 0x00, 'V', 'e', 'r', 's', 'i', 'o',
'n', 0x00, 0x00, 0x00, 0x05, 0x00, '4', '.',
'0', '.', '0', 0x00, 0x0c, 0x00, 0x00, 0x00,
' ', 0x00, 0x00, 0x00, 0x85, 0x01, 0x00, 0x00,
'@', 0x00, 0x00, 0x00, 'l', 0x00, 0x00, 0x00,
'8', 0x01, 0x00, 0x00, 0xcc, 0x00, 0x00, 0x00,
0x98, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x10, 0x01, 0x00, 0x00, '\\', 0x00, 0x00, 0x00,
'(', 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
'|', 0x00, 0x00, 0x00, '<', 0x00, 0x00, 0x00,
'p', 0x00, 0x00, 0x00, '`', 0x00, 0x00, 0x00
};
#else // QT_NO_DEBUG
QT_PLUGIN_METADATA_SECTION
static const unsigned char qt_pluginMetaData[] = {
'Q', 'T', 'M', 'E', 'T', 'A', 'D', 'A', 'T', 'A', ' ', ' ',
'q', 'b', 'j', 's', 0x01, 0x00, 0x00, 0x00,
'`', 0x02, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00,
'L', 0x02, 0x00, 0x00, 0x1b, 0x03, 0x00, 0x00,
0x03, 0x00, 'I', 'I', 'D', 0x00, 0x00, 0x00,
'!', 0x00, 'o', 'r', 'g', '.', 'q', 't',
'-', 'p', 'r', 'o', 'j', 'e', 'c', 't',
'.', 'Q', 't', '.', 'Q', 't', 'C', 'r',
'e', 'a', 't', 'o', 'r', 'P', 'l', 'u',
'g', 'i', 'n', 0x00, 0x95, 0x09, 0x00, 0x00,
0x08, 0x00, 'M', 'e', 't', 'a', 'D', 'a',
't', 'a', 0x00, 0x00, 0xc0, 0x01, 0x00, 0x00,
0x13, 0x00, 0x00, 0x00, 0x9c, 0x01, 0x00, 0x00,
0x1b, 0x03, 0x00, 0x00, 0x04, 0x00, 'N', 'a',
'm', 'e', 0x00, 0x00, 0x0c, 0x00, 'Q', 'T',
'a', 'n', 'g', 'o', 'W', 'i', 'd', 'g',
'e', 't', 0x00, 0x00, 0x1b, 0x07, 0x00, 0x00,
0x07, 0x00, 'V', 'e', 'r', 's', 'i', 'o',
'n', 0x00, 0x00, 0x00, 0x05, 0x00, '0', '.',
'0', '.', '1', 0x00, 0x9b, 0x0a, 0x00, 0x00,
0x0d, 0x00, 'C', 'o', 'm', 'p', 'a', 't',
'V', 'e', 'r', 's', 'i', 'o', 'n', 0x00,
0x05, 0x00, '0', '.', '0', '.', '1', 0x00,
0x1b, 0x0d, 0x00, 0x00, 0x06, 0x00, 'V', 'e',
'n', 'd', 'o', 'r', 0x02, 0x00, 'G', 'S',
0x9b, 0x0f, 0x00, 0x00, 0x09, 0x00, 'C', 'o',
'p', 'y', 'r', 'i', 'g', 'h', 't', 0x00,
0x17, 0x00, '(', 'C', ')', ' ', 'G', 'i',
'a', 'c', 'o', 'm', 'o', ' ', 'S', 't',
'r', 'a', 'n', 'g', 'o', 'l', 'i', 'n',
'o', 0x00, 0x00, 0x00, 0x1b, 0x15, 0x00, 0x00,
0x07, 0x00, 'L', 'i', 'c', 'e', 'n', 's',
'e', 0x00, 0x00, 0x00, '!', 0x00, 'P', 'u',
't', ' ', 'y', 'o', 'u', 'r', ' ', 'l',
'i', 'c', 'e', 'n', 's', 'e', ' ', 'i',
'n', 'f', 'o', 'r', 'm', 'a', 't', 'i',
'o', 'n', ' ', 'h', 'e', 'r', 'e', 0x00,
0x1b, 0x1c, 0x00, 0x00, 0x0b, 0x00, 'D', 'e',
's', 'c', 'r', 'i', 'p', 't', 'i', 'o',
'n', 0x00, 0x00, 0x00, '+', 0x00, 'P', 'u',
't', ' ', 'a', ' ', 's', 'h', 'o', 'r',
't', ' ', 'd', 'e', 's', 'c', 'r', 'i',
'p', 't', 'i', 'o', 'n', ' ', 'o', 'f',
' ', 'y', 'o', 'u', 'r', ' ', 'p', 'l',
'u', 'g', 'i', 'n', ' ', 'h', 'e', 'r',
'e', 0x00, 0x00, 0x00, 0x9b, '#', 0x00, 0x00,
0x03, 0x00, 'U', 'r', 'l', 0x00, 0x00, 0x00,
0x18, 0x00, 'h', 't', 't', 'p', ':', '/',
'/', 'w', 'w', 'w', '.', 'm', 'y', 'c',
'o', 'm', 'p', 'a', 'n', 'y', '.', 'c',
'o', 'm', 0x00, 0x00, 0x94, ')', 0x00, 0x00,
0x0c, 0x00, 'D', 'e', 'p', 'e', 'n', 'd',
'e', 'n', 'c', 'i', 'e', 's', 0x00, 0x00,
'P', 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
'L', 0x00, 0x00, 0x00, '@', 0x00, 0x00, 0x00,
0x05, 0x00, 0x00, 0x00, '8', 0x00, 0x00, 0x00,
0x1b, 0x03, 0x00, 0x00, 0x04, 0x00, 'N', 'a',
'm', 'e', 0x00, 0x00, 0x04, 0x00, 'C', 'o',
'r', 'e', 0x00, 0x00, 0x1b, 0x06, 0x00, 0x00,
0x07, 0x00, 'V', 'e', 'r', 's', 'i', 'o',
'n', 0x00, 0x00, 0x00, 0x05, 0x00, '4', '.',
'0', '.', '0', 0x00, 0x0c, 0x00, 0x00, 0x00,
' ', 0x00, 0x00, 0x00, 0x85, 0x01, 0x00, 0x00,
'@', 0x00, 0x00, 0x00, 'l', 0x00, 0x00, 0x00,
'8', 0x01, 0x00, 0x00, 0xcc, 0x00, 0x00, 0x00,
0x98, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x10, 0x01, 0x00, 0x00, '\\', 0x00, 0x00, 0x00,
'(', 0x00, 0x00, 0x00, 0x9b, 'C', 0x00, 0x00,
0x09, 0x00, 'c', 'l', 'a', 's', 's', 'N',
'a', 'm', 'e', 0x00, 0x12, 0x00, 'Q', 'T',
'a', 'n', 'g', 'o', 'W', 'i', 'd', 'g',
'e', 't', 'P', 'l', 'u', 'g', 'i', 'n',
'1', 0x00, 0x00, 0x00, 0x05, 0x00, 'd', 'e',
'b', 'u', 'g', 0x00, 0x1a, 0xc0, 0xa0, 0x00,
0x07, 0x00, 'v', 'e', 'r', 's', 'i', 'o',
'n', 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
'<', 0x00, 0x00, 0x00, 0x0c, 0x02, 0x00, 0x00,
'0', 0x02, 0x00, 0x00, '<', 0x02, 0x00, 0x00
};
#endif // QT_NO_DEBUG
using namespace QTangoWidget;
using namespace QTangoWidget::Internal;
QT_MOC_EXPORT_PLUGIN(QTangoWidget::Internal::QTangoWidgetPlugin, QTangoWidgetPlugin)
QT_END_MOC_NAMESPACE
| [
"delleceste@gmail.com"
] | delleceste@gmail.com |
627d665628859681890fb70404dd91a61a81ac45 | dfcff435ba01cea22e25ede2312d6223bf3ef389 | /src/ConEmuHk/hkCmdExe.cpp | e395a5bcdcd327f3af2e0db107a6496c932e91ed | [
"BSD-3-Clause"
] | permissive | shubham-theway/ConEmu | 79ee4d221f05558b87d970adaa47363fdcd51822 | 0cbba13abc7884e2af71c5feefd2295e39362d75 | refs/heads/master | 2021-01-22T02:40:27.766328 | 2018-10-17T20:36:40 | 2018-10-17T20:36:40 | 102,248,837 | 0 | 0 | null | 2017-09-03T07:41:41 | 2017-09-03T07:41:41 | null | UTF-8 | C++ | false | false | 8,917 | cpp |
/*
Copyright (c) 2015-2017 Maximus5
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#define HIDE_USE_EXCEPTION_INFO
#ifdef _DEBUG
#define DebugString(x) //OutputDebugString(x)
#else
#define DebugString(x) //OutputDebugString(x)
#endif
#include "../common/Common.h"
#include "hkCmdExe.h"
#include "hlpProcess.h"
/* **************** */
static wchar_t* gszClinkCmdLine = NULL;
/* **************** */
static bool InitializeClink()
{
if (gnCmdInitialized)
return true;
gnCmdInitialized = 1; // Single
//if (!gnAllowClinkUsage)
// return false;
CESERVER_CONSOLE_MAPPING_HDR* pConMap = GetConMap();
if (!pConMap /*|| !(pConMap->Flags & CECF_UseClink_Any)*/)
{
//gnAllowClinkUsage = 0;
gnCmdInitialized = -1;
return false;
}
// Запомнить режим
//gnAllowClinkUsage =
// (pConMap->Flags & CECF_UseClink_2) ? 2 :
// (pConMap->Flags & CECF_UseClink_1) ? 1 :
// CECF_Empty;
gbAllowClinkUsage = ((pConMap->Flags & CECF_UseClink_Any) != 0);
gbAllowUncPaths = (pConMap->ComSpec.isAllowUncPaths != FALSE);
if (gbAllowClinkUsage)
{
wchar_t szClinkBat[MAX_PATH+32];
wcscpy_c(szClinkBat, pConMap->ComSpec.ConEmuBaseDir);
wcscat_c(szClinkBat, L"\\clink\\clink.bat");
if (!FileExists(szClinkBat))
{
gbAllowClinkUsage = false;
}
else
{
int iLen = lstrlen(szClinkBat) + 16;
gszClinkCmdLine = (wchar_t*)malloc(iLen*sizeof(*gszClinkCmdLine));
if (gszClinkCmdLine)
{
*gszClinkCmdLine = L'"';
_wcscpy_c(gszClinkCmdLine+1, iLen-1, szClinkBat);
_wcscat_c(gszClinkCmdLine, iLen, L"\" inject");
}
}
}
return true;
//BOOL bRunRc = FALSE;
//DWORD nErrCode = 0;
//if (gnAllowClinkUsage == 2)
//{
// // New style. TODO
// wchar_t szClinkDir[MAX_PATH+32], szClinkArgs[MAX_PATH+64];
// wcscpy_c(szClinkDir, pConMap->ComSpec.ConEmuBaseDir);
// wcscat_c(szClinkDir, L"\\clink");
// wcscpy_c(szClinkArgs, L"\"");
// wcscat_c(szClinkArgs, szClinkDir);
// wcscat_c(szClinkArgs, WIN3264TEST(L"\\clink_x86.exe",L"\\clink_x64.exe"));
// wcscat_c(szClinkArgs, L"\" inject");
// STARTUPINFO si = {sizeof(si)};
// PROCESS_INFORMATION pi = {};
// bRunRc = CreateProcess(NULL, szClinkArgs, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, szClinkDir, &si, &pi);
//
// if (bRunRc)
// {
// WaitForSingleObject(pi.hProcess, INFINITE);
// CloseHandle(pi.hProcess);
// CloseHandle(pi.hThread);
// }
// else
// {
// nErrCode = GetLastError();
// _ASSERTEX(FALSE && "Clink loader failed");
// UNREFERENCED_PARAMETER(nErrCode);
// UNREFERENCED_PARAMETER(bRunRc);
// }
//}
//else if (gnAllowClinkUsage == 1)
//{
// if (!ghClinkDll)
// {
// wchar_t szClinkModule[MAX_PATH+30];
// _wsprintf(szClinkModule, SKIPLEN(countof(szClinkModule)) L"%s\\clink\\%s",
// pConMap->ComSpec.ConEmuBaseDir, WIN3264TEST(L"clink_dll_x86.dll",L"clink_dll_x64.dll"));
//
// ghClinkDll = LoadLibrary(szClinkModule);
// if (!ghClinkDll)
// return false;
// }
// if (!gpfnClinkReadLine)
// {
// gpfnClinkReadLine = (call_readline_t)GetProcAddress(ghClinkDll, "call_readline");
// _ASSERTEX(gpfnClinkReadLine!=NULL);
// }
//}
//return (gpfnClinkReadLine != NULL);
}
static bool IsInteractive()
{
const wchar_t* const cmdLine = ::GetCommandLineW();
if (!cmdLine)
{
return true; // can't know - assume it is
}
const wchar_t* pos = cmdLine;
while ((pos = wcschr(pos, L'/')) != NULL)
{
switch (pos[1])
{
case L'K': case L'k':
return true; // /k - execute and remain working
case L'C': case L'c':
return false; // /c - execute and exit
}
++pos;
}
return true;
}
bool IsClinkLoaded()
{
// Check processes supported
if (!gbIsCmdProcess && !gbIsPowerShellProcess)
return false;
// Check, if clink library is loaded
HMODULE hClink = GetModuleHandle(WIN3264TEST(L"clink_dll_x86.dll", L"clink_dll_x64.dll"));
return (hClink != NULL);
}
/* **************** */
// cmd.exe only!
LONG WINAPI OnRegQueryValueExW(HKEY hKey, LPCWSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData)
{
//typedef LONG (WINAPI* OnRegQueryValueExW_t)(HKEY hKey, LPCWSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData);
ORIGINAL_EX(RegQueryValueExW);
LONG lRc = -1;
if (gbIsCmdProcess && hKey && lpValueName)
{
// Allow `CD` to network paths
if (lstrcmpi(lpValueName, L"DisableUNCCheck") == 0)
{
if (lpData)
{
if (lpcbData && *lpcbData >= sizeof(DWORD))
*((LPDWORD)lpData) = gbAllowUncPaths;
else
*lpData = gbAllowUncPaths;
}
if (lpType)
*lpType = REG_DWORD;
if (lpcbData)
*lpcbData = sizeof(DWORD);
lRc = 0;
goto wrap;
}
if (gbIsCmdProcess && hKey && lpValueName
&& (lstrcmpi(lpValueName, L"AutoRun") == 0)
&& InitializeClink())
{
if (gbAllowClinkUsage && gszClinkCmdLine
&& IsInteractive())
{
// Is already loaded?
if (!IsClinkLoaded()
&& !gbClinkInjectRequested)
{
// Do this once, to avoid multiple initializations
gbClinkInjectRequested = true;
// May be it is set up itself?
typedef LONG (WINAPI* RegOpenKeyEx_t)(HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult);
typedef LONG (WINAPI* RegCloseKey_t)(HKEY hKey);
HMODULE hAdvApi = LoadLibrary(L"AdvApi32.dll");
if (hAdvApi)
{
RegOpenKeyEx_t _RegOpenKeyEx = (RegOpenKeyEx_t)GetProcAddress(hAdvApi, "RegOpenKeyExW");
RegCloseKey_t _RegCloseKey = (RegCloseKey_t)GetProcAddress(hAdvApi, "RegCloseKey");
if (_RegOpenKeyEx && _RegCloseKey)
{
const DWORD cchMax = 0x3FF0;
const DWORD cbMax = cchMax*2;
wchar_t* pszCmd = (wchar_t*)malloc(cbMax);
if (pszCmd)
{
DWORD cbSize;
bool bClinkInstalled = false;
for (int i = 0; i <= 1 && !bClinkInstalled; i++)
{
HKEY hk;
if (_RegOpenKeyEx(i?HKEY_LOCAL_MACHINE:HKEY_CURRENT_USER, L"Software\\Microsoft\\Command Processor", 0, KEY_READ, &hk))
continue;
if (!F(RegQueryValueExW)(hk, lpValueName, NULL, NULL, (LPBYTE)pszCmd, &(cbSize = cbMax))
&& (cbSize+2) < cbMax)
{
cbSize /= 2; pszCmd[cbSize] = 0;
CharLowerBuffW(pszCmd, cbSize);
if (wcsstr(pszCmd, L"\\clink.bat"))
bClinkInstalled = true;
}
_RegCloseKey(hk);
}
// Not installed via "Autorun"
if (!bClinkInstalled)
{
int iLen = lstrlen(gszClinkCmdLine);
_wcscpy_c(pszCmd, cchMax, gszClinkCmdLine);
_wcscpy_c(pszCmd+iLen, cchMax-iLen, L" & "); // conveyer next command indifferent to %errorlevel%
cbSize = cbMax - (iLen + 3)*sizeof(*pszCmd);
if (F(RegQueryValueExW)(hKey, lpValueName, NULL, NULL, (LPBYTE)(pszCmd + iLen + 3), &cbSize)
|| (pszCmd[iLen+3] == 0))
{
pszCmd[iLen] = 0; // There is no self value in registry
}
cbSize = (lstrlen(pszCmd)+1)*sizeof(*pszCmd);
// Return
lRc = 0;
if (lpData && lpcbData)
{
if (*lpcbData < cbSize)
lRc = ERROR_MORE_DATA;
else
_wcscpy_c((wchar_t*)lpData, (*lpcbData)/2, pszCmd);
}
if (lpcbData)
*lpcbData = cbSize;
free(pszCmd);
FreeLibrary(hAdvApi);
goto wrap;
}
free(pszCmd);
}
}
FreeLibrary(hAdvApi);
}
}
}
}
}
if (F(RegQueryValueExW))
lRc = F(RegQueryValueExW)(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData);
wrap:
return lRc;
}
/* **************** */
| [
"ConEmu.Maximus5@gmail.com"
] | ConEmu.Maximus5@gmail.com |
2ae347c7abe0db76730d9535ca9c5a26ec8504e4 | 394a279fc8b82f3e7e980698023f84bdab30beb9 | /src/rpcrawtransaction.cpp | 4d1199f6b6da2d6f09aacab038dfc152f0ef210e | [
"MIT"
] | permissive | hocf/h1 | d9dd886908776f6f6cdd7116a464ce9fbbc54d66 | 36ed792a0507f415e98cd2c9d3b1b6e3562571bf | refs/heads/master | 2020-07-21T02:42:37.129061 | 2016-11-14T21:16:27 | 2016-11-14T21:16:27 | 73,740,920 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 21,050 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The HuobiCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include "base58.h"
#include "bitcoinrpc.h"
#include "db.h"
#include "init.h"
#include "net.h"
#include "wallet.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
//
// Utilities: convert hex-encoded Values
// (throws error if not hex).
//
uint256 ParseHashV(const Value& v, string strName)
{
string strHex;
if (v.type() == str_type)
strHex = v.get_str();
if (!IsHex(strHex)) // Note: IsHex("") is false
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
uint256 result;
result.SetHex(strHex);
return result;
}
uint256 ParseHashO(const Object& o, string strKey)
{
return ParseHashV(find_value(o, strKey), strKey);
}
vector<unsigned char> ParseHexV(const Value& v, string strName)
{
string strHex;
if (v.type() == str_type)
strHex = v.get_str();
if (!IsHex(strHex))
throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')");
return ParseHex(strHex);
}
vector<unsigned char> ParseHexO(const Object& o, string strKey)
{
return ParseHexV(find_value(o, strKey), strKey);
}
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", scriptPubKey.ToString()));
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))
{
out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
{
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime));
Array vin;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
Object in;
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else
{
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n));
Object o;
o.push_back(Pair("asm", txin.scriptSig.ToString()));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
}
in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
Array vout;
for (unsigned int i = 0; i < tx.vout.size(); i++)
{
const CTxOut& txout = tx.vout[i];
Object out;
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("n", (boost::int64_t)i));
Object o;
ScriptPubKeyToJSON(txout.scriptPubKey, o);
out.push_back(Pair("scriptPubKey", o));
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (hashBlock != 0)
{
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
{
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
entry.push_back(Pair("time", (boost::int64_t)pindex->nTime));
entry.push_back(Pair("blocktime", (boost::int64_t)pindex->nTime));
}
else
entry.push_back(Pair("confirmations", 0));
}
}
}
Value getrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction <txid> [verbose=0]\n"
"If verbose=0, returns a string that is\n"
"serialized, hex-encoded data for <txid>.\n"
"If verbose is non-zero, returns an Object\n"
"with information about <txid>.");
uint256 hash = ParseHashV(params[0], "parameter 1");
bool fVerbose = false;
if (params.size() > 1)
fVerbose = (params[1].get_int() != 0);
CTransaction tx;
uint256 hashBlock = 0;
if (!GetTransaction(hash, tx, hashBlock, true))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
string strHex = HexStr(ssTx.begin(), ssTx.end());
if (!fVerbose)
return strHex;
Object result;
result.push_back(Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
Value listunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n"
"Returns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filtered to only include txouts paid to specified addresses.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}");
RPCTypeCheck(params, list_of(int_type)(int_type)(array_type));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
set<CBitcoinAddress> setAddress;
if (params.size() > 2)
{
Array inputs = params[2].get_array();
BOOST_FOREACH(Value& input, inputs)
{
CBitcoinAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid HuobiCoin address: ")+input.get_str());
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str());
setAddress.insert(address);
}
}
Array results;
vector<COutput> vecOutputs;
pwalletMain->AvailableCoins(vecOutputs, false);
BOOST_FOREACH(const COutput& out, vecOutputs)
{
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
if (setAddress.size())
{
CTxDestination address;
if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
if (!setAddress.count(address))
continue;
}
int64 nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
Object entry;
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
CTxDestination address;
if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
{
entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
if (pwalletMain->mapAddressBook.count(address))
entry.push_back(Pair("account", pwalletMain->mapAddressBook[address]));
}
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
if (pk.IsPayToScriptHash())
{
CTxDestination address;
if (ExtractDestination(pk, address))
{
const CScriptID& hash = boost::get<const CScriptID&>(address);
CScript redeemScript;
if (pwalletMain->GetCScript(hash, redeemScript))
entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
}
}
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations",out.nDepth));
results.push_back(entry);
}
return results;
}
Value createrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n"
"Create a transaction spending given inputs\n"
"(array of objects containing transaction id and output number),\n"
"sending to given address(es).\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.");
RPCTypeCheck(params, list_of(array_type)(obj_type));
Array inputs = params[0].get_array();
Object sendTo = params[1].get_obj();
CTransaction rawTx;
BOOST_FOREACH(const Value& input, inputs)
{
const Object& o = input.get_obj();
uint256 txid = ParseHashO(o, "txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
CTxIn in(COutPoint(txid, nOutput));
rawTx.vin.push_back(in);
}
set<CBitcoinAddress> setAddress;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid HuobiCoin address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64 nAmount = AmountFromValue(s.value_);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << rawTx;
return HexStr(ss.begin(), ss.end());
}
Value decoderawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction <hex string>\n"
"Return a JSON object representing the serialized, hex-encoded transaction.");
vector<unsigned char> txData(ParseHexV(params[0], "argument"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
Object result;
TxToJSON(tx, 0, result);
return result;
}
Value signrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex,\"redeemScript\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n"
"Sign inputs for raw transaction (serialized, hex-encoded).\n"
"Second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the block chain.\n"
"Third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
"Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n"
"ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n"
"Returns json object with keys:\n"
" hex : raw transaction with signature(s) (hex-encoded string)\n"
" complete : 1 if transaction has a complete set of signature (0 if not)"
+ HelpRequiringPassphrase());
RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true);
vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CTransaction> txVariants;
while (!ssData.empty())
{
try {
CTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CTransaction mergedTx(txVariants[0]);
bool fComplete = true;
// Fetch previous transactions (inputs):
CCoinsView viewDummy;
CCoinsViewCache view(viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache &viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {
const uint256& prevHash = txin.prevout.hash;
CCoins coins;
view.GetCoins(prevHash, coins); // this is certainly allowed to fail
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && params[2].type() != null_type)
{
fGivenKeys = true;
Array keys = params[2].get_array();
BOOST_FOREACH(Value k, keys)
{
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
tempKeystore.AddKey(key);
}
}
else
EnsureWalletIsUnlocked();
// Add previous txouts given in the RPC call:
if (params.size() > 1 && params[1].type() != null_type)
{
Array prevTxs = params[1].get_array();
BOOST_FOREACH(Value& p, prevTxs)
{
if (p.type() != obj_type)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
Object prevOut = p.get_obj();
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type));
uint256 txid = ParseHashO(prevOut, "txid");
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
CScript scriptPubKey(pkData.begin(), pkData.end());
CCoins coins;
if (view.GetCoins(txid, coins)) {
if (coins.IsAvailable(nOut) && coins.vout[nOut].scriptPubKey != scriptPubKey) {
string err("Previous output scriptPubKey mismatch:\n");
err = err + coins.vout[nOut].scriptPubKey.ToString() + "\nvs:\n"+
scriptPubKey.ToString();
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
// what todo if txid is known, but the actual output isn't?
}
if ((unsigned int)nOut >= coins.vout.size())
coins.vout.resize(nOut+1);
coins.vout[nOut].scriptPubKey = scriptPubKey;
coins.vout[nOut].nValue = 0; // we don't know the actual output value
view.SetCoins(txid, coins);
// if redeemScript given and not using the local wallet (private keys
// given), add redeemScript to the tempKeystore so it can be signed:
if (fGivenKeys && scriptPubKey.IsPayToScriptHash())
{
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)("redeemScript",str_type));
Value v = find_value(prevOut, "redeemScript");
if (!(v == Value::null))
{
vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
CScript redeemScript(rsData.begin(), rsData.end());
tempKeystore.AddCScript(redeemScript);
}
}
}
}
const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain);
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && params[3].type() != null_type)
{
static map<string, int> mapSigHashValues =
boost::assign::map_list_of
(string("ALL"), int(SIGHASH_ALL))
(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
(string("NONE"), int(SIGHASH_NONE))
(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
(string("SINGLE"), int(SIGHASH_SINGLE))
(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
;
string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
{
CTxIn& txin = mergedTx.vin[i];
CCoins coins;
if (!view.GetCoins(txin.prevout.hash, coins) || !coins.IsAvailable(txin.prevout.n))
{
fComplete = false;
continue;
}
const CScript& prevPubKey = coins.vout[txin.prevout.n].scriptPubKey;
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH(const CTransaction& txv, txVariants)
{
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, 0))
fComplete = false;
}
Object result;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << mergedTx;
result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end())));
result.push_back(Pair("complete", fComplete));
return result;
}
Value sendrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"sendrawtransaction <hex string>\n"
"Submits raw transaction (serialized, hex-encoded) to local node and network.");
// parse hex string from parameter
vector<unsigned char> txData(ParseHexV(params[0], "parameter"));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
// deserialize binary data stream
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
uint256 hashTx = tx.GetHash();
bool fHave = false;
CCoinsViewCache &view = *pcoinsTip;
CCoins existingCoins;
{
fHave = view.GetCoins(hashTx, existingCoins);
if (!fHave) {
// push to local node
CValidationState state;
if (!mempool.accept(state, tx, false, NULL))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX rejected"); // TODO: report validation state
}
}
if (fHave) {
if (existingCoins.nHeight < 1000000000)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "transaction already in block chain");
// Not in block, but already in the memory pool; will drop
// through to re-relay it.
} else {
SyncWithWallets(hashTx, tx, NULL, true);
}
RelayTransaction(tx, hashTx);
return hashTx.GetHex();
}
| [
"empowrcoin@gmail.com"
] | empowrcoin@gmail.com |
ad65b2a3bcc972ecbaf524314b12bd73db159bdf | 7f2f3aaf69fafde86eb4d552edb7cee1bd3bf6c2 | /include/registration.h | 25be92278629b77e8cb81b9f9e9efdde338466b1 | [] | no_license | liudaqikk/CMBNB-demo | a0804aa3b4a87813d9d467d396de8fac89582d06 | ed290323c0e377f1098013ee297bf87ab79625f2 | refs/heads/master | 2021-04-01T03:28:40.915439 | 2020-05-21T08:57:15 | 2020-05-21T08:57:15 | 248,152,765 | 22 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 4,459 | h | /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CONTRAST MAXIMISATION BRANCH AND BOUND
%
%
% This package contains the source code which implements the
% Contrast maximisation BnB algorithm (CMBnB) in
%
% Globally Optimal Contrast Maximisation for Event-based
% Motion Estimation
%
% The source code, binaries and demo are supplied for academic use only.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#ifndef REG_REG_SEARCH_
#define REG_REG_SEARCH_
#include "reg_common.h"
#include "state.h"
using namespace Eigen;
//TODO: split accordig to papers.
namespace reg {
namespace search {
//--------------------------------------------------------------------------
// Rotation search
//--------------------------------------------------------------------------
// on points
int bnb_rsearch_3dof_mcirc(const MatrixXd &X, const Matrix3X &Y, double th,
int gap, int lwbnd, int buckets,
AxisAngle &result);
//rot3_ml
int bnb_rsearch_3dof_mcirc_ml(const Matrix3X &X, const Matrix3X &Y, double th,
int gap, int lwbnd, int buckets,
AxisAngle &result);
// on matches
// ang distance
int rot3_matches(const MatrixXd &X, VectorXd &lowerB, VectorXd &upperB, MatrixXd &ray,
const MatrixXd MK, AxisAngle &result);
int rot3_matches_ml(const Matrix3X &X, const Matrix3X &Y, double th,
int gap, int lwbnd, AxisAngle &result);
// l2 distance
int rot3_matches_l2(const Matrix3X &X, const Matrix3X &Y, double th,
int lwbnd, int gap, AxisAngle &result);
int rot3_matches_l2_ml(const Matrix3X &X, const Matrix3X &Y, double th,
int lwbnd,int gap, AxisAngle &result);
int rot1_matches_l2(const Matrix3X &X, const Matrix3X &Y, double th,
int lwbnd, int gap, double &result);
int rot1_matches_l2_ml(const Matrix3X &X, const Matrix3X &Y, double th,
int lwbnd, int gap, double &result);
// minmax
double rot3minmax(const Matrix3X &X, const Matrix3X &Y, double gap, AxisAngle &result);
//--------------------------------------------------------------------------
// Registration
//--------------------------------------------------------------------------
// 6 DoF with matches
int reg6Matches(const Matrix3X &X, const Matrix3X &Y, double th,
int lwbnd, int gap, Transform3 &guessAndResult);
int reg4Matches(const Matrix3X &X, const Matrix3X &Y, double th,
int lwbnd, int gap, Transform3 &guessAndResult);
// Nested (6DoF)
int nestedbnb_search_6dof_mcirc(const Matrix3X &X, const Matrix3X &Y, double th,
int gap, int lwbnd,
TranslationSearchSpaceRegion3DOF &trDom,
int(*bnb_rsearch_3dof)(const Matrix3X&, const Matrix3X&,
double,int, int, int, AxisAngle&),
Transform3 &guessAndResult,
bool use_local_opt);
int nestedbnb_search_6dof_mcirc_ml(const Matrix3X &X, const Matrix3X &Y, double th,
int gap, int lwbnd,
TranslationSearchSpaceRegion3DOF &trDom,
Transform3 &guessAndResult,
bool use_local_opt);
// Local (6DoF)
int local_search_6dof(const Matrix3X &X, const Matrix3X &Y, double th,
int lwbnd,
TranslationSearchSpaceRegion3DOF trDom,
int(*bnb_rsearch_3dof)(const Matrix3X&, const Matrix3X&,
double,int, int, int, AxisAngle&),
Transform3 &guessAndResult);
} // End namespace sarch
} // End namespace reg
#endif
| [
"liudaqikk@gmail.co"
] | liudaqikk@gmail.co |
4bca35ae8eeda270194739fb7d10a7ef2a3a7f84 | 6db48755994469ce04f2029b77f8c9e799e792a7 | /8. Наследование. Функциональный калькулятор/Проект №1(Общая версия)/Pow.h | bd35ef08f880678d021f610c1f61ace73b770296 | [] | no_license | walleri18/Consol-Program-TK | 8c4fe43d2c06793f1a0f261511c881e1aa1c9199 | d418ab3657299db80f9d9e88d11b6973c5476552 | refs/heads/master | 2021-01-10T01:34:58.107084 | 2016-01-16T21:42:45 | 2016-01-16T21:42:45 | 49,791,087 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 654 | h | #pragma once
#include "CalculateFunction.h"
class Pow :
public CalculateFunction
{
// Данные
private:
double argument;// Аргумент
double step;// Возводимая степень
double result;// Результат возведения в степень
// Функции (методы)
public:
Pow(); // Конструктор без параметров
~Pow();// Деструктор без параметров
char *getName();// Геттер имени
void show();// Вывод результата
private:
void setArgument();// Сеттер аргумента и степени
void calculate();// Расчёт
};
| [
"walleri18@yandex.ru"
] | walleri18@yandex.ru |
0ec0dcc1f2a9c6628e0fdd6713b8359a5fd1fadb | edc6a5865ac97a2cc96b1ccced9494bf49b1b887 | /sources/source/appsystemgroup.cpp | 12fb3e660a2cbea4f4c7a73fdd2dcb0d5a95bc15 | [
"MIT"
] | permissive | vocweb/cso2-launcher | da0dd381a10a592390426b871b2eff485e5f73c9 | abc144acaa3dfb5b0c9acd61cd75970cac012617 | refs/heads/master | 2021-06-27T19:05:48.665744 | 2020-11-07T16:22:44 | 2020-11-07T16:22:44 | 182,375,440 | 0 | 0 | MIT | 2020-11-07T16:22:45 | 2019-04-20T07:32:45 | C++ | UTF-8 | C++ | false | false | 405 | cpp | #include "source/appsystemgroup.hpp"
CAppSystemGroup::CAppSystemGroup(
const std::vector<AppSystemData>& realSystems )
: m_SystemDict()
{
for ( auto&& system : realSystems )
{
int newIndex = this->m_Systems.AddToTail( system.pSystem );
this->m_SystemDict.Insert( system.szName.c_str(), newIndex );
}
this->m_pParentAppSystem = nullptr;
m_nErrorStage = NONE;
} | [
"luis@leite.xyz"
] | luis@leite.xyz |
66aeb258c08a5879a28776b661acd1369ba54feb | f041209e795ec1bad5f88c5e5aaca6c94a9a01fc | /exercise_10.13/exercise_10.13.cpp | 5f16e6d135a4e03b8c530061861c76bac93154bf | [] | no_license | Pt0lemaeus/C-Primer5Edition | 8ba6f26684e2ba2c0a774596f4cbc411bf3d8f41 | 7f21707d343eccc77cdb6be19782ebeba3264f30 | refs/heads/master | 2021-01-01T05:22:20.033801 | 2016-04-14T15:00:13 | 2016-04-14T15:00:13 | 56,126,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 600 | cpp | // exercise_10.13.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
bool isShorter5(const string&);
int main()
{
string s;
vector<string> vs;
while (cin >> s)
{
vs.push_back(s);
}
auto p = partition(vs.begin(), vs.end(), isShorter5);
vs.erase(p, vs.end());
for (auto s : vs)
{
cout << s << endl;
}
return 0;
}
bool isShorter5(const string &s)
{
return s.size() < 5;
return false;
}
| [
"tuxiaomi@gmail.com"
] | tuxiaomi@gmail.com |
222b2216abce8de16dc697f051222d47eb7ac4eb | f3b5c4a5ce869dee94c3dfa8d110bab1b4be698b | /controller/src/ifmap/ifmap_agent_table.cc | 3585f993d49d85aa91d86836302299fdf86fd768 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | pan2za/ctrl | 8f808fb4da117fce346ff3d54f80b4e3d6b86b52 | 1d49df03ec4577b014b7d7ef2557d76e795f6a1c | refs/heads/master | 2021-01-22T23:16:48.002959 | 2015-06-17T06:13:36 | 2015-06-17T06:13:36 | 37,454,161 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,264 | cc | /*
* Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
*/
#include "ifmap/ifmap_agent_table.h"
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
#include <boost/format.hpp>
#include "base/logging.h"
#include "db/db.h"
#include "db/db_graph.h"
#include "db/db_table_partition.h"
#include "ifmap/ifmap_agent_table.h"
#include "ifmap/ifmap_agent_parser.h"
#include "ifmap/ifmap_link_table.h"
#include "ifmap/ifmap_node.h"
#include "ifmap/ifmap_link.h"
#include "sandesh/sandesh.h"
#include "sandesh/sandesh_types.h"
#include "ifmap/ifmap_agent_types.h"
using namespace std;
SandeshTraceBufferPtr
IFMapAgentTraceBuf(SandeshTraceBufferCreate("IFMapAgentTrace", 1000));
IFMapAgentTable::IFMapAgentTable(DB *db, const string &name, DBGraph *graph)
: IFMapTable(db, name), graph_(graph), pre_filter_(NULL) {
}
auto_ptr<DBEntry> IFMapAgentTable::AllocEntry(const DBRequestKey *key) const {
auto_ptr<DBEntry> entry(
new IFMapNode(const_cast<IFMapAgentTable *>(this)));
entry->SetKey(key);
return entry;
}
IFMapNode* IFMapAgentTable::TableEntryLookup(DB *db, RequestKey *key) {
IFMapTable *table = FindTable(db, key->id_type);
if (!table) {
return NULL;
}
auto_ptr<DBEntry> entry(new IFMapNode(table));
entry->SetKey(key);
IFMapNode *node = static_cast<IFMapNode *>(table->Find(entry.get()));
return node;
}
IFMapAgentTable* IFMapAgentTable::TableFind(const string &node_name) {
string name = node_name;
boost::replace_all(name, "-", "_");
name = "__ifmap__." + name + ".0";
IFMapAgentTable *table =
static_cast<IFMapAgentTable *>(database()->FindTable(name));
return table;
}
IFMapNode *IFMapAgentTable::EntryLookup(RequestKey *request) {
auto_ptr<DBEntry> key(AllocEntry(request));
IFMapNode *node = static_cast<IFMapNode *>(Find(key.get()));
return node;
}
IFMapNode *IFMapAgentTable::EntryLocate(IFMapNode *node, RequestKey *req) {
IFMapObject *obj;
if (node != NULL) {
/* If delete marked, clear it now */
if (node->IsDeleted()) {
node->ClearDelete();
graph_->AddNode(node);
}
obj = node->GetObject();
assert(obj);
node->Remove(obj);
} else {
auto_ptr<DBEntry> key(AllocEntry(req));
node = const_cast<IFMapNode *>(
static_cast<const IFMapNode *>(key.release()));
DBTablePartition *partition =
static_cast<DBTablePartition *>(GetTablePartition(0));
partition->Add(node);
graph_->AddNode(node);
}
return node;
}
// A node is deleted. Move all links for the node to defer-list
void IFMapAgentTable::HandlePendingLinks(IFMapNode *node) {
IFMapNode *right;
DBGraphEdge *edge;
IFMapAgentLinkTable *ltable = static_cast<IFMapAgentLinkTable *>
(database()->FindTable(IFMAP_AGENT_LINK_DB_NAME));
assert(ltable != NULL);
DBGraphVertex::adjacency_iterator iter;
for (iter = node->begin(graph_); iter != node->end(graph_);) {
right = static_cast<IFMapNode *>(iter.operator->());
iter++;
edge = graph_->GetEdge(node, right);
assert(edge);
IFMapLink *l = static_cast<IFMapLink *>(edge);
// Create both the request keys
auto_ptr <IFMapAgentLinkTable::RequestKey> req_key (new IFMapAgentLinkTable::RequestKey);
req_key->left_key.id_name = node->name();
req_key->left_key.id_type = node->table()->Typename();
req_key->left_key.id_seq_num = node->GetObject()->sequence_number();
req_key->right_key.id_name = right->name();
req_key->right_key.id_type = right->table()->Typename();
req_key->right_key.id_seq_num = right->GetObject()->sequence_number();
req_key->metadata = l->metadata();
DBRequest req;
req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
req.key = req_key;
//Add it to defer list
ltable->LinkDefAdd(&req);
ltable->DelLink(node, right, edge);
}
}
void IFMapAgentTable::DeleteNode(IFMapNode *node) {
if ((node->HasAdjacencies(graph_) == true)) {
HandlePendingLinks(node);
}
//Now there should not be any more adjacencies
assert((node->HasAdjacencies(graph_) == false));
DBTablePartition *partition =
static_cast<DBTablePartition *>(GetTablePartition(0));
graph_->RemoveNode(node);
partition->Delete(node);
}
void IFMapAgentTable::NotifyNode(IFMapNode *node) {
DBTablePartition *partition =
static_cast<DBTablePartition *>(GetTablePartition(0));
partition->Change(node);
}
// Process link-defer list based for the request.
// If request is add, create left->right and right-left defer nodes
// If request is delete, remove left->right and right->left defer nodes
void IFMapAgentLinkTable::LinkDefAdd(DBRequest *request) {
RequestKey *key = static_cast<RequestKey *>(request->key.get());
std::list<DeferredNode>::iterator it;
std::list<DeferredNode> *left = NULL;
LinkDefMap::iterator left_it = link_def_map_.find(key->left_key);
if (link_def_map_.end() != left_it)
left = left_it->second;
std::list<DeferredNode> *right = NULL;
LinkDefMap::iterator right_it = link_def_map_.find(key->right_key);
if (link_def_map_.end() != right_it)
right = right_it->second;
if (request->oper == DBRequest::DB_ENTRY_DELETE) {
// remove left->right entry
if (left) {
for(it = left->begin(); it != left->end(); it++) {
if (((*it).node_key.id_type == key->right_key.id_type) &&
((*it).node_key.id_name == key->right_key.id_name)) {
left->erase(it);
break;
}
}
RemoveDefListEntry(&link_def_map_, left_it, NULL);
}
// remove right->left entry
if (right) {
for(it = right->begin(); it != right->end(); it++) {
if (((*it).node_key.id_type == key->left_key.id_type) &&
((*it).node_key.id_name == key->left_key.id_name)) {
right->erase(it);
break;
}
}
RemoveDefListEntry(&link_def_map_, right_it, NULL);
}
return;
}
bool push_left = true;
// Add/Update left->right entry
if (left) {
// If list already contains, just update the seq number
for(it = left->begin(); it != left->end(); it++) {
if (((*it).node_key.id_type == key->right_key.id_type) &&
((*it).node_key.id_name == key->right_key.id_name)) {
(*it).node_key.id_seq_num = key->right_key.id_seq_num;
(*it).link_metadata = key->metadata;
push_left = false;
break;
}
}
} else {
left = new std::list<DeferredNode>();
link_def_map_[key->left_key] = left;
}
bool push_right = true;
// Add/Update right->left entry
if (right) {
// If list already contains, just update the seq number
for(it = right->begin(); it != right->end(); it++) {
if (((*it).node_key.id_type == key->left_key.id_type) &&
((*it).node_key.id_name == key->left_key.id_name)) {
(*it).node_key.id_seq_num = key->left_key.id_seq_num;
(*it).link_metadata = key->metadata;
push_right = false;
break;
}
}
} else {
right = new std::list<DeferredNode>();
link_def_map_[key->right_key] = right;
}
// Add it to the end of the list
struct DeferredNode dn;
dn.link_metadata = key->metadata;
if (push_left) {
dn.node_key = key->right_key;
left->push_back(dn);
}
if (push_right) {
dn.node_key = key->left_key;
right->push_back(dn);
}
return;
}
void IFMapAgentTable::Input(DBTablePartition *partition, DBClient *client,
DBRequest *request) {
RequestKey *key = static_cast<RequestKey *>(request->key.get());
IFMapAgentTable *table = NULL;
struct IFMapAgentData *req_data;
IFMapObject *obj;
table = TableFind(key->id_type);
if (!table) {
IFMAP_AGENT_TRACE(Trace, key->id_seq_num,
"Table " + key->id_type + " not found");
return;
}
IFMapNode *node = EntryLookup(key);
if (table->pre_filter_) {
DBRequest::DBOperation old_oper = request->oper;
if (table->pre_filter_(table, node, request) == false) {
IFMAP_AGENT_TRACE(Trace, key->id_seq_num,
"Node " + key->id_name + " neglected as filter"
+ "suppressed");
return;
}
if ((old_oper != DBRequest::DB_ENTRY_DELETE) &&
(request->oper == DBRequest::DB_ENTRY_DELETE)) {
IFMAP_AGENT_TRACE(Trace, key->id_seq_num,
"Node " + key->id_name + "ID_PERMS Null");
}
}
if (request->oper == DBRequest::DB_ENTRY_DELETE) {
if (node == NULL) {
IFMAP_AGENT_TRACE(Trace, key->id_seq_num,
"Node " + key->id_name + " not found in Delete");
return;
}
if (node->IsDeleted()) {
IFMAP_AGENT_TRACE(Trace, key->id_seq_num,
"Node " + key->id_name + " already deleted");
return;
}
DeleteNode(node);
return;
}
node = EntryLocate(node, key);
assert(node);
//Get the data from request key and notify oper tables
req_data = static_cast<struct IFMapAgentData *>(request->data.get());
obj = static_cast<IFMapObject *>(req_data->content.release());
//Set the sequence number of the object
obj->set_sequence_number(key->id_seq_num);
node->Insert(obj);
NotifyNode(node);
IFMapAgentLinkTable *link_table = static_cast<IFMapAgentLinkTable *>(
database()->FindTable(IFMAP_AGENT_LINK_DB_NAME));
link_table->EvalDefLink(key);
}
void IFMapAgentTable::Clear() {
assert(!HasListeners());
DBTablePartition *partition = static_cast<DBTablePartition *>(
GetTablePartition(0));
IFMapNode *next = NULL;
for (IFMapNode *node = static_cast<IFMapNode *>(partition->GetFirst());
node != NULL; node = next) {
next = static_cast<IFMapNode *>(partition->GetNext(node));
if (node->IsDeleted()) {
continue;
}
graph_->RemoveNode(node);
partition->Delete(node);
}
}
// Agent link table routines
void IFMapAgentLinkTable::AddLink(DBGraphBase::edge_descriptor edge,
IFMapNode *left, IFMapNode *right,
const std::string &metadata,
uint64_t seq) {
IFMapLinkTable *table = static_cast<IFMapLinkTable *>(
database()->FindTable(IFMAP_AGENT_LINK_DB_NAME));
assert(table != NULL);
table->AddLink(edge, left, right, metadata, seq,
IFMapOrigin(IFMapOrigin::UNKNOWN));
}
void IFMapAgentLinkTable::DelLink(IFMapNode *left, IFMapNode *right, DBGraphEdge *edge) {
IFMapAgentLinkTable *table = static_cast<IFMapAgentLinkTable *>(
database()->FindTable(IFMAP_AGENT_LINK_DB_NAME));
assert(table != NULL);
table->DeleteLink(edge);
graph_->Unlink(left, right);
}
IFMapAgentLinkTable::IFMapAgentLinkTable(DB *db, const string &name, DBGraph *graph)
: IFMapLinkTable(db, name, graph), graph_(graph) {
}
DBTable *IFMapAgentLinkTable::CreateTable(DB *db, const string &name,
DBGraph *graph) {
IFMapAgentLinkTable *table = new IFMapAgentLinkTable(db, name, graph);
table->Init();
return table;
}
void IFMapAgentLinkTable_Init(DB *db, DBGraph *graph) {
db->RegisterFactory(IFMAP_AGENT_LINK_DB_NAME,
boost::bind(&IFMapAgentLinkTable::CreateTable, _1, _2, graph));
db->CreateTable(IFMAP_AGENT_LINK_DB_NAME);
}
void IFMapAgentLinkTable::Input(DBTablePartition *partition, DBClient *client,
DBRequest *req) {
RequestKey *key = static_cast<RequestKey *>(req->key.get());
IFMapNode *left;
left = IFMapAgentTable::TableEntryLookup(database(), &key->left_key);
if (!left) {
IFMAP_AGENT_TRACE(Trace, key->left_key.id_seq_num,
key->left_key.id_type + ":" + key->left_key.id_name +
" not present for link to " + key->right_key.id_type +
":" + key->right_key.id_name);
LinkDefAdd(req);
return;
}
IFMapNode *right;
right = IFMapAgentTable::TableEntryLookup(database(), &key->right_key);
if (!right) {
IFMAP_AGENT_TRACE(Trace, key->left_key.id_seq_num,
key->right_key.id_type + " : " + key->right_key.id_name +
" not present for link to " + key->left_key.id_type + " : " +
key->left_key.id_name);
LinkDefAdd(req);
return;
}
if (left->IsDeleted()) {
IFMAP_AGENT_TRACE(Trace, key->left_key.id_seq_num,
"Adding Link" + key->left_key.id_type + ":" +
key->left_key.id_name + "->" + key->right_key.id_type +
":" + key->right_key.id_name + " to defer "
"list as left is deleted marked");
LinkDefAdd(req);
return;
}
if (right->IsDeleted()) {
IFMAP_AGENT_TRACE(Trace, key->left_key.id_seq_num,
"Adding Link" + key->left_key.id_type + ":" +
key->left_key.id_name + "->" + key->right_key.id_type +
":" + key->right_key.id_name + " to defer "
"list as right is deleted marked");
LinkDefAdd(req);
return;
}
IFMapObject *obj = left->GetObject();
if (obj->sequence_number() < key->left_key.id_seq_num) {
IFMAP_AGENT_TRACE(Trace, key->left_key.id_seq_num,
"IFMap Link " + left->name() + right->name() +
" with wrong seq number");
LinkDefAdd(req);
return;
}
obj = right->GetObject();
if (obj->sequence_number() < key->left_key.id_seq_num) {
IFMAP_AGENT_TRACE(Trace, key->left_key.id_seq_num,
"IFMap Link " + left->name() + right->name() +
" with wrong seq number");
LinkDefAdd(req);
return;
}
DBGraph::Edge edge;
DBGraphEdge *link = graph_->GetEdge(left, right);
if (req->oper == DBRequest::DB_ENTRY_ADD_CHANGE) {
if (link == NULL) {
edge = graph_->Link(left, right);
AddLink(edge, left, right, key->metadata, key->left_key.id_seq_num);
} else {
IFMapOrigin origin(IFMapOrigin::UNKNOWN);
IFMapLink *l = static_cast<IFMapLink *>(link);
l->UpdateProperties(origin, key->left_key.id_seq_num);
}
} else {
if (link == NULL) {
return;
}
DelLink(left, right, link);
}
}
bool IFMapAgentLinkTable::RemoveDefListEntry
(LinkDefMap *map, LinkDefMap::iterator &map_it,
std::list<DeferredNode>::iterator *list_it) {
std::list<DeferredNode> *list = map_it->second;
if (list_it) {
list->erase(*list_it);
}
if (list->size()) {
return false;
}
map->erase(map_it);
delete list;
return true;
}
// For every link there are 2 entries,
// left->right
// right->left
//
// If both left and right node are available, remove the entries and try to
// add the link
void IFMapAgentLinkTable::EvalDefLink(IFMapTable::RequestKey *key) {
LinkDefMap::iterator link_defmap_it = link_def_map_.find(*key);
if (link_def_map_.end() == link_defmap_it)
return;
std::list<DeferredNode> *left_list = link_defmap_it->second;
std::list<DeferredNode>::iterator left_it, left_list_entry;
for(left_it = left_list->begin(); left_it != left_list->end();) {
left_list_entry = left_it++;
// If link seq is older, dont consider the link.
if ((*left_list_entry).node_key.id_seq_num < key->id_seq_num)
continue;
// Skip if right-node is not yet present
if (IFMapAgentTable::TableEntryLookup(database(),
&((*left_list_entry).node_key))
== NULL) {
continue;
}
// left->right entry found defer-list. Find the right->left entry
LinkDefMap::iterator right_defmap_it =
link_def_map_.find((*left_list_entry).node_key);
assert(link_def_map_.end() != right_defmap_it);
std::list<DeferredNode> *right_list = right_defmap_it->second;
std::list<DeferredNode>::iterator right_it, right_list_entry;
for(right_it = right_list->begin(); right_it != right_list->end();) {
right_list_entry = right_it++;
// If link seq is older, dont consider the link.
if ((*right_list_entry).node_key.id_seq_num < key->id_seq_num)
continue;
if ((*right_list_entry).node_key.id_type == key->id_type &&
(*right_list_entry).node_key.id_name == key->id_name) {
RemoveDefListEntry(&link_def_map_, right_defmap_it,
&right_list_entry);
break;
}
}
//Remove from deferred list before enqueing
auto_ptr <RequestKey> req_key (new RequestKey);
req_key->left_key = *key;
req_key->right_key = (*left_list_entry).node_key;
req_key->metadata = (*left_list_entry).link_metadata;
// Dont delete left_list_entry. Its passed in req structure
left_list->erase(left_list_entry);
DBRequest req;
req.key = req_key;
req.oper = DBRequest::DB_ENTRY_ADD_CHANGE;
Enqueue(&req);
}
// If list does not have any entries, delete the list
RemoveDefListEntry(&link_def_map_, link_defmap_it, NULL);
}
void IFMapAgentLinkTable::DestroyDefLink(uint64_t seq) {
std::list<DeferredNode> *ent;
std::list<DeferredNode>::iterator it, list_entry;
IFMapAgentLinkTable::LinkDefMap::iterator dlist_it, temp;
for(dlist_it = link_def_map_.begin(); dlist_it != link_def_map_.end(); ) {
temp = dlist_it++;
ent = temp->second;
for(it = ent->begin(); it != ent->end();) {
list_entry = it++;
//Delete the deferred link if it is old seq
if ((*list_entry).node_key.id_seq_num < seq) {
if (RemoveDefListEntry(&link_def_map_, temp,
&list_entry) == true) {
//The list has been deleted. Move to the next map
//entry
break;
}
}
}
}
}
//Stale Cleaner functionality
class IFMapAgentStaleCleaner::IFMapAgentStaleCleanerWorker : public Task {
public:
IFMapAgentStaleCleanerWorker(DB *db, DBGraph *graph, uint64_t seq):
Task(TaskScheduler::GetInstance()->GetTaskId("db::DBTable"), 0),
db_(db), graph_(graph), seq_(seq) {
}
bool Run() {
IFMAP_AGENT_TRACE(Trace, seq_,
"IFMap Config Audit start:");
//Handle the links first
DBGraph::edge_iterator e_next(graph_);
for (DBGraph::edge_iterator e_iter = graph_->edge_list_begin();
e_iter != graph_->edge_list_end(); e_iter = e_next) {
const DBGraph::DBVertexPair &tuple = *e_iter;
e_next = ++e_iter;
IFMapNode *lhs = static_cast<IFMapNode *>(tuple.first);
IFMapNode *rhs = static_cast<IFMapNode *>(tuple.second);
IFMapLink *link =
static_cast<IFMapLink *>(graph_->GetEdge(lhs, rhs));
assert(link);
bool exists = false;
IFMapLink::LinkOriginInfo origin_info =
link->GetOriginInfo(IFMapOrigin::UNKNOWN, &exists);
if (exists && (origin_info.sequence_number < seq_ )) {
IFMapAgentLinkTable *ltable = static_cast<IFMapAgentLinkTable *>(
db_->FindTable(IFMAP_AGENT_LINK_DB_NAME));
IFMAP_AGENT_TRACE(Trace,
origin_info.sequence_number, "Deleting Link between " +
lhs->name() + rhs->name());
ltable->DeleteLink(link, lhs, rhs);
}
}
//Handle the vertices now
DBGraph::vertex_iterator v_next(graph_);
for (DBGraph::vertex_iterator v_iter = graph_->vertex_list_begin();
v_iter != graph_->vertex_list_end(); v_iter = v_next) {
IFMapNode *node = static_cast<IFMapNode *>(v_iter.operator->());
v_next = ++v_iter;
IFMapObject *obj = node->GetObject();
assert(obj);
if (obj->sequence_number() < seq_) {
IFMapAgentTable *table = static_cast<IFMapAgentTable *>(node->table());
IFMAP_AGENT_TRACE(Trace, obj->sequence_number(),
"Deleting node " + node->name());
table->DeleteNode(node);
}
}
//Handle deferred list
IFMapAgentLinkTable *table = static_cast<IFMapAgentLinkTable *>(
db_->FindTable(IFMAP_AGENT_LINK_DB_NAME));
table->DestroyDefLink(seq_);
return true;
}
private:
DB *db_;
DBGraph *graph_;
uint64_t seq_;
};
IFMapAgentStaleCleaner::~IFMapAgentStaleCleaner() {
}
IFMapAgentStaleCleaner::IFMapAgentStaleCleaner(DB *db, DBGraph *graph) :
db_(db), graph_(graph) {
}
bool IFMapAgentStaleCleaner::StaleTimeout(uint64_t seq) {
seq_ = seq;
IFMapAgentStaleCleanerWorker *cleaner = new IFMapAgentStaleCleanerWorker(db_, graph_, seq_);
TaskScheduler *sch = TaskScheduler::GetInstance();
sch->Enqueue(cleaner);
return false;
}
void IFMapAgentStaleCleaner::Clear() {
IFMapLinkTable *table = static_cast<IFMapLinkTable *>(
db_->FindTable(IFMAP_AGENT_LINK_DB_NAME));
table->Clear();
IFMapTable::ClearTables(db_);
}
| [
"pan2za@live.com"
] | pan2za@live.com |
90e55eb4da1f3f9f37538be198cbfc6d20558a07 | a37d3b38e5f31aa0129097e62c81ff12c666bf3b | /simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/test/qr_fullpivoting.cpp | ce706029c8125b5b7b654f22e642c03eb1ed945c | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | frankie4fingers/bps-nav | 4f52dba1534e8d85cd8f02b1faf2a5a2a298c7df | 4c237ba3aaa9a99093065e184c2380b22bb6e574 | refs/heads/master | 2023-08-19T14:51:21.006332 | 2021-09-18T19:33:35 | 2021-10-19T20:59:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,234 | cpp | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <Eigen/QR>
template<typename MatrixType> void qr()
{
Index max_size = EIGEN_TEST_MAX_SIZE;
Index min_size = numext::maxi(1,EIGEN_TEST_MAX_SIZE/10);
Index rows = internal::random<Index>(min_size,max_size),
cols = internal::random<Index>(min_size,max_size),
cols2 = internal::random<Index>(min_size,max_size),
rank = internal::random<Index>(1, (std::min)(rows, cols)-1);
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> MatrixQType;
MatrixType m1;
createRandomPIMatrixOfRank(rank,rows,cols,m1);
FullPivHouseholderQR<MatrixType> qr(m1);
VERIFY_IS_EQUAL(rank, qr.rank());
VERIFY_IS_EQUAL(cols - qr.rank(), qr.dimensionOfKernel());
VERIFY(!qr.isInjective());
VERIFY(!qr.isInvertible());
VERIFY(!qr.isSurjective());
MatrixType r = qr.matrixQR();
MatrixQType q = qr.matrixQ();
VERIFY_IS_UNITARY(q);
// FIXME need better way to construct trapezoid
for(int i = 0; i < rows; i++) for(int j = 0; j < cols; j++) if(i>j) r(i,j) = Scalar(0);
MatrixType c = qr.matrixQ() * r * qr.colsPermutation().inverse();
VERIFY_IS_APPROX(m1, c);
// stress the ReturnByValue mechanism
MatrixType tmp;
VERIFY_IS_APPROX(tmp.noalias() = qr.matrixQ() * r, (qr.matrixQ() * r).eval());
MatrixType m2 = MatrixType::Random(cols,cols2);
MatrixType m3 = m1*m2;
m2 = MatrixType::Random(cols,cols2);
m2 = qr.solve(m3);
VERIFY_IS_APPROX(m3, m1*m2);
{
Index size = rows;
do {
m1 = MatrixType::Random(size,size);
qr.compute(m1);
} while(!qr.isInvertible());
MatrixType m1_inv = qr.inverse();
m3 = m1 * MatrixType::Random(size,cols2);
m2 = qr.solve(m3);
VERIFY_IS_APPROX(m2, m1_inv*m3);
}
}
template<typename MatrixType> void qr_invertible()
{
using std::log;
using std::abs;
typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;
typedef typename MatrixType::Scalar Scalar;
Index max_size = numext::mini(50,EIGEN_TEST_MAX_SIZE);
Index min_size = numext::maxi(1,EIGEN_TEST_MAX_SIZE/10);
Index size = internal::random<Index>(min_size,max_size);
MatrixType m1(size, size), m2(size, size), m3(size, size);
m1 = MatrixType::Random(size,size);
if (internal::is_same<RealScalar,float>::value)
{
// let's build a matrix more stable to inverse
MatrixType a = MatrixType::Random(size,size*2);
m1 += a * a.adjoint();
}
FullPivHouseholderQR<MatrixType> qr(m1);
VERIFY(qr.isInjective());
VERIFY(qr.isInvertible());
VERIFY(qr.isSurjective());
m3 = MatrixType::Random(size,size);
m2 = qr.solve(m3);
VERIFY_IS_APPROX(m3, m1*m2);
// now construct a matrix with prescribed determinant
m1.setZero();
for(int i = 0; i < size; i++) m1(i,i) = internal::random<Scalar>();
RealScalar absdet = abs(m1.diagonal().prod());
m3 = qr.matrixQ(); // get a unitary
m1 = m3 * m1 * m3;
qr.compute(m1);
VERIFY_IS_APPROX(absdet, qr.absDeterminant());
VERIFY_IS_APPROX(log(absdet), qr.logAbsDeterminant());
}
template<typename MatrixType> void qr_verify_assert()
{
MatrixType tmp;
FullPivHouseholderQR<MatrixType> qr;
VERIFY_RAISES_ASSERT(qr.matrixQR())
VERIFY_RAISES_ASSERT(qr.solve(tmp))
VERIFY_RAISES_ASSERT(qr.matrixQ())
VERIFY_RAISES_ASSERT(qr.dimensionOfKernel())
VERIFY_RAISES_ASSERT(qr.isInjective())
VERIFY_RAISES_ASSERT(qr.isSurjective())
VERIFY_RAISES_ASSERT(qr.isInvertible())
VERIFY_RAISES_ASSERT(qr.inverse())
VERIFY_RAISES_ASSERT(qr.absDeterminant())
VERIFY_RAISES_ASSERT(qr.logAbsDeterminant())
}
void test_qr_fullpivoting()
{
for(int i = 0; i < 1; i++) {
// FIXME : very weird bug here
// CALL_SUBTEST(qr(Matrix2f()) );
CALL_SUBTEST_1( qr<MatrixXf>() );
CALL_SUBTEST_2( qr<MatrixXd>() );
CALL_SUBTEST_3( qr<MatrixXcd>() );
}
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( qr_invertible<MatrixXf>() );
CALL_SUBTEST_2( qr_invertible<MatrixXd>() );
CALL_SUBTEST_4( qr_invertible<MatrixXcf>() );
CALL_SUBTEST_3( qr_invertible<MatrixXcd>() );
}
CALL_SUBTEST_5(qr_verify_assert<Matrix3f>());
CALL_SUBTEST_6(qr_verify_assert<Matrix3d>());
CALL_SUBTEST_1(qr_verify_assert<MatrixXf>());
CALL_SUBTEST_2(qr_verify_assert<MatrixXd>());
CALL_SUBTEST_4(qr_verify_assert<MatrixXcf>());
CALL_SUBTEST_3(qr_verify_assert<MatrixXcd>());
// Test problem size constructors
CALL_SUBTEST_7(FullPivHouseholderQR<MatrixXf>(10, 20));
CALL_SUBTEST_7((FullPivHouseholderQR<Matrix<float,10,20> >(10,20)));
CALL_SUBTEST_7((FullPivHouseholderQR<Matrix<float,10,20> >(Matrix<float,10,20>::Random())));
CALL_SUBTEST_7((FullPivHouseholderQR<Matrix<float,20,10> >(20,10)));
CALL_SUBTEST_7((FullPivHouseholderQR<Matrix<float,20,10> >(Matrix<float,20,10>::Random())));
}
| [
"etw@gatech.edu"
] | etw@gatech.edu |
88278a80b6a4b3635342f087c5b1776ccf6eb158 | 87535466717be83c50d66f42fc2d776ba34a388b | /Scripts/ProjectHellscape/ProjectHellscapeCharacter.h | 33725cadd168751fa2df2125b0933af851909bca | [] | no_license | nmsu-gdc/Hellscape | c86dd9178451d930cea64046b7c0ac7e1ac160b8 | e8117c23bf1d68e9ee2abed4c77a8049858304af | refs/heads/master | 2021-01-02T13:56:18.383339 | 2020-03-06T02:58:26 | 2020-03-06T02:58:26 | 239,651,921 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,752 | h | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "ProjectHellscapeCharacter.generated.h"
class UInputComponent;
UCLASS(config=Game)
class AProjectHellscapeCharacter : public ACharacter
{
GENERATED_BODY()
/** Pawn mesh: 1st person view (arms; seen only by self) */
UPROPERTY(VisibleDefaultsOnly, Category=Mesh)
class USkeletalMeshComponent* Mesh1P;
/** Gun mesh: 1st person view (seen only by self) */
UPROPERTY(VisibleDefaultsOnly, Category = Mesh)
class USkeletalMeshComponent* FP_Gun;
/** Location on gun mesh where projectiles should spawn. */
UPROPERTY(VisibleDefaultsOnly, Category = Mesh)
class USceneComponent* FP_MuzzleLocation;
/** Gun mesh: VR view (attached to the VR controller directly, no arm, just the actual gun) */
UPROPERTY(VisibleDefaultsOnly, Category = Mesh)
class USkeletalMeshComponent* VR_Gun;
/** Location on VR gun mesh where projectiles should spawn. */
UPROPERTY(VisibleDefaultsOnly, Category = Mesh)
class USceneComponent* VR_MuzzleLocation;
/** First person camera */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class UCameraComponent* FirstPersonCameraComponent;
/** Motion controller (right hand) */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
class UMotionControllerComponent* R_MotionController;
/** Motion controller (left hand) */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
class UMotionControllerComponent* L_MotionController;
public:
AProjectHellscapeCharacter();
protected:
virtual void BeginPlay();
public:
/** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera)
float BaseTurnRate;
/** Base look up/down rate, in deg/sec. Other scaling may affect final rate. */
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera)
float BaseLookUpRate;
/** Gun muzzle's offset from the characters location */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=Gameplay)
FVector GunOffset;
/** Projectile class to spawn */
UPROPERTY(EditDefaultsOnly, Category=Projectile)
TSubclassOf<class AProjectHellscapeProjectile> ProjectileClass;
/** Sound to play each time we fire */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category=Gameplay)
class USoundBase* FireSound;
/** AnimMontage to play each time we fire */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay)
class UAnimMontage* FireAnimation;
/** Whether to use motion controller location for aiming. */
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay)
uint32 bUsingMotionControllers : 1;
protected:
/** Fires a projectile. */
void OnFire();
/** Resets HMD orientation and position in VR. */
void OnResetVR();
/** Handles moving forward/backward */
void MoveForward(float Val);
/** Handles stafing movement, left and right */
void MoveRight(float Val);
/**
* Called via input to turn at a given rate.
* @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate
*/
void TurnAtRate(float Rate);
/**
* Called via input to turn look up/down at a given rate.
* @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate
*/
void LookUpAtRate(float Rate);
struct TouchData
{
TouchData() { bIsPressed = false;Location=FVector::ZeroVector;}
bool bIsPressed;
ETouchIndex::Type FingerIndex;
FVector Location;
bool bMoved;
};
void BeginTouch(const ETouchIndex::Type FingerIndex, const FVector Location);
void EndTouch(const ETouchIndex::Type FingerIndex, const FVector Location);
void TouchUpdate(const ETouchIndex::Type FingerIndex, const FVector Location);
TouchData TouchItem;
protected:
// APawn interface
virtual void SetupPlayerInputComponent(UInputComponent* InputComponent) override;
// End of APawn interface
/*
* Configures input for touchscreen devices if there is a valid touch interface for doing so
*
* @param InputComponent The input component pointer to bind controls to
* @returns true if touch controls were enabled.
*/
bool EnableTouchscreenMovement(UInputComponent* InputComponent);
public:
/** Returns Mesh1P subobject **/
FORCEINLINE class USkeletalMeshComponent* GetMesh1P() const { return Mesh1P; }
/** Returns FirstPersonCameraComponent subobject **/
FORCEINLINE class UCameraComponent* GetFirstPersonCameraComponent() const { return FirstPersonCameraComponent; }
};
| [
"lansfordjr14@gmail.com"
] | lansfordjr14@gmail.com |
4c2c46335c05b8cc18285d7d1f0c1dfeb624e861 | 13c2d3db2d49c40c74c2e6420a9cd89377f1c934 | /program_data/github_cpp_program_data/4/22.cpp | fa96df5ee925d8e7c867b6a4e3d43e7d5c8bc859 | [
"MIT"
] | permissive | qiuchili/ggnn_graph_classification | c2090fefe11f8bf650e734442eb96996a54dc112 | 291ff02404555511b94a4f477c6974ebd62dcf44 | refs/heads/master | 2021-10-18T14:54:26.154367 | 2018-10-21T23:34:14 | 2018-10-21T23:34:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,083 | cpp | #include <algorithm>
#include <iterator>
#include <functional>
#include "hash-table.h"
HashTable::HashTable()
: m_buckets{new std::forward_list<Pair*> [BUCKET_SIZE]}
, m_size{0}
{
for (auto i = 0; i < BUCKET_SIZE; i++) {
m_buckets[i] = new std::forward_list<Pair*>;
}
}
HashTable::~HashTable()
{
for (auto i = 0; i < BUCKET_SIZE; i++) {
if (m_buckets[i] != nullptr) {
m_buckets[i]->clear();
delete m_buckets[i];
}
}
}
void HashTable::insert(const std::string key, int value)
{
int i = std::hash<std::string>{}(key) % BUCKET_SIZE;
auto it = std::find_if(m_buckets[i]->cbegin(),
m_buckets[i]->cend(), [=] (Pair* pair) { return pair->key == key; });
if (it != m_buckets[i]->cend()) {
(*it)->value = value;
return;
}
m_buckets[i]->push_front(new Pair(key, value));
m_size++;
}
int HashTable::value(const std::string key, const int defaultValue) const
{
int i = std::hash<std::string>{}(key) % BUCKET_SIZE;
auto it = std::find_if(m_buckets[i]->cbegin(),
m_buckets[i]->cend(), [=] (Pair* pair) { return pair->key == key; });
if (it != m_buckets[i]->cend()) {
return (*it)->value;
} else {
return defaultValue;
}
}
void HashTable::remove(const std::string key)
{
int i = std::hash<std::string>{}(key) % BUCKET_SIZE;
auto it = std::find_if(m_buckets[i]->cbegin(),
m_buckets[i]->cend(), [=] (Pair* pair) { return pair->key == key; });
if (it != m_buckets[i]->cend()) {
m_buckets[i]->remove(*it);
m_size--;
}
}
bool HashTable::contains(const std::string key) const
{
int i = std::hash<std::string>{}(key) % BUCKET_SIZE;
auto it = std::find_if(m_buckets[i]->cbegin(), m_buckets[i]->cend(),
[key] (Pair* p) { return p->key == key; });
return it != m_buckets[i]->cend();
}
void HashTable::clear()
{
for (auto i = 0; i < BUCKET_SIZE; i++) {
if (m_buckets[i] != nullptr) {
m_buckets[i]->clear();
}
}
m_size = 0;
} | [
"y.yu@open.ac.uk"
] | y.yu@open.ac.uk |
dc163c4e264b826ecb5c7752e35723fa524c4de0 | 2b65a6e454684da50f9e41c2f5e5abfe2d208d1f | /SerialLink.cpp | 22202d303a5e47deb3fe71133ddcd0ef28f33436 | [
"MIT"
] | permissive | darevish/Serial2Websocket | 625b483e7627442c3539048f63f750f5de16160e | ce99fa6a5cf3ba86d66d51163e7171fc43118ff9 | refs/heads/master | 2020-05-19T14:17:28.981251 | 2014-12-18T22:51:05 | 2014-12-18T22:53:34 | 27,674,923 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,002 | cpp | #include "SerialLink.hpp"
#include "WebsocketLink.hpp"
SerialLink::SerialLink(
boost::asio::io_service& _io_service,
std::string& _device,
unsigned int _baud_rate,
unsigned int _character_size
) : io_service(_io_service),
strand(_io_service),
serial_port(_io_service, _device),
device(_device),
baud_rate(_baud_rate),
character_size(_character_size),
flow_control(boost::asio::serial_port_base::flow_control::none),
parity(boost::asio::serial_port_base::parity::none),
stop_bits(boost::asio::serial_port_base::stop_bits::one),
timer(_io_service)
{
std::cout<<"SerialLink constructor begin"<<std::endl;
initOptions();
std::cout<<"SerialLink constructor end"<<std::endl;
}
SerialLink::~SerialLink() {
destroy();
}
void SerialLink::initOptions()
{
// what baud rate do we communicate at
serial_port.set_option(baud_rate);
// how big is each "packet" of data (default is 8 bits)
serial_port.set_option(character_size);
// what flow control is used (default is none)
serial_port.set_option(flow_control);
// what parity is used (default is none)
serial_port.set_option(parity);
// how many stop bits are used (default is one)
serial_port.set_option(stop_bits);
}
unsigned int SerialLink::getBaudRate() {
boost::asio::serial_port_base::baud_rate temp_baud_rate;
serial_port.get_option(temp_baud_rate);
return temp_baud_rate.value();
}
void SerialLink::setWebsocketLink(WebsocketLink *_websocketLink) {
websocketLink = _websocketLink;
}
void SerialLink::restart(const boost::system::error_code& err) {
std::cout<<"restart begin"<<std::endl;
try {
if (serial_port.is_open()) {
std::cout<<"dest"<<std::endl;
destroy();
std::cout<<"dest. end."<<std::endl;
}
serial_port.open(device);
std::cout<<"open end."<<std::endl;
initOptions();
readNewLine();
} catch (std::exception e) {
std::cout<<"e "<<e.what()<<std::endl;
timer.expires_from_now(boost::posix_time::seconds(5));
timer.async_wait(boost::bind(&SerialLink::restart, this, boost::asio::placeholders::error));
}
std::cout<<"restart end"<<std::endl;
}
void SerialLink::processLine(const boost::system::error_code& err, std::size_t bytes_transferred) {
std::cout<<"process begin"<<std::endl;
if (!err)
{
std::istream is(&read_buffer);
std::string line;
std::getline(is, line);
std::cout<<"Line: "<<line<<std::endl;
io_service.post(strand.wrap( boost::bind(&WebsocketLink::doSend, websocketLink, line) ));
io_service.post(strand.wrap( boost::bind(&SerialLink::readNewLine, this) ));
} else {
timer.expires_from_now(boost::posix_time::seconds(5));
timer.async_wait(boost::bind(&SerialLink::restart, this, boost::asio::placeholders::error));
std::cout << "Error: " << err << std::endl;
}
std::cout<<"process end"<<std::endl;
}
void SerialLink::readNewLine() {
std::cout<<"readline begin"<<std::endl;
boost::asio::async_read_until(serial_port, read_buffer, "\n",
boost::bind(&SerialLink::processLine, this,
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred
));
std::cout<<"readline end"<<std::endl;
}
void SerialLink::writeHandler(const boost::system::error_code& error, std::size_t bytes_transferred) {
std::cout<<"written "<<bytes_transferred<<" bytes to serial port"<<std::endl;
}
void SerialLink::doWrite(std::string& msg) {
boost::asio::async_write(serial_port, boost::asio::buffer(msg),
boost::bind(
&SerialLink::writeHandler,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred
)
);
}
void SerialLink::destroy() {
serial_port.cancel();
if (serial_port.is_open()) {
serial_port.close();
}
}
| [
"dar3vish@gmail.com"
] | dar3vish@gmail.com |
914d28bb5a677412c9d95f9133643ba4c92c0fb6 | 2a15064b0064dec6da39b8f09b7cddb3b7b12dac | /include/sp2/audio/musicPlayer.h | 031293d32a790f427af44fdfc8288f1fff8df947 | [
"MIT",
"LicenseRef-scancode-other-permissive",
"Zlib",
"LicenseRef-scancode-public-domain"
] | permissive | daid/SeriousProton2 | 28a34cd928ad35a5a0e34961848257b04c7d1133 | 3fd555ddea591ddaf1b16531f53794c222e9e699 | refs/heads/master | 2023-08-19T02:24:20.009689 | 2023-08-11T05:58:16 | 2023-08-11T05:58:16 | 67,449,970 | 10 | 8 | null | 2021-09-30T06:47:15 | 2016-09-05T20:46:54 | C | UTF-8 | C++ | false | false | 700 | h | #ifndef SP2_AUDIO_MUSICPLAYER_H
#define SP2_AUDIO_MUSICPLAYER_H
#include <sp2/string.h>
#include <sp2/updatable.h>
namespace sp {
namespace audio {
/* The MusicPlayer is an object that allows playing multiple music files.
* It plays the files in random order.
*/
class MusicPlayer : public Updatable
{
public:
MusicPlayer() = default;
MusicPlayer(const string& resource_path);
MusicPlayer(std::initializer_list<string> files);
virtual void onUpdate(float delta) override;
void searchResources(const string& resource_path);
void add(const string& filename);
private:
std::vector<string> files;
};
}//namespace audio
}//namespace sp
#endif//SP2_AUDIO_MUSICPLAYER_H
| [
"daid303@gmail.com"
] | daid303@gmail.com |
b688f9427119e4a3266af1764a2f3f5cc20d710b | 58f69cfcc91dfcceb83ec0b846def931fb478f67 | /tests/pbr/src/test_lighting.cpp | 01c9a3d1835930de18e09e8c501d7cc50b6e985d | [] | no_license | xiayigeyese/OpenGL_Learning | bf742e77941614f8772ffbb19cc79f28b753cc1b | 6cdd0a79c796788a24068fd5529485711c38dbc9 | refs/heads/main | 2023-05-17T09:53:24.340124 | 2021-06-10T05:53:10 | 2021-06-10T05:53:10 | 357,232,047 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,154 | cpp | #include <app/app.h>
#include <opengl/opengl.h>
#include "test_pbr.h"
#include "pass/skyboxPass.h"
using namespace std;
using namespace glm;
void test_sphere()
{
// init app
const int width = 800, height = 600;
Application app("sphere", width, height);
GLFWwindow* window = app.getWindow();
Input* input = app.getInput();
// set camera
Camera camera = Camera::perspectiveCamera(
vec3(0, 0, 3),
vec3(0, 0, 1),
vec3(0, 1, 0),
45.0f,
static_cast<float>(width) / height,
0.1f,
100.0f
);
CameraController cameraController(&camera, input);
// init data
Sphere sphere(200);
// load texture
Texture2D diffuseMap;
diffuseMap.loadFromFile("resources/textures/Kerbin.png", 12);
diffuseMap.setTexWrapParameter(GL_REPEAT, GL_REPEAT);
diffuseMap.setTexFilterParameter(GL_LINEAR, GL_LINEAR);
// load shader
ShaderProgram shader({
VertexShader::loadFromFile("tests/pbr/shaders/sphere.vert").getHandler(),
FragmentShader::loadFromFile("tests/pbr/shaders/sphere.frag").getHandler()
});
UniformVariable<glm::mat4> shader_vs_mvp = shader.getUniformVariable<glm::mat4>("u_mvp");
shader.setUniformValue("diffuseMap", 0);
// openGL config
glEnable(GL_DEPTH_TEST);
// glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
// render
while(!glfwWindowShouldClose(window))
{
app.getKeyPressInput();
cameraController.processKeyPressInput();
glClearColor(0.2f, 0.2f, 0.2f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shader.use();
glActiveTexture(0);
diffuseMap.bindTexUnit(0);
shader.setUniformValue(shader_vs_mvp, camera.getProjectionMatrix() * camera.getViewMatrix());
sphere.draw();
shader.unUse();
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
}
void test_lighting()
{
// init app
const int width = 800, height = 600;
Application app("pbr_lighting", width, height);
GLFWwindow* window = app.getWindow();
Input* input = app.getInput();
// set camera
Camera camera = Camera::perspectiveCamera(
vec3(0, 0, 3),
vec3(0, 0, 1),
vec3(0, 1, 0),
45.0f,
static_cast<float>(width) / height,
0.1f,
100.0f
);
CameraController cameraController(&camera, input);
// init sphere
Sphere sphere(200);
// lights
// ------
glm::vec3 lightPositions[] = {
glm::vec3(-10.0f, 10.0f, 10.0f),
glm::vec3(10.0f, 10.0f, 10.0f),
glm::vec3(-10.0f, -10.0f, 10.0f),
glm::vec3(10.0f, -10.0f, 10.0f),
};
glm::vec3 lightColors[] = {
glm::vec3(300.0f, 300.0f, 300.0f),
glm::vec3(300.0f, 300.0f, 300.0f),
glm::vec3(300.0f, 300.0f, 300.0f),
glm::vec3(300.0f, 300.0f, 300.0f)
};
// load shader
ShaderProgram shader({
VertexShader::loadFromFile("tests/pbr/shaders/pbr_light.vert").getHandler(),
FragmentShader::loadFromFile("tests/pbr/shaders/pbr_light.frag").getHandler()
});
// set shader uniform
// --> vs
UniformVariable<glm::mat4> shader_vs_model = shader.getUniformVariable<glm::mat4>("u_model");
UniformVariable<glm::mat4> shader_vs_mvp = shader.getUniformVariable<glm::mat4>("u_mvp");
// --> fs
for(int i=0;i<4;i++)
{
shader.setUniformValue("light[" + to_string(i) + "].position", lightPositions[i]);
shader.setUniformValue("light[" + to_string(i) + "].color", lightColors[i]);
}
UniformVariable<vec3> shader_fs_viewPos = shader.getUniformVariable<glm::vec3>("viewPos");
shader.setUniformValue("albedo", glm::vec3(0.5f, 0.0f, 0.0f));
shader.setUniformValue("ao", 1.0f);
UniformVariable<float> shader_fs_metallic = shader.getUniformVariable<float>("metallic");
UniformVariable<float> shader_fs_roughness = shader.getUniformVariable<float>("roughness");
// set sphere position
int yNums = 7, xNums = 7;
float spacing = 2.5;
glm::mat4 model = glm::mat4(1.0f);
vector<mat4> worldMatrix(yNums * xNums);
vector<float> metallic(yNums);
vector<float> roughness(xNums);
for (int y = 0; y < yNums; y++)
{
metallic[y] = static_cast<float>(y) / static_cast<float>(yNums);
for (int x = 0; x < xNums; x++)
{
roughness[x] = glm::clamp(static_cast<float>(x) / static_cast<float>(xNums), 0.05f, 1.0f);
model = glm::mat4(1.0f);
model = glm::translate(model, glm::vec3(
static_cast<float>(x - (xNums / 2)) * spacing,
static_cast<float>(y - (yNums / 2)) * spacing,
0.0f
));
worldMatrix[x + y * xNums] = model;
}
}
// openGL config
glEnable(GL_DEPTH_TEST);
// render
while (!glfwWindowShouldClose(window))
{
app.getKeyPressInput();
cameraController.processKeyPressInput();
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
shader.use();
shader.setUniformValue(shader_fs_viewPos, camera.getPosition());
for(int y=0;y<yNums;y++)
{
shader.setUniformValue(shader_fs_metallic, metallic[y]);
for(int x=0; x < xNums;x++)
{
shader.setUniformValue(shader_fs_roughness, roughness[x]);
int index = x + y * xNums;
shader.setUniformValue(shader_vs_model, worldMatrix[index]);
glm::mat4 mvp = camera.getProjectionMatrix() * camera.getViewMatrix() * worldMatrix[index];
shader.setUniformValue(shader_vs_mvp, mvp);
sphere.draw();
}
}
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
}
| [
"1146004731@qq.com"
] | 1146004731@qq.com |
679e852043b28257aaad976ce0b8e29cd849f952 | 01aa77758f69215e3fe559140c1fd91f314fb536 | /common/lang/text_output_stream.cpp | 4a41f6d7884cea73b0cfef83d28e21ff792111d3 | [] | no_license | yuchenguangfd/Longan | 30f1acc66d76a859363a9421bf719b9d9a50f4f8 | da895e2704731c055ba36df2f05297186bbdf9fa | refs/heads/master | 2020-05-30T06:09:19.404290 | 2015-06-02T11:32:18 | 2015-06-02T11:32:18 | 22,028,930 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,796 | cpp | /*
* text_output_stream.cpp
* Created on: Jan 24, 2015
* Author: chenguangyu
*/
#include "text_output_stream.h"
namespace longan {
TextOutputStream::TextOutputStream() : mStream(stdout) { }
TextOutputStream::TextOutputStream(const std::string& filename) {
mStream = fopen(filename.c_str(), "w");
if (mStream == nullptr) {
throw LonganFileOpenError();
}
}
TextOutputStream::~TextOutputStream() {
if (mStream != nullptr) Close();
}
void TextOutputStream::Close() {
if (mStream == stdout) {
fflush(mStream);
mStream = nullptr;
return;
}
fclose(mStream);
mStream = nullptr;
}
void TextOutputStream::Write(const int32 *data, int size, const char *split) {
if (size == 0) return;
if (fprintf(mStream, "%d", data[0]) < 0) {
throw LonganFileWriteError();
}
for (int i = 1; i < size; ++i) {
if (fprintf(mStream, "%s%d", split, data[i]) < 0) {
throw LonganFileWriteError();
}
}
}
void TextOutputStream::Write(const float32 *data, int size, const char *split) {
if (size == 0) return;
if (fprintf(mStream, "%f", data[0]) < 0) {
throw LonganFileWriteError();
}
for (int i = 1; i < size; ++i) {
if (fprintf(mStream, "%s%f", split, data[i]) < 0) {
throw LonganFileWriteError();
}
}
}
void TextOutputStream::Write(const float64 *data, int size, const char *split) {
if (size == 0) return;
if (fprintf(mStream, "%lf", data[0]) < 0) {
throw LonganFileWriteError();
}
for (int i = 1; i < size; ++i) {
if (fprintf(mStream, "%s%lf", split, data[i]) < 0) {
throw LonganFileWriteError();
}
}
}
} //~ namespace longan
| [
"yuchenguangfd@gmail.com"
] | yuchenguangfd@gmail.com |
d428906d5a6b78731694fe4ae943c3439fa9f5f9 | c3a424748ca2a3bc8604d76f1bf70ff3fee40497 | /legacy_POL_source/oldPOL2_2007/src/pol/cliface.h | e415f03e50e089606763475bad31abb727c11a80 | [] | no_license | polserver/legacy_scripts | f597338fbbb654bce8de9c2b379a9c9bd4698673 | 98ef8595e72f146dfa6f5b5f92a755883b41fd1a | refs/heads/master | 2022-10-25T06:57:37.226088 | 2020-06-12T22:52:22 | 2020-06-12T22:52:22 | 23,924,142 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,516 | h | #ifndef CLIFACE_H
#define CLIFACE_H
#include <vector>
class Attribute;
class Client;
class Character;
class Vital;
class UOSkill;
struct ClientVitalUpdaters
{
public:
ClientVitalUpdaters();
void (*my_vital_changed)(Client* client, Character* me, const Vital* vital);
void (*others_vital_changed)(Client* client, Character* him, const Vital* vital);
};
struct ClientAttributeUpdaters
{
public:
ClientAttributeUpdaters();
void (*my_attr_changed)(Client* client, Character* me, const Attribute* attr);
const UOSkill* pUOSkill;
};
class ClientInterface
{
public:
virtual ~ClientInterface() {}
void register_client( Client* client );
void deregister_client( Client* client );
static void tell_vital_changed( Character* who, const Vital* vital );
static void tell_attribute_changed( Character* who, const Attribute* attr );
protected:
virtual void Initialize();
virtual void bcast_vital_changed( Character* who, const Vital* vital ) const = 0;
std::vector<ClientVitalUpdaters> vital_updaters;
std::vector<ClientAttributeUpdaters> attribute_updaters;
std::vector<Client*> clients;
friend void send_uo_skill( Client* client, Character* me, const Attribute* attr );
};
class UOClientInterface : public ClientInterface
{
public:
void Initialize();
protected:
friend class ClientInterface;
virtual void bcast_vital_changed( Character* who, const Vital* vital ) const;
};
extern UOClientInterface uo_client_interface;
#endif
| [
"hopelivesproject@gmail.com"
] | hopelivesproject@gmail.com |
e81235296fe8da8f563cdf6af65f699152ac377d | de37f7bb64df0b6b69e05b0d498a5ebc7af08f87 | /Namespaces/src/Cat.h | 443d98f0d53d32132e45069c977e02dd7a75778b | [] | no_license | twlghtzn/learning_cpp | fb6f05f993bc8091421ce1882a5dab80ef87a329 | adf384ff7e51aecdb42c0799b1ca12bce2f5b7c5 | refs/heads/main | 2023-02-07T14:36:05.398024 | 2021-01-01T19:40:38 | 2021-01-01T19:40:38 | 323,332,635 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 282 | h | /*
* Cat.h
*
* Created on: Jan 1, 2021
* Author: gyors
*/
#ifndef CAT_H_
#define CAT_H_
#include <iostream>
using namespace std;
namespace cats {
const string CATNAME = "Freddy";
class Cat {
public:
Cat();
virtual ~Cat();
void speak();
};
}
#endif /* CAT_H_ */
| [
"orsolya.bor@gmail.com"
] | orsolya.bor@gmail.com |
9444f23c902b1252b038199c47a5da3d13f6b2a4 | 1b64b8d3dcdf32e793fdf5f6fd5209fdbb24d38b | /Homework II/problem_2_item_c.cc | c20c37e65d8a411aac45f42e5636b1c19f884e50 | [] | no_license | sfuenzal/computational_physics | fa22fc19f7550097b93efd3e94d2e32ceda7bc2c | a0df3e90acf112b59e10d60e581cbdf89ad2fd33 | refs/heads/main | 2023-02-16T17:31:02.261733 | 2021-01-14T17:29:10 | 2021-01-14T17:29:10 | 308,085,577 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,327 | cc | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
int** initializeMatrix(int n)
{
int** temp = new int*[n];
for(int i=0; i<n; i++)
{
temp[i] = new int[n];
}
return temp;
}
void naive_multiplication(int** A, int** B, int n)
{
int** C = initializeMatrix(n);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
C[i][j] = 0;
for (int k = 0; k < n; k++)
{
C[i][j] += A[i][k]*B[k][j];
}
//cout << C[i][j] << endl;
}
}
}
int main()
{
ofstream times_file_2;
int n;
cout << "Please enter the dimension of the matrices: " << endl;
cin >> n;
int** A = initializeMatrix(n);
int** B = initializeMatrix(n);
clock_t start, end;
/* Recording the starting clock tick.*/
start = clock();
naive_multiplication(A, B, n);
// Recording the end clock tick.
end = clock();
// Calculating total time taken by the program.
double time_taken = double(end - start) / double(CLOCKS_PER_SEC);
times_file_2.open ("times_file_2.txt", ios::app | ios::ate);
times_file_2 << "Time taken by program is : " << fixed << time_taken << setprecision(10) << endl;
times_file_2.close();
} | [
"noreply@github.com"
] | sfuenzal.noreply@github.com |
87ca7f83e7762293138e25ee11af8f1a2d3350ac | e4516bc1ef2407c524af95f5b6754b3a3c37b3cc | /answers/lintcode/Kth Largest Element.cpp | 2ef717e4e03160936ff447b37b194b6f840c2dbd | [
"MIT"
] | permissive | FeiZhan/Algo-Collection | 7102732d61f324ffe5509ee48c5015b2a96cd58d | 9ecfe00151aa18e24846e318c8ed7bea9af48a57 | refs/heads/master | 2023-06-10T17:36:53.473372 | 2023-06-02T01:33:59 | 2023-06-02T01:33:59 | 3,762,869 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,194 | cpp | class Solution {
public:
/*
* param k : description of k
* param nums : description of array and index 0 ~ n-1
* return: description of return
*/
int kthLargestElement(int k, vector<int> nums) {
// write your code here
if (k > nums.size() || k <= 0) {
return 0;
}
return kthLargestElement(nums.size() - k + 1, nums, 0, nums.size() - 1);
}
int kthLargestElement(int k, vector<int> &nums, size_t begin, size_t end) {
int pivot = nums[end];
size_t left = begin;
size_t right = end;
while (true) {
while (nums[left] < pivot && left < right) {
++ left;
}
while (nums[right] >= pivot && right > left) {
-- right;
}
if (left == right) {
break;
}
swap(nums, left, right);
}
// one more swap
swap(nums, left, end);
// return value
if (left + 1 == k) {
return pivot;
}
else if (k < left + 1) {
return kthLargestElement(k, nums, begin, left - 1);
}
else {
return kthLargestElement(k, nums, left + 1, end);
}
}
void swap(vector<int> &nums, size_t n0, size_t n1) {
int temp = nums[n0];
nums[n0] = nums[n1];
nums[n1] = temp;
}
};
| [
"dog217@126.com"
] | dog217@126.com |
14d74d9adc16026fd47ff5e475834fa8622df4b6 | 8faee0b01b9afed32bb5b7ef1ab0dcbc46788b5b | /source/src/app/blastdb/blastdbcmd.cpp | 65a6e14ba56427b6e825abf210bf035bf513e178 | [] | no_license | jackgopack4/pico-blast | 5fe3fa1944b727465845e1ead1a3c563b43734fb | cde1bd03900d72d0246cb58a66b41e5dc17329dd | refs/heads/master | 2021-01-14T12:31:05.676311 | 2014-05-17T19:22:05 | 2014-05-17T19:22:05 | 16,808,473 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,168 | cpp | /* $Id: blastdbcmd.cpp 389689 2013-02-20 14:25:43Z fongah2 $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Christiam Camacho
*
*/
/** @file blastdbcmd.cpp
* Command line tool to examine the contents of BLAST databases. This is the
* successor to fastacmd from the C toolkit
*/
#ifndef SKIP_DOXYGEN_PROCESSING
static char const rcsid[] =
"$Id: blastdbcmd.cpp 389689 2013-02-20 14:25:43Z fongah2 $";
#endif /* SKIP_DOXYGEN_PROCESSING */
#include <ncbi_pch.hpp>
#include <corelib/ncbiapp.hpp>
#include <algo/blast/api/version.hpp>
#include <objtools/blast/seqdb_reader/seqdbexpert.hpp>
#include <algo/blast/api/blast_exception.hpp>
#include <algo/blast/blastinput/blast_input_aux.hpp>
#include <objtools/blast/blastdb_format/seq_writer.hpp>
#include <objtools/blast/blastdb_format/blastdb_formatter.hpp>
#include <objtools/blast/blastdb_format/blastdb_seqid.hpp>
#include <algo/blast/blastinput/blast_input.hpp>
#include "../blast/blast_app_util.hpp"
#include <iomanip>
#ifndef SKIP_DOXYGEN_PROCESSING
USING_NCBI_SCOPE;
USING_SCOPE(blast);
#endif
/// The application class
class CBlastDBCmdApp : public CNcbiApplication
{
public:
/** @inheritDoc */
CBlastDBCmdApp() {
CRef<CVersion> version(new CVersion());
version->SetVersionInfo(new CBlastVersion());
SetFullVersion(version);
}
private:
/** @inheritDoc */
virtual void Init();
/** @inheritDoc */
virtual int Run();
/// Handle to BLAST database
CRef<CSeqDBExpert> m_BlastDb;
/// Is the database protein
bool m_DbIsProtein;
/// Sequence range, non-empty if provided as command line argument
TSeqRange m_SeqRange;
/// Strand to retrieve
ENa_strand m_Strand;
/// output is FASTA
bool m_FASTA;
/// output is ASN.1 defline
bool m_Asn1DeflineOutput;
/// should we find duplicate entries?
bool m_GetDuplicates;
/// should we output target sequence only?
bool m_TargetOnly;
/// Initializes the application's data members
void x_InitApplicationData();
/// Prints the BLAST database information (e.g.: handles -info command line
/// option)
void x_PrintBlastDatabaseInformation();
/// Processes all requests except printing the BLAST database information
/// @return 0 on success; 1 if some sequences were not retrieved
int x_ProcessSearchRequest();
/// Vector of sequence identifiers in a BLAST database
typedef vector< CRef<CBlastDBSeqId> > TQueries;
/// Extract the queries for the BLAST database from the command line
/// options
/// @param queries queries to retrieve [in|out]
/// @return 0 on sucess; 1 if some queries were not processed
int x_GetQueries(TQueries& queries) const;
/// Add a query ID for processing
/// @param retval the return value where the queries will be added [in|out]
/// @param entry the user's query [in]
/// @return 0 on sucess; 1 if some seqid is not translated
int x_AddSeqId(CBlastDBCmdApp::TQueries& retval, const string& entry) const;
/// Add an OID for processing
/// @param retval the return value where the queries will be added [in|out]
/// @param entry the user's query [in]
void x_AddOid(CBlastDBCmdApp::TQueries& retval, const int oid, bool check=false) const;
/// Process batch entry with range, strand and filter id
/// @param args program input args
/// @param seq_fmt sequence formatter object
/// @return 0 on sucess; 1 if some queries were not processed
int x_ProcessBatchEntry(const CArgs& args, CSeqFormatter & seq_fmt);
};
int
CBlastDBCmdApp::x_AddSeqId(CBlastDBCmdApp::TQueries& retval,
const string& entry) const
{
// Process get dups
if (m_GetDuplicates) {
vector<int> oids;
m_BlastDb->AccessionToOids(entry, oids);
ITERATE(vector<int>, oid, oids) {
x_AddOid(retval, *oid, true);
}
return 0;
}
// FASTA / target_only just need one id
if (m_TargetOnly) {
retval.push_back(CRef<CBlastDBSeqId>(new CBlastDBSeqId(entry)));
return 0;
}
// Default: find oid first and add all pertinent
vector<int> oids;
m_BlastDb->AccessionToOids(entry, oids);
if (!oids.empty()) {
x_AddOid(retval, oids[0], true);
return 0;
}
ERR_POST(Error << entry << ": OID not found");
return 1;
}
void
CBlastDBCmdApp::x_AddOid(CBlastDBCmdApp::TQueries& retval,
const int oid,
bool check) const
{
// check to see if this oid has been excluded
if (check) {
list< CRef<CSeq_id> > filtered_ids = m_BlastDb->GetSeqIDs(oid);
if (filtered_ids.empty()) {
return;
}
}
// FASTA output just need one id
if (m_FASTA || m_Asn1DeflineOutput) {
CRef<CBlastDBSeqId> blastdb_seqid(new CBlastDBSeqId());
blastdb_seqid->SetOID(oid);
retval.push_back(blastdb_seqid);
return;
}
// Not a NR database, add oid instead
vector<int> gis;
m_BlastDb->GetGis(oid, gis);
if (gis.empty()) {
CRef<CBlastDBSeqId> blastdb_seqid(new CBlastDBSeqId());
blastdb_seqid->SetOID(oid);
retval.push_back(blastdb_seqid);
return;
}
// Default: add all possible ids
ITERATE(vector<int>, gi, gis) {
retval.push_back(CRef<CBlastDBSeqId>
(new CBlastDBSeqId(NStr::IntToString(*gi))));
}
}
int
CBlastDBCmdApp::x_GetQueries(CBlastDBCmdApp::TQueries& retval) const
{
int err_found = 0;
const CArgs& args = GetArgs();
retval.clear();
_ASSERT(m_BlastDb.NotEmpty());
if (args["pig"].HasValue()) {
retval.reserve(1);
retval.push_back(CRef<CBlastDBSeqId>
(new CBlastDBSeqId(args["pig"].AsInteger())));
} else if (args["entry"].HasValue()) {
static const string kDelim(",");
const string& entry = args["entry"].AsString();
if (entry.find(kDelim[0]) != string::npos) {
vector<string> tokens;
NStr::Tokenize(entry, kDelim, tokens);
ITERATE(vector<string>, itr, tokens) {
err_found += x_AddSeqId(retval, *itr);
}
} else if (entry == "all") {
for (int i = 0; m_BlastDb->CheckOrFindOID(i); i++) {
x_AddOid(retval, i);
}
} else {
err_found += x_AddSeqId(retval, entry);
}
} else {
NCBI_THROW(CInputException, eInvalidInput,
"Must specify query type: one of 'entry', 'entry_batch', or 'pig'");
}
if (retval.empty()) {
NCBI_THROW(CInputException, eInvalidInput,
"Entry not found in BLAST database");
}
return (err_found) ? 1 : 0;
}
void
CBlastDBCmdApp::x_InitApplicationData()
{
const CArgs& args = GetArgs();
CSeqDB::ESeqType seqtype = ParseMoleculeTypeString(args[kArgDbType].AsString());
m_BlastDb.Reset(new CSeqDBExpert(args[kArgDb].AsString(), seqtype));
m_DbIsProtein = static_cast<bool>(m_BlastDb->GetSequenceType() == CSeqDB::eProtein);
m_SeqRange = TSeqRange::GetEmpty();
if (args["range"].HasValue()) {
m_SeqRange = ParseSequenceRangeOpenEnd(args["range"].AsString());
}
m_Strand = eNa_strand_unknown;
if (args["strand"].HasValue() && !m_DbIsProtein) {
if (args["strand"].AsString() == "plus") {
m_Strand = eNa_strand_plus;
} else if (args["strand"].AsString() == "minus") {
m_Strand = eNa_strand_minus;
} else {
abort(); // both strands not supported
}
}
m_GetDuplicates = args["get_dups"];
m_TargetOnly = args["target_only"];
}
void
CBlastDBCmdApp::x_PrintBlastDatabaseInformation()
{
_ASSERT(m_BlastDb.NotEmpty());
static const NStr::TNumToStringFlags kFlags = NStr::fWithCommas;
const string kLetters = m_DbIsProtein ? "residues" : "bases";
const CArgs& args = GetArgs();
CNcbiOstream& out = args["out"].AsOutputFile();
// Print basic database information
out << "Database: " << m_BlastDb->GetTitle() << endl
<< "\t" << NStr::IntToString(m_BlastDb->GetNumSeqs(), kFlags)
<< " sequences; "
<< NStr::UInt8ToString(m_BlastDb->GetTotalLength(), kFlags)
<< " total " << kLetters << endl << endl
<< "Date: " << m_BlastDb->GetDate()
<< "\tLongest sequence: "
<< NStr::IntToString(m_BlastDb->GetMaxLength(), kFlags) << " "
<< kLetters << endl;
#if ((!defined(NCBI_COMPILER_WORKSHOP) || (NCBI_COMPILER_VERSION > 550)) && \
(!defined(NCBI_COMPILER_MIPSPRO)) )
// Print filtering algorithms supported
out << m_BlastDb->GetAvailableMaskAlgorithmDescriptions();
#endif
// Print volume names
vector<string> volumes;
m_BlastDb->FindVolumePaths(volumes,false);
out << endl << "Volumes:" << endl;
ITERATE(vector<string>, file_name, volumes) {
out << "\t" << *file_name << endl;
}
}
int
CBlastDBCmdApp::x_ProcessSearchRequest()
{
const CArgs& args = GetArgs();
CNcbiOstream& out = args["out"].AsOutputFile();
CSeqFormatterConfig conf;
conf.m_LineWidth = args["line_length"].AsInteger();
conf.m_SeqRange = m_SeqRange;
conf.m_Strand = m_Strand;
conf.m_TargetOnly = m_TargetOnly;
conf.m_UseCtrlA = args["ctrl_a"];
conf.m_FiltAlgoId = (args["mask_sequence_with"].HasValue())
? args["mask_sequence_with"].AsInteger() : -1;
string outfmt;
if (args["outfmt"].HasValue()) {
outfmt = args["outfmt"].AsString();
m_FASTA = false;
m_Asn1DeflineOutput = false;
if (outfmt.find("%f") != string::npos &&
outfmt.find("%d") != string::npos) {
NCBI_THROW(CInputException, eInvalidInput,
"The %d and %f output format options cannot be specified together.");
}
// If "%f" is found within outfmt, discard everything else
if (outfmt.find("%f") != string::npos) {
outfmt = "%f";
m_FASTA = true;
}
// If "%d" is found within outfmt, discard everything else
if (outfmt.find("%d") != string::npos) {
outfmt = "%d";
m_Asn1DeflineOutput = true;
}
if (outfmt.find("%m") != string::npos) {
int algo_id = 0;
size_t i = outfmt.find("%m") + 2;
bool found = false;
while (i < outfmt.size()
&& outfmt[i] >= '0' && outfmt[i] <= '9') {
algo_id = algo_id * 10 + (outfmt[i] - '0');
outfmt.erase(i, 1);
found = true;
}
if (!found) {
NCBI_THROW(CInputException, eInvalidInput,
"The option '-outfmt %m' is not followed by a masking algo ID.");
}
conf.m_FmtAlgoId = algo_id;
}
}
bool errors_found = false;
CSeqFormatter seq_fmt(outfmt, *m_BlastDb, out, conf);
/* Special case: full db dump when no range and mask data is specified */
if (m_FASTA &&
args["entry"].HasValue() && args["entry"].AsString() == "all" &&
! args["mask_sequence_with"].HasValue() &&
! args["range"].HasValue()) {
try {
seq_fmt.DumpAll(*m_BlastDb, conf);
} catch (const CException& e) {
ERR_POST(Error << e.GetMsg());
errors_found = true;
} catch (...) {
ERR_POST(Error << "Failed to retrieve requested item");
errors_found = true;
}
return errors_found ? 1 : 0;
}
if (args["entry_batch"].HasValue()) {
return x_ProcessBatchEntry(args, seq_fmt);
}
TQueries queries;
errors_found = (x_GetQueries(queries) > 0 ? true : false);
_ASSERT( !queries.empty() );
NON_CONST_ITERATE(TQueries, itr, queries) {
try {
seq_fmt.Write(**itr);
} catch (const CException& e) {
ERR_POST(Error << e.GetMsg());
errors_found = true;
} catch (...) {
ERR_POST(Error << "Failed to retrieve requested item");
errors_found = true;
}
}
return errors_found ? 1 : 0;
}
int CBlastDBCmdApp::x_ProcessBatchEntry(const CArgs& args, CSeqFormatter & seq_fmt)
{
CNcbiIstream& input = args["entry_batch"].AsInputFile();
bool err_found = false;
while (input) {
string line;
NcbiGetlineEOL(input, line);
if ( !line.empty() ) {
vector<string> tmp;
NStr::Tokenize(line, " \t", tmp, NStr::fSplit_MergeDelims);
if(tmp.empty())
continue;
TQueries queries;
if(x_AddSeqId(queries, tmp[0]) > 0 )
err_found = true;
if(queries.empty())
continue;
TSeqRange seq_range(TSeqRange::GetEmpty());
ENa_strand seq_strand = eNa_strand_plus;
int seq_algo_id = -1;
for(unsigned int i=1; i < tmp.size(); i++) {
if(tmp[i].find('-')!= string::npos)
{
try {
seq_range = ParseSequenceRangeOpenEnd(tmp[i]);
} catch (...) {
seq_range = TSeqRange::GetEmpty();
}
}
else if (!m_DbIsProtein && NStr::EqualNocase(tmp[i].c_str(), "minus")) {
seq_strand = eNa_strand_minus;
}
else {
seq_algo_id = NStr::StringToNonNegativeInt(tmp[i]);
}
}
seq_fmt.SetConfig(seq_range, seq_strand, seq_algo_id);
NON_CONST_ITERATE(TQueries, itr, queries) {
try {
seq_fmt.Write(**itr);
} catch (const CException& e) {
ERR_POST(Error << e.GetMsg());
err_found = true;
} catch (...) {
ERR_POST(Error << "Failed to retrieve requested item");
err_found = true;
}
}
}
}
return err_found ? 1:0;
}
void CBlastDBCmdApp::Init()
{
HideStdArgs(fHideConffile | fHideFullVersion | fHideXmlHelp | fHideDryRun);
auto_ptr<CArgDescriptions> arg_desc(new CArgDescriptions);
// Specify USAGE context
arg_desc->SetUsageContext(GetArguments().GetProgramBasename(),
"BLAST database client, version " + CBlastVersion().Print());
arg_desc->SetCurrentGroup("BLAST database options");
arg_desc->AddDefaultKey(kArgDb, "dbname", "BLAST database name",
CArgDescriptions::eString, "nr");
arg_desc->AddDefaultKey(kArgDbType, "molecule_type",
"Molecule type stored in BLAST database",
CArgDescriptions::eString, "guess");
arg_desc->SetConstraint(kArgDbType, &(*new CArgAllow_Strings,
"nucl", "prot", "guess"));
arg_desc->SetCurrentGroup("Retrieval options");
arg_desc->AddOptionalKey("entry", "sequence_identifier",
"Comma-delimited search string(s) of sequence identifiers"
":\n\te.g.: 555, AC147927, 'gnl|dbname|tag', or 'all' "
"to select all\n\tsequences in the database",
CArgDescriptions::eString);
arg_desc->AddOptionalKey("entry_batch", "input_file",
"Input file for batch processing (Format: one entry per line, seq id \n"
"followed by optional space-delimited specifier(s) [range|strand|mask_algo_id]",
CArgDescriptions::eInputFile);
arg_desc->SetDependency("entry_batch", CArgDescriptions::eExcludes, "entry");
arg_desc->SetDependency("entry_batch", CArgDescriptions::eExcludes, "range");
arg_desc->SetDependency("entry_batch", CArgDescriptions::eExcludes, "strand");
arg_desc->SetDependency("entry_batch", CArgDescriptions::eExcludes, "mask_sequence_with");
arg_desc->AddOptionalKey("pig", "PIG", "PIG to retrieve",
CArgDescriptions::eInteger);
arg_desc->SetConstraint("pig", new CArgAllowValuesGreaterThanOrEqual(0));
arg_desc->SetDependency("pig", CArgDescriptions::eExcludes, "entry");
arg_desc->SetDependency("pig", CArgDescriptions::eExcludes, "entry_batch");
arg_desc->SetDependency("pig", CArgDescriptions::eExcludes, "target_only");
arg_desc->AddFlag("info", "Print BLAST database information", true);
// All other options to this program should be here
const char* exclusions[] = { "entry", "entry_batch", "outfmt", "strand",
"target_only", "ctrl_a", "get_dups", "pig", "range",
"mask_sequence", "list", "remove_redundant_dbs", "recursive",
"list_outfmt" };
for (size_t i = 0; i < sizeof(exclusions)/sizeof(*exclusions); i++) {
arg_desc->SetDependency("info", CArgDescriptions::eExcludes,
string(exclusions[i]));
}
arg_desc->SetCurrentGroup("Sequence retrieval configuration options");
arg_desc->AddOptionalKey("range", "numbers",
"Range of sequence to extract in 1-based offsets "
"(Format: start-stop, for start to end of sequence use start - )",
CArgDescriptions::eString);
arg_desc->AddDefaultKey("strand", "strand",
"Strand of nucleotide sequence to extract",
CArgDescriptions::eString, "plus");
arg_desc->SetConstraint("strand", &(*new CArgAllow_Strings, "minus",
"plus"));
arg_desc->AddOptionalKey("mask_sequence_with", "mask_algo_id",
"Produce lower-case masked FASTA using the "
"algorithm ID specified",
CArgDescriptions::eInteger);
arg_desc->SetCurrentGroup("Output configuration options");
arg_desc->AddDefaultKey(kArgOutput, "output_file", "Output file name",
CArgDescriptions::eOutputFile, "-");
arg_desc->AddDefaultKey("outfmt", "format",
"Output format, where the available format specifiers are:\n"
"\t\t%f means sequence in FASTA format\n"
"\t\t%s means sequence data (without defline)\n"
"\t\t%a means accession\n"
"\t\t%g means gi\n"
"\t\t%o means ordinal id (OID)\n"
"\t\t%i means sequence id\n"
"\t\t%t means sequence title\n"
"\t\t%l means sequence length\n"
"\t\t%h means sequence hash value\n"
"\t\t%T means taxid\n"
"\t\t%e means membership integer\n"
"\t\t%L means common taxonomic name\n"
"\t\t%S means scientific name\n"
#if _BLAST_DEBUG
"\t\t%B means BLAST name\n" /* Is this useful outside NCBI? */
#endif /* _BLAST_DEBUG */
"\t\t%K means taxonomic super kingdom\n"
"\t\t%P means PIG\n"
#if _BLAST_DEBUG
"\t\t%d means defline in text ASN.1 format\n"
"\t\t%b means Bioseq in text ASN.1 format\n"
#endif /* _BLAST_DEBUG */
"\t\t%m means sequence masking data.\n"
"\t\t Masking data will be displayed as a series of 'N-M' values\n"
"\t\t separated by ';' or the word 'none' if none are available.\n"
#if _BLAST_DEBUG
"\tIf '%f' or '%d' are specified, all other format specifiers are ignored.\n"
"\tFor every format except '%f' and '%d', each line of output will "
#else
"\tIf '%f' is specified, all other format specifiers are ignored.\n"
"\tFor every format except '%f', each line of output will "
#endif /* _BLAST_DEBUG */
"correspond\n\tto a sequence.\n",
CArgDescriptions::eString, "%f");
//arg_desc->AddDefaultKey("target_only", "value",
// "Definition line should contain target gi only",
// CArgDescriptions::eBoolean, "false");
arg_desc->AddFlag("target_only",
"Definition line should contain target entry only", true);
//arg_desc->AddDefaultKey("get_dups", "value",
// "Retrieve duplicate accessions",
// CArgDescriptions::eBoolean, "false");
arg_desc->AddFlag("get_dups", "Retrieve duplicate accessions", true);
arg_desc->SetDependency("get_dups", CArgDescriptions::eExcludes,
"target_only");
arg_desc->SetCurrentGroup("Output configuration options for FASTA format");
arg_desc->AddDefaultKey("line_length", "number", "Line length for output",
CArgDescriptions::eInteger,
NStr::IntToString(CSeqFormatterConfig().m_LineWidth));
arg_desc->SetConstraint("line_length",
new CArgAllowValuesGreaterThanOrEqual(1));
arg_desc->AddFlag("ctrl_a",
"Use Ctrl-A as the non-redundant defline separator",true);
const char* exclusions_discovery[] = { "entry", "entry_batch", "outfmt",
"strand", "target_only", "ctrl_a", "get_dups", "pig", "range", kArgDb.c_str(),
"info", "mask_sequence", "line_length" };
arg_desc->SetCurrentGroup("BLAST database configuration and discovery options");
arg_desc->AddFlag("show_blastdb_search_path",
"Displays the default BLAST database search paths", true);
arg_desc->AddOptionalKey("list", "directory",
"List BLAST databases in the specified directory",
CArgDescriptions::eString);
arg_desc->AddFlag("remove_redundant_dbs",
"Remove the databases that are referenced by another "
"alias file in the directory in question", true);
arg_desc->AddFlag("recursive",
"Recursively traverse the directory structure to list "
"available BLAST databases", true);
arg_desc->AddDefaultKey("list_outfmt", "format",
"Output format for the list option, where the available format specifiers are:\n"
"\t\t%f means the BLAST database absolute file name path\n"
"\t\t%p means the BLAST database molecule type\n"
"\t\t%t means the BLAST database title\n"
"\t\t%d means the date of last update of the BLAST database\n"
"\t\t%l means the number of bases/residues in the BLAST database\n"
"\t\t%n means the number of sequences in the BLAST database\n"
"\t\t%U means the number of bytes used by the BLAST database\n"
"\tFor every format each line of output will "
"correspond to a BLAST database.\n",
CArgDescriptions::eString, "%f %p");
for (size_t i = 0; i <
sizeof(exclusions_discovery)/sizeof(*exclusions_discovery); i++) {
arg_desc->SetDependency("list", CArgDescriptions::eExcludes,
string(exclusions_discovery[i]));
arg_desc->SetDependency("recursive", CArgDescriptions::eExcludes,
string(exclusions_discovery[i]));
arg_desc->SetDependency("remove_redundant_dbs", CArgDescriptions::eExcludes,
string(exclusions_discovery[i]));
arg_desc->SetDependency("list_outfmt", CArgDescriptions::eExcludes,
string(exclusions_discovery[i]));
arg_desc->SetDependency("show_blastdb_search_path", CArgDescriptions::eExcludes,
string(exclusions_discovery[i]));
}
arg_desc->SetDependency("show_blastdb_search_path", CArgDescriptions::eExcludes,
"list");
arg_desc->SetDependency("show_blastdb_search_path", CArgDescriptions::eExcludes,
"recursive");
arg_desc->SetDependency("show_blastdb_search_path", CArgDescriptions::eExcludes,
"list_outfmt");
arg_desc->SetDependency("show_blastdb_search_path", CArgDescriptions::eExcludes,
"remove_redundant_dbs");
SetupArgDescriptions(arg_desc.release());
}
int CBlastDBCmdApp::Run(void)
{
int status = 0;
const CArgs& args = GetArgs();
// Silences warning in CSeq_id for CSeq_id::fParse_PartialOK
SetDiagFilter(eDiagFilter_Post, "!(1306.10)");
try {
CNcbiOstream& out = args["out"].AsOutputFile();
if (args["show_blastdb_search_path"]) {
out << CSeqDB::GenerateSearchPath() << NcbiEndl;
return status;
} else if (args["list"]) {
const string& blastdb_dir = args["list"].AsString();
const bool recurse = args["recursive"];
const bool remove_redundant_dbs = args["remove_redundant_dbs"];
const string dbtype = args[kArgDbType]
? args[kArgDbType].AsString()
: "guess";
const string& kOutFmt = args["list_outfmt"].AsString();
const vector<SSeqDBInitInfo> dbs =
FindBlastDBs(blastdb_dir, dbtype, recurse, true,
remove_redundant_dbs);
CBlastDbFormatter blastdb_fmt(kOutFmt);
ITERATE(vector<SSeqDBInitInfo>, db, dbs) {
out << blastdb_fmt.Write(*db) << NcbiEndl;
}
return status;
}
x_InitApplicationData();
if (args["info"]) {
x_PrintBlastDatabaseInformation();
} else {
status = x_ProcessSearchRequest();
}
} CATCH_ALL(status)
return status;
}
#ifndef SKIP_DOXYGEN_PROCESSING
int main(int argc, const char* argv[] /*, const char* envp[]*/)
{
return CBlastDBCmdApp().AppMain(argc, argv, 0, eDS_Default, 0);
}
#endif /* SKIP_DOXYGEN_PROCESSING */
| [
"jackgopack4@gmail.com"
] | jackgopack4@gmail.com |
eb9074562d943d32d32d1a108f72f13c323e6e65 | 7f3b555023324f901499b6524cbda92dffbc216a | /src/ImportExport/Utils.hxx | bdca1f8713e1405c9120ad1bef04015dae2b41fe | [
"LicenseRef-scancode-generic-cla",
"MIT",
"LicenseRef-scancode-khronos",
"Zlib",
"CC0-1.0",
"Unlicense",
"BSD-3-Clause"
] | permissive | adam-urbanczyk/CADRays | 0535facf363ead0748ea8fefa5a738906a83c4a1 | b6b6dff7bbcaae9ebf1fe079459ea17eda1a3827 | refs/heads/master | 2022-01-19T23:44:40.547114 | 2019-07-23T10:42:34 | 2019-07-23T10:42:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,823 | hxx | // Created: 2016-12-08
//
// Copyright (c) 2019 OPEN CASCADE SAS
//
// This file is a part of CADRays software.
//
// CADRays is free software; you can use it under the terms of the MIT license,
// refer to file LICENSE.txt for complete text of the license and disclaimer of
// any warranty.
#ifndef _RT_Utils_Header
#define _RT_Utils_Header
#include <AIS_Shape.hxx>
#include <AIS_TexturedShape.hxx>
namespace model
{
//! Tool class to provide access to textured shape.
class TexturedShape : public AIS_TexturedShape
{
public:
//! Returns 2D texture map applied.
const Handle (Graphic3d_Texture2Dmanual)& Texture ()
{
return myTexture;
}
//! Returns graphic attributes used.
const Handle (Graphic3d_AspectFillArea3d)& Aspect ()
{
return myAspect;
}
//! Updates material to the given one.
void UpdateMaterial (const Graphic3d_MaterialAspect& theMaterial);
//! Replaces current graphic aspect to the given one.
void SetGraphicAspect (const Handle (Graphic3d_AspectFillArea3d)& theAspect);
public:
//! Converts the given AIS object to textured shape.
Standard_EXPORT static TexturedShape* Create (const Handle (AIS_InteractiveObject)& theObject);
};
//! Returns graphic aspect of the given AIS object.
Standard_EXPORT Graphic3d_AspectFillArea3d* GetAspect (const Handle (AIS_InteractiveObject)& theObject);
//! Applies the given material to the given AIS object.
Standard_EXPORT void SetMaterial (const Handle (AIS_InteractiveObject)& theObject, const Graphic3d_MaterialAspect& theMaterial);
//! Applies the given graphic aspect to the given AIS object.
Standard_EXPORT void SetAspect (const Handle (AIS_InteractiveObject)& theObject, const Handle (Graphic3d_AspectFillArea3d)& theAspect);
}
#endif // _RT_Utils_Header
| [
"saso.badovinac@gmail.com"
] | saso.badovinac@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.