text
stringlengths 8
6.88M
|
|---|
#include "Motorbike.h"
Motorbike::Motorbike(){}
Motorbike::Motorbike(int id, std::string name, int posX, int posY) {
this->_id = id;
this->_name = name;
this->_posX = posX;
this->_posY = posY;
}
|
#ifndef CAUHOI_H
#define CAUHOI_H
#include <string>
using std::string;
enum QA{
A = 0,
B,
C,
D
};
class CauHoi
{
public:
CauHoi();
virtual ~CauHoi();
int id() const;
void setId(int id);
string maMH() const;
void setMaMH(const string &maMH);
string noiDung() const;
void setNoiDung(const string &noiDung);
void setLuaChon(QA luachon, string noidung);
string getLuaChon(QA luachon) const;
QA ketQua() const;
void setKetQua(const QA &ketQua);
private:
int m_id;
string m_maMH;
string m_noiDung;
string m_A;
string m_B;
string m_C;
string m_D;
QA m_ketQua;
};
#endif // CAUHOI_H
|
#include "ros/ros.h"
#include "std_msgs/String.h"
#include "beginner_tutorials/stu.h"
void chatterCallback(const beginner_tutorials::stu::ConstPtr& msg)
{
ROS_INFO("name and date: [%s] [%d] ", msg->name.c_str(),msg->date);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "listener");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
ros::spin();
return 0;
}
|
#include<iostream>
using namespace std;
// 深拷贝和浅拷贝
// 浅拷贝:简单的复制拷贝操作
// 深拷贝:在堆区重新申请空间进行拷贝操作
class Person
{
public:
Person()
{
cout<<"Person的默认构造函数调用"<<endl;
}
Person(int age)
{
m_age = age;
cout<<"Person的有参构造函数调用"<<endl;
}
Person(int age,int height)
{
m_age = age;
m_height =new int(height);
cout<<"Person的有参构造函数重载调用"<<endl;
}
Person(const Person & p)
{
m_age = p.m_age;
// m_height = p.m_height;//编译器默认执行的但是会有冲突的代码
m_height = new int (*p.m_height);
cout<<"Person拷贝构造函数"<<endl;
}
~Person()
{
//析构代码,将堆区开辟的数据做释放
//浅拷贝的问题是,堆区的内存重复释放
if(m_height != NULL)
{
delete m_height;
m_height = NULL;
}
cout<<"Person的析构函数调用"<<endl;
}
int m_age;
int *m_height;
};
void test01()
{
Person p1;
p1.m_age = 10;
cout<<p1.m_age<<endl;
Person p2(p1);
//虽然没有写拷贝构造函数,但是编译器会提供默认拷贝构造函数实现浅拷贝
cout<<p2.m_age<<endl;
}
void test02()
{
Person p3(11,160);
cout<<p3.m_age<<" "<<*(p3.m_height)<<endl;
Person p4(p3);
//虽然没有写拷贝构造函数,但是编译器会提供默认拷贝构造函数实现浅拷贝
cout<<p4.m_age<<" "<<*(p4.m_height)<<endl;
}
int main()
{
// test01();
test02();
return 0;
}
|
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin ("ssm.in");
ofstream fout ("ssm.out");
int main()
{
long long int n, i, mx_val, mx_index, s=0;
fin>>n;
long long int arr[n+1], prev_val;
for(i=0;i<n;i++)
fin>>arr[i];
prev_val = arr[0];
mx_val = prev_val;
mx_index = 0;
//cout<<prev_val<<' ' ;
for(i=1;i<n;i++)
{
if(prev_val+arr[i] < arr[i])
prev_val = arr[i];
else
prev_val = prev_val + arr[i];
// cout<<prev_val<<' ' ;
if(mx_val < prev_val)
{
mx_val = prev_val;
mx_index = i;
}
}
//cout<<'\n';
i = mx_index;
s = arr[i];
while(s != mx_val || arr[i-1] == 0)
{
i--;
s += arr[i];
}
fout<<mx_val<<' '<<i+1<<' '<<mx_index+1;
}
|
#include <iostream>
#include <string>
#include <math.h>
#include "../meteor/process_meteor.h"
#include "./tdefs.h"
#include <fst/fstlib.h>
//maximum difference between generated path and averagge
const int MAX_LEN_DIFF = 5;
float penaltyFunction(float expected, int actual) {
return pow((expected - actual),2);
}
class PathData {
private:
Label *labels;
int maxLen;
size_t len;
Weight weight;
Weight newWeight;
int ranking;
std::string path;
void makePath(std::string **sparseLabels);
float lengthPenalise(float avgLen) { return penaltyFunction(avgLen, this->pathLen); };
Weight fixWeight(float avgLen) { return (newWeight = weight.Value() + lengthPenalise(avgLen)); }
size_t pathLen;
public:
explicit PathData(int maxStates);
~PathData() { delete[] labels; };
void operator=(const PathData &orig);
size_t getLen() { return len; };
// size_t lenActual();
Weight getWeight() { return weight; };
Weight getNewWeight() { return newWeight; };
int getRank() { return ranking; };
size_t getPathLen() { return pathLen; };
size_t addLabel(Label l) { labels[len++] = l; return len; };
Weight addWeight(const Weight &addW) { return (weight = weight.Value() + addW.Value()); };
void setRank(int r) { ranking = r; };
void print(std::string prefix);
void finalise(float avgLength, std::string **sparseLabels);
std::string getPath() { return path; };
};
PathData::PathData(int maxStates) {
if(maxStates > 0) {
this->labels = new Label[maxStates];
this->maxLen = maxStates;
this->len=0; this->weight=0;
this->ranking = this->maxLen; // at most maxLen-1 (eventually; arcs# < states#)
for(int i=0; i<maxStates; i++)
labels[i] = 0;
}
}
void PathData::finalise(float avgLength, std::string **sparseLabels) {
fixWeight(avgLength);
makePath(sparseLabels);
}
void PathData::makePath(std::string **sparseLabels) {
std::string out = "";
this->pathLen=0;
for(int i=0; i<len; i++)
if(labels[i] != 0) {
this->pathLen++;
out += *sparseLabels[labels[i]] + " ";
}
this->path = out;
}
void PathData::operator=(const PathData &orig) {
this->maxLen = orig.maxLen;
this->len = orig.len;
this->weight = orig.weight;
this->ranking = orig.ranking;
// labels length could be len but do maxlen for consistency
this->labels = new Label[this->maxLen]; // DYN! //
for(int i=0; i<len; i++)
this->labels[i] = orig.labels[i];
}
void PathData::print(std::string prefix="\t") {
std::cerr << prefix << "Max length: " << maxLen << std::endl;
std::cerr << prefix << "(Length): " << len << std::endl;
std::cerr << prefix << "Actual len: " << pathLen << std::endl;
std::cerr << prefix << "Weight: " << weight << std::endl;
std::cerr << prefix << "Ranking: " << ranking << std::endl;
for(int i=0; i<len; i++)
std::cerr << prefix << "labels["<<i<<"]: " << labels[i] << std::endl;
}
class Finals {
private:
int finalCount;
int maxCount;
StateId *finalStates;
SVF *cn;
void getFinalStates();
public:
Finals(SVF *cn, int maxStates): cn(cn), maxCount(maxStates) {
getFinalStates(); };
bool checkFinal(StateId state);
~Finals() { delete[] finalStates; };
int getFC() { return finalCount; };//temp
};
void Finals::getFinalStates() {
this->finalStates = new StateId[this->maxCount];
int i=0;
for(fst::StateIterator<SVF> siter(*cn); !siter.Done(); siter.Next()) {
StateId s = siter.Value();
if(cn->Final(s) != Weight::Zero()) {
this->finalStates[i++] = s;
}
}
this->finalCount = i;
}
bool Finals::checkFinal(StateId state) {
for(int i=0; i<this->finalCount; i++) {
if(state == this->finalStates[i])
return true;
}
return false;
}
void recPathFind(PathData *currentPath, PathData **paths, int *pathCount,
SVF* cn, StateId state, Finals *finals,
float avgLen, std::string **sparseLabels) {
if(finals->checkFinal(state)) {
currentPath->finalise(avgLen, sparseLabels);
if(abs(avgLen - currentPath->getPathLen()) <= MAX_LEN_DIFF) { //only add if it's withing bounds
paths[(*pathCount)++] = currentPath;
std::cout << currentPath->getNewWeight() << " | " << currentPath->getWeight() << " | "<<currentPath->getPath()<< std::endl;
}
PathData *newPath;
for(fst::ArcIterator<SVF> aiter(*cn, state); !aiter.Done(); aiter.Next()) {
const fst::StdArc &arc = aiter.Value();
newPath = new PathData(0);
*newPath = *currentPath;
newPath->addLabel(arc.ilabel);
newPath->addWeight(arc.weight);
recPathFind(newPath, paths, pathCount, cn, arc.nextstate, finals, avgLen, sparseLabels);
}
}
int getPaths(SVF *cn, Finals *finals, PathData **paths, int n,
float avgLen, std::string **sparseLabels) {
/*/ For a given shortestpaths CN, find the strings, path lengths, and path weights,
* and return the actual number of paths (out of a maximum of n). Do this by
* recursive function calls */
StateId initialState = cn->Start();
PathData *initialPath = paths[0]; //default and will also be overwritten
int pathCount=0; int *pc = &pathCount;
recPathFind(initialPath, paths, pc,
cn, initialState, finals,
avgLen, sparseLabels);
return *pc;
}
void getBest(SVF* cn, int nBest, int nBestFinal, int maxStates, float avgLength,std::string **sparseLabels) {
SVF nBestCN;
fst::ShortestPath(*cn, &nBestCN, nBest, true); // true: unique only
nBestCN.Write("paths.cn");
PathData **paths = new PathData*[nBest];
for(int i=0; i < nBest; i++) {
paths[i] = new PathData(maxStates);
}
Finals finals(&nBestCN, maxStates);
int nActual = getPaths(&nBestCN, &finals, paths, nBest,
avgLength, sparseLabels);
std::cerr << "MAX PATHS: " << nBest << ", ACTUAL: " << nActual << std::endl;
// for(int i=0; i<nActual; i++) {
// paths[i]->finalise(avgLength, sparseLabels);
//// std::cout << i << ": "
// std::cout << paths[i]->getNewWeight() << " | " << paths[i]->getWeight() << " | "<<paths[i]->getPath()<< std::endl;
// }
}
|
#include "plane.h"
Plane::Plane() {}
Hit Plane::intersect(Ray& ray) {
float t = 0.0;
t = (-ray.origin.y - 1.0) / ray.direction.y;
Vec3 p = ray.getPosition(t);
Vec3 n = {0.0, 1.0, 0.0};
return Hit{p, n};
}
|
// Plots.h
// Created by Isaac Mooney on 7/23/18.
// A bunch of functions to make plotting more automated and less repetitive
#ifndef Plots_h
#define Plots_h
#include "TROOT.h"
#include <string>
#include <iostream>
#include <vector>
//constructs canvas
//second argument is: 0 = no log, 1 = logx, 2 = logy, 3 = logz (or combinations thereof)
TCanvas * MakeCanvas(const std::string can_name, const std::string log_scale, const double xdim, const double ydim) {
TCanvas * can = new TCanvas ((can_name).c_str(),(can_name).c_str(),xdim,ydim);
//set desired axes' log scales
if (log_scale.find("1") != std::string::npos || log_scale.find("x") != std::string::npos || log_scale.find("X") != std::string::npos) {can->SetLogx();}
if (log_scale.find("2") != std::string::npos || log_scale.find("y") != std::string::npos || log_scale.find("Y") != std::string::npos) {can->SetLogy();}
if (log_scale.find("3") != std::string::npos || log_scale.find("z") != std::string::npos || log_scale.find("Z") != std::string::npos) {can->SetLogz();}
if (log_scale.find("0") != std::string::npos) {can->SetLogx(0); can->SetLogy(0); can->SetLogz(0);}
return can;
}
//divides existing canvas into multiple (rows*cols) panels
void DivideCanvas(TCanvas *can, const std::string log_scale, const unsigned rows, const unsigned cols) {
can->Divide(rows, cols, 0, 0);
for (unsigned i = 1; i <= cols*rows; ++ i) {
can->cd(i);
if (log_scale.find("1") != std::string::npos || log_scale.find("x") != std::string::npos || log_scale.find("X") != std::string::npos) {gPad->SetLogx();}
if (log_scale.find("2") != std::string::npos || log_scale.find("y") != std::string::npos || log_scale.find("Y") != std::string::npos) {gPad->SetLogy();}
if (log_scale.find("3") != std::string::npos || log_scale.find("z") != std::string::npos || log_scale.find("Z") != std::string::npos) {gPad->SetLogz();}
if (log_scale.find("0") != std::string::npos) {gPad->SetLogx(0); gPad->SetLogy(0); gPad->SetLogz(0);}
}
return;
}
//projects a 3D histogram in desired ranges and returns an array of the (2D) projections on desired axis
//For 3D plots, have to use SetRange instead of SetRangeUser for some stupid reason. => pass bin numbers instead of bin values to the function
std::vector<TH2D*> Projection3D (TH3D * hist3D, const int nBins, int * ranges, const std::string axis) {
std::vector<TH2D*> proj2Ds;
for (int i = 0; i < nBins; ++ i) {
std::string low = std::to_string(ranges[i]);
std::string high = std::to_string(ranges[i+1]);
std::string low_rough = low.substr(0,2);
std::string high_rough = high.substr(0,2);
if (low_rough.substr(1,2) == ".") {low_rough = low_rough.substr(0,1);}
if (high_rough.substr(1,2) == ".") {high_rough = high_rough.substr(0,1);}
if (axis == "xy") {
hist3D->GetZaxis()->SetRange(ranges[i],ranges[i+1]);
proj2Ds.push_back((TH2D*) hist3D->Project3D((hist3D->GetName() + axis +"e"+ low_rough + high_rough).c_str()));
}
else if (axis == "yx") {
hist3D->GetZaxis()->SetRange(ranges[i],ranges[i+1]);
proj2Ds.push_back((TH2D*) hist3D->Project3D((hist3D->GetName() + axis +"e"+ low_rough + high_rough).c_str()));
}
else if (axis == "yz") {
hist3D->GetXaxis()->SetRange(ranges[i],ranges[i+1]);
proj2Ds.push_back((TH2D*) hist3D->Project3D((hist3D->GetName() + axis +"e"+ low_rough + high_rough).c_str()));
}
else if (axis == "zy") {
hist3D->GetXaxis()->SetRange(ranges[i],ranges[i+1]);
proj2Ds.push_back((TH2D*) hist3D->Project3D((hist3D->GetName() + axis +"e"+ low_rough + high_rough).c_str()));
}
else if (axis == "xz") {
hist3D->GetYaxis()->SetRange(ranges[i],ranges[i+1]);
proj2Ds.push_back((TH2D*) hist3D->Project3D((hist3D->GetName() + axis +"e"+ low_rough + high_rough).c_str()));
}
else if (axis == "zx") {
hist3D->GetYaxis()->SetRange(ranges[i],ranges[i+1]);
proj2Ds.push_back((TH2D*) hist3D->Project3D((hist3D->GetName() + axis +"e"+ low_rough + high_rough).c_str()));
}
else {
std::cerr << "Improper axis given for projections. Exiting." << std::endl; exit(1);
}
proj2Ds[i]->SetTitle("");
}
return proj2Ds;
}
//projects a 2D histogram in desired ranges and returns an array of the (1D) projections on desired axis
std::vector<TH1D*> Projection2D (TH2D * hist2D, const int nBins, double * ranges, const std::string axis) {
std::vector<TH1D*> proj1Ds;
for (int i = 0; i < nBins; ++ i) {
std::string low = std::to_string(ranges[i]);
std::string high = std::to_string(ranges[i+1]);
std::string low_rough = low.substr(0,2);
std::string high_rough = high.substr(0,2);
if (low_rough.substr(1,2) == ".") {low_rough = low_rough.substr(0,1);}
if (high_rough.substr(1,2) == ".") {high_rough = high_rough.substr(0,1);}
if (axis == "x" || axis == "X" || axis == "1") {
proj1Ds.push_back(hist2D->ProjectionX((hist2D->GetName() + axis + low_rough + high_rough).c_str(),ranges[i],ranges[i+1]));
}
else if (axis == "y" || axis == "Y" || axis == "2") {
proj1Ds.push_back(hist2D->ProjectionY((hist2D->GetName() + axis + low_rough + high_rough).c_str(),ranges[i],ranges[i+1]));
}
else {
std::cerr << "Improper axis given for projections. Exiting." << std::endl; exit(1);
}
proj1Ds[i]->SetTitle("");
}
return proj1Ds;
}
//prettify 1D histogram
void Prettify1D (TH1D * hist, const Color_t markColor, const Style_t markStyle, const double markSize, const Color_t lineColor,
const std::string xTitle, const std::string yTitle, const double lowx, const double highx, const double lowy, const double highy) {
if (yTitle.find("1/N") != std::string::npos && yTitle.find("N_{cons}") == std::string::npos) { //|| yTitle.find("prob") != std::string::npos) {
hist->Scale(1/(double)hist->Integral());
double binwidth = (hist->GetXaxis()->GetXmax() - hist->GetXaxis()->GetXmin()) / (double) hist->GetXaxis()->GetNbins();
hist->Scale(1/(double)binwidth);
}
else if (yTitle.find("1/N") != std::string::npos && yTitle.find("N_{cons}") != std::string::npos) {
double binwidth = (hist->GetXaxis()->GetXmax() - hist->GetXaxis()->GetXmin()) / (double) hist->GetXaxis()->GetNbins();
hist->Scale(1/(double)binwidth);
}
else {
cout << "Not scaling by histogram " << hist->GetName() << "'s integral & bin width! If this is a cross section measurement, this will be a problem! Fix by passing histogram y-axis title containing anything but 'arb'" << endl;
}
hist->SetMarkerColor(markColor); hist->SetMarkerStyle(markStyle); hist->SetMarkerSize(markSize); hist->SetLineColor(lineColor);
hist->GetXaxis()->SetTitle((xTitle).c_str()); hist->GetYaxis()->SetTitle((yTitle).c_str());
if (highx != -1) {
hist->GetXaxis()->SetRangeUser(lowx, highx);
}
if (highy != -1) {
hist->GetYaxis()->SetRangeUser(lowy, highy);
}
return;
}
//prettify 1D histogram to be drawn as line with "C" option
void Prettify1DwLineStyle(TH1D * hist, const Color_t lineColor, const Style_t lineStyle, const double lineWidth,
const std::string xTitle, const std::string yTitle, const double lowx, const double highx, const double lowy, const double highy) {
if (yTitle.find("1/N") != std::string::npos && yTitle.find("N_{cons}") == std::string::npos) { //|| yTitle.find("prob") != std::string::npos) {
hist->Scale(1/(double)hist->Integral());
double binwidth = (hist->GetXaxis()->GetXmax() - hist->GetXaxis()->GetXmin()) / (double) hist->GetXaxis()->GetNbins();
hist->Scale(1/(double)binwidth);
}
else if (yTitle.find("1/N") != std::string::npos && yTitle.find("N_{cons}") != std::string::npos) {
double binwidth = (hist->GetXaxis()->GetXmax() - hist->GetXaxis()->GetXmin()) / (double) hist->GetXaxis()->GetNbins();
hist->Scale(1/(double)binwidth);
}
else {
cout << "Not scaling by histogram " << hist->GetName() << "'s integral & bin width! If this is a cross section measurement, this will be a problem! Fix by passing histogram y-axis title containing anything but 'arb'" << endl;
}
hist->SetLineColor(lineColor); hist->SetLineStyle(lineStyle); hist->SetLineWidth(lineWidth);
hist->GetXaxis()->SetTitle((xTitle).c_str()); hist->GetYaxis()->SetTitle((yTitle).c_str());
if (highx != -1) {
hist->GetXaxis()->SetRangeUser(lowx, highx);
}
if (highy != -1) {
hist->GetYaxis()->SetRangeUser(lowy, highy);
}
hist->Sumw2(0);
return;
}
//prettify 1D histogram to be drawn as line with "C" option //OVERLOADED
void Prettify1DwLineStyle(TH1D * hist, const Style_t lineStyle, const double lineWidth,
const std::string xTitle, const std::string yTitle, const double lowx, const double highx, const double lowy, const double highy) {
if (yTitle.find("1/N") != std::string::npos && yTitle.find("N_{cons}") == std::string::npos) { //|| yTitle.find("prob") != std::string::npos) {
hist->Scale(1/(double)hist->Integral());
double binwidth = (hist->GetXaxis()->GetXmax() - hist->GetXaxis()->GetXmin()) / (double) hist->GetXaxis()->GetNbins();
hist->Scale(1/(double)binwidth);
}
else if (yTitle.find("1/N") != std::string::npos && yTitle.find("N_{cons}") != std::string::npos) {
double binwidth = (hist->GetXaxis()->GetXmax() - hist->GetXaxis()->GetXmin()) / (double) hist->GetXaxis()->GetNbins();
hist->Scale(1/(double)binwidth);
}
else {
cout << "Not scaling by histogram " << hist->GetName() << "'s integral & bin width! If this is a cross section measurement, this will be a problem! Fix by passing histogram y-axis title containing anything but 'arb'" << endl;
}
hist->SetLineStyle(lineStyle); hist->SetLineWidth(lineWidth);
hist->GetXaxis()->SetTitle((xTitle).c_str()); hist->GetYaxis()->SetTitle((yTitle).c_str());
if (highx != -1) {
hist->GetXaxis()->SetRangeUser(lowx, highx);
}
if (highy != -1) {
hist->GetYaxis()->SetRangeUser(lowy, highy);
}
hist->Sumw2(0);
return;
}
//prettify TGraphErrors
void PrettifyTGraph (TGraphErrors * gr, const Color_t markColor, const Style_t markStyle, const double markSize, const Color_t lineColor,
const std::string xTitle, const std::string yTitle, const double lowx, const double highx, const double lowy, const double highy) {
gr->SetMarkerColor(markColor); gr->SetMarkerStyle(markStyle); gr->SetMarkerSize(markSize); gr->SetLineColor(lineColor);
gr->SetTitle("");
gr->GetXaxis()->SetTitle((xTitle).c_str()); gr->GetYaxis()->SetTitle((yTitle).c_str());
gr->GetXaxis()->SetRangeUser(lowx, highx);
if (highx != -1) {
gr->GetXaxis()->SetRangeUser(lowx, highx);
}
if (highy != -1) {
gr->GetYaxis()->SetRangeUser(lowy, highy);
}
return;
}
//prettify 2D histogram
void Prettify2D (TH2D * hist, const std::string xTitle, const std::string yTitle,
const double lowx, const double highx, const double lowy, const double highy, const double lowz, const double highz) {
hist->GetXaxis()->SetTitle((xTitle).c_str()); hist->GetYaxis()->SetTitle((yTitle).c_str());
if (highx != -1) {
hist->GetXaxis()->SetRangeUser(lowx, highx);
}
if (highy != -1) {
hist->GetYaxis()->SetRangeUser(lowy, highy);
}
if (highz != -1) {
hist->GetZaxis()->SetRangeUser(lowz, highz);
}
return;
}
//construct legend with data information
TLegend * TitleLegend(const double xlow, const double ylow, const double xhigh, const double yhigh) {
TLegend * leg = new TLegend(xlow,ylow,xhigh,yhigh);
leg->SetBorderSize(0);
leg->AddEntry((TObject*)0,"pp 200 GeV" /*#pi_{0} trigger > 5.4 GeV/c*/,"");
leg->AddEntry((TObject*)0,"anti-k_{T}, R = 0.4"/*2"*/,"");
leg->AddEntry((TObject*)0,"Ch+Ne jets, |#eta| < 0.6"/*"Ch rec. jets, |#eta| < 0.8, p^{cons.}_{T} < 30 GeV/c"*/,"");
leg->AddEntry((TObject*)0,"Constituents assigned m_{PDG}"/*"#phi_{rec.} #in [3#pi/4, 5#pi/4] w/r/t #phi_{trig.}"*/,"");
return leg;
}
TLatex * PanelTitle() {
TLatex *t = new TLatex();
t->SetTextAlign(11);
// t->SetTextFont(63);
t->SetTextSize(0.07);
t->DrawLatexNDC(0.2,0.65, "Pythia8 - pp 200 GeV"/*#pi_{0} trigger > 5.4 GeV/c"*/);
t->DrawLatexNDC(0.2,0.55, "anti-k_{T}, R = 0.4"/*2"*/);
t->DrawLatexNDC(0.2,0.45, "Ch+Ne jets, |#eta| < 0.6"/*"Ch rec. jets, |#eta| < 0.8"*/);
t->DrawLatexNDC(0.2,0.35,"Constituents assigned m_{PDG}"/*"#phi_{rec.} within 1/4 of #phi_{trig.} + #pi"*/);
return t;
}
//constructs a slim legend useful for one panel of a projection denoting the range projected over
TLegend * SliceLegend(const std::string title, const double xlow, const double ylow, const double xhigh, const double yhigh) {
TLegend * leg = new TLegend(xlow,ylow,xhigh,yhigh);
leg->SetBorderSize(0);
leg->AddEntry((TObject*)0,(title).c_str(),"");
return leg;
}
#endif /* Plots_h */
|
#include <stdio.h>
int main(){
int a;
scanf("%d",&a);
if(a>=90&&a<=100){
printf("A");
} else if(a>=70&&a<=89){
printf("B");
} else if(a>=40&&a<=69){
printf("C");
} else{
printf("D");
}
return 0;
}
|
/* A Bison parser, made by GNU Bison 3.0.4. */
/* Bison interface for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
#ifndef YY_YY_PARSER_HPP_INCLUDED
# define YY_YY_PARSER_HPP_INCLUDED
/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif
#if YYDEBUG
extern int yydebug;
#endif
/* "%code requires" blocks. */
#line 3 "parser.y" /* yacc.c:1909 */
#include "../Kernel/PropertyAssignment.h"
#include "../Kernel/Conjecture.h"
#include "../Kernel/Width.h"
#include <iostream>
#include <vector>
#line 52 "parser.hpp" /* yacc.c:1909 */
/* Token type. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
enum yytokentype
{
WIDTHPARAM = 258,
SEPERATOR = 259,
COMPARATOR = 260,
FILEPATH = 261,
LEFTP = 262,
RIGHTP = 263,
NAME = 264,
NEWLINE = 265,
AND = 266,
OR = 267,
IFF = 268,
IMPLIES = 269,
NOT = 270,
TRUE = 271,
FALSE = 272,
COMMENT = 273,
INTEGER = 274
};
#endif
/* Value type. */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
union YYSTYPE
{
#line 31 "parser.y" /* yacc.c:1909 */
PropertyAssignment *property;
ConjectureNode *conjecture;
int number;
char* string;
#line 91 "parser.hpp" /* yacc.c:1909 */
};
typedef union YYSTYPE YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define YYSTYPE_IS_DECLARED 1
#endif
/* Location type. */
#if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED
typedef struct YYLTYPE YYLTYPE;
struct YYLTYPE
{
int first_line;
int first_column;
int last_line;
int last_column;
};
# define YYLTYPE_IS_DECLARED 1
# define YYLTYPE_IS_TRIVIAL 1
#endif
extern YYSTYPE yylval;
extern YYLTYPE yylloc;
int yyparse (std::vector<PropertyAssignment*> &pl, Conjecture &conj, Width &w, int &result);
#endif /* !YY_YY_PARSER_HPP_INCLUDED */
|
#ifndef __DUI_TREEVIEW_H__
#define __DUI_TREEVIEW_H__
#pragma once
/*#include "DUIControlBase.h"*/
#include "DUICanvas.h"
#include "DUIControlContainer.h"
#include "DUIButton.h"
DUI_BGN_NAMESPCE
#define KEEP_TREE_STRU 0
class IDUITreeViewItem;
class CDUITreeNode;
class IDUITreeView;
class CDUITreeViewImpl;
typedef CDUITreeNode* HDUITREEITEM;
class DUILIB_API IDUITreeViewItem /*: public CDUIControlBase*/
:public CDUIButton
{
public:
virtual void SetItemHeight(INT nHeight) = 0;
virtual INT GetItemHeight() = 0;
};
class DUILIB_API CDUITreeNode : public IDUITreeViewItem
{
public:
//IDUITreeViewItem
virtual void SetItemHeight(INT nHeight);
virtual INT GetItemHeight() ;
typedef IDUITreeViewItem theBase;
CDUITreeNode();
virtual ~CDUITreeNode();
virtual LPVOID GetInterface(const CDUIString& strName);
virtual CRefPtr<IDUIControl> Clone();
virtual VOID SetControlRect(const RECT& rt);
virtual VOID DoPaint(HDC dc, const RECT& rtDraw);
BOOL IsParent();
BOOL IsExpand();
BOOL SetExpand(BOOL bExpand);
INT GetTotalHeight();
//HDUITREEITEM GetTopItem(INT nOffsetY);
//! root is 1, child is 2, then +++
INT GetLevel();
BOOL HaveChild();
HDUITREEITEM GetParent();
HDUITREEITEM GetNextSibling();
HDUITREEITEM GetPrevSibling();
HDUITREEITEM GetFirstChild();
HDUITREEITEM GetChild(int nIndex);
void SetSel(BOOL bSel);
BOOL IsSelected();
virtual LRESULT ProcessEvent(const DUIEvent& info, BOOL& bHandled);
void FireNotifyToTreeView(const DUIEvent& event,BOOL& bHandled);
VOID SetAttribute(const CDUIString& strName, const CDUIString& strValue);
protected:
BOOL m_bExpand;
INT m_nItemHeight;
BOOL m_bSelected;
//CDUITreeViewImpl *m_lpTreeViewImpl;
CRefPtr<CImageList> m_pImgListBK;
CRefPtr<CImageList> m_pImgListIcon;
};
class DUILIB_API IDUITreeView : public CDUIControlBase
{
public:
virtual HDUITREEITEM AddRoot(HDUITREEITEM hItem) = 0;
virtual HDUITREEITEM AddChildItem(HDUITREEITEM hParent , HDUITREEITEM hChild) = 0;
virtual HDUITREEITEM GetTopItem() = 0;
virtual HDUITREEITEM GetRoot() = 0;
};
//////////////////////////////////////////////////////////////////////////
//implementation of treeview
//////////////////////////////////////////////////////////////////////////
class DUILIB_API CDUITreeViewImpl : public IDUITreeView
{
public:
typedef IDUITreeView theBase;
//IDUITreeView
virtual HDUITREEITEM AddRoot(HDUITREEITEM hItem) ;
virtual HDUITREEITEM AddChildItem(HDUITREEITEM hParent , HDUITREEITEM hChild) ;
virtual HDUITREEITEM GetTopItem();
virtual HDUITREEITEM GetRoot();
virtual CRefPtr<IDUIControl> Clone();
CDUITreeViewImpl();
virtual ~CDUITreeViewImpl();
virtual VOID SetControlRect(const RECT& rt);
virtual LRESULT ProcessEvent(const DUIEvent& info, BOOL& bHandled);
virtual LPVOID GetInterface(const CDUIString& strName);
virtual VOID DoPaint(HDC dc, const RECT& rtDraw);
virtual IDUIControl* FindControl(FINDCONTROLPROC Proc, LPVOID pData, UINT uFlags);
INT CalculateTotalHeight();
HDUITREEITEM CalculateTopItem();
HDUITREEITEM CalculateTopItem(HDUITREEITEM pItem,INT& nTempY,INT nOffsetY);
//! find the next visible item according to pItem
HDUITREEITEM GetNextVisibleItem(HDUITREEITEM pItem);
void SetItemHeight(INT nHeight);
BOOL IsExpand();
INT GetItemHeight();
protected:
virtual IDUIScrollBar* GetVerticalSB();
virtual VOID OnCreate();
virtual VOID OnDestroy();
VOID OnItemClick(const DUIEvent& info);
protected:
HDUITREEITEM m_hTopItem;
CRefPtr<IDUIScrollBar> m_pVertSB;
CRefPtr<IDUIScrollBar> m_pHorzSB;
INT m_nTotalHeight;
INT m_nExtraHeight;
INT m_nMaxRight;
};
DUI_END_NAMESPCE
#endif //#ifndef __DUI_TREEVIEW_H__
|
class Solution {
public:
int calculate(string s) {
if (s.empty()) return 0; // corner case
int n = s.size(), res = 0, lastNum = 0, curNum = 0;
char lastOp = '+'; // previous operator: 1+2*3 => 0+1+2*3
for (int i = 0; i < n; ++i) {
char curChar = s[i];
if ('0' <= curChar && curChar <= '9')
curNum = curNum * 10 + (curChar - '0');
else if (curChar == '(') {
int j = i, cnt = 0;
for (; i < n; ++i) {
if (s[i] == '(') ++cnt;
if (s[i] == ')') --cnt;
if (cnt == 0) break;
}
curNum = calculate(s.substr(j + 1, i - j - 1));
}
if (i == n - 1 || curChar == '+' ||
curChar == '-' || curChar == '*' || curChar == '/') {
if (lastOp == '+' || lastOp == '-') {
res += lastNum;
lastNum = (lastOp == '+') ? curNum : -curNum;
}
else if (lastOp == '*') {
lastNum *= curNum;
}
else if (lastOp == '/') {
lastNum /= curNum;
}
lastOp = curChar;
curNum = 0;
}
}
return res + lastNum; // must, add the very last num
}
};
|
#pragma once
#include "SlowControlProcessors.h"
#include "tree/TEvent.h"
#include <map>
#include <queue>
#include <memory>
namespace ant {
namespace analysis {
namespace slowcontrol {
struct event_t {
bool Save; // indicates that slowcontrol processors found this interesting
TEvent Event;
event_t() {}
event_t(bool save, TEvent event) :
Save(save), Event(std::move(event))
{}
explicit operator bool() const {
return static_cast<bool>(Event);
}
};
} // namespace slowcontrol
class SlowControlManager {
public:
protected:
std::queue<slowcontrol::event_t> eventbuffer;
using buffer_t = std::queue<TID>;
std::map<std::shared_ptr<slowcontrol::Processor>, buffer_t> slowcontrol;
bool all_complete = false;
void AddProcessor(std::shared_ptr<slowcontrol::Processor> p);
static TID min(const TID& a, const TID& b);
TID PopBuffers(const TID& id);
TID changepoint;
public:
SlowControlManager();
bool ProcessEvent(TEvent event);
slowcontrol::event_t PopEvent();
size_t BufferSize() const { return eventbuffer.size(); }
};
}
}
|
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
int main()
{
sf::RenderWindow window(sf::VideoMode({ 800, 600 }), "Colored Circles");
window.clear();
sf::CircleShape shape1(40);
shape1.setPosition({ 200, 120 });
shape1.setFillColor(sf::Color(0xFF, 0x0, 0x0));
window.draw(shape1);
sf::CircleShape shape2(48);
shape2.setPosition({ 260, 120 });
shape2.setFillColor(sf::Color(0x0, 0xFF, 0x0));
window.draw(shape2);
sf::CircleShape shape3(60);
shape3.setPosition({ 320, 160 });
shape3.setFillColor(sf::Color(0x0, 0x0, 0xFF));
window.draw(shape3);
sf::CircleShape shape4(75);
shape4.setPosition({ 330, 220 });
shape4.setFillColor(sf::Color(0xFF, 0xFF, 0x0));
window.draw(shape4);
window.display();
sf::sleep(sf::seconds(5));
}
|
/**********************************************************************
bilibili粉丝数监视器+天气显示
基于flyAkari 会飞的阿卡林 bilibili UID:751219 的代码修改
感谢UP:Hans叫泽涵UP: 小年轻只爱她提供的灵感修改!
**********************************************************************/
/* 4pin IIC引脚,正面看,从左到右依次为GND、VCC、SCL、SDA
* ESP01 --- OLED
* 3.3V --- VCC
* G (GND) --- GND
* 0(GPIO0)--- SCL
* 2(GPIO2)--- SDA
*/
#include <Arduino.h>
#include <U8g2lib.h>
#include <stdio.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
U8G2_SSD1306_128X64_NONAME_1_SW_I2C u8g2(U8G2_R0, /* clock=*/ 0, /* data=*/ 2, /* reset=*/ U8X8_PIN_NONE); //修改为你的引脚
const unsigned char col[] U8X8_PROGMEM= { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,
0x00,0x00,0x00,0x00,0x00,0x80,0x03,0x00,0x00,0x00,0x00,0x00,0x80,0x03,0x00,0x00,
0x00,0x00,0x00,0xC0,0x07,0x00,0x00,0x00,0x00,0x00,0xC0,0x0F,0x00,0x00,0x00,0x00,
0x00,0xE0,0x0F,0x00,0x00,0x00,0x00,0x00,0xE0,0x0F,0x00,0x00,0x00,0x00,0x00,0xF0,
0x1F,0x00,0x00,0x00,0x00,0x00,0xF0,0x1F,0x00,0x00,0x00,0x00,0x00,0xF8,0x3F,0x00,
0x00,0x00,0x00,0x00,0xF8,0x7F,0x00,0x00,0x00,0x00,0x00,0xFC,0xFF,0x00,0x00,0x00,
0x00,0xC0,0xFF,0xFF,0x0F,0x00,0x00,0xC0,0xFF,0xFF,0xFF,0xFF,0x03,0x00,0xF0,0xFF,
0xFF,0xFF,0xFF,0x1F,0x00,0xF0,0xFF,0xFF,0xFF,0xFF,0x1F,0x00,0xE0,0xFF,0xFF,0xFF,
0xFF,0x0F,0x00,0xC0,0xFF,0xDF,0xF7,0xFF,0x07,0x00,0x80,0xFF,0x8F,0xE3,0xFF,0x07,
0x00,0x00,0xFF,0xBF,0xEF,0xFF,0x03,0x00,0x00,0xFF,0xBF,0xEF,0xFF,0x03,0x00,0x00,
0xFE,0x9F,0xE7,0xFF,0x00,0x00,0x00,0xFC,0xDF,0xF7,0x7F,0x00,0x00,0x00,0xF8,0xFF,
0xFF,0x3F,0x00,0x00,0x00,0xF0,0xFF,0xFF,0x1F,0x00,0x00,0x00,0xE0,0xFF,0xFF,0x0F,
0x00,0x00,0x00,0xE0,0xFF,0xFF,0x0F,0x00,0x00,0x00,0xE0,0xFF,0xFF,0x0F,0x00,0x00,
0x00,0xE0,0xFF,0xFF,0x0F,0x00,0x00,0x00,0xE0,0xFF,0xFF,0x0F,0x00,0x00,0x00,0xF0,
0xFF,0xFF,0x1F,0x00,0x00,0x00,0xF0,0xFF,0xFF,0x1F,0x00,0x00,0x00,0xF0,0xFF,0xFF,
0x1F,0x00,0x00,0x00,0xF0,0xFF,0xFF,0x1F,0x00,0x00,0x00,0xF0,0x7F,0xFC,0x1F,0x00,
0x00,0x00,0xF0,0x1F,0xF0,0x3F,0x00,0x00,0x00,0xF8,0x0F,0xE0,0x3F,0x00,0x00,0x00,
0xF8,0x03,0x80,0x3F,0x00,0x00,0x00,0xF8,0x00,0x00,0x3E,0x00,0x00,0x00,0x38,0x00,
0x00,0x38,0x00,0x00,0x00,0x08,0x00,0x00,0x20,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00};//换成你喜欢的图片
static const unsigned char PROGMEM cor[][32] =
{
{0x00,0x04,0x00,0x04,0xDE,0x7F,0x12,0x04,0x92,0x3F,0x12,0x04,0xD2,0x7F,0x1E,0x00,0x92,0x3F,0x92,0x20,0x92,0x3F,0x92,0x20,0x9E,0x3F,0x92,0x20,0x80,0x28,0x80,0x10},//"晴",
{0x00,0x00,0xBE,0x3F,0xA2,0x20,0x92,0x20,0x92,0x20,0x8A,0x3F,0x92,0x20,0x92,0x20,0xA2,0x20,0xA2,0x3F,0xA2,0x20,0x96,0x20,0x4A,0x20,0x42,0x20,0x22,0x28,0x12,0x10},//"阴",
{0x40,0x00,0x40,0x00,0xE0,0x0F,0x10,0x04,0x1C,0x02,0x20,0x01,0xC0,0x02,0x30,0x01,0x8E,0x1F,0x40,0x10,0x30,0x08,0x4C,0x04,0x80,0x02,0x80,0x01,0x70,0x00,0x0E,0x00},//"多",
{0x00,0x00,0xFC,0x1F,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF,0x7F,0x40,0x00,0x20,0x00,0x20,0x00,0x10,0x02,0x08,0x04,0x04,0x08,0xFE,0x1F,0x04,0x10,0x00,0x10},//"云",
{0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x88,0x08,0x88,0x10,0x88,0x20,0x84,0x20,0x84,0x40,0x82,0x40,0x81,0x40,0x80,0x00,0x80,0x00,0xA0,0x00,0x40,0x00},//"小",
{0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0xFC,0x1F,0x84,0x10,0x84,0x10,0x84,0x10,0x84,0x10,0x84,0x10,0xFC,0x1F,0x84,0x10,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00},//"中",
{0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,0x00,0xFF,0x7F,0x80,0x00,0x80,0x00,0x40,0x01,0x40,0x01,0x20,0x02,0x20,0x02,0x10,0x04,0x08,0x08,0x04,0x10,0x03,0x60},//*"大",
{0x00,0x00,0xFF,0x7F,0x80,0x00,0x80,0x00,0x80,0x00,0xFE,0x3F,0x82,0x20,0x82,0x20,0x92,0x22,0xA2,0x24,0x82,0x20,0x92,0x22,0xA2,0x24,0x82,0x20,0x82,0x28,0x02,0x10},//*"雨",
{0xFC,0x1F,0x80,0x00,0xFE,0x7F,0x82,0x40,0xB9,0x2E,0x80,0x00,0xB8,0x0E,0x00,0x00,0xFC,0x1F,0x00,0x10,0x00,0x10,0xF8,0x1F,0x00,0x10,0x00,0x10,0xFC,0x1F,0x00,0x10}//*"雪",
};
//---------------修改此处""内的信息-----------------------
const char *ssid = "MERCURY_85A8"; //WiFi名
const char *password = "88888888"; //WiFi密码
String biliuid = "4694767"; //bilibili UID
const char* xinzhi= "GET /v3/weather/now.json?key=你的密钥&location=你的城市&language=zh-Hans&unit=c HTTP/1.1\r\n";//-- 使用时请修改为当前你的私秘钥和你的城市拼音
//-------------------------------------------------------
const unsigned long HTTP_TIMEOUT = 5000;
WiFiClient client;
HTTPClient http;
String response;
int follower = 0;
void parseUserData(String content) // Json数据解析并串口打印.可参考https://www.bilibili.com/video/av65322772
{
const size_t capacity = JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(1) + 2*JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(6) + 210;
//DynamicJsonBuffer jsonBuffer(capacity);
DynamicJsonDocument jsonBuffer(capacity);
deserializeJson(jsonBuffer, content);
//JsonObject& root = jsonBuffer.parseObject(content);
//JsonObject& results_0 = root["results"][0];
JsonObject results_0=jsonBuffer["results"][0];
JsonObject results_0_location = results_0["location"];
//JsonObject& results_0_location = results_0["location"];
const char* results_0_location_id = results_0_location["id"];
const char* results_0_location_name = results_0_location["name"];
const char* results_0_location_country = results_0_location["country"];
const char* results_0_location_path = results_0_location["path"];
const char* results_0_location_timezone = results_0_location["timezone"];
const char* results_0_location_timezone_offset = results_0_location["timezone_offset"];
JsonObject results_0_now = results_0["now"];
const char* results_0_now_text = results_0_now["text"];
const char* results_0_now_code = results_0_now["code"];
const char* results_0_now_temperature = results_0_now["temperature"];
const char* results_0_last_update = results_0["last_update"];
u8g2.setFont(u8g2_font_unifont_t_chinese2);
u8g2.setFontDirection(0);
u8g2.setCursor(50, 40);
u8g2.print(results_0_now_temperature);
u8g2.setCursor(50, 30);
u8g2.print("TEMP:");
u8g2.setCursor(50, 50);
u8g2.print("WEATHER:");
switch(int(results_0_now["code"])){
case 1:
case 0:
u8g2.drawXBMP( 50 , 50 , 16 , 16 , cor[0] );
//u8g2.print("Sunny");
break;
case 4:
case 5:
case 6:
case 7:
case 8:
u8g2.drawXBMP( 50 , 50 , 16 , 16 , cor[2] );
u8g2.drawXBMP( 66 , 50 , 16 , 16 , cor[3] );
break;
case 9:
u8g2.drawXBMP( 50 , 50 , 16 , 16 , cor[1] );
break;
case 13:
u8g2.drawXBMP( 50 , 50 , 16 , 16 , cor[4] );
u8g2.drawXBMP( 66 , 50 , 16 , 16 , cor[7] );
break;
case 14:
u8g2.drawXBMP( 50 , 50 , 16 , 16 , cor[5] );
u8g2.drawXBMP( 66 , 50 , 16 , 16 , cor[7] );
break;
case 11:
case 12:
case 15:
case 16:
case 17:
case 18:
case 19:
u8g2.drawXBMP( 50 , 50 , 16 , 16 , cor[6] );
u8g2.drawXBMP( 66 , 50 , 16 , 16 , cor[7] );
break;
case 22:
u8g2.drawXBMP( 50 , 50 , 16 , 16 , cor[4] );
u8g2.drawXBMP( 66 , 50 , 16 , 16 , cor[8] );
break;
case 23:
u8g2.drawXBMP( 50 , 50 , 16 , 16 , cor[5] );
u8g2.drawXBMP( 66 , 50 , 16 , 16 , cor[8] );
break;
case 24:
case 25:
u8g2.drawXBMP( 50 , 50 , 16 , 16 , cor[6] );
u8g2.drawXBMP( 66 , 50 , 16 , 16 , cor[8] );
break;
}
Serial.println(results_0_location_name); //通过串口打印出需要的信息
Serial.println(results_0_now_text);
Serial.println(results_0_now_code);
Serial.println(results_0_now_temperature);
Serial.println(results_0_last_update);
Serial.print("\r\n");
}
void setup()
{
Serial.begin(9600);
while (!Serial)
continue;
Serial.println("bilibili fans monitor, version v1.2");
u8g2.begin();
u8g2.enableUTF8Print();
Serial.println("OLED Ready");
Serial.print("Connecting WiFi...");
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
bool getJson()
{
bool r = false;
http.setTimeout(HTTP_TIMEOUT);
http.begin("http://api.bilibili.com/x/relation/stat?vmid=" + biliuid);
int httpCode = http.GET();
if (httpCode > 0){
if (httpCode == HTTP_CODE_OK){
response = http.getString();
//Serial.println(response);
r = true;
}
}else{
Serial.printf("[HTTP] GET JSON failed, error: %s\n", http.errorToString(httpCode).c_str());
u8g2.firstPage();
do {
u8g2.setFont(u8g2_font_ncenB08_tr);
u8g2.setFontDirection(0);
u8g2.setCursor(0, 32);
u8g2.print("Error");
} while ( u8g2.nextPage() );
r = false;
}
http.end();
return r;
}
bool parseJson(String json)
{
const size_t capacity = JSON_OBJECT_SIZE(4) + JSON_OBJECT_SIZE(5) + 70;
DynamicJsonDocument doc(capacity);
deserializeJson(doc, json);
int code = doc["code"];
const char *message = doc["message"];
if (code != 0){
Serial.print("[API]Code:");
Serial.print(code);
Serial.print(" Message:");
Serial.println(message);
return false;
}
JsonObject data = doc["data"];
unsigned long data_mid = data["mid"];
int data_follower = data["follower"];
if (data_mid == 0){
Serial.println("[JSON] FORMAT ERROR");
return false;
}
Serial.print("UID: ");
Serial.print(data_mid);
Serial.print(" follower: ");
Serial.println(data_follower);
follower = data_follower;
return true;
}
void tqyb()
{
if(client.connect("api.seniverse.com", 80)==1) //连接服务器并判断是否连接成功,若成功就发送GET 请求数据下发
{
client.print(xinzhi); //心知天气的URL格式
client.print("Host:api.seniverse.com\r\n");
client.print("Accept-Language:zh-cn\r\n");
client.print("Connection:close\r\n\r\n"); //向心知天气的服务器发送请求。
String status_code = client.readStringUntil('\r'); //读取GET数据,服务器返回的状态码,若成功则返回状态码200
Serial.println(status_code);
if(client.find("\r\n\r\n")==1) //跳过返回的数据头,直接读取后面的JSON数据,
{
String json_from_server=client.readStringUntil('\n'); //读取返回的JSON数据
Serial.println(json_from_server);
parseUserData(json_from_server); //将读取的JSON数据,传送到JSON解析函数中进行显示。
}
}
else
{
Serial.println("connection failed this time");
delay(5000); //请求失败等5秒
}
client.stop(); //关闭HTTP客户端,采用HTTP短链接,数据请求完毕后要客户端要主动断开https://blog.csdn.net/huangjin0507/article/details/52396580
delay(5000);
}
void loop()
{
if (WiFi.status() == WL_CONNECTED){
if (getJson()){
if (parseJson(response)){
u8g2.firstPage();
do {
tqyb();
u8g2.setFont(u8g2_font_ncenB08_tr);
u8g2.setFontDirection(0);
u8g2.setCursor(50, 10);
u8g2.print("Follower:");
u8g2.setCursor(50, 20);
u8g2.print(follower);
u8g2.drawXBMP( 0 , 0 , 50 , 50 , col );
} while ( u8g2.nextPage() );
}
}
}
else{
Serial.println("[WiFi] Waiting to reconnect...");
u8g2.firstPage();
do {
u8g2.setFont(u8g2_font_ncenB08_tr);
u8g2.setFontDirection(0);
u8g2.setCursor(0, 32);
u8g2.print("Error");
u8g2.drawXBMP( 50 , 0 , 50 , 50 , col );
} while ( u8g2.nextPage() );
}
delay(1000);
}
|
#pragma once
#include <utility>
namespace Lynx::Tuple_V1
{
namespace
{
template <std::size_t N, typename T>
struct TupleCell
{
constexpr explicit TupleCell() noexcept
: value()
{
}
constexpr explicit TupleCell(const T& arg) noexcept
: value(arg)
{
}
template <std::size_t I, typename U>
constexpr explicit TupleCell(const TupleCell<I, U>& tc) noexcept
: value(tc.value)
{
}
template <std::size_t I, typename U>
constexpr explicit TupleCell(TupleCell<I, U>&& tc) noexcept
: value(tc.value)
{
tc.value = U();
}
~TupleCell() noexcept = default;
constexpr explicit TupleCell(const TupleCell& tc) noexcept
: value(tc.value)
{
}
constexpr explicit TupleCell(TupleCell&& tc) noexcept
: value(tc.value)
{
tc.value = T();
}
constexpr TupleCell& operator=(const TupleCell& tc) noexcept
{
if (this != &tc)
{
value = tc.value;
}
return *this;
}
constexpr TupleCell& operator=(TupleCell&& tc) noexcept
{
if (this != &tc)
{
value = tc.value;
tc.value = T();
}
return *this;
}
template <std::size_t I, typename U>
constexpr TupleCell& operator=(const TupleCell<I, U>& tc) noexcept
{
value = tc.value;
return *this;
}
template <std::size_t I, typename U>
constexpr TupleCell& operator=(TupleCell<I, U>&& tc) noexcept
{
value = tc.value;
tc.value = U();
return *this;
}
constexpr void Swap(TupleCell& tc) noexcept
{
T tmp = value;
value = tc.value;
tc.value = tmp;
}
T value;
};
}
namespace
{
template <typename...>
struct TupleImpl
{
constexpr explicit TupleImpl() noexcept = delete;
~TupleImpl() noexcept = delete;
constexpr explicit TupleImpl(TupleImpl&) noexcept = delete;
constexpr explicit TupleImpl(TupleImpl&&) noexcept = delete;
constexpr explicit TupleImpl(const TupleImpl&) noexcept = delete;
constexpr explicit TupleImpl(const TupleImpl&&) noexcept = delete;
constexpr TupleImpl& operator=(TupleImpl&) noexcept = delete;
constexpr TupleImpl& operator=(TupleImpl&&) noexcept = delete;
constexpr TupleImpl& operator=(const TupleImpl&) noexcept = delete;
constexpr TupleImpl& operator=(const TupleImpl&&) noexcept = delete;
};
template <std::size_t... Ns, typename... Ts>
struct TupleImpl<std::index_sequence<Ns...>, Ts...>
: public TupleCell<Ns, Ts>...
{
constexpr explicit TupleImpl() noexcept
: TupleCell<Ns, Ts>()...
{
}
constexpr explicit TupleImpl(const Ts&... args) noexcept
: TupleCell<Ns, Ts>(static_cast<const Ts&>(args))...
{
}
template <std::size_t... Is, typename... Args>
constexpr explicit TupleImpl(const TupleImpl<std::index_sequence<Is...>, Args...>& ti) noexcept
: TupleCell<Ns, Ts>(static_cast<const TupleCell<Is, Args>&>(ti))...
{
}
template <std::size_t... Is, typename... Args>
constexpr explicit TupleImpl(TupleImpl<std::index_sequence<Is...>, Args...>&& ti) noexcept
: TupleCell<Ns, Ts>(static_cast<TupleCell<Is, Args>&&>(ti))...
{
}
~TupleImpl() noexcept = default;
constexpr explicit TupleImpl(const TupleImpl& ti) noexcept
: TupleCell<Ns, Ts>(static_cast<const TupleCell<Ns, Ts>&>(ti))...
{
}
constexpr explicit TupleImpl(TupleImpl&& ti) noexcept
: TupleCell<Ns, Ts>(static_cast<TupleCell<Ns, Ts>&&>(ti))...
{
}
constexpr TupleImpl& operator=(const TupleImpl& ti) noexcept
{
std::initializer_list<int>
{
(TupleCell<Ns, Ts>::operator=(static_cast<const TupleCell<Ns, Ts>&>(ti)), 0)...
};
return *this;
}
constexpr TupleImpl& operator=(TupleImpl&& ti) noexcept
{
std::initializer_list<int>
{
(TupleCell<Ns, Ts>::operator=(static_cast<TupleCell<Ns, Ts>&&>(ti)), 0)...
};
return *this;
}
template <std::size_t... Is, typename... Args>
constexpr TupleImpl& operator=(const TupleImpl<std::index_sequence<Is...>, Args...>& ti) noexcept
{
std::initializer_list<int>
{
(TupleCell<Ns, Ts>::template operator=<Is, Args>(static_cast<const TupleCell<Is, Args>&>(ti)), 0)...
};
return *this;
}
template <std::size_t... Is, typename... Args>
constexpr TupleImpl& operator=(TupleImpl<std::index_sequence<Is...>, Args...>&& ti) noexcept
{
std::initializer_list<int>
{
(TupleCell<Ns, Ts>::template operator=<Is, Args>(static_cast<TupleCell<Is, Args>&&>(ti)), 0)...
};
return *this;
}
constexpr void Swap(TupleImpl& ti) noexcept
{
std::initializer_list<int>
{
(TupleCell<Ns, Ts>::Swap(static_cast<TupleCell<Ns, Ts>&>(ti)), 0)...
};
}
};
}
/*
* Tuple 实现方式:非递归式多继承。
*/
template <typename... Ts>
struct Tuple
: public TupleImpl<std::make_index_sequence<sizeof...(Ts)>, Ts...>
{
static constexpr std::size_t TupleSize = sizeof...(Ts);
constexpr Tuple() noexcept
: TupleImpl<std::make_index_sequence<sizeof...(Ts)>, Ts...>()
{
}
constexpr Tuple(const Ts&... args) noexcept
: TupleImpl<std::make_index_sequence<sizeof...(Ts)>, Ts...>(static_cast<const Ts&>(args)...)
{
}
template
<
typename... Args,
typename = std::enable_if_t
<
sizeof...(Ts) == sizeof...(Args) &&
(... && std::is_constructible_v<Ts, const Args&>)
>
>
constexpr Tuple(const Tuple<Args...>& tuple) noexcept
: TupleImpl<std::make_index_sequence<sizeof...(Ts)>, Ts...>
(
static_cast<const TupleImpl<std::make_index_sequence<sizeof...(Args)>, Args...>&>(tuple)
)
{
}
template
<
typename... Args,
typename = std::enable_if_t
<
sizeof...(Ts) == sizeof...(Args) &&
(... && std::is_constructible_v<Ts, Args&&>)
>
>
constexpr Tuple(Tuple<Args...>&& tuple) noexcept
: TupleImpl<std::make_index_sequence<sizeof...(Ts)>, Ts...>
(
static_cast<TupleImpl<std::make_index_sequence<sizeof...(Args)>, Args...>&&>(tuple)
)
{
}
~Tuple() noexcept = default;
constexpr Tuple(const Tuple& tuple) noexcept
: TupleImpl<std::make_index_sequence<sizeof...(Ts)>, Ts...>
(
static_cast<const TupleImpl<std::make_index_sequence<sizeof...(Ts)>, Ts...>&>(tuple)
)
{
}
constexpr Tuple(Tuple&& tuple) noexcept
: TupleImpl<std::make_index_sequence<sizeof...(Ts)>, Ts...>
(
static_cast<TupleImpl<std::make_index_sequence<sizeof...(Ts)>, Ts...>&&>(tuple)
)
{
}
constexpr Tuple& operator=(const Tuple& tuple) noexcept
{
TupleImpl<std::make_index_sequence<sizeof...(Ts)>, Ts...>::operator=
(
static_cast<const TupleImpl<std::make_index_sequence<sizeof...(Ts)>, Ts...>&>(tuple)
);
return *this;
}
constexpr Tuple& operator=(Tuple&& tuple) noexcept
{
TupleImpl<std::make_index_sequence<sizeof...(Ts)>, Ts...>::operator=
(
static_cast<TupleImpl<std::make_index_sequence<sizeof...(Ts)>, Ts...>&&>(tuple)
);
return *this;
}
template
<
typename... Args,
typename = std::enable_if_t
<
sizeof...(Ts) == sizeof...(Args) &&
(... && std::is_assignable_v<Ts&, const Args&>)
>
>
constexpr Tuple& operator=(const Tuple<Args...>& tuple) noexcept
{
TupleImpl<std::make_index_sequence<sizeof...(Ts)>, Ts...>::template operator=
(
static_cast<const TupleImpl<std::make_index_sequence<sizeof...(Args)>, Args...>&>(tuple)
);
return *this;
}
template
<
typename... Args,
typename = std::enable_if_t
<
sizeof...(Ts) == sizeof...(Args) &&
(... && std::is_assignable_v<Ts&, Args>)
>
>
constexpr Tuple& operator=(Tuple<Args...>&& tuple) noexcept
{
TupleImpl<std::make_index_sequence<sizeof...(Ts)>, Ts...>::template operator=
(
static_cast<TupleImpl<std::make_index_sequence<sizeof...(Args)>, Args...>&&>(tuple)
);
return *this;
}
constexpr void Swap(Tuple& tuple) noexcept
{
TupleImpl<std::make_index_sequence<sizeof...(Ts)>, Ts...>::Swap
(
static_cast<TupleImpl<std::make_index_sequence<sizeof...(Ts)>, Ts...>&>(tuple)
);
}
};
template <>
struct Tuple<>
{
constexpr Tuple() noexcept = delete;
~Tuple() noexcept = delete;
constexpr Tuple(Tuple&) noexcept = delete;
constexpr Tuple(Tuple&&) noexcept = delete;
constexpr Tuple(const Tuple&) noexcept = delete;
constexpr Tuple(const Tuple&&) noexcept = delete;
constexpr Tuple& operator=(Tuple&) noexcept = delete;
constexpr Tuple& operator=(Tuple&&) noexcept = delete;
constexpr Tuple& operator=(const Tuple&) noexcept = delete;
constexpr Tuple& operator=(const Tuple&&) noexcept = delete;
};
} // namespace Lynx::Tuple_V1
namespace Lynx::Tuple_V1
{
namespace
{
template <std::size_t N, typename T, typename... Ts>
struct TupleElementTypeImpl
{
using Type = typename TupleElementTypeImpl<N - 1, Ts...>::Type;
};
template <typename T, typename... Ts>
struct TupleElementTypeImpl<0, T, Ts...>
{
using Type = T;
};
}
template <std::size_t, typename>
struct TupleElementType
{
constexpr explicit TupleElementType() noexcept = delete;
~TupleElementType() noexcept = delete;
constexpr explicit TupleElementType(TupleElementType&) noexcept = delete;
constexpr explicit TupleElementType(TupleElementType&&) noexcept = delete;
constexpr explicit TupleElementType(const TupleElementType&) noexcept = delete;
constexpr explicit TupleElementType(const TupleElementType&&) noexcept = delete;
constexpr TupleElementType& operator=(TupleElementType&) noexcept = delete;
constexpr TupleElementType& operator=(TupleElementType&&) noexcept = delete;
constexpr TupleElementType& operator=(const TupleElementType&) noexcept = delete;
constexpr TupleElementType& operator=(const TupleElementType&&) noexcept = delete;
};
template <std::size_t N, typename... Ts>
struct TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>
{
using Type = std::enable_if_t
<
(N >= 0) && (N < sizeof...(Ts)),
typename TupleElementTypeImpl<N, Ts...>::Type
>;
};
template <std::size_t N, typename... Ts>
struct TupleElementType<N, const Lynx::Tuple_V1::Tuple<Ts...>> : public TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>
{
};
template <std::size_t N, typename... Ts>
struct TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>&> : public TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>
{
};
template <std::size_t N, typename... Ts>
struct TupleElementType<N, const Lynx::Tuple_V1::Tuple<Ts...>&> : public TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>
{
};
template <std::size_t N, typename... Ts>
struct TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>&&> : public TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>
{
};
template <std::size_t N, typename... Ts>
struct TupleElementType<N, const Lynx::Tuple_V1::Tuple<Ts...>&&> : public TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>
{
};
template <typename>
struct TupleSize
{
constexpr explicit TupleSize() noexcept = delete;
~TupleSize() noexcept = delete;
constexpr explicit TupleSize(TupleSize&) noexcept = delete;
constexpr explicit TupleSize(TupleSize&&) noexcept = delete;
constexpr explicit TupleSize(const TupleSize&) noexcept = delete;
constexpr explicit TupleSize(const TupleSize&&) noexcept = delete;
constexpr TupleSize& operator=(TupleSize&) noexcept = delete;
constexpr TupleSize& operator=(TupleSize&&) noexcept = delete;
constexpr TupleSize& operator=(const TupleSize&) noexcept = delete;
constexpr TupleSize& operator=(const TupleSize&&) noexcept = delete;
};
template <typename... Ts>
struct TupleSize<Lynx::Tuple_V1::Tuple<Ts...>>
{
static constexpr std::enable_if_t<(sizeof...(Ts) > 0), std::size_t> value = sizeof...(Ts);
};
template <typename... Ts>
struct TupleSize<const Lynx::Tuple_V1::Tuple<Ts...>> : public TupleSize<Lynx::Tuple_V1::Tuple<Ts...>>
{
};
template <typename... Ts>
struct TupleSize<Lynx::Tuple_V1::Tuple<Ts...>&> : public TupleSize<Lynx::Tuple_V1::Tuple<Ts...>>
{
};
template <typename... Ts>
struct TupleSize<const Lynx::Tuple_V1::Tuple<Ts...>&> : public TupleSize<Lynx::Tuple_V1::Tuple<Ts...>>
{
};
template <typename... Ts>
struct TupleSize<Lynx::Tuple_V1::Tuple<Ts...>&&> : public TupleSize<Lynx::Tuple_V1::Tuple<Ts...>>
{
};
template <typename... Ts>
struct TupleSize<const Lynx::Tuple_V1::Tuple<Ts...>&&> : public TupleSize<Lynx::Tuple_V1::Tuple<Ts...>>
{
};
} // namespace Lynx::Tuple_V1
namespace Lynx::Tuple_V1
{
template <std::size_t N, typename... Ts>
inline constexpr auto Get(Lynx::Tuple_V1::Tuple<Ts...>& tuple) noexcept
-> typename TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>::Type&
{
return static_cast<typename TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>::Type&>
(
tuple.Lynx::Tuple_V1::template TupleCell<N, typename TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>::Type>::value
);
}
template <std::size_t N, typename... Ts>
inline constexpr auto Get(Lynx::Tuple_V1::Tuple<Ts...>&& tuple) noexcept
-> typename TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>::Type&&
{
return static_cast<typename TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>::Type&&>
(
tuple.Lynx::Tuple_V1::template TupleCell<N, typename TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>::Type>::value
);
}
template <std::size_t N, typename... Ts>
inline constexpr auto Get(const Lynx::Tuple_V1::Tuple<Ts...>& tuple) noexcept
-> const typename TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>::Type&
{
return static_cast<const typename TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>::Type&>
(
tuple.Lynx::Tuple_V1::template TupleCell<N, typename TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>::Type>::value
);
}
template <std::size_t N, typename... Ts>
inline constexpr auto Get(const Lynx::Tuple_V1::Tuple<Ts...>&& tuple) noexcept
-> const typename TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>::Type&&
{
return static_cast<const typename TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>::Type&&>
(
tuple.Lynx::Tuple_V1::template TupleCell<N, typename TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>::Type>::value
);
}
namespace
{
template <std::size_t N, typename T, std::size_t I, typename U, typename... Us>
struct GetImpl
{
static constexpr std::enable_if_t<(I < N), std::size_t> value = GetImpl<N, T, I + 1, Us...>::value;
};
template <std::size_t N, typename T, std::size_t I, typename... Us>
struct GetImpl<N, T, I, T, Us...>
{
static constexpr std::enable_if_t<(I < N), std::size_t> value = I;
};
}
template <typename T, typename... Ts>
inline constexpr T& Get(Lynx::Tuple_V1::Tuple<Ts...>& tuple) noexcept
{
constexpr std::size_t N = GetImpl<sizeof...(Ts), T, 0, Ts...>::value;
return static_cast<T&>(tuple.Lynx::Tuple_V1::template TupleCell<N, typename TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>::Type>::value);
}
template <typename T, typename... Ts>
inline constexpr T&& Get(Lynx::Tuple_V1::Tuple<Ts...>&& tuple) noexcept
{
constexpr std::size_t N = GetImpl<sizeof...(Ts), T, 0, Ts...>::value;
return static_cast<T&&>(tuple.Lynx::Tuple_V1::template TupleCell<N, typename TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>::Type>::value);
}
template <typename T, typename... Ts>
inline constexpr const T& Get(const Lynx::Tuple_V1::Tuple<Ts...>& tuple) noexcept
{
constexpr std::size_t N = GetImpl<sizeof...(Ts), T, 0, Ts...>::value;
return static_cast<const T&>(tuple.Lynx::Tuple_V1::template TupleCell<N, typename TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>::Type>::value);
}
template <typename T, typename... Ts>
inline constexpr const T&& Get(const Lynx::Tuple_V1::Tuple<Ts...>&& tuple) noexcept
{
constexpr std::size_t N = GetImpl<sizeof...(Ts), T, 0, Ts...>::value;
return static_cast<const T&&>(tuple.Lynx::Tuple_V1::template TupleCell<N, typename TupleElementType<N, Lynx::Tuple_V1::Tuple<Ts...>>::Type>::value);
}
} // namespace Lynx::Tuple_V1
namespace Lynx::Tuple_V1
{
template <typename... Ts>
inline constexpr auto MakeTuple(Ts&&... args) noexcept -> Lynx::Tuple_V1::Tuple<std::remove_reference_t<Ts>...>
{
return Lynx::Tuple_V1::Tuple<std::remove_reference_t<Ts>...>{ std::forward<Ts>(args)... };
}
namespace
{
struct IgnoreType
{
template <typename T>
const IgnoreType& operator=(const T&) const
{
return *this;
}
};
inline constexpr IgnoreType _;
}
template <typename... Ts>
inline constexpr auto Tie(Ts&... args) noexcept -> Lynx::Tuple_V1::Tuple<Ts&...>
{
return Lynx::Tuple_V1::Tuple<Ts&...>{ args... };
}
template <typename... Ts>
inline constexpr void Swap(Lynx::Tuple_V1::Tuple<Ts...>& a, Lynx::Tuple_V1::Tuple<Ts...>& b) noexcept
{
a.Swap(b);
}
namespace
{
template <std::size_t... Ns, typename... Ts>
inline constexpr bool OperatorEqual
(
std::index_sequence<Ns...>,
const Lynx::Tuple_V1::Tuple<Ts...>& a,
const Lynx::Tuple_V1::Tuple<Ts...>& b
) noexcept
{
return (... && (Get<Ns>(a) == Get<Ns>(b)));
}
}
template <typename... Ts>
inline constexpr bool operator==(const Lynx::Tuple_V1::Tuple<Ts...>& a, const Lynx::Tuple_V1::Tuple<Ts...>& b) noexcept
{
return OperatorEqual(std::make_index_sequence<sizeof...(Ts)>{}, a, b);
}
template <typename... Ts>
inline constexpr bool operator!=(const Lynx::Tuple_V1::Tuple<Ts...>& a, const Lynx::Tuple_V1::Tuple<Ts...>& b) noexcept
{
return !OperatorEqual(std::make_index_sequence<sizeof...(Ts)>{}, a, b);
}
} // namespace Lynx::Tuple_V1
namespace Lynx::Tuple_V1
{
namespace
{
template <template <typename...> typename>
struct IsLynxTupleV1Tuple
{
static constexpr bool value = false;
};
template <>
struct IsLynxTupleV1Tuple<Lynx::Tuple_V1::Tuple>
{
static constexpr bool value = true;
};
}
namespace
{
template <typename...>
struct OutputType;
template
<
template <typename...> typename LynxTupleV1Tuple,
typename... Ts
>
struct OutputType<LynxTupleV1Tuple<Ts...>>
{
using type = std::enable_if_t
<
(IsLynxTupleV1Tuple<LynxTupleV1Tuple>::value && (sizeof...(Ts) > 0)),
Lynx::Tuple_V1::Tuple<std::remove_reference_t<Ts>...>
>;
};
template
<
template <typename...> typename LynxTupleV1Tuple,
typename... Ts1,
typename... Ts2
>
struct OutputType<LynxTupleV1Tuple<Ts1...>, LynxTupleV1Tuple<Ts2...>>
{
using type = std::enable_if_t
<
(IsLynxTupleV1Tuple<LynxTupleV1Tuple>::value && (sizeof...(Ts1) > 0) && (sizeof...(Ts2) > 0)),
Lynx::Tuple_V1::Tuple<std::remove_reference_t<Ts1>..., std::remove_reference_t<Ts2>...>
>;
};
template
<
template <typename...> typename LynxTupleV1Tuple,
typename... Ts1,
typename... Ts2,
typename... Us
>
struct OutputType<LynxTupleV1Tuple<Ts1...>, LynxTupleV1Tuple<Ts2...>, Us...>
{
using type = std::enable_if_t
<
(IsLynxTupleV1Tuple<LynxTupleV1Tuple>::value && (sizeof...(Ts1) > 0) && (sizeof...(Ts2) > 0)),
typename OutputType<Lynx::Tuple_V1::Tuple<std::remove_reference_t<Ts1>..., std::remove_reference_t<Ts2>...>, Us...>::type
>;
};
}
namespace
{
template <typename T, std::size_t... Ns>
inline constexpr auto TupleCatImpl(T&& arg, std::index_sequence<Ns...>) noexcept
-> typename OutputType<std::remove_cv_t<std::remove_reference_t<T>>>::type
{
return { Get<Ns>(std::forward<T>(arg))... };
}
template <typename T, std::size_t... Ns, typename U, std::size_t... Is>
inline constexpr auto TupleCatImpl(T&& arg1, std::index_sequence<Ns...>, U&& arg2, std::index_sequence<Is...>) noexcept
-> typename OutputType<std::remove_cv_t<std::remove_reference_t<T>>, std::remove_cv_t<std::remove_reference_t<U>>>::type
{
return { Get<Ns>(std::forward<T>(arg1))..., Get<Is>(std::forward<U>(arg2))... };
}
}
template <typename T>
inline constexpr auto TupleCat(T&& arg) noexcept
-> typename OutputType<std::remove_cv_t<std::remove_reference_t<T>>>::type
{
return TupleCatImpl(std::forward<T>(arg), std::make_index_sequence<TupleSize<T>::value>{});
}
template <typename T, typename U>
inline constexpr auto TupleCat(T&& arg1, U&& arg2) noexcept
-> typename OutputType<std::remove_cv_t<std::remove_reference_t<T>>, std::remove_cv_t<std::remove_reference_t<U>>>::type
{
return TupleCatImpl
(
std::forward<T>(arg1), std::make_index_sequence<TupleSize<T>::value>{},
std::forward<U>(arg2), std::make_index_sequence<TupleSize<U>::value>{}
);
}
template <typename T, typename U, typename... Vs>
inline constexpr auto TupleCat(T&& arg1, U&& arg2, Vs&&... args) noexcept
-> typename OutputType
<
std::remove_cv_t<std::remove_reference_t<T>>,
std::remove_cv_t<std::remove_reference_t<U>>,
std::remove_cv_t<std::remove_reference_t<Vs>>...
>::type
{
return TupleCat
(
TupleCat(std::forward<T>(arg1), std::forward<U>(arg2)),
TupleCat(std::forward<Vs>(args)...)
);
}
} // namespace Lynx::Tuple_V1
|
#include <iostream>
using namespace std;
void Max (int A, int B);
int main ()
{
int N1, N2;
cout<<"Ingrese el primer valor del primer numero entero: ";
cin>>N1;
cout<<"Ingrese el segundo valor del segundo numero entero: ";
cin>>N2;
Max(N1,N2);
return 0;
}
void Max (int A, int B)
{
if (A>B)
{
cout<<"Es mayor"<<A;
}
else if (A<B)
{
cout<<"Es mayor"<<B;
}
else
cout<<"Error";
}
|
#include "Sensor.h"
//sensor construct, this is called by all sensors on creation
Sensor::Sensor(float value)
{
this->value = value;
}
Sensor::~Sensor()
{
}
float Sensor::getValue()
{
return value;
}
void Sensor::setValue(float value)
{
this->value=value;
}
|
#include "InvalidKennitalaException.h"
InvalidKennitalaException::InvalidKennitalaException()
{
//ctor
}
InvalidKennitalaException::~InvalidKennitalaException()
{
//dtor
}
|
#ifndef LEADERBOARD_H
#define LEADERBOARD_H
#include <string>
#include <map>
class Leaderboard {
public:
Leaderboard();
static Leaderboard *leaderDB; // the one, single leaderDB
//returns if score is greater than or equal to the lowest score
bool GEQLowestScore(int score);
//inserts new score into the ranking array
void insertNewScore(std::string username, int score);
//returns the index the score should be inserted at
int getRankIndex(int score);
std::string leaderboardHTML();
static Leaderboard *setleaderDB()
{
if (Leaderboard::leaderDB == 0)
{
Leaderboard::leaderDB = new Leaderboard;
}
return Leaderboard::leaderDB;
}
static Leaderboard *getleaderDB()
{
return Leaderboard::leaderDB;
}
//getter methods for unit testing
int getID(int index) {
return ranking[index];
}
std::string getUsername(int index) {
int id = ranking[index];
return IDusernameMap[id];
}
int getScore(int index) {
int id = ranking[index];
return IDscoreMap[id];
}
int getLowestScore() {
return lowestScore;
}
int getLastID() {
return lastID;
}
int scoreMapscore(int id) {
return IDscoreMap[id];
}
std::string usernameMapusername(int id) {
return IDusernameMap[id];
}
private:
std::map<int, int> IDscoreMap; //key: id, value: score
std::map<int, std::string> IDusernameMap; //key: id, value: username
int ranking[15]; //each array index holds an ID
int lowestScore;
int lastID;
};
#endif
|
#if (defined HAS_VTK)
#include <irtkImage.h>
#include <vtkPolyData.h>
#include <vtkPolyDataReader.h>
#include <vtkPolyDataWriter.h>
#include <vtkHull.h>
char *in_name = NULL, *out_name = NULL;
void usage()
{
cerr << "Usage: polydatahull [input] [output] <options>\n" << endl;
cerr << "" << endl;
cerr << "Options:" << endl;
cerr << "-levels n : Number of levels to subdivide planes in hull." << endl;
exit(1);
}
int main(int argc, char **argv)
{
bool ok;
int levels = 1;
if (argc < 3){
usage();
}
// Parse source and target point lists
in_name = argv[1];
argc--;
argv++;
out_name = argv[1];
argc--;
argv++;
while (argc > 1){
ok = false;
if ((ok == false) && (strcmp(argv[1], "-levels") == 0)){
argc--;
argv++;
levels = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if (ok == false){
cerr << "Can not parse argument " << argv[1] << endl;
usage();
}
}
// Read the input surface.
vtkPolyDataReader *reader = vtkPolyDataReader::New();
reader->SetFileName(in_name);
reader->Update();
vtkPolyData *input = vtkPolyData::New();
input = reader->GetOutput();
vtkHull *hull = vtkHull::New();
hull->SetInputData(input);
hull->AddRecursiveSpherePlanes(levels);
hull->Update();
vtkPolyDataWriter *writer = vtkPolyDataWriter::New();
writer->SetFileName(out_name);
writer->SetInputData(hull->GetOutput());
writer->Update();
writer->Write();
}
#else
#include <irtkImage.h>
int main( int argc, char *argv[] ){
cerr << argv[0] << " needs to be compiled with the VTK library " << endl;
}
#endif
|
#pragma once
#include <iostream>
#include <fstream>
#include <vector>
#include <pcl/point_types.h>
#include <pcl/features/normal_3d.h>
#include <vector>
using namespace std;
namespace pointCloudExtraction
{
bool RestorePointCloud(const float* pDepthImage, unsigned int uDepthWidth, unsigned int uDepthHeight,
const vector<vector<float>>& cameraIntrinsic,
const uint8_t* pColorImage, unsigned int uColorWidth, unsigned int uColorHeight, unsigned int uChannelNum,
pcl::PointCloud<pcl::PointXYZRGB>::Ptr outPointCloud);
bool write_point_cloud(std::string output_dir, pcl::PointCloud<pcl::PointXYZRGB>::Ptr pointCloud, int point_count);
/*void VoxelGridFilter(const std::vector<Point>& pointCloud, const std::vector<Point>& outPointCloud);
void ClusterRemoval(const std::vector<Point>& pointCloud, const std::vector<Point>& outPointCloud);
glm::mat4x4 PointCloudRegister(const std::vector<Point>& pointCloudP,
const std::vector<Point>& pointCloudQ,
unsigned int uMaxIterationNum,
float fDistanceThreshold,
float fTransformThreshold);*/
}
|
#ifndef __CAFFE_MTCNN_HPP__
#define __CAFFE_MTCNN_HPP__
#include <string>
#include <vector>
#include <opencv2/opencv.hpp>
#include "mtcnn.hpp"
#include "comm_lib.hpp"
#include "tengine_c_api.h"
class caffe_mtcnn: public mtcnn {
public:
caffe_mtcnn()=default;
int load_3model(const std::string& model_dir);
void detect(cv::Mat& img, std::vector<FaceBox>& face_list);
~caffe_mtcnn();
protected:
void copy_one_patch(const cv::Mat& img,FaceBox&input_box,float * data_to, int width, int height);
int run_PNet(const cv::Mat& img, scale_window& win, std::vector<FaceBox>& box_list);
void run_RNet(const cv::Mat& img,std::vector<FaceBox>& pnet_boxes, std::vector<FaceBox>& output_boxes);
void run_ONet(const cv::Mat& img,std::vector<FaceBox>& rnet_boxes, std::vector<FaceBox>& output_boxes);
private:
graph_t graph[3];
tensor_t input_tensor[3];
float*input_data[3];
int input_size[3];
};
#endif
|
#include "../../Common/Window.h"
#include "../CSC8503Common/StateMachine.h"
#include "../CSC8503Common/StateTransition.h"
#include "../CSC8503Common/State.h"
#include "../CSC8503Common/GameServer.h"
#include "../CSC8503Common/GameClient.h"
#include "../CSC8503Common/NavigationGrid.h"
#include "TutorialGame.h"
#include "Coursework.h"
#include "NetworkedGame.h"
#include <time.h>
using namespace NCL;
using namespace CSC8503;
void TestStateMachine() {
StateMachine* testMachine = new StateMachine();
int someData = 0;
StateFunc AFunc = [](void* data) {
int* realData = (int*)data;
(*realData)++;
std::cout << "In State A!" << std::endl;
};
StateFunc BFunc = [](void* data) {
int* realData = (int*)data;
(*realData)--;
std::cout << "In State B!" << std::endl;
};
GenericState* stateA = new GenericState(AFunc, (void*)&someData);
GenericState* stateB = new GenericState(BFunc, (void*)&someData);
testMachine->AddState(stateA);
testMachine->AddState(stateB);
GenericTransition<int&, int>* transitionA =
new GenericTransition<int&, int>(
GenericTransition<int&, int>::GreaterThanTransition,
someData, 10, stateA, stateB
);
GenericTransition<int&, int>* transitionB =
new GenericTransition<int&, int>(
GenericTransition<int&, int>::EqualsTransition,
someData, 0, stateA, stateB
);
testMachine->AddTransition(transitionA);
testMachine->AddTransition(transitionB);
for(int i = 0; i < 100; i++) testMachine->Update();
delete testMachine;
}
//void TestNetworking() {
// NetworkBase::Initialise();
//
// TestPacketReceiver serverReceiver("Server");
// TestPacketReceiver clientReceiver("Client");
//
// int port = NetworkBase::GetDefaultPort();
//
// GameServer* server = new GameServer(port, 1);
// GameClient* client = new GameClient();
//
// server->RegisterPacketHandler(StringMessage, &serverReceiver);
// client->RegisterPacketHandler(StringMessage, &clientReceiver);
//
// bool canConnect = client->Connect(127, 0, 0, 1, port);
//
// for(int i = 0; i < 100; i++) {
// server->SendGlobalPacket(
// StringPacket("Server says hello! " + std::to_string(i))
// );
// client->SendPacket(
// StringPacket("Client says hello! " + std::to_string(i))
// );
//
// server->UpdateServer();
// client->UpdateClient();
//
// std::this_thread::sleep_for(std::chrono::milliseconds(10));
// }
// NetworkBase::Destroy();
//}
vector<Vector3> testNodes;
void TestPathfinding() {
NavigationGrid grid("level1.txt");
NavigationPath outPath;
Vector3 startPos(280, 0, 220);
Vector3 endPos(120, 0, 40);
bool found = grid.FindPath(startPos, endPos, outPath);
Vector3 pos;
while(outPath.PopWaypoint(pos)) testNodes.push_back(pos);
}
void DisplayPathfinding() {
for(int i = 1; i < testNodes.size(); i++) {
Vector3 a = testNodes[i - 1];
Vector3 b = testNodes[i];
Debug::DrawLine(a, b, Vector4(0, 1, 0, 1));
}
}
/*
The main function should look pretty familar to you!
We make a window, and then go into a while loop that repeatedly
runs our 'game' until we press escape. Instead of making a 'renderer'
and updating it, we instead make a whole game, and repeatedly update that,
instead.
This time, we've added some extra functionality to the window class - we can
hide or show the
*/
int main() {
Window*w = Window::CreateGameWindow("CSC8503 Game technology!", 1280, 720);
if (!w->HasInitialised()) {
return -1;
}
srand(time(NULL));
// TestStateMachine();
// TestNetworking();
//TestPathfinding();
w->ShowOSPointer(false);
w->LockMouseToWindow(true);
// TutorialGame* g = new TutorialGame();
Coursework* g = new Coursework();
while (w->UpdateWindow() && !Window::GetKeyboard()->KeyDown(KEYBOARD_ESCAPE)) {
float dt = w->GetTimer()->GetTimeDelta() / 1000.0f;
if (dt > 1.0f) {
continue; //must have hit a breakpoint or something to have a 1 second frame time!
}
if (Window::GetKeyboard()->KeyPressed(KEYBOARD_PRIOR)) {
w->ShowConsole(true);
}
if (Window::GetKeyboard()->KeyPressed(KEYBOARD_NEXT)) {
w->ShowConsole(false);
}
//DisplayPathfinding();
if (g->isServer) w->SetTitle("Server");
else if (g->me != nullptr) w->SetTitle(g->me->name);
else w->SetTitle("Connecting...");
g->UpdateGame(dt);
}
delete g;
Window::DestroyGameWindow();
}
|
#include <Cipher.h>
//大漠算法!!!!
///////////////////////
//异或加/解密算法(以下参数类同)
//datas:待加/解密内容地址
//password:加密用的密码
void cipher_BitXor(QByteArray &datas,QString password)
{
uint datasLen=datas.length();//明文长度datasLen
uint pwdLen=password.length();//密码长度pwdLen
char *data=datas.data();//指针Data用于处理明文里的数据
uint i=0,j=0;
for(;i<datasLen;++i)//对明文中的每个字节都进行加密
{
if(j<pwdLen)//先加密pwdLen个明文字节
{
data[i]^=password[j].toAscii();//用密码进行异或加密
++j;
}
else//再加密1个字节
{
data[i]^=pwdLen;//用pwdLen进行异或加密
j=0;//如此循环使用密码
}
}//如此循环,直至每个字节都被加密了
}
//算数加密算法!!!
void cipher_Encryption(QByteArray &datas,QString password)
{
uint datasLen=datas.length();//明文长度datasLen
uint pwdLen=password.length();//密码长度pwdLen
char *data=datas.data();//指针Data用于处理明文里的数据
uint i=0,j=0;
for(;i<datasLen;++i)//对明文中的每个字节都进行加密
{
if(j<pwdLen)//先加密pwdLen个明文字节
{
data[i]+=password[j].toAscii();//用密码进行正偏移加密
++j;
}
else//再加密1个字节
{
data[i]+=pwdLen;//用pwdLen进行正偏移加密
j=0;//如此循环
}
}//如此循环,直至每个字节都被加密了
}
//算数解密算法!!!
void cipher_Decryption(QByteArray &datas,QString password)
{
uint datasLen=datas.length();//明文长度datasLen
uint pwdLen=password.length();//密码长度pwdLen
char *data=datas.data();//指针Data用于处理明文里的数据
uint i=0,j=0;
for(;i<datasLen;++i)//对明文中的每个字节都进行加密
{
if(j<pwdLen)//先加密pwdLen个明文字节
{
data[i]-=password[j].toAscii();//用密码进行负偏移加密
++j;
}
else//再加密1个字节
{
data[i]-=pwdLen;//用pwdLen进行负偏移加密
j=0;//如此循环
}
}//如此循环,直至每个字节都被加密了
}
|
#ifndef _HELPER_HPP_
#define _HELPER_HPP_
#include <vector>
bool Get_Int_Vector_From_C_To_Python(std::vector<int> &out, PyObject *int_list);
bool Get_Int64_Vector_From_C_To_Python(std::vector<int64_t> &out, PyObject *long_list);
#endif // _HELPER_HPP_
|
#ifndef DISABLE_RENDER
#include "renderer.h"
#endif
#include "aabb.h"
#include "body.h"
#include "contact_generator.h"
#include "gjk_epa.h"
#include "simplex.h"
namespace physics
{
#ifdef DEBUG_GJKEPA
extern std::vector<SupportPoint> minkowskiPoints;
extern std::vector<Vector3> allMinkowskiPoints;
static void renderMinkowskiPoints()
{
glDisable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT, GL_DIFFUSE);
glBegin(GL_LINES);
// search lines
if (minkowskiPoints.size() > 1)
{
int count = minkowskiPoints.size();
for (int i = 1; i < count; i++)
{
float c = 1.0f / count * (i - 1);
glColor3f(c, 0, 0);
Vector3 pta = minkowskiPoints[i - 1].minkowskiPoint;
Vector3 ptb = minkowskiPoints[i].minkowskiPoint;
glVertex3f(pta.x.to_d(), pta.y.to_d(), pta.z.to_d());
glVertex3f(ptb.x.to_d(), ptb.y.to_d(), ptb.z.to_d());
}
if (count > 3)
{
Vector3 pta = minkowskiPoints[count - 2].minkowskiPoint;
Vector3 ptb = minkowskiPoints[count - 4].minkowskiPoint;
glVertex3f(pta.x.to_d(), pta.y.to_d(), pta.z.to_d());
glVertex3f(ptb.x.to_d(), ptb.y.to_d(), ptb.z.to_d());
}
}
glEnd();
// axis
glBegin(GL_LINES);
// x
glColor3f(0.5, 0, 0);
glVertex3f(-50, 0, 0);
glVertex3f(0, 0, 0);
glColor3f(1, 0, 0);
glVertex3f(0, 0, 0);
glVertex3f(50, 0, 0);
// y
glColor3f(0, 0.5, 0);
glVertex3f(0, -50, 0);
glVertex3f(0, 0, 0);
glColor3f(0, 1, 0);
glVertex3f(0, 0, 0);
glVertex3f(0, 50, 0);
// z
glColor3f(0, 0, 0.5);
glVertex3f(0, 0, -50);
glVertex3f(0, 0, 0);
glColor3f(0, 0, 1);
glVertex3f(0, 0, 0);
glVertex3f(0, 0, 50);
glEnd();
glEnable(GL_POINT_SMOOTH);
glPointSize(3);
glColor3f(1.0, 0, 0);
glBegin(GL_POINTS);
// Draw orignal point
glVertex3f(0, 0, 0);
// all points
if (allMinkowskiPoints.size() > 1)
{
int count = allMinkowskiPoints.size();
for (int i = 0; i < count; i++)
{
float c = 1.0f / count * (i - 1);
glColor3f(0, c, 0);
Vector3 pt = allMinkowskiPoints[i];
glVertex3f(pt.x.to_d(), pt.y.to_d(), pt.z.to_d());
}
}
glEnd();
glDisable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT, GL_DIFFUSE);
}
#endif
void Renderer::setColor(float r, float g, float b)
{
GLfloat mat_ambient[] = {0.8f, 0.8f, 0.8f, 1.0f};
GLfloat mat_diffuse[] = {r, g, b, 1.0f};
GLfloat mat_specular[] = {0.7f, 0.7f, 0.7f, 1.0f};
GLfloat mat_emission[] = {0.0f, 0.0f, 0.0f, 1.f};
GLfloat mat_shininess = 30.0f;
glMaterialfv(GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialfv(GL_FRONT, GL_EMISSION, mat_emission);
glMaterialf(GL_FRONT, GL_SHININESS, mat_shininess);
}
void Renderer::renderAABB(const AABB &o)
{
glDisable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT, GL_DIFFUSE);
// back
glBegin(GL_LINE_LOOP);
glColor3f(0, 1, 0);
glVertex3f(o.min.x.to_d(), o.min.y.to_d(), o.min.z.to_d());
glVertex3f(o.max.x.to_d(), o.min.y.to_d(), o.min.z.to_d());
glVertex3f(o.max.x.to_d(), o.max.y.to_d(), o.min.z.to_d());
glVertex3f(o.min.x.to_d(), o.max.y.to_d(), o.min.z.to_d());
glEnd();
// front
glBegin(GL_LINE_LOOP);
glColor3f(0, 1, 0);
glVertex3f(o.min.x.to_d(), o.min.y.to_d(), o.max.z.to_d());
glVertex3f(o.max.x.to_d(), o.min.y.to_d(), o.max.z.to_d());
glVertex3f(o.max.x.to_d(), o.max.y.to_d(), o.max.z.to_d());
glVertex3f(o.min.x.to_d(), o.max.y.to_d(), o.max.z.to_d());
glEnd();
// side
glBegin(GL_LINES);
glColor3f(0, 1, 0);
glVertex3f(o.min.x.to_d(), o.min.y.to_d(), o.min.z.to_d());
glVertex3f(o.min.x.to_d(), o.min.y.to_d(), o.max.z.to_d());
glVertex3f(o.min.x.to_d(), o.max.y.to_d(), o.min.z.to_d());
glVertex3f(o.min.x.to_d(), o.max.y.to_d(), o.max.z.to_d());
glVertex3f(o.max.x.to_d(), o.min.y.to_d(), o.min.z.to_d());
glVertex3f(o.max.x.to_d(), o.min.y.to_d(), o.max.z.to_d());
glVertex3f(o.max.x.to_d(), o.max.y.to_d(), o.min.z.to_d());
glVertex3f(o.max.x.to_d(), o.max.y.to_d(), o.max.z.to_d());
glEnd();
glDisable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
}
void Renderer::renderPlane(Plane *p)
{
glDisable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT, GL_DIFFUSE);
// glEnable(GL_BLEND);
// glDisable(GL_DEPTH_TEST);
// glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// glColor4f(0.6f, 0.6f, 0.6f, 0.6);
glColor3f(0.6f, 0.6f, 0.6f);
Vector3 _lb = Vector3(-p->extents.x, 0, -p->extents.z);
Vector3 _lt = Vector3(-p->extents.x, 0, p->extents.z);
Vector3 _rb = Vector3(p->extents.x, 0, -p->extents.z);
Vector3 _rt = Vector3(p->extents.x, 0, p->extents.z);
_lb = p->body->getPosInWorldSpace(_lb);
_lt = p->body->getPosInWorldSpace(_lt);
_rb = p->body->getPosInWorldSpace(_rb);
_rt = p->body->getPosInWorldSpace(_rt);
glBegin(GL_TRIANGLE_STRIP);
glVertex3f(_lt.x.to_d(), _lt.y.to_d(), _lt.z.to_d());
glVertex3f(_lb.x.to_d(), _lb.y.to_d(), _lb.z.to_d());
glVertex3f(_rt.x.to_d(), _rt.y.to_d(), _rt.z.to_d());
glVertex3f(_rb.x.to_d(), _rb.y.to_d(), _rb.z.to_d());
glEnd();
// glEnable(GL_DEPTH_TEST);
// glDisable(GL_BLEND);
glDisable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
}
void Renderer::renderSphere(Sphere *p)
{
GLfloat mat[16];
p->transform.fillArray(mat);
if (p->body->isAwake)
setColor(0.6, 0.4, 0.2);
else
setColor(0.2, 0.6, 0.4);
glPushMatrix();
glMultMatrixf(mat);
glutSolidSphere(p->radius.to_d(), 50, 50);
glPopMatrix();
Renderer::renderAABB(p->aabb);
}
void Renderer::renderBox(Box *p)
{
GLfloat mat[16];
p->transform.fillArray(mat);
if (p->body->isAwake)
setColor(0.6, 0.4, 0.2);
else
setColor(0.2, 0.6, 0.4);
glPushMatrix();
glMultMatrixf(mat);
glScalef(p->extents.x.to_d() * 2, p->extents.y.to_d() * 2, p->extents.z.to_d() * 2);
glEnable(GL_NORMALIZE);
glutSolidCube(1.0f);
glPopMatrix();
Renderer::renderAABB(p->aabb);
}
void Renderer::renderCapsule(Capsule *p)
{
GLfloat mat[16];
p->transform.fillArray(mat);
if (p->body->isAwake)
setColor(0.6, 0.4, 0.2);
else
setColor(0.2, 0.6, 0.4);
glPushMatrix();
glMultMatrixf(mat);
glPushMatrix();
glTranslatef(p->pointLocalUp.x.to_d(), p->pointLocalUp.y.to_d(), p->pointLocalUp.z.to_d());
glutSolidSphere(p->radius.to_d(), 50, 50);
glPopMatrix();
// Draw the tube
glPushMatrix();
glTranslatef(0.0f, 0.0f, 0.0f);
GLfloat x = 0.0f;
GLfloat z = 0.0f;
GLfloat angle = 0.0f;
GLfloat step = 0.1f;
GLfloat pi = 3.1416f;
GLfloat radius = p->radius.to_d();
GLfloat halfHeight = p->halfHeight.to_d();
glBegin(GL_QUAD_STRIP);
angle = 0.0;
while (angle < 2 * pi)
{
float c = cos(angle);
float s = sin(angle);
x = radius * c;
z = radius * s;
glNormal3f(c, 0, s);
glVertex3f(x, halfHeight, z);
glVertex3f(x, -halfHeight, z);
angle = angle + step;
}
glNormal3f(1.0f, 0.0f, 0.0f);
glVertex3f(radius, halfHeight, 0.0f);
glVertex3f(radius, -halfHeight, 0.0f);
glEnd();
glPopMatrix();
glPushMatrix();
glTranslatef(p->pointLocalDown.x.to_d(), p->pointLocalDown.y.to_d(), p->pointLocalDown.z.to_d());
glutSolidSphere(p->radius.to_d(), 50, 50);
glPopMatrix();
glPopMatrix();
Renderer::renderAABB(p->aabb);
}
void Renderer::renderPolyhedron(Polyhedron *p)
{
GLfloat mat[16];
p->transform.fillArray(mat);
if (p->body->isAwake)
setColor(0.4, 0.6, 0.2);
else
setColor(0.2, 0.6, 0.4);
glPushMatrix();
glMultMatrixf(mat);
glBegin(GL_TRIANGLES);
for (unsigned i = 0; i < p->indices.size(); i += 3)
{
// setColor(0.4 + i * 0.02, 0.6+ i * 0.02, 0.2+ i * 0.02);
unsigned i0 = p->indices[i];
unsigned i1 = p->indices[i + 1];
unsigned i2 = p->indices[i + 2];
Vector3 va = p->pointsLocal[i0] - p->pointsLocal[i1];
Vector3 vb = p->pointsLocal[i2] - p->pointsLocal[i1];
Vector3 normal = vb.cross(va);
normal.normalise();
glNormal3f(normal.x.to_d(), normal.y.to_d(), normal.z.to_d());
glVertex3f(p->pointsLocal[i0].x.to_d(), p->pointsLocal[i0].y.to_d(), p->pointsLocal[i0].z.to_d());
glVertex3f(p->pointsLocal[i1].x.to_d(), p->pointsLocal[i1].y.to_d(), p->pointsLocal[i1].z.to_d());
glVertex3f(p->pointsLocal[i2].x.to_d(), p->pointsLocal[i2].y.to_d(), p->pointsLocal[i2].z.to_d());
}
glEnd();
glPopMatrix();
Renderer::renderAABB(p->aabb);
}
void Renderer::renderContactGenerator(ContactGenerator *p)
{
return;
glDisable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT, GL_DIFFUSE);
// Contact normal
// Vector3 n = p->_contactNormal;
// glColor3f(1, 1, 0);
// glDisable(GL_DEPTH_TEST);
// glBegin(GL_LINES);
// glVertex3f(p->_triangleP0.x.to_d(), p->_triangleP0.y.to_d(), p->_triangleP0.z.to_d());
// glVertex3f(p->_triangleP0.x.to_d() + n.x.to_d(),
// p->_triangleP0.y.to_d() + n.y.to_d(),
// p->_triangleP0.z.to_d() + n.z.to_d());
// glEnd();
// glEnable(GL_DEPTH_TEST);
// glDisable(GL_COLOR_MATERIAL);
// glEnable(GL_LIGHTING);
// glDisable(GL_LIGHTING);
// glEnable(GL_COLOR_MATERIAL);
// glColorMaterial(GL_FRONT,GL_DIFFUSE);
// glEnable(GL_BLEND);
// glDisable(GL_DEPTH_TEST);
// glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// glColor4f(1.0f, 0.0f, 0.0f, 0.1);
// glBegin(GL_TRIANGLES);
// glVertex3f(p->_triangleP0.x.to_d(), p->_triangleP0.y.to_d(), p->_triangleP0.z.to_d());
// glVertex3f(p->_triangleP1.x.to_d(), p->_triangleP1.y.to_d(), p->_triangleP1.z.to_d());
// glVertex3f(p->_triangleP2.x.to_d(), p->_triangleP2.y.to_d(), p->_triangleP2.z.to_d());
// glEnd();
OCTreeNode::PotentialContacts::iterator it = p->curPotentialContacts.begin();
for (; it < p->curPotentialContacts.end(); it++)
{
AABB &o = it->second->aabb;
double xmin = o.min.x.to_d();
double xmax = o.max.x.to_d();
double ymin = o.min.y.to_d();
double ymax = o.max.y.to_d();
double zmin = o.min.z.to_d();
double zmax = o.max.z.to_d();
// back
glBegin(GL_QUADS);
glVertex3f(xmin, ymin, zmin);
glVertex3f(xmax, ymin, zmin);
glVertex3f(xmax, ymax, zmin);
glVertex3f(xmin, ymax, zmin);
glEnd();
// front
glBegin(GL_QUADS);
glVertex3f(xmin, ymin, zmax);
glVertex3f(xmax, ymin, zmax);
glVertex3f(xmax, ymax, zmax);
glVertex3f(xmin, ymax, zmax);
glEnd();
// up
glBegin(GL_QUADS);
glVertex3f(xmin, ymax, zmin);
glVertex3f(xmax, ymax, zmin);
glVertex3f(xmax, ymax, zmax);
glVertex3f(xmin, ymax, zmax);
glEnd();
// down
glBegin(GL_QUADS);
glVertex3f(xmin, ymin, zmin);
glVertex3f(xmax, ymin, zmin);
glVertex3f(xmax, ymin, zmax);
glVertex3f(xmin, ymin, zmax);
glEnd();
// left
glBegin(GL_QUADS);
glVertex3f(xmin, ymin, zmin);
glVertex3f(xmin, ymax, zmin);
glVertex3f(xmin, ymax, zmax);
glVertex3f(xmin, ymin, zmax);
glEnd();
// right
glBegin(GL_QUADS);
glVertex3f(xmax, ymin, zmin);
glVertex3f(xmax, ymax, zmin);
glVertex3f(xmax, ymax, zmax);
glVertex3f(xmax, ymin, zmax);
glEnd();
}
glEnable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
glDisable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
}
void Renderer::renderContact(Contact *p)
{
#ifdef DEBUG_GJKEPA
renderMinkowskiPoints();
#endif
glDisable(GL_LIGHTING);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT, GL_DIFFUSE);
// Contact point
glDisable(GL_DEPTH_TEST);
glEnable(GL_POINT_SMOOTH);
glPointSize(1);
glColor3f(1.0, 0, 0);
glBegin(GL_POINTS);
glVertex3f(p->contactPoint.x.to_d(),
p->contactPoint.y.to_d(),
p->contactPoint.z.to_d());
glEnd();
glEnable(GL_DEPTH_TEST);
// Contact normal
Vector3 n = p->contactNormal * ffabs(p->penetration);
glColor3f(1, 1, 0);
glDisable(GL_DEPTH_TEST);
glBegin(GL_LINES);
glVertex3f(p->contactPoint.x.to_d(),
p->contactPoint.y.to_d(),
p->contactPoint.z.to_d());
glVertex3f(p->contactPoint.x.to_d() + n.x.to_d(),
p->contactPoint.y.to_d() + n.y.to_d(),
p->contactPoint.z.to_d() + n.z.to_d());
glEnd();
glEnable(GL_DEPTH_TEST);
glDisable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
}
}
|
// MFCActiveXCtrl.cpp : Implementation of the CMFCActiveXCtrl ActiveX Control class.
#include "stdafx.h"
#include "MFCActiveX.h"
#include "MFCActiveXCtrl.h"
#include "MFCActiveXPropPage.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
IMPLEMENT_DYNCREATE(CMFCActiveXCtrl, COleControl)
// Message map
BEGIN_MESSAGE_MAP(CMFCActiveXCtrl, COleControl)
ON_OLEVERB(AFX_IDS_VERB_PROPERTIES, OnProperties)
ON_WM_CREATE()
ON_WM_TIMER()
END_MESSAGE_MAP()
// Dispatch map
BEGIN_DISPATCH_MAP(CMFCActiveXCtrl, COleControl)
DISP_FUNCTION_ID(CMFCActiveXCtrl, "AboutBox", DISPID_ABOUTBOX, AboutBox, VT_EMPTY, VTS_NONE)
//-----生成代码声明
DISP_STOCKPROP_FORECOLOR()
DISP_STOCKPROP_BACKCOLOR()
DISP_PROPERTY_NOTIFY_ID(CMFCActiveXCtrl, "myinterval", dispidmyinterval, m_myinterval, OnmyintervalChanged, VT_I2)//在VB中测试看不到myinterval属性?????,VC中可以看到,修改报错??/
DISP_FUNCTION_ID(CMFCActiveXCtrl, "Hello", dispidHello, Hello, VT_EMPTY, VTS_NONE)//VB中也看不到????
END_DISPATCH_MAP()
// Event map
BEGIN_EVENT_MAP(CMFCActiveXCtrl, COleControl)
//------我的代码
EVENT_STOCK_CLICK()//是右击XXXCtrl类->add->add Event,只在ActiveX Control Test Container中测试可以,VB中报错
EVENT_CUSTOM_ID("NewMinute", eventidNewMinute, NewMinute, VTS_NONE)//只在ActiveX Control Test Container中测试可以,VB中报错
END_EVENT_MAP()
// Property pages
// TODO: Add more property pages as needed. Remember to increase the count!
//是对右击控件->properites显示的对话框中的tab,要用ActiveX Control Test Container测试生效
BEGIN_PROPPAGEIDS(CMFCActiveXCtrl, 2)//这里个数,要修改
PROPPAGEID(CMFCActiveXPropPage::guid)
PROPPAGEID(CLSID_CColorPropPage)//------我的代码,颜色属性的GUID
END_PROPPAGEIDS(CMFCActiveXCtrl)
// Initialize class factory and guid
IMPLEMENT_OLECREATE_EX(CMFCActiveXCtrl, "MFCACTIVEX.MFCActiveXCtrl.1",
0x603943f6, 0x2da0, 0x4936, 0xbd, 0x18, 0xda, 0xe8, 0xb9, 0xba, 0xcb, 0xf5)
// Type library ID and version
IMPLEMENT_OLETYPELIB(CMFCActiveXCtrl, _tlid, _wVerMajor, _wVerMinor)
// Interface IDs
const IID IID_DMFCActiveX = { 0x21D17C7A, 0x5F34, 0x4930, { 0xAD, 0xBC, 0x8C, 0xBC, 0xD7, 0xF2, 0xDC, 0xB3 } };
const IID IID_DMFCActiveXEvents = { 0xDA6F834D, 0xB2A7, 0x44C4, { 0x80, 0x48, 0xF, 0xB3, 0x6, 0x21, 0x5D, 0x71 } };
// Control type information
static const DWORD _dwMFCActiveXOleMisc =
OLEMISC_ACTIVATEWHENVISIBLE |
OLEMISC_SETCLIENTSITEFIRST |
OLEMISC_INSIDEOUT |
OLEMISC_CANTLINKINSIDE |
OLEMISC_RECOMPOSEONRESIZE;
IMPLEMENT_OLECTLTYPE(CMFCActiveXCtrl, IDS_MFCACTIVEX, _dwMFCActiveXOleMisc)
// CMFCActiveXCtrl::CMFCActiveXCtrlFactory::UpdateRegistry -
// Adds or removes system registry entries for CMFCActiveXCtrl
BOOL CMFCActiveXCtrl::CMFCActiveXCtrlFactory::UpdateRegistry(BOOL bRegister)
{
// TODO: Verify that your control follows apartment-model threading rules.
// Refer to MFC TechNote 64 for more information.
// If your control does not conform to the apartment-model rules, then
// you must modify the code below, changing the 6th parameter from
// afxRegApartmentThreading to 0.
if (bRegister)
return AfxOleRegisterControlClass(
AfxGetInstanceHandle(),
m_clsid,
m_lpszProgID,
IDS_MFCACTIVEX,
IDB_MFCACTIVEX,
afxRegApartmentThreading,
_dwMFCActiveXOleMisc,
_tlid,
_wVerMajor,
_wVerMinor);
else
return AfxOleUnregisterClass(m_clsid, m_lpszProgID);
}
// CMFCActiveXCtrl::CMFCActiveXCtrl - Constructor
CMFCActiveXCtrl::CMFCActiveXCtrl()
{
InitializeIIDs(&IID_DMFCActiveX, &IID_DMFCActiveXEvents);
// TODO: Initialize your control's instance data here.
m_myinterval=500;
//m_Interval=500;//初始化
}
// CMFCActiveXCtrl::~CMFCActiveXCtrl - Destructor
CMFCActiveXCtrl::~CMFCActiveXCtrl()
{
// TODO: Cleanup your control's instance data here.
}
// CMFCActiveXCtrl::OnDraw - Drawing function
void CMFCActiveXCtrl::OnDraw(
CDC* pdc, const CRect& rcBounds, const CRect& rcInvalid)
{
if (!pdc)
return;
// TODO: Replace the following code with your own drawing code.
//注释它
//pdc->FillRect(rcBounds, CBrush::FromHandle((HBRUSH)GetStockObject(WHITE_BRUSH)));
//pdc->Ellipse(rcBounds);
//ActiveX Control Test Container工具在 C:\Program Files\Microsoft Visual Studio 10.0\Samples\1033\VC2010Samples.zip\C++\MFC\ole\TstCon 是一个Solution项目
//-----------我的代码
CTime time=CTime::GetCurrentTime();//VS工具不提示有这个方法,但是有的
if(0 == time.GetSecond()%10)
NewMinute();//向容器发送事件发生通知
CString timeStr=time.Format("%H:%M:%S");
//加BackColor的Stock属性,展开XXXLib->图标"o-O"(不是Events结尾的),右击->add->add property
//要在VB中测试,才可以看到属性并修改
CBrush brush(TranslateColor(GetBackColor()));//GetBackColor得到用户设置的背景色属性,
pdc->FillRect(rcBounds, &brush);
pdc->SetTextColor(TranslateColor(GetForeColor()));
pdc->SetBkMode(TRANSPARENT);
pdc->TextOutW(0,0,timeStr);
}
// CMFCActiveXCtrl::DoPropExchange - Persistence support
void CMFCActiveXCtrl::DoPropExchange(CPropExchange* pPX)
{
ExchangeVersion(pPX, MAKELONG(_wVerMinor, _wVerMajor));
COleControl::DoPropExchange(pPX);
PX_Short(pPX,L"myinterval",m_myinterval,800);//--持久化属性值,VB中看不到myinterval????
// TODO: Call PX_ functions for each persistent custom property.
}
// CMFCActiveXCtrl::OnResetState - Reset control to default state
void CMFCActiveXCtrl::OnResetState()
{
COleControl::OnResetState(); // Resets defaults found in DoPropExchange
// TODO: Reset any other control state here.
}
// CMFCActiveXCtrl::AboutBox - Display an "About" box to the user
void CMFCActiveXCtrl::AboutBox()
{
CDialogEx dlgAbout(IDD_ABOUTBOX_MFCACTIVEX);
dlgAbout.DoModal();
}
// CMFCActiveXCtrl message handlers
//-----------我的代码
int CMFCActiveXCtrl::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (COleControl::OnCreate(lpCreateStruct) == -1)
return -1;
// TODO: Add your specialized creation code here
//SetTimer(1,1000,NULL);//使用WM_TIMER消息处理
//SetTimer(1,m_Interval,NULL);
SetTimer(1,m_myinterval,NULL);
return 0;
}
//-----------我的代码
void CMFCActiveXCtrl::OnTimer(UINT_PTR nIDEvent)
{
// TODO: Add your message handler code here and/or call default
//Invalidate();//
if(AmbientUserMode())//如在运行时更新,设计的时候更新,ActiveX Control Test Container中,Option->Design Mode
InvalidateControl();//与Invalidate()功能相同
COleControl::OnTimer(nIDEvent);
}
void CMFCActiveXCtrl::Hello(void)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
AfxMessageBox(L"Hello");//只在ActiveX Control Test Container中测试才可看到方法名
// TODO: Add your dispatch handler code here
}
void CMFCActiveXCtrl::OnmyintervalChanged(void)//外部修改属性时调用,如myinterval
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
//-----------我的代码
//wchar_t data[50];
//swprintf(data,L"m_myinterval=%d",m_myinterval);
//AfxMessageBox(data);
if(m_myinterval<0 || m_myinterval>6000)
m_myinterval = 6000;
else
m_myinterval = m_myinterval/1000*1000;//取整
KillTimer(1);//标识
SetTimer(1,m_myinterval,NULL);
BoundPropertyChanged(3);//3是"o-O"图标类的 mynterval属性前的ID值,通知容器更新值
//-----------我的代码
SetModifiedFlag();
}
|
/* --- Singly Linked List --- */
#include <bits/stdc++.h>
using namespace std;
struct node {
int data;
node *next;
};
class linked_list {
private:
node *head, *tail;
public:
linked_list() {
head = NULL;
tail = NULL;
}
void add(int n) {
node *tmp = new node;
tmp->data = n;
tmp->next = NULL;
if (head == NULL) {
head = tmp; tail = tmp;
} else {
tail->next = tmp;
tail = tail->next;
}
}
void trav() {
node *tmp;
tmp = head;
while (tmp != NULL) {
printf("%d -> ", tmp->data);
tmp = tmp->next;
}
printf("NULL\n");
}
};
int main() {
};
|
#include <whiskey/Parsing/ParserRuleEmpty.hpp>
#include <whiskey/Parsing/ParserContext.hpp>
#include <whiskey/Parsing/ParserResult.hpp>
namespace whiskey {
ParserResult ParserRuleEmpty::onParse(const ParserGrammar &grammar, ParserContext &ctx, MessageContext &msgs) const {
return action(msgs);
}
ParserRuleEmpty::ParserRuleEmpty(std::string name, Action action) : ParserRule(name, ""), action(action) {}
const ParserRuleEmpty::Action &ParserRuleEmpty::getAction() const {
return action;
}
void ParserRuleEmpty::setAction(ParserRuleEmpty::Action value) {
action = value;
}
}
|
#ifndef __WHISKEY_Parsing_ParserResult_HPP
#define __WHISKEY_Parsing_ParserResult_HPP
#include <whiskey/AST/Node.hpp>
namespace whiskey {
class ParserResult {
private:
std::unique_ptr<Node> node;
bool good;
public:
ParserResult();
ParserResult(const std::unique_ptr<Node> &node);
std::unique_ptr<Node> &getNode();
const std::unique_ptr<Node> &getNode() const;
void setNode(std::unique_ptr<Node> value);
bool isGood() const;
void setGood(bool value);
};
} // namespace whiskey
#endif
|
// -*- C++ -*-
//
// Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory,
// Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC
//
// This file is part of FreePOOMA.
//
// FreePOOMA is free software; you can redistribute it and/or modify it
// under the terms of the Expat license.
//
// 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 Expat
// license for more details.
//
// You should have received a copy of the Expat license along with
// FreePOOMA; see the file LICENSE.
//
// ----------------------------------------------------------------------------
// Various tests of transpose(Tensor<>) global function (transposeerminant).
// ----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Includes:
//-----------------------------------------------------------------------------
#include "Pooma/Fields.h"
#include "Utilities/Tester.h"
// Forward declarations:
template<int Dim>
void testTranspose(Pooma::Tester &tester);
//-----------------------------------------------------------------------------
// Main program:
//-----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
Pooma::initialize(argc,argv);
Pooma::Tester tester(argc, argv);
testTranspose<1>(tester);
testTranspose<2>(tester);
testTranspose<3>(tester);
int ret = tester.results("TestTranspose");
Pooma::finalize();
return ret;
}
template<int Dim>
void testTranspose(Pooma::Tester &tester)
{
// Create the physical Domains:
const int nVerts = 6;
const int nCells = nVerts - 1;
int nCellsTot = 1;
Interval<Dim> vertexDomain;
for (int d = 0; d < Dim; d++) {
vertexDomain[d] = Interval<1>(nVerts);
nCellsTot *= nCells;
}
// Create the (uniform, logically rectilinear) mesh.
Vector<Dim> origin(0.0), spacings(0.2);
typedef UniformRectilinearMesh<Dim> Mesh_t;
DomainLayout<Dim> layout(vertexDomain, GuardLayers<Dim>(0));
// Create the Fields:
Centering<Dim> cell = canonicalCentering<Dim>(CellType, Continuous);
// Full, Antisymmetric, Symmetric, Diagonal Tensor Fields:
Field<Mesh_t,Tensor<Dim,double,Full> > tff(cell, layout, origin, spacings);
Field<Mesh_t,Tensor<Dim,double,Symmetric> >
tfs(cell, layout, origin, spacings);
Field<Mesh_t,Tensor<Dim,double,Antisymmetric> >
tfa(cell, layout, origin, spacings);
Field<Mesh_t,Tensor<Dim,double,Diagonal> >
tfd(cell, layout, origin, spacings);
// Assign values:
Tensor<Dim,double,Full> tf(0.0), tfTranspose;
Tensor<Dim,double,Symmetric> ts(0.0), tsTranspose;
Tensor<Dim,double,Antisymmetric> ta(0.0), taTranspose;
Tensor<Dim,double,Diagonal> td(0.0), tdTranspose;
for (int i = 0; i < Dim; i++) {
for (int j = 0; j < Dim; j++) {
tf(i,j) = (i+1)*(i+1) + (j+1)*(j+1) + (i+4)*(j+4) + i;
tfTranspose(j,i) = tf(i,j);
}
}
ts = symmetrize<Symmetric>(tf);
ta = symmetrize<Antisymmetric>(tf);
td = symmetrize<Diagonal>(tf);
tff = tf;
tfs = ts;
tfa = ta;
tfd = td;
tsTranspose = ts;
tdTranspose = td;
for (int i = 1; i < Dim; i++) {
for (int j = 0; j < i; j++) {
taTranspose(i,j) = -ta(i,j);
}
}
tester.out() << "tf = " << tf << std::endl;
tester.out() << "ts = " << ts << std::endl;
tester.out() << "ta = " << ta << std::endl;
tester.out() << "td = " << td << std::endl;
// Test transpose of Full Tensor:
Tensor<Dim,double,Full> transposeValF;
transposeValF = sum(transpose(tff));
if (!tester.check("transposeValF", transposeValF, tfTranspose*nCellsTot)) {
tester.out() << Dim << "D, sum(transpose(tff)) = " << transposeValF
<< " != tfTransposenCellsTot = "
<< tfTranspose*nCellsTot << std::endl;
}
// Test transpose of Symmetric Tensor:
Tensor<Dim,double,Symmetric> transposeValS;
transposeValS = sum(transpose(tfs));
if (!tester.check("transposeValS", transposeValS, tsTranspose*nCellsTot)) {
tester.out() << Dim << "D, sum(transpose(tfs)) = " << transposeValS
<< " != tsTranspose*nCellsTot = "
<< tsTranspose*nCellsTot << std::endl;
}
// Test transpose of Antiymmetric Tensor:
Tensor<Dim,double,Antisymmetric> transposeValA;
transposeValA = sum(transpose(tfa));
if (!tester.check("transposeValA", transposeValA, taTranspose*nCellsTot)) {
tester.out() << Dim << "D, sum(transpose(tfa)) = " << transposeValA
<< " != taTranspose*nCellsTot = "
<< taTranspose*nCellsTot << std::endl;
}
// Test transpose of Diagonal Tensor:
Tensor<Dim,double,Diagonal> transposeValD;
transposeValD = sum(transpose(tfd));
if (!tester.check("transposeValD", transposeValD, tdTranspose*nCellsTot)) {
tester.out() << Dim << "D, sum(transpose(tfd)) = " << transposeValD
<< " != tdTranspose*nCellsTot = "
<< tdTranspose*nCellsTot << std::endl;
}
}
// ACL:rcsinfo
// ----------------------------------------------------------------------
// $RCSfile: TestTranspose.cpp,v $ $Author: richard $
// $Revision: 1.4 $ $Date: 2004/11/01 18:17:12 $
// ----------------------------------------------------------------------
// ACL:rcsinfo
|
/*
========================================================================
Name : TraceManagerMainView.h
Author : DH
Copyright : All right is reserved!
Version :
E-Mail : dh.come@gmail.com
Description :
Copyright (c) 2009-2015 DH.
This material, including documentation and any related
computer programs, is protected by copyright controlled BY Du Hui(DH)
========================================================================
*/
#ifndef TRACEMANAGERMAINVIEW_H
#define TRACEMANAGERMAINVIEW_H
#include <e32std.h>
#include <aknview.h>
#include "TraceClient.h"
#include "TmWriterIf.h"
#include "TmWriteHelper.h"
class CTraceManagerMain;
/**
* Avkon view class for TraceManagerMainView. It is register with the view server
* by the AppUi. It owns the container control.
* @class CTraceManagerMainView TraceManagerMainView.h
*/
class CTraceManagerMainView : public CAknView, MTraceObserver, MTMWriterStateObserver
{
public:
// constructors and destructor
CTraceManagerMainView();
static CTraceManagerMainView* NewL();
static CTraceManagerMainView* NewLC();
void ConstructL();
virtual ~CTraceManagerMainView();
// from base class CAknView
TUid Id() const;
void HandleCommandL( TInt aCommand );
CTraceManagerMain* CreateContainerL();
void NewWriterReport( const TDesC &aReport );
protected:
// from base class CAknView
void DoActivateL(
const TVwsViewId& aPrevViewId,
TUid aCustomMessageId,
const TDesC8& aCustomMessage );
void DoDeactivate();
void HandleStatusPaneSizeChange();
TBool HandleDisconnectSelectedL( TInt aCommand );
TBool HandleConnectSelectedL( TInt aCommand );
TBool HandleSettingsSelectedL( TInt aCommand );
TBool HandleControlPaneMiddleSoftKeyPressedL( TInt aCommand );
void NewTraceReady(const TDesC8& aTrace);
private:
void SetupStatusPaneL();
void CleanupStatusPane();
void DynInitMenuPaneL(TInt aResourceId, CEikMenuPane* aMenuPane);
private:
CTraceManagerMain* iTraceManagerMain;
CTMWriteHelper *iWriteHelper;
TBool iIsConnected;
TInt iConnType;
CTraceClient * iTrace;
HBufC8 * iTraceBuf;
};
#endif // TRACEMANAGERMAINVIEW_H
|
// string literal class based on
// http://en.cppreference.com/w/cpp/language/constexpr
#pragma once
#include <cstddef>
#include <stdexcept>
#include <string>
class conststr {
private:
static constexpr const char* EMPTY = "";
const char* m_ptr;
size_t m_size;
public:
inline constexpr conststr() : m_ptr(EMPTY), m_size(0) {
}
template<size_t N>
inline constexpr conststr(const char(&a)[N]) : m_ptr(a), m_size(N - 1) {
}
inline constexpr conststr(const conststr& other)
: m_ptr(other.m_ptr), m_size(other.m_size) {
}
inline constexpr char operator[](size_t n) const {
return n < m_size ? m_ptr[n] : throw std::out_of_range("");
}
inline constexpr const char* c_str() const {
return m_ptr;
}
inline std::string str() const {
return std::string(m_ptr, m_size);
}
inline operator std::string() const {
return str();
}
inline constexpr size_t size() const {
return m_size;
}
inline constexpr bool operator==(const conststr& other) const {
if(m_size != other.m_size) return false;
for(size_t i = 0; i < m_size; ++i) {
if(m_ptr[i] != other.m_ptr[i]) return false;
}
return true;
}
inline constexpr bool operator!=(const conststr& other) const {
return !(*this == other);
}
};
|
#pragma once
#include "vector3.h"
class Ray
{
public:
Ray(){}
Ray(const Vector3& inOrigin, const Vector3& inDirection)
: origin(inOrigin)
, direction(inDirection)
{}
Vector3 PointAt(float t) const { return origin + (direction * t); }
public:
Vector3 origin;
Vector3 direction;
};
|
// #123 - Write a main function that does the following:
// a) reads an indeterminate number of values from the keyboard and stores them in a linked-list
// b) prints all the values
// c) prints the average of the values
// d) prints the negative values
// Eric Farkas
// CUS 1144 MWF 7:00-7:55
// March 14, 2002
#include <fstream.h>
// node definition
struct node{
int info;
node* next;
};
typedef node* ptrType;
void main(){
int count, num, sum = 0;
ptrType l = NULL;
cout<<"How many values to enter? ";
cin>>count;
// get values for list
for (int i = 0; i < count; i++){
cout<<"Enter value: ";
cin>>num;
sum += num; // running sum
ptrType p = new node;
p->info = num;
p->next = l;
l = p;
}
cout<<endl;
// print the values
cout<<"Values In The List:\n";
ptrType ptr = l;
while (ptr != NULL){
cout<<ptr->info<<endl;
ptr = ptr->next;
}
cout<<endl;
// print the average
cout<<"The Average is: "<<(sum / count)<<endl;
cout<<endl;
// print the negative values
cout<<"Negative Values In The List:\n";
ptrType ptrTwo = l;
int j = 0;
while (ptrTwo != NULL){
if (ptrTwo->info < 0){
cout<<ptrTwo->info<<endl;
j++;}
ptrTwo = ptrTwo->next;
}
if (j == 0)
cout<<"NONE\n";
}
|
#include <bits/stdc++.h>
using namespace std;
bool contains7(int n)
{
for (; n != 0; n /= 10)
if (n % 10 == 7)
return true;
return false;
}
int main()
{
int n;
cin >> n;
array<int, 4> ans{};
for (int i = 1; n > 0; ++i)
{
if (i % 7 != 0 and not contains7(i))
{
--n;
}
else
{
++ans[(i - 1) % 4];
}
}
for (int i : ans)
cout << i << "\n";
return 0;
}
|
/********************************************************************************
** Form generated from reading UI file 'ventana2.ui'
**
** Created by: Qt User Interface Compiler version 5.0.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_VENTANA2_H
#define UI_VENTANA2_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QDialog>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QPushButton>
QT_BEGIN_NAMESPACE
class Ui_Ventana2
{
public:
QLabel *label;
QPushButton *btnCerrar;
void setupUi(QDialog *Ventana2)
{
if (Ventana2->objectName().isEmpty())
Ventana2->setObjectName(QStringLiteral("Ventana2"));
Ventana2->resize(400, 300);
label = new QLabel(Ventana2);
label->setObjectName(QStringLiteral("label"));
label->setGeometry(QRect(110, 50, 181, 151));
QFont font;
font.setPointSize(24);
font.setBold(true);
font.setWeight(75);
label->setFont(font);
btnCerrar = new QPushButton(Ventana2);
btnCerrar->setObjectName(QStringLiteral("btnCerrar"));
btnCerrar->setGeometry(QRect(270, 240, 99, 27));
retranslateUi(Ventana2);
QMetaObject::connectSlotsByName(Ventana2);
} // setupUi
void retranslateUi(QDialog *Ventana2)
{
Ventana2->setWindowTitle(QApplication::translate("Ventana2", "Dialog", 0));
label->setText(QApplication::translate("Ventana2", "Ventana 2", 0));
btnCerrar->setText(QApplication::translate("Ventana2", "Cerrar", 0));
} // retranslateUi
};
namespace Ui {
class Ventana2: public Ui_Ventana2 {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_VENTANA2_H
|
/*
* File: Database.cpp
* Author: Leonardo
*
* Created on 16 de Agosto de 2015, 19:00
*/
#include "Database.h"
Database::Database() {
}
Database::Database(const Database& orig) {
}
Database::~Database() {
}
|
/*
* Copyright (c) 2009-2012 André Tupinambá (andrelrt@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
//-----------------------------------------------------------------------------
#include "msg_command_queue.h"
using dcl::remote_id_t;
//-----------------------------------------------------------------------------
namespace dcl {
namespace network {
namespace message {
//-----------------------------------------------------------------------------
// msgCreateCommandQueue
//-----------------------------------------------------------------------------
void dcl_message< msgCreateCommandQueue >::create_request( void* payload_ptr )
{
msgCreateCommandQueue_request* request_ptr =
reinterpret_cast< msgCreateCommandQueue_request* >( payload_ptr );
request_ptr->device_id_ = host_to_network( device_id_ );
request_ptr->context_id_ = host_to_network( context_id_ );
request_ptr->properties_ = host_to_network( properties_ );
}
//-----------------------------------------------------------------------------
void dcl_message< msgCreateCommandQueue >::parse_request( const void* payload_ptr )
{
const msgCreateCommandQueue_request* request_ptr =
reinterpret_cast< const msgCreateCommandQueue_request* >( payload_ptr );
device_id_ = network_to_host( request_ptr->device_id_ );
context_id_ = network_to_host( request_ptr->context_id_ );
properties_ = network_to_host( request_ptr->properties_ );
}
//-----------------------------------------------------------------------------
void dcl_message< msgCreateCommandQueue >::create_response( void* payload_ptr )
{
remote_id_t* response_ptr = reinterpret_cast< remote_id_t* >( payload_ptr );
*response_ptr = host_to_network( remote_id_ );
}
//-----------------------------------------------------------------------------
void dcl_message< msgCreateCommandQueue >::parse_response( const void* payload_ptr )
{
const remote_id_t* response_ptr =
reinterpret_cast< const remote_id_t* >( payload_ptr );
remote_id_ = network_to_host( *response_ptr );
}
//-----------------------------------------------------------------------------
// msgFlush
//-----------------------------------------------------------------------------
void dcl_message< msgFlush >::create_request( void* payload_ptr )
{
remote_id_t* request_ptr = reinterpret_cast< remote_id_t* >( payload_ptr );
*request_ptr = host_to_network( remote_id_ );
}
//-----------------------------------------------------------------------------
void dcl_message< msgFlush >::parse_request( const void* payload_ptr )
{
const remote_id_t* request_ptr = reinterpret_cast<const remote_id_t*>( payload_ptr );
remote_id_ = network_to_host( *request_ptr );
}
//-----------------------------------------------------------------------------
// msgFinish
//-----------------------------------------------------------------------------
void dcl_message< msgFinish >::create_request( void* payload_ptr )
{
remote_id_t* request_ptr = reinterpret_cast< remote_id_t* >( payload_ptr );
*request_ptr = host_to_network( remote_id_ );
}
//-----------------------------------------------------------------------------
void dcl_message< msgFinish >::parse_request( const void* payload_ptr )
{
const remote_id_t* request_ptr = reinterpret_cast<const remote_id_t*>( payload_ptr );
remote_id_ = network_to_host( *request_ptr );
}
//-----------------------------------------------------------------------------
}}} // namespace dcl::network::message
//-----------------------------------------------------------------------------
|
#include<bits/stdc++.h>
using namespace std;
vector<int>adj[10002];
int vis[10002];
int dist[10002];
void bfs(int src)
{
queue<int>q;
vis[src]=1;
q.push(src);
dist[src]=0;
while(!q.empty())
{
int cur=q.front();
q.pop();
for(int x:adj[cur])
{
if(!vis[x])
{
vis[x]=1;
q.push(x);
dist[x]=dist[cur]+1;
}
}
}
}
int main()
{
int t;
cin>>t;
for(int tc=1;tc<=t;tc++)
{
int n,m,a,b;
cin>>n>>m;
for(int i=0;i<n;i++)
{
adj[i].clear();
vis[i]=0;
}
for(int i=1;i<=m;i++)
{
cin>>a>>b;
adj[a].push_back(b);
adj[b].push_back(a);
}
int s,d;
cin>>s>>d;
int dist1[n],dist2[n],mx=0;
bfs(s);
for(int i=0;i<n;i++)
{
dist1[i]=dist[i];
}
memset(vis,0,sizeof(vis));
memset(dist,0,sizeof(dist));
bfs(d);
for(int i=0;i<n;i++)
{
dist2[i]=dist[i];
}
for(int i=0;i<n;i++)
mx=max(mx,dist1[i]+dist2[i]);
cout<<"Case "<<tc<<": ";
cout<<mx<<"\n";
}
}
|
#include<bits/stdc++.h>
using namespace std;
vector <int> v[1000];
bool vst[1000];
queue <pair<int,int> > q;
int main(){
int i,j,a,b,st,n,m,ans=0;
cin>>n>>m;
for(i=0;i<m;i++)
{
cin>>a>>b;
v[a].push_back(b);
v[b].push_back(a);
}
cin>>st;
q.push({1,0});
while(!q.empty())
{
a=q.front().first;
b=q.front().second;
printf("%d %d\n",a,b);
q.pop();
vst[a]=1;
for(vector<int>::iterator it=v[a].begin();it!=v[a].end();it++)
if(vst[*it]==0)
q.push({*it,b+1});
}
}
|
#ifndef QUADBOARD_H
#define QUADBOARD_H
#include <SFML/Graphics.hpp>
class QuadBoard : public sf::Drawable, public sf::Transformable
{
public:
QuadBoard(size_t quad_size, size_t width, size_t height, size_t margin, sf::Color default_color = sf::Color::Green, sf::Color active_color = sf::Color::Yellow);
void set_quad_color(unsigned int x, unsigned int y, sf::Color color);
void set_active(int x, int y);
void set_default(int x, int y);
void update(sf::Event& e);
void clear();
void reset();
void backup();
bool get_active(int x, int y);
size_t get_quad_size(){return this->quad_size;}
size_t get_margin(){return this->margin;}
void disable(){this->is_enable = false;}
void enable(){this->is_enable = true;}
bool is_disable(){return not this->is_enable;}
private:
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
size_t quad_size;
size_t margin;
size_t width;
size_t height;
bool is_enable;
sf::Color active_color;
sf::Color default_color;
sf::VertexArray m_vertices;
sf::VertexArray m_o_vertices; // original vertex Array
};
#endif
|
//////////////////////////////////////////////////////////////////////////
//
// data library
//
// Written by Pavel Amialiushka
// No commercial use permited.
//
//////////////////////////////////////////////////////////////////////////
#pragma once
#include "outputter.h"
namespace monpac
{
class channel;
class console_outputter : public outputter
{
protected:
void out_header();
int get_holds() const;
std::string get_line_format(channel const &);
};
}
|
#include <iostream>
using namespace std;
void printArray(int* ar, int begin, int end)
{
for(int i = begin; i <= end; i++)
{
cout << ar[i] << " ";
}
cout << "\n";
}
void merger(int* ar, int begin1, int end1, int begin2, int end2 )
{
int a = begin1;
int z = end1;
int y = end2;
int b = begin2;
int temp[y];
int count = begin1;
while(a <= z && b <= y)
{
//while statement will continue to repeat until it reaches the end of the list
if(ar[a] < ar[b])
{
temp[count] = ar[a];
a++;
count++;
}
else
{
temp[count] = ar[b];
b++;
count++;
}
}
while(a <= z){
temp[count] = ar[a];
count++;
a++;
}
while(b <= y){
temp[count] = ar[b];
count++;
b++;
}
for(int i = begin1; i < count; i++){
ar[i] = temp[i];
}
}
//which portion of the array am I mergeSorting....
void mergeSort(int* ar, int begin, int end)
{
//cout << "Merge Sorting: ";
//printArray(ar, begin, end);
//if it is not a 1 list (not trivially sorted)
if(begin != end)
{
//divide in half and call mergeSort on each half
int begin1 = begin;
int end1 = (end + begin) / 2;
int begin2 = end1 + 1;
int end2 = end;
//call mergesort on the first half
mergeSort(ar, begin1, end1);
//call mergesort on the second half
//this will not fire until the entire
//first half is dealt with
mergeSort(ar, begin2, end2);
//now perform the merge step
//cout << "Now we have to merge!!!!\n Start to cry Clancy!!!\n";
merger(ar, begin1, end1, begin2, end2);
}
}
int main()
{
int ar[5] = {7,2,1,4,3};
mergeSort(ar, 0, 4);
printArray(ar, 0, 4);
return 0;
}
|
/*****************************************************************************************************
* 剑指offer第24题
* 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设
输入的数组的任意两个数字都互不相同。
*
* Input: 序列vector<int> num
* Output: 0或1
*
* Note:(后序遍历BTS的特征:后序遍历的最后一个元素为根节点,左子树的元素均小于根节点,右子树的元素均大于根节点)
* 1、确定root=seq[len-1];
2、遍历序列(除去root结点),找到第一个大于root的位置,则该位置左边为左子树,右边为右子树;
3、遍历右子树,若发现有小于root的值,则直接返回false;
4、分别判断左子树和右子树是否仍是二叉搜索树(即递归步骤1、2、3)
* author: lcxanhui@163.com
* time: 2019.5.7
******************************************************************************************************/
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
bool VerifySequenceOfBTS(vector<int> sequence)
{
int len= sequence.size();
if (len == 0)
return false;
int root = sequence[len - 1]; //根节点为后序遍历的最后一个参数
vector<int> leftTree, rightTree; //左子树和右子树为后续的递归初始化
int i=0;
for (; i < len - 1; i++)
{
if (sequence[i] > root) //查找左右子树的分界点,左子树均小于根节点,右子树均大于根节点
break;
}
for (int j = i; j < len - 1; j++)
{
if (sequence[j] < root) //如果右子树的某一元素大于根节点,则次二叉树序列非后序遍历序列
return false;
}
if (i != 0)
{
for (int k = 0; k < i; k++)
leftTree.push_back(sequence[k]); //构建左子树,其中分界点为上面保存的i
}
if (i != len-2)
{
for (int j = i; j < len-1; j++)
rightTree.push_back(sequence[j]); //构建右子树,右子树为i到len-2的所有参数
}
bool leftSub = true, rightSub = true;
if (leftTree.size() > 1)
VerifySequenceOfBTS(leftTree); //左右子树的递归判断
if (rightTree.size() > 1)
VerifySequenceOfBTS(rightTree);
return (leftSub&&rightSub);
}
int main()
{
vector<int> arr;
//初始化,测试用例{5,7,6,9,11,10,8}和{7,4,5,6}
arr.push_back(7);
arr.push_back(4);
arr.push_back(5);
arr.push_back(6);
//arr.push_back(5);
//arr.push_back(7);
//arr.push_back(6);
//arr.push_back(9);
//arr.push_back(11);
//arr.push_back(10);
//arr.push_back(8);
for (int i = 0; i < arr.size(); i++) {
cout << arr[i] << " ";
}
bool result=true;
result= VerifySequenceOfBTS(arr);
return result;
}
|
#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetCircleResolution(120);
rectWidth = 199;
rectHeight = 109;
barColor.set(0,0,255);
circle1Color.set(39, 39, 37);
circle2Color.set(39, 39, 38);
circle3Color.set(35, 39, 47);
}
//--------------------------------------------------------------
void ofApp::update(){
}
//--------------------------------------------------------------
void ofApp::draw(){
ofFill();
ofSetColor(barColor);
ofRect(11, 15, 413, 613);
ofSetColor(circle1Color); //ALL
ofRect(118, 15, rectWidth, rectHeight);
ofSetColor(37, 39, 40); //A
ofRect(11, 224, 107, 214);
ofSetColor(circle2Color); //B
//ofRect(118, 518, rect1Width, 214);
//ofSetColor(39, 39, 38); //B
ofRect(118, 518, 199, 109);
ofSetColor(circle2Color); //C
//ofRect(118, 518, rectWidth, rectHeight);
//ofSetColor(39, 39, 38); //C
ofRect(317, 224, 107, 214);
ofSetColor(circle3Color); //D
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
if (key == 'a') {
rectWidth = rectWidth + 10;
}
if (key == 'd') {
rectWidth = rectWidth - 10;
}
if (key == 'w') {
rectHeight = rectHeight + 10;
}
if (key == 's') {
rectHeight = rectHeight - 10;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
|
#include <bits/stdc++.h>
#define db double
const int MAX_N = 8e5 + 10 , INF = 0x3f3f3f3f ;
std::vector<int> a , b ;
std::map<int , int> cnt ;
std::map<int , bool> ap ;
std::map<int , std::vector<int> > p1 , p2 ;
int n , nxt[MAX_N] , f[MAX_N] , g[MAX_N] ;
void calc(int l1) {
if (l1 == 1) {
int cir = a[0] - b[0] ;
if (cir < 0) cir += 3600000 ;
++cnt[cir] ;
return ;
}
///
int l2 = l1 << 1 ;
--l1 ; --l2 ;
for (int i = 1 ; i <= l1 ; ++i) f[i] = a[i] - a[i - 1] ;
for (int i = 1 ; i <= l2 ; ++i) g[i] = b[i] - b[i - 1] ;
f[l1 + 1] = INF ;
///
int p = 0 ; nxt[0] = nxt[1] = 0 ;
for (int i = 2 ; i <= l1 ; ++i) {
for (; p && f[p + 1] != f[i] ; p = nxt[p]) ;
if (f[p + 1] == f[i]) ++p ;
nxt[i] = p ;
}
ap.clear() ;
p = 0 ;
for (int i = 1 ; i <= l2 ; ++i) {
for (; p && f[p + 1] != g[i] ; p = nxt[p]) ;
if (f[p + 1] == g[i]) ++p ;
if (p == l1) {
db cir = a[p] - b[i] ;
if (cir < 0) cir += 3600000 ;
if (ap.count(cir)) continue ;
ap[cir] = 1 ; ++cnt[cir] ;
}
}
}
int main() {
scanf("%d" , &n) ;
for (int i = 0 ; i < n ; ++i) {
db x , y ; scanf("%lf %lf" , &x , &y) ;
p1[round(x * 10000)].push_back(round(y * 10000)) ;
}
for (int i = 0 ; i < n ; ++i) {
db x , y ; scanf("%lf %lf" , &x , &y) ;
p2[round(x * 10000)].push_back(round(y * 10000)) ;
}
///
for (std::map<int , std::vector<int> > :: iterator p = p1.begin() ; p != p1.end() ; ++p) {
int idx = p->first ;
std::sort(p->second.begin() , p->second.end()) ;
std::sort(p2[idx].begin() , p2[idx].end()) ;
///
if (p->second.size() != p2[idx].size()) {printf("Different\n") ; return 0 ;}
a.clear() ; b.clear() ;
int siz = p->second.size() ;
for (int i = 0 ; i < siz ; ++i) a.push_back(p->second[i]) ;
for (int i = 0 ; i < siz ; ++i) b.push_back(p2[idx][i]) ;
for (int i = 0 ; i < siz ; ++i) b.push_back(p2[idx][i] + 3600000) ;
calc(siz) ;
}
///
int ned = p1.size() ;
for (std::map<int , int> :: iterator p = cnt.begin() ; p != cnt.end() ; ++p)
if (p->second == ned) {printf("Same\n") ; return 0 ;}
printf("Different\n") ;
return 0 ;
}
|
#include<sstream>
#include<string>
#include "Property.h"
using namespace std;
Property::Property(bool rentalIn, int valueIn, string addressIn)
{
rental = rentalIn;
value = valueIn;
address = addressIn;
}
Property:: ~Property(){}
bool Property::getRental()
{
return rental;
}
int Property::getValue()
{
return value;
}
string Property::getAddress()
{
return address;
}
double Property::getTax()
{
return tax;
}
int Property::getID() const
{
return ID;
}
string Property::toString()
{
string RENTAL;
if (rental == 0){
RENTAL = "Not a Rental ";
}
else{
RENTAL = "Rental ";
}
stringstream ss;
ss << "Property ID: " << ID << "\t" << "Address: " << address << "t" << RENTAL << "\t" << "Estimated Value: " << value << endl;
return ss.str();
}
|
#pragma once
#include <SFML/Graphics.hpp>
#include <functional>
// Тип данных: функция, выполняющая анимацию.
// @param dt - число секунд, прошедших с предыдущего кадра.
using AnimationUpdateFn = std::function<void(float dt)>;
// Класс AnimatedSprite имитирует sf::Sprite, но поддерживает покадровую анимацию.
// Для загрузки кадров используется текстурный атлас: изображение + информация о его нарезке.
// Атлас имеет формат, который соответствует формату Cheetah Texture Packer.
class AnimatedSprite
: public sf::Drawable
, public sf::Transformable
{
public:
AnimatedSprite() = default;
// Экземпляры класса нельзя копировать
AnimatedSprite(const AnimatedSprite&) = delete;
AnimatedSprite& operator=(const AnimatedSprite&) = delete;
// Запускает нецикличную анимацию. Возвращает функцию, которая обновляет эту анимацию.
// Возвращённую функцию нельзя использовать после разрушения спрайта.
AnimationUpdateFn startAnimation(float frameDuration, const std::vector<std::string>& frames);
// Запускает цикличную анимацию. Возвращает функцию, которая обновляет эту анимацию.
// Возвращённую функцию нельзя использовать после разрушения спрайта.
AnimationUpdateFn startCyclicAnimation(float frameDuration, const std::vector<std::string>& frames);
// Возвращает текущий кадр анимации, отображаемый в спрайте.
unsigned getCurrentFrame() const;
// Выбирает кадр анимации по индексу в массиве кадров.
// Возвращает true, если кадр с таким индексом существует.
bool selectFrame(unsigned frameIndex);
// Выбирает кадр анимации по имени исходного изображения.
// Возвращает true, если кадр с таким именем существует.
bool selectFrame(const std::string& name);
// Загружает анимированный спрайт из двух файлов (изображение и *.atlas)
bool loadFromFiles(const std::string& imagePath, const std::string& atlasPath);
protected:
void draw(sf::RenderTarget &target, sf::RenderStates states) const override;
private:
struct SpriteFrame
{
std::string name;
sf::IntRect rect;
};
static std::vector<SpriteFrame> loadAtlas(const std::string& filepath);
void updateSprite();
sf::Sprite m_sprite;
sf::Texture m_texture;
unsigned m_currentFrame = 0;
std::vector<SpriteFrame> m_frames;
};
|
#pragma once
#include "../PeptideSpectralMatch.h"
#include "PsmCrossType.h"
#include <string>
#include <unordered_map>
#include <vector>
#include "stringhelper.h"
#include "stringbuilder.h"
#include "../Ms2ScanWithSpecificMass.h"
#include "../PeptideSpectralMatch.h"
#include "Proteomics/Proteomics.h"
using namespace Proteomics::Fragmentation;
using namespace Proteomics::ProteolyticDigestion;
namespace EngineLayer
{
namespace CrosslinkSearch
{
class CrosslinkSpectralMatch : public PeptideSpectralMatch
{
private:
CrosslinkSpectralMatch *privateBetaPeptide=nullptr;
std::vector<int> privateLinkPositions;
double privateDeltaScore = 0;
double privateXLTotalScore = 0;
int privateXlProteinPos = 0;
std::vector<int> privateXlRank;
std::string privateParentIonExist;
int privateParentIonExistNum = 0;
std::vector<int> privateParentIonMaxIntensityRanks;
PsmCrossType privateCrossType = static_cast<PsmCrossType>(0);
public:
CrosslinkSpectralMatch(PeptideWithSetModifications *theBestPeptide, int notch, double score, int scanIndex,
Ms2ScanWithSpecificMass *scan, DigestionParams *digestionParams,
std::vector<MatchedFragmentIon*> &matchedFragmentIons);
CrosslinkSpectralMatch(PeptideWithSetModifications *theBestPeptide, int notch,
double score, int scanIndex,
std::string scanFullFilePath, int scanOneBasedScanNumber,
std::optional<int> scanOneBasedPrecursorScanNumber,
double scanRetentionTime, int scanNumPeaks, double scanTotalIonCurrent,
int scanPrecursorCharge, double scanPrecursorMonoisotopicPeakMz,
double scanPrecursorMass,
DigestionParams *digestionParams,
std::vector<MatchedFragmentIon*> &matchedFragmentIons);
CrosslinkSpectralMatch *getBetaPeptide() const;
void setBetaPeptide(CrosslinkSpectralMatch *value);
std::vector<int> getLinkPositions() const;
void setLinkPositions(const std::vector<int> &value);
double getDeltaScore() const;
void setDeltaScore(double value);
double getXLTotalScore() const;
void setXLTotalScore(double value);
int getXlProteinPos() const;
void setXlProteinPos(int value);
std::vector<int> getXlRank() const;
void setXlRank(const std::vector<int> &value);
std::string getParentIonExist() const;
void setParentIonExist(const std::string &value);
int getParentIonExistNum() const;
void setParentIonExistNum(int value);
std::vector<int> getParentIonMaxIntensityRanks() const;
void setParentIonMaxIntensityRanks(const std::vector<int> &value);
PsmCrossType getCrossType() const;
void setCrossType(PsmCrossType value);
static std::vector<int> GetPossibleCrosslinkerModSites(std::vector<char> &crosslinkerModSites,
PeptideWithSetModifications *peptide);
/// <summary>
/// Rank experimental mass spectral peaks by intensity
/// </summary>
static std::vector<int> GenerateIntensityRanks(std::vector<double> &experimental_intensities);
static std::string GetTabSepHeaderCross();
static std::string GetTabSepHeaderSingle();
static std::string GetTabSepHeaderGlyco();
std::string ToString();
static std::vector<std::tuple<std::string, std::string>> MatchedIonDataDictionary(PeptideSpectralMatch *psm);
/// <summary>
/// Pack a CrosslinkSpectralMatch into a character buffer.
/// Required for Communication Operations
///
/// Arguments:
/// buf : INOUT buffer used for packing
/// buf_size: IN size of the allocated buffer provided by the upper layer
/// OUT size of required buffer if not large enough (return value -1)
/// or number of bytes used for packgin (return value > 0)
/// MaF : IN (vector of) MatchedFragmentIon(s) to pack
///
/// Return value:
/// -1 : input buffer was not large enough. buf_size will contain the required number
/// of bytes in this case
/// >0 : packing successful, number of bytes used up.
/// </summary>
static int Pack ( char *buf, size_t &buf_size, CrosslinkSpectralMatch *csm);
static int Pack ( char *buf, size_t &buf_size, const std::vector<CrosslinkSpectralMatch *> &csmVec);
static int Pack_internal ( char *buf, size_t &buf_size, CrosslinkSpectralMatch *csm);
/// <summary>
/// Functionality used to reconstruct a CrosslinkSpectralMatch based on a
/// packed buffer.
///
/// Arguments
/// ---------
/// buf: IN input character buffer
/// buf_size: IN size of input buffer
/// count: IN how many elements to unpack. -1 indicates until end of buffer is reached
/// len: OUT number of bytes used for unpacking 'count' elements
/// newCsmVec: OUT (vector of) new CrosslinkSpectralMatch(s) .
/// mods: IN unordered_map of mods applied to Protein. Required to reconstruct a Csm
/// proteinList: IN vector of Protein*. Required to reconstruct a Csm
/// </summary>
static void Unpack ( char *buf, size_t buf_size, int count, size_t &len,
std::vector<CrosslinkSpectralMatch *> &newCsmVec,
const std::vector<Modification*> &mods,
const std::vector<Protein*> &proteinList );
static void Unpack ( char *buf, size_t buf_size, size_t &len,
CrosslinkSpectralMatch **newCsm,
const std::vector<Modification*> &mods,
const std::vector<Protein *> &proteinList );
static void Unpack_internal ( std::vector<char *> &input, int &index, size_t &len,
CrosslinkSpectralMatch** newCsm,
const std::vector<Modification*> &mods,
const std::vector<Protein* > &proteinList,
bool &has_beta_peptide);
};
}
}
|
#ifndef CITIESSTORAGE_H
#define CITIESSTORAGE_H
#include <QObject>
#include <QMap>
#include <QPointF>
#include <QTimer>
#include <QtQml/QQmlListProperty>
#include <QFutureWatcher>
#include <QtPositioning/QGeoPositionInfoSource>
QT_BEGIN_NAMESPACE
class QNetworkAccessManager;
class QNetworkSession;
QT_END_NAMESPACE
class CityData : public QObject{
Q_OBJECT
Q_PROPERTY(int id MEMBER m_id)
Q_PROPERTY(QString name MEMBER m_name)
Q_PROPERTY(QString country MEMBER m_country)
Q_PROPERTY(QPointF coord MEMBER m_coord)
public:
explicit CityData(QObject* parent = nullptr) : QObject(parent){}
CityData(const CityData& other);
int m_id;
QString m_name;
QString m_country;
QPointF m_coord;
};
Q_DECLARE_METATYPE(CityData)
class WeatherData : public QObject{
Q_OBJECT
Q_PROPERTY(QDateTime dateTime READ dateTime NOTIFY dateTimeChanged)
Q_PROPERTY(QString time READ time NOTIFY dateTimeChanged)
Q_PROPERTY(QString description READ description NOTIFY descriptionChanged)
Q_PROPERTY(QString icon READ icon NOTIFY iconChanged)
Q_PROPERTY(double temperature READ temperature NOTIFY temperatureChanged)
Q_PROPERTY(QString temperatureText READ temperatureText NOTIFY temperatureChanged)
public:
explicit WeatherData(QObject* parent = nullptr) : QObject(parent){}
WeatherData(const WeatherData& other) : QObject(nullptr){
m_dateTime = other.m_dateTime;
m_description = other.m_description;
m_icon = other.m_icon;
m_temperature = other.m_temperature;
}
QDateTime dateTime()const{return m_dateTime;}
void setDateTime(const QDateTime& val){
m_dateTime = val;
emit dateTimeChanged();
}
QString time()const;
QString description()const{
return m_description;
}
void setDescription(const QString& val){
m_description = val;
emit descriptionChanged();
}
void setIcon(const QString& base);
QString icon()const{return m_icon;}
void setTemperature(double val){
m_temperature = val;
emit temperatureChanged();
}
double temperature()const{return m_temperature;}
QString temperatureText()const{
QString numStr = QString::number(m_temperature,'f',1);
return QString::number(m_temperature,'f',1) + QStringLiteral(" °C");}
signals:
void dateTimeChanged();
void descriptionChanged();
void iconChanged();
void temperatureChanged();
private:
QDateTime m_dateTime;
QString m_description;
QString m_icon;
double m_temperature = 0;
};
Q_DECLARE_METATYPE(WeatherData)
class WeatherStorage : public QObject
{
Q_OBJECT
Q_PROPERTY(int cityId READ cityId WRITE setCityId)
Q_PROPERTY(QString cityName READ cityName WRITE setCityName)
Q_PROPERTY(QString cityNameToDisplay READ cityNameToDisplay NOTIFY cityNameToDisplayChanged)
Q_PROPERTY(QString suggestionMask READ suggestionMask WRITE setSuggestionMask)
Q_PROPERTY(QQmlListProperty<CityData> suggestion READ suggestion NOTIFY suggestionChanged)
Q_PROPERTY(WeatherData* currentWeather READ currentWeather NOTIFY currentWeatherChanged)
Q_PROPERTY(QQmlListProperty<WeatherData> forecastWeather READ forecastWeather NOTIFY forecastWeatherChanged)
Q_PROPERTY(QString getWeatherTime READ getWeatherTime WRITE setGetWeatherTime NOTIFY getWeatherTimeChanged)
Q_PROPERTY(bool hasValidWeather READ hasValidWeather WRITE setHasValidWeather NOTIFY hasValidWeatherChanged)
Q_PROPERTY(bool hasValidForecast READ hasValidForecast WRITE setHasValidForecast NOTIFY hasValidForecastChanged)
Q_PROPERTY(QPointF coordinates READ coordinates WRITE setCoordinates NOTIFY coordinatesChanged)
private:
using CitiesByNameContainer = QMultiMap<QString, CityData*>;
using CitiesByIdContainer = QMap<int,CityData*>;
struct CitiesContainers{
CitiesByIdContainer byId;
CitiesByNameContainer byName;
};
enum PreferredSource{
UnknownSource = 0,
GpsSource,
CityIdSource,
CityNameSource
};
static const int refreshIntervalMs = 10*60*1000; // 10 min
public:
explicit WeatherStorage(QObject *parent = nullptr);
~WeatherStorage();
bool hasValidWeather()const{return m_hasValidWeather;}
void setHasValidWeather(bool val){
m_hasValidWeather = val;
emit hasValidWeatherChanged();
}
bool hasValidForecast()const{return m_hasValidForecast;}
void setHasValidForecast(bool val){
m_hasValidForecast = val;
emit hasValidForecastChanged();
}
int cityId()const{return m_cityId;}
void setCityId(int val);
protected:
void setCityIdInternal(int val); // without sending data request
public:
QString cityName()const{return m_cityName;}
void setCityName(const QString& val);
protected:
void setCityNameInternal(const QString& val); // without sending data request
public:
QPointF coordinates()const{return m_coordinates;}
void setCoordinates(const QPointF& val);
protected:
void setCoordinatesInternal(const QPointF &val); // without sending data request
public:
QString suggestionMask()const{return m_suggestionMask;}
void setSuggestionMask(const QString& val);
QString cityNameToDisplay()const;
QString getWeatherTime()const{return m_getWeatherTime;}
void setGetWeatherTime(const QString& time){
m_getWeatherTime = tr("get at ") + time;
emit getWeatherTimeChanged();
}
void updateSuggestion();
QQmlListProperty<CityData> suggestion();
Q_INVOKABLE static QString appKey(){return QStringLiteral("6868571b061d81b7a8ea993ef165a68f");}
Q_INVOKABLE static int forecastItemsCount(){return 10;}
Q_INVOKABLE double temperatureAxisMin()const;
Q_INVOKABLE double temperatureAxisMax()const;
WeatherData* currentWeather()const{return m_currentWeather;}
QQmlListProperty<WeatherData> forecastWeather();
signals:
void suggestionChanged();
void cityNameToDisplayChanged();
void coordinatesChanged();
void hasValidWeatherChanged();
void hasValidForecastChanged();
void currentWeatherChanged();
void forecastWeatherChanged();
void getWeatherTimeChanged();
public slots:
Q_INVOKABLE void refreshWeatherAndForecast();
private:
void refreshWeatherOrForecast(bool isForecast);
static CitiesContainers loadCityData();
void parseWeatherJson(const QJsonObject& json, WeatherData* weatherData );
private: // slots
void onLoadCityDataFinished();
void onNetworkSessionOpened();
void onPositionUpdated(QGeoPositionInfo gpsPos);
void onPositionError(QGeoPositionInfoSource::Error e);
void onWeatherReply();
void onForecastReply();
private:
int m_cityId = 0;
QString m_cityName;
QPointF m_coordinates;
PreferredSource m_preferredSource = UnknownSource;
bool m_hasValidWeather = false;
bool m_hasValidForecast = false;
QString m_getWeatherTime;
QString m_suggestionMask;
CitiesByIdContainer m_citiesById;
CitiesByNameContainer m_citiesByName;
bool m_currentWeatherValid = false;
WeatherData* m_currentWeather;
QList<WeatherData*> m_forecastWeather;
QNetworkAccessManager* m_networkManager;
QNetworkSession* m_networkSession;
QFutureWatcher<CitiesContainers>* m_futureWatcher;
QList<CityData*> m_suggestionList;
QGeoPositionInfoSource* m_geoPositionSource = nullptr;
QTimer* m_refreshTimer;
qint64 m_lastGpsUpdated = 0;
};
#endif // CITIESSTORAGE_H
|
#include <QKeyEvent>
#include "myglwidget.h"
#include "modelloader.h"
#include <iostream>
void MyGLWidget::setupBuffers() {
ModelLoader model;
bool res = model.loadObjectFromFile("C:/Users/Fred/Documents/spacefunk/Prak 3/sphere_low.obj");
// Wenn erfolgreich, generiere VBO und Index-Array
if (res) {
if(model.hasTextureCoordinates()){
vboLength = model.lengthOfVBO(0, true, true);
iboLength = model.lengthOfIndexArray();
// Generiere VBO und Index-Array
vboData = new GLfloat[vboLength];
indexData = new GLuint[iboLength];
model.genVBO(vboData, 0, true, true);
model.genIndexArray(indexData);
}else{
modelHasTexture = false;
vboLength = model.lengthOfVBO(0, true, false);
iboLength = model.lengthOfIndexArray();
// Generiere VBO und Index-Array
vboData = new GLfloat[vboLength];
indexData = new GLuint[iboLength];
model.genVBO(vboData, 0, true, false);
model.genIndexArray(indexData);
}
}
else {
std::cout << "modell konnte nicht geladen werden" << std::endl;
}
vbo.create();
vbo.bind();
vbo.setUsagePattern(QOpenGLBuffer::StaticDraw);
vbo.allocate(vboData, sizeof(GLfloat) * vboLength);
vbo.release();
ibo.create();
ibo.bind();
ibo.setUsagePattern(QOpenGLBuffer::StaticDraw);
ibo.allocate(indexData, sizeof(GLuint) * iboLength);
ibo.release();
if(modelHasTexture){
shaderSun->setup([](QOpenGLShaderProgram& shaderProgram) {
int attrPosition = shaderProgram.attributeLocation("vert");
shaderProgram.enableAttributeArray(attrPosition);
int attrTexCoords = shaderProgram.attributeLocation("texCoord");
shaderProgram.enableAttributeArray(attrTexCoords);
int stride = sizeof(GL_FLOAT) * 12;
int offset = 0;
shaderProgram.setAttributeBuffer(attrPosition, GL_FLOAT, offset, 4, stride);
offset += 4 * sizeof(GL_FLOAT);
offset += 4 * sizeof(GL_FLOAT);
shaderProgram.setAttributeBuffer(attrTexCoords, GL_FLOAT, offset, 4, stride);
});
shaderPlanets->setup([](QOpenGLShaderProgram& shaderProgram) {
int attrPosition = shaderProgram.attributeLocation("vertexPosition");
shaderProgram.enableAttributeArray(attrPosition);
int attrNorm = shaderProgram.attributeLocation("vertexNormal");
shaderProgram.enableAttributeArray(attrNorm);
int attrTexCoords = shaderProgram.attributeLocation("texCoord");
shaderProgram.enableAttributeArray(attrTexCoords);
int stride = sizeof(GL_FLOAT) * 12;
int offset = 0;
shaderProgram.setAttributeBuffer(attrPosition, GL_FLOAT, offset, 4, stride);
offset += 4 * sizeof(GL_FLOAT);
shaderProgram.setAttributeBuffer(attrNorm, GL_FLOAT, offset, 4, stride);
offset += 4 * sizeof(GL_FLOAT);
shaderProgram.setAttributeBuffer(attrTexCoords, GL_FLOAT, offset, 4, stride);
});
shaderNormals->setup([](QOpenGLShaderProgram& shaderProgram) {
int attrPosition = shaderProgram.attributeLocation("vert");
shaderProgram.enableAttributeArray(attrPosition);
int attrNorm = shaderProgram.attributeLocation("norm");
shaderProgram.enableAttributeArray(attrNorm);
int attrTexCoords = shaderProgram.attributeLocation("texCoord");
shaderProgram.enableAttributeArray(attrTexCoords);
int stride = sizeof(GL_FLOAT) * 12;
int offset = 0;
shaderProgram.setAttributeBuffer(attrPosition, GL_FLOAT, offset, 4, stride);
offset += 4 * sizeof(GL_FLOAT);
shaderProgram.setAttributeBuffer(attrNorm, GL_FLOAT, offset, 4, stride);
offset += 4 * sizeof(GL_FLOAT);
shaderProgram.setAttributeBuffer(attrTexCoords, GL_FLOAT, offset, 4, stride);
});
}else{
shaderSun->setup([](QOpenGLShaderProgram& shaderProgram) {
int attrPosition = shaderProgram.attributeLocation("vert");
shaderProgram.enableAttributeArray(attrPosition);
int stride = sizeof(GL_FLOAT) * 8;
int offset = 0;
shaderProgram.setAttributeBuffer(attrPosition, GL_FLOAT, offset, 4, stride);
offset += 4 * sizeof(GL_FLOAT);
});
shaderPlanets->setup([](QOpenGLShaderProgram& shaderProgram) {
int attrPosition = shaderProgram.attributeLocation("vertexPosition");
shaderProgram.enableAttributeArray(attrPosition);
int attrNorm = shaderProgram.attributeLocation("vertexNormal");
shaderProgram.enableAttributeArray(attrNorm);
int stride = sizeof(GL_FLOAT) * 8;
int offset = 0;
shaderProgram.setAttributeBuffer(attrPosition, GL_FLOAT, offset, 4, stride);
offset += 4 * sizeof(GL_FLOAT);
shaderProgram.setAttributeBuffer(attrNorm, GL_FLOAT, offset, 4, stride);
});
shaderNormals->setup([](QOpenGLShaderProgram& shaderProgram) {
int attrPosition = shaderProgram.attributeLocation("vert");
shaderProgram.enableAttributeArray(attrPosition);
int attrNorm = shaderProgram.attributeLocation("norm");
shaderProgram.enableAttributeArray(attrNorm);
int stride = sizeof(GL_FLOAT) * 8;
int offset = 0;
shaderProgram.setAttributeBuffer(attrPosition, GL_FLOAT, offset, 4, stride);
offset += 4 * sizeof(GL_FLOAT);
shaderProgram.setAttributeBuffer(attrNorm, GL_FLOAT, offset, 4, stride);
});
}
}
void MyGLWidget::initializePlanets(){
sun = new Sun(QImage(":/textures/sun.jpg"), shaderSun);
sun->radius = 5.0f;
Planet* mercury = new Planet(QImage(":/textures/mercurymap.jpg"), shaderPlanets);
mercury->radius = 0.38f;
mercury->setRotation(0.0f, 1.0f / 60.0f);
mercury->setOrbit(sun->radius + mercury->radius + 7.54f, 1.2f);
Planet* venus = new Planet(QImage(":/textures/venusmap.jpg"), shaderPlanets);
venus->radius = 0.95f;
venus->setRotation(0.0f, 1.0f / 240.0f);
venus->setOrbit(sun->radius + venus->radius + 8.48f, 1.5f);
Planet* earth = new Planet(QImage(":/textures/earthmap.jpg"), shaderPlanets);
earth->radius = 1.00f;
earth->setRotation(23.22f, 1.0f);
earth->setOrbit(sun->radius + earth->radius + 11.72f, 1.0f);
Planet* moonEarth = new Planet(QImage(":/textures/moonmap.jpg"), shaderPlanets);
moonEarth->radius = 0.25f;
moonEarth->setRotation(0.0f, 0.0f);
moonEarth->setOrbit(sun->radius + earth->radius + moonEarth->radius + 13.0f, 1.0f);
earth->addChild(moonEarth);
Planet* mars = new Planet(QImage(":/textures/marsmap.jpg"), shaderPlanets);
mars->radius = 0.53f;
mars->setRotation(0.0f, 0.5f);
mars->setOrbit(sun->radius + mars->radius + 17.87f, 0.5f);
Planet* moonMars1 = new Planet(QImage(":/textures/moonmap.jpg"), shaderPlanets);
moonMars1->radius = 0.2f;
moonMars1->setRotation(0.0f, 1.0f);
moonMars1->setOrbit(sun->radius + mars->radius + moonMars1->radius + 18.5f, 1.5f);
Planet* moonMars2 = new Planet(QImage(":/textures/moonmap.jpg"), shaderPlanets);
moonMars2->radius = 0.3f;
moonMars2->setRotation(0.0f, 1.0f);
moonMars2->setOrbit(sun->radius + mars->radius + moonMars2->radius + 19.5f, 1.0f);
mars->addChild(moonMars1);
mars->addChild(moonMars2);
Planet* jupiter = new Planet(QImage(":/textures/jupitermap.jpg"), shaderPlanets);
jupiter->radius = 2.3f;
jupiter->setRotation(0.0f, 2.0f);
jupiter->setOrbit(sun->radius + jupiter->radius + 30.0f, 0.4f);
Planet* saturn = new Planet(QImage(":/textures/saturnmap.jpg"), shaderPlanets);
saturn->radius = 2.5f;
saturn->setRotation(0.0f, 2.0f);
saturn->setOrbit(sun->radius + saturn->radius + 50.0f, 0.3f);
Planet* uranus = new Planet(QImage(":/textures/uranusmap.jpg"), shaderPlanets);
uranus->radius = 3.0f;
uranus->setRotation(0.0f, 1.5f);
uranus->setOrbit(sun->radius + uranus->radius + 80.0f, 0.2f);
Planet* neptune = new Planet(QImage(":/textures/neptunemap.jpg"), shaderPlanets);
neptune->radius = 3.2f;
neptune->setRotation(0.0f, 1.5f);
neptune->setOrbit(sun->radius + neptune->radius + 120.0f, 0.15f);
sun->addChild(mercury);
sun->addChild(venus);
sun->addChild(earth);
sun->addChild(mars);
sun->addChild(jupiter);
sun->addChild(saturn);
sun->addChild(uranus);
sun->addChild(neptune);
}
void MyGLWidget::initializeGL() {
// Set global information
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
// *** Initialization ***
glEnable(GL_TEXTURE_2D);
shaderNormals = new Shader(":/shaders/shader.vert", ":/shaders/shader.frag", vbo, ibo);
if(modelHasTexture){
shaderSun = new Shader(":/shaders/shaderTextureSun.vert", ":/shaders/shaderTextureSun.frag", vbo, ibo);
shaderPlanets = new Shader(":/shaders/shaderTexture.vert", ":/shaders/shaderTexture.frag", vbo, ibo);
}else{
shaderSun = new Shader(":/shaders/shaderTextureSun.vert", ":/shaders/shaderEinfarbig.frag", vbo, ibo);
shaderPlanets = new Shader(":/shaders/shaderTexture.vert", ":/shaders/shaderEinfarbig.frag", vbo, ibo);
}
initializePlanets();
setupBuffers();
}
void MyGLWidget::resizeGL(int width, int height) {
// Compute aspect ratio
height = (height == 0) ? 1 : height;
GLfloat aspect = (GLfloat) width / (GLfloat) height;
// Where is the camera
QVector3D eye (0.0, 0.0, 0.1);
// At which point should it look
QVector3D center(0.0, 0.0, 0.0);
// In which direction should it look
QVector3D up (0.0, 1.0, 0.0);
pMatrix.setToIdentity();
pMatrix.lookAt(eye, center, up);
pMatrix.perspective(45.0f, aspect, 0.1f, 1000.0f);
pOld = pMatrix;
}
void MyGLWidget::paintGL() {
// Clear
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
vMatrix.setToIdentity();
pMatrix = pOld;
pMatrix.rotate(angle, 0, 1, 0);
pMatrix.rotate(angleY, 1, 0, 0);
pMatrix.translate(camX, camY, camZ);
sun->renderPlanet(counter, pMatrix, vMatrix, iboLength);
counter += 0.01f;
QOpenGLWidget::update();
}
void MyGLWidget::keyPressEvent(QKeyEvent* event) {
if (event->key() == Qt::Key_W) {
camY -= 1.5f;
}else if (event->key() == Qt::Key_S) {
camY += 1.5f;
}else if (event->key() == Qt::Key_A) {
camX += 1.5f;
}else if (event->key() == Qt::Key_D) {
camX -= 1.5f;
}else if (event->key() == Qt::Key_Up) {
angleY -= 1.0f;
}else if (event->key() == Qt::Key_Down) {
angleY += 1.0f;
}else if (event->key() == Qt::Key_Left) {
angle -= 1.0f;
}else if (event->key() == Qt::Key_Right) {
angle += 1.0f;
}else if (event->key() == Qt::Key_R){
angle = 0.0f;
angleY = 0.0f;
camX = 0.0f;
camY = 0.0f;
camZ = -7.0f;
}else {
QOpenGLWidget::keyPressEvent(event);
}
QOpenGLWidget::update();
}
void MyGLWidget::wheelEvent(QWheelEvent* event) {
const int degrees = event->delta() / 8;
int steps = degrees / 15;
if(steps > 0){
camZ += 1.0f;
}else{
camZ -= 1.0f;
}
QOpenGLWidget::update();
}
MyGLWidget::MyGLWidget(QWidget *parent) : QOpenGLWidget(parent) {
setFocusPolicy(Qt::StrongFocus);
}
|
#include "window_manager.hpp"
WindowManager::WindowManager():
shift_l_pressed(false),
shift_r_pressed(false),
ctrl_l_pressed(false),
ctrl_r_pressed(false),
left_dragging(false),
maybe_left_click(false),
max_queue_size(5),
sliding_step(10),
cur_offset_x(0.0), // center
cur_offset_y(0.0), // center
initial_scale(1.0),
scale_base(std::sqrt(2.0)), cur_scale_exponent(0),
last_scale(1.0), fit_to_window(true), tile_size(64),
last_im_cols(1),last_im_rows(1)
{
}
WindowManager::WindowManager(const int width, const int height)
:shift_l_pressed(false),
shift_r_pressed(false),
ctrl_l_pressed(false),
ctrl_r_pressed(false),
left_dragging(false),
maybe_left_click(false),
max_queue_size(5),
sliding_step(10),
cur_offset_x(0.0), // center
cur_offset_y(0.0), // center
initial_scale(1.0),
scale_base(std::sqrt(2.0)), cur_scale_exponent(0),
last_scale(1.0), fit_to_window(true), tile_size(64),
last_im_cols(1),last_im_rows(1){
dis = XOpenDisplay(nullptr);
if(! dis){
std::cerr << my_utils_kk4::red
<< "[ERROR] Failed to open a new window (" << __FILE__
<< ", line " << __LINE__ << ")"
<< my_utils_kk4::default_color
<< std::endl;
}
screen = DefaultScreen(dis);
win = XCreateSimpleWindow(dis, RootWindow(dis, screen), 0, 0, width, height,
5, None, None);
XSelectInput(dis, win,
ExposureMask | ButtonPressMask | ButtonReleaseMask |
Button1MotionMask | KeyPressMask | KeyReleaseMask |
StructureNotifyMask | PointerMotionMask);
gc = XCreateGC(dis, win, 0, 0);
Atom wmDelete = XInternAtom(dis, "WM_DELETE_WINDOW", true);
XSetWMProtocols(dis, win, &wmDelete, 1);
setDefaultBackground();
XMapRaised(dis, win);
// XAutoRepeatOff(dis);
while(true){
XEvent x_event;
XNextEvent(dis, &x_event);
if(x_event.type == Expose){
XClearWindow(dis, win);
break;
}
}
}
WindowManager::~WindowManager(){}
void WindowManager::update(const cv::Mat& im, const std::string& current_path){
XStoreName(dis, win, current_path.c_str());
const std::string window_title = generateWindowTitleFromPathString(current_path);
XChangeProperty(dis, win,
XInternAtom(dis, "_NET_WM_NAME", False),
XInternAtom(dis, "UTF8_STRING", False),
8, PropModeReplace, (const unsigned char*)window_title.c_str(),
strlen(window_title.c_str()));
last_im_cols = im.cols;
last_im_rows = im.rows;
if(im.empty()){
XClearWindow(dis, win);
}else{
drawImage(im);
}
}
WindowManager::Command WindowManager::nextCommand(){
XEvent x_event, dummy;
XNextEvent(dis, &x_event);
while(XEventsQueued(dis, QueuedAlready) > max_queue_size){
XNextEvent(dis, &dummy);
}
return processEvent(x_event);
}
void WindowManager::scaleUp(){
if(fit_to_window){
disableFitToWindow();
}
cur_scale_exponent += 1;
}
void WindowManager::scaleDown(){
if(fit_to_window){
disableFitToWindow();
}
cur_scale_exponent -= 1;
}
void WindowManager::moveRight(){
cur_offset_x += sliding_step / last_scale;
}
void WindowManager::moveLeft(){
cur_offset_x -= sliding_step / last_scale;
}
void WindowManager::moveUp(){
cur_offset_y -= sliding_step / last_scale;
}
void WindowManager::moveDown(){
cur_offset_y += sliding_step / last_scale;
}
void WindowManager::moveCenter(){
cur_offset_x = cur_offset_y = 0.0;
}
void WindowManager::clearScaleAndOffset(){
cur_offset_x = cur_offset_y = 0.0;
fit_to_window = true;
cur_scale_exponent = 0;
}
void WindowManager::closeWindow(){
XFreeGC(dis, gc);
XDestroyWindow(dis,win);
XCloseDisplay(dis);
}
void WindowManager::drawImage(const cv::Mat& im){
XColor c;
cv::Vec3b v;
Colormap cmap = XDefaultColormap(dis, screen);
const int depth = DefaultDepth(dis, screen);
double upper_left_x, upper_left_y;
cv::Mat tmp_im;
if(fit_to_window){
generateImageToDrawFitToWindow(im, &tmp_im, &upper_left_x, &upper_left_y, &last_scale);
}else{
generateImageToDraw(im, &tmp_im, &upper_left_x, &upper_left_y, &last_scale);
}
if(tmp_im.empty()){
XClearWindow(dis, win);
return;
}
cv::cvtColor(tmp_im, tmp_im, cv::COLOR_BGR2BGRA);
XImage *x_im = XCreateImage(dis, CopyFromParent, depth,
ZPixmap, 0, (char*)tmp_im.data,
tmp_im.cols, tmp_im.rows, 32, 0);
Pixmap pix = XCreatePixmap(dis, win, tmp_im.cols, tmp_im.rows, depth);
XPutImage(dis, pix, gc, x_im, 0, 0, 0, 0, tmp_im.cols, tmp_im.rows);
XClearWindow(dis, win);
XCopyArea(dis, pix, win, gc, 0, 0, tmp_im.cols, tmp_im.rows,
upper_left_x, upper_left_y);
XFlush(dis);
return;
}
void WindowManager::generateImageToDrawFitToWindow(const cv::Mat& in_im, cv::Mat * const out_im,
double * const upper_left_x,
double * const upper_left_y,
double * const scale)const{
const double tmp_scale = calcScaleToFitToWindow(in_im);
cv::resize(in_im, *out_im, cv::Size(0, 0), tmp_scale, tmp_scale, cv::INTER_AREA);
int width, height;
getWindowSize(&width, &height);
*upper_left_x = (width - out_im->cols) / 2 + cur_offset_x;
*upper_left_y = (height - out_im->rows) / 2 + cur_offset_y;
if(scale){
*scale = tmp_scale;
}
return;
}
void WindowManager::generateImageToDraw(const cv::Mat& in_im, cv::Mat * const out_im,
double * const upper_left_x,
double * const upper_left_y,
double * const scale)const{
const double tmp_scale = initial_scale * std::pow(scale_base, cur_scale_exponent);
double u_l_x, u_l_y, l_r_x, l_r_y;
getRegionToDraw(in_im, tmp_scale, &u_l_x, &u_l_y, &l_r_x, &l_r_y);
if(u_l_x < 0){
*upper_left_x = (-u_l_x) * tmp_scale;
u_l_x = 0;
}else if(u_l_x >= in_im.cols){
*upper_left_x = 0;
u_l_x = in_im.cols - 1;
}else{
*upper_left_x = 0;
}
if(u_l_y < 0){
*upper_left_y = (-u_l_y) * tmp_scale;
u_l_y = 0;
}else if(u_l_y >= in_im.rows){
*upper_left_y = 0;
u_l_y = in_im.rows - 1;
}else{
*upper_left_y = 0;
}
l_r_x = (l_r_x >= in_im.cols) ? in_im.cols - 1 : l_r_x;
l_r_y = (l_r_y >= in_im.rows) ? in_im.rows - 1 : l_r_y;
l_r_x = (l_r_x < 0) ? 0 : l_r_x;
l_r_y = (l_r_y < 0) ? 0 : l_r_y;
if(l_r_x - u_l_x <= 0 || l_r_y - u_l_y <= 0){
*out_im = cv::Mat();
}else{
cv::Rect roi(u_l_x, u_l_y, l_r_x - u_l_x + 1, l_r_y - u_l_y + 1);
cv::resize(in_im(roi), *out_im, cv::Size(0,0), tmp_scale, tmp_scale, cv::INTER_AREA);
}
if(scale){
*scale = tmp_scale;
}
return;
}
double WindowManager::calcScaleToFitToWindow(const cv::Mat& im)const{
XWindowAttributes window_attributes;
XGetWindowAttributes(dis, win, &window_attributes);
const double scale_v = (double)window_attributes.height / im.rows;
const double scale_h = (double)window_attributes.width / im.cols;
double tmp_scale = 1.0;
// calc min(1.0, scale_v, scale_h)
if(scale_v < tmp_scale){
tmp_scale = scale_v;
}
if(scale_h < tmp_scale){
tmp_scale = scale_h;
}
return tmp_scale;
}
void WindowManager::getWindowSize(int * const width, int * const height)const{
XWindowAttributes window_attributes;
XGetWindowAttributes(dis, win, &window_attributes);
*height = window_attributes.height;
*width = window_attributes.width;
return;
}
void WindowManager::setDefaultBackground(){
const int depth = DefaultDepth(dis, screen);
int width, height;
{
XWindowAttributes window_attributes;
XGetWindowAttributes(dis, win, &window_attributes);
width = window_attributes.width;
height = window_attributes.height;
}
const int width_big = width % tile_size ? (width / tile_size + 1) * tile_size : width;
const int height_big = height % tile_size ? (height / tile_size + 1) * tile_size : height;
std::vector<XRectangle> rectangles;
for(int i_v = 0; i_v < height_big / tile_size; i_v++){
int count = i_v % 2;
for(int i_h = 0; i_h < width_big / tile_size; i_h++){
if(count % 2){
XRectangle tmp_rect;
tmp_rect.x = i_h * tile_size;
tmp_rect.y = i_v * tile_size;
tmp_rect.width = tile_size;
tmp_rect.height = tile_size;
rectangles.push_back(tmp_rect);
}
count++;
}
}
XColor gray1, gray2;
gray1.red = gray1.green = gray1.blue = 0x4f00;
gray2.red = gray2.green = gray2.blue = 0x4000;
gray1.flags = gray2.flags = DoRed | DoGreen | DoBlue;
XAllocColor(dis, XDefaultColormap(dis, screen), &gray1);
XAllocColor(dis, XDefaultColormap(dis, screen), &gray2);
Pixmap pix = XCreatePixmap(dis, win, width, height, depth);
XSetForeground(dis, gc, gray1.pixel);
XFillRectangle(dis, pix, gc, 0, 0, width, height);
XSetForeground(dis, gc, gray2.pixel);
XFillRectangles(dis, pix, gc, rectangles.data(), (int)rectangles.size());
XSetWindowBackgroundPixmap(dis, win, pix);
}
void WindowManager::getRegionToDraw(const cv::Mat& in_im, const double scale,
double * const upper_left_x, double * const upper_left_y,
double * const lower_right_x, double * const lower_right_y)const{
int window_width, window_height;
getWindowSize(&window_width, &window_height);
const double tmp_width = window_width / scale;
const double tmp_height = window_height / scale;
*upper_left_x = - (tmp_width / 2.0) + in_im.cols / 2.0 - cur_offset_x;
*upper_left_y = - (tmp_height / 2.0) + in_im.rows / 2.0 - cur_offset_y;
*lower_right_x = // std::ceil
((tmp_width / 2.0) + in_im.cols / 2.0 - cur_offset_x);
*lower_right_y = // std::ceil
((tmp_height / 2.0) + in_im.rows / 2.0 - cur_offset_y);
return;
}
WindowManager::Command WindowManager::processEvent(const XEvent& event){
if(event.type == KeyPress){
KeySym key_sym = XkbKeycodeToKeysym(dis, event.xkey.keycode, 0,
event.xkey.state & ShiftMask ? 1 : 0);
switch(key_sym){
case XK_Right:
if(isShiftPressed()){
return MOVE_RIGHT;
}else{
return NEXT_IM;
}
case XK_Left:
if(isShiftPressed()){
return MOVE_LEFT;
}else{
return PREVIOUS_IM;
}
case XK_Return:
if(isShiftPressed()){
return PREVIOUS_IM;
}else{
return NEXT_IM;
}
case XK_Up:
if(isShiftPressed()){
return MOVE_UP;
}else if(isCtrlPressed()){
return SCALE_UP;
}else{
return PREVIOUS_BROTHER_DIR;
}
case XK_Down:
if(isShiftPressed()){
return MOVE_DOWN;
}else if(isCtrlPressed()){
return SCALE_DOWN;
}else{
return NEXT_BROTHER_DIR;
}
case XK_Page_Up:
return UPPER_DIR;
case XK_Page_Down:
return LOWER_DIR;
case XK_plus:
return SCALE_UP;
case XK_minus:
return SCALE_DOWN;
case XK_Shift_L:
shift_l_pressed = true;
return NOTHING;
case XK_Shift_R:
shift_r_pressed = true;
return NOTHING;
case XK_Control_L:
ctrl_l_pressed = true;
return NOTHING;
case XK_Control_R:
ctrl_r_pressed = true;
return NOTHING;
case XK_c:
return CLEAR;
case XK_q:
return QUIT;
default:
return NOTHING;
}
}else if(event.type == KeyRelease){
KeySym key_sym = XkbKeycodeToKeysym(dis, event.xkey.keycode, 0,
event.xkey.state & ShiftMask ? 1 : 0);
switch(key_sym){
case XK_Shift_L:
shift_l_pressed = false;
return NOTHING;
case XK_Shift_R:
shift_r_pressed = false;
return NOTHING;
case XK_Control_L:
ctrl_l_pressed = false;
return NOTHING;
case XK_Control_R:
ctrl_r_pressed = false;
return NOTHING;
default:
return NOTHING;
}
}else if(event.type == ButtonPress){
switch(event.xbutton.button){
case Button1: // left click
maybe_left_click = true;
return NOTHING;
case Button4: // wheel up
if(isCtrlPressed()){
return SCALE_UP;
}else{
return PREVIOUS_IM;
}
case Button5: // wheel down
if(isCtrlPressed()){
return SCALE_DOWN;
}else{
return NEXT_IM;
}
default:
return NOTHING;
}
}else if(event.type == ButtonRelease){
switch(event.xbutton.button){
case Button1:
if(maybe_left_click){
maybe_left_click = false;
return NEXT_IM;
}
return NOTHING;
default:
return NOTHING;
}
}else if(event.type == MotionNotify){ // mouse motion
XButtonEvent* tmp_event = (XButtonEvent*)&event;
{ // print mouse position on the image
int x_on_im = 0, y_on_im = 0;
window2ImageCoord(tmp_event->x, tmp_event->y, &x_on_im, &y_on_im);
x_on_im = (x_on_im < 0) ? 0 : x_on_im;
y_on_im = (y_on_im < 0) ? 0 : y_on_im;
x_on_im = (x_on_im >= last_im_cols) ? last_im_cols - 1: x_on_im;
y_on_im = (y_on_im >= last_im_rows) ? last_im_rows - 1: y_on_im;
std::cout << "\r(x: " << x_on_im << ", y: " << y_on_im << ") " << std::flush;
}
if(tmp_event->state & Button1Mask){
if(maybe_left_click){
maybe_left_click = false;
}
if(fit_to_window){
disableFitToWindow();
}
if(! left_dragging){
XButtonEvent* tmp_event = (XButtonEvent*)&event;
last_x_while_dragging = tmp_event->x;
last_y_while_dragging = tmp_event->y;
left_dragging = true;
}else{
cur_offset_x += (tmp_event->x - last_x_while_dragging) / last_scale;
cur_offset_y += (tmp_event->y - last_y_while_dragging) / last_scale;
last_x_while_dragging = tmp_event->x;
last_y_while_dragging = tmp_event->y;
return REDRAW;
}
}else{
left_dragging = false;
}
return NOTHING;
}else if(event.type == ConfigureNotify){
return REDRAW;
}else if(event.type == ClientMessage){
std::cerr << "[INFO ] Window closure detected. Quiting the program." << std::endl;
return QUIT;
}else{
return NOTHING;
}
return NOTHING;
}
std::string WindowManager::generateWindowTitleFromPathString(
const std::string& path_str
)const{
std::string ret;
size_t pos = 0;
const int len = static_cast<int>(path_str.size());
const size_t slash1_pos = path_str.rfind('/');
if(slash1_pos == std::string::npos){
pos = 0;
}else{
const size_t slash2_pos = path_str.substr(0, slash1_pos).rfind('/');
if(slash2_pos == std::string::npos){
pos = slash1_pos + 1;
}else{
pos = slash2_pos + 1;
}
}
if(pos == 0){
ret = path_str;
}else{
ret = path_str.substr(pos) + " (in " + path_str.substr(0, pos) + ")";
}
return ret;
}
bool WindowManager::isShiftPressed()const{
return shift_l_pressed || shift_r_pressed;
}
bool WindowManager::isCtrlPressed()const{
return ctrl_l_pressed || ctrl_r_pressed;
}
void WindowManager::disableFitToWindow(){
fit_to_window = false;
initial_scale = last_scale;
}
void WindowManager::window2ImageCoord(const int x_window, const int y_window,
int * const x_image, int * const y_image)const{
int window_width, window_height;
getWindowSize(&window_width, &window_height);
*x_image = (int)((x_window - window_width / 2.0) / last_scale + last_im_cols / 2.0 - cur_offset_x);
*y_image = (int)((y_window - window_height / 2.0) / last_scale + last_im_rows / 2.0 - cur_offset_y);
}
|
#include "client.h"
#include "gui/view_constants.h"
#include <algorithm>
#include <chrono>
#include "sprites/drawer_factory.h"
#include "messages/json_message_conversions.h"
#include "messages/message_makers.h"
#include "animations/animations_service.h"
#include "sprites/sprites_manager.h"
client::client(const std::string& address, unsigned short port)
: address(address),
port(port),
joiner("\n") {
}
void client::connect()
{
std::cout << "Waiting for server...\n";
asio::ip::tcp::endpoint endpoint(asio::ip::address::from_string(address), port);
socket = std::make_unique<asio::ip::tcp::socket>(io_service);
try {
socket->connect(endpoint);
} catch (...) {
std::cout << "connect exception\n";
}
std::cout << "Server connected:)\n";
read_async();
try {
io_service_thread = std::thread([this]() {
io_service.run();
});
} catch (asio::system_error& err) {
std::cout << "connect exception: " << err.what() << "\n";
}
}
threadsafe_queue<std::string>& client::get_message_queue() {
return message_queue;
}
void client::send_message(const std::string& message) {
asio::write(*socket, asio::buffer(message), asio::transfer_all());
}
void client::read_async() {
asio::async_read_until(*socket, buffer, "\n",
[this](const asio::error_code& error,
std::size_t bytes_transferred) {
if (error) {
std::cout << "errorfsdf" << error.message() << "\n";
}
std::cout << "Get message\n";
std::istream istream(&buffer);
std::string message_data(std::istreambuf_iterator<char>(istream), {});
auto messages = joiner.add_message_data(message_data);
for (auto&& message : messages) {
std::cout << message << "\n";
message_queue.push(message);
}
buffer.consume(buffer.size() + 1);
read_async();
});
}
|
#ifndef BUILDER_HPP_
#define BUILDER_HPP_
#include <iostream>
#include <memory>
class Plane {
public:
void SetType(const std::string& type) { type_ = type; }
void SetEngine(const std::string& engine) { engine_ = engine; }
void SetVendor(const std::string& vendor) { vendor_ = vendor; }
void SetModelName(const std::string& model_name) { model_ = model_name;}
void See() const {
std::cout << model_ << ":" << std::endl;
std::cout << "Plane's Vendor is " << vendor_ << ", with "
<< engine_ << " engine, " << type_ << "type." << std::endl;
}
private:
std::string type_;
std::string engine_;
std::string vendor_;
std::string model_;
};
class PlaneBuilder {
public:
virtual ~PlaneBuilder() = default;
void CreatePlane() {
plane_ = std::make_unique<Plane>();
}
Plane* GetPlane() { return plane_.get(); }
virtual void SelectType() = 0;
virtual void SelectEngineType() = 0;
virtual void SelectVendor() = 0;
virtual void SelectModel() = 0;
protected:
std::unique_ptr<Plane> plane_;
};
class F18 : public PlaneBuilder{
public:
~F18() override = default;
virtual void SelectType() override {
plane_->SetType("Fighter ");
}
virtual void SelectEngineType() override {
plane_->SetEngine("Jet");
}
virtual void SelectVendor() override {
plane_->SetVendor("Boeing");
}
virtual void SelectModel() override {
plane_->SetModelName("F-18");
}
};
class A320 : public PlaneBuilder {
public:
~A320() override = default;
virtual void SelectType() override {
plane_->SetType("Airliner ");
}
virtual void SelectEngineType() override {
plane_->SetEngine("Turbo Fan");
}
virtual void SelectVendor() override {
plane_->SetVendor("Airbus");
}
virtual void SelectModel() override {
plane_->SetModelName("A320");
}
};
class Consumer {
public:
void SeePlane() { builder->GetPlane()->See(); }
void ProducePlane(PlaneBuilder *pb) {
builder = pb;
builder->CreatePlane();
builder->SelectType();
builder->SelectEngineType();
builder->SelectVendor();
builder->SelectModel();
}
private:
PlaneBuilder *builder;
};
#endif // BUILDER_HPP_
|
#pragma once
#include <boost/asio.hpp>
#include "Protos.pb.h"
#include <iostream>
using boost::asio::ip::tcp;
namespace util {
static const int MAX_MESSAGE_SIZE = 1000000;
static const int HEADER_SIZE = 6;
static size_t decode_header(const char* data) {
char header[HEADER_SIZE + 1] = "";
strncat_s(header, data, HEADER_SIZE);
return std::atoi(header);
}
static void encode_header(size_t body_length, uint8_t* data)
{
char header[HEADER_SIZE + 1] = "";
sprintf_s(header, "%6d", static_cast<int>(body_length));
std::memcpy(data, header, HEADER_SIZE);
}
static int fillMessage(uint8_t* arr, protos::Message& message) {
int messageSize = message.ByteSize();
if (messageSize > MAX_MESSAGE_SIZE) {
std::cerr << "MAX MESSAGE SIZE EXCEEDED" << std::endl;
return 0;
}
encode_header(messageSize, arr);
message.SerializeToArray(&arr[HEADER_SIZE], messageSize);
return messageSize;
}
static void sendMessage(tcp::socket& socket, protos::Message& message) {
std::uint8_t arr[HEADER_SIZE + MAX_MESSAGE_SIZE] = {};
auto messageSize = fillMessage(arr, message);
if (messageSize != 0) {
boost::asio::write(socket,
boost::asio::buffer(arr, messageSize + HEADER_SIZE));
}
}
}
|
/* Arduino SdSpi Library
* Copyright (C) 2013 by William Greiman
*
* STM32F1 code for Maple and Maple Mini support, 2015 by Victor Perez
*
* This file is part of the Arduino SdSpi Library
*
* This Library is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This Library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with the Arduino SdSpi Library. If not, see
* <http://www.gnu.org/licenses/>.
*/
#if defined (__PIC32MX__)
#include "SdSpi.h"
#include <DSPI.h>
//May have to manually include DSPI.h in main sketch (unless using UECIDE)
#define SWAPENDIAN_32(x) (uint32_t)((((x) & 0xFF000000UL) >> 24UL) | (((x) & 0x00FF0000UL) >> 8UL) | \
(((x) & 0x0000FF00UL) << 8UL) | (((x) & 0x000000FFUL) << 24UL))
//Use the default SPI port because SDFat begin()
// doesn't allow passing application-specific variables
//This SHOULD be stored internally...
DSPI *_spi=new DSPI0;
/*
//------------------------------------------------------------------------------
void SdSpi::chipSelectHigh() {
//TODO: Needs to be implemented via direct register writes...
}
//------------------------------------------------------------------------------
void SdSpi::chipSelectLow() {
//TODO: Needs to be implemented via direct register writes...
}
*/
//------------------------------------------------------------------------------
void SdSpi::begin() {
_spi->begin();
//TODO: Needs to instantiate the user-selected DSPI object (0-4)
// Also needs to be passed the ChipSelect pin being used,
// otherwise it uses Pin 10 by default.
}
//------------------------------------------------------------------------------
void SdSpi::init(uint8_t divisor) {
//_spi->setOrder does not exist
_spi->setMode(DSPI_MODE0);
_spi->setSpeed( F_CPU/(2*((uint32_t) divisor+1)) );
}
//------------------------------------------------------------------------------
uint8_t SdSpi::receive() {
return _spi->transfer(0XFF);
}
//------------------------------------------------------------------------------
uint8_t SdSpi::receive(uint8_t* buf, size_t n) {
size_t m =(n >> 2);
if (m) {
uint32_t* byteptr = (uint32_t*)buf;
_spi->setTransferSize(DSPI_32BIT);
for (size_t i=0;i<m;i++) {
*byteptr=_spi->transfer( (uint32_t) 0xFFFFFFFF );
*byteptr=SWAPENDIAN_32(*byteptr);
byteptr++;
}
m = n+1;
n &= 0x3;
_spi->setTransferSize(DSPI_8BIT);
}
if(n) {
_spi->transfer(n,0xFF, &(buf[m]));
}
return 0;
}
//------------------------------------------------------------------------------
void SdSpi::send(uint8_t data) {
_spi->transfer(data);
}
//------------------------------------------------------------------------------
void SdSpi::send(const uint8_t* buf , size_t n) {
size_t m =(n >> 2);
if (m) {
uint32_t* byteptr = (uint32_t*)buf;
_spi->setTransferSize(DSPI_32BIT);
for (size_t i=0;i<m;i++) {
_spi->transfer( SWAPENDIAN_32(*byteptr));
byteptr++;
}
m = n+1;
n &= 0x3;
_spi->setTransferSize(DSPI_8BIT);
}
if(n) {
_spi->transfer(n,(uint8_t*)&(buf[m]));
}
}
#endif // __PIC32MX__
|
#include "Setup_2014_EPT.h"
using namespace std;
namespace ant {
namespace expconfig {
namespace setup {
/**
* @brief Ant Setup for the October 2014 End Point Tagger beam time
* @see https://wwwa2.kph.uni-mainz.de/intern/daqwiki/analysis/beamtimes/2014-10-14
*/
class Setup_2014_10_EPT_Prod : public Setup_2014_EPT
{
public:
Setup_2014_10_EPT_Prod(const std::string& name, OptionsPtr opt)
: Setup_2014_EPT(name, opt)
{
// see https://wwwa2.kph.uni-mainz.de/intern/daqwiki/analysis/beamtimes/2014-10-14
IgnoreDetectorChannels(Detector_t::Type_t::CB, {17,125,189,265,267,418,456,547,549,557,565,582,586,597,602,672,677,678,696});
IgnoreDetectorChannels(Detector_t::Type_t::TAPS, {2, 73, 127, 137, 138, 144, 145, 146, 147, 200, 218, 220, 222, 283, 291, 346, 353, 356, 357, 363, 364, 368, 437});
// Not enough statistics for runbyrun "-a 20"
IgnoreDetectorChannels(Detector_t::Type_t::TAPS, {0,3,64,72,74,75,139,149,210,217,273,284,295,347,358,362,367,419});
IgnoreDetectorChannels(Detector_t::Type_t::TAPSVeto, {6,64,128,192,256,263,287,321,337,349});
}
bool Matches(const TID& tid) const override {
if(!std_ext::time_between(tid.Timestamp, "2014-10-14", "2014-11-03"))
return false;
return true;
}
};
// don't forget registration
AUTO_REGISTER_SETUP(Setup_2014_10_EPT_Prod)
}}} // namespace ant::expconfig::setup
|
/*
16236. 아기 상어 다시풀기의 다시풀기
30분
bfs로 거리를 한칸 씩 늘려가면서 체크하려면,
int size = (int)q.size();
for(int m = 0; m < size; m++)
이런 식으로 1칸씩 이동된 현재 q의 데이터까지만 체크하는 방식으로 해야한다.
*/
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
#include <algorithm>
#define MAX 11
using namespace std;
typedef pair<int, int> pii;
struct shark_info
{
int r, c, size = 2, fish = 0;
};
shark_info shark;
int N;
int board[20][20];
bool visited[20][20];
int dr[4] = {0,0,-1,1};
int dc[4] = {1,-1,0,0};
bool comp(pii a, pii b)
{
if(a.first == b.first) return a.second < b.second;
else return a.first < b.first;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cin >> N;
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
cin >> board[i][j];
if(board[i][j] == 9)
{
shark.r = i; shark.c = j;
board[i][j] = 0;
}
}
}
bool eat = true;
int answer = 0;
while (eat)
{
memset(visited, false, sizeof(visited));
int time = answer;
queue<pii> q;
vector<pii> v; // 잡은 물고기
q.push(make_pair(shark.r, shark.c));
visited[shark.r][shark.c] = true;
eat = false;
while (!q.empty())
{
time++;
int size = (int)q.size();
for(int m = 0; m < size; m++)
{
int r = q.front().first;
int c = q.front().second;
q.pop();
for(int i = 0; i < 4; i++)
{
int nr = r + dr[i];
int nc = c + dc[i];
if(nr < 0 || nr > N-1 || nc < 0 || nc > N-1 ||
visited[nr][nc] || board[nr][nc] > shark.size) continue;
visited[nr][nc] = true;
if(0 < board[nr][nc] && board[nr][nc] < shark.size)
v.push_back(make_pair(nr, nc));
else
q.push(make_pair(nr, nc));
}
}
if(v.size() > 0)
{
sort(v.begin(), v.end(), comp);
board[v[0].first][v[0].second] = 0;
shark.fish++;
shark.r = v[0].first;
shark.c = v[0].second;
if(shark.fish == shark.size)
{
shark.fish = 0;
shark.size++;
}
answer = time;
eat = true;
break;
}
}
}
printf("%d\n", answer);
return 0;
}
|
#pragma once
struct Editor;
/*
This interface defines the Listenable object that Listeners can subscribe to
and are notified when the Listenable changes. User by the GUI elements to
know when they need a redraw.
*/
class Listenable
{
protected:
static const int maxListeners = 128;
Editor *mListeners[maxListeners];
int mNumListeners;
public:
Listenable();
bool addListener(Editor *editor);
void notify();
};
|
/**
* @file Configuration.cpp
* @author Lukas Schuller
* @date Tue Sep 24 21:21:57 2013
*
* @brief
*
*/
#include "Configuration.h"
#include <iostream>
#include <algorithm>
#include <iomanip>
using namespace std;
Configuration & Configuration::r = Configuration::Get();
std::ostream & operator << (std::ostream & os, Configuration const & cfg) {
cfg.Print(os);
}
Configuration & Configuration::Get() {
static Configuration instance;
return instance;
}
void Configuration::ParseCmd(int argc, char * argv[]) {
int i = 1;
if(argc > 1 && argv[i][0] != '-') r.mode = argv[i++];
while(i < argc) {
// cout << "argv " << i << ": " << argv[i] << endl;
r.cmdArgs.push_back(std::string(argv[i]));
++i;
}
}
std::string Configuration::GetMode(std::string const & defaultMode) {
return r.mode.size() ? r.mode : defaultMode;
}
void Configuration::RegisterOption(std::string const & longName,
std::string const shortName,
OptionValue const & defaultValue) {
RegisterOption(OptionName(longName,shortName),defaultValue);
}
void Configuration::RegisterOption(OptionName const & name, OptionValue const & defaultValue) {
if(r.options.find(name) != r.options.end()) return;
r.options[name] = defaultValue;
r.options[name].Unset();
auto ii = r.cmdArgs.begin();
for(; ii != r.cmdArgs.end(); ++ii) {
if(0 == ii->find( "--" + name.Long()) ||
0 == ii->find( "-" + name.Short())) {
size_t valPos = ii->find("=");
if(valPos != string::npos) {
++valPos;
r.options[name] = ii->substr(valPos, ii->size()-valPos);
}
r.options[name].Set();
r.cmdArgs.erase(ii);
break;
}
}
}
void Configuration::SetOption(std::string const & name, OptionValue const & value) {
if(r.options.find(OptionName(name)) == r.options.end());
r.options[name] = value;
r.options[name].Set();
}
void Configuration::Print(std::ostream & os) {
os << "Options:" << std::endl;
for(auto ii = r.options.begin(); ii != r.options.end(); ++ii) {
os << std::setw(16) << ii->first.Long()
<< std::setw(16) << " [" + ii->first.Short() + "] = "
<< ii->second.Str() << " (" << ii->second.IsSet() << ")" << std::endl;
}
}
OptionValue Configuration::GetOption(std::string const & name) {
//std::cout << "Requested: " << name << std::endl;
if(r.options.find(name) == r.options.end()) {
cout << "unknown name: " << name << endl;
throw invalid_argument("unregistered option");
}
//std::cout << "Returning: " << options[name].Str() << std::endl;
return r.options[name];
}
bool Configuration::IsSet(std::string const & name) {
if(r.options.find(name) == r.options.end()) {
cout << "unknown name: " << name << endl;
throw ConfigException("unregistered flag");
}
return r.options[name].IsSet();
}
|
#include <bits/stdc++.h>
using namespace std;
const int MAX_INT = std::numeric_limits<int>::max();
const int MIN_INT = std::numeric_limits<int>::min();
const int INF = 1000000000;
const int NEG_INF = -1000000000;
#define max(a,b)(a>b?a:b)
#define min(a,b)(a<b?a:b)
#define MEM(arr,val)memset(arr,val, sizeof arr)
#define PI acos(0)*2.0
#define eps 1.0e-9
#define are_equal(a,b)fabs(a-b)<eps
#define LS(b)(b& (-b)) // Least significant bit
#define DEG_to_RAD(a)((a*PI)/180.0) // convert to radians
typedef long long ll;
typedef pair<int,int> ii;
typedef pair<int,char> ic;
typedef pair<long,char> lc;
typedef vector<int> vi;
typedef vector<ii> vii;
int gcd(int a,int b){return b == 0 ? a : gcd(b,a%b);}
int lcm(int a,int b){return a*(b/gcd(a,b));}
ll _sieve_size;
bitset<10000010> bs;
vector<ll> fac, ftr, boo, primes;
ll sumation(ll num){
ll sum = 0;
while (num > 0){
sum += (num % 10);
num /= 10;
}
return sum;
}
bool isPrime(int n) {
if (n == 1) {
return false;
}
for (int i = 0; i < primes.size() && primes[i] < n; i++) {
if (n % primes[i] == 0) {
return false;
}
}
return true;
}
void sieve(ll upperbound){
_sieve_size = upperbound + 1;
bs.set();
bs[0] = bs[1] = 0;
for (ll i = 2; i <= _sieve_size; i++)
if (bs[i]){
for (ll j = i * i; j <= _sieve_size; j+=i)
bs[j] = 0;
primes.push_back(i);
}
}
int primeFactors(ll x) {
int sum = 0;
ll N = x;
// cout << "N " << N << endl;
if (isPrime(N))
return primeFactors(x+1);
ll PF_idx = 0, PF = primes[PF_idx];
// cout << PF << endl;
while (PF * PF <= N){
if (PF > sqrt(x) + 1)
break;
while (N % PF == 0){
// cout << "in" << endl;
N /= PF;
sum += sumation(PF);
// cout << sum << " ";
}
PF = primes[++PF_idx];
}
if (N != 1) {
sum += sumation(N);
// cout << sum << " ";
}
// cout << endl;
if (sum == sumation(x))
return x;
// cout << cnt << " " << cnt + fac[x - 1] << endl;
return primeFactors(x+1);
}
int main(){
int t, n;
sieve(100000);
scanf("%d", &t);
while (t--){
scanf("%d", &n);
printf("%d\n", primeFactors(n+1));
}
}
|
#include "Graph.h"
#include <limits> // numeric_limits
#include <algorithm> // push_heap, pop_heap, make_heap
Graph::Graph()
{
}
Graph::~Graph()
{
}
void Graph::addVertex(const char &letter, const std::unordered_map<char, int> &edges)
{
verticies.insert(std::unordered_map<char, const std::unordered_map<char, int>>::value_type(letter, edges));
}
std::vector<char> Graph::shortestPath(const char &start, const char &finish)
{
if (start == NULL || finish == NULL)
{
return{};
}
std::unordered_map<char, int> distance;
std::unordered_map<char, char> previous;
std::vector<char> nodes;
std::vector<char> path;
// [&] capture all variables within the lambda function scope by reference
auto comparator = [&](char left, char right) {return distance[left] > distance[right]; };
for (auto const &vertex : verticies)
{
if (vertex.first == start)
{
distance[vertex.first] = 0;
}
else
{
// Returns the maximum finite value
distance[vertex.first] = std::numeric_limits<int>::max();
}
nodes.push_back(vertex.first);
std::push_heap(std::begin(nodes), std::end(nodes), comparator);
}
while (!nodes.empty())
{
std::pop_heap(std::begin(nodes), std::end(nodes), comparator);
char smallest = nodes.back();
nodes.pop_back();
if (smallest == finish)
{
while (previous.find(smallest) != std::end(previous))
{
path.push_back(smallest);
smallest = previous[smallest];
}
break;
}
if (distance[smallest] == std::numeric_limits<int>::max())
{
break;
}
for (auto &neighbor : verticies[smallest])
{
int alt = distance[smallest] + neighbor.second;
if (alt < distance[neighbor.first])
{
distance[neighbor.first] = alt;
previous[neighbor.first] = smallest;
std::make_heap(std::begin(nodes), std::end(nodes), comparator);
}
}
}
std::reverse(path.begin(), path.end());
return path;
}
|
#include "render.h"
#include <iostream>
#include <vector>
#include <lodepng.h>
#include <glad/glad.h>
const char* vertex_shader1_source = R"(
#version 100
attribute vec3 position;
attribute vec2 a_texcoord;
attribute vec2 a_texpos;
attribute vec2 a_texsize;
varying vec2 v_texcoord;
varying vec2 v_texpos;
varying vec2 v_texsize;
uniform vec2 screen_size;
void main()
{
v_texcoord = a_texcoord;
v_texpos = a_texpos;
v_texsize = a_texsize;
vec2 temp = vec2(2, -2) * position.xy / screen_size + vec2(-1, 1);
gl_Position = vec4(temp, -position.z/100.0, 1.0);
}
)";
const char* fragment_shader1_source = R"(
#version 100
precision mediump float;
uniform sampler2D atlas;
uniform vec2 atlas_size;
varying vec2 v_texcoord;
varying vec2 v_texpos;
varying vec2 v_texsize;
void main()
{
gl_FragColor = texture2D(atlas, clamp(v_texcoord, v_texpos + vec2(0.5, 0.5), v_texpos + v_texsize - vec2(0.5, 0.5)) / atlas_size);
}
)";
const char* vertex_shader2_source = R"(
#version 100
attribute vec3 position;
attribute vec4 a_color;
attribute vec2 a_center;
attribute float a_radius;
varying vec4 v_color;
varying vec2 v_center;
varying vec3 v_position;
varying float v_radius;
uniform vec2 screen_size;
void main()
{
v_position = position;
v_color = a_color;
vec2 temp = vec2(2, -2) * position.xy / screen_size + vec2(-1, 1);
gl_Position = vec4(temp, -position.z/100.0, 1.0);
v_center = a_center;
v_radius = a_radius;
}
)";
const char* fragment_shader2_source = R"(
#version 100
precision mediump float;
varying vec4 v_color;
varying vec2 v_center;
varying vec3 v_position;
varying float v_radius;
void main()
{
vec2 pos = v_position.xy - v_center;
float dist = dot(pos, pos);
float alpha = 1.0 - smoothstep(v_radius * v_radius, (v_radius + 1.0) * (v_radius + 1.0), dist);
alpha = alpha * v_color.a;
gl_FragColor = vec4(v_color.rgb * alpha, alpha);
}
)";
// Create and compile an OpenGL shader of the given type.
// Also checks for errors and prints as necessary.
GLint create_and_compile_shader(const char* source, GLenum type) {
int shader = glCreateShader(type);
glShaderSource(shader, 1, &source, NULL);
glCompileShader(shader);
GLint success = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success) {
std::cerr << "Could not compile the required shader " << source << std::endl;
GLint logSize = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logSize);
std::string errorLog(logSize, 0);
glGetShaderInfoLog(shader, logSize, &logSize, &errorLog[0]);
std::cout<<errorLog<<std::endl;
exit(-1);
}
return shader;
}
// Load the texture atlas for the program.
void load_texture_atlas(int program) {
std::vector<unsigned char> image;
unsigned int atlas_width;
unsigned int atlas_height;
unsigned decode_error = lodepng::decode(image, atlas_width, atlas_height, "../assets/img/pixelPacker.png");
if (decode_error != 0) {
std::cerr << "error while decoding the texture atlas: " << lodepng_error_text(decode_error) << std::endl;
}
unsigned int texture;
glGenTextures(1, &texture);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, atlas_width, atlas_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.data());
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
int atlas_size_location = glGetUniformLocation(program, "atlas_size");
glUniform2f(atlas_size_location, atlas_width, atlas_height);
int sampler_location = glGetUniformLocation(program, "atlas");
glUniform1i(sampler_location, 0);
}
// Update the size. This requires changing a uniform variable and the viewport.
void update_size(int program, int pixel_width, int pixel_height,
int screen_width, int screen_height) {
glViewport(0, 0, pixel_width, pixel_height);
int screen_size_location = glGetUniformLocation(program, "screen_size");
glUniform2f(screen_size_location, screen_width, screen_height);
}
// Create and initialize the OpenGL program.
std::array<std::function<void(void)>, 2> create_and_use_program(int pixel_width, int pixel_height, int screen_width, int screen_height) {
int main_program = glCreateProgram();
{
int vertex_shader = create_and_compile_shader(vertex_shader1_source, GL_VERTEX_SHADER);
int fragment_shader = create_and_compile_shader(fragment_shader1_source, GL_FRAGMENT_SHADER);
glAttachShader(main_program, vertex_shader);
glAttachShader(main_program, fragment_shader);
glLinkProgram(main_program);
}
int flame_program = glCreateProgram();
{
int vertex_shader = create_and_compile_shader(vertex_shader2_source, GL_VERTEX_SHADER);
int fragment_shader = create_and_compile_shader(fragment_shader2_source, GL_FRAGMENT_SHADER);
glAttachShader(flame_program, vertex_shader);
glAttachShader(flame_program, fragment_shader);
glLinkProgram(flame_program);
}
std::array<unsigned int, 2> buffers;
glGenBuffers(2, buffers.data());
std::array<unsigned int, 2> vao;
glGenVertexArrays(2, vao.data());
{
glUseProgram(main_program);
glBindVertexArray(vao[0]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[0]);
int position_location = glGetAttribLocation(main_program, "position");
int tex_location = glGetAttribLocation(main_program, "a_texcoord");
int tex_pos = glGetAttribLocation(main_program, "a_texpos");
int tex_size = glGetAttribLocation(main_program, "a_texsize");
glEnableVertexAttribArray(position_location);
glVertexAttribPointer(position_location, 3, GL_FLOAT, false, 4 * 9, 0);
glEnableVertexAttribArray(tex_location);
glVertexAttribPointer(tex_location, 2, GL_FLOAT, false, 4 * 9, (void *)(4 * 3));
glEnableVertexAttribArray(tex_pos);
glVertexAttribPointer(tex_pos, 2, GL_FLOAT, false, 4 * 9, (void *)(4 * 5));
glEnableVertexAttribArray(tex_size);
glVertexAttribPointer(tex_size, 2, GL_FLOAT, false, 4 * 9, (void *)(4 * 7));
load_texture_atlas(main_program);
update_size(main_program, pixel_width, pixel_height, screen_width, screen_height);
}
{
glUseProgram(flame_program);
glBindVertexArray(vao[1]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[1]);
int position_location = glGetAttribLocation(flame_program, "position");
int color_location = glGetAttribLocation(flame_program, "a_color");
int center_location = glGetAttribLocation(flame_program, "a_center");
int radius_location = glGetAttribLocation(flame_program, "a_radius");
glEnableVertexAttribArray(position_location);
glVertexAttribPointer(position_location, 3, GL_FLOAT, false, 4 * 10, 0);
glEnableVertexAttribArray(color_location);
glVertexAttribPointer(color_location, 4, GL_FLOAT, false, 4 * 10, (void *)(4 * 3));
glEnableVertexAttribArray(center_location);
glVertexAttribPointer(center_location, 2, GL_FLOAT, false, 4 * 10, (void *)(4 * 7));
glEnableVertexAttribArray(radius_location);
glVertexAttribPointer(radius_location, 1, GL_FLOAT, false, 4 * 10, (void *)(4 * 9));
update_size(flame_program, pixel_width, pixel_height, screen_width, screen_height);
}
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glClearColor(1.0, 1, 1, 1.0);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_MULTISAMPLE);
auto main_setup = [=]() {
glUseProgram(main_program);
glBindVertexArray(vao[0]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[0]);
};
auto flame_setup = [=]() {
glUseProgram(flame_program);
glBindVertexArray(vao[1]);
glBindBuffer(GL_ARRAY_BUFFER, buffers[1]);
};
return {{main_setup, flame_setup}};
}
|
#include "DXUT.h"
#include "cResourceMgr.h"
#include "cTextureFile.h"
#include "cAseFile.h"
#include "cAseLoader.h"
#include "cToonShader.h"
#include "cImageFile.h"
#include "cAlphaShader.h"
#include "cTexBuf.h"
cResourceMgr::cResourceMgr(void)
:m_fRed( 0.0f )
,m_fAlpha( 0.0f )
,m_fScale( 1.0f )
{
m_vecShader.resize( SI_MAX );
std::vector<ST_PNT_VERTEX> vecVertices;
vecVertices.resize( 6 );
vecVertices[1].p = D3DXVECTOR3( -0.0f, -0.0f, 0.0f );
vecVertices[1].t = D3DXVECTOR2( 0.0f, 1.0f );
vecVertices[0].p = D3DXVECTOR3( 1.0f, -0.0f, 0.0f );
vecVertices[0].t = D3DXVECTOR2( 1.0f, 1.0f );
vecVertices[2].p = D3DXVECTOR3( -0.0f, 1.0f, 0.0f );
vecVertices[2].t = D3DXVECTOR2( 0.0f, 0.0f );
vecVertices[4].p = D3DXVECTOR3( -0.0f, 1.0f, 0.0f );
vecVertices[4].t = D3DXVECTOR2( 0.0f, 0.0f );
vecVertices[3].p = D3DXVECTOR3( 1.0f, -0.0f, 0.0f );
vecVertices[3].t = D3DXVECTOR2( 1.0f, 1.0f );
vecVertices[5].p = D3DXVECTOR3( 1.0f, 1.0f, 0.0f );
vecVertices[5].t = D3DXVECTOR2( 1.0f, 0.0f );
for( int n = 0; n < 6; ++n )
{
vecVertices[n].n = D3DXVECTOR3( 0.0f, 0.0f, 1.0f );
}
DXUTGetD3D9Device()->CreateVertexBuffer( 6 * sizeof( ST_PNT_VERTEX ),
0,ST_PNT_VERTEX::FVF, D3DPOOL_MANAGED, &m_pPlanVB, NULL );
LPVOID pVertices;
m_pPlanVB->Lock( 0, 0, &pVertices, 0 );
memcpy( pVertices, &vecVertices[0], sizeof( ST_PNT_VERTEX ) * 6 );
m_pPlanVB->Unlock();
}
cResourceMgr::~cResourceMgr(void)
{
SAFE_RELEASE( m_pPlanVB );
for each( auto i in m_mapResource )
{
SAFE_DELETE( i.second );
}
for each( auto iter in m_vecShader )
{
SAFE_DELETE( iter );
}
}
void cResourceMgr::AddTexture( char* pKey, LPCWSTR pFileName, int nFrame )
{
WCHAR FileName[1024];
CUSTOM_POINT Index;
cTextureFile* pTexture = new cTextureFile;
for( int i = 0; i < nFrame; ++i )
{
if( i < 10 )
swprintf_s( FileName, wcslen( pFileName ) + 1, pFileName, i );
else if( i < 100 )
swprintf_s( FileName, wcslen( pFileName ) + 2, pFileName, i );
else
swprintf_s( FileName, wcslen( pFileName ) + 3, pFileName, i );
pTexture->AddTextureNode( g_DialogResourceManager.GetTextureNode( g_DialogResourceManager.AddTexture( FileName ) ) );
}
pTexture->SetKey( pKey );
m_mapResource.insert( std::pair<std::string, cResourceFile*>( pKey, pTexture ) );
}
void cResourceMgr::AddAseFile( char* pKey, char* pFileName )
{
cAseFile* pAseFile = new cAseFile;
cAseLoader AseLoader;
std::string sName( pKey );
AseLoader.LoadAse( pFileName, pAseFile );
D3DXVECTOR3 vMinToMax = AseLoader.m_vMin + AseLoader.m_vMax;
pAseFile->m_vModelCenter = vMinToMax / 2.0f;
pAseFile->m_fModelRadius
= D3DXVec3Length( &( AseLoader.m_vMin - pAseFile->m_vModelCenter ) );
pAseFile->SetKey( pKey );
m_mapResource.insert( std::pair<std::string, cResourceFile*>( sName, pAseFile ) );
}
void cResourceMgr::AddEffect( char* pFileName, int nSID )
{
DWORD dwFlag = 0;
#if _ DEBUG
dwFlag != D3DXSHADER_DEBUG;
#endif
LPD3DXEFFECT pEffect;
LPD3DXBUFFER pError;
D3DXCreateEffectFromFileA( DXUTGetD3D9Device(),
pFileName, NULL, NULL, dwFlag, NULL, &pEffect, &pError );
if( !pEffect && pError )
{
int nSize = pError->GetBufferSize();
void* ask = pError->GetBufferPointer();
if( ask )
{
char* str = new char[nSize];
sprintf( str, (const char*)ask, nSize );
delete[] str;
}
return ;
}
cBaseShader* pShader = NULL;
switch( nSID )
{
case SI_TOON:
pShader = new cToonShader;
break;
case SI_ALPHA:
pShader = new cAlphaShader;
break;
default:
return;
}
pShader->SetEffect( pEffect );
m_vecShader[nSID] = pShader;
}
void cResourceMgr::AddImage( char* pKey, char* pFileName,int nFrame, bool IsBillBoard )
{
cImageFile* pImageFile = new cImageFile();
pImageFile->SetBillBoard( IsBillBoard );
char szBuf[1024];
for( int n = 0 ; n < nFrame; ++n )
{
LPDIRECT3DTEXTURE9 pTexture;
if( n < 10 )
sprintf_s( szBuf, strlen( pFileName ) + 1, pFileName, n );
else if( n < 100 )
sprintf_s( szBuf, strlen( pFileName ) + 2, pFileName, n );
D3DXCreateTextureFromFileA( DXUTGetD3D9Device()
,szBuf , &pTexture );
pImageFile->AddTexture( pTexture );
}
pImageFile->SetKey( pKey );
m_mapResource.insert( std::pair<std::string, cResourceFile*> ( pKey, pImageFile ) );
}
|
#include "rclcpp/rclcpp.hpp"
#include "geometry_msgs/msg/twist.hpp"
#include "sensor_msgs/msg/joy.hpp"
#include "tello_msgs/srv/tello_action.hpp"
namespace tello_joy {
// Simple teleop node:
// -- translate joystick commands to Tello actions and cmd_vel messages
// -- ignore all responses
// XBox One constants
constexpr int JOY_AXIS_LEFT_LR = 0; // Left stick left/right; 1.0 is left and -1.0 is right
constexpr int JOY_AXIS_LEFT_FB = 1; // Left stick forward/back; 1.0 is forward and -1.0 is back
constexpr int JOY_AXIS_RIGHT_LR = 3; // Right stick left/right; 1.0 is left and -1.0 is right
constexpr int JOY_AXIS_RIGHT_FB = 4; // Right stick forward/back; 1.0 is forward and -1.0 is back
constexpr int JOY_BUTTON_VIEW = 6; // View button
constexpr int JOY_BUTTON_MENU = 7; // Menu button
class TelloJoy : public rclcpp::Node
{
public:
explicit TelloJoy() : Node("tello_joy")
{
using std::placeholders::_1;
joy_sub_ = create_subscription<sensor_msgs::msg::Joy>("joy", std::bind(&TelloJoy::joy_callback, this, _1));
cmd_vel_pub_ = create_publisher<geometry_msgs::msg::Twist>("cmd_vel", 1);
tello_client_ = create_client<tello_msgs::srv::TelloAction>("tello_action");
(void)joy_sub_;
}
~TelloJoy() {}
private:
void joy_callback(const sensor_msgs::msg::Joy::SharedPtr joy_msg)
{
if (joy_msg->buttons[joy_button_takeoff_]) {
auto request = std::make_shared<tello_msgs::srv::TelloAction::Request>();
request->cmd = "takeoff";
tello_client_->async_send_request(request);
} else if (joy_msg->buttons[joy_button_land_]) {
auto request = std::make_shared<tello_msgs::srv::TelloAction::Request>();
request->cmd = "land";
tello_client_->async_send_request(request);
} else {
geometry_msgs::msg::Twist twist_msg;
twist_msg.linear.x = joy_msg->axes[joy_axis_throttle_];
twist_msg.linear.y = joy_msg->axes[joy_axis_strafe_];
twist_msg.linear.z = joy_msg->axes[joy_axis_vertical_];
twist_msg.angular.z = joy_msg->axes[joy_axis_yaw_];
cmd_vel_pub_->publish(twist_msg);
}
}
rclcpp::Subscription<sensor_msgs::msg::Joy>::SharedPtr joy_sub_;
rclcpp::Publisher<geometry_msgs::msg::Twist>::SharedPtr cmd_vel_pub_;
rclcpp::Client<tello_msgs::srv::TelloAction>::SharedPtr tello_client_;
// XBox One assignments
const int joy_axis_throttle_ = JOY_AXIS_RIGHT_FB;
const int joy_axis_strafe_ = JOY_AXIS_RIGHT_LR;
const int joy_axis_vertical_ = JOY_AXIS_LEFT_FB;
const int joy_axis_yaw_ = JOY_AXIS_LEFT_LR;
const int joy_button_takeoff_ = JOY_BUTTON_MENU;
const int joy_button_land_ = JOY_BUTTON_VIEW;
};
} // namespace tello_joy
int main(int argc, char **argv)
{
// Force flush of the stdout buffer
setvbuf(stdout, NULL, _IONBF, BUFSIZ);
// Init ROS
rclcpp::init(argc, argv);
// Create node
auto node = std::make_shared<tello_joy::TelloJoy>();
auto result = rcutils_logging_set_logger_level(node->get_logger().get_name(), RCUTILS_LOG_SEVERITY_INFO);
// Spin until rclcpp::ok() returns false
rclcpp::spin(node);
// Shut down ROS
rclcpp::shutdown();
return 0;
}
|
// NumericMFCCtrl.cpp : Implementation of the CNumericMFCCtrl ActiveX Control class.
#include "pch.h"
#include "framework.h"
#include "NumericMFC.h"
#include "NumericMFCCtrl.h"
#include "NumericMFCPropPage.h"
#include "afxdialogex.h"
#include <string>
#include <curl/curl.h>
#include <chrono>
using namespace std;
using namespace std::chrono;
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
IMPLEMENT_DYNCREATE(CNumericMFCCtrl, COleControl)
// Message map
BEGIN_MESSAGE_MAP(CNumericMFCCtrl, COleControl)
ON_OLEVERB(AFX_IDS_VERB_PROPERTIES, OnProperties)
END_MESSAGE_MAP()
// Dispatch map
BEGIN_DISPATCH_MAP(CNumericMFCCtrl, COleControl)
END_DISPATCH_MAP()
// Event map
BEGIN_EVENT_MAP(CNumericMFCCtrl, COleControl)
END_EVENT_MAP()
// Property pages
// TODO: Add more property pages as needed. Remember to increase the count!
BEGIN_PROPPAGEIDS(CNumericMFCCtrl, 1)
PROPPAGEID(CNumericMFCPropPage::guid)
END_PROPPAGEIDS(CNumericMFCCtrl)
// Initialize class factory and guid
IMPLEMENT_OLECREATE_EX(CNumericMFCCtrl, "MFCACTIVEXCONTRO.NumericMFCCtrl.1",
0x963ff900, 0x6d5f, 0x4956, 0x87, 0xee, 0x43, 0x22, 0xbf, 0x91, 0xeb, 0x19)
// Type library ID and version
IMPLEMENT_OLETYPELIB(CNumericMFCCtrl, _tlid, _wVerMajor, _wVerMinor)
// Interface IDs
const IID IID_DNumericMFC = {0xda81fade, 0x9353, 0x4b21, {0xb3, 0x51, 0xc1, 0x4d, 0xd6, 0x8f, 0xe4, 0x80}};
const IID IID_DNumericMFCEvents = {0x55265547, 0x7b55, 0x46bd, {0xbc, 0xff, 0x07, 0xe9, 0xfb, 0xed, 0x43, 0x2a}};
// Control type information
static const DWORD _dwNumericMFCOleMisc =
OLEMISC_ACTIVATEWHENVISIBLE |
OLEMISC_SETCLIENTSITEFIRST |
OLEMISC_INSIDEOUT |
OLEMISC_CANTLINKINSIDE |
OLEMISC_RECOMPOSEONRESIZE;
IMPLEMENT_OLECTLTYPE(CNumericMFCCtrl, IDS_NUMERICMFC, _dwNumericMFCOleMisc)
// CNumericMFCCtrl::CNumericMFCCtrlFactory::UpdateRegistry -
// Adds or removes system registry entries for CNumericMFCCtrl
BOOL CNumericMFCCtrl::CNumericMFCCtrlFactory::UpdateRegistry(BOOL bRegister)
{
// TODO: Verify that your control follows apartment-model threading rules.
// Refer to MFC TechNote 64 for more information.
// If your control does not conform to the apartment-model rules, then
// you must modify the code below, changing the 6th parameter from
// afxRegApartmentThreading to 0.
if (bRegister)
return AfxOleRegisterControlClass(
AfxGetInstanceHandle(),
m_clsid,
m_lpszProgID,
IDS_NUMERICMFC,
IDB_NUMERICMFC,
afxRegApartmentThreading,
_dwNumericMFCOleMisc,
_tlid,
_wVerMajor,
_wVerMinor);
else
return AfxOleUnregisterClass(m_clsid, m_lpszProgID);
}
// CNumericMFCCtrl::CNumericMFCCtrl - Constructor
CNumericMFCCtrl::CNumericMFCCtrl()
{
InitializeIIDs(&IID_DNumericMFC, &IID_DNumericMFCEvents);
startComps();
}
// CNumericMFCCtrl::~CNumericMFCCtrl - Destructor
CNumericMFCCtrl::~CNumericMFCCtrl()
{
// TODO: Cleanup your control's instance data here.
}
void CNumericMFCCtrl::startComps()
{
high_resolution_clock::time_point startTime = high_resolution_clock::now();
doNumericComputations();
high_resolution_clock::time_point endTime = high_resolution_clock::now();
int execTime = duration_cast<milliseconds>(endTime - startTime).count();
long long time = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
string sUrl = "http://localhost:4000/timer/end?tech=activex&app=numeric&time=" + to_string(time) + "&execTime=" + to_string(execTime);
const char *url = sUrl.c_str();
CURL *c;
c = curl_easy_init();
curl_easy_setopt(c, CURLOPT_URL, url);
curl_easy_perform(c);
curl_easy_cleanup(c);
}
void CNumericMFCCtrl::doNumericComputations()
{
srand(time(NULL));
const int SIZE = 100000000;
for (int i = 0; i < SIZE; i++)
{
int num1 = rand() % 10 + 1;
int num2 = rand() % 10 + 1;
if (num1 < num2)
{
num1 = 1;
}
if (num2 < num1)
{
num2 = 1;
}
if (num1 == num2)
{
num1 = 1;
num2 = 1;
}
}
}
// CNumericMFCCtrl::OnDraw - Drawing function
void CNumericMFCCtrl::OnDraw(
CDC *pdc, const CRect &rcBounds, const CRect & /* rcInvalid */)
{
if (!pdc)
return;
// TODO: Replace the following code with your own drawing code.
pdc->FillRect(rcBounds, CBrush::FromHandle((HBRUSH)GetStockObject(WHITE_BRUSH)));
pdc->Ellipse(rcBounds);
}
// CNumericMFCCtrl::DoPropExchange - Persistence support
void CNumericMFCCtrl::DoPropExchange(CPropExchange *pPX)
{
ExchangeVersion(pPX, MAKELONG(_wVerMinor, _wVerMajor));
COleControl::DoPropExchange(pPX);
// TODO: Call PX_ functions for each persistent custom property.
}
// CNumericMFCCtrl::OnResetState - Reset control to default state
void CNumericMFCCtrl::OnResetState()
{
COleControl::OnResetState(); // Resets defaults found in DoPropExchange
// TODO: Reset any other control state here.
}
// CNumericMFCCtrl message handlers
|
#include<iostream>
#include<string.h>
using namespace std;
int arr[100][100];
int dp[100][100];
char path[100][100];
int m,n;
int find(int i,int j)
{
if(i==m-1&&j==n-1)
{
path[i][j]='S';
return dp[i][j]=(arr[i][j]==1);
}
int rt,dn;
if(dp[i][j]!=-1) return dp[i][j];
if(i==m-1) // CANNOT GO DOWN;
{
path[i][j]='R';
return dp[i][j]=(arr[i][j]==1)+find(i,j+1);
}
if(j==n-1) //CANNOT GO RIGHT;
{
path[i][j]='D';
return dp[i][j]=(arr[i][j]==1)+find(i+1,j);
}
rt=find(i,j+1);
dn=find(i+1,j);
if(rt>dn)
path[i][j]='R';
else
path[i][j]='D';
return dp[i][j]=(arr[i][j]==1)+max(rt,dn);
}
int main()
{
memset(dp,-1,sizeof(dp));
cin>>m>>n;
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
cin>>arr[i][j];
cout<<find(0,0)<<endl;
/*
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
cout<<path[i][j]<<" ";
cout<<endl;
}
*/
int i=0,j=0;
while(path[i][j]!='S')
{
cout<<path[i][j]<<" ";
if(path[i][j]=='R')
j=j+1;
else
i=i+1;
}
}
|
#ifndef _INFO_H_
#define _INFO_H_
#include <vector>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
const int s_in_day = 24 * 60 * 60;
class Date {
public:
int year, month, day;
};
class Item {
public:
std::string title;
std::string query;
Date startdate, enddate, currentdate, nextdate;
time_t t_current, t_end, day_ahead;
struct tm current, end, next_day;
void init_times() {
current = *localtime(&t_current);
end = *localtime(&t_end);
next_day = *localtime(&day_ahead);
current.tm_year = startdate.year - 1900;
current.tm_mon = startdate.month - 1;
current.tm_mday = startdate.day;
next_day.tm_year = startdate.year - 1900;
next_day.tm_mon = startdate.month - 1;
next_day.tm_mday = startdate.day + 1;
end.tm_year = enddate.year - 1900;
end.tm_mon = enddate.month - 1;
end.tm_mday = enddate.day;
t_current = mktime(¤t);
day_ahead = mktime(&next_day);
t_end = mktime(&end);
currentdate = startdate;
}
void update_current_time() {
current.tm_mday += 1;
next_day.tm_mday += 1;
t_current = mktime(¤t);
day_ahead = mktime(&next_day);
}
std::string current_date() {
char date[1024];
int n = sprintf(date, "%d-%02d-%02d", current.tm_year + 1900, current.tm_mon + 1, current.tm_mday);
return date;
}
std::string currentheader() {
char header[1024];
int n = sprintf(header, "queries/headers/%s_%d-%02d-%02d.head", title.c_str(), current.tm_year + 1900, current.tm_mon + 1, current.tm_mday);
return header;
}
std::string currentbody() {
char body[1024];
int n = sprintf(body, "queries/bodies/%s_%d-%02d-%02d.body", title.c_str(), current.tm_year + 1900, current.tm_mon + 1, current.tm_mday);
return body;
}
std::string currentquery() {
char start[100], end[100];
int n = sprintf(start, "%d-%02d-%02d", current.tm_year + 1900, current.tm_mon + 1, current.tm_mday);
n = sprintf(end, "%d-%02d-%02d", next_day.tm_year + 1900, next_day.tm_mon + 1, next_day.tm_mday);
return query + "%20posted%3A" + start + "%2C" + end + "&size=500";
}
};
class Config {
public:
std::vector<Item> queries;
};
class Global_Info {
public:
std::string username;
std::string password;
std::string hostname;
std::string total;
Config config;
void set_url() {
this->total = "https://" + this->username + ":" + this->password + "@" + this->hostname;
}
};
#endif
|
#pragma once
#include "Vector3D.h"
enum LightType { POINT = 0, DIRECTIONAL = 1 };
class Light {
// Haven't consider spotlight and area light, may be extended.
public:
LightType type;
Vec3f position;
Vec3f color;
Vec3f attenuation; //How does the light decay with distance
Vec3f lightDir; // Direction to light, to reduce computation
Light(LightType t, Vec3f p, Vec3f c, Vec3f at) : type(t), position(p), color(c), attenuation(at)
{
}
};
|
/*=auto=========================================================================
Portions (c) Copyright 2009 Brigham and Women's Hospital (BWH) All Rights Reserved.
See Doc/copyright/copyright.txt
or http://www.slicer.org/copyright/copyright.txt for details.
Program: 3D Slicer
Module: $RCSfile: vtkMRMLGradientAnisotropicDiffusionFilterNode.cxx,v $
Date: $Date: 2006/03/17 15:10:10 $
Version: $Revision: 1.2 $
=========================================================================auto=*/
// OpenIGTLinkIF MRML includes
#include "vtkMRMLIGTLQueryNode.h"
#include "vtkMRMLIGTLConnectorNode.h"
// OpenIGTLink includes
#include <igtlOSUtil.h>
#include <igtlMessageBase.h>
#include <igtlMessageHeader.h>
#include <igtl_header.h> // to define maximum length of message name
// MRML includes
#include <vtkMRMLScene.h>
// VTK includes
#include <vtkObjectFactory.h>
#include <vtkTimerLog.h>
// STD includes
#include <string>
#include <iostream>
#include <sstream>
#include <map>
static const char ResponseDataNodeRole[] = "responseData";
static const char ConnectorNodeRole[] = "connector";
//------------------------------------------------------------------------------
vtkMRMLNodeNewMacro(vtkMRMLIGTLQueryNode);
//----------------------------------------------------------------------------
vtkMRMLIGTLQueryNode::vtkMRMLIGTLQueryNode()
{
this->QueryStatus = 0;
this->QueryType = 0;
this->TimeStamp = 0.0;
this->TimeOut = 0.0;
this->AddNodeReferenceRole(ResponseDataNodeRole);
this->AddNodeReferenceRole(ConnectorNodeRole);
}
//----------------------------------------------------------------------------
vtkMRMLIGTLQueryNode::~vtkMRMLIGTLQueryNode()
{
}
//----------------------------------------------------------------------------
void vtkMRMLIGTLQueryNode::WriteXML(ostream& of, int nIndent)
{
// Start by having the superclass write its information
Superclass::WriteXML(of, nIndent);
}
//----------------------------------------------------------------------------
void vtkMRMLIGTLQueryNode::ReadXMLAttributes(const char** atts)
{
vtkMRMLNode::ReadXMLAttributes(atts);
}
//----------------------------------------------------------------------------
// Copy the node's attributes to this object.
// Does NOT copy: ID, FilePrefix, Name, VolumeID
void vtkMRMLIGTLQueryNode::Copy(vtkMRMLNode* anode)
{
Superclass::Copy(anode);
vtkMRMLIGTLQueryNode* node = vtkMRMLIGTLQueryNode::SafeDownCast(anode);
if (node == NULL)
{
vtkErrorMacro("vtkMRMLIGTLQueryNode::Copy failed: unrelated input node type");
return;
}
this->IGTLName = node->IGTLName;
this->IGTLDeviceName = node->IGTLDeviceName;
this->QueryStatus = node->QueryStatus;
this->QueryType = node->QueryType;
this->TimeStamp = node->TimeStamp;
this->TimeOut = node->TimeOut;
}
//----------------------------------------------------------------------------
void vtkMRMLIGTLQueryNode::PrintSelf(ostream& os, vtkIndent indent)
{
Superclass::PrintSelf(os, indent);
os << indent << "IGTLName: " << this->IGTLName << "\n";
os << indent << "IGTLDeviceName: " << this->IGTLDeviceName << "\n";
os << indent << "QueryType: " << vtkMRMLIGTLQueryNode::QueryTypeToString(this->QueryType) << "\n";
os << indent << "QueryStatus: " << vtkMRMLIGTLQueryNode::QueryStatusToString(this->QueryStatus) << "\n";
if (this->TimeOut > 0 && this->QueryStatus == STATUS_WAITING)
{
double remainingTime = this->TimeOut - (vtkTimerLog::GetUniversalTime() - this->TimeStamp);
os << indent << indent << "Remaining time: " << remainingTime << "\n";
}
os << indent << "TimeStamp: " << this->TimeStamp << "\n";
os << indent << "TimeOut: " << this->TimeOut << "\n";
os << indent << "ConnectorNodeID: " << (this->GetConnectorNodeID() ? this->GetConnectorNodeID() : "(none)") << "\n";
os << indent << "DataNodeID: " << (this->GetResponseDataNodeID() ? this->GetResponseDataNodeID() : "(none)") << "\n";
}
//----------------------------------------------------------------------------
void vtkMRMLIGTLQueryNode::SetIGTLName(const char* name)
{
char buf[IGTL_HEADER_TYPE_SIZE + 1];
buf[IGTL_HEADER_TYPE_SIZE] = '\0';
strncpy(buf, name, IGTL_HEADER_TYPE_SIZE);
this->IGTLName = buf;
}
//----------------------------------------------------------------------------
void vtkMRMLIGTLQueryNode::SetIGTLDeviceName(const char* name)
{
char buf[IGTL_HEADER_NAME_SIZE + 1];
buf[IGTL_HEADER_NAME_SIZE] = '\0';
strncpy(buf, name, IGTL_HEADER_NAME_SIZE);
this->IGTLDeviceName = buf;
}
//----------------------------------------------------------------------------
const char* vtkMRMLIGTLQueryNode::GetErrorString()
{
return "";
}
//----------------------------------------------------------------------------
const char* vtkMRMLIGTLQueryNode::QueryStatusToString(int queryStatus)
{
switch (queryStatus)
{
case STATUS_NOT_DEFINED:
return "NOT_DEFINED";
case STATUS_PREPARED:
return "PREPARED";
case STATUS_WAITING:
return "WAITING";
case STATUS_SUCCESS:
return "SUCCESS";
case STATUS_EXPIRED:
return "EXPIRED";
default:
return "INVALID";
}
}
//----------------------------------------------------------------------------
const char* vtkMRMLIGTLQueryNode::QueryTypeToString(int queryType)
{
switch (queryType)
{
case TYPE_NOT_DEFINED:
return "NOT_DEFINED";
case TYPE_GET:
return "GET";
case TYPE_START:
return "START";
case TYPE_STOP:
return "STOP";
default:
return "INVALID";
}
}
//----------------------------------------------------------------------------
void vtkMRMLIGTLQueryNode::SetResponseDataNodeID(const char* id)
{
this->SetNodeReferenceID(ResponseDataNodeRole, id);
}
//----------------------------------------------------------------------------
const char* vtkMRMLIGTLQueryNode::GetResponseDataNodeID()
{
return GetNodeReferenceID(ResponseDataNodeRole);
}
//----------------------------------------------------------------------------
vtkMRMLNode* vtkMRMLIGTLQueryNode::GetResponseDataNode()
{
return GetNodeReference(ResponseDataNodeRole);
}
//----------------------------------------------------------------------------
void vtkMRMLIGTLQueryNode::SetConnectorNodeID(const char* id)
{
this->SetNodeReferenceID(ConnectorNodeRole, id);
}
//----------------------------------------------------------------------------
const char* vtkMRMLIGTLQueryNode::GetConnectorNodeID()
{
return GetNodeReferenceID(ConnectorNodeRole);
}
//----------------------------------------------------------------------------
vtkMRMLIGTLConnectorNode* vtkMRMLIGTLQueryNode::GetConnectorNode()
{
return vtkMRMLIGTLConnectorNode::SafeDownCast(GetNodeReference(ConnectorNodeRole));
}
|
/*
* SPDX-FileCopyrightText: 2020 Rolf Eike Beer <eike@sf-mail.de>
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
#pragma once
#include <osm.h>
#include <QAbstractTableModel>
#include <vector>
enum {
RELITEM_COL_TYPE = 0,
RELITEM_COL_MEMBER,
RELITEM_COL_ROLE,
RELITEM_COL_NAME,
RELITEM_NUM_COLS
};
class presets_items;
class RelationMembershipModel : public QAbstractTableModel {
Q_OBJECT
Q_DISABLE_COPY(RelationMembershipModel)
std::vector<relation_t *> m_relations;
osm_t::ref m_osm;
public:
RelationMembershipModel(osm_t::ref o, object_t obj, QObject *parent = nullptr);
~RelationMembershipModel() override = default;
int rowCount(const QModelIndex &parent) const override;
int columnCount(const QModelIndex &parent) const override;
QVariant data(const QModelIndex &index, int role) const override;
bool setData(const QModelIndex &idx, const QVariant &value, int role) override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
Qt::ItemFlags flags(const QModelIndex &index) const override;
const object_t m_obj;
};
|
#pragma once
#include <unordered_map>
#include <vector>
#include "Graphics\LightShader.h"
#include "Game\Model.h"
#include "Game\AnimModel.h"
#include "Game\SNode.h"
#include "Game\SMatrixTransform.h"
#include "Game\Player.h"
#include "Game\World.h"
#include "Graphics\GuiItem.h"
#include "Graphics\PlayerGameGUI.h"
#include "Graphics\ReadyGUI.h"
#include "Graphics\ImageGUI.h"
enum Models {
_Player, //used for type of object
_Player_Standing,
_Player_Running,
_Player_Punching,
_Player_Stunned,
_Player_Wuson,
_Player_Bear,
_Player_Flying,
_Player_Wand,
_Player_Wrench_Swing,
_Player_Wrench_Slam,
_Player_Grab,
_Player_Grab_Running,
_Player_Dead,
_PropellerHat_P1,
_PropellerHat_P2,
_PropellerHat_P3,
_PropellerHat_P4,
_Mango,
_Crate,
_WizardHat,
_HardHat,
_BearHat,
_PropellerHat,
_DeerstalkerHat
};
enum Shaders {
_GShader,
_LtShader,
_2DShader,
_AShader,
_TransShader
};
enum GUI {
_Background,
_LobbyBG,
_LobbyReadyBG,
_EndGameBG,
_Loading,
_Winner
};
class GameObjects
{
private:
int numPlayerGuiSet;
void generateWorld(string directory);
public:
std::unordered_map<std::uint32_t, SMatrixTransform*> playerMap;
std::vector<std::pair<std::uint32_t, PlayerGameGUI*>> playerGUIMap;
std::unordered_map<std::uint32_t, SMatrixTransform*> hatMap;
std::unordered_map<std::uint32_t, SMatrixTransform*> bulletMap;
std::unordered_map<std::uint32_t, Model*> modelMap;
std::unordered_map<std::uint32_t, Shader*> shaderMap;
std::unordered_map<std::uint32_t, GuiItem*> guiMap;
GUIText* winnerText;
//ImageGUI *winner;
ReadyGUI *ready;
SMatrixTransform *root;
GameObjects();
~GameObjects();
void loadShaders();
void loadLoadingObject();
void loadGameObjects();
void loadModelMap();
void loadHatModelsMap();
void setPlayerToGui(int id);
void drawPlayerGui(glm::mat4 translation);
void updatePlayerGui(int id, int lives, int health);
void updatePlayerTime(float time, int id);
};
|
#include <MetaValueBaseImplementation.h>
#include <ostream>
using namespace std;
using MVBI = MetaValueBaseImplementation;
using Interface = MVBI::Interface;
using Ptr = MVBI::Ptr;
using Data = MVBI::Data;
Interface& MVBI::operator=( Interface&& movee) {
return *this;
}
Ptr MVBI::copy() const {
return Ptr(new MVBI());
}
Data MVBI::get( Attributes a ) const {
Data res;
switch(a) {
case(Attributes::HasUncertainty): res.hasUncertainty = false;
break;
case(Attributes::Size) : res.size = 0;
break;
case(Attributes::Rows) : res.size = 0;
break;
case(Attributes::Cols) : res.size = 0;
break;
case(Attributes::TypeID) : res.size = id::attribute::Base::value();
break;
}
return res;
}
bool MVBI::set(Attributes a, Data d) {
return false;
}
ValueElement<double, true> MetaValueBaseImplementation::get(std::size_t row, std::size_t col) const {
return ValueElement<double, true>();
}
bool MetaValueBaseImplementation::set(std::size_t row, std::size_t col, ElemInitType elem) {
return false;
}
bool MVBI::unaryOp( UnaryOp op) {
return false;
}
Ptr MVBI::unaryConstOp( UnaryConstOp op ) const {
return copy();
}
bool MVBI::binaryOp( BinaryOp op, const Interface& b) {
return false;
}
Ptr MVBI::binaryConstOp( BinaryConstOp op, const Interface& b ) const {
return copy();
}
MVBI::Ptr MVBI::block(size_t i, size_t j, size_t numI, size_t numJ) const {
return copy();
}
bool MVBI::block(size_t i, size_t j, Ptr&&){
return false;
}
MVBI::Ptr MVBI::col(size_t col) const {
return copy();
}
MVBI::Ptr MVBI::row(size_t row) const {
return copy();
}
bool MVBI::scale(const MetaScale& scale, bool invert){
return false;
}
ostream& MVBI::print( ostream& o ) const {
return o << "void";
}
ostream& operator<<( ostream& o, const MVBI& mvbi) {
return mvbi.print(o);
}
|
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include "inout.h"
#include "wyarray.h"
#include "readpara.h"
#include "kktlp.h"
#include "pdmatrix.h"
#include "solverlin.h"
#include "cglv.h"
using namespace std;
void SetPara (double *A, double *b, double *c, int na) {
// define the operator
for (int i = 0; i < na; i ++)
A[i] = rand()/(RAND_MAX + 1.0);
A[0] = -0.973528;
A[1] = 0.0919762;
A[2] = 0.843787;
A[3] = -0.52274;
A[4] = 0.686307;
A[5] = -0.762521;
b[0] = 0.758965;
b[1] = 0.648628;
c[0] = -0.732288;
c[1] = 1.06376;
c[2] = -0.742943;
}
void SetSolution (double *x, double *v, double *s, double *A, double *b, double *c, int n, int m) {
double *AT = new double[m * n];
double *ct = new double[n];
double *cc = new double[m];
double *bb = new double[n];
for (int i = 0; i < n; i ++) {
x[i] = rand()/(RAND_MAX + 1.0);
s[i] = rand()/(RAND_MAX + 1.0);
}
for (int i = 0; i < m; i ++)
v[i] = rand()/(RAND_MAX + 1.0);
PDMatrix *pdm = new PDMatrix(A, m, n);
pdm->Adjoint(bb, b);
SolverCG *sol = new SolverCG(0.001, 0.01, 50, pdm);
sol->CheckCgsOp();
sol->CgsWy(x, x, bb);
for (int i = 0; i < m; i ++)
for (int j = 0; j < n; j ++)
AT[j * m + i] = A[i * n + j];
for (int i = 0; i < n; i ++)
ct[i] = c[i] - s[i];
PDMatrix *pm2 = new PDMatrix(AT, n, m);
pm2->Adjoint(cc, ct);
SolverCG *so2 = new SolverCG(0.001, 0.01, 50, pm2);
so2->CheckCgsOp();
so2->CgsWy(v, v, cc);
delete [] AT;
delete [] ct;
delete [] cc;
delete [] bb;
}
int main (int argc, char **argv) {
double start = time(NULL);
//srand((unsigned)time(NULL));
int n = 3;
int m = 2;
int ng = n * n;
int na = m * n;
double *A = new double[na]; // size(A) = m x n
double *b = new double[m];
double *c = new double[n];
// get RHS of equation
SetPara(A, b, c, na);
// set a solution
double *x = new double[n];
double *v = new double[m];
double *s = new double[n];
// SetSolution(x, v, s, A, b, c, n, m);
// define the specific problem
KKTlp *kktm = new KKTlp(A, m, n);
//kktm->PrintMatrix(A, m, n, "Aopr");
//kktm->PrintVector(x, n, "xxx");
// define the solver
SolverLin *sollp = new SolverLin (kktm);
//sollp->GetRhsBC(b, c, x, v, s);
//kktm->PrintVector(b, m, "bbb");
//kktm->PrintVector(c, n, "ccc");
kktm->PrintMatrix(A, m, n, "Aopr");
kktm->PrintVector(b, m, "bbb");
kktm->PrintVector(c, n, "ccc");
// solve the problem
double *x0 = new double[n];
double *v0 = new double[m];
double *s0 = new double[n];
sollp->InnerPoint(x0, v0, s0, b, c);
// print result
cout << "index predicted true " << endl;
for (int i = 0; i < n; i ++) {
cout << " i, x = " << i << ", " << x0[i] << ", " << x[i] << endl;
}
for (int i = 0; i < m; i ++) {
cout << " i, v = " << i << ", " << v0[i] << ", " << v[i] << endl;
}
for (int i = 0; i < n; i ++) {
cout << " i, s = " << i << ", " << s0[i] << ", " << s[i] << endl;
}
double stop = time(NULL);
double durationTime = (double)difftime(stop, start);
cout << endl << "Cost:" << durationTime << " sec" << endl;
kktm->Free();
}
|
/**
* @file ServiceAdvertiser.h
* @author Lukas Schuller
* @date Sun Oct 6 14:34:31 2013
*
* @brief
*
*/
#ifndef SERVICEADVERTISER_H
#define SERVICEADVERTISER_H
#include <iostream>
#include <exception>
#include <boost/asio.hpp>
#include <boost/array.hpp>
class AdvertiserException : public std::exception {
public:
AdvertiserException(const char * msg) : message(msg) { }
virtual ~AdvertiserException() throw() {}
virtual char const * what() const throw() {
return message;
}
private:
char const * message;
};
class ServiceAdvertiser {
public:
ServiceAdvertiser(std::shared_ptr<boost::asio::io_service> const & ios,
int const port);
void AcceptClient(boost::asio::ip::tcp::socket & client,
int const port = -1);
private:
void StartReceive();
void AcceptCb(const boost::system::error_code& error);
void ReceiveCb(const boost::system::error_code& error);
std::shared_ptr<boost::asio::io_service> pIoService;
boost::asio::ip::udp::socket mAdSocket;
boost::asio::ip::udp::endpoint remoteEndpoint;
int mPort;
boost::array<char, 1> rxBuf;
};
#endif /* SERVICEADVERTISER_H */
|
#pragma once
#include <string>
#include <unordered_map>
#include <vector>
#include "tangible_filesystem.h"
#include "Chemistry/Chemistry.h"
using namespace Chemistry;
#include "../EngineLayer/EngineLayer.h"
using namespace EngineLayer;
#include "../EngineLayer/CrosslinkSearch/CrosslinkSearchEngine.h"
using namespace EngineLayer::CrosslinkSearch;
#include "../EngineLayer/Indexing/IndexingResults.h"
using namespace EngineLayer::Indexing;
#include "MassSpectrometry/MassSpectrometry.h"
using namespace MassSpectrometry;
#include "MzLibUtil.h"
using namespace MzLibUtil;
#include "Proteomics/Proteomics.h"
using namespace Proteomics;
using namespace Proteomics::AminoAcidPolymer;
using namespace Proteomics::Fragmentation;
using namespace Proteomics::ProteolyticDigestion;
#include "../TaskLayer/TaskLayer.h"
#include "../TaskLayer/XLSearchTask/XLSearchParameters.h"
using namespace TaskLayer;
#include "UsefulProteomicsDatabases/UsefulProteomicsDatabases.h"
using namespace UsefulProteomicsDatabases;
namespace Test
{
class CSMSerializationTest final
{
public:
static void CSMSerializationTest_BSA_DSSO();
static void TestDeadendTrisSerialized();
};
class XLTestDataFile : public MsDataFile
{
//Create DSSO crosslinked fake MS data. Include single, deadend, loop, inter, intra crosslinks ms2 data for match.
public:
XLTestDataFile();
std::string getFilePath() const;
std::string getName() const;
void ReplaceFirstScanArrays(std::vector<double> &mz, std::vector<double> &intensities);
};
}
|
#include "Core/mvPythonModule.h"
#include "Core/mvApp.h"
#include "Core/mvPythonTranslator.h"
#include "Core/AppItems/mvAppItems.h"
#include "mvAppInterface.h"
namespace Marvel {
static std::map<std::string, mvPythonTranslator> Translators = BuildTranslations();
PyObject* addItemColorStyle(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* item;
int style;
PyObject* color;
if (!Translators["addItemColorStyle"].parse(args, kwargs, __FUNCTION__, &item, &style, &color))
Py_RETURN_NONE;
auto mcolor = mvPythonTranslator::getColor(color);
mvApp::GetApp()->addItemColorStyle(item, style, mcolor);
Py_RETURN_NONE;
}
PyObject* isItemHovered(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* item;
if (!Translators["isItemHovered"].parse(args, kwargs,__FUNCTION__, &item))
Py_RETURN_NONE;
bool value = mvApp::GetApp()->isItemHovered(std::string(item));
PyObject* pvalue = Py_BuildValue("i", value);
return pvalue;
}
PyObject* isItemActive(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* item;
if (!Translators["isItemActive"].parse(args, kwargs,__FUNCTION__, &item))
Py_RETURN_NONE;
bool value = mvApp::GetApp()->isItemActive(std::string(item));
PyObject* pvalue = Py_BuildValue("i", value);
return pvalue;
}
PyObject* isItemFocused(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* item;
if (!Translators["isItemFocused"].parse(args, kwargs,__FUNCTION__, &item))
Py_RETURN_NONE;
bool value = mvApp::GetApp()->isItemFocused(std::string(item));
PyObject* pvalue = Py_BuildValue("i", value);
return pvalue;
}
PyObject* isItemClicked(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* item;
if (!Translators["isItemClicked"].parse(args, kwargs,__FUNCTION__, &item))
Py_RETURN_NONE;
bool value = mvApp::GetApp()->isItemClicked(std::string(item));
PyObject* pvalue = Py_BuildValue("i", value);
return pvalue;
}
PyObject* isItemVisible(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* item;
if (!Translators["isItemVisible"].parse(args, kwargs,__FUNCTION__, &item))
Py_RETURN_NONE;
bool value = mvApp::GetApp()->isItemVisible(std::string(item));
PyObject* pvalue = Py_BuildValue("i", value);
return pvalue;
}
PyObject* isItemEdited(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* item;
if (!Translators["isItemEdited"].parse(args, kwargs,__FUNCTION__, &item))
Py_RETURN_NONE;
bool value = mvApp::GetApp()->isItemEdited(std::string(item));
PyObject* pvalue = Py_BuildValue("i", value);
return pvalue;
}
PyObject* isItemActivated(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* item;
if (!Translators["isItemActivated"].parse(args, kwargs,__FUNCTION__, &item))
Py_RETURN_NONE;
bool value = mvApp::GetApp()->isItemActivated(std::string(item));
PyObject* pvalue = Py_BuildValue("i", value);
return pvalue;
}
PyObject* isItemDeactivated(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* item;
if (!Translators["isItemDeactivated"].parse(args, kwargs,__FUNCTION__, &item))
Py_RETURN_NONE;
bool value = mvApp::GetApp()->isItemDeactivated(std::string(item));
PyObject* pvalue = Py_BuildValue("i", value);
return pvalue;
}
PyObject* isItemDeactivatedAfterEdit(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* item;
if (!Translators["isItemDeactivatedAfterEdit"].parse(args, kwargs,__FUNCTION__, &item))
Py_RETURN_NONE;
bool value = mvApp::GetApp()->isItemDeactivatedAfterEdit(std::string(item));
PyObject* pvalue = Py_BuildValue("i", value);
return pvalue;
}
PyObject* isItemToggledOpen(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* item;
if (!Translators["isItemToggledOpen"].parse(args, kwargs,__FUNCTION__, &item))
Py_RETURN_NONE;
bool value = mvApp::GetApp()->isItemToogledOpen(std::string(item));
PyObject* pvalue = Py_BuildValue("i", value);
return pvalue;
}
PyObject* getItemRectMin(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* item;
if (!Translators["getItemRectMin"].parse(args, kwargs,__FUNCTION__, &item))
Py_RETURN_NONE;
mvVec2 value = mvApp::GetApp()->getItemRectMin(std::string(item));
PyObject* pvalue = PyTuple_New(2);
PyTuple_SetItem(pvalue, 0, PyFloat_FromDouble(value.x));
PyTuple_SetItem(pvalue, 1, PyFloat_FromDouble(value.y));
return pvalue;
}
PyObject* getItemRectMax(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* item;
if (!Translators["getItemRectMax"].parse(args, kwargs,__FUNCTION__, &item))
Py_RETURN_NONE;
mvVec2 value = mvApp::GetApp()->getItemRectMax(std::string(item));
PyObject* pvalue = PyTuple_New(2);
PyTuple_SetItem(pvalue, 0, PyFloat_FromDouble(value.x));
PyTuple_SetItem(pvalue, 1, PyFloat_FromDouble(value.y));
return pvalue;
}
PyObject* getItemRectSize(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* item;
if (!Translators["getItemRectSize"].parse(args, kwargs,__FUNCTION__, &item))
Py_RETURN_NONE;
mvVec2 value = mvApp::GetApp()->getItemRectSize(std::string(item));
PyObject* pvalue = PyTuple_New(2);
PyTuple_SetItem(pvalue, 0, PyFloat_FromDouble(value.x));
PyTuple_SetItem(pvalue, 1, PyFloat_FromDouble(value.y));
return pvalue;
}
PyObject* changeStyleItem(PyObject* self, PyObject* args, PyObject* kwargs)
{
int item;
float x = 0.0f;
float y = 0.0f;
if (!Translators["changeStyleItem"].parse(args, kwargs,__FUNCTION__, &item, &x, &y))
Py_RETURN_NONE;
mvApp::GetApp()->changeStyleItem(item, x, y);
Py_RETURN_NONE;
}
PyObject* changeThemeItem(PyObject* self, PyObject* args, PyObject* kwargs)
{
int item;
float r, g, b, a;
if(!Translators["changeThemeItem"].parse(args, kwargs,__FUNCTION__, &item, &r, &g, &b, &a))
Py_RETURN_NONE;
mvApp::GetApp()->changeThemeItem(item, { r, g, b, a });
Py_RETURN_NONE;
}
PyObject* getValue(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* name;
if(!Translators["getValue"].parse(args, kwargs,__FUNCTION__, &name))
Py_RETURN_NONE;
mvAppItem* item = mvApp::GetApp()->getItem(std::string(name));
if(item == nullptr)
Py_RETURN_NONE;
return item->getPyValue();
}
PyObject* setValue(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* name;
PyObject* value;
if(!Translators["setValue"].parse(args, kwargs,__FUNCTION__, &name, &value))
Py_RETURN_NONE;
mvAppItem* item = mvApp::GetApp()->getItem(std::string(name));
if (item == nullptr)
Py_RETURN_NONE;
item->setPyValue(value);
Py_RETURN_NONE;
}
PyObject* showItem(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* name;
if(!Translators["showItem"].parse(args, kwargs,__FUNCTION__, &name))
Py_RETURN_NONE;
mvAppItem* item = mvApp::GetApp()->getItem(std::string(name));
if (item != nullptr)
item->show();
Py_RETURN_NONE;
}
PyObject* hideItem(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* name;
if(!Translators["hideItem"].parse(args, kwargs,__FUNCTION__, &name))
Py_RETURN_NONE;
mvAppItem* item = mvApp::GetApp()->getItem(std::string(name));
if (item != nullptr)
item->hide();
Py_RETURN_NONE;
}
PyObject* setMainCallback(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* callback;
if(!Translators["setMainCallback"].parse(args, kwargs,__FUNCTION__, &callback))
Py_RETURN_NONE;
mvApp::GetApp()->setMainCallback(std::string(callback));
Py_RETURN_NONE;
}
PyObject* setMouseDownCallback(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* callback;
if (!Translators["setMouseDownCallback"].parse(args, kwargs,__FUNCTION__, &callback))
Py_RETURN_NONE;
mvApp::GetApp()->setMouseDownCallback(std::string(callback));
Py_RETURN_NONE;
}
PyObject* setMouseDoubleClickCallback(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* callback;
if (!Translators["setMouseDoubleClickCallback"].parse(args, kwargs,__FUNCTION__, &callback))
Py_RETURN_NONE;
mvApp::GetApp()->setMouseDoubleClickCallback(std::string(callback));
Py_RETURN_NONE;
}
PyObject* setMouseClickCallback(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* callback;
if (!Translators["setMouseClickCallback"].parse(args, kwargs,__FUNCTION__, &callback))
Py_RETURN_NONE;
mvApp::GetApp()->setMouseClickCallback(std::string(callback));
Py_RETURN_NONE;
}
PyObject* setKeyDownCallback(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* callback;
if (!Translators["setKeyDownCallback"].parse(args, kwargs,__FUNCTION__, &callback))
Py_RETURN_NONE;
mvApp::GetApp()->setKeyDownCallback(std::string(callback));
Py_RETURN_NONE;
}
PyObject* setKeyPressCallback(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* callback;
if (!Translators["setKeyPressCallback"].parse(args, kwargs,__FUNCTION__, &callback))
Py_RETURN_NONE;
mvApp::GetApp()->setKeyPressCallback(std::string(callback));
Py_RETURN_NONE;
}
PyObject* setKeyReleaseCallback(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* callback;
if (!Translators["setKeyReleaseCallback"].parse(args, kwargs,__FUNCTION__, &callback))
Py_RETURN_NONE;
mvApp::GetApp()->setKeyReleaseCallback(std::string(callback));
Py_RETURN_NONE;
}
PyObject* setItemCallback(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* callback, * item;
if(!Translators["setItemCallback"].parse(args, kwargs,__FUNCTION__, &item, &callback))
Py_RETURN_NONE;
mvApp::GetApp()->setItemCallback(item, callback);
Py_RETURN_NONE;
}
PyObject* setItemPopup(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* popup, * item;
if (!Translators["setItemPopup"].parse(args, kwargs,__FUNCTION__, &item, &popup))
Py_RETURN_NONE;
mvApp::GetApp()->setItemPopup(std::string(item), std::string(popup));
Py_RETURN_NONE;
}
PyObject* setItemTip(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* tip, * item;
if(!Translators["setItemTip"].parse(args, kwargs,__FUNCTION__, &item, &tip))
Py_RETURN_NONE;
mvApp::GetApp()->setItemTip(std::string(item), std::string(tip));
Py_RETURN_NONE;
}
PyObject* setItemWidth(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* item;
int width;
if(!Translators["setItemWidth"].parse(args, kwargs,__FUNCTION__, &item, &width))
Py_RETURN_NONE;
mvApp::GetApp()->setItemWidth(std::string(item), width);
Py_RETURN_NONE;
}
PyObject* closePopup(PyObject* self, PyObject* args, PyObject* kwargs)
{
mvApp::GetApp()->closePopup();
Py_RETURN_NONE;
}
PyObject* setTheme(PyObject* self, PyObject* args, PyObject* kwargs)
{
const char* theme;
if(!Translators["setTheme"].parse(args, kwargs,__FUNCTION__, &theme))
Py_RETURN_NONE;
mvApp::GetApp()->setAppTheme(std::string(theme));
Py_RETURN_NONE;
}
PyObject* showMetrics(PyObject* self, PyObject* args, PyObject* kwargs)
{
mvApp::GetApp()->showMetrics();
Py_RETURN_NONE;
}
PyObject* showAbout(PyObject* self, PyObject* args, PyObject* kwargs)
{
mvApp::GetApp()->showAbout();
Py_RETURN_NONE;
}
void CreatePythonInterface(mvPythonModule& pyModule, PyObject* (*initfunc)())
{
pyModule.addMethod(showAbout, "Not Documented");
pyModule.addMethod(showMetrics, "Not Documented");
pyModule.addMethodD(addItemColorStyle);
pyModule.addMethodD(setItemPopup);
pyModule.addMethodD(closePopup);
pyModule.addMethodD(isItemHovered);
pyModule.addMethodD(isItemActive);
pyModule.addMethodD(isItemFocused);
pyModule.addMethodD(isItemClicked);
pyModule.addMethodD(isItemVisible);
pyModule.addMethodD(isItemEdited);
pyModule.addMethodD(isItemActivated);
pyModule.addMethodD(isItemDeactivated);
pyModule.addMethodD(isItemDeactivatedAfterEdit);
pyModule.addMethodD(isItemToggledOpen);
pyModule.addMethodD(getItemRectMin);
pyModule.addMethodD(getItemRectMax);
pyModule.addMethodD(getItemRectSize);
pyModule.addMethodD(setMouseClickCallback);
pyModule.addMethodD(setMouseDownCallback);
pyModule.addMethodD(setMouseDoubleClickCallback);
pyModule.addMethodD(setKeyDownCallback);
pyModule.addMethodD(setKeyPressCallback);
pyModule.addMethodD(setKeyReleaseCallback);
pyModule.addMethodD(changeStyleItem);
pyModule.addMethodD(showItem);
pyModule.addMethodD(hideItem);
pyModule.addMethodD(changeThemeItem);
pyModule.addMethodD(setTheme);
pyModule.addMethodD(setMainCallback);
pyModule.addMethodD(setItemCallback);
pyModule.addMethodD(setItemTip);
pyModule.addMethodD(setItemWidth);
pyModule.addMethodD(getValue);
pyModule.addMethodD(setValue);
PyImport_AppendInittab(pyModule.getName() , initfunc);
}
}
|
//------------------------------------------------------------------------------
// PointGroup
//------------------------------------------------------------------------------
// GMAT: General Mission Analysis Tool.
//
// Copyright (c) 2002 - 2015 United States Government as represented by the
// Administrator of the National Aeronautics and Space Administration.
// All Other Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// You may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
// http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language
// governing permissions and limitations under the License.
//
// Author: Wendy Shoan, NASA/GSFC
// Created: 2016.05.06
//
/**
* Implementation of the PointGroup class
*/
//------------------------------------------------------------------------------
#include "gmatdefs.hpp"
#include "PointGroup.hpp"
#include "RealUtilities.hpp"
#include "GmatConstants.hpp"
#include "Rmatrix33.hpp"
#include "TATCException.hpp"
#include "MessageInterface.hpp"
//#define DEBUG_HELICAL_POINTS
//#define DEBUG_POINTS
using namespace GmatMathConstants;
using namespace GmatMathUtil;
//------------------------------------------------------------------------------
// static data
//------------------------------------------------------------------------------
// None
//------------------------------------------------------------------------------
// public methods
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// PointGroup()
//------------------------------------------------------------------------------
/**
* Default constructor for the PointGroup class.
*
*/
//---------------------------------------------------------------------------
PointGroup::PointGroup() :
numPoints (0),
numRequestedPoints (0),
latUpper (PI_OVER_TWO),
latLower (-PI_OVER_TWO),
lonUpper (TWO_PI),
lonLower (0.0)
{
// lat, lon, and coords are all empty at the start
}
//------------------------------------------------------------------------------
// PointGroup(const PointGroup ©)
//------------------------------------------------------------------------------
/**
* Copy constructor for the PointGroup class.
*
* @param copy PointGroup object to copy
*
*/
//---------------------------------------------------------------------------
PointGroup::PointGroup(const PointGroup ©) :
numPoints (copy.numPoints),
numRequestedPoints (copy.numRequestedPoints),
latUpper (copy.latUpper),
latLower (copy.latLower),
lonUpper (copy.lonUpper),
lonLower (copy.lonLower)
{
lat.clear();
lon.clear();
coords.clear();
lat = copy.lat;
lon = copy.lon;
for (Integer ii = 0; ii < copy.numPoints; ii++)
{
Rvector3 *copyCoord = copy.coords.at(ii);
Rvector3 *newCoord = new Rvector3(*copyCoord);
coords.push_back(newCoord);
}
}
//------------------------------------------------------------------------------
// PointGroup & operator=(const PointGroup ©)
//------------------------------------------------------------------------------
/**
* operator= for the PointGroup class.
*
* @param copy PointGroup object to copy
*
*/
//---------------------------------------------------------------------------
PointGroup& PointGroup::operator=(const PointGroup ©)
{
if (© == this)
return *this;
numPoints = copy.numPoints;
numRequestedPoints = copy.numRequestedPoints;
latUpper = copy.latUpper;
latLower = copy.latLower;
lonUpper = copy.lonUpper;
lonLower = copy.lonLower;
lat.clear();
lon.clear();
coords.clear();
lat = copy.lat;
lon = copy.lon;
for (Integer ii = 0; ii < copy.numPoints; ii++)
{
Rvector3 *copyCoord = copy.coords.at(ii);
Rvector3 *newCoord = new Rvector3(*copyCoord);
coords.push_back(newCoord);
}
return *this;
}
//------------------------------------------------------------------------------
// ~PointGroup()
//------------------------------------------------------------------------------
/**
* Destructor for the PointGroup class.
*
*/
//---------------------------------------------------------------------------
PointGroup::~PointGroup()
{
lat.clear();
lon.clear();
for (Integer ii = 0; ii < numPoints; ii++)
delete coords.at(ii);
coords.clear();
}
//------------------------------------------------------------------------------
// void AddUserDefinedPoints(const RealArray& lats,
// const RealArray& lons)
//------------------------------------------------------------------------------
/**
* Adds user-defined points to the list of points, given the input latitudes
* and longitudes.
*
* @param lats list of latitudes for the points to add
* @param lons list of longitudes for the points to add
*
*/
//---------------------------------------------------------------------------
void PointGroup::AddUserDefinedPoints(const RealArray& lats,
const RealArray& lons)
{
// Add user defined latitude and longitude points
// Inputs are real arrays of longitude and latitude in radians
if (lats.size() != lons.size())
throw TATCException("latitude and longitude arrays must have the same length\n");
Integer sz = (Integer) lats.size();
for (Integer ptIdx = 0; ptIdx < sz; ptIdx++)
AccumulatePoints(lats.at(ptIdx),lons.at(ptIdx));
}
//------------------------------------------------------------------------------
// void AddHelicalPointsByNumPoints(Integer numGridPoints)
//------------------------------------------------------------------------------
/**
* Computes and adds the specified number of user-defined points to the list of
* points.
*
* @param numGridPoints number of grid points to add
*
*/
//---------------------------------------------------------------------------
void PointGroup::AddHelicalPointsByNumPoints(Integer numGridPoints)
{
ComputeTestPoints("Helical",numGridPoints);
}
//------------------------------------------------------------------------------
// void AddHelicalPointsByAngle(Real angleBetweenPoints)
//------------------------------------------------------------------------------
/**
* Computes and adds points to the list of points, based on the input
* angle.
*
* @param angleBetweenPoints angle between points
*
*/
//---------------------------------------------------------------------------
void PointGroup::AddHelicalPointsByAngle(Real angleBetweenPoints)
{
Integer numGridPoints = Floor(4.0*PI/
(angleBetweenPoints*angleBetweenPoints));
ComputeTestPoints("Helical",numGridPoints);
}
//------------------------------------------------------------------------------
// Rvector3* GetPointPositionVector(Integer idx)
//------------------------------------------------------------------------------
/**
* Returns the coordinates of the specified point.
*
* @param idx index of point whose coordinates to return
*
* @return a 3-vector representing the coordinates of the specifed point
*
*/
//---------------------------------------------------------------------------
Rvector3* PointGroup::GetPointPositionVector(Integer idx)
{
// Returns body fixed location of point given point index
// Inputs. int poiIndex
// Outputs. Rvector 3x1 containing the position.
// Make sure there are points
CheckHasPoints();
#ifdef DEBUG_POINTS
MessageInterface::ShowMessage(
"In PG::GetPointPositionVector, returning coords (%p) at idx = %d\n",
coords.at(idx), idx);
#endif
return coords.at(idx);
}
//------------------------------------------------------------------------------
// void GetLatAndLon(Integer idx, Real &theLat, Real &theLon)
//------------------------------------------------------------------------------
/**
* Returns the latitude and longtude of the specified point.
*
* @param idx index of point whose latitude/longitude to return
* @param theLat OUTPUT latitude of the specified point
* @param theLon OUTPUT longitude of the specified point
*
*/
//---------------------------------------------------------------------------
void PointGroup::GetLatAndLon(Integer idx, Real &theLat, Real &theLon)
{
// Returns body fixed location of point given point index
// Inputs. int poiIndex
// Outputs. double lat, double lon
// Make sure there are points
CheckHasPoints();
theLat = lat.at(idx);
theLon = lon.at(idx);
}
//------------------------------------------------------------------------------
// Integer GetNumPoints()
//------------------------------------------------------------------------------
/**
* Returns the number of points.
*
* @return the number of points
*
*/
//---------------------------------------------------------------------------
Integer PointGroup::GetNumPoints()
{
return numPoints;
}
//------------------------------------------------------------------------------
// void GetLatLonVectors(RealArray &lats, RealArray &lons)
//------------------------------------------------------------------------------
/**
* Returns vectors of latitudes and longitudes for the points.
*
* @param lats OUTPUT array of latitudes for the points
* @param lons OUTPUT array of longitudes for the points
*
*/
//---------------------------------------------------------------------------
void PointGroup::GetLatLonVectors(RealArray &lats, RealArray &lons)
{
// Returns the latitude and longitude vectors
//Make sure there are points
CheckHasPoints();
lats = lat;
lons = lon;
}
//------------------------------------------------------------------------------
// void SetLatLonBounds(Real latUp, Real latLow,
// Real lonUp, Real lonLow)
//------------------------------------------------------------------------------
/**
* Sets the latitude and longtude upper and lower bounds.
*
* @param latUp upper bound for latitude (radians)
* @param latLow lower bound for latitude (radians)
* @param lonUp upper bound for longitude (radians)
* @param lonLow lower bound for longitude (radians)
*
*/
//---------------------------------------------------------------------------
void PointGroup::SetLatLonBounds(Real latUp, Real latLow,
Real lonUp, Real lonLow)
{
if (numPoints >0)
throw TATCException("You must set Lat/Lon Bounds Before adding points\n");
// Sets bounds on latitude and longitude for grid points
// angle inputs are in radians
if (latLow >= latUp)
throw TATCException("latLower > latUpper or they are equal\n");
if (lonLow >= lonUp)
throw TATCException("lonLower > lonUpper or they are equal\n");
if (latUp < -PI_OVER_TWO ||
latUp > PI_OVER_TWO)
throw TATCException("latUpper value is invalid\n");
latUpper = latUp;
if (latLow < -PI_OVER_TWO ||
latLow > PI_OVER_TWO)
throw TATCException("latLower value is invalid\n");
latLower = latLow;
lonUpper = Mod(lonUp, TWO_PI);
lonLower = Mod(lonLow,TWO_PI);
}
//------------------------------------------------------------------------------
// protected methods
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// bool CheckHasPoints()
//------------------------------------------------------------------------------
/**
* Checks to see if there are any ponts set or computed
*
* @return true if there are points; false otherwise
*
*/
//---------------------------------------------------------------------------
bool PointGroup::CheckHasPoints()
{
if (numPoints <= 0)
throw TATCException("The point group does not have any points\n");
return true;
}
//------------------------------------------------------------------------------
// void AccumulatePoints(Real lat1, Real lon1)
//------------------------------------------------------------------------------
/**
* Adds a point with the specified latitude and longitude. The coordinates
* are computed from the input latitude and longitude.
*
* @param lat1 latitude for the point to add
* @param lon1 longitude for the point to add
*
*/
//---------------------------------------------------------------------------
void PointGroup::AccumulatePoints(Real lat1, Real lon1)
{
#ifdef DEBUG_POINTS
MessageInterface::ShowMessage(
"Entering PG::AccumulatePoints with lat1 = %12.10f and lon1 = %12.10f\n",
lat1, lon1);
#endif
// Accumulates points, only adding them if they pass constraint
// checks
if ((lat1 >= latLower) && (lat1 <= latUpper) &&
(lon1 >= lonLower) && (lon1 <= lonUpper))
{
lon.push_back(lon1);
lat.push_back(lat1);
// TODO: Use geodetic to Cartesian conversion and don't
// hard code the Earth radius.
Rvector3 *newCoord = new Rvector3(
(Cos(lon1) * Cos(lat1)) * 6378.1363,
(Sin(lon1) * Cos(lat1)) * 6378.1363,
Sin(lat1) * 6378.1363);
#ifdef DEBUG_POINTS
MessageInterface::ShowMessage(
"PG::AccumulatePoints, pushing back (%p) (into position %d, size = %d) %12.10f %12.10f %12.10f\n",
newCoord, coords.size(), numPoints, newCoord->GetElement(0), newCoord->GetElement(1), newCoord->GetElement(2));
#endif
coords.push_back(newCoord);
numPoints++;
}
// else
// {
// throw TATCException("lat or lon too big or small!!!!\n");
// }
}
//------------------------------------------------------------------------------
// void ComputeTestPoints(const std::string &modelName, Integer numGridPts)
//------------------------------------------------------------------------------
/**
* Computes the number of test points specified, for the model specified.
*
* @param modelName model for the points
* @param numGridPoints number of points to compute and add
*
*/
//---------------------------------------------------------------------------
void PointGroup::ComputeTestPoints(const std::string &modelName,
Integer numGridPts)
{
#ifdef DEBUG_POINTS
MessageInterface::ShowMessage(
"Entering PG::ComputeTestPoints with modelName = %s and numGridPoints = %d\n",
modelName.c_str(), numGridPts);
#endif
// Computes surface grid points
// Inputs: string modelName
// Place first point at north pole
if (numGridPts > 0)
{
// One Point at North Pole
AccumulatePoints(PI_OVER_TWO,0.0);
}
// Place second point at south pole
if (numGridPts > 1)
{
// One Point at South Pole
AccumulatePoints(-PI_OVER_TWO,0.0);
}
// Place remaining points according to requested algorithm
if (numGridPts > 2)
{
if (modelName == "Helical")
ComputeHelicalPoints(numGridPts-2);
}
}
//------------------------------------------------------------------------------
// void ComputeHelicalPoints(Integer numReqPts)
//------------------------------------------------------------------------------
/**
* Computes the number of test points specified, using a model.
*
* @param numReqPts number of test points to compute and add
*
*/
//---------------------------------------------------------------------------
void PointGroup::ComputeHelicalPoints(Integer numReqPts)
{
#ifdef DEBUG_HELICAL_POINTS
MessageInterface::ShowMessage("Entering PG::ComputeHelicalPoints with numReqPts = %d\n",
numReqPts);
#endif
// Build a set of evenly spaced points using Helical algorithm
// Inputs: int, numPoints
// Determine how many longitude "bands" and fill them in
Real q = ((Real)(numReqPts+1)) * (PI/4.0);
Integer numDiscreteLatitudes = (Integer) Floor(Sqrt(q));
Rvector discreteLatitudes(numDiscreteLatitudes); // all zeros by default
#ifdef DEBUG_HELICAL_POINTS
MessageInterface::ShowMessage("In PG::ComputeHelicalPoints, numDiscreteLatitudes = %d\n",
numDiscreteLatitudes);
#endif
for (Integer latIdx = 0; latIdx < numDiscreteLatitudes; latIdx += 2)
{
Real latOverNum = (Real) (((Real) (latIdx + 2)) / ((Real)(numDiscreteLatitudes + 1)));
// Real latOverNum = (Real) ((Real) (latIdx + 1)) / (Real)(numDiscreteLatitudes + 1);
Real latToUse = PI_OVER_TWO * (1.0 - latOverNum);
// EVEN numbers
discreteLatitudes(latIdx) = latToUse;
// ODD numbers
#ifdef DEBUG_HELICAL_POINTS
MessageInterface::ShowMessage(" latIdx = %d\n", latIdx);
MessageInterface::ShowMessage(" numDiscreteLatitudes = %d\n", numDiscreteLatitudes);
MessageInterface::ShowMessage(" latOverNum = %12.10f\n", latOverNum);
MessageInterface::ShowMessage(" latToUse = %12.10f\n", latToUse);
MessageInterface::ShowMessage(" Setting discreteLatitude(%d) = %12.10f\n",
latIdx, discreteLatitudes(latIdx));
#endif
// Only do this if it fits in the array (if numDiscreteLatitudes
// is odd, latIdx + 1 is too big for the array)
if (latIdx < (numDiscreteLatitudes - 1))
{
discreteLatitudes(latIdx+1) = -latToUse;
#ifdef DEBUG_HELICAL_POINTS
MessageInterface::ShowMessage(" Setting discreteLatitude(%d) = %12.10f\n",
latIdx+1, discreteLatitudes(latIdx+1));
#endif
}
}
// Now compute the longitude points for each latitude band
Real alpha = 0.0; // was Real array in MATLAB
for (Integer latIdx = 0; latIdx < numDiscreteLatitudes; latIdx++)
alpha += Cos(discreteLatitudes(latIdx));
#ifdef DEBUG_HELICAL_POINTS
MessageInterface::ShowMessage(" alpha = %12.10f\n", alpha);
#endif
Integer numPtsByBand = 0; // this was an int array in MATLAB
Integer numRemainingPoints = numReqPts; // this was an int array in MATLAB
for (Integer latIdx = 0; latIdx < numDiscreteLatitudes; latIdx++)
{
Real currentLat = discreteLatitudes(latIdx);
Real cosLat = Cos(currentLat);
Real numToRound = ((Real) numRemainingPoints) * cosLat / alpha;
numPtsByBand = (Integer) Round(numToRound);
#ifdef DEBUG_HELICAL_POINTS
MessageInterface::ShowMessage(" cosLat(for latIdx = %d) = %12.10f\n",
latIdx, cosLat);
MessageInterface::ShowMessage(" numPtsByBand = %d\n", numPtsByBand);
#endif
// decrement numRemainingPoints and alpha
numRemainingPoints -= numPtsByBand;
alpha -= cosLat;
for (Integer pt = 0; pt < numPtsByBand; pt++)
{
// Compute the latitude for the next point
// WAS (pt-1) but this causes a lat or lon out-of-range!!!
Real currentLongitude = TWO_PI * ((Real) (pt)) / ((Real) numPtsByBand);
// @TODO: Use geodetic to Cartesian conversion.
AccumulatePoints(currentLat,currentLongitude);
}
}
}
|
#include<iostream>
#include<cstdlib>
#include <cmath>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include<cstdio>
#include<cstring>
#include<sstream>
#ifdef __APPLE__
#include <OpenGL/OpenGL.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include "imageloader.h"
using namespace std;
# define pi 3.14
float start_time = 0, g = 0.000004, COR = 0.7, del = -0.0002, delsx = -0.05, zoom=1.0, panx=1.0;
int start_projectile = 0, LEVEL = 1, score = 100,lock = 0, flow = 0;
GLuint texture_ground_Id, texture_troll_Id, texture_tr_Id, texture_sh_Id, texture_intro_Id, texture_congo_Id;
float myabs(float a)
{
if(a<0)
return -a;
return a;
}
class bullet
{
public:
float bulletRad, thetaCopy, u, ux, uy, x0, y0, x, y, vx, vy, copyx0, copyy0;
bullet();
void make_bullet();
};
class cannon
{
public:
float cannonBaseX, cannonBaseY, cannonL, cannonRad, theta;
cannon();
void make_cannon();
void make_cannon_base();
};
class speedometer
{
public:
float x1,x2,y1,y2;
speedometer();
void display_speed();
};
class trampolene
{
public:
float x1,x2,y1,y2;
float x3,x4,y3,y4;
trampolene(float,float,float,float);
void make_tram();
void collision();
};
class balloon
{
public:
float rad,x1,y1,flag;
balloon();
void setP(float,float,float);
void make_balloon();
void collision();
void collision2();
};
class floater
{
public:
float x1,y1,rad,drop,speed,xlim1,xlim2,theta,arrowx,arrowy,arrowl,droptime,ht;
float copyx,copyy;
floater(float,float);
void resetF();
void movefloat();
void cut();
};
balloon target[30];
trampolene tram1(7,8,1.15,1.45);
speedometer s;
bullet b;
cannon c;
floater f1(9,5.2),f2(8,5.2),f3(7,5.2);
cannon::cannon()
{
cannonBaseX = 0.3;
cannonBaseY = 1.25;
cannonL = 1.0;
cannonRad = 0.1;
theta = 0;
}
bullet::bullet()
{
bulletRad = 0.1;
u = 0.0032;
ux = 0;
uy = 0;
thetaCopy = 0;
copyx0 = x0 = 0;
copyy0 = y0 = 0;
x = 0;
y = 0;
vx = 0;
vy = 0;
}
trampolene::trampolene(float a,float b, float c, float d)
{
x1 = a;
x2 = b;
y1 = c;
y2 = d;
}
balloon::balloon()
{
flag = 0;
}
floater::floater(float a,float b)
{
copyx = x1 = a;
copyy = y1 = b;
ht = y1 - 1;
drop = 0;
xlim1 = 2.5;
xlim2 = 9;
speed = 0.03;
rad = 0.2;
theta = 0;
arrowx = x1;
arrowy = y1 - 1;
arrowl = 0.2;
droptime = 0;
}
void bullet::make_bullet()
{
float t;
if(start_projectile == 0)
{
thetaCopy = c.theta;
x0 = c.cannonBaseX + (c.cannonL-bulletRad)*cos(thetaCopy*(pi/180));
y0 = c.cannonBaseY + (c.cannonL-bulletRad)*sin(thetaCopy*(pi/180));
x = x0;
y = y0;
copyx0 = x0;
copyy0 = y0;
ux = u*cos(thetaCopy*(pi/180));
uy = u*sin(thetaCopy*(pi/180));
}
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture_troll_Id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP);
glColor3f (1,1,1);
glBegin(GL_POLYGON);
for(int i=0;i<360;i++)
{
glTexCoord2f(0.5 + 0.55*cos(i*(pi/180)), 0.5 + 0.55*sin(i*(pi/180)));
glVertex3f(x + 0.1*cos(i*(pi/180)), y + 0.1*sin(i*(pi/180)),0);
}
glEnd();
glDisable(GL_TEXTURE_2D);
}
void cannon::make_cannon()
{
if(theta > 88)
theta = 88;
if(theta < 0)
theta = 0;
glRotatef(theta,0,0,1);
glColor3f(1.0f, 1.0f, 1.0f);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture_sh_Id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(0,-cannonRad,0);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(cannonL,-cannonRad,0);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(cannonL,cannonRad,0);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(0,cannonRad,0);
glEnd();
glDisable(GL_TEXTURE_2D);
glPopMatrix();
/*
glColor3f (0,0,1.0);
glBegin(GL_QUADS);
glVertex2f(0,-cannonRad);
glVertex2f(0,cannonRad);
glVertex2f(cannonL,cannonRad);
glVertex2f(cannonL,-cannonRad);
glEnd();
*/
}
void cannon::make_cannon_base()
{
glPushMatrix();
glTranslatef(cannonBaseX,cannonBaseY,0);
glBegin(GL_TRIANGLE_FAN);
glColor3f (0.0, 1.0, 0.0);
for(int i=0;i<360;i++)
{
glVertex2f(cannonRad*cos(i*(pi/180)),cannonRad*sin(i*(pi/180)));
}
glEnd();
make_cannon();
}
speedometer::speedometer()
{
x1 = 0.2;
x2 = 0.25;
y1 = 5.5;
y2 = 5.6;
}
void speedometer::display_speed()
{
glColor3f (138/255.0,43/255.0,226/255.0);
glBegin(GL_QUADS);
glVertex2f(x1,y1);
glVertex2f(x1,y2);
glVertex2f(x2,y2);
glVertex2f(x2,y1);
glEnd();
}
void trampolene::make_tram()
{
// /*
glColor3f(1.0f, 1.0f, 1.0f);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture_tr_Id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(x1,y1,0);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(x2,y1,0);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(x2,y2,0);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(x1,y2,0);
glEnd();
glDisable(GL_TEXTURE_2D);
//*/
/*
glBegin(GL_QUADS);
glColor3f (1,1,1);
glBegin(GL_QUADS);
glVertex2f(x1,y1);
glVertex2f(x2,y1);
glVertex2f(x2,y2);
glVertex2f(x1,y2);
glEnd();
*/
}
void trampolene::collision()
{
if(b.y>=y1 && b.y<=y2+0.05)
{
if(b.x+b.bulletRad > x1 && b.x+b.bulletRad <= x1+0.2)
{
start_time = glutGet(GLUT_ELAPSED_TIME);
b.ux *= -1;
b.x0 = x1-b.bulletRad;
b.y0 = b.y;
b.x = b.x0;
}
}
if(b.x>x1+0.1 && b.x<=x2+0.05)
{
if(b.y+b.bulletRad <= y2+0.05)
{
start_time = glutGet(GLUT_ELAPSED_TIME);
b.x0 = b.x;
b.y0 = y2;
b.uy = -b.vy*2;
b.y = y2;
}
}
}
void balloon::setP(float a,float b, float c)
{
x1 = a;
y1 = b;
rad = c;
}
void balloon::make_balloon()
{
if(flag == 1.0)
return;
glBegin(GL_TRIANGLE_FAN);
glColor3f (1, 215/255, 0.0);
for(int i=0;i<360;i++)
{
glVertex2f(x1 + rad*cos(i*(pi/180)),y1 + rad*sin(i*(pi/180)));
}
glEnd();
}
void balloon::collision()
{
if( (b.x-x1)*(b.x-x1)+(b.y-y1)*(b.y-y1) <= (rad+b.bulletRad)*(rad+b.bulletRad) )
{
flag = 1;
}
}
void balloon::collision2()
{
if(f1.arrowx>(x1-rad) && f1.arrowx<(x1+rad))
if(f1.arrowy>(y1-rad) && f1.arrowy<(y1+rad))
flag = 1;
if(f2.arrowx>(x1-rad) && f2.arrowx<(x1+rad))
if(f2.arrowy>(y1-rad) && f2.arrowy<(y1+rad))
flag = 1;
if(f3.arrowx>(x1-rad) && f3.arrowx<(x1+rad))
if(f3.arrowy>(y1-rad) && f3.arrowy<(y1+rad))
flag = 1;
}
void put_target1()
{
target[0].setP(9,3,0.2);
target[0].make_balloon();
target[1].setP(9.5,3.4,0.2);
target[1].make_balloon();
target[2].setP(10,3.8,0.2);
target[2].make_balloon();
}
void floater::resetF()
{
x1 = copyx;
y1 = copyy;
speed = myabs(speed);
}
void endchecklevel2();
void floater::movefloat()
{
float t;
if(drop == 1)
{
x1 += speed;
y1 += myabs(speed)/2;
}
else
{
if(x1 >= xlim2)
{
speed = -myabs(speed);
x1 = xlim2 - 0.01;
}
if(x1 <= xlim1)
{
speed = myabs(speed);
x1 = xlim1 + 0.01;
}
x1 += speed;
}
if(drop == 0)
{
glColor3f (0,0,0);
glBegin(GL_LINES);
glVertex2f(x1,y1);
glVertex2f(x1,y1-1);
glEnd();
}
glBegin(GL_TRIANGLE_FAN);
glColor3f (30/255, 44/255, 1);
for(int i=0;i<360;i++)
{
glVertex2f(
x1 + (rad + 0.1*sin(theta*(pi/100)))*cos(i*(pi/180)),
y1 + (rad + 0.1*sin(theta*(pi/100)))*sin(i*(pi/180))
);
}
glEnd();
theta += 0.5;
if(drop == 0)
{
arrowx = x1; arrowy = y1-1;
}
else if(drop == 1 && arrowy>-1)
{
arrowx += speed;
t = glutGet(GLUT_ELAPSED_TIME) - droptime;
arrowy = ht - 0.5*g*t*t;
}
if(arrowy >= 1.36)
{
glColor3f (1,0,0);
glBegin(GL_LINES);
glVertex2f(arrowx,arrowy);
glVertex2f(arrowx,arrowy-arrowl);
glEnd();
glBegin(GL_LINES);
glVertex2f(arrowx,arrowy-arrowl);
glVertex2f(arrowx+arrowl/2,arrowy-arrowl/2);
glEnd();
glBegin(GL_LINES);
glVertex2f(arrowx,arrowy-arrowl);
glVertex2f(arrowx-arrowl/2,arrowy-arrowl/2);
glEnd();
}
else
{
endchecklevel2();
}
}
void floater::cut()
{
if(b.y>y1-1 && b.y<y1)
{
if(b.x>x1 && b.x-x1 < 0.2)
{
drop = 1;
droptime = glutGet(GLUT_ELAPSED_TIME);
}
}
}
void put_target2()
{
target[0].setP(3,1.35,0.2);
target[0].make_balloon();
target[1].setP(4,1.35,0.2);
target[1].make_balloon();
target[2].setP(5,1.35,0.2);
target[2].make_balloon();
}
//Makes the image into a texture, and returns the id of the texture
GLuint loadTexture(Image* image) {
GLuint textureId;
glGenTextures(1, &textureId); //Make room for our texture
glBindTexture(GL_TEXTURE_2D, textureId); //Tell OpenGL which texture to edit
//Map the image to the texture
glTexImage2D(GL_TEXTURE_2D, //Always GL_TEXTURE_2D
0, //0 for now
GL_RGB, //Format OpenGL uses for image
image->width, image->height, //Width and height
0, //The border of the image
GL_RGB, //GL_RGB, because pixels are stored in RGB format
GL_UNSIGNED_BYTE, //GL_UNSIGNED_BYTE, because pixels are stored
//as unsigned numbers
image->pixels); //The actual pixel data
return textureId; //Returns the id of the texture
}
void initRendering()
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
Image* image = loadBMP("back.bmp");
texture_ground_Id = loadTexture(image);
delete image;
Image* image2 = loadBMP("troll.bmp");
texture_troll_Id = loadTexture(image2);
delete image2;
Image* image3 = loadBMP("trampo.bmp");
texture_tr_Id = loadTexture(image3);
delete image3;
Image* image4 = loadBMP("shoot.bmp");
texture_sh_Id = loadTexture(image4);
delete image4;
Image* image5 = loadBMP("intro.bmp");
texture_intro_Id = loadTexture(image5);
delete image5;
Image* image6 = loadBMP("congo.bmp");
texture_congo_Id = loadTexture(image6);
delete image6;
}
void background_image()
{
glColor3f(1.0f, 1.0f, 1.0f);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture_ground_Id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(0,0,0);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(11.5,0,0);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(11.5,6,0);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(0,6,0);
glEnd();
glDisable(GL_TEXTURE_2D);
string ans;
stringstream con;
con << score;
ans = con.str();
for(int i=0; i<ans.size(); i++)
{
glRasterPos2f(s.x1 + i*0.1,s.y1-0.1);
glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24 , ans[i]);
}
}
void intro()
{
glColor3f(1.0f, 1.0f, 1.0f);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture_intro_Id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(1.5,0,0);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(10,0,0);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(10,5.5,0);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(1.5,5.5,0);
glEnd();
glDisable(GL_TEXTURE_2D);
}
void congo()
{
glColor3f(1.0f, 1.0f, 1.0f);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texture_congo_Id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(1.5,0,0);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(10,0,0);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(10,5.5,0);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(1.5,5.5,0);
glEnd();
glDisable(GL_TEXTURE_2D);
}
void updatebullet()
{
float t = glutGet(GLUT_ELAPSED_TIME) - start_time;
b.x = b.x0 + b.ux*t;
b.vy = b.uy - g*t;
b.y = b.y0 + b.uy*t - 0.5*g*t*t;
}
void level1()
{
int i;
c.make_cannon_base();
b.make_bullet();
s.display_speed();
tram1.make_tram();
put_target1();
for(i=0; i<3; i++)
{
target[i].collision();
}
if(start_projectile == 1)
{
updatebullet();
tram1.collision();
}
}
void change2level2()
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(-5.55,-2.88,-5.0);
sleep(2);
LEVEL++;
flow++;
lock = 0;
}
void level2()
{
int i;
c.make_cannon_base();
b.make_bullet();
s.display_speed();
f1.movefloat();
f2.movefloat();
f3.movefloat();
f1.cut();
f2.cut();
f3.cut();
put_target2();
for(i=0; i<3; i++)
{
target[i].collision2();
}
if(start_projectile == 1)
{
updatebullet();
}
}
void change2level3()
{
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT );//| GL_DEPTH_BUFFER_BIT);
glTranslatef(-5.55,-2.88,-5.0);
sleep(2);
LEVEL++;
flow++;
cout << "flow " << flow << endl;
lock = 0;
}
void endchecklevel1()
{
int i;
for(i=0; i<3; i++)
if(target[i].flag == 0)
break;
if(i != 3)
{
for(i=0; i<3; i++)
target[i].flag = 0;
score--;
}
else
{
for(i=0; i<3; i++)
target[i].flag = 0;
change2level2();
}
}
void endchecklevel2()
{
if(f1.arrowy>=1.25 || f2.arrowy>=1.25 || f3.arrowy>=1.25)
{
if(f1.arrowy!=f1.copyy-1 && f2.arrowy!=f2.copyy-1 && f3.arrowy!=f3.copyy-1)
return;
}
int i;
for(i=0; i<3; i++)
if(target[i].flag == 0)
break;
if(i != 3)
{
for(i=0; i<3; i++)
target[i].flag = 0;
f1.resetF();
f2.resetF();
f3.resetF();
f1.drop = f2.drop = f3.drop = 0;
score--;
}
else
{
for(i=0; i<3; i++)
{
target[i].flag = 0;
f1.drop = f2.drop = f3.drop = 0;
change2level3();
}
}
}
void reload_cannon()
{
b.x0 = b.copyx0;
b.y0 = b.copyy0;
start_projectile = 0;
if(LEVEL == 1)
endchecklevel1();
}
void display (void)
{
float t;
int i;
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClear(GL_COLOR_BUFFER_BIT );//| GL_DEPTH_BUFFER_BIT);
glScalef(zoom,zoom,zoom);
if(zoom!=1)
glTranslatef(panx,0,0);
glTranslatef(-5.55,-2.88,-5.0);
background_image();
if(flow == 0)
intro();
else if(flow == 1)
level1();
else if(flow == 2)
congo();
else if(flow == 3)
level2();
else if(flow >= 4)
cannon();
if(start_projectile == 1)
{
if((b.ux < 0.00032 && b.uy < 0.000250) || b.x > 12 || b.x<0)
{
b.ux = 0;
b.uy = 0;
b.vy = 0;
b.y = 1.23;
reload_cannon();
}
else if(b.y <= 1.25)
{
start_time = glutGet(GLUT_ELAPSED_TIME);
b.x0 = b.x;
b.y0 = 1.25;
b.uy = -b.vy;
b.uy *= COR;
b.ux *= 0.8;
}
}
glutSwapBuffers();
}
void reshape (int width, int height) {
//Following command decides how much part of window to be used for rendering.
glViewport(0, 0, (GLsizei)width, (GLsizei)height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60, (GLfloat)width / (GLfloat)height, 1.0, 100.0);
glMatrixMode(GL_MODELVIEW);
}
void keyboard (unsigned char key, int, int) {
if((int)key == 27)
exit(0);
else if(key == 'a')
c.theta++;
else if(key == 'b')
c.theta--;
else if(key == 'f' && start_projectile == 0 && b.u < 0.0076)
{
b.u += 0.0002;
s.x2 += 0.05;
}
else if(key == 's' && start_projectile == 0 && b.u > 0.0032)
{
b.u -= 0.0002;
s.x2 -= 0.05;
}
else if(key ==' ')
{
if(start_projectile == 0)
{
start_projectile = 1;
start_time = glutGet(GLUT_ELAPSED_TIME);
}
}
else if(key == 'z'){
zoom+=0.5;
}
else if(key == 'x'){
if(zoom>1)
zoom-=0.5;
}
else if(key == 'c'){
panx++;
}
else if(key == 'v'){
panx--;
}
else if(key == 'n' && lock==0)
{
lock = 1;
flow++;
}
}
void mouse (int button, int state, int mx, int my)
{
if (state == GLUT_DOWN)
{
if (button == GLUT_LEFT_BUTTON)
{
if(start_projectile == 0)
{
if(b.u >= 0.0076 || b.u <= 0.0032)
{
del = -del;
delsx = -delsx;
}
b.u += del;
s.x2 += delsx;
}
}
else if (button == GLUT_RIGHT_BUTTON)
{
if(start_projectile == 0)
{
start_projectile = 1;
start_time = glutGet(GLUT_ELAPSED_TIME);
}
}
}
}
void mouse_passive(int x, int y)
{
y = 1000-y;
x = x-51;
y = y-216;
if(x>0 && y>0)
c.theta = (atan(y/x))*(180/pi);
printf("%f\n",c.theta);
}
int main (int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB );//| GLUT_DEPTH);
glutInitWindowSize (1920, 1000);
glutInitWindowPosition (0, 0);
glutCreateWindow ("GAmE.cpp");
initRendering();
glutDisplayFunc(display);
glutIdleFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutMouseFunc (mouse);
glutPassiveMotionFunc(mouse_passive);
glutMainLoop();
return 0;
}
|
#include "days.hpp"
#include <range/v3/all.hpp>
#include <map>
#include "lexical_cast.hpp"
enum class field {
byr,// (Birth Year)
iyr,// (Issue Year)
eyr,// (Expiration Year)
hgt,// (Height)
hcl,// (Hair Color)
ecl,// (Eye Color)
pid,// (Passport ID)
cid,// (Country ID)
num
};
static constexpr std::array<std::string_view, static_cast<size_t>(field::num)>
field_names{ "byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", "cid" };
using passport = std::map<field, std::string>;
std::vector<passport> parse_day(std::istream &input)
{
std::vector<passport> passports;
auto const r = std::regex("([a-z]{3}):([#0-9a-z]+)");
passport p;
for (std::string line; std::getline(input, line);) {
if (line.empty()) {
passports.push_back(p);
p = passport();
continue;
}
const int sub_matches[] = { 1, 2 };
std::regex_token_iterator<std::string::iterator> a(
line.begin(), line.end(), r, sub_matches);
std::regex_token_iterator<std::string::iterator> rend;
while (a != rend) {
auto found =
std::find(field_names.begin(), field_names.end(), (a++)->str());
auto const f =
static_cast<field>(std::distance(field_names.begin(), found));
p[f] = (a++)->str();
}
}
passports.push_back(p);
return passports;
}
auto is_in_range(std::string const &s, int min, int max) -> bool
{
if (const auto i = utils::try_lexical_cast<int>(s)) {
if (*i >= min && *i <= max) return true;
}
return false;
}
template<>
auto days::solve<days::day::day_4, days::part::part_1>(std::istream &input)
-> std::string
{
auto const candidates = parse_day(input);
auto const filtered =
candidates | ranges::views::filter([](passport const c) {
if (c.size() == static_cast<int>(field::num)
|| (c.size() == static_cast<int>(field::num) - 1
&& c.find(field::cid) == c.end())) {
return true;
}
return false;
})
| ranges::to<std::vector>;
return std::to_string(filtered.size());
}
template<>
auto days::solve<days::day::day_4, days::part::part_2>(std::istream &input)
-> std::string
{
auto const candidates = parse_day(input);
auto const filtered =
candidates | ranges::views::filter([](passport const c) {
if (c.size() == static_cast<int>(field::num)
|| (c.size() == static_cast<int>(field::num) - 1
&& c.find(field::cid) == c.end())) {
for (size_t n = 0; n < static_cast<size_t>(field::num); ++n) {
auto const f = static_cast<field>(n);
if (f == field::cid) continue;
auto const s = c.find(f)->second;
switch (f) {
case field::byr:
if (!is_in_range(s, 1920, 2002)) { return false; }
break;
case field::iyr:
if (!is_in_range(s, 2010, 2020)) { return false; }
break;
case field::eyr:
if (!is_in_range(s, 2020, 2030)) { return false; }
break;
case field::hgt: {
if (s.size() < 4) return false;
auto const unit = s.substr(s.size() - 2, 2);
auto const num = s.substr(0, s.size() - 2);
if (unit == "cm") {
if (!is_in_range(num, 150, 193)) { return false; }
} else if (unit == "in") {
if (!is_in_range(num, 59, 76)) { return false; }
} else {
return false;
}
} break;
case field::hcl:
if (s.size() != 7) return false;
if (s[0] != '#') return false;
if (s.find_first_not_of("0123456789abcdef", 1) != std::string::npos)
return false;
break;
case field::ecl: {
static constexpr std::array<std::string_view, 7> colors{
"amb", "blu", "brn", "gry", "grn", "hzl", "oth"
};
auto found = ranges::find(colors, s);
if (found == colors.end()) return false;
break;
}
case field::pid:
if (s.size() != 9) return false;
if (s.find_first_not_of("0123456789") != std::string::npos)
return false;
break;
case field::cid:
default:
break;
}
}
return true;
}
return false;
})
| ranges::to<std::vector>;
return std::to_string(filtered.size());
}
|
#include "Command_Configure.h"
ConfigureSaveLocationCommand::ConfigureSaveLocationCommand(std::string savePath) : Command(CommandTokens::PrimaryCommandType::Configure) {
_newSavePath = savePath;
}
UIFeedback ConfigureSaveLocationCommand::execute(RunTimeStorage* runTimeStorage) {
checkIsValidForExecute(runTimeStorage);
_oldSavePath = runTimeStorage->getFilePath();
try {
runTimeStorage->configureSaveLocation(_newSavePath);
} catch (INVALID_PATH_EXCEPTION e) {
throw COMMAND_EXECUTION_EXCEPTION(e.what());
} catch (INVALID_FILE_EXCEPTION e) {
throw COMMAND_EXECUTION_EXCEPTION(e.what());
}
postExecutionAction(runTimeStorage);
char buffer[255];
sprintf_s(buffer, MESSAGE_CONFIG_SAVE_PATH_SUCCESS.c_str(), _newSavePath.c_str());
return UIFeedback(runTimeStorage->getTasksToDisplay(), buffer);
}
UIFeedback ConfigureSaveLocationCommand::undo() {
checkIsValidForUndo();
_runTimeStorageExecuted->configureSaveLocation(_oldSavePath);
std::vector<Task> tasksToDisplay = _runTimeStorageExecuted->getTasksToDisplay();
postUndoAction();
return UIFeedback(tasksToDisplay, MESSAGE_CONFIG_SAVE_PATH_UNDO);
}
bool ConfigureSaveLocationCommand::canUndo() {
return true;
}
ConfigureSaveLocationCommand::~ConfigureSaveLocationCommand(void)
{
}
|
#include "rcon.h"
Rcon::Rcon(const Server server, QObject* parent)
: Query(server.getIp(), server.getPort(), parent) {
rconPassword = server.getRconPassword();
}
void Rcon::setPassword(QByteArray password) {
rconPassword = password;
}
void Rcon::send(QByteArray command) {
command.prepend(" ")
.prepend(rconPassword)
.prepend("rcon ");
Query::send(command);
}
|
#include <iostream>
using namespace std;
int main()
{
double x = 12.213;
cout.precision(2);
cout << " By default: " << x << endl;
cout << " showpoint: " << showpoint << x << endl;
cout << " fixed: " << fixed << x << endl;
cout << " scientific: " << scientific << x << endl;
return 0;
}
|
#ifndef LINKGENERATOR_HPP_
#define LINKGENERATOR_HPP_
#include <QtCore>
#include "Settings.hpp"
#include "FlurryAnalytics.hpp"
const QString SHAHASH_NA("08d2e98e6754af941484848930ccbaddfefe13d6"); //"N/A", but SHA-1 hashed
/*!
* @class LinkGenerator
* @brief LinkGenerator class
* @details Handles link generation
* @author Thurask
* @date 2015
*/
class LinkGenerator: public QObject
{
Q_OBJECT
public:
LinkGenerator();
Settings settings;
FlurryAnalytics fa;
public Q_SLOTS:
QString returnLinks();
QString returnOsLinks();
QString returnCoreLinks();
QString returnCoreAndDebrickLinks();
QString returnRadioLinks();
void setExportUrls(const QString& swversion, const QString& hashedswversion, const QString& osversion,
const QString& radioversion);
private Q_SLOTS:
void setOsLinks(const QString& hashedswversion, const QString& osversion);
void setCoreLinks(const QString& hashedswversion, const QString& osversion);
void setRadioLinks(const QString& hashedswversion, const QString& osversion,
const QString& radioversion);
void generateBools();
private:
QString exporturls;
QString radiolinks;
QString oslinks;
QString corelinks;
bool verizon;
bool core;
bool qcom;
bool winchester;
bool passport;
bool jakarta;
bool china;
bool sdk;
bool lseries;
bool nseries;
bool aseries;
bool aquarius;
bool laguna;
};
#endif /* LINKGENERATOR_HPP_ */
|
/*
* LocDirectOTA.cpp
*
* Created on: Nov 1, 2019
* Author: annuar
*/
#include <LocDirectOTA.h>
#include <WebServer.h>
LocDirectOTA *iniDirectOTA;
TaskHandle_t loopDirectOTA= NULL;
WebServer server(80);
JsonHandler *jsonHandler;
String makeTwoDigits(int digits);
LocDirectOTA::LocDirectOTA(int core, int loopDelay, int *lookVal)
{
iniDirectOTA = this;
iniDirectOTA->_lookVal = lookVal;
iniDirectOTA->_loopDelay = loopDelay;
iniDirectOTA->siniLocMando = NULL;
jsonHandler = new JsonHandler;
xTaskCreatePinnedToCore(iniDirectOTA->loop, "loopDirectOTA", 3072, NULL, 1, &loopDirectOTA, core);
}
void LocDirectOTA::loop(void* parameter) {
while(true){
if((WiFi.getMode() == WIFI_MODE_AP) || (WiFi.getMode() == WIFI_MODE_APSTA)){
if( !WiFi.softAPIP().toString().equals("0.0.0.0")){
break;
}
}
log_i("NO AP");
delay(iniDirectOTA->_loopDelay);
}
MDNS.begin("nine");
server.on("/stat", WebServer::THandlerFunction(iniDirectOTA->_StatusViaWiFi));
server.on("/adTech", WebServer::THandlerFunction(iniDirectOTA->_adTech));
server.on("/reboot", HTTP_GET, WebServer::THandlerFunction([]() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", "done");
delay(1000);
ESP.restart();
}));
server.on("/clearfs", WebServer::THandlerFunction([]() {
iniDirectOTA->_clearFile();
iniDirectOTA->_adTech();
}));
server.on("/config", WebServer::THandlerFunction(iniDirectOTA->_handleConfDDMS));
server.on("/ota", HTTP_GET, WebServer::THandlerFunction([]() {
server.sendHeader("Connection", "close");
server.send(200, "text/html", ota);}));
server.on("/update", HTTP_POST, WebServer::THandlerFunction([]() {
server.sendHeader("Connection", "close");
server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
delay(1000);
ESP.restart();}),
WebServer::THandlerFunction([]() {
HTTPUpload& upload = server.upload();
if (upload.status == UPLOAD_FILE_START) {
Serial.printf("Update: %s\n", upload.filename.c_str());
if (!Update.begin(UPDATE_SIZE_UNKNOWN,U_FLASH,2,1)) { //start with max available size
Update.printError(Serial);
}
}
else if (upload.status == UPLOAD_FILE_WRITE) {
/* flashing firmware to ESP*/
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
Update.printError(Serial);
}
}
else if (upload.status == UPLOAD_FILE_END) {
if (Update.end(true)) { //true to set the size to the current progress
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
}
else {
Update.printError(Serial);
}
}
}));
server.begin();
while(true){
server.handleClient();
delay(iniDirectOTA->_loopDelay);
}
}
void LocDirectOTA::_handleConfDDMS()
{
String msg = inputB;
if (server.args()==0) {
msg.replace("[minn]", "66655");
msg.replace("[maxx]", "33333");
msg.replace("[note]", "");
}
else {
if (server.arg(0)==0 || server.arg(1)==0) {
msg.replace("[minn]", server.arg(0));
msg.replace("[maxx]", server.arg(1));
msg.replace("[note]", "please fill in the blank(s)");
}
else {
msg.replace("[minn]", server.arg(0));
msg.replace("[maxx]", server.arg(1));
msg.replace("[note]", "Saved");
}
}
server.send(200, "text/html", msg);
}
void LocDirectOTA::_StatusViaWiFi(void) {
String msg="";
String timenow = makeTwoDigits(hour())+":"+makeTwoDigits(minute())+":"+makeTwoDigits(second());
long rssi = WiFi.RSSI();
msg = "MAC = " + iniDirectOTA->getMAC() + "</br>";
msg += "IP = " + WiFi.localIP().toString() + "</br>";
msg += "Live = " + String(millis()/1000) + "</br>";
msg += "Time = " + timenow + "</br>";
msg += "RSSI = " + String(rssi) + "</br>";
msg += "<hr>";
msg += iniDirectOTA->siniLocMando->dapatMandoText;
iniDirectOTA->siniLocMando->dapatMandoText = "";
server.sendHeader("Connection", "close");
server.send(200, "text/html", msg);
delay(50);
}
bool LocDirectOTA::_adTech() {
LocSpiff *locSpiff;
locSpiff = new LocSpiff("_adTech");
String msg = inputA;
if (server.args()==0) {
msg.replace("[note]", "");
msg.replace("[mID]", jsonHandler->mID);
msg.replace("[mac]", iniDirectOTA->getMAC());
}
else {
if (server.argName(0) == "clear") {
// spiffsHandler->mulaFiles(true);
locSpiff->mulaFiles(true);
msg.replace("[mac]", iniDirectOTA->getMAC());
msg.replace("[note]", "FS Cleared");
msg.replace("[mID]", jsonHandler->mID);
} else if (server.arg(0).length() < 6) {
msg.replace("[mac]", iniDirectOTA->getMAC());
msg.replace("[note]", "Require 6 digit alphanumeric id");
msg.replace("[mID]", server.arg(0));
}
else {
// spiffsHandler->writeToSpiffs("m", server.arg(0));
locSpiff->writeFile("/m", server.arg(0).c_str());
jsonHandler->mID = server.arg(0);
msg.replace("[mac]", iniDirectOTA->getMAC());
msg.replace("[note]", "Configuration sent.");
msg.replace("[mID]", server.arg(0));
}
}
delete locSpiff;
server.send(200, "text/html", msg);
return true;
}
void LocDirectOTA::_clearFile() {
LocSpiff *locSpiff;
locSpiff = new LocSpiff("_clearFile");
locSpiff->mulaFiles(true);
delete locSpiff;
}
String LocDirectOTA::getMAC() {
uint8_t mac[6];
WiFi.macAddress(mac);
String macID = "";
uint8_t num;
for(int i=0; i < 5; i++){
num = mac[i];
if(num < 16) macID += "0";
macID += String(mac[i], HEX) + ":";
}
macID += String(mac[5], HEX);
macID.toUpperCase();
return macID;
}
inline String makeTwoDigits(int digits)
{
if(digits < 10) {
String i = '0'+String(digits);
return i;
}
else {
return String(digits);
}
}
|
#include <iostream>
#include <vector>
using namespace std;
class Inimigo{
public:
Inimigo(){}
virtual void getTipo() = 0;
//...
};
class Carteiro : public Inimigo{
private:
public:
Carteiro(){}
virtual void getTipo(){cout << "Carteiro" << endl;}
//...
};
class Lixeiro : public Inimigo{
public:
Lixeiro(){}
virtual void getTipo(){cout << "Lixeiro" << endl;}
};
class Veterinario : public Inimigo{
public:
Veterinario(){}
virtual void getTipo(){cout << "Veterinário" << endl;}
};
class Fabrica{
public:
virtual Inimigo* criarInimigo() = 0;
};
template <class TipoInimigo>
class FabricaInimigo : public Fabrica{
public:
virtual Inimigo* criarInimigo();
};
template <class TipoInimigo>
Inimigo* FabricaInimigo<TipoInimigo>::criarInimigo(){
return new TipoInimigo;
}
FabricaInimigo<Carteiro> FabricaCarteiro;
FabricaInimigo<Lixeiro> FabricaLixeiro;
FabricaInimigo<Veterinario> FabricaVeterinario;
int main()
{
vector<Inimigo*> LI;
int choice = 1;
while (choice != 0)
{
cout << "Carteiro(1), Lixeiro(2), Veterinário(3), Listar inimigos(0): ";
cin >> choice;
switch(choice){
case 0:
break;
case 1:
LI.push_back(FabricaCarteiro.criarInimigo());
break;
case 2:
LI.push_back(FabricaLixeiro.criarInimigo());
break;
case 3:
LI.push_back(FabricaVeterinario.criarInimigo());
break;
default:
break;
}
}
for (int i = 0; i < LI.size(); i++)
LI[i]->getTipo();
for(int i = 0; i < LI.size(); i++)
delete LI[i];
}
|
//CtrlAKey.cpp
#include "CtrlAKey.h"
#include "MemoForm.h"
#include "PageForm.h"
#include "Memo.h"
#include "Line.h"
#include "Caret.h"
CtrlAKey::CtrlAKey(Form *form)
:KeyAction(form) {
}
CtrlAKey::CtrlAKey(const CtrlAKey& source)
: KeyAction(source) {
}
CtrlAKey::~CtrlAKey() {
}
CtrlAKey& CtrlAKey::operator=(const CtrlAKey& source) {
KeyAction::operator=(source);
return *this;
}
#include "SelectedBuffer.h"
void CtrlAKey::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) {
MemoForm *memoForm = static_cast<MemoForm*>(this->form);
memoForm->SetIsCaption(false);
memoForm->SetFocusType(MEMOFORM_FOCUS_CLIENT);
memoForm->GetSelectedBuffer()->SetInitialPosition(0, 0);
//자료구조 끝 계산
Long endRow;
Long endColumn;
endRow = static_cast<Memo*>(memoForm->GetContents())->GetLength() - 1;
endColumn = static_cast<Memo*>(memoForm->GetContents())->GetLine(endRow)->GetLength();
//영역 복사해서 buffer에 저장
memoForm->GetSelectedBuffer()->CopyToBuffer(endRow, endColumn);
//영역체크 유효화(선택보여주기)
memoForm->GetSelectedBuffer()->SetIsSelecting(true);
memoForm->RedrawWindow(NULL, NULL, RDW_INVALIDATE | RDW_NOERASE);
static_cast<Memo*>(memoForm->GetContents())->SetRow(endRow);
static_cast<Line*>(static_cast<Memo*>(memoForm->GetContents())->GetLine(endRow))->SetColumn(endColumn);
memoForm->GetCaret()->UpdateCaret();
}
|
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char* argv[]) {
ifstream htmlFile;
//string hilera = getenv("HTTP_COOKIE");
string line = "";
// Insertar header en el body
htmlFile.open("../html/headerInsert.html");
if(!htmlFile.is_open()) {
cout << "Content-Type:text/html\n";
cout << "<TITLE>Failure</TITLE>\n";
cout << "<P><EM>Unable to open data file, sorry!</EM>\n";
}
else {
cout << "Set-Cookie:estadoUsuario = NoRegistrado;\r\n";
cout << "Set-Cookie:correo = nulo;\r\n";
cout << "Set-Cookie:total = 0;\r\n";
cout << "Set-Cookie:articulo = vacio;\r\n";
cout << "Content-Type: text/html\n\n";
while(getline(htmlFile, line)){
if(line.find("fa-shopping-cart") == string::npos){
cout << line << "\n";
}
else{
if(line.find("fa-shopping-cart") != string::npos){
int a = 10;
}
}
}
htmlFile.close();
// Insertar contenido en el body
htmlFile.open("../html/loginRegistro.html");
if(!htmlFile.is_open()) {
cout << "<TITLE>Failure</TITLE>\n";
cout << "<P><EM>Unable to open data file, sorry!</EM>\n";
}
else {
line = "";
while(getline(htmlFile, line)){
cout << line +"\n";
}
htmlFile.close();
// Insertar footer en el body
htmlFile.open("../html/footerInsert.html");
if(!htmlFile.is_open()) {
cout << "<TITLE>Failure</TITLE>\n";
cout << "<P><EM>Unable to open data file, sorry!</EM>\n";
}
else {
line = "";
while(getline(htmlFile, line)){
cout << line +"\n";
}
htmlFile.close();
}
}
}
return 0;
}
|
/**
* $Source: /backup/cvsroot/project/pnids/zdk/zls/zvm/CZVMFunction.cpp,v $
*
* $Date: 2001/11/14 18:29:37 $
*
* $Revision: 1.3 $
*
* $Name: $
*
* $Author: zls $
*
* Copyright(C) since 1998 by Albert Zheng - 郑立松, All Rights Reserved.
*
* lisong.zheng@gmail.com
*
* $State: Exp $
*/
#include <zls/zvm/CZVMFunction.hpp>
#include <zls/zvm/CZVMObjectFile.hpp>
#include <zls/zvm/CInstruction.hpp>
ZLS_BEGIN_NAMESPACE(zvm)
void CZVMFunction::DoCache()
{
_pciConstantPool = &(_pciOwnerObjectFile->GetConstantPool());
const zvm::CGlobalFunctionReference * pciFunctionReference =
_pciConstantPool->GetAsGlobalFunctionReference(_iFunctionReference);
//< May throw zfc::EOutOfRange
// 先预解析name and signature reference
_pciNameAndSignatureReference = pciFunctionReference->GetNameAndSignatureReference();
}
CZVMFunction::CZVMFunction(const CZVMObjectFile * pciObjectFile,
zfc::CBinaryInputFileStream & bis)
: _pciOwnerObjectFile(pciObjectFile),
_pciConstantPool(0),
_pciNameAndSignatureReference(0),
_bDebugInfoStriped(false),
_iFunctionReference(0),
_uwParameterCount(0),
_uwLocalVariableCount(0)
{
bis >> *this;
// 预解析name and signature reference
DoCache();
}
CZVMFunction::~CZVMFunction()
{
delete [] _aciInstructionSequence;
}
void CZVMFunction::StripDebugInfo()
{
_vectorLineNumberDebugInfo.clear();
_vectorStackVariableDebugInfo.clear();
_bDebugInfoStriped = true;
}
TZVMIndex CZVMFunction::InstructionToLineNumber(const CInstruction * pciInstruction) const
{
// 计算这条指令的Index
TZVMIndex iInstruction = pciInstruction - _aciInstructionSequence;
return InstructionIndexToLineNumber(iInstruction);
}
TZVMIndex CZVMFunction::InstructionIndexToLineNumber(TZVMIndex iInstruction) const
{
static const char * __PRETTY_FUNC__ = ZLS_PRETTY_FUNCTION("CZVMFunction::InstructionIndexToLineNumber()");
if (_bDebugInfoStriped)
{
std::string stringError = "Sorry, But debug info had been striped";
throw zfc::EInvalidState(__FILE__, __PRETTY_FUNC__, __LINE__, stringError);
}
std::vector<TLineNumberDebug>::const_iterator it;
for (it = _vectorLineNumberDebugInfo.begin();
it != _vectorLineNumberDebugInfo.end();
++it)
{
if ((*it).iFromWhichInstructionStart > iInstruction)
{
if (it != _vectorLineNumberDebugInfo.begin())
{
return (*(--it)).iLineNumber;
}
else
{
return 0;
}
}
}
if (_vectorLineNumberDebugInfo.size() > 0)
{
return _vectorLineNumberDebugInfo.back().iLineNumber;
}
else
{
return 0;
}
}
void CZVMFunction::VerifyByteCodesIntegrity() const
{
static const char * __PRETTY_FUNC__ = ZLS_PRETTY_FUNCTION("CZVMFunction::VerifyByteCodesIntegrity()");
for (TZVMIndex nIndex = 0; nIndex < _nInstructionSequenceCapacity; ++nIndex)
{
try {
_aciInstructionSequence[nIndex].VerifyByteCodesIntegrity(*_pciConstantPool,
nIndex,
_nInstructionSequenceCapacity - 1);
}
catch (zvm::EVerifyFailure & e)
{
std::string stringError = std::string("Verifing function integrity stopped at the ") + nIndex + " instruction";
stringError += " of '";
stringError += FunctionNameAndSignatureToPrettyString(_pciNameAndSignatureReference->GetName(),
_pciNameAndSignatureReference->GetSignature());
stringError += "'";
e.AppendWhat(__FILE__, __PRETTY_FUNC__, __LINE__, stringError);
throw;
}
}
}
void CZVMFunction::DumpDetail() const
{
static const char * __PRETTY_FUNC__ = ZLS_PRETTY_FUNCTION("CZVMFunction::DumpDetail()");
std::cout << " >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" << std::endl;
std::cout << " function name: " << _pciNameAndSignatureReference->GetName() << std::endl;
std::cout << " function reference: " << _iFunctionReference << std::endl;
std::cout << " parameter count: " << _uwParameterCount << std::endl;
std::cout << " local variable count: " << _uwLocalVariableCount << std::endl;
std::cout << " instruction sequence: " << std::endl;
for (TZVMIndex nIndex = 0; nIndex < _nInstructionSequenceCapacity; ++nIndex)
{
std::cout << " " << nIndex << ": ";
#ifndef NDEBUG
try {
#endif
_aciInstructionSequence[nIndex].DumpDetail();
#ifndef NDEBUG
}
catch(zfc::EPanic & e)
{
std::string stringError = std::string("Dump stopped at the ") + nIndex + " instruction";
e.AppendWhat(__FILE__, __PRETTY_FUNC__, __LINE__, stringError);
throw;
}
#endif
}
std::cout << " <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" << std::endl << std::endl;
}
zfc::CBinaryInputFileStream & operator>>(zfc::CBinaryInputFileStream & bis, CZVMFunction::TLineNumberDebug & rsi)
{
bis >> rsi.iFromWhichInstructionStart >> rsi.iLineNumber;
return bis;
}
zfc::CBinaryInputFileStream & operator >> (zfc::CBinaryInputFileStream & bis, CZVMFunction::TStackVariableDebug & rsi)
{
bis >> rsi.iNameAndSignatureReference >> rsi.iBPOffset;
return bis;
}
zfc::CBinaryInputFileStream & operator>>(zfc::CBinaryInputFileStream & bis, CZVMFunction & rci)
{
static const char * __PRETTY_FUNC__ = ZLS_PRETTY_FUNCTION("operator>>(zfc::CBinaryInputFileStream &, CZVMFunction &)");
// 读入最前面的三个字段
bis >> rci._iFunctionReference >> rci._uwParameterCount >> rci._uwLocalVariableCount;
///> 读入各条指令
TZVMIndex nCapacity;
bis >> nCapacity;
rci._nInstructionSequenceCapacity = nCapacity; // instruction sequence capacity
rci._aciInstructionSequence = new __OPTION(_THROW) zvm::CInstruction[nCapacity];
memset(rci._aciInstructionSequence, '\0', sizeof(zvm::CInstruction) * nCapacity);
for (TZVMIndex nIndex = 0; nIndex < nCapacity; ++nIndex)
{
try {
bis >> rci._aciInstructionSequence[nIndex];
}
catch(zvm::EInvalidObjectFile & e)
{
std::string stringError = std::string("Read function stopped at the ") + nIndex + " instruction";
e.AppendWhat(__FILE__, __PRETTY_FUNC__, __LINE__, stringError);
throw;
}
}
///> 读入Line跟踪信息
bis >> nCapacity;
while (nCapacity > 0)
{
CZVMFunction::TLineNumberDebug siDebug;
bis >> siDebug;
rci._vectorLineNumberDebugInfo.push_back(siDebug);
--nCapacity;
}
///> 读入Stack variable跟踪信息
bis >> nCapacity;
while (nCapacity > 0)
{
CZVMFunction::TStackVariableDebug siDebug;
bis >> siDebug;
rci._vectorStackVariableDebugInfo.push_back(siDebug);
--nCapacity;
}
return bis;
}
ZLS_END_NAMESPACE
|
#include<bits/stdc++.h>
using namespace std;
int res;
void getRes(vector<int> data, int starts, int mid, int ends)
{
vector<int> temp(ends-starts+1);
int i = starts;
int j = mid + 1;
int k = 0;
while(i <= mid && j <= ends) {
if(data[i] <= data[j]) {
temp[k++] = data[i++];
}
else {
temp[k++] = data[j++];
res = (res + mid - i + 1) % 1000000007;
}
}
while(i <= mid) {
temp[k++] = data[i++];
}
while(j <= ends) {
temp[k++] = data[j++];
}
for(k = 0; k < temp.size(); k++)
data[starts + k] = temp[k];
}
void twoSort(vector<int> data, int starts, int ends)
{
if(starts >= ends)
return;
int mid = (starts + ends) / 2;
twoSort(data,starts,mid);
twoSort(data,mid+1,ends);
getRes(data, starts, mid, ends);
}
int InversePairs(vector<int> data) {
int n = data.size();
res = 0;
if(n != 0)
twoSort(data,0,n-1);
return res;
}
int main()
{
int n,m,t;
cin >> n;
while(n--) {
cin >> m;
vector<int> data;
for(int i = 0; i < m; i++) {
cin >> t;
data.push_back(t);
}
cout << InversePairs(data) << endl;
}
return 0;
}
|
// 飞机问题.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<algorithm>
using namespace std;
int t[400000];
int d[400000];
int main()
{
int n,s,i,j,len,temp;
while(cin>>n>>s)
{
for(i=0;i<n;i++)
{cin>>t[i];}
sort(t,t+n);//排序
for(i=0,j=1;i<n;i++)//除去重复元素
{ if(i==0)
{
d[j]=t[i];
j++;}
else
{
if(t[i]!=t[i-1])
{d[j]=t[i];j++;}
}
}
len=j;
t[1]=s+d[1]*d[1];
for(i=2;i<len;i++)//t[i]表示机场i到中心机场的最小费用,则有递推式:t[i]=min{s+d[i]^2,s+(d[j]-d[i])^2+t[j]}(1<=j<i)
{
t[i]=s+d[i]*d[i];
for(j=1;j<i;j++)
{
temp=s+(d[i]-d[j])*(d[i]-d[j])+t[j];
if(temp<t[i])
t[i]=temp;
}
}
cout<<t[len-1]<<endl;
}
return 0;
}
|
#ifndef __FILE_CHOOSER_H
#define __FILE_CHOOSER_H
#include<gtkmm.h>
class Filechooser: public Gtk::Window{
public:
Filechooser();
virtual ~Filechooser();
protected:
void on_button_file_clicked();
void on_button_folder_clicked();
Gtk::ButtonBox button_box;
Gtk::Button file_button, folder_button;
};
#endif
|
//
// Copyright (C) 2018 Ruslan Manaev (manavrion@yandex.com)
// This file is part of the Modern Expert System
//
#pragma once
namespace uwp_app {
public ref class ProjectContext sealed {
public:
ProjectContext(Windows::UI::Xaml::Controls::TextBlock^ HeaderTextBlock,
Windows::UI::Xaml::Controls::CommandBar^ HeaderCommandBar);
internal:
Windows::UI::Xaml::Controls::TextBlock^ HeaderTextBlock;
Windows::UI::Xaml::Controls::CommandBar^ HeaderCommandBar;
};
} // namespace uwp_app
|
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using vi = vector<int>;
#define pb push_back
#define rsz resize
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()
using pi = pair<int, int>;
#define f first
#define s second
#define mp make_pair
void setIO(string name = "lemonade") {
ios_base::sync_with_stdio(0); cin.tie(0);
if (sz(name)) {
freopen((name + ".in").c_str(), "r", stdin);
freopen((name + ".out").c_str(), "w", stdout);
}
}
int main() {
setIO();
int n; cin >> n;
vector<int> cows;
for (int i = 0; i < n; ++i) {
int cow; cin >> cow;
cows.pb(cow);
}
sort(all(cows), greater<int>());
int ans = 0;
for (int i = 0; i < n; ++i) {
if (i <= cows[i]) {
++ans;
}
}
cout << ans << endl;
}
|
#pragma once
#include <algorithm>
#include <limits>
#include <map>
#include <numeric>
#include <Eigen/Eigen>
#include "corpus.hpp"
#include "MarkovTagger.hpp"
#include "UnigramTagger.hpp"
using std::make_pair;
using std::map;
using std::string;
using std::vector;
using Eigen::MatrixXi;
using Eigen::MatrixXd;
using Eigen::VectorXd;
class HMMTagger : public MarkovTagger {
public:
UnigramTagger::tagcount_t wordTagCounts;
typedef map<string, VectorXd> wordtagprob_t;
wordtagprob_t wordTagProbs; // in log-space
public:
double getEmitLogProb(const string& word, int state) const {
string loweredWord(word.size(), '\0');
std::transform(word.begin(), word.end(),
loweredWord.begin(), (int (*)(int))std::tolower);
wordtagprob_t::const_iterator i = wordTagProbs.find(loweredWord);
if (i == wordTagProbs.end())
i = wordTagProbs.find("");
const VectorXd& probs = i->second;
assert(state >= 0);
assert(state < probs.size());
return probs[state];
}
void invertWordProbability() {
// We now have Prob(Tag|Word). We want Prob(Word|Tag).
// We can do this via Bayes' rule, a simple derivation from the definition
// of conditional probability. Prob(Tag|Word)=Prob(Tag & Word)/Prob(Word).
// Prob(Word|Tag)=Prob(Tag & Word)/Prob(Tag). Therefore,
// Prob(Word|Tag)=Prob(Tag|Word)*Prob(Word)/Prob(Tag).
// We have marginal tag counts in the word "".
// We can compute marginal word probabilities by summing word counts.
// number of pseudo-seen tags (not in training) of each type for each word
double tag_pseudocount = 0.5;
// number of pseudo-seen words not in training
double word_pseudocount = 2;
VectorXi marginalCounts = wordTagCounts[""];
assert(marginalCounts.size() > 0);
double total_obs = std::accumulate(&marginalCounts[0],
&marginalCounts[0]+marginalCounts.size(),
0);
total_obs += tag_pseudocount * marginalCounts.size() *
(wordTagCounts.size()-1+word_pseudocount);
VectorXd marginalTagProb((marginalCounts.cast<double>().array()
+ tag_pseudocount * (wordTagCounts.size()-1+
word_pseudocount)).log() -
log(total_obs));
for (size_t i = 0; i < marginalTagProb.size(); i++) {
assert(marginalTagProb(i) <= 0);
}
for (const pair<string, VectorXi>& wordCount : wordTagCounts) {
double word_obs = std::accumulate(&wordCount.second[0],
&wordCount.second[0]+
wordCount.second.size(), 0);
word_obs += tag_pseudocount * wordCount.second.size();
// P(word) = word_obs / total_obs
// P(tag|word) = Count(tag|word)/word_obs
// P(tag|word)*P(word) = Count(tag|word) / total_obs
VectorXd thisWordTagProb((wordCount.second.cast<double>().array()
+ tag_pseudocount).log()
- log(total_obs));
thisWordTagProb -= marginalTagProb;
wordTagProbs[wordCount.first] = thisWordTagProb;
for (size_t i = 0; i < thisWordTagProb.size(); i++) {
assert(thisWordTagProb(i) <= 0);
}
}
}
HMMTagger() : MarkovTagger() {}
HMMTagger(const TagLibrary& taglib) : MarkovTagger(taglib) {}
HMMTagger(const Corpus& corpus) : MarkovTagger(corpus.taglib) {
initCounts(tagcounts, taglib.size()+2);
tagprobs = tagprobs.Zero(taglib.size()+2,
taglib.size()+2);
UnigramTagger::newvec(wordTagCounts, "", taglib.size()); // for all words
// Apply Laplace smoothing, to account for out-of-vocabulary words.
VectorXi& nullCounts = wordTagCounts[""];
nullCounts = VectorXi::Constant(nullCounts.size(), 1);
for (shared_ptr<Sentence> sentence : corpus.sentences) {
updateSentenceCounts(tagcounts, *sentence);
UnigramTagger::updateSentenceCounts(wordTagCounts, *sentence);
}
countsToProbs(tagprobs, tagcounts);
invertWordProbability();
}
virtual ~HMMTagger() {}
virtual void tag(vector<pair<int, string> >& words) const {
MatrixXd viterbi(MatrixXd::Constant(tagprobs.cols()-1, words.size()+1,
-std::numeric_limits<double>::infinity()
));
MatrixXi backpointer(MatrixXi::Zero(tagprobs.cols()-1, words.size()));
for (size_t statenum = 0; statenum < tagprobs.cols()-1; statenum++) {
viterbi(statenum, 0) = log(tagprobs(statenum+1, 0));
assert(viterbi(statenum, 0) <= 0);
// For ease of iteration, apply emission probabilities only in
// update step.
}
int t = 0;
for (pair<int, string> word : words) {
// We already looked at the initial time above, which is the
// only time that can have the initial state, so laststate
// will always be something else.
// laststate goes to #cols - 2, since we ignore initial state here,
// and final state can't be a previous state, so don't compute it.
// We can transition *to* the final state, so we consider that in the
// statenum loop
for (size_t laststate = 0; laststate < tagprobs.cols() - 2; laststate++) {
double prev_viterbi = viterbi(laststate, t);
double logemitprob = getEmitLogProb(word.second, laststate);
if (prev_viterbi > 0) {
std::cerr << "Viterbi logprob > 0 at iteration " << t
<< "! Value " << prev_viterbi << std::endl;
throw 0;
}
if (logemitprob > 0) {
std::cerr << "Emission logprob > 0 at iteration " << t
<< "! Value " << logemitprob << std::endl;
throw 0;
}
for (size_t statenum = 0; statenum < tagprobs.cols()-1; statenum++) {
double logtransprob = log(tagprobs(statenum+1, laststate+1));
double thisval = prev_viterbi + logemitprob + logtransprob;
if (logtransprob > 0) {
std::cerr << "Transition logprob > 0 at iteration " << t
<< "! Value " << logtransprob << std::endl;
throw 0;
}
if (thisval > viterbi(statenum,t+1)) {
viterbi(statenum, t+1) = thisval;
backpointer(statenum, t) = laststate;
}
}
}
t++;
}
// Now produce backwords path
size_t last_state = tagprobs.cols() - 2;
while (--t >= 0) {
words[t].first = backpointer(last_state, t);
last_state = words[t].first;
assert(words[t].first >= 0);
assert(words[t].first < tagprobs.cols()-2);
}
}
};
|
#include "netlist.h"
netlist::~netlist()
{
list<gate *>::iterator iter = gates_.begin();
gates_.erase(iter, gates_.end());
map<string, net *>::iterator it = nets_.begin();
nets_.erase(it, nets_.end());
}
bool netlist::create(const evl_wires &wires, const evl_components &comps)
{
return create_nets(wires) && create_gates(comps);
}
string make_net_name(string wire_name, int i)
{
assert(i >= 0);
ostringstream oss;
oss << wire_name << "[" << i << "]";
return oss.str();
}
bool netlist::create_nets(const evl_wires &wires)
{
for (evl_wires::const_iterator it = wires.begin(); it != wires.end(); ++it)
{
if (it->second == 1)
{
create_net(it->first);
}
else
{
for (int i = 0; i < it->second; ++i)
{
create_net(make_net_name(it->first,i));
}
}
}
return true;
}
void netlist::create_net(string net_name)
{
assert(nets_.find(net_name) == nets_.end());
nets_[net_name] = new net(net_name);
}
net::net(string name)
{
net_name = name;
}
bool netlist::create_gates(const evl_components &comps)
{
for (evl_components::const_iterator iter = comps.begin(); iter != comps.end(); ++iter)
{
create_gate(*iter);
}
return true;
}
bool netlist::create_gate(const evl_component &c)
{
if (c.type == "dff")
{
gate *g = new flip_flop(c.name);
gates_.push_back(g);
}
else if (c.type == "and")
{
gates_.push_back(new and_gate(c.name));
}
else if (c.type == "or")
{
gates_.push_back(new and_gate(c.name));
}
else if (c.type == "xor")
{
gates_.push_back(new and_gate(c.name));
}
else if (c.type == "not")
{
gates_.push_back(new and_gate(c.name));
}
else if (c.type == "buf")
{
gates_.push_back(new and_gate(c.name));
}
else if (c.type == "one")
{
gates_.push_back(new and_gate(c.name));
}
else if (c.type == "zero")
{
gates_.push_back(new and_gate(c.name));
}
else if (c.type == "input")
{
gates_.push_back(new and_gate(c.name));
}
else if (c.type == "output")
{
gates_.push_back(new and_gate(c.name));
}
return gates_.back()->create(c, nets_);
}
bool pin::create(gate *g, size_t pin_index, const evl_pin &p, const map<string, net *> &netlist_nets)
{
this->gate_ = g;
this->pin_index_ = pin_index;
if (p.msb == -1) {
map<string, net *>::const_iterator it = netlist_nets.find(p.name);
if (it == netlist_nets.end())
{
cerr << "net '" << p.name << "' is not defined" << endl;
return false;
}
nets_.push_back(it->second);
(it->second)->append_pin(this, 0);
pin_size = 1;
}
else {
size_t net_index = 0;
for (int i = p.lsb; i <= p.msb; ++i, ++net_index) {
string net_name = make_net_name(p.name, i);
map<string, net *>::const_iterator it = netlist_nets.find(net_name);
if (it == netlist_nets.end())
{
cerr << "net '" << net_name << "' is not defined" << endl;
return false;
}
nets_.push_back(it->second);
nets_.back()->append_pin(this, net_index);
pin_size = net_index+1;
}
}
return true;
}
void net::append_pin(pin *p, size_t net_index)
{
connections_.push_back(make_pair(p, net_index));
}
bool parse_evl_file(std::string evl_file, evl_wires &wires, evl_components &comps)
{
// here you make an empty vector of type evl_token
evl_tokens tokens;
evl_statements statements;
// evl_file is the file name passed as an argument to the program; argv[0] is always the name of the program
if (!extract_line_from_File(evl_file, tokens))
{
return -1;
}
string inputfilename = evl_file;
if (!store_tokens_to_file(inputfilename, tokens))
{
return false;
}
if (!group_tokens_into_statements(statements, tokens))
{
return false;
}
evl_modules modules;
if (!process_module(modules, statements))
{
return false;
}
wires = modules.front().wires;
comps = modules.front().components;
store_module_to_file(inputfilename, modules);
return true;
}
void netlist::display_netlist(ostream &out)
{
out << nets_.size() << " " << gates_.size() << endl;
for (map<string, net *>::const_iterator it = nets_.begin(); it != nets_.end(); ++it)
{
out << "net " << it->first <<" "<< it->second->connections_.size() << endl;
for (list<pair<pin *, size_t> >::iterator iter = it->second->connections_.begin(); iter != it->second->connections_.end(); ++iter) {
out << "pin " << iter->first->get_gate_handle()->gate_type << " "<<iter->first->get_gate_handle()->gate_name << " " << iter->first->get_pin_index() << endl;
}
}
for (list<gate *>::const_iterator it1 = gates_.begin(); it1 != gates_.end(); ++it1)
{
out << "gate " << (*it1)->gate_type << " " << (*it1)->gate_name << " " << (*it1)->pins_.size() << endl;
for (size_t i = 0; i < (*it1)->pins_.size(); ++i)
{
out << "pin " << (*it1)->pins_[i]->get_nets().size() << " ";
for (size_t j = 0; j < (*it1)->pins_[i]->get_nets().size(); ++j) {
out << " "<<(*it1)->pins_[i]->get_nets()[j]->net_name;
}
out << endl;
}
}
}
const int pin::get_pin_index()
{
return pin_index_;
}
const gate* pin::get_gate_handle()
{
return gate_;
}
const vector<net *> pin::get_nets()
{
return nets_;
}
void netlist::save(string inputfilename)
{
ofstream outfile(inputfilename.c_str());
if (!outfile)
{
cerr << "This file cannot be written to!" << endl;
}
display_netlist(outfile);
}
|
#include <algorithm>
#include <exception>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "box_id.h"
#include "checksum.h"
std::vector<std::string> get_input_data(char const *const file_name);
BoxIdDiff find_correct_diff(std::vector<BoxId> const &box_ids);
struct BoxDiffNotFountException : public std::exception {
char const *what() const throw() {
return "Box ids with 1 character diff could not be found";
}
};
int main(int argc, char *argv[]) {
auto input_data = get_input_data(argv[1]);
std::vector<BoxId> box_ids;
CheckSum checksum{};
for (auto &str : input_data) {
box_ids.push_back(BoxId{str});
}
for (auto const &box_id : box_ids) {
checksum.add_id(box_id);
}
std::cout << "Checksum is: " << checksum.calculate() << '\n';
std::cout << "Diffed leftover is: " << find_correct_diff(box_ids) << '\n';
}
BoxIdDiff find_correct_diff(std::vector<BoxId> const &box_ids) {
for (std::size_t i = 0; i < box_ids.size(); i++) {
for (std::size_t j = i + 1; j < box_ids.size(); j++) {
BoxIdDiff diff = BoxIdDiff::from_box_ids(box_ids[i], box_ids[j]);
if (diff.get_diff_count() < 2) {
return diff;
}
}
}
throw BoxDiffNotFountException();
}
std::vector<std::string> get_input_data(char const *const file_name) {
std::ifstream ifs{file_name};
std::string tmp_str;
std::vector<std::string> result;
while (std::getline(ifs, tmp_str, '\n')) {
result.push_back(tmp_str);
}
return result;
}
|
// mal1007.cpp : Defines the entry point for the console application.
//The program is C++ implementation for DLL injection into a specified process of the windows system.
/*The program has been written for x64 version of the windows OS
++ The usage of the code is as follows: mal1007.exe 'dll_path' 'process PID'
++ The program displays a message associated with the dll included.
++ The program was referenced from the follwing links:
https://www.youtube.com/watch?v=IBwoVUR1gt8
https://www.youtube.com/watch?v=C2OtYr0EyOg&t=666s
*/
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
int main(int argc, char *argv[])
{
//path of the dll is taken from the arguments
LPCSTR dl_pa = argv[1];
HANDLE proc_name = OpenProcess(PROCESS_ALL_ACCESS, FALSE, atoi(argv[2])); // Open a handle to the process
LPVOID path_to_dll = VirtualAllocEx(proc_name, 0, strlen(dl_pa) + 1,MEM_COMMIT, PAGE_READWRITE); // Allocate memory for the dll
WriteProcessMemory(proc_name, path_to_dll, (LPVOID)dl_pa,strlen(dl_pa) + 1, 0); // Write the path to the address of the memory
HANDLE thread = CreateRemoteThread(proc_name, 0, 0,(LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandleA("Kernel32.dll"),
"LoadLibraryA"), path_to_dll, 0, 0); // Create a Remote Thread in the process for injection
WaitForSingleObject(thread, INFINITE);
std::cin.get();
// Free the memory allocated for our dll path
VirtualFreeEx(proc_name, path_to_dll, strlen(dl_pa) + 1, MEM_RELEASE);
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.