text
stringlengths 8
6.88M
|
|---|
#include "com_wind_ndk_opengles_n_NativeGLRenderer.h"
#include "GLLooper.h"
#include <android/native_window.h>
#include <android/native_window_jni.h>
#include "android/bitmap.h"
#include "global.h"
#ifdef __cplusplus
extern "C" {
#endif
ANativeWindow* window=0;
JNIEXPORT void JNICALL Java_com_wind_ndk_opengles_n_NativeGLRenderer_native_1init
(JNIEnv *, jobject){
//创建looper
glLooper=new GLLooper();
}
JNIEXPORT void JNICALL Java_com_wind_ndk_opengles_n_NativeGLRenderer_native_1on_1surface_1created
(JNIEnv *env, jobject, jobject jsurface) {
if (window!=NULL){
ANativeWindow_release(window);
window=NULL;
}
window=ANativeWindow_fromSurface(env,jsurface);
if(glLooper){
glLooper->postMessage(kMsgSurfaceCreated,window);
}
}
JNIEXPORT void JNICALL Java_com_wind_ndk_opengles_n_NativeGLRenderer_native_1on_1surface_1changed
(JNIEnv *, jobject, jobject , jint width, jint height) {
if(glLooper){
glLooper->postMessage(kMsgSurfaceChanged,width,height);
}
}
JNIEXPORT void JNICALL Java_com_wind_ndk_opengles_n_NativeGLRenderer_native_1on_1surface_1destroy
(JNIEnv *, jobject) {
if(glLooper){
glLooper->postMessage(kMsgSurfaceDestroyed);
}
}
JNIEXPORT void JNICALL Java_com_wind_ndk_opengles_n_NativeGLRenderer_native_1update_1tex_1image
(JNIEnv *env, jobject, jbyteArray jbitmap,jint width,jint height){
if(glLooper){
// ALOGE("post kMsgUpdateTexImage %d",Pixles);
//glLooper->postMessage(kMsgUpdateTexImage,width,height, Pixles);
}
/*AndroidBitmapInfo bitmapInfo;
AndroidBitmap_getInfo(env,jbitmap,&bitmapInfo);
int width=bitmapInfo.width;
int height=bitmapInfo.height;
void* bytes;
AndroidBitmap_lockPixels(env, jbitmap, &bytes);
AndroidBitmap_unlockPixels(env,jbitmap);
if(glLooper){
ALOGE("post kMsgUpdateTexImage");
glLooper->postMessage(kMsgUpdateTexImage,width,height,bytes);
}*/
}
#ifdef __cplusplus
}
#endif
|
#pragma once
class Student{
};
|
// Nama : Naufal Dean Anugrah
// NIM : 13518123
// Tanggal : 23 Januari 2020
// Topik : Pengenalan class
#include <iostream>
#include "Polinom.hpp"
using namespace std;
// ctor, cctor, dtor, op=
// untuk konstruktor, inisialisasi seluruh nilai koefisien dengan 0.
Polinom::Polinom() : Polinom(0) {}
// ctor Polinom dengan orde = 0
Polinom::Polinom(int n) {
// ctor Polinom dengan orde = n (sesuai parameter)
this->derajat = n;
for (int i = 0; i <= n; i++) {
this->koef[i] = 0;
}
}
Polinom::Polinom(const Polinom& Pol) {
this->derajat = Pol.derajat;
for (int i = 0; i <= this->derajat; ++i) {
this->koef[i] = Pol.koef[i];
}
}
Polinom::~Polinom() {
}
Polinom& Polinom::operator=(const Polinom& Pol) {
this->derajat = Pol.derajat;
for (int i = 0; i <= this->derajat; ++i) {
this->koef[i] = Pol.koef[i];
}
return *this;
}
// getter, setter
int Polinom::getKoefAt(int idx) const {
return this->koef[idx];
}
int Polinom::getDerajat() const {
return this->derajat;
}
void Polinom::setKoefAt(int idx, int val) {
this->koef[idx] = val;
}
void Polinom::setDerajat(int der) {
this->derajat = der;
}
// operator overloading
// Untuk setiap operator, **tidak perlu mengubah nilai derajat tertinggi**
// Orde Polinom hasil operasi adalah MAX(orde Polinom 1, orde Polinom 2)
Polinom operator+(const Polinom& P1, const Polinom& P2) {
// Penjumlahan 2 buah Polinom.
// Kamus lokal
Polinom P(max(P1.derajat, P2.derajat));
// Algoritma
for (int i = 0; i <= min(P1.derajat, P2.derajat); ++i) {
P.koef[i] = P1.koef[i] + P2.koef[i];
}
if (P1.derajat > P2.derajat) {
for (int i = P2.derajat + 1; i <= P1.derajat; i++)
P.koef[i] = P1.koef[i];
} else if (P1.derajat < P2.derajat) {
for (int i = P1.derajat + 1; i <= P2.derajat; i++)
P.koef[i] = P2.koef[i];
}
return P;
}
Polinom operator-(const Polinom& P1, const Polinom& P2) {
// Pengurangan 2 buah Polinom.
// Kamus lokal
Polinom P(max(P1.derajat, P2.derajat));
// Algoritma
for (int i = 0; i <= min(P1.derajat, P2.derajat); ++i) {
P.koef[i] = P1.koef[i] - P2.koef[i];
}
if (P1.derajat > P2.derajat) {
for (int i = P2.derajat + 1; i <= P1.derajat; i++)
P.koef[i] = P1.koef[i];
} else if (P1.derajat < P2.derajat) {
for (int i = P1.derajat + 1; i <= P2.derajat; i++)
P.koef[i] = -P2.koef[i];
}
return P;
}
Polinom operator*(const Polinom& P1, const int K) {
// Perkalian Polinom dengan konstanta
// Kamus lokal
Polinom P(P1.derajat);
// Algoritma
for (int i = 0; i <= P1.derajat; ++i) {
P.koef[i] = P1.koef[i] * K;
}
return P;
}
Polinom operator*(const int K, const Polinom& P1) {
// Perkalian Polinom dengan konstanta (sifat komutatif)
// Kamus lokal
Polinom P(P1.derajat);
// Algoritma
for (int i = 0; i <= P1.derajat; ++i) {
P.koef[i] = P1.koef[i] * K;
}
return P;
}
Polinom operator/(const Polinom& P1, const int K) {
// Pembagian bilangan bulat. Tidak perlu menangani apabila kasus pembagi = 0.
// Kamus lokal
Polinom P(P1.derajat);
// Algoritma
for (int i = 0; i <= P1.derajat; ++i) {
P.koef[i] = P1.koef[i] / K;
}
return P;
}
// member function
// Melakukan pembacaan koefisien sejumlah derajat Polinom, dimulai dari x^0 (konstanta)
void Polinom::input() {
for (int i = 0; i <= this->derajat; ++i) {
cin >> this->koef[i];
}
}
// Mencetak seluruh koefisien polinom. Untuk setiap koefisien akhiri dengan end-of-line
// Cetaklah apa adanya dari koefisien ke-0 hingga derajat tertinggi (termasuk apabila koefisien = 0)
void Polinom::printKoef() {
for (int i = 0; i <= this->derajat; ++i) {
cout << this->koef[i] << endl;
}
}
// Menghitung hasil substitusi x dengan sebuah bilangan ke dalam polinom
int Polinom::substitute(int x) {
// Kamus lokal
int sum = this->getKoefAt(this->derajat);
// Algoritma
for (int i = this->derajat - 1; i >= 0; i--) {
sum = sum * x + this->getKoefAt(i);
}
return sum;
}
// Melakukan aksi derivasi terhadap Polinom.
// Lakukan pengurangan pada derajat tertinggi Polinom.
// Apabila derajat tertinggi = 0, hasil derivasi = 0 (dengan derajat tertinggi = 0)
Polinom Polinom::derive() {
int degree = (this->derajat) ? (this->derajat - 1) : 0;
Polinom POut(degree);
for (int i = this->derajat - 1; i >= 0; i--) {
POut.setKoefAt(i, (i + 1) * this->getKoefAt(i + 1));
}
return POut;
}
// ** METHOD BONUS (TC 12,13,14) ** (Tidak wajib dikerjakan)
// Mencetak polinom dengan format: A+Bx^1+Cx^2+Dx^3...dst (diakhiri dengan end-of-line)
// Apabila suatu koefisien bernilai < 0, gunakan tanda "-" untuk menggantikan tanda "+"
// Apabila suatu koefisien bernilai 0, lewati koefisien tersebut dan lanjutkan ke koefisien selanjutnya
// Jika seluruh koefisien bernilai 0, keluarkan "0"
void printElmt(int i, bool printed, const Polinom& P) {
// Prekondisi: P.getKoefAt(i) != 0
// Sign
if (P.getKoefAt(i) > 0 && printed)
cout << "+";
if (P.getKoefAt(i) < 0)
cout << "-";
// Coefficient and variable
if (i == 0) {
cout << abs(P.getKoefAt(i));
} else { // i > 0
if (abs(P.getKoefAt(i)) != 1)
cout << abs(P.getKoefAt(i));
cout << "x^" << i;
}
}
void Polinom::print() {
bool printed = false;
for (int i = 0; i <= getDerajat(); i++) {
if (getKoefAt(i) != 0) {
printElmt(i, printed, *this);
printed = true;
}
}
if (!printed) cout << "0";
cout << endl;
}
|
#include <bits/stdc++.h>
using namespace std;
int main()
{
long long a,i,sum;
while(scanf("%lld",&a)!=EOF){
if(a==0) break;
sum=0;
for(i=1;i<=a;i++){
sum=sum+(i*i);
}
cout<<sum<<endl;
}
return 0;
}
|
#ifndef TIME_H
#define TIME_H
#include "commun.h"
class time
{
static double _time_prev;
static double _time_fps_prev;
static uint _fps;
static float _dt;
public:
static double get_time();
static float get_delta_time();
static void update();
};
#endif //!TIME_H
|
/*
* 机器人可回退
*/
const int maxn = 101;
class Solution {
public:
int mark[maxn][maxn];
int movingCount(int k, int rows, int cols)
{
if(rows <= 0 || cols <= 0 || k<=0){
return 0;
}
//构建数组
vector<vector<int> > mat;
for(int i=0; i<rows; ++i){
vector<int> temp;
for(int j=0; j<cols; ++j){
temp.push_back(cal(i)+cal(j));
}
mat.push_back(temp);
}
int ans = 0;
memset(mark,false,sizeof(mark));
search(mat,0,0,ans,k);
return ans;
}
void search(vector<vector<int> > &mat,int x,int y,int &ans,int k){
if(x < 0 || x >= mat.size() || y < 0 || y >= mat[0].size() || mark[x][y] || mat[x][y] > k){
return;
}
ans++;
mark[x][y] = true;
static const int dx[] = {-1,1,0,0};
static const int dy[] = {0,0,-1,1};
for(int i=0; i<4; ++i){
int newX = x+dx[i];
int newY = y+dy[i];
search(mat,newX,newY,ans,k);
}
}
int cal(int x){
int sum = 0;
while(x){
sum += x%10;
x/=10;
}
return sum;
}
};
/*
* 机器人不可回退
*/
const int maxn = 101;
class Solution {
public:
int mark[maxn][maxn];
int movingCount(int k, int rows, int cols)
{
if(rows <= 0 || cols <= 0 || k<=0){
return 0;
}
//构建数组
vector<vector<int> > mat;
for(int i=0; i<rows; ++i){
vector<int> temp;
for(int j=0; j<cols; ++j){
temp.push_back(cal(i)+cal(j));
}
mat.push_back(temp);
}
int ans = 1;
memset(mark,false,sizeof(mark));
search(mat,0,0,1,ans,k);
return ans;
}
void search(vector<vector<int> > &mat,int x,int y,int cur,int &ans,int k){
if(x < 0 || x >= mat.size() || y < 0 || y >= mat[0].size() || mark[x][y] || mat[x][y] <= k){
return;
}
if(cur > ans){
ans = cur;
}
mark[x][y] = true;
static const int dx[] = {-1,1,0,0};
static const int dy[] = {0,0,-1,1};
for(int i=0; i<4; ++i){
int newX = x+dx[i];
int newY = y+dy[i];
search(mat,newX,newY,cur+1,ans,k);
mark[x][y] = false;
}
}
int cal(int x){
int sum = 0;
while(x){
sum += x%10;
x/=10;
}
return sum;
}
};
|
// Created on: 2002-04-17
// Created by: Alexander Kartomin (akm)
// 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.
// Purpose: This is a base class for the List, Set, Queue and Stack
// collections. It offers operations on abstract lists (of the
// objects of class NCollection_ListNode).
// Apart from this class being brand new (in TCollection said
// collections were independent, only using the same class for
// node representation), here is an important new feature -
// the list length is continuously updated, so the method
// Extent is quite quick.
#ifndef NCollection_BaseList_HeaderFile
#define NCollection_BaseList_HeaderFile
#include <Standard_NoSuchObject.hxx>
#include <NCollection_DefineAlloc.hxx>
#include <NCollection_ListNode.hxx>
typedef void (* NCollection_DelListNode)
(NCollection_ListNode*, Handle(NCollection_BaseAllocator)& theAl);
// ********************************************************** BaseList class
class NCollection_BaseList
{
public:
//! Memory allocation
DEFINE_STANDARD_ALLOC
DEFINE_NCOLLECTION_ALLOC
public:
class Iterator
{
public:
// ******** Empty constructor
Iterator (void) :
myCurrent (NULL),
myPrevious(NULL) {}
// ******** Constructor with initialisation
Iterator (const NCollection_BaseList& theList) :
myCurrent (theList.myFirst),
myPrevious(NULL) {}
// ******** Initialisation
void Init (const NCollection_BaseList& theList)
{
myCurrent = theList.myFirst;
myPrevious = NULL;
}
// ******** Initialisation
void Initialize (const NCollection_BaseList& theList)
{
Init(theList);
}
// ******** More
Standard_Boolean More (void) const
{ return (myCurrent!=NULL); }
// ******** Comparison operator
Standard_Boolean operator== (const Iterator& theIt) const
{
return myCurrent == theIt.myCurrent;
}
//! Performs comparison of two iterators
Standard_Boolean IsEqual (const Iterator& theOther) const
{
return *this == theOther;
}
protected:
void Init (const NCollection_BaseList& theList,
NCollection_ListNode * const thePrev)
{
myCurrent = thePrev ? thePrev -> Next() :
(NCollection_ListNode *)theList.PLast();
myPrevious = thePrev;
}
public:
NCollection_ListNode * myCurrent; // Pointer to the current node
NCollection_ListNode * myPrevious;// Pointer to the previous one
friend class NCollection_BaseList;
}; // End of nested class Iterator
public:
// ---------- PUBLIC METHODS ------------
// ******** Extent
// Purpose: Returns the number of nodes in the list
Standard_Integer Extent (void) const
{ return myLength; }
// ******** IsEmpty
// Purpose: Query if the list is empty
Standard_Boolean IsEmpty (void) const
{ return (myFirst == NULL); }
// ******** Allocator
//! Returns attached allocator
const Handle(NCollection_BaseAllocator)& Allocator() const
{ return myAllocator; }
// ******** Destructor
// Purpose: defines virtual interface
virtual ~NCollection_BaseList (void)
{}
protected:
// --------- PROTECTED METHODS ----------
// ******** Constructor
// Purpose: Initializes an empty list
NCollection_BaseList (const Handle(NCollection_BaseAllocator)& theAllocator=0L) :
myFirst(NULL),
myLast(NULL),
myLength(0)
{
myAllocator = (theAllocator.IsNull() ? NCollection_BaseAllocator::CommonBaseAllocator() : theAllocator);
}
// ******** PClear
// Purpose: deletes all nodes
Standard_EXPORT void PClear (NCollection_DelListNode fDel);
// ******** PFirst
// Purpose: Returns pointer to the first node
const NCollection_ListNode* PFirst (void) const
{ return myFirst; }
// ******** PLast
// Purpose: Returns pointer to the last node
const NCollection_ListNode* PLast (void) const
{ return myLast; }
// ******** PAppend
// Purpose: Appends theNode at the end
Standard_EXPORT void PAppend (NCollection_ListNode* theNode);
// ******** PAppend
// Purpose: Appends theNode at the end, returns iterator to the previous
void PAppend (NCollection_ListNode* theNode,
Iterator& theIt)
{
NCollection_ListNode * aPrev = myLast;
PAppend (theNode);
theIt.Init (* this, aPrev);
}
// ******** PAppend
// Purpose: Appends theOther list at the end (clearing it)
Standard_EXPORT void PAppend (NCollection_BaseList& theOther);
// ******** PPrepend
// Purpose: Prepends theNode at the beginning
Standard_EXPORT void PPrepend (NCollection_ListNode* theNode);
// ******** PPrepend
// Purpose: Prepends theOther list at the beginning (clearing it)
Standard_EXPORT void PPrepend (NCollection_BaseList& theOther);
// ******** PRemoveFirst
// Purpose: Removes first node
Standard_EXPORT void PRemoveFirst
(NCollection_DelListNode fDel);
// ******** PRemove
// Purpose: Removes the node pointed by theIter[ator]
Standard_EXPORT void PRemove
(Iterator& theIter,
NCollection_DelListNode fDel);
// ******** PInsertBefore
// Purpose: Inserts theNode before one pointed by theIter[ator]
Standard_EXPORT void PInsertBefore (NCollection_ListNode* theNode,
Iterator& theIter);
// ******** PInsertBefore
// Purpose: Inserts theOther list before the node pointed by theIter[ator]
Standard_EXPORT void PInsertBefore (NCollection_BaseList& theOther,
Iterator& theIter);
// ******** PInsertAfter
// Purpose: Inserts theNode after one pointed by theIter[ator]
Standard_EXPORT void PInsertAfter (NCollection_ListNode* theNode,
Iterator& theIter);
// ******** PInsertAfter
// Purpose: Inserts theOther list after the node pointed by theIter[ator]
Standard_EXPORT void PInsertAfter (NCollection_BaseList& theOther,
Iterator& theIter);
// ******** PReverse
// Purpose: Reverse the list
Standard_EXPORT void PReverse ();
protected:
// ------------ PROTECTED FIELDS ------------
Handle(NCollection_BaseAllocator) myAllocator;
NCollection_ListNode * myFirst; // Pointer to the head
NCollection_ListNode * myLast; // Pointer to the tail
Standard_Integer myLength; // Actual length
// ------------ FRIEND CLASSES ------------
friend class Iterator;
};
#endif
|
//http://codeforces.com/problemset/problem/762/A
#include <iostream>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;
int best = 1;
map<string, vector<string>> tree;
map<string, string> parent;
void convertLower(string& str)
{
transform(str.begin(), str.end(), str.begin(), ::tolower);
}
void dfs(string whose,int len) {
if(tree[whose].size() == 0) {
best = max(best, len);
return;
}
for(string who: tree[whose])
{
dfs(who, len + 1);
//cout << who << " " <<tree[who].size() << endl;
}
}
int main() {
int n;
string who, temp, whose;
cin >> n;
for(int i = 0; i < n; i++) {
cin >> who >> temp >> whose;
//if(parent[whose] == "" && whose != "Polycarp")
// tree["Polycarp"].push_back(whose);
convertLower(who);
convertLower(whose);
tree[whose].push_back(who);
}
dfs("polycarp", 1);
cout << best << endl;
}
|
#ifndef MJR_GEN_STACK
#include <iostream>
#include <string>
using namespace std;
template <class T>
class GenStack{
public:
// Constructors
GenStack();
GenStack(int maxSize);
// Destructor
~GenStack();
// Add to stack
void push(T item);
// Remove top of stack
T pop();
// View top of stack
T peek();
bool isFull();
bool isEmpty();
//Variables
int size;
int top;
T* myArray;
};
// Default constructor
template <class T>
GenStack<T>::GenStack(){
myArray = new T[128];
size = 128;
top = -1; // empty
}
// Overloaded constructor
template <class T>
GenStack<T>::GenStack(int maxSize){
myArray = new T[maxSize];
size = maxSize;
top = -1; // empty
}
// Destructor
template <class T>
GenStack<T>::~GenStack(){
if(myArray)
delete[] myArray;
}
// Add to top of stack
template <class T>
void GenStack<T>::push(T d){
// If array is full
if(top == (size-1)){
// Create a new array
T* tempArray = new T[size+32];
// Copy everything over
for(int i = 0; i < size; ++i)
tempArray[i]=myArray[i];
// Switch around pointers
T* tempPointer = myArray;
myArray = tempArray;
tempArray = tempPointer;
delete[] tempArray;
size = size+32;
}
// Assign new element
myArray[++top] = d;
}
// Remove top of stack and return the value
template <class T>
T GenStack<T>::pop(){
if(top == -1)
throw out_of_range("Your stack is empty.");
return myArray[top--];
}
// Return the element from the top of the stack
template <class T>
T GenStack<T>::peek(){
if(top == -1)
throw out_of_range("Your stack is empty.");
return myArray[top];
}
// Determines if the stack is full. Returns a bool
template <class T>
bool GenStack<T>::isFull(){
return (top == size-1);
}
// Determines if the stack is empty. Returns a bool
template <class T>
bool GenStack<T>::isEmpty(){
return (top == -1);
}
#endif
|
#include<iostream>
#include<cmath>
using namespace std;
double Radius(double x, double y);
double Theta (double x, double y);
class Cartesian;
class Polar;
class Polar {
public:
double a;
double t;
Polar(float newa, float newt) {
a = newa;
t = newt;
}
Cartesian toCartesian();
};
class Cartesian {
public:
double x;
double y;
Cartesian(float newx, float newy) {
x = newx;
y = newy;
}
Polar toPolar();
};
Cartesian Polar::toCartesian() {
return Cartesian(a*cos(t),a*sin(t));
}
Polar Cartesian::toPolar() {
return Polar(Radius(x,y), Theta(x,y));
}
double Theta(double x, double y){
double Thta;
Thta = atan(y/x);
return Thta;
}
double Radius(double x, double y){
double rad;
rad = sqrt((pow(x,2))+(pow(y,2)));
return rad;
}
|
#include<bits/stdc++.h>
using namespace std;
typedef struct Node{
int x,y;
}node;
int L,n,m;
int useif[105];
int link[105];
node pl[105];
node pi[105];
node line[105][2];
int biao[105][105];
void input(){
scanf("%d%d",&n,&m);
scanf("%d%d",&pl[0].x,&pl[0].y);
int j=0;
for(int i=1;i<n;i++,j++){
scanf("%d%d",&pl[i].x,&pl[i].y);
line[j][0]=pl[i-1];
line[j][1]=pl[i];
}
for(int i=0;i<m;i++){
scanf("%d%d",&pi[i].x,&pi[i].y);
}
}
double dis(node a,node b){
double d=sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
return d;
}
void init(){
for(int i=0;i<n-1;i++){
for(int j=0;j<m;j++)
if(dis(line[i][0],pi[j])+dis(line[i][1],pi[j])-2*dis(line[i][0],line[i][1])<1e-20){
biao[i][j]=1;
}
}
// for(int i=0;i<n-1;i++){
// for(int j=0;j<m;j++)
// printf("%d ",biao[i][j]);
// cout<<endl;
// }
}
int can(int t)
{
int i;
for(i=0;i<m;i++){
if(useif[i]==0 &&biao[t][i]==1)
{
useif[i]=1;
if(link[i]==-1 || can(link[i])){
link[i]=t;
return 1;
}
}
}
return 0;
}
int MaxMatch()
{
int i,num;
num=0;
memset(link,-1,sizeof(link));
for(i=0;i<n-1;i++)
{
memset(useif,0,sizeof(useif));
if(can(i))
num++;
}
return num;
}
int main(){
scanf("%d",&L);
while(L--){
memset(pl,0,sizeof(pl));
memset(pi,0,sizeof(pi));
memset(biao,0,sizeof(biao));
memset(line,0,sizeof(line));
input();
init();
int ans=MaxMatch()+n;
printf("%d\n",ans);
for(int i=0;i<n-1;i++){
printf("%d %d ",line[i][0].x,line[i][0].y);
for(int j=0;j<m;j++){
if(link[j]==i){
printf("%d %d ",pi[j].x,pi[j].y);
}
}
}
printf("%d %d\n\n",line[n-2][1].x,line[n-2][1].y);
}
return 0;
}
|
/*
$License:
Copyright (C) 2011-2012 InvenSense Corporation, All Rights Reserved.
See included License.txt for License information.
$
*/
/**
* @defgroup Results_Holder results_holder
* @brief Motion Library - Results Holder
* Holds the data for MPL
*
* @{
* @file results_holder.c
* @brief Results Holder for HAL.
*/
#include <string.h>
#include "results_holder.h"
#include "ml_math_func.h"
#include "mlmath.h"
#include "start_manager.h"
#include "data_builder.h"
#include "message_layer.h"
#include "log.h"
// These 2 status bits are used to control when the 9 axis quaternion is updated
#define INV_COMPASS_CORRECTION_SET 1
#define INV_6_AXIS_QUAT_SET 2
struct results_t {
long nav_quat[4];
long gam_quat[4];
inv_time_t nav_timestamp;
inv_time_t gam_timestamp;
long local_field[3]; /**< local earth's magnetic field */
long mag_scale[3]; /**< scale factor to apply to magnetic field reading */
long compass_correction[4]; /**< quaternion going from gyro,accel quaternion to 9 axis */
int acc_state; /**< Describes accel state */
int got_accel_bias; /**< Flag describing if accel bias is known */
long compass_bias_error[3]; /**< Error Squared */
unsigned char motion_state;
unsigned int motion_state_counter; /**< Incremented for each no motion event in a row */
long compass_count; /**< compass state internal counter */
int got_compass_bias; /**< Flag describing if compass bias is known */
int large_mag_field; /**< Flag describing if there is a large magnetic field */
int compass_state; /**< Internal compass state */
long status;
struct inv_sensor_cal_t *sensor;
float quat_confidence_interval;
};
static struct results_t rh;
/** @internal
* Store a quaternion more suitable for gaming. This quaternion is often determined
* using only gyro and accel.
* @param[in] quat Length 4, Quaternion scaled by 2^30
*/
void inv_store_gaming_quaternion(const long *quat, inv_time_t timestamp)
{
rh.status |= INV_6_AXIS_QUAT_SET;
memcpy(&rh.gam_quat, quat, sizeof(rh.gam_quat));
rh.gam_timestamp = timestamp;
}
/** @internal
* Sets the quaternion adjustment from 6 axis (accel, gyro) to 9 axis quaternion.
* @param[in] data Quaternion Adjustment
* @param[in] timestamp Timestamp of when this is valid
*/
void inv_set_compass_correction(const long *data, inv_time_t timestamp)
{
rh.status |= INV_COMPASS_CORRECTION_SET;
memcpy(rh.compass_correction, data, sizeof(rh.compass_correction));
rh.nav_timestamp = timestamp;
}
/** @internal
* Gets the quaternion adjustment from 6 axis (accel, gyro) to 9 axis quaternion.
* @param[out] data Quaternion Adjustment
* @param[out] timestamp Timestamp of when this is valid
*/
void inv_get_compass_correction(long *data, inv_time_t *timestamp)
{
memcpy(data, rh.compass_correction, sizeof(rh.compass_correction));
*timestamp = rh.nav_timestamp;
}
/** Returns non-zero if there is a large magnetic field. See inv_set_large_mag_field() for setting this variable.
* @return Returns non-zero if there is a large magnetic field.
*/
int inv_get_large_mag_field()
{
return rh.large_mag_field;
}
/** Set to non-zero if there as a large magnetic field. See inv_get_large_mag_field() for getting this variable.
* @param[in] state value to set for magnetic field strength. Should be non-zero if it is large.
*/
void inv_set_large_mag_field(int state)
{
rh.large_mag_field = state;
}
/** Gets the accel state set by inv_set_acc_state()
* @return accel state.
*/
int inv_get_acc_state()
{
return rh.acc_state;
}
/** Sets the accel state. See inv_get_acc_state() to get the value.
* @param[in] state value to set accel state to.
*/
void inv_set_acc_state(int state)
{
rh.acc_state = state;
return;
}
/** Returns the motion state
* @param[out] cntr Number of previous times a no motion event has occured in a row.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
int inv_get_motion_state(unsigned int *cntr)
{
*cntr = rh.motion_state_counter;
return rh.motion_state;
}
/** Sets the motion state
* @param[in] state motion state where INV_NO_MOTION is not moving
* and INV_MOTION is moving.
*/
void inv_set_motion_state(unsigned char state)
{
long set;
if (state == rh.motion_state) {
if (state == INV_NO_MOTION) {
rh.motion_state_counter++;
} else {
rh.motion_state_counter = 0;
}
return;
}
rh.motion_state_counter = 0;
rh.motion_state = state;
/* Equivalent to set = state, but #define's may change. */
if (state == INV_MOTION)
set = INV_MSG_MOTION_EVENT;
else
set = INV_MSG_NO_MOTION_EVENT;
inv_set_message(set, (INV_MSG_MOTION_EVENT | INV_MSG_NO_MOTION_EVENT), 0);
}
/** Sets the local earth's magnetic field
* @param[in] data Local earth's magnetic field in uT scaled by 2^16.
* Length = 3. Y typically points north, Z typically points down in
* northern hemisphere and up in southern hemisphere.
*/
void inv_set_local_field(const long *data)
{
memcpy(rh.local_field, data, sizeof(rh.local_field));
}
/** Gets the local earth's magnetic field
* @param[out] data Local earth's magnetic field in uT scaled by 2^16.
* Length = 3. Y typically points north, Z typically points down in
* northern hemisphere and up in southern hemisphere.
*/
void inv_get_local_field(long *data)
{
memcpy(data, rh.local_field, sizeof(rh.local_field));
}
/** Sets the compass sensitivity
* @param[in] data Length 3, sensitivity for each compass axis
* scaled such that 1.0 = 2^30.
*/
void inv_set_mag_scale(const long *data)
{
memcpy(rh.mag_scale, data, sizeof(rh.mag_scale));
}
/** Gets the compass sensitivity
* @param[out] data Length 3, sensitivity for each compass axis
* scaled such that 1.0 = 2^30.
*/
void inv_get_mag_scale(long *data)
{
memcpy(data, rh.mag_scale, sizeof(rh.mag_scale));
}
/** Gets gravity vector
* @param[out] data gravity vector in body frame scaled such that 1.0 = 2^30.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_get_gravity(long *data)
{
data[0] =
inv_q29_mult(rh.nav_quat[1], rh.nav_quat[3]) - inv_q29_mult(rh.nav_quat[2], rh.nav_quat[0]);
data[1] =
inv_q29_mult(rh.nav_quat[2], rh.nav_quat[3]) + inv_q29_mult(rh.nav_quat[1], rh.nav_quat[0]);
data[2] =
(inv_q29_mult(rh.nav_quat[3], rh.nav_quat[3]) + inv_q29_mult(rh.nav_quat[0], rh.nav_quat[0])) -
1073741824L;
return INV_SUCCESS;
}
/** Returns a quaternion based only on gyro and accel.
* @param[out] data 6-axis gyro and accel quaternion scaled such that 1.0 = 2^30.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_get_6axis_quaternion(long *data)
{
memcpy(data, rh.gam_quat, sizeof(rh.gam_quat));
return INV_SUCCESS;
}
/** Returns a quaternion.
* @param[out] data 9-axis quaternion scaled such that 1.0 = 2^30.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_get_quaternion(long *data)
{
if (rh.status & (INV_COMPASS_CORRECTION_SET | INV_6_AXIS_QUAT_SET)) {
inv_q_mult(rh.compass_correction, rh.gam_quat, rh.nav_quat);
rh.status &= ~(INV_COMPASS_CORRECTION_SET | INV_6_AXIS_QUAT_SET);
}
memcpy(data, rh.nav_quat, sizeof(rh.nav_quat));
return INV_SUCCESS;
}
/** Returns a quaternion.
* @param[out] data 9-axis quaternion.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_get_quaternion_float(float *data)
{
long ldata[4];
inv_error_t result = inv_get_quaternion(ldata);
data[0] = inv_q30_to_float(ldata[0]);
data[1] = inv_q30_to_float(ldata[1]);
data[2] = inv_q30_to_float(ldata[2]);
data[3] = inv_q30_to_float(ldata[3]);
return result;
}
/** Returns a quaternion with accuracy and timestamp.
* @param[out] data 9-axis quaternion scaled such that 1.0 = 2^30.
* @param[out] accuracy Accuracy of quaternion, 0-3, where 3 is most accurate.
* @param[out] timestamp Timestamp of this quaternion in nanoseconds
*/
void inv_get_quaternion_set(long *data, int *accuracy, inv_time_t *timestamp)
{
inv_get_quaternion(data);
*timestamp = inv_get_last_timestamp();
if (inv_get_compass_on()) {
*accuracy = inv_get_mag_accuracy();
} else if (inv_get_gyro_on()) {
*accuracy = inv_get_gyro_accuracy();
}else if (inv_get_accel_on()) {
*accuracy = inv_get_accel_accuracy();
} else {
*accuracy = 0;
}
}
/** Callback that gets called everytime there is new data. It is
* registered by inv_start_results_holder().
* @param[in] sensor_cal New sensor data to process.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_generate_results(struct inv_sensor_cal_t *sensor_cal)
{
rh.sensor = sensor_cal;
return INV_SUCCESS;
}
/** Function to turn on this module. This is automatically called by
* inv_enable_results_holder(). Typically not called by users.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_start_results_holder(void)
{
inv_register_data_cb(inv_generate_results, INV_PRIORITY_RESULTS_HOLDER,
INV_GYRO_NEW | INV_ACCEL_NEW | INV_MAG_NEW);
return INV_SUCCESS;
}
/** Initializes results holder. This is called automatically by the
* enable function inv_enable_results_holder(). It may be called any time the feature is enabled, but
* is typically not needed to be called by outside callers.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_init_results_holder(void)
{
memset(&rh, 0, sizeof(rh));
rh.mag_scale[0] = 1L<<30;
rh.mag_scale[1] = 1L<<30;
rh.mag_scale[2] = 1L<<30;
rh.compass_correction[0] = 1L<<30;
rh.gam_quat[0] = 1L<<30;
rh.nav_quat[0] = 1L<<30;
rh.quat_confidence_interval = (float)M_PI;
return INV_SUCCESS;
}
/** Turns on storage of results.
*/
inv_error_t inv_enable_results_holder()
{
inv_error_t result;
result = inv_init_results_holder();
if ( result ) {
return result;
}
result = inv_register_mpl_start_notification(inv_start_results_holder);
return result;
}
/** Sets state of if we know the accel bias.
* @return return 1 if we know the accel bias, 0 if not.
* it is set with inv_set_accel_bias_found()
*/
int inv_got_accel_bias()
{
return rh.got_accel_bias;
}
/** Sets whether we know the accel bias
* @param[in] state Set to 1 if we know the accel bias.
* Can be retrieved with inv_got_accel_bias()
*/
void inv_set_accel_bias_found(int state)
{
rh.got_accel_bias = state;
}
/** Sets state of if we know the compass bias.
* @return return 1 if we know the compass bias, 0 if not.
* it is set with inv_set_compass_bias_found()
*/
int inv_got_compass_bias()
{
return rh.got_compass_bias;
}
/** Sets whether we know the compass bias
* @param[in] state Set to 1 if we know the compass bias.
* Can be retrieved with inv_got_compass_bias()
*/
void inv_set_compass_bias_found(int state)
{
rh.got_compass_bias = state;
}
/** Sets the compass state.
* @param[in] state Compass state. It can be retrieved with inv_get_compass_state().
*/
void inv_set_compass_state(int state)
{
rh.compass_state = state;
}
/** Get's the compass state
* @return the compass state that was set with inv_set_compass_state()
*/
int inv_get_compass_state()
{
return rh.compass_state;
}
/** Set compass bias error. See inv_get_compass_bias_error()
* @param[in] bias_error Set's how accurate we know the compass bias. It is the
* error squared.
*/
void inv_set_compass_bias_error(const long *bias_error)
{
memcpy(rh.compass_bias_error, bias_error, sizeof(rh.compass_bias_error));
}
/** Get's compass bias error. See inv_set_compass_bias_error() for setting.
* @param[out] bias_error Accuracy as to how well the compass bias is known. It is the error squared.
*/
void inv_get_compass_bias_error(long *bias_error)
{
memcpy(bias_error, rh.compass_bias_error, sizeof(rh.compass_bias_error));
}
/**
* @brief Returns 3-element vector of accelerometer data in body frame
* with gravity removed
* @param[out] data 3-element vector of accelerometer data in body frame
* with gravity removed
* @return INV_SUCCESS if successful
* INV_ERROR_INVALID_PARAMETER if invalid input pointer
*/
inv_error_t inv_get_linear_accel(long *data)
{
long gravity[3];
if (data != NULL)
{
inv_get_accel_set(data, NULL, NULL);
inv_get_gravity(gravity);
data[0] -= gravity[0] >> 14;
data[1] -= gravity[1] >> 14;
data[2] -= gravity[2] >> 14;
return INV_SUCCESS;
}
else {
return INV_ERROR_INVALID_PARAMETER;
}
}
/**
* @brief Returns 3-element vector of accelerometer data in body frame
* @param[out] data 3-element vector of accelerometer data in body frame
* @return INV_SUCCESS if successful
* INV_ERROR_INVALID_PARAMETER if invalid input pointer
*/
inv_error_t inv_get_accel(long *data)
{
if (data != NULL) {
inv_get_accel_set(data, NULL, NULL);
return INV_SUCCESS;
}
else {
return INV_ERROR_INVALID_PARAMETER;
}
}
/**
* @brief Returns 3-element vector of accelerometer float data
* @param[out] data 3-element vector of accelerometer float data
* @return INV_SUCCESS if successful
* INV_ERROR_INVALID_PARAMETER if invalid input pointer
*/
inv_error_t inv_get_accel_float(float *data)
{
long tdata[3];
unsigned char i;
if (data != NULL && !inv_get_accel(tdata)) {
for (i = 0; i < 3; ++i) {
data[i] = ((float)tdata[i] / (1L << 16));
}
return INV_SUCCESS;
}
else {
return INV_ERROR_INVALID_PARAMETER;
}
}
/**
* @brief Returns 3-element vector of gyro float data
* @param[out] data 3-element vector of gyro float data
* @return INV_SUCCESS if successful
* INV_ERROR_INVALID_PARAMETER if invalid input pointer
*/
inv_error_t inv_get_gyro_float(float *data)
{
long tdata[3];
unsigned char i;
if (data != NULL) {
inv_get_gyro_set(tdata, NULL, NULL);
for (i = 0; i < 3; ++i) {
data[i] = ((float)tdata[i] / (1L << 16));
}
return INV_SUCCESS;
}
else {
return INV_ERROR_INVALID_PARAMETER;
}
}
/** Set 9 axis 95% heading confidence interval for quaternion
* @param[in] ci Confidence interval in radians.
*/
void inv_set_heading_confidence_interval(float ci)
{
rh.quat_confidence_interval = ci;
}
/** Get 9 axis 95% heading confidence interval for quaternion
* @return Confidence interval in radians.
*/
float inv_get_heading_confidence_interval(void)
{
return rh.quat_confidence_interval;
}
/**
* @brief Returns 3-element vector of linear accel float data
* @param[out] data 3-element vector of linear aceel float data
* @return INV_SUCCESS if successful
* INV_ERROR_INVALID_PARAMETER if invalid input pointer
*/
inv_error_t inv_get_linear_accel_float(float *data)
{
long tdata[3];
unsigned char i;
if (data != NULL && !inv_get_linear_accel(tdata)) {
for (i = 0; i < 3; ++i) {
data[i] = ((float)tdata[i] / (1L << 16));
}
return INV_SUCCESS;
}
else {
return INV_ERROR_INVALID_PARAMETER;
}
}
/**
* @}
*/
|
//
// parser.cpp
// mini-sql
//
// Created by Дмитрий Маслюков on 17.02.2020.
// Copyright © 2020 Дмитрий Маслюков. All rights reserved.
//
#include "parser.h"
#define jsondb 1
#include <cstdarg>
Parser::astnode * create_node_va(Parser::asttype type, int children, va_list va){
Parser::astnode * node = new Parser::astnode();
node->type = type;
for(int i = 0; i < children; ++i){
Parser::astnode * _arg = va_arg(va, Parser::astnode*);
node->children.push_back(_arg);
_arg->parent = node;
}
return node;
}
Parser::astnode * create_node(Parser::asttype type, int children, ...){
va_list va;
va_start(va, children);
Parser::astnode * n = create_node_va(type, children, va);
va_end(va);
return n;
}
Parser::astnode * Parser::parse_expr(lwalker &walker){
astnode* left = parse_logor(walker);
if( (*walker).type == or_lex ){
walker ++;
astnode * right = parse_logor(walker);
if(! right)
return 0;
return create_node(Parser::asttype::OR, 2, left, right);
}
return left;
}
Parser::astnode * Parser::parse_logor(lwalker &walker){
astnode* left = parse_logand(walker);
if( (*walker).type == and_lex ){
walker ++;
astnode * right = parse_logand(walker);
return create_node(Parser::asttype::AND, 2, left, right);
}
return left;
}
Parser::astnode * Parser::parse_logand(lwalker &walker){
if((*walker).type == not_lex){
walker++;
astnode * node = parse_lognot(walker);
return create_node(NOT, 1, node);
}
return parse_lognot(walker);
}
Parser::astnode * Parser::parse_lognot(lwalker &walker){
if((*walker).type == open_bracket){
walker++;
astnode * subexp = parse_expr(walker);
if( (*walker).type != close_bracket ){
return 0;
}
return subexp;
}
lexem left = *walker;
if(left.type != name){
return 0;
}
astnode * _left = parse_symbol(walker);
#if jsondb
if(1){
//load global
astnode * gl = create_node(SYMBOL, 0);
gl->val = strdup("this");
_left = create_node(SUBSCR, 2, gl, _left);
}
#endif
lexem comp = * walker;
walker++;
lexem right = * walker;
walker ++;
asttype rtype = STRVAL;
if( right.type == strlit )
rtype = STRVAL;
if( right.type == numlit )
rtype = NUMVAL;
astnode * _right = create_node(rtype, 0);
_right->val = right.val;
asttype comptype = (asttype)(EQUALS + ((int)comp.type - (int)equals));
if( comptype != EQUALS && comptype != GREATER && comptype != LESS ){
return 0;
}
return create_node(comptype, 2, _left, _right);
}
Parser::astnode * Parser::parse_symbol (lwalker & walker){
lexem & l = *walker;
if( l.type != name ){
return 0;
}
astnode * _left = create_node(SYMBOL, 0);
_left->val = l.val;
walker++;
l = *walker;
if( l.type == dot ){
walker ++;
astnode * right = parse_symbol(walker);
if( !right )
return 0;
return create_node(SUBSCR, 2, _left, right);
}
return _left;
}
json Parser::parse_js_literal (lwalker & walker){
lexem & l = *walker;
walker++;
if(l.type == numlit){
return json( *(long*)l.val );
}
if(l.type == strlit){
return json((const char*)l.val);
}
if(l.type == _true){
return json(1.0);
}
if(l.type == _false){
return json(0.0);
}
return json::undefined;
}
json Parser::parse_js_array (lwalker & walker){
//assume that we stand at [
walker++;
json arr = json::Array();
json j = parse_js_anything(walker);
arr.push(j);
while( (*walker).type != arr_cl ){
if((*walker).type != comma){
return json::undefined;
}
walker++;
json elem = parse_js_anything(walker);
arr.push(elem);
}
walker++;
return arr;
}
json::prop_entry Parser::parse_entry(lwalker & walker){
Parser::lexem & l = *walker;
if(l.type != Parser::strlit){
return json::prop_entry();
}
char * name = strdup((char*)l.val);
walker ++;
if( (*walker).type != Parser::colon ){
return json::prop_entry();
}
walker++;
json val = parse_js_anything(walker);
json::prop_entry entry;
entry.name = name;
entry.val = val;
return entry;
}
json Parser::parse_js_dict (lwalker & walker){
//assume that we stand at {
walker++;
json dict = json::Dict();
json::prop_entry entry = parse_entry(walker);
dict.push(entry);
while( (*walker).type != cbrace ){
if((*walker).type != comma){
return json::undefined;
}
walker++;;
dict.push(parse_entry(walker));
}
walker++;
return dict;
}
json Parser::parse_js_anything (lwalker & walker){
lexem & l = *walker;
switch (l.type) {
case numlit:
case strlit:
case _true:
case _false:
return parse_js_literal(walker);
case arr_op:
return parse_js_array(walker);
case obrace:
return parse_js_dict(walker);
default:
return json::undefined;
break;
}
}
|
#include "Divide.h"
Divide::Divide()
{
value1 = 0;
value2 = 0;
}
Divide::Divide(Base* input1, Base* input2)
{
value1 = input1;
value2 = input2;
}
double Divide::evaluate()
{
return (value1->evaluate() / value2->evaluate());
}
|
#include "cxxtest/TestSuite.h"
#include "tinyxml/tinyxml.h"
#include "neural_network/cpu/NeuralNetworkCpu.h"
#include "neural_network/NeuralNetworkConfiguration.h"
#include "utility/TextAccess.h"
class NeuralNetworkCpuTestSuite : public CxxTest::TestSuite
{
public:
void test_neural_network_can_be_loaded_from_text_access()
{
try
{
TiXmlDocument doc;
doc.Parse(
"<neural_network input_node_group_id=\"0\" output_node_group_id=\"1\">\n"
" <node_group id=\"0\" node_count=\"2\" excitation_offset=\"0.1\" excitation_multiplier=\"0.2\" excitation_threshold=\"0.3\" excitation_fatigue=\"0.4\" />\n"
" <node_group id=\"1\" node_count=\"3\" excitation_offset=\"0.1\" excitation_multiplier=\"0.2\" excitation_threshold=\"0.3\" excitation_fatigue=\"0.4\" />\n"
" <edge_group source_group_id=\"0\" target_group_id=\"1\">\n"
" <weights width=\"2\" height=\"3\" values=\"0.16,-0.20;0.67,-0.9;-0.11,0.28\" />\n"
" </edge_group>\n"
"</neural_network>\n",
0,
TIXML_ENCODING_UTF8
);
const TiXmlElement* element = doc.FirstChildElement("neural_network");
std::shared_ptr<NeuralNetworkCpu> neuralNetwork = NeuralNetworkCpu::create(neuralNetworkConfigurationFromXmlElement(element));
TS_ASSERT(neuralNetwork);
}
catch (const std::exception& e)
{
TS_FAIL(e.what());
}
}
};
|
#ifndef manifold_h
#define manifold_h
#include <tr1/memory>
#include <vector>
#include <tr1/array>
#include <Eigen/Core>
#include <string>
#include "Intersection.h"
#include "PointTransport.h"
using Eigen::Matrix3d;
using Eigen::Vector3d;
//TODO: It might be possible to make it a template, given the address of a constant pointer to k.
class Manifold {
public:
class Point;
class PointOfReference;
class Geodesic;
class Portal;
typedef std::tr1::shared_ptr<Point> PointPtr;
typedef std::tr1::shared_ptr<PointOfReference> PointOfReferencePtr;
typedef std::tr1::shared_ptr<Geodesic> GeodesicPtr;
typedef std::tr1::shared_ptr<Portal> PortalPtr;
typedef std::tr1::array<PointPtr,3> Triangle;
class Point {
public:
bool isInManifold();
virtual Manifold* getSpace() = 0;
virtual Vector3d getVector() = 0;
};
class PointOfReference {
public:
virtual void rotate(Matrix3d rot) = 0;
virtual PointPtr getPosition() = 0;
Manifold* getSpace();
};
class Geodesic {
public:
virtual PointPtr getEndPoint() = 0;
virtual PointOfReferencePtr getEndPointOfReference() = 0;
virtual PointOfReferencePtr getStart() = 0;
virtual Vector3d getVector() = 0;
Manifold* getSpace();
virtual double intersectionDistance(PortalPtr portal) = 0;
};
class Portal { //Currently, this only supports spheres. It could be generalized to generalized spheres. This would require another kind of intersection.
public:
Portal();
Manifold* getSpace();
GeodesicPtr teleport(GeodesicPtr geodesic);
PointPtr teleport(PointPtr point);
void setMutualExits(Portal* exit);
void setMutualExits(Portal* exit, Matrix3d rotation);
void setSpace(Manifold* space);
Manifold* getExitSpace();
virtual bool containsPoint(Manifold::Point* point) = 0;
virtual double getRadiusOfCurvature() = 0;
virtual double getCircumference() = 0;
void setInvert(bool invert);
bool getInvert();
private:
virtual GeodesicPtr getGeodesic(IntersectionPtr intersection) = 0;
virtual IntersectionPtr getIntersection(GeodesicPtr geodesic) = 0;
virtual Manifold::PointPtr getPoint(PointTransportPtr transport) = 0;
virtual PointTransportPtr getTransport(Manifold::PointPtr point) = 0;
void setExit(Portal* exit);
void setExit(Portal* exit, Matrix3d rotation);
Portal* exit;
Manifold* space;
Matrix3d rotation;
bool rotate;
bool invert;
};
virtual std::string getType() = 0;
Vector3d vectorFromPoint(PointOfReferencePtr start, PointPtr end); //Maybe these two should be in PointOfReference.
PointPtr pointFromVector(PointOfReferencePtr start, Vector3d vector); //
PointOfReferencePtr getPointOfReference(PointOfReferencePtr start, Vector3d vector);
virtual GeodesicPtr getGeodesic(PointOfReferencePtr start, PointPtr end) = 0;
virtual GeodesicPtr getGeodesic(PointOfReferencePtr start, Vector3d vector) = 0;
std::vector<Triangle> icosahedron(PointOfReferencePtr por);
std::vector<Triangle> icosahedron(PointOfReferencePtr por, double k);
std::vector<Triangle> octahedron(PointOfReferencePtr por);
std::vector<Triangle> octahedron(PointOfReferencePtr por, double k);
//virtual Triangle makeTriangle() = 0; //For debug purposes
//virtual std::vector<Triangle> makeTriangleList() = 0;
GeodesicPtr nextPiece(GeodesicPtr previous);
void addPortal(PortalPtr portal);
std::vector<PortalPtr>* getPortals();
private:
std::vector<PortalPtr> portals;
};
#endif
|
#ifndef TREEFACE_STRING_CAST_H
#define TREEFACE_STRING_CAST_H
#include "treeface/base/Common.h"
#include "treeface/base/Enums.h"
#include "treeface/gl/Enums.h"
#define GLEW_STATIC
#include <GL/glew.h>
#include <treecore/String.h>
#include <treecore/StringCast.h>
#include <FreeImage.h>
namespace treecore {
template<>
bool fromString<treeface::MaterialType>( const treecore::String& string, treeface::MaterialType& result );
template<>
bool fromString<treeface::LineCap>( const String& str, treeface::LineCap& result );
template<>
bool fromString<treeface::LineJoin>( const String& str, treeface::LineJoin& result );
template<>
bool fromString<FREE_IMAGE_FORMAT>( const treecore::String& string, FREE_IMAGE_FORMAT& result );
template<>
bool fromString<FREE_IMAGE_TYPE>( const treecore::String& string, FREE_IMAGE_TYPE& result );
template<>
bool fromString<FREE_IMAGE_COLOR_TYPE>( const treecore::String& string, FREE_IMAGE_COLOR_TYPE& result );
template<>
bool fromString<treeface::GLBufferType>( const treecore::String& string, treeface::GLBufferType& result );
template<>
bool fromString<treeface::GLBufferUsage>( const treecore::String& string, treeface::GLBufferUsage& result );
template<>
bool fromString<treeface::GLImageFormat>( const treecore::String& string, treeface::GLImageFormat& result );
template<>
bool fromString<treeface::GLInternalImageFormat>( const treecore::String& string, treeface::GLInternalImageFormat& result );
template<>
bool fromString<treeface::GLPrimitive>( const treecore::String& string, treeface::GLPrimitive& result );
template<>
bool fromString<treeface::GLTextureType>( const treecore::String& string, treeface::GLTextureType& result );
template<>
bool fromString<treeface::GLTextureFilter>( const treecore::String& string, treeface::GLTextureFilter& result );
template<>
bool fromString<treeface::GLTextureWrap>( const treecore::String& string, treeface::GLTextureWrap& result );
template<>
bool fromString<treeface::GLType>( const treecore::String& string, treeface::GLType& result );
template<>
bool fromString<treeface::TextureImageSoloChannelPolicy>(const treecore::String& string, treeface::TextureImageSoloChannelPolicy& result);
template<>
bool fromString<treeface::TextureImageDualChannelPolicy>(const treecore::String& string, treeface::TextureImageDualChannelPolicy& result);
template<>
bool fromString<treeface::TextureImageIntDataPolicy>(const treecore::String& string, treeface::TextureImageIntDataPolicy& result);
template<>
treecore::String toString<treeface::MaterialType>( treeface::MaterialType value );
template<>
treecore::String toString<treeface::LineCap>( treeface::LineCap cap );
template<>
treecore::String toString<treeface::LineJoin>( treeface::LineJoin join );
template<>
treecore::String toString<FREE_IMAGE_FORMAT>( FREE_IMAGE_FORMAT arg );
template<>
treecore::String toString<FREE_IMAGE_TYPE>( FREE_IMAGE_TYPE arg );
template<>
treecore::String toString<FREE_IMAGE_COLOR_TYPE>( FREE_IMAGE_COLOR_TYPE arg );
template<>
treecore::String toString<treeface::GLBufferType>( treeface::GLBufferType arg );
template<>
treecore::String toString<treeface::GLBufferUsage>( treeface::GLBufferUsage arg );
template<>
treecore::String toString<treeface::GLImageFormat>( treeface::GLImageFormat arg );
template<>
treecore::String toString<treeface::GLInternalImageFormat>( treeface::GLInternalImageFormat arg );
template<>
treecore::String toString<treeface::GLImageDataType>( treeface::GLImageDataType arg );
template<>
treecore::String toString<treeface::GLPrimitive>( treeface::GLPrimitive arg );
template<>
treecore::String toString<treeface::GLTextureFilter>( treeface::GLTextureFilter arg );
template<>
treecore::String toString<treeface::GLTextureType>( treeface::GLTextureType arg );
template<>
treecore::String toString<treeface::GLTextureWrap>( treeface::GLTextureWrap arg );
template<>
treecore::String toString<treeface::GLType>( treeface::GLType arg );
template<>
treecore::String toString<treeface::TextureImageSoloChannelPolicy>(treeface::TextureImageSoloChannelPolicy arg);
template<>
treecore::String toString<treeface::TextureImageDualChannelPolicy>(treeface::TextureImageDualChannelPolicy arg);
template<>
treecore::String toString<treeface::TextureImageIntDataPolicy>(treeface::TextureImageIntDataPolicy arg);
} // namespace treecore
#endif // TREEFACE_STRING_CAST_H
|
#include "diode.h"
#include <QPainter>
#include <QDebug>
Diode::Diode(QWidget *parent) : QWidget(parent)
{
//qDebug() << "Création de la diode!" ;
m_isClicked = false;
power = true;
}
void Diode::paintEvent(QPaintEvent *event)
{
QPainter p(this);
p.setPen(Qt::black);
p.setBrush(m_isClicked ? Qt::darkGreen : Qt::red );
p.drawEllipse((this->width())/2,(this->height())/2, 40,40);
updateGeometry();
}
void Diode::setOn()
{
m_isClicked = true;
power =false;
repaint();
}
void Diode::setOff()
{
m_isClicked = false;
power =true;
repaint();
}
void Diode::setPower()
{
if(power) setOn();
else setOff();
}
Diode::~Diode()
{
//qDebug() << "Destruction de la diode!" ;
}
|
#include <cstdlib>
#include <string>
#include "env.hpp"
double getEnvDouble(std::string const& envName, double const& defaultValue){
// Returns environment variable as double.
// (from https://stackoverflow.com/questions/5866134/how-to-read-linux-environment-variables-in-c)
const char* val = std::getenv(envName.c_str());
if ( val == 0 ){
return defaultValue;
}
else {
return std::atof(val);
}
}
int getEnvInt(std::string const& envName, int const& defaultValue) {
// Returns environment variable as integer.
// (from https://stackoverflow.com/questions/5866134/how-to-read-linux-environment-variables-in-c)
const char* val = std::getenv(envName.c_str());
if ( val == 0 ){
return defaultValue;
}
else {
// return std::atoi(val);
return (int) std::atof(val);
}
}
bool getEnvBool(std::string const& envName, bool const& defaultValue) {
// Returns environment variable as boolean.
// WARNING: Be EXTRA CAREFUL with this function, only use "0" and "1" as
// environment variables.
// (from https://stackoverflow.com/questions/5866134/how-to-read-linux-environment-variables-in-c)
return (bool) getEnvInt(envName, defaultValue);
}
std::string getEnvString(std::string const& envName,
std::string const& defaultValue) {
// Returns environment variable as string.
// (from https://stackoverflow.com/questions/5866134/how-to-read-linux-environment-variables-in-c)
const char* val = std::getenv(envName.c_str());
if ( val == 0 ){
return defaultValue;
}
else {
return std::string(val);
}
}
|
#ifndef AWS_NODES_NULLCONSTANT_H
#define AWS_NODES_NULLCONSTANT_H
/*
* aws/nodes/nullconstant.h
* AwesomeScript Null Constant
* Author: Dominykas Djacenka
* Email: Chaosteil@gmail.com
*/
#include "expression.h"
namespace AwS{
namespace Nodes{
class NullConstant : public Expression{
public:
NullConstant()
: Expression(){
}
virtual ~NullConstant(){}
void translatePhp(std::ostream& output, TranslateSettings& settings) const throw(NodeException){
output << "null";
}
};
};
};
#endif
|
#include "threads.h"
Threads::Threads(int n) : stop_(false), max_threads_(n)
{
pthread_mutex_init(&mtx_, NULL);
pthread_cond_init(&cond_, NULL);
// mtx_ = PTHREAD_MUTEX_INITIALIZER;
// cond_ = PTHREAD_COND_INITIALIZER;
tid_ = new pthread_t[n];
for (int i = 0; i < n; ++i)
{
pthread_create(&tid_[i], NULL, thread_func, (void*)this);
}
}
Threads::~Threads()
{
pthread_mutex_lock(&mtx_);
stop_ = true;
pthread_mutex_unlock(&mtx_);
pthread_cond_broadcast(&cond_);
while (Job* job = tasks_.front())
free(job);
for (int i = 0; i < max_threads_; ++i)
pthread_join(tid_[i], NULL);
delete tid_;
}
// 增加任务
int Threads::add_task(void*(*callback_func)(void* args), void* args)
{
pthread_mutex_lock(&mtx_);
struct Job* job = (struct Job*) malloc(sizeof(struct Job));
if (job == NULL)
{
pthread_mutex_unlock(&mtx_);
return -1;
}
job->callback_func = callback_func;
job->args = args;
tasks_.push(job);
pthread_mutex_unlock(&mtx_);
// 通知线程池中的线程
pthread_cond_broadcast(&cond_);
return 0;
}
// 线程函数
void* Threads::thread_func(void* args)
{
Threads* thread = (Threads*) args;
pthread_t tid = pthread_self();
while(1)
{
pthread_mutex_lock(&thread->mtx_);
while (thread->tasks_.size() == 0 && !thread->stop_)
pthread_cond_wait(&thread->cond_, &thread->mtx_);
if (thread->stop_ && thread->tasks_.empty())
{
pthread_mutex_unlock(&thread->mtx_);
pthread_exit(NULL);
}
// 取出一个任务并执行
Job* job = thread->tasks_.front();
thread->tasks_.pop();
pthread_mutex_unlock(&thread->mtx_);
// 回调函数的调用
(*(job->callback_func))(job->args);
free(job);
job = NULL;
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 2000-2008 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 OPERABOOKMARKS_URL
#include "modules/util/opstring.h"
#include "modules/util/simset.h"
#include "modules/ecmascript_utils/esasyncif.h"
#include "modules/bookmarks/bookmark_manager.h"
#include "modules/bookmarks/bookmark_item.h"
#include "modules/locale/locale-enum.h"
#include "modules/bookmarks/operabookmarks.h"
OP_STATUS OperaBookmarks::GenerateData()
{
OpString line, url, title, str;
BookmarkAttribute attr;
BookmarkListElm *elm;
AutoDeleteHead bookmark_list;
OpString url_text, title_text, desc_text, sn_text, folder_text, add_text, add_folder_text, load_text, save_text, save_mod_text, modify_text, delete_text;
#ifdef _LOCALHOST_SUPPORT_
RETURN_IF_ERROR(OpenDocument(Str::SI_IDSTR_HL_BOOKMARKS_ROOT_FOLDER_NAME, PrefsCollectionFiles::StyleBookmarksFile));
#else
RETURN_IF_ERROR(OpenDocument(Str::SI_IDSTR_HL_BOOKMARKS_ROOT_FOLDER_NAME));
#endif // _LOCALHOST_SUPPORT_
RETURN_IF_ERROR(line.Set("<script>\n"
"function update()\n"
"{\n"
"var url = document.getElementById('au').value;\n"
"var title = document.getElementById('at').value;\n"
"var desc = document.getElementById('ad').value;\n"
"var sn = document.getElementById('as').value;\n"
"var pt=document.getElementById('ap').value;\n"
"opera.bookmarksSaveFormValues(url,title,desc,sn,pt);\n"
"location.reload();\n"
"}\n"
"function sv()\n"
"{\n"
"var url = opera.bookmarksGetFormUrlValue();\n"
"var title = opera.bookmarksGetFormTitleValue();\n"
"var desc = opera.bookmarksGetFormDescriptionValue();\n"
"var sn = opera.bookmarksGetFormShortnameValue();\n"
"var pt = opera.bookmarksGetFormParentTitleValue();\n"
"if (url && url!='undefined')"
"document.getElementById('au').value = url;\n"
"if (title && title!='undefined')"
"document.getElementById('at').value = title;\n"
"if (desc && desc!='undefined')"
"document.getElementById('ad').value = desc;\n"
"if (sn && sn!='undefined')"
"document.getElementById('as').value = sn;\n"
"if (pt && pt!='undefined')"
"document.getElementById('ap').value = pt;\n"
"}\n"
"function clearf()\n"
"{\n"
"opera.bookmarksSaveFormValues('','','','','');\n"
"document.getElementById('au').value = '';\n"
"document.getElementById('at').value = '';\n"
"document.getElementById('ad').value = '';\n"
"document.getElementById('as').value = '';\n"
"document.getElementById('ap').value = '';\n"
"}\n"
"opera.setBookmarkListener(update);\n"
"document.addEventListener('load', sv, false);"
"function mod(elm)"
"{"
"document.getElementById('au').setAttribute('uid', elm.getAttribute('uid'));"
"document.getElementById('au').value = elm.getAttribute('url');"
"document.getElementById('at').value = elm.getAttribute('t');"
"document.getElementById('ad').value = elm.getAttribute('d');"
"document.getElementById('as').value = elm.getAttribute('sn');"
"document.getElementById('ap').value = elm.getAttribute('pt');"
"}"
"function del(b)"
"{"
"opera.deleteBookmark(b.getAttribute('uid'));"
"update();"
"}"
"</script>"));
m_url.WriteDocumentData(URL::KNormal, line);
RETURN_IF_ERROR(OpenBody(Str::SI_IDSTR_HL_BOOKMARKS_ROOT_FOLDER_NAME));
if (!line.Reserve(256))
return OpStatus::ERR_NO_MEMORY;
if (!url.Reserve(128))
return OpStatus::ERR_NO_MEMORY;
if (!title.Reserve(128))
return OpStatus::ERR_NO_MEMORY;
// FIXME: Should be loaded using oplanguagemanager
RETURN_IF_ERROR(url_text.Set("URL"));
RETURN_IF_ERROR(title_text.Set("Title"));
RETURN_IF_ERROR(desc_text.Set("Description"));
RETURN_IF_ERROR(sn_text.Set("Shortname"));
RETURN_IF_ERROR(folder_text.Set("Folder"));
RETURN_IF_ERROR(add_text.Set("Add bookmark"));
RETURN_IF_ERROR(add_folder_text.Set("Add folder"));
RETURN_IF_ERROR(load_text.Set("Load"));
RETURN_IF_ERROR(save_text.Set("Save"));
RETURN_IF_ERROR(save_mod_text.Set("Save changes"));
RETURN_IF_ERROR(modify_text.Set("Modify"));
RETURN_IF_ERROR(delete_text.Set("Delete"));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("<p>")));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, url_text));
RETURN_IF_ERROR(line.Set(": <input type=\"text\" class=\"string\" maxlength="));
RETURN_IF_ERROR(line.AppendFormat(UNI_L("%u id=\"au\" uid=\"\" value=\"\"></p>"), g_bookmark_manager->GetAttributeMaxLength(BOOKMARK_URL)));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, line));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("<p>")));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, title_text));
RETURN_IF_ERROR(line.Set(": <input type=\"text\" class=\"string\" maxlength="));
RETURN_IF_ERROR(line.AppendFormat(UNI_L("%u id=\"at\" value=\"\"></p>"), g_bookmark_manager->GetAttributeMaxLength(BOOKMARK_TITLE)));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, line));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("<p>")));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, desc_text));
RETURN_IF_ERROR(line.Set(": <input type=\"text\" class=\"string\" maxlength="));
RETURN_IF_ERROR(line.AppendFormat(UNI_L("%u id=\"ad\" value=\"\"></p>"), g_bookmark_manager->GetAttributeMaxLength(BOOKMARK_DESCRIPTION)));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, line));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("<p>")));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, sn_text));
RETURN_IF_ERROR(line.Set(": <input type=\"text\" class=\"string\" maxlength="));
RETURN_IF_ERROR(line.AppendFormat(UNI_L("%u id=\"as\" value=\"\"></p>"), g_bookmark_manager->GetAttributeMaxLength(BOOKMARK_SHORTNAME)));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, line));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("<p>")));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, folder_text));
RETURN_IF_ERROR(line.Set(": <input type=\"text\" class=\"string\" maxlength="));
RETURN_IF_ERROR(line.AppendFormat(UNI_L("%u id=\"ap\" value=\"\"></p>"), g_bookmark_manager->GetAttributeMaxLength(BOOKMARK_TITLE)));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, line));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("<button type=\"button\" id=\"add_bookmark\" onclick=\"opera.addBookmark(document.getElementById('au').value, document.getElementById('at').value, document.getElementById('ad').value, document.getElementById('as').value, document.getElementById('ap').value); update(); clearf()\">")));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, add_text));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("</button>")));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("<button type=\"button\" id=\"add_folder\" onclick=\"opera.addBookmarkFolder(document.getElementById('at').value, document.getElementById('ad').value, document.getElementById('as').value, document.getElementById('ap').value); update(); clearf();\">")));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, add_folder_text));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("</button>")));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("<button type=\"button\" id=\"load_bookmarks\" onclick=\"opera.loadBookmarks(); clearf();\">")));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, load_text));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("</button>")));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("<button type=\"button\" id=\"save_bookmarks\" onclick=\"opera.saveBookmarks(); clearf();\">")));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, save_text));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("</button>")));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("<button type=\"button\" id=\"move\" onclick=\"opera.moveBookmark(document.getElementById('au').getAttribute('uid'), document.getElementById('au').value, document.getElementById('at').value, document.getElementById('ad').value, document.getElementById('as').value, document.getElementById('ap').value); update(); clearf();\">")));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, save_mod_text));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("</button>")));
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("<div id='bm'><ul>")));
RETURN_IF_ERROR(g_bookmark_manager->GetList(&bookmark_list));
UINT32 old_depth = 0;
for (elm = (BookmarkListElm*) bookmark_list.First(); elm; elm = (BookmarkListElm*) elm->Suc())
{
UINT32 i;
BookmarkItem *bookmark = elm->GetBookmark();
if (bookmark->GetFolderType() == FOLDER_NO_FOLDER)
i = bookmark->GetFolderDepth();
else
i = bookmark->GetFolderDepth()-1;
#ifdef CORE_SPEED_DIAL_SUPPORT
if (bookmark->GetFolderType() == FOLDER_SPEED_DIAL_FOLDER || bookmark->GetParentFolder()->GetFolderType() == FOLDER_SPEED_DIAL_FOLDER)
continue;
#endif // CORE_SPEED_DIAL_SUPPORT
for (; i<old_depth; i++)
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("</ul>")));
old_depth = elm->GetBookmark()->GetFolderDepth();
RETURN_IF_ERROR(bookmark->GetAttribute(BOOKMARK_URL, &attr));
RETURN_IF_ERROR(attr.GetTextValue(url));
RETURN_IF_ERROR(bookmark->GetAttribute(BOOKMARK_TITLE, &attr));
RETURN_IF_ERROR(attr.GetTextValue(title));
OpString htmlified_title;
if (!title.IsEmpty())
RETURN_IF_ERROR(AppendHTMLified(&htmlified_title, title, title.Length()));
line.Reserve(128);
if (bookmark->GetFolderType() == FOLDER_SEPARATOR_FOLDER)
{
RETURN_IF_ERROR(line.Set("<hr>"));
}
else if (bookmark->GetFolderType() == FOLDER_NORMAL_FOLDER || bookmark->GetFolderType() == FOLDER_TRASH_FOLDER)
{
RETURN_IF_ERROR(line.Set("<div class=\"limited\"><li id=\""));
RETURN_IF_ERROR(line.Append(bookmark->GetUniqueId()));
RETURN_IF_ERROR(line.Append("\"><b>"));
RETURN_IF_ERROR(line.Append(htmlified_title));
RETURN_IF_ERROR(line.Append("</b></div>"));
RETURN_IF_ERROR(line.Append("<button type=\"button\" id='del' uid=\""));
RETURN_IF_ERROR(line.Append(bookmark->GetUniqueId()));
RETURN_IF_ERROR(line.Append("\" onclick=\"del(this);\">"));
RETURN_IF_ERROR(line.Append(delete_text));
RETURN_IF_ERROR(line.Append("</button>"));
// Add a modify button containing all modifyable bookmark attributes as attributes.
RETURN_IF_ERROR(line.Append("<button type=\"button\" id='mod' uid=\""));
RETURN_IF_ERROR(line.Append(bookmark->GetUniqueId()));
RETURN_IF_ERROR(line.Append("\" t=\""));
RETURN_IF_ERROR(line.Append(htmlified_title));
RETURN_IF_ERROR(line.Append("\" d=\""));
RETURN_IF_ERROR(bookmark->GetAttribute(BOOKMARK_DESCRIPTION, &attr));
RETURN_IF_ERROR(attr.GetTextValue(str));
if (!str.IsEmpty())
RETURN_IF_ERROR(AppendHTMLified(&line, str, str.Length()));
RETURN_IF_ERROR(line.Append("\" sn=\""));
RETURN_IF_ERROR(bookmark->GetAttribute(BOOKMARK_SHORTNAME, &attr));
RETURN_IF_ERROR(attr.GetTextValue(str));
if (!str.IsEmpty())
RETURN_IF_ERROR(AppendHTMLified(&line, str, str.Length()));
RETURN_IF_ERROR(line.Append("\" pt=\""));
if (bookmark->GetParentFolder() != g_bookmark_manager->GetRootFolder())
{
RETURN_IF_ERROR(elm->GetBookmark()->GetParentFolder()->GetAttribute(BOOKMARK_TITLE, &attr));
RETURN_IF_ERROR(attr.GetTextValue(str));
if (!str.IsEmpty())
RETURN_IF_ERROR(AppendHTMLified(&line, str, str.Length()));
}
RETURN_IF_ERROR(line.Append("\" onclick=\"mod(this);\">"));
RETURN_IF_ERROR(line.Append(modify_text));
RETURN_IF_ERROR(line.Append(UNI_L("</button>")));
RETURN_IF_ERROR(line.Append(UNI_L("</li><ul>")));
}
else
{
RETURN_IF_ERROR(line.Set("<div class=\"limited\"><li id=\""));
RETURN_IF_ERROR(line.Append(elm->GetBookmark()->GetUniqueId()));
RETURN_IF_ERROR(line.Append("\">"));
if (url.HasContent())
{
RETURN_IF_ERROR(line.Append("<a href=\""));
RETURN_IF_ERROR(AppendHTMLified(&line, url, url.Length()));
RETURN_IF_ERROR(line.Append("\">"));
}
RETURN_IF_ERROR(line.Append(htmlified_title));
RETURN_IF_ERROR(line.Append("</a></div><button type=\"button\" id='del' uid=\""));
RETURN_IF_ERROR(line.Append(elm->GetBookmark()->GetUniqueId()));
RETURN_IF_ERROR(line.Append("\" onclick=\"del(this);\">"));
RETURN_IF_ERROR(line.Append(delete_text));
RETURN_IF_ERROR(line.Append("</button>"));
// Add a modify button containing all modifiable bookmark attributes as attributes.
RETURN_IF_ERROR(line.Append("<button type=\"button\" id='mod' uid=\""));
RETURN_IF_ERROR(line.Append(elm->GetBookmark()->GetUniqueId()));
RETURN_IF_ERROR(line.Append("\" url=\""));
RETURN_IF_ERROR(elm->GetBookmark()->GetAttribute(BOOKMARK_URL, &attr));
RETURN_IF_ERROR(attr.GetTextValue(str));
if (!str.IsEmpty())
RETURN_IF_ERROR(AppendHTMLified(&line, str, str.Length()));
RETURN_IF_ERROR(line.Append("\" t=\""));
RETURN_IF_ERROR(line.Append(htmlified_title));
RETURN_IF_ERROR(line.Append("\" d=\""));
RETURN_IF_ERROR(elm->GetBookmark()->GetAttribute(BOOKMARK_DESCRIPTION, &attr));
RETURN_IF_ERROR(attr.GetTextValue(str));
if (!str.IsEmpty())
RETURN_IF_ERROR(AppendHTMLified(&line, str, str.Length()));
RETURN_IF_ERROR(elm->GetBookmark()->GetAttribute(BOOKMARK_SHORTNAME, &attr));
RETURN_IF_ERROR(attr.GetTextValue(str));
RETURN_IF_ERROR(line.Append("\" sn=\""));
if (!str.IsEmpty())
RETURN_IF_ERROR(AppendHTMLified(&line, str, str.Length()));
RETURN_IF_ERROR(line.Append("\" pt=\""));
if (elm->GetBookmark()->GetParentFolder() != g_bookmark_manager->GetRootFolder())
{
RETURN_IF_ERROR(elm->GetBookmark()->GetParentFolder()->GetAttribute(BOOKMARK_TITLE, &attr));
RETURN_IF_ERROR(attr.GetTextValue(str));
if (!str.IsEmpty())
RETURN_IF_ERROR(AppendHTMLified(&line, str, str.Length()));
}
RETURN_IF_ERROR(line.Append("\" onclick=\"mod(this)\">"));
RETURN_IF_ERROR(line.Append(modify_text));
RETURN_IF_ERROR(line.Append("</button>"));
RETURN_IF_ERROR(line.Append("</li>"));
}
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, line));
}
RETURN_IF_ERROR(m_url.WriteDocumentData(URL::KNormal, UNI_L("</ul></div>")));
return CloseDocument();
}
OperaBookmarksListener::OperaBookmarksListener()
{
m_ai = NULL;
m_callback = NULL;
m_form_url = NULL;
m_form_title = NULL;
m_form_desc = NULL;
m_form_sn = NULL;
m_form_parent_title = NULL;
}
OperaBookmarksListener::~OperaBookmarksListener()
{
OP_DELETEA(m_form_url);
OP_DELETEA(m_form_title);
OP_DELETEA(m_form_desc);
OP_DELETEA(m_form_sn);
OP_DELETEA(m_form_parent_title);
}
OP_STATUS OperaBookmarksListener::SetValue(uni_char **dst, const uni_char *src)
{
unsigned len;
if (src)
{
if (*dst)
OP_DELETEA(*dst);
len = uni_strlen(src)+1;
*dst = OP_NEWA(uni_char, len);
if (!*dst)
return OpStatus::ERR_NO_MEMORY;
uni_strcpy(*dst, src);
}
return OpStatus::OK;
}
void OperaBookmarksListener::SetSavedFormValues(const uni_char *form_url, const uni_char *form_title, const uni_char *form_desc, const uni_char *form_sn, const uni_char *form_parent_title)
{
RETURN_VOID_IF_ERROR(SetValue(&m_form_url, form_url));
RETURN_VOID_IF_ERROR(SetValue(&m_form_title, form_title));
RETURN_VOID_IF_ERROR(SetValue(&m_form_desc, form_desc));
RETURN_VOID_IF_ERROR(SetValue(&m_form_sn, form_sn));
RETURN_VOID_IF_ERROR(SetValue(&m_form_parent_title, form_parent_title));
}
void OperaBookmarksListener::OnBookmarksLoaded(OP_STATUS ret, UINT32 operation_count)
{
m_ai->CallFunction(m_callback, NULL, 0, NULL);
}
void OperaBookmarksListener::OnBookmarksSaved(OP_STATUS ret, UINT32 operation_count)
{
}
#ifdef SUPPORT_DATA_SYNC
void OperaBookmarksListener::OnBookmarksSynced(OP_STATUS ret)
{
m_ai->CallFunction(m_callback, NULL, 0, NULL);
}
#endif // SUPPORT_DATA_SYNC
#endif // OPERABOOKMARKS_URL
|
#include "../include/cmpro/deep_process.h"
DeepProcess::DeepProcess() :config(),converter(),seqconverter(),model_process(){
std::cout << "starting." << std::endl;
rfleft = 0;
rftop = 0;
area_width = config.WIN_WIDTH;
area_height = config.WIN_HEIGHT;
detector = dlib::get_frontal_face_detector();
is_loop_continue = true;
state = 0;
score = 0;
is_updated = true;
try{
dlib::deserialize("../resource/shape_predictor_68_face_landmarks.dat") >> pose_model;
}
catch (dlib::serialization_error& e)
{
std::cout << std::endl << e.what() << std::endl;
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
void DeepProcess::loop_process() {
try{
//cap initialization
cv::VideoCapture cap;
if(config.stin == "0"){
cap.open(0);
}
else{
cap.open("../videoraw/" + config.stin + ".mp4");
}
if (!cap.isOpened()) {
std::cerr << "Unable to connect to camera" << std::endl;
return;
}
//ShowingWindow showing_window(&cap);
std::cout << "initialized." << std::endl;
while(cv::waitKey(10)!='q' && is_loop_continue) {
cap >> showing_image;
cv::Mat processing_image;
processing_image = showing_image.clone();
cv::resize(processing_image, processing_image, cv::Size(config.WIN_WIDTH, config.WIN_HEIGHT), 0, 0,
cv::INTER_LINEAR); //resize image to suitable size
processing_image = processing_image(cv::Rect(std::max(0L, rfleft), std::max(0L, rftop),
std::min(config.WIN_WIDTH - rfleft, area_width),
std::min(config.WIN_HEIGHT - rftop, area_height)));
dlib::cv_image<dlib::bgr_pixel> cimg(processing_image);
std::vector<dlib::rectangle> faces = detector(cimg);
dlib::full_object_detection sps;
clock_weight = clock();
if (!faces.empty()) {
sps = pose_model(cimg, faces[0]);
detected_shape = sps;
//if faces points found
DimensionCalculation();
if(sps.num_parts() < 68){
std::cerr << "extraction error" << std::endl;
return;
}
duration = clock() - clock_weight;
clock_weight = clock();
std::vector<int> uvdata;
for(unsigned long i=0;i<sps.num_parts();i++){
uvdata.push_back(sps.part(i).x());
uvdata.push_back(sps.part(i).y());
}
state = 0;
std::vector<double> xydata = converter.multi_convert(uvdata);
std::vector<std::vector<double> > new_vectors = seqconverter.newdata(xydata,duration);;
for(auto new_vector : new_vectors){
state = model_process.model_predict(new_vector);
if(state == 1){
score += 250;//Serious
}
if(state == 2){
score += 200;//Average
}
if(state ==3){
score += 75;//Slight
}
if(state ==4){
score -= 50;//Normal
}
score = std::max(0.0, score);
score = std::min(config.SCORE_MAX, score);
putText(showing_image, show_msg[state], cv::Point(10, 60), cv::QT_FONT_NORMAL, 1, cvScalar(0, 0, 255),
1, 1);
std::cout << ctmsg[state] << std::endl;
imshow("cap", showing_image);
}
//state = shape_processing.deep_cal();
//Sub 末端处理(人脸切割)
//final preperation (face selection)
rfleft += shape_differ_left - config.MARGIN_LEFT;
rftop += shape_differ_top - config.MARGIN_TOP;
area_width = shape_width + config.MARGIN_LEFT + config.MARGIN_RIGHT;
area_height = shape_height + config.MARGIN_TOP + config.MARGIN_DOWN;
}
}
}
catch (dlib::serialization_error& e)
{
std::cout << std::endl << e.what() << std::endl;
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
}
int DeepProcess::deep_cal() {
std::vector<int> shape_ori;
std::vector<double> shape_before;
int result=0;
for(int i=0;i<68;i++){
shape_ori.push_back(detected_shape.part(i).x());
shape_ori.push_back(detected_shape.part(i).y());
}
//the process to convert to a sorted input shape
shape_before = converter.multi_convert(shape_ori);
if(result >0 && result < 5){
return result;
}
return -1;
}
void DeepProcess::DimensionCalculation() {
long shape_differ_right=0;
long shape_differ_down=0;
if(is_updated){
shape_differ_left=detected_shape.part(0).x();
shape_differ_right=detected_shape.part(16).x();
shape_differ_top=std::min(detected_shape.part(19).y(),detected_shape.part(24).y());
shape_differ_down=detected_shape.part(9).y();
for(unsigned long i=1;i<27;i++){
shape_differ_left=std::min(shape_differ_left,detected_shape.part(i).x());
shape_differ_right=std::max(shape_differ_right,detected_shape.part(i).x());
shape_differ_top=std::min(shape_differ_top,detected_shape.part(i).y());
shape_differ_down=std::max(shape_differ_down,detected_shape.part(i).y());
}
shape_width = shape_differ_right - shape_differ_left;
shape_height = shape_differ_down - shape_differ_top;
}
else{
std::cerr << "Shape sub not prepared Error" << std::endl;
return;
}
}
|
/*
Written by Anshul Verma, 19/78065
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char **argv)
{
if (argc < 2)
{
fprintf(stderr, "Correct Usage: ./main <filename>\n");
return -1;
}
struct stat dt;
printf("\nFile Info\n");
printf("--------------------\n");
printf("Name: %s\n", argv[1]);
printf("UserID: %d\n", dt.st_uid);
printf("GroupID: %d\n", dt.st_gid);
printf("File Type: %d\n", S_IFMT);
printf("Directory: %s\n", S_IFDIR ? "Yes" : "No");
printf("Regular File: %s\n", S_IFREG ? "Yes" : "No");
printf("Last access time: %ld\n", dt.st_atime);
printf("Last modified time: %ld\n", dt.st_mtime);
printf("User Permissions:\n");
printf(" Read: %s\n", S_IRUSR ? "Yes" : "No");
printf(" Write: %s\n", S_IWUSR ? "Yes" : "No");
printf(" Execute: %s\n", S_IXUSR ? "Yes" : "No");
printf("Group Permissions:\n");
printf(" Read: %s\n", S_IRGRP ? "Yes" : "No");
printf(" Write: %s\n", S_IWGRP ? "Yes" : "No");
printf(" Execute: %s\n", S_IXGRP ? "Yes" : "No");
printf("Others Permissions:\n");
printf(" Read: %s\n", S_IROTH ? "Yes" : "No");
printf(" Write: %s\n", S_IWOTH ? "Yes" : "No");
printf(" Execute: %s\n\n", S_IXOTH ? "Yes" : "No");
}
|
/*====================================================================
Copyright(c) 2018 Adam Rankin
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files(the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
====================================================================*/
#pragma once
// Local includes
#include "pch.h"
#include "Common.h"
#include "MathCommon.h"
#include "Tool.h"
#include "ToolSystem.h"
// Rendering includes
#include "ModelRenderer.h"
// UI includes
#include "Icons.h"
// System includes
#include "NetworkSystem.h"
#include "NotificationSystem.h"
#include "RegistrationSystem.h"
using namespace Concurrency;
using namespace Windows::Data::Xml::Dom;
using namespace Windows::Foundation::Numerics;
using namespace Windows::Media::SpeechRecognition;
using namespace Windows::Perception::Spatial;
using namespace Windows::Storage;
using namespace Windows::UI::Input::Spatial;
namespace HoloIntervention
{
namespace System
{
//----------------------------------------------------------------------------
float3 ToolSystem::GetStabilizedPosition(SpatialPointerPose^ pose) const
{
std::shared_ptr<Tools::Tool> maxEntry(nullptr);
float maxPriority(PRIORITY_NOT_ACTIVE);
for (auto& entry : m_tools)
{
if (entry->GetStabilizePriority() > maxPriority)
{
maxPriority = entry->GetStabilizePriority();
maxEntry = entry;
}
}
if (maxEntry != nullptr)
{
return maxEntry->GetStabilizedPosition(pose);
}
return float3(0.f, 0.f, 0.f);
}
//----------------------------------------------------------------------------
float3 ToolSystem::GetStabilizedVelocity() const
{
std::shared_ptr<Tools::Tool> maxEntry(nullptr);
float maxPriority(PRIORITY_NOT_ACTIVE);
for (auto& entry : m_tools)
{
if (entry->GetStabilizePriority() > maxPriority)
{
maxPriority = entry->GetStabilizePriority();
maxEntry = entry;
}
}
if (maxEntry != nullptr)
{
return maxEntry->GetStabilizedVelocity();
}
return float3(0.f, 0.f, 0.f);
}
//----------------------------------------------------------------------------
float ToolSystem::GetStabilizePriority() const
{
float maxPriority(PRIORITY_NOT_ACTIVE);
for (auto& entry : m_tools)
{
if (entry->GetStabilizePriority() > maxPriority)
{
maxPriority = entry->GetStabilizePriority();
}
}
return maxPriority;
}
//----------------------------------------------------------------------------
task<bool> ToolSystem::WriteConfigurationAsync(XmlDocument^ document)
{
return create_task([this, document]()
{
auto xpath = ref new Platform::String(L"/HoloIntervention");
if (document->SelectNodes(xpath)->Length != 1)
{
return false;
}
auto node = document->SelectNodes(xpath)->Item(0);
auto toolsElem = document->CreateElement("Tools");
toolsElem->SetAttribute(L"IGTConnection", ref new Platform::String(m_connectionName.c_str()));
toolsElem->SetAttribute(L"ShowIcons", m_showIcons ? L"true" : L"false");
node->AppendChild(toolsElem);
for (auto tool : m_tools)
{
auto toolElem = document->CreateElement("Tool");
if (tool->GetModel()->IsPrimitive())
{
toolElem->SetAttribute(L"Primitive", ref new Platform::String(Rendering::ModelRenderer::PrimitiveToString(tool->GetModel()->GetPrimitiveType()).c_str()));
toolElem->SetAttribute(L"Argument", tool->GetModel()->GetArgument().x.ToString() + L" " + tool->GetModel()->GetArgument().y.ToString() + L" " + tool->GetModel()->GetArgument().z.ToString());
toolElem->SetAttribute(L"Colour", tool->GetModel()->GetCurrentColour().x.ToString() + L" " + tool->GetModel()->GetCurrentColour().y.ToString() + L" " + tool->GetModel()->GetCurrentColour().z.ToString() + L" " + tool->GetModel()->GetCurrentColour().w.ToString());
toolElem->SetAttribute(L"Tessellation", tool->GetModel()->GetTessellation().ToString());
toolElem->SetAttribute(L"RightHandedCoords", tool->GetModel()->GetRHCoords().ToString());
toolElem->SetAttribute(L"InvertN", tool->GetModel()->GetInvertN().ToString());
}
else
{
toolElem->SetAttribute(L"Model", ref new Platform::String(tool->GetModel()->GetAssetLocation().c_str()));
}
toolElem->SetAttribute("ModelToObjectTransform", ref new Platform::String(PrintMatrix(tool->GetModelToObjectTransform()).c_str()));
toolElem->SetAttribute(L"From", tool->GetCoordinateFrame()->From());
toolElem->SetAttribute(L"To", tool->GetCoordinateFrame()->To());
toolElem->SetAttribute(L"Id", ref new Platform::String(tool->GetUserId().c_str()));
toolElem->SetAttribute(L"LerpEnabled", tool->GetModel()->GetLerpEnabled() ? L"true" : L"false");
if (tool->GetModel()->GetLerpEnabled())
{
toolElem->SetAttribute(L"LerpRate", tool->GetModel()->GetLerpRate().ToString());
}
toolsElem->AppendChild(toolElem);
}
m_transformRepository->WriteConfiguration(document);
return true;
});
}
//----------------------------------------------------------------------------
task<bool> ToolSystem::ReadConfigurationAsync(XmlDocument^ document)
{
if (!m_transformRepository->ReadConfiguration(document))
{
return task_from_result(false);
}
return create_task([this, document]()
{
auto xpath = ref new Platform::String(L"/HoloIntervention/Tools");
if (document->SelectNodes(xpath)->Length != 1)
{
throw ref new Platform::Exception(E_INVALIDARG, L"Invalid \"Tools\" tag in configuration.");
}
auto node = document->SelectNodes(xpath)->Item(0);
if (!HasAttribute(L"IGTConnection", node))
{
throw ref new Platform::Exception(E_FAIL, L"Tool configuration does not contain \"IGTConnection\" attribute.");
}
Platform::String^ connectionName = dynamic_cast<Platform::String^>(node->Attributes->GetNamedItem(L"IGTConnection")->NodeValue);
m_connectionName = std::wstring(connectionName->Data());
m_hashedConnectionName = HashString(connectionName);
if (HasAttribute(L"ShowIcons", node))
{
Platform::String^ showIcons = dynamic_cast<Platform::String^>(node->Attributes->GetNamedItem(L"ShowIcons")->NodeValue);
m_showIcons = IsEqualInsensitive(showIcons, L"true");
}
xpath = ref new Platform::String(L"/HoloIntervention/Tools/Tool");
if (document->SelectNodes(xpath)->Length == 0)
{
throw ref new Platform::Exception(E_INVALIDARG, L"No tools defined in the configuration file. Check for the existence of Tools/Tool");
}
for (auto node : document->SelectNodes(xpath))
{
Platform::String^ modelString = nullptr;
Platform::String^ primString = nullptr;
Platform::String^ fromString = nullptr;
Platform::String^ toString = nullptr;
Platform::String^ argumentString = nullptr;
Platform::String^ colourString = nullptr;
Platform::String^ tessellationString = nullptr;
Platform::String^ rhcoordsString = nullptr;
Platform::String^ invertnString = nullptr;
Platform::String^ userId = nullptr;
// model, transform
if (HasAttribute(L"Id", node))
{
userId = dynamic_cast<Platform::String^>(node->Attributes->GetNamedItem(L"Id")->NodeValue);
}
else
{
throw ref new Platform::Exception(E_FAIL, L"Tool entry does not contain Id attribute.");
}
if (!HasAttribute(L"Model", node) && !HasAttribute(L"Primitive", node))
{
throw ref new Platform::Exception(E_FAIL, L"Tool entry does not contain model or primitive attribute.");
}
if (!HasAttribute(L"From", node) || !HasAttribute(L"To", node))
{
throw ref new Platform::Exception(E_FAIL, L"Tool entry does not contain transform attribute.");
}
if (HasAttribute(L"Model", node))
{
modelString = dynamic_cast<Platform::String^>(node->Attributes->GetNamedItem(L"Model")->NodeValue);
}
if (HasAttribute(L"Primitive", node))
{
primString = dynamic_cast<Platform::String^>(node->Attributes->GetNamedItem(L"Primitive")->NodeValue);
}
fromString = dynamic_cast<Platform::String^>(node->Attributes->GetNamedItem(L"From")->NodeValue);
toString = dynamic_cast<Platform::String^>(node->Attributes->GetNamedItem(L"To")->NodeValue);
if ((modelString != nullptr && modelString->IsEmpty()) || (primString != nullptr && primString->IsEmpty()) || fromString->IsEmpty() || toString->IsEmpty())
{
throw ref new Platform::Exception(E_FAIL, L"Tool entry contains an empty attribute.");
}
if (HasAttribute(L"Argument", node))
{
argumentString = dynamic_cast<Platform::String^>(node->Attributes->GetNamedItem(L"Argument")->NodeValue);
}
if (HasAttribute(L"Colour", node))
{
colourString = dynamic_cast<Platform::String^>(node->Attributes->GetNamedItem(L"Colour")->NodeValue);
}
if (HasAttribute(L"Tessellation", node))
{
tessellationString = dynamic_cast<Platform::String^>(node->Attributes->GetNamedItem(L"Tessellation")->NodeValue);
}
if (HasAttribute(L"RightHandedCoords", node))
{
rhcoordsString = dynamic_cast<Platform::String^>(node->Attributes->GetNamedItem(L"RightHandedCoords")->NodeValue);
}
if (HasAttribute(L"InvertN", node))
{
invertnString = dynamic_cast<Platform::String^>(node->Attributes->GetNamedItem(L"InvertN")->NodeValue);
}
UWPOpenIGTLink::TransformName^ trName = ref new UWPOpenIGTLink::TransformName(fromString, toString);
if (!trName->IsValid())
{
throw ref new Platform::Exception(E_FAIL, L"Tool entry contains invalid transform name.");
}
// Ensure unique tool id
for (auto& tool : m_tools)
{
if (IsEqualInsensitive(userId, tool->GetUserId()))
{
LOG_ERROR("Duplicate tool ID used. Skipping tool configuration.");
continue;
}
}
float4x4 mat = float4x4::identity();
if (HasAttribute(L"ModelToObjectTransform", node))
{
auto transformStr = dynamic_cast<Platform::String^>(node->Attributes->GetNamedItem(L"ModelToObjectTransform")->NodeValue);
mat = ReadMatrix(transformStr);
}
task<uint64> registerTask;
if (modelString != nullptr)
{
registerTask = RegisterToolAsync(std::wstring(modelString->Data()), userId, mat, false, trName);
}
else
{
size_t tessellation = 16;
float4 colour(float4::one());
bool rhcoords = true;
bool invertn = false;
float3 argument = { 0.f, 0.f, 0.f };
if (argumentString != nullptr && !argumentString->IsEmpty())
{
std::wstringstream wss;
wss << argumentString->Data();
wss >> argument.x;
wss >> argument.y;
wss >> argument.z;
}
if (colourString != nullptr && !colourString->IsEmpty())
{
std::wstringstream wss;
wss << colourString->Data();
wss >> colour.x;
wss >> colour.y;
wss >> colour.z;
wss >> colour.w;
}
if (tessellationString != nullptr && !tessellationString->IsEmpty())
{
std::wstringstream wss;
wss << tessellationString->Data();
wss >> tessellation;
}
if (rhcoordsString != nullptr && !rhcoordsString->IsEmpty())
{
rhcoords = IsEqualInsensitive(rhcoordsString, L"true");
}
if (invertnString != nullptr && !invertnString->IsEmpty())
{
invertn = IsEqualInsensitive(invertnString, L"true");
}
registerTask = RegisterToolAsync(std::wstring(primString->Data()), userId, mat, true, trName, colour, argument, tessellation, rhcoords, invertn);
}
registerTask.then([this, node](uint64 token)
{
if (token == INVALID_TOKEN)
{
return;
}
auto tool = GetTool(token);
bool lerpEnabled;
if (GetBooleanAttribute(L"LerpEnabled", node, lerpEnabled))
{
tool->GetModel()->EnablePoseLerp(lerpEnabled);
}
float lerpRate;
if (GetScalarAttribute<float>(L"LerpRate", node, lerpRate))
{
tool->GetModel()->SetPoseLerpRate(lerpRate);
}
});
}
m_componentReady = true;
return true;
});
}
//----------------------------------------------------------------------------
ToolSystem::ToolSystem(HoloInterventionCore& core, NotificationSystem& notificationSystem, RegistrationSystem& registrationSystem, Rendering::ModelRenderer& modelRenderer, NetworkSystem& networkSystem, UI::Icons& icons)
: IConfigurable(core)
, m_notificationSystem(notificationSystem)
, m_registrationSystem(registrationSystem)
, m_icons(icons)
, m_modelRenderer(modelRenderer)
, m_transformRepository(ref new UWPOpenIGTLink::TransformRepository())
, m_networkSystem(networkSystem)
{
}
//----------------------------------------------------------------------------
ToolSystem::~ToolSystem()
{
}
//----------------------------------------------------------------------------
uint32 ToolSystem::GetToolCount() const
{
std::lock_guard<std::mutex> guard(m_entriesMutex);
return m_tools.size();
}
//----------------------------------------------------------------------------
std::shared_ptr<Tools::Tool> ToolSystem::GetTool(uint64 token) const
{
std::lock_guard<std::mutex> guard(m_entriesMutex);
for (auto iter = m_tools.begin(); iter != m_tools.end(); ++iter)
{
if (token == (*iter)->GetId())
{
return *iter;
}
}
return nullptr;
}
//----------------------------------------------------------------------------
std::shared_ptr<HoloIntervention::Tools::Tool> ToolSystem::GetToolByUserId(const std::wstring& userId) const
{
std::lock_guard<std::mutex> guard(m_entriesMutex);
for (auto iter = m_tools.begin(); iter != m_tools.end(); ++iter)
{
if (IsEqualInsensitive(userId, (*iter)->GetUserId()))
{
return *iter;
}
}
return nullptr;
}
//----------------------------------------------------------------------------
std::shared_ptr<HoloIntervention::Tools::Tool> ToolSystem::GetToolByUserId(Platform::String^ userId) const
{
return GetToolByUserId(std::wstring(userId->Data()));
}
//----------------------------------------------------------------------------
std::vector<std::shared_ptr<Tools::Tool>> ToolSystem::GetTools()
{
return m_tools;
}
//----------------------------------------------------------------------------
bool ToolSystem::IsToolValid(uint64 token) const
{
auto tool = GetTool(token);
if (tool == nullptr)
{
return false;
}
return tool->IsValid();
}
//----------------------------------------------------------------------------
bool ToolSystem::WasToolValid(uint64 token) const
{
auto tool = GetTool(token);
if (tool == nullptr)
{
return false;
}
return tool->WasValid();
}
//----------------------------------------------------------------------------
task<uint64> ToolSystem::RegisterToolAsync(const std::wstring& modelName, Platform::String^ userId, float4x4 modelToObjectTransform, const bool isPrimitive, UWPOpenIGTLink::TransformName^ coordinateFrame, float4 colour, float3 argument, size_t tessellation, bool rhcoords, bool invertn)
{
task<uint64> modelTask;
if (!isPrimitive)
{
modelTask = m_modelRenderer.AddModelAsync(modelName);
}
else
{
modelTask = m_modelRenderer.AddPrimitiveAsync(modelName, argument, tessellation, rhcoords, invertn);
}
return modelTask.then([this, coordinateFrame, colour, modelToObjectTransform, userId](uint64 modelEntryId)
{
if (modelEntryId == INVALID_TOKEN)
{
LOG_ERROR("Cannot create tool. Model failed to load.");
return task_from_result(INVALID_TOKEN);
}
std::shared_ptr<Tools::Tool> entry = std::make_shared<Tools::Tool>(m_modelRenderer, m_networkSystem, m_icons, m_hashedConnectionName, coordinateFrame, m_transformRepository, userId);
entry->SetModelToObjectTransform(modelToObjectTransform);
auto modelEntry = m_modelRenderer.GetModel(modelEntryId);
return entry->SetModelAsync(modelEntry).then([this, entry, modelEntry, colour]()
{
modelEntry->SetVisible(false);
modelEntry->SetColour(colour);
std::lock_guard<std::mutex> guard(m_entriesMutex);
m_tools.push_back(entry);
entry->ShowIcon(m_showIcons);
return entry->GetId();
});
});
}
//----------------------------------------------------------------------------
void ToolSystem::UnregisterTool(uint64 toolToken)
{
std::lock_guard<std::mutex> guard(m_entriesMutex);
for (auto iter = m_tools.begin(); iter != m_tools.end(); ++iter)
{
if (toolToken == (*iter)->GetId())
{
m_tools.erase(iter);
return;
}
}
}
//----------------------------------------------------------------------------
void ToolSystem::ClearTools()
{
std::lock_guard<std::mutex> guard(m_entriesMutex);
m_tools.clear();
}
//----------------------------------------------------------------------------
void ToolSystem::Update(const DX::StepTimer& timer, SpatialCoordinateSystem^ hmdCoordinateSystem)
{
// Update the transform repository with the latest registration
float4x4 referenceToHMD(float4x4::identity());
bool registrationAvailable = m_registrationSystem.GetReferenceToCoordinateSystemTransformation(hmdCoordinateSystem, referenceToHMD);
m_transformRepository->SetTransform(ref new UWPOpenIGTLink::TransformName(L"Reference", HOLOLENS_COORDINATE_SYSTEM_PNAME), transpose(referenceToHMD), registrationAvailable);
std::lock_guard<std::mutex> guard(m_entriesMutex);
for (auto entry : m_tools)
{
entry->Update(timer);
}
}
//----------------------------------------------------------------------------
void ToolSystem::RegisterVoiceCallbacks(Input::VoiceInputCallbackMap& callbackMap)
{
callbackMap[L"hide tools"] = [this](SpeechRecognitionResult ^ result)
{
std::lock_guard<std::mutex> guard(m_entriesMutex);
for (auto entry : m_tools)
{
entry->SetHiddenOverride(true);
}
};
callbackMap[L"show tools"] = [this](SpeechRecognitionResult ^ result)
{
std::lock_guard<std::mutex> guard(m_entriesMutex);
for (auto entry : m_tools)
{
entry->SetHiddenOverride(false);
}
};
}
//----------------------------------------------------------------------------
void ToolSystem::ShowIcons(bool show)
{
for (auto& entry : m_tools)
{
entry->ShowIcon(show);
}
}
}
}
|
#ifndef COLORGROUP_H
#define COLORGROUP_H
#define INF 999999999
#include <vector>
#include "segment.h"
#include "distribution.h"
#include <cstdio>
#include <iostream>
#include <algorithm>
class ColorGroup
{
private:
std::vector<std::pair<char, Numeric> > properties;
std::vector<Segment*> mainSegments;
Color color;
QImage *image;
int totalSegments;
public:
ColorGroup();
ColorGroup(QImage *image);
ColorGroup(QColor color);
ColorGroup(QImage *image, QColor color);
float mean_segs;
int min_num_elements;
int max_num_elements;
std::vector<Segment> segments;
// Segment Size Statistics
void SegmentStatistics();
void setTotalSegments(int num);
float getRelativeSize();
int getLightness();
int getSaturation();
float relativeNumberofSegments();
void addSegment(Segment &seg);
void transformColor(QColor color);
int count();
int countMain();
Color getColor();
void setColor(QColor &color);
QImage *getImage();
void separateNoise(float noiseThreshold);
std::vector<std::pair<char, Numeric> > &getProperties();
void deepCopyTo(ColorGroup *to);
double score(std::vector<std::pair<char, Distribution*> > &distribution, int &index);
};
#endif // COLORGROUP_H
|
//
// TODO:
// - unarmed posture
// - relaxed posture
// - turning in place too much, rely more on look angles?
#include "../../idlib/precompiled.h"
#pragma hdrstop
#include "../Game_local.h"
#include "AI_Manager.h"
#include "AI_Util.h"
#include "AI_Tactical.h"
const idEventDef AI_ForcePosture ( "forcePosture", "d" );
CLASS_DECLARATION( idAI, rvAITactical )
EVENT( AI_ForcePosture, rvAITactical::Event_ForcePosture )
EVENT( EV_PostSpawn, rvAITactical::Event_PostSpawn )
END_CLASS
static const char* aiPostureString[AIPOSTURE_MAX] = {
"stand", // AIPOSTURE_STAND,
"crouch", // AIPOSTURE_CROUCH,
"cover_left", // AIPOSTURE_STAND_COVER_LEFT,
"cover_right", // AIPOSTURE_STAND_COVER_RIGHT,
"crouch_cover", // AIPOSTURE_CROUCH_COVER
"crouch_cover_left", // AIPOSTURE_CROUCH_COVER_LEFT,
"crouch_cover_right", // AIPOSTURE_CROUCH_COVER_RIGHT,
"relaxed", // AIPOSTURE_RELAXED
"unarmed", // AIPOSTURE_UNARMED
"at_attention", // AIPOSTURE_AT_ATTENTION
};
/*
================
rvAITactical::rvAITactical
================
*/
rvAITactical::rvAITactical ( void ) {
shots = 0;
nextWallTraceTime = 0;
}
void rvAITactical::InitSpawnArgsVariables ( void )
{
// Initialize the posture info
InitPostureInfo ( );
maxShots = spawnArgs.GetInt ( "maxShots", "1" );
minShots = spawnArgs.GetInt ( "minShots", "1" );
fireRate = SEC2MS ( spawnArgs.GetFloat ( "fireRate", "1" ) );
healthRegen = spawnArgs.GetInt( "healthRegen", "2" );
healthRegenEnabled = spawnArgs.GetBool( "healthRegenEnabled", "0" );
}
/*
================
rvAITactical::Spawn
================
*/
void rvAITactical::Spawn ( void ) {
InitSpawnArgsVariables();
// Force a posture?
const char* temp;
postureForce = AIPOSTURE_DEFAULT;
if ( spawnArgs.GetString ( "forcePosture", "", &temp ) && *temp ) {
for ( postureForce = AIPOSTURE_STAND; postureForce != AIPOSTURE_MAX; ((int&)postureForce)++ ) {
if ( !idStr::Icmp ( aiPostureString[postureForce], temp ) ) {
break;
}
}
if ( postureForce >= AIPOSTURE_MAX ) {
postureForce = AIPOSTURE_DEFAULT;
}
}
UpdatePosture ( );
postureCurrent = postureIdeal;
OnPostureChange ( );
ammo = spawnArgs.GetInt ( "ammo", "-1" );
// Initialize custom actions
actionElbowAttack.Init ( spawnArgs, "action_elbowAttack", NULL, AIACTIONF_ATTACK );
actionKillswitchAttack.Init ( spawnArgs, "action_killswitchAttack", NULL, AIACTIONF_ATTACK );
actionTimerPeek.Init ( spawnArgs, "actionTimer_peek" );
// playerFocusTime = 0;
// playerAnnoyTime = SEC2MS(spawnArgs.GetFloat ( "annoyed", "5" ));
healthRegenNextTime = 0;
maxHealth = health;
}
/*
================
rvAITactical::Think
================
*/
void rvAITactical::Think ( void ) {
idAI::Think ( );
// If not simple thinking and not in an action, update the posture
if ( !(aifl.scripted&&move.moveCommand==MOVE_NONE) && aifl.awake && !aifl.simpleThink && !aifl.action && !aifl.dead ) {
if ( UpdatePosture ( ) ) {
PerformAction ( "Torso_SetPosture", 4, true );
}
}
// FIXME: disabled for now, its annoying people
/*
idPlayer* localPlayer;
localPlayer = gameLocal.GetLocalPlayer();
// If the player has been standing in front of the marine and looking at him for too long he should say something
if ( !aifl.dead && playerFocusTime && playerAnnoyTime
&& !aifl.scripted && focusType == AIFOCUS_PLAYER && localPlayer && !IsSpeaking()
&& !localPlayer->IsBeingTalkedTo() //nobody else is talking to him right now
&& DistanceTo( localPlayer ) < 64.0f ) {
idVec3 diff;
diff = GetPhysics()->GetOrigin() - localPlayer->GetPhysics()->GetOrigin();
diff.NormalizeFast();
// Is the player looking at the marine?
if ( diff * localPlayer->viewAxis[0] > 0.7f ) {
// Say something every 5 seconds
if ( gameLocal.time - playerFocusTime > playerAnnoyTime ) {
// Debounce it against other marines
if ( aiManager.CheckTeamTimer ( team, AITEAMTIMER_ANNOUNCE_CANIHELPYOU ) ) {
Speak ( "lipsync_canihelpyou", true );
aiManager.SetTeamTimer ( team, AITEAMTIMER_ANNOUNCE_CANIHELPYOU, 5000 );
}
}
} else {
playerFocusTime = gameLocal.time;
}
} else {
playerFocusTime = gameLocal.time;
}
*/
if ( health > 0 ) {
//alive
if ( healthRegenEnabled && healthRegen ) {
if ( gameLocal.GetTime() >= healthRegenNextTime ) {
health = idMath::ClampInt( 0, maxHealth, health+healthRegen );
healthRegenNextTime = gameLocal.GetTime() + 1000;
}
}
}
//crappy place to do this, just testing
bool clearPrefix = true;
bool facingWall = false;
if ( move.fl.moving && InCoverMode() && combat.fl.aware ) {
clearPrefix = false;
if ( DistanceTo ( aasSensor->ReservedOrigin() ) < move.walkRange * 2.0f ) {
facingWall = true;
} else if ( nextWallTraceTime < gameLocal.GetTime() ) {
//do an occasional check for solid architecture directly in front of us
nextWallTraceTime = gameLocal.GetTime() + gameLocal.random.RandomInt(750)+750;
trace_t wallTrace;
idVec3 start, end;
idMat3 axis;
if ( neckJoint != INVALID_JOINT ) {
GetJointWorldTransform ( neckJoint, gameLocal.GetTime(), start, axis );
end = start + axis[0] * 32.0f;
} else {
start = GetEyePosition();
start += viewAxis[0] * 8.0f;//still inside bbox
end = start + viewAxis[0] * 32.0f;
}
//trace against solid arcitecture only, don't care about other entities
gameLocal.TracePoint ( this, wallTrace, start, end, MASK_SOLID, this );
if ( wallTrace.fraction < 1.0f ) {
facingWall = true;
} else {
clearPrefix = true;
}
}
}
if ( facingWall ) {
if ( !animPrefix.Length() ) {
animPrefix = "nearcover";
}
} else if ( clearPrefix && animPrefix == "nearcover" ) {
animPrefix = "";
}
}
/*
================
rvAITactical::Save
================
*/
void rvAITactical::Save( idSaveGame *savefile ) const {
savefile->WriteSyncId();
savefile->WriteInt ( ammo );
savefile->WriteInt ( shots );
// savefile->WriteInt ( playerFocusTime );
// savefile->WriteInt ( playerAnnoyTime );
savefile->WriteInt ( (int&)postureIdeal );
savefile->WriteInt ( (int&)postureCurrent );
savefile->WriteInt ( (int&)postureForce );
// TOSAVE: aiPostureInfo_t postureInfo[AIPOSTURE_MAX]; // cnicholson:
savefile->WriteInt ( healthRegenNextTime );
savefile->WriteInt ( maxHealth );
savefile->WriteInt ( nextWallTraceTime );
actionElbowAttack.Save ( savefile );
actionKillswitchAttack.Save ( savefile );
actionTimerPeek.Save ( savefile );
}
/*
================
rvAITactical::Restore
================
*/
void rvAITactical::Restore( idRestoreGame *savefile ) {
InitSpawnArgsVariables ( );
savefile->ReadSyncId( "rvAITactical" );
savefile->ReadInt ( ammo );
savefile->ReadInt ( shots );
// savefile->ReadInt ( playerFocusTime );
// savefile->ReadInt ( playerAnnoyTime );
savefile->ReadInt ( (int&)postureIdeal );
savefile->ReadInt ( (int&)postureCurrent );
savefile->ReadInt ( (int&)postureForce );
// TORESTORE: aiPostureInfo_t postureInfo[AIPOSTURE_MAX];
savefile->ReadInt ( healthRegenNextTime );
savefile->ReadInt ( maxHealth );
savefile->ReadInt ( nextWallTraceTime );
actionElbowAttack.Restore ( savefile );
actionKillswitchAttack.Restore ( savefile );
actionTimerPeek.Restore ( savefile );
UpdateAnimPrefix ( );
}
/*
================
rvAITactical::CanTurn
================
*/
bool rvAITactical::CanTurn ( void ) const {
if ( !move.fl.moving && !postureInfo[postureCurrent].fl.canTurn ) {
return false;
}
return idAI::CanTurn ( );
}
/*
================
rvAITactical::CanMove
================
*/
bool rvAITactical::CanMove ( void ) const {
if ( !postureInfo[postureCurrent].fl.canMove ) {
return false;
}
return idAI::CanMove ( );
}
/*
================
rvAITactical::CheckAction_Reload
================
*/
bool rvAITactical::CheckAction_Reload ( rvAIAction* action, int animNum ) {
if ( ammo == 0 ) {
return true;
}
return false;
}
/*
================
rvAITactical::CheckActions
================
*/
bool rvAITactical::CheckActions ( void ) {
// Pain?
if ( CheckPainActions ( ) ) {
return true;
}
// If we are pressed, fight-- do not break melee combat until you or the enemy is dead.
if ( IsMeleeNeeded ( )) {
if ( PerformAction ( &actionMeleeAttack, (checkAction_t)&idAI::CheckAction_MeleeAttack ) ||
PerformAction ( &actionElbowAttack, (checkAction_t)&idAI::CheckAction_LeapAttack ) ) {
return true;
}
//take no actions other than fighting
return false;
}
// Handle any posture changes
if ( postureIdeal != postureCurrent ) {
PerformAction ( "Torso_SetPosture", 4, true );
return true;
}
// Reload takes precedence
if ( !move.fl.moving && postureInfo[postureCurrent].fl.canReload && ammo == 0 ) {
PerformAction ( "Torso_Reload", 4, false );
return true;
}
if ( IsBehindCover ( ) ) {
// If we have no enemy try peeking
if ( !IsEnemyRecentlyVisible ( ) ) {
if ( aiManager.CheckTeamTimer ( team, AITEAMTIMER_ACTION_PEEK ) ) {
if ( actionTimerPeek.IsDone ( actionTime ) ) {
actionTimerPeek.Reset ( actionTime, 0.5f );
aiManager.SetTeamTimer ( team, AITEAMTIMER_ACTION_PEEK, 2000 );
PerformAction ( "Torso_Cover_Peek", 4, false );
return true;
}
}
}
// Attacks from cover
if ( postureInfo[postureCurrent].fl.canShoot && (ammo > 0 || ammo == -1) ) {
// Kill switch attack from cover?
if ( postureInfo[postureCurrent].fl.canKillswitch && IsEnemyRecentlyVisible ( ) ) {
if ( PerformAction ( &actionKillswitchAttack, NULL, &actionTimerRangedAttack ) ) {
return true;
}
}
if ( PerformAction ( &actionRangedAttack, (checkAction_t)&idAI::CheckAction_RangedAttack, &actionTimerRangedAttack ) ) {
return true;
}
}
return false;
}
// Standard attacks
if ( PerformAction ( &actionMeleeAttack, (checkAction_t)&idAI::CheckAction_MeleeAttack ) ||
PerformAction ( &actionElbowAttack, (checkAction_t)&idAI::CheckAction_LeapAttack ) ) {
return true;
}
// Ranged attack only if there is ammo
if ( postureInfo[postureCurrent].fl.canShoot && (ammo > 0 || ammo == -1) ) {
if ( PerformAction ( &actionRangedAttack, (checkAction_t)&idAI::CheckAction_RangedAttack, &actionTimerRangedAttack ) ) {
return true;
}
}
return false;
}
/*
================
rvAITactical::CheckRelaxed
Returns true if the marine should currently be in a relaxed state
================
*/
bool rvAITactical::CheckRelaxed ( void ) const {
// if ( forceRelaxed ) {
// return true;
// }
/*
// If we have a leader, no enemy, and havent had an enemy for over 5 seconds go to relaxed
if ( leader && !enemy.ent && !tether && gameLocal.time - enemy.changeTime > 5000 ) {
return true;
}
*/
// Alwasy relaxed when ignoring enemies
if ( !combat.fl.aware ) {
return true;
}
if ( enemy.ent || focusType != AIFOCUS_PLAYER || move.fl.moving || move.fl.crouching || talkState == TALK_OK ) {
return false;
}
if ( gameLocal.time >= focusTime ) {
return false;
}
return true;
}
/*
================
rvAITactical::GetIdleAnimName
================
*/
const char* rvAITactical::GetIdleAnimName ( void ) {
return "idle";
}
/*
================
rvAITactical::UpdateAnimPrefix
================
*/
void rvAITactical::UpdateAnimPrefix ( void ) {
if ( postureCurrent == AIPOSTURE_STAND ) {
animPrefix = "";
} else {
animPrefix = aiPostureString[postureCurrent];
}
}
/*
================
rvAITactical::InitPostureInfo
================
*/
void rvAITactical::InitPostureInfo ( void ) {
int posture;
for ( posture = AIPOSTURE_DEFAULT + 1; posture < AIPOSTURE_MAX; posture ++ ) {
aiPostureInfo_t& info = postureInfo[(aiPosture_t)posture];
postureCurrent = (aiPosture_t)posture;
UpdateAnimPrefix ( );
info.fl.canMove = HasAnim ( ANIMCHANNEL_TORSO, "run", true );
info.fl.canPeek = HasAnim ( ANIMCHANNEL_TORSO, "peek", true );
info.fl.canReload = HasAnim ( ANIMCHANNEL_TORSO, "reload", true );
info.fl.canShoot = HasAnim ( ANIMCHANNEL_TORSO, "range_attack", true );
info.fl.canKillswitch = HasAnim ( ANIMCHANNEL_TORSO, "killswitch", true );
info.fl.canTurn = false;
}
// FIXME: this should be based on the availablity of turn anims
postureInfo[AIPOSTURE_STAND].fl.canTurn = true;
postureInfo[AIPOSTURE_RELAXED].fl.canTurn = true;
postureInfo[AIPOSTURE_UNARMED].fl.canTurn = true;
}
/*
================
rvAITactical::UpdatePosture
================
*/
bool rvAITactical::UpdatePosture ( void ) {
// If the posture is being forced then use that until its no longer forced
if ( postureForce != AIPOSTURE_DEFAULT ) {
postureIdeal = postureForce;
// Not forcing posture, determine it from our current state
} else {
postureIdeal = AIPOSTURE_STAND;
// Behind cover?
if ( IsBehindCover ( ) ) {
bool left;
if ( enemy.ent ) {
left = (aasSensor->Reserved()->Normal().Cross ( physicsObj.GetGravityNormal ( ) ) * (enemy.lastVisibleEyePosition - physicsObj.GetOrigin())) > 0.0f;
} else if ( tether ) {
left = (aasSensor->Reserved()->Normal().Cross ( physicsObj.GetGravityNormal ( ) ) * tether->GetPhysics()->GetAxis()[0] ) > 0.0f;
} else {
left = false;
}
// Should be crouching behind cover?
if ( InCrouchCoverMode ( ) ) {
if ( (aasSensor->Reserved()->flags & FEATURE_LOOK_LEFT) && left ) {
postureIdeal = AIPOSTURE_CROUCH_COVER_LEFT;
} else if ( (aasSensor->Reserved()->flags & FEATURE_LOOK_RIGHT) && !left ) {
postureIdeal = AIPOSTURE_CROUCH_COVER_RIGHT;
} else {
postureIdeal = AIPOSTURE_CROUCH_COVER;
}
} else {
if ( (aasSensor->Reserved()->flags & FEATURE_LOOK_LEFT) && left ) {
postureIdeal = AIPOSTURE_STAND_COVER_LEFT;
} else if ( (aasSensor->Reserved()->flags & FEATURE_LOOK_RIGHT) && !left ) {
postureIdeal = AIPOSTURE_STAND_COVER_RIGHT;
} else if ( (aasSensor->Reserved()->flags & FEATURE_LOOK_LEFT) ) {
postureIdeal = AIPOSTURE_STAND_COVER_LEFT;
} else {
postureIdeal = AIPOSTURE_STAND_COVER_RIGHT;
}
}
} else if ( combat.fl.aware //aggressive
&& (FacingIdeal ( ) || CheckFOV ( currentFocusPos )) //looking in desired direction
&& ((leader && leader->IsCrouching()) || combat.fl.crouchViewClear) ) {//leader is crouching or we can crouch-look in this direction here
//we crouch only if leader is
postureIdeal = AIPOSTURE_CROUCH;
} else if ( CheckRelaxed ( ) ) {
postureIdeal = AIPOSTURE_RELAXED;
}
//never crouch in melee!
if( IsMeleeNeeded() ) {
postureIdeal = AIPOSTURE_STAND;
}
}
// Default the posture if trying to move with one that doesnt support it
if ( move.fl.moving && !postureInfo[postureIdeal].fl.canMove ) {
postureIdeal = AIPOSTURE_STAND;
// Default the posture if trying to turn and we cant in the posture we chose
} else if ( (move.moveCommand == MOVE_FACE_ENEMY || move.moveCommand == MOVE_FACE_ENTITY) && !postureInfo[postureIdeal].fl.canTurn ) {
postureIdeal = AIPOSTURE_STAND;
}
return (postureIdeal != postureCurrent);
}
/*
================
rvAITactical::OnPostureChange
================
*/
void rvAITactical::OnPostureChange ( void ) {
UpdateAnimPrefix ( );
}
/*
============
rvAITactical::OnSetKey
============
*/
void rvAITactical::OnSetKey ( const char* key, const char* value ) {
idAI::OnSetKey ( key, value );
/*
if ( !idStr::Icmp ( key, "annoyed" ) ) {
playerAnnoyTime = SEC2MS( atof ( value ) );
}
*/
}
/*
================
rvAITactical::OnStopMoving
================
*/
void rvAITactical::OnStopMoving ( aiMoveCommand_t oldMoveCommand ) {
// Ensure the peek doesnt happen immedately every time we stop at a cover
if ( IsBehindCover ( ) ){
actionTimerPeek.Clear ( actionTime );
actionTimerPeek.Add ( 2000, 0.5f );
actionKillswitchAttack.timer.Reset ( actionTime, actionKillswitchAttack.diversity );
// We should be looking fairly close to the right direction, so just snap it
TurnToward ( GetPhysics()->GetOrigin() + aasSensor->Reserved()->Normal() * 64.0f );
move.current_yaw = move.ideal_yaw;
}
idAI::OnStopMoving ( oldMoveCommand );
}
/*
================
rvAITactical::CalculateShots
================
*/
void rvAITactical::CalculateShots ( const char* fireAnim ) {
// Random number of shots ( scale by aggression range)
shots = (minShots + gameLocal.random.RandomInt(maxShots-minShots+1)) * combat.aggressiveScale;
if ( shots > ammo ) {
shots = ammo;
}
// Update the firing animation playback rate
int animNum;
animNum = GetAnim( ANIMCHANNEL_TORSO, fireAnim );
if ( animNum != 0 ) {
const idAnim* anim = GetAnimator()->GetAnim ( animNum );
if ( anim ) {
GetAnimator()->SetPlaybackRate ( animNum, ((float)anim->Length() * combat.aggressiveScale) / fireRate );
}
}
}
/*
================
rvAITactical::UseAmmo
================
*/
void rvAITactical::UseAmmo ( int amount ) {
if ( ammo <= 0 ) {
return;
}
shots--;
ammo-=amount;
if ( ammo < 0 ) {
ammo = 0;
shots = 0;
}
}
/*
================
rvAITactical::GetDebugInfo
================
*/
void rvAITactical::GetDebugInfo ( debugInfoProc_t proc, void* userData ) {
// Base class first
idAI::GetDebugInfo ( proc, userData );
proc ( "rvAITactical", "postureIdeal", aiPostureString[postureIdeal], userData );
proc ( "rvAITactical", "postureCurrent", aiPostureString[postureCurrent], userData );
proc ( "rvAITactical", "healthRegen", va("%d",healthRegen), userData );
proc ( "rvAITactical", "healthRegenEnabled",healthRegenEnabled?"true":"false", userData );
proc ( "rvAITactical", "healthRegenNextTime",va("%d",healthRegenNextTime), userData );
proc ( "rvAITactical", "maxHealth", va("%d",maxHealth), userData );
proc ( "rvAITactical", "nextWallTraceTime", va("%d",nextWallTraceTime), userData );
proc ( "idAI", "action_killswitchAttack", aiActionStatusString[actionKillswitchAttack.status], userData );
}
/*
===============================================================================
States
===============================================================================
*/
CLASS_STATES_DECLARATION ( rvAITactical )
STATE ( "Torso_RangedAttack", rvAITactical::State_Torso_RangedAttack )
STATE ( "Torso_MovingRangedAttack", rvAITactical::State_Torso_MovingRangedAttack )
STATE ( "Torso_Cover_LeanAttack", rvAITactical::State_Torso_Cover_LeanAttack )
STATE ( "Torso_Cover_LeanLeftAttack", rvAITactical::State_Torso_Cover_LeanLeftAttack )
STATE ( "Torso_Cover_LeanRightAttack", rvAITactical::State_Torso_Cover_LeanRightAttack )
STATE ( "Torso_Cover_Peek", rvAITactical::State_Torso_Cover_Peek )
STATE ( "Torso_Reload", rvAITactical::State_Torso_Reload )
STATE ( "Torso_SetPosture", rvAITactical::State_Torso_SetPosture )
STATE ( "Frame_Peek", rvAITactical::State_Frame_Peek )
END_CLASS_STATES
/*
================
rvAITactical::State_Torso_SetPosture
================
*/
stateResult_t rvAITactical::State_Torso_SetPosture ( const stateParms_t& parms ) {
enum {
STAGE_INIT,
STAGE_WAIT_RELAXED,
STAGE_WAIT
};
switch ( parms.stage ) {
case STAGE_INIT: {
idStr transAnim = va("%s_to_%s", aiPostureString[postureCurrent], aiPostureString[postureIdeal] );
if ( !HasAnim ( ANIMCHANNEL_TORSO, transAnim ) ) {
postureCurrent = postureIdeal;
OnPostureChange ( );
return SRESULT_DONE;
}
if ( postureCurrent < AIPOSTURE_STAND_COVER_LEFT
|| postureCurrent > AIPOSTURE_CROUCH_COVER_RIGHT
|| (postureIdeal != AIPOSTURE_STAND && postureIdeal != AIPOSTURE_RELAXED && postureIdeal != AIPOSTURE_CROUCH) )
{
// FIXME: TEMPORARY UNTIL ANIM IS FIXED TO NOT HAVE ORIGIN TRANSLATION
move.fl.allowAnimMove = false;
} else {
//no need to play cover-to-stand/relaxed transition if:
//scripted...
//or we're moving already...
//or turning away from our old cover direction...
if ( aifl.scripted
/*|| (move.fl.moving&&!move.fl.blocked)
|| (fabs(move.current_yaw-move.ideal_yaw) > 30.0f && (move.moveCommand == MOVE_FACE_ENEMY||move.moveCommand == MOVE_FACE_ENTITY))*/ ) {
postureCurrent = postureIdeal;
OnPostureChange ( );
return SRESULT_DONE;
}
}
DisableAnimState ( ANIMCHANNEL_LEGS );
PlayAnim ( ANIMCHANNEL_TORSO, transAnim, parms.blendFrames );
if ( postureCurrent >= AIPOSTURE_STAND_COVER_LEFT
&& postureCurrent <= AIPOSTURE_CROUCH_COVER_RIGHT
&& postureIdeal == AIPOSTURE_RELAXED ) {
//we need to also play stand_to_relaxed at the end...
return SRESULT_STAGE ( STAGE_WAIT_RELAXED );
}
return SRESULT_STAGE ( STAGE_WAIT );
}
case STAGE_WAIT_RELAXED:
if ( AnimDone ( ANIMCHANNEL_TORSO, parms.blendFrames ) ) {
if ( HasAnim ( ANIMCHANNEL_TORSO, "stand_to_relaxed" ) ) {
PlayAnim ( ANIMCHANNEL_TORSO, "stand_to_relaxed", parms.blendFrames );
}
return SRESULT_STAGE ( STAGE_WAIT );
}
return SRESULT_WAIT;
case STAGE_WAIT:
if ( AnimDone ( ANIMCHANNEL_TORSO, parms.blendFrames ) ) {
postureCurrent = postureIdeal;
OnPostureChange ( );
return SRESULT_DONE;
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
/*
================
rvAITactical::State_Torso_RangedAttack
================
*/
stateResult_t rvAITactical::State_Torso_RangedAttack ( const stateParms_t& parms ) {
enum {
STAGE_START,
STAGE_START_WAIT,
STAGE_SHOOT,
STAGE_SHOOT_WAIT,
STAGE_END,
STAGE_END_WAIT,
};
switch ( parms.stage ) {
case STAGE_START:
// If moving switch to the moving ranged attack (torso only)
if ( move.fl.moving && FacingIdeal() ) {
PostAnimState ( ANIMCHANNEL_TORSO, "Torso_MovingRangedAttack", parms.blendFrames );
return SRESULT_DONE;
}
// Full body animations
DisableAnimState ( ANIMCHANNEL_LEGS );
CalculateShots ( "range_attack" );
// Attack lead in animation?
if ( HasAnim ( ANIMCHANNEL_TORSO, "range_attack_start", true ) ) {
PlayAnim ( ANIMCHANNEL_TORSO, "range_attack_start", parms.blendFrames );
return SRESULT_STAGE ( STAGE_START_WAIT );
}
return SRESULT_STAGE ( STAGE_SHOOT );
case STAGE_START_WAIT:
// When the pre shooting animation is done head over to shooting
if ( AnimDone ( ANIMCHANNEL_TORSO, 0 ) ) {
return SRESULT_STAGE ( STAGE_SHOOT );
}
return SRESULT_WAIT;
case STAGE_SHOOT:
PlayAnim ( ANIMCHANNEL_TORSO, "range_attack", 0 );
UseAmmo ( 1 );
return SRESULT_STAGE ( STAGE_SHOOT_WAIT );
case STAGE_SHOOT_WAIT:
// When the shoot animation is done either play another shot animation
// or finish up with post_shooting
if ( AnimDone ( ANIMCHANNEL_TORSO, 0 ) ) {
// If our enemy is no longer in our fov we can stop shooting
if ( !enemy.fl.inFov ) {
return SRESULT_STAGE ( STAGE_END );
} else if ( enemy.fl.dead ) {
//if enemy is dead, stop shooting soon
if ( shots > 5 ) {
shots = gameLocal.random.RandomInt(6);
}
}
if ( shots <= 0 ) {
return SRESULT_STAGE ( STAGE_END );
}
return SRESULT_STAGE ( STAGE_SHOOT);
}
return SRESULT_WAIT;
case STAGE_END:
// Attack lead in animation?
if ( HasAnim ( ANIMCHANNEL_TORSO, "range_attack_end", true ) ) {
PlayAnim ( ANIMCHANNEL_TORSO, "range_attack_end", parms.blendFrames );
return SRESULT_STAGE ( STAGE_END_WAIT );
}
return SRESULT_DONE;
case STAGE_END_WAIT:
if ( AnimDone ( ANIMCHANNEL_TORSO, parms.blendFrames ) ) {
return SRESULT_DONE;
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
/*
================
rvAITactical::State_Torso_MovingRangedAttack
================
*/
stateResult_t rvAITactical::State_Torso_MovingRangedAttack ( const stateParms_t& parms ) {
enum {
STAGE_INIT,
STAGE_SHOOT,
STAGE_SHOOT_WAIT,
};
switch ( parms.stage ) {
case STAGE_INIT:
CalculateShots ( "range_attack_torso" );
return SRESULT_STAGE ( STAGE_SHOOT );
case STAGE_SHOOT:
UseAmmo ( 1 );
PlayAnim ( ANIMCHANNEL_TORSO, "range_attack_torso", 0 );
return SRESULT_STAGE ( STAGE_SHOOT_WAIT );
case STAGE_SHOOT_WAIT:
// When the shoot animation is done either play another shot animation
// or finish up with post_shooting
if ( AnimDone ( ANIMCHANNEL_TORSO, 0 ) ) {
if ( enemy.fl.dead ) {
//if enemy is dead, stop shooting soon
if ( shots > 5 ) {
shots = gameLocal.random.RandomInt(6);
}
}
if ( shots <= 0 || !enemy.fl.inFov ) {
return SRESULT_DONE;
}
return SRESULT_STAGE ( STAGE_SHOOT);
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
/*
================
rvAITactical::State_Torso_Reload
================
*/
stateResult_t rvAITactical::State_Torso_Reload ( const stateParms_t& parms ) {
enum {
STAGE_INIT,
STAGE_WAIT,
};
switch ( parms.stage ) {
case STAGE_INIT:
DisableAnimState ( ANIMCHANNEL_LEGS );
PlayAnim ( ANIMCHANNEL_TORSO, "reload", parms.blendFrames );
return SRESULT_STAGE ( STAGE_WAIT );
case STAGE_WAIT:
if ( AnimDone ( ANIMCHANNEL_TORSO, 2 ) ) {
ammo = spawnArgs.GetInt ( "ammo" );
return SRESULT_DONE;
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
/*
================
rvAITactical::State_Torso_Cover_LeanLeftAttack
================
*/
stateResult_t rvAITactical::State_Torso_Cover_LeanLeftAttack ( const stateParms_t& parms ) {
PostAnimState ( ANIMCHANNEL_TORSO, "Torso_RangedAttack", parms.blendFrames );
return SRESULT_DONE;
}
/*
================
rvAITactical::State_Torso_Cover_LeanRightAttack
================
*/
stateResult_t rvAITactical::State_Torso_Cover_LeanRightAttack ( const stateParms_t& parms ) {
PostAnimState ( ANIMCHANNEL_TORSO, "Torso_RangedAttack", parms.blendFrames );
return SRESULT_DONE;
}
/*
================
rvAITactical::State_Torso_Cover_LeanAttack
================
*/
stateResult_t rvAITactical::State_Torso_Cover_LeanAttack ( const stateParms_t& parms ) {
enum {
STAGE_OUT,
STAGE_OUTWAIT,
STAGE_FIRE,
STAGE_FIREWAIT,
STAGE_IN,
STAGE_INWAIT,
};
switch ( parms.stage ) {
case STAGE_OUT:
DisableAnimState ( ANIMCHANNEL_LEGS );
// The lean out animation cannot blend with any other animations since
// it is essential that the movement delta out match the one back in. Therefore
// we force the legs and torso to be stoped before playing any animations
torsoAnim.StopAnim ( 0 );
legsAnim.StopAnim ( 0 );
PlayAnim ( ANIMCHANNEL_TORSO, "lean_out", 0 );
return SRESULT_STAGE ( STAGE_OUTWAIT );
case STAGE_OUTWAIT:
if ( AnimDone ( ANIMCHANNEL_TORSO, 0 ) ) {
// Random number of shots
CalculateShots ( "lean_attack" );
return SRESULT_STAGE ( STAGE_FIRE );
}
return SRESULT_WAIT;
case STAGE_FIRE:
UseAmmo ( 1 );
PlayAnim ( ANIMCHANNEL_TORSO, "lean_attack", 0 );
return SRESULT_STAGE ( STAGE_FIREWAIT );
case STAGE_FIREWAIT:
if ( AnimDone ( ANIMCHANNEL_TORSO, 0 ) ) {
if ( enemy.fl.dead ) {
//if enemy is dead, stop shooting soon
if ( shots > 5 ) {
shots = gameLocal.random.RandomInt(6);
}
}
if ( shots > 0 ) {
return SRESULT_STAGE ( STAGE_FIRE );
}
return SRESULT_STAGE ( STAGE_IN );
}
return SRESULT_WAIT;
case STAGE_IN:
PlayAnim ( ANIMCHANNEL_TORSO, "lean_in", 0 );
return SRESULT_STAGE ( STAGE_INWAIT );
case STAGE_INWAIT:
if ( AnimDone ( ANIMCHANNEL_TORSO, 0 ) ) {
return SRESULT_DONE;
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
/*
================
rvAITactical::State_Torso_Cover_Peek
================
*/
stateResult_t rvAITactical::State_Torso_Cover_Peek ( const stateParms_t& parms ) {
enum {
STAGE_INIT,
STAGE_WAIT,
};
switch ( parms.stage ) {
case STAGE_INIT:
DisableAnimState ( ANIMCHANNEL_LEGS );
if ( !PlayAnim ( ANIMCHANNEL_TORSO, "peek", parms.blendFrames ) ) {
return SRESULT_DONE;
}
return SRESULT_STAGE ( STAGE_WAIT );
case STAGE_WAIT:
if ( AnimDone ( ANIMCHANNEL_TORSO, parms.blendFrames ) ) {
return SRESULT_DONE;
}
return SRESULT_WAIT;
}
return SRESULT_ERROR;
}
/*
================
rvAITactical::State_Frame_Peek
================
*/
stateResult_t rvAITactical::State_Frame_Peek ( const stateParms_t& parms ) {
CheckForEnemy ( true, true );
return SRESULT_OK;
}
/*
================
rvAITactical::Event_ForcePosture
================
*/
void rvAITactical::Event_ForcePosture ( int posture ) {
postureForce = (aiPosture_t)posture;
}
/*
===================
rvAITactical::IsCrouching
===================
*/
bool rvAITactical::IsCrouching( void ) const {
if ( postureCurrent == AIPOSTURE_CROUCH
|| postureCurrent == AIPOSTURE_CROUCH_COVER
|| postureCurrent == AIPOSTURE_CROUCH_COVER_LEFT
|| postureCurrent == AIPOSTURE_CROUCH_COVER_RIGHT ) {
return true;
}
return idAI::IsCrouching();
}
/*
================
rvAITactical::Event_PostSpawn
================
*/
void rvAITactical::Event_PostSpawn( void ) {
idAI::Event_PostSpawn();
if ( team == AITEAM_MARINE && healthRegenEnabled )
{//regen-enabled buddy marine
if ( CheckDeathCausesMissionFailure() )
{//who is important to a mission
if ( g_skill.GetInteger() > 2 )
{//on impossible
health *= 1.5f;
healthRegen *= 1.5f;
}
else if ( g_skill.GetInteger() > 1 )
{//on hard
health *= 1.2f;
healthRegen *= 1.25f;
}
}
}
}
|
#include "stdafx.h"
#include "QsoTime.h"
#include "Qso.h"
QsoTime::QsoTime(Qso* qso)
:
QsoItem(qso),
m_minutes(0)
{
}
QsoTime::~QsoTime()
{
}
bool QsoTime::ProcessToken(const string& token, Qso* qso)
{
QsoItem::ProcessToken(token, qso);
// the time is a string "hhmm"
// parse the string and calculate the number of minutes as hh*60 + mm
string t = token;
if (t.length() != 4)
{
const char* pmsg = t.empty() ? "<empty>" : t.c_str();
printf("Error: QsoTime - bad string %s\n", pmsg);
return false;
}
string h = t.substr(0, 2);
int hours = atoi(h.c_str());
string m = t.substr(2, 2);
int min = atoi(m.c_str());
m_minutes = hours * 60 + min;
return true;
}
// Copy the data for the qso item
void QsoTime::Copy(const QsoItem* source)
{
if (source == nullptr)
return;
QsoItem::Copy(source);
const QsoTime* time = dynamic_cast<const QsoTime*>(source);
if (time != nullptr)
{
m_minutes = time->m_minutes;
}
}
void QsoTime::Copy(const QsoItem& source)
{
QsoItem::Copy(source);
const QsoTime* time = dynamic_cast<const QsoTime*>(&source);
if (time != nullptr)
{
m_minutes = time->m_minutes;
}
}
|
//
// Created by Yujing Shen on 28/05/2017.
//
#ifndef TENSORGRAPH_TENSORGRAPH_H
#define TENSORGRAPH_TENSORGRAPH_H
#include <vector>
#include <map>
#include <set>
#include <string>
#include <ctime>
#include <cstdlib>
#include <utility>
#include <fstream>
#include <type_traits>
#include <cmath>
#include <iostream>
#ifndef Dtype
#define Dtype float
#endif // Dtype
#ifndef SAFEDELETE
#define SAFEDELETE(_) if(_){delete _, _ = NULL;}
#endif
#ifndef SAFEDELETES
#define SAFEDELETES(_) if(_){delete [] _, _ = NULL;}
#endif
#ifndef SET_RAND
#define SET_RAND srand(time(NULL))
#endif
namespace sjtu{
using std::vector;
using std::map;
using std::string;
using std::srand;
using std::time;
using std::rand;
using std::set;
using std::pair;
using std::make_pair;
using std::tuple;
using std::make_tuple;
using std::fstream;
using std::ifstream;
using std::ofstream;
using std::is_base_of;
using std::exp;
using std::tanh;
using std::cout;
using std::endl;
const int RANDOM = 0;
const int ZERO = 1;
const int MINI_RANDOM = 2;
const int SAME = 3;
const int VALID = 4;
class SessionTensor;
class SessionNode;
struct SessionEdge;
class SessionOptimizer;
class Session;
class Graph;
typedef SessionTensor* Tensor;
typedef SessionNode* Node;
typedef SessionEdge* Edge;
typedef SessionOptimizer* Optimizer;
typedef vector<int> Shape;
}
#include "Exception.h"
#include "SessionTensor.h"
#include "SessionEdge.h"
#include "SessionNode.h"
#include "SessionOptimizer.h"
#include "Graph.h"
#include "Session.h"
#endif //TENSORGRAPH_TENSORGRAPH_H
|
#define _USE_MATH_DEFINES
#include <opencv2/highgui.hpp>
#include <opencv2/imgcodecs.hpp>
#include <algorithm>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
#include "color.hpp"
#include "histo.hpp"
#include "intensity.hpp"
using namespace std;
using namespace cv;
void img_cat( std::vector<std::tuple<cv::Mat, string>> ImgArr )
{
int a = 20;
for ( auto it : ImgArr )
{
cv::namedWindow( std::get<1>( it ), cv::WINDOW_AUTOSIZE );
cv::moveWindow( std::get<1>( it ), a, 20 );
cv::imshow( std::get<1>( it ), std::get<0>( it ) );
a += 50;
}
if( ImgArr.size() != 0 )
{
cv::waitKey( 0 );
cv::destroyAllWindows();
}
return;
}
void img_save( std::vector<std::tuple<cv::Mat, string>> ImgArr,
const string savepath, const string postfix,
const std::vector<int>& params = std::vector< int >() )
{
for ( auto it : ImgArr )
{
cv::imwrite( savepath + std::get<1>( it ) + postfix, std::get<0>( it ),
params );
}
}
int main( int argv, char** argc )
{
const string inputPath = "./srcImg/";
const string arrowFile = "RGB-color-cube.tif";
const string savepath = "./dstImg/";
std::vector<std::tuple<cv::Mat, string>> ImgArr;
Mat originalImg = cv::imread( inputPath + arrowFile );
if ( originalImg.empty() )
{
cout << "image load failed!" << endl;
return -1;
}
cv::Mat TransformedImg, MiddleImg, AbcImg;
cv::Mat MiddleImgArr[3];
img_cat( ImgArr );
img_save( ImgArr, savepath, ".tif" );
return 0;
}
////////////////// color_cube ////////////////////
// MiddleImg = ColorTransform( originalImg, BGR2HSI );
// ImgArr.push_back( std::make_tuple( originalImg, "color_cube_orig" ) );
//
// cv::split( MiddleImg, MiddleImgArr );
//
// ImgArr.push_back( std::make_tuple( MiddleImgArr[0], "color_cube_H" ) );
// ImgArr.push_back( std::make_tuple( MiddleImgArr[1], "color_cube_S" ) );
// ImgArr.push_back( std::make_tuple( MiddleImgArr[2], "color_cube_I" ) );
//
// TransformedImg = ColorTransform( MiddleImg, HSI2BGR );
// ImgArr.push_back( std::make_tuple( TransformedImg, "color_cube_reconst" ) );
//////////////////////////////////////////////////
// cout << "Histogram calculation\n";
// cout << "ColorChannel count : " << originalImg.channels()
// << "\n" << endl;
//
// auto histo = histogram(originalImg);
// cout << "Original Histogram\n";
// for(int i = 0; i < 255; i++)
// {
// cout << histo[i] << ", ";
// }
// cout << histo[255] << endl;
//
// auto histo_trans = histogram(TransformedImg);
// cout << "Transfromed Histogram\n";
// for(int i = 0; i < 255; i++)
// {
// cout << histo_trans[i] << ", ";
// }
// cout << histo_trans[255] << endl;
|
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define rep1(i, n) for(int i = 1; i <= (int)(n); i++)
#define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;}
#define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;}
typedef long long ll;
typedef pair<int, int> P;
ll gcd(int x, int y){ return y?gcd(y, x%y):x;}
ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);}
#define N_MAX 1010
int main()
{
ll n, m;
cin >> n >> m;
vector<ll> p;
p.push_back(0);
rep(i, n) {int tmp; cin >> tmp; p.push_back(tmp);}
vector<ll> p2;
rep(i, n+1)rep(j, n+1) p2.push_back(p[i]+p[j]);
sort(p2.begin(), p2.end(), greater<ll>());
ll ans = 0;
rep(i, (n+1)*(n+1)){
int ab = p2[i];
int diff = m - ab;
if (diff < 0) continue;
auto itr = lower_bound(p2.begin(), p2.end(), diff, greater<ll>());
ans = max(*itr + ab, ans);
}
cout << ans << endl;
}
/*
一見dpっぽいが多分解けない。
dp[i] = i番目の数字を表現して、あと使える数字の最大数
だとO(mn)かかるはず。
4回固定という点に着目
2回の合計を全列挙しても10^6(正確には1001 * 1001)
全列挙数列p2をソートして、
全列挙数列p2を最初から見ていき、m-p2[i]をキーとして全列挙数列p2の降順lower_boundを取る
帰ってきた値と、p2[i]との和が、p2[i]を使った条件下での最大値
*/
|
#pragma once
#include <iberbar/Lua/LuaBase.h>
namespace iberbar
{
class __iberbarLuaApi__ CLuaTable
{
public:
CLuaTable( lua_State* L, int idx );
//~CLuaTable();
public:
bool IsTable();
lua_Integer GetInteger_KeyStr( const char* key );
lua_Number GetNumber_KeyStr( const char* key );
const char* GetString_KeyStr( const char* key );
CLuaTable GetTable_KeyStr( const char* key );
lua_Integer GetInteger_KeyInt( int key );
lua_Number GetNumber_KeyInt( int key );
const char* GetString_KeyInt( int key );
CLuaTable GetTable_KeyInt( int key );
void SetNil_KeyStr( const char* key );
void SetBoolean_KeyStr( const char* key, bool value );
void SetInteger_KeyStr( const char* key, lua_Integer value );
void SetNumber_KeyStr( const char* key, lua_Number value );
void SetString_KeyStr( const char* key, const char* value );
void SetTable_KeyStr( const char* key );
void SetNil_KeyInt( lua_Integer key );
void SetBoolean_KeyInt( lua_Integer key, bool value );
void SetInteger_KeyInt( lua_Integer key, lua_Integer value );
void SetNumber_KeyInt( lua_Integer key, lua_Number value );
void SetString_KeyInt( lua_Integer key, const char* value );
void SetTable_KeyInt( lua_Integer key );
lua_State* GetLuaState() { return m_pLuaState; }
int GetIdx() { return m_idx; };
private:
lua_State* m_pLuaState;
int m_idx;
};
}
inline iberbar::CLuaTable::CLuaTable( lua_State* L, int idx )
: m_pLuaState( L )
, m_idx( idx )
{
}
inline bool iberbar::CLuaTable::IsTable()
{
return lua_istable( m_pLuaState, m_idx );
}
inline lua_Integer iberbar::CLuaTable::GetInteger_KeyStr( const char* key )
{
lua_pushstring( m_pLuaState, key );
lua_gettable( m_pLuaState, m_idx );
lua_Integer value = lua_tointeger( m_pLuaState, -1 );
lua_pop( m_pLuaState, 1 );
return value;
}
inline lua_Number iberbar::CLuaTable::GetNumber_KeyStr( const char* key )
{
lua_pushstring( m_pLuaState, key );
lua_gettable( m_pLuaState, m_idx );
lua_Number value = lua_tonumber( m_pLuaState, -1 );
lua_pop( m_pLuaState, 1 );
return value;
}
inline const char* iberbar::CLuaTable::GetString_KeyStr( const char* key )
{
lua_pushstring( m_pLuaState, key );
lua_gettable( m_pLuaState, m_idx );
const char* value = lua_tostring( m_pLuaState, -1 );
lua_pop( m_pLuaState, 1 );
return value;
}
inline iberbar::CLuaTable iberbar::CLuaTable::GetTable_KeyStr( const char* key )
{
lua_pushstring( m_pLuaState, key );
lua_gettable( m_pLuaState, m_idx );
// 这里不调用lua_pop弹出
return CLuaTable( m_pLuaState, lua_gettop( m_pLuaState ) );
}
inline lua_Integer iberbar::CLuaTable::GetInteger_KeyInt( int key )
{
lua_pushinteger( m_pLuaState, key );
lua_gettable( m_pLuaState, m_idx );
lua_Integer value = lua_tointeger( m_pLuaState, -1 );
lua_pop( m_pLuaState, 1 );
return value;
}
inline lua_Number iberbar::CLuaTable::GetNumber_KeyInt( int key )
{
lua_pushinteger( m_pLuaState, key );
lua_gettable( m_pLuaState, m_idx );
lua_Number value = lua_tonumber( m_pLuaState, -1 );
lua_pop( m_pLuaState, 1 );
return value;
}
inline const char* iberbar::CLuaTable::GetString_KeyInt( int key )
{
lua_pushinteger( m_pLuaState, key );
lua_gettable( m_pLuaState, m_idx );
const char* value = lua_tostring( m_pLuaState, -1 );
lua_pop( m_pLuaState, 1 );
return value;
}
inline iberbar::CLuaTable iberbar::CLuaTable::GetTable_KeyInt( int key )
{
lua_pushinteger( m_pLuaState, key );
lua_gettable( m_pLuaState, m_idx );
// 这里不调用lua_pop弹出
return CLuaTable( m_pLuaState, lua_gettop( m_pLuaState ) );
}
inline void iberbar::CLuaTable::SetNil_KeyStr( const char* key )
{
lua_pushstring( m_pLuaState, key );
lua_pushnil( m_pLuaState );
lua_settable( m_pLuaState, m_idx );
}
inline void iberbar::CLuaTable::SetBoolean_KeyStr( const char* key, bool value )
{
lua_pushstring( m_pLuaState, key );
lua_pushboolean( m_pLuaState, value == true ? 1 : 0 );
lua_settable( m_pLuaState, m_idx );
}
inline void iberbar::CLuaTable::SetInteger_KeyStr( const char* key, lua_Integer value )
{
lua_pushstring( m_pLuaState, key );
lua_pushinteger( m_pLuaState, value );
lua_settable( m_pLuaState, m_idx );
}
inline void iberbar::CLuaTable::SetNumber_KeyStr( const char* key, lua_Number value )
{
lua_pushstring( m_pLuaState, key );
lua_pushnumber( m_pLuaState, value );
lua_settable( m_pLuaState, m_idx );
}
inline void iberbar::CLuaTable::SetString_KeyStr( const char* key, const char* value )
{
lua_pushstring( m_pLuaState, key );
lua_pushstring( m_pLuaState, value );
lua_settable( m_pLuaState, m_idx );
}
inline void iberbar::CLuaTable::SetTable_KeyStr( const char* key )
{
lua_pushstring( m_pLuaState, key );
lua_newtable( m_pLuaState );
lua_settable( m_pLuaState, m_idx );
}
inline void iberbar::CLuaTable::SetNil_KeyInt( lua_Integer key )
{
lua_pushinteger( m_pLuaState, key );
lua_pushnil( m_pLuaState );
lua_settable( m_pLuaState, m_idx );
}
inline void iberbar::CLuaTable::SetBoolean_KeyInt( lua_Integer key, bool value )
{
lua_pushinteger( m_pLuaState, key );
lua_pushboolean( m_pLuaState, value == true ? 1 : 0 );
lua_settable( m_pLuaState, m_idx );
}
inline void iberbar::CLuaTable::SetInteger_KeyInt( lua_Integer key, lua_Integer value )
{
lua_pushinteger( m_pLuaState, key );
lua_pushinteger( m_pLuaState, value );
lua_settable( m_pLuaState, m_idx );
}
inline void iberbar::CLuaTable::SetNumber_KeyInt( lua_Integer key, lua_Number value )
{
lua_pushinteger( m_pLuaState, key );
lua_pushnumber( m_pLuaState, value );
lua_settable( m_pLuaState, m_idx );
}
inline void iberbar::CLuaTable::SetString_KeyInt( lua_Integer key, const char* value )
{
lua_pushinteger( m_pLuaState, key );
lua_pushstring( m_pLuaState, value );
lua_settable( m_pLuaState, m_idx );
}
inline void iberbar::CLuaTable::SetTable_KeyInt( lua_Integer key )
{
lua_pushinteger( m_pLuaState, key );
lua_newtable( m_pLuaState );
lua_settable( m_pLuaState, m_idx );
}
|
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
//
// Copyright (C) 2006 Opera Software AS. All rights reserved.
//
// This file is part of the Opera web browser. It may not be distributed
// under any circumstances.
//
// Adam Minchinton, Huib Kleinhout
//
#ifndef __DESKTOP_SPEEDDIAL_H__
#define __DESKTOP_SPEEDDIAL_H__
#ifdef SUPPORT_SPEED_DIAL
#include "modules/hardcore/timer/optimer.h"
#include "adjunct/quick/extensions/ExtensionUIListener.h"
#include "adjunct/quick/speeddial/SpeedDialData.h"
#include "adjunct/quick/speeddial/SpeedDialListener.h"
#include "modules/thumbnails/thumbnailmanager.h"
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// DesktopSpeedDial is a class to hold and manipulate the Speed Dial information for a single speed dial
// across all of the speed dial pages
//
//
class DesktopSpeedDial
: public SpeedDialData
, public OpTimerListener
, public ThumbnailManagerListener
, public ExtensionDataListener
{
public:
DesktopSpeedDial();
virtual ~DesktopSpeedDial();
virtual OP_STATUS SetTitle(const OpStringC& title, BOOL custom);
virtual OP_STATUS SetURL(const OpStringC& url);
virtual OP_STATUS SetDisplayURL(const OpStringC& display_url);
virtual OP_STATUS Set(const SpeedDialData& original, bool retain_uid = false);
void SetReload(const ReloadPolicy policy, const int timeout = 0, const BOOL only_if_expired = FALSE);
// Readds the thumbnail ref after a Purge of the Thumbnail Manager
void ReAddThumnailRef();
// Starting and Stopping of loading of a speeddial's thumbnail
OP_STATUS StartLoadingSpeedDial(BOOL reload, INT32 width, INT32 height) const;
OP_STATUS StopLoadingSpeedDial() const;
// GetLoading function
BOOL GetLoading() const { return m_is_loading; }
BOOL GetReloading() const { return m_is_reloading; }
void SetExpired() { NotifySpeedDialExpired(); }
void Zoom() { NotifySpeedDialZoomRequest(); }
void OnPositionChanged() { NotifySpeedDialUIChanged(); }
/** Hook called when the dial has been added to the Speed Dial set. */
void OnAdded();
/** Hook called when the dial is being removed from the Speed Dial set. */
void OnRemoving();
/** Hook called when speed dial manager is being destroyed, before speed dials are saved to disk. */
void OnShutDown();
// OpTimerListener
void OnTimeOut(OpTimer* timer);
OP_STATUS AddListener(SpeedDialEntryListener& listener) const { return m_listeners.Add(&listener); }
OP_STATUS RemoveListener(SpeedDialEntryListener& listener) const { return m_listeners.Remove(&listener); }
OP_STATUS LoadL(PrefsFile& file, const OpStringC8& section_name);
void SaveL(PrefsFile& file, const OpStringC8& section_name) const;
bool HasInternalExtensionURL() const;
// ThumbnailManagerListener
virtual void OnThumbnailRequestStarted(const URL &document_url, BOOL reload);
virtual void OnThumbnailReady(const URL &document_url, const Image &thumbnail, const uni_char *title, long preview_refresh);
virtual void OnThumbnailFailed(const URL &document_url, OpLoadingListener::LoadingFinishStatus status);
virtual void OnInvalidateThumbnails() {}
// ExtensionDataListener
virtual void OnExtensionDataUpdated(const OpStringC& title, const OpStringC& url);
private:
void NotifySpeedDialDataChanged();
void NotifySpeedDialUIChanged();
void NotifySpeedDialExpired();
void NotifySpeedDialZoomRequest();
// Functions to setup and start/stop timers
void StartReloadTimer(int timeout, BOOL only_if_expired);
void RestartReloadTimer(const URL &document_url);
void StopReloadTimer();
void StartDataNotificationTimer(UINT32 timeout_in_ms);
void StopDataNotificationTimer();
// Function to make sure that the ThumbnailManagerListeners are only called for the correct url's
BOOL IsMatchingCall(const URL &document_url);
// Be careful if accessing these directly as they depend on each other
// Use of the timer functions is recommended
OpTimer *m_reload_timer; // Timer to control the reload (NULL when there is no auto reload)
OpTimer m_data_notification_timer; // timer for delayed OnSpeedDialDataChanged notification
bool m_data_notification_timer_running; // true if there are pending OnSpeedDialDataChanged notifications
bool m_extension_data_updated; // true if extension data was updated at least once in this session
double m_last_data_notification; // time of last OnSpeedDialDataChanged notification (runtime milliseconds)
static const UINT32 EXTENSION_UPDATE_INTERVAL = 10 * 60 * 1000; // time in miliseconds between two notifications about
// update of extension data
static const UINT32 EXTENSION_UPDATE_NO_DELAY_PERIOD = 1000; // period of time after OnSpeedDialDataChanged notification
// when new notifications are sent without delay (time in ms)
// The following are mutable so that Start/StopLoading() can be const.
// Starting and stopping the loading does not affect speed dial data.
// Flag to say if the speed dial is currently loading
mutable BOOL m_is_loading;
mutable BOOL m_is_reloading;
// Set to TRUE if all speed dials are closed and a "reload every" timer goes off
mutable BOOL m_need_reload;
// mutable so that Add/RemoveListener() can be const. Starting and stopping
// listening to changes does not affect speed dial data.
mutable OpListeners<SpeedDialEntryListener> m_listeners;
};
#endif // SUPPORT_SPEED_DIAL
#endif // __DESKTOP_SPEEDDIAL_H__
|
/**
* @file Card.cpp
* @author Jan Zarsky (xzarsk03@stud.fit.vutbr.cz)
* Andrei Paplauski (xpapla00@stud.fit.vutbr.cz)
* @brief Implementation of class Card
*/
#include "Card.hpp"
#include <iostream>
namespace solitaire
{
/**
Construct card
@param cs Card suit
@param value Value of card
*/
card::card(cardsuit cs,unsigned value):suit(cs),value(value)
{
if (value < 1 || value > K) {
std::cerr << "Wrong card inicialization: value" << std::endl;
exit(-1);
}
if (cs < CLUBS || cs > SPADES) {
std::cerr << "Wrong card inicialization: cardsuit" << std::endl;
exit(-1);
}
}
/**
Getter for suit of card
@return Card's suit
*/
cardsuit card::getSuit() {
return this->suit;
}
/**
Getter for value of card
@return Card's value
*/
unsigned card::getValue() {
return this->value;
}
card::~card()
{
}
}
|
#ifndef RECTANGLE_HPP
#define RECTANGLE_HPP
class Rectangle {
private:
int width;
int height;
public:
Rectangle();
Rectangle(int w,int h);
void set_width(int w);
void set_height(int h);
int area();
int perimeter();
int get_w(){
return width;
}
int get_h(){
return height;
}
};
#endif // RECTANGLE_HPP
|
//
// Edge.cpp
// TEST
//
// Created by ruby on 2017. 10. 13..
// Copyright © 2017년 ruby. All rights reserved.
//
#include "Edge.hpp"
void Edge::add_mousse(string mousse){
for (int i = 0; i < 3; i++) {
if (this->mousse[i] == "") {
this->mousse[i] = mousse;
break;
}
}
}
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
ll dp[6101][6101][2];
int main()
{
ll t;
cin>>t;
while(t--){
string a;
cin>>a;
memset(dp,1,sizeof(dp));
ll n = a.length();
ll left=-1,right=-1;
ll max = 1;
for(ll gap=1;gap<=n;gap++){
for(j=gap,i=1;j<=n;i++,j++){
if(i==j) {
dp[i][j][0] = 1;
dp[i][j][1] = 1;
continue;
}
if(a[i-1]==a[j-1]){
if(dp[i+1][j-1][1]) {
dp[i][j][0] = dp[i+1][j-1][0] + 2;
dp[i][j][1]=1;
if(dp[i][j][0]>max)
left = i;
right =j;
}
else
{
dp[i][j][1] = 0;
dp[i][j][0] = max(dp[i+1][j][0],dp[i][j-1][0]);
}
}
else{
dp[i][j][1] = 0;
dp[i][j][0] = max(dp[i+1][j][0],dp[i][j-1][0]);
}
}
}
}
}
|
//
// ButtonWithSprite.h
// Zengine
//
// Created by zhusu on 15/1/27.
//
//
#ifndef __Zengine__ButtonWithSprite__
#define __Zengine__ButtonWithSprite__
#include "cocos2d.h"
USING_NS_CC;
class ButtonWithSprite : public CCSprite
{
public:
static ButtonWithSprite* create(int id, const char* name,float scaleX,float scaleY);
virtual bool init(int id, const char* name,float scaleX,float scaleY);
static ButtonWithSprite* create(int id, const char* name);
virtual void draw();
ButtonWithSprite();
virtual ~ButtonWithSprite();
CC_SYNTHESIZE(int, _id, ID);
CC_SYNTHESIZE(float, _pressScale, PressScale);
CC_SYNTHESIZE(float, _buttonScaleX, ButtonScaleX);
CC_SYNTHESIZE(float, _buttonScaleY, ButtonScaleY);
CC_SYNTHESIZE(CCSize, _add, Add);
virtual bool touchesBegan(CCSet * touchs,CCEvent * event);
virtual bool touchesMoved(CCSet * touchs,CCEvent * event);
virtual bool touchesCancelled(CCSet * touchs,CCEvent * event);
virtual bool touchesEnded(CCSet * touchs,CCEvent * event);
virtual bool toucheBegan(CCTouch *pTouch,CCEvent * event);
virtual bool toucheMoved(CCTouch *pTouch,CCEvent * event);
virtual bool toucheCancelled(CCTouch *pTouch,CCEvent * event);
virtual bool toucheEnded(CCTouch *pTouch,CCEvent * event);
bool toucheBeganAction(CCPoint pos);
bool toucheMovedAction(CCPoint pos);
bool toucheCancelledAction(CCPoint pos);
bool toucheEndedAction(CCPoint pos);
void end();
CCRect getBodyRect() ;
};
#endif /* defined(__Zengine__ButtonWithSprite__) */
|
/***************************************************************************
* Copyright (C) 2009 by Dario Freddi *
* drf@chakra-project.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 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#include "Maintenance.h"
#include "Backend.h"
#include <QDebug>
#include <QtDBus/QDBusInterface>
#include <QtDBus/QDBusReply>
#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusConnectionInterface>
namespace Aqpm
{
class Maintenance::Private
{
public:
Private(Maintenance *parent) : q(parent) {}
Maintenance *q;
void __k__workerResult(bool result);
};
class MaintenanceHelper
{
public:
MaintenanceHelper() : q(0) {}
~MaintenanceHelper() {
delete q;
}
Maintenance *q;
};
Q_GLOBAL_STATIC(MaintenanceHelper, s_globalMaintenance)
Maintenance *Maintenance::instance()
{
if (!s_globalMaintenance()->q) {
new Maintenance;
}
return s_globalMaintenance()->q;
}
Maintenance::Maintenance()
: QObject(0)
, d(new Private(this))
{
Q_ASSERT(!s_globalMaintenance()->q);
s_globalMaintenance()->q = this;
}
Maintenance::~Maintenance()
{
delete d;
}
void Maintenance::performAction(Action type)
{
if (type == RemoveUnusedPackages) {
return;
}
QDBusMessage message;
message = QDBusMessage::createMethodCall("org.chakraproject.aqpmworker",
"/Worker",
"org.chakraproject.aqpmworker",
QLatin1String("isWorkerReady"));
QDBusMessage reply = QDBusConnection::systemBus().call(message);
if (reply.type() == QDBusMessage::ReplyMessage
&& reply.arguments().size() == 1) {
qDebug() << reply.arguments().first().toBool();
} else if (reply.type() == QDBusMessage::MethodCallMessage) {
qWarning() << "Message did not receive a reply (timeout by message bus)";
d->__k__workerResult(false);
return;
}
QDBusConnection::systemBus().connect("org.chakraproject.aqpmworker", "/Worker", "org.chakraproject.aqpmworker",
"workerResult", this, SLOT(__k__workerResult(bool)));
QDBusConnection::systemBus().connect("org.chakraproject.aqpmworker", "/Worker", "org.chakraproject.aqpmworker",
"messageStreamed", this, SIGNAL(actionOutput(QString)));
message = QDBusMessage::createMethodCall("org.chakraproject.aqpmworker",
"/Worker",
"org.chakraproject.aqpmworker",
QLatin1String("performMaintenance"));
message << (int)type;
QDBusConnection::systemBus().call(message, QDBus::NoBlock);
}
void Maintenance::Private::__k__workerResult(bool result)
{
QDBusConnection::systemBus().disconnect("org.chakraproject.aqpmworker", "/Worker", "org.chakraproject.aqpmworker",
"workerResult", q, SLOT(__k__workerResult(bool)));
emit q->actionPerformed(result);
}
}
#include "Maintenance.moc"
|
//------------------------------------------------------------------------------
// create ref colorplanes with yuv and pseudorgb
// 2016-06-25 11:04:03 parik
//------------------------------------------------------------------------------
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
#include <sstream>
#include <cassert>
#include <chrono>
typedef unsigned char pix_t;
struct yuv_t {
pix_t y, u, v;
};
struct rgb_t {
pix_t r, g, b;
void operator=(const yuv_t& yuv) {
int y = yuv.y;
int u = yuv.u - 128;
int v = yuv.v - 128;
//int u = yuv.u;
//int v = yuv.v;
int ri = (int)( y + 1.4075 * v);
int gi = (int)( y - 0.3455 * u - 0.7169 * v);
int bi = (int)( y + 1.779 * u);
// clamp to [0,255] to avoid distortion
if (ri > 255) ri=255;
else if (ri < 0) ri=0;
if (gi > 255) gi=255;
else if (gi <0) gi=0;
if (bi > 255) bi=255;
else if (bi < 0) bi=0;
r = (pix_t)ri;
g = (pix_t)gi;
b = (pix_t)bi;
//std::cout << "\t "
// << (int)yuv.y << " " << (int)yuv.u << " " << (int)yuv.v << " -> "
// << (int)r << " " << (int)g << " " << (int)b << std::endl;
}
};
bool parseArgs (int argc, char **argv, std::string& fnme,
int& width, int& height)
{
if (argc != 4) {
std::cout << "Usage: yuvplane out.ppm width height\n"
<< "\tGenerate a yuv color plane for given dims\n"
<< std::endl;
return false;
}
fnme = argv [1];
width = std::atoi (argv [2]);
height = std::atoi (argv [3]);
return true;
}
bool saveYuv2Ppm (const std::string& fnme, yuv_t *p_frame, int width, int height)
{
std::ofstream ofs (fnme. c_str ());
if (!ofs) {
std::cout << "Failed to write file " << fnme << std::endl;
return false;
}
ofs << "P6\n" << width << " " << height << "\n255\n";
for (int h=0; h<height; ++h) {
for (int w=0; w<width; ++w) {
rgb_t rgb;
rgb = p_frame [h*width + w];
ofs << rgb.r << rgb.g << rgb.b;
}
}
ofs.close ();
return true;
}
bool saveRgb2Ppm (const std::string& fnme, rgb_t *p_frame, int width, int height)
{
std::ofstream ofs (fnme. c_str ());
if (!ofs) {
std::cout << "Failed to write file " << fnme << std::endl;
return false;
}
ofs << "P6\n" << width << " " << height << "\n255\n";
for (int h=0; h<height; ++h) {
for (int w=0; w<width; ++w) {
rgb_t rgb;
rgb = p_frame [h*width + w];
ofs << rgb.r << rgb.g << rgb.b;
}
}
ofs.close ();
return true;
}
// use floats
void genYuvPlane (std::string ppmFnme, int width, int height)
{
int nPixels = width * height;
yuv_t *p_frame = new yuv_t [nPixels];
unsigned char y = 16;
for (int r=0; r < height; ++r) {
for (int c=0; c < width; ++c) {
yuv_t yuv;
yuv.y = y;
//yuv.u = 128 + (r - height/2) * (256.0/height);
//yuv.v = 128 + (c - width/2) * (256.0/width);
float r1 = r * 1.0 / (height -1); // range 0 to 1.0
float c1 = c * 1.0 / (width -1); // range 0 to 1.0
yuv.u = (pix_t)(255 * r1); // 0 to 255
yuv.v = (pix_t)(255 * c1); // 0 to 255
//r1 = r1 - 0.5; // -0.5 to +0.5
//c1 = c1 - 0.5;
//yuv.u = (pix_t)(255.0 + 255.0 * r1); // -0.5 =>
//yuv.v = (pix_t)(255.0 + 255.0 * c1); // 0 to 255
//yuv.u = (pix_t) (256.0 - (127.0 * r)/(height-1));
//yuv.v = (pix_t) (256.0 - (127.0 * c)/(width-1));
p_frame [r * width + c] = yuv;
//std::cout << r << " " << c << " yuv: " << (int)yuv.y << " "
// << (int)yuv.u << " " << (int)yuv.v << std::endl;
}
}
saveYuv2Ppm (ppmFnme, p_frame, width, height);
delete [] p_frame;
}
// use fixed point math`
void genYuvPlaneFixed (std::string ppmFnme, int width, int height)
{
int nPixels = width * height;
yuv_t *p_frame = new yuv_t [nPixels];
unsigned char y = 16;
for (int r=0; r < height; ++r) {
for (int c=0; c < width; ++c) {
yuv_t yuv;
yuv.y = y;
yuv.u = (pix_t)(255 * r / (height -1)); // 0 to 255
yuv.v = (pix_t)(255 * c / (width -1)); // 0 to 255
p_frame [r * width + c] = yuv;
//std::cout << r << " " << c << " yuv: " << (int)yuv.y << " "
// << (int)yuv.u << " " << (int)yuv.v << std::endl;
}
}
saveYuv2Ppm (ppmFnme, p_frame, width, height);
delete [] p_frame;
}
// directly create a rgb plane
void genRgbPlanePseudo (std::string ppmFnme, int width, int height)
{
int nPixels = width * height;
rgb_t *p_frame = new rgb_t [nPixels];
for (int r=0; r < height; ++r) {
for (int c=0; c < width; ++c) {
rgb_t rgb;
int y = (int)(r * 255.0/height);
int x = (int)(c * 255.0/width);
if (x > 127) {
if (y < 128) {
// 1 quad
rgb.r = x - 127 + (127-y)/2;
rgb.g = (127 - y)/2;
//rgb.g = 0;
rgb.b = 0;
} else {
// 4 quad
rgb.r = x - 127;
rgb.g = 0;
rgb.b = y - 127;
}
} else {
if (y < 128) {
// 2 quad
rgb.r = (127 - y)/2;
//rgb.r = 0;
rgb.g = 127 - x + (127-y)/2;
rgb.b = 0;
} else {
// 3 quad
rgb.r = 0;
rgb.g = 128 - x;
rgb.b = y - 127;
}
}
p_frame [r*width + c] = rgb;
}
}
saveRgb2Ppm (ppmFnme, p_frame, width, height);
delete [] p_frame;
}
// wrapper to call fn and time it
void timer ( void (*fn)(std::string, int, int), std::string ppmFnme, int width, int height) {
auto begin = std::chrono::steady_clock::now();
fn (ppmFnme, width, height);
auto end = std::chrono::steady_clock::now();
std::cout << "Time for " << ppmFnme << " "
<< std::chrono::duration_cast<std::chrono::microseconds> (end - begin). count ()
<< "us" << std::endl;
}
int main (int argc, char **argv)
{
std::string ppmFnme;
int width, height;
if (!parseArgs (argc, argv, ppmFnme, width, height)) {
return 1;
}
timer (&genYuvPlane, ppmFnme+"_def_timer.ppm", width, height);
timer (&genYuvPlane, ppmFnme+"_def_timer.ppm", width, height);
timer (&genYuvPlaneFixed, ppmFnme+"_p_timer.ppm", width, height);
timer (&genRgbPlanePseudo, ppmFnme+"_rgb_timer.ppm", width, height);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2009 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#ifndef VEGAD3D10WINDOW_H
#define VEGAD3D10WINDOW_H
#ifdef VEGA_BACKEND_DIRECT3D10
#include "modules/libvega/vega3ddevice.h"
class VEGAD3d10FramebufferObject;
class VEGAD3d10Texture;
class VEGA3dBuffer;
class VEGA3dVertexLayout;
class FontFlushListener;
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
#include <d2d1.h>
#endif
class VEGAD3d10Window : public VEGA3dWindow
{
public:
VEGAD3d10Window(VEGAWindow* w, ID3D10Device1* dev, IDXGIFactory* dxgi
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
, ID2D1Factory* d2dFactory, D2D1_FEATURE_LEVEL flevel, D2D1_TEXT_ANTIALIAS_MODE textMode
#endif
);
~VEGAD3d10Window();
OP_STATUS Construct();
virtual void present(const OpRect* updateRects, unsigned int numRects);
virtual unsigned int getWidth(){return m_width;}
virtual unsigned int getHeight(){return m_height;}
virtual OP_STATUS resizeBackbuffer(unsigned int width, unsigned int height);
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
ID2D1RenderTarget* getD2DRenderTarget(FontFlushListener* fontFlushListener);
#ifdef VEGA_NATIVE_FONT_SUPPORT
virtual void flushFonts();
#endif
#endif // VEGA_BACKEND_D2D_INTEROPERABILITY
ID3D10Texture2D* getRTTexture(){return m_rtResource;}
ID3D10RenderTargetView* getRTView(){return m_rtView;}
virtual void* getBackbufferHandle();
virtual void releaseBackbufferHandle(void* handle);
virtual OP_STATUS readBackbuffer(VEGAPixelStore*);
protected:
void destroyResources();
VEGAWindow* m_nativeWin;
unsigned int m_width;
unsigned int m_height;
ID3D10Device1* m_d3dDevice;
IDXGIFactory* m_dxgiFactory;
IDXGISwapChain* m_swapChain;
IDXGISurface1* m_dxgiSurface;
ID3D10Texture2D* m_rtResource;
ID3D10Texture2D* m_bufferResource;
ID3D10RenderTargetView* m_rtView;
#ifdef VEGA_BACKEND_D2D_INTEROPERABILITY
ID2D1Factory* m_d2dFactory;
D2D1_FEATURE_LEVEL m_d2dFLevel;
ID2D1RenderTarget* m_d2dRenderTarget;
ID2D1Layer* m_d2dLayer; ///< dummy object, used to avoid recreating the d3d device on resize
bool m_isDrawingD2D;
D2D1_TEXT_ANTIALIAS_MODE m_textMode;
FontFlushListener* m_fontFlushListener;
#endif // VEGA_BACKEND_D2D_INTEROPERABILITY
};
#endif // VEGA_BACKEND_DIRECT3D10
#endif // !VEGAD3D10WINDOW_H
|
#include <cstdlib>
#include <cmath>
#include "trm/subs.h"
#include "trm/constants.h"
#include "trm/binary.h"
/**
* kepler_omega computes the Keplerian angular velocity a distance \b r
* from a point mass of mass \b m.
* \param m mass of object (solar masses)
* \param r distance from object (solar radii)
* \return Angular velocity in radians per second.
*/
double Binary::kepler_omega(double m, double r){
return(sqrt(Constants::G*Constants::MSUN*m/(Constants::RSUN*r))/(Constants::RSUN*r));
}
|
//car.h
class Car {
private:
int _speed, _direction;
public:
Car();
Car(int speed, int direction);
~Car();
};
|
#pragma once
#if !defined ( __Tile_H__ )
#define __Tile_H__
#include "Common.h"
#include "DxTexture.h"
class Tile
{
public:
enum TileState
{
occupied,
blocked,
empty,
trapped,
occupiedTrap,
};
public:
Tile ();
~Tile ();
bool init ();
int x () { return myXPos; }
int y () { return myYPos; }
void setXPos ( int x );
void setYPos ( int y );
bool canPassThrough ( int allegiance );
bool isEmpty () { return myState == empty; }
bool isOccupied () { return ( myState == occupied || myState == occupiedTrap ); }
bool isBlocked () { return myState == blocked; }
bool isTrapped () { return ( myState == trapped || myState == occupiedTrap ); }
void setTrap ( int trapLevel );
bool isAccessible(int allegiance);
void removeTrap ();
void setState ( TileState state, int allegiance = -1 );
TileState getState () { return myState; }
DxTexture& texture () { return *mySprite; }
D3DCOLOR color ();
void toggleSelected ( bool on );
void toggleShowRange ( bool on );
void setColor ( D3DCOLOR color );
void setRangeColor ( D3DCOLOR color );
static bool loadTileImages ( DxTexture& emptyTile, DxTexture& filledTile );
private:
int myXPos, myYPos;
TileState myState;
int myTrapLevel; // equal to zero if not trapped
int occupiedAllegiance; // value of team number that has a unit on this tile. Zero if no unit is on tile.
DxTexture* mySprite;
D3DCOLOR myColor;
D3DCOLOR rangeColor;
bool selected;
bool showRange;
// tile images
static DxTexture ourEmptyTile;
static DxTexture ourFilledTile;
// prevent copying
private:
Tile ( const Tile& other );
Tile& operator= ( const Tile& other );
};
#endif
|
#include <stdio.h>
#include <stdlib.h>
main ()
{
/*Esta com erro de lógica */
float nota1, nota2, media;
printf ("Informe a primeira nota: ");
scanf ("%f",¬a1);
printf ("Informe a segunda nota: ");
scanf ("%f",¬a2);
media = (nota1 + nota2)/2;
printf ("Média igual a: %f\n",media);
if (media >= 6)
{
printf ("APROVADO\n");
}
else
{
if (media >= 3)
{
printf ("EXAME\n");
}
else
{
printf ("REPROVADO\n");
}
}
system ("pause");
}
|
#include "Button.h"
#include <UIFactory.h>
using namespace uth;
using namespace pmath;
Button::Button(const ButtonCallback& callback)
:Component("clickButton")
,m_Type(ButtonType::Click)
{
}
Button::Button(ButtonType type, const ButtonCallback& callback)
: Component("generalButton")
, m_Type(type)
, m_callback(callback)
{
}
void Button::Init()
{
}
void Button::Draw(uth::RenderTarget& target)
{
}
void Button::Update(float delta)
{
const auto& type = uthInput.Common.Event();
const auto& wnd = uthEngine.GetWindow();
const auto area = parent->transform.GetLocalBounds();
const bool wasPressed = m_isPressed;
#if defined(UTH_SYSTEM_WINDOWS)
const auto pos = wnd.PixelToCoords(uthInput.Mouse.Position());
if (type == InputEvent::STATIONARY)
{
if (area.contains(pos) && !m_isPressed)
{
if (m_Type == ButtonType::Click)
{
m_isPressed = true;
}
else if (m_Type == ButtonType::Toggle)
{
m_isPressed = true;
}
}
}
else if (type == InputEvent::CLICK)
{
if (area.contains(pos) && m_isPressed)
{
if (m_Type == ButtonType::Click)
{
m_isPressed = false;
}
else if (m_Type == ButtonType::Toggle)
{
if (m_isToggled)
{
m_isToggled = false;
m_isPressed = false;
}
else if (m_isPressed)
{
m_isToggled = true;
}
}
if (m_callback != nullptr)
{
m_callback(*parent);
}
}
else
{
m_isPressed = m_isToggled;
}
}
/**
else if (type == InputEvent::NONE)
{
m_isPressed = false;
}
/**/
#elif defined(UTH_SYSTEM_ANDROID)
const auto pos = wnd.PixelToCoords(uthInput.touch[0].Position());
if (type == InputEvent::STATIONARY)
{
if (area.contains(pos) && !m_isPressed)
{
if (m_Type == ButtonType::Click)
{
m_isPressed = true;
}
else if (m_Type == ButtonType::Toggle)
{
m_isPressed = true;
}
}
}
else if (type == InputEvent::CLICK)
{
if (area.contains(pos) && m_isPressed)
{
if (m_Type == ButtonType::Click)
{
m_isPressed = false;
}
else if (m_Type == ButtonType::Toggle)
{
if (m_isToggled)
{
m_isToggled = false;
m_isPressed = false;
}
else if (m_isPressed)
{
m_isToggled = true;
}
}
if (m_callback != nullptr)
{
m_callback(*parent);
}
}
else
{
m_isPressed = m_isToggled;
}
}
#endif
if (wasPressed != m_isPressed)
{
Sprite& sprite = *parent->GetComponent<Sprite>();
if (m_isPressed)
{
sprite.SetColor(0.75f, 0.75f, 0.75f, 1.0f);
}
else
{
sprite.SetColor(1.0f, 1.0f, 1.0f, 1.0f);
}
}
}
void Button::updateColor()
{
Sprite& sprite = *parent->GetComponent<Sprite>();
if (m_isPressed)
{
sprite.SetColor(0.75f, 0.75f, 0.75f, 1.0f);
}
else
{
sprite.SetColor(1.0f, 1.0f, 1.0f, 1.0f);
}
}
bool Button::isPressed() const
{
return m_isPressed;
}
void Button::reset()
{
m_isPressed = false;
m_isToggled = false;
updateColor();
}
|
#ifndef DESIGNPATTERN_OBSERVER_OBSERVER_H
#define DESIGNPATTERN_OBSERVER_OBSERVER_H
#include "iobserver.h"
#include <iostream>
namespace DesignPatter
{
class Observer : public IObserver
{
public:
virtual bool Update(const std::string& data)
{
std::cout << "Update: " << data << std::endl;
return true;
}
};
} // DesignPatter
#endif // DESIGNPATTERN_OBSERVER_OBSERVER_H
|
//Lecture 9 supplementary program
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main() {
//example 1
/*
short unsigned int i = 0; // short only uses 2 bytes instead of 4, unsigned means the value cannot be negative.
cout << i-- << endl; // outputs 0 since it is still a post decrement
cout << i << endl; //outputs 65535 the max value of the 2 bytes it can use to represent. The variable is represented by two's complement but cannot be negative so it becomes max value.
cout << ++i << endl; // returns the value to 0 since it has overflowed back to 0;
*/
//relational Operators
//when using multiple character comparators ensure there is no space between them (>= not > =)
if (5 > 0) {
cout << "Greater than" << endl; // wil print
}
if (5 < 0) {
cout << "Less than" << endl; // will not print
}
if (5 >= 0) {
cout << "Greater than or equal" << endl; // will print
}
if (5 <= 0) {
cout << "Less than or equal" << endl; // will not print
}
if (5 == 0) {
cout << "Exactly equal" << endl; // will not print
}
if (5 != 0) {
cout << "Not equal" << endl; // will print
}
if (5 > 0 && 5 != 0) {
cout << "And" << endl; // will print
}
if (5 > 0 || 5 == 0) {
cout << "OR" << endl; // will print
}
else {
cout << "Always check your comparators to be what you want" << endl;
}
cout << " \n \n" << endl;
//logic statements
int mark;
cout << "Enter your mark: " << endl; // gets integer mark from user
cin >> mark;
if (mark > 90) { // checks if the mark entered is above 90% and returns A+ if it is and not A+ if it isn't.
cout << "Your grade is A+." << endl;
}
else {
cout << "Your grade is not A+" << endl;
}
if (mark >= 80 && mark < 90) { // Checks if the mark is within the range from 80% to 89% and returns the appropriate letter grade.
cout << "Your grade is B+" << endl;
}
// using seperate if statements for checking the same condition can result in multiple outputs. Use else if or switch statements for multiple checks of the same condition
if (mark > 90) { // checks for grades over 90
cout << "A+" << endl;
}
else if (mark > 80) { // checks for grades over 80 but since we already filtered out grades over 90 this will only catch 81-90
cout << "B+" << endl;
}
else { // for any other values it outputs a standard statement
cout << "C or less" << endl;
}
//since these statements are linked under the umbrella of a single if statement it will only output one branch of the if statement.
//If statements can be nested for more complex evaluations
int temp;
cout << "Enter the temperature: " << endl;
cin >> temp;
if (temp > 20) { // checks if it is warm
if (temp > 40) { // checks if it is too warm
cout << "Turn on AC" << endl;
}
else { // catches temperature over 40
cout << "Go for a swim" << endl;
}
}
else { // catches if the temp is below 20
cout << "Stay home, too cold to swim" << endl;
}
//only one of the three output conditions will be met so only a single output will be given for each time through this check.
system("pause");
return 0;
}
|
/*************************************************************************
> File Name: mytime3.h
> Author: JY.ZH
> Mail: xw2016@mail.ustc.edu.cn
> Created Time: 2018年07月19日 星期四 20时48分19秒
************************************************************************/
#ifndef MYTIME3_H_
#define MYTIME3_H_
#include <iostream>
class Time
{
private:
int hours;
int minutes;
public:
Time();
Time(int h, int m = 0);
void AddMin(int m);
void AddHr(int h);
void Reset(int h = 0, int m = 0);
Time operator+(const Time & t) const;
Time operator-(const Time & t) const;
Time operator*(double n) const;
friend Time operator*(double m, const Time & t)
{return t * m;} // 用友元函数来逆转参数顺序
friend std::ostream & operator<<(std::ostream & os, const Time & t);
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-file-style: "stroustrup" -*-
*
* 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 INPUTMANAGER_MODULE_H
#define INPUTMANAGER_MODULE_H
class OpInputManager;
class InputmanagerModule
: public OperaModule
{
public:
InputmanagerModule()
: m_input_manager(NULL)
{ }
virtual void InitL(const OperaInitInfo &info);
virtual void Destroy();
OpInputManager* m_input_manager;
#ifndef HAS_COMPLEX_GLOBALS
private:
/* Duplicate OpInputAction's enum here to avoid having to include
* all of inputaction.h */
#include "modules/hardcore/actions/generated_actions_enum.h"
public:
const char* s_action_strings[LAST_ACTION + 1];
#endif // HAS_COMPLEX_GLOBALS
};
#ifndef HAS_COMPLEX_GLOBALS
#define s_action_strings g_opera->inputmanager_module.s_action_strings
#endif // HAS_COMPLEX_GLOBALS
#define INPUTMANAGER_MODULE_REQUIRED
#endif // INPUTMANAGER_CAPABILITIES_H
|
#ifndef RENDERAREA_H
#define RENDERAREA_H
#include <QWidget>
#include <QColor>
// default code on creation of the project
class RenderArea : public QWidget
{
Q_OBJECT
public:
// all our shapes from our gui
enum ShapeType {Ark, Polygon, Cross, Name, Ellipse, Square, Rectangle};
// default code on creation of the project
explicit RenderArea(QWidget *parent = nullptr);
// added these to make window size stable
QSize minimumSizeHint() const Q_DECL_OVERRIDE;
QSize sizeHint() const Q_DECL_OVERRIDE;
// set background color using INLINE and a SETTER
void setBackgroundColor (QColor color) {myBackgroundColor = color;} // Setter
QColor backgroundColor () const { return myBackgroundColor;} // getter
void setShape (ShapeType shape) {myShape = shape;} // setter
ShapeType shape () const { return myShape; } // getter
protected:
void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE;
signals:
public slots:
private:
//added these to change background
QColor myBackgroundColor;
QColor myShapeColor;
ShapeType myShape;
};
#endif // RENDERAREA_H
|
#ifndef AFX_VIEWING_H_
#define AFX_VIEWING_H_
#include <stdio.h>
class View
{
class Vec3 // structure for eye, vat, vup
{
public:
double ptr[3];
void set(double *v)
{
for (size_t i = 0; i<3; i++)
ptr[i] = v[i];
}
double* add(double* v, double mul)
{
double result[3];
for (size_t i = 0; i<3; i++)
result[i] = ptr[i] + v[i] * mul;
return result;
}
double* cross(double* v)
{
double result[3];
result[0] = ptr[1] * v[2] - ptr[2] * v[1];
result[1] = ptr[2] * v[0] - ptr[0] * v[2];
result[2] = ptr[0] * v[1] - ptr[1] * v[0];
return result;
}
inline double& operator[](size_t index)
{
return ptr[index];
}
};
public:
Vec3 eye_, vat_, vup_;
double fovy_;
double dnear_;
double dfar_;
int x_, y_;
size_t width_, height_;
View();
View(const char* viewFile);
~View();
void loadView(const char* viewFile);
};
#endif
|
//
// Created by OLD MAN on 2020/1/7.
//
//小蒜给了你一个整数,要求从个位开始分离出它的每一位数字。
//
//输入格式\
//输入一个整数,整数在 1 到 10^8 之间。
//
//输出格式\
//从个位开始按照从低位到高位的顺序依次输出每一位数字。数字之间以一个空格分开。
#include <iostream>
using namespace std;
int main(){
long a;
cin>>a;
while (a > 0){
cout<<a % 10<<" ";
a = a / 10;
}
}
|
#pragma once
#include<iostream>
using namespace std;
class MacAddress {
private:
char address[17];
public:
MacAddress();
MacAddress(const char*);
const char* getAddress()const;
bool operator<(const MacAddress&) const;
bool operator==(const MacAddress&) const;
bool operator>(const MacAddress&) const;
};
class Smartphone {
private:
char model[128];
char brand[256];
char owner[256];
size_t year;
size_t memory;
MacAddress address;
public:
Smartphone();
Smartphone(const char*, const char*, const char*, size_t, size_t, MacAddress);
void setModel(const char*);
void setBrand(const char*);
void setOwner(const char*);
void setYear(size_t);
void setMemory(size_t);
void setAddress(MacAddress);
const char* getModel()const;
const char* getBrand()const;
const char* getOwner()const;
size_t getMemory()const;
size_t getYear()const;
const MacAddress& getAddress()const;
void print() const;
};
class Router {
private:
Smartphone* phones;
size_t size;
size_t capacity;
void copy(const Router&);
void erase();
void resize();
void popAt(size_t index);
public:
Router();
Router(const Router&);
Router& operator=(const Router&);
~Router();
void addPhone(const Smartphone&);
void removePhone(MacAddress);
void sort();
Router& operator+=(const Router&);
Router& operator +=(const Smartphone&);
Router operator+(const Smartphone&) const;
void print()const;
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2009 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 SVG_SUPPORT
#include "modules/svg/src/animation/svganimationvalue.h"
#include "modules/svg/src/animation/svganimationvaluecontext.h"
#include "modules/svg/src/SVGFontSize.h"
#include "modules/svg/src/SVGPoint.h"
#include "modules/svg/src/SVGRect.h"
#include "modules/svg/src/SVGVector.h"
#include "modules/svg/src/OpBpath.h"
#include "modules/svg/src/SVGTransform.h"
#include "modules/svg/src/SVGMatrix.h"
#include "modules/svg/src/SVGValue.h"
#include "modules/svg/src/SVGUtils.h"
#include "modules/svg/src/AttrValueStore.h"
#include "modules/svg/src/SVGDocumentContext.h"
#include "modules/pi/OpScreenInfo.h"
#include "modules/layout/cascade.h"
#include "modules/layout/box/box.h"
#include "modules/layout/content/content.h"
#include "modules/layout/layout_workplace.h"
SVGAnimationValueContext::SVGAnimationValueContext() :
element(NULL),
location(NULL),
parent_props(NULL),
props(NULL),
font_height(0.0f),
ex_height(0.0f),
root_font_height(0.0f),
current_color(0x0),
viewport_width(0.0f),
viewport_height(0.0f),
containing_block_width(0),
containing_block_height(0),
percentage_of(0),
inherit_rgb_color(0x0),
resolved_props(0),
resolved_viewport(0),
resolved_percentage(0),
resolved_paint_inheritance(0) {}
SVGAnimationValueContext::~SVGAnimationValueContext()
{
prop_list.Clear();
}
void
SVGAnimationValueContext::ResolveProps()
{
SVGDocumentContext *element_doc_ctx = AttrValueStore::GetSVGDocumentContext(element);
OP_ASSERT(element_doc_ctx);
TempPresentationValues tmp_pres_values(FALSE);
// The cascade is done in the document of the element to animate,
// which must not be the same document as of the animation
// workplace. In the external-use use-case, the situation is
// exactly like that.
HLDocProfile* element_hld_profile = element_doc_ctx->GetHLDocProfile();
LayoutProperties* layout_props = LayoutProperties::CreateCascade(element,
prop_list,
LAYOUT_WORKPLACE(element_hld_profile));
if (layout_props)
{
const HTMLayoutProperties& parent_props = *layout_props->Pred()->GetProps();
const SvgProperties *svg_props = parent_props.svg;
font_height = (svg_props != NULL) ?
svg_props->fontsize.GetFloatValue() : LayoutFixedToFloat(parent_props.decimal_font_size);
if (element_hld_profile)
root_font_height = LayoutFixedToFloat(element_hld_profile->GetLayoutWorkplace()->GetDocRootProperties().GetRootFontSize());
ex_height = SVGUtils::GetExHeight(element_doc_ctx->GetVisualDevice(), SVGNumber(font_height), parent_props.font_number).GetFloatValue();
this->parent_props = &parent_props;
const HTMLayoutProperties& props = *layout_props->GetProps();
current_color = props.font_color;
this->props = &props;
}
layout_props = NULL;
resolved_props = 1;
}
void
SVGAnimationValueContext::ResolveViewport()
{
SVGDocumentContext *element_doc_ctx = AttrValueStore::GetSVGDocumentContext(element);
OP_ASSERT(element_doc_ctx);
SVGNumberPair viewport;
// If this fails, we'll be on thin ice, so make do with what we have
OpStatus::Ignore(SVGUtils::GetViewportForElement(element,
element_doc_ctx,
viewport, NULL, NULL));
viewport_width = viewport.x.GetFloatValue();
viewport_height = viewport.y.GetFloatValue();
HTML_Element* svg_root = element_doc_ctx->GetSVGRoot();
// FIXME: Viewport for things within <animation>
if (Box *box = svg_root->GetLayoutBox())
{
BOOL is_positioned = box->IsPositionedBox();
BOOL is_fixed = box->IsFixedPositionedBox();
if (HTML_Element* containing_element = Box::GetContainingElement(svg_root, is_positioned, is_fixed))
{
if (Box *parent_box = containing_element->GetLayoutBox())
{
if (Content *content = parent_box->GetContent())
{
containing_block_width = content->GetWidth();
containing_block_height = content->GetHeight();
}
}
}
}
resolved_viewport = 1;
}
void
SVGAnimationValueContext::ResolvePercentageOf()
{
if (!resolved_viewport)
ResolveViewport();
// Set default
percentage_of = 0.0f;
NS_Type ns = location->is_special ? NS_SPECIAL : g_ns_manager->GetNsTypeAt(element->ResolveNsIdx(location->ns_idx));
SVGLength::LengthOrientation orientation = SVGUtils::GetLengthOrientation(location->animated_name, ns);
if (orientation == SVGLength::SVGLENGTH_X)
{
percentage_of = viewport_width;
}
else if (orientation == SVGLength::SVGLENGTH_Y)
{
percentage_of = viewport_height;
}
else
{
float cw = viewport_width / 100.0f;
float ch = viewport_height / 100.0f;
percentage_of = (float)op_sqrt(cw*cw + ch*ch) / 1.414214f;
}
// We override percentage_of on the outermost svg element to mean
// the dimensions of the containing block (as computed by layout)
if (element->IsMatchingType(Markup::SVGE_SVG, NS_SVG) &&
element == SVGUtils::GetTopmostSVGRoot(element) &&
ns == NS_SVG)
{
if (location->animated_name == Markup::SVGA_WIDTH)
{
percentage_of = (float)containing_block_width;
}
else if (location->animated_name == Markup::SVGA_HEIGHT)
{
percentage_of = (float)containing_block_height;
}
}
resolved_percentage = 1;
}
void
SVGAnimationValueContext::ResolvePaintInheritance()
{
AssertProps();
NS_Type ns = location->is_special ? NS_SPECIAL : g_ns_manager->GetNsTypeAt(element->ResolveNsIdx(location->ns_idx));
// Support for inherit when animating fill and stroke.
if (parent_props && ns == NS_SVG && parent_props->svg)
{
const SvgProperties *svg_props = parent_props->svg;
if (location->animated_name == Markup::SVGA_STROKE)
{
const SVGPaint *parent_paint = svg_props->GetStroke();
if (parent_paint && parent_paint->GetPaintType() == SVGPaint::RGBCOLOR)
{
inherit_rgb_color = parent_paint->GetRGBColor();
}
}
else if (location->animated_name == Markup::SVGA_FILL)
{
const SVGPaint *parent_paint = svg_props->GetFill();
if (parent_paint && parent_paint->GetPaintType() == SVGPaint::RGBCOLOR)
{
inherit_rgb_color = parent_paint->GetRGBColor();
}
}
}
resolved_paint_inheritance = 1;
}
/* static */ OP_STATUS
SVGAnimationValue::Interpolate(SVGAnimationValueContext &context,
SVG_ANIMATION_INTERVAL_POSITION interval_position,
const SVGAnimationValue &from_value,
const SVGAnimationValue &to_value,
ExtraOperation extra_operation,
SVGAnimationValue &animation_value)
{
if (from_value.value_type != to_value.value_type &&
from_value.value_type != VALUE_EMPTY)
{
return OpStatus::ERR_NOT_SUPPORTED;
}
switch(to_value.value_type)
{
case VALUE_NUMBER:
case VALUE_PERCENTAGE:
{
animation_value.value_type = to_value.value_type;
float a = (from_value.value_type == VALUE_EMPTY) ? 0.0f : from_value.value.number;
float b = to_value.value.number;
if (extra_operation == EXTRA_OPERATION_TREAT_TO_AS_BY)
{
b += a;
}
animation_value.value.number = a + (b - a) * interval_position;
return Transfer(animation_value);
}
break;
case VALUE_COLOR:
{
UINT32 from_color = (from_value.value_type == VALUE_EMPTY) ? 0x0 : from_value.value.color;
animation_value.value.color = InterpolateColors(interval_position,
from_color,
to_value.value.color,
extra_operation);
return Transfer(animation_value);
}
break;
case VALUE_EMPTY:
{
if (from_value.reference_type == REFERENCE_SVG_POINT &&
to_value.reference_type == REFERENCE_SVG_POINT &&
animation_value.reference_type == REFERENCE_SVG_POINT)
{
InterpolateSVGPoints(interval_position,
from_value.reference.svg_point,
to_value.reference.svg_point,
extra_operation,
animation_value.reference.svg_point);
return OpStatus::OK;
}
else if (from_value.reference_type == REFERENCE_SVG_RECT &&
to_value.reference_type == REFERENCE_SVG_RECT &&
animation_value.reference_type == REFERENCE_SVG_RECT)
{
InterpolateSVGRects(interval_position,
from_value.reference.svg_rect,
to_value.reference.svg_rect,
extra_operation,
animation_value.reference.svg_rect);
return OpStatus::OK;
}
else if (from_value.reference_type == REFERENCE_SVG_VECTOR &&
to_value.reference_type == REFERENCE_SVG_VECTOR &&
animation_value.reference_type == REFERENCE_SVG_VECTOR)
{
return InterpolateSVGVectors(context, interval_position,
from_value.reference.svg_vector,
to_value.reference.svg_vector,
extra_operation,
animation_value.reference.svg_vector);
}
else if (from_value.reference_type == REFERENCE_SVG_OPBPATH &&
to_value.reference_type == REFERENCE_SVG_OPBPATH &&
animation_value.reference_type == REFERENCE_SVG_OPBPATH)
{
return InterpolateSVGOpBpaths(interval_position,
from_value.reference.svg_path,
to_value.reference.svg_path,
extra_operation,
animation_value.reference.svg_path);
}
else if (from_value.reference_type == REFERENCE_SVG_TRANSFORM &&
to_value.reference_type == REFERENCE_SVG_TRANSFORM &&
animation_value.reference_type == REFERENCE_SVG_TRANSFORM)
{
return InterpolateSVGTransforms(interval_position,
*from_value.reference.svg_transform,
*to_value.reference.svg_transform,
extra_operation,
*animation_value.reference.svg_transform);
}
else if (from_value.reference_type == REFERENCE_SVG_VECTOR &&
to_value.reference_type == REFERENCE_SVG_TRANSFORM &&
animation_value.reference_type == REFERENCE_SVG_TRANSFORM)
{
SVGTransform from_transform;
from_value.reference.svg_vector->GetTransform(from_transform);
return InterpolateSVGTransforms(interval_position,
from_transform,
*to_value.reference.svg_transform,
extra_operation,
*animation_value.reference.svg_transform);
}
else if (to_value.reference_type == REFERENCE_SVG_TRANSFORM &&
animation_value.reference_type == REFERENCE_SVG_TRANSFORM)
{
SVGTransform from_transform;
return InterpolateSVGTransforms(interval_position,
from_transform,
*to_value.reference.svg_transform,
extra_operation,
*animation_value.reference.svg_transform);
}
}
}
return OpStatus::ERR_NOT_SUPPORTED;
}
/* static */ OP_STATUS
SVGAnimationValue::AddBasevalue(const SVGAnimationValue &base_value,
SVGAnimationValue &animation_value)
{
if ((base_value.value_type == VALUE_NUMBER &&
animation_value.value_type == VALUE_NUMBER) ||
(base_value.value_type == VALUE_PERCENTAGE &&
animation_value.value_type == VALUE_PERCENTAGE))
{
animation_value.value.number += base_value.value.number;
RETURN_IF_ERROR(Transfer(animation_value));
}
else if (base_value.value_type == VALUE_COLOR && animation_value.value_type == VALUE_COLOR)
{
animation_value.value.color = AddBasevalueColor(base_value.value.color,
animation_value.value.color);
RETURN_IF_ERROR(Transfer(animation_value));
}
else if (base_value.reference_type == REFERENCE_SVG_TRANSFORM &&
animation_value.reference_type == REFERENCE_SVG_TRANSFORM)
{
SVGMatrix product_matrix;
animation_value.reference.svg_transform->GetMatrix(product_matrix);
SVGMatrix factor_matrix;
base_value.reference.svg_transform->GetMatrix(factor_matrix);
product_matrix.Multiply(factor_matrix);
animation_value.reference.svg_transform->SetMatrix(product_matrix);
}
return OpStatus::OK;
}
/* static */ OP_STATUS
SVGAnimationValue::AddAccumulationValue(const SVGAnimationValue &accumulation_value,
const SVGAnimationValue &accumulation_value_base,
SVG_ANIMATION_INTERVAL_REPETITION repetition,
SVGAnimationValue &animation_value)
{
if (accumulation_value.value_type != animation_value.value_type)
{
return OpStatus::OK;
}
if (accumulation_value_base.value_type != VALUE_EMPTY &&
accumulation_value_base.value_type != accumulation_value.value_type)
{
return OpStatus::OK;
}
if (accumulation_value.value_type == VALUE_NUMBER ||
accumulation_value.value_type == VALUE_PERCENTAGE)
{
float accumulate_number = accumulation_value.value.number;
if (accumulation_value_base.value_type == accumulation_value.value_type)
{
accumulate_number += accumulation_value_base.value.number;
}
animation_value.value.number += accumulate_number * repetition;
RETURN_IF_ERROR(Transfer(animation_value));
}
else if (accumulation_value.value_type == VALUE_COLOR)
{
UINT32 base_color = 0x0;
if (accumulation_value_base.value_type == VALUE_COLOR)
base_color = accumulation_value_base.value.color;
animation_value.value.color = AddAccumulationValueColor(accumulation_value.value.color,
base_color,
repetition,
animation_value.value.color);
RETURN_IF_ERROR(Transfer(animation_value));
}
else if (accumulation_value.value_type == VALUE_EMPTY)
{
if (accumulation_value.reference_type == REFERENCE_SVG_TRANSFORM &&
animation_value.reference_type == REFERENCE_SVG_TRANSFORM)
{
accumulation_value.reference.svg_transform->MakeDefaultsExplicit();
if (accumulation_value_base.reference_type == REFERENCE_SVG_TRANSFORM)
{
accumulation_value_base.reference.svg_transform->MakeDefaultsExplicit();
accumulation_value.reference.svg_transform->AddTransform(*accumulation_value_base.reference.svg_transform);
}
SVGTransform original_accumulation_transform;
original_accumulation_transform.Copy(*accumulation_value.reference.svg_transform);
SVGTransform &accumulation_transform = *animation_value.reference.svg_transform;
accumulation_transform.MakeDefaultsExplicit();
accumulation_transform.AddTransform(original_accumulation_transform);
for (SVG_ANIMATION_INTERVAL_REPETITION i=1;i<repetition;i++)
accumulation_transform.AddTransform(original_accumulation_transform);
}
}
return OpStatus::OK;
}
/* static */ OP_STATUS
SVGAnimationValue::Assign(SVGAnimationValueContext &context,
const SVGAnimationValue &rvalue, SVGAnimationValue &lvalue)
{
if (rvalue.reference_type != lvalue.reference_type)
{
return OpStatus::ERR;
}
switch(lvalue.reference_type)
{
case REFERENCE_SVG_FONT_SIZE:
{
*lvalue.reference.svg_font_size = *rvalue.reference.svg_font_size;
}
break;
case REFERENCE_SVG_BASELINE_SHIFT:
{
AssignSVGBaselineShifts(*rvalue.reference.svg_baseline_shift,
*lvalue.reference.svg_baseline_shift);
}
break;
case REFERENCE_SVG_LENGTH:
{
*lvalue.reference.svg_length = *rvalue.reference.svg_length;
}
break;
case REFERENCE_SVG_PAINT:
{
RETURN_IF_MEMORY_ERROR(AssignSVGPaints(*rvalue.reference.svg_paint,
*lvalue.reference.svg_paint));
}
break;
case REFERENCE_SVG_COLOR:
{
AssignSVGColors(*rvalue.reference.svg_color, *lvalue.reference.svg_color);
}
break;
case REFERENCE_SVG_RECT:
{
lvalue.reference.svg_rect->Set(*rvalue.reference.svg_rect);
}
break;
case REFERENCE_SVG_VECTOR:
{
lvalue.reference.svg_vector->Copy(context, *rvalue.reference.svg_vector);
}
break;
case REFERENCE_SVG_OPBPATH:
{
RETURN_IF_MEMORY_ERROR(lvalue.reference.svg_path->Copy(*rvalue.reference.svg_path));
}
break;
case REFERENCE_SVG_POINT:
{
lvalue.reference.svg_point->x = rvalue.reference.svg_point->x;
lvalue.reference.svg_point->y = rvalue.reference.svg_point->y;
}
break;
case REFERENCE_SVG_ENUM:
{
lvalue.reference.svg_enum->Copy(*rvalue.reference.svg_enum);
}
break;
case REFERENCE_SVG_NUMBER:
{
*lvalue.reference.svg_number = *rvalue.reference.svg_number;
}
break;
case REFERENCE_SVG_TRANSFORM:
{
lvalue.reference.svg_transform->Copy(*rvalue.reference.svg_transform);
}
break;
case REFERENCE_SVG_STRING:
{
SVGString *string_object = rvalue.reference.svg_string;
OP_ASSERT(string_object->GetString() != NULL);
RETURN_IF_ERROR(lvalue.reference.svg_string->SetString(string_object->GetString(),
string_object->GetLength()));
}
break;
case REFERENCE_SVG_URL:
{
RETURN_IF_ERROR(lvalue.reference.svg_url->Copy(*rvalue.reference.svg_url));
}
break;
case REFERENCE_SVG_ASPECT_RATIO:
{
lvalue.reference.svg_aspect_ratio->Copy(*rvalue.reference.svg_aspect_ratio);
}
break;
case REFERENCE_SVG_NAVREF:
{
lvalue.reference.svg_nav_ref->Copy(*rvalue.reference.svg_nav_ref);
}
break;
case REFERENCE_SVG_ORIENT:
{
RETURN_IF_ERROR(lvalue.reference.svg_orient->Copy(*rvalue.reference.svg_orient));
}
break;
case REFERENCE_SVG_CLASSOBJECT:
{
RETURN_IF_ERROR(lvalue.reference.svg_classobject->Copy(*rvalue.reference.svg_classobject));
}
break;
default:
{
OP_ASSERT(!"All reference types should be assignable");
}
}
switch(lvalue.value_type)
{
case VALUE_NUMBER:
case VALUE_PERCENTAGE:
{
lvalue.value.number = rvalue.value.number;
}
break;
case VALUE_COLOR:
{
lvalue.value.color = rvalue.value.color;
}
break;
case VALUE_EMPTY:
/* Nothing to do */
break;
default:
OP_ASSERT(!"Not reached");
}
return OpStatus::OK;
}
static const SVGObjectType s_reference_to_object_type[] = {
SVGOBJECT_NUMBER,
SVGOBJECT_LENGTH,
SVGOBJECT_STRING,
SVGOBJECT_BASELINE_SHIFT,
SVGOBJECT_COLOR,
SVGOBJECT_PAINT,
SVGOBJECT_FONTSIZE,
SVGOBJECT_POINT,
SVGOBJECT_RECT,
SVGOBJECT_VECTOR,
SVGOBJECT_PATH,
SVGOBJECT_MATRIX,
SVGOBJECT_TRANSFORM,
SVGOBJECT_ENUM,
SVGOBJECT_URL,
SVGOBJECT_ASPECT_RATIO,
SVGOBJECT_NAVREF,
SVGOBJECT_ORIENT,
SVGOBJECT_CLASSOBJECT
};
/* static */ SVGObjectType
SVGAnimationValue::TranslateToSVGObjectType(ReferenceType reference_type)
{
return (reference_type < REFERENCE_EMPTY) ?
s_reference_to_object_type[reference_type] :
SVGOBJECT_UNKNOWN;
}
/* static */ float
SVGAnimationValue::CalculateDistance(SVGAnimationValueContext &context,
const SVGAnimationValue &from_value,
const SVGAnimationValue &to_value)
{
if (from_value.value_type != to_value.value_type)
{
return 0.0f;
}
if (from_value.value_type == VALUE_NUMBER ||
from_value.value_type == VALUE_PERCENTAGE)
{
float a = from_value.value.number;
float b = to_value.value.number;
return (float)op_fabs(b - a);
}
else if (from_value.value_type == VALUE_COLOR)
{
return CalculateDistanceColors(from_value.value.color,
to_value.value.color);
}
else if (from_value.value_type == VALUE_EMPTY)
{
switch(from_value.reference_type)
{
case REFERENCE_SVG_VECTOR:
return CalculateDistanceSVGVector(context, *from_value.reference.svg_vector,
*to_value.reference.svg_vector);
case REFERENCE_SVG_POINT:
return CalculateDistanceSVGPoint(context, *from_value.reference.svg_point,
*to_value.reference.svg_point);
case REFERENCE_SVG_TRANSFORM:
return CalculateDistanceSVGTransform(*from_value.reference.svg_transform,
*to_value.reference.svg_transform);
case REFERENCE_SVG_OPBPATH:
return CalculateDistanceSVGPath(*from_value.reference.svg_path,
*to_value.reference.svg_path);
}
}
return 0.0f;
}
/* static */ UINT32
SVGAnimationValue::InterpolateColors(SVG_ANIMATION_INTERVAL_POSITION interval_position,
UINT32 from, UINT32 to, ExtraOperation extra_operation)
{
int fb = GetBValue(from);
int tb = GetBValue(to);
int fr = GetRValue(from);
int tr = GetRValue(to);
int fg = GetGValue(from);
int tg = GetGValue(to);
if (extra_operation == EXTRA_OPERATION_TREAT_TO_AS_BY)
{
tr += fr;
tg += fg;
tb += fb;
}
int cb = fb + (int)(interval_position * (tb-fb));
int cr = fr + (int)(interval_position * (tr-fr));
int cg = fg + (int)(interval_position * (tg-fg));
return OP_RGB(cr, cg, cb);
}
/* static */ float
SVGAnimationValue::CalculateDistanceColors(UINT32 from, UINT32 to)
{
int fr, fg, fb, tr, tb, tg;
fr = GetRValue(from);
fg = GetGValue(from);
fb = GetBValue(from);
tr = GetRValue(to);
tg = GetGValue(to);
tb = GetBValue(to);
int dr = fr - tr;
int dg = fg - tg;
int db = fb - tb;
return (float)op_sqrt((double)(dr*dr + dg*dg + db*db));
}
/* static */ UINT32
SVGAnimationValue::AddBasevalueColor(UINT32 base, UINT32 anim)
{
int fr, fg, fb, tr, tb, tg;
fr = GetRValue(base);
fg = GetGValue(base);
fb = GetBValue(base);
tr = GetRValue(anim);
tg = GetGValue(anim);
tb = GetBValue(anim);
return OP_RGB(MIN(255, fr + tr),
MIN(255, fg + tg),
MIN(255, fb + tb));
}
/* static */ UINT32
SVGAnimationValue::AddAccumulationValueColor(UINT32 accum,
UINT32 base,
SVG_ANIMATION_INTERVAL_REPETITION interval_repetition,
UINT32 anim)
{
int fr, fg, fb, tr, tb, tg;
fr = GetRValue(accum) + GetRValue(base);
fg = GetGValue(accum) + GetGValue(base);
fb = GetBValue(accum) + GetBValue(base);
tr = GetRValue(anim);
tg = GetGValue(anim);
tb = GetBValue(anim);
return OP_RGB(MIN(255, (fr * interval_repetition) + tr),
MIN(255, (fg * interval_repetition) + tg),
MIN(255, (fb * interval_repetition) + tb));
}
/* static */ void
SVGAnimationValue::Setup(SVGAnimationValue &animation_value,
SVGAnimationValueContext &context)
{
switch(animation_value.reference_type)
{
case REFERENCE_SVG_BASELINE_SHIFT:
{
SVGBaselineShift &baseline_shift = *animation_value.reference.svg_baseline_shift;
if (baseline_shift.GetShiftType() == SVGBaselineShift::SVGBASELINESHIFT_VALUE)
{
SetAnimationValueFromLength(animation_value, context, baseline_shift.GetValueRef());
}
else
{
animation_value.value_type = VALUE_EMPTY;
}
}
break;
case REFERENCE_SVG_FONT_SIZE:
{
SVGFontSize &font_size = *animation_value.reference.svg_font_size;
if (font_size.Mode() == SVGFontSize::MODE_LENGTH)
{
SVGLength &length = font_size.Length();
if (length.GetUnit() == CSS_PERCENTAGE)
{
animation_value.value_type = VALUE_NUMBER;
animation_value.value.number =
length.GetScalar().GetFloatValue() * context.GetFontHeight() / 100;
}
else
{
SetAnimationValueFromLength(animation_value, context, font_size.Length());
}
}
else if (font_size.Mode() == SVGFontSize::MODE_ABSOLUTE)
{
animation_value.value_type = VALUE_NUMBER;
animation_value.value.number = (float)font_size.AbsoluteFontSize();
}
else if (font_size.Mode() == SVGFontSize::MODE_RELATIVE)
{
animation_value.value_type = VALUE_NUMBER;
if (font_size.RelativeFontSize() == SVGRELATIVEFONTSIZE_SMALLER)
animation_value.value.number = (float)0.8*context.GetFontHeight();
else if (font_size.RelativeFontSize() == SVGRELATIVEFONTSIZE_LARGER)
animation_value.value.number = (float)1.2*context.GetFontHeight();
else
{
OP_ASSERT(!"Not reached");
animation_value.value.number = 1.0;
}
}
else if (font_size.Mode() == SVGFontSize::MODE_RESOLVED)
{
animation_value.value_type = VALUE_NUMBER;
animation_value.value.number = font_size.ResolvedLength().GetFloatValue();
}
else
{
// Default font-size:
animation_value.value_type = VALUE_NUMBER;
animation_value.value.number = 16.0;
}
}
break;
case REFERENCE_SVG_NUMBER:
{
animation_value.value_type = VALUE_NUMBER;
animation_value.value.number = animation_value.reference.svg_number->GetFloatValue();
}
break;
case REFERENCE_SVG_ORIENT:
{
SVGOrient &orient = *animation_value.reference.svg_orient;
if (orient.GetOrientType() == SVGORIENT_ANGLE)
{
SVGAngle &angle = *orient.GetAngle();
SVGNumber angle_in_deg = angle.GetAngleInUnits(SVGANGLE_DEG);
animation_value.value_type = VALUE_NUMBER;
animation_value.value.number = angle_in_deg.GetFloatValue();
}
}
break;
case REFERENCE_SVG_LENGTH:
{
SetAnimationValueFromLength(animation_value, context, *animation_value.reference.svg_length);
}
break;
case REFERENCE_SVG_PAINT:
{
SVGPaint &svg_paint = *animation_value.reference.svg_paint;
if (svg_paint.GetPaintType() == SVGPaint::RGBCOLOR ||
svg_paint.GetPaintType() == SVGPaint::RGBCOLOR_ICCCOLOR)
{
animation_value.value_type = VALUE_COLOR;
animation_value.value.color = svg_paint.GetRGBColor();
}
else if (svg_paint.GetPaintType() == SVGPaint::CURRENT_COLOR)
{
animation_value.value_type = VALUE_COLOR;
animation_value.value.color = context.GetCurrentColor();
}
else if (svg_paint.GetPaintType() == SVGPaint::INHERIT)
{
animation_value.value_type = VALUE_COLOR;
animation_value.value.color = context.GetInheritRGBColor();
}
else
{
animation_value.value_type = VALUE_EMPTY;
}
}
break;
case REFERENCE_SVG_COLOR:
{
SVGColor &svg_color = *animation_value.reference.svg_color;
if (svg_color.GetColorType() == SVGColor::SVGCOLOR_RGBCOLOR ||
svg_color.GetColorType() == SVGColor::SVGCOLOR_RGBCOLOR_ICCCOLOR)
{
animation_value.value_type = VALUE_COLOR;
animation_value.value.color = svg_color.GetRGBColor();
}
else if (svg_color.GetColorType() == SVGColor::SVGCOLOR_CURRENT_COLOR)
{
animation_value.value_type = VALUE_COLOR;
animation_value.value.color = context.GetCurrentColor();
}
#if 0 // Not sure how to deal with colors and inherit
else if (svg_color.GetColorType() == SVGColor::SVGCOLOR_INHERIT)
{
animation_value.value_type = VALUE_COLOR;
const HTMLayoutProperties* parent_props = context.GetParentProps();
if (parent_props)
animation_value.value.color = parent_props->font_color;
}
#endif
else
{
animation_value.value_type = VALUE_EMPTY;
}
}
break;
default:
animation_value.value_type = VALUE_EMPTY;
break;
}
}
/* static */ BOOL
SVGAnimationValue::Initialize(SVGAnimationValue &animation_value,
SVGObject *svg_object,
SVGAnimationValueContext &context)
{
if (svg_object == NULL)
{
return FALSE;
}
if (!svg_object->InitializeAnimationValue(animation_value))
return FALSE;
Setup(animation_value, context);
return TRUE;
}
/* static */ OP_STATUS
SVGAnimationValue::Transfer(SVGAnimationValue &animation_value)
{
switch(animation_value.reference_type)
{
case REFERENCE_SVG_BASELINE_SHIFT:
case REFERENCE_SVG_LENGTH:
{
SVGLength *length = NULL;
if (animation_value.reference_type == REFERENCE_SVG_BASELINE_SHIFT)
{
SVGBaselineShift &baseline_shift = *animation_value.reference.svg_baseline_shift;
baseline_shift.SetShiftType(SVGBaselineShift::SVGBASELINESHIFT_VALUE);
length = &baseline_shift.GetValueRef();
}
else
{
length = animation_value.reference.svg_length;
}
if (animation_value.value_type == VALUE_PERCENTAGE)
length->SetUnit(CSS_PERCENTAGE);
else
length->SetUnit(CSS_NUMBER);
length->SetScalar(animation_value.value.number);
}
break;
case REFERENCE_SVG_FONT_SIZE:
{
SVGFontSize &font_size = *animation_value.reference.svg_font_size;
if (animation_value.value_type == VALUE_PERCENTAGE)
{
font_size.SetLengthMode();
SVGLength &length = font_size.Length();
length.SetScalar(animation_value.value.number);
length.SetUnit(CSS_PERCENTAGE);
}
else
{
font_size.Resolve(animation_value.value.number);
}
}
break;
case REFERENCE_SVG_PAINT:
{
SVGPaint *paint = animation_value.reference.svg_paint;
paint->SetPaintType(SVGPaint::RGBCOLOR);
paint->SetColorRef(animation_value.value.color);
}
break;
case REFERENCE_SVG_COLOR:
{
SVGColor &color = *animation_value.reference.svg_color;
color.SetColorType(SVGColor::SVGCOLOR_RGBCOLOR);
color.SetColorRef(animation_value.value.color);
}
break;
case REFERENCE_SVG_NUMBER:
*animation_value.reference.svg_number = animation_value.value.number;
break;
case REFERENCE_SVG_ORIENT:
{
SVGOrient &orient = *animation_value.reference.svg_orient;
RETURN_IF_ERROR(orient.SetToAngleInDeg(animation_value.value.number));
}
break;
default:
break;
}
return OpStatus::OK;
}
/* static */ float
SVGAnimationValue::ResolveLength(float value, int css_unit, SVGAnimationValueContext& context)
{
switch(css_unit)
{
case CSS_EM:
return value * context.GetFontHeight();
case CSS_REM:
return value * context.GetRootFontHeight();
case CSS_EX:
return value * context.GetExHeight();
case CSS_PX:
return value;
case CSS_PT:
return (value * CSS_PX_PER_INCH) / 72.0f;
case CSS_PC:
return (value * CSS_PX_PER_INCH) / 6.0f;
case CSS_CM:
return (value * CSS_PX_PER_INCH) / 2.54f;
case CSS_MM:
return (value * CSS_PX_PER_INCH) / 25.4f;
case CSS_IN:
return value * CSS_PX_PER_INCH;
case CSS_PERCENTAGE:
return (value / 100.0f) * context.GetPercentageOf();
default:
return value;
}
}
/* static */ void
SVGAnimationValue::InterpolateSVGRects(SVG_ANIMATION_INTERVAL_POSITION interval_position,
SVGRect *from_rect,
SVGRect *to_rect,
ExtraOperation extra_operation,
SVGRect *target_rect)
{
/* Ignores extra_operation and treats rects as non-additive */
target_rect->Interpolate(*from_rect, *to_rect, interval_position);
}
/* static */ OP_STATUS
SVGAnimationValue::InterpolateSVGVectors(SVGAnimationValueContext &context,
SVG_ANIMATION_INTERVAL_POSITION interval_position,
SVGVector *from_vector,
SVGVector *to_vector,
ExtraOperation extra_operation,
SVGVector *target_vector)
{
/* Ignores extra_operation and treats vectors as non-additive.
* This one actually calls back into
* SVGAnimationValue::Interpolate to interpolate the objects it
* holds.
*/
return target_vector->Interpolate(context, *from_vector, *to_vector, interval_position);
}
/* static */ OP_STATUS
SVGAnimationValue::InterpolateSVGOpBpaths(SVG_ANIMATION_INTERVAL_POSITION interval_position,
OpBpath *from_path,
OpBpath *to_path,
ExtraOperation extra_operation,
OpBpath *target_path)
{
OP_STATUS status = from_path->SetUsedByDOM(TRUE);
if (OpStatus::IsSuccess(status))
status = to_path->SetUsedByDOM(TRUE);
RETURN_IF_ERROR(status);
/* Ignores extra_operation and treats paths as non-additive */
return target_path->Interpolate(*from_path, *to_path, interval_position);
}
/* static */ void
SVGAnimationValue::InterpolateSVGPoints(SVG_ANIMATION_INTERVAL_POSITION interval_position,
SVGPoint *from_point,
SVGPoint *to_point,
ExtraOperation extra_operation,
SVGPoint *target_point)
{
/* Ignores extra_operation and treats points as non-additive */
target_point->Interpolate(*from_point, *to_point, interval_position);
}
/* static */ OP_STATUS
SVGAnimationValue::InterpolateSVGTransforms(SVG_ANIMATION_INTERVAL_POSITION interval_position,
const SVGTransform &from_transform,
const SVGTransform &to_transform,
ExtraOperation extra_operation,
SVGTransform &target_transform)
{
SVGTransform modified_from_transform;
SVGTransform modified_to_transform;
modified_from_transform.Copy(from_transform);
modified_to_transform.Copy(to_transform);
if (modified_from_transform.GetTransformType() == SVGTRANSFORM_UNKNOWN)
{
modified_from_transform.Copy(to_transform);
modified_from_transform.SetZero();
}
else if (modified_to_transform.GetTransformType() == SVGTRANSFORM_UNKNOWN)
{
modified_to_transform.Copy(from_transform);
modified_from_transform.SetZero();
}
if (modified_from_transform.GetTransformType() == SVGTRANSFORM_UNKNOWN ||
modified_from_transform.GetTransformType() != modified_to_transform.GetTransformType())
{
modified_from_transform.Copy(modified_to_transform);
modified_from_transform.SetZero();
}
modified_from_transform.MakeDefaultsExplicit();
modified_to_transform.MakeDefaultsExplicit();
if (extra_operation == EXTRA_OPERATION_TREAT_TO_AS_BY)
{
modified_to_transform.AddTransform(modified_from_transform);
}
target_transform.SetTransformType(modified_from_transform.GetTransformType());
target_transform.Interpolate(modified_from_transform, modified_to_transform, interval_position);
return OpStatus::OK;
}
/* static */ void
SVGAnimationValue::SetCSSProperty(SVGAnimationAttributeLocation &location,
SVGAnimationValue &animation_value,
SVGAnimationValueContext &context)
{
const HTMLayoutProperties* props = context.GetProps();
if (!props)
return;
const SvgProperties *svg_props = props->svg;
switch(location.animated_name)
{
case Markup::SVGA_STROKE_DASHOFFSET:
case Markup::SVGA_STROKE_WIDTH:
{
animation_value.value_type = SVGAnimationValue::VALUE_NUMBER;
const SVGLength &length = location.animated_name == Markup::SVGA_STROKE_DASHOFFSET ?
svg_props->dashoffset :
svg_props->linewidth;
animation_value.value.number = SVGAnimationValue::ResolveLength(length.GetScalar().GetFloatValue(),
length.GetUnit(), context);
}
break;
case Markup::SVGA_FILL_OPACITY:
animation_value.value_type = SVGAnimationValue::VALUE_NUMBER;
animation_value.value.number = props->opacity/255.0f;
break;
case Markup::SVGA_OPACITY:
animation_value.value_type = SVGAnimationValue::VALUE_NUMBER;
animation_value.value.number = props->opacity/255.0f;
break;
case Markup::SVGA_FLOOD_OPACITY:
animation_value.value_type = SVGAnimationValue::VALUE_NUMBER;
animation_value.value.number = svg_props->floodopacity/255.0f;
break;
case Markup::SVGA_STOP_OPACITY:
animation_value.value_type = SVGAnimationValue::VALUE_NUMBER;
animation_value.value.number = svg_props->stopopacity/255.0f;
break;
case Markup::SVGA_STROKE_OPACITY:
animation_value.value_type = SVGAnimationValue::VALUE_NUMBER;
animation_value.value.number = svg_props->strokeopacity/255.0f;
break;
case Markup::SVGA_SOLID_OPACITY:
animation_value.value_type = SVGAnimationValue::VALUE_NUMBER;
animation_value.value.number = svg_props->solidopacity/255.0f;
break;
case Markup::SVGA_VIEWPORT_FILL_OPACITY:
animation_value.value_type = SVGAnimationValue::VALUE_NUMBER;
animation_value.value.number = svg_props->viewportfillopacity/255.0f;
break;
case Markup::SVGA_STROKE_MITERLIMIT:
animation_value.value_type = SVGAnimationValue::VALUE_NUMBER;
animation_value.value.number = svg_props->miterlimit.GetFloatValue();
break;
case Markup::SVGA_LETTER_SPACING:
animation_value.value_type = SVGAnimationValue::VALUE_NUMBER;
animation_value.value.number = (float)props->letter_spacing;
break;
case Markup::SVGA_WORD_SPACING:
animation_value.value_type = SVGAnimationValue::VALUE_NUMBER;
animation_value.value.number = props->word_spacing_i / 256.0f;
break;
case Markup::SVGA_FILL:
animation_value.reference_type = SVGAnimationValue::REFERENCE_SVG_PAINT;
// We make a const_cast here since we don't have
// SVGAnimationValues with const references (yet). Since it is
// a base value, we will just read from it anyway.
animation_value.reference.svg_paint = const_cast<SVGPaint *>(svg_props->GetFill());
SVGAnimationValue::Setup(animation_value, context);
break;
case Markup::SVGA_STROKE:
animation_value.reference_type = SVGAnimationValue::REFERENCE_SVG_PAINT;
// We make a const_cast here since we don't have
// SVGAnimationValues with const references (yet). Since it is
// a base value, we will just read from it anyway.
animation_value.reference.svg_paint = const_cast<SVGPaint *>(svg_props->GetStroke());
SVGAnimationValue::Setup(animation_value, context);
break;
case Markup::SVGA_COLOR:
animation_value.value_type = SVGAnimationValue::VALUE_COLOR;
animation_value.value.color = props->font_color;
break;
case Markup::SVGA_FLOOD_COLOR:
animation_value.value_type = SVGAnimationValue::VALUE_COLOR;
animation_value.value.color = svg_props->floodcolor.GetRGBColor();
break;
case Markup::SVGA_LIGHTING_COLOR:
animation_value.value_type = SVGAnimationValue::VALUE_COLOR;
animation_value.value.color = svg_props->lightingcolor.GetRGBColor();
break;
case Markup::SVGA_STOP_COLOR:
animation_value.value_type = SVGAnimationValue::VALUE_COLOR;
animation_value.value.color = svg_props->stopcolor.GetRGBColor();
break;
case Markup::SVGA_SOLID_COLOR:
animation_value.value_type = SVGAnimationValue::VALUE_COLOR;
animation_value.value.color = svg_props->solidcolor.GetRGBColor();
break;
case Markup::SVGA_VIEWPORT_FILL:
animation_value.value_type = SVGAnimationValue::VALUE_COLOR;
animation_value.value.color = svg_props->viewportfill.GetRGBColor();
break;
case Markup::SVGA_FONT_SIZE:
animation_value.value_type = SVGAnimationValue::VALUE_NUMBER;
animation_value.value.number = svg_props->fontsize.GetFloatValue();
break;
}
}
/* static */ float
SVGAnimationValue::CalculateDistanceSVGVector(SVGAnimationValueContext &context, const SVGVector &from, const SVGVector &to)
{
return SVGVector::CalculateDistance(from, to, context);
}
/* static */ float
SVGAnimationValue::CalculateDistanceSVGPoint(SVGAnimationValueContext &context, const SVGPoint &from, const SVGPoint &to)
{
SVGNumber dx = from.x - to.x;
SVGNumber dy = from.y - to.y;
return ((dx * dx) + (dy * dy)).sqrt().GetFloatValue();
}
/* static */ float
SVGAnimationValue::CalculateDistanceSVGTransform(const SVGTransform &from,
const SVGTransform &to)
{
return from.Distance(to);
}
/* static */ float
SVGAnimationValue::CalculateDistanceSVGPath(const OpBpath &from,
const OpBpath &to)
{
// UNIMPLEMENTED. The 1.2 spec has a crazy definition (in my
// opinion). We will see how it turns out. SVG 1.1 does not say
// how to calculate paced interpolation of paths.
return 0.0;
}
/* static */
SVGAnimationValue SVGAnimationValue::Empty()
{
SVGAnimationValue v;
v.reference_type = REFERENCE_EMPTY;
v.value_type = VALUE_EMPTY;
return v;
}
/* static */ BOOL
SVGAnimationValue::IsEmpty(SVGAnimationValue &animation_value)
{
return (animation_value.reference_type == REFERENCE_EMPTY &&
animation_value.value_type == VALUE_EMPTY);
}
/* static */ void
SVGAnimationValue::SetAnimationValueFromLength(SVGAnimationValue &animation_value,
SVGAnimationValueContext &context,
SVGLength &length)
{
if (length.GetUnit() == CSS_PERCENTAGE)
{
animation_value.value_type = VALUE_PERCENTAGE;
animation_value.value.number = length.GetScalar().GetFloatValue();
}
else
{
float n = ResolveLength(length.GetScalar().GetFloatValue(),
length.GetUnit(), context);
animation_value.value_type = VALUE_NUMBER;
animation_value.value.number = n;
}
}
#endif // SVG_SUPPORT
|
#ifndef AWS_NODES_FUNCTIONCALL_H
#define AWS_NODES_FUNCTIONCALL_H
/*
* aws/nodes/functioncall.h
* AwesomeScript Function Call Expression
* Author: Dominykas Djacenka
* Email: Chaosteil@gmail.com
*/
#include <list>
#include <string>
#include "expression.h"
namespace AwS{
namespace Nodes{
class FunctionCall : public Expression{
public:
FunctionCall(const std::string& name, std::list<Expression*>* content)
: Expression(), _name(name), _content(content){
}
virtual ~FunctionCall(){
if(_content){
for(std::list<Expression*>::iterator i = _content->begin(); i != _content->end(); ++i){
if(*i)delete *i;
}
delete _content;
}
}
const std::string& getName() const{ return _name; }
const std::list<Expression*>& getContent() const{ return *_content; }
void translatePhp(std::ostream& output, TranslateSettings& settings) const throw(NodeException){
output << settings.getFunctionPrefix() << _name << "(";
bool begin = true;
for(std::list<Expression*>::iterator i = _content->begin(); i != _content->end(); ++i){
if(begin == false)
output << ", ";
(*i)->translatePhp(output, settings);
begin = false;
}
output << ")";
}
private:
const std::string _name;
std::list<Expression*>* _content;
};
};
};
#endif
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
int n, m, c;
cin >> n >> m >> c;
vector<int> b;
vector<int> a[21];
for(int i = 0; i < m; i++)
{
int tmp;
cin >> tmp;
b.push_back(tmp);
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
int tmp;
cin >> tmp;
a[i].push_back(tmp);
}
}
int ans = 0;
for(int i = 0; i < n; i++)
{
int score = 0;
for(int j = 0; j < m; j++)
{
score += a[i][j]*b[j];
}
score += c;
if (score > 0) ans++;
}
cout << ans;
}
|
#ifndef RESULTWIDGET_HPP
#define RESULTWIDGET_HPP
#include <QWidget>
#include <boost/weak_ptr.hpp>
class Profile;
class Simulation;
class QwtPlot;
class QwtPlotCurve;
class ResultWidget : public QWidget
{
Q_OBJECT
public:
typedef boost::shared_ptr<QwtPlotCurve> plotcurve_sp;
explicit ResultWidget(QWidget *parent = 0);
void display(boost::weak_ptr<Profile> profile_wk, const Simulation& simul);
private:
QwtPlot* m_plotDataAccX;
QwtPlot* m_plotDataAccY;
QwtPlot* m_plotDataSpeedX;
QwtPlot* m_plotDataSpeedY;
QwtPlot* m_plotDataPosX;
QwtPlot* m_plotDataPosY;
std::list<plotcurve_sp> m_curves;
signals:
public slots:
};
#endif // RESULTWIDGET_HPP
|
#include "stdafx.h"
#include "ContestConfigTests.h"
#include "StringUtils.h"
#include "ContestConfig.h"
ContestConfigTests::ContestConfigTests()
:
TestBase("ContestConfigTests")
{
}
ContestConfigTests::~ContestConfigTests()
{
}
bool ContestConfigTests::Setup()
{
if (SetupComplete())
return SetupStatus();
if (!TestBase::Setup())
return false;
return true;
}
void ContestConfigTests::Teardown()
{
TestBase::Teardown();
}
bool ContestConfigTests::RunAllTests()
{
bool status = true;
status = CheckRequiredFoldersTest_NoLogsFolderSpecified() && status;
status = CheckRequiredFoldersTest_LogFolderDoesNotExist() && status;
return status;
}
bool ContestConfigTests::CheckRequiredFoldersTest_NoLogsFolderSpecified()
{
if (!StartTest("CheckRequiredFoldersTest_NoLogsFolder")) return false;
ContestConfig contestConfig;
contestConfig.SetVerbose(false); // don't dump errors to console
bool status = contestConfig.CheckRequiredFolders();
AssertFalse(status);
ContestConfigError error = contestConfig.GetError();
AssertTrue(error == eLogFolderNotProvided);
return status == false;
}
bool ContestConfigTests::CheckRequiredFoldersTest_LogFolderDoesNotExist()
{
if (!StartTest("CheckRequiredFoldersTest_LogFolderDoesNotExist")) return false;
ContestConfig contestConfig;
contestConfig.SetVerbose(false); // don't dump errors to console
contestConfig.AddFolderKeyValuePair("Logs", "c:\\DummyFolder\\LogsNotHere");
bool status = contestConfig.CheckRequiredFolders();
AssertFalse(status);
ContestConfigError error = contestConfig.GetError();
AssertTrue(error == eLogFolderDoesNotExist);
return status == false;
}
|
#ifndef _BIT_H_
#define _BIT_H_
#include <cstdint>
typedef uint8_t byte_t;
//************************************************************
class BitRef{
byte_t *byte;
uint8_t bit_index;
public:
BitRef(byte_t *_byte, byte_t _bit_index)
: byte(_byte), bit_index(_bit_index) {}
BitRef& operator=(bool value){
if(value)
*byte |= 1 << bit_index;
else
*byte &= ~(1 << bit_index);
return *this;
}
operator bool() const {
return *byte & (1 << bit_index);
}
};
//************************************************************
class ConstBitRef{
const byte_t *byte;
uint8_t bit_index;
public:
ConstBitRef(const byte_t *_byte, uint8_t _bit_index)
: byte(_byte), bit_index(_bit_index) {}
operator bool() const {
return *byte & (1 << bit_index);
}
};
//************************************************************
#endif //_BIT_H_
|
/*********************************************************\
* Copyright (c) 2012-2018 The Unrimp Team
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "OpenGLRenderer/ResourceGroup.h"
#include "OpenGLRenderer/RootSignature.h"
#include <Renderer/IAssert.h>
#include <Renderer/IRenderer.h>
#include <Renderer/IAllocator.h>
#include <Renderer/State/ISamplerState.h>
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace OpenGLRenderer
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
ResourceGroup::ResourceGroup(RootSignature& rootSignature, uint32_t rootParameterIndex, uint32_t numberOfResources, Renderer::IResource** resources, Renderer::ISamplerState** samplerStates) :
IResourceGroup(rootSignature.getRenderer()),
mRootParameterIndex(rootParameterIndex),
mNumberOfResources(numberOfResources),
mResources(RENDERER_MALLOC_TYPED(rootSignature.getRenderer().getContext(), Renderer::IResource*, mNumberOfResources)),
mSamplerStates(nullptr),
mResourceIndexToUniformBlockBindingIndex(nullptr)
{
// Get the uniform block binding start index
const Renderer::Context& context = rootSignature.getRenderer().getContext();
const Renderer::RootSignature& rootSignatureData = rootSignature.getRootSignature();
uint32_t uniformBlockBindingIndex = 0;
for (uint32_t currentRootParameterIndex = 0; currentRootParameterIndex < rootParameterIndex; ++currentRootParameterIndex)
{
const Renderer::RootParameter& rootParameter = rootSignatureData.parameters[currentRootParameterIndex];
if (Renderer::RootParameterType::DESCRIPTOR_TABLE == rootParameter.parameterType)
{
RENDERER_ASSERT(rootSignature.getRenderer().getContext(), nullptr != reinterpret_cast<const Renderer::DescriptorRange*>(rootParameter.descriptorTable.descriptorRanges), "Invalid OpenGL descriptor ranges")
const uint32_t numberOfDescriptorRanges = rootParameter.descriptorTable.numberOfDescriptorRanges;
for (uint32_t descriptorRangeIndex = 0; descriptorRangeIndex < numberOfDescriptorRanges; ++descriptorRangeIndex)
{
if (Renderer::DescriptorRangeType::UBV == reinterpret_cast<const Renderer::DescriptorRange*>(rootParameter.descriptorTable.descriptorRanges)[descriptorRangeIndex].rangeType)
{
++uniformBlockBindingIndex;
}
}
}
}
// Process all resources and add our reference to the renderer resource
const Renderer::RootParameter& rootParameter = rootSignatureData.parameters[rootParameterIndex];
for (uint32_t resourceIndex = 0; resourceIndex < mNumberOfResources; ++resourceIndex, ++resources)
{
Renderer::IResource* resource = *resources;
mResources[resourceIndex] = resource;
resource->addReference();
// Uniform block binding index handling
const Renderer::DescriptorRange& descriptorRange = reinterpret_cast<const Renderer::DescriptorRange*>(rootParameter.descriptorTable.descriptorRanges)[resourceIndex];
if (Renderer::DescriptorRangeType::UBV == descriptorRange.rangeType)
{
if (nullptr == mResourceIndexToUniformBlockBindingIndex)
{
mResourceIndexToUniformBlockBindingIndex = RENDERER_MALLOC_TYPED(context, uint32_t, mNumberOfResources);
memset(mResourceIndexToUniformBlockBindingIndex, 0, sizeof(uint32_t) * mNumberOfResources);
}
mResourceIndexToUniformBlockBindingIndex[resourceIndex] = uniformBlockBindingIndex;
++uniformBlockBindingIndex;
}
}
if (nullptr != samplerStates)
{
mSamplerStates = RENDERER_MALLOC_TYPED(context, Renderer::ISamplerState*, mNumberOfResources);
for (uint32_t resourceIndex = 0; resourceIndex < mNumberOfResources; ++resourceIndex)
{
Renderer::ISamplerState* samplerState = mSamplerStates[resourceIndex] = samplerStates[resourceIndex];
if (nullptr != samplerState)
{
samplerState->addReference();
}
}
}
}
ResourceGroup::~ResourceGroup()
{
// Remove our reference from the renderer resources
const Renderer::Context& context = getRenderer().getContext();
if (nullptr != mSamplerStates)
{
for (uint32_t resourceIndex = 0; resourceIndex < mNumberOfResources; ++resourceIndex)
{
Renderer::ISamplerState* samplerState = mSamplerStates[resourceIndex];
if (nullptr != samplerState)
{
samplerState->releaseReference();
}
}
RENDERER_FREE(context, mSamplerStates);
}
for (uint32_t resourceIndex = 0; resourceIndex < mNumberOfResources; ++resourceIndex)
{
mResources[resourceIndex]->releaseReference();
}
RENDERER_FREE(context, mResources);
RENDERER_FREE(context, mResourceIndexToUniformBlockBindingIndex);
}
//[-------------------------------------------------------]
//[ Protected virtual Renderer::RefCount methods ]
//[-------------------------------------------------------]
void ResourceGroup::selfDestruct()
{
RENDERER_DELETE(getRenderer().getContext(), ResourceGroup, this);
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // OpenGLRenderer
|
#include<iostream>
using namespace std;
class gadi{
public:
gadi(char* n,int ns,float rt): rate(rt)
{
int k=(ns<=15)?ns:15;
for(int j=0;j!=k;j++)
name[j]=n[j];
name[k]='\0';
}
gadi(const gadi& a)
{
for(int i=0;i!=15;i++)
name[i]=a.name[i];
rate=a.rate;
}
void bill(float hr)
{
cout<<"name:"<<name<<" | Rate: Rs"<<rate<<"/hr | Hours: "<<hr<<"hrs | Total fee to be paid: Rs"<<rate*hr;
}
private:
char name[15];
float rate;
};
int main(){
gadi bike1("Yatri",5,2.5);
bike1.bill(1.5);cout<<endl;
gadi bike2(bike1);
bike2.bill(2.5);
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
double m;
cin >> n >> m;
n %= 12;
double ans = abs(n*30 - m*5.5);
cout << min(ans, 360.0-ans) << endl;
return 0;
}
|
#ifndef DATAMODEL_H
#define DATAMODEL_H
#include <QMainWindow>
class QSqlTableModel;
namespace Ui {
class DataModel;
}
class DataModel : public QMainWindow
{
Q_OBJECT
public:
explicit DataModel(QWidget *parent = 0);
~DataModel();
private slots:
void on_submitButton_clicked();
void on_rollbackButton_clicked();
void on_addButton_clicked();
void on_deleteButton_clicked();
private:
Ui::DataModel *ui;
QSqlTableModel *model; //数据库
};
#endif // DATAMODEL_H
|
#ifndef _Configure_H
#define _Configure_H
#include <time.h>
#include "Util.h"
#include "GameConfig.h"
#define MAX_ALLOC_NUM 8
class Configure : public GameConfig
{
public:
static Configure* getInstance() {
static Configure * configure = NULL;
if (configure == NULL)
configure = new Configure();
return configure;
}
virtual bool LoadGameConfig();
virtual int GetMaxTableNumber() { return max_table; }
virtual int GetMaxUserNumber() { return max_user; }
//***********************************************************
public:
char alloc_ip[64];
short alloc_port;
short numplayer;
//控制进入桌子
short contrllevel;
//第一轮最大倍数
short maxmulone;
//第二轮最大倍数
short maxmultwo;
int monitor_time;//监控时间
int keeplive_time;//存活时间
//总轮数
short max_round;
//比牌轮数
//short compare_round;
//全下轮数
short allin_round;
//short check_round;
//下注的超时时间
int betcointime;
//大于两个人准备,另有人没有准备,启动倒计时把没准备的人踢出且游戏开始
int tablestarttime;
//超时踢出没准备用户
short kicktime;
time_t starttime; //服务器启动时间
time_t lasttime; //最近活动时间
//下低注就超时几次之后就把他踢出
short timeoutCount;
short fraction;
//简单任务的发放局数条件
short esayTaskCount;
short esayRandNum;
short esayTaskRand;
//获得乐劵通知的个数条件
short getIngotNoti1;
short getIngotNoti2;
short getIngotNoti3;
short robotTabNum1;
short robotTabNum2;
int rewardcoin;
int rewardroll;
short rewardRate;
//赢取金币小喇叭发送
int wincoin1;
int wincoin2;
int wincoin3;
int wincoin4;
short mulcount;
short mulnum1;
int mulcoin1;
short mulnum2;
int mulcoin2;
short forbidcount;
short forbidnum1;
int forbidcoin1;
short forbidnum2;
int forbidcoin2;
short changecount;
int changecoin1;
int changecoin2;
int changecoin3;
short betmaxallinflag;
private:
Configure();
private:
int max_table;
int max_user;
};
#endif
|
#pragma once
namespace aeEngineSDK
{
class AE_GRAPHICS_EXPORT aeVertexBuffer : public aeBuffer
{
protected:
aeVertexBuffer();
friend class aeGraphicsAPI;
friend class aeRenderer;
public:
aeVertexBuffer(const aeVertexBuffer& B);
virtual ~aeVertexBuffer();
};
}
|
#include "ns3/core-module.h"
#include "ns3/point-to-point-module.h"
#include "ns3/mobility-module.h"
#include "ns3/applications-module.h"
#include "ns3/wifi-module.h"
#include "ns3/network-module.h"
#include "ns3/csma-module.h"
#include "ns3/internet-module.h"
#include "ns3/bridge-helper.h"
#include "ns3/stats-module.h"
#include "ns3/flow-monitor-module.h"
#include <vector>
#include <stdint.h>
#include <sstream>
#include <fstream>
#include <iostream>
using namespace ns3;
#define MODULE_NAME "mo818"
#define DATA_PATH "data/"
#define NUM_WIFIS 2
#define NUM_SAMPLES 10
#define SIM_START_TIME 0.5
#define SIM_DURATION 120.0
#define AP_RANGE 20.0
#define MIN_STAS 4
#define MAX_STAS 20
#define STA_INCR 4
#define TRAF_TYPE_CBR 0
#define TRAF_TYPE_BURST 1
#define MOB_LEVEL_LOW 0
#define MOB_LEVEL_MED 1
#define MOB_LEVEL_HIGH 2
class Experiment
{
public:
Experiment ();
Experiment (uint32_t mobLevel, uint32_t trafficType);
void Run (uint32_t mobLevel, uint32_t trafficType, uint32_t enablePcap);
private:
std::vector<NodeContainer> staNodes;
std::vector<NetDeviceContainer> staDevices;
std::vector<NetDeviceContainer> apDevices;
std::vector<Ipv4InterfaceContainer> staInterfaces;
std::vector<Ipv4InterfaceContainer> apInterfaces;
std::string pcapPrefix;
Gnuplot lossPlot;
Gnuplot delayPlot;
Gnuplot throughputPlot;
Gnuplot2dDataset closestLossDataSet;
Gnuplot2dDataset allLossDataSet;
Gnuplot2dDataset fartherstLossDataSet;
Gnuplot2dDataset closestDelayDataSet;
Gnuplot2dDataset allDelayDataSet;
Gnuplot2dDataset fartherstDelayDataSet;
Gnuplot2dDataset closestThroughputDataSet;
Gnuplot2dDataset allThroughputDataSet;
Gnuplot2dDataset fartherstThroughputDataSet;
Average< double > closestLossSamples;
Average< double > allLossSamples;
Average< double > fartherstLossSamples;
Average< double > closestDelaySamples;
Average< double > allDelaySamples;
Average< double > fartherstDelaySamples;
Average< double > closestThroughputSamples;
Average< double > allThroughputSamples;
Average< double > fartherstThroughputSamples;
NetDeviceContainer connectP2pNodes (Ptr< Node > n1, Ptr< Node > n2);
void createBss(YansWifiPhyHelper wifiPhy,
Ptr< YansWifiChannel > wifiChannel,
Ptr< Node > apNode, Ptr< Node > routerNode,
uint32_t i, uint32_t nStas,
Ipv4AddressHelper& ip, uint32_t mobLevel,
uint32_t enablePcap);
void installApps(Ptr< Node > from, Ptr< Node > to, Ipv4Address destIp, uint32_t trafficType);
void getStats(FlowMonitorHelper& helper, Ipv4Address closestAddress, Ipv4Address fartherstAddress, uint32_t nStas);
void AddDataPoint(uint32_t totalStas, Gnuplot2dDataset& dataSet, Average< double >& samples);
void RunOneSample (uint32_t sample, uint32_t nStas, uint32_t mobLevel, uint32_t trafficType, uint32_t enablePcap);
void RunOnePass (uint32_t nStas, uint32_t mobLevel, uint32_t trafficType, uint32_t enablePcap);
};
Experiment::Experiment ()
{
}
Experiment::Experiment (uint32_t mobLevel, uint32_t trafficType)
{
const char* mob;
switch (mobLevel)
{
case MOB_LEVEL_HIGH:
mob = "high";
break;
case MOB_LEVEL_MED:
mob = "medium";
break;
case MOB_LEVEL_LOW:
default:
mob = "low";
break;
}
const char *traf = (trafficType == TRAF_TYPE_CBR) ? "CBR" : "burst";
closestLossDataSet = Gnuplot2dDataset ("Closest");
allLossDataSet = Gnuplot2dDataset ("Average");
fartherstLossDataSet = Gnuplot2dDataset ("Fartherst");
closestDelayDataSet = Gnuplot2dDataset ("Closest");
allDelayDataSet = Gnuplot2dDataset ("Average");
fartherstDelayDataSet = Gnuplot2dDataset ("Fartherst");
closestThroughputDataSet = Gnuplot2dDataset ("Closest");
allThroughputDataSet = Gnuplot2dDataset ("Average");
fartherstThroughputDataSet = Gnuplot2dDataset ("Fartherst");
closestLossDataSet.SetStyle (Gnuplot2dDataset::LINES_POINTS);
allLossDataSet.SetStyle (Gnuplot2dDataset::LINES_POINTS);
fartherstLossDataSet.SetStyle (Gnuplot2dDataset::LINES_POINTS);
closestLossDataSet.SetErrorBars (Gnuplot2dDataset::Y);
allLossDataSet.SetErrorBars (Gnuplot2dDataset::Y);
fartherstLossDataSet.SetErrorBars (Gnuplot2dDataset::Y);
std::ostringstream lossFile;
lossFile << "mo818-loss-mob-" << mobLevel << "-traf-" << trafficType << ".png";
std::ostringstream lossTitle;
lossTitle << "Loss: mobility " << mob << ", " << traf;
lossPlot = Gnuplot (lossFile.str (), lossTitle.str ());
lossPlot.AddDataset (closestLossDataSet);
lossPlot.AddDataset (allLossDataSet);
lossPlot.AddDataset (fartherstLossDataSet);
lossPlot.SetLegend("# WiFi stations", "Loss (%)");
closestDelayDataSet.SetStyle (Gnuplot2dDataset::LINES_POINTS);
allDelayDataSet.SetStyle (Gnuplot2dDataset::LINES_POINTS);
fartherstDelayDataSet.SetStyle (Gnuplot2dDataset::LINES_POINTS);
closestDelayDataSet.SetErrorBars (Gnuplot2dDataset::Y);
allDelayDataSet.SetErrorBars (Gnuplot2dDataset::Y);
fartherstDelayDataSet.SetErrorBars (Gnuplot2dDataset::Y);
std::ostringstream delayFile;
delayFile << "mo818-delay-mob-" << mobLevel << "-traf-" << trafficType << ".png";
std::ostringstream delayTitle;
delayTitle << "Delay: mobility " << mob << ", " << traf;
delayPlot = Gnuplot (delayFile.str (), delayTitle.str ());
delayPlot.AddDataset (closestDelayDataSet);
delayPlot.AddDataset (allDelayDataSet);
delayPlot.AddDataset (fartherstDelayDataSet);
delayPlot.SetLegend("# WiFi stations", "Delay (ms)");
closestThroughputDataSet.SetStyle (Gnuplot2dDataset::LINES_POINTS);
allThroughputDataSet.SetStyle (Gnuplot2dDataset::LINES_POINTS);
fartherstThroughputDataSet.SetStyle (Gnuplot2dDataset::LINES_POINTS);
closestThroughputDataSet.SetErrorBars (Gnuplot2dDataset::Y);
allThroughputDataSet.SetErrorBars (Gnuplot2dDataset::Y);
fartherstThroughputDataSet.SetErrorBars (Gnuplot2dDataset::Y);
std::ostringstream throughputFile;
throughputFile << "mo818-throughput-mob-" << mobLevel << "-traf-" << trafficType << ".png";
std::ostringstream throughputTitle;
throughputTitle << "Throughput: mobility " << mob << ", " << traf;
throughputPlot = Gnuplot (throughputFile.str (), throughputTitle.str ());
throughputPlot.AddDataset (closestThroughputDataSet);
throughputPlot.AddDataset (allThroughputDataSet);
throughputPlot.AddDataset (fartherstThroughputDataSet);
throughputPlot.SetLegend("# WiFi stations", "Throughput (Kibps)");
}
NetDeviceContainer
Experiment::connectP2pNodes (Ptr< Node > n1, Ptr< Node > n2)
{
NodeContainer p2pNodes;
p2pNodes.Add (n1);
p2pNodes.Add (n2);
PointToPointHelper pointToPoint;
pointToPoint.SetDeviceAttribute ("DataRate", StringValue ("100Mbps"));
pointToPoint.SetChannelAttribute ("Delay", StringValue ("2ms"));
NetDeviceContainer p2pDevices;
p2pDevices = pointToPoint.Install (p2pNodes);
//pointToPoint.EnablePcap (pcapPrefix, p2pDevices.Get (0));
return p2pDevices;
}
void
Experiment::createBss(YansWifiPhyHelper wifiPhy,
Ptr< YansWifiChannel > wifiChannel,
Ptr< Node > apNode, Ptr< Node > routerNode,
uint32_t i, uint32_t nStas,
Ipv4AddressHelper& ip, uint32_t mobLevel,
uint32_t enablePcap)
{
NodeContainer closestSta;
NodeContainer otherSta;
NodeContainer sta;
NetDeviceContainer staDev;
NetDeviceContainer apDev;
Ipv4InterfaceContainer staInterface;
Ipv4InterfaceContainer apInterface;
BridgeHelper bridge;
MobilityHelper mobility;
WifiHelper wifi = WifiHelper::Default ();
NqosWifiMacHelper wifiMac = NqosWifiMacHelper::Default ();
wifiPhy.SetChannel (wifiChannel);
closestSta.Create (1);
otherSta.Create (nStas-1);
sta.Add (closestSta);
sta.Add (otherSta);
Ssid ssid = Ssid ("mo818-ssid");
wifiMac.SetType ("ns3::ApWifiMac",
"Ssid", SsidValue (ssid));
apDev = wifi.Install (wifiPhy, wifiMac, apNode);
NetDeviceContainer bridgeDev;
bridgeDev = bridge.Install (apNode, NetDeviceContainer (apDev, apNode->GetDevice (1)));
// assign AP IP address to bridge, not wifi
apInterface = ip.Assign (bridgeDev);
if (enablePcap) wifiPhy.EnablePcap (pcapPrefix, apDev);
// setup the STAs
InternetStackHelper stack;
stack.Install (sta);
// setup mobility model for the closet station
Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator> ();
if (i % 2 == 0)
{
positionAlloc->Add (Vector (AP_RANGE / 10.0, AP_RANGE / 4, 0.0));
}
else
{
positionAlloc->Add (Vector (1.4 * AP_RANGE, AP_RANGE / 4, 0.0));
}
mobility.SetPositionAllocator (positionAlloc);
// calculate mobility model speed based on mobility level
std::ostringstream speed;
speed <<"ns3::ConstantRandomVariable[Constant=" << mobLevel << ".0]";
mobility.SetMobilityModel ("ns3::RandomWalk2dMobilityModel",
"Mode", StringValue ("Time"),
"Time", StringValue ("60s"),
"Speed", StringValue (speed.str ()),
"Bounds", RectangleValue (Rectangle (i * AP_RANGE / 2.0,
i * AP_RANGE / 2.0 + AP_RANGE,
0.0,
AP_RANGE / 2.0)));
mobility.Install (closestSta);
// setup mobility model for the other stations
if (i % 2 == 0)
{
mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
"MinX", DoubleValue (2.0 * AP_RANGE / 10.0),
"MinY", DoubleValue (0.0),
"DeltaX", DoubleValue (AP_RANGE / 10.0),
"DeltaY", DoubleValue (AP_RANGE / 10.0),
"GridWidth", UintegerValue (6),
"LayoutType", StringValue ("ColumnFirst"));
}
else
{
uint32_t nCols = ((nStas - 1) / 6) + (((nStas - 1) % 6 == 0) ? 0 : 1);
mobility.SetPositionAllocator ("ns3::GridPositionAllocator",
"MinX", DoubleValue (AP_RANGE * (14.0 - nCols) / 10.0),
"MinY", DoubleValue (0.0),
"DeltaX", DoubleValue (AP_RANGE / 10.0),
"DeltaY", DoubleValue (AP_RANGE / 10.0),
"GridWidth", UintegerValue (6),
"LayoutType", StringValue ("ColumnFirst"));
}
mobility.Install (otherSta);
wifiMac.SetType ("ns3::StaWifiMac",
"Ssid", SsidValue (ssid),
"ActiveProbing", BooleanValue (false));
staDev = wifi.Install (wifiPhy, wifiMac, sta);
staInterface = ip.Assign (staDev);
// save everything in containers.
staNodes.push_back (sta);
apDevices.push_back (apDev);
apInterfaces.push_back (apInterface);
staDevices.push_back (staDev);
staInterfaces.push_back (staInterface);
}
void Experiment::installApps(Ptr< Node > from, Ptr< Node > to, Ipv4Address destIp, uint32_t trafficType)
{
uint16_t port = 12345;
Address dest = InetSocketAddress (destIp, port);
//UniformVariable uv;
Time st = Seconds (SIM_START_TIME); // + MilliSeconds (uv.GetValue (0.0, 500.0));
//std::ostringstream rate;
switch (trafficType)
{
case TRAF_TYPE_CBR:
default:
{
PacketSinkHelper sinkHelper ("ns3::UdpSocketFactory",
InetSocketAddress (Ipv4Address::GetAny (), port));
ApplicationContainer sinkApp = sinkHelper.Install (to);
sinkApp.Start (Seconds (SIM_START_TIME));
sinkApp.Stop (Seconds (SIM_DURATION));
OnOffHelper onoff = OnOffHelper ("ns3::UdpSocketFactory", dest);
// rate << 200000 + uv.GetInteger (0, 1000) << "bps";
onoff.SetConstantRate (DataRate ("200Kbps"), 512);
ApplicationContainer apps = onoff.Install (from);
apps.Start (st);
apps.Stop (Seconds (SIM_DURATION));
break;
}
case TRAF_TYPE_BURST:
{
PacketSinkHelper sinkHelper ("ns3::TcpSocketFactory",
InetSocketAddress (Ipv4Address::GetAny (), port));
ApplicationContainer sinkApp = sinkHelper.Install (to);
sinkApp.Start (Seconds (SIM_START_TIME));
sinkApp.Stop (Seconds (SIM_DURATION));
OnOffHelper clientHelper ("ns3::TcpSocketFactory", dest);
clientHelper.SetAttribute ("OnTime", StringValue ("ns3::NormalRandomVariable[Mean=1.0|Variance=0.5]"));
clientHelper.SetAttribute ("OffTime", StringValue ("ns3::UniformRandomVariable[Min=2.0|Max=5.0]"));
//rate << 400000 + uv.GetInteger (0, 1000) << "bps";
clientHelper.SetConstantRate (DataRate ("400Kbps"), 1500);
ApplicationContainer clientApps;
clientApps = clientHelper.Install (from);
clientApps.Start (st);
clientApps.Stop (Seconds (SIM_DURATION));
break;
}
}
}
void Experiment::getStats(FlowMonitorHelper& helper, Ipv4Address closestAddress, Ipv4Address fartherstAddress, uint32_t nStas)
{
uint64_t allRxBytes = 0, closestRxBytes = 0, fartherstRxBytes = 0;
uint32_t allRxPackets = 0, closestRxPackets = 0, fartherstRxPackets = 0;
uint32_t allTxPackets = 0, closestTxPackets = 0, fartherstTxPackets = 0;
Time allDelaySum(0), closestDelaySum(0), fartherstDelaySum(0);
helper.GetMonitor ()->CheckForLostPackets ();
Ptr<Ipv4FlowClassifier> classifier = DynamicCast<Ipv4FlowClassifier> (helper.GetClassifier ());
std::map<FlowId, FlowMonitor::FlowStats> stats = helper.GetMonitor ()->GetFlowStats ();
for (std::map<FlowId, FlowMonitor::FlowStats>::const_iterator i = stats.begin (); i != stats.end (); ++i)
{
Ipv4FlowClassifier::FiveTuple t = classifier->FindFlow (i->first);
allRxBytes += i->second.rxBytes;
allRxPackets += i->second.rxPackets;
allTxPackets += i->second.txPackets;
allDelaySum += i->second.delaySum;
if (t.sourceAddress == closestAddress || t.destinationAddress == closestAddress)
{
closestRxBytes += i->second.rxBytes;
closestRxPackets += i->second.rxPackets;
closestTxPackets += i->second.txPackets;
closestDelaySum += i->second.delaySum;
}
if (t.sourceAddress == fartherstAddress || t.destinationAddress == fartherstAddress)
{
fartherstRxBytes += i->second.rxBytes;
fartherstRxPackets += i->second.rxPackets;
fartherstTxPackets += i->second.txPackets;
fartherstDelaySum += i->second.delaySum;
}
}
double closestLoss = (closestTxPackets == 0) ? 0.0 :
100 * (1.0 - ((double) closestRxPackets) / ((double) closestTxPackets));
double closestDelay = (closestRxPackets == 0) ? 0.0 :
((double) closestDelaySum.GetMilliSeconds ()) / ((double) closestRxPackets);
double closestThroughput = closestRxBytes * 8.0 / (SIM_DURATION * 1000.0);
double allLoss = (allTxPackets == 0) ? 0.0 :
100 * (1.0 - ((double) allRxPackets) / ((double) allTxPackets));
double allDelay = (allRxPackets == 0) ? 0.0 :
((double) allDelaySum.GetMilliSeconds ()) / ((double) allRxPackets);
double allThroughput = allRxBytes * 8.0 / (SIM_DURATION * 1000.0 * stats.size());
double fartherstLoss = (fartherstTxPackets == 0) ? 0.0 :
100 * (1.0 - ((double) fartherstRxPackets) / ((double) fartherstTxPackets));
double fartherstDelay = (fartherstRxPackets == 0) ? 0.0 :
((double) fartherstDelaySum.GetMilliSeconds ()) / ((double) fartherstRxPackets);
double fartherstThroughput = fartherstRxBytes * 8.0 / (SIM_DURATION * 1000.0);
closestLossSamples.Update (closestLoss);
allLossSamples.Update (allLoss);
fartherstLossSamples.Update (fartherstLoss);
closestDelaySamples.Update (closestDelay);
allDelaySamples.Update (allDelay);
fartherstDelaySamples.Update (fartherstDelay);
closestThroughputSamples.Update (closestThroughput);
allThroughputSamples.Update (allThroughput);
fartherstThroughputSamples.Update (fartherstThroughput);
}
void
Experiment::RunOneSample (uint32_t sample, uint32_t nStas, uint32_t mobLevel, uint32_t trafficType, uint32_t enablePcap)
{
std::ostringstream pref;
pref << DATA_PATH << MODULE_NAME << "-" << nStas * NUM_WIFIS << "-mob-" << mobLevel << "-traf-" << trafficType << "-samp-" << sample;
pcapPrefix = pref.str ();
NodeContainer term;
term.Create (1);
NodeContainer router;
router.Create (1);
InternetStackHelper stack;
stack.Install (term);
stack.Install (router);
Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.255.0");
NetDeviceContainer p2pDevices;
p2pDevices = connectP2pNodes (term.Get (0), router.Get (0));
Ipv4InterfaceContainer p2pInterfaces;
p2pInterfaces = address.Assign (p2pDevices);
NodeContainer apNodes;
apNodes.Create (NUM_WIFIS);
stack.Install (apNodes);
CsmaHelper csma;
NodeContainer backboneNodes;
backboneNodes.Add (router);
backboneNodes.Add (apNodes);
NetDeviceContainer backboneDevices;
backboneDevices = csma.Install (backboneNodes);
Ipv4AddressHelper ip;
ip.SetBase ("10.2.1.0", "255.255.255.0");
NetDeviceContainer routerCsmaDev;
routerCsmaDev.Add (backboneDevices.Get (0));
ip.Assign (routerCsmaDev);
//csma.EnablePcap (pcapPrefix, backboneDevices.Get (0));
YansWifiPhyHelper wifiPhy = YansWifiPhyHelper::Default ();
YansWifiChannelHelper wifiChannelFactory = YansWifiChannelHelper::Default ();
Ptr< YansWifiChannel > wifiChannel = wifiChannelFactory.Create ();
// setup mobility model for APs
Ptr<ListPositionAllocator> positionAlloc = CreateObject<ListPositionAllocator> ();
positionAlloc->Add (Vector (0.0, AP_RANGE / 4, 0.0));
positionAlloc->Add (Vector (1.5 * AP_RANGE, AP_RANGE / 4, 0.0));
MobilityHelper mobility;
mobility.SetPositionAllocator (positionAlloc);
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install (apNodes);
for (uint32_t i = 0; i < NUM_WIFIS; i++)
{
createBss (wifiPhy, wifiChannel, apNodes.Get (i), router.Get (0),
i, nStas, ip, mobLevel, enablePcap);
}
// Ptr< Node > closestSta = staNodes[0].Get (0);
// Ptr< Node > fartherstSta = staNodes[0].Get (nStas - 1);
// installApps (term.Get (0), closestSta, staInterfaces[0].GetAddress (0), trafficType);
// installApps (term.Get (0), fartherstSta, staInterfaces[0].GetAddress (nStas - 1), trafficType);
// installApps (staNodes[1].Get (0), term.Get (0), p2pInterfaces.GetAddress (0), trafficType);
//installApps (staNodes[1].Get (nStas - 1), term.Get (0), p2pInterfaces.GetAddress (0), trafficType);
for (uint32_t i = 0; i < nStas; i++)
{
installApps (term.Get (0), staNodes[0].Get (i), staInterfaces[0].GetAddress (i), trafficType);
installApps (term.Get (0), staNodes[1].Get (i), staInterfaces[1].GetAddress (i), trafficType);
}
Ipv4GlobalRoutingHelper::PopulateRoutingTables ();
//wifiPhy.EnablePcap (pcapPrefix, apDevices[0].Get (0));
FlowMonitorHelper fmHelper;
fmHelper.InstallAll ();
Simulator::Stop (Seconds (SIM_DURATION));
Simulator::Run ();
getStats (fmHelper, staInterfaces[0].GetAddress (0), staInterfaces[0].GetAddress (nStas - 1), nStas);
staNodes.clear ();
apDevices.clear ();
apInterfaces.clear ();
staDevices.clear ();
staInterfaces.clear ();
Simulator::Destroy ();
}
void
Experiment::AddDataPoint(uint32_t totalStas, Gnuplot2dDataset& dataSet, Average< double >& samples)
{
dataSet.Add (totalStas, samples.Avg (), samples.Error95 ());
}
void
Experiment::RunOnePass (uint32_t nStas, uint32_t mobLevel, uint32_t trafficType, uint32_t enablePcap)
{
closestLossSamples.Reset ();
allLossSamples.Reset ();
fartherstLossSamples.Reset ();
closestDelaySamples.Reset ();
allDelaySamples.Reset ();
fartherstDelaySamples.Reset ();
closestThroughputSamples.Reset ();
allThroughputSamples.Reset ();
fartherstThroughputSamples.Reset ();
for (uint32_t i = 1; i <= NUM_SAMPLES; i++)
{
RunOneSample(i, nStas, mobLevel, trafficType, enablePcap);
}
std::cout << "\nNumber of wireless stations: " << nStas * NUM_WIFIS << std::endl;
std::cout << "Closest\n";
std::cout << " Loss: " << closestLossSamples.Avg ()
<< "% (error=" << closestLossSamples.Error95 () << ")\n";
std::cout << " Delay: " << closestDelaySamples.Avg ()
<< " ms (error=" << closestDelaySamples.Error95 () << ")\n";
std::cout << " Throughput: " << closestThroughputSamples.Avg ()
<< " Kibps (error=" << closestThroughputSamples.Error95 () << ")\n";
std::cout << "Average\n";
std::cout << " Loss: " << allLossSamples.Avg ()
<< "% (error=" << allLossSamples.Error95 () << ")\n";
std::cout << " Delay: " << allDelaySamples.Avg ()
<< " ms (error=" << allDelaySamples.Error95 () << ")\n";
std::cout << " Throughput: " << allThroughputSamples.Avg ()
<< " Kibps (error=" << allThroughputSamples.Error95 () << ")\n";
std::cout << "Fartherst\n";
std::cout << " Loss: " << fartherstLossSamples.Avg ()
<< "% (error=" << fartherstLossSamples.Error95 () << ")\n";
std::cout << " Delay: " << fartherstDelaySamples.Avg ()
<< " ms (error=" << fartherstDelaySamples.Error95 () << ")\n";
std::cout << " Throughput: " << fartherstThroughputSamples.Avg ()
<< " Kibps (error=" << fartherstThroughputSamples.Error95 () << ")\n";
uint32_t totalStas = nStas * 2;
AddDataPoint (totalStas, closestLossDataSet, closestLossSamples);
AddDataPoint (totalStas, allLossDataSet, allLossSamples);
AddDataPoint (totalStas, fartherstLossDataSet, fartherstLossSamples);
AddDataPoint (totalStas, closestDelayDataSet, closestDelaySamples);
AddDataPoint (totalStas, allDelayDataSet, allDelaySamples);
AddDataPoint (totalStas, fartherstDelayDataSet, fartherstDelaySamples);
AddDataPoint (totalStas, closestThroughputDataSet, closestThroughputSamples);
AddDataPoint (totalStas, allThroughputDataSet, allThroughputSamples);
AddDataPoint (totalStas, fartherstThroughputDataSet, fartherstThroughputSamples);
}
void
Experiment::Run (uint32_t mobLevel, uint32_t trafficType, uint32_t enablePcap)
{
std::cout << "mobLevel=" << mobLevel
<< ", trafficType=" << trafficType
<< ", duration of sample=" << SIM_DURATION << "s"
<< ", AP range=" << AP_RANGE << "m"
<< ", #samples=" << NUM_SAMPLES
<< ", enablePcap=" << enablePcap
<< std::endl;
for (uint32_t nStas = MIN_STAS; nStas <= MAX_STAS; nStas += STA_INCR)
{
RunOnePass(nStas, mobLevel, trafficType, enablePcap);
}
std::ostringstream lossFileName;
lossFileName << DATA_PATH << "mo818-loss-mob-" << mobLevel << "-traf-" << trafficType << ".dat";
std::ofstream lossFile (lossFileName.str ().c_str ());
lossPlot.GenerateOutput (lossFile);
std::ostringstream delayFileName;
delayFileName << DATA_PATH << "mo818-delay-mob-" << mobLevel << "-traf-" << trafficType << ".dat";
std::ofstream delayFile (delayFileName.str ().c_str ());
delayPlot.GenerateOutput (delayFile);
std::ostringstream throughputFileName;
throughputFileName << DATA_PATH << "mo818-throughput-mob-" << mobLevel << "-traf-" << trafficType << ".dat";
std::ofstream throughputFile (throughputFileName.str ().c_str ());
throughputPlot.GenerateOutput (throughputFile);
}
int main (int argc, char *argv[])
{
uint32_t mobLevel = 9999;
uint32_t trafficType = 9999;
uint32_t enablePcap = 1;
CommandLine cmd;
cmd.AddValue ("mobLevel", "Mobility level [LOW(0), MED(1), HIGH(2)], default=LOW(0)", mobLevel);
cmd.AddValue ("trafficType", "Traffic type [CBR(0), BURST(1)], default=CBR", trafficType);
cmd.AddValue ("enablePcap", "Enable .pcap generation [no(0), yes(1)], default=yes(1)", enablePcap);
cmd.Parse (argc, argv);
if (mobLevel < MOB_LEVEL_LOW || mobLevel > MOB_LEVEL_HIGH ||
trafficType < TRAF_TYPE_CBR || trafficType > TRAF_TYPE_BURST)
{
for (mobLevel = MOB_LEVEL_LOW; mobLevel <= MOB_LEVEL_HIGH; mobLevel++)
{
for (trafficType = TRAF_TYPE_CBR; trafficType <= TRAF_TYPE_BURST; trafficType++)
{
Experiment experiment(mobLevel, trafficType);
experiment.Run(mobLevel, trafficType, enablePcap);
}
}
}
else
{
Experiment experiment(mobLevel, trafficType);
experiment.Run(mobLevel, trafficType, enablePcap);
}
}
|
#ifndef SHOC_XOODYAK_H
#define SHOC_XOODYAK_H
#include "shoc/util.h"
namespace shoc {
struct Xoodyak {
using word = uint32_t;
static constexpr size_t SIZE = 32;
void init();
void feed(const void *in, size_t len);
void stop(byte *out, size_t len = SIZE);
void operator()(const void *in, size_t len, byte *out, size_t out_len = SIZE);
private:
};
void Xoodyak::init()
{
}
}
#endif
|
// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ORBIT_LINUX_TRACING_PERF_EVENT_PROCESSOR_H_
#define ORBIT_LINUX_TRACING_PERF_EVENT_PROCESSOR_H_
#include <ctime>
#include <memory>
#include <queue>
#include "PerfEvent.h"
#include "PerfEventVisitor.h"
#include "absl/container/flat_hash_map.h"
namespace LinuxTracing {
// This class implements a data structure that holds a large number of different
// perf_event_open records coming from multiple ring buffers, and allows reading
// them in order (oldest first).
// Instead of keeping a single priority queue with all the events to process,
// on which push/pop operations would be logarithmic in the number of events,
// we leverage the fact that events coming from the same perf_event_open ring
// buffer are already sorted. We then keep a priority queue of queues, where
// the events in each queue come from the same ring buffer. Whenever an event
// is removed from a queue, we need to move such queue down the priority
// queue. As std::priority_queue does not support decreasing the priority of
// an element, we achieve this by removing and re-inserting.
// In order to be able to add an event to a queue, we also need to maintain
// the association between a queue and its ring buffer. We use the file
// descriptor used to read from the ring buffer as identifier for a ring
// buffer. Keeping this association is what the pairs and the map are for.
// TODO: Implement a custom priority queue that supports decreasing the
// priority.
class PerfEventQueue {
public:
void PushEvent(int origin_fd, std::unique_ptr<PerfEvent> event);
bool HasEvent();
PerfEvent* TopEvent();
std::unique_ptr<PerfEvent> PopEvent();
private:
// Comparator for the priority queue: pop will return the queue associated
// with the file descriptor from which the oldest event still to process
// originated.
struct QueueFrontTimestampReverseCompare {
bool operator()(
const std::pair<int, std::shared_ptr<std::queue<std::unique_ptr<PerfEvent>>>>& lhs,
const std::pair<int, std::shared_ptr<std::queue<std::unique_ptr<PerfEvent>>>>& rhs) {
return lhs.second->front()->GetTimestamp() > rhs.second->front()->GetTimestamp();
}
};
std::priority_queue<
std::pair<int, std::shared_ptr<std::queue<std::unique_ptr<PerfEvent>>>>,
std::vector<std::pair<int, std::shared_ptr<std::queue<std::unique_ptr<PerfEvent>>>>>,
QueueFrontTimestampReverseCompare>
event_queues_queue_{};
absl::flat_hash_map<int, std::shared_ptr<std::queue<std::unique_ptr<PerfEvent>>>>
fd_event_queues_{};
};
// This class receives perf_event_open events coming from several ring buffers
// and processes them in order according to their timestamps.
// Its implementation builds on the assumption that we never expect events with
// a timestamp older than PROCESSING_DELAY_MS to be added. By not processing
// events that are not older than this delay, we will never process events out
// of order.
class PerfEventProcessor {
public:
// Do not process events that are more recent than 0.1 seconds. There could be
// events coming out of order as they are read from different perf_event_open
// ring buffers and this ensure that all events are processed in the correct
// order.
static constexpr uint64_t PROCESSING_DELAY_MS = 100;
explicit PerfEventProcessor(std::unique_ptr<PerfEventVisitor> visitor)
: visitor_(std::move(visitor)) {}
void AddEvent(int origin_fd, std::unique_ptr<PerfEvent> event);
void ProcessAllEvents();
void ProcessOldEvents();
private:
PerfEventQueue event_queue_;
std::unique_ptr<PerfEventVisitor> visitor_;
#ifndef NDEBUG
uint64_t last_processed_timestamp_ = 0;
#endif
};
} // namespace LinuxTracing
#endif // ORBIT_LINUX_TRACING_PERF_EVENT_PROCESSOR_H_
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "GridContainer.h"
#include "GameGridBase.generated.h"
UCLASS()
class NEWTD_API AGameGridBase : public AActor
{
GENERATED_BODY()
protected:
UPROPERTY(BlueprintReadWrite, EditAnywhere)
int z_offset;
UPROPERTY(BlueprintReadWrite, EditAnywhere)
int dx;
UPROPERTY(BlueprintReadWrite, EditAnywhere)
int ux;
UPROPERTY(BlueprintReadWrite, EditAnywhere)
int ly;
UPROPERTY(BlueprintReadWrite, EditAnywhere)
int ry;
UPROPERTY(BlueprintReadWrite, EditAnywhere)
int gap;
UPROPERTY(BlueprintReadWrite, EditAnywhere)
bool use_ZO;
UPROPERTY(BlueprintReadWrite, EditAnywhere)
TArray<FVector> grid_poses; //x and y poses, z set to 0;
UPROPERTY(BlueprintReadWrite, EditAnywhere)
int rows;
UPROPERTY(BlueprintReadWrite, EditAnywhere)
int cols;
UPROPERTY(BlueprintReadWrite, EditAnywhere)
TMap<FString, AGridContainer*> container_pool;
UPROPERTY(BlueprintReadWrite, EditAnywhere)
AActor* conatiner_parent_ACT;
/// <summary>
/// Generate grid_poses from dx, ux ...
/// </summary>
UFUNCTION(BlueprintCallable)
bool Grid_pos_generator();
/// <summary>
/// Calculate the total row and col numbers.
/// </summary>
UFUNCTION(BlueprintCallable)
void Grid_row_col_num_cal();
virtual int Grid_axis_cal(int val, int small_border);
virtual int Grid_axis_to_rc(int val, int small_border);
virtual FString CoordToString(int x, int y);
virtual FString CoordToString_pos(FVector pos);
virtual AGridContainer* Spawn_one_conatiner(class TSubclassOf<AGridContainer> cont_prefab,
const FVector* pos);
public:
// Sets default values for this actor's properties
AGameGridBase();
/// <summary>
/// Assign the variables;
/// </summary>
UFUNCTION(BlueprintCallable)
bool InitGrid(int _z_offset, int _ly, int _ry, int _dx, int _ux, int _gap,
bool _use_ZO);
/// <summary>
/// Transfer a position to nearest grid position.
/// </summary>
UFUNCTION(BlueprintCallable)
virtual FVector Grid_pos_cal(const FVector& pos);
/// <summary>
/// Grid_pos_cal with z offset.
/// </summary>
UFUNCTION(BlueprintCallable)
virtual FVector Grid_pos_cal_ZO(const FVector& pos, bool use_offset);
/// <summary>
/// Implement in the blueprint.
/// </summary>
UFUNCTION(BlueprintImplementableEvent)
FVector Editor_grid_pos_cal(const FVector& pos);
/// <summary>
/// Spawn containers from prefab class.
/// </summary>
UFUNCTION(BlueprintCallable)
virtual bool Spawn_containers(class TSubclassOf<AGridContainer> cont_prefab,
int _z_offset);
/// <summary>
/// Spawn containers with boundaries.
/// </summary>
UFUNCTION(BlueprintCallable)
virtual bool Spawn_containers_bound(class TSubclassOf<AGridContainer> cont_prefab,
int left_bound, int right_bound, int up_bound, int low_bound, int _z_offset);
/// <summary>
/// Clear the container_pool and destroy the actors.
/// </summary>
UFUNCTION(BlueprintCallable)
virtual bool Clear_containers();
/// <summary>
/// Clear grid_poses;
/// </summary>
UFUNCTION(BlueprintCallable)
virtual bool Clear_poses();
/// <summary>
/// Get next row position from current position.
/// </summary>
UFUNCTION(BlueprintCallable)
virtual FVector Get_next_row_pos(const FVector& pos, MapDirection dir);
/// <summary>
/// Get next row position from current position.
/// </summary>
UFUNCTION(BlueprintCallable)
virtual FVector Get_next_col_pos(const FVector& pos, MapDirection dir);
/// <summary>
/// Calculate the current position to the nearest row can col indexes.
/// </summary>
UFUNCTION(BlueprintCallable)
void Pos_to_rc(const FVector& pos, int& r, int & c);
/// <summary>
/// Get grid position from row col indexes, No z position;
/// </summary>
UFUNCTION(BlueprintCallable)
FVector Row_col_to_pos(int r, int c);
/// <summary>
/// Get all grid_poses indexes from given row.
/// </summary>
UFUNCTION(BlueprintCallable)
TArray<int> Get_all_indexes_in_row(int r);
/// <summary>
/// Get all grid_poses indexes from given col.
/// </summary>
UFUNCTION(BlueprintCallable)
TArray<int> Get_all_indexes_in_col(int c);
/// <summary>
/// Get all containers in current row.
/// </summary>
/// <returns></returns>
UFUNCTION(BlueprintCallable)
TArray<AGridContainer*> Get_row_containers(int r);
/// <summary>
/// Get all containers in next row with current position.
/// </summary>
/// <returns></returns>
UFUNCTION(BlueprintCallable)
TArray<AGridContainer*> Get_next_row_containers(const FVector& pos, MapDirection dir);
/// <summary>
/// Get container object from world position.
/// </summary>
UFUNCTION(BlueprintCallable)
AGridContainer* Get_container_from_pos(const FVector& pos);
/// <summary>
/// Add building to container based on world position;
/// </summary>
UFUNCTION(BlueprintCallable)
bool Add_building_to_container(const FVector& pos, AUnit* _building);
TArray<FVector>* Get_grid_posos();
int Get_rows();
int Get_cols();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
};
|
#include <cassert>
#include <iostream>
#include <vector>
using namespace std;
int countPairs(vector<int>& nums, vector<int>& aux, int l, int mid, int r) {
for (int i = l; i <= r; ++i) {
aux[i] = nums[i];
}
int result = 0;
int i = l;
int j = mid + 1;
for (int k = l; k <= r; ++k) {
if (i > mid)
nums[k] = aux[j++];
else if (j > r)
nums[k] = aux[i++];
else if (aux[i] < aux[j]) {
nums[k] = aux[i++];
} else {
result += mid - i + 1;
nums[k] = aux[j++];
}
}
return result;
}
int _reversePairs(vector<int>& nums, vector<int>& aux, int l, int r) {
if (l >= r) return 0;
int result = 0;
int mid = l + (r - l) / 2;
result += _reversePairs(nums, aux, l, mid);
result += _reversePairs(nums, aux, mid + 1, r);
if (nums[mid] > nums[mid + 1]) {
result += countPairs(nums, aux, l, mid, r);
}
return result;
}
int reversePairs(vector<int>& nums) {
vector<int> aux(nums.size());
return _reversePairs(nums, aux, 0, nums.size() - 1);
}
int main() {
vector<int> nums = {7, 5, 6, 4};
assert(reversePairs(nums) == 5);
return 0;
}
|
#ifndef __LTabelView__LyfTableView__
#define __LTabelView__LyfTableView__
#include "publicDef/PublicDef.h"
#include "LyfIndicator.h"
#include "LyfIndexPath.h"
#include "LyfTableViewCell.h"
typedef enum {
TableViewEditNone = 0,
TableViewEdit
}TableViewEditState;
class LyfTableView;
class LyfTableViewCell;
class LyfIndexPath;
class LyfTableViewDelegate
{
public:
//cell选中代理回调
virtual void tableCellTouched(LyfTableView* table, LyfTableViewCell* cell, unsigned int idx){};
//多选时,点击已经选中的cell时取消选中状态代理回调
virtual void tableCellNoTouched(LyfTableView* table, LyfTableViewCell* cell, unsigned int idx){};
//点击cell的ImageView时代理会掉
virtual void tableCellImageViewTouchUpInSide(LyfTableView* table, LyfTableViewCell* cell, unsigned int idx){};
//翻页是回调,可用此回调方法更新显示页
virtual void tableViewUpdate(LyfTableView* table){};
virtual bool removeTableCell(LyfTableView* table, LyfTableViewCell* cell, unsigned int idx){return false;}
};
class LyfTableViewDataSource
{
public:
//init cell callback
virtual LyfTableViewCell* tableCellAtIndex(LyfTableView *table, unsigned int idx) = 0;
//get cell total num
virtual unsigned int numberfRowsInTableView(LyfTableView *table) = 0;
void removeDelegate(LyfTableView* table);
};
class LyfTableView:
public LayerColor,
public LyfTableViewCellDelegate
{
LyfTableViewDataSource* m_pDataSource;
LyfTableViewDelegate* m_pTableViewDelegate;
Node* m_backNode;
LyfIndicator* m_indicator;
float m_nIndicator_offX;
float m_nIndicator_scaleX;
int m_numOfRows;
vector<LyfTableViewCell*> m_TableViewCells;
vector<LyfIndexPath> m_SelectedIndexPaths;
vector<LyfIndexPath> m_DisabledIndexPaths;
void cellGoHome(float dt);
Point getHomeFromCellPos();
Point getFirmFromCellPos();
//void visit();
void visit(Renderer* renderer, const Mat4 &parentTransform, uint32_t parentFlags);
Rect getRect();
//int m_nTouchPriority;
// bool m_IsRehisterTouchDispatcher;
void registerTouch();
void unRegisterTouch();
void setTableViewCells();
void updateTableViewCellPos();
void setIndicator();
void updateIndicator();
void setPullShow();
void updatePullShow();
void pullDownShow();
void pullUpShow();
void PullShowHideFalse();
void update(float delta);
void updatePitchOn();
ActionInterval* cellAction(Point point, float time=0.25f);
protected:
virtual void onExit();
virtual void onEnter();
virtual bool onTouchBegan(Touch *pTouch, Event *pEvent);
virtual void onTouchMoved(Touch *pTouch, Event *pEvent);
virtual void onTouchEnded(Touch *pTouch, Event *pEvent);
virtual void onTouchCancelled(Touch *pTouch, Event *pEvent);
Point m_touchBeginUIPoint;
public:
LyfTableView();
virtual ~LyfTableView();
static LyfTableView* create(float contentSizeHeight);
bool initWithTableView(float contentSizeHeight);
void setContentSizeHeight(float contentSizeHeight);
//可设置右侧指示条x轴偏移
void setIndicatorPointOff(float offX);
//可设置右侧指示条x轴缩放值
void setIndicatorScaleX(float scaleX);
//数据代理
void setTableViewDataSource(LyfTableViewDataSource* node);
//可扩展功能代理,如touch事件
void setTableViewDelegate(LyfTableViewDelegate* node);
//获取当前处于第几页
int getPage();
//设置要翻到第几页
void setPage(const int page);
//获取总页数
int getMaxPage();
//刷新tableView,传入flase不回到起始位置
void readData(bool flag = true);
public:
//获取cell总数
int getNumberOfRows();
//
float getRowHight(unsigned int idx);
//获取tableView高度
float getTableViewHight();
//获取tableView的父节点
Node* getNode();
//获取当前选中的cell数
int getSelectedCountInCurrent();
//根据在tableView中的位置获取tableViewCell
LyfTableViewCell* getTableViewCellAtIndex(int idx);
//设置cell位置偏移
void setNodePosY(float y);
//传入被选中Cell的LyfIndexPath数组,让部分cell被选中
void setSelectedArray(CCArray *array);
//传入被选中Cell的LyfIndexPath数组,让部分cell不可点击
void setNoClickOtherArray(CCArray* array);
//取消某个cell的选中状态
void setNoPitchOnOfArray(LyfTableViewCell* cell);
LyfTableViewCell* insertTableCellAtIndex(unsigned int idx);
LyfTableViewCell* insertFirstTableCell();
LyfTableViewCell* insertLastTableCell();
void removeTableCellAtIndex(unsigned int idx, bool actions=false);
void removeFirstTableCell(bool actions=false);
void removeLastTableCell(bool actions=false);
void replaceTableCellAtIndex(unsigned int idx);
void exchangeTableCellAtIndex(unsigned int idx1, unsigned int idx2);
//设置tableView触摸优先级,可随时设置
//void setPriority(int nPriority);
void setOpacity(GLubyte opacity);
public:
//tableView编辑状态开关,目前支持滑动删除某个cell
CC_SYNTHESIZE(bool, m_nEdit, Edit);
//tableView滑动回弹开关
CC_SYNTHESIZE(bool, m_IsCanSkip, CanSkip);
//tableView滑动开关
CC_SYNTHESIZE(bool, m_IsTouchMoved, TouchMoved);
//设置tableView每页最大cell数,默认为30
CC_SYNTHESIZE(int, m_maxNumberOfPages, MaxNumberOfPages);
//设置tableView最大可选cell数
CC_PROPERTY(int, m_selectedCount, SelectedCount);
private:
void setTouchPitchOn(LyfTableViewCell* cell);
void setTouchImageView(LyfTableViewCell* cell);
void removeTableCell(LyfTableViewCell* cell);
void joinEditing(LyfTableViewCell* cell);
bool m_IsRunning;
int m_CellEditing;
bool isEditing();
bool isCanEdit();
void closeEditing();
bool isCanSelected();
std::deque<Point> m_nPointOffset;
float m_nInertiaLength;
void inertia(float dt);
int m_page;
int m_maxPage;
float m_sizeHeight;
void reLoadData();
void readDataInTurnLastPage(float dt);
void readDataInTurnNextpage(float dt);
void turnLastpage();
void turnNextPage();
bool isTurnLastPage();
bool isTurnNextPage();
Sprite* pullUpShowSprite;
Sprite* pullDownShowSprite;
};
#endif /* defined(__LTabelView__LyfTableView__) */
|
#include "qfont.h"
namespace qEngine
{
qFont::qFont(void)
{
}
bool qFont::loadResource(string strName)
{
string strINIFile = strName.substr(0, (strName.length() - 4));
strINIFile += ".ini";
if(m_sFontInfo.s_CMFontWidth.loadValuesFromFile(strINIFile))
{
m_sFontInfo.s_strFilename = strName;
return true;
}
return false;
}
bool qFont::unloadResource()
{
m_sFontInfo.s_CMFontWidth.clearValues();
return true;
}
qFont::~qFont(void)
{
}
}
|
#pragma once
#include <QWidget>
namespace Ui {
class PassedTestsForm;
}
class PassedTest;
class PassedTestsModel;
class PassedTestsForm : public QWidget {
Q_OBJECT
public:
explicit PassedTestsForm(QWidget *parent = nullptr);
~PassedTestsForm();
PassedTestsModel *getModel() const;
void setModel(PassedTestsModel *model);
public slots:
void startUpdating();
void stopUpdating();
signals:
void backButtonClicked();
void passedTestSelected(int id);
void passedTestSelected(const PassedTest &passedTest);
void error(const QString &errorMessage);
private slots:
void onPassedTestDoubleClicked(const QModelIndex &index);
private:
PassedTestsModel *m_model;
Ui::PassedTestsForm *ui;
};
|
// Created on: 2001-07-25
// Created by: Julia DOROVSKIKH
// Copyright (c) 2001-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 _XmlLDrivers_DocumentRetrievalDriver_HeaderFile
#define _XmlLDrivers_DocumentRetrievalDriver_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <XmlObjMgt_RRelocationTable.hxx>
#include <TCollection_ExtendedString.hxx>
#include <PCDM_RetrievalDriver.hxx>
#include <XmlObjMgt_Element.hxx>
#include <Standard_Integer.hxx>
#include <Storage_Data.hxx>
class XmlMDF_ADriverTable;
class CDM_Document;
class CDM_Application;
class Message_Messenger;
class XmlMDF_ADriver;
class XmlLDrivers_DocumentRetrievalDriver;
DEFINE_STANDARD_HANDLE(XmlLDrivers_DocumentRetrievalDriver, PCDM_RetrievalDriver)
class XmlLDrivers_DocumentRetrievalDriver : public PCDM_RetrievalDriver
{
public:
Standard_EXPORT XmlLDrivers_DocumentRetrievalDriver();
Standard_EXPORT virtual void Read (const TCollection_ExtendedString& theFileName,
const Handle(CDM_Document)& theNewDocument,
const Handle(CDM_Application)& theApplication,
const Handle(PCDM_ReaderFilter)& theFilter = Handle(PCDM_ReaderFilter)(),
const Message_ProgressRange& theRange = Message_ProgressRange()) Standard_OVERRIDE;
Standard_EXPORT virtual void Read (Standard_IStream& theIStream,
const Handle(Storage_Data)& theStorageData,
const Handle(CDM_Document)& theDoc,
const Handle(CDM_Application)& theApplication,
const Handle(PCDM_ReaderFilter)& theFilter = Handle(PCDM_ReaderFilter)(),
const Message_ProgressRange& theRange= Message_ProgressRange()) Standard_OVERRIDE;
Standard_EXPORT virtual Handle(XmlMDF_ADriverTable) AttributeDrivers (const Handle(Message_Messenger)& theMsgDriver);
DEFINE_STANDARD_RTTIEXT(XmlLDrivers_DocumentRetrievalDriver,PCDM_RetrievalDriver)
protected:
Standard_EXPORT virtual void ReadFromDomDocument (const XmlObjMgt_Element& theDomElement,
const Handle(CDM_Document)& theNewDocument,
const Handle(CDM_Application)& theApplication,
const Message_ProgressRange& theRange = Message_ProgressRange());
Standard_EXPORT virtual Standard_Boolean MakeDocument (const XmlObjMgt_Element& thePDoc,
const Handle(CDM_Document)& theTDoc,
const Message_ProgressRange& theRange = Message_ProgressRange());
Standard_EXPORT virtual Handle(XmlMDF_ADriver) ReadShapeSection
(const XmlObjMgt_Element& thePDoc,
const Handle(Message_Messenger)& theMsgDriver,
const Message_ProgressRange& theRange = Message_ProgressRange());
Standard_EXPORT virtual void ShapeSetCleaning (const Handle(XmlMDF_ADriver)& theDriver);
Handle(XmlMDF_ADriverTable) myDrivers;
XmlObjMgt_RRelocationTable myRelocTable;
TCollection_ExtendedString myFileName;
private:
};
#endif // _XmlLDrivers_DocumentRetrievalDriver_HeaderFile
|
#include "Barrel.hpp"
#include <iostream>
Barrel::Barrel(float headRadius, float bellyRadius, float height, Color color, Material material)
: Object(Transform(), color, material)
{
this->headRadius = headRadius;
this->bellyRadius = bellyRadius;
this->height = height;
barrelTextureName = 0;
woodTextureName = 0;
quad = gluNewQuadric();
}
Barrel::~Barrel() { gluDeleteQuadric(quad); }
void Barrel::drawObject()
{
// Top half
if (barrelTextureName != 0 && drawTexture) {
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, barrelTextureName);
gluQuadricDrawStyle(quad, GLU_FILL);
gluQuadricNormals(quad, GLU_SMOOTH);
gluQuadricTexture(quad, GL_TRUE);
}
glPushMatrix();
glRotatef(270, 1, 0, 0);
gluCylinder(quad, bellyRadius, headRadius, height / 2, slices, stacks);
glPopMatrix();
// Bottom half
glPushMatrix();
glRotatef(90, 1, 0, 0);
gluCylinder(quad, bellyRadius, headRadius, height / 2, slices, stacks);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
gluQuadricTexture(quad, GL_FALSE);
if (woodTextureName != 0 && drawTexture) {
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, woodTextureName);
gluQuadricDrawStyle(quad, GLU_FILL);
gluQuadricNormals(quad, GLU_SMOOTH);
gluQuadricTexture(quad, GL_TRUE);
}
// Top lid
glPushMatrix();
glTranslatef(0, height / 2, 0);
glRotatef(270, 1, 0, 0);
gluDisk(quad, 0, headRadius, slices, 1);
glPopMatrix();
// Bottom lid
glPushMatrix();
glTranslatef(0, -height / 2, 0);
glRotatef(90, 1, 0, 0);
gluDisk(quad, 0, headRadius, slices, 1);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
gluQuadricTexture(quad, GL_FALSE);
}
void Barrel::update(float deltaTime) {}
void Barrel::setHeadRadius(float headRadius) { this->headRadius = headRadius; }
void Barrel::setBellyRadius(float bellyRadius) { this->bellyRadius = bellyRadius; }
void Barrel::setHeight(float height) { this->height = height; }
void Barrel::setBarrelTextureName(unsigned int barrelTextureName)
{
this->barrelTextureName = barrelTextureName;
}
void Barrel::setWoodTextureName(unsigned int woodTextureName)
{
this->woodTextureName = woodTextureName;
}
float Barrel::getHeadRadius() { return headRadius; }
float Barrel::getBellyRadius() { return bellyRadius; }
float Barrel::getHeight() { return height; }
|
#include <pybind11/pybind11.h>
#include <pybind11/operators.h>
#include <pybind11/eigen.h>
#include <pybind11/stl.h>
#include "manif/SE3.h"
#include "bindings_optional.h"
#include "bindings_lie_group_base.h"
#include "bindings_tangent_base.h"
namespace py = pybind11;
void wrap_SE3(py::module &m)
{
using SE3d = manif::SE3d;
using Scalar = SE3d::Scalar;
using Quaternion = Eigen::Quaternion<Scalar>;
py::class_<manif::LieGroupBase<SE3d>, std::unique_ptr<manif::LieGroupBase<SE3d>, py::nodelete>> SE3_base(m, "_SE3Base");
py::class_<manif::TangentBase<manif::SE3Tangentd>, std::unique_ptr<manif::TangentBase<manif::SE3Tangentd>, py::nodelete>> SE3_tan_base(m, "_SE3TangentBase");
py::class_<SE3d, manif::LieGroupBase<SE3d>> SE3(m, "SE3");
py::class_<manif::SE3Tangentd, manif::TangentBase<manif::SE3Tangentd>> SE3_tan(m, "SE3Tangent");
// group
wrap_lie_group_base<SE3d, manif::LieGroupBase<SE3d>>(SE3);
SE3.def(py::init<const Scalar, const Scalar, const Scalar,
const Scalar, const Scalar, const Scalar>());
// SE3.def(py::init<const Translation&, const Quaternion&>());
// SE3.def(py::init<const Translation&, const Eigen::AngleAxis<Scalar>&>());
// SE3.def(py::init<const Translation&, const manif::SO3<Scalar>&>());
// SE3.def(py::init<igen::Transform<Scalar, 3, Eigen::Isometry>&>());
SE3.def("transform", &SE3d::transform);
// SE3.def("isometry", &SE3d::isometry);
SE3.def("rotation", &SE3d::rotation);
// SE3.def("quat", &SE3d::quat);
SE3.def(
"translation",
static_cast<SE3d::Translation (SE3d::*)(void) const>(&SE3d::translation)
);
SE3.def("x", &SE3d::x);
SE3.def("y", &SE3d::y);
SE3.def("z", &SE3d::z);
SE3.def("normalize", &SE3d::normalize);
//tangent
wrap_tangent_base<manif::SE3Tangentd, manif::TangentBase<manif::SE3Tangentd>>(SE3_tan);
// SE3_tan.def("v", &manif::SE3Tangentd::v);
// SE3_tan.def("w", &manif::SE3Tangentd::w);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
/** \file
*
* \brief Implement the global object for the memtools module
*
* \author Morten Rolland, mortenro@opera.com
*/
#include "core/pch.h"
#include "modules/memtools/memtools_module.h"
#include "modules/memtools/memtools_codeloc.h"
void MemtoolsModule::InitL(const OperaInitInfo&)
{
#ifdef MEMTOOLS_ENABLE_CODELOC
OpCodeLocationManager::Init();
#endif
}
void MemtoolsModule::Destroy(void)
{
}
|
/*
_ _
| |__ | |__ __ _ __ _ _ _ __ _
| '_ \| '_ \ / _` |/ _` | | | |/ _` |
| |_) | | | | (_| | (_| | |_| | (_| |
|_.__/|_| |_|\__,_|\__, |\__, |\__,_|
|___/ |___/
*/
#include<bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse2")
#define ll long long
#define pb push_back
#define ppb pop_back
#define endl '\n'
#define mii map<ll int,ll int>
#define msi map<string,ll int>
#define mis map<ll int, string>
#define mpi map<pair<ll int,ll int>,ll int>
#define pii pair<ll int,ll int>
#define vi vector<ll int>
#define vs vector<string>
#define all(a) (a).begin(),(a).end()
#define F first
#define S second
#define sz(x) (ll int)x.size()
#define hell 1000000007
#define lbnd lower_bound
#define ubnd upper_bound
#define bs binary_search
#define mp make_pair
#define what_is(x) cerr << #x << " is " << x << endl;
using namespace std;
ll int x,n;
ll int k,m;
ll int matrix[62][201][201];
vi s;
ll int a[201];
ll int fuck;
void init()
{
memset(matrix,0,sizeof(matrix));
for(int i=1;i<m;i++) matrix[0][1][i]=a[i];
matrix[0][1][m]=(a[m]+1)%hell;
for(int i=2;i<=m;i++) matrix[0][i][i-1]=1;
for(int num=1;num<62;num++)
{
for(int i=1;i<=m;i++)
{
for(int j=1;j<=m;j++)
{
fuck=0;
for(int k=1;k<=m;k++)
{
fuck=(fuck+(1ll*matrix[num-1][i][k]*matrix[num-1][k][j])%hell);
}
matrix[num][i][j]=fuck%hell;
}
}
}
}
ll int f[201];
ll int newf[201];
void move(ll int value)
{
for(int it=0;it<62;it++)
{
if((value>>it)&1ll)
{
memset(newf,0,sizeof(newf));
for(int i=1;i<=m;i++)
{
fuck=0;
for(int j=1;j<=m;j++)
{
fuck=(fuck+(1ll*matrix[it][m-i+1][j]*f[m-j+1])%hell);
}
newf[i]=fuck%hell;
}
for(int i=1;i<=m;i++) f[i]=newf[i];
}
}
}
// void print(ll int idx)
// {
// cout<<endl;
// for(ll int i=1;i<=m;i++)
// {
// for(ll int j=1;j<=m;j++)
// {
// cout<<matrix[i][j][idx]<<" ";
// }
// cout<<endl;
// }
// cout<<endl;
// }
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int TESTS=1;
// cin>>TESTS;
while(TESTS--)
{
cin>>x>>k>>m>>n;
s.resize(k);
for(int i=0;i<k;i++) cin>>s[i];
for(int i=1;i<=m;i++) cin>>a[i];
init();
f[0]=x;
for(int i=1;i<=m;i++)
{
ll int tmp=0;
for(int j=1;j<=i;j++)
{
tmp=(tmp+(1ll*f[i-j]*a[j])%hell)%hell;
}
f[i]=tmp;
bool fnd=0;
for(auto it:s) if(it==i) fnd=1;
if(fnd) f[i]=0;
}
// for(ll int i=0;i<=m;i++) cout<<f[i]<<" ";cout<<endl;
mii ma;
for(auto i:s)
{
if(i<=m)
{
f[i]=0;
}
else
{
ma[i]=1;
}
}
s.clear();
for(auto i:ma) s.pb(i.F);
k=s.size();
if(n<=m)
{
cout<<f[n]<<endl;
return 0;
}
ll int cur=m;
for(auto i:s)
{
move(i-cur);
f[m]=0;
cur=i;
}
move(n-cur);
cout<<f[m]<<endl;
}
// cerr << "\nTime elapsed: " << 1000 * clock() / CLOCKS_PER_SEC << "ms\n";
return 0;
}
|
//
// Created by drunkgranny on 08.04.16.
//
#include <iostream>
using namespace std;
int pointer()
{
int updates = 6;
int *p_updates;
p_updates = &updates;
cout << "Values: updates = " << updates << endl;
cout << "Values: *p_updates = " << *p_updates << endl;
cout << endl;
cout << "Address: &updates " << &updates << endl;
cout << "Address: p_updates " << p_updates << endl;
*p_updates = *p_updates + 1;
cout << endl;
cout << "Now updates = " << updates << endl;
cout << "Now *p_updates = " << *p_updates << endl;
return 0;
}
|
#include "msg_0x0d_playerpositionandlook_tw.h"
namespace MC
{
namespace Protocol
{
namespace Msg
{
PlayerPositionAndLook::PlayerPositionAndLook()
{
_pf_packetId = static_cast<int8_t>(0x0D);
_pf_initialized = false;
}
PlayerPositionAndLook::PlayerPositionAndLook(double _x, double _y, double _stance, double _z, float _yaw, float _pitch, bool _onGround)
: _pf_x(_x)
, _pf_y(_y)
, _pf_stance(_stance)
, _pf_z(_z)
, _pf_yaw(_yaw)
, _pf_pitch(_pitch)
, _pf_onGround(_onGround)
{
_pf_packetId = static_cast<int8_t>(0x0D);
_pf_initialized = true;
}
size_t PlayerPositionAndLook::serialize(Buffer& _dst, size_t _offset)
{
_pm_checkInit();
if(_offset == 0) _dst.clear();
_offset = WriteInt8(_dst, _offset, _pf_packetId);
_offset = WriteDouble(_dst, _offset, _pf_x);
_offset = WriteDouble(_dst, _offset, _pf_y);
_offset = WriteDouble(_dst, _offset, _pf_stance);
_offset = WriteDouble(_dst, _offset, _pf_z);
_offset = WriteFloat(_dst, _offset, _pf_yaw);
_offset = WriteFloat(_dst, _offset, _pf_pitch);
_offset = WriteBool(_dst, _offset, _pf_onGround);
return _offset;
}
size_t PlayerPositionAndLook::deserialize(const Buffer& _src, size_t _offset)
{
_offset = _pm_checkPacketId(_src, _offset);
_offset = ReadDouble(_src, _offset, _pf_x);
_offset = ReadDouble(_src, _offset, _pf_stance);
_offset = ReadDouble(_src, _offset, _pf_y);
_offset = ReadDouble(_src, _offset, _pf_z);
_offset = ReadFloat(_src, _offset, _pf_yaw);
_offset = ReadFloat(_src, _offset, _pf_pitch);
_offset = ReadBool(_src, _offset, _pf_onGround);
_pf_initialized = true;
return _offset;
}
double PlayerPositionAndLook::getX() const { return _pf_x; }
double PlayerPositionAndLook::getY() const { return _pf_y; }
double PlayerPositionAndLook::getStance() const { return _pf_stance; }
double PlayerPositionAndLook::getZ() const { return _pf_z; }
float PlayerPositionAndLook::getYaw() const { return _pf_yaw; }
float PlayerPositionAndLook::getPitch() const { return _pf_pitch; }
bool PlayerPositionAndLook::getOnGround() const { return _pf_onGround; }
void PlayerPositionAndLook::setX(double _val) { _pf_x = _val; }
void PlayerPositionAndLook::setY(double _val) { _pf_y = _val; }
void PlayerPositionAndLook::setStance(double _val) { _pf_stance = _val; }
void PlayerPositionAndLook::setZ(double _val) { _pf_z = _val; }
void PlayerPositionAndLook::setYaw(float _val) { _pf_yaw = _val; }
void PlayerPositionAndLook::setPitch(float _val) { _pf_pitch = _val; }
void PlayerPositionAndLook::setOnGround(bool _val) { _pf_onGround = _val; }
} // namespace Msg
} // namespace Protocol
} // namespace MC
|
#include "trigonometry.h" // import file to test
#include <vector> // used for test input
#include "ut.hpp" // import functionality and namespaces from single header file
using namespace boost::ut; // provides `expect`, `""_test`, etc
using namespace boost::ut::bdd; // provides `given`, `when`, `then`
#include <cmath>
#include <random>
int main() {
#ifdef _ // this test fails...
"atan2"_test = [] {
given("A vector of 100 random x and y coords") = [] {
const size_t N = 100;
double xs[N], ys[N], cmath_results[N], approx_results[N];
when("I calualte the cmath atan2 and the atan2-approximation") = [&] {
for (size_t i = 0; i < N; i++) {
xs[i] = random() * 1.0/RAND_MAX * 10 - 5;
ys[i] = random() * 1.0/RAND_MAX * 10 - 5;
cmath_results[i] = atan2(ys[i], xs[i]);
approx_results[i] = atan2_approximation1(ys[i], ys[i]);
}
then("I expect the calculations to be rougly equal") = [&] {
for (size_t i = 0; i < N; i++) {
expect(that % fabs(approx_results[i] - cmath_results[i]) < 1e-7);
}
};
};
};
};
#endif
}
|
#pragma once
#ifdef VK_USE_PLATFORM_ANDROID_KHR
#include <android/log.h>
#include <kompute_vk_ndk_wrapper.hpp>
// VK_NO_PROTOTYPES required before vulkan import but after wrapper.hpp
#undef VK_NO_PROTOTYPES
static const char* KOMPUTE_LOG_TAG = "KomputeLog";
#endif
#include <vulkan/vulkan.hpp>
// Typedefs to simplify interaction with core types
namespace kp {
typedef std::array<uint32_t, 3> Workgroup;
typedef std::vector<float> Constants;
}
// Must be after vulkan is included
#ifndef KOMPUTE_VK_API_VERSION
#ifndef KOMPUTE_VK_API_MAJOR_VERSION
#define KOMPUTE_VK_API_MAJOR_VERSION 1
#endif // KOMPUTE_VK_API_MAJOR_VERSION
#ifndef KOMPUTE_VK_API_MINOR_VERSION
#define KOMPUTE_VK_API_MINOR_VERSION 1
#endif // KOMPUTE_VK_API_MINOR_VERSION
#define KOMPUTE_VK_API_VERSION \
VK_MAKE_VERSION( \
KOMPUTE_VK_API_MAJOR_VERSION, KOMPUTE_VK_API_MINOR_VERSION, 0)
#endif // KOMPUTE_VK_API_VERSION
// SPDLOG_ACTIVE_LEVEL must be defined before spdlog.h import
#ifndef SPDLOG_ACTIVE_LEVEL
#if DEBUG
#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_DEBUG
#else
#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_INFO
#endif
#endif
#if defined(KOMPUTE_BUILD_PYTHON)
#include <pybind11/pybind11.h>
namespace py = pybind11;
// from python/src/main.cpp
extern py::object kp_debug, kp_info, kp_warning, kp_error;
#endif
#ifndef KOMPUTE_LOG_OVERRIDE
#if KOMPUTE_ENABLE_SPDLOG
#include <spdlog/spdlog.h>
#else
#include <iostream>
#if SPDLOG_ACTIVE_LEVEL > 1
#define SPDLOG_DEBUG(message, ...)
#else
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
#define SPDLOG_DEBUG(message, ...) \
((void)__android_log_print(ANDROID_LOG_DEBUG, KOMPUTE_LOG_TAG, message))
#elif defined(KOMPUTE_BUILD_PYTHON)
#define SPDLOG_DEBUG(message, ...) kp_debug(message);
#else
#define SPDLOG_DEBUG(message, ...) \
std::cout << "DEBUG: " << message << std::endl
#endif // VK_USE_PLATFORM_ANDROID_KHR
#endif // SPDLOG_ACTIVE_LEVEL > 1
#if SPDLOG_ACTIVE_LEVEL > 2
#define SPDLOG_INFO(message, ...)
#else
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
#define SPDLOG_INFO(message, ...) \
((void)__android_log_print(ANDROID_LOG_INFO, KOMPUTE_LOG_TAG, message))
#elif defined(KOMPUTE_BUILD_PYTHON)
#define SPDLOG_INFO(message, ...) kp_info(message);
#else
#define SPDLOG_INFO(message, ...) std::cout << "INFO: " << message << std::endl
#endif // VK_USE_PLATFORM_ANDROID_KHR
#endif // SPDLOG_ACTIVE_LEVEL > 2
#if SPDLOG_ACTIVE_LEVEL > 3
#define SPDLOG_WARN(message, ...)
#else
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
#define SPDLOG_WARN(message, ...) \
((void)__android_log_print(ANDROID_LOG_INFO, KOMPUTE_LOG_TAG, message))
#elif defined(KOMPUTE_BUILD_PYTHON)
#define SPDLOG_WARN(message, ...) kp_warning(message);
#else
#define SPDLOG_WARN(message, ...) \
std::cout << "WARNING: " << message << std::endl
#endif // VK_USE_PLATFORM_ANDROID_KHR
#endif // SPDLOG_ACTIVE_LEVEL > 3
#if SPDLOG_ACTIVE_LEVEL > 4
#define SPDLOG_ERROR(message, ...)
#else
#if defined(VK_USE_PLATFORM_ANDROID_KHR)
#define SPDLOG_ERROR(message, ...) \
((void)__android_log_print(ANDROID_LOG_INFO, KOMPUTE_LOG_TAG, message))
#elif defined(KOMPUTE_BUILD_PYTHON)
#define SPDLOG_ERROR(message, ...) kp_error(message);
#else
#define SPDLOG_ERROR(message, ...) \
std::cout << "ERROR: " << message << std::endl
#endif // VK_USE_PLATFORM_ANDROID_KHR
#endif // SPDLOG_ACTIVE_LEVEL > 4
#endif // KOMPUTE_SPDLOG_ENABLED
#endif // KOMPUTE_LOG_OVERRIDE
/*
THIS FILE HAS BEEN AUTOMATICALLY GENERATED - DO NOT EDIT
---
Copyright 2020 The Institute for Ethical AI & Machine Learning
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.
*/
#ifndef SHADEROP_SHADEROPMULT_HPP
#define SHADEROP_SHADEROPMULT_HPP
namespace kp {
namespace shader_data {
static const unsigned char shaders_glsl_opmult_comp_spv[] = {
0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x08, 0x00, 0x08, 0x00,
0x2e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00,
0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00,
0x47, 0x4c, 0x53, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x2e, 0x34, 0x35, 0x30,
0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x06, 0x00, 0x05, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00,
0x0b, 0x00, 0x00, 0x00, 0x10, 0x00, 0x06, 0x00, 0x04, 0x00, 0x00, 0x00,
0x11, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00,
0xc2, 0x01, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00,
0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00,
0x08, 0x00, 0x00, 0x00, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x00, 0x00, 0x00,
0x05, 0x00, 0x08, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x67, 0x6c, 0x5f, 0x47,
0x6c, 0x6f, 0x62, 0x61, 0x6c, 0x49, 0x6e, 0x76, 0x6f, 0x63, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x49, 0x44, 0x00, 0x00, 0x00, 0x05, 0x00, 0x06, 0x00,
0x12, 0x00, 0x00, 0x00, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x4f, 0x75,
0x74, 0x70, 0x75, 0x74, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x07, 0x00,
0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x61, 0x6c, 0x75,
0x65, 0x73, 0x4f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x00, 0x00, 0x00, 0x00,
0x05, 0x00, 0x03, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x00, 0x05, 0x00, 0x19, 0x00, 0x00, 0x00, 0x74, 0x65, 0x6e, 0x73,
0x6f, 0x72, 0x4c, 0x68, 0x73, 0x00, 0x00, 0x00, 0x06, 0x00, 0x06, 0x00,
0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x61, 0x6c, 0x75,
0x65, 0x73, 0x4c, 0x68, 0x73, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00,
0x1b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00,
0x21, 0x00, 0x00, 0x00, 0x74, 0x65, 0x6e, 0x73, 0x6f, 0x72, 0x52, 0x68,
0x73, 0x00, 0x00, 0x00, 0x06, 0x00, 0x06, 0x00, 0x21, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x52, 0x68,
0x73, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, 0x23, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x29, 0x00, 0x00, 0x00,
0x4c, 0x45, 0x4e, 0x5f, 0x4c, 0x48, 0x53, 0x00, 0x05, 0x00, 0x04, 0x00,
0x2a, 0x00, 0x00, 0x00, 0x4c, 0x45, 0x4e, 0x5f, 0x52, 0x48, 0x53, 0x00,
0x05, 0x00, 0x04, 0x00, 0x2b, 0x00, 0x00, 0x00, 0x4c, 0x45, 0x4e, 0x5f,
0x4f, 0x55, 0x54, 0x00, 0x47, 0x00, 0x04, 0x00, 0x0b, 0x00, 0x00, 0x00,
0x0b, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
0x11, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x48, 0x00, 0x05, 0x00, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, 0x00,
0x12, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
0x14, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0x14, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x18, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00,
0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, 0x00, 0x19, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x1b, 0x00, 0x00, 0x00,
0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
0x1b, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0x20, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x21, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x47, 0x00, 0x03, 0x00, 0x21, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0x23, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x23, 0x00, 0x00, 0x00,
0x21, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
0x29, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x2b, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
0x2d, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00,
0x13, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x21, 0x00, 0x03, 0x00,
0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x15, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x20, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x09, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00,
0x0a, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00,
0x3b, 0x00, 0x04, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00,
0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00,
0x0d, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x16, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
0x1d, 0x00, 0x03, 0x00, 0x11, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
0x1e, 0x00, 0x03, 0x00, 0x12, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00,
0x20, 0x00, 0x04, 0x00, 0x13, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x12, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x13, 0x00, 0x00, 0x00,
0x14, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x15, 0x00, 0x04, 0x00,
0x15, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x2b, 0x00, 0x04, 0x00, 0x15, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x03, 0x00, 0x18, 0x00, 0x00, 0x00,
0x10, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x03, 0x00, 0x19, 0x00, 0x00, 0x00,
0x18, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x1a, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
0x1a, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x20, 0x00, 0x04, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x10, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x03, 0x00, 0x20, 0x00, 0x00, 0x00,
0x10, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x03, 0x00, 0x21, 0x00, 0x00, 0x00,
0x20, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x22, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
0x22, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x32, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x32, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00,
0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x2b, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x06, 0x00, 0x09, 0x00, 0x00, 0x00,
0x2d, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00,
0x2c, 0x00, 0x00, 0x00, 0x36, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0xf8, 0x00, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
0x07, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
0x41, 0x00, 0x05, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00,
0x0b, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x03, 0x00, 0x08, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00,
0x3d, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00,
0x1c, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00,
0x1d, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x00, 0x00,
0x16, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x10, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00,
0x3d, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, 0x1d, 0x00, 0x00, 0x00,
0x25, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00,
0x24, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x10, 0x00, 0x00, 0x00,
0x26, 0x00, 0x00, 0x00, 0x25, 0x00, 0x00, 0x00, 0x85, 0x00, 0x05, 0x00,
0x10, 0x00, 0x00, 0x00, 0x27, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00,
0x26, 0x00, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, 0x1d, 0x00, 0x00, 0x00,
0x28, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00,
0x17, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, 0x28, 0x00, 0x00, 0x00,
0x27, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00
};
static const unsigned int shaders_glsl_opmult_comp_spv_len = 1464;
}
}
#endif // define SHADEROP_SHADEROPMULT_HPP
/*
THIS FILE HAS BEEN AUTOMATICALLY GENERATED - DO NOT EDIT
---
Copyright 2020 The Institute for Ethical AI & Machine Learning
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.
*/
#ifndef SHADEROP_SHADERLOGISTICREGRESSION_HPP
#define SHADEROP_SHADERLOGISTICREGRESSION_HPP
namespace kp {
namespace shader_data {
static const unsigned char shaders_glsl_logisticregression_comp_spv[] = {
0x03, 0x02, 0x23, 0x07, 0x00, 0x00, 0x01, 0x00, 0x08, 0x00, 0x08, 0x00,
0xae, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x00, 0x02, 0x00,
0x01, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x00,
0x47, 0x4c, 0x53, 0x4c, 0x2e, 0x73, 0x74, 0x64, 0x2e, 0x34, 0x35, 0x30,
0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x06, 0x00, 0x05, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00,
0x41, 0x00, 0x00, 0x00, 0x10, 0x00, 0x06, 0x00, 0x04, 0x00, 0x00, 0x00,
0x11, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x00,
0xc2, 0x01, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00,
0x6d, 0x61, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x05, 0x00,
0x0a, 0x00, 0x00, 0x00, 0x73, 0x69, 0x67, 0x6d, 0x6f, 0x69, 0x64, 0x28,
0x66, 0x31, 0x3b, 0x00, 0x05, 0x00, 0x03, 0x00, 0x09, 0x00, 0x00, 0x00,
0x7a, 0x00, 0x00, 0x00, 0x05, 0x00, 0x08, 0x00, 0x12, 0x00, 0x00, 0x00,
0x69, 0x6e, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x28, 0x76, 0x66,
0x32, 0x3b, 0x76, 0x66, 0x32, 0x3b, 0x66, 0x31, 0x3b, 0x00, 0x00, 0x00,
0x05, 0x00, 0x03, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00,
0x05, 0x00, 0x03, 0x00, 0x10, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00,
0x05, 0x00, 0x03, 0x00, 0x11, 0x00, 0x00, 0x00, 0x62, 0x00, 0x00, 0x00,
0x05, 0x00, 0x08, 0x00, 0x17, 0x00, 0x00, 0x00, 0x63, 0x61, 0x6c, 0x63,
0x75, 0x6c, 0x61, 0x74, 0x65, 0x4c, 0x6f, 0x73, 0x73, 0x28, 0x66, 0x31,
0x3b, 0x66, 0x31, 0x3b, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00,
0x15, 0x00, 0x00, 0x00, 0x79, 0x48, 0x61, 0x74, 0x00, 0x00, 0x00, 0x00,
0x05, 0x00, 0x03, 0x00, 0x16, 0x00, 0x00, 0x00, 0x79, 0x00, 0x00, 0x00,
0x05, 0x00, 0x03, 0x00, 0x21, 0x00, 0x00, 0x00, 0x7a, 0x00, 0x00, 0x00,
0x05, 0x00, 0x04, 0x00, 0x27, 0x00, 0x00, 0x00, 0x79, 0x48, 0x61, 0x74,
0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x28, 0x00, 0x00, 0x00,
0x70, 0x61, 0x72, 0x61, 0x6d, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00,
0x3e, 0x00, 0x00, 0x00, 0x69, 0x64, 0x78, 0x00, 0x05, 0x00, 0x08, 0x00,
0x41, 0x00, 0x00, 0x00, 0x67, 0x6c, 0x5f, 0x47, 0x6c, 0x6f, 0x62, 0x61,
0x6c, 0x49, 0x6e, 0x76, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49,
0x44, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x46, 0x00, 0x00, 0x00,
0x77, 0x43, 0x75, 0x72, 0x72, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00,
0x48, 0x00, 0x00, 0x00, 0x62, 0x77, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00,
0x06, 0x00, 0x04, 0x00, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x77, 0x69, 0x6e, 0x00, 0x05, 0x00, 0x03, 0x00, 0x4a, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x54, 0x00, 0x00, 0x00,
0x62, 0x43, 0x75, 0x72, 0x72, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00,
0x56, 0x00, 0x00, 0x00, 0x62, 0x62, 0x69, 0x6e, 0x00, 0x00, 0x00, 0x00,
0x06, 0x00, 0x04, 0x00, 0x56, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x62, 0x69, 0x6e, 0x00, 0x05, 0x00, 0x03, 0x00, 0x58, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x5b, 0x00, 0x00, 0x00,
0x78, 0x43, 0x75, 0x72, 0x72, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00,
0x5d, 0x00, 0x00, 0x00, 0x62, 0x78, 0x69, 0x00, 0x06, 0x00, 0x04, 0x00,
0x5d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x69, 0x00, 0x00,
0x05, 0x00, 0x03, 0x00, 0x5f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x00, 0x03, 0x00, 0x64, 0x00, 0x00, 0x00, 0x62, 0x78, 0x6a, 0x00,
0x06, 0x00, 0x04, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x78, 0x6a, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, 0x66, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x6b, 0x00, 0x00, 0x00,
0x79, 0x43, 0x75, 0x72, 0x72, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00,
0x6d, 0x00, 0x00, 0x00, 0x62, 0x79, 0x00, 0x00, 0x06, 0x00, 0x04, 0x00,
0x6d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79, 0x00, 0x00, 0x00,
0x05, 0x00, 0x03, 0x00, 0x6f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x05, 0x00, 0x04, 0x00, 0x73, 0x00, 0x00, 0x00, 0x79, 0x48, 0x61, 0x74,
0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x74, 0x00, 0x00, 0x00,
0x70, 0x61, 0x72, 0x61, 0x6d, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00,
0x76, 0x00, 0x00, 0x00, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x00, 0x00, 0x00,
0x05, 0x00, 0x04, 0x00, 0x78, 0x00, 0x00, 0x00, 0x70, 0x61, 0x72, 0x61,
0x6d, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, 0x7b, 0x00, 0x00, 0x00,
0x64, 0x5a, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, 0x7f, 0x00, 0x00, 0x00,
0x64, 0x57, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, 0x80, 0x00, 0x00, 0x00,
0x6d, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, 0x86, 0x00, 0x00, 0x00,
0x64, 0x42, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x8b, 0x00, 0x00, 0x00,
0x62, 0x77, 0x6f, 0x75, 0x74, 0x69, 0x00, 0x00, 0x06, 0x00, 0x05, 0x00,
0x8b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x77, 0x6f, 0x75, 0x74,
0x69, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, 0x8d, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x93, 0x00, 0x00, 0x00,
0x62, 0x77, 0x6f, 0x75, 0x74, 0x6a, 0x00, 0x00, 0x06, 0x00, 0x05, 0x00,
0x93, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x77, 0x6f, 0x75, 0x74,
0x6a, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, 0x95, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0x9c, 0x00, 0x00, 0x00,
0x62, 0x62, 0x6f, 0x75, 0x74, 0x00, 0x00, 0x00, 0x06, 0x00, 0x05, 0x00,
0x9c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x6f, 0x75, 0x74,
0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, 0x9e, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0xa3, 0x00, 0x00, 0x00,
0x62, 0x6c, 0x6f, 0x75, 0x74, 0x00, 0x00, 0x00, 0x06, 0x00, 0x05, 0x00,
0xa3, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6c, 0x6f, 0x75, 0x74,
0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, 0xa5, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00, 0xa7, 0x00, 0x00, 0x00,
0x70, 0x61, 0x72, 0x61, 0x6d, 0x00, 0x00, 0x00, 0x05, 0x00, 0x04, 0x00,
0xa9, 0x00, 0x00, 0x00, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0x41, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00,
0x1c, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x47, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00,
0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, 0x00, 0x48, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x4a, 0x00, 0x00, 0x00,
0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
0x4a, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0x55, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x56, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x47, 0x00, 0x03, 0x00, 0x56, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0x58, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x58, 0x00, 0x00, 0x00,
0x21, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
0x5c, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x48, 0x00, 0x05, 0x00, 0x5d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, 0x00,
0x5d, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
0x5f, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0x5f, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x63, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00,
0x64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, 0x00, 0x64, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x66, 0x00, 0x00, 0x00,
0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
0x66, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0x6c, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x6d, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x47, 0x00, 0x03, 0x00, 0x6d, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0x6f, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x6f, 0x00, 0x00, 0x00,
0x21, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
0x80, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0x8a, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0x8b, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x47, 0x00, 0x03, 0x00, 0x8b, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x8d, 0x00, 0x00, 0x00,
0x21, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
0x92, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
0x48, 0x00, 0x05, 0x00, 0x93, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, 0x00,
0x93, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
0x95, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0x95, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00,
0x05, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x9b, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00,
0x9c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x03, 0x00, 0x9c, 0x00, 0x00, 0x00,
0x03, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0x9e, 0x00, 0x00, 0x00,
0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
0x9e, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0xa2, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x48, 0x00, 0x05, 0x00, 0xa3, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x47, 0x00, 0x03, 0x00, 0xa3, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x47, 0x00, 0x04, 0x00, 0xa5, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00, 0xa5, 0x00, 0x00, 0x00,
0x21, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x47, 0x00, 0x04, 0x00,
0xad, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00,
0x13, 0x00, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x21, 0x00, 0x03, 0x00,
0x03, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x16, 0x00, 0x03, 0x00,
0x06, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00,
0x07, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x21, 0x00, 0x04, 0x00, 0x08, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00,
0x0d, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x21, 0x00, 0x06, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x0d, 0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
0x21, 0x00, 0x05, 0x00, 0x14, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x3f,
0x15, 0x00, 0x04, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x3d, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x17, 0x00, 0x04, 0x00,
0x3f, 0x00, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0x20, 0x00, 0x04, 0x00, 0x40, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x3f, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x40, 0x00, 0x00, 0x00,
0x41, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00,
0x3c, 0x00, 0x00, 0x00, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x20, 0x00, 0x04, 0x00, 0x43, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x3c, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x03, 0x00, 0x47, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x03, 0x00, 0x48, 0x00, 0x00, 0x00,
0x47, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x49, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
0x49, 0x00, 0x00, 0x00, 0x4a, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x15, 0x00, 0x04, 0x00, 0x4b, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00, 0x4b, 0x00, 0x00, 0x00,
0x4c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00,
0x4d, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x2b, 0x00, 0x04, 0x00, 0x4b, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x03, 0x00, 0x55, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x03, 0x00, 0x56, 0x00, 0x00, 0x00,
0x55, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x57, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x56, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
0x57, 0x00, 0x00, 0x00, 0x58, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x1d, 0x00, 0x03, 0x00, 0x5c, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x1e, 0x00, 0x03, 0x00, 0x5d, 0x00, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x00,
0x20, 0x00, 0x04, 0x00, 0x5e, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x5d, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x5e, 0x00, 0x00, 0x00,
0x5f, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x03, 0x00,
0x63, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x03, 0x00,
0x64, 0x00, 0x00, 0x00, 0x63, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00,
0x65, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00,
0x3b, 0x00, 0x04, 0x00, 0x65, 0x00, 0x00, 0x00, 0x66, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x03, 0x00, 0x6c, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x03, 0x00, 0x6d, 0x00, 0x00, 0x00,
0x6c, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x6e, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x6d, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
0x6e, 0x00, 0x00, 0x00, 0x6f, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x32, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x03, 0x00, 0x8a, 0x00, 0x00, 0x00,
0x06, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x03, 0x00, 0x8b, 0x00, 0x00, 0x00,
0x8a, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00, 0x8c, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x8b, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
0x8c, 0x00, 0x00, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x1d, 0x00, 0x03, 0x00, 0x92, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x1e, 0x00, 0x03, 0x00, 0x93, 0x00, 0x00, 0x00, 0x92, 0x00, 0x00, 0x00,
0x20, 0x00, 0x04, 0x00, 0x94, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x93, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x94, 0x00, 0x00, 0x00,
0x95, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x04, 0x00,
0x3c, 0x00, 0x00, 0x00, 0x97, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x1d, 0x00, 0x03, 0x00, 0x9b, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00,
0x1e, 0x00, 0x03, 0x00, 0x9c, 0x00, 0x00, 0x00, 0x9b, 0x00, 0x00, 0x00,
0x20, 0x00, 0x04, 0x00, 0x9d, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
0x9c, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x9d, 0x00, 0x00, 0x00,
0x9e, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x03, 0x00,
0xa2, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x03, 0x00,
0xa3, 0x00, 0x00, 0x00, 0xa2, 0x00, 0x00, 0x00, 0x20, 0x00, 0x04, 0x00,
0xa4, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0xa3, 0x00, 0x00, 0x00,
0x3b, 0x00, 0x04, 0x00, 0xa4, 0x00, 0x00, 0x00, 0xa5, 0x00, 0x00, 0x00,
0x02, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x06, 0x00, 0x3f, 0x00, 0x00, 0x00,
0xad, 0x00, 0x00, 0x00, 0x97, 0x00, 0x00, 0x00, 0x97, 0x00, 0x00, 0x00,
0x97, 0x00, 0x00, 0x00, 0x36, 0x00, 0x05, 0x00, 0x02, 0x00, 0x00, 0x00,
0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
0xf8, 0x00, 0x02, 0x00, 0x05, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
0x3d, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
0x3b, 0x00, 0x04, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x46, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00,
0x54, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
0x0d, 0x00, 0x00, 0x00, 0x5b, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
0x3b, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x6b, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00,
0x73, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
0x0d, 0x00, 0x00, 0x00, 0x74, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
0x3b, 0x00, 0x04, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x76, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00,
0x78, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
0x07, 0x00, 0x00, 0x00, 0x7b, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
0x3b, 0x00, 0x04, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00,
0x86, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
0x07, 0x00, 0x00, 0x00, 0xa7, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
0x3b, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0xa9, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, 0x43, 0x00, 0x00, 0x00,
0x44, 0x00, 0x00, 0x00, 0x41, 0x00, 0x00, 0x00, 0x42, 0x00, 0x00, 0x00,
0x3d, 0x00, 0x04, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x45, 0x00, 0x00, 0x00,
0x44, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, 0x3e, 0x00, 0x00, 0x00,
0x45, 0x00, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, 0x4d, 0x00, 0x00, 0x00,
0x4e, 0x00, 0x00, 0x00, 0x4a, 0x00, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x00,
0x4c, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00,
0x4f, 0x00, 0x00, 0x00, 0x4e, 0x00, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00,
0x4d, 0x00, 0x00, 0x00, 0x51, 0x00, 0x00, 0x00, 0x4a, 0x00, 0x00, 0x00,
0x4c, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x52, 0x00, 0x00, 0x00, 0x51, 0x00, 0x00, 0x00,
0x50, 0x00, 0x05, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x53, 0x00, 0x00, 0x00,
0x4f, 0x00, 0x00, 0x00, 0x52, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00,
0x46, 0x00, 0x00, 0x00, 0x53, 0x00, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00,
0x4d, 0x00, 0x00, 0x00, 0x59, 0x00, 0x00, 0x00, 0x58, 0x00, 0x00, 0x00,
0x4c, 0x00, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x59, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x03, 0x00, 0x54, 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00,
0x3d, 0x00, 0x04, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, 0x4d, 0x00, 0x00, 0x00,
0x61, 0x00, 0x00, 0x00, 0x5f, 0x00, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x00,
0x60, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00,
0x62, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x3c, 0x00, 0x00, 0x00, 0x67, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00,
0x41, 0x00, 0x06, 0x00, 0x4d, 0x00, 0x00, 0x00, 0x68, 0x00, 0x00, 0x00,
0x66, 0x00, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x67, 0x00, 0x00, 0x00,
0x3d, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x69, 0x00, 0x00, 0x00,
0x68, 0x00, 0x00, 0x00, 0x50, 0x00, 0x05, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x6a, 0x00, 0x00, 0x00, 0x62, 0x00, 0x00, 0x00, 0x69, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x03, 0x00, 0x5b, 0x00, 0x00, 0x00, 0x6a, 0x00, 0x00, 0x00,
0x3d, 0x00, 0x04, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x70, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, 0x4d, 0x00, 0x00, 0x00,
0x71, 0x00, 0x00, 0x00, 0x6f, 0x00, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x00,
0x70, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00,
0x72, 0x00, 0x00, 0x00, 0x71, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00,
0x6b, 0x00, 0x00, 0x00, 0x72, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x0c, 0x00, 0x00, 0x00, 0x75, 0x00, 0x00, 0x00, 0x5b, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x03, 0x00, 0x74, 0x00, 0x00, 0x00, 0x75, 0x00, 0x00, 0x00,
0x3d, 0x00, 0x04, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x77, 0x00, 0x00, 0x00,
0x46, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, 0x76, 0x00, 0x00, 0x00,
0x77, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00,
0x79, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00,
0x78, 0x00, 0x00, 0x00, 0x79, 0x00, 0x00, 0x00, 0x39, 0x00, 0x07, 0x00,
0x06, 0x00, 0x00, 0x00, 0x7a, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00,
0x74, 0x00, 0x00, 0x00, 0x76, 0x00, 0x00, 0x00, 0x78, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x03, 0x00, 0x73, 0x00, 0x00, 0x00, 0x7a, 0x00, 0x00, 0x00,
0x3d, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x7c, 0x00, 0x00, 0x00,
0x73, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00,
0x7d, 0x00, 0x00, 0x00, 0x6b, 0x00, 0x00, 0x00, 0x83, 0x00, 0x05, 0x00,
0x06, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x7c, 0x00, 0x00, 0x00,
0x7d, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, 0x7b, 0x00, 0x00, 0x00,
0x7e, 0x00, 0x00, 0x00, 0x88, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00,
0x81, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x3d, 0x00, 0x04, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x82, 0x00, 0x00, 0x00,
0x5b, 0x00, 0x00, 0x00, 0x8e, 0x00, 0x05, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x83, 0x00, 0x00, 0x00, 0x82, 0x00, 0x00, 0x00, 0x81, 0x00, 0x00, 0x00,
0x3d, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x84, 0x00, 0x00, 0x00,
0x7b, 0x00, 0x00, 0x00, 0x8e, 0x00, 0x05, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x85, 0x00, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00, 0x84, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x03, 0x00, 0x7f, 0x00, 0x00, 0x00, 0x85, 0x00, 0x00, 0x00,
0x88, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x87, 0x00, 0x00, 0x00,
0x19, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x88, 0x00, 0x00, 0x00, 0x7b, 0x00, 0x00, 0x00,
0x85, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x89, 0x00, 0x00, 0x00,
0x87, 0x00, 0x00, 0x00, 0x88, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00,
0x86, 0x00, 0x00, 0x00, 0x89, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x3c, 0x00, 0x00, 0x00, 0x8e, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00,
0x41, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00, 0x8f, 0x00, 0x00, 0x00,
0x7f, 0x00, 0x00, 0x00, 0x42, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00, 0x8f, 0x00, 0x00, 0x00,
0x41, 0x00, 0x06, 0x00, 0x4d, 0x00, 0x00, 0x00, 0x91, 0x00, 0x00, 0x00,
0x8d, 0x00, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x8e, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x03, 0x00, 0x91, 0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00,
0x3d, 0x00, 0x04, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x96, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x00, 0x00, 0x41, 0x00, 0x05, 0x00, 0x07, 0x00, 0x00, 0x00,
0x98, 0x00, 0x00, 0x00, 0x7f, 0x00, 0x00, 0x00, 0x97, 0x00, 0x00, 0x00,
0x3d, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x99, 0x00, 0x00, 0x00,
0x98, 0x00, 0x00, 0x00, 0x41, 0x00, 0x06, 0x00, 0x4d, 0x00, 0x00, 0x00,
0x9a, 0x00, 0x00, 0x00, 0x95, 0x00, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x00,
0x96, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00, 0x9a, 0x00, 0x00, 0x00,
0x99, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x3c, 0x00, 0x00, 0x00,
0x9f, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x86, 0x00, 0x00, 0x00,
0x41, 0x00, 0x06, 0x00, 0x4d, 0x00, 0x00, 0x00, 0xa1, 0x00, 0x00, 0x00,
0x9e, 0x00, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x9f, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x03, 0x00, 0xa1, 0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00,
0x3d, 0x00, 0x04, 0x00, 0x3c, 0x00, 0x00, 0x00, 0xa6, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00,
0xa8, 0x00, 0x00, 0x00, 0x73, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00,
0xa7, 0x00, 0x00, 0x00, 0xa8, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x6b, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x03, 0x00, 0xa9, 0x00, 0x00, 0x00, 0xaa, 0x00, 0x00, 0x00,
0x39, 0x00, 0x06, 0x00, 0x06, 0x00, 0x00, 0x00, 0xab, 0x00, 0x00, 0x00,
0x17, 0x00, 0x00, 0x00, 0xa7, 0x00, 0x00, 0x00, 0xa9, 0x00, 0x00, 0x00,
0x41, 0x00, 0x06, 0x00, 0x4d, 0x00, 0x00, 0x00, 0xac, 0x00, 0x00, 0x00,
0xa5, 0x00, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x00, 0xa6, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x03, 0x00, 0xac, 0x00, 0x00, 0x00, 0xab, 0x00, 0x00, 0x00,
0xfd, 0x00, 0x01, 0x00, 0x38, 0x00, 0x01, 0x00, 0x36, 0x00, 0x05, 0x00,
0x06, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x08, 0x00, 0x00, 0x00, 0x37, 0x00, 0x03, 0x00, 0x07, 0x00, 0x00, 0x00,
0x09, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00, 0x0b, 0x00, 0x00, 0x00,
0x3d, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00,
0x09, 0x00, 0x00, 0x00, 0x7f, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00,
0x1b, 0x00, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x06, 0x00,
0x06, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x1b, 0x00, 0x00, 0x00, 0x1b, 0x00, 0x00, 0x00, 0x81, 0x00, 0x05, 0x00,
0x06, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00,
0x1c, 0x00, 0x00, 0x00, 0x88, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00,
0x1e, 0x00, 0x00, 0x00, 0x19, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x00, 0x00,
0xfe, 0x00, 0x02, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x38, 0x00, 0x01, 0x00,
0x36, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x37, 0x00, 0x03, 0x00,
0x0d, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x37, 0x00, 0x03, 0x00,
0x0d, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x37, 0x00, 0x03, 0x00,
0x07, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00,
0x13, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00,
0x21, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x3b, 0x00, 0x04, 0x00,
0x07, 0x00, 0x00, 0x00, 0x27, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00,
0x3b, 0x00, 0x04, 0x00, 0x07, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00,
0x07, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x0c, 0x00, 0x00, 0x00,
0x22, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x0c, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00,
0x94, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00,
0x22, 0x00, 0x00, 0x00, 0x23, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x25, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00,
0x81, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00,
0x24, 0x00, 0x00, 0x00, 0x25, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00,
0x21, 0x00, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00, 0x21, 0x00, 0x00, 0x00,
0x3e, 0x00, 0x03, 0x00, 0x28, 0x00, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00,
0x39, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00,
0x0a, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x3e, 0x00, 0x03, 0x00,
0x27, 0x00, 0x00, 0x00, 0x2a, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x2b, 0x00, 0x00, 0x00, 0x27, 0x00, 0x00, 0x00,
0xfe, 0x00, 0x02, 0x00, 0x2b, 0x00, 0x00, 0x00, 0x38, 0x00, 0x01, 0x00,
0x36, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x37, 0x00, 0x03, 0x00,
0x07, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x37, 0x00, 0x03, 0x00,
0x07, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0xf8, 0x00, 0x02, 0x00,
0x18, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00,
0x2e, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x2f, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00,
0x0c, 0x00, 0x06, 0x00, 0x06, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00,
0x01, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x2f, 0x00, 0x00, 0x00,
0x85, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x31, 0x00, 0x00, 0x00,
0x2e, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00,
0x83, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00,
0x19, 0x00, 0x00, 0x00, 0x32, 0x00, 0x00, 0x00, 0x3d, 0x00, 0x04, 0x00,
0x06, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00,
0x83, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00, 0x35, 0x00, 0x00, 0x00,
0x19, 0x00, 0x00, 0x00, 0x34, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x06, 0x00,
0x06, 0x00, 0x00, 0x00, 0x36, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
0x1c, 0x00, 0x00, 0x00, 0x35, 0x00, 0x00, 0x00, 0x85, 0x00, 0x05, 0x00,
0x06, 0x00, 0x00, 0x00, 0x37, 0x00, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00,
0x36, 0x00, 0x00, 0x00, 0x81, 0x00, 0x05, 0x00, 0x06, 0x00, 0x00, 0x00,
0x38, 0x00, 0x00, 0x00, 0x31, 0x00, 0x00, 0x00, 0x37, 0x00, 0x00, 0x00,
0x7f, 0x00, 0x04, 0x00, 0x06, 0x00, 0x00, 0x00, 0x39, 0x00, 0x00, 0x00,
0x38, 0x00, 0x00, 0x00, 0xfe, 0x00, 0x02, 0x00, 0x39, 0x00, 0x00, 0x00,
0x38, 0x00, 0x01, 0x00
};
static const unsigned int shaders_glsl_logisticregression_comp_spv_len = 4816;
}
}
#endif // define SHADEROP_SHADERLOGISTICREGRESSION_HPP
#include <set>
#include <unordered_map>
#define KP_MAX_DIM_SIZE 1
namespace kp {
/**
* Structured data used in GPU operations.
*
* Tensors are the base building block in Kompute to perform operations across
* GPUs. Each tensor would have a respective Vulkan memory and buffer, which
* would be used to store their respective data. The tensors can be used for GPU
* data storage or transfer.
*/
class Tensor
{
public:
/**
* Type for tensors created: Device allows memory to be transferred from
* staging buffers. Staging are host memory visible. Storage are device
* visible but are not set up to transfer or receive data (only for shader
* storage).
*/
enum class TensorTypes
{
eDevice = 0, ///< Type is device memory, source and destination
eHost = 1, ///< Type is host memory, source and destination
eStorage = 2, ///< Type is Device memory (only)
};
/**
* Base constructor, should not be used unless explicitly intended.
*/
Tensor();
/**
* Default constructor with data provided which would be used to create the
* respective vulkan buffer and memory.
*
* @param data Non-zero-sized vector of data that will be used by the
* tensor
* @param tensorType Type for the tensor which is of type TensorTypes
*/
Tensor(const std::vector<float>& data,
TensorTypes tensorType = TensorTypes::eDevice);
/**
* Destructor which is in charge of freeing vulkan resources unless they
* have been provided externally.
*/
~Tensor();
/**
* Initialiser which calls the initialisation for all the respective tensors
* as well as creates the respective staging tensors. The staging tensors
* would only be created for the tensors of type TensorType::eDevice as
* otherwise there is no need to copy from host memory.
*/
void init(std::shared_ptr<vk::PhysicalDevice> physicalDevice,
std::shared_ptr<vk::Device> device);
/**
* Destroys and frees the GPU resources which include the buffer and memory.
*/
void freeMemoryDestroyGPUResources();
/**
* Returns the vector of data currently contained by the Tensor. It is
* important to ensure that there is no out-of-sync data with the GPU
* memory.
*
* @return Reference to vector of elements representing the data in the
* tensor.
*/
std::vector<float>& data();
/**
* Overrides the subscript operator to expose the underlying data's
* subscript operator which in this case would be its underlying
* vector's.
*
* @param i The index where the element will be returned from.
* @return Returns the element in the position requested.
*/
float& operator[](int index);
/**
* Returns the size/magnitude of the Tensor, which will be the total number
* of elements across all dimensions
*
* @return Unsigned integer representing the total number of elements
*/
uint32_t size();
/**
* Returns the shape of the tensor, which includes the number of dimensions
* and the size per dimension.
*
* @return Array containing the sizes for each dimension. Zero means
* respective dimension is not active.
*/
std::array<uint32_t, KP_MAX_DIM_SIZE> shape();
/**
* Retrieve the tensor type of the Tensor
*
* @return Tensor type of tensor
*/
TensorTypes tensorType();
/**
* Returns true if the tensor initialisation function has been carried out
* successful, which would mean that the buffer and memory will have been
* provisioned.
*/
bool isInit();
/**
* Sets / resets the vector data of the tensor. This function does not
* perform any copies into GPU memory and is only performed on the host.
*/
void setData(const std::vector<float>& data);
/**
* Records a copy from the memory of the tensor provided to the current
* thensor. This is intended to pass memory into a processing, to perform
* a staging buffer transfer, or to gather output (between others).
*
* @param commandBuffer Vulkan Command Buffer to record the commands into
* @param copyFromTensor Tensor to copy the data from
* @param createBarrier Whether to create a barrier that ensures the data is
* copied before further operations. Default is true.
*/
void recordCopyFrom(std::shared_ptr<vk::CommandBuffer> commandBuffer,
std::shared_ptr<Tensor> copyFromTensor,
bool createBarrier);
/**
* Records a copy from the internal staging memory to the device memory
* using an optional barrier to wait for the operation. This function would
* only be relevant for kp::Tensors of type eDevice.
*
* @param commandBuffer Vulkan Command Buffer to record the commands into
* @param createBarrier Whether to create a barrier that ensures the data is
* copied before further operations. Default is true.
*/
void recordCopyFromStagingToDevice(
std::shared_ptr<vk::CommandBuffer> commandBuffer,
bool createBarrier);
/**
* Records a copy from the internal device memory to the staging memory
* using an optional barrier to wait for the operation. This function would
* only be relevant for kp::Tensors of type eDevice.
*
* @param commandBuffer Vulkan Command Buffer to record the commands into
* @param createBarrier Whether to create a barrier that ensures the data is
* copied before further operations. Default is true.
*/
void recordCopyFromDeviceToStaging(
std::shared_ptr<vk::CommandBuffer> commandBuffer,
bool createBarrier);
/**
* Records the buffer memory barrier into the command buffer which
* ensures that relevant data transfers are carried out correctly.
*
* @param commandBuffer Vulkan Command Buffer to record the commands into
* @param srcAccessMask Access flags for source access mask
* @param dstAccessMask Access flags for destination access mask
* @param scrStageMask Pipeline stage flags for source stage mask
* @param dstStageMask Pipeline stage flags for destination stage mask
*/
void recordBufferMemoryBarrier(
std::shared_ptr<vk::CommandBuffer> commandBuffer,
vk::AccessFlagBits srcAccessMask,
vk::AccessFlagBits dstAccessMask,
vk::PipelineStageFlagBits srcStageMask,
vk::PipelineStageFlagBits dstStageMask);
/**
* Constructs a vulkan descriptor buffer info which can be used to specify
* and reference the underlying buffer component of the tensor without
* exposing it.
*
* @return Descriptor buffer info with own buffer
*/
vk::DescriptorBufferInfo constructDescriptorBufferInfo();
/**
* Maps data from the Host Visible GPU memory into the data vector. It
* requires the Tensor to be of staging type for it to work.
*/
void mapDataFromHostMemory();
/**
* Maps data from the data vector into the Host Visible GPU memory. It
* requires the tensor to be of staging type for it to work.
*/
void mapDataIntoHostMemory();
private:
// -------------- NEVER OWNED RESOURCES
std::shared_ptr<vk::PhysicalDevice> mPhysicalDevice;
std::shared_ptr<vk::Device> mDevice;
// -------------- OPTIONALLY OWNED RESOURCES
std::shared_ptr<vk::Buffer> mPrimaryBuffer;
bool mFreePrimaryBuffer = false;
std::shared_ptr<vk::Buffer> mStagingBuffer;
bool mFreeStagingBuffer = false;
std::shared_ptr<vk::DeviceMemory> mPrimaryMemory;
bool mFreePrimaryMemory = false;
std::shared_ptr<vk::DeviceMemory> mStagingMemory;
bool mFreeStagingMemory = false;
// -------------- ALWAYS OWNED RESOURCES
std::vector<float> mData;
TensorTypes mTensorType = TensorTypes::eDevice;
std::array<uint32_t, KP_MAX_DIM_SIZE> mShape;
bool mIsInit = false;
void allocateMemoryCreateGPUResources(); // Creates the vulkan buffer
void createBuffer(std::shared_ptr<vk::Buffer> buffer,
vk::BufferUsageFlags bufferUsageFlags);
void allocateBindMemory(std::shared_ptr<vk::Buffer> buffer,
std::shared_ptr<vk::DeviceMemory> memory,
vk::MemoryPropertyFlags memoryPropertyFlags);
void copyBuffer(std::shared_ptr<vk::CommandBuffer> commandBuffer,
std::shared_ptr<vk::Buffer> bufferFrom,
std::shared_ptr<vk::Buffer> bufferTo,
vk::DeviceSize bufferSize,
vk::BufferCopy copyRegion,
bool createBarrier);
// Private util functions
vk::BufferUsageFlags getPrimaryBufferUsageFlags();
vk::MemoryPropertyFlags getPrimaryMemoryPropertyFlags();
vk::BufferUsageFlags getStagingBufferUsageFlags();
vk::MemoryPropertyFlags getStagingMemoryPropertyFlags();
uint64_t memorySize();
};
} // End namespace kp
namespace kp {
/**
* Base Operation which provides the high level interface that Kompute
* operations implement in order to perform a set of actions in the GPU.
*
* Operations can perform actions on tensors, and optionally can also own an
* Algorithm with respective parameters. kp::Operations with kp::Algorithms
* would inherit from kp::OpBaseAlgo.
*/
class OpBase
{
public:
/**
* Base constructor, should not be used unless explicitly intended.
*/
OpBase() { SPDLOG_DEBUG("Compute OpBase base constructor"); }
/**
* Default constructor with parameters that provides the bare minimum
* requirements for the operations to be able to create and manage their
* sub-components.
*
* @param physicalDevice Vulkan physical device used to find device queues
* @param device Vulkan logical device for passing to Algorithm
* @param commandBuffer Vulkan Command Buffer to record commands into
* @param tensors Tensors that are to be used in this operation
*/
OpBase(std::shared_ptr<vk::PhysicalDevice> physicalDevice,
std::shared_ptr<vk::Device> device,
std::shared_ptr<vk::CommandBuffer> commandBuffer,
std::vector<std::shared_ptr<Tensor>>& tensors)
{
SPDLOG_DEBUG("Compute OpBase constructor with params");
this->mPhysicalDevice = physicalDevice;
this->mDevice = device;
this->mCommandBuffer = commandBuffer;
this->mTensors = tensors;
}
/**
* Default destructor for OpBase class. This OpBase destructor class should
* always be called to destroy and free owned resources unless it is
* intended to destroy the resources in the parent class.
*/
virtual ~OpBase()
{
SPDLOG_DEBUG("Kompute OpBase destructor started");
if (!this->mDevice) {
SPDLOG_WARN("Kompute OpBase destructor called with empty device");
return;
}
if (this->mFreeTensors) {
SPDLOG_DEBUG("Kompute OpBase freeing tensors");
for (std::shared_ptr<Tensor> tensor : this->mTensors) {
if (tensor && tensor->isInit()) {
tensor->freeMemoryDestroyGPUResources();
} else {
SPDLOG_WARN("Kompute OpBase expected to free "
"tensor but has already been freed.");
}
}
}
}
/**
* The init function is responsible for setting up all the resources and
* should be called after the Operation has been created.
*/
virtual void init() = 0;
/**
* The record function is intended to only send a record command or run
* commands that are expected to record operations that are to be submitted
* as a batch into the GPU.
*/
virtual void record() = 0;
/**
* Pre eval is called before the Sequence has called eval and submitted the commands to
* the GPU for processing, and can be used to perform any per-eval setup steps
* required as the computation iteration begins. It's worth noting that
* there are situations where eval can be called multiple times, so the
* resources that are created should be idempotent in case it's called multiple
* times in a row.
*/
virtual void preEval() = 0;
/**
* Post eval is called after the Sequence has called eval and submitted the commands to
* the GPU for processing, and can be used to perform any tear-down steps
* required as the computation iteration finishes. It's worth noting that
* there are situations where eval can be called multiple times, so the
* resources that are destroyed should not require a re-init unless explicitly
* provided by the user.
*/
virtual void postEval() = 0;
protected:
// -------------- NEVER OWNED RESOURCES
std::shared_ptr<vk::PhysicalDevice>
mPhysicalDevice; ///< Vulkan Physical Device
std::shared_ptr<vk::Device> mDevice; ///< Vulkan Logical Device
std::shared_ptr<vk::CommandBuffer>
mCommandBuffer; ///< Vulkan Command Buffer
// -------------- OPTIONALLY OWNED RESOURCES
std::vector<std::shared_ptr<Tensor>>
mTensors; ///< Tensors referenced by operation that can be managed
///< optionally by operation
bool mFreeTensors = false; ///< Explicit boolean that specifies whether the
///< tensors are freed (if they are managed)
};
} // End namespace kp
namespace kp {
/**
* Container of operations that can be sent to GPU as batch
*/
class Sequence
{
public:
/**
* Base constructor for Sequence. Should not be used unless explicit
* intended.
*/
Sequence();
/**
* Main constructor for sequence which requires core vulkan components to
* generate all dependent resources.
*
* @param physicalDevice Vulkan physical device
* @param device Vulkan logical device
* @param computeQueue Vulkan compute queue
* @param queueIndex Vulkan compute queue index in device
*/
Sequence(std::shared_ptr<vk::PhysicalDevice> physicalDevice,
std::shared_ptr<vk::Device> device,
std::shared_ptr<vk::Queue> computeQueue,
uint32_t queueIndex);
/**
* Destructor for sequence which is responsible for cleaning all subsequent
* owned operations.
*/
~Sequence();
/**
* Initialises sequence including the creation of the command pool and the
* command buffer.
*/
void init();
/**
* Begins recording commands for commands to be submitted into the command
* buffer.
*
* @return Boolean stating whether execution was successful.
*/
bool begin();
/**
* Ends the recording and stops recording commands when the record command
* is sent.
*
* @return Boolean stating whether execution was successful.
*/
bool end();
/**
* Eval sends all the recorded and stored operations in the vector of
* operations into the gpu as a submit job with a barrier.
*
* @return Boolean stating whether execution was successful.
*/
bool eval();
/**
* Eval Async sends all the recorded and stored operations in the vector of
* operations into the gpu as a submit job with a barrier. EvalAwait() must
* be called after to ensure the sequence is terminated correctly.
*
* @return Boolean stating whether execution was successful.
*/
bool evalAsync();
/**
* Eval Await waits for the fence to finish processing and then once it
* finishes, it runs the postEval of all operations.
*
* @param waitFor Number of milliseconds to wait before timing out.
* @return Boolean stating whether execution was successful.
*/
bool evalAwait(uint64_t waitFor = UINT64_MAX);
/**
* Returns true if the sequence is currently in recording activated.
*
* @return Boolean stating if recording ongoing.
*/
bool isRecording();
/**
* Returns true if the sequence is currently running - mostly used for async
* workloads.
*
* @return Boolean stating if currently running.
*/
bool isRunning();
/**
* Returns true if the sequence has been successfully initialised.
*
* @return Boolean stating if sequence has been initialised.
*/
bool isInit();
/**
* Destroys and frees the GPU resources which include the buffer and memory
* and sets the sequence as init=False.
*/
void freeMemoryDestroyGPUResources();
/**
* Record function for operation to be added to the GPU queue in batch. This
* template requires classes to be derived from the OpBase class. This
* function also requires the Sequence to be recording, otherwise it will
* not be able to add the operation.
*
* @param tensors Vector of tensors to use for the operation
* @param TArgs Template parameters that are used to initialise operation
* which allows for extensible configurations on initialisation.
*/
template<typename T, typename... TArgs>
bool record(std::vector<std::shared_ptr<Tensor>> tensors, TArgs&&... params)
{
static_assert(std::is_base_of<OpBase, T>::value,
"Kompute Sequence record(...) template only valid with "
"OpBase derived classes");
SPDLOG_DEBUG("Kompute Sequence record function started");
if (!this->isRecording()) {
SPDLOG_ERROR(
"Kompute sequence record attempted when not record BEGIN");
return false;
}
SPDLOG_DEBUG("Kompute Sequence creating OpBase derived class instance");
T* op = new T(this->mPhysicalDevice,
this->mDevice,
this->mCommandBuffer,
tensors,
std::forward<TArgs>(params)...);
OpBase* baseOp = dynamic_cast<OpBase*>(op);
std::unique_ptr<OpBase> baseOpPtr{ baseOp };
SPDLOG_DEBUG(
"Kompute Sequence running init on OpBase derived class instance");
baseOpPtr->init();
SPDLOG_DEBUG(
"Kompute Sequence running record on OpBase derived class instance");
baseOpPtr->record();
mOperations.push_back(std::move(baseOpPtr));
return true;
}
private:
// -------------- NEVER OWNED RESOURCES
std::shared_ptr<vk::PhysicalDevice> mPhysicalDevice = nullptr;
std::shared_ptr<vk::Device> mDevice = nullptr;
std::shared_ptr<vk::Queue> mComputeQueue = nullptr;
uint32_t mQueueIndex = -1;
// -------------- OPTIONALLY OWNED RESOURCES
std::shared_ptr<vk::CommandPool> mCommandPool = nullptr;
bool mFreeCommandPool = false;
std::shared_ptr<vk::CommandBuffer> mCommandBuffer = nullptr;
bool mFreeCommandBuffer = false;
// -------------- ALWAYS OWNED RESOURCES
vk::Fence mFence;
std::vector<std::unique_ptr<OpBase>> mOperations;
// State
bool mIsInit = false;
bool mRecording = false;
bool mIsRunning = false;
// Create functions
void createCommandPool();
void createCommandBuffer();
};
} // End namespace kp
namespace kp {
/**
Operation that syncs tensor's device by mapping local data into the device memory. For TensorTypes::eDevice it will use a record operation for the memory to be syncd into GPU memory which means that the operation will be done in sync with GPU commands. For TensorTypes::eStaging it will only map the data into host memory which will happen during preEval before the recorded commands are dispatched. This operation won't have any effect on TensorTypes::eStaging.
*/
class OpTensorSyncDevice : public OpBase
{
public:
OpTensorSyncDevice();
/**
* Default constructor with parameters that provides the core vulkan resources and the tensors that will be used in the operation. The tensos provided cannot be of type TensorTypes::eStorage.
*
* @param physicalDevice Vulkan physical device used to find device queues
* @param device Vulkan logical device for passing to Algorithm
* @param commandBuffer Vulkan Command Buffer to record commands into
* @param tensors Tensors that will be used to create in operation.
*/
OpTensorSyncDevice(std::shared_ptr<vk::PhysicalDevice> physicalDevice,
std::shared_ptr<vk::Device> device,
std::shared_ptr<vk::CommandBuffer> commandBuffer,
std::vector<std::shared_ptr<Tensor>> tensors);
/**
* Default destructor. This class does not manage memory so it won't be expecting the parent to perform a release.
*/
~OpTensorSyncDevice() override;
/**
* Performs basic checks such as ensuring that there is at least one tensor provided with min memory of 1 element.
*/
void init() override;
/**
* For device tensors, it records the copy command for the tensor to copy the data from its staging to device memory.
*/
void record() override;
/**
* Does not perform any preEval commands.
*/
virtual void preEval() override;
/**
* Does not perform any postEval commands.
*/
virtual void postEval() override;
private:
};
} // End namespace kp
#define KP_DEFAULT_SESSION "DEFAULT"
namespace kp {
/**
Base orchestrator which creates and manages device and child components
*/
class Manager
{
public:
/**
Base constructor and default used which creates the base resources
including choosing the device 0 by default.
*/
Manager();
/**
* Similar to base constructor but allows the user to provide the device
* they would like to create the resources on.
*
* @param physicalDeviceIndex The index of the physical device to use
* @param familyQueueIndices (Optional) List of queue indices to add for
* explicit allocation
* @param totalQueues The total number of compute queues to create.
*/
Manager(uint32_t physicalDeviceIndex,
const std::vector<uint32_t>& familyQueueIndices = {});
/**
* Manager constructor which allows your own vulkan application to integrate
* with the vulkan kompute use.
*
* @param instance Vulkan compute instance to base this application
* @param physicalDevice Vulkan physical device to use for application
* @param device Vulkan logical device to use for all base resources
* @param physicalDeviceIndex Index for vulkan physical device used
*/
Manager(std::shared_ptr<vk::Instance> instance,
std::shared_ptr<vk::PhysicalDevice> physicalDevice,
std::shared_ptr<vk::Device> device,
uint32_t physicalDeviceIndex);
/**
* Manager destructor which would ensure all owned resources are destroyed
* unless explicitly stated that resources should not be destroyed or freed.
*/
~Manager();
/**
* Get or create a managed Sequence that will be contained by this manager.
* If the named sequence does not currently exist, it would be created and
* initialised.
*
* @param sequenceName The name for the named sequence to be retrieved or
* created
* @param queueIndex The queue to use from the available queues
* @return Shared pointer to the manager owned sequence resource
*/
std::shared_ptr<Sequence> sequence(
std::string sequenceName = KP_DEFAULT_SESSION,
uint32_t queueIndex = 0);
/**
* Function that evaluates operation against named sequence.
*
* @param tensors The tensors to be used in the operation recorded
* @param sequenceName The name of the sequence to be retrieved or created
* @param TArgs Template parameters that will be used to initialise
* Operation to allow for extensible configurations on initialisation
*/
template<typename T, typename... TArgs>
void evalOp(std::vector<std::shared_ptr<Tensor>> tensors,
std::string sequenceName,
TArgs&&... params)
{
SPDLOG_DEBUG("Kompute Manager evalOp triggered");
std::shared_ptr<kp::Sequence> sq =
this->sequence(sequenceName);
SPDLOG_DEBUG("Kompute Manager evalOp running sequence BEGIN");
sq->begin();
SPDLOG_DEBUG("Kompute Manager evalOp running sequence RECORD");
sq->record<T>(tensors, std::forward<TArgs>(params)...);
SPDLOG_DEBUG("Kompute Manager evalOp running sequence END");
sq->end();
SPDLOG_DEBUG("Kompute Manager evalOp running sequence EVAL");
sq->eval();
SPDLOG_DEBUG("Kompute Manager evalOp running sequence SUCCESS");
}
/**
* Function that evaluates operation against a newly created sequence.
*
* @param tensors The tensors to be used in the operation recorded
* @param TArgs Template parameters that will be used to initialise
* Operation to allow for extensible configurations on initialisation
*/
template<typename T, typename... TArgs>
void evalOpDefault(std::vector<std::shared_ptr<Tensor>> tensors,
TArgs&&... params)
{
SPDLOG_DEBUG("Kompute Manager evalOp Default triggered");
this->mCurrentSequenceIndex++;
this->evalOp<T>(
tensors, KP_DEFAULT_SESSION, std::forward<TArgs>(params)...);
}
/**
* Function that evaluates operation against named sequence asynchronously.
*
* @param tensors The tensors to be used in the operation recorded
* @param sequenceName The name of the sequence to be retrieved or created
* @param params Template parameters that will be used to initialise
* Operation to allow for extensible configurations on initialisation
*/
template<typename T, typename... TArgs>
void evalOpAsync(std::vector<std::shared_ptr<Tensor>> tensors,
std::string sequenceName,
TArgs&&... params)
{
SPDLOG_DEBUG("Kompute Manager evalOpAsync triggered");
std::shared_ptr<kp::Sequence> sq =
this->sequence(sequenceName);
SPDLOG_DEBUG("Kompute Manager evalOpAsync running sequence BEGIN");
sq->begin();
SPDLOG_DEBUG("Kompute Manager evalOpAsync running sequence RECORD");
sq->record<T>(tensors, std::forward<TArgs>(params)...);
SPDLOG_DEBUG("Kompute Manager evalOpAsync running sequence END");
sq->end();
SPDLOG_DEBUG("Kompute Manager evalOpAsync running sequence EVAL");
sq->evalAsync();
SPDLOG_DEBUG("Kompute Manager evalOpAsync running sequence SUCCESS");
}
/**
* Operation that evaluates operation against default sequence
* asynchronously.
*
* @param tensors The tensors to be used in the operation recorded
* @param params Template parameters that will be used to initialise
* Operation to allow for extensible configurations on initialisation
*/
template<typename T, typename... TArgs>
void evalOpAsyncDefault(std::vector<std::shared_ptr<Tensor>> tensors,
TArgs&&... params)
{
SPDLOG_DEBUG("Kompute Manager evalOpAsyncDefault triggered");
this->mCurrentSequenceIndex++;
this->evalOpAsync<T>(
tensors, KP_DEFAULT_SESSION, std::forward<TArgs>(params)...);
}
/**
* Operation that awaits for named sequence to finish.
*
* @param sequenceName The name of the sequence to wait for termination
* @param waitFor The amount of time to wait before timing out
*/
void evalOpAwait(std::string sequenceName, uint64_t waitFor = UINT64_MAX)
{
SPDLOG_DEBUG("Kompute Manager evalOpAwait triggered with sequence {}",
sequenceName);
std::unordered_map<std::string, std::shared_ptr<Sequence>>::iterator
found = this->mManagedSequences.find(sequenceName);
if (found != this->mManagedSequences.end()) {
if (std::shared_ptr<kp::Sequence> sq = found->second) {
SPDLOG_DEBUG("Kompute Manager evalOpAwait running sequence "
"Sequence EVAL AWAIT");
if (sq->isRunning()) {
sq->evalAwait(waitFor);
}
}
SPDLOG_DEBUG(
"Kompute Manager evalOpAwait running sequence SUCCESS");
} else {
SPDLOG_ERROR("Kompute Manager evalOpAwait Sequence not found");
}
}
/**
* Operation that awaits for default sequence to finish.
*
* @param tensors The tensors to be used in the operation recorded
* @param params Template parameters that will be used to initialise
* Operation to allow for extensible configurations on initialisation
*/
void evalOpAwaitDefault(uint64_t waitFor = UINT64_MAX)
{
SPDLOG_DEBUG("Kompute Manager evalOpAwaitDefault triggered");
this->evalOpAwait(KP_DEFAULT_SESSION, waitFor);
}
/**
* Function that simplifies the common workflow of tensor creation and
* initialization. It will take the constructor parameters for a Tensor
* and will will us it to create a new Tensor and then create it. The
* tensor memory will then be managed and owned by the manager.
*
* @param data The data to initialize the tensor with
* @param tensorType The type of tensor to initialize
* @param syncDataToGPU Whether to sync the data to GPU memory
* @returns Initialized Tensor with memory Syncd to GPU device
*/
std::shared_ptr<Tensor> tensor(
const std::vector<float>& data,
Tensor::TensorTypes tensorType = Tensor::TensorTypes::eDevice,
bool syncDataToGPU = true);
/**
* Function that simplifies the common workflow of tensor initialisation. It
* will take the constructor parameters for a Tensor and will will us it to
* create a new Tensor. The tensor memory will then be managed and owned by
* the manager.
*
* @param tensors Array of tensors to rebuild
* @param syncDataToGPU Whether to sync the data to GPU memory
*/
void rebuild(std::vector<std::shared_ptr<kp::Tensor>> tensors,
bool syncDataToGPU = true);
/**
* Function that simplifies the common workflow of tensor initialisation. It
* will take the constructor parameters for a Tensor and will will us it to
* create a new Tensor. The tensor memory will then be managed and owned by
* the manager.
*
* @param tensors Single tensor to rebuild
* @param syncDataToGPU Whether to sync the data to GPU memory
*/
void rebuild(std::shared_ptr<kp::Tensor> tensor,
bool syncDataToGPU = true);
/**
* Destroy owned Vulkan GPU resources and free GPU memory for
* single tensor.
*
* @param tensors Single tensor to rebuild
*/
void destroy(std::shared_ptr<kp::Tensor> tensor);
/**
* Destroy owned Vulkan GPU resources and free GPU memory for
* vector of tensors.
*
* @param tensors Single tensor to rebuild
*/
void destroy(std::vector<std::shared_ptr<kp::Tensor>> tensors);
/**
* Destroy owned Vulkan GPU resources and free GPU memory for
* vector of sequences. Destroying by sequence name is more efficent
* and hence recommended instead of by object.
*
* @param sequences Vector for shared ptrs with sequences to destroy
*/
void destroy(std::vector<std::shared_ptr<kp::Sequence>> sequences);
/**
* Destroy owned Vulkan GPU resources and free GPU memory for
* single sequence. Destroying by sequence name is more efficent
* and hence recommended instead of by object.
*
* @param sequences Single sequence to rebuild
*/
void destroy(std::shared_ptr<kp::Sequence> sequence);
/**
* Destroy owned Vulkan GPU resources and free GPU memory for
* sequence by name.
*
* @param sequenceName Single name of named sequence to destroy
*/
void destroy(const std::string& sequenceName);
/**
* Destroy owned Vulkan GPU resources and free GPU memory for
* sequences using vector of named sequence names.
*
* @param sequenceName Vector of sequence names to destroy
*/
void destroy(const std::vector<std::string>& sequenceNames);
private:
// -------------- OPTIONALLY OWNED RESOURCES
std::shared_ptr<vk::Instance> mInstance = nullptr;
bool mFreeInstance = false;
std::shared_ptr<vk::PhysicalDevice> mPhysicalDevice = nullptr;
uint32_t mPhysicalDeviceIndex = -1;
std::shared_ptr<vk::Device> mDevice = nullptr;
bool mFreeDevice = false;
// -------------- ALWAYS OWNED RESOURCES
std::set<std::shared_ptr<Tensor>> mManagedTensors;
std::unordered_map<std::string, std::shared_ptr<Sequence>>
mManagedSequences;
std::vector<uint32_t> mComputeQueueFamilyIndices;
std::vector<std::shared_ptr<vk::Queue>> mComputeQueues;
uint32_t mCurrentSequenceIndex = -1;
#if DEBUG
#ifndef KOMPUTE_DISABLE_VK_DEBUG_LAYERS
vk::DebugReportCallbackEXT mDebugReportCallback;
vk::DispatchLoaderDynamic mDebugDispatcher;
#endif
#endif
// Create functions
void createInstance();
void createDevice(const std::vector<uint32_t>& familyQueueIndices = {});
};
} // End namespace kp
#include <fstream>
namespace kp {
/**
Abstraction for compute shaders that are run on top of tensors grouped via
ParameterGroups (which group descriptorsets)
*/
class Algorithm
{
public:
/**
Base constructor for Algorithm. Should not be used unless explicit
intended.
*/
Algorithm();
/**
* Default constructor for Algorithm
*
* @param device The Vulkan device to use for creating resources
* @param commandBuffer The vulkan command buffer to bind the pipeline and
* shaders
*/
Algorithm(std::shared_ptr<vk::Device> device,
std::shared_ptr<vk::CommandBuffer> commandBuffer,
const Constants& specializationConstants = {});
/**
* Initialiser for the shader data provided to the algorithm as well as
* tensor parameters that will be used in shader.
*
* @param shaderFileData The bytes in spir-v format of the shader
* @tensorParams The Tensors to be used in the Algorithm / shader for
* @specalizationInstalces The specialization parameters to pass to the function
* processing
*/
void init(const std::vector<char>& shaderFileData,
std::vector<std::shared_ptr<Tensor>> tensorParams);
/**
* Destructor for Algorithm which is responsible for freeing and desroying
* respective pipelines and owned parameter groups.
*/
~Algorithm();
/**
* Records the dispatch function with the provided template parameters or
* alternatively using the size of the tensor by default.
*
* @param x Layout X dispatch value
* @param y Layout Y dispatch value
* @param z Layout Z dispatch value
*/
void recordDispatch(uint32_t x = 1, uint32_t y = 1, uint32_t z = 1);
private:
// -------------- NEVER OWNED RESOURCES
std::shared_ptr<vk::Device> mDevice;
std::shared_ptr<vk::CommandBuffer> mCommandBuffer;
// -------------- OPTIONALLY OWNED RESOURCES
std::shared_ptr<vk::DescriptorSetLayout> mDescriptorSetLayout;
bool mFreeDescriptorSetLayout = false;
std::shared_ptr<vk::DescriptorPool> mDescriptorPool;
bool mFreeDescriptorPool = false;
std::shared_ptr<vk::DescriptorSet> mDescriptorSet;
bool mFreeDescriptorSet = false;
std::shared_ptr<vk::ShaderModule> mShaderModule;
bool mFreeShaderModule = false;
std::shared_ptr<vk::PipelineLayout> mPipelineLayout;
bool mFreePipelineLayout = false;
std::shared_ptr<vk::PipelineCache> mPipelineCache;
bool mFreePipelineCache = false;
std::shared_ptr<vk::Pipeline> mPipeline;
bool mFreePipeline = false;
// -------------- ALWAYS OWNED RESOURCES
Constants mSpecializationConstants;
// Create util functions
void createShaderModule(const std::vector<char>& shaderFileData);
void createPipeline();
// Parameters
void createParameters(std::vector<std::shared_ptr<Tensor>>& tensorParams);
void createDescriptorPool();
};
} // End namespace kp
namespace kp {
/**
* Operation that provides a general abstraction that simplifies the use of
* algorithm and parameter components which can be used with shaders.
* By default it enables the user to provide a dynamic number of tensors
* which are then passed as inputs.
*/
class OpAlgoBase : public OpBase
{
public:
/**
* Base constructor, should not be used unless explicitly intended.
*/
OpAlgoBase();
/**
* Default constructor with parameters that provides the bare minimum
* requirements for the operations to be able to create and manage their
* sub-components.
*
* @param physicalDevice Vulkan physical device used to find device queues
* @param device Vulkan logical device for passing to Algorithm
* @param commandBuffer Vulkan Command Buffer to record commands into
* @param tensors Tensors that are to be used in this operation
* @param shaderFilePath Optional parameter to specify the shader to load (either in spirv or raw format)
* @param komputeWorkgroup Optional parameter to specify the layout for processing
*/
OpAlgoBase(std::shared_ptr<vk::PhysicalDevice> physicalDevice,
std::shared_ptr<vk::Device> device,
std::shared_ptr<vk::CommandBuffer> commandBuffer,
std::vector<std::shared_ptr<Tensor>>& tensors,
const Workgroup& komputeWorkgroup = {},
const Constants& specializationConstants = {});
/**
* Constructor that enables a file to be passed to the operation with
* the contents of the shader. This can be either in raw format or in
* compiled SPIR-V binary format.
*
* @param physicalDevice Vulkan physical device used to find device queues
* @param device Vulkan logical device for passing to Algorithm
* @param commandBuffer Vulkan Command Buffer to record commands into
* @param tensors Tensors that are to be used in this operation
* @param shaderFilePath Parameter to specify the shader to load (either in spirv or raw format)
* @param komputeWorkgroup Optional parameter to specify the layout for processing
*/
OpAlgoBase(std::shared_ptr<vk::PhysicalDevice> physicalDevice,
std::shared_ptr<vk::Device> device,
std::shared_ptr<vk::CommandBuffer> commandBuffer,
std::vector<std::shared_ptr<Tensor>>& tensors,
std::string shaderFilePath,
const Workgroup& komputeWorkgroup = {},
const Constants& specializationConstants = {});
/**
* Constructor that enables raw shader data to be passed to the main operation
* which can be either in raw shader glsl code or in compiled SPIR-V binary.
*
* @param physicalDevice Vulkan physical device used to find device queues
* @param device Vulkan logical device for passing to Algorithm
* @param commandBuffer Vulkan Command Buffer to record commands into
* @param tensors Tensors that are to be used in this operation
* @param shaderDataRaw Optional parameter to specify the shader data either in binary or raw form
* @param komputeWorkgroup Optional parameter to specify the layout for processing
*/
OpAlgoBase(std::shared_ptr<vk::PhysicalDevice> physicalDevice,
std::shared_ptr<vk::Device> device,
std::shared_ptr<vk::CommandBuffer> commandBuffer,
std::vector<std::shared_ptr<Tensor>>& tensors,
const std::vector<char>& shaderDataRaw,
const Workgroup& komputeWorkgroup = {},
const Constants& specializationConstants = {});
/**
* Default destructor, which is in charge of destroying the algorithm
* components but does not destroy the underlying tensors
*/
virtual ~OpAlgoBase() override;
/**
* The init function is responsible for the initialisation of the algorithm
* component based on the parameters specified, and allows for extensibility
* on the options provided. Further dependent classes can perform more
* specific checks such as ensuring tensors provided are initialised, etc.
*/
virtual void init() override;
/**
* This records the commands that are to be sent to the GPU. This includes
* the barriers that ensure the memory has been copied before going in and
* out of the shader, as well as the dispatch operation that sends the
* shader processing to the gpu. This function also records the GPU memory
* copy of the output data for the staging buffer so it can be read by the
* host.
*/
virtual void record() override;
/**
* Does not perform any preEval commands.
*/
virtual void preEval() override;
/**
* Executes after the recorded commands are submitted, and performs a copy
* of the GPU Device memory into the staging buffer so the output data can
* be retrieved.
*/
virtual void postEval() override;
protected:
// -------------- NEVER OWNED RESOURCES
// -------------- OPTIONALLY OWNED RESOURCES
std::shared_ptr<Algorithm> mAlgorithm;
bool mFreeAlgorithm = false;
// -------------- ALWAYS OWNED RESOURCES
Workgroup mKomputeWorkgroup;
std::string mShaderFilePath; ///< Optional member variable which can be provided for the OpAlgoBase to find the data automatically and load for processing
std::vector<char> mShaderDataRaw; ///< Optional member variable which can be provided to contain either the raw shader content or the spirv binary content
virtual std::vector<char> fetchSpirvBinaryData();
};
} // End namespace kp
#include <fstream>
namespace kp {
/**
* Operation base class to simplify the creation of operations that require
* right hand and left hand side datapoints together with a single output.
* The expected data passed is two input tensors and one output tensor.
*/
class OpAlgoLhsRhsOut : public OpAlgoBase
{
public:
/**
* Base constructor, should not be used unless explicitly intended.
*/
OpAlgoLhsRhsOut();
/**
* Default constructor with parameters that provides the bare minimum
* requirements for the operations to be able to create and manage their
* sub-components.
*
* @param physicalDevice Vulkan physical device used to find device queues
* @param device Vulkan logical device for passing to Algorithm
* @param commandBuffer Vulkan Command Buffer to record commands into
* @param tensors Tensors that are to be used in this operation
* @param freeTensors Whether operation manages the memory of the Tensors
* @param komputeWorkgroup Optional parameter to specify the layout for processing
*/
OpAlgoLhsRhsOut(std::shared_ptr<vk::PhysicalDevice> physicalDevice,
std::shared_ptr<vk::Device> device,
std::shared_ptr<vk::CommandBuffer> commandBuffer,
std::vector<std::shared_ptr<Tensor>> tensors,
const Workgroup& komputeWorkgroup = {});
/**
* Default destructor, which is in charge of destroying the algorithm
* components but does not destroy the underlying tensors
*/
virtual ~OpAlgoLhsRhsOut() override;
/**
* The init function is responsible for ensuring that all of the tensors
* provided are aligned with requirements such as LHS, RHS and Output
* tensors, and creates the algorithm component which processes the
* computation.
*/
virtual void init() override;
/**
* This records the commands that are to be sent to the GPU. This includes
* the barriers that ensure the memory has been copied before going in and
* out of the shader, as well as the dispatch operation that sends the
* shader processing to the gpu. This function also records the GPU memory
* copy of the output data for the staging buffer so it can be read by the
* host.
*/
virtual void record() override;
/**
* Executes after the recorded commands are submitted, and performs a copy
* of the GPU Device memory into the staging buffer so the output data can
* be retrieved.
*/
virtual void postEval() override;
protected:
// -------------- NEVER OWNED RESOURCES
std::shared_ptr<Tensor> mTensorLHS; ///< Reference to the parameter used in the left hand side equation of the shader
std::shared_ptr<Tensor> mTensorRHS; ///< Reference to the parameter used in the right hand side equation of the shader
std::shared_ptr<Tensor> mTensorOutput; ///< Reference to the parameter used in the output of the shader and will be copied with a staging vector
};
} // End namespace kp
#include <fstream>
#if RELEASE
#endif
namespace kp {
/**
* Operation that performs multiplication on two tensors and outpus on third
* tensor.
*/
class OpMult : public OpAlgoBase
{
public:
/**
* Base constructor, should not be used unless explicitly intended.
*/
OpMult() {
}
/**
* Default constructor with parameters that provides the bare minimum
* requirements for the operations to be able to create and manage their
* sub-components.
*
* @param physicalDevice Vulkan physical device used to find device queues
* @param device Vulkan logical device for passing to Algorithm
* @param commandBuffer Vulkan Command Buffer to record commands into
* @param tensors Tensors that are to be used in this operation
* @param komputeWorkgroup Optional parameter to specify the layout for processing
*/
OpMult(std::shared_ptr<vk::PhysicalDevice> physicalDevice,
std::shared_ptr<vk::Device> device,
std::shared_ptr<vk::CommandBuffer> commandBuffer,
std::vector<std::shared_ptr<Tensor>> tensors,
const Workgroup& komputeWorkgroup = {})
: OpAlgoBase(physicalDevice, device, commandBuffer, tensors, "", komputeWorkgroup)
{
SPDLOG_DEBUG("Kompute OpMult constructor with params");
#ifndef RELEASE
this->mShaderFilePath = "shaders/glsl/opmult.comp";
#endif
}
#if RELEASE
/**
* If RELEASE=1 it will be using the static version of the shader which is
* loaded using this file directly. Otherwise it should not override the function.
*/
std::vector<char> fetchSpirvBinaryData() override
{
SPDLOG_WARN(
"Kompute OpMult Running shaders directly from header");
return std::vector<char>(
shader_data::shaders_glsl_opmult_comp_spv,
shader_data::shaders_glsl_opmult_comp_spv +
kp::shader_data::shaders_glsl_opmult_comp_spv_len);
}
#endif
/**
* Default destructor, which is in charge of destroying the algorithm
* components but does not destroy the underlying tensors
*/
~OpMult() override {
SPDLOG_DEBUG("Kompute OpMult destructor started");
}
};
} // End namespace kp
namespace kp {
/**
Operation that copies the data from the first tensor to the rest of the tensors provided, using a record command for all the vectors. This operation does not own/manage the memory of the tensors passed to it. The operation must only receive tensors of type
*/
class OpTensorCopy : public OpBase
{
public:
OpTensorCopy();
/**
* Default constructor with parameters that provides the core vulkan resources and the tensors that will be used in the operation.
*
* @param physicalDevice Vulkan physical device used to find device queues
* @param device Vulkan logical device for passing to Algorithm
* @param commandBuffer Vulkan Command Buffer to record commands into
* @param tensors Tensors that will be used to create in operation.
*/
OpTensorCopy(std::shared_ptr<vk::PhysicalDevice> physicalDevice,
std::shared_ptr<vk::Device> device,
std::shared_ptr<vk::CommandBuffer> commandBuffer,
std::vector<std::shared_ptr<Tensor>> tensors);
/**
* Default destructor. This class does not manage memory so it won't be expecting the parent to perform a release.
*/
~OpTensorCopy() override;
/**
* Performs basic checks such as ensuring there are at least two tensors provided, that they are initialised and that they are not of type TensorTypes::eStorage.
*/
void init() override;
/**
* Records the copy commands from the first tensor into all the other tensors provided. Also optionally records a barrier.
*/
void record() override;
/**
* Does not perform any preEval commands.
*/
virtual void preEval() override;
/**
* Copies the local vectors for all the tensors to sync the data with the gpu.
*/
virtual void postEval() override;
private:
};
} // End namespace kp
namespace kp {
/**
Operation that syncs tensor's local memory by mapping device data into the local CPU memory. For TensorTypes::eDevice it will use a record operation for the memory to be syncd into GPU memory which means that the operation will be done in sync with GPU commands. For TensorTypes::eStaging it will only map the data into host memory which will happen during preEval before the recorded commands are dispatched. This operation won't have any effect on TensorTypes::eStaging.
*/
class OpTensorSyncLocal : public OpBase
{
public:
OpTensorSyncLocal();
/**
* Default constructor with parameters that provides the core vulkan resources and the tensors that will be used in the operation. The tensors provided cannot be of type TensorTypes::eStorage.
*
* @param physicalDevice Vulkan physical device used to find device queues
* @param device Vulkan logical device for passing to Algorithm
* @param commandBuffer Vulkan Command Buffer to record commands into
* @param tensors Tensors that will be used to create in operation.
*/
OpTensorSyncLocal(std::shared_ptr<vk::PhysicalDevice> physicalDevice,
std::shared_ptr<vk::Device> device,
std::shared_ptr<vk::CommandBuffer> commandBuffer,
std::vector<std::shared_ptr<Tensor>> tensors);
/**
* Default destructor. This class does not manage memory so it won't be expecting the parent to perform a release.
*/
~OpTensorSyncLocal() override;
/**
* Performs basic checks such as ensuring that there is at least one tensor provided with min memory of 1 element.
*/
void init() override;
/**
* For device tensors, it records the copy command for the tensor to copy the data from its device to staging memory.
*/
void record() override;
/**
* Does not perform any preEval commands.
*/
virtual void preEval() override;
/**
* For host tensors it performs the map command from the host memory into local memory.
*/
virtual void postEval() override;
private:
};
} // End namespace kp
|
string nextP(vector<int> &v, string s, int k, vector<int> fact) {
if (v.empty())
return s;
//or iteratively while !v.empty()
int n = v.size();
int idx = k / fact[n - 1];
s.append(to_string(v[idx]));
k -= idx * fact[n - 1];
v.erase(v.begin() + idx);
return nextP(v, s, k, fact);
}
string Solution::getPermutation(int n, int B) {
vector<int> v(n);
for (int i = 0; i < n; i++)
v[i] = i + 1;
vector<int> fact(n + 1, 1);
for (int i = 1; i <= n; i++)
fact[i] = fact[i - 1] * i;
B--;
string s = "";
return nextP(v, s, B, fact);
}
//Proper backtracking
void nextP(int idx, int A, vector<string> &ans, string comb, unordered_map<int, bool> mp, int &cnt, int B) {
if (idx == A) {
ans.push_back(comb);
cnt++;
return;
}
for (int i = 1; i <= A && cnt < B; i++) {
if (mp[i]) {
int sz = comb.size();
string temp = to_string(i);
comb += temp;
mp[i] = 0;
nextP(idx + 1, A, ans, comb, mp, cnt, B);
mp[i] = 1;
comb.erase(sz);
}
}
}
string Solution::getPermutation(int A, int B) {
unordered_map<int, bool> mp;
for (int i = 1; i <= A; i++)
mp[i] = 1;
string comb = "";
vector<string> ans;
int cnt = 0;
nextP(0, A, ans, comb, mp, cnt, B);
return ans[ans.size() - 1];
}
for (int i = 1; i <= A; i++) {
if (mp[A[i]]) {
totalBefore += (i - 1) * fact(A - idx - 1);
if (totalBefore > B)
}
}
|
#include<stdio.h>
#include<conio.h>
void Adder(char*, char*);
void main(){
char arr1[50];
char arr2[50];
gets_s(arr1);
gets_s(arr2);
Adder(arr1, arr2);
_getch();
}
void Adder(char *a, char *b){
int i = 0;
int j = 0;
int k = 0;
char added[50];
while (a[k] != '\0')
{
added[k] = ((int)a[i]-48) +((int)b[i]-48);
if (added[k] == 9){
i++;
}
else if(added[k] < 9){
i++;
j = i;
}
else{
added[j]++;
added[i] = added[k] % 10;
while (i!=j)
{
j++;
added[j] = 0;
}
}
k++;
}
added[k] = '\0';
for (int i = 0; added[i] != '\0'; i++) printf("%d", added[i]);
}
|
#include "Constants.h"
#include "llvm/ADT/StringRef.h"
#include "Constant.h"
#include "llvm/ADT/ArrayRef.h"
#include "LLVMContext.h"
#include "Type.h"
#include "Constant.h"
#include "DerivedTypes.h"
#include "Value.h"
#include "Use.h"
#include "Function.h"
#include "BasicBlock.h"
#include "Instruction.h"
#include <msclr/marshal.h>
#include "utils.h"
using namespace LLVM;
ConstantInt::ConstantInt(llvm::ConstantInt *base)
: base(base)
, Constant(base)
{
}
inline ConstantInt ^ConstantInt::_wrap(llvm::ConstantInt *base)
{
return base ? gcnew ConstantInt(base) : nullptr;
}
ConstantInt::!ConstantInt()
{
}
ConstantInt::~ConstantInt()
{
this->!ConstantInt();
}
ConstantInt ^ConstantInt::getTrue(LLVMContext ^Context)
{
return ConstantInt::_wrap(llvm::ConstantInt::getTrue(*Context->base));
}
ConstantInt ^ConstantInt::getFalse(LLVMContext ^Context)
{
return ConstantInt::_wrap(llvm::ConstantInt::getFalse(*Context->base));
}
Constant ^ConstantInt::getTrue(Type ^Ty)
{
return Constant::_wrap(llvm::ConstantInt::getTrue(Ty->base));
}
Constant ^ConstantInt::getFalse(Type ^Ty)
{
return Constant::_wrap(llvm::ConstantInt::getFalse(Ty->base));
}
Constant ^ConstantInt::get(Type ^Ty, uint64_t V)
{
return Constant::_wrap(llvm::ConstantInt::get(Ty->base, V));
}
Constant ^ConstantInt::get(Type ^Ty, uint64_t V, bool isSigned)
{
return Constant::_wrap(llvm::ConstantInt::get(Ty->base, V, isSigned));
}
ConstantInt ^ConstantInt::get(IntegerType ^Ty, uint64_t V)
{
return ConstantInt::_wrap(llvm::ConstantInt::get(Ty->base, V));
}
ConstantInt ^ConstantInt::get(IntegerType ^Ty, uint64_t V, bool isSigned)
{
return ConstantInt::_wrap(llvm::ConstantInt::get(Ty->base, V, isSigned));
}
ConstantInt ^ConstantInt::getSigned(IntegerType ^Ty, int64_t V)
{
return ConstantInt::_wrap(llvm::ConstantInt::getSigned(Ty->base, V));
}
Constant ^ConstantInt::getSigned(Type ^Ty, int64_t V)
{
return Constant::_wrap(llvm::ConstantInt::getSigned(Ty->base, V));
}
ConstantInt ^ConstantInt::get(IntegerType ^Ty, System::String ^Str, uint8_t radix)
{
msclr::interop::marshal_context ctx;
return ConstantInt::_wrap(llvm::ConstantInt::get(Ty->base, ctx.marshal_as<const char *>(Str), radix));
}
unsigned ConstantInt::getBitWidth()
{
return base->getBitWidth();
}
inline uint64_t ConstantInt::getZExtValue()
{
return base->getZExtValue();
}
inline int64_t ConstantInt::getSExtValue()
{
return base->getSExtValue();
}
bool ConstantInt::equalsInt(uint64_t V)
{
return base->equalsInt(V);
}
inline IntegerType ^ConstantInt::getType()
{
return IntegerType::_wrap(base->getType());
}
bool ConstantInt::isValueValidForType(Type ^Ty, uint64_t V)
{
return llvm::ConstantInt::isValueValidForType(Ty->base, V);
}
bool ConstantInt::isValueValidForType(Type ^Ty, int64_t V)
{
return llvm::ConstantInt::isValueValidForType(Ty->base, V);
}
bool ConstantInt::isNegative()
{
return base->isNegative();
}
bool ConstantInt::isZero()
{
return base->isZero();
}
bool ConstantInt::isOne()
{
return base->isOne();
}
bool ConstantInt::isMinusOne()
{
return base->isMinusOne();
}
bool ConstantInt::isMaxValue(bool isSigned)
{
return base->isMaxValue(isSigned);
}
bool ConstantInt::isMinValue(bool isSigned)
{
return base->isMinValue(isSigned);
}
bool ConstantInt::uge(uint64_t Num)
{
return base->uge(Num);
}
bool ConstantInt::classof(Value ^V)
{
return llvm::ConstantInt::classof(V->base);
}
ConstantFP::ConstantFP(llvm::ConstantFP *base)
: base(base)
, Constant(base)
{
}
inline ConstantFP ^ConstantFP::_wrap(llvm::ConstantFP *base)
{
return base ? gcnew ConstantFP(base) : nullptr;
}
ConstantFP::!ConstantFP()
{
}
ConstantFP::~ConstantFP()
{
this->!ConstantFP();
}
Constant ^ConstantFP::getZeroValueForNegation(Type ^Ty)
{
return Constant::_wrap(llvm::ConstantFP::getZeroValueForNegation(Ty->base));
}
Constant ^ConstantFP::get(Type ^Ty, double V)
{
return Constant::_wrap(llvm::ConstantFP::get(Ty->base, V));
}
Constant ^ConstantFP::get(Type ^Ty, System::String ^Str)
{
msclr::interop::marshal_context ctx;
return Constant::_wrap(llvm::ConstantFP::get(Ty->base, ctx.marshal_as<const char *>(Str)));
}
ConstantFP ^ConstantFP::getNegativeZero(Type ^Ty)
{
return ConstantFP::_wrap(llvm::ConstantFP::getNegativeZero(Ty->base));
}
ConstantFP ^ConstantFP::getInfinity(Type ^Ty)
{
return ConstantFP::_wrap(llvm::ConstantFP::getInfinity(Ty->base));
}
ConstantFP ^ConstantFP::getInfinity(Type ^Ty, bool Negative)
{
return ConstantFP::_wrap(llvm::ConstantFP::getInfinity(Ty->base, Negative));
}
bool ConstantFP::isZero()
{
return base->isZero();
}
bool ConstantFP::isNegative()
{
return base->isNegative();
}
bool ConstantFP::isNaN()
{
return base->isNaN();
}
bool ConstantFP::isExactlyValue(double V)
{
return base->isExactlyValue(V);
}
bool ConstantFP::classof(Value ^V)
{
return llvm::ConstantFP::classof(V->base);
}
ConstantAggregateZero::ConstantAggregateZero(llvm::ConstantAggregateZero *base)
: base(base)
, Constant(base)
{
}
inline ConstantAggregateZero ^ConstantAggregateZero::_wrap(llvm::ConstantAggregateZero *base)
{
return base ? gcnew ConstantAggregateZero(base) : nullptr;
}
ConstantAggregateZero::!ConstantAggregateZero()
{
}
ConstantAggregateZero::~ConstantAggregateZero()
{
this->!ConstantAggregateZero();
}
ConstantAggregateZero ^ConstantAggregateZero::get(Type ^Ty)
{
return ConstantAggregateZero::_wrap(llvm::ConstantAggregateZero::get(Ty->base));
}
void ConstantAggregateZero::destroyConstant()
{
base->destroyConstant();
}
Constant ^ConstantAggregateZero::getSequentialElement()
{
return Constant::_wrap(base->getSequentialElement());
}
Constant ^ConstantAggregateZero::getStructElement(unsigned Elt)
{
return Constant::_wrap(base->getStructElement(Elt));
}
Constant ^ConstantAggregateZero::getElementValue(Constant ^C)
{
return Constant::_wrap(base->getElementValue(C->base));
}
Constant ^ConstantAggregateZero::getElementValue(unsigned Idx)
{
return Constant::_wrap(base->getElementValue(Idx));
}
bool ConstantAggregateZero::classof(Value ^V)
{
return llvm::ConstantAggregateZero::classof(V->base);
}
ConstantArray::ConstantArray(llvm::ConstantArray *base)
: base(base)
, Constant(base)
{
}
inline ConstantArray ^ConstantArray::_wrap(llvm::ConstantArray *base)
{
return base ? gcnew ConstantArray(base) : nullptr;
}
ConstantArray::!ConstantArray()
{
}
ConstantArray::~ConstantArray()
{
this->!ConstantArray();
}
Constant ^ConstantArray::get(ArrayType ^T, array<Constant ^> ^V)
{
llvm::Constant **b = new llvm::Constant*[V->Length];
for (int i = 0; i < V->Length; i++)
b[i] = V[i]->base;
llvm::ArrayRef<llvm::Constant*> brr(b, V->Length);
auto r = Constant::_wrap(llvm::ConstantArray::get(T->base, brr));
delete b;
return r;
}
inline ArrayType ^ConstantArray::getType()
{
return ArrayType::_wrap(base->getType());
}
void ConstantArray::destroyConstant()
{
base->destroyConstant();
}
void ConstantArray::replaceUsesOfWithOnConstant(Value ^From, Value ^To, Use ^U)
{
base->replaceUsesOfWithOnConstant(From->base, To->base, U->base);
}
bool ConstantArray::classof(Value ^V)
{
return llvm::ConstantArray::classof(V->base);
}
ConstantStruct::ConstantStruct(llvm::ConstantStruct *base)
: base(base)
, Constant(base)
{
}
inline ConstantStruct ^ConstantStruct::_wrap(llvm::ConstantStruct *base)
{
return base ? gcnew ConstantStruct(base) : nullptr;
}
ConstantStruct::!ConstantStruct()
{
}
ConstantStruct::~ConstantStruct()
{
this->!ConstantStruct();
}
Constant ^ConstantStruct::get(StructType ^T, array<Constant ^> ^V)
{
llvm::Constant **b = new llvm::Constant*[V->Length];
for (int i = 0; i < V->Length; i++)
b[i] = V[i]->base;
llvm::ArrayRef<llvm::Constant*> brr(b, V->Length);
auto r = Constant::_wrap(llvm::ConstantStruct::get(T->base, brr));
delete b;
return r;
}
Constant ^ConstantStruct::getAnon(array<Constant ^> ^V)
{
llvm::Constant **b = new llvm::Constant*[V->Length];
for (int i = 0; i < V->Length; i++)
b[i] = V[i]->base;
llvm::ArrayRef<llvm::Constant*> brr(b, V->Length);
auto r = Constant::_wrap(llvm::ConstantStruct::getAnon(brr));
delete b;
return r;
}
Constant ^ConstantStruct::getAnon(array<Constant ^> ^V, bool Packed)
{
llvm::Constant **b = new llvm::Constant*[V->Length];
for (int i = 0; i < V->Length; i++)
b[i] = V[i]->base;
llvm::ArrayRef<llvm::Constant*> brr(b, V->Length);
auto r = Constant::_wrap(llvm::ConstantStruct::getAnon(brr, Packed));
delete b;
return r;
}
Constant ^ConstantStruct::getAnon(LLVMContext ^Ctx, array<Constant ^> ^V)
{
llvm::Constant **b = new llvm::Constant*[V->Length];
for (int i = 0; i < V->Length; i++)
b[i] = V[i]->base;
llvm::ArrayRef<llvm::Constant*> brr(b, V->Length);
auto r = Constant::_wrap(llvm::ConstantStruct::getAnon(*Ctx->base, brr));
delete b;
return r;
}
Constant ^ConstantStruct::getAnon(LLVMContext ^Ctx, array<Constant ^> ^V, bool Packed)
{
llvm::Constant **b = new llvm::Constant*[V->Length];
for (int i = 0; i < V->Length; i++)
b[i] = V[i]->base;
llvm::ArrayRef<llvm::Constant*> brr(b, V->Length);
auto r = Constant::_wrap(llvm::ConstantStruct::getAnon(*Ctx->base, brr, Packed));
delete b;
return r;
}
StructType ^ConstantStruct::getTypeForElements(array<Constant ^> ^V)
{
llvm::Constant **b = new llvm::Constant*[V->Length];
for (int i = 0; i < V->Length; i++)
b[i] = V[i]->base;
llvm::ArrayRef<llvm::Constant*> brr(b, V->Length);
auto r = StructType::_wrap(llvm::ConstantStruct::getTypeForElements(brr));
delete b;
return r;
}
StructType ^ConstantStruct::getTypeForElements(array<Constant ^> ^V, bool Packed)
{
llvm::Constant **b = new llvm::Constant*[V->Length];
for (int i = 0; i < V->Length; i++)
b[i] = V[i]->base;
llvm::ArrayRef<llvm::Constant*> brr(b, V->Length);
auto r = StructType::_wrap(llvm::ConstantStruct::getTypeForElements(brr, Packed));
delete b;
return r;
}
StructType ^ConstantStruct::getTypeForElements(LLVMContext ^Ctx, array<Constant ^> ^V)
{
llvm::Constant **b = new llvm::Constant*[V->Length];
for (int i = 0; i < V->Length; i++)
b[i] = V[i]->base;
llvm::ArrayRef<llvm::Constant*> brr(b, V->Length);
auto r = StructType::_wrap(llvm::ConstantStruct::getTypeForElements(*Ctx->base, brr));
delete b;
return r;
}
StructType ^ConstantStruct::getTypeForElements(LLVMContext ^Ctx, array<Constant ^> ^V, bool Packed)
{
llvm::Constant **b = new llvm::Constant*[V->Length];
for (int i = 0; i < V->Length; i++)
b[i] = V[i]->base;
llvm::ArrayRef<llvm::Constant*> brr(b, V->Length);
auto r = StructType::_wrap(llvm::ConstantStruct::getTypeForElements(*Ctx->base, brr, Packed));
delete b;
return r;
}
inline StructType ^ConstantStruct::getType()
{
return StructType::_wrap(base->getType());
}
void ConstantStruct::destroyConstant()
{
base->destroyConstant();
}
void ConstantStruct::replaceUsesOfWithOnConstant(Value ^From, Value ^To, Use ^U)
{
base->replaceUsesOfWithOnConstant(From->base, To->base, U->base);
}
bool ConstantStruct::classof(Value ^V)
{
return llvm::ConstantStruct::classof(V->base);
}
ConstantVector::ConstantVector(llvm::ConstantVector *base)
: base(base)
, Constant(base)
{
}
inline ConstantVector ^ConstantVector::_wrap(llvm::ConstantVector *base)
{
return base ? gcnew ConstantVector(base) : nullptr;
}
ConstantVector::!ConstantVector()
{
}
ConstantVector::~ConstantVector()
{
this->!ConstantVector();
}
Constant ^ConstantVector::get(array<Constant ^> ^V)
{
llvm::Constant **b = new llvm::Constant*[V->Length];
for (int i = 0; i < V->Length; i++)
b[i] = V[i]->base;
llvm::ArrayRef<llvm::Constant*> brr(b, V->Length);
auto r = Constant::_wrap(llvm::ConstantVector::get(brr));
delete b;
return r;
}
Constant ^ConstantVector::getSplat(unsigned NumElts, Constant ^Elt)
{
return Constant::_wrap(llvm::ConstantVector::getSplat(NumElts, Elt->base));
}
inline VectorType ^ConstantVector::getType()
{
return VectorType::_wrap(base->getType());
}
Constant ^ConstantVector::getSplatValue()
{
return Constant::_wrap(base->getSplatValue());
}
void ConstantVector::destroyConstant()
{
base->destroyConstant();
}
void ConstantVector::replaceUsesOfWithOnConstant(Value ^From, Value ^To, Use ^U)
{
base->replaceUsesOfWithOnConstant(From->base, To->base, U->base);
}
bool ConstantVector::classof(Value ^V)
{
return llvm::ConstantVector::classof(V->base);
}
ConstantPointerNull::ConstantPointerNull(llvm::ConstantPointerNull *base)
: base(base)
, Constant(base)
{
}
inline ConstantPointerNull ^ConstantPointerNull::_wrap(llvm::ConstantPointerNull *base)
{
return base ? gcnew ConstantPointerNull(base) : nullptr;
}
ConstantPointerNull::!ConstantPointerNull()
{
}
ConstantPointerNull::~ConstantPointerNull()
{
this->!ConstantPointerNull();
}
ConstantPointerNull ^ConstantPointerNull::get(PointerType ^T)
{
return ConstantPointerNull::_wrap(llvm::ConstantPointerNull::get(T->base));
}
void ConstantPointerNull::destroyConstant()
{
base->destroyConstant();
}
inline PointerType ^ConstantPointerNull::getType()
{
return PointerType::_wrap(base->getType());
}
bool ConstantPointerNull::classof(Value ^V)
{
return llvm::ConstantPointerNull::classof(V->base);
}
ConstantDataSequential::ConstantDataSequential(llvm::ConstantDataSequential *base)
: base(base)
, Constant(base)
{
}
inline ConstantDataSequential ^ConstantDataSequential::_wrap(llvm::ConstantDataSequential *base)
{
return base ? gcnew ConstantDataSequential(base) : nullptr;
}
ConstantDataSequential::!ConstantDataSequential()
{
}
ConstantDataSequential::~ConstantDataSequential()
{
this->!ConstantDataSequential();
}
bool ConstantDataSequential::isElementTypeCompatible(Type ^Ty)
{
return llvm::ConstantDataSequential::isElementTypeCompatible(Ty->base);
}
uint64_t ConstantDataSequential::getElementAsInteger(unsigned i)
{
return base->getElementAsInteger(i);
}
float ConstantDataSequential::getElementAsFloat(unsigned i)
{
return base->getElementAsFloat(i);
}
double ConstantDataSequential::getElementAsDouble(unsigned i)
{
return base->getElementAsDouble(i);
}
Constant ^ConstantDataSequential::getElementAsConstant(unsigned i)
{
return Constant::_wrap(base->getElementAsConstant(i));
}
inline SequentialType ^ConstantDataSequential::getType()
{
return SequentialType::_wrap(base->getType());
}
Type ^ConstantDataSequential::getElementType()
{
return Type::_wrap(base->getElementType());
}
unsigned ConstantDataSequential::getNumElements()
{
return base->getNumElements();
}
uint64_t ConstantDataSequential::getElementByteSize()
{
return base->getElementByteSize();
}
bool ConstantDataSequential::isString()
{
return base->isString();
}
bool ConstantDataSequential::isCString()
{
return base->isCString();
}
System::String ^ConstantDataSequential::getAsString()
{
return utils::manage_str(base->getAsString());
}
System::String ^ConstantDataSequential::getAsCString()
{
return utils::manage_str(base->getAsCString());
}
System::String ^ConstantDataSequential::getRawDataValues()
{
return utils::manage_str(base->getRawDataValues());
}
void ConstantDataSequential::destroyConstant()
{
base->destroyConstant();
}
bool ConstantDataSequential::classof(Value ^V)
{
return llvm::ConstantDataSequential::classof(V->base);
}
ConstantDataArray::ConstantDataArray(llvm::ConstantDataArray *base)
: base(base)
, ConstantDataSequential(base)
{
}
inline ConstantDataArray ^ConstantDataArray::_wrap(llvm::ConstantDataArray *base)
{
return base ? gcnew ConstantDataArray(base) : nullptr;
}
ConstantDataArray::!ConstantDataArray()
{
}
ConstantDataArray::~ConstantDataArray()
{
this->!ConstantDataArray();
}
Constant ^ConstantDataArray::get(LLVMContext ^Context, array<uint8_t> ^Elts)
{
auto r = Constant::_wrap(llvm::ConstantDataArray::get(*Context->base, utils::unmanage_array(Elts)));
return r;
}
Constant ^ConstantDataArray::get(LLVMContext ^Context, array<uint16_t> ^Elts)
{
auto r = Constant::_wrap(llvm::ConstantDataArray::get(*Context->base, utils::unmanage_array(Elts)));
return r;
}
Constant ^ConstantDataArray::get(LLVMContext ^Context, array<uint32_t> ^Elts)
{
auto r = Constant::_wrap(llvm::ConstantDataArray::get(*Context->base, utils::unmanage_array(Elts)));
return r;
}
Constant ^ConstantDataArray::get(LLVMContext ^Context, array<uint64_t> ^Elts)
{
auto r = Constant::_wrap(llvm::ConstantDataArray::get(*Context->base, utils::unmanage_array(Elts)));
return r;
}
Constant ^ConstantDataArray::get(LLVMContext ^Context, array<float> ^Elts)
{
auto r = Constant::_wrap(llvm::ConstantDataArray::get(*Context->base, utils::unmanage_array(Elts)));
return r;
}
Constant ^ConstantDataArray::get(LLVMContext ^Context, array<double> ^Elts)
{
auto r = Constant::_wrap(llvm::ConstantDataArray::get(*Context->base, utils::unmanage_array(Elts)));
return r;
}
Constant ^ConstantDataArray::getString(LLVMContext ^Context, System::String ^Initializer)
{
msclr::interop::marshal_context ctx;
return Constant::_wrap(llvm::ConstantDataArray::getString(*Context->base, ctx.marshal_as<const char *>(Initializer)));
}
Constant ^ConstantDataArray::getString(LLVMContext ^Context, System::String ^Initializer, bool AddNull)
{
msclr::interop::marshal_context ctx;
return Constant::_wrap(llvm::ConstantDataArray::getString(*Context->base, ctx.marshal_as<const char *>(Initializer), AddNull));
}
inline ArrayType ^ConstantDataArray::getType()
{
return ArrayType::_wrap(base->getType());
}
bool ConstantDataArray::classof(Value ^V)
{
return llvm::ConstantDataArray::classof(V->base);
}
ConstantDataVector::ConstantDataVector(llvm::ConstantDataVector *base)
: base(base)
, ConstantDataSequential(base)
{
}
inline ConstantDataVector ^ConstantDataVector::_wrap(llvm::ConstantDataVector *base)
{
return base ? gcnew ConstantDataVector(base) : nullptr;
}
ConstantDataVector::!ConstantDataVector()
{
}
ConstantDataVector::~ConstantDataVector()
{
this->!ConstantDataVector();
}
Constant ^ConstantDataVector::get(LLVMContext ^Context, array<uint8_t> ^Elts)
{
auto r = Constant::_wrap(llvm::ConstantDataVector::get(*Context->base, utils::unmanage_array(Elts)));
return r;
}
Constant ^ConstantDataVector::get(LLVMContext ^Context, array<uint16_t> ^Elts)
{
auto r = Constant::_wrap(llvm::ConstantDataVector::get(*Context->base, utils::unmanage_array(Elts)));
return r;
}
Constant ^ConstantDataVector::get(LLVMContext ^Context, array<uint32_t> ^Elts)
{
auto r = Constant::_wrap(llvm::ConstantDataVector::get(*Context->base, utils::unmanage_array(Elts)));
return r;
}
Constant ^ConstantDataVector::get(LLVMContext ^Context, array<uint64_t> ^Elts)
{
auto r = Constant::_wrap(llvm::ConstantDataVector::get(*Context->base, utils::unmanage_array(Elts)));
return r;
}
Constant ^ConstantDataVector::get(LLVMContext ^Context, array<float> ^Elts)
{
auto r = Constant::_wrap(llvm::ConstantDataVector::get(*Context->base, utils::unmanage_array(Elts)));
return r;
}
Constant ^ConstantDataVector::get(LLVMContext ^Context, array<double> ^Elts)
{
auto r = Constant::_wrap(llvm::ConstantDataVector::get(*Context->base, utils::unmanage_array(Elts)));
return r;
}
Constant ^ConstantDataVector::getSplat(unsigned NumElts, Constant ^Elt)
{
return Constant::_wrap(llvm::ConstantDataVector::getSplat(NumElts, Elt->base));
}
Constant ^ConstantDataVector::getSplatValue()
{
return Constant::_wrap(base->getSplatValue());
}
inline VectorType ^ConstantDataVector::getType()
{
return VectorType::_wrap(base->getType());
}
bool ConstantDataVector::classof(Value ^V)
{
return llvm::ConstantDataVector::classof(V->base);
}
BlockAddress::BlockAddress(llvm::BlockAddress *base)
: base(base)
, Constant(base)
{
}
inline BlockAddress ^BlockAddress::_wrap(llvm::BlockAddress *base)
{
return base ? gcnew BlockAddress(base) : nullptr;
}
BlockAddress::!BlockAddress()
{
}
BlockAddress::~BlockAddress()
{
this->!BlockAddress();
}
BlockAddress ^BlockAddress::get(Function ^F, BasicBlock ^BB)
{
return BlockAddress::_wrap(llvm::BlockAddress::get(F->base, BB->base));
}
BlockAddress ^BlockAddress::get(BasicBlock ^BB)
{
return BlockAddress::_wrap(llvm::BlockAddress::get(BB->base));
}
Function ^BlockAddress::getFunction()
{
return Function::_wrap(base->getFunction());
}
BasicBlock ^BlockAddress::getBasicBlock()
{
return BasicBlock::_wrap(base->getBasicBlock());
}
void BlockAddress::destroyConstant()
{
base->destroyConstant();
}
void BlockAddress::replaceUsesOfWithOnConstant(Value ^From, Value ^To, Use ^U)
{
base->replaceUsesOfWithOnConstant(From->base, To->base, U->base);
}
inline bool BlockAddress::classof(Value ^V)
{
return llvm::BlockAddress::classof(V->base);
}
ConstantExpr::ConstantExpr(llvm::ConstantExpr *base)
: base(base)
, Constant(base)
{
}
inline ConstantExpr ^ConstantExpr::_wrap(llvm::ConstantExpr *base)
{
return base ? gcnew ConstantExpr(base) : nullptr;
}
ConstantExpr::!ConstantExpr()
{
}
ConstantExpr::~ConstantExpr()
{
this->!ConstantExpr();
}
Constant ^ConstantExpr::getAlignOf(Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getAlignOf(Ty->base));
}
Constant ^ConstantExpr::getSizeOf(Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getSizeOf(Ty->base));
}
Constant ^ConstantExpr::getOffsetOf(StructType ^STy, unsigned FieldNo)
{
return Constant::_wrap(llvm::ConstantExpr::getOffsetOf(STy->base, FieldNo));
}
Constant ^ConstantExpr::getOffsetOf(Type ^Ty, Constant ^FieldNo)
{
return Constant::_wrap(llvm::ConstantExpr::getOffsetOf(Ty->base, FieldNo->base));
}
Constant ^ConstantExpr::getNeg(Constant ^C)
{
return Constant::_wrap(llvm::ConstantExpr::getNeg(C->base));
}
Constant ^ConstantExpr::getNeg(Constant ^C, bool HasNUW)
{
return Constant::_wrap(llvm::ConstantExpr::getNeg(C->base, HasNUW));
}
Constant ^ConstantExpr::getNeg(Constant ^C, bool HasNUW, bool HasNSW)
{
return Constant::_wrap(llvm::ConstantExpr::getNeg(C->base, HasNUW, HasNSW));
}
Constant ^ConstantExpr::getFNeg(Constant ^C)
{
return Constant::_wrap(llvm::ConstantExpr::getFNeg(C->base));
}
Constant ^ConstantExpr::getNot(Constant ^C)
{
return Constant::_wrap(llvm::ConstantExpr::getNot(C->base));
}
Constant ^ConstantExpr::getAdd(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getAdd(C1->base, C2->base));
}
Constant ^ConstantExpr::getAdd(Constant ^C1, Constant ^C2, bool HasNUW)
{
return Constant::_wrap(llvm::ConstantExpr::getAdd(C1->base, C2->base, HasNUW));
}
Constant ^ConstantExpr::getAdd(Constant ^C1, Constant ^C2, bool HasNUW, bool HasNSW)
{
return Constant::_wrap(llvm::ConstantExpr::getAdd(C1->base, C2->base, HasNUW, HasNSW));
}
Constant ^ConstantExpr::getFAdd(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getFAdd(C1->base, C2->base));
}
Constant ^ConstantExpr::getSub(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getSub(C1->base, C2->base));
}
Constant ^ConstantExpr::getSub(Constant ^C1, Constant ^C2, bool HasNUW)
{
return Constant::_wrap(llvm::ConstantExpr::getSub(C1->base, C2->base, HasNUW));
}
Constant ^ConstantExpr::getSub(Constant ^C1, Constant ^C2, bool HasNUW, bool HasNSW)
{
return Constant::_wrap(llvm::ConstantExpr::getSub(C1->base, C2->base, HasNUW, HasNSW));
}
Constant ^ConstantExpr::getFSub(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getFSub(C1->base, C2->base));
}
Constant ^ConstantExpr::getMul(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getMul(C1->base, C2->base));
}
Constant ^ConstantExpr::getMul(Constant ^C1, Constant ^C2, bool HasNUW)
{
return Constant::_wrap(llvm::ConstantExpr::getMul(C1->base, C2->base, HasNUW));
}
Constant ^ConstantExpr::getMul(Constant ^C1, Constant ^C2, bool HasNUW, bool HasNSW)
{
return Constant::_wrap(llvm::ConstantExpr::getMul(C1->base, C2->base, HasNUW, HasNSW));
}
Constant ^ConstantExpr::getFMul(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getFMul(C1->base, C2->base));
}
Constant ^ConstantExpr::getUDiv(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getUDiv(C1->base, C2->base));
}
Constant ^ConstantExpr::getUDiv(Constant ^C1, Constant ^C2, bool isExact)
{
return Constant::_wrap(llvm::ConstantExpr::getUDiv(C1->base, C2->base, isExact));
}
Constant ^ConstantExpr::getSDiv(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getSDiv(C1->base, C2->base));
}
Constant ^ConstantExpr::getSDiv(Constant ^C1, Constant ^C2, bool isExact)
{
return Constant::_wrap(llvm::ConstantExpr::getSDiv(C1->base, C2->base, isExact));
}
Constant ^ConstantExpr::getFDiv(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getFDiv(C1->base, C2->base));
}
Constant ^ConstantExpr::getURem(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getURem(C1->base, C2->base));
}
Constant ^ConstantExpr::getSRem(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getSRem(C1->base, C2->base));
}
Constant ^ConstantExpr::getFRem(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getFRem(C1->base, C2->base));
}
Constant ^ConstantExpr::getAnd(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getAnd(C1->base, C2->base));
}
Constant ^ConstantExpr::getOr(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getOr(C1->base, C2->base));
}
Constant ^ConstantExpr::getXor(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getXor(C1->base, C2->base));
}
Constant ^ConstantExpr::getShl(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getShl(C1->base, C2->base));
}
Constant ^ConstantExpr::getShl(Constant ^C1, Constant ^C2, bool HasNUW)
{
return Constant::_wrap(llvm::ConstantExpr::getShl(C1->base, C2->base, HasNUW));
}
Constant ^ConstantExpr::getShl(Constant ^C1, Constant ^C2, bool HasNUW, bool HasNSW)
{
return Constant::_wrap(llvm::ConstantExpr::getShl(C1->base, C2->base, HasNUW, HasNSW));
}
Constant ^ConstantExpr::getLShr(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getLShr(C1->base, C2->base));
}
Constant ^ConstantExpr::getLShr(Constant ^C1, Constant ^C2, bool isExact)
{
return Constant::_wrap(llvm::ConstantExpr::getLShr(C1->base, C2->base, isExact));
}
Constant ^ConstantExpr::getAShr(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getAShr(C1->base, C2->base));
}
Constant ^ConstantExpr::getAShr(Constant ^C1, Constant ^C2, bool isExact)
{
return Constant::_wrap(llvm::ConstantExpr::getAShr(C1->base, C2->base, isExact));
}
Constant ^ConstantExpr::getTrunc(Constant ^C, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getTrunc(C->base, Ty->base));
}
Constant ^ConstantExpr::getSExt(Constant ^C, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getSExt(C->base, Ty->base));
}
Constant ^ConstantExpr::getZExt(Constant ^C, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getZExt(C->base, Ty->base));
}
Constant ^ConstantExpr::getFPTrunc(Constant ^C, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getFPTrunc(C->base, Ty->base));
}
Constant ^ConstantExpr::getFPExtend(Constant ^C, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getFPExtend(C->base, Ty->base));
}
Constant ^ConstantExpr::getUIToFP(Constant ^C, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getUIToFP(C->base, Ty->base));
}
Constant ^ConstantExpr::getSIToFP(Constant ^C, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getSIToFP(C->base, Ty->base));
}
Constant ^ConstantExpr::getFPToUI(Constant ^C, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getFPToUI(C->base, Ty->base));
}
Constant ^ConstantExpr::getFPToSI(Constant ^C, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getFPToSI(C->base, Ty->base));
}
Constant ^ConstantExpr::getPtrToInt(Constant ^C, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getPtrToInt(C->base, Ty->base));
}
Constant ^ConstantExpr::getIntToPtr(Constant ^C, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getIntToPtr(C->base, Ty->base));
}
Constant ^ConstantExpr::getBitCast(Constant ^C, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getBitCast(C->base, Ty->base));
}
Constant ^ConstantExpr::getNSWNeg(Constant ^C)
{
return Constant::_wrap(llvm::ConstantExpr::getNSWNeg(C->base));
}
Constant ^ConstantExpr::getNUWNeg(Constant ^C)
{
return Constant::_wrap(llvm::ConstantExpr::getNUWNeg(C->base));
}
Constant ^ConstantExpr::getNSWAdd(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getNSWAdd(C1->base, C2->base));
}
Constant ^ConstantExpr::getNUWAdd(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getNUWAdd(C1->base, C2->base));
}
Constant ^ConstantExpr::getNSWSub(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getNSWSub(C1->base, C2->base));
}
Constant ^ConstantExpr::getNUWSub(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getNUWSub(C1->base, C2->base));
}
Constant ^ConstantExpr::getNSWMul(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getNSWMul(C1->base, C2->base));
}
Constant ^ConstantExpr::getNUWMul(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getNUWMul(C1->base, C2->base));
}
Constant ^ConstantExpr::getNSWShl(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getNSWShl(C1->base, C2->base));
}
Constant ^ConstantExpr::getNUWShl(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getNUWShl(C1->base, C2->base));
}
Constant ^ConstantExpr::getExactSDiv(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getExactSDiv(C1->base, C2->base));
}
Constant ^ConstantExpr::getExactUDiv(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getExactUDiv(C1->base, C2->base));
}
Constant ^ConstantExpr::getExactAShr(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getExactAShr(C1->base, C2->base));
}
Constant ^ConstantExpr::getExactLShr(Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::getExactLShr(C1->base, C2->base));
}
Constant ^ConstantExpr::getBinOpIdentity(unsigned Opcode, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getBinOpIdentity(Opcode, Ty->base));
}
Constant ^ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getBinOpAbsorber(Opcode, Ty->base));
}
Constant ^ConstantExpr::getCast(unsigned ops, Constant ^C, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getCast(ops, C->base, Ty->base));
}
Constant ^ConstantExpr::getZExtOrBitCast(Constant ^C, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getZExtOrBitCast(C->base, Ty->base));
}
Constant ^ConstantExpr::getSExtOrBitCast(Constant ^C, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getSExtOrBitCast(C->base, Ty->base));
}
Constant ^ConstantExpr::getTruncOrBitCast(Constant ^C, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getTruncOrBitCast(C->base, Ty->base));
}
Constant ^ConstantExpr::getPointerCast(Constant ^C, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getPointerCast(C->base, Ty->base));
}
Constant ^ConstantExpr::getIntegerCast(Constant ^C, Type ^Ty, bool isSigned)
{
return Constant::_wrap(llvm::ConstantExpr::getIntegerCast(C->base, Ty->base, isSigned));
}
Constant ^ConstantExpr::getFPCast(Constant ^C, Type ^Ty)
{
return Constant::_wrap(llvm::ConstantExpr::getFPCast(C->base, Ty->base));
}
bool ConstantExpr::isCast()
{
return base->isCast();
}
bool ConstantExpr::isCompare()
{
return base->isCompare();
}
bool ConstantExpr::hasIndices()
{
return base->hasIndices();
}
bool ConstantExpr::isGEPWithNoNotionalOverIndexing()
{
return base->isGEPWithNoNotionalOverIndexing();
}
Constant ^ConstantExpr::getSelect(Constant ^C, Constant ^V1, Constant ^V2)
{
return Constant::_wrap(llvm::ConstantExpr::getSelect(C->base, V1->base, V2->base));
}
Constant ^ConstantExpr::get(unsigned Opcode, Constant ^C1, Constant ^C2)
{
return Constant::_wrap(llvm::ConstantExpr::get(Opcode, C1->base, C2->base));
}
Constant ^ConstantExpr::get(unsigned Opcode, Constant ^C1, Constant ^C2, unsigned Flags)
{
return Constant::_wrap(llvm::ConstantExpr::get(Opcode, C1->base, C2->base, Flags));
}
Constant ^ConstantExpr::getGetElementPtr(Constant ^C, array<Constant ^> ^IdxList)
{
llvm::Constant **b = new llvm::Constant*[IdxList->Length];
for (int i = 0; i < IdxList->Length; i++)
b[i] = IdxList[i]->base;
llvm::ArrayRef<llvm::Constant*> brr(b, IdxList->Length);
auto r = Constant::_wrap(llvm::ConstantExpr::getGetElementPtr(C->base, brr));
delete b;
return r;
}
Constant ^ConstantExpr::getGetElementPtr(Constant ^C, array<Constant ^> ^IdxList, bool InBounds)
{
llvm::Constant **b = new llvm::Constant*[IdxList->Length];
for (int i = 0; i < IdxList->Length; i++)
b[i] = IdxList[i]->base;
llvm::ArrayRef<llvm::Constant*> brr(b, IdxList->Length);
auto r = Constant::_wrap(llvm::ConstantExpr::getGetElementPtr(C->base, brr, InBounds));
delete b;
return r;
}
Constant ^ConstantExpr::getGetElementPtr(Constant ^C, Constant ^Idx)
{
return Constant::_wrap(llvm::ConstantExpr::getGetElementPtr(C->base, Idx->base));
}
Constant ^ConstantExpr::getGetElementPtr(Constant ^C, Constant ^Idx, bool InBounds)
{
return Constant::_wrap(llvm::ConstantExpr::getGetElementPtr(C->base, Idx->base, InBounds));
}
Constant ^ConstantExpr::getGetElementPtr(Constant ^C, array<Value ^> ^IdxList)
{
llvm::Value **b = new llvm::Value*[IdxList->Length];
for (int i = 0; i < IdxList->Length; i++)
b[i] = IdxList[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, IdxList->Length);
auto r = Constant::_wrap(llvm::ConstantExpr::getGetElementPtr(C->base, brr));
delete b;
return r;
}
Constant ^ConstantExpr::getGetElementPtr(Constant ^C, array<Value ^> ^IdxList, bool InBounds)
{
llvm::Value **b = new llvm::Value*[IdxList->Length];
for (int i = 0; i < IdxList->Length; i++)
b[i] = IdxList[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, IdxList->Length);
auto r = Constant::_wrap(llvm::ConstantExpr::getGetElementPtr(C->base, brr, InBounds));
delete b;
return r;
}
Constant ^ConstantExpr::getInBoundsGetElementPtr(Constant ^C, array<Constant ^> ^IdxList)
{
llvm::Constant **b = new llvm::Constant*[IdxList->Length];
for (int i = 0; i < IdxList->Length; i++)
b[i] = IdxList[i]->base;
llvm::ArrayRef<llvm::Constant*> brr(b, IdxList->Length);
auto r = Constant::_wrap(llvm::ConstantExpr::getInBoundsGetElementPtr(C->base, brr));
delete b;
return r;
}
Constant ^ConstantExpr::getInBoundsGetElementPtr(Constant ^C, Constant ^Idx)
{
return Constant::_wrap(llvm::ConstantExpr::getInBoundsGetElementPtr(C->base, Idx->base));
}
Constant ^ConstantExpr::getInBoundsGetElementPtr(Constant ^C, array<Value ^> ^IdxList)
{
llvm::Value **b = new llvm::Value*[IdxList->Length];
for (int i = 0; i < IdxList->Length; i++)
b[i] = IdxList[i]->base;
llvm::ArrayRef<llvm::Value*> brr(b, IdxList->Length);
auto r = Constant::_wrap(llvm::ConstantExpr::getInBoundsGetElementPtr(C->base, brr));
delete b;
return r;
}
Constant ^ConstantExpr::getExtractElement(Constant ^Vec, Constant ^Idx)
{
return Constant::_wrap(llvm::ConstantExpr::getExtractElement(Vec->base, Idx->base));
}
Constant ^ConstantExpr::getInsertElement(Constant ^Vec, Constant ^Elt, Constant ^Idx)
{
return Constant::_wrap(llvm::ConstantExpr::getInsertElement(Vec->base, Elt->base, Idx->base));
}
Constant ^ConstantExpr::getShuffleVector(Constant ^V1, Constant ^V2, Constant ^Mask)
{
return Constant::_wrap(llvm::ConstantExpr::getShuffleVector(V1->base, V2->base, Mask->base));
}
Constant ^ConstantExpr::getExtractValue(Constant ^Agg, array<unsigned> ^Idxs)
{
auto r = Constant::_wrap(llvm::ConstantExpr::getExtractValue(Agg->base, utils::unmanage_array(Idxs)));
return r;
}
Constant ^ConstantExpr::getInsertValue(Constant ^Agg, Constant ^Val, array<unsigned> ^Idxs)
{
auto r = Constant::_wrap(llvm::ConstantExpr::getInsertValue(Agg->base, Val->base, utils::unmanage_array(Idxs)));
return r;
}
unsigned ConstantExpr::getOpcode()
{
return base->getOpcode();
}
unsigned ConstantExpr::getPredicate()
{
return base->getPredicate();
}
array<unsigned> ^ConstantExpr::getIndices()
{
auto r = base->getIndices();
array<unsigned> ^s = gcnew array<unsigned>(r.size());
for (int i = 0; i < s->Length; i++)
s[i] = r[i];
return s;
}
System::String ^ConstantExpr::getOpcodeName()
{
return utils::manage_str(base->getOpcodeName());
}
Constant ^ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant ^Op)
{
return Constant::_wrap(base->getWithOperandReplaced(OpNo, Op->base));
}
Constant ^ConstantExpr::getWithOperands(array<Constant ^> ^Ops)
{
llvm::Constant **b = new llvm::Constant*[Ops->Length];
for (int i = 0; i < Ops->Length; i++)
b[i] = Ops[i]->base;
llvm::ArrayRef<llvm::Constant*> brr(b, Ops->Length);
auto r = Constant::_wrap(base->getWithOperands(brr));
delete b;
return r;
}
Constant ^ConstantExpr::getWithOperands(array<Constant ^> ^Ops, Type ^Ty)
{
llvm::Constant **b = new llvm::Constant*[Ops->Length];
for (int i = 0; i < Ops->Length; i++)
b[i] = Ops[i]->base;
llvm::ArrayRef<llvm::Constant*> brr(b, Ops->Length);
auto r = Constant::_wrap(base->getWithOperands(brr, Ty->base));
delete b;
return r;
}
Instruction ^ConstantExpr::getAsInstruction()
{
return Instruction::_wrap(base->getAsInstruction());
}
void ConstantExpr::destroyConstant()
{
base->destroyConstant();
}
void ConstantExpr::replaceUsesOfWithOnConstant(Value ^From, Value ^To, Use ^U)
{
base->replaceUsesOfWithOnConstant(From->base, To->base, U->base);
}
inline bool ConstantExpr::classof(Value ^V)
{
return llvm::ConstantExpr::classof(V->base);
}
UndefValue::UndefValue(llvm::UndefValue *base)
: base(base)
, Constant(base)
{
}
inline UndefValue ^UndefValue::_wrap(llvm::UndefValue *base)
{
return base ? gcnew UndefValue(base) : nullptr;
}
UndefValue::!UndefValue()
{
}
UndefValue::~UndefValue()
{
this->!UndefValue();
}
UndefValue ^UndefValue::get(Type ^T)
{
return UndefValue::_wrap(llvm::UndefValue::get(T->base));
}
UndefValue ^UndefValue::getSequentialElement()
{
return UndefValue::_wrap(base->getSequentialElement());
}
UndefValue ^UndefValue::getStructElement(unsigned Elt)
{
return UndefValue::_wrap(base->getStructElement(Elt));
}
UndefValue ^UndefValue::getElementValue(Constant ^C)
{
return UndefValue::_wrap(base->getElementValue(C->base));
}
UndefValue ^UndefValue::getElementValue(unsigned Idx)
{
return UndefValue::_wrap(base->getElementValue(Idx));
}
void UndefValue::destroyConstant()
{
base->destroyConstant();
}
bool UndefValue::classof(Value ^V)
{
return llvm::UndefValue::classof(V->base);
}
|
// From _Learning OpenCV, 2e_
#include <iostream>
#include <cstdlib>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main(int argc, char *argv[] )
{
if( argc < 2 ) {
return EXIT_FAILURE;
}
Mat img = imread(argv[1],-1);
if( img.empty() ) {
return EXIT_FAILURE;
}
namedWindow("Example1", WINDOW_AUTOSIZE );
imshow("Example1",img);
waitKey(0);
destroyWindow("Example1");
}
|
#include <iostream>
#include "MyClass.h"
using namespace std;
int main()
{
cout << "Hello World!" << endl;
MyClass * first = new MyClass();
cout<< first->KolStr() <<endl;
first->PrintStr();
first->debug();
return 0;
}
|
//
// Created by ryan on 7/29/17.
//
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "s3loader.cpp"
class MockVTAllocator : public VTAllocator {
public:
MockVTAllocator() {
}
//MOCK_METHOD1(alloc, void*(size_t size));
void *alloc(size_t size) {
return std::malloc(size);
}
};
class MockUDFileOperator : Vertica::UDFileOperator {
MOCK_METHOD2(read, size_t(void *buf, size_t count));
MOCK_METHOD2(append, size_t(const void *buf, size_t count));
MOCK_METHOD2(appendWithRetry, void(const void *buffer, size_t size));
MOCK_METHOD2(seek, off_t(off_t offset, int whence));
MOCK_CONST_METHOD0(getOffset, off_t());
MOCK_METHOD5(mmap, void*(void *addr, size_t length, int prot, int flags, off_t offset));
MOCK_METHOD2(munmap, void(void *addr, size_t length));
MOCK_METHOD0(fsync, void());
MOCK_METHOD0(doHurryUp, void());
MOCK_METHOD0(eof, bool());
};
class MockUDFileSystem : Vertica::UDFileSystem {
MOCK_CONST_METHOD0(open, UDFileOperator*());
MOCK_CONST_METHOD4(open, UDFileOperator*(const char *path, int flags, mode_t mode, bool removeOnClose));
MOCK_CONST_METHOD1(close, void(UDFileOperator *udfo));
MOCK_CONST_METHOD2(copy, void(const char *srcpath, const char *dstpath));
MOCK_CONST_METHOD2(statvfs, void(const char *path, struct ::statvfs *buf));
MOCK_CONST_METHOD2(stat, void(const char *path, struct ::stat *buf));
MOCK_CONST_METHOD2(mkdirs, void(const char *path, mode_t mode));
MOCK_CONST_METHOD1(rmdir, void(const char *path));
MOCK_CONST_METHOD1(rmdirRecursive, void(const char *path));
MOCK_CONST_METHOD2(listFiles, void(const char *path, std::vector<std::string> &result));
MOCK_CONST_METHOD2(rename, void(const char *oldpath, const char *newpath));
MOCK_CONST_METHOD1(remove, void(const char *path));
MOCK_METHOD2(link, void(const char *oldpath, const char *newpath));
MOCK_METHOD2(symlink, void(const char *oldpath, const char *newpath));
MOCK_METHOD0(supportsDirectorySnapshots, bool());
MOCK_METHOD2(snapshotDirectory, bool(const std::string &path, std::string &snapshot_handle));
MOCK_METHOD2(restoreSnapshot, bool(const std::string &snapshot_handle, const std::string &path));
MOCK_METHOD1(deleteSnapshot, bool(const std::string &snapshot_handle));
};
class MockServerImpl : public ServerInterface {
public:
MockServerImpl(VTAllocator *allocator, LoggingFunc func, const std::string &sqlName, vint udxDebugLogLevel = 0)
: ServerInterface(allocator, func, sqlName, udxDebugLogLevel) {
}
MockServerImpl(VTAllocator *allocator, LoggingFunc func, const std::string &sqlName, const ParamReader& paramReader, vint udxDebugLogLevel = 0)
: ServerInterface(allocator, func, sqlName, paramReader, udxDebugLogLevel) {
}
MockServerImpl(VTAllocator *allocator, LoggingFunc func, const std::string &sqlName, const ParamReader& paramReader, ParamReader& sessionParamReader, vint udxDebugLogLevel = 0)
: ServerInterface(allocator, func, sqlName, paramReader, udxDebugLogLevel) {
this->udSessionParamReaderMap.addUDSessionParamReader("library", sessionParamReader);
}
//MOCK_METHOD0(getParamReader, ParamReader());
MOCK_METHOD1(getFileSystem, UDFileSystem*(const char *path));
MOCK_CONST_METHOD1(getFileSystem, UDFileSystem*(const char *pat));
MOCK_METHOD2(describeFunction, bool(FunctionDescription &func, bool errorIfNotFound));
MOCK_METHOD3(listTables, void(const RelationDescription &lookup, std::vector<Oid> &tables, bool errorIfNotFound));
MOCK_METHOD3(listProjections, void(const RelationDescription &lookup, std::vector<Oid> &projections, bool errorIfNotFound));
MOCK_METHOD3(listTableProjections, void(const RelationDescription &baseTable, std::vector<Oid> &projections, bool errorIfNotFound));
MOCK_METHOD3(listDerivedTables, void(const RelationDescription &baseTable, std::vector<Oid> &tables, bool errorIfNotFound));
MOCK_METHOD2(describeTable, bool(RelationDescription &baseTable, bool errorIfNotFound));
MOCK_METHOD2(describeProjection, bool(RelationDescription &proj, bool errorIfNotFound));
MOCK_METHOD2(describeType, bool(TypeDescription &type, bool errorIfNotFound));
MOCK_METHOD3(describeBlob, bool(const BlobIdentifier &blobId, BlobDescription &blobDescription, bool errorIfNotFound));
MOCK_METHOD1(listBlobs, std::vector<BlobDescription>(BlobIdentifier::Namespace nsp));
};
class MockParamReader: public ParamReader {
public:
MockParamReader(std::map<std::string, size_t> paramNameToIndex, std::vector<char *> cols, std::vector<VString> svWrappers) {
this->cols = cols;
this->paramNameToIndex = paramNameToIndex;
this->svWrappers = svWrappers;
}
//MOCK_METHOD0(getParamNames, std::vector<std::string>());
};
class MockParamWriter: public ParamWriter {
public:
MockParamWriter(VTAllocator *allocator = NULL) : ParamWriter(allocator) {}
};
class MockNodeSpecifyingPlanContext: public NodeSpecifyingPlanContext {
public:
MockNodeSpecifyingPlanContext(ParamWriter& writer, std::vector<std::string> clusterNodes, bool canApportion)
: NodeSpecifyingPlanContext(writer, clusterNodes, canApportion) {}
//MOCK_CONST_METHOD0(canApportionSource, bool());
//MOCK_CONST_METHOD0(getTargetNodes, std::vector<std::string>&());
//MOCK_METHOD1(setTargetNodes, void(const std::vector<std::string>& nodes));
};
TEST(library, construct) {
S3Source s3Source("s3://datahub/path/to/s3");
ASSERT_EQ(std::string(s3Source.getBucket().c_str()), std::string("datahub"));
ASSERT_EQ(std::string(s3Source.getKey().c_str()), "path/to/s3");
}
TEST(library, download) {
//id
char id[] = "";
char secret[] = "";
char endpoint[] = "";
char tempfile[] = "";
std::string s3uri = "";
EE::StringValue *sId = (EE::StringValue *)malloc(sizeof(EE::StringValue) + sizeof(id) * sizeof(char) + 1);
sId->slen = sizeof(id) - 1;
sId->sloc = 0;
std::memcpy(&sId->base, &id[0], sizeof(id));
//secret
EE::StringValue *sSecret = (EE::StringValue *)malloc(sizeof(EE::StringValue) + sizeof(secret) * sizeof(char) + 1);
sSecret->slen = sizeof(secret) - 1;
sSecret->sloc = 0;
std::memcpy(&sSecret->base, &secret[0], sizeof(secret));
//verbose
vbool bVerbose = true;
//endpoint
EE::StringValue *sEndpoint = (EE::StringValue *)malloc(sizeof(EE::StringValue) + sizeof(endpoint) * sizeof(char) + 1);
sEndpoint->slen = sizeof(endpoint) - 1;
sEndpoint->sloc = 0;
std::memcpy(&sEndpoint->base, &endpoint[0], sizeof(endpoint));
std::map<std::string, size_t> paramNameToIndex;
paramNameToIndex["aws_id"] = 0;
paramNameToIndex["aws_secret"] = 1;
paramNameToIndex["aws_verbose"] = 2;
paramNameToIndex["aws_endpoint"] = 3;
std::vector<VString> svWrappers;
svWrappers.push_back(VString(NULL, NULL, StringNull));
svWrappers.push_back(VString(NULL, NULL, StringNull));
svWrappers.push_back(VString(NULL, NULL, StringNull));
svWrappers.push_back(VString(NULL, NULL, StringNull));
std::vector<char *> cols;
cols.push_back(reinterpret_cast<char*>(sId));
cols.push_back(reinterpret_cast<char*>(sSecret));
cols.push_back(reinterpret_cast<char*>(&bVerbose));
cols.push_back(reinterpret_cast<char*>(sEndpoint));
MockParamReader mockParamReader(paramNameToIndex,cols,svWrappers);
MockVTAllocator mockVTAllocator;
ServerInterface::LoggingFunc func;
MockServerImpl mockServer(&mockVTAllocator, func, std::string("string"), mockParamReader, mockParamReader, 0);
S3Source s3Source(s3uri);
s3Source.setup(mockServer);
DataBuffer dataBuffer;
LengthBuffer lengthBuffer;
dataBuffer.buf = new char[10240];
dataBuffer.offset = 0;
dataBuffer.size = 10240;
FILE* file = fopen(tempfile, "wb" );
long total = 0;
while(s3Source.processWithMetadata(mockServer, dataBuffer, lengthBuffer) != DONE) {
if (dataBuffer.offset > 0) {
total += fwrite(dataBuffer.buf, sizeof(char), dataBuffer.offset, file);
dataBuffer.offset = 0;
}
}
total += fwrite(dataBuffer.buf, sizeof(char), dataBuffer.offset, file);
std::cout << total << " Bytes written to file\n" << "Cleanup" << std::endl;
GTEST_ASSERT_EQ(total, s3Source.totalBytes);
delete dataBuffer.buf;
fclose(file);
s3Source.destroy(mockServer);
}
TEST(library, plan) {
MockVTAllocator mockVTAllocator;
ServerInterface::LoggingFunc func;
std::map<std::string, size_t> paramNameToIndex;
paramNameToIndex["url"] = 1;
std::vector<char *> cols;
std::vector<VString> svWrappers;
svWrappers.push_back(VString(NULL, NULL, StringNull));
svWrappers.push_back(VString(NULL, NULL, StringNull));
char temp[] = "s3://bucket/path1|s3://bucket/path2";
EE::StringValue *val = (EE::StringValue *)malloc(sizeof(EE::StringValue) + 36 * sizeof(char));
val->slen = 35;
val->sloc = 0;
std::memcpy(&val->base, &temp[0], sizeof(temp));
char temp1[] = "";
cols.push_back(&temp1[0]);
cols.push_back(reinterpret_cast<char*>(val));
MockParamReader mockParamReader(paramNameToIndex,cols,svWrappers);
MockServerImpl mockServer(&mockVTAllocator, func, std::string("string"), mockParamReader, 0);
MockParamWriter mockParamWriter(&mockVTAllocator);
std::vector<std::string> clusterNodes;
clusterNodes.push_back("node_a");
clusterNodes.push_back("node_b");
MockNodeSpecifyingPlanContext mockNodeSpecifyingPlanContext(mockParamWriter, clusterNodes, true);
std::cout << "Starting test" << std::endl;
S3SourceFactory s3SourceFactory;
s3SourceFactory.plan(mockServer, mockNodeSpecifyingPlanContext);
GTEST_ASSERT_EQ(mockNodeSpecifyingPlanContext.getTargetNodes().size(), 2);
GTEST_ASSERT_EQ(mockNodeSpecifyingPlanContext.getWriter().getParamNames().size(), 2);
GTEST_ASSERT_EQ(mockNodeSpecifyingPlanContext.getWriter().getStringRef("node_a:0").str(), "s3://bucket/path1");
GTEST_ASSERT_EQ(mockNodeSpecifyingPlanContext.getWriter().getStringRef("node_b:1").str(), "s3://bucket/path2");
}
|
#include <stdio.h> // basic I/O
#include <stdlib.h>
#include <sys/types.h> // standard system types
#include <netinet/in.h> // Internet address structures
#include <sys/socket.h> // socket API
#include <arpa/inet.h>
#include <netdb.h> // host to IP resolution
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <dirent.h>
#include <vector>
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
#define HOSTNAMELEN 40 // maximal host name length; can make it variable if you want
#define BUFLEN 1024 // maximum response size; can make it variable if you want
#define BUFFER_SIZE 256
// prototype
void checkParameters(int argc, char *argv[]);
int openSocket(void);
void connect2Server(int sock_id, struct sockaddr_in srv_ad);
struct hostent* getHostName(char* hostname);
void recvMessage(int sock_id, char buff[], int buff_size);
void sendMessage(int sock_id, char buff[], int buff_size);
void clearBuffer(char buff[]);
void printClientDir(void);
string getFileName(char buff[]);
bool isExists(string filename);
bool createFile(string filename);
int main(int argc, char *argv[])
{
// variable definitions
int c_sock_fd, port;
struct sockaddr_in srv_ad;
struct hostent *serv;
char buff[BUFFER_SIZE];
// check that there are enough parameters
checkParameters(argc, argv);
port = atoi(argv[2]); // getting port no.
c_sock_fd = openSocket(); // open socket
char *hostname = argv[1];
serv = getHostName(hostname); // get hostname
// server details
srv_ad.sin_family = AF_INET;
srv_ad.sin_port = htons(port);
int serv_l = serv->h_length;
bcopy((char *)serv->h_addr, (char *) &srv_ad.sin_addr.s_addr, serv_l);
connect2Server(c_sock_fd, srv_ad); // Connect to server
clearBuffer(buff);
recvMessage(c_sock_fd, buff, BUFFER_SIZE); // Welcome Message
cout << endl << buff << endl << endl;
bool flag = true;
string cmd;
do
{
clearBuffer(buff);
cout << "\nc : ";
fgets(buff, BUFFER_SIZE, stdin);
if (strncmp(buff, "List client", 11) == 0)
{
clearBuffer(buff);
cmd = "_noA";
strcpy(buff, cmd.c_str());
sendMessage(c_sock_fd, buff, strlen(buff));
printClientDir();
}
else if (strncmp(buff, "List server", 11) == 0)
{
clearBuffer(buff);
cmd = "list";
strcpy(buff, cmd.c_str());
sendMessage(c_sock_fd, buff, strlen(buff));
clearBuffer(buff);
recvMessage(c_sock_fd, buff, BUFFER_SIZE);
cout << buff << endl;
}
else if (strncmp(buff, "Create client", 13) == 0)
{
string filename = getFileName(buff);
clearBuffer(buff);
cmd = "_noA";
strcpy(buff, cmd.c_str());
sendMessage(c_sock_fd, buff, strlen(buff));
if (isExists(filename))
{
cout << "Client: The file '" << filename << "' already exists.";
}
else if (createFile(filename))
{
cout << "Client: The file '" << filename << "' has been created.";
}
}
else if (strncmp(buff, "Create server", 13) == 0)
{
string filename = getFileName(buff);
clearBuffer(buff);
cmd = "_cre";
strcpy(buff, cmd.c_str());
sendMessage(c_sock_fd, buff, strlen(buff));
clearBuffer(buff);
strcpy(buff, filename.c_str());
sendMessage(c_sock_fd, buff, strlen(buff));
clearBuffer(buff);
recvMessage(c_sock_fd, buff, BUFFER_SIZE);
cout << buff << endl;
}
else if (strncmp(buff, "exit", 4) == 0)
{
flag = false;
clearBuffer(buff);
cmd = "exit";
strcpy(buff, cmd.c_str());
sendMessage(c_sock_fd, buff, strlen(buff));
}
else
{
clearBuffer(buff);
cmd = "help";
strcpy(buff, cmd.c_str());
sendMessage(c_sock_fd, buff, strlen(buff));
clearBuffer(buff);
recvMessage(c_sock_fd, buff, BUFFER_SIZE);
cout << buff << endl;
}
} while (flag);
close(c_sock_fd);
return 0;
}
void checkParameters(int argc, char* argv[])
{
if (argc != 3)
{
fprintf(stderr, "Usage: %s <hostname> <port>\n", argv[0]);
exit(-1);
}
}
int openSocket(void)
{
int sock_id = socket(AF_INET, SOCK_STREAM, 0);
if (sock_id < 0)
{
cout << "Error : Opening Socket\n";
exit(-1);
}
return sock_id;
}
void connect2Server(int sock_id, struct sockaddr_in srv_ad)
{
int srv_size = sizeof(srv_ad);
if (connect(sock_id, (struct sockaddr *) &srv_ad, srv_size) < 0)
{
cout << "Error : connection failed\n";
exit(-1);
}
}
struct hostent* getHostName(char* hostname)
{
struct hostent *serv;
serv = gethostbyname(hostname);
if (serv == NULL)
{
cout << "Error : host not available\n";
exit(-1);
}
return serv;
}
void recvMessage(int sock_id, char buff[], int buff_size)
{
int x = read(sock_id, buff, buff_size);
if (x < 0)
{
cout << "Error : reading from socket failed\n";
exit(-1);
}
}
void sendMessage(int sock_id, char buff[], int buff_size)
{
int x = write(sock_id, buff, buff_size);
if (x < 0)
{
cout << "Error : writing to socket failed\n";
exit(-1);
}
}
void clearBuffer(char buff[])
{
bzero(buff, BUFFER_SIZE);
}
void printClientDir(void)
{
cout << "\n> Client : File List\n";
DIR *_dir;
struct dirent *_files;
_dir = opendir("./");
if (_dir != NULL)
{
while (_files = readdir(_dir))
{
cout << "> " << _files->d_name << endl;
}
}
}
string getFileName(char buff[])
{
vector<string> cmd;
string temp = "";
for (int i = 0; i < strlen(buff) - 1; i++)
{
if (buff[i] == ' ')
{
cmd.push_back(temp);
temp = "";
}
else
{
temp += buff[i];
}
}
cmd.push_back(temp);
return cmd[cmd.size() - 1];
}
bool isExists(string filename)
{
ifstream in_file;
in_file.open(filename.c_str());
if (in_file.fail())
{
return false;
}
in_file.close();
return true;
}
bool createFile(string filename)
{
ofstream of_file;
of_file.open(filename.c_str());
if (of_file.fail())
{
return false;
}
of_file.close();
return true;
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "WidgetNoteGradeBase.generated.h"
UENUM(BlueprintType)
enum class EGrade : uint8
{
COOL,
FINE,
SAFE,
BAD,
MISS
};
/**
*
*/
UCLASS()
class DIVAR_API UWidgetNoteGradeBase : public UUserWidget
{
GENERATED_BODY()
public:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
EGrade grade;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
int combo;
};
|
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
#define int long long int
#define ld long double
#define F first
#define S second
#define P pair<int,int>
#define pb push_back
#define endl '\n'
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
const int N = 1e2 + 5;
vector <int> Graph[N];
vector <int> ans;
vector <int> indeg;
int n, m;
typedef vector <int> vi;
void kahn(int n) {
priority_queue <int, vector<int>, greater<int>> q;
for (int i = 1; i <= n; i++) {
if (indeg[i] == 0)
q.push(i);
}
while (!q.empty()) {
int temp = q.top();
q.pop();
ans.pb(temp);
for (auto to : Graph[temp]) {
indeg[to]--;
if (indeg[to] == 0)
q.push(to);
}
}
for (auto x : ans)
cout << x << " ";
cout << endl;
}
void solve() {
indeg = vi(N, 0);
ans.clear();
cin >> n >> m;
while (m--) {
int u, v; cin >> u >> v;
Graph[u].pb(v);
indeg[v]++;
}
kahn(n);
return ;
}
int32_t main() {
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
ios_base:: sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
/* → → → → → → → → → → → → → → → → → → → → → → → → → → → →
→ → → → → → → → → → → → → → → → → → → → → → → → → → → → */
//int t;cin>>t;while(t--)
solve();
return 0;
}
|
// Copyright (c) 2021 ETH Zurich
//
// 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/config.hpp>
#include <pika/modules/execution.hpp>
#include <pika/testing.hpp>
#include <pika/execution_base/tests/algorithm_test_utils.hpp>
#include <atomic>
#include <exception>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
namespace ex = pika::execution::experimental;
// This overload is only used to check dispatching. It is not a useful
// implementation.
template <typename... Ss>
auto tag_invoke(ex::when_all_t, custom_sender_tag_invoke s, Ss&&... ss)
{
s.tag_invoke_overload_called = true;
return ex::when_all(std::forward<Ss>(ss)...);
}
int main()
{
// Success path
{
std::atomic<bool> set_value_called{false};
auto s = ex::when_all(ex::just(42));
auto f = [](int x) { PIKA_TEST_EQ(x, 42); };
auto r = callback_receiver<decltype(f)>{f, set_value_called};
auto os = ex::connect(std::move(s), std::move(r));
tag_invoke(ex::start, os);
PIKA_TEST(set_value_called);
}
{
std::atomic<bool> set_value_called{false};
auto s = ex::when_all(ex::just(42), ex::just(std::string("hello")), ex::just(3.14));
auto f = [](int x, std::string y, double z) {
PIKA_TEST_EQ(x, 42);
PIKA_TEST_EQ(y, std::string("hello"));
PIKA_TEST_EQ(z, 3.14);
};
auto r = callback_receiver<decltype(f)>{f, set_value_called};
auto os = ex::connect(std::move(s), std::move(r));
ex::start(os);
PIKA_TEST(set_value_called);
}
{
std::atomic<bool> set_value_called{false};
auto s = ex::when_all(ex::just(), ex::just(std::string("hello")), ex::just(3.14));
auto f = [](std::string y, double z) {
PIKA_TEST_EQ(y, std::string("hello"));
PIKA_TEST_EQ(z, 3.14);
};
auto r = callback_receiver<decltype(f)>{f, set_value_called};
auto os = ex::connect(std::move(s), std::move(r));
ex::start(os);
PIKA_TEST(set_value_called);
}
{
std::atomic<bool> set_value_called{false};
auto s = ex::when_all(ex::just(42), ex::just(), ex::just(3.14));
auto f = [](int x, double z) {
PIKA_TEST_EQ(x, 42);
PIKA_TEST_EQ(z, 3.14);
};
auto r = callback_receiver<decltype(f)>{f, set_value_called};
auto os = ex::connect(std::move(s), std::move(r));
ex::start(os);
PIKA_TEST(set_value_called);
}
{
std::atomic<bool> set_value_called{false};
auto s = ex::when_all(ex::just(), ex::just(), ex::just());
auto f = []() {};
auto r = callback_receiver<decltype(f)>{f, set_value_called};
auto os = ex::connect(std::move(s), std::move(r));
ex::start(os);
PIKA_TEST(set_value_called);
}
{
std::atomic<bool> set_value_called{false};
auto s = ex::when_all(ex::just(42), ex::just(std::string("hello")), ex::just());
auto f = [](int x, std::string y) {
PIKA_TEST_EQ(x, 42);
PIKA_TEST_EQ(y, std::string("hello"));
};
auto r = callback_receiver<decltype(f)>{f, set_value_called};
auto os = ex::connect(std::move(s), std::move(r));
ex::start(os);
PIKA_TEST(set_value_called);
}
{
std::atomic<bool> set_value_called{false};
auto s = ex::when_all(ex::just(42, std::string("hello"), 3.14));
auto f = [](int x, std::string y, double z) {
PIKA_TEST_EQ(x, 42);
PIKA_TEST_EQ(y, std::string("hello"));
PIKA_TEST_EQ(z, 3.14);
};
auto r = callback_receiver<decltype(f)>{f, set_value_called};
auto os = ex::connect(std::move(s), std::move(r));
ex::start(os);
PIKA_TEST(set_value_called);
}
{
std::atomic<bool> set_value_called{false};
auto s = ex::when_all(ex::just(42, std::string("hello")), ex::just(3.14));
auto f = [](int x, std::string y, double z) {
PIKA_TEST_EQ(x, 42);
PIKA_TEST_EQ(y, std::string("hello"));
PIKA_TEST_EQ(z, 3.14);
};
auto r = callback_receiver<decltype(f)>{f, set_value_called};
auto os = ex::connect(std::move(s), std::move(r));
ex::start(os);
PIKA_TEST(set_value_called);
}
{
std::atomic<bool> set_value_called{false};
auto s = ex::when_all(
ex::just(), ex::just(42, std::string("hello")), ex::just(), ex::just(3.14), ex::just());
auto f = [](int x, std::string y, double z) {
PIKA_TEST_EQ(x, 42);
PIKA_TEST_EQ(y, std::string("hello"));
PIKA_TEST_EQ(z, 3.14);
};
auto r = callback_receiver<decltype(f)>{f, set_value_called};
auto os = ex::connect(std::move(s), std::move(r));
ex::start(os);
PIKA_TEST(set_value_called);
}
{
std::atomic<bool> set_value_called{false};
auto s = ex::when_all(ex::just(custom_type_non_default_constructible(42)));
auto f = [](auto x) { PIKA_TEST_EQ(x.x, 42); };
auto r = callback_receiver<decltype(f)>{f, set_value_called};
auto os = ex::connect(std::move(s), std::move(r));
ex::start(os);
PIKA_TEST(set_value_called);
}
{
std::atomic<bool> set_value_called{false};
auto s = ex::when_all(ex::just(custom_type_non_default_constructible_non_copyable(42)));
auto f = [](auto x) { PIKA_TEST_EQ(x.x, 42); };
auto r = callback_receiver<decltype(f)>{f, set_value_called};
auto os = ex::connect(std::move(s), std::move(r));
ex::start(os);
PIKA_TEST(set_value_called);
}
{
std::atomic<bool> receiver_set_value_called{false};
std::atomic<bool> tag_invoke_overload_called{false};
auto s = ex::when_all(custom_sender_tag_invoke{tag_invoke_overload_called}, ex::just(42));
auto f = [](int x) { PIKA_TEST_EQ(x, 42); };
auto r = callback_receiver<decltype(f)>{f, receiver_set_value_called};
auto os = ex::connect(std::move(s), std::move(r));
ex::start(os);
PIKA_TEST(receiver_set_value_called);
PIKA_TEST(tag_invoke_overload_called);
}
{
std::atomic<bool> set_value_called{false};
int x = 42;
auto s = ex::when_all(const_reference_sender<int>{x});
auto f = [](auto&& x) { PIKA_TEST_EQ(x, 42); };
auto r = callback_receiver<decltype(f)>{f, set_value_called};
auto os = ex::connect(std::move(s), std::move(r));
ex::start(os);
PIKA_TEST(set_value_called);
}
{
int x = 42;
auto s = ex::when_all(const_reference_sender<int>{x});
#if defined(PIKA_HAVE_STDEXEC)
// The reference implementation does not remove_cvref the types sent.
PIKA_UNUSED(s);
#else
using value_types = typename pika::execution::experimental::sender_traits<
decltype(s)>::template value_types<std::tuple, pika::detail::variant>;
using expected_value_types = pika::detail::variant<std::tuple<int>>;
static_assert(std::is_same_v<value_types, expected_value_types>,
"when_all should remove_cvref the value types sent");
#endif
}
// Failure path
{
std::atomic<bool> set_error_called{false};
auto s = ex::when_all(error_sender<double>{});
auto r = error_callback_receiver<decltype(check_exception_ptr)>{
check_exception_ptr, set_error_called};
auto os = ex::connect(std::move(s), std::move(r));
ex::start(os);
PIKA_TEST(set_error_called);
}
{
std::atomic<bool> set_error_called{false};
auto s = ex::when_all(ex::just(42), error_sender<double>{});
auto r = error_callback_receiver<decltype(check_exception_ptr)>{
check_exception_ptr, set_error_called};
auto os = ex::connect(std::move(s), std::move(r));
ex::start(os);
PIKA_TEST(set_error_called);
}
{
std::atomic<bool> set_error_called{false};
auto s = ex::when_all(error_sender<double>{}, ex::just(42));
auto r = error_callback_receiver<decltype(check_exception_ptr)>{
check_exception_ptr, set_error_called};
auto os = ex::connect(std::move(s), std::move(r));
ex::start(os);
PIKA_TEST(set_error_called);
}
{
std::atomic<bool> set_error_called{false};
auto s = ex::when_all(const_reference_error_sender{}, ex::just(42));
auto r = error_callback_receiver<decltype(check_exception_ptr)>{
check_exception_ptr, set_error_called};
auto os = ex::connect(std::move(s), std::move(r));
ex::start(os);
PIKA_TEST(set_error_called);
}
test_adl_isolation(ex::when_all(my_namespace::my_sender{}));
return 0;
}
|
class Category_646 {
duplicate = 625;
};
class Category_611 {
duplicate = 625;
};
|
//
// Grenade.hpp for grenade in /home/deneub_s/cpp_indie_studio/include
//
// Made by Stanislas Deneubourg
// Login <deneub_s@epitech.net>
//
// Started on Thu Jun 1 07:50:34 2017 Stanislas Deneubourg
// Last update Thu Jun 1 08:06:35 2017 Stanislas Deneubourg
//
#ifndef GRENADE_HPP
#define GRENADE_HPP
#include "Interface/IWeapon.hpp"
class Grenade : public IWeapon
{
private:
float splash_damage_range;
int max_damage;
float weight;
public:
Grenade();
virtual ~Grenade();
};
#endif
|
// modulus.js
// return remainder of two numbers
function modulus(a, b) {
return a % b;
};
|
#include <bits/stdc++.h>
#define WIN 3
#define DRAW 1
#define LOSE 0
using namespace std;
int a[100][100];
int m, n;
void input(){
cin >> m >> n;
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
cin >> a[i][j];
}
int main(){
int highestScore = -1;
int champion;
freopen("BODA.inp", "r", stdin);
freopen("BODA.out", "w", stdout);
input();
for (int i = 0; i < m; ++i) {
int nWin = 0,
nDraw = 0,
nLose = 0,
score = 0;
for (int j = 0; j < n; ++j) {
if(a[i][j] == WIN)
nWin++;
if(a[i][j] == DRAW)
nDraw++;
if(a[i][j] == LOSE)
nLose++;
}
score += nDraw + nWin*WIN;
cout << nWin << " " << nDraw << " " << nLose << " " << score << endl;
if(score > highestScore){
highestScore = score;
champion = i;
}
}
cout << champion+1;
return 0;
}
|
/*
* Copyright (c) 2016, The Regents of the University of California (Regents).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Please contact the author(s) of this library if you have any questions.
* Author: Erik Nelson ( eanelson@eecs.berkeley.edu )
*/
#include <raytracing/scene.h>
#include <strings/has_substring.h>
#include <strings/tokenize.h>
#include <iostream>
#include <numeric>
Scene::Scene() {}
Scene::~Scene() {}
bool Scene::LoadFromFile(const std::string& filename) {
// Open the file.
std::ifstream file;
file.open(filename.c_str(), std::ifstream::in);
if (!file.is_open()) {
std::cout << "Could not open configuration file: " << filename << "."
<< std::endl;
return false;
}
// Read lines from the file.
std::string object_line;
while (std::getline(file, object_line)) {
// Create a lens.
if (strings::HasSubstring(object_line, "lens")) {
Lens lens;
std::string parameter;
std::vector<std::string> tokens;
// Load lens parameters.
if (!std::getline(file, parameter)) break;
if (!strings::HasSubstring(parameter, "parameters")) break;
if (!std::getline(file, parameter)) break;
strings::Tokenize(parameter, ' ', &tokens);
lens.SetRadius1(std::stod(tokens[1], NULL));
if (!std::getline(file, parameter)) break;
strings::Tokenize(parameter, ' ', &tokens);
lens.SetRadius2(std::stod(tokens[1], NULL));
if (!std::getline(file, parameter)) break;
strings::Tokenize(parameter, ' ', &tokens);
lens.SetThickness(std::stod(tokens[1], NULL));
if (!std::getline(file, parameter)) break;
strings::Tokenize(parameter, ' ', &tokens);
lens.SetWidth(std::stod(tokens[1], NULL));
if (!std::getline(file, parameter)) break;
strings::Tokenize(parameter, ' ', &tokens);
lens.SetIndexOfRefraction(std::stod(tokens[1], NULL));
if (!std::getline(file, parameter)) break;
if (!strings::HasSubstring(parameter, "position")) break;
if (!std::getline(file, parameter)) break;
strings::Tokenize(parameter, ' ', &tokens);
lens.SetX(std::stod(tokens[1], NULL));
if (!std::getline(file, parameter)) break;
strings::Tokenize(parameter, ' ', &tokens);
lens.SetY(std::stod(tokens[1], NULL));
if (!std::getline(file, parameter)) break;
strings::Tokenize(parameter, ' ', &tokens);
lens.SetZ(std::stod(tokens[1], NULL));
if (!std::getline(file, parameter)) break;
if (!strings::HasSubstring(parameter, "orientation")) break;
if (!std::getline(file, parameter)) break;
strings::Tokenize(parameter, ' ', &tokens);
lens.SetRoll(std::stod(tokens[1], NULL));
if (!std::getline(file, parameter)) break;
strings::Tokenize(parameter, ' ', &tokens);
lens.SetPitch(std::stod(tokens[1], NULL));
if (!std::getline(file, parameter)) break;
strings::Tokenize(parameter, ' ', &tokens);
lens.SetYaw(std::stod(tokens[1], NULL));
lens.Print("Loaded lens with parameters:");
lenses_.push_back(lens);
}
// Create a ray.
if (strings::HasSubstring(object_line, "ray")) {
Ray ray;
std::string parameter;
std::vector<std::string> tokens;
// Load ray parameters.
if (!std::getline(file, parameter)) break;
if (!strings::HasSubstring(parameter, "origin")) break;
if (!std::getline(file, parameter)) break;
strings::Tokenize(parameter, ' ', &tokens);
ray.SetOriginX(std::stod(tokens[1], NULL));
if (!std::getline(file, parameter)) break;
strings::Tokenize(parameter, ' ', &tokens);
ray.SetOriginY(std::stod(tokens[1], NULL));
if (!std::getline(file, parameter)) break;
strings::Tokenize(parameter, ' ', &tokens);
ray.SetOriginZ(std::stod(tokens[1], NULL));
if (!std::getline(file, parameter)) break;
if (!strings::HasSubstring(parameter, "direction")) break;
if (!std::getline(file, parameter)) break;
strings::Tokenize(parameter, ' ', &tokens);
ray.SetDirectionX(std::stod(tokens[1], NULL));
if (!std::getline(file, parameter)) break;
strings::Tokenize(parameter, ' ', &tokens);
ray.SetDirectionY(std::stod(tokens[1], NULL));
if (!std::getline(file, parameter)) break;
strings::Tokenize(parameter, ' ', &tokens);
ray.SetDirectionZ(std::stod(tokens[1], NULL));
ray.NormalizeDirection();
ray.Print("Loaded ray with parameters:");
rays_.push_back(ray);
}
}
// Loop back through and create buffer objects for all new lenses.
for (size_t ii = 0; ii < lenses_.size(); ++ii)
lenses_[ii].Initialize();
return true;
}
void Scene::Render(bool draw_axes, const glm::vec3& camera_position_) {
if (draw_axes) {
// Draw some axes.
RenderAxes();
}
// Render ray paths first, since they are opaque.
for (const auto& path : paths_) path.Render();
// Sort lenses by distance to camera. Render the back one first so that we
// alpha blend correctly.
std::vector<double> distances;
for (const auto& lens : lenses_)
distances.push_back(glm::length(camera_position_ - lens.GetPosition()));
std::vector<int> lens_indices(distances.size());
std::iota(lens_indices.begin(), lens_indices.end(), 0);
auto comparator = [&distances](int a, int b) {
return distances[a] > distances[b];
};
std::sort(lens_indices.begin(), lens_indices.end(), comparator);
// Render lenses from back to front.
for (const auto& lens_index : lens_indices) {
lenses_[lens_index].Render();
}
}
void Scene::ComputePaths() {
// Loop over rays, tracing their collisions and refractions off of lenses in
// the scene. Store all resulting ray paths.
paths_.clear();
for (const auto& ray : rays_) {
paths_.push_back(ray.Trace(lenses_));
}
// Make buffer objects for all new paths that were created.
for (auto& path : paths_){
path.Initialize();
path.MakeBufferObjects();
}
}
void Scene::RenderAxes() {
glBegin(GL_LINES);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(1.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, 1.0);
glEnd();
}
void Scene::MakeBufferObjects() {
for (auto& lens : lenses_) {
lens.MakeBufferObjects();
}
}
void Scene::AddLens(const Lens& lens) {
lenses_.push_back(lens);
}
void Scene::AddRay(const Ray& ray) {
rays_.push_back(ray);
}
bool Scene::GetLens(unsigned int index, Lens* lens) const {
if (index < lenses_.size()) {
*lens = lenses_[index];
return true;
}
return false;
}
bool Scene::GetRay(unsigned int index, Ray* ray) const {
if (index < rays_.size()) {
*ray = rays_[index];
return true;
}
return false;
}
|
/**
* @file test_icethread.cpp
*
* @author Fan Kai(fk), Peking University
*
*/
#include <IceUtil/Mutex.h>
#include <IceUtil/RecMutex.h>
#include <IceUtil/Thread.h>
#include <IceUtil/Exception.h>
#include <iostream>
using namespace std;
class MT : public IceUtil::Thread {
public:
void run() {
cout <<"start" <<endl;
//new char[8*1024*1024];
//throw exception();
sleep(3);
cout <<"finish" <<endl;
}
};
int main() {
try {
IceUtil::ThreadPtr tp = new MT();
tp->start();
tp->getThreadControl().join();
} catch (exception &ex) {
cerr <<"Catch: " <<ex.what() <<endl;
}
IceUtil::ThreadPtr tp = new MT();
tp->start();
tp->getThreadControl().join();
try {
int i = 0;
while (true) {
IceUtil::ThreadPtr tp = new MT();
tp->start(64*1024*1024);//.detach();
cout <<i++ <<" " <<tp->getThreadControl().id() <<endl;
sleep(1);
}
} catch (IceUtil::Exception &ex) {
cout <<ex <<endl;
}
return 0;
}
|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "GameFramework/GameMode.h"
#include "CarolloGameMode.generated.h"
UCLASS(minimalapi)
class ACarolloGameMode : public AGameMode
{
GENERATED_BODY()
public:
ACarolloGameMode();
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.