blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2 values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905 values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22 values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 3 10.4M | extension stringclasses 115 values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fc367bfbf43a6c7984e121f6c9ae9b7fd476ed10 | 05a8e4cdcc7b49dc7c92e759fc2f14d398ca9a2e | /projeto/QtTcpClientConsumer/plotter.cpp | 45f19e629129900dae19464d0484c8ec02e14a17 | [] | no_license | Ana-Beatriz-Marinho/DCA1202 | 8123bd2b6d1ad124f8be213caff99828d6258391 | 7e924f1cad7b0e2e173ef15d17a6da54499ea616 | refs/heads/master | 2020-04-03T11:47:48.357799 | 2018-12-12T10:39:11 | 2018-12-12T10:39:11 | 155,232,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,249 | cpp | #include "plotter.h"
#include <QPainter>
#include <QBrush>
#include <QPen>
#include <cmath>
#include <QMouseEvent>
using namespace std;
#define PI 3.1415
Plotter::Plotter(QWidget *parent) : QWidget(parent){
}
void Plotter::paintEvent(QPaintEvent *evento){
QPainter painter(this);
QBrush brush;
QPen pen;
int x1, y1, x2, y2;
//brush cor amarela e sólida
brush.setColor(QColor(255,255,100));
brush.setStyle(Qt::SolidPattern);
//caneta cor vermelha
pen.setColor(QColor(255,0,0));
pen.setWidth(2);
//informe ao pintor qual o brush atual
painter.setBrush(brush);
//informa um retangulo abrangendo toda a extensao
painter.setPen(pen);
//desenha um retangulo abrangendo toda extensao
//componente
painter.drawRect(0,0,width(),height());
//desenha um seno na tela
pen.setColor(QColor(255,180,0));
painter.setPen(pen);
painter.drawLine(0, height()/2, width(), height()/2);
x1 = 0;
y1 = height()/2;
//desenha um seno na tela
pen.setColor(QColor(0,0,255));
painter.setPen(pen);
for(int i=1; i<width(); i++){
x2 = i;
y2 = height()/2 *(1- sin(2*PI*x2/width()));
painter.drawLine(x1,y1,x2,y2);
x1 = x2;
y1 = y2;
}
}
void Plotter::mousePressEvent(QMouseEvent *event)
{
emit mudouX(event->x());
emit mudouY(event->y());
}
| [
"anabibimn@hotmail.com"
] | anabibimn@hotmail.com |
6a2d9538d823f77e96bda5d4e459a5fdd25bca3b | b0dd7779c225971e71ae12c1093dc75ed9889921 | /libs/math/test/test_rational_instances/test_rational_ldouble2.cpp | 49fdce22061a2e30762e6330d6a2052f54002db2 | [
"LicenseRef-scancode-warranty-disclaimer",
"BSL-1.0"
] | permissive | blackberry/Boost | 6e653cd91a7806855a162347a5aeebd2a8c055a2 | fc90c3fde129c62565c023f091eddc4a7ed9902b | refs/heads/1_48_0-gnu | 2021-01-15T14:31:33.706351 | 2013-06-25T16:02:41 | 2013-06-25T16:02:41 | 2,599,411 | 244 | 154 | BSL-1.0 | 2018-10-13T18:35:09 | 2011-10-18T14:25:18 | C++ | UTF-8 | C++ | false | false | 338 | cpp | // (C) Copyright John Maddock 2006-7.
// Use, modification and distribution are subject to 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 "test_rational.hpp"
template void do_test_spots<long double, int>(long double, int);
| [
"tvaneerd@rim.com"
] | tvaneerd@rim.com |
70780414496f670ad6b1c11e867727dd4c6db92a | 8f7fa80257b32885aeb7964e82b73147ae74365f | /bst/BST_connect34.h | 1e039520375ea6f1c0fa435d270bf3e40a941448 | [] | no_license | npjtwy/DS_CPP | 0f063a333121711666f29301dcefc0ffd1d06efe | 6dbe68e67249cb513884f6828355f3bb8e13639a | refs/heads/master | 2021-01-11T19:15:10.479933 | 2017-05-24T08:49:08 | 2017-05-24T08:49:08 | 79,341,972 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 653 | h | #pragma once
/*
* 3+4 重构 将失衡子树重组为平衡子树
*/
template<typename T>
BinNodePosi(T)
BST<T>::connect34( //按照“3 + 4”结构,联接3个节点及四棵子树
BinNodePosi(T) a, BinNodePosi(T) b, BinNodePosi(T) c,
BinNodePosi(T) t1, BinNodePosi(T) t2, BinNodePosi(T) t3, BinNodePosi(T) t4
)
{
a->lChild = t1; if ( t1 ) t1->parent = a;
a->rChild = t2; if ( t2 ) t2->parent = a;
updateHeight(a);
c->lChild = t3; if ( t3 ) t3->parent = c;
c->rChild = t4; if ( t4 ) t4->parent = c;
updateHeight(c);
a->parent = b; c->parent = b;
b->lChild = a; b->rChild = c;
updateHeight(b);
return b;//返回新的子树根节点
} | [
"nwpuwy.qq.com"
] | nwpuwy.qq.com |
8b0442ca06df5883727451b0e6222dd8549cb9dc | 4dda91e22ad7ea1fbfe4a8065865a380fdb9bda5 | /大作业22.cpp | a4df1575f775b11185316405cb9c942afb70b000 | [] | no_license | glj-27/github | 1d4e49543bc39ef9d2f65418d8f70e463b4ecdca | c323b6404c6aa04a0e6e5b9fc2ee265837954be1 | refs/heads/master | 2020-07-10T10:03:26.814252 | 2019-08-25T03:00:19 | 2019-08-25T03:00:19 | 204,236,443 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 15,723 | cpp | #include<iostream>
#include<cstdio>
#include<cstring>
#include <conio.h>
#include<stdlib.h>
#include<fstream>
#include<algorithm>
using namespace std;
class people
{
public:
char name[20];
int birthday[3];
char phone[20];
char email[30];
char relationship;
char mm[30];
};
int num;people student[100];
bool compare(people a , people b)
{
return strcmp( a.name ,b.name ) < 0;
}
class menu :public people
{
public:
void add()
{
cout << "*****录入个人信息*****" << endl;
cout << "*请输入他的姓名:";
cin >> student[num].name; cout << endl;
cout << "*请输入他与你的关系(1.同学,2.同事,3.亲戚):";
cin >> student[num].relationship; cout << endl;
if (student[num].relationship == '1'){cout << "*请输入你们的学校:";
cin >> student[num].mm; cout << endl;}
else if (student[num].relationship == '2'){cout << "*请输入你们的单位:";
cin >> student[num].mm; cout << endl;}
else if (student[num].relationship == '3'){cout << "*请输入你对他的称呼:";
cin >> student[num].mm; cout << endl;}
cout << "*请输入他的生日( 年 月 日):";
cin >> student[num].birthday[0] >> student[num].birthday[1] >> student[num].birthday[2]; cout << endl;
cout << "*请输入他的电话:";
cin >> student[num].phone; cout << endl;
cout << "*请输入他的邮箱:";
cin >> student[num].email;
cout << endl << "**********************"<<endl;
}
void modification()
{
int n; string m;int l=0;
system("cls");
cout << "******修改个人信息*****" << endl;
if (num != 0)
{
cout << "*要修改的人姓名:" ;
cin >> m;
for (n = 0; n < num; n++)
{
if (student[n].name == m)
{
l=1;
int i;
cout << "*你要修改(1.电话;2.邮箱; 3.关系; ):";
cin >> i;
switch (i)
{
case 1:
char p[20];
cout << "*请输入要修改的电话:";
cin >> p;
strcpy (student[n].phone,p);
cout<<endl<<"*修改完成!"<<endl;
break;
case 2:
char e[30];
cout << "*请输入要修改的邮箱:";
cin >> e;
strcpy (student[n].email,e);
cout<<endl<<"*修改完成!"<<endl;
break;
case 3:
char r;
cout<< "*请输入要修改为什么关系(1.同学;2.同事;3.亲戚;):";
cin >> r;
student[n].relationship=r;
char m[30];
if(student[n].relationship=='1')
{
cout<<"输入要修改为什么学校:";
cin>>m;
strcpy(student[n].mm,m);
}
else if(student[n].relationship=='2')
{
cout<<"输入要修改为什么单位:";
cin>>m;
strcpy(student[n].mm,m);
}
else if(student[n].relationship=='3')
{
cout<<"输入要修改为什么称呼:";
cin>>m;
strcpy(student[n].mm,m);
}
cout<<endl<<"*修改完成!"<<endl;
break ;
}
}
}
}
else cout << "*无记录!" << endl;
if(l==0)cout<< "*无记录!" << endl;
cout << "**********************"<<endl;
}
void deletes()
{
system("cls");
cout << "******删除个人信息*****" << endl;
int i=0;
if (num != 0)
{
cout << "*请输入要删除人的姓名:";
int n; string m;
cin>>m;
for (n = 0; n < num; n++)
{
if(student[n].name==m)
{
i=1;
cout << "*姓名:" << student[n].name << endl;
cout << "*生日:" << student[n].birthday[0] << "/" << student[n].birthday[1] << "/" << student[n].birthday[2] << endl;
cout << "*电话:" << student[n].phone << endl;
cout << "*邮箱:" << student[n].email << endl;
cout << "*关系:" ;
if(student[n].relationship=='1') cout<<"同学"<< endl<< "*学校:"<< student[n].mm << endl<< endl;
else if(student[n].relationship=='2') cout<<"同事"<< endl<< "*单位:"<< student[n].mm << endl<< endl;
else if(student[n].relationship=='3') cout<<"亲戚"<< endl<< "*称呼:"<<student[n].mm << endl<< endl;
cout << "*确定要删除吗?(y/n):";
char x;cin>>x;
if (x == 'y')
{
for(n;n<num;n++)
{
strcpy(student[n].name,student[n+1].name);
student[n].birthday[0] = student[n+1].birthday[0];
student[n].birthday[1] = student[n+1].birthday[1];
student[n].birthday[2] = student[n+1].birthday[2];
strcpy(student[n].phone,student[n+1].phone);
strcpy(student[n].email,student[n+1].email);
student[n].relationship=student[n+1].relationship;
strcpy(student[n].mm,student[n+1].mm);
}
cout<<endl<<"*删除完成!"<<endl;
num--;
}
else if(x == 'n')
{
cout<<endl<<"*未删除!";
}
}
}
}
else cout << "*无记录!" << endl;
if(i==0)cout<< "*无记录!" << endl;
cout << "**********************"<<endl;
}
void ashow()
{
system("cls");
cout << "******列出全部个人信息*****" << endl;
int n;
if (num != 0)
for (n = 0; n < num; n++)
{
cout << "*姓名:" << student[n].name << endl;
cout << "*生日:" << student[n].birthday[0] << "/" << student[n].birthday[1] << "/" << student[n].birthday[2] << endl;
cout << "*电话:" << student[n].phone << endl;
cout << "*邮箱:" << student[n].email << endl;
cout << "*关系:" ;
if(student[n].relationship=='1') cout<<"同学"<< endl<< "*学校:"<< student[n].mm << endl<< endl;
else if(student[n].relationship=='2') cout<<"同事"<< endl<< "*单位:"<< student[n].mm << endl<< endl;
else if(student[n].relationship=='3') cout<<"亲戚"<< endl<< "*称呼:"<<student[n].mm << endl<< endl;
}
else cout << "*无记录!" << endl;
cout << "****************************"<<endl;
}
void bshow()
{
system("cls");
cout << "******列出同学的个人信息*****" << endl;
int n;int i=0;
if (num != 0)
for (n = 0; n < num; n++)
{
if (student[n].relationship == '1')
{
cout << "*姓名:" << student[n].name << endl;
cout << "*生日:" << student[n].birthday[0] << "/" << student[n].birthday[1] << "/" << student[n].birthday[2] << endl;
cout << "*电话:" << student[n].phone << endl;
cout << "*邮箱:" << student[n].email << endl;
cout << "*学校:" << student[n].mm << endl;
cout <<endl;
i=1;
}
}
else cout << "*无记录!" << endl;
if(i==0)cout<< "*无记录!" << endl;
cout << "*****************************"<<endl;
}
void cshow()
{
system("cls");
cout << "******列出同事的个人信息*****" << endl;
int n;int i=0;
if (num != 0)
for (n = 0; n < num; n++)
{
if (student[n].relationship == '2')
{
cout << "*姓名:" << student[n].name << endl;
cout << "*生日:" << student[n].birthday[0] << "/" << student[n].birthday[1] << "/" << student[n].birthday[2] << endl;
cout << "*电话:" << student[n].phone << endl;
cout << "*邮箱:" << student[n].email << endl;
cout << "*单位:" << student[n].mm << endl;
cout <<endl;
i=1;
}
}
else cout << "*无记录!" << endl;
if(i==0)cout<< "*无记录!" << endl;
cout << "*****************************"<<endl;
}
void dshow()
{
system("cls");
int n;int i=0;
cout << "******列出亲戚的个人信息*****" << endl;
if (num != 0)
for (n = 0; n < num; n++)
{
if (student[n].relationship == '3')
{
cout << "*姓名:" << student[n].name << endl;
cout << "*生日:" << student[n].birthday[0] << "/" << student[n].birthday[1] << "/" << student[n].birthday[2] << endl;
cout << "*电话:" << student[n].phone << endl;
cout << "*邮箱:" << student[n].email << endl;
cout << "*称呼:" << student[n].mm << endl;
cout <<endl;
i=1;
}
}
else cout << "*无记录!" << endl;
if(i==0)cout<< "*无记录!" << endl;
cout << "*****************************"<<endl;
}
void checkname()
{
int n; string m;int i=0;
system("cls");
cout << "******查找个人信息*****" << endl;
if (num != 0)
{
cout << "*请输入要查找姓名:";
cin >> m;
for (n = 0; n < num; n++)
{
if (student[n].name == m)
{
cout << "*姓名:" << student[n].name << endl;
cout << "*生日:" << student[n].birthday[0] << "/" << student[n].birthday[1] << "/" << student[n].birthday[2] << endl;
cout << "*电话:" << student[n].phone << endl;
cout << "*邮箱:" << student[n].email << endl;
cout << "*关系:";
if(student[n].relationship='1') cout<<"同学"<< endl<< "*学校:"<< student[n].mm << endl<< endl;
else if(student[n].relationship='2') cout<<"同事"<< endl<< "*单位:"<< student[n].mm << endl<< endl;
else if(student[n].relationship='3') cout<<"亲戚"<< endl<< "*称呼:"<<student[n].mm << endl<< endl;
i=1;
}
}
}
else cout << "*无记录!" << endl;
if(i==0)cout<< "*无记录!" << endl;
cout << "**********************"<<endl;
}
void outfile()
{
system("cls");
cout << "******将个人信息存入文件*****" << endl;
if (num != 0)
{
fstream outfile;
outfile.open( "个人信息管理系统.txt", ios::out|ios::binary );
outfile<<num;
for(int n = 0; n < num; n++)
{ outfile.write( ( char* )&student[n],sizeof( people )) ;}
outfile.close() ;
cout<<endl<<"*写入文件成功!"<<endl;
}
else cout << "*无记录!" << endl;
cout << "*****************************"<<endl;
}
void paixu()
{
system("cls");
cout << "******排序个人信息*****" << endl;
sort(student,student+num,compare);
for (int n = 0; n < num; n++)
{
cout << "*姓名:" << student[n].name << endl;
cout << "*生日:" << student[n].birthday[0] << "/" << student[n].birthday[1] << "/" << student[n].birthday[2] << endl;
cout << "*电话:" << student[n].phone << endl;
cout << "*邮箱:" << student[n].email << endl;
cout << "*关系:" ;
if(student[n].relationship=='1') cout<<"同学"<< endl<< "*学校:"<< student[n].mm << endl<< endl;
else if(student[n].relationship=='2') cout<<"同事"<< endl<< "*单位:"<< student[n].mm << endl<< endl;
else if(student[n].relationship=='3') cout<<"亲戚"<< endl<< "*称呼:"<<student[n].mm << endl<< endl;
}
cout << "**********************"<<endl;
}
void checktime()
{
system("cls");
cout << "******查找同月出生的个人信息*****" << endl;
double m;int x=0;
if (num != 0)
{
cout << "*请输入要查找月份:";
cin >> m;
for (int n = 0; n < num; n++)
{
if (student[n].birthday[1] == m)
{
cout << "*姓名:" << student[n].name << endl;
cout << "*生日:" << student[n].birthday[0] << "/" << student[n].birthday[1] << "/" << student[n].birthday[2] << endl;
cout << "*电话:" << student[n].phone << endl;
cout << "*邮箱:" << student[n].email << endl;
cout << "*关系:";
if(student[n].relationship='1') cout<<"同学"<< endl<< "*学校:"<< student[n].mm << endl<< endl;
else if(student[n].relationship='2') cout<<"同事"<< endl<< "*单位:"<< student[n].mm << endl<< endl;
else if(student[n].relationship='3') cout<<"亲戚"<< endl<< "*称呼:"<<student[n].mm << endl<< endl;
x++;
}
}
}
else cout << "*无记录!" << endl;
if(x==0)cout<< "*无记录!" << endl;
else cout<<"*"<<m<<"月份出生的人数为:"<<x<<"人"<<endl;
cout << "**********************************"<<endl;
}
int runyear(int y)//判断是否是闰年
{
return y%4==0&&y%100!=0||y%400==0;//真返回为1,假为0
}
int daysOfMonth(int y,int m)
{
int day[12]={31,28,31,30,31,30,31,31,30,31,30,31};
if(m!=2) return day[m-1];
else return 28+runyear(y);
}
int daysOfDate(int y,int m,int d)//计算一共的天数
{
int days=d;
for(int a=1;a<y;a++)//计算年
days+=365+runyear(a);
for(int b=1;b<m;b++)//计算月
days+=daysOfMonth(y,b);
return days;
}
void checkdate()
{
system("cls");
cout << "******查找五天内过生日的个人信息*****" << endl;
int date[3];int i=0;
cout<<"*请输入要查找的日期(年 月 日):";
cin>>date[0]>>date[1]>>date[2];
int day1=daysOfDate(date[0],date[1],date[2]);
cout << "*五天内过生日的人如下:"<<endl;
for(int n;n<num;n++)
{
int day2=daysOfDate(date[0],student[n].birthday[1],student[n].birthday[2]);
if(day2-day1>=0&&day2-day1<5)
{
cout << "*姓名:" << student[n].name << endl;
cout << "*生日:" << student[n].birthday[0] << "/" << student[n].birthday[1] << "/" << student[n].birthday[2] << endl;
cout << "*电话:" << student[n].phone << endl;
cout << "*邮箱:" << student[n].email << endl;
cout << "*关系:";
if(student[n].relationship='1') cout<<"同学"<< endl<< "*学校:"<< student[n].mm << endl<< endl;
else if(student[n].relationship='2') cout<<"同事"<< endl<< "*单位:"<< student[n].mm << endl<< endl;
else if(student[n].relationship='3') cout<<"亲戚"<< endl<< "*称呼:"<<student[n].mm << endl<< endl;
i++;
}
}
if(i==0) cout<<"*没有人在最近五天过生日!"<<endl;
else cout<<"近五天过生日的有"<<i<<"人"<<endl;
cout << "*************************************"<<endl;
}
};
int main()
{
fstream infile;
infile.open( "个人信息管理系统.txt", ios::in|ios::binary );
infile>>num;
if(num!=0)
{
for(int n=0;n<num;n++)
{
infile.read(( char * )&student[n],sizeof( people ));
}
infile.close();
}
A:{
cout << "******欢迎使用学生信息管理系统!******"<<endl;
cout << "*1.录入信息;" << endl
<< "*2.修改信息;" << endl
<< "*3.删除信息;" << endl
<< "*4.查找信息;" << endl
<< "*5.列出信息;" << endl
<< "*6.信息排序;" << endl
<< "*7.同月出生查询;" << endl
<< "*8.五天内过生日查询; "<<endl
<< "*9.写入文件;" << endl
<< "*10.退出;" << endl
<< "*温馨提示:退出程序时记得将信息写入文件哦! "<<endl
<< "*请输入1-10:";
int n;
menu eee;
cin >> n;
switch (n)
{
case 1:
eee.add();
num++;
break;
case 2:
eee.modification();
break;
case 3:
eee.deletes();
break;
case 4:
eee.checkname();
break;
case 5:
{
cout << "*你想列出(1.全部信息;2.按关系列出;)" << endl;
cout << "*请输入1-2:";
int m;
cin >> m;
switch (m)
{
case 1:
eee.ashow();
break;
case 2:
{
cout << "*你想列出(1.同学;2.同事;3.亲戚)" << endl;
cout << "*请输入1-3:";
int l;
cin >> l;
switch (l)
{
case 1:
eee.bshow();break;
case 2:
eee.cshow();break;
case 3:
eee.dshow();break;
}
}
break;
}
}
break;
case 6:
eee.paixu();
break;
case 7:
eee.checktime();
break;
case 8:
eee.checkdate();
break;
case 9:
eee.outfile();
break;
case 10:
return 0;
}
}
cout<<"按回车键返回菜单!";
getch();
system("cls");
goto A;
}
| [
"glj1522029024@163.com"
] | glj1522029024@163.com |
7a5fd5e5340e4ffc1888d7a218a5e8135947c3b3 | 1a0ad7854a9b0a6ef5e946f7ee144ee6e5700f97 | /Location-Aware-IM/limit.cpp | ecb5c933c76926e025227e4e0f7d836f19915252 | [] | no_license | TsinghuaDatabaseGroup/SocialInfluenceMaximization | 9f07241afdf10d350c387c2b5832e07645538440 | 68824561f616468dd5d3c63b6c11c811205a518b | refs/heads/master | 2021-09-02T06:21:13.423035 | 2017-12-31T00:47:54 | 2017-12-31T00:47:54 | 114,575,221 | 13 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 256 | cpp | #include <vector>
#include "limit.h"
vector<bool> Args::is_native(MAX_NODE, false);
vector<bool> Args::is_cdd(MAX_NODE, false);
int Args::MAX_QK = 5000;
int Args::MAX_CK = 5000;
int Args::MIN_CK = 10;
int Args::CACHE_RATIO = 10;
int Args::CAPACITY = 500;
| [
"liguoliang@mail.tsinghua.edu.cn"
] | liguoliang@mail.tsinghua.edu.cn |
d0ac7841f09137315a59638863caa6479b8e22be | 74a9456b605da15cbce5eefcfc22b2c049925d24 | /mimosa/fft/scwf-gen.hxx | 6e9111bd94c0531e5feb61874195eb6740aa7979 | [
"MIT"
] | permissive | abique/mimosa | 195ae693e2270fbfe9129b95b981946fab780d4e | 87fff4dfce5f5a792bd7b93db3f3337e477aae76 | refs/heads/master | 2022-06-30T16:32:55.355008 | 2022-06-07T11:38:47 | 2022-06-07T11:38:47 | 2,087,313 | 27 | 8 | MIT | 2018-01-16T07:20:04 | 2011-07-22T05:40:03 | C++ | UTF-8 | C++ | false | false | 1,410 | hxx | #pragma once
#include "scwf-gen.hh"
namespace mimosa {
namespace fft {
template <typename fp_type, int len>
void generateIdealSawSpectrum(fp_type *spectrum)
{
static_assert(len & (len - 1) == 0, "len is a power of 2");
static_assert(len >= 4, "len must be greater or equal to 4");
for (int i = 0; i < len; i += 4)
{
spectrum[i] = 1;
spectrum[i + 1] = 0;
spectrum[i + 2] = 0;
spectrum[i + 3] = 0;
}
}
template <typename fp_type, int len>
void generateIdealSawSignal(fp_type *signal)
{
static_assert(len & (len - 1) == 0, "len is a power of 2");
fp_type spectrum[len];
generatePerfectSquareSpectrum<fp_type, len>(spectrum);
ifft<fp_type, len>(spectrum, signal);
}
template <typename fp_type, int len>
void generateIdealSquareSpectrum(fp_type *spectrum)
{
static_assert(len & (len - 1) == 0, "len is a power of 2");
static_assert(len >= 4, "len must be greater or equal to 4");
for (int i = 0; i < len; i += 4)
{
spectrum[i] = 1;
spectrum[i + 1] = 0;
spectrum[i + 2] = 0;
spectrum[i + 3] = 0;
}
}
template <typename fp_type, int len>
void generateIdealSquareSignal(fp_type *signal)
{
static_assert(len & (len - 1) == 0, "len is a power of 2");
fp_type spectrum[len];
generatePerfectSquareSpectrum<fp_type, len>(spectrum);
ifft<fp_type, len>(spectrum, signal);
}
}
}
| [
"bique.alexandre@gmail.com"
] | bique.alexandre@gmail.com |
4fa0fe5910b5816de06624c47c5d26cb0e1fa7e2 | af28900bba69ae238baf6851ccc2ab2ca8978c75 | /Polymorphic Malware/Polymorphic_Engine.cpp | 72689da65df9be3aaef47420f9873c3f48b7f684 | [] | no_license | tmd2018/Polymorphic-Engine- | dcdc4acf75615b114045201ba4c8c455de7140a3 | 3061c3af63d8f86b4862fd96204da9db8096249e | refs/heads/master | 2020-05-31T21:28:12.040614 | 2017-05-12T15:33:50 | 2017-05-12T15:33:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,233 | cpp | // Calc.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <string>
#include <cctype>
#include <sstream>
#include<fstream>
#include<ostream>
using namespace std;
void Encrypt(string&, int key);
string Decrypt(string strTarget, int key);
string preObfuscation(string line);
string insert_assembly(string s);
string scrambler(string s);
int main(int argc, char* argv[]) {
//float add = addition(1.3,3.4);
string line,payload,strTarget;
int iSecret, iGuess, iSeed;
//payload = "Payload.cpp";
while(1)
{
cout<<"Enter a to encrypt or b run, c to exit";
char ch;
cin>>ch;
switch(ch)
{
case 'a' :
{
cin>>payload;
ifstream myfile_in(payload.c_str());
//ofstream myfile_out ("Pay.cpp");
/* initialize random seed: */
iSeed = time(NULL);
srand(iSeed);
/* generate secret number between 1 and 10: */
iSecret = rand() % 10 + 1;
//stringstream ss;
//ss<<iSecret;
//strTarget+=string(ss.str())+'\n';
Label:
if (myfile_in.is_open() )
{
while ( getline (myfile_in,line) )
{
strTarget+= preObfuscation(line) + '\n';
}
}
strTarget+="EOF \n";
ifstream assembly_functions("assembly_functions.h");
if (assembly_functions.is_open() )
{
string lin1;
while ( getline (assembly_functions,lin1) )
{
strTarget+= lin1+'\n';
}
}
strTarget = insert_assembly(strTarget);
Encrypt(strTarget, iSecret);
ofstream myfile_out("resource.h");
myfile_out<<strTarget;
ofstream myfile_out1("testing.cpp");
myfile_out1<<Decrypt(strTarget,iSecret);
cout<<"File Encrypted!! Check testing.cpp";
break;
}
case 'b' :
{
ofstream fileout("Payload.cpp");
if(fileout.is_open())
{
fileout<<Decrypt(strTarget,iSecret);
}
cout<<Decrypt(strTarget,iSecret);
break;
}
case 'c' :
{
return 0;
}
}
}
//cout << "Encrypted: " << strTarget << endl;
//cout << "Decrypted: " << Decrypt(strTarget,iSecret) << endl;
return 0;
}
void Encrypt(string &strTarget, int key)
{
int len = strTarget.length();
char a;
string strFinal(strTarget);
for (int i = 0; i <= (len-1); i++)
{
a = strTarget.at(i);
int b = (int)a; //get the ASCII value of 'a'
b += key; //Mulitply the ASCII value by 2
if (b > 254) { b = 254; }
a = (char)b; //Set the new ASCII value back into the char
strFinal.insert(i , 1, a); //Insert the new Character back into the string
}
string strEncrypted(strFinal, 0, len);
strTarget = strEncrypted;
}
string Decrypt(string strTarget, int key)
{
int len = strTarget.length();
char a;
string strFinal(strTarget);
for (int i = 0; i <= (len-1); i++)
{
a = strTarget.at(i);
int b = (int)a;
b -= key;
a = (char)b;
strFinal.insert(i, 1, a);
}
string strDecrypted(strFinal, 0, len);
return strDecrypted;
}
string preObfuscation(string line)
{
string newLine;
if(line.find("main()")!=string::npos)
{
newLine+="void addition(float arg1, float arg2); \n void subtraction(float arg1, float arg2); \n void multiplication(float arg1, float arg2); \n void division(float arg1, float arg2); \n"+line + '\n';
}
else if(line.find("for")!=string::npos)
{
newLine="//for loop \n"+line;
}
else if(line.find("while")!=string::npos)
{
newLine="//while loop \n"+line;
}
else if(line.find("if")!=string::npos)
{
newLine="//condition \n"+line;
}
else if(line.find("}")!=string::npos)
{
newLine="//end of loop or block \n"+line;
}
else if(line.find("{")!=string::npos)
{
newLine=line+"//begin of loop or block \n";
}
else
{
newLine = line;
}
return newLine;
}
string insert_assembly(string s)
{
stringstream ss(s.c_str());
ostringstream ss1;
string line,newString;
int i=0;
bool flag = false;
int iSeed;
int loop = 0;
int j=0;
if(ss!=NULL)
{
while(getline(ss,line))
{
if(line.find("}")!=string::npos && flag==true)
{
i--;
if(i<1)
{
flag=false;
}
}
if(line.find("main")!=string::npos)
{
flag=true;
newString+=line+'\n';
continue;
}
else if(line.find("{")!=string::npos)
{
i++;
newString+=line+'\n';
continue;
}
else if(line.find("if")!=string::npos||line.find("for")!=string::npos||line.find("while")!=string::npos)
{
loop++;
newString+=line+'\n';
continue;
}
else if(line.find("EOF")!=string::npos)
{
flag=false;
}
else if(i>0&&flag==true)
{
if(loop==0||line.find("condition")!=string::npos)
{
/*float arg1 = rand()/rand();
float arg2 = rand()/rand();
ss1<<arg1<<","<<arg2;*/
switch((j%4)+1)
{
case 1:
newString+="addition(4.5,9.5);" + line+'\n';
break;
case 2:
newString+="subtraction(9.5,4.5);" + line+'\n';
break;
case 3:
newString+="multiplication(9,4.5);"+line+'\n';
break;
case 4:
newString+="division(9,4.5);"+line+'\n';
break;
default:
newString+=line+'\n';
}
}
else
{
newString+=line+'\n';
if(loop>0)
{
loop--;
}
}
}
else
{
newString+=line+'\n';
}
}
return newString;
}
}
string insert_labels(string s)
{
stringstream ss(s.c_str());
ostringstream ss1;
string line,newString;
int i=0;
bool flag = false;
int iSeed;
int loop = 0;
int j=0;
if(ss!=NULL)
{
while(getline(ss,line))
{
if(line.find("}")!=string::npos && flag==true)
{
i--;
if(i<1)
{
flag=false;
}
}
if(line.find("main")!=string::npos)
{
flag=true;
newString+=line+'\n';
continue;
}
else if(line.find("{")!=string::npos)
{
i++;
newString+=line+'\n';
continue;
}
else if(line.find("if")!=string::npos||line.find("for")!=string::npos||line.find("while")!=string::npos)
{
loop++;
newString+=line+'\n';
continue;
}
else if(line.find("EOF")!=string::npos)
{
flag=false;
}
else if(i>0&&flag==true)
{
if(loop==0||line.find("condition")!=string::npos)
{
/*float arg1 = rand()/rand();
float arg2 = rand()/rand();
ss1<<arg1<<","<<arg2;*/
switch((j%4)+1)
{
case 1:
newString+="addition(4.5,9.5);" + line+'\n';
break;
case 2:
newString+="subtraction(9.5,4.5);" + line+'\n';
break;
case 3:
newString+="multiplication(9,4.5);"+line+'\n';
break;
case 4:
newString+="division(9,4.5);"+line+'\n';
break;
default:
newString+=line+'\n';
}
}
else
{
newString+=line+'\n';
if(loop>0)
{
loop--;
}
}
}
else
{
newString+=line+'\n';
}
}
return newString;
}
}
string scrambler(string s)
{
stringstream ss(s.c_str());
ostringstream ss1;
string line,newString;
int i=0;
bool flag = false;
int iSeed;
int loop = 0;
int j=0;
if(ss!=NULL)
{
while(getline(ss,line))
{
if(line.find("}")!=string::npos && flag==true)
{
i--;
if(i<1)
{
flag=false;
}
}
if(line.find("main")!=string::npos)
{
flag=true;
newString+=line+'\n';
continue;
}
else if(line.find("{")!=string::npos)
{
i++;
newString+=line+'\n';
continue;
}
else if(line.find("if")!=string::npos||line.find("for")!=string::npos||line.find("while")!=string::npos)
{
loop++;
newString+=line+'\n';
continue;
}
else if(line.find("EOF")!=string::npos)
{
flag=false;
}
else if(i>0&&flag==true)
{
if(loop==0||line.find("condition")!=string::npos)
{
/*float arg1 = rand()/rand();
float arg2 = rand()/rand();
ss1<<arg1<<","<<arg2;*/
switch((j%4)+1)
{
case 1:
newString+="addition(4.5,9.5);" + line+'\n';
break;
case 2:
newString+="subtraction(9.5,4.5);" + line+'\n';
break;
case 3:
newString+="multiplication(9,4.5);"+line+'\n';
break;
case 4:
newString+="division(9,4.5);"+line+'\n';
break;
default:
newString+=line+'\n';
}
}
else
{
newString+=line+'\n';
if(loop>0)
{
loop--;
}
}
}
else
{
newString+=line+'\n';
}
}
return newString;
}
}
| [
"szm0093@auburn.edu"
] | szm0093@auburn.edu |
a8fb1f58469498d423aaa78c8f3900c8c60089ed | 36995789e9fe22d629bfe1b1dc78ed4cffaa6f75 | /firmware/arduino/Board4Control/Board4Control_LCD.h | 4d69b5b067b7766b737eebe4ec7fc11e53cb0bae | [] | no_license | FBSeletronica/4ControlBoard | feff9d59391c4dc770a5bd57ca99b15be408aa23 | 83b0a4db03e59af6b45ec9177873bf5e5b04a5e5 | refs/heads/master | 2021-01-10T17:14:12.736067 | 2016-02-07T00:12:51 | 2016-02-07T00:12:51 | 45,721,579 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,123 | h | /*
this library is based on arduino LiquidyCristal library:
https://github.com/arduino/Arduino/tree/master/libraries/LiquidCrystal
*/
#ifndef Board4Control_LCD_h
#define Board4Control_LCD_h
#include <inttypes.h>
#include "Print.h"
// commands
#define LCD_CLEARDISPLAY 0x01
#define LCD_RETURNHOME 0x02
#define LCD_ENTRYMODESET 0x04
#define LCD_DISPLAYCONTROL 0x08
#define LCD_CURSORSHIFT 0x10
#define LCD_FUNCTIONSET 0x20
#define LCD_SETCGRAMADDR 0x40
#define LCD_SETDDRAMADDR 0x80
// flags for display entry mode
#define LCD_ENTRYRIGHT 0x00
#define LCD_ENTRYLEFT 0x02
#define LCD_ENTRYSHIFTINCREMENT 0x01
#define LCD_ENTRYSHIFTDECREMENT 0x00
// flags for display on/off control
#define LCD_DISPLAYON 0x04
#define LCD_DISPLAYOFF 0x00
#define LCD_CURSORON 0x02
#define LCD_CURSOROFF 0x00
#define LCD_BLINKON 0x01
#define LCD_BLINKOFF 0x00
// flags for display/cursor shift
#define LCD_DISPLAYMOVE 0x08
#define LCD_CURSORMOVE 0x00
#define LCD_MOVERIGHT 0x04
#define LCD_MOVELEFT 0x00
// flags for function set
#define LCD_8BITMODE 0x10
#define LCD_4BITMODE 0x00
#define LCD_2LINE 0x08
#define LCD_1LINE 0x00
#define LCD_5x10DOTS 0x04
#define LCD_5x8DOTS 0x00
class Board4Control_LCD : public Print {
public:
Board4Control_LCD(uint8_t rs, uint8_t enable,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
Board4Control_LCD(uint8_t rs, uint8_t rw, uint8_t enable,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
Board4Control_LCD(uint8_t rs, uint8_t rw, uint8_t enable,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
Board4Control_LCD(uint8_t rs, uint8_t enable,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3);
void init(uint8_t fourbitmode, uint8_t rs, uint8_t rw, uint8_t enable,
uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3,
uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7);
void begin(uint8_t cols, uint8_t rows, uint8_t charsize = LCD_5x8DOTS);
void clear();
void home();
void noDisplay();
void display();
void noBlink();
void blink();
void noCursor();
void cursor();
void scrollDisplayLeft();
void scrollDisplayRight();
void leftToRight();
void rightToLeft();
void autoscroll();
void noAutoscroll();
// Turn the backlight on/off
void setBacklight(uint8_t status);
void setRowOffsets(int row1, int row2, int row3, int row4);
void createChar(uint8_t, uint8_t[]);
void setCursor(uint8_t, uint8_t);
virtual size_t write(uint8_t);
void command(uint8_t);
using Print::write;
private:
void send(uint8_t, uint8_t);
void write4bits(uint8_t);
void write8bits(uint8_t);
void pulseEnable();
void configMuxPins(int mode);
uint8_t _rs_pin; // LOW: command. HIGH: character.
uint8_t _rw_pin; // LOW: write to LCD. HIGH: read from LCD.
uint8_t _enable_pin; // activated by a HIGH pulse.
uint8_t _data_pins[8];
uint8_t _displayfunction;
uint8_t _displaycontrol;
uint8_t _displaymode;
uint8_t _initialized;
uint8_t _numlines;
uint8_t _row_offsets[4];
};
extern Board4Control_LCD lcd;
#endif
| [
"fabio_souza53@hotmail.com"
] | fabio_souza53@hotmail.com |
610b16e15df3731843ef78999e985522237a8365 | 220846e017a9992e596bd1ea806d527e3aeea243 | /79_Word_Search.cpp | a5cb29e5ac66481ecfd1fe0e20310c24639cfb08 | [] | no_license | anzhe-yang/Leetcode | bfa443b7a74ddbd441348c364ee00004173ddd86 | fe9eb16136035f25f31bddb37c6b4884cd7f6904 | refs/heads/master | 2020-04-08T14:49:04.781848 | 2019-10-25T02:39:22 | 2019-10-25T02:39:22 | 159,453,173 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,894 | cpp | /** 问题描述:
* 给定一个 2D 的字母数组,返回单词是否存在于这个数组中。
* 该单词可以由顺序相邻的单元的字母构成,其中“相邻”单元是水平或垂直相邻的单元。
* 相同的字母单元格不得多次使用。
*/
#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool exist(vector<vector<char>>& board, string word, int x, int y, int pos, int m, int n, int len)
{
char cur = board[x][y];
bool res = false;
if (cur != word[pos])
return false;
if (pos == len-1)
return true;
board[x][y] = '*';
if(x > 0) res = exist(board, word, x-1, y, pos+1, m, n, len);
if(!res && x < m-1) res = exist(board, word, x+1, y, pos+1, m, n, len);
if(!res && y > 0) res = exist(board, word, x, y-1, pos+1, m, n, len);
if(!res && y < n-1) res = exist(board, word, x, y+1, pos+1, m, n, len);
board[x][y] = cur;
return res;
}
bool exist(vector<vector<char>>& board, string word)
{
/*
回溯法。
首先找到第一个词,之后利用循环函数验证每个词cur是否等于word[pos]。
之后分别从左、右、上、下四个位置找下一个词。
都找到了,则pos=len-1,则返回。
有一个没找到就返回false。
*/
int m = board.size();
int n = board[0].size();
int len = word.length();
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
if (exist(board, word, i, j, 0, m, n, len))
{
return true;
}
}
}
return false;
}
int main(int argc, char const *argv[])
{
vector<vector<char>> board{
{'A','B','C','E'},
{'S','F','C','S'},
{'A','D','E','E'}
};
string word = "ABCCED";
cout << boolalpha << exist(board, word);
return 0;
}
| [
"anzhe_yang@yanganzhedeMacBook-Pro.local"
] | anzhe_yang@yanganzhedeMacBook-Pro.local |
92fde826bf54f34327539f61af4972bf3d8bb83b | 560b0fe26827a16eb6ffd16f5b5e3e28844158ba | /cpp/core/mailiverse/mail/cache/Info.cpp | c5b553195b4d17fd6ac2461e1de6890a08e46d95 | [] | no_license | timprepscius/mailiverse | 855e76b4d685305e426e6db9f97d15d8e86cf4c3 | 9c7fe87d9723aa81015598a29b4fe1bb61e226ac | refs/heads/master | 2021-01-15T14:29:07.506168 | 2014-01-19T20:11:13 | 2014-01-19T20:11:13 | 11,405,168 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 243 | cpp | /**
* Author: Timothy Prepscius
* License: BSD + keep my name in the code!
*/
#include "Info.h"
using namespace mailiverse::mail::cache;
Info::Info() :
cacheVersion(Version::NONE),
localVersion(Version::NONE)
{
}
Info::~Info()
{
}
| [
"tprepscius"
] | tprepscius |
22e017201d1cf23d831732fe07a83214bcaf4f3b | ae4d9cf742b9f6e5024bcd5bdf4b4473558da9e3 | /_PSmine/PS모음/boj/10992.cpp | ec396174b0a36e044be133e44dd64881de9bc486 | [] | no_license | son0179/ttt | b6d171141e0b7894258cfb367023de62cdc9dd19 | a5153b0170c0df156c96d9be85b21d73f1f2e21e | refs/heads/master | 2023-02-09T22:01:57.658467 | 2021-01-05T09:14:52 | 2021-01-05T09:14:52 | 200,059,589 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 377 | cpp | #include<stdio.h>
int main() {
int n,a,b;
scanf("%d",&n);
if(n==1) {
printf("*");
} else {
for(int i=1; i<n; i++) {
a=1;
b=1;
while(a<=n-i) {
printf(" ");
a++;
}
printf("*");
if(i!=1) {
while(b<=(i-1)*2-1) {
printf(" ");
b++;
}
printf("*");
}
printf("\n");
}
for(int i=1; i<n*2; i++) {
printf("*");
}
}
}
| [
"starson2648@gmail.com"
] | starson2648@gmail.com |
6789f7991ce38c5d29f8d123ee2128dd61fffef0 | cfcfb3502a0f2ebc4e1c5da3eb75336eda331146 | /Praktikum Pemograman 2/modul 6/lisitng_1.cpp | e09351f406d5af4842840c974c5ca77eeee25358 | [] | no_license | fadhilelrizanda/c-code | f5f05c8bbe31e1fd91acad034b721ce99a222cf4 | 9e67666b4c4144fac7205ceb89aa49f0498e570e | refs/heads/master | 2023-01-31T07:46:59.679251 | 2020-12-10T03:43:38 | 2020-12-10T03:43:38 | 282,821,800 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,101 | cpp | #include <iostream>
using namespace std;
class Rectangle
{
public:
int *length, *width;
public:
Rectangle(int a, int b)
{
length = new int;
width = new int;
*length = a;
*width = b;
}
int arectangle()
{
return (*length * *width);
}
~Rectangle()
{
cout << "\nThe result before destructor executed is : " << (*length * *width) << endl;
cout
<< "The address of length is : "
<< &length
<< endl;
cout << "The address of width is : " << &width << endl
<< endl;
system("pause");
delete length;
delete width;
cout << "\nThe result after destructor executed is : " << (*length * *width) << endl;
cout << "The address of length is : " << &length << endl;
cout << "The address of width is : " << &width << endl
<< endl;
system("pause");
}
};
int main()
{
Rectangle square1(3, 4);
cout << "The rectangle of the square1 is : " << square1.arectangle() << endl
<< endl;
} | [
"fadhilelrizanda@gmail.com"
] | fadhilelrizanda@gmail.com |
a22961755da4ae0d5a9e4bfac99a54b456ee68a8 | 810d3856f8c1bb5364ea20917690a8f3b5e83e66 | /c_cpp/dev/ALGO-184/contest_9_A.cpp | 4f98d7befeb42e2354b1286870ba4a7c36aa0904 | [] | no_license | Saber-f/code | 6c36bff79a6590bf8eb4f740cf5c403d31ddb17e | 9e8646a320d91c0019493854f879bd6aefa6521d | refs/heads/master | 2021-07-15T21:53:54.440183 | 2019-05-20T07:18:37 | 2019-05-20T07:18:37 | 129,101,087 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 274 | cpp | #include<stdio.h>
int main(void)
{
int n,m,num = 0;
scanf("%d %d",&n,&m);
for(int t,i =0; i < n; i++)
{
scanf("%d",&t);
if(t%m == 0)
num += t/m;
else
num += t/m + 1;
}
if(num % 2 == 0)
printf("%d",num /2);
else
printf("%d",(num+1)/2);
return 0;
}
| [
"735974175@qq.com"
] | 735974175@qq.com |
1264d182f0b170ab05386c58477b81f13fd376e8 | d65246568137d0f0713139b11f38838bec0185e4 | /miro/Worley.cpp | df9cf1a2a9c8856f837f12948e5f2ed4676490aa | [] | no_license | rayyada/CSE168PA2 | 4cd2e5c1e7702f3db56fe9e266e9afdc460aee78 | 3cbe06486931f981c73c6cdc0b098dc7b92e5282 | refs/heads/master | 2021-01-01T03:54:17.446239 | 2016-05-19T03:58:00 | 2016-05-19T03:58:00 | 58,539,262 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,583 | cpp | #include "Worley.h"
#include "Material.h"
#include <math.h>
// private helper functions
namespace
{
// A hardwired lookup table to quickly determine how many feature
// points should be in each spatial cube. We use a table so we don't
// need to make multiple slower tests. A random number indexed into
// this array will give an approximate Poisson distribution of mean
// density 2.5. Read the book for the longwinded explanation.
static int poissonCount[256] =
{
4,3,1,1,1,2,4,2,2,2,5,1,0,2,1,2,2,0,4,3,2,1,2,1,3,2,2,4,2,2,5,1,2,3,2,2,2,2,2,3,
2,4,2,5,3,2,2,2,5,3,3,5,2,1,3,3,4,4,2,3,0,4,2,2,2,1,3,2,2,2,3,3,3,1,2,0,2,1,1,2,
2,2,2,5,3,2,3,2,3,2,2,1,0,2,1,1,2,1,2,2,1,3,4,2,2,2,5,4,2,4,2,2,5,4,3,2,2,5,4,3,
3,3,5,2,2,2,2,2,3,1,1,4,2,1,3,3,4,3,2,4,3,3,3,4,5,1,4,2,4,3,1,2,3,5,3,2,1,3,1,3,
3,3,2,3,1,5,5,4,2,2,4,1,3,4,1,5,3,3,5,3,4,3,2,2,1,1,1,1,1,2,4,5,4,5,4,2,1,5,1,1,
2,3,3,3,2,5,2,3,3,2,0,2,1,1,4,2,1,3,2,1,2,2,3,2,5,5,3,4,5,5,2,4,4,5,3,2,2,2,1,4,
2,3,3,4,2,5,4,2,4,2,2,2,4,5,3,2
};
// This constant is manipulated to make sure that the mean value of F[0]
// is 1.0. This makes an easy natural "scale" size of the cellular features.
#define DENSITY_ADJUSTMENT 0.398150
// the function to merge-sort a "cube" of samples into the current best-found
// list of values.
void addSamples(long xi, long maxOrder,
float at, float *F, float(*delta), unsigned long *ID);
void addSamples(long xi, long yi, long maxOrder,
float at[2], float *F, float(*delta)[2], unsigned long *ID);
void addSamples(long xi, long yi, long zi, long maxOrder,
float at[3], float *F, float(*delta)[3], unsigned long *ID);
} // namespace
void
WorleyNoise::noise1D(float at, long maxOrder,
float *F, float(*delta), unsigned long *ID)
{
float x2, mx2;
float newAt;
long intAt, i;
// Initialize the F values to "huge" so they will be replaced by the
// first real sample tests. Note we'll be storing and comparing the
// SQUARED distance from the feature points to avoid lots of slow
// sqrt() calls. We'll use sqrt() only on the final answer.
for (i = 0; i < maxOrder; i++) F[i] = 999999.9;
// Make our own local copy, multiplying to make mean(F[0])==1.0
newAt = DENSITY_ADJUSTMENT * at;
// Find the integer cube holding the hit point
intAt = int(floor(newAt));
// A simple way to compute the closest neighbors would be to test all
// boundary cubes exhaustively. This is simple with code like:
// {
// long ii, jj, kk;
// for (ii=-1; ii<=1; ii++)
// addSamples(intAt+ii, maxOrder, newAt, F, delta, ID);
// }
// But this wastes a lot of time working on cubes which are known to be
// too far away to matter! So we can use a more complex testing method
// that avoids this needless testing of distant cubes. This doubles the
// speed of the algorithm.
// Test the central cube for closest point(s).
addSamples(intAt, maxOrder, newAt, F, delta, ID);
// We test if neighbor cubes are even POSSIBLE contributors by examining the
// combinations of the sum of the squared distances from the cube's lower
// or upper corners.
x2 = newAt - intAt;
mx2 = (1.0f - x2) * (1.0f - x2);
x2 *= x2;
// Test 2 facing neighbors of center cube.
if (x2 < F[maxOrder-1]) addSamples(intAt - 1, maxOrder, newAt, F, delta, ID);
if (mx2 < F[maxOrder-1]) addSamples(intAt + 1, maxOrder, newAt, F, delta, ID);
// We're done! Convert everything to right size scale
for (i = 0; i < maxOrder; i++)
{
F[i] = sqrt(F[i]) * (1.0 / DENSITY_ADJUSTMENT);
delta[i] *= (1.0 / DENSITY_ADJUSTMENT);
}
}
void
WorleyNoise::noise2D(float at[2], long maxOrder,
float *F, float(*delta)[2], unsigned long *ID)
{
float x2, y2, mx2, my2;
float newAt[2];
long intAt[2], i;
// Initialize the F values to "huge" so they will be replaced by the
// first real sample tests. Note we'll be storing and comparing the
// SQUARED distance from the feature points to avoid lots of slow
// sqrt() calls. We'll use sqrt() only on the final answer.
for (i = 0; i < maxOrder; i++) F[i] = 999999.9;
// Make our own local copy, multiplying to make mean(F[0])==1.0
newAt[0] = DENSITY_ADJUSTMENT * at[0];
newAt[1] = DENSITY_ADJUSTMENT * at[1];
// Find the integer cube holding the hit point
intAt[0] = int(floor(newAt[0]));
intAt[1] = int(floor(newAt[1]));
// A simple way to compute the closest neighbors would be to test all
// boundary cubes exhaustively. This is simple with code like:
// {
// long ii, jj, kk;
// for (ii=-1; ii<=1; ii++) for (jj=-1; jj<=1; jj++)
// addSamples(intAt[0]+ii, intAt[1]+jj, maxOrder, newAt, F, delta, ID);
// }
// But this wastes a lot of time working on cubes which are known to be
// too far away to matter! So we can use a more complex testing method
// that avoids this needless testing of distant cubes. This doubles the
// speed of the algorithm.
// Test the central cube for closest point(s).
addSamples(intAt[0], intAt[1], maxOrder, newAt, F, delta, ID);
// We test if neighbor cubes are even POSSIBLE contributors by examining the
// combinations of the sum of the squared distances from the cube's lower
// or upper corners.
x2 = newAt[0] - intAt[0];
y2 = newAt[1] - intAt[1];
mx2 = (1.0 - x2) * (1.0 - x2);
my2 = (1.0 - y2) * (1.0 - y2);
x2 *= x2;
y2 *= y2;
// Test 4 facing neighbors of center cube. These are closest and most
// likely to have a close feature point.
if (x2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] ,
maxOrder, newAt, F, delta, ID);
if (y2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] - 1,
maxOrder, newAt, F, delta, ID);
if (mx2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] ,
maxOrder, newAt, F, delta, ID);
if (my2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] + 1,
maxOrder, newAt, F, delta, ID);
// Test 4 "edge cube" neighbors if necessary. They're next closest.
if (x2 + y2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] - 1,
maxOrder, newAt, F, delta, ID);
if (mx2 + my2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] + 1,
maxOrder, newAt, F, delta, ID);
if (x2 + my2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] + 1,
maxOrder, newAt, F, delta, ID);
if (mx2 + y2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] - 1,
maxOrder, newAt, F, delta, ID);
// We're done! Convert everything to right size scale
for (i = 0; i < maxOrder; i++)
{
F[i] = sqrt(F[i]) * (1.0 / DENSITY_ADJUSTMENT);
delta[i][0] *= (1.0 / DENSITY_ADJUSTMENT);
delta[i][1] *= (1.0 / DENSITY_ADJUSTMENT);
}
}
void
WorleyNoise::noise3D(float at[3], long maxOrder,
float *F, float(*delta)[3], unsigned long *ID)
{
float x2, y2, z2, mx2, my2, mz2;
float newAt[3];
long intAt[3], i;
// Initialize the F values to "huge" so they will be replaced by the
// first real sample tests. Note we'll be storing and comparing the
// SQUARED distance from the feature points to avoid lots of slow
// sqrt() calls. We'll use sqrt() only on the final answer.
for (i = 0; i < maxOrder; i++) F[i] = 999999.9;
// Make our own local copy, multiplying to make mean(F[0])==1.0
newAt[0] = DENSITY_ADJUSTMENT * at[0];
newAt[1] = DENSITY_ADJUSTMENT * at[1];
newAt[2] = DENSITY_ADJUSTMENT * at[2];
// Find the integer cube holding the hit point
intAt[0] = int(floor(newAt[0]));
intAt[1] = int(floor(newAt[1]));
intAt[2] = int(floor(newAt[2]));
// A simple way to compute the closest neighbors would be to test all
// boundary cubes exhaustively. This is simple with code like:
// {
// long ii, jj, kk;
// for (ii=-1; ii<=1; ii++) for (jj=-1; jj<=1; jj++) for (kk=-1; kk<=1; kk++)
// addSamples(intAt[0]+ii,intAt[1]+jj,intAt[2]+kk,
// maxOrder, newAt, F, delta, ID);
// }
// But this wastes a lot of time working on cubes which are known to be
// too far away to matter! So we can use a more complex testing method
// that avoids this needless testing of distant cubes. This doubles the
// speed of the algorithm.
// Test the central cube for closest point(s).
addSamples(intAt[0], intAt[1], intAt[2], maxOrder, newAt, F, delta, ID);
// We test if neighbor cubes are even POSSIBLE contributors by examining the
// combinations of the sum of the squared distances from the cube's lower
// or upper corners.
x2 = newAt[0] - intAt[0];
y2 = newAt[1] - intAt[1];
z2 = newAt[2] - intAt[2];
mx2 = (1.0 - x2) * (1.0 - x2);
my2 = (1.0 - y2) * (1.0 - y2);
mz2 = (1.0 - z2) * (1.0 - z2);
x2 *= x2;
y2 *= y2;
z2 *= z2;
// Test 6 facing neighbors of center cube. These are closest and most
// likely to have a close feature point.
if (x2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] , intAt[2] ,
maxOrder, newAt, F, delta, ID);
if (y2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] - 1, intAt[2] ,
maxOrder, newAt, F, delta, ID);
if (z2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] , intAt[2] - 1,
maxOrder, newAt, F, delta, ID);
if (mx2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] , intAt[2] ,
maxOrder, newAt, F, delta, ID);
if (my2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] + 1, intAt[2] ,
maxOrder, newAt, F, delta, ID);
if (mz2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] , intAt[2] + 1,
maxOrder, newAt, F, delta, ID);
// Test 12 "edge cube" neighbors if necessary. They're next closest.
if (x2 + y2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] - 1, intAt[2] ,
maxOrder, newAt, F, delta, ID);
if (x2 + z2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] , intAt[2] - 1,
maxOrder, newAt, F, delta, ID);
if (y2 + z2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] - 1, intAt[2] - 1,
maxOrder, newAt, F, delta, ID);
if (mx2 + my2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] + 1, intAt[2] ,
maxOrder, newAt, F, delta, ID);
if (mx2 + mz2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] , intAt[2] + 1,
maxOrder, newAt, F, delta, ID);
if (my2 + mz2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] + 1, intAt[2] + 1,
maxOrder, newAt, F, delta, ID);
if (x2 + my2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] + 1, intAt[2] ,
maxOrder, newAt, F, delta, ID);
if (x2 + mz2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] , intAt[2] + 1,
maxOrder, newAt, F, delta, ID);
if (y2 + mz2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] - 1, intAt[2] + 1,
maxOrder, newAt, F, delta, ID);
if (mx2 + y2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] - 1, intAt[2] ,
maxOrder, newAt, F, delta, ID);
if (mx2 + z2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] , intAt[2] - 1,
maxOrder, newAt, F, delta, ID);
if (my2 + z2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] + 1, intAt[2] - 1,
maxOrder, newAt, F, delta, ID);
// Final 8 "corner" cubes
if (x2 + y2 + z2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] - 1, intAt[2] - 1,
maxOrder, newAt, F, delta, ID);
if (x2 + y2 + mz2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] - 1, intAt[2] + 1,
maxOrder, newAt, F, delta, ID);
if (x2 + my2 + z2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] + 1, intAt[2] - 1,
maxOrder, newAt, F, delta, ID);
if (x2 + my2 + mz2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] + 1, intAt[2] + 1,
maxOrder, newAt, F, delta, ID);
if (mx2 + y2 + z2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] - 1, intAt[2] - 1,
maxOrder, newAt, F, delta, ID);
if (mx2 + y2 + mz2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] - 1, intAt[2] + 1,
maxOrder, newAt, F, delta, ID);
if (mx2 + my2 + z2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] + 1, intAt[2] - 1,
maxOrder, newAt, F, delta, ID);
if (mx2 + my2 + mz2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] + 1, intAt[2] + 1,
maxOrder, newAt, F, delta, ID);
// We're done! Convert everything to right size scale
for (i = 0; i < maxOrder; i++)
{
F[i] = sqrt(F[i]) * (1.0 / DENSITY_ADJUSTMENT);
delta[i][0] *= (1.0 / DENSITY_ADJUSTMENT);
delta[i][1] *= (1.0 / DENSITY_ADJUSTMENT);
delta[i][2] *= (1.0 / DENSITY_ADJUSTMENT);
}
}
// private helper functions
namespace
{
void
addSamples(long xi, long maxOrder, float at, float *F, float(*delta), unsigned long *ID)
{
float dx, fx, d2;
long count, i, j, index;
unsigned long seed, this_id;
// Each cube has a random number seed based on the cube's ID number.
// The seed might be better if it were a nonlinear hash like Perlin uses
// for noise but we do very well with this faster simple one.
// Our LCG uses Knuth-approved constants for maximal periods.
seed = 702395077 * xi;
// How many feature points are in this cube?
count = poissonCount[seed>>24]; // 256 element lookup table. Use MSB
seed = 1402024253 * seed + 586950981; // churn the seed with good Knuth LCG
for (j = 0; j < count; j++) // test and insert each point into our solution
{
this_id = seed;
seed = 1402024253 * seed + 586950981; // churn
// compute the 0..1 feature point location's XYZ
fx = (seed + 0.5) * (1.0 / 4294967296.0);
seed = 1402024253 * seed + 586950981; // churn
// delta from feature point to sample location
dx = xi + fx - at;
d2 = dx * dx; // Euclidian distance, squared
if (d2 < F[maxOrder-1]) // Is this point close enough to rememember?
{
// Insert the information into the output arrays if it's close enough.
// We use an insertion sort. No need for a binary search to find
// the appropriate index.. usually we're dealing with order 2,3,4 so
// we can just go through the list. If you were computing order 50
// (wow!!) you could get a speedup with a binary search in the sorted
// F[] list.
index = maxOrder;
while (index > 0 && d2 < F[index-1]) index--;
// We insert this new point into slot # <index>
// Bump down more distant information to make room for this new point.
for (i = maxOrder - 2; i >= index; i--)
{
F[i+1] = F[i];
ID[i+1] = ID[i];
delta[i+1] = delta[i];
}
// Insert the new point's information into the list.
F[index] = d2;
ID[index] = this_id;
delta[index] = dx;
}
}
}
void
addSamples(long xi, long yi, long maxOrder,
float at[2], float *F, float(*delta)[2], unsigned long *ID)
{
float dx, dy, fx, fy, d2;
long count, i, j, index;
unsigned long seed, this_id;
// Each cube has a random number seed based on the cube's ID number.
// The seed might be better if it were a nonlinear hash like Perlin uses
// for noise but we do very well with this faster simple one.
// Our LCG uses Knuth-approved constants for maximal periods.
seed = 702395077 * xi + 915488749 * yi;
// How many feature points are in this cube?
count = poissonCount[seed>>24]; // 256 element lookup table. Use MSB
seed = 1402024253 * seed + 586950981; // churn the seed with good Knuth LCG
for (j = 0; j < count; j++) // test and insert each point into our solution
{
this_id = seed;
seed = 1402024253 * seed + 586950981; // churn
// compute the 0..1 feature point location's XYZ
fx = (seed + 0.5) * (1.0 / 4294967296.0);
seed = 1402024253 * seed + 586950981; // churn
fy = (seed + 0.5) * (1.0 / 4294967296.0);
seed = 1402024253 * seed + 586950981; // churn
// delta from feature point to sample location
dx = xi + fx - at[0];
dy = yi + fy - at[1];
d2 = dx * dx + dy * dy; // Euclidian distance, squared
if (d2 < F[maxOrder-1]) // Is this point close enough to rememember?
{
// Insert the information into the output arrays if it's close enough.
// We use an insertion sort. No need for a binary search to find
// the appropriate index.. usually we're dealing with order 2,3,4 so
// we can just go through the list. If you were computing order 50
// (wow!!) you could get a speedup with a binary search in the sorted
// F[] list.
index = maxOrder;
while (index > 0 && d2 < F[index-1]) index--;
// We insert this new point into slot # <index>
// Bump down more distant information to make room for this new point.
for (i = maxOrder - 2; i >= index; i--)
{
F[i+1] = F[i];
ID[i+1] = ID[i];
delta[i+1][0] = delta[i][0];
delta[i+1][1] = delta[i][1];
}
// Insert the new point's information into the list.
F[index] = d2;
ID[index] = this_id;
delta[index][0] = dx;
delta[index][1] = dy;
}
}
}
void
addSamples(long xi, long yi, long zi, long maxOrder,
float at[3], float *F, float(*delta)[3], unsigned long *ID)
{
float dx, dy, dz, fx, fy, fz, d2;
long count, i, j, index;
unsigned long seed, this_id;
// Each cube has a random number seed based on the cube's ID number.
// The seed might be better if it were a nonlinear hash like Perlin uses
// for noise but we do very well with this faster simple one.
// Our LCG uses Knuth-approved constants for maximal periods.
seed = 702395077 * xi + 915488749 * yi + 2120969693 * zi;
// How many feature points are in this cube?
count = poissonCount[seed>>24]; // 256 element lookup table. Use MSB
seed = 1402024253 * seed + 586950981; // churn the seed with good Knuth LCG
for (j = 0; j < count; j++) // test and insert each point into our solution
{
this_id = seed;
seed = 1402024253 * seed + 586950981; // churn
// compute the 0..1 feature point location's XYZ
fx = (seed + 0.5) * (1.0 / 4294967296.0);
seed = 1402024253 * seed + 586950981; // churn
fy = (seed + 0.5) * (1.0 / 4294967296.0);
seed = 1402024253 * seed + 586950981; // churn
fz = (seed + 0.5) * (1.0 / 4294967296.0);
seed = 1402024253 * seed + 586950981; // churn
// delta from feature point to sample location
dx = xi + fx - at[0];
dy = yi + fy - at[1];
dz = zi + fz - at[2];
d2 = dx * dx + dy * dy + dz * dz; // Euclidian distance, squared
if (d2 < F[maxOrder-1]) // Is this point close enough to rememember?
{
// Insert the information into the output arrays if it's close enough.
// We use an insertion sort. No need for a binary search to find
// the appropriate index.. usually we're dealing with order 2,3,4 so
// we can just go through the list. If you were computing order 50
// (wow!!) you could get a speedup with a binary search in the sorted
// F[] list.
index = maxOrder;
while (index > 0 && d2 < F[index-1]) index--;
// We insert this new point into slot # <index>
// Bump down more distant information to make room for this new point.
for (i = maxOrder - 2; i >= index; i--)
{
F[i+1] = F[i];
ID[i+1] = ID[i];
delta[i+1][0] = delta[i][0];
delta[i+1][1] = delta[i][1];
delta[i+1][2] = delta[i][2];
}
// Insert the new point's information into the list.
F[index] = d2;
ID[index] = this_id;
delta[index][0] = dx;
delta[index][1] = dy;
delta[index][2] = dz;
}
}
}
} // namespace
| [
"Ray Yada"
] | Ray Yada |
5e418da066f76f779f6e83f272f1b10d6ca77cc7 | 8ed7b2cb70c6e33b01679c17d0e340f11c733520 | /learnqt5/cm/cm-lib/source/framework/command.cpp | 3716e22b02dd3f1786f86966099df0483e63ae65 | [] | no_license | saibi/qt | 6528b727bd73da82f513f2f54c067a669f394c9a | a3066b90cbc1ac6b9c82af5c75c40ce9e845f9a2 | refs/heads/master | 2022-06-26T20:08:07.960786 | 2022-06-10T06:49:28 | 2022-06-10T06:49:28 | 88,221,337 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 903 | cpp | #include "command.h"
namespace cm {
namespace framework {
class Command::Implementation
{
public:
Implementation(const QString& _iconCharacter, const QString& _description, std::function<bool()> _canExecute) : iconCharacter(_iconCharacter), description(_description), canExecute(_canExecute)
{
}
QString iconCharacter;
QString description;
std::function<bool()> canExecute;
};
Command::Command(QObject *parent, const QString &iconCharacter, const QString &description, std::function<bool ()> canExecute) : QObject(parent)
{
implementation.reset(new Implementation(iconCharacter, description, canExecute));
}
Command::~Command()
{
}
const QString& Command::iconCharacter() const
{
return implementation->iconCharacter;
}
const QString& Command::description() const
{
return implementation->description;
}
bool Command::canExecute() const
{
return implementation->canExecute();
}
}}
| [
"ymkim@huvitz.com"
] | ymkim@huvitz.com |
781647facaa7cc4d0a19fab05eb6bf4ba8737390 | a5e486f7e08ab39fc18627518dfc1da8df57f8b5 | /DroppingBalls.cpp | 3dd8c1cac33e8a59aa6a077a67358ab18336fcae | [] | no_license | Anfer2325/Estructuras-de-datos-y-algoritmos | 621aaeabd2666cdae4cfba35387363815b63892a | 57b49297d9592f8429869c2962da765b79c2a6a6 | refs/heads/master | 2020-04-23T18:18:09.648375 | 2015-02-12T21:45:00 | 2015-02-12T21:45:00 | null | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 55,221 | cpp | /*
Definición de algunas excepciones de las distintas
implementaciones de los TADs.
Estructura de Datos y Algoritmos
Facultad de Informática
Universidad Complutense de Madrid
(c) Marco Antonio Gómez Martín, 2012
*/
#ifndef __ARBOLES_H
#define __ARBOLES_H
#include <string>
#include <iosfwd>
#include <cassert>
/**
Clase de la que heredan todas las excepciones, y
que proporciona el atributo que almacena el
mensaje de error.
*/
class ExcepcionTAD {
public:
ExcepcionTAD() {}
ExcepcionTAD(const std::string &msg) : _msg(msg) {}
const std::string msg() const { return _msg; }
friend std::ostream &operator<<(std::ostream &out, const ExcepcionTAD &e);
protected:
std::string _msg;
};
inline std::ostream &operator<<(std::ostream &out, const ExcepcionTAD &e) {
out << e._msg;
return out;
}
// Macro para declarar las clases de tipo excepción
// que heredan de ExcepcionConMensaje, para ahorrar
// escribir muchas veces lo mismo...
#define DECLARA_EXCEPCION(Excepcion) \
class Excepcion : public ExcepcionTAD { \
public: \
Excepcion() {}; \
Excepcion(const std::string &msg) : ExcepcionTAD(msg) {} \
};
/**
Excepción generada por algunas operaciones de las pilas.
*/
DECLARA_EXCEPCION(EPilaVacia);
/**
Excepción generada por algunas de las operaciones de las colas.
*/
DECLARA_EXCEPCION(EColaVacia);
/**
Excepción generada por algunas operaciones de las colas dobles.
*/
DECLARA_EXCEPCION(EDColaVacia);
/**
Excepción generada por algunas operaciones de las listas.
*/
DECLARA_EXCEPCION(EListaVacia);
/**
Excepción generada por accesos incorrectos a las listas
(tanto a un número de elemento incorrecto como por
mal manejo de los iteradores).
*/
DECLARA_EXCEPCION(EAccesoInvalido);
/**
Excepción generada por algunas operaciones de los
árboles binarios.
*/
DECLARA_EXCEPCION(EArbolVacio);
/**
Excepción generada por algunas operaciones de los
árboles de búsqueda.
*/
DECLARA_EXCEPCION(EClaveErronea);
/**
@file Lista.h
Implementación del TAD lista, utilizando una
lista doblemente enlazada.
Estructura de Datos y Algoritmos
Facultad de Informática
Universidad Complutense de Madrid
(c) Marco Antonio Gómez Martín, 2012
*/
/**
Implementación del TAD Pila utilizando vectores dinámicos.
Las operaciones son:
- ListaVacia: -> Lista. Generadora implementada en el
constructor sin parámetros.
- Cons: Lista, Elem -> Lista. Generadora.
- ponDr: Lista, Elem -> Lista. Modificadora.
- primero: Lista - -> Elem. Observadora parcial
- resto: Lista - -> Lista. Modificadora parcial
- ultimo: Lista - -> Elem. Observadora parcial
- inicio: Lista - -> Lista. Modificadora parcial
- esVacia: Lista -> Bool. Observadora
- numElems: Lista -> Elem. Obervadora.
- elem: Lista, Entero - -> Elem. Observador parcial.
@author Marco Antonio Gómez Martín
*/
template <class T>
class Lista {
private:
/**
Clase nodo que almacena internamente el elemento (de tipo T),
y dos punteros, uno al nodo anterior y otro al nodo siguiente.
Ambos punteros podrían ser NULL si el nodo es el primero
y/o último de la lista enlazada.
*/
class Nodo {
public:
Nodo() : _sig(NULL), _ant(NULL) {}
Nodo(const T &elem) : _elem(elem), _sig(NULL), _ant(NULL) {}
Nodo(Nodo *ant, const T &elem, Nodo *sig) :
_elem(elem), _sig(sig), _ant(ant) {}
T _elem;
Nodo *_sig;
Nodo *_ant;
};
public:
/** Constructor; operación ListaVacia. */
Lista() : _prim(NULL), _ult(NULL), _numElems(0) {}
/** Destructor; elimina la lista doblemente enlazada. */
~Lista() {
libera();
}
/**
Añade un nuevo elemento en la cabeza de la lista.
Operación generadora.
@param elem Elemento que se añade en la cabecera de
la lista.
*/
void Cons(const T &elem) {
_numElems++;
_prim = insertaElem(elem, NULL, _prim);
if (_ult == NULL)
_ult = _prim;
}
/**
Añade un nuevo elemento al final de la lista (a la
"derecha"). Operación modificadora.
ponDr(e, ListaVacia) = Cons(e, ListaVacia)
ponDr(e, Cons(x, xs)) = Cons(x, ponDr(e, xs))
*/
void ponDr(const T &elem) {
_numElems++;
_ult = insertaElem(elem, _ult, NULL);
if (_prim == NULL)
_prim = _ult;
}
/**
Devuelve el valor almacenado en la cabecera de la
lista. Es un error preguntar por el primero de
una lista vacía.
primero(Cons(x, xs)) = x
error primero(ListaVacia)
@return Elemento en la cabecera de la lista.
*/
const T &primero() const {
if (esVacia())
throw EListaVacia();
return _prim->_elem;
}
/**
Devuelve el valor almacenado en la última posición
de la lista (a la derecha).
Es un error preguntar por el primero de una lista vacía.
ultimo(Cons(x, xs)) = x SI esVacia(xs)
ultimo(Cons(x, xs)) = ultimo(xs) SI !esVacia(xs)
error ultimo(ListaVacia)
@return Elemento en la cola de la lista.
*/
const T &ultimo() const {
if (esVacia())
throw EListaVacia();
return _ult->_elem;
}
/**
Elimina el primer elemento de la lista.
Es un error intentar obtener el resto de una lista vacía.
resto(Cons(x, xs)) = xs
error resto(ListaVacia)
*/
void resto() {
if (esVacia())
throw EListaVacia();
Nodo *aBorrar = _prim;
_prim = _prim->_sig;
borraElem(aBorrar);
if (_prim == NULL)
_ult = NULL;
--_numElems;
}
/**
Elimina el último elemento de la lista.
Es un error intentar obtener el inicio de una lista vacía.
inicio(Cons(x, ListaVacia)) = ListaVacia
inicio(Cons(x, xs)) = Cons(x, inicio(xs)) SI !esVacia(xs)
error inicio(ListaVacia)
*/
void inicio() {
if (esVacia())
throw EListaVacia();
Nodo *aBorrar = _ult;
_ult = _ult->_ant;
borraElem(aBorrar);
if (_ult == NULL)
_prim = NULL;
--_numElems;
}
/**
Operación observadora para saber si una lista
tiene o no elementos.
esVacia(ListaVacia) = true
esVacia(Cons(x, xs)) = false
@return true si la lista no tiene elementos.
*/
bool esVacia() const {
return _prim == NULL;
}
/**
Devuelve el número de elementos que hay en la
lista.
numElems(ListaVacia) = 0
numElems(Cons(x, xs)) = 1 + numElems(xs)
@return Número de elementos.
*/
unsigned int numElems() const {
return _numElems;
}
/**
Devuelve el elemento i-ésimo de la lista, teniendo
en cuenta que el primer elemento (primero())
es el elemento 0 y el último es numElems()-1,
es decir idx está en [0..numElems()-1].
Operación observadora parcial que puede fallar
si se da un índice incorrecto. El índice es
entero sin signo, para evitar que se puedan
pedir elementos negativos.
elem(0, Cons(x, xs)) = x
elem(n, Cons(x, xs)) = elem(n-1, xs) si n > 0
error elem(n, xs) si !( 0 <= n < numElems(xs) )
*/
const T &elem(unsigned int idx) const {
if (idx >= _numElems)
throw EAccesoInvalido();
Nodo *aux = _prim;
for (int i = 0; i < idx; ++i)
aux = aux->_sig;
return aux->_elem;
}
/**
Clase interna que implementa un iterador sobre
la lista que permite recorrer la lista e incluso
alterar el valor de sus elementos.
*/
class Iterador {
public:
void avanza() {
if (_act == NULL) throw EAccesoInvalido();
_act = _act->_sig;
}
const T &elem() const {
if (_act == NULL) throw EAccesoInvalido();
return _act->_elem;
}
void pon(const T &elem) {
if (_act == NULL) throw EAccesoInvalido();
_act->_elem = elem;
}
bool operator==(const Iterador &other) const {
return _act == other._act;
}
bool operator!=(const Iterador &other) const {
return !(this->operator==(other));
}
protected:
// Para que pueda construir objetos del
// tipo iterador
friend class Lista;
Iterador() : _act(NULL) {}
Iterador(Nodo *act) : _act(act) {}
// Puntero al nodo actual del recorrido
Nodo *_act;
};
/**
Devuelve el iterador al principio de la lista.
@return iterador al principio de la lista;
coincidirá con final() si la lista está vacía.
*/
Iterador principio() {
return Iterador(_prim);
}
/**
@return Devuelve un iterador al final del recorrido
(fuera de éste).
*/
Iterador final() const {
return Iterador(NULL);
}
/**
Permite eliminar de la lista el elemento
apuntado por el iterador que se pasa como parámetro.
El iterador recibido DEJA DE SER VÁLIDO. En su
lugar, deberá utilizarse el iterador devuelto, que
apuntará al siguiente elemento al borrado.
@param it Iterador colocado en el elemento que se
quiere borrar.
@return Nuevo iterador colocado en el elemento siguiente
al borrado (podría coincidir con final() si el
elemento que se borró era el último de la lista).
*/
Iterador borra(const Iterador &it) {
if (it._act == NULL)
throw EAccesoInvalido();
// Cubrimos los casos especiales donde
// borramos alguno de los extremos
if (it._act == _prim) {
resto();
return Iterador(_prim);
} else if (it._act == _ult) {
inicio();
return Iterador(NULL);
} else {
// El elemento a borrar es interno a la lista.
--_numElems;
Nodo *sig = it._act->_sig;
borraElem(it._act);
return Iterador(sig);
}
}
/**
Método para insertar un elemento en la lista
en el punto marcado por el iterador. En concreto,
se añade _justo antes_ que el elemento actual. Es
decir, si it==l.primero(), el elemento insertado se
convierte en el primer elemento (y el iterador
apuntará al segundo). Si it==l.final(), el elemento
insertado será el último (e it seguirá apuntando
fuera del recorrido).
@param elem Valor del elemento a insertar.
@param it Punto en el que insertar el elemento.
*/
void insertar(const T &elem, const Iterador &it) {
// Caso especial: ¿añadir al principio?
if (_prim == it._act) {
Cons(elem);
} else
// Caso especial: ¿añadir al final?
if (it._act == NULL) {
ponDr(elem);
}
// Caso normal
else {
insertaElem(elem, it._act->_ant, it._act);
}
}
// //
// MÉTODOS DE "FONTANERÍA" DE C++ QUE HACEN VERSÁTIL
// A LA CLASE
// //
/** Constructor copia */
Lista(const Lista<T> &other) : _prim(NULL), _ult(NULL) {
copia(other);
}
/** Operador de asignación */
Lista<T> &operator=(const Lista<T> &other) {
if (this != &other) {
libera();
copia(other);
}
return *this;
}
/** Operador de comparación. */
bool operator==(const Lista<T> &rhs) const {
if (_numElems != rhs._numElems)
return false;
Nodo *p1 = _prim;
Nodo *p2 = rhs._prim;
while ((p1 != NULL) && (p2 != NULL)) {
if (p1->_elem != p2->_elem)
return false;
p1 = p1->_sig;
p2 = p2->_sig;
}
return (p1 == NULL) && (p2 == NULL);
}
bool operator!=(const Lista<T> &rhs) const {
return !(*this == rhs);
}
protected:
void libera() {
libera(_prim);
_prim = NULL;
_ult = NULL;
}
void copia(const Lista<T> &other) {
// En vez de trabajar con punteros en la inserción,
// usamos ponDr
_prim = 0;
_numElems = 0;
Nodo *act = other._prim;
while (act != NULL) {
ponDr(act->_elem);
act = act->_sig;
}
}
private:
/**
Inserta un elemento entre el nodo1 y el nodo2.
Devuelve el puntero al nodo creado.
Caso general: los dos nodos existen.
nodo1->_sig == nodo2
nodo2->_ant == nodo1
Casos especiales: alguno de los nodos no existe
nodo1 == NULL y/o nodo2 == NULL
*/
static Nodo *insertaElem(const T &e, Nodo *nodo1, Nodo *nodo2) {
Nodo *nuevo = new Nodo(nodo1, e, nodo2);
if (nodo1 != NULL)
nodo1->_sig = nuevo;
if (nodo2 != NULL)
nodo2->_ant = nuevo;
return nuevo;
}
/**
Elimina el nodo n. Si el nodo tiene nodos antes
o después, actualiza sus punteros anterior y siguiente.
Caso general: hay nodos anterior y siguiente.
Casos especiales: algunos de los nodos (anterior o siguiente
a n) no existen.
*/
static void borraElem(Nodo *n) {
assert(n != NULL);
Nodo *ant = n->_ant;
Nodo *sig = n->_sig;
if (ant != NULL)
ant->_sig = sig;
if (sig != NULL)
sig->_ant = ant;
delete n;
}
/**
Elimina todos los nodos de la lista enlazada cuyo
primer nodo se pasa como parámetro.
Se admite que el nodo sea NULL (no habrá nada que
liberar). En caso de pasarse un nodo válido,
su puntero al nodo anterior debe ser NULL (si no,
no sería el primero de la lista!).
*/
static void libera(Nodo *prim) {
assert(!prim || !prim->_ant);
while (prim != NULL) {
Nodo *aux = prim;
prim = prim->_sig;
delete aux;
}
}
// Puntero al primer y último elemento
Nodo *_prim, *_ult;
// Número de elementos (número de nodos entre _prim y _ult)
unsigned int _numElems;
};
/**
@file Pila.h
Implementación del TAD Pila utilizando un
vector dinámico cuyo tamaño va creciendo si
es necesario.
Estructura de Datos y Algoritmos
Facultad de Informática
Universidad Complutense de Madrid
(c) Marco Antonio Gómez Martín, 2012
*/
/**
Implementación del TAD Pila utilizando vectores dinámicos.
Las operaciones son:
- PilaVacia: -> Pila. Generadora implementada en el
constructor sin parámetros.
- apila: Pila, Elem -> Pila. Generadora
- desapila: Pila - -> Pila. Modificadora parcial.
- cima: Pila - -> Elem. Observadora parcial.
- esVacia: Pila -> Bool. Observadora.
- numElems: Pila -> Entero. Observadora.
@author Marco Antonio Gómez Martín
*/
template <class T>
class Pila {
public:
/** Tamaño inicial del vector dinámico. */
enum { TAM_INICIAL = 10 };
/** Constructor; operación PilaVacia */
Pila() {
inicia();
}
/** Destructor; elimina el vector. */
~Pila() {
libera();
}
/**
Apila un elemento. Operación generadora.
@param elem Elemento a apilar.
*/
void apila(const T &elem) {
if (_numElems == _tam)
amplia();
_v[_numElems] = elem;
_numElems++;
}
/**
Desapila un elemento. Operación modificadora parcial,
que falla si la pila está vacía.
desapila(Apila(elem, p)) = p
error: desapila(PilaVacia)
*/
void desapila() {
if (esVacia())
throw EPilaVacia();
--_numElems;
}
/**
Devuelve el elemento en la cima de la pila. Operación
observadora parcial, que falla si la pila está vacía.
cima(Apila(elem, p) = elem
error: cima(PilaVacia)
@return Elemento en la cima de la pila.
*/
const T &cima() const {
if (esVacia())
throw EPilaVacia();
return _v[_numElems - 1];
}
/**
Devuelve true si la pila no tiene ningún elemento.
esVacia(PilaVacia) = true
esVacia(Apila(elem, p)) = false
@return true si la pila no tiene ningún elemento.
*/
bool esVacia() const {
return _numElems == 0;
}
/**
Devuelve el número de elementos que hay en la
pila.
numElems(PilaVacia) = 0
numElems(Apila(elem, p)) = 1 + numElems(p)
@return Número de elementos.
*/
int numElems() const {
return _numElems;
}
// //
// MÉTODOS DE "FONTANERÍA" DE C++ QUE HACEN VERSÁTIL
// A LA CLASE
// //
/** Constructor copia */
Pila(const Pila<T> &other) {
copia(other);
}
/** Operador de asignación */
Pila<T> &operator=(const Pila<T> &other) {
if (this != &other) {
libera();
copia(other);
}
return *this;
}
/** Operador de comparación. */
bool operator==(const Pila<T> &rhs) const {
if (_numElems != rhs._numElems)
return false;
for (unsigned int i = 0; i < _numElems; ++i)
if (_v[i] != rhs._v[i])
return false;
return true;
}
bool operator!=(const Pila<T> &rhs) const {
return !(*this == rhs);
}
protected:
void inicia() {
_v = new T[TAM_INICIAL];
_tam = TAM_INICIAL;
_numElems = 0;
}
void libera() {
delete []_v;
_v = NULL;
}
void copia(const Pila &other) {
_tam = other._numElems + TAM_INICIAL;
_numElems = other._numElems;
_v = new T[_tam];
for (unsigned int i = 0; i < _numElems; ++i)
_v[i] = other._v[i];
}
void amplia() {
T *viejo = _v;
_tam *= 2;
_v = new T[_tam];
for (unsigned int i = 0; i < _numElems; ++i)
_v[i] = viejo[i];
delete []viejo;
}
private:
/** Puntero al array que contiene los datos. */
T *_v;
/** Tamaño del vector _v. */
unsigned int _tam;
/** Número de elementos reales guardados. */
unsigned int _numElems;
};
/**
@file PilaLE.h
Implementación del TAD Pila utilizando una
lista enlazada de nodos.
Estructura de Datos y Algoritmos
Facultad de Informática
Universidad Complutense de Madrid
(c) Marco Antonio Gómez Martín, 2012
*/
/**
Implementación del TAD Pila utilizando vectores dinámicos.
Las operaciones son:
- PilaVacia: -> Pila. Generadora implementada en el
constructor sin parámetros.
- apila: Pila, Elem -> Pila. Generadora
- desapila: Pila - -> Pila. Modificadora parcial.
- cima: Pila - -> Elem. Observadora parcial.
- esVacia: Pila -> Bool. Observadora.
- numElems: Pila -> Entero. Observadora.
@author Marco Antonio Gómez Martín
*/
template <class T>
class PilaLE {
public:
/** Constructor; operación PilaVacia */
PilaLE() : _cima(NULL), _numElems(0) {
}
/** Destructor; elimina la lista enlazada. */
~PilaLE() {
libera();
_cima = NULL;
}
/**
Apila un elemento. Operación generadora.
@param elem Elemento a apilar.
*/
void apila(const T &elem) {
_cima = new Nodo(elem, _cima);
_numElems++;
}
/**
Desapila un elemento. Operación modificadora parcial,
que falla si la pila está vacía.
desapila(Apila(elem, p) = p
error: desapila(PilaVacia)
*/
void desapila() {
if (esVacia())
throw EPilaVacia();
Nodo *aBorrar = _cima;
_cima = _cima->_sig;
delete aBorrar;
--_numElems;
}
/**
Devuelve el elemento en la cima de la pila. Operación
observadora parcial, que falla si la pila está vacía.
cima(Apila(elem, p) = elem
error: cima(PilaVacia)
@return Elemento en la cima de la pila.
*/
const T &cima() const {
if (esVacia())
throw EPilaVacia();
return _cima->_elem;
}
/**
Devuelve true si la pila no tiene ningún elemento.
esVacia(PilaVacia) = true
esVacia(Apila(elem, p)) = false
@return true si la pila no tiene ningún elemento.
*/
bool esVacia() const {
return _cima == NULL;
}
/**
Devuelve el número de elementos que hay en la
pila.
numElems(PilaVacia) = 0
numElems(Apila(elem, p)) = 1 + numElems(p)
@return Número de elementos.
*/
int numElems() const {
return _numElems;
}
// //
// MÉTODOS DE "FONTANERÍA" DE C++ QUE HACEN VERSÁTIL
// A LA CLASE
// //
/** Constructor copia */
PilaLE(const PilaLE<T> &other) : _cima(NULL) {
copia(other);
}
/** Operador de asignación */
PilaLE<T> &operator=(const PilaLE<T> &other) {
if (this != &other) {
libera();
copia(other);
}
return *this;
}
/** Operador de comparación. */
bool operator==(const PilaLE<T> &rhs) const {
if (_numElems != rhs._numElems)
return false;
Nodo *cima1 = _cima;
Nodo *cima2 = rhs._cima;
while ((cima1 != NULL) && (cima2 != NULL)) {
if (cima1->_elem != cima2->_elem)
return false;
cima1 = cima1->_sig;
cima2 = cima2->_sig;
}
return (cima1 == NULL) && (cima2 == NULL);
}
bool operator!=(const PilaLE<T> &rhs) const {
return !(*this == rhs);
}
protected:
void libera() {
libera(_cima);
}
void copia(const PilaLE &other) {
if (other.esVacia()) {
_cima = NULL;
_numElems = 0;
} else {
Nodo *act = other._cima;
Nodo *ant;
_cima = new Nodo(act->_elem);
ant = _cima;
while (act->_sig != NULL) {
act = act->_sig;
ant->_sig = new Nodo(act->_elem);
ant = ant->_sig;
}
_numElems = other._numElems;
}
}
private:
/**
Clase nodo que almacena internamente el elemento (de tipo T),
y un puntero al nodo siguiente, que podría ser NULL si
el nodo es el último de la lista enlazada.
*/
class Nodo {
public:
Nodo() : _sig(NULL) {}
Nodo(const T &elem) : _elem(elem), _sig(NULL) {}
Nodo(const T &elem, Nodo *sig) :
_elem(elem), _sig(sig) {}
T _elem;
Nodo *_sig;
};
/**
Elimina todos los nodos de la lista enlazada cuyo
primer nodo se pasa como parámetro.
Se admite que el nodo sea NULL (no habrá nada que
liberar).
*/
static void libera(Nodo *prim) {
while (prim != NULL) {
Nodo *aux = prim;
prim = prim->_sig;
delete aux;
}
}
/** Puntero al primer elemento */
Nodo *_cima;
/** Número de elementos */
int _numElems;
};
/**
@file Cola.h
Implementación del TAD Cola utilizando una
lista enlazada de nodos.
Estructura de Datos y Algoritmos
Facultad de Informática
Universidad Complutense de Madrid
(c) Marco Antonio Gómez Martín, 2012
*/
/**
Implementación del TAD Cola utilizando una lista enlazada.
Las operaciones son:
- ColaVacia: -> Cola. Generadora implementada en el
constructor sin parámetros.
- PonDetras: Cola, Elem -> Cola. Generadora
- quitaPrim: Cola - -> Cola. Modificadora parcial.
- primero: Cola - -> Elem. Observadora parcial.
- esVacia: Cola -> Bool. Observadora.
- numElems: Cola -> Entero. Observadora.
@author Marco Antonio Gómez Martín
*/
template <class T>
class Cola {
public:
/** Constructor; operacion ColaVacia */
Cola() : _prim(NULL), _ult(NULL), _numElems(0) {
}
/** Destructor; elimina la lista enlazada. */
~Cola() {
libera();
_prim = _ult = NULL;
}
/**
Añade un elemento en la parte trasera de la cola.
Operación generadora.
@param elem Elemento a añadir.
*/
void ponDetras(const T &elem) {
Nodo *nuevo = new Nodo(elem, NULL);
if (_ult != NULL)
_ult->_sig = nuevo;
_ult = nuevo;
// Si la cola estaba vacía, el primer elemento
// es el que acabamos de añadir
if (_prim == NULL)
_prim = nuevo;
_numElems++;
}
/**
Elimina el primer elemento de la cola.
Operación modificadora parcial, que falla si
la cola está vacía.
quitaPrim(PonDetras(elem, ColaVacia)) = ColaVacia
quitaPrim(PonDetras(elem, xs)) = PonDetras(elem, quitaPrim(xs)) si !esVacia(xs)
error: quitaPrim(ColaVacia)
*/
void quitaPrim() {
if (esVacia())
throw EColaVacia();
Nodo *aBorrar = _prim;
_prim = _prim->_sig;
delete aBorrar;
--_numElems;
// Si la cola se quedó vacía, no hay
// último
if (_prim == NULL)
_ult = NULL;
}
/**
Devuelve el primer elemento de la cola. Operación
observadora parcial, que falla si la cola está vacía.
primero(PonDetras(elem, ColaVacia)) = elem
primero(PonDetras(elem, xs)) = primero(xs) si !esVacia(xs)
error: primero(ColaVacia)
@return El primer elemento de la cola.
*/
const T &primero() const {
if (esVacia())
throw EColaVacia();
return _prim->_elem;
}
/**
Devuelve true si la cola no tiene ningún elemento.
esVacia(Cola) = true
esVacia(PonDetras(elem, p)) = false
@return true si la cola no tiene ningún elemento.
*/
bool esVacia() const {
return _prim == NULL;
}
/**
Devuelve el número de elementos que hay en la
cola.
numElems(ColaVacia) = 0
numElems(PonDetras(elem, p)) = 1 + numElems(p)
@return Número de elementos.
*/
int numElems() const {
return _numElems;
}
// //
// MÉTODOS DE "FONTANERÍA" DE C++ QUE HACEN VERSÁTIL
// A LA CLASE
// //
/** Constructor copia */
Cola(const Cola<T> &other) : _prim(NULL), _ult(NULL) {
copia(other);
}
/** Operador de asignación */
Cola<T> &operator=(const Cola<T> &other) {
if (this != &other) {
libera();
copia(other);
}
return *this;
}
/** Operador de comparación. */
bool operator==(const Cola<T> &rhs) const {
if (_numElems != rhs._numElems)
return false;
Nodo *p1 = _prim;
Nodo *p2 = rhs._prim;
while ((p1 != NULL) && (p2 != NULL)) {
if (p1->_elem != p2->_elem)
return false;
p1 = p1->_sig;
p2 = p2->_sig;
}
return (p1 == NULL) && (p2 == NULL);
}
bool operator!=(const Cola<T> &rhs) const {
return !(*this == rhs);
}
protected:
void libera() {
libera(_prim);
}
void copia(const Cola &other) {
if (other.esVacia()) {
_prim = _ult = NULL;
_numElems = 0;
} else {
Nodo *act = other._prim;
Nodo *ant;
_prim = new Nodo(act->_elem);
ant = _prim;
while (act->_sig != NULL) {
act = act->_sig;
ant->_sig = new Nodo(act->_elem);
ant = ant->_sig;
}
_ult = ant;
_numElems = other._numElems;
}
}
private:
/**
Clase nodo que almacena internamente el elemento (de tipo T),
y un puntero al nodo siguiente, que podría ser NULL si
el nodo es el último de la lista enlazada.
*/
class Nodo {
public:
Nodo() : _sig(NULL) {}
Nodo(const T &elem) : _elem(elem), _sig(NULL) {}
Nodo(const T &elem, Nodo *sig) :
_elem(elem), _sig(sig) {}
T _elem;
Nodo *_sig;
};
/**
Elimina todos los nodos de la lista enlazada cuyo
primer nodo se pasa como parámetro.
Se admite que el nodo sea NULL (no habrá nada que
liberar).
*/
static void libera(Nodo *prim) {
while (prim != NULL) {
Nodo *aux = prim;
prim = prim->_sig;
delete aux;
}
}
/** Puntero al primer elemento. */
Nodo *_prim;
/** Puntero al último elemento. */
Nodo *_ult;
/** Número de elementos */
int _numElems;
};
/**
@file DCola.h
Implementación del TAD doble cola, utilizando una
lista doblemente enlazada con nodo fantasma o
cabecera.
Estructura de Datos y Algoritmos
Facultad de Informática
Universidad Complutense de Madrid
(c) Marco Antonio Gómez Martín, 2012
*/
/**
Implementación del TAD Doble Cola utilizando una lista doblemente
enlazada circular y con nodo fantasma.
Las operaciones son:
- DColaVacia: -> DCola. Generadora implementada en el
constructor sin parámetros.
- PonDetras: DCola, Elem -> DCola. Generadora
- ponDelante: DCola, Elem -> DCola. Modificadora.
- quitaPrim: DCola - -> DCola. Modificadora parcial
- primero: DCola - -> Elem. Observadora parcial
- quitaUlt: DCola - -> DCola. Modificadora parcial
- ultimo: DCola - -> Elem. Observadora parcial
- esVacia: DCola -> Bool. Observadora
@author Marco Antonio Gómez Martín
*/
template <class T>
class DCola {
public:
/** Constructor; operación DColaVacia. */
DCola() {
_fantasma = new Nodo();
_fantasma->_sig = _fantasma;
_fantasma->_ant = _fantasma;
_numElems = 0;
}
/** Destructor; elimina la lista doblemente enlazada. */
~DCola() {
libera();
}
/**
Añade un elemento por la parte de atrás de la cola.
Es una operación generadora.
*/
void ponDetras(const T &e) {
insertaElem(e, _fantasma->_ant, _fantasma);
_numElems++;
}
/**
Devuelve el primer elemento de la cola; es una operación
observadora parcial, pues es un error preguntar por
el primer elemento de una doble cola vacía.
primero(PonDetras(elem, DColaVacia)) = elem
primero(PonDetras(elem, xs)) = primero(xs) si !esVacia(xs)
error: primero(DColaVacia)
*/
const T &primero() const {
if (esVacia())
throw EDColaVacia();
return _fantasma->_sig->_elem;
}
/**
Elimina el primer elemento de la doble cola.
Operación modificadora parcial, que falla si
está vacía.
quitaPrim(PonDetras(elem, DColaVacia)) = DColaVacia
quitaPrim(PonDetras(elem, xs)) = PonDetras(elem, quitaPrim(xs)) si !esVacia(xs)
error: quitaPrim(DColaVacia)
*/
void quitaPrim() {
if (esVacia())
throw EDColaVacia();
borraElem(_fantasma->_sig);
--_numElems;
}
/**
Añade un elemento a la parte delantera de una doble cola.
Operación modificadora.
ponDelante(elem, DColaVacia) = ponDetras(elem, DColaVacia)
ponDelante(elem, ponDetras(x, xs)) =
ponDetras(x, ponDelante(elem, xs))
@param e Elemento que se añade
*/
void ponDelante(const T &e) {
insertaElem(e, _fantasma, _fantasma->_sig);
++_numElems;
}
/**
Devuelve el último elemento de la doble cola. Es
un error preguntar por el último de una doble cola vacía.
ultimo(PonDetras(x, xs)) = x
error: ultimo(DColaVacia)
@return Último elemento de la cola.
*/
const T &ultimo() const {
if (esVacia())
throw EDColaVacia();
return _fantasma->_ant->_elem;
}
/**
Elimina el último elemento de la doble cola. Es
un error quitar el último de una doble cola vacía.
quitaUlt(PonDetras(x, xs)) = xs
error: quitaUlt(DColaVacia)
*/
void quitaUlt() {
if (esVacia())
throw EDColaVacia();
borraElem(_fantasma->_ant);
--_numElems;
}
/**
Operación observadora para saber si una doble cola
tiene o no elementos.
esVacia(DColaVacia) = true
esVacia(ponDetras(x, xs)) = false
@return true si la doble cola no tiene elementos.
*/
bool esVacia() const {
return _fantasma->_sig == _fantasma;
/* return _numElems == 0; */
}
/**
Devuelve el número de elementos que hay en la
doble cola.
numElems(DColaVacia) = 0
numElems(PonDetras(elem, p)) = 1 + numElems(p)
@return Número de elementos.
*/
int numElems() const {
return _numElems;
}
// //
// MÉTODOS DE "FONTANERÍA" DE C++ QUE HACEN VERSÁTIL
// A LA CLASE
// //
/** Constructor copia */
DCola(const DCola<T> &other) : _fantasma(NULL) {
copia(other);
}
/** Operador de asignación */
DCola<T> &operator=(const DCola<T> &other) {
if (this != &other) {
libera();
copia(other);
}
return *this;
}
/** Operador de comparación. */
bool operator==(const DCola<T> &rhs) const {
if (_numElems != rhs._numElems)
return false;
Nodo *p1 = _fantasma->_sig;
Nodo *p2 = rhs._fantasma->_sig;
while ((p1 != _fantasma) && (p2 != rhs._fantasma)) {
if (p1->_elem != p2->_elem)
return false;
p1 = p1->_sig;
p2 = p2->_sig;
}
return (p1 == _fantasma) && (p2 == rhs._fantasma);
}
bool operator!=(const DCola<T> &rhs) const {
return !(*this == rhs);
}
protected:
void libera() {
// Usamos libera(nodo), pero antes quitamos
// la circularidad para evitar bucle
// infinito...
_fantasma->_ant->_sig = NULL;
_fantasma->_ant = NULL;
libera(_fantasma);
_fantasma = NULL;
}
void copia(const DCola<T> &other) {
// En vez de trabajar con punteros en la inserción,
// usamos ponDetras.
_fantasma = new Nodo();
_fantasma->_sig = _fantasma;
_fantasma->_ant = _fantasma;
_numElems = 0;
Nodo *act = other._fantasma->_sig;
while (act != other._fantasma) {
ponDetras(act->_elem);
act = act->_sig;
}
}
private:
/**
Clase nodo que almacena internamente el elemento (de tipo T),
y dos punteros, uno al nodo anterior y otro al nodo siguiente.
Ambos punteros podrían ser NULL si el nodo es el primero
y/o último de la lista enlazada.
*/
class Nodo {
public:
Nodo() : _sig(NULL) {}
Nodo(const T &elem) : _elem(elem), _sig(NULL), _ant(NULL) {}
Nodo(Nodo *ant, const T &elem, Nodo *sig) :
_elem(elem), _sig(sig), _ant(ant) {}
T _elem;
Nodo *_sig;
Nodo *_ant;
};
/**
Inserta un elemento entre el nodo1 y el nodo2.
Devuelve el puntero al nodo creado.
Caso general: los dos nodos existen.
nodo1->_sig == nodo2
nodo2->_ant == nodo1
Casos especiales: alguno de los nodos no existe
nodo1 == NULL y/o nodo2 == NULL
*/
static Nodo *insertaElem(const T &e, Nodo *nodo1, Nodo *nodo2) {
Nodo *nuevo = new Nodo(nodo1, e, nodo2);
if (nodo1 != NULL)
nodo1->_sig = nuevo;
if (nodo2 != NULL)
nodo2->_ant = nuevo;
return nuevo;
}
/**
Elimina el nodo n. Si el nodo tiene nodos antes
o después, actualiza sus punteros anterior y siguiente.
Caso general: hay nodos anterior y siguiente.
Casos especiales: algunos de los nodos (anterior o siguiente
a n) no existen.
*/
static void borraElem(Nodo *n) {
if (n == NULL)
return;
Nodo *ant = n->_ant;
Nodo *sig = n->_sig;
if (ant != NULL)
ant->_sig = sig;
if (sig != NULL)
sig->_ant = ant;
delete n;
}
/**
Elimina todos los nodos de la lista enlazada cuyo
primer nodo se pasa como parámetro.
Se admite que el nodo sea NULL (no habrá nada que
liberar). En caso de pasarse un nodo válido,
su puntero al nodo anterior debe ser NULL (si no,
no sería el primero de la lista!).
*/
static void libera(Nodo *prim) {
if (prim == NULL)
return;
assert(!prim || !prim->_ant);
while (prim != NULL) {
Nodo *aux = prim;
prim = prim->_sig;
delete aux;
}
}
// Puntero al nodo fantasma
Nodo *_fantasma;
// Número de elementos
unsigned int _numElems;
};
/**
Implementación dinámica del TAD Arbin utilizando
nodos con un puntero al hijo izquierdo y otro al
hijo derecho. La implementación permite compartición
de estructura, manteniendola bajo control mediante
conteo de referencias. La implementación, sin embargo,
es bastante artesanal, pues para no complicar el código
excesivamente no se ha hecho uso de punteros inteligentes
que incrementen y decrementen automáticamente esas
referencias.
Las operaciones son:
- ArbolVacio: -> Arbin. Generadora implementada en el
constructor sin parámetros.
- Cons: Arbin, Elem, Arbin -> Arbin. Generadora implementada
en un constructor con tres parámetros.
- hijoIz, hijoDr: Arbin - -> Arbin. Observadoras que
devuelven el hijo izquiero o derecho de un árbol.
- esVacio: Arbin -> Bool. Observadora que devuelve si
un árbol binario es vacío.
@author Marco Antonio Gómez Martín
*/
template <class T>
class Arbin {
public:
/** Constructor; operacion ArbolVacio */
Arbin() : _ra(NULL) {
}
/** Constructor; operacion Cons */
Arbin(const Arbin &iz, const T &elem, const Arbin &dr) :
_ra(new Nodo(iz._ra, elem, dr._ra)) {
_ra->addRef();
}
/** Destructor; elimina la estructura jerárquica de nodos. */
~Arbin() {
libera();
_ra = NULL;
}
/**
Devuelve el elemento almacenado en la raiz
raiz(Cons(iz, elem, dr)) = elem
error raiz(ArbolVacio)
@return Elemento en la raíz.
*/
const T &raiz() const {
if (esVacio())
throw EArbolVacio();
return _ra->_elem;
}
/**
Devuelve un árbol copia del árbol izquierdo.
Es una operación parcial (falla con el árbol vacío).
hijoIz(Cons(iz, elem, dr)) = iz
error hijoIz(ArbolVacio)
*/
Arbin hijoIz() const {
if (esVacio())
throw EArbolVacio();
return Arbin(_ra->_iz);
}
/**
Devuelve un árbol copia del árbol derecho.
Es una operación parcial (falla con el árbol vacío).
hijoDr(Cons(iz, elem, dr)) = dr
error hijoDr(ArbolVacio)
*/
Arbin hijoDr() const {
if (esVacio())
throw EArbolVacio();
return Arbin(_ra->_dr);
}
/**
Operación observadora que devuelve si el árbol
es vacío (no contiene elementos) o no.
esVacio(ArbolVacio) = true
esVacio(Cons(iz, elem, dr)) = false
*/
bool esVacio() const {
return _ra == NULL;
}
// //
// RECORRIDOS SOBRE EL ÁRBOL
// //
Lista<T> preorden() const {
Lista<T> ret;
preordenAcu(_ra, ret);
return ret;
}
Lista<T> inorden() const {
Lista<T> ret;
inordenAcu(_ra, ret);
return ret;
}
Lista<T> postorden() const {
Lista<T> ret;
postordenAcu(_ra, ret);
return ret;
}
Lista<T> niveles() const {
if (esVacio())
return Lista<T>();
Lista<T> ret;
Cola<Nodo*> porProcesar;
porProcesar.ponDetras(_ra);
while (!porProcesar.esVacia()) {
Nodo *visita = porProcesar.primero();
porProcesar.quitaPrim();
ret.ponDr(visita->_elem);
if (visita->_iz)
porProcesar.ponDetras(visita->_iz);
if (visita->_dr)
porProcesar.ponDetras(visita->_dr);
}
return ret;
}
// //
// OTRAS OPERACIONES OBSERVADORAS
// //
/**
Devuelve el número de nodos de un árbol.
*/
unsigned int numNodos() const {
return numNodosAux(_ra);
}
/**
Devuelve la talla del árbol.
*/
unsigned int talla() const {
return tallaAux(_ra);
}
/**
Devuelve el número de hojas de un árbol.
*/
unsigned int numHojas() const {
return numHojasAux(_ra);
}
// //
// MÉTODOS DE "FONTANERÍA" DE C++ QUE HACEN VERSÁTIL
// A LA CLASE
// //
/** Constructor copia */
Arbin(const Arbin<T> &other) : _ra(NULL) {
copia(other);
}
/** Operador de asignación */
Arbin<T> &operator=(const Arbin<T> &other) {
if (this != &other) {
libera();
copia(other);
}
return *this;
}
/** Operador de comparación. */
bool operator==(const Arbin<T> &rhs) const {
return comparaAux(_ra, rhs._ra);
}
bool operator!=(const Arbin<T> &rhs) const {
return !(*this == rhs);
}
protected:
/**
Clase nodo que almacena internamente el elemento (de tipo T),
y los punteros al hijo izquierdo y al hijo derecho, así
como el número de referencias que hay.
*/
class Nodo {
public:
Nodo() : _iz(NULL), _dr(NULL), _numRefs(0) {}
Nodo(Nodo *iz, const T &elem, Nodo *dr) :
_elem(elem), _iz(iz), _dr(dr), _numRefs(0) {
if (_iz != NULL)
_iz->addRef();
if (_dr != NULL)
_dr->addRef();
}
void addRef() { assert(_numRefs >= 0); _numRefs++; }
void remRef() { assert(_numRefs > 0); _numRefs--; }
T _elem;
Nodo *_iz;
Nodo *_dr;
int _numRefs;
};
/**
Constructor protegido que crea un árbol
a partir de una estructura jerárquica existente.
Esa estructura jerárquica SE COMPARTE, por lo que
se añade la referencia.
Se utiliza en hijoIz e hijoDr.
*/
Arbin(Nodo *raiz) : _ra(raiz) {
if (_ra != NULL)
_ra->addRef();
}
void libera() {
libera(_ra);
}
void copia(const Arbin &other) {
assert(this != &other);
_ra = other._ra;
if (_ra != NULL)
_ra->addRef();
}
// //
// MÉTODOS AUXILIARES PARA LOS RECORRIDOS
// //
static void preordenAcu(Nodo *ra, Lista<T> &acu) {
if (ra == NULL)
return;
acu.ponDr(ra->_elem);
preordenAcu(ra->_iz, acu);
preordenAcu(ra->_dr, acu);
}
static void inordenAcu(Nodo *ra, Lista<T> &acu) {
if (ra == NULL)
return;
inordenAcu(ra->_iz, acu);
acu.ponDr(ra->_elem);
inordenAcu(ra->_dr, acu);
}
static void postordenAcu(Nodo *ra, Lista<T> &acu) {
if (ra == NULL)
return;
postordenAcu(ra->_iz, acu);
postordenAcu(ra->_dr, acu);
acu.ponDr(ra->_elem);
}
// //
// MÉTODOS AUXILIARES (RECURSIVOS) DE OTRAS OPERACIONES
// OBSERVADORAS
// //
static unsigned int numNodosAux(Nodo *ra) {
if (ra == NULL)
return 0;
return 1 + numNodosAux(ra->_iz) + numNodosAux(ra->_dr);
}
static unsigned int tallaAux(Nodo *ra) {
if (ra == NULL)
return 0;
int tallaiz = tallaAux(ra->_iz);
int talladr = tallaAux(ra->_dr);
if (tallaiz > talladr)
return 1 + tallaiz;
else
return 1 + talladr;
}
static unsigned int numHojasAux(Nodo *ra) {
if (ra == NULL)
return 0;
if ((ra->_iz == NULL) && (ra->_dr == NULL))
return 1;
return numHojasAux(ra->_iz) + numHojasAux(ra->_dr);
}
private:
/**
Elimina todos los nodos de una estructura arbórea
que comienza con el puntero ra.
Se admite que el nodo sea NULL (no habrá nada que
liberar).
*/
static void libera(Nodo *ra) {
if (ra != NULL) {
ra->remRef();
if (ra->_numRefs == 0) {
libera(ra->_iz);
libera(ra->_dr);
delete ra;
}
}
}
/**
Compara dos estructuras jerárquicas de nodos,
dadas sus raices (que pueden ser NULL).
*/
static bool comparaAux(Nodo *r1, Nodo *r2) {
if (r1 == r2)
return true;
else if ((r1 == NULL) || (r2 == NULL))
// En el if anterior nos aseguramos de
// que r1 != r2. Si uno es NULL, el
// otro entonces no lo será, luego
// son distintos.
return false;
else {
return (r1->_elem == r2->_elem) &&
comparaAux(r1->_iz, r2->_iz) &&
comparaAux(r1->_dr, r2->_dr);
}
}
protected:
/**
Puntero a la raíz de la estructura jerárquica
de nodos.
*/
Nodo *_ra;
};
/**
@file Arbus.h
Implementación dinámica del TAD Arbol de Búsqueda.
Estructura de Datos y Algoritmos
Facultad de Informática
Universidad Complutense de Madrid
(c) Marco Antonio Gómez Martín, 2012
*/
/**
Implementación dinámica del TAD Arbus utilizando
nodos con un puntero al hijo izquierdo y otro al
hijo derecho.
Las operaciones son:
- ArbusVacio: operación generadora que construye
un árbol de búsqueda vacío.
- Inserta(clave, valor): generadora que añade una
nueva pareja (clave, valor) al árbol. Si la
clave ya estaba se sustituye el valor.
- borra(clave): operación modificadora. Elimina la
clave del árbol de búsqueda. Si la clave no está,
la operación no tiene efecto.
- consulta(clave): operación observadora que devuelve
el valor asociado a una clave. Es un error preguntar
por una clave que no existe.
- esta(clave): operación observadora. Sirve para
averiguar si se ha introducido una clave en el
árbol.
- esVacio(): operacion observadora que indica si
el árbol de búsqueda tiene alguna clave introducida.
@author Marco Antonio Gómez Martín
*/
template <class Clave, class Valor>
class Arbus {
private:
/**
Clase nodo que almacena internamente la pareja (clave, valor)
y los punteros al hijo izquierdo y al hijo derecho.
*/
class Nodo {
public:
Nodo() : _iz(NULL), _dr(NULL) {}
Nodo(const Clave &clave, const Valor &valor)
: _clave(clave), _valor(valor), _iz(NULL), _dr(NULL) {}
Nodo(Nodo *iz, const Clave &clave, const Valor &valor, Nodo *dr)
: _clave(clave), _valor(valor), _iz(iz), _dr(dr) {}
Clave _clave;
Valor _valor;
Nodo *_iz;
Nodo *_dr;
};
public:
/** Constructor; operacion ArbolVacio */
Arbus() : _ra(NULL) {
}
/** Destructor; elimina la estructura jerárquica de nodos. */
~Arbus() {
libera();
_ra = NULL;
}
/**
Operación generadora que añade una nueva clave/valor
a un árbol de búsqueda.
@param clave Clave nueva.
@param valor Valor asociado a esa clave. Si la clave
ya se había insertado previamente, sustituimos el valor
viejo por el nuevo.
*/
void inserta(const Clave &clave, const Valor &valor) {
_ra = insertaAux(clave, valor, _ra);
}
/**
Operación modificadora que elimina una clave del árbol.
Si la clave no existía la operación no tiene efecto.
borra(elem, ArbusVacio) = ArbusVacio
borra(e, inserta(c, v, arbol)) =
inserta(c, v, borra(e, arbol)) si c != e
borra(e, inserta(c, v, arbol)) = borra(e, arbol) si c == e
@param clave Clave a eliminar.
*/
void borra(const Clave &clave) {
_ra = borraAux(_ra, clave);
}
/**
Operación observadora que devuelve el valor asociado
a una clave dada.
consulta(e, inserta(c, v, arbol)) = v si e == c
consulta(e, inserta(c, v, arbol)) = consulta(e, arbol) si e != c
error consulta(ArbusVacio)
@param clave Clave por la que se pregunta.
*/
const Valor &consulta(const Clave &clave) {
Nodo *p = buscaAux(_ra, clave);
if (p == NULL)
throw EClaveErronea();
return p->_valor;
}
/**
Operación observadora que permite averiguar si una clave
determinada está o no en el árbol de búsqueda.
esta(e, ArbusVacio) = false
esta(e, inserta(c, v, arbol)) = true si e == c
esta(e, inserta(c, v, arbol)) = esta(e, arbol) si e != c
@param clave Clave por la que se pregunta.
*/
bool esta(const Clave &clave) {
return buscaAux(_ra, clave) != NULL;
}
/**
Operación observadora que devuelve si el árbol
es vacío (no contiene elementos) o no.
esVacio(ArbusVacio) = true
esVacio(inserta(c, v, arbol)) = false
*/
bool esVacio() const {
return _ra == NULL;
}
// //
// OPERACIONES RELACIONADAS CON LOS ITERADORES
// //
/**
Clase interna que implementa un iterador sobre
la lista que permite recorrer la lista e incluso
alterar el valor de sus elementos.
*/
class Iterador {
public:
void avanza() {
if (_act == NULL) throw EAccesoInvalido();
// Si hay hijo derecho, saltamos al primero
// en inorden del hijo derecho
if (_act->_dr)
_act = primeroInOrden(_act->_dr);
else {
// Si no, vamos al primer ascendiente
// no visitado. Para eso consultamos
// la pila; si ya está vacía, no quedan
// ascendientes por visitar
if (_ascendientes.esVacia())
_act = NULL;
else {
_act = _ascendientes.cima();
_ascendientes.desapila();
}
}
}
const Clave &clave() const {
if (_act == NULL) throw EAccesoInvalido();
return _act->_clave;
}
const Valor &valor() const {
if (_act == NULL) throw EAccesoInvalido();
return _act->_valor;
}
bool operator==(const Iterador &other) const {
return _act == other._act;
}
bool operator!=(const Iterador &other) const {
return !(this->operator==(other));
}
protected:
// Para que pueda construir objetos del
// tipo iterador
friend class Arbus;
Iterador() : _act(NULL) {}
Iterador(Nodo *act) {
_act = primeroInOrden(act);
}
/**
Busca el primer elemento en inorden de
la estructura jerárquica de nodos pasada
como parámetro; va apilando sus ascendientes
para poder "ir hacia atrás" cuando sea necesario.
@param p Puntero a la raíz de la subestructura.
*/
Nodo *primeroInOrden(Nodo *p) {
if (p == NULL)
return NULL;
while (p->_iz != NULL) {
_ascendientes.apila(p);
p = p->_iz;
}
return p;
}
// Puntero al nodo actual del recorrido
// NULL si hemos llegado al final.
Nodo *_act;
// Ascendientes del nodo actual
// aún por visitar
Pila<Nodo*> _ascendientes;
};
/**
Devuelve el iterador al principio de la lista.
@return iterador al principio de la lista;
coincidirá con final() si la lista está vacía.
*/
Iterador principio() {
return Iterador(_ra);
}
/**
@return Devuelve un iterador al final del recorrido
(fuera de éste).
*/
Iterador final() const {
return Iterador(NULL);
}
// //
// MÉTODOS DE "FONTANERÍA" DE C++ QUE HACEN VERSÁTIL
// A LA CLASE
// //
/** Constructor copia */
Arbus(const Arbus<Clave, Valor> &other) : _ra(NULL) {
copia(other);
}
/** Operador de asignación */
Arbus<Clave, Valor> &operator=(const Arbus<Clave, Valor> &other) {
if (this != &other) {
libera();
copia(other);
}
return *this;
}
protected:
/**
Constructor protegido que crea un árbol
a partir de una estructura jerárquica de nodos
previamente creada.
Se utiliza en hijoIz e hijoDr.
*/
Arbus(Nodo *raiz) : _ra(raiz) {
}
void libera() {
libera(_ra);
}
void copia(const Arbus &other) {
_ra = copiaAux(other._ra);
}
private:
/**
Elimina todos los nodos de una estructura arbórea
que comienza con el puntero ra.
Se admite que el nodo sea NULL (no habrá nada que
liberar).
*/
static void libera(Nodo *ra) {
if (ra != NULL) {
libera(ra->_iz);
libera(ra->_dr);
delete ra;
}
}
/**
Copia la estructura jerárquica de nodos pasada
como parámetro (puntero a su raiz) y devuelve un
puntero a una nueva estructura jerárquica, copia
de anterior (y que, por tanto, habrá que liberar).
*/
static Nodo *copiaAux(Nodo *ra) {
if (ra == NULL)
return NULL;
return new Nodo(copiaAux(ra->_iz),
ra->_clave, ra->_valor,
copiaAux(ra->_dr));
}
/**
Inserta una pareja (clave, valor) en la estructura
jerárquica que comienza en el puntero pasado como parámetro.
Ese puntero se admite que sea NULL, por lo que se creará
un nuevo nodo que pasará a ser la nueva raíz de esa
estructura jerárquica. El método devuelve un puntero a la
raíz de la estructura modificada. En condiciones normales
coincidirá con el parámetro recibido; sólo cambiará si
la estructura era vacía.
@param clave Clave a insertar. Si ya aparecía en la
estructura de nodos, se sobreescribe el valor.
@param valor Valor a insertar.
@param p Puntero al nodo raíz donde insertar la pareja.
@return Nueva raíz (o p si no cambia).
*/
static Nodo *insertaAux(const Clave &clave, const Valor &valor, Nodo *p) {
if (p == NULL) {
return new Nodo(clave, valor);
} else if (p->_clave == clave) {
p->_valor = valor;
return p;
} else if (clave < p->_clave) {
p->_iz = insertaAux(clave, valor, p->_iz);
return p;
} else { // (clave > p->_clave)
p->_dr = insertaAux(clave, valor, p->_dr);
return p;
}
}
/**
Busca una clave en la estructura jerárquica de
nodos cuya raíz se pasa como parámetro, y devuelve
el nodo en la que se encuentra (o NULL si no está).
@param p Puntero a la raíz de la estructura de nodos
@param clave Clave a buscar
*/
static Nodo *buscaAux(Nodo *p, const Clave &clave) {
if (p == NULL)
return NULL;
if (p->_clave == clave)
return p;
if (clave < p->_clave)
return buscaAux(p->_iz, clave);
else
return buscaAux(p->_dr, clave);
}
/**
Elimina (si existe) la clave/valor de la estructura jerárquica
de nodos apuntada por p. Si la clave aparecía en la propia raíz,
ésta cambiará, por lo que se devuelve la nueva raíz. Si no cambia
se devuelve p.
@param p Raíz de la estructura jerárquica donde borrar la clave.
@param clave Clave a borrar.
@return Nueva raíz de la estructura, tras el borrado. Si la raíz
no cambia, se devuelve el propio p.
*/
static Nodo *borraAux(Nodo *p, const Clave &clave) {
if (p == NULL)
return NULL;
if (clave == p->_clave) {
return borraRaiz(p);
} else if (clave < p->_clave) {
p->_iz = borraAux(p->_iz, clave);
return p;
} else { // clave > p->_clave
p->_dr = borraAux(p->_dr, clave);
return p;
}
}
/**
Borra la raíz de la estructura jerárquica de nodos
y devuelve el puntero a la nueva raíz que garantiza
que la estructura sigue siendo válida para un árbol de
búsqueda (claves ordenadas).
*/
static Nodo *borraRaiz(Nodo *p) {
Nodo *aux;
// Si no hay hijo izquierdo, la raíz pasa a ser
// el hijo derecho
if (p->_iz == NULL) {
aux = p->_dr;
delete p;
return aux;
} else
// Si no hay hijo derecho, la raíz pasa a ser
// el hijo izquierdo
if (p->_dr == NULL) {
aux = p->_iz;
delete p;
return aux;
} else {
// Convertimos el elemento más pequeño del hijo derecho
// en la raíz.
return mueveMinYBorra(p);
}
}
/**
Método auxiliar para el borrado; recibe un puntero a la
raíz a borrar. Busca el elemento más pequeño del hijo derecho
que se convertirá en la raíz (que devolverá), borra la antigua
raíz (p) y "cose" todos los punteros, de forma que ahora:
- El mínimo pasa a ser la raíz, cuyo hijo izquierdo y
derecho eran los hijos izquierdo y derecho de la raíz
antigua.
- El hijo izquierdo del padre del elemento más pequeño
pasa a ser el antiguo hijo derecho de ese mínimo.
*/
static Nodo *mueveMinYBorra(Nodo *p) {
// Vamos bajando hasta que encontramos el elemento
// más pequeño (aquel que no tiene hijo izquierdo).
// Vamos guardando también el padre (que será null
// si el hijo derecho es directamente el elemento
// más pequeño).
Nodo *padre = NULL;
Nodo *aux = p->_dr;
while (aux->_iz != NULL) {
padre = aux;
aux = aux->_iz;
}
// aux apunta al elemento más pequeño.
// padre apunta a su padre (si el nodo es hijo izquierdo)
// Dos casos dependiendo de si el padre del nodo con
// el mínimo es o no la raíz a eliminar
// (=> padre != NULL)
if (padre != NULL) {
padre->_iz = aux->_dr;
aux->_iz = p->_iz;
aux->_dr = p->_dr;
} else {
aux->_iz = p->_iz;
}
delete p;
return aux;
}
/**
Puntero a la raíz de la estructura jerárquica
de nodos.
*/
Nodo *_ra;
};
#endif // __ARBOLES_H
#include <iostream>
using namespace std;
struct Par{
int valor;
bool visitado;
};
//Creo un arbol completo con pares valor-bool con la profundidad que me den, hasta un determinado valor
Arbin<Par> creaArbol(int profundidad, int valor) {
int elevado = 1, cont = 0;
while(cont!=profundidad){
elevado=elevado*2;
cont++;
}
if (valor >= elevado) {
return Arbin<Par>();
} else {
Par par;
par.valor = valor;
par.visitado = false;
Arbin<Par> iz = creaArbol(profundidad, valor+valor);
Arbin<Par> dr = creaArbol(profundidad, valor+valor+1);
return Arbin<Par>(iz, par, dr);
}
}
/*Tira una bola por el árbol, devuelve el arbol con los bool de los nodos por los que pasa cambiados, y devuelve
por referencia el valor de la hoja a la que cae*/
Arbin<Par> tiraBola(Arbin<Par> a, int &num){
if(a.hijoIz().esVacio() && a.hijoDr().esVacio()){ //Si sus hijos son vacios devuelvo su raiz por referencia y el arbol resultante
Par p;
num = a.raiz().valor;
p.valor = num;
p.visitado = false;
return Arbin<Par>(Arbin<Par>(), p , Arbin<Par>());
}else{
if(a.raiz().visitado){ //Caigo por el hijo derecho
Par pvis;
pvis = a.raiz();
pvis.visitado =false;
return Arbin<Par>(a.hijoIz(), pvis, tiraBola(a.hijoDr(), num));
}else{ //Caigo por el hijo izquierdo
Par pnvis;
pnvis = a.raiz();
pnvis.visitado =true;
return Arbin<Par>(tiraBola(a.hijoIz(), num), pnvis, a.hijoDr());
}
}
}
int main(){
int numCasos=0, profundidad=0, bolasLanzadas=0;
cin >> numCasos; //Leo numero de casos
while(numCasos!=0){
cin >> profundidad; // Leo profundidad
cin >> bolasLanzadas; // Leo numero de bolas lanzadas
Arbin<Par> arbol;
int solucion = 0;
//Creo el arbol de pares int-bool
arbol = creaArbol(profundidad, 1);
//Lanzo tantas bolas como indique el usuario
while(bolasLanzadas!=0){
arbol = tiraBola(arbol, solucion);
bolasLanzadas--;
}
cout << solucion << endl;
numCasos--;
}
cin >> numCasos; //Leo -1
return 0;
} | [
"jaimedel@ucm.es"
] | jaimedel@ucm.es |
e711d43d564dbea80ffd823de0196be88ed17b4d | e9a481c76a7921f109882416be1f24a0cbf82dc8 | /particle.cpp | 088f8764a8de83bd527921869450547798a1bf14 | [] | no_license | azgurath/GravSim | 91d8daa96d1f1ddacb9fbf94f05c34b05738c877 | 44d6a58ac45de2e37d06e861fc61c5a4135c3770 | refs/heads/master | 2020-04-13T21:51:59.773419 | 2016-10-07T16:06:43 | 2016-10-07T16:06:43 | 68,053,751 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 581 | cpp | /**
* @file particle.cpp
* @author Andrew Hoover
* @date 9/20/2016
* @brief Implementation of particle class.
*
* Implements the constructor for the particle class,
* initializing the location, velocity, mass and next
* particle to zero.
*/
#include "particle.h"
/**
* Constructor, initializes the particle to zero.
*
* @brief Particle::Particle
*/
Particle::Particle()
{
// Set every variable to zero but mass, which is set to 1.
x = 0.0;
y = 0.0;
z = 0.0;
angX = 0.0;
angY = 0.0;
angZ = 0.0;
mass = 1.0;
next = 0;
}
| [
"azgurath@gmail.com"
] | azgurath@gmail.com |
dbca2b47aeae072f824b279a023450880674f916 | 30d6ffcaed24e22c071b46652890e57ef40fce07 | /custom_projects/09_OLED_Interfacing/04_oled_ST7735_80_160_spi/04_oled_ST7735_80_160_spi.ino | 643a886ee21c441d1028449f5d948c553c69a05f | [] | no_license | softwaresunleashed/arduino | 6fac93d16a13317a6818bd84e760d834b06975ce | f28d5554d449368850f2d95bd88ec8354e6f308c | refs/heads/master | 2023-01-12T02:54:18.674457 | 2020-11-05T12:48:34 | 2020-11-05T12:48:34 | 213,021,879 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,548 | ino | /**************************************************************************
This is a library for several Adafruit displays based on ST77* drivers.
Works with the Adafruit 1.8" TFT Breakout w/SD card
----> http://www.adafruit.com/products/358
The 1.8" TFT shield
----> https://www.adafruit.com/product/802
The 1.44" TFT breakout
----> https://www.adafruit.com/product/2088
The 1.14" TFT breakout
----> https://www.adafruit.com/product/4383
The 1.3" TFT breakout
----> https://www.adafruit.com/product/4313
The 1.54" TFT breakout
----> https://www.adafruit.com/product/3787
The 2.0" TFT breakout
----> https://www.adafruit.com/product/4311
as well as Adafruit raw 1.8" TFT display
----> http://www.adafruit.com/products/618
Check out the links above for our tutorials and wiring diagrams.
These displays use SPI to communicate, 4 or 5 pins are required to
interface (RST is optional).
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
MIT license, all text above must be included in any redistribution
**************************************************************************/
#include <Adafruit_GFX.h> // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>
// For the breakout board, you can use any 2 or 3 pins.
// These pins will also work for the 1.8" TFT shield.
#define TFT_CS 10
#define TFT_RST 9 // Or set to -1 and connect to Arduino RESET pin
#define TFT_DC 8
#define TFT_MOSI 11 // Data out
#define TFT_SCLK 13 // Clock out
// For 1.44" and 1.8" TFT with ST7735 use:
//Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
// For 1.14", 1.3", 1.54", and 2.0" TFT with ST7789:
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);
// For ST7735-based displays, we will use this call
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
// OR for the ST7789-based displays, we will use this call
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
float p = 3.1415926;
void setup(void) {
Serial.begin(9600);
Serial.print(F("Hello! ST77xx TFT Test"));
// Use this initializer if using a 1.8" TFT screen:
//tft.initR(INITR_BLACKTAB); // Init ST7735S chip, black tab
// OR use this initializer (uncomment) if using a 1.44" TFT:
//tft.initR(INITR_144GREENTAB); // Init ST7735R chip, green tab
// OR use this initializer (uncomment) if using a 0.96" 160x80 TFT:
tft.initR(INITR_MINI160x80); // Init ST7735S mini display
// OR use this initializer (uncomment) if using a 1.3" or 1.54" 240x240 TFT:
//tft.init(240, 240); // Init ST7789 240x240
// OR use this initializer (uncomment) if using a 2.0" 320x240 TFT:
//tft.init(240, 320); // Init ST7789 320x240
// OR use this initializer (uncomment) if using a 1.14" 240x135 TFT:
//tft.init(135, 240); // Init ST7789 240x135
Serial.println(F("Initialized"));
uint16_t time = millis();
tft.fillScreen(ST77XX_BLACK);
time = millis() - time;
Serial.println(time, DEC);
delay(500);
// large block of text
tft.fillScreen(ST77XX_BLACK);
testdrawtext("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur adipiscing ante sed nibh tincidunt feugiat. Maecenas enim massa, fringilla sed malesuada et, malesuada sit amet turpis. Sed porttitor neque ut ante pretium vitae malesuada nunc bibendum. Nullam aliquet ultrices massa eu hendrerit. Ut sed nisi lorem. In vestibulum purus a tortor imperdiet posuere. ", ST77XX_WHITE);
delay(1000);
// tft print function!
tftPrintTest();
delay(4000);
// a single pixel
tft.drawPixel(tft.width()/2, tft.height()/2, ST77XX_GREEN);
delay(500);
// line draw test
testlines(ST77XX_YELLOW);
delay(500);
// optimized lines
testfastlines(ST77XX_RED, ST77XX_BLUE);
delay(500);
testdrawrects(ST77XX_GREEN);
delay(500);
testfillrects(ST77XX_YELLOW, ST77XX_MAGENTA);
delay(500);
tft.fillScreen(ST77XX_BLACK);
testfillcircles(10, ST77XX_BLUE);
testdrawcircles(10, ST77XX_WHITE);
delay(500);
testroundrects();
delay(500);
testtriangles();
delay(500);
mediabuttons();
delay(500);
Serial.println("done");
delay(1000);
}
void loop() {
tft.invertDisplay(true);
delay(500);
tft.invertDisplay(false);
delay(500);
}
void testlines(uint16_t color) {
tft.fillScreen(ST77XX_BLACK);
for (int16_t x=0; x < tft.width(); x+=6) {
tft.drawLine(0, 0, x, tft.height()-1, color);
delay(0);
}
for (int16_t y=0; y < tft.height(); y+=6) {
tft.drawLine(0, 0, tft.width()-1, y, color);
delay(0);
}
tft.fillScreen(ST77XX_BLACK);
for (int16_t x=0; x < tft.width(); x+=6) {
tft.drawLine(tft.width()-1, 0, x, tft.height()-1, color);
delay(0);
}
for (int16_t y=0; y < tft.height(); y+=6) {
tft.drawLine(tft.width()-1, 0, 0, y, color);
delay(0);
}
tft.fillScreen(ST77XX_BLACK);
for (int16_t x=0; x < tft.width(); x+=6) {
tft.drawLine(0, tft.height()-1, x, 0, color);
delay(0);
}
for (int16_t y=0; y < tft.height(); y+=6) {
tft.drawLine(0, tft.height()-1, tft.width()-1, y, color);
delay(0);
}
tft.fillScreen(ST77XX_BLACK);
for (int16_t x=0; x < tft.width(); x+=6) {
tft.drawLine(tft.width()-1, tft.height()-1, x, 0, color);
delay(0);
}
for (int16_t y=0; y < tft.height(); y+=6) {
tft.drawLine(tft.width()-1, tft.height()-1, 0, y, color);
delay(0);
}
}
void testdrawtext(char *text, uint16_t color) {
tft.setCursor(0, 0);
tft.setTextColor(color);
tft.setTextWrap(true);
tft.print(text);
}
void testfastlines(uint16_t color1, uint16_t color2) {
tft.fillScreen(ST77XX_BLACK);
for (int16_t y=0; y < tft.height(); y+=5) {
tft.drawFastHLine(0, y, tft.width(), color1);
}
for (int16_t x=0; x < tft.width(); x+=5) {
tft.drawFastVLine(x, 0, tft.height(), color2);
}
}
void testdrawrects(uint16_t color) {
tft.fillScreen(ST77XX_BLACK);
for (int16_t x=0; x < tft.width(); x+=6) {
tft.drawRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color);
}
}
void testfillrects(uint16_t color1, uint16_t color2) {
tft.fillScreen(ST77XX_BLACK);
for (int16_t x=tft.width()-1; x > 6; x-=6) {
tft.fillRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color1);
tft.drawRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color2);
}
}
void testfillcircles(uint8_t radius, uint16_t color) {
for (int16_t x=radius; x < tft.width(); x+=radius*2) {
for (int16_t y=radius; y < tft.height(); y+=radius*2) {
tft.fillCircle(x, y, radius, color);
}
}
}
void testdrawcircles(uint8_t radius, uint16_t color) {
for (int16_t x=0; x < tft.width()+radius; x+=radius*2) {
for (int16_t y=0; y < tft.height()+radius; y+=radius*2) {
tft.drawCircle(x, y, radius, color);
}
}
}
void testtriangles() {
tft.fillScreen(ST77XX_BLACK);
uint16_t color = 0xF800;
int t;
int w = tft.width()/2;
int x = tft.height()-1;
int y = 0;
int z = tft.width();
for(t = 0 ; t <= 15; t++) {
tft.drawTriangle(w, y, y, x, z, x, color);
x-=4;
y+=4;
z-=4;
color+=100;
}
}
void testroundrects() {
tft.fillScreen(ST77XX_BLACK);
uint16_t color = 100;
int i;
int t;
for(t = 0 ; t <= 4; t+=1) {
int x = 0;
int y = 0;
int w = tft.width()-2;
int h = tft.height()-2;
for(i = 0 ; i <= 16; i+=1) {
tft.drawRoundRect(x, y, w, h, 5, color);
x+=2;
y+=3;
w-=4;
h-=6;
color+=1100;
}
color+=100;
}
}
void tftPrintTest() {
tft.setTextWrap(false);
tft.fillScreen(ST77XX_BLACK);
tft.setCursor(0, 30);
tft.setTextColor(ST77XX_RED);
tft.setTextSize(1);
tft.println("Hello World!");
tft.setTextColor(ST77XX_YELLOW);
tft.setTextSize(2);
tft.println("Hello World!");
tft.setTextColor(ST77XX_GREEN);
tft.setTextSize(3);
tft.println("Hello World!");
tft.setTextColor(ST77XX_BLUE);
tft.setTextSize(4);
tft.print(1234.567);
delay(1500);
tft.setCursor(0, 0);
tft.fillScreen(ST77XX_BLACK);
tft.setTextColor(ST77XX_WHITE);
tft.setTextSize(0);
tft.println("Hello World!");
tft.setTextSize(1);
tft.setTextColor(ST77XX_GREEN);
tft.print(p, 6);
tft.println(" Want pi?");
tft.println(" ");
tft.print(8675309, HEX); // print 8,675,309 out in HEX!
tft.println(" Print HEX!");
tft.println(" ");
tft.setTextColor(ST77XX_WHITE);
tft.println("Sketch has been");
tft.println("running for: ");
tft.setTextColor(ST77XX_MAGENTA);
tft.print(millis() / 1000);
tft.setTextColor(ST77XX_WHITE);
tft.print(" seconds.");
}
void mediabuttons() {
// play
tft.fillScreen(ST77XX_BLACK);
tft.fillRoundRect(25, 10, 78, 60, 8, ST77XX_WHITE);
tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_RED);
delay(500);
// pause
tft.fillRoundRect(25, 90, 78, 60, 8, ST77XX_WHITE);
tft.fillRoundRect(39, 98, 20, 45, 5, ST77XX_GREEN);
tft.fillRoundRect(69, 98, 20, 45, 5, ST77XX_GREEN);
delay(500);
// play color
tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_BLUE);
delay(50);
// pause color
tft.fillRoundRect(39, 98, 20, 45, 5, ST77XX_RED);
tft.fillRoundRect(69, 98, 20, 45, 5, ST77XX_RED);
// play color
tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_GREEN);
}
| [
"softwares.unleashed@gmail.com"
] | softwares.unleashed@gmail.com |
9a111d6e64325e4e3603cb95d8193632f032e231 | d439909a41a1fcce6c859d1022c145d736d06f73 | /aten/src/ATen/native/TensorConversions.cpp | 71690c4bf2d17b6aac54d029a02c4a025203b76a | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"BSL-1.0",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | MarcelRaschke/pytorch-2 | f19f41f8dc072bd3c387b9fada8a998f10cb235a | a346a18150866dd62c9bacbca817d2d44148b74d | refs/heads/master | 2023-05-12T02:48:04.840889 | 2022-03-16T15:19:41 | 2022-03-16T15:19:41 | 159,927,967 | 1 | 1 | NOASSERTION | 2023-04-04T00:54:40 | 2018-12-01T09:16:04 | C++ | UTF-8 | C++ | false | false | 12,927 | cpp | #include <ATen/ATen.h>
#include <ATen/NativeFunctions.h>
#include <c10/util/Optional.h>
#include <ATen/quantized/Quantizer.h>
#include <c10/core/impl/DeviceGuardImplInterface.h>
namespace at {
namespace native {
// Take a Device that may not have device_index set (i.e., having it as -1
// representing the current device) and return the corresponding Device
// according to the actual device at the time of this function call. No-op
// if the device_index is set.
static inline Device ensure_has_index(Device device) {
if (device.is_cpu() || device.has_index()) {
return device;
}
const c10::impl::DeviceGuardImplInterface* impl = c10::impl::getDeviceGuardImpl(device.type());
return impl->getDevice();
}
static inline optional<Device> ensure_has_index(optional<Device> device) {
if (!device.has_value()) {
return nullopt;
}
return ensure_has_index(device.value());
}
Tensor _to_copy(
const Tensor& self,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory,
bool non_blocking,
c10::optional<c10::MemoryFormat> optional_memory_format) {
TORCH_CHECK(!layout.has_value() || self.layout() == layout.value(),
"to(options) doesn't support converting to a different layout, "
"but got self.layout being ", self.layout(),
" and options.layout set as ", layout.value());
auto options = TensorOptions()
.dtype(dtype)
.layout(layout)
.device(device)
.pinned_memory(pin_memory);
if (options.has_device()) {
options = options.device(ensure_has_index(options.device()));
}
// memory_format is handled separately due to MemoryFormat::Preserve logic
options = self.options().merge_in(options).memory_format(c10::nullopt);
auto memory_format = optional_memory_format.value_or(MemoryFormat::Preserve);
bool pin_out = (non_blocking && self.is_cuda() && options.device().is_cpu() &&
(options.layout() == c10::kStrided));
if (memory_format == MemoryFormat::Preserve) {
if (self.is_non_overlapping_and_dense() && options.device().supports_as_strided()) {
Tensor r;
if (self.is_quantized()) {
r = at::empty_quantized(self.sizes(), self, options);
at::QuantizerPtr quantizer = r.quantizer();
r.copy_(self, non_blocking);
set_quantizer_(r, quantizer);
} else {
r = at::empty_strided(
self.sizes(),
self.strides(),
options.pinned_memory(pin_out));
r.copy_(self, non_blocking);
}
return r;
} else {
memory_format = self.suggest_memory_format();
}
}
// See Note [Explicit nullopt MemoryFormat argument]
auto r = at::empty(self.sizes(),
options.memory_format(memory_format).pinned_memory(pin_out),
c10::nullopt);
r.copy_(self, non_blocking);
return r;
}
template <typename T>
static inline bool is_null_or_equal_to(const c10::optional<T>& test, const T& value) {
if (!test.has_value()) {
return true;
}
return test.value() == value;
}
// NOTE: static runtime's to_maybe_copy_out relies on details of this
// check; if you change how it works, please update static runtime as
// well.
bool to_will_alias(
const Tensor& self,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
bool copy,
c10::optional<c10::MemoryFormat> optional_memory_format) {
auto memory_format = optional_memory_format.value_or(MemoryFormat::Preserve);
return is_null_or_equal_to(dtype, self.dtype().toScalarType()) &&
is_null_or_equal_to(layout, self.layout()) &&
is_null_or_equal_to(device, self.device()) &&
!copy &&
(memory_format == MemoryFormat::Preserve ||
self.suggest_memory_format() == memory_format);
}
static inline Tensor to_impl(
const Tensor& self,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory,
bool non_blocking,
bool copy,
c10::optional<c10::MemoryFormat> optional_memory_format) {
// fast path
if (to_will_alias(self, dtype, layout, device, copy, optional_memory_format)) {
return self;
}
return at::_to_copy(
self, dtype, layout, device, pin_memory, non_blocking, optional_memory_format);
}
// If input tensor is fp32, cast it to fp16, otherwise leave it alone.
// (this is intended to be used internally by the JIT autocast implementation)
Tensor _autocast_to_reduced_precision(const Tensor& self, bool cuda_enabled, bool cpu_enabled, ScalarType cuda_dtype, ScalarType cpu_dtype) {
if (self.dtype() == at::ScalarType::Float &&
((self.device().is_cuda() && cuda_enabled) ||
(self.device().is_cpu() && cpu_enabled))
) {
at::ScalarType target = at::ScalarType::Undefined;
if (self.device().is_cuda()) {
target = cuda_dtype;
} else if (self.device().is_cpu()) {
target = cpu_dtype;
}
TORCH_INTERNAL_ASSERT(target != at::ScalarType::Undefined, "_autocast_to_reduced_precision requires legit ScalarType argument for given device");
return to_impl(
self, target, c10::nullopt, c10::nullopt, c10::nullopt, false, false, c10::nullopt);
} else {
return self;
}
}
// If input tensor is fp16, cast it to fp32, otherwise leave it alone.
// (this is intended to be used internally by the JIT autocast implementation)
Tensor _autocast_to_full_precision(const Tensor& self, bool cuda_enabled, bool cpu_enabled) {
if ((self.dtype() == at::ScalarType::Half || self.dtype() == at::ScalarType::BFloat16) &&
((self.device().is_cuda() && cuda_enabled) ||
(self.device().is_cpu() && cpu_enabled))
) {
return to_impl(
self, at::ScalarType::Float, c10::nullopt, c10::nullopt, c10::nullopt, false, false, c10::nullopt);
} else {
return self;
}
}
Tensor to(
const Tensor& self,
c10::optional<ScalarType> dtype,
c10::optional<Layout> layout,
c10::optional<Device> device,
c10::optional<bool> pin_memory,
bool non_blocking,
bool copy,
c10::optional<c10::MemoryFormat> optional_memory_format
) {
return to_impl(
self,
dtype,
layout,
ensure_has_index(device),
pin_memory,
non_blocking,
copy,
optional_memory_format);
}
Tensor to(const Tensor& self, Device device, ScalarType dtype, bool non_blocking, bool copy, c10::optional<c10::MemoryFormat> optional_memory_format) {
return to_impl(
self,
dtype,
nullopt,
ensure_has_index(device),
nullopt,
non_blocking,
copy,
optional_memory_format);
}
Tensor to(const Tensor& self, ScalarType dtype, bool non_blocking, bool copy, c10::optional<c10::MemoryFormat> optional_memory_format) {
return to_impl(
self,
dtype,
nullopt,
nullopt,
nullopt,
non_blocking,
copy,
optional_memory_format);
}
Tensor to(const Tensor& self, const Tensor& other, bool non_blocking, bool copy, c10::optional<c10::MemoryFormat> optional_memory_format) {
auto options = other.options();
return to_impl(
self,
options.dtype().toScalarType(),
options.layout(),
options.device(),
options.pinned_memory(),
non_blocking,
copy,
optional_memory_format);
}
// This op is important primarily for lazy / graph-based backends.
// While this vanilla implementation loops through each tensor and independently converts it to cpu,
// a lazy backend like XLA might need to tell sync updates across tensors.
std::vector<Tensor> _to_cpu(TensorList tensors) {
std::vector<Tensor> cpu_tensors;
for (const auto& t : tensors) {
cpu_tensors.push_back(t.cpu());
}
return cpu_tensors;
}
Tensor to_dense_backward(const Tensor& grad, const Tensor& input_) {
AT_ASSERT(input_.layout() != c10::kStrided);
if (input_.layout() == c10::kSparse) {
auto input = input_.coalesce();
return grad.sparse_mask(input);
} else if (input_.layout() == c10::kMkldnn) {
return grad.to_mkldnn(input_.scalar_type());
} else {
AT_ERROR("Unsupported input layout: ", input_.layout());
}
}
Tensor to_mkldnn_backward(const Tensor& grad, const Tensor& input_) {
AT_ASSERT(input_.layout() == c10::kStrided);
return grad.to_dense(input_.scalar_type());
}
// Computes the strides for view_dtype output when the view dtype is
// smaller than the original dtype
inline DimVector compute_strides_for_view_dtype_downsize(IntArrayRef old_strides, int64_t size_ratio, ScalarType old_dtype, ScalarType new_dtype) {
const int64_t ndim = old_strides.size();
TORCH_CHECK(
old_strides[ndim - 1] == 1,
"self.stride(-1) must be 1 to view ", old_dtype, " as ", new_dtype,
" (different element sizes), but got ", old_strides[ndim - 1]);
DimVector new_strides(ndim);
for (int64_t dim_idx = 0; dim_idx < ndim - 1; dim_idx++) {
new_strides[dim_idx] = old_strides[dim_idx] * size_ratio;
}
new_strides[ndim - 1] = 1;
return new_strides;
}
// Computes the strides for view_dtype output when the view dtype is
// larger than the original dtype
inline DimVector compute_strides_for_view_dtype_upsize(IntArrayRef old_strides, int64_t size_ratio, ScalarType old_dtype, ScalarType new_dtype) {
const int64_t ndim = old_strides.size();
TORCH_CHECK(
old_strides[ndim - 1] == 1,
"self.stride(-1) must be 1 to view ", old_dtype, " as ", new_dtype,
" (different element sizes), but got ", old_strides[ndim - 1]);
DimVector new_strides(ndim);
for (int64_t dim_idx = 0; dim_idx < ndim - 1; dim_idx++) {
TORCH_CHECK(
(old_strides[dim_idx] % size_ratio) == 0,
"self.stride(", dim_idx, ") must be divisible by ", size_ratio,
" to view ", old_dtype, " as ", new_dtype, " (different element sizes), ",
"but got ", old_strides[dim_idx]);
new_strides[dim_idx] = old_strides[dim_idx] / size_ratio;
}
new_strides[ndim - 1] = 1;
return new_strides;
}
Tensor view_dtype(const Tensor& self, ScalarType dtype) {
if (self.scalar_type() == dtype) {
return self;
}
const auto type_meta = c10::scalarTypeToTypeMeta(dtype);
TORCH_CHECK(!self.is_conj(),
"torch.Tensor.view is not supported for conjugate view tensors when converting to a different dtype.");
TORCH_CHECK(!self.is_neg(),
"torch.Tensor.view is not supported for tensors with negative bit set when converting to a different dtype.");
int64_t self_element_size = self.element_size();
int64_t new_element_size = static_cast<int64_t>(type_meta.itemsize());
Storage storage = self.storage();
auto new_tensor = detail::make_tensor<TensorImpl>(
std::move(storage), self.key_set(), type_meta);
auto* impl = new_tensor.unsafeGetTensorImpl();
if (self_element_size == new_element_size) {
impl->set_storage_offset(self.storage_offset());
impl->set_sizes_and_strides(self.sizes(), self.strides());
} else if (self.dim() == 0) {
TORCH_CHECK(false,
"self.dim() cannot be 0 to view ", self.scalar_type(), " as ",
dtype, " (different element sizes)");
} else if (self_element_size > new_element_size) {
// Downsizing element size
int64_t size_ratio = self_element_size / new_element_size;
auto new_strides = compute_strides_for_view_dtype_downsize(
self.strides(), size_ratio, self.scalar_type(), dtype);
auto old_sizes = self.sizes();
DimVector new_sizes(self.dim());
std::copy(old_sizes.begin(), old_sizes.end(), new_sizes.begin());
new_sizes[self.dim() - 1] *= size_ratio;
auto new_storage_offset = size_ratio * self.storage_offset();
impl->set_storage_offset(new_storage_offset);
impl->set_sizes_and_strides(new_sizes, new_strides);
} else {
// Upsizing element size
int64_t size_ratio = new_element_size / self_element_size;
TORCH_CHECK(
(self.size(-1) % size_ratio) == 0,
"self.size(-1) must be divisible by ", size_ratio, " to view ",
self.scalar_type(), " as ", dtype, " (different element sizes), ",
"but got ", self.size(-1));
TORCH_CHECK(
(self.storage_offset() % size_ratio) == 0,
"self.storage_offset() must be divisible by ", size_ratio, " to view ",
self.scalar_type(), " as ", dtype, " (different element sizes), but got ",
self.storage_offset());
auto new_strides = compute_strides_for_view_dtype_upsize(
self.strides(), size_ratio, self.scalar_type(), dtype);
auto old_sizes = self.sizes();
DimVector new_sizes(self.dim());
std::copy(old_sizes.begin(), old_sizes.end(), new_sizes.begin());
new_sizes[self.dim() - 1] /= size_ratio;
auto new_storage_offset = self.storage_offset() / size_ratio;
impl->set_storage_offset(new_storage_offset);
impl->set_sizes_and_strides(new_sizes, new_strides);
}
return new_tensor;
}
}} // namespace at::native
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
94bf82f377b4124866a3ca88ebd10f197655c430 | f43711e16bf8e16fee28df8376814e14ec6ee10e | /Spoj/absys.cpp | 1ff54a6186b9934e4eb0777867096a1309c8ab8c | [] | no_license | kshav/My_codes | 5e3ed56b99ba2860462d485b2c2c6cdc485db14a | 4337b951454b62010bcc91b8f78db2eb04dcdc67 | refs/heads/master | 2016-09-06T00:24:47.843220 | 2014-02-19T12:49:31 | 2014-02-19T12:49:31 | 16,978,109 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,724 | cpp | #include<iostream>
#include<string.h>
using namespace std;
int main()
{
int n,t,l=0,j,m,l1,l2,l3,d,e,f;
string k;
cin>>n;
t=0;
while(t<n)
{ cout<<"Loop: "<<t<<"\n";
getline (cin,k);
l=k.size();
char w[l];
for(int i=0;i<l;i++)
w[i]=0;
l1=l2=l3=0;
d=e=f=0;
m=0;
j=0;
for(int i=0;i<l;i++)
{
if(k[i]!=' ')
{
w[j]=k[i];
j++;
}
}
m=j-1;
for(int i=0;i<=m;i++)
{
if(w[i]=='m')
l1=i;
else if(w[i]=='+')
l2=i;
else if(w[i]=='=')
l3=i;
}
//cout<<l1<<" "<<l2<<" "<<l3<<"\n";
if(l1>l2 && l1>l3)
{
for(int i=0;i<l2;i++)
d=d*10+w[i]-48;
for(int i=l2+1;i<l3;i++)
e=e*10+w[i]-48;
f=e+d;
cout<<d<<" + "<<e<<" = "<<f<<"\n";
}
else if(l1<l2 && l1<l3)
{
for(int i=l3+1;i<=m;i++)
f=f*10+w[i]-48;
for(int i=l2+1;i<l3;i++)
e=e*10+w[i]-48;
d=f-e;
cout<<d<<" + "<<e<<" = "<<f<<"\n";
}
else if(l1>l2 && l1<l3)
{
for(int i=l3+1;i<=m;i++)
f=f*10+w[i]-48;
for(int i=0;i<l2;i++)
d=d*10+w[i]-48;
e=f-d;
cout<<d<<" + "<<e<<" = "<<f<<"\n";
}
t++;
}
system("pause");
return 0;
}
| [
"kshav1908@gmail.com"
] | kshav1908@gmail.com |
6f4d5948f123da8605259044df72c057f923c2f1 | 936fa91805ad7e156705a3446f88ddd258b77a4f | /example/gizmesh_example_gl3/renderer_impl_gl3.cpp | 44382cc084f76b539158181c4cdea7abc273d1f1 | [
"MIT"
] | permissive | ousttrue/gizmesh | 2456edd3b632bfe8835b0c77159caa8d542a47a2 | fbc845abcd20eacc06c89c03a9e86a81208c401d | refs/heads/master | 2023-08-23T08:41:19.628360 | 2021-09-10T11:24:53 | 2021-09-10T11:24:53 | 243,416,047 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,012 | cpp | #include "gl-api.hpp"
#include "renderer.h"
#include "teapot.h"
#include "wgl_context.h"
constexpr const char gizmo_vert[] = R"(#version 330
layout(location = 0) in vec3 vertex;
layout(location = 1) in vec3 normal;
layout(location = 2) in vec4 color;
out vec4 v_color;
out vec3 v_world, v_normal;
//uniform mat4 u_mvp;
uniform mat4 u_modelMatrix;
uniform mat4 u_viewProj;
void main()
{
gl_Position = u_viewProj * u_modelMatrix * vec4(vertex.xyz, 1);
v_color = color;
v_world = vertex;
v_normal = normal;
}
)";
constexpr const char gizmo_frag[] = R"(#version 330
in vec4 v_color;
in vec3 v_world, v_normal;
out vec4 f_color;
uniform vec3 u_eye;
void main()
{
vec3 light = vec3(1) * max(dot(v_normal, normalize(u_eye - v_world)), 0.50) + 0.25;
f_color = v_color * vec4(light, 1);
}
)";
constexpr const char lit_vert[] = R"(#version 330
uniform mat4 u_modelMatrix;
uniform mat4 u_viewProj;
layout(location = 0) in vec3 inPosition;
layout(location = 1) in vec3 inNormal;
out vec3 v_position, v_normal;
void main()
{
vec4 worldPos = u_modelMatrix * vec4(inPosition, 1);
v_position = worldPos.xyz;
v_normal = normalize((u_modelMatrix * vec4(inNormal,0)).xyz);
gl_Position = u_viewProj * worldPos;
}
)";
constexpr const char lit_frag[] = R"(#version 330
uniform vec3 u_diffuse = vec3(1, 1, 1);
uniform vec3 u_eye;
in vec3 v_position;
in vec3 v_normal;
out vec4 f_color;
vec3 compute_lighting(vec3 eyeDir, vec3 position, vec3 color)
{
vec3 light = vec3(0, 0, 0);
vec3 lightDir = normalize(position - v_position);
light += color * u_diffuse * max(dot(v_normal, lightDir), 0);
vec3 halfDir = normalize(lightDir + eyeDir);
light += color * u_diffuse * pow(max(dot(v_normal, halfDir), 0), 128);
return light;
}
void main()
{
vec3 eyeDir = vec3(0, 1, -2);
vec3 light = vec3(0, 0, 0);
light += compute_lighting(eyeDir, vec3(+3, 1, 0), vec3(235.0/255.0, 43.0/255.0, 211.0/255.0));
light += compute_lighting(eyeDir, vec3(-3, 1, 0), vec3(43.0/255.0, 236.0/255.0, 234.0/255.0));
f_color = vec4(light + vec3(0.5, 0.5, 0.5), 1.0);
}
)";
class ModelImpl {
std::unique_ptr<GlShader> m_shader;
GlMesh m_mesh;
public:
void upload_mesh(const void *pVertices, uint32_t verticesBytes,
uint32_t vertexStride, const void *pIndices,
uint32_t indicesBytes, uint32_t indexStride,
bool isDynamic = false) {
if (!m_shader) {
if (isDynamic) {
m_shader.reset(new GlShader(gizmo_vert, gizmo_frag));
} else {
m_shader.reset(new GlShader(lit_vert, lit_frag));
}
}
m_mesh.set_vertex_data(verticesBytes, pVertices,
isDynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
m_mesh.set_attribute(0, 3, GL_FLOAT, GL_FALSE, vertexStride, (GLvoid *)0);
m_mesh.set_attribute(1, 3, GL_FLOAT, GL_FALSE, vertexStride, (GLvoid *)12);
m_mesh.set_attribute(2, 4, GL_FLOAT, GL_FALSE, vertexStride, (GLvoid *)24);
GLenum type;
switch (indexStride) {
case 2:
type = GL_UNSIGNED_SHORT;
break;
case 4:
type = GL_UNSIGNED_INT;
break;
default:
throw;
}
m_mesh.set_index_data(GL_TRIANGLES, type, indicesBytes / indexStride,
pIndices,
isDynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW);
}
void draw(const float *eye, const float *viewProj, const float *model,
bool isGizmo = false) {
if (isGizmo) {
glClear(GL_DEPTH_BUFFER_BIT);
}
m_shader->bind();
m_shader->uniform_float16("u_viewProj", viewProj);
m_shader->uniform_float16("u_modelMatrix", model);
m_shader->uniform_float3("u_eye", eye);
m_mesh.draw_elements();
m_shader->unbind();
}
};
Model::Model(ModelImpl *impl) : m_impl(impl) {}
Model::~Model() { delete m_impl; }
void Model::uploadMesh(void *, const void *vertices, uint32_t verticesSize,
uint32_t vertexStride, const void *indices,
uint32_t indicesSize, uint32_t indexSize,
bool is_dynamic) {
m_impl->upload_mesh(vertices, verticesSize, vertexStride, indices,
indicesSize, indexSize, is_dynamic);
}
void Model::draw(void *, const float *model, const float *vp,
const float *eye) {
m_impl->draw(eye, vp, model);
}
/////////////////////////////////////////////
class RendererImpl {
WGLContext m_wgl;
public:
bool initialize(void *hwnd) {
if (!m_wgl.Create(hwnd, 3, 0)) {
return false;
}
return true;
}
void beginFrame(int width, int height) {
glViewport(0, 0, width, height);
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClearColor(0.725f, 0.725f, 0.725f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
void clearDepth() { glClear(GL_DEPTH_BUFFER_BIT); }
void endFrame() {
gl_check_error(__FILE__, __LINE__);
m_wgl.Present();
}
};
Renderer::Renderer() : m_impl(new RendererImpl) {}
Renderer::~Renderer() { delete m_impl; }
void *Renderer::initialize(void *hwnd) {
return m_impl->initialize(hwnd) ? this : nullptr;
}
std::shared_ptr<Model> Renderer::createMesh() {
auto modelImpl = new ModelImpl();
return std::make_shared<Model>(modelImpl);
}
void *Renderer::beginFrame(int width, int height) {
m_impl->beginFrame(width, height);
return nullptr;
}
void Renderer::endFrame() { m_impl->endFrame(); }
void Renderer::clearDepth() { m_impl->clearDepth(); }
| [
"ousttrue@gmail.com"
] | ousttrue@gmail.com |
5a4d15edf9888432ec25b410605ab1ce8971a3ec | 02987503becabd24aa359d6ceabcb332ad8c6302 | /sgpp-1.1.0/base/src/sgpp/base/grid/storage/hashmap/SerializationVersion.hpp | 40e63bcadc80d4d3005cb22dde9fcb885637e7bc | [] | no_license | HappyTiger1/Sparse-Grids | a9c07527481ee28fe24abed6dad378ca9fc6d466 | 2832b262c1aeaa25312a3f7e48c5a67c90d183a5 | refs/heads/master | 2020-05-07T14:06:20.673900 | 2016-08-08T17:57:12 | 2016-08-08T17:57:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,099 | hpp | // Copyright (C) 2008-today The SG++ project
// This file is part of the SG++ project. For conditions of distribution and
// use, please see the copyright notice provided with SG++ or at
// sgpp.sparsegrids.org
#ifndef SERIALIZATIONVERSION_HPP
#define SERIALIZATIONVERSION_HPP
/**
* This specifies the available serialization versions
*
* Version 1: classic verions without leaf proeperty
* Version 2: every gridpoint is extended by one boolean that specifies if it's a leaf
* Version 3: added support for the grid's bounding box
* Version 4: needed for import of the Bonner's Sparse Grid Definition files; same as Ver 3
* but without leaf property, NOT FOR EXPORT
* Version 5: differentiate BoundingBox and Stretching, added support for stretching.
* Version 6: added PointDistribution to HashGridIndex
* ("Normal" with x = i*2^(-l) and "ClenshawCurtis")
* Version 7: PointDistribution changed from enum to enum class
* Version 8: Add custom boundaryLevel (>= 1) for LinearBoundaryGrid etc.
*/
#define SERIALIZATION_VERSION 7
#endif /* SERIALIZATIONVERSION_HPP */
| [
"alexander.atanasov@yale.edu"
] | alexander.atanasov@yale.edu |
0e5be2a2f44a67ba2feffd3d77c3fd87b03bc177 | 302f4bda84739593ab952f01c9e38d512b0a7d73 | /ext/Vc-1.3.2/sse/helperimpl.h | 0c1663e97f55294413f2eeb22302a8af61e34be9 | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"ICU",
"BSL-1.0",
"X11",
"Beerware"
] | permissive | thomaskrause/graphANNIS | 649ae23dd74b57bcd8a699c1e309e74096be9db2 | 66d12bcfb0e0b9bfcdc2df8ffaa5ae8c84cc569c | refs/heads/develop | 2020-04-11T01:28:47.589724 | 2018-03-15T18:16:50 | 2018-03-15T18:16:50 | 40,169,698 | 9 | 3 | Apache-2.0 | 2018-07-28T20:18:41 | 2015-08-04T07:24:49 | C++ | UTF-8 | C++ | false | false | 3,271 | h | /* This file is part of the Vc library. {{{
Copyright © 2010-2015 Matthias Kretz <kretz@kde.org>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the names of contributing organizations 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 BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
}}}*/
#ifndef VC_SSE_DEINTERLEAVE_H_
#define VC_SSE_DEINTERLEAVE_H_
#include "macros.h"
namespace Vc_VERSIONED_NAMESPACE
{
namespace Detail
{
template <typename A>
inline void deinterleave(SSE::float_v &, SSE::float_v &, const float *, A);
template <typename A>
inline void deinterleave(SSE::float_v &, SSE::float_v &, const short *, A);
template <typename A>
inline void deinterleave(SSE::float_v &, SSE::float_v &, const ushort *, A);
template <typename A>
inline void deinterleave(SSE::double_v &, SSE::double_v &, const double *, A);
template <typename A>
inline void deinterleave(SSE::int_v &, SSE::int_v &, const int *, A);
template <typename A>
inline void deinterleave(SSE::int_v &, SSE::int_v &, const short *, A);
template <typename A>
inline void deinterleave(SSE::uint_v &, SSE::uint_v &, const uint *, A);
template <typename A>
inline void deinterleave(SSE::uint_v &, SSE::uint_v &, const ushort *, A);
template <typename A>
inline void deinterleave(SSE::short_v &, SSE::short_v &, const short *, A);
template <typename A>
inline void deinterleave(SSE::ushort_v &, SSE::ushort_v &, const ushort *, A);
Vc_ALWAYS_INLINE_L void prefetchForOneRead(const void *addr, VectorAbi::Sse) Vc_ALWAYS_INLINE_R;
Vc_ALWAYS_INLINE_L void prefetchForModify(const void *addr, VectorAbi::Sse) Vc_ALWAYS_INLINE_R;
Vc_ALWAYS_INLINE_L void prefetchClose(const void *addr, VectorAbi::Sse) Vc_ALWAYS_INLINE_R;
Vc_ALWAYS_INLINE_L void prefetchMid(const void *addr, VectorAbi::Sse) Vc_ALWAYS_INLINE_R;
Vc_ALWAYS_INLINE_L void prefetchFar(const void *addr, VectorAbi::Sse) Vc_ALWAYS_INLINE_R;
} // namespace Detail
} // namespace Vc
#include "deinterleave.tcc"
#include "prefetches.tcc"
#endif // VC_SSE_DEINTERLEAVE_H_
| [
"thomaskrause@posteo.de"
] | thomaskrause@posteo.de |
3e1bca31b4c3271e2d86c8366180befd2972a0dc | 98578e9b0e2f19b627c89c82b880448158589f6d | /Lab_4/Lab_4/Bvector.cpp | c6d8e0af2b6020d6292938efd7816b0e6d24b016 | [] | no_license | roziukp/OOP-C- | c384e662075cecf6a49f94b2fa1ab40976e47026 | a03c104ddcf041cb34f03d88fb3663d2692fd620 | refs/heads/master | 2020-04-03T12:11:26.532659 | 2018-10-29T16:25:27 | 2018-10-29T16:25:27 | 155,244,067 | 0 | 1 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,866 | cpp | #include <iostream>
#include "Bvector.h"
using namespace std;
Bvector::Bvector(int size)
{
this->size = size;
arr = new bool[size];
for (int i = 0; i < size; i++)
{
cin >> arr[i];
}
}
Bvector::Bvector(Bvector &object)
{
size = object.size;
arr = new bool[size];
for (int i = 0; i<size; i++)
{
arr[i] = object.arr[i];
}
}
void Bvector::set_size(int size)
{
this->size = size;
}
void Bvector::set_arr(int size)
{
for (int i = 0; i < size; i++)
{
cout << "Введите заначание "<<i<<": ";
cin >> arr[i];
}
}
int Bvector::get_size()
{
return size;
}
bool *Bvector::get_arr()
{
return arr;
}
void Bvector::calculation( int size)
{
int x1=0, x2=0;
for (int i = 0; i < size; i++)
{
if (arr[i] == 0)
x1++;
else x2++;
}
cout << "\nКоличество нулей в векторе: "<<x1<<"\n";
cout << "Количество единиц в векторе: "<< x2 << "\n";
}
void Bvector::print()
{
for (int i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
Bvector Bvector::operator=(Bvector t)
{
size = t.size;
arr = new bool[size];
for (int i = 0; i<size; i++)
{
arr[i] = t.arr[i];
}
return *this;
}
Bvector Bvector:: operator | (Bvector t)
{
Bvector c;
c.size = size;
c.arr = new bool[size];
if (size == t.size)
{
for (int i = 0; i < size; i++)
{
c.arr[i] = (arr[i] | t.arr[i]);
}
}
return c;
}
Bvector Bvector::operator & (Bvector t)
{
Bvector c;
c.size = size;
c.arr = new bool[size];
if (size == t.size)
{
for (int i = 0; i < size; i++)
{
c.arr[i] = (arr[i] & t.arr[i]);
}
}
return c;
}
Bvector Bvector::operator ~ ()
{
{
for (int i = 0; i < size; i++)
{
arr[i] =!arr[i];
}
}
return *this;
}
Bvector ::~Bvector()
{
delete arr;
} | [
"roziukp@gmail.com"
] | roziukp@gmail.com |
15f8ad8e0dd20acc7434b34363d067a5cec50da4 | 04d6eb2e833fcbb69477fd70a7c1ced91e196c51 | /third_party/wide-integer/test/test_uintwide_t_n_binary_ops_mul_div_4_by_4_template.h | 359fd0fd67f261d5cae3cf4751763c55bbc720c3 | [
"BSL-1.0",
"MIT"
] | permissive | potassco/clingcon | 678138f256f60295af53d081c74bdd2b9bddbdbc | 1d4a15721f1e301b3e2074bf9b7a27c6948a9e77 | refs/heads/master | 2023-04-30T13:24:41.713761 | 2022-09-11T13:17:49 | 2022-09-11T13:17:49 | 62,557,412 | 22 | 6 | MIT | 2023-04-17T15:07:01 | 2016-07-04T11:32:41 | C++ | UTF-8 | C++ | false | false | 7,072 | h | ///////////////////////////////////////////////////////////////////////////////
// Copyright Christopher Kormanyos 2021.
// Distributed under the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef TEST_UINTWIDE_T_N_BINARY_OPS_MUL_DIV_4_BY_4_TEMPLATE_2021_03_04_H_
#define TEST_UINTWIDE_T_N_BINARY_OPS_MUL_DIV_4_BY_4_TEMPLATE_2021_03_04_H_
#include <atomic>
#include <math/wide_integer/uintwide_t.h>
#include <test/test_uintwide_t_n_base.h>
template<const math::wide_integer::size_t MyWidth2,
typename MyLimbType,
typename EnableType = void>
class test_uintwide_t_n_binary_ops_mul_div_4_by_4_template;
template<const math::wide_integer::size_t MyWidth2,
typename MyLimbType>
class test_uintwide_t_n_binary_ops_mul_div_4_by_4_template
<MyWidth2,
MyLimbType,
typename std::enable_if<( (std::numeric_limits<MyLimbType>::digits * 4 == MyWidth2)
&& (std::is_fundamental<MyLimbType>::value == true)
&& (std::is_integral <MyLimbType>::value == true)
&& (std::is_unsigned <MyLimbType>::value == true))>::type>
: public test_uintwide_t_n_binary_ops_base
{
private:
static constexpr math::wide_integer::size_t digits2 = MyWidth2;
virtual math::wide_integer::size_t get_digits2 () const { return digits2; }
using native_uint_cntrl_type =
typename math::wide_integer::detail::uint_type_helper<digits2>::exact_unsigned_type;
using local_limb_type = MyLimbType;
using local_uint_ab_type = math::wide_integer::uintwide_t<digits2, local_limb_type>;
public:
test_uintwide_t_n_binary_ops_mul_div_4_by_4_template(const std::size_t count)
: test_uintwide_t_n_binary_ops_base(count),
a_local(),
b_local(),
a_cntrl(),
b_cntrl() { }
virtual ~test_uintwide_t_n_binary_ops_mul_div_4_by_4_template() = default;
virtual bool do_test(const std::size_t rounds)
{
bool result_is_ok = true;
for(std::size_t i = 0U; i < rounds; ++i)
{
std::cout << "initialize() native compare with uintwide_t: round " << i << ", digits2: " << this->get_digits2() << std::endl;
this->initialize();
std::cout << "test_binary_mul() native compare with uintwide_t: round " << i << ", digits2: " << this->get_digits2() << std::endl;
result_is_ok &= this->test_binary_mul();
std::cout << "test_binary_div() native compare with uintwide_t: round " << i << ", digits2: " << this->get_digits2() << std::endl;
result_is_ok &= this->test_binary_div();
}
return result_is_ok;
}
virtual void initialize()
{
a_local.clear();
b_local.clear();
a_cntrl.clear();
b_cntrl.clear();
a_local.resize(size());
b_local.resize(size());
a_cntrl.resize(size());
b_cntrl.resize(size());
get_equal_random_test_values_cntrl_and_local_n(a_local.data(), a_cntrl.data(), size());
get_equal_random_test_values_cntrl_and_local_n(b_local.data(), b_cntrl.data(), size());
}
virtual bool test_binary_mul() const
{
std::atomic_flag test_lock = ATOMIC_FLAG_INIT;
bool result_is_ok = true;
my_concurrency::parallel_for
(
std::size_t(0U),
size(),
[&test_lock, &result_is_ok, this](std::size_t i)
{
const native_uint_cntrl_type c_cntrl = native_uint_cntrl_type(a_cntrl[i])
* b_cntrl[i];
const local_uint_ab_type c_local = static_cast<local_uint_ab_type>(a_local[i])
* static_cast<local_uint_ab_type>(b_local[i]);
const std::string str_boost = hexlexical_cast(c_cntrl);
const std::string str_local = hexlexical_cast(c_local);
while(test_lock.test_and_set()) { ; }
result_is_ok &= (str_boost == str_local);
test_lock.clear();
}
);
return result_is_ok;
}
virtual bool test_binary_div() const
{
std::atomic_flag test_lock = ATOMIC_FLAG_INIT;
test_uintwide_t_n_binary_ops_base::my_gen.seed(static_cast<typename random_generator_type::result_type>(std::clock()));
std::uniform_int_distribution<> dis(1, static_cast<int>(digits2 - 1U));
bool result_is_ok = true;
my_concurrency::parallel_for
(
std::size_t(0U),
size(),
[&test_lock, &result_is_ok, this, &dis](std::size_t i)
{
while(test_lock.test_and_set()) { ; }
const std::size_t right_shift_amount = static_cast<std::size_t>(dis(my_gen));
test_lock.clear();
const native_uint_cntrl_type c_cntrl = a_cntrl[i] / (std::max)(native_uint_cntrl_type(1U), native_uint_cntrl_type(b_cntrl[i] >> right_shift_amount));
const local_uint_ab_type c_local = a_local[i] / (std::max)(local_uint_ab_type(1U), (b_local[i] >> right_shift_amount));
const std::string str_boost = hexlexical_cast(c_cntrl);
const std::string str_local = hexlexical_cast(c_local);
while(test_lock.test_and_set()) { ; }
result_is_ok &= (str_boost == str_local);
test_lock.clear();
}
);
return result_is_ok;
}
private:
std::vector<local_uint_ab_type> a_local;
std::vector<local_uint_ab_type> b_local;
std::vector<native_uint_cntrl_type> a_cntrl;
std::vector<native_uint_cntrl_type> b_cntrl;
template<typename OtherLocalUintType,
typename OtherCntrlUintType>
static void get_equal_random_test_values_cntrl_and_local_n(OtherLocalUintType* u_local,
OtherCntrlUintType* u_cntrl,
const std::size_t count)
{
using other_local_uint_type = OtherLocalUintType;
using other_cntrl_uint_type = OtherCntrlUintType;
test_uintwide_t_n_base::my_random_generator.seed(static_cast<typename std::linear_congruential_engine<std::uint32_t, 48271, 0, 2147483647>::result_type>(std::clock()));
using distribution_type =
math::wide_integer::uniform_int_distribution<other_local_uint_type::my_width2, typename other_local_uint_type::limb_type>;
distribution_type distribution;
std::atomic_flag rnd_lock = ATOMIC_FLAG_INIT;
my_concurrency::parallel_for
(
std::size_t(0U),
count,
[&u_local, &u_cntrl, &distribution, &rnd_lock](std::size_t i)
{
while(rnd_lock.test_and_set()) { ; }
const other_local_uint_type a = distribution(my_random_generator);
rnd_lock.clear();
u_local[i] = a;
u_cntrl[i] = static_cast<other_cntrl_uint_type>(a);
}
);
}
};
#endif // TEST_UINTWIDE_T_N_BINARY_OPS_MUL_DIV_4_BY_4_TEMPLATE_2021_03_04_H_
| [
"kaminski@cs.uni-potsdam.de"
] | kaminski@cs.uni-potsdam.de |
8793eca0f56ee2d2d85396062f7b95f711e372cc | 5d997fe0ccdcff70d2f7933f4c7f11d9c637fd86 | /modules/core/mgmt/rwuagent/src/rwuagent_confd_workspace.cpp | 979eb4747e5091860b0e7702035753be465835ff | [
"Apache-2.0"
] | permissive | gonotes/RIFT.ware | 02e1ea2d11aa99f5a65be6d686f2afabd3284070 | 45884f1e2b7b0028afae19eb0243dbfeb71edaff | refs/heads/master | 2021-01-18T02:50:07.858451 | 2016-06-02T14:55:14 | 2016-06-02T14:55:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,770 | cpp |
/*
*
* (c) Copyright RIFT.io, 2013-2016, All Rights Reserved
*
*/
/*
* @file rwuagent_confd_workspace.cpp
*
* Management Confd workspace handler
*/
#include <string>
#include <sstream>
#include <boost/algorithm/string.hpp>
#include "rw_schema_defs.h"
#include "rwuagent_mgmt_system.hpp"
#include "rw-manifest.pb-c.h"
#define CONFD_BASE_PATH ("/usr/local/confd")
#define CONFD_LOG_PATH ("/var/confd/log/")
using namespace rw_uagent;
namespace fs = boost::filesystem;
ConfdWorkspaceMgr::ConfdWorkspaceMgr(const ConfdMgmtSystem* mgmt,
Instance* inst):
mgmt_(mgmt),
instance_(inst),
memlog_buf_(
inst->get_memlog_inst(),
"ConfdWorkspaceMgr",
reinterpret_cast<intptr_t>(this))
{
}
rw_status_t ConfdWorkspaceMgr::generate_config_file()
{
RWMEMLOG(memlog_buf_, RWMEMLOG_MEM2, "generate config file");
auto prototype_conf_file = get_rift_install() + "/" + RW_SCHEMA_CONFD_PROTOTYPE_CONF;
auto confd_dir = mgmt_->mgmt_dir();
confd_conf_dom_ = std::move(instance_->xml_mgr()->create_document_from_file(
prototype_conf_file.c_str(), false));
if (!confd_conf_dom_) {
RW_MA_INST_LOG (instance_, InstanceError,
"Failed to convert prototype conf file to DOM");
return RW_STATUS_FAILURE;
}
if (!set_schema_load_path()) {
RW_MA_INST_LOG (instance_, InstanceError, "Failed to set load path");
return RW_STATUS_FAILURE;
}
set_directory_path("", "stateDir", confd_dir + "/var/confd/state");
set_directory_path("cdb", "dbDir", confd_dir + "/var/confd/cdb");
set_directory_path("rollback", "directory", confd_dir + "/var/confd/rollback");
set_directory_path(
"netconf/capabilities/url/file", "rootDir", confd_dir + "/var/confd/state");
set_directory_path(
"aaa", "sshServerKeyDir", get_rift_install() + "/usr/local/confd/etc/confd/ssh");
auto confd_log_path = confd_dir + CONFD_LOG_PATH;
set_directory_path("logs/webuiAccessLog", "dir", confd_log_path);
set_feature("cli", true);
set_feature("rest", true);
set_feature("snmpAgent", false);
auto vcs_inst = instance_->rwvcs();
RwManifest__YangEnum__NetconfTrace__E trace_e = RW_MANIFEST_NETCONF_TRACE_AUTO;
if (vcs_inst
&& vcs_inst->pb_rwmanifest
&& vcs_inst->pb_rwmanifest->init_phase
&& vcs_inst->pb_rwmanifest->init_phase->settings
&& vcs_inst->pb_rwmanifest->init_phase->settings->mgmt_agent
&& vcs_inst->pb_rwmanifest->init_phase->settings->mgmt_agent->has_netconf_trace)
{
trace_e = vcs_inst->pb_rwmanifest->init_phase->settings->mgmt_agent->netconf_trace;
}
switch (trace_e) {
case RW_MANIFEST_NETCONF_TRACE_ENABLE:
set_feature("logs/netconfTraceLog", true);
break;
case RW_MANIFEST_NETCONF_TRACE_DISABLE:
set_feature("logs/netconfTraceLog", false);
break;
default:
{
if (is_production()) {
set_feature("logs/netconfTraceLog", false);
} else {
set_feature("logs/netconfTraceLog", true);
}
}
};
std::map<const char*, const char*> log_types = {
{"logs/confdLog/file", "confd.log"},
{"logs/developerLog/file", "devel.log"},
{"logs/auditLog/file", "audit.log"},
{"logs/netconfLog/file", "netconf.log"},
{"logs/snmpLog/file", "snmp.log"}
};
for (auto& log_type : log_types) {
set_directory_path(log_type.first, "name", confd_log_path + log_type.second);
}
set_directory_path("logs/netconfTraceLog", "filename", confd_log_path + "netconf.trace");
set_directory_path("datastores/candidate", "filename", confd_dir + "/var/confd/candidate/candidate.db");
set_notif_directory_path(
"notifications/eventStreams/stream/builtinReplayStore/maxSize", "dir", confd_dir);
return confd_conf_dom_->to_file((confd_dir + "/rw_confd.conf").c_str());
}
bool ConfdWorkspaceMgr::set_schema_load_path()
{
RWMEMLOG(memlog_buf_, RWMEMLOG_MEM2, "set schema load path");
XMLNode* root_node = confd_conf_dom_->get_root_node();
RW_ASSERT (root_node);
XMLNode* load_path = root_node->find("loadPath");
if (!load_path) {
load_path = root_node->add_child("loadPath");
RW_ASSERT (load_path);
}
auto latest_ver_dir = get_rift_install() + "/" + RW_SCHEMA_VER_LATEST_NB_PATH + "/fxs";
if (!fs::exists(latest_ver_dir)) {
RW_MA_INST_LOG (instance_, InstanceError, "Schema directory does not exist.");
return false;
}
auto confd_yang_dir = get_rift_install() + "/usr/local/confd/etc/confd/";
XMLNode* dir = load_path->add_child("dir", confd_yang_dir.c_str());
RW_ASSERT(dir);
XMLNode* dir2 = load_path->add_child("dir", latest_ver_dir.c_str());
RW_ASSERT(dir2);
return true;
}
void ConfdWorkspaceMgr::set_directory_path(
const std::string& node_path,
const std::string& elem_name,
const std::string& elem_value)
{
RWMEMLOG(memlog_buf_, RWMEMLOG_MEM2, "set directory path");
std::vector<std::string> path_vec;
if (node_path.length()) {
boost::split(path_vec, node_path, boost::is_any_of("/"));
}
XMLNode* root_node = confd_conf_dom_->get_root_node();
RW_ASSERT (root_node);
XMLNode* node = root_node;
for (auto& path : path_vec) {
node = node->find(path.c_str());
RW_ASSERT (node);
}
XMLNode* child_node = node->add_child(elem_name.c_str(), elem_value.c_str());
RW_ASSERT (child_node);
}
void ConfdWorkspaceMgr::set_notif_directory_path(
const std::string& node_path,
const std::string& elem_name,
const std::string& elem_value)
{
RWMEMLOG(memlog_buf_, RWMEMLOG_MEM2, "set notif directory path");
std::vector<std::string> path_vec;
if (node_path.length()) {
boost::split(path_vec, node_path, boost::is_any_of("/"));
}
XMLNode* root_node = confd_conf_dom_->get_root_node();
RW_ASSERT (root_node);
XMLNode* node = root_node;
for (auto& path : path_vec) {
node = node->find(path.c_str());
RW_ASSERT (node);
}
XMLNode* sib_node = node->insert_before(elem_name.c_str(), elem_value.c_str());
RW_ASSERT (sib_node);
}
void ConfdWorkspaceMgr::set_feature(const std::string& conf_node, bool value)
{
RWMEMLOG(memlog_buf_, RWMEMLOG_MEM2, "set feature");
std::vector<std::string> path_vec;
if (conf_node.length()) {
boost::split(path_vec, conf_node, boost::is_any_of("/"));
}
XMLNode* root_node = confd_conf_dom_->get_root_node();
RW_ASSERT (root_node);
XMLNode* node = root_node;
for (auto& path : path_vec) {
node = node->find(path.c_str());
if (!node) break;
}
if (!node) {
std::string log_str;
log_str = "Feature path does not exist in prototype config: " + conf_node;
RW_MA_INST_LOG (instance_, InstanceError, log_str.c_str());
return;
}
XMLNode* enabled = nullptr;
if (value) {
enabled = node->add_child("enabled", "true");
} else {
enabled = node->add_child("enabled", "false");
}
RW_ASSERT (enabled);
}
bool ConfdWorkspaceMgr::create_confd_workspace()
{
RWMEMLOG(memlog_buf_, RWMEMLOG_MEM2, "create confd workspace");
auto rift_install = get_rift_install();
auto confd_dir = mgmt_->mgmt_dir();
std::array<const char*, 5> sub_dirs = {
"/var/confd/candidate",
"/var/confd/cdb",
"/var/confd/log",
"/var/confd/rollback",
"/var/confd/state"
};
try {
for (auto sdir : sub_dirs) {
auto dest_dir = confd_dir + sdir;
if (!fs::create_directories(dest_dir)) {
std::string log_str;
log_str = "Failed to create directory: " + dest_dir + ". ";
log_str += std::strerror(errno);
RW_MA_INST_LOG (instance_, InstanceError, log_str.c_str());
return false;
}
}
} catch (const fs::filesystem_error& e) {
RW_MA_INST_LOG (instance_, InstanceError, e.what());
return false;
}
try {
// Copy aaa_init.xml file
fs::copy_file(rift_install + CONFD_BASE_PATH + "/var/confd/cdb/aaa_init.xml",
confd_dir + "/var/confd/cdb/aaa_init.xml");
// Install the oper user aaa restrictions
fs::copy_file(rift_install + "/usr/data/security/oper_user_restrictions.xml",
confd_dir + "/var/confd/cdb/oper_user_restrictions.xml");
} catch (const fs::filesystem_error& e) {
RW_MA_INST_LOG (instance_, InstanceError, e.what());
return false;
}
return true;
}
rw_status_t ConfdWorkspaceMgr::create_mgmt_directory()
{
RWMEMLOG(memlog_buf_, RWMEMLOG_MEM2, "create mgmt directory");
auto confd_dir = mgmt_->mgmt_dir();
if (!confd_dir.length()) {
RW_MA_INST_LOG (instance_, InstanceCritInfo, "Workspace not yet created. Retrying.");
return RW_STATUS_FAILURE;
}
if (fs::exists(confd_dir))
{
auto confd_init_file = confd_dir + "/" + CONFD_INIT_FILE;
if (!fs::exists(confd_init_file)) {
RW_MA_INST_LOG (instance_, InstanceCritInfo,
"Confd init file not found. Perhaps confd was not initialized"
" completely in its previous run. Deleting existing confd directory.");
try {
fs::remove_all(confd_dir);
} catch (const fs::filesystem_error& e) {
RW_MA_INST_LOG (instance_, InstanceError, e.what());
}
} else {
std::string log_str;
log_str = "Confd workspace is " + confd_dir;
RW_MA_INST_LOG (instance_, InstanceInfo, log_str.c_str());
return RW_STATUS_SUCCESS;
}
}
// Create confd workspace
if (create_confd_workspace() &&
(generate_config_file() == RW_STATUS_SUCCESS))
{
std::string log_str;
log_str = "Confd workspace " + confd_dir +
" created successfully";
RW_MA_INST_LOG (instance_, InstanceCritInfo, log_str.c_str());
} else {
RW_MA_INST_LOG (instance_, InstanceError, "Failed to create confd workspace");
return RW_STATUS_FAILURE;
}
return RW_STATUS_SUCCESS;
}
| [
"Wei.Wang@riftio.com"
] | Wei.Wang@riftio.com |
cc416b4a1da592ad1df0bd2eb6d4279706e5b7c5 | b5e8a7b5798d6cb124aaf7172d78478eb72bd733 | /usaco/agrinet.cpp | 7c6c868bfbacd9cdf2692bb6b155c8326359258b | [] | no_license | manolismih/OJsolutions | 8e62b29ac604077473926dd63d8a636181db11be | 809999d34036033e3a8757518588bf5847ca7f5f | refs/heads/master | 2022-05-01T01:19:52.014312 | 2022-03-10T13:37:13 | 2022-03-10T13:37:13 | 244,162,474 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 954 | cpp | /*
ID:manolis2
PROG:agrinet
LANG:C++
*/
#include <cstdio>
#include <queue>
using namespace std;
FILE *fin = fopen("agrinet.in","r"), *fout = fopen("agrinet.out","w");
struct node{
int komvos,dist;
};
inline bool operator<(node a, node b)
{
return a.dist>b.dist;
}
inline node tonode(int komvos, int dist)
{
node ret={komvos,dist};
return ret;
}
int n,amatrix[100][100], msp=0;
priority_queue<node> oura;
bool visited[100];
int main()
{
fscanf(fin,"%i",&n);
for (int i=0; i<n; i++)
for (int j=0; j<n; j++)
fscanf(fin,"%i",&amatrix[i][j]);
oura.push(tonode(0,0));
int v;
for (int i=0; i<n; i++)
{
v = oura.top().komvos;
if (visited[v])
{
i--;
oura.pop();
continue;
}
visited[v] = true;
msp += oura.top().dist;
oura.pop();
for (int j=0; j<n; j++)
if (amatrix[v][j])
oura.push(tonode(j,amatrix[v][j]));
}
fprintf(fout,"%i\n",msp);
return 0;
}
| [
"manolismih@windowslive.com"
] | manolismih@windowslive.com |
9dd320800fb3006b822e19df6c0655cc4076177c | ff0545672e0bf75ea0cfe9423af18de9cb4669df | /compile_error.cpp/compile_error.cpp/compile_error.cpp | be77ed236f5d4ff69733a5f735cf89a7b45032c6 | [] | no_license | tsengliwei/UCLA-CS-31-Project1 | a76a35fcc797da88e4ea353a565650ad2236fc52 | d3fbb587dc711d3e54fda521b73958582db2c895 | refs/heads/master | 2020-06-08T17:18:52.113530 | 2015-01-22T23:34:44 | 2015-01-22T23:34:44 | 29,706,087 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,060 | cpp | // Code for Project 1
// Report poll results
#include <iostream>
using namespace std; // see p. 37-38 in Savitch book
int main()
{
int numberSurveyed;
int preferHomeTeam;
int preferAwayTeam;
cout << "How many fans in attendance were surveyed? "
cin >> numberSurveyed;
cout << "How many of them prefer the home team? ";
cin >> preferHomeTeam;
cout << "How many of them prefer the away team? ;
cin >> preferAwayTeam;
double pctHome = 100.0 * preferHomeTeam % numberSurveyed;
double pctAway = 100.0 * preferAwayTeam / numberSurveyed;
cout.setf(ios::fixed); // see pp. 30-31 in Savitch book
cout.precision(1);
cout << endl;
cout << pctHome << "% prefer the home team." << endl;
cout << pctAway << "% prefer the away team." << endl;
if (pctHome > pctAway)
cout << "The home team is more popular with this crowd." << endl;
else
cout << "The away team is more popular with this crowd." << endl;
} | [
"tsengliwei@gmail.com"
] | tsengliwei@gmail.com |
38d6569f430fcf0e89943b99811ea8775f213c4f | 2abc4ab516bec7cc7cf56786328f783ef9e16e85 | /Project/PathSearch/PathSearch.h | 12f8e7a6490b5e44924aa72ea12f224684e29a27 | [] | no_license | chrisloco11/Pathfinder-Lab | 420ed379d40bf616f505fab05e0105c5214b862d | aba07e77dbad162be0a39eda8512c71599f77e5e | refs/heads/master | 2021-01-18T17:15:27.648013 | 2014-12-01T19:14:31 | 2014-12-01T19:14:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,891 | h | //! \file PathSearch.h
//! \brief Defines the <code>fullsail_ai::algorithms::PathSearch</code> class interface.
//! \author Cromwell D. Enage, 2009; Jeremiah Blanchard, 2012
#ifndef _FULLSAIL_AI_PATH_PLANNER_PATH_SEARCH_H_
#define _FULLSAIL_AI_PATH_PLANNER_PATH_SEARCH_H_
// change this to start the program on whatever default map as you like from the table below
#define USEDEFAULTMAP hex035x035
#define hex006x006 "./Data/hex006x006.txt"
#define hex014x006 "./Data/hex014x006.txt"
#define hex035x035 "./Data/hex035x035.txt"
#define hex054x045 "./Data/hex054x045.txt"
#define hex098x098 "./Data/hex098x098.txt"
#define hex113x083 "./Data/hex113x083.txt"
// change this to 1(true), and change the data below when you want to test specific starting and goal locations on startup
#define OVERRIDE_DEFAULT_STARTING_DATA 0
// Make sure your start and goal are valid locations!
#define DEFAULT_START_ROW 0
#define DEFAULT_START_COL 0
#define DEFAULT_GOAL_ROW ?
#define DEFAULT_GOAL_COL ?
#include "../TileSystem/Tile.h"
#include "../TileSystem/TileMap.h"
#include "../platform.h"
#include <vector>
namespace fullsail_ai { namespace algorithms {
class PathSearch
{
public:
//! \brief Default constructor.
DLLEXPORT PathSearch();
//! \brief Destructor.
DLLEXPORT ~PathSearch();
//! \brief Sets the tile map.
//!
//! Invoked when the user opens a tile map file.
//!
//! \param _tileMap the data structure that this algorithm will use
//! to access each tile's location and weight data.
DLLEXPORT void initialize(TileMap* _tileMap);
//! \brief Enters and performs the first part of the algorithm.
//!
//! Invoked when the user presses one of the play buttons.
//!
//! \param startRow the row where the start tile is located.
//! \param startColumn the column where the start tile is located.
//! \param goalRow the row where the goal tile is located.
//! \param goalColumn the column where the goal tile is located.
DLLEXPORT void enter(int startRow, int startColumn, int goalRow, int goalColumn);
//! \brief Returns <code>true</code> if and only if no nodes are left open.
//!
//! \return <code>true</code> if no nodes are left open, <code>false</code> otherwise.
DLLEXPORT bool isDone() const;
//! \brief Performs the main part of the algorithm until the specified time has elapsed or
//! no nodes are left open.
DLLEXPORT void update(long timeslice);
//! \brief Returns an unmodifiable view of the solution path found by this algorithm.
DLLEXPORT std::vector<Tile const*> const getSolution() const;
//! \brief Resets the algorithm.
DLLEXPORT void exit();
//! \brief Uninitializes the algorithm before the tile map is unloaded.
DLLEXPORT void shutdown();
};
}} // namespace fullsail_ai::algorithms
#endif // _FULLSAIL_AI_PATH_PLANNER_PATH_SEARCH_H_
| [
"chrisloco11@fullsail.edu"
] | chrisloco11@fullsail.edu |
ade1b74a991f3bb4313bcd7e6c483f9b8db6dc69 | 1ad9c4de957e2a868d9534d415ffe63aec61b17e | /day02/main.cpp | 8299c976b9aba2bc058583b699601c008cced1d3 | [] | no_license | simrit1/Challange30Days | 2823153225c0f0000b02756dc6984ee2e1620757 | 2b4a054277baf00f0842ff38b17cfbbe9c1ef93d | refs/heads/master | 2022-07-03T05:45:44.070219 | 2020-05-17T00:10:33 | 2020-05-17T00:10:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,307 | cpp | #include <iostream>
using namespace std;
// prototype
void startCalc();
void penjumlahan(float a, float b);
void pengurangan(float a, float b);
void perkalian(float a, float b);
void pembagian(float a, float b);
// membuat kalkulator sederhana
int main(int argc, char const *argv[])
{
startCalc();
return 0;
}
void startCalc(){
int opt;
float a,b;
cout << "=Selamat datang di calculator sederhana=" << endl;
cout << "Masukan angka 1: ";
cin >> a;
cout << "Masukan angka 2: ";
cin >> b;
cout << "----------1. + 2. - 3. * 4. /-----------" << endl;
cout << "Pilih perhitungan: ";
cin >> opt;
if (opt == 1)
{
penjumlahan(a,b);
} else if (opt == 2)
{
pengurangan(a,b);
} else if (opt == 3)
{
perkalian(a,b);
} else if (opt == 4)
{
pembagian(a,b);
} else {
cout << "Yang kamu masukan salah broh!" << endl;
}
}
void penjumlahan(float a, float b){
cout << "Hasil penjumlahannya: " << a + b << endl;
}
void pengurangan(float a, float b){
cout << "Hasil pengurangannya: " << a - b << endl;
}
void perkalian(float a, float b){
cout << "Hasil perkaliannya: " << a * b << endl;
}
void pembagian(float a, float b){
cout << "Hasil pembagiannya: " << a / b << endl;
} | [
"randynetworks@gmail.com"
] | randynetworks@gmail.com |
d01500ed985f64e6ad4ad184b90d0e2e93364592 | e9d7c12a55dae228bc2c9f1b1819f062cddb3430 | /k-ahci.hh | 29f0ba5d8469968801684f2d13754a8cd5862baa | [] | no_license | NoorEMobeen/chickadee | 33b495e591523036386454afa8da982dcf3953fe | 362beaeae5e9e00a10597dcd36c823c2f2259d1e | refs/heads/master | 2020-08-06T12:56:12.149657 | 2019-05-05T17:36:12 | 2019-05-05T17:36:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,196 | hh | #ifndef CHICKADEE_K_AHCI_HH
#define CHICKADEE_K_AHCI_HH
#include "kernel.hh"
#include "k-wait.hh"
// achistate: communication with modern SATA disks
struct ahcistate {
// interesting IDE commands
// Specification: "ATA/ATAPI Command Set" for ATA-8
enum idecommand {
cmd_identify_device = 0xEC,
cmd_set_features = 0xEF,
cmd_read_fpdma_queued = 0x60,
cmd_write_fpdma_queued = 0x61
};
// memory-mapped I/O structures for device communication
// Specification/comment field names: "Serial ATA AHCI 1.3.1 Specification"
// The kernel finds the MMIO address of a `struct regs` using PCI.
// This contains up to 32 `struct portregs`, each corresponding to
// a different disk; most communication with the disk uses the
// `portregs`. One `ahcistate` corresponds to one disk.
struct portregs {
uint64_t cmdlist_pa; // PxCLB: physical addr of `cmdheader` array
uint64_t rfis_pa; // PxRFIS: physical address of `rfisstate`
uint32_t interrupt_status; // PxIS
uint32_t interrupt_enable; // PxIE
uint32_t command; // PxCMD
uint32_t reserved0;
uint32_t rstatus; // PxTFD
uint32_t psig; // PxSIG
uint32_t sstatus; // PxSSTS: 0 means port doesn't exist
uint32_t scontrol; // PxSCTL
uint32_t serror; // PxSERR [R/clear]
uint32_t ncq_active_mask; // PxSACT
uint32_t command_mask; // PxCI
uint32_t sata_notification; // PxSNTF
uint32_t pfbs, sleep;
uint32_t reserved[14];
};
struct regs {
uint32_t capabilities; // CAP: device capabilities [R]
uint32_t ghc; // GHC: global [adapter] control [R/W]
uint32_t interrupt_status; // IS: interrupt status [R/clear]
uint32_t port_mask; // PI: addressable ports (may not exist)
uint32_t ahci_version; // VS
uint32_t ccc_control; // CCC_CTL
uint32_t ccc_port_mask; // CCC_PORTS
uint32_t em_loc, em_ctl, cap2, bohc, reserved[53];
portregs p[32];
};
enum {
pcmd_interface_mask = 0xF0000000U,
pcmd_interface_active = 0x10000000U, pcmd_interface_idle = 0U,
pcmd_command_running = 0x8000, pcmd_rfis_running = 0x4000,
pcmd_rfis_enable = 0x0010,
pcmd_rfis_clear = 0x8, pcmd_power_up = 0x6, pcmd_start = 0x1U,
rstatus_busy = 0x80U, rstatus_datareq = 0x08U, rstatus_error = 0x01U,
interrupt_device_to_host = 0x1U,
interrupt_ncq_complete = 0x8U,
interrupt_error_mask = 0x7D800010U,
interrupt_fatal_error_mask = 0x78000000U, // HBFS|HBDS|IFS|TFES
ghc_ahci_enable = 0x80000000U, ghc_interrupt_enable = 0x2U
};
static inline bool sstatus_active(uint32_t sstatus) {
return (sstatus & 0x03) == 3
|| ((1U << ((sstatus & 0xF00) >> 8)) & 0x144) != 0;
}
// DMA structures for device communication
// Contains data buffers and commands for disk communication.
// This structure lives in host memory; the device finds it via
// physical-memory pointers in `portregs`.
struct bufstate { // initialized by `push_buffer`
uint64_t pa;
uint32_t reserved;
uint32_t maxbyte; // size of buffer minus 1
};
struct __attribute__((aligned(128))) cmdtable {
uint32_t cfis[16]; // command definition; set by `issue_*`
uint32_t acmd[4];
uint32_t reserved[12];
bufstate buf[16]; // called PRD in specifications
};
struct cmdheader {
uint16_t flags;
uint16_t nbuf;
uint32_t buf_byte_pos;
uint64_t cmdtable_pa; // physical address of `cmdtable`
uint64_t reserved[2];
};
struct __attribute__((aligned(256))) rfisstate {
uint32_t rfis[64];
};
struct __attribute__((aligned(1024))) dmastate {
cmdheader ch[32];
volatile rfisstate rfis;
cmdtable ct[32];
};
enum {
cfis_command = 0x8027,
ch_clear_flag = 0x400, ch_write_flag = 0x40
};
static constexpr size_t sectorsize = 512;
// DMA and memory-mapped I/O state
dmastate dma_;
int pci_addr_;
int sata_port_;
volatile regs* dr_;
volatile portregs* pr_;
// metadata read from disk at startup (constant thereafter)
unsigned irq_; // interrupt number
size_t nsectors_; // # sectors on disk
unsigned nslots_; // # NCQ slots
unsigned slots_full_mask_; // mask with each valid slot set to 1
// modifiable state
spinlock lock_;
wait_queue wq_;
unsigned nslots_available_; // # slots available for commands
uint32_t slots_outstanding_mask_; // 1 == that slot is used
volatile int* slot_status_[32]; // ptrs to status storage, one per slot
ahcistate(int pci_addr, int sata_port, volatile regs* mr);
NO_COPY_OR_ASSIGN(ahcistate);
static ahcistate* find(int pci_addr = 0, int sata_port = 0);
// high-level functions (they block)
inline int read(void* buf, size_t sz, size_t off);
inline int write(const void* buf, size_t sz, size_t off);
int read_or_write(idecommand cmd, void* buf, size_t sz, size_t off);
// interrupt handlers
void handle_interrupt();
void handle_error_interrupt();
// internal functions
void clear(int slot);
void push_buffer(int slot, void* data, size_t sz);
void issue_meta(int slot, idecommand cmd, int features, int count = -1);
void issue_ncq(int slot, idecommand cmd, size_t sector,
bool fua = false, int priority = 0);
void acknowledge(int slot, int status = 0);
void await_basic(int slot);
};
inline int ahcistate::read(void* buf, size_t sz, size_t off) {
return read_or_write(cmd_read_fpdma_queued, buf, sz, off);
}
inline int ahcistate::write(const void* buf, size_t sz, size_t off) {
return read_or_write(cmd_write_fpdma_queued, const_cast<void*>(buf),
sz, off);
}
#endif
| [
"ekohler@gmail.com"
] | ekohler@gmail.com |
dc28b7c00d60e61742c4ba6ec82fc2628c61b012 | 37b7f418beb3c37c273d9c60add94b7dc83fe0ac | /NeoML/src/Dnn/Layers/BinaryCrossEntropyLayer.cpp | 41f28172abca8d8967e5118763a8850799279016 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"NCSA",
"MIT",
"LicenseRef-scancode-protobuf",
"LicenseRef-scancode-arm-llvm-sga",
"Intel",
"LLVM-exception"
] | permissive | MTETERIN/neoml | d7ad604acdf9f5bc012e3d01461ebd650c7c0121 | 0a69f76507c194de092b82ed28bc55187cc8573b | refs/heads/master | 2022-12-11T18:15:23.312458 | 2020-09-03T15:11:42 | 2020-09-03T15:11:42 | 272,790,129 | 0 | 0 | NOASSERTION | 2020-09-03T15:11:43 | 2020-06-16T19:03:41 | null | UTF-8 | C++ | false | false | 6,262 | cpp | /* Copyright © 2017-2020 ABBYY Production LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------------------------------------------------*/
#include <common.h>
#pragma hdrstop
#include <NeoML/Dnn/Layers/LossLayer.h>
namespace NeoML {
CBinaryCrossEntropyLossLayer::CBinaryCrossEntropyLossLayer( IMathEngine& mathEngine ) :
CLossLayer( mathEngine, "CCnnBinaryCrossEntropyLossLayer" ),
positiveWeightMinusOneValue( 0 )
{
}
void CBinaryCrossEntropyLossLayer::SetPositiveWeight( float value )
{
positiveWeightMinusOneValue = value - 1;
}
float CBinaryCrossEntropyLossLayer::GetPositiveWeight() const
{
return positiveWeightMinusOneValue + 1;
}
void CBinaryCrossEntropyLossLayer::BatchCalculateLossAndGradient( int batchSize, CConstFloatHandle data, int vectorSize,
CConstFloatHandle label, int labelSize, CFloatHandle lossValue, CFloatHandle lossGradient )
{
// This layer can only work with a binary classificaion problem
// Therefore the labels vector can only contain {-1, 1} values
NeoAssert(vectorSize == 1 && labelSize == 1);
CFloatHandleStackVar one( MathEngine() );
one.SetValue( 1.f );
CFloatHandleStackVar half( MathEngine() );
half.SetValue( 0.5f );
CFloatHandleStackVar minusOne( MathEngine() );
minusOne.SetValue( -1.f );
CFloatHandleStackVar zero( MathEngine() );
zero.SetValue( 0.f );
CFloatHandleStackVar positiveWeightMinusOne( MathEngine() );
positiveWeightMinusOne.SetValue( positiveWeightMinusOneValue );
// Convert the target values to [0, 1] range using the binaryLabel = 0.5 * ( label + 1 ) formula
CFloatHandleStackVar binaryLabel( MathEngine(), batchSize );
MathEngine().VectorAddValue( label, binaryLabel, batchSize, one );
MathEngine().VectorMultiply( binaryLabel, binaryLabel, batchSize, half );
// Notations:
// x = logits, z = labels, q = pos_weight, l = 1 + (q - 1) * z
// The original loss function formula:
// loss = (1 - z) * x + l * log(1 + exp(-x))
// The formula to avoid overflow for large exponent power in exp(-x):
// loss = (1 - z) * x + l * (log(1 + exp(-abs(x))) + max(-x, 0))
// (1-z)*x
CFloatHandleStackVar temp( MathEngine(), batchSize);
MathEngine().VectorAddValue( binaryLabel, temp, batchSize, minusOne );
MathEngine().VectorEltwiseNegMultiply( temp, data, temp, batchSize );
// l = (1 + (q - 1) * z),
CFloatHandleStackVar temp2( MathEngine(), batchSize );
MathEngine().VectorMultiply( binaryLabel, temp2, batchSize, positiveWeightMinusOne );
MathEngine().VectorAddValue( temp2, temp2, batchSize, one );
// max(-x, 0)
CFloatHandleStackVar temp3( MathEngine(), batchSize );
MathEngine().VectorNegMultiply( data, temp3, batchSize, one );
MathEngine().VectorReLU( temp3, temp3, batchSize, zero );
// log( 1 + e^-|x|)
CFloatHandleStackVar temp4( MathEngine(), batchSize );
MathEngine().VectorAbs( data, temp4, batchSize );
MathEngine().VectorNegMultiply( temp4, temp4, batchSize, one );
MathEngine().VectorExp( temp4, temp4, batchSize );
MathEngine().VectorAddValue( temp4, temp4, batchSize, one );
MathEngine().VectorLog( temp4, temp4, batchSize );
// l * (log(1 + exp(-abs(x))) + max(-x, 0))
MathEngine().VectorAdd( temp3, temp4, lossValue, batchSize );
MathEngine().VectorEltwiseMultiply( lossValue, temp2, lossValue, batchSize );
// The loss
MathEngine().VectorAdd( lossValue, temp, lossValue, batchSize );
if( !lossGradient.IsNull() ) {
// loss' = (1-z) - l / ( 1+exp(x) ) = (1-z) - l * sigmoid(-x)
// (z-1)
CFloatHandleStackVar temp5( MathEngine(), batchSize );
MathEngine().VectorAddValue( binaryLabel, temp5, batchSize, minusOne );
// -x
CFloatHandleStackVar temp6( MathEngine(), batchSize );
MathEngine().VectorNegMultiply( data, temp6, batchSize, one );
// sigmoid(-x)
calculateStableSigmoid( temp6, temp6, batchSize );
//MathEngine().VectorSigmoid( temp6, temp6, batchSize );
// l * sigmoid(-x)
MathEngine().VectorEltwiseMultiply( temp6, temp2, temp6, batchSize );
// (z-1) + l * sigmoid(-x)
MathEngine().VectorAdd( temp5, temp6, lossGradient, batchSize );
//(1-z) - l * sigmoid(-x)
MathEngine().VectorNegMultiply( lossGradient, lossGradient, batchSize, one );
}
}
// Overflow-safe sigmoid calculation
void CBinaryCrossEntropyLossLayer::calculateStableSigmoid( const CConstFloatHandle& firstHandle,
const CFloatHandle& resultHandle, int vectorSize ) const
{
CFloatHandleStackVar one( MathEngine() );
one.SetValue( 1.f );
CFloatHandleStackVar zero( MathEngine() );
zero.SetValue( 0.f );
// The sigmoid formula:
// Sigmoid(x) = 1 / (1 + e^-x )
// The formula to avoid overflow for large exponent power in exp(-x):
// Sigmoid(x) = e^(-max(-x, 0) ) / ( 1 + e^-|x| )
// e^(-max(-x, 0) )
CFloatHandleStackVar temp( MathEngine(), vectorSize );
MathEngine().VectorNegMultiply( firstHandle, temp, vectorSize, one );
MathEngine().VectorReLU( temp, temp, vectorSize, zero );
MathEngine().VectorNegMultiply( temp, temp, vectorSize, one );
MathEngine().VectorExp( temp, temp, vectorSize );
// ( 1 + e^-|x| )
CFloatHandleStackVar temp2( MathEngine(), vectorSize );
MathEngine().VectorAbs( firstHandle, temp2, vectorSize );
MathEngine().VectorNegMultiply( temp2, temp2, vectorSize, one );
MathEngine().VectorExp( temp2, temp2, vectorSize );
MathEngine().VectorAddValue( temp2, temp2, vectorSize, one );
// The sigmoid
MathEngine().VectorEltwiseDivide( temp, temp2, resultHandle, vectorSize );
}
static const int BinaryCrossEntropyLossLayerVersion = 2000;
void CBinaryCrossEntropyLossLayer::Serialize( CArchive& archive )
{
archive.SerializeVersion( BinaryCrossEntropyLossLayerVersion, CDnn::ArchiveMinSupportedVersion );
CLossLayer::Serialize( archive );
archive.Serialize( positiveWeightMinusOneValue );
}
} // namespace NeoML
| [
"buildtech@abbyy.com"
] | buildtech@abbyy.com |
a2f2381089a7d9b9465fcaef40e21bb1b35f3945 | b1aa9ad6733efcb53d465809d5109e9174dabf04 | /CCode/EngineCode/C4Types.h | 0e0d64761046b521373b53758f2f305a976a5d8b | [] | no_license | dumpinfo/GameMatrixTest | d21545dbef9ade76fe092343a8362da4c8b142ca | 9e4a73ad17555ddb90020c47e2486698b90e4d0d | refs/heads/master | 2023-02-04T01:52:05.342214 | 2020-12-23T17:22:36 | 2020-12-23T17:22:36 | 323,961,033 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,839 | h |
#ifndef C4Types_h
#define C4Types_h
//# \component Utility Library
//# \prefix Utilities/
#include "C4Constants.h"
#include "C4Shared.h"
#include "C4Array.h"
#include "C4Tree.h"
#include "C4Graph.h"
#include "C4Map.h"
#include "C4Hash.h"
#include "C4Link.h"
#include "C4Rect.h"
#include "C4String.h"
#include "C4Complex.h"
#include "C4Bivector4D.h"
#include "C4Quaternion.h"
#include "C4Completable.h"
#include "C4Observable.h"
namespace C4
{
typedef unsigned_int32 Type;
typedef Type EventType;
//# \enum KeyCode
enum
{
kKeyCodeEnter = 13, //## The enter key (return key on the Mac).
kKeyCodeEscape = 27, //## The escape key.
kKeyCodeTab = 9, //## The tab key.
kKeyCodeLeftArrow = 28, //## The left arrow key.
kKeyCodeRightArrow = 29, //## The right arrow key.
kKeyCodeUpArrow = 30, //## The up arrow key.
kKeyCodeDownArrow = 31, //## The down arrow key.
kKeyCodePageUp = 11, //## The page up key.
kKeyCodePageDown = 12, //## The page down key.
kKeyCodeHome = 1, //## The home key.
kKeyCodeEnd = 4, //## The end key.
kKeyCodeDelete = 2, //## The delete key.
kKeyCodeBackspace = 8, //## The backspace key.
kKeyCodeF1 = 128, //## The F1 key.
kKeyCodeF2, //## The F2 key.
kKeyCodeF3, //## The F3 key.
kKeyCodeF4, //## The F4 key.
kKeyCodeF5, //## The F5 key.
kKeyCodeF6, //## The F6 key.
kKeyCodeF7, //## The F7 key.
kKeyCodeF8, //## The F8 key.
kKeyCodeF9, //## The F9 key.
kKeyCodeF10, //## The F10 key.
kKeyCodeF11, //## The F11 key.
kKeyCodeF12, //## The F12 key.
kKeyCodeF13,
kKeyCodeF14,
kKeyCodeF15,
kKeyCodeF16,
kKeyCodeF17,
kKeyCodeF18,
kKeyCodeF19,
kKeyCodeF20,
kKeyCodeF21,
kKeyCodeF22,
kKeyCodeF23,
kKeyCodeF24
};
//# \enum MouseEventFlags
enum
{
kMouseDoubleClick = 1 << 0 //## The mouse down event is the second click in a double-click.
};
//# \enum KeyboardModifiers
enum
{
kModifierKeyShift = 1 << 0, //## The shift key was held down.
kModifierKeyOption = 1 << 1, //## The alt key (option key on the Mac) was held down.
kModifierKeyCommand = 1 << 2, //## The control key (command key on the Mac) was held down.
kModifierKeyConsole = 1 << 16
};
enum : EventType
{
kEventNone = 0,
kEventMouseDown = 'MSDN',
kEventMouseUp = 'MSUP',
kEventRightMouseDown = 'RMDN',
kEventRightMouseUp = 'RMUP',
kEventMiddleMouseDown = 'MMDN',
kEventMiddleMouseUp = 'MMUP',
kEventMouseMoved = 'MSMV',
kEventMouseWheel = 'MSWH',
kEventMultiaxisMouseTranslation = 'MATR',
kEventMultiaxisMouseRotation = 'MART',
kEventMultiaxisMouseButtonState = 'MABS',
kEventKeyDown = 'KYDN',
kEventKeyUp = 'KYUP',
kEventKeyCommand = 'KYCM'
};
//# \struct MouseEventData Contains information about a mouse event.
//
//# The $MouseEventData$ structure contains information about a mouse event.
//
//# \def struct MouseEventData
//
//# \data MouseEventData
//
//# \desc
//# The $MouseEventData$ structure contains the event type, mouse position, and special flags
//# for a mouse event. The $eventFlags$ field can be a combination (through logical OR) of the
//# following constants.
//
//# \table MouseEventFlags
//
//# \also $@KeyboardEventData@$
//# \member MouseEventData
struct MouseEventData
{
EventType eventType; //## The type of mouse event.
unsigned_int32 eventFlags; //## The event flags for the event.
Point3D mousePosition; //## The mouse position associated with the event.
Vector2D wheelDelta; //## The wheel delta for $kEventMouseWheel$ events.
};
//# \struct KeyboardEventData Contains information about a keyboard event.
//
//# The $KeyboardEventData$ structure contains information about a keyboard event.
//
//# \def struct KeyboardEventData
//
//# \data KeyboardEventData
//
//# \desc
//# The $KeyboardEventData$ structure contains the type of event, the Unicode character, and
//# information about modifiers keys for a keyboard event. The $keyCode$ field is set to one of
//# the following values if a special key is pressed or released.
//
//# \table KeyCode
//
//# Special keys always have codes in the ranges [0x01, 0x1F] or [0x80, 0x9F], and keyboard event handlers
//# should not attempt to handle codes in these ranges as ordinary characters.
//#
//# The $modifierKeys$ field can be a combination (through logical OR) of the following constants.
//
//# \table KeyboardModifiers
//
//# \also $@MouseEventData@$
//# \member KeyboardEventData
struct KeyboardEventData
{
EventType eventType; //## The type of keyboard event.
unsigned_int32 keyCode; //## The Unicode value for the character associated with the event.
unsigned_int32 modifierKeys; //## The modifier keys associated with the event.
};
//# \class Range Encapsulates a range of values.
//
//# The $Range$ class template encapsulates a range of values.
//
//# \def template <typename type> struct Range
//
//# \tparam type The type of value used to represent the beginning and end of a range.
//
//# \data Range
//
//# \ctor Range();
//# \ctor Range(const type& x, const type& y);
//
//# \param x The beginning of the range.
//# \param y The end of the range.
//
//# \desc
//# The $Range$ class template encapsulates a range of values of the type given by the
//# $type$ class template.
//#
//# The default constructor leaves the beginning and end values of the range undefined.
//# If the values $x$ and $y$ are supplied, then they are assigned to the beginning and
//# end of the range, respectively.
//
//# \operator type& operator [](machine index);
//# Returns a reference to the minimum value if $index$ is 0, and returns a reference to the maximum value if $index$ is 1.
//# The $index$ parameter must be 0 or 1.
//
//# \operator const type& operator [](machine index) const;
//# Returns a constant reference to the minimum value if $index$ is 0, and returns a constant reference to the maximum value if $index$ is 1.
//# The $index$ parameter must be 0 or 1.
//
//# \operator bool operator ==(const Range& range) const;
//# Returns a boolean value indicating the equality of two ranges.
//
//# \operator bool operator !=(const Range& range) const;
//# Returns a boolean value indicating the inequality of two ranges.
//# \function Range::Set Sets the beginning and end of a range.
//
//# \proto Range& Set(const type& x, const type& y);
//
//# \param x The new beginning of the range.
//# \param y The new end of the range.
//
//# \desc
//# The $Set$ function sets the beginning and end of a range to the values given by the
//# $x$ and $y$ parameters, respectively.
//# \member Range
template <typename type> struct Range
{
type min; //## The beginning of the range.
type max; //## The end of the range.
Range() = default;
Range(const Range& range)
{
min = range.min;
max = range.max;
}
Range(const type& x, const type& y)
{
min = x;
max = y;
}
type& operator [](machine index)
{
return ((&min)[index]);
}
const type& operator [](machine index) const
{
return ((&min)[index]);
}
Range& operator =(const Range& range)
{
min = range.min;
max = range.max;
return (*this);
}
Range& Set(const type& x, const type& y)
{
min = x;
max = y;
return (*this);
}
bool operator ==(const Range& range) const
{
return ((min == range.min) && (max == range.max));
}
bool operator !=(const Range& range) const
{
return ((min != range.min) || (max != range.max));
}
};
//# \class Transformable Encapsulates an object-to-world transform and its inverse.
//
//# The $Transformable$ class encapsulates an object-to-world transform and its inverse.
//
//# \def class Transformable
//
//# \ctor Transformable();
//
//# \desc
//# The $Transformable$ class encapsulates a transform from object space to world space
//# and maintains the corresponding inverse transform from world space to object space.
//#
//# The constructor leaves the transform undefined.
//# \function Transformable::SetIdentityTransform Sets the transform to the identity.
//
//# \proto void SetIdentityTransform(void);
//
//# \desc
//# The $SetIdentityTransform$ function sets both the object-to-world transform and its
//# inverse to the identity transform.
//
//# \also $@Transformable::SetWorldTransform@$
//# \also $@Transformable::SetWorldPosition@$
//# \function Transformable::GetWorldTransform Returns the object-to-world transform.
//
//# \proto const Transform4D& GetWorldTransform(void) const;
//
//# \desc
//# The $GetWorldTransform$ returns the $@Math/Transform4D@$ object corresponding to the
//# transform from object space to world space.
//
//# \also $@Transformable::GetInverseWorldTransform@$
//# \also $@Transformable::SetWorldTransform@$
//# \also $@Transformable::GetWorldPosition@$
//# \also $@Transformable::SetWorldPosition@$
//# \function Transformable::GetInverseWorldTransform Returns the world-to-object transform.
//
//# \proto const Transform4D& GetInverseWorldTransform(void) const;
//
//# \desc
//# The $GetInverseWorldTransform$ returns the $@Math/Transform4D@$ object corresponding to the
//# transform from world space to object space. The inverse is not calculated at the time
//# this function is called, but when the transform is set, so the performance of this function
//# is high.
//
//# \also $@Transformable::GetWorldTransform@$
//# \also $@Transformable::SetWorldTransform@$
//# \also $@Transformable::GetWorldPosition@$
//# \also $@Transformable::SetWorldPosition@$
//# \function Transformable::SetWorldTransform Sets the object-to-world transform and its inverse.
//
//# \proto void SetWorldTransform(const Transform4D& transform);
//# \proto void SetWorldTransform(const Matrix3D& m, const Point3D& p);
//# \proto void SetWorldTransform(const Vector3D& c1, const Vector3D& c2, const Vector3D& c3, const Point3D& c4);
//# \proto void SetWorldTransform(float n00, float n01, float n02, float n03, float n10, float n11, float n12, float n13, float n20, float n21, float n22, float n23);
//
//# \param transform The new transform.
//# \param m The upper-left 3 × 3 portion of the 4D transform.
//# \param p The fourth column of the 4D transform, representing the world position.
//# \param c1 The first column of the 4D transform.
//# \param c2 The second column of the 4D transform.
//# \param c3 The third column of the 4D transform.
//# \param c4 The fourth column of the 4D transform.
//# \param nij The entry residing in row <i>i</i> and column <i>j</i> of the 4D transform.
//
//# \desc
//# The $SetWorldTransform$ function sets the object-to-world transform. It also calculates
//# and stores the inverse representing the transform from world space to object space.
//
//# \warning
//# The $SetWorldTransform$ function is normally called only by internal components of the engine
//# during routine update procedures. This function should not be called by external code to directly
//# set the world transform of an object.
//
//# \also $@Transformable::GetWorldTransform@$
//# \also $@Transformable::GetWorldPosition@$
//# \also $@Transformable::SetWorldPosition@$
//# \also $@Transformable::SetIdentityTransform@$
//# \function Transformable::GetWorldPosition Returns the world-space position.
//
//# \proto const Point3D& GetWorldPosition(void) const;
//
//# \desc
//# The $GetWorldPosition$ function returns the world-space position represented by a
//# transform. Calling $GetWorldPosition$ is equivalent to the following.
//
//# \source
//# GetWorldTransform().GetTranslation();
//
//# \also $@Transformable::SetWorldPosition@$
//# \also $@Transformable::GetWorldTransform@$
//# \also $@Transformable::SetWorldTransform@$
//# \function Transformable::SetWorldPosition Sets the world-space position.
//
//# \proto void SetWorldPosition(const Point3D& position);
//
//# \param position The new world-space position.
//
//# \desc
//# The $SetWorldPosition$ function sets the world-space position to that given by the
//# $position$ parameter and recalculates the inverse transform from world space to object space.
//# The upper-left 3 × 3 portion of the 4D transform is not affected.
//
//# \warning
//# The $SetWorldPosition$ function is normally called only by internal components of the engine
//# during routine update procedures. This function should not be called by external code to directly
//# set the world position of an object.
//
//# \also $@Transformable::GetWorldPosition@$
//# \also $@Transformable::GetWorldTransform@$
//# \also $@Transformable::SetWorldTransform@$
class Transformable
{
private:
Transform4D worldTransform;
Transform4D inverseWorldTransform;
public:
Transformable() = default;
void SetIdentityTransform(void)
{
worldTransform.SetIdentity();
inverseWorldTransform.SetIdentity();
}
const Transform4D& GetWorldTransform(void) const
{
return (worldTransform);
}
const Point3D& GetWorldPosition(void) const
{
return (worldTransform.GetTranslation());
}
const Transform4D& GetInverseWorldTransform(void) const
{
return (inverseWorldTransform);
}
void SetWorldTransform(const Transform4D& transform)
{
worldTransform = transform;
inverseWorldTransform = Inverse(worldTransform);
}
void SetWorldTransform(const Matrix3D& m, const Point3D& p)
{
worldTransform.Set(m, p);
inverseWorldTransform = Inverse(worldTransform);
}
void SetWorldTransform(const Vector3D& c1, const Vector3D& c2, const Vector3D& c3, const Point3D& c4)
{
worldTransform.Set(c1, c2, c3, c4);
inverseWorldTransform = Inverse(worldTransform);
}
void SetWorldTransform(float n00, float n01, float n02, float n03, float n10, float n11, float n12, float n13, float n20, float n21, float n22, float n23)
{
worldTransform.Set(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23);
inverseWorldTransform = Inverse(worldTransform);
}
void SetWorldPosition(const Point3D& position)
{
worldTransform.SetTranslation(position);
inverseWorldTransform = Inverse(worldTransform);
}
};
template <class type> class Reference : public ListElement<Reference<type>>
{
private:
type *referenceTarget;
public:
explicit Reference(type *target)
{
referenceTarget = target;
}
~Reference()
{
}
type *GetTarget(void) const
{
return (referenceTarget);
}
};
template <class type> class AutoDelete
{
private:
type *reference;
AutoDelete(const AutoDelete&) = delete;
public:
explicit AutoDelete(type *ptr)
{
reference = ptr;
}
~AutoDelete()
{
delete reference;
}
operator type *(void) const
{
return (reference);
}
type *const *operator &(void) const
{
return (&reference);
}
type *operator ->(void) const
{
return (reference);
}
AutoDelete& operator =(type *ptr)
{
reference = ptr;
return (*this);
}
};
class Buffer
{
private:
char *buffer;
public:
explicit Buffer(unsigned_int32 size)
{
buffer = new char[size];
}
~Buffer()
{
delete[] buffer;
}
operator void *(void) const
{
return (buffer);
}
template <typename type> type *GetPtr(void) const
{
return (reinterpret_cast<type *>(buffer));
}
};
template <class type> class Storage
{
private:
alignas(16) char storage[sizeof(type)];
public:
operator type *(void)
{
return (reinterpret_cast<type *>(storage));
}
operator const type *(void) const
{
return (reinterpret_cast<const type *>(storage));
}
type *operator ->(void)
{
return (reinterpret_cast<type *>(storage));
}
const type *operator ->(void) const
{
return (reinterpret_cast<const type *>(storage));
}
};
}
#endif
// ZYUQURM
| [
"twtravel@126.com"
] | twtravel@126.com |
39ba27017847feb75d267b8e7dc07a34fe07448c | e2400461ad0ee9db8a85a30c811e47d30e16e1c8 | /seleniumtestcases-qa/seleniumtestcases-qa/src/main/resources/firefox/win64/firefox-sdk/include/nsIDOMSerializer.h | 5872abef473cde998cd028f472db4047b936caa0 | [] | no_license | pratikcactus/Insights | 720a00187858bbca5b2d8cc36aee23e50c74efbc | 0c3178a50d60ba4c14a07f6515a84f0ce22cdc8e | refs/heads/master | 2021-01-19T14:48:56.139872 | 2018-01-23T07:12:47 | 2018-01-23T07:12:47 | 100,924,200 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,265 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM ../../../dist/idl\nsIDOMSerializer.idl
*/
#ifndef __gen_nsIDOMSerializer_h__
#define __gen_nsIDOMSerializer_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIOutputStream; /* forward declaration */
class nsIDOMNode; /* forward declaration */
/* starting interface: nsIDOMSerializer */
#define NS_IDOMSERIALIZER_IID_STR "9fd4ba15-e67c-4c98-b52c-7715f62c9196"
#define NS_IDOMSERIALIZER_IID \
{0x9fd4ba15, 0xe67c, 0x4c98, \
{ 0xb5, 0x2c, 0x77, 0x15, 0xf6, 0x2c, 0x91, 0x96 }}
class NS_NO_VTABLE nsIDOMSerializer : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMSERIALIZER_IID)
/* AString serializeToString (in nsIDOMNode root); */
NS_IMETHOD SerializeToString(nsIDOMNode *root, nsAString & _retval) = 0;
/* void serializeToStream (in nsIDOMNode root, in nsIOutputStream stream, in AUTF8String charset); */
NS_IMETHOD SerializeToStream(nsIDOMNode *root, nsIOutputStream *stream, const nsACString & charset) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMSerializer, NS_IDOMSERIALIZER_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMSERIALIZER \
NS_IMETHOD SerializeToString(nsIDOMNode *root, nsAString & _retval) override; \
NS_IMETHOD SerializeToStream(nsIDOMNode *root, nsIOutputStream *stream, const nsACString & charset) override;
/* Use this macro when declaring the members of this interface when the
class doesn't implement the interface. This is useful for forwarding. */
#define NS_DECL_NON_VIRTUAL_NSIDOMSERIALIZER \
NS_METHOD SerializeToString(nsIDOMNode *root, nsAString & _retval); \
NS_METHOD SerializeToStream(nsIDOMNode *root, nsIOutputStream *stream, const nsACString & charset);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMSERIALIZER(_to) \
NS_IMETHOD SerializeToString(nsIDOMNode *root, nsAString & _retval) override { return _to SerializeToString(root, _retval); } \
NS_IMETHOD SerializeToStream(nsIDOMNode *root, nsIOutputStream *stream, const nsACString & charset) override { return _to SerializeToStream(root, stream, charset); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMSERIALIZER(_to) \
NS_IMETHOD SerializeToString(nsIDOMNode *root, nsAString & _retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SerializeToString(root, _retval); } \
NS_IMETHOD SerializeToStream(nsIDOMNode *root, nsIOutputStream *stream, const nsACString & charset) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SerializeToStream(root, stream, charset); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsDOMSerializer : public nsIDOMSerializer
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIDOMSERIALIZER
nsDOMSerializer();
private:
~nsDOMSerializer();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS(nsDOMSerializer, nsIDOMSerializer)
nsDOMSerializer::nsDOMSerializer()
{
/* member initializers and constructor code */
}
nsDOMSerializer::~nsDOMSerializer()
{
/* destructor code */
}
/* AString serializeToString (in nsIDOMNode root); */
NS_IMETHODIMP nsDOMSerializer::SerializeToString(nsIDOMNode *root, nsAString & _retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void serializeToStream (in nsIDOMNode root, in nsIOutputStream stream, in AUTF8String charset); */
NS_IMETHODIMP nsDOMSerializer::SerializeToStream(nsIDOMNode *root, nsIOutputStream *stream, const nsACString & charset)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#define NS_XMLSERIALIZER_CID \
{ /* a6cf9124-15b3-11d2-932e-00805f8add32 */ \
0xa6cf9124, 0x15b3, 0x11d2, \
{0x93, 0x2e, 0x00, 0x80, 0x5f, 0x8a, 0xdd, 0x32} }
#define NS_XMLSERIALIZER_CONTRACTID \
"@mozilla.org/xmlextras/xmlserializer;1"
#endif /* __gen_nsIDOMSerializer_h__ */
| [
"pratik.sidam@cactusglobal.com"
] | pratik.sidam@cactusglobal.com |
69cfba894bd98e90fafb56c1bdcbd4534b7a83e4 | 124e8db708315c87eae0e4ee559612138ac79ce3 | /Server/NetworkControler.cpp | d319719a98aead7fc9e2dd86bb2a1a2877b13d14 | [] | no_license | protective/anno3112 | 7e2beec4a0a9892fb084d9237baf770cab655c81 | 8de8a12880501876d89893d9ed92d118c14ffe38 | refs/heads/master | 2021-01-22T23:54:32.286050 | 2014-09-27T20:27:59 | 2014-09-27T20:27:59 | 15,630,219 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,992 | cpp | /*
* File: NetworkControler.cpp
* Author: karsten
*
* Created on 22. februar 2014, 23:13
*/
#include "NetworkControler.h"
#include "Client.h"
#include "Sspacebjects/SSubAble.h"
#include "Commands/Processable.h"
NetworkControler::NetworkControler() {
pthread_mutex_init(&_clientLock ,NULL);
}
void NetworkControler::readBuffers(){
for (map<uint32_t, Client*>::iterator ci = _connections.begin(); ci != _connections.end(); ci++){
ReadBuffer(ci->second);
ci->second->proces();
}
}
void NetworkControler::registerObj(uint32_t objId, Processor* processor){
pthread_mutex_lock(&_objRegistrationListLock);
_objRegistration[objId] = processor;
//cerr<<"networkcontroler::register obj_id="<<objId<<" processerid="<<(uint32_t)processor->getId()<<endl;
//TODO GET all processores dealing with the active grid here
//cerr<<"register id="<<objId<<endl;
processor->addCommand(new CommandAddSubscriptions(processor,SubscriptionLevel::lowFreq,objId));
processor->addCommand(new CommandAddSubscriptions(processor,SubscriptionLevel::Init,objId));
pthread_mutex_unlock(&_objRegistrationListLock);
}
void NetworkControler::deRegisterObj(uint32_t objId){
pthread_mutex_lock(&_objRegistrationListLock);
_objRegistration.erase(objId);
pthread_mutex_unlock(&_objRegistrationListLock);
}
Processor* NetworkControler::getProcessor(uint32_t objId){
Processor* temp;
map<uint32_t, Processor*>::iterator it;
pthread_mutex_lock(&_objRegistrationListLock);
it = _objRegistration.find(objId);
temp = it != _objRegistration.end() ? it->second : NULL;
pthread_mutex_unlock(&_objRegistrationListLock);
return temp;
}
Processable* NetworkControler::getProcessable(uint32_t objId){
Processor* temp = getProcessor(objId);
if(!temp)
return NULL;
map<uint32_t, Processable*>::iterator it = temp->getLocalProcssables().find(objId);
if (it != temp->getLocalProcssables().end()){
return it->second;
}
return NULL;
}
uint32_t NetworkControler::addCommandToProcesable(Command* cmd, uint32_t obj){
Processor* temp = getProcessor(obj);
if(temp)
return temp->addCommand(cmd);
return 1;
}
uint32_t NetworkControler::sendToC(uint32_t id, void* block, uint32_t len){
bool sendt = false;
//cerr<<"send to c= "<<id<<endl;
pthread_mutex_lock(&_clientLock);
map<uint32_t, Client*>::iterator it = _connections.find(id);
if (it!= _connections.end()){
//cerr<<"network send len ="<<len<<endl;
send(it->second->getSocket(),block, len,MSG_NOSIGNAL);
sendt = true;
}else
cerr<<"ERROR CLIENT NOT FOUND"<<endl;
pthread_mutex_unlock(&_clientLock);
if(sendt)
return 0;
else
return 1;
}
void NetworkControler::addClient(Client* client){
cerr<<"add cli before lock"<<endl;
pthread_mutex_lock(&_clientLock);
cerr<<"add cli ="<<client->getId()<<endl;
_connections[client->getId()] = client;
pthread_mutex_unlock(&_clientLock);
}
void NetworkControler::removeClient(Client* client){
_connections.erase(client->getId());
}
NetworkControler::~NetworkControler() {
}
| [
"karstenjjakobsen@gmail.com"
] | karstenjjakobsen@gmail.com |
c533a66a590a143c01c77206870bbfc6763fdc32 | 5d2d6a0f5f9f12756ed9a80ef4daede2e7d7a320 | /includes/Drawable.hh | 80c54cd2b634d3cfc98bedde6b9a88ca01fa6342 | [] | no_license | z363989254/Bomberman | f1641e77cf73dbd7ef809b60dc2c943cd85d5192 | 46c2000ea54fb1ab946849b7589a3dc06ffb795f | refs/heads/master | 2021-01-06T23:53:37.335149 | 2015-09-08T15:49:43 | 2015-09-08T15:49:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 696 | hh | //
// Background.hh for Bomberman in /home/magrin_j/Project/Bomberman
//
// Made by Jérémy Magrin
// Login <magrin_j@epitech.net>
//
// Started on Fri Jun 7 17:11:05 2013 Jérémy Magrin
// Last update Sun Jun 9 21:51:23 2013 leo chazal
//
#pragma once
#include <Image.hpp>
namespace Bomberman
{
class Drawable
{
private:
gdl::Image _drawables[11];
public:
static Drawable *getInstance(void);
static void pushOrthoMatrix(float, float);
static void popOrthoMatrix(void);
static void drawAt(float, float, float, float,
gdl::Image &);
void drawBg(size_t);
private:
Drawable();
~Drawable();
void initialize(void);
};
}
| [
"bhullnatik@gmail.com"
] | bhullnatik@gmail.com |
0b37ddd685c341ed620d21eae4aecb7d7d805731 | eb5cf33b808de4f35f836cc90715be601c19144a | /Classes/AppDelegate.cpp | 4b1cf5455116607b1e616caf4221d5c70edfe774 | [] | no_license | kevenxiang/actual_chap06 | 8202f5956931a43499bb0d1d7f92e84922cdd7eb | 102e07e9f37bac416af30aab1ce3c54a5ab86c0f | refs/heads/master | 2020-12-03T03:45:06.698976 | 2017-06-29T11:08:46 | 2017-06-29T11:08:46 | 95,769,576 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,446 | cpp | #include "AppDelegate.h"
#include "HelloWorldScene.h"
#include "TouchOneByOneTest.hpp"
#include "ContentLayer.hpp"
#include "TouchPriorityTest.hpp"
#include "AccelerometerTest.hpp"
#include "CustomTest.hpp"
// #define USE_AUDIO_ENGINE 1
// #define USE_SIMPLE_AUDIO_ENGINE 1
#if USE_AUDIO_ENGINE && USE_SIMPLE_AUDIO_ENGINE
#error "Don't use AudioEngine and SimpleAudioEngine at the same time. Please just select one in your game!"
#endif
#if USE_AUDIO_ENGINE
#include "audio/include/AudioEngine.h"
using namespace cocos2d::experimental;
#elif USE_SIMPLE_AUDIO_ENGINE
#include "audio/include/SimpleAudioEngine.h"
using namespace CocosDenshion;
#endif
USING_NS_CC;
static cocos2d::Size designResolutionSize = cocos2d::Size(480, 320);
static cocos2d::Size smallResolutionSize = cocos2d::Size(480, 320);
static cocos2d::Size mediumResolutionSize = cocos2d::Size(1024, 768);
static cocos2d::Size largeResolutionSize = cocos2d::Size(2048, 1536);
AppDelegate::AppDelegate()
{
}
AppDelegate::~AppDelegate()
{
#if USE_AUDIO_ENGINE
AudioEngine::end();
#elif USE_SIMPLE_AUDIO_ENGINE
SimpleAudioEngine::end();
#endif
}
// if you want a different context, modify the value of glContextAttrs
// it will affect all platforms
void AppDelegate::initGLContextAttrs()
{
// set OpenGL context attributes: red,green,blue,alpha,depth,stencil
GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
GLView::setGLContextAttrs(glContextAttrs);
}
// if you want to use the package manager to install more packages,
// don't modify or remove this function
static int register_all_packages()
{
return 0; //flag for packages manager
}
bool AppDelegate::applicationDidFinishLaunching() {
// initialize director
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if(!glview) {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
glview = GLViewImpl::createWithRect("actual_chap06", cocos2d::Rect(0, 0, designResolutionSize.width, designResolutionSize.height));
#else
glview = GLViewImpl::create("actual_chap06");
#endif
director->setOpenGLView(glview);
}
// turn on display FPS
director->setDisplayStats(true);
// set FPS. the default value is 1.0/60 if you don't call this
director->setAnimationInterval(1.0f / 60);
// Set the design resolution
glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::NO_BORDER);
auto frameSize = glview->getFrameSize();
// if the frame's height is larger than the height of medium size.
if (frameSize.height > mediumResolutionSize.height)
{
director->setContentScaleFactor(MIN(largeResolutionSize.height/designResolutionSize.height, largeResolutionSize.width/designResolutionSize.width));
}
// if the frame's height is larger than the height of small size.
else if (frameSize.height > smallResolutionSize.height)
{
director->setContentScaleFactor(MIN(mediumResolutionSize.height/designResolutionSize.height, mediumResolutionSize.width/designResolutionSize.width));
}
// if the frame's height is smaller than the height of medium size.
else
{
director->setContentScaleFactor(MIN(smallResolutionSize.height/designResolutionSize.height, smallResolutionSize.width/designResolutionSize.width));
}
register_all_packages();
// create a scene. it's an autorelease object
auto scene = CustomTest::createScene();
// run
director->runWithScene(scene);
return true;
}
// This function will be called when the app is inactive. Note, when receiving a phone call it is invoked.
void AppDelegate::applicationDidEnterBackground() {
Director::getInstance()->stopAnimation();
#if USE_AUDIO_ENGINE
AudioEngine::pauseAll();
#elif USE_SIMPLE_AUDIO_ENGINE
SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
SimpleAudioEngine::getInstance()->pauseAllEffects();
#endif
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() {
Director::getInstance()->startAnimation();
#if USE_AUDIO_ENGINE
AudioEngine::resumeAll();
#elif USE_SIMPLE_AUDIO_ENGINE
SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
SimpleAudioEngine::getInstance()->resumeAllEffects();
#endif
}
| [
"1806322519@qq.com"
] | 1806322519@qq.com |
6fd7e86a822a3f9898da38c5754fc586ccf2fb6a | 7e38fc9705e48e4a7e6a003a8c414e8c3999424b | /CELib/TlsDevice.h | 285380e63b08cd42ee4260465a84ebf68ecb9041 | [] | no_license | vivianng30/rainer-fabian-gui | e5118df24ed6eab51b819499e0680b804e7eb87a | 2ca6f43513487fdf9a10c9354736449b300e21b5 | refs/heads/master | 2020-03-28T11:11:26.391374 | 2018-09-20T13:48:54 | 2018-09-20T13:48:54 | 148,186,875 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,334 | h | //=============================================================================
//=============================================================================
#ifndef __TLS_DEVICE_H__
#define __TLS_DEVICE_H__
#include <iphlpapi.h>
//===========================================================================//
class CTlsDevice
{
public:
CTlsDevice();
virtual ~CTlsDevice();
/*int GetVersion();
bool IsInEmulator();
void GetDeviceBuild(CStringW& sBuild); */ //ok
static CStringW GetDeviceID();
static CStringW GetSerialNumberFromKernelIoControl();
static void GetDeviceInfo();
static int GetAdapterInfo();
static void ParseData();
static CStringW GetMAC();
static CStringW GetUniqueMacID();
//void GetDeviceID(char* pszBuffer);
//
//BYTE GetBatteryFlag(); //ok
//BYTE GetBackupBatteryLifePercent(); //ok
//BYTE GetBackupBatteryFlag(); //ok
//DWORD GetAvailableMemory(); //ok
//BYTE GetBatteryLifePercent(); //ok
//ULONG GetFreeFlashSpace(); //ok
//bool SetSysTime(DWORD dwNewTime);
//void DbgSetBatteryFlag(bool bPower);
//void BeepSuccess();
//void BeepQuestion(); //ok
//void BeepWarning();
//void BeepError(); //ok
//void BeepAkku(); //ok
//
/*bool IsSipVisible();
void ShowSip(bool bShow);
*/
//static bool RegisterComDll(CStringW sDll);
//void Reboot()=0; //ok
//void Calibrate()=0;
//void PowerOff()=0; //ok
//void SetLocalTime(CTlsTime tm)=0;
//void PreventSystemPowerDown(){}; //ok
/*void EnableRegFlush() {};
void DisableRegFlush() {};
void FlushReg() {};*/
static PIP_ADAPTER_INFO pinfo;
static unsigned long len;
static CStringW m_macaddress;
static CStringW m_uniqueid;
static CStringW m_description;
static CStringW m_type;
static CStringW m_subnet;
static CStringW m_IpAddress;
static CStringW m_gateway;
static CStringW m_PrimaryWinsServer;
static CStringW m_dhcp;
};
#endif
/*=============================================================================
E O F
=============================================================================*/
| [
"quang.nguyen@vyaire.com"
] | quang.nguyen@vyaire.com |
f3f295508045a61fbcec92b5a57e237439e37f0f | a832f88501dcc2ed2803d8d2e99c5e653c55fb86 | /src/vnx_search_archive.cpp | 8bf1369ea8716298972e04a1532ba0bd6bc5f5c0 | [] | no_license | bucaklilar6-web/vnx-search | 0b610cdb392d9887d1ef91a72acb6a73a711c85d | 12fbad35f1786e02980e148615822fd0d65a3af9 | refs/heads/master | 2023-04-05T19:35:27.487674 | 2021-04-25T18:16:25 | 2021-04-25T18:16:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,072 | cpp | /*
* vnx_search_archive.cpp
*
* Created on: Jul 1, 2020
* Author: mad
*/
#include <vnx/keyvalue/Server.h>
#include <vnx/search/ArchiveProxy.h>
#include <vnx/search/ArchiveServer.h>
#include <vnx/addons/HttpServer.h>
#include <vnx/vnx.h>
#include <vnx/Terminal.h>
#include <vnx/Server.h>
#include <vnx/Proxy.h>
int main(int argc, char** argv)
{
std::map<std::string, std::string> options;
options["f"] = "frontend";
options["frontend"] = "frontend server url";
vnx::init("vnx_search_archive", argc, argv, options);
std::string frontend = ".vnx_search_frontend.sock";
vnx::read_config("frontend", frontend);
{
vnx::Handle<vnx::Terminal> terminal = new vnx::Terminal("Terminal");
terminal.start_detached();
}
{
vnx::Handle<vnx::Server> server = new vnx::Server("Server", vnx::Endpoint::from_url(".vnx_search_archive.sock"));
server.start_detached();
}
{
vnx::Handle<vnx::Proxy> proxy = new vnx::Proxy("Proxy", vnx::Endpoint::from_url(frontend));
proxy->import_list.push_back("frontend.http_responses");
proxy.start_detached();
}
{
vnx::Handle<vnx::keyvalue::Server> module = new vnx::keyvalue::Server("HttpArchive");
module->do_compress = true;
module->collection = "http_archive";
module->update_topic = "http_archive.updates";
module->update_topic_keys = "http_archive.key_updates";
module.start_detached();
}
{
vnx::Handle<vnx::search::ArchiveProxy> module = new vnx::search::ArchiveProxy("ArchiveProxy");
module->input_http = "frontend.http_responses";
module.start_detached();
}
std::string archive_path;
{
vnx::Handle<vnx::search::ArchiveServer> module = new vnx::search::ArchiveServer("ArchiveServer");
archive_path = module->path;
module.start_detached();
}
{
vnx::Handle<vnx::addons::HttpServerBase> module = vnx::addons::new_HttpServer("HttpServer");
module->chunk_size = 16 * 1024 * 1024;
module->components[archive_path] = "ArchiveServer";
module->output_request = "http.request";
module->output_response = "http.response";
module.start_detached();
}
vnx::wait();
}
| [
"max.wittal@mwittal.de"
] | max.wittal@mwittal.de |
ce080f7890f4cdf8328eb7f10738a08556a778eb | 89f8073f32c5e76c36d7e3072002015a5646119f | /common files/sum of e an i.cpp | 761c4ca814a042aa023bc53b787881186a5fc903 | [] | no_license | PulockDas/Competitive-Programming-Algorithms | f19b8eab081e73c01b4a8ba8673c9df752ff3646 | 2b3774a34170f10e81ec5b3479f4a49bc138e938 | refs/heads/main | 2023-06-11T20:59:57.458069 | 2021-06-29T19:54:05 | 2021-06-29T19:54:05 | 308,912,300 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 315 | cpp | #include <iostream>
using namespace std;
main ()
{
int n,e,ep;
cin>>n;
int a;
for (int i=0;i<n;i++)
{
cin>>a;
ep=a%10;
a=a/10;
while(a!=0)
{
e=a%10;
a=a/10;
}
cout<<"Sum = "<<ep+e<<endl;
}
}
| [
"pulock46@student.sust.edu"
] | pulock46@student.sust.edu |
b92de6fa72cdfca1b915d7676fd2246bf5602eb0 | 5149df84d1bf0bed5ccf2feca01770e0267ebd5a | /public/vphysics_interface.h | 46edafa1d614d344cf864a25de23a6c1a6eff501 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | iomeone/Kisak-Strike | 924185588bafe60fda198bed39f4e88ae0f2f5b3 | ae0f59e7263bf0165809b2bd8a1ff52ff483ebfd | refs/heads/master | 2023-02-25T20:08:52.822944 | 2021-02-05T09:04:58 | 2021-02-05T09:04:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 54,902 | h | //===== Copyright � 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose: Public interfaces to vphysics DLL
//
// $NoKeywords: $
//===========================================================================//
#ifndef VPHYSICS_INTERFACE_H
#define VPHYSICS_INTERFACE_H
#ifdef _WIN32
#pragma once
#endif
#include "tier1/interface.h"
#include "appframework/iappsystem.h"
#include "mathlib/vector.h"
#include "mathlib/vector4d.h"
#include "vcollide.h"
#include "tier3/tier3.h"
#include "SoundEmitterSystem/isoundemittersystembase.h"
// ------------------------------------------------------------------------------------
// UNITS:
// ------------------------------------------------------------------------------------
// NOTE: Coordinates are in HL units. 1 unit == 1 inch. X is east (forward), Y is north (left), Z is up (up)
// QAngle are pitch (around y), Yaw (around Z), Roll (around X)
// AngularImpulse are exponetial maps (an axis in HL units scaled by a "twist" angle in degrees)
// They can be transformed like normals/covectors and added linearly
// mass is kg, volume is in^3, acceleration is in/s^2, velocity is in/s
// density is kg/m^3 (water ~= 998 at room temperature)
// preferably, these would be in kg/in^3, but the range of those numbers makes them not very human readable
// having water be about 1000 is really convenient for data entry.
// Since volume is in in^3 and density is in kg/m^3:
// density = (mass / volume) * CUBIC_METERS_PER_CUBIC_INCH
// Force is applied using impulses (kg*in/s)
// Torque is applied using impulses (kg*degrees/s)
// ------------------------------------------------------------------------------------
#define METERS_PER_INCH (0.0254f)
#define CUBIC_METERS_PER_CUBIC_INCH (METERS_PER_INCH*METERS_PER_INCH*METERS_PER_INCH)
// 2.2 lbs / kg
#define POUNDS_PER_KG (2.2f)
#define KG_PER_POUND (1.0f/POUNDS_PER_KG)
// convert from pounds to kg
#define lbs2kg(x) ((x)*KG_PER_POUND)
#define kg2lbs(x) ((x)*POUNDS_PER_KG)
const float VPHYSICS_MIN_MASS = 0.1f;
const float VPHYSICS_MAX_MASS = 5e4f;
class IPhysicsObject;
class IPhysicsEnvironment;
class IPhysicsSurfaceProps;
class IPhysicsConstraint;
class IPhysicsConstraintGroup;
class IPhysicsFluidController;
class IPhysicsSpring;
class IPhysicsVehicleController;
class IConvexInfo;
class IPhysicsObjectPairHash;
class IPhysicsCollisionSet;
class IPhysicsPlayerController;
class IPhysicsFrictionSnapshot;
struct Ray_t;
struct constraint_ragdollparams_t;
struct constraint_hingeparams_t;
struct constraint_fixedparams_t;
struct constraint_ballsocketparams_t;
struct constraint_slidingparams_t;
struct constraint_pulleyparams_t;
struct constraint_lengthparams_t;
struct constraint_groupparams_t;
struct vehicleparams_t;
struct matrix3x4_t;
struct fluidparams_t;
struct springparams_t;
struct objectparams_t;
struct debugcollide_t;
class CGameTrace;
typedef CGameTrace trace_t;
struct physics_stats_t;
struct physics_performanceparams_t;
struct virtualmeshparams_t;
//enum PhysInterfaceId_t;
struct physsaveparams_t;
struct physrestoreparams_t;
struct physprerestoreparams_t;
enum PhysInterfaceId_t
{
PIID_UNKNOWN,
PIID_IPHYSICSOBJECT,
PIID_IPHYSICSFLUIDCONTROLLER,
PIID_IPHYSICSSPRING,
PIID_IPHYSICSCONSTRAINTGROUP,
PIID_IPHYSICSCONSTRAINT,
PIID_IPHYSICSSHADOWCONTROLLER,
PIID_IPHYSICSPLAYERCONTROLLER,
PIID_IPHYSICSMOTIONCONTROLLER,
PIID_IPHYSICSVEHICLECONTROLLER,
PIID_IPHYSICSGAMETRACE,
PIID_NUM_TYPES
};
class ISave;
class IRestore;
#define VPHYSICS_DEBUG_OVERLAY_INTERFACE_VERSION "VPhysicsDebugOverlay001"
abstract_class IVPhysicsDebugOverlay
{
public:
virtual void AddEntityTextOverlay(int ent_index, int line_offset, float duration, int r, int g, int b, int a, PRINTF_FORMAT_STRING const char *format, ...) = 0;
virtual void AddBoxOverlay(const Vector& origin, const Vector& mins, const Vector& max, QAngle const& orientation, int r, int g, int b, int a, float duration) = 0;
virtual void AddTriangleOverlay(const Vector& p1, const Vector& p2, const Vector& p3, int r, int g, int b, int a, bool noDepthTest, float duration) = 0;
virtual void AddLineOverlay(const Vector& origin, const Vector& dest, int r, int g, int b,bool noDepthTest, float duration) = 0;
virtual void AddTextOverlay(const Vector& origin, float duration, PRINTF_FORMAT_STRING const char *format, ...) = 0;
virtual void AddTextOverlay(const Vector& origin, int line_offset, float duration, PRINTF_FORMAT_STRING const char *format, ...) = 0;
virtual void AddScreenTextOverlay(float flXPos, float flYPos,float flDuration, int r, int g, int b, int a, const char *text) = 0;
virtual void AddSweptBoxOverlay(const Vector& start, const Vector& end, const Vector& mins, const Vector& max, const QAngle & angles, int r, int g, int b, int a, float flDuration) = 0;
virtual void AddTextOverlayRGB(const Vector& origin, int line_offset, float duration, float r, float g, float b, float alpha, PRINTF_FORMAT_STRING const char *format, ...) = 0;
};
#define VPHYSICS_INTERFACE_VERSION "VPhysics031"
abstract_class IPhysics : public IAppSystem
{
public:
virtual IPhysicsEnvironment *CreateEnvironment( void ) = 0;
virtual void DestroyEnvironment( IPhysicsEnvironment * ) = 0;
virtual IPhysicsEnvironment *GetActiveEnvironmentByIndex( int index ) = 0;
// Creates a fast hash of pairs of objects
// Useful for maintaining a table of object relationships like pairs that do not collide.
virtual IPhysicsObjectPairHash *CreateObjectPairHash() = 0;
virtual void DestroyObjectPairHash( IPhysicsObjectPairHash *pHash ) = 0;
// holds a cache of these by id. So you can get by id to search for the previously created set
// UNDONE: Sets are currently limited to 32 elements. More elements will return NULL in create.
// NOTE: id is not allowed to be zero.
virtual IPhysicsCollisionSet *FindOrCreateCollisionSet( uintptr_t id, int maxElementCount ) = 0;
virtual IPhysicsCollisionSet *FindCollisionSet( uintptr_t id ) = 0;
virtual void DestroyAllCollisionSets() = 0;
};
// CPhysConvex is a single convex solid
class CPhysConvex;
// CPhysPolysoup is an abstract triangle soup mesh
class CPhysPolysoup;
class ICollisionQuery;
class IVPhysicsKeyParser;
struct convertconvexparams_t;
class CPackedPhysicsDescription;
class CPolyhedron;
// UNDONE: Find a better place for this? Should be in collisionutils, but it's needs VPHYSICS' solver.
struct truncatedcone_t
{
Vector origin;
Vector normal;
float h; // height of the cone (hl units)
float theta; // cone angle (degrees)
};
abstract_class IPhysicsCollision
{
public:
virtual ~IPhysicsCollision( void ) {}
// produce a convex element from verts (convex hull around verts)
virtual CPhysConvex *ConvexFromVerts( Vector **pVerts, int vertCount ) = 0;
// produce a convex element from planes (csg of planes)
virtual CPhysConvex *ConvexFromPlanes( float *pPlanes, int planeCount, float mergeDistance ) = 0;
// calculate volume of a convex element
virtual float ConvexVolume( CPhysConvex *pConvex ) = 0;
virtual float ConvexSurfaceArea( CPhysConvex *pConvex ) = 0;
// store game-specific data in a convex solid
virtual void SetConvexGameData( CPhysConvex *pConvex, unsigned int gameData ) = 0;
// If not converted, free the convex elements with this call
virtual void ConvexFree( CPhysConvex *pConvex ) = 0;
virtual CPhysConvex *BBoxToConvex( const Vector &mins, const Vector &maxs ) = 0;
// produce a convex element from a convex polyhedron
virtual CPhysConvex *ConvexFromConvexPolyhedron( const CPolyhedron &ConvexPolyhedron ) = 0;
// produce a set of convex triangles from a convex polygon, normal is assumed to be on the side with forward point ordering, which should be clockwise, output will need to be able to hold exactly (iPointCount-2) convexes
virtual void ConvexesFromConvexPolygon( const Vector &vPolyNormal, const Vector *pPoints, int iPointCount, CPhysConvex **pOutput ) = 0;
// concave objects
// create a triangle soup
virtual CPhysPolysoup *PolysoupCreate( void ) = 0;
// destroy the container and memory
virtual void PolysoupDestroy( CPhysPolysoup *pSoup ) = 0;
// add a triangle to the soup
virtual void PolysoupAddTriangle( CPhysPolysoup *pSoup, const Vector &a, const Vector &b, const Vector &c, int materialIndex7bits ) = 0;
// convert the convex into a compiled collision model
virtual CPhysCollide *ConvertPolysoupToCollide( CPhysPolysoup *pSoup, bool useMOPP ) = 0;
// Convert an array of convex elements to a compiled collision model (this deletes the convex elements)
virtual CPhysCollide *ConvertConvexToCollide( CPhysConvex **pConvex, int convexCount ) = 0;
virtual CPhysCollide *ConvertConvexToCollideParams( CPhysConvex **pConvex, int convexCount, const convertconvexparams_t &convertParams ) = 0;
// Free a collide that was created with ConvertConvexToCollide()
virtual void DestroyCollide( CPhysCollide *pCollide ) = 0;
// Get the memory size in bytes of the collision model for serialization
virtual int CollideSize( CPhysCollide *pCollide ) = 0;
// serialize the collide to a block of memory
virtual int CollideWrite( char *pDest, CPhysCollide *pCollide, bool bSwap = false ) = 0;
// unserialize the collide from a block of memory
virtual CPhysCollide *UnserializeCollide( char *pBuffer, int size, int index ) = 0;
// compute the volume of a collide
virtual float CollideVolume( CPhysCollide *pCollide ) = 0;
// compute surface area for tools
virtual float CollideSurfaceArea( CPhysCollide *pCollide ) = 0;
// Get the support map for a collide in the given direction
virtual Vector CollideGetExtent( const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, const Vector &direction ) = 0;
// Get an AABB for an oriented collision model
virtual void CollideGetAABB( Vector *pMins, Vector *pMaxs, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles ) = 0;
virtual void CollideGetMassCenter( CPhysCollide *pCollide, Vector *pOutMassCenter ) = 0;
virtual void CollideSetMassCenter( CPhysCollide *pCollide, const Vector &massCenter ) = 0;
// get the approximate cross-sectional area projected orthographically on the bbox of the collide
// NOTE: These are fractional areas - unitless. Basically this is the fraction of the OBB on each axis that
// would be visible if the object were rendered orthographically.
// NOTE: This has been precomputed when the collide was built or this function will return 1,1,1
virtual Vector CollideGetOrthographicAreas( const CPhysCollide *pCollide ) = 0;
virtual void CollideSetOrthographicAreas( CPhysCollide *pCollide, const Vector &areas ) = 0;
// query the vcollide index in the physics model for the instance
virtual int CollideIndex( const CPhysCollide *pCollide ) = 0;
// Convert a bbox to a collide
virtual CPhysCollide *BBoxToCollide( const Vector &mins, const Vector &maxs ) = 0;
virtual int GetConvexesUsedInCollideable( const CPhysCollide *pCollideable, CPhysConvex **pOutputArray, int iOutputArrayLimit ) = 0;
// Trace an AABB against a collide
virtual void TraceBox( const Vector &start, const Vector &end, const Vector &mins, const Vector &maxs, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr ) = 0;
virtual void TraceBox( const Ray_t &ray, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr ) = 0;
virtual void TraceBox( const Ray_t &ray, unsigned int contentsMask, IConvexInfo *pConvexInfo, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr ) = 0;
// Trace one collide against another
virtual void TraceCollide( const Vector &start, const Vector &end, const CPhysCollide *pSweepCollide, const QAngle &sweepAngles, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr ) = 0;
// relatively slow test for box vs. truncated cone
virtual bool IsBoxIntersectingCone( const Vector &boxAbsMins, const Vector &boxAbsMaxs, const truncatedcone_t &cone ) = 0;
// loads a set of solids into a vcollide_t
virtual void VCollideLoad( vcollide_t *pOutput, int solidCount, const char *pBuffer, int size, bool swap = false ) = 0;
// destroyts the set of solids created by VCollideLoad
virtual void VCollideUnload( vcollide_t *pVCollide ) = 0;
// begins parsing a vcollide. NOTE: This keeps pointers to the text
// If you free the text and call members of IVPhysicsKeyParser, it will crash
virtual IVPhysicsKeyParser *VPhysicsKeyParserCreate( const char *pKeyData ) = 0;
virtual IVPhysicsKeyParser *VPhysicsKeyParserCreate( vcollide_t *pVCollide ) = 0;
// Free the parser created by VPhysicsKeyParserCreate
virtual void VPhysicsKeyParserDestroy( IVPhysicsKeyParser *pParser ) = 0;
// creates a list of verts from a collision mesh
virtual int CreateDebugMesh( CPhysCollide const *pCollisionModel, Vector **outVerts ) = 0;
// destroy the list of verts created by CreateDebugMesh
virtual void DestroyDebugMesh( int vertCount, Vector *outVerts ) = 0;
// create a queryable version of the collision model
virtual ICollisionQuery *CreateQueryModel( CPhysCollide *pCollide ) = 0;
// destroy the queryable version
virtual void DestroyQueryModel( ICollisionQuery *pQuery ) = 0;
virtual IPhysicsCollision *ThreadContextCreate( void ) = 0;
virtual void ThreadContextDestroy( IPhysicsCollision *pThreadContex ) = 0;
virtual CPhysCollide *CreateVirtualMesh( const virtualmeshparams_t ¶ms ) = 0;
virtual bool SupportsVirtualMesh() = 0;
virtual bool GetBBoxCacheSize( int *pCachedSize, int *pCachedCount ) = 0;
// extracts a polyhedron that defines a CPhysConvex's shape
virtual CPolyhedron *PolyhedronFromConvex( CPhysConvex * const pConvex, bool bUseTempPolyhedron ) = 0;
// dumps info about the collide to Msg()
virtual void OutputDebugInfo( const CPhysCollide *pCollide ) = 0;
virtual unsigned int ReadStat( int statID ) = 0;
// Get an AABB for an oriented collision model
virtual float CollideGetRadius( const CPhysCollide *pCollide ) = 0;
virtual void *VCollideAllocUserData( vcollide_t *pVCollide, size_t userDataSize ) = 0;
virtual void VCollideFreeUserData( vcollide_t *pVCollide ) = 0;
virtual void VCollideCheck( vcollide_t *pVCollide, const char *pName ) = 0;
virtual bool TraceBoxAA( const Ray_t &ray, const CPhysCollide *pCollide, trace_t *ptr ) = 0;
};
// this can be used to post-process a collision model
abstract_class ICollisionQuery
{
public:
virtual ~ICollisionQuery() {}
// number of convex pieces in the whole solid
virtual int ConvexCount( void ) = 0;
// triangle count for this convex piece
virtual int TriangleCount( int convexIndex ) = 0;
// get the stored game data
virtual unsigned int GetGameData( int convexIndex ) = 0;
// Gets the triangle's verts to an array
virtual void GetTriangleVerts( int convexIndex, int triangleIndex, Vector *verts ) = 0;
// UNDONE: This doesn't work!!!
virtual void SetTriangleVerts( int convexIndex, int triangleIndex, const Vector *verts ) = 0;
// returns the 7-bit material index
virtual int GetTriangleMaterialIndex( int convexIndex, int triangleIndex ) = 0;
// sets a 7-bit material index for this triangle
virtual void SetTriangleMaterialIndex( int convexIndex, int triangleIndex, int index7bits ) = 0;
};
//-----------------------------------------------------------------------------
// Purpose: Ray traces from game engine.
//-----------------------------------------------------------------------------
abstract_class IPhysicsGameTrace
{
public:
virtual void VehicleTraceRay( const Ray_t &ray, void *pVehicle, trace_t *pTrace ) = 0;
virtual void VehicleTraceRayWithWater( const Ray_t &ray, void *pVehicle, trace_t *pTrace ) = 0;
virtual bool VehiclePointInWater( const Vector &vecPoint ) = 0;
};
// The caller should implement this to return contents masks per convex on a collide
abstract_class IConvexInfo
{
public:
virtual unsigned int GetContents( int convexGameData ) = 0;
};
class CPhysicsEventHandler;
abstract_class IPhysicsCollisionData
{
public:
virtual void GetSurfaceNormal( Vector &out ) = 0; // normal points toward second object (object index 1)
virtual void GetContactPoint( Vector &out ) = 0; // contact point of collision (in world space)
virtual void GetContactSpeed( Vector &out ) = 0; // speed of surface 1 relative to surface 0 (in world space)
};
struct vcollisionevent_t
{
IPhysicsObject *pObjects[2];
int surfaceProps[2];
bool isCollision;
bool isShadowCollision;
float deltaCollisionTime;
float collisionSpeed; // only valid at postCollision
IPhysicsCollisionData *pInternalData; // may change pre/post collision
};
abstract_class IPhysicsCollisionEvent
{
public:
// returns the two objects that collided, time between last collision of these objects
// and an opaque data block of collision information
// NOTE: PreCollision/PostCollision ALWAYS come in matched pairs!!!
virtual void PreCollision( vcollisionevent_t *pEvent ) = 0;
virtual void PostCollision( vcollisionevent_t *pEvent ) = 0;
// This is a scrape event. The object has scraped across another object consuming the indicated energy
virtual void Friction( IPhysicsObject *pObject, float energy, int surfaceProps, int surfacePropsHit, IPhysicsCollisionData *pData ) = 0;
virtual void StartTouch( IPhysicsObject *pObject1, IPhysicsObject *pObject2, IPhysicsCollisionData *pTouchData ) = 0;
virtual void EndTouch( IPhysicsObject *pObject1, IPhysicsObject *pObject2, IPhysicsCollisionData *pTouchData ) = 0;
virtual void FluidStartTouch( IPhysicsObject *pObject, IPhysicsFluidController *pFluid ) = 0;
virtual void FluidEndTouch( IPhysicsObject *pObject, IPhysicsFluidController *pFluid ) = 0;
virtual void PostSimulationFrame() = 0;
virtual void ObjectEnterTrigger( IPhysicsObject *pTrigger, IPhysicsObject *pObject ) {}
virtual void ObjectLeaveTrigger( IPhysicsObject *pTrigger, IPhysicsObject *pObject ) {}
};
abstract_class IPhysicsObjectEvent
{
public:
// these can be used to optimize out queries on sleeping objects
// Called when an object is woken after sleeping
virtual void ObjectWake( IPhysicsObject *pObject ) = 0;
// called when an object goes to sleep (no longer simulating)
virtual void ObjectSleep( IPhysicsObject *pObject ) = 0;
};
abstract_class IPhysicsConstraintEvent
{
public:
// the constraint is now inactive, the game code is required to delete it or re-activate it.
virtual void ConstraintBroken( IPhysicsConstraint * ) = 0;
};
struct hlshadowcontrol_params_t
{
Vector targetPosition;
QAngle targetRotation;
float maxAngular;
float maxDampAngular;
float maxSpeed;
float maxDampSpeed;
float dampFactor;
float teleportDistance;
};
// UNDONE: At some point allow this to be parameterized using hlshadowcontrol_params_t.
// All of the infrastructure is in place to do that.
abstract_class IPhysicsShadowController
{
public:
virtual ~IPhysicsShadowController( void ) {}
virtual void Update( const Vector &position, const QAngle &angles, float timeOffset ) = 0;
virtual void MaxSpeed( float maxSpeed, float maxAngularSpeed ) = 0;
virtual void StepUp( float height ) = 0;
// If the teleport distance is non-zero, the object will be teleported to
// the target location when the error exceeds this quantity.
virtual void SetTeleportDistance( float teleportDistance ) = 0;
virtual bool AllowsTranslation() = 0;
virtual bool AllowsRotation() = 0;
// There are two classes of shadow objects:
// 1) Game physics controlled, shadow follows game physics (this is the default)
// 2) Physically controlled - shadow position is a target, but the game hasn't guaranteed that the space can be occupied by this object
virtual void SetPhysicallyControlled( bool isPhysicallyControlled ) = 0;
virtual bool IsPhysicallyControlled() = 0;
virtual void GetLastImpulse( Vector *pOut ) = 0;
virtual void UseShadowMaterial( bool bUseShadowMaterial ) = 0;
virtual void ObjectMaterialChanged( int materialIndex ) = 0;
//Basically get the last inputs to IPhysicsShadowController::Update(), returns last input to timeOffset in Update()
virtual float GetTargetPosition( Vector *pPositionOut, QAngle *pAnglesOut ) = 0;
virtual float GetTeleportDistance( void ) = 0;
virtual void GetMaxSpeed( float *pMaxSpeedOut, float *pMaxAngularSpeedOut ) = 0;
};
class CPhysicsSimObject;
class IPhysicsMotionController;
// Callback for simulation
class IMotionEvent
{
public:
// These constants instruct the simulator as to how to apply the values copied to linear & angular
// GLOBAL/LOCAL refer to the coordinate system of the values, whereas acceleration/force determine whether or not
// mass is divided out (forces must be divided by mass to compute acceleration)
enum simresult_e { SIM_NOTHING = 0, SIM_LOCAL_ACCELERATION, SIM_LOCAL_FORCE, SIM_GLOBAL_ACCELERATION, SIM_GLOBAL_FORCE };
virtual simresult_e Simulate( IPhysicsMotionController *pController, IPhysicsObject *pObject, float deltaTime, Vector &linear, AngularImpulse &angular ) = 0;
};
abstract_class IPhysicsMotionController
{
public:
virtual ~IPhysicsMotionController( void ) {}
virtual void SetEventHandler( IMotionEvent *handler ) = 0;
virtual void AttachObject( IPhysicsObject *pObject, bool checkIfAlreadyAttached ) = 0;
virtual void DetachObject( IPhysicsObject *pObject ) = 0;
// returns the number of objects currently attached to the controller
virtual int CountObjects( void ) = 0;
// NOTE: pObjectList is an array with at least CountObjects() allocated
virtual void GetObjects( IPhysicsObject **pObjectList ) = 0;
// detaches all attached objects
virtual void ClearObjects( void ) = 0;
// wakes up all attached objects
virtual void WakeObjects( void ) = 0;
enum priority_t
{
LOW_PRIORITY = 0,
MEDIUM_PRIORITY = 1,
HIGH_PRIORITY = 2,
};
virtual void SetPriority( priority_t priority ) = 0;
};
// -------------------
// Collision filter function. Return 0 if objects should not be tested for collisions, nonzero otherwise
// Install with IPhysicsEnvironment::SetCollisionFilter()
// -------------------
abstract_class IPhysicsCollisionSolver
{
public:
virtual int ShouldCollide( IPhysicsObject *pObj0, IPhysicsObject *pObj1, void *pGameData0, void *pGameData1 ) = 0;
virtual int ShouldSolvePenetration( IPhysicsObject *pObj0, IPhysicsObject *pObj1, void *pGameData0, void *pGameData1, float dt ) = 0;
// pObject has already done the max number of collisions this tick, should we freeze it to save CPU?
virtual bool ShouldFreezeObject( IPhysicsObject *pObject ) = 0;
// The system has already done too many collision checks, performance will suffer.
// How many more should it do?
virtual int AdditionalCollisionChecksThisTick( int currentChecksDone ) = 0;
// This list of objects is in a connected contact graph that is too large to solve quickly
// return true to freeze the system, false to solve it
virtual bool ShouldFreezeContacts( IPhysicsObject **pObjectList, int objectCount ) = 0;
};
enum PhysicsTraceType_t
{
VPHYSICS_TRACE_EVERYTHING = 0,
VPHYSICS_TRACE_STATIC_ONLY,
VPHYSICS_TRACE_MOVING_ONLY,
VPHYSICS_TRACE_TRIGGERS_ONLY,
VPHYSICS_TRACE_STATIC_AND_MOVING,
};
abstract_class IPhysicsTraceFilter
{
public:
virtual bool ShouldHitObject( IPhysicsObject *pObject, int contentsMask ) = 0;
virtual PhysicsTraceType_t GetTraceType() const = 0;
};
abstract_class IPhysicsEnvironment
{
public:
virtual ~IPhysicsEnvironment( void ) {}
virtual void SetDebugOverlay( CreateInterfaceFn debugOverlayFactory ) = 0;
virtual IVPhysicsDebugOverlay *GetDebugOverlay( void ) = 0;
// gravity is a 3-vector in in/s^2
virtual void SetGravity( const Vector &gravityVector ) = 0;
virtual void GetGravity( Vector *pGravityVector ) const = 0;
// air density is in kg / m^3 (water is 1000)
// This controls drag, air that is more dense has more drag.
virtual void SetAirDensity( float density ) = 0;
virtual float GetAirDensity( void ) const = 0;
// object creation
// create a polygonal object. pCollisionModel was created by the physics builder DLL in a pre-process.
virtual IPhysicsObject *CreatePolyObject( const CPhysCollide *pCollisionModel, int materialIndex, const Vector &position, const QAngle &angles, objectparams_t *pParams ) = 0;
// same as above, but this one cannot move or rotate (infinite mass/inertia)
virtual IPhysicsObject *CreatePolyObjectStatic( const CPhysCollide *pCollisionModel, int materialIndex, const Vector &position, const QAngle &angles, objectparams_t *pParams ) = 0;
// Create a perfectly spherical object
virtual IPhysicsObject *CreateSphereObject( float radius, int materialIndex, const Vector &position, const QAngle &angles, objectparams_t *pParams, bool isStatic ) = 0;
// destroy an object created with CreatePolyObject() or CreatePolyObjectStatic()
virtual void DestroyObject( IPhysicsObject * ) = 0;
// Create a polygonal fluid body out of the specified collision model
// This object will affect any other objects that collide with the collision model
virtual IPhysicsFluidController *CreateFluidController( IPhysicsObject *pFluidObject, fluidparams_t *pParams ) = 0;
// Destroy an object created with CreateFluidController()
virtual void DestroyFluidController( IPhysicsFluidController * ) = 0;
// Create a simulated spring that connects 2 objects
virtual IPhysicsSpring *CreateSpring( IPhysicsObject *pObjectStart, IPhysicsObject *pObjectEnd, springparams_t *pParams ) = 0;
virtual void DestroySpring( IPhysicsSpring * ) = 0;
// Create a constraint in the space of pReferenceObject which is attached by the constraint to pAttachedObject
virtual IPhysicsConstraint *CreateRagdollConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_ragdollparams_t &ragdoll ) = 0;
virtual IPhysicsConstraint *CreateHingeConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_hingeparams_t &hinge ) = 0;
virtual IPhysicsConstraint *CreateFixedConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_fixedparams_t &fixed ) = 0;
virtual IPhysicsConstraint *CreateSlidingConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_slidingparams_t &sliding ) = 0;
virtual IPhysicsConstraint *CreateBallsocketConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_ballsocketparams_t &ballsocket ) = 0;
virtual IPhysicsConstraint *CreatePulleyConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_pulleyparams_t &pulley ) = 0;
virtual IPhysicsConstraint *CreateLengthConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_lengthparams_t &length ) = 0;
virtual void DestroyConstraint( IPhysicsConstraint * ) = 0;
virtual IPhysicsConstraintGroup *CreateConstraintGroup( const constraint_groupparams_t &groupParams ) = 0;
virtual void DestroyConstraintGroup( IPhysicsConstraintGroup *pGroup ) = 0;
virtual IPhysicsShadowController *CreateShadowController( IPhysicsObject *pObject, bool allowTranslation, bool allowRotation ) = 0;
virtual void DestroyShadowController( IPhysicsShadowController * ) = 0;
virtual IPhysicsPlayerController *CreatePlayerController( IPhysicsObject *pObject ) = 0;
virtual void DestroyPlayerController( IPhysicsPlayerController * ) = 0;
virtual IPhysicsMotionController *CreateMotionController( IMotionEvent *pHandler ) = 0;
virtual void DestroyMotionController( IPhysicsMotionController *pController ) = 0;
virtual IPhysicsVehicleController *CreateVehicleController( IPhysicsObject *pVehicleBodyObject, const vehicleparams_t ¶ms, unsigned int nVehicleType, IPhysicsGameTrace *pGameTrace ) = 0;
virtual void DestroyVehicleController( IPhysicsVehicleController * ) = 0;
// install a function to filter collisions/penentration
virtual void SetCollisionSolver( IPhysicsCollisionSolver *pSolver ) = 0;
// run the simulator for deltaTime seconds
virtual void Simulate( float deltaTime ) = 0;
// true if currently running the simulator (i.e. in a callback during physenv->Simulate())
virtual bool IsInSimulation() const = 0;
// Manage the timestep (period) of the simulator. The main functions are all integrated with
// this period as dt.
virtual float GetSimulationTimestep() const = 0;
virtual void SetSimulationTimestep( float timestep ) = 0;
// returns the current simulation clock's value. This is an absolute time.
virtual float GetSimulationTime() const = 0;
virtual void ResetSimulationClock() = 0;
// returns the current simulation clock's value at the next frame. This is an absolute time.
virtual float GetNextFrameTime( void ) const = 0;
// Collision callbacks (game code collision response)
virtual void SetCollisionEventHandler( IPhysicsCollisionEvent *pCollisionEvents ) = 0;
virtual void SetObjectEventHandler( IPhysicsObjectEvent *pObjectEvents ) = 0;
virtual void SetConstraintEventHandler( IPhysicsConstraintEvent *pConstraintEvents ) = 0;
virtual void SetQuickDelete( bool bQuick ) = 0;
virtual int GetActiveObjectCount() const = 0;
virtual void GetActiveObjects( IPhysicsObject **pOutputObjectList ) const = 0;
virtual const IPhysicsObject **GetObjectList( int *pOutputObjectCount ) const = 0;
virtual bool TransferObject( IPhysicsObject *pObject, IPhysicsEnvironment *pDestinationEnvironment ) = 0;
virtual void CleanupDeleteList( void ) = 0;
virtual void EnableDeleteQueue( bool enable ) = 0;
// Save/Restore methods
virtual bool Save( const physsaveparams_t ¶ms ) = 0;
virtual void PreRestore( const physprerestoreparams_t ¶ms ) = 0;
virtual bool Restore( const physrestoreparams_t ¶ms ) = 0;
virtual void PostRestore() = 0;
// Debugging:
virtual bool IsCollisionModelUsed( CPhysCollide *pCollide ) const = 0;
// Physics world version of the enginetrace API:
virtual void TraceRay( const Ray_t &ray, unsigned int fMask, IPhysicsTraceFilter *pTraceFilter, trace_t *pTrace ) = 0;
virtual void SweepCollideable( const CPhysCollide *pCollide, const Vector &vecAbsStart, const Vector &vecAbsEnd,
const QAngle &vecAngles, unsigned int fMask, IPhysicsTraceFilter *pTraceFilter, trace_t *pTrace ) = 0;
// performance tuning
virtual void GetPerformanceSettings( physics_performanceparams_t *pOutput ) const = 0;
virtual void SetPerformanceSettings( const physics_performanceparams_t *pSettings ) = 0;
// perf/cost statistics
virtual void ReadStats( physics_stats_t *pOutput ) = 0;
virtual void ClearStats() = 0;
virtual unsigned int GetObjectSerializeSize( IPhysicsObject *pObject ) const = 0;
virtual void SerializeObjectToBuffer( IPhysicsObject *pObject, unsigned char *pBuffer, unsigned int bufferSize ) = 0;
virtual IPhysicsObject *UnserializeObjectFromBuffer( void *pGameData, unsigned char *pBuffer, unsigned int bufferSize, bool enableCollisions ) = 0;
virtual void EnableConstraintNotify( bool bEnable ) = 0;
virtual void DebugCheckContacts(void) = 0;
virtual void SetAlternateGravity( const Vector &gravityVector ) = 0;
virtual void GetAlternateGravity( Vector *pGravityVector ) const = 0;
virtual float GetDeltaFrameTime( int maxTicks ) const = 0;
virtual void ForceObjectsToSleep( IPhysicsObject **pList, int listCount ) = 0;
//Network prediction related functions
virtual void SetPredicted( bool bPredicted ) = 0; //Interaction with this system and it's objects may not always march forward, sometimes it will get/set data in the past.
virtual bool IsPredicted( void ) = 0;
virtual void SetPredictionCommandNum( int iCommandNum ) = 0; //what command the client is working on right now
virtual int GetPredictionCommandNum( void ) = 0;
virtual void DoneReferencingPreviousCommands( int iCommandNum ) = 0; //won't need data from commands before this one any more
virtual void RestorePredictedSimulation( void ) = 0; //called to restore results from a previous simulation with the same predicted timestamp set
// destroy a CPhysCollide used in CreatePolyObject()/CreatePolyObjectStatic() when any owning IPhysicsObject is flushed from the queued deletion list.
virtual void DestroyCollideOnDeadObjectFlush( CPhysCollide * ) = 0; //should only be used after calling DestroyObject() on all IPhysicsObjects created with it.
};
enum callbackflags
{
CALLBACK_GLOBAL_COLLISION = 0x0001,
CALLBACK_GLOBAL_FRICTION = 0x0002,
CALLBACK_GLOBAL_TOUCH = 0x0004,
CALLBACK_GLOBAL_TOUCH_STATIC = 0x0008,
CALLBACK_SHADOW_COLLISION = 0x0010,
CALLBACK_GLOBAL_COLLIDE_STATIC = 0x0020,
CALLBACK_IS_VEHICLE_WHEEL = 0x0040,
CALLBACK_FLUID_TOUCH = 0x0100,
CALLBACK_NEVER_DELETED = 0x0200, // HACKHACK: This means this object will never be deleted (set on the world)
CALLBACK_MARKED_FOR_DELETE = 0x0400, // This allows vphysics to skip some work for this object since it will be
// deleted later this frame. (Set automatically by destroy calls)
CALLBACK_ENABLING_COLLISION = 0x0800, // This is active during the time an object is enabling collisions
// allows us to skip collisions between "new" objects and objects marked for delete
CALLBACK_DO_FLUID_SIMULATION = 0x1000, // remove this to opt out of fluid simulations
CALLBACK_IS_PLAYER_CONTROLLER= 0x2000, // HACKHACK: Set this on players until player cotrollers are unified with shadow controllers
CALLBACK_CHECK_COLLISION_DISABLE = 0x4000,
CALLBACK_MARKED_FOR_TEST = 0x8000, // debug -- marked object is being debugged
};
enum collisionhints
{
COLLISION_HINT_DEBRIS = 0x0001,
COLLISION_HINT_STATICSOLID = 0x0002,
COLLISION_HINT_NOSOUND = 0x0004, // lwss add - disables collision sounds.
};
class IPredictedPhysicsObject;
abstract_class IPhysicsObject
{
public:
virtual ~IPhysicsObject( void ) {}
// returns true if this object is static/unmoveable
// NOTE: returns false for objects that are not created static, but set EnableMotion(false);
// Call IsMoveable() to find if the object is static OR has motion disabled
virtual bool IsStatic() const = 0;
virtual bool IsAsleep() const = 0;
virtual bool IsTrigger() const = 0;
virtual bool IsFluid() const = 0; // fluids are special triggers with fluid controllers attached, they return true to IsTrigger() as well!
virtual bool IsHinged() const = 0;
virtual bool IsCollisionEnabled() const = 0;
virtual bool IsGravityEnabled() const = 0;
virtual bool IsDragEnabled() const = 0;
virtual bool IsMotionEnabled() const = 0;
virtual bool IsMoveable() const = 0; // legacy: IsMotionEnabled() && !IsStatic()
virtual bool IsAttachedToConstraint(bool bExternalOnly) const = 0;
// Enable / disable collisions for this object
virtual void EnableCollisions( bool enable ) = 0;
// Enable / disable gravity for this object
virtual void EnableGravity( bool enable ) = 0;
// Enable / disable air friction / drag for this object
virtual void EnableDrag( bool enable ) = 0;
// Enable / disable motion (pin / unpin the object)
virtual void EnableMotion( bool enable ) = 0;
// Game can store data in each object (link back to game object)
virtual void SetGameData( void *pGameData ) = 0;
virtual void *GetGameData( void ) const = 0;
// This flags word can be defined by the game as well
virtual void SetGameFlags( unsigned short userFlags ) = 0;
virtual unsigned short GetGameFlags( void ) const = 0;
virtual void SetGameIndex( unsigned short gameIndex ) = 0;
virtual unsigned short GetGameIndex( void ) const = 0;
// setup various callbacks for this object
virtual void SetCallbackFlags( unsigned short callbackflags ) = 0;
// get the current callback state for this object
virtual unsigned short GetCallbackFlags( void ) const = 0;
// "wakes up" an object
// NOTE: ALL OBJECTS ARE "Asleep" WHEN CREATED
virtual void Wake( void ) = 0;
virtual void Sleep( void ) = 0;
// call this when the collision filter conditions change due to this
// object's state (e.g. changing solid type or collision group)
virtual void RecheckCollisionFilter() = 0;
// NOTE: Contact points aren't updated when collision rules change, call this to force an update
// UNDONE: Force this in RecheckCollisionFilter() ?
virtual void RecheckContactPoints( bool bSearchForNewContacts = false ) = 0;
// mass accessors
virtual void SetMass( float mass ) = 0;
virtual float GetMass( void ) const = 0;
// get 1/mass (it's cached)
virtual float GetInvMass( void ) const = 0;
virtual Vector GetInertia( void ) const = 0;
virtual Vector GetInvInertia( void ) const = 0;
virtual void SetInertia( const Vector &inertia ) = 0;
virtual void SetDamping( const float *speed, const float *rot ) = 0;
virtual void GetDamping( float *speed, float *rot ) const = 0;
// coefficients are optional, pass either
virtual void SetDragCoefficient( float *pDrag, float *pAngularDrag ) = 0;
virtual void SetBuoyancyRatio( float ratio ) = 0; // Override bouyancy
// material index
virtual int GetMaterialIndex() const = 0;
virtual void SetMaterialIndex( int materialIndex ) = 0;
// contents bits
virtual unsigned int GetContents() const = 0;
virtual void SetContents( unsigned int contents ) = 0;
// Get the radius if this is a sphere object (zero if this is a polygonal mesh)
virtual float GetSphereRadius() const = 0;
// Set the radius on a sphere. May need to force recalculation of contact points
virtual void SetSphereRadius(float radius) = 0;
virtual float GetEnergy() const = 0;
virtual Vector GetMassCenterLocalSpace() const = 0;
// NOTE: This will teleport the object
virtual void SetPosition( const Vector &worldPosition, const QAngle &angles, bool isTeleport ) = 0;
virtual void SetPositionMatrix( const matrix3x4_t&matrix, bool isTeleport ) = 0;
virtual void GetPosition( Vector *worldPosition, QAngle *angles ) const = 0;
virtual void GetPositionMatrix( matrix3x4_t *positionMatrix ) const = 0;
// force the velocity to a new value
// NOTE: velocity is in worldspace, angularVelocity is relative to the object's
// local axes (just like pev->velocity, pev->avelocity)
virtual void SetVelocity( const Vector *velocity, const AngularImpulse *angularVelocity ) = 0;
// like the above, but force the change into the simulator immediately
virtual void SetVelocityInstantaneous( const Vector *velocity, const AngularImpulse *angularVelocity ) = 0;
// NOTE: velocity is in worldspace, angularVelocity is relative to the object's
// local axes (just like pev->velocity, pev->avelocity)
virtual void GetVelocity( Vector *velocity, AngularImpulse *angularVelocity ) const = 0;
// NOTE: These are velocities, not forces. i.e. They will have the same effect regardless of
// the object's mass or inertia
virtual void AddVelocity( const Vector *velocity, const AngularImpulse *angularVelocity ) = 0;
// gets a velocity in the object's local frame of reference at a specific point
virtual void GetVelocityAtPoint( const Vector &worldPosition, Vector *pVelocity ) const = 0;
// gets the velocity actually moved by the object in the last simulation update
virtual void GetImplicitVelocity( Vector *velocity, AngularImpulse *angularVelocity ) const = 0;
// NOTE: These are here for convenience, but you can do them yourself by using the matrix
// returned from GetPositionMatrix()
// convenient coordinate system transformations (params - dest, src)
virtual void LocalToWorld( Vector *worldPosition, const Vector &localPosition ) const = 0;
virtual void WorldToLocal( Vector *localPosition, const Vector &worldPosition ) const = 0;
// transforms a vector (no translation) from object-local to world space
virtual void LocalToWorldVector( Vector *worldVector, const Vector &localVector ) const = 0;
// transforms a vector (no translation) from world to object-local space
virtual void WorldToLocalVector( Vector *localVector, const Vector &worldVector ) const = 0;
// push on an object
// force vector is direction & magnitude of impulse kg in / s
virtual void ApplyForceCenter( const Vector &forceVector ) = 0;
virtual void ApplyForceOffset( const Vector &forceVector, const Vector &worldPosition ) = 0;
// apply torque impulse. This will change the angular velocity on the object.
// HL Axes, kg degrees / s
virtual void ApplyTorqueCenter( const AngularImpulse &torque ) = 0;
// Calculates the force/torque on the center of mass for an offset force impulse (pass output to ApplyForceCenter / ApplyTorqueCenter)
virtual void CalculateForceOffset( const Vector &forceVector, const Vector &worldPosition, Vector *centerForce, AngularImpulse *centerTorque ) const = 0;
// Calculates the linear/angular velocities on the center of mass for an offset force impulse (pass output to AddVelocity)
virtual void CalculateVelocityOffset( const Vector &forceVector, const Vector &worldPosition, Vector *centerVelocity, AngularImpulse *centerAngularVelocity ) const = 0;
// calculate drag scale
virtual float CalculateLinearDrag( const Vector &unitDirection ) const = 0;
virtual float CalculateAngularDrag( const Vector &objectSpaceRotationAxis ) const = 0;
// returns true if the object is in contact with another object
// if true, puts a point on the contact surface in contactPoint, and
// a pointer to the object in contactObject
// NOTE: You can pass NULL for either to avoid computations
// BUGBUG: Use CreateFrictionSnapshot instead of this - this is a simple hack
virtual bool GetContactPoint( Vector *contactPoint, IPhysicsObject **contactObject ) const = 0;
// refactor this a bit - move some of this to IPhysicsShadowController
virtual void SetShadow( float maxSpeed, float maxAngularSpeed, bool allowPhysicsMovement, bool allowPhysicsRotation ) = 0;
virtual void UpdateShadow( const Vector &targetPosition, const QAngle &targetAngles, bool tempDisableGravity, float timeOffset ) = 0;
// returns number of ticks since last Update() call
virtual int GetShadowPosition( Vector *position, QAngle *angles ) const = 0;
virtual IPhysicsShadowController *GetShadowController( void ) const = 0;
virtual void RemoveShadowController() = 0;
// applies the math of the shadow controller to this object.
// for use in your own controllers
// returns the new value of secondsToArrival with dt time elapsed
virtual float ComputeShadowControl( const hlshadowcontrol_params_t ¶ms, float secondsToArrival, float dt ) = 0;
virtual const CPhysCollide *GetCollide( void ) const = 0;
virtual const char *GetName() const = 0;
virtual void BecomeTrigger() = 0;
virtual void RemoveTrigger() = 0;
// sets the object to be hinged. Fixed it place, but able to rotate around one axis.
virtual void BecomeHinged( int localAxis ) = 0;
// resets the object to original state
virtual void RemoveHinged() = 0;
// used to iterate the contact points of an object
virtual IPhysicsFrictionSnapshot *CreateFrictionSnapshot() = 0;
virtual void DestroyFrictionSnapshot( IPhysicsFrictionSnapshot *pSnapshot ) = 0;
// dumps info about the object to Msg()
virtual void OutputDebugInfo() const = 0;
#if OBJECT_WELDING
virtual void WeldToObject( IPhysicsObject *pParent ) = 0;
virtual void RemoveWeld( IPhysicsObject *pOther ) = 0;
virtual void RemoveAllWelds( void ) = 0;
#endif
// EnableGravity still determines whether to apply gravity
// This flag determines which gravity constant to use for an alternate gravity effect
virtual void SetUseAlternateGravity( bool bSet ) = 0;
virtual void SetCollisionHints( uint32 collisionHints ) = 0;
virtual uint32 GetCollisionHints() const = 0;
inline bool IsPredicted( void ) const { return GetPredictedInterface() != NULL; } //true if class has an IPredictedPhysicsObject interface
virtual IPredictedPhysicsObject *GetPredictedInterface( void ) const = 0;
virtual void SyncWith( IPhysicsObject *pOther ) = 0;
};
abstract_class IPredictedPhysicsObject : public IPhysicsObject
{
public:
virtual ~IPredictedPhysicsObject( void ) {}
virtual void SetErrorDelta_Position( const Vector &vPosition ) = 0;
virtual void SetErrorDelta_Velocity( const Vector &vVelocity ) = 0;
};
abstract_class IPhysicsSpring
{
public:
virtual ~IPhysicsSpring( void ) {}
virtual void GetEndpoints( Vector *worldPositionStart, Vector *worldPositionEnd ) = 0;
virtual void SetSpringConstant( float flSpringContant) = 0;
virtual void SetSpringDamping( float flSpringDamping) = 0;
virtual void SetSpringLength( float flSpringLenght) = 0;
// Get the starting object
virtual IPhysicsObject *GetStartObject( void ) = 0;
// Get the end object
virtual IPhysicsObject *GetEndObject( void ) = 0;
};
//-----------------------------------------------------------------------------
// Purpose: These properties are defined per-material. This is accessible at
// each triangle in a collision mesh
//-----------------------------------------------------------------------------
struct surfacephysicsparams_t
{
// vphysics physical properties
float friction;
float elasticity; // collision elasticity - used to compute coefficient of restitution
float density; // physical density (in kg / m^3)
float thickness; // material thickness if not solid (sheet materials) in inches
float dampening;
};
struct surfaceaudioparams_t
{
// sounds / audio data
float reflectivity; // like elasticity, but how much sound should be reflected by this surface
float hardnessFactor; // like elasticity, but only affects impact sound choices
float roughnessFactor; // like friction, but only affects scrape sound choices
// audio thresholds
float roughThreshold; // surface roughness > this causes "rough" scrapes, < this causes "smooth" scrapes
float hardThreshold; // surface hardness > this causes "hard" impacts, < this causes "soft" impacts
float hardVelocityThreshold; // collision velocity > this causes "hard" impacts, < this causes "soft" impacts
// NOTE: Hard impacts must meet both hardnessFactor AND velocity thresholds
};
struct surfacesoundnames_t
{
unsigned short walkStepLeft;
unsigned short walkStepRight;
unsigned short runStepLeft;
unsigned short runStepRight;
unsigned short impactSoft;
unsigned short impactHard;
unsigned short scrapeSmooth;
unsigned short scrapeRough;
unsigned short bulletImpact;
unsigned short rolling;
unsigned short breakSound;
unsigned short strainSound;
};
struct surfacesoundhandles_t
{
HSOUNDSCRIPTHASH walkStepLeft;
HSOUNDSCRIPTHASH walkStepRight;
HSOUNDSCRIPTHASH runStepLeft;
HSOUNDSCRIPTHASH runStepRight;
HSOUNDSCRIPTHASH impactSoft;
HSOUNDSCRIPTHASH impactHard;
HSOUNDSCRIPTHASH scrapeSmooth;
HSOUNDSCRIPTHASH scrapeRough;
HSOUNDSCRIPTHASH bulletImpact;
HSOUNDSCRIPTHASH rolling;
HSOUNDSCRIPTHASH breakSound;
HSOUNDSCRIPTHASH strainSound;
};
struct surfacegameprops_t
{
// game movement data
float maxSpeedFactor; // Modulates player max speed when walking on this surface
float jumpFactor; // Indicates how much higher the player should jump when on the surface
// Game-specific data
float penetrationModifier;
float damageModifier;
unsigned short material;
// Indicates whether or not the player is on a ladder.
unsigned char climbable;
unsigned char pad;
};
//-----------------------------------------------------------------------------
// Purpose: Each different material has an entry like this
//-----------------------------------------------------------------------------
struct surfacedata_t
{
surfacephysicsparams_t physics; // physics parameters
surfaceaudioparams_t audio; // audio parameters
surfacesoundnames_t sounds; // names of linked sounds
surfacegameprops_t game; // Game data / properties
surfacesoundhandles_t soundhandles;
};
class ISaveRestoreOps;
#define VPHYSICS_SURFACEPROPS_INTERFACE_VERSION "VPhysicsSurfaceProps001"
abstract_class IPhysicsSurfaceProps
{
public:
virtual ~IPhysicsSurfaceProps( void ) {}
// parses a text file containing surface prop keys
virtual int ParseSurfaceData( const char *pFilename, const char *pTextfile ) = 0;
// current number of entries in the database
virtual int SurfacePropCount( void ) const = 0;
virtual int GetSurfaceIndex( const char *pSurfacePropName ) const = 0;
virtual void GetPhysicsProperties( int surfaceDataIndex, float *density, float *thickness, float *friction, float *elasticity ) const = 0;
virtual surfacedata_t *GetSurfaceData( int surfaceDataIndex ) = 0;
virtual const char *GetString( unsigned short stringTableIndex ) const = 0;
virtual const char *GetPropName( int surfaceDataIndex ) const = 0;
// sets the global index table for world materials
// UNDONE: Make this per-CPhysCollide
virtual void SetWorldMaterialIndexTable( int *pMapArray, int mapSize ) = 0;
// NOTE: Same as GetPhysicsProperties, but maybe more convenient
virtual void GetPhysicsParameters( int surfaceDataIndex, surfacephysicsparams_t *pParamsOut ) const = 0;
//lwss - commented this out, not used.
//virtual ISaveRestoreOps* GetMaterialIndexDataOps() const = 0;
};
abstract_class IPhysicsFluidController
{
public:
virtual ~IPhysicsFluidController( void ) {}
virtual void SetGameData( void *pGameData ) = 0;
virtual void *GetGameData( void ) const = 0;
virtual void GetSurfacePlane( Vector *pNormal, float *pDist ) const = 0;
virtual float GetDensity() const = 0;
virtual void WakeAllSleepingObjects() = 0;
virtual int GetContents() const = 0;
};
//-----------------------------------------------------------------------------
// Purpose: parameter block for creating fluid dynamic motion
// UNDONE: Expose additional fluid model paramters?
//-----------------------------------------------------------------------------
struct fluidparams_t
{
Vector4D surfacePlane; // x,y,z normal, dist (plane constant) fluid surface
Vector currentVelocity; // velocity of the current in inches/second
float damping; // damping factor for buoyancy (tweak)
float torqueFactor;
float viscosityFactor;
void *pGameData;
bool useAerodynamics;// true if this controller should calculate surface pressure
int contents;
fluidparams_t() {}
fluidparams_t( fluidparams_t const& src )
{
Vector4DCopy( src.surfacePlane, surfacePlane );
VectorCopy( src.currentVelocity, currentVelocity );
damping = src.damping;
torqueFactor = src.torqueFactor;
viscosityFactor = src.viscosityFactor;
contents = src.contents;
}
};
//-----------------------------------------------------------------------------
// Purpose: parameter block for creating linear springs
// UNDONE: Expose additional spring model paramters?
//-----------------------------------------------------------------------------
struct springparams_t
{
springparams_t()
{
memset( this, 0, sizeof(*this) );
}
float constant; // spring constant
float naturalLength;// relaxed length
float damping; // damping factor
float relativeDamping; // relative damping (damping proportional to the change in the relative position of the objects)
Vector startPosition;
Vector endPosition;
bool useLocalPositions; // start & end Position are in local space to start and end objects if this is true
bool onlyStretch; // only apply forces when the length is greater than the natural length
};
//-----------------------------------------------------------------------------
// Purpose: parameter block for creating polygonal objects
//-----------------------------------------------------------------------------
struct objectparams_t
{
Vector *massCenterOverride;
float mass;
float inertia;
float damping;
float rotdamping;
float rotInertiaLimit;
const char *pName; // used only for debugging
void *pGameData;
float volume;
float dragCoefficient;
bool enableCollisions;
};
struct convertconvexparams_t
{
bool buildOuterConvexHull;
bool buildDragAxisAreas;
bool buildOptimizedTraceTables;
bool checkOptimalTracing;
bool bUseFastApproximateInertiaTensor;
bool bBuildAABBTree;
float dragAreaEpsilon;
CPhysConvex *pForcedOuterHull;
void Defaults()
{
dragAreaEpsilon = 0.25f; // 0.5in x 0.5in square
buildOuterConvexHull = false;
buildDragAxisAreas = false;
buildOptimizedTraceTables = false;
checkOptimalTracing = false;
bUseFastApproximateInertiaTensor = false;
bBuildAABBTree = false;
pForcedOuterHull = NULL;
}
};
//-----------------------------------------------------------------------------
// Physics interface IDs
//
// Note that right now the order of the enum also defines the order of save/load
//-----------------------------------------------------------------------------
// Purpose: parameter blocks for save and load operations
//-----------------------------------------------------------------------------
struct physsaveparams_t
{
ISave *pSave;
void *pObject;
PhysInterfaceId_t type;
};
struct physrestoreparams_t
{
IRestore *pRestore;
void **ppObject;
PhysInterfaceId_t type;
void *pGameData;
const char *pName; // used only for debugging
const CPhysCollide *pCollisionModel;
IPhysicsEnvironment *pEnvironment;
IPhysicsGameTrace *pGameTrace;
};
struct physrecreateparams_t
{
void *pOldObject;
void *pNewObject;
};
struct physprerestoreparams_t
{
int recreatedObjectCount;
physrecreateparams_t recreatedObjectList[1];
};
//-------------------------------------
#define DEFINE_PIID( type, enumval ) \
template <> inline PhysInterfaceId_t GetPhysIID<type>( type ** ) { return enumval; }
template <class PHYSPTR> inline PhysInterfaceId_t GetPhysIID(PHYSPTR **); // will get link error if no match
DEFINE_PIID( IPhysicsObject, PIID_IPHYSICSOBJECT );
DEFINE_PIID( IPhysicsFluidController, PIID_IPHYSICSFLUIDCONTROLLER );
DEFINE_PIID( IPhysicsSpring, PIID_IPHYSICSSPRING );
DEFINE_PIID( IPhysicsConstraintGroup, PIID_IPHYSICSCONSTRAINTGROUP );
DEFINE_PIID( IPhysicsConstraint, PIID_IPHYSICSCONSTRAINT );
DEFINE_PIID( IPhysicsShadowController, PIID_IPHYSICSSHADOWCONTROLLER );
DEFINE_PIID( IPhysicsPlayerController, PIID_IPHYSICSPLAYERCONTROLLER );
DEFINE_PIID( IPhysicsMotionController, PIID_IPHYSICSMOTIONCONTROLLER );
DEFINE_PIID( IPhysicsVehicleController, PIID_IPHYSICSVEHICLECONTROLLER );
DEFINE_PIID( IPhysicsGameTrace, PIID_IPHYSICSGAMETRACE );
//-----------------------------------------------------------------------------
#endif // VPHYSICS_INTERFACE_H
| [
"bbchallenger100@gmail.com"
] | bbchallenger100@gmail.com |
2db6139b17c565f378bf89f8c625046ea2ab0ad2 | 753a57645d0824a750fa07176bdf7e37369940f6 | /Engine/Plugins/UnrealCS/Source/MonoPlugin/Private/GeneratedScriptLibraries/LightmassPrimitiveSettingsObject.script.h | aa3dfbbe734c6832f9fd395a4e2484542f48f538 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | marynate/UnrealCS | 5782c4dd1b3fe6e136dcee54ce430aabd97b70a4 | de43f7e42ca037445202d59c8114fafc30e031ec | refs/heads/master | 2021-01-19T13:01:35.048880 | 2017-02-22T02:18:33 | 2017-02-22T02:18:33 | 82,354,770 | 2 | 1 | null | 2017-02-18T02:17:07 | 2017-02-18T02:17:06 | null | UTF-8 | C++ | false | false | 351 | h | #pragma once
namespace UnrealEngine
{
class _ULightmassPrimitiveSettingsObject
{
static UClass* StaticClass(){return ULightmassPrimitiveSettingsObject::StaticClass();}
public:
static void BindFunctions()
{
mono_add_internal_call("UnrealEngine.ULightmassPrimitiveSettingsObject::StaticClass",(const void*)StaticClass);
}
}
;
}
| [
"xg_55@126.com"
] | xg_55@126.com |
5a2fecb3012ea7151f989100d27ebdf61070ac65 | adf4e5bb27ab2bf5646b6b493698e03c16b38018 | /Pacman/Scene.cpp | 3c049699e4c16bb2da36a5b421f7fd12b83fca83 | [] | no_license | Milosz503/Pacman | 6102ee6860a55bdbc0592d138ef2eff4cee69357 | 6798079677f2c28d24f26e7fca7d7f6ff78dd929 | refs/heads/master | 2023-09-04T17:10:20.197381 | 2018-06-04T13:58:49 | 2018-06-04T13:58:49 | 429,800,431 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,541 | cpp | #include "Scene.h"
#include "ConsoleWindow.h"
#include "World.h"
Scene::Scene(World* world) :
world_(world),
player_(nullptr),
width_(0),
height_(0)
{
}
Scene::~Scene()
{
removeEntities();
removeTiles();
cleanObjects();
}
void Scene::cleanObjects()
{
//for (int x = 0; x < tiles_.size(); ++x)
//{
// for (int y = 0; y < tiles_[x].size(); ++y)
// {
// if (tiles_[x][y] != nullptr)
// {
// if (tiles_[x][y]->isToRemove())
// {
// tilesToRemove_.push_back(tiles_[x][y]);
// tiles_[x][y] = nullptr;
// }
// else
// {
// tiles_[x][y]->update();
// }
// }
// }
//}
for (int i = 0; i < tilesToRemove_.size(); ++i)
{
world_->getSystems()->sendSystemEvent(new OnRemoveEvent(tilesToRemove_[i]));
delete tilesToRemove_[i];
tilesToRemove_[i] = nullptr;
}
tilesToRemove_.erase(std::remove(tilesToRemove_.begin(), tilesToRemove_.end(), nullptr), tilesToRemove_.end());
for (int i = 0; i < entities_.size(); ++i)
{
if (entities_[i]->isToRemove())
{
world_->getSystems()->sendSystemEvent(new OnRemoveEvent(entities_[i]));
if (entities_[i] == player_)
player_ = nullptr;
delete entities_[i];
entities_[i] = nullptr;
}
}
entities_.erase(std::remove(entities_.begin(), entities_.end(), nullptr), entities_.end());
}
sf::Vector2i Scene::normalize(sf::Vector2i position) const
{
if (position.x < 0)
position.x = width_ - ((-position.x)%width_);
if (position.y < 0)
{
position.y = height_ - ((-position.y)%height_);
}
position.x %= width_;
position.y %= height_;
return position;
}
bool Scene::isInside(unsigned x, unsigned y)
{
if (x < width_ && y < height_)
return true;
return false;
}
bool Scene::isTilePhysical(int x, int y)
{
sf::Vector2i pos = normalize(sf::Vector2i(x, y));
if (tiles_[pos.x][pos.y] == nullptr)
return false;
return tiles_[pos.x][pos.y]->isPhysical();
}
bool Scene::isTilePhysicalF(sf::Vector2i & pos)
{
if (tiles_[pos.x][pos.y] == nullptr)
return false;
return tiles_[pos.x][pos.y]->isPhysical();
}
Tile * Scene::getTile(int x, int y) const
{
sf::Vector2i pos = normalize(sf::Vector2i(x, y));
return tiles_[pos.x][pos.y];
}
Entity * Scene::findEntity(int x, int y) const
{
for (auto& entity : entities_)
{
if (entity->getX() == x && entity->getY() == y)
return entity;
}
return nullptr;
}
std::vector<Entity*>& Scene::getEntities()
{
return entities_;
}
Entity * Scene::getPlayer()
{
if (player_ == nullptr)
{
std::cout << "PLAYER IS NULL!" << std::endl;
}
return player_;
}
unsigned Scene::getWidth()
{
return width_;
}
unsigned Scene::getHeight()
{
return height_;
}
void Scene::setSize(int width, int height)
{
for (auto& entity : entities_)
{
if (entity->getX() >= width || entity->getY() >= height)
{
entity->markToRemove();
}
}
for (int x = width; x < width_; ++x)
{
for (int y = 0; y < height_; ++y)
{
if (tiles_[x][y]) {
removeTile(tiles_[x][y]);
std::cout << "Removed tile: (" << x << ", " << y << ")" << std::endl;
}
}
}
for (int x = 0; x < width_; ++x)
{
for (int y = height; y < height_; ++y)
{
if (tiles_[x][y]) {
removeTile(tiles_[x][y]);
std::cout << "Removed tile: (" << x << ", " << y << ")" << std::endl;
}
}
}
width_ = width;
height_ = height;
tiles_.resize(width_);
for (int x = 0; x < tiles_.size(); ++x)
{
tiles_[x].resize(height_);
}
cleanObjects();
}
Tile * Scene::createTile(sol::table luaInstance, std::string category, int x, int y)
{
Tile* tile = new Tile(world_, luaInstance);
tile->setCategory(category);
tile->setPosition(x, y);
if (x < 0 || x >= width_ || y < 0 || y >= height_)
{
std::cout << "Warning: cannot add tile on position (" << x << ", " << y << ")" << std::endl;
tilesToRemove_.push_back(tile);
return tile;
}
if (tiles_[x][y] != nullptr)
{
removeTile(tiles_[x][y]);
}
tiles_[x][y] = tile;
return tile;
}
Entity * Scene::createEntity(sol::table luaInstance, std::string category)
{
Entity* entity = new Entity(world_, luaInstance);
entity->setCategory(category);
entities_.push_back(entity);
if (entity->getCategory() == "player")
{
player_ = entity;
std::cout << "player! " << entity->getCategory() << std::endl;
}
return entity;
}
void Scene::moveEntity(Entity * entity, sf::Vector2i & move)
{
entity->move(move);
entity->setPosition(normalize(entity->getPosition()));
}
void Scene::removeEntities()
{
for (int i = 0; i < entities_.size(); ++i)
{
entities_[i]->markToRemove();
}
}
void Scene::removeTiles()
{
for (auto& column : tiles_)
{
for (auto& tile : column)
{
if(tile != nullptr)
removeTile(tile);
}
}
}
void Scene::removeTile(Tile * tile)
{
if (tile != nullptr && tile == tiles_[tile->getX()][tile->getY()])
{
tile->addedToRemove();
tile->markToRemove();
tilesToRemove_.push_back(tile);
tiles_[tile->getX()][tile->getY()] = nullptr;
}
}
void Scene::update()
{
unsigned long long frameNumber = world_->getFrameNumber();
//for (auto& entity : entities_)
//{
// entity->update();
//
//}
cleanObjects();
//std::cout << "Entities size: " << entities_.size() << std::endl;
}
void Scene::draw()
{
for (int x = 0; x < tiles_.size(); ++x)
{
for (int y = 0; y < tiles_[x].size(); ++y)
{
if (tiles_[x][y] != nullptr)
world_->getConsole()->draw(*tiles_[x][y]);
}
}
for (auto& entity : entities_)
{
world_->getConsole()->draw(*entity);
}
if(player_ != nullptr)
world_->getConsole()->draw(*player_);
}
| [
"milosz.0518@gmail.com"
] | milosz.0518@gmail.com |
a89b95d3f506f968045cbb0fe24a5b29b1e596d3 | 52fea6f8611737f202ae7012b413199e28e57fa4 | /src/stealth.h | 31f1f95cee737675b1488cd8c1893a202ed990c7 | [
"MIT"
] | permissive | orestdrag/mynovacoin | dceb9f13d9777fac0a4eafa52290a8be36496bb2 | 1749132193870c4147211e421adb17bc0327d10b | refs/heads/master | 2021-01-24T07:57:05.102009 | 2018-03-12T13:17:24 | 2018-03-12T13:17:24 | 122,965,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,478 | h | // Copyright (c) 2014 The ShadowCoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#ifndef BCCA_STEALTH_H
#define BCCA_STEALTH_H
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <inttypes.h>
#include "util.h"
#include "serialize.h"
#include "key.h"
#include "hash.h"
#include "types.h"
const uint32_t MAX_STEALTH_NARRATION_SIZE = 48;
typedef uint32_t stealth_bitfield;
struct stealth_prefix
{
uint8_t number_bits;
stealth_bitfield bitfield;
};
const uint256 MAX_SECRET("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140");
const uint256 MIN_SECRET(16000); // increase? min valid key is 1
class CStealthAddress
{
public:
CStealthAddress()
{
options = 0;
};
uint8_t options;
ec_point scan_pubkey;
ec_point spend_pubkey;
//std::vector<ec_point> spend_pubkeys;
size_t number_signatures;
stealth_prefix prefix;
mutable std::string label;
data_chunk scan_secret;
data_chunk spend_secret;
bool SetEncoded(const std::string& encodedAddress);
std::string Encoded() const;
int SetScanPubKey(CPubKey pk);
bool operator <(const CStealthAddress& y) const
{
return memcmp(&scan_pubkey[0], &y.scan_pubkey[0], EC_COMPRESSED_SIZE) < 0;
};
bool operator ==(const CStealthAddress& y) const
{
return memcmp(&scan_pubkey[0], &y.scan_pubkey[0], EC_COMPRESSED_SIZE) == 0;
};
IMPLEMENT_SERIALIZE
(
READWRITE(this->options);
READWRITE(this->scan_pubkey);
READWRITE(this->spend_pubkey);
READWRITE(this->label);
READWRITE(this->scan_secret);
READWRITE(this->spend_secret);
);
};
int GenerateRandomSecret(ec_secret& out);
int SecretToPublicKey(const ec_secret& secret, ec_point& out);
int StealthSecret(ec_secret& secret, ec_point& pubkey, const ec_point& pkSpend, ec_secret& sharedSOut, ec_point& pkOut);
int StealthSecretSpend(ec_secret& scanSecret, ec_point& ephemPubkey, ec_secret& spendSecret, ec_secret& secretOut);
int StealthSharedToSecretSpend(const ec_secret& sharedS, const ec_secret& spendSecret, ec_secret& secretOut);
int StealthSharedToPublicKey(const ec_point& pkSpend, const ec_secret &sharedS, ec_point &pkOut);
bool IsStealthAddress(const std::string& encodedAddress);
#endif // BCCA_STEALTH_H
| [
"orestdrag@gmail.com"
] | orestdrag@gmail.com |
57c2b6a9edf14d14e9bcc13592f0ec19edea4866 | 87aba51b1f708b47d78b5c4180baf731d752e26d | /Replication/DataFileSystem/PRODUCT_SOURCE_CODE/itk/Modules/Core/Common/include/itkTorusInteriorExteriorSpatialFunction.hxx | 6f63fe33f05e31967768cca9f74fc3ec264480f7 | [] | no_license | jstavr/Architecture-Relation-Evaluator | 12c225941e9a4942e83eb6d78f778c3cf5275363 | c63c056ee6737a3d90fac628f2bc50b85c6bd0dc | refs/heads/master | 2020-12-31T05:10:08.774893 | 2016-05-14T16:09:40 | 2016-05-14T16:09:40 | 58,766,508 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,577 | hxx | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 __itkTorusInteriorExteriorSpatialFunction_hxx
#define __itkTorusInteriorExteriorSpatialFunction_hxx
#include "itkTorusInteriorExteriorSpatialFunction.h"
namespace itk
{
template< unsigned int VDimension, typename TInput >
TorusInteriorExteriorSpatialFunction< VDimension, TInput >
::TorusInteriorExteriorSpatialFunction()
{
m_Origin.Fill(0.0);
// These default values are not picked for any particular reason
m_MajorRadius = 3;
m_MinorRadius = 1;
}
template< unsigned int VDimension, typename TInput >
TorusInteriorExteriorSpatialFunction< VDimension, TInput >
::~TorusInteriorExteriorSpatialFunction()
{}
template< unsigned int VDimension, typename TInput >
typename TorusInteriorExteriorSpatialFunction< VDimension, TInput >::OutputType
TorusInteriorExteriorSpatialFunction< VDimension, TInput >
::Evaluate(const InputType & position) const
{
double x = position[0] - m_Origin[0];
double y = position[1] - m_Origin[1];
double z = position[2] - m_Origin[2];
double k = vcl_pow(m_MajorRadius - vcl_sqrt(x * x + y * y), 2.0) + z * z;
if ( k <= ( m_MinorRadius * m_MinorRadius ) )
{
return true;
}
else
{
return false;
}
}
template< unsigned int VDimension, typename TInput >
void
TorusInteriorExteriorSpatialFunction< VDimension, TInput >
::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
unsigned int i;
os << indent << "Origin: [";
for ( i = 0; i < VDimension - 1; i++ )
{
os << m_Origin[i] << ", ";
}
os << "]" << std::endl;
os << indent << "Major radius: " << m_MajorRadius << std::endl;
os << indent << "Minor radius: " << m_MinorRadius << std::endl;
}
} // end namespace itk
#endif
| [
"jstavr2@gmail.com"
] | jstavr2@gmail.com |
58e9ac31ff123567f234c44d22f284f63c5511f6 | 7ee32ddb0cdfdf1993aa4967e1045790690d7089 | /Topcoder/StoneGame.cpp | 5d1062ea32a6382e076e8504785f56af572fc0e2 | [] | no_license | ajimenezh/Programing-Contests | b9b91c31814875fd5544d63d7365b3fc20abd354 | ad47d1f38b780de46997f16fbaa3338c9aca0e1a | refs/heads/master | 2020-12-24T14:56:14.154367 | 2017-10-16T21:05:01 | 2017-10-16T21:05:01 | 11,746,917 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 6,006 | cpp | #include <iostream>
#include <sstream>
#include <vector>
#include <string.h>
#include <algorithm>
#include <utility>
#include <set>
#include <map>
#include <deque>
#include <queue>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstdio>
#include <stdio.h>
using namespace std;
#define rep(it,s) for(__typeof((s).begin()) it=(s).begin();it!=(s).end();it++)
class StoneGame {
public:
int getScore(vector <int> treasure, vector <int> stones) ;
};
int StoneGame::getScore(vector <int> treasure, vector <int> stones) {
int p = 0;
while (true) {
bool done = 0;
int last = -1;
for (int i=0; i<treasure.size(); i++) {
if (stones[i]==1) {
if (last!=-1) {
if (treasure[last]<treasure[i]) {
stones[last]++;
stones[i]--;
p -= treasure[last];
p += treasure[i];
last = i;
}
}
else {
stones[i]--;
p += treasure[i];
done = 1;
last = i;
done = 1;
}
}
}
if (!done) {
for (int i=0; i<treasure.size(); i++) {
if (stones[i]>2) {
stones[i]--;
done = 1;
break;
}
}
}
if (!done) {
for (int i=0; i<treasure.size(); i++) {
if (stones[i]==2) {
stones[i]--;
done = 1;
break;
}
}
}
if (!done) break;
done = 0;
last = -1;
for (int i=0; i<treasure.size(); i++) {
if (stones[i]==1) {
if (last!=-1) {
if (treasure[last]<treasure[i]) {
stones[last]++;
stones[i]--;
last = i;
}
}
else {
stones[i]--;
done = 1;
last = i;
done = 1;
}
}
}
if (!done) {
for (int i=0; i<treasure.size(); i++) {
if (stones[i]>2) {
stones[i]--;
done = 1;
break;
}
}
}
if (!done) {
for (int i=0; i<treasure.size(); i++) {
if (stones[i]==2) {
stones[i]--;
done = 1;
break;
}
}
}
if (!done) break;
if (!done) break;
}
return p;
};
//BEGIN CUT HERE
#include <ctime>
#include <cmath>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[])
{
if (argc == 1)
{
cout << "Testing StoneGame (500.0 points)" << endl << endl;
for (int i = 0; i < 20; i++)
{
ostringstream s; s << argv[0] << " " << i;
int exitCode = system(s.str().c_str());
if (exitCode)
cout << "#" << i << ": Runtime Error" << endl;
}
int T = time(NULL)-1391000642;
double PT = T/60.0, TT = 75.0;
cout.setf(ios::fixed,ios::floatfield);
cout.precision(2);
cout << endl;
cout << "Time : " << T/60 << " minutes " << T%60 << " secs" << endl;
cout << "Score : " << 500.0*(.3+(.7*TT*TT)/(10.0*PT*PT+TT*TT)) << " points" << endl;
}
else
{
int _tc; istringstream(argv[1]) >> _tc;
StoneGame _obj;
int _expected, _received;
time_t _start = clock();
switch (_tc)
{
case 0:
{
int treasure[] = {3,2};
int stones[] = {1,2};
_expected = 5;
_received = _obj.getScore(vector <int>(treasure, treasure+sizeof(treasure)/sizeof(int)), vector <int>(stones, stones+sizeof(stones)/sizeof(int))); break;
}
case 1:
{
int treasure[] = {5,4,3,2,1};
int stones[] = {1,1,1,1,1};
_expected = 9;
_received = _obj.getScore(vector <int>(treasure, treasure+sizeof(treasure)/sizeof(int)), vector <int>(stones, stones+sizeof(stones)/sizeof(int))); break;
}
case 2:
{
int treasure[] = {5,5};
int stones[] = {2,2};
_expected = 0;
_received = _obj.getScore(vector <int>(treasure, treasure+sizeof(treasure)/sizeof(int)), vector <int>(stones, stones+sizeof(stones)/sizeof(int))); break;
}
case 3:
{
int treasure[] = {1};
int stones[] = {10};
_expected = 0;
_received = _obj.getScore(vector <int>(treasure, treasure+sizeof(treasure)/sizeof(int)), vector <int>(stones, stones+sizeof(stones)/sizeof(int))); break;
}
/*case 4:
{
int treasure[] = ;
int stones[] = ;
_expected = ;
_received = _obj.getScore(vector <int>(treasure, treasure+sizeof(treasure)/sizeof(int)), vector <int>(stones, stones+sizeof(stones)/sizeof(int))); break;
}*/
/*case 5:
{
int treasure[] = ;
int stones[] = ;
_expected = ;
_received = _obj.getScore(vector <int>(treasure, treasure+sizeof(treasure)/sizeof(int)), vector <int>(stones, stones+sizeof(stones)/sizeof(int))); break;
}*/
/*case 6:
{
int treasure[] = ;
int stones[] = ;
_expected = ;
_received = _obj.getScore(vector <int>(treasure, treasure+sizeof(treasure)/sizeof(int)), vector <int>(stones, stones+sizeof(stones)/sizeof(int))); break;
}*/
default: return 0;
}
cout.setf(ios::fixed,ios::floatfield);
cout.precision(2);
double _elapsed = (double)(clock()-_start)/CLOCKS_PER_SEC;
if (_received == _expected)
cout << "#" << _tc << ": Passed (" << _elapsed << " secs)" << endl;
else
{
cout << "#" << _tc << ": Failed (" << _elapsed << " secs)" << endl;
cout << " Expected: " << _expected << endl;
cout << " Received: " << _received << endl;
}
}
}
//END CUT HERE
| [
"alejandrojh90@gmail.com"
] | alejandrojh90@gmail.com |
d0d5a0e7042d6db287c00053a89fd485dca007a3 | bdff7e2a59e5b266f82b7ab34ac4f44a00413adb | /Parallel-Computing-Class/HW2/timeBomb.cpp | 6b8cd981ee61ded104dd604f9353c4363e511c5c | [] | no_license | BrighamM/Course-Work-Archive | 256ffcabce672e8f7a09c7d2cc67b4b0f4e9b096 | 2e92872e36b86425f1d52b835f277a28772b2763 | refs/heads/master | 2023-06-23T14:50:26.685535 | 2021-05-15T22:25:07 | 2021-05-15T22:25:07 | 119,736,675 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,200 | cpp | #include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <mpi.h>
#define MCW MPI_COMM_WORLD
using namespace std;
int main(int argc, char **argv){
int rank;
int size;
int eliminatedProcess = -1;
srand(time(0));
int bombTimer=rand()%20 + 1;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MCW, &rank);
MPI_Comm_size(MCW, &size);
/**
* Remember!
*
* MPI_Send(
* void* data,
* int count,
* MPI_Datatype datatype,
* int destination,
* int tag,
* MPI_Comm communicator
* );
*
**/
/**
* And dont forget!
*
* MPI_Recv(
* void* data,
* int count,
* MPI_Datatype datatype,
* int source,
* int tag,
* MPI_Comm communicator,
* MPI_Status* status
* )
*
**/
if(rank==0){
// We are adding more logic so that we do not pass the bomb to ourselves.
int nextPassedPlayer = rand()%size;
while(nextPassedPlayer == 0){
nextPassedPlayer = rand()%size;
}
cout<<"*******************************************************"<<endl;
cout<<"* WE ARE NOW BEGINNING THE TIME BOMB GAME!!! *"<<endl;
cout<<"* GAME STATS: *"<<endl;
cout<<"* NUMBER OF PLAYERS: "<<size<<" *"<<endl;
cout<<"* STARTING BOMB TIME :"<<bombTimer<<" *"<<endl;
cout<<"* BEGIN THE GAME!!!!!!!!! *"<<endl;
cout<<"*******************************************************"<<endl;
cout<<"I am process "<<rank<<" and the bomb timer is at: "<<bombTimer<<" Passing to: "<<nextPassedPlayer<<endl;
MPI_Send(&bombTimer,1,MPI_INT,nextPassedPlayer,0,MCW);
}
while(true){
// Run until the bomb expl
MPI_Recv(&bombTimer,1,MPI_INT,MPI_ANY_SOURCE,0,MCW,MPI_STATUS_IGNORE);
if(!bombTimer){
cout << rank << ": all done."<<endl;
break;
}
// decrement the bomb timer
bombTimer--;
cout<<"I am process "<<rank<<" and the bomb timer is at: "<<bombTimer<<endl;
if(bombTimer == 0){
eliminatedProcess = rank;
}
if(!bombTimer){
for(int i=0;i<size;++i){
MPI_Send(&bombTimer,1,MPI_INT,i,0,MCW);
}
}
// We are not passing the bomb off to our selves. That is stupid!
// Thats like taking two turns in a row a Russian Roulette!
int passToPlayer = rand()%size;
while(passToPlayer == rank){
passToPlayer = rand()%size;
}
MPI_Send(&bombTimer,1,MPI_INT,passToPlayer,0,MCW);
}
if(rank == eliminatedProcess){
cout<<"*******************************************************"<<endl;
cout<<"* THE GAME IS OVER!!! *"<<endl;
cout<<"* PROCESS: "<<eliminatedProcess<<" HAS BEEN ELIMINATED!!! *"<<endl;
cout<<"*******************************************************"<<endl;
}
MPI_Finalize();
return 0;
} | [
"brigham.michaelis@gmail.com"
] | brigham.michaelis@gmail.com |
b9ca5b9fc60d6f560cde434383d7640aaa5e9120 | 7d39413b4d6e99369519db7772f010dce95e79ed | /cpp/test/shared_from_this_test.h | 14a55d55447071233fe80aad7ccde4ba0a5afd05 | [] | no_license | wangjiaming0909/al | 62a890cae0c1b753eccf14eec770adfb71fa8957 | 2b40372edfc9dcde1a379e97175f006c3c53f557 | refs/heads/master | 2023-04-20T22:45:11.799670 | 2023-04-15T09:52:44 | 2023-04-15T09:52:44 | 145,864,078 | 0 | 0 | null | 2022-12-08T01:36:19 | 2018-08-23T14:20:01 | HTML | UTF-8 | C++ | false | false | 1,102 | h | #pragma once
#include <boost\enable_shared_from_this.hpp>
#include <string>
using namespace boost;
class class_without_default_constructor {
public:
class_without_default_constructor(int a) : a_(a){}
private:
int a_;
};
class share_from_me : public enable_shared_from_this<share_from_me>{
public:
friend std::ostream& operator<<(std::ostream& os, const share_from_me& me) {
os << me.a_;
return os;
}
share_from_me(int a) : a_(a), c_(a){}
shared_ptr<share_from_me> f() {
return this->shared_from_this();
}
private:
int a_;
std::string str_;
class_without_default_constructor c_;
};
class parent {
public:
parent() { std::cout << "parent" << std::endl; }
~parent() { std::cout << "~parent" << std::endl; }
};
std::ostream& operator<<(std::ostream& os, const parent& p) {
os << "parent";
return os;
}
class son : public parent {
public:
son() { std::cout << "son" << std::endl; }
~son() { std::cout << "~son" << std::endl; }
friend std::ostream& operator<<(std::ostream& os, const son& s) {
os << "son";
return os;
}
};
| [
"JWang284@slb.com"
] | JWang284@slb.com |
1d23406f4ef0aca27c24878df7c83170b3b097e3 | 71c3c165a803b85964a07b6b710cf6a0e8d52195 | /Technikiprogramowaniaslownik/stdafx.cpp | ea893b24a4b16e51f1b462459b88ec66a4ecde3d | [] | no_license | andrzejboni/Technikiprogramowaniaslownik | e3a20da68de6fffee07b289486f2f287f309fc0b | 9ee8e688d8b46889257eba799ebda36d3a4dee33 | refs/heads/master | 2021-01-21T20:15:22.909416 | 2017-05-23T18:56:03 | 2017-05-23T18:56:03 | 92,208,777 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 307 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Technikiprogramowaniaslownik.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"andrzej.boni@outlook.com"
] | andrzej.boni@outlook.com |
8307abb8017947deb399caad05d506a3d9d93921 | d0a0170ff260d47a7d251216723a5e8be798544f | /day06/t01/app/src/Container.cpp | d8c691f50aa4fbe3e49d69cf31ab8092a508677a | [] | no_license | mmasniy/Maraphon-CPP-Ucode | c5d5a86c53f21b268c2b138fe3023e138dfecc4c | 4611c10c342d808c3f48770058f11eced2839068 | refs/heads/master | 2022-12-09T23:49:07.052325 | 2020-08-30T16:24:08 | 2020-08-30T16:24:08 | 288,213,058 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 499 | cpp | #include "Container.h"
Container::Container(bool isLocked, const LockpickDifficulty difficulty)
: m_isLocked(isLocked), m_difficulty(difficulty){
}
bool Container::isLocked() const {
return m_isLocked;
}
LockpickDifficulty Container::lockDifficulty() const {
return m_difficulty;
}
bool Container::tryToOpen(LockpickDifficulty skill) {
if (skill >= m_difficulty || !m_isLocked) {
m_isLocked = true;
return true;
} else {
return false;
}
}
| [
"masnijmaksim@gmail.com"
] | masnijmaksim@gmail.com |
d45a953065c93aa6dced6cdcba661bb7ba942235 | 6afae5bcd6e954f76f5644669e21614e2b555e8e | /sources/terminal.h | cd8222f3e186034f91d9bee62afe7562663a10b5 | [] | no_license | intelfx/pulse-dispatcher | cdfc59b04acce1bd425b5cd23f7db343afe73ae9 | 74b7340325a1b5aec6ecdb095985174d623c8966 | refs/heads/master | 2021-01-20T09:32:47.580018 | 2014-11-23T20:11:00 | 2014-11-23T20:11:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 538 | h | #ifndef _SOURCES_TERMINAL_H
#define _SOURCES_TERMINAL_H
#include <source.h>
#include <options.h>
class TerminalSource: public AbstractSource
{
channels_mask_t toggle_mode_channels_;
bool toggle_;
std::chrono::milliseconds pulse_width_;
void toggle();
void toggle_m (channels_mask_t mask);
void toggle_internal (channels_mask_t mask);
public:
TerminalSource(const options_map_t& options);
virtual ~TerminalSource();
virtual bool runs_in_main_thread() const;
protected:
virtual void loop();
};
#endif // _SOURCES_TERMINAL_H | [
"intelfx100@gmail.com"
] | intelfx100@gmail.com |
f9f66118579705d938786bd41eafa95619c1b7c0 | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /pts/src/v20210728/model/Attributes.cpp | 4cc530ee3a69369ea15d6d5e88e338995821f42b | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 5,767 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/pts/v20210728/model/Attributes.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Pts::V20210728::Model;
using namespace std;
Attributes::Attributes() :
m_statusHasBeenSet(false),
m_resultHasBeenSet(false),
m_serviceHasBeenSet(false),
m_methodHasBeenSet(false),
m_durationHasBeenSet(false)
{
}
CoreInternalOutcome Attributes::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("Status") && !value["Status"].IsNull())
{
if (!value["Status"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Attributes.Status` IsString=false incorrectly").SetRequestId(requestId));
}
m_status = string(value["Status"].GetString());
m_statusHasBeenSet = true;
}
if (value.HasMember("Result") && !value["Result"].IsNull())
{
if (!value["Result"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Attributes.Result` IsString=false incorrectly").SetRequestId(requestId));
}
m_result = string(value["Result"].GetString());
m_resultHasBeenSet = true;
}
if (value.HasMember("Service") && !value["Service"].IsNull())
{
if (!value["Service"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Attributes.Service` IsString=false incorrectly").SetRequestId(requestId));
}
m_service = string(value["Service"].GetString());
m_serviceHasBeenSet = true;
}
if (value.HasMember("Method") && !value["Method"].IsNull())
{
if (!value["Method"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Attributes.Method` IsString=false incorrectly").SetRequestId(requestId));
}
m_method = string(value["Method"].GetString());
m_methodHasBeenSet = true;
}
if (value.HasMember("Duration") && !value["Duration"].IsNull())
{
if (!value["Duration"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Attributes.Duration` IsString=false incorrectly").SetRequestId(requestId));
}
m_duration = string(value["Duration"].GetString());
m_durationHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void Attributes::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_statusHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Status";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_status.c_str(), allocator).Move(), allocator);
}
if (m_resultHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Result";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_result.c_str(), allocator).Move(), allocator);
}
if (m_serviceHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Service";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_service.c_str(), allocator).Move(), allocator);
}
if (m_methodHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Method";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_method.c_str(), allocator).Move(), allocator);
}
if (m_durationHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Duration";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_duration.c_str(), allocator).Move(), allocator);
}
}
string Attributes::GetStatus() const
{
return m_status;
}
void Attributes::SetStatus(const string& _status)
{
m_status = _status;
m_statusHasBeenSet = true;
}
bool Attributes::StatusHasBeenSet() const
{
return m_statusHasBeenSet;
}
string Attributes::GetResult() const
{
return m_result;
}
void Attributes::SetResult(const string& _result)
{
m_result = _result;
m_resultHasBeenSet = true;
}
bool Attributes::ResultHasBeenSet() const
{
return m_resultHasBeenSet;
}
string Attributes::GetService() const
{
return m_service;
}
void Attributes::SetService(const string& _service)
{
m_service = _service;
m_serviceHasBeenSet = true;
}
bool Attributes::ServiceHasBeenSet() const
{
return m_serviceHasBeenSet;
}
string Attributes::GetMethod() const
{
return m_method;
}
void Attributes::SetMethod(const string& _method)
{
m_method = _method;
m_methodHasBeenSet = true;
}
bool Attributes::MethodHasBeenSet() const
{
return m_methodHasBeenSet;
}
string Attributes::GetDuration() const
{
return m_duration;
}
void Attributes::SetDuration(const string& _duration)
{
m_duration = _duration;
m_durationHasBeenSet = true;
}
bool Attributes::DurationHasBeenSet() const
{
return m_durationHasBeenSet;
}
| [
"anonymous"
] | anonymous |
3103c67aa8c2614ff8627c0a6e39f6bf48b74896 | 70971245fb7c522dfa06e4f632b86ff2b8499528 | /Source/Core/World/World.cpp | 0990fe324ccead11edd4484c1556eea75e6f272d | [
"MIT"
] | permissive | Cube219/CubeEngine | f0f5afdf19ab908490f2b9981fe7baaabb1dd7c4 | b54a7373be96333aa38fdf49ea32272c28c42a4b | refs/heads/master | 2021-06-08T12:38:13.206138 | 2021-03-28T06:23:20 | 2021-03-28T06:23:20 | 102,942,324 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,290 | cpp | #include "World.h"
#include "../Assertion.h"
namespace cube
{
void World::Initialize()
{
}
void World::Shutdown()
{
mWorldObjectTable.ReleaseAll();
mWorldObjects.clear();
}
void World::Update(float dt)
{
}
HWorldObject World::RegisterWorldObject(UPtr<WorldObject>&& wo)
{
CHECK(wo->GetID() == Uint64InvalidValue, "Failed to register GameObject. It is already registered. (id: {})", wo->GetID());
wo->mEntity = mRegistry.create();
mRegistry.emplace<Transform>(wo->mEntity, Vector3::Zero(), Vector3::Zero(), Vector3(1.0f, 1.0f, 1.0f));
mWorldObjects.push_back(std::move(wo));
HWorldObject hwo = mWorldObjectTable.CreateNewHandler(mWorldObjects.back().get());
return hwo;
}
void World::UnregisterWorldObject(HWorldObject& wo)
{
mRegistry.destroy(wo->mEntity);
WorldObject* pWo = mWorldObjectTable.ReleaseHandler(wo);
auto findIter = std::find_if(mWorldObjects.cbegin(), mWorldObjects.cend(), [pWo](auto& element) {
return element.get() == pWo;
});
CHECK(findIter != mWorldObjects.cend(), "Cannot unregister WorldObject. It is not registered.");
mWorldObjects.erase(findIter);
}
} // namespace cube
| [
"max804800@gmail.com"
] | max804800@gmail.com |
a5e8e0bedde0a13d9457445cb670f84bcd30b5e3 | 4eda5347b1915958143b53d020e43f563372d296 | /第4章/Single/Single/MainFrm.cpp | 1e2bfa8aafc943bb0b497438eb4817360d980424 | [] | no_license | natsuki-Uzu/Windows_Program | 40e4380e7d08f764051104a4bbcc99e9b4ff387c | a994ffaa3174e83a7d69f2c7015dac930312afaf | refs/heads/master | 2023-04-26T15:53:39.205163 | 2012-07-31T06:21:23 | 2012-07-31T06:21:23 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,885 | cpp | // MainFrm.cpp : CMainFrame 类的实现
//
#include "stdafx.h"
#include "Single.h"
#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CMainFrame
IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
ON_WM_CREATE()
END_MESSAGE_MAP()
static UINT indicators[] =
{
ID_SEPARATOR, // 状态行指示器
ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL,
};
// CMainFrame 构造/析构
CMainFrame::CMainFrame()
{
// TODO: 在此添加成员初始化代码
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
{
TRACE0("未能创建工具栏\n");
return -1; // 未能创建
}
if (!m_wndStatusBar.Create(this) ||
!m_wndStatusBar.SetIndicators(indicators,
sizeof(indicators)/sizeof(UINT)))
{
TRACE0("未能创建状态栏\n");
return -1; // 未能创建
}
// TODO: 如果不需要工具栏可停靠,则删除这三行
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(&m_wndToolBar);
return 0;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CFrameWnd::PreCreateWindow(cs) )
return FALSE;
// TODO: 在此处通过修改
// CREATESTRUCT cs 来修改窗口类或样式
return TRUE;
}
// CMainFrame 诊断
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CFrameWnd::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CFrameWnd::Dump(dc);
}
#endif //_DEBUG
// CMainFrame 消息处理程序
| [
"Administrator@PRC-20120724DKO.(none)"
] | Administrator@PRC-20120724DKO.(none) |
094a6ea26f4356631558c59111f4916d48eae4e8 | 8383dfe55d0ea81d9d20f8724fd9081bbf3428dd | /vendor/tensorflow_bfloat16_patch/tensorflow/core/kernels/constant_op.cc | 00a784c7a9f6895bf2113a081c70e700039868b3 | [
"MIT"
] | permissive | soumith/blocksparse | 707f179da186e401ba4e6586c64320bd24360127 | 4071232a4a73a441424434ca2e81b1e4fd4e836c | refs/heads/master | 2020-05-25T09:46:53.676995 | 2019-05-28T05:45:31 | 2019-05-28T05:45:31 | 187,745,586 | 5 | 0 | MIT | 2019-05-21T02:16:42 | 2019-05-21T02:16:42 | null | UTF-8 | C++ | false | false | 16,048 | cc | /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// See docs in ../ops/array_ops.cc.
#define EIGEN_USE_THREADS
#if GOOGLE_CUDA
#define EIGEN_USE_GPU
#endif
#include "tensorflow/core/kernels/constant_op.h"
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/framework/variant_op_registry.h"
#include "tensorflow/core/kernels/bounds_check.h"
#include "tensorflow/core/kernels/fill_functor.h"
#include "tensorflow/core/platform/macros.h"
#ifdef TENSORFLOW_USE_SYCL
#include "tensorflow/core/common_runtime/sycl/sycl_util.h"
#endif // TENSORFLOW_USE_SYCL
namespace tensorflow {
ConstantOp::ConstantOp(OpKernelConstruction* ctx)
: OpKernel(ctx), tensor_(ctx->output_type(0)) {
const TensorProto* proto = nullptr;
OP_REQUIRES_OK(ctx, ctx->GetAttr("value", &proto));
OP_REQUIRES_OK(ctx, ctx->device()->MakeTensorFromProto(
*proto, AllocatorAttributes(), &tensor_));
OP_REQUIRES(
ctx, ctx->output_type(0) == tensor_.dtype(),
errors::InvalidArgument("Type mismatch between value (",
DataTypeString(tensor_.dtype()), ") and dtype (",
DataTypeString(ctx->output_type(0)), ")"));
}
void ConstantOp::Compute(OpKernelContext* ctx) { ctx->set_output(0, tensor_); }
ConstantOp::~ConstantOp() {}
REGISTER_KERNEL_BUILDER(Name("Const").Device(DEVICE_CPU), ConstantOp);
#if GOOGLE_CUDA
#define REGISTER_KERNEL(D, TYPE) \
REGISTER_KERNEL_BUILDER( \
Name("Const").Device(DEVICE_##D).TypeConstraint<TYPE>("dtype"), \
ConstantOp);
REGISTER_KERNEL(GPU, Eigen::half);
REGISTER_KERNEL(GPU, bfloat16);
REGISTER_KERNEL(GPU, float);
REGISTER_KERNEL(GPU, double);
REGISTER_KERNEL(GPU, uint8);
REGISTER_KERNEL(GPU, int8);
REGISTER_KERNEL(GPU, uint16);
REGISTER_KERNEL(GPU, int16);
REGISTER_KERNEL(GPU, int64);
REGISTER_KERNEL(GPU, complex64);
REGISTER_KERNEL(GPU, complex128);
REGISTER_KERNEL(GPU, bool);
REGISTER_KERNEL(GPU, Variant);
#undef REGISTER_KERNEL
#endif
#ifdef TENSORFLOW_USE_SYCL
#define REGISTER_SYCL_KERNEL(D, TYPE) \
REGISTER_KERNEL_BUILDER( \
Name("Const").Device(DEVICE_##D).TypeConstraint<TYPE>("dtype"), \
ConstantOp);
REGISTER_SYCL_KERNEL(SYCL, float);
REGISTER_SYCL_KERNEL(SYCL, double);
REGISTER_SYCL_KERNEL(SYCL, uint8);
REGISTER_SYCL_KERNEL(SYCL, int8);
REGISTER_SYCL_KERNEL(SYCL, uint16);
REGISTER_SYCL_KERNEL(SYCL, int16);
REGISTER_SYCL_KERNEL(SYCL, int64);
REGISTER_SYCL_KERNEL(SYCL, bool);
#undef REGISTER_SYCL_KERNEL
#endif
HostConstantOp::HostConstantOp(OpKernelConstruction* ctx)
: OpKernel(ctx), tensor_(ctx->output_type(0)) {
const TensorProto* proto = nullptr;
AllocatorAttributes alloc_attr;
alloc_attr.set_on_host(true);
OP_REQUIRES_OK(ctx, ctx->GetAttr("value", &proto));
OP_REQUIRES_OK(
ctx, ctx->device()->MakeTensorFromProto(*proto, alloc_attr, &tensor_));
OP_REQUIRES(
ctx, ctx->output_type(0) == tensor_.dtype(),
errors::InvalidArgument("Type mismatch between value (",
DataTypeString(tensor_.dtype()), ") and dtype (",
DataTypeString(ctx->output_type(0)), ")"));
}
void HostConstantOp::Compute(OpKernelContext* ctx) {
ctx->set_output(0, tensor_);
}
#if GOOGLE_CUDA
// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
REGISTER_KERNEL_BUILDER(Name("Const")
.Device(DEVICE_GPU)
.HostMemory("output")
.TypeConstraint<int32>("dtype"),
HostConstantOp);
#endif
#ifdef TENSORFLOW_USE_SYCL
REGISTER_KERNEL_BUILDER(Name("Const")
.Device(DEVICE_SYCL)
.HostMemory("output")
.TypeConstraint<int32>("dtype"),
HostConstantOp);
#endif // TENSORFLOW_USE_SYCL
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
#ifdef TENSORFLOW_USE_SYCL
typedef Eigen::SyclDevice SYCLDevice;
#endif // TENSORFLOW_USE_SYCL
namespace functor {
// Partial specialization of FillFunctor<Device=CPUDevice, T>.
template <typename T>
struct FillFunctor<CPUDevice, T> {
void operator()(const CPUDevice& d, typename TTypes<T>::Flat out,
typename TTypes<T>::ConstScalar in) {
out.device(d) = out.constant(in());
}
};
} // end namespace functor
template <typename Device, typename T>
class FillOp : public OpKernel {
public:
explicit FillOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
const Tensor& Tdims = context->input(0);
OP_REQUIRES(
context, IsLegacyVector(Tdims.shape()),
errors::InvalidArgument("dims must be a vector of int32, got shape ",
Tdims.shape().DebugString()));
const Tensor& Tvalue = context->input(1);
OP_REQUIRES(context, IsLegacyScalar(Tvalue.shape()),
errors::InvalidArgument("value must be a scalar, got shape ",
Tvalue.shape().DebugString()));
auto dims = Tdims.flat<int32>();
TensorShape shape;
OP_REQUIRES_OK(context, TensorShapeUtils::MakeShape(
reinterpret_cast<const int32*>(dims.data()),
dims.size(), &shape));
Tensor* out = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, shape, &out));
functor::FillFunctor<Device, T> functor;
functor(context->eigen_device<Device>(), out->flat<T>(),
Tvalue.scalar<T>());
}
};
#ifdef TENSORFLOW_USE_SYCL
namespace functor {
// Partial specialization of FillFunctor<Device=SYCLDevice, T>.
template <typename T>
struct FillFunctor<SYCLDevice, T> {
void operator()(const SYCLDevice& d, typename TTypes<T>::Flat out,
typename TTypes<T>::ConstScalar in) {
#if !defined(EIGEN_HAS_INDEX_LIST)
Eigen::array<int, 1> rank1{1};
#else
Eigen::IndexList<Eigen::type2index<1> > rank1;
#endif
const int size = out.dimension(0);
Eigen::array<int, 1> broadcast_dims{size};
To32Bit(out).device(d) = in.reshape(rank1).broadcast(broadcast_dims);
}
};
} // namespace functor
#endif // TENSORFLOW_USE_SYCL
#define REGISTER_KERNEL(D, TYPE) \
REGISTER_KERNEL_BUILDER(Name("Fill") \
.Device(DEVICE_##D) \
.TypeConstraint<TYPE>("T") \
.HostMemory("dims"), \
FillOp<D##Device, TYPE>);
#define REGISTER_CPU_KERNEL(TYPE) REGISTER_KERNEL(CPU, TYPE)
TF_CALL_ALL_TYPES(REGISTER_CPU_KERNEL);
// TODO(b/28917570): Add a test for this. Currently python 3 is not happy about
// the conversion from uint8 to quint8.
REGISTER_KERNEL(CPU, quint8);
REGISTER_KERNEL(CPU, quint16);
#undef REGISTER_CPU_KERNEL
#ifdef TENSORFLOW_USE_SYCL
REGISTER_KERNEL(SYCL, float);
REGISTER_KERNEL(SYCL, double);
REGISTER_KERNEL(SYCL, uint8);
REGISTER_KERNEL(SYCL, int8);
REGISTER_KERNEL(SYCL, uint16);
REGISTER_KERNEL(SYCL, int16);
REGISTER_KERNEL(SYCL, int64);
REGISTER_KERNEL_BUILDER(Name("Fill")
.Device(DEVICE_SYCL)
.TypeConstraint<int32>("T")
.HostMemory("dims")
.HostMemory("value")
.HostMemory("output"),
FillOp<CPUDevice, int32>);
#undef REGISTER_KERNEL_SYCL
#endif // TENSORFLOW_USE_SYCL
#if GOOGLE_CUDA
REGISTER_KERNEL(GPU, Eigen::half);
REGISTER_KERNEL(GPU, bfloat16);
REGISTER_KERNEL(GPU, float);
REGISTER_KERNEL(GPU, double);
REGISTER_KERNEL(GPU, uint8);
REGISTER_KERNEL(GPU, int8);
REGISTER_KERNEL(GPU, uint16);
REGISTER_KERNEL(GPU, int16);
REGISTER_KERNEL(GPU, int64);
REGISTER_KERNEL(GPU, bool);
// Currently we do not support filling strings and complex64 on GPU
// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
REGISTER_KERNEL_BUILDER(Name("Fill")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.HostMemory("dims")
.HostMemory("value")
.HostMemory("output"),
FillOp<CPUDevice, int32>);
#endif
#undef REGISTER_KERNEL
template <typename Device, typename T>
class ZerosLikeOp : public OpKernel {
public:
explicit ZerosLikeOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
const Tensor& input = ctx->input(0);
const Device& d = ctx->eigen_device<Device>();
if (std::is_same<T, Variant>::value) {
OP_REQUIRES(
ctx, input.dims() == 0,
errors::InvalidArgument("ZerosLike non-scalar Tensor with "
"dtype=DT_VARIANT is not supported."));
const Variant& v = input.scalar<Variant>()();
Tensor out(cpu_allocator(), DT_VARIANT, TensorShape({}));
Variant* out_v = &(out.scalar<Variant>()());
OP_REQUIRES_OK(ctx, UnaryOpVariant<Device>(
ctx, ZEROS_LIKE_VARIANT_UNARY_OP, v, out_v));
ctx->set_output(0, out);
} else {
Tensor* out = nullptr;
OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output(
{0}, 0, input.shape(), &out));
functor::SetZeroFunctor<Device, T> f;
f(d, out->flat<T>());
}
}
};
#define REGISTER_KERNEL(type, dev) \
REGISTER_KERNEL_BUILDER( \
Name("ZerosLike").Device(DEVICE_##dev).TypeConstraint<type>("T"), \
ZerosLikeOp<dev##Device, type>)
#define REGISTER_CPU(type) REGISTER_KERNEL(type, CPU)
TF_CALL_POD_STRING_TYPES(REGISTER_CPU);
REGISTER_CPU(Variant);
#undef REGISTER_CPU
#ifdef TENSORFLOW_USE_SYCL
REGISTER_KERNEL(bool, SYCL);
REGISTER_KERNEL(float, SYCL);
REGISTER_KERNEL(double, SYCL);
REGISTER_KERNEL(int64, SYCL);
REGISTER_KERNEL_BUILDER(Name("ZerosLike")
.Device(DEVICE_SYCL)
.TypeConstraint<int32>("T")
.HostMemory("y"),
ZerosLikeOp<CPUDevice, int32>);
#endif // TENSORFLOW_USE_SYCL
#if GOOGLE_CUDA
REGISTER_KERNEL(bool, GPU);
REGISTER_KERNEL(Eigen::half, GPU);
REGISTER_KERNEL(bfloat16, GPU);
REGISTER_KERNEL(float, GPU);
REGISTER_KERNEL(double, GPU);
REGISTER_KERNEL(complex64, GPU);
REGISTER_KERNEL(complex128, GPU);
REGISTER_KERNEL(int64, GPU);
REGISTER_KERNEL_BUILDER(Name("ZerosLike")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.HostMemory("y"),
ZerosLikeOp<CPUDevice, int32>);
// TODO(ebrevdo): Once rendezvous has been properly set up for
// Variants, we'll no longer need a HostMemory attribute for this case.
REGISTER_KERNEL_BUILDER(Name("ZerosLike")
.Device(DEVICE_GPU)
.TypeConstraint<Variant>("T")
.HostMemory("x")
.HostMemory("y"),
ZerosLikeOp<GPUDevice, Variant>);
#endif // GOOGLE_CUDA
#undef REGISTER_KERNEL
template <typename Device, typename T>
class OnesLikeOp : public OpKernel {
public:
explicit OnesLikeOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
void Compute(OpKernelContext* ctx) override {
const Tensor& input = ctx->input(0);
Tensor* out = nullptr;
OP_REQUIRES_OK(ctx, ctx->forward_input_or_allocate_output(
{0}, 0, input.shape(), &out));
functor::SetOneFunctor<Device, T> f;
f(ctx->eigen_device<Device>(), out->flat<T>());
}
};
#define REGISTER_KERNEL(type, dev) \
REGISTER_KERNEL_BUILDER( \
Name("OnesLike").Device(DEVICE_##dev).TypeConstraint<type>("T"), \
OnesLikeOp<dev##Device, type>)
#define REGISTER_CPU(type) REGISTER_KERNEL(type, CPU)
TF_CALL_POD_TYPES(REGISTER_CPU);
#undef REGISTER_CPU
#ifdef TENSORFLOW_USE_SYCL
REGISTER_KERNEL(float, SYCL);
REGISTER_KERNEL(bool, SYCL);
REGISTER_KERNEL_BUILDER(Name("OnesLike")
.Device(DEVICE_SYCL)
.TypeConstraint<int32>("T")
.HostMemory("y"),
OnesLikeOp<CPUDevice, int32>);
#endif // TENSORFLOW_USE_SYCL
#if GOOGLE_CUDA
REGISTER_KERNEL(bool, GPU);
REGISTER_KERNEL(Eigen::half, GPU);
REGISTER_KERNEL(bfloat16, GPU);
REGISTER_KERNEL(float, GPU);
REGISTER_KERNEL(double, GPU);
REGISTER_KERNEL(complex64, GPU);
REGISTER_KERNEL(complex128, GPU);
REGISTER_KERNEL(int64, GPU);
REGISTER_KERNEL_BUILDER(Name("OnesLike")
.Device(DEVICE_GPU)
.TypeConstraint<int32>("T")
.HostMemory("y"),
OnesLikeOp<CPUDevice, int32>);
#endif // GOOGLE_CUDA
#undef REGISTER_KERNEL
PlaceholderOp::PlaceholderOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("shape", &expected_shape_));
}
void PlaceholderOp::Compute(OpKernelContext* ctx) {
if (expected_shape_.dims() > 0) {
OP_REQUIRES(ctx, false,
errors::InvalidArgument(
"You must feed a value for placeholder tensor '", name(),
"' with dtype ", DataTypeString(output_type(0)),
" and shape ", expected_shape_.DebugString()));
} else {
OP_REQUIRES(ctx, false,
errors::InvalidArgument(
"You must feed a value for placeholder tensor '", name(),
"' with dtype ", DataTypeString(output_type(0))));
}
}
REGISTER_KERNEL_BUILDER(Name("Placeholder").Device(DEVICE_CPU), PlaceholderOp);
REGISTER_KERNEL_BUILDER(Name("PlaceholderV2").Device(DEVICE_CPU),
PlaceholderOp);
// The following GPU kernel registration is used to address the situation that
// a placeholder is added in a GPU device context and soft placement is false.
// Since a placeholder should never be executed, adding these GPU kernels has
// no effect on graph execution.
REGISTER_KERNEL_BUILDER(Name("Placeholder").Device(DEVICE_GPU), PlaceholderOp);
REGISTER_KERNEL_BUILDER(Name("PlaceholderV2").Device(DEVICE_GPU),
PlaceholderOp);
#if TENSORFLOW_USE_SYCL
REGISTER_KERNEL_BUILDER(Name("Placeholder").Device(DEVICE_SYCL), PlaceholderOp);
REGISTER_KERNEL_BUILDER(Name("PlaceholderV2").Device(DEVICE_SYCL),
PlaceholderOp);
#endif // TENSORFLOW_USE_SYCL
} // namespace tensorflow
| [
"jonas@openai.com"
] | jonas@openai.com |
fc41d2b3aa56e8aebd921ddc9e0addf38ff13977 | ecfa6ca72f03c60a293280108f8dcb6c0f0b7969 | /Wordclock/Wordclock/Wordclock/inc/Animation/Clock/AnimationClockTeletype.h | 9083ee32f38420f289a9b24f3d033e009f485c5d | [] | no_license | AndreasBur/Wordclock | 0946f7b939a4883273237ab903b2eff2087b8306 | 376a1dd8a385d507a71fa2e67bf2a269b2068242 | refs/heads/master | 2022-07-19T15:08:35.074029 | 2022-07-09T11:41:32 | 2022-07-09T11:41:32 | 94,092,644 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,015 | h | /******************************************************************************************************************************************************
* COPYRIGHT
* ---------------------------------------------------------------------------------------------------------------------------------------------------
* \verbatim
* Copyright (c) Andreas Burnickl All rights reserved.
*
* \endverbatim
* ---------------------------------------------------------------------------------------------------------------------------------------------------
* FILE DESCRIPTION
* -------------------------------------------------------------------------------------------------------------------------------------------------*/
/** \file AnimationClockTeletype.h
* \brief
*
* \details
*
******************************************************************************************************************************************************/
#ifndef _ANIMATION_CLOCK_TELETYPE_H_
#define _ANIMATION_CLOCK_TELETYPE_H_
/******************************************************************************************************************************************************
* INCLUDES
******************************************************************************************************************************************************/
#include "StandardTypes.h"
#include "Arduino.h"
#include "Clock.h"
#include "AnimationClockCommon.h"
/******************************************************************************************************************************************************
* GLOBAL CONSTANT MACROS
******************************************************************************************************************************************************/
/* AnimationClockTeletype configuration parameter */
/* AnimationClockTeletype parameter */
/******************************************************************************************************************************************************
* GLOBAL FUNCTION MACROS
******************************************************************************************************************************************************/
/******************************************************************************************************************************************************
* GLOBAL DATA TYPES AND STRUCTURES
*****************************************************************************************************************************************************/
/******************************************************************************************************************************************************
* CLASS AnimationClockTeletype
******************************************************************************************************************************************************/
class AnimationClockTeletype : public AnimationClockCommon
{
public:
/******************************************************************************************************************************************************
* GLOBAL DATA TYPES AND STRUCTURES
******************************************************************************************************************************************************/
/******************************************************************************************************************************************************
* P R I V A T E D A T A A N D F U N C T I O N S
******************************************************************************************************************************************************/
private:
Clock* pClock;
Display* pDisplay;
Clock::ClockWordsTableType ClockWordsTable;
byte CurrentWordIndex;
byte CurrentWordLength;
byte CurrentCharIndex;
DisplayWords Words;
// functions
void reset();
stdReturnType setNextWordIndex();
/******************************************************************************************************************************************************
* P U B L I C F U N C T I O N S
******************************************************************************************************************************************************/
public:
AnimationClockTeletype();
~AnimationClockTeletype();
// get methods
// set methods
// methods
void init(Display*, Clock*);
stdReturnType setClock(byte, byte);
void task();
void show() { pDisplay->show(); }
};
#endif
/******************************************************************************************************************************************************
* E N D O F F I L E
******************************************************************************************************************************************************/
| [
"a.burnickl@gmail.com"
] | a.burnickl@gmail.com |
e89208ef5990482965546656c6a36173c60227c2 | 78918391a7809832dc486f68b90455c72e95cdda | /boost_lib/boost/graph/vf2_sub_graph_iso.hpp | 2eff106db658c3613347f288262a88f0efa820cc | [
"MIT"
] | permissive | kyx0r/FA_Patcher | 50681e3e8bb04745bba44a71b5fd04e1004c3845 | 3f539686955249004b4483001a9e49e63c4856ff | refs/heads/master | 2022-03-28T10:03:28.419352 | 2020-01-02T09:16:30 | 2020-01-02T09:16:30 | 141,066,396 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 42,775 | hpp | //=======================================================================
// Copyright (C) 2012 Flavio De Lorenzi (fdlorenzi@gmail.com)
// Copyright (C) 2013 Jakob Lykke Andersen, University of Southern Denmark (jlandersen@imada.sdu.dk)
//
// The algorithm implemented here is derived from original ideas by
// Pasquale Foggia and colaborators. For further information see
// e.g. Cordella et al. 2001, 2004.
//
// 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)
//=======================================================================
// Revision History:
// 8 April 2013: Fixed a typo in vf2_print_callback. (Flavio De Lorenzi)
#ifndef BOOST_VF2_SUB_GRAPH_ISO_HPP
#define BOOST_VF2_SUB_GRAPH_ISO_HPP
#include <iostream>
#include <iomanip>
#include <iterator>
#include <vector>
#include <utility>
#include <boost/assert.hpp>
#include <boost/concept/assert.hpp>
#include <boost/concept_check.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/mcgregor_common_subgraphs.hpp> // for always_equivalent
#include <boost/graph/named_function_params.hpp>
#include <boost/type_traits/has_less.hpp>
#include <boost/mpl/int.hpp>
#include <boost/range/algorithm/sort.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/utility/enable_if.hpp>
#ifndef BOOST_GRAPH_ITERATION_MACROS_HPP
#define BOOST_ISO_INCLUDED_ITER_MACROS // local macro, see bottom of file
#include <boost/graph/iteration_macros.hpp>
#endif
namespace boost
{
// Default print_callback
template <typename Graph1,
typename Graph2>
struct vf2_print_callback
{
vf2_print_callback(const Graph1& graph1, const Graph2& graph2)
: graph1_(graph1), graph2_(graph2) {}
template <typename CorrespondenceMap1To2,
typename CorrespondenceMap2To1>
bool operator()(CorrespondenceMap1To2 f, CorrespondenceMap2To1) const
{
// Print (sub)graph isomorphism map
BGL_FORALL_VERTICES_T(v, graph1_, Graph1)
std::cout << '(' << get(vertex_index_t(), graph1_, v) << ", "
<< get(vertex_index_t(), graph2_, get(f, v)) << ") ";
std::cout << std::endl;
return true;
}
private:
const Graph1& graph1_;
const Graph2& graph2_;
};
namespace detail
{
// State associated with a single graph (graph_this)
template<typename GraphThis,
typename GraphOther,
typename IndexMapThis,
typename IndexMapOther>
class base_state
{
typedef typename graph_traits<GraphThis>::vertex_descriptor vertex_this_type;
typedef typename graph_traits<GraphOther>::vertex_descriptor vertex_other_type;
typedef typename graph_traits<GraphThis>::vertices_size_type size_type;
const GraphThis& graph_this_;
const GraphOther& graph_other_;
IndexMapThis index_map_this_;
IndexMapOther index_map_other_;
std::vector<vertex_other_type> core_vec_;
typedef iterator_property_map<typename std::vector<vertex_other_type>::iterator,
IndexMapThis, vertex_other_type,
vertex_other_type&> core_map_type;
core_map_type core_;
std::vector<size_type> in_vec_, out_vec_;
typedef iterator_property_map<typename std::vector<size_type>::iterator,
IndexMapThis, size_type, size_type&> in_out_map_type;
in_out_map_type in_, out_;
size_type term_in_count_, term_out_count_, term_both_count_, core_count_;
// Forbidden
base_state(const base_state&);
base_state& operator=(const base_state&);
public:
base_state(const GraphThis& graph_this, const GraphOther& graph_other,
IndexMapThis index_map_this, IndexMapOther index_map_other)
: graph_this_(graph_this), graph_other_(graph_other),
index_map_this_(index_map_this), index_map_other_(index_map_other),
core_vec_(num_vertices(graph_this_), graph_traits<GraphOther>::null_vertex()),
core_(core_vec_.begin(), index_map_this_),
in_vec_(num_vertices(graph_this_), 0),
out_vec_(num_vertices(graph_this_), 0),
in_(in_vec_.begin(), index_map_this_),
out_(out_vec_.begin(), index_map_this_),
term_in_count_(0), term_out_count_(0), term_both_count_(0), core_count_(0)
{
}
// Adds a vertex pair to the state of graph graph_this
void push(const vertex_this_type& v_this, const vertex_other_type& v_other)
{
++core_count_;
put(core_, v_this, v_other);
if (!get(in_, v_this))
{
put(in_, v_this, core_count_);
++term_in_count_;
if (get(out_, v_this))
++term_both_count_;
}
if (!get(out_, v_this))
{
put(out_, v_this, core_count_);
++term_out_count_;
if (get(in_, v_this))
++term_both_count_;
}
BGL_FORALL_INEDGES_T(v_this, e, graph_this_, GraphThis)
{
vertex_this_type w = source(e, graph_this_);
if (!get(in_, w))
{
put(in_, w, core_count_);
++term_in_count_;
if (get(out_, w))
++term_both_count_;
}
}
BGL_FORALL_OUTEDGES_T(v_this, e, graph_this_, GraphThis)
{
vertex_this_type w = target(e, graph_this_);
if (!get(out_, w))
{
put(out_, w, core_count_);
++term_out_count_;
if (get(in_, w))
++term_both_count_;
}
}
}
// Removes vertex pair from state of graph_this
void pop(const vertex_this_type& v_this, const vertex_other_type&)
{
if (!core_count_) return;
if (get(in_, v_this) == core_count_)
{
put(in_, v_this, 0);
--term_in_count_;
if (get(out_, v_this))
--term_both_count_;
}
BGL_FORALL_INEDGES_T(v_this, e, graph_this_, GraphThis)
{
vertex_this_type w = source(e, graph_this_);
if (get(in_, w) == core_count_)
{
put(in_, w, 0);
--term_in_count_;
if (get(out_, w))
--term_both_count_;
}
}
if (get(out_, v_this) == core_count_)
{
put(out_, v_this, 0);
--term_out_count_;
if (get(in_, v_this))
--term_both_count_;
}
BGL_FORALL_OUTEDGES_T(v_this, e, graph_this_, GraphThis)
{
vertex_this_type w = target(e, graph_this_);
if (get(out_, w) == core_count_)
{
put(out_, w, 0);
--term_out_count_;
if (get(in_, w))
--term_both_count_;
}
}
put(core_, v_this, graph_traits<GraphOther>::null_vertex());
--core_count_;
}
// Returns true if the in-terminal set is not empty
bool term_in() const
{
return core_count_ < term_in_count_ ;
}
// Returns true if vertex belongs to the in-terminal set
bool term_in(const vertex_this_type& v) const
{
return (get(in_, v) > 0) &&
(get(core_, v) == graph_traits<GraphOther>::null_vertex());
}
// Returns true if the out-terminal set is not empty
bool term_out() const
{
return core_count_ < term_out_count_;
}
// Returns true if vertex belongs to the out-terminal set
bool term_out(const vertex_this_type& v) const
{
return (get(out_, v) > 0) &&
(get(core_, v) == graph_traits<GraphOther>::null_vertex());
}
// Returns true of both (in- and out-terminal) sets are not empty
bool term_both() const
{
return core_count_ < term_both_count_;
}
// Returns true if vertex belongs to both (in- and out-terminal) sets
bool term_both(const vertex_this_type& v) const
{
return (get(in_, v) > 0) && (get(out_, v) > 0) &&
(get(core_, v) == graph_traits<GraphOther>::null_vertex());
}
// Returns true if vertex belongs to the core map, i.e. it is in the
// present mapping
bool in_core(const vertex_this_type& v) const
{
return get(core_, v) != graph_traits<GraphOther>::null_vertex();
}
// Returns the number of vertices in the mapping
size_type count() const
{
return core_count_;
}
// Returns the image (in graph_other) of vertex v (in graph_this)
vertex_other_type core(const vertex_this_type& v) const
{
return get(core_, v);
}
// Returns the mapping
core_map_type get_map() const
{
return core_;
}
// Returns the "time" (or depth) when vertex was added to the in-terminal set
size_type in_depth(const vertex_this_type& v) const
{
return get(in_, v);
}
// Returns the "time" (or depth) when vertex was added to the out-terminal set
size_type out_depth(const vertex_this_type& v) const
{
return get(out_, v);
}
// Returns the terminal set counts
boost::tuple<size_type, size_type, size_type>
term_set() const
{
return boost::make_tuple(term_in_count_, term_out_count_,
term_both_count_);
}
};
// Function object that checks whether a valid edge
// exists. For multi-graphs matched edges are excluded
template <typename Graph, typename Enable = void>
struct equivalent_edge_exists
{
typedef typename boost::graph_traits<Graph>::edge_descriptor edge_type;
BOOST_CONCEPT_ASSERT(( LessThanComparable<edge_type> ));
template<typename EdgePredicate>
bool operator()(typename graph_traits<Graph>::vertex_descriptor s,
typename graph_traits<Graph>::vertex_descriptor t,
EdgePredicate is_valid_edge, const Graph& g)
{
BGL_FORALL_OUTEDGES_T(s, e, g, Graph)
{
if ((target(e, g) == t) && is_valid_edge(e) &&
(matched_edges_.find(e) == matched_edges_.end()))
{
matched_edges_.insert(e);
return true;
}
}
return false;
}
private:
std::set<edge_type> matched_edges_;
};
template <typename Graph>
struct equivalent_edge_exists<Graph, typename boost::disable_if<is_multigraph<Graph> >::type>
{
template<typename EdgePredicate>
bool operator()(typename graph_traits<Graph>::vertex_descriptor s,
typename graph_traits<Graph>::vertex_descriptor t,
EdgePredicate is_valid_edge, const Graph& g)
{
typename graph_traits<Graph>::edge_descriptor e;
bool found;
boost::tie(e, found) = edge(s, t, g);
if (!found)
return false;
else if (is_valid_edge(e))
return true;
return false;
}
};
// Generates a predicate for edge e1 given a binary predicate and a
// fixed edge e2
template <typename Graph1,
typename Graph2,
typename EdgeEquivalencePredicate>
struct edge1_predicate
{
edge1_predicate(EdgeEquivalencePredicate edge_comp,
typename graph_traits<Graph2>::edge_descriptor e2)
: edge_comp_(edge_comp), e2_(e2) {}
bool operator()(typename graph_traits<Graph1>::edge_descriptor e1)
{
return edge_comp_(e1, e2_);
}
EdgeEquivalencePredicate edge_comp_;
typename graph_traits<Graph2>::edge_descriptor e2_;
};
// Generates a predicate for edge e2 given given a binary predicate and a
// fixed edge e1
template <typename Graph1,
typename Graph2,
typename EdgeEquivalencePredicate>
struct edge2_predicate
{
edge2_predicate(EdgeEquivalencePredicate edge_comp,
typename graph_traits<Graph1>::edge_descriptor e1)
: edge_comp_(edge_comp), e1_(e1) {}
bool operator()(typename graph_traits<Graph2>::edge_descriptor e2)
{
return edge_comp_(e1_, e2);
}
EdgeEquivalencePredicate edge_comp_;
typename graph_traits<Graph1>::edge_descriptor e1_;
};
enum problem_selector {subgraph_mono, subgraph_iso, isomorphism };
// The actual state associated with both graphs
template<typename Graph1,
typename Graph2,
typename IndexMap1,
typename IndexMap2,
typename EdgeEquivalencePredicate,
typename VertexEquivalencePredicate,
typename SubGraphIsoMapCallback,
problem_selector problem_selection>
class state
{
typedef typename graph_traits<Graph1>::vertex_descriptor vertex1_type;
typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_type;
typedef typename graph_traits<Graph1>::edge_descriptor edge1_type;
typedef typename graph_traits<Graph2>::edge_descriptor edge2_type;
typedef typename graph_traits<Graph1>::vertices_size_type graph1_size_type;
typedef typename graph_traits<Graph2>::vertices_size_type graph2_size_type;
const Graph1& graph1_;
const Graph2& graph2_;
IndexMap1 index_map1_;
EdgeEquivalencePredicate edge_comp_;
VertexEquivalencePredicate vertex_comp_;
base_state<Graph1, Graph2, IndexMap1, IndexMap2> state1_;
base_state<Graph2, Graph1, IndexMap2, IndexMap1> state2_;
// Three helper functions used in Feasibility and Valid functions to test
// terminal set counts when testing for:
// - graph sub-graph monomorphism, or
inline bool comp_term_sets(graph1_size_type a,
graph2_size_type b,
boost::mpl::int_<subgraph_mono>) const
{
return a <= b;
}
// - graph sub-graph isomorphism, or
inline bool comp_term_sets(graph1_size_type a,
graph2_size_type b,
boost::mpl::int_<subgraph_iso>) const
{
return a <= b;
}
// - graph isomorphism
inline bool comp_term_sets(graph1_size_type a,
graph2_size_type b,
boost::mpl::int_<isomorphism>) const
{
return a == b;
}
// Forbidden
state(const state&);
state& operator=(const state&);
public:
state(const Graph1& graph1, const Graph2& graph2,
IndexMap1 index_map1, IndexMap2 index_map2,
EdgeEquivalencePredicate edge_comp,
VertexEquivalencePredicate vertex_comp)
: graph1_(graph1), graph2_(graph2),
index_map1_(index_map1),
edge_comp_(edge_comp), vertex_comp_(vertex_comp),
state1_(graph1, graph2, index_map1, index_map2),
state2_(graph2, graph1, index_map2, index_map1) {}
// Add vertex pair to the state
void push(const vertex1_type& v, const vertex2_type& w)
{
state1_.push(v, w);
state2_.push(w, v);
}
// Remove vertex pair from state
void pop(const vertex1_type& v, const vertex2_type&)
{
vertex2_type w = state1_.core(v);
state1_.pop(v, w);
state2_.pop(w, v);
}
// Checks the feasibility of a new vertex pair
bool feasible(const vertex1_type& v_new, const vertex2_type& w_new)
{
if (!vertex_comp_(v_new, w_new)) return false;
// graph1
graph1_size_type term_in1_count = 0, term_out1_count = 0, rest1_count = 0;
{
equivalent_edge_exists<Graph2> edge2_exists;
BGL_FORALL_INEDGES_T(v_new, e1, graph1_, Graph1)
{
vertex1_type v = source(e1, graph1_);
if (state1_.in_core(v) || (v == v_new))
{
vertex2_type w = w_new;
if (v != v_new)
w = state1_.core(v);
if (!edge2_exists(w, w_new,
edge2_predicate<Graph1, Graph2, EdgeEquivalencePredicate>(edge_comp_, e1),
graph2_))
return false;
}
else
{
if (0 < state1_.in_depth(v))
++term_in1_count;
if (0 < state1_.out_depth(v))
++term_out1_count;
if ((state1_.in_depth(v) == 0) && (state1_.out_depth(v) == 0))
++rest1_count;
}
}
}
{
equivalent_edge_exists<Graph2> edge2_exists;
BGL_FORALL_OUTEDGES_T(v_new, e1, graph1_, Graph1)
{
vertex1_type v = target(e1, graph1_);
if (state1_.in_core(v) || (v == v_new))
{
vertex2_type w = w_new;
if (v != v_new)
w = state1_.core(v);
if (!edge2_exists(w_new, w,
edge2_predicate<Graph1, Graph2, EdgeEquivalencePredicate>(edge_comp_, e1),
graph2_))
return false;
}
else
{
if (0 < state1_.in_depth(v))
++term_in1_count;
if (0 < state1_.out_depth(v))
++term_out1_count;
if ((state1_.in_depth(v) == 0) && (state1_.out_depth(v) == 0))
++rest1_count;
}
}
}
// graph2
graph2_size_type term_out2_count = 0, term_in2_count = 0, rest2_count = 0;
{
equivalent_edge_exists<Graph1> edge1_exists;
BGL_FORALL_INEDGES_T(w_new, e2, graph2_, Graph2)
{
vertex2_type w = source(e2, graph2_);
if (state2_.in_core(w) || (w == w_new))
{
if (problem_selection != subgraph_mono)
{
vertex1_type v = v_new;
if (w != w_new)
v = state2_.core(w);
if (!edge1_exists(v, v_new,
edge1_predicate<Graph1, Graph2, EdgeEquivalencePredicate>(edge_comp_, e2),
graph1_))
return false;
}
}
else
{
if (0 < state2_.in_depth(w))
++term_in2_count;
if (0 < state2_.out_depth(w))
++term_out2_count;
if ((state2_.in_depth(w) == 0) && (state2_.out_depth(w) == 0))
++rest2_count;
}
}
}
{
equivalent_edge_exists<Graph1> edge1_exists;
BGL_FORALL_OUTEDGES_T(w_new, e2, graph2_, Graph2)
{
vertex2_type w = target(e2, graph2_);
if (state2_.in_core(w) || (w == w_new))
{
if (problem_selection != subgraph_mono)
{
vertex1_type v = v_new;
if (w != w_new)
v = state2_.core(w);
if (!edge1_exists(v_new, v,
edge1_predicate<Graph1, Graph2, EdgeEquivalencePredicate>(edge_comp_, e2),
graph1_))
return false;
}
}
else
{
if (0 < state2_.in_depth(w))
++term_in2_count;
if (0 < state2_.out_depth(w))
++term_out2_count;
if ((state2_.in_depth(w) == 0) && (state2_.out_depth(w) == 0))
++rest2_count;
}
}
}
if (problem_selection != subgraph_mono) // subgraph_iso and isomorphism
{
return comp_term_sets(term_in1_count, term_in2_count,
boost::mpl::int_<problem_selection>()) &&
comp_term_sets(term_out1_count, term_out2_count,
boost::mpl::int_<problem_selection>()) &&
comp_term_sets(rest1_count, rest2_count,
boost::mpl::int_<problem_selection>());
}
else // subgraph_mono
{
return comp_term_sets(term_in1_count, term_in2_count,
boost::mpl::int_<problem_selection>()) &&
comp_term_sets(term_out1_count, term_out2_count,
boost::mpl::int_<problem_selection>()) &&
comp_term_sets(term_in1_count + term_out1_count + rest1_count,
term_in2_count + term_out2_count + rest2_count,
boost::mpl::int_<problem_selection>());
}
}
// Returns true if vertex v in graph1 is a possible candidate to
// be added to the current state
bool possible_candidate1(const vertex1_type& v) const
{
if (state1_.term_both() && state2_.term_both())
return state1_.term_both(v);
else if (state1_.term_out() && state2_.term_out())
return state1_.term_out(v);
else if (state1_.term_in() && state2_.term_in())
return state1_.term_in(v);
else
return !state1_.in_core(v);
}
// Returns true if vertex w in graph2 is a possible candidate to
// be added to the current state
bool possible_candidate2(const vertex2_type& w) const
{
if (state1_.term_both() && state2_.term_both())
return state2_.term_both(w);
else if (state1_.term_out() && state2_.term_out())
return state2_.term_out(w);
else if (state1_.term_in() && state2_.term_in())
return state2_.term_in(w);
else
return !state2_.in_core(w);
}
// Returns true if a mapping was found
bool success() const
{
return state1_.count() == num_vertices(graph1_);
}
// Returns true if a state is valid
bool valid() const
{
boost::tuple<graph1_size_type, graph1_size_type, graph1_size_type> term1;
boost::tuple<graph2_size_type, graph2_size_type, graph2_size_type> term2;
term1 = state1_.term_set();
term2 = state2_.term_set();
return comp_term_sets(boost::get<0>(term1), boost::get<0>(term2),
boost::mpl::int_<problem_selection>()) &&
comp_term_sets(boost::get<1>(term1), boost::get<1>(term2),
boost::mpl::int_<problem_selection>()) &&
comp_term_sets(boost::get<2>(term1), boost::get<2>(term2),
boost::mpl::int_<problem_selection>());
}
// Calls the user_callback with a graph (sub)graph mapping
bool call_back(SubGraphIsoMapCallback user_callback) const
{
return user_callback(state1_.get_map(), state2_.get_map());
}
};
// Data structure to keep info used for back tracking during
// matching process
template<typename Graph1,
typename Graph2,
typename VertexOrder1>
struct vf2_match_continuation
{
typename VertexOrder1::const_iterator graph1_verts_iter;
typename graph_traits<Graph2>::vertex_iterator graph2_verts_iter;
};
// Non-recursive method that explores state space using a depth-first
// search strategy. At each depth possible pairs candidate are compute
// and tested for feasibility to extend the mapping. If a complete
// mapping is found, the mapping is output to user_callback in the form
// of a correspondence map (graph1 to graph2). Returning false from the
// user_callback will terminate the search. Function match will return
// true if the entire search space was explored.
template<typename Graph1,
typename Graph2,
typename IndexMap1,
typename IndexMap2,
typename VertexOrder1,
typename EdgeEquivalencePredicate,
typename VertexEquivalencePredicate,
typename SubGraphIsoMapCallback,
problem_selector problem_selection>
bool match(const Graph1& graph1, const Graph2& graph2,
SubGraphIsoMapCallback user_callback, const VertexOrder1& vertex_order1,
state<Graph1, Graph2, IndexMap1, IndexMap2,
EdgeEquivalencePredicate, VertexEquivalencePredicate,
SubGraphIsoMapCallback, problem_selection>& s)
{
typename VertexOrder1::const_iterator graph1_verts_iter;
typedef typename graph_traits<Graph2>::vertex_iterator vertex2_iterator_type;
vertex2_iterator_type graph2_verts_iter, graph2_verts_iter_end;
typedef vf2_match_continuation<Graph1, Graph2, VertexOrder1> match_continuation_type;
std::vector<match_continuation_type> k;
bool found_match = false;
recur:
if (s.success())
{
if (!s.call_back(user_callback))
return true;
found_match = true;
goto back_track;
}
if (!s.valid())
goto back_track;
graph1_verts_iter = vertex_order1.begin();
while (graph1_verts_iter != vertex_order1.end() &&
!s.possible_candidate1(*graph1_verts_iter))
{
++graph1_verts_iter;
}
boost::tie(graph2_verts_iter, graph2_verts_iter_end) = vertices(graph2);
while (graph2_verts_iter != graph2_verts_iter_end)
{
if (s.possible_candidate2(*graph2_verts_iter))
{
if (s.feasible(*graph1_verts_iter, *graph2_verts_iter))
{
match_continuation_type kk;
kk.graph1_verts_iter = graph1_verts_iter;
kk.graph2_verts_iter = graph2_verts_iter;
k.push_back(kk);
s.push(*graph1_verts_iter, *graph2_verts_iter);
goto recur;
}
}
graph2_loop:
++graph2_verts_iter;
}
back_track:
if (k.empty())
return found_match;
const match_continuation_type kk = k.back();
graph1_verts_iter = kk.graph1_verts_iter;
graph2_verts_iter = kk.graph2_verts_iter;
k.pop_back();
s.pop(*graph1_verts_iter, *graph2_verts_iter);
goto graph2_loop;
}
// Used to sort nodes by in/out degrees
template<typename Graph>
struct vertex_in_out_degree_cmp
{
typedef typename graph_traits<Graph>::vertex_descriptor vertex_type;
vertex_in_out_degree_cmp(const Graph& graph)
: graph_(graph) {}
bool operator()(const vertex_type& v, const vertex_type& w) const
{
// lexicographical comparison
return std::make_pair(in_degree(v, graph_), out_degree(v, graph_)) <
std::make_pair(in_degree(w, graph_), out_degree(w, graph_));
}
const Graph& graph_;
};
// Used to sort nodes by multiplicity of in/out degrees
template<typename Graph,
typename FrequencyMap>
struct vertex_frequency_degree_cmp
{
typedef typename graph_traits<Graph>::vertex_descriptor vertex_type;
vertex_frequency_degree_cmp(const Graph& graph, FrequencyMap freq)
: graph_(graph), freq_(freq) {}
bool operator()(const vertex_type& v, const vertex_type& w) const
{
// lexicographical comparison
return std::make_pair(freq_[v], in_degree(v, graph_)+out_degree(v, graph_)) <
std::make_pair(freq_[w], in_degree(w, graph_)+out_degree(w, graph_));
}
const Graph& graph_;
FrequencyMap freq_;
};
// Sorts vertices of a graph by multiplicity of in/out degrees
template<typename Graph,
typename IndexMap,
typename VertexOrder>
void sort_vertices(const Graph& graph, IndexMap index_map, VertexOrder& order)
{
typedef typename graph_traits<Graph>::vertices_size_type size_type;
boost::range::sort(order, vertex_in_out_degree_cmp<Graph>(graph));
std::vector<size_type> freq_vec(num_vertices(graph), 0);
typedef iterator_property_map<typename std::vector<size_type>::iterator,
IndexMap, size_type, size_type&> frequency_map_type;
frequency_map_type freq = make_iterator_property_map(freq_vec.begin(), index_map);
typedef typename VertexOrder::iterator order_iterator;
for (order_iterator order_iter = order.begin(); order_iter != order.end(); )
{
size_type count = 0;
for (order_iterator count_iter = order_iter;
(count_iter != order.end()) &&
(in_degree(*order_iter, graph) == in_degree(*count_iter, graph)) &&
(out_degree(*order_iter, graph) == out_degree(*count_iter, graph));
++count_iter)
++count;
for (size_type i = 0; i < count; ++i)
{
freq[*order_iter] = count;
++order_iter;
}
}
boost::range::sort(order, vertex_frequency_degree_cmp<Graph, frequency_map_type>(graph, freq));
}
// Enumerates all graph sub-graph mono-/iso-morphism mappings between graphs
// graph_small and graph_large. Continues until user_callback returns true or the
// search space has been fully explored.
template <problem_selector problem_selection,
typename GraphSmall,
typename GraphLarge,
typename IndexMapSmall,
typename IndexMapLarge,
typename VertexOrderSmall,
typename EdgeEquivalencePredicate,
typename VertexEquivalencePredicate,
typename SubGraphIsoMapCallback>
bool vf2_subgraph_morphism(const GraphSmall& graph_small, const GraphLarge& graph_large,
SubGraphIsoMapCallback user_callback,
IndexMapSmall index_map_small, IndexMapLarge index_map_large,
const VertexOrderSmall& vertex_order_small,
EdgeEquivalencePredicate edge_comp,
VertexEquivalencePredicate vertex_comp)
{
// Graph requirements
BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<GraphSmall> ));
BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<GraphSmall> ));
BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<GraphSmall> ));
BOOST_CONCEPT_ASSERT(( AdjacencyMatrixConcept<GraphSmall> ));
BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<GraphLarge> ));
BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<GraphLarge> ));
BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<GraphLarge> ));
BOOST_CONCEPT_ASSERT(( AdjacencyMatrixConcept<GraphLarge> ));
typedef typename graph_traits<GraphSmall>::vertex_descriptor vertex_small_type;
typedef typename graph_traits<GraphLarge>::vertex_descriptor vertex_large_type;
typedef typename graph_traits<GraphSmall>::vertices_size_type size_type_small;
typedef typename graph_traits<GraphLarge>::vertices_size_type size_type_large;
// Property map requirements
BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<IndexMapSmall, vertex_small_type> ));
typedef typename property_traits<IndexMapSmall>::value_type IndexMapSmallValue;
BOOST_STATIC_ASSERT(( is_convertible<IndexMapSmallValue, size_type_small>::value ));
BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<IndexMapLarge, vertex_large_type> ));
typedef typename property_traits<IndexMapLarge>::value_type IndexMapLargeValue;
BOOST_STATIC_ASSERT(( is_convertible<IndexMapLargeValue, size_type_large>::value ));
// Edge & vertex requirements
typedef typename graph_traits<GraphSmall>::edge_descriptor edge_small_type;
typedef typename graph_traits<GraphLarge>::edge_descriptor edge_large_type;
BOOST_CONCEPT_ASSERT(( BinaryPredicateConcept<EdgeEquivalencePredicate,
edge_small_type, edge_large_type> ));
BOOST_CONCEPT_ASSERT(( BinaryPredicateConcept<VertexEquivalencePredicate,
vertex_small_type, vertex_large_type> ));
// Vertex order requirements
BOOST_CONCEPT_ASSERT(( ContainerConcept<VertexOrderSmall> ));
typedef typename VertexOrderSmall::value_type order_value_type;
BOOST_STATIC_ASSERT(( is_same<vertex_small_type, order_value_type>::value ));
BOOST_ASSERT( num_vertices(graph_small) == vertex_order_small.size() );
if (num_vertices(graph_small) > num_vertices(graph_large))
return false;
typename graph_traits<GraphSmall>::edges_size_type num_edges_small = num_edges(graph_small);
typename graph_traits<GraphLarge>::edges_size_type num_edges_large = num_edges(graph_large);
// Double the number of edges for undirected graphs: each edge counts as
// in-edge and out-edge
if (is_undirected(graph_small)) num_edges_small *= 2;
if (is_undirected(graph_large)) num_edges_large *= 2;
if (num_edges_small > num_edges_large)
return false;
detail::state<GraphSmall, GraphLarge, IndexMapSmall, IndexMapLarge,
EdgeEquivalencePredicate, VertexEquivalencePredicate,
SubGraphIsoMapCallback, problem_selection>
s(graph_small, graph_large, index_map_small, index_map_large, edge_comp, vertex_comp);
return detail::match(graph_small, graph_large, user_callback, vertex_order_small, s);
}
} // namespace detail
// Returns vertex order (vertices sorted by multiplicity of in/out degrees)
template<typename Graph>
std::vector<typename graph_traits<Graph>::vertex_descriptor>
vertex_order_by_mult(const Graph& graph)
{
std::vector<typename graph_traits<Graph>::vertex_descriptor> vertex_order;
std::copy(vertices(graph).first, vertices(graph).second, std::back_inserter(vertex_order));
detail::sort_vertices(graph, get(vertex_index, graph), vertex_order);
return vertex_order;
}
// Enumerates all graph sub-graph monomorphism mappings between graphs
// graph_small and graph_large. Continues until user_callback returns true or the
// search space has been fully explored.
template <typename GraphSmall,
typename GraphLarge,
typename IndexMapSmall,
typename IndexMapLarge,
typename VertexOrderSmall,
typename EdgeEquivalencePredicate,
typename VertexEquivalencePredicate,
typename SubGraphIsoMapCallback>
bool vf2_subgraph_mono(const GraphSmall& graph_small, const GraphLarge& graph_large,
SubGraphIsoMapCallback user_callback,
IndexMapSmall index_map_small, IndexMapLarge index_map_large,
const VertexOrderSmall& vertex_order_small,
EdgeEquivalencePredicate edge_comp,
VertexEquivalencePredicate vertex_comp)
{
return detail::vf2_subgraph_morphism<detail::subgraph_mono>
(graph_small, graph_large,
user_callback,
index_map_small, index_map_large,
vertex_order_small,
edge_comp,
vertex_comp);
}
// All default interface for vf2_subgraph_iso
template <typename GraphSmall,
typename GraphLarge,
typename SubGraphIsoMapCallback>
bool vf2_subgraph_mono(const GraphSmall& graph_small, const GraphLarge& graph_large,
SubGraphIsoMapCallback user_callback)
{
return vf2_subgraph_mono(graph_small, graph_large, user_callback,
get(vertex_index, graph_small), get(vertex_index, graph_large),
vertex_order_by_mult(graph_small),
always_equivalent(), always_equivalent());
}
// Named parameter interface of vf2_subgraph_iso
template <typename GraphSmall,
typename GraphLarge,
typename VertexOrderSmall,
typename SubGraphIsoMapCallback,
typename Param,
typename Tag,
typename Rest>
bool vf2_subgraph_mono(const GraphSmall& graph_small, const GraphLarge& graph_large,
SubGraphIsoMapCallback user_callback,
const VertexOrderSmall& vertex_order_small,
const bgl_named_params<Param, Tag, Rest>& params)
{
return vf2_subgraph_mono(graph_small, graph_large, user_callback,
choose_const_pmap(get_param(params, vertex_index1),
graph_small, vertex_index),
choose_const_pmap(get_param(params, vertex_index2),
graph_large, vertex_index),
vertex_order_small,
choose_param(get_param(params, edges_equivalent_t()),
always_equivalent()),
choose_param(get_param(params, vertices_equivalent_t()),
always_equivalent())
);
}
// Enumerates all graph sub-graph isomorphism mappings between graphs
// graph_small and graph_large. Continues until user_callback returns true or the
// search space has been fully explored.
template <typename GraphSmall,
typename GraphLarge,
typename IndexMapSmall,
typename IndexMapLarge,
typename VertexOrderSmall,
typename EdgeEquivalencePredicate,
typename VertexEquivalencePredicate,
typename SubGraphIsoMapCallback>
bool vf2_subgraph_iso(const GraphSmall& graph_small, const GraphLarge& graph_large,
SubGraphIsoMapCallback user_callback,
IndexMapSmall index_map_small, IndexMapLarge index_map_large,
const VertexOrderSmall& vertex_order_small,
EdgeEquivalencePredicate edge_comp,
VertexEquivalencePredicate vertex_comp)
{
return detail::vf2_subgraph_morphism<detail::subgraph_iso>
(graph_small, graph_large,
user_callback,
index_map_small, index_map_large,
vertex_order_small,
edge_comp,
vertex_comp);
}
// All default interface for vf2_subgraph_iso
template <typename GraphSmall,
typename GraphLarge,
typename SubGraphIsoMapCallback>
bool vf2_subgraph_iso(const GraphSmall& graph_small, const GraphLarge& graph_large,
SubGraphIsoMapCallback user_callback)
{
return vf2_subgraph_iso(graph_small, graph_large, user_callback,
get(vertex_index, graph_small), get(vertex_index, graph_large),
vertex_order_by_mult(graph_small),
always_equivalent(), always_equivalent());
}
// Named parameter interface of vf2_subgraph_iso
template <typename GraphSmall,
typename GraphLarge,
typename VertexOrderSmall,
typename SubGraphIsoMapCallback,
typename Param,
typename Tag,
typename Rest>
bool vf2_subgraph_iso(const GraphSmall& graph_small, const GraphLarge& graph_large,
SubGraphIsoMapCallback user_callback,
const VertexOrderSmall& vertex_order_small,
const bgl_named_params<Param, Tag, Rest>& params)
{
return vf2_subgraph_iso(graph_small, graph_large, user_callback,
choose_const_pmap(get_param(params, vertex_index1),
graph_small, vertex_index),
choose_const_pmap(get_param(params, vertex_index2),
graph_large, vertex_index),
vertex_order_small,
choose_param(get_param(params, edges_equivalent_t()),
always_equivalent()),
choose_param(get_param(params, vertices_equivalent_t()),
always_equivalent())
);
}
// Enumerates all isomorphism mappings between graphs graph1_ and graph2_.
// Continues until user_callback returns true or the search space has been
// fully explored.
template <typename Graph1,
typename Graph2,
typename IndexMap1,
typename IndexMap2,
typename VertexOrder1,
typename EdgeEquivalencePredicate,
typename VertexEquivalencePredicate,
typename GraphIsoMapCallback>
bool vf2_graph_iso(const Graph1& graph1, const Graph2& graph2,
GraphIsoMapCallback user_callback,
IndexMap1 index_map1, IndexMap2 index_map2,
const VertexOrder1& vertex_order1,
EdgeEquivalencePredicate edge_comp,
VertexEquivalencePredicate vertex_comp)
{
// Graph requirements
BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<Graph1> ));
BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<Graph1> ));
BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<Graph1> ));
BOOST_CONCEPT_ASSERT(( AdjacencyMatrixConcept<Graph1> ));
BOOST_CONCEPT_ASSERT(( BidirectionalGraphConcept<Graph2> ));
BOOST_CONCEPT_ASSERT(( VertexListGraphConcept<Graph2> ));
BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<Graph2> ));
BOOST_CONCEPT_ASSERT(( AdjacencyMatrixConcept<Graph2> ));
typedef typename graph_traits<Graph1>::vertex_descriptor vertex1_type;
typedef typename graph_traits<Graph2>::vertex_descriptor vertex2_type;
typedef typename graph_traits<Graph1>::vertices_size_type size_type1;
typedef typename graph_traits<Graph2>::vertices_size_type size_type2;
// Property map requirements
BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<IndexMap1, vertex1_type> ));
typedef typename property_traits<IndexMap1>::value_type IndexMap1Value;
BOOST_STATIC_ASSERT(( is_convertible<IndexMap1Value, size_type1>::value ));
BOOST_CONCEPT_ASSERT(( ReadablePropertyMapConcept<IndexMap2, vertex2_type> ));
typedef typename property_traits<IndexMap2>::value_type IndexMap2Value;
BOOST_STATIC_ASSERT(( is_convertible<IndexMap2Value, size_type2>::value ));
// Edge & vertex requirements
typedef typename graph_traits<Graph1>::edge_descriptor edge1_type;
typedef typename graph_traits<Graph2>::edge_descriptor edge2_type;
BOOST_CONCEPT_ASSERT(( BinaryPredicateConcept<EdgeEquivalencePredicate,
edge1_type, edge2_type> ));
BOOST_CONCEPT_ASSERT(( BinaryPredicateConcept<VertexEquivalencePredicate,
vertex1_type, vertex2_type> ));
// Vertex order requirements
BOOST_CONCEPT_ASSERT(( ContainerConcept<VertexOrder1> ));
typedef typename VertexOrder1::value_type order_value_type;
BOOST_STATIC_ASSERT(( is_same<vertex1_type, order_value_type>::value ));
BOOST_ASSERT( num_vertices(graph1) == vertex_order1.size() );
if (num_vertices(graph1) != num_vertices(graph2))
return false;
typename graph_traits<Graph1>::edges_size_type num_edges1 = num_edges(graph1);
typename graph_traits<Graph2>::edges_size_type num_edges2 = num_edges(graph2);
// Double the number of edges for undirected graphs: each edge counts as
// in-edge and out-edge
if (is_undirected(graph1)) num_edges1 *= 2;
if (is_undirected(graph2)) num_edges2 *= 2;
if (num_edges1 != num_edges2)
return false;
detail::state<Graph1, Graph2, IndexMap1, IndexMap2,
EdgeEquivalencePredicate, VertexEquivalencePredicate,
GraphIsoMapCallback, detail::isomorphism>
s(graph1, graph2, index_map1, index_map2, edge_comp, vertex_comp);
return detail::match(graph1, graph2, user_callback, vertex_order1, s);
}
// All default interface for vf2_graph_iso
template <typename Graph1,
typename Graph2,
typename GraphIsoMapCallback>
bool vf2_graph_iso(const Graph1& graph1, const Graph2& graph2,
GraphIsoMapCallback user_callback)
{
return vf2_graph_iso(graph1, graph2, user_callback,
get(vertex_index, graph1), get(vertex_index, graph2),
vertex_order_by_mult(graph1),
always_equivalent(), always_equivalent());
}
// Named parameter interface of vf2_graph_iso
template <typename Graph1,
typename Graph2,
typename VertexOrder1,
typename GraphIsoMapCallback,
typename Param,
typename Tag,
typename Rest>
bool vf2_graph_iso(const Graph1& graph1, const Graph2& graph2,
GraphIsoMapCallback user_callback,
const VertexOrder1& vertex_order1,
const bgl_named_params<Param, Tag, Rest>& params)
{
return vf2_graph_iso(graph1, graph2, user_callback,
choose_const_pmap(get_param(params, vertex_index1),
graph1, vertex_index),
choose_const_pmap(get_param(params, vertex_index2),
graph2, vertex_index),
vertex_order1,
choose_param(get_param(params, edges_equivalent_t()),
always_equivalent()),
choose_param(get_param(params, vertices_equivalent_t()),
always_equivalent())
);
}
// Verifies a graph (sub)graph isomorphism map
template<typename Graph1,
typename Graph2,
typename CorresponenceMap1To2,
typename EdgeEquivalencePredicate,
typename VertexEquivalencePredicate>
inline bool verify_vf2_subgraph_iso(const Graph1& graph1, const Graph2& graph2,
const CorresponenceMap1To2 f,
EdgeEquivalencePredicate edge_comp,
VertexEquivalencePredicate vertex_comp)
{
BOOST_CONCEPT_ASSERT(( EdgeListGraphConcept<Graph1> ));
BOOST_CONCEPT_ASSERT(( AdjacencyMatrixConcept<Graph2> ));
detail::equivalent_edge_exists<Graph2> edge2_exists;
BGL_FORALL_EDGES_T(e1, graph1, Graph1)
{
typename graph_traits<Graph1>::vertex_descriptor s1, t1;
typename graph_traits<Graph2>::vertex_descriptor s2, t2;
s1 = source(e1, graph1);
t1 = target(e1, graph1);
s2 = get(f, s1);
t2 = get(f, t1);
if (!vertex_comp(s1, s2) || !vertex_comp(t1, t2))
return false;
typename graph_traits<Graph2>::edge_descriptor e2;
if (!edge2_exists(s2, t2,
detail::edge2_predicate<Graph1, Graph2, EdgeEquivalencePredicate>(edge_comp, e1),
graph2))
return false;
}
return true;
}
// Variant of verify_subgraph_iso with all default parameters
template<typename Graph1,
typename Graph2,
typename CorresponenceMap1To2>
inline bool verify_vf2_subgraph_iso(const Graph1& graph1, const Graph2& graph2,
const CorresponenceMap1To2 f)
{
return verify_vf2_subgraph_iso(graph1, graph2, f,
always_equivalent(), always_equivalent());
}
} // namespace boost
#ifdef BOOST_ISO_INCLUDED_ITER_MACROS
#undef BOOST_ISO_INCLUDED_ITER_MACROS
#include <boost/graph/iteration_macros_undef.hpp>
#endif
#endif // BOOST_VF2_SUB_GRAPH_ISO_HPP
| [
"k.melekhin@gmail.com"
] | k.melekhin@gmail.com |
9c938ff603321364a192d999d6d9762414a40ecd | 09f3df9b4ae970025b8a422635d70287db91493b | /src/cpp/conv3x3.cpp | 95ea57901c629ef350ff30cbb8aeae80ddc9af53 | [
"BSD-2-Clause"
] | permissive | ikwzm/QCONV-STRIP-Ultra96 | 3390f07a41e91fe2d4c5552964748770c4ec2b51 | 38c7ae9af9de9b8d0bfdd0bee8fc49784bd4aa11 | refs/heads/master | 2021-07-12T21:13:31.441444 | 2020-08-21T00:52:38 | 2020-08-21T00:52:38 | 188,438,599 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,819 | cpp | /* Copyright 2018 The Blueoil Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <iostream>
#include "common/global.h"
#include "cpp/utils.h"
namespace cpp {
namespace p = conv_common_params;
void conv3x3_impl(T_in in_data[], T_out out_data[], T_k k_data[], T_out threshold_data[], unsigned in_w, unsigned in_h,
unsigned in_c, unsigned out_w, unsigned out_h, unsigned out_c, unsigned pad, unsigned stride)
{
unsigned k_c = in_c;
unsigned k_w = 3;
unsigned k_h = 3;
unsigned k_n = out_c;
unsigned k_size = k_h * k_w * k_c;
T_k* k_local = new T_k[k_size * k_n];
T_out threshold_local[out_c][p::num_thresholds];
unsigned idx_k = 0;
unsigned idx_t = 0;
for (unsigned kn = 0; kn < k_n; kn++) {
for (unsigned k = 0; k < k_size; k++) { k_local[k * k_n + kn] = k_data[idx_k++]; }
}
if (threshold_data != NULL) {
for (unsigned oc = 0; oc < out_c; oc++) {
for (unsigned i = 0; i < p::num_thresholds; i++) { threshold_local[oc][i] = threshold_data[idx_t++]; }
}
}
unsigned idx_out = 0;
for (unsigned oh = 0; oh < out_h; ++oh)
for (unsigned ow = 0; ow < out_w; ++ow) {
T_out out[k_n] = {};
unsigned idx_k_local = 0;
for (unsigned kh = 0; kh < k_h; kh++) {
for (unsigned kw = 0; kw < k_w; kw++) {
int ih = (oh * stride) - pad + kh;
int iw = (ow * stride) - pad + kw;
bool valid = (iw >= 0) && (iw < int(in_w)) && (ih >= 0) && (ih < int(in_h));
for (unsigned kc = 0; kc < in_c; kc++) {
if (valid) {
int idx_in = ih * in_w * in_c + iw * in_c + kc;
T_in in_buf = in_data[idx_in];
for (int kn = 0; kn < k_n; kn++) {
T_k k_buf = k_local[idx_k_local * k_n + kn];
out[kn] += in_buf * k_buf;
}
}
idx_k_local++;
}
}
}
for (int oc = 0; oc < out_c; oc++) {
T_out conv_result = out[oc];
T_out out_buf;
if (threshold_data != NULL) {
T_out ts0 = threshold_local[oc][0];
T_out ts1 = threshold_local[oc][1];
T_out ts2 = threshold_local[oc][2];
T_out flag = threshold_local[oc][3];
if (flag == 1) // increasing function
{
if (conv_result < ts0)
out_buf = 0;
else if (conv_result < ts1)
out_buf = 1;
else if (conv_result < ts2)
out_buf = 2;
else
out_buf = 3;
} else if (flag == -1) // decreasing function
{
if (conv_result > ts2)
out_buf = 0;
else if (conv_result > ts1)
out_buf = 1;
else if (conv_result > ts0)
out_buf = 2;
else
out_buf = 3;
} else {
// max value of 2 bits
out_buf = flag - 2; // note: 2 is a magic number!
}
} else {
out_buf = conv_result;
}
out_data[idx_out++] = out_buf;
}
} // for LOOP_CONV_INPUT
delete[] k_local;
}
void qconv3x3_impl(T_q in_data[], T_out out_data[], T_q k_data[], T_out threshold_data, unsigned in_w, unsigned in_h,
unsigned in_c_by_word, unsigned out_w, unsigned out_h, unsigned out_c, unsigned pad, unsigned stride)
{
unsigned idx_k = 0;
unsigned k_w = 3;
unsigned k_h = 3;
unsigned k_n = out_c;
unsigned k_c_by_word = in_c_by_word;
unsigned k_size_packed = k_h * k_w * k_c_by_word * conv_common_params::nbits_k_data;
for (int oc_out = 0; oc_out < out_c; oc_out += p::num_pe) {
T_q* k_local = new T_q[k_size_packed * p::num_pe];
for (unsigned kn = 0; kn < p::num_pe; ++kn) {
for (unsigned k = 0; k < k_size_packed; ++k) { k_local[k * p::num_pe + kn] = k_data[idx_k++]; }
}
unsigned idx_out = oc_out;
for (unsigned oh = 0; oh < out_h; ++oh)
for (unsigned ow = 0; ow < out_w; ++ow) {
T_out out[p::num_pe] = {};
unsigned idx_k_local = 0;
for (unsigned kh = 0; kh < k_h; ++kh)
for (unsigned kw = 0; kw < k_w; ++kw)
for (unsigned ic = 0; ic < in_c_by_word; ++ic) {
int ih = (oh * stride) - pad + kh;
int iw = (ow * stride) - pad + kw;
bool valid = (iw >= 0) && (iw < int(in_w)) && (ih >= 0) && (ih < int(in_h));
if (valid) {
int idx_in = (ih * in_w * in_c_by_word + iw * in_c_by_word + ic) * p::nbits_in_data;
T_q in_buf0 = in_data[idx_in];
T_q in_buf1 = in_data[idx_in + 1];
for (int kn = 0; kn < p::num_pe; kn++) {
T_q k_buf = k_local[idx_k_local * p::num_pe + kn];
out[kn] += PE(k_buf, in_buf0, in_buf1);
}
}
idx_k_local++; // should be executed, even while no corresponding input
}
for (int kn = 0; kn < p::num_pe; kn++) { out_data[idx_out + kn] = out[kn]; }
idx_out += out_c;
} // for LOOP_CONV_INPUT
delete[] k_local;
}
}
} // namespace cpp
| [
"ichiro_k@ca2.so-net.ne.jp"
] | ichiro_k@ca2.so-net.ne.jp |
b84ac7f60d6f47b91b7df1774289a0a4273dd452 | 3b4f1dbc4c178bccc58a10fdb6eff650b3406aa6 | /Game/Money.cpp | 349fbe926ec43631209ae512339a4d0c5f2d31a9 | [] | no_license | LuongKimPhuong2611/supermario-master | b0c51096611700e7728e781d21c74528ca156091 | ed182738d36a178f8ecb067ccd0ed5c1893173f0 | refs/heads/master | 2023-02-02T18:52:11.905121 | 2020-12-18T00:36:20 | 2020-12-18T00:36:20 | 322,201,046 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,418 | cpp | #include "Money.h"
#include "Brick.h"
Money::Money(float posX, float posY)
{
x = posX;
y = posY;
oldY = y;
tag = EntityType::MONEY;
SetState(0);
//SetState(MUSHROOM_STATE_WALKING);
timeDelay = 0;
isDone = false;
isOnTop = false;
}
void Money::GetBoundingBox(float& left, float& top, float& right, float& bottom)
{
if (!isOnTop)
{
left = x-3;
top = y + 3;
right = left + 7;
bottom = top + 14;
}
else
{
if (!isDone)
{
left = x;
top = y;
right = x + MONEY_BBOX_WIDTH;
bottom = y + MONEY_BBOX_HEIGHT;
}
else
{
left = x;
top = y;
right = x;
bottom = y;
}
}
}
void Money::Update(DWORD dt, vector<LPGAMEENTITY>* coObjects)
{
if (isDone)
return;
Entity::Update(dt, coObjects);
/*if (isOnTop)
{
vy += 0.002 * dt;
if (vx == 0)
vx = -MONEY_WALKING_SPEED;
}*/
if (isCollis == true && isStart == false)
{
timeDelay += dt;
if (timeDelay >= 100)
{
alpha = 255;
vy = -0.18;
if (oldY - 50 >= y)
{
isOnTop = true;
isCollis = false;
isStart = true;
oldY = y;
}
}
}
else if (isOnTop)
{
vy = 0.15;
if (abs(y - oldY) > 20)
isDone = true;
}
vector<LPCOLLISIONEVENT> coEvents;
vector<LPCOLLISIONEVENT> coEventsResult;
coEvents.clear();
CalcPotentialCollisions(coObjects, coEvents);
// No collision occured, proceed normally
if (coEvents.size() == 0)
{
x += dx;
y += dy;
}
else
{
float min_tx, min_ty, nx = 0, ny;
float rdx = 0;
float rdy = 0;
// TODO: This is a very ugly designed function!!!!
FilterCollision(coEvents, coEventsResult, min_tx, min_ty, nx, ny, rdx, rdy);
for (UINT i = 0; i < coEventsResult.size(); i++)
{
LPCOLLISIONEVENT e = coEventsResult[i];
if (e->obj->GetType() == EntityType::CBRICK || e->obj->GetType() == EntityType::BRICK)
{
x += min_tx * dx + nx * 0.4f;
y += min_ty * dy + ny * 0.4f;
//if (nx != 0) vx = 0;
if (e->ny != 0) vy = 0;
if (e->nx != 0)
vx = -1 * vx;
}
}
}
for (UINT i = 0; i < coEvents.size(); i++) delete coEvents[i];
}
void Money::Render()
{
if (isDone)
return;
int ani = MONEY_ANI_WALKING;
animationSet->at(ani)->Render(nx, x, y, alpha);
RenderBoundingBox();
}
void Money::SetState(int state)
{
Entity::SetState(state);
switch (state)
{
case MONEY_STATE_WALKING:
//y -= 2;
isCollis = true;
break;
case 0:
alpha = 0;
vx = 0;
vy = 0;
isCollis = false;
break;
}
}
| [
"18521275@gm.uit.edu.vn"
] | 18521275@gm.uit.edu.vn |
7db1380d8897bf00a28d7934b2699b88f6e97f41 | 96f9b1d313eca3cfa731d121d072a44434cec768 | /src/qt/editaddressdialog.cpp | d34001ca8ce1a463810dbbecaa8674a4f8086147 | [
"MIT"
] | permissive | jjshsgsa/Bixbcoin-core | 32256da6d230fa151fa6f0eb5ac2d59d72c4a62d | f4b5c57e351a9285f136a27b70760e468fa830a8 | refs/heads/main | 2022-12-27T03:42:02.786514 | 2020-10-14T18:21:58 | 2020-10-14T18:21:58 | 306,915,613 | 1 | 0 | MIT | 2020-10-24T15:41:25 | 2020-10-24T15:41:24 | null | UTF-8 | C++ | false | false | 3,948 | cpp | // Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "editaddressdialog.h"
#include "ui_editaddressdialog.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
EditAddressDialog::EditAddressDialog(Mode _mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::EditAddressDialog),
mapper(0),
mode(_mode),
model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
switch(mode)
{
case NewReceivingAddress:
setWindowTitle(tr("New receiving address"));
ui->addressEdit->setEnabled(false);
break;
case NewSendingAddress:
setWindowTitle(tr("New sending address"));
break;
case EditReceivingAddress:
setWindowTitle(tr("Edit receiving address"));
ui->addressEdit->setEnabled(false);
break;
case EditSendingAddress:
setWindowTitle(tr("Edit sending address"));
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel *_model)
{
this->model = _model;
if(!_model)
return;
mapper->setModel(_model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
}
bool EditAddressDialog::saveCurrentRow()
{
if(!model)
return false;
switch(mode)
{
case NewReceivingAddress:
case NewSendingAddress:
address = model->addRow(
mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,
ui->labelEdit->text(),
ui->addressEdit->text());
break;
case EditReceivingAddress:
case EditSendingAddress:
if(mapper->submit())
{
address = ui->addressEdit->text();
}
break;
}
return !address.isEmpty();
}
void EditAddressDialog::accept()
{
if(!model)
return;
if(!saveCurrentRow())
{
switch(model->getEditStatus())
{
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
break;
case AddressTableModel::NO_CHANGES:
// No changes were made during edit operation. Just reject.
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid Bixbcoin address.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString &_address)
{
this->address = _address;
ui->addressEdit->setText(_address);
}
| [
"info@bixbcoin.com"
] | info@bixbcoin.com |
f0a32a95bc4489e5010d2bcb142cf234edb61a95 | 27ffb44629667cb5fc2c0816f7b593a0be462af6 | /Library/DXLibrary/DXLibrary/DirectX12/RootSignature/RootSignatureManager.h | 6f3daad705e4f2027b86255d1afec712d708cebd | [] | no_license | Moto0116/Library | 70ce9c39246781e749209eccdc358966f777abde | 856bfdd8cd98e17483fc4734d36caa0189d13778 | refs/heads/develop | 2021-01-19T18:24:47.576756 | 2018-03-21T11:16:46 | 2018-03-21T11:16:46 | 81,069,617 | 2 | 0 | null | 2017-03-18T11:38:40 | 2017-02-06T09:21:07 | C++ | UTF-8 | C++ | false | false | 272 | h | #ifndef LIB_DX12_ROOTSIGNATUREMANAGER_H
#define LIB_DX12_ROOTSIGNATUREMANAGER_H
namespace Lib
{
namespace Dx12
{
class RootSignatureManager
{
public:
RootSignatureManager();
~RootSignatureManager();
};
}
}
#endif // !LIB_DX12_ROOTSIGNATUREMANAGER_H | [
"moto01160902@gmail.com"
] | moto01160902@gmail.com |
116ba7c650b99fb2c34e7d7c8c4352ca32812c55 | 0e40a0486826825c2c8adba9a538e16ad3efafaf | /lib/boost/include/boost/mpl/vector/aux_/push_back.hpp | b10f072b9b96c4314ef3e932b3e5ad8803944feb | [
"MIT"
] | permissive | iraqigeek/iZ3D | 4c45e69a6e476ad434d5477f21f5b5eb48336727 | ced8b3a4b0a152d0177f2e94008918efc76935d5 | refs/heads/master | 2023-05-25T19:04:06.082744 | 2020-12-28T03:27:55 | 2020-12-28T03:27:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,008 | hpp |
#ifndef BOOST_MPL_VECTOR_AUX_PUSH_BACK_HPP_INCLUDED
#define BOOST_MPL_VECTOR_AUX_PUSH_BACK_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// 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)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: push_back.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-11 10:19:02 +0400 (Ñá, 11 îêò 2008) $
// $Revision: 49267 $
#include <boost/mpl/push_back_fwd.hpp>
#include <boost/mpl/aux_/config/typeof.hpp>
#if defined(BOOST_MPL_CFG_TYPEOF_BASED_SEQUENCES)
# include <boost/mpl/vector/aux_/item.hpp>
# include <boost/mpl/vector/aux_/tag.hpp>
namespace boost { namespace mpl {
template<>
struct push_back_impl< aux::vector_tag >
{
template< typename Vector, typename T > struct apply
{
typedef v_item<T,Vector,0> type;
};
};
}}
#endif
#endif // BOOST_MPL_VECTOR_AUX_PUSH_BACK_HPP_INCLUDED
| [
"github@bo3b.net"
] | github@bo3b.net |
05f6971ee94821cc12169a51e208a0008970d301 | 7fcd47097c42fcdb7acb2e10e75759e16ade518e | /binding.cc | 0ed90062b6157cb68280204e3e2bee19081929b3 | [
"MIT"
] | permissive | joaojeronimo/v8worker | eb1c6600ed3d9e387914a1f47e34975be3f5fb9b | e923014340b3a50023b0ea5d8452b275ed957a37 | refs/heads/master | 2021-01-22T00:24:05.322290 | 2015-03-30T13:42:41 | 2015-03-30T13:42:41 | 33,125,257 | 1 | 0 | null | 2015-03-30T13:39:14 | 2015-03-30T13:39:13 | null | UTF-8 | C++ | false | false | 6,899 | cc | #include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string>
#include "v8.h"
#include "libplatform/libplatform.h"
#include "binding.h"
using namespace v8;
struct worker_s {
int x;
void* data;
worker_recv_cb cb;
Isolate* isolate;
std::string last_exception;
Persistent<Function> recv;
Persistent<Context> context;
};
// Extracts a C string from a V8 Utf8Value.
const char* ToCString(const String::Utf8Value& value) {
return *value ? *value : "<string conversion failed>";
}
// Exception details will be appended to the first argument.
std::string ExceptionString(Isolate* isolate, TryCatch* try_catch) {
std::string out;
size_t scratchSize = 100;
char scratch[scratchSize]; // just some scratch space for sprintf
HandleScope handle_scope(isolate);
String::Utf8Value exception(try_catch->Exception());
const char* exception_string = ToCString(exception);
printf("exception string: %s\n", exception_string);
Handle<Message> message = try_catch->Message();
if (message.IsEmpty()) {
// V8 didn't provide any extra information about this error; just
// print the exception.
out.append(exception_string);
out.append("\n");
} else {
// Print (filename):(line number): (message).
String::Utf8Value filename(message->GetScriptOrigin().ResourceName());
const char* filename_string = ToCString(filename);
int linenum = message->GetLineNumber();
snprintf(scratch, scratchSize, "%s:%i: %s\n", filename_string, linenum, exception_string);
out.append(scratch);
// Print line of source code.
String::Utf8Value sourceline(message->GetSourceLine());
const char* sourceline_string = ToCString(sourceline);
out.append(sourceline_string);
out.append("\n");
// Print wavy underline (GetUnderline is deprecated).
int start = message->GetStartColumn();
for (int i = 0; i < start; i++) {
out.append(" ");
}
int end = message->GetEndColumn();
for (int i = start; i < end; i++) {
out.append("^");
}
out.append("\n");
String::Utf8Value stack_trace(try_catch->StackTrace());
if (stack_trace.length() > 0) {
const char* stack_trace_string = ToCString(stack_trace);
out.append(stack_trace_string);
out.append("\n");
}
}
return out;
}
extern "C" {
#include "_cgo_export.h"
void go_recv_cb(const char* msg, void* data) {
recvCb((char*)msg, data);
}
const char* worker_version() {
return V8::GetVersion();
}
const char* worker_last_exception(worker* w) {
return w->last_exception.c_str();
}
int worker_load(worker* w, char* name_s, char* source_s) {
Locker locker(w->isolate);
Isolate::Scope isolate_scope(w->isolate);
HandleScope handle_scope(w->isolate);
Local<Context> context = Local<Context>::New(w->isolate, w->context);
Context::Scope context_scope(context);
TryCatch try_catch;
Local<String> name = String::NewFromUtf8(w->isolate, name_s);
Local<String> source = String::NewFromUtf8(w->isolate, source_s);
ScriptOrigin origin(name);
Local<Script> script = Script::Compile(source, &origin);
if (script.IsEmpty()) {
assert(try_catch.HasCaught());
w->last_exception = ExceptionString(w->isolate, &try_catch);
return 1;
}
Handle<Value> result = script->Run();
if (result.IsEmpty()) {
assert(try_catch.HasCaught());
w->last_exception = ExceptionString(w->isolate, &try_catch);
return 2;
}
return 0;
}
void Print(const FunctionCallbackInfo<Value>& args) {
bool first = true;
for (int i = 0; i < args.Length(); i++) {
HandleScope handle_scope(args.GetIsolate());
if (first) {
first = false;
} else {
printf(" ");
}
String::Utf8Value str(args[i]);
const char* cstr = ToCString(str);
printf("%s", cstr);
}
printf("\n");
fflush(stdout);
}
// sets the recv callback.
void Recv(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
worker* w = (worker*)isolate->GetData(0);
assert(w->isolate == isolate);
HandleScope handle_scope(isolate);
Local<Context> context = Local<Context>::New(w->isolate, w->context);
Context::Scope context_scope(context);
Local<Value> v = args[0];
assert(v->IsFunction());
Local<Function> func = Local<Function>::Cast(v);
w->recv.Reset(isolate, func);
}
// Called from javascript. Must route message to golang.
void Send(const FunctionCallbackInfo<Value>& args) {
std::string msg;
worker* w = NULL;
{
Isolate* isolate = args.GetIsolate();
w = static_cast<worker*>(isolate->GetData(0));
assert(w->isolate == isolate);
Locker locker(w->isolate);
HandleScope handle_scope(isolate);
Local<Context> context = Local<Context>::New(w->isolate, w->context);
Context::Scope context_scope(context);
Local<Value> v = args[0];
assert(v->IsString());
String::Utf8Value str(v);
msg = ToCString(str);
}
// XXX should we use Unlocker?
w->cb(msg.c_str(), w->data);
}
// Called from golang. Must route message to javascript lang.
// non-zero return value indicates error. check worker_last_exception().
int worker_send(worker* w, const char* msg) {
Locker locker(w->isolate);
Isolate::Scope isolate_scope(w->isolate);
HandleScope handle_scope(w->isolate);
Local<Context> context = Local<Context>::New(w->isolate, w->context);
Context::Scope context_scope(context);
TryCatch try_catch;
Local<Function> recv = Local<Function>::New(w->isolate, w->recv);
if (recv.IsEmpty()) {
w->last_exception = "$recv not called";
return 1;
}
Local<Value> args[1];
args[0] = String::NewFromUtf8(w->isolate, msg);
assert(!try_catch.HasCaught());
recv->Call(context->Global(), 1, args);
if (try_catch.HasCaught()) {
w->last_exception = ExceptionString(w->isolate, &try_catch);
return 2;
}
return 0;
}
worker* worker_new(worker_recv_cb cb, void* data) {
V8::Initialize();
Platform* platform = platform::CreateDefaultPlatform();
V8::InitializePlatform(platform);
Isolate* isolate = Isolate::New();
Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
worker* w = new(worker);
w->isolate = isolate;
w->isolate->SetCaptureStackTraceForUncaughtExceptions(true);
w->isolate->SetData(0, w);
w->data = data;
w->cb = cb;
Local<ObjectTemplate> global = ObjectTemplate::New(w->isolate);
global->Set(String::NewFromUtf8(w->isolate, "$print"),
FunctionTemplate::New(w->isolate, Print));
global->Set(String::NewFromUtf8(w->isolate, "$recv"),
FunctionTemplate::New(w->isolate, Recv));
global->Set(String::NewFromUtf8(w->isolate, "$send"),
FunctionTemplate::New(w->isolate, Send));
Local<Context> context = Context::New(w->isolate, NULL, global);
w->context.Reset(w->isolate, context);
//context->Enter();
return w;
}
}
| [
"ry@tinyclouds.org"
] | ry@tinyclouds.org |
f7c1884f38483346d75894e4496b4bde7bb12bc8 | d757d87bfb845a578a92afa272e24abdaf2126dd | /support.cpp | 8d3961089b94f3e5378337affef267db710b3ec2 | [] | no_license | astachey/cs302 | b5f9637010fd2e815e034417134f32b82b0a56a6 | 2998ce7d2f12ce30644d2f442b345efe2eb2cde5 | refs/heads/master | 2020-05-20T00:40:51.130783 | 2014-02-06T05:13:37 | 2014-02-06T05:13:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,580 | cpp | // header files
#include <cmath>
#include "support.h"
using namespace std;
//RGB::RGB(uchar _R = 0, uchar _G= 0, uchar _B = 0){
// R = _R;
// G = _G;
// B = _B;
// return;
//}/
// RGB::operator<()
// RGB::distance()
double RGB::distance(const RGB& next){
double dist = sqrt(pow((double)R - next.R, 2)) + (pow((double)G - next.G, 2))+(pow((double)B - next.B, 2));
}
RGB RGB::quantize(const int &Q){
RGB tmp;
tmp.R = Q*(R/Q);
tmp.G = Q*(G/Q);
tmp.B = Q*(B/Q);
return tmp;
}
PPM::PPM() {
magicid = "P6";
nrows = 0;
ncols = 0;
maxvalue = 255;
}
PPM::~PPM() { }
void PPM::read(const string & fname)
{
ifstream fin;
if(fname.substr(fname.find_last_of(".")+1) == "ppm"){
fin.open(fname.c_str());
if(!fin.is_open()){
cerr << "Unable to open file."<<endl;
}
}
else{
cerr << "Invalid file name." <<endl;
exit (1);
}
// extract suffix: must be ppm
// open fname: check status
string magicid;
int nrows, ncols, maxval;
fin >> magicid >> nrows >> ncols >> maxvalue;
if (magicid!= "P6"){
cerr << "Magic Number for ppm file is not P6. Exiting. " << endl;
exit(1);
}
// read magicid: must be P6
// read ncols, nrows: check status
// read maxvalue: must be 255
if (maxvalue != 255){
cerr << "Max value does not equal 255. "<< endl;
exit(1);
}
int npixels = (ncols*nrows);
int nbytes = 3 * npixels;
img.assign(nbytes, RGB());
// allocate space for 3*npixels in img vector
// read 3*npixels bytes into img: check status
if(img.size()!=nbytes){
cerr<< "Error creating image vector. Exiting."<<endl;
exit(1);
}
fin.read((char* ) img.data(), nbytes);
// close input file
fin.close();
}
void PPM::write(const string & fname)
{
// open fname: check status
ofstream fout;
fout.open( fname.c_str());
if(!fout.is_open()){
cerr << "Unable to open output file. Exiting."<<endl;
exit (1);
}
// write header
fout << magicid << endl << ncols << " " << nrows << endl << maxvalue << endl;
int npixels = ncols*nrows;
// write 3*npixels from img vector
int nbytes = 3 * npixels;
fout.write(( char* ) img.data(), nbytes);
// close output file
fout.close();
}
void PPM::write(const string & fname, const string & addon)
{
// new_fname: image.ppm -> image_addon.ppm
string noext = fname.substr(0, fname.size() - 4);
string newfile = noext + "_" + addon + ".ppm";
// call write(new_fname);
write(newfile);
return;
}
void PPM::process(pmode_t pmode, const string &fname)
{
// read qcolors in fname
//int _R, _G, _B;
//ifstream colsin;
//colsin.open(fname.c_str());
//if(!colsin.is_open()){
// cerr << "Could not open filename to process. Exiting now."<<endl;
// }
// while ( colsin ) {
// qcolors.push_back(RGB());
// while (colsin.get()!= '\n' && !colsin.eof()) {}
// }
// colsin.close();
read_qcolors(fname);
// run proper process mode
if( pmode == run_process1){
process1();
}
else if(pmode == run_process2){
process2();
}
else{
cerr<< "No valid process to run. Exiting now." << endl;
exit(1);
}
return;
}
void PPM::process1()
{
// for each pixel {
for( int i = 0; i < img.size(); i++){
map<int, RGB> colormap;
// find closest qcolor
for( int j = 0; j< colormap.size(); j++){
// set pixel color to closest qcolor
colormap.insert( pair< int, RGB >( img[i].distance ( colormap[j]), colormap[j]));
}
img[i] = colormap.begin() -> second;
}
// }
}
void PPM::process2()
{
// for each pixel {
vector<map<int, RGB> > histo(qcolors.size());
map< int, float> qmap;
map< int, float> :: iterator iqmap;
for( int i = 0; i < img.size(); i++){
map<int, RGB> colormap;
// find closest qcolor
for( int j = 0; j< colormap.size(); j++){
qmap[j] = img[i].distance(qcolors[j]);
}
iqmap = min_element(qmap.begin(), qmap.end());
// update qcolor histogram of pixel color/8 counts
RGB tmp;
tmp = img[i].quantize(8);
// save closest qcolor index
//for (int i; i < iqmap.size(); i++){
// if (iqmap[i]==histo[i]){
// iqmap->second++;
// }
// else{
// histo[iqmap -> first].insert (tmp,1);
// }
// }
//
// for each qcolor {
// find highest count pixel value/8
// replace qcolor with highest count pixel value/8
// }
//
// for each pixel {
// set pixel color to qcolor[closest qcolor index]
// }
}
}
void PPM::read_qcolors(const string &fname)
{
// open fname: check status
RGB tmp;
ifstream fin;
fin.open(fname.c_str());
if(!fin.is_open()){
cerr<< "Unable to open file. Exiting."<< endl;
exit(1);
}
int r, g, b;
string buffer;
//
// while (more data0 {
// read R G B values
fin >> r >> g >> b >> buffer >> buffer;
while(fin){
tmp.R = r;
tmp.G = g;
tmp.B = b;
// save to qcolors vector
qcolors.push_back (tmp);
fin >> r >> g >> b >> buffer >> buffer;
}
// }
//
// close input file
fin.close();
}
| [
"astachey@utk.edu"
] | astachey@utk.edu |
ef276fdc3383e673fb992cff9a70b85cfe1e8266 | 6dacb8f59751c9647685d4b931b2cbef00fcd302 | /InterviewPrep/Array _ Strings/majorityElement.cpp | 9e67681a83f24553bcbd6048b7e2e4fefae7ecdc | [] | no_license | sudhanshu-t/DSA | 88662429514509c3a063d7610db3d32a6854c5c0 | 042fad26085405f77f159eb08c53555de9fb7732 | refs/heads/master | 2021-07-19T15:26:34.310444 | 2020-07-09T11:59:41 | 2020-07-09T11:59:41 | 278,350,018 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 818 | cpp | #include<iostream>
#include<vector>
using namespace std;
int majorityElement(vector<int>& nums) {
//Write your code here
int pot = nums[0];
int count = 1;
for(int i = 1; i < nums.size(); i++){
if(nums[i] != pot){
count--;
if(count == 0){
count = 1;
pot = nums[i];
}
} else {
count++;
}
}
count = 0;
for(int i = 0; i < nums.size(); i++){
if(nums[i] == pot){
count++;
}
}
if(count > nums.size() / 2){
return pot;
} else {
return -1;
}
}
int main(int argc,char**argv){
int n;
cin>>n;
vector<int> v(n);
for(int i=0;i<n;i++){
cin>>v[i];
}
int res=majorityElement(v);
cout<<res<<endl;
} | [
"sudhanshu21.st@gmail.com"
] | sudhanshu21.st@gmail.com |
a902a5f751ab425b27a305baedef0bcc45a338d6 | 0c95b0e960e0c23e47c9ff953bc60f1003158470 | /calculator_controller/calculator_controller.ino | 176a56ce1bed445530b7e4b96a7c31ee90fe50d4 | [] | no_license | kuzlab/midi_controller_pj | f1a5805de7e56d81fa643e0c567504bf6e300ed2 | 92612ba747f628e92c348d85fdcfcb7be2bed343 | refs/heads/master | 2021-01-19T21:52:20.916078 | 2015-05-18T18:35:04 | 2015-05-18T18:35:04 | 33,324,099 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,519 | ino | #include "assign_map.h"
#define PIN0 13
#define PIN1 14
#define PIN2 15
#define PIN3 16
#define PIN4 17
#define PIN5 18
#define PIN6 19
#define PIN7 20
#define PIN8 21
#define SW0 2
#define SW1_0 0
#define SW1_1 1
#define LOOP_DELAY 30
#define SEND_MIDI_DELAY 100
//#define _DEBUG_
//#define _COMMAND_MODE_DEBUG_
int inpins[5] = {
PIN0,
PIN2,
PIN4,
PIN6,
PIN8
};
int outpins[4] = {
PIN1,
PIN3,
PIN5,
PIN7,
};
uint8_t switch_state[20] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
int8_t keymap[5*4] =
{
-1, -1, -1, DECREMENT_KEY_VALUE, INCREMENT_KEY_VALUE,
-1, 9, 6, 3, SEND_KEY_VALUE,
-1, 8, 5, 2, 0,
-1, 7, 4, 1, CANCEL_KEY_VALUE
};
#define THD 800
void print_inpins_all(){
for(int i=0;i<5;i++){
// Serial.print(digitalRead(inpins[i]));
// Serial.print(' ');
// Serial.print(analogRead(inpins[i]));
if(analogRead(inpins[i]) > THD){
Serial.print("ON ");
}
else{
Serial.print("OFF");
}
Serial.print('(');
Serial.print(analogRead(inpins[i]));
Serial.print(')');
Serial.print('\t');
}
Serial.println("");
}
void set_one_pin_high_other_pins_low(int pin){
for(int i=0;i<4;i++){
if(pin == outpins[i]){
digitalWrite(outpins[i], HIGH);
}
else{
digitalWrite(outpins[i], LOW);
}
}
}
void setup(){
Serial.begin(57600);
for(int i=0;i<5;i++){
pinMode(inpins[i], INPUT);
}
for(int i=0;i<4;i++){
pinMode(outpins[i], OUTPUT);
digitalWrite(outpins[i], LOW);
}
pinMode(SW0, INPUT);
pinMode(SW1_0, INPUT);
pinMode(SW1_1, INPUT);
digitalWrite(SW0, HIGH);
digitalWrite(SW1_0, HIGH);
digitalWrite(SW1_1, HIGH);
delay(3000);
}
void print_SW0(){
if(digitalRead(SW0)){
Serial.println("SW0 : OFF");
}
else{
Serial.println("SW0 : ON");
}
}
void print_SW1(){
if(digitalRead(SW1_0)){
if(digitalRead(SW1_1)){
Serial.println("SW1 : position1");
}
else{
Serial.println("SW1 : position2");
}
}
else{
if(digitalRead(SW1_1)){
Serial.println("SW1 : position4");
}
else{
Serial.println("SW1 : position3");
}
}
}
int8_t return_pressed_button_number()
{
for(uint8_t i=0;i<5;i++){
if(analogRead(inpins[i]) > THD){
return i;
}
}
return -1;
}
uint8_t return_sw0_state()
{
if(digitalRead(SW0)){
return 1;
}
return 0;
}
uint8_t return_sw1_state(){
if(digitalRead(SW1_0)){
if(digitalRead(SW1_1)){
return 0;
}
else{
return 1;
}
}
else{
if(digitalRead(SW1_1)){
return 3;
}
}
return 2;
}
void send_midi(uint8_t sw0_state, uint8_t sw1_state, uint8_t num)
{
if(sw0_state == 1){ // kaos pad mode
uint8_t first_byte = 0xb4;
uint8_t second_byte = 0x00 + sw1_state * 16 + num;
Serial.print('$');
Serial.print(first_byte);
Serial.print(',');
Serial.print(second_byte);
Serial.print(',');
Serial.print(127);
Serial.println('%');
}
else{ // command mode
int temp = num%100;
uint8_t first_byte = (0xb6 + (num-temp)/100)&0xff;
uint8_t second_byte = 0x00 + temp;
Serial.print('$');
Serial.print(first_byte);
Serial.print(',');
Serial.print(second_byte);
Serial.print(',');
Serial.print(127);
Serial.println('%');
}
delay(SEND_MIDI_DELAY);
}
int return_keynum_if_pressed(){
int8_t num = -1;
int8_t res = -1;
int8_t temp;
for(uint8_t i=0;i<4;i++){
set_one_pin_high_other_pins_low(outpins[i]);
temp = return_pressed_button_number();
#ifdef _DEBUG_
print_inpins_all();
Serial.print("pressed [");
Serial.print(i);
Serial.print(" , ");
Serial.print(temp);
Serial.println(" ]");
#endif
if(temp >= 0){
num = temp + 5*i;
// Serial.println(num);
if(switch_state[num] != 1){
res = num;
}
}
#ifdef _DEBUG_
// Serial.println("------------------------------------------------------------------------------------");
Serial.print("switch_state = {");
for(uint8_t i=0;i<20;i++){
Serial.print(switch_state[i]);
Serial.print(",");
}
Serial.println("}");
Serial.println("------------------------------------------------------------------------------------");
#endif
for(uint8_t j=0;j<5;j++){
switch_state[5*i+j] = 0;
}
if(temp >= 0 && num >= 0){
switch_state[num] = 1;
}
if(res >= 0){
return res;
}
}
return res;
}
uint8_t command_buff[3] = { 0, 0, 0 };
void loop(){
int num = return_keynum_if_pressed();
if(num >= 0){
#ifdef _COMMAND_MODE_DEBUG_
Serial.print("keynum = ");
Serial.println(num);
#endif
if(return_sw0_state()){ // kaos pad mode
send_midi(return_sw0_state(), return_sw1_state(), num);
}
else{ // command mode
int8_t value = keymap[num];
#ifdef _COMMAND_MODE_DEBUG_
Serial.print("-> key value = ");
Serial.println(value);
#endif
if(value == SEND_KEY_VALUE){
uint8_t send_num = command_buff[0] * 100 + command_buff[1] * 10 + command_buff[2];
send_midi(return_sw0_state(), return_sw1_state(), send_num);
}
else if(value == CANCEL_KEY_VALUE){
command_buff[0] = 0;
command_buff[1] = 0;
command_buff[2] = 0;
}
else if(value == INCREMENT_KEY_VALUE){
uint8_t temp = command_buff[0] * 100 + command_buff[1] * 10 + command_buff[2];
temp++;
command_buff[2] = temp%10;
temp = (temp - command_buff[2])/10;
command_buff[1] = temp%10;
temp = (temp - command_buff[1])/10;
command_buff[0] = temp%10;
}
else if(value == DECREMENT_KEY_VALUE){
uint8_t temp = command_buff[0] * 100 + command_buff[1] * 10 + command_buff[2];
temp--;
if(temp < 0){temp = 0;}
command_buff[2] = temp%10;
temp = (temp - command_buff[2])/10;
command_buff[1] = temp%10;
temp = (temp - command_buff[1])/10;
command_buff[0] = temp%10;
}
else if(value >= 0){
command_buff[0] = command_buff[1];
command_buff[1] = command_buff[2];
command_buff[2] = value%10;
}
#ifdef _COMMAND_MODE_DEBUG_
Serial.print(command_buff[0]);
Serial.print(command_buff[1]);
Serial.println(command_buff[2]);
#endif
}
}
// print_SW0();
// print_SW1();
delay(LOOP_DELAY);
#ifdef _DEBUG_
delay(3000);
#endif
}
| [
"qzuryu@gmail.com"
] | qzuryu@gmail.com |
032c598bddf5520f276318d74a5fb571923dfba1 | 2906f1a8466c359cada4f2f9ec31c2b24e7c524d | /MIlestone 3/Client/Pkt_Def.h | aa8648d6744ad5de1fd04a856f84351b608acc01 | [] | no_license | Minashed/Robot-Controller | 7ff60d96d32183f1d9cb201c2ebeeb323f2259b9 | 01341727aa026333c7c8945274175df1a34b81b3 | refs/heads/master | 2021-05-05T01:12:00.705226 | 2018-01-31T05:14:48 | 2018-01-31T05:14:48 | 119,632,088 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,281 | h | #ifndef PKTDEF_H
#define PKTDEF_H
#include <iostream>
#include <iomanip>
#include <stdio.h>
//Globally defined variables
#define FORWARD 1
#define BACKWARD 2
#define LEFT 3
#define RIGHT 4
#define UP 5
#define DOWN 6
#define OPEN 7
#define CLOSE 8
//Size of the entire header varies in size
#define HEADERSIZE 6
//Enum for flags
enum CmdType { DRIVE, STATUS, SLEEP, ARM, CLAW, ACK, NACK};
// 0 1 2 3 4
//Header Struct
struct Header {
unsigned int PktCount; // 4Bytes 0
unsigned char Drive : 1;
unsigned char Status : 1;
unsigned char Sleep : 1;
unsigned char Arm : 1;
unsigned char Claw : 1;
unsigned char Ack : 1;
unsigned char Padding : 2; // 5Bytes 5
unsigned char Length; //6 Bytes
};
//Body Struct
struct MotorBody {
unsigned char Direction;
unsigned char Duration;
};
//Telemery Body
struct TelBody {
unsigned short int Sonar;
unsigned short int Arm;
unsigned char DriveF : 1;
unsigned char ArmUp : 1;
unsigned char ArmDown : 1;
unsigned char ClawOpen : 1;
unsigned char ClawClosed : 1;
unsigned char Padding : 3;
};
//MAIN CLASS
class PktDef {
private:
struct CmdPacket
{
Header header; // 6 Bytes
char* Data; // 1or2 Bytes?
char CRC;// 1 Bytes
} CP; // 8 Bytes 9 Bytes?
char* RawBuffer;
public:
//Constructors
PktDef();
PktDef(char*);
//Setters
void SetCmd(CmdType);
void SetBodyData(char*, int);
void SetPktCount(int);
//Getters
CmdType GetCmd();
bool GetStatus();
bool GetAck();
int GetLength();
char* GetBodyData();
int GetPktCount();
//a function that takes a pointer to a RAW data buffer, the
//size of the buffer in bytes, and calculates the CRC.If the calculated CRC matches the
//CRC of the packet in the buffer the function returns TRUE, otherwise FALSE
bool CheckCRC(char*, int);
//a function that calculates the CRC and sets the objects packet CRC parameter.
void CalcCRC();
//a function that allocates the private RawBuffer and transfers the
//contents from the objects member variables into a RAW data packet(RawBuffer) for
//transmission.The address of the allocated RawBuffer is returned.
char* GenPacket();
/*
std::string GetCmdStr();
int GetBitsSet(char* pktBuffer);
friend std::ostream& operator<<(std::ostream& os, PktDef&);
*/
};
#endif | [
"mmnashed@myseneca.ca"
] | mmnashed@myseneca.ca |
64a6dc204d1c390a91084b502c0d7bfe8afb24ac | 5175bd24b43d8db699341997df5fecf21cc7afc1 | /libs/config/checks/std/cpp_lib_transformation_trait_aliases_14.cpp | 1ce92f60a915a8bfdfc1b07dd71fe93456306bdf | [
"BSL-1.0",
"LicenseRef-scancode-proprietary-license"
] | permissive | quinoacomputing/Boost | 59d1dc5ce41f94bbd9575a5f5d7a05e2b0c957bf | 8b552d32489ff6a236bc21a5cf2c83a2b933e8f1 | refs/heads/master | 2023-07-13T08:03:53.949858 | 2023-06-28T20:18:05 | 2023-06-28T20:18:05 | 38,334,936 | 0 | 0 | BSL-1.0 | 2018-04-02T14:17:23 | 2015-06-30T21:50:37 | C++ | UTF-8 | C++ | false | false | 840 | cpp | // This file was automatically generated on Wed Mar 3 12:23:03 2021
// by libs/config/tools/generate.cpp
// Copyright John Maddock 2002-4.
// Use, modification and distribution are subject to 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)
// See http://www.boost.org/libs/config for the most recent version.//
// Revision $Id$
//
#ifdef __has_include
#if __has_include(<version>)
#include <version>
#endif
#endif
#include <type_traits>
#ifndef __cpp_lib_transformation_trait_aliases
#error "Macro << __cpp_lib_transformation_trait_aliases is not set"
#endif
#if __cpp_lib_transformation_trait_aliases < 201304
#error "Macro __cpp_lib_transformation_trait_aliases had too low a value"
#endif
int main( int, char *[] )
{
return 0;
}
| [
"apandare@lanl.gov"
] | apandare@lanl.gov |
ac0c7cb82a86670c60e7f6ec3594b902109ec037 | f8cdebfd3bb24190e288eda5ec66401a61e9f38d | /exercise_inschool/getLocalLessIndex/getLocalLessIndex.cpp | 2e3cbdb4e90e478149f4b1a2583b7a8380fd20e0 | [] | no_license | woaishixiaoxiao/algorithm | fd617d7cf8a5d65c5c14df325e99fd8a62fe4165 | e9268975d08d48f3607eeb80e53ca4710b47c9cc | refs/heads/master | 2020-04-23T21:23:06.390335 | 2019-07-21T09:38:32 | 2019-07-21T09:38:32 | 171,468,927 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,951 | cpp | //定义局部最小的概念。arr长度为1时,arr[0]是局部最小。arr的长度为N(N>1)时,如果arr[0]<arr[1],那么arr[0]是局部最小;
//如果arr[N-1]<arr[N-2],那么arr[N-1]是局部最小;如果0<i<N-1,既有arr[i]<arr[i-1]又有arr[i]<arr[i+1],那么arr[i]是局部最小。
//给定无序数组arr,已知arr中任意两个相邻的数都不相等,写一个函数,只需返回arr中任意一个局部最小出现的位置即可。
//解释下为什么第二个数比第一个数小,最后一个数比倒数第二个大,那么就一定会有一个局部最小值
//因为相邻的两个是不相等的,所以相邻三个数的关系,就有这么几种情况,一直降,一直升,先将后升,先升后降,
//因为最开始的两个数的趋势是下降,从最后到倒数第二个数的趋势也是下降,反正自己画画也能画出来,不要纠结
//最后结论就是只要两头的趋势都是下降,那么中间必有一个,如果两头有一个不是这样的,那答案就直接有了,所以这道题,一定有解
#include<iostream>
#include<vector>
using namespace std;
bool getLocalLessIndex(vector<int>&ivec,int &pos){
if(ivec.empty())return false;
int beg=0;
int end=ivec.size()-1;
int mid;
if(ivec.size()==1||ivec[beg]<ivec[beg+1]){
pos=beg;
return true;
}else{
if(ivec[end]<ivec[end-1]){
pos=end;
return true;
}
}
while(beg<end){//这个里面不用再去判断13-20的那个内容,因为你只要确定了解一定在这个区间范围内就可以了,进而把区间范围减小就行了
mid=(beg+end)/2;
if(ivec[mid]>ivec[mid-1]){
end=mid-1;
}else{
if(ivec[mid]>ivec[mid+1]){
beg=mid+1;
}else{
pos=mid;
return true;
}
}
}
return beg; //这里返回什么都无所谓,因为上面是一定有解得
}
main(){
vector<int>ivec={};
int pos;
if(getLocalLessIndex(ivec,pos)){
cout<<pos<<endl;
}
}
| [
"823124073@qq.com"
] | 823124073@qq.com |
624b678d5e90f9a795c3bfa86e8a809f15a9a0c4 | c49a1113fd445046e126a1e38cc16044e9e6fa03 | /zhouqi/source/OJ.cpp | 337d6a5f3fa8077273a9f24887a61aa33b60331a | [] | no_license | VicoandMe/HW | 276a8c289fab17e24afbb7a309a265c393ccd407 | 6900fbaf97761d2c5b7c4d92f976a5c70920f99e | refs/heads/master | 2021-01-10T15:26:04.342717 | 2016-02-02T07:04:31 | 2016-02-02T07:04:31 | 50,571,071 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 739 | cpp |
#include "OJ.h"
#include <string.h>
//#include <stdio.h>
/*
功能:计算字符串的最小周期。
原型:
int GetMinPeriod(char *string);
输入参数:
char * string:字符串。
返回值:
int 字符串最小周期。
*/
int GetMinPeriod(char *inputstring)
{
int length = strlen(inputstring);
for (int i = 1; i < length;i++) {
bool flag = 0;
if (length%i == 0) {
flag = 1;
for (int j = i; j < length; j++) {
if (inputstring[j] != inputstring[j-i]) {
flag = 0;
break;
}
}
if(flag == 1) {
return i;
}
}
}
return length;
}
//int main() {
// char a[] = "abcabcabcabc....\0";
// printf("%d\n",GetMinPeriod(a));
//}
| [
"li362927450@gmail.com"
] | li362927450@gmail.com |
81007cfbf3ec7f5e773a72fe7b1b1a5a8ea48168 | 25b36236d90aa38deb0e28db06f5f5ee5264d931 | /NPLib/Core/NPInputParser.h | 0791fe5c74a8c47f83b8bfd0390d79066d4dbc61 | [] | no_license | adrien-matta/nptool | 54b5ea6fe2d8c226e7422a948d3ecc94d62d1ff2 | 415ad50066f715ca1de312da1202201f9381e87e | refs/heads/NPTool.2.dev | 2021-04-18T23:52:44.645407 | 2019-09-02T12:38:49 | 2019-09-02T12:38:49 | 13,268,020 | 36 | 20 | null | 2016-12-05T11:46:35 | 2013-10-02T10:11:22 | C++ | UTF-8 | C++ | false | false | 4,562 | h | #ifndef NPINPUTPARSER
#define NPINPUTPARSER
/*****************************************************************************
* Copyright (C) 2009-2016 this file is part of the NPTool Project *
* *
* For the licensing terms see $NPTOOL/Licence/NPTool_Licence *
* For the list of contributors see $NPTOOL/Licence/Contributors *
*****************************************************************************/
/*****************************************************************************
* Original Author: Adrien Matta contact address: matta@lpccaen.in2p3.fr *
* *
* Creation Date : December 2016 *
* Last update : *
*---------------------------------------------------------------------------*
* Decription: *
* This class allow for parsing of tabulated input file with unit and token*
* *
*---------------------------------------------------------------------------*
* Comment: *
* *
* *
*****************************************************************************/
// STL
#include<string>
#include<vector>
#include<map>
// ROOT
#include"TVector3.h"
namespace NPL{
static std::string token_separator = "=";
std::string StripSpaces(std::string line);
std::string ToLower(std::string line);
double ApplyUnit(double value, std::string unit);
unsigned int GetLevel(std::string line);
class InputBlock{
public:
InputBlock(){};
InputBlock(std::string line);
~InputBlock(){};
NPL::InputBlock* Copy();
private:
unsigned int m_Level;
std::string m_MainToken;
std::string m_MainValue;
std::vector<std::string> m_Token;
std::vector<std::string> m_Value;
public:
void AddLine(std::string line);
std::string ExtractToken(std::string line,std::string separator="");
std::string ExtractValue(std::string line,std::string separator="");
public:
std::string GetToken(unsigned int i){return m_Token[i];};
std::string GetValue(unsigned int i){return m_Value[i];};
std::string GetValue(std::string Token);
void SetValue(unsigned int i, std::string val){m_Value[i]=val;};
public:
bool HasTokenList(std::vector<std::string> TokenList);
bool HasToken(std::string Token);
public:
std::string GetMainToken(){return m_MainToken;};
std::string GetMainValue(){return m_MainValue;};
unsigned int GetSize(){return m_Token.size();};
double GetDouble(std::string Token,std::string default_unit);
int GetInt(std::string Token);
std::string GetString(std::string Token);
TVector3 GetTVector3(std::string Token,std::string default_unit);
std::vector<double> GetVectorDouble(std::string Token,std::string default_unit);
std::vector<int> GetVectorInt(std::string Token);
std::vector<std::string> GetVectorString(std::string Token);
std::vector<NPL::InputBlock*> GetSubBlock(std::string Token);
public:
void Dump();
};
////////////////////////////////////////////////////////////////////////////////
class InputParser{
public:
InputParser(){};
InputParser(std::string filename,bool ExitOnError=true) {ReadFile(filename,ExitOnError);}
~InputParser(){};
private:
std::vector<InputBlock*> m_Block;
std::map<std::string, std::vector<std::string> > m_Aliases;
private:
int m_verbose;
public:
void ReadFile(std::string filename,bool ExitOnError=true);
void TreatAliases();
void TreatOneAlias(){};
void Dump();
void Print() {Dump();}
void Clear();
std::vector<InputBlock*> GetAllBlocksWithToken(std::string Token);
std::vector<InputBlock*> GetAllBlocksWithTokenAndValue(std::string Token,std::string Value);
std::vector<std::string> GetAllBlocksValues(std::string);
std::vector<std::string> GetAllBlocksToken();
private:
bool IsNotComment(std::string line);
};
}
#endif
| [
"matta@lpccaen.in2p3.fr"
] | matta@lpccaen.in2p3.fr |
4137e85f25a7e3f48a920606316533af6176a890 | 15b85084ba3a2d9833de12bfc3ba5d8fbca6fed7 | /test.cpp | b22bed4a89814f5ad5327dd2f6b1eb7587a5701a | [] | no_license | kryczko/water_simulation_data | 52f5d81580f0a4fca71fa701be3f1ec272c6b77b | 47e1e98545df69efcec56419c1409195f6fd987a | refs/heads/master | 2016-09-03T07:28:44.740603 | 2013-09-29T20:00:36 | 2013-09-29T20:00:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 209 | cpp | #include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <int> array;
int j = 7;
array[0].push_back(j);
array[1].push_back(j);
cout << array[0][0] << array[1][0] << endl;
return 0;
}
| [
"kevinryczko@me.com"
] | kevinryczko@me.com |
584ef20053e71b2c35bb71683823364f4530998b | 0f7a4119185aff6f48907e8a5b2666d91a47c56b | /sstd_utility/windows_boost/boost/interprocess/sync/shm/named_condition_any.hpp | a6fb7baff67d5d57e202696cddb8a65bc2de84b4 | [] | no_license | jixhua/QQmlQuickBook | 6636c77e9553a86f09cd59a2e89a83eaa9f153b6 | 782799ec3426291be0b0a2e37dc3e209006f0415 | refs/heads/master | 2021-09-28T13:02:48.880908 | 2018-11-17T10:43:47 | 2018-11-17T10:43:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,511 | hpp | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2005-2012. 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)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_INTERPROCESS_SHM_NAMED_CONDITION_ANY_HPP
#define BOOST_INTERPROCESS_SHM_NAMED_CONDITION_ANY_HPP
#ifndef BOOST_CONFIG_HPP
# include <boost/config.hpp>
#endif
#
#if defined(BOOST_HAS_PRAGMA_ONCE)
# pragma once
#endif
#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/interprocess/detail/workaround.hpp>
#include <boost/static_assert.hpp>
#include <boost/interprocess/detail/type_traits.hpp>
#include <boost/interprocess/creation_tags.hpp>
#include <boost/interprocess/exceptions.hpp>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/sync/interprocess_condition.hpp>
#include <boost/interprocess/detail/managed_open_or_create_impl.hpp>
#include <boost/interprocess/detail/posix_time_types_wrk.hpp>
#include <boost/interprocess/sync/shm/named_creation_functor.hpp>
#include <boost/interprocess/sync/named_mutex.hpp>
#include <boost/interprocess/permissions.hpp>
#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <boost/interprocess/sync/detail/condition_any_algorithm.hpp>
//!\file
//!Describes process-shared variables interprocess_condition class
namespace boost {
namespace interprocess {
namespace ipcdetail {
#if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)
class interprocess_tester;
#endif //#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED
//! A global condition variable that can be created by name.
//! This condition variable is designed to work with named_mutex and
//! can't be placed in shared memory or memory mapped files.
class shm_named_condition_any
{
#if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)
//Non-copyable
shm_named_condition_any();
shm_named_condition_any(const shm_named_condition_any &);
shm_named_condition_any &operator=(const shm_named_condition_any &);
#endif //#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED
public:
//!Creates a global condition with a name.
//!If the condition can't be created throws interprocess_exception
shm_named_condition_any(create_only_t create_only, const char *name, const permissions &perm = permissions())
: m_shmem (create_only
,name
,sizeof(internal_condition) +
open_create_impl_t::ManagedOpenOrCreateUserOffset
,read_write
,0
,construct_func_t(DoCreate)
,perm)
{}
//!Opens or creates a global condition with a name.
//!If the condition is created, this call is equivalent to
//!shm_named_condition_any(create_only_t, ... )
//!If the condition is already created, this call is equivalent
//!shm_named_condition_any(open_only_t, ... )
//!Does not throw
shm_named_condition_any(open_or_create_t open_or_create, const char *name, const permissions &perm = permissions())
: m_shmem (open_or_create
,name
,sizeof(internal_condition) +
open_create_impl_t::ManagedOpenOrCreateUserOffset
,read_write
,0
,construct_func_t(DoOpenOrCreate)
,perm)
{}
//!Opens a global condition with a name if that condition is previously
//!created. If it is not previously created this function throws
//!interprocess_exception.
shm_named_condition_any(open_only_t open_only, const char *name)
: m_shmem (open_only
,name
,read_write
,0
,construct_func_t(DoOpen))
{}
//!Destroys *this and indicates that the calling process is finished using
//!the resource. The destructor function will deallocate
//!any system resources allocated by the system for use by this process for
//!this resource. The resource can still be opened again calling
//!the open constructor overload. To erase the resource from the system
//!use remove().
~shm_named_condition_any()
{}
//!If there is a thread waiting on *this, change that
//!thread's state to ready. Otherwise there is no effect.*/
void notify_one()
{ m_cond.notify_one(); }
//!Change the state of all threads waiting on *this to ready.
//!If there are no waiting threads, notify_all() has no effect.
void notify_all()
{ m_cond.notify_all(); }
//!Releases the lock on the named_mutex object associated with lock, blocks
//!the current thread of execution until readied by a call to
//!this->notify_one() or this->notify_all(), and then reacquires the lock.
template <typename L>
void wait(L& lock)
{ m_cond.wait(lock); }
//!The same as:
//!while (!pred()) wait(lock)
template <typename L, typename Pr>
void wait(L& lock, Pr pred)
{ m_cond.wait(lock, pred); }
//!Releases the lock on the named_mutex object associated with lock, blocks
//!the current thread of execution until readied by a call to
//!this->notify_one() or this->notify_all(), or until time abs_time is reached,
//!and then reacquires the lock.
//!Returns: false if time abs_time is reached, otherwise true.
template <typename L>
bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time)
{ return m_cond.timed_wait(lock, abs_time); }
//!The same as: while (!pred()) {
//! if (!timed_wait(lock, abs_time)) return pred();
//! } return true;
template <typename L, typename Pr>
bool timed_wait(L& lock, const boost::posix_time::ptime &abs_time, Pr pred)
{ return m_cond.timed_wait(lock, abs_time, pred); }
//!Erases a named condition from the system.
//!Returns false on error. Never throws.
static bool remove(const char *name)
{ return shared_memory_object::remove(name); }
#if !defined(BOOST_INTERPROCESS_DOXYGEN_INVOKED)
private:
class internal_condition_members
{
public:
typedef interprocess_mutex mutex_type;
typedef interprocess_condition condvar_type;
condvar_type& get_condvar() { return m_cond; }
mutex_type& get_mutex() { return m_mtx; }
private:
mutex_type m_mtx;
condvar_type m_cond;
};
typedef ipcdetail::condition_any_wrapper<internal_condition_members> internal_condition;
internal_condition m_cond;
friend class boost::interprocess::ipcdetail::interprocess_tester;
void dont_close_on_destruction()
{ interprocess_tester::dont_close_on_destruction(m_shmem); }
typedef ipcdetail::managed_open_or_create_impl<shared_memory_object, 0, true, false> open_create_impl_t;
open_create_impl_t m_shmem;
template <class T, class Arg> friend class boost::interprocess::ipcdetail::named_creation_functor;
typedef boost::interprocess::ipcdetail::named_creation_functor<internal_condition> construct_func_t;
#endif //#ifndef BOOST_INTERPROCESS_DOXYGEN_INVOKED
};
} //namespace ipcdetail
} //namespace interprocess
} //namespace boost
#include <boost/interprocess/detail/config_end.hpp>
#endif // BOOST_INTERPROCESS_SHM_NAMED_CONDITION_ANY_HPP
| [
"nanguazhude@vip.qq.com"
] | nanguazhude@vip.qq.com |
9b63b4da7f2128aae31f22d53696933b3cdcf8f4 | 077e2cb43a4435e6bad1db626ccfbec18bd0b3a8 | /R1/Week2/xymodn.cpp | a9c7e07eb62cfefadef2ce993dae1c91a0ee3c31 | [] | no_license | peter0749/581_Homeworks | e57a4bdac33275c6617286d87009744b94b9be87 | f9394c8a71f4eb5991b78f22f4126dc1da94f46e | refs/heads/master | 2021-01-18T18:42:21.000721 | 2017-03-25T07:09:02 | 2017-03-25T07:09:02 | 52,514,761 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 815 | cpp | #include <iostream>
#include <iomanip>
#include <string>
#define MAX 100001
using namespace std;
int digit[MAX] = {0};
int book[MAX] = {0};
int modN(int x,long long int y, int N)
{
long long int i, base(1);
if(x==0) return 0;
if(y==0) return 1;
//getch();cout<<"ok"<<endl;
for(i=0;i<N;i++) book[i]=0;
//x%=N;
for(i=1; i<=y;i++)
{
base = (base*x)%N;
//cout<<base<<endl;
if(book[base]!=0) break;
book[base] = i;
digit[i] = base;
}
if(i>y)
{
return base;
}
//return -1;
return digit[book[base]+(y-i)%(i-book[base])];
}
int main(void)
{
int x, N;
int term;
long long int y;
cin>>term;
while(term--)
{
cin>>x>>y>>N;
cout<<modN(x,y,N)<<"\n";
}
return 0;
}
| [
"jengku@gmail.com"
] | jengku@gmail.com |
ab7f4348b6906422cdcef8a1fc604842a1d25105 | ef9a782df42136ec09485cbdbfa8a56512c32530 | /branches/Chickens/src/building/storage.h | ac4584fe42ca340bcdc0df10f60b5f0de55068b3 | [] | no_license | penghuz/main | c24ca5f2bf13b8cc1f483778e72ff6432577c83b | 26d9398309eeacbf24e3c5affbfb597be1cc8cd4 | refs/heads/master | 2020-04-22T15:59:50.432329 | 2017-11-23T10:30:22 | 2017-11-23T10:30:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,866 | h | /****************************************************************************\
$URL$
$LastChangedDate$
$LastChangedRevision$
$LastChangedBy$
\****************************************************************************/
//!Basic storage class
/*!Basic storage class. Should not be instanced except in inherited form.
* */
#ifndef __storage_H //Required for current class
#define __storage_H
#include "../base/linklist.h"
#include "../products/product.h" //Required for include files
#include "../products/products.h"
class storage: public base
{
//!The capacity of the storage in appropriate units
double theCapacity;
//!The product stored
product* theProduct;
public:
//!Constructor without arguments
storage ();// :();
//!Constructor with arguments
storage (const char* aname,const int aIndex,const base* aOwner,double aCapacity);
//!Copy constructor
storage(storage& aStore);
//!Destructor
~ storage ( ) //Destructor
{
delete theProduct;
}
// Get and set functions for attributes
//!Return the capacity of the store
double GetCapacity() const {return theCapacity;}
//!Set the capacity of the store
void SetCapacity (double aCapacity){ theCapacity = aCapacity;}
//!Return a pointer to the product stored
product * GetProductPointer() const {return theProduct;};
//!Set the pointer to the product stored
void SetProductPointer(product * aProduct) {theProduct = aProduct;};
//!Return amount of product stored in the appropriate units
double Getamountstored();
//!Return true if the stored product is the same as the desired product
/*!
* \param desiredProduct the product desired
* */
bool ProductCompare(const product* desiredProduct);
//!Add a product to the store
/*!
* \param p the product to add
* */
virtual void AddToStore(product * p);
//!Returns an amount of product from the store
/*!
* \param RequestedAmount the amount requested
* */
virtual product * GetFromStore(double RequestedAmount);
//!Returns the name of the stored product
string GiveNameStoredProduct();
//!Initialise storage details from a text file
void ReadParameters(fstream * file);
//!Returned a copy of a stored feed product
/*!
* \param feedType reference number of the feed product
* */
product* GetCopyStoredFeedProduct(int feedType);
//!Returned a copy of a stored feed product
/*!
* \param product1 the feed product to be copied
* */
product* GetCopyStoredFeedProduct(const product* product1);
//!Returned a pointer to the stored feed product
/*!
* \param feedType reference number of the feed product
* */
product* GetStoredFeedProductPtr(int feedType);
/*!Read default parameters
* \param file pointer to file containing default information
* */
void ReadDefaultParameters(fstream * file);
};
#endif
| [
"sai@agro.au.dk"
] | sai@agro.au.dk |
48907d779a89ed7c748a9d4ff41c98ed4f0ba65d | 60c275f5670d8a509421dbe53a704cdf85289035 | /CodeForces/1452B_Toy_Blocks/B_Toy_Blocks.cpp | e50ef640939c244363943ff72f0e25926d8cb409 | [
"MIT"
] | permissive | Cutyroach/Solve_Algorithms | f02f03c5ad146550b136e19292a3599b2eff6702 | 97d9f8bb65055fe5ad62d108a9359b91f0f40c49 | refs/heads/master | 2023-03-02T21:27:03.214056 | 2021-02-09T23:58:47 | 2021-02-09T23:58:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
// freopen("input.txt", "r", stdin);
ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
int t;
for (cin >> t; t--; ) {
int tc;
cin >> tc;
vector<long long> v(tc);
long long max_v = 0, sum = 0;
for (int i = 0; i < tc; i++) {
cin >> v[i];
sum += v[i];
max_v = max(max_v, v[i]);
}
long long ans = 0;
if (!(sum % (tc - 1))) ans = sum;
else ans = sum - sum % (tc - 1) + tc - 1;
if (ans < max_v * (tc - 1)) ans = max_v * (tc - 1);
cout << ans - sum << '\n';
}
return 0;
} | [
"spe0678@gmail.com"
] | spe0678@gmail.com |
e5d0a06a5f82cbd114f9c3bf94f4e206560eb637 | a11d6802ccb326a4fdcdd32cda309763f732e4d8 | /libs/agg23/include/agg_conv_unclose_polygon.h | a92fa45d096245bd3bd45e8f01bd67a398e3affc | [
"LicenseRef-scancode-boost-original"
] | permissive | martindafonte/eosim-fing2014 | f14ab03891e4e315a657c9f94f9dcb92b3c43557 | 9cb9fa777d91b1b90d0c7af4c942b68ab16593b9 | refs/heads/master | 2021-01-01T20:42:35.068696 | 2014-11-17T02:04:11 | 2014-11-17T02:04:11 | 42,748,038 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,757 | h | //----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.3
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
#ifndef AGG_CONV_UNCLOSE_POLYGON_INCLUDED
#define AGG_CONV_UNCLOSE_POLYGON_INCLUDED
#include "agg_basics.h"
namespace agg
{
//====================================================conv_unclose_polygon
template<class VertexSource> class conv_unclose_polygon
{
public:
conv_unclose_polygon(VertexSource& vs) : m_source(&vs) {}
void set_source(VertexSource& source) { m_source = &source; }
void rewind(unsigned path_id)
{
m_source->rewind(path_id);
}
unsigned vertex(double* x, double* y)
{
unsigned cmd = m_source->vertex(x, y);
if(is_end_poly(cmd)) cmd &= ~path_flags_close;
return cmd;
}
private:
conv_unclose_polygon(const conv_unclose_polygon<VertexSource>&);
const conv_unclose_polygon<VertexSource>&
operator = (const conv_unclose_polygon<VertexSource>&);
VertexSource* m_source;
};
}
#endif
| [
"martindafonte@gmail.com"
] | martindafonte@gmail.com |
ce1b5a66e31a227f43329fbd78b19bc8ceef6460 | b32200d629373216e32fb3423d7c8b3f1d28938d | /RetroSnaker_Colourso/RetroSnaker_0.3/贪吃蛇第三版/Snake.cpp | 431a0e706fec50625c671c5517b70eeecfb10bc0 | [] | no_license | Colourso/Simple-CPP-project-by-Colourso | 3a655cf238960ffad85e338ae63e3270e0fe7e0d | 36e22c6ec851bc695bd03c5939695e4afbbc0f39 | refs/heads/master | 2022-11-23T22:11:50.381102 | 2020-08-05T04:00:25 | 2020-08-05T04:00:25 | 268,247,781 | 1 | 1 | null | null | null | null | GB18030 | C++ | false | false | 4,176 | cpp | #include "Snake.h"
#include <stdio.h>
#include <ctime>
#include <graphics.h>
Snake::Snake()
{
Point pos0(210, 230);
Point pos1(190, 230);
Point pos2(170, 230);
this->m_snakelist.push_back(pos0);
this->m_snakelist.push_back(pos1);
this->m_snakelist.push_back(pos2);
this->m_direction = Dir::DIR_RIGHT;
this->m_len = 3;
this->m_speed = this->OrgSpeed;
}
int Snake::getLen()
{
return this->m_len;
}
int Snake::getSpeed()
{
return this->m_speed;
}
Dir Snake::getDirection()
{
return this->m_direction;
}
bool Snake::setSpeed(int speed)
{
if (speed > this->MaxSpeed)
{
if (this->m_speed != this->MaxSpeed)
{
this->m_speed = this->MaxSpeed;
return true;
}
return false;
}
else if (speed < this->MinSpeed)
{
if (this->m_speed != this->MinSpeed)
{
this->m_speed = this->MinSpeed;
return true;
}
return false;
}
else
{
this->m_speed = speed;
return true;
}
}
void Snake::Move()
{
this->m_tail = this->m_snakelist.back();
//移除最后一个节点,复制第一个节点两份
this->m_snakelist.pop_back();
Point headPos = this->m_snakelist.front();
this->m_snakelist.push_front(headPos);
switch (this->m_direction)
{
case Dir::DIR_UP:
this->m_snakelist.begin()->y -= SNAKE_WIDTH;
break;
case Dir::DIR_RIGHT:
this->m_snakelist.begin()->x += SNAKE_WIDTH;
break;
case Dir::DIR_DOWN:
this->m_snakelist.begin()->y += SNAKE_WIDTH;
break;
case Dir::DIR_LEFT:
this->m_snakelist.begin()->x -= SNAKE_WIDTH;
break;
}
}
void Snake::EatFood()
{
//吃到食物尾部增长
this->m_snakelist.push_back(this->m_tail);
this->m_len += 1;
}
void Snake::ChangeDir(Dir dir)
{
switch (dir)
{
case Dir::DIR_UP:
case Dir::DIR_DOWN:
if (m_direction != Dir::DIR_UP && m_direction != Dir::DIR_DOWN)
{
m_direction = dir;
}
break;
case Dir::DIR_RIGHT:
case Dir::DIR_LEFT:
if (m_direction != Dir::DIR_RIGHT && m_direction != Dir::DIR_LEFT)
{
m_direction = dir;
}
break;
}
}
void Snake::Dead()
{
//TODO
int x = 0;
int y = 0; //x、y表示坐标的该变量
int z = 0; //z表示改变方向
//使用随机函数
srand(time(0));
std::list<Point>::iterator it = this->m_snakelist.begin();
for (; it != this->m_snakelist.end(); ++it)
{
x = (rand() % 4) * SNAKE_WIDTH;
y = (rand() % 4) * SNAKE_WIDTH;
z = (rand() % 8);
switch (z)
{
case 0:
//右
(*it).x += x;
break;
case 1:
//下
(*it).y += y;
break;
case 2:
//左
(*it).x -= x;
break;
case 3:
//上
(*it).y -= y;
break;
case 4:
//右下
(*it).x += x;
(*it).y += y;
break;
case 5:
//左下
(*it).x -= x;
(*it).y += y;
break;
case 6:
//左上
(*it).x -= x;
(*it).y -= y;
break;
case 7:
//右上
(*it).x += x;
(*it).y -= y;
break;
}
}
}
bool Snake::ColideWall(int left, int top, int right, int bottom)
{
int x = this->m_snakelist.front().x;
int y = this->m_snakelist.front().y;
return (x < left || x > right || y < top || y > bottom);
}
bool Snake::ColideSnake()
{
if (m_len <= 3) return false;
std::list<Point>::iterator it = this->m_snakelist.begin();
Point pos = *it;
Point next_pos;
it++;
while(it != this->m_snakelist.end())
{
next_pos = *it;
if (pos == next_pos)
{
return true;
}
it++;
}
return false;
}
bool Snake::ColideFood(Point point)
{
if (this->m_snakelist.front() == point)
{
return true;
}
return false;
}
void Snake::DrawSnake()
{
std::list<Point>::iterator it = this->m_snakelist.begin();
for (; it != this->m_snakelist.end(); ++it)
{
DrawSnakeNode(*it);
}
DrawSnakeHead(this->m_snakelist.front());
}
void Snake::DrawSnakeHead(Point pos)
{
//紫色,全填充,无边框的正方形
setfillcolor(0xAA00AA);
setfillstyle(BS_SOLID);
solidrectangle(pos.x - SNAKE_RADIU, pos.y + SNAKE_RADIU, pos.x + SNAKE_RADIU, pos.y - SNAKE_RADIU);
}
void Snake::DrawSnakeNode(Point pos)
{
//绿色,全填充,无边框的正方形
setfillcolor(GREEN);
setfillstyle(BS_SOLID);
solidrectangle(pos.x - SNAKE_RADIU, pos.y + SNAKE_RADIU, pos.x + SNAKE_RADIU, pos.y - SNAKE_RADIU);
}
std::list<Point> Snake::GetSnakeAllNode()
{
return this->m_snakelist;
}
| [
"colourso@outlook.com"
] | colourso@outlook.com |
48b34cb562f9847543db971846a85f3646ff984d | 1e1b3f702bdf6c0544ae27a321c8ebe605434ee4 | /Chapter13/Sample304/UDPSever/StdAfx.cpp | 99b68b873f69041b2bf35eadaa8c10b1bcea4c53 | [] | no_license | Aque1228556367/Visual_Cpp_By_Example | 63e3d67e734b7d95385a329e4a1641e7b1727084 | 41f903d8c9938e7800d89fcff31b182bfc1c4f45 | refs/heads/master | 2021-03-12T20:36:56.780300 | 2015-05-08T02:05:46 | 2015-05-08T02:05:46 | 35,171,152 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 202 | cpp | // stdafx.cpp : source file that includes just the standard includes
// UDPSever.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"1228556367@qq.com"
] | 1228556367@qq.com |
c3c04ba93b620c5ee1a080a1be76fe09275e800f | 38616fa53a78f61d866ad4f2d3251ef471366229 | /3rdparty/RobustGNSS/gtsam/gtsam/3rdparty/GeographicLib/dotnet/examples/ManagedCPP/example-TransverseMercatorExact.cpp | 2f41fa616f3b1d2221448963adf5cf677c87da2e | [
"BSD-3-Clause",
"LGPL-2.1-only",
"MPL-2.0",
"LGPL-2.0-or-later",
"BSD-2-Clause",
"MIT"
] | permissive | wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation | 3b467fa6d3f34cabbd5ee59596ac1950aabf2522 | 2f1ff054b7c5059da80bb3b2f80c05861a02cc36 | refs/heads/master | 2020-06-08T12:42:31.977541 | 2019-06-10T15:04:33 | 2019-06-10T15:04:33 | 193,229,646 | 1 | 0 | MIT | 2019-06-22T12:07:29 | 2019-06-22T12:07:29 | null | UTF-8 | C++ | false | false | 940 | cpp | using namespace System;
using namespace NETGeographicLib;
int main(array<System::String ^> ^/*args*/)
{
try {
TransverseMercatorExact^ proj = gcnew TransverseMercatorExact(); // WGS84
double lon0 = -75; // Central meridian for UTM zone 18
{
// Sample forward calculation
double lat = 40.3, lon = -74.7; // Princeton, NJ
double x, y;
proj->Forward(lon0, lat, lon, x, y);
Console::WriteLine(String::Format("{0} {1}", x, y));
}
{
// Sample reverse calculation
double x = 25e3, y = 4461e3;
double lat, lon;
proj->Reverse(lon0, x, y, lat, lon);
Console::WriteLine(String::Format("{0} {1}", lat, lon));
}
}
catch (GeographicErr^ e) {
Console::WriteLine(String::Format("Caught exception: {0}", e->Message));
return -1;
}
return 0;
}
| [
"rwatso12@gmail.com"
] | rwatso12@gmail.com |
65c445a87703e13176476f3745d2004fb7ce7560 | 3624cb3da18011d62c2d4ddba35b26b1e9520e1f | /record.cpp | 4c212966baa46eeb4bca9fe95e82210b35a880da | [] | no_license | zRrrGet/qbook | 76841e67ab08c99e338071ce5e2c6868f0098f1b | 832f8c1a1e137473c5a6801274942bb217e7d7cf | refs/heads/master | 2023-03-21T10:49:33.381765 | 2021-03-12T11:26:00 | 2021-03-12T11:26:00 | 337,120,378 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 831 | cpp | #include "record.h"
Record::Record(QString name, int num, QDate date, QTime startTime, QTime endTime) : userName(name), num(num),
date(date), startTime(startTime), endTime(endTime)
{
}
QString Record::getUserName() const
{
return userName;
}
void Record::setUserName(const QString &value)
{
userName = value;
}
QDate Record::getDate() const
{
return date;
}
void Record::setDate(const QDate &value)
{
date = value;
}
int Record::getNum() const
{
return num;
}
void Record::setNum(int value)
{
num = value;
}
QTime Record::getStartTime() const
{
return startTime;
}
void Record::setStartTime(const QTime &value)
{
startTime = value;
}
QTime Record::getEndTime() const
{
return endTime;
}
void Record::setEndTime(const QTime &value)
{
endTime = value;
}
Record::Record() {
}
| [
"misha02.00@mail.ru"
] | misha02.00@mail.ru |
ea2bacf2e21728a4e0721f2e796d6df6b700b1e6 | 36cfac858d066576aa77a26e3040c4d4e66d0097 | /lab03/src/main.cpp | 05fe348326039ad32a697440afa1b630756ba3e9 | [] | no_license | Kotyarich/Algorithm-analysis | 3eff8a91c739a33e7a0cf58b36165c9de92f3957 | 4c8d72c0e6683e25af379f55ba86149c1f415cc4 | refs/heads/master | 2020-08-13T04:38:38.719464 | 2020-01-26T23:39:03 | 2020-01-26T23:39:03 | 214,907,280 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,190 | cpp | #include <functional>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <random>
#include "sorts.h"
using array = std::vector<double>;
double check_time(const std::function<void()> &f) {
int n = 5;
clock_t start = clock();
for (int i = 0; i < n; i++) {
f();
}
clock_t end = clock();
return static_cast<double >(end - start) / CLOCKS_PER_SEC / n;
}
void init_arrays(array &sorted, array &reversed, array &random) {
for (int i = 0; i < sorted.size(); i++) {
sorted[i] = i;
reversed[reversed.size() - 1 - i] = i;
random[i] = rand() % 2000 - 1000;
}
}
void check_sort_time(const array &s, const array &r, const array &random_arr) {
array sorted(s.size());
array reversed(r.size());
array randomised(random_arr.size());
auto run_check = [&](const std::string &sort_name, const std::function<void(array&)> &sort){
std::copy(s.begin(), s.end(), sorted.begin());
std::copy(r.begin(), r.end(), reversed.begin());
std::copy(random_arr.begin(), random_arr.end(), randomised.begin());
std::cout << sort_name << std::endl;
std::cout << "Sorted: " << std::fixed << std::setprecision(8)
<< check_time( [&](){ sort(sorted); }) << "s" << std::endl;
std::cout << "Reversed: " << std::fixed << std::setprecision(8)
<< check_time( [&](){ sort(reversed); }) << "s" << std::endl;
std::cout << "Randomised: " << std::fixed << std::setprecision(8)
<< check_time( [&](){ sort(randomised); }) << "s" << std::endl << std::endl;
};
run_check("Bubble", bubble_sort);
run_check("Insertion", insertion_sort);
run_check("Choice", choice_sort);
}
int main() {
srand(static_cast<unsigned int>(time(nullptr)));
std::vector<size_t> sizes{10, 50, 100, 500, 1000, 5000, 20000, 50000};
for (auto i: sizes) {
array sorted(i);
array reversed(i);
array random(i);
init_arrays(sorted, reversed, random);
std ::cout << "Number: " << i << std::endl;
check_sort_time(sorted, reversed, random);
std::cout << std::endl << std::endl;
}
} | [
"ndkotov@gmail.com"
] | ndkotov@gmail.com |
f392e806ea3cf53d469b3320dbea1fd8fa61d625 | db65b946860b5d6168f641bf49d177384410b61b | /src/colorChannel.h | 9b8e051f368da0bd8466304385f422717b38957f | [] | no_license | jhpoelen/ofPooks | eb63b3f2cd45b7c2d69aef3b3870a4276bf76590 | 2163da93fac5c415a0b5cabe9d8c166aedb74c46 | refs/heads/master | 2021-01-22T11:55:58.680795 | 2020-11-01T03:16:59 | 2020-11-01T03:16:59 | 3,616,835 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 255 | h | #pragma once
#include "ofMain.h"
const int MAX_COLORS = 8;
class ColorChannel {
public:
virtual ofColor nextColor();
virtual void loadColors();
virtual ofColor selectColor(int colorIndex);
private:
ofColor colors[MAX_COLORS];
}; | [
"jhpoelen@gmail.com"
] | jhpoelen@gmail.com |
475a6d9898821b03d48ee481270dd1e16251a38b | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/rsync/gumtree/rsync_patch_hunk_939.cpp | 6f0fdfd187017b4ac37a51e7e0af055c85d0c226 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 839 | cpp | * @return a socket which is attached to a subprocess running
* "prog". stdin and stdout are attached. stderr is left attached to
* the original stderr
**/
int sock_exec(const char *prog)
{
+ pid_t pid;
int fd[2];
if (socketpair_tcp(fd) != 0) {
rsyserr(FERROR, errno, "socketpair_tcp failed");
return -1;
}
if (verbose >= 2)
rprintf(FINFO, "Running socket program: \"%s\"\n", prog);
- if (fork() == 0) {
+
+ pid = fork();
+ if (pid < 0) {
+ rsyserr(FERROR, errno, "fork");
+ exit_cleanup(RERR_IPC);
+ }
+
+ if (pid == 0) {
close(fd[0]);
- close(0);
- close(1);
- dup(fd[1]);
- dup(fd[1]);
+ if (dup2(fd[1], STDIN_FILENO) < 0
+ || dup2(fd[1], STDOUT_FILENO) < 0) {
+ fprintf(stderr, "Failed to run \"%s\"\n", prog);
+ exit(1);
+ }
exit(system(prog));
}
+
close(fd[1]);
return fd[0];
}
| [
"993273596@qq.com"
] | 993273596@qq.com |
bb9eadca4492ac8a7313922886ed09db34579457 | b6607ecc11e389cc56ee4966293de9e2e0aca491 | /acm.kbtu.kz/KBTU OPEN/2014 Fall/E/copy.cpp | 52bab8f8ac9e4aec776f71e2bad3fa66131c910f | [] | no_license | BekzhanKassenov/olymp | ec31cefee36d2afe40eeead5c2c516f9bf92e66d | e3013095a4f88fb614abb8ac9ba532c5e955a32e | refs/heads/master | 2022-09-21T10:07:10.232514 | 2021-11-01T16:40:24 | 2021-11-01T16:40:24 | 39,900,971 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,971 | cpp | /****************************************
** Solution by NU #2 **
****************************************/
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
#define MP make_pair
#define all(x) (x).begin(), (x).end()
#define File "growingtree"
typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
const double EPS = 1e-9;
const double PI = acos(-1.0);
const int MOD = 1000 * 1000 * 1000 + 7;
const int INF = 2000 * 1000 * 1000;
template <typename T>
inline T sqr(T n) {
return n * n;
}
int n, k;
long long T;
void mul(long long a[3][3], long long b[3][3], long long c[3][3]) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
c[i][j] = 0;
for (int k = 0; k < 3; k++) {
c[i][j] += (a[i][k] * b[k][j]) % MOD;
c[i][j] %= MOD;
}
}
}
}
void cpy(long long dest[3][3], long long source[3][3]) {
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
dest[i][j] = source[i][j];
}
void binpow(long long a[3][3], long long p) {
long long result[3][3] = {{k, 0, 0},
{n, 1, (-1 + MOD)},
{k, 0, 0}};
long long temp[3][3];
while (p) {
if (p & 1) {
mul(result, a, temp);
cpy(result, temp);
}
mul(a, a, temp);
cpy(a, temp);
p >>= 1;
}
cpy(a, result);
}
int main() {
freopen(File".in", "r", stdin);
freopen(File".out", "w", stdout);
scanf("%d%d%I64d", &n, &k, &T);
long long a[3][3] = {{k, 0, 0},
{n, 1, (-1 + MOD)},
{k, 0, 0}};
binpow(a, T);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%11I64d", a[i][j]);
}
puts("");
}
printf("%I64d\n", a[1][0]);
return 0;
}
| [
"bekzhan.kassenov@nu.edu.kz"
] | bekzhan.kassenov@nu.edu.kz |
36cf3f31186671af260d124cf59cb08fcb5ef0ae | 2d01e812589588edcaeb7d8c1802f3ee7aa17909 | /GamePage/p2phash/seed.cpp | b0be8d3be88899ae4b78ab93af9fde9d412312d4 | [] | no_license | N2oBeef/vc_scan | 0c7b2e7f646e504aa4e14e2f53721ee8df7b6cf5 | e249381fd25ce1d63c10039cf27e0f5cfa5cf440 | refs/heads/master | 2020-12-29T00:25:38.652076 | 2016-04-13T22:22:44 | 2016-04-13T22:22:49 | 56,185,892 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 21,567 | cpp | /**************************************************************
* FileName : seed.cpp
* Description :
* Version : 1.0
* Author : chenmingxiang
* History : 1. 2009-11-17 Create this file.
**************************************************************/
#include "stdafx.h"
#include "seed.h"
#include <algorithm>
#include <iostream>
#include <string>
#include <time.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#if 1 // becode编码函数组
size_t bencode_begin_dict(FILE *fp)
{
return (EOF == fputc('d',fp)) ? 0 : 1;
}
size_t bencode_begin_list(FILE *fp)
{
return (EOF == fputc('l',fp)) ? 0 : 1;
}
size_t bencode_end_dict_list(FILE *fp)
{
return (EOF == fputc('e',fp)) ? 0 : 1;
}
size_t bencode_buf(const char *buf, size_t len, FILE *fp)
{
fprintf(fp, "%u:", (UINT32)len);
return fwrite(buf, len, 1, fp) == 1 ? 1 : 0;
}
size_t bencode_blk(const char *buf, size_t len, FILE *fp)
{
return fwrite(buf, len, 1, fp) == 1 ? 1 : 0;
}
size_t bencode_str(const char *str, FILE *fp)
{
return bencode_buf(str, strlen(str), fp);
}
size_t bencode_int(const int integer, FILE *fp)
{
if( EOF == fputc('i', fp)) return 0;
fprintf(fp, "%u", (UINT32)integer);
return (EOF == fputc('e', fp)) ? 0: 1;
}
size_t bencode_int64(const UINT64 integer, FILE *fp)
{
if( EOF == fputc('i', fp)) return 0;
fprintf(fp, "%lld", (UINT64)integer);
return (EOF == fputc('e', fp)) ? 0: 1;
}
#endif
/****************************************
* Function : WrapUnrecogChar
* Description : 转换字符串中的不可识别字符为'_'
* Parameters :
* Return : null
****************************************/
void WrapUnrecogChar(std::string& strpath)
{
std::replace(strpath.begin(),strpath.end(),'?' ,'_');
std::replace(strpath.begin(),strpath.end(),'/' ,'_');
std::replace(strpath.begin(),strpath.end(),'|' ,'_');
std::replace(strpath.begin(),strpath.end(),':' ,'_');
std::replace(strpath.begin(),strpath.end(),'*' ,'_');
std::replace(strpath.begin(),strpath.end(),'<' ,'_');
std::replace(strpath.begin(),strpath.end(),'>' ,'_');
std::replace(strpath.begin(),strpath.end(),'\\' ,'_');
std::replace(strpath.begin(),strpath.end(),'\"' ,'_');
std::replace(strpath.begin(),strpath.end(),'\'' ,'_');
}
/****************************************
* Function : CTORRENT::__initialize
* Description : 初始化成员变量(清空)
* Parameters : null
* Return : null
****************************************/
void CTORRENT::__initialize()
{
_m_single = true;
_m_pathlevel = 0;
_m_encoding = T_ENCODING_GBK;
_m_filenum = 0;
_m_filelength = 0;
_m_piecenum = 0;
_m_piecelength = 0;
_m_filename = "";
_m_tracker = "";
}
/****************************************
* Function : CTORRENT::__clearup
* Description : 释放成员变量
* Parameters : null
* Return : null
****************************************/
void CTORRENT::__clearup()
{
if(_m_vct_piece.size() > 0) _m_vct_piece.clear();
if(_m_vct_filelist.size() > 0) _m_vct_filelist.clear();
if(_m_vct_filesize.size() > 0) _m_vct_filesize.clear();
}
/****************************************
* Function : CTORRENT::__create
* Description : 从源文件创建种子文件属性
* Parameters : file - 源文件名
* filesz - 源文件大小
* Return : 成功 - true
* 失败 - false
****************************************/
bool CTORRENT::__create(const char* file, UINT64 filesz)
{
if(file == NULL) return false;
if(filesz == 0 )
{
printf("Error. file(%s) size zero\r\n", file);
return false; // 不处理大小为0的文件
}
_m_tracker = TORRENT_DEFAULT_TRACKER;
_m_filename = file;
_m_filenum = 1;
_m_single = true;
_m_filelength = filesz;
_m_vct_filelist.push_back(file);
_m_vct_filesize.push_back(filesz);
_m_piecelength = __calc_piecesize(_m_filelength);
__calc_hash(file);
_m_piecenum = _m_vct_piece.size();
return true;
}
/****************************************
* Function : CTORRENT::__create
* Description : 从源目录创建种子文件属性
* Parameters : dir - 源目录名
* vtrlist - 源目录下的文件名称列表
* vtrsize - 源目录下的文件大小列表
* Return : 成功 - true
* 失败 - false
****************************************/
bool CTORRENT::__create(const char* dir, VCTSTR& vtrlist, VCTINT64& vtrsize)
{
if(dir == NULL) return false;
_m_tracker = TORRENT_DEFAULT_TRACKER;
_m_filename = dir;
_m_filenum = 0;
_m_single = false;
VCTINT64::iterator it_size = vtrsize.begin();
VCTSTR::iterator it_list = vtrlist.begin();
while(it_size != vtrsize.end())
{
if(*it_size != 0) // 不处理大小为0的文件
{
_m_filenum++;
_m_filelength += *it_size;
_m_vct_filelist.push_back(*it_list);
_m_vct_filesize.push_back(*it_size);
}
it_size++;
it_list++;
}
if(_m_filelength == 0) return false; // 不处理大小为0的目录
_m_piecelength = __calc_piecesize(_m_filelength);
VCTSTR::iterator it = _m_vct_filelist.begin();
while(it != _m_vct_filelist.end())
{
__calc_hash((*it).c_str()); // 每个文件产生独立hash,不采用文件拼接
it++;
}
_m_piecenum = _m_vct_piece.size();
return true;
}
/****************************************
* Function : CTORRENT::__output
* Description : 根据属性,生成bencode格式的种子文件
* Parameters : trnfile - 种子文件名
* Return : 成功 - true
* 失败 - false
****************************************/
bool CTORRENT::__output(const char* trnfile)
{
FILE* fp = fopen(trnfile, "wb");
if(fp == NULL)
{
printf("Error! open trt file(%s) fail\r\n", trnfile);
return false;
}
bencode_begin_dict(fp); // Begin首字典序
//bencode_str("announce",fp); // Tracker Url
//bencode_str(_m_tracker.c_str(),fp);
bencode_str("encoding",fp); // 编码格式
bencode_str("GBK",fp);
bencode_str("creation date",fp); // 文件时间
time_t tm;
time(&tm);
bencode_str(ctime(&tm),fp);
bencode_str("info",fp); // Info信息(嵌套字典)
bencode_begin_dict(fp); // Info Begin字典序
bencode_str("name",fp); // 文件名
WrapUnrecogChar(_m_filename);
bencode_str(_m_filename.c_str(),fp);
if(_m_single)
{
bencode_str("length",fp); // 单文件长度
bencode_int64(_m_filelength,fp);
}
else
{
bencode_str("files",fp); // 多文件列表
bencode_begin_list(fp);
UINT32 idx;
VCTSTR::iterator it_list = _m_vct_filelist.begin();
VCTINT64::iterator it_size = _m_vct_filesize.begin();
for(idx = 0; idx < _m_filenum; idx++)
{
bencode_begin_dict(fp);
bencode_str("length", fp);
bencode_int64(*it_size, fp);
bencode_str("path", fp);
bencode_begin_list(fp);
WrapUnrecogChar(*it_list);
bencode_str((*it_list).c_str(), fp);
bencode_end_dict_list(fp);
bencode_end_dict_list(fp);
it_list++;
it_size++;
}
bencode_end_dict_list(fp);
}
bencode_str("piece length",fp); // 分片长度
bencode_int(_m_piecelength,fp);
bencode_str("pieces",fp); // 分片hash列表
char buf[256];
sprintf(buf, "%lu:", _m_vct_piece.size() * 20);
bencode_blk(buf, strlen(buf), fp);
VCTPIECE::iterator it = _m_vct_piece.begin();
while(it != _m_vct_piece.end())
{
bencode_blk((*it).hash, 20, fp);
it++;
}
bencode_end_dict_list(fp); // Info End字典序。
bencode_end_dict_list(fp); // End首字典序。
fclose(fp);
return true;
}
/****************************************
* Function : CTORRENT::__parse_dictionary
* Description :
* Parameters :
* Return :
****************************************/
char* CTORRENT::__parse_dictionary(const char* start)
{
UINT64 num;
char* buf = (char*)start;
if (*buf++ != 'd') return NULL;
while(*buf != 'e')
{
//嵌套字典
if (buf[0] == 'd'||buf[0] == 'l'||buf[0]=='i') return NULL;
std::string paraname;
std::string paravalue;
char* pcolon = buf;
while((*buf != ':') && (*buf!='e')) buf++;
if (*buf == 'e') return NULL; //结束
num = atoi(pcolon);
paraname.append(++buf, num);
buf += num;
if (buf[0] == 'd')
{
if((buf = __parse_dictionary(buf)) == NULL) return NULL;
}
else if(buf[0] == 'l')
{
if (paraname == "files") _m_single = false;
if (paraname == "path") _m_pathlevel++;
if((buf = __parse_list(buf)) == NULL) return NULL;
if (paraname == "path") _m_pathlevel--;
}
else if (buf[0] == 'i')//数值
{
num = atoi(++buf);
while( *buf != 'e' ) buf++;
buf++;
if (paraname == "piece length")
{
_m_piecelength = num;
}
if (paraname == "length")
{
if(_m_single)
{
_m_filelength = num;
_m_filenum = 1;
}
else
{
_m_filelength += num;
_m_filenum++;
_m_vct_filesize.push_back(num);
}
}
}
else
{
pcolon = buf;
while(*buf != ':' && *buf!='e') buf++;
if (*buf == 'e') return NULL; //结束
num = atoi(pcolon);
paravalue.append(++buf, num);
buf += num;
if (paraname == "pieces")
{
if ((_m_piecenum = num/20) == 0) return NULL;
}
if (paraname == "announce")
{
_m_tracker = paravalue;
}
if (paraname == "name")
{
_m_filename = paravalue;
}
if (paraname == "encoding")
{
if(paravalue == "GBK") _m_encoding = T_ENCODING_GBK;
else if(paravalue == "UTF-8") _m_encoding = T_ENCODING_UTF8;
else _m_encoding = T_ENCODING_BUTT;
}
}
}
return ++buf;
}
/****************************************
* Function : CTORRENT::__parse_list
* Description :
* Parameters :
* Return :
****************************************/
char* CTORRENT::__parse_list(const char* start)
{
char* buf = (char*)start;
if(*buf++ != 'l') return NULL;
bool _b_multi_path = false;
std::string path;
while(*buf != 'e')
{
if(*buf == 'l')
{
buf = __parse_list(buf);
if(!buf) return NULL;
}
else if(*buf == 'd')
{
buf = __parse_dictionary(buf);
if(!buf) return NULL;
}
else if(*buf == 'i')
{
while(*buf!= 'e') buf++;
buf++;
}
else
{
char* pcolon = buf;
while(*buf != ':' && *buf!= 'e') buf++;
if (*buf == 'e') return NULL; //结束
UINT32 num = atoi(pcolon);
buf++;
if(_m_pathlevel > 0)
{
if(_b_multi_path) path += '\\';
path.append(buf, num);
_b_multi_path = true;
}
buf += num;
}
}
if(_m_pathlevel > 0) _m_vct_filelist.push_back(path);
return ++buf;
}
/****************************************
* Function : CTORRENT::__calc_hash
* Description : 根据文件,初始化成员变量
* Parameters : file - 源文件名
* Return : 成功 - true
* 失败 - false
****************************************/
bool CTORRENT::__calc_hash(const char* file)
{
FILE* fp = fopen(file, "rb");
if(fp == NULL) return false;
char readbuf[512*1024]; // piece最大为512KB
while(1)
{
Piece piece;
UINT32 size = fread(readbuf, 1, _m_piecelength, fp);
if(size == 0) break;
//CSha1 sha(readbuf, size);
//sha.read(piece.hash);
hash_function::CSha1::HashBuffer(readbuf, size, (BYTE *)&piece);
_m_vct_piece.push_back(piece);
}
fclose(fp);
return true;
}
/****************************************
* Function : CTORRENT::__calc_piecesize
* Description : 根据文件大小计算分片长度
* 文件大小 分片长度
* ---------- ----------
* 0 - 4194303 16384
* 4194304-16777215 32768
* 16777216-67108863 65536
* 67108864-268435455 131072
* 268435456-1073741823 262144
* 1073741824-4G 524288
* 4G -- 524288
* ---------- ----------
* Parameters : filesz - 文件大小
* Return : 分片长度
****************************************/
UINT32 CTORRENT::__calc_piecesize(UINT64 filesz)
{
if (filesz <= 2 * 1024 * 1024) return 16 * 1024;
if (filesz >= (UINT64)4 * 1024 * 1024 * 1024) return 512 * 1024;
float f = sqrt( (float)filesz/4096);
unsigned short n = (unsigned short)f;
int i = 3;
while(n && i < 16)
{
if( n & (0x8000>>i)) return (0x8000 >> i) * 1024;
i++;
}
return 16 * 1024;
}
/****************************************
* Function : CTORRENT::__get_filesz
* Description : 计算文件大小
* Parameters : file - 文件名
* Return : 文件大小(Bytes)
****************************************/
UINT64 CTORRENT::__calc_filesize(const char* file)
{
struct _stati64 sb;
if(_stati64(file, &sb) != 0) return 0;
return sb.st_size;
}
/****************************************
* Function : CTORRENT::ShowTorrentInfo
* Description : 显示种子文件信息
* Parameters : null
* Return : null
****************************************/
void CTORRENT::ShowTorrentInfo()
{
printf("------------ global info ------------\r\n");
if(_m_single) printf("file name : %s \r\ntracker list: %s\r\n", _m_filename.c_str(), _m_tracker.c_str());
else printf("directory : %s \r\ntracker list: %s\r\n", _m_filename.c_str(), _m_tracker.c_str());
printf("total length: %u KB\r\ntotal number: %u\r\n", (int)(_m_filelength/1024), _m_filenum);
printf("piece length: %u KB\r\npiece number: %u\r\n", _m_piecelength/1024, _m_piecenum);
if(!_m_single)
{
printf("------------ detail info ------------\r\n");
VCTSTR::iterator it_list = _m_vct_filelist.begin();
VCTINT64::iterator it_size = _m_vct_filesize.begin();
for(UINT32 idx = 0; idx < _m_filenum; idx++, it_list++, it_size++)
{
UINT32 size = *it_size;
if(size > 4096) printf("[%03d] file length: %u KB\r\n", idx + 1, size/1024);
else printf("[%03d] file length: %u B\r\n", idx + 1, size);
switch(_m_encoding)
{
case T_ENCODING_GBK:
printf(" file name : %s\r\n", (*it_list).c_str());
break;
default:
break;
}
}
}
}
/****************************************
* Function : CTORRENT::LoadTorrentFromFile
* Description : 解析.torrent种子文件
* Parameters : trnfile - 种子文件名
* Return : 成功 - true
* 失败 - false
****************************************/
bool CTORRENT::LoadTorrent(const char* trnfile)
{
if(trnfile == NULL) return false;
FILE* fp = fopen(trnfile, "rb");
if(fp == NULL) return false;
char buf[TORRENT_MAX_SIZE];
int totallen = fread(buf, sizeof(char), TORRENT_MAX_SIZE, fp);
fclose(fp);
if((totallen <= 0) || (totallen >= TORRENT_MAX_SIZE)) return false;
return LoadTorrent(buf, totallen);
}
/****************************************
* Function : CTORRENT::LoadTorrentFromBuffer
* Description : 解析.torrent种子文件
* Parameters : buffer - torrent文件内容
* length - torrent文件长度
* Return : 成功 - true
* 失败 - false
****************************************/
bool CTORRENT::LoadTorrent(const char* buffer, UINT32 length)
{
if(buffer == NULL) return false;
if(length == 0) return false;
if((buffer[0] != 'd') || (buffer[length - 1] != 'e')) return false;
return __parse_dictionary(buffer) == NULL ? false : true;
}
/****************************************
* Function : CTORRENT::CreateTorrent
* Description : 制作.torrent种子文件
* Parameters : srcfile - 源文件名
* Return : 成功 - true
* 失败 - false
****************************************/
bool CTORRENT::CreateTorrent(const char* srcfile, const char* optdir)
{
if(srcfile == NULL) return false;
if(optdir == NULL) return false;
if(strlen(optdir) == 0) return false;
if(__create(srcfile, __calc_filesize(srcfile)) != true) return false;
char* pbuf = (char*)malloc(_m_piecenum * SHA1_HASH_SIZE);
memset(pbuf, 0, _m_piecenum * SHA1_HASH_SIZE);
char* pcur = pbuf;
VCTPIECE::iterator it = _m_vct_piece.begin();
while(it != _m_vct_piece.end())
{
memcpy(pcur, (*it).hash, SHA1_HASH_SIZE);
pcur += SHA1_HASH_SIZE;
it++;
}
char hash[SHA1_HASH_SIZE];
//CSha1 sha(pbuf, _m_piecenum * SHA1_HASH_SIZE);
// sha.read(hash);
hash_function::CSha1::HashBuffer(pbuf, _m_piecenum * SHA1_HASH_SIZE, (BYTE *)&hash);
free(pbuf);
std::string str = optdir;
if(optdir[strlen(optdir) - 1] != '\\') str += '\\';
for(UINT32 idx = 0; idx < SHA1_HASH_SIZE; idx++)
{
char code[16];
sprintf(code, "%02X", (UINT8)hash[idx]);
str += code;
}
str += ".trt"; // 文件后缀trt
bool _i_res = __output(str.c_str());
if(_i_res == true) printf("%s\r\n", strrchr(str.c_str(), '\\') + 1);
return _i_res;
}
/****************************************
* Function : CTORRENT::CreateTorrent
* Description : 制作.torrent种子文件
* Parameters : srcfile - 源文件名
trnfile - 种子文件名
* Return : 成功 - true
* 失败 - false
****************************************/
bool CTORRENT::CreateTorrent(const char* srcdir, VCTSTR& vtrlist, VCTINT64& vtrsize, const char* optdir)
{
if(srcdir == NULL) return false;
VCTINT64::iterator it_size = vtrsize.begin();
VCTSTR::iterator it_list = vtrlist.begin();
while(it_size != vtrsize.end())
{
if(*it_size != 0) // 不处理大小为0的文件
{
__clearup();
__initialize();
if(CreateTorrent((*it_list).c_str(), optdir) != true) return false;
}
it_size++;
it_list++;
}
return true;
}
/****************************************
* Function : CTORRENT::CalcTorrent
* Description : 显示文件Hash值
* Parameters : srcfile - 源文件名
* Return : 成功 - true
* 失败 - false
****************************************/
bool CTORRENT::CalcTorrentHash(const char* srcfile)
{
if(srcfile == NULL) return false;
if(__create(srcfile, __calc_filesize(srcfile)) != true) return false;
char* pbuf = (char*)malloc(_m_piecenum * SHA1_HASH_SIZE);
memset(pbuf, 0, _m_piecenum * SHA1_HASH_SIZE);
char* pcur = pbuf;
VCTPIECE::iterator it = _m_vct_piece.begin();
while(it != _m_vct_piece.end())
{
memcpy(pcur, (*it).hash, SHA1_HASH_SIZE);
pcur += SHA1_HASH_SIZE;
it++;
}
char hash[SHA1_HASH_SIZE];
//CSha1 sha(pbuf, _m_piecenum * SHA1_HASH_SIZE);
//sha.read(hash);
hash_function::CSha1::HashBuffer(pbuf, _m_piecenum * SHA1_HASH_SIZE, (BYTE *)&hash);
free(pbuf);
std::string str = "";
for(UINT32 idx = 0; idx < SHA1_HASH_SIZE; idx++)
{
char code[16];
sprintf(code, "%02X", (UINT8)hash[idx]);
str += code;
}
printf("%s\r\n", str.c_str());
return true;
}
| [
"460955584@qq.com"
] | 460955584@qq.com |
7d2f25de0cc6fe25e05f63269e71fa0b7c4b70ae | 92793f5f381d7b85be8e101d1fb68f3e0e4c17b0 | /example/testApp.cpp | de5d3ce1d71256c0e16bcfdb3a005ae4511f152e | [] | no_license | martinbabbels/ofxOMCS | b81c935eaf69ae325615d895c6760bb471b68728 | 5578a42c98e14855acf5c972b63f273bd3783287 | refs/heads/master | 2020-04-19T15:48:56.605805 | 2011-12-26T11:56:02 | 2011-12-26T11:56:02 | 2,077,631 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,993 | cpp | #include "testApp.h"
//--------------------------------------------------------------
void testApp::setup(){
ofSetFrameRate(60);
// Load the predicates
omcsnet.loadPredicates(ofToDataPath("predicates.dat"));
}
//--------------------------------------------------------------
void testApp::update(){
}
//--------------------------------------------------------------
void testApp::draw(){
}
//--------------------------------------------------------------
void testApp::keyPressed(int key){
}
//--------------------------------------------------------------
void testApp::keyReleased(int key){
// Analogous concepts
if(key=='a') {
string concept = "apollo";
list<AnalogousResult> r;
list<AnalogousResult>::iterator result_iterator;
list<AnalogousConcept> c;
list<AnalogousConcept>::iterator concepts_iterator;
omcsnet.findAnalogous(concept, r);
printf("*************************************************\n");
printf("Analogous concepts for %s\n", concept.c_str());
printf("*************************************************\n");
result_iterator = r.begin();
while(result_iterator != r.end()) {
printf("%s (%s%%) because both:\n",
(*result_iterator).concept.c_str(),
ofToString((int)(*result_iterator).score).c_str()
);
concepts_iterator = (*result_iterator).concepts.begin();
while(concepts_iterator != (*result_iterator).concepts.end()) {
printf("\t%s %s\n",
(*concepts_iterator).relation.c_str(),
(*concepts_iterator).concept.c_str()
);
++concepts_iterator;
}
printf("\n\n");
++result_iterator;
}
}
// Path cocept A to B
if(key=='p') {
string concept_a = "freak";
string concept_b = "day";
printf("*************************************************\n");
printf("Path from %s to %s\n", concept_a.c_str(), concept_b.c_str());
printf("*************************************************\n");
list<PathResults> r;
list<PathResults>::iterator result_iterator;
list<PathResult>::iterator path_iterator;
omcsnet.findPath(concept_a, concept_b, r);
result_iterator = r.begin();
while (result_iterator != r.end()) {
printf("\n");
path_iterator = (*result_iterator).paths.begin();
while(path_iterator != (*result_iterator).paths.end()) {
printf("%s is %s %s\n",
(*path_iterator).conceptA.c_str(),
(*path_iterator).relation.c_str(),
(*path_iterator).conceptB.c_str()
);
++path_iterator;
}
++result_iterator;
}
}
// Context concepts
if(key=='c') {
string concept = "framework";
printf("*************************************************\n");
printf("Context for %s\n", concept.c_str());
printf("*************************************************\n");
list<ContextResult> r;
list<ContextResult>::iterator result_iterator;
omcsnet.findContext(concept, r);
result_iterator = r.begin();
while(result_iterator != r.end()) {
printf("%s (%s%%)\n",
(*result_iterator).concept.c_str(),
ofToString((*result_iterator).score).c_str()
);
++result_iterator;
}
}
// Look up a concept
if(key=='l') {
string concept = "computer";
printf("*************************************************\n");
printf("Lookup concept %s\n", concept.c_str());
printf("*************************************************\n");
LookUpResult r;
list<LookUpResultLinks>::iterator result_iterator;
list<LookUpResultLink>::iterator concepts_iterator;
omcsnet.lookUp(concept, r);
printf("Forward:\n");
result_iterator = r.forward.begin();
while(result_iterator != r.forward.end()) {
printf("[%s]\n", (*result_iterator).relation.c_str());
concepts_iterator = (*result_iterator).concepts.begin();
while(concepts_iterator != (*result_iterator).concepts.end()) {
printf("\t%s\n",
(*concepts_iterator).concept.c_str()
);
++concepts_iterator;
}
++result_iterator;
}
printf("Backward:\n");
result_iterator = r.backward.begin();
while(result_iterator != r.backward.end()) {
printf("[%s]\n", (*result_iterator).relation.c_str());
concepts_iterator = (*result_iterator).concepts.begin();
while(concepts_iterator != (*result_iterator).concepts.end()) {
printf("\t%s\n",
(*concepts_iterator).concept.c_str()
);
++concepts_iterator;
}
++result_iterator;
}
}
}
//--------------------------------------------------------------
void testApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void testApp::windowResized(int w, int h){
} | [
"martin@apollomedia.nl"
] | martin@apollomedia.nl |
9159ae0cce2025921a4f32141fdc20870172a76a | 81302ee42c1b3c25ce1566d70a782ab5525c7892 | /daq/TDC/TDC Software/xerawdp-0.3.3_alpha04_test_tdc/src/XmlConfig.cpp | a9096f978cdadf4eedc3bf385570dc66bdcc3925 | [] | no_license | mdanthony17/neriX | 5dd8ce673cd340888d3d5e4d992f7296702c6407 | 2c4ddbb0b64e7ca54f30333ba4fb8f601bbcc32e | refs/heads/master | 2020-04-04T06:01:25.200835 | 2018-06-05T00:37:08 | 2018-06-05T00:46:11 | 49,095,961 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 54,611 | cpp | #include "XmlConfig.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <algorithm>
#include <libxml++/libxml++.h>
using std::string;
using std::stringstream;
using std::ostringstream;
using std::vector;
using std::map;
using std::cout;
using std::endl;
using std::ifstream;
using std::min;
using std::max;
using std::getline;
XmlConfig::XmlConfig()
{
// default values
m_hConfigFileContents = "";
m_iProcessingLevel = 0;
m_iUseTDC = 0;
m_iFirstTopPmt = -1;
m_iFirstBottomPmt = -1;
m_iFirstTopVetoPmt = -1;
m_iFirstBottomVetoPmt = -1;
m_iFirstUnusedChannel = -1;
m_iLastTopPmt = -1;
m_iLastBottomPmt = -1;
m_iLastTopVetoPmt = -1;
m_iLastBottomVetoPmt = -1;
m_iLastUnusedChannel = -1;
m_fExternalGainTopPmts = 10.;
m_fExternalGainBottomPmts = 10.;
m_fExternalGainVetoPmts = 10.;
#ifdef ENABLE_LIQ_SCI
m_iFirstLiqSciChannel = -1;
m_iLastLiqSciChannel = -1;
m_iLiqSciMultiplexingStart = -1;
#endif
#ifdef ENABLE_NAI
m_iFirstNaiChannel = -1;
m_iLastNaiChannel = -1;
#endif
#ifdef ENABLE_HPGE
m_iFirstGeChannel = -1;
m_iLastGeChannel = -1;
#endif
#ifdef ENABLE_TAC
m_iFirstTacChannel = -1;
m_iLastTacChannel = -1;
#endif
m_iSingleNbBaselineSamples = -1;
m_iSingleWindowStart = -1;
m_iSingleWindowWidth = -1;
m_iSinglePrePeakSamples = -1;
m_iSinglePostPeakSamples = -1;
m_bUseMaxPmtAlgorithm = false;
m_bUseSvmAlgorithm = false;
m_bUseNnAlgorithm = false;
m_bUseChi2Algorithm = false;
m_bCorrectForS1SpatialDependence = false;
m_bCorrectForS2AxialDependence = false;
m_fElectronLifetime = -1.;
}
XmlConfig::~XmlConfig()
{
}
bool
XmlConfig::readConfigFile(const string &hConfigFileName)
{
ifstream hConfigFile(hConfigFileName.c_str(), std::ios::binary);
ostringstream hStream(std::ios::binary);
hStream << hConfigFile.rdbuf();
m_hConfigFileContents = hStream.str();
hConfigFile.close();
xmlpp::DomParser hXmlParser;
hXmlParser.parse_memory(m_hConfigFileContents);
const xmlpp::Node* pRootNode = hXmlParser.get_document()->get_root_node();
readGlobalSettings(pRootNode);
if(!readPmtSettings(pRootNode))
return false;
readTriggerEfficiencySettings(pRootNode);
#ifdef ENABLE_LIQ_SCI
if(!readLiqSciSettings(pRootNode))
return false;
#endif
#ifdef ENABLE_NAI
readNaiSettings(pRootNode);
#endif
#ifdef ENABLE_HPGE
readGeSettings(pRootNode);
#endif
#ifdef ENABLE_TAC
readTacSettings(pRootNode);
#endif
readSinglePhotoelectronSettings(pRootNode);
readRawDataSettings(pRootNode);
readPeakFindingSettings(pRootNode);
readSignalsSettings(pRootNode);
readPositionReconstructionSettings(pRootNode);
if(!readSignalCorrectionsSettings(pRootNode))
return false;
return true;
}
void
XmlConfig::printSettings()
{
// print everything
cout
<< " XmlConfig" << endl
<< " Global" << endl
<< " DatasetNameFormat: " << m_hDatasetNameFormat << endl
<< " RawDataDir: " << m_hRawDataDir << endl
<< " ProcessedDataDir: " << m_hProcessedDataDir << endl
<< " MergedDataDir: " << m_hMergedDataDir << endl
<< " ProcessingLevel: " << m_iProcessingLevel << endl
<< " Pmts" << endl
<< " TopPmts: " << m_hTopPmts << endl
<< " BottomPmts: " << m_hBottomPmts << endl
<< " TopVetoPmts: " << m_hTopVetoPmts << endl
<< " BottomVetoPmts: " << m_hBottomVetoPmts << endl
<< " UnusedChannels: " << m_hUnusedChannels << endl;
if(m_hExternalGains.size())
{
cout
<< " ExternalGains: " << m_hExternalGains << endl;
}
else
{
cout
<< " ExternalGain " << endl
<< " TopPmts: " << m_fExternalGainTopPmts << endl
<< " BottomPmts: " << m_fExternalGainBottomPmts << endl
<< " VetoPmts: " << m_fExternalGainVetoPmts << endl;
}
if(m_iProcessingLevel == 0)
{
cout
<< " SinglePhotoelectron:" << endl
<< " NbBaselineSamples: " << m_iSingleNbBaselineSamples << endl
<< " WindowStart: " << m_iSingleWindowStart << endl
<< " WindowWidth: " << m_iSingleWindowWidth << endl
<< " PrePeakSamples: " << m_iSinglePrePeakSamples << endl
<< " PostPeakSamples: " << m_iSinglePostPeakSamples << endl;
}
if(m_iProcessingLevel > 0)
{
cout
<< " CalibrationSource: " << m_hPmtCalibrationSource << endl;
cout
<< " TriggerEfficiency" << endl
<< " NbTriggerSignals: " << m_iNbTriggerSignals << endl
<< " Channels: " << m_hTriggerEfficiencyChannels << endl
<< " TriggerWindowStart: " << m_iTriggerWindowStart << endl
<< " TriggerWindowWidth: " << m_iTriggerWindowWidth << endl
<< " TriggerSignalHeightThreshold: " << m_fTriggerSignalHeightThreshold << endl;
#ifdef ENABLE_LIQ_SCI
cout
<< " LiquidScintillators" << endl
<< " NbLiquidScintillators: " << m_iNbLiqScis << endl
<< " Channels: " << m_hLiqSciChannels << endl
<< " TailStart: " << m_iLiqSciTailStart << endl
<< " Multiplexed: " << m_bLiqSciMultiplexed << endl;
if(m_bLiqSciMultiplexed)
{
cout
<< " MultiplexingStart: " << m_iLiqSciMultiplexingStart << endl
<< " MultiplexingWindows: " << m_hLiqSciMultiplexingWindows << endl
<< " MultiplexingSignalHeightThreshold: " << m_fLiqSciMultiplexingSignalHeightThreshold << endl
<< " MultiplexingSignalWidthThreshold: " << m_iLiqSciMultiplexingSignalWidthThreshold << endl;
}
#endif
#ifdef ENABLE_NAI
cout
<< " SodiumIodideDetectors" << endl
<< " NbSodiumIodideDetectors: " << m_iNbNaiDetectors << endl
<< " Channels: " << m_hNaiChannels << endl;
#endif
#ifdef ENABLE_HPGE
cout
<< " GermaniumDetectors" << endl
<< " NbGermaniumDetectors: " << m_iNbGeDetectors << endl
<< " Channels: " << m_hGeChannels << endl;
#endif
#ifdef ENABLE_TAC
cout
<< " TimeToAmplitudeConverters" << endl
<< " NbTimeToAmplitudeConverters: " << m_iNbTacs << endl
<< " Channels: " << m_hTacChannels << endl
<< " WindowStart: " << m_iTacWindowStart << endl
<< " WindowWidth: " << m_iTacWindowWidth << endl
<< " Calibration: " << m_hTacCalibration << endl;
#endif
cout
<< " RawData" << endl
<< " NbBaselineSamples: " << m_iNbBaselineSamples << endl
<< " PeakFinding" << endl
<< " S1: " << endl
<< " ExcludedPmts: " << m_hS1PeakFindingExcludedPmts << endl;
if(m_bS1Filter)
{
cout
<< " Filter: " << endl
<< " Type: " << m_hS1FilterType << endl;
if(m_hS1FilterType == "RaisedCosine")
{
cout
<< " LowPass: " << m_bS1RaisedCosineLowPass << endl
<< " Limit: " << m_fS1RaisedCosineLimit << endl
<< " RollOff: " << m_fS1RaisedCosineRollOff << endl
<< " Length: " << m_iS1RaisedCosineLength << endl;
}
else if(m_hS1FilterType == "Custom")
{
cout
<< " Coefficients: " << m_hS1CustomFilterCoefficientList << endl;
}
}
cout
<< " MaxNbPeaks: " << m_iS1MaxNbPeaks << endl
<< " RightLimitHeightThreshold: " << m_fS1RightLimitHeightThreshold << endl
<< " SignalThreshold: " << m_fS1SignalThreshold << endl
<< " PeakWindow: " << m_iS1PeakWindow << endl
<< " PrePeakSamples: " << m_iS1PrePeakSamples << endl
<< " MaxLength: " << m_iS1MaxLength << endl
<< " PrePeakAvgWindow: " << m_iS1PrePeakAvgWindow << endl
<< " PostPeakAvgWindow: " << m_iS1PostPeakAvgWindow << endl
<< " PrePeakAvgThreshold: " << m_fS1PrePeakAvgThreshold << endl
<< " PostPeakAvgThreshold: " << m_fS1PostPeakAvgThreshold << endl
<< " FilteredWidthThreshold: " << m_fS1FilteredWidthThreshold << endl
<< " NegativeExcursionFractionThreshold: " << m_fS1NegativeExcursionFractionThreshold << endl
<< " HeightFractionThreshold: " << m_fS1HeightFractionThreshold << endl
<< " SamplesBelowThreshold: " << m_iS1SamplesBelowThreshold << endl;
cout
<< " S2" << endl
<< " ExcludedPmts: " << m_hS2PeakFindingExcludedPmts << endl
<< " MaxNbPeaks: " << m_iS2MaxNbPeaks << endl;
cout
<< " LargePeaks" << endl;
if(m_bS2LargePeakFilter)
{
cout
<< " Filter" << endl
<< " Type: " << m_hS2LargePeakFilterType << endl;
if(m_hS2LargePeakFilterType == "RaisedCosine")
{
cout
<< " LowPass: " << m_bS2LargePeakRaisedCosineLowPass << endl
<< " Limit: " << m_fS2LargePeakRaisedCosineLimit << endl
<< " RollOff: " << m_fS2LargePeakRaisedCosineRollOff << endl
<< " Length: " << m_iS2LargePeakRaisedCosineLength << endl;
}
}
cout
<< " SignalThreshold: " << m_fS2LargePeakSignalThreshold << endl
<< " DynamicFractionSignalThreshold: " << m_fS2LargePeakDynamicFractionSignalThreshold << endl
<< " MinWidth: " << m_iS2LargePeakMinWidth << endl
<< " MinIntervalWidth: " << m_iS2LargePeakMinIntervalWidth << endl
<< " PreIntervalAvgWindow: " << m_iS2LargePeakPreIntervalAvgWindow << endl
<< " PostIntervalAvgWindow: " << m_iS2LargePeakPostIntervalAvgWindow << endl
<< " PreTopLevelIntervalAvgThreshold: " << m_fS2LargePeakPreTopLevelIntervalAvgThreshold << endl
<< " PostTopLevelIntervalAvgThreshold: " << m_fS2LargePeakPostTopLevelIntervalAvgThreshold << endl
<< " PreIntervalAvgThreshold: " << m_fS2LargePeakPreIntervalAvgThreshold << endl
<< " PostIntervalAvgThreshold: " << m_fS2LargePeakPostIntervalAvgThreshold << endl
<< " OverlappingPeaksThreshold: " << m_fS2LargePeakOverlappingPeaksThreshold << endl
<< " LeftHeightFractionThreshold: " << m_fS2LargePeakLeftHeightFractionThreshold << endl
<< " RightHeightFractionThreshold: " << m_fS2LargePeakRightHeightFractionThreshold << endl
<< " LargePeakSlopeThreshold: " << m_fS2LargePeakSlopeThreshold << endl
<< " SmallPeakSlopeThreshold: " << m_fS2SmallPeakSlopeThreshold << endl
<< " SmallPeakThreshold: " << m_fS2SmallPeakThreshold << endl;
cout
<< " TinyPeaks" << endl;
if(m_bS2TinyPeakFilter)
{
cout
<< " Filter" << endl
<< " Type: " << m_hS2TinyPeakFilterType << endl;
if(m_hS2TinyPeakFilterType == "RaisedCosine")
{
cout
<< " LowPass: " << m_bS2TinyPeakRaisedCosineLowPass << endl
<< " Limit: " << m_fS2TinyPeakRaisedCosineLimit << endl
<< " RollOff: " << m_fS2TinyPeakRaisedCosineRollOff << endl
<< " Length: " << m_iS2TinyPeakRaisedCosineLength << endl;
}
else if(m_hS2TinyPeakFilterType == "Custom")
{
cout
<< " Coefficients: " << m_hS2TinyPeakCustomFilterCoefficientList << endl;
}
}
cout
<< " RightLimitHeightThreshold: " << m_fS2TinyPeakRightLimitHeightThreshold << endl
<< " SignalThreshold: " << m_fS2TinyPeakSignalThreshold << endl
<< " MinIntervalWidth: " << m_iS2TinyPeakMinIntervalWidth << endl
<< " MaxIntervalWidth: " << m_iS2TinyPeakMaxIntervalWidth << endl
<< " PrePeakAvgWindow: " << m_iS2TinyPeakPrePeakAvgWindow << endl
<< " PostPeakAvgWindow: " << m_iS2TinyPeakPostPeakAvgWindow << endl
<< " PrePeakAvgThreshold: " << m_fS2TinyPeakPrePeakAvgThreshold << endl
<< " PostPeakAvgThreshold: " << m_fS2TinyPeakPostPeakAvgThreshold << endl
<< " AspectRatioThreshold: " << m_fS2TinyPeakAspectRatioThreshold << endl
<< " HeightFractionThreshold: " << m_fS2TinyPeakHeightFractionThreshold << endl;
cout
<< " Signals" << endl
<< " SignalThreshold: " << m_fSignalThreshold << endl
<< " SaturationThreshold: " << m_fSaturationThreshold << endl
<< " S1" << endl
<< " CoincidenceExcludedPmts: " << m_hS1CoincidenceExcludedPmts << endl
<< " TotalSignalExcludedPmts: " << m_hS1TotalSignalExcludedPmts << endl
<< " CoincidenceWindow: " << m_iS1CoincidenceWindow << endl
<< " S2" << endl
<< " CoincidenceExcludedPmts: " << m_hS2CoincidenceExcludedPmts << endl
<< " TotalSignalExcludedPmts: " << m_hS2TotalSignalExcludedPmts << endl
<< " CoincidenceWindow: " << m_iS2CoincidenceWindow << endl;
cout
<< " PositionReconstruction " << endl
<< " RelativeEfficiencies: " << m_hRelativeEfficiencies << endl;
if(m_bUseMaxPmtAlgorithm)
{
cout
<< " MaxPmt: " << endl;
}
if(m_bUseSvmAlgorithm)
{
cout
<< " Svm: " << endl
<< " RModelFileName: " << m_hSvmRModelFileName << endl
<< " XModelFileName: " << m_hSvmXModelFileName << endl
<< " YModelFileName: " << m_hSvmYModelFileName << endl;
}
if(m_bUseNnAlgorithm)
{
cout
<< " Nn: " << endl
<< " XYModelName: " << m_hNnXYModelName << endl;
}
if(m_bUseChi2Algorithm)
{
cout
<< " Chi2: " << endl
<< " LceMapFileName: " << m_hChi2LceMapFileName << endl;
}
if(m_bUseFannAlgorithm)
{
cout
<< " Fann: " << endl
<< " XYModelFileName: " << m_hFannXYModelFileName << endl;
}
cout
<< " SignalCorrections " << endl;
if(m_bCorrectForS1SpatialDependence)
{
cout
<< " S1: " << endl
<< " SpatialCorrection: " << endl;
}
if(m_bCorrectForS2AxialDependence)
{
cout
<< " S2: " << endl
<< " AxialCorrection: " << endl
<< " ElectronLifetime: " << m_fElectronLifetime << endl;
}
}
}
bool
XmlConfig::readGlobalSettings(const xmlpp::Node* pRootNode)
{
stringstream hStream;
// get global settings
const xmlpp::NodeSet hGlobalNodeSet = pRootNode->find("/xerawdp/global/*");
for(int i = 0; i < (int) hGlobalNodeSet.size(); i++)
{
string hName = hGlobalNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hGlobalNodeSet[i]->get_children().front())->get_content());
if(hName == "verbosity")
hStream >> m_iVerbosity;
else if(hName == "dataset_name_format")
m_hDatasetNameFormat = hStream.str();
else if(hName == "raw_data_dir")
m_hRawDataDir = hStream.str();
else if(hName == "processed_data_dir")
m_hProcessedDataDir = hStream.str();
else if(hName == "merged_data_dir")
m_hMergedDataDir = hStream.str();
else if(hName == "processing_level")
hStream >> m_iProcessingLevel;
else if(hName == "use_tdc")
hStream >> m_iUseTDC;
hStream.clear();
}
}
bool
XmlConfig::readSinglePhotoelectronSettings(const xmlpp::Node* pRootNode)
{
stringstream hStream;
// get global settings
const xmlpp::NodeSet hSinglePhotoelectronNodeSet = pRootNode->find("/xerawdp/single_photoelectron/*");
for(int i = 0; i < (int) hSinglePhotoelectronNodeSet.size(); i++)
{
string hName = hSinglePhotoelectronNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hSinglePhotoelectronNodeSet[i]->get_children().front())->get_content());
if(hName == "nb_baseline_samples")
hStream >> m_iSingleNbBaselineSamples;
else if(hName == "window_start")
hStream >> m_iSingleWindowStart;
else if(hName == "window_width")
hStream >> m_iSingleWindowWidth;
else if(hName == "pre_peak_samples")
hStream >> m_iSinglePrePeakSamples;
else if(hName == "post_peak_samples")
hStream >> m_iSinglePostPeakSamples;
hStream.clear();
}
}
bool
XmlConfig::readPmtSettings(const xmlpp::Node* pRootNode)
{
stringstream hStream;
// get pmt number settings
const xmlpp::NodeSet hPmtsNodeSet = pRootNode->find("/xerawdp/pmts/*");
for(int i = 0; i < (int) hPmtsNodeSet.size(); i++)
{
string hName = hPmtsNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hPmtsNodeSet[i]->get_children().front())->get_content());
if(hName == "top_pmts")
{
m_hTopPmts = hStream.str();
parsePmtString(m_hTopPmts, m_iFirstTopPmt, m_iLastTopPmt);
}
else if(hName == "bottom_pmts")
{
m_hBottomPmts = hStream.str();
parsePmtString(m_hBottomPmts, m_iFirstBottomPmt, m_iLastBottomPmt);
}
else if(hName == "top_veto_pmts")
{
m_hTopVetoPmts = hStream.str();
parsePmtString(m_hTopVetoPmts, m_iFirstTopVetoPmt, m_iLastTopVetoPmt);
}
else if(hName == "bottom_veto_pmts")
{
m_hBottomVetoPmts = hStream.str();
parsePmtString(m_hBottomVetoPmts, m_iFirstBottomVetoPmt, m_iLastBottomVetoPmt);
}
else if(hName == "unused_channels")
{
m_hUnusedChannels = hStream.str();
parsePmtString(m_hUnusedChannels, m_iFirstUnusedChannel, m_iLastUnusedChannel);
}
hStream.clear();
}
// get pmt external gains settings
const xmlpp::NodeSet hPmtExternalGainsNodeSet = pRootNode->find("/xerawdp/pmts/*");
for(int i = 0; i < (int) hPmtExternalGainsNodeSet.size(); i++)
{
string hName = hPmtExternalGainsNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hPmtExternalGainsNodeSet[i]->get_children().front())->get_content());
if(hName == "external_gains")
{
m_hExternalGains = hStream.str();
parsePmtExternalGainsString(m_hExternalGains, m_hExternalGainsTable);
}
hStream.clear();
}
// get pmt external gain settings
const xmlpp::NodeSet hPmtExternalGainNodeSet = pRootNode->find("/xerawdp/pmts/external_gain/*");
for(int i = 0; i < (int) hPmtExternalGainNodeSet.size(); i++)
{
string hName = hPmtExternalGainNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hPmtExternalGainNodeSet[i]->get_children().front())->get_content());
if(hName == "top_pmts")
hStream >> m_fExternalGainTopPmts;
else if(hName == "bottom_pmts")
hStream >> m_fExternalGainBottomPmts;
else if(hName == "veto_pmts")
hStream >> m_fExternalGainVetoPmts;
hStream.clear();
}
// fill the external gains table if it is empty
if(!m_hExternalGainsTable.size())
{
for(int iPmt = m_iFirstTopPmt; iPmt <= m_iLastTopPmt; iPmt++)
m_hExternalGainsTable[iPmt] = m_fExternalGainTopPmts;
for(int iPmt = m_iFirstBottomPmt; iPmt <= m_iLastBottomPmt; iPmt++)
m_hExternalGainsTable[iPmt] = m_fExternalGainBottomPmts;
for(int iPmt = m_iFirstTopVetoPmt; iPmt <= m_iLastTopVetoPmt; iPmt++)
m_hExternalGainsTable[iPmt] = m_fExternalGainVetoPmts;
for(int iPmt = m_iFirstBottomVetoPmt; iPmt <= m_iLastBottomVetoPmt; iPmt++)
m_hExternalGainsTable[iPmt] = m_fExternalGainVetoPmts;
}
// get pmt calibration source settings
const xmlpp::NodeSet hPmtCalibrationSourceNodeSet = pRootNode->find("/xerawdp/pmts/calibration_source/*");
for(int i = 0; i < (int) hPmtCalibrationSourceNodeSet.size(); i++)
{
string hName = hPmtCalibrationSourceNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hPmtCalibrationSourceNodeSet[i]->get_children().front())->get_content());
if(hName == "file")
{
m_hPmtCalibrationSource = "file";
m_hPmtCalibrationFileName = hStream.str();
}
else if(hName == "here")
m_hPmtCalibrationSource = "here";
else if(hName == "database")
m_hPmtCalibrationSource = "database";
hStream.clear();
}
// get pmt calibration source here settings
const xmlpp::NodeSet hPmtHereNodeSet = pRootNode->find("/xerawdp/pmts/calibration_source/here/*");
for(int i = 0; i < (int) hPmtHereNodeSet.size(); i++)
{
string hName = hPmtHereNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hPmtHereNodeSet[i]->get_children().front())->get_content());
if(hName == "header")
m_hPmtCalibrationHeader = hStream.str();
else if(hName == "values")
m_hPmtCalibrationValues = hStream.str();
hStream.clear();
}
// get pmt calibration source database settings
const xmlpp::NodeSet hPmtDatabaseNodeSet = pRootNode->find("/xerawdp/pmts/calibration_source/database/*");
for(int i = 0; i < (int) hPmtDatabaseNodeSet.size(); i++)
{
string hName = hPmtDatabaseNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hPmtDatabaseNodeSet[i]->get_children().front())->get_content());
if(hName == "files")
m_hPmtCalibrationFiles = hStream.str();
else if(hName == "header")
m_hPmtCalibrationHeader = hStream.str();
else if(hName == "values")
m_hPmtCalibrationValues = hStream.str();
hStream.clear();
}
if(!fillPmtCalibrationTable())
return false;
else
return true;
}
bool
XmlConfig::readTriggerEfficiencySettings(const xmlpp::Node* pRootNode)
{
stringstream hStream;
// get trigger efficiency settings
const xmlpp::NodeSet hTriggerEfficiencyNodeSet = pRootNode->find("/xerawdp/trigger_efficiency/*");
for(int i = 0; i < (int) hTriggerEfficiencyNodeSet.size(); i++)
{
string hName = hTriggerEfficiencyNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hTriggerEfficiencyNodeSet[i]->get_children().front())->get_content());
if(hName == "nb_trigger_signals")
hStream >> m_iNbTriggerSignals;
else if(hName == "channels")
{
m_hTriggerEfficiencyChannels = hStream.str();
parsePmtString(m_hTriggerEfficiencyChannels, m_iFirstTriggerEfficiencyChannel, m_iLastTriggerEfficiencyChannel);
}
else if(hName == "trigger_window_start")
hStream >> m_iTriggerWindowStart;
else if(hName == "trigger_window_width")
hStream >> m_iTriggerWindowWidth;
else if(hName == "trigger_signal_height_threshold")
hStream >> m_fTriggerSignalHeightThreshold;
hStream.clear();
}
}
#ifdef ENABLE_LIQ_SCI
bool
XmlConfig::readLiqSciSettings(const xmlpp::Node* pRootNode)
{
stringstream hStream;
// get liquid scintillator settings
const xmlpp::NodeSet hLiquidScintillatorsNodeSet = pRootNode->find("/xerawdp/liquid_scintillators/*");
for(int i = 0; i < (int) hLiquidScintillatorsNodeSet.size(); i++)
{
string hName = hLiquidScintillatorsNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hLiquidScintillatorsNodeSet[i]->get_children().front())->get_content());
if(hName == "nb_liquid_scintillators")
hStream >> m_iNbLiqScis;
else if(hName == "channels")
{
m_hLiqSciChannels = hStream.str();
parsePmtString(m_hLiqSciChannels, m_iFirstLiqSciChannel, m_iLastLiqSciChannel);
}
else if(hName == "tail_start")
hStream >> m_iLiqSciTailStart;
else if(hName == "multiplexed")
hStream >> m_bLiqSciMultiplexed;
else if(hName == "multiplexing_start")
hStream >> m_iLiqSciMultiplexingStart;
else if(hName == "multiplexing_windows")
{
m_hLiqSciMultiplexingWindows = hStream.str();
parseLiqSciMultiplexingWindowsString(m_hLiqSciMultiplexingWindows, m_hLiqSciMultiplexingTable);
}
else if(hName == "multiplexing_signal_height_threshold")
hStream >> m_fLiqSciMultiplexingSignalHeightThreshold;
else if(hName == "multiplexing_signal_width_threshold")
hStream >> m_iLiqSciMultiplexingSignalWidthThreshold;
hStream.clear();
}
// verify liquid scintillator mutliplexing table
return verifyLiqSciMultiplexingTable();
}
#endif
#ifdef ENABLE_NAI
bool
XmlConfig::readNaiSettings(const xmlpp::Node* pRootNode)
{
stringstream hStream;
// get sodium iodide detector settings
const xmlpp::NodeSet hNaiNodeSet = pRootNode->find("/xerawdp/sodium_iodide_detectors/*");
for(int i = 0; i < (int) hNaiNodeSet.size(); i++)
{
string hName = hNaiNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hNaiNodeSet[i]->get_children().front())->get_content());
if(hName == "nb_sodium_iodide_detectors")
hStream >> m_iNbNaiDetectors;
else if(hName == "channels")
{
m_hNaiChannels = hStream.str();
parsePmtString(m_hNaiChannels, m_iFirstNaiChannel, m_iLastNaiChannel);
}
hStream.clear();
}
}
#endif
#ifdef ENABLE_HPGE
bool
XmlConfig::readGeSettings(const xmlpp::Node* pRootNode)
{
stringstream hStream;
// get germanium detector settings
const xmlpp::NodeSet hGeNodeSet = pRootNode->find("/xerawdp/germanium_detectors/*");
for(int i = 0; i < (int) hGeNodeSet.size(); i++)
{
string hName = hGeNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hGeNodeSet[i]->get_children().front())->get_content());
if(hName == "nb_germanium_detectors")
hStream >> m_iNbGeDetectors;
else if(hName == "channels")
{
m_hGeChannels = hStream.str();
parsePmtString(m_hGeChannels, m_iFirstGeChannel, m_iLastGeChannel);
}
hStream.clear();
}
}
#endif
#ifdef ENABLE_TAC
bool
XmlConfig::readTacSettings(const xmlpp::Node* pRootNode)
{
stringstream hStream;
// get tac settings
const xmlpp::NodeSet hTimeToAmplitudeConvertersNodeSet = pRootNode->find("/xerawdp/time_to_amplitude_converters/*");
for(int i = 0; i < (int) hTimeToAmplitudeConvertersNodeSet.size(); i++)
{
string hName = hTimeToAmplitudeConvertersNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hTimeToAmplitudeConvertersNodeSet[i]->get_children().front())->get_content());
if(hName == "nb_time_to_amplitude_converters")
hStream >> m_iNbTacs;
else if(hName == "channels")
{
m_hTacChannels = hStream.str();
parsePmtString(m_hTacChannels, m_iFirstTacChannel, m_iLastTacChannel);
}
else if(hName == "window_start")
hStream >> m_iTacWindowStart;
else if(hName == "window_width")
hStream >> m_iTacWindowWidth;
else if(hName == "calibration")
{
m_hTacCalibration = hStream.str();
parseTacCalibrationString(m_hTacCalibration, m_hTacCalibrationTable);
}
hStream.clear();
}
}
#endif
bool
XmlConfig::readRawDataSettings(const xmlpp::Node* pRootNode)
{
stringstream hStream;
// get raw data settings
const xmlpp::NodeSet hRawDataNodeSet = pRootNode->find("/xerawdp/raw_data/*");
for(int i = 0; i < (int) hRawDataNodeSet.size(); i++)
{
string hName = hRawDataNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hRawDataNodeSet[i]->get_children().front())->get_content());
if(hName == "nb_baseline_samples")
hStream >> m_iNbBaselineSamples;
hStream.clear();
}
return true;
}
bool
XmlConfig::readPeakFindingSettings(const xmlpp::Node* pRootNode)
{
stringstream hStream;
// get s1 peak finding raised cosine filter settings
const xmlpp::NodeSet hS1RaisedCosineNodeSet = pRootNode->find("/xerawdp/peak_finding/s1/filter/raised_cosine/*");
if(hS1RaisedCosineNodeSet.size())
{
m_bS1Filter = true;
m_hS1FilterType = "RaisedCosine";
}
for(int i = 0; i < (int) hS1RaisedCosineNodeSet.size(); i++)
{
string hName = hS1RaisedCosineNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hS1RaisedCosineNodeSet[i]->get_children().front())->get_content());
if(hName == "low_pass")
hStream >> m_bS1RaisedCosineLowPass;
else if(hName == "limit")
hStream >> m_fS1RaisedCosineLimit;
else if(hName == "roll_off")
hStream >> m_fS1RaisedCosineRollOff;
else if(hName == "length")
hStream >> m_iS1RaisedCosineLength;
hStream.clear();
}
// get s1 custom filter settings
const xmlpp::NodeSet hS1CustomFilterNodeSet = pRootNode->find("/xerawdp/peak_finding/s1/filter/custom/*");
if(hS1CustomFilterNodeSet.size())
{
m_bS1Filter = true;
m_hS1FilterType = "Custom";
}
for(int i = 0; i < (int) hS1CustomFilterNodeSet.size(); i++)
{
string hName = hS1CustomFilterNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hS1CustomFilterNodeSet[i]->get_children().front())->get_content());
if(hName == "coefficients")
{
m_hS1CustomFilterCoefficientList = hStream.str();
parseValueList(m_hS1CustomFilterCoefficientList, m_hS1CustomFilterCoefficients);
}
hStream.clear();
}
// get s1 peak finding settings
const xmlpp::NodeSet hS1NodeSet = pRootNode->find("/xerawdp/peak_finding/s1/*");
for(int i = 0; i < (int) hS1NodeSet.size(); i++)
{
string hName = hS1NodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hS1NodeSet[i]->get_children().front())->get_content());
if(hName == "excluded_pmts")
{
m_hS1PeakFindingExcludedPmts = hStream.str();
parsePmtEnumerationString(m_hS1PeakFindingExcludedPmts, m_hS1PeakFindingExcludedPmtSet);
}
else if(hName == "max_nb_peaks")
hStream >> m_iS1MaxNbPeaks;
else if(hName == "right_limit_height_threshold")
hStream >> m_fS1RightLimitHeightThreshold;
else if(hName == "signal_threshold")
hStream >> m_fS1SignalThreshold;
else if(hName == "peak_window")
hStream >> m_iS1PeakWindow;
else if(hName == "pre_peak_samples")
hStream >> m_iS1PrePeakSamples;
else if(hName == "max_length")
hStream >> m_iS1MaxLength;
else if(hName == "pre_peak_avg_window")
hStream >> m_iS1PrePeakAvgWindow;
else if(hName == "post_peak_avg_window")
hStream >> m_iS1PostPeakAvgWindow;
else if(hName == "pre_peak_avg_threshold")
hStream >> m_fS1PrePeakAvgThreshold;
else if(hName == "post_peak_avg_threshold")
hStream >> m_fS1PostPeakAvgThreshold;
else if(hName == "filtered_width_threshold")
hStream >> m_fS1FilteredWidthThreshold;
else if(hName == "negative_excursion_fraction_threshold")
hStream >> m_fS1NegativeExcursionFractionThreshold;
else if(hName == "height_fraction_threshold")
hStream >> m_fS1HeightFractionThreshold;
else if(hName == "samples_below_threshold")
hStream >> m_iS1SamplesBelowThreshold;
else if(hName == "coincidence_threshold")
hStream >> m_fS1CoincidenceThreshold;
hStream.clear();
}
// get s2 peak finding settings
const xmlpp::NodeSet hS2NodeSet = pRootNode->find("/xerawdp/peak_finding/s2/*");
for(int i = 0; i < (int) hS2NodeSet.size(); i++)
{
string hName = hS2NodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hS2NodeSet[i]->get_children().front())->get_content());
if(hName == "excluded_pmts")
{
m_hS2PeakFindingExcludedPmts = hStream.str();
parsePmtEnumerationString(m_hS2PeakFindingExcludedPmts, m_hS2PeakFindingExcludedPmtSet);
}
else if(hName == "max_nb_peaks")
hStream >> m_iS2MaxNbPeaks;
hStream.clear();
}
// get s2 large peak raised cosine filter settings
const xmlpp::NodeSet hS2LargePeakRaisedCosineNodeSet = pRootNode->find("/xerawdp/peak_finding/s2/large_peaks/filter/raised_cosine/*");
if(hS2LargePeakRaisedCosineNodeSet.size())
{
m_bS2LargePeakFilter = true;
m_hS2LargePeakFilterType = "RaisedCosine";
}
for(int i = 0; i < (int) hS2LargePeakRaisedCosineNodeSet.size(); i++)
{
string hName = hS2LargePeakRaisedCosineNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hS2LargePeakRaisedCosineNodeSet[i]->get_children().front())->get_content());
if(hName == "low_pass")
hStream >> m_bS2LargePeakRaisedCosineLowPass;
else if(hName == "limit")
hStream >> m_fS2LargePeakRaisedCosineLimit;
else if(hName == "roll_off")
hStream >> m_fS2LargePeakRaisedCosineRollOff;
else if(hName == "length")
hStream >> m_iS2LargePeakRaisedCosineLength;
hStream.clear();
}
// get s2 large peak settings
const xmlpp::NodeSet hS2LargePeaksNodeSet = pRootNode->find("/xerawdp/peak_finding/s2/large_peaks/*");
for(int i = 0; i < (int) hS2LargePeaksNodeSet.size(); i++)
{
string hName = hS2LargePeaksNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hS2LargePeaksNodeSet[i]->get_children().front())->get_content());
if(hName == "signal_threshold")
hStream >> m_fS2LargePeakSignalThreshold;
else if(hName == "dynamic_fraction_signal_threshold")
hStream >> m_fS2LargePeakDynamicFractionSignalThreshold;
else if(hName == "min_width")
hStream >> m_iS2LargePeakMinWidth;
else if(hName == "min_interval_width")
hStream >> m_iS2LargePeakMinIntervalWidth;
else if(hName == "pre_interval_avg_window")
hStream >> m_iS2LargePeakPreIntervalAvgWindow;
else if(hName == "post_interval_avg_window")
hStream >> m_iS2LargePeakPostIntervalAvgWindow;
else if(hName == "pre_top_level_interval_avg_threshold")
hStream >> m_fS2LargePeakPreTopLevelIntervalAvgThreshold;
else if(hName == "post_top_level_interval_avg_threshold")
hStream >> m_fS2LargePeakPostTopLevelIntervalAvgThreshold;
else if(hName == "pre_interval_avg_threshold")
hStream >> m_fS2LargePeakPreIntervalAvgThreshold;
else if(hName == "post_interval_avg_threshold")
hStream >> m_fS2LargePeakPostIntervalAvgThreshold;
else if(hName == "overlapping_peaks_threshold")
hStream >> m_fS2LargePeakOverlappingPeaksThreshold;
else if(hName == "left_height_fraction_threshold")
hStream >> m_fS2LargePeakLeftHeightFractionThreshold;
else if(hName == "right_height_fraction_threshold")
hStream >> m_fS2LargePeakRightHeightFractionThreshold;
else if(hName == "large_peak_slope_threshold")
hStream >> m_fS2LargePeakSlopeThreshold;
else if(hName == "small_peak_slope_threshold")
hStream >> m_fS2SmallPeakSlopeThreshold;
else if(hName == "small_peak_threshold")
hStream >> m_fS2SmallPeakThreshold;
hStream.clear();
}
// get s2 tiny peak raised cosine filter settings
const xmlpp::NodeSet hS2TinyPeakRaisedCosineNodeSet = pRootNode->find("/xerawdp/peak_finding/s2/tiny_peaks/filter/raised_cosine/*");
if(hS2TinyPeakRaisedCosineNodeSet.size())
{
m_bS2TinyPeakFilter = true;
m_hS2TinyPeakFilterType = "RaisedCosine";
}
for(int i = 0; i < (int) hS2TinyPeakRaisedCosineNodeSet.size(); i++)
{
string hName = hS2TinyPeakRaisedCosineNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hS2TinyPeakRaisedCosineNodeSet[i]->get_children().front())->get_content());
if(hName == "low_pass")
hStream >> m_bS2TinyPeakRaisedCosineLowPass;
else if(hName == "limit")
hStream >> m_fS2TinyPeakRaisedCosineLimit;
else if(hName == "roll_off")
hStream >> m_fS2TinyPeakRaisedCosineRollOff;
else if(hName == "length")
hStream >> m_iS2TinyPeakRaisedCosineLength;
hStream.clear();
}
// get s2 tiny peak custom filter settings
const xmlpp::NodeSet hS2TinyPeakCustomFilterNodeSet = pRootNode->find("/xerawdp/peak_finding/s2/tiny_peaks/filter/custom/*");
if(hS2TinyPeakCustomFilterNodeSet.size())
{
m_bS2TinyPeakFilter = true;
m_hS2TinyPeakFilterType = "Custom";
}
for(int i = 0; i < (int) hS2TinyPeakCustomFilterNodeSet.size(); i++)
{
string hName = hS2TinyPeakCustomFilterNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hS2TinyPeakCustomFilterNodeSet[i]->get_children().front())->get_content());
if(hName == "coefficients")
{
m_hS2TinyPeakCustomFilterCoefficientList = hStream.str();
parseValueList(m_hS2TinyPeakCustomFilterCoefficientList, m_hS2TinyPeakCustomFilterCoefficients);
}
hStream.clear();
}
// get s2 tiny peak settings
const xmlpp::NodeSet hS2TinyPeaksNodeSet = pRootNode->find("/xerawdp/peak_finding/s2/tiny_peaks/*");
for(int i = 0; i < (int) hS2TinyPeaksNodeSet.size(); i++)
{
string hName = hS2TinyPeaksNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hS2TinyPeaksNodeSet[i]->get_children().front())->get_content());
if(hName == "right_limit_height_threshold")
hStream >> m_fS2TinyPeakRightLimitHeightThreshold;
else if(hName == "signal_threshold")
hStream >> m_fS2TinyPeakSignalThreshold;
else if(hName == "min_interval_width")
hStream >> m_iS2TinyPeakMinIntervalWidth;
else if(hName == "max_interval_width")
hStream >> m_iS2TinyPeakMaxIntervalWidth;
else if(hName == "pre_peak_avg_window")
hStream >> m_iS2TinyPeakPrePeakAvgWindow;
else if(hName == "post_peak_avg_window")
hStream >> m_iS2TinyPeakPostPeakAvgWindow;
else if(hName == "pre_peak_avg_threshold")
hStream >> m_fS2TinyPeakPrePeakAvgThreshold;
else if(hName == "post_peak_avg_threshold")
hStream >> m_fS2TinyPeakPostPeakAvgThreshold;
else if(hName == "aspect_ratio_threshold")
hStream >> m_fS2TinyPeakAspectRatioThreshold;
else if(hName == "height_fraction_threshold")
hStream >> m_fS2TinyPeakHeightFractionThreshold;
hStream.clear();
}
return true;
}
bool
XmlConfig::readSignalsSettings(const xmlpp::Node* pRootNode)
{
stringstream hStream;
// get signals settings
const xmlpp::NodeSet hSignalsNodeSet = pRootNode->find("/xerawdp/signals/*");
for(int i = 0; i < (int) hSignalsNodeSet.size(); i++)
{
string hName = hSignalsNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hSignalsNodeSet[i]->get_children().front())->get_content());
if(hName == "signal_threshold")
hStream >> m_fSignalThreshold;
else if(hName == "saturation_threshold")
hStream >> m_fSaturationThreshold;
hStream.clear();
}
// get s1 signals settings
const xmlpp::NodeSet hS1SignalsNodeSet = pRootNode->find("/xerawdp/signals/s1/*");
for(int i = 0; i < (int) hS1SignalsNodeSet.size(); i++)
{
string hName = hS1SignalsNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hS1SignalsNodeSet[i]->get_children().front())->get_content());
if(hName == "coincidence_excluded_pmts")
{
m_hS1CoincidenceExcludedPmts = hStream.str();
parsePmtEnumerationString(m_hS1CoincidenceExcludedPmts, m_hS1CoincidenceExcludedPmtSet);
}
else if(hName == "total_signal_excluded_pmts")
{
m_hS1TotalSignalExcludedPmts = hStream.str();
parsePmtEnumerationString(m_hS1TotalSignalExcludedPmts, m_hS1TotalSignalExcludedPmtSet);
}
else if(hName == "coincidence_window")
hStream >> m_iS1CoincidenceWindow;
hStream.clear();
}
// get s2 signals settings
const xmlpp::NodeSet hS2SignalsNodeSet = pRootNode->find("/xerawdp/signals/s2/*");
for(int i = 0; i < (int) hS2SignalsNodeSet.size(); i++)
{
string hName = hS2SignalsNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hS2SignalsNodeSet[i]->get_children().front())->get_content());
if(hName == "coincidence_excluded_pmts")
{
m_hS2CoincidenceExcludedPmts = hStream.str();
parsePmtEnumerationString(m_hS2CoincidenceExcludedPmts, m_hS2CoincidenceExcludedPmtSet);
}
else if(hName == "total_signal_excluded_pmts")
{
m_hS2TotalSignalExcludedPmts = hStream.str();
parsePmtEnumerationString(m_hS2TotalSignalExcludedPmts, m_hS2TotalSignalExcludedPmtSet);
}
else if(hName == "coincidence_window")
hStream >> m_iS2CoincidenceWindow;
hStream.clear();
}
}
bool
XmlConfig::readPositionReconstructionSettings(const xmlpp::Node* pRootNode)
{
stringstream hStream;
// get position reconstruction settings
const xmlpp::NodeSet hPositionReconstructionNodeSet = pRootNode->find("/xerawdp/position_reconstruction/*");
for(int i = 0; i < (int) hPositionReconstructionNodeSet.size(); i++)
{
string hName = hPositionReconstructionNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hPositionReconstructionNodeSet[i]->get_children().front())->get_content());
if(hName == "relative_efficiencies")
{
m_hRelativeEfficiencies = hStream.str();
parseRelativeEfficienciesString(m_hRelativeEfficiencies, m_hRelativeEfficienciesTable);
}
hStream.clear();
}
// get max pmt algorithm settings
const xmlpp::NodeSet hMaxPmtAlgorithmNodeSet = pRootNode->find("/xerawdp/position_reconstruction/max_pmt/*");
for(int i = 0; i < (int) hMaxPmtAlgorithmNodeSet.size(); i++)
{
string hName = hMaxPmtAlgorithmNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hMaxPmtAlgorithmNodeSet[i]->get_children().front())->get_content());
if(hName == "use_algorithm")
hStream >> m_bUseMaxPmtAlgorithm;
hStream.clear();
}
// get svm algorithm settings
const xmlpp::NodeSet hSvmAlgorithmNodeSet = pRootNode->find("/xerawdp/position_reconstruction/svm/*");
for(int i = 0; i < (int) hSvmAlgorithmNodeSet.size(); i++)
{
string hName = hSvmAlgorithmNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hSvmAlgorithmNodeSet[i]->get_children().front())->get_content());
if(hName == "use_algorithm")
hStream >> m_bUseSvmAlgorithm;
else if(hName == "r_model_file_name")
m_hSvmRModelFileName = hStream.str();
else if(hName == "x_model_file_name")
m_hSvmXModelFileName = hStream.str();
else if(hName == "y_model_file_name")
m_hSvmYModelFileName = hStream.str();
hStream.clear();
}
// get neural network algorithm settings
const xmlpp::NodeSet hNnAlgorithmNodeSet = pRootNode->find("/xerawdp/position_reconstruction/nn/*");
for(int i = 0; i < (int) hNnAlgorithmNodeSet.size(); i++)
{
string hName = hNnAlgorithmNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hNnAlgorithmNodeSet[i]->get_children().front())->get_content());
if(hName == "use_algorithm")
hStream >> m_bUseNnAlgorithm;
else if(hName == "xy_model_name")
m_hNnXYModelName = hStream.str();
hStream.clear();
}
// get chi^2 algorithm settings
const xmlpp::NodeSet hChi2AlgorithmNodeSet = pRootNode->find("/xerawdp/position_reconstruction/chi2/*");
for(int i = 0; i < (int) hChi2AlgorithmNodeSet.size(); i++)
{
string hName = hChi2AlgorithmNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hChi2AlgorithmNodeSet[i]->get_children().front())->get_content());
if(hName == "use_algorithm")
hStream >> m_bUseChi2Algorithm;
else if(hName == "lce_map_file_name")
m_hChi2LceMapFileName = hStream.str();
hStream.clear();
}
// get fann algorithm settings
const xmlpp::NodeSet hFannAlgorithmNodeSet = pRootNode->find("/xerawdp/position_reconstruction/fann/*");
for(int i = 0; i < (int) hFannAlgorithmNodeSet.size(); i++)
{
string hName = hFannAlgorithmNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hFannAlgorithmNodeSet[i]->get_children().front())->get_content());
if(hName == "use_algorithm")
hStream >> m_bUseFannAlgorithm;
else if(hName == "xy_model_file_name")
m_hFannXYModelFileName = hStream.str();
hStream.clear();
}
}
bool
XmlConfig::readSignalCorrectionsSettings(const xmlpp::Node* pRootNode)
{
stringstream hStream;
// get s1 spatial correction settings
const xmlpp::NodeSet hS1SpatialCorrectionNodeSet = pRootNode->find("/xerawdp/signal_corrections/s1/spatial_correction/*");
for(int i = 0; i < (int) hS1SpatialCorrectionNodeSet.size(); i++)
{
string hName = hS1SpatialCorrectionNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hS1SpatialCorrectionNodeSet[i]->get_children().front())->get_content());
if(hName == "apply_correction")
hStream >> m_bCorrectForS1SpatialDependence;
if(hName == "electron_lifetime")
hStream >> m_fElectronLifetime;
hStream.clear();
}
// get s2 axial correction settings
const xmlpp::NodeSet hS2AxialCorrectionNodeSet = pRootNode->find("/xerawdp/signal_corrections/s2/axial_correction/*");
for(int i = 0; i < (int) hS2AxialCorrectionNodeSet.size(); i++)
{
string hName = hS2AxialCorrectionNodeSet[i]->get_name();
hStream.str(((xmlpp::ContentNode *) hS2AxialCorrectionNodeSet[i]->get_children().front())->get_content());
if(hName == "apply_correction")
hStream >> m_bCorrectForS2AxialDependence;
else if(hName == "electron_lifetime")
hStream >> m_fElectronLifetime;
hStream.clear();
}
if(m_bCorrectForS2AxialDependence && m_fElectronLifetime <= 0.)
{
cout << "xml config error: electron lifetime value required for s2 axial signal correction!" << endl;
return false;
}
return true;
}
bool
XmlConfig::parsePmtString(const string &hString, int &iFirstPmt, int &iLastPmt)
{
stringstream hTmp(hString);
hTmp >> iFirstPmt;
hTmp.ignore();
hTmp >> iLastPmt;
return true;
}
bool
XmlConfig::parsePmtExternalGainsString(const std::string &hString, ExternalGainsTable &hExternalGainsTable)
{
stringstream hTmp(hString);
string::size_type hNextDigit = hTmp.str().find_first_of("0123456789");
hTmp.seekg(hNextDigit);
hExternalGainsTable.clear();
while(!hTmp.eof() && hTmp.good())
{
// get the pmt range
int iFirstPmt, iLastPmt;
hTmp >> iFirstPmt;
if(hTmp.peek() == '-')
{
hTmp.ignore();
hTmp >> iLastPmt;
}
else
iLastPmt = iFirstPmt;
// get the external gain
float fExternalGain;
hTmp.ignore();
hTmp >> fExternalGain;
for(int iPmt = iFirstPmt; iPmt <= iLastPmt; iPmt++)
hExternalGainsTable[iPmt] = fExternalGain;
// find the next digit
hTmp.seekg(hTmp.str().find_first_of("0123456789", hTmp.tellg()));
}
return true;
}
bool
XmlConfig::parsePmtEnumerationString(const std::string &hString, PmtSet &hPmtSet)
{
stringstream hTmp(hString);
string::size_type hNextDigit = hTmp.str().find_first_of("0123456789");
hTmp.seekg(hNextDigit);
hPmtSet.clear();
while(!hTmp.eof() && hTmp.good())
{
// get the pmt range
int iFirstPmt, iLastPmt;
hTmp >> iFirstPmt;
if(hTmp.peek() == '-')
{
hTmp.ignore();
hTmp >> iLastPmt;
}
else
iLastPmt = iFirstPmt;
for(int iPmt = iFirstPmt; iPmt <= iLastPmt; iPmt++)
hPmtSet.insert(iPmt);
// find the next digit
hTmp.seekg(hTmp.str().find_first_of("0123456789", hTmp.tellg()));
}
return true;
}
bool
XmlConfig::parsePmtCalibrationHeader(const std::string &hHeader)
{
stringstream hStream(hHeader);
string hTmp;
while(!hStream.eof())
{
hStream >> hTmp;
m_hPmtCalibrationTableHeader.push_back(hTmp);
}
// if this is the header of a calibration file
if(m_hPmtCalibrationSource == "file")
{
// the pmt column is required
if(count(m_hPmtCalibrationTableHeader.begin(), m_hPmtCalibrationTableHeader.end(), "pmt") == 0)
{
cout << "xml config error: the pmt calibration file needs to contain the pmt number column!" << endl;
return false;
}
}
// verify that at least the gain is there
if(count(m_hPmtCalibrationTableHeader.begin(), m_hPmtCalibrationTableHeader.end(), "gain") == 0)
{
cout << "xml config error: the pmt calibration needs to contain at least the gain!" << endl;
return false;
}
return true;
}
bool
XmlConfig::parsePmtCalibrationFile(const string &hFile)
{
ifstream hIn(hFile.c_str());
if(hIn.fail())
{
cout << "xml config error: cannot open file " << hFile << "!" << endl;
return false;
}
// parse the header
string hHeader;
getline(hIn, hHeader);
if(!parsePmtCalibrationHeader(hHeader))
return false;
m_hPmtCalibrationTable.clear();
// read the pmt calibration values as described by the calibration table header
int iExpectedPmt = 1;
while(!hIn.eof())
{
map<string, float> hCalibration;
PmtCalibrationTableHeader::iterator pColumn;
for(pColumn = m_hPmtCalibrationTableHeader.begin(); pColumn != m_hPmtCalibrationTableHeader.end(); pColumn++)
{
float fValue = 0.;
hIn >> fValue;
if(hIn.fail())
break;
hCalibration[*pColumn] = fValue;
}
if(!hIn.fail())
{
int iPmt = (int) hCalibration["pmt"];
// store them in the pmt calibration table
m_hPmtCalibrationTable[iPmt] = hCalibration;
iExpectedPmt++;
}
}
// verify pmt calibration table
return verifyPmtCalibrationTable();
}
bool
XmlConfig::parsePmtCalibrationValues(const string &hValues)
{
// parse the header
if(!parsePmtCalibrationHeader(m_hPmtCalibrationHeader))
return false;
m_hPmtCalibrationTable.clear();
string::size_type hPos = 0;
string::size_type hColonPos;
// find the next colon
while((hColonPos = hValues.find(":", hPos)) != string::npos)
{
stringstream hTmp;
hTmp.clear();
hTmp.str(hValues.substr(hPos, hColonPos-hPos));
// get the pmt range
int iFirstPmt, iLastPmt;
hTmp >> iFirstPmt;
if(hTmp.peek() == '-')
{
hTmp.ignore();
hTmp >> iLastPmt;
}
else
iLastPmt = iFirstPmt;
hPos = hColonPos+1;
string::size_type hCommaPos;
hTmp.clear();
if((hCommaPos = hValues.find(",", hPos)) != string::npos)
hTmp.str(hValues.substr(hPos+1, hCommaPos-hPos-2));
else
hTmp.str(hValues.substr(hPos+1, hValues.size()-hPos-2));
// get the pmt calibration parameters
while(!hTmp.eof())
{
map<string, float> hCalibration;
PmtCalibrationTableHeader::iterator pColumn;
for(pColumn = m_hPmtCalibrationTableHeader.begin(); pColumn != m_hPmtCalibrationTableHeader.end(); pColumn++)
{
float fValue = 0.;
hTmp >> fValue;
if(hTmp.fail())
break;
hCalibration[*pColumn] = fValue;
}
if(!hTmp.fail())
{
// store them in the pmt calibration table
for(int iPmt = iFirstPmt; iPmt <= iLastPmt; iPmt++)
m_hPmtCalibrationTable[iPmt] = hCalibration;
}
}
hPos = hCommaPos+1;
if(hCommaPos == string::npos)
break;
}
// verify pmt calibration table
return verifyPmtCalibrationTable();
}
bool
XmlConfig::fillPmtCalibrationTable()
{
if(m_hPmtCalibrationSource == "file")
return parsePmtCalibrationFile(m_hPmtCalibrationFileName);
else if(m_hPmtCalibrationSource == "here" || m_hPmtCalibrationSource == "database")
return parsePmtCalibrationValues(m_hPmtCalibrationValues);
}
bool
XmlConfig::verifyPmtCalibrationTable()
{
int iFirstPmt = INT_MAX, iLastPmt = 1;
if(m_iFirstTopPmt != -1)
{
iFirstPmt = min(iFirstPmt, m_iFirstTopPmt);
iLastPmt = max(iLastPmt, m_iFirstTopPmt);
}
if(m_iFirstBottomPmt != -1)
{
iFirstPmt = min(iFirstPmt, m_iFirstBottomPmt);
iLastPmt = max(iLastPmt, m_iFirstBottomPmt);
}
if(m_iFirstTopVetoPmt != -1)
{
iFirstPmt = min(iFirstPmt, m_iFirstTopVetoPmt);
iLastPmt = max(iLastPmt, m_iFirstTopVetoPmt);
}
if(m_iFirstBottomVetoPmt != -1)
{
iFirstPmt = min(iFirstPmt, m_iFirstBottomVetoPmt);
iLastPmt = max(iLastPmt, m_iFirstBottomVetoPmt);
}
for(int iPmt = iFirstPmt; iPmt <= iLastPmt; iPmt++)
{
if(m_hPmtCalibrationTable.count(iPmt) != 1)
{
cout << "xml config error: pmt calibration table failed sanity check!" << endl;
return false;
}
}
return true;
}
bool
XmlConfig::parseValueList(const std::string &hString, std::vector<float> &hValues)
{
stringstream hTmp(hString);
string::size_type hNextDigit = hTmp.str().find_first_of("-0123456789");
hTmp.seekg(hNextDigit);
hValues.clear();
float fValue;
while(!hTmp.eof() && hTmp.good())
{
hTmp >> fValue;
hValues.push_back(fValue);
// find the next digit
hTmp.seekg(hTmp.str().find_first_of("-0123456789", hTmp.tellg()));
}
return true;
}
bool
XmlConfig::parseRelativeEfficienciesString(const std::string &hString, RelativeEfficienciesTable &hRelativeEfficienciesTable)
{
stringstream hTmp(hString);
string::size_type hNextDigit = hTmp.str().find_first_of("0123456789");
hTmp.seekg(hNextDigit);
hRelativeEfficienciesTable.clear();
while(!hTmp.eof() && hTmp.good())
{
// get the pmt range
int iFirstPmt, iLastPmt;
hTmp >> iFirstPmt;
if(hTmp.peek() == '-')
{
hTmp.ignore();
hTmp >> iLastPmt;
}
else
iLastPmt = iFirstPmt;
// get the external gain
float fRelativeSensitivity;
hTmp.ignore();
hTmp >> fRelativeSensitivity;
for(int iPmt = iFirstPmt; iPmt <= iLastPmt; iPmt++)
hRelativeEfficienciesTable[iPmt] = fRelativeSensitivity;
// find the next digit
hTmp.seekg(hTmp.str().find_first_of("0123456789", hTmp.tellg()));
}
return true;
}
#ifdef ENABLE_LIQ_SCI
void
XmlConfig::parseLiqSciMultiplexingWindowsString(const string &hString, LiqSciMultiplexingTable &hLiqSciMultiplexingTable)
{
// create the header
m_hLiqSciMultiplexingTableHeader.clear();
m_hLiqSciMultiplexingTableHeader.push_back("window_start");
m_hLiqSciMultiplexingTableHeader.push_back("window_width");
m_hLiqSciMultiplexingTable.clear();
string::size_type hPos = 0;
string::size_type hColonPos;
// find the next colon
while((hColonPos = hString.find(":", hPos)) != string::npos)
{
stringstream hTmp;
hTmp.clear();
hTmp.str(hString.substr(hPos, hColonPos-hPos));
// get the liquid scintillator channel range
int iFirstLiqSciChannel, iLastLiqSciChannel;
hTmp >> iFirstLiqSciChannel;
if(hTmp.peek() == '-')
{
hTmp.ignore();
hTmp >> iLastLiqSciChannel;
}
else
iLastLiqSciChannel = iFirstLiqSciChannel;
hPos = hColonPos+1;
string::size_type hCommaPos;
hTmp.clear();
if((hCommaPos = hString.find(",", hPos)) != string::npos)
hTmp.str(hString.substr(hPos+1, hCommaPos-hPos-2));
else
hTmp.str(hString.substr(hPos+1, hString.size()-hPos-2));
// get the liquid scintillator multiplexing parameters
while(!hTmp.eof())
{
LiqSciMultiplexingTableEntry hLiqSciMultiplexingTableEntry;
LiqSciMultiplexingTableHeader::iterator pColumn;
for(pColumn = m_hLiqSciMultiplexingTableHeader.begin(); pColumn != m_hLiqSciMultiplexingTableHeader.end(); pColumn++)
{
int iValue = 0;
hTmp >> iValue;
if(hTmp.fail())
break;
hLiqSciMultiplexingTableEntry.push_back(iValue);
}
if(!hTmp.fail())
{
// store them in the pmt calibration table
for(int iLiqSciChannel = iFirstLiqSciChannel; iLiqSciChannel <= iLastLiqSciChannel; iLiqSciChannel++)
m_hLiqSciMultiplexingTable.push_back(hLiqSciMultiplexingTableEntry);
}
}
hPos = hCommaPos+1;
if(hCommaPos == string::npos)
break;
}
}
bool
XmlConfig::verifyLiqSciMultiplexingTable()
{
if(m_bLiqSciMultiplexed && (m_hLiqSciMultiplexingTable.size() != m_iNbLiqScis))
{
cout << "xml config error: liquid scintillator multiplexing table failed sanity check!" << endl;
return false;
}
return true;
}
#endif
#ifdef ENABLE_TAC
void
XmlConfig::parseTacCalibrationString(const std::string &hString, TacCalibrationTable &hTacCalibrationTable)
{
// create the header
m_hTacCalibrationTableHeader.clear();
m_hTacCalibrationTableHeader.push_back("intercept");
m_hTacCalibrationTableHeader.push_back("slope");
m_hTacCalibrationTable.clear();
string::size_type hPos = 0;
string::size_type hColonPos;
// find the next colon
while((hColonPos = hString.find(":", hPos)) != string::npos)
{
stringstream hTmp;
hTmp.clear();
hTmp.str(hString.substr(hPos, hColonPos-hPos));
// get the channel range
int iFirstChannel, iLastChannel;
hTmp >> iFirstChannel;
if(hTmp.peek() == '-')
{
hTmp.ignore();
hTmp >> iLastChannel;
}
else
iLastChannel = iFirstChannel;
hPos = hColonPos+1;
string::size_type hCommaPos;
hTmp.clear();
if((hCommaPos = hString.find(",", hPos)) != string::npos)
hTmp.str(hString.substr(hPos+1, hCommaPos-hPos-2));
else
hTmp.str(hString.substr(hPos+1, hString.size()-hPos-2));
// get the time to amplitude converter calibration parameters
while(!hTmp.eof())
{
TacCalibrationTableEntry hTacCalibrationTableEntry;
TacCalibrationTableHeader::iterator pColumn;
for(pColumn = m_hTacCalibrationTableHeader.begin(); pColumn != m_hTacCalibrationTableHeader.end(); pColumn++)
{
float fValue = 0.;
hTmp >> fValue;
if(hTmp.fail())
break;
hTacCalibrationTableEntry.push_back(fValue);
}
if(!hTmp.fail())
{
// store them in the pmt calibration table
for(int iChannel = iFirstChannel; iChannel <= iLastChannel; iChannel++)
m_hTacCalibrationTable.push_back(hTacCalibrationTableEntry);
}
}
hPos = hCommaPos+1;
if(hCommaPos == string::npos)
break;
}
}
bool
XmlConfig::verifyTacCalibrationTable()
{
#ifdef ENABLE_LIQ_SCI
if(m_hTacCalibrationTable.size() != (m_bLiqSciMultiplexed)?(m_iNbLiqScis):(m_iNbTacs))
{
cout << "xml config error: time to amplitude converter calibration table failed sanity check!" << endl;
return false;
}
#else
if(m_hTacCalibrationTable.size() != m_iNbTacs)
{
cout << "xml config error: time to amplitude converter calibration table failed sanity check!" << endl;
return false;
}
#endif
return true;
}
#endif
| [
"mda2149@columbia.edu"
] | mda2149@columbia.edu |
d07c0a84586a280b00d8df32660d3e7201cd139f | f862edafff99a383ab7b85f34cc7a060de320922 | /core/depthmap.h | 64d72eee2ad025575c524d64a4e6bf256962d0ed | [] | no_license | FivestWu/ImageBasedModellingEduV1.0 | 51387cfdd654108d118b1f883464beb1dc77e37f | ef0f9f086ce641bafb30fb19a1c3ce90ca10a9fe | refs/heads/master | 2020-04-04T10:05:06.454977 | 2019-03-13T08:04:57 | 2019-03-13T08:04:57 | 155,842,300 | 0 | 0 | null | 2018-11-02T09:17:48 | 2018-11-02T09:17:47 | null | UTF-8 | C++ | false | false | 6,575 | h | /*
* Copyright (C) 2015, Simon Fuhrmann
* TU Darmstadt - Graphics, Capture and Massively Parallel Computing
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the LICENSE.txt file for details.
*/
#ifndef MVE_DEPTHMAP_HEADER
#define MVE_DEPTHMAP_HEADER
#include "core/defines.h"
#include "math/vector.h"
#include "math/matrix.h"
#include "core/camera.h"
#include "core/image.h"
#include "core/mesh.h"
CORE_NAMESPACE_BEGIN
CORE_IMAGE_NAMESPACE_BEGIN
/**
* Algorithm to clean small confident islands in the depth maps.
* Islands that are smaller than 'thres' pixels are removed.
* Zero depth values are considered unreconstructed.
*/
FloatImage::Ptr
depthmap_cleanup (FloatImage::ConstPtr dm, std::size_t thres);
/**
* Removes the backplane according to the confidence map IN-PLACE.
* Depth map values are reset to zero where confidence is leq 0.
*/
void
depthmap_confidence_clean (FloatImage::Ptr dm, FloatImage::ConstPtr cm);
/**
* Filters the given depthmap using a bilateral filter.
*
* The filter smoothes similar depth values but preserves depth
* discontinuities using gaussian weights for both, geometric
* closeness in image space and geometric closeness in world space.
*
* Geometric closeness in image space is controlled by 'gc_sigma'
* (useful values in [1, 20]). Photometric closeness is evaluated by
* calculating the pixel footprint multiplied with 'pc_factor' to
* detect depth discontinuities (useful values in [1, 20]).
*/
FloatImage::Ptr
depthmap_bilateral_filter (FloatImage::ConstPtr dm,
math::Matrix3f const& invproj, float gc_sigma, float pc_fator);
/**
* Converts between depth map conventions IN-PLACE. In one convention,
* a depth map with a constant value means a plane, in another convention,
* which is what MVE uses, a constant value creates a curved surface. The
* difference is whether only the z-value is considered, or the distance
* to the camera center is used (MVE).
*/
template <typename T>
void
depthmap_convert_conventions (typename Image<T>::Ptr dm,
math::Matrix3f const& invproj, bool to_mve);
CORE_IMAGE_NAMESPACE_END
CORE_NAMESPACE_END
/* ---------------------------------------------------------------- */
CORE_NAMESPACE_BEGIN
CORE_GEOM_NAMESPACE_BEGIN
/**
* Function that calculates the pixel footprint (pixel width)
* in 3D coordinates for pixel (x,y) and 'depth' for a depth map
* with inverse K matrix 'invproj'.
*/
float
pixel_footprint (std::size_t x, std::size_t y, float depth,
math::Matrix3f const& invproj);
/**
* Function that calculates the pixel 3D position in camera coordinates for
* pixel (x,y) and 'depth' for a depth map with inverse K matrix 'invproj'.
*/
math::Vec3f
pixel_3dpos (std::size_t x, std::size_t y, float depth,
math::Matrix3f const& invproj);
/**
* \description * Algorithm to triangulate depth maps.
*
* A factor may be specified that guides depth discontinuity detection. A
* depth discontinuity between pixels is assumed if depth difference is
* larger than pixel footprint times 'dd_factor'. If 'dd_factor' is zero,
* no depth discontinuity detection is performed. The depthmap is
* triangulated in the local camera coordinate system.
*
* If 'vids' is not null, image content is replaced with vertex indices for
* each pixel that generated the vertex. Index MATH_MAX_UINT corresponds to
* a pixel that did not generate a vertex.
* @param dm -- 深度图
* @param invproj -- 投影矩阵的逆矩阵
* @param dd_factor -- 不确定因子
* @param vids --可视图像
* @return
*/
TriangleMesh::Ptr
depthmap_triangulate (FloatImage::ConstPtr dm, math::Matrix3f const& invproj,
float dd_factor = 5.0f, core::Image<unsigned int>* vids = nullptr);
/**
* \description A helper function that triangulates the given depth map with optional
* color image (which generates additional per-vertex colors) in local
* image coordinates.
* @param dm
* @param ci
* @param invproj
* @param dd_factor
* @return
*/
TriangleMesh::Ptr
depthmap_triangulate (FloatImage::ConstPtr dm, ByteImage::ConstPtr ci,
math::Matrix3f const& invproj, float dd_factor = 5.0f);
/**
* \description A helper function that triangulates the given depth map with optional
* color image (which generates additional per-vertex colors) and transforms
* the mesh into the global coordinate system.
* @param dm -- 深度图像
* @param ci -- 彩色图像
* @param cam -- 相机参数
* @param dd_factor -- ??
* @return
*/
TriangleMesh::Ptr
depthmap_triangulate (FloatImage::ConstPtr dm, ByteImage::ConstPtr ci,
CameraInfo const& cam, float dd_factor = 5.0f);
/**
* Algorithm to triangulate range grids.
* Vertex positions are given in 'mesh' and a grid that contains vertex
* indices is specified. Four indices are taken at a time and triangulated
* with discontinuity detection. New triangles are added to the mesh.
*/
void
rangegrid_triangulate (Image<unsigned int> const& grid, TriangleMesh::Ptr mesh);
/**
* Algorithm to assign per-vertex confidence values to vertices of
* a triangulated depth map. Confidences are low near boundaries
* and small regions.
*/
void
depthmap_mesh_confidences (TriangleMesh::Ptr mesh, int iterations = 3);
/**
* Algorithm that peels away triangles at the mesh bounary of a
* triangulated depth map. The algorithm also works on other mesh
* data but is particularly useful for MVS depthmap where the edges
* of the real object are extended beyond their correct position.
*/
void
depthmap_mesh_peeling (TriangleMesh::Ptr mesh, int iterations = 1);
CORE_GEOM_NAMESPACE_END
CORE_NAMESPACE_END
/* ------------------------- Implementation ----------------------- */
CORE_NAMESPACE_BEGIN
CORE_IMAGE_NAMESPACE_BEGIN
template <typename T>
inline void
depthmap_convert_conventions (typename Image<T>::Ptr dm,
math::Matrix3f const& invproj, bool to_mve)
{
std::size_t w = dm->width();
std::size_t h = dm->height();
std::size_t pos = 0;
for (std::size_t y = 0; y < h; ++y)
for (std::size_t x = 0; x < w; ++x, ++pos)
{
// Construct viewing ray for that pixel
math::Vec3f px((float)x + 0.5f, (float)y + 0.5f, 1.0f);
px = invproj * px;
// Measure length of viewing ray
double len = px.norm();
// Either divide or multiply with the length
dm->at(pos) *= (to_mve ? len : 1.0 / len);
}
}
CORE_IMAGE_NAMESPACE_END
CORE_NAMESPACE_END
#endif /* MVE_DEPTHMAP_HEADER */
| [
"wsui@nl.pr.ia.ac.cn"
] | wsui@nl.pr.ia.ac.cn |
2e857525ec729de02671ef02df0d92152b8240a2 | ee5c13e2219d5b5196f779074c972c230a778e0d | /DP/fib.cpp | 42993c032021076da3c9fc3074f8e295f5f7d337 | [] | no_license | Malay-Acharya/CPP | 2b27f2f6557ad27036a41c9280f716fa0cfae05a | 48bfa883720b832688e2b387a114b90fa69a7b88 | refs/heads/master | 2023-06-29T09:50:49.902474 | 2021-08-02T11:36:02 | 2021-08-02T11:36:02 | 391,924,846 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 316 | cpp | #include <iostream>
#define int long long
using namespace std;
const int N = 1e5;
int dp[N] = {0};
int fib(int n)
{
if(n==0)
return 0;
if(n==1 || n==2)
return 1;
if(dp[n]!=0)
return dp[n];
dp[n] = fib(n-1) + fib(n-2);
return dp[n];
}
signed main() {
int n;
cin >> n;
cout<<fib(n)<<endl;
} | [
"malayacharya21@gmail.com"
] | malayacharya21@gmail.com |
d4f476118e01ebfc2197b656538e071111bbb5ed | be3167504c0e32d7708e7d13725c2dbc9232f2cb | /mameppk/src/osd/sdl/osdsdl.h | 61136a6680b38e6e93c02684c85a89b5f7dcbd4f | [] | no_license | sysfce2/MAME-Plus-Plus-Kaillera | 83b52085dda65045d9f5e8a0b6f3977d75179e78 | 9692743849af5a808e217470abc46e813c9068a5 | refs/heads/master | 2023-08-10T06:12:47.451039 | 2016-08-01T09:44:21 | 2016-08-01T09:44:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,063 | h | // license:BSD-3-Clause
// copyright-holders:Olivier Galibert, R. Belmont
#ifndef _osdsdl_h_
#define _osdsdl_h_
#include "sdlinc.h"
#include "watchdog.h"
#include "clifront.h"
#include "modules/lib/osdobj_common.h"
#include "modules/osdmodule.h"
#include "modules/font/font_module.h"
//============================================================
// System dependent defines
//============================================================
#if defined(SDLMAME_WIN32)
#if (SDLMAME_SDL2)
#define SDLMAME_EVENTS_IN_WORKER_THREAD (0)
#define SDLMAME_INIT_IN_WORKER_THREAD (0)
#define SDL13_COMBINE_RESIZE (0) //(1) no longer needed
#else
#define SDLMAME_EVENTS_IN_WORKER_THREAD (0)
#define SDLMAME_INIT_IN_WORKER_THREAD (1)
#define SDL13_COMBINE_RESIZE (0)
#endif
#else
#define SDLMAME_EVENTS_IN_WORKER_THREAD (0)
#define SDLMAME_INIT_IN_WORKER_THREAD (0)
#define SDL13_COMBINE_RESIZE (0)
#endif
//============================================================
// Defines
//============================================================
#define SDLOPTION_INIPATH "inipath"
#define SDLOPTION_SDLVIDEOFPS "sdlvideofps"
#define SDLOPTION_USEALLHEADS "useallheads"
#define SDLOPTION_CENTERH "centerh"
#define SDLOPTION_CENTERV "centerv"
#define SDLOPTION_SCALEMODE "scalemode"
#define SDLOPTION_WAITVSYNC "waitvsync"
#define SDLOPTION_SYNCREFRESH "syncrefresh"
#define SDLOPTION_KEYMAP "keymap"
#define SDLOPTION_KEYMAP_FILE "keymap_file"
#define SDLOPTION_SIXAXIS "sixaxis"
#define SDLOPTION_JOYINDEX "joy_idx"
#define SDLOPTION_KEYBINDEX "keyb_idx"
#define SDLOPTION_MOUSEINDEX "mouse_index"
#if (USE_XINPUT)
#define SDLOPTION_LIGHTGUNINDEX "lightgun_index"
#endif
#define SDLOPTION_AUDIODRIVER "audiodriver"
#define SDLOPTION_VIDEODRIVER "videodriver"
#define SDLOPTION_RENDERDRIVER "renderdriver"
#define SDLOPTION_GL_LIB "gl_lib"
#define SDLOPTVAL_OPENGL "opengl"
#define SDLOPTVAL_SOFT "soft"
#define SDLOPTVAL_SDL2ACCEL "accel"
#define SDLOPTVAL_BGFX "bgfx"
#define SDLMAME_LED(x) "led" #x
// read by sdlmame
#define SDLENV_DESKTOPDIM "SDLMAME_DESKTOPDIM"
#define SDLENV_VMWARE "SDLMAME_VMWARE"
// set by sdlmame
#define SDLENV_VISUALID "SDL_VIDEO_X11_VISUALID"
#define SDLENV_VIDEODRIVER "SDL_VIDEODRIVER"
#define SDLENV_AUDIODRIVER "SDL_AUDIODRIVER"
#define SDLENV_RENDERDRIVER "SDL_VIDEO_RENDERER"
#define SDLMAME_SOUND_LOG "sound.log"
#ifdef SDLMAME_MACOSX
/* Vas Crabb: Default GL-lib for MACOSX */
#define SDLOPTVAL_GLLIB "/System/Library/Frameworks/OpenGL.framework/Libraries/libGL.dylib"
#else
#define SDLOPTVAL_GLLIB OSDOPTVAL_AUTO
#endif
//============================================================
// TYPE DEFINITIONS
//============================================================
class sdl_options : public osd_options
{
public:
// construction/destruction
sdl_options();
// performance options
bool video_fps() const { return bool_value(SDLOPTION_SDLVIDEOFPS); }
// video options
bool centerh() const { return bool_value(SDLOPTION_CENTERH); }
bool centerv() const { return bool_value(SDLOPTION_CENTERV); }
const char *scale_mode() const { return value(SDLOPTION_SCALEMODE); }
// full screen options
#ifdef SDLMAME_X11
bool use_all_heads() const { return bool_value(SDLOPTION_USEALLHEADS); }
#endif
// keyboard mapping
bool keymap() const { return bool_value(SDLOPTION_KEYMAP); }
const char *keymap_file() const { return value(SDLOPTION_KEYMAP_FILE); }
// joystick mapping
const char *joy_index(int index) const { std::string temp; return value(strformat(temp, "%s%d", SDLOPTION_JOYINDEX, index).c_str()); }
bool sixaxis() const { return bool_value(SDLOPTION_SIXAXIS); }
#if (SDLMAME_SDL2)
const char *mouse_index(int index) const { std::string temp; return value(strformat(temp, "%s%d", SDLOPTION_MOUSEINDEX, index).c_str()); }
const char *keyboard_index(int index) const { std::string temp; return value(strformat(temp, "%s%d", SDLOPTION_KEYBINDEX, index).c_str()); }
#endif
const char *video_driver() const { return value(SDLOPTION_VIDEODRIVER); }
const char *render_driver() const { return value(SDLOPTION_RENDERDRIVER); }
const char *audio_driver() const { return value(SDLOPTION_AUDIODRIVER); }
#if USE_OPENGL
const char *gl_lib() const { return value(SDLOPTION_GL_LIB); }
#endif
private:
static const options_entry s_option_entries[];
};
class sdl_osd_interface : public osd_common_t
{
public:
// construction/destruction
sdl_osd_interface(sdl_options &options);
virtual ~sdl_osd_interface();
// general overridables
virtual void init(running_machine &machine);
virtual void update(bool skip_redraw);
// input overridables
virtual void customize_input_type_list(simple_list<input_type_entry> &typelist);
virtual void video_register();
virtual bool video_init();
virtual bool window_init();
virtual bool input_init();
virtual void input_pause();
virtual void input_resume();
virtual bool output_init();
//virtual bool midi_init();
virtual void video_exit();
virtual void window_exit();
virtual void input_exit();
virtual void output_exit();
//virtual void midi_exit();
sdl_options &options() { return m_options; }
private:
virtual void osd_exit();
void extract_video_config();
sdl_options &m_options;
watchdog *m_watchdog;
};
//============================================================
// sdlwork.c
//============================================================
extern int osd_num_processors;
#endif
| [
"mameppk@199a702f-54f1-4ac0-8451-560dfe28270b"
] | mameppk@199a702f-54f1-4ac0-8451-560dfe28270b |
ed878a123ed7de3787f8817c4e04db6368d7d043 | 0a1fb9fcfcbff0482dbbb4094d0ef00a3ccc6b05 | /SoundBoard/SoundBoard/SoundButtonGroup.cpp | 6f7df74968d52bbb4bc72851e1d5e49ca3161481 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | honky/SoftwareProjektTUBAF2013 | 4bd9f844e29d417059a8b4886afa8d233bb45200 | 1687ba77fa417fde7aa36477da4070bf9d3efa8d | refs/heads/master | 2021-01-22T23:26:02.752793 | 2014-01-10T15:35:17 | 2014-01-10T15:35:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 623 | cpp | #include "StdAfx.h"
#include "SoundButtonGroup.h"
namespace SoundBoard
{
SoundButtonGroup::SoundButtonGroup(String^ name)
{
this->name = name;
this->Text = System::IO::Path::GetFileName(name);
this->buttons = gcnew List<SoundButton^>();
this->Anchor = Windows::Forms::AnchorStyles::Right;
this->flPanel = gcnew Windows::Forms::FlowLayoutPanel();
this->flPanel->Dock = Windows::Forms::DockStyle::Fill;
this->Controls->Add(flPanel);
this->Width = 375;
this->Height= 50;
}
void SoundButtonGroup::addSoundButton(SoundButton^ sb)
{
this->buttons->Add(sb);
this->flPanel->Controls->Add(sb);
}
}
| [
"plotterhairy@googlemail.com"
] | plotterhairy@googlemail.com |
14e79e4cf861dd7412ad71586386eacd4e80a20f | b99f7ba8dbe2c6a43edf510066c76df0d4980b60 | /Maths3D/Sommet.hpp | 84840b3379d11831b5e67275a2d19377f9af7f72 | [] | no_license | anthonybazelle/VoronoiAndDelaunay | 860900d38a79c0b726fc8cbc892c84546984b746 | 98cb9efa27af3c107a9f634b6e0737def0519c8b | refs/heads/master | 2021-08-28T15:18:43.050791 | 2017-12-12T15:20:25 | 2017-12-12T15:20:25 | 111,926,526 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 824 | hpp |
#include "Cote.hpp"
class Sommet {
// each point connected to edges
private:
Point point;
std::vector<Cote*> * edgesConnected;
Couleur color;
public:
Sommet() {
edgesConnected = new std::vector<Cote*>();
}
Sommet(Point p)
{
point = p;
edgesConnected = new std::vector<Cote*>();
}
Sommet(Couleur c, Point p)
{
color = c;
point = p;
}
Sommet(Couleur c, std::vector<Cote*> *e, Point p)
{
color = c;
edgesConnected = e;
point = p;
}
void setPoint(const Point & p)
{
point = p;
}
Point getPoint()
{
return point;
}
void setColor(const Couleur & c)
{
color = c;
}
const Couleur & getColor() const
{
return color;
}
void setEdgesConnected(std::vector<Cote*> * f)
{
edgesConnected = f;
}
std::vector<Cote*> * getEdgesConnected()
{
return edgesConnected;
}
}; | [
"pourrier789@gmail.com"
] | pourrier789@gmail.com |
752c20ba2f29905548f6f1a935dfbbe14986d34d | 505446850988c792bc5d13bc0252b4a74c5eb7a3 | /p1.cpp | 3cce7f39f15720f47f8701e87ffe5cb2a6cfaca3 | [] | no_license | CED-9/Temp | c67691b7a06b2f46aecb7aae8fa7ff62ea9a1638 | 3a49433ebbeaa50a1e6976009c17a6c1c1a01630 | refs/heads/master | 2018-12-29T20:44:02.870165 | 2015-01-17T04:07:35 | 2015-01-17T04:07:35 | 29,379,263 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,522 | cpp | #include <iostream>
#include"thread.h"
#include<vector>
#include<ifstream>
#include<string>
using namespace std;
struct Requester{
int id;
string name;
};
mutex mutex1;
//cv cv1;
vector <int> done; // global variable; shared between the all threads.
//vector <Requester> rqs;
vector <int> waitQueue;
void sentRq(int track){
waitQueue.push_back(track);
}
void requester(void *id)
{
int * message = (int *) id;
vector<int> input;
ifstream fin;
fin.open(argv[i+2]);
while(line = fin.getline()){
input.push_back(atoi(line));
}
fin.close();
// enter critical section
mutex1.lock();
for (int i = 0; i < input.size(); i++)
{
sentRq(input[i]);
cout << "requester " << id << " track " << input[i] << endl;
}
done[id] = 1;
cv1.signal();
mutex1.unlock();
}
void service(void *numRq)
{
mutex1.lock();
while (!child_done) {
cout << "parent waiting for child to run\n";
cv1.wait(mutex1);
}
cout << "parent finishing" << endl;
mutex1.unlock();
}
int main(int argc, char* argv[])
{
int numRq = argc - 2;
// initialize the global record
for (int i = 0; i < numRq; i++)
{
done.push_back(0);
}
// Trigger service's thread
cpu::boot((thread_startfunc_t) service, (void *) numRq, 0);
// Trigger requesters' threads
ifstream fin;
for(int i = 0; i < numRq; i++){
Requester rq;
rq.id = i;
rq.name = (string)argv[i+2];
//rqs.push_back(rq);
thread requester_t ((thread_startfunc_t) requester, (void *) rq );
}
for (int i = 0; i < numRq; i++)
{
//join();
}
return 0;
}
| [
"liujm@umich.edu"
] | liujm@umich.edu |
2b7804a1324a969f005552394f8167f5320aff47 | ab1c643f224197ca8c44ebd562953f0984df321e | /wmi/wbem/providers/snmpprovider/provider/instclas/include/clasprov.h | 4b3e2af7e419f8a7f31d1786fe11382193054b60 | [] | no_license | KernelPanic-OpenSource/Win2K3_NT_admin | e162e0452fb2067f0675745f2273d5c569798709 | d36e522f16bd866384bec440517f954a1a5c4a4d | refs/heads/master | 2023-04-12T13:25:45.807158 | 2021-04-13T16:33:59 | 2021-04-13T16:33:59 | 357,613,696 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,901 | h | //***************************************************************************
//
// PropertyProvider.H
//
// Module: Sample Mini Server for Ole MS
//
// Purpose: Genral purpose include file.
//
// Copyright (c) 1996-2001 Microsoft Corporation, All Rights Reserved
//
//***************************************************************************
#ifndef _SNMPClassProvider_H_
#define _SNMPClassProvider_H_
extern CRITICAL_SECTION s_ProviderCriticalSection ;
class SnmpClassDefaultThreadObject : public SnmpThreadObject
{
private:
protected:
public:
SnmpClassDefaultThreadObject ( const char *threadName = NULL ) : SnmpThreadObject ( threadName ) {} ;
~SnmpClassDefaultThreadObject () {} ;
void Initialise () ;
void Uninitialise () { CoUninitialize () ; }
} ;
class CImpClasProv : public IWbemServices , public IWbemProviderInit
{
private:
LONG m_referenceCount ; //Object reference count
private:
BOOL initialised ;
IWbemServices *propertyProvider ;
IWbemServices *server ;
IWbemServices *parentServer ;
IWbemProviderInitSink *m_InitSink ;
char *ipAddressString ;
char *ipAddressValue ;
wchar_t *thisNamespace ;
WbemNamespacePath namespacePath ;
CCriticalSection m_notificationLock;
CCriticalSection m_snmpNotificationLock;
IWbemClassObject *m_notificationClassObject ;
IWbemClassObject *m_snmpNotificationClassObject ;
BOOL m_getNotifyCalled ;
BOOL m_getSnmpNotifyCalled ;
private:
HRESULT SetServer ( IWbemServices *serverArg ) ;
HRESULT SetParentServer ( IWbemServices *parentServerArg ) ;
BOOL AttachParentServer (
WbemSnmpErrorObject &a_errorObject ,
BSTR ObjectPath,
IWbemContext *pCtx
) ;
BOOL ObtainCachedIpAddress ( WbemSnmpErrorObject &a_errorObject ) ;
protected:
public:
CImpClasProv () ;
~CImpClasProv () ;
void SetProvider ( IWbemServices *provider ) ;
IWbemServices *GetParentServer () ;
IWbemServices *GetServer () ;
WbemNamespacePath *GetNamespacePath () ;
wchar_t *GetThisNamespace () ;
void SetThisNamespace ( wchar_t *thisNamespaceArg ) ;
char *GetIpAddressString () { return ipAddressString ; }
char *GetIpAddressValue () { return ipAddressValue ; }
BOOL FetchSnmpNotificationObject (
WbemSnmpErrorObject &a_errorObject ,
IWbemContext *a_Ctx
) ;
BOOL FetchNotificationObject (
WbemSnmpErrorObject &a_errorObject ,
IWbemContext *a_Ctx
) ;
IWbemClassObject *GetNotificationObject ( WbemSnmpErrorObject &a_errorObject ) ;
IWbemClassObject *GetSnmpNotificationObject ( WbemSnmpErrorObject &a_errorObject ) ;
public:
static BOOL s_Initialised ;
//Non-delegating object IUnknown
STDMETHODIMP QueryInterface ( REFIID , LPVOID FAR * ) ;
STDMETHODIMP_( ULONG ) AddRef () ;
STDMETHODIMP_( ULONG ) Release () ;
public:
/* IWbemServices methods */
HRESULT STDMETHODCALLTYPE OpenNamespace(
/* [in] */ const BSTR Namespace,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [unique][in][out] */ IWbemServices __RPC_FAR *__RPC_FAR *ppWorkingNamespace,
/* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppResult) ;
HRESULT STDMETHODCALLTYPE CancelAsyncCall(
/* [in] */ IWbemObjectSink __RPC_FAR *pSink) ;
HRESULT STDMETHODCALLTYPE QueryObjectSink(
/* [in] */ long lFlags,
/* [out] */ IWbemObjectSink __RPC_FAR *__RPC_FAR *ppResponseHandler) ;
HRESULT STDMETHODCALLTYPE GetObject(
/* [in] */ const BSTR ObjectPath,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [unique][in][out] */ IWbemClassObject __RPC_FAR *__RPC_FAR *ppObject,
/* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppCallResult) ;
HRESULT STDMETHODCALLTYPE GetObjectAsync(
/* [in] */ const BSTR ObjectPath,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ;
HRESULT STDMETHODCALLTYPE PutClass(
/* [in] */ IWbemClassObject __RPC_FAR *pObject,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppCallResult) ;
HRESULT STDMETHODCALLTYPE PutClassAsync(
/* [in] */ IWbemClassObject __RPC_FAR *pObject,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ;
HRESULT STDMETHODCALLTYPE DeleteClass(
/* [in] */ const BSTR Class,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppCallResult) ;
HRESULT STDMETHODCALLTYPE DeleteClassAsync(
/* [in] */ const BSTR Class,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ;
HRESULT STDMETHODCALLTYPE CreateClassEnum(
/* [in] */ const BSTR Superclass,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [out] */ IEnumWbemClassObject __RPC_FAR *__RPC_FAR *ppEnum) ;
HRESULT STDMETHODCALLTYPE CreateClassEnumAsync(
/* [in] */ const BSTR Superclass,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ;
HRESULT STDMETHODCALLTYPE PutInstance(
/* [in] */ IWbemClassObject __RPC_FAR *pInst,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppCallResult) ;
HRESULT STDMETHODCALLTYPE PutInstanceAsync(
/* [in] */ IWbemClassObject __RPC_FAR *pInst,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ;
HRESULT STDMETHODCALLTYPE DeleteInstance(
/* [in] */ const BSTR ObjectPath,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppCallResult) ;
HRESULT STDMETHODCALLTYPE DeleteInstanceAsync(
/* [in] */ const BSTR ObjectPath,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ;
HRESULT STDMETHODCALLTYPE CreateInstanceEnum(
/* [in] */ const BSTR Class,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [out] */ IEnumWbemClassObject __RPC_FAR *__RPC_FAR *ppEnum) ;
HRESULT STDMETHODCALLTYPE CreateInstanceEnumAsync(
/* [in] */ const BSTR Class,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ;
HRESULT STDMETHODCALLTYPE ExecQuery(
/* [in] */ const BSTR QueryLanguage,
/* [in] */ const BSTR Query,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [out] */ IEnumWbemClassObject __RPC_FAR *__RPC_FAR *ppEnum) ;
HRESULT STDMETHODCALLTYPE ExecQueryAsync(
/* [in] */ const BSTR QueryLanguage,
/* [in] */ const BSTR Query,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ;
HRESULT STDMETHODCALLTYPE ExecNotificationQuery(
/* [in] */ const BSTR QueryLanguage,
/* [in] */ const BSTR Query,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [out] */ IEnumWbemClassObject __RPC_FAR *__RPC_FAR *ppEnum) ;
HRESULT STDMETHODCALLTYPE ExecNotificationQueryAsync(
/* [in] */ const BSTR QueryLanguage,
/* [in] */ const BSTR Query,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ;
HRESULT STDMETHODCALLTYPE ExecMethod(
/* [in] */ const BSTR ObjectPath,
/* [in] */ const BSTR MethodName,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [in] */ IWbemClassObject __RPC_FAR *pInParams,
/* [unique][in][out] */ IWbemClassObject __RPC_FAR *__RPC_FAR *ppOutParams,
/* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppCallResult) ;
HRESULT STDMETHODCALLTYPE ExecMethodAsync(
/* [in] */ const BSTR ObjectPath,
/* [in] */ const BSTR MethodName,
/* [in] */ long lFlags,
/* [in] */ IWbemContext __RPC_FAR *pCtx,
/* [in] */ IWbemClassObject __RPC_FAR *pInParams,
/* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler) ;
/* IWbemProviderInit methods */
HRESULT STDMETHODCALLTYPE Initialize (
/* [in] */ LPWSTR pszUser,
/* [in] */ LONG lFlags,
/* [in] */ LPWSTR pszNamespace,
/* [in] */ LPWSTR pszLocale,
/* [in] */ IWbemServices *pCIMOM, // For anybody
/* [in] */ IWbemContext *pCtx,
/* [in] */ IWbemProviderInitSink *pInitSink // For init signals
);
} ;
#endif
| [
"polarisdp@gmail.com"
] | polarisdp@gmail.com |
1f092df0d49d197f47eda874f303cb040813fa2c | 9088eb860e84d53f22e639a5af1dd71f45859ab1 | /_Binary_Search_tress/3. Delete.cpp | a80eb8c8485a24b84d372c31ea8119f6a639e408 | [] | no_license | kritika2611/Algorithms-and-Datastructures | e6c547e5a1228401f73bb25a629779215bfdf2df | 71b3361cb9d106d72629402e6cb66f70e96da75a | refs/heads/master | 2023-01-11T04:20:22.582800 | 2020-10-23T16:22:23 | 2020-10-23T16:22:23 | 292,896,359 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,077 | cpp | //INPUT: 8 5 15 4 7 13 3 5 6 11 14 9 12 -1
#include <bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* left;
node* right;
node(int d){
this->data=d;
this->left=NULL;
this->right=NULL;
}
};
node* insert_(node* root, int d){
if(root==NULL){
node *n=new node(d);
return n;
}
if(d<=root->data) root->left=insert_(root->left,d);
else root->right=insert_(root->right,d);
return root;
}
node* BST_Tree(){
int d;
cin>>d;
if(d==-1) return NULL;
node* root=NULL;
while(d!=-1){
root=insert_(root,d);
cin>>d;
}
return root;
}
void print_BFS(node* root){
if(root==NULL){
return;
}
queue <node*> q;
q.push(root);
q.push(NULL);
while(!q.empty()){
node* f=q.front();
q.pop();
if(f==NULL){
cout<<endl;
if(!q.empty()) q.push(NULL);
continue;
}
cout<<f->data<<" ";
if(f->left!=NULL) q.push(f->left);
if(f->right!=NULL) q.push(f->right);
}
}
int max_(node* root){
//base case
if(root->right==NULL) return root->data;
//recursive case
return max_(root->right);
}
node* delete_(node* root, int d){
//base case
if(root==NULL) return NULL;
if(root->data==d){
if(root->left==NULL && root->right==NULL) return NULL; //leaf node
if(root->left==NULL || root->right==NULL){ //1 child
if(root->left!=NULL) return root->left;
else if(root->right!=NULL) return root->right;
}
//both children
int e=max_(root->left);
root->data=e;
root->left=delete_(root->left,e);
return root;
}
//recursive case
if(d<=root->data)
root->left=delete_(root->left,d);
else root->right=delete_(root->right,d);
return root;
}
int main(){
node* root=BST_Tree();
print_BFS(root); cout<<endl;
delete_(root,13);
print_BFS(root); cout<<endl;
delete_(root,15);
print_BFS(root);
return 0;
} | [
"sainikritika46@gmail.com"
] | sainikritika46@gmail.com |
2322795c69447304f98a125f432021f19d987086 | 7277d930b74618a0e09a5f5c345c0237bc092bb0 | /VirtualContest/20200521/abc137/c/main.cpp | 914fec8dd98e34bd856fa0df8309e1f242f6d451 | [] | no_license | fhiroki/atcoder | 78bccbdc10e2ca94543c965cc53874c2e99f32af | aaf50382f3c4008cd48183a06f480a103c623a7b | refs/heads/master | 2022-03-13T04:21:16.570731 | 2022-02-13T01:20:33 | 2022-02-13T01:20:33 | 245,597,349 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | cpp | #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < n; i++)
typedef long long ll;
using namespace std;
int main() {
int n;
cin >> n;
map<string, ll> a;
rep(i, n) {
string s;
cin >> s;
sort(s.begin(), s.end());
a[s]++;
}
ll ans = 0;
for (auto c : a) ans += c.second * (c.second - 1) / 2;
cout << ans << endl;
return 0;
}
| [
"hiroki976@gmail.com"
] | hiroki976@gmail.com |
9865fb4ad93619d6b79d50d2c68ec9332a49f99b | f960d194a3f837194b96f6fde779ecefdc164155 | /SampleIME/FunctionProviderSink.cpp | d3e68a32dc23d6d3452586ec45e724aefceed0ec | [] | no_license | jackfnx/NaiveIME | c2cc0a5a67878cbc42cd292f25e9e4e25d0a9a52 | d5688d142790c98c888bf7fc610f0b27a9b1afed | refs/heads/master | 2020-11-29T01:41:31.230984 | 2019-12-24T17:38:44 | 2019-12-24T17:38:44 | 229,980,720 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,902 | cpp | // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
#include "Private.h"
#include "SampleIME.h"
#include "SearchCandidateProvider.h"
//+---------------------------------------------------------------------------
//
// _InitFunctionProviderSink
//
//----------------------------------------------------------------------------
BOOL CSampleIME::_InitFunctionProviderSink()
{
ITfSourceSingle* pSourceSingle = nullptr;
BOOL ret = FALSE;
if (SUCCEEDED(_pThreadMgr->QueryInterface(IID_ITfSourceSingle, (void **)&pSourceSingle)))
{
IUnknown* punk = nullptr;
if (SUCCEEDED(QueryInterface(IID_IUnknown, (void **)&punk)))
{
if (SUCCEEDED(pSourceSingle->AdviseSingleSink(_tfClientId, IID_ITfFunctionProvider, punk)))
{
if (SUCCEEDED(CSearchCandidateProvider::CreateInstance(&_pITfFnSearchCandidateProvider, (ITfTextInputProcessorEx*)this)))
{
ret = TRUE;
}
}
punk->Release();
}
pSourceSingle->Release();
}
return ret;
}
//+---------------------------------------------------------------------------
//
// _UninitFunctionProviderSink
//
//----------------------------------------------------------------------------
void CSampleIME::_UninitFunctionProviderSink()
{
ITfSourceSingle* pSourceSingle = nullptr;
if (SUCCEEDED(_pThreadMgr->QueryInterface(IID_ITfSourceSingle, (void **)&pSourceSingle)))
{
pSourceSingle->UnadviseSingleSink(_tfClientId, IID_ITfFunctionProvider);
pSourceSingle->Release();
}
}
| [
"sixue@bbs.ustc.edu.cn"
] | sixue@bbs.ustc.edu.cn |
56cf9ce31a329955e8339d06ad640b15845724f6 | a551c17a46705a0dbfe2c2e284bc1ae2dcd1a8bb | /iwds/iwds/jni/src/include/smartsense/sensormanager.h | c856cfb5245a5eb16f91e720c2573db4d800d8db | [] | no_license | liaokesen168/slpt | 60b18542653a67c4149520aad9e3649d8a5f2154 | cdc874c15e762f8cdd2f8288b7166a30f6495109 | refs/heads/master | 2021-01-01T05:19:51.079608 | 2016-04-15T08:32:10 | 2016-04-15T08:32:10 | 56,303,858 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,085 | h | /*
* Copyright (C) 2014 Ingenic Semiconductor
*
* SunWenZhong(Fighter) <wenzhong.sun@ingenic.com, wanmyqawdr@126.com>
*
* Elf/IDWS Project
*
* 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.
*
* 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.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef SENSORMANAGER_H
#define SENSORMANAGER_H
#include <tr1/memory>
#include <string>
#include <iwds.h>
#include <utils/protectedlist.h>
#include <utils/mutex.h>
#include <smartsense/hal/sensordevice.h>
#include <smartsense/sensor.h>
class SensorEventCallback;
class SensorManager
{
public:
static std::tr1::shared_ptr<SensorManager> getInstance();
bool initialize();
int getSensorCount() const;
bool intallSensorEventCallback(
enum Sensor::SensorType sensorType,
std::tr1::shared_ptr<SensorEventCallback> callback);
std::tr1::shared_ptr<Sensor> getSensorByIndex(int index);
std::tr1::shared_ptr<Sensor> getSensorByType(
enum Sensor::SensorType type);
bool setSensorActive(enum Sensor::SensorType type, bool enable);
bool isSensorActive(enum Sensor::SensorType type);
std::string errorString() const;
bool handleEvent(sensors_event_t *hal_event);
private:
SensorManager();
std::tr1::shared_ptr<Sensor> getSensorByTypeNolock(
enum Sensor::SensorType type);
void fillSensorByHal(Sensor *sensor, const sensor_t *hal) const;
void setErrorString(const std::string &errorString);
Iwds::ProtectedList<std::tr1::shared_ptr<Sensor> > m_sensors;
mutable Iwds::Mutex m_errorStringLock;
std::string m_errorString;
std::tr1::shared_ptr<SensorDevice> m_sensorDevice;
};
#endif
| [
"kesen.liao@ingenic.com"
] | kesen.liao@ingenic.com |
c2aa11701f92297e16b12dae3bc8e6286df777dc | 36183993b144b873d4d53e7b0f0dfebedcb77730 | /GameDevelopment/Game Programming Gems 6/Section1-General_Programming/1-5-BSPTechniques/code/compiler.h | 0df929b4f0a432e51c187a5950263be1a61a43a3 | [] | no_license | alecnunn/bookresources | b95bf62dda3eb9b0ba0fb4e56025c5c7b6d605c0 | 4562f6430af5afffde790c42d0f3a33176d8003b | refs/heads/master | 2020-04-12T22:28:54.275703 | 2018-12-22T09:00:31 | 2018-12-22T09:00:31 | 162,790,540 | 20 | 14 | null | null | null | null | UTF-8 | C++ | false | false | 13,673 | h | #ifndef __COMPILER_H__
#define __COMPILER_H__
#include "geometry.h"
#include <list>
//--------------------------------------------------------------------------------
#define NODE_EMPTY 0x0
#define NODE_SOLID 0x1
#define NODE_LEAF 0x80000000
#define N_FRONT 1
#define N_BACK 0
#define FLAG_PROCESSED 0x8000000
//--------------------------------------------------------------------------------
#define _THREAD_WAIT_BRANCH_
//--------------------------------------------------------------------------------
class BaseThrCB
{
public:
BaseThrCB(){};
virtual ~BaseThrCB(){};
virtual int ThreadMain()=0;
static int ThreadFunction(void* p){return reinterpret_cast<BaseThrCB*>(p)->ThreadMain();}
void Start(){
DWORD uid;
h_t = ::CreateThread(0,0,reinterpret_cast<LPTHREAD_START_ROUTINE>(ThreadFunction), this,0,&uid);
}
void Wait(){::WaitForSingleObject(h_t, INFINITE);}
HANDLE h_t;
};
//--------------------------------------------------------------------------------
class Bsp_Tree;
class CBspNode
{
public:
CBspNode(Bsp_Tree* pBsp, DWORD dw=0)
{
_idxNodeThis = -1;
_nodeidx[0] = -1;
_nodeidx[1] = -1;
_planeIdx = -1;
_nPolys = 0;
_polyIdx = -1;
_flags = dw;
_pBsp = pBsp;
_leafIdx = -1;
_idxParent = -1;
}
virtual ~CBspNode(){}
CBspNode* Back();
CBspNode* Front();
CBspNode* Parent();
int FontIdx(){return _nodeidx[1];}
int BackIdx(){return _nodeidx[0];}
BOOL IsEmptyLeaf() {return (_flags & NODE_LEAF) && !(_flags & NODE_SOLID);}
BOOL IsLeaf() {return (_flags & NODE_LEAF);}
BOOL IsSolid() {return (_flags & NODE_SOLID);}
BOOL IsSpace() {return !(_flags & NODE_SOLID) && (_flags & NODE_LEAF);}
BOOL IsNode() {return !(_flags & NODE_LEAF);}
INLN Plane& GetPlane()const;//
INLN Poly* GetPolys(int& count);
public:
int _idxNodeThis;
int _idxParent;
int _nodeidx[2];
int _planeIdx;
int _leafIdx;
DWORD _flags;
int _nPolys;
int _polyIdx;
Bsp_Tree* _pBsp;
Box _bbox;
};
//--------------------------------------------------------------------------------
class CLeaf : public CBspNode
{
public:
CLeaf(Bsp_Tree* pBsp, DWORD dw=0):CBspNode(pBsp, dw),
_pvsIdx(-1),
_portIdxes(4),
_flags(0){
}
virtual ~CLeaf(){_portIdxes.clear();}
void AddPortalIdx(int idx){_portIdxes.push_back(idx);};
vvector<int>& GetPortalIdxes(){return _portIdxes;}
int _pvsIdx;
vvector<int> _portIdxes;
DWORD _flags;
};
//--------------------------------------------------------------------------------
class Bsp_Tree ;
struct ThrData
{
int nodeIdx;
#ifdef _THREAD_WAIT_BRANCH_
list<Poly>* polys;
#else
list<Poly> polys;
#endif //
Bsp_Tree* ptree;
};
//--------------------------------------------------------------------------------
class Compiler;
class Bsp_Tree
{
public:
enum _BSP_TYPE{BSP_LEAFY=0, BSP_TERRAIN};
public:
friend class CBspNode;
friend class Compiler;
Bsp_Tree(int expected=128){
_polys.reserve(expected);
_nodes.reserve(expected*2);
_balance = 6;
_bsptype = BSP_LEAFY;
::InitializeCriticalSection(&c_s);
};
virtual ~Bsp_Tree(){
::DeleteCriticalSection(&c_s);
Clear();
};
void SetType(_BSP_TYPE bt){
_bsptype = bt;
}
void Clear();
vvector<Poly>& GetPolys() {return _polys;};
void Process(vvector<Poly>& polys, BOOL busethreads); // virtual from base
int ThreadMain();
CBspNode* Root(){return _nodes[0];}// _pRoot;
vvector<CBspNode*>& GetNodes(){return _nodes; }
CBspNode* GetNode(int idx){ASSERT(idx < (int)_nodes.size()); return _nodes[idx];}
Plane& GetPlane(int iplane){ASSERT(iplane < (int)_planes.size()); return _planes[iplane];}
Poly& GetPoly(int idx) {ASSERT(idx < (int)_polys.size()); return _polys[idx];}
CLeaf* GetLeaf(int idx){ASSERT(idx < _leafs.size()); return _leafs[idx];}
BOOL SegmentIntersect(V3& paa, V3& pab, int node , V3& col);
int GetCurrentLeaf(V3& pov, int nodeIdx=0);
void R_Compile(int nodeIdx, list<Poly>&);
BOOL Lock(){if(b_usethreads)::EnterCriticalSection(&c_s); return 1;}
void UnLock(){if(b_usethreads)::LeaveCriticalSection(&c_s); ;}
static int T_Compile(void*);
private:
void Recurs_Or_Thread(int nodeIdx, list<Poly>& polys);
void UpdateNodeBB(CBspNode* pNode, list<Poly>& polys);
void UpdateNodeBB(CBspNode* pNode, vvector<Poly>& polys);
BOOL BuildDummyBSP(vvector<Poly>& polys);
void MakeRoot(){ASSERT(_nodes.size()==0); AddNode(new CBspNode(this));};
void BuildPlaneArray(list<Poly>& polys);
void R_TerrainCompile(int nodeIdx, list<Poly>&);
int GetBestSplitter(list<Poly>& polys, Poly* pWantPoly=0);
int Partition(CBspNode* pNode, list<Poly>&, list<Poly>&,list<Poly>&);
void PartitionTerrain(CBspNode* pNode, list<Poly>&, list<Poly>&,list<Poly>&);
void FindSplitterPlane(list<Poly>& polys, CBspNode* pNode);
Plane GetOptimSpliterPlane(list<Poly>& polys, int moe=16);
BOOL FormConvex(list<Poly>& frontPolys);
BOOL R_SegmentIntersect(int nodeIdx, V3& a, V3& b, V3& col);
void AddNode(CBspNode* pNn){
pNn->_idxNodeThis = _nodes.size();
_nodes << pNn;
if(pNn->IsEmptyLeaf())
{
pNn->_leafIdx = _leafs.size();
_leafs << (CLeaf*)pNn;
}
}
CBspNode* CreateNode(DWORD dw){
if(dw & NODE_SOLID)
return new CBspNode(this, dw);
return new CLeaf(this, dw);
}
public:
vvector<CBspNode*> _nodes;
vvector<CLeaf*> _leafs;
vvector<Poly> _polys;
vvector<Plane> _planes;
vvector<Poly>* _pInPolys;
_BSP_TYPE _bsptype;
int _reachedDepth;
int _balance;
BOOL _hitTest;
DWORD dw_deltatime;
BOOL b_usethreads;
int n_thrcount;
long n_threadsup;
HANDLE h_handles[64];
CRITICAL_SECTION c_s;
};
//------------------------------------------------------------------------------------------
INLN Plane& CBspNode::GetPlane()const
{
ASSERT(_planeIdx>=0 && _planeIdx < (int)_pBsp->_planes.size());
if(_planeIdx>=0 && _planeIdx < (int)_pBsp->_planes.size())
return _pBsp->_planes[_planeIdx];
return _pBsp->_planes[0];
};
INLN Poly* CBspNode::GetPolys(int& count){
vvector<Poly>& polys = _pBsp->GetPolys();
count = _nPolys;
return &polys[_polyIdx];
};
//--------------------------------------------------------------------------------
#define PORT_INITAL 0x1
#define PORT_DUP 0x2
#define PORT_REVERSED 0x4
#define PORT_DELETED 0x8
//--------------------------------------------------------------------------------
class Portal_Prc;
class Portal : public Plane
{
public:
Portal(){};
~Portal()
{
_vxes.clear();
_sideLIdx.clear();
_sideLIdxFinal.clear();
}
Portal(Portal_Prc* pp):_pPortPrc(pp),_flags(0),_planeIdx(-1){}
Portal(const Portal& r){
_planeIdx = r._planeIdx;
_flags = r._flags;
_vxes = r._vxes;
_sideLIdx = r._sideLIdx;
_n = r._n;
_c = r._c;
_pPortPrc = r._pPortPrc;
_idxThis = r._idxThis;
}
void Reverse(){
_flags |= PORT_REVERSED;
_n.negate();
_c=-_c;
_vxes.reverse();
}
Portal& operator=(const Portal& r){
if(this !=&r){
_planeIdx = r._planeIdx;
_flags = r._flags;
_vxes = r._vxes;
_sideLIdx = r._sideLIdx;
_n = r._n;
_c = r._c;
_pPortPrc = r._pPortPrc;
_idxThis = r._idxThis;
}
return *this;
}
V3 GetCenter()
{
V3 ret;
for(UINT i=0; i < _vxes.size(); ++i)
{
ret+=_vxes[i];
}
ret/= (REAL)_vxes.size();
return ret;
}
void AdjustVxOrder()
{
Plane tp;
GCalcNormal(&tp,_vxes[0],_vxes[1],_vxes[2]);
if(!IsZero( Vdp(tp._n, _n)-1.0f,.00625f))
{
_vxes.reverse();
GCalcNormal(&tp,_vxes[0],_vxes[1],_vxes[2]);
}
}
REL_POS Classify(Plane& plane)
{
int fronts = 0, backs = 0, coinciss = 0;
int vxes = _vxes.size();
REAL rdp;
FOREACH(vvector<V3>, _vxes, vx)
{
rdp = plane.DistTo(*vx);
if(rdp > .5f)
fronts++;
else if(rdp < -.5f)
backs++;
else{
coinciss++;
backs++;
fronts++;}
}
if (coinciss == vxes)
return ON_PLANE;
if (fronts == vxes)
return ON_FRONT;
if (backs == vxes)
return ON_BACK;
return ON_SPLIT;
}
void CopyProps(Portal& pFrom){
_planeIdx = pFrom._planeIdx;
_flags = pFrom._flags;
_sideLIdx = pFrom._sideLIdx;
_n = pFrom._n;
_c = pFrom._c;
_idxThis = pFrom._idxThis;
}
void AddSideLeafIdx(int idx){_sideLIdx<<idx;}
void Split(Plane& plane, Portal& a, Portal& b);
INLN CLeaf* BackLeaf();
INLN CLeaf* FrontLeaf();
INLN Plane& GetPlane();
void Clear(){_vxes.clear(); }
public:
int _idxThis;
int _planeIdx; // index in planes index of the BSP wich ortal belons too
DWORD _flags;
vvector<V3> _vxes;
vvector<int> _sideLIdx;
vvector<int> _sideLIdxFinal;
Portal_Prc* _pPortPrc;
};
//--------------------------------------------------------------------------------
class Portal_Prc
{
public:
friend class Portal;
friend class Compiler;
Portal_Prc(){
_pTree = 0;
}
~Portal_Prc(){Clear();}
void Process(Bsp_Tree& tree);
void Clear();
CLeaf* GetLeaf(int idx){
CBspNode* pL = _pTree->GetLeaf(idx);
ASSERT(pL->_flags & NODE_LEAF);
return (CLeaf*)pL;
}
Portal& GetPortal(int idx){return _portals[idx];}
vvector<Portal>& GetPortals(){return _portals;}
BOOL HasPortals(){return _portals.size()>0;}
private:
void CutPortalWithNodeBox(Portal& portal, Box& box,BOOL b=0);
BOOL CalculateInitialPortal(Portal&, CBspNode* );
BOOL ValidatePortal(Portal&);
BOOL DuplicatePortals(vvector<Portal>& i, vvector<Portal>& o);
Plane& GetPlane(int idx){return _pTree->GetPlane(idx);}
void AddPortal(Portal& p){
p._idxThis = _portals.size();
_portals << p;
}
void ClipWithLeafSides(CLeaf* pLeaf, Portal& portal);
public:
vvector<Portal> _portals;
Bsp_Tree* _pTree;
DWORD dw_deltatime;
};
//----------------------------------------------------------------------------------------
INLN CLeaf* Portal::BackLeaf(){
ASSERT(_sideLIdx.size()==2);
return _pPortPrc->GetLeaf(_sideLIdx[0]);
}
INLN CLeaf* Portal::FrontLeaf(){
ASSERT(_sideLIdx.size()==2);
return _pPortPrc->GetLeaf(_sideLIdx[1]);
}
Plane& Portal::GetPlane(){
return _pPortPrc->GetPlane(_planeIdx);
}
//--------------------------------------------------------------------------------
struct PortalData
{
PortalData(int sz):_portArrPvs(sz)
{
_possibleVisCount = 0;
_size = _portArrPvs.Size();
}
~PortalData(){}
int _size;
int _possibleVisCount;
CBitArray _portArrPvs;
};
//--------------------------------------------------------------------------------
class PVS_Prc
{
public:
PVS_Prc():_nleafs(0),_pvs(0),_cPvss(0){}
virtual ~PVS_Prc(){
Clear();
};
void Clear(){
delete[] _pvs; _pvs=0;
_cPvss = 0;
_portVs.deleteelements();
dw_deltatime = GetTickCount();
};
void Process(Bsp_Tree& tree, Portal_Prc& portalprc);
private:
BOOL InitalPortalVis(vvector<Portal>& rPortals);
void R_PortalFlood(Portal& portal, BYTE* pVis, int nLeaf); // flood in neghbour leaf
void PerformPVS(Portal& pOrigin, vvector<Portal>& rPortals, BYTE* prevPvs);
void GaterLeafsVis();
BOOL PortalSeesPortal(Portal& a, Portal& b);
Bsp_Tree* _pBspTree;
Portal_Prc* _pPortPrc;
int _nleafs;
public:
BYTE* _pvs;
int _cPvss;
vvector<PortalData*> _portVs;
DWORD dw_deltatime;
};
//--------------------------------------------------------------------------------
class CBsp_TechniquesDlg;
class Compiler : public BaseThrCB
{
public:
Compiler(){};
virtual ~Compiler(){};
BOOL Compile(Brush& brush, CBsp_TechniquesDlg& theDlg, BOOL usehthreads);
void Render(UINT mode, BOOL is3D);
void Clear();
private:
int ThreadMain();
void RenderBSP(BOOL is3D);
void RenderPortals(BOOL is3D);
public:
Portal_Prc portal_procesor;
PVS_Prc pvs_procesor;
Bsp_Tree bsp_tree;
CBsp_TechniquesDlg* p_dlg;
Brush* p_brush;
BOOL b_usethreads;
};
#endif // !__COMPILER_H__
| [
"alec.nunn@gmail.com"
] | alec.nunn@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.