text
stringlengths 8
6.88M
|
|---|
#include "Monster.h"
#include <algorithm>
#include "Skill.h"
#include "SoulBead.h"
#include "Fate.h"
struct CSpecialFeature
{
EnFeatures nFeature;
double dValue;
};
CMonster::CMonster() : m_nClass(EC_WOOD), m_nSpeciality(0), m_pSoulBead(nullptr), m_bIgnore(false), m_dFactor(0), m_bIsAffectAll(false), m_bIsGold(false)
{
}
CMonster::~CMonster()
{
}
void CMonster::init(CSoulBead* pSoulBead, const std::vector<CFate*>& oFateList)
{
m_pSoulBead = pSoulBead;
std::vector<CSpecialFeature> oFeatureOrder(EF_ALL);
for (int i = 0; i < EF_ALL; i++)
{
oFeatureOrder[i].dValue = m_nFeatures[i] + ((pSoulBead != nullptr) ? pSoulBead->getFeature((EnFeatures)i) : 0.0);
oFeatureOrder[i].nFeature = (EnFeatures)i;
}
std::sort(oFeatureOrder.begin(), oFeatureOrder.end(), [](CSpecialFeature& oFeature1, CSpecialFeature& oFeature2) {
return oFeature1.dValue > oFeature2.dValue + g_dEpsilon;
});
auto dVal = oFeatureOrder[0].dValue;
for each (auto oFeature in oFeatureOrder)
{
if ((dVal - oFeature.dValue) / dVal < 0.2)
m_nSpeciality |= 1 << oFeature.nFeature;
else
break;
}
for each (auto pSkill in m_oSkills)
{
m_nSpeciality |= pSkill->getAffectFeature();
auto pTemp = dynamic_cast<CProductFeatureSkill*>(pSkill);
if (pTemp)
{
if (pTemp->getClass() == EC_ALL)
{
m_bIsAffectAll = true;
}
m_dFactor += 1.0;
}
auto pTemp2 = dynamic_cast<CIncreaseFeatureSkill*>(pSkill);
if (pTemp2 )
{
if (pTemp2->getClass() == EC_ALL)
{
m_bIsAffectAll = true;
}
if (pTemp2->getValue() >= 100)
{
m_dFactor += 1.0;
}
}
}
}
double CMonster::getFeatureSum(char nFeatureSet)
{
double dResult = 0.0;
for (int i = 0; i < EF_ALL; i++)
{
if ((1 << i) & nFeatureSet)
{
dResult += m_nFeatures[i];
}
}
return dResult;
}
bool CMonster::hasSpeciality(char nSpecialitySet)
{
return (nSpecialitySet & m_nSpeciality) != 0;
}
|
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <list>
#include <random>
#include <time.h>
#include <set>
#include <map>
#include <math.h>
#include <cmath>
#include <queue>
#include <unordered_set>
#include <unordered_map>
#define mp make_pair
#define ull unsigned long long
#define ll long long
using namespace std;
struct point {
int x, y;
int operator*(point &a) {
return x*a.x + y*a.y;
}
int operator%(point &a) {
return x*a.y - y*a.x;
}
point() {}
point(int a, int b) {
x = a;
y = b;
}
int len() {
return (*this)*(*this);
}
bool operator<(point &a) {
return ((*this)%a ? (*this) % a > 0 : this->len() < a.len());
}
point operator-(point &a) {
return point(x - a.x, y - a.y);
}
};
istream& operator>>(istream &s, point &a) {
cin >> a.x >> a.y;
return s;
}
vector <point> conv_hull(vector <point> v) {
int n = v.size();
int xm = v[0].x, ym = v[0].y, im = 0;
for (int i = 1; i < n; i++) {
if (v[i].x < xm || (v[i].x == xm && v[i].y <= ym)) {
xm = v[i].x;
ym = v[i].y;
im = i;
}
}
swap(v[0], v[im]);
for (int i = n - 1; i >= 0; i--)
v[i].x -= v[0].x;
for (int i = n - 1; i >= 0; i--)
v[i].y -= v[0].y;
sort(v.begin() + 1, v.end());
v.push_back(v[0]);
vector <point> s(n + 2);
int len = 0;
s[len] = v[0];
for (int i = 1; i <= n; i++) {
while (len > 0 && ((s[len] - s[len - 1]) % (v[i] - s[len]) <= 0))
len--;
s[++len] = v[i];
}
return vector <point>(s.begin(), s.begin() + len);
}
double len(point &a, point &b) {
return sqrt(double((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y)));
}
int main() {
ios::sync_with_stdio(false);
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#else
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
int n;
cin >> n;
vector <point> v(n);
int xm = 0, ym = 0;
for (int i = 0; i < n; i++) {
cin >> v[i];
xm = min(xm, v[i].x);
ym = min(ym, v[i].y);
}
for (int i = 0; i < n; i++) {
v[i].x -= xm;
v[i].y -= ym;
}
vector <point> hull = conv_hull(v);
double p = len(hull[0], hull[hull.size() - 1]);
for (int i = 0; i < hull.size() - 1; i++)
p += len(hull[i], hull[i + 1]);
cout << p;
return 0;
}
|
#include<cstdio>
#include<algorithm>
using namespace std;
const int MARX=2147483646;
struct baka9
{
int u,v,w,ne;
}a[401000];
int head[20010];
int minn[20010];
bool f[20010];
int n,m,ans,num;
void add(int x,int y,int z)
{
a[++num].ne=head[x];
a[num].u=x;
a[num].v=y;
a[num].w=z;
head[x]=num;
}
bool prim();
int main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
add(x,y,z);
add(y,x,z);
}
if( prim() )
printf("%d",ans);
else
printf("orz");
}
bool prim()
{
for(int i=2;i<=n;i++)
minn[i]=MARX;
for(int i=head[1];i;i=a[i].ne)
minn[a[i].v]=min(minn[a[i].v],a[i].w);
for(int i=1;i<n;i++)
{
int minnn=MARX,k=-1;
for(int j=1;j<=n;j++)
if(!f[j] && minn[j]<minnn)
{
minnn=minn[j];
k=j;
}
if(k==-1) break;
f[k]=1;
for(int l=head[k];l;l=a[l].ne)
{
if(!f[a[l].v] && minn[a[l].v] > a[l].w)
minn[a[l].v]=a[l].w;
}
}
for(int i=1;i<=n;i++)
{
if(minn[i]==MARX)
return 0;
ans+=minn[i];
}
return 1;
}
|
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle == "") return 0;
int pos = 0, hlen = haystack.size(), nlen = needle.size();
for(int i = 0; i < hlen-nlen+1; ++i){
int j = 0;
for(; j < nlen; ++j){
if(haystack[i+j] != needle[j]) break;
}
if(j == nlen) return i;
}
return -1;
}
};
|
//
// nehe18.cpp
// NeheGL
//
// Created by Andong Li on 9/16/13.
// Copyright (c) 2013 Andong Li. All rights reserved.
//
#include "nehe18.h"
const char* NEHE18::TITLE = "NEHE18";
GLfloat NEHE18::sleepTime = 0.0f;
int NEHE18::frameCounter = 0;
int NEHE18::currentTime = 0;
int NEHE18::lastTime = 0;
char NEHE18::FPSstr[15] = "Calculating...";
GLuint NEHE18::texture[3] = {0,0,0};
GLuint NEHE18::filter = 0; //use first filter as default
GLfloat NEHE18::xrot = 0.0f;
GLfloat NEHE18::yrot = 0.0f;
GLfloat NEHE18::xspeed = 0.0f;
GLfloat NEHE18::yspeed = 0.0f;
GLfloat NEHE18::z = -5.0f;
int NEHE18::part1 = 0;
int NEHE18::part2 = 0;
int NEHE18::p1 = 0;
int NEHE18::p2 = 1;
GLUquadricObj* NEHE18::quadratic = NULL;
GLuint NEHE18::object = 0;
GLfloat NEHE18::LightAmbient[]= { 0.5f, 0.5f, 0.5f, 1.0f };
GLfloat NEHE18::LightDiffuse[]= { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat NEHE18::LightPosition[]= { 0.0f, 0.0f, 2.0f, 1.0f };
bool NEHE18::light = false;
bool NEHE18::lp = false;
bool NEHE18::fp = false;
bool NEHE18::sp = false;
bool NEHE18::keys[256] = {}; //all set to false
bool NEHE18::specialKeys[256] = {}; //all set to false
GLvoid NEHE18::ReSizeGLScene(GLsizei width, GLsizei height){
// Prevent A Divide By Zero By
if(height==0)
{
height=1;
}
// Reset The Current Viewport
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// Calculate The Aspect Ratio Of The Window
gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,100.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
bool NEHE18::LoadGLTextures(const char* dir){
int imageWidth, imageHeight;
//load image, using SOIL
unsigned char* image = SOIL_load_image(Utils::getAbsoluteDir(dir),&imageWidth,&imageHeight,0,0);
if(image == NULL){
return false;
}
glGenTextures(3, &texture[0]); // Create Three Textures
// Create Nearest Filtered Texture
glBindTexture(GL_TEXTURE_2D, texture[0]);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, imageWidth, imageHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
// Create Linear Filtered Texture
glBindTexture(GL_TEXTURE_2D, texture[1]);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, imageWidth, imageHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
// Create MipMapped Filtered Texture
glBindTexture(GL_TEXTURE_2D, texture[2]);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, imageWidth, imageHeight, GL_RGB, GL_UNSIGNED_BYTE, image);
//free loaded texture image
SOIL_free_image_data(image);
return true;
}
GLvoid NEHE18::InitGL(){
//give the relative directory of image under current project folder
if(!LoadGLTextures("NeheGL/img/Wall.bmp")){
cout<<"Fail to load textures"<<endl;
}
// Enable Texture Mapping
glEnable(GL_TEXTURE_2D);
// Enables Smooth Shading
glShadeModel(GL_SMOOTH);
// clear background as black
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0f);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
// want the best perspective correction to be done
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient); // Setup The Ambient Light
glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse); // Setup The Diffuse Light
glLightfv(GL_LIGHT1, GL_POSITION,LightPosition); // Position The Light
glEnable(GL_LIGHT1); // Enable Light One
quadratic=gluNewQuadric(); // Create A Pointer To The Quadric Object
gluQuadricNormals(quadratic, GLU_SMOOTH); // Create Smooth Normals
gluQuadricTexture(quadratic, GL_TRUE); // Create Texture Coords
}
GLvoid NEHE18::glDrawCube(){
glBegin(GL_QUADS);
// Front Face
glNormal3f( 0.0f, 0.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f);
// Back Face
glNormal3f( 0.0f, 0.0f,-1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
// Top Face
glNormal3f( 0.0f, 1.0f, 0.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f);
// Bottom Face
glNormal3f( 0.0f,-1.0f, 0.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
// Right face
glNormal3f( 1.0f, 0.0f, 0.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, -1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f( 1.0f, 1.0f, -1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f( 1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 1.0f);
// Left Face
glNormal3f(-1.0f, 0.0f, 0.0f);
glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0f, -1.0f, -1.0f);
glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0f, -1.0f, 1.0f);
glTexCoord2f(1.0f, 1.0f); glVertex3f(-1.0f, 1.0f, 1.0f);
glTexCoord2f(0.0f, 1.0f); glVertex3f(-1.0f, 1.0f, -1.0f);
glEnd();
}
GLvoid NEHE18::DrawGLScene(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0.0f,0.0f,z);
glRotatef(xrot,1.0f,0.0f,0.0f);
glRotatef(yrot,0.0f,1.0f,0.0f);
glBindTexture(GL_TEXTURE_2D, texture[filter]);
switch(object){
case 0:
glDrawCube();
break;
case 1:
glTranslatef(0.0f,0.0f,-1.5f);
gluCylinder(quadratic,1.0f,1.0f,3.0f,32,32);
break;
case 2:
gluDisk(quadratic,0.5f,1.5f,32,32);
break;
case 3:
gluSphere(quadratic,1.3f,32,32);
break;
case 4:
glTranslatef(0.0f,0.0f,-1.5f);
gluCylinder(quadratic,1.0f,0.0f,3.0f,32,32);
break;
case 5:
part1+=p1;
part2+=p2;
if(part1>359){
p1=0;
part1=0;
p2=1;
part2=0;
}
if(part2>359){
p1=1;
p2=0;
}
gluPartialDisk(quadratic,0.5f,1.5f,32,32,part1,part2-part1);
break;
};
//draw FPS text
glDisable(GL_TEXTURE_2D);
glDisable(GL_LIGHTING);
glLoadIdentity ();
glTranslatef(0.0f,0.0f,-1.0f);
glColor3f(0.8f,0.8f,0.8f);//set text color
computeFPS();
Utils::drawText(-0.54f,-0.4f, GLUT_BITMAP_HELVETICA_12, FPSstr);
if (light){
glEnable(GL_LIGHTING);
}
glEnable(GL_TEXTURE_2D);
glutSwapBuffers();
xrot += xspeed; // Add xspeed To xrot
yrot += yspeed; // Add yspeed To yrot
// handle key actions
if(keys['l'] && !lp){
lp=TRUE;
light=!light;
if (!light){
glDisable(GL_LIGHTING);
}
else{
glEnable(GL_LIGHTING);
}
}
if(!keys['l']){
lp=FALSE;
}
if(keys['f'] && !fp){
fp=TRUE;
filter = (filter+ 1) % 3;
}
if(!keys['f']){
fp=FALSE;
}
if (keys[' '] && !sp){
sp=TRUE;
object++;
if(object>5)
object=0;
}
if (!keys[' ']){
sp=FALSE;
}
if(specialKeys[GLUT_KEY_PAGE_UP]){
z-=0.02f;
}
if(specialKeys[GLUT_KEY_PAGE_DOWN]){
z+=0.02f;
}
if (specialKeys[GLUT_KEY_UP]){
xspeed-=0.01f;
}
if (specialKeys[GLUT_KEY_DOWN]){
xspeed+=0.01f;
}
if (specialKeys[GLUT_KEY_RIGHT]){
yspeed+=0.01f;
}
if (specialKeys[GLUT_KEY_LEFT]){
yspeed-=0.01f;
}
}
/*
This function is used to limit FPS for smooth animation
*/
GLvoid NEHE18::UpdateScene(int flag){
clock_t startTime = clock();
glutPostRedisplay();
clock_t endTime = clock();
//compute sleep time in millesecond
float sleepTime = ((CLOCKS_PER_SEC/EXPECT_FPS)-(endTime-startTime))/1000.0;
//sleepTime = floor(sleepTime+0.5);
sleepTime < 0 ? sleepTime = 0 : NULL;
glutTimerFunc(sleepTime, UpdateScene, flag);
}
GLvoid NEHE18::KeyboardFuction(unsigned char key, int x, int y){
keys[key] = true;
}
GLvoid NEHE18::KeyboardUpFuction(unsigned char key, int x, int y){
keys[key] = false;
}
GLvoid NEHE18::KeySpecialFuction(int key, int x, int y){
specialKeys[key] = true;
}
GLvoid NEHE18::KeySpecialUpFuction(int key, int x, int y){
specialKeys[key] = false;
}
void NEHE18::computeFPS(){
frameCounter++;
currentTime=glutGet(GLUT_ELAPSED_TIME);
if (currentTime - lastTime > FPS_UPDATE_CAP) {
sprintf(FPSstr,"FPS: %4.2f",frameCounter*1000.0/(currentTime-lastTime));
lastTime = currentTime;
frameCounter = 0;
}
}
|
#pragma once
//使用するヘッダー
#include "GameL\DrawTexture.h"
#include "GameL\SceneObjManager.h"
//使用するネームスペース
using namespace GameL;
//オブジェクト
class CObjHeroSword : public CObj
{
public:
CObjHeroSword(float x, float y); //コンストラクタ
~CObjHeroSword() {};
void Init(); //イニシャライズ
void Action(); //アクション
void Draw(); //ドロー
private:
float m_x; //X方向の位置用変数
float m_y; //Y方向の位置用変数
float m_vx; //X方向の速度用変数
float m_vy; //Y方向の速度用変数
float m_hero_x;
float m_hero_y;
bool m_hit; //衝突判定
float m_posture; //向き
int m_ani_frame_x; //アニメーション用変数
int m_ani_frame_y;
int m_sword_time; //剣が消える時間
int m_time;
//blockとの衝突状態確認用
bool m_hit_left;
bool m_hit_right;
};
|
// stack 的弹入弹出顺序: 边界扣得真烦
class PushPopSeq {
public:
bool IsPopOrder(vector<int> pushV, vector<int> popV) {
if (pushV.size() != popV.size()) return false;
stack<int> help;
int pushIdx = 0;
int popIdx = 0;
while (pushIdx < pushV.size() && popIdx < popV.size()) {
while (help.empty() || pushIdx < pushV.size() && help.top() != popV[popIdx])
help.push(pushV[pushIdx++]);
if (help.top() == popV[popIdx]) {
help.pop();
++popIdx;
}
}
while (popIdx < popV.size() && !help.empty()) {
if (help.top() != popV[popIdx])
return false;
else {
help.pop();
++popIdx;
}
}
return true;
}
void test() {
vector<pair<vector<int>, vector<int>>> test_cases = {
{{}, {}},
{{1}, {}},
{{1}, {2}},
{{1, 2}, {2, 1}},
{{1, 2, 3, 4, 5}, {4, 5, 3, 2, 1}},
{{1, 2, 3, 4, 5}, {4, 3, 5, 1, 2}} };
for (auto i : test_cases) {
cout << i.first << endl
<< i.second << endl
<< " ==>" << (IsPopOrder(i.first, i.second) ? "true" : "false")
<< endl;
}
}
};
|
#include <assert.h>
#include <stdlib.h>
#include "array_3d.h"
template <class T>
inline unsigned int Array3D<T>::index(unsigned int i1, unsigned int i2, unsigned int i3)
{
return this->size_i23*i1 + this->size_i3*i2 + i3;
}
template <class T>
Array3D<T>::Array3D(unsigned int size_i1, unsigned int size_i2, unsigned int size_i3)
{
this->init(size_i1, size_i2, size_i3);
}
template <class T>
void Array3D<T>::init(unsigned int size_i1, unsigned int size_i2, unsigned int size_i3)
{
this->size_i1 = size_i1;
this->size_i2 = size_i2;
this->size_i3 = size_i3;
this->size_i23 = this->size_i2*this->size_i3;
if(this->data) free(this->data);
this->data = (T *)calloc((size_t)size_i1*size_i2*size_i3, sizeof(T));
//assert (this->data != NULL);
}
template <class T>
Array3D<T>::~Array3D(void)
{
if(this->data) free(this->data);
this->data = NULL;
}
template <class T>
T Array3D<T>::get_data(unsigned int i1, unsigned int i2, unsigned int i3)
{
return this->data[this->index(i1, i2, i3)];
}
template <class T>
void Array3D<T>::set_data(unsigned int i1, unsigned int i2, unsigned int i3, T value)
{
this->data[this->index(i1, i2, i3)] = value;
}
template <class T>
void Array3D<T>::increment_data(unsigned int i1, unsigned int i2, unsigned int i3, T value)
{
this->data[this->index(i1, i2, i3)] += value;
}
template <class T>
void Array3D<T>::divide_data(unsigned int i1, unsigned int i2, unsigned int i3, T value)
{
this->data[this->index(i1, i2, i3)] /= value;
}
template class Array3D<unsigned int>;
template class Array3D<int>;
template class Array3D<long>;
template class Array3D<float>;
template class Array3D<double>;
|
// Card.cpp
#include "Card.h"
const string Card::SuitString[SUITSIZE] = { "Diamonds", "Hearts", "Clubs", "Spades" };
const string Card::ValueString[VALUESIZE] = { "2","3","4","5","6","7","8","9","10","J","Q","K","A" };
ostream& operator<<(ostream& output, const Card& c) {
output << Card::SuitString[c.suit] << " : " << Card::ValueString[c.value];
return output;
}
bool operator>(Card c1, Card c2) {
if (c1.value > c2.value)
return true;
else if (c1.value == c2.value) {
if (c1.suit > c2.suit)
return true;
}
return false;
}
bool operator<(Card c1, Card c2) {
if (c1.value < c2.value)
return true;
else if (c1.value == c2.value) {
if (c1.suit < c2.suit)
return true;
}
return false;
}
bool operator>=(Card c1, Card c2) {
bool cond = c1.value >= c2.value ? true : false;
return cond;
}
bool operator<=(Card c1, Card c2) {
bool cond = c1.value <= c2.value ? true : false;
return cond;
}
bool operator==(Card c1, Card c2) {
return (c1.value == c2.value);
}
Card::Card(int suit, int value) {
if (suit >= 0 && suit <= SUITSIZE && value >= 0 && value <= VALUESIZE) {
this->suit = (Suit)suit;
this->value = (Value)value;
} else
throw;
}
|
#include <iostream>
#include <vector>
using namespace std;
bool check(vector<int> const& v) {
for (int i = 0; i < 10; ++i) {
if (v[i] == 0)
return false;
}
return true;
}
void get_nums(int n, vector<int> &v) {
while (n > 0) {
v[n % 10]++;
n /= 10;
}
}
int main() {
int cases;
cin >> cases;
for (int i = 0; i < cases; ++i) {
int n, count = 1;
cin >> n;
if (!n) {
cout << "Case #" << i + 1 << ": INSOMNIA" << endl;
continue;
}
vector<int> frequency (10);
while (!check(frequency)) {
get_nums(n * count, frequency);
count++;
}
cout << "Case #" << i + 1 << ": " << n * (count - 1) << endl;
}
return 0;
}
|
/*
* Copyright (C) 2013 Tom Wong. All rights reserved.
*/
#ifndef __GT_OBJECT_H__
#define __GT_OBJECT_H__
#include "gtcommon.h"
#include <QtCore/qatomic.h>
GT_BEGIN_NAMESPACE
class GT_BASE_EXPORT GtObject
{
#ifdef GT_DEBUG
public:
explicit GtObject();
virtual ~GtObject();
public:
static int dumpObjects();
#endif /* !GT_DEBUG */
};
class GT_BASE_EXPORT GtSharedObject : public GtObject
{
public:
mutable QAtomicInt ref;
inline GtSharedObject() : ref(0) { }
inline GtSharedObject(const GtSharedObject &) : ref(0) { }
public:
inline void release() { if (!ref.deref()) delete this; }
private:
// using the assignment operator would lead to corruption in the ref-counting
GtSharedObject &operator=(const GtSharedObject &);
};
GT_END_NAMESPACE
#endif /* __GT_OBJECT_H__ */
|
#pragma once
#include <iostream>
#include "NodeInterface.h"
using namespace std;
struct Node : public NodeInterface {
int data;
Node* left;
Node* right;
Node(int the_data,
Node* left_value = NULL,
Node* right_value = NULL) :
data(the_data), left(left_value), right(right_value) {}
virtual ~Node();
virtual int getData();
virtual NodeInterface * getLeftChild();
virtual NodeInterface * getRightChild();
};
|
#include <assert.h>
#include <vector>
#include "BinarySearch.h"
#include "SelectionSort.h"
void testBinarySearch()
{
int testVal = 11;
std::vector<int> binarySearchTest{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 };
long algoRetVal = BinarySearch(binarySearchTest, testVal, binarySearchTest.size());
assert(algoRetVal > -1);
int algoRetValEvaluated = binarySearchTest[algoRetVal];
assert(algoRetValEvaluated == testVal);
}
void testSelectionSort()
{
std::vector<int> selectionSortTestData{ 4, 2, 84, 23, 94, 23, 7 };
selectionSortTestData.size();
SelectionSort(selectionSortTestData, selectionSortTestData.size());
for (int i = 0; i < selectionSortTestData.size() - 1; i++)
{
assert(selectionSortTestData[i] <= selectionSortTestData[i + 1]);
}
}
int main()
{
testBinarySearch();
testSelectionSort();
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include <core/pch.h>
#ifdef DOM_EXTENSIONS_CONTEXT_MENU_API_SUPPORT
#include "modules/dom/src/extensions/domextensionmenucontext_proxy.h"
#include "modules/dom/src/extensions/domextensionmenucontext.h"
#include "modules/dom/src/extensions/domextension_background.h"
#include "modules/dom/src/extensions/domextensioncontexts.h"
#include "modules/dom/src/extensions/domextensionmenuitem.h"
#include "modules/dom/src/extensions/domextensionmenuevent.h"
#include "modules/dom/src/extensions/domextensionmenuitem_proxy.h"
/* static */ OP_STATUS
DOM_ExtensionMenuContextProxy::Make(DOM_ExtensionMenuContextProxy *&new_obj, DOM_ExtensionSupport *extension_support, DOM_Runtime *origining_runtime)
{
return DOMSetObjectRuntime(new_obj = OP_NEW(DOM_ExtensionMenuContextProxy, (extension_support)), origining_runtime, origining_runtime->GetPrototype(DOM_Runtime::EXTENSION_MENUCONTEXT_PROXY_PROTOTYPE), "MenuContextProxy");
}
DOM_ExtensionMenuContextProxy::DOM_ExtensionMenuContextProxy(DOM_ExtensionSupport *extension_support)
: m_extension_support(extension_support)
{
}
DOM_ExtensionMenuContextProxy::~DOM_ExtensionMenuContextProxy()
{
class Iterator : public OpHashTableForEachListener
{
virtual void HandleKeyData(const void* key, void* data)
{
OP_ASSERT(data);
reinterpret_cast<DOM_ExtensionMenuItemProxy*>(data)->OnTopLevelContextDestroyed();
}
} iterator;
m_item_cache.ForEach(&iterator);
}
/* virtual */ ES_GetState
DOM_ExtensionMenuContextProxy::GetName(const uni_char* property_name, int property_atom, ES_Value* value, ES_Runtime* origining_runtime)
{
if (property_name[0] == 'o' && property_name[1] == 'n')
{
ES_GetState res = GetEventProperty(property_name, value, static_cast<DOM_Runtime*>(origining_runtime));
if (res != GET_FAILED)
return res;
}
return DOM_Object::GetName(property_name, property_atom, value, origining_runtime);
}
/* virtual */ ES_PutState
DOM_ExtensionMenuContextProxy::PutName(const uni_char* property_name, int property_atom, ES_Value* value, ES_Runtime* origining_runtime)
{
if (property_name[0] == 'o' && property_name[1] == 'n')
{
ES_PutState res = PutEventProperty(property_name, value, static_cast<DOM_Runtime*>(origining_runtime));
if (res != PUT_FAILED)
return res;
}
return DOM_Object::PutName(property_name, property_atom, value, origining_runtime);
}
/* virtual */ ES_GetState
DOM_ExtensionMenuContextProxy::FetchPropertiesL(ES_PropertyEnumerator *enumerator, ES_Runtime* origining_runtime)
{
ES_GetState result = DOM_Object::FetchPropertiesL(enumerator, origining_runtime);
if (result != GET_SUCCESS)
return result;
enumerator->AddPropertyL("onclick");
return GET_SUCCESS;
}
void DOM_ExtensionMenuContextProxy::GCTraceItemCacheIterator::HandleKeyData(const void* key, void* data)
{
OP_ASSERT(data);
DOM_ExtensionMenuItemProxy* item = reinterpret_cast<DOM_ExtensionMenuItemProxy*>(data);
if (item->GetIsSignificant())
runtime->GCMark(item);
}
/* virtual */ void
DOM_ExtensionMenuContextProxy::GCTrace()
{
GCTraceItemCacheIterator iterator(GetRuntime());
m_item_cache.ForEach(&iterator);
GCMark(FetchEventTarget());
}
DOM_ExtensionMenuItemProxy*
DOM_ExtensionMenuContextProxy::FindOrCreateProxyItem(UINT32 item_id, const uni_char* js_id)
{
DOM_ExtensionMenuItemProxy* proxy_item = NULL;
OP_STATUS status = m_item_cache.GetData(item_id, &proxy_item);
if (OpStatus::IsError(status))
{
OP_ASSERT(!proxy_item);
RETURN_VALUE_IF_ERROR(DOM_ExtensionMenuItemProxy::Make(proxy_item, m_extension_support, this, item_id, js_id, GetRuntime()), NULL);
OP_ASSERT(proxy_item);
status = m_item_cache.Add(item_id, proxy_item);
if (OpStatus::IsError(status))
{
// Break the connection between proxy item a container...
proxy_item->OnTopLevelContextDestroyed();
// ... and return NULL - we dont want to have items which might be inaccessible later.
return NULL;
}
}
return proxy_item;
}
void DOM_ExtensionMenuContextProxy::ProxyMenuItemDestroyed(UINT32 item_id)
{
DOM_ExtensionMenuItemProxy* unused;
OP_STATUS status = m_item_cache.Remove(item_id, &unused);
OpStatus::Ignore(status);
OP_ASSERT(OpStatus::IsSuccess(status));
}
void
DOM_ExtensionMenuContextProxy::OnMenuItemClicked(UINT32 item_id, const uni_char* item_js_id, OpDocumentContext* document_context, FramesDocument* document, HTML_Element* element)
{
DOM_EventTarget* event_target = FetchEventTarget();
OP_BOOLEAN status = OpStatus::OK;
if (event_target && event_target->HasListeners(ONCLICK, NULL, ES_PHASE_ANY)) // no point in creating proxy menu item if we know no one listens for events.
{
DOM_ExtensionMenuItemProxy* item_proxy = FindOrCreateProxyItem(item_id, item_js_id);
if (!item_proxy)
status = OpStatus::ERR_NO_MEMORY;
DOM_Event* menu_event;
OP_BOOLEAN status = DOM_ExtensionMenuEvent_UserJS::Make(menu_event, document_context, element, GetRuntime());
if (OpStatus::IsSuccess(status))
{
menu_event->InitEvent(ONCLICK, item_proxy, NULL, this);
menu_event->SetCurrentTarget(item_proxy);
menu_event->SetEventPhase(ES_PHASE_ANY);
status = GetEnvironment()->SendEvent(menu_event);
}
}
if (OpStatus::IsMemoryError(status))
g_memory_manager->RaiseCondition(status);
}
#include "modules/dom/src/domglobaldata.h"
DOM_FUNCTIONS_WITH_DATA_START(DOM_ExtensionMenuContextProxy)
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_ExtensionMenuContextProxy, DOM_Node::accessEventListener, 0, "addEventListener", "s-b-")
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_ExtensionMenuContextProxy, DOM_Node::accessEventListener, 1, "removeEventListener", "s-b-")
DOM_FUNCTIONS_WITH_DATA_END(DOM_ExtensionMenuContextProxy)
#endif // DOM_EXTENSIONS_CONTEXT_MENU_API_SUPPORT
|
#ifndef MESSAGEFIELDDESCRIPTORCONTAINER_H
#define MESSAGEFIELDDESCRIPTORCONTAINER_H
#include <QtGui/QWidget>
#include <QString>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/dynamic_message.h>
#include "FieldDescriptorContainer.h"
//Forward Declarations
template<class Object> class FieldDescriptorContainer;
class MessageFieldDescriptorContainer : public FieldDescriptorContainer<class Object>
{
private:
QWidget * m_msgParent;
std::vector<FieldDescriptorContainer<class Object> * > m_subMembers;
void parseMessage();
public:
MessageFieldDescriptorContainer(google::protobuf::FieldDescriptor * field):FieldDescriptorContainer<Object>(field)
{
parseMessage();
}
~MessageFieldDescriptorContainer()
{
delete m_field;
delete &m_value;
delete &m_defaultValue;
}
void addMember(FieldDescriptorContainer<class Object> * member, int index);
std::vector<FieldDescriptorContainer<class Object> * > getMembers();
void setParent(QWidget * parent);
virtual QWidget * getWidget(QWidget * parent = 0);
virtual QWidget * getParent();
virtual Object * getValue();
virtual void setValue(Object * value);
virtual QString toString();
virtual bool buildMsg(google::protobuf::Message * msg);
};
#endif // MESSAGEFIELDDESCRIPTORCONTAINER_H
|
#include<iostream>
#include<iomanip>
#include<string>
#include<cstring>
#include<fstream>
#include<cstdlib>
//#include"GUI.h"
using namespace std;
int input,Iseat;
char name[20] = "77";
char xname[20] = "77";
char password[20];
bool pass = false;
bool run = true;
bool seat[8][9] = {0};
int popS = 0;
int popM = 0;
int popL = 0;
int colaS = 0;
int colaM = 0;
int colaL = 0;
int cost = 0;
char format[] = "%s %s %d %d %d %d %d %d %d %d";
void asset();
void GUI(int);
void Show();
int MainMenu();
void refresh();
void login();
void ChooseSeat();
void change();
void check();
int main(){
while(run){
input = MainMenu();
GUI(input);
}
}
void ChooseSeat(){
Show();
int tempseat;
int j,i;
bool ava = true;
int count = 0;
do{
if(count>0) cout << "Please try again.\n";
cout << "Choose your seat: ";
cin >> tempseat;
j = tempseat%10;
i = tempseat/10;
if(seat[i][j]){
cout << "This seat not avalible...";
ava = false;
}
else ava = true;
count++;
}
while(i<0||i>7||j<0||j>8||!ava);
seat[i][j] = true;
if(Iseat==99) cost += 100;
Iseat = tempseat;
change();
}
void login(){
string a,b;
int seat;
cout << " ----------------------------------------------------------------- " << endl ;
cout <<"FirstName: ";
cin >> a;
cout <<"PassWord: ";
cin >> b;
ifstream source("member.txt");
string line;
while(getline(source,line)){
const char *tt = line.c_str();
const char *A = a.c_str();
const char *B = b.c_str();
sscanf(tt,format,&name,&password,&Iseat,&popS,&popM,&popL,&colaS,&colaM,&colaL,&cost);
if(!stricmp(name,A)&&!stricmp(password,B)){
pass = true;
break;
}
else strncpy(name, xname, 20);
}
if(!pass){
cout << "\nID or Password was worng... Return to main menu...\n";
}
else{
const char *A = a.c_str();
strncpy(name, A, 20);
const char *B = b.c_str();
strncpy(password, B, 20);
change();
}
}
void GUI(int x){
if(input==0){
check();
}
else if(input==1){
if(!stricmp(name,xname)) login();
else ChooseSeat();
}
else if(x == 2){ // Register
string ID_Register,Password_Register,Name;
char ag;
do{
cout << "You FirstName: ";
cin >> Name;
cout << "Your Password: ";
cin >> Password_Register;
cout << "\nFirstName: " << Name << "\nPassword: " << Password_Register << "\nDo you want to fill again? (y/n): ";
cin >> ag;
while(ag!='y'&&ag!='n'){
cout << "\nDo you want to fill again? (y/n): ";
cin >> ag;
}
}
while(ag=='y');
ofstream dest("member.txt",ios::app);
dest << "\n" << Name << " " << Password_Register << " 99 0 0 0 0 0 0 0";
dest.close();
}
else if(x == 3){
if(!stricmp(name,xname)) login();
else asset();
}
else if(x == 4){ // Exit
change();
cout << "Thank_You!!";
run = false;
}
}
int MainMenu(){
cout << " ----------------------------------------------------------------- " << endl ;
cout << " --------------------------------------- " << endl ;
cout << " Welcome To Cinderella Theater 10:00 AM 27/04/2019 " << endl ;
cout << " --------------------------------------- " << endl ;
cout << " ----------------------------------------------------------------- " << endl ;
if(stricmp(name,xname)){
cout << " Log in as " << name << " -> Spend " << cost << " " << endl ;
cout << " Check[0] Booking[1] Register[2] Food&Drnk[3] Exit[4] " << endl ;
}
else cout << " Login[1] Register[2] Food&Drnk[3] Exit[4] " << endl ;
cout << "Select : " ;
int x;
cin >> x;
if(x<0||x>4) x = MainMenu();
return x;
}
void Show(){
refresh();
cout << "\n========================= SCREEN =========================\n";
for(int i=0;i<8;i++){
cout << " ";
for(int j=0;j<9;j++){
if(seat[i][j]){
cout << "++ ";
}
else{
cout << i << j << " ";
}
}
cout << "\n";
}
cout << "****** 100 THB / Person ******\n";
}
void refresh(){
for(int i=0;i<8;i++){
for(int j=0;j<9;j++){
seat[i][j] = false;
}
}
ifstream source("member.txt");
string line;
char a[20];
char b[20];
int s;
int f[6] = {0};
int j,i;
int m = colaM;
while(getline(source,line)){
const char *tt = line.c_str();
sscanf(tt,format,&a,&b,&s,&f[0],&f[1],&f[2],&f[3],&f[4],&f[5],&cost);
j = s%10;
i = s/10;
seat[i][j] = true;
}
colaM = m;
}
void change(){
//step 1 make temp
ifstream source("member.txt");
ofstream dest("temp.txt");
string line;
while(getline(source,line)){
dest << line << "\n";
}
dest.close();
//step 2
ifstream so("temp.txt");
ofstream d("member.txt");
char a[20];
char b[20];
int s, c, f[6];
while(getline(so,line)){
const char *tt = line.c_str();
sscanf(tt,format,&a,&b,&s,&f[0],&f[1],&f[2],&f[3],&f[4],&f[5],&c);
if(!stricmp(name,a)&&!stricmp(password,b)){
d << name << " " << password << " " << Iseat << " " << popS << " " << popM << " " << popL << " " << colaS << " " << colaM << " " << colaL << " " << cost << "\n";
}
else{
d << line << "\n";
}
}
d.close();
cout << "Saved Success!!\n";
}
void asset(){
int type = 1;
do{
if(type<1||type>3) cout << " Please try again...\n";
cout << " ----------------------------------------------------------------- " << endl ;
cout << " [1]Promption [2]Food [3]Drink\n";
cout << " ----------------------------------------------------------------- " << endl ;
cin >> type;
}
while(type<1||type>3);
if(type==1){
int menu = 1;
do{
if(menu<1||menu>5) cout << " Please try again...\n";
cout << " ----------------------------------------------------------------- " << endl ;
cout << " [1][A] Popcorn size S + Cola size S [ 90 ? ] \n";
cout << " [2][B] Popcorn size M + Cola size M [ 120 ? ] \n";
cout << " [3][C] Popcorn size L + Cola size S(x2) [ 220 ? ] \n";
cout << " [4][COUPLE] Popcorn size M(x2) + Cola size S(x2) [ 200 ? ] \n";
cout << " [5][COMBO] Popcorn size M(x3) + Cola size M(x3) [ 350 ? ] \n";
cout << " ----------------------------------------------------------------- " << endl ;
cin >> menu;
}
while(menu<1||menu>5);
switch (menu)
{
case 1:
cost += 90;
popS++;
colaS++;
break;
case 2:
cost += 120;
popM++;
colaM++;
break;
case 3:
cost += 220;
popL++;
colaS += 2;
break;
case 4:
cost += 200;
popM += 2;
colaS += 2;
break;
case 5:
cost += 350;
popM += 3;
colaM += 3;
break;
}
}
else if(type==2){
int menu = 1;
do{
if(menu<1||menu>3) cout << " Please try again...\n";
cout << " ----------------------------------------------------------------- " << endl ;
cout << " [1] Popcorn size S [ 60 ? ] \n";
cout << " [2] Popcorn size M [ 80 ? ] \n";
cout << " [3] Popcorn size L [ 100 ? ] \n";
cout << " ----------------------------------------------------------------- " << endl ;
cin >> menu;
}
while(menu<1||menu>3);
switch (menu)
{
case 1:
cost += 60;
popS++;
break;
case 2:
cost += 80;
popM++;
break;
case 3:
cost += 100;
popL++;
break;
}
}
else if(type==3){
int menu = 1;
do{
if(menu<1||menu>3) cout << " Please try again...\n";
cout << " ----------------------------------------------------------------- " << endl ;
cout << " [1] Cola size S [ 30 ? ] \n";
cout << " [2] Cola size M [ 50 ? ] \n";
cout << " [3] Cola size L [ 70 ? ] \n";
cout << " ----------------------------------------------------------------- " << endl ;
cin >> menu;
}
while(menu<1||menu>3);
switch (menu)
{
case 1:
cost += 30;
colaS++;
break;
case 2:
cost += 50;
colaM++;
break;
case 3:
cost += 70;
colaL++;
break;
}
}
}
void check(){
cout << " ----------------------------------------------------------------- " << endl ;
cout << " Name: " << name << "\n" << " Seat: " << Iseat << "\n";
if(popS>0) cout << " Popcorn S: " << popS << "\n";
if(popM>0) cout << " Popcorn M: " << popM << "\n";
if(popL>0) cout << " Popcorn L: " << popL << "\n";
if(colaS>0) cout << " Cola S: " << colaS << "\n";
if(colaM>0) cout << " Cola M: " << colaM << "\n";
if(colaL>0) cout << " Cola L: " << colaL << "\n";
cout << " Cost: " << cost << "\n";
cout << " ----------------------------------------------------------------- " << endl ;
}
|
/**
* @file OpenFileDialog.h
* @brief 包含类 OpenFileDialog的定义
*/
#ifndef OPENFILEDIALOG_H
#define OPENFILEDIALOG_H
#include <qdialog.h>
#include "roammanager.h"
class QPushButton;
class QListWidget;
/**
* @class OpenFileDialog
* @brief 继承自QDialog类.
* 打开文件对话框
*/
class OpenFileDialog: public QDialog
{
Q_OBJECT
public:
OpenFileDialog (QWidget *parent = 0); ///<构造函数
signals:
void signalNotifyFileName (QString &text); ///<传送信号
public slots:
void enableButton(); ///<按钮使能函数
void openFile(); ///<打开文件
void closeDialog(); ///<关闭对话框
public:
void Initialise(std::vector<QString> &tab); ///<初始化
private:
QPushButton* confirmButton; ///<确认按钮
QPushButton* closeButton; ///<关闭按钮
QListWidget* contents; ///<指向列表部件的指针
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef OP_PLUGIN_CRASHED_BAR_H
#define OP_PLUGIN_CRASHED_BAR_H
#include "adjunct/desktop_util/crash/logsender.h"
#include "adjunct/quick/widgets/OpInfobar.h"
class OpProgressBar;
class OpLabel;
/** @brief Toolbar appearing when a plugin has crashed
* Toolbar appears when a plugin has crashed that affects the page visible in
* the window the toolbar appears in.
*/
class OpPluginCrashedBar : public OpInfobar, public LogSender::Listener
{
public:
static OP_STATUS Construct(OpPluginCrashedBar** bar) { return QuickOpWidgetBase::Construct(bar); }
OpPluginCrashedBar();
OP_STATUS Init() { return OpInfobar::Init("Plugin Crashed Toolbar"); }
OP_STATUS ShowCrash(const OpStringC& path, const OpMessageAddress& address);
// From OpInfoBar
virtual BOOL OnInputAction(OpInputAction* action);
virtual const char* GetInputContextName() { return "Plugin Crashed Toolbar"; }
virtual BOOL Hide();
// From LogSender::Listener
virtual void OnSendingStarted(LogSender* sender);
virtual void OnSendSucceeded(LogSender* sender);
virtual void OnSendFailed(LogSender* sender);
private:
OP_STATUS FindFile(time_t crash_time);
void OnSendingStarted(const OpMessageAddress& address);
void OnSendSucceeded(const OpMessageAddress& address);
void OnSendFailed(const OpMessageAddress& address);
static const time_t MaxCrashTimePassed = 2; // seconds
bool m_found_log_file;
bool m_sending_report;
bool m_sending_failed;
OpProgressBar* m_spinner;
OpLabel* m_progress_label;
OpWidget* m_send_button;
OpAutoPtr<LogSender> m_logsender;
OpMessageAddress m_address;
static OtlList<OpPluginCrashedBar*> s_visible_bars;
};
#endif // OP_PLUGIN_CRASHED_BAR_H
|
// -*- LSST-C++ -*-
/*
* LSST Data Management System
* Copyright 2009-2015 LSST Corporation.
*
* This product includes software developed by the
* LSST Project (http://www.lsst.org/).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the LSST License Statement and
* the GNU General Public License along with this program. If not,
* see <http://www.lsstcorp.org/LegalNotices/>.
*/
// SqlInsertIter.h:
// class SqlInsertIter -- A class that finds INSERT statements in
// mysqldump output and iterates over them.
//
#ifndef LSST_QSERV_RPROC_SQLINSERTITER_H
#define LSST_QSERV_RPROC_SQLINSERTITER_H
// System headers
#include <memory>
// Third-party headers
#include "boost/regex.hpp"
// Local headers
#include "util/PacketBuffer.h"
namespace lsst {
namespace qserv {
namespace rproc {
class SqlInsertIter {
public:
typedef char const* BufIter;
typedef boost::regex_iterator<BufIter> Iter;
typedef boost::match_results<BufIter> Match;
typedef boost::sub_match<BufIter> Value;
SqlInsertIter() : _allowNull(false), _lastUsed(NULL), _blockFound(false) {}
/// Constructor. Buffer must be valid over this object's lifetime.
/// Can query getFirstUnused() to see how much of buffer was used.
SqlInsertIter(char const* buf, off_t bufSize,
std::string const& tableName, bool allowNull);
/// constructor. Packetized input
SqlInsertIter(util::PacketBuffer::Ptr p,
std::string const& tableName, bool allowNull);
// Destructor
~SqlInsertIter();
// Dereference
const Value& operator*() const { return (*_iter)[0]; }
const Value* operator->() const { return &(*_iter)[0]; }
// Increment
SqlInsertIter& operator++();
// Const accessors:
bool operator==(SqlInsertIter const& rhs) const {
return _iter == rhs._iter;
}
bool isDone() const;
bool isMatch() const { return _blockFound; }
bool isNullInsert() const;
char const* getLastUsed() const { return _lastUsed; }
private:
SqlInsertIter operator++(int); // Disable: this isn't safe.
void _init(char const* buf, off_t bufSize, std::string const& tableName);
void _initRegex(std::string const& tableName);
void _resetMgrIter();
void _increment();
bool _incrementFragment();
bool _allowNull;
Iter _iter;
char const* _lastUsed; //< ptr to first unused data in buffer.
Match _blockMatch;
bool _blockFound;
class BufferMgr;
// should be scoped_ptr, but requires exposed defn of BufferMgr
std::shared_ptr<BufferMgr> _bufferMgr;
boost::regex _blockExpr;
boost::regex _insExpr;
boost::regex _nullExpr;
static Iter _nullIter;
};
}}} // namespace lsst::qserv::rproc
#endif // LSST_QSERV_RPROC_SQLINSERTITER_H
|
#pragma once
#include "../MonsterAction.h"
#include "cmp/CAct_Beam.h"
class Act_Blizzard : public MonsterAction
{
public:
Act_Blizzard();
~Act_Blizzard();
bool Action(Monster* me) override;
private:
CAct_Beam m_cBeam;
CVector3 m_efs = CVector3::One() * 3.5;
bool m_first = true;
float m_cost = 0.1f;
float m_timer = 0;
int m_cooltime = 5;
float laserRange = 100;
float m_grantAbsTime = 0.5;
float m_damage = 0.07f;
float m_DoTDamageParam = 1.f;
int m_DoTEndTime = 50;
};
|
#include "StdAfx.h"
#include "FriendListUI.h"
namespace DuiLib
{
CFriendListUI::CFriendListUI(CPaintManagerUI& paint_manager) : paint_manager_(paint_manager) , delay_deltaY_(0), delay_number_(0), delay_left_(0)
{
root_node_ = new Node;
//root_node_->data().level_ = -1;
//root_node_->data().child_visible_ = true;
//root_node_->data().has_child_ = true;
root_node_->data().list_elment_ = NULL;
}
CFriendListUI::~CFriendListUI(void)
{
RemoveAll();
if (root_node_)
delete root_node_;
root_node_ = NULL;
}
static bool OnLogoButtonEvent(void* event)
{
if( ((TEventUI*)event)->Type == UIEVENT_BUTTONDOWN )
{
CControlUI* pButton = ((TEventUI*)event)->pSender;
if( pButton != NULL )
{
CListContainerElementUI* pListElement = (CListContainerElementUI*)(pButton->GetTag());
if( pListElement != NULL ) pListElement->DoEvent(*(TEventUI*)event);
}
}
return true;
}
Node* CFriendListUI::AddNode(const FriendListItemInfo& item, Node* parent , int insertIndex)
{
if(parent == NULL)
parent = root_node_;
CListContainerElementUI* pListElement = NULL;
if( !m_dlgBuilder.GetMarkup()->IsValid() )
pListElement = static_cast<CListContainerElementUI*>(m_dlgBuilder.Create(L"friend_list.xml", (UINT)0, NULL, &paint_manager_));
else
pListElement = static_cast<CListContainerElementUI*>(m_dlgBuilder.Create((UINT)0, &paint_manager_));
if (pListElement == NULL)
return NULL;
Node* node = new Node;
node->data().list_elment_ = pListElement; //关联列表控件
node->data().folder_ = item.folder; //标记是否为根节点
node->data().text_ = item.nick_name; //保存昵称资源
node->data().type_ = item.id;
node->data().weixing_id = item.weixing_id;
node->data().logo = item.logo;
if(item.folder == false)
{
CContainerUI* logo_container = static_cast<CContainerUI*>(paint_manager_.FindSubControlByName(pListElement, L"logo_container"));
if(logo_container != NULL)
logo_container->SetVisible(true);
CButtonUI* log_button = static_cast<CButtonUI*>(paint_manager_.FindSubControlByName(pListElement, L"logo"));//找图标按钮
if(log_button != NULL)
{
if(!item.logo.IsEmpty())
{
TCHAR buf[MAX_PATH];
memset(buf,0,MAX_PATH);
wsprintf(buf,L"%s",item.logo);
log_button->SetNormalImage(buf);
//log_button->SetTag((UINT_PTR)pListElement);
//log_button->OnEvent += MakeDelegate(&OnLogoButtonEvent);
}
}
}
CLabelUI* nick_name = static_cast<CLabelUI*>(paint_manager_.FindSubControlByName(pListElement, L"nickname"));
if(nick_name != NULL)
{
TCHAR buf[MAX_PATH];
memset(buf,0,MAX_PATH);
wsprintf(buf,L"%s",item.nick_name);
nick_name->SetText(buf);
RECT rc = {0,0,0,0};
if(item.folder)
{
rc.left = 10;
rc.top = rc.right = rc.bottom = 0;
}
nick_name->SetPadding(rc);
}
pListElement->SetTag((UINT_PTR)node);
if(item.folder)
pListElement->SetFixedHeight(20);
else
pListElement->SetFixedHeight(60);
int index = 0;
if(parent->has_children())
{
Node* prev = parent->get_last_child();
index = prev->data().list_elment_->GetIndex()+1;
}
else
{
if(parent == root_node_)
index = 0;
else
index = parent->data().list_elment_->GetIndex()+1;
}
bool ret = CListUI::AddAt(pListElement, insertIndex==-1 ? index : insertIndex);
if(ret == false)
{
delete pListElement;
delete node;
node = NULL;
}
parent->add_child(node);
return node;
}
void CFriendListUI::DoEvent(TEventUI& event)
{
// if (!IsMouseEnabled() && event.Type > UIEVENT__MOUSEBEGIN && event.Type < UIEVENT__MOUSEEND)
// {
// if (m_pParent != NULL)
// m_pParent->DoEvent(event);
// else
// CVerticalLayoutUI::DoEvent(event);
// return;
// }
if( event.Type == UIEVENT_MOUSEENTER )
{
int a = 1;
}
if (event.Type == UIEVENT_TIMER && event.wParam == SCROLL_TIMERID)
{
if (delay_left_ > 0)
{
--delay_left_;
SIZE sz = GetScrollPos();
LONG lDeltaY = (LONG)(CalculateDelay((double)delay_left_ / delay_number_) * delay_deltaY_);
if ((lDeltaY > 0 && sz.cy != 0) || (lDeltaY < 0 && sz.cy != GetScrollRange().cy ))
{
sz.cy -= lDeltaY;
SetScrollPos(sz);
return;
}
}
delay_deltaY_ = 0;
delay_number_ = 0;
delay_left_ = 0;
m_pManager->KillTimer(this, SCROLL_TIMERID);
return;
}
if (event.Type == UIEVENT_SCROLLWHEEL)
{
LONG lDeltaY = 0;
if (delay_number_ > 0)
lDeltaY = (LONG)(CalculateDelay((double)delay_left_ / delay_number_) * delay_deltaY_);
switch (LOWORD(event.wParam))
{
case SB_LINEUP:
if (delay_deltaY_ >= 0)
delay_deltaY_ = lDeltaY + 7;
else
delay_deltaY_ = lDeltaY + 11;
break;
case SB_LINEDOWN:
if (delay_deltaY_ <= 0)
delay_deltaY_ = lDeltaY - 7;
else
delay_deltaY_ = lDeltaY - 11 ;
break;
}
if
(delay_deltaY_ > 100) delay_deltaY_ = 100;
else if
(delay_deltaY_ < -100) delay_deltaY_ = -100;
delay_number_ = (DWORD)sqrt((double)abs(delay_deltaY_)) * 5;
delay_left_ = delay_number_;
m_pManager->SetTimer(this, SCROLL_TIMERID, 20U);
return;
}
CListUI::DoEvent(event);
}
void CFriendListUI::RemoveAll()
{
CListUI::RemoveAll();
for (int i=0; i<root_node_->num_children(); )
{
Node* child = root_node_->child(i);
RemoveNode(child);
}
delete root_node_;
root_node_ = new Node;
//root_node_->data().level_ = -1;
//root_node_->data().child_visible_ = true;
//root_node_->data().has_child_ = true;
root_node_->data().list_elment_ = NULL;
}
bool CFriendListUI::RemoveNode(Node* node)
{
if(!node || node == root_node_)
return false;
for (int i=0; i<node->num_children(); ++i)
{
Node* child = node->child(i);
RemoveNode(child);
}
CListUI::Remove(node->data().list_elment_);
node->parent()->remove_child(node);
delete node;
node = NULL;
return true;
}
Node* CFriendListUI::GetRoot()
{
return root_node_;
}
// bool CFriendListUI::SelectItem(int iIndex, bool bTakeFocus) //列表行 根据 是否是当前选中行 显示不同的状态
// {
// if( iIndex == m_iCurSel ) return true;
//
// if (!__super::SelectItem(iIndex, bTakeFocus))
// return false;
//
// return true;
// }
}
|
//hung.nguyen@student.tut.fi - student id: 272585
//sanghun.2.lee@student.tut.fi - student id: 272571
#include <string>
#include <limits>
#include <vector>
#include <fstream>
#include <iomanip>
#include <iostream>
#include "splitter.hh"
#include "market.hh"
/*The input file is read in the constructor of the 'market' class
* in the class, there is a map of chains and a boolean value to tell
* if the input file is read successfully.
*/
market::market(){
inputRead_ = true;
ifstream inputFile("products.txt");
if(!inputFile){
cout<<"Error: the input file can not be read."<<endl;
inputRead_ = false;
}
else{
string line;
while(getline(inputFile,line)){
if(line.find(' ') != string::npos){
cout<<"Error: the input file can not be read."<<endl;
inputRead_ = false;
break;
}
vector<string> vec = split(line,';');
if(vec.size() != 4){
cout<<"Error: the input file can not be read."<<endl;
inputRead_ = false;
break;
}
double d = stod(vec.at(3));
chains1[vec.at(0)][vec.at(1)][vec.at(2)] = d;
}
inputFile.close();
}
}
/*return the boolean value: true if the input file is read successfully
*and false otherwise.
*/
bool market::inputRead() const{
return inputRead_;
}
/*print out all the chains available in the input file
*/
void market::getChains() const{
for(auto chain : chains1){
cout<<chain.first<<endl;
}
}
/*print out all the stores of the chain whose name is passed as the string
* parameter for the function
*/
void market::getChainStores(string chainName) const{
bool found = false;
for(auto chain : chains1){
if(chain.first == chainName){
found = true;
for(auto store: chain.second){
cout<<store.first<<endl;
}
}
}
if(!found) cout<<"Error: chain not found."<<endl;
}
/*print out all the chain-stores where the cheapest price of a product is found.
*The function takes the name of the product as the string parameter
*/
void market::getCheapest(string productName)const{
double cheapest = numeric_limits<double>::max();
bool foundProduct = false;
for(auto chain: chains1){
for(auto store: chain.second){
for(auto product: store.second){
if(product.first == productName){
foundProduct = true;
if(product.second < cheapest){
cheapest = product.second;
}
}
}
}
}
if(!foundProduct) cout<<"This product is not available anywhere."<<endl;
else{
cout<<fixed<<setprecision(2)<<cheapest<<endl;
for(auto chain: chains1){
for(auto store: chain.second){
for(auto product: store.second){
if(product.first == productName){
if(product.second == cheapest){
cout<<chain.first<<" "<<store.first<<endl;
}
}
}
}
}
}
}
/*print out all the products of a store of a chain. the function takes the name of the
* chain and the store as string-parameters
*/
void market::getStoreProducts(string chainName, string storeName) const{
bool foundChain = false;
bool foundStore = false;
for(auto chain : chains1){
if(chain.first==chainName){
foundChain = true;
for(auto store:chain.second){
if(store.first == storeName){
foundStore = true;
for(auto product : store.second){
cout<<product.first<<" "<<fixed<<setprecision(2)<<product.second<<endl;
}
}
}
}
}
if(!foundChain) cout<<"Error: chain not found."<<endl;
else{
if(!foundStore) cout<<"Error: store not found."<<endl;
}
}
|
#include "../include/surface_feature_extractor.h"
using namespace SurfaceFeatureExtractor;
void SurfaceFeatureExtractor::fillVertexToTriangleLookup(const std::vector<glm::ivec3> &_tris, const std::vector< TriangleData >& _triangleData, std::map<vertex_id, std::vector<triangle_id> >& _lookup)
{
for(size_t i = 0; i < _triangleData.size(); i++ )
{
if(!_triangleData[i].isHole)
{
_lookup[_tris[_triangleData[i].index].x].push_back(_triangleData[i].index);
_lookup[_tris[_triangleData[i].index].y].push_back(_triangleData[i].index);
_lookup[_tris[_triangleData[i].index].z].push_back(_triangleData[i].index);
}
}
}
//index of triangle, index of patch
std::pair<std::map<triangle_id,patch_id>, size_t> SurfaceFeatureExtractor::clusterPatches(const std::vector<glm::dvec3> &_verts, const std::vector<glm::ivec3> &_tris, const std::vector< TriangleData >& _triangleData)
{
std::map<triangle_id,patch_id> triangleToPatchLookup;
std::map<vertex_id, std::vector<triangle_id> > vertexToTriangleLookup;
fillVertexToTriangleLookup(_tris, _triangleData,vertexToTriangleLookup);
std::set<vertex_id> visitedVerts;
int number_of_patches = 0;
for(size_t i = 0; i < _verts.size(); i++)
{
//const size_t patch_index = maps[maps.size()-1].size();
int patch_index = number_of_patches-1;
const size_t key_was_found = visitedVerts.count(i);// (maps[patch_index].count(face));
if (key_was_found)
{
//do nothing
}
else if(vertexToTriangleLookup.count(i))
{
number_of_patches++;
patch_index++;
visitVertex(i,triangleToPatchLookup,visitedVerts,patch_index,vertexToTriangleLookup,_tris);
}
}
std::pair<std::map<triangle_id,patch_id>, size_t> result;
result.first = triangleToPatchLookup;
result.second = number_of_patches;
return result;
}
SurfaceFeatureExtractor::SurfaceFeature SurfaceFeatureExtractor::getSurfaceFeatureLongestLineMethodExportToPlyWithoutCgal(const std::vector<glm::dvec3> &_verts, const std::vector<glm::ivec3> &_tris, const double hole_factor, std::string _filename)
{
assert(_tris.size() > 0); //we need at least one triangle
std::vector< TriangleData > triangleData;
for(size_t i = 0; i < _tris.size(); i++)
{
const std::pair<double,double> sidelength_and_area = getLongestSideAndArea(_verts,_tris[i]);
triangleData.emplace_back(i,sidelength_and_area.first, sidelength_and_area.second,false);
}
std::sort(triangleData.begin(),triangleData.end(),[](const TriangleData& a, const TriangleData& b) -> bool {return a.longest_side < b.longest_side;});
const double holeSize = triangleData[triangleData.size()/10].longest_side * hole_factor;
for(size_t i = 0; i < triangleData.size();i++)
{
triangleData[i].isHole = triangleData[i].longest_side > holeSize;
}
std::pair<double,double> surfaceAndHoleArea = getSurfaceAndHoleArea(triangleData);
std::map<triangle_id, bool> holeLookup;
size_t number_of_holes = 0;
for(size_t i = 0; i < triangleData.size(); i++)
{
holeLookup[triangleData[i].index] = triangleData[i].isHole;
number_of_holes += triangleData[i].isHole;
}
std::pair<std::map<triangle_id,patch_id>, size_t> cluster_result = clusterPatches(_verts,_tris ,triangleData);
std::map<triangle_id,patch_id>& triangleToPatch = cluster_result.first;
size_t number_of_patches = cluster_result.second;
std::vector<double> patchSizes(number_of_patches);
for(size_t i = 0; i < patchSizes.size();i++)
{
patchSizes[i] = 0;
}
//going over all triangles, all patches
for(size_t i = 0; i < _tris.size(); i++)
{
if(!holeLookup.at(i))
{
//using herons formular
double sa = glm::length( _verts[_tris[i].x]-_verts[_tris[i].y]);
double sb = glm::length(_verts[_tris[i].x] -_verts[_tris[i].z]);
double sc = glm::length(_verts[_tris[i].y] - _verts[_tris[i].z]);
double s = sa + sb + sc;
s = s/2;
double area = std::sqrt( s * (s-sa) * (s-sb) * (s-sc));
patchSizes[triangleToPatch.at(i)] += area;
}
}
std::sort(patchSizes.begin(), patchSizes.end());
SurfaceFeature feat;
feat.surfaceArea = surfaceAndHoleArea.first;
feat.holeArea = surfaceAndHoleArea.second;
feat.surfaceToHoleRatio = feat.surfaceArea/feat.holeArea;
feat.numberOfPatches=number_of_patches;
feat.patchRatio= patchSizes.back()/patchSizes.front();
//----------------------------------------------------------
std::ofstream myfile;
myfile.open(_filename.c_str());
std::string header("ply\nformat ascii 1.0\ncomment Created by Blender 2.76 (sub 0) - www.blender.org, source file: ''\nelement vertex " + std::to_string(_verts.size()) + " \nproperty float x\nproperty float y\nproperty float z\nelement face "+ std::to_string(_tris.size()-number_of_holes) +"\nproperty list uchar uint vertex_indices\nproperty uchar red { start of vertex color }\nproperty uchar green\nproperty uchar blue\nend_header\n");
myfile << header;
for(size_t i = 0; i < _verts.size(); i++)
{
myfile << _verts[i].x << " " << _verts[i].y << " " << _verts[i].z << std::endl ;
}
std::vector<std::string> tris;
for(size_t i = 0; i < _tris.size(); i++)
{
if(!holeLookup.at(i))
{
myfile << ("3 " + std::to_string(_tris[i].x) + " " + std::to_string(_tris[i].y) + " " + std::to_string(_tris[i].z) + " " +
std::to_string((int)(triangleToPatch.at(i) < 5 ? (1+triangleToPatch.at(i))*50 : 0 )) + " " +
std::to_string( std::min((int)(triangleToPatch.at(i) >= 5 ? (triangleToPatch.at(i))*20 : 0 ),255))
+ " " + std::to_string((int)(triangleToPatch.at(i) == 0 ? 255 : 0))) << std::endl;
}
}
myfile.close();
//----------------------------------------------------------
return feat;
}
SurfaceFeatureExtractor::SurfaceFeature SurfaceFeatureExtractor::getSurfaceFeatureLongestLineMethodWithoutCgal(const std::vector<glm::dvec3> &_verts, const std::vector<glm::ivec3> &_tris, const double hole_factor)
{
assert(_tris.size() > 0); //we need at least one triangle
std::vector< TriangleData > triangleData;
for(size_t i = 0; i < _tris.size(); i++)
{
const std::pair<double,double> sidelength_and_area = getLongestSideAndArea(_verts,_tris[i]);
triangleData.emplace_back(i,sidelength_and_area.first, sidelength_and_area.second,false);
}
std::sort(triangleData.begin(),triangleData.end(),[](const TriangleData& a, const TriangleData& b) -> bool {return a.longest_side < b.longest_side;});
const double holeSize = triangleData[triangleData.size()/10].longest_side * hole_factor;
for(size_t i = 0; i < triangleData.size();i++)
{
triangleData[i].isHole = triangleData[i].longest_side > holeSize;
}
std::pair<double,double> surfaceAndHoleArea = getSurfaceAndHoleArea(triangleData);
std::map<triangle_id, bool> holeLookup;
size_t number_of_holes = 0;
for(size_t i = 0; i < triangleData.size(); i++)
{
holeLookup[triangleData[i].index] = triangleData[i].isHole;
number_of_holes += triangleData[i].isHole;
}
std::pair<std::map<triangle_id,patch_id>, size_t> cluster_result = clusterPatches(_verts,_tris ,triangleData);
std::map<triangle_id,patch_id>& triangleToPatch = cluster_result.first;
size_t number_of_patches = cluster_result.second;
std::vector<double> patchSizes(number_of_patches);
for(size_t i = 0; i < patchSizes.size();i++)
{
patchSizes[i] = 0;
}
//going over all triangles, all patches
for(size_t i = 0; i < _tris.size(); i++)
{
if(!holeLookup.at(i))
{
//using herons formular
double sa = glm::length( _verts[_tris[i].x]-_verts[_tris[i].y]);
double sb = glm::length(_verts[_tris[i].x] -_verts[_tris[i].z]);
double sc = glm::length(_verts[_tris[i].y] - _verts[_tris[i].z]);
double s = sa + sb + sc;
s = s/2;
double area = std::sqrt( s * (s-sa) * (s-sb) * (s-sc));
patchSizes[triangleToPatch.at(i)] += area;
}
}
std::sort(patchSizes.begin(), patchSizes.end());
SurfaceFeature feat;
feat.surfaceArea = surfaceAndHoleArea.first;
feat.holeArea = surfaceAndHoleArea.second;
feat.surfaceToHoleRatio = feat.surfaceArea/feat.holeArea;
feat.numberOfPatches=number_of_patches;
feat.patchRatio= patchSizes.back()/patchSizes.front();
return feat;
}
void SurfaceFeatureExtractor::visitVertex(vertex_id _vertex_id, std::map<triangle_id,patch_id>& _triangleToPatchLookup, std::set<vertex_id>& _visitedVerts, patch_id _patchid, const std::map<vertex_id, std::vector<triangle_id> >& _vertexToTriangleLookup, const std::vector<glm::ivec3> &_tris)
{
const size_t key_was_found = _visitedVerts.count(_vertex_id);
const size_t vertex_is_only_part_of_holes = _vertexToTriangleLookup.count(_vertex_id) == 0 ? 1 : 0;
if(!key_was_found && !vertex_is_only_part_of_holes)
{
_visitedVerts.insert(_vertex_id);
const std::vector<triangle_id>& connected_tris = _vertexToTriangleLookup.at(_vertex_id);
for(size_t i = 0; i < connected_tris.size(); i++)
{
_triangleToPatchLookup[connected_tris[i]] = _patchid;
const vertex_id vert1 = _tris[connected_tris[i]].x;
const vertex_id vert2 = _tris[connected_tris[i]].y;
const vertex_id vert3 = _tris[connected_tris[i]].z;
visitVertex(vert1, _triangleToPatchLookup, _visitedVerts, _patchid, _vertexToTriangleLookup, _tris);
visitVertex(vert2, _triangleToPatchLookup, _visitedVerts, _patchid, _vertexToTriangleLookup, _tris);
visitVertex(vert3, _triangleToPatchLookup, _visitedVerts, _patchid, _vertexToTriangleLookup, _tris);
}
}
}
std::pair<double,double> SurfaceFeatureExtractor::getLongestSideAndArea(const std::vector<glm::dvec3>& _verts, const glm::ivec3 &_tris)
{
glm::dvec3 p1(_verts[_tris.x]);
glm::dvec3 p2(_verts[_tris.y]);
glm::dvec3 p3(_verts[_tris.z]);
double side1 = glm::length(p2-p1);
double side2 = glm::length(p3-p1);
double side3 = glm::length(p3-p2);
glm::dvec3 p1p2 = p2-p1;
glm::dvec3 p1p3 = p3-p1;
double distance_1 = glm::length(p1p2);
double distance_2 = glm::length(p1p3);
p1p2 = glm::normalize(p1p2);
p1p3 = glm::normalize(p1p3);
double sin = glm::length(glm::cross(p1p2, p1p3));
double area = 0.5 * distance_1 * distance_2 * sin;
return std::make_pair(std::max(std::max(side1,side2),side3), area);
}
std::pair<double, double> SurfaceFeatureExtractor::getSurfaceAndHoleArea(const std::vector<SurfaceFeatureExtractor::TriangleData> &_triangleData)
{
double holeArea = 0;
double surfaceArea = 0;
for(size_t i = 0; i < _triangleData.size();i++)
{
surfaceArea += _triangleData[i].isHole == false ? _triangleData[i].area : 0;
holeArea += _triangleData[i].isHole == true ? _triangleData[i].area : 0;
}
return std::make_pair(surfaceArea,holeArea);
}
//copied code from longest side method, if this function changes, the code here must change too, including standard value of holefactor. should refactor this
void SurfaceFeatureExtractor::exportHolesAndSurface(const std::string _filename, const std::vector<glm::dvec3> &_verts, const std::vector<glm::ivec3> &_tris, const double hole_factor)
{
std::vector< TriangleData > triangleData;
for(size_t i = 0; i < _tris.size(); i++)
{
const std::pair<double,double> sidelength_and_area = getLongestSideAndArea(_verts,_tris[i]);
triangleData.emplace_back(i,sidelength_and_area.first, sidelength_and_area.second,false);
}
std::sort(triangleData.begin(),triangleData.end(),[](const TriangleData& a, const TriangleData& b) -> bool {return a.longest_side < b.longest_side;});
const double holeSize = triangleData[triangleData.size()/10].longest_side * hole_factor;
for(size_t i = 0; i < triangleData.size();i++)
{
triangleData[i].isHole = triangleData[i].longest_side > holeSize;
}
std::ofstream file_surface;
std::ofstream file_holes;
file_surface.open("surface_"+_filename);
file_holes.open("holes_"+_filename);
for(size_t b = 0; b < _verts.size(); b++)
{
file_surface << "v " << _verts[b].x << " " << _verts[b].y << " " << _verts[b].z << std::endl;
file_holes << "v " << _verts[b].x << " " << _verts[b].y << " " << _verts[b].z << std::endl;
}
for(size_t b = 0; b < _tris.size(); b++)
{
if(triangleData[b].isHole)
{
file_holes << "f " << _tris[triangleData[b].index].x+1 << " " << _tris[triangleData[b].index].y+1 << " " << _tris[triangleData[b].index].z+1 << std::endl;
}
else
{
file_surface << "f " << _tris[triangleData[b].index].x+1 << " " << _tris[triangleData[b].index].y+1 << " " << _tris[triangleData[b].index].z+1 << std::endl;
}
}
file_holes.close();
file_surface.close();
}
|
#ifndef _SHARED_H_
#define _SHARED_H_
#include <iostream>
#include "sqlite3/sqlite3.h"
#include <string.h>
#include <thread>
#ifdef _WIN32
#include <windows.h>
#include <tchar.h>
#endif
#ifdef __linux__
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#define pipename "\\\\.\\pipe\\sqlstats"
extern HANDLE hPipe;
extern DWORD dwWritten;
extern void sqliteRegisterUser(char *SQLStmnt, ...);
extern int sqliteSelectUserID(char *SQLStmnt, ...);
extern char *sqliteGetName(char *SQLStmnt, ...);
extern void sqliteUpdateStats(char *SQLStmnt, ...);
extern char *SHA1ThisPass(const unsigned char *myPass);
#endif
|
#pragma once
#include "CollidableSquare.h"
/*
Brick is a collidable square that can be destroied by the ball. Hitting it
for an amount of times, the brick will be destroied. An animation will be
applied to the brick. When number of hits is 0, a random powerup will be
generated. The brick only has a variable to signal other classes that
a powerup should be generated.
*/
class Brick : public CollidableSquare {
public:
Brick(std::string name, unsigned int width, unsigned int height, float x,
float y, int numHits, glm::vec3 color);
~Brick();
private:
int numHits;
bool getRndPw;
float scaleOffSpeed = 0.1f;
void ScaleOff(float stepTime);
public:
void Update(float gameTime) override;
void Hit();
int GetNumHits();
bool GenerateRndPw();
void Destroy(float gameTime);
};
|
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#define INT_MAX 0x7fffffff
#define INT_MIN 0x80000000
using namespace std;
struct TreeLinkNode{
int val;
TreeLinkNode *left, *right, *next;
TreeLinkNode(int x) : val(x) , left(NULL) , right(NULL) ,next(NULL){}
};
//Recursive
void connect(TreeLinkNode *root){
if(root == NULL) return;
if(root->left!=NULL){
root->left->next = root->right;
}
if(root->right!=NULL){
root->right->next = root->next==NULL?NULL:root->next->left;
}
connect(root->left);
connect(root->right);
}
//NonRecursive
void nonRecursiveConnect(TreeLinkNode *root){
if(root == NULL) return;
queue<TreeLinkNode*> myqueue;
myqueue.push(root);
while(!myqueue.empty()){
TreeLinkNode *q = myqueue.front();
myqueue.pop();
if(q->left!=NULL){
q->left->next = q->right;
myqueue.push(q->left);
}
if(q->right!=NULL){
q->right->next = q->next==NULL?NULL:q->next->left;
myqueue.push(q->right);
}
}
}
int main(){
}
|
/*
You are given with an integer k and an array of integers that contain numbers in random order. Write a program to find k
largest numbers from given array. You need to save them in an array and return it.
Time complexity should be O(nlogk) and space complexity should be not more than O(k).
Order of elements in the output is not important.
Input Format :
Line 1 : Size of array (n)
Line 2 : Array elements (separated by space)
Line 3 : Integer k
Output Format :
k largest elements
Sample Input :
13
2 12 9 16 10 5 3 20 25 11 1 8 6
4
Sample Output :
12
16
20
25
*/
#include<bits/stdc++.h>
using namespace std;
vector<int> kLargestElements(int input[],int n,int k){
priority_queue<int,vector<int>,greater<int>> pq; //Min Priority Queue.
vector<int> v;
for(int i=0;i<k;i++){
pq.push(input[i]);
}
for(int i=k;i<n;i++){
if(input[i] > pq.top()){
pq.pop();
pq.push(input[i]);
}
}
while(!pq.empty()){
v.push_back(pq.top());
pq.pop();
}
return v;
}
int main(){
int a[] = {8,5,12,10,0,15,6,19};
int k = 4;
int n = 8;
vector<int> output = kLargestElements(a,n,k);
for(int i=0;i<output.size();i++){
cout << output[i] << " ";
}
cout << endl;
return 0;
}
|
// Created on: 2002-12-10
// Created by: data exchange team
// Copyright (c) 2002-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepElement_ElementAspect_HeaderFile
#define _StepElement_ElementAspect_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <StepData_SelectType.hxx>
#include <Standard_Integer.hxx>
#include <StepElement_ElementVolume.hxx>
#include <StepElement_CurveEdge.hxx>
class Standard_Transient;
class StepData_SelectMember;
//! Representation of STEP SELECT type ElementAspect
class StepElement_ElementAspect : public StepData_SelectType
{
public:
DEFINE_STANDARD_ALLOC
//! Empty constructor
Standard_EXPORT StepElement_ElementAspect();
//! Recognizes a kind of ElementAspect select type
//! return 0
Standard_EXPORT Standard_Integer CaseNum (const Handle(Standard_Transient)& ent) const Standard_OVERRIDE;
//! Recognizes a items of select member ElementAspectMember
//! 1 -> ElementVolume
//! 2 -> Volume3dFace
//! 3 -> Volume2dFace
//! 4 -> Volume3dEdge
//! 5 -> Volume2dEdge
//! 6 -> Surface3dFace
//! 7 -> Surface2dFace
//! 8 -> Surface3dEdge
//! 9 -> Surface2dEdge
//! 10 -> CurveEdge
//! 0 else
Standard_EXPORT virtual Standard_Integer CaseMem (const Handle(StepData_SelectMember)& ent) const Standard_OVERRIDE;
//! Returns a new select member the type ElementAspectMember
Standard_EXPORT virtual Handle(StepData_SelectMember) NewMember() const Standard_OVERRIDE;
//! Set Value for ElementVolume
Standard_EXPORT void SetElementVolume (const StepElement_ElementVolume aVal);
//! Returns Value as ElementVolume (or Null if another type)
Standard_EXPORT StepElement_ElementVolume ElementVolume() const;
//! Set Value for Volume3dFace
Standard_EXPORT void SetVolume3dFace (const Standard_Integer aVal);
//! Returns Value as Volume3dFace (or Null if another type)
Standard_EXPORT Standard_Integer Volume3dFace() const;
//! Set Value for Volume2dFace
Standard_EXPORT void SetVolume2dFace (const Standard_Integer aVal);
//! Returns Value as Volume2dFace (or Null if another type)
Standard_EXPORT Standard_Integer Volume2dFace() const;
//! Set Value for Volume3dEdge
Standard_EXPORT void SetVolume3dEdge (const Standard_Integer aVal);
//! Returns Value as Volume3dEdge (or Null if another type)
Standard_EXPORT Standard_Integer Volume3dEdge() const;
//! Set Value for Volume2dEdge
Standard_EXPORT void SetVolume2dEdge (const Standard_Integer aVal);
//! Returns Value as Volume2dEdge (or Null if another type)
Standard_EXPORT Standard_Integer Volume2dEdge() const;
//! Set Value for Surface3dFace
Standard_EXPORT void SetSurface3dFace (const Standard_Integer aVal);
//! Returns Value as Surface3dFace (or Null if another type)
Standard_EXPORT Standard_Integer Surface3dFace() const;
//! Set Value for Surface2dFace
Standard_EXPORT void SetSurface2dFace (const Standard_Integer aVal);
//! Returns Value as Surface2dFace (or Null if another type)
Standard_EXPORT Standard_Integer Surface2dFace() const;
//! Set Value for Surface3dEdge
Standard_EXPORT void SetSurface3dEdge (const Standard_Integer aVal);
//! Returns Value as Surface3dEdge (or Null if another type)
Standard_EXPORT Standard_Integer Surface3dEdge() const;
//! Set Value for Surface2dEdge
Standard_EXPORT void SetSurface2dEdge (const Standard_Integer aVal);
//! Returns Value as Surface2dEdge (or Null if another type)
Standard_EXPORT Standard_Integer Surface2dEdge() const;
//! Set Value for CurveEdge
Standard_EXPORT void SetCurveEdge (const StepElement_CurveEdge aVal);
//! Returns Value as CurveEdge (or Null if another type)
Standard_EXPORT StepElement_CurveEdge CurveEdge() const;
protected:
private:
};
#endif // _StepElement_ElementAspect_HeaderFile
|
#include <stdio.h>
#include <stdlib.h>
struct kahoy
{
int item;
struct kahoy *left;
struct kahoy *right;
};
typedef struct kahoy tree;
tree *insert(tree *root,int x)
{
if(!root)
{
root=(tree*)malloc(sizeof(root));
root->item = x;
root->left = NULL;
root->right = NULL;
return(root);
}
if(root->item > x)
root->left = insert(root->left,x);
else
{
if(root->item < x)
root->right = insert(root->right,x);
}
return(root);
}
void preorder(tree *root)
{
if(root!=NULL)
{
printf("%d ",root->item);
preorder(root->left);
preorder(root->right);
}
return;
}
void inorder(tree *root)
{
if(root!=NULL)
{
preorder(root->left);
printf("%d ",root->item);
preorder(root->right);
}
return;
}
void display(tree *root)
{
printf("root is %d\n",root->item);
printf("left of root is %d\n",root->left->item);
printf("right of root is %d\n",root->right->item);
}
|
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int main(){
int n;
scanf("%d",&n);
for(int i=10000;i<100000;i++){
int a,b,c,d,e;
a=i/10000;
b=(i%10000)/1000;
c=(i%1000)/100;
d=(i%100)/10;
e=i%10;
if(a==e&&b==d&&(a+b+c+d+e==n)){
printf("%d\n",i);
}
}
for(int i=100000;i<1000000;i++){
int a,b,c,d,e,f;
f=i/100000;
a=i/10000%10;
b=(i%10000)/1000;
c=(i%1000)/100;
d=(i%100)/10;
e=i%10;
if(f==e&&a==d&&b==c&&(a+b+c+d+e+f==n)){
printf("%d\n",i);
}
}
return 0;
}
|
#include "../../idlib/precompiled.h"
#pragma hdrstop
#include "../Game_local.h"
#include "../client/ClientModel.h"
class rvMonsterGladiator : public idAI {
public:
CLASS_PROTOTYPE( rvMonsterGladiator );
rvMonsterGladiator ( void );
void InitSpawnArgsVariables( void );
void Spawn ( void );
void Save ( idSaveGame *savefile ) const;
void Restore ( idRestoreGame *savefile );
bool CanTurn ( void ) const;
virtual void GetDebugInfo ( debugInfoProc_t proc, void* userData );
virtual void Damage ( idEntity *inflictor, idEntity *attacker, const idVec3 &dir, const char *damageDefName, const float damageScale, const int location );
virtual void AddDamageEffect ( const trace_t &collision, const idVec3 &velocity, const char *damageDefName, idEntity* inflictor );
virtual bool UpdateRunStatus ( void );
virtual int FilterTactical ( int availableTactical );
virtual int GetDamageForLocation( int damage, int location );
// virtual void SetTether ( rvAITether* newTether );
protected:
// Actions
rvAIAction actionRailgunAttack;
// Blaster attack
int maxShots;
int minShots;
int shots;
int lastShotTime;
// Shield
bool usingShield;
idEntityPtr<idEntity> shield;
int shieldStartTime;
int shieldWaitTime;
int shieldHitDelay;
//int shieldInDelay;
//int shieldFov;
int shieldHealth;
int shieldConsecutiveHits;
int shieldLastHitTime;
int railgunHealth;
int railgunDestroyedTime;
int nextTurnTime;
virtual bool CheckActions ( void );
void ShowShield ( void );
void HideShield ( int hideTime=0 );
void DestroyRailgun ( void );
private:
// Global States
stateResult_t State_Killed ( const stateParms_t& parms );
// Torso states
stateResult_t State_Torso_BlasterAttack ( const stateParms_t& parms );
stateResult_t State_Torso_RailgunAttack ( const stateParms_t& parms );
stateResult_t State_Torso_ShieldStart ( const stateParms_t& parms );
stateResult_t State_Torso_ShieldEnd ( const stateParms_t& parms );
stateResult_t State_Torso_TurnRight90 ( const stateParms_t& parms );
stateResult_t State_Torso_TurnLeft90 ( const stateParms_t& parms );
stateResult_t State_Torso_ShieldFire ( const stateParms_t& parms );
rvScriptFuncUtility mPostWeaponDestroyed; // script to run after railgun is destroyed
CLASS_STATES_PROTOTYPE ( rvMonsterGladiator );
};
CLASS_DECLARATION( idAI, rvMonsterGladiator )
END_CLASS
/*
================
rvMonsterGladiator::rvMonsterGladiator
================
*/
rvMonsterGladiator::rvMonsterGladiator ( ) {
usingShield = false;
}
void rvMonsterGladiator::InitSpawnArgsVariables ( void )
{
maxShots = spawnArgs.GetInt ( "maxShots", "1" );
minShots = spawnArgs.GetInt ( "minShots", "1" );
shieldHitDelay = SEC2MS ( spawnArgs.GetFloat ( "shieldHitDelay", "1" ) );
// shieldInDelay = SEC2MS ( spawnArgs.GetFloat ( "shieldInDelay", "3" ) );
// shieldFov = spawnArgs.GetInt ( "shieldfov", "90" );
}
/*
================
rvMonsterGladiator::Spawn
================
*/
void rvMonsterGladiator::Spawn ( void ) {
shieldWaitTime = 0;
shieldStartTime = 0;
shieldHealth = 250;
shieldConsecutiveHits = 0;
shieldLastHitTime = 0;
InitSpawnArgsVariables();
shots = 0;
lastShotTime = 0;
railgunHealth = spawnArgs.GetInt ( "railgunHealth", "100" );
railgunDestroyedTime = 0;
actionRailgunAttack.Init ( spawnArgs, "action_railgunAttack", "Torso_RailgunAttack", AIACTIONF_ATTACK );
// Disable range attack until using shield
//actionRangedAttack.fl.disabled = true;
const char *func;
if ( spawnArgs.GetString( "script_postWeaponDestroyed", "", &func ) )
{
mPostWeaponDestroyed.Init( func );
}
}
/*
================
rvMonsterGladiator::CheckActions
Overriden to handle taking the shield out and putting it away. Will also ensure the gladiator
stays hidden behind his shield if getting shot at.
================
*/
bool rvMonsterGladiator::CheckActions ( void ) {
// If not moving, try turning in place
if ( !move.fl.moving && gameLocal.time > nextTurnTime ) {
float turnYaw = idMath::AngleNormalize180 ( move.ideal_yaw - move.current_yaw ) ;
if ( turnYaw > lookMax[YAW] * 0.75f || (turnYaw > 0 && !enemy.fl.inFov) ) {
PerformAction ( "Torso_TurnRight90", 4, true );
return true;
} else if ( turnYaw < -lookMax[YAW] * 0.75f || (turnYaw < 0 && !enemy.fl.inFov) ) {
PerformAction ( "Torso_TurnLeft90", 4, true );
return true;
}
}
if ( CheckPainActions ( ) ) {
return true;
}
// Limited actions with shield out
if ( usingShield ) {
if ( railgunHealth > 0 && PerformAction ( &actionRailgunAttack, (checkAction_t)&idAI::CheckAction_RangedAttack, &actionTimerSpecialAttack ) ) {
return true;
}
if ( move.moveCommand == MOVE_TO_ENEMY
&& move.fl.moving )
{//advancing on enemy with shield up
if ( gameLocal.GetTime() - lastShotTime > 1500 )
{//been at least a second since the last time we fired while moving
if ( !gameLocal.random.RandomInt(2) )
{//fire!
PerformAction ( "Torso_ShieldFire", 0, true );
return true;
}
}
}
// Only ranged attack and melee attack are available when using shield
if ( PerformAction ( &actionMeleeAttack, (checkAction_t)&idAI::CheckAction_MeleeAttack ) ||
PerformAction ( &actionRangedAttack, (checkAction_t)&idAI::CheckAction_RangedAttack, &actionTimerRangedAttack ) ||
( railgunHealth > 0
&& gameLocal.GetTime() - shieldStartTime > 2000
&& gameLocal.time - pain.lastTakenTime > 500
&& gameLocal.time - combat.shotAtTime > 300
&& gameLocal.GetTime() - shieldLastHitTime > 500
&& PerformAction ( &actionRailgunAttack, (checkAction_t)&idAI::CheckAction_RangedAttack, &actionTimerSpecialAttack ) ) ) {
shieldWaitTime = 0;
return true;
}
// see if it's safe to lower it?
if ( gameLocal.GetTime() - shieldStartTime > 2000 )
{//shield's been up for at least 2 seconds
if ( !enemy.fl.visible || (gameLocal.time - combat.shotAtTime > 1000 && gameLocal.GetTime() - shieldLastHitTime > 1500) )
{
if ( gameLocal.time - pain.lastTakenTime > 1500 )
{
PerformAction ( "Torso_ShieldEnd", 4, true );
return true;
}
}
}
return false;
}
else
{// Bring the shield out?
if ( combat.tacticalCurrent != AITACTICAL_MELEE || move.fl.done )
{//not while rushing (NOTE: unless railgun was just destroyed?)
if ( enemy.fl.visible && enemy.fl.inFov )
{
if ( combat.fl.aware && shieldWaitTime < gameLocal.GetTime() )
{
if ( gameLocal.time - pain.lastTakenTime <= 1500
|| ( combat.shotAtAngle < 0 && gameLocal.time - combat.shotAtTime < 100 )
|| !gameLocal.random.RandomInt( 20 ) )
{
if ( !gameLocal.random.RandomInt( 5 ) )
{
PerformAction ( "Torso_ShieldStart", 4, true );
return true;
}
}
}
}
}
if ( railgunHealth > 0 && PerformAction ( &actionRailgunAttack, (checkAction_t)&idAI::CheckAction_RangedAttack, &actionTimerSpecialAttack ) ) {
return true;
}
}
return idAI::CheckActions ( );
}
/*
================
rvMonsterGladiator::ShowShield
================
*/
void rvMonsterGladiator::ShowShield ( void ) {
// First time?
if ( !shield ) {
idEntity* ent;
idDict args;
const idDict *shieldDef = gameLocal.FindEntityDefDict( spawnArgs.GetString ( "def_shield" ), false );
args.Set ( "classname", spawnArgs.GetString ( "def_shield" ) );
if ( gameLocal.SpawnEntityDef( args, &ent ) ) {
shield = ent;
ent->GetPhysics()->SetClipMask ( 0 );
ent->GetPhysics()->SetContents ( CONTENTS_RENDERMODEL );
ent->GetPhysics()->GetClipModel ( )->SetOwner ( this );
Attach ( ent );
}
if ( !shield ) {
return;
}
if ( shieldDef && shield->IsType( idAFAttachment::GetClassType() ) )
{
idAFAttachment* afShield = static_cast<idAFAttachment*>(shield.GetEntity());
if ( afShield )
{
jointHandle_t joint = animator.GetJointHandle( shieldDef->GetString( "joint" ) );
afShield->SetBody ( this, shieldDef->GetString( "model" ), joint );
}
}
} else if ( !shield || !shield->IsHidden() ) {
return;
}
usingShield = true;
shieldWaitTime = 0;
animPrefix = "shield";
shieldStartTime = gameLocal.time;
// actionRangedAttack.fl.disabled = false;
shieldHealth = 250;
shieldConsecutiveHits = 0;
shieldLastHitTime = 0;
shield->SetShaderParm( SHADERPARM_MODE, 0 );
// Looping shield sound
StartSound ( "snd_shield_loop", SND_CHANNEL_ITEM, 0, false, NULL );
shield->Show ( );
SetShaderParm ( 6, gameLocal.time + 2000 );
}
/*
================
rvMonsterGladiator::HideShield
================
*/
void rvMonsterGladiator::HideShield ( int hideTime ) {
if ( !shield || shield->IsHidden() ) {
return;
}
usingShield = false;
animPrefix = "";
shieldWaitTime = gameLocal.GetTime()+hideTime;
// actionRangedAttack.fl.disabled = true;
shieldHealth = 0;
shieldConsecutiveHits = 0;
shieldLastHitTime = 0;
shield->SetShaderParm( SHADERPARM_MODE, 0 );
// Looping shield sound
StopSound ( SND_CHANNEL_ITEM, false );
shield->Hide ( );
}
/*
================
rvMonsterGladiator::DestroyRailgun
================
*/
void rvMonsterGladiator::DestroyRailgun ( void ) {
HideSurface ( "models/monsters/gladiator/glad_railgun" );
railgunHealth = -1;
idVec3 origin;
idMat3 axis;
jointHandle_t joint;
joint = animator.GetJointHandle ( spawnArgs.GetString ( "joint_railgun_explode", "gun_main_jt" ) );
GetJointWorldTransform ( joint, gameLocal.time, origin, axis );
gameLocal.PlayEffect ( spawnArgs, "fx_railgun_explode", origin, axis );
PlayEffect ( "fx_railgun_burn", joint, true );
GetAFPhysics()->GetBody ( "b_railgun" )->SetClipMask ( 0 );
pain.takenThisFrame = pain.threshold;
pain.lastTakenTime = gameLocal.time;
DisableAnimState( ANIMCHANNEL_LEGS );
painAnim = "pain_big";
SetAnimState( ANIMCHANNEL_TORSO, "Torso_Pain" );
PostAnimState( ANIMCHANNEL_TORSO, "Torso_Idle" );
railgunDestroyedTime = gameLocal.GetTime();
// Tweak-out the AI to be more aggressive and more likely to charge?
actionRailgunAttack.fl.disabled = true;
combat.attackRange[1] = 200;
combat.aggressiveRange = 400;
spawnArgs.SetFloat( "action_meleeAttack_rate", 0.3f );
actionMeleeAttack.Init( spawnArgs, "action_meleeAttack", NULL, AIACTIONF_ATTACK );
actionMeleeAttack.failRate = 200;
actionMeleeAttack.chance = 1.0f;
actionRangedAttack.chance = 0.25f;
actionRangedAttack.maxRange = 400;
minShots = 5;
maxShots = 15;
combat.tacticalMaskAvailable &= ~AITACTICAL_HIDE_BIT;
//temporarily disable this so we can charge and get mad
//FIXME: force MELEE
actionRangedAttack.timer.Add( 6000 );
actionTimerRangedAttack.Add( 6000 );
actionMeleeAttack.timer.Reset( actionTime );
//drop any tether since we need to advance
//SetTether(NULL);
//nevermind: let scripters handle it
ExecScriptFunction( mPostWeaponDestroyed );
}
/*
================
rvMonsterGladiator::UpdateRunStatus
================
*/
bool rvMonsterGladiator::UpdateRunStatus ( void ) {
// If rushing and moving forward, run
if ( combat.tacticalCurrent == AITACTICAL_MELEE && move.currentDirection == MOVEDIR_FORWARD ) {
move.fl.idealRunning = true;
return move.fl.running != move.fl.idealRunning;
}
// Alwasy walk with shield out
if ( usingShield ) {
move.fl.idealRunning = false;
return move.fl.running != move.fl.idealRunning;
}
return idAI::UpdateRunStatus ( );
}
/*
============
rvMonsterGladiator::SetTether
============
*/
/*
void rvMonsterGladiator::SetTether ( rvAITether* newTether ) {
if ( railgunHealth <= 0 ) {
//don't allow any tethers!
idAI::SetTether(NULL);
} else {
idAI::SetTether(newTether);
}
}
*/
/*
================
rvMonsterGladiator::FilterTactical
================
*/
int rvMonsterGladiator::FilterTactical ( int availableTactical ) {
if ( railgunHealth > 0 ) { // Only let the gladiator rush when he is really close to his enemy
if ( !enemy.range || enemy.range > combat.awareRange ) {
availableTactical &= ~AITACTICAL_MELEE_BIT;
} else {
availableTactical &= ~(AITACTICAL_RANGED_BITS);
}
} else if ( gameLocal.GetTime() - railgunDestroyedTime < 6000 ) {
availableTactical = AITACTICAL_MELEE_BIT;
}
return idAI::FilterTactical ( availableTactical );
}
/*
================
rvMonsterGladiator::AddDamageEffect
================
*/
void rvMonsterGladiator::AddDamageEffect( const trace_t &collision, const idVec3 &velocity, const char *damageDefName, idEntity* inflictor ) {
if ( collision.c.material != NULL && (collision.c.material->GetSurfaceFlags() & SURF_NODAMAGE ) ) {
// Delay putting shield away and shooting until the shield hasnt been hit for a while
actionRangedAttack.timer.Reset ( actionTime );
actionRangedAttack.timer.Add ( shieldHitDelay );
shieldStartTime = gameLocal.time;
return;
}
return idAI::AddDamageEffect ( collision, velocity, damageDefName, inflictor );
}
/*
=====================
rvMonsterGladiator::GetDamageForLocation
=====================
*/
int rvMonsterGladiator::GetDamageForLocation( int damage, int location ) {
// If the gun was hit only do damage to it
if ( idStr::Icmp ( GetDamageGroup ( location ), "gun" ) == 0 ) {
// pain.takenThisFrame = damage;
if ( railgunHealth > 0 ){
railgunHealth -= damage;
if ( railgunHealth <= 0 ) {
DestroyRailgun ( );
}
}
return 0;
}
return idAI::GetDamageForLocation ( damage, location );
}
/*
================
rvMonsterGladiator::CanTurn
================
*/
bool rvMonsterGladiator::CanTurn ( void ) const {
if ( !idAI::CanTurn ( ) ) {
return false;
}
return move.anim_turn_angles != 0.0f || move.fl.moving;
}
/*
================
rvMonsterGladiator::Damage
================
*/
void rvMonsterGladiator::Damage( idEntity *inflictor, idEntity *attacker, const idVec3 &dir,
const char *damageDefName, const float damageScale, const int location )
{
if (gameLocal.isClient && gameLocal.mpGame.IsGametypeCoopBased()) { //Disallow clientside damage in coop by now.
return;
}
const idDict *damageDef = gameLocal.FindEntityDefDict( damageDefName, false );
if ( damageDef )
{
if ( usingShield )
{//shield up
if ( !damageDef->GetString( "filter_electricity", NULL ) )
{//not by electricity
//If we get hit enough times with shield up, charge forward
if ( gameLocal.GetTime() - shieldLastHitTime > 1500 )
{
shieldConsecutiveHits = 0;
}
shieldConsecutiveHits++;
shieldLastHitTime = gameLocal.GetTime();
if ( shieldConsecutiveHits > 20 && combat.tacticalCurrent != AITACTICAL_MELEE && move.fl.done )
{//really laying into us, move up
combat.tacticalUpdateTime = gameLocal.GetTime();
MoveToEnemy();
//reset counter
shieldConsecutiveHits = 0;
}
}
if ( idStr::Icmp ( GetDamageGroup ( location ), "shield" ) == 0 )
{//Hit in shield
if ( damageDef->GetString( "filter_electricity", NULL ) )
{//by electricity
shieldHealth -= damageDef->GetInt( "damage" ) * damageScale;
if ( shield )
{
shield->SetShaderParm( SHADERPARM_MODE, gameLocal.GetTime() + gameLocal.random.RandomInt(1000) + 1000 );
}
StartSound( "snd_shield_flicker", SND_CHANNEL_ANY, 0, false, NULL );
if ( shieldHealth <= 0 )
{//drop it
HideShield( gameLocal.random.RandomInt(3000)+2000 );//FIXME: when it does come back on, flicker back on?
painAnim = "pain_con";
AnimTurn( 0, true );
PerformAction ( "Torso_Pain", 2, true );
}
combat.shotAtTime = gameLocal.GetTime();
}
return;
}
}
}
idAI::Damage( inflictor, attacker, dir, damageDefName, damageScale, location );
if ( aifl.pain )
{//hurt
if ( usingShield )
{//shield up
//move in!
combat.tacticalUpdateTime = gameLocal.GetTime();
MoveToEnemy();
//reset counter
shieldConsecutiveHits = 0;
}
}
}
/*
================
rvMonsterGladiator::Save
================
*/
void rvMonsterGladiator::Save( idSaveGame *savefile ) const {
actionRailgunAttack.Save ( savefile ) ;
savefile->WriteInt ( shots );
savefile->WriteInt ( lastShotTime );
savefile->WriteBool ( usingShield );
shield.Save( savefile );
savefile->WriteInt ( shieldStartTime );
savefile->WriteInt ( shieldWaitTime );
savefile->WriteInt ( shieldHealth );
savefile->WriteInt ( shieldConsecutiveHits );
savefile->WriteInt ( shieldLastHitTime );
savefile->WriteInt ( railgunHealth );
savefile->WriteInt ( railgunDestroyedTime );
savefile->WriteInt ( nextTurnTime ); // cnicholson: added unsaved var
mPostWeaponDestroyed.Save( savefile );
}
/*
================
rvMonsterGladiator::Restore
================
*/
void rvMonsterGladiator::Restore( idRestoreGame *savefile ) {
actionRailgunAttack.Restore ( savefile ) ;
savefile->ReadInt ( shots );
savefile->ReadInt ( lastShotTime );
savefile->ReadBool ( usingShield );
shield.Restore( savefile );
savefile->ReadInt ( shieldStartTime );
savefile->ReadInt ( shieldWaitTime );
savefile->ReadInt ( shieldHealth );
savefile->ReadInt ( shieldConsecutiveHits );
savefile->ReadInt ( shieldLastHitTime );
savefile->ReadInt ( railgunHealth );
savefile->ReadInt ( railgunDestroyedTime );
savefile->ReadInt ( nextTurnTime ); // cnicholson: added unsaved var
mPostWeaponDestroyed.Restore( savefile );
InitSpawnArgsVariables();
}
/*
================
rvMonsterGladiator::GetDebugInfo
================
*/
void rvMonsterGladiator::GetDebugInfo( debugInfoProc_t proc, void* userData ) {
// Base class first
idAI::GetDebugInfo ( proc, userData );
proc ( "idAI", "action_RailgunAttack", aiActionStatusString[actionRailgunAttack.status], userData );
}
/*
===============================================================================
States
===============================================================================
*/
CLASS_STATES_DECLARATION ( rvMonsterGladiator )
STATE ( "State_Killed", rvMonsterGladiator::State_Killed )
STATE ( "Torso_BlasterAttack", rvMonsterGladiator::State_Torso_BlasterAttack )
STATE ( "Torso_RailgunAttack", rvMonsterGladiator::State_Torso_RailgunAttack )
STATE ( "Torso_ShieldStart", rvMonsterGladiator::State_Torso_ShieldStart )
STATE ( "Torso_ShieldEnd", rvMonsterGladiator::State_Torso_ShieldEnd )
STATE ( "Torso_TurnRight90", rvMonsterGladiator::State_Torso_TurnRight90 )
STATE ( "Torso_TurnLeft90", rvMonsterGladiator::State_Torso_TurnLeft90 )
STATE ( "Torso_ShieldFire", rvMonsterGladiator::State_Torso_ShieldFire )
END_CLASS_STATES
/*
================
rvMonsterGladiator::State_Killed
================
*/
stateResult_t rvMonsterGladiator::State_Killed ( const stateParms_t& parms ) {
HideShield ( );
return idAI::State_Killed ( parms );
}
/*
================
rvMonsterGladiator::State_Torso_ShieldStart
================
*/
stateResult_t rvMonsterGladiator::State_Torso_ShieldStart ( const stateParms_t& parms ) {
enum {
STAGE_INIT,
STAGE_WAIT
};
switch ( parms.stage ) {
case STAGE_INIT:
DisableAnimState ( ANIMCHANNEL_LEGS );
ShowShield ( );
PlayAnim ( ANIMCHANNEL_TORSO, "start", parms.blendFrames );
return SRESULT_STAGE ( STAGE_WAIT );
case STAGE_WAIT:
if ( AnimDone ( ANIMCHANNEL_TORSO, 0 )
|| animator.CurrentAnim( ANIMCHANNEL_TORSO )->GetEndTime() < 0//anim somehow cycled?!!
|| idStr::Icmp( animator.CurrentAnim( ANIMCHANNEL_TORSO )->AnimName(), "shield_end" ) ) {//anim changed
SetShaderParm ( 6, 0 );
PostAnimState ( ANIMCHANNEL_TORSO, "Torso_Idle", 0 );
PostAnimState ( ANIMCHANNEL_LEGS, "Legs_Idle", 0 );
return SRESULT_DONE;
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
/*
================
rvMonsterGladiator::State_Torso_ShieldEnd
================
*/
stateResult_t rvMonsterGladiator::State_Torso_ShieldEnd ( const stateParms_t& parms ) {
enum {
STAGE_INIT,
STAGE_WAIT
};
switch ( parms.stage ) {
case STAGE_INIT:
DisableAnimState ( ANIMCHANNEL_LEGS );
PlayAnim ( ANIMCHANNEL_TORSO, "end", parms.blendFrames );
return SRESULT_STAGE ( STAGE_WAIT );
case STAGE_WAIT:
if ( AnimDone ( ANIMCHANNEL_TORSO, 2 ) //anim done
|| animator.CurrentAnim( ANIMCHANNEL_TORSO )->GetEndTime() < 0//anim somehow cycled?!!!
|| idStr::Icmp( animator.CurrentAnim( ANIMCHANNEL_TORSO )->AnimName(), "shield_end" ) ) {//anim changed
HideShield ( 2000 );
actionRailgunAttack.timer.Reset( actionTime );
actionMeleeAttack.timer.Reset( actionTime );
actionRangedAttack.timer.Reset( actionTime );
actionTimerRangedAttack.Reset( actionTime );
PostAnimState ( ANIMCHANNEL_TORSO, "Torso_Idle", 2 );
return SRESULT_DONE;
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
/*
================
rvMonsterGladiator::State_Torso_BlasterAttack
================
*/
stateResult_t rvMonsterGladiator::State_Torso_BlasterAttack ( const stateParms_t& parms ) {
enum {
STAGE_INIT,
STAGE_WAITSTART,
STAGE_LOOP,
STAGE_WAITLOOP,
STAGE_WAITEND
};
switch ( parms.stage ) {
case STAGE_INIT:
DisableAnimState ( ANIMCHANNEL_LEGS );
PlayAnim ( ANIMCHANNEL_TORSO, "blaster_start", parms.blendFrames );
//shots = 4;
shots = (minShots + gameLocal.random.RandomInt(maxShots-minShots+1)) * combat.aggressiveScale;
return SRESULT_STAGE ( STAGE_WAITSTART );
case STAGE_WAITSTART:
if ( AnimDone ( ANIMCHANNEL_TORSO, 0 )
|| animator.CurrentAnim( ANIMCHANNEL_TORSO )->GetEndTime() < 0//anim somehow cycled?!!!
|| idStr::Icmp( animator.CurrentAnim( ANIMCHANNEL_TORSO )->AnimName(), "blaster_start" ) ) {//anim changed
return SRESULT_STAGE ( STAGE_LOOP );
}
return SRESULT_WAIT;
case STAGE_LOOP:
PlayAnim ( ANIMCHANNEL_TORSO, "blaster_loop", 0 );
return SRESULT_STAGE ( STAGE_WAITLOOP );
case STAGE_WAITLOOP:
if ( AnimDone ( ANIMCHANNEL_TORSO, 0 )
|| animator.CurrentAnim( ANIMCHANNEL_TORSO )->GetEndTime() < 0//anim somehow cycled?!!!
|| idStr::Icmp( animator.CurrentAnim( ANIMCHANNEL_TORSO )->AnimName(), "blaster_loop" ) ) {//anim changed
if ( --shots <= 0 || !enemy.fl.inFov || aifl.damage ) {
PlayAnim ( ANIMCHANNEL_TORSO, "blaster_end", 0 );
return SRESULT_STAGE ( STAGE_WAITEND );
}
return SRESULT_STAGE ( STAGE_LOOP );
}
return SRESULT_WAIT;
case STAGE_WAITEND:
if ( AnimDone ( ANIMCHANNEL_TORSO, 4 )
|| animator.CurrentAnim( ANIMCHANNEL_TORSO )->GetEndTime() < 0//anim somehow cycled?!!!
|| idStr::Icmp( animator.CurrentAnim( ANIMCHANNEL_TORSO )->AnimName(), "blaster_loop" ) ) {//anim changed
return SRESULT_DONE;
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
/*
================
rvMonsterGladiator::State_Torso_RailgunAttack
================
*/
stateResult_t rvMonsterGladiator::State_Torso_RailgunAttack ( const stateParms_t& parms ) {
enum {
STAGE_INIT,
STAGE_WAIT
};
switch ( parms.stage ) {
case STAGE_INIT:
if ( usingShield ) {
PostAnimState ( ANIMCHANNEL_TORSO, "Torso_ShieldEnd", parms.blendFrames );
PostAnimState ( ANIMCHANNEL_TORSO, "Torso_RailgunAttack", parms.blendFrames );
return SRESULT_DONE;
}
DisableAnimState ( ANIMCHANNEL_LEGS );
PlayAnim ( ANIMCHANNEL_TORSO, "railgun_attack", parms.blendFrames );
return SRESULT_STAGE ( STAGE_WAIT );
case STAGE_WAIT:
if ( AnimDone ( ANIMCHANNEL_TORSO, parms.blendFrames )
|| animator.CurrentAnim( ANIMCHANNEL_TORSO )->GetEndTime() < 0//anim somehow cycled?!!!
|| idStr::Icmp( animator.CurrentAnim( ANIMCHANNEL_TORSO )->AnimName(), "railgun_attack" ) ) {//anim changed
return SRESULT_DONE;
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
/*
================
rvMonsterGladiator::State_Torso_TurnRight90
================
*/
stateResult_t rvMonsterGladiator::State_Torso_TurnRight90 ( const stateParms_t& parms ) {
enum {
STAGE_INIT,
STAGE_WAIT
};
switch ( parms.stage ) {
case STAGE_INIT:
DisableAnimState ( ANIMCHANNEL_LEGS );
PlayAnim ( ANIMCHANNEL_TORSO, "turn_right", parms.blendFrames );
AnimTurn ( 90.0f, true );
return SRESULT_STAGE ( STAGE_WAIT );
case STAGE_WAIT:
if ( move.fl.moving
|| AnimDone ( ANIMCHANNEL_TORSO, 0 )
|| animator.CurrentAnim( ANIMCHANNEL_TORSO )->GetEndTime() < 0//anim somehow cycled?!!!
|| idStr::Icmp( animator.CurrentAnim( ANIMCHANNEL_TORSO )->AnimName(), "turn_right" ) ) {//anim changed
AnimTurn ( 0, true );
nextTurnTime = gameLocal.time + 250;
return SRESULT_DONE;
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
/*
================
rvMonsterGladiator::State_Torso_TurnLeft90
================
*/
stateResult_t rvMonsterGladiator::State_Torso_TurnLeft90 ( const stateParms_t& parms ) {
enum {
STAGE_INIT,
STAGE_WAIT
};
switch ( parms.stage ) {
case STAGE_INIT:
DisableAnimState ( ANIMCHANNEL_LEGS );
PlayAnim ( ANIMCHANNEL_TORSO, "turn_left", parms.blendFrames );
AnimTurn ( 90.0f, true );
return SRESULT_STAGE ( STAGE_WAIT );
case STAGE_WAIT:
if ( move.fl.moving
|| AnimDone ( ANIMCHANNEL_TORSO, 0 )
|| animator.CurrentAnim( ANIMCHANNEL_TORSO )->GetEndTime() < 0//anim somehow cycled?!!!
|| idStr::Icmp( animator.CurrentAnim( ANIMCHANNEL_TORSO )->AnimName(), "turn_left" ) ) {//anim changed
AnimTurn ( 0, true );
nextTurnTime = gameLocal.time + 250;
return SRESULT_DONE;
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
/*
================
rvMonsterGladiator::State_Torso_ShieldFire
================
*/
stateResult_t rvMonsterGladiator::State_Torso_ShieldFire ( const stateParms_t& parms ) {
enum {
STAGE_INIT,
STAGE_ATTACK,
STAGE_ATTACK_WAIT,
};
switch ( parms.stage ) {
case STAGE_INIT:
if ( !enemy.ent ) {
return SRESULT_DONE;
}
shots = (minShots + gameLocal.random.RandomInt(maxShots-minShots+1)) * combat.aggressiveScale;
PlayCycle( ANIMCHANNEL_TORSO, "walk_aim", 1 );
return SRESULT_STAGE ( STAGE_ATTACK );
case STAGE_ATTACK:
Attack( "blaster", animator.GetJointHandle( "lft_wrist_jt"), GetEnemy() );
PlayEffect( "fx_blaster_flash", animator.GetJointHandle("lft_wrist_jt") );
lastShotTime = gameLocal.GetTime();
return SRESULT_STAGE ( STAGE_ATTACK_WAIT );
case STAGE_ATTACK_WAIT:
if ( move.fl.done )
{
return SRESULT_DONE;
}
if ( (gameLocal.GetTime()-lastShotTime) >= 250 ) {
shots--;
if ( GetEnemy() && shots > 0 )
{
return SRESULT_STAGE ( STAGE_ATTACK );
}
PlayCycle( ANIMCHANNEL_TORSO, "walk", 1 );
return SRESULT_DONE;
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
|
#include <string>
#include <iostream>
#include <vector>
#include <cctype>
using namespace std;
int getLength(int m){
int l = 0;
while(m){
m/=10;
l++;
}
return l;
}
int getI(int a, int l){
while(l!=1){
a/=10;
l--;
}
a%=10;
return a;
}
void largestNumber(const vector<int> &A) {
int m = INT_MAX;
vector<vector<int> > v(10);
for(int i =0;i<A.size();i++){
m = max(A[i], m);
}
int l =getLength(m);
for(int k =1;k<=l;k++){
for(int i =0;i<v.size();i++){
for(int j =0;j<v[i].size();j++){
if(k<=getLength(v[i][j])){
v[getI(v[i][j],k)].push_back(v[i][j]);
}
}
}
}
for(int i =v.size()-1;i>=0;i--){
for(int j =0;j<v[i].size();j++){
cout<<v[i][j];
}
}
}
int main(){
int n;
cin>>n;
const vector<int> A(n);
for(int i =0;i<n;i++){
scanf("%d",&A[i]);
}
largestNumber(A);
return 0;
}
|
#ifndef __DDISPLAYMANAGER__
#define __DDISPLAYMANAGER__
class DDisplayManager
{
public:
DDisplayManager ();
~DDisplayManager ();
bool initSDL ();
bool initIMG ();
bool initTTF ();
bool isLegit () { return imgLegit && sdlLegit && ttfLegit; }
private:
bool imgLegit;
bool sdlLegit;
bool ttfLegit;
};
#endif /* DDisplayManager.h */
|
#include <iostream>
#include "string.h"
#include "messagedisplay.h"
using namespace std;
int main(){
MessageDisplay k("Default");
k.setstring("This is a message.");
k.display();
return 0;
}
|
String processor(const String &var)
{
// Serial.println(var);
if (var == "Last_Update")
{
return (String(Time) + String(Date));
}
else if (var == "Temp")
{
return String(bmp.readTemperature());
}
else if (var == "Battery")
{
return String(BattLevel());
}
else if (var == "Hum")
{
return String(Values("Hum"));
}
else if (var == "Pressure")
{
return String(bmp.readPressure());
}
else if (var == "Altitude")
{
return String(abs(bmp.readAltitude()));
}
else if (var == "PumpTime")
{
return String(Pump_status ? Remain_Pump_ON : Remain_Pump_OFF);
}
else if (var == "WP")
{
return String(Pump_status ? "ON" : "OFF");
}
else
return "";
}
void Server() // Update values in background
{
server.on("/TimeUpdate", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send_P(200, "text/plain", (String(Time) + String(Date)).c_str());
});
server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send_P(200, "text/plain", processor("Temp").c_str());
});
server.on("/Battery", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send_P(200, "text/plain", processor("Battery").c_str());
});
server.on("/Humidity", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send_P(200, "text/plain", processor("Hum").c_str());
});
server.on("/pressure", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send_P(200, "text/plain", processor("Pressure").c_str());
});
server.on("/altitude", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send_P(200, "text/plain", processor("Altitude").c_str());
});
server.on("/Pump_Time", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send_P(200, "text/plain", processor("PumpTime").c_str());
});
server.on("/WP", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send_P(200, "text/plain", processor("WP").c_str());
});
// Start server
server.begin();
}
void File_System()
{
if (!SPIFFS.begin())
{
Serial.println("An Error has occurred while mounting SPIFFS");
return;
}
// Route for root / web page
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
if (!request->authenticate(http_username, http_password))
return request->requestAuthentication();
request->send(SPIFFS, "/index.html", String(), false, processor);
});
server.on("/style.css", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(SPIFFS, "/style.css", "text/css");
});
server.on("/clock", HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(SPIFFS, "/clock.png", "image/png");
});
}
|
#include "SimExamples/voronoi/ExmVoronoi.h"
#include "simd3d9/include/SimD3D9.h"
#include "include/SimException.h"
ExmVoronoi::ExmVoronoi(HINSTANCE app_instance, const char* init_file):
Framework(app_instance, init_file),
depth_(2.0f),
effect_vor_(NULL),
scene_texture_(NULL),
scene_surface_(NULL),
final_surface_(NULL){
d3d9_device_ = *(sim::SimD3D9::GetInstancePtr()->d3d9_device());
InitAllVertexDeclaration(d3d9_device_);
}
ExmVoronoi::~ExmVoronoi(){
DestroyAllVertexDeclaration();
ReleaseCOM(scene_texture_);
ReleaseCOM(scene_surface_);
ReleaseCOM(final_surface_);
}
void ExmVoronoi::CreateTriangle(){
HRESULT hr;
hr = d3d9_device_->CreateVertexBuffer(3 * sizeof(VertexPos), D3DUSAGE_WRITEONLY,
D3DFVF_XYZ, D3DPOOL_MANAGED, &vb_triangle, 0);
if (FAILED(hr)){
SIM_EXCEPTION("Create triangle vertex buffer failed!");
}
VertexPos* vp = 0;
vb_triangle->Lock(0, 0, (void**)&vp, 0);
vp[0] = VertexPos(-1.0f, 0.0f, 2.0f);
vp[1] = VertexPos(0.0f, 1.0f, 2.0f);
vp[2] = VertexPos(1.0f, 0.0f, 2.0f);
vb_triangle->Unlock();
}
void ExmVoronoi::CreateTriangleFan(float length, int num, const D3DCOLOR& clr, IDirect3DVertexBuffer9** vb) {
HRESULT hr;
hr = d3d9_device_->CreateVertexBuffer((num + 2) * sizeof(VertexPosClr), D3DUSAGE_WRITEONLY,
VertexPosClr::FVF, D3DPOOL_MANAGED, vb, 0);
if (FAILED(hr)){
SIM_EXCEPTION("Create trianglefan vertex buffer failed!");
}
VertexPosClr* vp = 0;
(*vb)->Lock(0, 0, (void**)&vp, 0);
vp[0] = VertexPosClr(0.0f, 0.0f, 0.0f, clr);
float x, y, z;
z = length;
float alpha = 0.0f;
float alpha_dt = D3DX_PI * 2.0f / num;
for (int i = 1; i <= num; ++i, alpha += alpha_dt) {
x = length * cosf(alpha);
y = length * sinf(alpha);
vp[i] = VertexPosClr(x, y, z, clr);
}
vp[num+1] = vp[1];
(*vb)->Unlock();
}
void ExmVoronoi::InitSceneBefore(){
//CreateTriangle();
CreateTriangleFan(2.0f, 30, RED, &vb_trianglefan);
CreateTriangleFan(2.0f, 30, GREEN, &vb_trianglefan1);
D3DXMatrixIdentity(&world_);
D3DXMatrixTranslation(&world_, -1.0f, 0.0f, 0.0f);
D3DXMatrixIdentity(&world1_);
D3DXMatrixTranslation(&world1_, 1.0f, 0.0f, 0.0f);
D3DXVECTOR3 eye(D3DXVECTOR3(0.0f, 0.0f, -3.0f)); // ¶¥ÊÓͼ
//D3DXVECTOR3 eye(D3DXVECTOR3(0.0f, 7.0f, 0.0f)); // ÕýÊÓͼ
D3DXVECTOR3 at(D3DXVECTOR3(0.0f, 0.0f, 0.0f));
D3DXVECTOR3 up(D3DXVECTOR3(0.0f, 1.0f, 0.0f));
D3DXMatrixLookAtLH(&view_, &eye, &at, &up);
ComputeProjectionMatrix();
//d3d9_device_->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);
//d3d9_device_->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
// [important]Only vertex with normal can open this
d3d9_device_->SetRenderState(D3DRS_LIGHTING, false);
// load effect
ID3DXBuffer* error_info;
HRESULT hr = D3DXCreateEffectFromFile(d3d9_device_, "./voronoi/gvd.fx", NULL, NULL,
D3DXSHADER_DEBUG, NULL, &effect_vor_, &error_info);
if (FAILED(hr)){
SIM_EXCEPTION("D3DXCreateEffectFromFile() failed!");
}
if (error_info) {
SIM_EXCEPTION((const char*)error_info->GetBufferPointer());
}
// create pattern
/*D3DXVECTOR3 p0(-1.0f, 1.0f, 0.0f);
D3DXVECTOR3 p1(-1.0f, -1.0f, 0.0f);
D3DXVECTOR3 p2(1.0f, -1.0f, 0.0f);
std::vector<D3DXVECTOR3> v;
v.push_back(p0);
v.push_back(p1);
VoronoiPattern* pt0 = new PatternLine(PATTERN_LINE, 2.0f, 30, v);
pt0->CreateBuffer(&d3d9_device_);
pattern_set_.push_back(pt0);
v.clear();
v.push_back(p1);
v.push_back(p2);
VoronoiPattern* pt1 = new PatternLine(PATTERN_LINE, 2.0f, 30, v);
pt1->CreateBuffer(&d3d9_device_);
pt1->SetColor(D3DXVECTOR4(1.0f, 0.0f, 0.0f, 0.0f));
pattern_set_.push_back(pt1);*/
depth_ = 2.0f;
slice_ = 30;
InitSceneBlock1(depth_, slice_);
CreateTexture();
CreateQuad();
//DrawWithPostProcessing();
}
void ExmVoronoi::InitSceneBlock1(float depth, int slice){
D3DXVECTOR3 p0(-3.0f, 3.0f, 0.0f);
D3DXVECTOR3 p1(-1.0f, 3.0f, 0.0f);
D3DXVECTOR3 p2(-1.0f, 1.0f, 0.0f);
D3DXVECTOR3 p3(-3.0f, 1.0f, 0.0f);
std::vector<D3DXVECTOR3> v;
v.push_back(p0);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
VoronoiPattern* ppt = new PatternPolygon(PATTERN_POLYGON, depth, slice, v);
ppt->CreateBuffer(&d3d9_device_);
ppt->SetColor(D3DXVECTOR4(1.0f, 1.0f, 0.0f, 0.0f));
pattern_set_.push_back(ppt);
D3DXVECTOR3 p4(1.0f, 3.0f, 0.0f);
D3DXVECTOR3 p5(3.0f, 3.0f, 0.0f);
D3DXVECTOR3 p6(3.0f, 1.0f, 0.0f);
D3DXVECTOR3 p7(1.0f, 1.0f, 0.0f);
v.clear();
v.push_back(p4);
v.push_back(p5);
v.push_back(p6);
v.push_back(p7);
ppt = new PatternPolygon(PATTERN_POLYGON, depth, slice, v);
ppt->CreateBuffer(&d3d9_device_);
ppt->SetColor(D3DXVECTOR4(0.0f, 1.0f, 0.0f, 0.0f));
pattern_set_.push_back(ppt);
D3DXVECTOR3 p8(1.0f, -1.0f, 0.0f);
D3DXVECTOR3 p9(3.0f, -1.0f, 0.0f);
D3DXVECTOR3 p10(3.0f, -3.0f, 0.0f);
D3DXVECTOR3 p11(1.0f, -3.0f, 0.0f);
v.clear();
v.push_back(p8);
v.push_back(p9);
v.push_back(p10);
v.push_back(p11);
ppt = new PatternPolygon(PATTERN_POLYGON, depth, slice, v);
ppt->CreateBuffer(&d3d9_device_);
ppt->SetColor(D3DXVECTOR4(0.0f, 1.0f, 1.0f, 0.0f));
pattern_set_.push_back(ppt);
D3DXVECTOR3 p12(-3.0f, -1.0f, 0.0f);
D3DXVECTOR3 p13(-1.0f, -1.0f, 0.0f);
D3DXVECTOR3 p14(-1.0f, -3.0f, 0.0f);
D3DXVECTOR3 p15(-3.0f, -3.0f, 0.0f);
v.clear();
v.push_back(p12);
v.push_back(p13);
v.push_back(p14);
v.push_back(p15);
ppt = new PatternPolygon(PATTERN_POLYGON, depth, slice, v);
ppt->CreateBuffer(&d3d9_device_);
ppt->SetColor(D3DXVECTOR4(1.0f, 0.0f, 1.0f, 0.0f));
pattern_set_.push_back(ppt);
}
void ExmVoronoi::UpdateScene(float dt){
}
void ExmVoronoi::DrawScene(){
//DrawByShader();
//DrawPatterGroup();
DrawWithPostProcessing();
}
void ExmVoronoi::DrawPatterGroup(){
int n = pattern_set_.size();
d3d9_device_->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
D3DCOLOR_XRGB(255, 255, 255), 1.0f, 0);
d3d9_device_->BeginScene();
d3d9_device_->SetVertexDeclaration(VertexPos::decl);
D3DXHANDLE fx_technique = effect_vor_->GetTechniqueByName("NoLighting");
HR( effect_vor_->SetTechnique(fx_technique) );
effect_vor_->Begin(NULL, 0);
effect_vor_->BeginPass(0);
effect_vor_->SetMatrix("matrix_wvp", &(view_ * proj_));
for (int i = 0; i < n; ++i) {
pattern_set_[i]->Draw(&d3d9_device_, &effect_vor_);
}
effect_vor_->EndPass();
effect_vor_->End();
d3d9_device_->EndScene();
HRESULT hr = d3d9_device_->Present(0,0,0,0);
if (FAILED(hr)) SIM_EXCEPTION("Present() failed!");
}
void ExmVoronoi::DrawWithPostProcessing(){
int n = pattern_set_.size();
d3d9_device_->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
D3DCOLOR_XRGB(255, 255, 255), 1.0f, 0);
HR( d3d9_device_->GetRenderTarget(0, &final_surface_) );
HR( d3d9_device_->BeginScene() );
d3d9_device_->SetRenderTarget(0, scene_surface_);
d3d9_device_->SetVertexDeclaration(VertexPos::decl);
D3DXHANDLE fx_technique = effect_vor_->GetTechniqueByName("NoLighting");
// 1. Draw Scene.
HR( effect_vor_->SetTechnique(fx_technique) );
effect_vor_->Begin(NULL, 0);
effect_vor_->BeginPass(0);
effect_vor_->SetMatrix("matrix_wvp", &(view_ * proj_));
for (int i = 0; i < n; ++i) {
pattern_set_[i]->Draw(&d3d9_device_, &effect_vor_);
}
effect_vor_->EndPass();
effect_vor_->End();
HR( d3d9_device_->EndScene());
// debug part
//HR( D3DXSaveTextureToFileA("scene.bmp", D3DXIFF_BMP, scene_texture_, NULL) );
IDirect3DTexture9* scene_texture_1 = NULL;
//D3DXCreateTextureFromResource(d3d9_device_,
HR( D3DXCreateTextureFromFileA(d3d9_device_, "scene.bmp", &scene_texture_1) );
/*D3DSURFACE_DESC scene_tex_desc;
scene_texture_1->GetLevelDesc(0, &scene_tex_desc);*/
// 2. Post Processing
//HR( d3d9_device_->SetRenderTarget(0, NULL) );
d3d9_device_->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
D3DCOLOR_XRGB(255, 255, 255), 1.0f, 0);
//HR( d3d9_device_->BeginScene());
d3d9_device_->SetRenderTarget(0, final_surface_);
D3DXHANDLE hd = effect_vor_->GetParameterByName(NULL,"texture_scene");
//HR( effect_vor_->SetTexture(hd, scene_texture_) );
/*D3DSURFACE_DESC desc;
scene_texture_->GetLevelDesc(0, &desc);*/
HR( effect_vor_->SetTexture("texture_scene", scene_texture_1) );
fx_technique = effect_vor_->GetTechniqueByName("PostProcess");
HR( effect_vor_->SetTechnique(fx_technique));
HR( d3d9_device_->SetVertexDeclaration(VertexPosT::decl) );
HR( d3d9_device_->SetStreamSource(0, vb_quad_, 0, sizeof(VertexPosT)) );
HR( effect_vor_->Begin(NULL, 0) );
HR( effect_vor_->BeginPass(0) );
D3DPRESENT_PARAMETERS& d3dpp = sim::SimD3D9::GetInstancePtr()->d3dpp();
HR( effect_vor_->SetMatrix("matrix_wvp", &(view_ * proj_)) );
HR( effect_vor_->SetFloat("dx", 1.0f/d3dpp.BackBufferWidth));
HR( effect_vor_->SetFloat("dy", 1.0f/d3dpp.BackBufferHeight));
HR( d3d9_device_->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2) );
HR( effect_vor_->EndPass() );
HR( effect_vor_->End() );
//HR( d3d9_device_->EndScene() );
//HR( d3d9_device_->StretchRect(scene_surface_, NULL, final_surface_, NULL, D3DTEXF_LINEAR) );
HRESULT hr = d3d9_device_->Present(0,0,0,0);
if (FAILED(hr)) SIM_EXCEPTION("Present() failed!");
}
void ExmVoronoi::DrawByFixedPipeline(){
d3d9_device_->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
D3DCOLOR_XRGB(255, 255, 255), 1.0f, 0);
d3d9_device_->BeginScene();
d3d9_device_->SetTransform(D3DTS_WORLD, &world_);
d3d9_device_->SetTransform(D3DTS_VIEW, &view_);
d3d9_device_->SetTransform(D3DTS_PROJECTION, &proj_);
/*d3d9_device_->SetStreamSource(0, vb_triangle, 0, sizeof(VertexPos));*/
d3d9_device_->SetStreamSource(0, vb_trianglefan, 0, sizeof(VertexPosClr));
d3d9_device_->SetFVF(VertexPosClr::FVF);
/*d3d9_device_->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);*/
d3d9_device_->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 30);
d3d9_device_->SetTransform(D3DTS_WORLD, &world1_);
d3d9_device_->SetStreamSource(0, vb_trianglefan1, 0, sizeof(VertexPosClr));
d3d9_device_->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 30);
d3d9_device_->EndScene();
HRESULT hr = d3d9_device_->Present(0,0,0,0);
if (FAILED(hr)) SIM_EXCEPTION("Present() failed!");
}
void ExmVoronoi::DrawByShader(){
d3d9_device_->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
D3DCOLOR_XRGB(255, 255, 255), 1.0f, 0);
d3d9_device_->BeginScene();
d3d9_device_->SetVertexDeclaration(VertexPosClr::decl);
D3DXHANDLE fx_technique = effect_vor_->GetTechniqueByName("NoLighting");
effect_vor_->SetTechnique(fx_technique);
effect_vor_->Begin(NULL, 0);
effect_vor_->BeginPass(0);
effect_vor_->SetMatrix("matrix_wvp", &(world_ * view_ * proj_));
effect_vor_->CommitChanges();
d3d9_device_->SetStreamSource(0, vb_trianglefan, 0, sizeof(VertexPosClr));
d3d9_device_->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 30);
effect_vor_->SetMatrix("matrix_wvp", &(world1_ * view_ * proj_));
effect_vor_->CommitChanges();
d3d9_device_->SetStreamSource(0, vb_trianglefan1, 0, sizeof(VertexPosClr));
d3d9_device_->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, 30);
effect_vor_->EndPass();
effect_vor_->End();
d3d9_device_->EndScene();
HRESULT hr = d3d9_device_->Present(0,0,0,0);
if (FAILED(hr)) SIM_EXCEPTION("Present() failed!");
}
void ExmVoronoi::CreatePatternPoint(float depth, int slice, const D3DXVECTOR3& pos){
depth_ = depth;
HR( d3d9_device_->CreateVertexBuffer((slice + 2) * sizeof(VertexPos), D3DUSAGE_WRITEONLY,
VertexPos::FVF, D3DPOOL_MANAGED, &vb_pattern_point_, 0) );
VertexPos* vp = 0;
HR( vb_pattern_point_->Lock(0, 0, (void**)&vp, 0) );
vp[0] = pos/*VertexPos(0.0f, 0.0f, 0.0f)*/;
float x, y, z;
z = depth + pos.z;
float alpha = 0.0f;
float alpha_dt = D3DX_PI * 2.0f / slice;
// clockwise order
for (int i = 1; i <= slice; ++i, alpha += alpha_dt) {
x = depth * cosf(alpha) + pos.x;
y = depth * sinf(alpha) + pos.y;
vp[i] = VertexPos(x, y, z);
}
vp[slice+1] = vp[1];
HR( vb_pattern_point_->Unlock() );
}
void ExmVoronoi::CreatePatternLine(float depth, int slice,
const D3DXVECTOR3& pos_start, const D3DXVECTOR3& pos_end)
{
depth_ = depth;
int num_points = slice + 4;
HR( d3d9_device_->CreateVertexBuffer(num_points * sizeof(VertexPos), D3DUSAGE_WRITEONLY,
VertexPos::FVF, D3DPOOL_MANAGED, &vb_pattern_point_, 0) );
VertexPos* vp = 0;
HR( vb_pattern_point_->Lock(0, 0, (void**)&vp, 0) );
vp[0] = pos_start;/*VertexPos(0.0f, 0.0f, 0.0f)*/;
float x, y, z;
z = depth + pos_start.z;
float alpha = 0.0f;
float alpha_dt = D3DX_PI * 2.0f / slice;
// clockwise order
for (int i = 1; i <= slice; ++i, alpha += alpha_dt) {
x = depth * cosf(alpha) + pos_start.x;
y = depth * sinf(alpha) + pos_start.y;
vp[i] = VertexPos(x, y, z);
}
vp[slice+1] = vp[1];
HR( vb_pattern_point_->Unlock() );
}
void ExmVoronoi::CreatePatternPolygon(const std::vector<D3DXVECTOR3>& pos_set, float depth, int slice){
}
void ExmVoronoi::ComputeProjectionMatrix(){
D3DPRESENT_PARAMETERS& d3dpp = sim::SimD3D9::GetInstancePtr()->d3dpp();
//D3DXMatrixPerspectiveFovLH(
// &proj_,
// D3DX_PI * 0.5f, // 90 - degree
// (float)d3dpp.BackBufferWidth / (float)d3dpp.BackBufferHeight,
// 1.0f,
// 1000.0f);
float radio = (float)d3dpp.BackBufferWidth / (float)d3dpp.BackBufferHeight;
surface_height_ = 10.0f;
surface_width_ = radio * surface_height_;
D3DXMatrixOrthoLH(&proj_, surface_width_, surface_height_, -10.0f, 10.0f);
}
void ExmVoronoi::CreateTexture(){
D3DPRESENT_PARAMETERS& d3dpp = sim::SimD3D9::GetInstancePtr()->d3dpp();
//HRESULT hr;
HR(d3d9_device_->CreateTexture(d3dpp.BackBufferWidth, d3dpp.BackBufferHeight,
1, D3DUSAGE_RENDERTARGET, /*d3dpp.BackBufferFormat*/D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT,
&scene_texture_, 0) );
//DWORD error = GetLastError();
HR( scene_texture_->GetSurfaceLevel(0, &scene_surface_) );
}
void ExmVoronoi::CreateQuad(){
HR( d3d9_device_->CreateVertexBuffer(4 * sizeof(VertexPosT), D3DUSAGE_WRITEONLY,
VertexPosT::FVF, D3DPOOL_MANAGED, &vb_quad_, 0) );
VertexPosT* vp = 0;
//D3DPRESENT_PARAMETERS& d3dpp = sim::SimD3D9::GetInstancePtr()->d3dpp();
HR( vb_quad_->Lock(0, 0, (void**)&vp, 0) );
/*vp[0] = VertexPosT(-0.5f, -0.5f, depth_, 0.0f, 0.0f);
vp[1] = VertexPosT(-0.5f + d3dpp.BackBufferWidth, -0.5f, depth_, 1.0f, 0.0f);
vp[2] = VertexPosT(-0.5f, -0.5f + d3dpp.BackBufferHeight, depth_, 0.0f, 1.0f);
vp[3] = VertexPosT(-0.5f + d3dpp.BackBufferWidth, -0.5f + d3dpp.BackBufferHeight, depth_, 1.0f, 1.0f);*/
vp[0] = VertexPosT(-surface_width_/2.0f, surface_height_/2.0f, depth_, 0.0f, 0.0f);
vp[1] = VertexPosT(surface_width_/2.0f, surface_height_/2.0f, depth_, 1.0f, 0.0f);
vp[2] = VertexPosT(-surface_width_/2.0f, -surface_height_/2.0f, depth_, 0.0f, 1.0f);
vp[3] = VertexPosT(surface_width_/2.0f, -surface_height_/2.0f, depth_, 1.0f, 1.0f);
HR( vb_quad_->Unlock());
}
void ExmVoronoi::OnLostDevice(){
ReleaseCOM(scene_texture_);
ReleaseCOM(scene_surface_);
ReleaseCOM(vb_quad_);
effect_vor_->OnLostDevice();
}
void ExmVoronoi::OnResetDevice(){
effect_vor_->OnResetDevice();
ComputeProjectionMatrix();
CreateQuad();
CreateTexture();
}
|
#include <iostream>
#include <array>
#include <fstream>
#include <string>
#include <optional>
#include <cmath>
#include <vector>
#include <iomanip>
typedef std::array<std::array<double, 3>, 3> matrix;
std::optional<std::string> ParseArgs(int argc, char* argv[])
{
if (argc != 2)
{
std::cout << "Invalid arguments count\n";
std::cout << "Usage: Multimatrix.exe <matrix file>\n";
return std::nullopt;
}
std::string arg = argv[1];
return arg;
}
std::vector<std::string> Split(const std::string& str, const std::string& delim)
{
std::vector<std::string> tokens;
size_t prev = 0, pos = 0;
do
{
pos = str.find(delim, prev);
if (pos == std::string::npos)
{
pos = str.length();
}
std::string token = str.substr(prev, pos - prev);
if (!token.empty())
{
tokens.push_back(token);
}
prev = pos + delim.length();
} while (pos < str.length() && prev < str.length());
return tokens;
}
bool IsValidCharacter(const char & ch)
{
return (ch == '.' || ch == '-' || (ch <= '9') && (ch >= '0'));
}
std::optional<matrix> ReadMatrix(std::istream& file)
{
int row = 0;
std::string matrixLine;
matrix matrix = { 0 };
while (getline(file, matrixLine))
{
if (Split(matrixLine, " ").size() < 3)
{
std::cout << "Matrix hax empty values\n";
return std::nullopt;
}
int column = 0;
std::string digit;
for (unsigned i = 0; i < matrixLine.length(); i++)
{
if (matrixLine[i] != ' ')
{
if (!IsValidCharacter(matrixLine[i]))
{
std::cout << "The file contains non-digit values\n";
return std::nullopt;
}
digit += matrixLine[i];
continue;
}
matrix[row][column] = stoi(digit);
column++;
digit = "";
}
matrix[row][column] = stoi(digit);
row++;
}
return matrix;
}
std::optional<matrix> ReadMatrixFromFile(const std::string& fileName)
{
std::ifstream file(fileName);
if (!file.is_open())
{
std::cout << "Failed to open '" << &file << "' for reading\n";
return std::nullopt;
}
auto matrix = ReadMatrix(file);
return matrix;
}
void ShowMatrix(matrix matrix)
{
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
std::cout << std::fixed << std::setprecision(3) << matrix[i][j];
if (j != 2) std::cout << " ";
}
if (i != 2) std::cout << std::endl;
}
}
double GetDetermenant(const matrix &m)
{
double determenant;
determenant = m[0][0] * (m[1][1] * m[2][2] - m[2][1] * m[1][2]) - m[0][1] * (m[1][0] * m[2][2] - m[2][0] * m[1][2]) + m[0][2] * (m[1][0] * m[2][1] - m[2][0] * m[1][1]);
return determenant;
}
matrix GetAlgebraicExtension(const matrix& m)
{
matrix algebraicExtension;
algebraicExtension[0][0] = m[1][1] * m[2][2] - m[1][2] * m[2][1];;
algebraicExtension[0][1] = -(m[1][0] * m[2][2] - m[2][0] * m[1][2]);;
algebraicExtension[0][2] = m[1][0] * m[2][1] - m[1][1] * m[2][0];;
algebraicExtension[1][0] = -(m[0][1] * m[2][2] - m[0][2] * m[2][1]);;
algebraicExtension[1][1] = m[0][0] * m[2][2] - m[0][2] * m[2][0];;
algebraicExtension[1][2] = -(m[0][0] * m[2][1] - m[2][0] * m[0][1]);;
algebraicExtension[2][0] = m[0][1] * m[1][2] - m[0][2] * m[1][1];;
algebraicExtension[2][1] = -(m[0][0] * m[1][2] - m[0][2] * m[1][0]);;
algebraicExtension[2][2] = m[0][0] * m[1][1] - m[1][0] * m[0][1];;
return algebraicExtension;
}
std::optional<matrix> InverseMatrix(const matrix& m)
{
matrix resultMatrix;
double det = GetDetermenant(m);
if (det == 0)
{
std::cout << "The determenant is 0\n";
return std::nullopt;
}
matrix algebraicExtension = GetAlgebraicExtension(m);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
resultMatrix[j][i] = (1 / det) * algebraicExtension[i][j];
}
}
return resultMatrix;
}
int main(int argc, char* argv[])
{
auto args = ParseArgs(argc, argv);
if (!args)
{
return 1;
}
auto matrix = ReadMatrixFromFile(*args);
if (!matrix)
{
return 1;
}
auto resultMatrix = InverseMatrix(*matrix);
if (!resultMatrix)
{
return 1;
}
ShowMatrix(*resultMatrix);
return 0;
}
|
#include <LocalDB.hpp>
#include "Client.hpp"
Client::Client(boost::asio::io_service &ioService, std::string const &host, std::string const &port)
: APacketServer(ioService, 0, new LocalDB()) {
this->_serverEndpoint = *this->_resolver.resolve({boost::asio::ip::udp::v4(), host, port});
this->saveClient("SERVER", this->_serverEndpoint);
}
void Client::run() {
this->_moduleManager.run();
}
void Client::addModuleCommunication(IModuleCommunication *moduleCommunication) {
this->_moduleCommunication = moduleCommunication;
this->_moduleManager.addModuleCommunication(moduleCommunication);
this->_crypt.addModuleCommunication(moduleCommunication);
this->_crypt.init();
}
bool Client::requestCheck(boost::system::error_code &ec, std::string &req, boost::asio::ip::udp::endpoint &clientEndpoint) {
if (this->_serverEndpoint != clientEndpoint) {
return false;
}
return true;
}
void Client::packetHandler(Packet &packet) {
std::cout << packet << std::endl;
auto data = packet.get<Packet::Field::DATA, std::string>();
boost::property_tree::ptree ptree = packet.getPtree();
if (ptree.get<std::string>("data.type") == "Order") {
this->_moduleCommunication->add(ptree.get_child("data.order"));
} else if (ptree.get<std::string>("data.type") == "Upload")
this->_moduleManager.addLibrary(ptree.get_child("data.lib"));
else if (ptree.get<std::string>("data.type") == "AesKey") {
this->_crypt.init(ptree.get<std::string>("data.key.AES_KEY"),
ptree.get<std::string>("data.key.AES_IV"));
this->_cookie = ptree.get<std::string>("data.key.cookie");
}
}
void Client::encryptor(Packet &packet, boost::asio::ip::udp::endpoint const &) {
this->_crypt.encrypt(packet);
}
std::string Client::encryptorMethod(Packet &packet, boost::asio::ip::udp::endpoint const &) {
return this->_crypt.encryptMethod(packet);
}
void Client::decryptor(Packet &packet) {
this->_crypt.decrypt(packet);
}
void Client::send(std::string const &data,
std::string const &id) {
this->sendPacket(data, this->_serverEndpoint, id);
}
void Client::send(std::string const &data) {
this->sendPacket(data, this->_serverEndpoint);
}
|
#ifndef FILESYSTEM_H
#define FILESYSTEM_H
#include <string>
#include <Vector>
#include <boost/shared_ptr.hpp>
class File;
class FileSystem
{
public:
FileSystem();
virtual ~FileSystem();
private:
typedef std::vector<boost::shared_ptr<File> > fileVector;
fileVector mFiles;
};
#endif // FILESYSTEM_H
|
#include "../headers/Stage.h"
Stage::Stage( int width, int height, int x , int y, SDL_Renderer* pRenderer) : Drawable(STAGE_IMG_PATH, pRenderer) {
this->setPosition(x,y);
this->height = height;
this->width = width;
this->setSize(width, height);
}
Stage::~Stage() {
}
void Stage::draw() {
/*
this->texture::draw();
//Render green outlined quad
SDL_Rect outlineRect = { 50, 50, width, height };
SDL_SetRenderDrawColor( pRenderer_, 0x00, 0xFF, 0x00, 0xFF );
SDL_RenderDrawRect( pRenderer_, &outlineRect );
//int a = SDL_RenderDrawRect( pRenderer_, &rendererRectangle );
*/
}
|
//
// Copyright (C) 2006-2012 Greg Landrum
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#ifndef _RD_CHEMTRANSFORMS_H__
#define _RD_CHEMTRANSFORMS_H__
#include <boost/smart_ptr.hpp>
#include <vector>
#include <iostream>
#include "MolFragmenter.h"
namespace RDKit{
class ROMol;
typedef boost::shared_ptr<ROMol> ROMOL_SPTR;
//! \brief Returns a copy of an ROMol with the atoms and bonds that
//! match a pattern removed.
/*!
\param mol the ROMol of interest
\param query the query ROMol
\param onlyFrags if this is set, atoms will only be removed if
the entire fragment in which they are found is
matched by the query.
\return a copy of \c mol with the matching atoms and bonds (if any)
removed.
*/
ROMol *deleteSubstructs(const ROMol &mol, const ROMol &query,
bool onlyFrags=false);
//! \brief Returns a list of copies of an ROMol with the atoms and bonds that
//! match a pattern replaced with the atoms contained in another molecule.
/*!
Bonds are created between the joining atom in the existing molecule
and the atoms in the new molecule. So, using SMILES instead of molecules:
replaceSubstructs('OC(=O)NCCNC(=O)O','C(=O)O','[X]') ->
['[X]NCCNC(=O)O','OC(=O)NCCN[X]']
replaceSubstructs('OC(=O)NCCNC(=O)O','C(=O)O','[X]',true) ->
['[X]NCCN[X]']
Chains should be handled "correctly":
replaceSubstructs('CC(=O)C','C(=O)','[X]') ->
['C[X]C']
As should rings:
replaceSubstructs('C1C(=O)C1','C(=O)','[X]') ->
['C1[X]C1']
And higher order branches:
replaceSubstructs('CC(=O)(C)C','C(=O)','[X]') ->
['C[X](C)C']
Note that the client is responsible for making sure that the
resulting molecule actually makes sense - this function does not
perform sanitization.
\param mol the ROMol of interest
\param query the query ROMol
\param replacement the ROMol to be inserted
\param replaceAll if this is true, only a single result, with all occurances
of the substructure replaced, will be returned.
\param replacementConnectionPoint index of the atom in the replacement that
the bond should made to
\return a vector of pointers to copies of \c mol with the matching atoms
and bonds (if any) replaced
*/
std::vector<ROMOL_SPTR> replaceSubstructs(const ROMol &mol, const ROMol &query,
const ROMol &replacement,
bool replaceAll=false,
unsigned int replacementConnectionPoint=0);
//! \brief Returns a copy of an ROMol with the atoms and bonds that
//! don't fall within a substructure match removed.
//!
//! dummy atoms are left to indicate attachment points.
//!
/*!
\param mol the ROMol of interest
\param coreQuery a query ROMol to be used to match the core
\return a copy of \c mol with the non-matching atoms and bonds (if any)
removed and dummies at the connection points.
*/
ROMol *replaceSidechains(const ROMol &mol, const ROMol &coreQuery);
//! \brief Returns a copy of an ROMol with the atoms and bonds that
//! do fall within a substructure match removed.
//!
//! dummy atoms are left to indicate attachment points.
//!
/*!
Note that this is essentially identical to the replaceSidechains function, except we
invert the query and replace the atoms that *do* match the query.
\param mol - the ROMol of interest
\param coreQuery - a query ROMol to be used to match the core
\param replaceDummies - if set, atoms matching dummies in the core will also be replaced
\param labelByIndex - if set, the dummy atoms at attachment points are labelled with the
index+1 of the corresponding atom in the core
\param requireDummyMatch - if set, only side chains that are connected to atoms in
the core that have attached dummies will be considered.
Molecules that have sidechains that are attached
at other points will be rejected (NULL returned).
\return a copy of \c mol with the non-matching atoms and bonds (if any)
removed and dummies at the connection points. The client is responsible
for deleting this molecule. If the core query is not matched, NULL is returned.
*/
ROMol *replaceCore(const ROMol &mol, const ROMol &coreQuery,
bool replaceDummies=true,bool labelByIndex=false,
bool requireDummyMatch=false);
//! \brief Carries out a Murcko decomposition on the molecule provided
//!
/*!
\param mol - the ROMol of interest
\return a new ROMol with the Murcko scaffold
The client is responsible for deleting this molecule.
*/
ROMol *MurckoDecompose(const ROMol &mol);
//! \brief Combined two molecules to create a new one
//!
/*!
\param mol1 - the first ROMol to be combined
\param mol2 - the second ROMol to be combined
\param offset - a constant offset to be added to every
atom position in mol2
\return a new ROMol with the two molecules combined.
The new molecule has not been sanitized.
The client is responsible for deleting this molecule.
*/
ROMol *combineMols(const ROMol &mol1, const ROMol &mol2,
RDGeom::Point3D offset=RDGeom::Point3D(0,0,0));
//! \brief Adds named recursive queries to a molecule's atoms based on atom labels
//!
/*!
\param mol - the molecule to be modified
\param queries - the dictionary of named queries to add
\param propName - the atom property to use to get query names
\param reactantLabels - to store pairs of (atom index, query string)
NOTES:
- existing query information, if present, will be supplemented (AND logic)
- non-query atoms will be replaced with query atoms using only the query
logic
- query names can be present as comma separated lists, they will then
be combined using OR logic.
- throws a KeyErrorException if a particular query name is not present
in \c queries
*/
void addRecursiveQueries(ROMol &mol,const std::map<std::string,ROMOL_SPTR> &queries,std::string propName,
std::vector<std::pair<unsigned int, std::string> > *reactantLabels=NULL);
//! \brief parses a query definition file and sets up a set of definitions
//! suitable for use by addRecursiveQueries()
/*!
\param filename - the name of the file to be read
\param queryDefs - the dictionary of named queries (return value)
\param standardize - if true, query names will be converted to lower case
\param delimiter - the line delimiter in the file
\param comment - text used to recognize comment lines
\param nameColumn - column with the names of queries
\param smartsColumn - column with the SMARTS definitions of the queries
*/
void parseQueryDefFile(std::string filename,std::map<std::string,ROMOL_SPTR> &queryDefs,
bool standardize=true,std::string delimiter="\t",std::string comment="//",
unsigned int nameColumn=0,unsigned int smartsColumn=1);
//! \overload
void parseQueryDefFile(std::istream *inStream,std::map<std::string,ROMOL_SPTR> &queryDefs,
bool standardize=true,std::string delimiter="\t",std::string comment="//",
unsigned int nameColumn=0,unsigned int smartsColumn=1);
//! \brief equivalent to parseQueryDefFile() but the query definitions are explicitly passed in
void parseQueryDefText(const std::string &queryDefText,std::map<std::string,ROMOL_SPTR> &queryDefs,
bool standardize=true,std::string delimiter="\t",std::string comment="//",
unsigned int nameColumn=0,unsigned int smartsColumn=1);
}
#endif
|
#ifndef CPOINT_H
#define CPOINT_H
// external include
#include "xmlParser.h"
// project include
#include "CShape.h"
class CPoint : public CShape
{
public:
CPoint( double inX, double inY );
~CPoint();
void SetCoord( double inX, double inY );
void GetCoord( double& outX, double& outY ) const;
//void GetCoord2( double outX, double outY ); // errata
double GetX() const { return mX; }
double GetY() const { return mY; }
static CShape* CreateFromXml( XMLNode& currNode );//aggiunto
virtual void Draw() const;
virtual void SaveXml ( XMLNode& inNode );
//static CPoint* CreateFromXml(XMLNode inNode);
private:
double mX;
double mY;
};
#endif // CPOINT_H
|
#include "cpptest.h"
CPPTEST_CONTEXT("core.threads.test.cpptest.TA_Thread_CppTest/core.thread.test.cpptest/src/Thread.cpp");
CPPTEST_TEST_SUITE_INCLUDED_TO("core.threads.test.cpptest.TA_Thread_CppTest/core.thread.test.cpptest/src/Thread.cpp");
class TestSuite_get_time_f531f15c : public CppTest_TestSuite
{
public:
CPPTEST_TEST_SUITE(TestSuite_get_time_f531f15c);
CPPTEST_TEST(test_get_time_1);
CPPTEST_TEST_SUITE_END();
void setUp();
void tearDown();
void test_get_time_1();
};
CPPTEST_TEST_SUITE_REGISTRATION(TestSuite_get_time_f531f15c);
void TestSuite_get_time_f531f15c::setUp()
{
FUNCTION_ENTRY( "setUp" );
FUNCTION_EXIT;
}
void TestSuite_get_time_f531f15c::tearDown()
{
FUNCTION_ENTRY( "tearDown" );
FUNCTION_EXIT;
}
/* CPPTEST_TEST_CASE_BEGIN test_get_time_1 */
/* CPPTEST_TEST_CASE_CONTEXT void TA_Base_Core::Thread::get_time(unsigned long *, unsigned long *, unsigned long, unsigned long) */
void TestSuite_get_time_f531f15c::test_get_time_1()
{
FUNCTION_ENTRY( "test_get_time_1" );
/* Pre-condition initialization */
/* Initializing argument 1 (abs_sec) */
unsigned long _abs_sec_0 [1];
unsigned long * _abs_sec = (unsigned long * )cpptestMemset((void*)&_abs_sec_0, 0, (1 * sizeof(unsigned long)));
/* Initializing argument 2 (abs_nsec) */
unsigned long _abs_nsec_1 [1];
unsigned long * _abs_nsec = (unsigned long * )cpptestMemset((void*)&_abs_nsec_1, 0, (1 * sizeof(unsigned long)));
/* Initializing argument 3 (rel_sec) */
unsigned long _rel_sec = 0;
/* Initializing argument 4 (rel_nsec) */
unsigned long _rel_nsec = 0;
/* Tested function call */
::TA_Base_Core::Thread::get_time(_abs_sec, _abs_nsec, _rel_sec, _rel_nsec);
/* Post-condition check */
CPPTEST_POST_CONDITION_MEM_BUFFER("unsigned long * _abs_sec", ( _abs_sec ), sizeof(unsigned long));
CPPTEST_POST_CONDITION_MEM_BUFFER("unsigned long * _abs_nsec", ( _abs_nsec ), sizeof(unsigned long));
FUNCTION_EXIT;
}
/* CPPTEST_TEST_CASE_END test_get_time_1 */
|
#include<cstdio>
#include<cstring>
#define M 10010
using namespace std;
int l[M],r[M],pre[M],next[M],key[M];
int n,len,root,pr,ne;
int x;
void insert(int &x,int num)
{
if(x==0)
{
x=++len;
l[x]=r[x]=0;
pre[x]=pr;
next[x]=ne;
//给x的前趋后趋都标志一下
next[pr]=x;
pre[ne]=x;
//
key[x]=num;
}
else{
if(num<=key[x]) ne=x,insert(l[x],num);
else pr=x,insert(r[x],num);
}
}
void small_big()
{
int cur=root;
while(pre[cur]!=0) cur=pre[cur];
while(cur!=0)
{
printf("%d ",key[cur]);
cur=next[cur];
}
printf("\n");
}
void big_small()
{
int cur=root;
while(next[cur]!=0) cur=next[cur];
while(cur!=0)
{
printf("%d ",key[cur]);
cur=pre[cur];
}
printf("\n");
}
int main()
{
freopen("test.in","r",stdin);
len=0;
root=0;
scanf("%d",&n);
for(int i=1;i<=n;++i)
{
scanf("%d",&x);
pr=ne=0;
insert(root,x);
}
small_big();
big_small();
return 0;
}
|
#pragma once
#include <glm/glm.hpp>
namespace Game
{
struct CameraData
{
CameraData()
{
}
glm::mat4 viewMatrix;
glm::mat4 projectionMatrix;
};
}
|
//KM算法
#include<cstdio>
#include<cstring>
#include<algorithm>
#define INF 1000000000
using namespace std;
bool x[110],y[110];
int link[110],lx[110],ly[110];
int w[110][110];
struct point
{
int x,y;
}man[110],house[110];
int n,m,lm,lh,ans;
char ch;
void build()
{
memset(w,0,sizeof(w));
for(int i=1;i<=lm;++i)
for(int j=1;j<=lh;++j)
//最大还是最小权匹配主要在这里区分,
//如果是最大权,那么就是正的,否则就是负权。
w[i][j]=-(abs(man[i].x-house[j].x)+abs(man[i].y-house[j].y));
}
bool dfs(int src)
{
x[src]=true;
for(int j=1;j<=lh;++j)
{
if(!y[j]&&lx[src]+ly[j]==w[src][j])
{
y[j]=true;
if(link[j]==0||dfs(link[j]))
{
link[j]=src;
return true;
}
}
}
return false;
}
void KM()
{
fill(lx,lx+lm+1,-INF);
memset(ly,0,sizeof(ly));
memset(link,0,sizeof(link));
for(int i=1;i<=lm;++i)
for(int j=1;j<=lh;++j)
lx[i]=max(lx[i],w[i][j]);
for(int i=1;i<=lm;++i)
while(1)
{
memset(x,0,sizeof(x));
memset(y,0,sizeof(y));
if(dfs(i)) break;
int d=INF;
for(int j=1;j<=lm;++j)
if(x[j])
for(int k=1;k<=lh;++k)
if(!y[k])
d=min(d,lx[j]+ly[k]-w[j][k]);
for(int j=1;j<=lh;++j)
{
if(x[j]) lx[j]-=d;
if(y[j]) ly[j]+=d;
}
}
ans=0;
for(int i=1;i<=lh;++i) if(link[i]>0)
ans+=w[link[i]][i];
printf("%d\n",-ans);
}
int main()
{
freopen("test.in","r",stdin);
scanf("%d%d\n",&n,&m);
while(n+m!=0)
{
lm=lh=0;
for(int i=1;i<=n;++i)
{
for(int j=1;j<=m;++j)
{
ch=getchar();
if(ch=='m') man[++lm]=(point){i,j};
else if(ch=='H') house[++lh]=(point){i,j};
}
getchar();
}
build();
KM();
scanf("%d%d\n",&n,&m);
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef DOM3_LOAD
#include "modules/dom/src/domenvironmentimpl.h"
#include "modules/dom/src/domcore/domconfiguration.h"
#include "modules/dom/src/domcore/domxmldocument.h"
#include "modules/dom/src/domcore/domerror.h"
#include "modules/dom/src/domcore/domlocator.h"
#include "modules/dom/src/domcore/entity.h"
#include "modules/dom/src/domcore/node.h"
#include "modules/dom/src/domevents/domeventtarget.h"
#include "modules/dom/src/domload/lscontenthandler.h"
#include "modules/dom/src/domload/lsevents.h"
#include "modules/dom/src/domload/lsexception.h"
#include "modules/dom/src/domload/lsinput.h"
#include "modules/dom/src/domload/lsloader.h"
#include "modules/dom/src/domload/lsparser.h"
#include "modules/dom/src/domload/lsthreads.h"
#include "modules/dom/src/opera/domhttp.h"
#include "modules/dom/src/js/window.h"
#include "modules/doc/frm_doc.h"
#include "modules/ecmascript_utils/esasyncif.h"
#include "modules/ecmascript_utils/essched.h"
#include "modules/ecmascript_utils/esthread.h"
#include "modules/dochand/win.h"
#include "modules/security_manager/include/security_manager.h"
#ifdef DOM_WEBWORKERS_SUPPORT
#include "modules/dom/src/domwebworkers/domwebworkers.h"
#endif // DOM_WEBWORKERS_SUPPORT
#include "modules/url/protocols/scomm.h"
#include "modules/url/protocols/comm.h"
class DOM_LSParser_ThreadListener
: public ES_ThreadListener
{
private:
DOM_LSParser *parser;
ES_Thread *thread;
public:
DOM_LSParser_ThreadListener(DOM_LSParser *parser, ES_Thread *thread)
: parser(parser)
, thread(thread)
{
thread->AddListener(this);
}
virtual ~DOM_LSParser_ThreadListener()
{
ES_ThreadListener::Remove();
}
virtual OP_STATUS Signal(ES_Thread *, ES_ThreadSignal signal)
{
if (signal == ES_SIGNAL_CANCELLED)
parser->CallingThreadCancelled();
return OpStatus::OK;
}
};
class DOM_LSParser_LoadHandler
: public DOM_LSLoadHandler
{
public:
DOM_LSParser_LoadHandler(DOM_Runtime *origining_runtime, DOM_LSParser *parser, DOM_LSLoader *loader)
: origining_runtime(origining_runtime)
, parser(parser)
, loader(loader)
, headers_handled(FALSE)
, security_callback(NULL)
{
}
virtual ~DOM_LSParser_LoadHandler()
{
if (security_callback)
security_callback->Release();
}
virtual OP_STATUS OnHeadersReceived(URL &url);
virtual OP_BOOLEAN OnRedirect(URL &url, URL &moved_to_url);
virtual OP_STATUS OnLoadingFailed(URL &url, BOOL is_network_error);
#ifdef PROGRESS_EVENTS_SUPPORT
virtual OP_BOOLEAN OnTimeout();
virtual unsigned GetTimeoutMS();
virtual OP_STATUS OnProgressTick();
virtual OP_STATUS OnUploadProgress(OpFileLength bytes);
#endif // PROGRESS_EVENTS_SUPPORT
private:
DOM_Runtime *origining_runtime;
DOM_LSParser *parser;
DOM_LSLoader *loader;
BOOL headers_handled;
OpSecurityCallbackHelper *security_callback;
};
/* Loading an external resource is gated on passing a DOM_LOADSAVE security
check. This callback handles the interaction with the security manager
during that check. */
class DOM_LSParser_SecurityCallback
: public OpSecurityCheckCallback
, public ES_ThreadListener
{
public:
DOM_LSParser_SecurityCallback(DOM_LSParser *parser)
: parser(parser)
, error(OpStatus::OK)
, is_finished(FALSE)
, is_allowed(FALSE)
, thread(NULL)
{
}
virtual void OnSecurityCheckSuccess(BOOL allowed, ChoicePersistenceType type = PERSISTENCE_NONE)
{
is_allowed = allowed;
if (parser)
parser->OnSecurityCheckResult(allowed);
Finish();
}
virtual void OnSecurityCheckError(OP_STATUS status)
{
error = status;
if (parser)
parser->OnSecurityCheckResult(FALSE);
Finish();
}
BOOL IsFinished() { return is_finished; }
BOOL IsAllowed() { return is_allowed; }
void Cancel()
{
OP_ASSERT(!is_finished);
thread = NULL;
parser = NULL;
ES_ThreadListener::Remove();
}
void BlockOnSecurityCheck(ES_Thread *t)
{
OP_ASSERT(!thread || !t);
thread = t;
if (thread)
{
thread->AddListener(this);
thread->Block();
}
}
virtual OP_STATUS Signal(ES_Thread *, ES_ThreadSignal signal)
{
if (signal == ES_SIGNAL_CANCELLED || signal == ES_SIGNAL_FAILED)
{
ES_ThreadListener::Remove();
thread = NULL;
}
return OpStatus::OK;
}
private:
void Finish()
{
if (!is_finished)
{
is_finished = TRUE;
if (thread)
{
ES_ThreadListener::Remove();
thread->Unblock();
}
thread = NULL;
}
if (!parser)
OP_DELETE(this);
}
DOM_LSParser *parser;
OP_STATUS error;
BOOL is_finished;
BOOL is_allowed;
ES_Thread *thread;
};
OP_BOOLEAN
DOM_LSParser_LoadHandler::OnHeadersReceived(URL &url)
{
#if defined(CORS_SUPPORT) && defined(DOM_HTTP_SUPPORT)
if (DOM_XMLHttpRequest *xmlhttprequest = parser->GetXMLHttpRequest())
if (OpCrossOrigin_Request *cross_origin_request = xmlhttprequest->GetCrossOriginRequest())
{
/* Perform final resource sharing check for CORS. */
BOOL allowed = FALSE;
URL target_url = url.GetAttribute(URL::KMovedToURL, URL::KFollowRedirect);
if (!target_url.IsValid())
target_url = url;
OpSecurityContext source_context(origining_runtime, cross_origin_request);
OpSecurityContext target_context(target_url);
/* This is a sync security check. */
OP_STATUS status = OpSecurityManager::CheckSecurity(OpSecurityManager::CORS_RESOURCE_ACCESS, source_context, target_context, allowed);
if (OpStatus::IsMemoryError(status))
return status;
if (OpStatus::IsError(status))
allowed = FALSE;
if (parser)
parser->OnSecurityCheckResult(allowed);
if (allowed)
RETURN_IF_ERROR(xmlhttprequest->SetStatus(url));
else
{
ES_Thread *interrupt_thread = parser->GetContentHandler()->GetInterruptThread();
xmlhttprequest->SetNetworkErrorFlag();
RETURN_IF_ERROR(xmlhttprequest->SetReadyState(DOM_XMLHttpRequest::READYSTATE_LOADED, interrupt_thread));
return OpStatus::ERR;
}
}
#endif // CORS_SUPPORT && DOM_HTTP_SUPPORT
#ifdef DOM_HTTP_SUPPORT
if (DOM_XMLHttpRequest *xmlhttprequest = parser->GetXMLHttpRequest())
{
/* CORS completed, allowing the response to be used. */
if (!headers_handled)
{
headers_handled = TRUE;
RETURN_IF_ERROR(xmlhttprequest->SetResponseHeaders(url));
}
/* If HEAD, stop loading after having processed the payload. */
if (uni_stri_eq(xmlhttprequest->GetMethod(), "HEAD"))
return OpBoolean::IS_FALSE;
}
#endif // DOM_HTTP_SUPPORT
return OpBoolean::IS_TRUE;
}
OP_BOOLEAN
DOM_LSParser_LoadHandler::OnRedirect(URL &url, URL &moved_to_url)
{
/* Assume that there will only be one redirect "in flight" at any one time. */
OP_ASSERT(!security_callback || security_callback->IsFinished());
if (!security_callback)
RETURN_OOM_IF_NULL(security_callback = OP_NEW(OpSecurityCallbackHelper, (loader)));
else
security_callback->Reset();
#ifdef DOM_HTTP_SUPPORT
DOM_XMLHttpRequest *xmlhttprequest = parser->GetXMLHttpRequest();
#endif // DOM_HTTP_SUPPORT
#if defined(CORS_SUPPORT) && defined(DOM_HTTP_SUPPORT)
OpCrossOrigin_Request *cross_origin_request = xmlhttprequest ? xmlhttprequest->GetCrossOriginRequest() : NULL;
if (!cross_origin_request && xmlhttprequest)
{
OP_BOOLEAN result = xmlhttprequest->CheckIfCrossOriginCandidate(moved_to_url);
RETURN_IF_ERROR(result);
if (result == OpBoolean::IS_TRUE)
{
/* Check if a cross-origin redirect has been initiated for the redirect target,
the original request being to a same-origin target but which became cross-origin
when redirecting. */
if (OpCrossOrigin_Manager *manager = g_secman_instance->GetCrossOriginManager(url))
cross_origin_request = manager->FindNetworkRedirect(url);
if (cross_origin_request)
RETURN_IF_ERROR(xmlhttprequest->SetCrossOriginRequest(cross_origin_request));
else
{
RETURN_IF_ERROR(xmlhttprequest->CreateCrossOriginRequest(loader->GetURL(), moved_to_url));
cross_origin_request = xmlhttprequest->GetCrossOriginRequest();
}
security_callback->OnSecurityCheckSuccess(TRUE);
return OpBoolean::IS_TRUE;
}
}
if (cross_origin_request)
cross_origin_request->SetInRedirect();
OpSecurityContext source_context(origining_runtime, cross_origin_request);
#else
OpSecurityContext source_context(origining_runtime);
#endif // CORS_SUPPORT && DOM_HTTP_SUPPORT
OpSecurityContext redirect_context(moved_to_url, url);
OP_STATUS status = OpSecurityManager::CheckSecurity(OpSecurityManager::DOM_LOADSAVE, source_context, redirect_context, security_callback);
if (OpStatus::IsError(status) || !security_callback->IsAllowed() && security_callback->IsFinished())
{
#ifdef DOM_HTTP_SUPPORT
if (xmlhttprequest)
{
RETURN_IF_ERROR(xmlhttprequest->SetStatus(url));
xmlhttprequest->SetNetworkErrorFlag();
RETURN_IF_ERROR(xmlhttprequest->SetReadyState(DOM_XMLHttpRequest::READYSTATE_LOADED, parser->GetContentHandler()->GetInterruptThread()));
}
#endif // DOM_HTTP_SUPPORT
return OpStatus::ERR;
}
else if (!security_callback->IsFinished())
return OpBoolean::IS_FALSE;
else
return OpBoolean::IS_TRUE;
}
OP_STATUS
DOM_LSParser_LoadHandler::OnLoadingFailed(URL &url, BOOL is_network_error)
{
#ifdef DOM_HTTP_SUPPORT
DOM_XMLHttpRequest *xmlhttprequest = parser->GetXMLHttpRequest();
#endif // DOM_HTTP_SUPPORT
#if defined(CORS_SUPPORT) && defined(DOM_HTTP_SUPPORT)
OpCrossOrigin_Request *cross_origin_request = NULL;
if (is_network_error && xmlhttprequest)
{
cross_origin_request = xmlhttprequest->GetCrossOriginRequest();
if (!cross_origin_request)
{
/* Check if a cross-origin redirect was attempted for 'url', which
failed. */
if (OpCrossOrigin_Manager *manager = g_secman_instance->GetCrossOriginManager(url))
{
cross_origin_request = manager->FindNetworkRedirect(url);
if (cross_origin_request)
RETURN_IF_ERROR(xmlhttprequest->SetCrossOriginRequest(cross_origin_request));
}
}
}
if (cross_origin_request)
{
cross_origin_request->SetNetworkError();
/* The cross-origin access ran into a network error; forcibly
signal this as a security error failure to propagate the
required network error back to the user. */
parser->OnSecurityCheckResult(FALSE);
}
#endif // CORS_SUPPORT && DOM_HTTP_SUPPORT
#ifdef DOM_HTTP_SUPPORT
if (xmlhttprequest)
{
if (is_network_error)
RETURN_IF_ERROR(xmlhttprequest->SetNetworkError(parser->GetContentHandler()->GetInterruptThread()));
else
RETURN_IF_ERROR(xmlhttprequest->SetStatus(url));
if (!headers_handled)
{
headers_handled = TRUE;
return xmlhttprequest->SetResponseHeaders(url);
}
}
#endif // DOM_HTTP_SUPPORT
return OpStatus::OK;
}
#ifdef PROGRESS_EVENTS_SUPPORT
OP_BOOLEAN
DOM_LSParser_LoadHandler::OnTimeout()
{
#ifdef DOM_HTTP_SUPPORT
if (DOM_XMLHttpRequest *xmlhttprequest = parser->GetXMLHttpRequest())
return xmlhttprequest->HandleTimeout();
#endif // DOM_HTTP_SUPPORT
return OpBoolean::IS_FALSE;
}
unsigned
DOM_LSParser_LoadHandler::GetTimeoutMS()
{
#ifdef DOM_HTTP_SUPPORT
if (DOM_XMLHttpRequest *xmlhttprequest = parser->GetXMLHttpRequest())
return xmlhttprequest->GetTimeoutMS();
#endif // DOM_HTTP_SUPPORT
return 0;
}
OP_STATUS
DOM_LSParser_LoadHandler::OnProgressTick()
{
#ifdef DOM_HTTP_SUPPORT
if (DOM_XMLHttpRequest *xmlhttprequest = parser->GetXMLHttpRequest())
return xmlhttprequest->HandleProgressTick();
#endif // DOM_HTTP_SUPPORT
return OpStatus::OK;
}
OP_STATUS
DOM_LSParser_LoadHandler::OnUploadProgress(OpFileLength bytes)
{
#ifdef DOM_HTTP_SUPPORT
if (DOM_XMLHttpRequest *xmlhttprequest = parser->GetXMLHttpRequest())
return xmlhttprequest->HandleUploadProgress(bytes);
#endif // DOM_HTTP_SUPPORT
return OpStatus::OK;
}
#endif // PROGRESS_EVENTS_SUPPORT
DOM_LSParser::DOM_LSParser(BOOL async)
: loader(NULL)
, contenthandler(NULL)
, async(async)
, busy(FALSE)
, failed(FALSE)
, oom(FALSE)
, need_reset(FALSE)
, is_fragment(FALSE)
, is_document_load(FALSE)
, document_info_handled(FALSE)
, with_dom_config(TRUE)
, is_parsing_error_document(FALSE)
, config(NULL)
, filter(NULL)
, whatToShow(static_cast<unsigned>(SHOW_ALL))
, action(ACTION_APPEND_AS_CHILDREN)
, calling_thread(NULL)
, calling_thread_listener(NULL)
, eventtarget(NULL)
, document(NULL)
, first_top_node(NULL)
, context(NULL)
, parent(NULL)
, before(NULL)
, input(NULL)
, uri(NULL)
, string(NULL)
, keep_alive_id(0)
, restart_systemId(NULL)
, restart_stringData(NULL)
, restart_parent(NULL)
, restart_before(NULL)
, has_started_parsing(FALSE)
, security_check_passed(FALSE)
, security_callback(NULL)
, load_handler(NULL)
#ifdef DOM_HTTP_SUPPORT
, xmlhttprequest(NULL)
#endif // DOM_HTTP_SUPPORT
, parse_document(TRUE)
{
}
DOM_LSParser::~DOM_LSParser()
{
keep_alive_id = 0;
need_reset = TRUE;
Reset();
if (security_callback && !security_callback->IsFinished())
security_callback->Cancel();
else
OP_DELETE(security_callback);
OP_DELETE(load_handler);
}
OP_STATUS
DOM_LSParser::Start(URL url, const uni_char *uri_, const uni_char *string_, DOM_Node *parent, DOM_Node *before, DOM_Runtime *origining_runtime, BOOL &is_security_error)
{
if (uri_)
RETURN_IF_ERROR(UniSetStr(uri, uri_));
if (string_)
RETURN_IF_ERROR(UniSetStr(string, string_));
is_security_error = TRUE;
BOOL allowed = FALSE;
URL ref_url;
if (uri || !url.IsEmpty())
{
DOM_Runtime* object_runtime = GetRuntime();
if (FramesDocument *obj_doc = object_runtime->GetFramesDocument())
ref_url = obj_doc->GetURL();
else
{
#ifdef DOM_WEBWORKERS_SUPPORT
if (GetEnvironment()->GetWorkerController()->GetWorkerObject())
ref_url = GetEnvironment()->GetWorkerController()->GetWorkerObject()->GetLocationURL();
else
#endif // DOM_WEBWORKERS_SUPPORT
ref_url = origining_runtime->GetFramesDocument()->GetURL();
}
if (uri)
url = g_url_api->GetURL(ref_url, uri, FALSE);
#if defined(CORS_SUPPORT) && defined(DOM_HTTP_SUPPORT)
if (xmlhttprequest && xmlhttprequest->WantCrossOriginRequest() && !xmlhttprequest->GetCrossOriginRequest())
CALL_FAILED_IF_ERROR(xmlhttprequest->CreateCrossOriginRequest(ref_url, url));
OpCrossOrigin_Request *cross_origin_request = xmlhttprequest ? xmlhttprequest->GetCrossOriginRequest() : NULL;
#endif // CORS_SUPPORT && DOM_HTTP_SUPPORT
// The request will be made with the object's security rather than the scripts.
// See CORE-15635 for the background
#ifdef CORS_SUPPORT
OpSecurityContext source_context(object_runtime, cross_origin_request);
#else
OpSecurityContext source_context(object_runtime);
#endif // CORS_SUPPORT
OpSecurityContext target_context(url, ref_url);
if (!security_callback)
RETURN_OOM_IF_NULL(security_callback = OP_NEW(DOM_LSParser_SecurityCallback, (this)));
OP_STATUS status = OpSecurityManager::CheckSecurity(OpSecurityManager::DOM_LOADSAVE, source_context, target_context, security_callback);
if (OpStatus::IsError(status))
{
OP_DELETE(security_callback);
security_callback = NULL;
#if defined(CORS_SUPPORT) && defined(DOM_HTTP_SUPPORT)
if (xmlhttprequest && cross_origin_request && cross_origin_request->IsNetworkError())
/* Accessing a non-existent URL is better reported as a non-security error. */
RETURN_IF_ERROR(xmlhttprequest->UpdateCrossOriginStatus(url, FALSE, is_security_error));
#endif // CORS_SUPPORT && DOM_HTTP_SUPPORT
return status;
}
if (!security_callback->IsFinished())
{
security_callback->BlockOnSecurityCheck(GetCurrentThread(origining_runtime));
return OpStatus::ERR;
}
allowed = security_callback->IsAllowed();
#if defined(CORS_SUPPORT) && defined(DOM_HTTP_SUPPORT)
if (xmlhttprequest && cross_origin_request)
RETURN_IF_ERROR(xmlhttprequest->UpdateCrossOriginStatus(url, allowed, is_security_error));
else
#endif // CORS_SUPPORT && DOM_HTTP_SUPPORT
#ifdef DOM_HTTP_SUPPORT
if (xmlhttprequest && !allowed)
xmlhttprequest->SetNetworkErrorFlag();
#endif // DOM_HTTP_SUPPORT
if (!allowed)
return OpStatus::ERR;
}
RETURN_OOM_IF_NULL(loader = OP_NEW(DOM_LSLoader, (this)));
if (!parse_document)
loader->DisableParsing(TRUE);
if (parent && !parent->IsA(DOM_TYPE_DOCUMENT))
loader->SetParsingFragment();
RETURN_OOM_IF_NULL(contenthandler = OP_NEW(DOM_LSContentHandler, (this, loader, whatToShow, filter)));
loader->SetContentHandler(contenthandler);
contenthandler->SetInsertionPoint(parent, before);
if (!load_handler)
RETURN_OOM_IF_NULL(load_handler = OP_NEW(DOM_LSParser_LoadHandler, (origining_runtime, this, loader)));
loader->SetLoadHandler(load_handler);
OP_STATUS status;
if (uri || !url.IsEmpty())
{
parsedurl = url;
if (!allowed)
if (url.Type() == URL_FILE && ref_url.Type() == URL_FILE)
/* If we refused to load a file from another file,
pretend it was there but was empty. */
status = loader->Construct(NULL, NULL, UNI_L(""), is_fragment, load_handler);
else
return OpStatus::ERR;
#ifdef CORS_SUPPORT
if (OpCrossOrigin_Request *cross_origin_request = xmlhttprequest ? xmlhttprequest->GetCrossOriginRequest() : NULL)
url = cross_origin_request->GetURL();
#endif // CORS_SUPPORT
status = loader->Construct(&url, &ref_url, NULL, is_fragment, load_handler);
}
else
status = loader->Construct(NULL, NULL, string, is_fragment, load_handler);
if (OpStatus::IsError(status))
{
OP_DELETE(loader);
loader = NULL;
OP_DELETE(load_handler);
load_handler = NULL;
is_security_error = FALSE;
return status;
}
RETURN_IF_ERROR(SetKeepAlive());
busy = TRUE;
return OpStatus::OK;
}
OP_STATUS
DOM_LSParser::SetKeepAlive()
{
if (keep_alive_id != 0)
return OpStatus::OK;
DOM_Object *window = GetEnvironment()->GetWindow();
if (window->IsA(DOM_TYPE_WINDOW))
RETURN_IF_ERROR(static_cast<JS_Window *>(window)->AddKeepAlive(this, &keep_alive_id));
#ifdef DOM_WEBWORKERS_SUPPORT
else
{
OP_ASSERT(window->IsA(DOM_TYPE_WEBWORKERS_WORKER));
RETURN_IF_ERROR(static_cast<DOM_WebWorker *>(window)->AddKeepAlive(this, &keep_alive_id));
}
#else
else
{
OP_ASSERT(!"Unexpected window object; cannot happen");
return OpStatus::ERR;
}
#endif // DOM_WEBWORKERS_SUPPORT
OP_ASSERT(keep_alive_id);
return OpStatus::OK;
}
void
DOM_LSParser::UnsetKeepAlive()
{
if (keep_alive_id == 0)
return;
DOM_Object *window = GetEnvironment()->GetWindow();
if (window->IsA(DOM_TYPE_WINDOW))
static_cast<JS_Window *>(window)->RemoveKeepAlive(keep_alive_id);
#ifdef DOM_WEBWORKERS_SUPPORT
else
{
OP_ASSERT(window->IsA(DOM_TYPE_WEBWORKERS_WORKER));
static_cast<DOM_WebWorker *>(window)->RemoveKeepAlive(keep_alive_id);
}
#else
else
{
OP_ASSERT(!"Unexpected window object; cannot happen");
}
#endif // DOM_WEBWORKERS_SUPPORT
keep_alive_id = 0;
}
OP_STATUS
DOM_LSParser::ResetCallingThread()
{
OP_NEW_DBG("DOM_LSParser::ResetCallingThread", "DOM3LS");
if (calling_thread)
{
ES_Thread *thread = calling_thread;
if (calling_thread_listener)
calling_thread_listener->Remove();
OP_DELETE(calling_thread_listener);
calling_thread = NULL;
calling_thread_listener = NULL;
return thread->Unblock();
}
else
return OpStatus::OK;
}
OP_STATUS
DOM_LSParser::UnblockCallingThread()
{
if (calling_thread)
{
OP_STATUS status = calling_thread->Unblock();
calling_thread = NULL;
return status;
}
else
return OpStatus::OK;
}
/* static */ OP_STATUS
#ifdef DOM_HTTP_SUPPORT
DOM_LSParser::Make(DOM_LSParser *&parser, DOM_EnvironmentImpl *environment, BOOL async, DOM_XMLHttpRequest *xmlhttprequest)
#else
DOM_LSParser::Make(DOM_LSParser *&parser, DOM_EnvironmentImpl *environment, BOOL async)
#endif // DOM_HTTP_SUPPORT
{
DOM_Runtime *runtime = environment->GetDOMRuntime();
RETURN_IF_ERROR(DOMSetObjectRuntime(parser = OP_NEW(DOM_LSParser, (async)), runtime, runtime->GetPrototype(DOM_Runtime::LSPARSER_PROTOTYPE), "LSParser"));
#ifdef DOM_HTTP_SUPPORT
if (xmlhttprequest)
{
parser->with_dom_config = FALSE;
parser->xmlhttprequest = xmlhttprequest;
}
else
#endif // DOM_HTTP_SUPPORT
/* Create DOMConfiguration on demand; a good candidate as it is not the lightest and not often used. */
parser->with_dom_config = TRUE;
#ifdef DOM_WEBWORKERS_SUPPORT
if (environment->GetWorkerController()->GetWorkerObject())
parser->parse_document = FALSE;
#endif // DOM_WEBWORKERS_SUPPORT
return OpStatus::OK;
}
/* virtual */ ES_GetState
DOM_LSParser::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
Reset();
switch (property_name)
{
case OP_ATOM_async:
DOMSetBoolean(value, async);
return GET_SUCCESS;
case OP_ATOM_busy:
DOMSetBoolean(value, busy);
return GET_SUCCESS;
case OP_ATOM_domConfig:
if (with_dom_config && !config)
GET_FAILED_IF_ERROR(DOM_DOMConfiguration::Make(config, GetEnvironment()));
DOMSetObject(value, config);
return GET_SUCCESS;
case OP_ATOM_filter:
DOMSetObject(value, filter);
return GET_SUCCESS;
}
return GET_FAILED;
}
/* virtual */ ES_PutState
DOM_LSParser::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
Reset();
if (GetName(property_name, NULL, origining_runtime) == GET_SUCCESS)
if (property_name == OP_ATOM_filter)
if (value->type != VALUE_OBJECT)
return PutNameDOMException(TYPE_MISMATCH_ERR, value);
else
{
filter = value->value.object;
ES_Value wts;
OP_BOOLEAN result;
PUT_FAILED_IF_ERROR(result = origining_runtime->GetName(filter, UNI_L("whatToShow"), &wts));
if (result == OpBoolean::IS_TRUE && wts.type == VALUE_NUMBER)
whatToShow = (int) wts.value.number;
else
whatToShow = static_cast<unsigned>(SHOW_ALL);
return PUT_SUCCESS;
}
else
return PUT_READ_ONLY;
else
return PUT_FAILED;
}
/* virtual */ void
DOM_LSParser::GCTrace()
{
Reset();
if (contenthandler)
contenthandler->GCTrace();
if (eventtarget)
eventtarget->GCTrace();
GCMark(filter);
GCMark(config);
GCMark(document);
GCMark(first_top_node);
GCMark(context);
GCMark(parent);
GCMark(before);
if (loader)
loader->GCTrace();
GCMark(restart_parent);
GCMark(restart_before);
#ifdef DOM_HTTP_SUPPORT
GCMark(xmlhttprequest);
#endif // DOM_HTTP_SUPPORT
}
DOM_Document *
DOM_LSParser::GetOwnerDocument()
{
return parent ? parent->GetOwnerDocument() : document;
}
OP_STATUS
DOM_LSParser::HandleDocumentInfo(const XMLDocumentInformation &docinfo)
{
DOM_Node *doc;
if (!document_info_handled)
{
document_info_handled = TRUE;
if ((doc = document) || (doc = context) && context->IsA(DOM_TYPE_DOCUMENT) && action == ACTION_REPLACE_CHILDREN)
{
RETURN_IF_ERROR(contenthandler->HandleDocumentInfo(docinfo));
if (!parsedurl.IsEmpty())
((DOM_Document *) doc)->SetURL(parsedurl);
}
}
return OpStatus::OK;
}
OP_STATUS
DOM_LSParser::HandleFinished()
{
UnsetKeepAlive();
ES_Thread *interrupt_thread = calling_thread;
RETURN_IF_ERROR(ResetCallingThread());
#ifdef DOM_HTTP_SUPPORT
if (xmlhttprequest)
{
if (parse_document)
xmlhttprequest->SetResponseXML(document);
RETURN_IF_ERROR(xmlhttprequest->SetReadyState(DOM_XMLHttpRequest::READYSTATE_LOADED, interrupt_thread));
}
#endif // DOM_HTTP_SUPPORT
if (async)
{
if (!context && eventtarget)
{
if (!input)
{
RETURN_IF_ERROR(DOM_LSInput::Make(input, GetEnvironment(), string, uri));
RETURN_IF_ERROR(PutPrivate(DOM_PRIVATE_input, input));
}
DOM_LSLoadEvent *event;
RETURN_IF_ERROR(DOM_LSLoadEvent::Make(event, this, document, input));
RETURN_IF_ERROR(GetEnvironment()->SendEvent(event));
}
#ifdef DOM_HTTP_SUPPORT
if (!xmlhttprequest || !xmlhttprequest->HasEventHandlerAndUnsentEvents())
need_reset = TRUE;
#else
need_reset = TRUE;
#endif // DOM_HTTP_SUPPORT
}
if (is_document_load)
{
DOM_Runtime *runtime = GetEnvironment()->GetDOMRuntime();
DOM_Event *event;
RETURN_IF_ERROR(DOM_Object::DOMSetObjectRuntime(event = OP_NEW(DOM_Event, ()), runtime, runtime->GetPrototype(DOM_Runtime::EVENT_PROTOTYPE), "Event"));
event->InitEvent(ONLOAD, context);
if (async)
RETURN_IF_ERROR(GetEnvironment()->SendEvent(event));
else
RETURN_IF_ERROR(GetEnvironment()->SendEvent(event, interrupt_thread));
}
return OpStatus::OK;
}
OP_STATUS
DOM_LSParser::HandleProgress(unsigned position, unsigned total)
{
if (async && !context && eventtarget)
{
DOM_LSProgressEvent *event;
RETURN_IF_ERROR(DOM_LSProgressEvent::Make(event, this, input, position, total));
OP_BOOLEAN result = GetEnvironment()->SendEvent(event);
if (OpStatus::IsError(result))
return result;
}
return OpStatus::OK;
}
OP_STATUS
DOM_LSParser::SignalError(const uni_char *message, const uni_char *type, unsigned line, unsigned column, unsigned byteOffset, unsigned charOffset)
{
failed = need_reset = TRUE;
UnsetKeepAlive();
ES_Thread *interrupt_thread = calling_thread;
RETURN_IF_ERROR(ResetCallingThread());
/* Note: the default error-handler is 'null', hence no need to force creation
of the DOMConfiguration object here to look that up. */
if (config)
{
ES_Value value;
RETURN_IF_ERROR(config->GetParameter(UNI_L("error-handler"), &value));
if (value.type == VALUE_OBJECT)
{
DOM_EnvironmentImpl *environment = GetEnvironment();
ES_AsyncInterface *asyncif = environment->GetAsyncInterface();
ES_Object *location;
RETURN_IF_ERROR(DOM_DOMLocator::Make(location, environment, line, column, byteOffset, charOffset, NULL, uri));
ES_Object *error;
RETURN_IF_ERROR(DOM_DOMError::Make(error, environment, DOM_DOMError::SEVERITY_FATAL_ERROR, message, type, NULL, NULL, location));
ES_Value arguments[1];
DOMSetObject(&arguments[0], error);
if (op_strcmp(ES_Runtime::GetClass(value.value.object), "Function") == 0)
RETURN_IF_ERROR(asyncif->CallFunction(value.value.object, NULL, 1, arguments, NULL, interrupt_thread));
else
RETURN_IF_ERROR(asyncif->CallMethod(value.value.object, UNI_L("handleError"), 1, arguments, NULL, interrupt_thread));
}
}
return OpStatus::OK;
}
void
DOM_LSParser::SignalOOM()
{
oom = need_reset = TRUE;
UnsetKeepAlive();
OpStatus::Ignore(ResetCallingThread());
}
void
DOM_LSParser::NewTopNode(DOM_Node *node)
{
if (!first_top_node)
first_top_node = node;
}
void
DOM_LSParser::Reset()
{
if (need_reset)
{
UnsetKeepAlive();
OP_DELETE(loader);
loader = NULL;
OP_DELETE(contenthandler);
contenthandler = NULL;
busy = FALSE;
need_reset = FALSE;
document = NULL;
first_top_node = context = parent = before = NULL;
input = NULL;
OP_DELETEA(uri);
uri = NULL;
OP_DELETEA(string);
string = NULL;
restart_url = URL();
OP_DELETEA(restart_systemId);
restart_systemId = NULL;
OP_DELETEA(restart_stringData);
restart_stringData = NULL;
restart_parent = NULL;
restart_before = NULL;
}
}
void
DOM_LSParser::CallingThreadCancelled()
{
calling_thread = NULL;
calling_thread_listener = NULL;
if (contenthandler)
contenthandler->SetCallingThread(NULL);
if (loader)
{
OP_DELETE(loader);
loader = NULL;
}
}
#ifdef DOM_HTTP_SUPPORT
DOM_XMLHttpRequest *
DOM_LSParser::GetXMLHttpRequest()
{
return xmlhttprequest;
}
#endif // DOM_HTTP_SUPPORT
void
DOM_LSParser::SetParseLoadedData(BOOL enable)
{
parse_document = enable;
if (loader)
loader->DisableParsing(!parse_document);
}
/* static */ void
DOM_LSParser::ConstructLSParserObjectL(ES_Object *object, DOM_Runtime *runtime)
{
PutNumericConstantL(object, "ACTION_APPEND_AS_CHILDREN", ACTION_APPEND_AS_CHILDREN, runtime);
PutNumericConstantL(object, "ACTION_REPLACE_CHILDREN", ACTION_REPLACE_CHILDREN, runtime);
PutNumericConstantL(object, "ACTION_INSERT_BEFORE", ACTION_INSERT_BEFORE, runtime);
PutNumericConstantL(object, "ACTION_INSERT_AFTER", ACTION_INSERT_AFTER, runtime);
PutNumericConstantL(object, "ACTION_REPLACE", ACTION_REPLACE, runtime);
}
/* static */ void
DOM_LSParser::ConstructLSParserFilterObjectL(ES_Object *object, DOM_Runtime *runtime)
{
PutNumericConstantL(object, "FILTER_ACCEPT", FILTER_ACCEPT, runtime);
PutNumericConstantL(object, "FILTER_REJECT", FILTER_REJECT, runtime);
PutNumericConstantL(object, "FILTER_SKIP", FILTER_SKIP, runtime);
PutNumericConstantL(object, "FILTER_INTERRUPT", FILTER_INTERRUPT, runtime);
}
/* static */ void
DOM_LSParser::ConstructDOMImplementationLSObjectL(ES_Object *object, DOM_Runtime *runtime)
{
PutNumericConstantL(object, "MODE_SYNCHRONOUS", MODE_SYNCHRONOUS, runtime);
PutNumericConstantL(object, "MODE_ASYNCHRONOUS", MODE_ASYNCHRONOUS, runtime);
}
/* static */ int
DOM_LSParser::abort(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(parser, DOM_TYPE_LSPARSER, DOM_LSParser);
parser->need_reset = TRUE;
parser->Reset();
CALL_FAILED_IF_ERROR(parser->ResetCallingThread());
return ES_FAILED;
}
void
DOM_LSParser::OnSecurityCheckResult(BOOL allowed)
{
security_check_passed = allowed;
}
#ifdef DOM_HTTP_SUPPORT
void
DOM_LSParser::SetBaseURL()
{
if (FramesDocument* frames_doc = GetRuntime()->GetFramesDocument())
if (frames_doc->GetLogicalDocument() && frames_doc->GetLogicalDocument()->GetBaseURL())
base_url = *frames_doc->GetLogicalDocument()->GetBaseURL();
else
base_url = frames_doc->GetURL();
#ifdef DOM_WEBWORKERS_SUPPORT
else if (GetEnvironment()->GetWorkerController()->GetWorkerObject())
base_url = GetEnvironment()->GetWorkerController()->GetWorkerObject()->GetLocationURL();
#endif // DOM_WEBWORKERS_SUPPORT
else
base_url = URL();
}
#endif // DOM_HTTP_SUPPORT
/* static */ int
DOM_LSParser::parse(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime, int data)
{
DOM_LSParser *parser;
if (argc >= 0)
{
DOM_THIS_OBJECT_EXISTING(parser, DOM_TYPE_LSPARSER, DOM_LSParser);
if (parser->busy ||
!parser->GetFramesDocument()
#ifdef DOM_WEBWORKERS_SUPPORT
&& !parser->GetEnvironment()->GetWorkerController()->GetWorkerObject()
#endif // DOM_WEBWORKERS_SUPPORT
)
return DOM_CALL_DOMEXCEPTION(INVALID_STATE_ERR);
parser->failed = FALSE;
parser->document_info_handled = FALSE;
DOM_EnvironmentImpl *environment = parser->GetEnvironment();
const uni_char *stringData = NULL, *systemId = NULL;
URL url;
if (data == 0 || data == 2)
{
if (data == 0)
DOM_CHECK_ARGUMENTS("o");
else
DOM_CHECK_ARGUMENTS("oon");
parser->input = argv[0].value.object;
CALL_FAILED_IF_ERROR(parser->PutPrivate(DOM_PRIVATE_input, parser->input));
#ifdef DOM_HTTP_SUPPORT
ES_Object *byteStream;
CALL_FAILED_IF_ERROR(DOM_LSInput::GetByteStream(byteStream, parser->input, environment));
if (byteStream)
{
if (DOM_Object *object = DOM_HOSTOBJECT(byteStream, DOM_Object))
if (object->IsA(DOM_TYPE_HTTPINPUTSTREAM))
{
/* An XMLHttpRequest URL is resolved in the document it was created, see CORE-2975. */
if (parser->base_url.IsEmpty())
{
parser->SetBaseURL();
if (parser->base_url.IsEmpty())
return DOM_CALL_DOMEXCEPTION(INVALID_STATE_ERR);
}
DOM_HTTPInputStream *input_stream = static_cast<DOM_HTTPInputStream *>(object);
CALL_FAILED_IF_ERROR(input_stream->GetRequest()->GetURL(url, parser->base_url));
CALL_FAILED_IF_ERROR(parser->xmlhttprequest->SetCredentials(url));
}
if (url.IsEmpty())
return DOM_CALL_DOMEXCEPTION(NOT_SUPPORTED_ERR);
}
else
#endif // DOM_HTTP_SUPPORT
{
CALL_FAILED_IF_ERROR(DOM_LSInput::GetStringData(stringData, parser->input, environment));
if (!stringData)
{
CALL_FAILED_IF_ERROR(DOM_LSInput::GetSystemId(systemId, parser->input, environment));
if (!systemId)
return DOM_CALL_DOMEXCEPTION(NOT_SUPPORTED_ERR);
}
}
}
else
{
DOM_CHECK_ARGUMENTS("s");
systemId = argv[0].value.string;
}
DOM_Node *parent = NULL, *before = NULL, *context = NULL;
BOOL removeContext = FALSE, removeContextChildren = FALSE;
if (data == 2)
{
DOM_ARGUMENT_OBJECT_EXISTING(context, 1, DOM_TYPE_NODE, DOM_Node);
unsigned actionArg = (unsigned) argv[2].value.number;
if (actionArg >= ACTION_APPEND_AS_CHILDREN && actionArg <= ACTION_REPLACE)
parser->action = actionArg;
parser->is_fragment = TRUE;
switch (parser->action)
{
case ACTION_APPEND_AS_CHILDREN:
parent = context;
break;
case ACTION_REPLACE_CHILDREN:
parent = context;
removeContextChildren = TRUE;
if (context->IsA(DOM_TYPE_DOCUMENT))
parser->is_fragment = FALSE;
break;
case ACTION_INSERT_BEFORE:
CALL_FAILED_IF_ERROR(context->GetParentNode(parent));
before = context;
break;
case ACTION_REPLACE:
removeContext = TRUE;
case ACTION_INSERT_AFTER:
CALL_FAILED_IF_ERROR(context->GetParentNode(parent));
CALL_FAILED_IF_ERROR(context->GetNextSibling(before));
}
if (!parent->IsA(DOM_TYPE_ELEMENT) && !parent->IsA(DOM_TYPE_DOCUMENTFRAGMENT))
if (parser->action != ACTION_REPLACE_CHILDREN || !parent->IsA(DOM_TYPE_DOCUMENT))
#ifdef DOM_SUPPORT_ENTITY
if (!parent->IsA(DOM_TYPE_ENTITY) || !((DOM_Entity *) parent)->IsBeingParsed())
#endif // DOM_SUPPORT_ENTITY
return DOM_CALL_DOMEXCEPTION(HIERARCHY_REQUEST_ERR);
}
else if (parser->parse_document)
{
CALL_FAILED_IF_ERROR(environment->ConstructDocumentNode());
CALL_FAILED_IF_ERROR(DOM_XMLDocument::Make(parser->document, ((DOM_Document *) environment->GetDocument())->GetDOMImplementation(), TRUE));
parent = parser->document;
context = NULL;
}
parser->context = context;
parser->parent = parent;
parser->before = before;
#ifdef DOM2_MUTATION_EVENTS
if (removeContext || removeContextChildren)
{
ES_Thread *thread = OP_NEW(DOM_LSParser_RemoveThread, (context, removeContextChildren));
if (!thread)
return ES_NO_MEMORY;
ES_Thread *interrupt_thread = GetCurrentThread(origining_runtime);
CALL_FAILED_IF_ERROR(interrupt_thread->GetScheduler()->AddRunnable(thread, interrupt_thread));
}
#else // DOM2_MUTATION_EVENTS
if (removeContext)
CALL_FAILED_IF_ERROR(context->RemoveFromParent(origining_runtime));
else if (removeContextChildren)
while (1)
{
DOM_Node *child;
CALL_FAILED_IF_ERROR(context->GetFirstChild(child));
if (!child)
break;
CALL_FAILED_IF_ERROR(child->RemoveFromParent(origining_runtime));
}
#endif // DOM2_MUTATION_EVENTS
BOOL is_security_error;
OP_STATUS status = parser->Start(url, systemId, stringData, parent, before, origining_runtime, is_security_error);
if (OpStatus::IsError(status))
{
if (OpStatus::IsMemoryError(status))
return ES_NO_MEMORY;
else if (!is_security_error)
return ES_FAILED;
else
{
if (parser->security_callback && !parser->security_callback->IsFinished())
{
/* The security callback has blocked the calling thread. */
parser->calling_thread = NULL;
parser->restart_url = url;
CALL_FAILED_IF_ERROR(UniSetStr(parser->restart_systemId, systemId));
CALL_FAILED_IF_ERROR(UniSetStr(parser->restart_stringData, stringData));
parser->restart_parent = parent;
parser->restart_before = before;
DOMSetObject(return_value, parser);
return parser->xmlhttprequest ? ES_SUSPEND | ES_ABORT : ES_SUSPEND | ES_RESTART;
}
return ES_EXCEPT_SECURITY;
}
}
else if (parser->security_callback && parser->security_callback->IsFinished())
{
parser->has_started_parsing = TRUE;
parser->security_check_passed = parser->security_callback->IsAllowed();
parser->calling_thread = NULL;
parser->restart_url = url;
CALL_FAILED_IF_ERROR(UniSetStr(parser->restart_systemId, systemId));
CALL_FAILED_IF_ERROR(UniSetStr(parser->restart_stringData, stringData));
parser->restart_parent = parent;
parser->restart_before = before;
}
else if (!parser->security_callback)
{
parser->has_started_parsing = TRUE;
parser->security_check_passed = TRUE;
}
else
OP_ASSERT(!"Security check not completed, but security check reported success? Cannot happen.");
goto start_parsing;
}
else
{
parser = DOM_VALUE2OBJECT(*return_value, DOM_LSParser);
int result;
if (!parser->has_started_parsing)
{
OP_DELETE(parser->security_callback);
parser->has_started_parsing = TRUE;
parser->security_callback = NULL;
BOOL is_security_error;
OP_STATUS status = parser->Start(parser->restart_url, parser->restart_systemId, parser->restart_stringData, parser->restart_parent, parser->restart_before, origining_runtime, is_security_error);
parser->restart_url = URL();
OP_DELETEA(parser->restart_systemId);
parser->restart_systemId = NULL;
OP_DELETEA(parser->restart_stringData);
parser->restart_stringData = NULL;
parser->restart_parent = NULL;
parser->restart_before = NULL;
if (OpStatus::IsError(status))
{
if (OpStatus::IsMemoryError(status))
return ES_NO_MEMORY;
else if (!is_security_error)
return ES_FAILED;
else
return ES_EXCEPT_SECURITY;
}
goto start_parsing;
}
if (parser->oom)
result = ES_NO_MEMORY;
if (!parser->security_check_passed)
result = ES_EXCEPT_SECURITY;
else if (parser->failed)
result = DOM_LSException::CallException(parser, DOM_LSException::PARSE_ERR, return_value);
#ifdef DOM_HTTP_SUPPORT
/* Caller will appropriately handle the timeout error / exception.
(The XHR2 spec has the "request error" step as throwing for all
sync errors, but this is incompatible with what others implement.) */
else if (parser->xmlhttprequest && parser->xmlhttprequest->HasTimeoutError())
result = ES_EXCEPTION;
#endif // DOM_HTTP_SUPPORT
else
{
if (parser->document)
DOMSetObject(return_value, parser->document);
else
DOMSetObject(return_value, parser->first_top_node);
result = ES_VALUE;
}
parser->need_reset = TRUE;
parser->Reset();
return result;
}
start_parsing:
if (parser->async && (data != 2 || parser->is_document_load))
{
DOMSetNull(return_value);
return ES_VALUE;
}
else
{
ES_Thread *calling_thread = GetCurrentThread(origining_runtime);
if (!(parser->calling_thread_listener = OP_NEW(DOM_LSParser_ThreadListener, (parser, calling_thread))))
return ES_NO_MEMORY;
parser->calling_thread = calling_thread;
if (parser->contenthandler)
parser->contenthandler->SetCallingThread(calling_thread);
DOMSetObject(return_value, parser);
calling_thread->Block();
return ES_SUSPEND | ES_RESTART;
}
}
#include "modules/dom/src/domglobaldata.h"
DOM_FUNCTIONS_START(DOM_LSParser)
DOM_FUNCTIONS_FUNCTION(DOM_LSParser, DOM_LSParser::abort, "abort", 0)
DOM_FUNCTIONS_FUNCTION(DOM_LSParser, DOM_Node::dispatchEvent, "dispatchEvent", 0)
DOM_FUNCTIONS_END(DOM_LSParser)
DOM_FUNCTIONS_WITH_DATA_START(DOM_LSParser)
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_LSParser, DOM_LSParser::parse, 0, "parse", 0)
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_LSParser, DOM_LSParser::parse, 1, "parseURI", "s-")
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_LSParser, DOM_LSParser::parse, 2, "parseWithContext", "--n-")
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_LSParser, DOM_Node::accessEventListener, 0, "addEventListener", "s-b-")
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_LSParser, DOM_Node::accessEventListener, 1, "removeEventListener", "s-b-")
#ifdef DOM3_EVENTS
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_LSParser, DOM_Node::accessEventListener, 2, "addEventListenerNS", "ss-b-")
DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_LSParser, DOM_Node::accessEventListener, 3, "removeEventListenerNS", "ss-b-")
#endif // DOM3_EVENTS
DOM_FUNCTIONS_WITH_DATA_END(DOM_LSParser)
#endif // DOM3_LOAD
|
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;
int main()
/*
endl = end line
cout = for formatted output operations
cin = for formatted input operations
*/
{
//cout example
int x;
x = 1;
cout << "Output sentence" << endl; // prints 'output' sentence on screen
cout << 120 << endl; // prints number 120 on screen
cout << x << endl; // prints the value of x on screen;
cout << "-----------------" << endl;
//cin example
string firstname;
string lastname;
cout << "Please enter your firstname: ";
cin >> firstname;
cout << "Please enter your surname: ";
cin >> lastname;
cout << "Hello " << firstname << " " << lastname << ".\n";
system("pause");
return 0;
}
|
#include <iostream>
const int SPECIAL = 1000000;
const int FIXED = 10000;
int main()
{
int i = 1;
int bef1 = 144, bef2 = 154; // 144 and 154 in that order works
int found1 = 0, found2, found3, found4;
int count =1;
int new1, new2;
int total;
std::cout << bef2 << " " << bef1<< std::endl;
while(i < SPECIAL)
{
i = bef1 + bef2;
bef2 = bef1;
bef1 = i;
std::cout << i << " "<< std::endl;
total = 0;
count++;
/*for (int f = 0; f < FIXED; f++)
{
new1 = i * f;
for (int j = 0 ; j < FIXED; j++)
{
new2 = bef2 * j;
total = new1 + new2;
if (total == SPECIAL)
{
std::cout << "yay" << j << " " << bef2 << " + " << f << " " << i;
if (found1 + found2 <= bef2 + i || found1 == 0)
{
found1 = i;
found2 = bef2;
found3 = f;
found4 = j;
}
}
}
}*/
}
std::cout << count << std::endl;
std::cout << found1 << " " << found2 << " "<< found3 << " "<< found4;
//std::cout << bef2 << " "<<bef3 ;
}
|
//************************* FUNÇÕES PARA O MENU DE DADOS BATERIA *********************************
void dadosBateria() {
while(!digitalRead(up) == LOW) { //Loop necessário para o programa ficar nesse menu
//Leitura de botões e atualização de variáveis
if(!digitalRead(mais) == HIGH) {
SeletorDadosBateria += 1;
delay(AtrasoBotoes);
} else if(!digitalRead(menos) == HIGH) {
SeletorDadosBateria -= 1;
delay(AtrasoBotoes);
}
//Limites no menu da bateria
if(SeletorDadosBateria < 1) {
SeletorDadosBateria = 4;
}
else if(SeletorDadosBateria > 4) {
SeletorDadosBateria = 1;
}
//Trocar entre os menus
switch(SeletorDadosBateria) {
case 1:
statusBat(Bateria1, 1);
break;
case 2:
statusBat(Bateria2, 2);
break;
case 3:
statusBat(Bateria3, 3);
break;
case 4:
statusBat(Bateria4, 4);
break;
}
}
}
//Função para mostrar o dado da bateria selecionada
void statusBat(float NivelBateria, int ValorBat) {
String TensaoEmString = "";
while(true) {
LeituraHora(true); //Verifico o timer e consequentemente a hora
NiveisBaterias(); //Leio os níveis das 4 baterias
lcd.clear(); //Limpar o que tem na tela
lcd.setCursor(3, 0); //Posiciono o cursor para printar o número da SOLUÇÃO selecionada
lcd.print("Solu");
lcd.write((byte)2);
lcd.write((byte)4);
lcd.write('o');
lcd.write(' ');
//Mostrar o status das bateria selecionada
//BATERIA X:
if(ValorBat == 1) {
lcd.write('1');
NivelBateria = Bateria1;
}
else if(ValorBat == 2) {
lcd.write('2');
NivelBateria = Bateria2;
}
else if(ValorBat == 3)
{
lcd.write('3');
NivelBateria = Bateria3;
}
else if(ValorBat == 4) {
lcd.write('4');
NivelBateria = Bateria4;
}
lcd.write(':');
//Sinal de menos
lcd.setCursor(4, 1);
lcd.write('-');
//Mostrar o valor da bateria em VOLTS
lcd.setCursor(5, 1);
if(NivelBateria >= 1.00) {
lcd.print(NivelBateria, 3);
lcd.setCursor(11, 1);
lcd.write('V');
}
//Mostro o valor da bateria em miliVolts
else {
lcd.setCursor(5, 1);
TensaoEmString = String(NivelBateria, 4);
for(byte i = 2; i < 5; i++) {
lcd.write(TensaoEmString[i]);
}
lcd.write(' ');
lcd.write('m');
lcd.write('V');
}
//Verifico os botões
if(!digitalRead(up) == HIGH) {
delay(AtrasoBotoes);
break;
}
if(!digitalRead(mais) == HIGH) {
SeletorDadosBateria += 1;
delay(AtrasoBotoes);
break;
}
if(!digitalRead(menos) == HIGH) {
SeletorDadosBateria -= 1;
delay(AtrasoBotoes);
break;
}
delay(AtualizacaoDisplay); //Atraso para Atualizar o display
}
}
|
#pragma once
class SuddenDeath :public GameObject
{
public:
bool Start();
void Update() override;
private:
};
|
#pragma GCC optimize("Ofast")
#include <algorithm>
#include <bitset>
#include <deque>
#include <iostream>
#include <numeric>
#include <iterator>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
void abhisheknaiidu()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
// S.C - O(w*n + n) ==> O(w*n)
// w = length of words vector and n = longest anagram length;
// T.C - O(w*nlog(n) + n*wlog(w));
// sorting w words of max of length n;
// sorting w indices with anagrams of max length n;
int main(int argc, char* argv[]) {
abhisheknaiidu();
vector <string> words{"yo", "act", "flop", "tac", "cat", "oy", "olfp"};
vector <string> sortedWords;
for(auto word: words) {
sort(word.begin(), word.end());
sortedWords.push_back(word);
}
// vector<int> indices(words.size());
// iota(indices.begin(), indices.end(), 0);
// sort(indices.begin(), indices.end(), [sortedWords](int a, int b) -> bool {
// // cout << a << " " << b << endl;
// return sortedWords[a] < sortedWords[b];
// });
// vector<vector<string>> res;
// vector<string> anaGroup;
// string currentAna = sortedWords[indices[0]];
// for(auto index: indices) {
// string word = words[index];
// string sortedWord = sortedWords[index];
// if(sortedWord == currentAna) {
// anaGroup.push_back(word);
// continue;
// }
// res.push_back(anaGroup);
// anaGroup = vector <string>{word};
// currentAna = sortedWord;
// }
// res.push_back(anaGroup);
// MOST OPTIMAL 🔥
// S.C remains same
// T.C will be O(w*nlogn)
// because we are just sorting w words of max of length n;
unordered_map<string, vector<string>>m;
for(auto word: words) {
string sortedWord = word;
sort(sortedWord.begin(), sortedWord.end());
if(m.find(sortedWord) != m.end()) {
m[sortedWord].push_back(word);
}
else {
m[sortedWord] = vector<string>{word};
}
}
vector<vector<string>> res;
for(auto x:m) {
res.push_back(x.second);
}
for(auto x: res) {
for(auto y: x) {
cout << y << " ";
}
cout << endl;
}
return 0;
}
|
#include "SteeringController.h"
SteeringController::SteeringController(double Kp_, double Ki_, double Kd_, bool optimize)
: pid{Kp_, Ki_, Kd_}, is_optimized{optimize} { }
SteeringController::~SteeringController() { }
double SteeringController::update(double cte) {
if(is_optimized) opt.run(pid);
pid.UpdateError(cte);
double steer_value = pid.TotalError();
if (steer_value < -1.0) return -1.0;
if (steer_value > 1.0) return 1.0;
return steer_value;
}
|
#include "simulatorwindow.h"
#include "ui_simulatorwindow.h"
SimulatorWindow::SimulatorWindow(QWidget *parent)
:
QWidget(parent),
m_exportFilename(""),
m_importFilename(""),
m_updateFrameTimer(this),
m_currentPlayingFrame(0),
ui(new Ui::SimulatorWindow)
{
ui->setupUi(this);
ui->frameEditor->init(CELL_WIDTH, CELL_HEIGHT);
ui->framePreview->init(CELL_WIDTH, CELL_HEIGHT);
ui->quickPreviewWidget->init((CELL_WIDTH*9)/15, (CELL_HEIGHT*9)/15,
(CELL_WIDTH*FRAME_COLS*9)/15 + 2,
(CELL_HEIGHT*FRAME_ROWS*9)/15 + 2);
m_updateFrameTimer.setInterval(FRAME_TIMER_INTERVAL);
connect(&m_updateFrameTimer, SIGNAL(timeout()), this, SLOT(loadNextFrame()));
connect(ui->playButton, SIGNAL(clicked()), this, SLOT(playPause()));
ui->storeFrameButton->setMenu(new QMenu(ui->storeFrameButton));
connect(ui->storeFrameButton->menu()->addAction(QString("OR and store")),
SIGNAL(triggered()), this, SLOT(orWithFrame()));
connect(ui->storeFrameButton->menu()->addAction(QString("AND and store")),
SIGNAL(triggered()), this, SLOT(andWithFrame()));
ui->insertFrameButton->setMenu(new QMenu(ui->insertFrameButton));
connect(ui->insertFrameButton->menu()->addAction(QString("Append")),
SIGNAL(triggered()), this, SLOT(insertFrameAppend()));
ui->insertFrameButton->menu()->actions().back()->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_A);
connect(ui->insertFrameButton->menu()->addAction(QString("Prepend")),
SIGNAL(triggered()), this, SLOT(insertFramePrepend()));
ui->insertFrameButton->menu()->actions().back()->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_Z);
ui->featuresButton->setMenu(new QMenu(ui->featuresButton));
connect(ui->featuresButton->menu()->addAction(QString("Merge frames")),
SIGNAL(triggered()), this, SLOT(mergeFrames()));
ui->featuresButton->menu()->actions().back()->setShortcut(Qt::CTRL + Qt::Key_Z);
connect(ui->featuresButton->menu()->addAction(QString("Rotate left")),
SIGNAL(triggered()), this, SLOT(rotateFrameLeft()));
ui->featuresButton->menu()->actions().back()->setShortcut(Qt::CTRL + Qt::Key_A);
connect(ui->featuresButton->menu()->addAction(QString("Rotate right")),
SIGNAL(triggered()), this, SLOT(rotateFrameRight()));
ui->featuresButton->menu()->actions().back()->setShortcut(Qt::CTRL + Qt::Key_S);
connect(ui->featuresButton->menu()->addAction(QString("Rotate up")),
SIGNAL(triggered()), this, SLOT(rotateFrameUp()));
ui->featuresButton->menu()->actions().back()->setShortcut(Qt::CTRL + Qt::Key_Q);
connect(ui->featuresButton->menu()->addAction(QString("Rotate down")),
SIGNAL(triggered()), this, SLOT(rotateFrameDown()));
ui->featuresButton->menu()->actions().back()->setShortcut(Qt::CTRL + Qt::Key_W);
connect(ui->featuresButton->menu()->addAction(QString("Quick store")),
SIGNAL(triggered()), this, SLOT(quickStore()));
ui->featuresButton->menu()->actions().back()->setShortcut(Qt::CTRL + Qt::Key_D);
connect(ui->featuresButton->menu()->addAction(QString("Quick load")),
SIGNAL(triggered()), this, SLOT(quickLoad()));
ui->featuresButton->menu()->actions().back()->setShortcut(Qt::CTRL + Qt::Key_F);
ui->importButton->setMenu(new QMenu(ui->importButton));
connect(ui->importButton->menu()->addAction(QString("Import frame")),
SIGNAL(triggered()), this, SLOT(importFrame()));
ui->exportButton->setMenu(new QMenu(ui->exportButton));
connect(ui->exportButton->menu()->addAction(QString("Export frame")),
SIGNAL(triggered()), this, SLOT(exportFrame()));
addAction(new QAction(this));
actions().back()->setShortcut(Qt::CTRL + Qt::Key_C);
connect(actions().back(), SIGNAL(triggered()), this, SLOT(copyToClipboard()));
addAction(new QAction(this));
actions().back()->setShortcut(Qt::CTRL + Qt::Key_X);
connect(actions().back(), SIGNAL(triggered()), this, SLOT(cutToClipboard()));
addAction(new QAction(this));
actions().back()->setShortcut(Qt::CTRL + Qt::Key_V);
connect(actions().back(), SIGNAL(triggered()), this, SLOT(pasteToAnimationAppend()));
addAction(new QAction(this));
actions().back()->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_V);
connect(actions().back(), SIGNAL(triggered()), this, SLOT(pasteToAnimationPrepend()));
}
SimulatorWindow::~SimulatorWindow()
{
delete ui;
}
void SimulatorWindow::removeFrame(void)
{
if(m_animation.size())
{
QModelIndexList selectedFrames = ui->frameSelector->selectedIndexesList();
while(selectedFrames.size())
{
m_animation.removeAt(selectedFrames.back().column());
selectedFrames.removeLast();
}
ui->frameSelector->setColumnCount(m_animation.size());
}
else
{
QMessageBox msg(QMessageBox::Warning, QString("Warning"), QString("No frames avalible"), QMessageBox::Ok);
msg.exec();
}
}
void SimulatorWindow::insertFrameAppend(void)
{
QModelIndexList selectedFrames = ui->frameSelector->selectedIndexesList();
if(selectedFrames.size())
m_animation.insert(selectedFrames.back().column() + 1, SimFrame());
else
m_animation.append(SimFrame());
ui->frameSelector->setColumnCount(m_animation.size());
}
void SimulatorWindow::insertFramePrepend()
{
QModelIndexList selectedFrames = ui->frameSelector->selectedIndexesList();
if(selectedFrames.size())
m_animation.insert(selectedFrames.front().column(), SimFrame());
else
m_animation.prepend(SimFrame());
ui->frameSelector->setColumnCount(m_animation.size());
}
void SimulatorWindow::switchFrame(int dummy, int v_frameNumber)
{
ui->framePreview->setSimFrame(m_animation[v_frameNumber]);
m_currentPlayingFrame = v_frameNumber;
}
void SimulatorWindow::loadFrameToEditor(void)
{
SimFrame frameToLoad;
ui->framePreview->getSimFrame(frameToLoad);
ui->frameEditor->setSimFrame(frameToLoad);
}
void SimulatorWindow::storeFrame(void)
{
if(m_animation.size())
{
QModelIndexList selectedFrames = ui->frameSelector->selectedIndexesList();
if(selectedFrames.size())
{
SimFrame editedFrame;
ui->frameEditor->getSimFrame(editedFrame);
ui->framePreview->setSimFrame(editedFrame);
while(selectedFrames.size())
{
m_animation[selectedFrames.back().column()] = editedFrame;
selectedFrames.removeLast();
}
}
else
{
QMessageBox msg(QMessageBox::Warning, QString("Warning"), QString("Select frames to store into"), QMessageBox::Ok);
msg.exec();
}
}
else
{
QMessageBox msg(QMessageBox::Warning, QString("Warning"), QString("No frames avalible"), QMessageBox::Ok);
msg.exec();
}
}
void SimulatorWindow::orWithFrame(void)
{
if(m_animation.size())
{
QModelIndexList selectedFrames = ui->frameSelector->selectedIndexesList();
if(selectedFrames.size())
{
SimFrame editedFrame, previewFrame;
ui->frameEditor->getSimFrame(editedFrame);
ui->framePreview->getSimFrame(previewFrame);
editedFrame |= previewFrame;
ui->framePreview->setSimFrame(editedFrame);
SimFrame toOr;
ui->frameEditor->getSimFrame(toOr);
while(selectedFrames.size())
{
m_animation[selectedFrames.back().column()] |= toOr;
selectedFrames.removeLast();
}
}
else
{
QMessageBox msg(QMessageBox::Warning, QString("Warning"), QString("Select frames to store into"), QMessageBox::Ok);
msg.exec();
}
}
else
{
QMessageBox msg(QMessageBox::Warning, QString("Warning"), QString("No frames avalible"), QMessageBox::Ok);
msg.exec();
}
}
void SimulatorWindow::andWithFrame(void)
{
if(m_animation.size())
{
QModelIndexList selectedFrames = ui->frameSelector->selectedIndexesList();
if(selectedFrames.size())
{
SimFrame editedFrame, previewFrame;
ui->frameEditor->getSimFrame(editedFrame);
ui->framePreview->getSimFrame(previewFrame);
editedFrame &= previewFrame;
ui->framePreview->setSimFrame(editedFrame);
SimFrame toAnd;
ui->frameEditor->getSimFrame(toAnd);
while(selectedFrames.size())
{
m_animation[selectedFrames.back().column()] &= toAnd;
selectedFrames.removeLast();
}
}
else
{
QMessageBox msg(QMessageBox::Warning, QString("Warning"), QString("Select frames to store into"), QMessageBox::Ok);
msg.exec();
}
}
else
{
QMessageBox msg(QMessageBox::Warning, QString("Warning"), QString("No frames avalible"), QMessageBox::Ok);
msg.exec();
}
}
void SimulatorWindow::mergeFrames(void)
{
QModelIndexList selectedFrames = ui->frameSelector->selectedIndexesList();
if(selectedFrames.size())
{
SimFrame mergedFrame;
ui->frameEditor->getSimFrame(mergedFrame);
while(selectedFrames.size())
{
mergedFrame |= m_animation[selectedFrames.back().column()];
selectedFrames.removeLast();
}
ui->frameEditor->setSimFrame(mergedFrame);
}
else
{
QMessageBox msg(QMessageBox::Warning, QString("Warning"), QString("Select frames to merge"), QMessageBox::Ok);
msg.exec();
}
}
void SimulatorWindow::rotateFrameLeft(void)
{
SimFrame frameToRotate, rotatedFrame;
ui->frameEditor->getSimFrame(frameToRotate);
for(int row = 0; row < frameToRotate.rows(); ++row)
for(int col = 0; col < frameToRotate.cols(); ++col)
rotatedFrame.setPixel(row, col, frameToRotate.getPixel(row, (col + 1) % frameToRotate.cols()));
ui->frameEditor->setSimFrame(rotatedFrame);
}
void SimulatorWindow::rotateFrameRight(void)
{
SimFrame frameToRotate, rotatedFrame;
ui->frameEditor->getSimFrame(frameToRotate);
for(int row = 0; row < frameToRotate.rows(); ++row)
for(int col = 0; col < frameToRotate.cols(); ++col)
rotatedFrame.setPixel(row, (col + 1) % frameToRotate.cols(), frameToRotate.getPixel(row, col));
ui->frameEditor->setSimFrame(rotatedFrame);
}
void SimulatorWindow::rotateFrameUp(void)
{
SimFrame frameToRotate, rotatedFrame;
ui->frameEditor->getSimFrame(frameToRotate);
for(int row = 0; row < frameToRotate.rows(); ++row)
for(int col = 0; col < frameToRotate.cols(); ++col)
rotatedFrame.setPixel(row, col, frameToRotate.getPixel((row + 1) % frameToRotate.rows(), col));
ui->frameEditor->setSimFrame(rotatedFrame);
}
void SimulatorWindow::rotateFrameDown(void)
{
SimFrame frameToRotate, rotatedFrame;
ui->frameEditor->getSimFrame(frameToRotate);
for(int row = 0; row < frameToRotate.rows(); ++row)
for(int col = 0; col < frameToRotate.cols(); ++col)
rotatedFrame.setPixel((row + 1) % frameToRotate.rows(), col, frameToRotate.getPixel(row, col));
ui->frameEditor->setSimFrame(rotatedFrame);
}
void SimulatorWindow::importAnimation(void)
{
m_importFilename = QFileDialog::getOpenFileName(this, "Open File",
"");
if(m_importFilename != QString(""))
{
m_animation.clear();
QFile inFile(m_importFilename);
inFile.open(QIODevice::ReadOnly);
int size;
inFile.read((char *)(&size), 4);
for(int i = 0; i < size; ++i)
{
SimFrame frame;
readFrameFromFile(frame, inFile);
m_animation.append(frame);
}
ui->framePreview->setSimFrame(m_animation.front());
ui->frameSelector->setColumnCount(m_animation.size());
inFile.close();
}
}
void SimulatorWindow::exportAnimation(void)
{
m_exportFilename = QFileDialog::getSaveFileName(this, "Save File",
"");
if(m_exportFilename != QString(""))
{
QFile outFile(m_exportFilename);
outFile.open(QIODevice::WriteOnly);
int size = m_animation.size();
outFile.write((const char *)(&size), 4);
for(int i = 0; i < m_animation.size(); ++i)
writeFrameToFile(m_animation[i], outFile);
outFile.close();
}
}
void SimulatorWindow::importFrame(void)
{
m_importFilename = QFileDialog::getOpenFileName(this, "Open File",
"");
if(m_importFilename != QString(""))
{
QFile inFile(m_importFilename);
inFile.open(QIODevice::ReadOnly);
QModelIndexList selectedFrames = ui->frameSelector->selectedIndexesList();
if(selectedFrames.size())
{
SimFrame inFrame;
readFrameFromFile(inFrame, inFile);
while(selectedFrames.size())
{
m_animation[selectedFrames.back().column()] = inFrame;
selectedFrames.removeLast();
}
ui->framePreview->setSimFrame(inFrame);
}
else
{
QMessageBox msg(QMessageBox::Warning, QString("Warning"), QString("Select frames to import into"), QMessageBox::Ok);
msg.exec();
}
inFile.close();
}
}
void SimulatorWindow::exportFrame(void)
{
m_exportFilename = QFileDialog::getSaveFileName(this, "Save File",
"");
if(m_exportFilename != QString(""))
{
QFile outFile(m_exportFilename);
outFile.open(QIODevice::WriteOnly);
SimFrame outFrame;
ui->framePreview->getSimFrame(outFrame);
writeFrameToFile(outFrame, outFile);
outFile.close();
}
}
void SimulatorWindow::quickStore(void)
{
SimFrame frameToStore;
ui->frameEditor->getSimFrame(frameToStore);
ui->quickPreviewWidget->setSimFrame(frameToStore);
}
void SimulatorWindow::quickLoad(void)
{
SimFrame frameToLoad;
ui->quickPreviewWidget->getSimFrame(frameToLoad);
ui->frameEditor->setSimFrame(frameToLoad);
}
void SimulatorWindow::copyToClipboard(void)
{
QModelIndexList selectedFrames = ui->frameSelector->selectedIndexesList();
if(selectedFrames.size())
{
m_clipboard.clear();
while(selectedFrames.size())
{
m_clipboard.prepend(m_animation[selectedFrames.back().column()]);
selectedFrames.removeLast();
}
}
}
void SimulatorWindow::cutToClipboard()
{
QModelIndexList selectedFrames = ui->frameSelector->selectedIndexesList();
if(selectedFrames.size())
{
m_clipboard.clear();
while(selectedFrames.size())
{
m_clipboard.prepend(m_animation[selectedFrames.back().column()]);
m_animation.removeAt(selectedFrames.back().column());
selectedFrames.removeLast();
}
ui->frameSelector->setColumnCount(m_animation.size());
}
}
void SimulatorWindow::pasteToAnimationAppend(void)
{
if(m_clipboard.size())
{
if(m_animation.size())
{
QModelIndexList selectedFrames = ui->frameSelector->selectedIndexesList();
if(selectedFrames.size() == 1)
{
QList<SimFrame> clipboardCopy = m_clipboard;
while(clipboardCopy.size())
{
m_animation.insert(selectedFrames.back().column() + 1, clipboardCopy.back());
clipboardCopy.removeLast();
}
ui->frameSelector->setColumnCount(m_animation.size());
}
else
{
QMessageBox msg(QMessageBox::Warning, QString("Warning"),
QString("Select one frame, to paste clipboard after"),
QMessageBox::Ok);
msg.exec();
}
}
else
{
m_animation = m_clipboard;
ui->frameSelector->setColumnCount(m_animation.size());
}
}
}
void SimulatorWindow::pasteToAnimationPrepend(void)
{
if(m_clipboard.size())
{
if(m_animation.size())
{
QModelIndexList selectedFrames = ui->frameSelector->selectedIndexesList();
if(selectedFrames.size() == 1)
{
QList<SimFrame> clipboardCopy = m_clipboard;
while(clipboardCopy.size())
{
m_animation.insert(selectedFrames.back().column(), clipboardCopy.back());
clipboardCopy.removeLast();
}
ui->frameSelector->setColumnCount(m_animation.size());
}
else
{
QMessageBox msg(QMessageBox::Warning, QString("Warning"),
QString("Select one frame, to paste clipboard after"),
QMessageBox::Ok);
msg.exec();
}
}
else
{
m_animation = m_clipboard;
ui->frameSelector->setColumnCount(m_animation.size());
}
}
}
void SimulatorWindow::loadNextFrame(void)
{
if(m_animation.size())
{
if(m_currentPlayingFrame >= m_animation.size())
m_currentPlayingFrame = 0;
ui->framePreview->setSimFrame(m_animation[m_currentPlayingFrame]);
m_currentPlayingFrame = (m_currentPlayingFrame + 1) % m_animation.size();
}
else
m_updateFrameTimer.stop();
}
void SimulatorWindow::playPause(void)
{
if(m_updateFrameTimer.isActive())
m_updateFrameTimer.stop();
else
m_updateFrameTimer.start();
}
void SimulatorWindow::writeFrameToFile(const SimFrame v_frame, QFile &v_outFile)
{
for(int row = 0; row < v_frame.rows(); ++row)
for(int col = 0; col < v_frame.cols()/8; ++col)
v_outFile.putChar(v_frame.getByte(row, col));
}
void SimulatorWindow::readFrameFromFile(SimFrame &v_frame, QFile &v_inFile)
{
char byte;
for(int row = 0; row < v_frame.rows(); ++row)
for(int col = 0; col < v_frame.cols()/8; ++col)
{
v_inFile.getChar(&byte);
v_frame.setByte(row, col, byte);
}
}
|
#include <SoftwareSerial.h>
#include <Adafruit_Sensor.h>
#include <ArduinoJson.h>
#include <DHT.h>
//?sensores
#define Sensor1 A0
#define Sensor2 A1
#define Sensor3 A2
#define Sensor4 A3
#define Sensor5 A4
int Dht11 = 8;
int Ws = 3;
//?variables
float h1 = 0;
float h2 = 0;
float h3 = 0;
float h4 = 0;
float h5 = 0;
float threshold1l = 100;
float threshold2l = 110;
float threshold3l = 130;
float threshold4l = 160;
float threshold5l = 150;
float threshold1h = 180;
float threshold2h = 150;
float threshold3h = 180;
float threshold4h = 200;
float threshold5h = 190;
float temp = 0;
int fan = 7;
int manual = 6;
int mn = 0;
int ecode = 0;
int s1 = 9;
int s2 = 10;
int s3 = 11;
int s4 = 12;
int s5 = 13;
bool s1s = 0;
bool s2s = 0;
bool s3s = 0;
bool s4s = 0;
bool s5s = 0;
bool agua = 0;
int l_error = 5;
int btn1 = 2;
int btn1s = 0;
int buzzer = 4;
//?RX pin, TX pin
SoftwareSerial s(0,1);
//?dht
#define DHTPIN 8
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup(){
s.begin(115200);
dht.begin();
pinMode(btn1, INPUT);
pinMode(manual, INPUT);
pinMode(Ws, INPUT);
pinMode(fan, OUTPUT);
pinMode(l_error, OUTPUT);
pinMode(s1, OUTPUT);
pinMode(s2, OUTPUT);
pinMode(s3, OUTPUT);
pinMode(s4, OUTPUT);
pinMode(s5, OUTPUT);
pinMode(buzzer, OUTPUT);
digitalWrite(l_error, LOW);
}
void humedad(){
/ ?Valores humedad
for(int i = 0; i <= 100; i++){
h1 = h1 + analogRead(Sensor1);
delay(1);
h1 = h1 / 100.00;
h2 = h2 + analogRead(Sensor2);
delay(1);
h2 = h2 / 100.00;
h3 = h3 + analogRead(Sensor3);
delay(1);
h3 = h3 / 100.00;
h4 = h4 + analogRead(Sensor4);
delay(1);
h4 = h4 / 100.00;
h5 = h5 + analogRead(Sensor5);
delay(1);
h5 = h5 / 100.00;
}
}
void s1error(){
while(true){
humedad();
digitalWrite(l_error, HIGH);
btn1s = digitalRead(btn1);
ecode = 1;
Serial.println(h1);
if(btn1s == 1){
//? 0
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(1500);
//? 1
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
Serial.println(ecode);
}
if(h1 < 1000){
return;
}
}
}
void s2error(){
while(true){
humedad();
digitalWrite(l_error, HIGH);
btn1s = digitalRead(btn1);
ecode = 2;
if(btn1s == 1){
//? 0
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(1500);
//? 2
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
}
if(h2 < 1000){
return;
}
}
}
void s3error(){
while(true){
humedad();
digitalWrite(l_error, HIGH);
btn1s = digitalRead(btn1);
ecode = 3;
if(btn1s == 1){
//? 0
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(1500);
//? 3
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
}
if(h3 < 1000){
return;
}
}
}
void s4error(){
while(true){
humedad();
digitalWrite(l_error, HIGH);
btn1s = digitalRead(btn1);
ecode = 4;
if(btn1s == 1){
//? 0
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(1500);
//? 4
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
}
if(h4 < 1000){
return;
}
}
}
void s5error(){
while(true){
humedad();
digitalWrite(l_error, HIGH);
btn1s = digitalRead(btn1);
ecode = 5;
if(btn1s == 1){
//? 0
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(1500);
//? 5
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
}
if(h5 < 1000){
return;
}
}
}
void dhterror(){
while(true){
digitalWrite(l_error, HIGH);
btn1s = digitalRead(btn1);
ecode = 6;
if(btn1s == 1){
//? 0
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(1500);
//? 6
digitalWrite(buzzer, HIGH);
delay(1000);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
delay(300);
digitalWrite(buzzer, HIGH);
delay(500);
digitalWrite(buzzer, LOW);
}
if(temp < 40){
return;
}
}
}
void RA(){
for(int i = 0; i <= 100; i++){
h1 = h1 + analogRead(Sensor1);
delay(1);
h1 = h1 / 100.00;
h2 = h2 + analogRead(Sensor2);
delay(1);
h2 = h2 / 100.00;
h3 = h3 + analogRead(Sensor3);
delay(1);
h3 = h3 / 100.00;
h4 = h4 + analogRead(Sensor4);
delay(1);
h4 = h4 / 100.00;
h5 = h5 + analogRead(Sensor5);
delay(1);
h5 = h5 / 100.00;
}
//?riego
if(h1 < threshold1l){
digitalWrite(s2, LOW);
digitalWrite(s3, LOW);
digitalWrite(s4, LOW);
digitalWrite(s5, LOW);
digitalWrite(s1, HIGH);
while(true){
agua = digitalRead(Ws);
delay(10);
if(agua == 0){
digitalWrite(s2, LOW);
digitalWrite(s3, LOW);
digitalWrite(s4, LOW);
digitalWrite(s5, LOW);
digitalWrite(s1, LOW);
return;
}
humedad();
if(h1 > threshold1h){
digitalWrite(s1, LOW);
s1s = 0;
return;
}
}
}
if(h1 > 1000){
s1error();
}
if(h1 >= threshold1h){
digitalWrite(s1, LOW);
s1s = 0;
}
Serial.println(h1);
if(h2 < threshold2l && s1s == 0){
digitalWrite(s1, LOW);
digitalWrite(s3, LOW);
digitalWrite(s4, LOW);
digitalWrite(s5, LOW);
digitalWrite(s2, HIGH);
while(true){
agua = digitalRead(Ws);
delay(10);
if(agua == 0){
digitalWrite(s2, LOW);
digitalWrite(s3, LOW);
digitalWrite(s4, LOW);
digitalWrite(s5, LOW);
digitalWrite(s1, LOW);
return;
}
humedad();
if(h2 > threshold2h){
digitalWrite(s2, LOW);
s2s = 0;
return;
}
}
}
if(h2 > 1000){
s2error();
}
if(h2 >= threshold2h){
digitalWrite(s2, LOW);
s2s = 0;
}
if(h3 < threshold3l && s2s == 0){
digitalWrite(s2, LOW);
digitalWrite(s1, LOW);
digitalWrite(s4, LOW);
digitalWrite(s5, LOW);
digitalWrite(s3, HIGH);
while(true){
agua = digitalRead(Ws);
delay(10);
if(agua == 0){
digitalWrite(s2, LOW);
digitalWrite(s3, LOW);
digitalWrite(s4, LOW);
digitalWrite(s5, LOW);
digitalWrite(s1, LOW);
return;
}
humedad();
if(h3 > threshold3h){
digitalWrite(s3, LOW);
s3s = 0;
return;
}
}
}
if(h3 > 1000){
s3error();
}
if(h3 >= threshold3h){
digitalWrite(s3, LOW);
s3s = 0;
}
if(h4 < threshold4l && s3s == 0){
digitalWrite(s2, LOW);
digitalWrite(s3, LOW);
digitalWrite(s1, LOW);
digitalWrite(s5, LOW);
digitalWrite(s4, HIGH);
while(true){
agua = digitalRead(Ws);
delay(10);
if(agua == 0){
digitalWrite(s2, LOW);
digitalWrite(s3, LOW);
digitalWrite(s4, LOW);
digitalWrite(s5, LOW);
digitalWrite(s1, LOW);
}
humedad();
if(h1 > threshold1h){
digitalWrite(s4, LOW);
s4s = 0;
return;
}
}
}
if(h4 > 1000){
s4error();
}
if(h4 >= threshold4h){
digitalWrite(s4, LOW);
s4s = 0;
}
if(h5 < threshold5l && s4s == 0){
digitalWrite(s2, LOW);
digitalWrite(s3, LOW);
digitalWrite(s4, LOW);
digitalWrite(s1, LOW);
digitalWrite(s5, HIGH);
while(true){
agua = digitalRead(Ws);
delay(10);
if(agua == 0){
digitalWrite(s2, LOW);
digitalWrite(s3, LOW);
digitalWrite(s4, LOW);
digitalWrite(s5, LOW);
digitalWrite(s1, LOW);
return;
}
humedad();
if(h5 > threshold5h){
digitalWrite(s5, LOW);
s5s = 0;
return;
}
}
}
if(h5 > 1000){
s5error();
}
if(h5 >= threshold5h){
digitalWrite(s5, LOW);
s5s = 0;
}
}
void loop(){
//?modo manual o automático
mn = digitalRead(manual);
//?Temperatura y ventilador
digitalWrite(l_error, LOW);
temp = dht.readTemperature();
if(temp >= 30){
digitalWrite(fan, HIGH);
}
else if(temp > 40){
dhterror();
}
else{
digitalWrite(fan, LOW);
}
//? Sensor de agua
agua = digitalRead(Ws);
delay(10);
if(agua == 0){
digitalWrite(s2, LOW);
digitalWrite(s3, LOW);
digitalWrite(s4, LOW);
digitalWrite(s5, LOW);
digitalWrite(s1, LOW);
}
//?Comunicación con esp8266
// StaticJsonDocument<1000> doc;
// DeserializationError error = deserializeJson(doc, json);
// doc["agua"] = agua;
// doc["error"] = ecode;
//doc["humedad1"] = h1;
// doc["humedad2"] = h2;
// doc["humedad3"] = h3;
// doc["humedad4"] = h4;
// doc["humedad5"] = h5;
// doc["manual"] = mn;
// doc["sector1"] = s1s;
// doc["sector2"] = s2s;
// doc["sector3"] = s3s;
// doc["sector4"] = s4s;
// doc["sector5"] = s5s;
// if(s.available()>0){
// doc.printTo(s);
// }
if(mn == 1){
humedad();
}
else if (mn == 0 && agua == 1){
RA();
}
Serial.println(ecode);
}
|
#ifndef ICETOWER_H
#define ICETOWER_H
#include "Tower.h"
const float ICETOWERCOOLDOWN = 1.0f;
const float ICETOWERRANGE = 0.5f;
const float ICETOWERPRICE = 25;
const string ICEPROJECTILETEXTURE = "rock";
const int ICEPROJECTILEDAMAGE = 5;
const float ICEPROJECTILESPEED = 1.0f;
class IceTower :
public Tower
{
public:
virtual void update(double, vector<Enemy*>, vector<Projectile*>*);
IceTower(glm::vec3);
~IceTower();
};
#endif // !ICETOWER_H
|
#include "PhysicalPlan.h"
void PhyPlanNode::addParameter(string parameter)
{
parameters.push_back(parameter);
}
void PhyPlanNode::addAddition(string addition)
{
additions.push_back(addition);
}
void PhyPlanNode::showParameters()
{
cout << "paramater:" << endl;
for (string parameter : parameters) {
cout << parameter << endl;
}
}
void PhyPlanNode::showAdditions()
{
if (additions.empty())
return;
cout << "addition:" << endl;
for (string info : additions)
cout << info << endl;
cout << endl;
}
vector<string>& PhyPlanNode::getParameters()
{
return parameters;
}
vector<string>& PhyPlanNode::getAddition()
{
return additions;
}
void PhysicalPlan::showPlan()
{
backLoopTree(root);
}
void PhysicalPlan::backLoopTree(PhyPlanNode* ppnode)
{
if (ppnode == nullptr)
return;
backLoopTree(ppnode->left);
backLoopTree(ppnode->right);
cout << "method name:" << ppnode->methodName << endl;
//cout << "parameter:" << endl;
ppnode->showAdditions();
ppnode->showParameters();
cout << endl << endl;
}
bool PhysicalPlan::canFinish(vector<PhyPlanNode*>& phyNodes)
{
reverse(phyNodes.begin(), phyNodes.end());//颠倒phyNodes顺序
/*for (PhyPlanNode* p : phyNodes)
cout << p->getParameters()[0] << endl;
cout << endl;*/
queue<string> tableNames;
vector<string> type;
for (PhyPlanNode* root : phyNodes) {
tableNames.push(getTableName(root));
if (root->methodName == "Update") {
type.push_back("update");
}
else if (root->methodName != "Insert" && root->methodName != "Delete")
type.push_back("select");
}
/*while (!tableNames.empty()) {
cout << tableNames.front() << endl;
tableNames.pop();
}*/
//调用函数
return Transaction::check(tableNames,type);//调用事务函数确认是否能够执行
}
string PhysicalPlan::getTableName(PhyPlanNode* root)
{
string tableNames;
queue<PhyPlanNode*>phyQueue;
phyQueue.push(root);
while (!phyQueue.empty()) {
PhyPlanNode* target = phyQueue.front();
phyQueue.pop();
if (target->left)
phyQueue.push(target->left);
if (target->right)
phyQueue.push(target->right);
if (target->methodName == "TableScan") {
//说明为表扫描
if (tableNames.length() > 0) {
tableNames += " ";
}
tableNames += target->getParameters()[0];
}
}
return tableNames;
}
|
#pragma once
#include <cstddef>
#include <stdexcept>
#include <string>
#include <iostream>
template <class T>
class Allocator {
public:
Allocator(size_t min_size, size_t max_size): min_size_(min_size), max_size_(max_size),
blocks_(new Block[max_size_]), memory_(new T[max_size_]) {
blocks_[0] = Block{blocks_, blocks_ + max_size_, false};
}
Allocator() {
Allocator(kDefaultMinSize, kDefaultMaxSize);
}
T* alloc(size_t size) {
size = std::max(size, min_size_);
for (Block* ptr = blocks_; ptr != blocks_ + max_size_; ptr = ptr->end) {
if (!ptr->used && ptr->Size() >= size) {
while (ptr->Size() / 2 >= size) {
Block* mid = ptr + ptr->Size() / 2;
*mid = Block{mid, ptr->end, false};
ptr->end = mid;
}
ptr->used = true;
return memory_ + (ptr - blocks_);
}
}
throw std::runtime_error("No free space");
}
void dealloc(T* ptr) {
Block* block = blocks_ + (ptr - memory_);
block->used = false;
while (block->Size() != max_size_) {
size_t size = block->Size();
size_t shift = block - blocks_;
Block* first = blocks_ + (shift / (2 * size)) * 2 * size;
Block* second = first + size;
if (first->used || second->used || first->Size() != second->Size()) {
break;
}
*first = Block{first, second->end, false};
block = first;
}
}
std::string ToString() {
std::string result = "|";
Block* ptr = blocks_;
while (ptr != blocks_ + max_size_) {
for (int j = 0; j < ptr->Size(); ++j) {
result += ptr->used + '0';
}
result += "|";
ptr = ptr->end;
}
return result;
}
~Allocator() {
delete blocks_;
delete memory_;
}
private:
struct Block {
public:
Block* begin;
Block* end;
bool used;
public:
size_t Size() {
return end - begin;
}
};
private:
size_t min_size_;
size_t max_size_;
Block* blocks_;
T* memory_;
static const int kDefaultMinSize;
static const int kDefaultMaxSize;
};
template<class T>
const int Allocator<T>::kDefaultMinSize = 4;
template<class T>
const int Allocator<T>::kDefaultMaxSize = 1 << 20;
|
#pragma once
#include <stdint.h>
class InputManager
{
public:
inline static InputManager* GetInstance();
bool GetKeyDown(uint8_t keyCode);
private:
static InputManager* m_instance;
InputManager();
~InputManager();
};
inline InputManager* InputManager::GetInstance()
{
if (m_instance == nullptr)
{
m_instance = new InputManager();
}
return m_instance;
}
|
#ifndef CONSTRAINTS_H
#define CONSTRAINTS_H
#include <vector>
#include <math.h>
#include <unordered_map>
#include "gl_const.h"
#include "Vector2D.h"
#include "structs.h"
#include <algorithm>
#include <iostream>
class Constraints
{
public:
Constraints(int width, int height);
virtual ~Constraints(){}
std::vector<std::pair<int,int>> findConflictCells(Node cur, Node parent);
void updateSafeIntervals(const std::vector<std::pair<int,int>> &cells, section sec, bool goal);
std::vector<std::pair<double, double> > getSafeIntervals(Node curNode, const std::unordered_multimap<int, Node> &close, int w);
virtual void addConstraints(const std::vector<Node> §ions, int num) = 0;
virtual std::vector<std::pair<double, double> > findIntervals(Node curNode, std::vector<double> &EAT, const std::unordered_multimap<int, Node> &close, int w) = 0;
std::pair<double,double> getSafeInterval(int i, int j, int n) {return safe_intervals[i][j][n];}
std::vector<std::vector<std::vector<std::pair<double,double>>>> safe_intervals;
std::vector<int> collision_obstacles;
};
class PointConstraints : public Constraints
{
public:
PointConstraints(int width, int height);
void addConstraints(const std::vector<Node> §ions, int num);
std::vector<std::pair<double, double> > findIntervals(Node curNode, std::vector<double> &EAT, const std::unordered_multimap<int, Node> &close, int w);
private:
std::vector<std::vector<std::vector<constraint>>> constraints;
double gap;
};
class VelocityConstraints : public Constraints
{
public:
VelocityConstraints(int width, int height);
void addConstraints(const std::vector<Node> §ions, int num);
std::vector<std::vector<std::vector<section>>> constraints;
std::vector<std::pair<double, double> > findIntervals(Node curNode, std::vector<double> &EAT, const std::unordered_multimap<int, Node> &close, int w);
private:
bool hasCollision(const Node &curNode, double startTimeA, const section &constraint, bool &goal_collision);
};
class SectionConstraints : public VelocityConstraints
{
public:
SectionConstraints(int width, int height):VelocityConstraints(width,height){}
std::vector<std::pair<double, double> > findIntervals(Node curNode, std::vector<double> &EAT, const std::unordered_multimap<int, Node> &close, int w);
std::pair<double,double> countInterval(section sec, Node curNode);
private:
int checkIntersection(Point A, Point B, Point C, Point D, Point &intersec);
double dist(Node A, Node B){return sqrt(pow(A.i - B.i, 2) + pow(A.j - B.j, 2));}
double dist(Point A, Point B){return sqrt(pow(A.i - B.i, 2) + pow(A.j - B.j, 2));}
double minDist(Point A, Point C, Point D)
{
int classA=A.classify(C,D);
if(classA==3)
return sqrt(pow(A.i-C.i,2)+pow(A.j-C.j,2));
else if(classA==4)
return sqrt(pow(A.i-D.i,2)+pow(A.j-D.j,2));
else
return fabs((C.i-D.i)*A.j+(D.j-C.j)*A.i+(C.j*D.i-D.j*C.i))/sqrt(pow(C.i-D.i,2)+pow(C.j-D.j,2));
}
double dist(Point A, Point C, Point D)
{
return fabs((C.i-D.i)*A.j+(D.j-C.j)*A.i+(C.j*D.i-D.j*C.i))/sqrt(pow(C.i-D.i,2)+pow(C.j-D.j,2));
}
};
#endif // CONSTRAINTS_H
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "Item.h"
#include "PhysicsEngine/DestructibleActor.h"
#include "Hammer.generated.h"
/**
*
*/
UCLASS()
class HYPOXIA_API AHammer : public AItem
{
GENERATED_BODY()
public:
virtual void BeginPlay() override;
protected:
UFUNCTION()
virtual void OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComponent, FVector NormalImpulse, const FHitResult& Hit);
};
|
#include "imu_mpu9250.h"
#ifndef __cplusplus
#error "Please define __cplusplus, because this is a c++ based file "
#endif
#include "imu_mpu9250.h"
uint8_t Imu::adc_[SENSOR_DATA_LENGTH];
extern Imu imu_;
namespace {
//Delay function
uint32_t getUs(void) {
uint32_t usTicks = HAL_RCC_GetSysClockFreq() / 1000000;
register uint32_t ms, cycle_cnt;
do {
ms = HAL_GetTick();
cycle_cnt = SysTick->VAL;
} while (ms != HAL_GetTick());
return (ms * 1000) + (usTicks * 1000 - cycle_cnt) / usTicks;
}
void delayUs(uint16_t micros) {
uint32_t start = getUs();
while (getUs()-start < (uint32_t) micros) {
asm("nop");
}
}
} //namespace
void Imu::init(SPI_HandleTypeDef* hspi)
{
acc_.fill(0);
gyro_.fill(0);
mag_.fill(0);
for(int i = 0; i < SENSOR_DATA_LENGTH; i++)
{
dummy_[i] = 0;
adc_[i] = 0;
}
hspi_ = hspi;
gyroInit();
accInit();
magInit();
/* change to 13.5Mhz for polling sensor data from acc, gyro and mag */
hspi_->Instance->CR1 &= (uint32_t)(~SPI_BAUDRATEPRESCALER_256); //reset
hspi_->Instance->CR1 |= (uint32_t)(SPI_BAUDRATEPRESCALER_8); //8 = 13.5Mhz
}
void Imu::update()
{
pollingRead(); //read from SPI
}
void Imu::mpuWrite(uint8_t address, uint8_t value)
{
IMU_SPI_CS_L;
HAL_SPI_Transmit(hspi_, &address, 1, 1000);
HAL_SPI_Transmit(hspi_, &value, 1, 1000);
IMU_SPI_CS_H;
}
uint8_t Imu::mpuRead(uint8_t address)
{
uint8_t t_data[1] = {0};
t_data[0] = address | 0x80;
uint8_t temp;
IMU_SPI_CS_L;
HAL_SPI_Transmit(hspi_, t_data, 1, 1000);
HAL_SPI_Receive(hspi_, &temp, 1, 1000);
IMU_SPI_CS_H;
return temp;
}
void Imu::gyroInit(void)
{
HAL_Delay(100);
// mpuWrite( 0x6B, 0x80); //PWR_MGMT_1 -- DEVICE_RESET 1
HAL_Delay(10);
//mpuWrite( 0x6B, 0x01); //PWR_MGMT_1 -- SLEEP 0; CYCLE 0; TEMP_DIS 0; CLKSEL 3 (PLL with Z Gyro reference)
HAL_Delay(1); //very important!, some duration for process the setting
mpuWrite( 0x6A, 0x10); //disable i2c communication
HAL_Delay(1); //very importnat! between gyro and acc
mpuWrite( 0x1A, GYRO_DLPF_CFG); //CONFIG -- EXT_SYNC_SET 0 (disable input pin for data sync) ; default DLPF_CFG = 0 => ACC bandwidth = 260Hz GYRO bandwidth = 256Hz)
HAL_Delay(1); //very importnat! between gyro and acc
mpuWrite( 0x1B, 0x18); //GYRO_CONFIG -- FS_SEL = 3: Full scale set to 2000 deg/sec
HAL_Delay(10); //very importnat! between gyro and acc
}
void Imu::accInit (void) {
mpuWrite( 0x1C, 0x10); //ACCEL_CONFIG -- AFS_SEL=2 (Full Scale = +/-8G) ; ACCELL_HPF=0 //note something is wrong in the spec.
HAL_Delay(1);
mpuWrite( 0x1D, ACC_DLPF_CFG);
HAL_Delay(10);
}
void Imu::magInit(void)
{
HAL_Delay(10);
//at this stage, the MAG is configured via the original MAG init function in I2C bypass mode
//now we configure MPU as a I2C Master device to handle the MAG via the I2C AUX port (done here for HMC5883)
mpuWrite( 0x6A, 0x20); //USER_CTRL -- DMP_EN=0 ; FIFO_EN=0 ; I2C_MST_EN=1 (I2C master mode) ; I2C_IF_DIS=0 ; FIFO_RESET=0 ; I2C_MST_RESET=0 ; SIG_COND_RESET=0
HAL_Delay(10);
mpuWrite( 0x37, 0x00); //INT_PIN_CFG -- INT_LEVEL=0 ; INT_OPEN=0 ; LATCH_INT_EN=0 ; INT_RD_CLEAR=0 ; FSYNC_INT_LEVEL=0 ; FSYNC_INT_EN=0 ; I2C_BYPASS_EN=0 ; CLKOUT_EN=0
HAL_Delay(1);
mpuWrite( 0x24, 0x0D); //I2C_MST_CTRL -- MULT_MST_EN=0 ; WAIT_FOR_ES=0 ; SLV_3_FIFO_EN=0 ; I2C_MST_P_NSR=0 ; I2C_MST_CLK=13 (I2C slave speed bus = 400kHz)
HAL_Delay(1);
//write mode
mpuWrite( 0x25, MAG_ADDRESS);
HAL_Delay(1);
mpuWrite( 0x26, 0x0B);
HAL_Delay(1);
mpuWrite( 0x63, 0x01);
HAL_Delay(1);
mpuWrite( 0x27, 0x81);
HAL_Delay(1);
mpuWrite( 0x26, 0x0A);
HAL_Delay(1);
mpuWrite( 0x63, 0x16);
HAL_Delay(1);
mpuWrite( 0x27, 0x81);
HAL_Delay(1);
//read mode
mpuWrite( 0x25, 0x80|MAG_ADDRESS);//I2C_SLV0_ADDR -- I2C_SLV4_RW=1 (read operation) ; I2C_SLV4_ADDR=MAG_ADDRESS
HAL_Delay(1);
mpuWrite( 0x26, MAG_DATA_REGISTER);//I2C_SLV0_REG -- 6 data bytes of MAG are stored in 6 registers. First register address is MAG_DATA_REGISTER
HAL_Delay(1);
mpuWrite( 0x27, 0x87);
HAL_Delay(1);
}
void Imu::pollingRead()
{
static int i = 0;
uint8_t t_data[1];
t_data[0] = GYRO_ADDRESS | 0x80;
IMU_SPI_CS_L;
HAL_SPI_Transmit(hspi_, t_data, 1, 1);
HAL_SPI_Receive(hspi_, adc_, 6, 1);
IMU_SPI_CS_H;
/* we need add some delay between each sensor reading */
/* previous code */
//gyro_[0] = (int16_t)(adc_[0] << 8 | adc_[1]) * 2000.0f / 32767.0f * M_PI / 180.0f ; */
gyro_[0] = (int16_t)(adc_[0] << 8 | adc_[1]);
gyro_[1] = (int16_t)(adc_[2] << 8 | adc_[3]);
gyro_[2] = (int16_t)(adc_[4] << 8 | adc_[5]);
delayUs(1);
//asm("nop");
t_data[0] = ACC_ADDRESS | 0x80;
IMU_SPI_CS_L;
HAL_SPI_Transmit(hspi_, t_data, 1, 1);
HAL_SPI_Receive(hspi_, adc_, 6, 1);
IMU_SPI_CS_H;
/* we need add some delay between each sensor reading */
/* previous code */
/*acc_[0] = (int16_t)(adc_[0] << 8 | adc_[1]) / 4096.0f * GRAVITY_MSS;*/
acc_[0] = (int16_t)(adc_[0] << 8 | adc_[1]);
acc_[1] = (int16_t)(adc_[2] << 8 | adc_[3]);
acc_[2] = (int16_t)(adc_[4] << 8 | adc_[5]);
if(i == MAG_PRESCALER) {
//mag is in low speed
hspi_->Instance->CR1 &= (uint32_t)(~SPI_BAUDRATEPRESCALER_256); //reset
hspi_->Instance->CR1 |= (uint32_t)(SPI_BAUDRATEPRESCALER_64); //128 = 0.8Mhz
t_data[0] = MAG_SPI_ADDRESS | 0x80;
delayUs(1);
IMU_SPI_CS_L;
HAL_SPI_Transmit(hspi_, t_data, 1, 1000);
HAL_SPI_Receive(hspi_, adc_, 7, 1000);
IMU_SPI_CS_H;
hspi_->Instance->CR1 &= (uint32_t)(~SPI_BAUDRATEPRESCALER_256); //reset
hspi_->Instance->CR1 |= (uint32_t)(SPI_BAUDRATEPRESCALER_8); //8 = 13.5Mhz
//uT(10e-6 T)
/* previous code */
/*mag_[0] = (int16_t)(adc_[1] << 8 | adc_[0]) * 4912.0f / 32760.0f;*/
mag_[0] = (int16_t)(adc_[1] << 8 | adc_[0]);
mag_[1] = (int16_t)(adc_[3] << 8 | adc_[2]);
mag_[2] = (int16_t)(adc_[5] << 8 | adc_[4]);
}
if(i == MAG_PRESCALER) i = 0;
else i++;
update_ = true;
}
extern "C" ImuData getImuData()
{
imu_.update();
ImuData data;
data.acc[0] = imu_.getAcc()[0];
data.acc[1] = imu_.getAcc()[1];
data.acc[2] = imu_.getAcc()[2];
data.gyro[0] = imu_.getGyro()[0];
data.gyro[1] = imu_.getGyro()[1];
data.gyro[2] = imu_.getGyro()[2];
data.mag[0] = imu_.getMag()[0];
data.mag[1] = imu_.getMag()[1];
data.mag[2] = imu_.getMag()[2];
return data;
}
|
#ifndef MQTT_FRAME_H_
#define MQTT_FRAME_H_
#include "mqttError.h"
#include <stdint.h>
#include <string>
#include <vector>
//typedef MessageType uint8_t;
enum MessageType {
RESERVED_0 = 0,
CONNECT_MESSAGE_TYPE,
CONNACK_MESSAGE_TYPE,
PUBLISH_MESSAGE_TYPE,
PUBACK_MESSAGE_TYPE,
PUBREC_MESSAGE_TYPE,
PUBREL_MESSAGE_TYPE,
PUBCOMP_MESSAGE_TYPE,
SUBSCRIBE_MESSAGE_TYPE,
SUBACK_MESSAGE_TYPE,
UNSUBSCRIBE_MESSAGE_TYPE,
UNSUBACK_MESSAGE_TYPE,
PINGREQ_MESSAGE_TYPE,
PINGRESP_MESSAGE_TYPE,
DISCONNECT_MESSAGE_TYPE,
RESERVED_15,
};
static const std::string TypeString[] = {
"RESERVED_0",
"CONNECT",
"CONNACK",
"PUBLISH"
"PUBACK",
"PUBREC",
"PUBREL",
"PUBCOMP",
"SUBSCRIBE",
"SUBACK",
"UNSUBSCRIBE",
"UNSUBACK",
"PINGREQ",
"PINGRESP",
"DISCONNECT",
"RESERVED_15",
};
typedef uint8_t ConnectFlag;
const static ConnectFlag RESERVED_FLAG = 0x01;
const static ConnectFlag CLEANSESSION_FLAG = 0x02;
const static ConnectFlag WILL_FLAG = 0x04;
const static ConnectFlag WILL_QOS0_FLAG = 0x00;
const static ConnectFlag WILL_QOS1_FLAG = 0x08;
const static ConnectFlag WILL_QOS2_FLAG = 0x10;
const static ConnectFlag WILL_QOS3_FLAG = 0x18;
const static ConnectFlag WILL_RETAIN_FLAG = 0x20;
const static ConnectFlag PASSWORD_FLAG = 0x40;
const static ConnectFlag USERNAME_FLAG = 0x80;
enum ConnectReturnCode {
CONNECT_ACCEPTED = 0,
CONNECT_UNNACCEPTABLE_PROTOCOL_VERSION,
CONNECT_IDENTIFIER_REJECTED,
CONNECT_SERVER_UNAVAILABLE,
CONNECT_BAD_USERNAME_OR_PASSWORD,
CONNECT_NOT_AUTHORIZED,
};
static const std::string ReturnCodeString[] = {
"CONNECT_ACCEPTED",
"CONNECT_UNNACCEPTABLE_PROTOCOL_VERSION",
"CONNECT_IDENTIFIER_REJECTED",
"CONNECT_SERVER_UNAVAILABLE",
"CONNECT_BAD_USERNAME_OR_PASSWORD",
"CONNECT_NOT_AUTHORIZED",
};
struct Will {
Will(std::string topic, std::string message, bool retain, uint8_t qos) : topic(topic), message(message), retain(retain), qos(qos) {};
std::string topic;
std::string message;
bool retain;
uint8_t qos;
};
struct User {
User(std::string name, std::string pass) : name(name), passwd(pass) {};
std::string name;
std::string passwd;
};
const static struct MQTT_VERSION {
std::string name;
uint8_t level;
} MQTT_3_1_1 = {"MQTT", 4};
class FixedHeader {
public:
MessageType type;
bool dup;
bool retain;
uint8_t qos;
uint32_t length;
uint16_t packetID;
FixedHeader(MessageType type, bool dup, uint8_t qos, bool retain, uint32_t length, uint16_t id);
FixedHeader() {};
~FixedHeader() {};
int64_t getWire(uint8_t* wire);
std::string getString();
int64_t parseHeader(const uint8_t* wire, MQTT_ERROR& err);
};
class Message {
public:
FixedHeader* fh;
Message(FixedHeader* fh);
virtual ~Message();
virtual int64_t getWire(uint8_t* wire) = 0;
virtual std::string getString() = 0;
virtual int64_t parse(const uint8_t* wire, MQTT_ERROR& err) = 0;
};
class ConnectMessage : public Message {
public:
uint8_t flags;
uint16_t keepAlive;
std::string clientID;
bool cleanSession;
const Will* will;
const User* user;
struct MQTT_VERSION protocol;
ConnectMessage(uint16_t keepAlive, std::string id, bool cleanSession, const struct Will* will, const struct User* user);
ConnectMessage(FixedHeader* fh, const uint8_t* wire, MQTT_ERROR& err) : Message(fh) {this->parse(wire, err);};
~ConnectMessage();
int64_t getWire(uint8_t* wire);
std::string flagString();
std::string getString();
int64_t parse(const uint8_t* wire, MQTT_ERROR& err);
};
class ConnackMessage : public Message {
public:
bool sessionPresent;
ConnectReturnCode returnCode;
ConnackMessage(bool sp, ConnectReturnCode code);
ConnackMessage(FixedHeader* fh, const uint8_t* wire, MQTT_ERROR& err) : Message(fh) {this->parse(wire, err);};
~ConnackMessage() {};
int64_t getWire(uint8_t* wire);
std::string getString();
int64_t parse(const uint8_t* wire, MQTT_ERROR& err);
};
class PublishMessage : public Message {
public:
std::string topicName;
std::string payload;
PublishMessage(bool dup, uint8_t qos, bool retain, uint16_t id, std::string topic, std::string payload);
PublishMessage(FixedHeader* fh, const uint8_t* wire, MQTT_ERROR& err) : Message(fh) {this->parse(wire, err);};
~PublishMessage() {};
int64_t getWire(uint8_t* wire);
std::string getString();
int64_t parse(const uint8_t* wire, MQTT_ERROR& err);
};
class PubackMessage : public Message {
public:
PubackMessage(uint16_t id);
PubackMessage(FixedHeader* fh, const uint8_t* wire, MQTT_ERROR& err) : Message(fh) {this->parse(wire, err);};
~PubackMessage() {};
int64_t getWire(uint8_t* wire);
std::string getString();
int64_t parse(const uint8_t* wire, MQTT_ERROR& err);
};
class PubrecMessage : public Message {
public:
PubrecMessage(uint16_t id);
PubrecMessage(FixedHeader* fh, const uint8_t* wire, MQTT_ERROR& err) : Message(fh) {this->parse(wire, err);};
~PubrecMessage() {};
int64_t getWire(uint8_t* wire);
std::string getString();
int64_t parse(const uint8_t* wire, MQTT_ERROR& err);
};
class PubrelMessage : public Message {
public:
PubrelMessage(uint16_t id);
PubrelMessage(FixedHeader* fh, const uint8_t* wire, MQTT_ERROR& err) : Message(fh) {this->parse(wire, err);};
~PubrelMessage() {};
int64_t getWire(uint8_t* wire);
std::string getString();
int64_t parse(const uint8_t* wire, MQTT_ERROR& err);
};
class PubcompMessage : public Message {
public:
PubcompMessage(uint16_t id);
PubcompMessage(FixedHeader* fh, const uint8_t* wire, MQTT_ERROR& err) : Message(fh) {this->parse(wire, err);};
~PubcompMessage() {};
int64_t getWire(uint8_t* wire);
std::string getString();
int64_t parse(const uint8_t* wire, MQTT_ERROR& err);
};
struct SubscribeTopic {
SubscribeTopic(std::string topic, uint8_t qos) : topic(topic), qos(qos) {};
std::string topic;
uint8_t qos;
};
class SubscribeMessage : public Message {
public:
std::vector<SubscribeTopic*> subTopics;
SubscribeMessage(uint16_t id, std::vector<SubscribeTopic*> topics);
SubscribeMessage(FixedHeader* fh, const uint8_t* wire, MQTT_ERROR& err) : Message(fh) {this->parse(wire, err);};
~SubscribeMessage();
int64_t getWire(uint8_t* wire);
std::string getString();
int64_t parse(const uint8_t* wire, MQTT_ERROR& err);
};
enum SubackCode {
ACK_MAX_QOS0 = 0,
ACK_MAX_QOS1,
ACK_MAX_QOS2,
FAILURE,
};
static const std::string SubackCodeString[4] = {"ACK_MAX_QOS0", "ACK_MAX_QOS1", "ACK_MAX_QOS2", "FAILURE"};
class SubackMessage : public Message {
public:
std::vector<SubackCode> returnCodes;
SubackMessage(uint16_t id, std::vector<SubackCode> codes);
SubackMessage(FixedHeader* fh, const uint8_t* wire, MQTT_ERROR& err) : Message(fh) {this->parse(wire, err);};
~SubackMessage() {};
int64_t getWire(uint8_t* wire);
std::string getString();
int64_t parse(const uint8_t* wire, MQTT_ERROR& err);
};
class UnsubscribeMessage : public Message {
public:
std::vector<std::string> topics;
UnsubscribeMessage(uint16_t id, std::vector<std::string> topics);
UnsubscribeMessage(FixedHeader* fh, const uint8_t* wire, MQTT_ERROR& err) : Message(fh) {this->parse(wire, err);};
~UnsubscribeMessage() {};
int64_t getWire(uint8_t* wire);
std::string getString();
int64_t parse(const uint8_t* wire, MQTT_ERROR& err);
};
class UnsubackMessage : public Message {
public:
UnsubackMessage(uint16_t id);
UnsubackMessage(FixedHeader* fh, const uint8_t* wire, MQTT_ERROR& err) : Message(fh) {this->parse(wire, err);};
~UnsubackMessage() {};
int64_t getWire(uint8_t* wire);
std::string getString();
int64_t parse(const uint8_t* wire, MQTT_ERROR& err);
};
class PingreqMessage : public Message {
public:
PingreqMessage();
PingreqMessage(FixedHeader* fh, const uint8_t* wire, MQTT_ERROR& err) : Message(fh) {this->parse(wire, err);};
~PingreqMessage() {};
int64_t getWire(uint8_t* wire);
std::string getString();
int64_t parse(const uint8_t* wire, MQTT_ERROR& err);
};
class PingrespMessage : public Message {
public:
PingrespMessage();
PingrespMessage(FixedHeader* fh, const uint8_t* wire, MQTT_ERROR& err) : Message(fh) {this->parse(wire, err);};
~PingrespMessage() {};
int64_t getWire(uint8_t* wire);
std::string getString();
int64_t parse(const uint8_t* wire, MQTT_ERROR& err);
};
class DisconnectMessage : public Message {
public:
DisconnectMessage();
DisconnectMessage(FixedHeader* fh, const uint8_t* wire, MQTT_ERROR& err) : Message(fh) {this->parse(wire, err);};
~DisconnectMessage() {};
int64_t getWire(uint8_t* wire);
std::string getString();
int64_t parse(const uint8_t* wire, MQTT_ERROR& err);
};
#endif // MQTT_FRAME_H
|
/*
* MCB.h
* File defining the MCB state manager
* Author: Alex St. Clair
* February 2018
*/
/* To add a new state:
* 1) Add it to the enum "MCB_States_t"
* 2) Define a private member function of the form "void func(bool exit)""
* 3) Add the state to the private array "state_array"
* 4) Write the function for the state in the .cpp file
*/
#ifndef MCB_H_
#define MCB_H_
#include "MCBBufferGuard.h"
#include "InternalSerialDriverMCB.h"
#include "LTC2983Manager.h"
#include "PowerControllerMCB.h"
#include "StorageManagerMCB.h"
#include "ConfigManagerMCB.h"
#include "LevelWind.h"
#include "MonitorMCB.h"
#include "ActionsMCB.h"
#include "Reel.h"
#include "SafeBuffer.h"
#include <String.h>
#include <StdInt.h>
#include <StdLib.h>
#define ENTRY_SUBSTATE 0
#define EXIT_SUBSTATE 1
// Enum describing all states
enum MCB_States_t : uint8_t {
ST_READY = 0,
ST_NOMINAL,
ST_REEL_OUT,
ST_REEL_IN,
ST_DOCK,
ST_IN_NO_LW,
ST_HOME_LW,
NUM_STATES, // not a state, used for counting
UNUSED_STATE = 0xFF // not a state, used as default
};
class MCB {
public:
MCB();
~MCB(void) { };
// public interface for MCB_Main.ino
void Startup();
void Loop();
private:
// handle commanded actions
void PerformActions(void);
// state machine interface
void RunState(void);
bool SetState(MCB_States_t new_state);
// Watchdog
void InitializeWatchdog();
void KickWatchdog();
// State Methods, located in States.cpp file
void Ready();
void Nominal();
void ReelOut();
void ReelIn();
void Dock();
void InNoLW();
void HomeLW();
// Array of state functions
void (MCB::*state_array[NUM_STATES])() = {
&MCB::Ready,
&MCB::Nominal,
&MCB::ReelOut,
&MCB::ReelIn,
&MCB::Dock,
&MCB::InNoLW,
&MCB::HomeLW
};
// Helper functions
void PrintBootInfo(void);
void CheckReel(void);
bool CheckLevelWind(void); // returns true iff motion complete
void CheckLevelWindCam(void);
void LogFault(void);
// Reel and level wind power control
bool ReelControllerOn(void);
bool LevelWindControllerOn(void);
void ReelControllerOff(void);
void LevelWindControllerOff(void);
// send EEPROM contents to DIB/PIB as binary message
void SendEEPROM(void);
// Interface objects
SafeBuffer action_queue;
SafeBuffer monitor_queue;
uint8_t action_queue_buffer[16] = {0};
uint8_t monitor_queue_buffer[16] = {0};
// Hardware objects
PowerControllerMCB powerController;
StorageManagerMCB storageManager;
ConfigManagerMCB configManager;
// Serial interface objects
InternalSerialDriverMCB dibDriver;
// Reel and level wind objects
Reel reel;
LevelWind levelWind;
// Limit monitor object
MonitorMCB limitMonitor;
// Variables tracking current and last state
MCB_States_t curr_state = ST_READY;
MCB_States_t last_state = ST_READY;
// Maintain motor operation information
uint32_t last_pos_print = 0;
bool reel_initialized = false;
bool levelwind_initialized = false;
bool camming = false;
bool homed = false;
bool lw_docked = false;
bool lw_direction_out = true;
// The current substate
uint8_t substate = ENTRY_SUBSTATE;
// buffer used for sending EEPROM contents as TM
uint8_t eeprom_buffer[MAX_MCB_BINARY];
};
#endif
|
// CSC 111
// Sharna Hossain
// Assignment 2B
#include <iostream>
using namespace std;
double calc_area(double radius)
{
return (radius * radius) * 3.14;
}
double calc_circumference(double radius)
{
return 2 * 3.14 * radius;
}
int main()
{
double radius, area, circumference;
cout << "Enter the radius of the circle: ";
cin >> radius;
area = calc_area(radius);
circumference = calc_circumference(radius);
cout << "The area is " << area << endl;
cout << "The circumference is " << circumference << endl;
return 0;
}
|
#ifndef _WORLDOBJECT_AERO_H_
#define _WORLDOBJECT_AERO_H_
#include "../../Toolbox/Toolbox.h"
#include "../../Idioms/NotCopiable/NotCopiable.h"
#include "../World.h"
namespace ae
{
/// \ingroup scene
/// <summary>
/// Class that represent an object in the world. <para/>
/// Identified by an unique ID.
/// </summary>
class AERO_CORE_EXPORT WorldObject : public NotCopiable
{
public:
/// <summary>Initialize the object and add it to the world hierarchy.</summary>
WorldObject();
/// <summary>Destroy an object and remove it from the world.</summary>
virtual ~WorldObject();
/// <summary>Retrieve the ID that identify this object in the world.</summary>
/// <returns>ID in the world of the object.</returns>
const World::ObjectID& GetObjectID() const;
/// <summary>Make this object active or not in the world.</summary>
/// <param name="_IsEnabled">The new object active state.</param>
virtual void SetEnabled( Bool _IsEnabled );
/// <summary>Retrieve the active state of the object.</summary>
/// <returns>True if the object is active in the world, false otherwise.</returns>
virtual Bool IsEnabled() const;
/// <summary>Retrieve the name of the object.</summary>
/// <returns>Name of the object.</returns>
virtual const std::string& GetName() const;
/// <summary>Set the name of the object.</summary>
/// <param name="_NewName">The new name to apply to the object.</param>
virtual void SetName( const std::string& _NewName );
/// <summary>
/// Function called by the editor.
/// It allows the class to expose some attributes for user editing.
/// Think to call all inherited class function too when overloading.
/// </summary>
virtual void ToEditor();
private:
/// <summary>Unique ID of the object in the world.</summary>
World::ObjectID m_ObjectID;
/// <summary>Is this object active in the world ?</summary>
Bool m_IsEnabled;
/// <summary>Name of the object.</summary>
std::string m_Name;
};
} // ae
#endif // _WORLDOBJECT_AERO_H_
|
#ifndef BUTTON_H
#define BUTTON_H
#include <UtH/UtHEngine.hpp>
enum class ButtonType
{
Click,
Toggle
};
typedef std::function<void(uth::GameObject&)> ButtonCallback;
class Button : public uth::Component
{
public:
Button() = default;
Button(const ButtonCallback&);
Button(ButtonType, const ButtonCallback&);
~Button() = default;
void Init() override;
void Draw(uth::RenderTarget& target) override;
void Update(float delta) override;
void updateColor();
bool isPressed() const;
void reset();
private:
bool m_isPressed = false;
bool m_isToggled = false;
const ButtonType m_Type;
ButtonCallback m_callback;
};
#endif // !BUTTON_H
|
#include "Shader.h"
#include "../app/Engine.h"
#include <assert.h>
#include <stdio.h>
Shader::Shader()
{
}
Shader::~Shader()
{
DeleteProgram();
}
bool Shader::Initialize(string shaderFileName)
{
m_name = shaderFileName;
string vsFile = shaderFileName + "_vs.glsl";
string psFile = shaderFileName + "_ps.glsl";
if (!InitializeShader(vsFile, psFile))
{
cout << "Shader " << shaderFileName << " couldnt be initialized" << endl;
return false;
}
return true;
}
void Shader::BeginShader()
{
glUseProgram(m_programID);
}
void Shader::EndShader()
{
glUseProgram(NULL);
}
bool Shader::InitializeShader(string shaderVSFileName, string shaderPSFileName)
{
const char* shaderBuffer_VS = LoadShaderSourceFile("Shaders/" + shaderVSFileName);
const char* shaderBuffer_PS = LoadShaderSourceFile("Shaders/" + shaderPSFileName);
if (!shaderBuffer_VS)
{
cout << "Shader: " << shaderVSFileName << " could not be loaded" << endl;
return false;
}
if (!shaderBuffer_PS)
{
cout << "Shader: " << shaderVSFileName << " could not be loaded" << endl;
return false;
}
m_vertexID = glCreateShader(GL_VERTEX_SHADER);
m_fragID = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(m_vertexID, 1, &shaderBuffer_VS, NULL);
glShaderSource(m_fragID, 1, &shaderBuffer_PS, NULL);
delete[] shaderBuffer_VS;
delete[] shaderBuffer_PS;
glCompileShader(m_vertexID);
glCompileShader(m_fragID);
int status;
glGetShaderiv(m_vertexID, GL_COMPILE_STATUS, &status);
if (status != 1)
{
OutputShaderErrorMessage(m_vertexID, (char*)shaderVSFileName.c_str());
return false;
}
glGetShaderiv(m_fragID, GL_COMPILE_STATUS, &status);
if (status != 1)
{
OutputShaderErrorMessage(m_fragID, (char*)shaderPSFileName.c_str());
return false;
}
m_programID = glCreateProgram();//set the Program ID to the first element by default
glAttachShader(m_programID, m_vertexID);
glAttachShader(m_programID, m_fragID);
glLinkProgram(m_programID);
glGetProgramiv(m_programID, GL_LINK_STATUS, &status);
if(status != 1)
{
// If it did not link then write the syntax error message out to a text file for review.
OutputLinkerErrorMessage(m_programID);
DeleteProgram();
return false;
}
return true;
}
void Shader::BindAttributes(int index, const char* name)
{
assert(m_programID);
glBindAttribLocation(m_programID, index, name);
}
char* Shader::LoadShaderSourceFile(string shaderFileName)
{
FILE *pFile = NULL;
char* shaderBuffer = NULL;
fopen_s(&pFile, shaderFileName.c_str(), "rb");
if(!pFile)
{
return NULL;
}
//get size of the file
fseek(pFile, 0L, SEEK_END);
//file lenght
unsigned int bufferSize = ftell(pFile);
//back to the start of the file
rewind(pFile);
shaderBuffer = new char[bufferSize+1];
if(fread(shaderBuffer, bufferSize, 1, pFile) <= 0)
{
delete [] shaderBuffer;
fclose(pFile);
return NULL;
}
shaderBuffer[bufferSize] = '\0';
fclose(pFile);
return shaderBuffer;
}
void Shader::OutputShaderErrorMessage(unsigned int shaderID, char* shaderFilename)
{
int logSize;
char* infoLog;
ofstream fout;
//get the size of the string containing the info log
glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH, &logSize);
if(!logSize)
{
return;
}
infoLog = new char[logSize + 1];
//retrieve info log
glGetShaderInfoLog(shaderID, logSize, NULL, infoLog);
//open a file to write to
fout.open("shader-error.txt");
for(int i = 0; i < logSize+1; ++i)
{
fout << infoLog[i];
}
fout.close();
delete [] infoLog;
//pop message on screen
MessageBox(Engine::GetEngine()->GetGraphics()->GetOpenGL()->GetHWND(), "Error compiling shader. Check shader-error.txt for message", shaderFilename, MB_OK);
}
void Shader::OutputLinkerErrorMessage(unsigned int programID)
{
int logSize;
char* infoLog;
ofstream fout;
//get the size of the string containing the info log
glGetProgramiv(programID, GL_INFO_LOG_LENGTH, &logSize);
if(!logSize)
{
return;
}
infoLog = new char[logSize + 1];
//retrieve info log
glGetProgramInfoLog(programID, logSize, NULL, infoLog);
//open a file to write to
fout.open("shader-linkerror.txt");
for(int i = 0; i < logSize+1; ++i)
{
fout << infoLog[i];
}
fout.close();
delete [] infoLog;
//pop message on screen
MessageBox(Engine::GetEngine()->GetGraphics()->GetOpenGL()->GetHWND(), "Error compiling shader. Check shader-error.txt for message", "LinkerError", MB_OK);
}
bool Shader::SetShaderMatrixParameter(const char* name, float* matrix)
{
int locID = glGetUniformLocation(m_programID, name);
if (locID >= 0)
{
glUniformMatrix4fv(locID, 1, true, matrix);
}
return true;
}
bool Shader::SetShaderFloatParameter(const char* name, float pValue)
{
int locID = glGetUniformLocation(m_programID, name);
if (locID >= 0)
{
glUniform1f(locID, pValue);
}
return true;
}
bool Shader::SetShaderIntParameter(const char* name, int pValue)
{
int locID = glGetUniformLocation(m_programID, name);
if (locID >= 0)
{
glUniform1i(locID, pValue);
}
return true;
}
bool Shader::SetShaderVec2Parameter(const char* name, Vector2 vec2)
{
int locID = glGetUniformLocation(m_programID, name);
if (locID >= 0)
{
glUniform2f(locID, vec2.GetX(), vec2.GetY());
}
return true;
}
bool Shader::SetShaderVec3Parameter(const char* name, Vector3 vec3)
{
int locID = glGetUniformLocation(m_programID, name);
if (locID >= 0)
{
glUniform3f(locID, vec3.GetX(), vec3.GetY(), vec3.GetZ());
}
return true;
}
bool Shader::SetShaderSampler(const char* name, int slot, TextureLoader* texture)
{
if(texture == NULL)
{
cout << "Shader::SetShaderSampler setting a null texture" << endl;
return true;
}
int locID = glGetUniformLocation(m_programID, name);
if (locID >= 0)
{
texture->Bind(slot);
glUniform1i(locID, slot);
}
return true;
}
void Shader::DeleteProgram()
{
glDetachShader(m_programID, m_vertexID);
glDeleteShader(m_vertexID);
glDetachShader(m_programID, m_fragID);
glDeleteShader(m_fragID);
glDeleteProgram(m_programID);
}
|
class ItemTrapTripwireCans
{
weight = 0.2;
};
class ItemTrapTripwireFlare
{
weight = 0.2;
};
class ItemTrapTripwireGrenade
{
weight = 0.2;
};
class ItemTrapTripwireSmoke
{
weight = 0.2;
};
|
#include "../core/core.h"
#include "proxy_object.h"
extern "C" EXPORT const char* proxy_initialize(int n_args, const char** args)
{
if (!(Core::initialize() && Proxy::initialize()))
return Core::FAIL;
return Core::SUCCESS;
}
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Daniel Gomez Ferro <dgomezferro@gmail.com>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "sparse.h"
template<typename SparseMatrixType> void sparse_product(const SparseMatrixType& ref)
{
typedef typename SparseMatrixType::Index Index;
const Index rows = ref.rows();
const Index cols = ref.cols();
typedef typename SparseMatrixType::Scalar Scalar;
enum { Flags = SparseMatrixType::Flags };
double density = std::max(8./(rows*cols), 0.01);
typedef Matrix<Scalar,Dynamic,Dynamic> DenseMatrix;
typedef Matrix<Scalar,Dynamic,1> DenseVector;
Scalar s1 = ei_random<Scalar>();
Scalar s2 = ei_random<Scalar>();
// test matrix-matrix product
{
DenseMatrix refMat2 = DenseMatrix::Zero(rows, rows);
DenseMatrix refMat3 = DenseMatrix::Zero(rows, rows);
DenseMatrix refMat4 = DenseMatrix::Zero(rows, rows);
DenseMatrix refMat5 = DenseMatrix::Random(rows, rows);
DenseMatrix dm4 = DenseMatrix::Zero(rows, rows);
DenseVector dv1 = DenseVector::Random(rows);
SparseMatrixType m2(rows, rows);
SparseMatrixType m3(rows, rows);
SparseMatrixType m4(rows, rows);
initSparse<Scalar>(density, refMat2, m2);
initSparse<Scalar>(density, refMat3, m3);
initSparse<Scalar>(density, refMat4, m4);
int c = ei_random<int>(0,rows-1);
VERIFY_IS_APPROX(m4=m2*m3, refMat4=refMat2*refMat3);
VERIFY_IS_APPROX(m4=m2.transpose()*m3, refMat4=refMat2.transpose()*refMat3);
VERIFY_IS_APPROX(m4=m2.transpose()*m3.transpose(), refMat4=refMat2.transpose()*refMat3.transpose());
VERIFY_IS_APPROX(m4=m2*m3.transpose(), refMat4=refMat2*refMat3.transpose());
VERIFY_IS_APPROX(m4 = m2*m3/s1, refMat4 = refMat2*refMat3/s1);
VERIFY_IS_APPROX(m4 = m2*m3*s1, refMat4 = refMat2*refMat3*s1);
VERIFY_IS_APPROX(m4 = s2*m2*m3*s1, refMat4 = s2*refMat2*refMat3*s1);
// sparse * dense
VERIFY_IS_APPROX(dm4=m2*refMat3, refMat4=refMat2*refMat3);
VERIFY_IS_APPROX(dm4=m2*refMat3.transpose(), refMat4=refMat2*refMat3.transpose());
VERIFY_IS_APPROX(dm4=m2.transpose()*refMat3, refMat4=refMat2.transpose()*refMat3);
VERIFY_IS_APPROX(dm4=m2.transpose()*refMat3.transpose(), refMat4=refMat2.transpose()*refMat3.transpose());
VERIFY_IS_APPROX(dm4=m2*(refMat3+refMat3), refMat4=refMat2*(refMat3+refMat3));
VERIFY_IS_APPROX(dm4=m2.transpose()*(refMat3+refMat5)*0.5, refMat4=refMat2.transpose()*(refMat3+refMat5)*0.5);
// dense * sparse
VERIFY_IS_APPROX(dm4=refMat2*m3, refMat4=refMat2*refMat3);
VERIFY_IS_APPROX(dm4=refMat2*m3.transpose(), refMat4=refMat2*refMat3.transpose());
VERIFY_IS_APPROX(dm4=refMat2.transpose()*m3, refMat4=refMat2.transpose()*refMat3);
VERIFY_IS_APPROX(dm4=refMat2.transpose()*m3.transpose(), refMat4=refMat2.transpose()*refMat3.transpose());
// sparse * dense and dense * sparse outer product
VERIFY_IS_APPROX(m4=m2.col(c)*dv1.transpose(), refMat4=refMat2.col(c)*dv1.transpose());
VERIFY_IS_APPROX(m4=dv1*m2.col(c).transpose(), refMat4=dv1*refMat2.col(c).transpose());
VERIFY_IS_APPROX(m3=m3*m3, refMat3=refMat3*refMat3);
}
// test matrix - diagonal product
{
DenseMatrix refM2 = DenseMatrix::Zero(rows, rows);
DenseMatrix refM3 = DenseMatrix::Zero(rows, rows);
DiagonalMatrix<Scalar,Dynamic> d1(DenseVector::Random(rows));
SparseMatrixType m2(rows, rows);
SparseMatrixType m3(rows, rows);
initSparse<Scalar>(density, refM2, m2);
initSparse<Scalar>(density, refM3, m3);
VERIFY_IS_APPROX(m3=m2*d1, refM3=refM2*d1);
VERIFY_IS_APPROX(m3=m2.transpose()*d1, refM3=refM2.transpose()*d1);
VERIFY_IS_APPROX(m3=d1*m2, refM3=d1*refM2);
VERIFY_IS_APPROX(m3=d1*m2.transpose(), refM3=d1 * refM2.transpose());
}
// test self adjoint products
{
DenseMatrix b = DenseMatrix::Random(rows, rows);
DenseMatrix x = DenseMatrix::Random(rows, rows);
DenseMatrix refX = DenseMatrix::Random(rows, rows);
DenseMatrix refUp = DenseMatrix::Zero(rows, rows);
DenseMatrix refLo = DenseMatrix::Zero(rows, rows);
DenseMatrix refS = DenseMatrix::Zero(rows, rows);
SparseMatrixType mUp(rows, rows);
SparseMatrixType mLo(rows, rows);
SparseMatrixType mS(rows, rows);
do {
initSparse<Scalar>(density, refUp, mUp, ForceRealDiag|/*ForceNonZeroDiag|*/MakeUpperTriangular);
} while (refUp.isZero());
refLo = refUp.transpose().conjugate();
mLo = mUp.transpose().conjugate();
refS = refUp + refLo;
refS.diagonal() *= 0.5;
mS = mUp + mLo;
for (int k=0; k<mS.outerSize(); ++k)
for (typename SparseMatrixType::InnerIterator it(mS,k); it; ++it)
if (it.index() == k)
it.valueRef() *= 0.5;
VERIFY_IS_APPROX(refS.adjoint(), refS);
VERIFY_IS_APPROX(mS.transpose().conjugate(), mS);
VERIFY_IS_APPROX(mS, refS);
VERIFY_IS_APPROX(x=mS*b, refX=refS*b);
VERIFY_IS_APPROX(x=mUp.template selfadjointView<Upper>()*b, refX=refS*b);
VERIFY_IS_APPROX(x=mLo.template selfadjointView<Lower>()*b, refX=refS*b);
VERIFY_IS_APPROX(x=mS.template selfadjointView<Upper|Lower>()*b, refX=refS*b);
}
}
void test_sparse_product()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( sparse_product(SparseMatrix<double>(8, 8)) );
CALL_SUBTEST_2( sparse_product(SparseMatrix<std::complex<double> >(16, 16)) );
CALL_SUBTEST_1( sparse_product(SparseMatrix<double>(33, 33)) );
CALL_SUBTEST_3( sparse_product(DynamicSparseMatrix<double>(8, 8)) );
}
}
|
#ifndef VULKANLAB_INDEXBUFFER_H
#define VULKANLAB_INDEXBUFFER_H
class IndexBuffer {
public:
/**
* The index buffer constructor.
*/
IndexBuffer() {
glGenBuffers(1, &this->id);
}
/**
* The index buffer destructor.
*/
~IndexBuffer() {
glDeleteBuffers(1, &id);
}
inline void bind() {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->id);
}
/**
* Fill the buffer with data, size must the speficied.
* @param data
*/
inline void setData(void *data, GLsizei size) {
this->data = data;
this->bind();
glBufferData(GL_ELEMENT_ARRAY_BUFFER, size * sizeof(unsigned int), data, GL_STATIC_DRAW);
}
/**
* Return the OpenGL index buffer id.
* @return
*/
inline unsigned int getId() const {
return id;
}
/**
* Set the OpenGL index buffer id.
* @param id
*/
inline void setId(unsigned int id) {
this->id = id;
}
/**
* Return the OpenGL buffer data.
* @return
*/
inline void *getData() const {
return data;
}
private:
unsigned int id;
void* data;
};
#endif //VULKANLAB_INDEXBUFFER_H
|
#include <bits/stdc++.h>
using namespace std;
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAXN 100
#define INF 0x3f3f3f3f
#define DEVIATION 0.00000005
int main(int argc, char const *argv[])
{
int kase;
scanf("%d",&kase);
int num;
for(int K = 1 ; K <= kase ; K++ ){
scanf("%d",&num);
double ans = 0;
if ( num > 1180000 ) {
ans += (num-1180000)/4.0;
num = 1180000;
}
if ( num > 880000 ) {
ans += (num-880000)/5.0;
num = 880000;
}
if ( num > 480000 ) {
ans += (num-480000)*3/20.0;
num = 480000;
}
if ( num > 180000 )
ans += (num-180000)/10.0;
if ( ans > 0 && ans < 2000 )
ans = 2000;
printf("Case %d: %d\n", K, (int)(ans+0.99));
}
return 0;
}
|
#include <signal.h>
#include "CDLReactor.h"
#include "Configure.h"
#include "Despatch.h"
#include "Logger.h"
#include "Version.h"
#include "RobotSvrConfig.h"
#include "GameServerConnect.h"
#include "CoinConf.h"
//#include "RobotRedis.h"
#include "Util.h"
#include "Protocol.h"
#include "NamePool.h"
#ifdef CRYPT
#include "CryptRedis.h"
#endif
int initGameConnector(int32_t robotSvrId)
{
RobotSvrConfig& svf = RobotSvrConfig::getInstance();
svf.initServerConf(Configure::getInstance()->serverxml.c_str());
for (int i = 0, max = svf.getServerListSize(); i < max; ++i)
{
ServerNode* node = svf.getServerNode(i);
if (node == NULL)
{
continue;
}
// 通过RobotSvrId, 间接地指定需要连接的目标GameSvr的等级
if (node->svid != robotSvrId)
{
continue;
}
GameConnector* gameserver = new GameConnector(node->svid);
if(gameserver && gameserver->connect(node->ip, node->port) !=0)
{
LOGGER(E_LOG_WARNING)<<"Svid["<<node->svid<<"] Connect BackServer error["<<node->ip<<":"<<node->port<<"]";
delete gameserver;
exit(1);
}
BackGameConnectManager::addGameNode(node->svid, gameserver);
}
return 0;
}
int main(int argc, char* argv[])
{
CDLReactor::Instance()->Init();
srand((unsigned int)time(0)^getpid());
Util::registerSignal();
if (!Configure::getInstance()->LoadConfig(argc, argv))
{
LOGGER(E_LOG_ERROR) << "ReadConfig Failed.";
return -1;
}
//__LOG_INIT__(Configure::getInstance()->loglevel, Configure::getInstance()->logfile );
AddressInfo addrLog;
Util::parseAddress(Configure::getInstance()->m_sLogAddr.c_str(), addrLog);
CLogger::InitLogger(
Configure::getInstance()->m_nLogLevel,
"BullHundredRobot",
Configure::getInstance()->m_nServerId,
addrLog.ip,
addrLog.port
);
NamePool::getInstance()->Initialize("../conf/names.txt");
if(initGameConnector(Configure::getInstance()->m_nServerId)<0)
{
LOGGER(E_LOG_ERROR) << "Init Alloc Server Connector fault,System exit\n";
return -1;
}
#ifdef CRYPT
if (!CCryptRedis::getInstance().init(Configure::getInstance()->m_sPhpRedisAddr[WRITE_REDIS_CONF].c_str()))
{
LOGGER(E_LOG_ERROR) << "Connect Crypt Redis Error," << Configure::getInstance()->m_sPhpRedisAddr[WRITE_REDIS_CONF];
return -1;
}
#endif
if(CoinConf::getInstance()->init() != 0 )
LOGGER(E_LOG_ERROR) << "CoinConf Error\n";
if(PlayerManager::getInstance()->init()<0)
return -1;
return CDLReactor::Instance()->RunEventLoop();
}
|
#include <ros/ros.h>
#include <actionlib/client/simple_action_client.h>
#include <actionlib/client/terminal_state.h>
#include <mc_graspable/FindGraspablesAction.h>
int main (int argc, char **argv)
{
ros::init(argc, argv, "test_find_graspables");
// create the action client
// true causes the client to spin its own thread
actionlib::SimpleActionClient<mc_graspable::FindGraspablesAction> ac("mc_graspable", true);
ROS_INFO("Waiting for action server to start.");
// wait for the action server to start
ac.waitForServer(); //will wait for infinite time
ROS_INFO("Action server started, sending goal.");
// send a goal to the action
mc_graspable::FindGraspablesGoal goal;
goal.cloud_topic = "/camera/rgb/points";
goal.frame_id = "/map";
goal.aabb_min.x = atof(argv[1]);
goal.aabb_min.y = atof(argv[2]);
goal.aabb_min.z = .5;
goal.aabb_max.x = atof(argv[3]);
goal.aabb_max.y = atof(argv[4]);
goal.aabb_max.z = 1.5;
goal.delta = 0.02;
goal.scaling = 20;
goal.pitch_limit = 0.4;
goal.thickness = 0.04;
ac.sendGoal(goal);
//wait for the action to return
bool finished_before_timeout = ac.waitForResult(ros::Duration(30.0));
if (finished_before_timeout)
{
actionlib::SimpleClientGoalState state = ac.getState();
ROS_INFO("Action finished: %s",state.toString().c_str());
}
else
ROS_INFO("Action did not finish before the time out.");
//exit
return 0;
}
|
#include "pch.h"
#ifdef KORE_OCULUS
#include <Kore/Vr/VrInterface.h>
#include <Kore/Graphics4/Graphics.h>
#include <Kore/Log.h>
#include "Direct3D11.h"
#include "OVR_CAPI_D3D.h"
#include <vector>
#include "d3d11.h"
#if _MSC_VER > 1600
#include "DirectXMath.h"
using namespace DirectX;
#else
#include "xnamath.h"
#endif //_MSC_VER > 1600
#pragma comment(lib, "dxgi.lib")
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "d3dcompiler.lib")
using namespace Kore;
namespace {
SensorState sensorStates[2];
}
//------------------------------------------------------------
struct DepthBuffer {
ID3D11DepthStencilView* TexDsv;
DepthBuffer(ID3D11Device* Device, int sizeW, int sizeH, int sampleCount = 1) {
DXGI_FORMAT format = DXGI_FORMAT_D32_FLOAT;
D3D11_TEXTURE2D_DESC dsDesc;
dsDesc.Width = sizeW;
dsDesc.Height = sizeH;
dsDesc.MipLevels = 1;
dsDesc.ArraySize = 1;
dsDesc.Format = format;
dsDesc.SampleDesc.Count = sampleCount;
dsDesc.SampleDesc.Quality = 0;
dsDesc.Usage = D3D11_USAGE_DEFAULT;
dsDesc.CPUAccessFlags = 0;
dsDesc.MiscFlags = 0;
dsDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
ID3D11Texture2D* Tex;
Device->CreateTexture2D(&dsDesc, NULL, &Tex);
Device->CreateDepthStencilView(Tex, NULL, &TexDsv);
Tex->Release();
}
~DepthBuffer() {
TexDsv->Release();
TexDsv = nullptr;
}
};
//---------------------------------------------------------------------
struct DirectX11 {
HWND Window;
bool Running;
bool Key[256];
int WinSizeW;
int WinSizeH;
HINSTANCE hInstance;
DirectX11() : Window(nullptr), Running(false), WinSizeW(0), WinSizeH(0), hInstance(nullptr) {
// Clear input
for (int i = 0; i < sizeof(Key) / sizeof(Key[0]); ++i)
Key[i] = false;
}
~DirectX11() {
ReleaseDevice();
CloseWindow();
}
bool InitWindow(HINSTANCE hinst, const char* title, const char* windowClassName) {
hInstance = hinst;
Running = true;
// Adjust the window size and show at InitDevice time
wchar_t wchTitle[256];
MultiByteToWideChar(CP_ACP, 0, title, -1, wchTitle, 256);
wchar_t wchClassName[256];
MultiByteToWideChar(CP_ACP, 0, windowClassName, -1, wchClassName, 256);
Window = CreateWindowW(wchClassName, wchTitle, WS_OVERLAPPEDWINDOW, 0, 0, 0, 0, 0, 0, hinst, 0);
if (!Window) return false;
SetWindowLongPtr(Window, 0, LONG_PTR(this));
return true;
}
void CloseWindow() {
if (Window) {
Window = nullptr;
}
}
bool InitDevice(int vpW, int vpH, const LUID* pLuid, bool windowed = true, int scale = 1) {
WinSizeW = vpW;
WinSizeH = vpH;
if (scale == 0)
scale = 1;
RECT size = { 0, 0, vpW / scale, vpH / scale };
AdjustWindowRect(&size, WS_OVERLAPPEDWINDOW, false);
const UINT flags = SWP_NOMOVE | SWP_NOZORDER | SWP_SHOWWINDOW;
if (!SetWindowPos(Window, nullptr, 0, 0, size.right - size.left, size.bottom - size.top, flags))
return false;
return true;
}
void SetAndClearRenderTarget(ID3D11RenderTargetView* rendertarget, DepthBuffer* depthbuffer,
float R = 0, float G = 0, float B = 0, float A = 0) {
float black[] = { R, G, B, A }; // Important that alpha=0, if want pixels to be transparent, for manual layers
context->OMSetRenderTargets(1, &rendertarget, (depthbuffer ? depthbuffer->TexDsv : nullptr));
context->ClearRenderTargetView(rendertarget, black);
if (depthbuffer)
context->ClearDepthStencilView(depthbuffer->TexDsv, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1, 0);
}
void SetViewport(float vpX, float vpY, float vpW, float vpH) {
D3D11_VIEWPORT D3Dvp;
D3Dvp.Width = vpW; D3Dvp.Height = vpH;
D3Dvp.MinDepth = 0; D3Dvp.MaxDepth = 1;
D3Dvp.TopLeftX = vpX; D3Dvp.TopLeftY = vpY;
context->RSSetViewports(1, &D3Dvp);
}
void ReleaseDevice() {
}
};
static DirectX11 Platform;
//---------------------------------------------------------------------
// ovrSwapTextureSet wrapper class that also maintains the render target views needed for D3D11 rendering.
struct OculusTexture {
ovrSession Session;
ovrTextureSwapChain TextureChain;
std::vector<ID3D11RenderTargetView*> TexRtv;
OculusTexture(ovrSession session, int sizeW, int sizeH) : Session(session), TextureChain(nullptr) {
ovrTextureSwapChainDesc desc = {};
desc.Type = ovrTexture_2D;
desc.ArraySize = 1;
desc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB;
desc.Width = sizeW;
desc.Height = sizeH;
desc.MipLevels = 1;
desc.SampleCount = 1;
desc.MiscFlags = ovrTextureMisc_DX_Typeless;
desc.BindFlags = ovrTextureBind_DX_RenderTarget;
desc.StaticImage = ovrFalse;
ovrResult result = ovr_CreateTextureSwapChainDX(session, device, &desc, &TextureChain);
int textureCount = 0;
ovr_GetTextureSwapChainLength(Session, TextureChain, &textureCount);
if (OVR_SUCCESS(result)) {
for (int i = 0; i < textureCount; ++i) {
ID3D11Texture2D* tex = nullptr;
ovr_GetTextureSwapChainBufferDX(Session, TextureChain, i, IID_PPV_ARGS(&tex));
D3D11_RENDER_TARGET_VIEW_DESC rtvd = {};
rtvd.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
rtvd.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D;
ID3D11RenderTargetView* rtv;
device->CreateRenderTargetView(tex, &rtvd, &rtv);
TexRtv.push_back(rtv);
tex->Release();
}
}
}
~OculusTexture() {
for (int i = 0; i < (int)TexRtv.size(); ++i) {
TexRtv[i]->Release();
TexRtv[i] = nullptr;
}
if (TextureChain) {
ovr_DestroyTextureSwapChain(Session, TextureChain);
TextureChain = nullptr;
}
}
ID3D11RenderTargetView* GetRTV() {
int index = 0;
ovr_GetTextureSwapChainCurrentIndex(Session, TextureChain, &index);
return TexRtv[index];
}
void Commit() {
ovr_CommitTextureSwapChain(Session, TextureChain);
}
};
//---------------------------------------------------------------------
namespace {
ovrRecti eyeRenderViewport[2];
OculusTexture* pEyeRenderTexture[2] = { nullptr, nullptr };
DepthBuffer* pEyeDepthBuffer[2] = { nullptr, nullptr };
ovrSizei windowSize;
ovrMirrorTexture mirrorTexture = nullptr;
long long frameIndex = 0;
bool isVisible = true;
ovrSession session;
ovrHmdDesc hmdDesc;
ovrPosef EyePose[2];
ovrPosef EyePredictedPose[2];
double sensorSampleTime;
double predictedFrameTiming;
ovrTrackingState trackingState;
void done() {
if (mirrorTexture)
ovr_DestroyMirrorTexture(session, mirrorTexture);
for (int eye = 0; eye < 2; ++eye) {
delete pEyeRenderTexture[eye];
delete pEyeDepthBuffer[eye];
}
Platform.ReleaseDevice();
ovr_Destroy(session);
}
void createOculusTexture() {
// Create mirror texture
ovrMirrorTextureDesc desc;
memset(&desc, 0, sizeof(desc));
desc.Width = Platform.WinSizeW;
desc.Height = Platform.WinSizeH;
desc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB;
HRESULT result = ovr_CreateMirrorTextureDX(session, device, &desc, &mirrorTexture);
if (!OVR_SUCCESS(result)) {
log(Error, "Failed to create mirror texture.");
done();
}
// Make eye render buffers
for (int eye = 0; eye < 2; ++eye) {
ovrSizei idealSize = ovr_GetFovTextureSize(session, ovrEyeType(eye), hmdDesc.DefaultEyeFov[eye], 1);
pEyeRenderTexture[eye] = new OculusTexture(session, idealSize.w, idealSize.h);
pEyeDepthBuffer[eye] = new DepthBuffer(device, idealSize.w, idealSize.h);
eyeRenderViewport[eye].Pos.x = 0;
eyeRenderViewport[eye].Pos.y = 0;
eyeRenderViewport[eye].Size = idealSize;
if (!pEyeRenderTexture[eye]->TextureChain) {
log(Error, "Failed to create texture.");
done();
}
}
}
}
void* VrInterface::init(void* hinst, const char* title, const char* windowClassName) {
ovrInitParams initParams = { ovrInit_RequestVersion, OVR_MINOR_VERSION, NULL, 0, 0 };
ovrResult result = ovr_Initialize(&initParams);
if (!OVR_SUCCESS(result)) {
log(Error, "Failed to initialize libOVR.");
return(0);
}
if (!Platform.InitWindow((HINSTANCE)hinst, title, windowClassName)) {
log(Error, "Failed to open window.");
return(0);
}
ovrGraphicsLuid luid;
result = ovr_Create(&session, &luid);
if (!OVR_SUCCESS(result)) {
log(Error, "HMD not connected.");
return false; // TODO: retry
}
hmdDesc = ovr_GetHmdDesc(session);
// Setup Window and Graphics
// Note: the mirror window can be any size, for this sample we use 1/2 the HMD resolution
windowSize = { hmdDesc.Resolution.w / 2, hmdDesc.Resolution.h / 2 };
if (!Platform.InitDevice(windowSize.w, windowSize.h, reinterpret_cast<LUID*>(&luid))) {
log(Error, "Failed to init device.");
done();
}
ovr_SetTrackingOriginType(session, ovrTrackingOrigin_FloorLevel);
// Return window
return Platform.Window;
}
void VrInterface::begin() {
// Call ovr_GetRenderDesc each frame to get the ovrEyeRenderDesc, as the returned values (e.g. HmdToEyeOffset) may change at runtime.
ovrEyeRenderDesc eyeRenderDesc[2];
eyeRenderDesc[0] = ovr_GetRenderDesc(session, ovrEye_Left, hmdDesc.DefaultEyeFov[0]);
eyeRenderDesc[1] = ovr_GetRenderDesc(session, ovrEye_Right, hmdDesc.DefaultEyeFov[1]);
// Get eye poses, feeding in correct IPD offset
ovrVector3f HmdToEyeOffset[2] = { eyeRenderDesc[0].HmdToEyeOffset, eyeRenderDesc[1].HmdToEyeOffset };
// Get predicted eye pose
ovr_GetEyePoses(session, frameIndex, ovrTrue, HmdToEyeOffset, EyePose, &sensorSampleTime);
// Ask the API for the times when this frame is expected to be displayed.
predictedFrameTiming = ovr_GetPredictedDisplayTime(session, frameIndex);
trackingState = ovr_GetTrackingState(session, predictedFrameTiming, ovrTrue);
ovr_CalcEyePoses(trackingState.HeadPose.ThePose, HmdToEyeOffset, EyePredictedPose);
}
void VrInterface::beginRender(int eye) {
if (pEyeRenderTexture[0] == nullptr || pEyeRenderTexture[1] == nullptr) createOculusTexture();
// Clear and set up rendertarget
Platform.SetAndClearRenderTarget(pEyeRenderTexture[eye]->GetRTV(), pEyeDepthBuffer[eye]);
Platform.SetViewport((float)eyeRenderViewport[eye].Pos.x, (float)eyeRenderViewport[eye].Pos.y,
(float)eyeRenderViewport[eye].Size.w, (float)eyeRenderViewport[eye].Size.h);
}
void VrInterface::endRender(int eye) {
// Commit rendering to the swap chain
pEyeRenderTexture[eye]->Commit();
}
SensorState VrInterface::getSensorState(int eye) {
VrPoseState poseState;
ovrQuatf orientation = EyePose[eye].Orientation;
poseState.vrPose.orientation = Quaternion(orientation.x, orientation.y, orientation.z, orientation.w);
ovrVector3f pos = EyePose[eye].Position;
poseState.vrPose.position = vec3(pos.x, pos.y, pos.z);
ovrFovPort fov = hmdDesc.DefaultEyeFov[eye];
poseState.vrPose.left = fov.LeftTan;
poseState.vrPose.right = fov.RightTan;
poseState.vrPose.bottom = fov.DownTan;
poseState.vrPose.top = fov.UpTan;
ovrVector3f angularVelocity = trackingState.HeadPose.AngularVelocity;
ovrVector3f linearVelocity = trackingState.HeadPose.LinearVelocity;
ovrVector3f angularAcceleration = trackingState.HeadPose.AngularAcceleration;
ovrVector3f linearAcceleration = trackingState.HeadPose.LinearAcceleration;
poseState.angularVelocity = vec3(angularVelocity.x, angularVelocity.y, angularVelocity.z);
poseState.linearVelocity = vec3(linearVelocity.x, linearVelocity.y, linearVelocity.z);
poseState.angularAcceleration = vec3(angularAcceleration.x, angularAcceleration.y, angularAcceleration.z);
poseState.linearAcceleration = vec3(linearAcceleration.x, linearAcceleration.y, linearAcceleration.z);
// Get predicted orientation and position
VrPoseState predictedPoseState;
ovrQuatf predOrientation = EyePredictedPose[eye].Orientation;
predictedPoseState.vrPose.orientation = Quaternion(predOrientation.x, predOrientation.y, predOrientation.z, predOrientation.w);
ovrVector3f predPos = EyePredictedPose[eye].Position;
predictedPoseState.vrPose.position = vec3(predPos.x, predPos.y, predPos.z);
sensorStates[eye].predictedPose = predictedPoseState;
sensorStates[eye].pose = poseState;
ovrSessionStatus sessionStatus;
ovr_GetSessionStatus(session, &sessionStatus);
if (sessionStatus.IsVisible) sensorStates[eye].isVisible = true;
else sensorStates[eye].isVisible = false;
if (sessionStatus.HmdPresent) sensorStates[eye].hmdPresenting = true;
else sensorStates[eye].hmdPresenting = false;
if (sessionStatus.HmdMounted) sensorStates[eye].hmdMounted = true;
else sensorStates[eye].hmdMounted = false;
if (sessionStatus.DisplayLost) sensorStates[eye].displayLost = true;
else sensorStates[eye].displayLost = false;
if (sessionStatus.ShouldQuit) sensorStates[eye].shouldQuit = true;
else sensorStates[eye].shouldQuit = false;
if (sessionStatus.ShouldRecenter) sensorStates[eye].shouldRecenter = true;
else sensorStates[eye].shouldRecenter = false;
return sensorStates[eye];
}
/*VrPoseState VrInterface::getController(int index) {
return -1;
}*/
void VrInterface::warpSwap() {
// Initialize our single full screen Fov layer.
ovrLayerEyeFov ld = {};
ld.Header.Type = ovrLayerType_EyeFov;
ld.Header.Flags = 0;
if (isVisible) {
for (int eye = 0; eye < 2; ++eye) {
ld.ColorTexture[eye] = pEyeRenderTexture[eye]->TextureChain;
ld.Viewport[eye] = eyeRenderViewport[eye];
ld.Fov[eye] = hmdDesc.DefaultEyeFov[eye];
ld.RenderPose[eye] = EyePose[eye]; // eyePredictedPose[eye];
ld.SensorSampleTime = sensorSampleTime; // predictedFrameTiming;
}
}
ovrLayerHeader* layers = &ld.Header;
ovrResult result = ovr_SubmitFrame(session, frameIndex, nullptr, &layers, 1);
if (!OVR_SUCCESS(result)) {
isVisible = false;
} else {
isVisible = true;
}
frameIndex++;
// Render mirror
ID3D11Texture2D* tex = nullptr;
ovr_GetMirrorTextureBufferDX(session, mirrorTexture, IID_PPV_ARGS(&tex));
context->CopyResource(backBuffer, tex);
tex->Release();
}
void VrInterface::updateTrackingOrigin(TrackingOrigin origin) {
switch (origin) {
case Stand:
ovr_SetTrackingOriginType(session, ovrTrackingOrigin_FloorLevel);
break;
case Sit:
ovr_SetTrackingOriginType(session, ovrTrackingOrigin_EyeLevel);
break;
default:
ovr_SetTrackingOriginType(session, ovrTrackingOrigin_FloorLevel);
break;
}
}
void VrInterface::resetHmdPose() {
ovr_RecenterTrackingOrigin(session);
}
void VrInterface::ovrShutdown() {
ovr_Shutdown();
}
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2008 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Yngve Pettersen
*/
#include "core/pch.h"
#include "modules/prefs/prefsmanager/collections/pc_files.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
#include "modules/util/opfile/opsafefile.h"
#include "modules/pi/OpSystemInfo.h"
#include "modules/datastream/opdatastreamsafefile.h"
#include "modules/stdlib/util/opdate.h"
#include "modules/url/url2.h"
#include "modules/url/url_man.h"
#include "modules/url/url_rep.h"
#include "modules/url/url_ds.h"
#include "modules/cache/url_cs.h"
#include "modules/formats/url_dfr.h"
#include "modules/cache/url_stor.h"
#include "modules/cache/cache_common.h"
#include "modules/cache/cache_man.h"
#include "modules/cache/cache_utils.h"
#include "modules/cache/cache_propagate.h"
#ifdef CACHE_FAST_INDEX
#include "modules/cache/simple_stream.h"
#endif
void Context_Manager::AutoSaveCacheL()
{
if(urlManager->updated_cache)
{
#ifdef DISK_CACHE_SUPPORT
WriteCacheIndexesL(FALSE, FALSE);
#endif
urlManager->updated_cache = FALSE;
#if defined(CACHE_MAX_VISITED_URL_COUNT) && CACHE_MAX_VISITED_URL_COUNT>0
if(url_store->URL_RepCount() > CACHE_MAX_VISITED_URL_COUNT)
{
Head collect_list;
Head sort_list[256];
int i;
time_t index;
int num_selected=0;
// Count the number of affected URLs, to avoid all the operations if it is not required
URL_Rep* url_rep = url_store->GetFirstURL_Rep();
while (url_rep)
{
if(url_rep->GetRefCount() == 1 && (!url_rep->GetDataStorage() || !url_rep->GetDataStorage()->GetCacheStorage()))
num_selected++;
url_rep = url_store->GetNextURL_Rep();
}
// Remove the URLs exceeding CACHE_MAX_VISITED_URL_COUNT, after sorting them
if(num_selected > CACHE_MAX_VISITED_URL_COUNT)
{
url_rep = url_store->GetFirstURL_Rep();
// First radix sort path (it sorts only based ont the first digit);
while (url_rep)
{
if(url_rep->GetRefCount() == 1 && (!url_rep->GetDataStorage() || !url_rep->GetDataStorage()->GetCacheStorage()))
{
url_store->RemoveURL_Rep(url_rep);
index = 0;
url_rep->GetAttribute(URL::KVLocalTimeVisited, &index);
url_rep->Into(&sort_list[ index & 0xff]);
}
url_rep = url_store->GetNextURL_Rep();
}
for(i=0;i< 256;i++)
collect_list.Append(&sort_list[i]);
/* At this stage, the URLs are sorted only by the first digit, but the list is complete */
int shift=0;
// Finishes the radix sort
while(shift<24)
{
shift += 8;
while((url_rep = (URL_Rep *) collect_list.First()) != NULL)
{
url_rep->Out();
index = 0;
url_rep->GetAttribute(URL::KVLocalTimeVisited, &index);
url_rep->Into(&sort_list[ (index >> shift) & 0xff]);
}
for(i=0;i< 256;i++)
collect_list.Append(&sort_list[i]);
}
// Move the first CACHE_MAX_VISITED_URL_COUNT URLs to url_store, to preserve them
int i=0;
while(i < CACHE_MAX_VISITED_URL_COUNT && !collect_list.Empty())
{
url_rep = (URL_Rep *) collect_list.Last();
url_rep->Out();
url_store->AddURL_Rep(url_rep);
i++;
}
// Delete the remaining URLs, to avoid OOM on some devices ( CORE-36314 )
while(!collect_list.Empty())
{
url_rep = (URL_Rep *) collect_list.First();
url_rep->Out();
url_rep->DecRef();
OP_DELETE(url_rep);
}
}
}
#endif // defined(CACHE_MAX_VISITED_URL_COUNT) && CACHE_MAX_VISITED_URL_COUNT>0
}
CACHE_PROPAGATE_ALWAYS_VOID(AutoSaveCacheL());
}
#if defined(DISK_CACHE_SUPPORT) && !defined(SEARCH_ENGINE_CACHE)
#ifdef SELFTEST
void Context_Manager::TestWriteIndexFileL(OpStringC filename, OpFileFolder folder, BOOL fast)
{
URLLinkHead dcache_list;
ANCHOR(URLLinkHead, dcache_list);
URL_Rep *url_rep ;
url_rep = url_store->GetFirstURL_Rep();
// Populate the dcache_list
while(url_rep)
{
URL_DataStorage *storage=url_rep->GetDataStorage();
BOOL embedded=storage && storage->GetCacheStorage() && storage->GetCacheStorage()->IsEmbedded();
if((URLStatus) url_rep->GetAttribute(URL::KLoadStatus) == URL_LOADED &&
(url_rep->GetAttribute(URL::KCacheType) == URL_CACHE_DISK || embedded))
{
if(url_rep->CheckStorage() &&
(url_rep->GetDataStorage()->GetCacheStorage()->GetCacheType() == URL_CACHE_DISK || embedded)
&& !url_rep->GetDataStorage()->GetCacheStorage()->GetIsMultipart())
{
URL url(url_rep, (const char *) NULL);
URLLink *item = OP_NEW(URLLink, (url));
if(item)
item->Into(&dcache_list);
}
}
url_rep = url_store->GetNextURL_Rep();
}
#ifdef CACHE_FAST_INDEX
if(fast)
WriteIndexFileSimpleL(dcache_list, TAG_CACHE_FILE_ENTRY, filename, folder, TRUE, FALSE);
else
WriteIndexFileL(dcache_list, TAG_CACHE_FILE_ENTRY, filename, folder, TRUE, FALSE);
#else
OP_ASSERT(!fast);
WriteIndexFileL(dcache_list, TAG_CACHE_FILE_ENTRY, filename, folder, FALSE, FALSE);
#endif
}
#endif // SELFTEST
void Context_Manager::WriteIndexFileL(URLLinkHead &list, uint32 tag, OpStringC filename, OpFileFolder folder, BOOL write_lastentry, BOOL destroy_urls)
{
DataStream_NonSensitive_ByteArrayL(write_cache_index);
OpStackAutoPtr<DataFile> listfile(NULL);
OpStackAutoPtr<OpDataStreamSafeFile> base_listfile(OP_NEW_L(OpDataStreamSafeFile, ()));
LEAVE_IF_ERROR(base_listfile->Construct(filename.CStr(), folder));
OpStackAutoPtr<DataFile_Record> url_rec(NULL);
OpStackAutoPtr<URLLink> item(NULL);
URLLink *item2;
LEAVE_IF_ERROR(base_listfile->Open(OPFILE_WRITE));
listfile.reset(OP_NEW_L(DataFile, (base_listfile.get(), CURRENT_CACHE_VERSION, 1, 2)));
base_listfile.release();
listfile->InitL();
while((item2 = list.First()) != NULL && listfile->Opened())
{
item.reset(item2);
item2->Out();
if(tag == TAG_VISITED_FILE_ENTRY || !item->url.GetAttribute(URL::KFileName).IsEmpty())
{
url_rec.reset(OP_NEW_L(DataFile_Record, (tag)));
url_rec->SetRecordSpec(listfile->GetRecordSpec());
item->url.WriteCacheDataL(url_rec.get());
url_rec->WriteRecordL(listfile.get());
url_rec.reset();
}
if(destroy_urls)
{
DestroyURL(item2->url);
}
item.reset();
}
#ifndef SEARCH_ENGINE_CACHE
if(write_lastentry && listfile->Opened())
{
url_rec.reset(OP_NEW_L(DataFile_Record, (TAG_CACHE_LASTFILENAME_ENTRY)));
OpStringC tempstring(file_str+3);
ANCHOR(OpStringC,tempstring);
OpString8 tempstring1;
ANCHOR(OpString8,tempstring1);
tempstring1.SetUTF8FromUTF16L(tempstring.CStr());
tempstring1.Delete(5);
url_rec->SetRecordSpec(listfile->GetRecordSpec());
url_rec->AddContentL(tempstring1);
url_rec->WriteRecordL(listfile.get());
url_rec.reset();
}
#endif
if(!listfile->Opened())
LEAVE(OpStatus::ERR);
listfile->Close();
listfile.reset();
}
#ifdef CACHE_FAST_INDEX
void Context_Manager::WriteIndexFileSimpleL(URLLinkHead &list, uint32 tag, OpStringC filename, OpFileFolder folder, BOOL write_lastentry, BOOL destroy_urls)
{
OpConfigFileWriter cache;
ANCHOR(OpConfigFileWriter, cache);
DiskCacheEntry disk_entry;
ANCHOR(DiskCacheEntry, disk_entry);
OpStackAutoPtr<URLLink> item(NULL);
URLLink *item2;
#ifdef CACHE_SAFE_FILE
LEAVE_IF_ERROR(cache.Construct(filename.CStr(), folder, 1, 2, TRUE));
#else
LEAVE_IF_ERROR(cache.Construct(filename.CStr(), folder, 1, 2, FALSE));
#endif
#ifndef SEARCH_ENGINE_CACHE
// The last entry is now the first entry, to prevent the cache file from being corrupted
if(write_lastentry)
{
//url_rec.reset(OP_NEW_L(DataFile_Record, (TAG_CACHE_LASTFILENAME_ENTRY)));
OpStringC tempstring(file_str+3);
ANCHOR(OpStringC,tempstring);
OpString8 tempstring1;
ANCHOR(OpString8,tempstring1);
tempstring1.SetUTF8FromUTF16L(tempstring.CStr());
tempstring1.Delete(5);
LEAVE_IF_ERROR(cache.WriteBufTag(TAG_CACHE_LASTFILENAME_ENTRY, tempstring1.CStr(), 5));
}
#endif
while((item2 = list.First()) != NULL)
{
item.reset(item2);
item2->Out();
const OpStringC cf_name=item->url.GetAttribute(URL::KFileName);
if(
tag == TAG_VISITED_FILE_ENTRY || !cf_name.IsEmpty()
#if CACHE_SMALL_FILES_SIZE>0
|| item->url.GetRep()->IsEmbedded()
#endif
)
{
disk_entry.Reset();
disk_entry.SetTag(tag);
OP_ASSERT(disk_entry.GetEmbeddedContentSize()==0);
// Fill the disk_entry with all the data required
item->url.GetRep()->WriteCacheDataL(&disk_entry);
#if CACHE_CONTAINERS_ENTRIES>0
if(item->url.GetRep()->GetDataStorage() && item->url.GetRep()->GetDataStorage()->GetCacheStorage())
disk_entry.SetContainerID(item->url.GetRep()->GetDataStorage()->GetCacheStorage()->GetContainerID());
#endif
//url_rec->WriteRecordL(listfile.get());
//url_rec.reset();
// Write all the data on the disk
BOOL embedded=
#if CACHE_SMALL_FILES_SIZE>0
item->url.GetRep()->IsEmbedded()
#else
FALSE
#endif
;
// URLs can be discarded because above the maximum size allowed for the index (maybe because of big headers or
// or becasue they are big data://)
BOOL url_refused=FALSE;
LEAVE_IF_ERROR(disk_entry.WriteValues(&cache, TAG_CACHE_FILE_ENTRY, embedded, url_refused));
// If the URL has been refused, we make it temporary, so it will stay around but it will be deleted when possible
if(url_refused)
item->url.GetRep()->SetAttribute(URL::KCacheType, URL_CACHE_TEMP);
}
if(destroy_urls)
{
DestroyURL(item2->url);
}
item.reset();
}
LEAVE_IF_ERROR(cache.Close((char *)NULL));
}
#endif // CACHE_FAST_INDEX
#endif // DISK_CACHE_SUPPORT
#ifdef DISK_CACHE_SUPPORT
#ifdef SEARCH_ENGINE_CACHE
BOOL Context_Manager::IndexFileL(CacheIndex &index, URL_Rep *url_rep, BOOL force_index, OpFileLength cache_size_limit)
{
OP_STATUS err;
time_t visited = 0;
url_rep->GetAttribute(URL::KVLocalTimeVisited, &visited);
if(!force_index &&
// older than 10 minutes
visited + 600 >= g_timecache->CurrentTime())
return TRUE;
OP_ASSERT(index.IsOpen());
if(index.IsOpen())
{
if(OpStatus::IsError(err = index.Insert(url_rep, cache_size_limit)))
{
index.Abort();
LEAVE(err);
}
if(err == OpBoolean::IS_FALSE)
url_rep->SetAttribute(URL::KCacheType, URL_CACHE_TEMP);
}
else
err = OpBoolean::IS_FALSE;
return err == OpBoolean::IS_TRUE;
}
void Context_Manager::MakeFileTemporary(URL_Rep *url_rep)
{
url_store->m_disk_index.MakeFileTemporary(url_rep);
}
#endif // SEARCH_ENGINE
#endif // DISK_CACHE_SUPPORT
|
#ifndef IMAGEWINDOW_H
#define IMAGEWINDOW_H
#include <QGraphicsView>
#include <../framework/ModuleManager.hpp>
namespace uipf {
class ImageWindow : public QGraphicsView
{
Q_OBJECT
public:
ImageWindow(ModuleManager& mm, QWidget *parent = 0) : QGraphicsView(parent), mm_(mm) {};
ImageWindow(ModuleManager& mm, QGraphicsScene * scene, QWidget * parent = 0) : QGraphicsView(scene, parent), mm_(mm) {};
~ImageWindow() {};
protected:
void closeEvent(QCloseEvent *event);
void keyReleaseEvent(QKeyEvent *event);
private:
ModuleManager& mm_;
};
} // namespace
#endif // MAINWINDOW_H
|
// API_07_DIVWINDOW.cpp : 애플리케이션에 대한 진입점을 정의합니다.
//
#include "framework.h"
#include "API_07_DIVWINDOW.h"
#define IDC_USER 500
#define IDC_BUTTON_SEND IDC_USER + 1
#define IDC_EDIT_TYPO IDC_USER + 2
#define IDC_EDIT_OUT IDC_USER + 3
#define MAX_LOADSTRING 100
// 전역 변수:
HINSTANCE hInst; // 현재 인스턴스입니다.
WCHAR szTitle[MAX_LOADSTRING]; // 제목 표시줄 텍스트입니다.
WCHAR szWindowClass[MAX_LOADSTRING]; // 기본 창 클래스 이름입니다.
// 이 코드 모듈에 포함된 함수의 선언을 전달합니다:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK ChildWndProc(HWND, UINT, WPARAM, LPARAM); // Child Window 프로시저 함수
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: 여기에 코드를 입력합니다.
// 전역 문자열을 초기화합니다.
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_API07DIVWINDOW, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// 애플리케이션 초기화를 수행합니다:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_API07DIVWINDOW));
MSG msg;
// 기본 메시지 루프입니다:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// 함수: MyRegisterClass()
//
// 용도: 창 클래스를 등록합니다.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_API07DIVWINDOW));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_API07DIVWINDOW);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
RegisterClassExW(&wcex); // Frame window 등록
// 자식 윈도우 등록
wcex.lpfnWndProc = ChildWndProc;
wcex.lpszMenuName = NULL;
wcex.lpszClassName = _T("Child Window ClassName");
return RegisterClassExW(&wcex);
}
//
// 함수: InitInstance(HINSTANCE, int)
//
// 용도: 인스턴스 핸들을 저장하고 주 창을 만듭니다.
//
// 주석:
//
// 이 함수를 통해 인스턴스 핸들을 전역 변수에 저장하고
// 주 프로그램 창을 만든 다음 표시합니다.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // 인스턴스 핸들을 전역 변수에 저장합니다.
HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// 함수: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// 용도: 주 창의 메시지를 처리합니다.
//
// WM_COMMAND - 애플리케이션 메뉴를 처리합니다.
// WM_PAINT - 주 창을 그립니다.
// WM_DESTROY - 종료 메시지를 게시하고 반환합니다.
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
static HWND hChild[3];
RECT rectView;
TCHAR str[100];
switch (message)
{
case WM_CREATE :
_stprintf_s(str, _T("ID : %u"), (UINT_PTR)IDC_BUTTON_SEND);
MessageBox(hWnd, str, 0, 0);
GetClientRect(hWnd, &rectView);
hChild[0] = CreateWindowEx(WS_EX_CLIENTEDGE, _T("Child Window ClassName"),
NULL, WS_CHILD | WS_VISIBLE, 0, 0, rectView.right *0.2, rectView.bottom,
hWnd, NULL, hInst, NULL);
hChild[1] = CreateWindowEx(WS_EX_CLIENTEDGE, _T("Child Window ClassName"),
NULL, WS_CHILD | WS_VISIBLE, rectView.right * 0.2, 0, rectView.right, rectView.bottom / 2-1,
hWnd, NULL, hInst, NULL);
hChild[2] = CreateWindowEx(WS_EX_CLIENTEDGE, _T("Child Window ClassName"),
NULL, WS_CHILD | WS_VISIBLE, rectView.right * 0.2, rectView.bottom / 2 + 1, rectView.right, rectView.bottom / 2 - 1,
hWnd, NULL, hInst, NULL);
return 0;
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// 메뉴 선택을 구문 분석합니다:
switch (wmId)
{
case IDC_BUTTON_SEND:
break;
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: 여기에 hdc를 사용하는 그리기 코드를 추가합니다...
EndPaint(hWnd, &ps);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// 정보 대화 상자의 메시지 처리기입니다.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
//
LRESULT CALLBACK ChildWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
static HWND hBtnSend, hEditTypo, hEditOut;
static TCHAR str[100];
switch (message) {
case WM_CREATE:
hBtnSend = CreateWindow(_T("button"), _T("전송"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON
, 10, 10, 210, 60,hWnd,(HMENU)IDC_BUTTON_SEND, hInst, NULL);
hEditTypo = CreateWindow(_T("edit"), _T(""), WS_CHILD | WS_VISIBLE | WS_BORDER,
220, 10, 400, 60, hWnd, (HMENU)IDC_EDIT_TYPO, hInst, NULL);
hEditOut = CreateWindow(_T("edit"), _T(""), WS_CHILD | WS_VISIBLE | WS_BORDER,
220, 70, 400, 130, hWnd, (HMENU)IDC_EDIT_OUT, hInst, NULL);
break;
case WM_COMMAND :
switch (LOWORD(wParam)) {
case IDC_BUTTON_SEND :
GetDlgItemText(hWnd,IDC_EDIT_TYPO, str, 100);
SetDlgItemText(hWnd, IDC_EDIT_OUT, str);
MessageBox(hWnd, str, 0, 0);
SetDlgItemText(hWnd, IDC_EDIT_TYPO, _T(""));
break;
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
}
return DefWindowProc(hWnd, message, wParam, lParam);
}
|
/*
* @lc app=leetcode id=64 lang=cpp
*
* [64] Minimum Path Sum
*
* https://leetcode.com/problems/minimum-path-sum/description/
*
* algorithms
* Medium (47.77%)
* Likes: 1484
* Dislikes: 42
* Total Accepted: 245.3K
* Total Submissions: 513.4K
* Testcase Example: '[[1,3,1],[1,5,1],[4,2,1]]'
*
* Given a m x n grid filled with non-negative numbers, find a path from top
* left to bottom right which minimizes the sum of all numbers along its path.
*
* Note: You can only move either down or right at any point in time.
*
* Example:
*
*
* Input:
* [
* [1,3,1],
* [1,5,1],
* [4,2,1]
* ]
* Output: 7
* Explanation: Because the path 1→3→1→1→1 minimizes the sum.
*
*
*/
class Solution {
public:
int min(int a, int b) {
return a < b ? a : b;
}
int minPathSum(vector<vector<int>>& grid) {
int rows = grid.size();
int cols = grid[0].size();
int dp[rows][cols] = {0};
dp[0][0] = grid[0][0];
for (int c = 1; c < cols; ++c)
dp[0][c] = grid[0][c] + dp[0][c - 1];
for (int r = 1; r < rows; ++r)
dp[r][0] = grid[r][0] + dp[r - 1][0];
for (int i = 1; i < rows; ++i) {
for (int j = 1; j < cols; ++j) {
dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1]);
}
}
return dp[rows - 1][cols - 1];
}
};
|
#ifndef ESPChipConnection_h
#define ESPChipConnection_h
#include <Arduino.h>
#include <SoftwareSerial.h>
class NetworkController {
private:
int PIN_RX;
int PIN_TX;
String ssid;
String pw;
void sendSerialMessage(String msg);
public:
NetworkController(int pinRx, int pinTx, String ssid, String pw);
void establishConnection(String ssid, String pw);
void uploadTemperature(String temp);
void testConnection();
};
#endif
|
#ifndef KDTREE_H_
#define KDTREE_H_
#include <memory>
// Structure to represent node of kd tree
template<typename PointT>
struct Node
{
PointT point;
int id;
std::unique_ptr<Node> left;
std::unique_ptr<Node> right;
Node(const PointT &pnt, int setId)
: point(pnt), id(setId), left(nullptr), right(nullptr)
{}
};
template<typename PointT>
struct KdTree
{
std::unique_ptr<Node<PointT>> root;
KdTree()
: root(nullptr) {}
void insert(const PointT &point, int id)
{
// the function should create a new node and place correctly with in the root
if (root == nullptr)
{
root = std::unique_ptr<Node<PointT>>(new Node<PointT>(point, id));
}
else
{
// traverse tree
const int pointDimensions = 3;
int depth = 0;
// alias current node
Node<PointT> *node = root.get();
// TODO: restrict depth to a max value
while (true) {
const int check_index = depth % pointDimensions;
if (point.data[check_index] < node->point.data[check_index]) {
if (node->left == nullptr) {
node->left = std::unique_ptr<Node<PointT>>(new Node<PointT>(point, id));
break;
} else {
node = node->left.get();
}
} else {
if (node->right == nullptr) {
node->right = std::unique_ptr<Node<PointT>>(new Node<PointT>(point, id));
break;
} else {
node = node->right.get();
}
}
depth++;
}
}
}
void searchHelper(const PointT &target, const float distanceTol, std::unique_ptr<Node<PointT>> &node, const int depth, std::vector<int> &ids) {
const int pointDimensions = 3;
if (node != nullptr) {
const int dim = depth % pointDimensions;
if (target.data[dim] + distanceTol < node->point.data[dim]) {
// not in box, recurse into left only
searchHelper(target, distanceTol, node->left, depth + 1, ids);
} else if (target.data[dim] - distanceTol > node->point.data[dim]) {
// not in box, recurse into right only
searchHelper(target, distanceTol, node->right, depth + 1, ids);
} else {
// target is in this dimension's box range
// check remaining dimensions and radius
bool inside_box = true;
double sumsqr = std::pow(target.data[dim] - node->point.data[dim], 2.0);
for (int k = 1; k < pointDimensions; ++k) {
const int test_dim = (dim + k) % pointDimensions;
if ((target.data[test_dim] + distanceTol < node->point.data[test_dim]) ||
(target.data[test_dim] - distanceTol > node->point.data[test_dim])) {
inside_box = false;
break;
} else {
sumsqr += std::pow(target.data[test_dim] - node->point.data[test_dim], 2.0);
}
}
if (inside_box && std::sqrt(sumsqr) <= distanceTol) {
ids.push_back(node->id);
}
// recurse into both sides
searchHelper(target, distanceTol, node->left, depth + 1, ids);
searchHelper(target, distanceTol, node->right, depth + 1, ids);
}
}
}
// return a list of point ids in the tree that are within distance of target
std::vector<int> search(const PointT &target, float distanceTol)
{
std::vector<int> ids;
if (root == nullptr)
{
PCL_ERROR ("KdTree has no points \n");
}
else
{
// traverse tree
searchHelper(target, distanceTol, root, 0, ids);
}
return ids;
}
};
#endif // KDTREE_H_
|
#include <iostream>
#include <vector>
using namespace std;
#define MAX_ARR 4
vector<int> countingSort(vector<int> arr)
{
vector<int> countArr;
countArr.assign(MAX_ARR, 0);
for(int i=0; i < arr.size(); i++)
{
int index = arr[i];
countArr[index] += 1;
}
return countArr;
}
int main()
{
vector<int> mArray = {1, 1, 3, 2, 1};
vector<int> result = countingSort(mArray);
for(auto & n: result)
{
cout << n << " ";
}
return 0;
}
|
#ifndef USART2_H
#define USART2_H
#include "serial.h"
#include "message/ithread.h"
#include <QThread>
#define USART2_DEVNAME ("/dev/ttySAC1")
class USART2 : public Serial
{
public:
USART2();
~USART2();
public:
static USART2* getInstance(void);
void initSerialPort(int dataBits, int parity, int stopBits, int baud);
void run(void);
void getData(char* buf);
private:
void saveData(char* src, int len);
private:
char deviceName[30];
char txBuf[1024];
char rxBuf[1024];
static USART2* s_pInstance;
static QThread* thread;
QMutex rxBufMutex;
};
#endif // USART2_H
|
#include "../include/RenderableObject.h"
#include "../include/Renderer.h"
RenderableObject::RenderableObject()
{
//_IsMoveCheck = false;
Renderer::GetInstance()->addRenderObject(this);
position = glm::vec3(0.0f, 0.0f, 0.0f);
rotVec = glm::vec3(0.0f, 0.0f, 0.0f);
scaleVec = glm::vec3(0.0f, 0.0f, 0.0f);
Rot = glm::mat4(1.0f);
Scale = glm::mat4(1.0f);
rotSpeed = 0.0f;
}
|
#include <bits/stdc++.h>
#include <vector>
using namespace std;
int main()
{
// Assign vector
vector<int> v;
// fill the array with 10 five times
v.assign(5, 10); // we can write : vector<int>v(5,10);
cout << "The vector elements are: ";
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
// inserts 15 to the last position
v.push_back(15);
int n = v.size();
cout << "\nThe last element is: " << v[n - 1];
// removes last element
v.pop_back();
// prints the vector
cout << "\nAfter pop_back() the vector elements are: ";
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
// inserts 5 at the beginning
v.insert(v.begin(), 5); // we can insert multiple element at a time like: v.insert(v.begin(),{5,6,7})
cout << "\nThe first element is: " << v[0];
//insert element at given position
v.insert(v.begin()+3,7);
cout << "\nafter inserting element at 3rd index are: ";
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
// removes the first element
v.erase(v.begin()); // we can delete elements upto some range like: v.erase(v.begin(),v.begin()+3)
cout << "\n after delete first element: "<<endl ;
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
// removes the specified position element
v.erase(v.begin()+2);
cout << "\n after delete 2nd index element: "<<endl ;
for (int i = 0; i < v.size(); i++)
cout << v[i] << " ";
// inserts at the beginning
v.emplace(v.begin(), 5);
cout << "\nThe first element is: " << v.front();//v[0];
// Inserts 20 at the end
v.emplace_back(20);
n = v.size();
cout << "\nThe last element is: " << v.back(); //v[n - 1];
// erases the vector
v.clear();
cout << "\nVector size after clear(): " << v.size();
}
|
#include <ZSharpIR.h>
#include <RunningMedian.h>
// define the number of runs to calculate median
#define NumOfRuns 20
// define 5 short range sensors
#define SENSOR_1 A0
#define SENSOR_2 A1
#define SENSOR_3 A2
#define SENSOR_4 A3
#define SENSOR_5 A4
// define 1 long range sensors
#define SENSOR_6 A5
//long range sensors
ZSharpIR sensor1(SENSOR_1, 1080);
ZSharpIR sensor2(SENSOR_2, 1080);
ZSharpIR sensor3(SENSOR_3, 1080);
ZSharpIR sensor4(SENSOR_4, 1080);
ZSharpIR sensor5(SENSOR_5, 1080);
//short range sensors
ZSharpIR sensor6(SENSOR_6, 20150);
//RunningMedian class to calculate the median values from the sensor
RunningMedian sensor1Values(NumOfRuns);
RunningMedian sensor2Values(NumOfRuns);
RunningMedian sensor3Values(NumOfRuns);
RunningMedian sensor4Values(NumOfRuns);
RunningMedian sensor5Values(NumOfRuns);
RunningMedian sensor6Values(NumOfRuns);
void setup() {
//initialize the variables we're linked to
Serial.begin(9600);
}
void loop() {
//getReading();
getMedianReading();
delay(5000);
}
void getReading(){
Serial.print("Front Right sensor 1 reading: ");
Serial.println(sensor1.distance());
Serial.print("Front Mid sensor 2 reading: ");
Serial.println(sensor2.distance());
Serial.print("Front Left sensor 3 reading: ");
Serial.println(sensor3.distance());
Serial.print("Left Front sensor 4 reading: ");
Serial.println(sensor4.distance());
Serial.print("Left Back sensor 5 reading: ");
Serial.println(sensor5.distance());
Serial.print("Right Long sensor 6 reading: ");
Serial.println(sensor6.distance());
}
void getMedianReading(){
for (int i=0; i<NumOfRuns; i++){
sensor1Values.add(sensor1.distance());
sensor2Values.add(sensor2.distance());
sensor3Values.add(sensor3.distance());
sensor4Values.add(sensor4.distance());
sensor5Values.add(sensor5.distance());
sensor6Values.add(sensor6.distance());
}
Serial.print("Front Right sensor 1 median reading: ");
Serial.println(sensor1Values.getMedian());
Serial.print("Front Mid sensor 2 median reading: ");
Serial.println(sensor2Values.getMedian());
Serial.print("Front Left sensor 3 median reading: ");
Serial.println(sensor3Values.getMedian());
Serial.print("Left Front sensor 4 median reading: ");
Serial.println(sensor4Values.getMedian());
Serial.print("Left Back sensor 5 median reading: ");
Serial.println(sensor5Values.getMedian());
//Comment this line to avoid using long range sensor 6
// Serial.print("Right Long sensor 6 median reading: ");
// Serial.println(sensor6Values.getMedian());
}
|
// Copyright (c) 2011 Thomas Heller
// Copyright (c) 2014 Bryce Adelstein-Lelbach
//
// SPDX-License-Identifier: BSL-1.0
// 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)
#include <pika/functional/function.hpp>
#include <pika/modules/timing.hpp>
#include <pika/pika.hpp>
#include <pika/modules/program_options.hpp>
// noinshpect to silence inshpect check for deprecated includes and names
// (boost::function later in the file)
#include <boost/function.hpp>
#include <cstdint>
#include <functional>
#include <iostream>
#include "worker_timed.hpp"
using pika::program_options::command_line_parser;
using pika::program_options::notify;
using pika::program_options::options_description;
using pika::program_options::store;
using pika::program_options::value;
using pika::program_options::variables_map;
std::uint64_t iterations = 500000;
std::uint64_t delay = 5;
struct foo
{
void operator()() const { worker_timed(delay * 1000); }
};
template <typename F>
void run(F const& f, std::uint64_t local_iterations)
{
std::uint64_t i = 0;
pika::chrono::detail::high_resolution_timer t;
for (; i < local_iterations; ++i) f();
double elapsed = t.elapsed();
std::cout << " walltime/iteration: " << ((elapsed / i) * 1e9) << " ns\n";
}
int app_main(variables_map& vm)
{
{
foo f;
std::cout << "baseline";
run(f, iterations);
}
{
pika::util::detail::function<void(), false> f = foo();
std::cout << "pika::util::detail::function (non-serializable)";
run(f, iterations);
}
{
pika::util::detail::function<void()> f = foo();
std::cout << "pika::util::detail::function (serializable)";
run(f, iterations);
}
{
boost::function<void()> f = foo();
std::cout << "boost::function";
run(f, iterations);
}
{
std::function<void()> f = foo();
std::cout << "std::function";
run(f, iterations);
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
///////////////////////////////////////////////////////////////////////////
// Parse command line.
variables_map vm;
options_description cmdline("Usage: " PIKA_APPLICATION_STRING " [options]");
cmdline.add_options()("help,h", "print out program usage (this message)")
("iterations", value<std::uint64_t>(&iterations)->default_value(500000),
"number of iterations to invoke for each test")
("delay", value<std::uint64_t>(&delay)->default_value(5),
"duration of delay in microseconds");
store(command_line_parser(argc, argv).options(cmdline).run(), vm);
notify(vm);
// Print help screen.
if (vm.count("help"))
{
std::cout << cmdline;
return 0;
}
return app_main(vm);
}
|
#include "UIElement.h"
UIElement::UIElement(int UIElementID, GameEngine* Engine) :GameObject() {
engine = Engine;
if (UIElementID == 2) {
spriteIcon.loadFromFile("spritesheet.png", sf::IntRect(96, 0, 32, 32));
icon.setTexture(spriteIcon);
icon.setScale(800.0 / 32, 200.0 / 32);
icon.setPosition(0, WINDOW_HEIGHT-200);
}
}
UIElement::UIElement() : GameObject() {
}
void UIElement::update(sf::Time time) {
}
|
#include <include/cef_app.h>
int mainImpl(CefMainArgs & args);
int main(int argc, char ** argv) {
CefMainArgs args { argc, argv };
return mainImpl(args);
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
#include <limits.h>
using namespace std;
typedef long long ll;
#define INF 10e10
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define END cout << endl
#define MOD 1000000007
#define pb push_back
#define sorti(x) sort(x.begin(), x.end())
#define sortd(x) sort(x.begin(), x.end(), std::greater<int>())
// Beet's Segment Tree Library (Thanks for Beet)
template <typename T, typename E>
struct SegmentTree {
typedef function<T(T,T)> F;
typedef function<T(T,E)> G;
int n;
F f; // function<T(T,T)>
G g; // function<T(T,E)>
T d1; // template T
E d0; // template E
vector<T> dat;
// constractor
SegmentTree() {};
/*
* @param
* int n_ : number of elements
* F f : compare elements function
* G g : ?
* T d1: init value
*/
SegmentTree(int n_, F f, G g, T d1, vector<T> v = vector<T>()) :
f(f), g(g), d1(d1) {
init(n_);
if (n_ == (int)v.size()) build(n_, v);
}
// member methods
void init(int n_) {
n = 1;
while (n < n_) n *= 2;
dat.clear();
dat.resize(2*n-1, d1);
}
void build(int n_, vector<T> v) {
for (int i = 0; i < n_; ++i) dat[i+n-1] = v[i];
for (int i = n-2; i >= 0; --i) dat[i] = f(dat[i*2+1], dat[i*2+2]);
}
void update(int k, E a) {
k += n-1;
dat[k] = g(dat[k], a);
while (k > 0) {
k = (k - 1) / 2;
dat[k] = f(dat[k*2+1], dat[k*2+2]);
}
}
inline T query(int a, int b) {
T vl = d1, vr = d1;
for (int l = a + n, r = b + n; l < r; l >>= 1) {
if (l & 1) vl = f(vl, dat[(l++) - 1]);
if (r & 1) vr = f(dat[(--r)-1], vr);
}
return f(vl,vr);
}
};
int main() {
int n,q;
cin >> n >> q;
SegmentTree<int, int> rmq(n,
[](int a, int b){return min(a,b);},
[](int a, int b){return b;},
INT_MAX);
for (int i = 0; i < q; ++i) {
int c,x,y;
cin >> c >> x >> y;
if (c) cout << rmq.query(x,y+1) << endl;
else rmq.update(x,y);
}
}
|
#include "PlaneObject.hh"
PlaneObject :: PlaneObject(const Vector3F &surfaceNormal, float distanceFromOrigin){
this->surfaceNorm = surfaceNormal;
this->distanceFromOrigin = distanceFromOrigin;
}
Vector3F PlaneObject :: get_surfaceNormal(void) const{
return surfaceNorm;
}
float PlaneObject :: get_distanceFromOrigin(void) const{
return distanceFromOrigin;
}
/* Intersection point of a ray is: t = -(P · N + d) / (D · N) */
float PlaneObject :: intersection(const Ray &r) const{
float intersectionPoint;
Vector3F rayDir = r.get_dir();
Vector3F rayOrig = r.get_orig();
float denominator = rayDir * surfaceNorm;
float numerator = -((rayOrig * surfaceNorm) + distanceFromOrigin);
if(denominator == 0){
intersectionPoint = NO_INTERSECTION;
}else{
intersectionPoint = numerator / denominator;
/* Only values of t >= 0 are considered to be intersections */
if(intersectionPoint < 0){
intersectionPoint = 0;
}
}
return intersectionPoint;
}
Vector3F PlaneObject :: surfaceNormal(const Vector3F &point) const{
return surfaceNorm;
}
|
#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/gpio.h"
#include "hardware/clocks.h"
#include "hardware/pwm.h"
typedef uint16_t u16;
typedef uint32_t u32;
#define SPK 19
int main()
{
// set your desired inputs here
const u32 f_pwm = 440; // frequency we want to generate
const u16 duty = 60; // duty cycle, in percent
gpio_set_function(SPK, GPIO_FUNC_PWM);
uint slice_num = pwm_gpio_to_slice_num(SPK);
// set frequency
// determine top given Hz - assumes free-running counter rather than phase-correct
u32 f_sys = clock_get_hz(clk_sys); // typically 125'000'000 Hz
float divider = f_sys / 1'000'000UL; // let's arbitrarily choose to run pwm clock at 1MHz
pwm_set_clkdiv(slice_num, divider); // pwm clock should now be running at 1MHz
u32 top = 1'000'000UL/f_pwm -1; // TOP is u16 has a max of 65535, being 65536 cycles
pwm_set_wrap(slice_num, top);
// set duty cycle
u16 level = (top+1) * duty / 100 -1; // calculate channel level from given duty cycle in %
pwm_set_gpio_level(SPK, level);
pwm_set_enabled(slice_num, true); // let's go!
for(;;);
return 0;
}
|
/** Kabuki SDK
@file /.../Source/Kabuki_SDK/include/_Com/MIDI/String.h
@author Cale McCollough
@copyright Copyright © 2016 Cale McCollough ©
@license Read accompanying /.../README.md or online at http://www.boost.org/LICENSE_1_0.txt
*/
#pragma once
namespace _Com {
namespace MIDI {
/** This class represents a String that can be displaYed on a standard MIDI complaitble device.
This class contains a few usingant static functions for verifiYing if a String is valid. */
class String
{
public:
static const int DefaultLength = 16; //< The maximum length of a String.
String(const char * initString=NULL); //< Default constructor.
~String(); //< Destructor.
string GetString(); //< The text of this String.
int SetText(const char newName[]); //< Renames this control to the newName.
/*< @pre String::isValid(newString) must be true.
@param newName The new nameText string. */
void ForceText(char *newName); //< Renames this control to newName without error checking.
/*< @param newName The new name for this String.
@warning Does not perform error checking! */
bool CompairedTo(String *thatString); //< Compaires this String to thatString and returns true if theY are identical(before the NULL term char).
bool CompairedTo(char *thatString) const; //< Compaires this String to thatString and returns true if theY are identical(before the NULL term char).
static char *Format(const char *thisString); //< Formats thisString to remove anY invalid charictors.
/*< @param newName The text string to be formatted.
@return Returns a new instance of the formatted string */
static bool IsValid(const char thisChar); //< Checks to see if thisChar is a valid String char.
/*< @param thisChar The char to check the validitY of. */
static bool IsValid(const char *thisString); //< Checks to see if thisString is a valid String
/*< @pre thisString must be initialized
@return Returns true thisString if everY char in thisString isValid.
@param thisName The String to check the validitY of. */
char *ToString(); //< Returns a string representation of this object.
private:
char *stringText; //< The text of this String.
};
}
}
|
#include <vector>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <unordered_map>
#include <algorithm>
#include <fstream>
#include <sstream>
using namespace std;
int main(int argc, char** argv)
{
ifstream f;
f.open(argv[1]);
string s;
vector<int> numbers;
int result=0;
int median;
while(getline(f,s))
{
int num;
stringstream st(s);
st>>num;
numbers.push_back(num);
sort(numbers.begin(),numbers.end());
if (numbers.size() % 2 == 0)
median = numbers[numbers.size() / 2 - 1];
else
median = numbers[numbers.size() / 2];
result += median;
result %= 10000;
}
cout<<result<<"\n";
return 0;
}
|
#ifndef PERSONNE_H
#define PERSONNE_H
#include"QString"
#include"QDebug"
#include "connection.h"
#include "QSqlQueryModel"
#include <QPalette>
#include <QDesktopWidget>
#include <QtGui>
class Personne
{
private:
QString Prenom ;
QString Nom;
QString Num_Tel;
QString CIN ;
QString Adresse ;
int ID;
public:
Personne();
Personne(QString Prenom,QString Nom,QString Num_Tel,QString CIN,QString Adresse,int ID);
QString getNom(){return Nom;};
QString getPrenom(){return Prenom;} ;
QString getNum_Tel() {return Num_Tel;};
QString getCIN() {return CIN;};
QString getAdresse(){return Adresse;};
int getID(){return ID;};
virtual bool AjoutPersonne(Personne *PE);
virtual QSqlQueryModel * AfficherPersonne();
QSqlQueryModel * RechercherPersonne(int ID);
bool SupprimerPersonne(int ID);
bool ModifierPersonne (Personne *PE);
};
#endif // PERSONNE_H
|
#include <iostream>
#include <string>
int main() {
std::string xosq[4] = {"barev","vonc es","dasern inchpes en","hajox"};
std::cout<<"Barev sireli ogtater. Es Chat_bot em ev karox em patasxanel ays harcerin \n";
for(int i = 0; i < 4; ++i) {
std::cout<<xosq[i]<<std::endl;
}
std::string question;
while(true) {
int arjeq = -1;
std::cout<<"Tveq dzer harc@ -> ";
std::getline(std::cin, question);
for(int i = 0; i < 4; ++i) {
if(xosq[i] == question) {
arjeq = i;
}
}
switch(arjeq) {
case (0): std::cout<<"Bot -> barev \n";
break;
case (1): std::cout<<"Bot -> shat lav em \n";
break;
case (2): std::cout<<"Bot -> uxxaki artakarg \n";
break;
default: std::cout<<"Bot -> chem haskanum harcd \n";
case (3): std::cout<<"Bot -> bye \n";
return 0;
}
}
return 0;
}
|
/*
Copyright 2021 University of Manchester
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.
*/
#pragma once
#include "acceleration_module.hpp"
#include "memory_manager_interface.hpp"
#include "multiplication_interface.hpp"
namespace orkhestrafs::dbmstodspi {
/**
* @brief Class which implements low level memory writes to the multiplication
* operation accelerator.
*
* This is for decimal(15,2) multiplication. Which means there is a loss of
* accuracy since the results are floored not rounded.
*/
class Multiplication : public AccelerationModule,
public MultiplicationInterface {
private:
public:
~Multiplication() override = default;
/**
* @brief Constructor to set the memory manager instance to access memory
* mapped registers.
* @param memory_manager Memory manager instance to access memory mapping.
* @param module_position Position of the module in the bitstream.
*/
explicit Multiplication(MemoryManagerInterface* memory_manager,
int module_position)
: AccelerationModule(memory_manager, module_position){};
/**
* @brief Defube which streams need to have the multiplication operation.
* @param active_streams Array of booleans noting active streams.
*/
void DefineActiveStreams(std::bitset<16> active_streams) override;
/**
* @brief Define which positions in which chunk should have the multiplication
* results.
* @param chunk_id Which chunk is being configured.
* @param active_positions Which positions should have the multiplication
* result.
*/
void ChooseMultiplicationResults(int chunk_id,
std::bitset<8> active_positions) override;
};
} // namespace orkhestrafs::dbmstodspi
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2009 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
*/
#include "core/pch.h"
#ifdef APPLICATION_CACHE_SUPPORT
#include "modules/applicationcache/src/application_cache_common.h"
#include "modules/applicationcache/application_cache_manager.h"
UpdateAlgorithmArguments::~UpdateAlgorithmArguments()
{
if (InList())
Out();
if (m_owner)
m_owner->SetRestartArguments(NULL);
}
#endif // APPLICATION_CACHE_SUPPORT
|
//
// Created by 송지원 on 2020/07/04.
//
#include <iostream>
using namespace std;
int input[7];
int MIN = 100;
int SUM;
int main() {
for (int i=0; i<7; i++) {
cin >> input[i];
if (input[i] % 2 == 1) {
SUM += input[i];
if (input[i] < MIN) MIN=input[i];
}
}
if (SUM != 0) cout << SUM << "\n" << MIN;
else cout << -1;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.