text
stringlengths 8
6.88M
|
|---|
//用递归来解决全排列问题
#include<cstdio>
const int maxn=11;//因为有0-9这十个数
int n,P[maxn],hashTable[maxn]={false};//P为当前排列,hashTable记录整数x是否已经在P中
void generateP(int index);
int main()
{
n=5;//输出3的全排列
generateP(1);//从1开始试探
return 0;
}
void generateP(int index)
{
if(index==n+1)//递归边界,说明1-n位已经排好
{
//输出已经排好的序列
for(int i=1;i<=n;i++)
printf("%d",P[i]);
//序列输出完整后打印一个空格
printf("\n");
return ;//递归结束
}
for(int x=1;x<=n;x++)//枚举1-n,试图将x填入P[index]
{
if(hashTable[x]==false)//说明x不在P中,可以填入
{
P[index]=x;//把x加入当前排列
hashTable[x]=true;//标记x已经在P中
generateP(index+1);//处理下一号位的数字
hashTable[x]=false;//已经处理完P[index]的子问题,还原状态,才可进行下一次尝试
}
}
}
|
double jackson(unsigned n, unsigned N);
Eigen::Array<TR, -1, -1> calc_dos(Eigen::Array<TR, -1, -1> mu, Eigen::Array<TR, -1, -1> energies, std::string mode);
void extended_euclidean(int a, int b, int *x, int *y, int *gcd);
class variables{
public:
double avg_time;
unsigned iter;
unsigned max_iter;
bool has_initialized;
bool has_finished;
unsigned Lx, Ly;
unsigned nx, ny;
unsigned nrandom, ndisorder, nmoments;
int mult, seed;
double anderson_W;
double conc;
std::string status;
variables(){
has_initialized = false;
has_finished = false;
status="";
}
void update_status(){
std::string init = "0";
std::string fin = "0";
if(has_initialized)
init = "1";
if(has_finished)
fin = "1";
//std::cout << "before string\n" << std::flush;
status = init + " " + fin + " running "
+ "Lx=" + std::to_string(Lx) + " "
+ "Ly=" + std::to_string(Ly) + " "
+ "nx=" + std::to_string(nx) + " "
+ "ny=" + std::to_string(ny) + " "
+ "NR=" + std::to_string(nrandom) + " "
+ "ND=" + std::to_string(ndisorder) + " "
+ "N=" + std::to_string(nmoments) + " "
+ "B=" + std::to_string(mult) + " "
+ "S=" + std::to_string(seed) + " "
+ "W=" + std::to_string(anderson_W) + " "
+ "C=" + std::to_string(conc) + " "
+ "i=" + std::to_string(iter) + " "
+ "M=" + std::to_string(max_iter) + " "
+ "T=" + std::to_string(avg_time);
};
void update_status(std::string custom){
status = custom;
}
};
struct parameters{
unsigned Lx, Ly;
unsigned nx, ny;
unsigned nrandom, ndisorder, nmoments;
int mult, seed;
double anderson_W;
double conc;
Eigen::Array<TR, -1, -1> energies;
unsigned NEnergies;
bool found_NEnergies;
bool found_energies;
bool output_energies;
bool need_write;
std::string saveto, readfrom;
bool need_moremoments;
unsigned moremoments;
bool need_read;
std::string filename_read;
std::string filename_write;
bool need_print_to_file, need_print_to_cout, need_print;
bool need_log_status;
std::string filename_status;
};
void parse_input(int argc, char **argv, parameters*);
void save(KPM_vector*, KPM_vector*);
void load(std::string, KPM_vector *, KPM_vector *, Eigen::Array<TR, -1, -1> *);
void print_ham_info(parameters P);
void print_cheb_info(parameters P);
void print_compilation_info();
void print_magnetic_info(parameters, int, int, int);
void print_output_info(parameters);
void print_restart_info(parameters);
void print_log_info(parameters);
void print_dos(parameters P, unsigned N_lists, unsigned *nmoments_list, Eigen::Array<TR, -1, -1> *dos);
|
#pragma once
#include <cstddef>
#include <cstring>
#include <string>
#include "CIL/xadd.h"
namespace cil {
class FileNode;
class String {
public:
typedef char value_type;
typedef char& reference;
typedef const char& const_reference;
typedef char* pointer;
typedef const char* const_pointer;
typedef ptrdiff_t difference_type;
typedef size_t size_type;
typedef char* iterator;
typedef const char* const_iterator;
static const size_t npos = size_t(-1);
explicit String();
String(const String& str);
String(const String& str, size_t pos, size_t len = npos);
String(const char* s);
String(const char* s, size_t n);
String(size_t n, char c);
String(const char* first, const char* last);
template <typename Iterator>
String(Iterator first, Iterator last);
explicit String(const FileNode& fn);
~String();
String& operator=(const String& str);
String& operator=(const char* s);
String& operator=(char c);
String& operator+=(const String& str);
String& operator+=(const char* s);
String& operator+=(char c);
size_t size() const;
size_t length() const;
char operator[](size_t idx) const;
char operator[](int idx) const;
const char* begin() const;
const char* end() const;
const char* c_str() const;
bool empty() const;
void clear();
int compare(const char* s) const;
int compare(const String& str) const;
void swap(String& str);
String substr(size_t pos = 0, size_t len = npos) const;
size_t find(const char* s, size_t pos, size_t n) const;
size_t find(char c, size_t pos = 0) const;
size_t find(const String& str, size_t pos = 0) const;
size_t find(const char* s, size_t pos = 0) const;
size_t rfind(const char* s, size_t pos, size_t n) const;
size_t rfind(char c, size_t pos = npos) const;
size_t rfind(const String& str, size_t pos = npos) const;
size_t rfind(const char* s, size_t pos = npos) const;
size_t find_first_of(const char* s, size_t pos, size_t n) const;
size_t find_first_of(char c, size_t pos = 0) const;
size_t find_first_of(const String& str, size_t pos = 0) const;
size_t find_first_of(const char* s, size_t pos = 0) const;
size_t find_last_of(const char* s, size_t pos, size_t n) const;
size_t find_last_of(char c, size_t pos = npos) const;
size_t find_last_of(const String& str, size_t pos = npos) const;
size_t find_last_of(const char* s, size_t pos = npos) const;
friend String operator+(const String& lhs, const String& rhs);
friend String operator+(const String& lhs, const char* rhs);
friend String operator+(const char* lhs, const String& rhs);
friend String operator+(const String& lhs, char rhs);
friend String operator+(char lhs, const String& rhs);
String toLowerCase() const;
String(const std::string& str);
String(const std::string& str, size_t pos, size_t len = npos);
String& operator=(const std::string& str);
String& operator+=(const std::string& str);
operator std::string() const;
friend String operator+(const String& lhs, const std::string& rhs);
friend String operator+(const std::string& lhs, const String& rhs);
private:
char* cstr_;
size_t len_;
char* allocate(size_t len); // len without trailing 0
void deallocate();
String(int); // disabled and invalid. Catch invalid usages like,
// commandLineParser.has(0) problem
};
inline String::String() : cstr_(0), len_(0) {}
inline String::String(const String& str) : cstr_(str.cstr_), len_(str.len_) {
if (cstr_)
CIL_XADD(((int*)cstr_) - 1, 1);
}
inline String::String(const String& str, size_t pos, size_t len)
: cstr_(0), len_(0) {
pos = std::min(pos, str.len_);
len = std::min(str.len_ - pos, len);
if (!len)
return;
if (len == str.len_) {
CIL_XADD(((int*)str.cstr_) - 1, 1);
cstr_ = str.cstr_;
len_ = str.len_;
return;
}
memcpy(allocate(len), str.cstr_ + pos, len);
}
inline String::String(const char* s) : cstr_(0), len_(0) {
if (!s)
return;
size_t len = strlen(s);
memcpy(allocate(len), s, len);
}
inline String::String(const char* s, size_t n) : cstr_(0), len_(0) {
if (!n)
return;
memcpy(allocate(n), s, n);
}
inline String::String(size_t n, char c) : cstr_(0), len_(0) {
memset(allocate(n), c, n);
}
inline String::String(const char* first, const char* last) : cstr_(0), len_(0) {
size_t len = (size_t)(last - first);
memcpy(allocate(len), first, len);
}
template <typename Iterator>
inline String::String(Iterator first, Iterator last) : cstr_(0), len_(0) {
size_t len = (size_t)(last - first);
char* str = allocate(len);
while (first != last) {
*str++ = *first;
++first;
}
}
inline String::~String() {
deallocate();
}
inline String& String::operator=(const String& str) {
if (&str == this)
return *this;
deallocate();
if (str.cstr_)
CIL_XADD(((int*)str.cstr_) - 1, 1);
cstr_ = str.cstr_;
len_ = str.len_;
return *this;
}
inline String& String::operator=(const char* s) {
deallocate();
if (!s)
return *this;
size_t len = strlen(s);
memcpy(allocate(len), s, len);
return *this;
}
inline String& String::operator=(char c) {
deallocate();
allocate(1)[0] = c;
return *this;
}
inline String& String::operator+=(const String& str) {
*this = *this + str;
return *this;
}
inline String& String::operator+=(const char* s) {
*this = *this + s;
return *this;
}
inline String& String::operator+=(char c) {
*this = *this + c;
return *this;
}
inline size_t String::size() const {
return len_;
}
inline size_t String::length() const {
return len_;
}
inline char String::operator[](size_t idx) const {
return cstr_[idx];
}
inline char String::operator[](int idx) const {
return cstr_[idx];
}
inline const char* String::begin() const {
return cstr_;
}
inline const char* String::end() const {
return len_ ? cstr_ + 1 : 0;
}
inline bool String::empty() const {
return len_ == 0;
}
inline const char* String::c_str() const {
return cstr_ ? cstr_ : "";
}
inline void String::swap(String& str) {
std::swap(cstr_, str.cstr_);
std::swap(len_, str.len_);
}
inline void String::clear() {
deallocate();
}
inline int String::compare(const char* s) const {
if (cstr_ == s)
return 0;
return strcmp(c_str(), s);
}
inline int String::compare(const String& str) const {
if (cstr_ == str.cstr_)
return 0;
return strcmp(c_str(), str.c_str());
}
inline String String::substr(size_t pos, size_t len) const {
return String(*this, pos, len);
}
inline size_t String::find(const char* s, size_t pos, size_t n) const {
if (n == 0 || pos + n > len_)
return npos;
const char* lmax = cstr_ + len_ - n;
for (const char* i = cstr_ + pos; i <= lmax; ++i) {
size_t j = 0;
while (j < n && s[j] == i[j])
++j;
if (j == n)
return (size_t)(i - cstr_);
}
return npos;
}
inline size_t String::find(char c, size_t pos) const {
return find(&c, pos, 1);
}
inline size_t String::find(const String& str, size_t pos) const {
return find(str.c_str(), pos, str.len_);
}
inline size_t String::find(const char* s, size_t pos) const {
if (pos >= len_ || !s[0])
return npos;
const char* lmax = cstr_ + len_;
for (const char* i = cstr_ + pos; i < lmax; ++i) {
size_t j = 0;
while (s[j] && s[j] == i[j]) {
if (i + j >= lmax)
return npos;
++j;
}
if (!s[j])
return (size_t)(i - cstr_);
}
return npos;
}
inline size_t String::rfind(const char* s, size_t pos, size_t n) const {
if (n > len_)
return npos;
if (pos > len_ - n)
pos = len_ - n;
for (const char* i = cstr_ + pos; i >= cstr_; --i) {
size_t j = 0;
while (j < n && s[j] == i[j])
++j;
if (j == n)
return (size_t)(i - cstr_);
}
return npos;
}
inline size_t String::rfind(char c, size_t pos) const {
return rfind(&c, pos, 1);
}
inline size_t String::rfind(const String& str, size_t pos) const {
return rfind(str.c_str(), pos, str.len_);
}
inline size_t String::rfind(const char* s, size_t pos) const {
return rfind(s, pos, strlen(s));
}
inline size_t String::find_first_of(const char* s, size_t pos, size_t n) const {
if (n == 0 || pos + n > len_)
return npos;
const char* lmax = cstr_ + len_;
for (const char* i = cstr_ + pos; i < lmax; ++i) {
for (size_t j = 0; j < n; ++j)
if (s[j] == *i)
return (size_t)(i - cstr_);
}
return npos;
}
inline size_t String::find_first_of(char c, size_t pos) const {
return find_first_of(&c, pos, 1);
}
inline size_t String::find_first_of(const String& str, size_t pos) const {
return find_first_of(str.c_str(), pos, str.len_);
}
inline size_t String::find_first_of(const char* s, size_t pos) const {
if (len_ == 0)
return npos;
if (pos >= len_ || !s[0])
return npos;
const char* lmax = cstr_ + len_;
for (const char* i = cstr_ + pos; i < lmax; ++i) {
for (size_t j = 0; s[j]; ++j)
if (s[j] == *i)
return (size_t)(i - cstr_);
}
return npos;
}
inline size_t String::find_last_of(const char* s, size_t pos, size_t n) const {
if (len_ == 0)
return npos;
if (pos >= len_)
pos = len_ - 1;
for (const char* i = cstr_ + pos; i >= cstr_; --i) {
for (size_t j = 0; j < n; ++j)
if (s[j] == *i)
return (size_t)(i - cstr_);
}
return npos;
}
inline size_t String::find_last_of(char c, size_t pos) const {
return find_last_of(&c, pos, 1);
}
inline size_t String::find_last_of(const String& str, size_t pos) const {
return find_last_of(str.c_str(), pos, str.len_);
}
inline size_t String::find_last_of(const char* s, size_t pos) const {
if (len_ == 0)
return npos;
if (pos >= len_)
pos = len_ - 1;
for (const char* i = cstr_ + pos; i >= cstr_; --i) {
for (size_t j = 0; s[j]; ++j)
if (s[j] == *i)
return (size_t)(i - cstr_);
}
return npos;
}
inline String String::toLowerCase() const {
String res(cstr_, len_);
for (size_t i = 0; i < len_; ++i)
res.cstr_[i] = (char)::tolower(cstr_[i]);
return res;
}
inline String operator+(const String& lhs, const String& rhs) {
String s;
s.allocate(lhs.len_ + rhs.len_);
memcpy(s.cstr_, lhs.cstr_, lhs.len_);
memcpy(s.cstr_ + lhs.len_, rhs.cstr_, rhs.len_);
return s;
}
inline String operator+(const String& lhs, const char* rhs) {
String s;
size_t rhslen = strlen(rhs);
s.allocate(lhs.len_ + rhslen);
memcpy(s.cstr_, lhs.cstr_, lhs.len_);
memcpy(s.cstr_ + lhs.len_, rhs, rhslen);
return s;
}
inline String operator+(const char* lhs, const String& rhs) {
String s;
size_t lhslen = strlen(lhs);
s.allocate(lhslen + rhs.len_);
memcpy(s.cstr_, lhs, lhslen);
memcpy(s.cstr_ + lhslen, rhs.cstr_, rhs.len_);
return s;
}
inline String operator+(const String& lhs, char rhs) {
String s;
s.allocate(lhs.len_ + 1);
memcpy(s.cstr_, lhs.cstr_, lhs.len_);
s.cstr_[lhs.len_] = rhs;
return s;
}
inline String operator+(char lhs, const String& rhs) {
String s;
s.allocate(rhs.len_ + 1);
s.cstr_[0] = lhs;
memcpy(s.cstr_ + 1, rhs.cstr_, rhs.len_);
return s;
}
static inline bool operator==(const String& lhs, const String& rhs) {
return 0 == lhs.compare(rhs);
}
static inline bool operator==(const char* lhs, const String& rhs) {
return 0 == rhs.compare(lhs);
}
static inline bool operator==(const String& lhs, const char* rhs) {
return 0 == lhs.compare(rhs);
}
static inline bool operator!=(const String& lhs, const String& rhs) {
return 0 != lhs.compare(rhs);
}
static inline bool operator!=(const char* lhs, const String& rhs) {
return 0 != rhs.compare(lhs);
}
static inline bool operator!=(const String& lhs, const char* rhs) {
return 0 != lhs.compare(rhs);
}
static inline bool operator<(const String& lhs, const String& rhs) {
return lhs.compare(rhs) < 0;
}
static inline bool operator<(const char* lhs, const String& rhs) {
return rhs.compare(lhs) > 0;
}
static inline bool operator<(const String& lhs, const char* rhs) {
return lhs.compare(rhs) < 0;
}
static inline bool operator<=(const String& lhs, const String& rhs) {
return lhs.compare(rhs) <= 0;
}
static inline bool operator<=(const char* lhs, const String& rhs) {
return rhs.compare(lhs) >= 0;
}
static inline bool operator<=(const String& lhs, const char* rhs) {
return lhs.compare(rhs) <= 0;
}
static inline bool operator>(const String& lhs, const String& rhs) {
return lhs.compare(rhs) > 0;
}
static inline bool operator>(const char* lhs, const String& rhs) {
return rhs.compare(lhs) < 0;
}
static inline bool operator>(const String& lhs, const char* rhs) {
return lhs.compare(rhs) > 0;
}
static inline bool operator>=(const String& lhs, const String& rhs) {
return lhs.compare(rhs) >= 0;
}
static inline bool operator>=(const char* lhs, const String& rhs) {
return rhs.compare(lhs) <= 0;
}
static inline bool operator>=(const String& lhs, const char* rhs) {
return lhs.compare(rhs) >= 0;
}
inline String::String(const std::string& str) : cstr_(0), len_(0) {
if (!str.empty()) {
size_t len = str.size();
memcpy(allocate(len), str.c_str(), len);
}
}
inline String::String(const std::string& str, size_t pos, size_t len)
: cstr_(0), len_(0) {
size_t strlen = str.size();
pos = std::min(pos, strlen);
len = std::min(strlen - pos, len);
if (!len)
return;
memcpy(allocate(len), str.c_str() + pos, len);
}
inline String& String::operator=(const std::string& str) {
deallocate();
if (!str.empty()) {
size_t len = str.size();
memcpy(allocate(len), str.c_str(), len);
}
return *this;
}
inline String& String::operator+=(const std::string& str) {
*this = *this + str;
return *this;
}
inline String::operator std::string() const {
return std::string(cstr_, len_);
}
inline String operator+(const String& lhs, const std::string& rhs) {
String s;
size_t rhslen = rhs.size();
s.allocate(lhs.len_ + rhslen);
memcpy(s.cstr_, lhs.cstr_, lhs.len_);
memcpy(s.cstr_ + lhs.len_, rhs.c_str(), rhslen);
return s;
}
inline String operator+(const std::string& lhs, const String& rhs) {
String s;
size_t lhslen = lhs.size();
s.allocate(lhslen + rhs.len_);
memcpy(s.cstr_, lhs.c_str(), lhslen);
memcpy(s.cstr_ + lhslen, rhs.cstr_, rhs.len_);
return s;
}
} // namespace cil
|
//
// Created by 王润基 on 2017/4/8.
//
#ifndef INC_2RAYTRACE_INTERSECTRESULT_H
#define INC_2RAYTRACE_INTERSECTRESULT_H
#include <iostream>
#include "Ray.h"
class Material;
class IRayCastable;
class Shape;
class Object;
struct IntersectInfo {
// Request
Ray ray;
float testBlockT = 0; // 若此数不为0,则直接给success赋值:是否存在交点使得 t < testBlockT
bool needNormal = false;
bool needParam = false;
bool needUV = false;
// Response
bool success = false;
float t = std::numeric_limits<float>::max() / 8;
Vector3f point, normal, param, uv;
const IRayCastable* object = nullptr;
// temp
Vector3f weight;
// Methods
IntersectInfo(){}
IntersectInfo(const Ray &ray);
bool isOuter () const;
Vector3f getPoint() const;
Material getMaterial () const;
Object* getObject() const;
Shape* getShape() const;
friend std::ostream &operator<<(std::ostream &os, const IntersectInfo &info);
};
#endif //INC_2RAYTRACE_INTERSECTRESULT_H
|
#include <iostream>
#include "Ant.hpp"
#include "Doodlebug.hpp"
#include "Grid.hpp"
int main()
{
Grid grid;
grid.displayGrid();
int steps = 20;
for (int step = 0; step < steps; step++)
{
grid.moveCritters();
}
return 0;
}
|
#include "MyListView.h"
#include <QMouseEvent>
#include <QDebug>
MyListView::MyListView(QWidget *parent) :
QListView(parent)
{
}
void MyListView::mouseMoveEvent(QMouseEvent *event)
{
//qDebug()<<event->x()<<" "<<event->y();
int x = mapToGlobal(event->globalPos()).x();
int y = mapToGlobal(event->globalPos()).y() + 1;
//qDebug()<<x;
QPoint p(this->pos());
// qDebug()<< p;
int x1 = mapToGlobal(p).x();
int x2 = mapToGlobal(p).x() + this->width();
int y1 =mapToGlobal(p).y() + this->height();
if(x <= x1 + OFFSET_VIEW || x >= x2 - OFFSET_VIEW || y >= y1 - OFFSET_VIEW)
{
this->hide();
}
}
void MyListView::initSetting()
{
this->setMouseTracking(true);
}
|
//
// Created by wiktor on 25.04.18.
//
#ifndef JIMP_EXERCISES_PESEL_H
#define JIMP_EXERCISES_PESEL_H
#include <string>
namespace academia{
using std::string;
class Pesel {
public:
Pesel(string);
~Pesel() = default;
void validatePESEL(string);
private:
string pesel_;
};
class AcademiaDataValidationError{
};
class InvalidPeselChecksum : public AcademiaDataValidationError{
};
class InvalidPeselCharacter : public AcademiaDataValidationError{
};
class InvalidPeselLength : public AcademiaDataValidationError{
InvalidPeselLength(string);
};
}
#endif //JIMP_EXERCISES_PESEL_H
|
#include <iostream>
#include "Medico.h"
#include "Ginecologista.h"
Ginecologista::Ginecologista(){}
Ginecologista::Ginecologista(string n, float a, float p, string e){
setNome(n);
setAltura(a);
setPeso(p);
setEspecialidade(e);
}
void Ginecologista::setEspecialidade(string e){
especialidade = e;
}
string Ginecologista::getEspecialidade(){
return especialidade;
}
string Ginecologista::realizaCirurgia(){
return "Metodos cirurgicos: Realiza cirurgias e lida diretamente com a saúde do aparelho reprodutor feminino (vagina, útero ovários) e mamas";
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Security.Authentication.Web.Core.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_ac7f26f2_feb7_5b2a_8ac4_345bc62caede
#define WINRT_GENERIC_ac7f26f2_feb7_5b2a_8ac4_345bc62caede
template <> struct __declspec(uuid("ac7f26f2-feb7-5b2a-8ac4-345bc62caede")) __declspec(novtable) IMapView<hstring, hstring> : impl_IMapView<hstring, hstring> {};
#endif
#ifndef WINRT_GENERIC_f6d1f700_49c2_52ae_8154_826f9908773c
#define WINRT_GENERIC_f6d1f700_49c2_52ae_8154_826f9908773c
template <> struct __declspec(uuid("f6d1f700-49c2-52ae-8154-826f9908773c")) __declspec(novtable) IMap<hstring, hstring> : impl_IMap<hstring, hstring> {};
#endif
#ifndef WINRT_GENERIC_60310303_49c5_52e6_abc6_a9b36eccc716
#define WINRT_GENERIC_60310303_49c5_52e6_abc6_a9b36eccc716
template <> struct __declspec(uuid("60310303-49c5-52e6-abc6-a9b36eccc716")) __declspec(novtable) IKeyValuePair<hstring, hstring> : impl_IKeyValuePair<hstring, hstring> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_0a815852_7c44_5674_b3d2_fa2e4c1e46c9
#define WINRT_GENERIC_0a815852_7c44_5674_b3d2_fa2e4c1e46c9
template <> struct __declspec(uuid("0a815852-7c44-5674-b3d2-fa2e4c1e46c9")) __declspec(novtable) IAsyncOperation<Windows::Security::Authentication::Web::Core::WebTokenRequestResult> : impl_IAsyncOperation<Windows::Security::Authentication::Web::Core::WebTokenRequestResult> {};
#endif
#ifndef WINRT_GENERIC_acd76b54_297f_5a18_9143_20a309e2dfd3
#define WINRT_GENERIC_acd76b54_297f_5a18_9143_20a309e2dfd3
template <> struct __declspec(uuid("acd76b54-297f-5a18-9143-20a309e2dfd3")) __declspec(novtable) IAsyncOperation<Windows::Security::Credentials::WebAccount> : impl_IAsyncOperation<Windows::Security::Credentials::WebAccount> {};
#endif
#ifndef WINRT_GENERIC_88c66009_12f7_58e2_8dbe_6efc620c85ba
#define WINRT_GENERIC_88c66009_12f7_58e2_8dbe_6efc620c85ba
template <> struct __declspec(uuid("88c66009-12f7-58e2-8dbe-6efc620c85ba")) __declspec(novtable) IAsyncOperation<Windows::Security::Credentials::WebAccountProvider> : impl_IAsyncOperation<Windows::Security::Credentials::WebAccountProvider> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_cb15d439_a910_542a_89ed_7cfe67848a83
#define WINRT_GENERIC_cb15d439_a910_542a_89ed_7cfe67848a83
template <> struct __declspec(uuid("cb15d439-a910-542a-89ed-7cfe67848a83")) __declspec(novtable) IIterable<Windows::Security::Credentials::WebAccount> : impl_IIterable<Windows::Security::Credentials::WebAccount> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_fa704f04_87b6_516b_9596_cd7cc092169b
#define WINRT_GENERIC_fa704f04_87b6_516b_9596_cd7cc092169b
template <> struct __declspec(uuid("fa704f04-87b6-516b-9596-cd7cc092169b")) __declspec(novtable) TypedEventHandler<Windows::Security::Authentication::Web::Core::WebAccountMonitor, Windows::Security::Authentication::Web::Core::WebAccountEventArgs> : impl_TypedEventHandler<Windows::Security::Authentication::Web::Core::WebAccountMonitor, Windows::Security::Authentication::Web::Core::WebAccountEventArgs> {};
#endif
#ifndef WINRT_GENERIC_c8cb498d_e0da_52a1_abf9_7198c7f5cb42
#define WINRT_GENERIC_c8cb498d_e0da_52a1_abf9_7198c7f5cb42
template <> struct __declspec(uuid("c8cb498d-e0da-52a1-abf9-7198c7f5cb42")) __declspec(novtable) TypedEventHandler<Windows::Security::Authentication::Web::Core::WebAccountMonitor, Windows::Foundation::IInspectable> : impl_TypedEventHandler<Windows::Security::Authentication::Web::Core::WebAccountMonitor, Windows::Foundation::IInspectable> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_e0798d3d_2b4a_589a_ab12_02dccc158afc
#define WINRT_GENERIC_e0798d3d_2b4a_589a_ab12_02dccc158afc
template <> struct __declspec(uuid("e0798d3d-2b4a-589a-ab12-02dccc158afc")) __declspec(novtable) IVectorView<Windows::Security::Credentials::WebAccount> : impl_IVectorView<Windows::Security::Credentials::WebAccount> {};
#endif
#ifndef WINRT_GENERIC_199e065c_8195_55da_9c10_8aeaf9ac1062
#define WINRT_GENERIC_199e065c_8195_55da_9c10_8aeaf9ac1062
template <> struct __declspec(uuid("199e065c-8195-55da-9c10-8aeaf9ac1062")) __declspec(novtable) IVectorView<Windows::Security::Authentication::Web::Core::WebTokenResponse> : impl_IVectorView<Windows::Security::Authentication::Web::Core::WebTokenResponse> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_deb54b22_70f2_55ab_97c0_6cbdc5ddb6f0
#define WINRT_GENERIC_deb54b22_70f2_55ab_97c0_6cbdc5ddb6f0
template <> struct __declspec(uuid("deb54b22-70f2-55ab-97c0-6cbdc5ddb6f0")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Security::Authentication::Web::Core::WebTokenRequestResult> : impl_AsyncOperationCompletedHandler<Windows::Security::Authentication::Web::Core::WebTokenRequestResult> {};
#endif
#ifndef WINRT_GENERIC_4bd6f1e5_ca89_5240_8f3d_7f1b54ae90a7
#define WINRT_GENERIC_4bd6f1e5_ca89_5240_8f3d_7f1b54ae90a7
template <> struct __declspec(uuid("4bd6f1e5-ca89-5240-8f3d-7f1b54ae90a7")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Security::Credentials::WebAccount> : impl_AsyncOperationCompletedHandler<Windows::Security::Credentials::WebAccount> {};
#endif
#ifndef WINRT_GENERIC_9477622b_1340_5574_81fc_5013581f57c9
#define WINRT_GENERIC_9477622b_1340_5574_81fc_5013581f57c9
template <> struct __declspec(uuid("9477622b-1340-5574-81fc-5013581f57c9")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Security::Credentials::WebAccountProvider> : impl_AsyncOperationCompletedHandler<Windows::Security::Credentials::WebAccountProvider> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_fe11c488_371a_5330_b7fa_282326fdfbda
#define WINRT_GENERIC_fe11c488_371a_5330_b7fa_282326fdfbda
template <> struct __declspec(uuid("fe11c488-371a-5330-b7fa-282326fdfbda")) __declspec(novtable) IVector<Windows::Security::Credentials::WebAccount> : impl_IVector<Windows::Security::Credentials::WebAccount> {};
#endif
#ifndef WINRT_GENERIC_bfb82cca_aebc_567c_95d9_eba25c365faa
#define WINRT_GENERIC_bfb82cca_aebc_567c_95d9_eba25c365faa
template <> struct __declspec(uuid("bfb82cca-aebc-567c-95d9-eba25c365faa")) __declspec(novtable) IIterator<Windows::Security::Credentials::WebAccount> : impl_IIterator<Windows::Security::Credentials::WebAccount> {};
#endif
#ifndef WINRT_GENERIC_58dc4e4c_a84d_5ad6_a6d9_6ee477329c9f
#define WINRT_GENERIC_58dc4e4c_a84d_5ad6_a6d9_6ee477329c9f
template <> struct __declspec(uuid("58dc4e4c-a84d-5ad6-a6d9-6ee477329c9f")) __declspec(novtable) IVector<Windows::Security::Authentication::Web::Core::WebTokenResponse> : impl_IVector<Windows::Security::Authentication::Web::Core::WebTokenResponse> {};
#endif
#ifndef WINRT_GENERIC_f080b0c9_a095_5b3a_a1dc_d17e7d2982c7
#define WINRT_GENERIC_f080b0c9_a095_5b3a_a1dc_d17e7d2982c7
template <> struct __declspec(uuid("f080b0c9-a095-5b3a-a1dc-d17e7d2982c7")) __declspec(novtable) IIterator<Windows::Security::Authentication::Web::Core::WebTokenResponse> : impl_IIterator<Windows::Security::Authentication::Web::Core::WebTokenResponse> {};
#endif
#ifndef WINRT_GENERIC_7e5bb7ec_bbd7_5575_9a61_f5815fa22a0e
#define WINRT_GENERIC_7e5bb7ec_bbd7_5575_9a61_f5815fa22a0e
template <> struct __declspec(uuid("7e5bb7ec-bbd7-5575-9a61-f5815fa22a0e")) __declspec(novtable) IIterable<Windows::Security::Authentication::Web::Core::WebTokenResponse> : impl_IIterable<Windows::Security::Authentication::Web::Core::WebTokenResponse> {};
#endif
#ifndef WINRT_GENERIC_e9bdaaf0_cbf6_5c72_be90_29cbf3a1319b
#define WINRT_GENERIC_e9bdaaf0_cbf6_5c72_be90_29cbf3a1319b
template <> struct __declspec(uuid("e9bdaaf0-cbf6-5c72-be90-29cbf3a1319b")) __declspec(novtable) IIterable<Windows::Foundation::Collections::IKeyValuePair<hstring, hstring>> : impl_IIterable<Windows::Foundation::Collections::IKeyValuePair<hstring, hstring>> {};
#endif
#ifndef WINRT_GENERIC_05eb86f1_7140_5517_b88d_cbaebe57e6b1
#define WINRT_GENERIC_05eb86f1_7140_5517_b88d_cbaebe57e6b1
template <> struct __declspec(uuid("05eb86f1-7140-5517-b88d-cbaebe57e6b1")) __declspec(novtable) IIterator<Windows::Foundation::Collections::IKeyValuePair<hstring, hstring>> : impl_IIterator<Windows::Foundation::Collections::IKeyValuePair<hstring, hstring>> {};
#endif
}
namespace Windows::Security::Authentication::Web::Core {
struct IWebAccountEventArgs :
Windows::Foundation::IInspectable,
impl::consume<IWebAccountEventArgs>
{
IWebAccountEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct IWebAccountMonitor :
Windows::Foundation::IInspectable,
impl::consume<IWebAccountMonitor>
{
IWebAccountMonitor(std::nullptr_t = nullptr) noexcept {}
};
struct IWebAuthenticationCoreManagerStatics :
Windows::Foundation::IInspectable,
impl::consume<IWebAuthenticationCoreManagerStatics>
{
IWebAuthenticationCoreManagerStatics(std::nullptr_t = nullptr) noexcept {}
};
struct IWebAuthenticationCoreManagerStatics2 :
Windows::Foundation::IInspectable,
impl::consume<IWebAuthenticationCoreManagerStatics2>,
impl::require<IWebAuthenticationCoreManagerStatics2, Windows::Security::Authentication::Web::Core::IWebAuthenticationCoreManagerStatics>
{
IWebAuthenticationCoreManagerStatics2(std::nullptr_t = nullptr) noexcept {}
using impl_IWebAuthenticationCoreManagerStatics::FindAccountProviderAsync;
using impl_IWebAuthenticationCoreManagerStatics2::FindAccountProviderAsync;
};
struct IWebAuthenticationCoreManagerStatics3 :
Windows::Foundation::IInspectable,
impl::consume<IWebAuthenticationCoreManagerStatics3>,
impl::require<IWebAuthenticationCoreManagerStatics3, Windows::Security::Authentication::Web::Core::IWebAuthenticationCoreManagerStatics>
{
IWebAuthenticationCoreManagerStatics3(std::nullptr_t = nullptr) noexcept {}
};
struct IWebProviderError :
Windows::Foundation::IInspectable,
impl::consume<IWebProviderError>
{
IWebProviderError(std::nullptr_t = nullptr) noexcept {}
};
struct IWebProviderErrorFactory :
Windows::Foundation::IInspectable,
impl::consume<IWebProviderErrorFactory>
{
IWebProviderErrorFactory(std::nullptr_t = nullptr) noexcept {}
};
struct IWebTokenRequest :
Windows::Foundation::IInspectable,
impl::consume<IWebTokenRequest>
{
IWebTokenRequest(std::nullptr_t = nullptr) noexcept {}
};
struct IWebTokenRequest2 :
Windows::Foundation::IInspectable,
impl::consume<IWebTokenRequest2>
{
IWebTokenRequest2(std::nullptr_t = nullptr) noexcept {}
};
struct IWebTokenRequest3 :
Windows::Foundation::IInspectable,
impl::consume<IWebTokenRequest3>
{
IWebTokenRequest3(std::nullptr_t = nullptr) noexcept {}
};
struct IWebTokenRequestFactory :
Windows::Foundation::IInspectable,
impl::consume<IWebTokenRequestFactory>
{
IWebTokenRequestFactory(std::nullptr_t = nullptr) noexcept {}
};
struct IWebTokenRequestResult :
Windows::Foundation::IInspectable,
impl::consume<IWebTokenRequestResult>
{
IWebTokenRequestResult(std::nullptr_t = nullptr) noexcept {}
};
struct IWebTokenResponse :
Windows::Foundation::IInspectable,
impl::consume<IWebTokenResponse>
{
IWebTokenResponse(std::nullptr_t = nullptr) noexcept {}
};
struct IWebTokenResponseFactory :
Windows::Foundation::IInspectable,
impl::consume<IWebTokenResponseFactory>
{
IWebTokenResponseFactory(std::nullptr_t = nullptr) noexcept {}
};
}
}
|
//
// Created by Tidesun on 2019-04-23.
//
#include "file_reader.hpp"
// util function to split string into vector
template<typename Out>
void split(const std::string &s, char delim, Out result) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
*(result++) = item;
}
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;
}
FileReader::FileReader(string _fileName,int _format) {
fileName = _fileName;
format = _format;
delimeter = ',';
}
void FileReader::readGraph(Graph* g) {
if (format == SVCN) {
convertReadGraph(g);
}
if (format == GRAPH) {
g->readGraph(fileName.c_str());
}
g->calculateCopyNum();
}
vector<vector<string> > FileReader::getData(){
ifstream file(fileName);
vector<std::vector<string> > dataList;
string line = "";
getline(file, line);
vector<string> header = split(line,delimeter);
// Iterate through each line and split the content using delimeter
while (getline(file, line))
{
vector<string> vec = split(line,delimeter);
dataList.push_back(vec);
}
// Close the File
file.close();
return dataList;
}
void FileReader::convertReadGraph(Graph* g) {
vector<vector<string>> dataframe = getData();
g->setAvgCoverage(20);
g->setAvgRawCoverage(20);
g->setAvgPloidy(2.0);
g->setPurity(1.0);
vector<pair<int,int>> breakpoints;
vector<tuple<int,int,int,int>> segments;
int bk_max = -1;
int bk_min = numeric_limits<int>::max();
for (auto row:dataframe) {
int bkpos_5p = stoi(row[1]);
int bkpos_3p = stoi(row[4]);
int cn = stoi(row[6]);
bk_max = max(bk_max,max(bkpos_3p,bkpos_5p));
bk_min = min(bk_min,min(bkpos_3p,bkpos_5p));
breakpoints.emplace_back(make_pair(bkpos_5p,cn));
breakpoints.emplace_back(make_pair(bkpos_3p,cn));
}
breakpoints.push_back(make_pair(bk_max+1,10));
breakpoints.push_back(make_pair(bk_min-1,10));
sort(breakpoints.begin(), breakpoints.end());
int index = 0;
for (auto it = breakpoints.begin(),end = breakpoints.end();it != end-1;++it) {
int left_bkpos = it->first;
int right_bkpos = next(it,1)->first;
int cn = max(it->second,next(it,1)->second);
if (index >0 ) {
int prev_cn = get<3>(segments.back());
if (abs(cn - prev_cn) < 10) {
get<2>(segments.back()) = right_bkpos;
} else {
segments.emplace_back(make_tuple(index,left_bkpos,right_bkpos,cn));
index++;
}
} else {
segments.emplace_back(make_tuple(index,left_bkpos,right_bkpos,cn));
index ++;
}
}
map<int, int> leftDic;
map<int, int> rightDic;
for (auto seg:segments){
leftDic[get<1>(seg)] = get<0>(seg);
rightDic[get<2>(seg)] = get<0>(seg);
g->addSegment(get<0>(seg),get<3>(seg)+10,1.0);
}
for (auto it = segments.begin(),end = segments.end();it != end-1;++it) {
int currentId = get<0>(*it);
int nextId = get<0>(*next(it,1));
g->addJunction(currentId,'+',nextId,'+',10,1.0);
}
for (auto row:dataframe) {
int bkpos_5p = stoi(row[1]);
int bkpos_3p = stoi(row[4]);
char dir_5p = row[2][0];
char dir_3p = row[5][0];
int cn = stoi(row[6]);
auto leftId = rightDic.upper_bound(bkpos_5p)->second;
auto rightId = leftDic.upper_bound(bkpos_3p)->second;
cout<< leftId << dir_5p << rightId<<dir_3p<<endl;
g->addJunction(leftId,dir_5p,rightId,dir_3p,cn,1.0);
}
}
|
#pragma once
#include "Obstacle.hh"
const std::string kModelCuboid("solid/cuboidRead.dat");
const std::string kCuboidFile("solid/cuboid.dat");
/**
* @brief 3D type of obstacle
*
*/
class Cuboid: public Obstacle{
public:
Cuboid();
virtual ~Cuboid() override;
virtual void draw(std::string filename) const override;
virtual bool checkCollision(const Drone& drone) const;
virtual void getName() const{std::cout << "cuboid";};
};
|
#ifndef _SQMMDB_DATABASE_HPP_
#define _SQMMDB_DATABASE_HPP_
// ------------------------------------------------------------------------------------------------
#include "Handle/Database.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Class that can be used to open and query information from MaxMind database files.
*/
class Database
{
public:
// --------------------------------------------------------------------------------------------
typedef DbHnd::Type Type; // The managed type.
// --------------------------------------------------------------------------------------------
typedef Type* Pointer; // Pointer to the managed type.
typedef const Type* ConstPtr; // Constant pointer to the managed type.
// --------------------------------------------------------------------------------------------
typedef Type& Reference; // Reference to the managed type.
typedef const Type& ConstRef; // Constant reference to the managed type.
protected:
/* --------------------------------------------------------------------------------------------
* Validate the managed database handle and throw an error if invalid.
*/
#if defined(_DEBUG) || defined(SQMOD_EXCEPTLOC)
void Validate(CCStr file, Int32 line) const;
#else
void Validate() const;
#endif //
/* --------------------------------------------------------------------------------------------
* Validate the managed database handle and throw an error if invalid.
*/
#if defined(_DEBUG) || defined(SQMOD_EXCEPTLOC)
const DbRef & GetValid(CCStr file, Int32 line) const;
#else
const DbRef & GetValid() const;
#endif // _DEBUG
private:
// ---------------------------------------------------------------------------------------------
DbRef m_Handle; // The managed database handle.
public:
/* --------------------------------------------------------------------------------------------
* Default constructor. (null)
*/
Database()
: m_Handle()
{
/* ... */
}
/* --------------------------------------------------------------------------------------------
* Base constructor. (default flags)
*/
Database(CSStr filepath)
: m_Handle(new DbHnd(filepath, 0))
{
/* ... */
}
/* --------------------------------------------------------------------------------------------
* Base constructor.
*/
Database(CSStr filepath, Uint32 flags)
: m_Handle(new DbHnd(filepath, flags))
{
/* ... */
}
/* --------------------------------------------------------------------------------------------
* Explicit handle constructor.
*/
Database(const DbRef & db)
: m_Handle(db)
{
/* ... */
}
/* --------------------------------------------------------------------------------------------
* Copy constructor.
*/
Database(const Database & o) = default;
/* --------------------------------------------------------------------------------------------
* Move constructor.
*/
Database(Database && o) = default;
/* --------------------------------------------------------------------------------------------
* Copy assignment operator.
*/
Database & operator = (const Database & o) = default;
/* --------------------------------------------------------------------------------------------
* Move assignment operator.
*/
Database & operator = (Database && o) = default;
/* --------------------------------------------------------------------------------------------
* Used by the script engine to convert an instance of this type to a string.
*/
CSStr ToString() const
{
return m_Handle ? m_Handle->mDb.filename : _SC("");
}
/* --------------------------------------------------------------------------------------------
* Used by the script engine to retrieve the name from instances of this type.
*/
static SQInteger Typename(HSQUIRRELVM vm);
/* --------------------------------------------------------------------------------------------
* See whether this instance references a valid database instance.
*/
bool IsValid() const
{
return m_Handle;
}
/* --------------------------------------------------------------------------------------------
* Release the manages handles/pointers and become a null instance.
*/
void Release()
{
m_Handle.Reset();
}
/* --------------------------------------------------------------------------------------------
* Return the number of active references to the managed database instance.
*/
Uint32 GetRefCount() const
{
return m_Handle.Count();
}
/* --------------------------------------------------------------------------------------------
* Attempt to open the specified database.
*/
void Open(CSStr filepath)
{
Open(filepath, 0);
}
/* --------------------------------------------------------------------------------------------
* Attempt to open the specified database.
*/
void Open(CSStr filepath, Uint32 flags)
{
// Make sure there isn't another database handle
if (!m_Handle)
{
m_Handle = DbRef(new DbHnd(filepath, flags));
}
else
{
STHROWF("Loading is disabled while database is referenced");
}
}
/* --------------------------------------------------------------------------------------------
* Retrieve the metadata associated with the managed database handle.
*/
Metadata GetMetadata() const;
/* --------------------------------------------------------------------------------------------
* Retrieve the metadata associated with the managed database handle as an entry data list.
*/
Object GetMetadataAsEntryDataList() const;
/* --------------------------------------------------------------------------------------------
* Look up an IP address that is passed in as a null-terminated string.
*/
LookupResult LookupString(CSStr addr);
/* --------------------------------------------------------------------------------------------
* Looks up an IP address that has already been resolved by getaddrinfo().
*/
LookupResult LookupSockAddr(SockAddr & sockaddr);
/* --------------------------------------------------------------------------------------------
* Retrieve a speciffic node from the managed database.
*/
SearchNode ReadNode(Uint32 node) const;
};
} // Namespace:: SqMod
#endif // _SQMMDB_DATABASE_HPP_
|
#include <stdlib.h>
#include <iostream>
#include "TQueue.cpp"
//#include "support.h"
#include "Customer.h"
#include "Cashier.h"
using namespace std;
int compare(int * a, int *b){
if(*a < *b) return -1;
else if(*a > *b) return 1;
else return 0;
}
int Random(const int start, const int end){
return(start + random()%(end - start + 1));
}
void printArrival(Customer *n){
cout<<"Time:"<<time<<":Customer Arrival:";
n->print();
n = NULL;
}
void printDequeue(Customer *n){
cout<<"Time:"<<time<<":Customer Dequeue:";
n->print();
n = NULL;
}
void main(){
cout<<"Started\n";
int aTR[2] = {1,4}; //arrival time range
int sTR[2] = {1,4}; // service time range
int id = 0; // customer ID
int arrivalTime;
int serviceTime;
int time = 0;
Cashier cashier;
TQueue<Customer> customerQueue; // Customer queue
TQueue<Cashier> cashierQueue; // Cashier queue
//first Customer arrival
//1)
time += Random(1,4);
Customer *first = new Customer;
serviceTime = Random(1,4); //2a)
first->set(id++,time,0,serviceTime);
//Customer arrival
printArrival(first);
customerQueue.enqueue(first);
first = NULL;
//Customer Dequeue
first = customerQueue.dequeue();
first->setDequeue(time);
printDequeue(first);
cashier.setCustomer(*first);//2b)
cout<<"Time:"<<time<<":Service Start:"; first->print();
delete first;
first = NULL;
while(time<20){
time += Random(1,4);
Customer *n = new Customer;
serviceTime = Random(1,4);
n->set(id++,time,0,serviceTime);
printArrival(n);
customerQueue.enqueue(n);
n = NULL;
if(cashier.getServiceTime() <= time){
cout<<"Time:"<<time<<"Service End:"; cashier.printCustomer();
n = customerQueue.dequeue();
printDequeue(n);
cashier.setCustomer(*n);
cout<<"Time:"<<time<<"Service Start:"; first->print();
delete n;
n = NULL;
}
}
/*
TQueue<int> tint;
for(int i=0;i<5;i++) {
int *x = new int;
*x = i*i;
tint.insert(x, compare);
}
for(int j=0;j<5;j++) {
int *x;
x = tint.dequeue();
cout << x << "," << *x << endl;
delete x;
}
*/
}
|
#include "Particle.hpp"
#include <math.h>
Particle::Particle(float xpos, float ypos) {
location = new Location(xpos, ypos);
trajectory = new Vector2(0, 0);
color.red = color.blue = color.green = 1.0;
}
void Particle::setColor(float red, float blue, float green) {
if (red < 0.2 && green < 0.2 && blue < 0.2) { red = green = blue = 1; }
color.red = red;
color.blue = blue;
color.green = green;
}
void Particle::setRandomColor() {
setColor(sin(clock()), cos(clock()), sin(clock()));
}
void Particle::render() {
updateLocation();
float x = location->getX();
float y = location->getY();
glBegin(GL_QUADS);
glColor3f(color.red, color.blue, color.green);
glVertex2f(x-0.002f, y-0.002f);
glVertex2f(x-0.002f, y+0.002f);
glVertex2f(x+0.002f, y+0.002f);
glVertex2f(x+0.002f, y-0.002f);
glEnd();
glFlush();
}
void Particle::updateLocation() {
float x = location->getX();
float y = location->getY();
location->set(x + trajectory->getX(), y + trajectory->getY());
}
Particle::~Particle() {
delete location;
delete trajectory;
}
|
#include "stdafx.h"
#include "plotModel.h"
#include "data/grader.h"
#include "data/locator.h"
plot_model::plot_model(bool m)
: plot_maker(m)
, bitmap_maker_(this)
, valid_(false)
{
bitmap_maker_.attach_listener(this);
}
plot_model::~plot_model()
{
bitmap_maker_.detach_listener(this);
}
bool plot_model::valid() const
{
return valid_;
}
void plot_model::set_dimensions(int cx, int cy)
{
bitmap_maker_.set_dimensions(CSize(cx, cy));
}
void plot_model::attach_listener(process::host_listener *ls)
{
bitmap_maker_.attach_listener(ls);
}
void plot_model::detach_listener(process::host_listener *ls)
{
bitmap_maker_.detach_listener(ls);
}
std::vector<double> plot_model::get_timemarks() const
{
if (valid())
return result_->timemarks;
return std::vector<double>();
}
shared_ptr<CBitmap> plot_model::get_bitmap() const
{
if (valid())
return result_->bitmap_;
CDC desktop_dc=::GetWindowDC( 0 );
CSize s = bitmap_maker_.get_dimensions();
HBITMAP bitmap = ::CreateCompatibleBitmap( desktop_dc, s.cx, s.cy);
CDC dc2( ::CreateCompatibleDC(desktop_dc) );
dc2.SelectBitmap( bitmap );
dc2.FillSolidRect(0, 0, s.cx, s.cy, 0x3f3f3f);
dc2.DeleteDC();
return shared_ptr<CBitmap>( new CBitmap( bitmap ));
}
plot::range plot_model::get_xrange() const
{
if (valid())
return result_->screen->get_xrange();
return plot_maker::get_xrange();
}
plot::range plot_model::get_yrange() const
{
if (valid())
return result_->screen->get_yrange();
return plot_maker::get_yrange();
}
axe_info plot_model::get_xaxe_info() const
{
axe_info info = plot_maker::get_xaxe_info();
if (valid())
{
plot::range range = result_->screen->get_xrange();
info.lo = range.lo;
info.hi = range.hi;
}
return info;
}
axe_info plot_model::get_yaxe_info() const
{
axe_info info = plot_maker::get_yaxe_info();
if (valid())
{
plot::range range = result_->screen->get_yrange();
info.lo = range.lo;
info.hi = range.hi;
}
return info;
}
location::pclusters plot_model::get_clusters() const
{
shared_ptr<nodes::locator_result> r=
process::get_parent_result<
nodes::locator_result>(this, false);
if (!r) return location::pclusters();
return r->get_clusters();
}
bool plot_model::get_working_location_setup(location::Setup & result) const
{
shared_ptr<nodes::grader_result> r=
process::get_parent_result<
nodes::grader_result>(this, false);
if (!r) return false;
if (r->location.empty()) return false;
result = r->location;
return true;
}
void plot_model::get_xminmax(bool &a, double &z, double &x) const
{
plot_maker::get_xminmax(a, z, x);
if (valid())
{
plot::range range = result_->screen->get_xrange();
z = range.lo;
x = range.hi;
}
}
void plot_model::get_yminmax(bool &a, double &z, double &x) const
{
plot_maker::get_yminmax(a, z, x);
if (valid())
{
plot::range range = result_->screen->get_yrange();
z = range.lo;
x = range.hi;
}
}
void plot_model::safe_on_restart()
{
valid_ = false;
}
void plot_model::safe_on_finish(process::prslt rsl)
{
valid_ = true;
result_ = boost::dynamic_pointer_cast<bitmap_result>(rsl);
assert(result_);
}
|
/*
* CylindricalCoordinate.h
*
* Created on: Feb 18, 2012
* Author: wjones
*/
#ifndef CYLINDRICALCOORDINATE_H_
#define CYLINDRICALCOORDINATE_H_
#include "Utilities/Definitions.h"
#include "GeometricComponents/SpatialVector.hpp"
namespace CoordinateComponents
{
template<typename T>
class CylindricalCoordinate;
template<typename T>
class CartesianCoordinate;
template<typename T>
std::ostream& operator<<(std::ostream& outStrm, const CylindricalCoordinate<T>& value )
{
outStrm << "( " << value.X() << " , " << value.Y() << " , " << value.Z() << ")";
return outStrm;
}
template<typename T>
class CylindricalCoordinate : public GeometricComponents::SpatialVector<T>
{
public:
T X() = delete;
T Y() = delete;
CylindricalCoordinate(const CartesianCoordinate<T>& inCoord)
{
SetFromCartesian(inCoord);
}
CylindricalCoordinate(const CylindricalCoordinate<T>& inCoord)
{
SetFromCylindrical(inCoord);
}
CylindricalCoordinate(T R, T Theta, T Z)
{
this->SetR(R);
this->SetTheta(Theta);
this->SetZ(Z);
}
CylindricalCoordinate(const GeometricComponents::SpatialVector<T>& arg)
: CylindricalCoordinate(std::get<0>(arg), std::get<1>(arg), std::get<2>(arg))
{
}
CylindricalCoordinate()
{
}
virtual ~CylindricalCoordinate()
{
}
T const R() const
{
return std::get<0>(*this);
}
T const Theta() const
{
return std::get<1>(*this);
}
T const Z() const
{
return std::get<2>(*this);
}
void SetR(const T inR)
{
(*this)[0] = inR;
}
void SetTheta(const T inTheta)
{
(*this)[1] = inTheta;
}
void SetZ(const T inZ)
{
(*this)[2] = inZ;
}
void SetFromCartesian(const CartesianCoordinate<T>& inCoord)
{
CartesianToCylindrical(inCoord, *this);
}
void SetFromCylindrical(const CylindricalCoordinate<T>& inCoord)
{
SetR(inCoord.R());
SetTheta(inCoord.Theta());
SetZ(inCoord.Z());
}
CartesianCoordinate<T>* GenerateCartesianCoordinate()
{
CartesianCoordinate<T>* outCoordinate = new CartesianCoordinate<T>();
CylindricalToCartesian(*this, *outCoordinate);
return (outCoordinate);
}
friend std::ostream& operator<< <T>(std::ostream& outStrm, const CylindricalCoordinate<T>& value);
};
} /* namespace CoordinateComponents */
#endif /* CYLINDRICALCOORDINATE_H_ */
|
#include<iostream>
#include<queue>
#include<string.h>
#include<vector>
#define MAX 51
using namespace std;
int d[MAX][MAX];
bool visit[MAX][MAX];
typedef struct {
int x;
int y;
}Point;
vector<Point> list;
int w, h;
int xy[8][2] = { {-1, 0}, { 1, 0 }, { 0, -1 }, { 0, 1 }
,{ -1, -1 } ,{ 1, 1 },{ -1, 1 },{ 1, -1 } };
void bfs(int x, int y) {
queue<Point> q;
q.push({ x,y });
visit[y][x] = true;
while (!q.empty()) {
Point p = q.front();
q.pop();
for (int i = 0; i < 8; i++) {
Point next = { p.x + xy[i][0], p.y + xy[i][1] };
if (next.x<0 || next.x>=w || next.y<0 || next.y>=h) continue;
if (visit[next.y][next.x] == false && d[next.y][next.x] == 1) {
visit[next.y][next.x] = true;
q.push({ next.x, next.y });
}
}
}
}
int main() {
//int w, h;
int n;
int cnt = 0;
queue<Point> empty;
while (true) {
cin >> w >> h;
if (w == 0 && h == 0) break;
list.clear();
memset(d, 0, sizeof(d));
memset(visit, false, sizeof(visit));
cnt = 0;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
cin >> n;
d[i][j] = n;
if (n == 1) list.push_back({ j, i });
}
}
if (list.size() == 0) {
cout << 0 << endl;
continue;
}
for (int i = 0; i < list.size(); i++) {
Point cur = list[i];
if (visit[cur.y][cur.x] == false) {
bfs(cur.x, cur.y);
cnt++;
}
}
cout << cnt << endl;
}
return 0;
}
|
#include "pch.h"
#include "Color.h"
using namespace GameEngine;
Color::Color(float r, float g, float b, float a)
{
R = r;
G = g;
B = b;
A = a;
}
uint32_t Color::ToUInt32() const
{
uint32_t r = (uint32_t)(R * 255.0f);
uint32_t g = (uint32_t)(G * 255.0f);
uint32_t b = (uint32_t)(B * 255.0f);
uint32_t a = (uint32_t)(A * 255.0f);
return (a << 24) | (r << 16) | (g << 8) | b;
}
ByteColor Color::ToByte() const
{
return ByteColor((byte)(255 * R), (byte)(255 * G), (byte)(255 * B), (byte)(255 * A));
}
Color Color::operator + (const Color &c) const
{
return Color(R + c.R, G + c.G, B + c.B, A + c.A);
}
Color Color::operator - (const Color &c) const
{
return Color(R - c.R, G - c.G, B - c.B, A - c.A);
}
Color Color::operator * (float f) const
{
return Color(R * f, G * f, B * f, A);
}
Color Color::operator* (const Color &c) const
{
return Color(R * c.R, G * c.G, B * c.B, A * c.A);
}
|
#include "utils.h"
using namespace wheel;
int main() {
std::vector<std::string> strVec;
std::string str = "HELLO TOYOTA|HELLO TOYODA|HELLO TOYO";
std::string pattern = "|";
Utils* u = new Utils();
strVec = u->split(str, pattern);
std::cout<<"Utils::split test: "<<std::endl;
for(auto iter: strVec) {
std::cout<<" "<<iter <<std::endl;
}
delete u;
return 0;
}
|
#include <cstdio>
const int MAXN = 2000;
int main() {
int a = 0,
b = 0,
i = 0,
result[MAXN] = {0};
int len = 0;
int tmp = 0;
bool isZero = true;
// 无须腾出空格
while(scanf("%d%d", &a, &b) != EOF) {
if(b != 0) {
result[i++] = a * b;
result[i++] = b - 1;
if(b-1 != 0)
isZero = false;
}
}
if(isZero == true) {
printf("0 0");
return 0;
}
for(len = i, i = 0; i < len; i++) {
printf("%d", result[i]);
if(i < len-1) {
printf(" ");
}
}
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
freopen("page.txt", "r", stdin);
int frames;
while (cin >> frames)
{
int n = 0, h;
vector<int> arr;
while (cin >> h)
{
if (h == -1)
break;
arr.push_back(h);
++n;
}
int uu = 0;
int uu2 = 0;
int house[500][500] = {0}, current[500];
for (int t = 0; t < 500; t++)
for (int y = 0; y < 500; y++)
house[t][y] = -1;
int time[500] = {0};
for (int t = 0; t < 500; t++)
{
time[t] = 0;
current[t] = -2;
}
for (int e = 0; e < n; e++)
{
int a = arr[e];
int maxx = -99999999, pos;
int zz = -1;
for (int q = 0; q < frames; q++)
{
if (arr[e] == current[q])
{
time[q] = 1;
zz = 1;
}
}
if (zz == 1)
{
++uu;
continue;
}
for (int w = 0; w < frames; w++)
{
if (time[w] > maxx)
{
maxx = time[w];
pos = w;
}
time[w] += 1;
}
current[pos] = arr[e];
++uu2;
time[pos] = 0;
for (int w = 0; w < frames; w++)
house[w][e] = current[w];
}
for (int e = 0; e < frames; e++)
{
for (int v = 0; v < n; v++)
{
if (house[e][v] == -2)
{
house[e][v] = 0;
cout << house[e][v] << " ";
}
else if (house[e][v] == -1)
cout << " ";
else
cout << house[e][v] << " ";
}
cout << endl;
}
cout << "NO OF HITS=" << uu;
cout << endl;
cout << "NO OF FAULTS=" << uu2;
cout << endl;
}
}
|
#include "RectF.h"
RectF::RectF()
{
}
RectF::RectF(float left, float top, float right, float bottom)
{
this->left = left;
this->top = top;
this->right = right;
this->bottom = bottom;
}
RectF::RectF(RectF * r)
{
if (r == NULL)
{
left = top = right = bottom = 0.0f;
}
else
{
left = r->left;
top = r->top;
right = r->right;
bottom = r->bottom;
}
}
RectF::RectF(Rect *r)
{
if (r == NULL)
{
left = top = right = bottom = 0.0f;
}
else
{
left = (float)(r->left);
top = (float)(r->top);
right = (float)(r->right);
bottom = (float)(r->bottom);
}
}
bool RectF::isEmpty()
{
return left >= right || top >= bottom;
}
float RectF::width()
{
return right - left;
}
float RectF::height()
{
return bottom - top;
}
float RectF::centerY()
{
return (top + bottom) * 0.5f;
}
void RectF::setEmpty()
{
left = right = top = bottom = 0;
}
void RectF::set(float left, float top, float right, float bottom)
{
this->left = left;
this->top = top;
this->right = right;
this->bottom = bottom;
}
void RectF::set(RectF src)
{
this->left = src.left;
this->top = src.top;
this->right = src.right;
this->bottom = src.bottom;
}
void RectF::set(Rect src)
{
this->left = (float)(src.left);
this->top = (float)(src.top);
this->right = (float)(src.right);
this->bottom = (float)(src.bottom);
}
void RectF::offset(float dx, float dy)
{
left += dx;
top += dy;
right += dx;
bottom += dy;
}
void RectF::offsetTo(float newLeft, float newTop)
{
right += newLeft - left;
bottom += newTop - top;
left = newLeft;
top = newTop;
}
void RectF::inset(float dx, float dy)
{
left += dx;
top += dy;
right -= dx;
bottom -= dy;
}
bool RectF::contains(float x, float y)
{
return left < right && top < bottom // check for empty first
&& x >= left && x < right && y >= top && y < bottom;
}
bool RectF::contains(float left, float top, float right, float bottom)
{
// check for empty first
return this->left < this->right && this->top < this->bottom
// now check for containment
&& this->left <= left && this->top <= top
&& this->right >= right && this->bottom >= bottom;
}
bool RectF::contains(RectF * r)
{
// check for empty first
return this->left < this->right && this->top < this->bottom
// now check for containment
&& left <= r->left && top <= r->top
&& right >= r->right && bottom >= r->bottom;
}
bool RectF::intersect(float left, float top, float right, float bottom)
{
if (this->left < right && left < this->right
&& this->top < bottom && top < this->bottom)
{
if (this->left < left)
{
this->left = left;
}
if (this->top < top)
{
this->top = top;
}
if (this->right > right)
{
this->right = right;
}
if (this->bottom > bottom)
{
this->bottom = bottom;
}
return true;
}
return false;
}
bool RectF::intersect(RectF * r)
{
return intersect(r->left, r->top, r->right, r->bottom);
}
bool RectF::setIntersect(RectF a, RectF b)
{
if (a.left < b.right && b.left < a.right
&& a.top < b.bottom && b.top < a.bottom)
{
left = (std::max)(a.left, b.left);
top = (std::max)(a.top, b.top);
right = (std::min)(a.right, b.right);
bottom = (std::min)(a.bottom, b.bottom);
return true;
}
return false;
}
bool RectF::intersects(float left, float top, float right, float bottom)
{
return this->left < right && left < this->right
&& this->top < bottom && top < this->bottom;
}
bool RectF::intersects(RectF a, RectF b)
{
return a.left < b.right && b.left < a.right
&& a.top < b.bottom && b.top < a.bottom;
}
void RectF::_union(float left, float top, float right, float bottom)
{
if ((left < right) && (top < bottom))
{
if ((this->left < this->right) && (this->top < this->bottom))
{
if (this->left > left)
this->left = left;
if (this->top > top)
this->top = top;
if (this->right < right)
this->right = right;
if (this->bottom < bottom)
this->bottom = bottom;
}
else
{
this->left = left;
this->top = top;
this->right = right;
this->bottom = bottom;
}
}
}
void RectF::_union(RectF * r)
{
_union(r->left, r->top, r->right, r->bottom);
}
void RectF::_union(float x, float y)
{
if (x < left)
{
left = x;
}
else if (x > right)
{
right = x;
}
if (y < top)
{
top = y;
}
else if (y > bottom)
{
bottom = y;
}
}
void RectF::sort()
{
if (left > right)
{
float temp = left;
left = right;
right = temp;
}
if (top > bottom)
{
float temp = top;
top = bottom;
bottom = temp;
}
}
int RectF::describeContents()
{
return 0;
}
|
#include "StdAfx.h"
#include "BRenderer.h"
#include "BViewport.h"
#include "BDriver.h"
#include "BCamera.h"
#include "BRenderPass.h"
#include "BRenderingBatch.h"
#include "InputDefine.h"
#include "UWorld.h"
#include "CWindowsApplication.h"
#include "CWindowsViewport.h"
#include "RResourceManager.h"
CWindowsApplication* CWindowsApplication::StaticThis = 0;
SYSTEM_INFO GSystemInformation;
unsigned char GKeyMap[KEYMAP_SIZE] = { 0, };
CWindowsApplication::CWindowsApplication() {
StaticThis = this;
m_MouseMap.bLButtonDown = 0;
m_MouseMap.bRButtonDown = 0;
m_MouseMap.bMButtonDown = 0;
GetSystemInfo(&GSystemInformation);
m_pRenderer = 0;
}
BViewport* CWindowsApplication::FindViewport(HWND hWnd) {
for(unsigned int i=0;i<Worlds.Size();++i) {
BViewport* Viewport = Worlds(i)->FindViewport(hWnd);
if(Viewport) {
return Viewport;
}
}
return 0;
}
bool CWindowsApplication::CreateApplicationWindow(TApplicationInfo& Info) {
m_WindowInfo = (TWindowInfo&) Info;
m_WindowInfo.m_hInstance = GetModuleHandle(NULL);
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = Proc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = m_WindowInfo.m_hInstance;
wcex.hIcon = LoadIcon(m_WindowInfo.m_hInstance, 0);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wcex.lpszMenuName = 0;
wcex.lpszClassName = _T("CLASS NAME");
wcex.hIconSm = LoadIcon(m_WindowInfo.m_hInstance, 0);
RegisterClassEx(&wcex);
m_WindowInfo.m_hWnd = ::CreateWindow(
_T("CLASS NAME"),
_T("CAPTION"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
m_WindowInfo.m_wWidth + 14,
m_WindowInfo.m_wHeight + 36,
NULL,
0,
m_WindowInfo.m_hInstance,
0);
ShowWindow(m_WindowInfo.m_hWnd, SW_SHOW);
UpdateWindow(m_WindowInfo.m_hWnd);
GDriver->CreateDriver(this);
m_pRenderer = new BRenderer(this);
RResourceManager::LoadResources();
GRenderPassResource.Initialize(m_WindowInfo.m_wWidth, m_WindowInfo.m_wHeight);
bRenderThreadQuit = false;
m_pRenderer->Start();
return true;
}
bool CWindowsApplication::DestroyApp() {
delete m_pRenderer;
m_pRenderer = 0;
RResourceManager::ReleaseAllResources();
return true;
}
void CWindowsApplication::Do() {
static bool initialized = false;
if(!initialized) {
Worlds(0)->Viewports.AddItem(new CWindowsViewport(m_WindowInfo.m_wWidth, m_WindowInfo.m_wHeight, Projection_Perpective, RenderMode_All, CameraMode_ThridPerson, m_WindowInfo.m_hWnd));
Worlds(0)->Viewports(0)->Camera->m_Subject = ((TWorldOctree*)Worlds(0)->m_pWorldData)->AllObjects(0);
initialized = true;
}
MSG msg;
int Count = 0;
DWORD PrevTime = timeGetTime();
while (!bQuit) {
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
if (msg.message == WM_QUIT || GKeyMap[VK_ESCAPE]) {
bQuit = true;
break;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
} else {
if ((timeGetTime() - PrevTime) > 16) {
Tick(timeGetTime() - PrevTime);
PrevTime = timeGetTime();
m_pRenderer->ThreadExecute();
}
}
//Sleep(1);
}
//while(!bRenderThreadQuit);
}
bool CWindowsApplication::Tick(unsigned long Time) {
for(unsigned int i=0;i<Worlds.Size();++i) {
UWorld* World = Worlds(i);
World->Tick(Time);
}
return true;
}
void CWindowsApplication::SetMousePos(float X, float Y, bool isRatio) {
POINT MousePt;
if (isRatio) {
RECT rt;
::GetClientRect(m_WindowInfo.m_hWnd, &rt);
MousePt.x = (LONG)(X * (rt.right - rt.left));
MousePt.y = (LONG)(Y * (rt.bottom - rt.top));
} else {
MousePt.x = (LONG) X;
MousePt.y = (LONG) Y;
}
m_MousePt.x = MousePt.x;
m_MousePt.y = MousePt.y;
::ClientToScreen(m_WindowInfo.m_hWnd, &MousePt);
::SetCursorPos((int) MousePt.x, (int) MousePt.y);
}
void CWindowsApplication::MouseEventTranslator(BViewport* Viewport, UINT Message, WPARAM wParam, LPARAM lParam) {
TMouseInput_Param Param;
Param.bLButtonDown = m_MouseMap.bLButtonDown;
Param.bRButtonDown = m_MouseMap.bRButtonDown;
Param.bMButtonDown = m_MouseMap.bMButtonDown;
Param.X = LOWORD(lParam);
Param.Y = HIWORD(lParam);
if (m_MousePt.x)
Param.dX = m_MousePt.x - Param.X;
else
Param.dX = 0;
if (m_MousePt.y)
Param.dY = m_MousePt.y - Param.Y;
else
Param.dY = 0;
m_MousePt.x = Param.X;
m_MousePt.y = Param.Y;
EMouse_Event Event;
switch (Message) {
case WM_LBUTTONDBLCLK:
Event = MOUSE_LeftButtonDblClk;
break;
case WM_RBUTTONDBLCLK:
Event = MOUSE_RightButtonDblClk;
break;
case WM_MBUTTONDBLCLK:
Event = MOUSE_MiddleButtonDblClk;
break;
case WM_LBUTTONDOWN:
m_MouseMap.bLButtonDown = true;
Event = MOUSE_LeftButtonDown;
break;
case WM_RBUTTONDOWN:
m_MouseMap.bRButtonDown = true;
Event = MOUSE_RightButtonDown;
break;
case WM_MBUTTONDOWN:
m_MouseMap.bMButtonDown = true;
Event = MOUSE_MiddleButtonDown;
break;
case WM_LBUTTONUP:
m_MouseMap.bLButtonDown = false;
Event = MOUSE_LeftButtonUp;
break;
case WM_RBUTTONUP:
m_MouseMap.bRButtonDown = false;
Event = MOUSE_RightButtonUp;
break;
case WM_MBUTTONUP:
m_MouseMap.bMButtonDown = false;
Event = MOUSE_MiddleButtonUp;
break;
case WM_MOUSEWHEEL:
Param.delta = -HIWORD(wParam);
Event = MOUSE_Wheel;
break;
case WM_MOUSEMOVE:
Event = MOUSE_Move;
break;
default:
return;
}
InputMouse(Viewport, Event, Param);
}
void CWindowsApplication::KeyEventTranslator(BViewport* Viewport, UINT Message, WPARAM wParam, LPARAM lParam) {
TKeyInput_Param Param;
Param.Key = (unsigned short) wParam;
EKey_Event Event;
switch (Message) {
case WM_KEYDOWN:
Event = KEY_Down;
break;
case WM_KEYUP:
Event = KEY_Up;
break;
}
InputKey(Viewport, Event, Param);
}
void CWindowsApplication::InputMouse(BViewport* Viewport, EMouse_Event Event, TMouseInput_Param& Param) {
for(unsigned int i=0;i<Worlds.Size();++i) {
UWorld* World = Worlds(i);
World->InputMouse(Event, Param);
}
Viewport->InputMouse(Event, Param);
}
void CWindowsApplication::InputKey(BViewport* Viewport, EKey_Event Event, TKeyInput_Param& Param) {
switch(Event) {
case KEY_Down:
GKeyMap[Param.Key] = 0x01;
break;
case KEY_Up:
GKeyMap[Param.Key] = 0x00;
break;
}
for(unsigned int i=0;i<Worlds.Size();++i) {
UWorld* World = Worlds(i);
World->InputKey(Event, Param);
}
Viewport->InputKey(Event, Param);
}
void CWindowsApplication::MessageTranslator(HWND Handle, UINT Message, WPARAM wParam, LPARAM lParam) {
switch (Message) {
case WM_SIZE:
for(unsigned int i=0;i<Worlds.Size();++i) {
Worlds(i)->OnViewportsResized();
}
break;
case WM_MOUSEWHEEL:
RECT rt;
GetClientRect(Handle, &rt);
ClientToScreen(Handle, reinterpret_cast<POINT*>(&rt.left));
lParam -= rt.left;
lParam -= (rt.top << (sizeof(WORD)*8));
case WM_LBUTTONDBLCLK:
case WM_RBUTTONDBLCLK:
case WM_MBUTTONDBLCLK:
case WM_LBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_LBUTTONUP:
case WM_RBUTTONUP:
case WM_MBUTTONUP:
case WM_MOUSEMOVE:
MouseEventTranslator(FindViewport(Handle), Message, wParam, lParam);
break;
case WM_KEYDOWN:
case WM_KEYUP:
KeyEventTranslator(FindViewport(Handle), Message, wParam, lParam);
break;
}
}
LRESULT CALLBACK CWindowsApplication::Proc(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) {
switch (Message) {
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
if (StaticThis)
StaticThis->MessageTranslator(hWnd, Message, wParam, lParam);
return DefWindowProc(hWnd, Message, wParam, lParam);
}
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int change(int amount, vector<int> &coins)
{
if (amount == 0)
return 1;
int ssize = coins.size();
vector<vector<int>> dp(ssize + 1, vector<int>(amount + 1, 0));
for (int i = 0; i <= ssize; i++)
dp[i][0] = 1;
for (int i = 1; i <= amount; i++)
dp[0][i] = 0;
for (int i = 1; i <= ssize; i++)
{
for (int j = 1; j <= amount; j++)
{
dp[i][j] = dp[i - 1][j];
if (j >= coins[i - 1])
for (int k = 1; k <= j / coins[i - 1]; k++)
dp[i][j] += dp[i - 1][j - k * coins[i - 1]];
}
}
return dp[ssize][amount];
}
};
|
///
/// \file expression.h
/// \brief Déclare la classe Expression
///
/// La classe Expression est abstraite
///
#ifndef EXPRESSION_H
#define EXPRESSION_H
#include "../headers/computer.h"
/*_______________ Expression ________________
Interface de toute expression existante
dans le programme. Toute expression est
construite par l'ExpressionManager qui
est chargé de réugler le cycle de vie
d'une expression. La pile du programme
est composée d'une QStack<Expression*>
*/
///
/// \class Expression
/// \brief Classe abstraite de tout type d'Expression
///
/// Interface de toute expression existante dans le programme
/// Toute expression est construite par l'ExpressionManager qui est chargé de réguler le cycle de vie d'une Expression
/// L'amitié avec l'ExpressionManager permet que lui seul puisse créer des Expression
///
class Expression {
friend class ExpressionManager;
private:
///
/// \brief Constructeur de copie
/// \deprecated N'est pas implémenté
/// \param e : L'Expression à copier
///
Expression(const Expression& e);
///
/// \brief Operateur d'affectation
/// \deprecated N'est pas implémenté
/// \param e : L'Expression à affecter
/// \return Retourne une référence sur l'Expression elle-même
///
Expression& operator=(const Expression& e);
protected:
///
/// \brief Constructeur de Expression
///
Expression() {}
///
/// \brief Destructeur de Expression
///
virtual ~Expression() {}
public:
///
/// \brief Retourne la chaîne de caractères représentative de l'Expression
/// Méthode virtuelle pure implémentée dans les classes filles
/// \return Retourne une chaîne de caractères qui permet de recréer exactement la même Expression via la méthode ExpressionManager::addExpression(QString c)
///
virtual QString toString() const = 0;
///
/// \brief L'Expression peut-elle être poussée sur la Pile
/// \return true si l'Expression peut être poussée sur la pile
/// false si la pile doit plutôt l'évaluer
///
virtual bool isPushable() const = 0;
};
#endif // EXPRESSION_H
|
#include "pixel.h"
Pixel::Pixel (uint16_t x_, uint16_t y_, const uint16_t color_)
:x(x_), y (y_), color (color_)
{
}
void Pixel::draw () const
{
displayDriver->pixel(x,y,color);
}
void Pixel::setPosition (uint16_t x_, uint16_t y_)
{
x = x_;
y = y_;
}
|
#pragma once
#include <string>
#include <cstdio>
#include <cstring>
#include <iostream>
#include "JsonLog.h"
#include "JObject.h"
class JSONDocument {
private:
static bool is_special(char c);
static bool is_ws(char c);
static bool is_num(char* str);
public:
static JObject* parseFromFile(const std::string& path);
static JObject* parse(const std::string& src);
};
|
/*****************************************************************
* Filename: main.cpp
*
* Author: Patrick Cook
* Start Date: 9-23-2020
*
* Description: QApplication which instantiates and displays the game
* window.
*
*****************************************************************/
#include <QApplication>
#include "game.h"
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
Game w;
w.show();
return a.exec();
}
|
#ifndef ZDDTOPDOWN_H
#define ZDDTOPDOWN_H
/// @file ZddTopDown.h
/// @brief ZddTopDown のヘッダファイル
/// @author Yusuke Matsunaga (松永 裕介)
///
/// Copyright (C) 2005-2012 Yusuke Matsunaga
/// All rights reserved.
#include "YmLogic/Zdd.h"
#include "YmLogic/ZddMgr.h"
#include "YmNetworks/bdn.h"
BEGIN_NAMESPACE_YM
//////////////////////////////////////////////////////////////////////
/// @class ZddTopDown ZddTopDown.h "ZddTopDown.h"
/// @brief ZDD を用いた非明示的列挙を行うクラス
//////////////////////////////////////////////////////////////////////
class ZddTopDown
{
public:
/// @brief コンストラクタ
/// @param[in] mgr
ZddTopDown(ZddMgr& mgr);
/// @brief デストラクタ
~ZddTopDown();
public:
/// @brief カット列挙を行う.
/// @param[in] network 対象のネットワーク
/// @param[in] limit カットサイズの制限
void
operator()(BdnMgr& network,
ymuint limit);
private:
Zdd
dfs(const BdnNode* node,
const Zdd& cut);
private:
//////////////////////////////////////////////////////////////////////
// 内部で用いられるデータ構造
//////////////////////////////////////////////////////////////////////
struct NodeTemp
{
// カット集合
Zdd mCut;
// footprint ノード
vector<ymuint> mFpNodeList;
// 作業領域
ymuint32 mMark;
};
private:
//////////////////////////////////////////////////////////////////////
// データメンバ
//////////////////////////////////////////////////////////////////////
// マネージャ
ZddMgr& mMgr;
// ノードの情報
vector<NodeTemp> mNodeTemp;
};
END_NAMESPACE_YM
#endif // ZDDTOPDOWN_H
|
#pragma once
#include <vector>
#include <algorithm>
#include <sstream>
namespace Poker
{
enum class Suit { suit_unknown, suit_diamonds, suit_clubs, suit_hearts, suit_spades };
enum class CardSource { source_unknown, source_from_player, source_from_board };
// -------------------------------------------------------------------------------------------------------
class PlayingCard
{
protected:
unsigned int m_rank; // A=1(low),2,3,4,5,6,7,8,9,T=10,J=11,Q=12,K=13,A=14(high)
Suit m_suit; // d,c,h,s
public:
PlayingCard() : m_rank(0), m_suit(Suit::suit_unknown) { }
PlayingCard(const std::string&);
PlayingCard(const PlayingCard& other) : m_rank(other.m_rank), m_suit(other.m_suit) { }
PlayingCard& operator= (const PlayingCard& rValue)
{
m_rank = rValue.m_rank; m_suit = rValue.m_suit;
return *this;
}
virtual bool operator == (const PlayingCard& rValue) const { return m_rank == rValue.m_rank && m_suit == rValue.m_suit; }
virtual bool operator != (const PlayingCard& rValue) const { return m_rank != rValue.m_rank || m_suit != rValue.m_suit; }
virtual std::string ToString() const;
unsigned int GetCardRank() const { return m_rank; }
Suit GetSuit() const { return m_suit; }
bool empty() const { return m_rank ? false : true; }
};
inline std::ostream& operator<<(std::ostream& out, const PlayingCard& c) { return out << c.ToString(); }
// -------------------------------------------------------------------------------------------------------
class PokerCard : public PlayingCard
{
protected:
CardSource m_source;
public:
PokerCard() : PlayingCard(), m_source(CardSource::source_unknown) { }
PokerCard(std::string r) : PlayingCard(r), m_source(CardSource::source_unknown) { }
PokerCard(const PokerCard& other) : PlayingCard(other), m_source(other.m_source) { }
PokerCard& operator= (const PokerCard& rValue)
{
m_rank = rValue.m_rank; m_suit = rValue.m_suit; m_source = rValue.m_source;
return *this;
}
void transformForLow8() { m_suit = Suit::suit_unknown; if ( m_rank == 14 ) m_rank = 1; }
void AceToLowestCard() { if ( m_rank == 14 ) m_rank = 1; }
void SetAsFromPlayer() { m_source = CardSource::source_from_player; }
void SetAsFromBoard() { m_source = CardSource::source_from_board; }
CardSource GetCardSource() const { return m_source; }
bool IsLow8() const { return m_rank <= 8; }
bool HasSuit() const { return m_suit != Suit::suit_unknown; }
virtual bool operator == (const PokerCard& rValue) const { return m_rank == rValue.m_rank; }
virtual bool operator != (const PokerCard& rValue) const { return m_rank != rValue.m_rank; }
virtual bool operator > (const PokerCard& rValue) const { return m_rank > rValue.m_rank; }
virtual bool operator < (const PokerCard& rValue) const { return m_rank < rValue.m_rank; }
virtual bool operator >= (const PokerCard& rValue) const { return m_rank >= rValue.m_rank; }
virtual bool operator <= (const PokerCard& rValue) const { return m_rank <= rValue.m_rank; }
};
using PokerCardArray = std::vector<PokerCard>;
// -------------------------------------------------------------------------------------------------------
class PokerCardSet
{
protected:
PokerCardArray m_cards;
std::string m_set_name;
private:
static bool notQualifyForLow8(PokerCard c) { return !c.IsLow8(); }
public:
PokerCardSet() { }
PokerCardSet(const PokerCardArray& ar) : m_cards(ar) { }
PokerCardSet(const std::string&);
PokerCardSet(const PokerCardSet& other) : m_cards(other.m_cards), m_set_name(other.m_set_name) { }
~PokerCardSet() { }
virtual std::string ToString() const;
unsigned int Cards() const { return m_cards.size(); }
std::string GetName() const { return m_set_name; }
void SetName(std::string& s) { m_set_name = s; }
const PokerCardArray& GetCards() const { return m_cards; }
const PokerCard& operator [] (PokerCardArray::size_type i) const { return m_cards[i]; }
PokerCardSet& operator= (const PokerCardSet& rValue)
{
m_cards = rValue.m_cards; m_set_name = rValue.m_set_name;
return *this;
}
PokerCardSet& operator + (const PokerCardSet& rValue)
{
m_cards.insert(m_cards.end(), rValue.m_cards.begin(), rValue.m_cards.end());
return *this;
}
bool operator == (const PokerCardSet& rValue) const { return Cards() == rValue.Cards() && m_cards == rValue.m_cards; }
bool operator > (const PokerCardSet& rValue) const { return Cards() == rValue.Cards() && m_cards > rValue.m_cards; }
bool operator < (const PokerCardSet& rValue) const { return Cards() == rValue.Cards() && m_cards < rValue.m_cards; }
void SortSet() { sort(m_cards.begin(), m_cards.end(), std::greater<PokerCard>()); }
bool InConsecutiveOrder() const
{
PokerCardArray::const_iterator first = m_cards.begin(), next = m_cards.begin(); ++next;
while ( next != m_cards.end() )
{
if ( first->GetCardRank() - next->GetCardRank() != 1 ) return false;
++first; ++next;
}
return true;
}
bool AllCardsOfTheSameSuit() const
{
if ( Cards() < 2 ) return true;
Suit s = m_cards[0].GetSuit();
for(PokerCardArray::size_type i = 1; i < Cards(); i++)
if ( s != m_cards[i].GetSuit() ) return false;
return true;
}
void MakeLow8()
{
for(PokerCardArray::iterator pos = m_cards.begin(); pos != m_cards.end(); ++pos)
pos->transformForLow8();
PokerCardArray::iterator it = remove_if(m_cards.begin(), m_cards.end(), PokerCardSet::notQualifyForLow8);
sort(m_cards.begin(), it);
m_cards.resize( distance(m_cards.begin(), unique(m_cards.begin(), it) ) );
}
void MoveFirstCardToTheEnd()
{
PokerCard c = m_cards[0];
for(PokerCardArray::size_type i = 1; i < Cards(); i++)
m_cards[i-1] = m_cards[i];
m_cards[Cards()-1] = c;
}
bool MakeStraightFlush();
bool Make4ofKind();
bool MakeFullHouse();
bool MakeFlush();
bool MakeStraight();
bool Make3ofKind();
bool MakeTwoPair();
bool MakeOnePair();
};
inline std::ostream& operator<<(std::ostream& out, const PokerCardSet& cs) { return out << cs.ToString(); }
// -------------------------------------------------------------------------------------------------------
class PokerPlayerCards : public PokerCardSet
{
public:
PokerPlayerCards() { }
PokerPlayerCards(const std::string& s) : PokerCardSet(s)
{
for(PokerCardArray::iterator pos = m_cards.begin(); pos != m_cards.end(); ++pos)
pos->SetAsFromPlayer();
}
};
class PokerBoardCards : public PokerCardSet
{
public:
PokerBoardCards() { }
PokerBoardCards(const std::string& s) : PokerCardSet(s)
{
for(PokerCardArray::iterator pos = m_cards.begin(); pos != m_cards.end(); ++pos)
pos->SetAsFromBoard();
}
};
// -------------------------------------------------------------------------------------------------------
class PokerHand : public PokerCardSet // Abstract Class
{
protected:
std::string m_rank_name;
public:
std::string GetRankName() const { return m_rank_name; }
virtual bool operator == (const PokerHand& rValue) const
{ return qualified() && rValue.qualified() && m_cards == rValue.m_cards; }
virtual bool operator > (const PokerHand& rValue) const
{ return qualified() && rValue.qualified() && m_cards > rValue.m_cards; }
virtual bool qualified() const { return Cards() == 5; }
virtual unsigned int GetRank() const { return 0; }
virtual std::string ObjectSuffix() const=0;
};
/* -------------------------------------------------------------------------------------------------------
9 - Straight Flush: Five cards in sequence, of the same suit. (A,K,Q,J,10 is known as a Royal Flush)
8 - Four of a Kind: Four cards of the same rank, and one side card or 'kicker'.
7 - Full House: Three cards of the same rank, and two cards of a different, matching rank.
6 - Flush: Five cards of the same suit.
5 - Straight: Five cards in sequence.
4 - Three of a kind: Three cards of the same rank, and two unrelated side cards.
3 - Two pair: Two cards of a matching rank, another two cards of a different matching rank, and one side card.
2 - One pair: Two cards of a matching rank, and three unrelated side cards.
1 - High card: Any hand that does not qualify under a category listed above.
*/
class PokerHandHigh : public PokerHand
{
protected:
unsigned int m_hand_rank;
public:
PokerHandHigh(PokerPlayerCards, PokerBoardCards);
PokerHandHigh(const PokerHandHigh& other) : m_hand_rank(other.m_hand_rank)
{
m_rank_name = other.m_rank_name;
m_cards = other.m_cards;
m_set_name = other.m_set_name;
}
PokerHandHigh& operator= (const PokerHandHigh& rValue)
{
m_hand_rank = rValue.m_hand_rank;
m_rank_name = rValue.m_rank_name;
m_cards = rValue.m_cards;
m_set_name = rValue.m_set_name;
return *this;
}
static std::string GetRankNameForHighHand(unsigned int);
virtual std::string ToString() const;
virtual unsigned int GetRank() const { return m_hand_rank; }
virtual std::string ObjectSuffix() const { return std::string("Hi"); }
virtual bool operator == (const PokerHand& rValue) const
{ return m_hand_rank == rValue.GetRank() && m_cards == rValue.GetCards(); }
virtual bool operator > (const PokerHand& rValue) const
{ return m_hand_rank > rValue.GetRank() || m_hand_rank == rValue.GetRank() && m_cards > rValue.GetCards(); }
};
/* -------------------------------------------------------------------------------------------------------
10 - 5, 4, 3, 2, A
9 - 6, 4, 3, 2, A
8 - 6, 5, 4, 3, 2
7 - 7, 5, 4, 3, 2
6 - 7, 6, 5, 2, A
5 - 7, 6, 5, 4, 2
4 - 8, 4, 3, 2, A
3 - 8, 6, 4, 2, A
2 - 8, 7, 6, 5, 3
1 - 8, 7, 6, 5, 4
0 - Cannot qualify for Low
*/
class PokerHandLow : public PokerHand
{
bool m_qualified;
public:
PokerHandLow(PokerPlayerCards, PokerBoardCards);
PokerHandLow(const PokerHandLow& other) : m_qualified(other.m_qualified)
{
m_rank_name = other.m_rank_name;
m_cards = other.m_cards;
m_set_name = other.m_set_name;
}
PokerHandLow& operator= (const PokerHandLow& rValue)
{
m_qualified = rValue.m_qualified;
m_rank_name = rValue.m_rank_name;
m_cards = rValue.m_cards;
m_set_name = rValue.m_set_name;
return *this;
}
virtual bool qualified() const { return m_qualified; }
virtual std::string ObjectSuffix() const { return std::string("Lo"); }
virtual bool operator > (const PokerHand& rValue) const
{ return m_qualified && ( !rValue.qualified() || rValue.qualified() && m_cards < rValue.GetCards() ); }
};
} // End Namespace Poker
|
// Copyright 2020-2021 Russ 'trdwll' Treadwell <trdwll.com>. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Steam.h"
#include "SteamEnums.h"
#include "SteamStructs.h"
#include "UObject/NoExportTypes.h"
#include "SteamVideo.generated.h"
//DECLARE_DYNAMIC_MULTICAST_DELEGATE(FOnBroadcastUploadStartDelegate);
//DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnBroadcastUploadStopDelegate, ESteamResult, Result);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FOnGetOPFSettingsResultDelegate, ESteamResult, Result, int32, VideoAppID);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_ThreeParams(FOnGetVideoURLResultDelegate, ESteamResult, Result, int32, VideoAppID, FString, URL);
/**
* Provides functions to interface with the Steam video and broadcasting platforms.
* https://partner.steamgames.com/doc/api/ISteamVideo
*/
UCLASS()
class STEAMBRIDGE_API USteamVideo final : public UObject
{
GENERATED_BODY()
public:
USteamVideo();
~USteamVideo();
UFUNCTION(BlueprintPure, Category = "SteamBridgeCore", meta = (DisplayName = "Steam Video", CompactNodeTitle = "SteamVideo"))
static USteamVideo* GetSteamVideo() { return USteamVideo::StaticClass()->GetDefaultObject<USteamVideo>(); }
/**
* Get the OPF details for 360 video playback
* To retrieve the 360 OPF (open projection format) data to playback a 360 video, start by making a call to this, then the callback will indicate whether the request was successful. If it was successful, the
* actual OPF JSON data can be retrieved with a call to GetOPFStringForApp.
* Triggers a GetOPFSettingsResult_t callback.
*
* @param int32 VideoAppID - The video app ID to get the OPF details of.
* @return void
*/
UFUNCTION(BlueprintCallable, Category = "SteamBridgeCore|Video")
void GetOPFSettings(int32 VideoAppID) { SteamVideo()->GetOPFSettings(VideoAppID); }
/**
* Gets the OPF string for the specified video App ID.
* Once the callback for GetOPFSettingsResult_t has been raised and the EResult indicates success, then calling this will return back the actual OPF data in a JSON format. The size of the OPF string varies, but at
* this time 48,000 bytes should be sufficient to contain the full string. If it is not, pnBufferSize will be set to the size required. In that case, make a second call with the correct buffer size.
* NOTE: The data returned in a successful call to GetOPFStringForApp() can only be retrieved once. If you need to retrieve it multiple times, a call to GetOPFSettings will need to be made each time.
*
* @param int32 VideoAppID - The video app ID to get the OPF string for.
* @param FString & OPFString - Returns the OPF string by writing it to this buffer.
* @return bool - true if we have the OPF details from a previous call to GetOPFSettings, otherwise false.
*/
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "SteamBridgeCore|Video")
bool GetOPFStringForApp(int32 VideoAppID, FString& OPFString) const;
/**
* Asynchronously gets the URL suitable for streaming the video associated with the specified video app ID.
* Triggers a GetVideoURLResult_t callback.
*
* @param int32 VideoAppID - The video app ID to receive the video stream for.
* @return void
*/
UFUNCTION(BlueprintCallable, Category = "SteamBridgeCore|Video")
void GetVideoURL(int32 VideoAppID) { SteamVideo()->GetVideoURL(VideoAppID); }
/**
* Checks if the user is currently live broadcasting and gets the number of users.
*
* @param int32 & NumViewers - Returns the number of viewers currently watching the live broadcast.
* @return bool - true if user is uploading a live broadcast, otherwise false.
*/
UFUNCTION(BlueprintPure, Category = "SteamBridgeCore|Video")
bool IsBroadcasting(int32& NumViewers) { return SteamVideo()->IsBroadcasting(&NumViewers); }
/** Delegates */
/*UPROPERTY(BlueprintAssignable, Category = "SteamBridgeCore|Video", meta = (DisplayName = "OnBroadcastUploadStart"))
FOnBroadcastUploadStartDelegate m_OnBroadcastUploadStart;
UPROPERTY(BlueprintAssignable, Category = "SteamBridgeCore|Video", meta = (DisplayName = "OnBroadcastUploadStop"))
FOnBroadcastUploadStopDelegate m_OnBroadcastUploadStop;*/
/** Triggered when the OPF Details for 360 video playback are retrieved. After receiving this you can use GetOPFStringForApp to access the OPF details. */
UPROPERTY(BlueprintAssignable, Category = "SteamBridgeCore|Video", meta = (DisplayName = "OnGetOPFSettingsResult"))
FOnGetOPFSettingsResultDelegate m_OnGetOPFSettingsResult;
/** Provides the result of a call to GetVideoURL. */
UPROPERTY(BlueprintAssignable, Category = "SteamBridgeCore|Video", meta = (DisplayName = "OnGetVideoURLResult"))
FOnGetVideoURLResultDelegate m_OnGetVideoURLResult;
protected:
private:
/*STEAM_CALLBACK_MANUAL(USteamVideo, OnBroadcastUploadStart, BroadcastUploadStart_t, OnBroadcastUploadStartCallback);
STEAM_CALLBACK_MANUAL(USteamVideo, OnBroadcastUploadStop, BroadcastUploadStop_t, OnBroadcastUploadStopCallback);*/
STEAM_CALLBACK_MANUAL(USteamVideo, OnGetOPFSettingsResult, GetOPFSettingsResult_t, OnGetOPFSettingsResultCallback);
STEAM_CALLBACK_MANUAL(USteamVideo, OnGetVideoURLResult, GetVideoURLResult_t, OnGetVideoURLResultCallback);
};
|
#include "TransformCmp.h"
namespace cello
{
REGISTER_COMPONENT(TransformCmp, "transform")
TransformCmp::TransformCmp()
{
}
TransformCmp::~TransformCmp()
{
}
}
|
#include <stdio.h>
#include <unistd.h>
int main() {
fork();
fork();
fork();
printf("Good Bye\n");
return 0;
}
|
#pragma once
#include <string>
#include "Registry.h"
enum Type
{
Stream,
Char,
Period,
String
};
class Parser : public IRegistryEntry<Type>
{
public:
virtual const Type& getRegistryType() const = 0;
virtual std::string parse(std::string& str) = 0;
};
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QDebug>
#include <Qfile>
#include <fstream>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pb_abrirArchivo_clicked()
{
rutaArchivo = QFileDialog::getOpenFileName(
this, tr("Selecione el archivo :)"), "..//", "Text files (*.txt)");
QFile archivo(rutaArchivo);
if(!archivo.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream leer(&archivo);
QString aux;
leer >> aux;
elementos = aux.toInt();
leer >> aux;
atributos = aux.toInt();
leer >> aux;
clases = aux.toInt();
int row = 1;
while (!leer.atEnd()) {
QString plok;
leer >> plok;
QStringList lista = plok.split(',', QString::SkipEmptyParts);
qDebug() << "row " << row << "\n" << lista;
row++;
}
actualizarDatos();
}
void MainWindow::actualizarDatos()
{
ui->lb_numCol->setText(QString::number(atributos));
}
|
#include<bits/stdc++.h>
using namespace std;
void operation(string &s,int n)
{
for(int i=0;i<=n;i++)
{
if(s[i]=='1')s[i]='0';
else s[i]='1';
}
reverse(s.begin(),s.begin()+n+1);
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
string s1,s2;
cin>>s1>>s2;
vector<int>v;
for(int i=n-1;i>=0;i--)
{
if(s1[i]==s2[i])continue;
else
{
if(s2[i]==s1[0])
v.push_back(1);
v.push_back(i+1);
operation(s1,i);
}
}
cout<<v.size()<<" ";
for(int x:v)
cout<<x<<" ";
cout<<"\n";
}
}
|
#include "stdafx.h"
#include "LocWindow.h"
#include "zonalLocationDlg.h"
#include "LinearLocationDlg.h"
#include "PlanarLocationDlg.h"
#include "VesselLocationDlg.h"
#include "NagDlg.h"
#include "utilites/Localizator.h"
#include "utilites/serl/Archive.h"
#include "utilites/document.h"
#include "data/locationSetup.h"
#include "data/nodeFactory.h"
#include "toolbarbtns.h"
#include "NewLocation.h"
#include "data/LocationSetup.h"
#include "data/ZonalSetup.h"
#include "data/LinearSetup.h"
#include "data/PlanarSetup.h"
#include "data/VesselSetup.h"
CLocWnd::CLocWnd()
{
}
void CLocWnd::serialization(serl::archiver &arc)
{
}
HWND CLocWnd::Create(HWND hparent)
{
ignore_=0;
CWindow parent(hparent);
CRect prc; parent.GetWindowRect(prc);
parent.ClientToScreen(prc);
return baseClass::Create(
parent, CRect(prc.TopLeft(), CSize(200, 200)), "",
WS_VISIBLE|WS_CAPTION|WS_POPUP|WS_OVERLAPPED
|WS_CLIPSIBLINGS|WS_CLIPCHILDREN
|WS_SYSMENU|WS_THICKFRAME);
}
LRESULT CLocWnd::OnCreate(LPCREATESTRUCT)
{
listctrl_.Create(m_hWnd, rcDefault, "",
WS_VISIBLE|WS_CHILD|WS_BORDER
|LVS_REPORT|LVS_SINGLESEL|LVS_NOCOLUMNHEADER);
listctrl_.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT);
listctrl_.InsertColumn(0, "Location", 0, 200, 0);
toolbar_.Create(m_hWnd, rcDefault, "",
WS_CHILD|WS_VISIBLE
|TBSTYLE_FLAT
|TBSTYLE_LIST
|CCS_TOP);
toolbar_.SetButtonStructSize();
CToolbarButtons main=IDR_LOCATION_WND;
main.Append(IDC_LOCWIN_INSERT, 0, ""/*_lcs("LW-Insert#Insert")*/, TBSTYLE_AUTOSIZE);
main.Append(IDC_LOCWIN_DELETE, 1, ""/*_lcs("LW-Delete#Delete")*/, TBSTYLE_AUTOSIZE);
main.Append();
main.Append(IDC_LOCWIN_PROPERTY, 2, "", TBSTYLE_AUTOSIZE);
main.Apply(toolbar_);
OnChangeLanguage();
OnSizeChanged(0, 0, 0);
BuildList();
nodes::factory().location_slot().connect(this,
bind(&CLocWnd::UpdateList, this));
return 0;
}
void CLocWnd::OnChangeLanguage()
{
SetWindowText(_lcs("Location"));
}
LRESULT CLocWnd::OnDestroy()
{
nodes::factory().location_slot().disconnect(this);
return 0;
}
void CLocWnd::UpdateList()
{
if (!ignore_)
{
ignore_=true;
listctrl_.DeleteAllItems();
BuildList();
ignore_=false;
}
}
void CLocWnd::BuildList()
{
listctrl_.InsertItem(0, _lcs("No location"));
std::vector< location::Setup > lprm=
nodes::factory().get_location_setup();
bool selected=false;
unsigned cloc=
nodes::factory().get_sel_location();
unsigned count=lprm.size();
for (unsigned index=0; index<count; ++index)
{
std::string name=lprm[index].name();
listctrl_.InsertItem(index+1, name.c_str());
if (index==cloc)
{
selected=true;
listctrl_.SelectItem(index+1);
}
}
if (!selected) listctrl_.SelectItem(0);
}
LRESULT CLocWnd::OnEraseBackground(HDC hdc)
{
CDCHandle dc=hdc;
CRect rc; GetClientRect(rc);
dc.FillRect(rc, GetSysColorBrush(COLOR_3DFACE));
return 0;
}
LRESULT CLocWnd::OnSizeChanged(UINT uMsg, WPARAM, LPARAM)
{
CRect rc; GetClientRect(rc);
rc.DeflateRect(5, 5);
if (toolbar_)
{
toolbar_.AutoSize();
CRect tb;
toolbar_.GetWindowRect(tb);
ScreenToClient(tb);
rc.top=tb.bottom+5;
}
listctrl_.MoveWindow(rc);
CRect lrc; listctrl_.GetClientRect(lrc);
listctrl_.SetColumnWidth(0, lrc.Width()-3);
return 0;
}
LRESULT CLocWnd::OnItemChanged(LPNMHDR hdr)
{
LPNMLISTVIEW nm=(LPNMLISTVIEW)hdr;
if (nm->uNewState & LVIS_SELECTED)
{
int index=nm->iItem;
if (index==0)
{
nodes::factory().set_sel_location(-1);
}
else
{
nodes::factory().set_sel_location(index-1);
}
if (toolbar_)
{
TBBUTTONINFO info=
{
sizeof(TBBUTTONINFO),
TBIF_STATE, 0, 0,
index==0 ? 0 : TBSTATE_ENABLED
};
toolbar_.SetButtonInfo(IDC_LOCWIN_PROPERTY, &info);
info.fsState=index<2 ? 0 : TBSTATE_ENABLED;
toolbar_.SetButtonInfo(IDC_LOCWIN_DELETE, &info);
}
}
return 0;
}
LRESULT CLocWnd::OnItemDblClick(LPNMHDR hdr)
{
LPNMLISTVIEW nm=(LPNMLISTVIEW)hdr;
if (nm->iItem!=0)
{
OnProperty(0, nm->iItem, 0);
}
return 0;
}
LRESULT CLocWnd::OnProperty(UINT, int pos, HWND)
{
Document().Nag();
std::vector< location::Setup > setups=
nodes::factory().get_location_setup();
int index=listctrl_.GetSelectedIndex();
if (index>=1)
{
--index;
if (setups[index].planar())
{
CPlanarLocationDlg(setups[index].planar()).DoModal();
} else if (setups[index].linear())
{
CLinearLocationDlg(setups[index].linear()).DoModal();
} else if (setups[index].vessel())
{
CVesselLocationDlg( setups[index].vessel()).DoModal();
} else if (setups[index].zonal())
{
CZonalLocationDlg( setups[index].zonal() ).DoModal();
}
nodes::factory().set_location_setup( setups );
}
return 0;
}
LRESULT CLocWnd::OnInsertPos(UINT, int pos, HWND)
{
CNewLocation dlg;
if (dlg.DoModal()!=IDCANCEL)
{
std::vector< location::Setup > lcks=
nodes::factory().get_location_setup();
lcks.push_back( dlg.loc_ );
nodes::factory().set_location_setup( lcks );
listctrl_.InsertItem(listctrl_.GetItemCount()-1,
dlg.loc_.name().c_str());
listctrl_.SetItemState(listctrl_.GetItemCount()-2,
LVIS_SELECTED, LVIS_SELECTED);
OnProperty(0, pos, 0);
}
return 0;
}
LRESULT CLocWnd::OnDeletePos(UINT, int pos, HWND)
{
std::vector< location::Setup > lcks=
nodes::factory().get_location_setup();
int index=listctrl_.GetSelectedIndex();
if (index >= 2)
{
listctrl_.DeleteItem(index);
listctrl_.SetItemState(
std::min(index, listctrl_.GetItemCount()-1),
LVIS_SELECTED, LVIS_SELECTED);
--index;
lcks.erase(lcks.begin()+index);
nodes::factory().set_location_setup( lcks );
}
return 0;
}
|
#include "cybMLM.h"
#include "cybMatrixOperator.h"
CybMLM::CybMLM(int variablesNumber,float prioriProbability)
{
this->variablesNumber = variablesNumber;
this->precisionMatrix = NULL;
this->prioriProbability = prioriProbability;
this->variables = new mfList<int>;
this->mean = new float[getVariablesNumber()];
this->covariance = new float[getVariablesNumber()*getVariablesNumber()];
this->determinat = 0;
}
CybMLM::~CybMLM()
{
delete[] this->mean;
delete[] this->covariance;
variables->clear();
delete variables;
}
float CybMLM::getMean(int node_id)
{
return this->mean[node_id];
}
float CybMLM::getVariance(int node_id)
{
return this->covariance[node_id*getVariablesNumber() + node_id];
}
float CybMLM::getPrioriProbability()
{
return this->prioriProbability;
}
void CybMLM::setMean(float newMean, int node_id)
{
this->mean[node_id] = newMean;
}
float * CybMLM::getCovariance()
{
return this->covariance;
}
int CybMLM::getVariablesNumber()
{
return this->variablesNumber;
}
void CybMLM::setCovariance(float* newCovariance)
{
this->covariance = newCovariance;
}
void CybMLM::initData()
{
//it calculates the mean for each variable
for(int i=0; i < this->getVariablesNumber();i++)
{
float mean = 0;
for(int j=0; j < this->getData()->size(); j++)
mean += this->getData()->pos(j)->operator[](i);
this->setMean(mean/this->getData()->size(), i);
}
//it calculates the precisionMatrix matrix
for(int i=0; i < this->getVariablesNumber();i++)
for(int j=0; j < this->getVariablesNumber();j++)
{
for(int k=0; k < this->getData()->size(); k++)
{
this->covariance[i*this->getVariablesNumber() + j] +=
(this->getData()->pos(k)->toArray()[i]- this->getMean(i)) *
(this->getData()->pos(k)->toArray()[j]- this->getMean(j));
}
this->covariance[i*this->getVariablesNumber() + j] /= this->getData()->size();
}
checkVariables();
}
void CybMLM::checkVariables()
{
for(int i=0; i < getVariablesNumber(); i++)
if(getVariance(i))
this->variables->insert(i);
this->precisionMatrix = new float[getVariablesNumber()*getVariablesNumber()];
this->determinat = CybMatrixOperator::matrixDeterminant(covariance, variables->size());
CybMatrixOperator::matrixInverse(covariance,this->precisionMatrix,variables->size(),determinat);
}
void CybMLM::training()
{
initData();
}
double CybMLM::assessment(CybVectorND<>* data)
{
return getFunctionResult(data->toArray(), this->variables) + log(prioriProbability);;
}
double CybMLM::getFunctionResult(float* data, mfList<int> * variables)
{
float* aux1 = new float[variables->size()];
float* aux2 = new float[variables->size()];
float* matrix = this->precisionMatrix;
float* inverse = new float[variables->size()*variables->size()];
double res = 0.0;
for(int i=0; i < variables->size(); i++)
aux1[i] = (data[variables->pos(i)] - this->getMean(variables->pos(i)));
for(int i=0; i < variables->size(); i++)
for(int j=0; j < variables->size(); j++)
aux2[i] += aux1[j] * matrix[j * variables->size() + i];
for(int i=0; i < variables->size(); i++)
res += aux1[i]*aux2[i];
int size = variables->size();
delete[] aux1;
delete[] aux2;
return -log(abs(determinat)) - res;
}
|
//
// Created by 邓岩 on 2019/2/28.
//
# include <iostream>
# include <string>
# include <sstream>
# include <iomanip>
# include <algorithm>
# include <vector>
# include <stdio.h>
using namespace std;
class teacher {
public:
static int uid;
double salary;
double add;
int time;
int id;
virtual void info () {};
};
int teacher:: uid = 1;
class professor : public teacher {
public:
professor() = default;
professor(int t) {
id = uid++;
add = 50;
salary = 5000;
time = t;
}
virtual void info () { cout << "professor id = " << id << " wage = " << salary + add * time << endl; };
};
class assprofessor : public teacher {
public:
assprofessor() = default;
assprofessor(int t) {
id = uid++;
add = 30;
salary = 3000;
time = t;
}
virtual void info () { cout << "assprofessor id = " << id << " wage = " << salary + add * time << endl; };
};
class lecturer : public teacher {
public:
lecturer() = default;
lecturer(int t) {
id = uid++;
add = 20;
salary = 2000;
time = t;
}
virtual void info () { cout << "lecturer id = " << id << " wage = " << salary + add * time << endl; };
};
int main(void) {
teacher * a = new lecturer(10);
teacher * b = new assprofessor(10);
teacher * c = new professor(10);
a->info();
b->info();
c->info();
}
/*
class StudentManger;
class Student {
public:
int no; //学生的学号
string name; //学生的姓名
float score; //学生的成绩
Student* per; //当前结点的前一个结点指针
Student* next; //下一个结点指针
};
class StudentManger //类的定义
{
private:
Student * head;
public:
StudentManger(); //构造函数
Student* find(int i_no); //查找指定学号的学生
void edit(Student * , string i_newname,float i_score); //修改学生的信息
void erase(Student *); //删除指定学号的学生
int add(Student* i_newStudent); //增加学生
int getno(Student *); //获得学生的学号
string getname(Student *); //获得学生的名字
float getscore(Student *); //获得学生的成绩
static int maxno;
};
StudentManger::StudentManger()
{
head = new Student();
head->next = NULL;
}
Student* StudentManger::find(int i_no)
{
Student * t = head->next;
while (t != NULL) {
if (t->no == i_no)
return t;
t = t->next;
}
return NULL;
}
void StudentManger::edit(Student * t, string i_name,float i_score)
{
if(i_name=="")
return ;
t->name=i_name;
t->score=i_score;
}
void StudentManger::erase(Student * t)
{
if(t->no<0)
return ;
if(t->per!=NULL)
t->per->next=t->next;
if(t->next!=NULL)
t->next->per=t->per;
t->next=NULL;
t->per=NULL;
}
int StudentManger::add(Student* i_newStudent)
{
int no=maxno+1;
while(true)
{
if(NULL==find(no))
break;
no=no+1;
}
Student * tmp = head;
while(true){
if(tmp->next==NULL)
break;
tmp=tmp->next;
}
tmp->next=i_newStudent;
i_newStudent->next=NULL;
i_newStudent->per=tmp;
i_newStudent->no=no;
return no;
}
int StudentManger::getno(Student * t){return t->no;}
string StudentManger::getname(Student * t){return t->name;}
float StudentManger::getscore(Student * t){return t->score;}
int StudentManger::maxno=1000;
int main()
{
StudentManger * Studentroot=new StudentManger();
string input1;
float input2;
Student* tmp=NULL;
while(true){
cout<<"输入指令:查找(F),增加(A),编辑(E),删除(D),退出(Q)"<<endl;
cin>>input1;
if(("F"==input1)||("f"==input1))
{
cout<<"输入学号:";
int no=-1;
cin>>no;
tmp=Studentroot->find(no);
if(tmp==NULL)
{
cout<<"没找到"<<endl;
continue;
}
cout<<"学号:"<<Studentroot->getno(tmp);
cout<<" 姓名:";
string name;
if((name=Studentroot->getname(tmp))!="")
cout<<name;
else
cout<<"未输入"<<endl;
cout<<" 成绩:"<<Studentroot->getscore(tmp)<<endl;
}
else if((input1=="A")||(input1=="a"))
{
cout<<"输入姓名,成绩: ";
cin>>input1>>input2;;
tmp=new Student();
Studentroot->edit(tmp, input1,input2);
cout<<"学号: "<<Studentroot->add(tmp)<<endl;
}
else if((input1=="E")||(input1=="e"))
{
cout<<"输入学号:";
int no=0;
cin>>no;
tmp=Studentroot->find(no);
if(tmp==NULL)
{
cout<<"空号"<<endl;
continue;
}
cout<<"新姓名,新成绩: ";
cin>>input1>>input2;
Studentroot->edit(tmp, input1, input2);
cout<<"更改成功."<<endl;
}
else if((input1=="D")||(input1=="d"))
{
cout<<"输入学号:";
int no=0;
cin>>no;
tmp=Studentroot->find(no);
Studentroot->erase(tmp);
cout<<"已成功删除"<<endl;
delete tmp;
}
else if((input1=="Q")||(input1=="q"))
{
break;
}
else
{
cout<<"输入有误!"<<endl;
}
}
delete Studentroot;
return 0;
}
*/
/*
class Circle {
public:
Circle () = default;
Circle(double radius) {
this->radius = radius;
}
double area() {
return 3.1415 * radius * radius;
}
void set(double x) {
radius = x;
}
double get() {
return radius;
}
private:
double radius;
};
class stack {
private:
int * a;
int index;
int len;
public:
stack() = default;
~stack() { free(a); }
stack(int n) {
a = (int *)malloc(sizeof(int) * n);
len = n;
index = 0;
}
void push(int x) {
if (full()) {
a = (int *)realloc(a, sizeof(int) * len * 2);
len = 2 * len;
}
a[index++] = x;
}
int pop() {
if (empty()) {
cout << "The stack is empty" << endl;
exit(-1);
}
return a[--index];
}
bool empty() { return index == 0; }
bool full() { return index == len; }
};
*/
/*
struct twodim {
int r;
int c;
float * a;
};
void get_twodim(twodim &s, int row, int col) {
s.r = row;
s.c = col;
s.a = new float[row * col];
}
float &val(twodim &s, int i, int j ) {
return s.a[i * s.c + j];
}
void free_twodim(twodim &s) {
delete [] s.a;
}
int main(void) {//16.1.5
struct twodim s;
int i, j;
get_twodim(s, 3, 4);
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++)
val(s, i, j) = 5;
}
for (i = 0;i < 3; i++) {
for (j = 0; j < 4; j++)
cout << setw(5) << val(s, i, j);
cout << endl;
}
free_twodim(s);
return 0;
}
*/
/*
void print(string &s, int n = 10)
{
cout << string(s.begin(), s.begin() + min(int(s.size()), n)) << endl;
}
*/
/*
string s;
vector<string> buf;
getline(cin, s);
istringstream str(s);
copy(istream_iterator<string>(str), istream_iterator<string>(), back_inserter(buf));
sort(buf.begin(), buf.end());
copy(buf.begin(), buf.end(), ostream_iterator<string>(cout, " "));
*/
// 输若干数据,找出最大值输出
/*
# include <iostream>
# include <string>
# include <sstream>
# include <algorithm>
using namespace std;
int main(void) {
string s;
getline(cin, s);
istringstream str(s);
cout << *max_element(istream_iterator<int>(str), istream_iterator<int>()) << endl;
return 0;[
}
*/
/*
# include <iostream>
# include <string>
# include <iomanip>
using namespace std;
int main() {//16.1.5
int day, stop, i = 0;
cin >> day >> stop;
cout << " Sun Mon Tue Wed Thu Fri Sat" << endl;
cout << string(day * 5, ' ');
while (stop--) {
cout << setw(5) << ++i;
if ((day + i) % 7 == 0)
cout << endl;
}
return 0;
}
*/
|
#include "FoundationPch.h"
#include "Foundation/Reflect/ReflectionInfo.h"
using namespace Helium;
using namespace Helium::Reflect;
const tchar_t* ReflectionTypes::Strings[ ReflectionTypes::Count ] =
{
TXT("Type"),
TXT("Enumeration"),
TXT("Composite"),
TXT("Structure"),
TXT("Class"),
};
ReflectionInfo::ReflectionInfo()
{
}
ReflectionInfo::~ReflectionInfo()
{
}
|
#include "Scheduler.h"
/**********************************************************************
* Create a new Scheduler with the process interval specified by
* <loopInterval>. The specified interval is the frequency at which
* the scheduler will check to see if a callback should be executed, so
* its best if this is frequent.
*/
Scheduler::Scheduler(unsigned long loopInterval) {
this->size = 0;
this->loopInterval = loopInterval;
}
/**********************************************************************
* This function must be called from the main loop(). It will execute
* any scheduled callback functions and then delete it from the
* collection of scheduled callback functions (unless the callback was
* scheduled with a repeat flag in which cast the callback will be
* re-scheduled).
*/
void Scheduler::loop() {
static unsigned long deadline = 0UL;
unsigned long now = millis();
if ((now > deadline) && (this->size > 0)) {
for (unsigned int i = 0; i < 10; i++) {
if (this->callbacks[i].when >= now) {
this->callbacks[i].func();
if (!this->callbacks[i].repeat) {
this->callbacks[i].when = 0UL;
this->size--;
} else {
this->callbacks[i].when = (now + this->callbacks[i].interval);
}
}
}
deadline = (now + this->loopInterval);
}
}
/**********************************************************************
* Schedule <func> for callback in <interval> milliseconds. If <repeat>
* is omitted or false, then the <func> will be called once, otherwise
* it will be called repeatedly every <interval> milliseconds.
*/
bool Scheduler::schedule(void (*func)(), unsigned long interval, bool repeat) {
bool retval = false;
if (this->size < 10) {
for (unsigned int i = 0; i < 10; i++) {
if (this->callbacks[i].when == 0UL) {
this->callbacks[i].func = func;
this->callbacks[i].interval = interval;
this->callbacks[i].repeat = repeat;
this->callbacks[i].when = (millis() + interval);
this->size++;
retval = true;
break;
}
}
}
return(retval);
}
|
#include "DebugWindow.h"
#include <imgui.h>
#include "DebugUIElements.h"
vkw::DebugWindow::DebugWindow(const std::string& name)
:m_Name{ name }
{
}
vkw::DebugWindow::~DebugWindow()
{
Cleanup();
}
void vkw::DebugWindow::Render() const
{
ImGui::Begin(m_Name.c_str(), nullptr, ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_MenuBar);
for (const std::pair<std::string, std::vector<IDebugUIElement*>>& uiElements : m_UIElements)
{
if(uiElements.first == "") //no collapsing header
{
for (IDebugUIElement* uiElement : uiElements.second)
{
uiElement->Render();
}
}
else
if (ImGui::CollapsingHeader(uiElements.first.c_str()))
{
for (IDebugUIElement* uiElement : uiElements.second)
{
uiElement->Render();
}
}
}
ImGui::End();
}
void vkw::DebugWindow::AddUIElement(IDebugUIElement* variable, const std::string& group)
{
m_UIElements[group].push_back(variable);
}
void vkw::DebugWindow::Cleanup()
{
for (const std::pair<std::string, std::vector<IDebugUIElement*>>& uiElements : m_UIElements)
{
for (IDebugUIElement* uiElement : uiElements.second)
{
delete uiElement;
}
}
}
|
#include <cstdio>
#include <iostream>
#include <queue>
using namespace std;
typedef long long ll;
struct Node {
int id, arrive, process, priority;
Node(int _id, int _arrive, int _process, int _priority) : id(_id), arrive(_arrive), process(_process), priority(_priority) {}
bool operator<(const Node& a) const {
if (priority != a.priority)
return priority < a.priority;
return arrive > a.arrive;
}
};
priority_queue<Node> pq;
// #define DEBUG
int main() {
#ifdef DEBUG
freopen("d:\\.in", "r", stdin);
freopen("d:\\.out", "w", stdout);
#endif
int id, arrive, process, priority, startTime = -1;
while (scanf("%d%d%d%d", &id, &arrive, &process, &priority) != EOF) {
// 在两个任务到达的间隔期内不断地取出任务执行
while (!pq.empty()) {
Node curNode = pq.top();
pq.pop();
startTime = max(startTime, curNode.arrive);
if (startTime + curNode.process <= arrive) {
// 能执行完
startTime += curNode.process;
printf("%d %d\n", curNode.id, startTime);
} else {
// 不能执行完就放回去
curNode.process -= arrive - startTime;
pq.push(curNode);
startTime = arrive;
break;
}
}
pq.push(Node(id, arrive, process, priority));
}
// 所有任务都入队了,处理剩余任务
startTime = max(startTime, pq.top().arrive);
while (!pq.empty()) {
Node curNode = pq.top();
pq.pop();
// 一定要执行完
startTime += curNode.process;
printf("%d %d\n", curNode.id, startTime);
}
return 0;
}
|
#ifndef PARSERS_PARSER_HEADER
#define PARSERS_PARSER_HEADER
#include "Source/Units/SystemUnit.h"
#include "Source/Units/Unit.h"
namespace solar
{
//Loads simulated data for the simulation and optionally also saves them after the simulation finished.
class Parser : public SystemUnit
{
public:
//Loads input from whethever
virtual SimData Load() = 0;
//Save them after end of simulation
virtual void Save(const SimData&) {};
virtual ~Parser() = default;
};
}
#endif
|
#include <touchgfx/Font.hpp>
FONT_KERNING_LOCATION_FLASH_PRAGMA
KEEP extern const touchgfx::KerningNode kerning_arial_20_4bpp[] FONT_KERNING_LOCATION_FLASH_ATTRIBUTE =
{
{ 0x0041, -1 }, // (First char = [0x0041, A], Second char = [0x0020, space], Kerning dist = -1)
{ 0x004C, -1 }, // (First char = [0x004C, L], Second char = [0x0020, space], Kerning dist = -1)
{ 0x0031, -1 }, // (First char = [0x0031, one], Second char = [0x0031, one], Kerning dist = -1)
{ 0x0056, -1 }, // (First char = [0x0056, V], Second char = [0x003A, colon], Kerning dist = -1)
{ 0x0020, -1 }, // (First char = [0x0020, space], Second char = [0x0041, A], Kerning dist = -1)
{ 0x0046, -1 }, // (First char = [0x0046, F], Second char = [0x0041, A], Kerning dist = -1)
{ 0x0050, -1 }, // (First char = [0x0050, P], Second char = [0x0041, A], Kerning dist = -1)
{ 0x0056, -1 }, // (First char = [0x0056, V], Second char = [0x0041, A], Kerning dist = -1)
{ 0x0041, -1 }, // (First char = [0x0041, A], Second char = [0x0056, V], Kerning dist = -1)
{ 0x004C, -1 }, // (First char = [0x004C, L], Second char = [0x0056, V], Kerning dist = -1)
{ 0x0056, -1 }, // (First char = [0x0056, V], Second char = [0x0061, a], Kerning dist = -1)
{ 0x0056, -1 }, // (First char = [0x0056, V], Second char = [0x0065, e], Kerning dist = -1)
{ 0x0056, -1 }, // (First char = [0x0056, V], Second char = [0x006F, o], Kerning dist = -1)
{ 0x0056, -1 }, // (First char = [0x0056, V], Second char = [0x0072, r], Kerning dist = -1)
{ 0x0056, -1 }, // (First char = [0x0056, V], Second char = [0x0075, u], Kerning dist = -1)
{ 0x004C, -1 }, // (First char = [0x004C, L], Second char = [0x0079, y], Kerning dist = -1)
{ 0x0056, -1 }, // (First char = [0x0056, V], Second char = [0x0079, y], Kerning dist = -1)
};
|
#ifndef TREE_MESH_PRESENTER_H
#define TREE_MESH_PRESENTER_H
#include <Data/MultiMesh.h>
#include <View/EdgeVisualizer/GL/MeshRenderer/GLTriangleList.h>
#include "TreeDataPresenter.h"
class TreeMeshPresenter : public TreeDataPresenter
{
private:
//
struct BranchPresenter
{
Mesh<vec4> *wrappedBranch;
GLTriangleList *branchRepresentation = nullptr;
//
void RefreshBranch();
//
BranchPresenter()
{}
//
~BranchPresenter()
{
if(branchRepresentation != nullptr)
{delete branchRepresentation;}
}
};
//
struct JunctionPresenter
{
MyMesh *wrappedJunction;
GLTriangleList *junctionRepresentation = nullptr;
//
void RefreshBranch();
//
JunctionPresenter()
{}
//
~JunctionPresenter()
{
if(junctionRepresentation != nullptr)
{delete junctionRepresentation;}
}
};
//
MultiMesh *wrappedMultiMesh;
std::list<BranchPresenter> branchPresenters;
std::list<JunctionPresenter> junctionPresenters;
//
virtual void Refresh() override;
//
public:
//
virtual void Accept(ITreeDataVisitor &visitor) override
{
visitor.Visit(*this);
}
//
void OnChanged(MultiMesh *new_multi_mesh)
{
wrappedMultiMesh = new_multi_mesh;
//
Changed = true;
//
NotifyChanged();
}
//
TreeMeshPresenter()
{}
//
~TreeMeshPresenter()
{}
};
#endif // TREE_MESH_PRESENTER_H
|
/*
* Copyright (C) 2012-2016 Open Source Robotics Foundation
*
* 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 <test/TestUtils.hh>
#include <collision_benchmark/BasicTypes.hh>
#include <collision_benchmark/MirrorWorld.hh>
#include <ignition/math/Vector3.hh>
#include <gazebo/gazebo.hh>
#include <gazebo/msgs/msgs.hh>
#include <boost/filesystem.hpp>
#include <sstream>
#include <thread>
#include <atomic>
using collision_benchmark::Shape;
using collision_benchmark::BasicState;
using collision_benchmark::Vector3;
using collision_benchmark::Quaternion;
using collision_benchmark::PhysicsWorldBaseInterface;
using collision_benchmark::MirrorWorld;
using collision_benchmark::GzWorldManager;
std::atomic<bool> g_keypressed(false);
// waits until Enter has been pressed and sets g_keypressed to true
////////////////////////////////////////////////////////////////
void WaitForEnterImpl()
{
// wait for keypress
getchar();
g_keypressed = true;
}
////////////////////////////////////////////////////////////////
void collision_benchmark::UpdateUntilEnter(GzWorldManager::Ptr &worlds)
{
g_keypressed = false;
std::thread * t = new std::thread(WaitForEnterImpl);
t->detach(); // detach so it can be terminated
while (!g_keypressed)
{
worlds->Update(1);
}
delete t;
}
////////////////////////////////////////////////////////////////
bool collision_benchmark::GetConsistentAABB(const std::string &modelName,
const GzWorldManager::Ptr &worldManager,
const double bbTol,
GzAABB &mAABB)
{
std::vector<GzWorldManager::PhysicsWorldModelInterfacePtr>
worlds = worldManager->GetModelPhysicsWorlds();
// AABB's from all worlds: need to be equal or this function
// must return false.
std::vector<GzAABB> aabbs;
std::vector<GzWorldManager::PhysicsWorldModelInterfacePtr>::iterator it;
for (it = worlds.begin(); it != worlds.end(); ++it)
{
GzWorldManager::PhysicsWorldModelInterfacePtr w = *it;
GzAABB aabb;
bool inLocalFrame;
if (!w->GetAABB(modelName, aabb.min, aabb.max, inLocalFrame))
{
std::cerr << "Model " << modelName << " AABB could not be retrieved"
<< std::endl;
return false;
}
aabbs.push_back(aabb);
}
if (aabbs.empty())
{
std::cerr << "At least one bounding box should "
<< "have been returned" << std::endl;
return false;
}
// Check that all AABBs are the same
std::vector<GzAABB>::iterator itAABB;
GzAABB lastAABB;
for (itAABB = aabbs.begin(); itAABB != aabbs.end(); ++itAABB)
{
const GzAABB &aabb = *itAABB;
if (itAABB != aabbs.begin())
{
if (!aabb.min.Equal(lastAABB.min, bbTol) ||
!aabb.max.Equal(lastAABB.max, bbTol))
{
std::cerr << "Bounding boxes should be of the same size: "
<< aabb.min << ", " << aabb.max << " --- "
<< lastAABB.min << ", " << lastAABB.max;
return false;
}
}
lastAABB = aabb;
}
mAABB = aabbs.front();
return true;
}
////////////////////////////////////////////////////////////////
std::vector<collision_benchmark::GzContactInfoPtr>
collision_benchmark::GetContactInfo(const std::string &modelName1,
const std::string &modelName2,
const std::string &worldName,
const GzWorldManager::Ptr &worldManager)
{
PhysicsWorldBaseInterface::Ptr w = worldManager->GetWorld(worldName);
assert(w);
GzWorldManager::PhysicsWorldPtr pWorld = worldManager->ToPhysicsWorld(w);
assert(pWorld);
return pWorld->GetContactInfo(modelName1, modelName2);
}
////////////////////////////////////////////////////////////////
bool collision_benchmark::CollisionState(const std::string &modelName1,
const std::string &modelName2,
const GzWorldManager::Ptr &worldManager,
std::vector<std::string>& colliding,
std::vector<std::string>& notColliding,
double &maxDepth)
{
colliding.clear();
notColliding.clear();
maxDepth = 0;
if (!worldManager) return false;
std::vector<GzWorldManager::PhysicsWorldPtr>
worlds = worldManager->GetPhysicsWorlds();
std::vector<GzWorldManager::PhysicsWorldPtr>::iterator it;
for (it = worlds.begin(); it != worlds.end(); ++it)
{
GzWorldManager::PhysicsWorldPtr w = *it;
if (!w->SupportsContacts())
{
std::cout << "A world does not support contact calculation" << std::endl;
return false;
}
std::vector<GzContactInfoPtr> contacts =
w->GetContactInfo(modelName1, modelName2);
if (!contacts.empty())
{
colliding.push_back(w->GetName());
for (typename std::vector<GzContactInfoPtr>::const_iterator
cit = contacts.begin(); cit != contacts.end(); ++cit)
{
GzContactInfoPtr c = *cit;
double tmpMax;
if (c->maxDepth(tmpMax) && tmpMax > maxDepth)
maxDepth = tmpMax;
}
// std::cout << "Max depth: " << maxDepth << std::endl;
}
else
{
notColliding.push_back(w->GetName());
}
}
return true;
}
|
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
string s;
cin>>s;
if(s.length()<3){
cout<<"0\n";
continue;
}
if(s.length()==0){
cout<<"0\n";
continue;
}
int one=0,zero=0,zi=-1,oi=-1;
for(int i=0; i<s.length(); i++){
if(s[i]=='1'){
one++;
oi=i;
}else{
zero++;
zi=i;
}
}
if(one==0 || zero==0){
cout<<"0\n";
continue;
}
int count= INT_MAX;
int n = s.length()-1;
// vector<int>oc(s.length(),0);
// vector<int>zc(s.length(),0);
// int co=0,cz=0;
// if(s[0]=='1'){
// oc[0]=1;
// }else{
// zc[0] =1;
// }
// for(int i=1; i<n; i++){
// oc[i] = oc[i-1];
// zc[i] = zc[i-1];
// if(s[i]=='1'){
// oc[i]++;
// }else{
// zc[i]++;
// }
// }
for(int i=0; i<s.length(); i++){
int zc=0,oc=0;
for(int j=0; j<=i; j++){
if(s[j]=='0')zc++;
}
for(int j=i+1; j<s.length(); j++){
if(s[j]=='1')oc++;
}
int x = zc+oc;
// int x = zc[i] + (oc[n-1]-oc[i]);
count =min(count,x);
}
for(int i=0; i<s.length(); i++){
int zc=0,oc=0;
for(int j=0; j<=i; j++){
if(s[j]=='1')oc++;
}
for(int j=i+1; j<s.length(); j++){
if(s[j]=='0')zc++;
}
int x = zc+oc;
/// cout<<x<<" ";
count =min(count,x);
// cout<<count<<"\n";
}
cout<<count<<"\n";
// if(s[0]=='1'){
// int i=0;
// while(i<s.length() && s[i]=='1'){
// i++;
// }
// while(i<s.length() && s[i]=='0'){
// i++;
// }
// if(i==s.length()){
// cout<<"0\n";
// continue;
// }
// }else{
// int i=0;
// while(i<s.length() && s[i]=='0'){
// i++;
// }
// while(i<s.length() && s[i]=='1'){
// i++;
// }
// if(i==s.length()){
// cout<<"0\n";
// continue;
// }
// }
//
// int i=1,ss=0,ee=0;
// one=0,zero=0;
// while(i<s.length()){
// if(s[i]!=s[i-1] && ss==0){
// ss=i;
// //break;
// }
// if(s[i]!=s[i-1]){
// ee=i-1;
// }
// i++;
// }
// if(s[0]==s[s.length()-1]){
// for(int i=ss; i<s.length(); i++){
// if(s[i]=='1'){
// one++;
// }else{
// zero++;
// }
// }
// }else{
// // cout<<ss<<" "<<ee<<" ";
// for(int i=ss; i<=ee; i++){
// if(s[i]=='1'){
// one++;
// }else{
// zero++;
// }
// }
// }
//
// cout<<min(one,zero)<<"\n";
}
return 0;
}
|
/**
* @file numericalDiff.cpp
* @brief Numerical differentiation.
* @author Michael Kaess
* @version $Id: numericalDiff.cpp 4038 2011-02-26 04:31:00Z kaess $
*
* Copyright (C) 2009-2013 Massachusetts Institute of Technology.
* Michael Kaess, Hordur Johannsson, David Rosen,
* Nicholas Carlevaris-Bianco and John. J. Leonard
*
* This file is part of iSAM.
*
* iSAM 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 2.1 of the License, or (at
* your option) any later version.
*
* iSAM is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with iSAM. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <iostream>
#include "isam/numericalDiff.h"
#define SYMMETRIC
const double epsilon = 0.0001;
using namespace std;
using namespace Eigen;
namespace isam {
MatrixXd numericalDiff(Function& func)
{
#ifndef SYMMETRIC
VectorXd y0 = func.evaluate();
#endif
// number of measurement rows
int m = func.num_measurements();
// number of variables
int n = 0;
vector<Node*>& nodes = func.nodes();
for (vector<Node*>::iterator it = nodes.begin(); it != nodes.end(); it++)
{
n += (*it)->dim();
}
// result has one column per variable
MatrixXd Jacobian(m, n);
int col = 0;
// for each node...
for (vector<Node*>::iterator it = nodes.begin(); it != nodes.end(); it++)
{
Node* node = *it;
int dim_n = node->dim();
// for each dimension of the node...
for (int j = 0; j<dim_n; j++, col++)
{
VectorXd delta(dim_n);
delta.setZero();
// remember original value
VectorXd original = node->vector0();
// evaluate positive delta
delta(j) = epsilon;
node->self_exmap(delta);
VectorXd y_plus = func.evaluate();
node->update0(original);
#ifdef SYMMETRIC
// evaluate negative delta
delta(j) = -epsilon;
node->self_exmap(delta);
VectorXd y_minus = func.evaluate();
node->update0(original);
// store column
VectorXd diff = (y_plus - y_minus) / (epsilon + epsilon);
#else
VectorXd diff = (y_plus - y0) / epsilon;
#endif
Jacobian.col(col) = diff;
}
}
return Jacobian;
}
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "base.h"
WINRT_WARNING_PUSH
#include "internal/Windows.Foundation.3.h"
#include "internal/Windows.Devices.Background.3.h"
#include "Windows.Devices.h"
WINRT_EXPORT namespace winrt {
namespace impl {
template <typename D>
struct produce<D, Windows::Devices::Background::IDeviceServicingDetails> : produce_base<D, Windows::Devices::Background::IDeviceServicingDetails>
{
HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().DeviceId());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_Arguments(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Arguments());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_ExpectedDuration(impl::abi_arg_out<Windows::Foundation::TimeSpan> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().ExpectedDuration());
return S_OK;
}
catch (...)
{
return impl::to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Devices::Background::IDeviceUseDetails> : produce_base<D, Windows::Devices::Background::IDeviceUseDetails>
{
HRESULT __stdcall get_DeviceId(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().DeviceId());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
HRESULT __stdcall get_Arguments(impl::abi_arg_out<hstring> value) noexcept override
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_abi(this->shim().Arguments());
return S_OK;
}
catch (...)
{
*value = nullptr;
return impl::to_hresult();
}
}
};
}
namespace Windows::Devices::Background {
template <typename D> hstring impl_IDeviceUseDetails<D>::DeviceId() const
{
hstring value;
check_hresult(WINRT_SHIM(IDeviceUseDetails)->get_DeviceId(put_abi(value)));
return value;
}
template <typename D> hstring impl_IDeviceUseDetails<D>::Arguments() const
{
hstring value;
check_hresult(WINRT_SHIM(IDeviceUseDetails)->get_Arguments(put_abi(value)));
return value;
}
template <typename D> hstring impl_IDeviceServicingDetails<D>::DeviceId() const
{
hstring value;
check_hresult(WINRT_SHIM(IDeviceServicingDetails)->get_DeviceId(put_abi(value)));
return value;
}
template <typename D> hstring impl_IDeviceServicingDetails<D>::Arguments() const
{
hstring value;
check_hresult(WINRT_SHIM(IDeviceServicingDetails)->get_Arguments(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::TimeSpan impl_IDeviceServicingDetails<D>::ExpectedDuration() const
{
Windows::Foundation::TimeSpan value {};
check_hresult(WINRT_SHIM(IDeviceServicingDetails)->get_ExpectedDuration(put_abi(value)));
return value;
}
}
}
template<>
struct std::hash<winrt::Windows::Devices::Background::IDeviceServicingDetails>
{
size_t operator()(const winrt::Windows::Devices::Background::IDeviceServicingDetails & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Background::IDeviceUseDetails>
{
size_t operator()(const winrt::Windows::Devices::Background::IDeviceUseDetails & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Background::DeviceServicingDetails>
{
size_t operator()(const winrt::Windows::Devices::Background::DeviceServicingDetails & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
template<>
struct std::hash<winrt::Windows::Devices::Background::DeviceUseDetails>
{
size_t operator()(const winrt::Windows::Devices::Background::DeviceUseDetails & value) const noexcept
{
return winrt::impl::hash_unknown(value);
}
};
WINRT_WARNING_POP
|
#ifndef OPERATEUROR_H
#define OPERATEUROR_H
#include "../headers/operateur.h"
#include "../headers/pile.h"
#include "../headers/entier.h"
#include "../headers/expressionmanager.h"
///
/// \brief Opération logique OU
///
class OperateurOR : public Operateur
{
friend class ExpressionManager;
private:
///
/// \brief Constructeur de copie
/// \deprecated N'est pas implémenté
/// \param e : L'operateur à copier
///
OperateurOR(const OperateurOR& e);
///
/// \brief Opérateur d'affectation
/// \deprecated N'est pas implémenté
/// \param e : L'operateur à copier
/// \return Une référence vers l'objet lui-même
///
OperateurOR& operator=(const OperateurOR& e);
protected:
///
/// \brief Constructeur d'un OperateurOR
///
OperateurOR() : Operateur("OR", 2) {}
///
/// \brief Destructeur d'un OperateurOR
///
virtual ~OperateurOR() {}
public:
///
/// \brief Applique l'opération sur la Pile
/// \param pile : la Pile sur laquelle effectuer l'opération
/// \return Une référence vers l'Operateur lui-même (ne sert à rien)
///
virtual const OperateurOR& evaluate(Pile& pile) const override final;
};
#endif // OPERATEUROR_H
|
#ifndef _HS_SFM_SFM_UTILITY_CAMERA_ROTATED_BOUNDING_BOX_INTERSECTOR_HPP_
#define _HS_SFM_SFM_UTILITY_CAMERA_ROTATED_BOUNDING_BOX_INTERSECTOR_HPP_
#include "hs_math/geometry/plane_from_3points.hpp"
#include "hs_sfm/sfm_utility/camera_type.hpp"
#include "hs_sfm/sfm_utility/projective_functions.hpp"
namespace hs
{
namespace sfm
{
template <typename _Scalar>
class CameraRotatedBoundingBoxIntersector
{
public:
typedef _Scalar Scalar;
typedef CameraIntrinsicParams<Scalar> IntrinsicParams;
typedef CameraExtrinsicParams<Scalar> ExtrinsicParams;
typedef EIGEN_VECTOR(Scalar, 3) Point;
typedef EIGEN_MATRIX(Scalar, 3, 3) RMatrix;
private:
typedef hs::sfm::ProjectiveFunctions<Scalar> ProjectiveFunctions;
typedef EIGEN_VECTOR(Scalar, 2) Key;
typedef EIGEN_VECTOR(Scalar, 4) Vector4;
typedef EIGEN_MATRIX(Scalar, 4, 4) Matrix44;
typedef hs::math::geometry::PlaneFrom3Points<Scalar> PlaneFrom3Points;
public:
bool operator()(const IntrinsicParams& intrinsic_params,
const ExtrinsicParams& extrinsic_params,
size_t width, size_t height,
const Point& center,
const Point& min, const Point& max,
const RMatrix& rmatrix) const
{
Point corners[8] =
{
Point(min[0], min[1], min[2]),
Point(min[0], min[1], max[2]),
Point(min[0], max[1], min[2]),
Point(min[0], max[1], max[2]),
Point(max[0], min[1], min[2]),
Point(max[0], min[1], max[2]),
Point(max[0], max[1], min[2]),
Point(max[0], max[1], max[2])
};
bool is_all_corners_outside = true;
for (auto& corner : corners)
{
corner = rmatrix.transpose() * corner + center;
Key key;
key = ProjectiveFunctions::WorldPointProjectToImageKey(
intrinsic_params, extrinsic_params, corner);
if (key[0] >= Scalar(0) && key[0] < Scalar(width) &&
key[1] >= Scalar(0) && key[1] < Scalar(height))
{
key = ProjectiveFunctions::WorldPointProjectToImageKeyNoDistort(
intrinsic_params, extrinsic_params, corner);
if (key[0] >= Scalar(0) && key[0] < Scalar(width) &&
key[1] >= Scalar(0) && key[1] < Scalar(height))
{
is_all_corners_outside = false;
break;
}
}
}
if (is_all_corners_outside)
{
Vector4 position;
position.template segment<3>(0) = extrinsic_params.position();
position[3] = Scalar(1);
Vector4 camera_corners[4] =
{
Vector4(-Scalar(width) / Scalar(2),
-Scalar(height) / Scalar(2),
Scalar(intrinsic_params.focal_length()),
Scalar(1)),
Vector4(Scalar(width) / Scalar(2),
-Scalar(height) / Scalar(2),
Scalar(intrinsic_params.focal_length()),
Scalar(1)),
Vector4(Scalar(width) / Scalar(2),
Scalar(height) / Scalar(2),
Scalar(intrinsic_params.focal_length()),
Scalar(1)),
Vector4(-Scalar(width) / Scalar(2),
Scalar(height) / Scalar(2),
Scalar(intrinsic_params.focal_length()),
Scalar(1))
};
RMatrix rmatrix_camera = extrinsic_params.rotation();
Point translate = -rmatrix_camera * extrinsic_params.position();
for (int i = 0; i < 4; i++)
{
camera_corners[i].template segment<3>(0) =
rmatrix_camera.transpose() *
(camera_corners[i].template segment<3>(0) - translate);
}
Vector4 plane_left =
PlaneFrom3Points()(corners[0], corners[1], corners[2]);
Vector4 plane_right =
PlaneFrom3Points()(corners[4], corners[5], corners[6]);
Vector4 plane_bottom =
PlaneFrom3Points()(corners[0], corners[1], corners[5]);
Vector4 plane_top =
PlaneFrom3Points()(corners[2], corners[3], corners[7]);
Vector4 plane_back =
PlaneFrom3Points()(corners[2], corners[4], corners[6]);
Vector4 plane_front =
PlaneFrom3Points()(corners[3], corners[5], corners[7]);
for (int i = 0; i < 4; i++)
{
Matrix44 line = position * camera_corners[i].transpose() -
camera_corners[i] * position.transpose();
for (int j = 0; j < 6; j++)
{
Vector4 point_left = line * plane_left;
if (std::abs(point_left[3]) > 1e-10)
{
point_left /= point_left[3];
Point point_left_r = point_left.template segment<3>(0);
point_left_r = rmatrix * (point_left_r - center);
if (point_left_r[1] > min[1] && point_left_r[1] < max[1] &&
point_left_r[2] > min[2] && point_left_r[2] < max[2])
{
return true;
}
}
Vector4 point_right = line * plane_right;
if (std::abs(point_right[3]) > 1e-10)
{
point_right /= point_right[3];
Point point_right_r = point_right.template segment<3>(0);
point_right_r = rmatrix * (point_right_r - center);
if (point_right_r[1] > min[1] && point_right_r[1] < max[1] &&
point_right_r[2] > min[2] && point_right_r[2] < max[2])
{
return true;
}
}
Vector4 point_bottom = line * plane_bottom;
if (std::abs(point_bottom[3]) > 1e-10)
{
point_bottom /= point_bottom[3];
Point point_bottom_r = point_bottom.template segment<3>(0);
point_bottom_r = rmatrix * (point_bottom_r - center);
if (point_bottom_r[0] > min[0] && point_bottom_r[0] < max[0] &&
point_bottom_r[2] > min[2] && point_bottom_r[2] < max[2])
{
return true;
}
}
Vector4 point_top = line * plane_top;
if (std::abs(point_top[3]) > 1e-10)
{
point_top /= point_top[3];
Point point_top_r = point_top.template segment<3>(0);
point_top_r = rmatrix * (point_top_r - center);
if (point_top_r[0] > min[0] && point_top_r[0] < max[0] &&
point_top_r[2] > min[2] && point_top_r[2] < max[2])
{
return true;
}
}
Vector4 point_back = line * plane_back;
if (std::abs(point_back[3]) > 1e-10)
{
point_back /= point_back[3];
Point point_back_r = point_back.template segment<3>(0);
point_back_r = rmatrix * (point_back_r - center);
if (point_back_r[0] > min[0] && point_back_r[0] < max[0] &&
point_back_r[1] > min[1] && point_back_r[1] < max[1])
{
return true;
}
}
Vector4 point_front = line * plane_front;
if (std::abs(point_front[3]) > 1e-10)
{
point_front /= point_front[3];
Point point_front_r = point_front.template segment<3>(0);
point_front_r = rmatrix * (point_front_r - center);
if (point_front_r[0] > min[0] && point_front_r[0] < max[0] &&
point_front_r[1] > min[1] && point_front_r[1] < max[1])
{
return true;
}
}
}
}
return false;
}
else
{
return true;
}
}
};
}
}
#endif
|
//eStack.h - stack class implemenation using linked list
#include "linkedList.h"
class eStack{
private:
linkedList list;
public:
eStack();
void push(int); //enter an element
int pop(); //return element
int getCount(); //return count of list elements
int fullStack();//return 1 if stack is full
int emptystack();//return 1 if stack is empty
};
#include "eStack.cpp"
|
#ifndef ELEMENTS_ELEMENT_HEADER
#define ELEMENTS_ELEMENT_HEADER
#include <string>
#include <vector>
#include "Source/Math/Math.h"
#include "PhysicsUnits.h"
namespace solar
{
//Basic unit of simulated data - planet, star, moon...
struct Unit
{
public:
explicit Unit(const Vec3d& pos = Vec3d(), const Vec3d&vel = Vec3d(), double mass = 0.0, const std::string& name = "",
const Vec4d& color = Vec4d(1.0, 1.0, 1.0, 1.0), double radius = 0.0)
:pos(pos), vel(vel), mass(mass), name(name), color(color), radius(radius)
{}
Vec3d pos, vel;
double mass;
Vec4d color;
std::string name;
double radius;
};
class SimData
{
public:
using units_t = std::vector<Unit>;
//Quick access to vector of simulated units
units_t* operator->();
const units_t* operator->() const;
//Quick access to vector of simulated units
units_t& operator*();
const units_t& operator*() const;
Unit& operator[](size_t index);
const Unit& operator[](size_t index) const;
//Access to vector of simulated units
units_t& Get();
const units_t& Get() const;
//Set units in which are simData
void SetPhysUnits(PhysUnits::ratio newMass, PhysUnits::ratio newDist, PhysUnits::ratio newTime);
void SetPhysUnits(const PhysUnits& newPhysUnits);
const PhysUnits& GetPhysUnits() const;
//Converts simData to desired physics units
void ConvertTo(PhysUnits::ratio newMass, PhysUnits::ratio newDist, PhysUnits::ratio newTime);
void ConvertMassTo(PhysUnits::ratio newMass);
void ConvertDistTo(PhysUnits::ratio newDist);
void ConvertTimeTo(PhysUnits::ratio newTime);
//Converts to such units that all values lie in [-1.0,1.0]
void Normalize();
//Returns ratio with which one can multiply simData to get them to new physics units
// one can divide other numbers in new physics units to convert them to same units as data are
PhysUnits::ratio RatioOfMassTo(PhysUnits::ratio newMass) const;
PhysUnits::ratio RatioOfDistTo(PhysUnits::ratio newDist) const;
PhysUnits::ratio RatioOfTimeTo(PhysUnits::ratio newTime) const;
private:
units_t units;
//Physics units in which objects are
PhysUnits physUnits;
};
}
#endif
|
#include "DirectionalLight.h"
void DirectionalLight::setUniform(std::shared_ptr<Shader>& shader, int index)
{
shader->use();
shader->setUniform("directionalLights["+std::to_string(index)+"].color", properties.color);
shader->setUniform("directionalLights[" + std::to_string(index) + "].direction", properties.direction);
shader->unuse();
}
DirectionalLight::DirectionalLight(glm::vec3 color, glm::vec3 direction):properties(color,glm::normalize(direction))
{
}
DirectionalLight::~DirectionalLight()
{
}
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct cities
{
pair <ll,ll> coordinates;
bool visited;
double price;
};
double distance(cities c1, cities c2)
{
double dist = sqrt(pow((c1.coordinates.first - c2.coordinates.first), 2) + pow((c1.coordinates.second - c2.coordinates.second), 2));
return dist;
}
void solve(int sp, vector <cities>& v)
{
int i = sp;
double petrol = 0, ccost, excost, petreq, petuse, petrem, petbuy;
while(v.size() > 1)
{
int x = 0;
if(!i)
x = 1;
double mindist = distance(v[i], v[x]), cdist;
for(int j = 0; j < v.size(); j++)
{
cdist = distance(v[i], v[j]);
if(cdist && (cdist < mindist))
{
x = j;
mindist = cdist;
}
}
petreq = mindist/10;
if( petreq > 30 )
petreq = 30;
if(v[i].price > 6)
{
petuse = (petreq < petrol)?petreq:petrol;
petrol = petrol - petuse;
cout<<i+1<<","<<v[i].price<<","<<0<<"\n" ;
v.erase(v.begin()+i) ;
i = x;
continue;
}
if(v[i].price < v[x].price)
{
petbuy = 30 - petrol;
if(petreq > 30)
petrol = 0;
else
petrol = 30 - petreq;
v.erase(v.begin()+i) ;
cout<<i+1<<","<<v[i].price<<","<<petbuy<<"\n";
i = x;
continue;
}
petbuy = (petreq > petrol)?(petreq-petrol):0 ;
if(petreq > petrol)
petrol = 0;
else
petrol = petrol - petreq;
cout<<i+1<<","<<v[i].price<<","<<petbuy<<"\n";
v.erase(v.begin()+i) ;
i = x;
continue;
}
double cdist = distance(v[sp], v[i]) ;
petreq = cdist/10;
if(petreq > 30)
petreq = 30;
petbuy = (petreq > petrol)?(petreq-petrol):0 ;
cout<<i+1<<","<<v[i].price<<","<<petbuy<<"\n";
return ;
}
int main()
{
vector <cities> v(500);
int mini = 0; //index for min priced city
double minprice; //min price for cities
char c;
for(int i = 0; i < 500; i++)
{
cin>>v[i].coordinates.first>>c>>v[i].coordinates.second;
v[i].visited = false;
}
for(int i = 0; i < 500; i++)
{
cin>>v[i].price;
}
minprice = v[0].price ;
//now finding the city with minimum price
for(int i = 1; i < 500; i++)
{
if(v[i].price < minprice)
{
minprice = v[i].price ;
mini = i ;
}
}
solve(mini, v) ;
return 0 ;
}
|
/**
* \file VectorToc.hpp
*
* \brief To describe the content with conversion specific informations of a type.
*
*
* \todo use hashes instead of strings to describe the place in a type.
*/
#ifndef TYPETOVECTOR_VECTORTOC_HPP
#define TYPETOVECTOR_VECTORTOC_HPP
#include <string>
#include <vector>
#include <boost/shared_ptr.hpp>
#include <utilmm/stringtools.hh>
#include "NumericConverter.hpp"
namespace type_to_vector {
struct VectorToc;
typedef boost::shared_ptr<VectorToc> VectorTocPointer;
/** Information to which place in a type a vector value belongs.
*
* Only types that should be stored is numerics and containers.
* Containers will not increase the position. They have to be
* determined during conversion time. */
struct VectorValueInfo {
std::string placeDescription; //!< Something like position.3, rotation.im.1 or ...
unsigned int position; //!< The position in bytes in the memory of this value.
CastFunction castFun; //!< To cast the value, 0 for container or other type.
BackCastFunction backCastFun; //!< Cast it back to the original type.
VectorTocPointer content; //!< Subcontent (is needed for containers).
std::string containerType; //!< Type name of the content aka container.
public:
VectorValueInfo();
bool operator== (const VectorValueInfo& other) const;
};
/** Table of contents for the vector made of a type.
*
* This class holds the information where to find what in the type and how to put
* it into a vector.
*/
struct VectorToc : public std::vector<VectorValueInfo> {
std::string mType; //!< The type the toc is made for.
std::string mSlice; //!< Slice operations made and marks a concrete toc.
int maxDepth; //!< Maximum recursion depth for the visitors.
VectorToc();
void clear();
/** Checks if the toc has any containers. */
bool isFlat();
private:
class EqualityVisitor;
};
/** To recursivly go into containers. */
class VectorTocVisitor {
int mMaxDepth; //!< Max recursive depth (<0 means no depth limit).
int mDepth;
protected:
virtual void visit(VectorValueInfo const& info);
virtual void visit(VectorToc const& toc);
public:
VectorTocVisitor(int max_depth=-1) : mMaxDepth(max_depth), mDepth(0) {}
};
class SliceTree;
/** Generates a VectorToc by slicing another VectorToc.
*
* This can be used to convert a vector and should be faster
* since it has not to go through the whole VectorToc of a type.*/
class VectorTocSlicer : public VectorTocVisitor {
const VectorToc& mToc;
std::vector<VectorToc> mResultStack;
utilmm::stringlist mPlaceStack;
SliceTree* mpMatcher;
void push_element (const VectorValueInfo& info);
protected:
void visit (const VectorValueInfo& info);
public:
VectorTocSlicer (const VectorToc& toc);
~VectorTocSlicer ();
VectorToc apply (const std::string& slice);
static VectorToc slice (const VectorToc& toc, const std::string& slice);
};
} // namespace type_to_vector
#endif // TYPETOVECTOR_VECTORTOC_HPP
|
// Given two binary trees with head reference as T and S having at most N nodes. The task is to check if S is present as subtree in T.
// A subtree of a tree T1 is a tree T2 consisting of a node in T1 and all of its descendants in T1.
// bool isIdentical(Node* T,Node* S)
{
if(T==NULL && S==NULL)
{
return true;
}
if((T==NULL && S!=NULL) || (T!=NULL && S==NULL))
{
return false;
}
if(T->data != S->data)
{
return false;
}
return (isIdentical(T->left,S->left) && isIdentical(T->right,S->right));
}
void inorder(Node* T,Node* S,int& check)
{
if(T!=NULL)
{
inorder(T->left,S,check);
if(T->data == S->data)
{
bool temp = isIdentical(T,S);
if(temp==true)
{
check = 1;
return ;
}
}
inorder(T->right,S,check);
}
return ;
}
/*yu are required to
complete this function */
bool isSubTree(Node* T, Node* S) {
// Your code here
int check = 0;
// return 1 if S is subtree of T else 0
inorder(T,S,check);
if(check==1)
{
return true;
}
return false;
}
|
#include "std_lib_facilities.h"
#include "Image.h"
#include "ImageFilter.h"
#include "ComplementImageFilter.h"
#include <numeric>
ComplementImageFilter::T ComplementImageFilter::getMaxIntensity() {
//compute the max intensity value of the image (function of std)
T maxValue = *max_element(getInput().begin(), getInput().end());
return maxValue;
}
void ComplementImageFilter::execute(const Image& i) {
this->setInput(i);
max = this->getMaxIntensity();
//Resize the output image
(_output).resize(i.size());
for (unsigned int t = 0; t < i.dim(4); ++t) {
for (unsigned int c = 0; c < i.dim(3); ++c) {
for (unsigned int z = 0; z < i.dim(2); ++z) {
for (unsigned int y = 0; y < i.dim(1); ++y) {
for (unsigned int x = 0; x < i.dim(0); ++x) {
(_output)(x, y, z, c, t) = max - i(x, y, z, c, t);
}
}
}
}
}
}
|
#if (defined HAS_VTK && defined HAS_CONTRIB)
#include <irtkImage.h>
#include <irtkTransformation.h>
// Minimum norm of an eigenvector
#define MIN_NORM 0.01
#include <vtkStructuredGrid.h>
#include <vtkStructuredGridReader.h>
#include <vtkStructuredGridWriter.h>
#include <vtkUnstructuredGrid.h>
#include <vtkUnstructuredGridReader.h>
#include <vtkUnstructuredGridWriter.h>
#include <vtkFloatArray.h>
vtkPointSet *data1;
vtkPoints *points1;
vtkDataArray *vectors1;
vtkPointSet *data2;
vtkPoints *points2;
vtkDataArray *vectors2;
char *templateFileName = NULL;
char **outputFilenames = NULL;
char **inputFilenames = NULL;
char *meanFilename = NULL;
int alignVersion = 1;
vtkPointSet *read(char *file)
{
int i;
char buffer[256];
vtkPointSet *pset;
ifstream is(file);
if (!is){
cerr << "Can't open file " << file << endl;
exit(1);
}
for (i = 0; i < 3; i++){
is.getline(buffer, 256);
}
is >> buffer >> buffer;
if (strcmp(buffer, "POLYDATA") == 0) {
// Read vtkPolyData object
vtkPolyDataReader *reader = vtkPolyDataReader::New();
reader->SetFileName(file);
reader->Update();
pset = reader->GetOutput();
pset->Register(pset);
reader->Delete();
} else {
if (strcmp(buffer, "UNSTRUCTURED_GRID") == 0) {
// Read vtkUnstructuredGrid object
vtkUnstructuredGridReader *reader = vtkUnstructuredGridReader::New();
reader->SetFileName(file);
reader->Update();
pset = reader->GetOutput();
pset->Register(pset);
reader->Delete();
} else {
if (strcmp(buffer, "STRUCTURED_GRID") == 0) {
// Read vtkStructuredGrid object
vtkStructuredGridReader *reader = vtkStructuredGridReader::New();
reader->SetFileName(file);
reader->Update();
pset = reader->GetOutput();
pset->Register(pset);
reader->Delete();
} else {
cerr << "Unknown VTK data type" << endl;
exit(1);
}
}
}
return pset;
}
void write(char *file, vtkPointSet *pset)
{
if (pset->IsA("vtkStructuredGrid")){
vtkStructuredGridWriter *writer = vtkStructuredGridWriter::New();
writer->SetInputData((vtkStructuredGrid *)pset);
writer->SetFileName(file);
writer->SetFileTypeToBinary();
writer->Update();
} else {
if (pset->IsA("vtkUnstructuredGrid")){
vtkUnstructuredGridWriter *writer = vtkUnstructuredGridWriter::New();
writer->SetInputData((vtkUnstructuredGrid *)pset);
writer->SetFileName(file);
writer->SetFileTypeToBinary();
writer->Update();
} else {
if (pset->IsA("vtkPolyData")){
vtkPolyDataWriter *writer = vtkPolyDataWriter::New();
writer->SetInputData((vtkPolyData *)pset);
writer->SetFileName(file);
writer->SetFileTypeToASCII();
writer->Write();
} else {
cerr << "Unknown VTK data type" << endl;
exit(1);
}
}
}
}
void print_matrix(irtkMatrix M)
{
int i,j;
cerr << "Matrix start" << endl;
for (i=0;i<M.Rows();i++){
for (j=0;j<M.Cols();j++){
if (j!=M.Cols()-1) cerr << M(i,j) << " ";
else cerr << M(i,j) <<endl;
}
}
cerr << "Matrix end" << endl;
}
// Returns result of aligning M_1 to M_2.
// Reference argument transformation will contain the homogeneous transformation matrix.
irtkMatrix align2(irtkMatrix & M_2, irtkMatrix & M_1, int iNoOfLandmarks, irtkMatrix & transformationMatrix)
{
// calculate centroids
irtkMatrix centroid_1, centroid_2;
centroid_1.Initialize(3, 1);
centroid_2.Initialize(3, 1);
int j;
for (j = 0; j < iNoOfLandmarks; j++){
centroid_1(0, 0) += M_1(3 * j, 0);
centroid_1(1, 0) += M_1(3 * j + 1, 0);
centroid_1(2, 0) += M_1(3 * j + 2, 0);
}
for (j = 0; j < iNoOfLandmarks; j++){
centroid_2(0, 0) += M_2(3 * j, 0);
centroid_2(1, 0) += M_2(3 * j + 1, 0);
centroid_2(2, 0) += M_2(3 * j + 2, 0);
}
centroid_1 *= (1.0/iNoOfLandmarks);
centroid_2 *= (1.0/iNoOfLandmarks);
irtkVector M_1_centred, M_2_centred;
M_1_centred.Initialize(3 * iNoOfLandmarks);
M_2_centred.Initialize(3 * iNoOfLandmarks);
for (j = 0; j < iNoOfLandmarks; j++){
M_1_centred(3 * j) = M_1(3 * j , 0) - centroid_1(0, 0);
M_1_centred(3 * j + 1) = M_1(3 * j + 1, 0) - centroid_1(1, 0);
M_1_centred(3 * j + 2) = M_1(3 * j + 2, 0) - centroid_1(2, 0);
M_2_centred(3 * j) = M_2(3 * j , 0) - centroid_2(0, 0);
M_2_centred(3 * j + 1) = M_2(3 * j + 1, 0) - centroid_2(1, 0);
M_2_centred(3 * j + 2) = M_2(3 * j + 2, 0) - centroid_2(2, 0);
}
double norm_1 = 0.0;
double norm_2 = 0.0;
for (j = 0; j < 3 * iNoOfLandmarks; ++j){
norm_1 += M_1_centred(j) * M_1_centred(j);
norm_2 += M_2_centred(j) * M_2_centred(j);
}
norm_1 = sqrt(norm_1);
norm_2 = sqrt(norm_2);
// Normalise the scales of the datasets.
for (j = 0; j < 3 * iNoOfLandmarks; ++j){
M_1_centred(j) = M_1_centred(j) / norm_1;
M_2_centred(j) = M_2_centred(j) / norm_2;
}
// Treat M_1_centred and M_2_centred as Z_1 and Z_2 as per Mardia & Dryden.
// calculate Z_2^T * Z_1, call it m.
irtkMatrix m;
m.Initialize(3, 3);
for (j = 0; j < iNoOfLandmarks; j++){
m(0, 0) += M_2_centred(3 * j ) * M_1_centred(3 * j );
m(0, 1) += M_2_centred(3 * j ) * M_1_centred(3 * j + 1);
m(0, 2) += M_2_centred(3 * j ) * M_1_centred(3 * j + 2);
m(1, 0) += M_2_centred(3 * j + 1) * M_1_centred(3 * j );
m(1, 1) += M_2_centred(3 * j + 1) * M_1_centred(3 * j + 1);
m(1, 2) += M_2_centred(3 * j + 1) * M_1_centred(3 * j + 2);
m(2, 0) += M_2_centred(3 * j + 2) * M_1_centred(3 * j );
m(2, 1) += M_2_centred(3 * j + 2) * M_1_centred(3 * j + 1);
m(2, 2) += M_2_centred(3 * j + 2) * M_1_centred(3 * j + 2);
}
irtkMatrix u, v, d;
irtkVector w;
d.Initialize(3, 3);
u.Initialize(3, 3);
v.Initialize(3, 3);
w.Initialize(3);
m.SVD(v, w, u);
// m = v * d * (~u);
d(0, 0) = w(0);
d(1, 1) = w(1);
d(2, 2) = w(2);
double scale, beta;
beta = w(0) + w(1) + w(2);
scale = norm_2 * beta / norm_1;
// Ignoring beta seems to give better results.
scale = norm_2 / norm_1;
irtkMatrix rot;
rot.Initialize(3, 3);
rot = u * (~v);
// now calculate translation t
irtkMatrix t;
t.Initialize(3, 1);
t = centroid_2 - (~rot) * centroid_1 * scale;
// now transform shape 2 into coordinate system of shape 1
irtkMatrix transformed_M_1;
transformed_M_1.Initialize(3 * iNoOfLandmarks, 1);
for (j = 0; j < iNoOfLandmarks; j++){
transformed_M_1(3 * j, 0) = M_1(3 * j, 0) * rot(0, 0) + M_1(3 * j + 1, 0) * rot(1, 0) + M_1(3 * j + 2, 0) * rot(2, 0);
transformed_M_1(3 * j + 1, 0) = M_1(3 * j, 0) * rot(0, 1) + M_1(3 * j + 1, 0) * rot(1, 1) + M_1(3 * j + 2, 0) * rot(2, 1);
transformed_M_1(3 * j + 2, 0) = M_1(3 * j, 0) * rot(0, 2) + M_1(3 * j + 1, 0) * rot(1, 2) + M_1(3 * j + 2, 0) * rot(2, 2);
}
transformed_M_1 *= scale;
for (j = 0; j < iNoOfLandmarks; j++){
transformed_M_1(3 * j, 0) += t(0, 0);
transformed_M_1(3 * j + 1, 0) += t(1, 0);
transformed_M_1(3 * j + 2, 0) += t(2, 0);
}
// Store the transformation matrix if it is needed.
transformationMatrix *= 0;
// Put the rotation matrix into the upper left corner.
rot.Transpose();
transformationMatrix(rot, 0, 0);
transformationMatrix *= scale;
// Put the translation in the right column
transformationMatrix(t, 0, 3);
// Set the bottom right corner.
transformationMatrix(3, 3) = 1.0;
return transformed_M_1;
}
// Returns result of aligning M_2 to M_1.
// Reference argument transformation will contain the homogeneous transformation matrix.
irtkMatrix align1(irtkMatrix & M_1, irtkMatrix & M_2, int iNoOfLandmarks, irtkMatrix & transformationMatrix)
{
// calculate centroids
irtkMatrix centroid_1, centroid_2;
centroid_1.Initialize(3, 1);
centroid_2.Initialize(3, 1);
// int i, j;
int j;
for (j = 0; j < iNoOfLandmarks; j++){
centroid_1(0, 0) += M_1(3 * j, 0);
centroid_1(1, 0) += M_1(3 * j + 1, 0);
centroid_1(2, 0) += M_1(3 * j + 2, 0);
}
for (j = 0; j < iNoOfLandmarks; j++){
centroid_2(0, 0) += M_2(3 * j, 0);
centroid_2(1, 0) += M_2(3 * j + 1, 0);
centroid_2(2, 0) += M_2(3 * j + 2, 0);
}
centroid_1 *= (1.0/iNoOfLandmarks);
centroid_2 *= (1.0/iNoOfLandmarks);
irtkVector M_1_centred, M_2_centred;
M_1_centred.Initialize(3 * iNoOfLandmarks);
M_2_centred.Initialize(3 * iNoOfLandmarks);
for (j = 0; j < iNoOfLandmarks; j++){
M_1_centred(3 * j) = M_1(3 * j , 0) - centroid_1(0, 0);
M_1_centred(3 * j + 1) = M_1(3 * j + 1, 0) - centroid_1(1, 0);
M_1_centred(3 * j + 2) = M_1(3 * j + 2, 0) - centroid_1(2, 0);
M_2_centred(3 * j) = M_2(3 * j , 0) - centroid_2(0, 0);
M_2_centred(3 * j + 1) = M_2(3 * j + 1, 0) - centroid_2(1, 0);
M_2_centred(3 * j + 2) = M_2(3 * j + 2, 0) - centroid_2(2, 0);
}
// have centroid centred data
// now calculate sums for matrix N, shape 1 is right coord system, shape
// 2 is left coord system, doing left to right
float sxx, sxy, sxz, syx, syy, syz, szx, szy, szz;
sxx = sxy = sxz = syx = syy = syz = szx = szy = szz = 0;
for (j = 0; j < iNoOfLandmarks; j++){
sxx += M_2_centred(3 * j) * M_1_centred(3 * j);
sxy += M_2_centred(3 * j) * M_1_centred(3 * j + 1);
sxz += M_2_centred(3 * j) * M_1_centred(3 * j + 2);
syx += M_2_centred(3 * j + 1) * M_1_centred(3 * j);
syy += M_2_centred(3 * j + 1) * M_1_centred(3 * j + 1);
syz += M_2_centred(3 * j + 1) * M_1_centred(3 * j + 2);
szx += M_2_centred(3 * j + 2) * M_1_centred(3 * j);
szy += M_2_centred(3 * j + 2) * M_1_centred(3 * j + 1);
szz += M_2_centred(3 * j + 2) * M_1_centred(3 * j + 2);
}
irtkMatrix N;
N.Initialize(4,4);
N(0, 0) = sxx + syy + szz;
N(1, 1) = sxx - syy - szz;
N(2, 2) = -sxx + syy - szz;
N(3, 3) = -sxx - syy + szz;
N(0, 1) = N(1, 0) = syz - szy;
N(0, 2) = N(2, 0) = szx - sxz;
N(1, 2) = N(2, 1) = sxy + syx;
N(0, 3) = N(3, 0) = sxy - syx;
N(1, 3) = N(3, 1) = szx + sxz;
N(2, 3) = N(3, 2) = syz + szy;
irtkVector er;
er.Initialize(4);
irtkMatrix ev, ev2;
ev.Initialize(4,4);
ev2.Initialize(4,4);
N.Eigenvalues(ev, er, ev2);
//1st eigenvector is quaternion of the rotation
irtkVector quat;
quat.Initialize(4);
quat(0) = ev(0, 0);
quat(1) = ev(1, 0);
quat(2) = ev(2, 0);
quat(3) = ev(3, 0);
// calculate rotation matrix
irtkMatrix Rot;
Rot.Initialize(3, 3);
Rot(0, 0) = quat(0) * quat(0) + quat(1) * quat(1) - quat(2) * quat(2) - quat(3) * quat(3);
Rot(1, 1) = quat(0) * quat(0) - quat(1) * quat(1) + quat(2) * quat(2) - quat(3) * quat(3);
Rot(2, 2) = quat(0) * quat(0) - quat(1) * quat(1) - quat(2) * quat(2) + quat(3) * quat(3);
Rot(0, 1) = 2 * (quat(1) * quat(2) - quat(0) * quat(3));
Rot(1, 0) = 2 * (quat(1) * quat(2) + quat(0) * quat(3));
Rot(0, 2) = 2 * (quat(1) * quat(3) + quat(0) * quat(2));
Rot(2, 0) = 2 * (quat(1) * quat(3) - quat(0) * quat(2));
Rot(1, 2) = 2 * (quat(2) * quat(3) - quat(0) * quat(1));
Rot(2, 1) = 2 * (quat(2) * quat(3) + quat(0) * quat(1));
// calculate scale, symmetric scaling is used
float scale, shape1dev, shape2dev;
shape1dev = shape2dev = 0.0;
for (j = 0; j < iNoOfLandmarks; j++){
shape1dev += M_1_centred(3 * j) * M_1_centred(3 * j);
shape1dev += M_1_centred(3 * j + 1) * M_1_centred(3 * j + 1);
shape1dev += M_1_centred(3 * j + 2) * M_1_centred(3 * j + 2);
shape2dev += M_2_centred(3 * j) * M_2_centred(3 * j);
shape2dev += M_2_centred(3 * j + 1) * M_2_centred(3 * j + 1);
shape2dev += M_2_centred(3 * j + 2) * M_2_centred(3 * j + 2);
}
scale = sqrt(shape1dev/shape2dev);
// now calculate translation t
irtkMatrix t;
t.Initialize(3, 1);
t = centroid_1 - Rot * centroid_2 * scale;
// now transform shape 2 into coordinate system of shape 1
irtkMatrix transformed_M_2;
transformed_M_2.Initialize(3 * iNoOfLandmarks, 1);
for (j = 0; j < iNoOfLandmarks; j++){
transformed_M_2(3 * j, 0) = Rot(0, 0) * M_2(3 * j, 0) + Rot(0, 1) * M_2(3 * j + 1, 0) + Rot(0, 2) * M_2(3 * j + 2, 0);
transformed_M_2(3 * j + 1, 0) = Rot(1, 0) * M_2(3 * j, 0) + Rot(1, 1) * M_2(3 * j + 1, 0) + Rot(1, 2) * M_2(3 * j + 2, 0);
transformed_M_2(3 * j + 2, 0) = Rot(2, 0) * M_2(3 * j, 0) + Rot(2, 1) * M_2(3 * j + 1, 0) + Rot(2, 2) * M_2(3 * j + 2, 0);
}
transformed_M_2 *= scale;
for (j = 0; j < iNoOfLandmarks; j++){
transformed_M_2(3 * j, 0) = transformed_M_2(3 * j, 0) + t(0, 0);
transformed_M_2(3 * j + 1, 0) = transformed_M_2(3 * j + 1, 0) + t(1, 0);
transformed_M_2(3 * j + 2, 0) = transformed_M_2(3 * j + 2, 0) + t(2, 0);
}
// Store the transformation matrix if it is needed.
transformationMatrix *= 0;
// Put the rotation matrix into the upper left corner.
transformationMatrix(Rot, 0, 0);
transformationMatrix *= scale;
// Put the translation in the right column
transformationMatrix(t, 0, 3);
// Set the bottom right corner.
transformationMatrix(3, 3) = 1.0;
return transformed_M_2;
}
irtkMatrix align(irtkMatrix & M_1, irtkMatrix & M_2, int iNoOfLandmarks, irtkMatrix & transformationMatrix)
{
if (alignVersion == 1){
return align1(M_1, M_2, iNoOfLandmarks, transformationMatrix);
} else if (alignVersion == 2) {
return align2(M_1, M_2, iNoOfLandmarks, transformationMatrix);
} else {
cerr << "non-valid align version : " << alignVersion << endl;
exit(1);
}
}
void usage(){
cerr << "Usage: procrustes_align N [inSurf_1] ... [inSurf_N] [outSurf_1] ... [outSurf_N] <options>" << endl;
cerr << "Procrustes alignment of inSurf_1 ... inSurf_N. Write results to outSurf_1 ... outSurf_N" << endl;
cerr << "N is the number of datasets." << endl;
cerr << "Options:" << endl;
cerr << "-dofs : Write the transformations from each input surface to the procrustes mean." << endl;
cerr << "-v : verbose." << endl;
cerr << "-m [file] : write mean shape to [file]" << endl;
exit(0);
}
int main(int argc, char **argv)
{
// This code does a Procustes alignment of a series of shapes using
// scaling, rotations and translations output is all the aligned shapes
int i, j, k;
bool writeDofs, writeMean, verbose;
bool ok;
writeDofs = false;
writeMean = false;
verbose = false;
irtkMatrix *matrices;
irtkMatrix dummyMatrix(4, 4);
irtkAffineTransformation *dof = new irtkAffineTransformation;
double coord[3];
char buf[300];
char dofSuffix[] = "dof\0";
if (argc < 3){
usage();
}
// Number of datasets.
int iNoOfDatasets = atoi(argv[1]);
argv++;
argc--;
// Template for connectivity. Used when writing results.
templateFileName = argv[1];
int iNoOfLandmarks_1, iNoOfLandmarks_2;
iNoOfLandmarks_1 = iNoOfLandmarks_2 = 0;
irtkMatrix M_1;
// Read in the names of the input files.
inputFilenames = new char*[iNoOfDatasets];
for (i = 0; i < iNoOfDatasets; i++){
inputFilenames[i] = argv[1];
argv++;
argc--;
}
// Read in the names of the output files.
outputFilenames = new char*[iNoOfDatasets];
for (i = 0; i < iNoOfDatasets; i++){
outputFilenames[i] = argv[1];
argv++;
argc--;
}
// Make space for transformation matrices.
matrices = new irtkMatrix[iNoOfDatasets];
for (i = 0; i < iNoOfDatasets; i++){
matrices[i].Initialize(4, 4);
}
// Read optional arguments.
while (argc > 1){
ok = false;
if ((ok == false) && (strcmp(argv[1], "-dofs") == 0)){
argc--;
argv++;
writeDofs = true;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-v") == 0)){
argc--;
argv++;
verbose = true;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-m") == 0)){
argc--;
argv++;
writeMean = true;
meanFilename = argv[1];
argc--;
argv++;
ok = true;
}
if ((ok == false) && (strcmp(argv[1], "-av") == 0)){
argc--;
argv++;
alignVersion = atoi(argv[1]);
argc--;
argv++;
ok = true;
}
if (ok == false){
cerr << "Cannot parse argument " << argv[1] << endl;
usage();
}
}
// Read all landmarks_1 in matrix M_1
for (i = 0; i < iNoOfDatasets; i++){
data1 = read(inputFilenames[i]);
points1 = data1->GetPoints();
vectors1 = data1->GetPointData()->GetVectors();
if (i == 0){
iNoOfLandmarks_1 = points1->GetNumberOfPoints();
M_1.Initialize(3 * iNoOfLandmarks_1, iNoOfDatasets);
cerr << "There are " << iNoOfDatasets
<< " datasets with "
<< points1->GetNumberOfPoints()
<< " landmarks." << endl;
}
if (verbose){
cerr << "Including landmarks in " << inputFilenames[i] << endl;
}
for (j = 0; j < iNoOfLandmarks_1; j++){
double p[3];
points1->GetPoint(j, p);
M_1(3 * j, i) = p[0];
M_1(3 * j + 1, i) = p[1];
M_1(3 * j + 2, i) = p[2];
}
}
// matrix of all aligned shapes
irtkMatrix aligned_shapes(3 * iNoOfLandmarks_1, iNoOfDatasets);
// align each shape to first data set and calculate mean of aligned shapes
irtkMatrix first_shape;
first_shape.Initialize(3 * iNoOfLandmarks_1, 1);
for (j = 0; j < 3 * iNoOfLandmarks_1; j++)
first_shape(j, 0) = M_1(j, 0);
// current mean pre alignment
irtkMatrix current_mean;
// initialize as first shape
current_mean = first_shape;
// shape we are currently aligning to aligned mean
irtkMatrix current_shapetoalign;
current_shapetoalign.Initialize(3 * iNoOfLandmarks_1, 1);
// current shape after aligning to aligned mean
irtkMatrix current_alignedshape;
for (i = 0; i < iNoOfDatasets; i++)
{
// align ith shape
for (j = 0; j < 3 * iNoOfLandmarks_1; j++){
current_shapetoalign(j, 0) = M_1(j, i);
}
current_alignedshape = align(first_shape, current_shapetoalign, iNoOfLandmarks_1, dummyMatrix);
if (verbose){
cerr << "aligned shape " << i << " to first shape" << endl;
}
// add to current mean
for (j = 0; j < 3 * iNoOfLandmarks_1; j++){
current_mean(j, 0) += current_alignedshape(j, 0);
}
}
// now have mean of aligned shapes
current_mean *= (1.0 / iNoOfDatasets);
float error2 = 0.0;
for (j = 0; j < 3 * iNoOfLandmarks_1; j++){
error2 += (first_shape(j, 0) - current_mean(j, 0)) * (first_shape(j, 0) - current_mean(j, 0));
}
cerr << "error = " << error2/(3 * iNoOfLandmarks_1) << endl;;
// align mean to first data set
//stores aligned mean that we use going into loop
irtkMatrix previous_aligned_mean;
previous_aligned_mean = align(first_shape, current_mean, iNoOfLandmarks_1, dummyMatrix);
cerr << "aligned mean to first shape" << endl;
irtkMatrix current_aligned_mean; //stores aligned mean calculated at end of loop
int noits = 0;
float error;
do{
// reinitialize current mean
for (j = 0;j<3 * iNoOfLandmarks_1;j++){
current_mean(j, 0) = 0.0;
}
// realign every shape with previous aligned mean
for (i = 0; i < iNoOfDatasets; i++){
// align ith shape
for (j = 0; j < 3 * iNoOfLandmarks_1; j++){
current_shapetoalign(j, 0) = M_1(j, i);
}
current_alignedshape = align(previous_aligned_mean, current_shapetoalign, iNoOfLandmarks_1, matrices[i]);
for (j = 0; j < 3 * iNoOfLandmarks_1; j++){
aligned_shapes(j, i) = current_alignedshape(j, 0);
}
// add to current mean
for (j = 0; j < 3 * iNoOfLandmarks_1; j++){
current_mean(j, 0)+=current_alignedshape(j, 0);
}
}
current_mean *= (1.0 / iNoOfDatasets);
current_aligned_mean = align(first_shape, current_mean, iNoOfLandmarks_1, dummyMatrix);
for (i = 0; i < iNoOfDatasets; i++){
matrices[i] = dummyMatrix * matrices[i];
}
error = 0;
for (j = 0; j < 3 * iNoOfLandmarks_1; j++){
error+= (current_aligned_mean(j, 0) - previous_aligned_mean(j, 0)) * (current_aligned_mean(j, 0) - previous_aligned_mean(j, 0));
}
cerr << "error = " << error << endl;
noits++;
previous_aligned_mean = current_aligned_mean;
cerr << "no. of iterations = " << noits << endl;
} while (error>0.0000001);
// Write aligned shapes as vtk output
// Read surface used as template.
vtkPolyDataReader *surface_reader = vtkPolyDataReader::New();
surface_reader->SetFileName(templateFileName);
surface_reader->Modified();
surface_reader->Update();
vtkPolyData *surface = surface_reader->GetOutput();
for (j = 0; j < iNoOfDatasets; j++){
for (i = 0; i < surface->GetNumberOfPoints(); i++){
coord[0] = aligned_shapes(3 * i , j);
coord[1] = aligned_shapes(3 * i + 1, j);
coord[2] = aligned_shapes(3 * i + 2, j);
surface->GetPoints()->SetPoint(i, coord);
}
surface->Modified();
vtkPolyDataWriter *writer = vtkPolyDataWriter::New();
writer->SetInputData(surface);
if (verbose){
cout << "Writing output " << j + 1 << " to " << outputFilenames[j] << endl;
}
writer->SetFileName(outputFilenames[j]);
writer->Write();
if (writeDofs == true){
strcpy(buf, outputFilenames[j]);
k = 0;
while (buf[k] != '\0'){
k++;
}
strcpy(&buf[k - 3], dofSuffix);
if (verbose){
cout << "Dof file is : " << buf << endl;
}
dof->PutMatrix(matrices[j]);
dof->irtkTransformation::Write(buf);
}
}
if (writeMean == true && meanFilename != NULL){
for (i = 0; i < surface->GetNumberOfPoints(); i++){
coord[0] = current_aligned_mean(3 * i , 0);
coord[1] = current_aligned_mean(3 * i + 1, 0);
coord[2] = current_aligned_mean(3 * i + 2, 0);
surface->GetPoints()->SetPoint(i, coord);
}
cout << "Writing mean to " << meanFilename << endl;
surface->Modified();
vtkPolyDataWriter *writer = vtkPolyDataWriter::New();
writer->SetInputData(surface);
writer->SetFileName(meanFilename);
writer->Write();
}
exit(0);
///////////////////// TESTING
double ssq, meanPt[3], sd, maxSD;
for (i = 0; i < surface->GetNumberOfPoints(); i++){
coord[0] = coord[1] = coord[2] = 0;
for (j = 0; j < iNoOfDatasets; j++){
coord[0] += (M_1(3 * i , j) / iNoOfDatasets);
coord[1] += (M_1(3 * i + 1, j) / iNoOfDatasets);
coord[2] += (M_1(3 * i + 2, j) / iNoOfDatasets);
}
surface->GetPoints()->SetPoint(i, coord);
}
vtkFloatArray *scalars = vtkFloatArray::New();
scalars->SetNumberOfComponents(1);
maxSD = 0;
for (i = 0; i < surface->GetNumberOfPoints(); i++){
surface->GetPoint(i, meanPt);
ssq = 0;
for (j = 0; j < iNoOfDatasets; j++){
ssq += (M_1(3 * i , j) - meanPt[0]) * (M_1(3 * i , j) - meanPt[0]);
ssq += (M_1(3 * i + 1, j) - meanPt[1]) * (M_1(3 * i + 1, j) - meanPt[1]);
ssq += (M_1(3 * i + 2, j) - meanPt[2]) * (M_1(3 * i + 2, j) - meanPt[2]);
}
sd = sqrt(ssq / iNoOfDatasets);
scalars->InsertTuple1(i, sd);
if (sd > maxSD){
maxSD = sd;
}
}
surface->GetPointData()->AddArray(scalars);
cout << "Writing second mean with scalars to blah.vtk" << endl;
cout << "Maximum SD = " << maxSD << endl;
vtkPolyDataWriter *writer = vtkPolyDataWriter::New();
writer->SetInputData(surface);
writer->SetFileName("blah.vtk");
writer->Write();
}
#else
#include <irtkImage.h>
int main( int argc, char *argv[] ){
cerr << argv[0] << " needs to be compiled with the contrib and VTK library"
<< endl;
}
#endif
|
#include "imath.h"
#include <cassert>
#include <algorithm>
Vec2::Vec2(float x, float y)
: x(x),
y(y)
{}
void Vec2::set(float x, float y) {
x = x;
y = y;
}
Vec2 Vec2::operator-() const {
return Vec2(-x, -y);
}
Vec2 Vec2::operator*(float s) const {
return Vec2(x * s, y * s);
}
Vec2 Vec2::operator/(float s) const {
return Vec2(x / s, y / s);
}
void Vec2::operator*=(float s) {
x *= s;
y *= s;
}
Vec2 Vec2::operator+(const Vec2& rhs) const {
return Vec2(x + rhs.x, y + rhs.y);
}
Vec2 Vec2::operator+(float s) const {
return Vec2(x + s, y + s);
}
void Vec2::operator+=(const Vec2& rhs) {
x += rhs.x;
y += rhs.y;
}
Vec2 Vec2::operator-(const Vec2& rhs) const {
return Vec2(x - rhs.x, y - rhs.y);
}
void Vec2::operator-=(const Vec2& rhs) {
x -= rhs.x;
y -= rhs.y;
}
float Vec2::len_sqr() const {
return x * x + y * y;
}
float Vec2::len() const {
return std::sqrt(x * x + y * y);
}
void Vec2::rotate_self(float radians) {
const float c = std::cos(radians);
const float s = std::sin(radians);
const float xp = x * c - y * s;
const float yp = x * s + y * c;
x = xp;
y = yp;
}
Vec2 Vec2::rotate(float radians) const {
Vec2 v = *this;
v.rotate_self(radians);
return v;
}
void Vec2::normalize_self() {
const float l = len();
if (l > EPSILON) {
const float inv_l = 1.0f / l;
x *= inv_l;
y *= inv_l;
}
}
Vec2 Vec2::normalize() const {
Vec2 v = *this;
v.normalize_self();
return v;
}
Vec2 operator*(float s, const Vec2& v) {
return Vec2(s * v.x, s * v.y);
}
float dot(const Vec2& a, const Vec2& b) {
return a.x * b.x + a.y * b.y;
}
float dist_sqr(const Vec2& a, const Vec2& b) {
const Vec2 c = a - b;
return dot(c, c);
}
float projection_on(const Vec2& v, const Vec2& axis) {
return dot(v, axis.normalize());
}
bool is_equal_eps(float a, float b) {
return std::abs(a - b) <= EPSILON;
}
float clamp(float min, float max, float a) {
if (a < min) {
return min;
}
if (a > max) {
return max;
}
return a;
}
float random(float l, float h) {
float a = (float)rand();
a /= RAND_MAX;
a = (h - l) * a + l;
return a;
}
// vim: set tabstop=2 shiftwidth=2 softtabstop=2 expandtab:
|
#ifndef QMLTOAST_H
#define QMLTOAST_H
#include <QObject>
class QmlToast : public QObject
{
Q_OBJECT
public:
enum Duration {
Short = 0x00000000,
Long = 0x00000001
};
Q_ENUM(Duration)
explicit QmlToast(QObject *parent = nullptr);
public slots:
void toast(const QString &text, Duration duration = Short);
};
#endif // QMLTOAST_H
|
// Filename: dnaSignBaseline.h
// Created by: skyler (2001-30-01)
//
////////////////////////////////////////////////////////////////////
#ifndef DNASignBaseline_H
#define DNASignBaseline_H
//
#include "dnaNode.h"
#include "dnaBuildings.h"
#include "textFont.h"
#include "pandaNode.h"
#include "nodePath.h"
#include "luse.h"
#include "pvector.h"
class DNASignText;
////////////////////////////////////////////////////////////////////
// Class : DNASignBaseline
// Description : A Sign
////////////////////////////////////////////////////////////////////
class EXPCL_TOONTOWN DNASignBaseline : public DNANode {
PUBLISHED:
DNASignBaseline(const std::string &initial_name = "");
DNASignBaseline(const DNASignBaseline &Sign);
virtual NodePath traverse(NodePath &parent, DNAStorage *store, int editing=0);
virtual void write(std::ostream &out, DNAStorage *store, int indent_level = 0) const;
INLINE void set_code(std::string code);
INLINE std::string get_code() const;
INLINE void set_color(const LColorf &color);
INLINE LColorf get_color() const;
INLINE void set_font(TextFont *font);
INLINE TextFont *get_font() const;
INLINE void set_indent(float indent);
INLINE float get_indent() const;
INLINE void set_kern(float kern);
INLINE float get_kern() const;
INLINE float get_current_kern();
INLINE void set_wiggle(float wiggle);
INLINE float get_wiggle() const;
INLINE float get_current_wiggle();
INLINE void set_stumble(float stumble);
INLINE float get_stumble() const;
INLINE float get_current_stumble();
INLINE void set_stomp(float stomp);
INLINE float get_stomp() const;
INLINE float get_current_stomp();
INLINE void set_width(float width);
INLINE float get_width() const;
INLINE void set_height(float height);
INLINE float get_height() const;
INLINE void set_flags(std::string flags);
INLINE std::string get_flags() const;
bool isFirstLetterOfWord(std::string letter);
void reset_counter();
void inc_counter();
virtual void baseline_next_pos_hpr_scale(
LVector3f &pos, LVector3f &hpr, LVector3f &scale,
const LVector3f &size);
protected:
std::string _code;
std::string _flags;
LColorf _color;
PT(TextFont) _font;
LVector3f _next_pos;
LVector3f _next_hpr;
LVector3f _next_scale;
float _indent;
float _kern;
float _wiggle;
float _stumble;
float _stomp;
float _total_width;
int _counter;
float _width;
float _height;
float _prior_cursor;
float _cursor;
bool _priorCharWasBlank;
virtual void reset();
void center(LVector3f &pos, LVector3f &hpr);
// Lines:
void line_next_pos_hpr_scale(
LVector3f &pos, LVector3f &hpr, LVector3f &scale,
const LVector3f &size);
// Circles:
void circle_next_pos_hpr_scale(
LVector3f &pos, LVector3f &hpr, LVector3f &scale,
const LVector3f &size);
private:
virtual DNAGroup* make_copy();
public:
static TypeHandle get_class_type() {
return _type_handle;
}
static void init_type() {
DNANode::init_type();
register_type(_type_handle, "DNASignBaseline",
DNANode::get_class_type()
);
}
virtual TypeHandle get_type() const {
return get_class_type();
}
virtual TypeHandle force_init_type() {init_type(); return get_class_type();}
private:
static TypeHandle _type_handle;
};
#include "dnaSignBaseline.I"
#endif
|
#include <bitset>
#include <iostream>
int main(int argc, char *argv[])
{
enum Color{red, yellow, green,blue, white, black ,numColors};
std::bitset<numColors> usedColors;
usedColors.set(red);
usedColors.set(blue);
std::cout << "bitfield of used colors: " << usedColors << std::endl;
std::cout << "number of used colors:" << usedColors.count() << std::endl;
std::cout << "bitfield of unused colors: " << ~usedColors << std::endl;
if(usedColors.any()){
for(int c = 0; c < numColors; ++c){
// if(usedColors[(Color)c]){
std::cout << "c = "<< c << " usedCorlors = " << usedColors[(Color)c] << std::endl;
//}
}
}
return 0;
}
|
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <set>
#include <cmath>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <cstring>
#include <climits>
#include <queue>
#include <assert.h>
using namespace std;
int R,C;
int h,v;
int color;
int visited[20][20];
int grid[20][20];
bool exist[16];
bool hExist[4];
bool vExist[4];
int expand(int x, int y){
if(x<0 || x>=R || y<0 || y>=C || visited[x][y]){return 0;}
visited[x][y]=1;
bool isBlack= (grid[x][y]==1);
if(y<v && x<h){
if( isBlack && (!(color & 8)) ){return 0;}
if( !isBlack && (color &8)){return 0;}
}
else if(y>=v && x<h){
if( isBlack && (!(color & 4)) ){return 0;}
if( !isBlack && (color &4)){return 0;}
}
else if(y<v && x>=h){
if( isBlack && (!(color & 2)) ){return 0;}
if( !isBlack && (color & 2)){return 0;}
}
else if(y>=v && x>=h){
if( isBlack && (!(color & 1)) ){return 0;}
if( !isBlack && (color & 1)){return 0;}
}
int myVal=0;
myVal+=expand(x+1,y);
myVal+=expand(x-1,y);
myVal+=expand(x,y+1);
myVal+=expand(x,y-1);
myVal++;
return myVal;
}
int compute(){
int answer=0;
for(int i=0;i<R;++i){
for(int j=0;j<C;++j){
if(!visited[i][j]){
int p=expand(i,j);
answer=max(answer,p);
}
}
}
return answer;
}
int main(){
int T;
cin>>T;
for(int tt=1;tt<T+1;++tt){
cin>>R>>C;
for(int i=0;i<R;++i){
string line;
cin>>line;
for(int j=0;j<C;++j){
if(line[j]=='B'){grid[i][j]=1;}
else{grid[i][j]=0;}
}
}
memset(exist,0,sizeof exist);
memset(hExist,0,sizeof hExist);
memset(vExist,0,sizeof vExist);
int m1,m2,m3,m4;
for(int i=1;i<R;++i){
for(int j=1;j<C;++j){
m1=(grid[i-1][j-1]<<1)+grid[i-1][j];
m2=(grid[i][j-1]<<1)+grid[i][j];
hExist[m1]=true;
hExist[m2]=true;
exist[(m1<<2)+m2]=true;
m3=(grid[i-1][j-1]<<1)+grid[i][j-1];
m4=(grid[i-1][j]<<1)+grid[i][j];
vExist[m3]=true;
vExist[m4]=true;
}
}
for(int j=1;j<C;++j){
hExist[(grid[0][j-1]<<1)+grid[0][j]]=true;
}
for(int i=1;i<R;++i){
vExist[(grid[i-1][0]<<1)+grid[i][0]]=true;
}
int result=0;
for(int cool=0;cool<(1<<4);cool++){
color=cool;
for(int vertical=0;vertical<=C;++vertical){
for(int horizontal=0;horizontal<=R;++horizontal){
v=vertical;
h=horizontal;
if((0<h) && (h<R) && (0<v) && (v<C) && (!exist[ color ]) ) {continue;}
if((0<h) && (h<R) && (v==0) && !vExist[ (((color&4)>>2)<<1) + (color & 1) ] ){continue;}
if((0<h) && (h<R) && (v==C) && !vExist[ (((color&8)>>3)<<1)+ ((color & 2)>>1) ] ) {continue;}
if((0<v) && (v<C) && (h==0) && !hExist[ (color & 3) ] ) {continue;}
if((0<v) && (v<C) && (h==R) && !hExist[ (color>>2) ] ){continue;}
memset(visited,0,sizeof visited);
int r=compute();
result=max(result,r);
}
}
}
cout<<"Case #"<<tt<<": "<<result<<endl;
}
}
|
#include "Student.h"
Student::Student() {
this->id = 0;
this->name = "";
this->school = "";
this->score = 0;
}
void Student::showInfo() {
cout << "학번 : " << this->id << endl;
cout << "이름 : " << this->name << endl;
cout << "출신학교 : " << this->school << endl;
cout << "점수 : " << this->score << endl;
}
|
//
// Created by zanbo on 2020/5/2.
//
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if( (p==NULL && q!=NULL) || (p!=NULL && q==NULL)) return false;
if(p==NULL && q==NULL) return true;
if(p->val != q->val) return false;
return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}
};
|
/*
* SomaInt.cpp
*
* Created on: 10 de fev de 2018
* Author: kryptonian
*/
#include <iostream>
using namespace std;
int main() {
int x = 10;
int y = 25;
int z = x + y;
cout << endl;
cout << x << " + " << y << " = " << z;
}
|
#pragma once
#include <QThread>
#include "MyFFmpeg.h"
#include <list>
using namespace std;
class PlayThread : public QThread
{
Q_OBJECT
public:
// static PlayThread* GetObj()
// {
// static PlayThread pt(MyFFmpeg::GetObj());
// return &pt;
// }
~PlayThread();
PlayThread(MyFFmpeg * m_ffmpeg);
void run();
private:
MyFFmpeg* m_ffmpeg;
// list<AVPacket> g_videos;
};
|
/***********************************************************************
created: Fri Jun 06 2014
author: Timotei Dolean <timotei21@gmail.com>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
*
* 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 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 "CEGUI/WindowRendererSets/Core/TreeView.h"
#include "CEGUI/falagard/WidgetLookManager.h"
#include "CEGUI/falagard/WidgetLookFeel.h"
#include "CEGUI/Image.h"
#include "CEGUI/ImageManager.h"
namespace CEGUI
{
//----------------------------------------------------------------------------//
const String FalagardTreeView::TypeName("Core/TreeView");
static ColourRect ICON_COLOUR_RECT(Colour(1, 1, 1, 1));
//----------------------------------------------------------------------------//
FalagardTreeView::FalagardTreeView(const String& type) :
TreeViewWindowRenderer(type),
d_subtreeExpanderImagery(nullptr),
d_subtreeCollapserImagery(nullptr),
d_subtreeExpanderImagerySize(0, 0)
{
}
//----------------------------------------------------------------------------//
void FalagardTreeView::createRenderGeometry()
{
const WidgetLookFeel& wlf = getLookNFeel();
TreeView* tree_view = getView();
tree_view->prepareForRender();
bool has_focused_state =
tree_view->isFocused() && wlf.isStateImageryPresent("EnabledFocused");
const StateImagery* imagery = &wlf.getStateImagery(
tree_view->isEffectiveDisabled() ? "Disabled" :
(has_focused_state ? "EnabledFocused" : "Enabled"));
imagery->render(*tree_view);
Rectf items_area(getViewRenderArea());
glm::vec2 item_pos(getItemRenderStartPosition(tree_view, items_area));
renderTreeItem(tree_view, items_area, item_pos, &tree_view->getRootItemState(), 0);
}
//----------------------------------------------------------------------------//
void FalagardTreeView::renderTreeItem(TreeView* tree_view, const Rectf& items_area,
glm::vec2& item_pos, const TreeViewItemRenderingState* item_to_render, size_t depth)
{
float expander_margin = tree_view->getSubtreeExpanderMargin();
for (TreeViewItemRenderingState* const item : item_to_render->d_renderedChildren)
{
Sizef size = item->d_size;
// center the expander compared to the item's height
float half_diff = (size.d_height - d_subtreeExpanderImagerySize.d_height) / 2.0f;
size.d_width = std::max(items_area.getWidth(), size.d_width);
float indent = d_subtreeExpanderImagerySize.d_width + expander_margin * 2;
if (item->d_totalChildCount > 0)
{
const ImagerySection* section = item->d_subtreeIsExpanded
? d_subtreeCollapserImagery : d_subtreeExpanderImagery;
Rectf button_rect;
button_rect.left(item_pos.x + expander_margin);
button_rect.top(item_pos.y +
(half_diff > 0 ? half_diff : 0));
button_rect.setSize(d_subtreeExpanderImagerySize);
Rectf button_clipper(button_rect.getIntersection(items_area));
section->render(*tree_view, button_rect, nullptr, &button_clipper);
indent = button_rect.getWidth() + expander_margin * 2;
}
Rectf item_rect;
item_rect.left(item_pos.x + indent);
item_rect.top(item_pos.y + (half_diff < 0 ? -half_diff : 0));
item_rect.setSize(size);
if (!item->d_icon.empty())
{
Image& img = ImageManager::getSingleton().get(item->d_icon);
Rectf icon_rect(item_rect);
icon_rect.setWidth(size.d_height);
icon_rect.setHeight(size.d_height);
Rectf icon_clipper(icon_rect.getIntersection(items_area));
ImageRenderSettings renderSettings(icon_rect, &icon_clipper, ICON_COLOUR_RECT, 1.0f);
img.createRenderGeometry(tree_view->getGeometryBuffers(), renderSettings);
item_rect.left(item_rect.left() + icon_rect.getWidth());
}
Rectf item_clipper(item_rect.getIntersection(items_area));
createRenderGeometryAndAddToItemView(tree_view, item->d_renderedText, item_rect,
tree_view->getEffectiveFont(), &tree_view->getTextColourRect(), &item_clipper, item->d_isSelected);
item_pos.y += std::max(size.d_height, d_subtreeExpanderImagerySize.d_height);
if (item->d_renderedChildren.empty())
continue;
item_pos.x += indent;
if (item->d_subtreeIsExpanded)
renderTreeItem(tree_view, items_area, item_pos, item, depth + 1);
item_pos.x -= indent;
}
}
//----------------------------------------------------------------------------//
static Sizef getImagerySize(const ImagerySection& section)
{
//!!!TODO: handle more than 1 imagerycomponent
return section.getImageryComponents().front().getImage()->getRenderedSize();
}
//----------------------------------------------------------------------------//
void FalagardTreeView::onLookNFeelAssigned()
{
const WidgetLookFeel& wlf = getLookNFeel();
d_subtreeExpanderImagery = &wlf.getImagerySection("SubtreeExpander");
d_subtreeCollapserImagery = &wlf.getImagerySection("SubtreeCollapser");
Sizef open_size = getImagerySize(*d_subtreeExpanderImagery);
Sizef close_size = getImagerySize(*d_subtreeCollapserImagery);
d_subtreeExpanderImagerySize = Sizef(
(open_size.d_width + close_size.d_width) / 2.0f + getView()->getSubtreeExpanderMargin(),
(open_size.d_height + close_size.d_height) / 2.0f + getView()->getSubtreeExpanderMargin());
}
//----------------------------------------------------------------------------//
Sizef FalagardTreeView::getSubtreeExpanderSize(void) const
{
return d_subtreeExpanderImagerySize;
}
//----------------------------------------------------------------------------//
Rectf FalagardTreeView::getViewRenderArea(void) const
{
return ItemViewRenderer::getViewRenderArea(getView());
}
//----------------------------------------------------------------------------//
float FalagardTreeView::getSubtreeExpanderXIndent(int depth) const
{
return depth * (
d_subtreeExpanderImagerySize.d_width +
getView()->getSubtreeExpanderMargin() * 2);
}
//----------------------------------------------------------------------------//
TreeView* FalagardTreeView::getView() const
{
return static_cast<TreeView*>(d_window);
}
//----------------------------------------------------------------------------//
void FalagardTreeView::resizeViewToContent(bool fit_width, bool fit_height) const
{
ItemViewRenderer::resizeViewToContent(getView(), fit_width, fit_height);
}
}
|
#ifndef MATRIXGRAPH_H
#define MATRIXGRAPH_H
#include "Graph.h"
#include "Exception.h"
#include "DynamicArray.h"
namespace DTLib
{
template <int N, typename V, typename E>
class MatrixGraph : public Graph<V, E>
{
protected:
V* m_vertexes[N];
E* m_edges[N][N];
int m_eCount;
public:
MatrixGraph()
{
for(int i = 0; i < vCount(); i++)
{
m_vertexes[i] = nullptr;
for(int j = 0; j < vCount(); j++)
{
m_edges[i][j] = nullptr;
}
}
m_eCount = 0;
}
V getVertex(int i) override // O(1)
{
V ret;
if(!getVertex(i, ret))
{
THROW_EXCEPTION(InvalidParameterException, "Index i is invalid ...");
}
return ret;
}
bool getVertex(int i, V& value) override // O(1)
{
bool ret = (0 <= i) && (i < vCount());
if(ret)
{
if(m_vertexes[i] != nullptr)
{
value = *(m_vertexes[i]);
}
else
{
THROW_EXCEPTION(InvalidOperationException, "No value asigned to this vertex ...");
}
}
return ret;
}
bool setVertex(int i, const V& value) override // O(1)
{
bool ret = (0 <= i) && (i < vCount());
if(ret)
{
V* data = m_vertexes[i];
if(data == nullptr)
{
data = new V();
}
if(data != nullptr)
{
*data = value;
m_vertexes[i] = data;
}
else
{
THROW_EXCEPTION(NoEnoughMemoryException, "No memory to create vertex ...");
}
}
return ret;
}
SharedPointer<Array<int>> getAdjacent(int i) override // O(n)
{
DynamicArray<int>* ret = nullptr;
if((0 <= i) && (i < vCount()))
{
int n = 0; // 记录与i相连的元素有几个
for(int j = 0; j < vCount(); j++)
{
if(m_edges[i][j] != nullptr)
{
n++;
}
ret = new DynamicArray<int>(n); // 根据记录的n创建对应大小的数组
if(ret != nullptr)
{
for(int j = 0, k = 0; j < vCount(); j++)
{
if(m_edges[i][j] != nullptr)
{
ret->set(k++, j); // 将与i相连的元素编号依次记录在数组中
}
}
}
else
{
THROW_EXCEPTION(NoEnoughMemoryException, "No memory to create ret object ...");
}
}
}
else
{
THROW_EXCEPTION(InvalidParameterException, "Index i is invalid ...");
}
return ret;
}
bool isAdjacent(int i, int j) override
{
return (0 <= i) && (i < vCount()) && (0 <= j) && (j < vCount()) && (m_edges[i][j] != nullptr);
}
E getEdge(int i, int j) override // O(1)
{
E ret;
if(!getEdge(i, j, ret))
{
THROW_EXCEPTION(InvalidOperationException, "Index <i, j> is invalid ...");
}
return ret;
}
bool getEdge(int i, int j, E& value) override // O(1)
{
bool ret = (0 <= i) && (i < vCount()) &&
(0 <= j) && (j < vCount());
if(ret)
{
if(m_edges[i][j] != nullptr)
{
value = *(m_edges[i][j]);
}
else
{
THROW_EXCEPTION(InvalidOperationException, "No value asigned to this edge ...");
}
}
return ret;
}
bool setEdge(int i, int j, const E& value) override // O(1)
{
bool ret = (0 <= i) && (i < vCount()) &&
(0 <= j) && (j < vCount());
if(ret)
{
E* ne = m_edges[i][j];
if(ne == nullptr)
{
ne = new E();
if(ne != nullptr)
{
*ne = value;
m_edges[i][j] = ne;
m_eCount++;
}
else
{
THROW_EXCEPTION(NoEnoughMemoryException, "No memory to create edge ...");
}
}
else
{
*ne = value;
}
}
return ret;
}
bool removeEdge(int i, int j) override // O(1)
{
bool ret = (0 <= i) && (i < vCount()) &&
(0 <= j) && (j < vCount());
if(ret)
{
E* toDel = m_edges[i][j];
m_edges[i][j] = nullptr;
if(toDel != nullptr)
{
m_eCount--;
delete toDel;
}
}
return ret;
}
int vCount() override // O(1)
{
return N;
}
int eCount() override // O(1)
{
return m_eCount;
}
int OD(int i) override // O(n)
{
int ret = 0;
if((0 <= i) && (i < vCount()))
{
for(int j = 0; j < vCount(); j++)
{
if(m_edges[i][j] != nullptr)
{
ret++;
}
}
}
else
{
THROW_EXCEPTION(InvalidParameterException, "Index i is invalid ...");
}
return ret;
}
int ID(int i) override // O(n)
{
int ret = 0;
if((0 <= i) && (i < vCount()))
{
for(int j = 0; j < vCount(); j++)
{
if(m_edges[j][i] != nullptr)
{
ret++;
}
}
}
else
{
THROW_EXCEPTION(InvalidParameterException, "Index i is invalid ...");
}
return ret;
}
~MatrixGraph()
{
for(int i = 0; i < this->vCount(); i++)
{
for(int j = 0; j < this->vCount(); j++)
{
delete m_edges[i][j];
}
delete m_vertexes[i];
}
}
};
}
#endif // MATRIXGRAPH_H
|
/* Copyright (C) 2014 Digipen Institute of Technology */
#include "HMC5883L.h"
#define X_SF 1.09195f
#define Y_SF 1
#define X_OFF -7.097f
#define Y_OFF -30.5f
void HMC5883L::SetupHMC5883LDevice()
{
I2CObject->frequency(Standard);
//setup continuous mode
int buffer[1];
buffer[0] = HMC5883_L_75HZ_NORMAL;
Write(ConfigA, buffer,1);
buffer[0] = HMC5883_L_E0GA;
Write(ConfigB, buffer,1);
buffer[0] = HMC5883_L_CONTINUOUS;
Write(ModeSelect ,buffer, 1);
timer.start();
tx.start();
ty.start();
tz.start();
m_x.SetCalibration(1, .0003, .1);
m_y.SetCalibration(1, .0003, .1);
m_z.SetCalibration(1, .3, .1);
}
void HMC5883L::Write(int dataOutputReg, int * buffer, int length)
{
int ack = 0;
char transmit[length+1];
transmit[0] = dataOutputReg;
for(int i = 1; i <= length; ++i)
{
transmit[i] = buffer[i-1];
}
I2CObject->write(writeAddress, transmit, length+1);
if(ack != 0)
{
return;
}
}
bool HMC5883L::FetchData()
{
int16_t xM,yM,zM;
int CompassReadings[3];
SampleCompass(CompassReadings);
xM = -(int16_t)CompassReadings[0];
yM = (int16_t)CompassReadings[2];
zM = (int16_t)CompassReadings[1];
xM = m_x.KalmanCalculate(xM, txM, tx.read());
yM = m_y.KalmanCalculate(yM, tyM, ty.read());
zM = m_z.KalmanCalculate(zM, tzM, tz.read());
txM = xM;
tyM = yM;
tzM = zM;
tx.reset();
ty.reset();
tz.reset();
XFilter = xM;
YFilter = yM;
ZFilter = zM;
return true;
/*
bool result1 = xAxis.ApplyFilter(xM,XFilter);
bool result2 = yAxis.ApplyFilter(yM,YFilter);
bool result3 = zAxis.ApplyFilter(zM,ZFilter);
if(result1 == false || result2 == false || result3 == false)
{
return false;
}
return true;
*/
}
float HMC5883L::MagneticNorthCalculations(float Pitch, float Roll)
{
int16_t temp = (X_SF*XFilter) + X_OFF;
int16_t temp2= (Y_SF*YFilter) + Y_OFF;
int16_t temp3= ZFilter;
int16_t newX = (temp*cos((Pitch*PI)/180)) + (temp2*sin((Roll*PI)/180)*sin(Pitch*PI/180)) - (temp3*cos((Roll*PI)/180)*sin((Pitch*PI)/180));
int16_t newY = (temp2*cos((Roll*PI)/180)) + (temp3*sin((Roll*PI)/180));
filter.SetCalibration(1.0f, .03f, .1f);
float north = Azimuth(newX, newY);
//return north;
// float newVal = filter.KalmanCalculate(north, MagneticNorthO, timer.read());
// MagneticNorthO = newVal;
// return newVal; // Angular Offset
return north;
}
void HMC5883L::FillAxis(float & x, float & y, float & z)
{
x = XFilter;
y = YFilter;
z = ZFilter;
}
float HMC5883L::Azimuth(int16_t & x, int16_t & y)
{
if(x==0 && y < 0)
return 90.0f;
if(x==0 && y > 0)
return 270.0f;
if(x < 0)
return (180.0f - ((atan((float)y/(float)x))*180.0f/PI));
if(x > 0 && y < 0)
return -((atan((float)y/(float)x))*180.0f/PI);
if(x > 0 && y > 0)
return (360.0f - (atan((float)y/(float)x)*180.0f/PI));
return 0.0f;
}
void HMC5883L::AssignI2CObject(I2C & Object)
{
I2CObject = &Object;
}
void HMC5883L::NewDataReady()
{
char tx[1];
char rx[1];
int ready = 0;
int count = 0;
while(ready == 0)
{
tx[0] = statusRegister;
I2CObject->write(readAddress, tx, 1);
I2CObject->read(readAddress, rx, 1);
ready = (int)rx[0];
if(ready != 1)
{
ready = 0;
}
++count;
}
count= 0;
}
void HMC5883L::SampleCompass(int * data )
{
char tx[1];
char rx[6];
tx[0]=HMC5883_L_X_MSB;
I2CObject->write(readAddress,tx,1);
I2CObject->read(readAddress,rx,6);
data[0]= (int)rx[0]<<8|(int)rx[1];
data[0] = ~data[0] + 1;
data[1]= (int)rx[2]<<8|(int)rx[3];
data[1] = ~data[1] + 1;
data[2]= (int)rx[4]<<8|(int)rx[5];
data[2] = ~data[2] + 1;
//Check Status Register before reading
//NewDataReady();
}
|
#ifndef QEMPLOYEELISTFORCALC_H
#define QEMPLOYEELISTFORCALC_H
#include <QWidget>
#include <QVBoxLayout>
#include <QPushButton>
#include <vector>
#include <utility>
#include "qemployeeforcalc.h"
#include "../../model/headers/worker.h"
#include "../../model/headers/container.h"
class QEmployeeListForCalc : public QWidget
{
Q_OBJECT
private:
std::vector<std::pair<int, int>> collection;
int size;
QVBoxLayout* list;
public:
explicit QEmployeeListForCalc(QWidget* parent = nullptr, Container<worker*> c = Container<worker*>());
void clearData();
bool isFilledOut();
signals:
void emitCalcFullSal(std::vector<std::pair<int, int>>);
void enableConfirm(const bool&);
public slots:
void collectData();
void checkFilled();
};
#endif // QEMPLOYEELISTFORCALC_H
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Devices.Perception.Provider.1.h"
#include "Windows.Foundation.1.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e
#define WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e
template <> struct __declspec(uuid("e2fcc7c1-3bfc-5a0b-b2b0-72e769d1cb7e")) __declspec(novtable) IIterable<hstring> : impl_IIterable<hstring> {};
#endif
#ifndef WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e
#define WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e
template <> struct __declspec(uuid("2f13c006-a03a-5f69-b090-75a43e33423e")) __declspec(novtable) IVectorView<hstring> : impl_IVectorView<hstring> {};
#endif
#ifndef WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90
#define WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90
template <> struct __declspec(uuid("98b9acc1-4b56-532e-ac73-03d5291cca90")) __declspec(novtable) IVector<hstring> : impl_IVector<hstring> {};
#endif
#ifndef WINRT_GENERIC_ca6bf87e_1745_5cd0_aee2_59736f5a206d
#define WINRT_GENERIC_ca6bf87e_1745_5cd0_aee2_59736f5a206d
template <> struct __declspec(uuid("ca6bf87e-1745-5cd0-aee2-59736f5a206d")) __declspec(novtable) IIterable<Windows::Devices::Perception::Provider::PerceptionCorrelation> : impl_IIterable<Windows::Devices::Perception::Provider::PerceptionCorrelation> {};
#endif
#ifndef WINRT_GENERIC_244cad66_afbe_5394_b7b7_43a61fcbfc6d
#define WINRT_GENERIC_244cad66_afbe_5394_b7b7_43a61fcbfc6d
template <> struct __declspec(uuid("244cad66-afbe-5394-b7b7-43a61fcbfc6d")) __declspec(novtable) IVectorView<Windows::Devices::Perception::Provider::PerceptionCorrelation> : impl_IVectorView<Windows::Devices::Perception::Provider::PerceptionCorrelation> {};
#endif
#ifndef WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236
#define WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236
template <> struct __declspec(uuid("8c304ebb-6615-50a4-8829-879ecd443236")) __declspec(novtable) IIterator<hstring> : impl_IIterator<hstring> {};
#endif
#ifndef WINRT_GENERIC_98fe92a5_2f0b_5a81_938f_b5173d2b1355
#define WINRT_GENERIC_98fe92a5_2f0b_5a81_938f_b5173d2b1355
template <> struct __declspec(uuid("98fe92a5-2f0b-5a81-938f-b5173d2b1355")) __declspec(novtable) IVector<Windows::Devices::Perception::Provider::PerceptionCorrelation> : impl_IVector<Windows::Devices::Perception::Provider::PerceptionCorrelation> {};
#endif
#ifndef WINRT_GENERIC_c4db1093_d705_5503_8bce_68535cd42ffa
#define WINRT_GENERIC_c4db1093_d705_5503_8bce_68535cd42ffa
template <> struct __declspec(uuid("c4db1093-d705-5503-8bce-68535cd42ffa")) __declspec(novtable) IIterator<Windows::Devices::Perception::Provider::PerceptionCorrelation> : impl_IIterator<Windows::Devices::Perception::Provider::PerceptionCorrelation> {};
#endif
}
namespace Windows::Devices::Perception::Provider {
struct [[deprecated("PerceptionStartFaceAuthenticationHandler may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] PerceptionStartFaceAuthenticationHandler : Windows::Foundation::IUnknown
{
PerceptionStartFaceAuthenticationHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> PerceptionStartFaceAuthenticationHandler(L lambda);
template <typename F> PerceptionStartFaceAuthenticationHandler (F * function);
template <typename O, typename M> PerceptionStartFaceAuthenticationHandler(O * object, M method);
bool operator()(const Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup & sender) const;
};
struct [[deprecated("PerceptionStopFaceAuthenticationHandler may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] PerceptionStopFaceAuthenticationHandler : Windows::Foundation::IUnknown
{
PerceptionStopFaceAuthenticationHandler(std::nullptr_t = nullptr) noexcept {}
template <typename L> PerceptionStopFaceAuthenticationHandler(L lambda);
template <typename F> PerceptionStopFaceAuthenticationHandler (F * function);
template <typename O, typename M> PerceptionStopFaceAuthenticationHandler(O * object, M method);
void operator()(const Windows::Devices::Perception::Provider::PerceptionFaceAuthenticationGroup & sender) const;
};
struct IKnownPerceptionFrameKindStatics :
Windows::Foundation::IInspectable,
impl::consume<IKnownPerceptionFrameKindStatics>
{
IKnownPerceptionFrameKindStatics(std::nullptr_t = nullptr) noexcept {}
};
struct [[deprecated("KnownPerceptionFrameKind may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] IKnownPerceptionFrameKindStatics;
struct IPerceptionControlGroup :
Windows::Foundation::IInspectable,
impl::consume<IPerceptionControlGroup>
{
IPerceptionControlGroup(std::nullptr_t = nullptr) noexcept {}
};
struct [[deprecated("PerceptionControlGroup may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] IPerceptionControlGroup;
struct IPerceptionControlGroupFactory :
Windows::Foundation::IInspectable,
impl::consume<IPerceptionControlGroupFactory>
{
IPerceptionControlGroupFactory(std::nullptr_t = nullptr) noexcept {}
};
struct [[deprecated("PerceptionControlGroup may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] IPerceptionControlGroupFactory;
struct IPerceptionCorrelation :
Windows::Foundation::IInspectable,
impl::consume<IPerceptionCorrelation>
{
IPerceptionCorrelation(std::nullptr_t = nullptr) noexcept {}
};
struct [[deprecated("PerceptionCorrelation may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] IPerceptionCorrelation;
struct IPerceptionCorrelationFactory :
Windows::Foundation::IInspectable,
impl::consume<IPerceptionCorrelationFactory>
{
IPerceptionCorrelationFactory(std::nullptr_t = nullptr) noexcept {}
};
struct [[deprecated("PerceptionCorrelation may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] IPerceptionCorrelationFactory;
struct IPerceptionCorrelationGroup :
Windows::Foundation::IInspectable,
impl::consume<IPerceptionCorrelationGroup>
{
IPerceptionCorrelationGroup(std::nullptr_t = nullptr) noexcept {}
};
struct [[deprecated("PerceptionCorrelationGroup may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] IPerceptionCorrelationGroup;
struct IPerceptionCorrelationGroupFactory :
Windows::Foundation::IInspectable,
impl::consume<IPerceptionCorrelationGroupFactory>
{
IPerceptionCorrelationGroupFactory(std::nullptr_t = nullptr) noexcept {}
};
struct [[deprecated("PerceptionCorrelationGroup may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] IPerceptionCorrelationGroupFactory;
struct IPerceptionFaceAuthenticationGroup :
Windows::Foundation::IInspectable,
impl::consume<IPerceptionFaceAuthenticationGroup>
{
IPerceptionFaceAuthenticationGroup(std::nullptr_t = nullptr) noexcept {}
};
struct [[deprecated("PerceptionFaceAuthenticationGroup may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] IPerceptionFaceAuthenticationGroup;
struct IPerceptionFaceAuthenticationGroupFactory :
Windows::Foundation::IInspectable,
impl::consume<IPerceptionFaceAuthenticationGroupFactory>
{
IPerceptionFaceAuthenticationGroupFactory(std::nullptr_t = nullptr) noexcept {}
};
struct [[deprecated("PerceptionFaceAuthenticationGroup may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] IPerceptionFaceAuthenticationGroupFactory;
struct IPerceptionFrame :
Windows::Foundation::IInspectable,
impl::consume<IPerceptionFrame>
{
IPerceptionFrame(std::nullptr_t = nullptr) noexcept {}
};
struct [[deprecated("PerceptionFrame may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] IPerceptionFrame;
struct IPerceptionFrameProvider :
Windows::Foundation::IInspectable,
impl::consume<IPerceptionFrameProvider>,
impl::require<IPerceptionFrameProvider, Windows::Foundation::IClosable>
{
IPerceptionFrameProvider(std::nullptr_t = nullptr) noexcept {}
};
struct [[deprecated("IPerceptionFrameProvider may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] IPerceptionFrameProvider;
struct IPerceptionFrameProviderInfo :
Windows::Foundation::IInspectable,
impl::consume<IPerceptionFrameProviderInfo>
{
IPerceptionFrameProviderInfo(std::nullptr_t = nullptr) noexcept {}
};
struct [[deprecated("PerceptionFrameProviderInfo may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] IPerceptionFrameProviderInfo;
struct IPerceptionFrameProviderManager :
Windows::Foundation::IInspectable,
impl::consume<IPerceptionFrameProviderManager>,
impl::require<IPerceptionFrameProviderManager, Windows::Foundation::IClosable>
{
IPerceptionFrameProviderManager(std::nullptr_t = nullptr) noexcept {}
};
struct [[deprecated("IPerceptionFrameProviderManager may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] IPerceptionFrameProviderManager;
struct IPerceptionFrameProviderManagerServiceStatics :
Windows::Foundation::IInspectable,
impl::consume<IPerceptionFrameProviderManagerServiceStatics>
{
IPerceptionFrameProviderManagerServiceStatics(std::nullptr_t = nullptr) noexcept {}
};
struct [[deprecated("PerceptionFrameProviderManagerService may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] IPerceptionFrameProviderManagerServiceStatics;
struct IPerceptionPropertyChangeRequest :
Windows::Foundation::IInspectable,
impl::consume<IPerceptionPropertyChangeRequest>
{
IPerceptionPropertyChangeRequest(std::nullptr_t = nullptr) noexcept {}
};
struct [[deprecated("PerceptionPropertyChangeRequest may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] IPerceptionPropertyChangeRequest;
struct IPerceptionVideoFrameAllocator :
Windows::Foundation::IInspectable,
impl::consume<IPerceptionVideoFrameAllocator>,
impl::require<IPerceptionVideoFrameAllocator, Windows::Foundation::IClosable>
{
IPerceptionVideoFrameAllocator(std::nullptr_t = nullptr) noexcept {}
};
struct [[deprecated("PerceptionVideoFrameAllocator may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] IPerceptionVideoFrameAllocator;
struct IPerceptionVideoFrameAllocatorFactory :
Windows::Foundation::IInspectable,
impl::consume<IPerceptionVideoFrameAllocatorFactory>
{
IPerceptionVideoFrameAllocatorFactory(std::nullptr_t = nullptr) noexcept {}
};
struct [[deprecated("PerceptionVideoFrameAllocator may be unavailable after Windows Creator Update. Please refer to AVStream on MSDN.")]] IPerceptionVideoFrameAllocatorFactory;
}
}
|
#ifndef __DISPLAY__AUTHOR__HPP
#define __DISPLAY__AUTHOR__HPP
#include "display.hpp"
#include <iostream>
#include <string>
using namespace std;
class Display_Author : public Display {
private:
string author;
public:
Display_Author(const string& author) : author(author) {}
void display(vector<Book*> books,ostream& out) {
vector<Book*>::iterator pos;
out << "Author: " << author << endl << endl;
for (pos = books.begin(); pos != books.end();pos++) {
Book* book = *pos;
string str1 = book->getauthor();
string str2 = author;
bool result = iequals(str1, str2);
if (result) {
book->display(out);
}
}
}
};
#endif // !__DISPLAY__SUBGENRE__HPP
|
#include<iostream>
using namespace std;
int main() {
double a, b;
a = 4.2;
b = 5.1;
a = a + b;
cout << fixed;
cout.precision(6);
cout << a;
//이러면 소수점 4번째 자리까지 나옴
//소수점 바꾸고 싶으면
/* cout << fixed
cout.precision(4) */
//이런식으로 써야함
}
|
//
// Copyright Jason Rice 2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef NBDL_WEB_NAV_ROUTE_HPP
#define NBDL_WEB_NAV_ROUTE_HPP
#include <nbdl/fwd/webui/nav_route.hpp>
#include <nbdl/message.hpp>
#include <nbdl/string.hpp>
#include <nbdl/webui/detail/event_receiver.hpp>
#include <nbdl/webui/route_map.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/functional/overload_linearly.hpp>
#include <boost/hana/tuple.hpp>
#include <boost/hana/type.hpp>
#include <emscripten.h>
#include <type_traits>
#include <utility>
namespace nbdl::webui
{
namespace hana = boost::hana;
namespace detail
{
template <typename Message>
constexpr bool is_nav_route_path = decltype(hana::equal(
message::get_path_type(std::declval<Message>())
, hana::typeid_(hana::make_tuple(nbdl::webui::nav_route_s))
))::value;
template <typename Message>
constexpr bool is_nav_route_string_path = decltype(hana::equal(
message::get_path_type(std::declval<Message>())
, hana::typeid_(hana::make_tuple(nbdl::webui::nav_route_s, hana::type_c<nbdl::string>))
))::value;
inline void web_route_update(nbdl::string const& route)
{
EM_ASM_(
{
var s = Module.NBDL_WEBUI_NAV_URI_PREFIX + UTF8ToString($0);
window.history.pushState(null, null, s);
}
, route.data()
);
}
template <typename Context>
struct popstate_event_receiver
{
Context context;
std::unique_ptr<event_receiver_vals> vals;
popstate_event_receiver(Context c)
: context(c)
, vals(new event_receiver_vals{})
{
EM_ASM_(
{
if (!Module.NBDL_WEBUI_NAV_URI_PREFIX) {
Module.NBDL_WEBUI_NAV_URI_PREFIX = "";
}
window.onpopstate = function()
{
// call the handler
Module.NBDL_DETAIL_JS_GET($0)();
};
}
, vals->handler.handle()
);
}
void receive_event()
{
std::size_t length = EM_ASM_INT({
return window.location.pathname.length
- Module.NBDL_WEBUI_NAV_URI_PREFIX.length;
}, 0);
nbdl::string route(length, '\0');
EM_ASM_(
{
var s = window.location.pathname.slice(
Module.NBDL_WEBUI_NAV_URI_PREFIX.length);
stringToAscii(s, $0);
}
, route.data()
);
nbdl::apply_message(
context
, message::make_downstream_update(
hana::make_tuple(nav_route_s, hana::type_c<nbdl::string>)
, message::no_uid
, route
, message::no_is_confirmed
)
);
}
};
}
template <typename Context, typename RouteMap>
struct nav_route_producer_impl
{
using hana_tag = nav_route_producer<RouteMap>;
using route_map = RouteMap;
Context context;
std::unique_ptr<detail::event_receiver> receiver;
nav_route_producer_impl(actor_initializer<Context, hana_tag> a)
: context(a.context)
, receiver(detail::make_event_receiver(detail::popstate_event_receiver<Context>{a.context}))
{ }
nav_route_producer_impl(actor_initializer<Context, hana::type<void>> a)
: context(a.context)
, receiver(detail::make_event_receiver(detail::popstate_event_receiver<Context>{a.context}))
{ }
};
template <typename RouteMap>
struct nav_route_store_impl
{
using hana_tag = nav_route_store<RouteMap>;
typename RouteMap::variant value{};
};
}
namespace nbdl
{
// nav_route_producer
template <typename RouteMap, typename Context>
struct actor_type<nbdl::webui::nav_route_producer<RouteMap>, Context>
{
using type = nbdl::webui::nav_route_producer_impl<Context, RouteMap>;
};
template <typename RouteMap>
struct producer_init_impl<nbdl::webui::nav_route_producer<RouteMap>>
{
template <typename Producer>
static void apply(Producer& p)
{
// load the store with the initial value
p.receiver->virtual_(webui::detail::receive_event_s)(*p.receiver);
}
};
template <typename RouteMap>
struct send_upstream_message_impl<nbdl::webui::nav_route_producer<RouteMap>>
{
template <typename Producer, typename Message>
static void apply(Producer& p, Message&& m)
{
static_assert(message::is_update<Message>);
if constexpr(nbdl::webui::detail::is_nav_route_string_path<Message>)
{
webui::detail::web_route_update(message::get_payload(m));
}
else if constexpr(nbdl::webui::detail::is_nav_route_path<Message>)
{
nbdl::match(
typename RouteMap::variant(message::get_payload(std::forward<Message>(m)))
, hana::overload_linearly(
[](webui::route_not_found) { }
, [](auto&& payload)
{
webui::detail::web_route_update(RouteMap{}.to_string(
std::forward<decltype(payload)>(payload)
));
}
)
);
p.receiver->virtual_(webui::detail::receive_event_s)(*p.receiver);
}
}
};
// nav_route_store
template <typename RouteMap>
struct apply_foreign_message_impl<nbdl::webui::nav_route_store<RouteMap>>
{
template <typename Message, typename Fn>
static void apply(nbdl::webui::nav_route_store_impl<RouteMap>& store, Message&& m, Fn&& f)
{
if constexpr(
message::is_update<Message>
and message::is_downstream<Message>
and webui::detail::is_nav_route_string_path<Message>
)
{
constexpr RouteMap map{};
store.value = map.from_string(message::get_payload(std::forward<Message>(m)));
std::forward<Fn>(f)(hana::make_tuple(webui::nav_route_s));
}
}
};
template <typename RouteMap>
struct make_store_impl<nbdl::webui::nav_route_store<RouteMap>>
{
static auto apply(...)
-> nbdl::webui::nav_route_store_impl<RouteMap>
{ return {}; }
};
template <typename RouteMap>
struct match_impl<nbdl::webui::nav_route_store<RouteMap>>
{
template <typename Store, typename Key, typename ...Args>
static void apply(Store&& s, Key&&, Args&& ...args)
{
nbdl::match(
std::forward<Store>(s).value
, std::forward<Args>(args)...
);
}
};
}
#endif
|
/*************************************************************
* > File Name : CF1247A.cpp
* > Author : Tony
* > Created Time : 2019/10/26 19:15:54
* > Algorithm : +
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
inline int read() {
int x = 0; int f = 1; char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();}
while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();}
return x * f;
}
int da, db;
int main() {
da = read(); db = read();
if (da == 9 && db == 1) {
printf("9 10\n");
} else if (da > db || db - da >= 2) {
printf("-1\n");
} else if (da == db) {
printf("%d %d\n", da * 10 + 2, db * 10 + 3);
} else if (db - da == 1) {
printf("%d %d\n", da * 10 + 9 , db * 10);
}
return 0;
}
|
#include "freeglut.h"
//#include "glut.h"
#include <stdio.h>
#include <math.h>
// Inicijalizacija funkcije
void drawRect(GLfloat, GLfloat, int, int, float, float, float);
void update();
// Dimenzije prozora
const int Width = 1000;
const int Height = 500;
// Dimenzije bloka
#define paddleHeight 10
#define paddleWidth 80
float p1 = 500; // Pocetna pozicija bloka po x-osi
const float pspeed = 10; // Brzina pomeranja bloka
int score[1];
#define bsize 10 // Velicina lopte
GLdouble bpos[2] = {235,235}; // Pocetna pozicija lopte
GLfloat bvx = 1; // Vektor kretanja lopte (levo-desno)
GLfloat bvy = 1; // Vektor kretanja lopte (gore-dole)
float bspeed = 0.5; // Brzina lopte
// Tekstualna promenljiva
static char str[100];
void * font = GLUT_BITMAP_9_BY_15;
void renderScene(void)
{
update();
glClear(GL_COLOR_BUFFER_BIT);
sprintf(str, "Broj poena: %d", score[0]);
glRasterPos2f(10, 10);
glutBitmapString(font,(unsigned char*)str);
// Crtanje bloka i lopte
drawRect(p1, 0.0, paddleHeight, paddleWidth, 0, 0, 1); // Plavi blok
drawRect(bpos[0], bpos[1], bsize, bsize, 1, 1, 0); // Zuta lopta
glutSwapBuffers(); // Crtanje novog frejma
}
void update()
{
// Ponasanje lopte kada je u interakciji sa prozorom
if(bpos[1] > 500-bsize)
bvy = -1;
else if (bpos[1] < 0)
{
bvy = -1;
score[0] = 0;
}
if(bpos[0] > 1000-bsize)
bvx = -1;
else if (bpos[0] < 0)
bvx = 1;
// Ponasanje lopte kada je u interakciji sa blokom
if(bpos[1] <= paddleHeight && bpos[0] >= p1 && bpos[0] + bsize <= p1 + paddleWidth)
{
bvy *= -1;
score[0]++;
bspeed *= 1.01;
}
// Nova pozicija lopte zavisno od brzine
bpos[0] += bspeed * bvx;
bpos[1] += bspeed * bvy;
}
// Crtanje novog bloka pri pomeranju
void drawRect(GLfloat x, GLfloat y, int height, int width, float R, float G, float B)
{
glColor3f(R,G,B);
glBegin(GL_QUADS);
glVertex2f( x, y); // Gore levo
glVertex2f( x, height + y); // Dole levo
glVertex2f( x + width, y + height); // Dole desno
glVertex2f( x + width, y); // Gore desno
glEnd();
}
// Tasteri za upravljanje blokom
void specialKeyPress(int key, int x, int y)
{
switch (key)
{
case GLUT_KEY_RIGHT:
if(920>=p1+pspeed)
{p1 += pspeed;}
break;
case GLUT_KEY_LEFT:
if(0<=p1-pspeed)
{p1 -= pspeed;}
break;
}
}
void EscPress(unsigned char key, int x, int y)
{
switch (key)
{
case '\033': // oktalni kod tastature za taster Esc
exit(0);
break;
}
}
void init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
gluOrtho2D(0,1000,0,500);
// Pocetno stanje poena
score[0] = 0;
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(Width, Height);
glutInitWindowPosition(150,50);
glutCreateWindow("Ping Pong");
glutDisplayFunc(renderScene);
glutSpecialFunc(specialKeyPress);
glutKeyboardFunc(EscPress);
glutIdleFunc(renderScene);
init();
glutMainLoop();
return 0;
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::UI {
struct Color;
}
namespace Windows::UI {
using Color = ABI::Windows::UI::Color;
}
namespace ABI::Windows::UI {
struct IColorHelper;
struct IColorHelperStatics;
struct IColorHelperStatics2;
struct IColors;
struct IColorsStatics;
struct ColorHelper;
struct Colors;
}
namespace Windows::UI {
struct IColorHelper;
struct IColorHelperStatics;
struct IColorHelperStatics2;
struct IColors;
struct IColorsStatics;
struct ColorHelper;
struct Colors;
}
namespace Windows::UI {
template <typename T> struct impl_IColorHelper;
template <typename T> struct impl_IColorHelperStatics;
template <typename T> struct impl_IColorHelperStatics2;
template <typename T> struct impl_IColors;
template <typename T> struct impl_IColorsStatics;
}
}
|
/*
Copyright (c) 2013-2014 Sam Hardeman
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#pragma once
#ifdef _WIN32
#include <Windows.h>
#endif
#ifdef __linux__
#include <pthread.h>
#endif
/*
EXTEXE Support Code
class Mutex:
A very basic mutex class that has support for Linux and Win32.
Implemented as a CRITICAL_SECTION on Win32.
Uses pthreads on Linux;
*/
namespace ExtExe
{
#ifdef _WIN32
typedef CRITICAL_SECTION InternalMutexObject;
#endif
#ifdef __linux__
typedef pthread_mutex_t InternalMutexObject;
#endif
class Mutex
{
public:
Mutex( void );
~Mutex( void );
public:
void Lock( void );
void Unlock( void );
public:
InternalMutexObject& GetMutexObject( void );
private:
InternalMutexObject m_MutexObject;
};
};
|
#pragma once
#include <algorithm>
#include <map>
#include <memory>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include "drake/common/drake_assert.h"
#include "drake/common/drake_copyable.h"
#include "drake/common/drake_throw.h"
#include "drake/systems/framework/diagram.h"
#include "drake/systems/framework/system.h"
namespace drake {
namespace systems {
/// DiagramBuilder is a factory class for Diagram. It is single
/// use: after calling Build or BuildInto, DiagramBuilder gives up ownership
/// of the constituent systems, and should therefore be discarded.
///
/// A system must be added to the DiagramBuilder with AddSystem before it can
/// be wired up in any way. Every system must have a unique, non-empty name.
template <typename T>
class DiagramBuilder {
public:
// DiagramBuilder objects are neither copyable nor moveable.
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(DiagramBuilder)
DiagramBuilder() {}
virtual ~DiagramBuilder() {}
// TODO(sherm1) The AddSystem methods (or some variant) should take the system
// name as their first parameter. See discussion in issue #5895.
/// Takes ownership of @p system and adds it to the builder. Returns a bare
/// pointer to the System, which will remain valid for the lifetime of the
/// Diagram built by this builder.
///
/// If the system's name is unset, sets it to System::GetMemoryObjectName()
/// as a default in order to have unique names within the diagram.
///
/// @code
/// DiagramBuilder<T> builder;
/// auto foo = builder.AddSystem(std::make_unique<Foo<T>>());
/// @endcode
///
/// @tparam S The type of system to add.
template<class S>
S* AddSystem(std::unique_ptr<S> system) {
if (system->get_name().empty()) {
system->set_name(system->GetMemoryObjectName());
}
S* raw_sys_ptr = system.get();
systems_.insert(raw_sys_ptr);
registered_systems_.push_back(std::move(system));
return raw_sys_ptr;
}
/// Constructs a new system with the given @p args, and adds it to the
/// builder, which retains ownership. Returns a bare pointer to the System,
/// which will remain valid for the lifetime of the Diagram built by this
/// builder.
///
/// @code
/// DiagramBuilder<double> builder;
/// auto foo = builder.AddSystem<Foo<double>>("name", 3.14);
/// @endcode
///
/// Note that for dependent names you must use the template keyword:
///
/// @code
/// DiagramBuilder<T> builder;
/// auto foo = builder.template AddSystem<Foo<T>>("name", 3.14);
/// @endcode
///
/// You may prefer the `unique_ptr` variant instead.
///
///
/// @tparam S The type of System to construct. Must subclass System<T>.
template<class S, typename... Args>
S* AddSystem(Args&&... args) {
return AddSystem(std::make_unique<S>(std::forward<Args>(args)...));
}
/// Constructs a new system with the given @p args, and adds it to the
/// builder, which retains ownership. Returns a bare pointer to the System,
/// which will remain valid for the lifetime of the Diagram built by this
/// builder.
///
/// @code
/// DiagramBuilder<double> builder;
/// // Foo must be a template.
/// auto foo = builder.AddSystem<Foo>("name", 3.14);
/// @endcode
///
/// Note that for dependent names you must use the template keyword:
///
/// @code
/// DiagramBuilder<T> builder;
/// auto foo = builder.template AddSystem<Foo>("name", 3.14);
/// @endcode
///
/// You may prefer the `unique_ptr` variant instead.
///
/// @tparam S A template for the type of System to construct. The template
/// will be specialized on the scalar type T of this builder.
template<template<typename Scalar> class S, typename... Args>
S<T>* AddSystem(Args&&... args) {
return AddSystem(std::make_unique<S<T>>(std::forward<Args>(args)...));
}
/// Returns whether any Systems have been added yet.
bool empty() const { return registered_systems_.empty(); }
/// Returns the list of contained Systems.
std::vector<systems::System<T>*> GetMutableSystems() {
std::vector<systems::System<T>*> result;
result.reserve(registered_systems_.size());
for (const auto& system : registered_systems_) {
result.push_back(system.get());
}
return result;
}
/// Declares that input port @p dest is connected to output port @p src.
void Connect(const OutputPort<T>& src,
const InputPort<T>& dest) {
DRAKE_DEMAND(src.size() == dest.size());
InputPortLocator dest_id{dest.get_system(), dest.get_index()};
OutputPortLocator src_id{&src.get_system(), src.get_index()};
ThrowIfInputAlreadyWired(dest_id);
ThrowIfSystemNotRegistered(&src.get_system());
ThrowIfSystemNotRegistered(dest.get_system());
connection_map_[dest_id] = src_id;
}
/// Declares that sole input port on the @p dest system is connected to sole
/// output port on the @p src system. Throws an exception if the sole-port
/// precondition is not met (i.e., if @p dest has no input ports, or @p dest
/// has more than one input port, or @p src has no output ports, or @p src
/// has more than one output port).
void Connect(const System<T>& src, const System<T>& dest) {
DRAKE_THROW_UNLESS(src.get_num_output_ports() == 1);
DRAKE_THROW_UNLESS(dest.get_num_input_ports() == 1);
Connect(src.get_output_port(0), dest.get_input_port(0));
}
/// Cascades @p src and @p dest. The sole input port on the @p dest system
/// is connected to sole output port on the @p src system. Throws an
/// exception if the sole-port precondition is not met (i.e., if @p dest has
/// no input ports, or @p dest has more than one input port, or @p src has no
/// output ports, or @p src has more than one output port).
void Cascade(const System<T>& src, const System<T>& dest) {
Connect(src, dest);
}
/// Declares that the given @p input port of a constituent system is an input
/// to the entire Diagram. @p name is an optional name for the input port;
/// if it is unspecified, then a default name will be provided.
/// @pre If supplied at all, @p name must not be empty.
/// @return The index of the exported input port of the entire diagram.
InputPortIndex ExportInput(const InputPort<T>& input,
std::string name = kUseDefaultName) {
DRAKE_DEMAND(!name.empty());
InputPortLocator id{input.get_system(), input.get_index()};
ThrowIfInputAlreadyWired(id);
ThrowIfSystemNotRegistered(input.get_system());
InputPortIndex return_id(input_port_ids_.size());
input_port_ids_.push_back(id);
// The requirement that subsystem names are unique guarantees uniqueness
// of the port names.
std::string port_name =
name == kUseDefaultName
? input.get_system()->get_name() + "_" + input.get_name()
: std::move(name);
input_port_names_.emplace_back(std::move(port_name));
diagram_input_set_.insert(id);
return return_id;
}
/// Declares that the given @p output port of a constituent system is an
/// output of the entire diagram. @p name is an optional name for the output
/// port; if it is unspecified, then a default name will be provided.
/// @pre If supplied at all, @p name must not be empty.
/// @return The index of the exported output port of the entire diagram.
OutputPortIndex ExportOutput(const OutputPort<T>& output,
std::string name = kUseDefaultName) {
ThrowIfSystemNotRegistered(&output.get_system());
OutputPortIndex return_id(output_port_ids_.size());
output_port_ids_.push_back(
OutputPortLocator{&output.get_system(), output.get_index()});
// The requirement that subsystem names are unique guarantees uniqueness
// of the port names.
std::string port_name =
name == kUseDefaultName
? output.get_system().get_name() + "_" + output.get_name()
: std::move(name);
output_port_names_.emplace_back(std::move(port_name));
return return_id;
}
/// Builds the Diagram that has been described by the calls to Connect,
/// ExportInput, and ExportOutput. Throws std::logic_error if the graph is
/// not buildable.
std::unique_ptr<Diagram<T>> Build() {
std::unique_ptr<Diagram<T>> diagram(new Diagram<T>(Compile()));
return diagram;
}
/// Configures @p target to have the topology that has been described by
/// the calls to Connect, ExportInput, and ExportOutput. Throws
/// std::logic_error if the graph is not buildable.
///
/// Only Diagram subclasses should call this method. The target must not
/// already be initialized.
void BuildInto(Diagram<T>* target) {
target->Initialize(Compile());
}
private:
using InputPortLocator = typename Diagram<T>::InputPortLocator;
using OutputPortLocator = typename Diagram<T>::OutputPortLocator;
// This generic port identifier is used only for cycle detection below
// because the algorithm treats both input & output ports as nodes.
using PortIdentifier = std::pair<const System<T>*, int>;
// Throws if the given input port (belonging to a child subsystem) has
// already been connected to an output port, or exported to be an input
// port of the whole diagram.
void ThrowIfInputAlreadyWired(const InputPortLocator& id) const {
if (connection_map_.find(id) != connection_map_.end() ||
diagram_input_set_.find(id) != diagram_input_set_.end()) {
throw std::logic_error("Input port is already wired.");
}
}
void ThrowIfSystemNotRegistered(const System<T>* system) const {
DRAKE_THROW_UNLESS(systems_.find(system) != systems_.end());
}
// Helper method to do the algebraic loop test. It recursively performs the
// depth-first search on the graph to find cycles.
static bool HasCycleRecurse(
const PortIdentifier& n,
const std::map<PortIdentifier, std::set<PortIdentifier>>& edges,
std::set<PortIdentifier>* visited,
std::vector<PortIdentifier>* stack) {
DRAKE_ASSERT(visited->count(n) == 0);
visited->insert(n);
auto edge_iter = edges.find(n);
if (edge_iter != edges.end()) {
DRAKE_ASSERT(std::find(stack->begin(), stack->end(), n) == stack->end());
stack->push_back(n);
for (const auto& target : edge_iter->second) {
if (visited->count(target) == 0 &&
HasCycleRecurse(target, edges, visited, stack)) {
return true;
} else if (std::find(stack->begin(), stack->end(), target) !=
stack->end()) {
return true;
}
}
stack->pop_back();
}
return false;
}
// Evaluates the graph of port dependencies -- including *connections* between
// output ports and input ports and direct feedthrough connections between
// input ports and output ports. If an algebraic loop is detected, throws
// a std::logic_error.
void ThrowIfAlgebraicLoopsExist() const {
// Each port in the diagram is a node in a graph.
// An edge exists from node u to node v if:
// 1. output u is connected to input v (via Connect(u, v) method), or
// 2. a direct feedthrough from input u to output v is reported.
// A depth-first search of the graph should produce a forest of valid trees
// if there are no algebraic loops. Otherwise, at least one link moving
// *up* the tree will exist.
// Build the graph.
// Generally, the nodes of the graph would be the set of all defined ports
// (input and output) of each subsystem. However, we only need to
// consider the input/output ports that have a diagram level output-to-input
// connection (ports that are not connected in this manner cannot contribute
// to an algebraic loop).
// Track *all* of the nodes involved in a diagram-level connection as
// described above.
std::set<PortIdentifier> nodes;
// A map from node u, to the set of edges { (u, v_i) }. In normal cases,
// not every node in `nodes` will serve as a key in `edges` (as that is a
// necessary condition for there to be no algebraic loop).
std::map<PortIdentifier, std::set<PortIdentifier>> edges;
// In order to store PortIdentifiers for both input and output ports in the
// same set, I need to encode the ports. The identifier for the first input
// port and output port look identical (same system pointer, same port
// id 0). So, to distinguish them, I'll modify the output ports to use the
// negative half of the int space. The function below provides a utility for
// encoding an output port id.
auto output_to_key = [](int port_id) { return -(port_id + 1); };
// Populate the node set from the connections (and define the edges implied
// by those connections).
for (const auto& connection : connection_map_) {
// Dependency graph is a mapping from the destination of the connection
// to what it *depends on* (the source).
const PortIdentifier& src = connection.second;
const PortIdentifier& dest = connection.first;
PortIdentifier encoded_src{src.first, output_to_key(src.second)};
nodes.insert(encoded_src);
nodes.insert(dest);
edges[encoded_src].insert(dest);
}
// Populate more edges based on direct feedthrough.
for (const auto& system : registered_systems_) {
for (const auto& pair : system->GetDirectFeedthroughs()) {
PortIdentifier src_port{system.get(), pair.first};
PortIdentifier dest_port{system.get(), output_to_key(pair.second)};
if (nodes.count(src_port) > 0 && nodes.count(dest_port) > 0) {
// Track direct feedthrough only on port pairs where *both* ports are
// connected to other ports at the diagram level.
edges[src_port].insert(dest_port);
}
}
}
// Evaluate the graph for cycles.
std::set<PortIdentifier> visited;
std::vector<PortIdentifier> stack;
for (const auto& node : nodes) {
if (visited.count(node) == 0) {
if (HasCycleRecurse(node, edges, &visited, &stack)) {
std::stringstream ss;
auto port_to_stream = [&ss](const auto& id) {
ss << " " << id.first->get_name() << ":";
if (id.second < 0)
ss << "Out(";
else
ss << "In(";
ss << (id.second >= 0 ? id.second : -id.second - 1) << ")";
};
ss << "Algebraic loop detected in DiagramBuilder:\n";
for (size_t i = 0; i < stack.size() - 1; ++i) {
port_to_stream(stack[i]);
ss << " depends on\n";
}
port_to_stream(stack.back());
throw std::runtime_error(ss.str());
}
}
}
}
// TODO(russt): Implement AddRandomSources method to wire up all dangling
// random input ports with a compatible RandomSource system.
// Produces the Blueprint that has been described by the calls to
// Connect, ExportInput, and ExportOutput. Throws std::logic_error if the
// graph is empty or contains algebraic loops.
// The DiagramBuilder passes ownership of the registered systems to the
// blueprint.
std::unique_ptr<typename Diagram<T>::Blueprint> Compile() {
if (registered_systems_.size() == 0) {
throw std::logic_error("Cannot Compile an empty DiagramBuilder.");
}
ThrowIfAlgebraicLoopsExist();
auto blueprint = std::make_unique<typename Diagram<T>::Blueprint>();
blueprint->input_port_ids = input_port_ids_;
blueprint->input_port_names = input_port_names_;
blueprint->output_port_ids = output_port_ids_;
blueprint->output_port_names = output_port_names_;
blueprint->connection_map = connection_map_;
blueprint->systems = std::move(registered_systems_);
return blueprint;
}
// The ordered inputs and outputs of the Diagram to be built.
std::vector<InputPortLocator> input_port_ids_;
std::vector<std::string> input_port_names_;
std::vector<OutputPortLocator> output_port_ids_;
std::vector<std::string> output_port_names_;
// For fast membership queries: has this input port already been declared?
std::set<InputPortLocator> diagram_input_set_;
// A map from the input ports of constituent systems, to the output ports of
// the systems from which they get their values.
std::map<InputPortLocator, OutputPortLocator> connection_map_;
// A mirror on the systems in the diagram. Should have the same values as
// registered_systems_. Used for fast membership queries.
std::unordered_set<const System<T>*> systems_;
// The Systems in this DiagramBuilder, in the order they were registered.
std::vector<std::unique_ptr<System<T>>> registered_systems_;
friend int AddRandomInputs(double, systems::DiagramBuilder<double>*);
};
} // namespace systems
} // namespace drake
|
#pragma once
#include <cmath>
namespace FastBVH {
//! \brief A type-generic 3 dimensional vector.
//! Used for the representation of bounding volumes
//! as well as the representation of rays and intersections.
//! \tparam Float The type used for the vector components.
template <typename Float>
struct alignas(sizeof(float) * 4) Vector3 final {
//! The X component of the vector.
Float x;
//! The Y component of the vector.
Float y;
//! The Z component of the vector.
Float z;
//! Adds two vectors.
Vector3 operator+(const Vector3& b) const noexcept { return Vector3{x + b.x, y + b.y, z + b.z}; }
//! Subtracts two vectors.
Vector3 operator-(const Vector3& b) const noexcept { return Vector3{x - b.x, y - b.y, z - b.z}; }
//! Multiplies the vector by a scalar value.
Vector3 operator*(Float b) const noexcept { return Vector3{x * b, y * b, z * b}; }
//! Divides the vector by a scalar value.
Vector3 operator/(Float b) const noexcept { return Vector3{x / b, y / b, z / b}; }
//! Component-wise vector multiplication.
//! This is also called the hadamard product.
Vector3 cmul(const Vector3& b) const noexcept { return Vector3{x * b.x, y * b.y, z * b.z}; }
//! Component-wise vector division.
Vector3 cdiv(const Vector3& b) const noexcept { return Vector3{x / b.x, y / b.y, z / b.z}; }
/// Component-wise vector division.
Vector3 operator/(const Vector3& b) const noexcept { return Vector3{x / b.x, y / b.y, z / b.z}; }
//! Accesses a vector component by its index.
inline Float& operator[](const unsigned int i) { return (&x)[i]; }
//! Accesses a vector component by its index.
inline const Float& operator[](const unsigned int i) const noexcept { return (&x)[i]; }
};
//! Computes the cross product of two vectors.
template <typename Float>
Vector3<Float> cross(const Vector3<Float>& a, const Vector3<Float>& b) noexcept {
return Vector3<Float>{
(a.y * b.z) - (a.z * b.y),
(a.z * b.x) - (a.x * b.z),
(a.x * b.y) - (a.y * b.x),
};
}
//! Computes the dot product between two vectors.
template <typename Float>
Float dot(const Vector3<Float>& a, const Vector3<Float>& b) noexcept {
return (a.x * b.x) + (a.y * b.y) + (a.z * b.z);
}
//! Calculates all minimum values between two vectors.
//! \tparam Float The floating point type of the vector.
template <typename Float>
inline Vector3<Float> min(const Vector3<Float>& a, const Vector3<Float>& b) noexcept {
return Vector3<Float>{std::fmin(a.x, b.x), std::fmin(a.y, b.y), std::fmin(a.z, b.z)};
}
//! Calculates all maximum values between two vectors.
//! \tparam Float The floating point type of the vector.
template <typename Float>
inline Vector3<Float> max(const Vector3<Float>& a, const Vector3<Float>& b) noexcept {
return Vector3<Float>{std::fmax(a.x, b.x), std::fmax(a.y, b.y), std::fmax(a.z, b.z)};
}
//! Computes the length of a vector.
//! \tparam Float The floating point type of the vector.
//! \param a The vector to compute the length of.
//! \return The length of @p a.
template <typename Float>
inline Float length(const Vector3<Float>& a) noexcept {
return std::sqrt(dot(a, a));
}
//! Divides a vector by it's length, making its magnitude equal to one.
//! \tparam Float The floating point type of the vector.
//! \param in The vector to normalize.
//! \return The normalized copy of @p in.
template <typename Float>
inline Vector3<Float> normalize(const Vector3<Float>& in) noexcept {
return in * (1.0f / length(in));
}
} // namespace FastBVH
|
#pragma once
#ifndef WOTPP_INTRINSICS
#define WOTPP_INTRINSICS
#include <string>
#include <vector>
#include <structures/environment.hpp>
namespace wpp {
std::string intrinsic_log (wpp::node_t, wpp::node_t, wpp::Env&, wpp::FnEnv* = nullptr);
std::string intrinsic_error (wpp::node_t, wpp::node_t, wpp::Env&, wpp::FnEnv* = nullptr);
std::string intrinsic_assert (wpp::node_t, wpp::node_t, wpp::node_t, wpp::Env&, wpp::FnEnv* = nullptr);
std::string intrinsic_file (wpp::node_t, wpp::node_t, wpp::Env&, wpp::FnEnv* = nullptr);
std::string intrinsic_use (wpp::node_t, wpp::node_t, wpp::Env&, wpp::FnEnv* = nullptr);
std::string intrinsic_eval (wpp::node_t, wpp::node_t, wpp::Env&, wpp::FnEnv* = nullptr);
std::string intrinsic_run (wpp::node_t, wpp::node_t, wpp::Env&, wpp::FnEnv* = nullptr);
std::string intrinsic_pipe (wpp::node_t, wpp::node_t, wpp::node_t, wpp::Env&, wpp::FnEnv* = nullptr);
}
#endif
|
#include<iostream>
#include<string>
using namespace std;
template <class T>
class AutoPtr
{
public:
//构造函数
AutoPtr(T* ptr = NULL)
:_ptr(ptr)
{}
//拷贝构造
AutoPtr(AutoPtr<T>& ap)
{
//管理权转移
_ptr = ap._ptr;
ap._ptr = NULL;
}
//赋值运算符重载
AutoPtr<T>& operator = (AutoPtr<T>& ap)
{
if(_ptr != ap._ptr)
{
if(_ptr)
{
delete _ptr;
}
//管理权转移
_ptr = ap._ptr;
ap._ptr = NULL;
}
return *this;
}
T* operator ->()
{
return _ptr;
}
T& operator *()
{
return *_ptr;
}
//析构函数
~AutoPtr()
{
cout<<"~AutoPtr()"<<endl;
if(_ptr)
{
delete _ptr;
}
}
private:
T* _ptr;
};
void TestAutoPtr()
{
AutoPtr<int> ptr1(new int(10));
AutoPtr<int> ptr2(ptr1);
AutoPtr<int> ptr3(ptr2);
cout<<*ptr3<<endl;
}
int main()
{
TestAutoPtr();
return 0;
}
|
/*-----------------------------------------------------------------------
Matt Marchant 2015 - 2016
http://trederia.blogspot.com
Robomower - Zlib license.
This software is provided 'as-is', without any express or
implied warranty.In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions :
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
-----------------------------------------------------------------------*/
#include <components/Tilemap.hpp>
#include <xygine/util/Json.hpp>
#include <xygine/util/Random.hpp>
#include <xygine/parsers/picojson.h>
#include <SFML/Graphics/RenderStates.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <fstream>
#include <bitset>
#include <functional>
namespace
{
const sf::Vector2f tileSize(16.f, 16.f);
//tiles are drawn 4x larger than the tile set size
const float tileWidth = 64.f;
const float tileHeight = 64.f;
const sf::Uint8 tileCountX = 20u;
const sf::Uint8 tileCountY = 14u;
const sf::Uint8 borderTop = 2u;
const sf::Uint8 borderLeft = 3u;
}
//actually we probably only need to store positions
std::vector<sf::Vector2f> Tilemap::tilePositions(Tilemap::Count);
Tilemap::Tilemap(xy::MessageBus& mb, sf::Texture& texture)
: xy::Component (mb, this),
m_texture (texture)
{
//shouldn't really be loading stuff in a ctor
//but buns to it. We'll just fail gracefully.
loadJson();
buildMap();
}
//public
void Tilemap::entityUpdate(xy::Entity&, float) {}
//private
void Tilemap::loadJson()
{
std::ifstream file("assets/images/tileset.tst");
if (file.good() && xy::Util::File::validLength(file))
{
std::string jsonString;
std::string temp;
while (!file.eof())
{
file >> temp;
jsonString += temp;
}
if (!jsonString.empty())
{
picojson::value rootValue;
auto err = picojson::parse(rootValue, jsonString);
if (err.empty())
{
getValue("short1", rootValue, Tile::ShortGrassLight);
getValue("short2", rootValue, Tile::ShortGrassDark);
getValue("fence_tl", rootValue, Tile::FenceTopLeft);
getValue("fence_top", rootValue, Tile::FenceTop);
getValue("fence_tr", rootValue, Tile::FenceTopRight);
getValue("long", rootValue, Tile::LongGrass);
getValue("dirt", rootValue, Tile::Dirt);
getValue("fence_bl", rootValue, Tile::FenceBottomLeft);
getValue("fence_bottom", rootValue, Tile::FenceBottom);
getValue("fence_br", rootValue, Tile::FenceBottomRight);
getValue("fence_left", rootValue, Tile::FenceLeft);
getValue("fence_right", rootValue, Tile::FenceRight);
getValue("edge_n", rootValue, Tile::EdgeNorth);
getValue("edge_e", rootValue, Tile::EdgeEast);
getValue("edge_s", rootValue, Tile::EdgeSouth);
getValue("edge_w", rootValue, Tile::EdgeWest);
getValue("edge_ne", rootValue, Tile::EdgeNorthEast);
getValue("edge_se", rootValue, Tile::EdgeSouthEast);
getValue("edge_sw", rootValue, Tile::EdgeSouthWest);
getValue("edge_nw", rootValue, Tile::EdgeNorthWest);
getValue("flower1", rootValue, Tile::FlowersOne);
getValue("flower2", rootValue, Tile::FlowersTwo);
getValue("flower3", rootValue, Tile::FlowersThree);
getValue("flower4", rootValue, Tile::FlowersFour);
getValue("rock1", rootValue, Tile::RockOne);
getValue("rock2", rootValue, Tile::RockTwo);
getValue("rock3", rootValue, Tile::RockThree);
}
else
{
xy::Logger::log("tileset data: " + err, xy::Logger::Type::Error, xy::Logger::Output::All);
}
}
else
{
xy::Logger::log("tileset data file is empty", xy::Logger::Type::Error, xy::Logger::Output::All);
}
}
else
{
//always write this, and write to log file so we can see this in release builds
xy::Logger::log("failed to open tileset data file.", xy::Logger::Type::Error, xy::Logger::Output::All);
}
file.close();
}
void Tilemap::getValue(const std::string& name, const picojson::value& source, Tilemap::Tile tile)
{
if (source.get(name).is<picojson::array>())
{
auto arr = source.get(name).get<picojson::array>();
sf::Vector2f pos
(
arr[0].is<double>() ? static_cast<float>(arr[0].get<double>()) : 0.f,
arr[1].is<double>() ? static_cast<float>(arr[1].get<double>()) : 0.f
);
tilePositions[tile] = pos;
}
}
void Tilemap::buildMap()
{
//used to create details
std::bitset<tileCountX*tileCountY> bs(0);
//create border
for (auto y = 0u; y < tileCountY; ++y)
{
for (auto x = 0u; x < tileCountX; ++x)
{
//we need to place tiles from top layer down
//top fence
if ((y == borderTop - 1) && (x >= borderLeft && x < tileCountX - borderLeft))
{
addTile(x * tileWidth, y * tileHeight, Tile::EdgeNorth, m_borderArray);
addTile(x * tileWidth, y * tileHeight, Tile::FenceTop, m_borderArray);
continue;
}
//bottom fence
else if ((y == tileCountY - borderTop) && (x >= borderLeft && x < tileCountX - borderLeft))
{
addTile(x * tileWidth, y * tileHeight, Tile::EdgeSouth, m_borderArray);
addTile(x * tileWidth, y * tileHeight, Tile::FenceBottom, m_borderArray);
continue;
}
//left fence
else if ((x == borderLeft - 1) && (y >= borderTop && y < tileCountY - borderTop))
{
addTile(x * tileWidth, y * tileHeight, Tile::EdgeWest, m_borderArray);
addTile(x * tileWidth, y * tileHeight, Tile::FenceLeft, m_borderArray);
continue;
}
//right fence
else if ((x == tileCountX - borderLeft) && (y >= borderTop && y < tileCountY - borderTop))
{
addTile(x * tileWidth, y * tileHeight, Tile::EdgeEast, m_borderArray);
addTile(x * tileWidth, y * tileHeight, Tile::FenceRight, m_borderArray);
continue;
}
//tl
else if (x == borderLeft - 1 && y == borderTop - 1)
{
addTile(x * tileWidth, y * tileHeight, Tile::EdgeNorthWest, m_borderArray);
addTile(x * tileWidth, y * tileHeight, Tile::FenceTopLeft, m_borderArray);
continue;
}
//tr
else if (x == tileCountX - borderLeft && y == borderTop - 1)
{
addTile(x * tileWidth, y * tileHeight, Tile::EdgeNorthEast, m_borderArray);
addTile(x * tileWidth, y * tileHeight, Tile::FenceTopRight, m_borderArray);
continue;
}
//br
else if (x == tileCountX - borderLeft && y == tileCountY - borderTop)
{
addTile(x * tileWidth, y * tileHeight, Tile::EdgeSouthEast, m_borderArray);
addTile(x * tileWidth, y * tileHeight, Tile::FenceBottomRight, m_borderArray);
continue;
}
//bl
else if (x == borderLeft - 1 && y == tileCountY - borderTop)
{
addTile(x * tileWidth, y * tileHeight, Tile::EdgeSouthWest, m_borderArray);
addTile(x * tileWidth, y * tileHeight, Tile::FenceBottomLeft, m_borderArray);
continue;
}
//dirt border
else if ((y < borderTop - 1 || y > tileCountY - borderTop)
|| (x < borderLeft - 1 || x > tileCountX - borderLeft))
{
addTile(x * tileWidth, y * tileHeight, Tile::Dirt, m_borderArray);
//decide if this tile should have detail on it
static const int proabability = 85;
if (xy::Util::Random::value(0, 100) > proabability)
{
bs[(y * tileCountX) + x] = 1;
}
}
}
}
//smooth the bitset by essentially using a convolution blur
std::function<int(std::size_t)> getNeighbours = [&bs](std::size_t idx)
{
std::size_t retVal = 0;
sf::Vector2u coord(idx % tileCountX, idx / tileCountX);
for (auto x = coord.x - 1; x <= coord.x + 1; ++x)
{
for (auto y = coord.y - 1; y <= coord.y + 1; ++y)
{
if (x >= 0 && x < tileCountX && y >= 0 && y < tileCountY)
{
if (x != coord.x || y != coord.y)
{
retVal += bs[tileCountX * y + x];
}
}
else
{
retVal++;
}
}
}
return retVal;
};
for (auto i = 0u; i < 5; ++i)
{
for (auto j = 0u; j < bs.size(); ++j)
{
auto count = getNeighbours(j);
if (count < 4) bs[i] = 1;
else if (count > 4) bs[i] = 0;
}
}
//add the detail tiles
int tile = 0;
std::vector<int> usedTiles = { 0 };
for (auto i = 0u; i < bs.size(); ++i)
{
if (bs[i] == 1)
{
auto x = i % tileCountX;
auto y = i / tileCountX;
while (std::find(usedTiles.begin(), usedTiles.end(), tile) != usedTiles.end())
{
tile = xy::Util::Random::value(Tile::FlowersOne, Tile::RockThree);
}
usedTiles.push_back(tile);
addTile(x * tileWidth, y * tileHeight, static_cast<Tile>(tile), m_borderArray);
if (usedTiles.size() == (Tile::RockThree - Tile::FlowersOne))
{
usedTiles = { 0 };
}
}
}
//load lawn data. build this row/column order so we can set specific tiles as needed
for (auto y = borderTop; y < tileCountY - borderTop; ++y)
{
for (auto x = borderLeft; x < tileCountX - borderLeft; ++x)
{
addTile(x * tileWidth, y * tileHeight, Tile::LongGrass, m_lawnArray);
}
}
}
void Tilemap::addTile(float x, float y, Tile tile, std::vector<sf::Vertex>& vertArray)
{
vertArray.emplace_back(sf::Vertex({ x, y }, { tilePositions[tile].x, tilePositions[tile].y }));
vertArray.emplace_back(sf::Vertex({ x + tileWidth, y }, { tilePositions[tile].x + tileSize.x, tilePositions[tile].y }));
vertArray.emplace_back(sf::Vertex({ x + tileWidth, y + tileHeight }, { tilePositions[tile].x + tileSize.x, tilePositions[tile].y + tileSize.y }));
vertArray.emplace_back(sf::Vertex({ x, y + tileHeight }, { tilePositions[tile].x, tilePositions[tile].y + tileSize.y}));
}
void Tilemap::draw(sf::RenderTarget& rt, sf::RenderStates states) const
{
states.texture = &m_texture;
rt.draw(m_borderArray.data(), m_borderArray.size(), sf::Quads, states);
rt.draw(m_lawnArray.data(), m_lawnArray.size(), sf::Quads, states);
}
|
#ifndef __DUI_APP_H__
#define __DUI_APP_H__
#include "DUILib.h"
DUI_BGN_NAMESPCE
class DUILIB_API CDUIApp: public IDUIApp
{
public:
CDUIApp();
~CDUIApp();
virtual BOOL Init(const CDUIString& strEntryXML);
virtual void Term();
virtual IDUISkinMgr* GetSkinMgr() const;
virtual IDUIControlFactory* GetControlFactory() const;
virtual CDUIMessageLoop* GetMessageLoop();
protected:
IDUISkinMgr* m_pSkinMgr;
IDUIControlFactory* m_pControlFactory;
CDUIMessageLoop m_messageLoop;
};
DUI_END_NAMESPCE
#endif //__DUI_APP_H__
|
class Codec {
public:
string serialize(Node* root) {
if (!root) return "#"; // NOTE, "#"
queue<Node*> q {{root}};
string res = "";
while (!q.empty()) {
auto t = q.front(); q.pop();
// NOTE, children size to seperate nodes
res += to_string(t->val) + " " + to_string(t->children.size()) + " ";
for (auto & a : t->children) {
q.push(a); }}
return res; }
Node* deserialize(string data) {
if (data.empty()) return nullptr;
istringstream is(data);
string val, size;
is >> val;
if (val == "#") return nullptr;
is >> size;
Node * res = new Node(stoi(val), {}), * root = res;
queue<Node*> qNode{{root}};
queue<int> qSize{{stoi(size)}};
while (!qNode.empty()) {
auto t = qNode.front(); qNode.pop();
int len = qSize.front(); qSize.pop();
for (int i = 0; i < len; i++) {
if (!(is >> val)) break;
if (!(is >> size)) break;
Node * node = new Node(stoi(val), {});
qNode.push(node);
qSize.push(stoi(size));
// NOTE: add child nodes
t->children.push_back(node); } }
return res; }
};
|
#include <bits/stdc++.h>
using namespace std;
int dist(int a,int b, int c, int d){
int y;
y = abs(c-a) + abs(d-b);
return y;
}
int man(int a, int b, int c, int d){
int y;
y = pow(abs(c-a),2) + pow(abs(d-b),2);
return y;
}
FILE* inf;
FILE* outf;
int row,col,prow,pcol,frow,fcol,que;
int main(){
inf = fopen("probein.txt","r");
outf = fopen("probeout.txt","w");
fscanf(inf,"%d%d%d%d%d%d%d",&row,&col,&prow,&pcol,&frow,&fcol,&que);
for(int i = 0;i<que;i++){
int x,y,water,lava; // x,y is the coords of the querey, water and lava is dist from water / lava
fscanf(inf,"%d%d",&x,&y);
if(abs(prow-frow) == abs(pcol - fcol)){
water = max(abs(prow-x),abs(pcol-y));
lava = max(abs(frow-x),abs(fcol-y));
}
else{
water = abs(prow-x) + abs(pcol-y);
lava = abs(frow-x) + abs(fcol-y);
}
if (water==lava){
fprintf(outf,"MOUNTAINS\n");
}
else if(water < lava){
fprintf(outf,"WATER\n");
}
else{
fprintf(outf,"LAVA\n");
}
}
return 0;
}
|
#include "graphics\Singularity.Graphics.h"
namespace Singularity
{
namespace Graphics
{
class Texture2D
{
protected:
#pragma region Variables
ID3D10Device* m_pDevice;
ID3D10Texture2D* m_pTexture;
ID3D10ShaderResourceView* m_pShaderResView;
D3D10_TEXTURE2D_DESC m_kDescription;
bool m_bDirty;
unsigned m_iRowSpan;
unsigned char* m_pTextureBuffer;
#pragma endregion
public:
#pragma region Properties
const unsigned Get_Width() const;
const unsigned Get_Height() const;
const unsigned Get_MipLevels() const;
#pragma endregion
#pragma region Constructors and Finalizers
Texture2D(unsigned width, unsigned height, bool mipmap = true);
~Texture2D();
#pragma endregion
#pragma region Methods
void SetPixel(unsigned x, unsigned y, Color color);
void SetPixels(void* buffer, int size, int level = 1);
Color GetPixel(unsigned x, unsigned y, bool force = false);
void Apply();
#pragma endregion
#pragma region Static Methods
static Texture2D* LoadTextureFromFile(String path);
#pragma endregion
friend class Material;
friend class Singularity::Graphics::Devices::DrawingContext;
friend class Singularity::Graphics::Devices::DeferredDrawingContext;
protected:
#pragma region Constructors and Finalizers
Texture2D(ID3D10Device* device, ID3D10Texture2D* texture);
#pragma endregion
};
#include "graphics\Texture2d.inc"
}
}
|
#pragma once
#include <basetsd.h>
#include <string>
#include <rapidxml/rapidxml.hpp>
#include <dxgi1_2.h>
namespace GraphicsEngine
{
class SettingsManager
{
public:
static SettingsManager Build(const std::wstring& filename);
uint32_t GetAdapterIndex() const;
const std::wstring& GetAdapterDescription() const;
SIZE_T GetAdapterDedicatedVideoMemory() const;
private:
SettingsManager();
void ReadFile(const std::wstring& filename);
void CreateFile(const std::wstring& filename);
void AddAdaptersInfo(rapidxml::xml_document<wchar_t>* document, rapidxml::xml_node<wchar_t>* parent);
void AddAdapterInfo(rapidxml::xml_document<wchar_t>* document, rapidxml::xml_node<wchar_t>* parent, uint32_t adapterIndex, const DXGI_ADAPTER_DESC2& adapterDesc) const;
template<typename T>
wchar_t* AllocateValue(rapidxml::xml_document<wchar_t>* document, T value) const;
private:
uint32_t m_adapterIndex;
std::wstring m_adapterDescription;
SIZE_T m_adapterDedicatedVideoMemory;
};
template <typename T>
wchar_t* SettingsManager::AllocateValue(rapidxml::xml_document<wchar_t>* document, T value) const
{
return document->allocate_string(std::to_wstring(value).data());
}
}
|
// This file has been generated by Py++.
#ifndef StateIterator_hpp__pyplusplus_wrapper
#define StateIterator_hpp__pyplusplus_wrapper
void register_StateIterator_class();
#endif//StateIterator_hpp__pyplusplus_wrapper
|
#include <cmath>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <set>
#include <stack>
#include <sstream>
#include <string>
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/* Solution */
const int MOD = 1000000007;
typedef long long ll;
class Solution
{
public:
int ways(vector<string>& pizza, int k)
{
int m = pizza.size();
int n = pizza[0].size();
vector<vector<int>> presum(m, vector<int>(n, 0));
for (int r = m - 1; r >= 0; --r)
{
for (int c = n - 1; c >= 0; --c)
{
presum[r][c] = (pizza[r][c] == 'A' ? 1 : 0)
+ (r + 1 > m - 1 ? 0 : presum[r + 1][c])
+ (c + 1 > n - 1 ? 0 : presum[r][c + 1])
- (r + 1 > m - 1 || c + 1 > n - 1 ? 0 : presum[r + 1][c + 1]);
}
}
vector<vector<vector<ll>>> dp(m, vector<vector<ll>>(n, vector<ll>(k, -1)));
return dfs(presum, dp, 0, 0, k - 1);
}
ll dfs(vector<vector<int>>& presum, vector<vector<vector<ll>>>& dp, int r0, int c0, int cuts)
{
if (dp[r0][c0][cuts] != -1) return dp[r0][c0][cuts];
if (cuts == 0 && presum[r0][c0] > 0) return 1;
if (presum[r0][c0] == 0) return 0;
int m = presum.size();
int n = presum[0].size();
ll ans = 0;
for (int r = r0 + 1; r < m; ++r)
{
if (presum[r0][c0] > presum[r][c0] && presum[r][c0] > 0)
{
ans = (ans + dfs(presum, dp, r, c0, cuts - 1)) % MOD;
}
}
for (int c = c0 + 1; c < n; ++c)
{
if (presum[r0][c0] > presum[r0][c] && presum[r0][c] > 0)
{
ans = (ans + dfs(presum, dp, r0, c, cuts - 1)) % MOD;
}
}
dp[r0][c0][cuts] = ans % MOD;
return dp[r0][c0][cuts];
}
};
int main()
{
Solution sol;
// vector<string> pizza = {"A..", "AAA", "..."};
// int k = 3;
// vector<string> pizza = {"A..", "AA.", "..."};
// int k = 3;
// vector<string> pizza = {"A..", "A..", "..."};
// int k = 1;
vector<string> pizza = {".A..A",
"A.A..",
"A.AA.",
"AAAA.",
"A.AA."};
int k = 5;
cout << sol.ways(pizza, k) << endl;
}
|
#include <bits/stdc++.h>
using namespace std;
int main(){
int N;
bool cc = false;
while(cin >> N,N)
{
if(cc) cout << endl;
cc = true;
string ids[1001];
vector<int> ages;
while(N--)
{
string nome;
int idade;
cin >> nome >> idade;
ids[idade] = nome;
ages.push_back(idade);
}
sort(ages.begin(),ages.end());
for(auto age: ages)
{
cout << ids[age] << endl;
}
}
return 0;
}
|
#include "thunderbolt.h"
thunderbolt::thunderbolt(int x, int y)
{
image.load("thunderbolt.png");
rect = image.rect();
rect.translate(x, y);
hit = false;
std::cout << "wtf" << std::endl;
}
thunderbolt::~thunderbolt() {
std::cout << "thunderbolt deleted" << std::endl;
}
void thunderbolt::autoMove(int x) { //BALL AUTOMOVE
if(x == 1)
rect.translate(2, 0);
else if(x == 2)
rect.translate(-2, 0);
}
|
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <math.h>
#include <time.h>
#include "boost/date_time/posix_time/posix_time.hpp"
//Librerias propias usadas
#include "constantes.hpp"
#include "camina10/v_repConst.h"
#include "../../Convexhull/vector3d.hpp"
#include "../../Convexhull/convexhull.cpp"
#include "../../Convexhull/analisis.cpp"
// Used data structures:
#include "camina10/DatosTrayectoriaPata.h"
#include "camina10/PlanificadorParametros.h"
#include "camina10/SenalesCambios.h"
#include "camina10/UbicacionRobot.h"
// Used API services:
#include "vrep_common/VrepInfo.h"
//Clientes y Servicios
ros::ServiceClient client_Planificador;
camina10::PlanificadorParametros srv_Planificador;
// variables Globales
bool simulationRunning=true;
bool sensorTrigger=false, Inicio=true;
bool InicioApoyo[Npatas]={false,false,false,false,false,false}, FinApoyo[Npatas]={false,false,false,false,false,false};
bool InicioTransf[Npatas]={false,false,false,false,false,false}, FinTransf[Npatas]={false,false,false,false,false,false},mediaTransf[Npatas]={true,true,true,true,true,true};
float simulationTime=0.0f;
float divisionTrayectoriaPata[Npatas], divisionTiempo=0.0, desfasaje_t[Npatas], beta=0.0, phi[Npatas],alfa=0.0, dh=0.0, velApoyo=0.0;
float T[Npatas], T_contador[Npatas], T_apoyo[Npatas],T_transf[Npatas], contadores[Npatas],delta_t[Npatas], modificacion_T_apoyo = 0.0, modificacion_lambda =0.0;
float xCuerpo_1=0.0, xCuerpo_2=0.0, yCuerpo_1=0.0, yCuerpo_2=0.0, mod_velocidadCuerpo=0.0;
int pataApoyo[Npatas],divisionTrayectoriaPata_ini;
int cuenta=0, PasosIni=0, PataPrint=0;
FILE *fp1;
punto3d coordenadaCuerpo, velocidadCuerpo, posicionActualPataSistemaPata[Npatas],posCuerpo_1, posCuerpo_2;
punto3d Offset;
boost::posix_time::ptime timer_1,timer_2;
camina10::DatosTrayectoriaPata datosTrayectoriaPata;
ros::Publisher chatter_pub1,chatter_pub2;
// Funciones
void Inizializacion();
bool CambioDeEstado_Apoyo(int nPata);
bool CambioDeEstado_Transf(int nPata);
int VerificacionEstadoPata(int nPata, int estadoActual);
bool LlegadaFinEDT(int nPata);
void ParametrosVelocidad();
float VelocidadCuerpo(boost::posix_time::ptime t1, boost::posix_time::ptime t2, punto3d Pos1, punto3d Pos2);
punto3d TransformacionHomogenea(punto3d Punto_in, punto3d L_traslacion, float ang_rotacion);
// Topic subscriber callbacks:
void infoCallback(const vrep_common::VrepInfo::ConstPtr& info)
{
simulationTime=info->simulationTime.data;
simulationRunning=(info->simulatorState.data&1)!=0;
}
void ubicacionRobCallback(camina10::UbicacionRobot msgUbicacionRobot)
{
coordenadaCuerpo.x = msgUbicacionRobot.coordenadaCuerpo_x;
coordenadaCuerpo.y = msgUbicacionRobot.coordenadaCuerpo_y;
for(int k=0; k<Npatas;k++) {
pataApoyo[k] = msgUbicacionRobot.pataApoyo[k];
posicionActualPataSistemaPata[k].x = msgUbicacionRobot.coordenadaPataSistemaPata_x[k];
posicionActualPataSistemaPata[k].y = msgUbicacionRobot.coordenadaPataSistemaPata_y[k];
posicionActualPataSistemaPata[k].z = msgUbicacionRobot.coordenadaPataSistemaPata_z[k];
}
}
void relojCallback(camina10::SenalesCambios msgSenal)
{
bool cambio_a_Apoyo=false,llegada_FEDT=false;
float lambda = 0.0;
if (!msgSenal.Stop){
ParametrosVelocidad();
if (Inicio){
Inizializacion();
} else {
chatter_pub1.publish(datosTrayectoriaPata);
for(int k=0;k<Npatas;k++){
if(k==PataPrint) ROS_INFO("pata[%d] contador=%.3f",k+1,contadores[k]);
datosTrayectoriaPata.cambio_estado[k]=0;
//-- Verificacion por posicion actual de pata recibida
//-- Seleccion de estado proximo de la pata
//-- si hay cambio de estado se activa la bandera correspondiente
datosTrayectoriaPata.vector_estados[k]=VerificacionEstadoPata(k,datosTrayectoriaPata.vector_estados[k]);
if(k==PataPrint) ROS_INFO("pata[%d] estado=%d",k+1,datosTrayectoriaPata.vector_estados[k]);
if(datosTrayectoriaPata.vector_estados[k]==Apoyo and datosTrayectoriaPata.cambio_estado[k]==1) contadores[k]=0.0;
if (datosTrayectoriaPata.vector_estados[k]==Transferencia) {
T_contador[k]=T[k];
} else {
T_contador[k]=T_apoyo[k];
}
if (fabs(contadores[k]-T_contador[k])<(T[k]/divisionTrayectoriaPata[k])){
contadores[k] = contadores[k];
} else {
contadores[k] = contadores[k] + T[k]/divisionTrayectoriaPata[k];
}
if (datosTrayectoriaPata.vector_estados[k]==Transferencia) {
delta_t[k] = contadores[k]-T_apoyo[k];
} else {
delta_t[k] = contadores[k];
}
// if (fabs(contadores[k]-T[k])<(T[k]/divisionTrayectoriaPata[k])) {
// contadores[k]=0.0;
// datosTrayectoriaPata.vector_estados[k]==Apoyo;
// }
datosTrayectoriaPata.T[k]=T_transf[k];
datosTrayectoriaPata.t_Trayectoria[k]=delta_t[k];
}// fin del for
}//-- Checkea por inicio
}//-- fin is !Stop
} //-- fin de callback
int main(int argc, char **argv)
{
float lambda=0.0, f=0.0, vector_estados[Npatas], T_ini;
int Narg=0;
Narg=23;
if (argc>=Narg)
{
PasosIni=atoi(argv[1]);
T_ini=atof(argv[2]); // Periodo de trayectoria [seg]
divisionTrayectoriaPata_ini=atof(argv[3]); //N puntos
beta=atof(argv[4]);
lambda=atof(argv[5]);
velApoyo=atof(argv[6]);
alfa=atof(argv[7])*pi/180;
dh=atof(argv[8]);
Offset.x=atof(argv[9]);
Offset.y=atof(argv[10]);
Offset.z=atof(argv[11]);
for(int k=0;k<Npatas;k++) desfasaje_t[k]=atof(argv[12+k]);
for(int k=0;k<Npatas;k++) phi[k]=atof(argv[12+Npatas+k])*pi/180;
} else {
ROS_ERROR("Nodo1: Indique argumentos!\n");
return 0;
}
/*Inicio nodo de ROS*/
std::string nodeName("Nodo1_datosTrayectoriaPata");
ros::init(argc,argv,nodeName.c_str());
ros::NodeHandle node;
ROS_INFO("Nodo1_datosTrayectoriaPata just started\n");
//-- Topicos susbcritos y publicados
ros::Subscriber subInfo1=node.subscribe("/vrep/info",100,infoCallback);
ros::Subscriber subInfo2=node.subscribe("Reloj",100,relojCallback);
ros::Subscriber subInfo3=node.subscribe("UbicacionRobot",100,ubicacionRobCallback);
//-- Manda topico especifico para cada pata
chatter_pub1=node.advertise<camina10::DatosTrayectoriaPata>("datosTrayectoria", 100);
//-- Clientes y Servicios
client_Planificador = node.serviceClient<camina10::PlanificadorParametros>("PlanificadorPisada");
//-- Log de datos
std::string fileName("../fuerte_workspace/sandbox/TesisMaureen/ROS/camina10/datos/SalidaDatos");
std::string texto(".txt");
fileName+=texto;
fp1 = fopen(fileName.c_str(),"w+");
//-- Inicializo variables
for(int k=0;k<Npatas;k++) {
T[k] = T_ini;
T_apoyo[k] = beta*T[k];
T_transf[k] = T[k]-T_apoyo[k];
if(k==0) ROS_INFO("T_apoyo=%.3f, T_trans=%.3f",T_apoyo[k],T_transf[k]);
contadores[k] = desfasaje_t[k]*T_ini;
divisionTrayectoriaPata[k] = divisionTrayectoriaPata_ini;
if(desfasaje_t[k]>beta){
vector_estados[k] = 1;
T_contador[k] = T_transf[k];
} else {
vector_estados[k] = 0;
T_contador[k] = T_apoyo[k];
}
}
//-- Datos de envio
for(int k=0;k<Npatas;k++) {
datosTrayectoriaPata.T.push_back(T_transf[k]);
datosTrayectoriaPata.t_Trayectoria.push_back(0);
datosTrayectoriaPata.lambda.push_back(lambda);
datosTrayectoriaPata.alfa.push_back(alfa);
datosTrayectoriaPata.desfasaje_t.push_back(desfasaje_t[k]);
datosTrayectoriaPata.vector_estados.push_back(vector_estados[k]);
datosTrayectoriaPata.cambio_estado.push_back(0);
datosTrayectoriaPata.correccion_x.push_back(0);
datosTrayectoriaPata.correccion_y.push_back(0);
datosTrayectoriaPata.correccion_ID.push_back(-1);
}
//-- Prepara variables para calculos de trayectoria de PATA
//contadores = 1/divisionTrayectoriaPata;
divisionTiempo = T_ini/divisionTrayectoriaPata_ini;
f=1/divisionTiempo;
/* La velocidad de envío de los datos se encarga de darme el tiempo total de trayectoria deseado */
/* Velocidad de transmision */
ros::Rate loop_rate(f); //Frecuencia [Hz]
//-- Delay inicial para esperar inicio de todos los nodos
// for(i=0;i<10;i++) loop_rate.sleep();
modificacion_T_apoyo = T_ini;
modificacion_lambda = lambda;
while (ros::ok() && simulationRunning){
ros::spinOnce();
// loop_rate.sleep();
}
ROS_INFO("Adios1!");
// fclose(fp1);
ros::shutdown();
return 0;
}
/* Funciones */
void Inizializacion(){
cuenta++;
if (cuenta==PasosIni*divisionTrayectoriaPata_ini){
Inicio=false;
} else {
for(int k=0;k<Npatas;k++) {
datosTrayectoriaPata.t_Trayectoria[k]=delta_t[k];
datosTrayectoriaPata.T[k]=T_transf[k];
}
chatter_pub1.publish(datosTrayectoriaPata);
for(int k=0;k<Npatas;k++){
datosTrayectoriaPata.cambio_estado[k]=0;
fprintf(fp1,"%.3f\t",delta_t[k]);
contadores[k] = contadores[k] + T[k]/divisionTrayectoriaPata[k];
if(k==0) ROS_INFO("cuenta=%.3f",contadores[k]);
if (contadores[k]>=beta*T[k]) {
delta_t[k] = contadores[k]-T_apoyo[k];
datosTrayectoriaPata.vector_estados[k]=Transferencia;
} else {
delta_t[k] = contadores[k];
datosTrayectoriaPata.vector_estados[k]=Apoyo;
}
if (fabs(contadores[k]-T[k])<=(T[k]/divisionTrayectoriaPata[k])){
contadores[k] = 0.0;
}
CambioDeEstado_Apoyo(k);
LlegadaFinEDT(k);
}
fprintf(fp1,"\n");
}
}
//bool CambioDeEstado_Apoyo(int nPata){
// bool cambio = false;
////--- Apoyo de Pata
// if (pataApoyo[nPata]==1 and FinApoyo[nPata]) {
// InicioApoyo[nPata]=true;
// FinApoyo[nPata]=false;
// }
// if (pataApoyo[nPata]==0) {
// FinApoyo[nPata]=true;
// }
// if (InicioApoyo[nPata]){
// InicioApoyo[nPata] = false;
// cambio = true;
// }
// return cambio;
//}
//bool CambioDeEstado_Transf(int nPata){
// bool cambio = false;
////--- Transferencia Pata
// if (pataApoyo[nPata]==0 and FinTransf[nPata]) {
// InicioTransf[nPata]=true;
// FinTransf[nPata]=false;
// }
// if (pataApoyo[nPata]==1) {
// FinTransf[nPata]=true;
// }
// if (InicioTransf[nPata]){
// InicioTransf[nPata] = false;
// cambio = true;
// }
// return cambio;
//}
//bool LlegadaFinEDT(int nPata){
//
// float paso_y = 0.0;
// bool cambio = false; punto3d P0, Fin_EDT;
// int n = 0;
// paso_y = velApoyo*divisionTiempo;
//// ROS_WARN("%.3f,%.3f",velApoyo,divisionTiempo);
// P0.x = Offset.y-FinEspacioTrabajo_y-paso_y;
// //-----Transformacion de trayectoria a Sistema de Pata
// Fin_EDT = TransformacionHomogenea(P0,Offset,phi[nPata]+alfa);
//
//// if(nPata==n) ROS_WARN("pata.y=%.4f,finEDT.y=%.4f",posicionActualPataSistemaPata[nPata].y,Fin_EDT.y);
// if (fabs(posicionActualPataSistemaPata[nPata].y-Fin_EDT.y)<=0.005 and FinTransf[nPata]) {
// InicioTransf[nPata]=true;
// FinTransf[nPata]=false;
// mediaTransf[nPata]=true;
// }
//
//// if(nPata==n) ROS_WARN("Pata.z=%.4f",posicionActualPataSistemaPata[nPata].z);
// if (posicionActualPataSistemaPata[nPata].z>=(dh-0.002) and mediaTransf[nPata]) {
// FinTransf[nPata]=true;
// mediaTransf[nPata]=false;
// if(nPata==0) ROS_WARN("------Pata[%d] arriba",nPata+1);
// }
// if (InicioTransf[nPata]){
// InicioTransf[nPata] = false;
// cambio = true;
// }
// return cambio;
//}
/* Toma de muestras de tiempo y posicion para calculo de velocidad
.. se toma de muestra la pata1*/
void ParametrosVelocidad(){
//--- Apoyo de Pata 1
if (InicioApoyo[0]){
posCuerpo_1.x = coordenadaCuerpo.x;
posCuerpo_1.y = coordenadaCuerpo.y;
timer_1 = boost::posix_time::microsec_clock::local_time();
}
//--- Transferencia de Pata 1
if (InicioTransf[0]){
posCuerpo_2.x = coordenadaCuerpo.x;
posCuerpo_2.y = coordenadaCuerpo.y;
timer_2 = boost::posix_time::microsec_clock::local_time();
}
}
/* Retorna el modulo de la velocidad del cuerpo, segun el tiempo y distancia del cuerpo
.. en apoyo y transferencia*/
float VelocidadCuerpo(boost::posix_time::ptime t1, boost::posix_time::ptime t2, punto3d Pos1, punto3d Pos2){
float delta_x=0.0, delta_y=0.0, tiempo_ahora=0.0;
boost::posix_time::time_duration diff_t;
delta_x = fabs(Pos1.x-Pos2.x);
delta_y = fabs(Pos1.y-Pos2.y);
diff_t = t1 - t2;
tiempo_ahora = (float) fabs(diff_t.total_milliseconds())/1000;
velocidadCuerpo.x = delta_x/tiempo_ahora;
velocidadCuerpo.y = delta_y/tiempo_ahora;
return (sqrt(velocidadCuerpo.x*velocidadCuerpo.x + velocidadCuerpo.y*velocidadCuerpo.y));
}
punto3d TransformacionHomogenea(punto3d Punto_in, punto3d L_traslacion, float ang_rotacion){
punto3d Punto_out;
Punto_out.x = L_traslacion.x + Punto_in.x*cos(ang_rotacion) - Punto_in.y*sin(ang_rotacion);
Punto_out.y = L_traslacion.y + Punto_in.x*sin(ang_rotacion) + Punto_in.y*cos(ang_rotacion);
Punto_out.z = L_traslacion.z + Punto_in.z;
return(Punto_out);
}
//-- Verificacion por posicion actual de pata recibida
int VerificacionEstadoPata(int nPata, int estadoActual){
bool cambio_a_Apoyo=false,llegada_FEDT=false;
int estadoSiguiente;
estadoSiguiente=estadoActual;
cambio_a_Apoyo = CambioDeEstado_Apoyo(nPata);
if(cambio_a_Apoyo){
cambio_a_Apoyo = false;
estadoSiguiente = Apoyo;
datosTrayectoriaPata.cambio_estado[nPata]=1;
// if(nPata==0) ROS_WARN("****Inicia Apoyo pata[%d]",nPata+1);
}
llegada_FEDT = LlegadaFinEDT(nPata);
if(llegada_FEDT){
llegada_FEDT = false;
estadoSiguiente = Transferencia;
datosTrayectoriaPata.cambio_estado[nPata]=1;
if(nPata==PataPrint) ROS_WARN("------Inicia Transferencia pata[%d]",nPata+1);
}
return(estadoSiguiente);
}
bool CambioDeEstado_Apoyo(int nPata){
bool cambio = false;
//--- Apoyo de Pata
if (pataApoyo[nPata]==Apoyo and FinApoyo[nPata]) {
InicioApoyo[nPata]=true;
FinApoyo[nPata]=false;
if(nPata==PataPrint) ROS_WARN("****Inicia Apoyo pata[%d]",nPata+1);
}
if (fabs(contadores[nPata]-T[nPata])<(T[nPata]/divisionTrayectoriaPata[nPata])) {
FinApoyo[nPata]=true;
if(nPata==PataPrint) ROS_WARN("****Pata[%d] preApoyo",nPata+1);
}
if (InicioApoyo[nPata]){
InicioApoyo[nPata] = false;
cambio = true;
}
return cambio;
}
bool LlegadaFinEDT(int nPata){
float paso_y = 0.0;
bool cambio = false; punto3d P0, Fin_EDT;
paso_y = velApoyo*divisionTiempo;
// ROS_WARN("%.3f,%.3f",velApoyo,divisionTiempo);
P0.x = Offset.y-FinEspacioTrabajo_y-paso_y;
//-----Transformacion de trayectoria a Sistema de Pata
Fin_EDT = TransformacionHomogenea(P0,Offset,phi[nPata]+alfa);
if(nPata==PataPrint) ROS_WARN("pata.y=%.4f,finEDT.y=%.4f",posicionActualPataSistemaPata[nPata].y,Fin_EDT.y);
if (fabs(posicionActualPataSistemaPata[nPata].y-Fin_EDT.y)<=0.005 and FinTransf[nPata]) {
InicioTransf[nPata]=true;
FinTransf[nPata]=false;
}
// if(nPata==n) ROS_WARN("Pata.z=%.4f",posicionActualPataSistemaPata[nPata].z);
if (fabs(contadores[nPata]-T_apoyo[nPata])<(T[nPata]/divisionTrayectoriaPata[nPata])) {
FinTransf[nPata]=true;
// if(nPata==PataPrint) ROS_WARN("------Pata[%d] preTransferencia",nPata+1);
}
if (InicioTransf[nPata]){
InicioTransf[nPata] = false;
cambio = true;
if(nPata==PataPrint) ROS_WARN("------Pata[%d] Transferencia",nPata+1);
}
return cambio;
}
//-- Hay llamada al planificador?
// cambio_a_Apoyo = CambioDeEstado_Apoyo(k);
// if(cambio_a_Apoyo){
// cambio_a_Apoyo = false;
// //-- reinicio cuenta para iniciar apoyo
// contadores[k] = 0.0;
// datosTrayectoriaPata.cambio_estado[k]=1;
// datosTrayectoriaPata.vector_estados[k]=0;
// }
// llegada_FEDT = LlegadaFinEDT(k);
// if(llegada_FEDT){
// llegada_FEDT = false;
// ROS_INFO("------Inicia Transferencia pata[%d]",k);
// datosTrayectoriaPata.cambio_estado[k]=1;
// datosTrayectoriaPata.vector_estados[k]=1;
// contadores[k] = contadores[k] + 3*T[k]/divisionTrayectoriaPata[k];
// }
// //-------------------------------
// if(cambio_a_Apoyo){
// cambio_a_Apoyo = false;
// //-- reinicio cuenta para iniciar apoyo
// contadores[k] = 0.0;
// datosTrayectoriaPata.correccion_ID[k]=-1;
// datosTrayectoriaPata.correccion_x[k]=0.0;
// datosTrayectoriaPata.correccion_y[k]=0.0;
// mod_velocidadCuerpo = VelocidadCuerpo(timer_1,timer_2,posCuerpo_1,posCuerpo_2);
//
// srv_Planificador.request.T = T[k];
// srv_Planificador.request.lambda = lambda;
// srv_Planificador.request.mod_velApoyo = mod_velocidadCuerpo;
// if (client_Planificador.call(srv_Planificador)){
// modificacion_lambda = srv_Planificador.response.modificacion_lambda;
// modificacion_T_apoyo = srv_Planificador.response.modificacion_T_apoyo;
// datosTrayectoriaPata.correccion_ID[k] = srv_Planificador.response.correccion_ID;
// datosTrayectoriaPata.correccion_x[k] = srv_Planificador.response.correccion_x;
// datosTrayectoriaPata.correccion_y[k] = srv_Planificador.response.correccion_y;
// ROS_INFO("Nodo1::t_sim=%.3f, lambda_c=%.3f,t_c=%.3f",simulationTime,modificacion_lambda,modificacion_T_apoyo);
// } else {
// ROS_ERROR("Nodo1::servicio de Planificacion no funciona");
// ROS_ERROR("result=%d", srv_Planificador.response.result);
// }
//
//// /////////////////////PRUEBAS///////////////////////////////////
//// for(int k=0;k<Npatas;k++) {
//// datosTrayectoriaPata.correccion_ID[k]=-1;
//// datosTrayectoriaPata.correccion_x[k]=0;
//// datosTrayectoriaPata.correccion_y[k]=0;
//// }
//// ///////////////////////////////////////////////////////////////
//// datosTrayectoriaPata.correccion_ID[2]=1;
//// datosTrayectoriaPata.correccion_x[2]=0.01;
//// datosTrayectoriaPata.correccion_y[2]=0.01;
//
//
// T_apoyo[k] = modificacion_T_apoyo;
// T[k] = T_apoyo[k]/beta;
// divisionTrayectoriaPata[k] = T[k]/divisionTiempo;
// datosTrayectoriaPata.lambda[k]=modificacion_lambda;
// }// Fin cambio de estado
// if (fabs(contadores[k]-beta*T[k])<(T[k]/divisionTrayectoriaPata[k])) {
// ROS_INFO("Inicia Transferencia pata[%d]",k);
//// contadores[k] = beta*T[k];
// datosTrayectoriaPata.cambio_estado[k]=1;
// datosTrayectoriaPata.vector_estados[k]=1;
// }
|
#ifndef _WEBCREATOR
#define _WEBCREATOR
#include "Style.hpp"
#include "Element.hpp"
#include <vector>
using namespace std;
class WebCreator
{
private:
vector<Style> m_styleList;
vector<IElement*> m_elementList;
string m_title;
void ReadStyle(const string& stylePage);
void ReadPage(const string& pagePath);
void BuildPage(const string& pagePath);
ostream& OutputHeader(ostream& out);
ostream& OutputStyle(ostream& out);
ostream& OutputElement(ostream& out);
ostream& OutputFooter(ostream& out);
public:
WebCreator(const string& title);
~WebCreator();
void ConvertToHTML(const string& stylePath, const string& pagePath, const string& outputPath);
};
#endif
|
/*====================================================================*
- Copyright (C) 2001 Leptonica. All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions
- are met:
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
- 2. Redistributions in binary form must reproduce the above
- copyright notice, this list of conditions and the following
- disclaimer in the documentation and/or other materials
- provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANY
- 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.
*====================================================================*/
/*
* textops.c
*
* Font layout
* PIX *pixAddSingleTextblock()
* PIX *pixAddSingleTextline()
* l_int32 pixSetTextblock()
* l_int32 pixSetTextline()
* PIXA *pixaAddTextNumber()
* PIXA *pixaAddTextline()
*
* Text size estimation and partitioning
* SARRAY *bmfGetLineStrings()
* NUMA *bmfGetWordWidths()
* l_int32 bmfGetStringWidth()
*
* Text splitting
* SARRAY *splitStringToParagraphs()
* static l_int32 stringAllWhitespace()
* static l_int32 stringLeadingWhitespace()
*
* This is a simple utility to put text on images. One font and style
* is provided, with a variety of pt sizes. For example, to put a
* line of green 10 pt text on an image, with the beginning baseline
* at (50, 50):
* L_Bmf *bmf = bmfCreate("./fonts", 10);
* const char *textstr = "This is a funny cat";
* pixSetTextline(pixs, bmf, textstr, 0x00ff0000, 50, 50, NULL, NULL);
*
* The simplest interfaces for adding text to an image are
* pixAddSingleTextline() and pixAddSingleTextblock().
*/
#include <string.h>
#include "allheaders.h"
static l_int32 stringAllWhitespace(char *textstr, l_int32 *pval);
static l_int32 stringLeadingWhitespace(char *textstr, l_int32 *pval);
/*---------------------------------------------------------------------*
* Font layout *
*---------------------------------------------------------------------*/
/*!
* pixAddSingleTextblock()
*
* Input: pixs (input pix; colormap ok)
* bmf (bitmap font data)
* textstr (<optional> text string to be added)
* val (color to set the text)
* location (L_ADD_ABOVE, L_ADD_AT_TOP, L_ADD_AT_BOT, L_ADD_BELOW)
* &overflow (<optional return> 1 if text overflows
* allocated region and is clipped; 0 otherwise)
* Return: pixd (new pix with rendered text), or either a copy
* or null on error
*
* Notes:
* (1) This function paints a set of lines of text over an image.
* If @location is L_ADD_ABOVE or L_ADD_BELOW, the pix size
* is expanded with a border and rendered over the border.
* (2) @val is the pixel value to be painted through the font mask.
* It should be chosen to agree with the depth of pixs.
* If it is out of bounds, an intermediate value is chosen.
* For RGB, use hex notation: 0xRRGGBB00, where RR is the
* hex representation of the red intensity, etc.
* (3) If textstr == NULL, use the text field in the pix.
* (4) If there is a colormap, this does the best it can to use
* the requested color, or something similar to it.
* (5) Typical usage is for labelling a pix with some text data.
*/
PIX *
pixAddSingleTextblock(PIX *pixs,
L_BMF *bmf,
const char *textstr,
l_uint32 val,
l_int32 location,
l_int32 *poverflow)
{
char *linestr;
l_int32 w, h, d, i, y, xstart, ystart, extra, spacer, rval, gval, bval;
l_int32 nlines, htext, ovf, overflow, offset, index;
l_uint32 textcolor;
PIX *pixd;
PIXCMAP *cmap, *cmapd;
SARRAY *salines;
PROCNAME("pixAddSingleTextblock");
if (poverflow)
{
*poverflow = 0;
}
if (!pixs)
{
return (PIX *)ERROR_PTR("pixs not defined", procName, NULL);
}
if (location != L_ADD_ABOVE && location != L_ADD_AT_TOP &&
location != L_ADD_AT_BOT && location != L_ADD_BELOW)
{
return (PIX *)ERROR_PTR("invalid location", procName, NULL);
}
if (!bmf)
{
L_ERROR("no bitmap fonts; returning a copy\n", procName);
return pixCopy(NULL, pixs);
}
if (!textstr)
{
textstr = pixGetText(pixs);
}
if (!textstr)
{
L_ERROR("no textstring defined; returning a copy\n", procName);
return pixCopy(NULL, pixs);
}
/* Make sure the "color" value for the text will work
* for the pix. If the pix is not colormapped and the
* value is out of range, set it to mid-range. */
pixGetDimensions(pixs, &w, &h, &d);
cmap = pixGetColormap(pixs);
if (d == 1 && val > 1)
{
val = 1;
}
else if (d == 2 && val > 3 && !cmap)
{
val = 2;
}
else if (d == 4 && val > 15 && !cmap)
{
val = 8;
}
else if (d == 8 && val > 0xff && !cmap)
{
val = 128;
}
else if (d == 16 && val > 0xffff)
{
val = 0x8000;
}
else if (d == 32 && val < 256)
{
val = 0x80808000;
}
xstart = (l_int32)(0.1 * w);
salines = bmfGetLineStrings(bmf, textstr, w - 2 * xstart, 0, &htext);
if (!salines)
{
return (PIX *)ERROR_PTR("line string sa not made", procName, NULL);
}
nlines = sarrayGetCount(salines);
/* Add white border if required */
spacer = 10; /* pixels away from image boundary or added border */
if (location == L_ADD_ABOVE || location == L_ADD_BELOW)
{
extra = htext + 2 * spacer;
pixd = pixCreate(w, h + extra, d);
pixCopyColormap(pixd, pixs);
pixSetBlackOrWhite(pixd, L_BRING_IN_WHITE);
if (location == L_ADD_ABOVE)
{
pixRasterop(pixd, 0, extra, w, h, PIX_SRC, pixs, 0, 0);
}
else /* add below */
{
pixRasterop(pixd, 0, 0, w, h, PIX_SRC, pixs, 0, 0);
}
}
else
{
pixd = pixCopy(NULL, pixs);
}
cmapd = pixGetColormap(pixd);
/* bmf->baselinetab[93] is the approximate distance from
* the top of the tallest character to the baseline. 93 was chosen
* at random, as all the baselines are essentially equal for
* each character in a font. */
offset = bmf->baselinetab[93];
if (location == L_ADD_ABOVE || location == L_ADD_AT_TOP)
{
ystart = offset + spacer;
}
else if (location == L_ADD_AT_BOT)
{
ystart = h - htext - spacer + offset;
}
else /* add below */
{
ystart = h + offset + spacer;
}
/* If cmapped, add the color if necessary to the cmap. If the
* cmap is full, use the nearest color to the requested color. */
if (cmapd)
{
extractRGBValues(val, &rval, &gval, &bval);
pixcmapAddNearestColor(cmapd, rval, gval, bval, &index);
pixcmapGetColor(cmapd, index, &rval, &gval, &bval);
composeRGBPixel(rval, gval, bval, &textcolor);
}
else
{
textcolor = val;
}
/* Keep track of overflow condition on line width */
overflow = 0;
for (i = 0, y = ystart; i < nlines; i++)
{
linestr = sarrayGetString(salines, i, 0);
pixSetTextline(pixd, bmf, linestr, textcolor,
xstart, y, NULL, &ovf);
y += bmf->lineheight + bmf->vertlinesep;
if (ovf)
{
overflow = 1;
}
}
/* Also consider vertical overflow where there is too much text to
* fit inside the image: the cases L_ADD_AT_TOP and L_ADD_AT_BOT.
* The text requires a total of htext + 2 * spacer vertical pixels. */
if (location == L_ADD_AT_TOP || location == L_ADD_AT_BOT)
{
if (h < htext + 2 * spacer)
{
overflow = 1;
}
}
if (poverflow)
{
*poverflow = overflow;
}
sarrayDestroy(&salines);
return pixd;
}
/*!
* pixAddSingleTextline()
*
* Input: pixs (input pix; colormap ok)
* bmf (bitmap font data)
* textstr (<optional> text string to be added)
* val (color to set the text)
* location (L_ADD_ABOVE, L_ADD_BELOW, L_ADD_LEFT, L_ADD_RIGHT)
* Return: pixd (new pix with rendered text), or either a copy
* or null on error
*
* Notes:
* (1) This function expands an image as required to paint a single
* line of text adjacent to the image. If @bmf == NULL, this
* returns a copy.
* (2) @val is the pixel value to be painted through the font mask.
* It should be chosen to agree with the depth of pixs.
* If it is out of bounds, an intermediate value is chosen.
* For RGB, use hex notation: 0xRRGGBB00, where RR is the
* hex representation of the red intensity, etc.
* (3) If textstr == NULL, use the text field in the pix.
* (4) If there is a colormap, this does the best it can to use
* the requested color, or something similar to it.
* (5) Typical usage is for labelling a pix with some text data.
*/
PIX *
pixAddSingleTextline(PIX *pixs,
L_BMF *bmf,
const char *textstr,
l_uint32 val,
l_int32 location)
{
l_int32 w, h, d, wtext, htext, wadd, hadd, spacer, hbaseline;
l_int32 rval, gval, bval, index;
l_uint32 textcolor;
PIX *pixd;
PIXCMAP *cmap, *cmapd;
PROCNAME("pixAddSingleTextline");
if (!pixs)
{
return (PIX *)ERROR_PTR("pixs not defined", procName, NULL);
}
if (location != L_ADD_ABOVE && location != L_ADD_BELOW &&
location != L_ADD_LEFT && location != L_ADD_RIGHT)
{
return (PIX *)ERROR_PTR("invalid location", procName, NULL);
}
if (!bmf)
{
L_ERROR("no bitmap fonts; returning a copy\n", procName);
return pixCopy(NULL, pixs);
}
if (!textstr)
{
textstr = pixGetText(pixs);
}
if (!textstr)
{
L_ERROR("no textstring defined; returning a copy\n", procName);
return pixCopy(NULL, pixs);
}
/* Make sure the "color" value for the text will work
* for the pix. If the pix is not colormapped and the
* value is out of range, set it to mid-range. */
pixGetDimensions(pixs, &w, &h, &d);
cmap = pixGetColormap(pixs);
if (d == 1 && val > 1)
{
val = 1;
}
else if (d == 2 && val > 3 && !cmap)
{
val = 2;
}
else if (d == 4 && val > 15 && !cmap)
{
val = 8;
}
else if (d == 8 && val > 0xff && !cmap)
{
val = 128;
}
else if (d == 16 && val > 0xffff)
{
val = 0x8000;
}
else if (d == 32 && val < 256)
{
val = 0x80808000;
}
/* Get the necessary text size */
bmfGetStringWidth(bmf, textstr, &wtext);
hbaseline = bmf->baselinetab[93];
htext = 1.5 * hbaseline;
/* Add white border */
spacer = 10; /* pixels away from the added border */
if (location == L_ADD_ABOVE || location == L_ADD_BELOW)
{
hadd = htext + spacer;
pixd = pixCreate(w, h + hadd, d);
pixCopyColormap(pixd, pixs);
pixSetBlackOrWhite(pixd, L_BRING_IN_WHITE);
if (location == L_ADD_ABOVE)
{
pixRasterop(pixd, 0, hadd, w, h, PIX_SRC, pixs, 0, 0);
}
else /* add below */
{
pixRasterop(pixd, 0, 0, w, h, PIX_SRC, pixs, 0, 0);
}
}
else /* L_ADD_LEFT or L_ADD_RIGHT */
{
wadd = wtext + spacer;
pixd = pixCreate(w + wadd, h, d);
pixCopyColormap(pixd, pixs);
pixSetBlackOrWhite(pixd, L_BRING_IN_WHITE);
if (location == L_ADD_LEFT)
{
pixRasterop(pixd, wadd, 0, w, h, PIX_SRC, pixs, 0, 0);
}
else /* add to right */
{
pixRasterop(pixd, 0, 0, w, h, PIX_SRC, pixs, 0, 0);
}
}
/* If cmapped, add the color if necessary to the cmap. If the
* cmap is full, use the nearest color to the requested color. */
cmapd = pixGetColormap(pixd);
if (cmapd)
{
extractRGBValues(val, &rval, &gval, &bval);
pixcmapAddNearestColor(cmapd, rval, gval, bval, &index);
pixcmapGetColor(cmapd, index, &rval, &gval, &bval);
composeRGBPixel(rval, gval, bval, &textcolor);
}
else
{
textcolor = val;
}
/* Add the text */
if (location == L_ADD_ABOVE)
pixSetTextline(pixd, bmf, textstr, textcolor,
(w - wtext) / 2, hbaseline, NULL, NULL);
else if (location == L_ADD_BELOW)
pixSetTextline(pixd, bmf, textstr, textcolor,
(w - wtext) / 2, h + spacer + hbaseline, NULL, NULL);
else if (location == L_ADD_LEFT)
pixSetTextline(pixd, bmf, textstr, textcolor,
0, (h - htext) / 2 + hbaseline, NULL, NULL);
else /* location == L_ADD_RIGHT */
pixSetTextline(pixd, bmf, textstr, textcolor,
w + spacer, (h - htext) / 2 + hbaseline, NULL, NULL);
return pixd;
}
/*!
* pixSetTextblock()
*
* Input: pixs (input image)
* bmf (bitmap font data)
* textstr (block text string to be set)
* val (color to set the text)
* x0 (left edge for each line of text)
* y0 (baseline location for the first text line)
* wtext (max width of each line of generated text)
* firstindent (indentation of first line, in x-widths)
* &overflow (<optional return> 0 if text is contained in
* input pix; 1 if it is clipped)
* Return: 0 if OK, 1 on error
*
* Notes:
* (1) This function paints a set of lines of text over an image.
* (2) @val is the pixel value to be painted through the font mask.
* It should be chosen to agree with the depth of pixs.
* If it is out of bounds, an intermediate value is chosen.
* For RGB, use hex notation: 0xRRGGBB00, where RR is the
* hex representation of the red intensity, etc.
* The last two hex digits are 00 (byte value 0), assigned to
* the A component. Note that, as usual, RGBA proceeds from
* left to right in the order from MSB to LSB (see pix.h
* for details).
* (3) If there is a colormap, this does the best it can to use
* the requested color, or something similar to it.
*/
l_int32
pixSetTextblock(PIX *pixs,
L_BMF *bmf,
const char *textstr,
l_uint32 val,
l_int32 x0,
l_int32 y0,
l_int32 wtext,
l_int32 firstindent,
l_int32 *poverflow)
{
char *linestr;
l_int32 d, h, i, w, x, y, nlines, htext, xwidth, wline, ovf, overflow;
SARRAY *salines;
PIXCMAP *cmap;
PROCNAME("pixSetTextblock");
if (!pixs)
{
return ERROR_INT("pixs not defined", procName, 1);
}
if (!bmf)
{
return ERROR_INT("bmf not defined", procName, 1);
}
if (!textstr)
{
return ERROR_INT("textstr not defined", procName, 1);
}
/* Make sure the "color" value for the text will work
* for the pix. If the pix is not colormapped and the
* value is out of range, set it to mid-range. */
pixGetDimensions(pixs, &w, &h, &d);
cmap = pixGetColormap(pixs);
if (d == 1 && val > 1)
{
val = 1;
}
else if (d == 2 && val > 3 && !cmap)
{
val = 2;
}
else if (d == 4 && val > 15 && !cmap)
{
val = 8;
}
else if (d == 8 && val > 0xff && !cmap)
{
val = 128;
}
else if (d == 16 && val > 0xffff)
{
val = 0x8000;
}
else if (d == 32 && val < 256)
{
val = 0x80808000;
}
if (w < x0 + wtext)
{
L_WARNING("reducing width of textblock\n", procName);
wtext = w - x0 - w / 10;
if (wtext <= 0)
{
return ERROR_INT("wtext too small; no room for text", procName, 1);
}
}
salines = bmfGetLineStrings(bmf, textstr, wtext, firstindent, &htext);
if (!salines)
{
return ERROR_INT("line string sa not made", procName, 1);
}
nlines = sarrayGetCount(salines);
bmfGetWidth(bmf, 'x', &xwidth);
y = y0;
overflow = 0;
for (i = 0; i < nlines; i++)
{
if (i == 0)
{
x = x0 + firstindent * xwidth;
}
else
{
x = x0;
}
linestr = sarrayGetString(salines, i, 0);
pixSetTextline(pixs, bmf, linestr, val, x, y, &wline, &ovf);
y += bmf->lineheight + bmf->vertlinesep;
if (ovf)
{
overflow = 1;
}
}
/* (y0 - baseline) is the top of the printed text. Character
* 93 was chosen at random, as all the baselines are essentially
* equal for each character in a font. */
if (h < y0 - bmf->baselinetab[93] + htext)
{
overflow = 1;
}
if (poverflow)
{
*poverflow = overflow;
}
sarrayDestroy(&salines);
return 0;
}
/*!
* pixSetTextline()
*
* Input: pixs (input image)
* bmf (bitmap font data)
* textstr (text string to be set on the line)
* val (color to set the text)
* x0 (left edge for first char)
* y0 (baseline location for all text on line)
* &width (<optional return> width of generated text)
* &overflow (<optional return> 0 if text is contained in
* input pix; 1 if it is clipped)
* Return: 0 if OK, 1 on error
*
* Notes:
* (1) This function paints a line of text over an image.
* (2) @val is the pixel value to be painted through the font mask.
* It should be chosen to agree with the depth of pixs.
* If it is out of bounds, an intermediate value is chosen.
* For RGB, use hex notation: 0xRRGGBB00, where RR is the
* hex representation of the red intensity, etc.
* The last two hex digits are 00 (byte value 0), assigned to
* the A component. Note that, as usual, RGBA proceeds from
* left to right in the order from MSB to LSB (see pix.h
* for details).
* (3) If there is a colormap, this does the best it can to use
* the requested color, or something similar to it.
*/
l_int32
pixSetTextline(PIX *pixs,
L_BMF *bmf,
const char *textstr,
l_uint32 val,
l_int32 x0,
l_int32 y0,
l_int32 *pwidth,
l_int32 *poverflow)
{
char chr;
l_int32 d, i, x, w, nchar, baseline, index, rval, gval, bval;
l_uint32 textcolor;
PIX *pix;
PIXCMAP *cmap;
PROCNAME("pixSetTextline");
if (!pixs)
{
return ERROR_INT("pixs not defined", procName, 1);
}
if (!bmf)
{
return ERROR_INT("bmf not defined", procName, 1);
}
if (!textstr)
{
return ERROR_INT("teststr not defined", procName, 1);
}
d = pixGetDepth(pixs);
cmap = pixGetColormap(pixs);
if (d == 1 && val > 1)
{
val = 1;
}
else if (d == 2 && val > 3 && !cmap)
{
val = 2;
}
else if (d == 4 && val > 15 && !cmap)
{
val = 8;
}
else if (d == 8 && val > 0xff && !cmap)
{
val = 128;
}
else if (d == 16 && val > 0xffff)
{
val = 0x8000;
}
else if (d == 32 && val < 256)
{
val = 0x80808000;
}
/* If cmapped, add the color if necessary to the cmap. If the
* cmap is full, use the nearest color to the requested color. */
if (cmap)
{
extractRGBValues(val, &rval, &gval, &bval);
pixcmapAddNearestColor(cmap, rval, gval, bval, &index);
pixcmapGetColor(cmap, index, &rval, &gval, &bval);
composeRGBPixel(rval, gval, bval, &textcolor);
}
else
{
textcolor = val;
}
nchar = strlen(textstr);
x = x0;
for (i = 0; i < nchar; i++)
{
chr = textstr[i];
if ((l_int32)chr == 10)
{
continue; /* NL */
}
pix = bmfGetPix(bmf, chr);
bmfGetBaseline(bmf, chr, &baseline);
pixPaintThroughMask(pixs, pix, x, y0 - baseline, textcolor);
w = pixGetWidth(pix);
x += w + bmf->kernwidth;
pixDestroy(&pix);
}
if (pwidth)
{
*pwidth = x - bmf->kernwidth - x0;
}
if (poverflow)
{
*poverflow = (x > pixGetWidth(pixs) - 1) ? 1 : 0;
}
return 0;
}
/*!
* pixaAddTextNumber()
*
* Input: pixas (input pixa; colormap ok)
* bmf (bitmap font data)
* numa (<optional> number array; use 1 ... n if null)
* val (color to set the text)
* location (L_ADD_ABOVE, L_ADD_BELOW, L_ADD_LEFT, L_ADD_RIGHT)
* Return: pixad (new pixa with rendered numbers), or null on error
*
* Notes:
* (1) Typical usage is for labelling each pix in a pixa with a number.
* (2) This function paints numbers external to each pix, in a position
* given by @location. In all cases, the pix is expanded on
* on side and the number is painted over white in the added region.
* (3) @val is the pixel value to be painted through the font mask.
* It should be chosen to agree with the depth of pixs.
* If it is out of bounds, an intermediate value is chosen.
* For RGB, use hex notation: 0xRRGGBB00, where RR is the
* hex representation of the red intensity, etc.
* (4) If na == NULL, number each pix sequentially, starting with 1.
* (5) If there is a colormap, this does the best it can to use
* the requested color, or something similar to it.
*/
PIXA *
pixaAddTextNumber(PIXA *pixas,
L_BMF *bmf,
NUMA *na,
l_uint32 val,
l_int32 location)
{
char textstr[128];
l_int32 i, n, index;
PIX *pix1, *pix2;
PIXA *pixad;
PROCNAME("pixaAddTextNumber");
if (!pixas)
{
return (PIXA *)ERROR_PTR("pixas not defined", procName, NULL);
}
if (!bmf)
{
return (PIXA *)ERROR_PTR("bmf not defined", procName, NULL);
}
if (location != L_ADD_ABOVE && location != L_ADD_BELOW &&
location != L_ADD_LEFT && location != L_ADD_RIGHT)
{
return (PIXA *)ERROR_PTR("invalid location", procName, NULL);
}
n = pixaGetCount(pixas);
pixad = pixaCreate(n);
for (i = 0; i < n; i++)
{
pix1 = pixaGetPix(pixas, i, L_CLONE);
if (na)
{
numaGetIValue(na, i, &index);
}
else
{
index = i + 1;
}
snprintf(textstr, sizeof(textstr), "%d", index);
pix2 = pixAddSingleTextline(pix1, bmf, textstr, val, location);
pixaAddPix(pixad, pix2, L_INSERT);
pixDestroy(&pix1);
}
return pixad;
}
/*!
* pixaAddTextline()
*
* Input: pixas (input pixa; colormap ok)
* bmf (bitmap font data)
* sa (<optional> sarray; use text embedded in each pix if null)
* val (color to set the text)
* location (L_ADD_ABOVE, L_ADD_BELOW, L_ADD_LEFT, L_ADD_RIGHT)
* Return: pixad (new pixa with rendered text), or null on error
*
* Notes:
* (1) This function paints a line of text external to each pix,
* in a position given by @location. In all cases, the pix is
* expanded as necessary to accommodate the text.
* (2) @val is the pixel value to be painted through the font mask.
* It should be chosen to agree with the depth of pixs.
* If it is out of bounds, an intermediate value is chosen.
* For RGB, use hex notation: 0xRRGGBB00, where RR is the
* hex representation of the red intensity, etc.
* (3) If sa == NULL, use the text embedded in each pix.
* (4) If sa has a smaller count than pixa, issue a warning
* but do not use any embedded text.
* (5) If there is a colormap, this does the best it can to use
* the requested color, or something similar to it.
*/
PIXA *
pixaAddTextline(PIXA *pixas,
L_BMF *bmf,
SARRAY *sa,
l_uint32 val,
l_int32 location)
{
char *textstr;
l_int32 i, n, nstr;
PIX *pix1, *pix2;
PIXA *pixad;
PROCNAME("pixaAddTextline");
if (!pixas)
{
return (PIXA *)ERROR_PTR("pixas not defined", procName, NULL);
}
if (!bmf)
{
return (PIXA *)ERROR_PTR("bmf not defined", procName, NULL);
}
if (location != L_ADD_ABOVE && location != L_ADD_BELOW &&
location != L_ADD_LEFT && location != L_ADD_RIGHT)
{
return (PIXA *)ERROR_PTR("invalid location", procName, NULL);
}
n = pixaGetCount(pixas);
pixad = pixaCreate(n);
nstr = (sa) ? sarrayGetCount(sa) : 0;
if (nstr > 0 && nstr < n)
{
L_WARNING("There are %d strings and %d pix\n", procName, nstr, n);
}
for (i = 0; i < n; i++)
{
pix1 = pixaGetPix(pixas, i, L_CLONE);
if (i < nstr)
{
textstr = sarrayGetString(sa, i, L_NOCOPY);
}
else
{
textstr = pixGetText(pix1);
}
pix2 = pixAddSingleTextline(pix1, bmf, textstr, val, location);
pixaAddPix(pixad, pix2, L_INSERT);
pixDestroy(&pix1);
}
return pixad;
}
/*---------------------------------------------------------------------*
* Text size estimation and partitioning *
*---------------------------------------------------------------------*/
/*!
* bmfGetLineStrings()
*
* Input: bmf
* textstr
* maxw (max width of a text line in pixels)
* firstindent (indentation of first line, in x-widths)
* &h (<return> height required to hold text bitmap)
* Return: sarray of text strings for each line, or null on error
*
* Notes:
* (1) Divides the input text string into an array of text strings,
* each of which will fit within maxw bits of width.
*/
SARRAY *
bmfGetLineStrings(L_BMF *bmf,
const char *textstr,
l_int32 maxw,
l_int32 firstindent,
l_int32 *ph)
{
char *linestr;
l_int32 i, ifirst, sumw, newsum, w, nwords, nlines, len, xwidth;
NUMA *na;
SARRAY *sa, *sawords;
PROCNAME("bmfGetLineStrings");
if (!bmf)
{
return (SARRAY *)ERROR_PTR("bmf not defined", procName, NULL);
}
if (!textstr)
{
return (SARRAY *)ERROR_PTR("teststr not defined", procName, NULL);
}
if ((sawords = sarrayCreateWordsFromString(textstr)) == NULL)
{
return (SARRAY *)ERROR_PTR("sawords not made", procName, NULL);
}
if ((na = bmfGetWordWidths(bmf, textstr, sawords)) == NULL)
{
return (SARRAY *)ERROR_PTR("na not made", procName, NULL);
}
nwords = numaGetCount(na);
if (nwords == 0)
{
return (SARRAY *)ERROR_PTR("no words in textstr", procName, NULL);
}
bmfGetWidth(bmf, 'x', &xwidth);
if ((sa = sarrayCreate(0)) == NULL)
{
return (SARRAY *)ERROR_PTR("sa not made", procName, NULL);
}
ifirst = 0;
numaGetIValue(na, 0, &w);
sumw = firstindent * xwidth + w;
for (i = 1; i < nwords; i++)
{
numaGetIValue(na, i, &w);
newsum = sumw + bmf->spacewidth + w;
if (newsum > maxw)
{
linestr = sarrayToStringRange(sawords, ifirst, i - ifirst, 2);
if (!linestr)
{
continue;
}
len = strlen(linestr);
if (len > 0) /* it should always be */
{
linestr[len - 1] = '\0'; /* remove the last space */
}
sarrayAddString(sa, linestr, 0);
ifirst = i;
sumw = w;
}
else
{
sumw += bmf->spacewidth + w;
}
}
linestr = sarrayToStringRange(sawords, ifirst, nwords - ifirst, 2);
if (linestr)
{
sarrayAddString(sa, linestr, 0);
}
nlines = sarrayGetCount(sa);
*ph = nlines * bmf->lineheight + (nlines - 1) * bmf->vertlinesep;
sarrayDestroy(&sawords);
numaDestroy(&na);
return sa;
}
/*!
* bmfGetWordWidths()
*
* Input: bmf
* textstr
* sa (of individual words)
* Return: numa (of word lengths in pixels for the font represented
* by the bmf), or null on error
*/
NUMA *
bmfGetWordWidths(L_BMF *bmf,
const char *textstr,
SARRAY *sa)
{
char *wordstr;
l_int32 i, nwords, width;
NUMA *na;
PROCNAME("bmfGetWordWidths");
if (!bmf)
{
return (NUMA *)ERROR_PTR("bmf not defined", procName, NULL);
}
if (!textstr)
{
return (NUMA *)ERROR_PTR("teststr not defined", procName, NULL);
}
if (!sa)
{
return (NUMA *)ERROR_PTR("sa not defined", procName, NULL);
}
nwords = sarrayGetCount(sa);
if ((na = numaCreate(nwords)) == NULL)
{
return (NUMA *)ERROR_PTR("na not made", procName, NULL);
}
for (i = 0; i < nwords; i++)
{
wordstr = sarrayGetString(sa, i, 0); /* not a copy */
bmfGetStringWidth(bmf, wordstr, &width);
numaAddNumber(na, width);
}
return na;
}
/*!
* bmfGetStringWidth()
*
* Input: bmf
* textstr
* &w (<return> width of text string, in pixels for the
* font represented by the bmf)
* Return: 0 if OK, 1 on error
*/
l_int32
bmfGetStringWidth(L_BMF *bmf,
const char *textstr,
l_int32 *pw)
{
char chr;
l_int32 i, w, width, nchar;
PROCNAME("bmfGetStringWidth");
if (!bmf)
{
return ERROR_INT("bmf not defined", procName, 1);
}
if (!textstr)
{
return ERROR_INT("teststr not defined", procName, 1);
}
if (!pw)
{
return ERROR_INT("&w not defined", procName, 1);
}
nchar = strlen(textstr);
w = 0;
for (i = 0; i < nchar; i++)
{
chr = textstr[i];
bmfGetWidth(bmf, chr, &width);
if (width != UNDEF)
{
w += width + bmf->kernwidth;
}
}
w -= bmf->kernwidth; /* remove last one */
*pw = w;
return 0;
}
/*---------------------------------------------------------------------*
* Text splitting *
*---------------------------------------------------------------------*/
/*!
* splitStringToParagraphs()
*
* Input: textstring
* splitting flag (see enum in bmf.h; valid values in {1,2,3})
* Return: sarray (where each string is a paragraph of the input),
* or null on error.
*/
SARRAY *
splitStringToParagraphs(char *textstr,
l_int32 splitflag)
{
char *linestr, *parastring;
l_int32 nlines, i, allwhite, leadwhite;
SARRAY *salines, *satemp, *saout;
PROCNAME("splitStringToParagraphs");
if (!textstr)
{
return (SARRAY *)ERROR_PTR("textstr not defined", procName, NULL);
}
if ((salines = sarrayCreateLinesFromString(textstr, 1)) == NULL)
{
return (SARRAY *)ERROR_PTR("salines not made", procName, NULL);
}
nlines = sarrayGetCount(salines);
saout = sarrayCreate(0);
satemp = sarrayCreate(0);
linestr = sarrayGetString(salines, 0, 0);
sarrayAddString(satemp, linestr, 1);
for (i = 1; i < nlines; i++)
{
linestr = sarrayGetString(salines, i, 0);
stringAllWhitespace(linestr, &allwhite);
stringLeadingWhitespace(linestr, &leadwhite);
if ((splitflag == SPLIT_ON_LEADING_WHITE && leadwhite) ||
(splitflag == SPLIT_ON_BLANK_LINE && allwhite) ||
(splitflag == SPLIT_ON_BOTH && (allwhite || leadwhite)))
{
parastring = sarrayToString(satemp, 1); /* add nl to each line */
sarrayAddString(saout, parastring, 0); /* insert */
sarrayDestroy(&satemp);
satemp = sarrayCreate(0);
}
sarrayAddString(satemp, linestr, 1);
}
parastring = sarrayToString(satemp, 1); /* add nl to each line */
sarrayAddString(saout, parastring, 0); /* insert */
sarrayDestroy(&satemp);
return saout;
}
/*!
* stringAllWhitespace()
*
* Input: textstring
* &val (<return> 1 if all whitespace; 0 otherwise)
* Return: 0 if OK, 1 on error
*/
static l_int32
stringAllWhitespace(char *textstr,
l_int32 *pval)
{
l_int32 len, i;
PROCNAME("stringAllWhitespace");
if (!textstr)
{
return ERROR_INT("textstr not defined", procName, 1);
}
if (!pval)
{
return ERROR_INT("&va not defined", procName, 1);
}
len = strlen(textstr);
*pval = 1;
for (i = 0; i < len; i++)
{
if (textstr[i] != ' ' && textstr[i] != '\t' && textstr[i] != '\n')
{
*pval = 0;
return 0;
}
}
return 0;
}
/*!
* stringLeadingWhitespace()
*
* Input: textstring
* &val (<return> 1 if leading char is ' ' or '\t'; 0 otherwise)
* Return: 0 if OK, 1 on error
*/
static l_int32
stringLeadingWhitespace(char *textstr,
l_int32 *pval)
{
PROCNAME("stringLeadingWhitespace");
if (!textstr)
{
return ERROR_INT("textstr not defined", procName, 1);
}
if (!pval)
{
return ERROR_INT("&va not defined", procName, 1);
}
*pval = 0;
if (textstr[0] == ' ' || textstr[0] == '\t')
{
*pval = 1;
}
return 0;
}
|
/*
* File: main.cpp
* Author: azizm
*
*
*/
//Time Complexity O(n^2)
#include <iostream>
using namespace std;
#include <bits/stdc++.h>
void Q2()
{
int maxlen = 5;
cout<<"Length of rod = ";cin>>maxlen;
int length[maxlen];
int rate[maxlen];
for(int i =0;i<maxlen;i++)
length[i]=i+1;
cout<<"Enter rate :"<<endl;
for(int i=0;i<maxlen;i++)
{
cout<<"Length = "<<i+1<<", Rate = ";cin>>rate[i];
}
int size = sizeof(length)/sizeof(length[0]);
int temp1[maxlen+1];
int temp2[maxlen+1];
temp1[0] = 0;
temp2[0] = -1;
for(int i=1;i<=maxlen;i++)
{
temp2[i] = temp2[i-1];
int max = temp1[i-1];
for(int j=0;j<size;j++)
{
int prev = i-length[j];
if(prev >= 0 && (temp1[prev] + rate[j]) > max)
{
max = temp1[prev] + rate[j];
temp2[i]= j;
}
temp1[i] = max;
}
}
cout<<"Maximum rate = "<<temp1[maxlen]<<endl;
int k = maxlen;
int instances[size];
for(int i=0;i<size;i++)
instances[i] = 0;
while(k >= 0)
{
int x = temp2[k];
if(x == -1)
break;
instances[x] += 1;
k -= length[temp2[k]];
}
cout<<"pieces = [ ";
for(int i=0;i<size;i++)
{
for(int j=0;j<instances[i];j++)
cout<<length[i]<<" ";
}
cout<<"]"<<endl;
}
int main() {
Q2();
return 0;
}
|
#include<stdio.h>
#include "statemachine.h"
#include "clusterip.h"
#include "params.h"
HA_STATES CActiveWithStandbyNoLink::Handler( HA_EVENTS p_event )
{
HA_STATES next_state = ACTIVE_WITH_STANDBY_NOLINK;
CStateMachine *cSM = CStateMachine::GetInstance();
CParams cp;
HA_EVENTS hb_event = HB_A_L;
cp = cSM->GetParameters();
if ( ! CStateMachine::GetInstance()->Promoted() ) {
if ( p_event == HB_NAK ) { // we're about to become active
next_state = ACTIVE_WITH_STANDBY_NOLINK;
return CStateMachine::GetInstance()->CurrentState( next_state );
}
CStateMachine::GetInstance()->Promoted( true );
Promote();
}
switch( p_event ) {
case HB_A_L: // this should not happen
case HB_A_NL: // this should not happen
SplitBrain();
break;
case NONE:
case PNG:
case HB_NAK: // this should not happen
case HB_S_NL:
case HB_A2S:
case HB_ACK: // this should not happen
break;
case NPNG:
next_state = ACTIVE_NOLINK_STANDBY_NOLINK;
break;
case HB_S_L:
next_state = ACTIVE_WITH_STANDBY;
break;
case MAINT:
Demote( true );
next_state = MAINTENANCE;
break;
case F_S_B: // Force Standby
hb_event = HB_A2S;
next_state = STANDBY;
break;
case NHB:
next_state = ACTIVE_NOSTANDBY;
break;
case HB_REQ:
hb_event = HB_NAK;
break;
}
HB_Sender( &cp, hb_event );
return CStateMachine::GetInstance()->CurrentState( next_state );
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.