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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9cd930ab631a29738417abe8c115fe244d0bf7ac | af89790dd0c9f5e45053aa70f036326222ff90f3 | /Zephyr/src/zephyr/gfx/Program.cpp | bf8f845ddc02ca7e4793af346f7efc09d9893a7f | [] | no_license | marcinlos/zephyr | cc6ede5903bb7842543a22980dcf1bfe94ff0ae2 | b39e146f46f905caf2f8c1d7d40029b677d505a0 | refs/heads/master | 2016-09-06T13:31:02.777957 | 2013-09-24T01:45:13 | 2013-09-24T01:45:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 181 | cpp | /*
* Program.cpp
*
* Created on: Sep 4, 2013
* Author: los
*/
#include "Program.hpp"
namespace zephyr {
namespace gfx {
} /* namespace gfx */
} /* namespace zephyr */
| [
"losiu99@gazeta.pl"
] | losiu99@gazeta.pl |
492a485e85cc86fd6479786a876bf3a51403d186 | 2c2d357c8c0d3982fe990fa31953876fbb222f14 | /Super Mario/SuperMarioBros/Menu.h | 6c1a81768773a762eab744313551fa6f64b84555 | [] | no_license | ZeevShamni/SuperMario | 5fa79e2d955a4958c002d6fa5c0f100f77113efe | 032dce174a30da569f75571be4f39c45de134e05 | refs/heads/master | 2021-01-20T21:34:49.270125 | 2017-08-29T14:27:38 | 2017-08-29T14:27:38 | 101,770,456 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,125 | h | #pragma once
#include "GameObject.h"
#include "Macro.h"
#include <thread>
class Menu
{
public:
Menu();
~Menu();
void startGame(sf::RenderWindow & window);
void disqualified(sf::RenderWindow & window);
void gameOver(sf::RenderWindow & window);
void wellDone(sf::RenderWindow & window);
void thanks(sf::RenderWindow & window);
private:
void Menu::careEvent(sf::RenderWindow& window, bool & again);
void Menu::mousePresse(sf::RenderWindow& window, bool & b, bool & again);
sf::Texture m_textureBackground;
sf::Texture m_texturePlay;
sf::Texture m_textureHelp;
sf::Texture m_textureExit;
sf::Texture m_textureInstructions;
sf::Texture m_textureBack;
sf::Texture m_textureDisqua;
sf::Texture m_textureOver;
sf::Texture m_textureDone;
sf::Texture m_textureThank;
sf::RectangleShape m_rectBackground;
sf::RectangleShape m_rectPlay;
sf::RectangleShape m_rectHelp;
sf::RectangleShape m_rectExit;
sf::RectangleShape m_rectInstructions;
sf::RectangleShape m_rectBack;
sf::RectangleShape m_rectDisqua;
sf::RectangleShape m_rectOver;
sf::RectangleShape m_rectDone;
sf::RectangleShape m_rectThank;
};
| [
"zeevshamni@gmail.com"
] | zeevshamni@gmail.com |
3e5a26b9f014274a5a213742c5c105e7e447a534 | fe87d809058b57da26ffde0b494cc4e5aef85102 | /project/ScannercodeCheckSystem/main.cpp | 39dee74615c3d456e1ffe110ccf051b8c3da5b81 | [
"MIT"
] | permissive | happyrabbit456/Qt5_dev | 4f2c354d1cead315dc1b2c43fa6a4fceb1a09131 | 1812df2f04d4b6d24eaf0195ae25d4c67d4f3da2 | refs/heads/master | 2020-07-08T05:39:16.436243 | 2020-01-02T07:53:04 | 2020-01-02T07:53:04 | 203,581,423 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | cpp | #include "mainwindow.h"
#include <QApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.setWindowTitle(QString("Manufacturing Test System"));
w.show();
// MainWindow *pMainWindow=MainWindow::getMainWindow();
// MainWindow *pMainWindow=w.getMainWindow();
// qDebug()<<pMainWindow;
return a.exec();
}
| [
"530633668@qq.com"
] | 530633668@qq.com |
697cabe3ec7a58c86becc19c44cd298b4c06efae | 383f6af87df71826218db68b1637b5a9d198865f | /jyb_paper/resource/proc_code/match_test(2010)/match_test/match.cpp | 63c9df3f5933f9068d255f2ff9728f8e595e32b7 | [] | no_license | youbin-jia/jyb_paper | 59a2c2517f366799109e3a0ae306d4a43b160dfa | cdff5c8214b8895ac31d519458ad626d24a5ca9b | refs/heads/master | 2022-04-19T23:13:22.772166 | 2020-04-20T00:11:20 | 2020-04-20T00:11:20 | 255,092,174 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 14,576 | cpp | #include<iostream>
#include<sstream>
#include<string>
#include<opencv2\opencv.hpp>
#include<opencv2\highgui\highgui.hpp>
#include<opencv2\imgproc\imgproc.hpp>
#include<opencv2\core\core.hpp>
using namespace std;
using namespace cv;
Mat src_img, src_img1,roi, part2;
Mat locateImage; //定位模板
Mat locateUp;
Mat temp;
Mat rect;//用于二次定位模板
Point matchLocation;
Point matchLocation0; //用于存储相较于大图的绝对定位信息
Point tempLocation; //用于存储微调后相较与小图的相对位置信息
Point midLocation;
int partw = 150;
int parth = 190;
int judge_count = 0;
struct Node
{
int x;
int y;
Node():x(0),y(0){};
};
template<typename T>
string ValToString(T& val)
{
ostringstream os;
os << val;
return os.str();
}
void Locate(Mat &input, Mat &input2, Point &location)
{
if (!input.data)
{
cout << ("没有单帧图像待处理,请检查内部图像数据指针是否为空!");
return;
}
Mat resultimage, srcimage1;
srcimage1 = input.clone();
int m_tw = input2.cols;
int m_th = input2.rows;
int resultimage_cols = srcimage1.cols - m_tw + 1;
int resultimage_rows = srcimage1.rows - m_th + 1;
resultimage.create(resultimage_rows, resultimage_cols, CV_32FC1);//给图像分配空间,单通道 CV_32FC1 CV_8UC4
//进行匹配和标准化 用方法1
matchTemplate(srcimage1, input2, resultimage, 4);//***********************匹配,模板搜索结果输出图像,必须为单通道32-bit位浮点型图像
normalize(resultimage, resultimage, 0, 1, NORM_MINMAX, -1, Mat());//归一化为单通道
//归一化范围(0,1) 掩码
//通过函数minMaxLoc定位最匹配的位置
double minValue, maxValue;
Point minLocation, maxLocation;
minMaxLoc(resultimage, &minValue, &maxValue, &minLocation, &maxLocation, Mat());//************找出匹配基点
//对于方法SQDIFF(0)和SQDIFF_NORMED(1),越小的数值有着更高的匹配效果,而其余的方法,数值越大匹配效果越小
location = maxLocation;
}
//bool continuity(Mat& input)
//{
// bool t_f = true;//返回值
//
// int c_long = 0;//统计行(连续单边)
// int r_count = 0;//统计单行白点数
// int beg = 0, end = 0;//单行轮廓左右极限位置
// //cout<<"rows:"<<input.rows<<" cols:"<<input.cols<<endl;
// for (int i = input.rows - 70; i < input.rows; i++)
// {
// r_count = 0;
// int r_long = 0;
// uchar* data = input.ptr<uchar>(i);
// for (int j = 1; j < input.cols; j++)
// {
// if (data[j] > 0) r_count++;
// if ((data[j]>data[j - 1]) && r_count == 1) beg = j;//单行轮廓开始位置
// if (data[j]<data[j - 1]) end = j;//轮廓结束位置
// r_long = end - beg;//单行轮廓宽度
// }
// if (r_long < 30) c_long++;//设置单边宽度阈值为30
// //cout<<"r="<<i<<" r_long:"<<r_long<<endl;
// if (r_long >= 30 && c_long<30) c_long = 0;//判断单边条件是连续30行都是单边
// if (c_long>30) break;
// }
// if (c_long >30) t_f = false;
// else t_f = true;
// //cout << "c_long:" << c_long << endl;
// return t_f;
//}
void contourProc(Mat &input, Mat &output)
{
/******前期轮廓参数等变量的声明*********/
int m_ih = input.rows;
int loc_x = 0;
int loc_y = 0;
//Mat input_dilate;
//Mat element=getStructuringElement(MORPH_RECT,Size(5,5));
//dilate(input,input_dilate,element);
//imshow("input_dilate",input_dilate);
output = Mat::zeros(input.size(), CV_8UC1);
vector<Mat> contours1;
Mat hierarchy1;
findContours(input, contours1, hierarchy1, CV_RETR_EXTERNAL, CHAIN_APPROX_NONE, Point(0, 0));
vector<Moments> mu(contours1.size());
vector<Point2f> mc(contours1.size());
int count = 0;
/*********开始对轮廓进行筛选及质心采样点等处理***************/
for (int i = 0; i< contours1.size(); i++)
{
if (contourArea(contours1[i])>200)//去除小区域干扰
{
Scalar color = Scalar(255);
//绕线区域质心
mu[i] = moments(contours1[i], false);
mc[i] = Point2d(mu[i].m10 / mu[i].m00, mu[i].m01 / mu[i].m00);
if ((mc[i].x>30 && mc[i].y>=160 && mc[i].x<120)||mc[i].y<160)//去除下面左右边角处干扰
{
//cout << "mc_x:" << mc[i].x << " mc_y" << mc[i].y << endl;
drawContours(output, contours1, i, color, 1, 8, hierarchy1, 0, Point());
}
}
}
}
//int right_node(int x, int y, Mat& img, vector<vector<int>>& marked, int max_x, int max_y)
//{
// vector<vector<int>> vv = { { 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 }, { -1, 0 }, { -1, -1 }, { 0, -1 }, { 1, -1 } };
// for (int i = 0; i < 8;i++)
// {
// if (marked[x + vv[i][0]][y + vv[i][1]]==1) continue;
// else marked[x + vv[i][0]][y + vv[i][1]] = 1;
//
// if (x + vv[i][0]<=5 || x + vv[i][0]>=img.cols-5 || y + vv[i][1]<=5 || y + vv[i][1]>=img.rows-5) continue;
//
// uchar* data0 = img.ptr<uchar>(y + vv[i][1]);
// int data = data0[x + vv[i][0]];
//
// //cout << "x=" << x + vv[i][0] << "y=" << y + vv[i][1] <<" data="<<data<< endl;
// if ((int)data != 0)
// {
// if (x + vv[i][0]>=max_x)
// {
// max_x = x + vv[i][0];
// max_y = y + vv[i][1];
// //cout << "max_x=" << x + vv[i][0] << " max_y=" << y + vv[i][1] << endl;
// }
// //cout << ">0" << endl;
// max_y=right_node(x + vv[i][0], y + vv[i][1], img, marked,max_x,max_y);
// break;
// }
// }
// //cout << "max_y=" << max_y << endl;
// return max_y;
//}
//int min_line(Mat & input_contour)
//{
// int light_count = 0, light_count0 = 0;
// int beg = 0, end = 0, beg0 = 0, end0 = 0;
// int count = 0, count0 = 0;
// int min_line = 100;
// int min_flag = 0;
// for (int i = input_contour.rows - 100; i<input_contour.rows; i++)//检测交叉点位置
// {
// uchar *data = input_contour.ptr<uchar>(i);
// for (int j = 0; j<input_contour.cols; j++)//统计单行轮廓宽度
// {
// if ((int)data[j] != 0) light_count0++;
// if ((data[j - 1]<data[j]) && (light_count0 == 1)) beg0 = j;
// if ((int)data[j]<(int)data[j - 1]) end0 = j;
// }
// if ((end0 - beg0) <= min_line) //统计最小宽度位置(交叉点)
// {
// min_line = (end0 - beg0);
// min_flag = i;
// }
// }
// return min_flag;
//}
bool turning_node(Mat & input,Mat& color_img)
{
Node up_node, middle_node, low_node;
for (int r = 70; r < input.rows; r++)
{
int light_count = 0;
uchar *data = input.ptr<uchar>(r);
for (int c = 0; c < input.cols; c++)
{
if (data[c] == 255) light_count++;
if (light_count>1) break;
if (up_node.x == 0 && data[c] == 255 && c < 60)
{
up_node.x = r;
up_node.y = c;
middle_node.x = r;
middle_node.y = c;
break;
}
if (up_node.x != 0 && low_node.x==0 && data[c] == 255 && c>middle_node.y && c - middle_node.y < 10)
{
middle_node.x = r;
middle_node.y = c;
break;
}
if (up_node.x != 0 && middle_node.x != 0 && low_node.x==0 && r - middle_node.x>30) return false;
if (middle_node.y - c>10 && low_node.x == 0 && data[c] == 255)
{
low_node.x = r;
low_node.y = c;
break;
}
if (up_node.x != 0 && data[c] == 255 && middle_node.x != 0 && low_node.x != 0 && c < low_node.y && low_node.y - c < 10)
{
low_node.x = r;
low_node.y = c;
break;
}
}
}
rectangle(color_img, Point(up_node.y, up_node.x), Point(up_node.y + 10,up_node.x + 10), Scalar(0, 0, 255), 1, 8);
rectangle(color_img, Point(middle_node.y, middle_node.x), Point(middle_node.y + 10,middle_node.x + 10), Scalar(0, 0, 255), 1, 8);
rectangle(color_img, Point(low_node.y, low_node.x), Point(low_node.y + 10,low_node.x + 10), Scalar(0, 0, 255), 1, 8);
if (middle_node.x - up_node.x < 10||low_node.x-up_node.x<40) return false;
if (low_node.x != 0) return true;
else return false;
}
void RGB_threshold(Mat& input)
{
for (int i = 0; i <input.rows; i++)//基于黄色三通道阈值处理
{
for (int j = 0; j < input.cols; j++)
{
if (input.at<Vec3b>(i, j)[2]>input.at<Vec3b>(i, j)[1])
{ // 第三通道 第二通道
input.at<Vec3b>(i, j)[0] = 255;//第一通道
input.at<Vec3b>(i, j)[1] = 255;//
input.at<Vec3b>(i, j)[2] = 255;
}
else
{
input.at<Vec3b>(i, j)[0] = 0;
input.at<Vec3b>(i, j)[1] = 0;
input.at<Vec3b>(i, j)[2] = 0;
}
}
}
}
bool judge(Mat& input, Mat& out_img)
{
judge_count++;
out_img = input.clone();
RGB_threshold(input);
Mat input_gray, input_contour;//m11,m1;
cvtColor(input, input_gray, CV_RGB2GRAY);
cv::imshow("input_gray", input_gray);
contourProc(input_gray, input_contour);
cv::imshow("first_pro", input_contour);
int min_line = 100;
int min_flag = 0;
bool T_F;
T_F = turning_node(input_contour,out_img);
if (T_F == true) cout << "合格" << endl;
else
{
if (judge_count > 1) return T_F;
cout << "不合格" << endl;
input = src_img1(Rect(tempLocation.x + matchLocation.x + 160, tempLocation.y + matchLocation.y, partw, parth + 30));
out_img = input.clone();
T_F=judge(input, out_img);
}
//bool t_f;
//t_f = continuity(input_contour);//双边连续性判定
//t_f = true;
//if (t_f == false)
//{
// cout << "该转子不合格" << endl;
// T_F = false;
//}
//else
//{
// uchar *data = input_contour.ptr<uchar>(100);
// for (int j = 0; j < input_contour.cols; j++)
// {
// vector<vector<int>> marked(200,vector<int>(200,0));//标记已访问点的标记矩阵
// if ((int)data[j] != 0)
// {
// min_flag = right_node(j, 100, input_contour, marked, 0, 0);//计算交叉点位置
// break;
// }
// }
// //调整交叉点位置(调整图像的高)**************************************************************************************
// Mat contour_temp = input_contour;
// if (min_flag<(contour_temp.rows - 35))//下调,交叉点位置(min_flag)距离下边缘大于30
// {
// int parthh = parth - (contour_temp.rows-20- min_flag);
// if (parthh < 50) parthh =parthh+10;
// input = src_img1(Rect(tempLocation.x + matchLocation.x + 160, tempLocation.y + matchLocation.y, partw, parthh));
// out_img = input.clone();
// cv::imshow("jianshao_color", input);
// cout << "下调" << endl;
// RGB_threshold(input);
// cvtColor(input, input_gray, CV_RGB2GRAY);
// cv::imshow("jianshao", input_gray);
// contourProc(input_gray, input_contour);
// }
// if (min_flag>(contour_temp.rows - 20))//上调
// {
// input = src_img1(Rect(tempLocation.x + matchLocation.x + 160, tempLocation.y + matchLocation.y, partw, parth + 20));
// out_img = input.clone();
// cv::imshow("zengjia_color", input);
// cout << "上调" << endl;
// RGB_threshold(input);
// cvtColor(input, input_gray, CV_RGB2GRAY);
// cv::imshow("zengjia", input_gray);
// contourProc(input_gray, input_contour);
// }
// //***********************************************************************************************************************************************************
// //检测下边缘宽度
// int light_count = 0, beg = 0, end = 0, count = 0;
//
// uchar *data1 = input_contour.ptr<uchar>(input.rows - 3);
// for (int j = 1; j<input_contour.cols; j++)
// {
// if ((int)data1[j] != 0) light_count++;//轮廓边缘数量
// if ((data1[j - 1]<data1[j]) && (light_count == 1)) beg = j;//轮廓初始位置
// if ((int)data1[j]<(int)data1[j - 1]) end = j;//终止位置
// }
// count = end - beg;//下边缘轮廓宽度
// if (count>30)
// {
// cout << "转子合格" << endl;//判断
// T_F = true;
// }
// else
// {
// cout << "转子不合格" << endl;
// T_F = false;
// }
//}
//cv::imshow("pro", input_contour);
return T_F;
}
void IsOk(string path, ostringstream& n,ostringstream& m) /////转子转动24次
{
Mat out_img;
bool T_F = true;
int cycleCount = 1;
int locw, loch;
//locateImage = imread("t1.jpg", 1);
//locateUp = imread("t3.jpg", 1);
locateImage = imread("96100_big_model.jpg", 1);
locateUp = imread("96100_model.jpg", 1);
locw = locateImage.cols;//740
loch = locateImage.rows;//300
int roiw = locateUp.cols;//450
int roih = locateUp.rows;//200
while (true)//一圈
{
if (cycleCount>3481) break;
string image_path = "";
image_path = path + ValToString(cycleCount) + ".jpg";
Mat src_img = imread(image_path,1);
if (src_img.empty()) { cout << image_path << "数据错误!" << endl; break; }
else cout << "读入" << image_path << "数据正常!" << endl;
imshow("Pic", src_img);
if (cycleCount != 0)//匹配
{
Locate(src_img, locateImage, matchLocation);
rect = src_img.clone();
src_img1 = src_img.clone();
rectangle(rect, Point(matchLocation.x, matchLocation.y), Point(matchLocation.x + locw, matchLocation.y + loch), Scalar(0, 0, 255), 1, 8);
temp = src_img(Rect(matchLocation.x, matchLocation.y, locw, loch));
Locate(temp, locateUp, tempLocation);
rectangle(rect, Point(tempLocation.x + matchLocation.x, tempLocation.y + matchLocation.y), Point(tempLocation.x + matchLocation.x + roiw, tempLocation.y + matchLocation.y + roih), Scalar(0, 0, 255), 1, 8);
cv::imshow("rect", rect);
cv::imshow("src_img", src_img);
roi = temp(Rect(tempLocation.x, tempLocation.y, roiw, roih));
part2 = src_img(Rect(tempLocation.x + matchLocation.x + 160, tempLocation.y + matchLocation.y, partw, parth));
}
else
{
temp = src_img(Rect(matchLocation.x, matchLocation.y, locw, loch));
rect = src_img.clone();
src_img1 = src_img.clone();
rectangle(rect, Point(matchLocation.x, matchLocation.y), Point(matchLocation.x + locw, matchLocation.y + loch), Scalar(0, 0, 255), 1, 8);
rectangle(rect, Point(tempLocation.x + matchLocation.x, tempLocation.y + matchLocation.y), Point(tempLocation.x + matchLocation.x + roiw, tempLocation.y + matchLocation.y + roih), Scalar(0, 0, 255), 1, 8);
cv::imshow("rect", rect);
cv::imshow("src_img", src_img);
part2 = src_img(Rect(tempLocation.x + matchLocation.x + 160, tempLocation.y + matchLocation.y, partw, parth));
}
judge_count = 0;
T_F = judge(part2, out_img);//分类(合格)
if (T_F == true) imwrite("C:\\Users\\Jia Youbin\\Desktop\\rotor\\gb\\good\\" + n.str() + "-" + m.str() +"-"+ ValToString(cycleCount)+".jpg", out_img);
else imwrite("C:\\Users\\Jia Youbin\\Desktop\\rotor\\gb\\bad\\"+n.str() + "-" + m.str() + "-" + ValToString(cycleCount) + ".jpg", out_img);
cycleCount++;
cv::imshow("out_img", out_img);
waitKey(0);
}
}
int main()
{
for (int n = 1; n<=1; n++)
{
ostringstream os;
os<<n;
for (int m = 1; m <= 1;m++)
{
ostringstream oss;
oss << m;
string path = "E:\jia_you_bing\\"+os.str()+"/"+oss.str()+"/";
IsOk(path, os,oss);
}
}
getchar();
}
| [
"2448396171@qq.com"
] | 2448396171@qq.com |
342ae895b197211560092313148d4c083e99c14d | bcae6681107f3102d871318619aded222714d26d | /trunk/Ej_8/p_C/banco.cpp | 1a0e815eaeb80a938e9263fd6f2bd89aa4d23ac2 | [] | no_license | gruizFING/SED | 04d7a471391031b81ed6db61f9e0a8e7821cf002 | ccef0b24ede64e0ad56c3273c5f4dc2dcfe2555f | refs/heads/master | 2020-06-16T22:32:09.469388 | 2019-07-08T02:33:00 | 2019-07-08T02:33:00 | 195,721,732 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,678 | cpp | #include "banco.hpp"
#include <eosim/core/entity.hpp>
#include <eosim/dist/numbergenerator.hpp>
#include <iostream>
using namespace eosim::core;
using namespace eosim::dist;
using namespace std;
Banco::Banco(unsigned int cantC, bool cajasSoloRetiro[], double tiempoEntreArribos, double tiempoServicioM1,
double tiempoServicioM2, double tiempoServicioS1, double tiempoServicioS2):
// se contruyen los eventos B, los eventos C, las distribuciones, los recursos y los histogramas
cantCajas(cantC),
cF(*this),
cS(*this),
eC(*this),
distArribosClientes(MT19937, tiempoEntreArribos),
distTiempoServicioNR(MT19937, tiempoServicioM1, tiempoServicioS1),
distTiempoServicioR(MT19937, tiempoServicioM2, tiempoServicioS2),
tEspera("Tiempos de Espera"),
lCola("Largos Medios de Colas", *this)
{
for (unsigned int i = 0; i < cantC; i++) {
filasCajas.push_back(new eosim::utils::EntityQueueFifo());
cajas.push_back(new Caja(cajasSoloRetiro[i]));
}
}
Banco::~Banco() {}
void Banco::init() {
// registro los eventos B
registerBEvent(&cF);
registerBEvent(&cS);
registerBEvent(&eC);
// registro las distribuciones
registerDist(&distArribosClientes);
registerDist(&distTiempoServicioNR);
registerDist(&distTiempoServicioR);
}
void Banco::doInitialSchedules() {
// agendo el primer paciente, probabilidad de 1/3 de ser operacion de retiro
nroCliente = 1;
unsigned int number = numberGen.nextLong() % 3;
Cliente* cliente = new Cliente(number == 0 ? true : false);
cliente->nro = nroCliente;
schedule(0.0, cliente, clienteF);
}
| [
"germanruizravi@gmail.com"
] | germanruizravi@gmail.com |
17ef55f7e481b5d6b37bebecc78cee6541a6ccfa | 8768518c22a13ceab29b4165f99218a0ac65b2f9 | /Examples/Expression/CPP/Src/Program.cpp | fcce239326488b2bb938a3c8cad9c170699f8197 | [
"DOC"
] | permissive | blockspacer/niveum | e4acf8adf8d6f1f1e4ee2ab652c2a86b7f8e5d92 | d1f187752795afb8bb97e6920159d9ad6c60ad54 | refs/heads/master | 2021-02-14T16:49:29.662596 | 2019-09-17T15:48:06 | 2019-09-17T15:48:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,893 | cpp | //==========================================================================
//
// File: Program.cpp
// Location: Niveum.Examples <C++ 2011>
// Description: 表达式计算工具
// Version: 2019.04.28.
// Author: F.R.C.
// Copyright(C) Public Domain
//
//==========================================================================
#include "ExpressionSchema.h"
#include "ExpressionSchemaBinary.h"
#include "Streams.h"
#include "Calculation.h"
#include "BaseSystem/StringUtilities.h"
#include <memory>
#include <exception>
#include <cwchar>
#include <cassert>
using namespace Niveum::ExpressionSchema;
namespace ExprTest
{
class Program
{
public:
static int MainInner(int argc, char **argv)
{
DisplayInfo();
Test();
return 0;
}
static void DisplayInfo()
{
std::wprintf(L"%ls\n", L"表达式测试:");
std::wprintf(L"%ls\n", L"ExprTest, Public Domain");
std::wprintf(L"%ls\n", L"F.R.C.");
}
static void Test()
{
std::shared_ptr<Assembly> a;
{
ReadableStream s(u"Assembly.bin");
a = BinaryTranslator::AssemblyFromBinary(s);
}
auto c = std::make_shared<Calculation>(a);
assert(c->Character->GetUpgradeExperience(1, 2) == 2);
TestBasic(c);
}
static void TestBasic(std::shared_ptr<Calculation> c)
{
//等于/不等于
assert(c->Test->CaseA01() == true);
assert(c->Test->CaseA02() == false);
assert(c->Test->CaseA03() == false);
assert(c->Test->CaseA04() == true);
assert(c->Test->CaseA05() == false);
assert(c->Test->CaseA06() == true);
assert(c->Test->CaseA07() == true);
assert(c->Test->CaseA08() == false);
assert(c->Test->CaseA09() == true);
assert(c->Test->CaseA10() == false);
assert(c->Test->CaseA11() == false);
assert(c->Test->CaseA12() == true);
//特殊运算符
assert(c->Test->CaseB01());
assert(c->Test->CaseB02());
assert(c->Test->CaseB03());
assert(c->Test->CaseB04());
assert(c->Test->CaseB05());
try
{
assert(c->Test->CaseB06());
assert(false);
}
catch (...)
{
assert(true);
}
assert(c->Test->CaseB07());
assert(c->Test->CaseB08());
assert(c->Test->CaseB09());
assert(c->Test->CaseB10());
assert(c->Test->CaseB11());
try
{
assert(c->Test->CaseB12());
assert(false);
}
catch (...)
{
assert(true);
}
assert(c->Test->CaseB13());
assert(c->Test->CaseB14());
assert(c->Test->CaseB15());
assert(c->Test->CaseB16());
assert(c->Test->CaseB17());
try
{
assert(c->Test->CaseB18());
assert(false);
}
catch (...)
{
assert(true);
}
assert(c->Test->CaseB19());
assert(c->Test->CaseB20());
//算术运算
assert(c->Test->CaseC01());
assert(c->Test->CaseC02());
assert(c->Test->CaseC03());
assert(c->Test->CaseC04());
assert(c->Test->CaseC05());
assert(c->Test->CaseC06());
assert(c->Test->CaseC07());
assert(c->Test->CaseC08());
assert(c->Test->CaseC09());
assert(c->Test->CaseC10());
assert(c->Test->CaseC11());
assert(c->Test->CaseC12());
assert(c->Test->CaseC13());
assert(c->Test->CaseC14());
assert(c->Test->CaseC15());
assert(c->Test->CaseC16());
assert(c->Test->CaseC17());
assert(c->Test->CaseC18());
assert(c->Test->CaseC19());
assert(c->Test->CaseC20());
assert(c->Test->CaseC21());
assert(c->Test->CaseC22());
assert(c->Test->CaseC23());
assert(c->Test->CaseC24());
assert(c->Test->CaseC25());
assert(c->Test->CaseC26());
assert(c->Test->CaseC27());
assert(c->Test->CaseC28());
assert(c->Test->CaseC29());
assert(c->Test->CaseC30());
//逻辑运算
assert(c->Test->CaseD01());
assert(c->Test->CaseD02());
//关系运算
assert(c->Test->CaseE01());
assert(c->Test->CaseE02());
assert(c->Test->CaseE03());
assert(c->Test->CaseE04());
assert(c->Test->CaseE05());
assert(c->Test->CaseE06());
assert(c->Test->CaseE07());
assert(c->Test->CaseE08());
assert(c->Test->CaseE09());
assert(c->Test->CaseE10());
assert(c->Test->CaseE11());
assert(c->Test->CaseE12());
assert(c->Test->CaseE13());
assert(c->Test->CaseE14());
assert(c->Test->CaseE15());
assert(c->Test->CaseE16());
assert(c->Test->CaseE17());
assert(c->Test->CaseE18());
assert(c->Test->CaseE19());
assert(c->Test->CaseE20());
assert(c->Test->CaseE21());
assert(c->Test->CaseE22());
assert(c->Test->CaseE23());
assert(c->Test->CaseE24());
//取整运算
assert(c->Test->CaseF01());
assert(c->Test->CaseF02());
assert(c->Test->CaseF03());
assert(c->Test->CaseF04());
assert(c->Test->CaseF05());
assert(c->Test->CaseF06());
assert(c->Test->CaseF07());
assert(c->Test->CaseF08());
assert(c->Test->CaseF09());
assert(c->Test->CaseF10());
assert(c->Test->CaseF11());
assert(c->Test->CaseF12());
assert(c->Test->CaseF13());
assert(c->Test->CaseF14());
assert(c->Test->CaseF15());
assert(c->Test->CaseF16());
assert(c->Test->CaseF17());
assert(c->Test->CaseF18());
assert(c->Test->CaseF19());
assert(c->Test->CaseF20());
assert(c->Test->CaseF21());
assert(c->Test->CaseF22());
assert(c->Test->CaseF23());
assert(c->Test->CaseF24());
assert(c->Test->CaseF25());
assert(c->Test->CaseF26());
assert(c->Test->CaseF27());
assert(c->Test->CaseF28());
assert(c->Test->CaseF29());
assert(c->Test->CaseF30());
assert(c->Test->CaseF31());
assert(c->Test->CaseF32());
assert(c->Test->CaseF33());
assert(c->Test->CaseF34());
assert(c->Test->CaseF35());
assert(c->Test->CaseF36());
assert(c->Test->CaseF37());
assert(c->Test->CaseF38());
assert(c->Test->CaseF39());
assert(c->Test->CaseF40());
assert(c->Test->CaseF41());
assert(c->Test->CaseF42());
assert(c->Test->CaseF43());
assert(c->Test->CaseF44());
assert(c->Test->CaseF45());
assert(c->Test->CaseF46());
assert(c->Test->CaseF47());
assert(c->Test->CaseF48());
assert(c->Test->CaseF49());
assert(c->Test->CaseF50());
assert(c->Test->CaseF51());
assert(c->Test->CaseF52());
assert(c->Test->CaseF53());
assert(c->Test->CaseF54());
assert(c->Test->CaseF55());
assert(c->Test->CaseF56());
assert(c->Test->CaseF57());
assert(c->Test->CaseF58());
assert(c->Test->CaseF59());
assert(c->Test->CaseF60());
assert(c->Test->CaseF61());
assert(c->Test->CaseF62());
assert(c->Test->CaseF63());
assert(c->Test->CaseF64());
assert(c->Test->CaseF65());
assert(c->Test->CaseF66());
assert(c->Test->CaseF67());
assert(c->Test->CaseF68());
assert(c->Test->CaseF69());
assert(c->Test->CaseF70());
assert(c->Test->CaseF71());
assert(c->Test->CaseF72());
assert(c->Test->CaseF73());
assert(c->Test->CaseF74());
assert(c->Test->CaseF75());
assert(c->Test->CaseF76());
assert(c->Test->CaseF77());
assert(c->Test->CaseF78());
assert(c->Test->CaseF79());
assert(c->Test->CaseF80());
assert(c->Test->CaseF81());
assert(c->Test->CaseF82());
assert(c->Test->CaseF83());
assert(c->Test->CaseF84());
assert(c->Test->CaseF85());
assert(c->Test->CaseF86());
assert(c->Test->CaseF87());
assert(c->Test->CaseF88());
assert(c->Test->CaseF89());
assert(c->Test->CaseF90());
assert(c->Test->CaseF91());
assert(c->Test->CaseF92());
assert(c->Test->CaseF93());
assert(c->Test->CaseF94());
assert(c->Test->CaseF95());
assert(c->Test->CaseF96());
assert(c->Test->CaseF97());
assert(c->Test->CaseF98());
assert(c->Test->CaseF99());
assert(c->Test->CaseFA0());
assert(c->Test->CaseFA1());
assert(c->Test->CaseFA2());
assert(c->Test->CaseFA3());
assert(c->Test->CaseFA4());
assert(c->Test->CaseFA5());
assert(c->Test->CaseFA6());
assert(c->Test->CaseFA7());
assert(c->Test->CaseFA8());
assert(c->Test->CaseFA9());
assert(c->Test->CaseFB0());
assert(c->Test->CaseFB1());
assert(c->Test->CaseFB2());
assert(c->Test->CaseFB3());
assert(c->Test->CaseFB4());
//范围限制运算
assert(c->Test->CaseG01());
assert(c->Test->CaseG02());
assert(c->Test->CaseG03());
assert(c->Test->CaseG04());
assert(c->Test->CaseG05());
assert(c->Test->CaseG06());
assert(c->Test->CaseG07());
assert(c->Test->CaseG08());
assert(c->Test->CaseG09());
assert(c->Test->CaseG10());
assert(c->Test->CaseG11());
assert(c->Test->CaseG12());
assert(c->Test->CaseG13());
assert(c->Test->CaseG14());
assert(c->Test->CaseG15());
assert(c->Test->CaseG16());
assert(c->Test->CaseG17());
assert(c->Test->CaseG18());
assert(c->Test->CaseG19());
assert(c->Test->CaseG20());
assert(c->Test->CaseG21());
assert(c->Test->CaseG22());
assert(c->Test->CaseG23());
assert(c->Test->CaseG24());
//其他运算
assert(c->Test->CaseH01());
assert(c->Test->CaseH02());
assert(c->Test->CaseH03());
assert(c->Test->CaseH04());
for (int k = 0; k < 100; k += 1)
{
assert(c->Test->CaseH05());
assert(c->Test->CaseH06());
assert(c->Test->CaseH07());
assert(c->Test->CaseH08());
assert(c->Test->CaseH09());
assert(c->Test->CaseH10());
}
assert(c->Test->CaseH11());
assert(c->Test->CaseH12());
}
};
}
#ifdef _MSC_VER
#include <io.h>
#include <fcntl.h>
void ModifyStdoutUnicode()
{
_setmode(_fileno(stdout), _O_U16TEXT);
}
#else
void ModifyStdoutUnicode()
{
}
#endif
#include <locale.h>
void SetLocale()
{
setlocale(LC_ALL, "");
}
int main(int argc, char **argv)
{
ModifyStdoutUnicode();
SetLocale();
try
{
return ExprTest::Program::MainInner(argc, argv);
}
catch (std::exception &ex)
{
std::wprintf(L"Error:\n%ls\n", systemToWideChar(ex.what()).c_str());
return -1;
}
}
| [
"r_ex@163.com"
] | r_ex@163.com |
e12c05474c1dcf424e9c07be939329afbe5a7541 | 004d53f62195057de3308868645b5831fc02d0e3 | /project 3/core/HashSet.hpp | f897e553a6c192dd793bd1d19e09252388c9a782 | [] | no_license | briandinh1/ICS-46 | 16e6c434671f42635a8c8d5c6583471db78c75ec | 6772aac52834bc9cecc717e53ffc08e63753dd57 | refs/heads/master | 2020-03-23T02:32:00.606773 | 2018-07-14T21:19:21 | 2018-07-14T21:19:21 | 140,978,761 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,028 | hpp | // HashSet.hpp
//
// ICS 46 Spring 2016
// Project #3: Set the Controls for the Heart of the Sun
//
// A HashSet is an implementation of a Set that is a separately-chained
// hash table, implemented as a dynamically-allocated array of linked
// lists. At any given time, the HashSet has a "size" indicating
// how many elements are stored within it, along with a "capacity"
// indicating the size of the array.
//
// As elements are added to the HashSet and the proportion of the HashSet's
// size to its capacity exceeds 0.8 (i.e., there are more than 80% as many
// elements as there are array cells), the HashSet should be resized so
// that it is twice as large as it was before.
//
// You are not permitted to use the containers in the C++ Standard Library
// (such as std::vector, std::list, or std::array). Instead, you'll need
// to use a dynamically-allocated array and your own linked list
// implementation; the linked list doesn't have to be its own class,
// though you can do that, if you'd like.
#ifndef HASHSET_HPP
#define HASHSET_HPP
#include <functional>
#include "Set.hpp"
template <typename T>
class HashSet : public Set<T>
{
public:
// The default capacity of the HashSet before anything has been
// added to it
static constexpr unsigned int DEFAULT_CAPACITY = 10;
// A HashFunction
typedef std::function<unsigned int(const T&)> HashFunction;
public:
// Initializes a HashSet to be empty, so that it will use the given
// hash function whenever it needs to hash an element.
HashSet(HashFunction hashFunction);
// Cleans up the HashSet so that it leaks no memory.
virtual ~HashSet();
// Initializes a new HashSet to be a copy of an existing one.
HashSet(const HashSet& s);
// Assigns an existing HashSet into another.
HashSet& operator=(const HashSet& s);
// isImplemented() should be modified to return true if you've
// decided to implement a HashSet, false otherwise.
virtual bool isImplemented() const;
// add() adds an element to the set. If the element is already in the set,
// this function has no effect. This function triggers a resizing of the
// array when the ratio of size to capacity would exceed 0.8. In the case
// where the array is resized, this function runs in linear time (with
// respect to the number of elements, assuming a good hash function);
// otherwise, it runs in constant time (again, assuming a good hash
// function).
virtual void add(const T& element);
// contains() returns true if the given element is already in the set,
// false otherwise. This function runs in constant time (with respect
// to the number of elements, assuming a good hash function).
virtual bool contains(const T& element) const;
// size() returns the number of elements in the set.
virtual unsigned int size() const;
private:
HashFunction hashFunction;
private:
struct Node
{
Node() : next(nullptr) {}
Node(T newKey, Node* next = nullptr)
: key(newKey), next(next) {}
T key;
Node* next;
};
Node** array;
int capacity;
int arraySize;
void resize();
void destroyAll();
void copyAll(const HashSet& s);
};
template <typename T>
HashSet<T>::HashSet(HashFunction hashFunction)
: hashFunction{hashFunction}, array(new Node*[DEFAULT_CAPACITY])
, capacity(DEFAULT_CAPACITY), arraySize(0)
{
for (int i = 0; i < capacity; ++i) array[i] = nullptr;
}
template <typename T>
HashSet<T>::~HashSet()
{
destroyAll();
}
template <typename T>
HashSet<T>::HashSet(const HashSet& s)
: hashFunction{s.hashFunction}, array(new Node*[s.capacity])
, capacity(s.capacity), arraySize(s.arraySize)
{
copyAll(s);
}
template <typename T>
HashSet<T>& HashSet<T>::operator=(const HashSet& s)
{
if (this != &s)
{
destroyAll();
hashFunction = s.hashFunction;
capacity = s.capacity;
arraySize = s.arraySize;
array = new Node*[s.capacity];
copyAll(s);
}
return *this;
}
template <typename T>
bool HashSet<T>::isImplemented() const
{
return true;
}
template <typename T>
void HashSet<T>::add(const T& element)
{
if (!contains(element))
{
int index = hashFunction(element) % capacity;
array[index] = new Node(element, array[index]);
++arraySize;
float ratio = (float)arraySize / (float)capacity;
if (ratio > 0.8) resize();
}
}
template <typename T>
bool HashSet<T>::contains(const T& element) const
{
int index = hashFunction(element) % capacity;
Node* temp = array[index];
while (temp)
{
if (temp->key == element) return true;
temp = temp->next;
}
return false;
}
template <typename T>
unsigned int HashSet<T>::size() const
{
return arraySize;
}
// ==========================================================
// added helper functions
template <typename T>
void HashSet<T>::resize()
{
int newCapacity = capacity * 2;
Node** newArray = new Node*[newCapacity];
for (int i = 0; i < newCapacity; ++i) newArray[i] = nullptr;
for (int i = 0; i < capacity; ++i)
{
Node* temp = array[i];
while (temp)
{
int index = hashFunction(temp->key) % newCapacity;
newArray[index] = new Node(temp->key, newArray[index]);
temp = temp->next;
}
}
destroyAll();
capacity = newCapacity;
array = newArray;
}
template <typename T>
void HashSet<T>::destroyAll()
{
for (int i = 0; i < capacity; ++i)
{
Node* temp = array[i];
while (temp)
{
Node* to_delete = temp;
temp = temp->next;
delete to_delete;
}
}
delete[] array;
}
template <typename T>
void HashSet<T>::copyAll(const HashSet& s)
{
for (int i = 0; i < capacity; ++i)
{
array[i] = nullptr;
Node* temp = s.array[i];
while (temp)
{
array[i] = new Node(temp->key, array[i]);
temp = temp->next;
}
}
}
#endif // HASHSET_HPP
| [
"briandinh1@gmail.com"
] | briandinh1@gmail.com |
8a71bd7d645870342faf1db73fa40d0855effba8 | 2a13491cbbe49be1bc15b619b3a9f3c76e535658 | /src/helper.cpp | 290295bdc25753f00690478205a0b6ebc8d0977a | [] | no_license | paulrolland1307/Motion-onset-detection | 1df2e5327eb84bd952dd2571763ed5ac36928936 | f9d4163878bdb9a24b6ca0fdb5eefac64d1cc816 | refs/heads/master | 2020-05-23T09:09:58.746396 | 2017-01-30T16:52:38 | 2017-01-30T16:52:38 | 80,441,249 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,816 | cpp | /*
* helper.cpp
*
* Created on: 22 nov. 2016
* Author: paul
*/
#include "helper.hpp"
#include "timing.h"
#include "filters.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <cmath>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/ml.hpp>
using namespace std;
using namespace cv;
using namespace cv::ml;
vector<vector<double>> readMatrix(string filename) {
ifstream input(filename.c_str());
vector<vector<double>> data;
if (input) {
while(!input.eof()) {
string line;
getline(input, line);
istringstream stm(line);
vector<double> timeWindow;
while(!stm.eof()) {
double val;
stm >> val;
timeWindow.push_back(val);
}
timeWindow.pop_back();
input >> ws;
if (!timeWindow.empty()) data.push_back(timeWindow);
}
} else {
cerr << "Couldn't open " << filename << " for reading." << endl;
}
return data;
}
vector<double> readVector(string filename) {
ifstream input(filename.c_str());
vector<double> data;
if (input) {
double value(0.0);
while(input >> value) {
data.push_back(value);
}
} else {
cerr << "Couldn't open " << filename << " for reading." << endl;
}
return data;
}
void standardizeBy(vector<vector<double>>& data, vector<double> const& means, vector<double> const& stds) {
for (size_t i(0); i < data.size(); ++i) {
for (size_t j(0); j < data[0].size(); ++j) {
data[i][j] = (data[i][j] - means[j]) / stds[j];
}
}
}
void standardize(vector<vector<double>>& features, string const& fileMeans, string const& fileStds) {
vector<double> featureMeans(features[0].size(), 0.0);
vector<double> featureStds(features[0].size(), 0.0);
ofstream meanOut(fileMeans);
ofstream stdOut(fileStds);
for(size_t j(0); j < features[0].size(); ++j) {
for (size_t i(0); i < features.size(); ++i) {
featureMeans[j] += features[i][j];
featureStds[j] += features[i][j]*features[i][j];
}
featureMeans[j] /= features.size();
featureStds[j] = sqrt(featureStds[j]/features.size() - featureMeans[j]*featureMeans[j]);
meanOut << featureMeans[j] << ' ';
stdOut << featureStds[j] << ' ';
}
meanOut.close();
stdOut.close();
for (size_t i(0); i < features.size(); ++i) {
for (size_t j(0); j < features[0].size(); ++j) {
features[i][j] = (features[i][j] - featureMeans[j]) / featureStds[j];
}
}
}
vector<vector<double>> applyPCA(vector<vector<double>> const& data, vector<vector<double>> const& pcaMatrix, int numPCAVectors) {
vector<vector<double>> result(data.size(), vector<double>(numPCAVectors, 0));
for (int i(0); i < result.size(); ++i) {
for (int j(0); j < result[0].size(); ++j) {
double value(0);
for (int k(0); k < data[0].size(); ++k) {
value += data[i][k] * pcaMatrix[k][j];
}
result[i][j] = value;
}
}
return result;
}
// Seperate features from labels
MLData split_data(vector<vector<double>> const& data, bool standardize) {
MLData mldata;
vector<vector<double>> features(data.size(), vector<double>(data[0].size()-1, 0.0));
vector<int> labels(data.size(), 0);
for (size_t i(0); i < features.size(); ++i) {
for (size_t j(0); j < features[0].size(); ++j) {
features[i][j] = data[i][j];
}
}
for (size_t i(0); i < labels.size(); ++i) {
labels[i] = data[i][data[0].size()-1];
}
mldata.features = features;
mldata.labels = labels;
return mldata;
}
double correctness(vector<int> labels, vector<int> predictions) {
double percentage(0);
for (size_t i(0); i < labels.size(); ++i) {
if (labels[i] == predictions[i]) {
percentage += 1;
}
}
return percentage / labels.size();
}
void outputResult(vector<int> const& predictions) {
ofstream out("Resources/predictions.txt");
for (auto i : predictions) {
out << i << endl;
}
out.close();
}
// Compute PCA, train the SVM model from data within file "fileTrain" and save the results
void trainSVM(string const& fileTrain, string const& fileSVM, string const& fileMeans, string const& fileStds, string const& filePCA, string const& kernel, double C, double gamma) {
int nFeaturesPerMuscle = 3;
int nMuscles = 12;
int nPCAVectors = 18;
vector<vector<double>> training = readMatrix(fileTrain);
MLData trainData = split_data(training, true);
standardize(trainData.features, fileMeans, fileStds);
// Compute PCA
if (!filePCA.empty()) {
ofstream pcaOut(filePCA);
vector<vector<double>> pcaMatrix = vector<vector<double>>(nFeaturesPerMuscle*nMuscles, vector<double>(nFeaturesPerMuscle*nMuscles, 0.0));
Mat featuresMat = Mat(trainData.features.size(), trainData.features[0].size(), CV_64F);
for (size_t i(0); i < trainData.features.size(); ++i) {
for (size_t j(0); j < trainData.features[0].size(); ++j) {
featuresMat.at<double>(i,j) = trainData.features[i][j];
}
}
PCA pca(featuresMat, Mat(), PCA::DATA_AS_ROW);
Mat pcaEigenvectors = pca.eigenvectors;
for (int i(0); i < pcaMatrix.size(); ++i) {
for (int j(0); j < pcaMatrix[0].size(); ++j) {
pcaMatrix[i][j] = pcaEigenvectors.at<double>(i, j);
pcaOut << pcaMatrix[i][j] << ' ';
}
pcaOut << endl;
}
pcaOut.close();
trainData.features = applyPCA(trainData.features, pcaMatrix, nPCAVectors);
}
cout << trainData.labels.size() << " items in training set." << endl;
int nbData = trainData.features.size();
int nbFeatures = trainData.features[0].size();
float trainingFeaturesArray[nbData][nbFeatures];
for(size_t i(0); i < nbData; ++i) {
for(size_t j(0); j < nbFeatures; ++j) {
trainingFeaturesArray[i][j] = trainData.features[i][j];
}
}
int *trainingLabelsArray = &trainData.labels[0];
Mat trainingFeaturesMat(nbData, nbFeatures, CV_32FC1, trainingFeaturesArray);
Mat trainingLabelsMat(nbData, 1, CV_32SC1, trainingLabelsArray);
Ptr<SVM> svm;
svm = SVM::create();
svm->setC(C);
svm->setType(SVM::C_SVC);
if (kernel == "RBF") {
svm->setKernel(SVM::RBF);
svm->setGamma(gamma);
}
else {
svm->setKernel(SVM::LINEAR);
}
svm->setTermCriteria(TermCriteria(TermCriteria::MAX_ITER, 100000, 1e-6));
svm->train(trainingFeaturesMat, ROW_SAMPLE, trainingLabelsMat);
svm->save(fileSVM);
}
// Evaluate the performance of an SVM (fileTest must also contain the labels)
void testSVM(string const& fileTest, string const& fileSVM, string const& fileMeans, string const& fileStds, string const& filePCA) {
Ptr<SVM> svm = SVM::load(fileSVM);
int nFeaturesPerMuscle = 3;
int nMuscles = 12;
int nPCAVectors = 18;
vector<vector<double>> testing = readMatrix(fileTest);
MLData testData = split_data(testing, false);
vector<double> means = readVector(fileMeans);
vector<double> stds = readVector(fileStds);
standardizeBy(testData.features, means,stds);
if (!filePCA.empty()) {
vector<vector<double>> pcaMatrix = readMatrix(filePCA);
testData.features = applyPCA(testData.features, pcaMatrix, nPCAVectors);
}
cout << testData.labels.size() << " items in testing set." << endl;
int nbData = testData.features.size();
int nbFeatures = testData.features[0].size();
vector<int> predictions;
for(size_t i(0); i < nbData; ++i) { // iterate over all samples
float row[nbFeatures];
for(size_t j(0); j < nbFeatures; ++j) { // record all corresponding features
row[j] = testData.features[i][j];
}
Mat sampleData(1, nbFeatures, CV_32FC1, row);
float response = svm->predict(sampleData);
if (response >= 1.0) {
predictions.push_back(1);
}
else {
predictions.push_back(0);
}
}
cout << "Percentage of correctness : " << correctness(testData.labels, predictions) << endl;
outputResult(predictions);
}
vector<double> computeFeatures(vector<vector<double>> signal, vector<double> Bbdp, vector<double> Abdp, vector<double> Blp, vector<double> Alp, vector<double> MVC, vector<vector<double>> Xs_start) {
vector<double> f(3*signal.size());
vector<vector<double>> filteredSignal = preProcessTW(Bbdp, Abdp, Blp, Alp, MVC, signal, Xs_start);
for (size_t i(0); i < signal.size(); ++i) {
f[3*i] = computeRMS(filteredSignal[i]);
f[3*i+1] = computeWaveformLength(filteredSignal[i]);
f[3*i+2] = computeZeroCrossing(signal[i]); // the Zero Crossing feature is computed on raw signal
}
return f;
}
int computeZeroCrossing(vector<double> signal) {
int zc(0);
for(size_t i(1); i < signal.size(); ++i) {
if (signal[i] * signal[i-1] < 0) {
++zc;
}
}
return zc;
}
double computeRMS(std::vector<double> const& signal) {
double rms(0.0);
for (auto i : signal) {
rms += i*i;
}
return sqrt(rms / signal.size());
}
double computeWaveformLength(vector<double> const& signal) {
double wfl(0.0);
for (size_t i(1); i < signal.size(); ++i) {
wfl += abs(signal[i] - signal[i-1]);
}
return wfl;
}
void computeFilterCoeff() {
// the sample rate of the acquisition
int fs = 1500;
int filt_order = 7;
// High pass frequency
double cof_h = 50;
// Low pass frequency
double cof_l = 450;
double W_hp = 2 * cof_h / fs;
double W_lp = 2 * cof_l / fs;
double FrequencyBands[2] = { W_hp, W_lp };
double *Atmp = 0; // temporary denominator
double *Btmp = 0; // temporary numerator
std::vector<double> A(2 * filt_order + 1, 0); // denominator
std::vector<double> B(2 * filt_order + 1, 0); // numerator
Atmp = ComputeDenCoeffs(filt_order, FrequencyBands[0], FrequencyBands[1]);
for (int k = 0; k<2 * filt_order + 1; k++)
{
A[k] = Atmp[k];
}
Btmp = ComputeNumCoeffs(filt_order, FrequencyBands[0], FrequencyBands[1], Atmp);
for (int k = 0; k<2 * filt_order + 1; k++)
{
B[k] = Btmp[k];
}
ofstream outA("Resources/A_BP.txt");
for (int k = 0; k<2 * filt_order + 1; k++) {
outA << A[k] << ' ';
}
outA.close();
ofstream outB("Resources/B_BP.txt");
for (int k = 0; k<2 * filt_order + 1; k++) {
outB << B[k] << ' ';
}
outB.close();
}
vector<vector<double>> exctractTW(vector<vector<double>> data, int jStart, int jEnd) {
vector<vector<double>> tw(data.size());
for (size_t i(0); i < tw.size(); ++i) {
for (int j(jStart); j <= jEnd; ++j) {
tw[i].push_back(data[i][j]);
}
}
return tw;
}
float predict(vector<double> features, Ptr<SVM> svm, vector<vector<double>> const& pcaMatrix, vector<double> const& means, vector<double> const& stds) {
// Standardize the features
for (size_t i(0); i < features.size(); ++i) {
features[i] = (features[i] - means[i]) / stds[i];
}
// Apply PCA
float featuresPCA[pcaMatrix[0].size()];
for (int i(0); i < pcaMatrix[0].size(); ++i) {
float val(0.0);
for (int k(0); k < features.size(); ++k) {
val += features[k] * pcaMatrix[k][i];
}
featuresPCA[i] = val;
}
// Predict using SVM
Mat sample(1, pcaMatrix[0].size(), CV_32FC1, featuresPCA);
return svm->predict(sample);
}
void startPredictions() {
// Get the parameters for the filter
vector<double> Abdp = readVector("Resources/A_BP.txt");
vector<double> Bbdp = readVector("Resources/B_BP.txt");
vector<double> Alp = readVector("Resources/A_low.txt");
vector<double> Blp = readVector("Resources/B_low.txt");
vector<double> MVC = readVector("Resources/MVC.txt");
// Get the SVM model and the data needed for preprocessing
vector<double> meansMotion = readVector("Resources/Mean_Motion.txt");
vector<double> stdsMotion = readVector("Resources/Std_Motion.txt");
vector<vector<double>> fullPCAMatrixMotion = readMatrix("Resources/coeff_PCA_Motion.txt");
Ptr<SVM> svmMotion = SVM::load("Resources/SVM_Motion.xml");
vector<double> meansGrasp = readVector("Resources/Mean_Grasp.txt");
vector<double> stdsGrasp = readVector("Resources/Std_Grasp.txt");
vector<vector<double>> fullPCAMatrixGrasp = readMatrix("Resources/coeff_PCA_Grasp.txt");
Ptr<SVM> svmGrasp = SVM::load("Resources/SVM_Grasp.xml");
// Only keep a limited number of PCA eigenvectors
int numPCAVectors = 18;
int nFeatures = 12*3;
int nMuscles = 12;
vector<vector<double>> pcaMatrixMotion(nFeatures, vector<double>(numPCAVectors, 0));
vector<vector<double>> pcaMatrixGrasp(nFeatures, vector<double>(numPCAVectors, 0));
for (size_t i(0); i < pcaMatrixGrasp.size(); ++i) {
for (size_t j(0); j < pcaMatrixGrasp[0].size(); ++j) {
pcaMatrixMotion[i][j] = fullPCAMatrixMotion[i][j];
pcaMatrixGrasp[i][j] = fullPCAMatrixGrasp[i][j];
}
}
// Get the data on which the models will be applied
vector<vector<double>> fullRawData = readMatrix("Resources/testingRaw.txt");
vector<vector<double>> rawData; //nMuscles x T matrix
for (int i(0); i < nMuscles; ++i) {
rawData.push_back(fullRawData[i]);
}
// Some variables we will need
bool motionDetection(true);
double detectedStartMotion(-1);
double detectedEndMotion(-1);
double detectedStartGrasp(-1);
double detectedEndGrasp(-1);
double meanComputationTime = 0.0;
double meanFeatureComputationTime = 0.0;
double meanPredictionTime = 0.0;
int numberTW = 0;
int count(0);
vector<vector<double>> timeWindow_prev = vector<vector<double>>(nMuscles, vector<double>(1, 0.0));
// Parameters of for the detection
int timeWindowsToWaitMotion_Start = 6;
int timeWindowsToWaitMotion_End = 6;
int timeWindowsToWaitGrasp_Start = 6;
int timeWindowsToWaitGrasp_End = 7;
// Parameters for time discretization
int fs = 1500;
double timeWindowDuration = 0.05;
int indexStart = 0;
int indexEnd = fs * timeWindowDuration - 1;
cout << endl << "Apply the models to real problem." << endl;
while(indexEnd < rawData[0].size()) {
vector<vector<double>> timeWindow = exctractTW(rawData, indexStart, indexEnd);
double startPrediction = second();
vector<double> features = computeFeatures(timeWindow, Bbdp, Abdp, Blp, Alp, MVC, timeWindow_prev);
meanFeatureComputationTime += second() - startPrediction;
float prediction;
if (motionDetection) { // Apply motion detection model
prediction = predict(features, svmMotion, pcaMatrixMotion, meansMotion, stdsMotion);
if (detectedStartMotion < 0) {
if (prediction >= 1.0) ++ count;
else count = max(count-1, 0);
} else {
if (prediction <= 0.0) ++ count;
else count = max(count-1, 0);
}
if (detectedStartMotion < 0 and count >= timeWindowsToWaitMotion_Start) {
detectedStartMotion = indexEnd / double(fs);
motionDetection = false; // switch to grasping detection once motion start has been detected
count = 0;
//cout << "Motion start detected" << endl;
}
if (detectedStartMotion >= 0 and detectedEndMotion < 0 and count >= timeWindowsToWaitMotion_End) {
detectedEndMotion = indexEnd / double(fs);
count = 0;
//cout << "Motion end detected" << endl;
}
}
else { // Apply grasping detection model
prediction = predict(features, svmGrasp, pcaMatrixGrasp, meansGrasp, stdsGrasp);
if (detectedStartGrasp< 0) {
if (prediction >= 1.0) ++ count;
else count = max(count-1, 0);
} else {
if (prediction <= 0.0) ++ count;
else count = max(count-1, 0);
}
if (detectedStartGrasp < 0 and count >= timeWindowsToWaitGrasp_Start) {
detectedStartGrasp = indexEnd / double(fs);
count = 0;
//cout << "Grasp start detected" << endl;
}
if (detectedStartGrasp >= 0 and detectedEndGrasp < 0 and count >= timeWindowsToWaitGrasp_End) {
detectedEndGrasp = indexEnd / double(fs);
motionDetection = true; // switch to motion detection once grasping end has been detected
count = 0;
//cout << "Grasp end detected" << endl;
}
}
double timePrediction = second() - startPrediction;
meanComputationTime += timePrediction;
timeWindow_prev = timeWindow; // we record the last time window for the filter
indexStart += fs * timeWindowDuration / 2;
indexEnd += fs * timeWindowDuration / 2;
++numberTW;
}
meanComputationTime /= numberTW;
meanFeatureComputationTime /= numberTW;
cout << "Detected start of motion : " << detectedStartMotion << endl;
cout << "Detected end of motion : " << detectedEndMotion << endl;
cout << "Detected start of grasp : " << detectedStartGrasp << endl;
cout << "Detected end of grasp : " << detectedEndGrasp << endl;
cout << endl;
cout << "Mean features computation time : " << meanFeatureComputationTime << " s" << endl;
cout << "Mean prediction time : " << meanComputationTime - meanFeatureComputationTime << " s" << endl;
cout << "Mean computation time : " << meanComputationTime << " s" << endl;
}
void trainAllModels() {
// Define the files into which the data will be saved
string detectionType = "Motion";
string fileSVM = "Resources/SVM_"+detectionType+".xml";
string filePCA = "Resources/coeff_PCA_"+detectionType+".txt";
//string filePCA = "Resources/identity.txt";
string fileMeans = "Resources/Mean_"+detectionType+".txt";
string fileStds = "Resources/Std_"+detectionType+".txt";
string fileTrain = "Resources/training_"+detectionType+".txt";
string fileTest = "Resources/testing_"+detectionType+".txt";
string kernel = "linear";
double C(1.0);
double startTrain = second();
cout << "Training for motion detection" << endl;
trainSVM(fileTrain, fileSVM, fileMeans, fileStds, filePCA, kernel, C);
cout << "Training time for motion : " << second() - startTrain << " s" << endl;
testSVM(fileTest, fileSVM, fileMeans, fileStds, filePCA);
cout << endl << "Training for grasping detection" << endl;
detectionType = "Grasp";
fileSVM = "Resources/SVM_"+detectionType+".xml";
filePCA = "Resources/coeff_PCA_"+detectionType+".txt";
fileMeans = "Resources/Mean_"+detectionType+".txt";
fileStds = "Resources/Std_"+detectionType+".txt";
fileTrain = "Resources/training_"+detectionType+".txt";
fileTest = "Resources/testing_"+detectionType+".txt";
kernel = "linear";
C = 1.0;
double gamma = 6.0;
startTrain = second();
trainSVM(fileTrain, fileSVM, fileMeans, fileStds, filePCA, kernel, C, gamma);
//trainSVM(fileTrain, fileSVM, fileMeans, fileStds, "", kernel, C, gamma);
cout << "Training time for grasp : " << second() - startTrain << " s" << endl;
testSVM(fileTest, fileSVM, fileMeans, fileStds, filePCA);
}
| [
"paul.rolland@epfl.ch"
] | paul.rolland@epfl.ch |
541a1728afb38fbefd74d40ef3ece73f77fdf94f | 05fc3c3168ff1345e8bcd8e51c83278b0554b440 | /group4_rwa4/src/order_manager.cpp | 0062ebba1a9aebf0fef252c144f8524bae952cf7 | [
"MIT"
] | permissive | Ip-umd/ROS-ARIAC2019-Build-A-Whole-Kit | 6d6c61cbf697d87b9ff7619f65666dc907586d9c | 24e07f7ef8d58c62586f22334e4aeb6a25b1df17 | refs/heads/master | 2022-09-22T05:26:34.556569 | 2020-05-30T03:14:35 | 2020-05-30T03:15:02 | 267,999,568 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,768 | cpp | //
// Created by zeid on 2/27/20.
//
#include "order_manager.h"
#include <osrf_gear/AGVControl.h>
#include <ros/ros.h>
#include <std_srvs/Trigger.h>
//AriacOrderManager::AriacOrderManager(): arm1_{"arm1"}, arm2_{"arm2"}
AriacOrderManager::AriacOrderManager(): arm1_{"arm1"}
{
order_subscriber_ = order_manager_nh_.subscribe(
"/ariac/orders", 10,
&AriacOrderManager::OrderCallback, this);
break_beam_subscriber_ = order_manager_nh_.subscribe(
"/ariac/break_beam_1_change", 10,
&AriacOrderManager::break_beam_callback, this);
camera_4_subscriber_ = order_manager_nh_.subscribe("/ariac/logical_camera_4", 10,
&AriacOrderManager::LogicalCamera4Callback, this);
}
AriacOrderManager::~AriacOrderManager(){}
void AriacOrderManager::OrderCallback(const osrf_gear::Order::ConstPtr& order_msg) {
ROS_WARN(">>>>> OrderCallback");
received_orders_.push_back(*order_msg);
}
void AriacOrderManager::break_beam_callback(const osrf_gear::Proximity::ConstPtr& msg) {
double temp=ros::Time::now().toSec();
if (flag_==1)
{ROS_INFO_STREAM("Time Delay observed"<<temp-camera_4_detection_time_);}
if (flag_==1 && temp-camera_4_detection_time_>4.50)
{
if(msg->object_detected) {
ROS_INFO("Part Required Detected by Break beam triggered..");
flag_break_beam_ = 1;
break_beam_time = ros::Time::now();
}
}
}
void AriacOrderManager::LogicalCamera4Callback(const osrf_gear::LogicalCameraImage::ConstPtr & image_msg){
// if (init_) return;
// ROS_INFO_STREAM_THROTTLE(10,
// "Logical camera 4: '" << image_msg->models.size() << "' objects.");
// if (image_msg->models.size() == 0)
// ROS_ERROR_STREAM("Logical Camera 4 does not see anything");
// current_parts_4_ = *image_msg;
// this->BuildProductFrames(3);
if (init_==0)
return;
for(int i=0; i<image_msg->models.size();i++){
if (image_msg->models[i].type==camera_4_product_){
//ROS_INFO_STREAM("Part Required Detected");
flag_=1;
camera_4_detection_time_=ros::Time::now().toSec();
ROS_INFO_STREAM("Camera Detected at "<<camera_4_detection_time_);
geometry_msgs::PoseStamped StampedPose_in,StampedPose_out;
StampedPose_in.header.frame_id = "/logical_camera_4_frame";
StampedPose_in.pose = image_msg->models[i].pose;
//ROS_INFO_STREAM("StampedPose_int (" << StampedPose_in.pose.position.x <<","<< StampedPose_in.pose.position.y << "," << StampedPose_in.pose.position.z<<")");
part_tf_listener_.transformPose("/world",StampedPose_in,StampedPose_out);
camera4_op_pose_=StampedPose_out.pose;
//ROS_INFO_STREAM("part is at "<<camera4_op_pose_);
}
}
if (image_msg->models.size()==0)
{flag_=0;}
init_=1;}
/**
* @brief Get the product frame for a product type
* @param product_type
* @return
*/
std::string AriacOrderManager::GetProductFrame(std::string product_type) {
//--Grab the last one from the list then remove it
if (!product_frame_list_.empty()) {
std::string frame = product_frame_list_[product_type].back();
ROS_INFO_STREAM("Frame >>>> " << frame);
product_frame_list_[product_type].pop_back();
return frame;
} else {
ROS_ERROR_STREAM("No product frame found for " << product_type);
ros::shutdown();
}
}
bool AriacOrderManager::PickAndPlace(const std::pair<std::string,geometry_msgs::Pose> product_type_pose, int agv_id) {
std::string product_type = product_type_pose.first;
ROS_WARN_STREAM("Product type >>>> " << product_type);
std::string product_frame = this->GetProductFrame(product_type);
ROS_WARN_STREAM("Product frame >>>> " << product_frame);
auto part_pose = camera_.GetPartPose("/world",product_frame);
if(product_type == "pulley_part")
part_pose.position.z += 0.08;
//--task the robot to pick up this part
bool failed_pick = arm1_.PickPart(part_pose);
ROS_WARN_STREAM("Picking up state " << failed_pick);
ros::Duration(0.5).sleep();
while(!failed_pick){
auto part_pose = camera_.GetPartPose("/world",product_frame);
failed_pick = arm1_.PickPart(part_pose);
}
//--get the pose of the object in the tray from the order
geometry_msgs::Pose drop_pose = product_type_pose.second;
geometry_msgs::PoseStamped StampedPose_in,StampedPose_out;
if(agv_id==1){
StampedPose_in.header.frame_id = "/kit_tray_1";
StampedPose_in.pose = drop_pose;
ROS_INFO_STREAM("StampedPose_int (" << StampedPose_in.pose.position.x <<","<< StampedPose_in.pose.position.y << "," << StampedPose_in.pose.position.z<<")");
part_tf_listener_.transformPose("/world",StampedPose_in,StampedPose_out);
StampedPose_out.pose.position.z += 0.1;
StampedPose_out.pose.position.y -= 0.2;
ROS_INFO_STREAM("StampedPose_out (" << StampedPose_out.pose.position.x <<","<< StampedPose_out.pose.position.y << "," << StampedPose_out.pose.position.z<<")");
}
else{
StampedPose_in.header.frame_id = "/kit_tray_2";
StampedPose_in.pose = drop_pose;
//ROS_INFO_STREAM("StampedPose_in " << StampedPose_in.pose.position.x);
part_tf_listener_.transformPose("/world",StampedPose_in,StampedPose_out);
StampedPose_out.pose.position.z += 0.1;
StampedPose_out.pose.position.y += 0.2;
//ROS_INFO_STREAM("StampedPose_out " << StampedPose_out.pose.position.x);
}
auto result = arm1_.DropPart(StampedPose_out.pose);
bool result1;
if (result==-1){
ROS_INFO_STREAM("Retrying due to defected part");
std::pair<std::string,geometry_msgs::Pose> retry_pair;
retry_pair.first=product_type;
retry_pair.second=drop_pose;
//Make it go to home first
arm1_.SendRobotHome();
ros::Duration(0.5).sleep();
arm1_.GripperToggle(false);
result1=PickAndPlace(retry_pair, int(1)); }
if (result==0)
result1=false;
else
result1=true;
return result1;
}
void AriacOrderManager::PickFromConveyer(std::string product_type)
{ camera_4_product_=product_type; //Let camera detect product_type parts
ROS_INFO_STREAM("Picking up from conveyer");
arm1_.SendRobotConveyer();
ros::Duration(0.5).sleep();
auto temp_pose=camera4_op_pose_;
temp_pose.position.z=temp_pose.position.z-0.1;
geometry_msgs::Pose temporaryPose;
temporaryPose.position.x = 1.193;
temporaryPose.position.y = 0.407;
temporaryPose.position.z = 1.175 ;
auto temp_pose_1 = temporaryPose;
temp_pose_1.position.z -= (0.120);
if (product_type=="pulley_part")
{
temp_pose_1.position.z -= (0.120+0.08);
} //Take robot to conveyer position
arm1_.GoToTarget({ temporaryPose,temp_pose_1,});
while(1)
{
init_=1;
//auto time1=ros::Time::now();
auto up_pose=camera4_op_pose_;
up_pose.position.z=up_pose.position.z+0.15;
up_pose.position.y=up_pose.position.y+0.10;
if (flag_==1){
ROS_INFO_STREAM("Moving down...");
camera4_op_pose_.position.y=camera4_op_pose_.position.y-0.25+0.008;
arm1_.GripperToggle(true);
camera4_op_pose_.position.z=camera4_op_pose_.position.z+0.02;
arm1_.GoToTarget(camera4_op_pose_);
if (arm1_.GetGripperStatus()==true)
break;
else{ros::spinOnce();
arm1_.GoToTarget(temp_pose_1);}
}
ros::spinOnce();}
init_=0;
arm1_.SendRobotHome();
ros::Duration(0.25).sleep();
}
void AriacOrderManager::ExecuteOrder() {
ROS_WARN(">>>>>> Executing order...");
//scanned_objects_ = camera_.GetParts();
//-- used to check if pick and place was successful
while (1)
{ros::spinOnce();
if (received_orders_.size()!=0)
break;
}
bool pick_n_place_success{false};
std::list<std::pair<std::string,geometry_msgs::Pose>> failed_parts;
ros::spinOnce();
// ros::Duration(1.0).sleep();
product_frame_list_ = camera_.get_product_frame_list();
for (const auto &order:received_orders_){
//auto order_id = order.order_id;
auto shipments = order.shipments;
for (const auto &shipment: shipments){
auto shipment_type = shipment.shipment_type;
for (const auto &product: shipment.products){
ROS_INFO_STREAM("Product to place is " <<product.type);
std::pair<std::string,geometry_msgs::Pose> product_type_pose;
product_type_pose.first=product.type;
product_type_pose.second=product.pose;
if (product_frame_list_.find(product.type)!=product_frame_list_.end()) //Found in list
PickAndPlace(product_type_pose, int(1));
else{
ROS_INFO_STREAM("Please pick up from conveyer" <<product.type);
PickFromConveyer(product_type_pose.first);
bool result,result1;
geometry_msgs::Pose drop_pose = product_type_pose.second;
geometry_msgs::PoseStamped StampedPose_in,StampedPose_out;
// if(agv_id==1){
StampedPose_in.header.frame_id = "/kit_tray_1";
StampedPose_in.pose = drop_pose;
ROS_INFO_STREAM("StampedPose_int (" << StampedPose_in.pose.position.x <<","<< StampedPose_in.pose.position.y << "," << StampedPose_in.pose.position.z<<")");
part_tf_listener_.transformPose("/world",StampedPose_in,StampedPose_out);
StampedPose_out.pose.position.z += 0.1;
StampedPose_out.pose.position.y -= 0.2;
ROS_INFO_STREAM("StampedPose_out (" << StampedPose_out.pose.position.x <<","<< StampedPose_out.pose.position.y << "," << StampedPose_out.pose.position.z<<")");
// }
while(1) {
result = arm1_.DropPart(StampedPose_out.pose);
ROS_INFO_STREAM("result from DropPart: "<< result);
// bool result1;
if (result==-1){
ROS_INFO_STREAM("Retrying due to defected part");
std::pair<std::string,geometry_msgs::Pose> retry_pair;
retry_pair.first=product.type;
retry_pair.second=product.pose;
//Make it go to home first
arm1_.SendRobotHome();
ros::Duration(0.5).sleep();
arm1_.GripperToggle(false);
PickFromConveyer(retry_pair.first);
//result1 = arm1_.GetGripperStatus();
}
if (result==0) break;}
// return result1;
}
}
//Write function for pick and place from conveyer
ROS_INFO_STREAM("Shipment completed Please send back AGV");
SubmitAGV(1);
ros::spinOnce();
//SubmitAGV(1);
}
ROS_INFO_STREAM("Congragulations Order Completed");
ros::spinOnce();
}
}
void AriacOrderManager::SubmitAGV(int num) {
std::string s = std::to_string(num);
ros::ServiceClient start_client =
order_manager_nh_.serviceClient<osrf_gear::AGVControl>("/ariac/agv"+s);
if (!start_client.exists()) {
ROS_INFO("Waiting for the client to be ready...");
start_client.waitForExistence();
ROS_INFO("Service started.");
}
osrf_gear::AGVControl srv;
// srv.request.kit_type = "order_0_kit_0";
start_client.call(srv);
if (!srv.response.success) {
ROS_ERROR_STREAM("Service failed!");
} else
ROS_INFO("Service succeeded.");
}
| [
"patelishan393@gmail.com"
] | patelishan393@gmail.com |
6d07d4083dad8665c5ad54854f8195d6e620c840 | 77b96e06a802b68d1384ae9b558e80046176bd83 | /TREE/tempCodeRunnerFile.cpp | 98c1eac485ac6b8d786c15957a3f2c8f7fdb562a | [] | no_license | andy01248/data-structure-cpp | 77f6b08657607c53bb355032b5284167f97bace4 | 70d4a1888628c7cd8fba7733277ce71505d6bd18 | refs/heads/master | 2020-09-22T11:42:01.715336 | 2019-12-11T16:42:52 | 2019-12-11T16:42:52 | 225,179,056 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 166 | cpp | root = Insert(root,6);
root = Insert(root,23);
root = Insert(root,59);
root = Insert(root,12);
root = Insert(root,14);
root = Insert(root,18);
root = Insert(root,28); | [
"apple@dhcp-10-248-120-234.eduroam.wireless.private.cam.ac.uk"
] | apple@dhcp-10-248-120-234.eduroam.wireless.private.cam.ac.uk |
57584c21a9b06ebabe460b6136c2dec3483e6f08 | 963451d6561400a36bb8ff81981b29e8e7912046 | /Source/TowerDefense/Private/TDTypes.cpp | 4e2ff3b4bb9cdc49967df799f9af98f06a201801 | [] | no_license | haiaimi/TowerDefense | ded5420f3007d58324672e06c49e473b3dbe4f4e | baadeebee577bb8ab0c03c3f876360fb5beda0d9 | refs/heads/master | 2020-04-11T18:55:45.946148 | 2019-03-22T13:03:05 | 2019-03-22T13:03:05 | 162,017,023 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 101 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "TDTypes.h"
| [
"wanghai1997@outlook.com"
] | wanghai1997@outlook.com |
be28e150fa1e5db51dc0cd10f47291582ef1a00f | 58ac7ce414dcbe875e26bb6fae692e3c74f39c4e | /net/quic/core/quic_session.h | f5874015ed191d32abdb12949be5a3ae1c062f27 | [] | no_license | markthomas93/tempwork | f4ba7b4620c1cb806aef40a66692115140b42c90 | 93c852f3d14c95b2d73077b00e7284ea6f416d84 | refs/heads/master | 2021-12-10T10:35:39.230466 | 2016-08-11T12:00:33 | 2016-08-11T12:00:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,842 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// A QuicSession, which demuxes a single connection to individual streams.
#ifndef NET_QUIC_QUIC_SESSION_H_
#define NET_QUIC_QUIC_SESSION_H_
#include <stddef.h>
#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "base/compiler_specific.h"
#include "base/containers/small_map.h"
#include "base/macros.h"
#include "base/strings/string_piece.h"
#include "net/base/ip_endpoint.h"
#include "net/quic/core/quic_connection.h"
#include "net/quic/core/quic_crypto_stream.h"
#include "net/quic/core/quic_packet_creator.h"
#include "net/quic/core/quic_protocol.h"
#include "net/quic/core/quic_write_blocked_list.h"
#include "net/quic/core/reliable_quic_stream.h"
namespace net {
class QuicCryptoStream;
class QuicFlowController;
class ReliableQuicStream;
namespace test {
class QuicSessionPeer;
} // namespace test
class NET_EXPORT_PRIVATE QuicSession : public QuicConnectionVisitorInterface {
public:
// CryptoHandshakeEvent enumerates the events generated by a QuicCryptoStream.
enum CryptoHandshakeEvent {
// ENCRYPTION_FIRST_ESTABLISHED indicates that a full client hello has been
// sent by a client and that subsequent packets will be encrypted. (Client
// only.)
ENCRYPTION_FIRST_ESTABLISHED,
// ENCRYPTION_REESTABLISHED indicates that a client hello was rejected by
// the server and thus the encryption key has been updated. Therefore the
// connection should resend any packets that were sent under
// ENCRYPTION_INITIAL. (Client only.)
ENCRYPTION_REESTABLISHED,
// HANDSHAKE_CONFIRMED, in a client, indicates the the server has accepted
// our handshake. In a server it indicates that a full, valid client hello
// has been received. (Client and server.)
HANDSHAKE_CONFIRMED,
};
// Takes ownership of |connection|.
QuicSession(QuicConnection* connection, const QuicConfig& config);
~QuicSession() override;
virtual void Initialize();
// QuicConnectionVisitorInterface methods:
void OnStreamFrame(const QuicStreamFrame& frame) override;
void OnRstStream(const QuicRstStreamFrame& frame) override;
void OnGoAway(const QuicGoAwayFrame& frame) override;
void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override;
void OnBlockedFrame(const QuicBlockedFrame& frame) override;
void OnConnectionClosed(QuicErrorCode error,
const std::string& error_details,
ConnectionCloseSource source) override;
void OnWriteBlocked() override {}
void OnSuccessfulVersionNegotiation(const QuicVersion& version) override;
void OnCanWrite() override;
void OnCongestionWindowChange(QuicTime /*now*/) override {}
void OnConnectionMigration(PeerAddressChangeType type) override {}
// Deletes streams that are safe to be deleted now that it's safe to do so (no
// other operations are being done on the streams at this time).
void PostProcessAfterData() override;
bool WillingAndAbleToWrite() const override;
bool HasPendingHandshake() const override;
bool HasOpenDynamicStreams() const override;
void OnPathDegrading() override;
// Called on every incoming packet. Passes |packet| through to |connection_|.
virtual void ProcessUdpPacket(const IPEndPoint& self_address,
const IPEndPoint& peer_address,
const QuicReceivedPacket& packet);
// Called by streams when they want to write data to the peer.
// Returns a pair with the number of bytes consumed from data, and a boolean
// indicating if the fin bit was consumed. This does not indicate the data
// has been sent on the wire: it may have been turned into a packet and queued
// if the socket was unexpectedly blocked.
// If provided, |ack_notifier_delegate| will be registered to be notified when
// we have seen ACKs for all packets resulting from this call.
virtual QuicConsumedData WritevData(
ReliableQuicStream* stream,
QuicStreamId id,
QuicIOVector iov,
QuicStreamOffset offset,
bool fin,
QuicAckListenerInterface* ack_notifier_delegate);
// Called by streams when they want to close the stream in both directions.
virtual void SendRstStream(QuicStreamId id,
QuicRstStreamErrorCode error,
QuicStreamOffset bytes_written);
// Called when the session wants to go away and not accept any new streams.
void SendGoAway(QuicErrorCode error_code, const std::string& reason);
// Removes the stream associated with 'stream_id' from the active stream map.
virtual void CloseStream(QuicStreamId stream_id);
// Returns true if outgoing packets will be encrypted, even if the server
// hasn't confirmed the handshake yet.
virtual bool IsEncryptionEstablished();
// For a client, returns true if the server has confirmed our handshake. For
// a server, returns true if a full, valid client hello has been received.
virtual bool IsCryptoHandshakeConfirmed();
// Called by the QuicCryptoStream when a new QuicConfig has been negotiated.
virtual void OnConfigNegotiated();
// Called by the QuicCryptoStream when the handshake enters a new state.
//
// Clients will call this function in the order:
// ENCRYPTION_FIRST_ESTABLISHED
// zero or more ENCRYPTION_REESTABLISHED
// HANDSHAKE_CONFIRMED
//
// Servers will simply call it once with HANDSHAKE_CONFIRMED.
virtual void OnCryptoHandshakeEvent(CryptoHandshakeEvent event);
// Called by the QuicCryptoStream when a handshake message is sent.
virtual void OnCryptoHandshakeMessageSent(
const CryptoHandshakeMessage& message);
// Called by the QuicCryptoStream when a handshake message is received.
virtual void OnCryptoHandshakeMessageReceived(
const CryptoHandshakeMessage& message);
// Returns mutable config for this session. Returned config is owned
// by QuicSession.
QuicConfig* config();
// Returns true if the stream existed previously and has been closed.
// Returns false if the stream is still active or if the stream has
// not yet been created.
bool IsClosedStream(QuicStreamId id);
QuicConnection* connection() { return connection_.get(); }
const QuicConnection* connection() const { return connection_.get(); }
size_t num_active_requests() const { return dynamic_stream_map_.size(); }
const IPEndPoint& peer_address() const { return connection_->peer_address(); }
QuicConnectionId connection_id() const {
return connection_->connection_id();
}
// Returns the number of currently open streams, excluding the reserved
// headers and crypto streams, and never counting unfinished streams.
virtual size_t GetNumActiveStreams() const;
// Returns the number of currently open peer initiated streams, excluding the
// reserved headers and crypto streams.
virtual size_t GetNumOpenIncomingStreams() const;
// Returns the number of currently open self initiated streams, excluding the
// reserved headers and crypto streams.
virtual size_t GetNumOpenOutgoingStreams() const;
// Returns the number of "available" streams, the stream ids less than
// largest_peer_created_stream_id_ that have not yet been opened.
virtual size_t GetNumAvailableStreams() const;
// Add the stream to the session's write-blocked list because it is blocked by
// connection-level flow control but not by its own stream-level flow control.
// The stream will be given a chance to write when a connection-level
// WINDOW_UPDATE arrives.
void MarkConnectionLevelWriteBlocked(QuicStreamId id);
// Returns true if the session has data to be sent, either queued in the
// connection, or in a write-blocked stream.
bool HasDataToWrite() const;
bool goaway_sent() const;
bool goaway_received() const;
QuicErrorCode error() const { return error_; }
Perspective perspective() const { return connection_->perspective(); }
QuicFlowController* flow_controller() { return &flow_controller_; }
// Returns true if connection is flow controller blocked.
bool IsConnectionFlowControlBlocked() const;
// Returns true if any stream is flow controller blocked.
bool IsStreamFlowControlBlocked();
size_t max_open_incoming_streams() const {
return max_open_incoming_streams_;
}
size_t max_open_outgoing_streams() const {
return max_open_outgoing_streams_;
}
size_t MaxAvailableStreams() const;
// Returns existing static or dynamic stream with id = |stream_id|. If no
// such stream exists, and |stream_id| is a peer-created dynamic stream id,
// then a new stream is created and returned. In all other cases, nullptr is
// returned.
ReliableQuicStream* GetOrCreateStream(const QuicStreamId stream_id);
// Mark a stream as draining.
virtual void StreamDraining(QuicStreamId id);
// Returns true if this stream should yield writes to another blocked stream.
bool ShouldYield(QuicStreamId stream_id);
protected:
using StaticStreamMap =
base::SmallMap<std::unordered_map<QuicStreamId, ReliableQuicStream*>, 2>;
using DynamicStreamMap =
base::SmallMap<std::unordered_map<QuicStreamId, ReliableQuicStream*>, 10>;
// Creates a new stream to handle a peer-initiated stream.
// Caller does not own the returned stream.
// Returns nullptr and does error handling if the stream can not be created.
virtual ReliableQuicStream* CreateIncomingDynamicStream(QuicStreamId id) = 0;
// Create a new stream to handle a locally-initiated stream.
// Caller does not own the returned stream.
// Returns nullptr if max streams have already been opened.
virtual ReliableQuicStream* CreateOutgoingDynamicStream(
SpdyPriority priority) = 0;
// Return the reserved crypto stream.
virtual QuicCryptoStream* GetCryptoStream() = 0;
// Adds |stream| to the dynamic stream map.
// Takes ownership of |stream|.
virtual void ActivateStream(ReliableQuicStream* stream);
// Returns the stream ID for a new outgoing stream, and increments the
// underlying counter.
QuicStreamId GetNextOutgoingStreamId();
// Returns existing stream with id = |stream_id|. If no such stream exists,
// and |stream_id| is a peer-created id, then a new stream is created and
// returned. However if |stream_id| is a locally-created id and no such stream
// exists, the connection is closed.
// Caller does not own the returned stream.
ReliableQuicStream* GetOrCreateDynamicStream(QuicStreamId stream_id);
// Performs the work required to close |stream_id|. If |locally_reset|
// then the stream has been reset by this endpoint, not by the peer.
virtual void CloseStreamInner(QuicStreamId stream_id, bool locally_reset);
// When a stream is closed locally, it may not yet know how many bytes the
// peer sent on that stream.
// When this data arrives (via stream frame w. FIN, or RST) this method
// is called, and correctly updates the connection level flow controller.
void UpdateFlowControlOnFinalReceivedByteOffset(
QuicStreamId id,
QuicStreamOffset final_byte_offset);
// Return true if given stream is peer initiated.
bool IsIncomingStream(QuicStreamId id) const;
StaticStreamMap& static_streams() { return static_stream_map_; }
const StaticStreamMap& static_streams() const { return static_stream_map_; }
DynamicStreamMap& dynamic_streams() { return dynamic_stream_map_; }
const DynamicStreamMap& dynamic_streams() const {
return dynamic_stream_map_;
}
std::vector<ReliableQuicStream*>* closed_streams() {
return &closed_streams_;
}
void set_max_open_incoming_streams(size_t max_open_incoming_streams);
void set_max_open_outgoing_streams(size_t max_open_outgoing_streams);
void set_largest_peer_created_stream_id(
QuicStreamId largest_peer_created_stream_id) {
largest_peer_created_stream_id_ = largest_peer_created_stream_id;
}
void set_error(QuicErrorCode error) { error_ = error; }
QuicWriteBlockedList* write_blocked_streams() {
return &write_blocked_streams_;
}
size_t GetNumDynamicOutgoingStreams() const;
size_t GetNumDrainingOutgoingStreams() const;
size_t num_locally_closed_incoming_streams_highest_offset() const {
return num_locally_closed_incoming_streams_highest_offset_;
}
size_t GetNumLocallyClosedOutgoingStreamsHighestOffset() const;
// Returns true if the stream is still active.
bool IsOpenStream(QuicStreamId id);
QuicStreamId next_outgoing_stream_id() const {
return next_outgoing_stream_id_;
}
// Close connection when receive a frame for a locally-created nonexistant
// stream.
// Prerequisite: IsClosedStream(stream_id) == false
// Server session might need to override this method to allow server push
// stream to be promised before creating an active stream.
virtual void HandleFrameOnNonexistentOutgoingStream(QuicStreamId stream_id);
bool MaybeIncreaseLargestPeerStreamId(const QuicStreamId stream_id);
void InsertLocallyClosedStreamsHighestOffset(const QuicStreamId id,
QuicStreamOffset offset);
// If stream is a locally closed stream, this RST will update FIN offset.
// Otherwise stream is a preserved stream and the behavior of it depends on
// derived class's own implementation.
virtual void HandleRstOnValidNonexistentStream(
const QuicRstStreamFrame& frame);
private:
friend class test::QuicSessionPeer;
// Called in OnConfigNegotiated when we receive a new stream level flow
// control window in a negotiated config. Closes the connection if invalid.
void OnNewStreamFlowControlWindow(QuicStreamOffset new_window);
// Called in OnConfigNegotiated when we receive a new connection level flow
// control window in a negotiated config. Closes the connection if invalid.
void OnNewSessionFlowControlWindow(QuicStreamOffset new_window);
// Keep track of highest received byte offset of locally closed streams, while
// waiting for a definitive final highest offset from the peer.
std::map<QuicStreamId, QuicStreamOffset>
locally_closed_streams_highest_offset_;
std::unique_ptr<QuicConnection> connection_;
std::vector<ReliableQuicStream*> closed_streams_;
QuicConfig config_;
// The maximum number of outgoing streams this connection can open.
size_t max_open_outgoing_streams_;
// The maximum number of incoming streams this connection will allow.
size_t max_open_incoming_streams_;
// Static streams, such as crypto and header streams. Owned by child classes
// that create these streams.
StaticStreamMap static_stream_map_;
// Map from StreamId to pointers to streams. Owns the streams.
DynamicStreamMap dynamic_stream_map_;
// The ID to use for the next outgoing stream.
QuicStreamId next_outgoing_stream_id_;
// Set of stream ids that are less than the largest stream id that has been
// received, but are nonetheless available to be created.
std::unordered_set<QuicStreamId> available_streams_;
// Set of stream ids that are "draining" -- a FIN has been sent and received,
// but the stream object still exists because not all the received data has
// been consumed.
std::unordered_set<QuicStreamId> draining_streams_;
// A list of streams which need to write more data.
QuicWriteBlockedList write_blocked_streams_;
QuicStreamId largest_peer_created_stream_id_;
// A counter for peer initiated streams which are in the dynamic_stream_map_.
size_t num_dynamic_incoming_streams_;
// A counter for peer initiated streams which are in the draining_streams_.
size_t num_draining_incoming_streams_;
// A counter for peer initiated streams which are in the
// locally_closed_streams_highest_offset_.
size_t num_locally_closed_incoming_streams_highest_offset_;
// The latched error with which the connection was closed.
QuicErrorCode error_;
// Used for connection-level flow control.
QuicFlowController flow_controller_;
// The stream id which was last popped in OnCanWrite, or 0, if not under the
// call stack of OnCanWrite.
QuicStreamId currently_writing_stream_id_;
DISALLOW_COPY_AND_ASSIGN(QuicSession);
};
} // namespace net
#endif // NET_QUIC_QUIC_SESSION_H_
| [
"gaoxiaojun@gmail.com"
] | gaoxiaojun@gmail.com |
8701370054c1e56a704b08d85daf3941a0f952f1 | c4ed4a33172e01504879c0543f7873880ebf5376 | /cores/pico/picorv32/demo/src/riscv_SRL.cc | e184607613d8616d337e1e5c02e9686c08ba543a | [
"MIT",
"ISC",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | yuex1994/iw_imdb | fb60b616c696fde80db7b19c22ef1f212c2d19ef | 946ce12d1b28075bfc513b2baf0f30601d36558c | refs/heads/master | 2021-01-06T16:04:16.626959 | 2020-04-26T16:20:58 | 2020-04-26T16:20:58 | 241,388,900 | 1 | 1 | MIT | 2020-02-29T19:26:37 | 2020-02-18T14:55:52 | C++ | UTF-8 | C++ | false | false | 7,380 | cc | #include "riscv.h"
void riscv::decode_riscv_SRL_update() {
c_2847 = (riscv_pc + 4);
riscv_pc_next = c_2847;
riscv_x0_next = 0;
uint5_t tmp_17 = 0 - 1;
c_17 = static_cast<uint5_t> ((riscv_inst >> 7) & tmp_17);
c_3733 = c_17 == 1;
uint5_t tmp_19 = 0 - 1;
c_19 = static_cast<uint5_t> ((riscv_inst >> 15) & tmp_19);
c_2681 = c_19 == 31;
c_2676 = c_19 == 30;
c_2671 = c_19 == 29;
c_2666 = c_19 == 28;
c_2661 = c_19 == 27;
c_2656 = c_19 == 26;
c_2651 = c_19 == 25;
c_2646 = c_19 == 24;
c_2641 = c_19 == 23;
c_2636 = c_19 == 22;
c_2631 = c_19 == 21;
c_2626 = c_19 == 20;
c_2621 = c_19 == 19;
c_2616 = c_19 == 18;
c_2611 = c_19 == 17;
c_2606 = c_19 == 16;
c_2601 = c_19 == 15;
c_2596 = c_19 == 14;
c_2591 = c_19 == 13;
c_2586 = c_19 == 12;
c_2581 = c_19 == 11;
c_2576 = c_19 == 10;
c_2571 = c_19 == 9;
c_2566 = c_19 == 8;
c_2561 = c_19 == 7;
c_2556 = c_19 == 6;
c_2551 = c_19 == 5;
c_2546 = c_19 == 4;
c_2541 = c_19 == 3;
c_2536 = c_19 == 2;
c_2531 = c_19 == 1;
c_2533 = (c_2531) ? riscv_x1 : 0;
c_2538 = (c_2536) ? riscv_x2 : c_2533;
c_2543 = (c_2541) ? riscv_x3 : c_2538;
c_2548 = (c_2546) ? riscv_x4 : c_2543;
c_2553 = (c_2551) ? riscv_x5 : c_2548;
c_2558 = (c_2556) ? riscv_x6 : c_2553;
c_2563 = (c_2561) ? riscv_x7 : c_2558;
c_2568 = (c_2566) ? riscv_x8 : c_2563;
c_2573 = (c_2571) ? riscv_x9 : c_2568;
c_2578 = (c_2576) ? riscv_x10 : c_2573;
c_2583 = (c_2581) ? riscv_x11 : c_2578;
c_2588 = (c_2586) ? riscv_x12 : c_2583;
c_2593 = (c_2591) ? riscv_x13 : c_2588;
c_2598 = (c_2596) ? riscv_x14 : c_2593;
c_2603 = (c_2601) ? riscv_x15 : c_2598;
c_2608 = (c_2606) ? riscv_x16 : c_2603;
c_2613 = (c_2611) ? riscv_x17 : c_2608;
c_2618 = (c_2616) ? riscv_x18 : c_2613;
c_2623 = (c_2621) ? riscv_x19 : c_2618;
c_2628 = (c_2626) ? riscv_x20 : c_2623;
c_2633 = (c_2631) ? riscv_x21 : c_2628;
c_2638 = (c_2636) ? riscv_x22 : c_2633;
c_2643 = (c_2641) ? riscv_x23 : c_2638;
c_2648 = (c_2646) ? riscv_x24 : c_2643;
c_2653 = (c_2651) ? riscv_x25 : c_2648;
c_2658 = (c_2656) ? riscv_x26 : c_2653;
c_2663 = (c_2661) ? riscv_x27 : c_2658;
c_2668 = (c_2666) ? riscv_x28 : c_2663;
c_2673 = (c_2671) ? riscv_x29 : c_2668;
c_2678 = (c_2676) ? riscv_x30 : c_2673;
c_2683 = (c_2681) ? riscv_x31 : c_2678;
uint5_t tmp_21 = 0 - 1;
c_21 = static_cast<uint5_t> ((riscv_inst >> 20) & tmp_21);
c_2838 = c_21 == 31;
c_2833 = c_21 == 30;
c_2828 = c_21 == 29;
c_2823 = c_21 == 28;
c_2818 = c_21 == 27;
c_2813 = c_21 == 26;
c_2808 = c_21 == 25;
c_2803 = c_21 == 24;
c_2798 = c_21 == 23;
c_2793 = c_21 == 22;
c_2788 = c_21 == 21;
c_2783 = c_21 == 20;
c_2778 = c_21 == 19;
c_2773 = c_21 == 18;
c_2768 = c_21 == 17;
c_2763 = c_21 == 16;
c_2758 = c_21 == 15;
c_2753 = c_21 == 14;
c_2748 = c_21 == 13;
c_2743 = c_21 == 12;
c_2738 = c_21 == 11;
c_2733 = c_21 == 10;
c_2728 = c_21 == 9;
c_2723 = c_21 == 8;
c_2718 = c_21 == 7;
c_2713 = c_21 == 6;
c_2708 = c_21 == 5;
c_2703 = c_21 == 4;
c_2698 = c_21 == 3;
c_2693 = c_21 == 2;
c_2688 = c_21 == 1;
c_2690 = (c_2688) ? riscv_x1 : 0;
c_2695 = (c_2693) ? riscv_x2 : c_2690;
c_2700 = (c_2698) ? riscv_x3 : c_2695;
c_2705 = (c_2703) ? riscv_x4 : c_2700;
c_2710 = (c_2708) ? riscv_x5 : c_2705;
c_2715 = (c_2713) ? riscv_x6 : c_2710;
c_2720 = (c_2718) ? riscv_x7 : c_2715;
c_2725 = (c_2723) ? riscv_x8 : c_2720;
c_2730 = (c_2728) ? riscv_x9 : c_2725;
c_2735 = (c_2733) ? riscv_x10 : c_2730;
c_2740 = (c_2738) ? riscv_x11 : c_2735;
c_2745 = (c_2743) ? riscv_x12 : c_2740;
c_2750 = (c_2748) ? riscv_x13 : c_2745;
c_2755 = (c_2753) ? riscv_x14 : c_2750;
c_2760 = (c_2758) ? riscv_x15 : c_2755;
c_2765 = (c_2763) ? riscv_x16 : c_2760;
c_2770 = (c_2768) ? riscv_x17 : c_2765;
c_2775 = (c_2773) ? riscv_x18 : c_2770;
c_2780 = (c_2778) ? riscv_x19 : c_2775;
c_2785 = (c_2783) ? riscv_x20 : c_2780;
c_2790 = (c_2788) ? riscv_x21 : c_2785;
c_2795 = (c_2793) ? riscv_x22 : c_2790;
c_2800 = (c_2798) ? riscv_x23 : c_2795;
c_2805 = (c_2803) ? riscv_x24 : c_2800;
c_2810 = (c_2808) ? riscv_x25 : c_2805;
c_2815 = (c_2813) ? riscv_x26 : c_2810;
c_2820 = (c_2818) ? riscv_x27 : c_2815;
c_2825 = (c_2823) ? riscv_x28 : c_2820;
c_2830 = (c_2828) ? riscv_x29 : c_2825;
c_2835 = (c_2833) ? riscv_x30 : c_2830;
c_2840 = (c_2838) ? riscv_x31 : c_2835;
uint5_t tmp_2841 = 0 - 1;
c_2841 = static_cast<uint5_t> ((c_2840 >> 0) & tmp_2841);
c_2843 = 0;
c_2843 = static_cast<uint32_t>(c_2841);
c_3728 = (c_2683 >> c_2843);
c_3735 = (c_3733) ? c_3728 : riscv_x1;
riscv_x1_next = c_3735;
c_3778 = c_17 == 10;
c_3780 = (c_3778) ? c_3728 : riscv_x10;
riscv_x10_next = c_3780;
c_3783 = c_17 == 11;
c_3785 = (c_3783) ? c_3728 : riscv_x11;
riscv_x11_next = c_3785;
c_3788 = c_17 == 12;
c_3790 = (c_3788) ? c_3728 : riscv_x12;
riscv_x12_next = c_3790;
c_3793 = c_17 == 13;
c_3795 = (c_3793) ? c_3728 : riscv_x13;
riscv_x13_next = c_3795;
c_3798 = c_17 == 14;
c_3800 = (c_3798) ? c_3728 : riscv_x14;
riscv_x14_next = c_3800;
c_3803 = c_17 == 15;
c_3805 = (c_3803) ? c_3728 : riscv_x15;
riscv_x15_next = c_3805;
c_3808 = c_17 == 16;
c_3810 = (c_3808) ? c_3728 : riscv_x16;
riscv_x16_next = c_3810;
c_3813 = c_17 == 17;
c_3815 = (c_3813) ? c_3728 : riscv_x17;
riscv_x17_next = c_3815;
c_3818 = c_17 == 18;
c_3820 = (c_3818) ? c_3728 : riscv_x18;
riscv_x18_next = c_3820;
c_3823 = c_17 == 19;
c_3825 = (c_3823) ? c_3728 : riscv_x19;
riscv_x19_next = c_3825;
c_3738 = c_17 == 2;
c_3740 = (c_3738) ? c_3728 : riscv_x2;
riscv_x2_next = c_3740;
c_3828 = c_17 == 20;
c_3830 = (c_3828) ? c_3728 : riscv_x20;
riscv_x20_next = c_3830;
c_3833 = c_17 == 21;
c_3835 = (c_3833) ? c_3728 : riscv_x21;
riscv_x21_next = c_3835;
c_3838 = c_17 == 22;
c_3840 = (c_3838) ? c_3728 : riscv_x22;
riscv_x22_next = c_3840;
c_3843 = c_17 == 23;
c_3845 = (c_3843) ? c_3728 : riscv_x23;
riscv_x23_next = c_3845;
c_3848 = c_17 == 24;
c_3850 = (c_3848) ? c_3728 : riscv_x24;
riscv_x24_next = c_3850;
c_3853 = c_17 == 25;
c_3855 = (c_3853) ? c_3728 : riscv_x25;
riscv_x25_next = c_3855;
c_3858 = c_17 == 26;
c_3860 = (c_3858) ? c_3728 : riscv_x26;
riscv_x26_next = c_3860;
c_3863 = c_17 == 27;
c_3865 = (c_3863) ? c_3728 : riscv_x27;
riscv_x27_next = c_3865;
c_3868 = c_17 == 28;
c_3870 = (c_3868) ? c_3728 : riscv_x28;
riscv_x28_next = c_3870;
c_3873 = c_17 == 29;
c_3875 = (c_3873) ? c_3728 : riscv_x29;
riscv_x29_next = c_3875;
c_3743 = c_17 == 3;
c_3745 = (c_3743) ? c_3728 : riscv_x3;
riscv_x3_next = c_3745;
c_3878 = c_17 == 30;
c_3880 = (c_3878) ? c_3728 : riscv_x30;
riscv_x30_next = c_3880;
c_3883 = c_17 == 31;
c_3885 = (c_3883) ? c_3728 : riscv_x31;
riscv_x31_next = c_3885;
c_3748 = c_17 == 4;
c_3750 = (c_3748) ? c_3728 : riscv_x4;
riscv_x4_next = c_3750;
c_3753 = c_17 == 5;
c_3755 = (c_3753) ? c_3728 : riscv_x5;
riscv_x5_next = c_3755;
c_3758 = c_17 == 6;
c_3760 = (c_3758) ? c_3728 : riscv_x6;
riscv_x6_next = c_3760;
c_3763 = c_17 == 7;
c_3765 = (c_3763) ? c_3728 : riscv_x7;
riscv_x7_next = c_3765;
c_3768 = c_17 == 8;
c_3770 = (c_3768) ? c_3728 : riscv_x8;
riscv_x8_next = c_3770;
c_3773 = c_17 == 9;
c_3775 = (c_3773) ? c_3728 : riscv_x9;
riscv_x9_next = c_3775;
};
| [
"yuex@princeton.edu"
] | yuex@princeton.edu |
a09d16805b1b0c1fc15d83657eb1b9546e9a71a4 | 611c32786f7cdb43932e67dcae53b6817f7858ba | /hphp/util/cache/test/cache-manager.cpp | 17bc090e5e0b33f6e2484e152e00914ccb7672e1 | [
"PHP-3.01",
"LicenseRef-scancode-unknown-license-reference",
"Zend-2.0"
] | permissive | prakul/hiphop-php | eaa65e6c2274629cb9bfad706f754cf099e520af | 51c5cbdf527e4335cf33af6f3da1cfa6842c6785 | refs/heads/master | 2021-01-21T00:45:29.485704 | 2013-09-25T19:16:16 | 2013-09-26T18:03:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,785 | cpp | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/util/cache/cache-manager.h"
#include <string>
#include "gtest/gtest.h"
namespace HPHP {
using std::string;
class TestCacheManager : public testing::Test {
protected:
bool makeTempFile(const string& contents, string* fn) {
char fn_tmpl[] = "/tmp/hhvm_unit_test.XXXXXX";
int fd = mkstemp(fn_tmpl);
if (fd < 0) {
return false;
}
ssize_t ret = write(fd, contents.c_str(), contents.length());
close(fd);
if (ret != contents.length()) {
return false;
}
*fn = fn_tmpl;
return true;
}
bool makeTempDir(string* dir) {
char dir_tmpl[] = "/tmp/hhvm_unit_test.XXXXXX";
const char* temp = mkdtemp(dir_tmpl);
if (temp == nullptr) {
return false;
}
dir->assign(temp);
return true;
}
};
TEST_F(TestCacheManager, BadLoadPath) {
CacheManager cm;
EXPECT_FALSE(cm.addFileContents("/test/name", "/invalid/path"));
}
TEST_F(TestCacheManager, LocalStoreAndFetch) {
CacheManager cm;
string name = "/test/name";
EXPECT_FALSE(cm.entryExists(name));
EXPECT_FALSE(cm.fileExists(name));
EXPECT_FALSE(cm.dirExists(name));
const char* data;
uint64_t data_len;
bool compressed;
EXPECT_FALSE(cm.getFileContents(name, &data, &data_len, &compressed));
string uncompressed;
EXPECT_FALSE(cm.getDecompressed(name, &uncompressed));
uint64_t uncompressed_size;
EXPECT_FALSE(cm.getUncompressedFileSize(name, &uncompressed_size));
// Add a real (highly compressible) file for it to read in.
string test_data;
for (int i = 0; i < 1024; ++i) {
test_data.append("123456789012345678901234567890");
}
string data_fn;
ASSERT_TRUE(makeTempFile(test_data, &data_fn));
ASSERT_TRUE(cm.addFileContents(name, data_fn));
ASSERT_EQ(unlink(data_fn.c_str()), 0);
EXPECT_TRUE(cm.entryExists(name));
EXPECT_TRUE(cm.fileExists(name));
EXPECT_FALSE(cm.dirExists(name));
// The "/test" of "/test/name" should have been added as a directory.
EXPECT_TRUE(cm.dirExists("/test"));
EXPECT_TRUE(cm.getFileContents(name, &data, &data_len, &compressed));
EXPECT_TRUE(compressed);
// It's compressed, so it'll be different.
ASSERT_NE(memcmp(test_data.c_str(), data, data_len), 0);
ASSERT_TRUE(cm.getUncompressedFileSize(name, &uncompressed_size));
EXPECT_EQ(test_data.length(), uncompressed_size);
// So let's decompress it.
ASSERT_TRUE(cm.getDecompressed(name, &uncompressed));
ASSERT_EQ(test_data.length(), uncompressed.length());
ASSERT_EQ(test_data, uncompressed);
}
TEST_F(TestCacheManager, Empty) {
CacheManager cm;
string name = "/test/name";
EXPECT_FALSE(cm.entryExists(name));
EXPECT_FALSE(cm.fileExists(name));
EXPECT_FALSE(cm.dirExists(name));
ASSERT_TRUE(cm.addEmptyEntry(name));
EXPECT_TRUE(cm.entryExists(name));
EXPECT_FALSE(cm.fileExists(name));
EXPECT_FALSE(cm.dirExists(name));
const char* data;
uint64_t data_len;
bool compressed;
EXPECT_FALSE(cm.getFileContents(name, &data, &data_len, &compressed));
string uncompressed;
EXPECT_FALSE(cm.getDecompressed(name, &uncompressed));
uint64_t file_size;
EXPECT_FALSE(cm.getUncompressedFileSize(name, &file_size));
}
TEST_F(TestCacheManager, Duplicates) {
CacheManager cm;
string name = "/test/name";
EXPECT_TRUE(cm.addEmptyEntry(name));
EXPECT_FALSE(cm.addEmptyEntry(name));
EXPECT_FALSE(cm.addFileContents(name, "/invalid/path"));
}
TEST_F(TestCacheManager, AddUncompressibleData) {
string test_data = "let's hope this won't compress too terribly well.";
string data_fn;
ASSERT_TRUE(makeTempFile(test_data, &data_fn));
CacheManager cm;
string name = "/test/name";
ASSERT_TRUE(cm.addFileContents(name, data_fn));
ASSERT_EQ(unlink(data_fn.c_str()), 0);
ASSERT_TRUE(cm.dirExists("/test"));
// Read it back from the cache.
const char* data;
uint64_t data_len;
bool compressed;
EXPECT_TRUE(cm.getFileContents(name, &data, &data_len, &compressed));
ASSERT_FALSE(compressed);
EXPECT_EQ(data_len, test_data.length());
ASSERT_EQ(memcmp(test_data.c_str(), data, data_len), 0);
uint64_t file_size;
ASSERT_TRUE(cm.getUncompressedFileSize(name, &file_size));
EXPECT_EQ(file_size, test_data.length());
}
TEST_F(TestCacheManager, SaveAndLoad) {
CacheManager cm;
// Create an uncompressed file.
//1234567890123456
string test_data_1 = "don't compress!!";
string data_fn_1;
ASSERT_TRUE(makeTempFile(test_data_1, &data_fn_1));
string name_1 = "/test/name/not_compressible12345";
ASSERT_TRUE(cm.addFileContents(name_1, data_fn_1));
ASSERT_EQ(unlink(data_fn_1.c_str()), 0);
ASSERT_TRUE(cm.dirExists("/test"));
ASSERT_TRUE(cm.dirExists("/test/name"));
// Create a compressed file.
string test_data_2;
test_data_2.assign(1048576, 0x55);
string data_fn_2;
ASSERT_TRUE(makeTempFile(test_data_2, &data_fn_2));
string name_2 = "/test/name/very/compressible1234";
ASSERT_TRUE(cm.addFileContents(name_2, data_fn_2));
ASSERT_EQ(unlink(data_fn_2.c_str()), 0);
ASSERT_TRUE(cm.dirExists("/test"));
ASSERT_TRUE(cm.dirExists("/test/name"));
ASSERT_TRUE(cm.dirExists("/test/name/very"));
// Create an empty entry.
string name_3 = "/test/with/a/very/long/name/for/an/empty/entry";
ASSERT_TRUE(cm.addEmptyEntry(name_3));
// Write it out ...
string temp_dir;
ASSERT_TRUE(makeTempDir(&temp_dir));
string save_path(temp_dir);
save_path.append("/cm.save");
ASSERT_TRUE(cm.saveCache(save_path));
// ... and load it back in.
CacheManager cm2;
ASSERT_TRUE(cm2.loadCache(save_path));
ASSERT_TRUE(cm2.fileExists(name_1));
ASSERT_TRUE(cm2.fileExists(name_2));
ASSERT_TRUE(cm2.entryExists(name_3));
EXPECT_TRUE(cm.dirExists("/test"));
EXPECT_TRUE(cm.dirExists("/test/name"));
// Empty entries also get their parent directories added.
EXPECT_TRUE(cm.dirExists("/test/with"));
const char* compare_1;
uint64_t compare_len_1;
bool compressed_1;
ASSERT_TRUE(cm2.getFileContents(name_1, &compare_1, &compare_len_1,
&compressed_1));
ASSERT_FALSE(compressed_1);
ASSERT_EQ(test_data_1.length(), compare_len_1);
ASSERT_EQ(memcmp(test_data_1.c_str(), compare_1, compare_len_1), 0);
string compare_2;
ASSERT_TRUE(cm2.getDecompressed(name_2, &compare_2));
EXPECT_EQ(compare_2, test_data_2);
// Clean up the mess.
ASSERT_EQ(unlink(save_path.c_str()), 0);
ASSERT_EQ(rmdir(temp_dir.c_str()), 0);
}
// This is a great way to make mmap fail, since it hates a length of 0 bytes.
TEST_F(TestCacheManager, LoadEmptyCache) {
string data;
string fn;
ASSERT_TRUE(makeTempFile(data, &fn));
CacheManager cm;
ASSERT_FALSE(cm.loadCache(fn));
ASSERT_EQ(unlink(fn.c_str()), 0);
}
// Long enough to get past the "mmap punts at 0 bytes" thing, but
// short enough to trip an attempted read of the magic number.
TEST_F(TestCacheManager, LoadTruncatedCache) {
string data = "X";
string fn;
ASSERT_TRUE(makeTempFile(data, &fn));
CacheManager cm;
ASSERT_FALSE(cm.loadCache(fn));
ASSERT_EQ(unlink(fn.c_str()), 0);
}
// Long enough for the magic number read and check to happen (and fail).
TEST_F(TestCacheManager, LoadNonCache) {
string data = "_________________nope____________________";
string fn;
ASSERT_TRUE(makeTempFile(data, &fn));
CacheManager cm;
ASSERT_FALSE(cm.loadCache(fn));
ASSERT_EQ(unlink(fn.c_str()), 0);
}
TEST_F(TestCacheManager, SaveNothing) {
string temp_dir;
ASSERT_TRUE(makeTempDir(&temp_dir));
string save_path(temp_dir);
save_path.append("/cm.save");
CacheManager cm;
ASSERT_TRUE(cm.saveCache(save_path));
ASSERT_EQ(unlink(save_path.c_str()), 0);
}
TEST_F(TestCacheManager, SaveBadPath) {
CacheManager cm;
ASSERT_FALSE(cm.saveCache("/__invalid__/__path__/"));
}
} // namespace HPHP
| [
"sgolemon@fb.com"
] | sgolemon@fb.com |
227451c8615630994ab6d31d2e58784e7347e812 | bd9a52b07003370676ed55e59bcf196e7939186e | /server/connector.cpp | 26a8d35b95197f18d86c359ae535f6df0d250230 | [] | no_license | youyouye/my_server | d32cb1efaa098fa4feb0b18d36deea76f051ae7d | 42c95b71865f02130e3f0f9b9a658285e0df2265 | refs/heads/master | 2021-05-02T06:02:10.129518 | 2018-11-28T03:27:50 | 2018-11-28T03:27:50 | 120,851,133 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,571 | cpp | #include "connector.h"
#include <functional>
#include <assert.h>
#include "event_loop.h"
#include "../log/Log.h"
#include "socket_op.h"
#include "channel.h"
Connector::Connector(EventLoop* loop, const std::string& addr, int port)
:loop_(loop),
addr_(addr),
port_(port),
connected_(false),
state_(kDisconnected)
{
}
Connector::~Connector()
{
}
void Connector::start()
{
connected_ = true;
std::function<void()> func = std::bind(&Connector::startInLoop,this);
loop_->runInLoop(func);
}
void Connector::restart()
{
connected_ = true;
}
void Connector::stop()
{
connected_ = false;
std::function<void()> func = std::bind(&Connector::stopInLoop, this);
loop_->runInLoop(func);
}
void Connector::connect()
{
int sockfd = sockets::createSocket();
int ret = sockets::connect(sockfd, addr_, port_);
int saved_error = (ret == 0) ? 0 : errno;
switch (saved_error)
{
case 0:
case EINPROGRESS:
case EINTR:
case EISCONN:
connecting(sockfd);
break;
case EAGAIN:
case EADDRINUSE:
case EADDRNOTAVAIL:
case ECONNREFUSED:
case ENETUNREACH:
retry(sockfd);
break;
case EACCES:
case EPERM:
case EAFNOSUPPORT:
case EALREADY:
case EBADF:
case EFAULT:
case ENOTSOCK:
LOG_ERROR << "connect error in Connector::startInLoop " << saved_error << LOG_END;
sockets::close(sockfd);
break;
default:
LOG_ERROR << "Unexpected error in Connector::startInLoop" << saved_error << LOG_END;
sockets::close(sockfd);
break;
}
}
void Connector::connecting(int sockfd)
{
setState(kConnecting);
assert(!channel_);
channel_.reset(new Channel(loop_,sockfd));
channel_->setWriteCallback(std::bind(&Connector::handleWrite,this));
channel_->setErrorCallback(std::bind(&Connector::handleError,this));
channel_->enableWriting();
}
void Connector::retry(int sockfd)
{
sockets::close(sockfd);
setState(kDisconnected);
if (connected_)
{
}
else
{
LOG_DEBUG << "do not connect!" << LOG_END;
}
}
void Connector::startInLoop()
{
assert(state_ == kDisconnected);
if (connected_)
{
connect();
}
else
{
LOG_DEBUG << "not connect!" << LOG_END;
}
}
void Connector::stopInLoop()
{
if (state_ == kConnecting)
{
setState(kDisconnected);
int sockfd = removeAndResetChannel();
//why retry?
}
}
int Connector::removeAndResetChannel()
{
channel_->disableAll();
channel_->remove();
int sockfd = channel_->fd();
std::function<void()> func = std::bind(&Connector::resetChannel, this);
loop_->queueInLoop(func);
return sockfd;
}
void Connector::resetChannel()
{
channel_.reset();
}
void Connector::handleWrite()
{
LOG_DEBUG << "Connector::handleWrite state=" <<state_ << LOG_END;
if (state_ == kConnecting)
{
int sockfd = removeAndResetChannel();
int err = sockets::getSocketError(sockfd);
if (err)
{
LOG_ERROR << "Connector::handleWrite - SO_ERROR ="<<strerror(err) << " " << LOG_END;
}
// else if ()
// {
// //is-self-connect
// }
else
{
setState(kConnected);
if (connected_)
{
new_connection_callback_(sockfd);
}
else
{
sockets::close(sockfd);
}
}
}
else
{
assert(state_ == kDisconnected);
}
}
void Connector::handleError()
{
LOG_ERROR << "Connector::handleError state=" <<state_ << LOG_END;
if (state_ == kConnecting)
{
int sockfd = removeAndResetChannel();
int err = sockets::getSocketError(sockfd);
LOG_ERROR << "SO_ERROR ="<<strerror(err)<<" " << LOG_END;
}
}
| [
"15834315345@163.com"
] | 15834315345@163.com |
74a67e2fef20cdf08f76ac4f980cdb13eddfda39 | 733b72e9279c7fbfcdd3fb9a9b4954f08f9e63c6 | /part_e/bus.h | ae90cfcc666fc0cfc08dd567e52973427acce174 | [] | no_license | aasmc/coursera_brown_final | f7b65f1366348d7d5e5f412d102e7c78876a9f07 | b9fe416e680a748945e4cbefd294ae5aee5cfab1 | refs/heads/master | 2023-07-13T23:03:48.300435 | 2021-08-10T20:22:34 | 2021-08-10T20:22:34 | 385,633,326 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 645 | h | #pragma once
#include "vector"
#include "stop.h"
class Bus {
private:
std::string number;
bool isCircular = false;
std::vector<std::string> forward_stops;
public:
Bus() = default;
void addBusStop(const std::string &stop);
void setCircular(bool isCircular_);
void setNumber(const std::string &number_);
Bus(std::vector<std::string> stops_, bool isCircular_);
int getNumberOfStopsOnRoute() const;
int getUniqueStops() const;
std::string getNumber() const;
size_t getTotalNumberOfStops() const;
const std::vector<std::string>& getBusStops() const;
bool isBusCircular() const;
}; | [
"aasmc@yandex.ru"
] | aasmc@yandex.ru |
18a12dee616b89756cff178938bf1f19d4589461 | f522d706c87b07a2ad07dc08ebbadb9b23ee6dc2 | /src/script_interface/utils.cpp | a59adc21e0972ca2fefbfa533b67f9c1292c198e | [
"Unlicense"
] | permissive | kpw2210/foo_jscript_panel | 74d9aac341cc29db5d0594316f745aa27dfb42eb | 2c02a933a1f5aa52bdabce9f08bda200a6d27dd6 | refs/heads/master | 2020-04-29T15:25:04.182184 | 2019-03-18T06:47:03 | 2019-03-18T06:47:03 | 176,227,242 | 0 | 0 | NOASSERTION | 2019-03-18T07:29:19 | 2019-03-18T07:29:19 | null | UTF-8 | C++ | false | false | 10,959 | cpp | #include "stdafx.h"
#include "helpers.h"
#include "ui_input_box.h"
#include "utils.h"
Utils::Utils() {}
Utils::~Utils() {}
STDMETHODIMP Utils::CheckComponent(BSTR name, VARIANT_BOOL is_dll, VARIANT_BOOL* p)
{
if (!p) return E_POINTER;
service_enum_t<componentversion> e;
componentversion::ptr ptr;
string_utf8_from_wide uname(name);
pfc::string8_fast temp;
*p = VARIANT_FALSE;
while (e.next(ptr))
{
if (is_dll != VARIANT_FALSE)
{
ptr->get_file_name(temp);
}
else
{
ptr->get_component_name(temp);
}
if (_stricmp(temp, uname) == 0)
{
*p = VARIANT_TRUE;
break;
}
}
return S_OK;
}
STDMETHODIMP Utils::CheckFont(BSTR name, VARIANT_BOOL* p)
{
if (!p) return E_POINTER;
*p = VARIANT_FALSE;
wchar_t family_name[LF_FACESIZE] = { 0 };
Gdiplus::InstalledFontCollection fonts;
const int count = fonts.GetFamilyCount();
Gdiplus::FontFamily* families = new Gdiplus::FontFamily[count];
int found;
if (fonts.GetFamilies(count, families, &found) == Gdiplus::Ok)
{
for (int i = 0; i < found; i++)
{
families[i].GetFamilyName(family_name);
if (_wcsicmp(name, family_name) == 0)
{
*p = VARIANT_TRUE;
break;
}
}
}
delete[] families;
return S_OK;
}
STDMETHODIMP Utils::ColourPicker(UINT window_id, int default_colour, int* p)
{
if (!p) return E_POINTER;
COLORREF COLOR = helpers::convert_argb_to_colorref(default_colour);
COLORREF COLORS[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
uChooseColor(&COLOR, (HWND)window_id, &COLORS[0]);
*p = helpers::convert_colorref_to_argb(COLOR);
return S_OK;
}
STDMETHODIMP Utils::FileTest(BSTR path, BSTR mode, VARIANT* p)
{
if (!p) return E_POINTER;
if (wcscmp(mode, L"e") == 0)
{
p->vt = VT_BOOL;
p->boolVal = TO_VARIANT_BOOL(PathFileExists(path));
}
else if (wcscmp(mode, L"s") == 0)
{
WIN32_FILE_ATTRIBUTE_DATA data;
t_filesize size = 0;
if (GetFileAttributesEx(path, GetFileExInfoStandard, &data) && !(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
size = (t_filesize)data.nFileSizeHigh << 32 | data.nFileSizeLow;
}
p->vt = VT_I8;
p->llVal = size;
}
else if (wcscmp(mode, L"d") == 0)
{
p->vt = VT_BOOL;
p->boolVal = TO_VARIANT_BOOL(PathIsDirectory(path));
}
else if (wcscmp(mode, L"split") == 0)
{
const wchar_t* fn = PathFindFileName(path);
const wchar_t* ext = PathFindExtension(fn);
wchar_t dir[MAX_PATH] = { 0 };
helpers::com_array helper;
_variant_t vars[3];
if (!helper.create(_countof(vars))) return E_OUTOFMEMORY;
vars[0].vt = VT_BSTR;
vars[0].bstrVal = nullptr;
vars[1].vt = VT_BSTR;
vars[1].bstrVal = nullptr;
vars[2].vt = VT_BSTR;
vars[2].bstrVal = nullptr;
if (PathIsFileSpec(fn))
{
StringCchCopyN(dir, _countof(dir), path, fn - path);
PathAddBackslash(dir);
vars[0].bstrVal = SysAllocString(dir);
vars[1].bstrVal = SysAllocStringLen(fn, ext - fn);
vars[2].bstrVal = SysAllocString(ext);
}
else
{
StringCchCopy(dir, _countof(dir), path);
PathAddBackslash(dir);
vars[0].bstrVal = SysAllocString(dir);
}
for (LONG i = 0; i < helper.get_count(); ++i)
{
if (!helper.put_item(i, vars[i])) return E_OUTOFMEMORY;
}
p->vt = VT_VARIANT | VT_ARRAY;
p->parray = helper.get_ptr();
}
else if (wcscmp(mode, L"chardet") == 0)
{
p->vt = VT_UI4;
p->ulVal = helpers::detect_charset(string_utf8_from_wide(path));
}
else
{
return E_INVALIDARG;
}
return S_OK;
}
STDMETHODIMP Utils::FormatDuration(double seconds, BSTR* p)
{
if (!p) return E_POINTER;
pfc::string8_fast str = pfc::format_time_ex(seconds, 0).get_ptr();
*p = SysAllocString(string_wide_from_utf8_fast(str));
return S_OK;
}
STDMETHODIMP Utils::FormatFileSize(LONGLONG bytes, BSTR* p)
{
if (!p) return E_POINTER;
pfc::string8_fast str = pfc::format_file_size_short(bytes);
*p = SysAllocString(string_wide_from_utf8_fast(str));
return S_OK;
}
STDMETHODIMP Utils::GetAlbumArtAsync(UINT window_id, IMetadbHandle* handle, UINT art_id, VARIANT_BOOL need_stub, VARIANT_BOOL only_embed, VARIANT_BOOL no_load, UINT* p)
{
if (!p) return E_POINTER;
t_size cookie = 0;
metadb_handle* ptr = nullptr;
handle->get__ptr((void**)&ptr);
if (!ptr) return E_INVALIDARG;
try
{
helpers::album_art_async* task = new helpers::album_art_async((HWND)window_id, ptr, art_id, need_stub != VARIANT_FALSE, only_embed != VARIANT_FALSE, no_load != VARIANT_FALSE);
if (simple_thread_pool::instance().enqueue(task))
cookie = reinterpret_cast<t_size>(task);
else
delete task;
}
catch (...)
{
cookie = 0;
}
*p = cookie;
return S_OK;
}
STDMETHODIMP Utils::GetAlbumArtEmbedded(BSTR rawpath, UINT art_id, IGdiBitmap** pp)
{
if (!pp) return E_POINTER;
*pp = helpers::get_album_art_embedded(string_utf8_from_wide(rawpath).get_ptr(), art_id);
return S_OK;
}
STDMETHODIMP Utils::GetAlbumArtV2(IMetadbHandle* handle, UINT art_id, VARIANT_BOOL need_stub, IGdiBitmap** pp)
{
if (!pp) return E_POINTER;
metadb_handle* ptr = nullptr;
handle->get__ptr((void**)&ptr);
if (!ptr) return E_INVALIDARG;
pfc::string8_fast dummy;
*pp = helpers::get_album_art(ptr, art_id, need_stub != VARIANT_FALSE, dummy);
return S_OK;
}
STDMETHODIMP Utils::GetSysColour(UINT index, int* p)
{
if (!p) return E_POINTER;
*p = 0;
if (::GetSysColorBrush(index) != nullptr)
{
*p = helpers::convert_colorref_to_argb(::GetSysColor(index));
}
return S_OK;
}
STDMETHODIMP Utils::GetSystemMetrics(UINT index, int* p)
{
if (!p) return E_POINTER;
*p = ::GetSystemMetrics(index);
return S_OK;
}
STDMETHODIMP Utils::Glob(BSTR pattern, UINT exc_mask, UINT inc_mask, VARIANT* p)
{
if (!p) return E_POINTER;
pfc::string8_fast path = string_utf8_from_wide(pattern).get_ptr();
const char* fn = path.get_ptr() + path.scan_filename();
pfc::string8_fast dir(path.get_ptr(), fn - path.get_ptr());
puFindFile ff = uFindFirstFile(path.get_ptr());
pfc::string_list_impl files;
if (ff)
{
do
{
DWORD attr = ff->GetAttributes();
if ((attr& inc_mask) && !(attr& exc_mask))
{
pfc::string8_fast fullpath = dir;
fullpath.add_string(ff->GetFileName());
files.add_item(fullpath.get_ptr());
}
} while (ff->FindNext());
}
delete ff;
ff = nullptr;
helpers::com_array helper;
if (!helper.create(files.get_count())) return E_OUTOFMEMORY;
for (LONG i = 0; i < helper.get_count(); ++i)
{
_variant_t var;
var.vt = VT_BSTR;
var.bstrVal = SysAllocString(string_wide_from_utf8_fast(files[i]).get_ptr());
if (!helper.put_item(i, var)) return E_OUTOFMEMORY;
}
p->vt = VT_ARRAY | VT_VARIANT;
p->parray = helper.get_ptr();
return S_OK;
}
STDMETHODIMP Utils::InputBox(UINT window_id, BSTR prompt, BSTR caption, BSTR def, VARIANT_BOOL error_on_cancel, BSTR* p)
{
if (!p) return E_POINTER;
modal_dialog_scope scope;
if (scope.can_create())
{
scope.initialize(HWND(window_id));
string_utf8_from_wide uprompt(prompt);
string_utf8_from_wide ucaption(caption);
string_utf8_from_wide udef(def);
CInputBox dlg(uprompt, ucaption, udef);
int status = dlg.DoModal(HWND(window_id));
if (status == IDOK)
{
pfc::string8_fast str;
dlg.GetValue(str);
*p = SysAllocString(string_wide_from_utf8_fast(str));
}
else if (status == IDCANCEL)
{
if (error_on_cancel != VARIANT_FALSE)
{
return E_FAIL;
}
*p = SysAllocString(def);
}
}
return S_OK;
}
STDMETHODIMP Utils::IsKeyPressed(UINT vkey, VARIANT_BOOL* p)
{
if (!p) return E_POINTER;
*p = TO_VARIANT_BOOL(::IsKeyPressed(vkey));
return S_OK;
}
STDMETHODIMP Utils::ListFiles(BSTR folder, VARIANT_BOOL recur, VARIANT* p)
{
if (!p) return E_POINTER;
pfc::string_list_impl list;
helpers::list(string_utf8_from_wide(folder).get_ptr(), true, recur != VARIANT_FALSE, list);
const LONG count = list.get_count();
helpers::com_array helper;
if (!helper.create(count)) return E_OUTOFMEMORY;
for (LONG i = 0; i < count; ++i)
{
_variant_t var;
var.vt = VT_BSTR;
var.bstrVal = SysAllocString(string_wide_from_utf8_fast(file_path_display(list.get_item(i))));
if (!helper.put_item(i, var)) return E_OUTOFMEMORY;
}
p->vt = VT_ARRAY | VT_VARIANT;
p->parray = helper.get_ptr();
return S_OK;
}
STDMETHODIMP Utils::ListFolders(BSTR folder, VARIANT* p)
{
if (!p) return E_POINTER;
pfc::string_list_impl list;
helpers::list(string_utf8_from_wide(folder).get_ptr(), false, false, list);
const LONG count = list.get_count();
helpers::com_array helper;
if (!helper.create(count)) return E_OUTOFMEMORY;
for (LONG i = 0; i < count; ++i)
{
pfc::string8_fast path = file_path_display(list.get_item(i)).get_ptr();
path.add_char('\\');
_variant_t var;
var.vt = VT_BSTR;
var.bstrVal = SysAllocString(string_wide_from_utf8_fast(path));
if (!helper.put_item(i, var)) return E_OUTOFMEMORY;
}
p->vt = VT_ARRAY | VT_VARIANT;
p->parray = helper.get_ptr();
return S_OK;
}
STDMETHODIMP Utils::MapString(BSTR str, UINT lcid, UINT flags, BSTR* p)
{
if (!p) return E_POINTER;
int r = ::LCMapStringW(lcid, flags, str, wcslen(str) + 1, nullptr, 0);
if (!r) return E_FAIL;
wchar_t* dst = new wchar_t[r];
r = ::LCMapStringW(lcid, flags, str, wcslen(str) + 1, dst, r);
if (r) *p = SysAllocString(dst);
delete[] dst;
return S_OK;
}
STDMETHODIMP Utils::PathWildcardMatch(BSTR pattern, BSTR str, VARIANT_BOOL* p)
{
if (!p) return E_POINTER;
*p = TO_VARIANT_BOOL(PathMatchSpec(str, pattern));
return S_OK;
}
STDMETHODIMP Utils::ReadINI(BSTR filename, BSTR section, BSTR key, VARIANT defaultval, BSTR* p)
{
if (!p) return E_POINTER;
enum
{
BUFFER_LEN = 255
};
TCHAR buff[BUFFER_LEN] = { 0 };
GetPrivateProfileString(section, key, nullptr, buff, BUFFER_LEN, filename);
if (!buff[0])
{
_variant_t var;
if (SUCCEEDED(VariantChangeType(&var, &defaultval, 0, VT_BSTR)))
{
*p = SysAllocString(var.bstrVal);
return S_OK;
}
}
*p = SysAllocString(buff);
return S_OK;
}
STDMETHODIMP Utils::ReadTextFile(BSTR filename, UINT codepage, BSTR* p)
{
if (!p) return E_POINTER;
pfc::array_t<wchar_t> content;
if (helpers::read_file_wide(codepage, filename, content))
{
*p = SysAllocString(content.get_ptr());
}
else
{
*p = SysAllocString(L"");
}
return S_OK;
}
STDMETHODIMP Utils::WriteINI(BSTR filename, BSTR section, BSTR key, VARIANT val, VARIANT_BOOL* p)
{
if (!p) return E_POINTER;
_variant_t var;
if (FAILED(VariantChangeType(&var, &val, 0, VT_BSTR))) return E_INVALIDARG;
*p = TO_VARIANT_BOOL(WritePrivateProfileString(section, key, var.bstrVal, filename));
return S_OK;
}
STDMETHODIMP Utils::WriteTextFile(BSTR filename, BSTR content, VARIANT_BOOL write_bom, VARIANT_BOOL* p)
{
if (!p) return E_POINTER;
if (filename == nullptr || content == nullptr)
{
*p = VARIANT_FALSE;
}
else
{
*p = TO_VARIANT_BOOL(helpers::write_file(string_utf8_from_wide(filename).get_ptr(), string_utf8_from_wide(content).get_ptr(), write_bom != VARIANT_FALSE));
}
return S_OK;
}
STDMETHODIMP Utils::get_Version(UINT* v)
{
if (!v) return E_POINTER;
*v = 2210;
return S_OK;
}
| [
"34617027+marc2k3@users.noreply.github.com"
] | 34617027+marc2k3@users.noreply.github.com |
8e535b18e2474799d830b82f4acb59e285fc3e0d | bd380e6585660109fe29c3194ddcdfd82c26899a | /platformio/arduino-esp/Taller 4 Telemetria MQTT/lib/IoTcomLib/src/IoTcomLib.cpp | 41b9533d6c0dd4449c856c7ededb6603508d6568 | [] | no_license | manzamb/curso-IoT-semantics | 0761e9057014ceac56bbc5ffe46448eeabf2ab4b | a7c51f61b8b7848010ae1038eea8457c296f3bc7 | refs/heads/master | 2022-12-20T15:30:36.061482 | 2022-12-12T00:50:08 | 2022-12-12T00:50:08 | 83,190,020 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,587 | cpp | #include <IoTcomLib.h>
//------------------- FUNCIONES PARA CONECTAR A LA RED ---------------------
#include <ESP8266WiFi.h>
void ConectarRed(char ssid[], char password[])
{
Serial.println("Conectandose a la WIFI!");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("WiFi conectada");
Serial.println(WiFi.localIP());
}
//------------------- FUNCIONES PARA CONECTAR A THINGSPEAK ---------------------
#include <ThingSpeak.h>
WiFiClient client; //Cliente Wifi para ThingSpeak
// Información del Canal y Campos de ThingSpeak
//static char thingSpeakAddress[] = "api.thingspeak.com";
static unsigned long channelID = 799494;
static char* readAPIKey=(char*)"70GGTLNT0EMFP0WO";
static char* writeAPIKey = (char*)"7ZBZ9LU15LQRYKRF";
unsigned int dataFieldOne = 1; // Calpo para escribir el estado de la Temperatura
unsigned int dataFieldTwo = 2; // Campo para escribir el estado del Bombillo
unsigned int dataFieldThree = 3; // Campo para escribir el estado del ventilador
unsigned int dataFieldFour = 4; // Campo para enviar el tiempo de medición
void InicializarThingSpeak()
{
//************ Conectar Cliente ThinkSpeak *******
ThingSpeak.begin( client );
//************ Fin Conectar Cliente ThingSpeak ***
}
// Use this function if you want to write a single field
int EnviarThingSpeakDatos(unsigned int TSField, float data ){
int writeSuccess = ThingSpeak.writeField( channelID, TSField, data, writeAPIKey ); // Write the data to the channel
if ( writeSuccess ){
//lcd.setCursor(0, 1);
//lcd.print("Send ThinkSpeak");
Serial.println( String(data) + " Enviando a ThingSpeak." );
}
return writeSuccess;
}
//use this function if you want multiple fields simultaneously
int EnviarThingSpeakVariosDatos( unsigned int TSField1,
float field1Data,unsigned int TSField2, long field2Data,
unsigned int TSField3, long field3Data ,
unsigned int TSField4, long field4Data ){
ThingSpeak.setField( TSField1, field1Data );
ThingSpeak.setField( TSField2, field2Data );
ThingSpeak.setField( TSField3, field3Data );
ThingSpeak.setField( TSField4, field4Data );
Serial.print("Enviando Datos ThingSpeak...");
int printSuccess = ThingSpeak.writeFields( channelID, writeAPIKey );
Serial.println("Success: "); Serial.print(printSuccess);
return printSuccess;
}
| [
"manzamb@unicauca.edu.co"
] | manzamb@unicauca.edu.co |
5d24e8eeb5753ac57fba6827bc3d3fc0553fe16d | 6b660cb96baa003de9e18e332b048c0f1fa67ab9 | /External/SDK/BeltsClothingCategory_functions.cpp | 0964cd21c67b65490bd01c1b1fbfc54527b0bd55 | [] | no_license | zanzo420/zSoT-SDK | 1edbff62b3e12695ecf3969537a6d2631a0ff36f | 5e581eb0400061f6e5f93b3affd95001f62d4f7c | refs/heads/main | 2022-07-30T03:35:51.225374 | 2021-07-07T01:07:20 | 2021-07-07T01:07:20 | 383,634,601 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 562 | cpp | // Name: SoT, Version: 2.2.0.2
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
void UBeltsClothingCategory_C::AfterRead()
{
UClothingCategory::AfterRead();
}
void UBeltsClothingCategory_C::BeforeDelete()
{
UClothingCategory::BeforeDelete();
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"Massimo.linker@gmail.com"
] | Massimo.linker@gmail.com |
38e518d585bd7387a4517ca8c4d452326d5c92f8 | bee55c8da97e1f4769103ac34f71814edb66ad41 | /src/test/test_esbcoin.cpp | c9e1e71ca6f598bd012f28c2ac0ba6db15aa0c5e | [
"MIT"
] | permissive | DSSCOS/DSSC-Public-Chain | d245240e48aa914e7b82449a458c4ac8017773d4 | b82c9a1f78420d7de1c118bc0af6d3008d889e10 | refs/heads/master | 2021-04-07T15:32:50.260916 | 2020-03-20T06:53:03 | 2020-03-20T06:53:03 | 248,686,157 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,432 | cpp | // Copyright (c) 2011-2013 The Bitcoin Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#define BOOST_TEST_MODULE bitpcoin Test Suite
#include "main.h"
#include "random.h"
#include "txdb.h"
#include "ui_interface.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "db.h"
#include "wallet.h"
#endif
#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/thread.hpp>
CClientUIInterface uiInterface;
CWallet* pwalletMain;
extern bool fPrintToConsole;
extern void noui_connect();
struct TestingSetup {
CCoinsViewDB *pcoinsdbview;
boost::filesystem::path pathTemp;
boost::thread_group threadGroup;
TestingSetup() {
SetupEnvironment();
fPrintToDebugLog = false; // don't want to write to debug.log file
fCheckBlockIndex = true;
SelectParams(CBaseChainParams::UNITTEST);
noui_connect();
#ifdef ENABLE_WALLET
bitdb.MakeMock();
#endif
pathTemp = GetTempPath() / strprintf("test_bitpcoin_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
boost::filesystem::create_directories(pathTemp);
mapArgs["-datadir"] = pathTemp.string();
pblocktree = new CBlockTreeDB(1 << 20, true);
pcoinsdbview = new CCoinsViewDB(1 << 23, true);
pcoinsTip = new CCoinsViewCache(pcoinsdbview);
InitBlockIndex();
#ifdef ENABLE_WALLET
bool fFirstRun;
pwalletMain = new CWallet("wallet.dat");
pwalletMain->LoadWallet(fFirstRun);
RegisterValidationInterface(pwalletMain);
#endif
nScriptCheckThreads = 3;
for (int i=0; i < nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
RegisterNodeSignals(GetNodeSignals());
}
~TestingSetup()
{
threadGroup.interrupt_all();
threadGroup.join_all();
UnregisterNodeSignals(GetNodeSignals());
#ifdef ENABLE_WALLET
delete pwalletMain;
pwalletMain = NULL;
#endif
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
#ifdef ENABLE_WALLET
bitdb.Flush(true);
#endif
boost::filesystem::remove_all(pathTemp);
}
};
BOOST_GLOBAL_FIXTURE(TestingSetup);
void Shutdown(void* parg)
{
exit(0);
}
void StartShutdown()
{
exit(0);
}
bool ShutdownRequested()
{
return false;
}
| [
"lyyyouqian1992"
] | lyyyouqian1992 |
8e0613a7b56efbc45be7586f8ae962aab40f3010 | c43082458d931c5a8ad30ccd8e14e169c9b79405 | /algos/dynamic-programming/basic/problem54.cpp | c8bac283976b297946ce3eaa9bd1653a4b91bb7d | [] | no_license | pranshu667/dsa | 4bb3f4d5d680ab38bc0a50a407d6756cd704702c | a8899437a5df5297babf2892697d456e697cee53 | refs/heads/master | 2022-11-15T18:07:21.815063 | 2020-07-16T23:57:27 | 2020-07-16T23:57:27 | 280,282,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 888 | cpp | #include<bits/stdc++.h>
using namespace std;
int largestSquareSubMatrix(int **arr,int n,int m) {
int maximum=INT_MIN;
for(int i=1;i<n;i++) {
for(int j=1;j<m;j++) {
if(arr[i][j]==0) {
}
else {
arr[i][j]=min(arr[i-1][j],min(arr[i][j-1],arr[i-1][j-1]))+1;
if(maximum<arr[i][j]) {
maximum=arr[i][j];
}
}
}
}
return maximum;
}
int main() {
int t;
cin>>t;
while(t--) {
int n,m;
cin>>n>>m;
int **arr=new int*[n];
for(int i=0;i<n;i++) {
arr[i]=new int[m];
}
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
cin>>arr[i][j];
}
}
int ans=largestSquareSubMatrix(arr,n,m);
cout<<ans<<endl;
}
} | [
"pranshus.ic.17@nsit.net.in"
] | pranshus.ic.17@nsit.net.in |
4e17b15e101a6e39bb1d8a3e267f8b59d59ca59b | 062f73b7e41f6a3a9f6a33845e60788638bcadb5 | /src/SteenX/Program/Instruction/Instruction.cpp | 042dd2ec4a020aac4b5e64298b05d783a6ad75e5 | [
"MIT"
] | permissive | cherusker/racehog | 7a75d98391b98f1c9d76d1d7f13c19c635fd7d0b | 30f6285866f528fae0e05a8e8f2c354b1e171b1f | refs/heads/master | 2020-05-22T14:10:14.931131 | 2019-05-13T08:35:56 | 2019-05-28T20:13:52 | 186,378,936 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,923 | cpp | #include "SteenX/Program/Instruction/Instruction.h"
#include "Support/Macros.h"
// TODO: Use OperandVisitor and get rid of the switches?
#define RH_INSTRUCTION_READ_STREAM_CASE(TYPE) \
case Operand::Type::TYPE: \
RH_ISTREAM_READ( \
stream, TYPE ## Operand, ops.emplace_back<TYPE ## Operand>()); \
break;
#define RH_INSTRUCTION_APPEND_OPERAND_CASE(TYPE) \
case Operand::Type::TYPE: \
(void) ops.emplace_back<TYPE ## Operand>( \
*op.as<TYPE ## Operand>()); \
break;
bool
racehog::Instruction::
readFromStream(InputStream& stream) {
RH_ISTREAM_READ(stream, MetadataReference, meta);
auto num_ops = stream.readOperandId();
while (num_ops-- > 0) {
switch (static_cast<Operand::Type>(stream.readOperandType())) {
RH_INSTRUCTION_READ_STREAM_CASE(Constant);
RH_INSTRUCTION_READ_STREAM_CASE(Function);
RH_INSTRUCTION_READ_STREAM_CASE(GlobalMemoryAtom);
RH_INSTRUCTION_READ_STREAM_CASE(LocalMemoryAtom);
default:
LOG(ERROR) << "Unexpected operand type.";
return false;
}
}
return stream.allReadsGood();
}
bool
racehog::Instruction::
writeToStream(OutputStream& stream) const {
RH_OSTREAM_WRITE(stream, MetadataReference, meta);
(void) stream.writeOperandId(ops.size());
for (const auto& op : ops) {
(void) stream.writeOperandType(op.getType());
RH_OSTREAM_WRITE(stream, Operand, op);
}
return stream.good();
}
void
racehog::Instruction::
append(const Operand& op) {
switch (op.getType()) {
RH_INSTRUCTION_APPEND_OPERAND_CASE(Constant);
RH_INSTRUCTION_APPEND_OPERAND_CASE(Function);
RH_INSTRUCTION_APPEND_OPERAND_CASE(GlobalMemoryAtom);
RH_INSTRUCTION_APPEND_OPERAND_CASE(LocalMemoryAtom);
default:
LOG(ERROR) << "Unexpected operand type.";
}
}
| [
"prince.cherusker@gmail.com"
] | prince.cherusker@gmail.com |
861993583cfe72d9e9445cfef8446d703ec56124 | bc5aa3bca2448209738daf7da1c00e78d1ad3f1b | /ajg/synth/exceptions.hpp | b28e89580de6095e15295cd77c475332bc265034 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | legutierr/synth | 29de19039237387ac09b1b38371e97269a6ec56e | 7540072bde2ea9c8258c2dca69d2ed3bd62fb991 | refs/heads/master | 2021-01-18T06:13:57.716733 | 2014-05-12T09:48:04 | 2014-05-12T09:48:04 | 20,218,259 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,706 | hpp | // (C) Copyright 2014 Alvaro J. Genial (http://alva.ro)
// 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).
#ifndef AJG_SYNTH_EXCEPTIONS_HPP_INCLUDED
#define AJG_SYNTH_EXCEPTIONS_HPP_INCLUDED
#include <ajg/synth/support.hpp>
#include <string>
#include <typeinfo>
#include <stdexcept>
#include <exception>
namespace ajg {
namespace synth {
struct exception {
exception() {}
~exception() throw () {}
};
//
// not_implemented
////////////////////////////////////////////////////////////////////////////////////////////////////
struct not_implemented : public exception, public std::runtime_error {
not_implemented(std::string const& feature) : std::runtime_error("not implemented: " + feature) {}
~not_implemented() throw () {}
};
//
// path_error
////////////////////////////////////////////////////////////////////////////////////////////////////
struct path_error : public exception, public std::runtime_error {
std::string const path;
path_error(std::string const& path, std::string const& message) : std::runtime_error(message), path(path) {}
~path_error() throw () {}
};
//
// read_error
////////////////////////////////////////////////////////////////////////////////////////////////////
struct read_error : public path_error {
read_error(std::string const& path, std::string const& reason) : path_error(path, "reading `" + path + "` failed (" + reason + ")") {}
~read_error() throw () {}
};
//
// write_error
////////////////////////////////////////////////////////////////////////////////////////////////////
struct write_error : public path_error {
write_error(std::string const& path, std::string const& reason) : path_error(path, "writing `" + path + "` failed (" + reason + ")") {}
~write_error() throw () {}
};
//
// conversion_error
////////////////////////////////////////////////////////////////////////////////////////////////////
struct conversion_error : public exception, public std::runtime_error {
std::type_info const& from;
std::type_info const& to;
conversion_error(std::type_info const& from, std::type_info const& to)
: std::runtime_error("could not convert value from `" +
std::string(from.name()) + "` to `" + // TODO: Unmangle.
std::string(to.name()) + "`") // TODO: Unmangle.
, from(from)
, to(to) {}
~conversion_error() throw () {}
};
//
// parsing_error
////////////////////////////////////////////////////////////////////////////////////////////////////
struct parsing_error : public exception, public std::runtime_error {
parsing_error(std::string const& line) : std::runtime_error("parsing error near `" + line + "`") {}
~parsing_error() throw () {}
};
//
// missing_variable
////////////////////////////////////////////////////////////////////////////////////////////////////
struct missing_variable : public exception, public std::invalid_argument {
std::string const name;
missing_variable(std::string const& name) : std::invalid_argument("missing variable `" + name + "`"), name(name) {}
~missing_variable() throw () {}
};
//
// missing_attribute
////////////////////////////////////////////////////////////////////////////////////////////////////
struct missing_attribute : public exception, public std::invalid_argument {
std::string const name;
missing_attribute(std::string const& name) : std::invalid_argument("missing attribute `" + name + "`"), name(name) {}
~missing_attribute() throw () {}
};
//
// missing_library
////////////////////////////////////////////////////////////////////////////////////////////////////
struct missing_library : public exception, public std::invalid_argument {
std::string const name;
missing_library(std::string const& name) : std::invalid_argument("missing library `" + name + "`"), name(name) {}
~missing_library() throw () {}
};
//
// missing_key
////////////////////////////////////////////////////////////////////////////////////////////////////
struct missing_key : public exception, public std::invalid_argument {
std::string const name;
missing_key(std::string const& name) : std::invalid_argument("missing key `" + name + "`"), name(name) {}
~missing_key() throw () {}
};
//
// missing_tag
////////////////////////////////////////////////////////////////////////////////////////////////////
struct missing_tag : public exception, public std::invalid_argument {
std::string const name;
missing_tag(std::string const& name) : std::invalid_argument("missing tag `" + name + "`"), name(name) {}
~missing_tag() throw () {}
};
//
// missing_filter
////////////////////////////////////////////////////////////////////////////////////////////////////
struct missing_filter : public exception, public std::invalid_argument {
std::string const name;
missing_filter(std::string const& name) : std::invalid_argument("missing filter `" + name + "`"), name(name) {}
~missing_filter() throw () {}
};
//
// missing_option
////////////////////////////////////////////////////////////////////////////////////////////////////
struct missing_option : public exception, public std::invalid_argument {
std::string const name;
missing_option(std::string const& name) : std::invalid_argument("missing option `" + name + "`"), name(name) {}
~missing_option() throw () {}
};
//
// unknown_option
////////////////////////////////////////////////////////////////////////////////////////////////////
struct unknown_option : public exception, public std::invalid_argument {
std::string const name;
unknown_option() : std::invalid_argument("unknown option"), name() {}
unknown_option(std::string const& name) : std::invalid_argument("unknown option `" + name + "`"), name(name) {}
~unknown_option() throw () {}
};
//
// empty_parameter
////////////////////////////////////////////////////////////////////////////////////////////////////
struct empty_parameter : public exception, public std::invalid_argument {
std::string const option;
empty_parameter(std::string const& option) : std::invalid_argument("empty parameter for option `" + option + "`"), option(option) {}
~empty_parameter() throw () {}
};
//
// invalid_parameter
////////////////////////////////////////////////////////////////////////////////////////////////////
struct invalid_parameter : public exception, public std::invalid_argument {
std::string const option;
invalid_parameter(std::string const& option) : std::invalid_argument("invalid parameter for option `" + option + "`"), option(option) {}
~invalid_parameter() throw () {}
};
//
// missing_parameter
////////////////////////////////////////////////////////////////////////////////////////////////////
struct missing_parameter : public exception, public std::invalid_argument {
std::string const option;
missing_parameter(std::string const& option) : std::invalid_argument("missing parameter for option `" + option + "`"), option(option) {}
~missing_parameter() throw () {}
};
//
// superfluous_parameter
////////////////////////////////////////////////////////////////////////////////////////////////////
struct superfluous_parameter : public exception, public std::invalid_argument {
std::string const option;
superfluous_parameter(std::string const& option) : std::invalid_argument("superfluous parameter for option `" + option + "`"), option(option) {}
~superfluous_parameter() throw () {}
};
//
// missing_argument
////////////////////////////////////////////////////////////////////////////////////////////////////
struct missing_argument : public exception, public std::invalid_argument {
std::string const name;
missing_argument() : std::invalid_argument("missing argument"), name() {}
missing_argument(std::string const& name) : std::invalid_argument("missing argument `" + name + "`"), name(name) {}
~missing_argument() throw () {}
};
//
// superfluous_argument
////////////////////////////////////////////////////////////////////////////////////////////////////
struct superfluous_argument : public exception, public std::invalid_argument {
std::string const name;
superfluous_argument() : std::invalid_argument("superfluous argument") {}
superfluous_argument(std::string const& name) : std::invalid_argument("superfluous argument `" + name + "`"), name(name) {}
~superfluous_argument() throw () {}
};
//
// unknown_argument
////////////////////////////////////////////////////////////////////////////////////////////////////
struct unknown_argument : public exception, public std::invalid_argument {
std::string const value;
unknown_argument(std::string const& value) : std::invalid_argument("unknown argument `" + value + "`"), value(value) {}
~unknown_argument() throw () {}
};
/*
//
// invalid_argument
// TODO: Replace all uses of std::invalid_argument with this?
////////////////////////////////////////////////////////////////////////////////////////////////////
struct invalid_argument : public exception, public std::invalid_argument {
std::string const name;
invalid_argument(std::string const& name) : std::invalid_argument("invalid argument `" + name + "`"), name(name) {}
~invalid_argument() throw () {}
};
*/
//
// invalid_attribute
////////////////////////////////////////////////////////////////////////////////////////////////////
struct invalid_attribute : public exception, public std::invalid_argument {
std::string const name;
invalid_attribute(std::string const& name) : std::invalid_argument("invalid attribute `" + name + "`"), name(name) {}
~invalid_attribute() throw () {}
};
//
// duplicate_attribute
////////////////////////////////////////////////////////////////////////////////////////////////////
struct duplicate_attribute : public exception, public std::invalid_argument {
std::string const name;
duplicate_attribute(std::string const& name) : std::invalid_argument("duplicate attribute `" + name + "`"), name(name) {}
~duplicate_attribute() throw () {}
};
//
// invalid_method
////////////////////////////////////////////////////////////////////////////////////////////////////
struct invalid_method : public exception, public std::invalid_argument {
std::string const name;
invalid_method(std::string const& name) : std::invalid_argument("invalid method `" + name + "`"), name(name) {}
~invalid_method() throw () {}
};
}} // namespace ajg::synth
#endif // AJG_SYNTH_EXCEPTIONS_HPP_INCLUDED
| [
"genial@alva.ro"
] | genial@alva.ro |
9270e56dd9a863035f02e38e41bdc1786265aea3 | dd511176da003ac15f71ffca7dda016eddc1cab8 | /chen/anisotropy.hpp | 651f89111ed91c5a7b0bdf61f6b5d4af5119c602 | [] | no_license | ChristianZhao/multiphase-interface-planarization | ff09a257694394f7a744566620080f76a2a5078f | 4f3ba7728771d23ceaa08ecfc8711a2b63f5439a | refs/heads/main | 2022-10-22T11:39:12.659883 | 2019-07-15T19:30:54 | 2019-07-15T19:30:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,061 | hpp | // anisotropy.hpp
// Anisotropic energy and mobility functions
// Questions/comments to gruberja@gmail.com (Jason Gruber)
#ifndef ANISOTROPY
#define ANISOTROPY
#include<map>
// global energy and mobility storage
namespace anisotropy{
std::map<int,std::map<int,double> > energy_table;
std::map<int,std::map<int,double> > width_table;
}
template <typename T> T min(const T& a, const T& b) {return (a<b?a:b);}
template <typename T> T max(const T& a, const T& b) {return (a>b?a:b);}
double energy(int i, int j)
{
using namespace anisotropy;
// use computed value, if possible
int a = min(i,j);
int b = max(i,j);
double energy = energy_table[a][b];
if (energy==0.0) {
// compute energy here...
energy = 3.375;
energy_table[a][b] = energy;
}
return energy;
}
double width(int i, int j)
{
using namespace anisotropy;
// use computed value, if possible
int a = min(i,j);
int b = max(i,j);
double width = width_table[a][b];
if (width==0.0) {
// compute width here...
width = 1.0;
width_table[a][b] = width;
}
return width;
}
#endif
| [
"trevor.keller@nist.gov"
] | trevor.keller@nist.gov |
bf49155eb95b126d77b05d36f49178e5e41bea26 | f6040844d8399b4476ba6d3adac9a2cbe07f13ec | /sketchbook/rosr_main_v25/rosr_main.ino | d1bd52237d2263d5744cb5dd5f1113efd981e273 | [] | no_license | mike6440/rosr-sw | 110261e17a0c9d6da22b4e4cf934be0113a40ea4 | a4c00438c2ebd8b948043bfde3e01b53376c9500 | refs/heads/master | 2021-01-25T01:03:18.144628 | 2017-12-16T00:22:29 | 2017-12-16T00:22:29 | 94,718,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 82,692 | ino |
// NOTE ========= DEFINES
#define PROGRAMNAME "rosr_main"
#define VERSION "25"//"24"//23
#define EDITDATE "151029"//"151010,15"//"150528,0553"
const byte EEPROM_ID = 11;
//v23 - ComputeSSST had issues. No more!
//v24 - Added calibrated therm coefs for ROSR2
//v25 - ek shutter control, and menu
//NOTE ====== INCLUDES
#include <string.h>
#include <math.h>
#include <SoftwareSerial.h>
#include <EEPROM.h>
//Added for the ADS
#include <Wire.h>
#include <Adafruit_ADS1015.h>
Adafruit_ADS1115 ads0; // ad0, u13, construct an ads1115 at address 0x48
Adafruit_ADS1115 ads1(0x49); // ad1, u16, construct an ads1115 at address 0x49
Adafruit_ADS1115 ads2(0x4A); // ad2, u14, construct an ads1115 at address 0x4A
//Adafruit_ADS1115 ads3(0x4B); // ad3, u17, spare,
//NOTE ====== DIGITAL LINES
const int Serial4Tx = 2; // Testing KT15 Tx; TILT TX
const int Serial4Rx = 3; // Testing KT15 Rx; TILT RX
const int RAIN = 4; // RAIN DETECTOR -- Drives the LED
const int DHe1 = 5; // INPUT Hall Effect Switch 1
const int DHe2 = 6; // IN Hall Effect Switch 2
const int D2a = 7; // shutter motor
const int D2b = 8; // shutter motor
const int BB1 = 9; // bb1 heater on/off
const int BB2 = 10; // bb2 heater on/off
const int D1a = 11; // motor forward
const int D1b = 12; // motor !forward
//const int HBT = 13; // heartbeat LED31
const int LED11 = 24; // Green Scan Drum motor
const int LED12 = 26; // Red shutter motor
const int LED21 = 28; // green BB2 heater on
const int LED22 = 30; // red BB1 heat on
const int LED31 = 32; // green -- continuous on = power
const int LED32 = 13; // red -- heartbeat. red 5REF
const int REFSW = 22; // BB thermistor reference voltage
// ANALOG ASSIGNMENTS
// three 4-chan 16 bit adc, adc#=(unsigned)(x/4), chan#=x%4;
const int ADCMAX = 12; // =12 normally. maximum number of ADC channels
const int Nbb11 = 0; // BB1 thermistor 1
const int Nbb12 = 4; // BB2 thermistor1
const int Nbb21 = 1; // BB1 thermistor 2
const int Nbb22 = 5; // BB2 thermistor 2
const int Nkt15 = 2; // KT15 analog output
const int NRF = 3; // 5REF/2
const int Npwr = 6; // Circuit power temp
const int Nwindow = 7; // Window thermistor
const int Ntkt15 = 8; // KT15 body temperature
const int NVin = 9; // VIN/4
const int Nrain = 10; // Rain / 4
const int Nspare1 = 11; // Spare input 1
//NOTE ====== CONSTANTS
const char OK = 1;
const char NOTOK = 0;
const int MISSING = -999;
const int POS = 1;
const int NEG = -1;
const int CCW = 1; // forward direction
const int CW = -1; // reverse direction
const int STOP = 0; // motor stop
const int ON = 1;
const int OFF = 0;
const int OPEN = 1;
const int CLOSED = 0;
const char SPACE = ' ';
const char ZERO = '0';
//encoder Use the SEI program to set the address to E
const char EncCmd = 0x11;
// test menu
const char TEST = -1;
const char RUN = 1;
// TEMPERATURE
const int WARMUPMILLISECS = 50;
const int ADCREADWAIT = 100;
const double TMAX = 50;
const double TMIN = -5;
// SPECTRON TILT
const double C1 = 0.0129;
const double C2 = 0;
const double C3 = -0.0000000003;
const double P1 = -1; // use -1 for a reversed direction
const double P0 = 0;
const double R1 = -1; // use -1 for a reversed direction
const double R0 = 0;
// SHUTTER
// CCW = open shutter
const double CCWSHUTTERCURRENTTHRESHOLD = 50;
const unsigned CCWSHUTTERTIMEOUT = 1400;
const unsigned CCWSTOPMILLISECS = 200;
// CW = close
const double CWSHUTTERCURRENTTHRESHOLD = 50;
const unsigned CWSHUTTERTIMEOUT = 2000;
const unsigned CWSTOPMILLISECS = 200;
// mega adc
const int I1a = 0; // shutter motor
const int I1b = 1; // shutter motor
const int Arain = 10; // rain sensor ADC16 channel
//=========================================================================
//NOTE ====== GLOBAL VARIABLES
//=========================================================================
// system time
unsigned long msstart; //set at start, milliseconds
unsigned long menustart;
// user i/o
char RunMode;
int ScanMotorFlag;
float EncoderAngle = 0;
int ShutterState;
// READING THE ADC
unsigned long nsamp; // counter for each sample.
double vmean[ADCMAX]; // adc16 read
unsigned int BbThermIndex[4] = {
0, 1, 4, 5
}; // v[i] index for adc channels. {0,1,4,5}; (eeprom)
double Vref; //compute from adc16;
// ADC16 limits for BB temperature cal. volts
double threshold[2] = {
1.00, 4.00
};
// AVERAGES
// BB temps
double Tbb[4] = {
0, 0, 0, 0
}; // for the four precision bb therms
double Tbbav[4] = {
0, 0, 0, 0
};
double Tbbsd[4] = {
0, 0, 0, 0
};
int nbb[4] = {
0, 0, 0, 0
};
double T1, T2;
double ssst;
// ENCODER
double enav[4] = {
0, 0, 0, 0
}; // for the four views.
double ensd[4] = {
0, 0, 0, 0
};
int nen[4] = {
0, 0, 0, 0
};
// TILT
double pitav = 0;
double pitsd = 0;
double rolav = 0;
double rolsd = 0;
int npit = 0;
int nrol = 0;
// POINTANGLE = combine encoder angle and roll. Used in ssst calculation.
double sea_angle;
double e_sea;
// KT RAD
double ktav[4] = {
0, 0, 0, 0
}; // for the four views.
double ktsd[4] = {
0, 0, 0, 0
};
int nkt[4] = {
0, 0, 0, 0
};
// OTHER TEMPS
double Tkt = 0; // 4-20 ma KT15 analog output. v[
double Tktx = 0; // KT15 external, case temperature
double Twin = 0; // window temperature
double Tpwr = 0; // Temp of the
// RAIN
unsigned long millisec_rain; // the clock count to open. 0 if open
char RainState;
unsigned long secs_lapsed;
//NOTE ====== EEPROM
// Scan angles: abb1, abb2, asky, asea, a1, a2
const byte default_CalFlag = 0;
const float default_abb1 = 265;
const float default_abb2 = 325;
const float default_asky = 45;
const float default_aocean = 135;
const float default_encoderref = 0;
const byte default_Nbb = 30;
const byte default_Nsky = 10;
const byte default_Nocean = 40;
const float default_rain_threshold = .090;
const char default_shutter = 1;
const unsigned long default_rainsecs = 600;
const char default_bbheat[2] = {
OFF, ON
};
// THERMISTOR S/N, 0=>std YSI cal. (eeprom)
const unsigned int default_ntherm[4] = {
5, 6, 7, 8
};
//const char default_bbheater=BB2;
const double default_Rref[7] = {
10000, 10000, 10000, 10000, 10000, 10000, 10000
}; // BB11, BB12, BB21, BB22, Tktx, Twin, Tpwr
// See rmrtools/MakeRadTempTables.m to compute these numbers.
const double default_pt2b[4] = {
-1.12206540049944e-08, 6.5886824242969e-05, 0.0117168998631263, 0.64265621081911
};
const double default_pb2t[4] = {
11.3632032970786, -52.9876174795602, 137.697099404017, -69.5189906138133
};
const double default_Acorr = 1;
const double default_Offset = 0;
const double default_ebb = 1;
const float SCAN_TOLERANCE = .1;
struct eeprom {
byte id, Nbb, Nsky, Nocean, ShutterFlag, CalFlag;
float abb1, abb2, aocean, asky, encoderref, rain_threshold, ScanTolerance;
unsigned long rainsecs;
char bbheat[2];
unsigned int ntherm[4]; // bb11, bb12, bb21, bb22
//char bbheater;;
double Rref[7];
double pt2b[4];
double pb2t[4];
double Acorr, Offset, ebb;
};
struct eeprom ee;
int eeSize;
int isample, iangle; // iangle = 0-3 for pointing positions.
float pointangle[4];
byte nsample[4];
byte ianglemax = 3; // max = 1 during rain or 3 when open
byte kavflag; // signals when to compute averages and ssst.
int istart; // set to 1 at startup so we can go to a menu.
//NOTE ====== FUNCTIONS
// i/o
void Action(char*);
double BB_TempCal(double, double, double);
void BBHeater(int, int);
void CheckRain(double *, unsigned long *);
unsigned int checksum_nmea(char *);
unsigned long ElapsedTime (char *);
float DiffAngle(float, float);
void EepromDefault(void);
void EepromStore(void);
void EepromRead(void);
void EepromPrint(void);
char * floatToString(char *, double, byte, byte);
double GetAdcVolts (unsigned int ); // ads adc
unsigned int GetAdcSample(unsigned int ch, double *vmean); // ads adc
double GetEmis( double vsea, double missing);
unsigned int GetThermCoefs(unsigned int, double *coef ); // ads adc
double GetMotorCurrent();
double GetRadFromTemp (double);
double GetTempFromRad (double);
long Hex2Dec(char *);
double KTanalogTemp(double);
void MeanStdev(double *, double *, int, double );
void PrintProgramID(void);
void PrintBytes(char *);
float PointScanDrum(float);
float ReadEncoder (float);
void ReadKT15(double *irrad, double *irtemp);
void ReadTilt(double*, double*);
unsigned Ref(int);
int ScanMotor(int);
int ShutterMotor(int);
void ShutterOpen(void);
void ShutterClose(void);
int sign (float);
double SteinhartHart(double beta[], double r);
double ThermistorTemp(double v, double Vref, double Rref, unsigned int ntherm);
double ComputeSSST( double, double, double, double, double, double, double, double, double, double, double missing, byte);
//============================================================================
void setup() {
// USER Serial setup
Serial.begin(9600);
// ENCODER serial setup
Serial1.begin(9600); // serial
// TILT
Serial2.begin(19200); // serial
// KT15
Serial3.begin(9600); // serial kt15
// BLACK BODIES
pinMode(REFSW, OUTPUT); // BB therm ref on/off
pinMode(BB1, OUTPUT); // BB1 heater on/off
pinMode(BB2, OUTPUT); // BB2 heater on/off
digitalWrite(BB1, LOW); // BB1 heater start off;
digitalWrite(BB2, LOW); // BB2 heater start off;
// sign on
PrintProgramID();
// Set system clock
msstart = millis();
// 5REF START OFF
Ref(OFF);
// MISC
//pinMode(HBT, OUTPUT); // WDT heartbeat.
pinMode(LED11, OUTPUT);
pinMode(LED12, OUTPUT);
pinMode(LED21, OUTPUT);
pinMode(LED22, OUTPUT);
pinMode(LED31, OUTPUT); // HBT
pinMode(LED32, OUTPUT);
pinMode(RAIN, INPUT); // LED OUTPUT
// MOTORS
pinMode(D1a, OUTPUT); // Drum motor
pinMode(D1b, OUTPUT); // Drum motor
pinMode(D2a, OUTPUT); // Shutter motor (in4)
pinMode(D2b, OUTPUT); // Shutter motor (in3)
// ScanMotor(STOP); // start with motor stopped
// HE SWITCHES
pinMode(DHe1, INPUT); // HE#1, 0 => shutter is open
pinMode(DHe2, INPUT); // HE#2, 0 => shutter is closed
// set mem for eeprom
eeSize = sizeof(struct eeprom);
// Serial.print("Check EEPROM. ");
EepromRead();
//Serial.print("EEPROM_ID = "); Serial.println(EEPROM_ID);
//Serial.print("ee.id = "); Serial.println(ee.id);
if (ee.id != EEPROM_ID ) {
Serial.println("ID NO match => use default.");
EepromDefault();
};// else Serial.println("ID MATCH.");
pointangle[0] = ee.abb1;
pointangle[1] = ee.abb2;
pointangle[2] = ee.asky;
pointangle[3] = ee.aocean;
nsample[0] = nsample[1] = ee.Nbb;
nsample[2] = ee.Nsky;
nsample[3] = ee.Nocean;
// ADS1115 ADC
// Serial.println("Getting single-ended readings from AIN0..3");
// Serial.println("ADC Range: +/- 6.144V (1 bit = .15mV)");
ads0.begin();
ads0.setGain(GAIN_ONE); // 1x gain +/- 4.096V
// ads0.setGain(GAIN_ONE); // 1x gain +/- 4.096V 1 bit = 2mV
// ads0.setGain(GAIN_TWO); // 2x gain +/- 2.048V 1 bit = 1mV
// ads0.setGain(GAIN_FOUR); // 4x gain +/- 1.024V 1 bit = 0.5mV
// ads0.setGain(GAIN_EIGHT); // 8x gain +/- 0.512V 1 bit = 0.25mV
// ads0.setGain(GAIN_SIXTEEN); // 16x gain +/- 0.256V
ads1.begin();
ads1.setGain(GAIN_ONE); // 1x gain +/- 4.096V
ads2.begin();
ads2.setGain(GAIN_ONE); // 1x gain +/- 4.096V
// POINT THE ENCODER TO BB1
//EncoderAngle = PointScanDrum(ee.abb2);
iangle = 0; // bb1 position
isample = 3; //
ianglemax = 1; // open=3, rain=1;
kavflag = 0; // when =1 a WIRAV record is generated.
//SHUTTER IS CLOSED
if ( digitalRead(DHe1) == 0 && digitalRead(DHe2) == 1) {
//Serial.println("SHUTTER IS OPEN");
ShutterState = OPEN;
digitalWrite(LED12, LOW);
}
else if ( digitalRead(DHe1) == 1 && digitalRead(DHe2) == 0) {
//Serial.println("SHUTTER IS CLOSED");
ShutterState = CLOSED;
digitalWrite(LED12, HIGH);
}
else {
Serial.println("SHUTTER POSITION UNDETERMINED");
digitalWrite(LED12, LOW);
}
// Drum motor setup;
ScanMotor(STOP); // start with motor off; Set ScanMotorFlag.
// Shutter
ShutterMotor(STOP);
istart = 1;
}
//=============================================================================
void loop() {
int i = 0;
unsigned int b = 0;
char buf[20];
char OutStr[1024], AvStr[512], SsstStr[512];
double ddum, fdum;
unsigned long ldum;
Serial.setTimeout(1000); // 1 sec wait for a key entry
//test Serial.println("Enter 'T' or 't' to go directly to test mode.");
i = Serial.readBytes(buf, 1); // normal operation -- wait for key entry
if ( i > 0 || istart == 1) {
if ( buf[0] == 't' || buf[0] == 'T' || istart == 1) {
menustart = millis();
istart = 0; // normal operation
RunMode = TEST;
Serial.setTimeout(10000); // 10 sec wait for a key entry
//Serial.println("TEST mode.");
while ( RunMode == TEST ) {
if ( millis() - menustart > 600000) {
break;
}
// prompt
Serial.print("> ");
// Wait for a command
i = Serial.readBytesUntil(13, buf, 11);
buf[i] = '\0';
if ( i > 0 ) {
// G - go to main loop
if ( buf[0] == 'G' || buf[0] == 'g' ) {
RunMode = RUN;
Serial.println("Begin Operation...");
}
else {
Serial.println("");
Action(buf);
menustart = millis();
}
}
}
}
}
BBHeater(BB1, ee.bbheat[0]);
BBHeater(BB2, ee.bbheat[1]);
// Point drum
EncoderAngle = PointScanDrum(pointangle[iangle]);
// OUTPUT STRING
// header
strcpy(OutStr, "$WIROS,\0");
// Elapsed time, days, since startup
ElapsedTime(buf);
strcat(OutStr, buf); // end of AvStr strcat(AvStr,",");
strcat(OutStr, ",\0");
// ReadEncoder
//EncoderAngle=ReadEncoder(ee.encoderref);
floatToString(buf, EncoderAngle, 2, 6);
strcat(OutStr, buf);
strcat(OutStr, ",\0");
// Accumulate encoder
if (EncoderAngle > 0) {
enav[iangle] += EncoderAngle;
ensd[iangle] += EncoderAngle * EncoderAngle;
nen[iangle]++;
}
// RADIOMETER
ReadKT15(&ddum, &fdum);
floatToString(buf, ddum, 0, 7);
strcat(OutStr, buf);
strcat(OutStr, ",");
floatToString(buf, fdum, 2, 5);
strcat(OutStr, buf);
strcat(OutStr, ",");
// Accumulate kt
if (ddum > 0) {
ktav[iangle] += ddum;
ktsd[iangle] += ddum * ddum;
nkt[iangle]++;
}
// ADC16 READ
// REF POWER ON
Ref(ON);
delay(WARMUPMILLISECS);
// ALL ADC CHANS
for (i = 0; i < ADCMAX; i++) {
GetAdcSample(i, (vmean + i));
floatToString(buf, vmean[i], 3, 5);
strcat(OutStr, buf);
strcat(OutStr, ",");
}
// REF POWER OFF
Ref(OFF);
// COMPUTE VREF
Vref = vmean[3] * 2;
floatToString(buf, Vref, 3, 5);
strcat(OutStr, buf);
strcat(OutStr, ",");
// BBTEMP
for (i = 0; i < 4; i++) {
Tbb[i] = ThermistorTemp(vmean[BbThermIndex[i]], Vref, ee.Rref[i], ee.ntherm[i]);
if (Tbb[i] < TMIN || Tbb[i] > TMAX) {
strcat(OutStr, "-999,");
}
else {
floatToString(buf, Tbb[i], 2, 5);
strcat(OutStr, buf);
strcat(OutStr, ",");
Tbbav[i] += Tbb[i];
Tbbsd[i] += Tbb[i] * Tbb[i];
nbb[i]++;
}
}
// TILT
ReadTilt(&ddum, &fdum);
// Pitch
if ( ddum == MISSING ) {
strcat(OutStr, "-999,");
}
else {
floatToString(buf, ddum, 1, 4);
strcat(OutStr, buf);
strcat(OutStr, ",");
npit++;
pitav += ddum;
pitsd += ddum * ddum;
}
//Roll
if ( fdum == MISSING ) {
strcat(OutStr, "-999,");
}
else {
floatToString(buf, fdum, 1, 4);
strcat(OutStr, buf);
strcat(OutStr, ",");
nrol++;
rolav += fdum; //v21 add +
rolsd += fdum * fdum; //v21 add +
}
// HOUSEKEEPING
Tkt = KTanalogTemp(vmean[2]);
floatToString(buf, Tkt, 1, 4);
strcat(OutStr, buf);
strcat(OutStr, ",");
Tktx = ThermistorTemp(vmean[11], Vref, ee.Rref[4], 0); // 0 = standard steinhart-hart coefs
floatToString(buf, Tktx, 1, 4);
strcat(OutStr, buf);
strcat(OutStr, ",");
Twin = ThermistorTemp(vmean[7], Vref, ee.Rref[5], 0); // 0 = standard steinhart-hart coefs
floatToString(buf, Twin, 1, 4);
strcat(OutStr, buf);
strcat(OutStr, ",");
Tpwr = ThermistorTemp(vmean[6], Vref, ee.Rref[6], 0); // 0 = standard steinhart-hart coefs
floatToString(buf, Tpwr, 1, 4);
strcat(OutStr, buf);
strcat(OutStr, ",");
ddum = vmean[9] * 4; // Vin
floatToString(buf, ddum, 1, 4);
strcat(OutStr, buf);
strcat(OutStr, ",");
//RAIN STATE
CheckRain(&ddum, &ldum);
if (ddum == MISSING) {
strcat(OutStr, "-999,-999");
}
else {
floatToString(buf, ddum, 1, 4);
strcat(OutStr, buf);
strcat(OutStr, ",");
floatToString(buf, (double)ldum, 0, 3);
strcat(OutStr, buf); // End of OutStr. strcat(OutStr,",");
}
// SHUTTER ACTION
if ( RainState == 1 ) {
ShutterClose();
}
else {
ShutterOpen();
}
// CHECKSUM AND END
b = checksum_nmea(OutStr + 1);
Serial.print(OutStr);
Serial.print("*");
Serial.print(b, HEX);
Serial.print("\r\n");
// SHUTTER OPEN/CLOSE
// RAIN
if ( RainState == 1 ) {
ianglemax = 1;
if ( iangle > 1 ) {
iangle = 0;
isample = 0;
}
}
else ianglemax = 3;
// SWITCH ANGLES
isample++;
if (isample >= nsample[iangle]) {
iangle++;
if ( iangle > ianglemax ) {
iangle = 0;
if ( ianglemax == 3 ) {
kavflag = 1;
}
}
// PRINT HEADER -- used during test
//Serial.println("ID elapsedTi drum KT Tkt adc0 adc1 adc2 adc3 adc4 adc5 adc6 adc7 adc8 adc9 adc10 adc11 vref t11 t12 t21 t22 pit rol Tkt Tktx Twin Tpwr Vin vrain sec*chk");
// $WIROS,01.231245 280.02, 174545,24.86,2.537,2.541,0.414,2.472,1.854,1.853,1.776,2.484,4.096,3.634,-0.000,2.487,4.944,23.66,23.70,38.22,38.21,-2.8,-1.1,-0.0, 0,*50
// PRINT AVERAGES (AvStr) and SSST (SsstStr)
if (kavflag == 1) {
strcpy(AvStr, "$WIRAV,\0");
strcpy(SsstStr, "$WIRST,\0");
// Elapsed time, days, since startup
ElapsedTime(buf);
strcat(AvStr, buf);
strcat(AvStr, ",");
strcat(SsstStr, buf);
strcat(SsstStr, ",");
// ENCODER VIEWS
for (i = 0; i < 4; i++) {
MeanStdev( (enav + i), (ensd + i), nen[i], MISSING);
floatToString(buf, enav[i], 2, 6);
strcat(AvStr, buf);
strcat(AvStr, ",");
strcat(SsstStr, buf);
strcat(SsstStr, ",");
//floatToString(buf,ensd[i],1,4);
//strcat(AvStr,buf); strcat(AvStr,",");
}
// KT
for (i = 0; i < 4; i++) {
MeanStdev( (ktav + i), (ktsd + i), nkt[i], MISSING);
//mean
floatToString(buf, ktav[i], 0, 6);
strcat(AvStr, buf);
strcat(AvStr, ",");
strcat(SsstStr, buf);
strcat(SsstStr, ",");
//stdev
floatToString(buf, ktsd[i], 1, 4);
strcat(AvStr, buf);
strcat(AvStr, ",");
}
// BB TEMPS
for (i = 0; i < 4; i++) {
MeanStdev( (Tbbav + i), (Tbbsd + i), nbb[i], MISSING);
floatToString(buf, Tbbav[i], 2, 5);
strcat(AvStr, buf);
strcat(AvStr, ",");
floatToString(buf, Tbbsd[i], 2, 4);
strcat(AvStr, buf);
strcat(AvStr, ",");
}
// FINAL BB TEMPERATURES FOR SST COMPUTATION
T1 = 0;
i = 0;
//Serial.print("Tbbav[0] = "); Serial.println(Tbbav[0],2);
//Serial.print("Tbbav[1] = "); Serial.println(Tbbav[1],2);
if (Tbbav[0] > -20) {
T1 = Tbbav[0];
i = 1;
}
if (Tbbav[1] > -20) {
T1 += Tbbav[1];
i++;
}
if (i == 0) {
T1 = MISSING;
strcat(AvStr, "-999,");
strcat(SsstStr, "-999,");
}
else {
T1 = T1 / (double)i;
floatToString(buf, T1, 3, 6);
strcat(AvStr, buf);
strcat(AvStr, ",");
strcat(SsstStr, buf);
strcat(SsstStr, ",");
}
//Serial.print("T1 = "); Serial.println(T1,2);
T2 = 0;
i = 0;
if (Tbbav[2] > -20) {
T2 = Tbbav[2];
i = 1;
}
if (Tbbav[3] > -20) {
T2 += Tbbav[3];
i++;
}
if (i == 0) {
T2 = MISSING;
strcat(AvStr, "-999,");
strcat(SsstStr, "-999,");
}
else {
T2 = T2 / (double)i;
floatToString(buf, T2, 3, 6);
strcat(AvStr, buf);
strcat(AvStr, ",");
strcat(SsstStr, buf);
strcat(SsstStr, ",");
}
//Serial.print("T2 = "); Serial.println(T2,2);
// PITCH & ROLL
MeanStdev( &pitav, &pitsd, npit, MISSING);
floatToString(buf, pitav, 2, 5);
strcat(AvStr, buf);
strcat(AvStr, ",");
floatToString(buf, pitsd, 2, 5);
strcat(AvStr, buf);
strcat(AvStr, ",");
//Serial.print("Mean pitch = "); Serial.println(pitav,2);
//Serial.print("Stdev pitch = "); Serial.println(pitsd,2);
MeanStdev( &rolav, &rolsd, nrol, MISSING);
floatToString(buf, rolav, 2, 5);
strcat(AvStr, buf);
strcat(AvStr, ",");
floatToString(buf, rolsd, 2, 5);
strcat(AvStr, buf);
strcat(AvStr, ",");
//Serial.print("Mean roll = "); Serial.println(rolav,2);
//Serial.print("Stdev roll = "); Serial.println(rolsd,2);
// SEA ANGLE
sea_angle = enav[3] - rolav;
floatToString(buf, sea_angle, 1, 5);
strcat(AvStr, buf);
strcat(AvStr, ",");
strcat(SsstStr, buf);
strcat(SsstStr, ",");
//Serial.print("sea angle = "); Serial.println(sea_angle,2);
// EMISSIVITY
e_sea = GetEmis(sea_angle, MISSING);
floatToString(buf, e_sea, 6, 8);
strcat(AvStr, buf); // strcat(AvStr,",");
strcat(SsstStr, buf);
strcat(SsstStr, ",");
ssst = ComputeSSST(T1, T2, ktav[0], ktav[1], ktav[2], ktav[3], e_sea, ee.ebb, ee.Acorr, ee.Offset, MISSING, ee.CalFlag);
floatToString(buf, ssst, 2, 5);
strcat(SsstStr, buf); //strcat(SsstStr,",");
// CHECKSUM AND END
// AvStr -- averages
b = checksum_nmea(AvStr + 1);
Serial.print(AvStr);
Serial.print("*");
Serial.print(b, HEX);
Serial.print("\r\n");
// SsstStr
b = checksum_nmea(SsstStr + 1);
Serial.print(SsstStr);
Serial.print("*");
Serial.print(b, HEX);
Serial.print("\r\n");
// RESET FOR NEXT CYCLE
for (i = 0; i < 4; i++) {
// encoder -- 4 views
enav[i] = ensd[i] = 0;
nen[i] = 0;
// kt15 -- 4 views
ktav[i] = ktsd[i] = 0;
nkt[i] = 0;
// bb therms -- 4 each
Tbbav[i] = Tbbsd[i] = 0;
nbb[i] = 0;
}
// tilt sensor
pitav = pitsd = 0;
npit = 0;
rolav = rolsd = 0;
nrol = 0;
kavflag = 0;
}
isample = 0;
}
}
// =============== END OF LOOP =======================================
//*****************************************************************
void Action(char *cmd)
{
// Read message and take action.
// Create an output packet in out_buffer and send;
// input:
// in_buffer = pointer to a message string
// in_fromlist = char string, e.g. "121115"
// meaning the message came from 12 in the route 15->11->12
char str[50], str1[10];
char ix, yesno[4], eok = 0;
double fdum, ddum, av1, av2, fsum1, fsq1, fsum2, fsq2;
unsigned int nsum;
char *stop_at;
byte i, ib;
unsigned long Ldum;
int n, n1;
//Serial.print("Action cmd = "); Serial.println(cmd);
// TAKE ACTION AND PREPARE AN OUTPUT MESSAGE IN out_message
if (cmd[0] == '?') {
PrintProgramID();
Serial.println("------- EEPROM -----------------------------------");
Serial.println("E -- show eeprom ");
Serial.println("Ecfff.f -- BB1 point angle ECfff.f -- BB2 point angle");
Serial.println("EHnn -- set bb1 and bb2 heater, 0/1 = off,on. Standard=01");
Serial.println("Epfff.f -- SKY point angle EPfff.f -- OCEAN point angle");
Serial.println("EFfff.f -- Encoder Scan Tolerance");
Serial.println("EBnn -- Black body sample count EMn -- Shutter motor on=1, disable=0");
Serial.println("EUnn -- SKY sample count ETnn -- OCEAN (target) count");
Serial.println("EDfff.f -- Drum zero ref EEn -- MODE: 0=Run, 1=Cal");
Serial.println("ERfff.f -- Rain threshold volts Ernn -- Shutter open delay, nn secs");
Serial.println("Egfff.f -- Cal slope Acorr EGfff.f -- Cal offset, degC");
Serial.println("EAnff.f -- Ref R[n] = fff.f ohms Ehfff.f -- BB Emissivity");
Serial.println("");
Serial.println("------- FUNCTIONS -----------------------------------");
Serial.println("an -- ADC Chan n A -- ADC all loop");
Serial.println("bn -- BB n heater OFF Bn -- BB n heater ON");
Serial.println("c -- 5REF OFF C -- 5REF ON");
Serial.println("d[ff.f] -- Point to angle f.f, Omit f.f for current position");
Serial.println("Dff.f -- Set the encoder to ff.f");
Serial.println("fo -- Shutter Open (CCW) fc -- Shutter Close (CW)");
Serial.println("F -- Shutter 20x or keystroke");
Serial.println("h -- HE switches H -- HE loop");
Serial.println("k -- KT15 RAD K -- KT15 loop");
Serial.println("l -- Send KT15 command ");
Serial.println("m -- Drum motor CCW M -- Drum motor CW");
Serial.println("p -- pitch/roll single P -- pitch/roll loop");
Serial.println("r -- Rain check single R -- Rain check loop");
Serial.println("t -- Read system clock T -- Set default f.p. day");
Serial.println("sn -- LED test: 1=Heartbeat 2=Drum 3=Shutter/Rain");
Serial.println("wff.f-- GetEmis(ff.f,MISSING)");
Serial.println("Wff.f-- GetRadFromTemp(ff.f) --> GetTempFromRad");
Serial.println("x -- Compute SSST");
Serial.println("v/V -- Program version");
Serial.println("g/G -- Continue sampling.");
}
// READ ADC CHANNEL
else if (cmd[0] == 'a' && strlen(cmd) > 1) {
ix = cmd[1] - 48;
Serial.print("Chan ");
Serial.println(ix, DEC);
if (ix < 0 || ix > 15) {
Serial.println("Error");
}
else {
GetAdcSample(ix, (vmean + ix));
Serial.print("Chan ");
Serial.print(ix, DEC);
Serial.print(" ");
Serial.println(vmean[ix], 4);
}
}
// ADC LOOP
else if (cmd[0] == 'A') {
Serial.println("");
// v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 T11(0) T12(1) T21(4) T22(5) TKT(2) TKX(11) TWI(7) TPW(6) VIN(9) VREF(3) VRA(10)
// 2.630 2.634 0.409 2.473 2.632 2.630 1.812 2.575 4.096 3.664 -0.000 2.464 21.85 21.90 21.93 21.93 52.31 25.19 22.97 39.11 14.7 4.946 -0.0
Serial.println(" v0 v1 v2 v3 v4 v5 v6 v7 v8 v9 v10 v11 T11(0) T12(1) T21(4) T22(5) TKT(2) TKX(11) TWI(7) TPW(6) VIN(9) VREF(3) VRA(10)");
while ( !Serial.available() ) {
for (ix = 0; ix < ADCMAX; ix++) {
GetAdcSample(ix, (vmean + ix));
Serial.print(" ");
Serial.print(vmean[ix], 3);
}
Vref = vmean[3] * 2;
for (i = 0; i < 4; i++) {
Tbb[i] = ThermistorTemp(vmean[BbThermIndex[i]], Vref, ee.Rref[i], ee.ntherm[i]);
Serial.print(" ");
Serial.print(Tbb[i], 2);
}
// 0 1 2 3 4 5 6 7 8 9 10 11
// Rref = BB11 BB12 BB21 BB22 Tktx Twin Tpwr
// vmean= BB11 BB12 KTanalog Ref/2 BB21 BB22 Tpwr Twin Tkt15 Vin/4 Vrain/2 Tktx
// KT15 4-20
Tkt = KTanalogTemp(vmean[2]);
Serial.print(" ");
Serial.print(Tkt, 2);
// KT15 case thermistor
Tktx = ThermistorTemp(vmean[11], Vref, ee.Rref[4], 0); // 0 = standard steinhart-hart coefs
Serial.print(" ");
Serial.print(Tktx, 2);
// window temp
Twin = ThermistorTemp(vmean[7], Vref, ee.Rref[5], 0); // 0 = standard steinhart-hart coefs
Serial.print(" ");
Serial.print(Twin, 2);
// temp on the UWR power
Tpwr = ThermistorTemp(vmean[6], Vref, ee.Rref[6], 0); // 0 = standard steinhart-hart coefs
Serial.print(" ");
Serial.print(Tpwr, 2);
// VIN
ddum = vmean[9] * 4; // 0 = standard steinhart-hart coefs
Serial.print(" ");
Serial.print(ddum, 1);
// VREF
Serial.print(" ");
Serial.print(Vref, 3);
// VRAIN
ddum = vmean[10] * 4;
Serial.print(" ");
Serial.print(ddum, 1);
Serial.println("");
delay(500);
}
}
// BB HEATER ON
else if (cmd[0] == 'B' && strlen(cmd) > 1) {
ix = cmd[1] - 48;
Serial.print("BB");
Serial.print(ix, DEC);
Serial.println(" ON.");
if (ix < 1 || ix > 2) {
Serial.println("Error");
}
else {
if (ix == 1) BBHeater(BB1, ON);
else if (ix == 2) BBHeater(BB2, ON);
}
}
// BB HEATER OFF
else if (cmd[0] == 'b' && strlen(cmd) > 1) {
ix = cmd[1] - 48;
Serial.print("BB");
Serial.print(ix, DEC);
Serial.println(" OFF.");
if (ix < 1 || ix > 2) {
Serial.println("Error");
}
else {
if (ix == 1) BBHeater(BB1, OFF);
else if (ix == 2) BBHeater(BB2, OFF);
}
}
// 5REF TOGGLE ON/OFF
else if (cmd[0] == 'C' ) {
Serial.println("5REF ON");
Ref(ON);
}
else if (cmd[0] == 'c' ) {
Serial.println("5REF OFF");
Ref(OFF);
}
// SHUTTER MOTOR
else if (cmd[0] == 'f' && cmd[1] == 'o') {
ShutterOpen();
}
else if (cmd[0] == 'f' && cmd[1] == 'c') {
ShutterClose();
}
else if (cmd[0] == 'F') {
ib = 20;
i = 0;
Serial.print("Shutter cycle ");
Serial.print(ib);
Serial.println(" times");
if (digitalRead(DHe1) == 0 ) {
ShutterClose();
delay(1000);
}
while (i < ib) {
Serial.print("Cycle ");
Serial.print(i);
Serial.print(" of ");
Serial.println(ib);
ShutterOpen();
delay(5000);
ShutterClose();
delay(5000);
if ( Serial.available()) {
break;
}
}
}
// HALL EFFECT (HE) SWITCHES
else if (cmd[0] == 'h' || cmd[0] == 'H' ) {
Serial.println("CLOSED OPEN");
while ( !Serial.available() ) {
Serial.print(digitalRead(DHe1));
Serial.print(" ");
Serial.println(digitalRead(DHe2));
delay(1000);
}
}
// TIME
else if (cmd[0] == 't') {
Serial.println("Elapsed time as dd.hhmmss---");
while (1) {
Ldum = ElapsedTime(str);
Serial.print("Millisecs elapsed: "); Serial.print(Ldum);
Serial.print(" "); Serial.println(str);
if ( Serial.available()) {
break;
}
delay(2000);
}
}
// POINT SCAN DRUM
else if (cmd[0] == 'd') {
EncoderAngle = ReadEncoder(ee.encoderref);
Serial.print("Drum = ");
Serial.print(EncoderAngle, 2);
Serial.println(" deg");
if (strlen(cmd) > 1) {
ddum = atof(cmd + 1);
Serial.print("Request ");
Serial.println(ddum, 2);
EncoderAngle = PointScanDrum(ddum);
Serial.print("Final EncoderAngle = ");
Serial.println(EncoderAngle, 2);
}
}
else if (cmd[0] == 'D' && strlen(cmd) > 1) {
EncoderAngle = ReadEncoder(ee.encoderref);
Serial.print("Encoder now = ");
Serial.print(EncoderAngle, 2);
Serial.println(" deg");
Serial.print("NOTE--SET ENCODER ANGLE TO ");
Serial.println((cmd + 1));
strcpy(yesno, "n\0"); // default
Serial.println("Are you sure? Enter 'y' or 'n':");
Serial.readBytes(yesno, 1);
yesno[1] = '\0';
if ( yesno[0] == 'y' ) {
Serial.println("yes");
ddum = atof(cmd + 1) - EncoderAngle + ee.encoderref;
strcpy(str, "ED\0");
floatToString(str1, ddum, 1, 5);
str1[5] = '\0';
strcat(str, str1);
strcat(str, ",\0");
Serial.println(str);
Action(str);
}
else {
Serial.println("no");
}
}
// KT15
else if (cmd[0] == 'k') {
ReadKT15(&ddum, &fdum);
Serial.print("rad = ");
Serial.print(ddum, 0);
Serial.print(" irt = ");
Serial.println(fdum, 3);
}
else if (cmd[0] == 'K') {
fsum1 = fsq1 = fsum2 = fsq2 = 0;
nsum = 0;
Serial.println(" N RAD IRT");
ix = 0;
while (! Serial.available()) {
// index
Serial.print(ix, DEC);
Serial.print(" ");
ReadKT15(&ddum, &fdum);
fsum1 += ddum;
fsum2 += fdum;
fsq1 += ddum * ddum;
fsq2 += fdum * fdum;
nsum += 1;
Serial.print(ddum, 0);
Serial.print(" ");
Serial.println(fdum, 3);
delay(1000);
ix++;
}
if (nsum > 3) {
Serial.print("------");
Serial.print(" ");
Serial.println("------");
av1 = fsum1 / nsum;
av2 = fsum2 / nsum;
Serial.print(av1, 0);
Serial.print(" ");
Serial.println(av2, 3);
ddum = fsq1 / (nsum - 1) - nsum * av1 * av1 / (nsum - 1);
ddum = sqrt(ddum);
fdum = fsq2 / (nsum - 1) - nsum * av2 * av2 / (nsum - 1);
fdum = sqrt(fdum);
Serial.print(ddum, 0);
Serial.print(" ");
Serial.println(fdum, 3);
//ddum=100*ddum/av1; fdum=100*fdum/av2;
//Serial.print(ddum,1);Serial.print(" ");Serial.println(fdum,1);
}
}
// KT15 COMMAND
else if (cmd[0] == 'l') {
Serial.println("SEND A COMMAND TO KT15");
Serial.println("Enter a command: ");
Serial.setTimeout(30000);
ib = Serial.readBytesUntil('\r', str, 49);
str[ib] = '\0';
Serial.print("You entered: ");
Serial.println(str);
while (Serial3.available()) {
Serial3.read();
} // clear the input buffer
Serial3.println(str); // Send the string with lf
Serial3.setTimeout(100); // set the wait time
ib = Serial3.readBytesUntil('\n', str, 45); // capture incoming bytes
str[ib] = '\0'; // end the string
Serial.print("Reply: ");
Serial.println(str);
}
// EEPROM
else if ( cmd[0] == 'E' || cmd[0] == 'e') {
if ( strlen(cmd) <= 1 ) {
EepromPrint();
}
else if (strlen(cmd) > 2) {
eok = 0;
if ( cmd[1] == 'c') {
ddum = atof(cmd + 2);
Serial.print("SET BB1 ANGLE = ");
Serial.println(ddum, 2);
ee.abb1 = ddum;
eok = 1;
}
else if ( cmd[1] == 'C' ) {
ddum = atof(cmd + 2);
Serial.print("SET BB2 ANGLE = ");
Serial.println(ddum, 2);
ee.abb2 = ddum;
eok = 1;
}
else if ( cmd[1] == 'p' ) {
ddum = atof(cmd + 2);
Serial.print("SET SKY ANGLE = ");
Serial.println(ddum, 2);
ee.asky = ddum;
eok = 1;
}
else if ( cmd[1] == 'P' ) {
ddum = atof(cmd + 2);
Serial.print("SET OCEAN ANGLE = ");
Serial.println(ddum, 2);
ee.aocean = ddum;
eok = 1;
}
// else if( cmd[1]=='P' ){
// ddum = atof(cmd+2);
// Serial.print("SET OCEAN ANGLE = ");
// Serial.println(ddum,2);
// ee.aocean=ddum;
// eok=1;
// }
else if ( cmd[1] == 'g' ) {
ddum = atof(cmd + 2);
Serial.print("CAL SLOPE CORRECTION = ");
Serial.println(ddum, 5);
ee.Acorr = ddum;
eok = 1;
}
else if ( cmd[1] == 'G' ) {
ddum = atof(cmd + 2);
Serial.print("CAL OFFSET = ");
Serial.println(ddum, 3);
ee.Offset = ddum;
eok = 1;
}
else if ( cmd[1] == 'h' ) {
ddum = atof(cmd + 2);
Serial.print("BB EMISSIVITY = ");
Serial.println(ddum, 6);
ee.ebb = ddum;
eok = 1;
}
else if ( cmd[1] == 'H' ) {
if ( strlen(cmd) == 4) {
ee.bbheat[0] = cmd[2] - 48;
ee.bbheat[1] = cmd[3] - 48;
}
else {
ee.bbheat[0] = 0;
ee.bbheat[1] = 1;
}
eok = 1;
}
else if ( cmd[1] == 'A' ) {
ix = cmd[2] - 48;
if (ix < 0 || ix > 3 ) {
Serial.println("Error.");
}
else {
ddum = atof(cmd + 3);
Serial.print("Set BB Rref[");
Serial.print(ix, DEC);
Serial.print("] = ");
Serial.print(ddum, 1);
Serial.println("ohms.");
ee.Rref[ix] = ddum;
}
}
else if ( cmd[1] == 'R' ) {
ddum = atof(cmd + 2);
Serial.print("SET RAIN THRESHOLD = ");
Serial.println(ddum, 2);
ee.rain_threshold = ddum;
eok = 1;
}
else if ( cmd[1] == 'E' ) {
Serial.print("SET MODE: ");
ix = atoi(cmd + 2);
if (ix == 0) {
Serial.println("RUN");
}
else if (ix == 1) {
Serial.println("CALIBRATION");
}
else {
Serial.println("UNDEFINED, NO CHANGE");
}
ee.CalFlag = ix;
eok = 1;
}
else if ( cmd[1] == 'r' ) {
ix = atoi(cmd + 2);
Serial.print("SET RAIN DELAY SECS = ");
Serial.println(ix, DEC);
ee.rainsecs = ix;
eok = 1;
}
else if ( cmd[1] == 'D' || cmd[1] == 'd' ) {
ddum = atof(cmd + 2);
Serial.print("SET ENCODER REF = ");
Serial.println(ddum, 2);
ee.encoderref = ddum;
eok = 1;
}
else if ( cmd[1] == 'F' ) {
ddum = atof(cmd + 2);
Serial.print("SET SCAN TOLERANCE = ");
Serial.println(ddum, 2);
ee.ScanTolerance = ddum;
eok = 1;
}
else if ( cmd[1] == 'B' ) {
ix = atoi(cmd + 2);
Serial.print("SET BB Count = ");
Serial.println(ix);
ee.Nbb = ix;
eok = 1;
}
else if ( cmd[1] == 'U' ) {
ix = atoi(cmd + 2);
Serial.print("SET Sky Count = ");
Serial.println(ix);
ee.Nsky = ix;
eok = 1;
}
else if ( cmd[1] == 'T' ) {
ix = atoi(cmd + 2);
Serial.print("SET Ocean Count = ");
Serial.println(ix);
ee.Nocean = ix;
eok = 1;
}
else if ( cmd[1] == 'M' ) {
ix = atoi(cmd + 2);
Serial.print("Shutter on/off = ");
Serial.println(ix);
ee.ShutterFlag = ix;
eok = 1;
}
if ( eok == 1 ) {
EepromStore();
EepromPrint();
}
}
}
// SCAN DRUM MOTOR
else if (cmd[0] == 'm' || cmd[0] == 'M' ) {
if ( cmd[0] == 'm' ) {
ScanMotor(CCW);
Serial.println("Scan drum CCW");
}
else {
ScanMotor(CW);
Serial.println("Scan drum CW");
}
while ( !Serial.available() );
ScanMotor(STOP);
Serial.println("Scan drum STOP");
}
// PITCH/ROLL
else if (cmd[0] == 'p') {
ReadTilt(&ddum, &fdum);
Serial.print("pitch = ");
Serial.print(ddum, 2);
Serial.print(" roll = ");
Serial.println(fdum, 2);
}
else if (cmd[0] == 'P') {
Serial.println(" N PITCH ROLL");
ix = 0;
while (! Serial.available()) {
// index
Serial.print(ix, DEC);
Serial.print(" ");
ReadTilt(&ddum, &fdum);
Serial.print(ddum, 2);
Serial.print(" ");
Serial.println(fdum, 2);
delay(1000);
ix++;
}
}
// RAIN
else if (cmd[0] == 'r') {
CheckRain( &ddum, &Ldum );
Serial.print("Rain volts = ");
Serial.print(ddum, 2);
Serial.print(" Sec to open = ");
Serial.print(Ldum);
Serial.print(" State = ");
Serial.println(RainState, DEC);
}
else if (cmd[0] == 'R') {
Serial.println(" N STATUS VOLTS SECS");
ix = 0;
while (! Serial.available()) {
// index
Serial.print(ix, DEC);
Serial.print(" ");
CheckRain( &ddum, &Ldum );
Serial.print(RainState, DEC);
Serial.print(" ");
Serial.print(ddum, 2);
Serial.print(" ");
Serial.println( Ldum );
delay(1000);
ix++;
}
}
// EMISSIVITY
else if (cmd[0] == 'w' && strlen(cmd) > 1) {
ddum = atof(cmd + 1);
fdum = GetEmis(ddum, MISSING);
Serial.print("View angle=");
Serial.print(ddum, 1);
Serial.print(" Emissivity=");
Serial.println(fdum, 6);
}
// PLANCK CALCULATIONS GetRadFromTemp
else if (cmd[0] == 'W' && strlen(cmd) > 1) {
ddum = atof(cmd + 1);
fdum = GetRadFromTemp(ddum);
Serial.print("T = ");
Serial.print(ddum, 3);
Serial.print(" RAD=");
Serial.println(fdum, 6);
ddum = GetTempFromRad(fdum);
Serial.print("RAD = ");
Serial.print(fdum, 6);
Serial.print(" T =");
Serial.println(ddum, 3);
}
// COMPUTE SSST
else if (cmd[0] == 'x') {
Serial.println("T1, T2, k1, k2, ksky, ksea, e_sea, ebb, Acorr, Offset");
Serial.println("19.835,34.322,161078,197500,111319,152559,0.98753,1,1.0106,-0.0426");
ddum = ComputeSSST(19.835, 34.322, 161078, 197500, 111319, 152559, 0.98753, 1, 1.0106, -0.0426, MISSING, 0);
Serial.print("SSST = ");
Serial.print(ddum, 3);
Serial.println(" degC");
}
else if (cmd[0] == 'X') {
ddum = 1234567890;
floatToString(str, ddum, 0, 12);
Serial.print(ddum, 6);
Serial.print(" ");
Serial.print(str);
}
else if (cmd[0] == 's' && strlen(cmd) > 1) {
ix = cmd[1] - 48;
n = 1;
if (ix == 1) {
Serial.println("HEARTBEAT LED FLASH");
n1 = LED31;
}
else if (ix == 2) {
Serial.println("DRUM LED FLASH");
n1 = LED11;
}
else if (ix == 3) {
Serial.println("SHUTTER LED FLASH");
n1 = LED12;
}
else {
Serial.println("HEARTBEAT LED FLASH");
n1 = LED31;
}
// flash led
while (! Serial.available()) {
digitalWrite(n1, HIGH);
delay(500);
digitalWrite(n1, LOW);
delay(500);
}
}
// testing Serial1
// else if(cmd[0] == 'q' ){
// while(! Serial.available()){
// Serial.println("HIGH");
// Ref(OFF);
// delay(5000);
// Serial.println("LOW");
// Ref(ON);
// delay(5000);
// }
// Serial.read();
// Serial.println();
// }
// VERSION
else if (cmd[0] == 'v' || cmd[0] == 'V') {
PrintProgramID();
}
// RETURN TO RUN
else if (cmd[0] == 'g' || cmd[0] == 'G') {
RunMode == RUN;
}
// DEFAULT
else {
Serial.print(cmd);
Serial.println(" not recognized.");
}
return;
}
//==================================================================
void BBHeater(int j, int k)
/***************
* input:
* j = BB1 or BB2
* k = ON or OFF
**********/
{
if (j == BB1) {
if (k == ON) {
digitalWrite(BB1, HIGH);
digitalWrite(LED22, HIGH);
}
if (k == OFF) {
digitalWrite(BB1, LOW);
digitalWrite(LED22, LOW);
}
}
else if (j == BB2) {
if (k == ON) {
digitalWrite(BB2, HIGH);
digitalWrite(LED21, HIGH);
}
if (k == OFF) {
digitalWrite(BB2, LOW);
digitalWrite(LED21, LOW);
}
}
return;
}
//==========================================================================
double ThermistorTemp(double v, double Vref, double Rref, unsigned int ntherm) {
double r;
double a[3], t;
if (v < threshold[0]) return 0;
if (v > threshold[1]) return 200;
GetThermCoefs(ntherm, a);
r = Rref * (v / (Vref - v));
t = SteinhartHart(a, r);
return t;
}
//======================================================================================
void CheckRain(double *v, unsigned long *rainsecs)
// Output
// v = analog (volts)
// rainsecs = seconds until shutter opens
// RETURN 1 or 0 for rain mode and shutter control.
// Global in
// ee.rain_threshold;
// ee.rainsecs;
// Global out
// unsigned long millisec_rain; // clock count for opening
// RainState
{
int a;
GetAdcSample(Arain, v);
*v *= 4;
//Serial.print("Chan "); Serial.print(Arain,DEC); Serial.print(" "); Serial.println(*v,4);
// RAIN
if ( *v > ee.rain_threshold ) {
RainState = 1;
millisec_rain = millis();
*rainsecs = ee.rainsecs;
}
// NO RAIN
else {
// SHUTTER IS CLOSED
if ( RainState == 1 ) {
secs_lapsed = ( millis() - millisec_rain ) / 1000;
// TIME TO OPEN
if ( secs_lapsed > ee.rainsecs ) {
RainState = 0;
*rainsecs = 0;
}
// DRYING TIME
else {
RainState = 1;
*rainsecs = ee.rainsecs - secs_lapsed;
}
}
else {
*rainsecs = 0;
RainState = 0;
}
}
return;
}
//***************************************************************************
unsigned int checksum_nmea(char *strPtr) {
// code -- http://www.mculabs.com/snippets/nmea_checksum.html
// validate -- http://www.hhhh.org/wiml/proj/nmeaxor.html
int p;
char c;
byte chksum;
c = strPtr[0]; // get first chr
chksum = c;
p = 1;
while ( c != 0x00 ) {
c = strPtr[p]; // get next chr
if ( c != 0x00 ) {
chksum = chksum ^ c;
}
p++;
}
return chksum;
}
//============================================================================
// void Configure4017(void)
// // %0101090600
// //See adam 4000 manual page 5-4
// {
// char cmd1[5];
// char cmd2[12];
// char strin[15];
// byte i, j, ic, chrin,lencmd,rxlen;
// unsigned long millistart, millilapsed; // define input wait time
//
// strcpy(cmd1,"$012");
// strcpy(cmd2,"%0101090600");
//
// // SEND CMD1
// for(i=0;i<4;i++){Serial2.write(cmd1[i]);}
// Serial2.write(13);
//
// delay(10);
//
// // Receive string
// millistart = millis();
// j=0;
// while(j<11){
// if( Serial2.available() ){
// chrin=Serial2.read();
// if(chrin == 13){break;}
// else{ strin[j++]=chrin; }
// }
// millilapsed=millis()-millistart;
// if ( millilapsed > 700 ) break;
// }
// strin[j]='\0';
// Serial.print("Configuration: ");Serial.println(strin);
//
// Serial.println("Configuration should be %0101090600");
// Serial.println("Do you want to set the configuration? (enter y or Y)");
// while ( Serial.available()==0 );
// chrin=Serial.read();
// if ( chrin == 'y' || chrin == 'Y' ){
// Serial.println("Change to default. Valid reply is !01");
// // SEND CMD2
// for(i=0;i<11;i++){Serial2.write(cmd2[i]);}
// Serial2.write(13);
//
// delay(10);
//
// // Receive string
// millistart = millis();
// j=0;
// while(j<11){
// if( Serial2.available() ){
// chrin=Serial2.read();
// if(chrin == 13){break;}
// else{ strin[j++]=chrin; }
// }
// millilapsed=millis()-millistart;
// if ( millilapsed > 700 ) break;
// }
// strin[j]='\0';
// Serial.print("Reply: ");Serial.println(strin);
// } else {
// Serial.println("Do NOT change configuration.");
// }
// }
//========================================================================
float DiffAngle(float a2, float a1) {
// Compute the smallest angle arc between the a2 and a1.
float arc;
arc = a2 - a1;
if ( abs(arc) > 180 ) {
if ( sign(arc) > 0 ) arc -= 360;
else arc += 360;
}
return arc;
}
//*******************************************************************
void EepromDefault() {
int i;
Serial.println("Initialize eeprom...");
ee.id = EEPROM_ID;
ee.abb1 = default_abb1;
ee.abb2 = default_abb2;
ee.asky = default_asky;
ee.aocean = default_aocean;
ee.encoderref = default_encoderref;
ee.Nbb = default_Nbb;
ee.Nsky = default_Nsky;
ee.Nocean = default_Nocean;
ee.ShutterFlag = default_shutter;
ee.CalFlag = default_CalFlag;
ee.rain_threshold = default_rain_threshold;
ee.rainsecs = default_rainsecs;
for (i = 0; i < 7; i++) {
ee.Rref[i] = default_Rref[i];
}
ee.bbheat[0] = default_bbheat[0];
ee.bbheat[1] = default_bbheat[1];
ee.ntherm[0] = default_ntherm[0];
ee.ntherm[1] = default_ntherm[1];
ee.ntherm[2] = default_ntherm[2];
ee.ntherm[3] = default_ntherm[3];
//ee.bbheater=default_bbheater;
ee.pt2b[0] = default_pt2b[0];
ee.pt2b[1] = default_pt2b[1];
ee.pt2b[2] = default_pt2b[2];
ee.pt2b[3] = default_pt2b[3];
ee.pb2t[0] = default_pb2t[0];
ee.pb2t[1] = default_pb2t[1];
ee.pb2t[2] = default_pb2t[2];
ee.pb2t[3] = default_pb2t[3];
ee.ScanTolerance = SCAN_TOLERANCE;
ee.Acorr = default_Acorr;
ee.Offset = default_Offset;
ee.ebb = default_ebb;
EepromStore();
EepromRead();
EepromPrint();
}
//=============================================================================
void EepromStore()
//Determines the size of the structure and stores it entirely
//in eeprom space
{
Serial.println("StoreUee...");
int i;
// pointer to struct ee
//struct eeprom* ptr = ⅇ
byte* a = &(ee.id);
// for each byte in the eeprom structure
for (i = 0; i < eeSize; i++) {
EEPROM.write(i, *a ); // store this byte
a++;
}
return;
}
//=============================================================================
void EepromRead()
{
Serial.println("ReadUee:");
int i;
// pointer to struct ee
byte* a = &(ee.id);
// for each byte in the eeprom structure
for (i = 0; i < eeSize; i++)
{
*a = EEPROM.read(i); // get the byte
a++;
}
return;
}
//===============================================================================
void EepromPrint()
{
int i;
Serial.println("EepromPrint: ");
Serial.print(" ID = ");
Serial.print(ee.id);
Serial.println(" ");
//Serial.print(" E BBHeater = ");
//Serial.println(ee.bbheater,DEC); xyx
Serial.print(" c BB1 angle = ");
Serial.print(ee.abb1, 2);
Serial.println(" deg");
Serial.print(" C BB2 angle = ");
Serial.print(ee.abb2, 2);
Serial.println(" deg");
Serial.print(" p sky angle = ");
Serial.print(ee.asky, 2);
Serial.println(" deg");
Serial.print(" P ocean angle = ");
Serial.print(ee.aocean, 2);
Serial.println(" deg");
Serial.print(" D drum zero ref = ");
Serial.print(ee.encoderref, 2);
Serial.println(" deg");
Serial.print(" F Encoder scan tolerance = ");
Serial.print(ee.ScanTolerance, 2);
Serial.println(" deg");
Serial.print(" B BB sample count = ");
Serial.print(ee.Nbb);
Serial.println("");
Serial.print(" U sky sample count = ");
Serial.print(ee.Nsky);
Serial.println("");
Serial.print(" T ocean sample count = ");
Serial.print(ee.Nocean);
Serial.println("");
Serial.print(" M Shutter on/off = "); //v25
Serial.print(ee.ShutterFlag, 2);
Serial.println(""); //v25
Serial.print(" E Calibration Flag = ");
Serial.println(ee.CalFlag);
Serial.print(" R Rain threshold = ");
Serial.print(ee.rain_threshold, 2);
Serial.println(" volts");
Serial.print(" r Rain shutter delay = ");
Serial.print(ee.rainsecs);
Serial.println(" secs");
Serial.print(" g Acorr = ");
Serial.print(ee.Acorr, 5);
Serial.println("");
Serial.print(" G Offset = ");
Serial.print(ee.Offset, 4);
Serial.println("");
Serial.print(" h BB Emis = ");
Serial.print(ee.ebb, 5);
Serial.println("");
Serial.print(" A Ref esistors = ");
for (i = 0; i < 7; i++) {
Serial.print(ee.Rref[i], 1);
Serial.print(" ");
}
Serial.println("");
Serial.print(" BB heater configuration = ");
Serial.print(ee.bbheat[0], DEC);
Serial.print(" ");
Serial.println(ee.bbheat[1], DEC);
Serial.print(" BB Therm SNs = ");
for (i = 0; i < 4; i++) {
Serial.print(ee.ntherm[i], 1);
Serial.print(" ");
}
Serial.println("");
Serial.print(" T to B Quadratic = ");
for (i = 0; i < 4; i++) {
Serial.print(ee.pt2b[i], 8);
Serial.print(" ");
}
Serial.println("");
Serial.print(" B to T Quadratic = ");
for (i = 0; i < 4; i++) {
Serial.print(ee.pb2t[i], 8);
Serial.print(" ");
}
Serial.println("");
return;
}
//*******************************************************************
char * floatToString(char * outstr, double val, byte precision, byte widthp)
/********
* Convert a double prec variable to a string of characters.
* Example floatToString(s, 123.456, 2, 8) returns
* s = [' ',' ','1','2','3','.','4','6','\0'] for 8 characters and a NULL
*********/
{
// http://forum.arduino.cc/index.php/topic,37391.0.html
char temp[16];
byte i;
// ROUNDING
double roundingFactor = 0.5;
unsigned long mult = 1;
for (i = 0; i < precision; i++)
{ // *
roundingFactor /= 10.0; // .5, .05, .005, ...
mult *= 10; // 1, 10, 100, ...
}
// OUTSTRING
temp[0] = '\0';
outstr[0] = '\0';
// NEGATIVE NUMBERS
if (val < 0.0) {
strcpy(outstr, "-\0");
val = -val;
}
// 123.461
val += roundingFactor;
strcat(outstr, ltoa(long(val), temp, 10)); //prints the int part
if ( precision > 0) {
strcat(outstr, ".\0"); // print the decimal point
unsigned long frac;
unsigned long mult = 1;
byte padding = precision - 1;
while (precision--)
mult *= 10;
if (val >= 0)
frac = (val - long(val)) * mult;
else
frac = (long(val) - val ) * mult;
unsigned long frac1 = frac;
while (frac1 /= 10)
padding--;
while (padding--)
strcat(outstr, "0\0");
strcat(outstr, ltoa(frac, temp, 10));
}
//Serial.print("test2 ");Serial.println(outstr);
// generate space padding
if ((widthp != 0) && (widthp >= strlen(outstr))) {
byte J = 0;
J = widthp - strlen(outstr);
for (i = 0; i < J; i++) {
temp[i] = ' ';
}
temp[i++] = '\0';
strcat(temp, outstr);
strcpy(outstr, temp);
}
return outstr;
}
//======================================================================================
double GetAdcVolts (unsigned int chan) {
//GetAdcVolts returns a single read of 16 bit adc channel ch.
double v;
int16_t adc;
if (chan >= 0 && chan <= 3)
adc = ads0.readADC_SingleEnded(chan);
else if (chan >= 4 && chan <= 7)
adc = ads1.readADC_SingleEnded(chan - 4);
else if (chan >= 8 && chan <= 11)
adc = ads2.readADC_SingleEnded(chan - 8);
else adc = 0;
v = (double)adc / 8000;
return v;
}
//======================================================================================
unsigned int GetAdcSample(unsigned int ch, double *vmean) {
// okflag = GetAdcSample(ch, *vmean){
// GetAdcSample takes nsap (=10) readings of the ADC channel ch. Tosses out the min and max
// voltages and takes the mean of the remainder.
double v, vi[10], vsum, vmn, vmx;
unsigned int i, imx, imn, nav;
nav = 10;
vsum = 0;
vmx = -1e15;
vmn = 1e15;
imx = imn = 0;
for (i = 0; i < nav; i++) {
v = vi[i] = GetAdcVolts(ch);
vsum += vi[i];
if (v < vmn) {
imn = i;
vmn = v;
}
if (v > vmx) {
imx = i;
vmx = v;
}
}
*vmean = (vsum - vi[imx] - vi[imn]) / (double)(nav - 2);
return 1;
}
//=================================================================#
double GetEmis( double vsea, double missing)
/* COMPUTE EMISSIVITY OF THE SEA SURFACE FROM A GIVEN
VIEWING ANGLE. See email from Donlon 040313
Call: emis = GetEmis($viewangle, $missing)
INPUT
$viewangle = the isar drum angle toward the sea. From 90-180 deg.
OUTPUT
emissivity: viewangle from 90-120 emis=$missing, from 120-140 deg, emai is calculated, from 140-180 deg, emis = 0.99
20150211 rmr
*/
{
double e_sea;
double vx;
double p[3] = {
-7.00848940533115e-05, 0.00581739911141455, 0.867605108660296
};
double a1;
double a2;
double e1;
double e2;
int i;
double va[21] = {
40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60
};
double esea[21] = {
0.9893371, 0.9889863, 0.9885924, 0.9881502, 0.9876541, 0.9870975, 0.9864734, 0.9857735,
0.9849886, 0.9841085, 0.9831214, 0.9820145, 0.9807728, 0.9793796, 0.9778162, 0.9760611,
0.9740904, 0.9718768, 0.9693894, 0.9665933, 0.9634488
};
e_sea = missing;
vx = 180 - vsea; // vx = nadir angle
// NEAR VERTICAL POINTING
if ( vx >= 0 && vx < 40 ) e_sea = 0.99;
// NEAR HORIZONTAL, APPROXIMATION
// I worked out a matlab fit
else if ( vx > 60 && vx < 90) {
e_sea = vx * vx * p[0] + vx * p[1] + p[2]; // quadratic fit
//p[2] = {-0.00251543428571427, 1.11488077142857}; // linear fit
//esea = vx * p[0] + p[1];
// FINAL NUDGE
//esea += .05;
}
// 40 <= vx <= 60 // donlon email 040317
else if (vx >= 40 && vx <= 60) {
for (i = 1; i <= 20; i++ ) {
if ( va[i] >= vx ) {
a2 = va[i];
a1 = va[i - 1];
e2 = esea[i];
e1 = esea[i - 1];
e_sea = e1 + (vx - a1) * (e2 - e1) / (a2 - a1);
break;
}
}
}
return (e_sea);
}
//===========================================================================
double GetMotorCurrent(void) {
// Read two analog channels and take the difference.
double vdiff = 0;
int v1 = 0, v2 = 0;
//Serial.println("C");
v1 = analogRead(I1a);
v2 = analogRead(I1b);
vdiff = (double)(v1 - v2);
//Serial.print(v1);
//Serial.print(" ");
//Serial.print(v2);
//Serial.print(" diff=");
//Serial.println(vdiff);
return vdiff;
}
//============================================================
unsigned int GetThermCoefs(unsigned int nt, double c[] ) {
// Give the correct SHH coefs for the thermnumber
// COMPUTE TEML
double tcal[9][3] = {
//0 standard ysi
{ 1.025579e-03, 2.397338e-04, 1.542038e-07 },
//1 Therm #1, Rosr1 T11
{ 1.0108115e-03, 2.4212099e-04, 1.4525424e-07 },
//2 Therm #2, ROSR1, T12
{ 1.0138029e-03, 2.4156995e-04, 1.4628056e-07 },
//3 Therm #3, ROSR1, T21
{ 1.0101740e-03, 2.4208389e-04, 1.4485814e-07 },
//4 Therm #4, ROSR1, T22
{ 1.0137647e-03, 2.4161708e-04, 1.4619775e-07 },
//5 Therm #5, ROSR2, T11
// { 1.0136495e-03, 2.4158562e-04, 1.4769608e-07 },
{ 1.0073532E-03, 2.41655931E-04, 1.56252214E-07 },
//6 Therm #8, ROSR2, T12
{ 1.00647228E-03, 2.42265935E-04, 1.50546312E-07 },
//7 Therm #9, ROSR2, T21
{ 1.01935214E-03, 2.40428900E-04, 1.56322696E-07 },
//8 Therm #10, ROSR2, T22
{ 1.02013510E-03, 2.40304832E-04, 1.55160255E-07 }
};
if (nt < 0 || nt > 8) {
Serial.print("Error in GetThermCoefs() -- bad thermnumber=");
Serial.println(nt, DEC);
c[0] = c[1] = c[2] = 0;
return 0;
}
else {
c[0] = tcal[nt][0];
c[1] = tcal[nt][1];
c[2] = tcal[nt][2];
return 1;
}
}
//==========================================================================
long Hex2Dec(char *e)
// Convert a 3-char hex string to a decimal number
{
unsigned int j;
byte i;
// Serial.print(e[0],DEC); Serial.print(" ");
if (e[0] >= 48 && e[0] <= 57) i = e[0] - 48;
else if (e[0] >= 65 && e[0] <= 70) i = e[0] - 55;
else return MISSING;
// else {Serial.println(" BAD"); return MISSING;}
j = i * 256;
// Serial.print(e[1],DEC); Serial.print(" ");
if (e[1] >= 8 && e[1] <= 57) i = e[1] - 48;
else if (e[1] >= 65 && e[1] <= 70) i = e[1] - 55;
else return MISSING;
// else {Serial.println(" BAD"); return MISSING;}
j = j + i * 16;
// Serial.println(e[2],DEC);
if (e[2] >= 48 && e[2] <= 57) i = e[2] - 48;
else if (e[2] >= 65 && e[2] <= 70) i = e[2] - 55;
// else {Serial.println(" BAD"); return MISSING;}
else return MISSING;
j = j + i;
return j;
}
//====================================================================================================
double KTanalogTemp(double v) {
double t;
double r = 50.0; // loop resistor => .2 to 1.0 v
double imin = 0.0; // 4-20 ma loop
double imax = 20.0; // ditto
double tmin = -100; // from manual
double tmax = 200.0; // ditto
t = tmin + (tmax - tmin) * (v - imin * r / 1000) / ((imax - imin) * r / 1000);
return t;
}
//====================================================================================================
void MeanStdev(double *sum, double *sum2, int N, double missing)
// Compute mean and standard deviation from
// the count, the sum and the sum of squares.
{
if ( N <= 2 ) {
*sum = missing;
*sum2 = missing;
}
else {
*sum /= (double)N; // mean value
*sum2 = *sum2 / (double)N - (*sum * *sum); // sumsq/N - mean^2
*sum2 = *sum2 * (double)N / (double)(N - 1); // (N/N-1) correction
if ( *sum2 < 0 ) *sum2 = 0;
else *sum2 = sqrt(*sum2);
}
return;
}
//====================================================================================================
float PointScanDrum(float requestpos) {
// Move the encoder angle to a requested position
// Choose the smallest arc angle and move in that direction.
// Within +/-8 degrees of the requested position
// We need to cycle the drive very fast to get the necessary read
// resolution using ReadEncoder(). Without this approach,
// ReadEncoder() returns a position of 2-3 degrees at full speed
// which is way beyond the precision of the A2 encoder.
//
// We may overshoot as we approach the requestpos and if there
// is not an unequal shift fwd/back, we enter a hysteresis state.
//
//INPUT
// requestpos = the desired angle
// OUTPUT
// pos = the final encoder angle
//
float pos = 0, diff = 0, lmmult = 1000;
int direction = CW; //, iOldDirection=CW;
int msdelay;
byte ib;
unsigned long ulTime;
// Get the initial encoder position
pos = ReadEncoder (ee.encoderref);
if (pos == MISSING) {
Serial.println("PointScanDrum error, ReadEncoder=MISSING.");
return MISSING;
}
// Compute the smallest arc between pos and the requestpos
diff = DiffAngle(requestpos, pos);
//Serial.print("diff = ");
//Serial.println(diff,2);
// Only move the encoder if necessary
if ( fabs(diff) > ee.ScanTolerance ) {
// LED11 on
digitalWrite(LED11, HIGH);
// set timer
ulTime = millis(); // The beginning of the positioning.
// If the encoder is +/-5 degrees from requestpos
// start the motors continuously until we are within
// ~5 degrees
while (fabs(diff) > 5) {
if ( sign(diff) < 0 ) {
//Serial.print("Motor CCW.");
ScanMotor(CCW);
}
else {
//Serial.print("Motor CW.");
ScanMotor(CW);
}
delay(10);
pos = ReadEncoder(ee.encoderref);
diff = DiffAngle(requestpos, pos);
if ( millis() - ulTime > 10000 ) {
Serial.println("PointScanDrum course timeout");
digitalWrite(LED11, LOW);
return pos;
}
}
ScanMotor(STOP);
pos = ReadEncoder(ee.encoderref);
//Serial.print("End of course, ");Serial.println(pos,2);
// NUDGING (W TIMEOUT)
//Serial.println("Begin nudging. Pos=");Serial.println(pos,2);
while (fabs(diff) >= ee.ScanTolerance) {
pos = ReadEncoder(ee.encoderref);
diff = DiffAngle(requestpos, pos);
// DIRECTION
if ( sign(diff) < 0 ) {
direction = CCW;
}
else {
direction = CW;
}
// MOTOR ON TIME
msdelay = abs(diff) * 8;
if (msdelay < 2) msdelay = 2;
ScanMotor(direction);
delay(msdelay);
ScanMotor(STOP);
// SETTLE AND CHECK
delay(120);
pos = ReadEncoder(ee.encoderref);
diff = DiffAngle(requestpos, pos);
// GIVE UP AFTER A SMALL EFFORT
if ( millis() - ulTime > 5000 ) {
Serial.println("PointScanDrum timeout");
return pos;
}
}
}
// Read the final position
pos = ReadEncoder(ee.encoderref);
digitalWrite(LED11, LOW);
return pos;
}
//==================================================================
void PrintBytes(char *str) {
int i, ic;
i = strlen(str);
Serial.print("PrintBytes: ");
for (ic = 0; ic < i; ic++) {
Serial.print(str[ic], HEX);
Serial.print(", ");
}
Serial.println("");
}
//==================================================================
void PrintProgramID(void)
{
Serial.println("");
Serial.print("PROGRAM:");
Serial.print(PROGRAMNAME);
Serial.print(" VERSION:");
Serial.print(VERSION);
Serial.print(" EDIT:");
Serial.print(EDITDATE);
Serial.println("");
}
//*******************************************************
// void Read4017 (double *adc, char chan)
// // Issue a command to the 4017, jump to receive, read in the string.
// // See Adam 4000 manual page 4-14,
// // #01<cr> for all channels, >+7.2111+7.23453+...<cr>
// // ">+02.368+02.393+02.404+02.399+01.685+00.866+00.461+00.237" len=57
// // #01x<cr> where x=0-7, >+1.4567<cr>
// // ">+02.394" len=8
// // adc[7] is a float array of the result of the read.
// {
// char strcmd[6];
// char strin[65];
// byte i, j, ic, chrin,lencmd,rxlen;
// unsigned long millistart, millilapsed; // define input wait time
//
// //Serial.print("Read4017: "); Serial.println(chan,DEC);
//
// // MAKE COMMAND
// // all channels
// if ( chan > 7 || chan < 0 ) {
// strncpy(strcmd,"#01",3);
// strcmd[3] = '\0';
// lencmd = 3;
// rxlen=59;
// }
// // single channel
// else {
// // individual channel
// strncpy(strcmd,"#01",3);
// strcmd[3]=chan+48;
// strcmd[4]='\0';
// lencmd=4;
// rxlen=9;
// }
//
// // Command sent
// for(i=0;i<lencmd;i++){
// Serial2.write(strcmd[i]);
// }
// Serial2.write(13);
//
// delay(10);
//
// // Receive string
// millistart = millis();
// j=0;
// while(j<rxlen){
// if( Serial2.available() ){
// chrin=Serial2.read();
// if(chrin == 13){break;}
// else{ strin[j++]=chrin; }
// }
// millilapsed=millis()-millistart;
// if ( millilapsed > 700 ) break;
// }
// //Serial2.setTimeout(700);
// //Serial2.readBytes(strin,rxlen);
//
// //ic = strlen(strin);
// //Serial.print(ic);
// //Serial.println(" bytes received.");
// //Serial.println(strin);
//
// strin[rxlen]='\0';
// if(rxlen==9){
// adc[chan]=atof( strin+1 );
// //Serial.println(adc[0],2);
// }
// else {
// j=0;
// for(i=1; i<rxlen; i++){
// if(strin[i]=='+'|| strin[i]=='-'){
// adc[j]=atof( strin+i );
// //Serial.print(j);Serial.print(" "); Serial.println(adc[j],2);
// j++;
// }
// }
// }
// }
//
//*******************************************************
float ReadEncoder (float ref)
// Read the USDIGITAL encoder
// Absolute position is computed using output = encoder angle - ref
// input: zero reference angle.
// output: encoder angle - ref OR MISSING
// global variables:
// MISSING (=-999)
{
unsigned char count = 0; // number of trys for input;
unsigned long microstart, micronow; // define input wait time
byte i = 0; // number of bytes in the buffer.
float angle = MISSING;
byte e[4];
count = 0;
while ( count < 3 ) {
// position command
Serial1.write(EncCmd);
// get three bytes
microstart = micros();
i = 0;
while (i <= 2) {
// i=0 get the command byte
if (i == 0 && Serial1.available()) {
e[0] = Serial1.read();
if (e[0] == EncCmd) {
//Serial.print("0-");Serial.print(e[0],HEX);
i++;
}
}
// i=1 First byte
else if (Serial1.available() && i == 1) {
e[1] = Serial1.read();
//Serial.print(" 1-");Serial.print(e[1],HEX);
i++;
}
// i=2, second byte
else if (Serial1.available() && i == 2) {
e[2] = Serial1.read();
//Serial.print(" 2-");Serial.println(e[2],HEX);
i++;
}
// timeout
else if ( micros() - microstart > 10000 ) {
//Serial.println("ReadEncoder timeout.");
break;
}
}
// DO WE HAVE A GOOD ANGLE
if ( i >= 2 ) {
// This next calc assumes an encoder setting of 14400 resolution
angle = (float)(e[1] * 256 + e[2]) / 40.0;
//Serial.print("angle=");Serial.print(angle,2);
if (angle >= 0 && angle <= 360) {
count = 100;
}
}
// if not, try again
else {
count++;
}
}
//Serial.print("angle = ");Serial.println(angle,3);
if ( angle != (float)MISSING ) {
//Serial.print("ref = ");Serial.println(ref,3);
angle += ref;
if ( angle >= 360 ) angle -= 360;
if ( angle < 0 ) angle += 360;
}
return angle;
}
//============================================================================
void ReadKT15(double *irrad, double *irtemp)
{
char e[10], chrin;
byte i, count;
double ddum;
Serial3.setTimeout(100);
// READ IN RAD
while (Serial3.available()) {
Serial3.read();
}
Serial3.println("RAD");
i = Serial3.readBytesUntil('\n', e, 7);
e[i] = '\0';
*irrad = atof(e);
// READ IN RAD
while (Serial3.available()) {
Serial3.read();
}
Serial3.println("TEMP");
i = Serial3.readBytesUntil('\n', e, 7);
e[i] = '\0';
*irtemp = atof(e);
return;
}
//============================================================================
void ReadTilt(double *pitch, double *roll)
{
unsigned long microstart; // define input wait time
char e[4], chrin;
byte i, count;
double ddum;
Serial2.setTimeout(100);
// Clear buffer
// while( Serial2.available() ) Serial2.read();
// READ IN PITCH, TRY SEVERAL TIMES
// count=0;
// Serial.print("pitch ");
// while( count < 3 ) {
// count++;
Serial2.write(66);
delay(10); //v6
Serial2.readBytesUntil('\n', e, 4);
e[3] = '\0';
// Serial.print(e[0],DEC);Serial.print(" ");
// Serial.print(e[1],DEC);Serial.print(" ");
// Serial.println(e[2],DEC);
// }
ddum = (double) Hex2Dec(e);
if (ddum != MISSING && ddum >= 0 && ddum <= 4097) {
ddum -= 2048;
if (ddum < -1660) ddum = -1660;
if (ddum > 1660) ddum = 1660;
*pitch = P1 * (C1 * ddum + C2 * ddum * ddum + C3 * ddum * ddum * ddum) + P0;
}
else *pitch = MISSING;
// Serial.print("Pitch = "); Serial.println(*pitch,1);
// READ IN ROLL, TRY SEVERAL TIMES
// Clear buffer
// while( Serial2.available() ) Serial2.read();
// count=0;
// Serial.print("roll ");
// while( count < 3 ) {
// count++;
Serial2.write(67);
delay(10); //v6
Serial2.readBytesUntil('\n', e, 4);
e[3] = '\0';
// Serial.print(e[0],DEC);Serial.print(" ");
// Serial.print(e[1],DEC);Serial.print(" ");
// Serial.println(e[2],DEC);
// }
ddum = (double) Hex2Dec(e);
if (ddum != MISSING && ddum >= 0 && ddum <= 4097) {
ddum -= 2048;
if (ddum < -1660) ddum = -1660;
if (ddum > 1660) ddum = 1660;
*roll = R1 * (C1 * ddum + C2 * ddum * ddum + C3 * ddum * ddum * ddum) + R0;
}
else *roll = MISSING;
// Serial.print("Roll = "); Serial.println(*roll,1);
return;
}
//==================================================================
unsigned Ref(int K) {
if (K == ON) {
digitalWrite(REFSW, LOW);
digitalWrite(LED32, HIGH);
return OK;
}
else if (K == OFF) {
digitalWrite(REFSW, HIGH);
digitalWrite(LED32, LOW);
return OK;
}
return NOTOK;
}
//==================================================================
int ScanMotor(int direction)
/***************
* Operate the scan motor in a CCW, CW, or STOP mode.
* Output= ScanMotorFlag;
* defines: CCW, CW, STOP
* global variables: ScanMotorFlag;
*
* History
* 08-01-2000 M R Reynolds
* 2013-11-26 moved to Arduino
**********/
{
int flag;
switch (direction) {
case CCW:
digitalWrite(LED11, HIGH);
digitalWrite(D1a, LOW);
digitalWrite(D1b, HIGH);
flag = CCW;
break;
case CW:
digitalWrite(LED11, HIGH);
digitalWrite(D1a, HIGH);
digitalWrite(D1b, LOW);
flag = CW;
break;
case STOP:
digitalWrite(LED11, LOW);
digitalWrite(D1a, LOW);
digitalWrite(D1b, LOW);
flag = STOP;
break;
}
//ScanMotorFlag = flag;
return flag;
}
//==================================================================
int ShutterMotor(int direction)
/***************
* Operate the shutter motor in a CCW, CW, or STOP mode.
* Output= flag;
* defines: CCW, CW, STOP
* global variables: ShutterMotorFlag;
*
* History
* From ScanMotor()
* 2013-11-26 moved to Arduino
**********/
{
int flag;
switch (direction) {
case CCW:
digitalWrite(LED12, LOW);
digitalWrite(D2a, LOW);
digitalWrite(D2b, HIGH);
flag = CCW;
break;
case CW: // close
digitalWrite(LED12, HIGH);
digitalWrite(D2a, HIGH);
digitalWrite(D2b, LOW);
flag = CW;
break;
case STOP:
digitalWrite(D2a, LOW);
digitalWrite(D2b, LOW);
flag = STOP;
break;
}
//ShutterMotorFlag = flag;
return flag;
}
//==============================================================================
void ShutterOpen(void) {
unsigned long t0;
double fdum;
// DISABLED?
if ( ee.ShutterFlag > 0 ) { //v25
// CHECK SHUTTER POSITION
if (digitalRead(DHe1) == 0 && digitalRead(DHe2) == 1) {
ShutterState = OPEN;
return;
}
// STOPWATCH
t0 = millis();
// START MOTOR CCW=open CW=CLOSE
ShutterMotor(CCW);
// STOP MOTOR keystroke || current || timeout || HEswitch
while ( !Serial.available() ) {
delay(100);
// CURRENT
fdum = abs(GetMotorCurrent()); // absolute value
//Serial.println(fdum,2); // test
if (fdum >= CCWSHUTTERCURRENTTHRESHOLD && (unsigned)(millis() - t0) > 100) {
Serial.println("SHUTTER OPEN, CCW CURRENT");
ShutterMotor(STOP);
break;
}
// TIMEOUT
if ( (unsigned)(millis() - t0) > CCWSHUTTERTIMEOUT ) {
Serial.println("SHUTTER OPEN, CCW TIMEOUT");
ShutterMotor(STOP);
break;
}
// HE SWITCH
if ( digitalRead(DHe1) == 0 ) {
Serial.println("SHUTTER OPEN, HE1");
delay(CCWSTOPMILLISECS);
ShutterMotor(STOP);
break;
}
}
Serial.print((millis() - t0));
Serial.println(" msecs");
ShutterMotor(STOP);
ShutterState = OPEN;
digitalWrite(LED12, LOW);
}
return;
}
//==============================================================================
void ShutterClose(void) {
unsigned long t0;
double fdum;
// DISABLED?
if ( ee.ShutterFlag > 0 ) {
// CHECK DOOR POSITION
if (digitalRead(DHe1) == 1 && digitalRead(DHe2) == 0) {
//Serial.println("SHUTTER CLOSED");
ShutterState = CLOSED;
}
// CLOSE THE DOOR
else {
// STOPWATCH
t0 = millis();
// START MOTOR CCW=open CW=CLOSE
ShutterMotor(CW);
// STOP MOTOR keystroke || current || timeout || HEswitch
while ( !Serial.available() ) {
delay(100);
// CURRENT
fdum = abs(GetMotorCurrent() && (unsigned)(millis() - t0) > 100); // absolute value
//Serial.println(fdum,2);
if (fdum >= CWSHUTTERCURRENTTHRESHOLD) {
Serial.println("SHUTTER CLOSED, CW CURRENT");
ShutterMotor(STOP);
break;
}
// TIMEOUT
if ( (unsigned)(millis() - t0) > CWSHUTTERTIMEOUT ) {
Serial.println("SHUTTER CLOSED, CW TIMEOUT");
ShutterMotor(STOP);
break;
}
// HE SWITCH
if ( digitalRead(DHe2) == 0 ) {
Serial.println("SHUTTER CLOSED, HE2");
delay(CWSTOPMILLISECS);
ShutterMotor(STOP);
break;
}
}
Serial.print((millis() - t0));
Serial.println(" msecs");
ShutterMotor(STOP);
ShutterState = CLOSED;
digitalWrite(LED12, HIGH);
}
}
return;
}
//============================================================================
int sign (float input) {
return ((input < 0.0) ? NEG : POS);
}
//===========================================================================
double SteinhartHart(double beta[], double r)
//input
// beta is the 3x1 calibration vector where temp is computed by
// xt = beta(1) + beta(2)*xr + beta(3)*xr^3
// where
// xr = log(1/R)
// T = 1/xt - 273.15
// r = measured resistance, ohms
//
//output
// t = calibrated temperature vector, degC
{
double vx, t2, t;
vx = log(r);
//Serial.print("r="); Serial.print(r,3);
//Serial.print(" vx="); Serial.print(vx,3);
//Serial.print(" beta="); Serial.print(beta
//fitted curve
t2 = beta[0] + beta[1] * vx + beta[2] * vx * vx * vx;
t = 1 / t2 - (double)273.15;
return t;
}
//*************************************************************/
double ComputeSSST(double t1, double t2, double k1, double k2, double ksky, double ksea,
double esea, double ebb, double Acorr, double Offset, double missing, byte CalFlag)
// where
// t1 = black body 1, ambient, temperature, degC
// t2 = heated BB temp, degC
// k1, k2, ksky, ksea = kt15 readings for the different pointing angles, adc counts or mV
// esea = ocean emissivity from viewing angle.
// ebb = estimated emissivity of the black bodies, usually set to 1.
// Acorr = calibration parameter, multiplier of the interpolation slope. Typ = 1 +/- 0.01
// Offset = final sst adjustment, deg C. Typ +/-0.1.
// missing = value for bad data, usually = -999
// example
// 150211 rmr -- moved to perl module Isar.pm
{
double s1, s2, sk, s1v, s2v, Ad, sd, sdv, Au, suv;
double s_reflected, s_skin, ssst, ssst_uncorrected;
if ( t1 != missing && t2 != missing && t1 > 0 && (t2 - t1) > 5 &&
ksky != missing && ksea != missing && k1 != missing && k2 != missing &&
k2 > 0 && k1 > 0 && k2 > k1 ) {
//Serial.print("SSST computed emis = ");Serial.println(esea,6);
s1 = GetRadFromTemp(t1);
s2 = GetRadFromTemp(t2);
sk = s1; // approximation of planck radiance from the kt15 lens
//Serial.print("s1 = ");Serial.println(s1,6);
//Serial.print("s2 = ");Serial.println(s2,6);
// VIEW IRRADIANCES DEPEND ON THE EMISSIVITIES OF THE BB'S AND SOURCE
s1v = ebb * s1 - (1 - ebb) * sk;
s2v = ebb * s2 - (1 - ebb) * sk;
//Serial.print("s1v = ");Serial.println(s1v,6);
//Serial.print("s2v = ");Serial.println(s2v,6);
// ---DOWN VIEW RADIANCE---
Ad = (ksea - k1) / (k2 - k1);
//Serial.print("Ad = ");Serial.println(Ad,6);
// Correct for the irt beam spread
Ad = Acorr * Ad;
//Serial.print("Ad corrected = ");Serial.println(Ad,6);
// down view radiance
sdv = s1v + (s2v - s1v) * Ad;
//Serial.print("sdv = ");Serial.println(sdv,6);
// up view radiance
Au = Acorr * (ksky - k1) / (k2 - k1);
//Serial.print("Au corrected = ");Serial.println(Au,6);
// up view radiance
suv = s1v + (s2v - s1v) * Au;
//Serial.print("suv = ");Serial.println(suv,6);
// reflected sky radiance
s_reflected = suv * (1 - esea);
//Serial.print("s_reflected = ");Serial.println(s_reflected,6);
// planck radiance from the skin
s_skin = (sdv - s_reflected) / esea;
//Serial.print("s_skin = ");Serial.println(s_skin,6);
// uncorrected ssst, ignore reflection
if (CalFlag == 1) esea = 1;
ssst_uncorrected = GetTempFromRad(sdv / esea) + Offset;
//Serial.print("ssst_uncorrected = ");Serial.println(ssst_uncorrected,3);
// corrected skin temperature
ssst = GetTempFromRad(s_skin) + Offset;
//Serial.print("ssst = ");Serial.println(ssst,3);
}
else {
ssst_uncorrected = ssst = missing;
}
if (CalFlag == 1) return ssst_uncorrected;
else return ssst;
}
/*****************************************************************************************/
double GetRadFromTemp (double t) {
double x;
x = ee.pt2b[0] * t * t * t + ee.pt2b[1] * t * t + ee.pt2b[2] * t + ee.pt2b[3];
return x;
}
/*****************************************************************************************/
double GetTempFromRad (double r) {
double x;
x = ee.pb2t[0] * r * r * r + ee.pb2t[1] * r * r + ee.pb2t[2] * r + ee.pb2t[3];
return x;
}
/***************************************************************************************/
unsigned long ElapsedTime (char *ddhhmmss) {
unsigned long Ld, Lh, Lm, Ls, ms;
char ch[3];
ddhhmmss[0] = '\0';
// Elapsed time, days, since startup
ms = millis() - msstart;
//days
Ld = ms / 86400000; // number of days
if (Ld >= 0 && Ld < 100) {
ch[2] = '\0'; ch[1] = Ld % 10 + 48; ch[0] = Ld / 10 + 48;
} else {
strcpy(ch, "xx");
}
strcat(ddhhmmss, ch);
strcat(ddhhmmss, ".");
// Serial.print("days = "); Serial.print(Ld);
// Serial.print(" string:"); Serial.print(ch);
// Serial.print(" ddhhmmss:"); Serial.println(ddhhmmss);
//hours
Lh = (ms - Ld * 86400000) / 3600000; // number hours
if (Lh >= 0 && Lh < 100) {
ch[2] = '\0'; ch[1] = Lh % 10 + 48; ch[0] = Lh / 10 + 48;
} else {
strcpy(ch, "xx");
}
strcat(ddhhmmss, ch);
// Serial.print("hours = "); Serial.print(Lh);
// Serial.print(" string = "); Serial.print(ch);
// Serial.print(" ddhhmmss:"); Serial.println(ddhhmmss);
//min
Lm = (ms - Ld * 86400000 - Lh * 3600000) / 60000;
if (Lm >= 0 && Lm < 100) {
ch[2] = '\0'; ch[1] = Lm % 10 + 48; ch[0] = Lm / 10 + 48;
} else {
strcpy(ch, "xx");
}
strcat(ddhhmmss, ch);
// Serial.print("mins = "); Serial.print(Lm);
// Serial.print(" string = "); Serial.print(ch);
// Serial.print(" ddhhmmss:"); Serial.println(ddhhmmss);
//sec
Ls = (ms - Ld * 86400000 - Lh * 3600000 - Lm * 60000) / 1000;
if (Ls >= 0 && Ls < 100) {
ch[2] = '\0'; ch[1] = Ls % 10 + 48; ch[0] = Ls / 10 + 48;
} else {
strcpy(ch, "xx");
}
strcat(ddhhmmss, ch);
// Serial.print("secs = "); Serial.print(Ls);
// Serial.print(" string = "); Serial.print(ch);
// Serial.print(" ddhhmmss:"); Serial.println(ddhhmmss);
return ms;
}
| [
"michael@rmrco.com"
] | michael@rmrco.com |
b2302eb9bb516b64e7cc4cff32ccf8307de629c0 | 5e853451b0f09f79390230c98dc5a06f2d7c26b5 | /kinect-Release1.0-28-1/src/kinect_gl.h | 53c934b281a93dcfbada253bdefd1d6980041fce | [] | no_license | manavkataria/mindspace | 34633a295cbcab95411f5bbde4936000dd61e44b | 40f844f9d46578e71b6e6921b1fb75310dbd8fb0 | refs/heads/master | 2021-01-10T07:49:56.198374 | 2015-10-30T07:38:16 | 2015-10-30T07:38:16 | 45,234,652 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 544 | h | /*
Kinect CLNUI Sample Code
Alex Olwal, Jan 2011 (olwal@mit.edu)
*/
#pragma once
#include "kinect.h"
#include "kinect_texture_gl.h"
#include <cv.h>
#include <highgui.h>
#include <cxcore.h>
#include <GL/glut.h>
#include <BlobResult.h>
#include <math.h>
class KinectGL : public Kinect
{
public:
static const int WIDTH;
static const int HEIGHT;
//RGB: KinectTextureGL * rgb;
KinectTextureGL * z;
void update();
//RGB: void renderRGB();
void renderZ();
bool start();
KinectGL();
~KinectGL();
}; | [
"manav@letslinc.com"
] | manav@letslinc.com |
a7203e6f98fc8313555255b7800379f3a23a3589 | d20cf7de868dfb2c53578a70d0dda21306167d72 | /data/raw/train/student_4/1225/PoleVaulting_Zombie.cpp | 2eb4c3f330bde317ef56c013d2471824c17982cd | [] | no_license | bulacu-magda/Alemia | 905a84ca79157fb657eb424e337b0303fd3323bd | 0fd019c4517064d300399feb94dbcb0f467e8d48 | refs/heads/main | 2023-03-01T17:41:08.788500 | 2021-02-05T08:00:35 | 2021-02-05T08:00:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | cpp | #include "PoleVaulting_Zombie.h"
PoleVaulting_Zombie::PoleVaulting_Zombie(int x, int y) : Zombie(x, y)
{
}
void PoleVaulting_Zombie::print(int x, int y)
{
conOut(x, y) << "PoleVaulting";
conOut(x+1, y) << "Zombie ";
}
PoleVaulting_Zombie::~PoleVaulting_Zombie()
{
}
| [
"ionutm.bajan@yahoo.com"
] | ionutm.bajan@yahoo.com |
2f405947b3ebe49dfa2445f5d227b0c762699137 | a32cd478d2a6f2b261d32d39e1d384faf42c359a | /libs/ofxHTTP/src/PostRouteHandler.cpp | 1c055308843646c7460c9850f83189f08217969e | [] | no_license | laserpilot/ofxHTTP | d588cfa671ceb2c896c0733afceaa33d1f18a4c3 | 38e8ff083872562a774e8b749a1c3b903c62d3b1 | refs/heads/master | 2020-12-30T23:22:27.303497 | 2014-09-12T21:14:25 | 2014-09-12T21:14:25 | 14,499,730 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,822 | cpp | // =============================================================================
//
// Copyright (c) 2013 Christopher Baker <http://christopherbaker.net>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// =============================================================================
#include "ofx/HTTP/PostRouteHandler.h"
#include "ofx/HTTP/PostRoute.h"
#include "ofx/HTTP/Utils.h"
#include "Poco/UUID.h"
#include "Poco/UUIDGenerator.h"
namespace ofx {
namespace HTTP {
const Poco::Net::MediaType PostRouteHandler::POST_CONTENT_TYPE_TEXT_PLAIN = Poco::Net::MediaType("text/plain");
const Poco::Net::MediaType PostRouteHandler::POST_CONTENT_TYPE_MULTIPART = Poco::Net::MediaType("multipart/form-data");
const Poco::Net::MediaType PostRouteHandler::POST_CONTENT_TYPE_URLENCODED = Poco::Net::MediaType("application/x-www-form-urlencoded");
const Poco::Net::MediaType PostRouteHandler::POST_CONTENT_TYPE_JSON = Poco::Net::MediaType("application/json");
PostRouteHandler::PostRouteHandler(PostRoute& parent):
_parent(parent)
{
}
PostRouteHandler::~PostRouteHandler()
{
}
void PostRouteHandler::handleRequest(Poco::Net::HTTPServerRequest& request,
Poco::Net::HTTPServerResponse& response)
{
Poco::UUID sessionId = _parent.getSessionId(request, response);
// this uuid helps us track form progress updates
Poco::UUID formUUID = Poco::UUIDGenerator::defaultGenerator().createOne();
// get the content type header (already checked in parent route)
Poco::Net::MediaType contentType(request.get("Content-Type", ""));
if (contentType.matches(POST_CONTENT_TYPE_URLENCODED) ||
contentType.matches(POST_CONTENT_TYPE_MULTIPART))
{
// prepare the upload directory if needed
if (contentType.matches(POST_CONTENT_TYPE_MULTIPART))
{
ofDirectory _uploadFolder(_parent.getSettings().getUploadFolder());
if(!_uploadFolder.exists())
{
ofLogError("ServerUploadRouteHandler::handleRequest") << "Upload folder does not exist and cannot be created.";
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
_parent.handleRequest(request,response);
return;
}
}
PostRouteFileHandler postRoutePartHandler(sessionId, request, _parent, formUUID);
Poco::Net::HTMLForm form(contentType.toString());
form.setFieldLimit(_parent.getSettings().getFieldLimit());
form.load(request, request.stream(), postRoutePartHandler);
PostFormEventArgs args(sessionId,
request,
response,
formUUID,
form);
ofNotifyEvent(_parent.events.onHTTPFormEvent, args, &_parent);
}
else
{
// Poco::Net::HTMLForm, like php does not handle text/plain because
// it cannot be unambiguously encoded. Here we simply return
// the raw text with the event.
std::string result;
Poco::StreamCopier::copyToString(request.stream(), result);
ofBuffer buffer(result);
PostEventArgs args(sessionId, request, response, formUUID, buffer);
ofNotifyEvent(_parent.events.onHTTPPostEvent, args, &_parent);
}
if (response.sent())
{
return;
}
else if(!_parent.getSettings().getUploadRedirect().empty())
{
response.redirect(_parent.getSettings().getUploadRedirect());
return;
}
else
{
// done
response.setStatusAndReason(Poco::Net::HTTPResponse::HTTP_OK);
response.setContentLength(0);
response.send();
return;
}
}
} } // namespace ofx::HTTP
| [
"me@christopherbaker.net"
] | me@christopherbaker.net |
04006a85b819d85059839ad9a6613727fcf6fa7a | 1e6a93dc6786797202006d7e8080c73ddd78df23 | /MainWindow/sortdialog.h | 470d9da737c6b8652f01c8dd8c366f6444fa59fb | [] | no_license | liangjingli/Qt4 | 7569a61b1d51c3891d368668bd2c02405ae272a3 | 6ef1ae300da65ea9e2864955cee2a7b75f44e81b | refs/heads/master | 2021-08-19T14:02:02.828008 | 2017-11-26T14:22:18 | 2017-11-26T14:22:18 | 110,934,682 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 255 | h | #ifndef SORTDIALOG_H
#define SORTDIALOG_H
#include <QDialog>
#include "ui_sortdialog.h"
class SortDialog :public QDialog, public Ui::SortDialog
{
Q_OBJECT
public:
SortDialog(QWidget *parent=0);
void setColumnRange(QChar first, QChar last);
};
#endif | [
"jingli_liang@163.com"
] | jingli_liang@163.com |
c1d8a57c5387e1ab340c2561e70b9d1ab697d261 | e273bc30bdc88c91233685b1f966c097e229e0f2 | /CH-HCNetSDK_V5.0.3.4_build20150114(for Linux32)/QtDemo/Linux32/build-QtClientDemo-桌面-Release/obj/Gui/ui_crtspparams.h | 1c5570843591d807b7f8f11f3c8d3aa4f542216f | [] | no_license | goodfuture/Ubuntu_Documents | 086ba8a9782d4123d8b028bd017edcd903d2c7db | 7db056daad3c38109965e4793ef4df567ed8869f | refs/heads/master | 2020-05-31T22:19:25.633043 | 2015-05-25T02:39:44 | 2015-05-25T02:39:44 | 94,051,970 | 1 | 0 | null | 2017-06-12T03:31:02 | 2017-06-12T03:31:02 | null | UTF-8 | C++ | false | false | 3,397 | h | /********************************************************************************
** Form generated from reading UI file 'crtspparams.ui'
**
** Created by: Qt User Interface Compiler version 4.8.6
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_CRTSPPARAMS_H
#define UI_CRTSPPARAMS_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QDialog>
#include <QtGui/QGridLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QPushButton>
#include <QtGui/QWidget>
QT_BEGIN_NAMESPACE
class Ui_CRtspParamsClass
{
public:
QPushButton *btnRefresh;
QPushButton *btnSave;
QPushButton *btnExit;
QWidget *layoutWidget;
QGridLayout *gridLayout;
QLabel *label;
QLineEdit *editPort;
void setupUi(QDialog *CRtspParamsClass)
{
if (CRtspParamsClass->objectName().isEmpty())
CRtspParamsClass->setObjectName(QString::fromUtf8("CRtspParamsClass"));
CRtspParamsClass->resize(319, 181);
btnRefresh = new QPushButton(CRtspParamsClass);
btnRefresh->setObjectName(QString::fromUtf8("btnRefresh"));
btnRefresh->setGeometry(QRect(10, 120, 75, 23));
btnSave = new QPushButton(CRtspParamsClass);
btnSave->setObjectName(QString::fromUtf8("btnSave"));
btnSave->setGeometry(QRect(150, 120, 75, 23));
btnExit = new QPushButton(CRtspParamsClass);
btnExit->setObjectName(QString::fromUtf8("btnExit"));
btnExit->setGeometry(QRect(240, 120, 75, 23));
layoutWidget = new QWidget(CRtspParamsClass);
layoutWidget->setObjectName(QString::fromUtf8("layoutWidget"));
layoutWidget->setGeometry(QRect(50, 50, 231, 23));
gridLayout = new QGridLayout(layoutWidget);
gridLayout->setSpacing(6);
gridLayout->setContentsMargins(11, 11, 11, 11);
gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
gridLayout->setContentsMargins(0, 0, 0, 0);
label = new QLabel(layoutWidget);
label->setObjectName(QString::fromUtf8("label"));
gridLayout->addWidget(label, 0, 0, 1, 1);
editPort = new QLineEdit(layoutWidget);
editPort->setObjectName(QString::fromUtf8("editPort"));
gridLayout->addWidget(editPort, 0, 1, 1, 1);
retranslateUi(CRtspParamsClass);
QMetaObject::connectSlotsByName(CRtspParamsClass);
} // setupUi
void retranslateUi(QDialog *CRtspParamsClass)
{
CRtspParamsClass->setWindowTitle(QApplication::translate("CRtspParamsClass", "CRtspParams", 0, QApplication::UnicodeUTF8));
btnRefresh->setText(QApplication::translate("CRtspParamsClass", "Update", 0, QApplication::UnicodeUTF8));
btnSave->setText(QApplication::translate("CRtspParamsClass", "Confirm", 0, QApplication::UnicodeUTF8));
btnExit->setText(QApplication::translate("CRtspParamsClass", "Cancel", 0, QApplication::UnicodeUTF8));
label->setText(QApplication::translate("CRtspParamsClass", "RTSP port", 0, QApplication::UnicodeUTF8));
} // retranslateUi
};
namespace Ui {
class CRtspParamsClass: public Ui_CRtspParamsClass {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_CRTSPPARAMS_H
| [
"wangboshine@126.com"
] | wangboshine@126.com |
733a550f57afd4aa6b61bd5d37f3c88412ba93f3 | 27bb5ed9eb1011c581cdb76d96979a7a9acd63ba | /aws-cpp-sdk-dynamodb/include/aws/dynamodb/model/DescribeLimitsRequest.h | b425dce552252d0c9c07b1198c21d1b32de1e02b | [
"Apache-2.0",
"JSON",
"MIT"
] | permissive | exoscale/aws-sdk-cpp | 5394055f0876a0dafe3c49bf8e804d3ddf3ccc54 | 0876431920136cf638e1748d504d604c909bb596 | refs/heads/master | 2023-08-25T11:55:20.271984 | 2017-05-05T17:32:25 | 2017-05-05T17:32:25 | 90,744,509 | 0 | 0 | null | 2017-05-09T12:43:30 | 2017-05-09T12:43:30 | null | UTF-8 | C++ | false | false | 1,308 | h | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/dynamodb/DynamoDB_EXPORTS.h>
#include <aws/dynamodb/DynamoDBRequest.h>
namespace Aws
{
namespace DynamoDB
{
namespace Model
{
/**
* <p>Represents the input of a <code>DescribeLimits</code> operation. Has no
* content.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/DescribeLimitsInput">AWS
* API Reference</a></p>
*/
class AWS_DYNAMODB_API DescribeLimitsRequest : public DynamoDBRequest
{
public:
DescribeLimitsRequest();
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
};
} // namespace Model
} // namespace DynamoDB
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
0caa9e1141ba2747ce3bf41270c3ad132e2e8e9f | 1517127cccf448ee11d84bd83c807976b00cf5d2 | /libraries/SensorXtr/utility/AqualaboModbusSensors.cpp | 3a35e645beb0efe28835eb04a9e9ec2d2c1107c8 | [] | no_license | KubaFYI/waspmoteapi | 44d4838b1a284e63e17f28f06a8a4773cbd2166a | e38a1e1409f5520ebbcffb811e3c16f278cbe7cc | refs/heads/master | 2020-08-01T06:39:21.995357 | 2019-09-16T12:13:40 | 2019-09-16T12:13:40 | 210,902,279 | 0 | 0 | null | 2019-09-25T17:27:02 | 2019-09-25T17:27:01 | null | UTF-8 | C++ | false | false | 41,954 | cpp | /*! \file AqualaboModbusSensors.cpp
\brief Library for managing the modbus sensors in Smart Water Xtreme.
This library is not compatible con Smart water version.
Copyright (C) 2018 Libelium Comunicaciones Distribuidas S.L.
http://www.libelium.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 2.1 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Version: 3.0
Design: David Gascón
Implementation: Victor Boria
*/
/***********************************************************************
* Includes
***********************************************************************/
#ifndef __WPROGRAM_H__
#include <WaspClasses.h>
#endif
#include "AqualaboModbusSensors.h"
/***********************************************************************
* Class contructors
***********************************************************************/
aqualaboModbusSensorsClass::aqualaboModbusSensorsClass()
{
waitingTime = DEFAULT_WAITING_TIME;
sensorAddr = DEFAULT_ADDRESS;
temporaryCoefficientListBuffer = 0;
}
/***********************************************************************
* Methods of the Class
***********************************************************************/
//!*************************************************************
//! Name: initCommunication()
//! Description: Initializes the communication channel
//! Param : void
//! Returns: void
//!*************************************************************
void aqualaboModbusSensorsClass::initCommunication()
{
sensor = ModbusMaster(RS232_COM, sensorAddr);
// The sensor uses 9600 bps speed communication
sensor.begin(9600, 1);
// set Auxiliar2 socket
Utils.setMuxAux2();
clearBuffer();
}
//!*************************************************************
//! Name: searchAddress()
//! Description: check if slave address is correct
//! Param : void
//! Returns: uint8_t "0" if no error, "1" if error
//!*************************************************************
uint8_t aqualaboModbusSensorsClass::searchAddress(uint8_t _sensorAddr)
{
sensorAddr = _sensorAddr;
initCommunication();
uint8_t status = 0xFF;
uint8_t retries = 0;
while ((status !=0) && (retries < 3))
{
//Read 1 register: POD description
status = sensor.readHoldingRegisters(0x0D00, 16);
delay(10);
retries++;
}
if (status == 0)
{
uint8_t sensorAddress = sensor.getResponseBuffer(0);
char podDescription[33];
memset(podDescription, 0x00, sizeof(podDescription));
uint8_t j = 0;
for (int i=0; i<16; i++)
{
podDescription[j++] = sensor.getResponseBuffer(i) >>8 & 0xFF;
podDescription[j++] = sensor.getResponseBuffer(i) & 0xFF;
}
#if DEBUG_XTR_MODBUS > 1
PRINT_XTR_MODBUS(F("POD description:"));
USB.println(podDescription);
#endif
uint8_t desiredDefaultAddress = 0;
//Compare the POD description returned by the sensor
//"ODO / Temperature PONSEL "
if(strncmp(podDescription, "ODO / Te" , 8) == 0)
{
USB.println("OPTOD sensor found");
desiredDefaultAddress = 10;
}
//"pH / Redox / Temperature PONSEL "
if(strncmp(podDescription, "pH / Red" , 8) == 0)
{
USB.println("PHEHT sensor found");
desiredDefaultAddress = 20;
}
//"C4E /Salinite/Temp PONSEL "
if(strncmp(podDescription, "C4E /Sal" , 8) == 0)
{
USB.println("C4E sensor found");
desiredDefaultAddress = 30;
}
//"Nephelo/TU / Temperature PONSEL "
if(strncmp(podDescription, "Nephelo/" , 8) == 0)
{
USB.println("NTU sensor found");
desiredDefaultAddress = 40;
}
//"CTZ/Salinity/Temp PONSEL "
if(strncmp(podDescription, "CTZ/Sali" , 8) == 0)
{
USB.println("CTZN sensor found");
desiredDefaultAddress = 50;
}
//"TU/MES/VB 5 PONSEL "
if(strncmp(podDescription, "TU/MES/V" , 8) == 0)
{
USB.println("MES5 sensor found");
desiredDefaultAddress = 60;
}
if(desiredDefaultAddress != 0)
{
#if DEBUG_XTR_MODBUS > 1
//Change MODBUS slave address to default
USB.print("Changing MODBUS slave address to ");
USB.println(desiredDefaultAddress, DEC);
#endif
if (changeAddress(desiredDefaultAddress) == 0)
{
#if DEBUG_XTR_MODBUS > 1
USB.println(F("Sensor MODBUS slave address changed to default"));
#endif
}
else
{
#if DEBUG_XTR_MODBUS > 0
USB.println(F("Error changing sensor MODBUS slave address to default"));
#endif
}
return 0;
}
else
{
//if fails return 1
return 1;
}
}
else
{
// If no response from the slave, print an error message.
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Communication error reading address"));
#endif
//if fails return 1
return 1;
}
return 0;
}
//!*************************************************************
//! Name: changeAddress(uint8_t _sensorAddress)
//! Description: Change the sensor slave address
//! Param : _sensorAddress
//! Returns: uint8_t "0" if no error, "1" if error
//!*************************************************************
uint8_t aqualaboModbusSensorsClass::changeAddress(uint8_t _sensorAddr)
{
initCommunication();
uint8_t status = 0xFF;
uint8_t retries = 0;
if (_sensorAddr > 247) _sensorAddr = 247;
while ((status !=0) && (retries < 5))
{
status = sensor.writeSingleRegister(0x00A3, _sensorAddr);
delay(100);
retries++;
}
// Check that the address has been well written
if (status == 0)
{
#if DEBUG_XTR_MODBUS > 1
PRINT_XTR_MODBUS(F("Sensor address configured with value: "));
USB.println(_sensorAddr, DEC);
#endif
sensorAddr = _sensorAddr;
return 0;
}
else
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Communication Error. Sensor address not configured."));
#endif
return 1;
}
}
//!*************************************************************
//! Name: initSensor()
//! Description: Setups the sensor configuration paramenters
//! Param : void
//! Returns: void
//!*************************************************************
uint8_t aqualaboModbusSensorsClass::initSensor()
{
initCommunication();
//Get the necessary waiting time to get measures after asking for them
if(readWaitingTime() != 0)
{
return 1;
}
//Our avg by default must be 1
uint8_t avg = 1;
//Configure average
if(writeAverage(avg) == 0)
{
if(readAverage() != avg)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error configuring average"));
#endif
return 1;
}
}
else
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Communication error writing average"));
#endif
//if fails return 1
return 1;
}
return 0;
}
//!*************************************************************
//! Name: initSensor()
//! Description: Setups the sensor configuration paramenters
//! Param : void
//! Returns: void
//!*************************************************************
uint8_t aqualaboModbusSensorsClass::initSensor(uint8_t range)
{
initCommunication();
//Get the necessary waiting time to get measures after asking for them
if(readWaitingTime() != 0)
{
return 1;
}
//Configure Parameter 1:
//In NTU sensor is Nephelometric Turbidity
//In C4E sensor is Conductivity
if(writeParamConfig(1, range) == 0)
{
if(readParamConfig(1)/256 != range)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error configuring param"));
#endif
return 1;
}
}
else
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Communication error writing param config"));
#endif
//if fails return 1
return 1;
}
//Our avg by default must be 1
uint8_t avg = 1;
//Configure average
if(writeAverage(avg) == 0)
{
if(readAverage() != avg)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error configuring average"));
#endif
return 1;
}
}
else
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Communication error writing average"));
#endif
//if fails return 1
return 1;
}
return 0;
}
//!*************************************************************
//! Name: initSensor()
//! Description: Setups the sensor configuration paramenters
//! Param : void
//! Returns: void
//!*************************************************************
uint8_t aqualaboModbusSensorsClass::initSensor(uint8_t range, uint8_t avg)
{
initCommunication();
//Get the necessary waiting time to get measures after asking for them
if(readWaitingTime() != 0)
{
return 1;
}
//Configure Parameter 1: Nephelo turbidity in NTU
//Configure Parameter 1: Conductivity in C4E
if(writeParamConfig(1, range) == 0)
{
if(readParamConfig(1)/256 != range)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error configuring param"));
#endif
return 1;
}
}
else
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Communication error writing param config"));
#endif
//if fails return 1
return 1;
}
//Configure average
if(writeAverage(avg) == 0)
{
if(readAverage() != avg)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error configuring average"));
#endif
return 1;
}
}
else
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Communication error writing average"));
#endif
//if fails return 1
return 1;
}
return 0;
}
//!*************************************************************
//! Name: readParamConfig(uint8_t paramNumber)
//! Description: Returns all the measures of the sensor
//! Param : paramNumber
//! Returns: 0 is OK, 1 if error
//!*************************************************************
uint8_t aqualaboModbusSensorsClass::writeParamConfig(uint8_t paramNumber, uint8_t range)
{
initCommunication();
uint8_t status = 0xFF;
uint8_t retries = 0;
uint16_t address;
switch(paramNumber)
{
case 1:
address = 0x00A6;
break;
case 2:
address = 0x00A7;
break;
case 3:
address = 0x00A8;
break;
case 4:
address = 0x00A9;
break;
default:
address = 0x00A6;
break;
}
//Range is set in byte 1 of the parameter, byte 0 is 0
uint16_t configRegister = range*256;
status = -1;
retries = 0;
while ((status !=0) && (retries < 5))
{
//Write 1 register (set previouly in TX buffer) in param address
status = sensor.writeSingleRegister(address, configRegister);
retries++;
delay(100);
}
if (status == 0)
{
#if DEBUG_XTR_MODBUS > 1
PRINT_XTR_MODBUS(F("Param "));
USB.print(paramNumber, DEC);
USB.print(F(" configured to range:"));
USB.println(range, DEC);
#endif
}
else
{
// If no response from the slave, print an error message.
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Communication error (Writing Multiple Registers)"));
#endif
return 1;
}
return 0;
}
//!*************************************************************
//! Name: readParamConfig(uint8_t paramNumber)
//! Description: Returns all the measures of the sensor
//! Param : paramNumber
//! Returns: paramConfig if OK, 0 if error
//!*************************************************************
uint16_t aqualaboModbusSensorsClass::readParamConfig(uint8_t paramNumber)
{
uint16_t address;
uint8_t status = 0xFF;
uint8_t retries = 0;
initCommunication();
switch(paramNumber)
{
case 1:
address = 0x00A6;
break;
case 2:
address = 0x00A7;
break;
case 3:
address = 0x00A8;
break;
case 4:
address = 0x00A9;
break;
default:
address = 0x00A6;
break;
}
while ((status !=0) && (retries < 10))
{
//Read 1 register
status = sensor.readHoldingRegisters(address, 1);
delay(100);
retries++;
}
uint16_t configRegister = 0;
if (status == 0)
{
configRegister = sensor.getResponseBuffer(0);
#if DEBUG_XTR_MODBUS > 1
PRINT_XTR_MODBUS(F("Param "));
USB.print(paramNumber, DEC);
USB.print(F(" read with range:"));
USB.println(configRegister/256, DEC);
#endif
return configRegister;
}
else
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error reading ParamConfig"));
#endif
return 0;
}
}
//!*************************************************************
//! Name: writeCalibrationStandard()
//! Description: Configure the acalibration standart
//! Param : address and value
//! Returns: uint8_t "0" if no error, "1" if error
//!*************************************************************
uint8_t aqualaboModbusSensorsClass::writeCalibrationStandard(uint16_t address, float value)
{
initCommunication();
uint8_t status = 0xFF;
uint8_t retries = 0;
foo.toFloat = value;
sensor.setTransmitBuffer(0, foo.ints[1]);
sensor.setTransmitBuffer(1, foo.ints[0]);
while ((status !=0) && (retries < 5))
{
status = sensor.writeMultipleRegisters(address, 2);
delay(100);
retries++;
}
// Check that the direction has been well written
if (status == 0)
{
#if DEBUG_XTR_MODBUS > 1
PRINT_XTR_MODBUS(F("Calibration standard with address 0x0"));
USB.print(address, HEX);
USB.print(F(" written with value:"));
USB.println(value);
#endif
return 0;
}
else
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error writing calibration standard"));
#endif
return 1;
}
}
//!*************************************************************
//! Name: readCalibrationStandard(uint8_t address)
//! Description: Returns the calibration standard in a particular address
//! Param : address
//! Returns: calibrationStandard if OK, -1 if error
//!*************************************************************
float aqualaboModbusSensorsClass::readCalibrationStandard(uint16_t address)
{
uint8_t status = 0xFF;
uint8_t retries = 0;
initCommunication();
while ((status !=0) && (retries < 10))
{
//Read 2 register -> 1 float (4 bytes)
status = sensor.readHoldingRegisters(address, 2);
delay(100);
retries++;
}
float calibrationStandard = 0;
if (status == 0)
{
foo.ints[0] = sensor.getResponseBuffer(1);
foo.ints[1] = sensor.getResponseBuffer(0);
calibrationStandard = foo.toFloat;
#if DEBUG_XTR_MODBUS > 1
PRINT_XTR_MODBUS(F("Calibration standard with address 0x0"));
USB.print(address, HEX);
USB.print(F(" read with value:"));
USB.println(calibrationStandard);
#endif
return calibrationStandard;
}
else
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error reading calibration standard"));
#endif
return -1;
}
}
//!*************************************************************
//! Name: restoreToFactoryCalibration()
//! Description: restores to factory calibration
//! Param : the use of value depends on the step
//! Returns: "0" if no error, "1" if error
//!*************************************************************
uint8_t aqualaboModbusSensorsClass::restoreToFactoryCalibration(uint8_t parameter)
{
initCommunication();
uint8_t status = 0xFF;
uint8_t retries = 0;
uint16_t transmit_buffer = 0;
switch (parameter)
{
case TEMPERATURE:
transmit_buffer = 0x0001;
break;
case PARAMETER_1:
transmit_buffer = 0x0002;
break;
case PARAMETER_2:
transmit_buffer = 0x0004;
break;
case PARAMETER_3:
transmit_buffer = 0x0008;
break;
case PARAMETER_4:
transmit_buffer = 0x0010;
break;
}
while ((status !=0) && (retries < 5))
{
status = sensor.writeSingleRegister(RESTORE_CALIB_REG, transmit_buffer);
delay(100);
retries++;
}
// Check that the direction has been well written
if (status == 0)
{
#if DEBUG_XTR_MODBUS > 1
PRINTLN_XTR_MODBUS(F("Restore to factory calibration successfully"));
#endif
return 0;
}
else
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error restoring to factory calibration"));
#endif
return 1;
}
}
//!*************************************************************
//! Name: calibrate()
//! Description: Calibrates several parameters
//! Param : the use of value depends on the step
//! Returns: "0" if no error, "1" if error
//!*************************************************************
uint8_t aqualaboModbusSensorsClass::calibrate(uint8_t sensor, uint8_t parameter, uint8_t step, float value)
{
// General calibration process for several parameters
switch (step)
{
//In step 1 we reset temporary calibration data and indicate the range if it exist
//Additionaly we change the averagin to 25 only during calibration process
case STEP_1:
switch (sensor)
{
case OPTOD:
switch (parameter)
{
case TEMPERATURE:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_TEMP_1;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_TEMP_2;
break;
case PARAMETER_1:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_1;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_4;
break;
}
break;
case PHEHT:
switch (parameter)
{
case TEMPERATURE:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_TEMP_1;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_TEMP_2;
break;
case PARAMETER_1:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_1;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_2;
break;
case PARAMETER_2:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_3;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_4;
break;
}
break;
case C4E:
switch (parameter)
{
case TEMPERATURE:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_TEMP_1;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_TEMP_2;
break;
case PARAMETER_1:
switch ((uint8_t)value)
{
case RANGE_1:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_1;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_2;
break;
case RANGE_2:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_3;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_4;
break;
case RANGE_3:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_5;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_6;
break;
case RANGE_4:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_7;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_8;
break;
}
break;
}
break;
case NTU:
switch (parameter)
{
case TEMPERATURE:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_TEMP_1;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_TEMP_2;
break;
case PARAMETER_1:
switch ((uint8_t)value)
{
case RANGE_1:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_1;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_2;
break;
case RANGE_2:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_3;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_4;
break;
case RANGE_3:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_5;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_6;
break;
case RANGE_4:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_7;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_8;
break;
}
break;
}
break;
case CTZN:
switch (parameter)
{
case TEMPERATURE:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_TEMP_1;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_TEMP_2;
break;
case PARAMETER_1:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_1;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_2;
break;
}
break;
case MES5:
switch (parameter)
{
case TEMPERATURE:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_TEMP_1;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_TEMP_2;
break;
case PARAMETER_1:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_3;
//address_slope = CALIB_STANDARD_2;
break;
case PARAMETER_3:
aqualaboModbusSensors.address_offset = CALIB_STANDARD_1;
aqualaboModbusSensors.address_slope = CALIB_STANDARD_2;
break;
}
break;
}
//[231] Reset all temporary calibration data
resetTemporaryCalibrationData(DONT_RETURN_AVG_TO_1);
//Read all calibration standard registers
//must be set to 0 after the reset
if((readCalibrationStandard(aqualaboModbusSensors.address_offset) != 0)
|| (readCalibrationStandard(aqualaboModbusSensors.address_slope) != 0))
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error reseting temporary calibration data"));
#endif
return 1;
}
else
{
//Configure average -> change to 25 like Calsens
if(writeAverage(25) == 0)
{
if(readAverage() != 25)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error configuring average to 25"));
#endif
return 1;
}
}
else
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Communication error configuring average to 25"));
#endif
//if fails return 1
return 1;
}
//PHEHT sensor in REDOX parameter requiere activate ELECTRONIC ZERO
if((sensor == PHEHT) && (parameter == REDOX))
{
//Write float 1.0 in 0x0208 address
if(writeCalibrationStandard(aqualaboModbusSensors.address_offset, (float)1.0) == 1)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error writing calibration standart for offset for 1st time (electronic zero)"));
#endif
return 1;
}
}
}
break;
//In step 2 user select calibration standard 1 (offset)
//This step must be done after stabilizing and measuring in water with
//the selected value using readMeasures function previosly
case STEP_2:
if((sensor == PHEHT) && (parameter == REDOX))
{
//Write float 2.0 in 0x0208 address
if(writeCalibrationStandard(aqualaboModbusSensors.address_offset, (float)2.0) == 1)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error writing calibration standart for offset for 2nd time (electronic zero)"));
#endif
return 1;
}
//[230] Then we update the list "temporary coefficient to be used for next measurement"
//First we read the state of the list
if(readTemporaryCoefficientList() == 1)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error reading Temporary Coefficient List"));
#endif
return 1;
}
//Then we update with the right bit in the list
if(writeTemporaryCoefficientList(aqualaboModbusSensors.address_offset) == 1)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error updating temporary coef list for offset"));
#endif
return 1;
}
//Write float 0.0 in 0x0208 address
if(writeCalibrationStandard(aqualaboModbusSensors.address_offset, (float)0.0) == 1)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error writing calibration standart for offset for 3rd time (electronic zero)"));
#endif
return 1;
}
}
else
{
//[170] It stores the calibration standart, calculates automatically the coefficient
//using the last measurement
if(writeCalibrationStandard(aqualaboModbusSensors.address_offset, value) == 1)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error writing calibration standart for offset"));
#endif
return 1;
}
//[230] Then we update the list "temporary coefficient to be used for next measurement"
//First we read the state of the list
if(readTemporaryCoefficientList() == 1)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error reading Temporary Coefficient List"));
#endif
return 1;
}
//Then we update with the right bit in the list
if(writeTemporaryCoefficientList(aqualaboModbusSensors.address_offset) == 1)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error updating temporary coef list for offset"));
#endif
return 1;
}
}
break;
//In step 3 user select calibration standard 2 (slope)
//This step must be done after stabilizing and measuring in water with
//the selected value
case STEP_3:
//[170] It stores the calibration standart, calculates automatically the coefficient
//using the last measurement
if(writeCalibrationStandard(aqualaboModbusSensors.address_slope, value) == 1)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error writing calibration standart for slope"));
#endif
return 1;
}
//[230] Then we update the list "temporary coefficient to be used for next measurement"
//First we read the state of the list
if(readTemporaryCoefficientList() == 1)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error reading Temporary Coefficient List"));
#endif
return 1;
}
//Then we update with the right bit in the list
if(writeTemporaryCoefficientList(aqualaboModbusSensors.address_slope) == 1)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error updating temporary coef list for slope"));
#endif
return 1;
}
break;
//Special case for pH calibration with 2 slopes (three point calibration)
//In step 3 user select calibration standard 2 (slope)
//This step must be done after stabilizing and measuring in water with
//the selected value
case STEP_3B:
aqualaboModbusSensors.address_slope = CALIB_STANDARD_5;
//[170] It stores the calibration standart, calculates automatically the coefficient
//using the last measurement
if(writeCalibrationStandard(aqualaboModbusSensors.address_slope, value) == 1)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error writing calibration standart for slope"));
#endif
return 1;
}
//[230] Then we update the list "temporary coefficient to be used for next measurement"
//First we read the state of the list
if(readTemporaryCoefficientList() == 1)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error reading Temporary Coefficient List"));
#endif
return 1;
}
//Then we update with the right bit in the list
if(writeTemporaryCoefficientList(aqualaboModbusSensors.address_slope) == 1)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error updating temporary coef list for slope"));
#endif
return 1;
}
break;
//In step 4 user validates the entire calibration entering operator's name and date
case STEP_4:
//[210]
uint8_t response_1 = writeCalibrationValidation((uint8_t)parameter);
delay(500);
//[231] Reset all temporary calibration data for finishing the validation and return averaging to 1
uint8_t response_2 = resetTemporaryCalibrationData(RETURN_AVG_TO_1);
//if error, return 1
if((response_1 == 1) || (response_2 == 1))
{
return 1;
}
break;
}
return 0;
}
//!*************************************************************
//! Name: validateCalibration()
//! Description: Validates the calibration entering name and date
//! Param : void
//! Returns: 0 if OK, 1 if error
//!*************************************************************
uint8_t aqualaboModbusSensorsClass::writeCalibrationValidation(uint8_t value)
{
initCommunication();
uint8_t status = 0xFF;
uint8_t retries = 0;
uint16_t validationAddress;
switch (value)
{
case TEMPERATURE:
validationAddress = 0x027E;
break;
case PARAMETER_1:
validationAddress = 0x028E;
break;
case PARAMETER_2:
validationAddress = 0x029E;
break;
case PARAMETER_3:
validationAddress = 0x02AE;
break;
}
//Prepare operator name in buffer
for(uint8_t i = 0; i < 8; i++)
{
foo2.uint8t[0] = calibrationOperatorsName[(i*2)+1];
foo2.uint8t[1] = calibrationOperatorsName[(i*2)];
sensor.setTransmitBuffer(i, foo2.uint16t);
}
//Now prepare calibration date in buffer
for(uint8_t j = 8; j < 16; j++)
{
foo2.uint8t[0] = calibrationDate[((j-8)*2)+1];
foo2.uint8t[1] = calibrationDate[((j-8)*2)];
sensor.setTransmitBuffer(j, foo2.uint16t);
}
while ((status !=0) && (retries < 5))
{
status = sensor.writeMultipleRegisters(validationAddress, 16);
delay(100);
retries++;
}
// Check that the operater name and date has been well written
if (status == 0)
{
#if DEBUG_XTR_MODBUS > 1
PRINTLN_XTR_MODBUS(F("Operator name and date written"));
#endif
}
else
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error writing operator name and date"));
#endif
return 1;
}
return 0;
}
//!*************************************************************
//! Name: readTemporaryCoefficientList()
//! Description: read Temporary Coefficient List
//! Param : void
//! Returns: 0 if OK, 1 if error
//!*************************************************************
uint8_t aqualaboModbusSensorsClass::readTemporaryCoefficientList()
{
initCommunication();
uint16_t average = 0;
uint8_t status = 0xFF;
uint8_t retries = 0;
while ((status !=0) && (retries < 10))
{
//Read 1 register
status = sensor.readHoldingRegisters(TEMP_COEF_LIST_REG, 2);
delay(100);
retries++;
}
if (status == 0)
{
//sensor.getResponseBuffer(0); must be always 0x00
temporaryCoefficientListBuffer = sensor.getResponseBuffer(1);
#if DEBUG_XTR_MODBUS > 1
PRINT_XTR_MODBUS(F("Temporary Coefficient List read: Ox"));
foo2.uint16t = temporaryCoefficientListBuffer;
USB.printHex(foo2.uint8t[1]);
USB.printHex(foo2.uint8t[0]);
USB.println();
#endif
return 0;
}
else
{
// If no response from the slave, print an error message.
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Communication error Temporary Coefficient List"));
#endif
//if fails return 1
return 1;
}
}
//!*************************************************************
//! Name: writeTemporaryCoefficientList()
//! Description: write temporary coefficient list
//! Param : coefficient
//! Returns: "0" if no error, "1" if error
//!*************************************************************
uint8_t aqualaboModbusSensorsClass::writeTemporaryCoefficientList(uint16_t coefficient)
{
initCommunication();
uint8_t status = 0xFF;
uint8_t retries = 0;
switch (coefficient)
{
case CALIB_STANDARD_TEMP_1:
bitSet(temporaryCoefficientListBuffer, 0);
break;
case CALIB_STANDARD_TEMP_2:
bitSet(temporaryCoefficientListBuffer, 1);
break;
case CALIB_STANDARD_1:
bitSet(temporaryCoefficientListBuffer, 2);
break;
case CALIB_STANDARD_2:
bitSet(temporaryCoefficientListBuffer, 3);
break;
case CALIB_STANDARD_3:
bitSet(temporaryCoefficientListBuffer, 4);
break;
case CALIB_STANDARD_4:
bitSet(temporaryCoefficientListBuffer, 5);
break;
case CALIB_STANDARD_5:
bitSet(temporaryCoefficientListBuffer, 6);
break;
case CALIB_STANDARD_6:
bitSet(temporaryCoefficientListBuffer, 7);
break;
case CALIB_STANDARD_7:
bitSet(temporaryCoefficientListBuffer, 8);
break;
case CALIB_STANDARD_8:
bitSet(temporaryCoefficientListBuffer, 9);
break;
case CALIB_STANDARD_9:
bitSet(temporaryCoefficientListBuffer, 10);
break;
case CALIB_STANDARD_10:
bitSet(temporaryCoefficientListBuffer, 11);
break;
}
sensor.setTransmitBuffer(0, 0x0000);
sensor.setTransmitBuffer(1, temporaryCoefficientListBuffer);
while ((status !=0) && (retries < 5))
{
status = sensor.writeMultipleRegisters(TEMP_COEF_LIST_REG, 2);
delay(100);
retries++;
}
// Check that the direction has been well written
if (status == 0)
{
#if DEBUG_XTR_MODBUS > 1
PRINT_XTR_MODBUS(F("Temporary Coefficient List written with value 0x0"));
foo2.uint16t = temporaryCoefficientListBuffer;
USB.printHexln(foo2.uint8t, 2);
#endif
return 0;
}
else
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error writing Temporary Coefficient List"));
#endif
return 1;
}
}
//!*************************************************************
//! Name: resetTemporaryCalibrationData()
//! Description: Reset all temporary calibration data and return average to 1
//! Param : void
//! Returns: "0" if no error, "1" if error
//!*************************************************************
uint8_t aqualaboModbusSensorsClass::resetTemporaryCalibrationData(uint8_t returnAvgTo1_stopElectronicZero)
{
//Write '0x00000000 ' at 0x014C address
//List of temporary coefficients to be used in measurement calculation
initCommunication();
uint8_t status = 0xFF;
uint8_t retries = 0;
sensor.setTransmitBuffer(0, 0x0000);
sensor.setTransmitBuffer(1, 0x0000);
while ((status !=0) && (retries < 5))
{
status = sensor.writeMultipleRegisters(0x014C, 2);
delay(100);
retries++;
}
// Check that the direction has been well written
if (status != 0)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("0x014C writing failed"));
#endif
return 1;
}
//Write '0x0001' at 0x004C address
//Reset standard + Operator + Date of temporary calibration
//active with value 0x01
status = -1;
retries = 0;
sensor.setTransmitBuffer(0, 0x0001);
while ((status !=0) && (retries < 5))
{
//List of temporary coefficients to be used in measurement calculation
status = sensor.writeMultipleRegisters(0x004C, 1);
delay(100);
retries++;
}
// Check that the direction has been well written
if (status != 0)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("0x014C writing failed"));
#endif
return 1;
}
if(returnAvgTo1_stopElectronicZero > 0)
{
//Configure average -> return to 1
if(writeAverage(1) == 0)
{
if(readAverage() != 1)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error configuring average to 1"));
#endif
return 1;
}
}
else
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Communication error configuring average to 1"));
#endif
//if fails return 1
return 1;
}
}
if(returnAvgTo1_stopElectronicZero == RETURN_AVG_TO_1_AND_STOP_ELECTRONIC_ZERO)
{
//Write float 3.0 in 0x0208 address
if(writeCalibrationStandard(0x0208, (float)3.0) == 1)
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error writing calibration standart for stopping electronic zero"));
#endif
return 1;
}
}
return 0;
}
//!*************************************************************
//! Name: writeAverage()
//! Description: Configure the average value (1-50)
//! Param : avg
//! Returns: uint8_t "0" if no error, "1" if error
//!*************************************************************
uint8_t aqualaboModbusSensorsClass::writeAverage(uint8_t avg)
{
initCommunication();
uint8_t status = 0xFF;
uint8_t retries = 0;
if (avg > 50) avg = 50;
while ((status !=0) && (retries < 5))
{
status = sensor.writeSingleRegister(AVRG_PARA_REG, avg);
delay(100);
retries++;
}
// Check that the direction has been well written
if (status == 0)
{
#if DEBUG_XTR_MODBUS > 1
PRINT_XTR_MODBUS(F("Average configured with value:"));
USB.println(avg, DEC);
#endif
return 0;
}
else
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Communication Error. Average not configured."));
#endif
return 1;
}
}
//!*************************************************************
//! Name: readWaitingTime()
//! Description: Get the necessary waiting time to get measures after asking for them
//! Param : void
//! Returns: 0 if OK, 1 if error
//!*************************************************************
uint8_t aqualaboModbusSensorsClass::readWaitingTime()
{
initCommunication();
uint8_t status = 0xFF;
uint8_t retries = 0;
while ((status !=0) && (retries < 10))
{
//Read 1 register
status = sensor.readHoldingRegisters(WAITING_TIME_REG, 1);
delay(100);
retries++;
}
if (status == 0)
{
waitingTime = sensor.getResponseBuffer(0);
#if DEBUG_XTR_MODBUS > 1
PRINT_XTR_MODBUS(F("waitingTime:"));
USB.print(waitingTime);
USB.println(F("ms"));
#endif
return 0;
}
else
{
// If no response from the slave, print an error message.
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Communication error reading waiting time"));
#endif
//if fails return 1
return 1;
}
}
//!*************************************************************
//! Name: readAverage()
//! Description: Read the average value (1-50)
//! Param : void
//! Returns: average value (1-50) if OK, 0 if error
//!*************************************************************
uint16_t aqualaboModbusSensorsClass::readAverage()
{
initCommunication();
uint16_t average = 0;
uint8_t status = 0xFF;
uint8_t retries = 0;
while ((status !=0) && (retries < 10))
{
//Read 1 register
status = sensor.readHoldingRegisters(AVRG_PARA_REG, 1);
delay(100);
retries++;
}
if (status == 0)
{
average = sensor.getResponseBuffer(0);
#if DEBUG_XTR_MODBUS > 1
PRINT_XTR_MODBUS(F("Average read with value:"));
USB.println(average, DEC);
#endif
return average;
}
else
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error reading average"));
#endif
return 0;
}
}
//!*************************************************************
//! Name: clearBuffer()
//! Description: Flushes the buffers.
//! Param : void
//! Returns: void
//!*************************************************************
void aqualaboModbusSensorsClass::clearBuffer()
{
// Clear Response Buffer
sensor.clearResponseBuffer();
sensor.clearTransmitBuffer();
delay(10);
}
//!*************************************************************
//! Name: readSerialNumber()
//! Description: Gets the serial number of the sensor
//! Param : void
//! Returns: "0" if no error, "1" if error
//!*************************************************************
uint8_t aqualaboModbusSensorsClass::readSerialNumber(char *sensorSerialNumber)
{
initCommunication();
uint8_t status = 0xFF;
uint8_t retries = 0;
while ((status !=0) && (retries < 5))
{
retries++;
status = sensor.readHoldingRegisters(SERIAL_NUMBER_REG, 16);
delay(100);
}
uint8_t j = 0;
if (status == 0)
{
for (int i=0; i<7; i++)
{
sensorSerialNumber[j++] = sensor.getResponseBuffer(i) >>8 & 0xFF;
sensorSerialNumber[j++] = sensor.getResponseBuffer(i) & 0xFF;
}
}
else
{
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Error reading serial number"));
#endif
return 1;
}
return status;
}
void aqualaboModbusSensorsClass::setParametersBySensor(uint8_t sensorType)
{
switch (sensorType)
{
case OPTOD:
sensorAddr = 10;
waitingTime = 500;
break;
case PHEHT:
sensorAddr = 20;
waitingTime = 400;
break;
case C4E:
sensorAddr = 30;
waitingTime = 500;
break;
case NTU:
sensorAddr = 40;
waitingTime = 300;
break;
case CTZN:
sensorAddr = 50;
waitingTime = 500;
break;
case MES5:
sensorAddr = 60;
waitingTime = 500;
break;
default:
sensorAddr = DEFAULT_ADDRESS;
waitingTime = DEFAULT_WAITING_TIME;
break;
}
}
//!*************************************************************
//! Name: readMeasures()
//! Description: Returns all the measures of the sensor
//! Param : void
//! Returns: 1 if OK, 0 if error
//!*************************************************************
uint8_t aqualaboModbusSensorsClass::readMeasures(float ¶meter1, float ¶meter2, float ¶meter3, float ¶meter4)
{
initCommunication();
uint8_t status = 0xFF;
uint8_t retries = 0;
//Set Modbus TX buffer with "0x000F" in order to get the 4 measures of the sensor
// TX buffer
// 0 0 0 0 1 1 1 1
// P3 P2 P1 T
sensor.setTransmitBuffer(0, 0x000F);
while ((status !=0) && (retries < 5))
{
retries++;
//Write 1 register (set previouly in TX buffer) in address "NEW_MEAS_REG"
status = sensor.writeMultipleRegisters(NEW_MEAS_REG, 1);
delay(100);
}
// Important delay
delay(waitingTime + 10);
if (status == 0)
{
status = -1;
retries = 0;
while ((status !=0) && (retries < 10))
{
//Read 8 registers with the 4 measures (each register is 2 bytes)
status = sensor.readHoldingRegisters(MEASUREMENTS_REG, 0x08);
retries++;
delay(100);
}
if (status == 0)
{
foo.ints[0] = sensor.getResponseBuffer(1);
foo.ints[1] = sensor.getResponseBuffer(0);
parameter1 = foo.toFloat;
foo.ints[0] = sensor.getResponseBuffer(3);
foo.ints[1] = sensor.getResponseBuffer(2);
parameter2 = foo.toFloat;
foo.ints[0] = sensor.getResponseBuffer(5);
foo.ints[1] = sensor.getResponseBuffer(4);
parameter3 = foo.toFloat;
foo.ints[0] = sensor.getResponseBuffer(7);
foo.ints[1] = sensor.getResponseBuffer(6);
parameter4 = foo.toFloat;
}
else
{
// If no response from the slave, print an error message.
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Communication error reading parameters"));
#endif
//if fails return 0
return 0;
}
}
else
{
// If no response from the slave, print an error message.
#if DEBUG_XTR_MODBUS > 0
PRINTLN_XTR_MODBUS(F("Communication error (Writing Multiple Registers)"));
#endif
return 0;
}
return 1;
}
aqualaboModbusSensorsClass aqualaboModbusSensors = aqualaboModbusSensorsClass();
| [
"tech@libelium.com"
] | tech@libelium.com |
b02ad122a7a0ce947f1a28810cb01c5bf34e2e7d | 7fe339704b452c6159cd04095f7880f875f5cc9c | /2_Foundations/02_Introduction_to_the_C++_Language/02_Write_Your_First_C++_Program/main.cpp | adc48dd604c01b83f4b9c66d9f3d740883eddee0 | [] | no_license | jianlu8/LearnC- | e99fcf36fb39584dab2ab89c31ce67dfdcfd0f62 | d4d4693e44002a9e8d185d79a2196453af6c089b | refs/heads/master | 2023-06-07T23:21:47.161865 | 2021-07-07T14:34:45 | 2021-07-07T14:34:45 | 383,167,690 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 74 | cpp | # include<iostream>
int main() {
std::cout << "Hello" << std::endl;
} | [
"limitlujian@163.com"
] | limitlujian@163.com |
0f52716f839d27ad22fae7054630aa1742a19e18 | 04fee3ff94cde55400ee67352d16234bb5e62712 | /7.20/source/Stu-35-王宇飞-STHLS2-2019-7-20/sculpture.cpp | 22b568fd2f13faf2c56e431071e5797d356ba8f4 | [] | no_license | zsq001/oi-code | 0bc09c839c9a27c7329c38e490c14bff0177b96e | 56f4bfed78fb96ac5d4da50ccc2775489166e47a | refs/heads/master | 2023-08-31T06:14:49.709105 | 2021-09-14T02:28:28 | 2021-09-14T02:28:28 | 218,049,685 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 472 | cpp | #include<bits/stdc++.h>
using namespace std;
long long int i,j,countt,a[100010],sum,l,r;
int pd,n,m;
int main () {
freopen("sculpture.in","r",stdin);
freopen("sculpture.out","w",stdout);
cin>>n;
for(i=1;i<=n;i++){
cin>>a[i];
}
cin>>m;
for(i=1;i<=m;i++){
cin>>pd>>l>>r;
if(pd==0){
for(j=l;j<=r;j++){
a[j]=(int)sqrt(a[j]);
}
}
if(pd==1){
for(j=l;j<=r;j++){
sum+=a[j];
}
cout<<sum<<endl;
sum=0;
}
}
}
| [
"15276671309@163.com"
] | 15276671309@163.com |
9e3572939aa56558ffa8e41745de323173feac00 | d210e600dac9df96ab9e7ee24752bd5c2915a47b | /A2oj Ladder/337C.cpp | bfa3f1363645f0de1a74db9a5ee3c83b2a28f2df | [] | no_license | Vaibhav026/Competitive-Coding | 7d1846b15cb69d0ab56e9f96b720aa9139197112 | 852cbba65215c4e08dd468a1aba157ec06a9555c | refs/heads/master | 2021-06-11T02:00:56.024321 | 2019-08-05T11:44:48 | 2019-08-05T11:44:48 | 128,098,255 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 740 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
long long binpow(long long val, long long deg, long long mod) {
if (!deg) return 1 % mod;
if (deg & 1) return binpow(val, deg - 1, mod) * val % mod;
long long res = binpow(val ,deg >> 1, mod);
return (res*res) % mod;
}
int main()
{
long int n,m,k;
long int mod = 1000000009;
cin >> n >> m >> k;
long long int p = 1ll*(k-1)*(n-m);
long int rem = (m)-(p) ;
//cout << p << endl;
if(rem <= 0){
cout << (m);
return 0;
}
else{
long int groups = rem/k;
long long int ans = ( ( 2*k )%mod * (binpow(2,groups,mod)-1))%mod;
long long int left = rem%k ;
ans = (ans + left + p%mod)%mod;
cout << ans;
}
return 0;
} | [
"vaibhavvashisht5@gmail.com"
] | vaibhavvashisht5@gmail.com |
5673225400f453855e9d92de82c78a3644cfc234 | e76ea38dbe5774fccaf14e1a0090d9275cdaee08 | /src/content/browser/renderer_host/render_view_host_factory.h | b0466355d4910f60e5cb6fef5a8964e98d49cd0a | [
"BSD-3-Clause"
] | permissive | eurogiciel-oss/Tizen_Crosswalk | efc424807a5434df1d5c9e8ed51364974643707d | a68aed6e29bd157c95564e7af2e3a26191813e51 | refs/heads/master | 2021-01-18T19:19:04.527505 | 2014-02-06T13:43:21 | 2014-02-06T13:43:21 | 16,070,101 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,624 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_FACTORY_H_
#define CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_FACTORY_H_
#include "base/basictypes.h"
#include "content/common/content_export.h"
namespace content {
class RenderViewHost;
class RenderViewHostDelegate;
class RenderWidgetHostDelegate;
class SessionStorageNamespace;
class SiteInstance;
// A factory for creating RenderViewHosts. There is a global factory function
// that can be installed for the purposes of testing to provide a specialized
// RenderViewHost class.
class RenderViewHostFactory {
public:
// Creates a RenderViewHost using the currently registered factory, or the
// default one if no factory is registered. Ownership of the returned
// pointer will be passed to the caller.
static RenderViewHost* Create(
SiteInstance* instance,
RenderViewHostDelegate* delegate,
RenderWidgetHostDelegate* widget_delegate,
int routing_id,
int main_frame_routing_id,
bool swapped_out,
bool hidden);
// Returns true if there is currently a globally-registered factory.
static bool has_factory() {
return !!factory_;
}
protected:
RenderViewHostFactory() {}
virtual ~RenderViewHostFactory() {}
// You can derive from this class and specify an implementation for this
// function to create a different kind of RenderViewHost for testing.
virtual RenderViewHost* CreateRenderViewHost(
SiteInstance* instance,
RenderViewHostDelegate* delegate,
RenderWidgetHostDelegate* widget_delegate,
int routing_id,
int main_frame_routing_id,
bool swapped_out) = 0;
// Registers your factory to be called when new RenderViewHosts are created.
// We have only one global factory, so there must be no factory registered
// before the call. This class does NOT take ownership of the pointer.
CONTENT_EXPORT static void RegisterFactory(RenderViewHostFactory* factory);
// Unregister the previously registered factory. With no factory registered,
// the default RenderViewHosts will be created.
CONTENT_EXPORT static void UnregisterFactory();
private:
// The current globally registered factory. This is NULL when we should
// create the default RenderViewHosts.
CONTENT_EXPORT static RenderViewHostFactory* factory_;
DISALLOW_COPY_AND_ASSIGN(RenderViewHostFactory);
};
} // namespace content
#endif // CONTENT_BROWSER_RENDERER_HOST_RENDER_VIEW_HOST_FACTORY_H_
| [
"ronan@fridu.net"
] | ronan@fridu.net |
dbf05015b79734701abdfb9e8ddef91ce7a0bb90 | 200bd4df89c3e11aa2205550faceb6ca6afa6e74 | /testAndr/mainwindow.cpp | 7a43fb190eb2e1cbb3c073667773e66053af373a | [
"MIT"
] | permissive | as-i-see/OOPFundamentals2sem | 4d564875ed818602b4d0ea927a84cd2cf615dc5b | a859001fba5e81446edf1e272909991fa2bfbd81 | refs/heads/master | 2021-10-28T12:30:42.942777 | 2018-06-10T14:24:55 | 2018-06-10T14:24:55 | 126,541,055 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,242 | cpp | #include "mainwindow.h"
#include "collisionsmaster.h"
#include "ui_mainwindow.h"
#include <QApplication>
#include <QScreen>
#include <QSlider>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
this->scene = new Scene();
setCentralWidget(this->scene);
// this->toolBar = new ToolBar(this, this->scene);
this->toolBar = new QToolBar;
this->toolBar->setIconSize(QSize(150, 150));
this->toolBar->setMovable(false);
this->toolBar->setStyleSheet("padding: 30px;"
"spacing: 30px");
QAction *restart =
new QAction(QIcon(":/images/restart.png"), QString("Restart"), this);
connect(restart, SIGNAL(triggered(bool)), this->scene, SLOT(restart()));
this->toolBar->addAction(restart);
QSlider *slider = new QSlider(Qt::Horizontal);
slider->setMaximum(0);
slider->setMaximum(10);
slider->setValue(10);
slider->setSingleStep(1);
slider->setTickPosition(QSlider::TicksBothSides);
slider->setTickInterval(1);
connect(slider, SIGNAL(valueChanged(int)), this->scene,
SLOT(setElasticFactor(int)));
this->toolBar->addWidget(slider);
this->addToolBar(this->toolBar);
}
MainWindow::~MainWindow() { delete ui; }
| [
"qtug@yandex.com"
] | qtug@yandex.com |
3a6447ec3f81f8d7e34266adf0443839c506f548 | 71feb2c3ad228b782a96a4eea0eb0fe230a0238b | /WowBot/ProcessDispatcher.h | b4eb79495d7caa5fed5528706c98956aed5e962f | [] | no_license | Cailiaock/OLDSHIT_WowBot | 1ca7b8f1b53cc0c466c3162bb556349c18d6e92b | 27a2ee48ca9afe6ae6f8dcb39a31570fa5a07411 | refs/heads/master | 2021-04-28T07:36:42.107806 | 2015-09-11T06:58:04 | 2015-09-11T06:58:04 | 122,226,808 | 1 | 1 | null | 2018-02-20T16:51:23 | 2018-02-20T16:51:23 | null | UTF-8 | C++ | false | false | 436 | h | #pragma once
#include "stdafx.h"
class ProcessCreationException: public Exception
{
public:
ProcessCreationException(string * text, DWORD error):Exception(text,error){};
};
class ProcessDispatcher
{
vector <Communicator*> communicators;
public:
vector<int*> *c;
ProcessDispatcher(void);
~ProcessDispatcher(void);
void ScanProcesses();
ProcessInteractor * CreateWowProcess();
//ProcessInteractor * StartNewProcess();
};
| [
"arttambel@gmail.com"
] | arttambel@gmail.com |
9f571301e3799fe6ae0cb95c915eb274300104cf | 373d47e80ab4275e4cb9febf0108e6c2027c0196 | /src/qt/optionsmodel.cpp | 884c37696a0260f846cbed9f217524aaa71d191d | [
"MIT"
] | permissive | PacManCoin/pmccore | bb30ffa964f840de936a435023c783ce4d9765a7 | 116333941d78eb257189cf7f636d586593da86df | refs/heads/master | 2020-03-14T15:13:02.707616 | 2018-05-10T00:47:24 | 2018-05-10T00:47:24 | 131,671,086 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 20,979 | cpp | // Copyright (c) 2011-2015 The Bitcoin Core developers
// Copyright (c) 2014-2018 The Dash developers
// Copyright (c) 2018-2018 The Pmc developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/pmc-config.h"
#endif
#include "optionsmodel.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "amount.h"
#include "init.h"
#include "validation.h" // For DEFAULT_SCRIPTCHECK_THREADS
#include "net.h"
#include "netbase.h"
#include "txdb.h" // for -dbcache defaults
#ifdef ENABLE_WALLET
#include "wallet/wallet.h"
#include "wallet/walletdb.h"
#include "masternodeconfig.h"
#include "privatesend-client.h"
#endif
#include <QNetworkProxy>
#include <QSettings>
#include <QStringList>
OptionsModel::OptionsModel(QObject *parent, bool resetSettings) :
QAbstractListModel(parent)
{
Init(resetSettings);
}
void OptionsModel::addOverriddenOption(const std::string &option)
{
strOverriddenByCommandLine += QString::fromStdString(option) + "=" + QString::fromStdString(mapArgs[option]) + " ";
}
// Writes all missing QSettings with their default values
void OptionsModel::Init(bool resetSettings)
{
if (resetSettings)
Reset();
this->resetSettings = resetSettings;
QSettings settings;
// Ensure restart flag is unset on client startup
setRestartRequired(false);
// These are Qt-only settings:
// Window
if (!settings.contains("fHideTrayIcon"))
settings.setValue("fHideTrayIcon", false);
fHideTrayIcon = settings.value("fHideTrayIcon").toBool();
Q_EMIT hideTrayIconChanged(fHideTrayIcon);
if (!settings.contains("fMinimizeToTray"))
settings.setValue("fMinimizeToTray", false);
fMinimizeToTray = settings.value("fMinimizeToTray").toBool() && !fHideTrayIcon;
if (!settings.contains("fMinimizeOnClose"))
settings.setValue("fMinimizeOnClose", false);
fMinimizeOnClose = settings.value("fMinimizeOnClose").toBool();
// Display
if (!settings.contains("nDisplayUnit"))
settings.setValue("nDisplayUnit", BitcoinUnits::PMC);
nDisplayUnit = settings.value("nDisplayUnit").toInt();
if (!settings.contains("strThirdPartyTxUrls"))
settings.setValue("strThirdPartyTxUrls", "");
strThirdPartyTxUrls = settings.value("strThirdPartyTxUrls", "").toString();
if (!settings.contains("theme"))
settings.setValue("theme", "");
#ifdef ENABLE_WALLET
if (!settings.contains("fCoinControlFeatures"))
settings.setValue("fCoinControlFeatures", false);
fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool();
if (!settings.contains("digits"))
settings.setValue("digits", "2");
if (!settings.contains("fShowMasternodesTab"))
settings.setValue("fShowMasternodesTab", masternodeConfig.getCount());
if (!settings.contains("fShowAdvancedPSUI"))
settings.setValue("fShowAdvancedPSUI", false);
fShowAdvancedPSUI = settings.value("fShowAdvancedPSUI", false).toBool();
if (!settings.contains("fLowKeysWarning"))
settings.setValue("fLowKeysWarning", true);
#endif // ENABLE_WALLET
// These are shared with the core or have a command-line parameter
// and we want command-line parameters to overwrite the GUI settings.
//
// If setting doesn't exist create it with defaults.
//
// If SoftSetArg() or SoftSetBoolArg() return false we were overridden
// by command-line and show this in the UI.
// Main
if (!settings.contains("nDatabaseCache"))
settings.setValue("nDatabaseCache", (qint64)nDefaultDbCache);
if (!SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString()))
addOverriddenOption("-dbcache");
if (!settings.contains("nThreadsScriptVerif"))
settings.setValue("nThreadsScriptVerif", DEFAULT_SCRIPTCHECK_THREADS);
if (!SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString()))
addOverriddenOption("-par");
// Wallet
#ifdef ENABLE_WALLET
if (!settings.contains("bSpendZeroConfChange"))
settings.setValue("bSpendZeroConfChange", true);
if (!SoftSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool()))
addOverriddenOption("-spendzeroconfchange");
// PrivateSend
if (!settings.contains("nPrivateSendRounds"))
settings.setValue("nPrivateSendRounds", DEFAULT_PRIVATESEND_ROUNDS);
if (!SoftSetArg("-privatesendrounds", settings.value("nPrivateSendRounds").toString().toStdString()))
addOverriddenOption("-privatesendrounds");
privateSendClient.nPrivateSendRounds = settings.value("nPrivateSendRounds").toInt();
if (!settings.contains("nPrivateSendAmount")) {
// for migration from old settings
if (!settings.contains("nAnonymizePmcAmount"))
settings.setValue("nPrivateSendAmount", DEFAULT_PRIVATESEND_AMOUNT);
else
settings.setValue("nPrivateSendAmount", settings.value("nAnonymizePmcAmount").toInt());
}
if (!SoftSetArg("-privatesendamount", settings.value("nPrivateSendAmount").toString().toStdString()))
addOverriddenOption("-privatesendamount");
privateSendClient.nPrivateSendAmount = settings.value("nPrivateSendAmount").toInt();
if (!settings.contains("fPrivateSendMultiSession"))
settings.setValue("fPrivateSendMultiSession", DEFAULT_PRIVATESEND_MULTISESSION);
if (!SoftSetBoolArg("-privatesendmultisession", settings.value("fPrivateSendMultiSession").toBool()))
addOverriddenOption("-privatesendmultisession");
privateSendClient.fPrivateSendMultiSession = settings.value("fPrivateSendMultiSession").toBool();
#endif
// Network
if (!settings.contains("fUseUPnP"))
settings.setValue("fUseUPnP", DEFAULT_UPNP);
if (!SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool()))
addOverriddenOption("-upnp");
if (!settings.contains("fListen"))
settings.setValue("fListen", DEFAULT_LISTEN);
if (!SoftSetBoolArg("-listen", settings.value("fListen").toBool()))
addOverriddenOption("-listen");
if (!settings.contains("fUseProxy"))
settings.setValue("fUseProxy", false);
if (!settings.contains("addrProxy"))
settings.setValue("addrProxy", "127.0.0.1:9050");
// Only try to set -proxy, if user has enabled fUseProxy
if (settings.value("fUseProxy").toBool() && !SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString()))
addOverriddenOption("-proxy");
else if(!settings.value("fUseProxy").toBool() && !GetArg("-proxy", "").empty())
addOverriddenOption("-proxy");
if (!settings.contains("fUseSeparateProxyTor"))
settings.setValue("fUseSeparateProxyTor", false);
if (!settings.contains("addrSeparateProxyTor"))
settings.setValue("addrSeparateProxyTor", "127.0.0.1:9050");
// Only try to set -onion, if user has enabled fUseSeparateProxyTor
if (settings.value("fUseSeparateProxyTor").toBool() && !SoftSetArg("-onion", settings.value("addrSeparateProxyTor").toString().toStdString()))
addOverriddenOption("-onion");
else if(!settings.value("fUseSeparateProxyTor").toBool() && !GetArg("-onion", "").empty())
addOverriddenOption("-onion");
// Display
if (!settings.contains("language"))
settings.setValue("language", "");
if (!SoftSetArg("-lang", settings.value("language").toString().toStdString()))
addOverriddenOption("-lang");
language = settings.value("language").toString();
}
void OptionsModel::Reset()
{
QSettings settings;
// Remove all entries from our QSettings object
settings.clear();
resetSettings = true; // Needed in pmc.cpp during shotdown to also remove the window positions
// default setting for OptionsModel::StartAtStartup - disabled
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(false);
}
int OptionsModel::rowCount(const QModelIndex & parent) const
{
return OptionIDRowCount;
}
// read QSettings values and return them
QVariant OptionsModel::data(const QModelIndex & index, int role) const
{
if(role == Qt::EditRole)
{
QSettings settings;
switch(index.row())
{
case StartAtStartup:
return GUIUtil::GetStartOnSystemStartup();
case HideTrayIcon:
return fHideTrayIcon;
case MinimizeToTray:
return fMinimizeToTray;
case MapPortUPnP:
#ifdef USE_UPNP
return settings.value("fUseUPnP");
#else
return false;
#endif
case MinimizeOnClose:
return fMinimizeOnClose;
// default proxy
case ProxyUse:
return settings.value("fUseProxy", false);
case ProxyIP: {
// contains IP at index 0 and port at index 1
QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
return strlIpPort.at(0);
}
case ProxyPort: {
// contains IP at index 0 and port at index 1
QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
return strlIpPort.at(1);
}
// separate Tor proxy
case ProxyUseTor:
return settings.value("fUseSeparateProxyTor", false);
case ProxyIPTor: {
// contains IP at index 0 and port at index 1
QStringList strlIpPort = settings.value("addrSeparateProxyTor").toString().split(":", QString::SkipEmptyParts);
return strlIpPort.at(0);
}
case ProxyPortTor: {
// contains IP at index 0 and port at index 1
QStringList strlIpPort = settings.value("addrSeparateProxyTor").toString().split(":", QString::SkipEmptyParts);
return strlIpPort.at(1);
}
#ifdef ENABLE_WALLET
case SpendZeroConfChange:
return settings.value("bSpendZeroConfChange");
case ShowMasternodesTab:
return settings.value("fShowMasternodesTab");
case ShowAdvancedPSUI:
return fShowAdvancedPSUI;
case LowKeysWarning:
return settings.value("fLowKeysWarning");
case PrivateSendRounds:
return settings.value("nPrivateSendRounds");
case PrivateSendAmount:
return settings.value("nPrivateSendAmount");
case PrivateSendMultiSession:
return settings.value("fPrivateSendMultiSession");
#endif
case DisplayUnit:
return nDisplayUnit;
case ThirdPartyTxUrls:
return strThirdPartyTxUrls;
#ifdef ENABLE_WALLET
case Digits:
return settings.value("digits");
#endif // ENABLE_WALLET
case Theme:
return settings.value("theme");
case Language:
return settings.value("language");
#ifdef ENABLE_WALLET
case CoinControlFeatures:
return fCoinControlFeatures;
#endif // ENABLE_WALLET
case DatabaseCache:
return settings.value("nDatabaseCache");
case ThreadsScriptVerif:
return settings.value("nThreadsScriptVerif");
case Listen:
return settings.value("fListen");
default:
return QVariant();
}
}
return QVariant();
}
// write QSettings values
bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
bool successful = true; /* set to false on parse error */
if(role == Qt::EditRole)
{
QSettings settings;
switch(index.row())
{
case StartAtStartup:
successful = GUIUtil::SetStartOnSystemStartup(value.toBool());
break;
case HideTrayIcon:
fHideTrayIcon = value.toBool();
settings.setValue("fHideTrayIcon", fHideTrayIcon);
Q_EMIT hideTrayIconChanged(fHideTrayIcon);
break;
case MinimizeToTray:
fMinimizeToTray = value.toBool();
settings.setValue("fMinimizeToTray", fMinimizeToTray);
break;
case MapPortUPnP: // core option - can be changed on-the-fly
settings.setValue("fUseUPnP", value.toBool());
MapPort(value.toBool());
break;
case MinimizeOnClose:
fMinimizeOnClose = value.toBool();
settings.setValue("fMinimizeOnClose", fMinimizeOnClose);
break;
// default proxy
case ProxyUse:
if (settings.value("fUseProxy") != value) {
settings.setValue("fUseProxy", value.toBool());
setRestartRequired(true);
}
break;
case ProxyIP: {
// contains current IP at index 0 and current port at index 1
QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
// if that key doesn't exist or has a changed IP
if (!settings.contains("addrProxy") || strlIpPort.at(0) != value.toString()) {
// construct new value from new IP and current port
QString strNewValue = value.toString() + ":" + strlIpPort.at(1);
settings.setValue("addrProxy", strNewValue);
setRestartRequired(true);
}
}
break;
case ProxyPort: {
// contains current IP at index 0 and current port at index 1
QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts);
// if that key doesn't exist or has a changed port
if (!settings.contains("addrProxy") || strlIpPort.at(1) != value.toString()) {
// construct new value from current IP and new port
QString strNewValue = strlIpPort.at(0) + ":" + value.toString();
settings.setValue("addrProxy", strNewValue);
setRestartRequired(true);
}
}
break;
// separate Tor proxy
case ProxyUseTor:
if (settings.value("fUseSeparateProxyTor") != value) {
settings.setValue("fUseSeparateProxyTor", value.toBool());
setRestartRequired(true);
}
break;
case ProxyIPTor: {
// contains current IP at index 0 and current port at index 1
QStringList strlIpPort = settings.value("addrSeparateProxyTor").toString().split(":", QString::SkipEmptyParts);
// if that key doesn't exist or has a changed IP
if (!settings.contains("addrSeparateProxyTor") || strlIpPort.at(0) != value.toString()) {
// construct new value from new IP and current port
QString strNewValue = value.toString() + ":" + strlIpPort.at(1);
settings.setValue("addrSeparateProxyTor", strNewValue);
setRestartRequired(true);
}
}
break;
case ProxyPortTor: {
// contains current IP at index 0 and current port at index 1
QStringList strlIpPort = settings.value("addrSeparateProxyTor").toString().split(":", QString::SkipEmptyParts);
// if that key doesn't exist or has a changed port
if (!settings.contains("addrSeparateProxyTor") || strlIpPort.at(1) != value.toString()) {
// construct new value from current IP and new port
QString strNewValue = strlIpPort.at(0) + ":" + value.toString();
settings.setValue("addrSeparateProxyTor", strNewValue);
setRestartRequired(true);
}
}
break;
#ifdef ENABLE_WALLET
case SpendZeroConfChange:
if (settings.value("bSpendZeroConfChange") != value) {
settings.setValue("bSpendZeroConfChange", value);
setRestartRequired(true);
}
break;
case ShowMasternodesTab:
if (settings.value("fShowMasternodesTab") != value) {
settings.setValue("fShowMasternodesTab", value);
setRestartRequired(true);
}
break;
case ShowAdvancedPSUI:
fShowAdvancedPSUI = value.toBool();
settings.setValue("fShowAdvancedPSUI", fShowAdvancedPSUI);
Q_EMIT advancedPSUIChanged(fShowAdvancedPSUI);
break;
case LowKeysWarning:
settings.setValue("fLowKeysWarning", value);
break;
case PrivateSendRounds:
if (settings.value("nPrivateSendRounds") != value)
{
privateSendClient.nPrivateSendRounds = value.toInt();
settings.setValue("nPrivateSendRounds", privateSendClient.nPrivateSendRounds);
Q_EMIT privateSendRoundsChanged();
}
break;
case PrivateSendAmount:
if (settings.value("nPrivateSendAmount") != value)
{
privateSendClient.nPrivateSendAmount = value.toInt();
settings.setValue("nPrivateSendAmount", privateSendClient.nPrivateSendAmount);
Q_EMIT privateSentAmountChanged();
}
break;
case PrivateSendMultiSession:
if (settings.value("fPrivateSendMultiSession") != value)
{
privateSendClient.fPrivateSendMultiSession = value.toBool();
settings.setValue("fPrivateSendMultiSession", privateSendClient.fPrivateSendMultiSession);
}
break;
#endif
case DisplayUnit:
setDisplayUnit(value);
break;
case ThirdPartyTxUrls:
if (strThirdPartyTxUrls != value.toString()) {
strThirdPartyTxUrls = value.toString();
settings.setValue("strThirdPartyTxUrls", strThirdPartyTxUrls);
setRestartRequired(true);
}
break;
#ifdef ENABLE_WALLET
case Digits:
if (settings.value("digits") != value) {
settings.setValue("digits", value);
setRestartRequired(true);
}
break;
#endif // ENABLE_WALLET
case Theme:
if (settings.value("theme") != value) {
settings.setValue("theme", value);
setRestartRequired(true);
}
break;
case Language:
if (settings.value("language") != value) {
settings.setValue("language", value);
setRestartRequired(true);
}
break;
#ifdef ENABLE_WALLET
case CoinControlFeatures:
fCoinControlFeatures = value.toBool();
settings.setValue("fCoinControlFeatures", fCoinControlFeatures);
Q_EMIT coinControlFeaturesChanged(fCoinControlFeatures);
break;
#endif // ENABLE_WALLET
case DatabaseCache:
if (settings.value("nDatabaseCache") != value) {
settings.setValue("nDatabaseCache", value);
setRestartRequired(true);
}
break;
case ThreadsScriptVerif:
if (settings.value("nThreadsScriptVerif") != value) {
settings.setValue("nThreadsScriptVerif", value);
setRestartRequired(true);
}
break;
case Listen:
if (settings.value("fListen") != value) {
settings.setValue("fListen", value);
setRestartRequired(true);
}
break;
default:
break;
}
}
Q_EMIT dataChanged(index, index);
return successful;
}
/** Updates current unit in memory, settings and emits displayUnitChanged(newUnit) signal */
void OptionsModel::setDisplayUnit(const QVariant &value)
{
if (!value.isNull())
{
QSettings settings;
nDisplayUnit = value.toInt();
settings.setValue("nDisplayUnit", nDisplayUnit);
Q_EMIT displayUnitChanged(nDisplayUnit);
}
}
bool OptionsModel::getProxySettings(QNetworkProxy& proxy) const
{
// Directly query current base proxy, because
// GUI settings can be overridden with -proxy.
proxyType curProxy;
if (GetProxy(NET_IPV4, curProxy)) {
proxy.setType(QNetworkProxy::Socks5Proxy);
proxy.setHostName(QString::fromStdString(curProxy.proxy.ToStringIP()));
proxy.setPort(curProxy.proxy.GetPort());
return true;
}
else
proxy.setType(QNetworkProxy::NoProxy);
return false;
}
void OptionsModel::setRestartRequired(bool fRequired)
{
QSettings settings;
return settings.setValue("fRestartRequired", fRequired);
}
bool OptionsModel::isRestartRequired()
{
QSettings settings;
return settings.value("fRestartRequired", false).toBool();
}
| [
"pacmancoin.com@gmail.com"
] | pacmancoin.com@gmail.com |
ee5a3a5755e027f3a00c3c67b7c2be3ca7bce109 | e067f1809211406ebb17081e95893b5d5d291b93 | /NetworkSystem/Source/NetworkSystem.h | a6853fcd927b9f206474bffd597ffd6ad179d92b | [] | no_license | knnth3/Network-System | 4f0f7274d3e432b3f68914bd7753adc46f7a1598 | 258018b890049b5a860289f9745202cb925136dd | refs/heads/master | 2022-05-02T15:54:37.071189 | 2019-11-25T21:58:36 | 2019-11-25T21:58:36 | 223,854,431 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,821 | h | #pragma once
#define NETWORK_LAYER_API _declspec(dllexport)
#include <functional>
#include <map>
#include <queue>
#include <thread>
#include <mutex>
#include <atomic>
#include "TransportLayer.h"
#include "EncryptionLayer.h"
#include "Packet.h"
class NetworkSystem
{
public:
NetworkSystem();
~NetworkSystem();
template<typename Transport>
void Startup(int mode, int ip, int port)
{
m_bThreadRunning = true;
UpdateThread<Transport>((NetworkMode)mode, ip, port);
}
void ShutDown();
void SendData(int ID, char* data, int size);
void SetEncryptionLayer(EncryptionLayer* layer);
std::function<void(int)> OnSendData;
std::function<void(int)> OnDataRecieved;
private:
void DepositPacket(const Packet& p);
void AddRecievedPacket(const Packet& p);
void GenerateSendPacket();
Packet* GetOutgoingPacket();
void UnpackIncomingPacket(const Packet& p);
template<class T>
void UpdateThread(NetworkMode mode, int ip, int port)
{
static_assert(std::is_base_of<TransportLayer, T>::value, "T must inherit from TransportLayer");
TransportLayer* transport = (TransportLayer*)new T();
if (!transport->Intialize(mode, ip, port))
m_bThreadRunning = false;
while (m_bThreadRunning)
{
Packet* outbound = GetOutgoingPacket();
if (outbound)
{
transport->SendData(outbound->DataPtr, outbound->Size);
delete outbound;
}
if (transport->HasDataAvailable())
{
Packet p;
transport->GetNextData(p.DataPtr, p.Size);
UnpackIncomingPacket(p);
}
}
delete transport;
}
int m_MaxPacketSize;
int m_PacketSize;
std::mutex m_RecvMutex;
std::mutex m_sendMutex;
EncryptionLayer* m_EncryptionLayer;
std::queue<Packet> m_OutboundPackets;
std::map<int, std::queue<Packet>> m_RecievedPackets;
std::atomic<bool> m_bThreadRunning;
std::queue<Packet> m_SendBuffer;
};
| [
"kenkm963@gmail.com"
] | kenkm963@gmail.com |
46d9c35eadd6c57a111a1ae4ba17c52fef691566 | 7849d9e798f493deaae87b65ef35d91c7616f87c | /_tacoma/SIS.cpp | db06f62f24d97efaf7e004163d1db48278502791 | [
"MIT"
] | permissive | franksh/tacoma | 98903cb8866359702ce4c4cea8dac7ec4aa66096 | 3288d9f5642d1043059a23e8f884df901c441e26 | refs/heads/master | 2020-04-02T16:55:53.906121 | 2018-10-16T09:05:33 | 2018-10-16T09:05:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,560 | cpp | /*
* The MIT License (MIT)
* Copyright (c) 2018, Benjamin Maier
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall
* be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-
* INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "SIS.h"
using namespace std;
//namespace sis = SIS;
void SIS::update_network(
vector < set < size_t > > &_G,
double t
)
{
// map this network to the current network
G = &_G;
// compute degree and R0
size_t number_of_edges_times_two = 0;
for(auto const &neighbors: *G)
number_of_edges_times_two += neighbors.size();
mean_degree = number_of_edges_times_two / (double) N;
// update infected
SI_edges.clear();
// for each infected, check its neighbors.
// if the neighbor is susceptible, push it to the
// endangered susceptible vector
for(auto const &inf: infected)
for(auto const &neighbor_of_infected: (*G)[inf])
if (node_status[neighbor_of_infected] == EPI::S)
SI_edges.push_back( make_pair( inf, neighbor_of_infected ) );
// update the arrays containing the observables
update_observables(t);
}
void SIS::update_network(
vector < set < size_t > > &_G,
vector < pair < size_t, size_t > > &edges_in,
vector < pair < size_t, size_t > > &edges_out,
double t
)
{
// map this network to the current network
G = &_G;
// compute degree and R0
size_t number_of_edges_times_two = 0;
for(auto const &neighbors: *G)
number_of_edges_times_two += neighbors.size();
mean_degree = number_of_edges_times_two / (double) N;
// make searchable list
set < pair < size_t, size_t > > set_of_out_edges(edges_out.begin(), edges_out.end());
// erase all entries from SI which are part of the list of edges leaving
SI_edges.erase(
remove_if(
SI_edges.begin(),
SI_edges.end(),
[&set_of_out_edges](const pair < size_t, size_t > & edge) {
size_t u = edge.first;
size_t v = edge.second;
if (v<u)
swap(u,v);
return set_of_out_edges.find( make_pair(u,v) ) != set_of_out_edges.end();
}),
SI_edges.end()
);
for(auto const &e: edges_in)
{
size_t u = e.first;
size_t v = e.second;
if ((node_status[u] == EPI::S) and (node_status[v] == EPI::I))
SI_edges.push_back( make_pair( v, u ) );
else if ((node_status[v] == EPI::S) and (node_status[u] == EPI::I))
SI_edges.push_back( make_pair( u, v ) );
}
// update the arrays containing the observables
update_observables(t);
}
void SIS::get_rates_and_Lambda(
vector < double > &_rates,
double &_Lambda
)
{
// delete current rates
rates.clear();
// compute rates of infection
rates.push_back(infection_rate * SI_edges.size());
// compute rates of recovery
rates.push_back(recovery_rate * infected.size());
// return those new rates
_rates = rates;
_Lambda = accumulate(rates.begin(),rates.end(),0.0);
}
void SIS::make_event(
size_t const &event,
double t
)
{
if (event == 0)
infection_event();
else if (event == 1)
recovery_event();
else
throw length_error("SIS: chose event larger than rate vector which should not happen.");
update_observables(t);
}
void SIS::infection_event()
{
// initialize uniform integer random distribution
uniform_int_distribution < size_t > random_susceptible(0,SI_edges.size()-1);
// find the index of the susceptible which will become infected
size_t this_susceptible_index = random_susceptible(generator);
// get the node number of this susceptible
size_t this_susceptible = (SI_edges.begin() + this_susceptible_index)->second;
// save this node as an infected
infected.push_back(this_susceptible);
// change node status of this node
node_status[this_susceptible] = EPI::I;
// erase all edges in the SI set where this susceptible is part of
SI_edges.erase(
remove_if(
SI_edges.begin(),
SI_edges.end(),
[&this_susceptible](const pair < size_t, size_t > & edge) {
return edge.second == this_susceptible;
}),
SI_edges.end()
);
// push the new SI edges
size_t & this_infected = this_susceptible;
for(auto const &neighbor: (*G)[this_infected])
if (node_status[neighbor] == EPI::S)
SI_edges.push_back( make_pair(this_infected, neighbor) );
}
void SIS::recovery_event()
{
if ((prevent_disease_extinction) and (infected.size() == 1))
return ;
// initialize uniform integer random distribution
uniform_int_distribution < size_t > random_infected(0,infected.size()-1);
// find the index of the susceptible which will become infected
size_t this_infected_index = random_infected(generator);
auto it_infected = infected.begin() + this_infected_index;
// get the node id of this infected about to be recovered
size_t this_infected = *(it_infected);
// delete this from the infected vector
infected.erase( it_infected );
// change node status of this node
node_status[this_infected] = EPI::S;
// erase all edges in the SI set which this infected is part of
SI_edges.erase(
remove_if(
SI_edges.begin(),
SI_edges.end(),
[&this_infected](const pair < size_t, size_t > & edge) {
return edge.first == this_infected;
}),
SI_edges.end()
);
size_t const & this_susceptible = this_infected;
// push the new SI edges
for(auto const &neighbor: (*G)[this_susceptible])
if (node_status[neighbor] == EPI::I)
SI_edges.push_back( make_pair(neighbor, this_susceptible) );
}
void SIS::update_observables(
double t
)
{
double _R0 = infection_rate * mean_degree / recovery_rate;
R0.push_back(_R0);
// compute SI
SI.push_back(SI_edges.size());
// compute I
I.push_back(infected.size());
// push back time
time.push_back(t);
}
| [
"benjaminfrankmaier@gmail.com"
] | benjaminfrankmaier@gmail.com |
223499deb2c804490ca4b18f2f21d9dec5da0f2d | 59f00d4f6fccb6b1103c5aa54f43a6e4d4f8bfc5 | /src/common-plugin-operation/FilterPlugin/stdafx.h | 854d21d5fbf99ff878c89d7ba5fca46bf17554e7 | [] | no_license | tomas-pluskal/masspp | 9c9492443bb796533bcb27fe52a0a60e4ba62160 | 808bf095215e549e7eb5317c02c04dfb2ceaba15 | refs/heads/master | 2021-01-01T05:33:44.483127 | 2015-06-07T12:54:17 | 2015-06-07T12:54:17 | 33,917,190 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,969 | h | /**
* @file stdafx.h
* @brief common header file
*
* @author S.Tanaka
* @date 2007.08.16
*
* Copyright(C) 2006-2014 Eisai Co., Ltd. All rights reserved.
*/
#ifndef __KOME_FILTER_STD_AFX_H__
#define __KOME_FILTER_STD_AFX_H__
//
// namespace
//
/// kome project namespace
namespace kome {
/// filter namespace
namespace filter {
}
}
//
// macros
//
#define WXUSINGDLL
//
// message
//
#ifdef _MSC_VER
#pragma warning( disable:4190 )
#pragma warning( disable:4244 )
#pragma warning( disable:4251 )
#pragma warning( disable:4267 )
#pragma warning( disable:4561 )
#pragma warning( disable:4793 )
#pragma warning( disable:4819 )
#pragma warning( disable:4996 )
#endif // _MSC_VER
//
// libraries
//
#ifdef _MSC_VER
#pragma comment( lib, "CoreFunctions" )
#pragma comment( lib, "CoreToolkits" )
#pragma comment( lib, "DataObjects" )
#pragma comment( lib, "PluginTools" )
#pragma comment( lib, "ImageManager" )
#pragma comment( lib, "WindowManager" )
#pragma comment( lib, "NumericalTools" )
#pragma comment( lib, "DataOperation" )
#ifdef _DEBUG
#pragma comment( lib, "wxbase28d" )
#pragma comment( lib, "wxbase28d_net" )
#pragma comment( lib, "wxbase28d_xml" )
#pragma comment( lib, "wxexpatd" )
#pragma comment( lib, "wxjpegd" )
#pragma comment( lib, "wxmsw28d_adv" )
#pragma comment( lib, "wxmsw28d_aui" )
#pragma comment( lib, "wxmsw28d_core" )
#pragma comment( lib, "wxmsw28d_gl" )
#pragma comment( lib, "wxmsw28d_html" )
#pragma comment( lib, "wxmsw28d_media" )
#pragma comment( lib, "wxmsw28d_qa" )
#pragma comment( lib, "wxmsw28d_richtext" )
#pragma comment( lib, "wxmsw28d_xrc" )
#pragma comment( lib, "wxpngd" )
#pragma comment( lib, "wxregexd" )
#pragma comment( lib, "wxtiffd" )
#pragma comment( lib, "wxzlibd" )
#else
#pragma comment( lib, "wxbase28" )
#pragma comment( lib, "wxbase28_net" )
#pragma comment( lib, "wxbase28_xml" )
#pragma comment( lib, "wxexpat" )
#pragma comment( lib, "wxjpeg" )
#pragma comment( lib, "wxmsw28_adv" )
#pragma comment( lib, "wxmsw28_aui" )
#pragma comment( lib, "wxmsw28_core" )
#pragma comment( lib, "wxmsw28_gl" )
#pragma comment( lib, "wxmsw28_html" )
#pragma comment( lib, "wxmsw28_media" )
#pragma comment( lib, "wxmsw28_qa" )
#pragma comment( lib, "wxmsw28_richtext" )
#pragma comment( lib, "wxmsw28_xrc" )
#pragma comment( lib, "wxpng" )
#pragma comment( lib, "wxregex" )
#pragma comment( lib, "wxtiff" )
#pragma comment( lib, "wxzlib" )
#endif // _DEBUG
#endif // _MSC_VER
//
// includes
//
#include "kome/CoreFunctions.h"
#include "kome/CoreToolkits.h"
#include "kome/DataObjects.h"
#include "kome/PluginTools.h"
#include "kome/ImageManager.h"
#include "kome/WindowManager.h"
#include "kome/NumericalTools.h"
#include "kome/DataOperation.h"
#endif // __KOME_FILTER_STD_AFX_H__
| [
"Satoshi Tanaka@localhost"
] | Satoshi Tanaka@localhost |
cfb01db3ec169627f29d82115a14d3c2c5f0943d | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_new_log_972.cpp | 79984851b02b402095ad30fcff39880541026f43 | [] | 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 | 27 | cpp | printf(" forked: "); | [
"993273596@qq.com"
] | 993273596@qq.com |
f5b140506b534a67a1e416c6c161eff2bf9293f0 | 87e14b0f29f4450b9ee18f5767882f66b08524f4 | /handy_firmware/handy_firmware.ino | e74ed9933bb30ae39ad851a77acaad125b0ce993 | [
"Unlicense"
] | permissive | no-go/ATMegaHandy | e5e629033158bee6a40796e9a2b8c8cf76da604f | ff215bbd95ade34dfd654a6f11a9ba541ebcdce2 | refs/heads/master | 2022-03-21T05:36:20.564014 | 2022-01-18T12:45:16 | 2022-01-18T12:45:16 | 171,131,347 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,840 | ino | #include <Wire.h> //I2C Arduino Library
#include <Adafruit_GFX.h>
#include "Adafruit_SSD1306.h"
#include <EEPROM.h>
#define RESET_EEPROM false
// ------------------------------------------------------
#define BUTTON1 A3
#define BUTTON2 4 // blue
#define BUTTON3 3 // red
#define BUTTON4 2 // yellow
#define LEDRED A0
#define LEDWHITE 9 // unused
#define VIBRATO 8 // unused (only on startup)
#define pinA A1
#define pinB A2
#define SERIAL_SPEED 9600
// HARDWARE I2C: A4 -> SDA, A5 -> SCL
#define PIN_RESET 4 // dummy
Adafruit_SSD1306 oled(PIN_RESET);
bool logi[8] = {0,0,0,0, 0,0,0,0};
int tick = 0;
bool changes = false;
byte valA = 0;
byte valB = 0;
byte valAold = 0;
byte valBold = 0;
bool valRed = false;
bool numberselect = false;
char numbers[21] = "+49 1570 000 00 00 "; // and char 21 is numbers[20] = '\0'
byte numberi = 0;
char buff;
int buffid = 0;
int vcc = 3780;
uint16_t counter = 0;
uint16_t eepromID = 0;
void head() {
oled.fillRect(0, 0, 20, 8, BLACK);
oled.drawRect(0, 0, 18, 8, WHITE);
oled.fillRect(18, 2, 3, 4, WHITE);
oled.fillRect(2, 2, map(vcc, 3700, 4350, 2, 14), 4, WHITE);
}
void setup() {
Serial.begin(SERIAL_SPEED);
pinMode(BUTTON1, INPUT_PULLUP);
pinMode(pinA, INPUT_PULLUP);
pinMode(pinB, INPUT_PULLUP);
pinMode(BUTTON2, INPUT_PULLUP);
pinMode(BUTTON3, INPUT_PULLUP);
pinMode(BUTTON4, INPUT_PULLUP);
digitalWrite(BUTTON3, HIGH);
digitalWrite(BUTTON4, HIGH);
pinMode(LEDRED, OUTPUT);
pinMode(LEDWHITE, OUTPUT);
pinMode(VIBRATO, OUTPUT);
oled.begin();
Serial.println(F("atz")); // reset
oled.clearDisplay();
oled.setTextColor(WHITE, BLACK);
oled.setTextSize(2);
oled.setCursor(8, 20);
oled.print(F("TelEiFone"));
oled.display();
if (RESET_EEPROM == true) {
for (eepromID=0; eepromID<6; ++eepromID) {
EEPROM.put(21*eepromID, numbers);
}
eepromID=0;
}
EEPROM.get(21*eepromID, numbers);
digitalWrite(LEDRED, LOW);
digitalWrite(LEDWHITE, LOW);
Serial.println(F("ate0")); // echo off
delay(800);
// store incoming sms and returns: +CMTI: "SM",1\n
Serial.println(F("at+cnmi=2,1,0,0,0"));
// not store incoming sms and returns the SMS data:
// +CMT: "+4915xxxyyyyy4","","22/01/13,21:49:52+04"
// sms text
//Serial.println(F("at+cnmi=1,2,0,0,0"));
delay(800);
// info/status/hello
digitalWrite(VIBRATO, HIGH);
Serial.println(F("ati"));
delay(500);
digitalWrite(VIBRATO, LOW);
// at+cops? get network cooperator
// at+cops=? list networks cooperator
// at+cbc 0,80,4025 (0=not charge,80%,4025mV)
oled.clearDisplay();
oled.setTextSize(1);
oled.setCursor(0, 8);
}
void loop() {
counter = (counter+1)%32000;
changes = false;
valA = digitalRead(pinA);
valB = digitalRead(pinB);
if (valA != valAold || valB != valBold) {
if (valA && valB) {
tick=0;
for (int i=0;i<8;++i) {
logi[i] = false;
}
}
logi[tick] = valA;
tick = (tick+1)%8;
logi[tick] = valB;
tick = (tick+1)%8;
valAold = valA;
valBold = valB;
changes = true;
}
// rotation encoder -----------------
if (changes) {
if (
logi[0] == 1 && logi[1] == 1 && logi[2] == 0 && logi[3] == 1 &&
logi[4] == 0 && logi[5] == 0 && logi[6] == 1 && logi[7] == 0
) {
// anti clockwise
if (numberselect) {
if (numbers[numberi] == '+') {
numbers[numberi] = '9';
} else if (numbers[numberi] == ' ') {
numbers[numberi] = '+';
} else if (numbers[numberi] == '0') {
numbers[numberi] = ' ';
} else {
numbers[numberi]--;
}
oled.clearDisplay();
head();
oled.setCursor(26, 0);
oled.print(numbers);
oled.setCursor(26+6*numberi, 8);
oled.print(F("-"));
oled.display();
}
}
if (
logi[0] == 1 && logi[1] == 1 && logi[2] == 1 && logi[3] == 0 &&
logi[4] == 0 && logi[5] == 0 && logi[6] == 0 && logi[7] == 1
) {
// clockwise
if (numberselect) {
if (numbers[numberi] == '9') {
numbers[numberi] = '+';
} else if (numbers[numberi] == '+') {
numbers[numberi] = ' ';
} else if (numbers[numberi] == ' ') {
numbers[numberi] = '0';
} else {
numbers[numberi]++;
}
oled.clearDisplay();
head();
oled.setCursor(26, 0);
oled.print(numbers);
oled.setCursor(26+6*numberi, 8);
oled.print(F("-"));
oled.display();
}
}
}
// rotation encoder pressed --------------------------- (next digit)
if (digitalRead(BUTTON1) == LOW) {
if (numberselect) {
delay(100);
numberi = (numberi+1)%20;
oled.clearDisplay();
head();
oled.setCursor(26, 0);
oled.print(numbers);
oled.setCursor(26+6*numberi, 8);
oled.println(F("-"));
oled.print(F("Addr. id: "));
oled.print(eepromID+1);
oled.display();
} else {
// -------------------------------------- load next addr id
EEPROM.put(21*eepromID, numbers);
eepromID = (eepromID+1)%6;
EEPROM.get(21*eepromID, numbers);
oled.clearDisplay();
head();
oled.setCursor(26, 0);
oled.print(F("Addr. id: "));
oled.print(eepromID+1);
oled.setCursor(0, 16);
oled.print(numbers);
oled.display();
}
}
// blue button ------------------------------------------------ (sms mode !) ---------
if (digitalRead(BUTTON2) == LOW) {
Serial.println(F("at+cmgf=1")); // sms text mode
if (numberselect) {
// select and send sms
EEPROM.put(21*eepromID, numbers);
numberselect = false;
oled.setCursor(0, 8);
oled.println(F("Send sms:"));
oled.println(F(" ja kann nicht"));
oled.println(F(" nein bis gleich"));
oled.println(F(" ohje ca. +15min"));
oled.println(F(" hm. ok bin spaet"));
oled.println(F(" haha 0 problemo"));
oled.print (F(" ruf mich mal an"));
oled.display();
uint8_t mid=0;
while (digitalRead(BUTTON1) == HIGH) {
// ----------------------------------- rotation encoder button: send sms
if (digitalRead(BUTTON2) == LOW) { // 2x blue button: break/not send --------
delay(200);
mid=100;
oled.clearDisplay();
oled.setCursor(0, 16);
buffid=0;
head();
oled.display();
break;
}
if (digitalRead(BUTTON3) == LOW) { // -------------- red button
delay(100);
if (mid<6) oled.setCursor(0, 16+mid*8); else oled.setCursor(54, 16+(mid-6)*8);
oled.print(F(" "));
if (mid>0) {
mid=mid-1;
}
}
if (digitalRead(BUTTON4) == LOW) { // --------------- yellow button
delay(100);
if (mid<6) oled.setCursor(0, 16+mid*8); else oled.setCursor(54, 16+(mid-6)*8);
oled.print(F(" "));
if (mid<10) {
mid=mid+1;
}
}
if (mid<6) oled.setCursor(0, 16+mid*8); else oled.setCursor(54, 16+(mid-6)*8);
oled.print(F(">"));
oled.display();
}
if (mid<100) {
// ----------------------------- send sms
oled.clearDisplay();
head();
oled.setCursor(0, 8);
buffid=0;
oled.println(F("send..."));
Serial.println(F("at+cmgf=1")); // sms text mode
delay(500);
Serial.print(F("AT+CMGS=\""));
for (numberi=0; numberi<20; ++numberi) {
if (numbers[numberi] != ' ') Serial.print(numbers[numberi]);
}
numberi=0;
Serial.println(F("\""));
delay(500);
switch(mid) {
case 0:
Serial.print(F("ja"));
break;
case 1:
Serial.print(F("nein"));
break;
case 2:
Serial.print(F("ohje"));
break;
case 3:
Serial.print(F("hm. okay."));
break;
case 4:
Serial.print(F("haha :-D"));
break;
case 5:
Serial.print(F("Ruf mich mal an!"));
break;
case 6:
Serial.print(F("ich kann nicht"));
break;
case 7:
Serial.print(F("bis gleich"));
break;
case 8:
Serial.print(F("ca. +15min"));
break;
case 9:
Serial.print(F("bin spaet"));
break;
case 10:
Serial.print(F("null problemo"));
break;
default:
Serial.print(F("hm..."));
}
delay(500);
Serial.print((char)26); // ctrl+z
delay(500);
oled.display();
}
} else {
delay(1000);
if (digitalRead(BUTTON2) == LOW) {
// --------------------------------- long press!
oled.setCursor(0, 16);
oled.println(F("del all sms!"));
oled.display();
// ---------------------------------> delete all sms
Serial.println(F("at+cmgd=1,4"));
} else {
// --------------------------------- read all sms
Serial.println(F("at+cmgl=\"ALL\",1"));
}
}
}
// red button --------------------------------------------------
if (digitalRead(BUTTON3) == LOW) {
valRed = !valRed;
digitalWrite(LEDRED, valRed);
oled.clearDisplay();
head();
oled.setCursor(0, 8);
delay(400);
if (valRed) {
if (numberselect) {
// --------------------------------- dial
EEPROM.put(21*eepromID, numbers);
numberselect = false;
oled.println(F("Dial..."));
oled.display();
// dial
Serial.print(F("atd"));
for (numberi=0; numberi<20; ++numberi) {
if (numbers[numberi] != ' ') Serial.print(numbers[numberi]);
}
numberi = 0;
Serial.println(F(";"));
delay(300);
Serial.println(F("atm"));
} else {
// --------------------------------- accept call
oled.println(F("Accept Call..."));
oled.display();
Serial.println(F("ata"));
}
} else {
// --------------------------------- hang up
oled.println(F("Hang up..."));
oled.display();
Serial.println(F("ath"));
}
}
// yellow button ----------------------------- (select a address/number)
if (digitalRead(BUTTON4) == LOW) {
numberselect = !numberselect;
delay(400);
oled.clearDisplay();
head();
oled.setCursor(26, 0);
if (numberselect) {
oled.print(numbers);
oled.setCursor(26+6*numberi, 8);
oled.print(F("-"));
} else {
EEPROM.put(21*eepromID, numbers);
}
}
// log: read/print gsm answers -------------------------------
while (Serial.available()) {
buff = (char) Serial.read();
if (buff != '\n' && buff != '\r') {
oled.print(buff);
} else {
oled.print(' ');
}
buffid++;
}
// log: display refresh ----------------------
if (counter%300==100) {
if (buffid > (21*6)) {
oled.setCursor(0, 16);
buffid=0;
}
oled.display();
}
// request/update power and net quality ----------------------
if (counter==20000) {
ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
delay(5);
ADCSRA |= _BV(ADSC); // Start conversion
while (bit_is_set(ADCSRA,ADSC)); // measuring
vcc = ADCL;
vcc |= ADCH<<8;
vcc = 1126400L / vcc;
if (vcc<3700) vcc = 3700;
if (numberselect == false) {
head();
Serial.println(F("at+csq")); // net quality
}
}
}
| [
"no-go@localhost"
] | no-go@localhost |
81ab66eb22748f1fd6f4894b2c02254309219381 | 6f6a88ba519d9569b8bf17a1dd87537c24f28098 | /TrkDiag/inc/TrkCaloInfo.hh | 8c9393642b6032c1a62209406eeb363ea9d62ef7 | [
"Apache-2.0"
] | permissive | Mu2e/Offline | 728e3d9cd8144702aefbf35e98d2ddd65d113084 | d4083c0223d31ca42e87288009aa127b56354855 | refs/heads/main | 2023-08-31T06:28:23.289967 | 2023-08-31T02:23:04 | 2023-08-31T02:23:04 | 202,804,692 | 12 | 73 | Apache-2.0 | 2023-09-14T19:55:58 | 2019-08-16T22:03:57 | C++ | UTF-8 | C++ | false | false | 2,378 | hh | //
// structs used to record calorimeter information matched to a track
// All energies are in units of MeV, momenta are in units of MeV/c,
// time in nsec WRT when the proton bunch pulse peak hits the production target,
// positions are in mm WRT the center of the tracker.
// Dave Brown (LBNL)
//
#ifndef TrkCaloInfo_HH
#define TrkCaloInfo_HH
#include "Offline/DataProducts/inc/GenVector.hh"
#include "Rtypes.h"
#include <string>
namespace {
std::string XYZnames(const char* vname) {
std::string svname(vname);
static std::string leaves; leaves = svname + std::string("x/F:") +
svname + std::string("y/F:") + svname + std::string("z/F");
return leaves;
}
}
namespace mu2e
{
using std::string;
// struct for Calorimeter information associated with a track
struct TrkCaloInfo {
// construct from a track-calo match
Float_t _dt; // extrapolated track - cluster time
Float_t _du; // track-cluster match separation in 'u' direction
Float_t _dv; // track-cluster match separation in 'v' direction
Float_t _ds; // path through crystal (?)
Float_t _ep; // track-cluster match E/p
Float_t _uvChisq; // chisquared from UV match
Float_t _tChisq; // chisquared from time match
Float_t _dtllr; // log likelihood ratio for this dt (electron/muon??)
Float_t _epllr; // log likelihood ratio for this e/p
Float_t _eclust; // cluster energy
Float_t _tclust; // cluster time
Int_t _section; // cluster section
XYZVectorF _cpos; // calorimeter cluster position
XYZVectorF _tpos; // extrapolated track position near calorimeter cluster
XYZVectorF _tdir; // extrapolated track position near calorimeter cluster
Float_t _ttrk; // track time at intersection point
static string leafnames() {
static string leaves;
leaves =
string("dt/F:du/F:dv/F:ds/F:ep/F:uvchisq/F:tchisq/F:dtllr/F:epllr/F:") + // matching info
string("eclust/F:tclust/F:section/I:") + // cluster information
XYZnames("cpos").c_str() + string(":") +
XYZnames("tpos").c_str() + string(":") +
XYZnames("tdir").c_str() + string(":") +
string("ttrk/F");
return leaves;
}
void reset() {
_dt = _du = _dv = _ds = _ep = _uvChisq = _tChisq = _dtllr = _epllr = _eclust = _tclust = _ttrk = 0.0;
_cpos = _tpos = _tdir = XYZVectorF();
}
};
}
#endif
| [
"dave_brown@lbl.gov"
] | dave_brown@lbl.gov |
cd9897bb9ad1f5017d7f0e133ac7dd06a3d08256 | a6e2d1cdd028144c2e1da717b6fab7b4ff6228c4 | /Raspberry/main.cpp | 7350f8dd8983f62d0b92a0ad94b71d68771cd7f5 | [] | no_license | HeroChan0330/SPI-Raspberry-Arduino | 4d3d60e929d35da86fff82e59f0f67c462e27a5d | 7a8c9ab11838bbce4928f6551dddb5e11a166721 | refs/heads/master | 2020-03-28T08:46:49.639082 | 2018-09-09T03:08:32 | 2018-09-09T03:08:32 | 147,988,738 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 178 | cpp | #include "ArduinoModule.h"
#include <stdint.h>
#include <iostream>
using namespace std;
int main(){
connectInit();
while(1){
sleep(1);
}
return 0;
}
| [
"592061719@qq.com"
] | 592061719@qq.com |
b151edbdc4783721bf29ffbdb4acdcd65d4c855c | eff5f0d1575e7e6e8adff5150d658096fa7c8658 | /Actividades/A6.2.LvalueRValue/main.cpp | 23847ea197288602f1441bf3f7ee5b867cd2c16c | [] | no_license | TeraBlitz/A00820377_AyMSS18 | 043db7174989d790d5d7b732de7424ee8982c268 | 74b15ef511646af27e4de255d5c4df266501c6d1 | refs/heads/master | 2021-05-12T15:49:27.448165 | 2018-05-19T14:25:18 | 2018-05-19T14:25:18 | 116,961,423 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 883 | cpp | #include <iostream>
using namespace std;
class Foo{
int value;
int* pointer;
public:
/// ///predefine el valor de value
explicit Foo(int value = 0): value(value), pointer(new int[value]){cout<<"param const"<<endl;}
Foo( const Foo& red){cout<<"coy const"<<endl;}
Foo& operator=(const Foo& ref)
{
cout<<"copy assig"<<endl;
this->value=ref.value;
this->pointer= new int[value];
///ciclo para poiar cada valor del areglo pointer
///ooooooooooooooooooooooooooooo
Foo temp(ref);
swap(value,temp.value);
swap(pointer,temp.pointer);
return *this;
}
Foo& operator=(Foo&& temp)
{
cout<<"MOVEgi assig"<<endl;
swap(value,temp.value);
swap(pointer,temp.pointer);
return *this;
}
};
int main() {
Foo a(5);
Foo b;
b=a;
return 0;
}
| [
"raulspam96@gmail.com"
] | raulspam96@gmail.com |
10e2d1bc91440cf13cc356f32902f2e2a18db7df | fcc4255330e54117e785fe4f9ad7f03f13e9b59f | /practice/cpp/dynamic_programming/best_time_to_buy.cpp | 3423b1ff6717a445c6f8d83ccc31d228df7f3874 | [] | no_license | truongpt/warm_up | f5cc018e997e7edefe2802c6e346366e32c41b35 | 47c5694537fbe32ed389e82c862e283b90a9066d | refs/heads/master | 2023-07-18T11:10:22.978036 | 2021-09-02T20:32:04 | 2021-09-02T20:32:04 | 242,413,021 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 780 | cpp | /*
- Problem: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
- Solution:
- Using 2 state BUY and SELL, and result is max value at SELL state
- Find max value for each state.
- for BUY: comparing buy and NOT buy
- for SELL: comparing sell and NOT sell with pre state must be buy
- Time and space complexity
- TC: O(n)
- SC: O(1)
*/
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
int maxProfit(vector<int>& prices) {
int sell = 0, buy = INT_MIN;
for (auto price : prices) {
buy = max(buy, -price);
sell = max(sell, buy + price);
}
return sell;
}
int main(void)
{
vector<int> prices = {7,1,5,3,6,4};
cout << maxProfit(prices) << endl;
}
| [
"truong.phamtrong@vti.com.vn"
] | truong.phamtrong@vti.com.vn |
798f3b44c5252d2488cb6eaa82b01e1a7b6d4211 | f7ae8c0c70ccba8a15fdf9e0ad52dceb06810e54 | /libraries/GhostwareEngine/include/GG/Graphics/BasicSceneGraph.h | 12b10ce48638a4518933fb34cc625df7aad0aa01 | [
"Apache-2.0"
] | permissive | Xaer033/PitWizard | 8efbf27dd9883857276e6d1db823017ea5994a62 | 9fb32cb4330d7d83676dc6db1f7cfec65dfb2568 | refs/heads/master | 2020-05-21T20:58:41.275791 | 2016-11-02T06:34:34 | 2016-11-02T06:34:34 | 62,694,540 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 562 | h | // Ghostware Games inc. 2016 -Julian Williams
#pragma once
#include <string>
#include <array>
#include "ISceneGraph.h"
namespace GG
{
class BasicSceneGraph : public ISceneGraph
{
public:
BasicSceneGraph( int maxSize );
virtual ~BasicSceneGraph();
virtual void init();
virtual void shutdown();
virtual SceneNode * createSceneNode( );
virtual void removeSceneNode( SceneNode * node );
virtual bool getVisibleObjects( const Camera * cam, RenderableObjectList & renderList );
private:
std::vector<SceneNode> _sceneNodeList;
};
} | [
"jdfrag@gmail.com"
] | jdfrag@gmail.com |
f102978e99ff3d1b4768960c67f07129ab02b46c | 1b09e99d580881a2f34ea038d5a26bc689872093 | /examples/multiple_timer/multiple_timer.ino | 3b5f152a5a603d8e4c2d69b14d60c5f2e1a8b8d3 | [] | no_license | just-another-archive/timuino | 95a1dd676255a13535c5b56c8be2f3190b5789d9 | a6bda68d68c0077b970a45e20a218931a5ea0aee | refs/heads/master | 2023-01-15T11:30:16.964192 | 2017-04-26T14:04:32 | 2017-04-26T14:04:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 654 | ino | #include <Timer.h>
double q = 0;
double w = 0;
double e = 0;
double r = 0;
void inc_q() { q += 1.0 ; }
void inc_w() { w += 0.5 ; }
void inc_e() { e += 0.1 ; }
void inc_r() { r += 0.01 ; }
Timer t1 = Timer(inc_q, 1, true);
Timer t2 = Timer(inc_w, 2, true);
Timer t3 = Timer(inc_e, 10, true);
Timer t4 = Timer(inc_r, 100, true);
void setup() {
Serial.begin(9600);
while(!Serial);
}
void loop() {
if (q > 3) {
return;
}
t1.tick();
t2.tick();
t3.tick();
t4.tick();
Serial.print(q);
Serial.print("\t");
Serial.print(w);
Serial.print("\t");
Serial.print(e);
Serial.print("\t");
Serial.print(r);
Serial.println();
}
| [
"julien.barbay@technicolor.com"
] | julien.barbay@technicolor.com |
4cf961ce57c44db46df78aa19b196fcb7626762f | e6b668c5afc2a333a836bd8dc1dce6e04a5ef328 | /codeforces/B. Balanced Substring.cpp | 6e728226025635e10932e56398f9069893df68e8 | [] | no_license | mahim007/Online-Judge | 13b48cfe8fe1e8a723ea8e9e2ad40efec266e7ee | f703fe624035a86d7c6433c9111a3e3ee3e43a77 | refs/heads/master | 2020-03-11T21:02:04.724870 | 2018-04-20T11:28:42 | 2018-04-20T11:28:42 | 130,253,727 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,494 | cpp | ///Bismillahir Rahmanir Rahim
#include<cstdio>
#include<iomanip>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<cctype>
#include<algorithm>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<stack>
#include<list>
#include<iostream>
#include<assert.h>
#include<bits/stdc++.h>
/**Define file I/O **/
#define f_input freopen("input.txt","r",stdin)
#define f_output freopen("output.txt","w",stdout)
/**Define memory set function**/
#define mem(x,y) memset(x,y,sizeof(x))
#define CLEAR(x) memset(x,0,sizeof(x))
/**Define function and object**/
#define pb push_back
#define Sort(v) sort(v.begin(),v.end())
#define RSort(v) sort(v.rbegin(),v.rend())
#define CSort(v,C) sort(v.begin(),v.end(),C)
#define all(v) (v).begin(),(v).end()
#define sqr(x) ((x)*(x))
#define find_dist(a,b) sqrt(sqr(a.x-b.x)+sqr(a.y-b.y))
/**Define constant value**/
#define ERR 1e-9
#define pi (2*acos(0))
#define PI 3.141592653589793
/**Define input**/
#define scanint(a) scanf("%d",&a)
#define scanLLD(a) scanf("%lld",&a)
#define scanstr(s) scanf("%s",s)
#define scanline(l) scanf(" %[^\n]",l)
#define scandouble(d) scanf("%lf",&d)
#define scanchar(c) scanf("%c",&c)
/**Define Bitwise operation**/
#define check(n, pos) (n & (1ll<<(pos)))
#define biton(n, pos) (n | (1ll<<(pos)))
#define bitoff(n, pos) (n & ~(1ll<<(pos)))
/**Define color**/
enum {WHITE,GREY,BLACK};
/**Sync off with stdio**/
#define __ cin.sync_with_stdio(false);\
cin.tie();
/**Debug tools**/
#define what_is(x) cerr<<(#x)<<" is "<<x<<endl
using namespace std;
/**Typedef**/
typedef vector<int> vint;
typedef vector< vint > vint2D;
typedef vector<string> vstr;
typedef vector<char>vchar;
typedef vector< vchar >vchar2D;
typedef queue<int> Qi;
typedef queue< Qi > Qii;
typedef map<int,int> Mii;
typedef map<string,int> Msi;
typedef map<int,string> Mis;
typedef stack<int> stk;
typedef pair<int,int> pp;
typedef pair<int, pp > ppp;
typedef long long int ll;
ll inf=1e18;
/**Template & structure**/
template<class T>T gcd(T a,T b){return b == 0 ? a : gcd(b, a % b);}
template<typename T>T lcm(T a, T b) {return a / gcd(a,b) * b;}
template<typename T>T last_bit(T n) { return n & 1; }
template<class T>T big_mod(T n,T p,T m){if(p==0)return (T)1;T x=big_mod(n,p/2,m);x=(x*x)%m;if(p&1)x=(x*n)%m;return x;}
template<class T>T modInv(T a, T m){T x, y; extgcd(a, m, x, y); x %= m; while (x < 0){x += m;} return x;}
template<class T> T extgcd(T a,T b,T& x,T& y){if(b==0){x=1;y=0;return a;}else{int g=extgcd(b,a%b,y,x);y-=a/b*x;return g;}}
template<class T>T multiplication(T n,T p,T m){if(p==0)return (T)0;T x=multiplication(n,p/2,m);x=(x+x)%m;if(p&1)x=(x+n)%m;return x;}
template<class T>T my_pow(T n,T p){if(p==0)return 1;T x=my_pow(n,p/2);x=(x*x);if(p&1)x=(x*n);return x;} ///n to the power p
template <class T> double getdist(T a, T b){return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));}/// distance between a & b
template <class T> T extract(string s, T ret) {stringstream ss(s); ss >> ret; return ret;}/// extract words or numbers from a line
template <class T> string tostring(T n) {stringstream ss; ss << n; return ss.str();}/// convert a number to string
template<class T> T Mod(T n,T m) {return (n%m+m)%m;} ///For Positive Negative No.
template<class T> T MIN3(T a,T b,T c) {return min(a,min(b,c));} /// minimum of 3 number
template<class T> T MAX3(T a,T b,T c) {return max(a,max(b,c));} ///maximum of 3 number
template <class T> void print_vector(T &v){int sz=v.size();if(sz)cout<<v[0];for(int i = 1; i < sz; i++)cout << ' '<<v[i];cout<<"\n";}/// prints all elements in a vector
bool isVowel(char ch){ ch=toupper(ch); if(ch=='A'||ch=='U'||ch=='I'||ch=='O'||ch=='E') return true; return false;}
bool isConsonant(char ch){if (isalpha(ch) && !isVowel(ch)) return true; return false;}
template <class R> R Josephus(R n,R k){R ans=1;for(R i=2;i<=n;i++)ans=(ans+k-1)%i+1;return ans;}
template <class R> R toitent_Phi2(R a){R result = a;for(R i=2;i*i<=a;i++){if(a%i==0) result=result-result/i;while(a%i==0) a=a/i;}if(a>1) result=result-result/a;return result;}
template <typename T> T Angle(T x1,T y1,T x2, T y2){ return atan( double(y1-y2) / double(x1-x2));}
//namespace debug{
// int sum(){return 0;}
// template<typename T,typename... Args> T sum(T a,Args... args) {return a+sum(args...);}
// void print(){cout<<"\n";return;}template<typename T, typename... Args>void print(T a,Args... args){cout<<a<<" ";print(args...);}
//}
/**Direction**/
///int dx[8] = {0, 1, 1, 1, 0, -1, -1, -1};int dy[8] = {1, 1, 0, -1, -1, -1, 0, 1}; ///8 Direction
///int dx[4] = {1, 0, -1, 0};int dy[4] = {0, 1, 0, -1}; ///4 Direction
///int dx[]={2,1,-1,-2,-2,-1,1,2};int dy[]={1,2,2,1,-1,-2,-2,-1};///Knight Direction
///int dx[]={-1,-1,+0,+1,+1,+0};int dy[]={-1,+1,+2,+1,-1,-2}; ///Hexagonal Direction
/******************************End******************************/
#define mxn 100005
string s;
ll zero[mxn],one[mxn];
map<ll,ll>M;
int main()
{
__;
ll T,t;
ll i,j,k;
ll n,m,q;
cin>>n;
cin>>s;
M[0]=-1;
ll ans=0;
for(i=0;i<n;i++){
if(i!=0){
zero[i]=zero[i-1];
one[i]=one[i-1];
}
if(s[i]=='0'){
zero[i]++;
}
else one[i]++;
ll b=zero[i]-one[i];
if(M.find(b)==M.end()){
M[b]=i;
}
else{
ans=max(ans,i-M[b]);
}
}
cout<<ans<<"\n";
return 0;
}
| [
"ashrafulmahim@gmail.com"
] | ashrafulmahim@gmail.com |
8ef49687f1386f7bfbd971e33deb19676b6238c1 | 5a9a43f1b949bb06ee963c6196100602df3f028e | /Arduino/ServoValues/ServoValues.ino | b66c064bfcd5e2cb6349cd8e50fe99fbd35ca461 | [] | no_license | kjeldvdl/ArduinoKringloop | b947e23cdfb6cc23b460f321977ec116c3a7790e | 347816e1a824bbca2e46013ee6e5d90b4718ee13 | refs/heads/master | 2021-08-26T04:41:16.698636 | 2017-11-21T15:43:51 | 2017-11-21T15:43:51 | 111,567,383 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,709 | ino |
// zoomkat 3-28-14 serial servo incremental test code
// using serial monitor type a character (s to increase or a
// to decrease) and enter to change servo position
// (two hands required, one for letter entry and one for enter key)
// use strings like 90x or 1500x for new servo position
// for IDE 1.0.5 and later
// Powering a servo from the arduino usually *DOES NOT WORK*.
#include<Servo.h>
String readString;
Servo myservo;
int pos=1500; //~neutral value for continous rotation servo
//int pos=90;
void setup()
{
myservo.attach(10); //, 400, 2600); //servo control pin, and range if desired
Serial.begin(9600);
Serial.println("serial servo incremental test code");
Serial.println("type a character (s to increase or a to decrease)");
Serial.println("and enter to change servo position");
Serial.println("use strings like 90x or 1500x for new servo position");
Serial.println();
}
void loop()
{
while (Serial.available()) {
char c = Serial.read(); //gets one byte from serial buffer
readString += c; //makes the string readString
delay(2); //slow looping to allow buffer to fill with next character
}
if (readString.length() >0) {
if(readString.indexOf('x') >0) {
pos = readString.toInt();
}
if(readString =="a"){
(pos=pos-100); //use larger numbers for larger increments
if(pos<0) (pos=0); //prevent negative number
}
if (readString =="s"){
(pos=pos+100);
}
if(pos >= 400) //determine servo write method
{
Serial.println(pos);
myservo.writeMicroseconds(pos);
}
else
{
Serial.println(pos);
myservo.write(pos);
}
}
readString=""; //empty for next input
}
| [
"kjeld@famvdlinden.nl"
] | kjeld@famvdlinden.nl |
d96f53d9e28c3b3f0e10a71d01285a5659f6c0c9 | 7762b2955cc842dda06c400e24bb29cfb5dbd664 | /Dream/3rdParty/STLPort/Package/test/unit/iota_test.cpp | 97a77947ea2d443fb7b88a2b7be3ae8ca0ff951f | [
"LicenseRef-scancode-stlport-4.5"
] | permissive | roke123/DreamEngine | d3b2404778cf8e253454bc65fbf839b59ed7b4de | 6f3d2b73367a8783078496af7f33e72a4bcc6915 | HEAD | 2016-09-05T11:31:06.882346 | 2014-10-09T15:57:53 | 2014-10-09T15:58:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 978 | cpp | #include <stlport/vector>
#include <stlport/numeric>
#include "cppunit/cppunit_proxy.h"
#if defined(_STLP_USE_NAMESPACES)
using namespace std;
#endif
//
// TestCase class
//
class IotaTest : public CPPUNIT_NS::TestCase
{
CPPUNIT_TEST_SUITE(IotaTest);
#if !defined (STLPORT) || defined (_STLP_NO_EXTENSIONS)
CPPUNIT_IGNORE;
#endif
CPPUNIT_TEST(iota1);
CPPUNIT_TEST_SUITE_END();
protected:
void iota1();
};
CPPUNIT_TEST_SUITE_REGISTRATION(IotaTest);
//
// tests implementation
//
void IotaTest::iota1()
{
#if defined (STLPORT) && !defined (_STLP_NO_EXTENSIONS)
int numbers[10];
iota(numbers, numbers + 10, 42);
CPPUNIT_ASSERT(numbers[0]==42);
CPPUNIT_ASSERT(numbers[1]==43);
CPPUNIT_ASSERT(numbers[2]==44);
CPPUNIT_ASSERT(numbers[3]==45);
CPPUNIT_ASSERT(numbers[4]==46);
CPPUNIT_ASSERT(numbers[5]==47);
CPPUNIT_ASSERT(numbers[6]==48);
CPPUNIT_ASSERT(numbers[7]==49);
CPPUNIT_ASSERT(numbers[8]==50);
CPPUNIT_ASSERT(numbers[9]==51);
#endif
}
| [
"roke-123@163.com"
] | roke-123@163.com |
93dec59b48deafbab83e9c890a1b02c315ebb1a9 | 955e74f1189da6d0e2e1a6b84b9a35397c43b0b7 | /include/ViewerHandler.h | 72968f96b41807b6c153e9f4afdf4d18d32e01f9 | [
"MIT"
] | permissive | TingKaiChen/B-SHOT-SLAM | d09ff922077a36600b87131396305cad5884ae49 | 1c36b0226db43f6958ad5dfc5f01d14c482d1515 | refs/heads/master | 2020-03-17T23:55:40.874078 | 2018-08-24T19:52:03 | 2018-08-24T19:52:03 | 134,068,399 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,044 | h | #ifndef VIEWERHANDLER_H
#define VIEWERHANDLER_H
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <fstream>
#include <sstream>
#include <string>
#include <opencv2/opencv.hpp>
#include <opencv2/viz.hpp>
typedef cv::viz::Viz3d VizViewer;
typedef cv::Affine3d ATrans;
typedef cv::Affine3d::Mat3 AMat3;
typedef cv::Affine3d::Mat4 AMat4;
typedef cv::Affine3d::Vec3 AVec3;
enum MODE{STOP, NEXT, SELECT1, SELECT2};
class InputHandler{
public:
InputHandler(VizViewer* v, MODE m):
viewer(v), mode(m), pov(TOP), isFirstSelection(true),
max_z(0), min_z(0), hasTrimSelected(false), isFirstSave(true){
saveIdxs.clear();
outFilename = "test.txt";
};
void setZRange(double zmin, double zmax){min_z = zmin; max_z = zmax;};
void setPointClouds(std::vector<cv::Vec3f>* s, std::vector<cv::Vec3f>* t,
std::vector<cv::Vec3f>* save){
source = s;
trim = t;
savedpc = save;
};
void setMode(MODE m){mode = m;};
MODE getMode(){return mode;};
void setFirstSelection(bool b){isFirstSelection = b;};
bool getFisrtSelection(){return isFirstSelection;};
bool isSelected(){return !sPoints.empty();};
bool rangeDefined(){return cube_vertices.size() >=2;};
bool isExist(int idx);
void seperateByRange();
bool trimEmpty(){return trim->empty();};
void saveTrimPC();
std::vector<cv::Vec3f>* getSavedPC(){return savedpc;};
void saveSelectedPT(){
if(isFirstSave){
saveIdxs.push_back(framePtIdx);
isFirstSave = false;
}
else{
saveIdxs.back() = framePtIdx;
}
};
void resetSelectedPT(){
if(!framePtIdx.empty()){
viewer->removeWidget("Cloud_saved");
}
savedpc->clear();
tempIdx.clear();
framePtIdx.clear();
isFirstSave = true;
};
void saveIdxOutFilename(std::string fn){outFilename = fn;};
void savePtIdxs();
void printProjMat(){
cv::Matx44d m;
viewer->getCamera().computeProjectionMatrix(m);
std::cout<<m<<std::endl;
};
void setClickPt(cv::Point p);
void printSelectingRange(cv::Point p);
void clearSelPoints();
void closeWindow(){viewer->close();};
void printViewerPose();
enum PoV{TOP, LEFT, BACK, RIGHT, FRONT};
void rotateViewerPose();
void resetViewerPose(){
viewer->setViewerPose(AMat4(1,0,0,0,0,-1,0,0,0,0,-1,220000,0,0,0,1));
pov = TOP;
};
void spinOnce(){viewer->spinOnce();};
private:
VizViewer* viewer;
MODE mode;
PoV pov;
bool isFirstSelection;
bool hasTrimSelected;
bool isFirstSave;
std::vector<cv::Point3d> sPoints;
std::vector<cv::Point3d> cube_vertices; // (min, max, min, max)
double max_z;
double min_z;
std::vector<cv::Vec3f> *source, *trim, *savedpc;
std::ifstream ifs;
std::ofstream ofs;
std::stringstream ss;
std::string outFilename;
std::vector<std::vector<int>> saveIdxs;
std::vector<int> framePtIdx;
std::vector<int> tempIdx;
};
#endif | [
"kai.tkchen@gmail.com"
] | kai.tkchen@gmail.com |
43ff224e38240d73c74a9d1708b45ff1aecc9825 | 0f8965ca3ef310dc0ba47f383ebdcc1bcef3616a | /ext/Xenos-master/ext/blackbone/src/BlackBone/Include/Macro.h | 7d5830f8a91c2a6b0a372cca220acd457132963d | [
"MIT"
] | permissive | sbaa2014/MFCApplication1 | dc8f58200845ad6c51edb7aff72b3532ad63f532 | ca6106582c77a55d50cfa209341dc424757d3978 | refs/heads/master | 2021-01-20T17:19:52.409004 | 2017-07-14T11:47:28 | 2017-07-14T11:47:28 | 95,742,921 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,806 | h | #pragma once
#include "../Config.h"
#include <stdint.h>
// Architecture-dependent pointer size
#define WordSize sizeof(void*)
// Rebase address
#define MAKE_PTR(T, pRVA, base) (T)((ptr_t)pRVA + (ptr_t)base)
#define REBASE(pRVA, baseOld, baseNew) ((ptr_t)pRVA - (ptr_t)baseOld + (ptr_t)baseNew)
// Field offset info
#define FIELD_OFFSET2(type, field) ((LONG)(LONG_PTR)&(((type)0)->field))
#define GET_FIELD_PTR(entry, field) (uintptr_t)((uint8_t*)entry + FIELD_OFFSET2(decltype(entry), field))
#define CALL_64_86(b, f, ...) (b ? f<uint64_t>(__VA_ARGS__) : f<uint32_t>(__VA_ARGS__))
#define FIELD_PTR_64_86(b, e, t, f) (b ? fieldPtr( e, &t<uint64_t>::f ) : fieldPtr( e, &t<uint32_t>::f ))
#define LODWORD(l) ((uint32_t)(((uint64_t)(l)) & 0xffffffff))
#define HIDWORD(l) ((uint32_t)((((uint64_t)(l)) >> 32) & 0xffffffff))
// Set or reset particular bit
#define SET_BIT(v, b) v |= (1ull << b)
#define RESET_BIT(v, b) v &= ~(1ull << b)
// Register aliases
#ifdef USE64
#define NAX Rax
#define NSP Rsp
#define NIP Rip
#define NDI Rdi
#define BitScanForwardT _BitScanForward64
#define BitScanReverseT _BitScanReverse64
#define BitTestAndSetT _bittestandset64
#define BitTestAndResetT _bittestandreset64
#define SET_JUMP(_src,_dst) *(uintptr_t*)(_src) = 0x25FF; *(uintptr_t*)((_src) + 6) = (uintptr_t)_dst;
#else
#define NAX Eax
#define NSP Esp
#define NIP Eip
#define NDI Edi
#define BitScanForwardT _BitScanForward
#define BitScanReverseT _BitScanReverse
#define BitTestAndSetT _bittestandset
#define BitTestAndResetT _bittestandreset
#define SET_JUMP(_src,_dst) *(uint8_t*)(_src) = 0xE9; *(uintptr_t*)((_src) + 1) = (uintptr_t)(_dst) - (uintptr_t)(_src) - 5
#endif
#define ENUM_OPS(e) \
inline e operator |(e a1, e a2) { \
return static_cast<e>(static_cast<int>(a1) | static_cast<int>(a2)); \
} \
\
inline e operator |= (e& a1, e a2) { \
return a1 = a1 | a2; \
} \
\
inline e operator &(e a1, e a2) { \
return static_cast<e>(static_cast<int>(a1)& static_cast<int>(a2)); \
} \
\
inline e operator &= (e& a1, e a2) { \
return a1 = a1 & a2; \
} \
\
inline e operator ~(e a1) { \
return static_cast<e>(~static_cast<int>(a1)); \
}
template<int s>
struct CompileTimeSizeOf;
// offsetof alternative
template<typename T, typename U>
constexpr size_t offsetOf( U T::*member )
{
return (size_t)&((T*)nullptr->*member);
}
template<typename T, typename U>
constexpr uint64_t fieldPtr( uint64_t base, U T::*member )
{
return base + offsetOf( member );
}
// CONTAINING_RECORD alternative
template<typename T, typename U>
constexpr uint64_t structBase( uint64_t ptr, U T::*member )
{
return ptr - offsetOf( member );
}
// Type-unsafe cast.
template<typename _Tgt, typename _Src>
inline _Tgt brutal_cast( const _Src& src )
{
static_assert(sizeof( _Tgt ) == sizeof( _Src ), "Operand size mismatch");
union _u { _Src s; _Tgt t; } u;
u.s = src;
return u.t;
}
// Align value
inline size_t Align( size_t val, size_t alignment )
{
return (val % alignment == 0) ? val : (val / alignment + 1) * alignment;
}
// Offset of 'LastStatus' field in TEB
#define LAST_STATUS_OFS (0x598 + 0x197 * WordSize)
typedef long NTSTATUS;
/// <summary>
/// Get last NT status
/// </summary>
/// <returns></returns>
inline NTSTATUS LastNtStatus()
{
return *(NTSTATUS*)((unsigned char*)NtCurrentTeb() + LAST_STATUS_OFS);
}
/// <summary>
/// Set last NT status
/// </summary>
/// <param name="status">The status.</param>
/// <returns></returns>
inline NTSTATUS SetLastNtStatus( NTSTATUS status )
{
return *(NTSTATUS*)((unsigned char*)NtCurrentTeb() + LAST_STATUS_OFS) = status;
}
#define SharedUserData32 ((KUSER_SHARED_DATA* const)0x7FFE0000)
| [
"sbaa2009@gmail.com"
] | sbaa2009@gmail.com |
e446d36ba4560754f3e41e0344b5f02107322a00 | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir7941/dir7942/dir8062/dir8063/dir8254/dir8444/dir8720/dir11129/file11194.cpp | c03e9ba6dddfaa57b4906f3758bb07b912348932 | [] | no_license | tgeng/HugeProject | 829c3bdfb7cbaf57727c41263212d4a67e3eb93d | 4488d3b765e8827636ce5e878baacdf388710ef2 | refs/heads/master | 2022-08-21T16:58:54.161627 | 2020-05-28T01:54:03 | 2020-05-28T01:54:03 | 267,468,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | #ifndef file11194
#error "macro file11194 must be defined"
#endif
static const char* file11194String = "file11194"; | [
"tgeng@google.com"
] | tgeng@google.com |
f2c010597c885f8cb2fe32f9deb55c02694adf9c | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/base/fs/hsm/rms/server/rmstmplt.cpp | 62897cec5dc69cf5f8de43b2ff45a87ba0d84cf1 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | WINDOWS-1252 | C++ | false | false | 802 | cpp | /*++
© 1998 Seagate Software, Inc. All rights reserved
Module Name:
RmsTmplt.cpp
Abstract:
Implementation of CRmsTemplate
Author:
Brian Dodd [brian] 15-Nov-1996
Revision History:
--*/
#include "stdafx.h"
#include "RmsTmplt.h"
/////////////////////////////////////////////////////////////////////////////
// CRmsTemplate Implementation
STDMETHODIMP
CRmsTemplate::InterfaceSupportsErrorInfo(
REFIID riid
)
/*++
Implements:
ISupportsErrorInfo::InterfaceSupportsErrorInfo
--*/
{
static const IID* arr[] =
{
&IID_IRmsTemplate,
};
for (int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
{
if (InlineIsEqualGUID(*arr[i],riid))
return S_OK;
}
return S_FALSE;
}
| [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
c57c0b52066de749609d22985349a72f4c53d6b9 | 345a2d403aaa52c373985bbcfdf4344cb9c73e0e | /Amazon/MinimumDelToAnagram.cpp | 95f70034993e5829ee7826ad28f2c3668f675720 | [] | no_license | srinivas-github/InterPrep | a4826908ad5aba350705e6cedd646809cf173cab | a2fb6342eec89057df364c47fcee74cb1581e417 | refs/heads/master | 2021-05-12T00:12:22.196015 | 2018-07-23T07:48:18 | 2018-07-23T07:48:18 | 117,530,420 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,104 | cpp | /**
* Given two strings in lowercase, the task is to make them anagram.
* The only allowed operation is to remove a character from any string.
* Find minimum number of characters to be deleted to make both the strings anagram?
* If two strings contains same data set in any order then strings are called Anagrams.
* Examples:
*
* Input : str1 = "bcadeh" str2 = "hea"
* Output: 3
* We need to remove b, c and d from str1.
*
* Input : str1 = "cddgk" str2 = "gcd"
* Output: 2
*
* Input : str1 = "bca" str2 = "acb"
* Output: 0
*/
#include <iostream>
#include <string>
const int CHARS = 26;
int remCountAnagrams(string str1, string str2)
{
char count1[CHARS] = {0}, count2[CHARS] = {0};
for (int i = 0; str1[i] != '\0'; i++)
count1[str1[i]]++;
for (int i = 0; str2[i] != '\0¨; i++)
count2[str2[i]]++;
int res = 0;
for(int i = 0; i < 26; i++)
res += abs(count1[i] - count2[i]);
return res;
}
int main()
{
string str1 = "bcadeh";
string str2 = "deh";
int count = remCountAnagrams(str1, str12);
cout<<count;
return 0;
}
| [
"srinivasreddy.j@gmail.com"
] | srinivasreddy.j@gmail.com |
79ecae4f8ff9a63224c344683e73d184765e7b9e | 8ab496b292ea94e5da3f8f49e591003f4cf9a1c9 | /Source/SimpleShooter/Gun.cpp | c7122af034c6845515e61146305254693d00d67a | [] | no_license | denzelnasol/simple-shooter | 33688289d12fcce79dae67ff80efd9b1b5be4cbd | 1b39d5eee9fc46a12c3b846070aacf5c588f691b | refs/heads/master | 2022-12-19T15:02:47.193436 | 2020-09-23T06:02:51 | 2020-09-23T06:02:51 | 293,909,871 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,318 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "Gun.h"
#include "Components/SkeletalMeshComponent.h"
#include "Kismet/GameplayStatics.h"
#include "DrawDebugHelpers.h"
// Sets default values
AGun::AGun()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
Root = CreateDefaultSubobject<USceneComponent>(TEXT("Root"));
SetRootComponent(Root);
Mesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("Mesh"));
Mesh->SetupAttachment(Root);
}
void AGun::PullTrigger()
{
UGameplayStatics::SpawnEmitterAttached(MuzzleFlash, Mesh, TEXT("MuzzleFlashSocket"));
UGameplayStatics::SpawnSoundAttached(MuzzleSound, Mesh, TEXT("MuzzleFlashSocket"));
FHitResult Hit;
FVector ShotDirection;
bool bSuccess = GunTrace(Hit, ShotDirection);
if (bSuccess)
{
UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), ImpactEffect, Hit.Location, ShotDirection.Rotation());
UGameplayStatics::PlaySoundAtLocation(GetWorld(), ImpactSound, Hit.Location);
AActor* HitActor = Hit.GetActor();
if (HitActor != nullptr)
{
FPointDamageEvent DamageEvent(Damage, Hit, ShotDirection, nullptr);
AController* OwnerController = GetOwnerController();
HitActor->TakeDamage(Damage, DamageEvent, OwnerController, this);
}
}
}
// Called when the game starts or when spawned
void AGun::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void AGun::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
bool AGun::GunTrace(FHitResult& Hit, FVector& ShotDirection)
{
AController* OwnerController = GetOwnerController();
if (OwnerController == nullptr)
{
return false;
}
FVector Location;
FRotator Rotation;
OwnerController->GetPlayerViewPoint(Location, Rotation);
ShotDirection = -Rotation.Vector();
FVector End = Location + Rotation.Vector() * MaxRange;
FCollisionQueryParams Params;
Params.AddIgnoredActor(this);
Params.AddIgnoredActor(GetOwner());
return GetWorld()->LineTraceSingleByChannel(Hit, Location, End, ECollisionChannel::ECC_GameTraceChannel1, Params);
}
AController* AGun::GetOwnerController() const
{
APawn* OwnerPawn = Cast<APawn>(GetOwner());
if (OwnerPawn == nullptr)
{
return nullptr;
}
return OwnerPawn->GetController();
}
| [
"denzelnasol@users.noreply.github.com"
] | denzelnasol@users.noreply.github.com |
545104f5fefd58f8c085987d361d80969758f6e7 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/26/ef5111fe0abf9f/main.cpp | 5134f412967b4dd57c5fb62b067275aa672f277c | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 61 | cpp | void test(int x)
{
return test(3);
}
int main() {} | [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
69df9ec7e8a759a23927c69cedd2ca008f5f44a5 | 6be8485806bd658b2deaf00ea03a79201558fa8d | /Fase4/Generator/figures.h | f1ea1885ac3e98076e995084b30d45be5f0af503 | [] | no_license | joaop21/ComputerGraphics_Assignment | 59d70323806c957cac475e0f7a7f48bbdfd9deef | a676c9d4d91368f6d471f8354e30497bc7f5bbf1 | refs/heads/master | 2021-10-22T11:47:39.403073 | 2021-10-13T11:33:03 | 2021-10-13T11:33:03 | 171,955,068 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,929 | h | #ifndef FIGURES_H
#define FIGURES_H
#endif
#include <string>
namespace figures{
/**
* @brief classe que define intancias de Ponto
*/
class Point{
private:
float x,y,z;
public:
Point(){
x = 0;
y = 0;
z = 0;
}
Point(float xn, float yn, float zn){
x = xn;
y = yn;
z = zn;
}
float getX(){return x;}
float getY(){return y;}
float getZ(){return z;}
void setX(float num){x = num;}
void setY(float num){y = num;}
void setZ(float num){z = num;}
};
/**
* @brief classe que define intancias dum Ponto de textura
*/
class TexturePoint{
private:
float x,y;
public:
TexturePoint(){ x = 0; y = 0;}
TexturePoint(float a, float b){ x = a ; y = b;}
float getX(){return x;}
float getY(){return y;}
void setX(float value){x = value;}
void setY(float value){y = value;}
};
/**
* @brief Função que gera o pontos para a realização dos devidos triângulos, e
* conseguentemente gravação em ficheiro.
*
* @param side - parâmetro que é o tamanho do lado do plano.
* @param file_name - parâmetro que é o nome do ficheiro onde se devem gravar os
* pontos e triangulos gerados.
*
* @returns Integer que dita se a geração foi um sucesso ou não
*/
int generatePlane(float side, std::string file_name);
/**
* @brief Função que gera o pontos para a realização dos devidos triângulos, e
* conseguentemente gravação em ficheiro.
*
* @param xdim - parâmetro que é o tamanho da dimensão X.
* @param ydim - parâmetro que é o tamanho da dimensão Y.
* @param zdim - parâmetro que é o tamanho da dimensão Z.
* @param div - parâmetro que é o números de divisões na box.
* @param file_name - parâmetro que é o nome do ficheiro onde se devem gravar os
* pontos e triangulos gerados.
*
* @returns Integer que dita se a geração foi um sucesso ou não
*/
int generateBox(float xdim, float ydim, float zdim, int div, std::string file_name);
/**
* @brief Função que gera o pontos para a realização dos devidos triângulos, e
* conseguentemente gravação em ficheiro.
*
* @param r - parâmetro que é o raio da esfera
* @param slices - parâmetro que é o numero de fatias da esfera
* @param stacks - parâmetro que é o número de partições de cada slice
* @param file_name - parâmetro que é o nome do ficheiro onde se devem gravar os
* pontos e triangulos gerados.
*
* Para que o algoritmo ficasse mais percetível e mais curto usamos abreviações
* nas variáveis, tal correspondência é feita de seguida:
* - r : radius
* - sls : SliceStep
* - sts : StackStep
* - rs : raio da stack atual
* - rsn : raio da stack seguinte
*
* @returns Integer que dita se a geração foi um sucesso ou não
*/
int generateSphere(float r, int slices, int stacks, std::string file_name);
/**
* @brief Função que gera o pontos para a realização dos devidos triângulos, e
* conseguentemente gravação em ficheiro.
*
* @param bottom_radius - parâmetro que é o raio da base do cone.
* @param height - parâmetro que é o tamanho do cone.
* @param slices - parâmetro que é o número de fatias em que o cone se deve dividir.
* @param stacks - parâmetro que é o números de divisões de cada slice.
* @param file_name - parâmetro que é o nome do ficheiro onde se devem gravar os
* pontos e triangulos gerados.
*
* @returns Integer que dita se a geração foi um sucesso ou não
*/
int generateCone(float bottom_radius, float height, int slices, int stacks, std::string file_name);
/**
* @brief Função que gera o pontos para a realização dos devidos triângulos, e
* conseguentemente gravação em ficheiro.
*
* @param inner_radius - parâmetro que é o raio de cada anel do torus.
* @param inner_radius - parâmetro que é a distância desde o centro do torus até à figura.
* @param nsides - parâmetro que é o número de lados de cada anel da figura.
* @param nrings - parâmetro que é o números de anéis da figura.
* @param file_name - parâmetro que é o nome do ficheiro onde se devem gravar os
* pontos e triangulos gerados.
*
* @returns Integer que dita se a geração foi um sucesso ou não
*/
int generateTorus(float innerRadius, float outerRadius, int nsides, int nrings, std::string file_name);
/**
* @brief Função que gera um ficheiro XML que contém todas as coordenadas dos
* asteróides a que foram gerados
*
* @param num_asteroids - parâmetro que é o número de asteróides a serem gerados.
* @param min_radius - parâmetro que é a distância mínima dos asteróides ao sol.
* @param mas_radius - parâmetro que é a distância máxima dos asteróides ao sol.
* @param file_name - parâmetro que é o nome do ficheiro onde se deve gravar tudo
* o que foi gerado anteriormente.
*
* @returns Integer que dita se a geração foi um sucesso ou não
*/
int generateAsteroids(int num_asteroids, int min_radius, int max_radius, std::string file_name);
int generateBezierSurface(std::string patch_file, int tesselation, std::string file_name);
/**
* @brief Função guarda em ficheiro todos os pontos passados como parâmetro.
*
* @param points - Parâmetro que é um vector que contém todos os pontos a serem
* gravados em ficheiro.
* @param file_name - parâmetro que é o nome do ficheiro onde se devem gravar os
* pontos e triangulos gerados.
*
* @returns Integer que dita se a geração foi um sucesso ou não
*/
int write_in_file(std::vector<Point> points, std::string file_name);
/**
* @brief Função guarda em ficheiro todos os pontos passados como parâmetro.
*
* @param points - Parâmetro que é um vector que contém todos os pontos a serem
* gravados em ficheiro.
* @param normals - Parâmetro que é um vector que contém todos as normais a serem
* gravados em ficheiro.
* @param textures - Parâmetro que é um vector que contém todos as texturas a serem
* gravados em ficheiro.
* @param file_name - parâmetro que é o nome do ficheiro onde se devem gravar os
* pontos e triangulos gerados.
*
* @returns Integer que dita se a geração foi um sucesso ou não
*/
int write_in_file(std::vector<Point> points, std::vector<Point> normals, std::vector<TexturePoint> textures, std::string file_name);
}
| [
"jpsilva9898@gmail.com"
] | jpsilva9898@gmail.com |
63c272baf8fc2f3d465f4707ce3e734c07284efd | 1686fa830ebabd71e455372dd5335b5e60c027d4 | /Tutorial 34_Billboarding/Engine/inputclass.h | 5b703d5026c82a0c4f2cfe0ffbb59493b52091d1 | [] | no_license | matt77hias/RasterTek | ec7892d8871641cf434d3ec1c2c6dbb688952136 | f65a3eb7bfe4c2419dbece9fce8adebd92c580f9 | refs/heads/master | 2023-07-23T04:02:42.010575 | 2023-07-10T07:05:12 | 2023-07-10T07:05:12 | 93,774,234 | 125 | 36 | null | 2023-07-10T07:35:04 | 2017-06-08T17:18:25 | C++ | UTF-8 | C++ | false | false | 1,335 | h | ////////////////////////////////////////////////////////////////////////////////
// Filename: inputclass.h
////////////////////////////////////////////////////////////////////////////////
#ifndef _INPUTCLASS_H_
#define _INPUTCLASS_H_
///////////////////////////////
// PRE-PROCESSING DIRECTIVES //
///////////////////////////////
#define DIRECTINPUT_VERSION 0x0800
/////////////
// LINKING //
/////////////
#pragma comment(lib, "dinput8.lib")
#pragma comment(lib, "dxguid.lib")
//////////////
// INCLUDES //
//////////////
#include <dinput.h>
////////////////////////////////////////////////////////////////////////////////
// Class name: InputClass
////////////////////////////////////////////////////////////////////////////////
class InputClass
{
public:
InputClass();
InputClass(const InputClass&);
~InputClass();
bool Initialize(HINSTANCE, HWND, int, int);
void Shutdown();
bool Frame();
bool IsEscapePressed();
void GetMouseLocation(int&, int&);
bool IsLeftPressed();
bool IsRightPressed();
private:
bool ReadKeyboard();
bool ReadMouse();
void ProcessInput();
private:
IDirectInput8* m_directInput;
IDirectInputDevice8* m_keyboard;
IDirectInputDevice8* m_mouse;
unsigned char m_keyboardState[256];
DIMOUSESTATE m_mouseState;
int m_screenWidth, m_screenHeight;
int m_mouseX, m_mouseY;
};
#endif | [
"matthias.moulin@gmail.com"
] | matthias.moulin@gmail.com |
c00cd9bec3a3d80b9e8d486ba5b30ac2eb6ffb85 | 15497b667b7826f54b22b909e0a38b3704fd7b76 | /cpp/003_longest_substring.cpp | 2a1162b98482f1f2e4cc1ec24f13ffeb5a2073cb | [] | no_license | wanggchongg/leetcode | 195bbc4645fd90f8a0e3861881186571d7532510 | 00cdc0b5c889abe152bae0cf40a41d3c14d05fdc | refs/heads/master | 2022-04-26T16:05:55.062972 | 2022-03-13T08:43:32 | 2022-03-13T08:43:32 | 33,589,144 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 627 | cpp | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
int lengthOfLongestSubstring(char *s) {
int len = strlen(s);
if(len <= 1)
return len;
int map[127];
memset(map, -1, sizeof(int)*127);
int max = 0, temp = 0;
int index = -1, i;
for(i=0; i<len; i++)
{
if(map[s[i]]>index)
{
index = map[s[i]];
temp = i-index;
}
else
temp++;
if(max<temp)
max = temp;
map[s[i]] = i;
printf("temp=%d,max=%d\n", temp, max);
}
return max;
}
int main()
{
char s[] = "asjrgapa";
int max;
max = lengthOfLongestSubstring(s);
printf("max = %d\n", max);
return 0;
}
| [
"wangchonggg@163.com"
] | wangchonggg@163.com |
ed5e8e37a6b8c4815c31565166bbde68c2f31dfc | e9d301a03d44e2d44212aa92498d465e373a5052 | /MSToolkit/src/mzIMLTools/CEnzymeName.cpp | 7893e5d079aa713852ea1ecf24bc192cc5217d8a | [
"Apache-2.0"
] | permissive | UWPR/Comet | 69190c4b24f41998c30dfb9dabe4edf2129621ce | a8541e8bfac5005e85a05a8ccc9cc6d0e7b485a0 | refs/heads/master | 2023-08-31T15:23:30.132265 | 2023-08-29T20:01:40 | 2023-08-29T20:01:40 | 407,622,951 | 31 | 10 | null | 2023-09-08T19:04:30 | 2021-09-17T17:15:42 | C | UTF-8 | C++ | false | false | 1,886 | cpp | /*
Copyright 2020, Michael R. Hoopmann, Institute for Systems Biology
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 "CEnzymeName.h"
using namespace std;
//CEnzymeName::CEnzymeName(){
// cvParam=new vector<sCvParam>;
// sCvParam c;
// cvParam->push_back(c);
//
// sUserParam u;
// userParam=new vector<sUserParam>;
// userParam->push_back(u);
//}
//
//CEnzymeName::CEnzymeName(const CEnzymeName& c){
// cvParam=new vector<sCvParam>(*c.cvParam);
// userParam=new vector<sUserParam>(*c.userParam);
//}
//
//CEnzymeName::~CEnzymeName(){
// delete cvParam;
// delete userParam;
//}
//
////Operators
//CEnzymeName& CEnzymeName::operator=(const CEnzymeName& c){
// if(this!=&c){
// delete cvParam;
// delete userParam;
// cvParam = new vector<sCvParam>(*c.cvParam);
// userParam = new vector<sUserParam>(*c.userParam);
// }
// return *this;
//}
//Functions
void CEnzymeName::writeOut(FILE* f, int tabs){
int i,j;
for (i = 0; i<tabs; i++) fprintf(f, " ");
fprintf(f, "<EnzymeName>\n");
if(tabs>-1){
for (j = 0; j<cvParam.size(); j++) cvParam[j].writeOut(f, tabs + 1);
for (j = 0; j<userParam.size(); j++) userParam[j].writeOut(f, tabs + 1);
}else {
for(j = 0; j<cvParam.size(); j++) cvParam[j].writeOut(f);
for (j = 0; j<userParam.size(); j++) userParam[j].writeOut(f);
}
for (i = 0; i<tabs; i++) fprintf(f, " ");
fprintf(f, "</EnzymeName>\n");
}
| [
"jke000@gmail.com"
] | jke000@gmail.com |
e99b86c6c3ea5f39014a0fccb5a95a4106a07550 | 36f052ee6b4799cba74b03f61f477b7f433626d4 | /main.cpp | 5663cfdc6c194f8a1e79e050705e63d017a1ed7d | [] | no_license | swaroopba/Music-Player | 5870d76eba26547904228a5e9b964ce0e4a35db5 | 79abba7174a253f5410d9c235a80028dd9b229ad | refs/heads/main | 2023-06-07T03:18:00.767688 | 2021-07-04T16:02:20 | 2021-07-04T16:02:20 | 382,890,905 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,241 | cpp | #include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "mediahandler.h"
#include <QQmlContext>
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
qDebug()<<"Command arg count->"<<argc;
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
QSharedPointer<MediaHandler> m_mediaHandlerPtr = QSharedPointer<MediaHandler>(new MediaHandler);
engine.rootContext()->setContextProperty("MediaHandler", m_mediaHandlerPtr.data() );
engine.rootContext()->setContextProperty("ImageProvider", m_mediaHandlerPtr->getImageProvider());
engine.rootContext()->setContextProperty("FileModel", m_mediaHandlerPtr->getModel());
engine.addImageProvider("imageprovider", m_mediaHandlerPtr->getImageProvider());
//m_mediaHandlerPtr->populateModel("../../MediaPlayer/Audio");
engine.load(url);
return app.exec();
}
| [
"swaroop.ba@videojet.com"
] | swaroop.ba@videojet.com |
a6b01dc3ad69de302c8cac2c56258fc3f93013d7 | b33f4549a93baca6728efd3ab7d5bf7f1edf1d8e | /src/P12_Numerical_Integer_Power.h | 769b40e47e9a95c3d77077a64d184b37925c683c | [] | no_license | guyongpu/SwordOffer | de8b5c952036c9030262011ed4b96cd7da9a41bc | 100d91dcccd510fb6146ff4d71edeed0b9b77632 | refs/heads/master | 2020-07-23T05:23:12.640702 | 2019-09-28T14:13:38 | 2019-09-28T14:13:38 | 207,456,494 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 344 | h | //
// Created by yongpu on 2019/9/11.
//
#ifndef SWORDOFFER_P12_NUMERICAL_INTEGER_POWER_H
#define SWORDOFFER_P12_NUMERICAL_INTEGER_POWER_H
#include <iostream>
using namespace std;
class P12_Numerical_Integer_Power {
public:
double Power(double base, int exponent);
int test();
};
#endif //SWORDOFFER_P12_NUMERICAL_INTEGER_POWER_H
| [
"gyphust@qq.com"
] | gyphust@qq.com |
dcb00c5a6e6fbcbd991acaba699bff1fa81832d3 | 07074962be026c67519a0ccfb3d48bd95ede38ed | /Editors/ce5goodsbarcodelabelview.h | a487298559610897450fb9e98fea545dacbad75c | [] | no_license | End1-1/Cafe5 | 2fa65c62f395c186e2204f3fb941a2f93fd3a653 | ba2b695c627cf59260a3ac1134927198c004fe53 | refs/heads/master | 2023-08-17T02:39:29.224396 | 2023-08-14T06:37:55 | 2023-08-14T06:37:55 | 151,380,276 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 294 | h | #ifndef CE5GOODSBARCODELABELVIEW_H
#define CE5GOODSBARCODELABELVIEW_H
#include <QWidget>
class CE5GoodsBarcodeLabelView : public QWidget
{
Q_OBJECT
public:
explicit CE5GoodsBarcodeLabelView(QWidget *parent = nullptr);
signals:
public slots:
};
#endif // CE5GOODSBARCODELABELVIEW_H
| [
"end1_1@yahoo.com"
] | end1_1@yahoo.com |
04d9a8a375bef4db7db309223cbfc35b225e57dd | 74e74bb94cb6065eebccc52f4dcf63d4f09af4f7 | /old/Library.cpp | fcc7ef75a23ea132fc1c25b5875eda1e55c6e658 | [] | no_license | kssilveira/topcoder | 39f247e355285a29c3a859428830f40e06933e9a | 8acf4e459c0637bb98081f7469197d0a4b5cd9bf | refs/heads/master | 2021-01-22T14:38:34.267868 | 2012-04-02T01:41:59 | 2012-04-02T01:41:59 | 3,001,657 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,111 | cpp | #include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <cfloat>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <streambuf>
#include <string>
#include <utility>
#include <vector>
#define rep(i, n) repb(i, 0, n)
#define repb(i, b, n) repbc(i, b, n, <)
#define repe(i, n) repbe(i, 0, n)
#define repbe(i, b, n) repbc(i, b, n, <=)
#define repbc(i, b, n, c) for(int i = b; i c n; i++)
using namespace std;
class Library {
public:
int documentAccess(vector <string> records, vector <string> userGroups, vector <string> roomRights) {
set<string> res;
set<string> g, r;
rep(i, userGroups.size()) {
g.insert(userGroups[i]);
}
rep(i, roomRights.size()) {
r.insert(roomRights[i]);
}
rep(i, records.size()) {
char name[1000], room[1000], group[1000];
sscanf(records[i].c_str(), "%s %s %s", name, room, group);
if(g.count(group) && r.count(room)) {
res.insert(name);
}
}
return res.size();
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"diary computers editor","fairytale gardening editor","comix cars author","comix cars librarian"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"employee","editor","author"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arr2[] = {"history","cars","computers"}; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 2; verify_case(0, Arg3, documentAccess(Arg0, Arg1, Arg2)); }
void test_case_1() { string Arr0[] = {"diary computers editor","fairytale gardening editor","comix cars author","comix cars librarian"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"employee","editor","author","librarian"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arr2[] = {"history","cars","computers"}; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 2; verify_case(1, Arg3, documentAccess(Arg0, Arg1, Arg2)); }
void test_case_2() { string Arr0[] = {"diary computers editor","fairytale gardening editor","comix cars author","comix cars librarian"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"employee","editor","author","librarian"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arr2[] = {}; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 0; verify_case(2, Arg3, documentAccess(Arg0, Arg1, Arg2)); }
void test_case_3() { string Arr0[] = {"a b c","a b d","b b c","b b d","e c d","e c b","e c c","t d e"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"c","d","x"}; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arr2[] = {"a","b","c"}; vector <string> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 3; verify_case(3, Arg3, documentAccess(Arg0, Arg1, Arg2)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
Library ___test;
___test.run_test(-1);
}
// END CUT HERE
| [
"silveira.kaue@gmail.com"
] | silveira.kaue@gmail.com |
aabc2206e21ef235f52a8600d623f217244b2b11 | e0d98a746319928696ed563347fba8702c825116 | /sdk/structs.hpp | 9929dae367f23106c65a1199ebe810b5869295ec | [] | no_license | FlashSup/saphire | 09927463b1095b67820ee4bf087d477750ef132a | fb434daedc68275bc27241954e46bf7ae656b488 | refs/heads/master | 2023-08-14T03:05:42.058262 | 2021-09-11T18:29:32 | 2021-09-11T18:29:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 55,072 | hpp | #pragma once
#include "..\includes.hpp"
#include "interfaces\IClientEntity.hpp"
#include "misc\EHandle.hpp"
#include "misc\UtlVector.hpp"
#include "math\QAngle.hpp"
#include "..\utils\netmanager.hpp"
#include "misc\CBoneAccessor.hpp"
#include "..\cheats\misc\fakelag.h"
#include "..\sdk\misc\Recv.hpp"
#define min(a, b) (((a) < (b)) ? (a) : (b))
#define max(a, b) (((a) > (b)) ? (a) : (b))
#define TIME_TO_TICKS(t) ((int)(0.5f + (float)(t) / m_globals()->m_intervalpertick))
#define TIME_TO_TICKS2(t) ((int)(1.f + (float)(t) / m_globals()->m_intervalpertick))
#define TICKS_TO_TIME(t) (m_globals()->m_intervalpertick * (t))
#define NETVAR(type, name, table, netvar) \
type& name##() const { \
static int _##name = netvars::get().get_offset(table, netvar); \
return *(type*)((uintptr_t)this + _##name); \
}
#define PNETVAR(type, name, table, netvar) \
type* name##() const { \
static int _##name = netvars::get().get_offset(table, netvar); \
return (type*)((uintptr_t)this + _##name); \
}
#define OFFSET(type, name, offset)\
type &name##() const\
{\
return *(type*)(uintptr_t(this) + offset);\
}
class player_t;
struct datamap_t;
enum CSWeaponType
{
WEAPONTYPE_KNIFE = 0,
WEAPONTYPE_PISTOL,
WEAPONTYPE_SUBMACHINEGUN,
WEAPONTYPE_RIFLE,
WEAPONTYPE_SHOTGUN,
WEAPONTYPE_SNIPER_RIFLE,
WEAPONTYPE_MACHINEGUN,
WEAPONTYPE_C4,
WEAPONTYPE_PLACEHOLDER,
WEAPONTYPE_GRENADE,
WEAPONTYPE_UNKNOWN
};
class VarMapEntry_t
{
public:
unsigned short type;
unsigned short m_bNeedsToInterpolate;
void* data;
void* watcher;
};
struct VarMapping_t
{
VarMapping_t()
{
m_Entries = nullptr;
m_nInterpolatedEntries = 0;
m_lastInterpolationTime = 0.0f;
}
VarMapEntry_t* m_Entries;
int m_nInterpolatedEntries;
float m_lastInterpolationTime;
};
struct client_hit_verify_t
{
Vector position;
float time;
float expires;
};
class AnimationLayer;
class c_baseplayeranimationstate;
class entity_t;
class clientanimating_t;
class weapon_info_t
{
public:
char pad_0000[4]; //0x0000
char* ConsoleName; //0x0004
char pad_0008[12]; //0x0008
int iMaxClip1; //0x0014
char pad_0018[12]; //0x0018
int iMaxClip2; //0x0024
char pad_0028[4]; //0x0028
char* szWorldModel; //0x002C
char* szViewModel; //0x0030
char* szDropedModel; //0x0034
char pad_0038[4]; //0x0038
char* N00000984; //0x003C
char pad_0040[56]; //0x0040
char* szEmptySound; //0x0078
char pad_007C[4]; //0x007C
char* szBulletType; //0x0080
char pad_0084[4]; //0x0084
char* szHudName; //0x0088
char* szWeaponName; //0x008C
char pad_0090[60]; //0x0090
int WeaponType; //0x00CC
int iWeaponPrice; //0x00D0
int iKillAward; //0x00D4
char* szAnimationPrefex; //0x00D8
float flCycleTime; //0x00DC
float flCycleTimeAlt; //0x00E0
float flTimeToIdle; //0x00E4
float flIdleInterval; //0x00E8
bool bFullAuto; //0x00EC
char pad_00ED[3]; //0x00ED
int iDamage; //0x00F0
float flArmorRatio; //0x00F4
int iBullets; //0x00F8
float flPenetration; //0x00FC
float flFlinchVelocityModifierLarge; //0x0100
float flFlinchVelocityModifierSmall; //0x0104
float flRange; //0x0108
float flRangeModifier; //0x010C
char pad_0110[28]; //0x0110
int iCrosshairMinDistance; //0x012C
float flMaxPlayerSpeed; //0x0130
float flMaxPlayerSpeedAlt; //0x0134
char pad_0138[4]; //0x0138
float flSpread; //0x013C
float flSpreadAlt; //0x0140
float flInaccuracyCrouch; //0x0144
float flInaccuracyCrouchAlt; //0x0148
float flInaccuracyStand; //0x014C
float flInaccuracyStandAlt; //0x0150
float flInaccuracyJumpIntial; //0x0154
float flInaccaurcyJumpApex;
float flInaccuracyJump; //0x0158
float flInaccuracyJumpAlt; //0x015C
float flInaccuracyLand; //0x0160
float flInaccuracyLandAlt; //0x0164
float flInaccuracyLadder; //0x0168
float flInaccuracyLadderAlt; //0x016C
float flInaccuracyFire; //0x0170
float flInaccuracyFireAlt; //0x0174
float flInaccuracyMove; //0x0178
float flInaccuracyMoveAlt; //0x017C
float flInaccuracyReload; //0x0180
int iRecoilSeed; //0x0184
float flRecoilAngle; //0x0188
float flRecoilAngleAlt; //0x018C
float flRecoilVariance; //0x0190
float flRecoilAngleVarianceAlt; //0x0194
float flRecoilMagnitude; //0x0198
float flRecoilMagnitudeAlt; //0x019C
float flRecoilMagnatiudeVeriance; //0x01A0
float flRecoilMagnatiudeVerianceAlt; //0x01A4
float flRecoveryTimeCrouch; //0x01A8
float flRecoveryTimeStand; //0x01AC
float flRecoveryTimeCrouchFinal; //0x01B0
float flRecoveryTimeStandFinal; //0x01B4
int iRecoveryTransititionStartBullet; //0x01B8
int iRecoveryTransititionEndBullet; //0x01BC
bool bUnzoomAfterShot; //0x01C0
char pad_01C1[31]; //0x01C1
char* szWeaponClass; //0x01E0
char pad_01E4[56]; //0x01E4
float flInaccuracyPitchShift; //0x021C
float flInaccuracySoundThreshold; //0x0220
float flBotAudibleRange; //0x0224
char pad_0228[12]; //0x0228
bool bHasBurstMode; //0x0234
};
struct NoticeText_t
{
wchar_t text[512];
int unk0; // 0x400
float unk1; // 0x404
float unk2; // 0x408
int unk3; // 0x40C
float time; // 0x410
int unk4; // 0x414
float fade; // 0x418
int unk5; // 0x41C
};
struct KillFeed_t
{
char pad[0x7C];
CUtlVector <NoticeText_t> notices;
};
//PoseParam_t
enum PoseParam_t {
STRAFE_YAW,
STAND,
LEAN_YAW,
SPEED,
LADDER_YAW,
LADDER_SPEED,
JUMP_FALL,
MOVE_YAW,
MOVE_BLEND_CROUCH,
MOVE_BLEND_WALK,
MOVE_BLEND_RUN,
BODY_YAW,
BODY_PITCH,
AIM_BLEND_STAND_IDLE,
AIM_BLEND_STAND_WALK,
AIM_BLEND_STAND_RUN,
AIM_BLEND_COURCH_IDLE,
AIM_BLEND_CROUCH_WALK,
DEATH_YAW
};
class entity_t : public IClientEntity
{
public:
NETVAR(int, body, crypt_str("CBaseAnimating"), crypt_str("m_nBody"));
NETVAR(int, m_nModelIndex, crypt_str("CBaseEntity"), crypt_str("m_nModelIndex"));
NETVAR(int, m_iTeamNum, crypt_str("CBaseEntity"), crypt_str("m_iTeamNum"));
NETVAR(Vector, m_vecOrigin, crypt_str("CBaseEntity"), crypt_str("m_vecOrigin"));
NETVAR(CHandle <player_t>, m_hOwnerEntity, crypt_str("CBaseEntity"), crypt_str("m_hOwnerEntity"));
NETVAR(int, m_CollisionGroup, crypt_str("CBaseEntity"), crypt_str("m_CollisionGroup"));
NETVAR(int, m_nSequence, crypt_str("CBaseAnimating"), crypt_str("m_nSequence"));
void set_m_bUseCustomBloomScale(byte value)
{
*reinterpret_cast<byte*>(uintptr_t(this) + (int)netvars::get().get_offset(crypt_str("CEnvTonemapController"), crypt_str("m_bUseCustomBloomScale"))) = value;
}
void set_m_flCustomBloomScale(float value)
{
*reinterpret_cast<float*>(uintptr_t(this) + (int)netvars::get().get_offset(crypt_str("CEnvTonemapController"), crypt_str("m_flCustomBloomScale"))) = value;
}
void set_m_bUseCustomAutoExposureMin(byte value)
{
*reinterpret_cast<byte*>(uintptr_t(this) + (int)netvars::get().get_offset(crypt_str("CEnvTonemapController"), crypt_str("m_bUseCustomAutoExposureMin"))) = value;
}
void set_m_flCustomAutoExposureMin(float value)
{
*reinterpret_cast<float*>(uintptr_t(this) + (int)netvars::get().get_offset(crypt_str("CEnvTonemapController"), crypt_str("m_flCustomAutoExposureMin"))) = value;
}
void set_m_bUseCustomAutoExposureMax(byte value)
{
*reinterpret_cast<byte*>(uintptr_t(this) + (int)netvars::get().get_offset(crypt_str("CEnvTonemapController"), crypt_str("m_bUseCustomAutoExposureMax"))) = value;
}
void set_m_flCustomAutoExposureMax(float value)
{
*reinterpret_cast<float*>(uintptr_t(this) + (int)netvars::get().get_offset(crypt_str("CEnvTonemapController"), crypt_str("m_flCustomAutoExposureMax"))) = value;
}
const matrix3x4_t& m_rgflCoordinateFrame()
{
static auto _m_rgflCoordinateFrame = netvars::get().get_offset(crypt_str("CBaseEntity"), crypt_str("m_CollisionGroup")) - 0x30;
return *(matrix3x4_t*)((uintptr_t)this + _m_rgflCoordinateFrame);
}
int GetPropInt(std::string& table, std::string& var)
{
static auto offset = netvars::get().get_offset(table.c_str(), var.c_str());
int val = *(int*)(uintptr_t(this) + (int)offset);
return val;
}
float GetPropFloat(std::string& table, std::string& var)
{
static auto offset = netvars::get().get_offset(table.c_str(), var.c_str());
float val = *(float*)(uintptr_t(this) + (int)offset);
return val;
}
bool GetPropBool(std::string& table, std::string& var)
{
static auto offset = netvars::get().get_offset(table.c_str(), var.c_str());
bool val = *(bool*)(uintptr_t(this) + (int)offset);
return val;
}
std::string GetPropString(std::string& table, std::string& var)
{
static auto offset = netvars::get().get_offset(table.c_str(), var.c_str());
char* val = (char*)(uintptr_t(this) + (int)offset);
return std::string(val);
}
void SetPropInt(std::string& table, std::string& var, int val)
{
*reinterpret_cast<int*>(uintptr_t(this) + (int)netvars::get().get_offset(table.c_str(), var.c_str())) = val;
}
void SetPropFloat(std::string& table, std::string& var, float val)
{
*reinterpret_cast<float*>(uintptr_t(this) + (int)netvars::get().get_offset(table.c_str(), var.c_str())) = val;
}
void SetPropBool(std::string& table, std::string& var, bool val)
{
*reinterpret_cast<float*>(uintptr_t(this) + (int)netvars::get().get_offset(table.c_str(), var.c_str())) = val;
}
datamap_t* GetPredDescMap();
std::array <float, 24>& m_flPoseParameter();
bool is_player();
void set_model_index(int index);
void set_abs_angles(const Vector& angle);
void set_abs_origin(const Vector& origin);
};
class attributableitem_t : public entity_t
{
public:
NETVAR(int, m_iItemDefinitionIndex, crypt_str("CBaseAttributableItem"), crypt_str("m_iItemDefinitionIndex"));
NETVAR(int, m_nFallbackStatTrak, crypt_str("CBaseAttributableItem"), crypt_str("m_nFallbackStatTrak"));
NETVAR(int, m_nFallbackPaintKit, crypt_str("CBaseAttributableItem"), crypt_str("m_nFallbackPaintKit"));
NETVAR(int, m_nFallbackSeed, crypt_str("CBaseAttributableItem"), crypt_str("m_nFallbackSeed"));
NETVAR(float, m_flFallbackWear, crypt_str("CBaseAttributableItem"), crypt_str("m_flFallbackWear"));
NETVAR(int, m_iAccountID, crypt_str("CBaseAttributableItem"), crypt_str("m_iAccountID"));
NETVAR(int, m_iItemIDHigh, crypt_str("CBaseAttributableItem"), crypt_str("m_iItemIDHigh"));
PNETVAR(char, m_szCustomName, crypt_str("CBaseAttributableItem"), crypt_str("m_szCustomName"));
NETVAR(int, m_OriginalOwnerXuidLow, crypt_str("CBaseAttributableItem"), crypt_str("m_OriginalOwnerXuidLow"));
NETVAR(int, m_OriginalOwnerXuidHigh, crypt_str("CBaseAttributableItem"), crypt_str("m_OriginalOwnerXuidHigh"));
NETVAR(int, m_iEntityQuality, crypt_str("CBaseAttributableItem"), crypt_str("m_iEntityQuality"));
};
class weapon_t : public attributableitem_t
{
public:
NETVAR(float, m_flNextPrimaryAttack, crypt_str("CBaseCombatWeapon"), crypt_str("m_flNextPrimaryAttack"));
NETVAR(float, m_flNextSecondaryAttack, crypt_str("CBaseCombatWeapon"), crypt_str("m_flNextSecondaryAttack"));
NETVAR(bool, initialized, crypt_str("CBaseAttributableItem"), crypt_str("m_bInitialized"));
NETVAR(int, weapon, crypt_str("CBaseViewModel"), crypt_str("m_hWeapon"));
NETVAR(short, m_iItemDefinitionIndex, crypt_str("CBaseCombatWeapon"), crypt_str("m_iItemDefinitionIndex"));
NETVAR(int, m_iClip1, crypt_str("CBaseCombatWeapon"), crypt_str("m_iClip1"));
NETVAR(int, m_iViewModelIndex, crypt_str("CBaseCombatWeapon"), crypt_str("m_iViewModelIndex"));
NETVAR(int, m_iWorldModelIndex, crypt_str("CBaseCombatWeapon"), crypt_str("m_iWorldModelIndex"));
NETVAR(float, m_fAccuracyPenalty, crypt_str("CWeaponCSBase"), crypt_str("m_fAccuracyPenalty"));
NETVAR(int, m_zoomLevel, crypt_str("CWeaponCSBaseGun"), crypt_str("m_zoomLevel"));
NETVAR(bool, m_bPinPulled, crypt_str("CBaseCSGrenade"), crypt_str("m_bPinPulled"));
NETVAR(float, m_fThrowTime, crypt_str("CBaseCSGrenade"), crypt_str("m_fThrowTime"));
NETVAR(float, m_flPostponeFireReadyTime, crypt_str("CWeaponCSBase"), crypt_str("m_flPostponeFireReadyTime"));
NETVAR(float, m_fLastShotTime, crypt_str("CWeaponCSBase"), crypt_str("m_fLastShotTime"));
NETVAR(float, m_flRecoilSeed, crypt_str("CWeaponCSBase"), crypt_str("m_flRecoilIndex"));
NETVAR(int, m_weaponMode, crypt_str("CWeaponCSBase"), crypt_str("m_weaponMode"));
NETVAR(CHandle <weapon_t>, m_hWeaponWorldModel, crypt_str("CBaseCombatWeapon"), crypt_str("m_hWeaponWorldModel"));
bool IsGun();
weapon_info_t* get_csweapon_info();
bool is_empty();
bool can_fire(bool check_revolver);
int get_weapon_group(bool rage);
bool is_rifle();
bool is_smg();
bool is_shotgun();
bool is_pistol();
bool is_sniper();
bool is_autosniper();
bool is_singlesniper();
bool is_grenade();
bool is_knife();
bool is_non_aim();
bool can_double_tap();
int get_max_tickbase_shift();
float get_spread_virtual();
float get_inaccuracy_virtual();
float get_inaccuracy();
float get_spread();
void update_accuracy_penality();
char* get_icon();
std::string get_name();
};
class viewmodel_t;
class player_t : public entity_t
{
public:
NETVAR(bool, m_bClientSideAnimation, crypt_str("CBaseAnimating"), crypt_str("m_bClientSideAnimation"));
NETVAR(bool, m_bHasDefuser, crypt_str("CCSPlayer"), crypt_str("m_bHasDefuser"));
NETVAR(bool, m_bGunGameImmunity, crypt_str("CCSPlayer"), crypt_str("m_bGunGameImmunity"));
NETVAR(int, m_iShotsFired, crypt_str("CCSPlayer"), crypt_str("m_iShotsFired"));
NETVAR(Vector, m_angEyeAngles, crypt_str("CCSPlayer"), crypt_str("m_angEyeAngles[0]"));
NETVAR(Vector, m_angRotation, crypt_str("CBaseEntity"), crypt_str("m_angRotation"));
NETVAR(int, m_ArmorValue, crypt_str("CCSPlayer"), crypt_str("m_ArmorValue"));
NETVAR(int, m_iAccount, crypt_str("CCSPlayer"), crypt_str("m_iAccount"));
NETVAR(bool, m_bHasHelmet, crypt_str("CCSPlayer"), crypt_str("m_bHasHelmet"));
NETVAR(float, m_flFlashDuration, crypt_str("CCSPlayer"), crypt_str("m_flFlashDuration"));
NETVAR(bool, m_bHasHeavyArmor, crypt_str("CCSPlayer"), crypt_str("m_bHasHeavyArmor"));
NETVAR(bool, m_bIsScoped, crypt_str("CCSPlayer"), crypt_str("m_bIsScoped"));
NETVAR(float, m_flLowerBodyYawTarget, crypt_str("CCSPlayer"), crypt_str("m_flLowerBodyYawTarget"));
NETVAR(CBaseHandle, m_hVehicle, crypt_str("CBasePlayer"), crypt_str("m_hVehicle"));
NETVAR(int, m_iHealth, crypt_str("CBasePlayer"), crypt_str("m_iHealth"));
NETVAR(int, m_lifeState, crypt_str("CBasePlayer"), crypt_str("m_lifeState"));
NETVAR(int, m_fFlags, crypt_str("CBasePlayer"), crypt_str("m_fFlags"));
NETVAR(int, m_nHitboxSet, crypt_str("CBasePlayer"), crypt_str("m_nHitboxSet"));
NETVAR(int, m_nTickBase, crypt_str("CBasePlayer"), crypt_str("m_nTickBase"));
NETVAR(Vector, m_vecViewOffset, crypt_str("CBasePlayer"), crypt_str("m_vecViewOffset[0]"));
NETVAR(Vector, m_viewPunchAngle, crypt_str("CBasePlayer"), crypt_str("m_viewPunchAngle"));
NETVAR(Vector, m_aimPunchAngle, crypt_str("CBasePlayer"), crypt_str("m_aimPunchAngle"));
NETVAR(Vector, m_aimPunchAngleVel, crypt_str("CBasePlayer"), crypt_str("m_aimPunchAngleVel"));
NETVAR(CHandle <viewmodel_t>, m_hViewModel, crypt_str("CBasePlayer"), crypt_str("m_hViewModel[0]"));
NETVAR(Vector, m_vecVelocity, crypt_str("CBasePlayer"), crypt_str("m_vecVelocity[0]"));
NETVAR(Vector, m_vecMins, crypt_str("CBaseEntity"), crypt_str("m_vecMins"));
NETVAR(Vector, m_vecMaxs, crypt_str("CBaseEntity"), crypt_str("m_vecMaxs"));
NETVAR(float, m_flVelocityModifier, crypt_str("CCSPlayer"), crypt_str("m_flVelocityModifier"));
NETVAR(float, m_flSimulationTime, crypt_str("CBaseEntity"), crypt_str("m_flSimulationTime"));
OFFSET(float, m_flOldSimulationTime, netvars::get().get_offset(crypt_str("CBaseEntity"), crypt_str("m_flSimulationTime")) + 0x4);
NETVAR(float, m_flDuckSpeed, crypt_str("CCSPlayer"), crypt_str("m_flDuckSpeed"));
NETVAR(float, m_flDuckAmount, crypt_str("CCSPlayer"), crypt_str("m_flDuckAmount"));
NETVAR(bool, m_bDucked, crypt_str("CCSPlayer"), crypt_str("m_bDucked"));
NETVAR(bool, m_bDucking, crypt_str("CCSPlayer"), crypt_str("m_bDucking"));
NETVAR(float, m_flHealthShotBoostExpirationTime, crypt_str("CCSPlayer"), crypt_str("m_flHealthShotBoostExpirationTime"));
NETVAR(int, m_bInBombZone, crypt_str("CCSPlayer"), crypt_str("m_bInBombZone"));
NETVAR(float, m_flFallVelocity, crypt_str("CBasePlayer"), crypt_str("m_flFallVelocity"));
NETVAR(float, m_flStepSize, crypt_str("CBaseEntity"), crypt_str("m_flStepSize"));
NETVAR(float, m_flNextAttack, crypt_str("CBaseCombatCharacter"), crypt_str("m_flNextAttack"));
PNETVAR(CBaseHandle, m_hMyWearables, crypt_str("CBaseCombatCharacter"), crypt_str("m_hMyWearables"));
NETVAR(int, m_iObserverMode, crypt_str("CBasePlayer"), crypt_str("m_iObserverMode"));
NETVAR(CHandle <player_t>, m_hObserverTarget, crypt_str("CBasePlayer"), crypt_str("m_hObserverTarget"));
NETVAR(CHandle <weapon_t>, m_hActiveWeapon, crypt_str("CBaseCombatCharacter"), crypt_str("m_hActiveWeapon"));
NETVAR(CHandle <attributableitem_t>, m_hWeaponWorldModel, crypt_str("CBaseCombatWeapon"), crypt_str("m_hWeaponWorldModel"));
NETVAR(CHandle <entity_t>, m_hGroundEntity, crypt_str("CBasePlayer"), crypt_str("m_hGroundEntity"));
NETVAR(bool, m_bSpotted, crypt_str("CBaseEntity"), crypt_str("m_bSpotted"));
NETVAR(int, m_vphysicsCollisionState, crypt_str("CBasePlayer"), crypt_str("m_vphysicsCollisionState"));
NETVAR(bool, m_bIsWalking, crypt_str("CCSPlayer"), crypt_str("m_bIsWalking"));
NETVAR(bool, m_bIsDefusing, crypt_str("CCSPlayer"), crypt_str("m_bIsDefusing"));
VIRTUAL(think(void), 138, void(__thiscall*)(void*));
VIRTUAL(pre_think(void), 317, void(__thiscall*)(void*));
VIRTUAL(post_think(void), 318, void(__thiscall*)(void*));
VIRTUAL(set_local_view_angles(Vector& angle), 372, void(__thiscall*)(void*, Vector&), angle);
bool player_t::IsDead()
{
if (this == nullptr || *(void**)this == nullptr)
return true;
return (m_lifeState());
}
CBaseHandle* m_hMyWeapons()
{
return (CBaseHandle*)((uintptr_t)this + 0x2DF8);
}
float& m_flSpawnTime()
{
return *(float*)((uintptr_t)this + 0xA360);
}
uint32_t& m_iMostRecentModelBoneCounter();
float& m_flLastBoneSetupTime();
Vector get_eye_pos();
void select_item(const char* string, int sub_type);
bool using_standard_weapons_in_vechile();
bool physics_run_think(int index);
VarMapping_t* var_mapping();
c_baseplayeranimationstate* get_animation_state();
CStudioHdr* m_pStudioHdr();
bool setup_bones_rebuilt(matrix3x4_t* matrix, int mask);
Vector get_shoot_position();
void modify_eye_position(Vector& eye_position);
uint32_t& m_fEffects();
uint32_t& m_iEFlags();
float& m_surfaceFriction();
Vector& m_vecAbsVelocity();
int get_hitbox_bone_id(int hitbox_id);
Vector hitbox_position(int hitbox_id);
Vector hitbox_position_matrix(int hitbox_id, matrix3x4_t matrix[MAXSTUDIOBONES]);
AnimationLayer* get_animlayers();
CUtlVector <matrix3x4_t>& m_CachedBoneData();
CBoneAccessor& m_BoneAccessor();
void invalidate_bone_cache();
void set_abs_velocity(const Vector& velocity);
Vector get_render_angles();
void set_render_angles(const Vector& angles);
void update_clientside_animation();
bool is_alive();
bool valid(bool check_team, bool check_dormant = true);
int get_move_type();
int animlayer_count();
int sequence_activity(int sequence);
float get_max_desync_delta();
void invalidate_physics_recursive(int change_flags);
int GetChokedPackets();
};
class C_BaseAnimating : public player_t
{
public:
NETVAR(int, get_hitbox_set, "CBaseAnimating", "m_nHitboxSet");
};
class projectile_t : public entity_t
{
public:
NETVAR(Vector, m_vInitialVelocity, crypt_str("CBaseCSGrenadeProjectile"), crypt_str("m_vInitialVelocity"));
NETVAR(int, m_flAnimTime, crypt_str("CBaseCSGrenadeProjectile"), crypt_str("m_flAnimTime"));
NETVAR(int, m_nExplodeEffectTickBegin, crypt_str("CBaseCSGrenadeProjectile"), crypt_str("m_nExplodeEffectTickBegin"));
NETVAR(int, m_nBody, crypt_str("CBaseCSGrenadeProjectile"), crypt_str("m_nBody"));
NETVAR(int, m_nForceBone, crypt_str("CBaseCSGrenadeProjectile"), crypt_str("m_nForceBone"));
NETVAR(Vector, m_vecVelocity, crypt_str("CBaseGrenade"), crypt_str("m_vecVelocity"));
NETVAR(CHandle<player_t>, m_hThrower, "CBaseGrenade", "m_hThrower");
NETVAR(Vector, m_vecOrigin, crypt_str("CBaseCSGrenadeProjectile"), crypt_str("m_vecOrigin"));
OFFSET(float, m_flSpawnTime, netvars::get().get_offset(crypt_str("CBaseCSGrenadeProjectile"), crypt_str("m_vecExplodeEffectOrigin")) + 0xC);
};
class viewmodel_t : public entity_t
{
public:
NETVAR(int, m_nModelIndex, crypt_str("CBaseViewModel"), crypt_str("m_nModelIndex"));
NETVAR(int, m_nViewModelIndex, crypt_str("CBaseViewModel"), crypt_str("m_nViewModelIndex"));
NETVAR(CHandle <weapon_t>, m_hWeapon, crypt_str("CBaseViewModel"), crypt_str("m_hWeapon"));
NETVAR(CHandle <player_t>, m_hOwner, crypt_str("CBaseViewModel"), crypt_str("m_hOwner"));
NETVAR(int, m_nAnimationParity, crypt_str("CBaseViewModel"), crypt_str("m_nAnimationParity"));
float& m_flCycle();
float& m_flAnimTime();
void SendViewModelMatchingSequence(int sequence);
};
class CCSBomb : public entity_t
{
public:
NETVAR(float, m_flDefuseCountDown, crypt_str("CPlantedC4"), crypt_str("m_flDefuseCountDown"));
NETVAR(int, m_hBombDefuser, crypt_str("CPlantedC4"), crypt_str("m_hBombDefuser"));
NETVAR(float, m_flC4Blow, crypt_str("CPlantedC4"), crypt_str("m_flC4Blow"));
NETVAR(bool, m_bBombDefused, crypt_str("CPlantedC4"), crypt_str("m_bBombDefused"));
};
class ragdoll_t : public entity_t
{
public:
NETVAR(Vector, m_vecForce, crypt_str("CCSRagdoll"), crypt_str("m_vecForce"));
NETVAR(Vector, m_vecRagdollVelocity, crypt_str("CCSRagdoll"), crypt_str("m_vecRagdollVelocity"));
};
struct inferno_t : public entity_t
{
OFFSET(float, get_spawn_time, 0x20);
NETVAR(int, m_fireCount , crypt_str("CInferno"), crypt_str("m_fireCount"));
/* NETVAR(int, m_fireCount, crypt_str("CInferno"), crypt_str("m_fireXDelta"));
NETVAR(int, m_fireCount, crypt_str("CInferno"), crypt_str("m_fireYDelta"));
NETVAR(int, m_fireCount, crypt_str("CInferno"), crypt_str("m_fireZDelta"));*/
static float get_expiry_time()
{
return 7.03125f;
}
};
struct smoke_t : public entity_t
{
NETVAR(int, m_nSmokeEffectTickBegin, crypt_str("CSmokeGrenadeProjectile"), crypt_str("m_nSmokeEffectTickBegin"));
NETVAR(bool, m_bDidSmokeEffect, crypt_str("CSmokeGrenadeProjectile"), crypt_str("m_bDidSmokeEffect"));
static float get_expiry_time()
{
return 19.0f;
}
};
class CHudChat
{
public:
char pad_0x0000[0x4C];
int m_timesOpened;
char pad_0x0050[0x8];
bool m_isOpen;
char pad_0x0059[0x427];
void chat_print(const char* fmt, ...);
};
class AnimationLayer
{
public:
bool m_bClientBlend; //0x0000
float m_flBlendIn; //0x0004
void* m_pStudioHdr; //0x0008
int m_nDispatchSequence; //0x000C
int m_nDispatchSequence_2; //0x0010
uint32_t m_nOrder; //0x0014
uint32_t m_nSequence; //0x0018
float_t m_flPrevCycle; //0x001C
float_t m_flWeight; //0x0020
float_t m_flWeightDeltaRate; //0x0024
float_t m_flPlaybackRate; //0x0028
float_t m_flCycle; //0x002C
void* m_pOwner; //0x0030
char pad_0038[4]; //0x0034
};
class c_baseplayeranimationstate
{
public:
char pad[3];
char bUnknown; //0x4
char pad2[87];
weapon_t* m_pLastBoneSetupWeapon; //0x5C
player_t* m_pBaseEntity; //0x60
weapon_t* m_pActiveWeapon; //0x64
weapon_t* m_pLastActiveWeapon; //0x68
float m_flLastClientSideAnimationUpdateTime; //0x6C
int m_iLastClientSideAnimationUpdateFramecount; //0x70
float m_flUpdateTimeDelta; //0x74
float m_flEyeYaw; //0x78
float m_flPitch; //0x7C
float m_flGoalFeetYaw; //0x80
float m_flCurrentFeetYaw; //0x84
float m_flCurrentTorsoYaw; //0x88
float m_flUnknownVelocityLean; //0x8C //changes when moving/jumping/hitting ground
float m_flLeanAmount; //0x90
char pad4[4]; //NaN
float m_flFeetCycle; //0x98 0 to 1
float m_flFeetYawRate; //0x9C 0 to 1
float m_fUnknown2;
float m_fDuckAmount; //0xA4
float m_fLandingDuckAdditiveSomething; //0xA8
float m_fUnknown3; //0xAC
Vector m_vOrigin; //0xB0, 0xB4, 0xB8
Vector m_vLastOrigin; //0xBC, 0xC0, 0xC4
float m_vVelocityX; //0xC8
float m_vVelocityY; //0xCC
char pad5[4];
float m_flUnknownFloat1; //0xD4 Affected by movement and direction
char pad6[8];
float m_flUnknownFloat2; //0xE0 //from -1 to 1 when moving and affected by direction
float m_flUnknownFloat3; //0xE4 //from -1 to 1 when moving and affected by direction
float m_unknown; //0xE8
float m_velocity; //0xEC
float flUpVelocity; //0xF0
float m_flSpeedNormalized; //0xF4 //from 0 to 1
float m_flFeetSpeedForwardsOrSideWays; //0xF8 //from 0 to 2. something is 1 when walking, 2.something when running, 0.653 when crouch walking
float m_flFeetSpeedUnknownForwardOrSideways; //0xFC //from 0 to 3. something
float m_flTimeSinceStartedMoving; //0x100
float m_flTimeSinceStoppedMoving; //0x104
bool m_bOnGround; //0x108
bool m_bInHitGroundAnimation; //0x109
char pad7[10];
float m_flLastOriginZ; //0x114
float m_flHeadHeightOrOffsetFromHittingGroundAnimation; //0x118 from 0 to 1, is 1 when standing
float m_flStopToFullRunningFraction; //0x11C from 0 to 1, doesnt change when walking or crouching, only running
char pad8[4]; //NaN
float m_flMovingFraction; //0x124 affected while jumping and running, or when just jumping, 0 to 1
char pad9[4]; //NaN
float m_flUnknown3;
char pad10[528];
float& time_since_in_air()
{
return *(float*)((uintptr_t)this + 0x110);
}
float& yaw_desync_adjustment()
{
return *(float*)((uintptr_t)this + 0x334);
}
};
enum Activity
{
ACT_RESET,
ACT_IDLE,
ACT_TRANSITION,
ACT_COVER,
ACT_COVER_MED,
ACT_COVER_LOW,
ACT_WALK,
ACT_WALK_AIM,
ACT_WALK_CROUCH,
ACT_WALK_CROUCH_AIM,
ACT_RUN,
ACT_RUN_AIM,
ACT_RUN_CROUCH,
ACT_RUN_CROUCH_AIM,
ACT_RUN_PROTECTED,
ACT_SCRIPT_CUSTOM_MOVE,
ACT_RANGE_ATTACK1,
ACT_RANGE_ATTACK2,
ACT_RANGE_ATTACK1_LOW,
ACT_RANGE_ATTACK2_LOW,
ACT_DIESIMPLE,
ACT_DIEBACKWARD,
ACT_DIEFORWARD,
ACT_DIEVIOLENT,
ACT_DIERAGDOLL,
ACT_FLY,
ACT_HOVER,
ACT_GLIDE,
ACT_SWIM,
ACT_JUMP,
ACT_HOP,
ACT_LEAP,
ACT_LAND,
ACT_CLIMB_UP,
ACT_CLIMB_DOWN,
ACT_CLIMB_DISMOUNT,
ACT_SHIPLADDER_UP,
ACT_SHIPLADDER_DOWN,
ACT_STRAFE_LEFT,
ACT_STRAFE_RIGHT,
ACT_ROLL_LEFT,
ACT_ROLL_RIGHT,
ACT_TURN_LEFT,
ACT_TURN_RIGHT,
ACT_CROUCH,
ACT_CROUCHIDLE,
ACT_STAND,
ACT_USE,
ACT_ALIEN_BURROW_IDLE,
ACT_ALIEN_BURROW_OUT,
ACT_SIGNAL1,
ACT_SIGNAL2,
ACT_SIGNAL3,
ACT_SIGNAL_ADVANCE,
ACT_SIGNAL_FORWARD,
ACT_SIGNAL_GROUP,
ACT_SIGNAL_HALT,
ACT_SIGNAL_LEFT,
ACT_SIGNAL_RIGHT,
ACT_SIGNAL_TAKECOVER,
ACT_LOOKBACK_RIGHT,
ACT_LOOKBACK_LEFT,
ACT_COWER,
ACT_SMALL_FLINCH,
ACT_BIG_FLINCH,
ACT_MELEE_ATTACK1,
ACT_MELEE_ATTACK2,
ACT_RELOAD,
ACT_RELOAD_START,
ACT_RELOAD_FINISH,
ACT_RELOAD_LOW,
ACT_ARM,
ACT_DISARM,
ACT_DROP_WEAPON,
ACT_DROP_WEAPON_SHOTGUN,
ACT_PICKUP_GROUND,
ACT_PICKUP_RACK,
ACT_IDLE_ANGRY,
ACT_IDLE_RELAXED,
ACT_IDLE_STIMULATED,
ACT_IDLE_AGITATED,
ACT_IDLE_STEALTH,
ACT_IDLE_HURT,
ACT_WALK_RELAXED,
ACT_WALK_STIMULATED,
ACT_WALK_AGITATED,
ACT_WALK_STEALTH,
ACT_RUN_RELAXED,
ACT_RUN_STIMULATED,
ACT_RUN_AGITATED,
ACT_RUN_STEALTH,
ACT_IDLE_AIM_RELAXED,
ACT_IDLE_AIM_STIMULATED,
ACT_IDLE_AIM_AGITATED,
ACT_IDLE_AIM_STEALTH,
ACT_WALK_AIM_RELAXED,
ACT_WALK_AIM_STIMULATED,
ACT_WALK_AIM_AGITATED,
ACT_WALK_AIM_STEALTH,
ACT_RUN_AIM_RELAXED,
ACT_RUN_AIM_STIMULATED,
ACT_RUN_AIM_AGITATED,
ACT_RUN_AIM_STEALTH,
ACT_CROUCHIDLE_STIMULATED,
ACT_CROUCHIDLE_AIM_STIMULATED,
ACT_CROUCHIDLE_AGITATED,
ACT_WALK_HURT,
ACT_RUN_HURT,
ACT_SPECIAL_ATTACK1,
ACT_SPECIAL_ATTACK2,
ACT_COMBAT_IDLE,
ACT_WALK_SCARED,
ACT_RUN_SCARED,
ACT_VICTORY_DANCE,
ACT_DIE_HEADSHOT,
ACT_DIE_CHESTSHOT,
ACT_DIE_GUTSHOT,
ACT_DIE_BACKSHOT,
ACT_FLINCH_HEAD,
ACT_FLINCH_CHEST,
ACT_FLINCH_STOMACH,
ACT_FLINCH_LEFTARM,
ACT_FLINCH_RIGHTARM,
ACT_FLINCH_LEFTLEG,
ACT_FLINCH_RIGHTLEG,
ACT_FLINCH_PHYSICS,
ACT_FLINCH_HEAD_BACK,
ACT_FLINCH_HEAD_LEFT,
ACT_FLINCH_HEAD_RIGHT,
ACT_FLINCH_CHEST_BACK,
ACT_FLINCH_STOMACH_BACK,
ACT_FLINCH_CROUCH_FRONT,
ACT_FLINCH_CROUCH_BACK,
ACT_FLINCH_CROUCH_LEFT,
ACT_FLINCH_CROUCH_RIGHT,
ACT_IDLE_ON_FIRE,
ACT_WALK_ON_FIRE,
ACT_RUN_ON_FIRE,
ACT_RAPPEL_LOOP,
ACT_180_LEFT,
ACT_180_RIGHT,
ACT_90_LEFT,
ACT_90_RIGHT,
ACT_STEP_LEFT,
ACT_STEP_RIGHT,
ACT_STEP_BACK,
ACT_STEP_FORE,
ACT_GESTURE_RANGE_ATTACK1,
ACT_GESTURE_RANGE_ATTACK2,
ACT_GESTURE_MELEE_ATTACK1,
ACT_GESTURE_MELEE_ATTACK2,
ACT_GESTURE_RANGE_ATTACK1_LOW,
ACT_GESTURE_RANGE_ATTACK2_LOW,
ACT_MELEE_ATTACK_SWING_GESTURE,
ACT_GESTURE_SMALL_FLINCH,
ACT_GESTURE_BIG_FLINCH,
ACT_GESTURE_FLINCH_BLAST,
ACT_GESTURE_FLINCH_BLAST_SHOTGUN,
ACT_GESTURE_FLINCH_BLAST_DAMAGED,
ACT_GESTURE_FLINCH_BLAST_DAMAGED_SHOTGUN,
ACT_GESTURE_FLINCH_HEAD,
ACT_GESTURE_FLINCH_CHEST,
ACT_GESTURE_FLINCH_STOMACH,
ACT_GESTURE_FLINCH_LEFTARM,
ACT_GESTURE_FLINCH_RIGHTARM,
ACT_GESTURE_FLINCH_LEFTLEG,
ACT_GESTURE_FLINCH_RIGHTLEG,
ACT_GESTURE_TURN_LEFT,
ACT_GESTURE_TURN_RIGHT,
ACT_GESTURE_TURN_LEFT45,
ACT_GESTURE_TURN_RIGHT45,
ACT_GESTURE_TURN_LEFT90,
ACT_GESTURE_TURN_RIGHT90,
ACT_GESTURE_TURN_LEFT45_FLAT,
ACT_GESTURE_TURN_RIGHT45_FLAT,
ACT_GESTURE_TURN_LEFT90_FLAT,
ACT_GESTURE_TURN_RIGHT90_FLAT,
ACT_BARNACLE_HIT,
ACT_BARNACLE_PULL,
ACT_BARNACLE_CHOMP,
ACT_BARNACLE_CHEW,
ACT_DO_NOT_DISTURB,
ACT_SPECIFIC_SEQUENCE,
ACT_VM_DRAW,
ACT_VM_HOLSTER,
ACT_VM_IDLE,
ACT_VM_FIDGET,
ACT_VM_PULLBACK,
ACT_VM_PULLBACK_HIGH,
ACT_VM_PULLBACK_LOW,
ACT_VM_THROW,
ACT_VM_PULLPIN,
ACT_VM_PRIMARYATTACK,
ACT_VM_SECONDARYATTACK,
ACT_VM_RELOAD,
ACT_VM_DRYFIRE,
ACT_VM_HITLEFT,
ACT_VM_HITLEFT2,
ACT_VM_HITRIGHT,
ACT_VM_HITRIGHT2,
ACT_VM_HITCENTER,
ACT_VM_HITCENTER2,
ACT_VM_MISSLEFT,
ACT_VM_MISSLEFT2,
ACT_VM_MISSRIGHT,
ACT_VM_MISSRIGHT2,
ACT_VM_MISSCENTER,
ACT_VM_MISSCENTER2,
ACT_VM_HAULBACK,
ACT_VM_SWINGHARD,
ACT_VM_SWINGMISS,
ACT_VM_SWINGHIT,
ACT_VM_IDLE_TO_LOWERED,
ACT_VM_IDLE_LOWERED,
ACT_VM_LOWERED_TO_IDLE,
ACT_VM_RECOIL1,
ACT_VM_RECOIL2,
ACT_VM_RECOIL3,
ACT_VM_PICKUP,
ACT_VM_RELEASE,
ACT_VM_ATTACH_SILENCER,
ACT_VM_DETACH_SILENCER,
ACT_VM_EMPTY_FIRE,
ACT_VM_EMPTY_RELOAD,
ACT_VM_EMPTY_DRAW,
ACT_VM_EMPTY_IDLE,
ACT_SLAM_STICKWALL_IDLE,
ACT_SLAM_STICKWALL_ND_IDLE,
ACT_SLAM_STICKWALL_ATTACH,
ACT_SLAM_STICKWALL_ATTACH2,
ACT_SLAM_STICKWALL_ND_ATTACH,
ACT_SLAM_STICKWALL_ND_ATTACH2,
ACT_SLAM_STICKWALL_DETONATE,
ACT_SLAM_STICKWALL_DETONATOR_HOLSTER,
ACT_SLAM_STICKWALL_DRAW,
ACT_SLAM_STICKWALL_ND_DRAW,
ACT_SLAM_STICKWALL_TO_THROW,
ACT_SLAM_STICKWALL_TO_THROW_ND,
ACT_SLAM_STICKWALL_TO_TRIPMINE_ND,
ACT_SLAM_THROW_IDLE,
ACT_SLAM_THROW_ND_IDLE,
ACT_SLAM_THROW_THROW,
ACT_SLAM_THROW_THROW2,
ACT_SLAM_THROW_THROW_ND,
ACT_SLAM_THROW_THROW_ND2,
ACT_SLAM_THROW_DRAW,
ACT_SLAM_THROW_ND_DRAW,
ACT_SLAM_THROW_TO_STICKWALL,
ACT_SLAM_THROW_TO_STICKWALL_ND,
ACT_SLAM_THROW_DETONATE,
ACT_SLAM_THROW_DETONATOR_HOLSTER,
ACT_SLAM_THROW_TO_TRIPMINE_ND,
ACT_SLAM_TRIPMINE_IDLE,
ACT_SLAM_TRIPMINE_DRAW,
ACT_SLAM_TRIPMINE_ATTACH,
ACT_SLAM_TRIPMINE_ATTACH2,
ACT_SLAM_TRIPMINE_TO_STICKWALL_ND,
ACT_SLAM_TRIPMINE_TO_THROW_ND,
ACT_SLAM_DETONATOR_IDLE,
ACT_SLAM_DETONATOR_DRAW,
ACT_SLAM_DETONATOR_DETONATE,
ACT_SLAM_DETONATOR_HOLSTER,
ACT_SLAM_DETONATOR_STICKWALL_DRAW,
ACT_SLAM_DETONATOR_THROW_DRAW,
ACT_SHOTGUN_RELOAD_START,
ACT_SHOTGUN_RELOAD_FINISH,
ACT_SHOTGUN_PUMP,
ACT_SMG2_IDLE2,
ACT_SMG2_FIRE2,
ACT_SMG2_DRAW2,
ACT_SMG2_RELOAD2,
ACT_SMG2_DRYFIRE2,
ACT_SMG2_TOAUTO,
ACT_SMG2_TOBURST,
ACT_PHYSCANNON_UPGRADE,
ACT_RANGE_ATTACK_AR1,
ACT_RANGE_ATTACK_AR2,
ACT_RANGE_ATTACK_AR2_LOW,
ACT_RANGE_ATTACK_AR2_GRENADE,
ACT_RANGE_ATTACK_HMG1,
ACT_RANGE_ATTACK_ML,
ACT_RANGE_ATTACK_SMG1,
ACT_RANGE_ATTACK_SMG1_LOW,
ACT_RANGE_ATTACK_SMG2,
ACT_RANGE_ATTACK_SHOTGUN,
ACT_RANGE_ATTACK_SHOTGUN_LOW,
ACT_RANGE_ATTACK_PISTOL,
ACT_RANGE_ATTACK_PISTOL_LOW,
ACT_RANGE_ATTACK_SLAM,
ACT_RANGE_ATTACK_TRIPWIRE,
ACT_RANGE_ATTACK_THROW,
ACT_RANGE_ATTACK_SNIPER_RIFLE,
ACT_RANGE_ATTACK_RPG,
ACT_MELEE_ATTACK_SWING,
ACT_RANGE_AIM_LOW,
ACT_RANGE_AIM_SMG1_LOW,
ACT_RANGE_AIM_PISTOL_LOW,
ACT_RANGE_AIM_AR2_LOW,
ACT_COVER_PISTOL_LOW,
ACT_COVER_SMG1_LOW,
ACT_GESTURE_RANGE_ATTACK_AR1,
ACT_GESTURE_RANGE_ATTACK_AR2,
ACT_GESTURE_RANGE_ATTACK_AR2_GRENADE,
ACT_GESTURE_RANGE_ATTACK_HMG1,
ACT_GESTURE_RANGE_ATTACK_ML,
ACT_GESTURE_RANGE_ATTACK_SMG1,
ACT_GESTURE_RANGE_ATTACK_SMG1_LOW,
ACT_GESTURE_RANGE_ATTACK_SMG2,
ACT_GESTURE_RANGE_ATTACK_SHOTGUN,
ACT_GESTURE_RANGE_ATTACK_PISTOL,
ACT_GESTURE_RANGE_ATTACK_PISTOL_LOW,
ACT_GESTURE_RANGE_ATTACK_SLAM,
ACT_GESTURE_RANGE_ATTACK_TRIPWIRE,
ACT_GESTURE_RANGE_ATTACK_THROW,
ACT_GESTURE_RANGE_ATTACK_SNIPER_RIFLE,
ACT_GESTURE_MELEE_ATTACK_SWING,
ACT_IDLE_RIFLE,
ACT_IDLE_SMG1,
ACT_IDLE_ANGRY_SMG1,
ACT_IDLE_PISTOL,
ACT_IDLE_ANGRY_PISTOL,
ACT_IDLE_ANGRY_SHOTGUN,
ACT_IDLE_STEALTH_PISTOL,
ACT_IDLE_PACKAGE,
ACT_WALK_PACKAGE,
ACT_IDLE_SUITCASE,
ACT_WALK_SUITCASE,
ACT_IDLE_SMG1_RELAXED,
ACT_IDLE_SMG1_STIMULATED,
ACT_WALK_RIFLE_RELAXED,
ACT_RUN_RIFLE_RELAXED,
ACT_WALK_RIFLE_STIMULATED,
ACT_RUN_RIFLE_STIMULATED,
ACT_IDLE_AIM_RIFLE_STIMULATED,
ACT_WALK_AIM_RIFLE_STIMULATED,
ACT_RUN_AIM_RIFLE_STIMULATED,
ACT_IDLE_SHOTGUN_RELAXED,
ACT_IDLE_SHOTGUN_STIMULATED,
ACT_IDLE_SHOTGUN_AGITATED,
ACT_WALK_ANGRY,
ACT_POLICE_HARASS1,
ACT_POLICE_HARASS2,
ACT_IDLE_MANNEDGUN,
ACT_IDLE_MELEE,
ACT_IDLE_ANGRY_MELEE,
ACT_IDLE_RPG_RELAXED,
ACT_IDLE_RPG,
ACT_IDLE_ANGRY_RPG,
ACT_COVER_LOW_RPG,
ACT_WALK_RPG,
ACT_RUN_RPG,
ACT_WALK_CROUCH_RPG,
ACT_RUN_CROUCH_RPG,
ACT_WALK_RPG_RELAXED,
ACT_RUN_RPG_RELAXED,
ACT_WALK_RIFLE,
ACT_WALK_AIM_RIFLE,
ACT_WALK_CROUCH_RIFLE,
ACT_WALK_CROUCH_AIM_RIFLE,
ACT_RUN_RIFLE,
ACT_RUN_AIM_RIFLE,
ACT_RUN_CROUCH_RIFLE,
ACT_RUN_CROUCH_AIM_RIFLE,
ACT_RUN_STEALTH_PISTOL,
ACT_WALK_AIM_SHOTGUN,
ACT_RUN_AIM_SHOTGUN,
ACT_WALK_PISTOL,
ACT_RUN_PISTOL,
ACT_WALK_AIM_PISTOL,
ACT_RUN_AIM_PISTOL,
ACT_WALK_STEALTH_PISTOL,
ACT_WALK_AIM_STEALTH_PISTOL,
ACT_RUN_AIM_STEALTH_PISTOL,
ACT_RELOAD_PISTOL,
ACT_RELOAD_PISTOL_LOW,
ACT_RELOAD_SMG1,
ACT_RELOAD_SMG1_LOW,
ACT_RELOAD_SHOTGUN,
ACT_RELOAD_SHOTGUN_LOW,
ACT_GESTURE_RELOAD,
ACT_GESTURE_RELOAD_PISTOL,
ACT_GESTURE_RELOAD_SMG1,
ACT_GESTURE_RELOAD_SHOTGUN,
ACT_BUSY_LEAN_LEFT,
ACT_BUSY_LEAN_LEFT_ENTRY,
ACT_BUSY_LEAN_LEFT_EXIT,
ACT_BUSY_LEAN_BACK,
ACT_BUSY_LEAN_BACK_ENTRY,
ACT_BUSY_LEAN_BACK_EXIT,
ACT_BUSY_SIT_GROUND,
ACT_BUSY_SIT_GROUND_ENTRY,
ACT_BUSY_SIT_GROUND_EXIT,
ACT_BUSY_SIT_CHAIR,
ACT_BUSY_SIT_CHAIR_ENTRY,
ACT_BUSY_SIT_CHAIR_EXIT,
ACT_BUSY_STAND,
ACT_BUSY_QUEUE,
ACT_DUCK_DODGE,
ACT_DIE_BARNACLE_SWALLOW,
ACT_GESTURE_BARNACLE_STRANGLE,
ACT_PHYSCANNON_DETACH,
ACT_PHYSCANNON_ANIMATE,
ACT_PHYSCANNON_ANIMATE_PRE,
ACT_PHYSCANNON_ANIMATE_POST,
ACT_DIE_FRONTSIDE,
ACT_DIE_RIGHTSIDE,
ACT_DIE_BACKSIDE,
ACT_DIE_LEFTSIDE,
ACT_DIE_CROUCH_FRONTSIDE,
ACT_DIE_CROUCH_RIGHTSIDE,
ACT_DIE_CROUCH_BACKSIDE,
ACT_DIE_CROUCH_LEFTSIDE,
ACT_OPEN_DOOR,
ACT_DI_ALYX_ZOMBIE_MELEE,
ACT_DI_ALYX_ZOMBIE_TORSO_MELEE,
ACT_DI_ALYX_HEADCRAB_MELEE,
ACT_DI_ALYX_ANTLION,
ACT_DI_ALYX_ZOMBIE_SHOTGUN64,
ACT_DI_ALYX_ZOMBIE_SHOTGUN26,
ACT_READINESS_RELAXED_TO_STIMULATED,
ACT_READINESS_RELAXED_TO_STIMULATED_WALK,
ACT_READINESS_AGITATED_TO_STIMULATED,
ACT_READINESS_STIMULATED_TO_RELAXED,
ACT_READINESS_PISTOL_RELAXED_TO_STIMULATED,
ACT_READINESS_PISTOL_RELAXED_TO_STIMULATED_WALK,
ACT_READINESS_PISTOL_AGITATED_TO_STIMULATED,
ACT_READINESS_PISTOL_STIMULATED_TO_RELAXED,
ACT_IDLE_CARRY,
ACT_WALK_CARRY,
ACT_STARTDYING,
ACT_DYINGLOOP,
ACT_DYINGTODEAD,
ACT_RIDE_MANNED_GUN,
ACT_VM_SPRINT_ENTER,
ACT_VM_SPRINT_IDLE,
ACT_VM_SPRINT_LEAVE,
ACT_FIRE_START,
ACT_FIRE_LOOP,
ACT_FIRE_END,
ACT_CROUCHING_GRENADEIDLE,
ACT_CROUCHING_GRENADEREADY,
ACT_CROUCHING_PRIMARYATTACK,
ACT_OVERLAY_GRENADEIDLE,
ACT_OVERLAY_GRENADEREADY,
ACT_OVERLAY_PRIMARYATTACK,
ACT_OVERLAY_SHIELD_UP,
ACT_OVERLAY_SHIELD_DOWN,
ACT_OVERLAY_SHIELD_UP_IDLE,
ACT_OVERLAY_SHIELD_ATTACK,
ACT_OVERLAY_SHIELD_KNOCKBACK,
ACT_SHIELD_UP,
ACT_SHIELD_DOWN,
ACT_SHIELD_UP_IDLE,
ACT_SHIELD_ATTACK,
ACT_SHIELD_KNOCKBACK,
ACT_CROUCHING_SHIELD_UP,
ACT_CROUCHING_SHIELD_DOWN,
ACT_CROUCHING_SHIELD_UP_IDLE,
ACT_CROUCHING_SHIELD_ATTACK,
ACT_CROUCHING_SHIELD_KNOCKBACK,
ACT_TURNRIGHT45,
ACT_TURNLEFT45,
ACT_TURN,
ACT_OBJ_ASSEMBLING,
ACT_OBJ_DISMANTLING,
ACT_OBJ_STARTUP,
ACT_OBJ_RUNNING,
ACT_OBJ_IDLE,
ACT_OBJ_PLACING,
ACT_OBJ_DETERIORATING,
ACT_OBJ_UPGRADING,
ACT_DEPLOY,
ACT_DEPLOY_IDLE,
ACT_UNDEPLOY,
ACT_CROSSBOW_DRAW_UNLOADED,
ACT_GAUSS_SPINUP,
ACT_GAUSS_SPINCYCLE,
ACT_VM_PRIMARYATTACK_SILENCED,
ACT_VM_RELOAD_SILENCED,
ACT_VM_DRYFIRE_SILENCED,
ACT_VM_IDLE_SILENCED,
ACT_VM_DRAW_SILENCED,
ACT_VM_IDLE_EMPTY_LEFT,
ACT_VM_DRYFIRE_LEFT,
ACT_VM_IS_DRAW,
ACT_VM_IS_HOLSTER,
ACT_VM_IS_IDLE,
ACT_VM_IS_PRIMARYATTACK,
ACT_PLAYER_IDLE_FIRE,
ACT_PLAYER_CROUCH_FIRE,
ACT_PLAYER_CROUCH_WALK_FIRE,
ACT_PLAYER_WALK_FIRE,
ACT_PLAYER_RUN_FIRE,
ACT_IDLETORUN,
ACT_RUNTOIDLE,
ACT_VM_DRAW_DEPLOYED,
ACT_HL2MP_IDLE_MELEE,
ACT_HL2MP_RUN_MELEE,
ACT_HL2MP_IDLE_CROUCH_MELEE,
ACT_HL2MP_WALK_CROUCH_MELEE,
ACT_HL2MP_GESTURE_RANGE_ATTACK_MELEE,
ACT_HL2MP_GESTURE_RELOAD_MELEE,
ACT_HL2MP_JUMP_MELEE,
ACT_VM_FIZZLE,
ACT_MP_STAND_IDLE,
ACT_MP_CROUCH_IDLE,
ACT_MP_CROUCH_DEPLOYED_IDLE,
ACT_MP_CROUCH_DEPLOYED,
ACT_MP_DEPLOYED_IDLE,
ACT_MP_RUN,
ACT_MP_WALK,
ACT_MP_AIRWALK,
ACT_MP_CROUCHWALK,
ACT_MP_SPRINT,
ACT_MP_JUMP,
ACT_MP_JUMP_START,
ACT_MP_JUMP_FLOAT,
ACT_MP_JUMP_LAND,
ACT_MP_JUMP_IMPACT_N,
ACT_MP_JUMP_IMPACT_E,
ACT_MP_JUMP_IMPACT_W,
ACT_MP_JUMP_IMPACT_S,
ACT_MP_JUMP_IMPACT_TOP,
ACT_MP_DOUBLEJUMP,
ACT_MP_SWIM,
ACT_MP_DEPLOYED,
ACT_MP_SWIM_DEPLOYED,
ACT_MP_VCD,
ACT_MP_ATTACK_STAND_PRIMARYFIRE,
ACT_MP_ATTACK_STAND_PRIMARYFIRE_DEPLOYED,
ACT_MP_ATTACK_STAND_SECONDARYFIRE,
ACT_MP_ATTACK_STAND_GRENADE,
ACT_MP_ATTACK_CROUCH_PRIMARYFIRE,
ACT_MP_ATTACK_CROUCH_PRIMARYFIRE_DEPLOYED,
ACT_MP_ATTACK_CROUCH_SECONDARYFIRE,
ACT_MP_ATTACK_CROUCH_GRENADE,
ACT_MP_ATTACK_SWIM_PRIMARYFIRE,
ACT_MP_ATTACK_SWIM_SECONDARYFIRE,
ACT_MP_ATTACK_SWIM_GRENADE,
ACT_MP_ATTACK_AIRWALK_PRIMARYFIRE,
ACT_MP_ATTACK_AIRWALK_SECONDARYFIRE,
ACT_MP_ATTACK_AIRWALK_GRENADE,
ACT_MP_RELOAD_STAND,
ACT_MP_RELOAD_STAND_LOOP,
ACT_MP_RELOAD_STAND_END,
ACT_MP_RELOAD_CROUCH,
ACT_MP_RELOAD_CROUCH_LOOP,
ACT_MP_RELOAD_CROUCH_END,
ACT_MP_RELOAD_SWIM,
ACT_MP_RELOAD_SWIM_LOOP,
ACT_MP_RELOAD_SWIM_END,
ACT_MP_RELOAD_AIRWALK,
ACT_MP_RELOAD_AIRWALK_LOOP,
ACT_MP_RELOAD_AIRWALK_END,
ACT_MP_ATTACK_STAND_PREFIRE,
ACT_MP_ATTACK_STAND_POSTFIRE,
ACT_MP_ATTACK_STAND_STARTFIRE,
ACT_MP_ATTACK_CROUCH_PREFIRE,
ACT_MP_ATTACK_CROUCH_POSTFIRE,
ACT_MP_ATTACK_SWIM_PREFIRE,
ACT_MP_ATTACK_SWIM_POSTFIRE,
ACT_MP_STAND_PRIMARY,
ACT_MP_CROUCH_PRIMARY,
ACT_MP_RUN_PRIMARY,
ACT_MP_WALK_PRIMARY,
ACT_MP_AIRWALK_PRIMARY,
ACT_MP_CROUCHWALK_PRIMARY,
ACT_MP_JUMP_PRIMARY,
ACT_MP_JUMP_START_PRIMARY,
ACT_MP_JUMP_FLOAT_PRIMARY,
ACT_MP_JUMP_LAND_PRIMARY,
ACT_MP_SWIM_PRIMARY,
ACT_MP_DEPLOYED_PRIMARY,
ACT_MP_SWIM_DEPLOYED_PRIMARY,
ACT_MP_ATTACK_STAND_PRIMARY,
ACT_MP_ATTACK_STAND_PRIMARY_DEPLOYED,
ACT_MP_ATTACK_CROUCH_PRIMARY,
ACT_MP_ATTACK_CROUCH_PRIMARY_DEPLOYED,
ACT_MP_ATTACK_SWIM_PRIMARY,
ACT_MP_ATTACK_AIRWALK_PRIMARY,
ACT_MP_RELOAD_STAND_PRIMARY,
ACT_MP_RELOAD_STAND_PRIMARY_LOOP,
ACT_MP_RELOAD_STAND_PRIMARY_END,
ACT_MP_RELOAD_CROUCH_PRIMARY,
ACT_MP_RELOAD_CROUCH_PRIMARY_LOOP,
ACT_MP_RELOAD_CROUCH_PRIMARY_END,
ACT_MP_RELOAD_SWIM_PRIMARY,
ACT_MP_RELOAD_SWIM_PRIMARY_LOOP,
ACT_MP_RELOAD_SWIM_PRIMARY_END,
ACT_MP_RELOAD_AIRWALK_PRIMARY,
ACT_MP_RELOAD_AIRWALK_PRIMARY_LOOP,
ACT_MP_RELOAD_AIRWALK_PRIMARY_END,
ACT_MP_ATTACK_STAND_GRENADE_PRIMARY,
ACT_MP_ATTACK_CROUCH_GRENADE_PRIMARY,
ACT_MP_ATTACK_SWIM_GRENADE_PRIMARY,
ACT_MP_ATTACK_AIRWALK_GRENADE_PRIMARY,
ACT_MP_STAND_SECONDARY,
ACT_MP_CROUCH_SECONDARY,
ACT_MP_RUN_SECONDARY,
ACT_MP_WALK_SECONDARY,
ACT_MP_AIRWALK_SECONDARY,
ACT_MP_CROUCHWALK_SECONDARY,
ACT_MP_JUMP_SECONDARY,
ACT_MP_JUMP_START_SECONDARY,
ACT_MP_JUMP_FLOAT_SECONDARY,
ACT_MP_JUMP_LAND_SECONDARY,
ACT_MP_SWIM_SECONDARY,
ACT_MP_ATTACK_STAND_SECONDARY,
ACT_MP_ATTACK_CROUCH_SECONDARY,
ACT_MP_ATTACK_SWIM_SECONDARY,
ACT_MP_ATTACK_AIRWALK_SECONDARY,
ACT_MP_RELOAD_STAND_SECONDARY,
ACT_MP_RELOAD_STAND_SECONDARY_LOOP,
ACT_MP_RELOAD_STAND_SECONDARY_END,
ACT_MP_RELOAD_CROUCH_SECONDARY,
ACT_MP_RELOAD_CROUCH_SECONDARY_LOOP,
ACT_MP_RELOAD_CROUCH_SECONDARY_END,
ACT_MP_RELOAD_SWIM_SECONDARY,
ACT_MP_RELOAD_SWIM_SECONDARY_LOOP,
ACT_MP_RELOAD_SWIM_SECONDARY_END,
ACT_MP_RELOAD_AIRWALK_SECONDARY,
ACT_MP_RELOAD_AIRWALK_SECONDARY_LOOP,
ACT_MP_RELOAD_AIRWALK_SECONDARY_END,
ACT_MP_ATTACK_STAND_GRENADE_SECONDARY,
ACT_MP_ATTACK_CROUCH_GRENADE_SECONDARY,
ACT_MP_ATTACK_SWIM_GRENADE_SECONDARY,
ACT_MP_ATTACK_AIRWALK_GRENADE_SECONDARY,
ACT_MP_STAND_MELEE,
ACT_MP_CROUCH_MELEE,
ACT_MP_RUN_MELEE,
ACT_MP_WALK_MELEE,
ACT_MP_AIRWALK_MELEE,
ACT_MP_CROUCHWALK_MELEE,
ACT_MP_JUMP_MELEE,
ACT_MP_JUMP_START_MELEE,
ACT_MP_JUMP_FLOAT_MELEE,
ACT_MP_JUMP_LAND_MELEE,
ACT_MP_SWIM_MELEE,
ACT_MP_ATTACK_STAND_MELEE,
ACT_MP_ATTACK_STAND_MELEE_SECONDARY,
ACT_MP_ATTACK_CROUCH_MELEE,
ACT_MP_ATTACK_CROUCH_MELEE_SECONDARY,
ACT_MP_ATTACK_SWIM_MELEE,
ACT_MP_ATTACK_AIRWALK_MELEE,
ACT_MP_ATTACK_STAND_GRENADE_MELEE,
ACT_MP_ATTACK_CROUCH_GRENADE_MELEE,
ACT_MP_ATTACK_SWIM_GRENADE_MELEE,
ACT_MP_ATTACK_AIRWALK_GRENADE_MELEE,
ACT_MP_STAND_ITEM1,
ACT_MP_CROUCH_ITEM1,
ACT_MP_RUN_ITEM1,
ACT_MP_WALK_ITEM1,
ACT_MP_AIRWALK_ITEM1,
ACT_MP_CROUCHWALK_ITEM1,
ACT_MP_JUMP_ITEM1,
ACT_MP_JUMP_START_ITEM1,
ACT_MP_JUMP_FLOAT_ITEM1,
ACT_MP_JUMP_LAND_ITEM1,
ACT_MP_SWIM_ITEM1,
ACT_MP_ATTACK_STAND_ITEM1,
ACT_MP_ATTACK_STAND_ITEM1_SECONDARY,
ACT_MP_ATTACK_CROUCH_ITEM1,
ACT_MP_ATTACK_CROUCH_ITEM1_SECONDARY,
ACT_MP_ATTACK_SWIM_ITEM1,
ACT_MP_ATTACK_AIRWALK_ITEM1,
ACT_MP_STAND_ITEM2,
ACT_MP_CROUCH_ITEM2,
ACT_MP_RUN_ITEM2,
ACT_MP_WALK_ITEM2,
ACT_MP_AIRWALK_ITEM2,
ACT_MP_CROUCHWALK_ITEM2,
ACT_MP_JUMP_ITEM2,
ACT_MP_JUMP_START_ITEM2,
ACT_MP_JUMP_FLOAT_ITEM2,
ACT_MP_JUMP_LAND_ITEM2,
ACT_MP_SWIM_ITEM2,
ACT_MP_ATTACK_STAND_ITEM2,
ACT_MP_ATTACK_STAND_ITEM2_SECONDARY,
ACT_MP_ATTACK_CROUCH_ITEM2,
ACT_MP_ATTACK_CROUCH_ITEM2_SECONDARY,
ACT_MP_ATTACK_SWIM_ITEM2,
ACT_MP_ATTACK_AIRWALK_ITEM2,
ACT_MP_GESTURE_FLINCH,
ACT_MP_GESTURE_FLINCH_PRIMARY,
ACT_MP_GESTURE_FLINCH_SECONDARY,
ACT_MP_GESTURE_FLINCH_MELEE,
ACT_MP_GESTURE_FLINCH_ITEM1,
ACT_MP_GESTURE_FLINCH_ITEM2,
ACT_MP_GESTURE_FLINCH_HEAD,
ACT_MP_GESTURE_FLINCH_CHEST,
ACT_MP_GESTURE_FLINCH_STOMACH,
ACT_MP_GESTURE_FLINCH_LEFTARM,
ACT_MP_GESTURE_FLINCH_RIGHTARM,
ACT_MP_GESTURE_FLINCH_LEFTLEG,
ACT_MP_GESTURE_FLINCH_RIGHTLEG,
ACT_MP_GRENADE1_DRAW,
ACT_MP_GRENADE1_IDLE,
ACT_MP_GRENADE1_ATTACK,
ACT_MP_GRENADE2_DRAW,
ACT_MP_GRENADE2_IDLE,
ACT_MP_GRENADE2_ATTACK,
ACT_MP_PRIMARY_GRENADE1_DRAW,
ACT_MP_PRIMARY_GRENADE1_IDLE,
ACT_MP_PRIMARY_GRENADE1_ATTACK,
ACT_MP_PRIMARY_GRENADE2_DRAW,
ACT_MP_PRIMARY_GRENADE2_IDLE,
ACT_MP_PRIMARY_GRENADE2_ATTACK,
ACT_MP_SECONDARY_GRENADE1_DRAW,
ACT_MP_SECONDARY_GRENADE1_IDLE,
ACT_MP_SECONDARY_GRENADE1_ATTACK,
ACT_MP_SECONDARY_GRENADE2_DRAW,
ACT_MP_SECONDARY_GRENADE2_IDLE,
ACT_MP_SECONDARY_GRENADE2_ATTACK,
ACT_MP_MELEE_GRENADE1_DRAW,
ACT_MP_MELEE_GRENADE1_IDLE,
ACT_MP_MELEE_GRENADE1_ATTACK,
ACT_MP_MELEE_GRENADE2_DRAW,
ACT_MP_MELEE_GRENADE2_IDLE,
ACT_MP_MELEE_GRENADE2_ATTACK,
ACT_MP_ITEM1_GRENADE1_DRAW,
ACT_MP_ITEM1_GRENADE1_IDLE,
ACT_MP_ITEM1_GRENADE1_ATTACK,
ACT_MP_ITEM1_GRENADE2_DRAW,
ACT_MP_ITEM1_GRENADE2_IDLE,
ACT_MP_ITEM1_GRENADE2_ATTACK,
ACT_MP_ITEM2_GRENADE1_DRAW,
ACT_MP_ITEM2_GRENADE1_IDLE,
ACT_MP_ITEM2_GRENADE1_ATTACK,
ACT_MP_ITEM2_GRENADE2_DRAW,
ACT_MP_ITEM2_GRENADE2_IDLE,
ACT_MP_ITEM2_GRENADE2_ATTACK,
ACT_MP_STAND_BUILDING,
ACT_MP_CROUCH_BUILDING,
ACT_MP_RUN_BUILDING,
ACT_MP_WALK_BUILDING,
ACT_MP_AIRWALK_BUILDING,
ACT_MP_CROUCHWALK_BUILDING,
ACT_MP_JUMP_BUILDING,
ACT_MP_JUMP_START_BUILDING,
ACT_MP_JUMP_FLOAT_BUILDING,
ACT_MP_JUMP_LAND_BUILDING,
ACT_MP_SWIM_BUILDING,
ACT_MP_ATTACK_STAND_BUILDING,
ACT_MP_ATTACK_CROUCH_BUILDING,
ACT_MP_ATTACK_SWIM_BUILDING,
ACT_MP_ATTACK_AIRWALK_BUILDING,
ACT_MP_ATTACK_STAND_GRENADE_BUILDING,
ACT_MP_ATTACK_CROUCH_GRENADE_BUILDING,
ACT_MP_ATTACK_SWIM_GRENADE_BUILDING,
ACT_MP_ATTACK_AIRWALK_GRENADE_BUILDING,
ACT_MP_STAND_PDA,
ACT_MP_CROUCH_PDA,
ACT_MP_RUN_PDA,
ACT_MP_WALK_PDA,
ACT_MP_AIRWALK_PDA,
ACT_MP_CROUCHWALK_PDA,
ACT_MP_JUMP_PDA,
ACT_MP_JUMP_START_PDA,
ACT_MP_JUMP_FLOAT_PDA,
ACT_MP_JUMP_LAND_PDA,
ACT_MP_SWIM_PDA,
ACT_MP_ATTACK_STAND_PDA,
ACT_MP_ATTACK_SWIM_PDA,
ACT_MP_GESTURE_VC_HANDMOUTH,
ACT_MP_GESTURE_VC_FINGERPOINT,
ACT_MP_GESTURE_VC_FISTPUMP,
ACT_MP_GESTURE_VC_THUMBSUP,
ACT_MP_GESTURE_VC_NODYES,
ACT_MP_GESTURE_VC_NODNO,
ACT_MP_GESTURE_VC_HANDMOUTH_PRIMARY,
ACT_MP_GESTURE_VC_FINGERPOINT_PRIMARY,
ACT_MP_GESTURE_VC_FISTPUMP_PRIMARY,
ACT_MP_GESTURE_VC_THUMBSUP_PRIMARY,
ACT_MP_GESTURE_VC_NODYES_PRIMARY,
ACT_MP_GESTURE_VC_NODNO_PRIMARY,
ACT_MP_GESTURE_VC_HANDMOUTH_SECONDARY,
ACT_MP_GESTURE_VC_FINGERPOINT_SECONDARY,
ACT_MP_GESTURE_VC_FISTPUMP_SECONDARY,
ACT_MP_GESTURE_VC_THUMBSUP_SECONDARY,
ACT_MP_GESTURE_VC_NODYES_SECONDARY,
ACT_MP_GESTURE_VC_NODNO_SECONDARY,
ACT_MP_GESTURE_VC_HANDMOUTH_MELEE,
ACT_MP_GESTURE_VC_FINGERPOINT_MELEE,
ACT_MP_GESTURE_VC_FISTPUMP_MELEE,
ACT_MP_GESTURE_VC_THUMBSUP_MELEE,
ACT_MP_GESTURE_VC_NODYES_MELEE,
ACT_MP_GESTURE_VC_NODNO_MELEE,
ACT_MP_GESTURE_VC_HANDMOUTH_ITEM1,
ACT_MP_GESTURE_VC_FINGERPOINT_ITEM1,
ACT_MP_GESTURE_VC_FISTPUMP_ITEM1,
ACT_MP_GESTURE_VC_THUMBSUP_ITEM1,
ACT_MP_GESTURE_VC_NODYES_ITEM1,
ACT_MP_GESTURE_VC_NODNO_ITEM1,
ACT_MP_GESTURE_VC_HANDMOUTH_ITEM2,
ACT_MP_GESTURE_VC_FINGERPOINT_ITEM2,
ACT_MP_GESTURE_VC_FISTPUMP_ITEM2,
ACT_MP_GESTURE_VC_THUMBSUP_ITEM2,
ACT_MP_GESTURE_VC_NODYES_ITEM2,
ACT_MP_GESTURE_VC_NODNO_ITEM2,
ACT_MP_GESTURE_VC_HANDMOUTH_BUILDING,
ACT_MP_GESTURE_VC_FINGERPOINT_BUILDING,
ACT_MP_GESTURE_VC_FISTPUMP_BUILDING,
ACT_MP_GESTURE_VC_THUMBSUP_BUILDING,
ACT_MP_GESTURE_VC_NODYES_BUILDING,
ACT_MP_GESTURE_VC_NODNO_BUILDING,
ACT_MP_GESTURE_VC_HANDMOUTH_PDA,
ACT_MP_GESTURE_VC_FINGERPOINT_PDA,
ACT_MP_GESTURE_VC_FISTPUMP_PDA,
ACT_MP_GESTURE_VC_THUMBSUP_PDA,
ACT_MP_GESTURE_VC_NODYES_PDA,
ACT_MP_GESTURE_VC_NODNO_PDA,
ACT_VM_UNUSABLE,
ACT_VM_UNUSABLE_TO_USABLE,
ACT_VM_USABLE_TO_UNUSABLE,
ACT_PRIMARY_VM_DRAW,
ACT_PRIMARY_VM_HOLSTER,
ACT_PRIMARY_VM_IDLE,
ACT_PRIMARY_VM_PULLBACK,
ACT_PRIMARY_VM_PRIMARYATTACK,
ACT_PRIMARY_VM_SECONDARYATTACK,
ACT_PRIMARY_VM_RELOAD,
ACT_PRIMARY_VM_DRYFIRE,
ACT_PRIMARY_VM_IDLE_TO_LOWERED,
ACT_PRIMARY_VM_IDLE_LOWERED,
ACT_PRIMARY_VM_LOWERED_TO_IDLE,
ACT_SECONDARY_VM_DRAW,
ACT_SECONDARY_VM_HOLSTER,
ACT_SECONDARY_VM_IDLE,
ACT_SECONDARY_VM_PULLBACK,
ACT_SECONDARY_VM_PRIMARYATTACK,
ACT_SECONDARY_VM_SECONDARYATTACK,
ACT_SECONDARY_VM_RELOAD,
ACT_SECONDARY_VM_DRYFIRE,
ACT_SECONDARY_VM_IDLE_TO_LOWERED,
ACT_SECONDARY_VM_IDLE_LOWERED,
ACT_SECONDARY_VM_LOWERED_TO_IDLE,
ACT_MELEE_VM_DRAW,
ACT_MELEE_VM_HOLSTER,
ACT_MELEE_VM_IDLE,
ACT_MELEE_VM_PULLBACK,
ACT_MELEE_VM_PRIMARYATTACK,
ACT_MELEE_VM_SECONDARYATTACK,
ACT_MELEE_VM_RELOAD,
ACT_MELEE_VM_DRYFIRE,
ACT_MELEE_VM_IDLE_TO_LOWERED,
ACT_MELEE_VM_IDLE_LOWERED,
ACT_MELEE_VM_LOWERED_TO_IDLE,
ACT_PDA_VM_DRAW,
ACT_PDA_VM_HOLSTER,
ACT_PDA_VM_IDLE,
ACT_PDA_VM_PULLBACK,
ACT_PDA_VM_PRIMARYATTACK,
ACT_PDA_VM_SECONDARYATTACK,
ACT_PDA_VM_RELOAD,
ACT_PDA_VM_DRYFIRE,
ACT_PDA_VM_IDLE_TO_LOWERED,
ACT_PDA_VM_IDLE_LOWERED,
ACT_PDA_VM_LOWERED_TO_IDLE,
ACT_ITEM1_VM_DRAW,
ACT_ITEM1_VM_HOLSTER,
ACT_ITEM1_VM_IDLE,
ACT_ITEM1_VM_PULLBACK,
ACT_ITEM1_VM_PRIMARYATTACK,
ACT_ITEM1_VM_SECONDARYATTACK,
ACT_ITEM1_VM_RELOAD,
ACT_ITEM1_VM_DRYFIRE,
ACT_ITEM1_VM_IDLE_TO_LOWERED,
ACT_ITEM1_VM_IDLE_LOWERED,
ACT_ITEM1_VM_LOWERED_TO_IDLE,
ACT_ITEM2_VM_DRAW,
ACT_ITEM2_VM_HOLSTER,
ACT_ITEM2_VM_IDLE,
ACT_ITEM2_VM_PULLBACK,
ACT_ITEM2_VM_PRIMARYATTACK,
ACT_ITEM2_VM_SECONDARYATTACK,
ACT_ITEM2_VM_RELOAD,
ACT_ITEM2_VM_DRYFIRE,
ACT_ITEM2_VM_IDLE_TO_LOWERED,
ACT_ITEM2_VM_IDLE_LOWERED,
ACT_ITEM2_VM_LOWERED_TO_IDLE,
ACT_RELOAD_SUCCEED,
ACT_RELOAD_FAIL,
ACT_WALK_AIM_AUTOGUN,
ACT_RUN_AIM_AUTOGUN,
ACT_IDLE_AUTOGUN,
ACT_IDLE_AIM_AUTOGUN,
ACT_RELOAD_AUTOGUN,
ACT_CROUCH_IDLE_AUTOGUN,
ACT_RANGE_ATTACK_AUTOGUN,
ACT_JUMP_AUTOGUN,
ACT_IDLE_AIM_PISTOL,
ACT_WALK_AIM_DUAL,
ACT_RUN_AIM_DUAL,
ACT_IDLE_DUAL,
ACT_IDLE_AIM_DUAL,
ACT_RELOAD_DUAL,
ACT_CROUCH_IDLE_DUAL,
ACT_RANGE_ATTACK_DUAL,
ACT_JUMP_DUAL,
ACT_IDLE_SHOTGUN,
ACT_IDLE_AIM_SHOTGUN,
ACT_CROUCH_IDLE_SHOTGUN,
ACT_JUMP_SHOTGUN,
ACT_IDLE_AIM_RIFLE,
ACT_RELOAD_RIFLE,
ACT_CROUCH_IDLE_RIFLE,
ACT_RANGE_ATTACK_RIFLE,
ACT_JUMP_RIFLE,
ACT_SLEEP,
ACT_WAKE,
ACT_FLICK_LEFT,
ACT_FLICK_LEFT_MIDDLE,
ACT_FLICK_RIGHT_MIDDLE,
ACT_FLICK_RIGHT,
ACT_SPINAROUND,
ACT_PREP_TO_FIRE,
ACT_FIRE,
ACT_FIRE_RECOVER,
ACT_SPRAY,
ACT_PREP_EXPLODE,
ACT_EXPLODE,
ACT_DOTA_IDLE,
ACT_DOTA_RUN,
ACT_DOTA_ATTACK,
ACT_DOTA_ATTACK_EVENT,
ACT_DOTA_DIE,
ACT_DOTA_FLINCH,
ACT_DOTA_DISABLED,
ACT_DOTA_CAST_ABILITY_1,
ACT_DOTA_CAST_ABILITY_2,
ACT_DOTA_CAST_ABILITY_3,
ACT_DOTA_CAST_ABILITY_4,
ACT_DOTA_OVERRIDE_ABILITY_1,
ACT_DOTA_OVERRIDE_ABILITY_2,
ACT_DOTA_OVERRIDE_ABILITY_3,
ACT_DOTA_OVERRIDE_ABILITY_4,
ACT_DOTA_CHANNEL_ABILITY_1,
ACT_DOTA_CHANNEL_ABILITY_2,
ACT_DOTA_CHANNEL_ABILITY_3,
ACT_DOTA_CHANNEL_ABILITY_4,
ACT_DOTA_CHANNEL_END_ABILITY_1,
ACT_DOTA_CHANNEL_END_ABILITY_2,
ACT_DOTA_CHANNEL_END_ABILITY_3,
ACT_DOTA_CHANNEL_END_ABILITY_4,
ACT_MP_RUN_SPEEDPAINT,
ACT_MP_LONG_FALL,
ACT_MP_TRACTORBEAM_FLOAT,
ACT_MP_DEATH_CRUSH,
ACT_MP_RUN_SPEEDPAINT_PRIMARY,
ACT_MP_DROWNING_PRIMARY,
ACT_MP_LONG_FALL_PRIMARY,
ACT_MP_TRACTORBEAM_FLOAT_PRIMARY,
ACT_MP_DEATH_CRUSH_PRIMARY,
ACT_DIE_STAND,
ACT_DIE_STAND_HEADSHOT,
ACT_DIE_CROUCH,
ACT_DIE_CROUCH_HEADSHOT,
ACT_CSGO_NULL,
ACT_CSGO_DEFUSE,
ACT_CSGO_DEFUSE_WITH_KIT,
ACT_CSGO_FLASHBANG_REACTION,
ACT_CSGO_FIRE_PRIMARY,
ACT_CSGO_FIRE_PRIMARY_OPT_1,
ACT_CSGO_FIRE_PRIMARY_OPT_2,
ACT_CSGO_FIRE_SECONDARY,
ACT_CSGO_FIRE_SECONDARY_OPT_1,
ACT_CSGO_FIRE_SECONDARY_OPT_2,
ACT_CSGO_RELOAD,
ACT_CSGO_RELOAD_START,
ACT_CSGO_RELOAD_LOOP,
ACT_CSGO_RELOAD_END,
ACT_CSGO_OPERATE,
ACT_CSGO_DEPLOY,
ACT_CSGO_CATCH,
ACT_CSGO_SILENCER_DETACH,
ACT_CSGO_SILENCER_ATTACH,
ACT_CSGO_TWITCH,
ACT_CSGO_TWITCH_BUYZONE,
ACT_CSGO_PLANT_BOMB,
ACT_CSGO_IDLE_TURN_BALANCEADJUST,
ACT_CSGO_IDLE_ADJUST_STOPPEDMOVING,
ACT_CSGO_ALIVE_LOOP,
ACT_CSGO_FLINCH,
ACT_CSGO_FLINCH_HEAD,
ACT_CSGO_FLINCH_MOLOTOV,
ACT_CSGO_JUMP,
ACT_CSGO_FALL,
ACT_CSGO_CLIMB_LADDER,
ACT_CSGO_LAND_LIGHT,
ACT_CSGO_LAND_HEAVY,
ACT_CSGO_EXIT_LADDER_TOP,
ACT_CSGO_EXIT_LADDER_BOTTOM,
}; | [
"54349566+maj0roff@users.noreply.github.com"
] | 54349566+maj0roff@users.noreply.github.com |
a665a3a82457b6d6758f87204696547d72c92120 | 4cc285b0c585241ff4404087e6fbb901195639be | /NeuralNetworkNumbers/venv/Lib/site-packages/tensorflow/include/external/mkl_dnn_v1/src/common/primitive_cache.hpp | bb706f0d9ffff5090c6c7cc7c1c8d76cd73fae09 | [] | no_license | strazhg/NeuralNetworksPython | 815542f4ddbb86e918e657f783158f8c078de514 | 15038e44a5a6c342336c119cdd2abdeffd84b5b1 | refs/heads/main | 2023-04-16T18:51:29.602644 | 2021-04-27T14:46:55 | 2021-04-27T14:46:55 | 361,944,482 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | hpp | version https://git-lfs.github.com/spec/v1
oid sha256:9a1d89a0b94c000a41c9de30ad67edd2968fbea328ac8e166462e8807192e694
size 3141
| [
"golubstrazh@gmail.com"
] | golubstrazh@gmail.com |
c0e7ca3388b9809d12cdc32b092b6e8e651f43ea | f50a347491a7ff5db2715f72bb6df34c27866fa5 | /xui_global.cpp | 03f0a4bf510388b93cf73854dc5e451c173e2c14 | [] | no_license | jeffcai8888/xui_kit | 182181a981f58975c0612a01a9a4d8a3cb967cd9 | ec32e374ce72efc8fd2063d109a66115c28731b8 | refs/heads/master | 2021-01-13T03:47:19.061176 | 2017-01-02T16:04:58 | 2017-01-02T16:04:58 | 77,228,876 | 1 | 0 | null | 2016-12-23T14:00:04 | 2016-12-23T14:00:04 | null | GB18030 | C++ | false | false | 27,712 | cpp | #include "xui_desktop.h"
#include "xui_render_window.h"
#include "xui_window.h"
#include "xui_syswnd.h"
#include "xui_global.h"
/*
//icon
*/
xui_bitmap* xui_global::icon_pickcolour = NULL;
xui_bitmap* xui_global::icon_pickselect = NULL;
xui_bitmap* xui_global::icon_loop = NULL;
/*
//global
*/
bool def_deviceproc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam );
/*
//string
*/
xui_method_explain(xui_global, get_upper, std::wstring )( const std::wstring& src )
{
std::wstring result;
for (u32 i = 0; i < src.length(); ++i)
result.push_back((src[i] >= L'a' && src[i] <= L'z') ? (src[i]-32) : src[i]);
return result;
}
xui_method_explain(xui_global, unicode_to_utf8, std::string )( const std::wstring& src )
{
std::string result;
for (u32 i = 0; i < src.length(); ++i)
{
if (src[i] < 0x80)
{
result += (char)src[i];
}
else
if (src[i] < 0x800)
{
result += (char)(0xC0 | (src[i] >> 6));
result += (char)(0x80 | (src[i] & 0x3F));
}
else
if (src[i] < 0x10000)
{
result += (char)(0xE0 | (src[i] >> 12));
result += (char)(0x80 | ((src[i] >> 6 ) & 0x3F));
result += (char)(0x80 | (src[i] & 0x3F));
}
}
return result;
}
xui_method_explain(xui_global, utf8_to_unicode, std::wstring )( const std::string& src )
{
std::wstring result;
for (u32 i = 0; i < src.length(); )
{
wchar_t w;
if ((src[i] & 0x80) == 0) // U-00000000 - U-0000007F : 0xxxxxxx
{
w = (wchar_t)(src[i]);
i += 1;
}
else
if ((src[i] & 0xe0) == 0xc0 && i+1 < src.length()) // U-00000080 - U-000007FF : 110xxxxx 10xxxxxx
{
w = (wchar_t)(src[i+0] & 0x3f) << 6;
w |= (wchar_t)(src[i+1] & 0x3f);
i += 2;
}
else
if ((src[i] & 0xf0) == 0xe0 && i+2 < src.length()) // U-00000800 - U-0000FFFF : 1110xxxx 10xxxxxx 10xxxxxx
{
w = (wchar_t)(src[i+0] & 0x1f) << 12;
w |= (wchar_t)(src[i+1] & 0x3f) << 6;
w |= (wchar_t)(src[i+2] & 0x3f);
i += 3;
}
else
if ((src[i] & 0xf8) == 0xf0) // U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx , this is not Chinese
{
w = 0x20;
i += 4;
}
else
if ((src[i] & 0xfc) == 0xf8) // U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx , this is not Chinese
{
w = 0x20;
i += 5;
}
else // U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx , this is not Chinese
{
w = 0x20;
i += 6;
}
//add
result += w;
}
return result;
}
xui_method_explain(xui_global, unicode_to_ascii,std::string )( const std::wstring& src )
{
char buffer[512];
WideCharToMultiByte(CP_ACP, 0, src.c_str(), -1, buffer, 512, NULL, NULL);
return std::string(buffer);
}
xui_method_explain(xui_global, ascii_to_unicode,std::wstring )( const std::string& src )
{
wchar_t buffer[512];
MultiByteToWideChar(CP_ACP, 0, src.c_str(), -1, buffer, 512);
return std::wstring(buffer);
}
/*
//screen
*/
HWND scolor_hwnd = NULL;
CHAR* screen_buffer = NULL;
s32 screen_w = 0;
s32 screen_h = 0;
void capture_screen( void )
{
HDC hdcScreen = ::GetDC(NULL);
screen_w = GetSystemMetrics(SM_CXSCREEN); // 屏幕宽
screen_h = GetSystemMetrics(SM_CYSCREEN); // 屏幕高
HDC hdcMemory = CreateCompatibleDC(hdcScreen); // 创建兼容内存DC
if (hdcMemory == NULL)
{
goto done;
}
// 通过窗口DC 创建一个兼容位图
BITMAPINFO bi;
bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bi.bmiHeader.biWidth = screen_w;
bi.bmiHeader.biHeight = -screen_h;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biBitCount = 24;
bi.bmiHeader.biCompression = BI_RGB;
bi.bmiHeader.biSizeImage = 0;
bi.bmiHeader.biXPelsPerMeter = 0;
bi.bmiHeader.biYPelsPerMeter = 0;
bi.bmiHeader.biClrUsed = 0;
bi.bmiHeader.biClrImportant = 0;
char* buffer = NULL;
HBITMAP hbmScreen = CreateDIBSection(hdcMemory, &bi, DIB_RGB_COLORS, (void**)(&buffer), 0, 0);
if (hbmScreen == NULL)
{
goto done;
}
// 将位图块传送到我们兼容的内存DC中
SelectObject(hdcMemory, hbmScreen);
if (!BitBlt(
hdcMemory, // 目的DC
0, 0, // 目的DC的 x,y 坐标
screen_w, screen_h, // 目的 DC 的宽高
hdcScreen, // 来源DC
0, 0, // 来源DC的 x,y 坐标
SRCCOPY)) // 粘贴方式
{
goto done;
}
screen_buffer = new char[screen_w*screen_h*3];
memcpy(screen_buffer, buffer, screen_w*screen_h*3);
// 清理资源
done:
DeleteObject(hbmScreen);
DeleteObject(hdcMemory);
ReleaseDC(NULL, hdcScreen);
}
xui_method_explain(xui_global, was_scolorstart, bool )( void )
{
return screen_buffer != NULL;
}
xui_method_explain(xui_global, set_scolorstart, void )( xui_syswnd* syswnd )
{
if (screen_buffer == NULL)
{
if (syswnd)
{
scolor_hwnd = syswnd->get_renderwnd()->get_hwnd();
}
else
{
extern HWND gHWND;
scolor_hwnd = gHWND;
}
::SetWindowPos(scolor_hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
capture_screen();
}
}
xui_colour pick_colour( s32 x, s32 y )
{
u32 index = (y * screen_w + x) * 3;
BYTE b = screen_buffer[index ];
BYTE g = screen_buffer[index+1];
BYTE r = screen_buffer[index+2];
return xui_colour(1.0f, r/255.0f, g/255.0f, b/255.0f);
}
xui_method_explain(xui_global, get_scolor, xui_colour )( void )
{
if (screen_buffer)
{
POINT pt;
GetCursorPos(&pt);
return pick_colour(pt.x, pt.y);
}
return xui_colour::transparent;
}
xui_method_explain(xui_global, get_scolor, std::vector<xui_colour> )( const xui_vector<s32>& sz )
{
std::vector<xui_colour> result;
result.resize(sz.w*sz.h, xui_colour::black);
if (screen_buffer)
{
POINT pt;
GetCursorPos(&pt);
s32 sc = pt.x - sz.w/2;
s32 sr = pt.y - sz.h/2;
for (s32 ir = 0; ir < sz.h; ++ir)
{
for (s32 ic = 0; ic < sz.w; ++ic)
{
s32 x = sc + ic;
s32 y = sr + ir;
u32 index = ir * sz.w + ic;
result[index] = pick_colour(x, y);
}
}
}
return result;
}
xui_method_explain(xui_global, set_scolorclose, void )( void )
{
if (screen_buffer)
{
if (scolor_hwnd)
::SetWindowPos(scolor_hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
//释放
delete [] screen_buffer;
screen_buffer = NULL;
scolor_hwnd = NULL;
}
}
/*
//system
*/
std::map<HWND, xui_syswnd*> syswnd_map;
LRESULT CALLBACK xui_syswnd_proc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam )
{
if (def_deviceproc(hwnd, message, wparam, lparam))
return 0;
switch (message)
{
case WM_CLOSE:
{
xui_syswnd* syswnd = xui_global::get_syswnd(hwnd);
if (syswnd)
{
xui_window* wnd = syswnd->get_popupctrl();
if (wnd->was_modal())
xui_desktop::get_ins()->del_modalwnd(wnd);
std::map<HWND, xui_syswnd*>::iterator itor = syswnd_map.find(hwnd);
if (itor != syswnd_map.end())
{
delete (*itor).second;
syswnd_map.erase(itor);
}
wnd->set_visible(false);
}
DestroyWindow(hwnd);
}
break;
case WM_SIZE:
{
xui_syswnd* syswnd = xui_global::get_syswnd(hwnd);
if (syswnd)
{
extern HWND gHWND;
RECT rect;
GetWindowRect(gHWND, &rect);
s32 title = GetSystemMetrics(SM_CYCAPTION);
s32 frame = GetSystemMetrics(SM_CXSIZEFRAME);
HWND hwnd = syswnd->get_renderwnd()->get_hwnd();
RECT window;
RECT client;
GetWindowRect(hwnd, &window);
GetClientRect(hwnd, &client);
s32 edgex = (window.right-window.left) - (client.right-client.left);
s32 edgey = (window.bottom-window.top) - (client.bottom-client.top);
s32 x = (window.left + edgex/2) - (rect.left + frame);
s32 y = (window.top + edgey/2) - (rect.top + title);
s32 w = client.right - client.left;
s32 h = client.bottom - client.top ;
xui_window* wnd = syswnd->get_popupctrl();
xui_method_ptrcall(wnd, set_owner )(NULL);
xui_method_ptrcall(wnd, set_renderpt)(xui_vector<s32>(x, y));
xui_method_ptrcall(wnd, set_rendersz)(xui_vector<s32>(w, h));
xui_method_ptrcall(wnd, set_owner )(syswnd);
}
}
break;
default:
return DefWindowProc(hwnd, message, wparam, lparam);
}
return 0;
}
void reg_syswndclass( void )
{
static bool has_register = false;
if (has_register == false)
{
WNDCLASS wc;
memset(&wc, 0, sizeof(WNDCLASS));
extern HINSTANCE gHINSTANCE;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wc.hInstance = gHINSTANCE;
wc.lpfnWndProc = xui_syswnd_proc;
wc.lpszClassName = L"xui_syswnd";
wc.lpszMenuName = NULL;
wc.style = CS_VREDRAW | CS_HREDRAW | CS_OWNDC;
if (RegisterClass(&wc))
has_register = true;
}
}
u08 VKToKey(WPARAM wParam)
{
switch (wParam)
{
case 'A': return KEY_A;
case 'B': return KEY_B;
case 'C': return KEY_C;
case 'D': return KEY_D;
case 'E': return KEY_E;
case 'F': return KEY_F;
case 'G': return KEY_G;
case 'H': return KEY_H;
case 'I': return KEY_I;
case 'J': return KEY_J;
case 'K': return KEY_K;
case 'L': return KEY_L;
case 'M': return KEY_M;
case 'N': return KEY_N;
case 'O': return KEY_O;
case 'P': return KEY_P;
case 'Q': return KEY_Q;
case 'R': return KEY_R;
case 'S': return KEY_S;
case 'T': return KEY_T;
case 'U': return KEY_U;
case 'V': return KEY_V;
case 'W': return KEY_W;
case 'X': return KEY_X;
case 'Y': return KEY_Y;
case 'Z': return KEY_Z;
case VK_ESCAPE: return KEY_ESC;
case VK_RETURN: return KEY_ENTER;
case VK_TAB: return KEY_TAB;
case VK_BACK: return KEY_BACK;
case VK_SHIFT: return KEY_SHIFT;
case VK_UP: return KEY_UARROW;
case VK_DOWN: return KEY_DARROW;
case VK_LEFT: return KEY_LARROW;
case VK_RIGHT: return KEY_RARROW;
case VK_HOME: return KEY_HOME;
case VK_END: return KEY_END;
case VK_DELETE: return KEY_DELETE;
case VK_F1: return KEY_F1;
case VK_F2: return KEY_F2;
case VK_F3: return KEY_F3;
case VK_F4: return KEY_F4;
case VK_F5: return KEY_F5;
case VK_F6: return KEY_F6;
case VK_F7: return KEY_F7;
case VK_F8: return KEY_F8;
case VK_F9: return KEY_F9;
default: return KEY_NONE;
}
}
xui_method_explain(xui_global, get_syswndmouse, xui_vector<s32> )( xui_syswnd* syswnd )
{
POINT pt;
GetCursorPos(&pt);
if (syswnd)
{
ScreenToClient(syswnd->get_renderwnd()->get_hwnd(), &pt);
}
else
{
extern HWND gHWND;
ScreenToClient(gHWND, &pt);
}
return xui_vector<s32>(pt.x, pt.y);
}
xui_method_explain(xui_global, set_syswndrect, void )( xui_syswnd* syswnd, const xui_rect2d<s32>& rt )
{
xui_vector<s32> pt = xui_desktop::get_ins()->get_mousedown();
xui_desktop::get_ins()->set_mouselast(pt);
xui_desktop::get_ins()->set_mousecurr(pt);
extern HWND gHWND;
RECT rect;
GetWindowRect(gHWND, &rect);
s32 title = GetSystemMetrics(SM_CYCAPTION);
s32 frame = GetSystemMetrics(SM_CXSIZEFRAME);
HWND hwnd = syswnd->get_renderwnd()->get_hwnd();
RECT window;
RECT client;
GetWindowRect(hwnd, &window);
GetClientRect(hwnd, &client);
s32 edgex = (window.right-window.left) - (client.right-client.left);
s32 edgey = (window.bottom-window.top) - (client.bottom-client.top);
s32 x = rect.left + frame + rt.ax - edgex/2;
s32 y = rect.top + title + rt.ay - edgey/2;
s32 w = rt.get_w() + edgex;
s32 h = rt.get_h() + edgey;
MoveWindow(hwnd, x, y, w, h, FALSE);
}
xui_method_explain(xui_global, get_syswndall, std::vector<xui_syswnd*> )( void )
{
std::vector<xui_syswnd*> vec;
for (std::map<HWND, xui_syswnd*>::iterator itor = syswnd_map.begin(); itor != syswnd_map.end(); ++itor)
{
vec.push_back((*itor).second);
}
return vec;
}
xui_method_explain(xui_global, get_syswnd, xui_syswnd* )( void* hwnd )
{
std::map<HWND, xui_syswnd*>::iterator itor = syswnd_map.find((HWND)hwnd);
if (itor != syswnd_map.end())
return (*itor).second;
return NULL;
}
xui_method_explain(xui_global, add_syswnd, xui_syswnd* )( xui_window* popupctrl, bool sizable )
{
reg_syswndclass();
DWORD style = WS_POPUP |
(sizable ? WS_THICKFRAME : WS_DLGFRAME);
extern HINSTANCE gHINSTANCE;
extern HWND gHWND;
HWND hwnd = CreateWindow(L"xui_syswnd", L"", style , 0, 0, 0, 0, gHWND, NULL, gHINSTANCE, NULL);
xui_syswnd* syswnd = new xui_syswnd(hwnd, popupctrl);
syswnd_map[hwnd] = syswnd;
set_syswndrect(syswnd, popupctrl->get_renderrt() + popupctrl->get_renderpt());
ShowWindow (hwnd, SW_NORMAL);
UpdateWindow (hwnd);
return syswnd;
}
xui_method_explain(xui_global, del_syswnd, void )( xui_syswnd* syswnd )
{
HWND hwnd = syswnd->get_renderwnd()->get_hwnd();
if (hwnd == scolor_hwnd)
set_scolorclose();
SendMessage(hwnd, WM_CLOSE, 0, 0);
}
xui_method_explain(xui_global, mod_syswnd, void )( xui_syswnd* syswnd )
{
extern HWND gHWND;
EnableWindow(gHWND, FALSE);
std::map<HWND, xui_syswnd*>::iterator itor = syswnd_map.begin();
for (; itor != syswnd_map.end(); ++itor)
{
HWND hwnd = (*itor).first;
xui_syswnd* swnd = (*itor).second;
EnableWindow(hwnd, (swnd == syswnd) ? TRUE : FALSE);
}
SetForegroundWindow(syswnd->get_renderwnd()->get_hwnd());
}
xui_method_explain(xui_global, res_syswnd, void )( void )
{
std::map<HWND, xui_syswnd*>::iterator itor = syswnd_map.begin();
for (; itor != syswnd_map.end(); ++itor)
{
HWND hwnd = (*itor).first;
EnableWindow(hwnd, TRUE);
}
extern HWND gHWND;
EnableWindow(gHWND, TRUE);
SetForegroundWindow(gHWND);
}
std::map<u32, HCURSOR> cursor_map;
xui_method_explain(xui_global, add_cursor, void )( u32 cursor, const std::wstring& filename )
{
std::map<u32, HCURSOR>::iterator itor = cursor_map.find(cursor);
if (itor != cursor_map.end())
::DestroyCursor((*itor).second);
cursor_map[cursor] = ::LoadCursorFromFile(filename.c_str());
}
xui_method_explain(xui_global, set_cursor, void )( u32 cursor )
{
std::map<u32, HCURSOR>::iterator itor = cursor_map.find(cursor);
if (itor != cursor_map.end())
{
::SetCursor((*itor).second);
}
else
{
switch (cursor)
{
case CURSOR_DEFAULT: ::SetCursor(::LoadCursor(NULL, IDC_ARROW )); break;
case CURSOR_NS: ::SetCursor(::LoadCursor(NULL, IDC_SIZENS )); break;
case CURSOR_WE: ::SetCursor(::LoadCursor(NULL, IDC_SIZEWE )); break;
case CURSOR_TEXT: ::SetCursor(::LoadCursor(NULL, IDC_IBEAM )); break;
case CURSOR_HAND: ::SetCursor(::LoadCursor(NULL, IDC_HAND )); break;
case CURSOR_DRAG: ::SetCursor(::LoadCursor(NULL, IDC_HAND )); break;
case CURSOR_FORBID: ::SetCursor(::LoadCursor(NULL, IDC_NO )); break;
}
}
}
xui_method_explain(xui_global, cpy_string, void )( const std::wstring& text )
{
HGLOBAL hGlobal = GlobalAlloc(GHND, (text.length() + 1) * sizeof(wchar_t));
wchar_t* buffer = (wchar_t*)GlobalLock(hGlobal);
wcscpy(buffer, text.c_str());
GlobalUnlock(hGlobal);
OpenClipboard(NULL);
EmptyClipboard();
SetClipboardData(CF_UNICODETEXT, hGlobal);
CloseClipboard();
}
xui_method_explain(xui_global, pst_string, std::wstring )( void )
{
std::wstring result;
OpenClipboard(NULL);
HGLOBAL hGlobal = GetClipboardData(CF_UNICODETEXT);
if (hGlobal)
{
wchar_t* buffer = (wchar_t*)GlobalLock(hGlobal);
result = std::wstring(buffer);
GlobalUnlock(hGlobal);
}
CloseClipboard();
return result;
}
bool def_deviceproc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam )
{
switch (message)
{
case WM_KILLFOCUS:
{
if (hwnd == scolor_hwnd)
{
xui_desktop::get_ins()->set_focusctrl(NULL);
::SetFocus(hwnd);
}
}
break;
case WM_MOUSEWHEEL:
{
xui_method_mouse args;
args.wheel = (s32)(s16)HIWORD(wparam) / 3;
xui_desktop::get_ins()->os_mousewheel(args);
}
break;
case WM_CAPTURECHANGED:
{
HWND other_hwnd = (HWND)lparam;
if (other_hwnd)
{
extern HWND gHWND;
if (xui_global::get_syswnd(other_hwnd) == NULL || other_hwnd != gHWND)
{
if (xui_desktop::get_ins()->get_catchctrl() != NULL)
{
POINT pt;
GetCursorPos(&pt);
ScreenToClient(hwnd, &pt);
xui_method_mouse args;
args.wparam = hwnd;
args.mouse = MB_L;
args.point = xui_vector<s32>((s32)pt.x, (s32)pt.y);
args.ctrl = false;
args.shift = false;
args.alt = false;
xui_desktop::get_ins()->os_mouserise(args);
}
}
}
}
break;
case WM_LBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_MBUTTONDOWN:
{
POINT pt;
GetCursorPos(&pt);
ScreenToClient(hwnd, &pt);
xui_method_mouse args;
args.wparam = hwnd;
args.point = xui_vector<s32>((s32)pt.x, (s32)pt.y);
args.ctrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
args.shift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
args.alt = (GetKeyState(VK_MENU) & 0x8000) != 0;
switch (message)
{
case WM_LBUTTONDOWN: args.mouse = MB_L; break;
case WM_RBUTTONDOWN: args.mouse = MB_R; break;
case WM_MBUTTONDOWN: args.mouse = MB_M; break;
}
xui_desktop::get_ins()->os_mousedown(args);
if (xui_desktop::get_ins()->get_catchctrl())
SetCapture(hwnd);
}
break;
case WM_MOUSEMOVE:
{
POINT pt;
GetCursorPos(&pt);
ScreenToClient(hwnd, &pt);
xui_method_mouse args;
args.wparam = hwnd;
args.point = xui_vector<s32>((s32)pt.x, (s32)pt.y);
args.ctrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
args.shift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
args.alt = (GetKeyState(VK_MENU) & 0x8000) != 0;
xui_desktop::get_ins()->os_mousemove(args);
}
break;
case WM_LBUTTONUP:
case WM_RBUTTONUP:
case WM_MBUTTONUP:
{
POINT pt;
GetCursorPos(&pt);
ScreenToClient(hwnd, &pt);
xui_method_mouse args;
args.wparam = hwnd;
args.point = xui_vector<s32>((s32)pt.x, (s32)pt.y);
args.ctrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
args.shift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
args.alt = (GetKeyState(VK_MENU) & 0x8000) != 0;
switch (message)
{
case WM_LBUTTONUP: args.mouse = MB_L; break;
case WM_RBUTTONUP: args.mouse = MB_R; break;
case WM_MBUTTONUP: args.mouse = MB_M; break;
}
xui_desktop::get_ins()->os_mouserise(args);
if (xui_desktop::get_ins()->get_catchctrl() == NULL)
ReleaseCapture();
}
break;
case WM_KEYDOWN:
{
xui_method_keybd args;
args.ctrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
args.shift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
args.alt = (GetKeyState(VK_MENU) & 0x8000) != 0;
args.kcode = VKToKey(wparam);
xui_desktop::get_ins()->os_keybddown(args);
}
break;
case WM_KEYUP:
{
xui_method_keybd args;
args.ctrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0;
args.shift = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
args.alt = (GetKeyState(VK_MENU) & 0x8000) != 0;
args.kcode = VKToKey(wparam);
xui_desktop::get_ins()->os_keybdrise(args);
}
break;
case WM_CHAR:
{
xui_desktop::get_ins()->os_keybdchar((u16)wparam);
}
break;
default:
return false;
}
return true;
}
/*
//modify
*/
std::wstring pathstyle_replace( const std::wstring& path, wchar_t src, wchar_t dst )
{
std::wstring result = path;
for (u32 i = 0; i < result.length(); ++i)
{
if (result[i] == src)
result[i] = dst;
}
return result;
}
#include <Shlobj.h>
#include <shellapi.h>
std::wstring g_workpath;
extern HWND gHWND;
xui_notify_vec notify_vec;
ULONG notify_id = 0;
xui_method_explain(xui_global, set_fwatchstart, void )( const std::wstring& path )
{
std::wstring temp = pathstyle_replace(path, L'/', L'\\');
ITEMIDLIST* pidlist;
SHParseDisplayName(temp.c_str(), NULL, &pidlist, SFGAO_CANCOPY, NULL);
SHChangeNotifyEntry shEntry;
shEntry.fRecursive = TRUE;
shEntry.pidl = pidlist;
LONG lEvent = SHCNE_CREATE|SHCNE_DELETE|SHCNE_MKDIR|SHCNE_RENAMEFOLDER|SHCNE_RENAMEITEM|SHCNE_RMDIR|SHCNE_UPDATEITEM;
notify_id = SHChangeNotifyRegister(gHWND, SHCNRF_InterruptLevel|SHCNRF_ShellLevel|SHCNRF_RecursiveInterrupt|SHCNRF_NewDelivery, lEvent, WM_USER+0x1000, 1, &shEntry);
}
xui_method_explain(xui_global, set_fwatchclose, void )( void )
{
SHChangeNotifyDeregister(notify_id);
notify_id = 0;
}
xui_method_explain(xui_global, add_fwatch, void )( u32 eventid, const std::wstring& srcpath, const std::wstring& dstpath )
{
xui_notify_info info;
info.eventid = eventid;
info.srcpath = pathstyle_replace(srcpath, L'\\', L'/');
info.dstpath = pathstyle_replace(dstpath, L'\\', L'/');
if (info.srcpath.length() > 0) info.srcpath.erase(0, g_workpath.length());
if (info.dstpath.length() > 0) info.dstpath.erase(0, g_workpath.length());
notify_vec.push_back(info);
}
xui_method_explain(xui_global, del_fwatch, void )( void )
{
notify_vec.clear();
}
xui_method_explain(xui_global, get_fwatch, const xui_notify_vec& )( void )
{
return notify_vec;
}
/*
//font
*/
std::vector<std::string> g_fontfilevec;
xui_method_explain(xui_global, get_fontfile, const std::string& )( s32 face )
{
return g_fontfilevec[face];
}
xui_method_explain(xui_global, add_fontfile, void )( const std::string& file )
{
g_fontfilevec.push_back(file);
}
/*
//file
*/
INT CALLBACK BrowseCallbackProc(HWND hwnd, UINT uMsg, LPARAM lp, LPARAM pData)
{
switch(uMsg)
{
case BFFM_INITIALIZED:
{
// WParam is TRUE since you are passing a path.
// It would be FALSE if you were passing a pidl.
TCHAR szDir[MAX_PATH]={0};
GetCurrentDirectory(sizeof(szDir)/sizeof(TCHAR), szDir);
SendMessage(hwnd, BFFM_SETSELECTION, TRUE, (LPARAM)szDir);
}
break;
}
return 0;
}
xui_method_explain(xui_global, get_fileline, std::string )( FILE* file )
{
std::string line;
while (1)
{
char c = 0;
fread(&c, 1, 1, file);
if (c == '\n' || c == 0)
break;
line.append(1, c);
}
return line;
}
xui_method_explain(xui_global, get_openpath, std::wstring )( void )
{
BROWSEINFO info;
memset(&info, 0, sizeof(BROWSEINFO));
info.hwndOwner = gHWND;
info.lpszTitle = L"Select Path";
info.ulFlags = BIF_USENEWUI;
info.lpfn = BrowseCallbackProc;
LPITEMIDLIST lpitem = SHBrowseForFolder(&info);
if (lpitem == NULL)
return std::wstring();
wchar_t buffer[MAX_PATH];
SHGetPathFromIDList(lpitem, buffer);
return std::wstring(buffer);
}
xui_method_explain(xui_global, get_workpath, std::wstring )( void )
{
if (g_workpath.empty())
{
wchar_t buffer[MAX_PATH];
GetCurrentDirectory(MAX_PATH, buffer);
g_workpath = pathstyle_replace(std::wstring(buffer), L'\\', L'/') + L"/";
}
return g_workpath;
}
xui_method_explain(xui_global, set_workpath, void )( const std::wstring& path )
{
std::wstring temp = pathstyle_replace(path, L'/', L'\\');
SetCurrentDirectory(temp.c_str());
g_workpath = pathstyle_replace(path, L'\\', L'/') + L"/";
}
xui_method_explain(xui_global, set_showfind, void )( const std::wstring& path )
{
std::wstring full = g_workpath + path;
std::wstring temp = L"/select," + pathstyle_replace(full, L'/', L'\\');
ShellExecute(gHWND, L"open", L"Explorer.exe", temp.c_str(), NULL, SW_SHOW);
}
xui_method_explain(xui_global, get_path, std::vector<std::wstring> )( const std::wstring& path )
{
std::vector<std::wstring> result;
WIN32_FIND_DATAW findData;
std::wstring full = (path.length() == 0) ? L"*.*" : path+L"/*.*";
std::wstring temp = pathstyle_replace(full, L'/', L'\\');
HANDLE handle = FindFirstFile(temp.c_str(), &findData);
if (handle != INVALID_HANDLE_VALUE)
{
if ((findData.cFileName[0] != L'.') &&
(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 &&
(findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) == 0)
result.push_back(std::wstring(findData.cFileName));
while (FindNextFile(handle, &findData))
{
if ((findData.cFileName[0] != L'.') &&
(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0 &&
(findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) == 0)
result.push_back(std::wstring(findData.cFileName));
}
FindClose(handle);
}
return result;
}
xui_method_explain(xui_global, get_file, std::vector<std::wstring> )( const std::wstring& path, const std::wstring& filter )
{
std::vector<std::wstring> result;
WIN32_FIND_DATAW findData;
std::wstring full = (path.length() == 0) ? filter : path+L"/"+filter;
std::wstring temp = pathstyle_replace(full, L'/', L'\\');
HANDLE handle = FindFirstFile(temp.c_str(), &findData);
if (handle != INVALID_HANDLE_VALUE)
{
if ((findData.cFileName[0] != L'.') &&
(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0 &&
(findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) == 0 &&
(findData.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) == 0)
result.push_back(std::wstring(findData.cFileName));
while (FindNextFile(handle, &findData))
{
if ((findData.cFileName[0] != L'.') &&
(findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0 &&
(findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) == 0 &&
(findData.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) == 0)
result.push_back(std::wstring(findData.cFileName));
}
FindClose(handle);
}
return result;
}
xui_method_explain(xui_global, has_path, bool )( const std::wstring& path )
{
WIN32_FIND_DATAW findData;
std::wstring full = (path.length() == 0) ? L"*.*" : path+L"/*.*";
std::wstring temp = pathstyle_replace(full, L'/', L'\\');
HANDLE handle = FindFirstFile(temp.c_str(), &findData);
if (handle != INVALID_HANDLE_VALUE)
{
FindClose(handle);
return true;
}
return false;
}
xui_method_explain(xui_global, has_file, bool )( const std::wstring& file )
{
std::string temp = unicode_to_ascii(file);
FILE* handle = fopen(temp.c_str(), "rb");
if (handle)
{
fclose(handle);
return true;
}
return false;
}
xui_method_explain(xui_global, add_path, bool )( const std::wstring& path )
{
std::wstring full = path;
std::wstring temp = pathstyle_replace(full, L'/', L'\\');
return CreateDirectory(temp.c_str(), NULL) != 0;
}
xui_method_explain(xui_global, del_file, bool )( const std::wstring& path )
{
std::wstring temp = pathstyle_replace(path+L'\0', L'/', L'\\');
SHFILEOPSTRUCTW fileOP;
memset(&fileOP, 0, sizeof(SHFILEOPSTRUCTW));
fileOP.hwnd = gHWND;
fileOP.wFunc = FO_DELETE;
fileOP.pFrom = temp.c_str();
fileOP.pTo = NULL;
fileOP.fFlags = FOF_ALLOWUNDO|FOF_NOCONFIRMATION;
return SHFileOperation(&fileOP) == 0;
}
xui_method_explain(xui_global, mov_file, bool )( const std::wstring& src, const std::wstring& dst )
{
std::wstring tempsrc = pathstyle_replace(src+L'\0', L'/', L'\\');
std::wstring tempdst = pathstyle_replace(dst+L'\0', L'/', L'\\');
SHFILEOPSTRUCTW fileOP;
memset(&fileOP, 0, sizeof(SHFILEOPSTRUCTW));
fileOP.hwnd = gHWND;
fileOP.wFunc = FO_MOVE;
fileOP.pFrom = tempsrc.c_str();
fileOP.pTo = tempdst.c_str();
fileOP.fFlags = FOF_NOCONFIRMATION|FOF_NOCONFIRMMKDIR;
return SHFileOperation(&fileOP) == 0;
}
xui_method_explain(xui_global, cpy_file, bool )( const std::wstring& src, const std::wstring& dst )
{
std::wstring tempsrc = pathstyle_replace(src+L'\0', L'/', L'\\');
std::wstring tempdst = pathstyle_replace(dst+L'\0', L'/', L'\\');
SHFILEOPSTRUCTW fileOP;
memset(&fileOP, 0, sizeof(SHFILEOPSTRUCTW));
fileOP.hwnd = gHWND;
fileOP.wFunc = FO_COPY;
fileOP.pFrom = tempsrc.c_str();
fileOP.pTo = tempdst.c_str();
fileOP.fFlags = FOF_NOCONFIRMATION|FOF_NOCONFIRMMKDIR;
return SHFileOperation(&fileOP) == 0;
}
xui_method_explain(xui_global, rna_file, bool )( const std::wstring& src, const std::wstring& dst )
{
std::wstring tempsrc = pathstyle_replace(src+L'\0', L'/', L'\\');
std::wstring tempdst = pathstyle_replace(dst+L'\0', L'/', L'\\');
SHFILEOPSTRUCTW fileOP;
memset(&fileOP, 0, sizeof(SHFILEOPSTRUCTW));
fileOP.hwnd = gHWND;
fileOP.wFunc = FO_RENAME;
fileOP.pFrom = tempsrc.c_str();
fileOP.pTo = tempdst.c_str();
fileOP.fFlags = FOF_NOCONFIRMATION;
return SHFileOperation(&fileOP) == 0;
} | [
"228966759@qq.com"
] | 228966759@qq.com |
e88e103c78d10e56cbe13cba994483da9706ca7f | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/library/expr_lt.h | 490c4fef14fd07a3610ccefb7f9edb1f0ef95452 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 2023-08-30T01:57:45.786981 | 2023-08-29T23:14:28 | 2023-08-29T23:14:28 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 2023-09-14T18:29:16 | 2018-04-15T02:49:20 | Lean | UTF-8 | C++ | false | false | 1,626 | h | /*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#pragma once
#include "kernel/expr.h"
#include "util/rb_map.h"
#include "kernel/local_ctx.h"
namespace lean {
/** \brief Total order on expressions.
\remark If \c use_hash is true, then we use the hash_code to
partially order expressions. Setting use_hash to false is useful
for testing the code.
\remark If lctx is not nullptr, then we use the local_decl index to compare local constants.
*/
bool is_lt(expr const & a, expr const & b, bool use_hash, local_ctx const * lctx = nullptr);
/** \brief Similar to is_lt, but universe level parameter names are ignored. */
bool is_lt_no_level_params(expr const & a, expr const & b);
inline bool is_hash_lt(expr const & a, expr const & b) { return is_lt(a, b, true); }
inline bool operator<(expr const & a, expr const & b) { return is_lt(a, b, true); }
inline bool operator>(expr const & a, expr const & b) { return is_lt(b, a, true); }
inline bool operator<=(expr const & a, expr const & b) { return !is_lt(b, a, true); }
inline bool operator>=(expr const & a, expr const & b) { return !is_lt(a, b, true); }
struct expr_quick_cmp {
typedef expr type;
int operator()(expr const & e1, expr const & e2) const { return is_lt(e1, e2, true) ? -1 : (e1 == e2 ? 0 : 1); }
};
struct expr_cmp_no_level_params { int operator()(expr const & e1, expr const & e2) const; };
template<typename T>
using rb_expr_map = rb_map<expr, T, expr_quick_cmp>;
typedef rb_tree<expr, expr_quick_cmp> rb_expr_tree;
}
| [
"leonardo@microsoft.com"
] | leonardo@microsoft.com |
94871f4b0d36995b63c75de248ecad53ab43c4ed | 59cacf6c27395c65935d852047c02744ca01a813 | /practice/practice/saving.cpp | 1e02e54216c7b24dc4581b1aa583f98bdeef1c60 | [] | no_license | zmd9220/object-trainning | 2131432f552520888e5d69d9cd1355a59da98854 | c0945710ec7ff3164bcdbcdf8f6864a0d67c7902 | refs/heads/master | 2021-07-15T17:45:06.763697 | 2020-05-20T15:04:07 | 2020-05-20T15:04:07 | 151,281,660 | 0 | 0 | null | 2020-05-20T15:04:08 | 2018-10-02T15:53:29 | null | UTF-8 | C++ | false | false | 303 | cpp | #include <iostream>
#include "saving.h"
using namespace std;
saving::saving()
{
daily_interest = 0.06;
balance = 10;
}
saving::saving(std::string a, std::string b, std::string c, double d)
{
setName(a);
setSSN(b);
setAddress(c);
}
void saving::setDailyInterest(double a)
{
daily_interest = a;
} | [
"31811018+zmd9220@users.noreply.github.com"
] | 31811018+zmd9220@users.noreply.github.com |
767bcdf598d837f9978911a41c5dd5c18f9c18a8 | 6bb45234fe96618d7e1cc0e64a3e0d0220ae8153 | /2_term/languages/bigint/big_integer.cpp | 5bd89961215abcb495c16e07ae518bd0c87f5d9c | [] | no_license | artemohanjanyan/university | 032f94862a22066070ca777063d13fc51adfc08b | 1a6b0406798e1aa862227751f7a0b9d81f0f1068 | refs/heads/master | 2022-07-19T18:59:17.177990 | 2019-06-03T15:06:09 | 2019-06-03T22:27:01 | 58,167,891 | 6 | 4 | null | 2022-07-07T20:58:25 | 2016-05-05T23:55:37 | C++ | UTF-8 | C++ | false | false | 10,897 | cpp | #include "big_integer.h"
#include <cstring>
#include <stdexcept>
#include <sstream>
#include <algorithm>
#include <limits>
big_integer::big_integer() : digits(0), sign(plus)
{}
big_integer::big_integer(big_integer const& other): digits(other.digits), sign(other.sign)
{}
// Assuming sizeof(int) <= sizeof(size_t)
big_integer::big_integer(int a) : digits(a == 0 ? 0 : 1, static_cast<size_t>(a)), sign(a >= 0 ? plus : minus)
{
if (a < 0)
digits[0] = -digits[0];
}
big_integer::big_integer(size_t a) : digits(a == 0 ? 0 : 1, a), sign(plus)
{}
big_integer::big_integer(std::string const& str) : big_integer()
{
for (size_t i = (str[0] == '-' ? 1 : 0); i < str.length(); ++i)
{
*this *= 10;
*this += str[i] - '0';
}
if (str[0] == '-')
*this *= -1;
}
big_integer::~big_integer()
{}
big_integer& big_integer::operator=(big_integer const& other)
{
digits = other.digits;
sign = other.sign;
return *this;
}
void big_integer::pop_zeros()
{
while (digits.size() > 0 && digits.back() == 0)
digits.pop_back();
}
void big_integer::add(big_integer const& other)
{
if (digits.size() < other.digits.size())
digits.resize(other.digits.size());
size_t carry = 0;
for (size_t i = 0; i < other.digits.size(); ++i)
digits[i] = add(digits[i], other.digits[i], carry);
for (size_t i = other.digits.size(); i < digits.size(); ++i)
digits[i] = add(digits[i], 0, carry);
if (carry > 0)
digits.push_back(carry);
}
// Returns |*this| < |other|
bool big_integer::sub(big_integer const& other)
{
bool is_less = false;
if (is_zero() && other.is_zero())
is_less = false;
else if (digits.size() != other.digits.size())
is_less = digits.size() < other.digits.size();
else
for (size_t i = digits.size(); i > 0; --i)
if (digits[i - 1] != other.digits[i - 1])
{
is_less = digits[i - 1] < other.digits[i - 1];
break;
}
big_integer const *subtrahend = this, *subtractor = &other;
if (is_less)
std::swap(subtrahend, subtractor);
if (subtrahend->digits.size() > digits.size())
digits.resize(subtrahend->digits.size());
size_t carry = 0;
for (size_t i = 0; i < subtractor->digits.size(); ++i)
digits[i] = sub(subtrahend->digits[i], subtractor->digits[i], carry);
for (size_t i = subtractor->digits.size(); i < digits.size(); ++i)
digits[i] = sub(subtrahend->digits[i], 0, carry);
pop_zeros();
return is_less;
}
big_integer& big_integer::operator+=(big_integer const& rhs)
{
if (sign == rhs.sign)
add(rhs);
else
sign ^= sub(rhs);
return *this;
}
big_integer& big_integer::operator-=(big_integer const& rhs)
{
if (sign == rhs.sign)
sign ^= sub(rhs);
else
add(rhs);
return *this;
}
big_integer& big_integer::operator*=(big_integer const& rhs)
{
if (rhs.sign == minus)
sign ^= 1;
digits.resize(digits.size() + rhs.digits.size());
for (size_t i = digits.size() - rhs.digits.size(); i > 0; --i)
{
size_t hi = 0, carry = 0, cur_digit = digits[i - 1];
digits[i - 1] = 0;
for (size_t j = 0; j < rhs.digits.size(); ++j)
{
digits[i - 1 + j] = add(digits[i - 1 + j], mul(cur_digit, rhs.digits[j], hi), carry);
carry += hi;
}
for (size_t j = rhs.digits.size(); carry != 0; ++j)
digits[i - 1 + j] = add(digits[i - 1 + j], 0, carry);
}
pop_zeros();
return *this;
}
size_t big_integer::get_digit(size_t i)
{
if (i < digits.size())
return digits[i];
else
return 0;
}
int big_integer::words_to_bits(size_t n)
{
return static_cast<int>(std::numeric_limits<size_t>::digits * n);
}
big_integer& big_integer::operator/=(big_integer other)
{
//if (other.is_zero())
// throw std::runtime_error("division by zero");
int new_sign = sign;
if (other.sign == minus)
new_sign ^= 1;
sign = other.sign = plus;
if (*this < other)
return *this = 0;
int k = 0;
size_t back_digit = other.digits.back();
while (back_digit <= std::numeric_limits<size_t>::max() / 2)
{
++k;
back_digit <<= 1;
}
*this <<= k;
other <<= k;
size_t m = digits.size() - other.digits.size();
size_t n = other.digits.size();
big_integer quotient;
quotient.digits.resize(m + 1);
if (*this >= (other << words_to_bits(m)))
{
quotient.digits[m] = 1;
*this -= (other << words_to_bits(m));
}
for (size_t j = m; j > 0; --j)
{
quotient.digits[j - 1] = div(get_digit(n + j - 1), get_digit(n + j - 2), other.digits[n - 1]);
*this -= quotient.digits[j - 1] * (other << words_to_bits(j - 1));
while (*this < 0)
{
--quotient.digits[j - 1];
*this += (other << words_to_bits(j - 1));
}
}
quotient.sign = new_sign;
quotient.pop_zeros();
return *this = quotient;
}
big_integer& big_integer::operator%=(big_integer const& rhs)
{
return *this -= (*this / rhs * rhs);
}
digit_array big_integer::to_twos_complement(size_t length) const
{
digit_array vec = digits;
vec.resize(length);
if (sign == minus)
{
size_t carry = 0;
for (size_t i = 0; i < vec.size(); ++i)
vec[i] = add(~vec[i], i == 0, carry);
}
return vec;
}
big_integer big_integer::from_twos_complement(const digit_array& a)
{
big_integer num;
num.digits = a;
if ((a.back() >> (std::numeric_limits<size_t>::digits - 1)) == 1)
{
size_t carry = 1;
for (size_t i = 0; i < num.digits.size(); ++i)
num.digits[i] = add(~num.digits[i], 0, carry);
num.sign = minus;
}
num.pop_zeros();
return num;
}
big_integer& big_integer::operator&=(big_integer const& rhs)
{
size_t size = std::max(digits.size(), rhs.digits.size()) + 1;
auto vec1 = to_twos_complement(size);
auto vec2 = rhs.to_twos_complement(size);
for (size_t i = 0; i < size; ++i)
vec1[i] &= vec2[i];
return *this = from_twos_complement(vec1);
}
big_integer& big_integer::operator|=(big_integer const& rhs)
{
size_t size = std::max(digits.size(), rhs.digits.size()) + 1;
auto vec1 = to_twos_complement(size);
auto vec2 = rhs.to_twos_complement(size);
for (size_t i = 0; i < size; ++i)
vec1[i] |= vec2[i];
return *this = from_twos_complement(vec1);
}
big_integer& big_integer::operator^=(big_integer const& rhs)
{
size_t size = std::max(digits.size(), rhs.digits.size()) + 1;
auto vec1 = to_twos_complement(size);
auto vec2 = rhs.to_twos_complement(size);
for (size_t i = 0; i < size; ++i)
vec1[i] ^= vec2[i];
return *this = from_twos_complement(vec1);
}
big_integer& big_integer::operator<<=(int rhs)
{
size_t shift_n = static_cast<size_t>(rhs / std::numeric_limits<size_t>::digits); // word_shift_n
auto vector = to_twos_complement(digits.size() + shift_n + 1);
for (size_t i = digits.size(); i > 0; --i)
vector[i + shift_n - 1] = vector[i - 1];
for (size_t i = 0; i < shift_n; ++i)
vector[i] = 0;
shift_n = rhs - shift_n * std::numeric_limits<size_t>::digits; // bit_shift_n
if (shift_n != 0)
{
for (size_t i = vector.size(); i > 1; --i)
vector[i - 1] = ((vector[i - 1] << shift_n) | (vector[i - 2] >> (std::numeric_limits<size_t>::digits - shift_n)));
vector[0] <<= shift_n;
}
return *this = from_twos_complement(vector);
}
big_integer& big_integer::operator>>=(int rhs)
{
size_t shift_n = static_cast<size_t>(rhs / std::numeric_limits<size_t>::digits); // word_shift_n
auto vector = to_twos_complement(digits.size() + 1);
size_t pad = vector.back();
for (size_t i = 0; i < digits.size() - shift_n; ++i)
vector[i] = vector[i + shift_n];
for (size_t i = digits.size() - shift_n; i < vector.size(); ++i)
vector[i] = pad;
shift_n = rhs - shift_n * std::numeric_limits<size_t>::digits; // bit_shift_n
if (shift_n != 0)
{
for (size_t i = 0; i < vector.size() - 1; ++i)
vector[i] = ((vector[i] >> shift_n) | (vector[i + 1] << (std::numeric_limits<size_t>::digits - shift_n)));
vector.back() = pad;
}
return *this = from_twos_complement(vector);
}
big_integer big_integer::operator+() const
{
return *this;
}
big_integer big_integer::operator-() const
{
return *this * -1;
}
big_integer big_integer::operator~() const
{
auto vec = to_twos_complement(digits.size() + 1);
for (size_t i = 0; i < vec.size(); ++i)
vec[i] = ~vec[i];
return from_twos_complement(vec);
}
big_integer& big_integer::operator++()
{
return *this += 1;
}
big_integer big_integer::operator++(int)
{
big_integer const r = *this;
++*this;
return r;
}
big_integer& big_integer::operator--()
{
return *this -= 1;
}
big_integer big_integer::operator--(int)
{
big_integer const r = *this;
--*this;
return r;
}
big_integer operator+(big_integer a, big_integer const& b)
{
return a += b;
}
big_integer operator-(big_integer a, big_integer const& b)
{
return a -= b;
}
big_integer operator*(big_integer a, big_integer const& b)
{
return a *= b;
}
big_integer operator/(big_integer a, big_integer const& b)
{
return a /= b;
}
big_integer operator%(big_integer a, big_integer const& b)
{
return a %= b;
}
big_integer operator&(big_integer a, big_integer const& b)
{
return a &= b;
}
big_integer operator|(big_integer a, big_integer const& b)
{
return a |= b;
}
big_integer operator^(big_integer a, big_integer const& b)
{
return a ^= b;
}
big_integer operator<<(big_integer a, int b)
{
return a <<= b;
}
big_integer operator>>(big_integer a, int b)
{
return a >>= b;
}
bool big_integer::is_zero() const
{
return digits.size() == 0;
}
bool operator==(big_integer const& a, big_integer const& b)
{
if (a.is_zero() && b.is_zero())
return true;
return a.sign == b.sign && a.digits == b.digits;
}
bool operator!=(big_integer const& a, big_integer const& b)
{
return !(a == b);
}
bool operator<(big_integer const& a, big_integer const& b)
{
if (a.is_zero() && b.is_zero())
return false;
if (a.sign != b.sign)
return a.sign < b.sign;
if (a.digits.size() != b.digits.size())
return a.digits.size() < b.digits.size();
for (size_t i = a.digits.size(); i > 0; --i)
if (a.digits[i - 1] != b.digits[i - 1])
return a.digits[i - 1] < b.digits[i - 1];
return false;
}
bool operator>(big_integer const& a, big_integer const& b)
{
return !(a <= b);
}
bool operator<=(big_integer const& a, big_integer const& b)
{
if (a.is_zero() && b.is_zero())
return true;
if (a.sign != b.sign)
return a.sign <= b.sign;
if (a.digits.size() != b.digits.size())
return a.digits.size() <= b.digits.size();
for (size_t i = a.digits.size(); i > 0; --i)
if (a.digits[i - 1] != b.digits[i - 1])
return a.digits[i - 1] <= b.digits[i - 1];
return true;
}
bool operator>=(big_integer const& a, big_integer const& b)
{
return !(a < b);
}
std::string to_string(big_integer a)
{
if (a.is_zero())
return "0";
bool is_negative = (a.sign == big_integer::minus);
if (is_negative)
a *= -1;
std::string str;
while (a != 0)
{
big_integer const mod = a % 10;
if (mod != 0)
str.append(1, char(mod.digits[0] + '0'));
else
str.append(1, '0');
a /= 10;
}
if (is_negative)
str.append("-");
std::reverse(str.begin(), str.end());
return str;
}
std::ostream& operator<<(std::ostream& s, big_integer const& a)
{
return s << to_string(a);
}
| [
"artemohanjanyan@gmail.com"
] | artemohanjanyan@gmail.com |
5d18003ec3eb6acf41ba0325811842507c011a91 | eb6afcb54d538b0771904858756e1fffb828b913 | /VideoXpertSdk/Include/VxNewNotification.h | 84f17ab95f46e5aea470630243881f02a880bd65 | [] | no_license | lexuanquyen/VideoXpertSdk | 8878964b12093e09104e6b7e1970af941583dffc | 26293e5342b0b01311c191213b4ad76f046e78b7 | refs/heads/master | 2022-10-11T03:36:53.088532 | 2020-06-04T20:49:39 | 2020-06-04T20:49:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,911 | h | #ifndef VxNewNotification_h__
#define VxNewNotification_h__
#include "VxPrimitives.h"
#include "VxUtilities.h"
#include "VxMacros.h"
namespace VxSdk {
/// <summary>
/// Represents a new notification configuration for a situation.
/// </summary>
struct VxNewNotification {
public:
/// <summary>
/// Initializes a new instance of the <see cref="VxNewNotification"/> struct.
/// </summary>
VxNewNotification() {
Clear();
}
/// <summary>
/// Initializes a new instance of the <see cref="VxNewNotification"/> struct.
/// </summary>
/// <param name="ref">The reference.</param>
VxNewNotification(const VxNewNotification& ref) {
this->roleIdSize = ref.roleIdSize;
this->roleIds = nullptr;
if (ref.roleIds != nullptr) {
this->roleIds = new char*[ref.roleIdSize];
for (int i = 0; i < ref.roleIdSize; i++) {
const size_t len = strlen(ref.roleIds[i]) + 1;
this->roleIds[i] = new char[len];
Utilities::StrCopySafe(this->roleIds[i], ref.roleIds[i], len);
}
}
}
/// <summary>
/// Finalizes an instance of the <see cref="VxNewNotification"/> class.
/// </summary>
~VxNewNotification() {
Clear();
}
/// <summary>
/// Clears this instance.
/// </summary>
void Clear() {
this->roleIds = nullptr;
this->roleIdSize = 0;
}
public:
/// <summary>
/// The ids for each role that should receive this notification.
/// </summary>
char** roleIds;
/// <summary>
/// The size of <see cref="roleIds"/>.
/// </summary>
int roleIdSize;
};
}
#endif // VxNewNotification_h__ | [
"Zach.Moore@schneider-electric.com"
] | Zach.Moore@schneider-electric.com |
76aa6d009743255c00a8d5da87b0b1376e951b15 | b452e6308d47ba80161aed1bb5129ef69aa541f2 | /rush/Game.cpp | bb1b8d12be7586d03368178ae99921cc754b6991 | [] | no_license | AlexTiniakov/Piscine_CPP | 3dbc27c24c6ad5e634063ddb90b8f3a29d9730cd | 80cef87fde790d25ef6740da9083e80f12bb7413 | refs/heads/master | 2020-03-30T11:08:19.383653 | 2018-10-15T09:00:31 | 2018-10-15T09:00:31 | 151,155,242 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,138 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Game.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: otiniako <otiniako@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/10/07 17:24:01 by otiniako #+# #+# */
/* Updated: 2018/10/07 23:00:47 by otiniako ### ########.fr */
/* */
/* ************************************************************************** */
#include "Game.hpp"
int Game::_width = 100;
int Game::_hight = 50;
Game::Game()
{
win = newwin(_hight, _width, 0, 0);
initscr();
noecho();
timeout(13);
keypad(stdscr, TRUE);
curs_set(0);
set_random();
}
Game::~Game()
{
endwin();
}
void Game::set_random()
{
int i = -1;
int j;
while (++i < 15)
{
_enemies[i]._j = rand() % 48 + 1;
j = 0;
while (++j < i)
{
if (_enemies[i]._j == _enemies[j]._j)
{
_enemies[i]._j += 2;
_enemies[i]._j %= 48 + 1;
j = 0;
}
}
}
}
int Game::ProcessEvents()
{
int key;
key = getch();
if (key == 259 && _player.y > 0) //up
{
_player.print_space();
_player.y--;
}
else if (key == 258 && _player.y < 50) //down
{
_player.print_space();
_player.y++;
}
else if (key == 260 && _player.x > 0) //left
{
_player.print_space();
_player.x--;
}
else if (key == 261 && _player.x < 100) //right
{
_player.print_space();
_player.x++;
}
else if (key == 27)
return (-1);
else if (key == 32)
_player.fight();
refresh();
return (0);
}
int Game::Update()
{
int i = -1;
int j;
_player.print_pl();
while (++i < 15)
if (_enemies[i].check_deth(_player))
return (-1);
i = -1;
while (++i < 100)
{
if (_player.bul[i].i == 1)
{
j = -1;
while (++j < 15)
if (_player.bul[i]._y == _enemies[j].y && _player.bul[i]._x == _enemies[j].x)
{
_player.bul[i].i = -1;
_enemies[j].x = 100;
}
_player.bul[i].check_f();
}
}
return (0);
}
void Game::Loop()
{
while (1)
{
if (ProcessEvents() == -1)
break ;
if (Update() == -1)
break ;
//Render();
}
}
int Game::get_y_i(int i)
{
return this->_enemies[i].y;
}
int Game::get_x_i(int i)
{
return this->_enemies[i].x;
}
void Game::set_x_i(int i, int x)
{
this->_enemies[i].x = x;
} | [
"otiniako@e2r1p6.unit.ua"
] | otiniako@e2r1p6.unit.ua |
eccb2ebc57d643a118ce216caccfb373c409e919 | 746b4181b1255b21f95b93b32377a85489827fb6 | /bloquearchivo.cpp | ef5e34c774d007b0e6416c355a0e1f172a79e4a2 | [] | no_license | renanz/DiscoVirtual | b69fc4273afaf31ca1896e0170d98d249dc0d764 | ca69ff8b039cb35757578a0a6562e95254c6ddba | refs/heads/master | 2021-01-22T10:28:31.643407 | 2017-06-13T21:18:28 | 2017-06-13T21:18:28 | 92,644,227 | 0 | 0 | null | 2017-05-28T06:32:31 | 2017-05-28T06:32:31 | null | UTF-8 | C++ | false | false | 2,093 | cpp | #include "BloqueArchivo.h"
BloqueArchivo::BloqueArchivo(char * nom, char * cont, int pb, int ub, int tam, Archivo * ar){
nombre = nom;
contenido = cont;
primerBloque = pb;
ultimoBloque = ub;
tamanoBloque = tam;
this->ar = ar;
}
char * BloqueArchivo::getNombre(){
return nombre;
}
char * BloqueArchivo::getContenido(){
return contenido;
}
int BloqueArchivo::getPrimerBloque(){
return primerBloque;
}
int BloqueArchivo::getUltimoBloque(){
return ultimoBloque;
}
int BloqueArchivo::getTamanoBloque(){
return tamanoBloque;
}
void BloqueArchivo::setContenido(char * contenido){
this->contenido = contenido;
}
char * BloqueArchivo::bloqueArchivoToChar(){
int tam = 20, pos = 0;
tam += (strlen(nombre) + strlen(contenido));
char * data = new char[tam];
int tamNombre = strlen(nombre), tamContenido = strlen(contenido);
memcpy(&(data[pos]), &tamNombre, 4);
pos += 4;
memcpy(&(data[pos]), nombre, tamNombre);
pos += tamNombre;
memcpy(&(data[pos]), &primerBloque, 4);
pos += 4;
memcpy(&(data[pos]), &ultimoBloque, 4);
pos += 4;
memcpy(&(data[pos]), &tamanoBloque, 4);
pos += 4;
memcpy(&(data[pos]), &tamContenido, 4);
pos += 4;
memcpy(&(data[pos]), contenido, tamContenido);
return data;
}
void BloqueArchivo::guardar(){
char * data = bloqueArchivoToChar();
int longitud = (ultimoBloque-primerBloque+1) * tamanoBloque;
ar->escribir(primerBloque*tamanoBloque, data, longitud);
}
void BloqueArchivo::initFromChar(char * data){
int pos = 0, tamNombre = 0, tamContenido = 0;
memcpy(&tamNombre, &(data[pos]), 4);
pos += 4;
nombre = new char[tamNombre];
memcpy(nombre, &(data[pos]), tamNombre);
pos += tamNombre;
memcpy(&primerBloque, &(data[pos]), 4);
pos += 4;
memcpy(&ultimoBloque, &(data[pos]), 4);
pos += 4;
memcpy(&tamanoBloque, &(data[pos]), 4);
pos += 4;
memcpy(&tamContenido, &(data[pos]), 4);
pos += 4;
contenido = new char[tamContenido];
memcpy(contenido, &(data[pos]), tamContenido);
}
| [
"Leonardo José Vásquez Vindel"
] | Leonardo José Vásquez Vindel |
716a7ca2d461e45ff6363179e10a0e45cef871a4 | 50eb6a64e33cd5a561b85acc94614334ac4aec66 | /CatalanitzadorPerAlWindows/UI/Dialogs/DownloadErrorDlgUI.h | 2e976cba7939a11bdc5542ccb989965e0d80ac5d | [] | no_license | Softcatala/Catalanitzador | 4024fc98b85047e4fefc2123ac98b53fcf3774e1 | 9466d699f6b25c45d16331057f8b454dcc2ae812 | refs/heads/master | 2021-12-23T06:19:34.760551 | 2021-12-11T14:43:06 | 2021-12-11T14:43:06 | 2,496,055 | 11 | 1 | null | 2020-06-24T10:31:54 | 2011-10-01T18:44:34 | C++ | UTF-8 | C++ | false | false | 1,092 | h | /*
* Copyright (C) 2012 Jordi Mas i Hernàndez <jmas@softcatala.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
#pragma once
#include "DlgUI.h"
class DownloadErrorDlgUI : public DlgUI
{
public:
DownloadErrorDlgUI(wstring action_name);
virtual LPCTSTR GetResourceTemplate() {return MAKEINTRESOURCE(IDD_DOWNLOADERROR);}
virtual void _onInitDialog();
private:
wstring m_action_name;
};
| [
"jmas@softcatala.org"
] | jmas@softcatala.org |
51a9c28b6b6278e45c6f4900719afbeefbdc9e1b | 440855a2792c03305350f1779b55509b46933a0b | /Source/ToonTanks/PlayerControllers/PlayerControllerBase.h | 47771355105a5c28beabebba5eca23b85ed04633 | [] | no_license | dynamiquel/Udemy-ToonTanks | 2eae327a1ea87de9d3f67d951c9279e9773cdbca | 9079f1132fd54d69938e1491aa4645399232c2b0 | refs/heads/master | 2022-12-06T08:20:27.998453 | 2020-09-03T21:59:05 | 2020-09-03T21:59:05 | 292,688,256 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "PlayerControllerBase.generated.h"
/**
*
*/
UCLASS()
class TOONTANKS_API APlayerControllerBase : public APlayerController
{
GENERATED_BODY()
public:
void SetPlayerEnabledState(bool SetPlayerEnable);
};
| [
"50085636+dynamiquel@users.noreply.github.com"
] | 50085636+dynamiquel@users.noreply.github.com |
1d69970116c57523c2952c9123817d9140f1d257 | 9bf7ee5fad1b10d70a52dc345d18734fdaf8bb80 | /Assignment 9/pet.h | f60185632a77fa38211af09201cf0b27504995d2 | [] | no_license | peter0512lee/YZU-Programming-Lab-II | c308e6c1f720e2a8c6161d90fc51abfe6e3bfd8c | 86a96bcd0829c5165b663e8c754e412a4d1d9f01 | refs/heads/master | 2022-10-10T02:46:41.620994 | 2020-06-10T04:58:44 | 2020-06-10T04:58:44 | 271,182,890 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 552 | h | #pragma once
#ifndef PET_H
#define PET_H
#include<iostream>
#include<string>
using namespace std;
class pet
{
public:
pet(string s) : name(s) {}
~pet() {}
string Name()
{
return name;
}
virtual string makeSound()
{
return "";
}
private:
string name;
};
class cat : public pet
{
public:
cat(string s) : pet(s) {}
~cat() {}
string makeSound()
{
return "miau";
}
private:
};
class dog : public pet
{
public:
dog(string s) : pet(s) {}
~dog() {}
string makeSound()
{
return "won";
}
private:
};
#endif // !PET_H
| [
"peter0512lee@gmail.com"
] | peter0512lee@gmail.com |
0b571303d8aaab80d4a97e0d419de7f72054cac0 | 38c10c01007624cd2056884f25e0d6ab85442194 | /net/cert/asn1_util.cc | 4bc37a677578973b31714cf3bbac3c79d38d8c86 | [
"BSD-3-Clause"
] | permissive | zenoalbisser/chromium | 6ecf37b6c030c84f1b26282bc4ef95769c62a9b2 | e71f21b9b4b9b839f5093301974a45545dad2691 | refs/heads/master | 2022-12-25T14:23:18.568575 | 2016-07-14T21:49:52 | 2016-07-23T08:02:51 | 63,980,627 | 0 | 2 | BSD-3-Clause | 2022-12-12T12:43:41 | 2016-07-22T20:14:04 | null | UTF-8 | C++ | false | false | 9,921 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/cert/asn1_util.h"
namespace net {
namespace asn1 {
bool ParseElement(base::StringPiece* in,
unsigned tag_value,
base::StringPiece* out,
unsigned *out_header_len) {
const uint8_t* data = reinterpret_cast<const uint8_t*>(in->data());
// We don't support kAny and kOptional at the same time.
if ((tag_value & kAny) && (tag_value & kOptional))
return false;
if (in->empty() && (tag_value & kOptional)) {
if (out_header_len)
*out_header_len = 0;
if (out)
*out = base::StringPiece();
return true;
}
if (in->size() < 2)
return false;
if (tag_value != kAny &&
static_cast<unsigned char>(data[0]) != (tag_value & 0xff)) {
if (tag_value & kOptional) {
if (out_header_len)
*out_header_len = 0;
if (out)
*out = base::StringPiece();
return true;
}
return false;
}
size_t len = 0;
if ((data[1] & 0x80) == 0) {
// short form length
if (out_header_len)
*out_header_len = 2;
len = static_cast<size_t>(data[1]) + 2;
} else {
// long form length
const unsigned num_bytes = data[1] & 0x7f;
if (num_bytes == 0 || num_bytes > 2)
return false;
if (in->size() < 2 + num_bytes)
return false;
len = data[2];
if (num_bytes == 2) {
if (len == 0) {
// the length encoding must be minimal.
return false;
}
len <<= 8;
len += data[3];
}
if (len < 128) {
// the length should have been encoded in short form. This distinguishes
// DER from BER encoding.
return false;
}
if (out_header_len)
*out_header_len = 2 + num_bytes;
len += 2 + num_bytes;
}
if (in->size() < len)
return false;
if (out)
*out = base::StringPiece(in->data(), len);
in->remove_prefix(len);
return true;
}
bool GetElement(base::StringPiece* in,
unsigned tag_value,
base::StringPiece* out) {
unsigned header_len;
if (!ParseElement(in, tag_value, out, &header_len))
return false;
if (out)
out->remove_prefix(header_len);
return true;
}
// SeekToSPKI changes |cert| so that it points to a suffix of the
// TBSCertificate where the suffix begins at the start of the ASN.1
// SubjectPublicKeyInfo value.
static bool SeekToSPKI(base::StringPiece* cert) {
// From RFC 5280, section 4.1
// Certificate ::= SEQUENCE {
// tbsCertificate TBSCertificate,
// signatureAlgorithm AlgorithmIdentifier,
// signatureValue BIT STRING }
// TBSCertificate ::= SEQUENCE {
// version [0] EXPLICIT Version DEFAULT v1,
// serialNumber CertificateSerialNumber,
// signature AlgorithmIdentifier,
// issuer Name,
// validity Validity,
// subject Name,
// subjectPublicKeyInfo SubjectPublicKeyInfo,
base::StringPiece certificate;
if (!GetElement(cert, kSEQUENCE, &certificate))
return false;
// We don't allow junk after the certificate.
if (!cert->empty())
return false;
base::StringPiece tbs_certificate;
if (!GetElement(&certificate, kSEQUENCE, &tbs_certificate))
return false;
if (!GetElement(&tbs_certificate,
kOptional | kConstructed | kContextSpecific | 0,
NULL)) {
return false;
}
// serialNumber
if (!GetElement(&tbs_certificate, kINTEGER, NULL))
return false;
// signature
if (!GetElement(&tbs_certificate, kSEQUENCE, NULL))
return false;
// issuer
if (!GetElement(&tbs_certificate, kSEQUENCE, NULL))
return false;
// validity
if (!GetElement(&tbs_certificate, kSEQUENCE, NULL))
return false;
// subject
if (!GetElement(&tbs_certificate, kSEQUENCE, NULL))
return false;
*cert = tbs_certificate;
return true;
}
bool ExtractSPKIFromDERCert(base::StringPiece cert,
base::StringPiece* spki_out) {
if (!SeekToSPKI(&cert))
return false;
if (!ParseElement(&cert, kSEQUENCE, spki_out, NULL))
return false;
return true;
}
bool ExtractSubjectPublicKeyFromSPKI(base::StringPiece spki,
base::StringPiece* spk_out) {
// From RFC 5280, Section 4.1
// SubjectPublicKeyInfo ::= SEQUENCE {
// algorithm AlgorithmIdentifier,
// subjectPublicKey BIT STRING }
//
// AlgorithmIdentifier ::= SEQUENCE {
// algorithm OBJECT IDENTIFIER,
// parameters ANY DEFINED BY algorithm OPTIONAL }
// Step into SubjectPublicKeyInfo sequence.
base::StringPiece spki_contents;
if (!asn1::GetElement(&spki, asn1::kSEQUENCE, &spki_contents))
return false;
// Step over algorithm field (a SEQUENCE).
base::StringPiece algorithm;
if (!asn1::GetElement(&spki_contents, asn1::kSEQUENCE, &algorithm))
return false;
// Extract the subjectPublicKey field.
if (!asn1::GetElement(&spki_contents, asn1::kBITSTRING, spk_out))
return false;
return true;
}
bool ExtractCRLURLsFromDERCert(base::StringPiece cert,
std::vector<base::StringPiece>* urls_out) {
urls_out->clear();
std::vector<base::StringPiece> tmp_urls_out;
if (!SeekToSPKI(&cert))
return false;
// From RFC 5280, section 4.1
// TBSCertificate ::= SEQUENCE {
// ...
// subjectPublicKeyInfo SubjectPublicKeyInfo,
// issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
// subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
// extensions [3] EXPLICIT Extensions OPTIONAL
// subjectPublicKeyInfo
if (!GetElement(&cert, kSEQUENCE, NULL))
return false;
// issuerUniqueID
if (!GetElement(&cert, kOptional | kConstructed | kContextSpecific | 1, NULL))
return false;
// subjectUniqueID
if (!GetElement(&cert, kOptional | kConstructed | kContextSpecific | 2, NULL))
return false;
base::StringPiece extensions_seq;
if (!GetElement(&cert, kOptional | kConstructed | kContextSpecific | 3,
&extensions_seq)) {
return false;
}
if (extensions_seq.empty())
return true;
// Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
// Extension ::= SEQUENCE {
// extnID OBJECT IDENTIFIER,
// critical BOOLEAN DEFAULT FALSE,
// extnValue OCTET STRING
// |extensions_seq| was EXPLICITly tagged, so we still need to remove the
// ASN.1 SEQUENCE header.
base::StringPiece extensions;
if (!GetElement(&extensions_seq, kSEQUENCE, &extensions))
return false;
while (extensions.size() > 0) {
base::StringPiece extension;
if (!GetElement(&extensions, kSEQUENCE, &extension))
return false;
base::StringPiece oid;
if (!GetElement(&extension, kOID, &oid))
return false;
// kCRLDistributionPointsOID is the DER encoding of the OID for the X.509
// CRL Distribution Points extension.
static const uint8_t kCRLDistributionPointsOID[] = {0x55, 0x1d, 0x1f};
if (oid.size() != sizeof(kCRLDistributionPointsOID) ||
memcmp(oid.data(), kCRLDistributionPointsOID, oid.size()) != 0) {
continue;
}
// critical
GetElement(&extension, kBOOLEAN, NULL);
// extnValue
base::StringPiece extension_value;
if (!GetElement(&extension, kOCTETSTRING, &extension_value))
return false;
// RFC 5280, section 4.2.1.13.
//
// CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
//
// DistributionPoint ::= SEQUENCE {
// distributionPoint [0] DistributionPointName OPTIONAL,
// reasons [1] ReasonFlags OPTIONAL,
// cRLIssuer [2] GeneralNames OPTIONAL }
base::StringPiece distribution_points;
if (!GetElement(&extension_value, kSEQUENCE, &distribution_points))
return false;
while (distribution_points.size() > 0) {
base::StringPiece distrib_point;
if (!GetElement(&distribution_points, kSEQUENCE, &distrib_point))
return false;
base::StringPiece name;
if (!GetElement(&distrib_point, kContextSpecific | kConstructed | 0,
&name)) {
// If it doesn't contain a name then we skip it.
continue;
}
if (GetElement(&distrib_point, kContextSpecific | 1, NULL)) {
// If it contains a subset of reasons then we skip it. We aren't
// interested in subsets of CRLs and the RFC states that there MUST be
// a CRL that covers all reasons.
continue;
}
if (GetElement(&distrib_point,
kContextSpecific | kConstructed | 2, NULL)) {
// If it contains a alternative issuer, then we skip it.
continue;
}
// DistributionPointName ::= CHOICE {
// fullName [0] GeneralNames,
// nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
base::StringPiece general_names;
if (!GetElement(&name,
kContextSpecific | kConstructed | 0, &general_names)) {
continue;
}
// GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
// GeneralName ::= CHOICE {
// ...
// uniformResourceIdentifier [6] IA5String,
// ...
while (general_names.size() > 0) {
base::StringPiece url;
if (GetElement(&general_names, kContextSpecific | 6, &url)) {
tmp_urls_out.push_back(url);
} else {
if (!GetElement(&general_names, kAny, NULL))
return false;
}
}
}
}
urls_out->swap(tmp_urls_out);
return true;
}
} // namespace asn1
} // namespace net
| [
"zeno.albisser@hemispherian.com"
] | zeno.albisser@hemispherian.com |
96f9f55a0d08aabaa516dccfd84c2bea4b9f8732 | 6c0d489a8032915848fa7f9368698a2636eecd33 | /522/crypto/des3.cpp | a5199539c65c65cd4fcbee596c4a707c8dcbba4f | [] | no_license | lstefani006/teensy | d05f044557fdff19594b9b4882226b42acb7dd1a | c8200f1ee43f6426d4f3acf0a3784f13626b8b48 | refs/heads/master | 2021-05-16T02:19:27.449462 | 2020-11-20T20:59:08 | 2020-11-20T20:59:08 | 43,541,230 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,686 | cpp | /**
* @file des3.c
* @brief Triple DES (Triple Data Encryption Algorithm)
*
* @section License
*
* Copyright (C) 2010-2016 Oryx Embedded SARL. All rights reserved.
*
* This file is part of CycloneCrypto Open.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @section Description
*
* Triple DES is an encryption algorithm designed to encipher and decipher blocks
* of 64 bits under control of a 192-bit key. Refer to FIPS 46-3 for more details
*
* @author Oryx Embedded SARL (www.oryx-embedded.com)
* @version 1.7.2
**/
//Switch to the appropriate trace level
#define TRACE_LEVEL CRYPTO_TRACE_LEVEL
//Dependencies
#include <string.h>
#include "crypto.h"
#include "des3.h"
#include "des.h"
//Check crypto library configuration
#if (DES3_SUPPORT == ENABLED)
//Common interface for encryption algorithms
const CipherAlgo des3CipherAlgo =
{
"3DES",
sizeof(Des3Context),
CIPHER_ALGO_TYPE_BLOCK,
DES3_BLOCK_SIZE,
(CipherAlgoInit) des3Init,
nullptr,
nullptr,
(CipherAlgoEncryptBlock) des3EncryptBlock,
(CipherAlgoDecryptBlock) des3DecryptBlock
};
/**
* @brief Initialize a Triple DES context using the supplied key
* @param[in] context Pointer to the Triple DES context to initialize
* @param[in] key Pointer to the key
* @param[in] keyLength Length of the key
* @return Error code
**/
error_t des3Init(Des3Context *context, const uint8_t *key, size_t keyLength)
{
//Check key length
if(keyLength == 8)
{
//This option provides backward compatibility with DES, because the
//first and second DES operations cancel out
desInit(&context->k1, key, 8);
desInit(&context->k2, key, 8);
desInit(&context->k3, key, 8);
}
else if(keyLength == 16)
{
//If the key length is 128 bits including parity, the first 8 bytes of the
//encoding represent the key used for the two outer DES operations, and
//the second 8 bytes represent the key used for the inner DES operation
desInit(&context->k1, key, 8);
desInit(&context->k2, key + 8, 8);
desInit(&context->k3, key, 8);
}
else if(keyLength == 24)
{
//If the key length is 192 bits including parity, then three independent DES
//keys are represented, in the order in which they are used for encryption
desInit(&context->k1, key, 8);
desInit(&context->k2, key + 8, 8);
desInit(&context->k3, key + 16, 8);
}
else
{
//Invalid key length...
return ERROR_INVALID_KEY_LENGTH;
}
//No error to report
return NO_ERROR;
}
/**
* @brief Encrypt a 8-byte block using Triple DES algorithm
* @param[in] context Pointer to the Triple DES context
* @param[in] input Plaintext block to encrypt
* @param[out] output Ciphertext block resulting from encryption
**/
void des3EncryptBlock(Des3Context *context, const uint8_t *input, uint8_t *output)
{
//The first pass is a DES encryption
desEncryptBlock(&context->k1, input, output);
//The second pass is a DES decryption of the first ciphertext result
desDecryptBlock(&context->k2, output, output);
//The third pass is a DES encryption of the second pass result
desEncryptBlock(&context->k3, output, output);
}
/**
* @brief Decrypt a 8-byte block using Triple DES algorithm
* @param[in] context Pointer to the Triple DES context
* @param[in] input Ciphertext block to decrypt
* @param[out] output Plaintext block resulting from decryption
**/
void des3DecryptBlock(Des3Context *context, const uint8_t *input, uint8_t *output)
{
//The first pass is a DES decryption
desDecryptBlock(&context->k3, input, output);
//The second pass is a DES encryption of the first pass result
desEncryptBlock(&context->k2, output, output);
//The third pass is a DES decryption of the second ciphertext result
desDecryptBlock(&context->k1, output, output);
}
#endif
| [
"leonardo.stefani.ge@gmail.com"
] | leonardo.stefani.ge@gmail.com |
0cbbe5574c1e106d5aef9e2161943590f99da0af | 2a75fd1fa01446573196d782c248751c98031ec1 | /ver2-mov-codes/kaatru-ver2-M14/kaatru-ver2-M14.ino | 0b1d54718061e900eb46a09183f240a7c7c31bca | [] | no_license | kaatrucodes/kaatrucodes | bc41ee832713fa8a49ce58ab7c11a92985633b0f | ac113399410213953d6db4dab4bce89206c41ebd | refs/heads/master | 2020-08-04T08:33:46.643056 | 2019-10-01T11:14:21 | 2019-10-01T11:14:21 | 212,068,905 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,435 | ino | #include <SoftwareSerial.h>
#include "Arduino.h"
#include <stdlib.h> // included for floatToString
#include <math.h>
#include <SPI.h>
#include <SD.h>
#include "DHT.h"
#include "ULP.h"
#include <Wire.h>
#include "SI114X.h"
#include "MutichannelGasSensor.h"
String DeviceID = String("M14"); //change according to the device
File myFile;
#define LENG 31 //0x42 + 31 bytes equal to 32 bytes
unsigned char buf[LENG];
int PM01Value = 0; //define PM1.0 value of the air detector module
int PM2_5Value = 0; //define PM2.5 value of the air detector module
int PM10Value = 0; //define PM10 value of the air detector module
SoftwareSerial PMSerial(11, 10); // RX, TX
int resetPM = 3;
const int MPU_addr = 0x68; // I2C address of the MPU-6050
int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ, Temp ;
#define DHTPIN 2 // what pin we're connected to
#define DHTTYPE DHT22 // DHT 22 (AM2302)
DHT dht(DHTPIN, DHTTYPE);
const int C1 = A0;
const int T1 = A2;
const float Sf1 = 29.92; //nA/ppm replace this value with your own sensitivity
float temp1;
float vGas;
float getConcen;
float TZero;
float Vzero1;
SO2 sensor1(C1, T1, Sf1);// X - to be find
SI114X SI1145 = SI114X();
/*
** MOSI - pin 51
** MISO - pin 50
** SCK - pin 52
** CS - pin 53 (for MKRZero SD: SDCARD_SS_PIN)
*/
char copy[255];
char dateTitle[50];
byte fetch_pressure(unsigned int *p_Pressure, unsigned int *t_Temperature);
#define TRUE 1
#define FALSE 0
byte _status;
unsigned int P_dat;
unsigned int T_dat;
double P;
double PR;
double TR;
double V;
double VV;
String airspeed;
int analogInput = A3;
float vout = 0.0;
float vin = 0.0;
int value = 0;
SoftwareSerial SIM808(12, 13);
typedef struct {
String latitude;
String longitude;
String datetime;
} MyDataGPS;
MyDataGPS dataGPS;
String gps;
String gpsDummy;
char delimiter = ',';
String finalOutStr = ""; //+delimieter is needed only if start needs to be delimeter
/*
|1|2|3|
1|2|3
*/
void addOutStr(String val)
{
//concat output string
//output string is global and needs to be cleaned/initialised before using.
finalOutStr += String(val) + delimiter;
}
String getOutStr(void)
{
return finalOutStr;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
//pinMode(analogInput, INPUT);
dht.begin(); // setting up DHT
if (!SD.begin(53)) {
Serial.println("initialization failed!");
while (1);
}
gas.begin(0x04);//the default I2C address of the slave is 0x04 // setting up multichannel gas sensor
gas.powerOn();
gas.getVersion();
while (!SI1145.Begin()) {
Serial.println("Si1145 is not ready!");
delay(1000);
}
Wire.begin(); // setting up Accelerometer
Wire.beginTransmission(MPU_addr);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
ULP::_Vsup;
ULP::_Vcc;
sensor1._Vref;
Vzero1 = sensor1.zero();
sensor1._Tz;
delay(5000);
SIM808.begin(9600); // setting up SIM808
initGps();
//getRtctime();
gprs_init();
gprs_init_http();
PMSerial.begin(9600); // setting up PM2.5 sensor
PMSerial.setTimeout(1500);
}
void loop() {
// put your main code here, to run repeatedly:
SIM808.listen();
gps = getGps(); // getting gps location
//uncomment to get dummy gps
// gpsDummy = getGpsDummy(); // getting dummy gps location
// Serial.println(gpsDummy);
printDateTitle(dateTitle, date(dataGPS.datetime).toInt(), mon(dataGPS.datetime).toInt(), Year(dataGPS.datetime).toInt());
myFile = SD.open(dateTitle, FILE_WRITE); //opening sd card
finalOutStr = "";
if (myFile) {
addOutStr(String(getDhtValues()));
addOutStr(String(getSunlightSenValues()));
addOutStr(String(getaccelvalues()));
//addOutStr(String(getaccelvaluesDummy()));
addOutStr(String (getSo2senValues()));
//addOutStr(String (getSo2senValuesDummy()));
addOutStr(String(getGasSenValues()));
addOutStr(String(getPmValues()));
addOutStr(String(getAirSpeed()));
//addOutStr(String(getAirSpeedDummy()));
//Serial.println(getOutStr());
SIM808.listen(); //Softwareserial switching for SIM808
Serial.println(getValues()); //getting the final values from box
gprs_send(getValues()); // sending data to server via http post request
// Serial.println(getValuesDummy()); //getting the final values from box
// gprs_send(getValuesDummy()); // sending data to server via http post request
Serial.println("writting to sdcard");
Serial.println(dateTitle);
myFile.println(getValues()); // writing the values to sdcard
Serial.println("done");
myFile.close();
}
}
String ReadGSM() {
char c;
String str;
while (SIM808.available()) {
c = SIM808.read();
str += c;
delay(20);
}
str = "<<< " + str;
//Serial.println(str);
return str;
}
void initGps()
{
SIM808.println("AT+CGNSPWR=1\r\n");
delay(1000);
Serial.println(ReadGSM());
}
MyDataGPS getGPSLocation(void) {
//Serial.println("inside getGPSLocation");
String readLocation;
String data[5];
MyDataGPS d;
int a = 0, b = 0;
SIM808.println("AT+CGNSINF\r\n");
delay(400);
delay(400);
readLocation = ReadGSM();
//Serial.println("data is " + readLocation);
for (int i = 0; i < 5; i++) {
a = readLocation.indexOf(",", a);
if (a != -1) {
b = readLocation.indexOf(",", a + 1);
data[i] = readLocation.substring(a + 1, b);
//Serial.println(String("data: " + String(i) + " - " + data[i]));
a = b;
}
}
d.datetime = data[1];
d.latitude = data[2];
d.longitude = data[3];
return d;
}
void gprs_init() {
Serial.println("GPRS init start");
delay(2000);
SIM808.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"\r\n");
delay(2500);
Serial.println(ReadGSM());
delay(2500);
SIM808.println("AT+SAPBR=3,1,\"APN\",\"airtelgprs.com\"\r\n"); //APN
delay(500);
Serial.println(ReadGSM());
delay(1000);
SIM808.println("AT+SAPBR=1,1\r\n");
delay(1500);
Serial.println(ReadGSM());
SIM808.println("AT+SAPBR=2,1\r\n");
delay(500);
Serial.println(ReadGSM());
delay(2500);
Serial.println("GPRS init complete");
Serial.println("");
}
void gprs_init_http() {
Serial.println("GPRS init http start");
delay(2000);
Serial.println("Send start");
SIM808.println("AT+HTTPINIT\r\n"); // initializes the HTTP service
delay(2000);
Serial.println(ReadGSM());
SIM808.println("AT+HTTPPARA=\"CID\",1\r\n");
delay(1000);
Serial.println(ReadGSM());
Serial.println("setup url");
//SIM808.println("AT+HTTPPARA=\"URL\",\"http://34.206.153.59/IMS/GISData\"\r\n");
SIM808.println("AT+HTTPPARA=\"URL\",\"http://kaatruelb-670631449.us-east-1.elb.amazonaws.com//api/entry.php\"\r\n");
delay(5000);
Serial.println(ReadGSM());
delay(2500);
Serial.println("GPRS init http complete");
Serial.println("");
}
void gprs_send(String val)
{
Serial.println("Data sending start");
Serial.println("");
String dataToBeSent = val;
dataToBeSent.toCharArray(copy, 255);
SIM808.println("AT+HTTPDATA=255,8000\r\n");
delay(1500);
Serial.println(ReadGSM());
delay(2000);
SIM808.println(dataToBeSent);
delay(2500);
Serial.println(ReadGSM());
Serial.println("GET url");
SIM808.println("AT+HTTPACTION=1\r\n");
delay(1500);
Serial.println(ReadGSM());
Serial.println("Data send complete");
Serial.println("");
}
String getGps()
{
String localstr = " ";
//String delimiter2 = String(",");
String n = String("N");
String e = String("E");
String Altitude = String("null");
//String accuracy = String(getInputVoltageValue());
String accuracy = String("null");
String provider = String("Airtel");
String Speed = String("null");
dataGPS = getGPSLocation();
// uncomment for debug
// Serial.print(dataGPS.latitude);
// Serial.print(dataGPS.longitude);
// Serial.print(dateParser(dataGPS.datetime));
localstr = String(dataGPS.latitude) + delimiter;
localstr += n + delimiter;
localstr += String(dataGPS.longitude) + delimiter;
localstr += e + delimiter;
localstr += accuracy + delimiter;
localstr += Altitude + delimiter;
localstr += Speed + delimiter;
localstr += dateParser(dataGPS.datetime) + delimiter;
localstr += provider + delimiter;
return localstr;
}
// uncomment to use
String getGpsDummy()
{
String localstr = " ";
String n = String("N");
String e = String("E");
String Time = String("04-01-19 15:45:54");
String latitude = String("12.594408");
String longitude = String("80.138824");
String Altitude = String("null");
String bearing = String("null");
String accuracy = String(getInputVoltageValue());
String Speed = String("null");
String provider = String("Airtel");
dataGPS = getGPSLocation();
localstr = String(latitude) + delimiter ;
localstr += n + delimiter;
localstr += String(longitude) + delimiter ;
localstr += e + delimiter ;
localstr += accuracy + delimiter ;
localstr += Altitude + delimiter ;
localstr += Time + delimiter;
//localstr += dateParser(dataGPS.datetime) + delimiter;
localstr += provider + delimiter;
return localstr;
}
void printDateTitle(char* dateTitle, int d, int m, int y) {
//char dateTitle[20];
sprintf(dateTitle, "%02d-%02d-%02d.txt", d, m, y);
return;
}
// comment to get dummy dateparser
String dateParser(String str) // dateparser for gps
{
String var = str;
String yy = var.substring(2, 4);
String mm = var.substring(4, 6);
String dd = var.substring(6, 8);
String hh = var.substring(8, 10);
String mi = var.substring(10, 12);
String sec = var.substring(12, 14);
//String mi = var.substring(14);
String delimiter1 = " ";
String delimiter3 = "-";
String delimiter4 = ":";
String finalstr = (yy + delimiter3 + mm + delimiter3 + dd + delimiter1 + hh + delimiter4 + mi + delimiter4 + sec );
return finalstr;
}
String date(String str) // dateparser for gps
{
String var = str;
String dd = var.substring(6, 8);
String finalstr = (dd);
return finalstr;
}
String mon(String str) // dateparser for gps
{
String var = str;
String mm = var.substring(4, 6);
String finalstr = (mm);
return finalstr;
}
String Year(String str) // dateparser for gps
{
String var = str;
String yy = var.substring(2, 4);
String finalstr = (yy);
return finalstr;
}
String getInputVoltageValue()
{
value = analogRead(analogInput);
vout = (value) * (25.0 / 1023.0); // see text
String localstr = " ";
localstr = String(vout);
return localstr;
}
String getDhtValues()
{
String localstr = " ";
float humidity = dht.readHumidity();
float temperature = dht.readTemperature(); // Read temperature as Celsius
float f = dht.readTemperature(true);// Read temperature as Fahrenheit (isFahrenheit = true)
float computeHeatIndex = dht.computeHeatIndex(f, humidity);
localstr = String(humidity) + delimiter;
localstr += String(temperature) + delimiter;
localstr += String(computeHeatIndex);
return localstr;
}
String getSunlightSenValues()
{
String localstr = " ";
String UV = String((float)SI1145.ReadUV() / 100); // the real UV value must be div 100 from the reg value , datasheet for more information.
String VIS = String(SI1145.ReadVisible());// vis
String IR = String(SI1145.ReadIR()); //IR
localstr = String(UV) + delimiter;
localstr += String(VIS) + delimiter;
localstr += String(IR) ;
return localstr;
}
String getaccelvalues()
{
String localstr = " ";
Wire.beginTransmission(MPU_addr);
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU_addr, 14, true); // request a total of 14 registers
AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
Temp = Tmp / 340.00 + 36.53;
localstr = String(AcX) + delimiter;
localstr += String(AcY) + delimiter;
localstr += String(AcZ) + delimiter;
localstr += String(Temp) + delimiter;
localstr += String(GyX) + delimiter;
localstr += String(GyY) + delimiter;
localstr += String(GyZ) ;
return localstr;
}
String getaccelvaluesDummy()
{
String localstr = " ";
localstr = String("null") + delimiter;
localstr += String("null") + delimiter;
localstr += String("null") + delimiter;
localstr += String("null") + delimiter;
localstr += String("null") + delimiter;
localstr += String("null") + delimiter;
localstr += String("null") ;
return localstr;
}
String getSo2senValues()
{
temp1 = sensor1.getTemp(1, "C"); // Use .getTemp(n, "F") to get temp in Fahrenheit, with n as int number of seconds for averaging and "F" or "C" for temp units
vGas = sensor1.getVgas(1);
getConcen = sensor1.getConc(1, temp1);
String localstr = " ";
localstr = String(temp1) + delimiter;
localstr += String(vGas) + delimiter;
localstr += String(getConcen) ;
return localstr;
}
String getSo2senValuesDummy()
{
String localstr = " ";
localstr = String("null") + delimiter;
localstr += String("null") + delimiter;
localstr += String("null") ;
return localstr;
}
String getGasSenValues()
{
float c;
String localstr = " ";
String Null = String("null");
c = gas.measure_NH3();
if (c >= 0) localstr = String(c) + delimiter; // value in ppm
else localstr = String(Null) + delimiter;
c = gas.measure_CO();
if (c >= 0) localstr += String(c) + delimiter;
else localstr += String(Null) + delimiter;
c = gas.measure_NO2();
if (c >= 0) localstr += String(c) + delimiter;
else localstr += String(Null) + delimiter;
c = gas.measure_C3H8();
if (c >= 0) localstr += String(c) + delimiter;
else localstr += String(Null) + delimiter;
c = gas.measure_C4H10();
if (c >= 0) localstr += String(c) + delimiter;
else localstr += String(Null) + delimiter;
c = gas.measure_CH4();
if (c >= 0) localstr += String(c) + delimiter;
else localstr += String(Null) + delimiter;
c = gas.measure_H2();
if (c >= 0) localstr += String(c) + delimiter;
else localstr += String(Null) + delimiter;
c = gas.measure_C2H5OH();
if (c >= 0) localstr += String(c) ;
else localstr += String(Null) ;
return localstr;
}
String getPmValues()
{
String localstr = " ";
PMSerial.listen(); //Softwareserial switching for PM2.5 sensor
if (PMSerial.find(0x42)) {
PMSerial.readBytes(buf, LENG);
if (buf[0] == 0x4d) {
if (checkValue(buf, LENG)) {
PM01Value = transmitPM01(buf); //count PM1.0 value of the air detector module
PM2_5Value = transmitPM2_5(buf); //count PM2.5 value of the air detector module
PM10Value = transmitPM10(buf); //count PM10 value of the air detector module
}
}
}
static unsigned long OledTimer = millis();
if (millis() - OledTimer >= 1000)
{
OledTimer = millis();
localstr = String(PM01Value) + delimiter;
localstr += String(PM2_5Value) + delimiter;
localstr += String(PM10Value);
}
return localstr;
}
char checkValue(unsigned char *thebuf, char leng)
{
char receiveflag = 0;
int receiveSum = 0;
for (int i = 0; i < (leng - 2); i++) {
receiveSum = receiveSum + thebuf[i];
}
receiveSum = receiveSum + 0x42;
if (receiveSum == ((thebuf[leng - 2] << 8) + thebuf[leng - 1])) //check the serial data
{
receiveSum = 0;
receiveflag = 1;
}
return receiveflag;
}
int transmitPM01(unsigned char *thebuf)
{
int PM01Val;
PM01Val = ((thebuf[3] << 8) + thebuf[4]); //count PM1.0 value of the air detector module
return PM01Val;
}
//transmit PM Value to PC
int transmitPM2_5(unsigned char *thebuf)
{
int PM2_5Val;
PM2_5Val = ((thebuf[5] << 8) + thebuf[6]); //count PM2.5 value of the air detector module
return PM2_5Val;
}
//transmit PM Value to PC
int transmitPM10(unsigned char *thebuf)
{
int PM10Val;
PM10Val = ((thebuf[7] << 8) + thebuf[8]); //count PM10 value of the air detector module
return PM10Val;
}
String getAirSpeed()
{
String tempStr = "";
Wire.begin();
while (1)
{
_status = fetch_pressure(&P_dat, &T_dat);
switch (_status)
{
case 0: Serial.println("Ok ");
break;
case 1: Serial.println("Busy");
break;
case 2: Serial.println("Slate");
break;
default: Serial.println("Error");
break;
}
PR = (double)((P_dat - 819.15) / (14744.7)) ;
PR = (PR - 0.49060678) ;
PR = abs(PR);
P = (double) P_dat * .0009155;
V = ((PR * 13789.5144) / 1.225);
VV = (sqrt((V)));
TR = (double)((T_dat * 0.09770395701));
TR = TR - 50;
//tempStr = String(P_dat) + delimiter;
tempStr = String(P, 10) + delimiter;
tempStr += String(P * 2.3067 ) + delimiter;
tempStr += String(TR) + delimiter;
tempStr += String(VV, 5);
return tempStr;
}
}
byte fetch_pressure(unsigned int *p_P_dat, unsigned int *p_T_dat)
{
byte address, Press_H, Press_L, _status;
unsigned int P_dat;
unsigned int T_dat;
address = 0x28;
Wire.beginTransmission(address);
Wire.endTransmission();
delay(100);
Wire.requestFrom((int)address, (int) 4);//Request 4 bytes need 4 bytes are read
Press_H = Wire.read();
Press_L = Wire.read();
byte Temp_H = Wire.read();
byte Temp_L = Wire.read();
Wire.endTransmission();
_status = (Press_H >> 6) & 0x03;
Press_H = Press_H & 0x3f;
P_dat = (((unsigned int)Press_H) << 8) | Press_L;
*p_P_dat = P_dat;
Temp_L = (Temp_L >> 5);
T_dat = (((unsigned int)Temp_H) << 3) | Temp_L;
*p_T_dat = T_dat;
return (_status);
}
String getValues()
{
//String fullvalue = (DeviceID+delimiter+gps+getOutStr());
//String fullvalue = (DeviceID + delimiter + DeviceID + delimiter + gps + getOutStr() + airspeed);
String fullvalue = (DeviceID + delimiter + gps + getOutStr());
return fullvalue;
}
String getValuesDummy() //uncomment to send dummy gps data
{
String fullvalue = (DeviceID + delimiter + gpsDummy + getOutStr());
//String fullvalue = (DeviceID + delimiter + DeviceID + delimiter + gpsDummy + getOutStr() + airspeed);
return fullvalue;
}
| [
"kaatrucodes@gmail.com"
] | kaatrucodes@gmail.com |
b707015a4064c6883086679be09352c7365e4ad9 | cdfddb330c4774ec2b0f525eb9466ac423067e97 | /TMCM_Motor/main.cpp | 76e298232a141f8dacb0a63e33e5cfaf465fcfd7 | [] | no_license | jurbschat/trinamic_3110 | 7d8daa546a347fc83036402812aed07642a98f7c | e3638ac396cf68bb92ef5a92f952ab4f6e13896e | refs/heads/master | 2020-08-08T15:57:49.354065 | 2019-11-11T10:31:42 | 2019-11-11T10:31:42 | 213,864,061 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,556 | cpp | /*----- PROTECTED REGION ID(TMCM_Motor::main.cpp) ENABLED START -----*/
//=============================================================================
//
// file : main.cpp
//
// description : C++ source for the TMCM_Motor device server main.
// The main rule is to initialise (and create) the Tango
// system and to create the DServerClass singleton.
// The main should be the same for every Tango device server.
//
// project :
//
// This file is part of Tango device class.
//
// Tango is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Tango is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Tango. If not, see <http://www.gnu.org/licenses/>.
//
//
//
//=============================================================================
// This file is generated by POGO
// (Program Obviously used to Generate tango Object)
//=============================================================================
#include <tango.h>
// Check if crash reporting is used.
#if defined(ENABLE_CRASH_REPORT)
# include <crashreporting/crash_report.h>
#else
# define DECLARE_CRASH_HANDLER
# define INSTALL_CRASH_HANDLER
#endif
DECLARE_CRASH_HANDLER;
int main(int argc,char *argv[])
{
INSTALL_CRASH_HANDLER
try
{
// Initialise the device server
//----------------------------------------
Tango::Util *tg = Tango::Util::init(argc,argv);
// Create the device server singleton
// which will create everything
//----------------------------------------
tg->server_init(false);
// Run the endless loop
//----------------------------------------
cout << "Ready to accept request" << endl;
tg->server_run();
}
catch (bad_alloc &)
{
cout << "Can't allocate memory to store device object !!!" << endl;
cout << "Exiting" << endl;
}
catch (CORBA::Exception &e)
{
Tango::Except::print_exception(e);
cout << "Received a CORBA_Exception" << endl;
cout << "Exiting" << endl;
}
Tango::Util::instance()->server_cleanup();
return(0);
}
/*----- PROTECTED REGION END -----*/ // TMCM_Motor::main.cpp
| [
"jaur@gmx.de"
] | jaur@gmx.de |
a2e2dbb97044a606c68fc0c3da66d69be5e93199 | ea357fdf925349a30ca52ee86864c7e1804a327f | /src/gui/model/colorsmodel/ColorsModel.h | 5518fd732244d2510bcf1031f2f7084d1f1b32f8 | [
"MIT"
] | permissive | belijzajac/TermColor | 9142aeb82a9116663293d6ca2241eb2e527c4031 | 00a32efcf8d19dfb2c89cc5b8113a497c179128f | refs/heads/master | 2023-07-16T13:11:28.834528 | 2021-09-04T14:35:23 | 2021-09-04T14:35:23 | 197,977,241 | 54 | 2 | MIT | 2021-09-04T14:35:24 | 2019-07-20T20:17:58 | C++ | UTF-8 | C++ | false | false | 1,288 | h | #ifndef COLORSMODEL_H
#define COLORSMODEL_H
#include "backend/dominantcolor/DominantColor.h"
#include <QObject>
#include <memory>
#include <map>
namespace TermColor {
class ColorsModel : public QObject {
class ColorsModelImpl;
Q_OBJECT
public:
explicit ColorsModel(QObject *parent = nullptr);
~ColorsModel();
// To mark what changed: nothing, new colors added, changed background color
enum class ChangedState { None, NewColors, Background };
// Storing colors data
struct Colors {
Colors();
ChangedState changedState_;
std::vector<color_t> BGFG_; // Background and Foreground colors
std::vector<color_t> BGFGintense_; // Same as above, but intense
std::vector<color_t> regular_; // Regular colors
std::vector<color_t> intense_; // Intense colors
};
// Methods for Colors
Colors &getColors() const;
void setImgColors(const std::vector<color_t> &colors);
void setBGFGColors(const std::vector<color_t> &bgfg);
public slots:
void onImageDropped(const QString& path);
signals:
void hideImageDropWidget();
void doProcessColors(std::string_view);
void modelChanged();
private:
std::unique_ptr<ColorsModelImpl> pimpl_;
};
}
#endif // COLORSMODEL_H
| [
"tautvydas749@gmail.com"
] | tautvydas749@gmail.com |
a9d7255251fe02c8432e40c611949b5660806f7a | 491f11457d9b28ce6d86ca3760b87c871c99b94e | /Random/HakerRank Cat and mouse .cpp | 5d98eaca3d78c2987f86bccc2b87d8ddb0b454fb | [] | no_license | jongli747/Contest-Code | 3d5d400bd61114a085f914163433be3b406523ee | 57d7f4fe830edb3b00ec284e0b1d7a14df7fe128 | refs/heads/master | 2021-01-10T23:17:13.181515 | 2018-11-10T19:42:08 | 2018-11-10T19:42:08 | 70,623,962 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 387 | cpp |
#include <bits/stdc++.h>
using namespace std;
int main()
{
int q;
cin >>q;
for(int i=1; i<=q; i++)
{
int x, y, z;
cin >> x >> y >> z;
if(abs(x-z) > abs(y-z))
cout << "Cat B" << endl;
else if(abs(x-z) < abs(y-z))
cout << "Cat A" << endl;
else
cout << "Mouse C" << endl;
}
return 0;
}
| [
"labibx70@gmail.com"
] | labibx70@gmail.com |
bcbfad024125b71d567bc6629f426d14bd31bb07 | 1fafd294cd0771e7720c4ff7c2cef673da550a4c | /MedCalcM/MedCalcS/MedCalcS.h | 33e1d57eded4e4eeec511f2e88b4918e2737bd0a | [] | no_license | tornadocean/Wcalc | e2e1516d5025e60dea6b3b3231e53b320b525fd2 | da8e65849ce78b7ac4796f83fa33aa1e293e3be3 | refs/heads/master | 2020-04-11T04:27:57.713625 | 2015-09-08T01:38:09 | 2015-09-08T01:38:09 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 496 | h |
// MedCalcS.h : MedCalcS 应用程序的主头文件
//
#pragma once
#ifndef __AFXWIN_H__
#error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件"
#endif
#include "resource.h" // 主符号
// CMedCalcSApp:
// 有关此类的实现,请参阅 MedCalcS.cpp
//
class CMedCalcSApp : public CWinApp
{
public:
CMedCalcSApp();
// 重写
public:
virtual BOOL InitInstance();
// 实现
afx_msg void OnAppAbout();
DECLARE_MESSAGE_MAP()
};
extern CMedCalcSApp theApp;
| [
"smallsmilejiang@msn.com"
] | smallsmilejiang@msn.com |
f78ebc65cf783cddbfc6fa654a3e5a1cdbfb44b4 | 1850fe58a070c6fcf64ac3644a0982ec93bd1b74 | /renderer/base/decoderobj.h | 84c83ddee5a1a49e90cf58344f83d551897170bd | [
"MIT"
] | permissive | TheExceptionist/software-renderer | 37ed80cc17675ef74756b32f306b22670d470de3 | dfeb24eb4ac6f90552e65cc7e0cf97d7d693ad7b | refs/heads/master | 2021-04-28T01:10:38.344736 | 2013-02-24T11:06:17 | 2013-02-24T11:06:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 867 | h | /*
* decoderobj.h
*
* Author: flamingo
* E-mail: epiforce57@gmail.com
*/
#ifndef DECODEROBJ_H
#define DECODEROBJ_H
#include "resourcedecoder.h"
#include "math/vertex.h"
namespace base
{
class DecoderOBJ : public ResourceDecoder
{
void appendVertex(std::string &line);
void appendFace(std::string &line);
void appendNormal(std::string &line);
void triangulateModel();
std::vector<math::vertex> vertexList;
std::vector<math::vec3> normalsList;
struct FaceInfo
{
std::vector<int> indices;
std::vector<int> normalIndices;
};
std::vector<FaceInfo> faces;
std::vector<int> resultTrianglesIndices;
void clear();
public:
DecoderOBJ() { }
~DecoderOBJ() { }
sptr(Resource) decode(const std::string &path);
std::string extension() const;
};
}
#endif // DECODEROBJ_H
| [
"epiforce57@gmail.com"
] | epiforce57@gmail.com |
758c08fc300ea4ef89726e6d81c5153d5ccc9271 | ed033bdd4ded921dc94cc78110507e1e9e8c257c | /game_c++_2019/game_c++_2019/EditGame.h | f2594d67b233b60639b2180a6fe99980c0260e96 | [] | no_license | coint-my/store | cda8f37db9859a02141e1f59aee9c56d79fdc145 | 395d717c8f3053ab3db3084f4261b0344cbbc4ba | refs/heads/master | 2023-04-14T22:52:36.659403 | 2023-04-05T13:48:17 | 2023-04-05T13:48:17 | 245,461,456 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 16,462 | h | #pragma once
#include "ManagerLogick.h"
#include <experimental/filesystem>
namespace ed
{
static int counter_panel = 0;
static int counter_tile = 0;
const static int offset_scroll_x = 8;
void showAllTextures(std::vector<my::MyTexture*>& _texture_store)
{
namespace fs = std::experimental::filesystem;
const char* path = "texture/ground";
if (fs::exists(path))
{
std::cout << "directories is found 'textures'" << std::endl;
for (const auto& entry : fs::directory_iterator(path))
{
std::string tmp = entry.path().string();
if ((tmp.compare(tmp.length() - 3, 3, "jpg") == 0) ||
(tmp.compare(tmp.length() - 3, 3, "png") == 0))
{
std::cout << tmp << std::endl;
_texture_store.push_back(new my::MyTexture(tmp.c_str()));
}
else std::cout << "unknow format texture = " << tmp << std::endl;
}
}
else
{
std::cout << "directories is not found 'textures'" << std::endl;
}
}
class panel : public object
{
protected:
my::colori col;
my::colori col_active;
public:
bool isShowName;
panel()
{
isShowName = true;
initialize("panel" + std::to_string(counter_panel++), new my::vec2f(10, 10), new my::rectf(10, 10, 40, 40));
}
panel(my::colori _col, my::vec2f _pos)
{
isShowName = true;
col = _col;
col_active = my::colori(220, 0, 0);
initialize("panel" + std::to_string(counter_panel++), new my::vec2f(_pos), new my::rectf(_pos.x, _pos.y, 40, 40));
}
panel(my::colori _col, my::vec2f _pos, my::vec2f _size)
{
isShowName = true;
col = _col;
col_active = my::colori(220, 0, 0);
initialize("panel" + std::to_string(counter_panel++), new my::vec2f(_pos), new my::rectf(_pos.x, _pos.y, _size.x, _size.y));
}
panel(my::vec2f* _pos, my::vec2f _size, my::colori _col = my::colori(200, 200, 200))
{
isShowName = true;
col = _col;
col_active = my::colori(220, 0, 0);
pos = _pos;
initialize("panel" + std::to_string(counter_panel++), pos, new my::rectf(pos->x, pos->y, _size.x, _size.y));
}
virtual ~panel() { counter_panel--; std::cout << "destructor = " << name << "\n"; }
protected:
virtual void initialize(std::string _name, my::vec2f* _pos, my::rectf* _rect) override
{
name = _name; pos = _pos; rect = _rect; first_pos = *pos;
}
virtual void showName() const
{
if (isShowName)
{
int temp = glutBitmapLength((void*)0x0007, (unsigned char*)name.c_str());
int hei = glutBitmapHeight((void*)0x0007);
my::ShowStringFont(name, 3, pos->x + ((rect->size.x / 2) - temp / 2), pos->y + hei, my::colori(255, 255, 255));
}
}
virtual void draw(const float time) override
{
glDisable(GL_TEXTURE_2D);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
if (isActive)
glColor4ub(col_active.r, col_active.g, col_active.b, 200);
else
glColor4ub(col.r, col.g, col.b, 200);
glBegin(GL_QUADS);
glVertex2f(rect->pos.x, rect->pos.y);
glVertex2f(rect->pos.x + rect->size.x, rect->pos.y);
glVertex2f(rect->size.x + rect->pos.x, rect->size.y + rect->pos.y);
glVertex2f(rect->pos.x, rect->size.y + rect->pos.y);
glEnd();
glEnable(GL_TEXTURE_2D);
}
virtual void update(const float time) override
{
}
};
class texture_panel : public panel
{
private:
short border;
my::MyTexture* texture;
public:
texture_panel(my::MyTexture* _texture, my::vec2f _pos) :
panel(new my::vec2f(_pos), my::vec2f(40, 40)), texture(_texture), border(2) {
texture->initTexture();
}
~texture_panel() { }
public:
my::MyTexture* get_tex() { return texture; }
virtual void showName() const
{
if (isShowName)
{
int temp = glutBitmapLength((void*)0x0007, (unsigned char*)name.c_str());
int hei = glutBitmapHeight((void*)0x0007);
my::ShowStringFont(name, 3, pos->x + ((rect->size.x / 2) - temp / 2), pos->y + hei, my::colori(255, 255, 255));
}
}
void draw(const float time) override
{
panel::draw(time);
glBindTexture(GL_TEXTURE_2D, texture->tex.id);
glColor3ub(255, 255, 255);
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex2f(rect->pos.x + (float)border, rect->pos.y + (float)border);
glTexCoord2f(1, 0); glVertex2f(rect->pos.x + rect->size.x - (float)border, rect->pos.y + (float)border);
glTexCoord2f(1, 1); glVertex2f(rect->size.x + rect->pos.x - (float)border, rect->size.y + rect->pos.y - (float)border);
glTexCoord2f(0, 1); glVertex2f(rect->pos.x + (float)border, rect->size.y + rect->pos.y - (float)border);
glEnd();
}
};
class textBox : public panel, public my::MyMessage
{
private:
std::string text;
int x, y;
bool isFocuse;
public:
textBox(my::vec2f* _pos, my::vec2f _size) : panel(_pos, _size)
{
isFocuse = false;
my::m_message.push_back(this);
}
textBox(my::vec2f _parent, my::vec2f _pos, my::vec2f _size) : panel(new my::vec2f(_parent + _pos), _size)
{
isFocuse = false;
my::m_message.push_back(this);
}
virtual ~textBox() { /*std::cout << "destructor textBox = " << name << " " << text << "\n";*/ }
inline void IsFocuse(const bool _flag) { isFocuse = _flag; }
inline bool IsFocuse() { return isFocuse; }
//событие изменение экрана формы
void call()
{
}
//присвоить новый текст
void set_text(const char* _text) { text = _text; }
void set_text(std::string _text) { text = _text; }
//выровнить по центру плитки текст типа char*
void setStringCenter(const unsigned char* _text, int& _xOut, int& _yOut)
{
int w = glutBitmapLength((void*)0x0006, _text);
int h = glutBitmapWidth((void*)0x0006, 35);
int xx = (rect->center().x - (w / 2));
int yy = (rect->center().y + (h / 2));
_xOut = xx;
_yOut = yy;
}
//выровнить по центру плитки текст типа string
void setStringCenter(std::string _text, int& _xOut, int& _yOut)
{
int w = glutBitmapLength((void*)0x0006, (unsigned char*)_text.c_str());
int h = glutBitmapWidth((void*)0x0006, 35);
int xx = (rect->center().x - (w / 2));
int yy = (rect->center().y + (h / 2));
_xOut = xx;
_yOut = yy;
}
void mouse(int button, int state, int _x, int _y)
{
if ((button == GLUT_LEFT) && (state == GLUT_UP) && (isFocuse))
{
if (my::intersect_rect(*rect, my::rectf(_x, _y, 5, 5)))
IsActive(true);
}
else IsActive(false);
}
void keyboard_up(unsigned char _key, int _x, int _y)
{
if (isActive && isFocuse)
{
//если ключь enter
if (_key == 13)
IsActive(false);
else
{
//если ключь backspace
if (_key == 8 && text.length() != 0)
text.pop_back();
else
text += _key;
}
glutPostRedisplay();
}
}
void draw(const float time) override
{
panel::draw(time);
setStringCenter(text, x, y);
my::ShowStringFont(text, 2, x, y);
}
void update(const float time) override
{
}
};
class textStatus : public my::MyMessage
{
private:
textBox *name;
textBox *posX;
textBox *posY;
my::rectf* par;
float hei_line;
float wid_separate;
public:
textStatus(my::rectf* const _parent, int _heiLine)
{
par = _parent;
hei_line = _heiLine;
wid_separate = _parent->size.x / 2;
name = new textBox(_parent->pos, my::vec2f(), my::vec2f(_parent->size.x, hei_line));
posX = new textBox(_parent->pos, my::vec2f(0, hei_line + 2), my::vec2f(wid_separate - 1, hei_line));
posY = new textBox(_parent->pos, my::vec2f(wid_separate, hei_line + 2), my::vec2f(wid_separate - 1, hei_line));
my::m_message.push_back(this);
}
~textStatus()
{
delete name;
delete posX;
delete posY;
}
inline textBox* getName() const { return name; }
inline textBox* getPosX() const { return posX; }
inline textBox* getPosY() const { return posY; }
void call()
{
wid_separate = par->pos.x + (par->size.x / 2);
name->rect->size.x = par->size.x;
posX->rect->size.x = par->size.x / 2 - 1;
posY->set_pos(wid_separate, posY->pos->y);
posY->rect->size.x = par->size.x / 2 - 1;
}
};
class ScrollBarObject : public panel, public my::MyMessage
{
private:
float scroll_val;
std::vector<object*> item;
public:
enum status { QUAD, LINE, CUSTOM } stat;
public:
ScrollBarObject() : scroll_val(0) { stat = QUAD; }
ScrollBarObject(my::rectf _rect, my::colori _col = my::colori(150, 100, 50)) :
panel(new my::vec2f(_rect.pos), my::vec2f(_rect.size), _col), scroll_val(0)
{
my::m_message.push_back(this);
}
~ScrollBarObject()
{
std::cout << "destructor = " << name << "\n";
for(auto i : item)
delete i;
item.clear();
}
void setStatus(const status _val) { stat = _val; }
void call()
{
//вычисляем ширину подокна, и задаём прямоугольнику ширину
GLint w = my::width_sub - offset_scroll_x * 2;
rect->size.x = w;
//если плиточная система отображения
if (stat == QUAD)
{
//вычисляем высоту подокна, и задаём высоту
//rect->size.y = my::HEI / 2 + rect->pos.y;
float _siz = (w / 2) + 1;
//идет разположения позиции ячеек в прямоугольнике
int i = 0;
int y = 0;
for (auto obj : item)
{
obj->rect->size.x = _siz;
obj->rect->size.y = _siz;
int res_w = w / _siz;
int x = i % (res_w + 1);
my::vec2f _pos = my::vec2f(pos->x + (x * _siz), pos->y + (y * _siz));
obj->set_pos(_pos);
x == res_w ? y++ : y = y;
i++;
}
}
else if (stat == LINE)//если линейная система отображения
{
//идет разположения позиции ячеек в прямоугольнике
int i = 0;
for (auto obj : item)
{
float h = 30.0f;
obj->rect->size.x = w;
obj->rect->size.y = h;
my::vec2f _pos = my::vec2f(pos->x, pos->y + (i * h));
obj->set_pos(_pos);
i++;
}
}
else if (stat == CUSTOM)
{
}
}
object& getf() const
{
if (item.size() > 0)
{
return *item[0];
}
else std::cout << "fail the object of scroll bar" << std::endl;
}
object& gete() const
{
if (item.size() > 0)
{
return *item[item.size() - 1];
}
else std::cout << "fail the object of scroll bar" << std::endl;
}
void AddItem(object* const _obj)
{
item.push_back(_obj);
}
bool visible(const float _y) const
{
return (_y > rect->pos.y && _y < rect->bottom());
}
void mouse(int button, int state, int _x, int _y)
{
if (state == GLUT_UP && button == GLUT_LEFT)
{
for (auto obj : item)
{
obj->IsActive(false);
if (obj->isVisible)
{
my::rectf test = my::rectf(_x, _y, 5, 5);
if (my::intersect_rect(*obj->rect, test))
{
std::cout << "ok" << std::endl;
obj->IsActive(true);
if (texture_panel * p = dynamic_cast<texture_panel*>(obj))
{
buff.tex = p->get_tex();
buff.obj = obj;
}
else buff.tex = &tex_none;
}
}
}
}
}
void mouseWheel(int button, int dir, int _x, int _y)
{
if (my::intersect_rect(my::rectf(rect->pos.x, rect->pos.y, rect->size.x, rect->size.y),
my::rectf(_x, _y, 2, 2)))
{
float _size = getf().rect->size.y;
float top = getf().pos->y + (_size * 1.4f);
float bottom = gete().rect->bottom() - (_size * 1.4f);
if ((dir > 0) && (pos->y < bottom))
{
scroll_val += -getf().rect->size.y;
glutPostRedisplay();
}
else if ((dir < 0) && (rect->bottom() > top))
{
scroll_val += getf().rect->size.y;
glutPostRedisplay();
}
}
}
void draw(const float time) override
{
panel::draw(time);
my::ShowStringFont(std::to_string(scroll_val), 2, rect->center().x, rect->center().y, my::colori(0, 0, 200));
for (auto i : item)
{
if (i->isVisible)
{
i->draw(time);
//i->showName();
}
}
}
void update(const float time) override
{
for (auto i : item)
{
i->set_offset_pos(0, scroll_val);
if (visible(i->rect->center().y)) i->isVisible = true;
else i->isVisible = false;
}
}
};
class EditGame : public my::MyMessage
{
public:
ManagerLogick* man;
ScrollBarObject* bar_texture;
ScrollBarObject* bar_textBox;
textStatus* tex_stat;
/*textBox* textB;
textBox* textBx;
textBox* textBy;*/
std::vector<object*> objects_list;
EditGame()
{
click_message_edit = this;
}
~EditGame()
{
for (auto obj : objects_list)
delete obj;
objects_list.clear();
for (auto obj : texture_store)
delete obj;
texture_store.clear();
}
void addTileScrollBar(object* _obj, object* _parent)
{
_obj->isScroll = true;
ScrollBarObject* _par = dynamic_cast<ScrollBarObject*>(_parent);
_par->AddItem(_obj);
counter_tile++;
}
void init(ManagerLogick* _man)
{
man = _man;
showAllTextures(texture_store);
//скролинг панель для текстур
bar_texture = new ScrollBarObject(my::rectf(8, 10, my::width_sub - 16, my::HEI / 2));
objects_list.push_back((object*)bar_texture);
bar_texture->isShowName = false;
//скролинг панель статуса
bar_textBox = new ScrollBarObject(my::rectf(8, my::HEI / 2 + 80, my::width_sub - 16, my::HEI - 10));
//bar_textBox->setStatus(ScrollBarObject::LINE);
bar_textBox->setStatus(ScrollBarObject::CUSTOM);
objects_list.push_back((object*)bar_textBox);
//добовляю панель с текстурой
for (size_t i = 0; i < texture_store.size(); i++)
{
texture_panel* p = new texture_panel(texture_store[i], my::vec2f());
addTileScrollBar(p, bar_texture);
if (p->get_tex()->tex.width <= 10) p->name = "Clear";
}
tex_stat = new textStatus(bar_textBox->rect, 30);
addTileScrollBar(tex_stat->getName(), bar_textBox);
addTileScrollBar(tex_stat->getPosX(), bar_textBox);
addTileScrollBar(tex_stat->getPosY(), bar_textBox);
////-----------------------Name
//textB = new textBox(*bar_textBox->pos, my::vec2f(), my::vec2f(bar_textBox->rect->size.x, 20));
//textB->set_text(buff.tex->name);
//textB->IsFocuse(true);
//addTileScrollBar(textB, bar_textBox);
////-----------------------pos.X
//textBx = new textBox(*bar_textBox->pos, my::vec2f(0, 22), my::vec2f(100, 20));
//addTileScrollBar(textBx, bar_textBox);
////-----------------------pos.Y
//textBy = new textBox(*bar_textBox->pos, my::vec2f(0, 44), my::vec2f(100, 20));
//addTileScrollBar(textBy, bar_textBox);
printf("{%i}\n", counter_tile);
}
void click()
{
/*textB->set_text(buff.tex->name);
textBx->set_text("x = " + std::to_string(buff.obj->pos->pos.x));
textBy->set_text("y = " + std::to_string(buff.obj->pos->pos.y));*/
presset_status();
glutSetWindow(my::win_id[1]);
glutPostRedisplay();
}
void presset_status()
{
object* ob1 = dynamic_cast<object*>(buff.obj);
my::gameObject* ob2 = dynamic_cast<my::gameObject*>(buff.obj);
tex_stat->getName()->set_text(buff.tex->name);
//textB->set_text(buff.tex->name);
if (ob1)
{
tex_stat->getPosX()->set_text("x = " + std::to_string((int)ob1->pos->x));
tex_stat->getPosY()->set_text("y = " + std::to_string((int)ob1->pos->y));
/*textBx->set_text("x = " + std::to_string(ob1->pos->x));
textBy->set_text("y = " + std::to_string(ob1->pos->y));*/
}
else if (ob2)
{
tex_stat->getPosX()->set_text("x = " + std::to_string((int)ob2->pos->pos.x));
tex_stat->getPosY()->set_text("y = " + std::to_string((int)ob2->pos->pos.y));
/*textBx->set_text("x = " + std::to_string(ob2->pos->pos.x));
textBy->set_text("y = " + std::to_string(ob2->pos->pos.y));*/
}
}
void keyboard_up(unsigned char _key, int _x, int _y)
{
/*textB->keyboard_up(_key, _x, _y);*/
}
void mouse(int button, int state, int _x, int _y)
{
bar_texture->mouse(button, state, _x, _y);
bar_textBox->mouse(button, state, _x, _y);
click_message_edit->click();
}
void mouseWheel(int button, int dir, int _x, int _y)
{
bar_texture->mouseWheel(button, dir, _x, _y);
bar_textBox->mouseWheel(button, dir, _x, _y);
}
void draw(const float time) const
{
for (auto obj : objects_list)
{
obj->draw(time);
}
}
void update(const float time)
{
for (auto obj : objects_list)
{
obj->update(time);
}
}
};
} | [
"vovabelyaev1984@gmail.com"
] | vovabelyaev1984@gmail.com |
e3ebb88398a3e414e34ff68866d4331bb34921f5 | 2b30d2124f46e335fab96012feb1d98e60711a79 | /tc/srm210/500.cpp | 3fe7666f1f72fb22c908503fcb1666572c655507 | [] | no_license | ldfaiztt/algorithm-3 | 9ac150c5a1b67dccbe8f56c386f809fa99d3d4be | 8a1f078b291723459047b91064ee4d7b9da5e889 | refs/heads/master | 2021-01-15T10:36:09.657594 | 2014-07-09T18:23:48 | 2014-07-09T18:23:48 | 39,565,754 | 6 | 5 | null | 2015-07-23T12:21:18 | 2015-07-23T12:21:18 | null | UTF-8 | C++ | false | false | 7,637 | cpp | #include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
string get_location(string &_s, int &dir){
string turn_left = "Turn LEFT on ";
string turn_right = "Turn RIGHT on ";
string start = "Start on ";
if(_s.substr(0,turn_left.length() ) == turn_left){
dir = 0;
return _s.substr(turn_left.length(), _s.length() - turn_left.length());
}else if(_s.substr(0,turn_right.length()) == turn_right){
dir = 1;
return _s.substr(turn_right.length(), _s.length() - turn_right.length());
}else{
dir = 2;
return _s.substr(start.length(), _s.length() - start.length());
}
}
class DrivingDirections {
public:
vector <string> reverse(vector <string> directions) {
int sz = directions.size();
vector<string> ans;
string location;
int tmp, dir;
location = get_location(directions[sz-1], tmp);
ans.push_back("Start on "+location);
for(int i=directions.size()-2; i>=0; i--){
//int dir = -1;
//location = get_location(directions[i], dir);
int t;
location = get_location(directions[i], t);
get_location(directions[i+1], dir);
cout<<"look "<<i<<endl;
if(dir==0){
ans.push_back("Turn RIGHT on "+location);
}else if(dir==1){
ans.push_back("Turn LEFT on "+location);
}
}
return ans;
}
};
// BEGIN KAWIGIEDIT TESTING
// Generated by KawigiEdit 2.1.4 (beta) modified by pivanof
bool KawigiEdit_RunTest(int testNum, vector <string> p0, bool hasAnswer, vector <string> p1) {
cout << "Test " << testNum << ": [" << "{";
for (int i = 0; int(p0.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p0[i] << "\"";
}
cout << "}";
cout << "]" << endl;
DrivingDirections *obj;
vector <string> answer;
obj = new DrivingDirections();
clock_t startTime = clock();
answer = obj->reverse(p0);
clock_t endTime = clock();
delete obj;
bool res;
res = true;
cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl;
if (hasAnswer) {
cout << "Desired answer:" << endl;
cout << "\t" << "{";
for (int i = 0; int(p1.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << p1[i] << "\"";
}
cout << "}" << endl;
}
cout << "Your answer:" << endl;
cout << "\t" << "{";
for (int i = 0; int(answer.size()) > i; ++i) {
if (i > 0) {
cout << ",";
}
cout << "\"" << answer[i] << "\"";
}
cout << "}" << endl;
if (hasAnswer) {
if (answer.size() != p1.size()) {
res = false;
} else {
for (int i = 0; int(answer.size()) > i; ++i) {
if (answer[i] != p1[i]) {
res = false;
}
}
}
}
if (!res) {
cout << "DOESN'T MATCH!!!!" << endl;
} else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) {
cout << "FAIL the timeout" << endl;
res = false;
} else if (hasAnswer) {
cout << "Match :-)" << endl;
} else {
cout << "OK, but is it right?" << endl;
}
cout << "" << endl;
return res;
}
int main() {
bool all_right;
all_right = true;
vector <string> p0;
vector <string> p1;
{
// ----- test 0 -----
string t0[] = {"Start on Pirate Street","Turn LEFT on Viking Avenue","Turn RIGHT on Ninja Court"};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
string t1[] = {"Start on Ninja Court","Turn LEFT on Viking Avenue","Turn RIGHT on Pirate Street"};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
all_right = KawigiEdit_RunTest(0, p0, true, p1) && all_right;
// ------------------
}
{
// ----- test 1 -----
string t0[] = {"Start on planet Earth"};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
string t1[] = {"Start on planet Earth"};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
all_right = KawigiEdit_RunTest(1, p0, true, p1) && all_right;
// ------------------
}
{
// ----- test 2 -----
string t0[] = {"Start on Hebron Ave","Turn RIGHT on CT-2","Turn LEFT on I-84","Turn LEFT on I-81","Turn RIGHT on I-80","Turn LEFT on I-680","Turn RIGHT on Mission Blvd","Turn LEFT on I-880","Turn RIGHT on Montague Expressway","Turn RIGHT on Mission College Blvd"};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
string t1[] = {"Start on Mission College Blvd","Turn LEFT on Montague Expressway","Turn LEFT on I-880","Turn RIGHT on Mission Blvd","Turn LEFT on I-680","Turn RIGHT on I-80","Turn LEFT on I-81","Turn RIGHT on I-84","Turn RIGHT on CT-2","Turn LEFT on Hebron Ave"};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
all_right = KawigiEdit_RunTest(2, p0, true, p1) && all_right;
// ------------------
}
{
// ----- test 3 -----
string t0[] = {"Start on ","Turn LEFT on 0123456789 - ","Turn RIGHT on 0123456789 - ","Turn LEFT on ","Turn RIGHT on ","Turn LEFT on -a0b1c2d3e4f5g6h7i8j9k ","Turn RIGHT on -A0B1C2D3E4F5G6H7I8J9K ","Turn LEFT on -","Turn RIGHT on -"};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
string t1[] = {"Start on -","Turn LEFT on -","Turn RIGHT on -A0B1C2D3E4F5G6H7I8J9K ","Turn LEFT on -a0b1c2d3e4f5g6h7i8j9k ","Turn RIGHT on ","Turn LEFT on ","Turn RIGHT on 0123456789 - ","Turn LEFT on 0123456789 - ","Turn RIGHT on "};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
all_right = KawigiEdit_RunTest(3, p0, true, p1) && all_right;
// ------------------
}
{
// ----- test 4 -----
string t0[] = {"Start on Duke University Rd","Turn RIGHT on Swift Ave","Turn LEFT on NC-147","Turn LEFT on I-85","Turn RIGHT on I-40","Turn RIGHT on US-52","Turn LEFT on I-74","Turn RIGHT on I-77","Turn LEFT on I-64","Turn RIGHT on Martin Luther King Memorial Bridge","Turn RIGHT on N 3rd St","Turn LEFT on Cole St","Turn LEFT on N Broadway","Turn RIGHT on Convention Plz"};
p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0]));
string t1[] = {"Start on Convention Plz","Turn LEFT on N Broadway","Turn RIGHT on Cole St","Turn RIGHT on N 3rd St","Turn LEFT on Martin Luther King Memorial Bridge","Turn LEFT on I-64","Turn RIGHT on I-77","Turn LEFT on I-74","Turn RIGHT on US-52","Turn LEFT on I-40","Turn LEFT on I-85","Turn RIGHT on NC-147","Turn RIGHT on Swift Ave","Turn LEFT on Duke University Rd"};
p1.assign(t1, t1 + sizeof(t1) / sizeof(t1[0]));
all_right = KawigiEdit_RunTest(4, p0, true, p1) && all_right;
// ------------------
}
if (all_right) {
cout << "You're a stud (at least on the example cases)!" << endl;
} else {
cout << "Some of the test cases had errors." << endl;
}
return 0;
}
| [
"oeddyo@gmail.com"
] | oeddyo@gmail.com |
78e16b98678b660bce1f2e6b46031dfcb2da4d98 | 049a2e4b1d2c8201bfa18cc19d553213f6fa021c | /src/qt/bitcoin.cpp | 87f61a0452151a9e847827e6927f2a111768f28b | [
"MIT"
] | permissive | BlueDragon747/Blakecoin | 54936d6c125017a476c2c54dcc51f2cf97b99296 | 35e825a3ae319362b306df3c832c03aa6365d8ac | refs/heads/master | 2022-06-03T04:06:24.454695 | 2022-03-18T07:07:26 | 2022-03-18T07:07:26 | 13,365,558 | 12 | 13 | MIT | 2022-03-05T23:20:51 | 2013-10-06T17:02:20 | C++ | UTF-8 | C++ | false | false | 10,444 | cpp | /*
* W.J. van der Laan 2011-2012
*/
#include <QApplication>
#include "bitcoingui.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "optionsmodel.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include "paymentserver.h"
#include "splashscreen.h"
#include <QMessageBox>
#if QT_VERSION < 0x050000
#include <QTextCodec>
#endif
#include <QLocale>
#include <QTimer>
#include <QTranslator>
#include <QLibraryInfo>
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
#define _BITCOIN_QT_PLUGINS_INCLUDED
#define __INSURE__
#include <QtPlugin>
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtaccessiblewidgets)
#endif
// Declare meta types used for QMetaObject::invokeMethod
Q_DECLARE_METATYPE(bool*)
// Need a global reference for the notifications to find the GUI
static BitcoinGUI *guiref;
static SplashScreen *splashref;
static bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style)
{
// Message from network thread
if(guiref)
{
bool modal = (style & CClientUIInterface::MODAL);
bool ret = false;
// In case of modal message, use blocking connection to wait for user to click a button
QMetaObject::invokeMethod(guiref, "message",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message)),
Q_ARG(unsigned int, style),
Q_ARG(bool*, &ret));
return ret;
}
else
{
printf("%s: %s\n", caption.c_str(), message.c_str());
fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
return false;
}
}
static bool ThreadSafeAskFee(int64 nFeeRequired)
{
if(!guiref)
return false;
if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon)
return true;
bool payFee = false;
QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
Q_ARG(qint64, nFeeRequired),
Q_ARG(bool*, &payFee));
return payFee;
}
static void InitMessage(const std::string &message)
{
if(splashref)
{
splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55));
qApp->processEvents();
}
printf("init message: %s\n", message.c_str());
}
/*
Translate string to current locale using Qt.
*/
static std::string Translate(const char* psz)
{
return QCoreApplication::translate("blakecoin-core", psz).toStdString();
}
/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
*/
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Blakecoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
#ifndef BITCOIN_QT_TEST
int main(int argc, char *argv[])
{
// Command-line options take precedence:
ParseParameters(argc, argv);
#if QT_VERSION < 0x050000
// Internal string conversion is all UTF-8
QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
#endif
Q_INIT_RESOURCE(bitcoin);
QApplication app(argc, argv);
// Register meta types used for QMetaObject::invokeMethod
qRegisterMetaType< bool* >();
// Do this early as we don't want to bother initializing if we are just calling IPC
// ... but do it after creating app, so QCoreApplication::arguments is initialized:
if (PaymentServer::ipcSendCommandLine())
exit(0);
PaymentServer* paymentServer = new PaymentServer(&app);
// Install global event filter that makes sure that long tooltips can be word-wrapped
app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
// ... then blakecoin.conf:
if (!boost::filesystem::is_directory(GetDataDir(false)))
{
// This message can not be translated, as translation is not initialized yet
// (which not yet possible because lang=XX can be overridden in blakecoin.conf in the data directory)
QMessageBox::critical(0, "Blakecoin",
QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
ReadConfigFile(mapArgs, mapMultiArgs);
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
QApplication::setOrganizationName("Blakecoin");
QApplication::setOrganizationDomain("Blakecoin.org");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
QApplication::setApplicationName("Blakecoin-Qt-testnet");
else
QApplication::setApplicationName("Blakecoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
// Get desired locale (e.g. "de_DE") from command line or use system locale
QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
QString lang = lang_territory;
// Convert to "de" only by truncating "_DE"
lang.truncate(lang_territory.lastIndexOf('_'));
QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
// Load language files for configured locale:
// - First load the translator for the base language, without territory
// - Then load the more specific locale translator
// Load e.g. qt_de.qm
if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslatorBase);
// Load e.g. qt_de_DE.qm
if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
app.installTranslator(&qtTranslator);
// Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
if (translatorBase.load(lang, ":/translations/"))
app.installTranslator(&translatorBase);
// Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
if (translator.load(lang_territory, ":/translations/"))
app.installTranslator(&translator);
// Subscribe to global signals from core
uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
uiInterface.InitMessage.connect(InitMessage);
uiInterface.Translate.connect(Translate);
// Show help message immediately after parsing command-line options (for "-lang") and setting locale,
// but before showing splash screen.
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
GUIUtil::HelpMessageBox help;
help.showOrPrint();
return 1;
}
#ifdef Q_OS_MAC
// on mac, also change the icon now because it would look strange to have a testnet splash (green) and a std app icon (orange)
if(GetBoolArg("-testnet")) {
MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet"));
}
#endif
SplashScreen splash(QPixmap(), 0);
if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
{
splash.show();
splash.setAutoFillBackground(true);
splashref = &splash;
}
app.processEvents();
app.setQuitOnLastWindowClosed(false);
try
{
#ifndef Q_OS_MAC
// Regenerate startup link, to fix links to old versions
// OSX: makes no sense on mac and might also scan/mount external (and sleeping) volumes (can take up some secs)
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(true);
#endif
boost::thread_group threadGroup;
BitcoinGUI window;
guiref = &window;
QTimer* pollShutdownTimer = new QTimer(guiref);
QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown()));
pollShutdownTimer->start(200);
if(AppInit2(threadGroup))
{
{
// Put this in a block, so that the Model objects are cleaned up before
// calling Shutdown().
optionsModel.Upgrade(); // Must be done after AppInit2
if (splashref)
splash.finish(&window);
ClientModel clientModel(&optionsModel);
WalletModel walletModel(pwalletMain, &optionsModel);
window.setClientModel(&clientModel);
window.addWallet("~Default", &walletModel);
window.setCurrentWallet("~Default");
// If -min option passed, start window minimized.
if(GetBoolArg("-min"))
{
window.showMinimized();
}
else
{
window.show();
}
// Now that initialization/startup is done, process any command-line
// blakecoin: URIs
QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString)));
QTimer::singleShot(100, paymentServer, SLOT(uiReady()));
app.exec();
window.hide();
window.setClientModel(0);
window.removeAllWallets();
guiref = 0;
}
// Shutdown the core and its threads, but don't exit Blakecoin-Qt here
threadGroup.interrupt_all();
threadGroup.join_all();
Shutdown();
}
else
{
threadGroup.interrupt_all();
threadGroup.join_all();
Shutdown();
return 1;
}
} catch (std::exception& e) {
handleRunawayException(&e);
} catch (...) {
handleRunawayException(NULL);
}
return 0;
}
#endif // BITCOIN_QT_TEST
| [
"bluedragon747@gmail.com"
] | bluedragon747@gmail.com |
14e30181d4ca60a91ba6e8ef837350065262a742 | a8e1a37048dd33a883e9c07afd943303277636e0 | /TerminalVelocityJni/jni/ViewManager/ViewManager.cpp | cab3d397424aa19799577a60a3789a9983c86dc0 | [] | no_license | maxhappy/TerVel | ec6a75473fdde0c2a60cc68e6e83d675931622c1 | d256452a22bba81898ddc5ee59127fa7a8586088 | refs/heads/master | 2021-01-10T07:24:22.681322 | 2016-01-14T20:21:32 | 2016-01-14T20:21:32 | 49,662,995 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 217 | cpp | /*
* ViewManager.cpp
*
* Created on: 29-Oct-2012
* Author: Praveen Ojha
*/
#include "ViewManager.h"
#include <jni.h>
ViewManager::ViewManager()
{
this->screenstate=0;
}
ViewManager::~ViewManager()
{
}
| [
"inductionlabs1@gmail.com"
] | inductionlabs1@gmail.com |
7244987a9b7f3e31797826b614d41c843dac00f4 | 06681bca998dae0aa57bd761a5788542e7b1c821 | /p686 - Goldbach’s Conjecture (II)/p686 - Goldbach’s Conjecture (II).cpp | 8d253be64f259e89828381b8754a459781aaf27e | [] | no_license | sarafinmahtab/Solved-UVA-Problems | 11f89aaf6f2e44922c9f9d0457d224d191db1066 | 0d5b59363d0c4537c2a142ef6ec40f4b43afbc81 | refs/heads/master | 2021-10-22T11:43:12.200718 | 2019-03-10T14:33:11 | 2019-03-10T14:33:11 | 111,911,644 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 998 | cpp | #include<bits/stdc++.h>
using namespace std;
int r = 1000000;
int main()
{
bool arr[r];
int i, j, sq, n;
sq = sqrt(r);
memset(arr, true, sizeof(arr));
for(i = 4; i < r; i += 2)
{
arr[i] = false;
}
for(i = 3; i <= sq; i += 2)
{
if(arr[i])
{
for(j = i+i; j < r; j += i)
{
arr[j] = false;
}
}
}
arr[0] = false;
arr[1] = false;
int cnt;
while(scanf("%d", &n) == 1 && n != 0)
{
cnt = 0;
if(arr[2] && arr[n-2])
{
cnt++;
}
for(i = 3; i < n; i += 2)
{
if(arr[i] && arr[n-i])
{
cnt++;
}
}
if(cnt%2 == 0)
{
cnt = cnt / 2;
printf("%d\n", cnt);
}
else
{
cnt = cnt + 1;
cnt = cnt / 2;
printf("%d\n", cnt);
}
}
return 0;
}
| [
"arafinmahtab@gmail.com"
] | arafinmahtab@gmail.com |
eaf095dbf4eb8dbed7655c29f60c585d16411ebe | 7d16adc41050099c5dbbb79f06aaea3bfade2569 | /src/python/cupoch_pybind/collision/collision.cpp | 54de3ea35e1b68573da8cdcf5c1dd6e82c81841a | [
"MIT"
] | permissive | kimsoohwan/cupoch | 88f8decd94066c313b5953fc0cfce493b3be6e85 | 44af0956d84fec676c22dad327e68f3e77451dc3 | refs/heads/master | 2022-11-23T09:38:10.344971 | 2020-08-02T08:45:27 | 2020-08-02T09:13:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,568 | cpp | /**
* Copyright (c) 2020 Neka-Nat
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
**/
#include "cupoch_pybind/collision/collision.h"
#include "cupoch/collision/collision.h"
#include "cupoch/geometry/lineset.h"
#include "cupoch/geometry/occupancygrid.h"
#include "cupoch/geometry/voxelgrid.h"
#include "cupoch_pybind/docstring.h"
using namespace cupoch;
void pybind_collision_methods(py::module& m) {
py::class_<collision::CollisionResult,
std::shared_ptr<collision::CollisionResult>>
col_res(m, "CollitionResult", "Collision result class.");
py::detail::bind_default_constructor<collision::CollisionResult>(col_res);
py::detail::bind_copy_functions<collision::CollisionResult>(col_res);
col_res.def("is_collided", &collision::CollisionResult::IsCollided)
.def_property(
"collision_index_pairs",
[](collision::CollisionResult& res) {
return wrapper::device_vector_vector2i(
res.collision_index_pairs_);
},
[](collision::CollisionResult& res,
const wrapper::device_vector_vector2i& vec) {
wrapper::FromWrapper(res.collision_index_pairs_, vec);
});
py::enum_<collision::CollisionResult::CollisionType> collision_type(
col_res, "Type", py::arithmetic());
collision_type
.value("Unspecified",
collision::CollisionResult::CollisionType::Unspecified)
.value("Primitives",
collision::CollisionResult::CollisionType::Primitives)
.value("VoxelGrid",
collision::CollisionResult::CollisionType::VoxelGrid)
.value("OccupancyGrid",
collision::CollisionResult::CollisionType::OccupancyGrid)
.value("LineSet",
collision::CollisionResult::CollisionType::LineSet)
.export_values();
m.def("compute_intersection",
py::overload_cast<const geometry::VoxelGrid&,
const geometry::VoxelGrid&, float>(
&collision::ComputeIntersection));
m.def("compute_intersection",
py::overload_cast<const geometry::VoxelGrid&,
const geometry::LineSet<3>&, float>(
&collision::ComputeIntersection));
m.def("compute_intersection",
py::overload_cast<const geometry::LineSet<3>&,
const geometry::VoxelGrid&, float>(
&collision::ComputeIntersection));
m.def("compute_intersection",
py::overload_cast<const geometry::VoxelGrid&,
const geometry::OccupancyGrid&, float>(
&collision::ComputeIntersection));
m.def("compute_intersection",
py::overload_cast<const geometry::OccupancyGrid&,
const geometry::VoxelGrid&, float>(
&collision::ComputeIntersection));
m.def("compute_intersection",
[](const wrapper::device_vector_primitives& primitives,
const geometry::VoxelGrid& voxel, float margin) {
return collision::ComputeIntersection(primitives.data_, voxel,
margin);
});
m.def("compute_intersection",
[](const geometry::VoxelGrid& voxel,
const wrapper::device_vector_primitives& primitives,
float margin) {
return collision::ComputeIntersection(voxel, primitives.data_,
margin);
});
m.def("compute_intersection",
[](const wrapper::device_vector_primitives& primitives,
const geometry::OccupancyGrid& occgrid, float margin) {
return collision::ComputeIntersection(primitives.data_, occgrid,
margin);
});
m.def("compute_intersection",
[](const geometry::OccupancyGrid& occgrid,
const wrapper::device_vector_primitives& primitives,
float margin) {
return collision::ComputeIntersection(occgrid, primitives.data_,
margin);
});
}
void pybind_collision(py::module& m) {
py::module m_submodule = m.def_submodule("collision");
pybind_collision_methods(m_submodule);
pybind_primitives(m_submodule);
} | [
"nekanat.stock@gmail.com"
] | nekanat.stock@gmail.com |
4c9662670cd25cba56bb1c4172910d07c8fbc7e5 | c65d154be87b7fc7229bad3d484122934f3e99aa | /19120075/Bai01/Bai01.cpp | ee773030ed9e630957a7b7450b7f3358320147d9 | [] | no_license | vophiminhhieu/OOP | 4c4e0394954ca4c702572557c55731dfdd917ec4 | 60be07f257dcf6e11d7f331e5d004a42fc64b401 | refs/heads/master | 2023-04-26T01:39:54.740265 | 2021-06-02T09:16:06 | 2021-06-02T09:16:06 | 373,104,381 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,477 | cpp | #include "Detail.h"
#include "DetailItem.h"
#include "SubDetail.h"
#include "Machine.h"
void menuPrint() {
cout << endl << endl << endl;
cout << " MENU" << endl;
cout << " [1] . Nhap cac chi tiet cho may" << endl;
cout << " [2] . Tim kiem mot chi tiet may theo ma so" << endl;
cout << " [3] . Tinh tien cho mot chi tiet may, hoac cho may" << endl;
cout << " [4] . Xuat cac chi tiet may" << endl;
cout << " [5] . Dem so luong chi tiet don co trong cai may" << endl;
cout << " [6] . Thoat" << endl;
cout << endl << endl;
cout << " Moi ban nhap lua chon : ";
}
DetailItem* option1() {
cout << " Moi ban nhap them chi tiet moi. Ban muon nhap chi tiet don (0) hay phuc (1) : ";
int option = 0;
cin >> option;
DetailItem* dtItem;
string id;
double price;
int count;
cout << "Moi ban nhap id: ";
cin >> id;
if (option == 0) {
cout << "Moi ban nhap gia: ";
cin >> price;
dtItem = new SubDetail(id, price);
}
else {
cout << "Moi ban nhap so luong chi tiet con (>=1) : ";
cin >> count;
vector<DetailItem*> dt;
dt.resize(count);
for (int i = 0; i < count; i++) {
cout << "-------------- Moi ban nhap chi tiet thu " << (i + 1) << " --------"<<endl;
dt[i] = option1();
}
dtItem = new Detail(dt, count, id);
}
return dtItem;
}
int main()
{
Machine machine;
int option = 0;
menuPrint();
cin >> option;
system("cls");
while (option != 6) {
if (option == 1)
{
machine.Add(option1());
system("cls");
}
else if (option == 2) {
DetailItem* it = machine.Search();
if (it != nullptr) {
cout << "Da tim thay chi tiet cua ban tim: " << endl << it->toString() << endl;
}
else {
cout << "Khong tim thay chi tiet can tim!!" << endl;
}
}
else if (option == 3) {
cout << "Ban muon tinh tien cho chi tiet (0) hay cho may (1): ";
int subOption = 0; cin >> subOption;
if (subOption == 0) {
DetailItem* it = machine.Search();
if (it != nullptr) {
cout << "Tong tien: " << machine.MoneyDetail(it);
}
else {
cout << "Khong tim thay chi tiet can tim!!" << endl;
}
}
else {
cout << "Tong tien: " << machine.MoneyMachine();
}
}
else if (option == 4) {
machine.Show();
}
else if (option == 5) {
cout << "Tong so chi tiet don la: " << machine.countSubDetail() << endl;
}
menuPrint();
cin >> option;
system("cls");
}
} | [
"minhhieu.maicogroup@gmail.com"
] | minhhieu.maicogroup@gmail.com |
6a09ef2d61804c4d80691d2a21094f4315aca629 | c776476e9d06b3779d744641e758ac3a2c15cddc | /examples/litmus/c/run-scripts/tmp_5/R+dmb.sy+dmb.ldpa.c.cbmc.cpp | e164d077958511adc149cd1153466fac4ce5c65c | [] | no_license | ashutosh0gupta/llvm_bmc | aaac7961c723ba6f7ffd77a39559e0e52432eade | 0287c4fb180244e6b3c599a9902507f05c8a7234 | refs/heads/master | 2023-08-02T17:14:06.178723 | 2023-07-31T10:46:53 | 2023-07-31T10:46:53 | 143,100,825 | 3 | 4 | null | 2023-05-25T05:50:55 | 2018-08-01T03:47:00 | C++ | UTF-8 | C++ | false | false | 25,886 | cpp | // Global variabls:
// 0:vars:2
// 2:atom_1_X2_0:1
// Local global variabls:
// 0:thr0:1
// 1:thr1:1
#define ADDRSIZE 3
#define LOCALADDRSIZE 2
#define NTHREAD 3
#define NCONTEXT 5
#define ASSUME(stmt) __CPROVER_assume(stmt)
#define ASSERT(stmt) __CPROVER_assert(stmt, "error")
#define max(a,b) (a>b?a:b)
char __get_rng();
char get_rng( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
char get_rng_th( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
int main(int argc, char **argv) {
// Declare arrays for intial value version in contexts
int local_mem[LOCALADDRSIZE];
// Dumping initializations
local_mem[0+0] = 0;
local_mem[1+0] = 0;
int cstart[NTHREAD];
int creturn[NTHREAD];
// declare arrays for contexts activity
int active[NCONTEXT];
int ctx_used[NCONTEXT];
// declare arrays for intial value version in contexts
int meminit_[ADDRSIZE*NCONTEXT];
#define meminit(x,k) meminit_[(x)*NCONTEXT+k]
int coinit_[ADDRSIZE*NCONTEXT];
#define coinit(x,k) coinit_[(x)*NCONTEXT+k]
int deltainit_[ADDRSIZE*NCONTEXT];
#define deltainit(x,k) deltainit_[(x)*NCONTEXT+k]
// declare arrays for running value version in contexts
int mem_[ADDRSIZE*NCONTEXT];
#define mem(x,k) mem_[(x)*NCONTEXT+k]
int co_[ADDRSIZE*NCONTEXT];
#define co(x,k) co_[(x)*NCONTEXT+k]
int delta_[ADDRSIZE*NCONTEXT];
#define delta(x,k) delta_[(x)*NCONTEXT+k]
// declare arrays for local buffer and observed writes
int buff_[NTHREAD*ADDRSIZE];
#define buff(x,k) buff_[(x)*ADDRSIZE+k]
int pw_[NTHREAD*ADDRSIZE];
#define pw(x,k) pw_[(x)*ADDRSIZE+k]
// declare arrays for context stamps
char cr_[NTHREAD*ADDRSIZE];
#define cr(x,k) cr_[(x)*ADDRSIZE+k]
char iw_[NTHREAD*ADDRSIZE];
#define iw(x,k) iw_[(x)*ADDRSIZE+k]
char cw_[NTHREAD*ADDRSIZE];
#define cw(x,k) cw_[(x)*ADDRSIZE+k]
char cx_[NTHREAD*ADDRSIZE];
#define cx(x,k) cx_[(x)*ADDRSIZE+k]
char is_[NTHREAD*ADDRSIZE];
#define is(x,k) is_[(x)*ADDRSIZE+k]
char cs_[NTHREAD*ADDRSIZE];
#define cs(x,k) cs_[(x)*ADDRSIZE+k]
char crmax_[NTHREAD*ADDRSIZE];
#define crmax(x,k) crmax_[(x)*ADDRSIZE+k]
char sforbid_[ADDRSIZE*NCONTEXT];
#define sforbid(x,k) sforbid_[(x)*NCONTEXT+k]
// declare arrays for synchronizations
int cl[NTHREAD];
int cdy[NTHREAD];
int cds[NTHREAD];
int cdl[NTHREAD];
int cisb[NTHREAD];
int caddr[NTHREAD];
int cctrl[NTHREAD];
__LOCALS__
buff(0,0) = 0;
pw(0,0) = 0;
cr(0,0) = 0;
iw(0,0) = 0;
cw(0,0) = 0;
cx(0,0) = 0;
is(0,0) = 0;
cs(0,0) = 0;
crmax(0,0) = 0;
buff(0,1) = 0;
pw(0,1) = 0;
cr(0,1) = 0;
iw(0,1) = 0;
cw(0,1) = 0;
cx(0,1) = 0;
is(0,1) = 0;
cs(0,1) = 0;
crmax(0,1) = 0;
buff(0,2) = 0;
pw(0,2) = 0;
cr(0,2) = 0;
iw(0,2) = 0;
cw(0,2) = 0;
cx(0,2) = 0;
is(0,2) = 0;
cs(0,2) = 0;
crmax(0,2) = 0;
cl[0] = 0;
cdy[0] = 0;
cds[0] = 0;
cdl[0] = 0;
cisb[0] = 0;
caddr[0] = 0;
cctrl[0] = 0;
cstart[0] = get_rng(0,NCONTEXT-1);
creturn[0] = get_rng(0,NCONTEXT-1);
buff(1,0) = 0;
pw(1,0) = 0;
cr(1,0) = 0;
iw(1,0) = 0;
cw(1,0) = 0;
cx(1,0) = 0;
is(1,0) = 0;
cs(1,0) = 0;
crmax(1,0) = 0;
buff(1,1) = 0;
pw(1,1) = 0;
cr(1,1) = 0;
iw(1,1) = 0;
cw(1,1) = 0;
cx(1,1) = 0;
is(1,1) = 0;
cs(1,1) = 0;
crmax(1,1) = 0;
buff(1,2) = 0;
pw(1,2) = 0;
cr(1,2) = 0;
iw(1,2) = 0;
cw(1,2) = 0;
cx(1,2) = 0;
is(1,2) = 0;
cs(1,2) = 0;
crmax(1,2) = 0;
cl[1] = 0;
cdy[1] = 0;
cds[1] = 0;
cdl[1] = 0;
cisb[1] = 0;
caddr[1] = 0;
cctrl[1] = 0;
cstart[1] = get_rng(0,NCONTEXT-1);
creturn[1] = get_rng(0,NCONTEXT-1);
buff(2,0) = 0;
pw(2,0) = 0;
cr(2,0) = 0;
iw(2,0) = 0;
cw(2,0) = 0;
cx(2,0) = 0;
is(2,0) = 0;
cs(2,0) = 0;
crmax(2,0) = 0;
buff(2,1) = 0;
pw(2,1) = 0;
cr(2,1) = 0;
iw(2,1) = 0;
cw(2,1) = 0;
cx(2,1) = 0;
is(2,1) = 0;
cs(2,1) = 0;
crmax(2,1) = 0;
buff(2,2) = 0;
pw(2,2) = 0;
cr(2,2) = 0;
iw(2,2) = 0;
cw(2,2) = 0;
cx(2,2) = 0;
is(2,2) = 0;
cs(2,2) = 0;
crmax(2,2) = 0;
cl[2] = 0;
cdy[2] = 0;
cds[2] = 0;
cdl[2] = 0;
cisb[2] = 0;
caddr[2] = 0;
cctrl[2] = 0;
cstart[2] = get_rng(0,NCONTEXT-1);
creturn[2] = get_rng(0,NCONTEXT-1);
// Dumping initializations
mem(0+0,0) = 0;
mem(0+1,0) = 0;
mem(2+0,0) = 0;
// Dumping context matching equalities
co(0,0) = 0;
delta(0,0) = -1;
mem(0,1) = meminit(0,1);
co(0,1) = coinit(0,1);
delta(0,1) = deltainit(0,1);
mem(0,2) = meminit(0,2);
co(0,2) = coinit(0,2);
delta(0,2) = deltainit(0,2);
mem(0,3) = meminit(0,3);
co(0,3) = coinit(0,3);
delta(0,3) = deltainit(0,3);
mem(0,4) = meminit(0,4);
co(0,4) = coinit(0,4);
delta(0,4) = deltainit(0,4);
co(1,0) = 0;
delta(1,0) = -1;
mem(1,1) = meminit(1,1);
co(1,1) = coinit(1,1);
delta(1,1) = deltainit(1,1);
mem(1,2) = meminit(1,2);
co(1,2) = coinit(1,2);
delta(1,2) = deltainit(1,2);
mem(1,3) = meminit(1,3);
co(1,3) = coinit(1,3);
delta(1,3) = deltainit(1,3);
mem(1,4) = meminit(1,4);
co(1,4) = coinit(1,4);
delta(1,4) = deltainit(1,4);
co(2,0) = 0;
delta(2,0) = -1;
mem(2,1) = meminit(2,1);
co(2,1) = coinit(2,1);
delta(2,1) = deltainit(2,1);
mem(2,2) = meminit(2,2);
co(2,2) = coinit(2,2);
delta(2,2) = deltainit(2,2);
mem(2,3) = meminit(2,3);
co(2,3) = coinit(2,3);
delta(2,3) = deltainit(2,3);
mem(2,4) = meminit(2,4);
co(2,4) = coinit(2,4);
delta(2,4) = deltainit(2,4);
// Dumping thread 1
int ret_thread_1 = 0;
cdy[1] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[1] >= cstart[1]);
T1BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !34, metadata !DIExpression()), !dbg !43
// br label %label_1, !dbg !44
goto T1BLOCK1;
T1BLOCK1:
// call void @llvm.dbg.label(metadata !42), !dbg !45
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !35, metadata !DIExpression()), !dbg !46
// call void @llvm.dbg.value(metadata i64 1, metadata !38, metadata !DIExpression()), !dbg !46
// store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !47
// ST: Guess
iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l19_c3
old_cw = cw(1,0);
cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l19_c3
// Check
ASSUME(active[iw(1,0)] == 1);
ASSUME(active[cw(1,0)] == 1);
ASSUME(sforbid(0,cw(1,0))== 0);
ASSUME(iw(1,0) >= 0);
ASSUME(iw(1,0) >= 0);
ASSUME(cw(1,0) >= iw(1,0));
ASSUME(cw(1,0) >= old_cw);
ASSUME(cw(1,0) >= cr(1,0));
ASSUME(cw(1,0) >= cl[1]);
ASSUME(cw(1,0) >= cisb[1]);
ASSUME(cw(1,0) >= cdy[1]);
ASSUME(cw(1,0) >= cdl[1]);
ASSUME(cw(1,0) >= cds[1]);
ASSUME(cw(1,0) >= cctrl[1]);
ASSUME(cw(1,0) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0) = 1;
mem(0,cw(1,0)) = 1;
co(0,cw(1,0))+=1;
delta(0,cw(1,0)) = -1;
ASSUME(creturn[1] >= cw(1,0));
// call void (...) @dmbsy(), !dbg !48
// dumbsy: Guess
old_cdy = cdy[1];
cdy[1] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[1] >= old_cdy);
ASSUME(cdy[1] >= cisb[1]);
ASSUME(cdy[1] >= cdl[1]);
ASSUME(cdy[1] >= cds[1]);
ASSUME(cdy[1] >= cctrl[1]);
ASSUME(cdy[1] >= cw(1,0+0));
ASSUME(cdy[1] >= cw(1,0+1));
ASSUME(cdy[1] >= cw(1,2+0));
ASSUME(cdy[1] >= cr(1,0+0));
ASSUME(cdy[1] >= cr(1,0+1));
ASSUME(cdy[1] >= cr(1,2+0));
ASSUME(creturn[1] >= cdy[1]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !39, metadata !DIExpression()), !dbg !49
// call void @llvm.dbg.value(metadata i64 1, metadata !41, metadata !DIExpression()), !dbg !49
// store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !50
// ST: Guess
iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l21_c3
old_cw = cw(1,0+1*1);
cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l21_c3
// Check
ASSUME(active[iw(1,0+1*1)] == 1);
ASSUME(active[cw(1,0+1*1)] == 1);
ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(iw(1,0+1*1) >= 0);
ASSUME(cw(1,0+1*1) >= iw(1,0+1*1));
ASSUME(cw(1,0+1*1) >= old_cw);
ASSUME(cw(1,0+1*1) >= cr(1,0+1*1));
ASSUME(cw(1,0+1*1) >= cl[1]);
ASSUME(cw(1,0+1*1) >= cisb[1]);
ASSUME(cw(1,0+1*1) >= cdy[1]);
ASSUME(cw(1,0+1*1) >= cdl[1]);
ASSUME(cw(1,0+1*1) >= cds[1]);
ASSUME(cw(1,0+1*1) >= cctrl[1]);
ASSUME(cw(1,0+1*1) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0+1*1) = 1;
mem(0+1*1,cw(1,0+1*1)) = 1;
co(0+1*1,cw(1,0+1*1))+=1;
delta(0+1*1,cw(1,0+1*1)) = -1;
ASSUME(creturn[1] >= cw(1,0+1*1));
// ret i8* null, !dbg !51
ret_thread_1 = (- 1);
goto T1BLOCK_END;
T1BLOCK_END:
// Dumping thread 2
int ret_thread_2 = 0;
cdy[2] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[2] >= cstart[2]);
T2BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !54, metadata !DIExpression()), !dbg !64
// br label %label_2, !dbg !46
goto T2BLOCK1;
T2BLOCK1:
// call void @llvm.dbg.label(metadata !63), !dbg !66
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !55, metadata !DIExpression()), !dbg !67
// call void @llvm.dbg.value(metadata i64 2, metadata !57, metadata !DIExpression()), !dbg !67
// store atomic i64 2, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !49
// ST: Guess
iw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l27_c3
old_cw = cw(2,0+1*1);
cw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l27_c3
// Check
ASSUME(active[iw(2,0+1*1)] == 2);
ASSUME(active[cw(2,0+1*1)] == 2);
ASSUME(sforbid(0+1*1,cw(2,0+1*1))== 0);
ASSUME(iw(2,0+1*1) >= 0);
ASSUME(iw(2,0+1*1) >= 0);
ASSUME(cw(2,0+1*1) >= iw(2,0+1*1));
ASSUME(cw(2,0+1*1) >= old_cw);
ASSUME(cw(2,0+1*1) >= cr(2,0+1*1));
ASSUME(cw(2,0+1*1) >= cl[2]);
ASSUME(cw(2,0+1*1) >= cisb[2]);
ASSUME(cw(2,0+1*1) >= cdy[2]);
ASSUME(cw(2,0+1*1) >= cdl[2]);
ASSUME(cw(2,0+1*1) >= cds[2]);
ASSUME(cw(2,0+1*1) >= cctrl[2]);
ASSUME(cw(2,0+1*1) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,0+1*1) = 2;
mem(0+1*1,cw(2,0+1*1)) = 2;
co(0+1*1,cw(2,0+1*1))+=1;
delta(0+1*1,cw(2,0+1*1)) = -1;
ASSUME(creturn[2] >= cw(2,0+1*1));
// call void (...) @dmbld(), !dbg !50
// dumbld: Guess
cdl[2] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdl[2] >= cdy[2]);
ASSUME(cdl[2] >= cr(2,0+0));
ASSUME(cdl[2] >= cr(2,0+1));
ASSUME(cdl[2] >= cr(2,2+0));
ASSUME(creturn[2] >= cdl[2]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !59, metadata !DIExpression()), !dbg !70
// %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) acquire, align 8, !dbg !52
// LD: Guess
// : Acquire
old_cr = cr(2,0);
cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM _l29_c15
// Check
ASSUME(active[cr(2,0)] == 2);
ASSUME(cr(2,0) >= iw(2,0));
ASSUME(cr(2,0) >= 0);
ASSUME(cr(2,0) >= cdy[2]);
ASSUME(cr(2,0) >= cisb[2]);
ASSUME(cr(2,0) >= cdl[2]);
ASSUME(cr(2,0) >= cl[2]);
ASSUME(cr(2,0) >= cx(2,0));
ASSUME(cr(2,0) >= cs(2,0+0));
ASSUME(cr(2,0) >= cs(2,0+1));
ASSUME(cr(2,0) >= cs(2,2+0));
// Update
creg_r0 = cr(2,0);
crmax(2,0) = max(crmax(2,0),cr(2,0));
caddr[2] = max(caddr[2],0);
if(cr(2,0) < cw(2,0)) {
r0 = buff(2,0);
ASSUME((!(( (cw(2,0) < 1) && (1 < crmax(2,0)) )))||(sforbid(0,1)> 0));
ASSUME((!(( (cw(2,0) < 2) && (2 < crmax(2,0)) )))||(sforbid(0,2)> 0));
ASSUME((!(( (cw(2,0) < 3) && (3 < crmax(2,0)) )))||(sforbid(0,3)> 0));
ASSUME((!(( (cw(2,0) < 4) && (4 < crmax(2,0)) )))||(sforbid(0,4)> 0));
} else {
if(pw(2,0) != co(0,cr(2,0))) {
ASSUME(cr(2,0) >= old_cr);
}
pw(2,0) = co(0,cr(2,0));
r0 = mem(0,cr(2,0));
}
cl[2] = max(cl[2],cr(2,0));
ASSUME(creturn[2] >= cr(2,0));
// call void @llvm.dbg.value(metadata i64 %0, metadata !61, metadata !DIExpression()), !dbg !70
// %conv = trunc i64 %0 to i32, !dbg !53
// call void @llvm.dbg.value(metadata i32 %conv, metadata !58, metadata !DIExpression()), !dbg !64
// %cmp = icmp eq i32 %conv, 0, !dbg !54
creg__r0__0_ = max(0,creg_r0);
// %conv1 = zext i1 %cmp to i32, !dbg !54
// call void @llvm.dbg.value(metadata i32 %conv1, metadata !62, metadata !DIExpression()), !dbg !64
// store i32 %conv1, i32* @atom_1_X2_0, align 4, !dbg !55, !tbaa !56
// ST: Guess
iw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l31_c15
old_cw = cw(2,2);
cw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l31_c15
// Check
ASSUME(active[iw(2,2)] == 2);
ASSUME(active[cw(2,2)] == 2);
ASSUME(sforbid(2,cw(2,2))== 0);
ASSUME(iw(2,2) >= creg__r0__0_);
ASSUME(iw(2,2) >= 0);
ASSUME(cw(2,2) >= iw(2,2));
ASSUME(cw(2,2) >= old_cw);
ASSUME(cw(2,2) >= cr(2,2));
ASSUME(cw(2,2) >= cl[2]);
ASSUME(cw(2,2) >= cisb[2]);
ASSUME(cw(2,2) >= cdy[2]);
ASSUME(cw(2,2) >= cdl[2]);
ASSUME(cw(2,2) >= cds[2]);
ASSUME(cw(2,2) >= cctrl[2]);
ASSUME(cw(2,2) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,2) = (r0==0);
mem(2,cw(2,2)) = (r0==0);
co(2,cw(2,2))+=1;
delta(2,cw(2,2)) = -1;
ASSUME(creturn[2] >= cw(2,2));
// ret i8* null, !dbg !60
ret_thread_2 = (- 1);
goto T2BLOCK_END;
T2BLOCK_END:
// Dumping thread 0
int ret_thread_0 = 0;
cdy[0] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[0] >= cstart[0]);
T0BLOCK0:
// %thr0 = alloca i64, align 8
// %thr1 = alloca i64, align 8
// call void @llvm.dbg.value(metadata i32 %argc, metadata !87, metadata !DIExpression()), !dbg !107
// call void @llvm.dbg.value(metadata i8** %argv, metadata !88, metadata !DIExpression()), !dbg !107
// %0 = bitcast i64* %thr0 to i8*, !dbg !59
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #6, !dbg !59
// call void @llvm.dbg.declare(metadata i64* %thr0, metadata !89, metadata !DIExpression()), !dbg !109
// %1 = bitcast i64* %thr1 to i8*, !dbg !61
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #6, !dbg !61
// call void @llvm.dbg.declare(metadata i64* %thr1, metadata !93, metadata !DIExpression()), !dbg !111
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !94, metadata !DIExpression()), !dbg !112
// call void @llvm.dbg.value(metadata i64 0, metadata !96, metadata !DIExpression()), !dbg !112
// store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !64
// ST: Guess
iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l39_c3
old_cw = cw(0,0+1*1);
cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l39_c3
// Check
ASSUME(active[iw(0,0+1*1)] == 0);
ASSUME(active[cw(0,0+1*1)] == 0);
ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(cw(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cw(0,0+1*1) >= old_cw);
ASSUME(cw(0,0+1*1) >= cr(0,0+1*1));
ASSUME(cw(0,0+1*1) >= cl[0]);
ASSUME(cw(0,0+1*1) >= cisb[0]);
ASSUME(cw(0,0+1*1) >= cdy[0]);
ASSUME(cw(0,0+1*1) >= cdl[0]);
ASSUME(cw(0,0+1*1) >= cds[0]);
ASSUME(cw(0,0+1*1) >= cctrl[0]);
ASSUME(cw(0,0+1*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+1*1) = 0;
mem(0+1*1,cw(0,0+1*1)) = 0;
co(0+1*1,cw(0,0+1*1))+=1;
delta(0+1*1,cw(0,0+1*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !97, metadata !DIExpression()), !dbg !114
// call void @llvm.dbg.value(metadata i64 0, metadata !99, metadata !DIExpression()), !dbg !114
// store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !66
// ST: Guess
iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l40_c3
old_cw = cw(0,0);
cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l40_c3
// Check
ASSUME(active[iw(0,0)] == 0);
ASSUME(active[cw(0,0)] == 0);
ASSUME(sforbid(0,cw(0,0))== 0);
ASSUME(iw(0,0) >= 0);
ASSUME(iw(0,0) >= 0);
ASSUME(cw(0,0) >= iw(0,0));
ASSUME(cw(0,0) >= old_cw);
ASSUME(cw(0,0) >= cr(0,0));
ASSUME(cw(0,0) >= cl[0]);
ASSUME(cw(0,0) >= cisb[0]);
ASSUME(cw(0,0) >= cdy[0]);
ASSUME(cw(0,0) >= cdl[0]);
ASSUME(cw(0,0) >= cds[0]);
ASSUME(cw(0,0) >= cctrl[0]);
ASSUME(cw(0,0) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0) = 0;
mem(0,cw(0,0)) = 0;
co(0,cw(0,0))+=1;
delta(0,cw(0,0)) = -1;
ASSUME(creturn[0] >= cw(0,0));
// store i32 0, i32* @atom_1_X2_0, align 4, !dbg !67, !tbaa !68
// ST: Guess
iw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l41_c15
old_cw = cw(0,2);
cw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l41_c15
// Check
ASSUME(active[iw(0,2)] == 0);
ASSUME(active[cw(0,2)] == 0);
ASSUME(sforbid(2,cw(0,2))== 0);
ASSUME(iw(0,2) >= 0);
ASSUME(iw(0,2) >= 0);
ASSUME(cw(0,2) >= iw(0,2));
ASSUME(cw(0,2) >= old_cw);
ASSUME(cw(0,2) >= cr(0,2));
ASSUME(cw(0,2) >= cl[0]);
ASSUME(cw(0,2) >= cisb[0]);
ASSUME(cw(0,2) >= cdy[0]);
ASSUME(cw(0,2) >= cdl[0]);
ASSUME(cw(0,2) >= cds[0]);
ASSUME(cw(0,2) >= cctrl[0]);
ASSUME(cw(0,2) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,2) = 0;
mem(2,cw(0,2)) = 0;
co(2,cw(0,2))+=1;
delta(2,cw(0,2)) = -1;
ASSUME(creturn[0] >= cw(0,2));
// %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #6, !dbg !72
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[1] >= cdy[0]);
// %call3 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #6, !dbg !73
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[2] >= cdy[0]);
// %2 = load i64, i64* %thr0, align 8, !dbg !74, !tbaa !75
r2 = local_mem[0];
// %call4 = call i32 @pthread_join(i64 noundef %2, i8** noundef null), !dbg !77
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[1]);
// %3 = load i64, i64* %thr1, align 8, !dbg !78, !tbaa !75
r3 = local_mem[1];
// %call5 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !79
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[2]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !101, metadata !DIExpression()), !dbg !125
// %4 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !81
// LD: Guess
old_cr = cr(0,0+1*1);
cr(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l49_c12
// Check
ASSUME(active[cr(0,0+1*1)] == 0);
ASSUME(cr(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cr(0,0+1*1) >= 0);
ASSUME(cr(0,0+1*1) >= cdy[0]);
ASSUME(cr(0,0+1*1) >= cisb[0]);
ASSUME(cr(0,0+1*1) >= cdl[0]);
ASSUME(cr(0,0+1*1) >= cl[0]);
// Update
creg_r4 = cr(0,0+1*1);
crmax(0,0+1*1) = max(crmax(0,0+1*1),cr(0,0+1*1));
caddr[0] = max(caddr[0],0);
if(cr(0,0+1*1) < cw(0,0+1*1)) {
r4 = buff(0,0+1*1);
ASSUME((!(( (cw(0,0+1*1) < 1) && (1 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,1)> 0));
ASSUME((!(( (cw(0,0+1*1) < 2) && (2 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,2)> 0));
ASSUME((!(( (cw(0,0+1*1) < 3) && (3 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,3)> 0));
ASSUME((!(( (cw(0,0+1*1) < 4) && (4 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,4)> 0));
} else {
if(pw(0,0+1*1) != co(0+1*1,cr(0,0+1*1))) {
ASSUME(cr(0,0+1*1) >= old_cr);
}
pw(0,0+1*1) = co(0+1*1,cr(0,0+1*1));
r4 = mem(0+1*1,cr(0,0+1*1));
}
ASSUME(creturn[0] >= cr(0,0+1*1));
// call void @llvm.dbg.value(metadata i64 %4, metadata !103, metadata !DIExpression()), !dbg !125
// %conv = trunc i64 %4 to i32, !dbg !82
// call void @llvm.dbg.value(metadata i32 %conv, metadata !100, metadata !DIExpression()), !dbg !107
// %cmp = icmp eq i32 %conv, 2, !dbg !83
creg__r4__2_ = max(0,creg_r4);
// %conv6 = zext i1 %cmp to i32, !dbg !83
// call void @llvm.dbg.value(metadata i32 %conv6, metadata !104, metadata !DIExpression()), !dbg !107
// %5 = load i32, i32* @atom_1_X2_0, align 4, !dbg !84, !tbaa !68
// LD: Guess
old_cr = cr(0,2);
cr(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l51_c12
// Check
ASSUME(active[cr(0,2)] == 0);
ASSUME(cr(0,2) >= iw(0,2));
ASSUME(cr(0,2) >= 0);
ASSUME(cr(0,2) >= cdy[0]);
ASSUME(cr(0,2) >= cisb[0]);
ASSUME(cr(0,2) >= cdl[0]);
ASSUME(cr(0,2) >= cl[0]);
// Update
creg_r5 = cr(0,2);
crmax(0,2) = max(crmax(0,2),cr(0,2));
caddr[0] = max(caddr[0],0);
if(cr(0,2) < cw(0,2)) {
r5 = buff(0,2);
ASSUME((!(( (cw(0,2) < 1) && (1 < crmax(0,2)) )))||(sforbid(2,1)> 0));
ASSUME((!(( (cw(0,2) < 2) && (2 < crmax(0,2)) )))||(sforbid(2,2)> 0));
ASSUME((!(( (cw(0,2) < 3) && (3 < crmax(0,2)) )))||(sforbid(2,3)> 0));
ASSUME((!(( (cw(0,2) < 4) && (4 < crmax(0,2)) )))||(sforbid(2,4)> 0));
} else {
if(pw(0,2) != co(2,cr(0,2))) {
ASSUME(cr(0,2) >= old_cr);
}
pw(0,2) = co(2,cr(0,2));
r5 = mem(2,cr(0,2));
}
ASSUME(creturn[0] >= cr(0,2));
// call void @llvm.dbg.value(metadata i32 %5, metadata !105, metadata !DIExpression()), !dbg !107
// %and = and i32 %conv6, %5, !dbg !85
creg_r6 = max(creg__r4__2_,creg_r5);
r6 = (r4==2) & r5;
// call void @llvm.dbg.value(metadata i32 %and, metadata !106, metadata !DIExpression()), !dbg !107
// %cmp7 = icmp eq i32 %and, 1, !dbg !86
creg__r6__1_ = max(0,creg_r6);
// br i1 %cmp7, label %if.then, label %if.end, !dbg !88
old_cctrl = cctrl[0];
cctrl[0] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[0] >= old_cctrl);
ASSUME(cctrl[0] >= creg__r6__1_);
if((r6==1)) {
goto T0BLOCK1;
} else {
goto T0BLOCK2;
}
T0BLOCK1:
// call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([102 x i8], [102 x i8]* @.str.1, i64 0, i64 0), i32 noundef 53, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #7, !dbg !89
// unreachable, !dbg !89
r7 = 1;
goto T0BLOCK_END;
T0BLOCK2:
// %6 = bitcast i64* %thr1 to i8*, !dbg !92
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %6) #6, !dbg !92
// %7 = bitcast i64* %thr0 to i8*, !dbg !92
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %7) #6, !dbg !92
// ret i32 0, !dbg !93
ret_thread_0 = 0;
goto T0BLOCK_END;
T0BLOCK_END:
ASSUME(meminit(0,1) == mem(0,0));
ASSUME(coinit(0,1) == co(0,0));
ASSUME(deltainit(0,1) == delta(0,0));
ASSUME(meminit(0,2) == mem(0,1));
ASSUME(coinit(0,2) == co(0,1));
ASSUME(deltainit(0,2) == delta(0,1));
ASSUME(meminit(0,3) == mem(0,2));
ASSUME(coinit(0,3) == co(0,2));
ASSUME(deltainit(0,3) == delta(0,2));
ASSUME(meminit(0,4) == mem(0,3));
ASSUME(coinit(0,4) == co(0,3));
ASSUME(deltainit(0,4) == delta(0,3));
ASSUME(meminit(1,1) == mem(1,0));
ASSUME(coinit(1,1) == co(1,0));
ASSUME(deltainit(1,1) == delta(1,0));
ASSUME(meminit(1,2) == mem(1,1));
ASSUME(coinit(1,2) == co(1,1));
ASSUME(deltainit(1,2) == delta(1,1));
ASSUME(meminit(1,3) == mem(1,2));
ASSUME(coinit(1,3) == co(1,2));
ASSUME(deltainit(1,3) == delta(1,2));
ASSUME(meminit(1,4) == mem(1,3));
ASSUME(coinit(1,4) == co(1,3));
ASSUME(deltainit(1,4) == delta(1,3));
ASSUME(meminit(2,1) == mem(2,0));
ASSUME(coinit(2,1) == co(2,0));
ASSUME(deltainit(2,1) == delta(2,0));
ASSUME(meminit(2,2) == mem(2,1));
ASSUME(coinit(2,2) == co(2,1));
ASSUME(deltainit(2,2) == delta(2,1));
ASSUME(meminit(2,3) == mem(2,2));
ASSUME(coinit(2,3) == co(2,2));
ASSUME(deltainit(2,3) == delta(2,2));
ASSUME(meminit(2,4) == mem(2,3));
ASSUME(coinit(2,4) == co(2,3));
ASSUME(deltainit(2,4) == delta(2,3));
ASSERT(r7== 0);
}
| [
"tuan-phong.ngo@it.uu.se"
] | tuan-phong.ngo@it.uu.se |
2d469140060b39ff672933e35656bf73eb51ff92 | 843910b963dca4555308d2736c26fa0234d631a6 | /WinSystemLib/src/_old_window/control/c_ListView.cpp | 1a78c19bf61a52554e871a9a03d7ffadd4ea5ea3 | [] | no_license | kobake/KppLibs | 1bbb11bbea8765738e975ddde81d8536c6a129f1 | 60d9343a41260f3d90be61b1e6fd4ee31b05d05b | refs/heads/master | 2021-01-17T19:26:04.315121 | 2020-03-28T00:37:43 | 2020-03-28T00:37:43 | 58,841,018 | 1 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 6,176 | cpp | #include <windows.h>
#include <commctrl.h>
#include <string>
using namespace std;
#include "../../_old_app/c_App.h"
#include "c_ListView.h"
#include "../f_window.h"
#include <BaseLib.h>
#include <StringLib.h>
using namespace util;
LRESULT ListView::onSize(UINT msg,WPARAM wParam,LPARAM lParam)
{
Window::onSize(msg,wParam,lParam);
MoveWindow(hwndList,0,0,rcClient.right,rcClient.bottom,TRUE);
return 0L;
}
LRESULT ListView::onFocus(UINT msg,WPARAM wParam,LPARAM lParam)
{
if(msg==WM_SETFOCUS){
SetFocus(hwndList);
return 0L;
}
return Window::onActivate(msg,wParam,lParam);
}
ListView::ListView(int x,int y,int w,int h,Window *_parent,int _option,int _id)
: Window(CID_LIST_VIEW,0,_parent,_option | WINDOWF_TABSTOP,_id)
{
convertXYWH(&x,&y,&w,&h);
hwnd=CreateAWindow(g_app->getInstance(),g_app->getPrevInstance(),L"baseListView",DefWindowProc,(HBRUSH)(COLOR_BTNFACE+1),NULL,NULL,
0,WS_VISIBLE | WS_CHILD,L"",x,y,w,h,getParent()->getHWND(),(HMENU)getID());
_afterCreate();
hwndList=CreateWindowEx(WS_EX_CLIENTEDGE,WC_LISTVIEW,L"",
WS_VISIBLE | WS_CHILD | LVS_REPORT | WS_MAXIMIZE | LVS_SHOWSELALWAYS,0,0,210,210,hwnd,(HMENU)getID(),g_app->getInstance(),NULL);
// hwnd=hwndList=CreateWindowEx(WS_EX_CLIENTEDGE,WC_LISTVIEW,L"",
// WS_VISIBLE | WS_CHILD | LVS_REPORT | WS_MAXIMIZE | LVS_SHOWSELALWAYS,0,0,0,0,parent->getHWND(),(HMENU)id,g_app->getInstance(),NULL);
// _afterCreate();
messageNotify(true);
}
ListView::~ListView()
{
DestroyWindow(hwndList);
}
void ListView::insertColumn(int index,const wchar *caption,int width,int align,bool imagecolumn)
{
LVCOLUMN lvcol;
lvcol.mask=LVCF_FMT | LVCF_TEXT;
if(width!=-1)lvcol.mask|=LVCF_WIDTH;
if(align==-1){
lvcol.fmt=LVCFMT_LEFT;
}else if(align==0){
lvcol.fmt=LVCFMT_CENTER;
}else if(align==1){
lvcol.fmt=LVCFMT_RIGHT;
}
if(imagecolumn)
lvcol.fmt|=LVCFMT_IMAGE;
lvcol.cx=width; //if -1, ignore
lvcol.pszText=(wchar*)caption;
lvcol.cchTextMax=0; //ignore
lvcol.iSubItem=0; //ignore
lvcol.iImage=0; //ignore
lvcol.iOrder=0; //ignore
ListView_InsertColumn(hwndList,index,&lvcol);
}
bool ListView_ColumnHasImage(HWND hwnd,int column)
{
LVCOLUMN col;
col.mask=LVCF_FMT;
ListView_GetColumn(hwnd,column,&col);
return (col.fmt & LVCFMT_IMAGE)!=0;
}
int ListView::insertItem(int index,int subindex,wchar *text,bool setimage,int imageindex,LPARAM lParam)
{
LVITEM item;
item.mask=LVIF_TEXT | LVIF_PARAM;
if(setimage)item.mask|=LVIF_IMAGE;
item.iItem=index;
item.iSubItem=subindex;
item.state=0; //ignore
item.stateMask=0; //ignore
item.pszText=text;
item.cchTextMax=0; //ignore
item.iImage=imageindex; //ignore if ==-1
item.lParam=lParam;
return ListView_InsertItem(hwndList,&item);
}
int ListView::addItem(int subindex,wchar *text,bool setimage,int imageindex,LPARAM lParam)
{
return insertItem(ListView_GetItemCount(hwndList),subindex,text,setimage,imageindex,lParam);
}
void ListView::setItem(int index,int subindex,wchar *text,bool setimage,int imageindex)
{
LVITEM item;
item.mask=LVIF_TEXT;
if(setimage)item.mask|=LVIF_IMAGE;
item.iItem=index;
item.iSubItem=subindex;
item.state=0; //ignore
item.stateMask=0; //ignore
item.pszText=text;
item.cchTextMax=0; //ignore
item.iImage=imageindex; //ignore if ==-1
item.lParam=0; //ignore
ListView_SetItem(hwndList,&item);
}
void ListView::deleteItem(int index)
{
ListView_DeleteItem(hwndList,index);
}
void ListView::clear()
{
ListView_DeleteAllItems(hwndList);
}
void ListView::setImageList(HIMAGELIST hImageList)
{
ListView_SetImageList(hwndList,hImageList,LVSIL_SMALL); //###LVSIL_STATEのほうがいい??
}
struct CompInfo{
HWND hwndList;
int column;
bool az;
};
static int CALLBACK CompProcString(LPARAM lParam1,LPARAM lParam2,LPARAM lParamSort)
{
static wchar buf1[256],buf2[256];
CompInfo *info=(CompInfo*)lParamSort;
//アイテムの検索
LVFINDINFO fi; int n1,n2;
fi.flags=LVFI_PARAM;
fi.lParam=lParam1;
n1=ListView_FindItem(info->hwndList,-1,&fi);
fi.lParam=lParam2;
n2=ListView_FindItem(info->hwndList,-1,&fi);
//テキストの取得
ListView_GetItemText(info->hwndList,n1,info->column,buf1,256);
ListView_GetItemText(info->hwndList,n2,info->column,buf2,256);
//比較
if(info->az){
return wcsicmp(buf1,buf2);
}else{
return wcsicmp(buf2,buf1);
}
}
void ListView::sortItemsByFunc(PFNLVCOMPARE pfnCompare,LPARAM lParamSort)
{
ListView_SortItems(hwndList,pfnCompare,lParamSort);
}
void ListView::sortItemsByString(int column,bool az)
{
static CompInfo info;
info.hwndList=hwndList;
info.column=column;
info.az=az;
ListView_SortItems(hwndList,CompProcString,(LPARAM)&info);
}
static int CALLBACK CompProclParam(LPARAM lParam1,LPARAM lParam2,LPARAM lParamSort)
{
//比較
if(lParamSort){ //AZ
return lParam1-lParam2;
}else{ //ZA
return lParam2-lParam1;
}
}
void ListView::sortItemsBylParam(bool az)
{
ListView_SortItems(hwndList,CompProclParam,(LPARAM)az?1:0);
}
int ListView::getSelectedIndex()
{
return ListView_GetNextItem(hwndList,-1,LVNI_SELECTED);
}
int ListView::getSelectedParam()
{
LVITEM item;
item.iItem=getSelectedIndex();
item.iSubItem=0;
item.mask=LVIF_PARAM;
item.lParam=-1;
ListView_GetItem(hwndList,&item);
return item.lParam;
}
ChainList<int> *ListView::getSelectedParams()
{
static ChainList<int> list;
LVITEM item;
item.iItem=-1; item.iSubItem=0;
item.mask=LVIF_PARAM; item.lParam=-1;
list.clear();
while((item.iItem=ListView_GetNextItem(hwndList,item.iItem,LVNI_SELECTED))!=-1){
ListView_GetItem(hwndList,&item);
list.put(-1,item.lParam);
}
return &list;
}
wchar *ListView::getSelectedText(int iSubItem)
{
static wchar buf[256];
LVITEM item;
item.iItem=getSelectedIndex();
item.iSubItem=iSubItem;
item.mask=LVIF_TEXT;
item.pszText=buf;
item.cchTextMax=sizeof(buf);
ListView_GetItem(hwndList,&item);
return item.pszText;
}
void ListView::removeFoundByText(wchar *text,int iSubItem)
{
int i,n=ListView_GetItemCount(hwndList);
int nbuf=wcslen(text)+1;
wchar *buf=(wchar*)calloc(nbuf,sizeof(wchar)); buf[nbuf-1]=L'\0';
for(i=0;i<n;i++){
ListView_GetItemText(hwndList,i,iSubItem,buf,nbuf);
if(wcscmp(buf,text)==0){
ListView_DeleteItem(hwndList,i);
n--;
i--;
}
}
}
| [
"kobake@users.sourceforge.net"
] | kobake@users.sourceforge.net |
6f0f13342672fb2152b128826a8e47f68e5e4151 | 951b69aae583da24134fac00e8ca39fb684fc577 | /arduino/opencr_develop/opencr_fw_template/opencr_fw_arduino/src/arduino/libraries/turtlebot3_ros_lib/roscpp/Empty.h | fe7cb171660f2d29ba04466dc05ffe0ccca365c2 | [
"Apache-2.0"
] | permissive | ROBOTIS-Will/OpenCR | 6bb9281030c389fc40669ab8d2ea921ac8a4545e | 0787393e189fd790eca6402c9c72574024123450 | refs/heads/master | 2021-06-06T04:33:29.635094 | 2021-05-17T09:32:55 | 2021-05-17T09:32:55 | 138,265,877 | 2 | 0 | Apache-2.0 | 2018-06-22T06:51:25 | 2018-06-22T06:49:31 | C | UTF-8 | C++ | false | false | 1,260 | h | #ifndef _ROS_SERVICE_Empty_h
#define _ROS_SERVICE_Empty_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros/msg.h"
namespace roscpp
{
static const char EMPTY[] = "roscpp/Empty";
class EmptyRequest : public ros::Msg
{
public:
EmptyRequest()
{
}
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
return offset;
}
const char * getType(){ return EMPTY; };
const char * getMD5(){ return "d41d8cd98f00b204e9800998ecf8427e"; };
};
class EmptyResponse : public ros::Msg
{
public:
EmptyResponse()
{
}
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
return offset;
}
const char * getType(){ return EMPTY; };
const char * getMD5(){ return "d41d8cd98f00b204e9800998ecf8427e"; };
};
class Empty {
public:
typedef EmptyRequest Request;
typedef EmptyResponse Response;
};
}
#endif
| [
"willson@robotis.com"
] | willson@robotis.com |
db6e7de86309f57a1ea75e9a2a844aab14cdbe02 | 619941b532c6d2987c0f4e92b73549c6c945c7e5 | /Include/Nuclex/Text/TextServer.h | 3ca5869ac03ed3c533dfef95724dae1af1e4fbff | [] | no_license | dzw/stellarengine | 2b70ddefc2827be4f44ec6082201c955788a8a16 | 2a0a7db2e43c7c3519e79afa56db247f9708bc26 | refs/heads/master | 2016-09-01T21:12:36.888921 | 2008-12-12T12:40:37 | 2008-12-12T12:40:37 | 36,939,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,429 | h | // //
// # # ### # # -= Nuclex Project =- //
// ## # # # ## ## TextServer.h - Font server //
// ### # # ### //
// # ### # ### Font loading and management //
// # ## # # ## ## //
// # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt //
// //
#ifndef NUCLEX_TEXT_TEXTSERVER_H
#define NUCLEX_TEXT_TEXTSERVER_H
#include "Nuclex/Nuclex.h"
#include "Nuclex/Support/String.h"
#include "Nuclex/Support/Exception.h"
#include <map>
// Support::stringFrom<T>(T)
// Support::crcFromString()
// Support::base64FromString()
// Nuclex::Text::TextServer
// Nuclex::Text::FontCodec
// Nuclex::Text::Font
// Nuclex::Text::Translation
// +removeTranslatedText()
// +addTranslatedText()
// +getTranslatedText()
// +clearTranslatedTexts()
namespace Nuclex {
namespace Storage { class Stream; }
}
namespace Nuclex { namespace Text {
class FontCodec;
class Font;
// //
// Nuclex::Text::TextServer //
// //
/// Font server
/** The font server manages a set of font codecs as a chain of
responsibility for loading various font types. Each font codec will
read its supported font file formats and create font objects from
these which can then be used to render text onto surfaces.
A set of these font objects is also managed here to facilitate
font sharing and to provide a set of standard fonts which can be
easily changed depending on screen resolution, theme, etc.
*/
class TextServer {
public:
NUCLEX_DECLAREEXCEPTION(UnsupportedFormatException, UnsupportedFontFormatException);
/// Font codec enumerator
class CodecEnumerator;
/// Font codec enumerator
class FontEnumerator;
/// Constructor
NUCLEX_API TextServer();
/// Destructor
NUCLEX_API virtual ~TextServer();
//
// TextServer implementation
//
public:
/// Retrieve font codec by name
NUCLEX_API const shared_ptr<FontCodec> &getCodec(const string &sName) const;
/// Add font codec
NUCLEX_API void addCodec(const string &sName, const shared_ptr<FontCodec> &spCodec);
/// Remove font codec
NUCLEX_API void removeCodec(const string &sName);
/// Remove all codecs
NUCLEX_API void clearCodecs();
/// Get codec enumerator
NUCLEX_API shared_ptr<CodecEnumerator> enumCodecs() const;
/// Load font from stream
NUCLEX_API shared_ptr<Font> loadFont(
const shared_ptr<Storage::Stream> &spSource,
const string &sExtension = "",
size_t Size = 0
) const;
/// Get font by name
NUCLEX_API const shared_ptr<Font> &getFont(const string &sName) const;
/// Add font to list
NUCLEX_API void addFont(const string &sName, const shared_ptr<Font> &spFont);
/// Remove font from list
NUCLEX_API void removeFont(const string &sName);
/// Add font to list
NUCLEX_API void clearFonts();
/// Remove font from list
NUCLEX_API shared_ptr<FontEnumerator> enumFonts() const;
private:
/// A map of font codecs
typedef std::map<string, shared_ptr<FontCodec> > CodecMap;
/// A map of fonts
typedef std::map<string, shared_ptr<Font> > FontMap;
CodecMap m_Codecs; ///< Registered codecs
FontMap m_Fonts; ///< Fonts
};
// //
// Nuclex::Text::TextServer::CodecEnumerator //
// //
/** Enumerates a list of font codecs
*/
class TextServer::CodecEnumerator {
public:
/// Destructor
/** Destroys an instance of CodecEnumerator
*/
NUCLEX_API virtual ~CodecEnumerator() {}
//
// CodecEnumerator implementation
//
public:
/// Advance to next entry
/** Advances to the next stream. If no more streams are available,
false is returned. Also required to be the first method called,
in order to correctly handle enumerators to empty lists.
@return True if the next stream was reached
*/
NUCLEX_API virtual bool next() = 0;
/// Get current stream information
/** Returns informations about the stream being enumerated.
@return Informations about the current stream
*/
NUCLEX_API virtual const shared_ptr<FontCodec> &get() const = 0;
};
// //
// Nuclex::Text::TextServer::FontEnumerator //
// //
/** Enumerates a list of fonts
*/
class TextServer::FontEnumerator {
public:
/// Destructor
/** Destroys an instance of FontEnumerator
*/
NUCLEX_API virtual ~FontEnumerator() {}
//
// FontEnumerator implementation
//
public:
/// Advance to next entry
/** Advances to the next stream. If no more streams are available,
false is returned. Also required to be the first method called,
in order to correctly handle enumerators to empty lists.
@return True if the next stream was reached
*/
NUCLEX_API virtual bool next() = 0;
/// Get current stream information
/** Returns informations about the stream being enumerated.
@return Informations about the current stream
*/
NUCLEX_API virtual const shared_ptr<Font> &get() const = 0;
};
}} // namespace Nuclex::Text
#endif // NUCLEX_TEXT_TEXTSERVER_H
| [
"ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38"
] | ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38 |
2cf9b5b3258ca64f56e71ce44c5a7c327564f8e1 | 342fdca8d9f10f3ed633f7f4270131bdf7cd6d38 | /src/spacings/hypotest.hpp | ff420c072ef00ff0240e1d5cdcd728b97c8fee65 | [] | no_license | rytis-paskauskas/data_analysis | d46490e8d030922df5d613771705aa19c503ee4b | a3bbdabfe5710393ea2e3d4458527292960ca702 | refs/heads/master | 2021-03-30T21:04:49.677120 | 2018-03-13T07:05:41 | 2018-03-13T07:05:41 | 124,772,093 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,206 | hpp |
// pi^2/6 - 1
#define MSE_SIG2_INF 0.64493406684822643647
// SQRT of the above
#define MSE_ASYMPTOTIC_ROOTVAR 0.80307787097405842818
namespace spacings {
/**
* Large sample central limit.
* The large sample central limit transformation of \f$X_n\f$ is \f$Y_n = \frac{\sqrt{n}X_n}{\sigma}\f$. In theory, \f$\displaystyle\lim_{n\to\infty}Y_n=\mathsf{N}(0,1)\f$.
*
* @param[in] f KL statistic \f$S_n(\theta)\f$
* @param[in] n sample size (number of data; the \f$n\f$ in \f$S_n(\theta)\f$).
*
* @return A transformed input random variable, distributed approximately as \f$\displaystyle\mathrm{N}(0,1)\f$.
*/
double normal_cl_statistic(double f, size_t n) {
double sm = MSE_ASYMPTOTIC_ROOTVAR/sqrt(double(n+1));
// return (f - M_EULER)/sm;
return f/sm;
}
double normal_pvalue(double f, size_t n) {
return gsl_cdf_gaussian_Q(f,1);
}
/**
* Small sample central limit.
*
* The small sample central limit transformation of \f$X_n\f$ is
* \f$\displaystyle Y_n = \frac{\sqrt{n+1}(X_n-\gamma_n)}{\sigma_n}\f$.
* In theory, \f$\displaystyle Y_n\approx\frac{\chi^2_n-n}{\sqrt{2n}}\f$.
*
* @param[in] f KL statistic \f$S_n(\theta)\f$.
* @param[in] n size of the sample (number of data).
* @param[in] k \f$=0\f$ if \f$\theta\f$ is known, otherwise \f$k=\dim{\theta}\f$.
*
* @return A transformed input random variable, distributed approximately as \f$\displaystyle \frac{\chi^2_n-n}{\sqrt{2n}}\f$.
*/
double chisq_cl_statistic(double f, size_t n, int const k=0) {
if(f==+std::numeric_limits<double>::infinity() ||
f==-std::numeric_limits<double>::infinity())
return std::numeric_limits<double>::infinity();
double m = 1.0/double(n+1);
// double gm = M_EULER - m * (0.5 + (0.08333333333333333333 * m)); // asymptotic value + O(m^3) of KL_statistic
double gm = - m * (0.5*double(k) + 0.5 + (0.08333333333333333333 * m)); // asymptotic value + O(m^3) of KL_statistic
double sm = sqrt( m *( MSE_SIG2_INF - m * ( 0.5 + 0.16666666666666666667 * m )) ); // asymptotic variance
// double c1 = gm - sqrt(0.5*double(n)) * sm;
// double c2 = sqrt (0.5/double(n)) * sm;
// recycle m;
// m = (f - c1 + 0.5*double(k) * m)/c2;
// return (f - gm + (m * 0.5*double(k)))/sm; // should yield (chi^2(n) - n)/sqrt(2n)
return (f - gm)/sm; // should yield (chi^2(n) - n)/sqrt(2n)
}
/**
* Returns the p-value assuming that input is a statistic given by chisq_cl
*
* @param f
* @param n
* @param g
*
* @return
*/
double chisq_pvalue(double f, size_t n) {
if(f==+std::numeric_limits<double>::infinity() ||
f==-std::numeric_limits<double>::infinity()) return 0;
// double m = 1.0/double(n+1);
// double gm = M_EULER - m * (0.5 + (0.08333333333333333333 * m));
// double sm = sqrt( m *( MSE_SIG2_INF - m * ( 0.5 + 0.16666666666666666667 * m )) );
// double c1 = gm - sqrt(0.5*double(n)) * sm;
// double c2 = sqrt (0.5/double(n)) * sm;
// // recycle m;
// m = (f - c1 + 0.5*double(k) * m)/c2;
// return gsl_cdf_chisq_Q(m,n);
return gsl_cdf_chisq_Q(sqrt(2*n)*f + n, n);
}
}
| [
"rytis.paskauskas@gmail.com"
] | rytis.paskauskas@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.