blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
652ebcf39fdc35f559b5462c6c7d54acff365a80 | 2617eccbf0959ae7dd7c5abca1d33defc2ccdd60 | /src/HttpData.cpp | aebbfc73ffe3e2c0d165ff30cd7c32bce3f859f7 | [] | no_license | JackRJ/epollServer | 1b3d8df357e2e9b6d2a346525e7e250efa2dc683 | 1de0bae9a1f9fb93eaecf7602a292f9186e4db4d | refs/heads/master | 2021-03-26T12:44:22.507694 | 2020-09-25T12:26:14 | 2020-09-25T12:26:14 | 247,705,279 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,010 | cpp | /*
* @Author: your name
* @Date: 2020-03-17 21:44:09
* @LastEditTime: 2020-07-24 16:05:10
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: /try/src/HttpData.cpp
*/
#include "HttpData.h"
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <string>
#include <algorithm>
#include <sys/socket.h>
#include <netinet/in.h>
std::map<std::string, APIpath> HttpData::hash_ =
{
std::make_pair("daylist/login", daylist_login),
std::make_pair("daylist/register", daylist_register),
std::make_pair("daylist/uploadScheduleItem", daylist_uploadScheduleItem),
std::make_pair("daylist/getUserItems", daylist_getUserItems),
std::make_pair("daylist/getUserInformation", daylist_getUserInformation),
std::make_pair("daylist/modifyUserInformation", daylist_modifyUserInformation),
std::make_pair("daylist/deleteScheduleItem", daylist_deleteScheduleItem)
};
HttpData::HttpData(int fd):
fd_(fd),
error_(false),
HTTPVersion_(HTTP_11),
method_(METHOD_GET),
state_(STATE_PARSE_URI),
hState_(H_START),
nowReadPos_(0)
{}
HttpData::~HttpData()
{
// test http 1.0
// if (HTTPVersion_ == 1 || error_)
close(fd_);
}
void HttpData::startup()
{
// start reading http data
handleRead();
}
void HttpData::handleRead()
{
bool zero = false;
int readNum = readn(fd_, inBuffer_, zero);
// LOG << "Request: " << inBuffer_;
do
{
if (readNum < 0)
{
error_ = true;
perror("read error");
handleError(400, "BAD REQUEST");
break;
} else if (zero)
{
// 有请求出现但是读不到数据,可能是Request Aborted,或者来自网络的数据没有达到等原因
// 最可能是对端已经关闭了,统一按照对端已经关闭处理
if (readNum == 0)
break;
}
if (state_ == STATE_PARSE_URI)
{
if (!error_)
{
URIState flag = parseLine();
if (flag == PARSE_URI_AGAIN)
break;
else if (flag == PARSE_URI_ERROR)
{
perror("parse url error");
// LOG << "FD = " << fd_ << "," << inBuffer_ << "******";
inBuffer_.clear();
error_ = true;
handleError(400, "BAD REQUEST");
break;
} else
state_ = STATE_PARSE_HEADERS;
}
}
if (state_ == STATE_PARSE_HEADERS)
{
HeaderState flag = parseHeader();
if (flag == PARSE_HEADER_AGAIN)
break;
else if (flag == PARSE_HEADER_ERROR)
{
perror("parse header error");
error_ = true;
handleError(400, "BAD REQUEST");
break;
}
if(method_ == METHOD_POST)
{
// POST方法准备
state_ = STATE_RECV_BODY;
}
else
{
state_ = STATE_ANALYSIS;
}
}
if (state_ == STATE_RECV_BODY)
{
state_ = STATE_ANALYSIS;
}
if (state_ == STATE_ANALYSIS)
{
AnalysisState flag = this -> analysisRequest();
if (flag == ANALYSIS_SUCCESS)
{
state_ = STATE_FINISH;
break;
} else
{
error_ = true;
break;
}
}
} while (false);
if (!error_)
{
if (outBuffer_.size() > 0)
{
handleWrite();
}
} else
{
handleError(400, "BAD REQUEST");
}
}
void HttpData::handleWrite()
{
if (!error_)
{
if (writen(fd_, outBuffer_) < 0)
{
perror("writen");
error_ = 1;
}
}
}
int HttpData::parseUrlData(int pos)
{
std::string data = url_.substr(pos);
int start = 0;
int end = data.size();
while (start < end)
{
std::string key;
std::string val;
int index = start;
while (index < end && data[index] != '=')
++index;
key = std::string(data.begin() + start, data.begin() + index);
++index;
start = index;
while (index < end && data[index] != '&')
++index;
val = std::string(data.begin() + start, data.begin() + index);
start = ++index;
urlData[key] = val;
// printf("%s, %s\n", key.c_str(), val.c_str());
}
}
URIState HttpData::parseLine()
{
// solve method url and httpversion
std::string &str = inBuffer_;
std::string cop = str;
// 读到完整的请求行再开始解析请求
size_t pos = str.find('\r', nowReadPos_);
if (pos < 0)
return PARSE_URI_AGAIN;
// 去掉请求行所占的空间,节省空间
std::string request_line = str.substr(0, pos);
if (str.size() > pos + 1)
str = str.substr(pos + 1);
else
str.clear();
// Method
int posGet = request_line.find("GET");
int posPost = request_line.find("POST");
int posHead = request_line.find("HEAD");
if (posGet >= 0)
{
pos = posGet;
method_ = METHOD_GET;
}
else if (posPost >= 0)
{
pos = posPost;
method_ = METHOD_POST;
}
else if (posHead >= 0)
{
pos = posHead;
method_ = METHOD_HEAD;
}
else
{
// method not found
return PARSE_URI_ERROR;
}
// filename
pos = request_line.find("/", pos);
if (pos < 0)
{
url_ = "index.html";
HTTPVersion_ = HTTP_11;
return PARSE_URI_SUCCESS;
} else
{
size_t _pos = request_line.find(' ', pos);
if (_pos < 0)
return PARSE_URI_ERROR;
else
{
if (_pos - pos > 1)
{
url_ = request_line.substr(pos + 1, _pos - pos - 1);
size_t __pos = url_.find('?');
// 有参数需要处理
if (__pos != url_.npos)
{
printf("%s\n", url_.substr(__pos + 1).c_str());
this -> parseUrlData(__pos + 1);
}
// params to do
if (__pos >= 0)
url_ = url_.substr(0, __pos);
} else
url_ = "index.html";
}
pos = _pos;
}
// HTTP 版本号
pos = request_line.find("/", pos);
if (pos < 0)
return PARSE_URI_ERROR;
else
{
if (request_line.size() - pos <= 3)
return PARSE_URI_ERROR;
else
{
std::string ver = request_line.substr(pos + 1, 3);
if (ver == "1.0")
HTTPVersion_ = HTTP_10;
else if (ver == "1.1")
HTTPVersion_ = HTTP_11;
else
return PARSE_URI_ERROR;
}
}
return PARSE_URI_SUCCESS;
}
HeaderState HttpData::parseHeader()
{
std::string &str = inBuffer_;
int key_start = -1, key_end = -1, value_start = -1, value_end = -1;
int now_read_line_begin = 0;
bool notFinish = true;
size_t i = 0;
for (; i < str.size() && notFinish; ++i)
{
switch(hState_)
{
case H_START:
{
if (str[i] == '\n' || str[i] == '\r')
break;
hState_ = H_KEY;
key_start = i;
now_read_line_begin = i;
break;
}
case H_KEY:
{
if (str[i] == ':')
{
key_end = i;
if (key_end - key_start <= 0)
return PARSE_HEADER_ERROR;
hState_ = H_COLON;
} else if (str[i] == '\n' || str[i] == '\r')
return PARSE_HEADER_ERROR;
break;
}
case H_COLON:
{
if (str[i] == ' ')
hState_ = H_SPACES_AFTER_COLON;
else
return PARSE_HEADER_ERROR;
break;
}
case H_SPACES_AFTER_COLON:
{
hState_ = H_VALUE;
value_start = i;
break;
}
case H_VALUE:
{
if (str[i] == '\r')
{
hState_ = H_CR;
value_end = i;
if (value_end - value_start <= 0)
return PARSE_HEADER_ERROR;
} else if (i - value_start > 255)
return PARSE_HEADER_ERROR;
break;
}
case H_CR:
{
if (str[i] == '\n')
{
hState_ = H_LF;
std::string key(str.begin() + key_start, str.begin() + key_end);
std::string value(str.begin() + value_start, str.begin() + value_end);
headers_[key] = value;
now_read_line_begin = i;
} else
return PARSE_HEADER_ERROR;
break;
}
case H_LF:
{
if (str[i] == '\r')
hState_ = H_END_CR;
else
{
key_start = i;
hState_ = H_KEY;
}
break;
}
case H_END_CR:
{
if (str[i] == '\n')
hState_ = H_END_LF;
else
return PARSE_HEADER_ERROR;
break;
}
case H_END_LF:
{
notFinish = false;
key_start = i;
now_read_line_begin = i;
break;
}
}
}
if (hState_ == H_END_LF)
{
str = str.substr(i - 1);
return PARSE_HEADER_SUCCESS;
}
str = str.substr(now_read_line_begin);
return PARSE_HEADER_AGAIN;
}
int HttpData::parseBody(bool isDecode)
{
if (isDecode)
{
// 对中文的url解码
std::shared_ptr<UrlTranslation> translation(new UrlTranslation());
std::shared_ptr<char> tmp(new char[inBuffer_.size() + 1]);
translation -> urlDecode(inBuffer_.data(), tmp.get());
inBuffer_ = std::string(tmp.get());
}
bool error = 0;
std::string& str = inBuffer_;
int key_start = 0, key_end = 0;
int val_start = 0;
int i = 0;
for (; i < str.size(); ++i)
{
if (str[i] == '=')
{
key_end = i;
val_start = i + 1;
} else if (str[i] == '&')
{
std::string key = std::string(str.begin() + key_start, str.begin() + key_end);
std::string val = std::string(str.begin() + val_start, str.begin() + i);
bodies[key] = val;
key_start = i + 1;
}
}
std::string key = std::string(str.begin() + key_start, str.begin() + key_end);
std::string val = std::string(str.begin() + val_start, str.begin() + i);
bodies[key] = val;
if (error)
return -1;
}
AnalysisState HttpData::analysisRequest()
{
if (method_ == METHOD_POST)
{
switch (hash_[url_])
{
/**
* 登陆
*/
case daylist_login :
{
this -> parseBody(0);
shared_ptr<DayListAPI> daylistApi(new DayListAPI(headers_, outBuffer_));
int res = daylistApi -> loginAPI(bodies);
return ANALYSIS_SUCCESS;
break;
}
/**
* 注册
*/
case daylist_register :
{
this -> parseBody(0);
int userId = 0;
shared_ptr<DayListAPI> daylistApi(new DayListAPI(headers_, outBuffer_));
int rst = daylistApi -> registeAPI(bodies, userId);
return ANALYSIS_SUCCESS;
break;
}
/**
* 上传日程item
*/
case daylist_uploadScheduleItem:
{
// 对中文的url解码
// 之后再进行解析请求体
this -> parseBody(true);
shared_ptr<DayListAPI> daylistApi(new DayListAPI(headers_, outBuffer_));
int rst = daylistApi -> uploadScheduleItemAPI(bodies);
return ANALYSIS_SUCCESS;
break;
}
/**
* 修改用户信息
*/
case daylist_modifyUserInformation:
{
// 对中文的url解码
// 之后再进行解析请求体
this -> parseBody(true);
shared_ptr<DayListAPI> daylistApi(new DayListAPI(headers_, outBuffer_));
int res = daylistApi -> modifyUserInformation(bodies);
return ANALYSIS_SUCCESS;
}
/**
* 删除日程
*/
case daylist_deleteScheduleItem:
{
// 之后再进行解析请求体
this -> parseBody(0);
shared_ptr<DayListAPI> daylistApi(new DayListAPI(headers_, outBuffer_));
int res = daylistApi -> deleteScheduleItem(bodies);
return ANALYSIS_SUCCESS;
}
default: return ANALYSIS_ERROR;
}
} else if (method_ == METHOD_GET || method_ == METHOD_HEAD)
{
switch(hash_[url_])
{
/**
* 获取某个用户的所有日程,每次获取10条
*/
case daylist_getUserItems:
{
shared_ptr<DayListAPI> daylistApi(new DayListAPI(headers_, outBuffer_));
int res = daylistApi -> getUserItem(urlData);
return ANALYSIS_SUCCESS;
}
/**
* 获取用户信息
*/
case daylist_getUserInformation:
{
std::string userInformation;
shared_ptr<DayListAPI> daylistApi(new DayListAPI(headers_, outBuffer_));
int res = daylistApi -> getUserInformation(urlData);
return ANALYSIS_SUCCESS;
}
default: break;
}
// test
if (url_ == "hello")
{
// printf("fileName: %s\n", url_.c_str());
std::string str = "{\"r\" : 1, \"msg\" : s}\r\n\r\n";
outBuffer_ = "HTTP/1.1 200 OK\r\nContent-type: application/json\r\n\r\n" + str;
return ANALYSIS_SUCCESS;
}
}
return ANALYSIS_ERROR;
}
void HttpData::handleError(int err_num, std::string short_msg)
{
std::string body_buff, header_buff;
char send_buff[4096];
body_buff += "<html><title>哎~出错了</title>";
body_buff += "<body bgcolor=\"ffffff\">";
body_buff += std::to_string(err_num) + short_msg;
body_buff += "<hr><em> RJ's Web Server</em>\n</body></html>";
header_buff += "HTTP/1.1 " + std::to_string(err_num) + short_msg + "\r\n";
header_buff += "Content-Type: text/html\r\n";
header_buff += "Connection: Close\r\n";
header_buff += "Content-Length: " + std::to_string(body_buff.size()) + "\r\n";
header_buff += "Server: RJ's Web Server\r\n";
header_buff += "\r\n";
// 错误处理不考虑writen不完的情况
sprintf(send_buff, "%s", header_buff.c_str());
writen(this -> fd_, send_buff, strlen(send_buff));
sprintf(send_buff, "%s", body_buff.c_str());
writen(this -> fd_, send_buff, strlen(send_buff));
}
| [
"1129075520@qq.com"
] | 1129075520@qq.com |
802cc22c0dd07b699d3543aa04523e130b1a778a | c92c71071d3d6615765786ecf08386918c6a2349 | /CodeForces/CF16-D2-E.cpp | 5af64835bcc9187b2a570f86f104d3e0a3365f4a | [] | no_license | 3agwa/CompetitiveProgramming | ef757ede03c00e4a47a1629cec2fe862cc7b871d | 532eb309ffeb2901d1af90fc46ce7ad904f0cbc6 | refs/heads/master | 2021-01-19T22:16:49.231249 | 2019-03-12T17:13:50 | 2019-03-12T17:13:50 | 88,785,488 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,053 | cpp | /*
consider all the possibilities, a mask of (1<<n) size
now for each 2 pair of bits in the mask, they will try to eat each other with the same probability
increment all probabilities accordingly
*/
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define vll vector<ll>
#define pii pair<int, int>
#define vii vector<pii>
#define vs vector<string>
#define vb vector<bool>
#define vi vector<int>
#define vd vector<double>
#define vvi vector< vector<int> >
#define vvii vector< vector< pii > >
#define ld long double
#define mapii map<int, int>
#define mapsi map<string, int>
#define erep(i, x, n) for (auto i = x; i<=(ll)(n); i++)
#define rep(i, x, n) for(auto i = x; i<(ll)(n); i++)
//#define INF LLONG_MAX
#define all(v) ((v).begin()), ((v).end())
#define sz(v) ((int)((v).size()))
#define pie acos(-1)
#define mod(n,m) ((n % m + m) % m)
#define eps (1e-8)
#define reset(n, m) memset(n, m, sizeof n)
#define endl '\n'
#define output freopen("output.txt", "w", stdout)
#define mp(x, y, z) {x, {y, z}}
double memo[(1<<18) + 1];
double arr[18][18];
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
rep(i, 0, n) rep(j, 0, n) cin >> arr[i][j];
memo[(1<<n)-1] = 1.;
for(int mask = (1<<n)-1; mask>=0; mask--)
{
rep(i, 0, n)
{
if (mask & (1<<i))
{
rep(j, i+1, n)
{
if (mask & (1<<j))
{
double x = __builtin_popcount(mask);
double hoba = (x*(x-1)) / 2.0;
memo[mask - (1<<i)] += memo[mask] * arr[j][i] / hoba; // ith eaten
memo[mask - (1<<j)] += memo[mask] * arr[i][j] / hoba; // jth eaten
}
}
}
}
}
cout << fixed << setprecision(9);
rep(i, 0, n) cout << memo[(1<<i)] << " ";
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
defe8180505285ca0d8d0f2ec1c316aca5313528 | 6290caf661a9c7fa5efe736b095a48a95f39a21c | /GPRS_SIM800C_F1/libraries/SIM800C_FONA/SIM800C_FONA.h | e73b4603d01594aa3b00122e498905412efa891d | [] | no_license | GPRSArduino/GPRS_Kat | 70a337e7870ee279019993fa6a6824ba283ae56f | 6d9ab1fbcaadde2127b2de4c9243db0659ba7aeb | refs/heads/master | 2021-09-08T10:00:13.724815 | 2021-09-07T13:32:09 | 2021-09-07T13:32:14 | 78,192,740 | 0 | 1 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 9,494 | h | /***************************************************
This is a library for our SIM800C Module
BSD license, all text above must be included in any redistribution
****************************************************/
#ifndef SIM800C_FONA_H
#define SIM800C_FONA_H
#include "includes/FONAConfig.h"
#include "includes/FONAExtIncludes.h"
#include "includes/platform/FONAPlatform.h"
//#define FONA800L 1
//#define FONA800H 6
//#define FONA800C 7
//
//#define FONA808_V1 2
//#define FONA808_V2 3
//
//#define FONA3G_A 4
//#define FONA3G_E 5
// Uncomment to changed the preferred SMS storage
//#define FONA_PREF_SMS_STORAGE "SM"
#define FONA_HEADSETAUDIO 0
#define FONA_EXTAUDIO 1
#define FONA_STTONE_DIALTONE 1
#define FONA_STTONE_BUSY 2
#define FONA_STTONE_CONGESTION 3
#define FONA_STTONE_PATHACK 4
#define FONA_STTONE_DROPPED 5
#define FONA_STTONE_ERROR 6
#define FONA_STTONE_CALLWAIT 7
#define FONA_STTONE_RINGING 8
#define FONA_STTONE_BEEP 16
#define FONA_STTONE_POSTONE 17
#define FONA_STTONE_ERRTONE 18
#define FONA_STTONE_INDIANDIALTONE 19
#define FONA_STTONE_USADIALTONE 20
#define FONA_DEFAULT_TIMEOUT_MS 500
#define FONA_HTTP_GET 0
#define FONA_HTTP_POST 1
#define FONA_HTTP_HEAD 2
#define FONA_CALL_READY 0
#define FONA_CALL_FAILED 1
#define FONA_CALL_UNKNOWN 2
#define FONA_CALL_RINGING 3
#define FONA_CALL_INPROGRESS 4
typedef enum {
HTTP_DISABLED = 0,
HTTP_READY,
HTTP_CONNECTING,
HTTP_READING,
HTTP_ERROR,
} HTTP_STATES;
class SIM800C_FONA : public FONAStreamType {
public:
SIM800C_FONA(int8_t rst);
void put_operator(int8_t home_operator);
bool getOperatorName(char *OperatorName);
boolean begin(FONAStreamType &port);
uint8_t type();
boolean ping(FONAFlashStringPtr tspserver);
// Stream
int available(void);
size_t write(uint8_t x);
int read(void);
int peek(void);
void flush();
// Добавил код
char buffer[128];
byte httpState;
String val = "";
// send AT command and check for expected response
byte sendCommand(const char* cmd, unsigned int timeout = 2000, const char* expected = 0);
// send AT command and check for two possible responses
byte sendCommand(const char* cmd, const char* expected1, const char* expected2, unsigned int timeout = 2000);
// FONA 3G requirements
boolean setBaudrate(uint16_t baud);
// RTC
boolean enableRTC(uint8_t i);
boolean readRTC(uint8_t *year, uint8_t *month, uint8_t *date, uint8_t *hr, uint8_t *min, uint8_t *sec);
//// Battery and ADC
//boolean getADCVoltage(uint16_t *v);
//boolean getBattPercent(uint16_t *p);
//boolean getBattVoltage(uint16_t *v);
// SIM query
uint8_t unlockSIM(char *pin);
uint8_t getSIMCCID(char *ccid);
uint8_t getNetworkStatus(void);
uint8_t getRSSI(void);
// IMEI
uint8_t getIMEI(char *imei);
//// set Audio output
//boolean setAudio(uint8_t a);
//boolean setVolume(uint8_t i);
//uint8_t getVolume(void);
//boolean playToolkitTone(uint8_t t, uint16_t len);
//boolean setMicVolume(uint8_t a, uint8_t level);
//boolean playDTMF(char tone);
// SMS handling
boolean setSMSInterrupt(uint8_t i);
uint8_t getSMSInterrupt(void);
int8_t getNumSMS(void);
boolean readSMS(uint8_t i, char *smsbuff, uint16_t max, uint16_t *readsize);
boolean sendSMS(char *smsaddr, char *smsmsg);
boolean deleteSMS(uint8_t i);
boolean getSMSSender(uint8_t i, char *sender, int senderlen);
boolean sendUSSD(char *ussdmsg, char *ussdbuff, uint16_t maxlen, uint16_t *readlen);
// Time
boolean enableNetworkTimeSync(boolean onoff);
boolean enableNTPTimeSync(boolean onoff, FONAFlashStringPtr ntpserver=0);
boolean getTime(char *buff, uint16_t maxlen);
// GPRS handling
boolean checkGPRS();
boolean enableGPRS(boolean onoff);
uint8_t GPRSstate(void);
boolean getGSMLoc(uint16_t *replycode, char *buff, uint16_t maxlen);
boolean getGSMLoc(float *lat, float *lon);
void setGPRSNetworkSettings(FONAFlashStringPtr apn, FONAFlashStringPtr username=0, FONAFlashStringPtr password=0);
// GPS handling
/* boolean enableGPS(boolean onoff);
int8_t GPSstatus(void);
uint8_t getGPS(uint8_t arg, char *buffer, uint8_t maxbuff);
boolean getGPS(float *lat, float *lon, float *speed_kph=0, float *heading=0, float *altitude=0);
boolean enableGPSNMEA(uint8_t nmea);
*/
// TCP raw connections
boolean TCPconnect(char *server, uint16_t port);
boolean TCPclose(void);
boolean TCPconnected(void);
boolean TCPsend(char *packet, uint8_t len);
uint16_t TCPavailable(void);
uint16_t TCPread(uint8_t *buff, uint8_t len);
// HTTP low level interface (maps directly to SIM800 commands).
bool httpConnectStr(const char* url, String args);
byte httpIsConnected();
// read data from HTTP connection
void httpRead();
// return 0 for in progress, -1 for error, bytes of http payload on success
int httpIsRead();
boolean HTTP_init();
boolean HTTP_term();
bool httpInit1();
// terminate HTTP connection
void httpUninit1();
void HTTP_para_start(FONAFlashStringPtr parameter, boolean quoted = true);
boolean HTTP_para_end(boolean quoted = true);
boolean HTTP_para(FONAFlashStringPtr parameter, const char *value);
boolean HTTP_para(FONAFlashStringPtr parameter, FONAFlashStringPtr value);
boolean HTTP_para(FONAFlashStringPtr parameter, int32_t value);
boolean HTTP_data(uint32_t size, uint32_t maxTime=10000);
boolean HTTP_action(uint8_t method, uint16_t *status, uint16_t *datalen, int32_t timeout = 10000);
boolean HTTP_readall(uint16_t *datalen);
boolean HTTP_ssl(boolean onoff);
// HTTP high level interface (easier to use, less flexible).
boolean HTTP_GET_start(char *url, uint16_t *status, uint16_t *datalen);
void HTTP_GET_end(void);
boolean HTTP_POST_start(char *url, FONAFlashStringPtr contenttype, const uint8_t *postdata, uint16_t postdatalen, uint16_t *status, uint16_t *datalen);
void HTTP_POST_end(void);
void setUserAgent(FONAFlashStringPtr useragent);
// HTTPS
void setHTTPSRedirect(boolean onoff);
// PWM (buzzer)
// boolean setPWM(uint16_t period, uint8_t duty = 50);
// Phone calls
/* boolean callPhone(char *phonenum);
uint8_t getCallStatus(void);
boolean hangUp(void);
boolean pickUp(void);
boolean callerIdNotification(boolean enable, uint8_t interrupt = 0);
boolean incomingCallNumber(char* phonenum);
*/
// Helper functions to verify responses.
boolean expectReply(FONAFlashStringPtr reply, uint16_t timeout = 10000);
boolean sendCheckReply(char *send, char *reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS);
boolean sendCheckReply(FONAFlashStringPtr send, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS);
boolean sendCheckReply(char* send, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS);
protected:
int8_t _rstpin;
uint8_t _type;
char replybuffer[140];
FONAFlashStringPtr apn;
FONAFlashStringPtr apnusername;
FONAFlashStringPtr apnpassword;
boolean httpsredirect;
FONAFlashStringPtr useragent;
FONAFlashStringPtr ok_reply;
// HTTP helpers
boolean HTTP_setup(char *url);
void flushInput();
uint16_t readRaw(uint16_t b);
uint8_t readline(uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS, boolean multiline = false);
uint8_t getReply(char *send, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS);
uint8_t getReply(FONAFlashStringPtr send, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS);
uint8_t getReply(FONAFlashStringPtr prefix, char *suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS);
uint8_t getReply(FONAFlashStringPtr prefix, int32_t suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS);
uint8_t getReply(FONAFlashStringPtr prefix, int32_t suffix1, int32_t suffix2, uint16_t timeout); // Don't set default value or else function call is ambiguous.
uint8_t getReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS);
boolean sendCheckReply(FONAFlashStringPtr prefix, char *suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS);
boolean sendCheckReply(FONAFlashStringPtr prefix, int32_t suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS);
boolean sendCheckReply(FONAFlashStringPtr prefix, int32_t suffix, int32_t suffix2, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS);
boolean sendCheckReplyQuoted(FONAFlashStringPtr prefix, FONAFlashStringPtr suffix, FONAFlashStringPtr reply, uint16_t timeout = FONA_DEFAULT_TIMEOUT_MS);
boolean parseReply(FONAFlashStringPtr toreply,
uint16_t *v, char divider = ',', uint8_t index=0);
boolean parseReply(FONAFlashStringPtr toreply,
char *v, char divider = ',', uint8_t index=0);
boolean parseReplyQuoted(FONAFlashStringPtr toreply,
char *v, int maxlen, char divider, uint8_t index);
boolean sendParseReply(FONAFlashStringPtr tosend,
FONAFlashStringPtr toreply,
uint16_t *v, char divider = ',', uint8_t index=0);
static boolean _incomingCall;
static void onIncomingCall();
FONAStreamType *mySerial;
private:
byte checkbuffer(const char* expected1, const char* expected2 = 0, unsigned int timeout = 2000);
void purgeSerial();
byte m_bytesRecv;
uint32_t m_checkTimer;
};
#endif
| [
"promavto@ntmp.ru"
] | promavto@ntmp.ru |
7d5a930e455cb0be5f4e1bc4393cab7aad5e24aa | cbb3ef472b4f4bbf1480552160aedbd88f230ee3 | /Carpeta_de_proyectos_Arduino_copia_de_seguridad/NODEMCU_ESPNOW_previo/NODEMCU_ESPNOW_previo.ino | aedb77382a4f39eeebb624c0655eff24594b1edb | [] | no_license | agrgal/ARDUINO_CS | 5a68e236ec660b7ce4e34ee1253b1c0ed27033f0 | f94200dceb4a8d7d27332a3045301daecbb6c979 | refs/heads/master | 2022-09-13T08:06:10.458851 | 2022-08-29T14:30:27 | 2022-08-29T14:30:27 | 242,396,006 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 169 | ino |
int entrada = D0;
int salida = D1;
void setup() {
pinMode(entrada,INPUT);
pinMode(salida,OUTPUT);
}
void loop() {
digitalWrite(salida,digitalRead(entrada));
}
| [
"aurelio@seritium.es"
] | aurelio@seritium.es |
1d517c0660e32f4a5ae6d630835436e3c90ff870 | c2ff831ab22bd144c0da32bde98dcebdc319e6a0 | /leetcode/C&C++/easy/SymmetricTree.cpp | 066dd416177ede713e12fa25ddf3e4727f1ed024 | [] | no_license | elvisflash/elvisflash.github.io | 96d3367500d0df498c18d22584a259558fec25c5 | 3ee8143bded98b9782e7162da0d006780693d3b3 | refs/heads/master | 2021-09-07T06:59:09.546812 | 2018-02-19T07:31:48 | 2018-02-19T07:31:48 | 119,966,783 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 751 | cpp | /*
* Symmetric Tree
* Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isMirror(TreeNode *l, TreeNode *r)
{
if (l == NULL && r == NULL) return true;
else if (l == NULL || r == NULL) return false;
else return (l->val == r->val)&&isMirror(l->left, r->right)&&isMirror(l->right, r->left);
}
bool isSymmetric(TreeNode *root) {
if (root == NULL) return true;
return isMirror(root->left, root->right);
}
}; | [
"zhongbincharles@gmail.com"
] | zhongbincharles@gmail.com |
42abce9a6804ea1468ac92a49b8cf7baf8f2c717 | 04721d03a4bf0bdefcdd527d2d1c845af7850a14 | /Misc/colombia2018/K.cpp | 54a674c71f8fa9e1707f645418e487ac64cbdef9 | [] | no_license | ArielGarciaM/CompetitiveProgramming | 81e3808fdb14372f14e54d1e69c582be9ba44893 | c7115c38b988b6bc053850f1024a8005eb24fcee | refs/heads/master | 2020-03-28T15:19:55.788844 | 2019-08-09T20:54:25 | 2019-08-09T20:54:25 | 148,581,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 489 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef double ld;
vector<ld> expe;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
for(int i = 0; i < n; i++) {
int x;
ld y;
cin >> x >> y;
expe.push_back(((ld)x)*y);
}
ld ans = 0.0;
sort(expe.rbegin(), expe.rend());
for(int i = 1; i <= n; i++)
ans += ((ld)i)*expe[i - 1];
cout << fixed << setprecision(20) << ans/((ld)n) << endl;
} | [
"largam@ciencias.unam.mx"
] | largam@ciencias.unam.mx |
8c64c24aae59791295d667009b4fbc58710f8253 | e35f5e2ad302507da001a9eea94a123de5a95e5a | /Catalog/DdlCommandExecutor.cpp | 5b13a578972338acc0704dc02037e9089bcaaedc | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | geogubd/omniscidb | 100266d36585f6e640adbba0166c32ce77e796f5 | 8a228a10764ae4a34359516867d2ad0a5baf2b08 | refs/heads/master | 2022-12-09T19:31:37.477999 | 2020-09-15T17:08:21 | 2020-09-15T18:47:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,433 | cpp | /*
* Copyright 2020 OmniSci, Inc.
*
* 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 "DdlCommandExecutor.h"
#include <boost/algorithm/string/predicate.hpp>
#include "Catalog/Catalog.h"
#include "Catalog/SysCatalog.h"
#include "DataMgr/ForeignStorage/CsvDataWrapper.h"
#include "DataMgr/ForeignStorage/ParquetDataWrapper.h"
#include "LockMgr/LockMgr.h"
#include "Parser/ParserNode.h"
#include "Shared/StringTransform.h"
extern bool g_enable_fsi;
bool DdlCommand::isDefaultServer(const std::string& server_name) {
return boost::iequals(server_name.substr(0, 7), "omnisci");
}
namespace {
void set_headers(TQueryResult& _return, const std::vector<std::string>& headers) {
TRowDescriptor row_descriptor;
for (const auto& header : headers) {
TColumnType column_type{};
column_type.col_name = header;
column_type.col_type.type = TDatumType::type::STR;
row_descriptor.push_back(column_type);
_return.row_set.columns.emplace_back();
}
_return.row_set.row_desc = row_descriptor;
_return.row_set.is_columnar = true;
}
void add_row(TQueryResult& _return, const std::vector<std::string>& row) {
for (size_t i = 0; i < row.size(); i++) {
_return.row_set.columns[i].data.str_col.emplace_back(row[i]);
_return.row_set.columns[i].nulls.emplace_back(false);
}
}
} // namespace
DdlCommandExecutor::DdlCommandExecutor(
const std::string& ddl_statement,
std::shared_ptr<Catalog_Namespace::SessionInfo const> session_ptr)
: session_ptr_(session_ptr) {
CHECK(!ddl_statement.empty());
ddl_query_.Parse(ddl_statement);
CHECK(ddl_query_.IsObject());
CHECK(ddl_query_.HasMember("payload"));
CHECK(ddl_query_["payload"].IsObject());
const auto& payload = ddl_query_["payload"].GetObject();
CHECK(payload.HasMember("command"));
CHECK(payload["command"].IsString());
}
void DdlCommandExecutor::execute(TQueryResult& _return) {
const auto& payload = ddl_query_["payload"].GetObject();
const auto& ddl_command = std::string_view(payload["command"].GetString());
if (ddl_command == "CREATE_SERVER") {
CreateForeignServerCommand{payload, session_ptr_}.execute(_return);
} else if (ddl_command == "DROP_SERVER") {
DropForeignServerCommand{payload, session_ptr_}.execute(_return);
} else if (ddl_command == "CREATE_FOREIGN_TABLE") {
CreateForeignTableCommand{payload, session_ptr_}.execute(_return);
} else if (ddl_command == "DROP_FOREIGN_TABLE") {
DropForeignTableCommand{payload, session_ptr_}.execute(_return);
} else if (ddl_command == "SHOW_TABLES") {
ShowTablesCommand{payload, session_ptr_}.execute(_return);
} else if (ddl_command == "SHOW_DATABASES") {
ShowDatabasesCommand{payload, session_ptr_}.execute(_return);
} else if (ddl_command == "SHOW_SERVERS") {
ShowForeignServersCommand{payload, session_ptr_}.execute(_return);
} else if (ddl_command == "ALTER_SERVER") {
AlterForeignServerCommand{payload, session_ptr_}.execute(_return);
} else if (ddl_command == "REFRESH_FOREIGN_TABLES") {
RefreshForeignTablesCommand{payload, session_ptr_}.execute(_return);
} else {
throw std::runtime_error("Unsupported DDL command");
}
}
bool DdlCommandExecutor::isShowUserSessions() {
const auto& payload = ddl_query_["payload"].GetObject();
const auto& ddl_command = std::string_view(payload["command"].GetString());
return (ddl_command == "SHOW_USER_SESSIONS");
}
CreateForeignServerCommand::CreateForeignServerCommand(
const rapidjson::Value& ddl_payload,
std::shared_ptr<Catalog_Namespace::SessionInfo const> session_ptr)
: DdlCommand(ddl_payload, session_ptr) {
CHECK(ddl_payload.HasMember("serverName"));
CHECK(ddl_payload["serverName"].IsString());
CHECK(ddl_payload.HasMember("dataWrapper"));
CHECK(ddl_payload["dataWrapper"].IsString());
CHECK(ddl_payload.HasMember("options"));
CHECK(ddl_payload["options"].IsObject());
CHECK(ddl_payload.HasMember("ifNotExists"));
CHECK(ddl_payload["ifNotExists"].IsBool());
}
void CreateForeignServerCommand::execute(TQueryResult& _return) {
std::string server_name = ddl_payload_["serverName"].GetString();
if (isDefaultServer(server_name)) {
throw std::runtime_error{"Server names cannot start with \"omnisci\"."};
}
bool if_not_exists = ddl_payload_["ifNotExists"].GetBool();
if (session_ptr_->getCatalog().getForeignServer(server_name)) {
if (if_not_exists) {
return;
} else {
throw std::runtime_error{"A foreign server with name \"" + server_name +
"\" already exists."};
}
}
// check access privileges
if (!session_ptr_->checkDBAccessPrivileges(DBObjectType::ServerDBObjectType,
AccessPrivileges::CREATE_SERVER)) {
throw std::runtime_error("Server " + std::string(server_name) +
" will not be created. User has no create privileges.");
}
auto& current_user = session_ptr_->get_currentUser();
auto foreign_server = std::make_unique<foreign_storage::ForeignServer>();
foreign_server->data_wrapper_type = to_upper(ddl_payload_["dataWrapper"].GetString());
foreign_server->name = server_name;
foreign_server->user_id = current_user.userId;
foreign_server->populateOptionsMap(ddl_payload_["options"]);
foreign_server->validate();
auto& catalog = session_ptr_->getCatalog();
catalog.createForeignServer(std::move(foreign_server),
ddl_payload_["ifNotExists"].GetBool());
Catalog_Namespace::SysCatalog::instance().createDBObject(
current_user, server_name, ServerDBObjectType, catalog);
}
AlterForeignServerCommand::AlterForeignServerCommand(
const rapidjson::Value& ddl_payload,
std::shared_ptr<const Catalog_Namespace::SessionInfo> session_ptr)
: DdlCommand(ddl_payload, session_ptr) {
CHECK(ddl_payload.HasMember("serverName"));
CHECK(ddl_payload["serverName"].IsString());
CHECK(ddl_payload.HasMember("alterType"));
CHECK(ddl_payload["alterType"].IsString());
if (ddl_payload["alterType"] == "SET_OPTIONS") {
CHECK(ddl_payload.HasMember("options"));
CHECK(ddl_payload["options"].IsObject());
} else if (ddl_payload["alterType"] == "SET_DATA_WRAPPER") {
CHECK(ddl_payload.HasMember("dataWrapper"));
CHECK(ddl_payload["dataWrapper"].IsString());
} else if (ddl_payload["alterType"] == "RENAME_SERVER") {
CHECK(ddl_payload.HasMember("newServerName"));
CHECK(ddl_payload["newServerName"].IsString());
} else if (ddl_payload["alterType"] == "CHANGE_OWNER") {
CHECK(ddl_payload.HasMember("newOwner"));
CHECK(ddl_payload["newOwner"].IsString());
} else {
UNREACHABLE(); // not-implemented alterType
}
}
void AlterForeignServerCommand::execute(TQueryResult& _return) {
std::string server_name = ddl_payload_["serverName"].GetString();
if (isDefaultServer(server_name)) {
throw std::runtime_error{"OmniSci default servers cannot be altered."};
}
if (!session_ptr_->getCatalog().getForeignServer(server_name)) {
throw std::runtime_error{"Foreign server with name \"" + server_name +
"\" does not exist and can not be altered."};
}
if (!hasAlterServerPrivileges()) {
throw std::runtime_error("Server " + server_name +
" can not be altered. User has no ALTER SERVER privileges.");
}
std::string alter_type = ddl_payload_["alterType"].GetString();
if (alter_type == "CHANGE_OWNER") {
changeForeignServerOwner();
} else if (alter_type == "SET_DATA_WRAPPER") {
setForeignServerDataWrapper();
} else if (alter_type == "SET_OPTIONS") {
setForeignServerOptions();
} else if (alter_type == "RENAME_SERVER") {
renameForeignServer();
}
}
void AlterForeignServerCommand::changeForeignServerOwner() {
std::string server_name = ddl_payload_["serverName"].GetString();
std::string new_owner = ddl_payload_["newOwner"].GetString();
auto& sys_cat = Catalog_Namespace::SysCatalog::instance();
if (!session_ptr_->get_currentUser().isSuper) {
throw std::runtime_error(
"Only a super user can change a foreign server's owner. "
"Current user is not a super-user. "
"Foreign server with name \"" +
server_name + "\" will not have owner changed.");
}
Catalog_Namespace::UserMetadata user, original_owner;
if (!sys_cat.getMetadataForUser(new_owner, user)) {
throw std::runtime_error("User with username \"" + new_owner + "\" does not exist. " +
"Foreign server with name \"" + server_name +
"\" can not have owner changed.");
}
auto& cat = session_ptr_->getCatalog();
// get original owner metadata
bool original_owner_exists = sys_cat.getMetadataForUserById(
cat.getForeignServer(server_name)->user_id, original_owner);
// update catalog
cat.changeForeignServerOwner(server_name, user.userId);
try {
// update permissions
DBObject db_object(server_name, DBObjectType::ServerDBObjectType);
sys_cat.changeDBObjectOwnership(
user, original_owner, db_object, cat, original_owner_exists);
} catch (const std::runtime_error& e) {
// update permissions failed, revert catalog update
cat.changeForeignServerOwner(server_name, original_owner.userId);
throw;
}
}
void AlterForeignServerCommand::renameForeignServer() {
std::string server_name = ddl_payload_["serverName"].GetString();
std::string new_server_name = ddl_payload_["newServerName"].GetString();
if (isDefaultServer(new_server_name)) {
throw std::runtime_error{"OmniSci prefix can not be used for new name of server."};
}
auto& cat = session_ptr_->getCatalog();
// check for a conflicting server
if (cat.getForeignServer(new_server_name)) {
throw std::runtime_error("Foreign server with name \"" + server_name +
"\" can not be renamed to \"" + new_server_name + "\"." +
"Foreign server with name \"" + new_server_name +
"\" exists.");
}
// update catalog
cat.renameForeignServer(server_name, new_server_name);
try {
// migrate object privileges
auto& sys_cat = Catalog_Namespace::SysCatalog::instance();
sys_cat.renameDBObject(server_name,
new_server_name,
DBObjectType::ServerDBObjectType,
cat.getForeignServer(new_server_name)->id,
cat);
} catch (const std::runtime_error& e) {
// permission migration failed, revert catalog update
cat.renameForeignServer(new_server_name, server_name);
throw;
}
}
void AlterForeignServerCommand::setForeignServerOptions() {
std::string server_name = ddl_payload_["serverName"].GetString();
auto& cat = session_ptr_->getCatalog();
// update catalog
const auto foreign_server = cat.getForeignServer(server_name);
foreign_storage::OptionsContainer opt;
opt.populateOptionsMap(foreign_server->getOptionsAsJsonString());
opt.populateOptionsMap(ddl_payload_["options"]);
cat.setForeignServerOptions(server_name, opt.getOptionsAsJsonString());
}
void AlterForeignServerCommand::setForeignServerDataWrapper() {
std::string server_name = ddl_payload_["serverName"].GetString();
std::string data_wrapper = ddl_payload_["dataWrapper"].GetString();
auto& cat = session_ptr_->getCatalog();
// update catalog
cat.setForeignServerDataWrapper(server_name, data_wrapper);
}
bool AlterForeignServerCommand::hasAlterServerPrivileges() {
// TODO: implement `GRANT/REVOKE ALTER_SERVER` DDL commands
std::string server_name = ddl_payload_["serverName"].GetString();
return session_ptr_->checkDBAccessPrivileges(
DBObjectType::ServerDBObjectType, AccessPrivileges::ALTER_SERVER, server_name);
}
DropForeignServerCommand::DropForeignServerCommand(
const rapidjson::Value& ddl_payload,
std::shared_ptr<Catalog_Namespace::SessionInfo const> session_ptr)
: DdlCommand(ddl_payload, session_ptr) {
CHECK(ddl_payload.HasMember("serverName"));
CHECK(ddl_payload["serverName"].IsString());
CHECK(ddl_payload.HasMember("ifExists"));
CHECK(ddl_payload["ifExists"].IsBool());
}
void DropForeignServerCommand::execute(TQueryResult& _return) {
std::string server_name = ddl_payload_["serverName"].GetString();
if (isDefaultServer(server_name)) {
throw std::runtime_error{"OmniSci default servers cannot be dropped."};
}
bool if_exists = ddl_payload_["ifExists"].GetBool();
if (!session_ptr_->getCatalog().getForeignServer(server_name)) {
if (if_exists) {
return;
} else {
throw std::runtime_error{"Foreign server with name \"" + server_name +
"\" does not exist."};
}
}
// check access privileges
if (!session_ptr_->checkDBAccessPrivileges(
DBObjectType::ServerDBObjectType, AccessPrivileges::DROP_SERVER, server_name)) {
throw std::runtime_error("Server " + server_name +
" will not be dropped. User has no DROP SERVER privileges.");
}
Catalog_Namespace::SysCatalog::instance().revokeDBObjectPrivilegesFromAll(
DBObject(server_name, ServerDBObjectType), session_ptr_->get_catalog_ptr().get());
session_ptr_->getCatalog().dropForeignServer(ddl_payload_["serverName"].GetString());
}
SQLTypes JsonColumnSqlType::getSqlType(const rapidjson::Value& data_type) {
CHECK(data_type.IsObject());
CHECK(data_type.HasMember("type"));
CHECK(data_type["type"].IsString());
std::string type = data_type["type"].GetString();
if (boost::iequals(type, "ARRAY")) {
CHECK(data_type.HasMember("array"));
CHECK(data_type["array"].IsObject());
const auto& array = data_type["array"].GetObject();
CHECK(array.HasMember("elementType"));
CHECK(array["elementType"].IsString());
type = array["elementType"].GetString();
}
return getSqlType(type);
}
SQLTypes JsonColumnSqlType::getSqlType(const std::string& type) {
if (boost::iequals(type, "BIGINT")) {
return kBIGINT;
}
if (boost::iequals(type, "BOOLEAN")) {
return kBOOLEAN;
}
if (boost::iequals(type, "DATE")) {
return kDATE;
}
if (boost::iequals(type, "DECIMAL")) {
return kDECIMAL;
}
if (boost::iequals(type, "DOUBLE")) {
return kDOUBLE;
}
if (boost::iequals(type, "FLOAT")) {
return kFLOAT;
}
if (boost::iequals(type, "INTEGER")) {
return kINT;
}
if (boost::iequals(type, "LINESTRING")) {
return kLINESTRING;
}
if (boost::iequals(type, "MULTIPOLYGON")) {
return kMULTIPOLYGON;
}
if (boost::iequals(type, "POINT")) {
return kPOINT;
}
if (boost::iequals(type, "POLYGON")) {
return kPOLYGON;
}
if (boost::iequals(type, "SMALLINT")) {
return kSMALLINT;
}
if (boost::iequals(type, "TEXT")) {
return kTEXT;
}
if (boost::iequals(type, "TIME")) {
return kTIME;
}
if (boost::iequals(type, "TIMESTAMP")) {
return kTIMESTAMP;
}
if (boost::iequals(type, "TINYINT")) {
return kTINYINT;
}
throw std::runtime_error{"Unsupported type \"" + type + "\" specified."};
}
int JsonColumnSqlType::getParam1(const rapidjson::Value& data_type) {
int param1 = -1;
CHECK(data_type.IsObject());
if (data_type.HasMember("precision") && !data_type["precision"].IsNull()) {
CHECK(data_type["precision"].IsInt());
param1 = data_type["precision"].GetInt();
} else if (auto type = getSqlType(data_type); IS_GEO(type)) {
param1 = static_cast<int>(kGEOMETRY);
}
return param1;
}
int JsonColumnSqlType::getParam2(const rapidjson::Value& data_type) {
int param2 = 0;
CHECK(data_type.IsObject());
if (data_type.HasMember("scale") && !data_type["scale"].IsNull()) {
CHECK(data_type["scale"].IsInt());
param2 = data_type["scale"].GetInt();
} else if (auto type = getSqlType(data_type); IS_GEO(type) &&
data_type.HasMember("coordinateSystem") &&
!data_type["coordinateSystem"].IsNull()) {
CHECK(data_type["coordinateSystem"].IsInt());
param2 = data_type["coordinateSystem"].GetInt();
}
return param2;
}
bool JsonColumnSqlType::isArray(const rapidjson::Value& data_type) {
CHECK(data_type.IsObject());
CHECK(data_type.HasMember("type"));
CHECK(data_type["type"].IsString());
return boost::iequals(data_type["type"].GetString(), "ARRAY");
}
int JsonColumnSqlType::getArraySize(const rapidjson::Value& data_type) {
int size = -1;
if (isArray(data_type)) {
CHECK(data_type.HasMember("array"));
CHECK(data_type["array"].IsObject());
const auto& array = data_type["array"].GetObject();
if (array.HasMember("size") && !array["size"].IsNull()) {
CHECK(array["size"].IsInt());
size = array["size"].GetInt();
}
}
return size;
}
std::string* JsonColumnEncoding::getEncodingName(const rapidjson::Value& data_type) {
CHECK(data_type.IsObject());
CHECK(data_type.HasMember("encoding"));
CHECK(data_type["encoding"].IsObject());
const auto& encoding = data_type["encoding"].GetObject();
CHECK(encoding.HasMember("type"));
CHECK(encoding["type"].IsString());
return new std::string(encoding["type"].GetString());
}
int JsonColumnEncoding::getEncodingParam(const rapidjson::Value& data_type) {
CHECK(data_type.IsObject());
CHECK(data_type.HasMember("encoding"));
CHECK(data_type["encoding"].IsObject());
int encoding_size = 0;
const auto& encoding = data_type["encoding"].GetObject();
if (encoding.HasMember("size") && !encoding["size"].IsNull()) {
CHECK(encoding["size"].IsInt());
encoding_size = encoding["size"].GetInt();
}
return encoding_size;
}
CreateForeignTableCommand::CreateForeignTableCommand(
const rapidjson::Value& ddl_payload,
std::shared_ptr<Catalog_Namespace::SessionInfo const> session_ptr)
: DdlCommand(ddl_payload, session_ptr) {
CHECK(ddl_payload.HasMember("serverName"));
CHECK(ddl_payload["serverName"].IsString());
CHECK(ddl_payload.HasMember("tableName"));
CHECK(ddl_payload["tableName"].IsString());
CHECK(ddl_payload.HasMember("ifNotExists"));
CHECK(ddl_payload["ifNotExists"].IsBool());
CHECK(ddl_payload.HasMember("columns"));
CHECK(ddl_payload["columns"].IsArray());
}
void CreateForeignTableCommand::execute(TQueryResult& _return) {
auto& catalog = session_ptr_->getCatalog();
const std::string& table_name = ddl_payload_["tableName"].GetString();
if (!session_ptr_->checkDBAccessPrivileges(DBObjectType::TableDBObjectType,
AccessPrivileges::CREATE_TABLE)) {
throw std::runtime_error(
"Foreign table \"" + table_name +
"\" will not be created. User has no CREATE TABLE privileges.");
}
bool if_not_exists = ddl_payload_["ifNotExists"].GetBool();
if (!catalog.validateNonExistentTableOrView(table_name, if_not_exists)) {
return;
}
foreign_storage::ForeignTable foreign_table{};
std::list<ColumnDescriptor> columns{};
setColumnDetails(columns);
setTableDetails(table_name, foreign_table, columns.size());
catalog.createTable(foreign_table, columns, {}, true);
// TODO (max): It's transactionally unsafe, should be fixed: we may create object w/o
// privileges
Catalog_Namespace::SysCatalog::instance().createDBObject(
session_ptr_->get_currentUser(),
foreign_table.tableName,
TableDBObjectType,
catalog);
}
void CreateForeignTableCommand::setTableDetails(const std::string& table_name,
TableDescriptor& td,
const size_t column_count) {
ddl_utils::set_default_table_attributes(table_name, td, column_count);
td.userId = session_ptr_->get_currentUser().userId;
td.storageType = StorageType::FOREIGN_TABLE;
td.hasDeletedCol = false;
td.keyMetainfo = "[]";
td.fragments = "";
td.partitions = "";
auto& foreign_table = dynamic_cast<foreign_storage::ForeignTable&>(td);
const std::string server_name = ddl_payload_["serverName"].GetString();
foreign_table.foreign_server = session_ptr_->getCatalog().getForeignServer(server_name);
if (!foreign_table.foreign_server) {
throw std::runtime_error{"Foreign server with name \"" + server_name +
"\" does not exist."};
}
if (ddl_payload_.HasMember("options") && !ddl_payload_["options"].IsNull()) {
CHECK(ddl_payload_["options"].IsObject());
foreign_table.populateOptionsMap(ddl_payload_["options"]);
if (foreign_table.foreign_server->data_wrapper_type ==
foreign_storage::DataWrapperType::CSV) {
foreign_storage::CsvDataWrapper::validateOptions(&foreign_table);
} else if (foreign_table.foreign_server->data_wrapper_type ==
foreign_storage::DataWrapperType::PARQUET) {
foreign_storage::ParquetDataWrapper::validateOptions(&foreign_table);
}
}
if (const auto it = foreign_table.options.find("FRAGMENT_SIZE");
it != foreign_table.options.end()) {
foreign_table.maxFragRows = std::stoi(it->second);
}
}
void CreateForeignTableCommand::setColumnDetails(std::list<ColumnDescriptor>& columns) {
std::unordered_set<std::string> column_names{};
for (auto& column_def : ddl_payload_["columns"].GetArray()) {
CHECK(column_def.IsObject());
CHECK(column_def.HasMember("name"));
CHECK(column_def["name"].IsString());
const std::string& column_name = column_def["name"].GetString();
CHECK(column_def.HasMember("dataType"));
CHECK(column_def["dataType"].IsObject());
JsonColumnSqlType sql_type{column_def["dataType"]};
const auto& data_type = column_def["dataType"].GetObject();
CHECK(data_type.HasMember("notNull"));
CHECK(data_type["notNull"].IsBool());
std::unique_ptr<JsonColumnEncoding> encoding;
if (data_type.HasMember("encoding") && !data_type["encoding"].IsNull()) {
CHECK(data_type["encoding"].IsObject());
encoding = std::make_unique<JsonColumnEncoding>(column_def["dataType"]);
}
ColumnDescriptor cd;
ddl_utils::validate_non_duplicate_column(column_name, column_names);
ddl_utils::validate_non_reserved_keyword(column_name);
ddl_utils::set_column_descriptor(
column_name, cd, &sql_type, data_type["notNull"].GetBool(), encoding.get());
columns.emplace_back(cd);
}
}
DropForeignTableCommand::DropForeignTableCommand(
const rapidjson::Value& ddl_payload,
std::shared_ptr<Catalog_Namespace::SessionInfo const> session_ptr)
: DdlCommand(ddl_payload, session_ptr) {
CHECK(ddl_payload.HasMember("tableName"));
CHECK(ddl_payload["tableName"].IsString());
CHECK(ddl_payload.HasMember("ifExists"));
CHECK(ddl_payload["ifExists"].IsBool());
}
void DropForeignTableCommand::execute(TQueryResult& _return) {
auto& catalog = session_ptr_->getCatalog();
const std::string& table_name = ddl_payload_["tableName"].GetString();
const TableDescriptor* td{nullptr};
std::unique_ptr<lockmgr::TableSchemaLockContainer<lockmgr::WriteLock>> td_with_lock;
try {
td_with_lock =
std::make_unique<lockmgr::TableSchemaLockContainer<lockmgr::WriteLock>>(
lockmgr::TableSchemaLockContainer<lockmgr::WriteLock>::acquireTableDescriptor(
catalog, table_name, false));
td = (*td_with_lock)();
} catch (const std::runtime_error& e) {
if (ddl_payload_["ifExists"].GetBool()) {
return;
} else {
throw e;
}
}
CHECK(td);
CHECK(td_with_lock);
if (!session_ptr_->checkDBAccessPrivileges(
DBObjectType::TableDBObjectType, AccessPrivileges::DROP_TABLE, table_name)) {
throw std::runtime_error(
"Foreign table \"" + table_name +
"\" will not be dropped. User has no DROP TABLE privileges.");
}
ddl_utils::validate_drop_table_type(td, ddl_utils::TableType::FOREIGN_TABLE);
auto table_data_write_lock =
lockmgr::TableDataLockMgr::getWriteLockForTable(catalog, table_name);
catalog.dropTable(td);
}
ShowTablesCommand::ShowTablesCommand(
const rapidjson::Value& ddl_payload,
std::shared_ptr<Catalog_Namespace::SessionInfo const> session_ptr)
: DdlCommand(ddl_payload, session_ptr) {}
void ShowTablesCommand::execute(TQueryResult& _return) {
// Get all table names in the same way as OmniSql \t command
auto cat_ptr = session_ptr_->get_catalog_ptr();
auto table_names =
cat_ptr->getTableNamesForUser(session_ptr_->get_currentUser(), GET_PHYSICAL_TABLES);
set_headers(_return, std::vector<std::string>{"table_name"});
// Place table names in query result
for (auto& table_name : table_names) {
add_row(_return, std::vector<std::string>{table_name});
}
}
ShowDatabasesCommand::ShowDatabasesCommand(
const rapidjson::Value& ddl_payload,
std::shared_ptr<Catalog_Namespace::SessionInfo const> session_ptr)
: DdlCommand(ddl_payload, session_ptr) {}
void ShowDatabasesCommand::execute(TQueryResult& _return) {
const auto& user = session_ptr_->get_currentUser();
const Catalog_Namespace::DBSummaryList db_summaries =
Catalog_Namespace::SysCatalog::instance().getDatabaseListForUser(user);
set_headers(_return, {"Database", "Owner"});
for (const auto& db_summary : db_summaries) {
add_row(_return, {db_summary.dbName, db_summary.dbOwnerName});
}
}
ShowForeignServersCommand::ShowForeignServersCommand(
const rapidjson::Value& ddl_payload,
std::shared_ptr<Catalog_Namespace::SessionInfo const> session_ptr)
: DdlCommand(ddl_payload, session_ptr) {
if (!g_enable_fsi) {
throw std::runtime_error("Unsupported command: SHOW FOREIGN SERVERS");
}
// Verify that members are valid
CHECK(ddl_payload.HasMember("command"));
if (ddl_payload.HasMember("filters")) {
CHECK(ddl_payload["filters"].IsArray());
int num_filters = 0;
for (auto const& filter_def : ddl_payload["filters"].GetArray()) {
CHECK(filter_def.IsObject());
CHECK(filter_def.HasMember("attribute"));
CHECK(filter_def["attribute"].IsString());
CHECK(filter_def.HasMember("value"));
CHECK(filter_def["value"].IsString());
CHECK(filter_def.HasMember("operation"));
CHECK(filter_def["operation"].IsString());
if (num_filters > 0) {
CHECK(filter_def.HasMember("chain"));
CHECK(filter_def["chain"].IsString());
} else {
CHECK(!filter_def.HasMember("chain"));
}
num_filters++;
}
}
}
void ShowForeignServersCommand::execute(TQueryResult& _return) {
const std::vector<std::string> col_names{
"server_name", "data_wrapper", "created_at", "options"};
std::vector<const foreign_storage::ForeignServer*> results;
const auto& user = session_ptr_->get_currentUser();
if (ddl_payload_.HasMember("filters")) {
session_ptr_->getCatalog().getForeignServersForUser(
&ddl_payload_["filters"], user, results);
} else {
session_ptr_->getCatalog().getForeignServersForUser(nullptr, user, results);
}
set_headers(_return, col_names);
_return.row_set.row_desc[2].col_type.type = TDatumType::type::TIMESTAMP;
for (auto const& server_ptr : results) {
_return.row_set.columns[0].data.str_col.emplace_back(server_ptr->name);
_return.row_set.columns[1].data.str_col.emplace_back(server_ptr->data_wrapper_type);
_return.row_set.columns[2].data.int_col.push_back(server_ptr->creation_time);
_return.row_set.columns[3].data.str_col.emplace_back(
server_ptr->getOptionsAsJsonString());
for (size_t i = 0; i < _return.row_set.columns.size(); i++)
_return.row_set.columns[i].nulls.emplace_back(false);
}
}
RefreshForeignTablesCommand::RefreshForeignTablesCommand(
const rapidjson::Value& ddl_payload,
std::shared_ptr<Catalog_Namespace::SessionInfo const> session_ptr)
: DdlCommand(ddl_payload, session_ptr) {
CHECK(ddl_payload.HasMember("tableNames"));
CHECK(ddl_payload["tableNames"].IsArray());
for (auto const& tablename_def : ddl_payload["tableNames"].GetArray()) {
CHECK(tablename_def.IsString());
}
}
void RefreshForeignTablesCommand::execute(TQueryResult& _return) {
auto& cat = session_ptr_->getCatalog();
auto& data_mgr = cat.getDataMgr();
auto foreign_storage_mgr = data_mgr.getForeignStorageMgr();
const size_t num_tables = ddl_payload_["tableNames"].GetArray().Size();
std::vector<ChunkKey> table_keys(num_tables, ChunkKey(2));
// Once a refresh command is started it needs to lock all tables it's refreshing.
std::vector<std::unique_ptr<lockmgr::TableSchemaLockContainer<lockmgr::WriteLock>>>
locked_table_vec(num_tables);
for (size_t i = 0; i < num_tables; ++i) {
locked_table_vec[i] =
std::make_unique<lockmgr::TableSchemaLockContainer<lockmgr::WriteLock>>(
lockmgr::TableSchemaLockContainer<lockmgr::WriteLock>::acquireTableDescriptor(
cat, ddl_payload_["tableNames"].GetArray()[i].GetString(), false));
}
// We can only start refreshing once we have all the locks we need.
for (size_t i = 0; i < num_tables; ++i) {
const TableDescriptor* td = (*locked_table_vec[i])();
cat.removeFragmenterForTable(td->tableId);
ChunkKey table_prefix{cat.getCurrentDB().dbId, td->tableId};
data_mgr.deleteChunksWithPrefix(table_prefix, MemoryLevel::CPU_LEVEL);
data_mgr.deleteChunksWithPrefix(table_prefix, MemoryLevel::GPU_LEVEL);
table_keys[i] = table_prefix;
}
foreign_storage::OptionsContainer opt;
if (ddl_payload_.HasMember("options") && !ddl_payload_["options"].IsNull()) {
opt.populateOptionsMap(ddl_payload_["options"]);
CHECK(opt.options.find("EVICT") != opt.options.end());
CHECK(boost::iequals(opt.options["EVICT"], "true") ||
boost::iequals(opt.options["EVICT"], "false"));
if (boost::iequals(opt.options["EVICT"], "true")) {
foreign_storage_mgr->refreshTables(table_keys, true);
return;
}
}
foreign_storage_mgr->refreshTables(table_keys, false);
}
| [
"dev@aas.io"
] | dev@aas.io |
0298c5ab73b250fb494b0111a8b80f6e9d2bb300 | 4d5a3fbaeb32cfc1a291ef09199fac654a64537c | /GameData.hpp | 53a28d2246f4e47b2fe21dce0f952bf43fdc765d | [] | no_license | gheaeckkseqrz/ChessIA | c83300a24ede4904c9ed861345feff621d779c65 | 1dc8d3fb752643b9f26f350939239d8dca44cae2 | refs/heads/master | 2016-09-01T19:48:50.564247 | 2013-12-05T21:34:55 | 2013-12-05T21:34:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,798 | hpp | //
// GameData.hpp for ChessIA in /home/wilmot_p/PROG/C++/ChessIA
//
// Made by WILMOT Pierre
// Login <wilmot@epitech.net>
//
// Started on Mon Nov 26 22:14:07 2012 WILMOT Pierre
// Last update Fri Jan 18 02:15:37 2013 WILMOT Pierre
//
#ifndef __GAMEDATA_HPP__
#define __GAMEDATA_HPP__
#include <iostream>
#include <vector>
class GameData
{
public:
enum piece
{
Empty = 0,
Pawn = 1,
Bishop = 2,
Knight = 3,
Rook = 4,
Queen = 5,
King = 6
};
std::string m_pieceNames[9] =
{
"Empty",
"Pawn",
"Bishop",
"Knight",
"Rook",
"Queen",
"King"
};
enum team
{
None,
Black,
White
};
enum e_castle
{
KingSide = 0,
QueenSide = 1
};
enum e_row
{
R1 = 7,
R2 = 6,
R3 = 5,
R4 = 4,
R5 = 3,
R6 = 2,
R7 = 1,
R8 = 0
};
enum e_col
{
CA = 0,
CB = 1,
CC = 2,
CD = 3,
CE = 4,
CF = 5,
CG = 6,
CH = 7
};
GameData();
GameData(GameData const &g);
~GameData() {};
void copy(GameData const &g);
std::ostream& display(std::ostream &os) const;
std::vector<std::pair<piece, team> > & operator[](int i)
{
return m_board[i];
}
std::vector<std::pair<piece, team> > const & operator[](int i) const
{
return m_board[i];
}
int getDirection(team t) const;
team getOtherTeam(team t) const;
std::string getFenString() const;
void setCase(int x, int y, piece p, team t);
protected:
std::vector<std::vector<std::pair<piece, team> > > m_board;
int m_direction[3];
bool m_castle[3][2];
};
std::ostream& operator<<(std::ostream &os, GameData const &gd);
#endif /* __GAMEDATA_HPP__ */
| [
"pierre.wilmot@gmail.com"
] | pierre.wilmot@gmail.com |
738942915aaf42a8110d9c7298ebc10bd32d5749 | 025414d26a2661a3479a6842ce8716877fd2e9da | /BWin/BWin/Event/EventState.h | 09cced81f17c17e92dbb858dd8cb2265d3e3f497 | [
"MIT"
] | permissive | benbraide/BWin | d5ed92d2cf133d090387463fad0e20b9a6aaa3e9 | 465df64e889321283236e405212a37c528dc9f2d | refs/heads/master | 2022-12-07T17:17:44.169467 | 2020-09-03T06:48:55 | 2020-09-03T06:48:55 | 290,417,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 634 | h | #pragma once
namespace Win::Event{
using StateValueType = unsigned __int32;
struct State{
static constexpr StateValueType StopPropagation = (1u << 0x0000);
static constexpr StateValueType PreventDefault = (1u << 0x0001);
static constexpr StateValueType DoingDefault = (1u << 0x0002);
static constexpr StateValueType DoneDefault = (1u << 0x0003);
static constexpr StateValueType CallingHandler = (1u << 0x0004);
static constexpr StateValueType CalledHandler = (1u << 0x0005);
static constexpr StateValueType ValueSet = (1u << 0x0006);
static constexpr StateValueType StopListening = (1u << 0x0007);
};
}
| [
"benbraide@yahoo.com"
] | benbraide@yahoo.com |
de3b47ed104775dd854b3c3dc3b2adf5bf69f7af | b4f35c9cee280f95d59e3752bb9811510b9fa361 | /HelloTuiLua/frameworks/runtime-src/Classes/tui/TuiManager.cpp | 822dbd363701f664e14dea2ec7fad4204ad3b3d9 | [
"MIT"
] | permissive | jackini/Tui-x | be10cce7e92138b26697aa47adb99ae252b3dd6e | 704161ab6f85d83913021c09a17169405f1f92a6 | refs/heads/master | 2021-01-15T22:52:52.112462 | 2015-03-17T01:01:33 | 2015-03-17T01:01:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 39,601 | cpp | #include "TuiManager.h"
#include "tuiconsts.h"
NS_TUI_BEGIN
bool TuiManager::init()
{
m_isAdaptResolution = true;
m_fScaleResolutionX = 1.0f;
m_fScaleResolutionY = 1.0f;
setAdaptResolution(true);
return true;
}
void TuiManager::parseScene(Node* pScene ,const char* sceneName,const char* xmlPath)
{
loadXml(xmlPath);
string xmlContent = m_DataMap.at(xmlPath);
char* buf = new char[ xmlContent.size()+1 ];
memcpy( buf, xmlContent.c_str(), xmlContent.size()+1 );
xml_document<> doc;
doc.parse<0>(buf);
for(xml_node<char> *item = doc.first_node("control");item != NULL;item = item->next_sibling()){
if( strcmp(item->first_attribute("type")->value(),kTuiContainerPanel) == 0){//panel
if(strcmp(item->first_attribute("name")->value(),sceneName) != 0) continue;//only parse the key panel
this->parseControl(pScene,item);
}
}
if(m_isAdaptResolution)
doAdapterResolution(pScene);
delete[] buf;
setAdaptResolution(true);
}
void TuiManager::parseCell(CLayout* pCell, const char* cellName, const char* xmlPath)
{
string xmlContent = m_DataMap.at(xmlPath);
char* buf = new char[xmlContent.size() + 1];
memcpy(buf, xmlContent.c_str(), xmlContent.size() + 1);
xml_document<> doc;
doc.parse<0>(buf);
for (xml_node<char> *item = doc.first_node("control"); item != NULL; item = item->next_sibling()){
if (strcmp(item->first_attribute("type")->value(), kTuiControlCell) == 0){//cell
if (strcmp(item->first_attribute("name")->value(), cellName) != 0) continue;//only parse the key cell
this->parseControl(pCell, item);
}
}
delete[] buf;
}
/////////////////////////////////////////////////////////////////
void TuiManager::parseControl(Node* container, xml_node<char> *item)
{
int tag = atof(item->first_attribute("tag")->value());
int x = atof(item->first_attribute("x")->value());
int y = atof(item->first_attribute("y")->value());
int w = atoi(item->first_attribute("width")->value());
int h = atoi(item->first_attribute("height")->value());
int rotation = atof(item->first_attribute("rotation")->value());
if (strcmp(item->first_attribute("type")->value(), kTuiContainerPanel) == 0){//panel
CWidgetWindow* pPanel = createPanel(tag, x, y, w, h, rotation);
container->addChild(pPanel);
//recursive
for (xml_node<char> *iitem = item->first_node(kTuiNodeControl); iitem != NULL; iitem = iitem->next_sibling()){
parseControl(pPanel, iitem);
}
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlCell) == 0){//cell
//recursive
for (xml_node<char> *iitem = item->first_node(kTuiNodeControl); iitem != NULL; iitem = iitem->next_sibling()){
parseControl(container, iitem);
}
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlImage) == 0){//image
const char* file = item->first_attribute("image")->value();
float scaleX = atof(item->first_attribute("scaleX")->value());
float scaleY = atof(item->first_attribute("scaleY")->value());
int flipX = atoi(item->first_attribute("flipX")->value());
int flipY = atoi(item->first_attribute("flipY")->value());
int isUseFrame = atoi(item->first_attribute("spriteFrame")->value());
CImageView *pImg = createImage(tag, file, scaleX, scaleY, flipX, flipY, x, y, rotation, isUseFrame);
container->addChild(pImg);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlImage9) == 0){//image9
const char* file = item->first_attribute("image")->value();
float w = atof(item->first_attribute("width")->value());
float h = atof(item->first_attribute("height")->value());
float up = atof(item->first_attribute("up")->value());
float down = atof(item->first_attribute("down")->value());
float left = atof(item->first_attribute("left")->value());
float right = atof(item->first_attribute("right")->value());
int isUseFrame = atoi(item->first_attribute("spriteFrame")->value());
CImageViewScale9 *pImg = createImage9(tag, file, x, y, w, h, up, down, left, right, rotation, isUseFrame);
container->addChild(pImg);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlButton) == 0){//button
const char* normal = item->first_attribute("normal")->value();
const char* select = item->first_attribute("select")->value();
const char* disable = item->first_attribute("disable")->value();
float w = atof(item->first_attribute("width")->value());
float h = atof(item->first_attribute("height")->value());
int isUseFrame = atoi(item->first_attribute("spriteFrame")->value());
CButton *pBtn = NULL;
if (item->first_attribute("text")){
const char* lab = item->first_attribute("text")->value();
int r = atoi(item->first_attribute("red")->value());
int g = atoi(item->first_attribute("green")->value());
int b = atoi(item->first_attribute("blue")->value());
int fontSize = atoi(item->first_attribute("textSize")->value());
const char* font = item->first_attribute("textFont")->value();
pBtn = createBtn(tag, Color3B(r, g, b), fontSize, font, lab, normal, select, disable, x, y, w, h, rotation, isUseFrame);
}
else{
pBtn = createBtn(tag, Color3B(), 0, nullptr, nullptr, normal, select, disable, x, y, w, h, rotation, isUseFrame);
}
container->addChild(pBtn);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlToggleView) == 0){//toggleView
const char* normal = item->first_attribute("normal")->value();
const char* select = item->first_attribute("select")->value();
const char* disable = item->first_attribute("disable")->value();
float exclusion = atof(item->first_attribute("exclusion")->value());
int isUseFrame = atoi(item->first_attribute("spriteFrame")->value());
CToggleView* toggle = createToggleView(tag, exclusion, normal, select, disable, x, y, rotation, isUseFrame);
container->addChild(toggle);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlSlider) == 0){//slider
const char* bg = item->first_attribute("bg")->value();
const char* progress = item->first_attribute("progress")->value();
const char* thumb = item->first_attribute("thumb")->value();
int max = atoi(item->first_attribute("max")->value());
int min = atoi(item->first_attribute("min")->value());
int cur = atoi(item->first_attribute("cur")->value());
int isUseFrame = atoi(item->first_attribute("spriteFrame")->value());
CSlider *pSlider = createSlider(tag, max, min, cur, bg, progress, thumb, x, y, rotation, isUseFrame);
container->addChild(pSlider);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlProgress) == 0){//progress
const char* bg = item->first_attribute("bg")->value();
const char* progress = item->first_attribute("progress")->value();
int isShowLabel = atoi(item->first_attribute("showLabel")->value());
int max = atoi(item->first_attribute("max")->value());
int min = atoi(item->first_attribute("min")->value());
int cur = atoi(item->first_attribute("cur")->value());
int isUseFrame = atoi(item->first_attribute("spriteFrame")->value());
CProgressBar *pProgress = createProgress(tag, max, min, cur, bg, progress, isShowLabel, x, y, rotation, isUseFrame);
container->addChild(pProgress);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlLabel) == 0){//label
float size = atof(item->first_attribute("textSize")->value());
int alignment = atoi(item->first_attribute("alignment")->value());
const char* text = item->first_attribute("text")->value();
const char* font = item->first_attribute("textFont")->value();
float w = atof(item->first_attribute("width")->value());
float h = atof(item->first_attribute("height")->value());
int r = atoi(item->first_attribute("red")->value());
int g = atoi(item->first_attribute("green")->value());
int b = atoi(item->first_attribute("blue")->value());
int r2 = atoi(item->first_attribute("strokeRed")->value());
int g2 = atoi(item->first_attribute("strokeGreen")->value());
int b2 = atoi(item->first_attribute("strokeBlue")->value());
int strokeSize = atoi(item->first_attribute("strokeSize")->value());
int shadowDistance = atoi(item->first_attribute("shadowDistance")->value());
int shadowBlur = atoi(item->first_attribute("shadowBlur")->value());
CLabel *pLabel = createLabel(tag, text, font, alignment, size, r, g, b, x, y, w, h,
r2, g2, b2, strokeSize, shadowDistance, shadowBlur, rotation);
container->addChild(pLabel);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlLabelAtlas) == 0){//labelAtlas
const char* imgPath = item->first_attribute("image")->value();
const char* num = item->first_attribute("num")->value();
float w = atof(item->first_attribute("width")->value());
float h = atof(item->first_attribute("height")->value());
CLabelAtlas *pLabAtlas = createLabelAtlas(tag, num, imgPath, x, y, w, h, rotation);
container->addChild(pLabAtlas);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlLabelBMFont) == 0){//labelBmfont
const char* file = item->first_attribute("fnt")->value();
const char* text = item->first_attribute("text")->value();
float w = atof(item->first_attribute("width")->value());
float h = atof(item->first_attribute("height")->value());
CLabelBMFont *pLabBMFont = createLabelBMFont(tag, text, file, x, y, w, h, rotation);
container->addChild(pLabBMFont);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlArmature) == 0){//armature
const char* xml = item->first_attribute("xml")->value();
const char* png = item->first_attribute("png")->value();
const char* plist = item->first_attribute("plist")->value();
const char* name = item->first_attribute("name")->value();
const char* actionName = NULL;
if (item->first_attribute("play")) actionName = item->first_attribute("play")->value();
Armature *pArmature = createArmature(tag, name, actionName, png, plist, xml, x, y, rotation);
container->addChild(pArmature);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlAnim) == 0){//animation
const char* plist = item->first_attribute("plist")->value();
const char* name = item->first_attribute("name")->value();
Sprite *pSprite = createAnim(tag, name, plist, x, y, rotation);
container->addChild(pSprite);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlControl) == 0){//controlView
const char* baseboard = item->first_attribute("baseboard")->value();
const char* joystick = item->first_attribute("joystick")->value();
int isUseFrame = atoi(item->first_attribute("spriteFrame")->value());
CControlView *pControl = createControl(tag, baseboard, joystick, x, y, rotation, isUseFrame);
container->addChild(pControl);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiContainerScroll) == 0){//scrollView
float w = atof(item->first_attribute("width")->value());
float h = atof(item->first_attribute("height")->value());
int innerWidth = atoi(item->first_attribute("innerWidth")->value());
int innerHeight = atoi(item->first_attribute("innerHeight")->value());
int direction = atof(item->first_attribute("direction")->value());
int r = atoi(item->first_attribute("red")->value());
int g = atoi(item->first_attribute("green")->value());
int b = atoi(item->first_attribute("blue")->value());
int a = atoi(item->first_attribute("alpha")->value());
CScrollView *pView = createScrollView(tag, Color4B(r, g, b, a), direction, innerWidth, innerHeight, x, y, w, h, rotation);
container->addChild(pView);
//recursive
for (xml_node<char> *iitem = item->first_node(kTuiNodeControl); iitem != NULL; iitem = iitem->next_sibling()){
parseControl(pView->getContainer(), iitem);
}
}
else if (strcmp(item->first_attribute("type")->value(), kTuiContainerLayout) == 0){//layout
float w = atof(item->first_attribute("width")->value());
float h = atof(item->first_attribute("height")->value());
CLayout *pLayout = createLayout(tag, x, y, w, h, rotation);
container->addChild(pLayout);
//recursive
for (xml_node<char> *iitem = item->first_node(kTuiNodeControl); iitem != NULL; iitem = iitem->next_sibling()){
parseControl(pLayout, iitem);
}
Vector<Node*> vet = pLayout->getChildren();
for (Node *pChild : vet){//Offset coordinates Because CLayout zero point in the lower left corner
pChild->setPosition(pChild->getPosition() + Vec2(w / 2, h / 2));
}
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlListView) == 0){//listView
float w = atof(item->first_attribute("width")->value());
float h = atof(item->first_attribute("height")->value());
float num = atof(item->first_attribute("num")->value());
int r = atoi(item->first_attribute("red")->value());
int g = atoi(item->first_attribute("green")->value());
int b = atoi(item->first_attribute("blue")->value());
int a = atoi(item->first_attribute("alpha")->value());
CListView* pList = createListView(tag, Color4B(r, g, b, a), x, y, w, h, rotation);
container->addChild(pList);
for (int i = 0; i < num; i++){//add item
xml_node<char> *iitem = item->first_node(kTuiNodeControl);
w = atof(iitem->first_attribute("width")->value());
h = atof(iitem->first_attribute("height")->value());
CLayout *pLayout = createLayout(i, 0, 0, w, h, rotation);
for (xml_node<char> *iiitem = iitem->first_node(kTuiNodeControl); iiitem != NULL; iiitem = iiitem->next_sibling()){
parseControl(pLayout, iiitem);
}
Vector<Node*> vet = pLayout->getChildren();
for (Node *pChild : vet){//Offset coordinates Because CLayout zero point in the lower left corner
if (pChild->getTag() > 0)
pChild->setPosition(pChild->getPosition() + Vec2(w / 2, h / 2));
}
pList->insertNodeAtLast(pLayout);
}
pList->reloadData();
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlCheckBox) == 0){//checkBox
const char* normal1 = item->first_attribute("normal1")->value();
const char* normal2 = item->first_attribute("normal2")->value();
const char* select1 = item->first_attribute("select1")->value();
const char* select2 = item->first_attribute("select2")->value();
const char* disable1 = item->first_attribute("disable1")->value();
const char* disable2 = item->first_attribute("disable2")->value();
int isUseFrame = atoi(item->first_attribute("spriteFrame")->value());
CCheckBox *pCheckBox = createCheckBox(tag, normal1, normal2, select1, select2, disable1, disable2, x, y, rotation, isUseFrame);
container->addChild(pCheckBox);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlArmatureBtn) == 0){//ArmatureBtn
const char* png = item->first_attribute("png")->value();
const char* plist = item->first_attribute("plist")->value();
const char* name = item->first_attribute("name")->value();
const char* xml = item->first_attribute("xml")->value();
const char* normal = item->first_attribute("normal")->value();
const char* select = item->first_attribute("select")->value();
ArmatureBtn *pArmBtn = createArmatureBtn(tag, name, normal, select, png, plist, xml, x, y, rotation);
container->addChild(pArmBtn);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlNumbericStepper) == 0){//NumbericStepper
const char* lnormal = item->first_attribute("lnormal")->value();
const char* rnormal = item->first_attribute("rnormal")->value();
const char* lselect = item->first_attribute("lselect")->value();
const char* rselect = item->first_attribute("rselect")->value();
const char* ldisable = item->first_attribute("ldisable")->value();
const char* rdisable = item->first_attribute("rdisable")->value();
const char* stepBg = item->first_attribute("stepBg")->value();
int isLongClickRun = atoi(item->first_attribute("longClickRun")->value());
int max = atoi(item->first_attribute("max")->value());
int min = atoi(item->first_attribute("min")->value());
int cur = atoi(item->first_attribute("cur")->value());
int step = atoi(item->first_attribute("step")->value());
int isUseFrame = atoi(item->first_attribute("spriteFrame")->value());
NumericStepper *pNumStep = createNumStep(tag, isLongClickRun, max, min, cur, step, lnormal, lselect, ldisable, rnormal, rselect, rdisable, stepBg, x, y, rotation, isUseFrame);
container->addChild(pNumStep);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlPaticle) == 0){//Particle
const char* plist = item->first_attribute("plist")->value();
ParticleSystem *pPartical = createParticle(tag, plist, x, y);
container->addChild(pPartical);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlPageView) == 0){//pageView
float w = atof(item->first_attribute("width")->value());
float h = atof(item->first_attribute("height")->value());
float num = atoi(item->first_attribute("num")->value());
int dir = atoi(item->first_attribute("direction")->value());
int r = atoi(item->first_attribute("red")->value());
int g = atoi(item->first_attribute("green")->value());
int b = atoi(item->first_attribute("blue")->value());
int a = atoi(item->first_attribute("alpha")->value());
CPageView *pPageView = createPageView(tag, Color4B(r, g, b, a), dir, num, x, y, w, h, rotation);
container->addChild(pPageView);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlTable) == 0){//TableView
float w = atof(item->first_attribute("width")->value());
float h = atof(item->first_attribute("height")->value());
float num = atoi(item->first_attribute("num")->value());
int dir = atoi(item->first_attribute("direction")->value());
int cellWidth = atoi(item->first_attribute("cellWidth")->value());
int cellHeight = atoi(item->first_attribute("cellHeight")->value());
int r = atoi(item->first_attribute("red")->value());
int g = atoi(item->first_attribute("green")->value());
int b = atoi(item->first_attribute("blue")->value());
int a = atoi(item->first_attribute("alpha")->value());
CTableView *pView = createTableView(tag, Color4B(r, g, b, a), dir, num, cellWidth, cellHeight, x, y, w, h, rotation);
container->addChild(pView);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlGridView) == 0){//GridView
float w = atof(item->first_attribute("width")->value());
float h = atof(item->first_attribute("height")->value());
int cellWidth = atoi(item->first_attribute("cellWidth")->value());
int cellHeight = atoi(item->first_attribute("cellHeight")->value());
int column = atoi(item->first_attribute("column")->value());
int num = atoi(item->first_attribute("num")->value());
int r = atoi(item->first_attribute("red")->value());
int g = atoi(item->first_attribute("green")->value());
int b = atoi(item->first_attribute("blue")->value());
int a = atoi(item->first_attribute("alpha")->value());
CGridView *pView = createGridView(tag, Color4B(r, g, b, a), column, num, cellWidth, cellHeight, x, y, w, h, rotation);
container->addChild(pView);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlGridPageView) == 0){//GridPageView
float w = atof(item->first_attribute("width")->value());
float h = atof(item->first_attribute("height")->value());
int cellWidth = atoi(item->first_attribute("cellWidth")->value());
int cellHeight = atoi(item->first_attribute("cellHeight")->value());
int column = atoi(item->first_attribute("column")->value());
int row = atoi(item->first_attribute("row")->value());
int num = atoi(item->first_attribute("num")->value());
int dir = atoi(item->first_attribute("direction")->value());
int r = atoi(item->first_attribute("red")->value());
int g = atoi(item->first_attribute("green")->value());
int b = atoi(item->first_attribute("blue")->value());
int a = atoi(item->first_attribute("alpha")->value());
CGridPageView *pView = createGridPageView(tag, Color4B(r, g, b, a), dir, column, row, num, cellWidth, cellHeight, x, y, w, h, rotation);
container->addChild(pView);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlEditBox) == 0){//EditBox
float w = atof(item->first_attribute("width")->value());
float h = atof(item->first_attribute("height")->value());
const char* img = item->first_attribute("image")->value();
int inputMode = atoi(item->first_attribute("inputMode")->value());
int inputFlag = atoi(item->first_attribute("inputFlag")->value());
const char* placeHolder = item->first_attribute("placeHolder")->value();
int isUseFrame = atoi(item->first_attribute("spriteFrame")->value());
extension::EditBox *pEdit = createEditBox(tag, placeHolder, img, inputMode, inputFlag, x, y, w, h, rotation, isUseFrame);
container->addChild(pEdit);
}
else if (strcmp(item->first_attribute("type")->value(), kTuiContainerCircleMenu) == 0){//CircleMenu
float w = atof(item->first_attribute("width")->value());
float h = atof(item->first_attribute("height")->value());
CircleMenu *pMenu = createCircleMenu(tag, x, y, w, h, rotation);
container->addChild(pMenu);
//recursive
for (xml_node<char> *iitem = item->first_node(kTuiNodeControl); iitem != NULL; iitem = iitem->next_sibling()){
parseControl(pMenu, iitem);
}
pMenu->reloadData();
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlRichText) == 0){
const char* text = item->first_attribute("text")->value();
int maxLen = atoi(item->first_attribute("max")->value());
int isSpriteFrame = atoi(item->first_attribute("spriteFrame")->value());
CTextRich *pTextRich = createTextRich(tag, text, maxLen, x, y, w, h, rotation, isSpriteFrame);
container->addChild(pTextRich);
}
}
///////////////////////////////////////////////////////////////////
CWidgetWindow *TuiManager::createPanel(float tag, float x, float y, int w, int h, float rotation){
CWidgetWindow *pPanel = CWidgetWindow::create();
pPanel->setContentSize(Size(w, h));
pPanel->setPosition(Vec2(x, y));
pPanel->setRotation(rotation);
pPanel->setTag(tag);
return pPanel;
}
CLayout *TuiManager::createLayout(float tag, float x, float y, float w, float h, float rotation){
CLayout *pLayout = CLayout::create(Size(w, h));
pLayout->setPosition(Vec2(x, -y));
pLayout->setRotation(rotation);
pLayout->setTag(tag);
return pLayout;
}
CScrollView *TuiManager::createScrollView(float tag, Color4B color, int direction, int innerWidth, int innerHeight, float x, float y, float w, float h, float rotation){
CScrollView *pView = CScrollView::create(Size(w, h));
if (color.a != 0) pView->setBackgroundColor(color);
pView->setPosition(Vec2(x, -y));
pView->setContainerSize(Size(innerWidth, innerHeight));
pView->setDirection((CScrollViewDirection)direction);
pView->setRotation(rotation);
pView->setTag(tag);
return pView;
}
CListView *TuiManager::createListView(float tag, Color4B color, float x, float y, float w, float h, float rotation){
CListView *pView = CListView::create(Size(w, h));
if (color.a != 0) pView->setBackgroundColor(color);
pView->setDirection(eScrollViewDirectionVertical);
pView->setPosition(Vec2(x, -y));
pView->setRotation(rotation);
pView->setTag(tag);
return pView;
}
CImageView *TuiManager::createImage(float tag, const char* file, float scaleX, float scaleY, int flipX, int flipY, float x, float y, float rotation, int isUseFrame){
CImageView *pImg = isUseFrame ? CImageView::createWithSpriteFrameName(file) : CImageView::create(file);
Size size = pImg->getContentSize();
pImg->setPosition(Vec2(x, -y));
pImg->setFlippedX(flipX == 1);
pImg->setFlippedY(flipY == 1);
pImg->setScale(scaleX, scaleY);
pImg->setRotation(rotation);
pImg->setTag(tag);
return pImg;
}
CImageViewScale9 *TuiManager::createImage9(float tag, const char* file, float x, float y, float w, float h, float up, float down, float left, float right, float rotation, int isUseFrame){
CImageViewScale9* pSprite = NULL;
if (isUseFrame){
pSprite = CImageViewScale9::createWithSpriteFrameName(file, Rect(up, down, left, right));
}
else{
CImageView *temp = CImageView::create(file);
Size size = temp->getContentSize();
pSprite = CImageViewScale9::create(file, Rect(0, 0, size.width, size.height), Rect(up, down, left, right));
}
pSprite->setContentSize(Size(w * m_fScaleResolutionX, h * m_fScaleResolutionY));
pSprite->setPosition(Vec2(x, -y));
pSprite->setRotation(rotation);
pSprite->setTag(tag);
return pSprite;
}
CButton* TuiManager::createBtn(float tag, Color3B color, int fontSize, const char* font, const char* lab, const char* normal, const char* select, const char* disable, float x, float y, float w, float h, float rotation, int isUseFrame){
CButton * pBtn = NULL;
if (isUseFrame){
pBtn = CButton::createWith9SpriteFrameName(Size(w, h), normal, select, disable);
}
else{
pBtn = CButton::createWith9Sprite(Size(w, h), normal, select, disable);
}
if (lab) pBtn->initText(lab, font, fontSize, Size::ZERO, color);
pBtn->setRotation(rotation);
pBtn->setPosition(Vec2(x, -y));
pBtn->setTag(tag);
return pBtn;
}
CToggleView* TuiManager::createToggleView(float tag, int exclusion, const char* normal, const char* select, const char* disable, float x, float y, float rotation, int isUseFrame){
CToggleView *pToggle = NULL;
if (isUseFrame){
pToggle = CToggleView::create();
pToggle->setNormalSpriteFrameName(normal);
pToggle->setSelectedSpriteFrameName(select);
pToggle->setDisabledSpriteFrameName(disable);
}
else{
pToggle = CToggleView::create(normal, select, disable);
}
pToggle->setRotation(rotation);
pToggle->setExclusion(exclusion);
pToggle->setPosition(x, -y);
pToggle->setTag(tag);
return pToggle;
}
CSlider* TuiManager::createSlider(float tag, int max, int min, int cur, const char* bg, const char* progress, const char* thumb, float x, float y, float rotation, int isUseFrame){
CSlider *pSlider = NULL;
if (isUseFrame){
pSlider = CSlider::createSpriteFrame(thumb, progress);
pSlider->setBackgroundSpriteFrameName(bg);
}
else{
pSlider = CSlider::create(thumb, progress);
pSlider->setBackgroundImage(bg);
}
pSlider->setRotation(rotation);
pSlider->setPosition(Vec2(x, -y));
pSlider->setMinValue(min);
pSlider->setMaxValue(max);
pSlider->setValue(cur);
pSlider->setTag(tag);
return pSlider;
}
CProgressBar* TuiManager::createProgress(float tag, int max, int min, int cur, const char* bg, const char* progress, int isShowLabel, float x, float y, float rotation, int isUseFrame){
CProgressBar *pProgress = NULL;
if (isUseFrame){
pProgress = CProgressBar::createSpriteFrame(progress);
pProgress->setBackgroundSpriteFrameName(bg);
}
else{
pProgress = CProgressBar::create(progress);
pProgress->setBackgroundImage(bg);
}
pProgress->setShowValueLabel(isShowLabel == 1);
pProgress->setRotation(rotation);
pProgress->setPosition(Vec2(x, -y));
pProgress->setMaxValue(max);
pProgress->setMinValue(min);
pProgress->setValue(cur);
pProgress->setTag(tag);
return pProgress;
}
CLabel* TuiManager::createLabel(float tag, const char* text, const char* font, int alignment, float fontSize, int r, int g, int b, float x, float y, float w, float h,
int r2, int g2, int b2, float strokeSize, int shadowDistance, float shadowBlur, float rotation)
{
CLabel *pLabel = CLabel::createWithTTF(text, font, fontSize);
if (shadowDistance != 0){
pLabel->setTextColor(Color4B(r, g, b, 255));
pLabel->enableShadow(Color4B(r2, g2, b2, 255), Size(shadowDistance, shadowDistance), shadowBlur);
}
if (strokeSize != 0){
pLabel->setTextColor(Color4B(r, g, b, 255));
pLabel->enableOutline(Color4B(r2, g2, b2, 255), strokeSize);
}
if (shadowDistance == 0 && strokeSize == 0){
pLabel->setColor(Color3B(r, g, b));
}
pLabel->setAlignment((TextHAlignment)alignment);
pLabel->setDimensions(w, h);
pLabel->setRotation(rotation);
pLabel->setPosition(Vec2(x + w / 2, -(y + h / 2)));
pLabel->setTag(tag);
return pLabel;
}
CLabelAtlas* TuiManager::createLabelAtlas(float tag, const char* num, const char* imgPath, float x, float y, float w, float h, float rotation){
CLabelAtlas *pLabAtlas = CLabelAtlas::create(num, imgPath, w / 12, h, 48);
pLabAtlas->setRotation(rotation);
pLabAtlas->setPosition(Vec2(x, -y));
pLabAtlas->setTag(tag);
return pLabAtlas;
}
CLabelBMFont* TuiManager::createLabelBMFont(float tag, const char* text, const char* file, float x, float y, float w, float h, float rotation){
CLabelBMFont *pLabBMFont = CLabelBMFont::create(TuiUtil::replace_all(string(text), "\\n", "\n"), file, TextHAlignment::LEFT);
pLabBMFont->setAnchorPoint(Vec2(0, 1));
pLabBMFont->setRotation(rotation);
pLabBMFont->setPosition(Vec2(x, -y));
pLabBMFont->setTag(tag);
return pLabBMFont;
}
Armature* TuiManager::createArmature(float tag, const char* name, const char* actionName, const char* png, const char* plist, const char* xml, float x, float y, float rotation){
ArmatureDataManager::getInstance()->addArmatureFileInfo(png, plist, xml);
Armature *pArmature = Armature::create(name);
if (actionName) pArmature->getAnimation()->play(actionName, 0, 1);
pArmature->setPosition(Vec2(x, -y));
pArmature->setRotation(rotation);
pArmature->setTag(tag);
return pArmature;
}
Sprite* TuiManager::createAnim(float tag, const char* name, const char* plist, float x, float y, float rotation){
SpriteFrameCache::getInstance()->addSpriteFramesWithFile(plist);
Animation* pAnim = TuiUtil::createAnimWithName(name, 0.05f, -1);
SpriteFrame *pTmpFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(string(name) + "1.png");
Sprite* pSprite = Sprite::create();
pSprite->runAction(Animate::create(pAnim));
pSprite->setPosition(Vec2(x, -y));
pSprite->setRotation(rotation);
pSprite->setContentSize(pTmpFrame->getOriginalSize());
pSprite->setTag(tag);
return pSprite;
}
CControlView* TuiManager::createControl(float tag, const char* baseboard, const char* joystick, float x, float y, float rotation, int isUseFrame){
CControlView* pView = NULL;
if (isUseFrame){
pView = CControlView::create();
pView->setBaseBoardSpriteFrameName(baseboard);
pView->setJoystickSpriteFrameName(joystick);
}
else{
pView = CControlView::create(baseboard, joystick);
}
pView->setPosition(Vec2(x, -y));
pView->setRadius(pView->getContentSize().width / 2);
pView->setRotation(rotation);
pView->setTag(tag);
return pView;
}
CCheckBox* TuiManager::createCheckBox(float tag, const char* normal1, const char* normal2, const char* select1, const char* select2, const char* disable1, const char* disable2, float x, float y, float rotation, int isUseFrame){
CCheckBox* pCheckBox = NULL;
if (isUseFrame){
pCheckBox = CCheckBox::create();
pCheckBox->setNormalSpriteFrameName(normal1);
pCheckBox->setNormalPressSpriteFrameName(normal2);
pCheckBox->setCheckedSpriteFrameName(select1);
pCheckBox->setCheckedPressSpriteFrameName(select2);
pCheckBox->setDisabledNormalSpriteFrameName(disable1);
pCheckBox->setDisabledCheckedSpriteFrameName(disable2);
}
else{
pCheckBox = CCheckBox::create();
pCheckBox->setNormalImage(normal1);
pCheckBox->setNormalPressImage(normal2);
pCheckBox->setCheckedImage(select1);
pCheckBox->setCheckedPressImage(select2);
pCheckBox->setDisabledNormalImage(disable1);
pCheckBox->setDisabledCheckedImage(disable2);
}
pCheckBox->setRotation(rotation);
pCheckBox->setPosition(Vec2(x, -y));
pCheckBox->setTag(tag);
return pCheckBox;
}
ArmatureBtn* TuiManager::createArmatureBtn(float tag, const char* name, const char* normal, const char* select, const char* png, const char* plist, const char* xml, float x, float y, float rotation){
ArmatureDataManager::getInstance()->addArmatureFileInfo(png, plist, xml);
ArmatureBtn *pArmBtn = ArmatureBtn::create(name);
pArmBtn->setNormalAnimName(normal);
pArmBtn->setSelectAnimName(select);
Size size = pArmBtn->getContentSize();
pArmBtn->setRotation(rotation);
pArmBtn->setPosition(Vec2(x - size.width / 2, -y - size.height / 2));
pArmBtn->setTag(tag);
return pArmBtn;
}
NumericStepper* TuiManager::createNumStep(float tag, int isLongClickRun, int max, int min, int cur, int step, const char* lnormal, const char* lselect, const char* ldisable, const char* rnormal, const char* rselect, const char* rdisable, const char* stepBg, float x, float y, float rotation, int isUseFrame){
NumericStepper* pNumStep = NULL;
if (isUseFrame){
pNumStep = NumericStepper::createSpriteFrameName(lnormal, lselect, ldisable, rnormal, rselect, rdisable, stepBg);
}
else{
pNumStep = NumericStepper::create(lnormal, lselect, ldisable, rnormal, rselect, rdisable, stepBg);
}
Size size = pNumStep->getContentSize();
pNumStep->setLimit(min, max);
pNumStep->setValue(cur);
pNumStep->setStep(step);
pNumStep->setAutoRun(isLongClickRun == 1);
pNumStep->setRotation(rotation);
pNumStep->setPosition(Vec2(x, -y));
pNumStep->setTag(tag);
return pNumStep;
}
ParticleSystemQuad* TuiManager::createParticle(float tag, const char* plist, float x, float y){
ParticleSystemQuad *pPartical = ParticleSystemQuad::create(plist);
pPartical->setPosition(x, -y);
pPartical->setTag(tag);
return pPartical;
}
CTableView* TuiManager::createTableView(float tag, Color4B color, int dir, int num, int cellWidth, int cellHeight, float x, float y, float w, float h, float rotation){
CTableView *pView = CTableView::create(Size(w, h));
if (color.a != 0) pView->setBackgroundColor(color);
pView->setAutoRelocate(true);
pView->setRotation(rotation);
pView->setDirection((CScrollViewDirection)dir);
pView->setCountOfCell(num);
pView->setSizeOfCell(Size(cellWidth, cellHeight));
pView->setRotation(rotation);
pView->setPosition(x, -y);
pView->setTag(tag);
return pView;
}
CGridView* TuiManager::createGridView(float tag, Color4B color, int column, int num, int cellWidth, int cellHeight, float x, float y, float w, float h, float rotation){
CGridView* pView = CGridView::create(Size(w, h));
if (color.a != 0) pView->setBackgroundColor(color);
pView->setAutoRelocate(true);
pView->setRotation(rotation);
pView->setPosition(x, -y);
pView->setColumns(column);
pView->setCountOfCell(num);
pView->setSizeOfCell(Size(cellWidth, cellHeight));
pView->setTag(tag);
return pView;
}
CPageView *TuiManager::createPageView(float tag, Color4B color, int dir, int num, float x, float y, float w, float h, float rotation){
CPageView *pView = CPageView::create(Size(w, h));
if (color.a != 0) pView->setBackgroundColor(color);
pView->setAutoRelocate(true);
pView->setRotation(rotation);
pView->setDirection((CScrollViewDirection)dir);
pView->setCountOfCell(num);
pView->setSizeOfCell(Size(w, h));
pView->setPosition(Vec2(x, -y));
pView->setTag(tag);
return pView;
}
CGridPageView* TuiManager::createGridPageView(float tag, Color4B color, int dir, int column, int row, int num, int cellWidth, int cellHeight, float x, float y, float w, float h, float rotation){
CGridPageView *pView = CGridPageView::create(Size(w, h));
if (color.a != 0) pView->setBackgroundColor(color);
pView->setAutoRelocate(true);
pView->setRotation(rotation);
pView->setDirection((CScrollViewDirection)dir);
pView->setCountOfCell(num);
pView->setColumns(column);
pView->setRows(row);
pView->setSizeOfCell(Size(cellWidth, cellHeight));
pView->setPosition(Vec2(x, -y));
pView->setTag(tag);
return pView;
}
EditBox* TuiManager::createEditBox(float tag, const char* placeHolder, const char* file, int inputMode, int inputFlag, float x, float y, float w, float h, float rotation, int isUseFrame){
EditBox *pEditBox = NULL;
if (isUseFrame){
pEditBox = EditBox::create(Size(w, h), Scale9Sprite::createWithSpriteFrameName(file));
}
else{
pEditBox = EditBox::create(Size(w, h), Scale9Sprite::create(file));
}
pEditBox->setPlaceHolder(placeHolder);
pEditBox->setInputMode((EditBox::InputMode)inputMode);
pEditBox->setInputFlag((EditBox::InputFlag)inputFlag);
pEditBox->setRotation(rotation);
pEditBox->setPosition(Vec2(x, -y));
pEditBox->setTag(tag);
return pEditBox;
}
CircleMenu *TuiManager::createCircleMenu(float tag, float x, float y, float w, float h, float rotation){
CircleMenu *pMenu = CircleMenu::create(Size(w, h));
pMenu->setRotation(rotation);
pMenu->setPosition(Vec2(x, -y));
pMenu->setTag(tag);
return pMenu;
}
CTextRich *TuiManager::createTextRich(float tag, const char *text, int maxLen, float x, float y, float w, float h, float rotation, int isUseFrame){
CTextRich *pTextRich = CTextRich::create();
pTextRich->setMaxLineLength(maxLen);
char* buf = new char[string(text).size() + 1];
memcpy(buf, text, string(text).size() + 1);
xml_document<> doc;
doc.parse<0>(buf);
for (xml_node<char> *item = doc.first_node("e"); item != NULL; item = item->next_sibling()){
if (strcmp(item->first_attribute("type")->value(), kTuiControlLabel) == 0){ //label
const char *text = item->first_attribute("text")->value();
float textSize = 22;
const char *fontName = "";
int r = 255, g = 255, b = 255;
Color3B color = Color3B::WHITE;
if (item->first_attribute("size")) textSize = atof(item->first_attribute("size")->value());
if (item->first_attribute("font")) fontName = item->first_attribute("font")->value();
if (item->first_attribute("r")) r = atoi(item->first_attribute("r")->value());
if (item->first_attribute("g")) g = atoi(item->first_attribute("g")->value());
if (item->first_attribute("b")) b = atoi(item->first_attribute("b")->value());
pTextRich->insertElement(TuiUtil::replace_all(text, "\\n", "\n").c_str(), fontName, textSize, Color3B(r, g, b));
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlImage) == 0){//image
const char *imgSrc = item->first_attribute("src")->value();
int len = atoi(item->first_attribute("len")->value());
if (isUseFrame){
pTextRich->insertElement(CImageView::createWithSpriteFrameName(imgSrc), len);
}
else{
pTextRich->insertElement(CImageView::create(imgSrc), len);
}
}
else if (strcmp(item->first_attribute("type")->value(), kTuiControlAnim) == 0){//anim
const char *name = item->first_attribute("name")->value();
const char *plist = item->first_attribute("src")->value();
int len = atoi(item->first_attribute("len")->value());
Sprite *pAnim = createAnim(0, name, plist, 0, 0, 0);
pTextRich->insertElement(pAnim, len);
}
}
delete[] buf;
pTextRich->reloadData();
pTextRich->setAnchorPoint(Vec2(0, 1));
pTextRich->setRotation(rotation);
pTextRich->setPosition(Vec2(x, -y));
pTextRich->setTag(tag);
return pTextRich;
}
void TuiManager::loadXml(const string& path)
{
if (m_DataMap.find(path) == m_DataMap.end())
{
string pathAbs = FileUtils::getInstance()->fullPathForFilename(path);
m_DataMap[path] = FileUtils::getInstance()->getStringFromFile(pathAbs);
}
}
void TuiManager::doAdapterResolution(Node* pScene){
for (auto node : pScene->getChildren()) {
CWidgetWindow *pWindow = dynamic_cast<CWidgetWindow*>(node);
if (pWindow != nullptr){
pWindow->setPosition(Arp(pWindow->getPosition()));
for (auto child : pWindow->getChildren()) {
child->setPosition(Arp(child->getPosition()));
}
}
}
}
/************************************************************************/
// GET/SET/IS
/************************************************************************/
void TuiManager::setAdaptResolution(bool b, float designWidth/* =800 */,float designHeight/* =480 */){
m_isAdaptResolution = b;
if(b){
Size winSize = Director::getInstance()->getWinSize();
Size desSize = Size(designWidth, designHeight);
m_fScaleResolutionX = winSize.width / desSize.width;
m_fScaleResolutionY = winSize.height / desSize.height;
}else{
m_fScaleResolutionX = 1.0f;
m_fScaleResolutionY = 1.0f;
}
}
NS_TUI_END | [
"342854406@qq.com"
] | 342854406@qq.com |
3de084afd40e00642e8a14d776d02fac7c5dd55d | 247611a46841ab59d7f5776352a3731bf4ae62da | /Source/core/shader/IEshader.cpp | 144e8b1b0652151b3cb19dfd19591a713d0b459f | [] | no_license | ComeOnSweetCandy/Iridescent-Game-Engine | d002cb4ec5c558fe713767db1d0a717b2204c9b0 | d815d610975ca9a6ba29c235fccb195ad31f3edf | refs/heads/master | 2020-03-28T20:08:44.878661 | 2017-10-13T10:03:16 | 2017-10-13T10:03:16 | 94,608,382 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,585 | cpp | #define __IE_DLL_EXPORTS__
#include "IEshader.h"
IE_BEGIN
#define MAX_SHADER_INFO_LOG_SIZE 2048
IEShader::IEShader()
{
m_glslFile = IEString("");
m_vsText = NULL;
m_fsText = NULL;
}
IEShader::IEShader(const char *file)
{
m_glslFile = file;
m_vsText = NULL;
m_fsText = NULL;
}
IEShader::IEShader(IEString &file)
{
m_glslFile = file;
m_vsText = NULL;
m_fsText = NULL;
}
IEShader::~IEShader()
{
}
void IEShader::Initialization()
{
LoadShaderText();
CreateShader();
}
IEShader * IEShader::Create(IEString &file)
{
IEObject * obj = RESOURCE[(char *)(file.GetString())];
if (obj == NULL)
{
IEShader * object = new IEShader(file);
object->Initialization();
RESOURCE[(char *)(file.GetString())] = (IEObject *)object;
return object;
}
else
{
return (IEShader *)obj;
}
}
IEShader * IEShader::Create(const char *file)
{
IEObject * obj = RESOURCE[file];
if (obj == NULL)
{
IEShader * object = new IEShader(file);
object->Initialization();
RESOURCE[file] = (IEObject *)object;
return object;
}
else
{
return (IEShader *)obj;
}
}
void IEShader::ResetShader()
{
LoadShaderText();
CreateShader();
}
void IEShader::LoadShaderText()
{
IEString * texturesFileBaseDir = (IEString *)(SETTING["ShaderDir"]);
IEString body = m_glslFile.GetFileNameBody();
IEString vsFile = *texturesFileBaseDir + body + ".vs.glsl";
IEString fsFile = *texturesFileBaseDir + body + ".fs.glsl";
int shaderLength = 0;
FILE *vsFp = fopen(vsFile.GetString(), "r");
if (vsFp != NULL)
{
while (fgetc(vsFp) != EOF)
{
shaderLength++;
}
rewind(vsFp);
m_vsText = (char *)malloc(shaderLength + 1);
if (m_vsText != NULL)
{
fread(m_vsText, 1, shaderLength, vsFp);
}
m_vsText[shaderLength] = '\0';
fclose(vsFp);
}
shaderLength = 0;
FILE *fsFp = fopen(fsFile.GetString(), "r");
if (fsFp != NULL)
{
while (fgetc(fsFp) != EOF)
{
shaderLength++;
}
rewind(fsFp);
m_fsText = (char *)malloc(shaderLength + 1);
if (m_fsText != NULL)
{
fread(m_fsText, 1, shaderLength, fsFp);
}
m_fsText[shaderLength] = '\0';
fclose(fsFp);
}
}
void IEShader::CreateShader()
{
m_fShader = glCreateShader(GL_FRAGMENT_SHADER);
m_vShader = glCreateShader(GL_VERTEX_SHADER);
const GLchar *vsStringPtr[1];
const GLchar *fsStringPtr[1];
int success;
vsStringPtr[0] = m_vsText;
fsStringPtr[0] = m_fsText;
glShaderSource(m_fShader, 1, fsStringPtr, NULL);
glShaderSource(m_vShader, 1, vsStringPtr, NULL);
glCompileShader(m_vShader);
glGetShaderiv(m_vShader, GL_COMPILE_STATUS, &success);
if (!success)
{
GLchar infoLog[MAX_SHADER_INFO_LOG_SIZE];
glGetShaderInfoLog(m_vShader, MAX_SHADER_INFO_LOG_SIZE, NULL, infoLog);
printf("%s\n", infoLog);
}
glCompileShader(m_fShader);
glGetShaderiv(m_fShader, GL_COMPILE_STATUS, &success);
if (!success)
{
GLchar infoLog[MAX_SHADER_INFO_LOG_SIZE];
glGetShaderInfoLog(m_fShader, MAX_SHADER_INFO_LOG_SIZE, NULL, infoLog);
printf("%s\n", infoLog);
}
m_shaderProgram = glCreateProgram();
glAttachShader(m_shaderProgram, m_vShader);
glAttachShader(m_shaderProgram, m_fShader);
//glDetachShader(m_shaderProgram, m_vShader);
//glDetachShader(m_shaderProgram, m_fShader);
glLinkProgram(m_shaderProgram);
glGetProgramiv(m_shaderProgram, GL_LINK_STATUS, &success);
if (!success)
{
GLchar infoLog[MAX_SHADER_INFO_LOG_SIZE];
glGetProgramInfoLog(m_shaderProgram, MAX_SHADER_INFO_LOG_SIZE, NULL, infoLog);
printf("%s\n", infoLog);
}
free(m_vsText);
free(m_fsText);
glUseProgram(NULL);
}
unsigned int &IEShader::GetShaderProgram()
{
return m_shaderProgram;
}
IE_END
| [
"dingyukun_2008@163.com"
] | dingyukun_2008@163.com |
5ba67ff05e538e4b3d08b7faeea2f3bb4e9c032d | a0eec09e34faea8be09cf9af7df7448dfe87d343 | /nfbe/media/renderers/renderer_impl.cc | 15da61dbe78bc139ed1675264a27abef5029256e | [
"BSD-3-Clause"
] | permissive | bopopescu/SmartTV-SeriesL | 4a7b882d676ba6ff46cdc5813dd9ce22b70e8fe7 | 4b073cd59812cd4702dc318a17fc6ff91ed3cf5b | refs/heads/master | 2021-09-15T00:34:40.911285 | 2018-03-03T16:06:24 | 2018-03-03T16:06:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,501 | cc | // Copyright 2014 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 "media/renderers/renderer_impl.h"
#include <utility>
#include "base/bind.h"
#include "base/callback.h"
#include "base/callback_helpers.h"
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/location.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "media/base/audio_decoder_config.h"
#include "media/base/audio_renderer.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/demuxer_stream_provider.h"
#include "media/base/media_switches.h"
#include "media/base/time_source.h"
#include "media/base/video_decoder_config.h"
#include "media/base/video_renderer.h"
#include "media/base/wall_clock_time_source.h"
namespace media {
// See |video_underflow_threshold_|.
static const int kDefaultVideoUnderflowThresholdMs = 3000;
RendererImpl::RendererImpl(
const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
scoped_ptr<AudioRenderer> audio_renderer,
scoped_ptr<VideoRenderer> video_renderer)
: state_(STATE_UNINITIALIZED),
task_runner_(task_runner),
audio_renderer_(std::move(audio_renderer)),
video_renderer_(std::move(video_renderer)),
time_source_(NULL),
time_ticking_(false),
playback_rate_(0.0),
audio_buffering_state_(BUFFERING_HAVE_NOTHING),
video_buffering_state_(BUFFERING_HAVE_NOTHING),
audio_ended_(false),
video_ended_(false),
cdm_context_(nullptr),
underflow_disabled_for_testing_(false),
clockless_video_playback_enabled_for_testing_(false),
video_underflow_threshold_(
base::TimeDelta::FromMilliseconds(kDefaultVideoUnderflowThresholdMs)),
weak_factory_(this) {
weak_this_ = weak_factory_.GetWeakPtr();
DVLOG(1) << __FUNCTION__;
// TODO(dalecurtis): Remove once experiments for http://crbug.com/470940 are
// complete.
int threshold_ms = 0;
std::string threshold_ms_str(
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kVideoUnderflowThresholdMs));
if (base::StringToInt(threshold_ms_str, &threshold_ms) && threshold_ms > 0) {
video_underflow_threshold_ =
base::TimeDelta::FromMilliseconds(threshold_ms);
}
}
RendererImpl::~RendererImpl() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
// Tear down in opposite order of construction as |video_renderer_| can still
// need |time_source_| (which can be |audio_renderer_|) to be alive.
video_renderer_.reset();
audio_renderer_.reset();
if (!init_cb_.is_null()) {
FinishInitialization(PIPELINE_ERROR_ABORT);
} else if (!flush_cb_.is_null()) {
base::ResetAndReturn(&flush_cb_).Run();
}
}
void RendererImpl::Initialize(
DemuxerStreamProvider* demuxer_stream_provider,
const PipelineStatusCB& init_cb,
const StatisticsCB& statistics_cb,
const BufferingStateCB& buffering_state_cb,
const base::Closure& ended_cb,
const PipelineStatusCB& error_cb,
const base::Closure& waiting_for_decryption_key_cb) {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK_EQ(state_, STATE_UNINITIALIZED);
DCHECK(!init_cb.is_null());
DCHECK(!statistics_cb.is_null());
DCHECK(!buffering_state_cb.is_null());
DCHECK(!ended_cb.is_null());
DCHECK(!error_cb.is_null());
DCHECK(demuxer_stream_provider->GetStream(DemuxerStream::AUDIO) ||
demuxer_stream_provider->GetStream(DemuxerStream::VIDEO));
demuxer_stream_provider_ = demuxer_stream_provider;
statistics_cb_ = statistics_cb;
buffering_state_cb_ = buffering_state_cb;
ended_cb_ = ended_cb;
error_cb_ = error_cb;
init_cb_ = init_cb;
waiting_for_decryption_key_cb_ = waiting_for_decryption_key_cb;
if (HasEncryptedStream() && !cdm_context_) {
state_ = STATE_INIT_PENDING_CDM;
return;
}
state_ = STATE_INITIALIZING;
InitializeAudioRenderer();
}
void RendererImpl::SetCdm(CdmContext* cdm_context,
const CdmAttachedCB& cdm_attached_cb) {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK(cdm_context);
if (cdm_context_) {
DVLOG(1) << "Switching CDM not supported.";
cdm_attached_cb.Run(false);
return;
}
cdm_context_ = cdm_context;
if (state_ != STATE_INIT_PENDING_CDM) {
cdm_attached_cb.Run(true);
return;
}
DCHECK(!init_cb_.is_null());
state_ = STATE_INITIALIZING;
// |cdm_attached_cb| will be fired after initialization finishes.
pending_cdm_attached_cb_ = cdm_attached_cb;
InitializeAudioRenderer();
}
void RendererImpl::Flush(const base::Closure& flush_cb) {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK(flush_cb_.is_null());
if (state_ != STATE_PLAYING) {
DCHECK_EQ(state_, STATE_ERROR);
return;
}
flush_cb_ = flush_cb;
state_ = STATE_FLUSHING;
if (time_ticking_)
PausePlayback();
FlushAudioRenderer();
}
void RendererImpl::StartPlayingFrom(base::TimeDelta time) {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
if (state_ != STATE_PLAYING) {
DCHECK_EQ(state_, STATE_ERROR);
return;
}
time_source_->SetMediaTime(time);
if (audio_renderer_)
audio_renderer_->StartPlaying();
if (video_renderer_)
video_renderer_->StartPlayingFrom(time);
}
void RendererImpl::SetPlaybackRate(double playback_rate) {
DVLOG(1) << __FUNCTION__ << "(" << playback_rate << ")";
DCHECK(task_runner_->BelongsToCurrentThread());
// Playback rate changes are only carried out while playing.
if (state_ != STATE_PLAYING)
return;
time_source_->SetPlaybackRate(playback_rate);
const double old_rate = playback_rate_;
playback_rate_ = playback_rate;
if (!time_ticking_ || !video_renderer_)
return;
if (old_rate == 0 && playback_rate > 0)
video_renderer_->OnTimeStateChanged(true);
else if (old_rate > 0 && playback_rate == 0)
video_renderer_->OnTimeStateChanged(false);
}
void RendererImpl::SetVolume(float volume) {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
if (audio_renderer_)
audio_renderer_->SetVolume(volume);
}
base::TimeDelta RendererImpl::GetMediaTime() {
// No BelongsToCurrentThread() checking because this can be called from other
// threads.
return time_source_->CurrentMediaTime();
}
bool RendererImpl::HasAudio() {
DCHECK(task_runner_->BelongsToCurrentThread());
return audio_renderer_ != NULL;
}
bool RendererImpl::HasVideo() {
DCHECK(task_runner_->BelongsToCurrentThread());
return video_renderer_ != NULL;
}
#if defined(VIDEO_HOLE)
void RendererImpl::UpdateVideoHoleRect(const gfx::RectF& position) {
if (video_renderer_)
video_renderer_->UpdateVideoHoleRect(position);
}
#endif
void RendererImpl::DisableUnderflowForTesting() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK_EQ(state_, STATE_UNINITIALIZED);
underflow_disabled_for_testing_ = true;
}
void RendererImpl::EnableClocklessVideoPlaybackForTesting() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK_EQ(state_, STATE_UNINITIALIZED);
DCHECK(underflow_disabled_for_testing_)
<< "Underflow must be disabled for clockless video playback";
clockless_video_playback_enabled_for_testing_ = true;
}
bool RendererImpl::GetWallClockTimes(
const std::vector<base::TimeDelta>& media_timestamps,
std::vector<base::TimeTicks>* wall_clock_times) {
// No BelongsToCurrentThread() checking because this can be called from other
// threads.
//
// TODO(scherkus): Currently called from VideoRendererImpl's internal thread,
// which should go away at some point http://crbug.com/110814
if (clockless_video_playback_enabled_for_testing_) {
if (media_timestamps.empty()) {
*wall_clock_times = std::vector<base::TimeTicks>(1,
base::TimeTicks::Now());
} else {
*wall_clock_times = std::vector<base::TimeTicks>();
for (auto const &media_time : media_timestamps) {
wall_clock_times->push_back(base::TimeTicks() + media_time);
}
}
return true;
}
return time_source_->GetWallClockTimes(media_timestamps, wall_clock_times);
}
bool RendererImpl::HasEncryptedStream() {
DemuxerStream* audio_stream =
demuxer_stream_provider_->GetStream(DemuxerStream::AUDIO);
if (audio_stream && audio_stream->audio_decoder_config().is_encrypted())
return true;
DemuxerStream* video_stream =
demuxer_stream_provider_->GetStream(DemuxerStream::VIDEO);
if (video_stream && video_stream->video_decoder_config().is_encrypted())
return true;
return false;
}
void RendererImpl::FinishInitialization(PipelineStatus status) {
DCHECK(!init_cb_.is_null());
if (!pending_cdm_attached_cb_.is_null())
base::ResetAndReturn(&pending_cdm_attached_cb_).Run(status == PIPELINE_OK);
base::ResetAndReturn(&init_cb_).Run(status);
}
void RendererImpl::InitializeAudioRenderer() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK_EQ(state_, STATE_INITIALIZING);
DCHECK(!init_cb_.is_null());
PipelineStatusCB done_cb =
base::Bind(&RendererImpl::OnAudioRendererInitializeDone, weak_this_);
if (!demuxer_stream_provider_->GetStream(DemuxerStream::AUDIO)) {
audio_renderer_.reset();
task_runner_->PostTask(FROM_HERE, base::Bind(done_cb, PIPELINE_OK));
return;
}
// Note: After the initialization of a renderer, error events from it may
// happen at any time and all future calls must guard against STATE_ERROR.
audio_renderer_->Initialize(
demuxer_stream_provider_->GetStream(DemuxerStream::AUDIO), done_cb,
cdm_context_, base::Bind(&RendererImpl::OnUpdateStatistics, weak_this_),
base::Bind(&RendererImpl::OnBufferingStateChanged, weak_this_,
&audio_buffering_state_),
base::Bind(&RendererImpl::OnAudioRendererEnded, weak_this_),
base::Bind(&RendererImpl::OnError, weak_this_),
waiting_for_decryption_key_cb_);
}
void RendererImpl::OnAudioRendererInitializeDone(PipelineStatus status) {
DVLOG(1) << __FUNCTION__ << ": " << status;
DCHECK(task_runner_->BelongsToCurrentThread());
// OnError() may be fired at any time by the renderers, even if they thought
// they initialized successfully (due to delayed output device setup).
if (state_ != STATE_INITIALIZING) {
DCHECK(init_cb_.is_null());
audio_renderer_.reset();
return;
}
if (status != PIPELINE_OK) {
FinishInitialization(status);
return;
}
DCHECK(!init_cb_.is_null());
InitializeVideoRenderer();
}
void RendererImpl::InitializeVideoRenderer() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK_EQ(state_, STATE_INITIALIZING);
DCHECK(!init_cb_.is_null());
PipelineStatusCB done_cb =
base::Bind(&RendererImpl::OnVideoRendererInitializeDone, weak_this_);
if (!demuxer_stream_provider_->GetStream(DemuxerStream::VIDEO)) {
video_renderer_.reset();
task_runner_->PostTask(FROM_HERE, base::Bind(done_cb, PIPELINE_OK));
return;
}
video_renderer_->Initialize(
demuxer_stream_provider_->GetStream(DemuxerStream::VIDEO), done_cb,
cdm_context_, base::Bind(&RendererImpl::OnUpdateStatistics, weak_this_),
base::Bind(&RendererImpl::OnBufferingStateChanged, weak_this_,
&video_buffering_state_),
base::Bind(&RendererImpl::OnVideoRendererEnded, weak_this_),
base::Bind(&RendererImpl::OnError, weak_this_),
base::Bind(&RendererImpl::GetWallClockTimes, base::Unretained(this)),
waiting_for_decryption_key_cb_);
}
void RendererImpl::OnVideoRendererInitializeDone(PipelineStatus status) {
DVLOG(1) << __FUNCTION__ << ": " << status;
DCHECK(task_runner_->BelongsToCurrentThread());
// OnError() may be fired at any time by the renderers, even if they thought
// they initialized successfully (due to delayed output device setup).
if (state_ != STATE_INITIALIZING) {
DCHECK(init_cb_.is_null());
audio_renderer_.reset();
video_renderer_.reset();
return;
}
DCHECK(!init_cb_.is_null());
if (status != PIPELINE_OK) {
FinishInitialization(status);
return;
}
if (audio_renderer_) {
time_source_ = audio_renderer_->GetTimeSource();
} else if (!time_source_) {
wall_clock_time_source_.reset(new WallClockTimeSource());
time_source_ = wall_clock_time_source_.get();
}
state_ = STATE_PLAYING;
DCHECK(time_source_);
DCHECK(audio_renderer_ || video_renderer_);
FinishInitialization(PIPELINE_OK);
}
void RendererImpl::FlushAudioRenderer() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK_EQ(state_, STATE_FLUSHING);
DCHECK(!flush_cb_.is_null());
if (!audio_renderer_) {
OnAudioRendererFlushDone();
return;
}
audio_renderer_->Flush(
base::Bind(&RendererImpl::OnAudioRendererFlushDone, weak_this_));
}
void RendererImpl::OnAudioRendererFlushDone() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
if (state_ == STATE_ERROR) {
DCHECK(flush_cb_.is_null());
return;
}
DCHECK_EQ(state_, STATE_FLUSHING);
DCHECK(!flush_cb_.is_null());
// If we had a deferred video renderer underflow prior to the flush, it should
// have been cleared by the audio renderer changing to BUFFERING_HAVE_NOTHING.
DCHECK(deferred_underflow_cb_.IsCancelled());
DCHECK_EQ(audio_buffering_state_, BUFFERING_HAVE_NOTHING);
audio_ended_ = false;
FlushVideoRenderer();
}
void RendererImpl::FlushVideoRenderer() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK_EQ(state_, STATE_FLUSHING);
DCHECK(!flush_cb_.is_null());
if (!video_renderer_) {
OnVideoRendererFlushDone();
return;
}
video_renderer_->Flush(
base::Bind(&RendererImpl::OnVideoRendererFlushDone, weak_this_));
}
void RendererImpl::OnVideoRendererFlushDone() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
if (state_ == STATE_ERROR) {
DCHECK(flush_cb_.is_null());
return;
}
DCHECK_EQ(state_, STATE_FLUSHING);
DCHECK(!flush_cb_.is_null());
DCHECK_EQ(video_buffering_state_, BUFFERING_HAVE_NOTHING);
video_ended_ = false;
state_ = STATE_PLAYING;
base::ResetAndReturn(&flush_cb_).Run();
}
void RendererImpl::OnUpdateStatistics(const PipelineStatistics& stats) {
DCHECK(task_runner_->BelongsToCurrentThread());
statistics_cb_.Run(stats);
}
void RendererImpl::OnBufferingStateChanged(BufferingState* buffering_state,
BufferingState new_buffering_state) {
const bool is_audio = buffering_state == &audio_buffering_state_;
DVLOG(1) << __FUNCTION__ << "(" << *buffering_state << ", "
<< new_buffering_state << ") " << (is_audio ? "audio" : "video");
DCHECK(task_runner_->BelongsToCurrentThread());
bool was_waiting_for_enough_data = WaitingForEnoughData();
// When audio is present and has enough data, defer video underflow callbacks
// for some time to avoid unnecessary glitches in audio; see
// http://crbug.com/144683#c53.
if (audio_renderer_ && !is_audio && state_ == STATE_PLAYING) {
if (video_buffering_state_ == BUFFERING_HAVE_ENOUGH &&
audio_buffering_state_ == BUFFERING_HAVE_ENOUGH &&
new_buffering_state == BUFFERING_HAVE_NOTHING &&
deferred_underflow_cb_.IsCancelled()) {
deferred_underflow_cb_.Reset(base::Bind(
&RendererImpl::OnBufferingStateChanged, weak_factory_.GetWeakPtr(),
buffering_state, new_buffering_state));
task_runner_->PostDelayedTask(FROM_HERE,
deferred_underflow_cb_.callback(),
video_underflow_threshold_);
return;
}
deferred_underflow_cb_.Cancel();
} else if (!deferred_underflow_cb_.IsCancelled() && is_audio &&
new_buffering_state == BUFFERING_HAVE_NOTHING) {
// If audio underflows while we have a deferred video underflow in progress
// we want to mark video as underflowed immediately and cancel the deferral.
deferred_underflow_cb_.Cancel();
video_buffering_state_ = BUFFERING_HAVE_NOTHING;
}
*buffering_state = new_buffering_state;
// Disable underflow by ignoring updates that renderers have ran out of data.
if (state_ == STATE_PLAYING && underflow_disabled_for_testing_ &&
time_ticking_) {
DVLOG(1) << "Update ignored because underflow is disabled for testing.";
return;
}
// Renderer underflowed.
if (!was_waiting_for_enough_data && WaitingForEnoughData()) {
PausePlayback();
// TODO(scherkus): Fire BUFFERING_HAVE_NOTHING callback to alert clients of
// underflow state http://crbug.com/144683
return;
}
// Renderer prerolled.
if (was_waiting_for_enough_data && !WaitingForEnoughData()) {
StartPlayback();
buffering_state_cb_.Run(BUFFERING_HAVE_ENOUGH);
return;
}
}
bool RendererImpl::WaitingForEnoughData() const {
DCHECK(task_runner_->BelongsToCurrentThread());
if (state_ != STATE_PLAYING)
return false;
if (audio_renderer_ && audio_buffering_state_ != BUFFERING_HAVE_ENOUGH)
return true;
if (video_renderer_ && video_buffering_state_ != BUFFERING_HAVE_ENOUGH)
return true;
return false;
}
void RendererImpl::PausePlayback() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK(time_ticking_);
switch (state_) {
case STATE_PLAYING:
DCHECK(PlaybackHasEnded() || WaitingForEnoughData())
<< "Playback should only pause due to ending or underflowing";
break;
case STATE_FLUSHING:
// It's OK to pause playback when flushing.
break;
case STATE_UNINITIALIZED:
case STATE_INIT_PENDING_CDM:
case STATE_INITIALIZING:
NOTREACHED() << "Invalid state: " << state_;
break;
case STATE_ERROR:
// An error state may occur at any time.
break;
}
time_ticking_ = false;
time_source_->StopTicking();
if (playback_rate_ > 0 && video_renderer_)
video_renderer_->OnTimeStateChanged(false);
}
void RendererImpl::StartPlayback() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK_EQ(state_, STATE_PLAYING);
DCHECK(!time_ticking_);
DCHECK(!WaitingForEnoughData());
time_ticking_ = true;
time_source_->StartTicking();
if (playback_rate_ > 0 && video_renderer_)
video_renderer_->OnTimeStateChanged(true);
}
void RendererImpl::OnAudioRendererEnded() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
if (state_ != STATE_PLAYING)
return;
DCHECK(!audio_ended_);
audio_ended_ = true;
RunEndedCallbackIfNeeded();
}
void RendererImpl::OnVideoRendererEnded() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
if (state_ != STATE_PLAYING)
return;
DCHECK(!video_ended_);
video_ended_ = true;
RunEndedCallbackIfNeeded();
}
bool RendererImpl::PlaybackHasEnded() const {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
if (audio_renderer_ && !audio_ended_)
return false;
if (video_renderer_ && !video_ended_)
return false;
return true;
}
void RendererImpl::RunEndedCallbackIfNeeded() {
DVLOG(1) << __FUNCTION__;
DCHECK(task_runner_->BelongsToCurrentThread());
if (!PlaybackHasEnded())
return;
if (time_ticking_)
PausePlayback();
ended_cb_.Run();
}
void RendererImpl::OnError(PipelineStatus error) {
DVLOG(1) << __FUNCTION__ << "(" << error << ")";
DCHECK(task_runner_->BelongsToCurrentThread());
DCHECK_NE(PIPELINE_OK, error) << "PIPELINE_OK isn't an error!";
// An error has already been delivered.
if (state_ == STATE_ERROR)
return;
const State old_state = state_;
state_ = STATE_ERROR;
if (!init_cb_.is_null()) {
DCHECK(old_state == STATE_INITIALIZING ||
old_state == STATE_INIT_PENDING_CDM);
FinishInitialization(error);
return;
}
// After OnError() returns, the pipeline may destroy |this|.
base::ResetAndReturn(&error_cb_).Run(error);
if (!flush_cb_.is_null())
base::ResetAndReturn(&flush_cb_).Run();
}
} // namespace media
| [
"opensource@hisense.com"
] | opensource@hisense.com |
3263837369bc486ecdcef8845cdc2c187e6f6c18 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_6377668744314880_1/C++/Erop/code.cpp | a93a97d33a2230eed1dfca1786239b137940502a | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 5,231 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <thread>
#include <condition_variable>
#include <mutex>
#include <memory>
#include <vector>
#include <queue>
#include <cstdio>
#include <cmath>
#include <set>
#include <map>
#include <algorithm>
#include <string>
#include <cstring>
#include <iostream>
#include <assert.h>
using namespace std;
#pragma comment(linker, "/STACK:167772160")
typedef long long ll;
typedef pair<int, int> pii;
const int INF = 1e9;
const double EPS = 1e-9;
const double PI = acos(-1.);
struct TResult {
int ans[3010];
int cnt;
void PrintToStdout(int index) {
printf("Case #%d:\n", (int)(index + 1));
for (int i = 0; i < cnt; ++i) {
printf("%d\n", ans[i]);
}
}
};
struct point {
ll x, y;
point()
: x(0)
, y(0)
{}
point(ll x, ll y)
: x(x)
, y(y)
{}
point operator - (const point & other) {
return point(x - other.x, y - other.y);
}
ll operator % (const point & other) {
return x*other.y - y*other.x;
}
void scan() {
scanf("%lld %lld", &x, &y);
}
};
struct TInput {
int N;
point P[3010];
void ReadFromStdin() {
scanf("%d", &N);
for (int i = 0; i < N; ++i) {
P[i].scan();
}
}
void Run(TResult& result) {
result.cnt = N;
for (int i = 0; i < N; ++i) {
result.ans[i] = N;
}
if (N == 1) {
result.ans[0] = 0;
return;
}
for (int i = 0; i < N; ++i) {
for (int j = i + 1; j < N; ++j) {
int cnt1 = 0;
int cnt2 = 0;
for (int k = 0; k < N; ++k) {
ll v = (P[k] - P[i]) % (P[j] - P[i]);
if (v < 0)
++cnt1;
if (v > 0)
++cnt2;
}
int ans = min(cnt1, cnt2);
result.ans[i] = min(result.ans[i], ans);
result.ans[j] = min(result.ans[j], ans);
}
}
}
};
typedef shared_ptr<TResult> TResultPtr;
typedef shared_ptr<TInput> TInputPtr;
class TResultQueue {
struct TResultQueueItem {
TResultPtr Result;
size_t Index;
TResultQueueItem(const TResultPtr& result, size_t index)
: Result(result)
, Index(index)
{
}
bool operator < (const TResultQueueItem& other) const {
return Index > other.Index;
}
};
size_t NextIndex;
priority_queue<TResultQueueItem> ResultQueue;
mutex Sync;
public:
TResultQueue()
: NextIndex(0)
{}
void Push(TResultPtr result, size_t index) {
lock_guard<mutex> g(Sync);
ResultQueue.push(TResultQueueItem(result, index));
while (ResultQueue.size() > 0 && ResultQueue.top().Index == NextIndex) {
TResultQueueItem item = ResultQueue.top();
item.Result->PrintToStdout(item.Index);
++NextIndex;
ResultQueue.pop();
if ((NextIndex >= 10000 && NextIndex % 100 == 0) || (NextIndex < 10000 && NextIndex >= 1000 && NextIndex % 10 == 0) || (NextIndex < 1000)) {
cerr << "\r" << NextIndex << " ";
}
}
}
};
class TJobQueue {
typedef pair<TInputPtr, size_t> TInputQueueItem;
queue<TInputQueueItem> InputQueue;
bool IsRunning;
size_t JobIndex;
typedef shared_ptr<thread> TThreadPtr;
vector<TThreadPtr> Threads;
mutex Sync;
TResultQueue ResultQueue;
void operator() () {
TInputQueueItem job;
while (GetNewJob(job)) {
TResultPtr result(new TResult);
job.first.get()->Run(*result.get());
ResultQueue.Push(result, job.second);
}
}
bool GetNewJob(TInputQueueItem& resJob) {
lock_guard<mutex> g(Sync);
if (InputQueue.empty())
return false;
resJob = InputQueue.front();
InputQueue.pop();
return true;
}
public:
TJobQueue()
: IsRunning(false)
, JobIndex(0)
{
}
void Push(TInputPtr input) {
assert(!IsRunning);
InputQueue.push(make_pair(input, JobIndex));
++JobIndex;
}
void Run(size_t numThreads) {
IsRunning = true;
if (numThreads == 1) {
(*this)();
return;
}
for (size_t i = 0; i < numThreads; ++i) {
Threads.push_back(TThreadPtr(new thread(&TJobQueue::operator(), this)));
}
for (const auto& t : Threads) {
t->join();
}
}
};
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int T;
scanf("%d", &T);
TJobQueue jobQueue;
for (int i = 0; i < T; ++i) {
TInputPtr in(new TInput);
in->ReadFromStdin();
jobQueue.Push(in);
}
jobQueue.Run(15);
return 0;
}
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
d53103fa91f5bb2b1d1644c20bd9fd5dce9bd6a4 | ad273708d98b1f73b3855cc4317bca2e56456d15 | /aws-cpp-sdk-synthetics/include/aws/synthetics/model/RuntimeVersion.h | 893714f6d9ea2dee622018ece710d2717d1777e0 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | novaquark/aws-sdk-cpp | b390f2e29f86f629f9efcf41c4990169b91f4f47 | a0969508545bec9ae2864c9e1e2bb9aff109f90c | refs/heads/master | 2022-08-28T18:28:12.742810 | 2020-05-27T15:46:18 | 2020-05-27T15:46:18 | 267,351,721 | 1 | 0 | Apache-2.0 | 2020-05-27T15:08:16 | 2020-05-27T15:08:15 | null | UTF-8 | C++ | false | false | 8,961 | h | /*
* Copyright 2010-2017 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/synthetics/Synthetics_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/DateTime.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace Synthetics
{
namespace Model
{
/**
* <p>This structure contains information about one canary runtime version. For
* more information about runtime versions, see <a
* href="https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html">
* Canary Runtime Versions</a>.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/RuntimeVersion">AWS
* API Reference</a></p>
*/
class AWS_SYNTHETICS_API RuntimeVersion
{
public:
RuntimeVersion();
RuntimeVersion(Aws::Utils::Json::JsonView jsonValue);
RuntimeVersion& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The name of the runtime version. Currently, the only valid value is
* <code>syn-1.0</code>. </p> <p>Specifies the runtime version to use for the
* canary. Currently, the only valid value is <code>syn-1.0</code>.</p>
*/
inline const Aws::String& GetVersionName() const{ return m_versionName; }
/**
* <p>The name of the runtime version. Currently, the only valid value is
* <code>syn-1.0</code>. </p> <p>Specifies the runtime version to use for the
* canary. Currently, the only valid value is <code>syn-1.0</code>.</p>
*/
inline bool VersionNameHasBeenSet() const { return m_versionNameHasBeenSet; }
/**
* <p>The name of the runtime version. Currently, the only valid value is
* <code>syn-1.0</code>. </p> <p>Specifies the runtime version to use for the
* canary. Currently, the only valid value is <code>syn-1.0</code>.</p>
*/
inline void SetVersionName(const Aws::String& value) { m_versionNameHasBeenSet = true; m_versionName = value; }
/**
* <p>The name of the runtime version. Currently, the only valid value is
* <code>syn-1.0</code>. </p> <p>Specifies the runtime version to use for the
* canary. Currently, the only valid value is <code>syn-1.0</code>.</p>
*/
inline void SetVersionName(Aws::String&& value) { m_versionNameHasBeenSet = true; m_versionName = std::move(value); }
/**
* <p>The name of the runtime version. Currently, the only valid value is
* <code>syn-1.0</code>. </p> <p>Specifies the runtime version to use for the
* canary. Currently, the only valid value is <code>syn-1.0</code>.</p>
*/
inline void SetVersionName(const char* value) { m_versionNameHasBeenSet = true; m_versionName.assign(value); }
/**
* <p>The name of the runtime version. Currently, the only valid value is
* <code>syn-1.0</code>. </p> <p>Specifies the runtime version to use for the
* canary. Currently, the only valid value is <code>syn-1.0</code>.</p>
*/
inline RuntimeVersion& WithVersionName(const Aws::String& value) { SetVersionName(value); return *this;}
/**
* <p>The name of the runtime version. Currently, the only valid value is
* <code>syn-1.0</code>. </p> <p>Specifies the runtime version to use for the
* canary. Currently, the only valid value is <code>syn-1.0</code>.</p>
*/
inline RuntimeVersion& WithVersionName(Aws::String&& value) { SetVersionName(std::move(value)); return *this;}
/**
* <p>The name of the runtime version. Currently, the only valid value is
* <code>syn-1.0</code>. </p> <p>Specifies the runtime version to use for the
* canary. Currently, the only valid value is <code>syn-1.0</code>.</p>
*/
inline RuntimeVersion& WithVersionName(const char* value) { SetVersionName(value); return *this;}
/**
* <p>A description of the runtime version, created by Amazon.</p>
*/
inline const Aws::String& GetDescription() const{ return m_description; }
/**
* <p>A description of the runtime version, created by Amazon.</p>
*/
inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; }
/**
* <p>A description of the runtime version, created by Amazon.</p>
*/
inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }
/**
* <p>A description of the runtime version, created by Amazon.</p>
*/
inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); }
/**
* <p>A description of the runtime version, created by Amazon.</p>
*/
inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }
/**
* <p>A description of the runtime version, created by Amazon.</p>
*/
inline RuntimeVersion& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}
/**
* <p>A description of the runtime version, created by Amazon.</p>
*/
inline RuntimeVersion& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}
/**
* <p>A description of the runtime version, created by Amazon.</p>
*/
inline RuntimeVersion& WithDescription(const char* value) { SetDescription(value); return *this;}
/**
* <p>The date that the runtime version was released.</p>
*/
inline const Aws::Utils::DateTime& GetReleaseDate() const{ return m_releaseDate; }
/**
* <p>The date that the runtime version was released.</p>
*/
inline bool ReleaseDateHasBeenSet() const { return m_releaseDateHasBeenSet; }
/**
* <p>The date that the runtime version was released.</p>
*/
inline void SetReleaseDate(const Aws::Utils::DateTime& value) { m_releaseDateHasBeenSet = true; m_releaseDate = value; }
/**
* <p>The date that the runtime version was released.</p>
*/
inline void SetReleaseDate(Aws::Utils::DateTime&& value) { m_releaseDateHasBeenSet = true; m_releaseDate = std::move(value); }
/**
* <p>The date that the runtime version was released.</p>
*/
inline RuntimeVersion& WithReleaseDate(const Aws::Utils::DateTime& value) { SetReleaseDate(value); return *this;}
/**
* <p>The date that the runtime version was released.</p>
*/
inline RuntimeVersion& WithReleaseDate(Aws::Utils::DateTime&& value) { SetReleaseDate(std::move(value)); return *this;}
/**
* <p>If this runtime version is deprecated, this value is the date of
* deprecation.</p>
*/
inline const Aws::Utils::DateTime& GetDeprecationDate() const{ return m_deprecationDate; }
/**
* <p>If this runtime version is deprecated, this value is the date of
* deprecation.</p>
*/
inline bool DeprecationDateHasBeenSet() const { return m_deprecationDateHasBeenSet; }
/**
* <p>If this runtime version is deprecated, this value is the date of
* deprecation.</p>
*/
inline void SetDeprecationDate(const Aws::Utils::DateTime& value) { m_deprecationDateHasBeenSet = true; m_deprecationDate = value; }
/**
* <p>If this runtime version is deprecated, this value is the date of
* deprecation.</p>
*/
inline void SetDeprecationDate(Aws::Utils::DateTime&& value) { m_deprecationDateHasBeenSet = true; m_deprecationDate = std::move(value); }
/**
* <p>If this runtime version is deprecated, this value is the date of
* deprecation.</p>
*/
inline RuntimeVersion& WithDeprecationDate(const Aws::Utils::DateTime& value) { SetDeprecationDate(value); return *this;}
/**
* <p>If this runtime version is deprecated, this value is the date of
* deprecation.</p>
*/
inline RuntimeVersion& WithDeprecationDate(Aws::Utils::DateTime&& value) { SetDeprecationDate(std::move(value)); return *this;}
private:
Aws::String m_versionName;
bool m_versionNameHasBeenSet;
Aws::String m_description;
bool m_descriptionHasBeenSet;
Aws::Utils::DateTime m_releaseDate;
bool m_releaseDateHasBeenSet;
Aws::Utils::DateTime m_deprecationDate;
bool m_deprecationDateHasBeenSet;
};
} // namespace Model
} // namespace Synthetics
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
309a893e44ceeb5369e81298eb0653406adbad22 | de052c5e5ff3aa59e0b97b91e6b3ef6f9e733986 | /ImageSegmentation/Canvas.cpp | f41a91d9b869cbbbb0bd7b1f5a8868db9f993bb3 | [] | no_license | gnishida/ImageSegmentation | bbb408932229a4441413381d064568d8b5bdbd44 | 1f3283bfcd70c582b541162d344d56ee5c05bb1b | refs/heads/master | 2020-07-27T08:57:21.019190 | 2016-09-04T23:19:36 | 2016-09-04T23:19:36 | 67,313,869 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,915 | cpp | #include "Canvas.h"
#include <QPainter>
#include <QMouseEvent>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include "ImageSegmentation.h"
#include <iostream>
Canvas::Canvas(QWidget *parent) : QWidget(parent) {
lineWidth = 10;
}
Canvas::~Canvas() {
}
void Canvas::load(const QString& filename) {
image.load(filename);
update();
}
void Canvas::segment() {
cv::Mat src_img = QImageToCvMat(image);
// create a mask image
QImage maskImage(image.width(), image.height(), QImage::Format_RGB888);
QPainter painter(&maskImage);
painter.fillRect(0, 0, maskImage.width(), maskImage.height(), QColor(255, 255, 255));
drawMaskLines(painter);
cv::Mat mask = QImageToCvMat(maskImage);
// segmentation
cv::Mat dst_img;
imgseg::segment(src_img, mask, dst_img);
image = cvMatToQImage(dst_img);
//cv::imwrite("result.png", dst_img);
foreground_lines.clear();
background_lines.clear();
update();
}
void Canvas::drawMaskLines(QPainter& painter) {
painter.setPen(QPen(QBrush(QColor(0, 0, 255)), lineWidth, Qt::SolidLine, Qt::RoundCap));
for (auto line : foreground_lines) {
for (int i = 0; i < line.size() - 1; ++i) {
painter.drawLine(line[i].x(), line[i].y(), line[i + 1].x(), line[i + 1].y());
}
}
painter.setPen(QPen(QBrush(QColor(255, 0, 0)), lineWidth, Qt::SolidLine, Qt::RoundCap));
for (auto line : background_lines) {
for (int i = 0; i < line.size() - 1; ++i) {
painter.drawLine(line[i].x(), line[i].y(), line[i + 1].x(), line[i + 1].y());
}
}
}
QImage Canvas::cvMatToQImage(const cv::Mat &inMat) {
QImage ret;
static QVector<QRgb> sColorTable(256);
switch (inMat.type()) {
case CV_8UC4: // 8-bit, 4 channel
ret = QImage(inMat.data, inMat.cols, inMat.rows, static_cast<int>(inMat.step), QImage::Format_ARGB32);
break;
case CV_8UC3: // 8-bit, 3 channel
ret = QImage(inMat.data, inMat.cols, inMat.rows, static_cast<int>(inMat.step), QImage::Format_RGB888).rgbSwapped();
break;
case CV_8UC1: // 8-bit, 1 channel
// only create our color table the first time
if (sColorTable.isEmpty()) {
for (int i = 0; i < 256; ++i) {
sColorTable[i] = qRgb(i, i, i);
}
}
ret = QImage(inMat.data, inMat.cols, inMat.rows, static_cast<int>(inMat.step), QImage::Format_Indexed8);
ret.setColorTable(sColorTable);
break;
default:
std::cerr << "cv::Mat image type is not supported:" << inMat.type() << std::endl;
break;
}
return ret;
}
cv::Mat Canvas::QImageToCvMat(const QImage &inImage) {
QImage swapped;
switch (inImage.format()) {
case QImage::Format_ARGB32: // 8-bit, 4 channel
case QImage::Format_ARGB32_Premultiplied: // 8-bit, 4 channel
return cv::Mat(inImage.height(), inImage.width(), CV_8UC4, const_cast<uchar*>(inImage.bits()), static_cast<size_t>(inImage.bytesPerLine())).clone();
case QImage::Format_RGB32: // 8-bit, 3 channel
case QImage::Format_RGB888: // 8-bit, 3 channel
if (inImage.format() == QImage::Format_RGB32)
swapped = inImage.convertToFormat(QImage::Format_RGB888).rgbSwapped();
else
swapped = inImage.rgbSwapped();
return cv::Mat(swapped.height(), swapped.width(), CV_8UC3, const_cast<uchar*>(swapped.bits()), static_cast<size_t>(swapped.bytesPerLine())).clone();
case QImage::Format_Indexed8: // 8-bit, 1 channel
return cv::Mat(inImage.height(), inImage.width(), CV_8UC1, const_cast<uchar*>(inImage.bits()), static_cast<size_t>(inImage.bytesPerLine())).clone();
default:
std::cerr << "cv::Mat image type is not supported:" << inImage.format() << std::endl;
break;
}
return cv::Mat();
}
void Canvas::paintEvent(QPaintEvent *event) {
QPainter painter(this);
painter.drawImage(0, 0, image, 0, 0);
drawMaskLines(painter);
/*
painter.setPen(QPen(QBrush(QColor(0, 0, 255)), lineWidth, Qt::SolidLine, Qt::RoundCap));
for (auto line : foreground_lines) {
for (int i = 0; i < line.size() - 1; ++i) {
painter.drawLine(line[i].x(), line[i].y(), line[i + 1].x(), line[i + 1].y());
}
}
painter.setPen(QPen(QBrush(QColor(255, 0, 0)), lineWidth, Qt::SolidLine, Qt::RoundCap));
for (auto line : background_lines) {
for (int i = 0; i < line.size() - 1; ++i) {
painter.drawLine(line[i].x(), line[i].y(), line[i + 1].x(), line[i + 1].y());
}
}
*/
}
void Canvas::mousePressEvent(QMouseEvent *event) {
lastPoint = event->pos();
if (event->button() == Qt::LeftButton) {
foreground_lines.resize(foreground_lines.size() + 1);
foreground_lines.back().push_back(event->pos());
}
else if (event->button() == Qt::RightButton) {
background_lines.resize(background_lines.size() + 1);
background_lines.back().push_back(event->pos());
}
update();
}
void Canvas::mouseMoveEvent(QMouseEvent *event) {
if (event->buttons() & Qt::LeftButton) {
foreground_lines.back().push_back(event->pos());
}
else if (event->buttons() & Qt::RightButton) {
background_lines.back().push_back(event->pos());
}
update();
}
void Canvas::mouseReleaseEvent(QMouseEvent *event) {
} | [
"gnishida@purdue.edu"
] | gnishida@purdue.edu |
1bfa6cd83af4985b942d9b2275d0c10531aba438 | f3b05abbc9622b85bf337479bf3ce42e9fdfc957 | /threading_socket/socket_cl.cpp | a5e74462fb1e708d5ae40bf4c16254adf06c2b66 | [] | no_license | LukMRVC/Osy | b1a4a97afd402b362a2798b14be1be4427cbca44 | c321871aafd20c1acdb1f513ee7a64149c812a70 | refs/heads/master | 2021-05-18T15:59:19.657834 | 2020-05-18T13:21:10 | 2020-05-18T13:21:10 | 251,306,822 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,230 | cpp | //***************************************************************************
//
// Program example for labs in subject Operating Systems
//
// Petr Olivka, Dept. of Computer Science, petr.olivka@vsb.cz, 2017
//
// Example of socket server.
//
// This program is example of socket client.
// The mandatory arguments of program is IP adress or name of server and
// a port number.
//
//***************************************************************************
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <stdarg.h>
#include <sys/socket.h>
#include <sys/param.h>
#include <sys/time.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h>
#include "BufferedFileDescriptorReader.h"
#include <time.h>
#define STR_CLOSE "close"
//***************************************************************************
// log messages
#define LOG_ERROR 0 // errors
#define LOG_INFO 1 // information and notifications
#define LOG_DEBUG 2 // debug messages
// debug flag
int debug = LOG_INFO;
void log_msg( int log_level, const char *form, ... )
{
const char *out_fmt[] = {
"ERR: (%d-%s) %s\n",
"INF: %s\n",
"DEB: %s\n" };
if ( log_level && log_level > debug ) return;
char buf[ 1024 ];
va_list arg;
va_start( arg, form );
vsprintf( buf, form, arg );
va_end( arg );
switch ( log_level )
{
case LOG_INFO:
case LOG_DEBUG:
fprintf( stdout, out_fmt[ log_level ], buf );
break;
case LOG_ERROR:
fprintf( stderr, out_fmt[ log_level ], errno, strerror( errno ), buf );
break;
}
}
//***************************************************************************
// help
void help( int argn, char **arg )
{
if ( argn <= 1 ) return;
if ( !strcmp( arg[ 1 ], "-h" ) )
{
printf(
"\n"
" Socket client example.\n"
"\n"
" Use: %s [-h -d] ip_or_name port_number\n"
"\n"
" -d debug mode \n"
" -h this help\n"
"\n", arg[ 0 ] );
exit( 0 );
}
if ( !strcmp( arg[ 1 ], "-d" ) )
debug = LOG_DEBUG;
}
//***************************************************************************
int main( int argn, char **arg )
{
if ( argn <= 2 ) help( argn, arg );
int port = 0;
int total_sent = 0;
int total_received = 0;
char *host = NULL;
// parsing arguments
for ( int i = 1; i < argn; i++ )
{
if ( !strcmp( arg[ i ], "-d" ) )
debug = LOG_DEBUG;
if ( !strcmp( arg[ i ], "-h" ) )
help( argn, arg );
if ( *arg[ i ] != '-' )
{
if ( !host )
host = arg[ i ];
else if ( !port )
port = atoi( arg[ i ] );
}
}
if ( !host || !port )
{
log_msg( LOG_INFO, "Host or port is missing!" );
help( argn, arg );
exit( 1 );
}
log_msg( LOG_INFO, "Connection to '%s':%d.", host, port );
addrinfo ai_req, *ai_ans;
bzero( &ai_req, sizeof( ai_req ) );
ai_req.ai_family = AF_INET;
ai_req.ai_socktype = SOCK_STREAM;
int get_ai = getaddrinfo( host, NULL, &ai_req, &ai_ans );
if ( get_ai )
{
log_msg( LOG_ERROR, "Unknown host name!" );
exit( 1 );
}
sockaddr_in cl_addr = *( sockaddr_in * ) ai_ans->ai_addr;
cl_addr.sin_port = htons( port );
freeaddrinfo( ai_ans );
// socket creation
int sock_client = socket( AF_INET, SOCK_STREAM, 0 );
if ( sock_client == -1 )
{
log_msg( LOG_ERROR, "Unable to create socket.");
exit( 1 );
}
// connect to server
if ( connect( sock_client, ( sockaddr * ) &cl_addr, sizeof( cl_addr ) ) < 0 )
{
log_msg( LOG_ERROR, "Unable to connect server." );
exit( 1 );
}
uint lsa = sizeof( cl_addr );
// my IP
getsockname( sock_client, ( sockaddr * ) &cl_addr, &lsa );
log_msg( LOG_INFO, "My IP: '%s' port: %d",
inet_ntoa( cl_addr.sin_addr ), ntohs( cl_addr.sin_port ) );
// server IP
getpeername( sock_client, ( sockaddr * ) &cl_addr, &lsa );
log_msg( LOG_INFO, "Server IP: '%s' port: %d",
inet_ntoa( cl_addr.sin_addr ), ntohs( cl_addr.sin_port ) );
log_msg( LOG_INFO, "Enter 'close' to close application." );
BufferedFileDescriptorReader stdinReader(STDIN_FILENO);
BufferedFileDescriptorReader reader(sock_client);
srand(time(NULL));
// go!
while ( 1 )
{
int sum = total_sent;
int count = rand() % 16 + 5;
dprintf(sock_client, "%d ", sum);
for (int i = 0; i < count; ++i) {
int num = rand() % 1000;
dprintf(sock_client, "%d ", num);
sum += num;
}
dprintf(sock_client, "%d\n", sum);
++total_sent;
char buf[ 128 ];
// set of handles
fd_set read_wait_set;
// clean set
FD_ZERO( &read_wait_set );
// add stdin
FD_SET( STDIN_FILENO, &read_wait_set );
// add socket
FD_SET( sock_client, &read_wait_set );
// select from handles
if ( select( sock_client + 1, &read_wait_set, NULL, NULL, NULL ) < 0 ) break;
// data on stdin?
if ( FD_ISSET( STDIN_FILENO, &read_wait_set ) )
{
// read from stdin
int l = stdinReader.readline(buf, sizeof( buf ) );
if ( l < 0 )
log_msg( LOG_ERROR, "Unable to read from stdin." );
else
log_msg( LOG_DEBUG, "Read %d bytes from stdin.", l );
// send data to server
l = write( sock_client, buf, l );
if ( l < 0 )
log_msg( LOG_ERROR, "Unable to send data to server." );
else
log_msg( LOG_DEBUG, "Sent %d bytes to server.", l );
}
// data from server?
if ( FD_ISSET( sock_client, &read_wait_set ) )
{
// read data from server
int l = reader.readline(buf, sizeof( buf ) );
total_received++;
if ( !l )
{
log_msg( LOG_DEBUG, "Server closed socket." );
break;
}
else if ( l < 0 )
log_msg( LOG_DEBUG, "Unable to read data from server." );
else
log_msg( LOG_DEBUG, "Read %d bytes from server.", l );
// display on stdout
l = write( STDOUT_FILENO, buf, l );
if ( l < 0 )
log_msg( LOG_ERROR, "Unable to write to stdout." );
// request to close?
if ( !strncasecmp( buf, STR_CLOSE, strlen( STR_CLOSE ) ) )
{
log_msg( LOG_INFO, "Connection will be closed..." );
break;
}
}
}
// close socket
close( sock_client );
printf("Totally send %d requests\n", total_sent);
printf("Totally received %d responses\n", total_received);
return 0;
}
| [
"sydnexpklover@gmail.com"
] | sydnexpklover@gmail.com |
a07b679d593f4a2b5316e173c2723d797f48f7bb | 5856e508efacad6354c3b823d78512a51ba203ec | /P5/Project 3/SDLSimple/Level1.cpp | f053bbd096f8a4c898aab972f8fda97146c630b4 | [] | no_license | YuehanD/CSUY3113 | 75fc9f0b76d6755017ce8b7e0b671912e5c5e2e7 | 7b5c13f35e25814c5aaf75160586fe890dd5567b | refs/heads/main | 2023-07-08T15:34:38.351894 | 2021-08-11T17:51:42 | 2021-08-11T17:51:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,494 | cpp | #include "Level1.h"
#define LEVEL1_ENEMY_COUNT 1
#define LEVEL1_WIDTH 14
#define LEVEL1_HEIGHT 8
unsigned int level1_data[] =
{
3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
3, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
3, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2,
3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
};
void Level1::Initialize() {
state.nextScene = -1;
GLuint mapTextureID = Util::LoadTexture("tileset.png");
state.map = new Map(LEVEL1_WIDTH, LEVEL1_HEIGHT, level1_data, mapTextureID, 1.0f, 4, 1);
// Move over all of the player and enemy code from initialization.
// Initialize Player
state.player = new Entity();
//state.player->modelMatrix = glm::scale(modelMatrix, glm::vec3(0.5f, 0.5f, 1.0f));
state.player->position = glm::vec3(5, -3.0f, 0);
state.player->movement = glm::vec3(0);
state.player->acceleration = glm::vec3(0, -10.81f, 0);
state.player->speed = 2.2f;
state.player->textureID = Util::LoadTexture("mdr.png");
state.player->animRight = new int[4]{ 8, 9, 10, 11 };
state.player->animLeft = new int[4]{ 4, 5, 6, 7 };
state.player->animUp = new int[4]{ 12, 13, 14, 15 };
state.player->animDown = new int[4]{ 0, 1, 2, 3 };
state.player->animIndices = state.player->animRight;
state.player->animFrames = 4;
state.player->animIndex = 0;
state.player->animTime = 0;
state.player->animCols = 4;
state.player->animRows = 4;
state.player->height = 0.8f;
state.player->width = 0.5f;
state.player->entityType = PLAYER;
state.player->jumpPower = 5.2f;
state.player->entityType = PLAYER;
state.enemies = new Entity[LEVEL1_ENEMY_COUNT];
GLuint enemyTextureID = Util::LoadTexture("ctg2.png");
state.enemies[0].entityType = ENEMY;
state.enemies[0].textureID = enemyTextureID;
state.enemies[0].position = glm::vec3(5, -3.0f, 0);
state.enemies[0].speed = 1;
state.enemies[0].isActive = true;
state.enemies[0].aiType = WALKER;
}
void Level1::Update(float deltaTime) {
state.player->Update(deltaTime, state.player, state.enemies, LEVEL1_ENEMY_COUNT, state.map);
//state.enemies[0].Update(deltaTime, state.player, state.enemies, LEVEL1_ENEMY_COUNT, state.map);
if (state.player->position.x >= 12) {
state.nextScene = 2;
}
}
void Level1::Render(ShaderProgram *program) {
state.map->Render(program);
state.player->Render(program);
state.enemies[0].Render(program);
}
| [
"yd1521@nyu.edu"
] | yd1521@nyu.edu |
7033d5a4415ea8bc4abb82bf6be678aa6ebb24ef | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_old_new_block_417.cpp | c87de9e377f73ae0bb03d007a898fe6ee99afb66 | [] | 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 | 108 | cpp | {
this->ImportFlag = false;
fprintf(this->FileOut,"EXPORTS \n");
} | [
"993273596@qq.com"
] | 993273596@qq.com |
f49106afebb627b203cb2fd37cb56f1da402ff23 | 4b001fc8ce01429b1ffc8c7144f3b55ccf07f5e0 | /main/main.ino | 9abbf9e7005f2993440e8286130d4f3e1f62d854 | [] | no_license | vSebas/SelfBalancingRobot | 01b352b680e3bc1c0ca551331e9ac64762c94f3c | aed87f6b4d11a41d7b15af0ce1502f29d4463990 | refs/heads/master | 2023-02-03T14:48:09.363471 | 2020-12-24T00:26:28 | 2020-12-24T00:26:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,655 | ino | #include <Adafruit_NeoPixel.h>
#define PIN 12
#define NUM_LEDS 16 // set to an even number
#define MIRROR 8 // set to 1/2 of the LED count
#define SPARKLES_PERCENTAGE 20
// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products)
// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);
void setup() {
strip.begin();
strip.setBrightness(5);
strip.show(); // Initialize all pixels to 'off'
}
void loop() {
Fire(55,120,15);
}
void Fire(int Cooling, int Sparking, int SpeedDelay) {
static byte heat[NUM_LEDS];
int cooldown;
// Step 1. Cool down every cell a little
for( int i = 0; i < NUM_LEDS; i++) {
cooldown = random(0, ((Cooling * 10) / NUM_LEDS) + 2);
if(cooldown>heat[i]) {
heat[i]=0;
} else {
heat[i]=heat[i]-cooldown;
}
}
// Step 2. Heat from each cell drifts 'up' and diffuses a little
for( int k= NUM_LEDS - 1; k >= 2; k--) {
heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2]) / 3;
}
// Step 3. Randomly ignite new 'sparks' near the bottom
if( random(255) < Sparking ) {
int y = random(NUM_LEDS / (100 / SPARKLES_PERCENTAGE));
heat[y] = heat[y] + random(160,255);
}
// Step 4. Convert heat to LED colors
for( int j = 0; j < NUM_LEDS - MIRROR; j++) {
setPixelHeatColor(j+MIRROR, heat[j] );
setPixelHeatColor(MIRROR-j-1, heat[j] );
}
showStrip();
delay(SpeedDelay);
}
void setPixelHeatColor (int Pixel, byte temperature) {
byte t192 = round((temperature/255.0)*191);
byte heatramp = t192 & 0x3F; // 0..63
heatramp <<= 2; // scale up to 0..252
// figure out which third of the spectrum we're in:
if(t192 > 0x80){ // hottest
setPixel(Pixel, 255, 255, heatramp);
}else if(t192 > 0x40 ){ // middle
setPixel(Pixel, 255, heatramp, 0);
}else{ // coolest
setPixel(Pixel, heatramp, 0, 0);
}
}
void showStrip(){
// NeoPixel
strip.show();
}
void setPixel(int Pixel, byte red, byte green, byte blue){
// NeoPixel
strip.setPixelColor(Pixel, strip.Color(red, green, blue));
}
void setAll(byte red, byte green, byte blue) {
for(int i = 0; i < NUM_LEDS; i++ ) {
setPixel(i, red, green, blue);
}
showStrip();
} | [
"pcruiher089@gmail.com"
] | pcruiher089@gmail.com |
8517c79afd1fb9e8e80010930c2c9404bc2b49d9 | 8049b3d1607937b13be0755a02179268d79b03e1 | /CPU/CPU.cpp | 65839a56b629e86ee67852b9287edf7b7da87299 | [] | no_license | romirk/CPU | d8a02c256b14d6ff867c41d2abaf275ba605cf7f | 7bbe7191d4b7c78877030e648f54a8f5b17d471a | refs/heads/master | 2023-01-01T04:09:59.907695 | 2020-09-30T12:42:55 | 2020-09-30T12:42:55 | 297,413,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 847 | cpp | #include <iostream>
#include <string>
#include "CPU.h"
int main()
{
void program();
//cpu.dumpFlags();
cpu.load(program); // the program to be exeuted is passed as a param
cpu.run(); // and off we go!
}
/**
aux function to write program into memory so I don't have to do it manually
*/
void program() {
std::string s = "Hello world!";
for (char c : s) { //technically for loops don't exist in x64 but I'm lazy and dont want to copy/paste this 20 times
cpu.write_instruction(MOVL, c, 0, false, true); //MOVQ c, %rax
cpu.write_instruction(PUTC); //PUTCHAR
}
cpu.push('\n');
cpu.write_instruction(MOV, cpu.sp(), 0, false, true);
cpu.write_instruction(PUTC);
cpu.write_instruction(EXIT);
}
| [
"romir.kulshrestha@gmail.com"
] | romir.kulshrestha@gmail.com |
2ea2582c38c8df23d9abd2728b6fb09b2a6e8386 | 12ad1447e12565e5cdd916eae7799ad335e8e38e | /dataStructures/main.cpp | 1be64d65fa3f2dfe67017c1835e96243f07c88f3 | [] | no_license | Weikang01/dataStructures | a7a410c12fd320a017aea4943e7a6c5a6872f3a9 | a362170bb1cb3618e311d2a10f09680945f4facd | refs/heads/master | 2023-07-11T07:49:32.664359 | 2021-08-12T10:00:25 | 2021-08-12T10:00:25 | 392,946,867 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 174 | cpp | #include <iostream>
#include "binaryTree.h"
int main()
{
binaryTree<int> t;
t.add(2);
t.add(10);
t.add(1);
t.add(3);
t.inOrderTraverse();
std::cin.get();
return 0;
} | [
"Administrator@XTZJ-2021VIRHQS"
] | Administrator@XTZJ-2021VIRHQS |
04fedbe4ee010d9fad7c8fa7045b5bff433cb73b | 5456502f97627278cbd6e16d002d50f1de3da7bb | /chrome/browser/metrics/perf/random_selector.cc | 17b925be9a9e47da32185ba7e7adf00dcf9f9dab | [
"BSD-3-Clause"
] | permissive | TrellixVulnTeam/Chromium_7C66 | 72d108a413909eb3bd36c73a6c2f98de1573b6e5 | c8649ab2a0f5a747369ed50351209a42f59672ee | refs/heads/master | 2023-03-16T12:51:40.231959 | 2017-12-20T10:38:26 | 2017-12-20T10:38:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,847 | cc | // Copyright 2015 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 "chrome/browser/metrics/perf/random_selector.h"
#include "base/logging.h"
#include "base/rand_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
RandomSelector::RandomSelector() : sum_of_weights_(0) {}
RandomSelector::~RandomSelector() {}
// static
double RandomSelector::SumWeights(const std::vector<WeightAndValue>& odds) {
double sum = 0.0;
for (const auto& odd : odds) {
if (odd.weight <= 0.0)
return -1.0;
sum += odd.weight;
}
return sum;
}
bool RandomSelector::SetOdds(const std::vector<WeightAndValue>& odds) {
double sum = SumWeights(odds);
if (sum <= 0.0)
return false;
odds_ = odds;
sum_of_weights_ = sum;
return true;
}
const std::string& RandomSelector::Select() {
// Get a random double between 0 and the sum.
double random = RandDoubleUpTo(sum_of_weights_);
// Figure out what it belongs to.
return GetValueFor(random);
}
double RandomSelector::RandDoubleUpTo(double max) {
CHECK_GT(max, 0.0);
return max * base::RandDouble();
}
const std::string& RandomSelector::GetValueFor(double random) {
double current = 0.0;
for (const auto& odd : odds_) {
current += odd.weight;
if (random < current)
return odd.value;
}
NOTREACHED() << "Invalid value for key: " << random;
return base::EmptyString();
}
// Print the value. Used for friendly test failure messages.
::std::ostream& operator<<(
::std::ostream& os, const RandomSelector::WeightAndValue& value) {
return os << "{" << value.weight << ", \"" << value.value << "\"}";
}
| [
"lixiaodonglove7@aliyun.com"
] | lixiaodonglove7@aliyun.com |
22b663f748445f414a6efd12e7bbd6917b423b23 | ce4005ce4e91cc59733a52e908cba935eb11582e | /plugins/producer_api_plugin/producer_api_plugin.cpp | 40ff117692a1f0e1d9de5a5dccaf1d8caea88b4c | [
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | Arielce/dio | a4322e0e47d9aa2bea36ac29a290290fdac8d0d3 | eb8035664f605783f86b41d34006aeb9ef861f13 | refs/heads/master | 2020-04-03T11:35:24.038809 | 2018-10-29T14:37:57 | 2018-10-29T14:37:57 | 155,226,338 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,664 | cpp | /**
* @file
* @copyright defined in dcc/LICENSE.txt
*/
#include <dccio/producer_api_plugin/producer_api_plugin.hpp>
#include <dccio/chain/exceptions.hpp>
#include <fc/variant.hpp>
#include <fc/io/json.hpp>
#include <chrono>
namespace dccio { namespace detail {
struct producer_api_plugin_response {
std::string result;
};
}}
FC_REFLECT(dccio::detail::producer_api_plugin_response, (result));
namespace dccio {
static appbase::abstract_plugin& _producer_api_plugin = app().register_plugin<producer_api_plugin>();
using namespace dccio;
#define CALL(api_name, api_handle, call_name, INVOKE, http_response_code) \
{std::string("/v1/" #api_name "/" #call_name), \
[&api_handle](string, string body, url_response_callback cb) mutable { \
try { \
if (body.empty()) body = "{}"; \
INVOKE \
cb(http_response_code, fc::json::to_string(result)); \
} catch (...) { \
http_plugin::handle_exception(#api_name, #call_name, body, cb); \
} \
}}
#define INVOKE_R_R(api_handle, call_name, in_param) \
auto result = api_handle.call_name(fc::json::from_string(body).as<in_param>());
#define INVOKE_R_R_R_R(api_handle, call_name, in_param0, in_param1, in_param2) \
const auto& vs = fc::json::json::from_string(body).as<fc::variants>(); \
auto result = api_handle.call_name(vs.at(0).as<in_param0>(), vs.at(1).as<in_param1>(), vs.at(2).as<in_param2>());
#define INVOKE_R_V(api_handle, call_name) \
auto result = api_handle.call_name();
#define INVOKE_V_R(api_handle, call_name, in_param) \
api_handle.call_name(fc::json::from_string(body).as<in_param>()); \
dccio::detail::producer_api_plugin_response result{"ok"};
#define INVOKE_V_R_R(api_handle, call_name, in_param0, in_param1) \
const auto& vs = fc::json::json::from_string(body).as<fc::variants>(); \
api_handle.call_name(vs.at(0).as<in_param0>(), vs.at(1).as<in_param1>()); \
dccio::detail::producer_api_plugin_response result{"ok"};
#define INVOKE_V_V(api_handle, call_name) \
api_handle.call_name(); \
dccio::detail::producer_api_plugin_response result{"ok"};
void producer_api_plugin::plugin_startup() {
ilog("starting producer_api_plugin");
// lifetime of plugin is lifetime of application
auto& producer = app().get_plugin<producer_plugin>();
app().get_plugin<http_plugin>().add_api({
CALL(producer, producer, pause,
INVOKE_V_V(producer, pause), 201),
CALL(producer, producer, resume,
INVOKE_V_V(producer, resume), 201),
CALL(producer, producer, paused,
INVOKE_R_V(producer, paused), 201),
CALL(producer, producer, get_runtime_options,
INVOKE_R_V(producer, get_runtime_options), 201),
CALL(producer, producer, update_runtime_options,
INVOKE_V_R(producer, update_runtime_options, producer_plugin::runtime_options), 201),
CALL(producer, producer, add_greylist_accounts,
INVOKE_V_R(producer, add_greylist_accounts, producer_plugin::greylist_params), 201),
CALL(producer, producer, remove_greylist_accounts,
INVOKE_V_R(producer, remove_greylist_accounts, producer_plugin::greylist_params), 201),
CALL(producer, producer, get_greylist,
INVOKE_R_V(producer, get_greylist), 201),
CALL(producer, producer, get_whitelist_blacklist,
INVOKE_R_V(producer, get_whitelist_blacklist), 201),
CALL(producer, producer, set_whitelist_blacklist,
INVOKE_V_R(producer, set_whitelist_blacklist, producer_plugin::whitelist_blacklist), 201),
CALL(producer, producer, get_integrity_hash,
INVOKE_R_V(producer, get_integrity_hash), 201),
CALL(producer, producer, create_snapshot,
INVOKE_R_V(producer, create_snapshot), 201),
});
}
void producer_api_plugin::plugin_initialize(const variables_map& options) {
try {
const auto& _http_plugin = app().get_plugin<http_plugin>();
if( !_http_plugin.is_on_loopback()) {
wlog( "\n"
"**********SECURITY WARNING**********\n"
"* *\n"
"* -- Producer API -- *\n"
"* - EXPOSED to the LOCAL NETWORK - *\n"
"* - USE ONLY ON SECURE NETWORKS! - *\n"
"* *\n"
"************************************\n" );
}
} FC_LOG_AND_RETHROW()
}
#undef INVOKE_R_R
#undef INVOKE_R_R_R_R
#undef INVOKE_R_V
#undef INVOKE_V_R
#undef INVOKE_V_R_R
#undef INVOKE_V_V
#undef CALL
}
| [
"13821402840@139.com"
] | 13821402840@139.com |
cd62a975bb56eda2922d12240251aa36b6acb93e | 85381529f7a09d11b2e2491671c2d5e965467ac6 | /OJ/Leetcode/Algorithm/22. Generate Parentheses.cpp | 26f5adf042e54b54344de7744d9e90a34228c8f8 | [] | no_license | Mr-Phoebe/ACM-ICPC | 862a06666d9db622a8eded7607be5eec1b1a4055 | baf6b1b7ce3ad1592208377a13f8153a8b942e91 | refs/heads/master | 2023-04-07T03:46:03.631407 | 2023-03-19T03:41:05 | 2023-03-19T03:41:05 | 46,262,661 | 19 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 632 | cpp | class Solution {
public:
vector<string> generateParenthesis(int n) {
string cur = "";
vector<string> ans;
dfs(cur, ans, 0, 0, n);
return ans;
}
private:
void dfs(string& cur, vector<string>& ans, int left, int right, const int n)
{
if(right == n)
{
ans.push_back(cur);
return;
}
if(left > right)
{
string tmp = cur + ")";
dfs(tmp, ans, left, right+1, n);
}
if(left < n)
{
string tmp = cur + "(";
dfs(tmp, ans, left+1, right, n);
}
}
};
| [
"whn289467822@outlook.com"
] | whn289467822@outlook.com |
5816fbf6b8c3a135cdd6b7f61858f20a83dc2f74 | 32cbda50e1b511538a655f02a6c6ca231c85ff84 | /code/agse_rosmod_project/01-Software-Configuration/agse/src/agse_package/src/agse_package/camera_main.cpp | 0e7c0280b4a5a9930d9e75ba5c4377c05c857f7c | [] | no_license | finger563/agse2015 | 6534de59ef2c3ec0897ca95f622f57f31aea5600 | 1f80092666879d38787b6d7f25857ac2d618fb9d | refs/heads/master | 2021-01-15T17:42:14.490061 | 2018-05-03T14:34:51 | 2018-05-03T14:34:51 | 25,938,897 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 874 | cpp | #include "ros/ros.h"
#include <cstdlib>
// Required for boost::thread
#include <boost/thread.hpp>
// Include all components this actor requires
#include "agse_package/image_processor.hpp"
void componentThread(Component* compPtr)
{
compPtr->startUp();
compPtr->processQueue();
}
int main(int argc, char **argv)
{
std::string nodeName = "camera";
ros::init(argc, argv, nodeName.c_str());
// Create Node Handle
ros::NodeHandle n;
// Create Component Objects
image_processor image_processor_i;
// Create Component Threads
boost::thread image_processor_i_thread(componentThread, &image_processor_i);
ROS_INFO("Node camera has started image_processor_i");
ROS_INFO_STREAM("NodeMain thread id = " << boost::this_thread::get_id());
// Create Component Threads
image_processor_i_thread.join();
return 0;
}
| [
"emfinger@isis.vanderbilt.edu"
] | emfinger@isis.vanderbilt.edu |
3a792740fee929a89ae11b2507320ff13a2d1f2c | bc050379a219ee7e92c3652ed9952724f02f737a | /qtci11/watcher.h | 80ce5ad7fca7826602d7869fe75a76b60f3b3e7f | [] | no_license | galliume/Qt5Core | 6ebe5fefeb4b3356e5d9bd7bca0e0d55b9f904e3 | c29f07cbc314965169fc6fad9fa456ecdf06b1fe | refs/heads/main | 2023-03-29T16:02:49.550452 | 2021-04-14T16:58:01 | 2021-04-14T16:58:01 | 355,606,400 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 357 | h | #ifndef WATCHER_H
#define WATCHER_H
#include <QObject>
#include <QDebug>
#include <QDir>
#include <QFileSystemWatcher>
class watcher : public QObject
{
Q_OBJECT
public:
watcher();
public slots:
void fileChanged(const QString &path);
void directoryChanged(const QString &path);
private:
QFileSystemWatcher fsw;
};
#endif // WATCHER_H
| [
"gcconantc@gmail.com"
] | gcconantc@gmail.com |
87700499c32db30900de0d82c4f35a71c23e5bc7 | bc10911b97dc92aa044dfdae57f51eb9e96dce89 | /AVWClient/test_clamav.cpp | 5e7124d8f4387077c66b0213bf7c655d3018a774 | [
"MIT"
] | permissive | Sr173/AVWClient | 46c34ee93ce824209d8d17a307d8b06d60d08e33 | 478e1c29b7b0c059d2171c01ad96fffd035c7c9d | refs/heads/master | 2020-05-14T14:03:37.126432 | 2019-08-09T14:56:03 | 2019-08-09T14:56:03 | 181,824,831 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 504 | cpp | #include "../thrty_party/ClamAV/libclamav/clamav.h"
#include "iostream"
int mainchawefdsfwer()
{
cl_initialize_crypto();
std::cout << "init:" << cl_init(1) << std::endl;
auto engine = cl_engine_new();
unsigned int a = 0;
//std::cout << cl_load("C:\\Users\\admin\\Personal\\lib\\clamav\\cvd\\daily.mdb", engine, &a, CL_DB_STDOPT) << std::endl;
std::cout << cl_load("C:\\Users\\admin\\Personal\\lib\\clamav\\cvd\\daily.ldb", engine, &a, CL_DB_STDOPT) << std::endl;
system("pause");
return 1;
} | [
"66456804@qq.com"
] | 66456804@qq.com |
5a00e1d56241da8c8c06bf3c99217b6c900b99ad | 636d052f2a7182dc14a0d743b87db071f4477e78 | /src/qt/transactiontablemodel.cpp | 7e4e69b8bbf71a679bb12d72c138fae9f62cdb01 | [
"MIT"
] | permissive | smartinsider/cryptoyen | 8f20a664225f82d4250f8a2eeb29e34625195278 | b51677403c7e308bbc0319cb0904466ed4c43e71 | refs/heads/master | 2021-06-16T08:13:36.427008 | 2021-04-04T20:29:40 | 2021-04-04T20:29:40 | 339,136,171 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,716 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2016 The Dash developers
// Copyright (c) 2018-2021 @smartinsider
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "transactiontablemodel.h"
#include "addresstablemodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "transactiondesc.h"
#include "transactionrecord.h"
#include "walletmodel.h"
#include "main.h"
#include "sync.h"
#include "uint256.h"
#include "util.h"
#include "wallet.h"
#include <QColor>
#include <QDateTime>
#include <QDebug>
#include <QIcon>
#include <QList>
// Amount column is right-aligned it contains numbers
static int column_alignments[] = {
Qt::AlignLeft | Qt::AlignVCenter, /* status */
Qt::AlignLeft | Qt::AlignVCenter, /* watchonly */
Qt::AlignLeft | Qt::AlignVCenter, /* date */
Qt::AlignLeft | Qt::AlignVCenter, /* type */
Qt::AlignLeft | Qt::AlignVCenter, /* address */
Qt::AlignRight | Qt::AlignVCenter /* amount */
};
// Comparison operator for sort/binary search of model tx list
struct TxLessThan {
bool operator()(const TransactionRecord& a, const TransactionRecord& b) const
{
return a.hash < b.hash;
}
bool operator()(const TransactionRecord& a, const uint256& b) const
{
return a.hash < b;
}
bool operator()(const uint256& a, const TransactionRecord& b) const
{
return a < b.hash;
}
};
// Private implementation
class TransactionTablePriv
{
public:
TransactionTablePriv(CWallet* wallet, TransactionTableModel* parent) : wallet(wallet),
parent(parent)
{
}
CWallet* wallet;
TransactionTableModel* parent;
/* Local cache of wallet.
* As it is in the same order as the CWallet, by definition
* this is sorted by sha256.
*/
QList<TransactionRecord> cachedWallet;
/* Query entire wallet anew from core.
*/
void refreshWallet()
{
qDebug() << "TransactionTablePriv::refreshWallet";
cachedWallet.clear();
{
LOCK2(cs_main, wallet->cs_wallet);
for (std::map<uint256, CWalletTx>::iterator it = wallet->mapWallet.begin(); it != wallet->mapWallet.end(); ++it) {
if (TransactionRecord::showTransaction(it->second))
cachedWallet.append(TransactionRecord::decomposeTransaction(wallet, it->second));
}
}
}
/* Update our model of the wallet incrementally, to synchronize our model of the wallet
with that of the core.
Call with transaction that was added, removed or changed.
*/
void updateWallet(const uint256& hash, int status, bool showTransaction)
{
qDebug() << "TransactionTablePriv::updateWallet : " + QString::fromStdString(hash.ToString()) + " " + QString::number(status);
// Find bounds of this transaction in model
QList<TransactionRecord>::iterator lower = qLowerBound(
cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
QList<TransactionRecord>::iterator upper = qUpperBound(
cachedWallet.begin(), cachedWallet.end(), hash, TxLessThan());
int lowerIndex = (lower - cachedWallet.begin());
int upperIndex = (upper - cachedWallet.begin());
bool inModel = (lower != upper);
if (status == CT_UPDATED) {
if (showTransaction && !inModel)
status = CT_NEW; /* Not in model, but want to show, treat as new */
if (!showTransaction && inModel)
status = CT_DELETED; /* In model, but want to hide, treat as deleted */
}
qDebug() << " inModel=" + QString::number(inModel) +
" Index=" + QString::number(lowerIndex) + "-" + QString::number(upperIndex) +
" showTransaction=" + QString::number(showTransaction) + " derivedStatus=" + QString::number(status);
switch (status) {
case CT_NEW:
if (inModel) {
qWarning() << "TransactionTablePriv::updateWallet : Warning: Got CT_NEW, but transaction is already in model";
break;
}
if (showTransaction) {
LOCK2(cs_main, wallet->cs_wallet);
// Find transaction in wallet
std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash);
if (mi == wallet->mapWallet.end()) {
qWarning() << "TransactionTablePriv::updateWallet : Warning: Got CT_NEW, but transaction is not in wallet";
break;
}
// Added -- insert at the right position
QList<TransactionRecord> toInsert =
TransactionRecord::decomposeTransaction(wallet, mi->second);
if (!toInsert.isEmpty()) /* only if something to insert */
{
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex + toInsert.size() - 1);
int insert_idx = lowerIndex;
foreach (const TransactionRecord& rec, toInsert) {
cachedWallet.insert(insert_idx, rec);
insert_idx += 1;
}
parent->endInsertRows();
}
}
break;
case CT_DELETED:
if (!inModel) {
qWarning() << "TransactionTablePriv::updateWallet : Warning: Got CT_DELETED, but transaction is not in model";
break;
}
// Removed -- remove entire transaction from table
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex - 1);
cachedWallet.erase(lower, upper);
parent->endRemoveRows();
break;
case CT_UPDATED:
// Miscellaneous updates -- nothing to do, status update will take care of this, and is only computed for
// visible transactions.
break;
}
}
int size()
{
return cachedWallet.size();
}
TransactionRecord* index(int idx)
{
if (idx >= 0 && idx < cachedWallet.size()) {
TransactionRecord* rec = &cachedWallet[idx];
// Get required locks upfront. This avoids the GUI from getting
// stuck if the core is holding the locks for a longer time - for
// example, during a wallet rescan.
//
// If a status update is needed (blocks came in since last check),
// update the status of this transaction from the wallet. Otherwise,
// simply re-use the cached status.
TRY_LOCK(cs_main, lockMain);
if (lockMain) {
TRY_LOCK(wallet->cs_wallet, lockWallet);
if (lockWallet && rec->statusUpdateNeeded()) {
std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash);
if (mi != wallet->mapWallet.end()) {
rec->updateStatus(mi->second);
}
}
}
return rec;
}
return 0;
}
QString describe(TransactionRecord* rec, int unit)
{
{
LOCK2(cs_main, wallet->cs_wallet);
std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(rec->hash);
if (mi != wallet->mapWallet.end()) {
return TransactionDesc::toHTML(wallet, mi->second, rec, unit);
}
}
return QString();
}
};
TransactionTableModel::TransactionTableModel(CWallet* wallet, WalletModel* parent) : QAbstractTableModel(parent),
wallet(wallet),
walletModel(parent),
priv(new TransactionTablePriv(wallet, this)),
fProcessingQueuedTransactions(false)
{
columns << QString() << QString() << tr("Date") << tr("Type") << tr("Address") << BitcoinUnits::getAmountColumnTitle(walletModel->getOptionsModel()->getDisplayUnit());
priv->refreshWallet();
connect(walletModel->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
subscribeToCoreSignals();
}
TransactionTableModel::~TransactionTableModel()
{
unsubscribeFromCoreSignals();
delete priv;
}
/** Updates the column title to "Amount (DisplayUnit)" and emits headerDataChanged() signal for table headers to react. */
void TransactionTableModel::updateAmountColumnTitle()
{
columns[Amount] = BitcoinUnits::getAmountColumnTitle(walletModel->getOptionsModel()->getDisplayUnit());
emit headerDataChanged(Qt::Horizontal, Amount, Amount);
}
void TransactionTableModel::updateTransaction(const QString& hash, int status, bool showTransaction)
{
uint256 updated;
updated.SetHex(hash.toStdString());
priv->updateWallet(updated, status, showTransaction);
}
void TransactionTableModel::updateConfirmations()
{
// Blocks came in since last poll.
// Invalidate status (number of confirmations) and (possibly) description
// for all rows. Qt is smart enough to only actually request the data for the
// visible rows.
emit dataChanged(index(0, Status), index(priv->size() - 1, Status));
emit dataChanged(index(0, ToAddress), index(priv->size() - 1, ToAddress));
}
int TransactionTableModel::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int TransactionTableModel::columnCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QString TransactionTableModel::formatTxStatus(const TransactionRecord* wtx) const
{
QString status;
switch (wtx->status.status) {
case TransactionStatus::OpenUntilBlock:
status = tr("Open for %n more block(s)", "", wtx->status.open_for);
break;
case TransactionStatus::OpenUntilDate:
status = tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx->status.open_for));
break;
case TransactionStatus::Offline:
status = tr("Offline");
break;
case TransactionStatus::Unconfirmed:
status = tr("Unconfirmed");
break;
case TransactionStatus::Confirming:
status = tr("Confirming (%1 of %2 recommended confirmations)").arg(wtx->status.depth).arg(TransactionRecord::RecommendedNumConfirmations);
break;
case TransactionStatus::Confirmed:
status = tr("Confirmed (%1 confirmations)").arg(wtx->status.depth);
break;
case TransactionStatus::Conflicted:
status = tr("Conflicted");
break;
case TransactionStatus::Immature:
status = tr("Immature (%1 confirmations, will be available after %2)").arg(wtx->status.depth).arg(wtx->status.depth + wtx->status.matures_in);
break;
case TransactionStatus::MaturesWarning:
status = tr("This block was not received by any other nodes and will probably not be accepted!");
break;
case TransactionStatus::NotAccepted:
status = tr("Orphan Block - Generated but not accepted. This does not impact your holdings.");
break;
}
return status;
}
QString TransactionTableModel::formatTxDate(const TransactionRecord* wtx) const
{
if (wtx->time) {
return GUIUtil::dateTimeStr(wtx->time);
}
return QString();
}
/* Look up address in address book, if found return label (address)
otherwise just return (address)
*/
QString TransactionTableModel::lookupAddress(const std::string& address, bool tooltip) const
{
QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(address));
QString description;
if (!label.isEmpty()) {
description += label;
}
if (label.isEmpty() || tooltip) {
description += QString(" (") + QString::fromStdString(address) + QString(")");
}
return description;
}
QString TransactionTableModel::formatTxType(const TransactionRecord* wtx) const
{
switch (wtx->type) {
case TransactionRecord::RecvWithAddress:
return tr("Received with");
case TransactionRecord::MNReward:
return tr("Masternode Reward");
case TransactionRecord::RecvFromOther:
return tr("Received from");
case TransactionRecord::RecvWithObfuscation:
return tr("Received via Obfuscation");
case TransactionRecord::SendToAddress:
case TransactionRecord::SendToOther:
return tr("Sent to");
case TransactionRecord::SendToSelf:
return tr("Payment to yourself");
case TransactionRecord::StakeMint:
return tr("YEN Stake");
//case TransactionRecord::YouTube:
// return tr("YouTube Mining");
default:
return QString();
}
}
QVariant TransactionTableModel::txAddressDecoration(const TransactionRecord* wtx) const
{
switch (wtx->type) {
case TransactionRecord::Generated:
case TransactionRecord::StakeMint:
//case TransactionRecord::YouTube:
case TransactionRecord::MNReward:
return QIcon(":/icons/tx_mined");
case TransactionRecord::RecvWithObfuscation:
case TransactionRecord::RecvWithAddress:
case TransactionRecord::RecvFromOther:
return QIcon(":/icons/tx_input");
case TransactionRecord::SendToAddress:
case TransactionRecord::SendToOther:
return QIcon(":/icons/tx_output");
default:
return QIcon(":/icons/tx_inout");
}
}
QString TransactionTableModel::formatTxToAddress(const TransactionRecord* wtx, bool tooltip) const
{
QString watchAddress;
if (tooltip) {
// Mark transactions involving watch-only addresses by adding " (watch-only)"
watchAddress = wtx->involvesWatchAddress ? QString(" (") + tr("watch-only") + QString(")") : "";
}
switch (wtx->type) {
case TransactionRecord::RecvFromOther:
return QString::fromStdString(wtx->address) + watchAddress;
case TransactionRecord::RecvWithAddress:
case TransactionRecord::MNReward:
case TransactionRecord::RecvWithObfuscation:
case TransactionRecord::SendToAddress:
case TransactionRecord::Generated:
case TransactionRecord::StakeMint:
//case TransactionRecord::YouTube:
// return lookupAddress(wtx->address, tooltip);
case TransactionRecord::Obfuscated:
return lookupAddress(wtx->address, tooltip) + watchAddress;
case TransactionRecord::SendToOther:
return QString::fromStdString(wtx->address) + watchAddress;
case TransactionRecord::SendToSelf:
default:
return tr("(n/a)") + watchAddress;
}
}
QVariant TransactionTableModel::addressColor(const TransactionRecord* wtx) const
{
switch (wtx->type) {
case TransactionRecord::SendToSelf:
// Show addresses without label in a less visible color
case TransactionRecord::RecvWithAddress:
case TransactionRecord::SendToAddress:
case TransactionRecord::Generated:
case TransactionRecord::MNReward: {
QString label = walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(wtx->address));
if (label.isEmpty())
return COLOR_BAREADDRESS;
}
default:
// To avoid overriding above conditional formats a default text color for this QTableView is not defined in stylesheet,
// so we must always return a color here
return COLOR_BLACK;
}
}
QString TransactionTableModel::formatTxAmount(const TransactionRecord* wtx, bool showUnconfirmed, BitcoinUnits::SeparatorStyle separators) const
{
QString str = BitcoinUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), wtx->credit + wtx->debit, false, separators);
if (showUnconfirmed) {
if (!wtx->status.countsForBalance) {
str = QString("[") + str + QString("]");
}
}
return QString(str);
}
QVariant TransactionTableModel::txStatusDecoration(const TransactionRecord* wtx) const
{
switch (wtx->status.status) {
case TransactionStatus::OpenUntilBlock:
case TransactionStatus::OpenUntilDate:
return COLOR_TX_STATUS_OPENUNTILDATE;
case TransactionStatus::Offline:
return COLOR_TX_STATUS_OFFLINE;
case TransactionStatus::Unconfirmed:
return QIcon(":/icons/transaction_0");
case TransactionStatus::Confirming:
switch (wtx->status.depth) {
case 1:
return QIcon(":/icons/transaction_1");
case 2:
return QIcon(":/icons/transaction_2");
case 3:
return QIcon(":/icons/transaction_3");
case 4:
return QIcon(":/icons/transaction_4");
default:
return QIcon(":/icons/transaction_5");
};
case TransactionStatus::Confirmed:
return QIcon(":/icons/transaction_confirmed");
case TransactionStatus::Conflicted:
return QIcon(":/icons/transaction_conflicted");
case TransactionStatus::Immature: {
int total = wtx->status.depth + wtx->status.matures_in;
int part = (wtx->status.depth * 5 / total) + 1;
return QIcon(QString(":/icons/transaction_%1").arg(part));
}
case TransactionStatus::MaturesWarning:
case TransactionStatus::NotAccepted:
return QIcon(":/icons/transaction_0");
default:
return COLOR_BLACK;
}
}
QVariant TransactionTableModel::txWatchonlyDecoration(const TransactionRecord* wtx) const
{
if (wtx->involvesWatchAddress)
return QIcon(":/icons/eye");
else
return QVariant();
}
QString TransactionTableModel::formatTooltip(const TransactionRecord* rec) const
{
QString tooltip = formatTxStatus(rec) + QString("\n") + formatTxType(rec);
if (rec->type == TransactionRecord::RecvFromOther || rec->type == TransactionRecord::SendToOther ||
rec->type == TransactionRecord::SendToAddress || rec->type == TransactionRecord::RecvWithAddress || rec->type == TransactionRecord::MNReward) {
tooltip += QString(" ") + formatTxToAddress(rec, true);
}
return tooltip;
}
QVariant TransactionTableModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
TransactionRecord* rec = static_cast<TransactionRecord*>(index.internalPointer());
switch (role) {
case Qt::DecorationRole:
switch (index.column()) {
case Status:
return txStatusDecoration(rec);
case Watchonly:
return txWatchonlyDecoration(rec);
case ToAddress:
return txAddressDecoration(rec);
}
break;
case Qt::DisplayRole:
switch (index.column()) {
case Date:
return formatTxDate(rec);
case Type:
return formatTxType(rec);
case ToAddress:
return formatTxToAddress(rec, false);
case Amount:
return formatTxAmount(rec, true, BitcoinUnits::separatorAlways);
}
break;
case Qt::EditRole:
// Edit role is used for sorting, so return the unformatted values
switch (index.column()) {
case Status:
return QString::fromStdString(rec->status.sortKey);
case Date:
return rec->time;
case Type:
return formatTxType(rec);
case Watchonly:
return (rec->involvesWatchAddress ? 1 : 0);
case ToAddress:
return formatTxToAddress(rec, true);
case Amount:
return qint64(rec->credit + rec->debit);
}
break;
case Qt::ToolTipRole:
return formatTooltip(rec);
case Qt::TextAlignmentRole:
return column_alignments[index.column()];
case Qt::ForegroundRole:
// Minted
if (rec->type == TransactionRecord::Generated || rec->type == TransactionRecord::StakeMint ||
rec->type == TransactionRecord::StakeZYEN || rec->type == TransactionRecord::MNReward) {
if (rec->status.status == TransactionStatus::Conflicted || rec->status.status == TransactionStatus::NotAccepted)
return COLOR_ORPHAN;
else
return COLOR_STAKE;
}
// Conflicted tx
if (rec->status.status == TransactionStatus::Conflicted || rec->status.status == TransactionStatus::NotAccepted) {
return COLOR_CONFLICTED;
}
// Unconfimed or immature
if ((rec->status.status == TransactionStatus::Unconfirmed) || (rec->status.status == TransactionStatus::Immature)) {
return COLOR_UNCONFIRMED;
}
if (index.column() == Amount && (rec->credit + rec->debit) < 0) {
return COLOR_NEGATIVE;
}
if (index.column() == ToAddress) {
return addressColor(rec);
}
// To avoid overriding above conditional formats a default text color for this QTableView is not defined in stylesheet,
// so we must always return a color here
return COLOR_BLACK;
case TypeRole:
return rec->type;
case DateRole:
return QDateTime::fromTime_t(static_cast<uint>(rec->time));
case WatchonlyRole:
return rec->involvesWatchAddress;
case WatchonlyDecorationRole:
return txWatchonlyDecoration(rec);
case LongDescriptionRole:
return priv->describe(rec, walletModel->getOptionsModel()->getDisplayUnit());
case AddressRole:
return QString::fromStdString(rec->address);
case LabelRole:
return walletModel->getAddressTableModel()->labelForAddress(QString::fromStdString(rec->address));
case AmountRole:
return qint64(rec->credit + rec->debit);
case TxIDRole:
return rec->getTxID();
case TxHashRole:
return QString::fromStdString(rec->hash.ToString());
case ConfirmedRole:
return rec->status.countsForBalance;
case FormattedAmountRole:
// Used for copy/export, so don't include separators
return formatTxAmount(rec, false, BitcoinUnits::separatorNever);
case StatusRole:
return rec->status.status;
}
return QVariant();
}
QVariant TransactionTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal) {
if (role == Qt::DisplayRole) {
return columns[section];
} else if (role == Qt::TextAlignmentRole) {
return column_alignments[section];
} else if (role == Qt::ToolTipRole) {
switch (section) {
case Status:
return tr("Transaction status. Hover over this field to show number of confirmations.");
case Date:
return tr("Date and time that the transaction was received.");
case Type:
return tr("Type of transaction.");
case Watchonly:
return tr("Whether or not a watch-only address is involved in this transaction.");
case ToAddress:
return tr("Destination address of transaction.");
case Amount:
return tr("Amount removed from or added to balance.");
}
}
}
return QVariant();
}
QModelIndex TransactionTableModel::index(int row, int column, const QModelIndex& parent) const
{
Q_UNUSED(parent);
TransactionRecord* data = priv->index(row);
if (data) {
return createIndex(row, column, priv->index(row));
}
return QModelIndex();
}
void TransactionTableModel::updateDisplayUnit()
{
// emit dataChanged to update Amount column with the current unit
updateAmountColumnTitle();
emit dataChanged(index(0, Amount), index(priv->size() - 1, Amount));
}
// queue notifications to show a non freezing progress dialog e.g. for rescan
struct TransactionNotification {
public:
TransactionNotification() {}
TransactionNotification(uint256 hash, ChangeType status, bool showTransaction) : hash(hash), status(status), showTransaction(showTransaction) {}
void invoke(QObject* ttm)
{
QString strHash = QString::fromStdString(hash.GetHex());
qDebug() << "NotifyTransactionChanged : " + strHash + " status= " + QString::number(status);
QMetaObject::invokeMethod(ttm, "updateTransaction", Qt::QueuedConnection,
Q_ARG(QString, strHash),
Q_ARG(int, status),
Q_ARG(bool, showTransaction));
}
private:
uint256 hash;
ChangeType status;
bool showTransaction;
};
static bool fQueueNotifications = false;
static std::vector<TransactionNotification> vQueueNotifications;
static void NotifyTransactionChanged(TransactionTableModel* ttm, CWallet* wallet, const uint256& hash, ChangeType status)
{
// Find transaction in wallet
std::map<uint256, CWalletTx>::iterator mi = wallet->mapWallet.find(hash);
// Determine whether to show transaction or not (determine this here so that no relocking is needed in GUI thread)
bool inWallet = mi != wallet->mapWallet.end();
bool showTransaction = (inWallet && TransactionRecord::showTransaction(mi->second));
TransactionNotification notification(hash, status, showTransaction);
if (fQueueNotifications) {
vQueueNotifications.push_back(notification);
return;
}
notification.invoke(ttm);
}
static void ShowProgress(TransactionTableModel* ttm, const std::string& title, int nProgress)
{
if (nProgress == 0)
fQueueNotifications = true;
if (nProgress == 100) {
fQueueNotifications = false;
if (vQueueNotifications.size() > 10) // prevent balloon spam, show maximum 10 balloons
QMetaObject::invokeMethod(ttm, "setProcessingQueuedTransactions", Qt::QueuedConnection, Q_ARG(bool, true));
for (unsigned int i = 0; i < vQueueNotifications.size(); ++i) {
if (vQueueNotifications.size() - i <= 10)
QMetaObject::invokeMethod(ttm, "setProcessingQueuedTransactions", Qt::QueuedConnection, Q_ARG(bool, false));
vQueueNotifications[i].invoke(ttm);
}
std::vector<TransactionNotification>().swap(vQueueNotifications); // clear
}
}
void TransactionTableModel::subscribeToCoreSignals()
{
// Connect signals to wallet
wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
wallet->ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
}
void TransactionTableModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from wallet
wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
wallet->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
}
| [
"reyner.info@gmail.com"
] | reyner.info@gmail.com |
0a8b73a4151bf30ab08a1fe2c88f3e6d3baccf2b | 38c10c01007624cd2056884f25e0d6ab85442194 | /third_party/WebKit/Source/bindings/core/v8/ScriptPromiseResolver.cpp | 3dcb2f1cba1c04f901a9ef9ef24b8eee0874bebd | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft"
] | 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 | 2,529 | cpp | // Copyright 2014 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 "config.h"
#include "bindings/core/v8/ScriptPromiseResolver.h"
namespace blink {
ScriptPromiseResolver::ScriptPromiseResolver(ScriptState* scriptState)
: ActiveDOMObject(scriptState->executionContext())
, m_state(Pending)
, m_scriptState(scriptState)
, m_timer(this, &ScriptPromiseResolver::onTimerFired)
, m_resolver(scriptState)
#if ENABLE(ASSERT)
, m_isPromiseCalled(false)
#endif
{
if (executionContext()->activeDOMObjectsAreStopped()) {
m_state = ResolvedOrRejected;
m_resolver.clear();
}
}
void ScriptPromiseResolver::suspend()
{
m_timer.stop();
}
void ScriptPromiseResolver::resume()
{
if (m_state == Resolving || m_state == Rejecting)
m_timer.startOneShot(0, BLINK_FROM_HERE);
}
void ScriptPromiseResolver::stop()
{
m_timer.stop();
clear();
}
void ScriptPromiseResolver::keepAliveWhilePending()
{
// keepAliveWhilePending() will be called twice if the resolver
// is created in a suspended execution context and the resolver
// is then resolved/rejected while in that suspended state.
if (m_state == ResolvedOrRejected || m_keepAlive)
return;
// Keep |this| around while the promise is Pending;
// see clear() for the dual operation.
m_keepAlive = this;
}
void ScriptPromiseResolver::onTimerFired(Timer<ScriptPromiseResolver>*)
{
ASSERT(m_state == Resolving || m_state == Rejecting);
if (!scriptState()->contextIsValid()) {
clear();
return;
}
ScriptState::Scope scope(m_scriptState.get());
resolveOrRejectImmediately();
}
void ScriptPromiseResolver::resolveOrRejectImmediately()
{
ASSERT(!executionContext()->activeDOMObjectsAreStopped());
ASSERT(!executionContext()->activeDOMObjectsAreSuspended());
{
if (m_state == Resolving) {
m_resolver.resolve(m_value.newLocal(m_scriptState->isolate()));
} else {
ASSERT(m_state == Rejecting);
m_resolver.reject(m_value.newLocal(m_scriptState->isolate()));
}
}
clear();
}
void ScriptPromiseResolver::clear()
{
if (m_state == ResolvedOrRejected)
return;
m_state = ResolvedOrRejected;
m_resolver.clear();
m_value.clear();
m_keepAlive.clear();
}
DEFINE_TRACE(ScriptPromiseResolver)
{
ActiveDOMObject::trace(visitor);
}
} // namespace blink
| [
"zeno.albisser@hemispherian.com"
] | zeno.albisser@hemispherian.com |
3366bd78a73e5dd06266bc60668606b56f1b4ee6 | 87247dd40e2e3a7dc866a184f45cc009e2723e61 | /TBTest/TAbstractThreadLocal.h | 2655f82b0a8b116badfd8e5e0ffc6fa3fab5decb | [] | no_license | pbujak/treebase-codename | 600d46c6251522241a3774a7bfb375f4e1cd7bd7 | fc1c108aa6b989109936241400bb9f09960202ba | refs/heads/master | 2018-12-27T23:15:34.990546 | 2015-01-06T20:34:22 | 2015-01-06T20:34:22 | 27,611,651 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,865 | h | // TAbstractThreadLocal.h: interface for the TAbstractThreadLocal class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(_THREAD_LOCAL_BASE_H_)
#define _THREAD_LOCAL_BASE_H_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <afxtempl.h>
class TAbstractThreadLocal
{
static TAbstractThreadLocal *S_pFirst;
static long S_nSizeTotal;
static long S_tlsIndex;
protected:
TAbstractThreadLocal *m_pNext;
long m_nOffset;
private:
TAbstractThreadLocal(){};
public:
void* GetData();
TAbstractThreadLocal(long a_nSize);
virtual ~TAbstractThreadLocal();
static void ClearAllData();
protected:
virtual void InitData(void *a_pvData)=0;
virtual void ClearData(void *a_pvData)=0;
};
template<class T>
class TThreadLocal: public TAbstractThreadLocal
{
T* GetItem()
{
void *pvData = GetData();
T* pData = (T*)((BYTE*)pvData + m_nOffset);
return pData;
}
public:
TThreadLocal(): TAbstractThreadLocal(sizeof(T))
{
}
operator T&()
{
T* pData = GetItem();
return *pData;
}
T& Value()
{
T* pData = GetItem();
return *pData;
}
T* operator&()
{
T* pData = GetItem();
return pData;
}
T& operator=(T &a_src)
{
T* pData = GetItem();
*pData = a_src;
return *this;
}
protected:
virtual void InitData(void *a_pvData)
{
T* pData = (T*)((BYTE*)a_pvData + m_nOffset);
new(pData) T();
};
virtual void ClearData(void *a_pvData)
{
T* pData = (T*)((BYTE*)a_pvData + m_nOffset);
pData->~T();
};
};
#endif // !defined(_THREAD_LOCAL_BASE_H_)
| [
"pawelbu.code@gmail.com@185dbd00-4dec-8738-eca1-b2e70f345e0e"
] | pawelbu.code@gmail.com@185dbd00-4dec-8738-eca1-b2e70f345e0e |
f54e798975caf268845aee4566747ba30abaf342 | 8042163dbac5ddf47f078b4d14f4eb6fe1da030d | /tensorflow/compiler/mlir/tensorflow/ir/tf_side_effects.h | 9be61b1db39566d7c8b2b0af49e76ca1b4977937 | [
"Apache-2.0"
] | permissive | AITutorials/tensorflow | 4513de8db4e9bb74b784f5ba865ef8a573b9efc1 | 6bee0d45f8228f2498f53bd6dec0a691f53b3c7b | refs/heads/master | 2022-07-29T13:37:23.749388 | 2020-06-11T17:47:26 | 2020-06-11T17:57:06 | 271,615,051 | 3 | 0 | Apache-2.0 | 2020-06-11T18:07:11 | 2020-06-11T18:07:10 | null | UTF-8 | C++ | false | false | 1,502 | h | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This is the side effect definition file for TensorFlow.
#ifndef TENSORFLOW_COMPILER_MLIR_TENSORFLOW_IR_TF_SIDE_EFFECTS_H_
#define TENSORFLOW_COMPILER_MLIR_TENSORFLOW_IR_TF_SIDE_EFFECTS_H_
#include "mlir/Interfaces/SideEffectInterfaces.h" // from @llvm-project
namespace mlir {
namespace TF {
namespace ResourceEffects {
struct Variable : ::mlir::SideEffects::Resource::Base<Variable> {
StringRef getName() final { return "Variable"; }
};
struct Stack : ::mlir::SideEffects::Resource::Base<Stack> {
StringRef getName() final { return "Stack"; }
};
struct TensorArray : ::mlir::SideEffects::Resource::Base<TensorArray> {
StringRef getName() final { return "TensorArray"; }
};
} // namespace ResourceEffects
} // namespace TF
} // namespace mlir
#endif // TENSORFLOW_COMPILER_MLIR_TENSORFLOW_IR_TF_SIDE_EFFECTS_H_
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
5a0d7c06c79ee8255fe034ccac2b7253e009f55a | 3c2757761f14c4c3396d0094c84ec681fa6bc0c8 | /CryptCube/PublicKeyECC.cpp | 65172a34b83a3677f515fe53e9960a8b6697eaa4 | [] | no_license | Albert-x/CryptCube | 55d3ae0073626309e4ae396878c7e10997ca3799 | afe0a608a29d86463045244e12c3f889240dc37b | refs/heads/master | 2021-01-11T07:36:29.595503 | 2016-01-10T06:28:08 | 2016-01-10T06:28:08 | 48,937,771 | 4 | 3 | null | null | null | null | WINDOWS-1256 | C++ | false | false | 2,598 | cpp | #include "stdafx.h"
#include <stdio.h>
#include <memory.h>
#include <string.h>
#include <iostream>
using namespace std;
#include "PublicKeyECC.h"
#include <math.h>
#define random(min,max) (rand()%(max+1-min)+min)
long ECC::invmod(long a,long b)
{
long s0=1,s1=0,s2,q,t,b0;
b0=b;
while(b)
{
q=a/b;
s2=s0-q*s1;
if(s2>=0)
s2=s2%b0;
else
s2=b0-(-s2)%b0;
s0=s1;
s1=s2;
t=b;
b=a%b;
a=t;
}
if(1==a)
return s0;
else if(-1==a)
return b0-s0;
else
return 0;
}
point ECC::add(point p1,point p2,long a,long b,long p)
{
point p3;
long x1,x2,x3,y1,y2,y3,m;
x1=p1.x;
y1=p1.y;
x2=p2.x;
y2=p2.y;
if( x1==x2 && y1==-y2 )
{
p3.x=inf;
p3.y=inf;
return p3;
}
if( p1.x==inf && p1.y==inf )
return p2;
if( p2.x==inf && p2.y==inf )
return p1;
if( x2!=x1)
m=((y2-y1)*invmod(x2-x1,p))%p;
else
m=((3*x1*x1+a)%p*invmod(2*y1,p))%p;
if(m<0)
m=m+p;
x3=(m*m-x1-x2)%p;
y3=(m*(x1-x3)-y1)%p;
if(x3<0)
x3+=p;
if(y3<0)
y3+=p;
p3.x=x3;
p3.y=y3;
return p3;
}
point ECC::subtract(point p1,point p2,long a,long b,long p)
{
point p3;
p2.y = -p2.y;
p3=add(p1,p2,a,b,p);
return p3;
}
point ECC::multipy(point p,long m,long a,long b,long n)
{
point q;
q.x=inf;
q.y=inf;
while(m)
{
if(m%2)
q=add(q,p,a,b,n);
p=add(p,p,a,b,n);
m=m>>1;
}
return q;
}
int ECC::testprime(long n)
{
long i,j,s,t,a,y;
srand((unsigned)time(NULL));
if(n%2==0) return 0;
s=0;
t=n-1;
while(t%2==0)
{
t=t/2;
s++;
}
for(i=0;i<10;i++)
{
a=random(2,n-2);
y=powmod(a,t,n);
if(y!=1&&y!=n-1)
{
j=1;
while(j<s && y!=n-1)
{
y=(y*y)%n;
if(1==y) return 0;
j++;
}
if(y!=n-1) return 0;
}
}
return 1;
}
long ECC::powmod(long a, long b, long m)
{
long A=1;
while(b!=0)
{
if(b%2) A=(A*a)%m;
a=(a*a)%m;
b=b>>1;
}
return A;
}
long ECC::SquareRoot(long x,long p)
{
long s,t,y,x_inv,n,b;
s=p-1;
t=0;
n=0;
while(s%2==0)
{
s=s/2;
t++;
}
while(powmod(n,(p-1)/2,p)==1)
n++;
b=powmod(n,s,p);
y=powmod(x,(s+1)/2,p);
x_inv=invmod(x,p);
while(t-2>=0)
{
if(powmod(x_inv*y*y,(long)pow((long double)2,t-2),p)==p-1)
y=y*(long)pow((long double)b,pow((long double)2,t-2));
t--;
}
return y;
}
long ECC::modNUm(long b3,long a3)
{
long q,a1,a2,b1,b2,t1,t2,t3,m;
m=a3;
a1=b2=1;
a2=b1=0;
long result;
while(1)
{
if(0==b3)
{
//SetDlgItemText(IDC_RESULT2,"²»´وشع،£");
return 0;
}
if(1==b3)
{
if(b2<0)
b2+=m;
result=b2;
//cout<<result;
return result;
}
q=a3/b3;
t1=a1-q*b1,t2=a2-q*b2,t3=a3-q*b3;
a1=b1,a2=b2,a3=b3;
b1=t1,b2=t2,b3=t3;
}
} | [
"albert-hu@outlook.com"
] | albert-hu@outlook.com |
efd26f49d002b816bf9c3b6fa40b5751d2254674 | cfb746d9bd4dbbe814a10b0061766667117cf624 | /include/mpx/algorithm/cached-value.hh | 2f93bc14a60d100f4b7b2cea77da95f278803caf | [] | no_license | mderezynski/Youki2 | d37310ac9f132f994940d774cc03fc490527cf41 | 547b4b84e8a0a476bee49278a26dca9b10266ca6 | refs/heads/master | 2020-05-18T14:16:39.142415 | 2012-08-20T19:33:29 | 2012-08-20T19:33:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 606 | hh | #ifndef MPX_ALGO__CACHED_VALUE
#define MPX_ALGO__CACHED_VALUE
#include <boost/optional.hpp>
#include <sigc++/sigc++.h>
namespace MPX
{
template <typename T>
class CachedValue
{
protected:
boost::optional<T> mValue ;
public:
typedef sigc::slot<T> GetSlot ;
protected:
GetSlot mSlot ;
public:
CachedValue() = delete ;
CachedValue(const GetSlot& slot)
{
mSlot = slot ;
}
const& T
get()
{
if(!mValue)
update() ;
return mValue ;
}
void
update()
{
mValue = mSlot() ;
}
} ;
}
#endif
| [
"mderezynski@gmail.com"
] | mderezynski@gmail.com |
1c857a92c743af0b38457336186544acd56d360a | 303e592c312459bf9eb3ce231b1357c4de91124b | /pku/2624/2624.cpp | 2865645a9d00e3682ee20939b1e33ab87f160a33 | [] | no_license | kohyatoh/contests | 866c60a1687f8a59d440da3356c6117f9596e8ce | b3dffeaf15564d57aec5c306f5f84bd448bc791f | refs/heads/master | 2021-01-17T15:06:23.216232 | 2016-07-18T14:06:05 | 2016-07-18T14:06:05 | 2,369,261 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 431 | cpp | #include <stdio.h>
#define rep(i, n) for(int i=0; i<(int)(n); i++)
double x[4], y[4];
int main() {
while(scanf("%lf%lf", x, y)!=EOF) {
rep(i, 3) scanf("%lf%lf", x+i+1, y+i+1);
double sx=0, sy=0;
rep(i, 4) sx+=x[i], sy+=y[i];
rep(i, 4) rep(j, i) if(x[i]==x[j] && y[i]==y[j]) {
printf("%.3f %.3f\n", sx-3*x[i], sy-3*y[i]);
goto fin;
}
fin:;
}
return 0;
}
| [
"kohyatoh@yahoo.co.jp"
] | kohyatoh@yahoo.co.jp |
ea12599187ed46965a7c623fdcf0c152e2fa5ac4 | 2947ee1ced6044abfcdfc700510da97bc5527268 | /LeetCode 151.cpp | a4154a3cb931071659723c0abb956377caf6f247 | [] | no_license | ytWu1314/LeetCode_summer_holiday | 1a54ffbbc457c236777ffa28563d2a56314c6e33 | 4a860fa6227bdf3ed5638b0915faecd6a295b5fc | refs/heads/master | 2023-07-16T03:58:03.099682 | 2021-08-28T15:13:50 | 2021-08-28T15:13:50 | 389,531,832 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 579 | cpp | class Solution {
public:
string reverseWords(string s) {
int k=0;
for(int i=0;i<s.size();i++)
{
if(s[i]==' ') continue;
int j=i,t=k; //双指针算法 i和j t和k
while(j<s.size()&&s[j]!=' ') s[t++]=s[j++];
reverse(s.begin()+k,s.begin()+t);
s[t++]=' ';
i=j,k=t;
}
if(k) k--; //去掉最后一个单词添加的空格
s.erase(s.begin()+k,s.end()); //去掉多余的空格
reverse(s.begin(),s.end());
return s;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
b1bf87934c18f51bac38ff341799ace872214430 | dc4df933902fc292235ecc97605f63d9f7145ee1 | /14-Scope/Solution.cpp | 0fcc7383f8b22558532c3acd32fdacd25bba987a | [] | no_license | LegendaryKim/Hackerrank_30_Days_of_Code | 49eb9bd88bc071a33dc85f203f5e69744bf8e792 | 7e8a738f97ebeef56835a8278a9dd7b60a053f96 | refs/heads/master | 2021-05-06T13:33:37.714750 | 2017-12-11T23:56:46 | 2017-12-11T23:56:46 | 113,234,200 | 0 | 0 | null | 2017-12-11T23:56:47 | 2017-12-05T21:19:19 | C++ | UTF-8 | C++ | false | false | 1,054 | cpp | #include <cmath>
#include <vector>
#include <iostream>
using namespace std;
class Differenc {
private:
vector<int> elements;
public:
int maximumDifference;
// Add your code here
Difference(vector<int> elements) {
this->elements = elements;
}
void computeDifference() {
int maximum = 0;
for (int i = 0; i < this->elements.size(); i++) {
for (int j = i; j < this->elements.size(); j++) {
int absolute = abs(elements[i] - elements[j]);
if (absolute > maximum) {
maximum = absolute;
}
}
}
maximumDifference = maximum;
}
}; // End of Difference class
int main() {
int N;
cin >> N;
vector<int> a;
for (int i = 0; i < N; i++) {
int e; cin >> e;
a.push_back(e);
}
Difference d(a);
d.computeDifference();
cout << d.maximumDifference;
return 0;
}
| [
"khwanpy1@jhu.edu"
] | khwanpy1@jhu.edu |
f2fa1b659cb112d8c5cd4913180caf3ecbf1d614 | 9da42e04bdaebdf0193a78749a80c4e7bf76a6cc | /third_party/gecko-2/win32/include/nsIDOMXPathResult.h | db277545a8177d80b6e4b03aa3411c93fad82be7 | [
"Apache-2.0"
] | permissive | bwp/SeleniumWebDriver | 9d49e6069881845e9c23fb5211a7e1b8959e2dcf | 58221fbe59fcbbde9d9a033a95d45d576b422747 | refs/heads/master | 2021-01-22T21:32:50.541163 | 2012-11-09T16:19:48 | 2012-11-09T16:19:48 | 6,602,097 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,372 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-2.0-xr-w32-bld/build/dom/interfaces/xpath/nsIDOMXPathResult.idl
*/
#ifndef __gen_nsIDOMXPathResult_h__
#define __gen_nsIDOMXPathResult_h__
#ifndef __gen_domstubs_h__
#include "domstubs.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class XPathException; /* forward declaration */
/* starting interface: nsIDOMXPathResult */
#define NS_IDOMXPATHRESULT_IID_STR "75506f84-b504-11d5-a7f2-ca108ab8b6fc"
#define NS_IDOMXPATHRESULT_IID \
{0x75506f84, 0xb504, 0x11d5, \
{ 0xa7, 0xf2, 0xca, 0x10, 0x8a, 0xb8, 0xb6, 0xfc }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMXPathResult : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMXPATHRESULT_IID)
enum { ANY_TYPE = 0U };
enum { NUMBER_TYPE = 1U };
enum { STRING_TYPE = 2U };
enum { BOOLEAN_TYPE = 3U };
enum { UNORDERED_NODE_ITERATOR_TYPE = 4U };
enum { ORDERED_NODE_ITERATOR_TYPE = 5U };
enum { UNORDERED_NODE_SNAPSHOT_TYPE = 6U };
enum { ORDERED_NODE_SNAPSHOT_TYPE = 7U };
enum { ANY_UNORDERED_NODE_TYPE = 8U };
enum { FIRST_ORDERED_NODE_TYPE = 9U };
/* readonly attribute unsigned short resultType; */
NS_SCRIPTABLE NS_IMETHOD GetResultType(PRUint16 *aResultType) = 0;
/* readonly attribute double numberValue; */
NS_SCRIPTABLE NS_IMETHOD GetNumberValue(double *aNumberValue) = 0;
/* readonly attribute DOMString stringValue; */
NS_SCRIPTABLE NS_IMETHOD GetStringValue(nsAString & aStringValue) = 0;
/* readonly attribute boolean booleanValue; */
NS_SCRIPTABLE NS_IMETHOD GetBooleanValue(PRBool *aBooleanValue) = 0;
/* readonly attribute nsIDOMNode singleNodeValue; */
NS_SCRIPTABLE NS_IMETHOD GetSingleNodeValue(nsIDOMNode **aSingleNodeValue) = 0;
/* readonly attribute boolean invalidIteratorState; */
NS_SCRIPTABLE NS_IMETHOD GetInvalidIteratorState(PRBool *aInvalidIteratorState) = 0;
/* readonly attribute unsigned long snapshotLength; */
NS_SCRIPTABLE NS_IMETHOD GetSnapshotLength(PRUint32 *aSnapshotLength) = 0;
/* nsIDOMNode iterateNext () raises (XPathException, DOMException); */
NS_SCRIPTABLE NS_IMETHOD IterateNext(nsIDOMNode **_retval NS_OUTPARAM) = 0;
/* nsIDOMNode snapshotItem (in unsigned long index) raises (XPathException); */
NS_SCRIPTABLE NS_IMETHOD SnapshotItem(PRUint32 index, nsIDOMNode **_retval NS_OUTPARAM) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMXPathResult, NS_IDOMXPATHRESULT_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMXPATHRESULT \
NS_SCRIPTABLE NS_IMETHOD GetResultType(PRUint16 *aResultType); \
NS_SCRIPTABLE NS_IMETHOD GetNumberValue(double *aNumberValue); \
NS_SCRIPTABLE NS_IMETHOD GetStringValue(nsAString & aStringValue); \
NS_SCRIPTABLE NS_IMETHOD GetBooleanValue(PRBool *aBooleanValue); \
NS_SCRIPTABLE NS_IMETHOD GetSingleNodeValue(nsIDOMNode **aSingleNodeValue); \
NS_SCRIPTABLE NS_IMETHOD GetInvalidIteratorState(PRBool *aInvalidIteratorState); \
NS_SCRIPTABLE NS_IMETHOD GetSnapshotLength(PRUint32 *aSnapshotLength); \
NS_SCRIPTABLE NS_IMETHOD IterateNext(nsIDOMNode **_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD SnapshotItem(PRUint32 index, nsIDOMNode **_retval NS_OUTPARAM);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMXPATHRESULT(_to) \
NS_SCRIPTABLE NS_IMETHOD GetResultType(PRUint16 *aResultType) { return _to GetResultType(aResultType); } \
NS_SCRIPTABLE NS_IMETHOD GetNumberValue(double *aNumberValue) { return _to GetNumberValue(aNumberValue); } \
NS_SCRIPTABLE NS_IMETHOD GetStringValue(nsAString & aStringValue) { return _to GetStringValue(aStringValue); } \
NS_SCRIPTABLE NS_IMETHOD GetBooleanValue(PRBool *aBooleanValue) { return _to GetBooleanValue(aBooleanValue); } \
NS_SCRIPTABLE NS_IMETHOD GetSingleNodeValue(nsIDOMNode **aSingleNodeValue) { return _to GetSingleNodeValue(aSingleNodeValue); } \
NS_SCRIPTABLE NS_IMETHOD GetInvalidIteratorState(PRBool *aInvalidIteratorState) { return _to GetInvalidIteratorState(aInvalidIteratorState); } \
NS_SCRIPTABLE NS_IMETHOD GetSnapshotLength(PRUint32 *aSnapshotLength) { return _to GetSnapshotLength(aSnapshotLength); } \
NS_SCRIPTABLE NS_IMETHOD IterateNext(nsIDOMNode **_retval NS_OUTPARAM) { return _to IterateNext(_retval); } \
NS_SCRIPTABLE NS_IMETHOD SnapshotItem(PRUint32 index, nsIDOMNode **_retval NS_OUTPARAM) { return _to SnapshotItem(index, _retval); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMXPATHRESULT(_to) \
NS_SCRIPTABLE NS_IMETHOD GetResultType(PRUint16 *aResultType) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetResultType(aResultType); } \
NS_SCRIPTABLE NS_IMETHOD GetNumberValue(double *aNumberValue) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNumberValue(aNumberValue); } \
NS_SCRIPTABLE NS_IMETHOD GetStringValue(nsAString & aStringValue) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetStringValue(aStringValue); } \
NS_SCRIPTABLE NS_IMETHOD GetBooleanValue(PRBool *aBooleanValue) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetBooleanValue(aBooleanValue); } \
NS_SCRIPTABLE NS_IMETHOD GetSingleNodeValue(nsIDOMNode **aSingleNodeValue) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSingleNodeValue(aSingleNodeValue); } \
NS_SCRIPTABLE NS_IMETHOD GetInvalidIteratorState(PRBool *aInvalidIteratorState) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetInvalidIteratorState(aInvalidIteratorState); } \
NS_SCRIPTABLE NS_IMETHOD GetSnapshotLength(PRUint32 *aSnapshotLength) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSnapshotLength(aSnapshotLength); } \
NS_SCRIPTABLE NS_IMETHOD IterateNext(nsIDOMNode **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->IterateNext(_retval); } \
NS_SCRIPTABLE NS_IMETHOD SnapshotItem(PRUint32 index, nsIDOMNode **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->SnapshotItem(index, _retval); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsDOMXPathResult : public nsIDOMXPathResult
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIDOMXPATHRESULT
nsDOMXPathResult();
private:
~nsDOMXPathResult();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMXPathResult, nsIDOMXPathResult)
nsDOMXPathResult::nsDOMXPathResult()
{
/* member initializers and constructor code */
}
nsDOMXPathResult::~nsDOMXPathResult()
{
/* destructor code */
}
/* readonly attribute unsigned short resultType; */
NS_IMETHODIMP nsDOMXPathResult::GetResultType(PRUint16 *aResultType)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute double numberValue; */
NS_IMETHODIMP nsDOMXPathResult::GetNumberValue(double *aNumberValue)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute DOMString stringValue; */
NS_IMETHODIMP nsDOMXPathResult::GetStringValue(nsAString & aStringValue)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute boolean booleanValue; */
NS_IMETHODIMP nsDOMXPathResult::GetBooleanValue(PRBool *aBooleanValue)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute nsIDOMNode singleNodeValue; */
NS_IMETHODIMP nsDOMXPathResult::GetSingleNodeValue(nsIDOMNode **aSingleNodeValue)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute boolean invalidIteratorState; */
NS_IMETHODIMP nsDOMXPathResult::GetInvalidIteratorState(PRBool *aInvalidIteratorState)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute unsigned long snapshotLength; */
NS_IMETHODIMP nsDOMXPathResult::GetSnapshotLength(PRUint32 *aSnapshotLength)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIDOMNode iterateNext () raises (XPathException, DOMException); */
NS_IMETHODIMP nsDOMXPathResult::IterateNext(nsIDOMNode **_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIDOMNode snapshotItem (in unsigned long index) raises (XPathException); */
NS_IMETHODIMP nsDOMXPathResult::SnapshotItem(PRUint32 index, nsIDOMNode **_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIDOMXPathResult_h__ */
| [
"haleokekahuna@gmail.com"
] | haleokekahuna@gmail.com |
159c933fb1f495ab9641ed42ca338a20cbe404e1 | f8b0f2b54e314099bd2071a08dfcd5a2355d2181 | /src/src/Utilities/Random/PerlinNoise.cpp | c6bc0a31482fee3ed914a4151ffab68df765bf7e | [] | no_license | Taylor-Fowler/TDF-Engine | e643825d19df2a801b4ca4e2dbe7c0ea1c43ea9f | a8006aeb0dba1ef7f3c3766d30105a56ebb0b108 | refs/heads/master | 2021-04-12T08:01:47.554829 | 2018-04-23T10:46:19 | 2018-04-23T10:46:19 | 126,081,664 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,858 | cpp | #include "PerlinNoise.h"
#include <cmath>
//https://github.com/TheThinMatrix/LowPolyTerrain/blob/master/src/generation/PerlinNoise.java
int PerlinNoise::permutation[] = { 151,160,137,91,90,15,
131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180 };
PerlinNoise::PerlinNoise()
{
for (int i = 0; i < 256; i++) p[256 + i] = p[i] = permutation[i];
}
float PerlinNoise::cnoise(glm::vec2 P)
{
glm::vec4 Pi = floor(glm::vec4(P.x, P.y, P.x, P.y)) + glm::vec4(0.0, 0.0, 1.0, 1.0);
glm::vec4 Pf = fract(glm::vec4(P.x, P.y, P.x, P.y)) - glm::vec4(0.0, 0.0, 1.0, 1.0);
Pi = mod289(Pi); // To avoid truncation effects in permutation
glm::vec4 ix = glm::vec4(Pi.x, Pi.z, Pi.x, Pi.z);
glm::vec4 iy = glm::vec4(Pi.y, Pi.y, Pi.w, Pi.w);
glm::vec4 fx = glm::vec4(Pf.x, Pf.z, Pf.x, Pf.z);
glm::vec4 fy = glm::vec4(Pf.y, Pf.y, Pf.w, Pf.w);
glm::vec4 i = permute(permute(ix) + iy);
glm::vec4 gx = fract(i * (1.0f / 41.0f)) * 2.0f - 1.0f;
glm::vec4 gy = abs(gx) - 0.5f;
glm::vec4 tx = floor(gx + 0.5f);
gx = gx - tx;
glm::vec2 g00 = glm::vec2(gx.x, gy.x);
glm::vec2 g10 = glm::vec2(gx.y, gy.y);
glm::vec2 g01 = glm::vec2(gx.z, gy.z);
glm::vec2 g11 = glm::vec2(gx.w, gy.w);
glm::vec4 norm = taylorInvSqrt(glm::vec4(dot(g00, g00), dot(g01, g01), dot(g10, g10), dot(g11, g11)));
g00 *= norm.x;
g01 *= norm.y;
g10 *= norm.z;
g11 *= norm.w;
float n00 = dot(g00, glm::vec2(fx.x, fy.x));
float n10 = dot(g10, glm::vec2(fx.y, fy.y));
float n01 = dot(g01, glm::vec2(fx.z, fy.z));
float n11 = dot(g11, glm::vec2(fx.w, fy.w));
glm::vec2 fade_xy = fade(glm::vec2(Pf.x, Pf.y));
glm::vec2 n_x = mix(glm::vec2(n00, n01), glm::vec2(n10, n11), fade_xy.x);
float n_xy = lerp(fade_xy.y, n_x.x, n_x.y);
return 2.3 * n_xy;
}
double PerlinNoise::GetNoise2D(double x, double y)
{
int X = (int)floor(x) & 255;
int Y = (int)floor(y) & 255;
// Find relative x, y, z of point in cube
x -= floor(x);
y -= floor(y);
// Compute fade curves for each of x, y, z
double u = fade(x);
double v = fade(y);
// X, Y and Z always range from 0 to 255
// The p array has values ranging from 0 to 255
// A and B will always result in a value between 0 and 510
// AA, AB, BA and BB will result in a value between 0 and 510
// Any two given x, y, z positions that are in the same unit cube, will result in the same hash co-ordinates
// Hash coordinates of the 4 cube corners
int A = p[X + p[Y]];
int AB = p[X + p[Y + 1]];
int B = p[X + 1 + p[Y]];
int BB = p[X + 1 + p[Y + 1]];
double resA = lerp(u, GetGradient(p[A], x, y - 1), GetGradient(p[AB], x, y));
double resB = lerp(u, GetGradient(p[B], x - 1, y - 1), GetGradient(p[BB], x - 1, y));
double res = lerp(v, resA, resB);
return (res + 1.0) * 0.5;
}
double PerlinNoise::GetNoise3D(double x, double y, double z)
{
// Imagine there is a grid of cubes, 256 cubes wide (x), 256 cubes tall (y), and 256 cubes deep (z)
// The cube at the origin is located at 0, 0, 0
// The cube at the farthest point point from the origin is located at 255, 255, 255
// Given any x, y, z value, we have to find which cube in our grid that point is located in
// At this point in time
// Find the unit cube that contains the point
int X = (int)floor(x) & 255;
int Y = (int)floor(y) & 255;
int Z = (int)floor(z) & 255;
// Find relative x, y, z of point in cube
x -= floor(x);
y -= floor(y);
z -= floor(z);
// Compute fade curves for each of x, y, z
double u = fade(x);
double v = fade(y);
double w = fade(z);
// X, Y and Z always range from 0 to 255
// The p array has values ranging from 0 to 255
// A and B will always result in a value between 0 and 510
// AA, AB, BA and BB will result in a value between 0 and 510
// Any two given x, y, z positions that are in the same unit cube, will result in the same hash co-ordinates
// Hash coordinates of the 8 cube corners
int A = p[X] + Y;
int AA = p[A] + Z;
int AB = p[A + 1] + Z;
int B = p[X + 1] + Y;
int BA = p[B] + Z;
int BB = p[B + 1] + Z;
//double // Add blended results from 8 corners of cube
double res = lerp(w, lerp(v, lerp(u, GetGradient(p[AA], x, y, z), GetGradient(p[BA], x - 1, y, z)),
lerp(u, GetGradient(p[AB], x, y - 1, z), GetGradient(p[BB], x - 1, y - 1, z))),
lerp(v, lerp(u, GetGradient(p[AA + 1], x, y, z - 1), GetGradient(p[BA + 1], x - 1, y, z - 1)),
lerp(u, GetGradient(p[AB + 1], x, y - 1, z - 1), GetGradient(p[BB + 1], x - 1, y - 1, z - 1))));
return (res + 1.0) * 0.5;
}
double PerlinNoise::OctaveNoise2D(double x, double y, int octaves, double persistence)
{
double total = 0;
double ampl = persistence;
double max = 0;
double freq = 1;
for (int i = 0; i < octaves; i++)
{
total += GetNoise2D(x * freq, y * freq) * ampl;
freq *= 2;
max += ampl;
ampl *= persistence;
}
return total / max;
}
// Octaves create a more natural perlin noise result
double PerlinNoise::OctaveNoise3D(double x, double y, double z, int octaves, double persistence)
{
double noise, frequency, amplitude, maxNoise;
// Amplitude refers to the scalar co-effecient of each noise iteration
// Frequency = 2 ^ iteration
amplitude = frequency = 1.0;
// No iterations have passed, the max noise cannot have a value
noise = maxNoise = 0.0;
for (int i = 0; i < octaves; ++i)
{
noise += GetNoise3D(x * frequency, y * frequency, z * frequency) * amplitude;
maxNoise += amplitude;
amplitude *= persistence;
frequency *= 2;
}
// Normalise the result
return noise / maxNoise;
}
// Get Gradient returns the dot product between a random gradient vector (of unit length)
// and the vector representing the x, y, z point in the unit cube
// NOTE: This function is biased towards 4 gradients because it is faster
// to do hash & 15 than hash % 11 (as there should only be 12 gradient vectors)
// Source: http://riven8192.blogspot.com/2010/08/calculate-perlinnoise-twice-as-fast.html
double PerlinNoise::GetGradient(int hash, double x, double y, double z)
{
// Convert lower 4 bits of hash into 12 gradient directions
switch (hash & 0xF)
{
case 0x0: return x + y;
case 0x1: return -x + y;
case 0x2: return x - y;
case 0x3: return -x - y;
case 0x4: return x + z;
case 0x5: return -x + z;
case 0x6: return x - z;
case 0x7: return -x - z;
case 0x8: return y + z;
case 0x9: return -y + z;
case 0xA: return y - z;
case 0xB: return -y - z;
case 0xC: return y + x;
case 0xD: return -y + z;
case 0xE: return y - x;
case 0xF: return -y - z;
default: return 0;
}
}
double PerlinNoise::GetGradient(int hash, double x, double y)
{
switch (hash & 0xF)
{
case 0x0: return x + y;
case 0x1: return -x + y;
case 0x2: return x - y;
case 0x3: return -x - y;
case 0x4: return x + y;
case 0x5: return -x + y;
case 0x6: return x - y;
case 0x7: return -x - y;
case 0x8: return x + y;
case 0x9: return -x + y;
case 0xA: return x - y;
case 0xB: return -x - y;
case 0xC: return x + y;
case 0xD: return -x + y;
case 0xE: return x - y;
case 0xF: return -x - y;
}
return 0.0;
}
| [
"Taylor-Fowler@users.noreply.github.com"
] | Taylor-Fowler@users.noreply.github.com |
7a5badfde3e5aae7385b88369b82c9624d606cb0 | 545503a603f15360a78cccccfc778cb47948b4fa | /tests/cpp/tree/test_node_partition.cc | d7254fa60162295df964b886d4ab0a34d81d01a3 | [
"Apache-2.0"
] | permissive | jediyoda36/xgboost | 8211a6cbbe06d7ed14858a5e1ba38add3b820cd1 | a58055075b5fa7c432a3c0a2a177ffecb6889b9f | refs/heads/master | 2023-04-03T15:49:58.338168 | 2023-03-29T19:16:18 | 2023-03-29T19:16:18 | 218,066,629 | 1 | 0 | Apache-2.0 | 2019-10-28T14:32:18 | 2019-10-28T14:32:18 | null | UTF-8 | C++ | false | false | 852 | cc | /**
* Copyright 2023 by XGBoost contributors
*/
#include <gtest/gtest.h>
#include <xgboost/context.h> // for Context
#include <xgboost/task.h> // for ObjInfo
#include <xgboost/tree_updater.h> // for TreeUpdater
#include <memory> // for unique_ptr
namespace xgboost {
TEST(Updater, HasNodePosition) {
Context ctx;
ObjInfo task{ObjInfo::kRegression, true, true};
std::unique_ptr<TreeUpdater> up{TreeUpdater::Create("grow_histmaker", &ctx, &task)};
ASSERT_TRUE(up->HasNodePosition());
up.reset(TreeUpdater::Create("grow_quantile_histmaker", &ctx, &task));
ASSERT_TRUE(up->HasNodePosition());
#if defined(XGBOOST_USE_CUDA)
ctx.gpu_id = 0;
up.reset(TreeUpdater::Create("grow_gpu_hist", &ctx, &task));
ASSERT_TRUE(up->HasNodePosition());
#endif // defined(XGBOOST_USE_CUDA)
}
} // namespace xgboost
| [
"noreply@github.com"
] | noreply@github.com |
3d18a98a0c5ed143dfdfdfc11d475652de5001e0 | 38294b9174cb78eb578856c2054916c4e032afbb | /List/test_list/my_list.cpp | 2257e3f8240481ece0a4d14825a784fdeba663e9 | [] | no_license | bsteve456/ft_containers | 0c954af76152820f6390034c1365e5d3ca217a2a | 5a5db5003136dd033ce1638ebe81705b68b84579 | refs/heads/master | 2023-03-18T17:17:32.077209 | 2021-03-10T16:39:00 | 2021-03-10T16:39:00 | 332,820,281 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,175 | cpp | #include "../list.hpp"
#include "../../Vector/vector.hpp"
#include <vector>
#include <cmath>
#include <string>
#include <cctype>
bool compare_nocase (const std::string& first, const std::string& second)
{
unsigned int i=0;
while ( (i<first.length()) && (i<second.length()) )
{
if (tolower(first[i])<tolower(second[i])) return true;
else if (tolower(first[i])>tolower(second[i])) return false;
++i;
}
return ( first.length() < second.length() );
}
bool single_digit (const int& value) { return (value<10); }
struct is_odd {
bool operator() (const int& value) { return (value%2)==1; }
};
bool same_integral_part (double first, double second)
{ return ( int(first)==int(second) ); }
struct is_near {
bool operator() (double first, double second)
{ return (fabs(first-second)<5.0); }
};
bool mycomparison (double first, double second)
{ return ( int(first)<int(second) ); }
int main()
{
ft::list<int>::iterator ite;
std::cout << "############################" << std::endl;
std::cout << "##### CONSTRUCTOR TEST #####" << std::endl;
std::cout << "############################\n" << std::endl;
ft::list<int> first;
std::cout << "The contents of first are: ";
for (ft::list<int>::iterator it = first.begin(); it != first.end(); it++)
std::cout << ' ' << *it;
std::cout << std::endl;
ft::list<int> second (4,100);
std::cout << "The contents of second are: ";
for (ft::list<int>::iterator it = second.begin(); it != second.end(); it++)
std::cout << ' ' << *it;
std::cout << std::endl;
ft::list<int> third (second.begin(),second.end());
std::cout << "The contents of third are: ";
for (ft::list<int>::iterator it = third.begin(); it != third.end(); it++)
std::cout << ' ' << *it;
std::cout << std::endl;
ft::list<int> fourth (third);
std::cout << "The contents of fourth are: ";
for (ft::list<int>::iterator it = fourth.begin(); it != fourth.end(); it++)
std::cout << ' ' << *it;
std::cout << std::endl;
int myints[] = {16,2,77,29};
ft::list<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );
std::cout << "The contents of fifth are: ";
for (ft::list<int>::iterator it = fifth.begin(); it != fifth.end(); it++)
std::cout << ' ' << *it;
std::cout << std::endl;
std::cout << "\n##############################" << std::endl;
std::cout << "##### OPERATOR = TEST #####" << std::endl;
std::cout << "##############################\n" << std::endl;
ft::list<int> f (3); // list of 3 zero-initialized ints
ft::list<int> s (5); // list of 5 zero-initialized ints
std::cout << "Size of f: " << int (f.size()) << '\n';
std::cout << "Size of s: " << int (s.size()) << '\n';
s = f;
std::cout << "Apply operator = to f and s" << std::endl;
f = ft::list<int>();
std::cout << "Size of f: " << int (f.size()) << '\n';
std::cout << "Size of s: " << int (s.size()) << '\n';
std::cout << "\n###################################" << std::endl;
std::cout << "##### REVERSE ITERATOR TEST #####" << std::endl;
std::cout << "###################################\n" << std::endl;
ft::list<int> mylist;
for (int i=1; i<=6; ++i)
mylist.push_back(i);
std::cout << "The contents of mylist are: ";
for (ft::list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << std::endl;
std::cout << "The reverse contents of mylist are: ";
for (ft::list<int>::reverse_iterator it=mylist.rbegin(); it!=mylist.rend(); ++it)
std::cout << ' ' << *it;
std::cout << std::endl;
const ft::list<int> test = mylist;
std::cout << "The const reverse contents of const mylist(test) are: ";
for (ft::list<int>::const_reverse_iterator it=test.rbegin(); it!=test.rend(); ++it)
std::cout << ' ' << *it;
std::cout << std::endl;
typedef ft::list<int>::iterator iter_type;
ft::MyReverseIterator<iter_type> rev_end (mylist.begin());
ft::MyReverseIterator<iter_type> rev_begin (mylist.end());
std::cout << "The base() contents of mylist in Reverse Iterator are: ";
for (iter_type it = rev_end.base(); it != rev_begin.base(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "\n###########################" << std::endl;
std::cout << "##### MAX SIZE TEST #####" << std::endl;
std::cout << "###########################\n" << std::endl;
std::cout << "Maximum size of a 'list' is " << mylist.max_size() << "\n";
std::cout << "\n#############################" << std::endl;
std::cout << "##### EMPTY SIZE TEST #####" << std::endl;
std::cout << "#############################\n" << std::endl;
mylist.push_front(300);
mylist.push_front(200);
std::cout << "The contents of mylist are: ";
for (ft::list<int>::iterator it = mylist.begin(); it != mylist.end(); it++)
std::cout << ' ' << *it;
std::cout << std::endl;
std::cout << "Popping out the elements in mylist:";
while (!mylist.empty())
{
std::cout << ' ' << mylist.front();
mylist.pop_front();
}
std::cout << "\nFinal size of mylist is " << mylist.size() << '\n';
std::cout << "\n#############################" << std::endl;
std::cout << "####### FRONT BACK TEST ####" << std::endl;
std::cout << "#############################\n" << std::endl;
mylist.push_back(77);
mylist.push_back(22);
mylist.front() -= mylist.back();
std::cout << "mylist.front() is now " << mylist.front() << '\n';
std::cout << "\n#############################" << std::endl;
std::cout << "########## INSERT TEST #####" << std::endl;
std::cout << "#############################\n" << std::endl;
mylist.push_back(3500);
mylist.push_back(100);
std::cout << "The contents of mylist are: ";
for (ft::list<int>::iterator it = mylist.begin(); it != mylist.end(); it++)
std::cout << ' ' << *it;
std::cout << std::endl;
ite = mylist.begin();
++ite;
mylist.insert (ite,10);
std::cout << "The contents of mylist after first insert(one value insert) are: ";
for (ft::list<int>::iterator it = mylist.begin(); it != mylist.end(); it++)
std::cout << ' ' << *it;
std::cout << std::endl;
mylist.insert (ite, 1 , 5);
std::cout << "The contents of mylist after second insert(range insert) are: ";
for (ft::list<int>::iterator it = mylist.begin(); it != mylist.end(); it++)
std::cout << ' ' << *it;
std::cout << std::endl;
mylist.insert (ite, 1 , 7);
std::cout << "The contents of mylist after third insert(range insert) are: ";
for (ft::list<int>::iterator it = mylist.begin(); it != mylist.end(); it++)
std::cout << ' ' << *it;
std::cout << std::endl;
ft::vector<int> myvector (2,30);
mylist.insert (ite,myvector.begin(),myvector.end());
std::cout << "The contents of mylist after fourth insert(vector insert) are: ";
for (ft::list<int>::iterator it = mylist.begin(); it != mylist.end(); it++)
std::cout << ' ' << *it;
std::cout << std::endl;
for (ite=mylist.begin(); ite!=mylist.end(); ++ite)
std::cout << ' ' << *ite;
std::cout << '\n';
std::cout << "\n############################" << std::endl;
std::cout << "##### ERASE SIZE TEST ####" << std::endl;
std::cout << "############################\n" << std::endl;
ft::list<int>::iterator it1, it2;
it1 = mylist.begin();
it2 = mylist.end();
--it2;
it2 = mylist.erase (it2);
std::cout << "The contents of mylist after first erase are: ";
for (ft::list<int>::iterator it = mylist.begin(); it != mylist.end(); it++)
std::cout << ' ' << *it;
std::cout << std::endl;
it1 = mylist.erase (it1);
std::cout << "The contents of mylist after second erase are: ";
for (ft::list<int>::iterator it = mylist.begin(); it != mylist.end(); it++)
std::cout << ' ' << *it;
std::cout << std::endl;
++it1;
--it2;
mylist.erase (it1,it2);
std::cout << "The contents of mylist after third erase(range) are: ";
for (ite=mylist.begin(); ite!=mylist.end(); ite++)
std::cout << ' ' << *ite;
std::cout << '\n';
std::cout << "\n###########################" << std::endl;
std::cout << "##### SWAP SIZE TEST ####" << std::endl;
std::cout << "###########################\n" << std::endl;
ft::list<int> fir (5,200); // five ints with a value of 200
std::cout << "fir contains before swap:";
for (ft::list<int>::iterator it=fir.begin(); it!=fir.end(); it++)
std::cout << ' ' << *it;
std::cout << '\n';
mylist.swap(fir);
std::cout << "mylist contains after swap:";
for (ft::list<int>::iterator it=mylist.begin(); it!=mylist.end(); it++)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "fir contains after swap:";
for (ft::list<int>::iterator it=fir.begin(); it!=fir.end(); it++)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "\n############################" << std::endl;
std::cout << "######### RESIZE TEST #####" << std::endl;
std::cout << "############################\n" << std::endl;
mylist.resize(5);
std::cout << "mylist contains after first resize:";
for (ft::list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
mylist.resize(8,100);
std::cout << "mylist contains after second resize:";
for (ft::list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
mylist.resize(12);
std::cout << "mylist contains after third resize:";
for (ft::list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "\n############################" << std::endl;
std::cout << "######### CLEAR TEST ######" << std::endl;
std::cout << "############################\n" << std::endl;
first.push_back(100);
first.push_back(45);
std::cout << "size of first before clear is " << first.size() << '\n';
first.clear();
std::cout << "size of first after clear is " << first.size() << '\n';
std::cout << "\n############################" << std::endl;
std::cout << "######### SPLICE TEST #####" << std::endl;
std::cout << "############################\n" << std::endl;
for (int i = 1; i <= 4; ++i)
first.push_back(i * 10);
std::cout << "first contains:";
for (ft::list<int>::iterator it=first.begin(); it!=first.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
ite = mylist.begin();
++ite;
std::cout << "mylist contains before splice:";
for (ft::list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
mylist.splice(ite, first);
std::cout << "mylist contains after first splice:";
for (ft::list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
first.splice(first.begin(), mylist, ite);
std::cout << "first contains after second splice:";
for (ft::list<int>::iterator it=first.begin(); it!=first.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
ite = mylist.begin();
ite++;
++ite;
ite++;
mylist.splice (mylist.begin(), mylist, ite, mylist.end());
std::cout << "mylist contains after third splice:";
for (ft::list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "\n############################" << std::endl;
std::cout << "######### REMOVE TEST #####" << std::endl;
std::cout << "############################\n" << std::endl;
mylist.remove(200);
std::cout << "mylist contains after remove:";
for (ft::list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "\n###############################" << std::endl;
std::cout << "######### REMOVE IF TEST #####" << std::endl;
std::cout << "###############################\n" << std::endl;
mylist.push_front(2);
mylist.push_front(9);
mylist.push_front(29);
std::cout << "mylist contains before remove if:";
for (ft::list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
mylist.remove_if (single_digit);
std::cout << "mylist contains after remove if(single digit):";
for (ft::list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
mylist.remove_if (is_odd());
std::cout << "mylist contains after second remove if (is odd):";
for (ft::list<int>::iterator it=mylist.begin(); it!=mylist.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "\n###############################" << std::endl;
std::cout << "######### UNIQUE TEST ########" << std::endl;
std::cout << "###############################\n" << std::endl;
ft::list<double> doubles;
doubles.push_back(15.6);
doubles.push_back(15.6);
doubles.push_back(15.455);
doubles.push_back(17.2);
doubles.push_back(25.6);
doubles.push_back(25.6);
doubles.push_back(200.34);
doubles.push_back(201.5);
std::cout << "doubles contains before unique:";
for (ft::list<double>::iterator it=doubles.begin(); it!=doubles.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
doubles.unique();
std::cout << "doubles contains after unique:";
for (ft::list<double>::iterator it=doubles.begin(); it!=doubles.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
doubles.unique (same_integral_part);
std::cout << "doubles contains after second unique(same integral part):";
for (ft::list<double>::iterator it=doubles.begin(); it!=doubles.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
doubles.unique (is_near());
std::cout << "doubles contains after second unique(is near):";
for (ft::list<double>::iterator it=doubles.begin(); it!=doubles.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "\n###############################" << std::endl;
std::cout << "######### SORT TEST ##########" << std::endl;
std::cout << "###############################\n" << std::endl;
ft::list<std::string> tp;
tp.push_back ("one");
tp.push_back ("two");
tp.push_back ("Three");
std::cout << "tp contains before sort:";
for (ft::list<std::string>::iterator it=tp.begin(); it != tp.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
tp.sort();
std::cout << "tp contains after sort:";
for (ft::list<std::string>::iterator it=tp.begin(); it != tp.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
tp.sort(compare_nocase);
std::cout << "tp contains after sort(compare nocase):";
for (ft::list<std::string>::iterator it=tp.begin(); it != tp.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "\n################################" << std::endl;
std::cout << "######### MERGE TEST ##########" << std::endl;
std::cout << "################################\n" << std::endl;
ft::list<double> five, six;
five.push_back (3.1);
five.push_back (2.2);
five.push_back (2.9);
std::cout << "five contains before :";
for (ft::list<double>::iterator it=five.begin(); it!=five.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
six.push_back (3.7);
six.push_back (7.1);
six.push_back (1.4);
std::cout << "six contains before :";
for (ft::list<double>::iterator it=six.begin(); it!=six.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
five.sort();
std::cout << "sort five" << std::endl;
six.sort();
std::cout << "sort six" << std::endl;
five.merge(six);
std::cout << "five contains after merge with six:";
for (ft::list<double>::iterator it=five.begin(); it!=five.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
six.push_back (2.1);
five.merge(six,mycomparison);
std::cout << "five contains after merge with six + funct compare:";
for (ft::list<double>::iterator it=five.begin(); it!=five.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "\n##################################" << std::endl;
std::cout << "######### REVERSE TEST #########" << std::endl;
std::cout << "##################################\n" << std::endl;
five.reverse();
std::cout << "five contains after reverse:";
for (ft::list<double>::iterator it=five.begin(); it!=five.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "\n#######################################" << std::endl;
std::cout << "######### RELATION OPERATOR TEST #####" << std::endl;
std::cout << "#######################################\n" << std::endl;
ft::list<int> a, b, c;
a.push_back(10);
a.push_back(20);
a.push_back(30);
std::cout << "a contains:";
for (ft::list<int>::iterator it=a.begin(); it!=a.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
b = a;
std::cout << "b contains:";
for (ft::list<int>::iterator it=b.begin(); it!=b.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
c.push_front(10);
c.push_front(20);
c.push_front(30);
std::cout << "c contains:";
for (ft::list<int>::iterator it=c.begin(); it!=c.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
if (a==b) std::cout << "a and b are equal\n";
if (b!=c) std::cout << "b and c are not equal\n";
if (b<c) std::cout << "b is less than c\n";
if (c>b) std::cout << "c is greater than b\n";
if (a<=b) std::cout << "a is less than or equal to b\n";
if (a>=b) std::cout << "a is greater than or equal to b\n";
std::cout << "\n#######################################" << std::endl;
std::cout << "######### SWAP NO MEMBER TEST ########" << std::endl;
std::cout << "#######################################\n" << std::endl;
ft::list<int> foo (3,100); // three ints with a value of 100
ft::list<int> bar (5,200); // five ints with a value of 200
std::cout << "foo contains:";
for (ft::list<int>::iterator it = foo.begin(); it!=foo.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "bar contains:";
for (ft::list<int>::iterator it = bar.begin(); it!=bar.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::swap(foo,bar);
std::cout << "foo contains after swap:";
for (ft::list<int>::iterator it = foo.begin(); it!=foo.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "bar contains after swap:";
for (ft::list<int>::iterator it = bar.begin(); it!=bar.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "\n#######################################" << std::endl;
std::cout << "######### CONST ITERATOR TEST ########" << std::endl;
std::cout << "#######################################\n" << std::endl;
std::cout << "bar contains:";
for (ft::list<int>::const_iterator it = bar.begin(); it!=bar.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "\n###############################" << std::endl;
std::cout << "######### ASSIGN TEST ########" << std::endl;
std::cout << "###############################\n" << std::endl;
foo.assign(4, 45);
std::cout << "foo contains after assign:";
for (ft::list<int>::iterator it = foo.begin(); it!=foo.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
std::cout << "foo contains after assign(bar assign):";
foo.assign(bar.begin(), bar.end());
for (ft::list<int>::iterator it = foo.begin(); it!=foo.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
int myint[]={1776,7,4};
foo.assign (myint,myint+3);
std::cout << "foo contains after assign(array assign):";
for (ft::list<int>::iterator it = foo.begin(); it!=foo.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
}
| [
"stevealan1@protonmail.com"
] | stevealan1@protonmail.com |
82a7abccea258918f0d31eb244ae4832f3d892f1 | ab189df4ab3389184422ffdc8193dc6f4477a646 | /admin/RunSubscriptions.h | c219adb64d6f71db2ef4ebc8338a4d1336a59f8a | [] | no_license | gottafixthat/tacc | cfe10b2db0436afbec528c44cd1b3eeb44117675 | da5bb6393ae02a6b4f99bdb1b05de92b60e722d6 | refs/heads/master | 2021-01-25T04:02:28.248364 | 2015-09-04T22:49:25 | 2015-09-04T22:49:25 | 41,939,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,270 | h | /* Total Accountability Customer Care (TACC)
*
* Written by R. Marc Lewis
* (C)opyright 1997-2009, R. Marc Lewis and Avvatel Corporation
* All Rights Reserved
*
* Unpublished work. No portion of this file may be reproduced in whole
* or in part by any means, electronic or otherwise, without the express
* written consent of Avvatel Corporation and R. Marc Lewis.
*/
#ifndef RunSubscriptions_included
#define RunSubscriptions_included
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <Qt3Support/q3listview.h>
#include <TAAWidget.h>
class RunSubscriptions : public TAAWidget
{
Q_OBJECT
public:
RunSubscriptions(QWidget* parent = NULL, const char* name = NULL);
virtual ~RunSubscriptions();
protected slots:
virtual void cancelAction();
virtual void processSelections();
protected:
Q3ListView *subscrList;
QPushButton *beginButton;
QPushButton *cancelButton;
QLabel *totalSubscriptions;
QLabel *accountsReceivable;
QLabel *amountCharged;
private:
void fillList(void);
int totSubscriptions;
long totActiveLogins;
int ARAcct;
float startingAR;
float totCharged;
};
#endif // RunSubscriptions_included
// vim: expandtab
| [
"marc@innovotel.com"
] | marc@innovotel.com |
9468e9098f30a61d5ce5958acb54ca44bd2256c0 | deae7741fe31d6cb5b8ccb472cb4a7db17fe40e6 | /es2/integral/main.cpp | 7f47e5afe7731798798fe723c9927ad52b02be6f | [] | no_license | AlessandroCermenati/LaboratorioSimulazioneNumerica | f036f4df85911fe94c32f3abdd2b933019beac0f | c31c51f94a3b15616ff86b742736d294d1d22138 | refs/heads/master | 2022-10-20T15:48:06.074463 | 2020-06-29T12:46:01 | 2020-06-29T12:46:01 | 274,658,858 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,351 | cpp | #include "funzionebase.h"
#include "coseno_es2.h"
#include "random.h"
#include "integral.h"
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main(){
ofstream mean; //file di output
mean.open("integral_mean_value.txt");
ofstream sigma;
sigma.open("integral_sigma_mean.txt");
ofstream NUmean;
NUmean.open("non_uniform_integral_mean.txt");
ofstream NUsigma;
NUsigma.open("non_uniform_integral_sigma_mean.txt");
coseno_es2 *F = new coseno_es2(M_PI/2); //costruttori per la funzione da valutare e per il calcolo del suo integrale
integral *I = new integral(0., 1.);
Random *rnd = new Random(); //creo l'oggetto random per produrre i campionamenti della variabile
int seed[4];
int p1, p2;
ifstream Primes("Primes");
if (Primes.is_open()){
Primes >> p1 >> p2 ;
} else cerr << "PROBLEM: Unable to open Primes" << endl;
Primes.close();
ifstream input("seed.in");
string property;
if (input.is_open()){
while ( !input.eof() ){
input >> property;
if( property == "RANDOMSEED" ){
input >> seed[0] >> seed[1] >> seed[2] >> seed[3];
rnd->SetRandom(seed,p1,p2);
}
}
input.close();
} else cerr << "PROBLEM: Unable to open seed.in" << endl;
int hitpoint = 10000; //numero di campionamenti della variabile per valutare l'integrale ad ogni blocco
int N = 100; //numero di blocchi -> il totale dei campionamenti è N*hitpoint
double y[N];
double y2[N];
double sum_prog[N];
double sum2_prog[N];
double devstd[N];
for(int i=0; i<N; i++){
sum_prog[i]=0;
sum2_prog[i]=0;
y[i] = I->integration_MeanValue(F, rnd, hitpoint); //l'array y è riempito con N stime dell'integrale, utilizzando ad ogni stima hitpoint punti
y2[i] = pow(y[i],2);
}
for(int i=0; i<N; i++){ //calcola valor medio e incertezza statistica ad ogni blocco
for(int j=0; j<i+1; j++){
sum_prog[i]= sum_prog[i] + y[j];
sum2_prog[i]= sum2_prog[i] + y2[j];
}
sum_prog[i] = sum_prog[i]/(i+1);
sum2_prog[i] = sum2_prog[i]/(i+1);
if(i==0){
devstd[i] = 0;
}
else{
devstd[i] = sqrt((sum2_prog[i] - pow((sum_prog[i]),2))/i);
}
}
for(int i=0; i<N; i++){
mean<<sum_prog[i]<<endl;
sigma<<devstd[i]<<endl;
}
//RIPETO L'ESERCIZIO PER UN CAMPIONAMENTO NON UNIFORME
for(int i=0; i<N; i++){
sum_prog[i]=0;
sum2_prog[i]=0;
y[i] = I->integration_importance(F, rnd, hitpoint); //l'array y è riempito con N stime dell'integrale, utilizzando ad ogni stima hitpoint punti campionati con importance sampling
y2[i]= pow(y[i],2);
}
for(int i=0; i<N; i++){ //calcola valor medio e incertezza statistica ad ogni blocco
for(int j=0; j<i+1; j++){
sum_prog[i]= sum_prog[i] + y[j];
sum2_prog[i]= sum2_prog[i] + y2[j];
}
sum_prog[i] = sum_prog[i]/(i+1);
sum2_prog[i] = sum2_prog[i]/(i+1);
if(i==0){
devstd[i] = 0;
}
else{
devstd[i] = sqrt((sum2_prog[i] - pow((sum_prog[i]),2))/i);
}
}
for(int i=0; i<N; i++){
NUmean<<sum_prog[i]<<endl;
NUsigma<<devstd[i]<<endl;
}
delete F; //dealloco la memoria
delete I;
delete rnd;
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
98b3df2217486d86d9eeb86efb0d342577ebd376 | 4cf75bd8dd051f278f115ae8fdc2eeafeaeafba9 | /TalonXVI.cpp | dc3d6abd321a5d6b4363979a67297bb009c97cac | [] | no_license | Gaelhawks-Team-230/FRC-team230-2015 | 2d4d3afaa0bd223b794fb0315e8cd5aa45c4874a | c2790c7d4bda585daceb24c5d0200de254432941 | refs/heads/main | 2023-03-07T10:49:10.756344 | 2021-02-22T18:39:24 | 2021-02-22T18:39:24 | 338,457,027 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 60,027 | cpp | #include "WPILib.h"
#include "TalonXVI.h"
/*
** TalonXVI... aka Planet Fitness
** "We pick things up and put things down"
*/
TalonXVI::TalonXVI()
{
driveStick = new Joystick(0);
gamepad = new Joystick(1);
#ifdef CALIBRATION
#ifdef PRACTICE_BOT
calDevice = new Talon(PWM_CALDEVICE);
#else
calDevice = new VictorSP(PWM_CALDEVICE);
#endif
#else
drive = new DriveTrain();
barrelGrabber = new BarrelGrab();
automodeSwitch = new ModeSwitch();
toteGrabber = new ToteGrab();
elevator = new Elevator();
crane = new Crane();
pilot = new Autopilot();
//MAX location = new Navigation();
#ifdef USE_USBCAMERA
//camServer = CameraServer::GetInstance();
#endif
#endif
firstTime = true;
cameraInitialized = false;
autoMode = 0;
autoStage = 0;
dashCounter = 0;
loopTime = LOOPTIME;
startTime = 0.0;
curTime = 0.0;
waitTime = 0.0;
loopOverTime = false;
thumbButtonPressed = false;
NumLoopsOverTime = 0;
}
void TalonXVI::RobotInit()
{
#ifdef USE_USBCAMERA
if(!cameraInitialized)
{
printf("CameraServer being started\n");
CameraServer::GetInstance()->SetQuality(50);
//the camera name (ex "cam0") was verified through the roborio web interface
CameraServer::GetInstance()->StartAutomaticCapture("cam0");
cameraInitialized = true;
}
#endif
}
/*
** Drive left & right motors for 2 seconds then stopA
*/
void TalonXVI::Autonomous()
{
#ifndef CALIBRATION
autoMode = automodeSwitch->Get();
int loopCounter=0;
autoStage = 0;
if(firstTime)
{
elevator->StartFromTheBottom();
firstTime = false;
}
//resets all control systems
elevator->ControlSystemReset();
barrelGrabber->ControlSystemReset();
crane->ControlSystemReset();
pilot->StopAll();
printf("Auto Mode %d\n", autoMode);
double initialStartTime;
initialStartTime = GetTime();
startTime = initialStartTime - loopTime;
drive->GyroOn();
while (IsAutonomous() && IsEnabled())
{
startTime += loopTime;
loopCounter++;
#ifdef PRACTICE_BOT
//autoMode = 3;
#endif
switch (autoMode)
{
case 0:
default:
break;
case 1:
//AutoModeGrabAndMove();
AutoModeTwoTote();
break;
case 2:
AutoModeMove();
break;
case 3:
AutoModeContainersFromStepFlat();
break;
case 4:
//AutoModeTest();
AutoModeToteStackPilot();
//AutoModeAutoPilotTest();
//AutoModeTotesAndBarrels();
break;
case 5:
AutoModeJustGrabBarrelFlat();
break;
case 6:
AutoModeContainersFromStepTilt();
break;
case 7:
AutoModeJustGrabBarrelTilt();
break;
/*
case 8:
AutoModeTwoTote();
break;
*/
}
/*
** COMMUNITY SERVICE
*/
//drive->JoystickDrive(driveStick->GetX(), driveStick->GetY(), driveStick->GetZ(), driveStick->GetTrigger());
CommunityService();
ServiceDash();
// ENFORCE LOOP TIMING
curTime = GetTime();
waitTime = loopTime - (curTime - startTime);
if (waitTime < 0.0)
{
printf("WARNING! LOOP IS OVERTIME by %f seconds\n", waitTime*-1);
loopOverTime = true;
}
else
{
Wait(waitTime);
loopOverTime = false;
#ifdef CHECK_LOOPTIMING
endTime = GetTime();
totalLoopTime = endTime - startTime;
printf("startTime: %f curTime : %f endTime: %f Wait Time: %f This Loop Time: %f Total Delta Time: %f [avg: %f] \n",
startTime, curTime, endTime, waitTime, totalLoopTime, endTime-initialStartTime, (endTime-initialStartTime)/loopCounter);
#endif
}
}
Omnicide();
#endif //CALIBRATION
}
void TalonXVI::OperatorControl()
{
int loopCounter=0;
//bool init_flag = true;
#ifndef CALIBRATION
if(firstTime)
{
elevator->StartFromTheBottom();
firstTime = false;
}
//resets all control systems
elevator->ControlSystemReset();
barrelGrabber->ControlSystemReset();
crane->ControlSystemReset();
drive->GyroOn();
thumbButtonPressed = false;
#endif
#ifdef CHECK_LOOPTIMING
double endTime;
double totalLoopTime;
#endif
double initialStartTime;
initialStartTime = GetTime();
startTime = initialStartTime - loopTime;
while (IsOperatorControl() && IsEnabled())
{
startTime += loopTime;
loopCounter++;
#ifdef CALIBRATION
float cal_command_x = (driveStick->GetY());
if(cal_command_x < -0.5)
cal_command_x =-1.0;
else if(cal_command_x > .5)
cal_command_x = 1.0;
else
cal_command_x = 0.0;
printf("calibrating PWM %d -- %f\n", PWM_CALDEVICE, cal_command_x);
calDevice->Set(cal_command_x);
#else
/*
** JOYSTICK/GAMEPAD BUTTONS
*/
#ifdef USE_GYRO
if (driveStick->GetRawButton(ENABLE_GYRO_BUTTON))
{
drive->GyroOn();
}
else if (driveStick->GetRawButton(DISABLE_GYRO_BUTTON))
{
drive->GyroOff();
}
#endif
//
// BARREL OPERATIONS = Crane + BarrelGrab
//
barrelGrabber->JoystickMove(gamepad->GetRawAxis(GAMEPAD_TROLLEY));
crane->GetBarrelAutomation(gamepad->GetRawButton(BUTTON_GET_BARREL_FLAT), gamepad->GetRawButton(BUTTON_GET_BARREL_TILT));
#ifdef USE_CRANE
if(gamepad->GetPOV(0) == DPAD_CRANE_UP)
{
//printf("joystick DPAD crane UP\n");
crane->JoystickMove(1.0);//change rate in the crane class, keep this 1
}
else if(gamepad->GetPOV(0) == DPAD_CRANE_DOWN)
{
//printf("joystick DPAD crane DOWN\n");
crane->JoystickMove(-1.0);//change rate in the crane class, keep this -1
}
else
{
//printf("joystick DPAD crane STOP\n");
crane->JoystickMove(0.0);
}
#endif
#ifdef USE_BARRELGRAB
if(gamepad->GetPOV(0) == DPAD_WRIST_UP)
{
//printf("calling WristUp\n");
barrelGrabber->WristUp();
}
else if(gamepad->GetPOV(0) == DPAD_WRIST_DOWN)
{
//printf("calling WristDown\n");
barrelGrabber->WristDown();
}
if(gamepad->GetRawButton(BUTTON_CLAW_PINCH))
{
//printf("calling ClawPinch\n");
barrelGrabber->ClawPinch();
}
if(gamepad->GetRawButton(BUTTON_CLAW_RELEASE))
{
//printf("calling ClawRelease\n");
barrelGrabber->ClawRelease();
}
#endif
//
// TOTE OPERATIONS
//
if(driveStick->GetRawButton(DRIVER_ELEVATOR_UP))
{
elevator->ManualMove(-1.0);
}
else if(driveStick->GetRawButton(DRIVER_ELEVATOR_DOWN))
{
elevator->ManualMove(1.0);
}
else
{
elevator->ManualMove(gamepad->GetRawAxis(GAMEPAD_ELEVATOR));
}
// TESTING ONLY!!!!
/*
if(gamepad->GetRawButton(4))
{
if(init_flag)
elevator->GoToHeight(27, init_flag);
if(!elevator->atGoal())
{
elevator->GoToHeight(27, init_flag);
}
init_flag = false;
}
else
{
init_flag = true;
elevator->StopSeekingHeight();
}
*/
if(gamepad->GetRawButton(BUTTON_GET_TOTE) || driveStick->GetRawButton(DRIVER_GET_TOTE))
{
//printf("calling GetTote\n");
toteGrabber->GetTote();
}
if(gamepad->GetRawButton(BUTTON_EJECT_TOTE) || driveStick->GetRawButton(DRIVER_EJECT_TOTE))
{
//printf("calling EjectTote\n");
toteGrabber->EjectTote();
}
if(gamepad->GetRawButton(STOP_TOTE_MOTOR) || driveStick->GetRawButton(DRIVER_STOP_MOTOR))
{
toteGrabber->StopMotor();
}
if(gamepad->GetRawButton(BUTTON_SQUEEZE_TOTE) || driveStick->GetRawButton(DRIVER_SQUEEZE_TOTE) || driveStick->GetRawButton(THUMB_BUTTON))
{
//printf("calling SqueezeTote\n");
toteGrabber->SqueezeTote();
}
if(gamepad->GetRawButton(BUTTON_RELEASE_TOTE) || driveStick->GetRawButton(DRIVER_RELEASE_TOTE) ||
(thumbButtonPressed && !(driveStick->GetRawButton(THUMB_BUTTON))))
{
//printf("calling ReleaseTote\n");
toteGrabber->ReleaseTote();
}
thumbButtonPressed = driveStick->GetRawButton(THUMB_BUTTON);
/*
** COMMUNITY SERVICE
*/
//victorTest->Set(driveStick->GetX());
drive->JoystickDrive(driveStick->GetX(), driveStick->GetY(), driveStick->GetZ(), driveStick->GetTrigger());
CommunityService();
ServiceDash();
#endif //Calibration
// ENFORCE LOOP TIMING
curTime = GetTime();
waitTime = loopTime - (curTime - startTime);
if (waitTime < 0.0)
{
printf("WARNING! LOOP IS OVERTIME by %f seconds\n", waitTime*-1);
loopOverTime = true;
NumLoopsOverTime++;
}
else
{
Wait(waitTime);
loopOverTime = false;
#ifdef CHECK_LOOPTIMING
endTime = GetTime();
totalLoopTime = endTime - startTime;
printf("startTime: %f curTime : %f endTime: %f Wait Time: %f This Loop Time: %f Total Delta Time: %f [avg: %f] \n",
startTime, curTime, endTime, waitTime, totalLoopTime, endTime-initialStartTime, (endTime-initialStartTime)/loopCounter);
#endif
}
}
Omnicide();
}
/*
** Runs during test mode
*/
void TalonXVI::Test()
{
}
/*
** Runs when disabled
*/
void TalonXVI::Disabled()
{
/*
Wait(1.0);
while (!IsEnabled())
{
//autoMode = (int) SmartDashboard::GetNumber("Auto Mode (1-2): ");
//SmartDashboard::PutNumber("Auto Mode printout", autoMode);
// give it some time to catch its breath
Wait(0.5);
}
*/
}
void TalonXVI::Omnicide()
{
#ifndef CALIBRATION
drive->StopAll();
toteGrabber->StopAll();
elevator->StopAll();
barrelGrabber->StopAll();
pilot->StopAll();
crane->StopAll();
#endif
}
void TalonXVI::CommunityService()
{
#ifndef CALIBRATION
toteGrabber->Service();
barrelGrabber->Service();
//pilot->Service();
elevator->Service();
crane->Service();
// NOTE: DriveTrain and ModeSwitch do not have Service functions
#endif
}
void TalonXVI::ServiceDash()
{
#ifndef CALIBRATION
if (dashCounter == 10)
{
//printf("Updating Dash \n");
SmartDashboard::PutBoolean("Loop OverTime: ", loopOverTime);
SmartDashboard::PutNumber("Number of Loops OverTime: ", NumLoopsOverTime);
toteGrabber->UpdateDash();
barrelGrabber->UpdateDash();
#ifdef USE_GYRO
drive->UpdateDash();
#endif
automodeSwitch->UpdateDash();
elevator->UpdateDash();
pilot->UpdateDash();
crane->UpdateDash();
dashCounter = 0;
}
else
{
dashCounter++;
}
#endif
}
double TalonXVI::Limit(double min, double max, double curVal)
{
if (curVal > max)
return max;
if (curVal < min)
return min;
return curVal;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////// AUTONOMOUS MODES //////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef CALIBRATION
void TalonXVI::AutoModeToteStackSimple() // three tote stack with help
{
static float xcmd;
static float ycmd;
static float zcmd;
static bool piloting;
static int loopcount = 0;
switch(autoStage)
{
case 0: //START: begin lift first tote
piloting = false;
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
pilot->StopAll(); // ensure reset
elevator->GoToHeight(AUTO_ELEVATOR_STACK, true);
loopcount = 0;
autoStage++;
break;
case 1: // wait for the tote to be off the ground
piloting = false;
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
loopcount++;
if(loopcount >= FIRST_PAUSE_TIME) //after the wait, set driving goals
{
piloting = true;
pilot->SetGoals(AUTO_DRIVE_TO_TOTE, 0.0, 0.0);
autoStage++;
loopcount = 0;
}
break;
case 2: //wait for tote and autopilot goals, grab second tote
piloting = true;
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
toteGrabber->GetTote();
if(pilot->IsAtGoal())
{
pilot->StopAll();
toteGrabber->GetTote();
toteGrabber->SqueezeTote();
loopcount = 0;
autoStage++;
}
break;
case 3: //when tote is grabbed, send elevator down
piloting = false;
elevator->ManualMove(0.0);
if(toteGrabber->HasTote())
{
autoStage++;
loopcount = 0;
}
break;
case 4: // move forward a little and get the tote
piloting = false;
elevator->ManualMove(0.0);
xcmd = AUTO_GRAB_DRIVE_CMD; ycmd = 0.0; zcmd = 0.0;
loopcount++;
if(loopcount >= AUTO_WAIT_FOR_TOTE)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
//pilot->StopAll();
toteGrabber->ReleaseTote();
toteGrabber->StopMotor();
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, true);
loopcount = 0;
autoStage++;
}
break;
case 5: //ensure elevator is all the way down
piloting = false;
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, false);
if(elevator->atGoal())
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, true);
loopcount = 0;
autoStage++;
}
break;
case 6: // wait for the tote to be off the ground
piloting = false;
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
loopcount++;
if(loopcount >= AUTO_WAIT_FOR_LIFT) //after the wait, set driving goals
{
piloting = true;
pilot->SetGoals(AUTO_DRIVE_TO_TOTE, 0.0, 0.0);
toteGrabber->GetTote();
autoStage++;
loopcount = 0;
}
break;
case 7: //wait for tote and autopilot goals, grab third tote
piloting = true;
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
toteGrabber->GetTote();
if(pilot->IsAtGoal())
{
pilot->StopAll();
toteGrabber->GetTote();
toteGrabber->SqueezeTote();
loopcount = 0;
autoStage++;
}
break;
case 8: //when tote is grabbed, send elevator down
piloting = false;
elevator->ManualMove(0.0);
if(toteGrabber->HasTote())
{
autoStage++;
loopcount = 0;
}
break;
case 9: // move forward a little and get the tote
piloting = false;
elevator->ManualMove(0.0);
xcmd = AUTO_GRAB_DRIVE_CMD; ycmd = 0.0; zcmd = 0.0;
loopcount++;
if(loopcount >= AUTO_WAIT_FOR_TOTE)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
pilot->StopAll();
toteGrabber->ReleaseTote();
toteGrabber->StopMotor();
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, true);
loopcount = 0;
autoStage++;
}
break;
case 10: //ensure elevator is all the way down
piloting = false;
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, false);
if(elevator->atGoal())
{
elevator->GoToHeight(AUTO_ELEVATOR_MOVE, true);
loopcount = 0;
autoStage++;
}
break;
case 11: //ensure elevator is all the way up
piloting = false;
elevator->GoToHeight(AUTO_ELEVATOR_MOVE, false);
if(elevator->atGoal())
{
xcmd = 0.0; ycmd = 0.0; zcmd = -2.0;
loopcount = 0;
autoStage++;
}
break;
case 12: //rotate 90 deg
piloting = false;
elevator->ManualMove(0.0);
loopcount++;
if(loopcount >= AUTO_90DEGROT_TIMEX2)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
pilot->StopAll();
loopcount = 0;
autoStage++;
}
break;
case 13: //drive to autozone...
piloting = true;
pilot->SetGoals(AUTO_DRIVE_AUTOZONE_BACK, 0.0, 0.0); //DRIVING BACKWARDS INTO AUTOZONE
elevator->ManualMove(0.0);
loopcount = 0;
autoStage++;
break;
case 14: // when arrive at goal, move elevator to bottom
piloting = true;
elevator->ManualMove(0.0);
loopcount++;
if(loopcount >= AUTO_DROP_DRIVE_TIME)
{
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, true);
}
if(pilot->IsAtGoal())
{
pilot->StopAll();
loopcount = 0;
}
break;
case 15: // when arrive at goal, move elevator to bottom
piloting = true;
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, false);
if(pilot->IsAtGoal())
{
pilot->StopAll();
loopcount = 0;
}
if (elevator->atGoal())
{
elevator->ManualMove(0.0);
autoStage++;
}
break;
default:
break;
}
if(piloting)
{
//printf("stage %d piloting\n", autoStage);
pilot->Service();
}
else
{
//printf("stage %d driving\n", autoStage);
drive->DriveControl(xcmd, ycmd, zcmd);
}
}
void TalonXVI::AutoModeTotesWithStrafe() // three tote stack with help
{
static float xcmd;
static float ycmd;
static float zcmd;
static bool piloting;
static int loopcount = 0;
switch(autoStage)
{
case 0: //START: begin lift first tote
piloting = false;
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
pilot->StopAll(); // ensure reset
elevator->GoToHeight(AUTO_ELEVATOR_STACK, true);
loopcount = 0;
autoStage++;
break;
case 1: // wait for the tote to be off the ground
pilot->StopAll();
piloting = true;
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
pilot->SetGoals(0.0, AUTO_STRAFE_RIGHT, 0.0);
autoStage++;
loopcount = 0;
break;
case 2: //wait for tote and autopilot goals, grab second tote
piloting = true;
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
if(pilot->IsAtGoal())
{
pilot->StopAll();
toteGrabber->EjectTote();
loopcount = 0;
autoStage++;
}
break;
case 3:
piloting = true;
pilot->SetGoals(AUTO_NORTH_TO_TOTE, AUTO_STRAFE_LEFT, 0.0);
loopcount++;
if(loopcount >= AUTO_DRIVE_ONLY_TIME)
{
toteGrabber->StopMotor();
toteGrabber->GetTote();
loopcount = 0;
autoStage++;
}
break;
case 4: //when tote is grabbed, send elevator down
piloting = true;
if(pilot->IsAtGoal())
{
pilot->StopAll();
toteGrabber->GetTote();
toteGrabber->SqueezeTote();
loopcount = 0;
autoStage++;
}
break;
case 5:
elevator->ManualMove(0.0);
if(toteGrabber->HasTote())
{
autoStage++;
loopcount = 0;
}
break;
case 6: // move forward a little and get the tote
piloting = false;
elevator->ManualMove(0.0);
xcmd = AUTO_GRAB_DRIVE_CMD; ycmd = 0.0; zcmd = 0.0;
loopcount++;
if(loopcount >= AUTO_WAIT_FOR_TOTE)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
//pilot->StopAll();
toteGrabber->ReleaseTote();
toteGrabber->StopMotor();
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, true);
loopcount = 0;
autoStage++;
}
break;
case 7: //ensure elevator is all the way down
piloting = true;
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, false);
if(elevator->atGoal())
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, true);
loopcount = 0;
autoStage++;
}
break;
case 8: // wait for the tote to be off the ground
pilot->StopAll();
piloting = true;
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
pilot->SetGoals(0.0, AUTO_SECOND_STRAFE_RIGHT, 0.0);
autoStage++;
loopcount = 0;
break;
case 9: //wait for tote and autopilot goals, grab second tote
piloting = true;
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
if(pilot->IsAtGoal())
{
pilot->StopAll();
toteGrabber->EjectTote();
loopcount = 0;
autoStage++;
}
break;
case 10:
piloting = true;
pilot->SetGoals(AUTO_NORTH_TO_TOTE, AUTO_SECOND_STRAFE_LEFT, 0.0);
loopcount++;
if(loopcount >= AUTO_DRIVE_ONLY_TIME)
{
toteGrabber->StopMotor();
toteGrabber->GetTote();
loopcount = 0;
autoStage++;
}
break;
case 11: //when tote is grabbed, send elevator down
piloting = true;
if(pilot->IsAtGoal())
{
pilot->StopAll();
toteGrabber->GetTote();
toteGrabber->SqueezeTote();
loopcount = 0;
autoStage++;
}
break;
case 12: //when tote is grabbed, send elevator down
piloting = false;
elevator->ManualMove(0.0);
if(toteGrabber->HasTote())
{
autoStage++;
loopcount = 0;
}
break;
case 13: // move forward a little and get the tote
piloting = false;
elevator->ManualMove(0.0);
xcmd = AUTO_GRAB_DRIVE_CMD; ycmd = 0.0; zcmd = 0.0;
loopcount++;
if(loopcount >= AUTO_WAIT_FOR_TOTE)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
pilot->StopAll();
toteGrabber->ReleaseTote();
toteGrabber->StopMotor();
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, true);
loopcount = 0;
autoStage++;
}
break;
case 14: //ensure elevator is all the way down
piloting = false;
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, false);
if(elevator->atGoal())
{
elevator->GoToHeight(AUTO_ELEVATOR_MOVE, true);
loopcount = 0;
autoStage++;
}
break;
case 15: //ensure elevator is all the way up
piloting = false;
elevator->GoToHeight(AUTO_ELEVATOR_MOVE, false);
if(elevator->atGoal())
{
xcmd = 0.0; ycmd = 0.0; zcmd = -2.0;
loopcount = 0;
autoStage++;
}
break;
case 16: //rotate 90 deg
piloting = false;
elevator->ManualMove(0.0);
loopcount++;
if(loopcount >= AUTO_90DEGROT_TIMEX2)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
pilot->StopAll();
loopcount = 0;
autoStage++;
}
break;
case 17: //drive to autozone...
piloting = true;
pilot->SetGoals(AUTO_DRIVE_AUTOZONE_BACK, 0.0, 0.0); //DRIVING BACKWARDS INTO AUTOZONE
elevator->ManualMove(0.0);
loopcount = 0;
autoStage++;
break;
case 18: // when arrive at goal, move elevator to bottom
piloting = true;
elevator->ManualMove(0.0);
loopcount++;
if(loopcount >= AUTO_DROP_DRIVE_TIME)
{
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, true);
}
if(pilot->IsAtGoal())
{
pilot->StopAll();
loopcount = 0;
}
break;
case 19: // when arrive at goal, move elevator to bottom
piloting = true;
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, false);
if(pilot->IsAtGoal())
{
pilot->StopAll();
loopcount = 0;
}
if (elevator->atGoal())
{
elevator->ManualMove(0.0);
autoStage++;
}
break;
default:
break;
}
if(piloting)
{
//printf("stage %d piloting\n", autoStage);
pilot->Service();
}
else
{
//printf("stage %d driving\n", autoStage);
drive->DriveControl(xcmd, ycmd, zcmd);
}
}
void TalonXVI::AutoModeContainersFromStepFlat()
{
static int loopCount = 0;
static bool buttonASim = false;
static bool buttonYSim = false;
static float xcmd;
static float ycmd;
static float zcmd;
switch(autoStage)
{
case 0://start moving claw into position
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
buttonASim = true;
buttonYSim = false;
loopCount = 0;
autoStage++;
break;
case 1: //drive backwards
xcmd = -0.25; ycmd = 0.0; zcmd = 0.0;
loopCount = 0;
autoStage++;
break;
case 2: // stop driving after short distance
loopCount++;
if(loopCount >= AUTO_CRANE_DRIVE)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
autoStage++;
}
break;
case 3:// wait for claw in position, start picking up barrel
if(crane->IsDoneExtending())
{
buttonASim = false;
autoStage++;
}
break;
case 4: //drive backwards
xcmd = -0.25; ycmd = 0.0; zcmd = 0.0;
loopCount = 0;
autoStage++;
break;
case 5: // stop driving after short distance
loopCount++;
if(loopCount >= GET_BARREL_DELAY)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
autoStage++;
}
break;
case 6: // wait for barrel lifted, start drop and regrab
if(crane->IsDoneRetracting())
{
loopCount = 0;
barrelGrabber->ControlledMove(0.0);
autoStage++;
}
break;
case 7: // bring barrel down on tote, and release
barrelGrabber->ControlledMove(-0.5);
//printf("Trolley: %f (top is 3.84) \n", trolleyHeight);
if(barrelGrabber->GetTrolleyHeight() <= AUTO_REGRAB_TROLLEY_HEIGHT)
{
barrelGrabber->ControlledMove(0.0);
barrelGrabber->ClawRelease();
loopCount = 0;
autoStage++;
}
break;
case 8: // bring trolley down further and pinch again
loopCount++;
if(loopCount >= AUTO_WAIT_FOR_PINCH)
{
barrelGrabber->ControlledMove(-0.5);
if(barrelGrabber->GetTrolleyHeight() <= MIN_TROLLEY_POSITION)
{
barrelGrabber->ControlledMove(0.0);
barrelGrabber->ClawPinch();
loopCount = 0;
autoStage++;
}
}
break;
case 9: // regrab barrel and move trolley up
loopCount++;
if(loopCount >= AUTO_WAIT_FOR_PINCH)
{
barrelGrabber->ControlledMove(0.5);
if((barrelGrabber->GetTrolleyHeight()) >= AUTO_TROLLEY_BACK_UP)
{
barrelGrabber->ControlledMove(0.0);
loopCount = 0;
autoStage++;
}
}
break;
case 10: // when done moving, stop
xcmd = 0.5; ycmd = 0.0; zcmd = 0.0;
loopCount++;
barrelGrabber->ControlledMove(0.0);
if(loopCount >= AUTO_BARREL_BACKUP_TIME)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
}
break;
default:
barrelGrabber->ControlledMove(0.0);
break;
}
// note that this automation includes calls to both crane and trolley control system
crane->GetBarrelAutomation(buttonASim, buttonYSim);
drive->DriveControl(xcmd, ycmd, zcmd);
//printf("stage %d, drive %f, %f, %f\n", autoStage, xcmd, ycmd, zcmd);
}
void TalonXVI::AutoModeJustGrabBarrelFlat()
{
static int loopCount = 0;
static bool buttonASim = false;
static bool buttonYSim = false;
static float xcmd;
static float ycmd;
static float zcmd;
switch(autoStage)
{
case 0://start moving claw into position
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
buttonASim = true;
buttonYSim = false;
loopCount = 0;
autoStage++;
break;
case 1: //drive backwards
xcmd = -0.25; ycmd = 0.0; zcmd = 0.0;
loopCount = 0;
autoStage++;
break;
case 2: // stop driving after short distance
loopCount++;
if(loopCount >= AUTO_CRANE_DRIVE)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
autoStage++;
}
break;
case 3:// wait for claw in position, start picking up barrel
if(crane->IsDoneExtending())
{
buttonASim = true;
barrelGrabber->ClawPinch();
autoStage++;
}
break;
case 4: //drive backwards
xcmd = -0.25; ycmd = 0.0; zcmd = 0.0;
loopCount = 0;
autoStage++;
break;
case 5: // stop driving after short distance
loopCount++;
if(loopCount >= GET_BARREL_DELAY)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
autoStage++;
}
break;
default:
break;
}
// note that this automation includes calls to both crane and trolley control system
crane->GetBarrelAutomation(buttonASim, buttonYSim);
drive->DriveControl(xcmd, ycmd, zcmd);
//printf("stage %d, drive %f, %f, %f\n", autoStage, xcmd, ycmd, zcmd);
}
void TalonXVI::AutoModeContainersFromStepTilt()
{
static int loopCount = 0;
static bool buttonASim = false;
static bool buttonYSim = false;
static float xcmd;
static float ycmd;
static float zcmd;
switch(autoStage)
{
case 0://start moving claw into position
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
buttonASim = false;
buttonYSim = true;
loopCount = 0;
autoStage++;
break;
case 1: //drive backwards
xcmd = -0.25; ycmd = 0.0; zcmd = 0.0;
loopCount = 0;
autoStage++;
break;
case 2: // stop driving after short distance
loopCount++;
if(loopCount >= AUTO_CRANE_DRIVE)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
autoStage++;
}
break;
case 3:// wait for claw in position, start picking up barrel
if(crane->IsDoneExtending())
{
buttonYSim = false;
autoStage++;
}
break;
case 4: //drive backwards
xcmd = -0.25; ycmd = 0.0; zcmd = 0.0;
loopCount = 0;
autoStage++;
break;
case 5: // stop driving after short distance
loopCount++;
if(loopCount >= GET_BARREL_DELAY)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
autoStage++;
}
break;
case 6: // wait for barrel lifted, start drop and regrab
if(crane->IsDoneRetracting())
{
loopCount = 0;
barrelGrabber->ControlledMove(0.0);
autoStage++;
}
break;
case 7: // bring barrel down on tote, and release
barrelGrabber->ControlledMove(-0.5);
//printf("Trolley: %f (top is 3.84) \n", trolleyHeight);
if(barrelGrabber->GetTrolleyHeight() <= AUTO_REGRAB_TROLLEY_HEIGHT)
{
barrelGrabber->ControlledMove(0.0);
barrelGrabber->ClawRelease();
loopCount = 0;
autoStage++;
}
break;
case 8: // bring trolley down further and pinch again
loopCount++;
if(loopCount >= AUTO_WAIT_FOR_PINCH)
{
barrelGrabber->ControlledMove(-0.5);
if(barrelGrabber->GetTrolleyHeight() <= TILTED_MIN_TROLLEY)
{
barrelGrabber->ControlledMove(0.0);
barrelGrabber->ClawPinch();
loopCount = 0;
autoStage++;
}
}
break;
case 9: // regrab barrel and move trolley up
loopCount++;
if(loopCount >= AUTO_WAIT_FOR_PINCH)
{
barrelGrabber->ControlledMove(0.5);
if((barrelGrabber->GetTrolleyHeight()) >= AUTO_TROLLEY_BACK_UP)
{
barrelGrabber->ControlledMove(0.0);
loopCount = 0;
autoStage++;
}
}
break;
/*
case 10: // when done moving, stop
xcmd = 0.5; ycmd = 0.0; zcmd = 0.0;
loopCount++;
barrelGrabber->ControlledMove(0.0);
if(loopCount >= AUTO_BARREL_BACKUP_TIME)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
}
break;
*/
default:
barrelGrabber->ControlledMove(0.0);
break;
}
// note that this automation includes calls to both crane and trolley control system
crane->GetBarrelAutomation(buttonASim, buttonYSim);
drive->DriveControl(xcmd, ycmd, zcmd);
//printf("stage %d, drive %f, %f, %f\n", autoStage, xcmd, ycmd, zcmd);
}
void TalonXVI::AutoModeJustGrabBarrelTilt()
{
static int loopCount = 0;
static bool buttonASim = false;
static bool buttonYSim = false;
static float xcmd;
static float ycmd;
static float zcmd;
switch(autoStage)
{
case 0://start moving claw into position
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
buttonASim = false;
buttonYSim = true;
loopCount = 0;
autoStage++;
break;
case 1: //drive backwards
xcmd = -0.25; ycmd = 0.0; zcmd = 0.0;
loopCount = 0;
autoStage++;
break;
case 2: // stop driving after short distance
loopCount++;
if(loopCount >= AUTO_CRANE_DRIVE)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
autoStage++;
}
break;
case 3:// wait for claw in position, start picking up barrel
if(crane->IsDoneExtending())
{
buttonYSim = true;
barrelGrabber->ClawPinch();
autoStage++;
}
break;
case 4: //drive backwards
xcmd = -0.25; ycmd = 0.0; zcmd = 0.0;
loopCount = 0;
autoStage++;
break;
case 5: // stop driving after short distance
loopCount++;
if(loopCount >= GET_BARREL_DELAY)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
autoStage++;
}
break;
default:
break;
}
// note that this automation includes calls to both crane and trolley control system
crane->GetBarrelAutomation(buttonASim, buttonYSim);
drive->DriveControl(xcmd, ycmd, zcmd);
//printf("stage %d, drive %f, %f, %f\n", autoStage, xcmd, ycmd, zcmd);
}
void TalonXVI::AutoModeGrabAndMove()
{
static float trolleyMotorCmd = 0.0;
static int loopcount = 0;
static float trolleyHeight;
static float xcmd;
static float ycmd;
static float zcmd;
switch(autoStage)
{
case 0: //grab tote
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
elevator->GoToHeight(15.0, true);
barrelGrabber->ClawRelease();
trolleyMotorCmd = 0.0;
autoStage++;
break;
case 1: //wait for elevator at height
elevator->GoToHeight(15.0, false);
barrelGrabber->WristDown();
if(elevator->atGoal())
{
autoStage++;
}
break;
case 2: //drive backwards
elevator->ManualMove(0.0);
xcmd = -0.25; ycmd = 0.0; zcmd = 0.0;
loopcount = 0;
autoStage++;
break;
case 3: // stop driving after short distance
elevator->ManualMove(0.0);
loopcount++;
if(loopcount >= AUTO_BACK_TIME)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
autoStage++;
}
break;
case 4: //grab barrel
elevator->ManualMove(0.0);
barrelGrabber->ClawPinch();
autoStage++;
break;
case 5: //lift barrel
elevator->ManualMove(0.0);
trolleyMotorCmd = 0.5;
trolleyHeight = barrelGrabber->GetTrolleyHeight();
//printf("Trolley: %f (top is 3.84) \n", trolleyHeight);
if(trolleyHeight >= AUTO_TROLLEY_HEIGHT)
{
trolleyMotorCmd = 0.0;
autoStage++;
}
break;
case 6: //rotate sideways
elevator->ManualMove(0.0);
xcmd = 0.0; ycmd = 0.0; zcmd = 1.0;
loopcount = 0;
autoStage++;
break;
case 7: //stop in autozone
elevator->ManualMove(0.0);
loopcount++;
if(loopcount >= AUTO_90DEGROT_TIME)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
autoStage++;
}
break;
case 8: //drive forward
elevator->ManualMove(0.0);
xcmd = 0.50; ycmd = 0.0; zcmd = 0.0;
loopcount = 0;
autoStage++;
break;
case 9: //stop in autozone
elevator->ManualMove(0.0);
loopcount++;
if(loopcount >= AUTO_DRIVE_TIME)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
autoStage++;
}
break;
default:
break;
}
barrelGrabber->ControlledMove(trolleyMotorCmd);
drive->DriveControl(xcmd, ycmd, zcmd);
}
void TalonXVI::AutoModeMove()
{
static int loopcount = 0;
static float xcmd;
static float ycmd;
static float zcmd;
switch(autoStage)
{
case 0: //drive forward
xcmd = 0.50; ycmd = 0.0; zcmd = 0.0;
loopcount = 0;
autoStage++;
break;
case 1: //stop in autozone
loopcount++;
if(loopcount >= AUTO_DRIVE_ONLY_TIME)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
autoStage++;
}
break;
default:
break;
}
drive->DriveControl(xcmd, ycmd, zcmd);
}
void TalonXVI::AutoModeTotesAndBarrels()
{
static float trolleyMotorCmd = 0.0;
static int loopcount = 0;
static float xcmd;
static float ycmd;
static float zcmd;
static bool piloting;
switch(autoStage)
{
case 0: //grab tote
piloting = false;
elevator->GoToHeight(AUTO_ELEVATOR_STACK, true); //was 15.0
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
barrelGrabber->ClawRelease();
trolleyMotorCmd = 0.0;
loopcount = 0;
autoStage++;
break;
case 1: // wait for the tote to be off the ground
piloting = false;
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
barrelGrabber->WristDown();
loopcount++;
if(loopcount >= FIRST_PAUSE_TIME) //after the wait, set driving goals
{
xcmd = -0.25; ycmd = 0.0; zcmd = 0.0;
loopcount = 0;
autoStage++;
}
break;
case 2: //wait for elevator at goal and done driving
piloting = false;
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false); //was 15.0
loopcount++;
//printf("stage %d loopcount %d\n", autoStage, loopcount);
if(loopcount >= AUTO_BACK_TIME)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
}
if(elevator->atGoal() && (loopcount >= AUTO_BACK_TIME))
{
//printf("done driving back, loopcount %d\n", loopcount);
loopcount = 0;
autoStage++;
}
break;
case 3: //grab barrel
piloting = false;
elevator->ManualMove(0.0);
barrelGrabber->ClawPinch();
loopcount++;
if(loopcount >= AUTO_WAIT_FOR_PINCH)
{
loopcount = 0;
autoStage++;
}
break;
case 4: //lift barrel
piloting = false;
elevator->ManualMove(0.0);
trolleyMotorCmd = 0.75; //was 0.5
//printf("Trolley: %f motorcmd %f \n", barrelGrabber->GetTrolleyHeight(), trolleyMotorCmd);
autoStage++;
break;
case 5: // wait for the barrel to be off the ground
piloting = false;
elevator->ManualMove(0.0);
//printf("Trolley: %f motorcmd %f \n", barrelGrabber->GetTrolleyHeight(), trolleyMotorCmd);
if(trolleyMotorCmd != 0.0 && barrelGrabber->GetTrolleyHeight() >= AUTO_TROLLEY_HEIGHT)
{
printf("stage %d stopping Trolley\n", autoStage);
trolleyMotorCmd = 0.0;
}
loopcount++;
if(loopcount >= BARREL_PAUSE_TIME) //after the wait, set driving goals
{
// xcmd = -0.25; ycmd = 0.0; zcmd = 0.0;
autoStage++;
loopcount = 0;
}
break;
case 6: //spin 180
piloting = false;
elevator->ManualMove(0.0);
//printf("Trolley: %f motorcmd %f \n", barrelGrabber->GetTrolleyHeight(), trolleyMotorCmd);
if(trolleyMotorCmd != 0.0 && barrelGrabber->GetTrolleyHeight() >= AUTO_TROLLEY_HEIGHT)
{
//printf("stage %d stopping Trolley\n", autoStage);
trolleyMotorCmd = 0.0;
}
xcmd = 0.0; ycmd = 0.0; zcmd = 2.0;
loopcount = 0;
autoStage++;
break;
case 7: //stop rotating
piloting = false;
elevator->ManualMove(0.0);
//printf("Trolley: %f motorcmd %f \n", barrelGrabber->GetTrolleyHeight(), trolleyMotorCmd);
if(trolleyMotorCmd != 0.0 && barrelGrabber->GetTrolleyHeight() >= AUTO_TROLLEY_HEIGHT)
{
//printf("stage %d stopping Trolley\n", autoStage);
trolleyMotorCmd = 0.0;
}
loopcount++;
if(loopcount >= AUTO_180DEGROT_TIME)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
loopcount = 0;
pilot->StopAll();
autoStage++;
}
break;
case 8: //drive forward to second tote
piloting = true;
elevator->ManualMove(0.0);
//printf("Trolley: %f motorcmd %f \n", barrelGrabber->GetTrolleyHeight(), trolleyMotorCmd);
if(trolleyMotorCmd != 0.0 && barrelGrabber->GetTrolleyHeight() >= AUTO_TROLLEY_HEIGHT)
{
//printf("stage %d stopping Trolley\n", autoStage);
trolleyMotorCmd = 0.0;
}
//printf("stage %d Driving to %f\n", autoStage, AUTO_DRIVE_SECOND_TOTE);
pilot->SetGoals(AUTO_DRIVE_SECOND_TOTE, 0.0, 0.0);
loopcount = 0;
autoStage++;
break;
case 9: // when arrive at goal, begin squeeze tote
piloting = true;
elevator->ManualMove(0.0);
//printf("Trolley: %f motorcmd %f \n", barrelGrabber->GetTrolleyHeight(), trolleyMotorCmd);
if(trolleyMotorCmd != 0.0 && barrelGrabber->GetTrolleyHeight() >= AUTO_TROLLEY_HEIGHT)
{
//printf("stage %d stopping Trolley\n", autoStage);
trolleyMotorCmd = 0.0;
}
if(pilot->IsAtGoal())
{
pilot->StopAll();
toteGrabber->GetTote();
toteGrabber->SqueezeTote();
loopcount = 0;
autoStage++;
}
break;
case 10: // wait to until have tote, start to move elevator down
piloting = false;
elevator->ManualMove(0.0);
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
if(toteGrabber->HasTote())
{
loopcount = 0;
autoStage++;
}
break;
case 11: // move forward a little and get the tote
piloting = false;
elevator->ManualMove(0.0);
xcmd = 0.25; ycmd = 0.0; zcmd = 0.0;
loopcount++;
if(loopcount >= AUTO_WAIT_FOR_TOTE)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
pilot->StopAll();
toteGrabber->ReleaseTote();
toteGrabber->StopMotor();
elevator->GoToHeight(1.5, true);
loopcount = 0;
autoStage++;
}
break;
case 12: //elevator going down...
piloting = false;
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
elevator->GoToHeight(1.5, false);
if(elevator->atGoal())
{
//printf("picking up tote 2\n");
elevator->GoToHeight(AUTO_ELEVATOR_STACK, true);
autoStage++;
}
break;
case 13: // wait for the tote to be off the ground
piloting = false;
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
loopcount++;
if(loopcount >= FIRST_PAUSE_TIME) //after the wait, set rotate
{
xcmd = 0.0; ycmd = 0.0; zcmd = -2.0;
autoStage++;
loopcount = 0;
}
break;
case 14: //rotate 180
piloting = false;
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
loopcount++;
if(loopcount >= AUTO_180DEGROT_TIME)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
pilot->StopAll();
loopcount = 0;
autoStage++;
}
break;
case 15: //drive forward to 3rd tote
piloting = true;
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
//printf("stage %d Driving to %f\n", autoStage, AUTO_DRIVE_THIRD_TOTE);
pilot->SetGoals(AUTO_DRIVE_THIRD_TOTE, 3.0, 0.0);
loopcount = 0;
autoStage++;
break;
case 16: // when arrive at goal, begin squeeze tote
piloting = true;
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
if(pilot->IsAtGoal())
{
pilot->StopAll();
toteGrabber->GetTote();
toteGrabber->SqueezeTote();
loopcount = 0;
autoStage++;
}
break;
case 17: // wait to until have tote, move elevator down
piloting = false;
elevator->ManualMove(0.0);
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
if(toteGrabber->HasTote())
{
loopcount = 0;
autoStage++;
}
break;
case 18: // move forward a little and get the tote
piloting = false;
elevator->ManualMove(0.0);
xcmd = 0.25; ycmd = 0.0; zcmd = 0.0;
loopcount++;
if(loopcount >= AUTO_WAIT_FOR_TOTE)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
pilot->StopAll();
toteGrabber->ReleaseTote();
toteGrabber->StopMotor();
elevator->GoToHeight(1.5, true);
loopcount = 0;
autoStage++;
}
break;
case 19: //elevator going down...
piloting = false;
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
elevator->GoToHeight(1.5, false);
if(elevator->atGoal())
{
//printf("picking up tote 3!!!\n");
elevator->GoToHeight(10.0, true);
autoStage++;
}
break;
case 20: //elevator picking up 3rd tote, wait for at height
piloting = false;
elevator->GoToHeight(10.0, false);
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
xcmd = 0.0; ycmd = 0.0; zcmd = 2.0;
loopcount = 0;
autoStage++;
}
break;
case 21: //rotate 90 deg
piloting = false;
elevator->ManualMove(0.0);
loopcount++;
if(loopcount >= AUTO_90DEGROT_TIMEX2)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
pilot->StopAll();
loopcount = 0;
pilot->StopAll();
autoStage++;
}
break;
case 22: //drive to autozone...
piloting = true;
//printf("stage %d Driving to %f\n", autoStage, AUTO_DRIVE_AUTOZONE);
pilot->SetGoals(AUTO_DRIVE_AUTOZONE, 0.0, 0.0);
elevator->ManualMove(0.0);
loopcount = 0;
autoStage++;
break;
case 23: // when arrive at goal, move elevator to bottom
piloting = true;
elevator->ManualMove(0.0);
if(pilot->IsAtGoal())
{
pilot->StopAll();
elevator->GoToHeight(0.5, true);
loopcount = 0;
autoStage++;
}
break;
case 24: //wait for elevator to get to goal
piloting = false;
elevator->GoToHeight(0.5, false);
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
if(elevator->atGoal())
{
loopcount = 0;
autoStage++;
}
break;
case 25: //drive away from totes
piloting = true;
elevator->ManualMove(0.0);
//printf("stage %d Driving to %f\n", autoStage, AUTO_DRIVE_DROP_STACK);
pilot->SetGoals(AUTO_DRIVE_DROP_STACK, 0.0, 0.0);
loopcount = 0;
autoStage++;
break;
case 26: // when arrive at goal, move elevator to bottom
piloting = true;
elevator->ManualMove(0.0);
if(pilot->IsAtGoal())
{
pilot->StopAll();
}
break;
default:
break;
}
if(piloting)
{
//printf("stage %d piloting\n", autoStage);
pilot->Service();
}
else
{
//printf("stage %d driving\n", autoStage);
drive->DriveControl(xcmd, ycmd, zcmd);
}
barrelGrabber->ControlledMove(trolleyMotorCmd);
elevator->Service();
}
#ifdef UNUSED_AUTOMODES
void TalonXVI::AutoModeAutoPilotTest()
{
switch(autoStage)
{
case 0:
pilot->SetGoals(50.0, 0.0, 0.0);
printf("Setting Goals to 24 and 12\n");
autoStage++;
break;
case 1:
if(pilot->IsAtGoal())
{
printf("Autopilot At Goal\n");
}
break;
}
pilot->Service();
}
void TalonXVI::AutoModeTwoTotesAndBarrel()
{
static float trolleyMotorCmd = 0.0;
static int loopcount = 0;
static float xcmd;
static float ycmd;
static float zcmd;
static bool piloting;
switch(autoStage)
{
case 0: //grab tote
piloting = false;
elevator->GoToHeight(AUTO_ELEVATOR_STACK, true); //was 15.0
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
barrelGrabber->ClawRelease();
trolleyMotorCmd = 0.0;
loopcount = 0;
autoStage++;
break;
case 1: // wait for the tote to be off the ground
piloting = false;
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
barrelGrabber->WristDown();
loopcount++;
if(loopcount >= FIRST_PAUSE_TIME) //after the wait, set driving goals
{
xcmd = -0.25; ycmd = 0.0; zcmd = 0.0;
loopcount = 0;
autoStage++;
}
break;
case 2: //wait for elevator at goal and done driving
piloting = false;
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false); //was 15.0
loopcount++;
//printf("stage %d loopcount %d\n", autoStage, loopcount);
if(loopcount >= AUTO_BACK_TIME)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
}
if(elevator->atGoal() && (loopcount >= AUTO_BACK_TIME))
{
//printf("done driving back, loopcount %d\n", loopcount);
loopcount = 0;
autoStage++;
}
break;
case 3: //grab barrel
piloting = false;
elevator->ManualMove(0.0);
barrelGrabber->ClawPinch();
loopcount++;
if(loopcount >= AUTO_WAIT_FOR_PINCH)
{
loopcount = 0;
autoStage++;
}
break;
case 4: //lift barrel
piloting = false;
elevator->ManualMove(0.0);
trolleyMotorCmd = 0.75; //was 0.5
//printf("Trolley: %f motorcmd %f \n", barrelGrabber->GetTrolleyHeight(), trolleyMotorCmd);
autoStage++;
break;
case 5: // wait for the barrel to be off the ground
piloting = false;
elevator->ManualMove(0.0);
//printf("Trolley: %f motorcmd %f \n", barrelGrabber->GetTrolleyHeight(), trolleyMotorCmd);
if(trolleyMotorCmd != 0.0 && barrelGrabber->GetTrolleyHeight() >= AUTO_TROLLEY_HEIGHT)
{
printf("stage %d stopping Trolley\n", autoStage);
trolleyMotorCmd = 0.0;
}
loopcount++;
if(loopcount >= BARREL_PAUSE_TIME) //after the wait, set driving goals
{
// xcmd = -0.25; ycmd = 0.0; zcmd = 0.0;
autoStage++;
loopcount = 0;
}
break;
case 6: //check for trolley at goal, but start sping and move on to next stage
piloting = false;
elevator->ManualMove(0.0);
//printf("Trolley: %f motorcmd %f \n", barrelGrabber->GetTrolleyHeight(), trolleyMotorCmd);
if(trolleyMotorCmd != 0.0 && barrelGrabber->GetTrolleyHeight() >= AUTO_TROLLEY_HEIGHT)
{
//printf("stage %d stopping Trolley\n", autoStage);
trolleyMotorCmd = 0.0;
}
xcmd = 0.0; ycmd = 0.0; zcmd = 2.0;
loopcount = 0;
autoStage++;
break;
case 7: //spin 180 - stop rotating
piloting = false;
elevator->ManualMove(0.0);
//printf("Trolley: %f motorcmd %f \n", barrelGrabber->GetTrolleyHeight(), trolleyMotorCmd);
if(trolleyMotorCmd != 0.0 && barrelGrabber->GetTrolleyHeight() >= AUTO_TROLLEY_HEIGHT)
{
//printf("stage %d stopping Trolley\n", autoStage);
trolleyMotorCmd = 0.0;
}
loopcount++;
if(loopcount >= AUTO_180DEGROT_TIME)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
loopcount = 0;
pilot->StopAll();
autoStage++;
}
break;
case 8: //drive forward to second tote (also making sure to stop trolley when at goal)
piloting = true;
elevator->ManualMove(0.0);
//printf("Trolley: %f motorcmd %f \n", barrelGrabber->GetTrolleyHeight(), trolleyMotorCmd);
if(trolleyMotorCmd != 0.0 && barrelGrabber->GetTrolleyHeight() >= AUTO_TROLLEY_HEIGHT)
{
//printf("stage %d stopping Trolley\n", autoStage);
trolleyMotorCmd = 0.0;
}
//printf("stage %d Driving to %f\n", autoStage, AUTO_DRIVE_SECOND_TOTE);
pilot->SetGoals(AUTO_DRIVE_SECOND_TOTE, 0.0, 0.0);
loopcount = 0;
autoStage++;
break;
case 9: // when arrive at goal, begin squeeze tote (also making sure to stop trolley when at goal)
piloting = true;
elevator->ManualMove(0.0);
//printf("Trolley: %f motorcmd %f \n", barrelGrabber->GetTrolleyHeight(), trolleyMotorCmd);
if(trolleyMotorCmd != 0.0 && barrelGrabber->GetTrolleyHeight() >= AUTO_TROLLEY_HEIGHT)
{
//printf("stage %d stopping Trolley\n", autoStage);
trolleyMotorCmd = 0.0;
}
if(pilot->IsAtGoal())
{
pilot->StopAll();
toteGrabber->GetTote();
toteGrabber->SqueezeTote();
loopcount = 0;
autoStage++;
}
break;
case 10: // wait to until have tote, start to move elevator down
piloting = false;
elevator->ManualMove(0.0);
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
if(toteGrabber->HasTote())
{
loopcount = 0;
autoStage++;
}
break;
case 11: // move forward a little and get the tote
piloting = false;
elevator->ManualMove(0.0);
xcmd = 0.25; ycmd = 0.0; zcmd = 0.0;
loopcount++;
if(loopcount >= AUTO_WAIT_FOR_TOTE)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
pilot->StopAll();
toteGrabber->ReleaseTote();
toteGrabber->StopMotor();
elevator->GoToHeight(1.5, true);
loopcount = 0;
autoStage++;
}
break;
case 12: //elevator going down...
piloting = false;
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
elevator->GoToHeight(1.5, false);
if(elevator->atGoal())
{
//printf("picking up tote 2\n");
elevator->GoToHeight(AUTO_ELEVATOR_STACK, true);
autoStage++;
}
break;
case 13: // wait for the tote to be off the ground
piloting = false;
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
loopcount++;
if(loopcount >= FIRST_PAUSE_TIME) //after the wait, set rotate
{
xcmd = 0.0; ycmd = 0.0; zcmd = -2.0;
autoStage++;
loopcount = 0;
}
break;
case 14: //stop in autozone
piloting = false;
elevator->ManualMove(0.0);
loopcount++;
if(loopcount >= AUTO_90DEGROT_TIMEX2)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
autoStage++;
}
break;
case 15: //drive forward
piloting = false;
elevator->ManualMove(0.0);
xcmd = 0.50; ycmd = 0.0; zcmd = 0.0;
loopcount = 0;
autoStage++;
break;
case 16: //stop in autozone
piloting = false;
elevator->ManualMove(0.0);
loopcount++;
if(loopcount >= AUTO_DRIVE_TIME)
{
xcmd = 0.0; ycmd = 0.0; zcmd = 0.0;
autoStage++;
}
break;
}
if(piloting)
{
//printf("stage %d piloting\n", autoStage);
pilot->Service();
}
else
{
//printf("stage %d driving\n", autoStage);
drive->DriveControl(xcmd, ycmd, zcmd);
}
barrelGrabber->ControlledMove(trolleyMotorCmd);
elevator->Service();
}
void TalonXVI::AutoModeTest()
{
static int loopcount = 0;
switch(autoStage)
{
case 0: //elevator picking up 3rd tote, wait for at height
//drive->DriveControl(0.0, 0.0, 2.0);
pilot->SetGoals(10.0, 30.0, 0.785);
loopcount = 0;
autoStage++;
break;
case 1: //rotate 45 deg
loopcount++;
//drive->DriveControl(0.0, 0.0, 2.0);
if(loopcount >= 50)
{
//drive->DriveControl(0.0, 0.0, 0.0);
//pilot->StopAll();
pilot->SetGoals(60.0, 0.0, 0.0);
loopcount = 0;
autoStage++;
}
break;
case 2:
pilot->SetGoals(60.0, 0.0, 0.0);
loopcount++;
autoStage++;
break;
case 3:
loopcount++;
break;
default:
break;
}
printf("Loops %d ", loopcount);
pilot->Service();
printf("\n");
}
#endif
void TalonXVI::AutoModeTwoTote()
{
static int loopcount = 0;
switch(autoStage)
{
case 0: //START: begin lift first tote
pilot->StopAll(); // ensure reset
elevator->GoToHeight(AUTO_ELEVATOR_STACK, true);
loopcount = 0;
autoStage++;
break;
case 1: // wait for the tote to be off the ground tote one
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
loopcount++;
if(loopcount >= 25) //50 //after the wait, set driving goals
{
pilot->SetGoals(-5.0, 0.0, 0.785);
autoStage++;
loopcount = 0;
}
break;
case 2: // wait for back-up and rotate
loopcount++;
toteGrabber->EjectTote();
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
if(loopcount >= 25) //50)
{
pilot->SetGoals(40.0, 40.0, 0.785);
autoStage++;
loopcount = 0;
}
break;
case 3: // wait for drive forward at angle
loopcount++;
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
if(loopcount >= 30) //40) //50)
{
pilot->SetGoals(40.0, 00.0, 0.0);
autoStage++;
loopcount = 0;
}
break;
case 4: // wait for rotate back and move forward move barrel ONE
loopcount++;
elevator->ManualMove(0.0);
if(loopcount >= 50) //50)
{
pilot->SetGoals(93.0, -10.0, 0.0); //pilot->SetGoals(89.0, -5.0, 0.0);
autoStage++;
toteGrabber->GetTote();
loopcount = 0;
}
break;
case 5: // wait for drive up to totes (2)
loopcount++;
if(loopcount >= 85) //80)
{
toteGrabber->GetTote();
toteGrabber->SqueezeTote();
pilot->ForcedReset();
loopcount = 0;
autoStage++;
}
break;
case 6: //wait for small drive to grab tote
loopcount++;
if(loopcount >= 10 && toteGrabber->HasTote())
{
pilot->SetGoals(100.0, -5.0, 0.0); //pilot->SetGoals(93.0, -5.0, 0.0);
loopcount = 0;
autoStage++;
}
break;
case 7: // move forward a little and get the tote
elevator->ManualMove(0.0);
loopcount++;
if(loopcount >= AUTO_WAIT_FOR_TOTE)
{
toteGrabber->ReleaseTote();
toteGrabber->StopMotor();
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, true);
loopcount = 0;
autoStage++;
}
break;
case 8: //ensure elevator is all the way down
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, false);
if(elevator->atGoal())
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, true);
loopcount = 0;
autoStage++;
//pilot->StopAll();
}
break;
case 9: // wait for the tote to be off the ground tote TWO
loopcount++;
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
autoStage++;
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
break;
case 10: // keep driving and leave stack behind
loopcount++;
if(loopcount >= 110)
{
pilot->ForcedReset();
autoStage++;
loopcount = 0;
}
break;
default:
break;
}
pilot->Service();
printf("autoStage: %d \n", autoStage);
}
void TalonXVI::AutoModeToteStackPilot() // three tote stack with help
{
static int loopcount = 0;
switch(autoStage)
{
case 0: //START: begin lift first tote
pilot->StopAll(); // ensure reset
elevator->GoToHeight(AUTO_ELEVATOR_STACK, true);
loopcount = 0;
autoStage++;
break;
case 1: // wait for the tote to be off the ground tote one
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
loopcount++;
if(loopcount >= 25) //50 //after the wait, set driving goals
{
pilot->SetGoals(-5.0, 0.0, 0.785);
autoStage++;
loopcount = 0;
}
break;
case 2: // wait for back-up and rotate
loopcount++;
toteGrabber->EjectTote();
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
if(loopcount >= 25) //50)
{
pilot->SetGoals(40.0, 40.0, 0.785);
autoStage++;
loopcount = 0;
}
break;
case 3: // wait for drive forward at angle
loopcount++;
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
if(loopcount >= 30) //40) //50)
{
pilot->SetGoals(40.0, 00.0, 0.0);
autoStage++;
loopcount = 0;
}
break;
case 4: // wait for rotate back and move forward move barrel ONE
loopcount++;
elevator->ManualMove(0.0);
if(loopcount >= 50) //50)
{
pilot->SetGoals(93.0, -10.0, 0.0); //pilot->SetGoals(89.0, -5.0, 0.0);
autoStage++;
toteGrabber->GetTote();
loopcount = 0;
}
break;
case 5: // wait for drive up to totes (2)
loopcount++;
if(loopcount >= 85) //80)
{
toteGrabber->GetTote();
toteGrabber->SqueezeTote();
pilot->ForcedReset();
loopcount = 0;
autoStage++;
}
break;
case 6: //wait for small drive to grab tote
loopcount++;
if(loopcount >= 10 && toteGrabber->HasTote())
{
pilot->SetGoals(97.0, -10.0, 0.0); //pilot->SetGoals(93.0, -5.0, 0.0);
loopcount = 0;
autoStage++;
}
break;
case 7: // move forward a little and get the tote
elevator->ManualMove(0.0);
loopcount++;
if(loopcount >= AUTO_WAIT_FOR_TOTE)
{
toteGrabber->ReleaseTote();
toteGrabber->StopMotor();
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, true);
loopcount = 0;
autoStage++;
}
break;
case 8: //ensure elevator is all the way down
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, false);
if(elevator->atGoal())
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, true);
loopcount = 0;
autoStage++;
//pilot->StopAll();
}
break;
case 9: // wait for the tote to be off the ground tote TWO
loopcount++;
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
if(loopcount >= 30) //50) //after the wait, set driving goals
{
pilot->SetGoals(97.0, -10.0, 0.785);
autoStage++;
loopcount = 0;
}
break;
case 10: // wait for rotate
loopcount++;
toteGrabber->EjectTote();
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
if(loopcount >= 30) //50)
{
//pilot->SetGoals(120.0, 25.0, 0.785);
pilot->SetGoals(135.0, 30.0, 0.785);
autoStage++;
loopcount = 0;
}
break;
case 11: // wait for drive forward at angle
loopcount++;
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
}
else
{
elevator->GoToHeight(AUTO_ELEVATOR_STACK, false);
}
if(loopcount >= 30) //50)
{
pilot->SetGoals(135.0, -20.0, 0.0);
autoStage++;
loopcount = 0;
}
break;
case 12: // wait for rotate back and move forward moving barrel TWO
loopcount++;
elevator->ManualMove(0.0);
if(loopcount >= 50) //after the wait, set driving goals
{
pilot->SetGoals(190.0, -20.0, 0.0);
autoStage++;
toteGrabber->GetTote();
loopcount = 0;
}
break;
case 13: // wait to drive up to totes
loopcount++;
if(loopcount >= 85) //100)
{
toteGrabber->GetTote();
toteGrabber->SqueezeTote();
pilot->SetGoals(195.0, -20.0, 0.0);
loopcount = 0;
autoStage++;
}
break;
case 14: //wait for small drive
loopcount++;
if(loopcount >= 10 && toteGrabber->HasTote())
{
toteGrabber->GetTote();
loopcount = 0;
autoStage++;
}
break;
case 15: // move forward a little and get the tote
elevator->ManualMove(0.0);
loopcount++;
if(loopcount >= AUTO_WAIT_FOR_TOTE)
{
pilot->ForcedReset();
toteGrabber->ReleaseTote();
toteGrabber->StopMotor();
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, true);
loopcount = 0;
autoStage++;
}
break;
case 16: //ensure elevator is all the way down tote THREE
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, false);
if(elevator->atGoal())
{
elevator->GoToHeight(AUTO_ELEVATOR_MOVE, true);
loopcount = 0;
autoStage++;
pilot->ForcedReset();
}
break;
case 17: // wait for the tote to be off the ground - rotate and goto AutoZone
elevator->GoToHeight(AUTO_ELEVATOR_MOVE, false);
if(elevator->atGoal())
{
elevator->ManualMove(0.0);
pilot->SetGoals(215.0, 120.0, -1.57);
autoStage++;
loopcount = 0;
}
break;
case 18: // wait for a short time and start dropping the tote stack
loopcount++;
elevator->ManualMove(0.0);
if(loopcount >= AUTO_DROP_DRIVE_TIME)
{
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, true);
autoStage++;
loopcount = 0;
}
break;
case 19: // keep driving and leave stack behind
loopcount++;
elevator->GoToHeight(AUTO_ELEVATOR_BOTTOM, false);
if(loopcount >= 110)
{
pilot->ForcedReset();
autoStage++;
loopcount = 0;
}
break;
default:
break;
}
pilot->Service();
printf("autoStage: %d \n", autoStage);
}
#endif // !CALIBRATION
START_ROBOT_CLASS(TalonXVI);
| [
"noreply@github.com"
] | noreply@github.com |
386ebe5c974acea08288f7ed84b5e88fa21460d9 | b50255cc06f98a8a6fed936333608481865e0a1e | /InspectDLL/stdafx.cpp | 695dbddd8c6aeb600465dd5186ef4ff56a1c5775 | [] | no_license | l1007482035/vs2015TestPrj | 3fdc093789889f3687516804ef8a078fd901c3c8 | 13624b0125d4df46ab4001928dd4fe466347c398 | refs/heads/master | 2021-06-27T12:36:48.592712 | 2021-06-23T09:10:19 | 2021-06-23T09:10:19 | 234,292,573 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 261 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// InspectDLL.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中引用任何所需的附加头文件,
//而不是在此文件中引用
| [
"1007482035@qq.com"
] | 1007482035@qq.com |
1dd13e42c0c2989966e44da2a212255f4e3c84b3 | 2ec590c73e8750d5ea43ab113464164b518731d7 | /PE_Plus_077.cpp | a778c6439846d11f7193bf21069bad8c13c470f2 | [] | no_license | atulmerchia/ProjectEulerPlus | c5a4c05cffc7d49a6dcbb73ad13146a06d67ce2d | 8285a94cf8b1fed4c1f7d7a553b9bd8985061c1b | refs/heads/master | 2020-03-29T14:47:31.325471 | 2018-09-23T23:26:26 | 2018-09-23T23:26:26 | 150,032,837 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 872 | cpp | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
typedef unsigned long long ull;
static vector<ull> ans;
void getAns(){
vector<int> primes;
vector<int> sieve(1000, true);
sieve[0] = sieve[1] = false;
for(int i = 4; i < 1000; i+=2)
sieve[i] = false;
for(int i = 3; i < 32; i+=2)
if(sieve[i])
for(int j = 3*i; j < 1000; j+=2*i)
sieve[j] = false;
for(int i = 0; i < 1000; i++)
if(sieve[i])
primes.push_back(i);
ans.resize(1001, 0);
ans[0] = 1;
for(int i : primes)
for(int j = 0; j <= 1000 - i; j++)
ans[j + i] += ans[j];
}
int main() {
if(!ans.size()) getAns();
int t, n;
cin >> t;
while(t--){
cin >> n;
cout << ans[n] << endl;
}
return 0;
}
| [
"atulmerchia@gmail.com"
] | atulmerchia@gmail.com |
9b8c9242fb4948ce6a6b6d40ace96dc9b6f8ded3 | 2b8514446051b71f690c3192b5c9ff28ad7d895e | /src/base_framework/utility/utility.cpp | d9e54b30072fd1a09699e5e333c08e08b2c8de78 | [] | no_license | xixihaha123-xjh/server_framework | f9292c6e8f23b2ed600eb175ba66f6027d9f0967 | 749f69059de1b8742598122e4575c61a1d4669f8 | refs/heads/master | 2022-11-24T10:49:27.805680 | 2020-08-03T00:06:27 | 2020-08-03T00:06:27 | 280,903,615 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 158 | cpp | #include "utility.h"
namespace utility {
pid_t GetThreadId()
{
return syscall(SYS_gettid);
}
uint32_t GetFiberId()
{
return 0;
}
} | [
"13919250447@163.com"
] | 13919250447@163.com |
5c9fa8fac9a9e068206269cee79097b3531bf60d | 977c82ec23f2f8f2b0da5c57984826e16a22787d | /src/IceRay/main/interface/python/core/material/illumination/ward_isotropic.cpp | 952271b5e85f821d1f147aee733afd21fb7db8e2 | [
"MIT-0"
] | permissive | dmilos/IceRay | 47ce08e2920171bc20dbcd6edcf9a6393461c33e | 84fe8d90110c5190c7f58c4b2ec3cdae8c7d86ae | refs/heads/master | 2023-04-27T10:14:04.743094 | 2023-04-20T14:33:45 | 2023-04-20T15:07:18 | 247,471,987 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,642 | cpp |
#include "../../../def_submodule.hpp"
#include "IceRay/material/compute/instruction.hpp"
#include "IceRay/material/compute/illumination/ward_isotropic.hpp"
void expose_IceRay_material_illumination_ward_isotropic()
{
typedef GS_DDMRM::S_IceRay::S_type::GT_size GTs_size;
typedef GS_DDMRM::S_IceRay::S_type::GT_scalar GTs_scalar;
typedef GS_DDMRM::S_IceRay::S_type::S_color::GT_scalar GTs_color;
typedef GS_DDMRM::S_IceRay::S_type::S_coord::GT_scalar3D GTs_coord3D;
typedef GS_DDMRM::S_IceRay::S_material::S_compute::GC_instruction GTs_instruction;
typedef GS_DDMRM::S_IceRay::S_material::S_compute::S_illumination::S_ward::GC_isotropic GTs_wardIsotropic;
//MAKE_SUBMODULE( IceRay );
MAKE_SUBMODULE( core );
MAKE_SUBMODULE( material );
MAKE_SUBMODULE( illumination );
typedef bool (GTs_wardIsotropic::*Tf_setScalar )( GTs_scalar const& );
typedef GTs_scalar const& (GTs_wardIsotropic::*Tf_getScalar )( void ) const;
typedef bool (GTs_wardIsotropic::*Tf_setColor )( GTs_color const& );
typedef GTs_color const& (GTs_wardIsotropic::*Tf_getColor )( void ) const;
typedef bool (GTs_wardIsotropic::*Tf_setCoord3D )( GTs_coord3D const& );
typedef GTs_coord3D const& (GTs_wardIsotropic::*Tf_getCoord3D )( void ) const;
typedef boost::python::class_<GTs_wardIsotropic, boost::python::bases< GTs_instruction > > Tf_this;
boost::python::object I_this = Tf_this( "MaterialIlluminationWardIsotropic" )
.def( boost::python::init<>() )
.def( boost::python::init<GTs_size,GTs_size,GTs_size,GTs_size,GTs_size,GTs_size>() )
//.def( "interval", >s_wardIsotropic::F_get, boost::python::return_value_policy<boost::python::copy_const_reference>() )
//.def( "interval", >s_wardIsotropic::F_set )
;
boost::python::scope I_scope = I_this;
boost::python::enum_<GTs_wardIsotropic::Ee_input>( "Input" )
.value( "SpotBegin", GTs_wardIsotropic::En_inSize_SpotBegin )
.value( "SpotEnd", GTs_wardIsotropic::En_inSize_SpotEnd )
.value( "Specular", GTs_wardIsotropic::En_inColor_Specular )
.value( "Alpha", GTs_wardIsotropic::En_inColor_Alpha )
.value( "point", GTs_wardIsotropic::En_inCoord_Point )
.value( "normal", GTs_wardIsotropic::En_inCoord_Normal )
.export_values()
;
boost::python::enum_<GTs_wardIsotropic::Ee_output>( "Output" )
.value( "result", GTs_wardIsotropic::En_outColor_result )
.export_values()
;
}
| [
"dmilos@gmail.com"
] | dmilos@gmail.com |
7ff9162aedbdc1531462f00d6f310b3d8eed1702 | 10da9bb0477bf0042fc0490eb09bb63fa93f0d87 | /Praktikum_2_1/main.cpp | c7838142014f4dadce0cf5507ef9cc6fce0d03a1 | [] | no_license | mrmosch/ADS-Praktikum-SS18 | a5b259b13701c1f4fb879b72e5dbcac01c80fc72 | 187574599700e7a9fa1801ce25ce3f92b404e63a | refs/heads/master | 2020-05-05T07:38:07.037671 | 2020-04-02T13:58:19 | 2020-04-02T13:58:19 | 179,832,087 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,420 | cpp | #include <iostream>
#include <string>
using namespace std;
#include "RingPuffer.h"
void einfuegen(RingPuffer& ring)
{
cout << "+Neuen Datensatz einfuegen\n";
cout << "Beschreibung ?> ";
string beschreibung; getline(cin, beschreibung);
cout << "Daten ?> ";
string daten; getline(cin, daten);
if(ring.addNode(beschreibung, daten))
cout << "+Ihr Datensatz wurde hinzugefuegt\n";
}
void suchen(RingPuffer& ring)
{
cout << "+Nach welchen Daten soll gesucht werden?\n"
<< "?> ";
string daten; getline(cin, daten);
if (!ring.search(daten))
cout << "+Der gesuchte Datensatz wurde nicht gefunden.\n";
}
void menu(RingPuffer& ring)
{
ring.trennlinie('=', 34);
cout << "OneRingToRuleThemAll v0.1, by Sauron Schmidt\n";
ring.trennlinie('=', 34);
// Auswahl
int auswahl = 0;
cout << "1) Backup einfuegen\n"
<< "2) Backup suchen\n"
<< "3) Alle Backups ausgeben\n"
<< "?> "; cin >> auswahl;
cin.ignore(); cin.clear();
switch (auswahl)
{
case 1: // Backup einfuegen
einfuegen(ring);
break;
case 2: // Backup suchen
suchen(ring);
break;
case 3: // Alle Backups ausgeben
ring.print();
break;
default:
cout << "Falsche Eingabe! Bitte fuehren Sie das Programm erneut aus." << endl;
}
}
int main()
{
RingPuffer ring;
char weiter;
do {
menu(ring);
cout << "Soll eine weitere Aktion ausgefuehrt werden? (j/n)\n"
<< "> "; cin >> weiter;
} while (weiter == 'j');
system("PAUSE");
return 0;
} | [
"daniel-95-binas@live.de"
] | daniel-95-binas@live.de |
8b54458e0440d2394a4600abbb917d3d133ee684 | 85efd8f08024725b0ab2e21cbc0ce9a85228f108 | /textedit.cpp | d29773c2be815e5946b17d08c5645dc3d4762f97 | [] | no_license | qjcn/qjcn | a6cdfab6c68b12bf5d01fb42934a6b4b9cb43060 | b44b22025f2459ad25a5c36bd54e295f73caa242 | refs/heads/master | 2016-09-05T20:52:15.534585 | 2015-03-16T18:03:06 | 2015-03-16T18:03:06 | 32,332,409 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 12,766 | cpp | #include "textedit.h"
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QTextCodec>
#include <QtCore/QtDebug>
#ifdef WITH_QT5
#include <QtPrintSupport/QPrintDialog>
#include <QtPrintSupport/QPrinter>
#include <QtPrintSupport/QPrintPreviewDialog>
#include <QtGui/QClipboard>
#include <QtGui/QFontDatabase>
#include <QtGui/QTextCursor>
#include <QtGui/QTextDocumentWriter>
#include <QtGui/QTextList>
#include <QtGui/QCloseEvent>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QColorDialog>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QFontComboBox>
#include <QtWidgets/QFileDialog>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QPlainTextEdit>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QMessageBox>
#else
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QClipboard>
#include <QtGui/QColorDialog>
#include <QtGui/QComboBox>
#include <QtGui/QFontComboBox>
#include <QtGui/QFileDialog>
#include <QtGui/QFontDatabase>
#include <QtGui/QMenu>
#include <QtGui/QMenuBar>
#include <QtGui/QPrintDialog>
#include <QtGui/QPrinter>
#include <QtGui/QTextEdit>
#include <QtGui/QPlainTextEdit>
#include <QtGui/QToolBar>
#include <QtGui/QTextCursor>
#include <QtGui/QTextDocumentWriter>
#include <QtGui/QTextList>
#include <QtGui/QCloseEvent>
#include <QtGui/QMessageBox>
#include <QtGui/QPrintPreviewDialog>
#endif
#include "FileChkSum.h"
const QString rsrcPath = ":/ted_images";
// ---------------------------------------------------------------------------
TextEdit::TextEdit(QWidget * parent)
: QMainWindow(parent, Qt::Dialog)
{
setWindowModality (Qt::ApplicationModal);
setupFileActions();
setupEditActions();
{
QMenu *helpMenu = new QMenu(tr("Help"), this);
menuBar()->addMenu(helpMenu);
helpMenu->addAction(tr("About"), this, SLOT(about()));
}
textEdit = new QPlainTextEdit(this);
// textEdit->setLineWrapMode(QTextEdit::NoWrap);
connect(textEdit, SIGNAL(currentCharFormatChanged(const QTextCharFormat &)),
this, SLOT(currentCharFormatChanged(const QTextCharFormat &)));
connect(textEdit, SIGNAL(cursorPositionChanged()),
this, SLOT(cursorPositionChanged()));
setCentralWidget(textEdit);
textEdit->setFocus();
setCurrentFileName(QString());
connect(textEdit->document(), SIGNAL(modificationChanged(bool)),
actionSave, SLOT(setEnabled(bool)));
connect(textEdit->document(), SIGNAL(modificationChanged(bool)),
this, SLOT(setWindowModified(bool)));
connect(textEdit->document(), SIGNAL(undoAvailable(bool)),
actionUndo, SLOT(setEnabled(bool)));
connect(textEdit->document(), SIGNAL(redoAvailable(bool)),
actionRedo, SLOT(setEnabled(bool)));
setWindowModified(textEdit->document()->isModified());
actionSave->setEnabled(textEdit->document()->isModified());
actionUndo->setEnabled(textEdit->document()->isUndoAvailable());
actionRedo->setEnabled(textEdit->document()->isRedoAvailable());
connect(actionUndo, SIGNAL(triggered()), textEdit, SLOT(undo()));
connect(actionRedo, SIGNAL(triggered()), textEdit, SLOT(redo()));
actionCut->setEnabled(false);
actionCopy->setEnabled(false);
connect(actionCut, SIGNAL(triggered()), textEdit, SLOT(cut()));
connect(actionCopy, SIGNAL(triggered()), textEdit, SLOT(copy()));
connect(actionPaste, SIGNAL(triggered()), textEdit, SLOT(paste()));
connect(textEdit, SIGNAL(copyAvailable(bool)), actionCut, SLOT(setEnabled(bool)));
connect(textEdit, SIGNAL(copyAvailable(bool)), actionCopy, SLOT(setEnabled(bool)));
connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(clipboardDataChanged()));
QString initialFile = ":/example.html";
const QStringList args = QCoreApplication::arguments();
if (args.count() == 2)
initialFile = args.at(1);
if (!load(initialFile))
fileNew();
}
// ---------------------------------------------------------------------------
void TextEdit::closeEvent(QCloseEvent *e)
{
if (maybeSave())
e->accept();
else
e->ignore();
}
// ---------------------------------------------------------------------------
void
TextEdit::setupFileActions()
{
QToolBar *tb = new QToolBar(this);
tb->setWindowTitle(tr("File Actions"));
addToolBar(tb);
QMenu *menu = new QMenu(tr("&File"), this);
menuBar()->addMenu(menu);
QAction *a;
a = new QAction(QIcon(rsrcPath + "/filenew.png"), tr("&New"), this);
a->setShortcut(QKeySequence::New);
connect(a, SIGNAL(triggered()), this, SLOT(fileNew()));
tb->addAction(a);
menu->addAction(a);
a = new QAction(QIcon(rsrcPath + "/fileopen.png"), tr("&Open..."), this);
a->setShortcut(QKeySequence::Open);
connect(a, SIGNAL(triggered()), this, SLOT(fileOpen()));
tb->addAction(a);
menu->addAction(a);
menu->addSeparator();
actionSave = a = new QAction(QIcon(rsrcPath + "/filesave.png"), tr("&Save"), this);
a->setShortcut(QKeySequence::Save);
connect(a, SIGNAL(triggered()), this, SLOT(fileSave()));
a->setEnabled(false);
tb->addAction(a);
menu->addAction(a);
a = new QAction(tr("Save &As..."), this);
connect(a, SIGNAL(triggered()), this, SLOT(fileSaveAs()));
menu->addAction(a);
menu->addSeparator();
#ifndef QT_NO_PRINTER
a = new QAction(QIcon(rsrcPath + "/fileprint.png"), tr("&Print..."), this);
a->setShortcut(QKeySequence::Print);
connect(a, SIGNAL(triggered()), this, SLOT(filePrint()));
tb->addAction(a);
menu->addAction(a);
a = new QAction(QIcon(rsrcPath + "/fileprint.png"), tr("Print Preview..."), this);
connect(a, SIGNAL(triggered()), this, SLOT(filePrintPreview()));
menu->addAction(a);
a = new QAction(QIcon(rsrcPath + "/exportpdf.png"), tr("&Export PDF..."), this);
a->setShortcut(Qt::CTRL + Qt::Key_D);
connect(a, SIGNAL(triggered()), this, SLOT(filePrintPdf()));
tb->addAction(a);
menu->addAction(a);
menu->addSeparator();
#endif
a = new QAction(tr("&Quit"), this);
a->setShortcut(Qt::CTRL + Qt::Key_Q);
connect(a, SIGNAL(triggered()), this, SLOT(close()));
menu->addAction(a);
}
// ---------------------------------------------------------------------------
void
TextEdit::setupEditActions()
{
QToolBar *tb = new QToolBar(this);
tb->setWindowTitle(tr("Edit Actions"));
addToolBar(tb);
QMenu *menu = new QMenu(tr("&Edit"), this);
menuBar()->addMenu(menu);
QAction *a;
a = actionUndo = new QAction(QIcon(rsrcPath + "/editundo.png"), tr("&Undo"), this);
a->setShortcut(QKeySequence::Undo);
tb->addAction(a);
menu->addAction(a);
a = actionRedo = new QAction(QIcon(rsrcPath + "/editredo.png"), tr("&Redo"), this);
a->setShortcut(QKeySequence::Redo);
tb->addAction(a);
menu->addAction(a);
menu->addSeparator();
a = actionCut = new QAction(QIcon(rsrcPath + "/editcut.png"), tr("Cu&t"), this);
a->setShortcut(QKeySequence::Cut);
tb->addAction(a);
menu->addAction(a);
a = actionCopy = new QAction(QIcon(rsrcPath + "/editcopy.png"), tr("&Copy"), this);
a->setShortcut(QKeySequence::Copy);
tb->addAction(a);
menu->addAction(a);
a = actionPaste = new QAction(QIcon(rsrcPath + "/editpaste.png"), tr("&Paste"), this);
a->setShortcut(QKeySequence::Paste);
tb->addAction(a);
menu->addAction(a);
actionPaste->setEnabled(!QApplication::clipboard()->text().isEmpty());
}
// ---------------------------------------------------------------------------
bool TextEdit::load(const QString &f)
{
if (!QFile::exists(f))
return false;
QFile file(f);
if (!file.open(QFile::ReadOnly))
return false;
QByteArray data = file.readAll();
textEdit->setPlainText(data);
setCurrentFileName(f);
return true;
}
// ---------------------------------------------------------------------------
bool
TextEdit::maybeSave()
{
if (!textEdit->document()->isModified())
return true;
if (fileName.startsWith(QLatin1String(":/")))
return true;
QMessageBox::StandardButton ret;
ret = QMessageBox::warning(this, tr("Application"),
tr("The document has been modified.\n"
"Do you want to save your changes?"),
QMessageBox::Save | QMessageBox::Discard
| QMessageBox::Cancel);
if (ret == QMessageBox::Save)
return fileSave();
else
if (ret == QMessageBox::Cancel)
return false;
return true;
}
// ---------------------------------------------------------------------------
void
TextEdit::setCurrentFileName(const QString &fileName)
{
this->fileName = fileName;
textEdit->document()->setModified(false);
QString shownName;
if (fileName.isEmpty())
shownName = "untitled.txt";
else
shownName = QFileInfo(fileName).fileName();
setWindowTitle(tr("%1[*] - %2").arg(shownName).arg(tr("Rich Text")));
setWindowModified(false);
}
// ---------------------------------------------------------------------------
void
TextEdit::fileNew()
{
if (maybeSave())
{
textEdit->clear();
setCurrentFileName(QString());
}
}
// ---------------------------------------------------------------------------
void
TextEdit::fileOpen()
{
QString fn = QFileDialog::getOpenFileName(this, tr("Open File..."),
QString(), tr("HTML-Files (*.htm *.html);;All Files (*)"));
if (!fn.isEmpty())
load(fn);
}
// ---------------------------------------------------------------------------
bool
TextEdit::fileSave()
{
if (fileName.isEmpty())
return fileSaveAs();
QTextDocumentWriter writer(fileName);
bool success = writer.write(textEdit->document());
if (success)
textEdit->document()->setModified(false);
return success;
}
// ---------------------------------------------------------------------------
bool
TextEdit::fileSaveAs()
{
QString fn = QFileDialog::getSaveFileName(this, tr("Save as..."),
QString(), tr("TXT files (*.txt);;All Files (*)"));
if (fn.isEmpty())
return false;
if (! fn.endsWith(".txt", Qt::CaseInsensitive) )
fn += ".txt"; // default
setCurrentFileName(fn);
return fileSave();
}
// ---------------------------------------------------------------------------
void
TextEdit::filePrint()
{
#ifndef QT_NO_PRINTER
QPrinter printer(QPrinter::HighResolution);
QPrintDialog *dlg = new QPrintDialog(&printer, this);
if (textEdit->textCursor().hasSelection())
dlg->addEnabledOption(QAbstractPrintDialog::PrintSelection);
dlg->setWindowTitle(tr("Print Document"));
if (dlg->exec() == QDialog::Accepted) {
textEdit->print(&printer);
}
delete dlg;
#endif
}
// ---------------------------------------------------------------------------
void
TextEdit::filePrintPreview()
{
#ifndef QT_NO_PRINTER
QPrinter printer(QPrinter::HighResolution);
QPrintPreviewDialog preview(&printer, this);
connect(&preview, SIGNAL(paintRequested(QPrinter *)), SLOT(printPreview(QPrinter *)));
preview.exec();
#endif
}
// ---------------------------------------------------------------------------
/*
void
TextEdit::printPreview(QPrinter * printer)
{
#ifdef QT_NO_PRINTER
Q_UNUSED(printer);
#else
textEdit->print(printer);
#endif
}
*/
// ---------------------------------------------------------------------------
void
TextEdit::filePrintPdf()
{
#ifndef QT_NO_PRINTER
//! [0]
QString fileName = QFileDialog::getSaveFileName(this, "Export PDF",
QString(), "*.pdf");
if (!fileName.isEmpty()) {
if (QFileInfo(fileName).suffix().isEmpty())
fileName.append(".pdf");
QPrinter printer(QPrinter::HighResolution);
printer.setOutputFormat(QPrinter::PdfFormat);
printer.setOutputFileName(fileName);
textEdit->document()->print(&printer);
}
//! [0]
#endif
}
// ---------------------------------------------------------------------------
void
TextEdit::clipboardDataChanged()
{
actionPaste->setEnabled(!QApplication::clipboard()->text().isEmpty());
}
// ---------------------------------------------------------------------------
void
TextEdit::about()
{
QMessageBox::about(this, tr("About"), tr("JCN File Edtor"));
}
// ---------------------------------------------------------------------------
| [
"qjcn@appqloud.com"
] | qjcn@appqloud.com |
5877b909aba52b3e424c2bd194465de808f8e2ac | 9a631fb3bc2f3ae1b53cd476379184fbb57e5704 | /Chemistry/tools/fuego/Pythia/config/compiler/MIPSpro-7.3/cstdlib | f8cb30c06d634e45b7f403c2cd320c435ea6a71a | [] | no_license | pinebai/Combustion | 93827d255a4e875a1e9c9a6b8c4dd79446b1bb2d | 701f6a56a44fe04c30e7e4f25436c54e46ee688f | refs/heads/development | 2021-06-21T21:56:54.419981 | 2017-08-25T22:51:33 | 2017-08-25T22:51:33 | 104,155,122 | 3 | 4 | null | 2017-09-20T02:29:33 | 2017-09-20T02:29:33 | null | UTF-8 | C++ | false | false | 2,201 | // -*- C++ -*-
//
//--------------------------------------------------------------------------
//
//
// Michael A.G. Aivazis
// California Institute of Technology
// (C) 1999 All Rights Reserved
//
//--------------------------------------------------------------------------
// $Log: cstdlib,v $
// Revision 1.5 2003/04/10 02:10:42 aivazis
// Added getenv
//
// Revision 1.4 2001/11/30 03:01:07 cummings
// Since wchar_t is provided as a keyword by the SGI C++ compiler, we
// cannot inject this symbol into the std namespace. I have removed
// this to avoid confusing the EDG parser used by PDT/TAU.
//
// Revision 1.3 2001/06/12 19:10:57 cummings
// Added include guards to these replacement header files.
//
// Revision 1.2 2001/05/25 21:12:32 cummings
// Check if wchar_t is a keyword before attempting to import symbol into namespace std.
//
// Revision 1.1 2001/04/19 01:40:52 cummings
// Replacements for the remaining new-style C headers that are
// missing from the MIPSpro compiler header file set. Each file
// includes the corresponding standard C header file and then
// imports types and functions from the global namespace into
// namespace std, so that they can be used in the standard way.
// I have attempted to import only ANSI standard items.
//
//
#if !defined(__config_compiler_cstdlib__)
#define __config_compiler_cstdlib__
//
// Deficiency file: route cstdlib to stdlib.h
// and import symbols into namespace std
//
#include <stdlib.h>
namespace std {
/* Standard C library functions and structures */
using ::div_t;
using ::ldiv_t;
using ::size_t;
using ::ssize_t;
using ::atof;
using ::atoi;
using ::atol;
using ::strtod;
using ::strtol;
using ::strtoul;
using ::rand;
using ::srand;
using ::calloc;
using ::free;
using ::malloc;
using ::realloc;
using ::abort;
using ::atexit;
using ::exit;
using ::getenv;
using ::system;
using ::bsearch;
using ::qsort;
using ::abs;
using ::div;
using ::labs;
using ::ldiv;
using ::mbtowc;
using ::mblen;
using ::wctomb;
using ::mbstowcs;
using ::wcstombs;
using ::getenv;
}
#endif
// End of file
| [
"MSDay@lbl.gov"
] | MSDay@lbl.gov | |
f694bb1b229fe8d9afd45c61c02cc94a9ac9d577 | 5517fd00768d2a51c65896a199874dda7fcb31f3 | /main.cc | daa6949f634d089edf0cda462632e9e7815ea964 | [] | no_license | celloasleep/musical-palm-tree | b199ad1a4d7f29104d7e70bc8edf4d0382e62e6e | 5faee785bec973192145e08a6ceba15640beaceb | refs/heads/master | 2020-12-03T01:42:23.553120 | 2017-07-28T06:07:57 | 2017-07-28T06:07:57 | 95,853,614 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 194 | cc | #include <iostream>
void main(int argc, char *argv[])
{
std::cout << "see the world" << std::endl;
std::cout << "add after the creation of the new branch" << std::endl;
return 0;
}
| [
"linhong.jiang@ygomi.com"
] | linhong.jiang@ygomi.com |
95837e1e34541410a474bc144db05ca0ce5ec09c | 26aea82ed3815751053a133d9190389add667b23 | /fluffy-dollop/ctrcore/visual/abstracttilemapper.cpp | c19d3b7b1585d5c49524cbe89419900835c4fdc6 | [] | no_license | autocomp/fluffy-dollop | f8d234151f3ca91664cf3361f6b2cd6646bf7b95 | c7ebd5a26016a604ce42a3c829253ba1a1e58537 | refs/heads/master | 2020-04-06T04:01:01.085460 | 2017-03-06T17:36:53 | 2017-03-06T17:36:53 | 83,069,411 | 2 | 1 | null | 2017-03-12T11:24:59 | 2017-02-24T18:10:50 | C++ | UTF-8 | C++ | false | false | 3,308 | cpp | #include "abstracttilemapper.h"
#include <QDebug>
#include <QPolygonF>
#include <math.h>
#include <ctrcore/provider/dataproviderfactory.h>
using namespace visualize_system;
AbstractTileMapper::AbstractTileMapper(uint providerId, const SceneDescriptor &_sceneDescriptor)
: sceneDescriptor(_sceneDescriptor)
, bytesPerPixel(32/8)
, rasterMapperCoef(1)
{
QSharedPointer<data_system::AbstractDataProvider> ptr = data_system::DataProviderFactory::instance()->getProvider(providerId);
raster_provider = ptr.dynamicCast<data_system::RasterDataProvider>();
}
AbstractTileMapper::~AbstractTileMapper()
{
}
void AbstractTileMapper::init(QPointF shift, QRectF sceneRect, double coef)
{
shiftImageOnScene = shift;
rasterSceneRect = sceneRect;
rasterMapperCoef = coef;
}
QSharedPointer<data_system::RasterDataProvider> AbstractTileMapper::provider() const
{
return raster_provider;
}
image_types::TImage * AbstractTileMapper::normalizeTImage(image_types::TImage *src, QPoint shiftImageInTile)
{
if(shiftImageInTile == QPoint(-1,-1))
shiftImageInTile = QPoint(0,0);
image_types::TImage *dest = new image_types::TImage;
dest->depth = 32;
dest->w = sceneDescriptor.tileSize().width();
dest->h = sceneDescriptor.tileSize().height();
dest->prt = new char[dest->w * dest->h * bytesPerPixel];
memset(dest->prt, 0, dest->w * dest->h * bytesPerPixel);
int destLine = dest->w * bytesPerPixel;
int destShiftX = bytesPerPixel * shiftImageInTile.x();
int destShiftY = destLine * shiftImageInTile.y();
for (int y = 0; y < src->h; y++)
for (int x = 0; x < src->w; x++)
memcpy(dest->prt + destShiftY + destLine*y + destShiftX + x*bytesPerPixel,
src->prt + y * src->w * bytesPerPixel + x * bytesPerPixel,
bytesPerPixel);
return dest;
}
/////////////////////////////////////////////////////////////////////////////////
QPointF AbstractTileMapper::geoToScene(const QPointF& coordinateIn)
{
const uint W(sceneDescriptor.sceneSize().width());
const uint H(sceneDescriptor.sceneSize().height());
QPointF point;
point.setX( (coordinateIn.y() +180 )*W/360.0 ); // long
point.setY( ( -coordinateIn.x() + 90)*( H)/180.0 ); //latt
return point;
}
QPointF AbstractTileMapper::sceneToGeo(const QPointF& point)
{
const uint W(sceneDescriptor.sceneSize().width());
const uint H(sceneDescriptor.sceneSize().height());
double longitude = (point.x()*(360. / W))-180.;
double latitude = -(point.y()*(180. / H))+90.;
return QPointF(latitude, longitude);
}
QRectF AbstractTileMapper::getTileExtend(int x, int y, int z)
{
double POW(pow(2,z-1));
double tileWidthOnView(sceneDescriptor.tileSize().width() / POW);
double tileHeightOnView(sceneDescriptor.tileSize().height() / POW);
QRectF tileSceneRect(tileWidthOnView*x, tileHeightOnView*y, tileWidthOnView, tileHeightOnView);
QPolygonF sceneRectPolygon(tileSceneRect), geoRectPolygon;
foreach(QPointF p, sceneRectPolygon)
{
double x(p.x()), y(p.y());
sceneDescriptor.convertSceneToRefSystem(x,y);
geoRectPolygon.append(QPointF(x,y));
// geoRectPolygon.append(sceneToGeo(p));
}
return geoRectPolygon.boundingRect();
}
| [
"vs.zaharchenko@gmail.com"
] | vs.zaharchenko@gmail.com |
2c84942f231c7371b899ba5def69aab4d0c666bf | 3dd60415e8be4c470968bd4cb64e0c45079a47d1 | /src/CurveMatching/CurveSignature.h | e0159324bee8628db0a099a5de19023a9a94a9fe | [
"MIT"
] | permissive | jmlien/mesh_unfolder | ecec52794b8bb95c2d25fbfff0443ea0c03bf762 | 3f1ed2f4b906a57bebf7b35ed75c7c3fa976de58 | refs/heads/master | 2022-12-08T01:02:00.420232 | 2020-09-01T15:29:40 | 2020-09-01T15:29:40 | 98,562,765 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,017 | h | /*
* CurveSignature.h
* CurveMatching
*
* Created by Roy Shilkrot on 12/7/12.
* Copyright (c) 2013 MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*
*/
#pragma once
#include <opencv2/core/core.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <sys/stat.h>
#include "CurveMatching/opencvstd.h"
using namespace cv;
//
#ifdef ENABLE_PROFILE
#define CV_PROFILE_MSG(msg,code) \
{\
std::cout << msg << " ";\
double __time_in_ticks = (double)cv::getTickCount();\
{ code }\
std::cout << "DONE " << ((double)cv::getTickCount() - __time_in_ticks)/cv::getTickFrequency() << "s" << std::endl;\
}
#define CV_PROFILE(code) \
{\
std::cout << #code << " ";\
double __time_in_ticks = (double)cv::getTickCount();\
{ code }\
std::cout << "DONE " << ((double)cv::getTickCount() - __time_in_ticks)/cv::getTickFrequency() << "s" << std::endl;\
}
#else
#define CV_PROFILE_MSG(msg,code) code
#define CV_PROFILE(code) code
#endif
class CurveMatcher
{
public:
//in this class position type is int for measuing vertex location
typedef int position_type;
CurveMatcher()
{
RESAMPLE_SIZE=200; //curve resample size
SMALLEST_CURVE_SIZE=50; //smalles curve in the segment DB
LONGEST_CURVE_SIZE = RESAMPLE_SIZE / 2;
OFFSET_STEP=2; //curve segment DB offset incremental size
CURVATURE_FILTER_SIZE=200; //number of matches that will pass through curvature filter
}
//---
// set source/target of the match
//---
void setSource(const string& filename);
void setSource(const vector<cv::Point>& a);
void setSource(const vector<cv::Point2d>& a);
vector<cv::Point2d>& getSource(){ return source; }
void setTarget(const string& filename);
void setTarget(const vector<cv::Point>& b);
void setTarget(const vector<cv::Point2d>& b);
vector<cv::Point2d>& getTarget(){ return target; }
// THE MAIN Function: match the source to the target
void CompareCurvesUsingSignatureDB(int& a_len, int& a_off, int& b_len, int& b_off, double& score)
{
vector<cv::Point2d> ad; ConvertCurve(source, ad);
vector<cv::Point2d> bd; ConvertCurve(target, bd);
CompareCurvesUsingSignatureDB(ad, bd, a_len, a_off, b_len, b_off, score);
}
void CompareCurvesUsingSignatureDB(
vector<cv::Point>& a_DB_params, vector<vector<double> > & a_DB,
vector<cv::Point>& b_DB_params, vector<vector<double> > & b_DB,
int& a_len,
int& a_off,
int& b_len,
int& b_off,
double& score
);
template<typename T>
void PrepareSignatureDB(const vector<cv::Point_<T> >& curve, vector<vector<double> >& DB, vector<cv::Point>& DB_params) {
vector<cv::Point2d> curved; ConvertCurve(curve, curved);
PrepareSignatureDB(curved, DB, DB_params);
}
// prepare curve segment database for comparisons among the shadwos casted by the same model
// In this case, we would like the min_curve at least half of the given curve.
template<typename T>
void PrepareSignatureDB_For_IntraModel_Comparison(const vector<cv::Point_<T> >& curve, vector<vector<double> >& DB, vector<cv::Point>& DB_params)
{
vector<cv::Point2d> curved; ConvertCurve(curve, curved);
PrepareSignatureDB_For_IntraModel_Comparison(curved, DB, DB_params);
}
//given a match compute transform
void computeTransform(int a_len, int a_off, int b_len, int b_off, cv::Mat& transform);
void computeTransform(vector<cv::Point2d>& a_subset, vector<cv::Point2d>& b_subset, cv::Mat& transform);
//visualize the match
void visualizeMatching(int a_len, int a_off, int b_len, int b_off);
//render matching into an image with name "filename"
void renderMatching(const string& filename, int a_len, int a_off, int b_len, int b_off);
void drawMatching(cv::Mat& outout, vector<cv::Point2d> & a_subset, vector<cv::Point2d> & b_subset);
//compute RMSE of the match
double ComputeRMSE(int a_len, int a_off, int b_len, int b_off);
double ComputeRMSE(vector<cv::Point2d>& a_subset, vector<cv::Point2d>& b_subset);
//compute RMSE of the whole curve using the match
double ComputeWholeRMSE(int a_len, int a_off, int b_len, int b_off);
//
//
// Access functions!
//
//
//get the length of a given curve
//in this case, all given curves will be resampled into RESAMPLE_SIZE vertices
//so the length is always RESAMPLE_SIZE
int getLength(const vector<cv::Point >& curve) { return RESAMPLE_SIZE; }
void setCurveResampleSize(int size)
{
if (size <= 0){
cerr << "! Warning: CurveMatcher::setCurveResampleSize has size < 0" << endl; return;
}
RESAMPLE_SIZE = size;
}
int getCurveResampleSize() const { return RESAMPLE_SIZE; }
void setSmallestCurveSegmentSize(int size)
{
if (size <= 0){
cerr << "! Warning: CurveMatcher::setSmallestCurveSegmentSize has size < 0" << endl; return;
}
SMALLEST_CURVE_SIZE = size; //smalles curve in the segment DB
}
int getSmallestCurveSegmentSize() const { return SMALLEST_CURVE_SIZE; }
void setLongestCurveSegmentSize(int size)
{
if (size <= 0 || size >= RESAMPLE_SIZE)
{
cerr << "! Warning: CurveMatcher::setLongestCurveSegmentSize has size smaller than 0 or greater than " << RESAMPLE_SIZE << endl; return;
}
LONGEST_CURVE_SIZE = size;
}
int getLongestCurveSegmentSize() const { return LONGEST_CURVE_SIZE; }
void setOffsetStepSize(int size)
{
if (size <= 0){
cerr << "! Warning: CurveMatcher::setOffsetStepSize has size < 0" << endl; return;
}
OFFSET_STEP = size; //curve segment DB offset incremental size
}
int getOffsetStepSize() const { return OFFSET_STEP; }
void setCurvatureFilterSize(int size)
{
if (size <= 0) return;
CURVATURE_FILTER_SIZE = size; //number of matches that will pass through curvature filter
}
int getCurvatureFilterSize() const { return CURVATURE_FILTER_SIZE; }
//get a subset of curve
template<typename PT>
void getSubset(const vector<PT>& curve, int arclen, int offset, vector<PT>& subcurve)
{
//make sure that the size of the curve is the same as the RESAMPLE_SIZE
if (curve.size() != RESAMPLE_SIZE)
{
vector<PT> tmp;
ResampleCurve(curve, tmp, RESAMPLE_SIZE, false);
subcurve.insert(subcurve.end(), tmp.begin() + offset, tmp.begin() + offset + arclen);
}
else
{
subcurve.insert(subcurve.end(), curve.begin() + offset, curve.begin() + offset + arclen);
}
//
}
//load curve from image
template <typename T>
void GetCurveForImage(const cv::Mat& filename, vector<cv::Point_<T> >& curve, bool onlyUpper = true, bool getLower = false)
{
vector<cv::Point> curve_2i;
GetCurveForImage(filename, curve_2i, onlyUpper, getLower);
ConvertCurve(curve_2i, curve);
}
//this prepares the curve segment database for both a and b
void CompareCurvesUsingSignatureDB
(const vector<cv::Point>& a_DB_params,
const cv::Point& b_DB_params,
const vector<vector<double> >& a_DB,
const vector<double>& b_DB,
cv::DMatch& best_match);
void CompareCurvesUsingSignatureDB_curvature_only
(const vector<cv::Point>& a_DB_params,
const cv::Point& b_DB_params,
const vector<vector<double> >& a_DB,
const vector<double>& b_DB,
cv::DMatch& best_match);
//this prepares the curve segment database for both a and b
void CompareCurvesUsingSignatureDB(const vector<cv::Point>& a_DB_params,
const vector<cv::Point>& b_DB_params,
const vector<vector<double> >& a_DB,
const vector<vector<double> >& b_DB,
vector<pair<double, cv::DMatch> >& scores_to_matches
);
//this prepares the curve segment database for both a and b
void CompareCurvesUsingSignatureDB(const vector<cv::Point2d>& a,
const vector<cv::Point2d>& b,
int& a_len,
int& a_off,
int& b_len,
int& b_off,
double& score
);
protected:
bool fileExists(const std::string& filename);
template<typename T>
int closestPointOnCurveToPoint(const vector<cv::Point_<T> >& _tmp, const cv::Point& checkPt, const T cutoff) {
vector<cv::Point_<T> > tmp = _tmp;
Mat(tmp) -= Scalar(checkPt.x, checkPt.y);
vector<float> tmpx, tmpy, tmpmag;
PolyLineSplit(tmp, tmpx, tmpy);
magnitude(tmpx, tmpy, tmpmag);
double minDist = -1;
cv::Point minLoc; minMaxLoc(tmpmag, &minDist, 0, &minLoc);
if (minDist < cutoff)
return minLoc.x;
else
return -1;
}
template<typename T>
void saveCurveToFile(const vector<cv::Point_<T> >& curve) {
static int curve_id = 0;
stringstream ss; ss << "curves/curves_" << (curve_id++) << ".txt";
while (fileExists(ss.str())) {
ss.str("");
ss << "curves/curves_" << (curve_id++) << ".txt";
}
ofstream ofs(ss.str().c_str());
ofs << curve.size() << "\n";
for (int i = 0; i < curve.size(); i++) {
ofs << curve[i].x << " " << curve[i].y << "\n";
}
cout << "saved " << ss.str() << "\n";
}
template<typename T>
vector<cv::Point_<T> > loadCurveFromFile(const string& filename) {
vector<cv::Point_<T> > curve;
ifstream ifs(filename.c_str());
int curve_size; ifs >> skipws >> curve_size;
while (!ifs.eof()) {
T x, y;
ifs >> x >> y;
curve.push_back(cv::Point_<T>(x, y));
}
return curve;
}
template<typename V>
cv::Mat_<double> Find2DRigidTransform(const vector<cv::Point_<V> >& a, const vector<cv::Point_<V> >& b,
cv::Point_<V>* diff = 0, V* angle = 0, V* scale = 0) {
//use PCA to find relational scale
Mat_<V> P; Mat(a).reshape(1, a.size()).copyTo(P);
Mat_<V> Q; Mat(b).reshape(1, b.size()).copyTo(Q);
PCA a_pca(P, Mat(), PCA::DATA_AS_ROW), b_pca(Q, Mat(), PCA::DATA_AS_ROW);
double s = sqrt(b_pca.eigenvalues.at<V>(0)) / sqrt(a_pca.eigenvalues.at<V>(0));
if (s != s)
{
for (int i = 0; i < a.size(); i++) if (a[i].x != a[i].x) cout << "a(" << i << ")=" << a[i] << endl;
//cout << "a_pca=" << a_pca.eigenvalues.at<V>(0) << endl;
}
// cout << a_pca.eigenvectors << endl << a_pca.eigenvalues << endl << a_pca.mean << endl;
// cout << b_pca.eigenvectors << endl << b_pca.eigenvalues << endl << b_pca.mean << endl;
//convert to matrices and subtract mean
// Mat_<double> P(a.size(),2),Q(b.size(),2);
Scalar a_m = Scalar(a_pca.mean.at<V>(0), a_pca.mean.at<V>(1));
Scalar b_m = Scalar(b_pca.mean.at<V>(0), b_pca.mean.at<V>(1));
// for (int i=0; i<a.size(); i++) { P(i,0) = a[i].x - a_m[0]; P(i,1) = a[i].y - a_m[1]; }
// for (int i=0; i<b.size(); i++) { Q(i,0) = b[i].x - b_m[0]; Q(i,1) = b[i].y - b_m[1]; }
P -= repeat((Mat_<V>(1, 2) << a_m[0], a_m[1]), P.rows, 1);
Q -= repeat((Mat_<V>(1, 2) << b_m[0], b_m[1]), Q.rows, 1);
// cout << "new mean for a " << mean(P) << "\n";
//from http://en.wikipedia.org/wiki/Kabsch_algorithm
Mat_<double> A = P.t() * Q;
SVD svd(A);
Mat_<double> C = svd.vt.t() * svd.u.t();
double d = (determinant(C) > 0) ? 1 : -1;
Mat_<double> R = svd.vt.t() * (Mat_<double>(2, 2) << 1, 0, 0, d) * svd.u.t();
Mat_<double> T = (Mat_<double>(3, 3) << 1, 0, b_m[0] / s, 0, 1, b_m[1] / s, 0, 0, 1) *
(Mat_<double>(3, 3) << s, 0, 0, 0, s, 0, 0, 0, s) *
(Mat_<double>(3, 3) << R(0, 0), R(0, 1), 0, R(1, 0), R(1, 1), 0, 0, 0, 1) *
(Mat_<double>(3, 3) << 1, 0, -a_m[0], 0, 1, -a_m[1], 0, 0, 1)
;
if (diff != NULL) {
diff->x = b_m[0] - a_m[0];
diff->y = b_m[1] - a_m[1];
}
if (angle != NULL) {
*angle = atan2(R(1, 0), R(0, 0));
}
if (scale != NULL) {
*scale = s;
}
return T(Range(0, 2), Range::all());
}
template<typename T, typename V>
cv::Mat_<T> ConvertToMat(const vector<vector<V> >& mnt_DB) {
Mat_<T> mnt_DB_m(mnt_DB.size(), mnt_DB[0].size());
for (int i = 0; i < mnt_DB.size(); i++) {
for (int j = 0; j < mnt_DB[i].size(); j++) {
mnt_DB_m(i, j) = (T)(mnt_DB[i][j]);
}
}
return mnt_DB_m;
}
template<typename T>
void drawCurvePoints(cv::Mat& img, const vector<cv::Point_<T> >& curve_, const cv::Scalar& color, int thickness) {
vector<cv::Point> curve;
ConvertCurve(curve_, curve);
for (int i = 0; i < curve.size(); i++) {
circle(img, curve[i], 3, color, thickness);
}
}
void GetCurveForImage(const cv::Mat& filename, vector<cv::Point>& curve, bool onlyUpper = true, bool getLower = false);
void GetCurveForImage(const cv::Mat& filename, vector<cv::Point>& whole, vector<cv::Point>& curve_upper, vector<cv::Point>& curve_lower);
template<int x, int y>
void imshow_(const std::string& str, const cv::Mat& img)
{
cv::Mat big;
resize(img, big, cv::Size(x, y), -1, -1, INTER_NEAREST);
imshow(str, big);
}
template<typename T, typename V>
vector<cv::Point_<V> > YnormalizedCurve(const vector<cv::Point_<T> >& curve) {
vector<T> curvex, curvey; PolyLineSplit(curve, curvex, curvey);
double minval, maxval;
minMaxIdx(curvey, &minval, &maxval);
vector<cv::Point_<V> > curveout;
for (int i = 0; i < curve.size(); i++) {
curveout.push_back(cv::Point_<V>(i, (curvey[i] - minval) / (maxval - minval)));
}
return curveout;
}
cv::Mat_<double> GetSmithWatermanHMatrix(const vector<pair<char, int> >& a, const vector<pair<char, int> >& b);
double MatchSmithWaterman(const vector<pair<char, int> >& a, const vector<pair<char, int> >& b, vector<cv::Point>& matching);
// prepare curve segment database for generic purposes
// in particular for comparison between different models
void PrepareSignatureDB(const vector<cv::Point2d>& curve, vector<vector<double> >& DB, vector<cv::Point>& DB_params);
// prepare curve segment database for comparisons among the shadwos casted by the same model
// In this case, we would like the min_curve at least half of the given curve.
void PrepareSignatureDB_For_IntraModel_Comparison(const vector<cv::Point2d>& curve, vector<vector<double> >& DB, vector<cv::Point>& DB_params);
private:
vector<cv::Point2d> source;
vector<cv::Point2d> target;
//parameters used in this matcher
int RESAMPLE_SIZE; //curve resample size
int SMALLEST_CURVE_SIZE; //smallest curve in the segment DB
int LONGEST_CURVE_SIZE; //longest curve in the segment DB
int OFFSET_STEP; //curve segment DB offset incremental size
int CURVATURE_FILTER_SIZE; //number of matches that will pass through curvature filter
};
//a dummy function for compatiability
inline float getArcLength(const vector<cv::Point>& curve)
{
return (float)curve.size();
}
| [
"jmlien@cs.gmu.edu"
] | jmlien@cs.gmu.edu |
2aff55ca7a45737afcc034e1da3b2e280ea0e4fb | 8ae31e5db1f7c25b6ce1c708655ab55c15dde14e | /比赛/学校/2019-11-6测试/source/PC02_19-11-6 ylh/product.cpp | 4399620fc4f8d58a1764ba0f318042060987fa9d | [] | no_license | LeverImmy/Codes | 99786afd826ae786b5024a3a73c8f92af09aae5d | ca28e61f55977e5b45d6731bc993c66e09f716a3 | refs/heads/master | 2020-09-03T13:00:29.025752 | 2019-12-16T12:11:23 | 2019-12-16T12:11:23 | 219,466,644 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 685 | cpp | #include <bits/stdc++.h>
#define ll long long
const ll inf=(ll)1<<(ll)60;
ll f[205][205];
int n,t[205],d[205],sumt[205],sumd[205];
ll dfs(int l,int r){
if (l>r)return 0;
if (f[l][r]!=-1)return f[l][r];
f[l][r]=inf;
for(int i=l;i<=r;++i){
f[l][r]=std::min(f[l][r],
dfs(l,i-1)+dfs(i+1,r)+(ll)(sumt[i-1]-sumt[l-1])*(sumd[r]-sumd[i])+(ll)d[i]*(sumt[r]-sumt[i]+sumt[i-1]-sumt[l-1]+t[i]));
}return f[l][r];
}
int main(){
freopen("product.in","r",stdin);
freopen("product.out","w",stdout);
scanf("%d",&n);
for(int i=1;i<=n;++i){
scanf("%d%d",&t[i],&d[i]);
sumt[i]=sumt[i-1]+t[i];sumd[i]=sumd[i-1]+d[i];
}std::memset(f,-1,sizeof(f));
printf("%lld",dfs(1,n));
return 0;
}
| [
"506503360@qq.com"
] | 506503360@qq.com |
2f024add3f61db61e7825c6b09a0f6822ce42c46 | 1c2cd5951f82a5fb12142621a3b9baea14cf4a31 | /ABC134/ABC134B.cpp | ae97fc2fdd787b69a747dc2c01ee7400fc1a69c3 | [] | no_license | ksera332/Atcoder_records | 55ef832eb3e517b99334eb00d2287cd4a1bc83cd | f8b1f13211bae79b7da6d63ba9b1bd177031aef9 | refs/heads/master | 2022-12-08T19:25:26.834948 | 2020-08-29T12:55:30 | 2020-08-29T12:55:30 | 263,906,419 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 614 | cpp | #include <set>
#include <map>
#include <list>
#include <stack>
#include <cmath>
#include <ctime>
#include <cstdio>
#include <vector>
#include <string>
#include <bitset>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <utility>
#include <numeric>
#include <complex>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <cassert>
#include <iostream>
#include <iterator>
#include <algorithm>
using namespace std;
int main(){
int N,D,mieru,ans;
cin >> N >> D;
mieru = (D * 2) + 1;
if(N%mieru == 0)ans = (N/mieru);
else ans = (N/mieru) + 1;
cout << ans << endl;
} | [
"ksera6@gmail.com"
] | ksera6@gmail.com |
2e10b26b47f0acc5a0a33f95b70a39eb2088e4de | 6f5379f9dc222a2b409cdf54ac62617e988e7754 | /gtest/googletest/videocapture/hi3559av100/videocaptureimpl.cpp | 46d8697b995f9d3443a1796fb84da792f488f1c8 | [] | no_license | ToSaySomething/Leaning | b581379b9bf572682bd45ac11c5a315552cea51f | 523e040f16a6de3d4bf2e5de8a1e65fd1a7ff4e8 | refs/heads/master | 2020-03-28T11:57:04.180983 | 2018-09-12T02:50:27 | 2018-09-12T02:50:27 | 148,258,479 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,117 | cpp | #include <iostream>
#include "videocaptureimpl.h"
#include "basedatatype.h"
using namespace std;
// 视频帧最大长度
#define VIDEO_FRAME_MAX_LEN 4000*3200
// 读取视频帧最大超时时间
#define READ_VIDEO_FRAME_MAX_TIMEOUT 2000
void *Hi3559WorkThread(void* threadContext)
{
unsigned int tWaitTimeout = READ_VIDEO_FRAME_MAX_TIMEOUT;
if(NULL == threadContext)
return NULL;
Hi3559AVideoCaptureImpl *hi3559AVideoCaptureImpl = static_cast<Hi3559AVideoCaptureImpl*>(threadContext);
if(NULL != hi3559AVideoCaptureImpl) {
char *buffer = (char*)malloc(VIDEO_FRAME_MAX_LEN*sizeof(char));
unsigned int bufferLen = VIDEO_FRAME_MAX_LEN;
do {
memset(buffer,0,VIDEO_FRAME_MAX_LEN*sizeof(char));
int ret = hi3559AVideoCaptureImpl->getVideoFrame(0,0,buffer,bufferLen,tWaitTimeout);
if(ret > 0) {
hi3559AVideoCaptureImpl->onRecvData(buffer,ret);
}
if(hi3559AVideoCaptureImpl->getThreadExit())
break;
} while(true);
free(buffer);
buffer = NULL;
}
std::cout<<"read video frame thread exit."<<std::endl;
return NULL;
}
int Hi3559AVideoCaptureImpl::open(unsigned int channelId,
CW_ENUM_PIXEL_FORMAT videoFormat,
unsigned int frameRate)
{
if( CW_RET_SUCCESS != Hi3559VideoCaptureWrap::initMPP() )
return CW_RET_FAILED;
if(CW_RET_SUCCESS != this->setVIVPSSWorkMode()) {
goto MPP_ERROR;
}
std::cout<<"setVIVPSSWorkMode success."<<std::endl;
if(CW_RET_SUCCESS != this->startVI()) {
goto MPP_ERROR;
}
std::cout<<"startVI success."<<std::endl;
if(CW_RET_SUCCESS != this->startISP()) {
goto VI_ERROR;
}
std::cout<<"startISP success."<<std::endl;
if(CW_RET_SUCCESS != this->startVPSS()) {
goto ISP_ERROR;
}
std::cout<<"startVPSS success."<<std::endl;
bThreadExit_ = false;
// 启动线程
pthread_create(&workThreadId_,NULL,Hi3559WorkThread,(void*)this);
return CW_RET_SUCCESS;
VI_ERROR:
this->stopVi();
ISP_ERROR:
this->stopISP();
MPP_ERROR:
this->finiMPP();
return CW_RET_FAILED;
}
int Hi3559AVideoCaptureImpl::onRecvData(const char* buffer,unsigned int bufferLen)
{
fVideoCaptureDataCallBack fVideoCaptrueCallBack = this->getVideoCaptureDataCallBack();
if(fVideoCaptrueCallBack != NULL) {
fVideoCaptrueCallBack(this,buffer,bufferLen);
}
return CW_RET_SUCCESS;
}
int Hi3559AVideoCaptureImpl::close()
{
bThreadExit_ = true;
pthread_join(workThreadId_,NULL);
if(CW_RET_SUCCESS != this->stopVPSS()) {
std::cout<<"call stopVPSS failed."<<std::endl;
}
if(CW_RET_SUCCESS != this->stopISP()) {
std::cout<<"call stopISP failed."<<std::endl;
}
if(CW_RET_SUCCESS != this->stopVi()) {
std::cout<<"call stopVi failed."<<std::endl;
}
if(CW_RET_SUCCESS != this->finiMPP()) {
std::cout<<"call finiMPP failed."<<std::endl;
}
return CW_RET_SUCCESS;
}
| [
"dengyuting@cloudwalk.cn"
] | dengyuting@cloudwalk.cn |
df9588be896f66424b0ba21ce929148c9ee541eb | 0f7ab0cd5aa2563c24bdbeb49a66942bd5d2ffbd | /Wasabi/include/Wasabi/graphic/vulkan/instance.h | 4cc1e306050e34bd4da27cfba10030c7ea5f4d23 | [] | no_license | takowasaby/vulkan_game | 6ba416ed9d9a5ad3d7c169f2f02d5c89af7bfad8 | 1dbedca6b0c410791d1f37ed3a77311c8cc3ce42 | refs/heads/master | 2020-09-10T15:18:38.733909 | 2019-11-28T11:50:43 | 2019-11-28T11:50:43 | 221,736,322 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 379 | h | #pragma once
#include <vector>
#include <Wasabi/libdef/vulkan.h>
namespace wsb {
namespace graphic {
namespace vulkan {
class Instance {
public:
static std::vector<const char*> getRequiredExtensions();
public:
Instance();
~Instance();
VkInstance getInstanceHandle() const;
private:
VkInstance _instance;
};
}
}
} | [
"tomioka2012@gmail.com"
] | tomioka2012@gmail.com |
ab008ac57bc684c31e5293919d79cec72f897be5 | 65f9576021285bc1f9e52cc21e2d49547ba77376 | /LINUX/android/vendor/qcom/proprietary/qcril-data-hal/datamodule/module/src/request/RilRequestDataCallListMessage.cpp | 24da636f783f944756ddbb78e5e72f9ed1f1f8bf | [] | no_license | AVCHD/qcs605_root_qcom | 183d7a16e2f9fddc9df94df9532cbce661fbf6eb | 44af08aa9a60c6ca724c8d7abf04af54d4136ccb | refs/heads/main | 2023-03-18T21:54:11.234776 | 2021-02-26T11:03:59 | 2021-02-26T11:03:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 535 | cpp | /**
* Copyright (c) 2017 Qualcomm Technologies, Inc.
* All Rights Reserved.
* Confidential and Proprietary - Qualcomm Technologies, Inc.
**/
#include <string.h>
#include "modules/android/ril_message_factory.h"
#include "DataCommon.h"
#include "request/RilRequestDataCallListMessage.h"
namespace rildata {
RilRequestDataCallListMessage::~RilRequestDataCallListMessage() {
if (mCallback) {
delete mCallback;
mCallback = nullptr;
}
}
string RilRequestDataCallListMessage::dump() {
return mName + "{ }";
}
}// namespace
| [
"jagadeshkumar.s@pathpartnertech.com"
] | jagadeshkumar.s@pathpartnertech.com |
25b98c3bd6248aae15380f540223425a9bdaa198 | aadf31061666fc9fd95583710a34d01fa571b09f | /include/LocalPrimitiveVariable.hpp | 45e749678786902cdb1889d88487de313e567c6c | [] | no_license | vladfridman/wisey | 6198cf88387ea82175ea6e1734edb7f9f7cf20c6 | 9d0efcee32e05c7b8dc3dfd22293737324294fea | refs/heads/master | 2022-04-14T08:00:42.743194 | 2020-03-12T14:22:45 | 2020-03-12T14:22:45 | 74,822,543 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,599 | hpp | //
// LocalPrimitiveVariable.hpp
// Wisey
//
// Created by Vladimir Fridman on 2/9/17.
// Copyright © 2017 Vladimir Fridman. All rights reserved.
//
#ifndef LocalPrimitiveVariable_h
#define LocalPrimitiveVariable_h
#include "IPrimitiveType.hpp"
#include "IVariable.hpp"
namespace wisey {
/**
* Represents a local variable of primitive type
*/
class LocalPrimitiveVariable : public IVariable {
std::string mName;
const IPrimitiveType* mType;
llvm::Value* mValueStore;
int mLine;
public:
LocalPrimitiveVariable(std::string name,
const IPrimitiveType* type,
llvm::Value* valueStore,
int line);
~LocalPrimitiveVariable();
std::string getName() const override;
const IPrimitiveType* getType() const override;
bool isField() const override;
bool isStatic() const override;
int getLine() const override;
llvm::Value* generateIdentifierIR(IRGenerationContext& context, int line) const override;
llvm::Value* generateIdentifierReferenceIR(IRGenerationContext& context,
int line) const override;
llvm::Value* generateAssignmentIR(IRGenerationContext& context,
IExpression* assignToExpression,
std::vector<const IExpression*> arrayIndices,
int line) override;
};
} /* namespace wisey */
#endif /* LocalPrimitiveVariable_h */
| [
"vlad.fridman@gmail.com"
] | vlad.fridman@gmail.com |
3d25b01967df378b44ed8f0ec61f1ec222385e62 | cdeccfe63cedee76f87e8bd9d45d866ca1a90563 | /include/minecraft/structure/StructureSettings.h | c2b3dc83ffff66a0d69bea49db29974bfc6f6ea3 | [
"MIT"
] | permissive | mclauncherlinux/bdlauncher | d6cfc7b1e7f7c90b7319087f2832b98360536536 | 9d7482786ba8be1e06fc7c81b448c5862e970870 | refs/heads/master | 2020-09-20T23:46:13.569316 | 2019-11-27T05:18:31 | 2019-11-27T05:18:31 | 224,619,858 | 1 | 0 | MIT | 2019-11-28T09:43:01 | 2019-11-28T09:43:00 | null | UTF-8 | C++ | false | false | 601 | h | #pragma once
#include "../core/types.h"
#include <string>
enum class Rotation : char {};
enum class Mirror : char {};
struct StructureSettings {
std::string palette_name; // 0
bool ignore_entities; // 32
bool ignore_blocks; // 33
BlockPos size, offset; // 36, 48
ActorUniqueID last_touched_id; // 64
Rotation rotation; // 72
Mirror mirror; // 73
float integrity; // 76
unsigned integrity_seed; // 80
StructureSettings();
inline ~StructureSettings() { asm("call _ZN17StructureSettingsD2Ev"); }
}; | [
"3321056730@qq.com"
] | 3321056730@qq.com |
6457965aa15547a9f06a1ea6824f0d9ae9b3c147 | 32bb33e1f9d14060fc7778c4f2cf93176fbf0ff0 | /libs/volvis_utils/reader.h | 7611cf39cf3082bef8e30895f199de5332159b90 | [
"MIT"
] | permissive | lquatrin/s_cpp_volume_rendering | 617d323bdb3685489d2c54c62c5879c503ac841d | 72c47274ab88d5ef159199f873e3ea38db5a1d43 | refs/heads/main | 2023-06-20T15:02:08.346843 | 2021-07-15T03:24:17 | 2021-07-15T03:24:17 | 384,561,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 996 | h | /**
* Classes to read Volumes and Transfer Functions
* - VolumeReader:
* .pvm
* .raw
*
* - TransferFunctionReader:
* .tf1d
*
* Leonardo Quatrin Campagnolo
* . campagnolo.lq@gmail.com
**/
#ifndef VOL_VIS_UTILS_VOLUME_AND_TF_READER_H
#define VOL_VIS_UTILS_VOLUME_AND_TF_READER_H
#include <volvis_utils/structuredgridvolume.h>
#include <volvis_utils/transferfunction.h>
#include <iostream>
namespace vis
{
class VolumeReader
{
public:
VolumeReader ();
~VolumeReader ();
StructuredGridVolume* ReadStructuredVolume (std::string filepath);
protected:
StructuredGridVolume* readpvm (std::string filename);
StructuredGridVolume* readraw (std::string filepath);
private:
};
class TransferFunctionReader
{
public:
TransferFunctionReader ();
~TransferFunctionReader ();
vis::TransferFunction* ReadTransferFunction (std::string file);
protected:
vis::TransferFunction* readtf1d (std::string file);
private:
};
}
#endif | [
"campagnolo.lq@gmail.com"
] | campagnolo.lq@gmail.com |
e476b492e7926df6cc256ceec02cd5a90beb7dfc | 05108a23fde55d1c904efca21732d90a1443b152 | /leetcode225.h | 624125ff271cf4952d0a4350bb79d0ce1283fcda | [] | no_license | qingmang178/C- | accf8282051eda40c06f18353d17027b550d0c8c | 25360e55671a245c0931f399148165351fda2997 | refs/heads/master | 2020-09-23T14:10:58.839895 | 2020-01-16T03:25:26 | 2020-01-16T03:25:26 | 225,518,364 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,348 | h | #pragma once
#ifndef leetcode225_
#define leetcode225_
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<queue>
#include<stack>
#include <utility>
#include <map>
#include<unordered_set>
using namespace std;
class MyStack {
public:
/** Initialize your data structure here. **/
queue<int> q1;
queue<int> q2;
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q1.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int i = 0;
while (!q1.empty())
{
q2.push(q1.front());
q1.pop();
i++;
}
while (i != 1)
{
q1.push(q2.front());
//top = q2.front();
q2.pop();
i--;
}
int temp = q2.front();
q2.pop();
return temp;
}
/** Get the top element. */
int top() {
int i = 0;
while (!q1.empty())
{
q2.push(q1.front());
q1.pop();
i++;
}
while (i != 1)
{
q1.push(q2.front());
q2.pop();
i--;
}
int temp = q2.front();
q1.push(temp);
q2.pop();
return temp;
}
/** Returns whether the stack is empty. */
bool empty() {
return q1.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
#endif
| [
"18260068839@163.com"
] | 18260068839@163.com |
6dca739622e5c32c469c9aa74bf7c5520552d46f | 797ec81c4f76fa7d28d7e3c2afed50a98f9f3b73 | /src/core/events/events.cpp | 9ef37ab8eac5ae280a81bd8a13d21955bc5d4602 | [] | no_license | xaivour/Dawn | 7c16d57b385fbf67441a0231ec960437f2d083eb | 26a4bca509b7b044465e79af5b4350d3c38ad960 | refs/heads/master | 2020-04-28T08:29:36.353724 | 2019-03-14T05:01:01 | 2019-03-14T05:01:01 | 175,129,173 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,321 | cpp | #include "events.h"
#include "event_handler.h"
namespace Dawn
{
void EventHandler::onKeyDown(uint32 keyCode, bool isRepeat)
{
static KeyDownEvent keyDownEvent;
keyDownEvent.keyCode = keyCode;
keyDownEvent.isRepeat = isRepeat;
EventDispatcher::getEventDispatcher().dispatchEvent(keyDownEvent);
}
void EventHandler::onKeyUp(uint32 keyCode, bool isRepeat)
{
static KeyUpEvent keyUpEvent;
keyUpEvent.keyCode = keyCode;
keyUpEvent.isRepeat = isRepeat;
EventDispatcher::getEventDispatcher().dispatchEvent(keyUpEvent);
}
void EventHandler::onMouseButtonDown(uint32 mouseButton, uint8 numClicks, int32 posX, int32 posY)
{
static MouseButtonDownEvent mouseButtonDownEvent;
mouseButtonDownEvent.mouseButtonCode = mouseButton;
mouseButtonDownEvent.numClicks = numClicks;
mouseButtonDownEvent.posX = posX;
mouseButtonDownEvent.posY = posY;
EventDispatcher::getEventDispatcher().dispatchEvent(mouseButtonDownEvent);
}
void EventHandler::onMouseButtonUp(uint32 mouseButton, uint8 numClicks, int32 posX, int32 posY)
{
static MouseButtonUpEvent mouseButtonUpEvent;
mouseButtonUpEvent.mouseButtonCode = mouseButton;
mouseButtonUpEvent.numClicks = numClicks;
mouseButtonUpEvent.posX = posX;
mouseButtonUpEvent.posY = posY;
EventDispatcher::getEventDispatcher().dispatchEvent(mouseButtonUpEvent);
}
void EventHandler::onMouseMove(int32 mousePosX, int32 mousePosY,
int32 deltaX, int32 deltaY)
{
static MouseMoveEvent mouseMoveEvent;
mouseMoveEvent.posX = mousePosX;
mouseMoveEvent.posY = mousePosY;
mouseMoveEvent.deltaX = deltaX;
mouseMoveEvent.deltaY = deltaY;
EventDispatcher::getEventDispatcher().dispatchEvent(mouseMoveEvent);
}
void EventListener::shipEvent(Event& e)
{
onEvent(e);
switch(e.getEventType())
{
case Event::KEY_DOWN:
onKeyDown((KeyDownEvent&)e);
break;
case Event::KEY_UP:
onKeyUp((KeyUpEvent&)e);
break;
case Event::MOUSE_BUTTON_DOWN:
onMouseButtonDown((MouseButtonDownEvent&)e);
break;
case Event::MOUSE_BUTTON_UP:
onMouseButtonUp((MouseButtonUpEvent&)e);
break;
case Event::MOUSE_MOVE:
onMouseMove((MouseMoveEvent&)e);
break;
}
}
EventHandler* EventHandler::getEventHandler()
{
static EventHandler* eventHandlerInstance = new EventHandler;
return eventHandlerInstance;
}
EventDispatcher& EventDispatcher::getEventDispatcher()
{
static EventDispatcher eventDispathcer;
return eventDispathcer;
}
void EventDispatcher::addEventListener(EventListener* eventListener)
{
eventListeners.push_back(eventListener);
}
void EventDispatcher::removeEventListener(EventListener* eventListener)
{
eventListeners.erase(std::remove_if(eventListeners.begin(),
eventListeners.end(), [eventListener](EventListener* e){
return (e == eventListener);
}));
}
} | [
"rajat.vx@gmail.com"
] | rajat.vx@gmail.com |
f322b627c5b715f50af6cd6ae7524ce3375562f0 | 32d9b0c23801ca3b2ef0514d95222454a7c862c3 | /blocks/hrfm/src/visual/inherits/ShaderVisual.h | 77403e3d2bf9e83b71b571aee2257951154c687c | [] | no_license | hrfm/CinderFiles | 44a253ea54d3677676d00d6b1c1a761b568c4389 | 0c639f2c135215d9a316ee195d97efa0159fe72a | refs/heads/master | 2021-06-23T04:37:41.155158 | 2015-11-02T07:43:37 | 2015-11-02T07:43:37 | 24,394,196 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,969 | h | #pragma once
#include "VisualBase.h"
#include "cinder/gl/Texture.h"
using namespace ci;
using namespace std;
using namespace hrfm;
using namespace hrfm::visual;
namespace hrfm{ namespace visual{
class ShaderVisual : public VisualBase{
public :
ShaderVisual( AppBase * app, Vec2i resolution, string fragment ){
VisualBase();
setup( app, resolution );
addVisual(fragment);
};
ShaderVisual( AppBase * app, Vec2i resolution, vector<string> fragments ){
VisualBase();
setup( app, resolution );
vector<string>::iterator it = fragments.begin();
while( it != fragments.end() ){
addVisual( (*it) );
it++;
}
};
void setup( AppBase * app, Vec2i resolution ){
cout << "- Setup ShaderVisual " << resolution << endl;
VisualBase::setup( app, resolution );
};
void addVisual( string fragment ){
cout << "addVisual : " << fragment << endl;
try {
gl::GlslProg shader = gl::GlslProg(
loadResource("../resources/vert.glsl"),
loadResource(fragment)
);
mShaders.push_back( shader );
}catch( ci::gl::GlslProgCompileExc &exc ) {
cout << "Shader compile error: " << endl;
cout << exc.what();
}catch( ... ) {
cout << "Unable to load shader" << endl;
}
}
void update(){
mTextures.clear();
if( mAppBase->useCapture ){
mTextures.push_back( mAppBase->captureInput.getCaptureTexture() );
}
if( mAppBase->captureInput.useOpticalFlow ){
mTextures.push_back( mAppBase->captureInput.getForceMap().getForceTexture() );
}
float iGlobalTime = (float)getElapsedSeconds();
Vec2f iResolution = Vec2f( mOutputFbo.getWidth(), mOutputFbo.getHeight() );
Vec2f iMouse = Vec2f( 0, 0 );
float average = mAppBase->audioInput.getAudioManagerFFTAverage();
float fader0 = mAppBase->getFaderValueAt(4) * mAppBase->getFaderValueAt(12) * 3.0;
float fader1 = mAppBase->getFaderValueAt(5) * mAppBase->getFaderValueAt(13) * 3.0;
average = fader0 + average * fader1;
vector<gl::GlslProg>::iterator it = mShaders.begin();
const std::vector<gl::GlslProg>::const_iterator & end = mShaders.end();
vector<gl::Texture>::iterator texIt;
const std::vector<gl::Texture>::const_iterator & texItEnd = mTextures.end();
gl::enableAdditiveBlending();
mOutputFbo.bindFramebuffer();
gl::pushMatrices();
gl::setMatricesWindow( mOutputFbo.getSize(), false );
gl::clear();
gl::color( ColorA( 1.0, 1.0, 1.0, 1.0 ) );
for (it = mShaders.begin(); it != end; ++it) {
gl::GlslProg shader = (*it);
shader.bind();
// --- Bind Textures if needed. ---
int bindIndex = 0;
if( mAppBase->useCapture ){
mAppBase->captureInput.getCaptureTexture().bind(bindIndex);
shader.uniform( "iChannel"+toString(bindIndex), bindIndex++ );
}
for( texIt = mTextures.begin(); texIt != texItEnd; ++texIt ) {
(*texIt).bind( bindIndex );
shader.uniform( "iChannel"+toString(bindIndex), bindIndex++ );
}
// ---
shader.uniform( "iResolution", iResolution );
shader.uniform( "iGlobalTime", iGlobalTime );
shader.uniform( "iMouse" , iMouse );
shader.uniform( "iFFT" , mAppBase->audioInput.fft2, 64 );
shader.uniform( "iFFTAverage", average );
shader.uniform( "iAudioGain" , mAppBase->audioInput.getAudioManagerGain() );
gl::drawSolidRect( mOutputFbo.getBounds() );
// --- Unbind Textures if needed.
if( mAppBase->useCapture ){
mAppBase->captureInput.getCaptureTexture().unbind();
}
for( texIt = mTextures.begin(); texIt != texItEnd; ++texIt ) {
(*texIt).unbind();
}
// ---
shader.unbind();
}
gl::popMatrices();
mOutputFbo.unbindFramebuffer();
gl::disableAlphaBlending();
}
void draw(){};
private :
vector<gl::Texture> mTextures;
vector<gl::GlslProg> mShaders;
};
}} | [
"hrfm0818@gmail.com"
] | hrfm0818@gmail.com |
d5925b6c38642b4c82c1eccceaeb62db24d0503d | a06a9ae73af6690fabb1f7ec99298018dd549bb7 | /_Library/_Include/boost/python/object/pickle_support.hpp | b3993f2f36cb2180d53253a9829495a93efa7177 | [] | no_license | longstl/mus12 | f76de65cca55e675392eac162dcc961531980f9f | 9e1be111f505ac23695f7675fb9cefbd6fa876e9 | refs/heads/master | 2021-05-18T08:20:40.821655 | 2020-03-29T17:38:13 | 2020-03-29T17:38:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,449 | hpp | ////////////////////////////////////////////////////////////////////////////////
// pickle_support.hpp
// (C) Copyright R.W. Grosse-Kunstleve 2002.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_PYTHON_OBJECT_PICKLE_SUPPORT_RWGK20020603_HPP
# define BOOST_PYTHON_OBJECT_PICKLE_SUPPORT_RWGK20020603_HPP
# include <boost/python/detail/prefix.hpp>
namespace boost { namespace python {
namespace api
{
class object;
}
using api::object;
class tuple;
BOOST_PYTHON_DECL object const& make_instance_reduce_function();
struct pickle_suite;
namespace error_messages {
template <class T>
struct missing_pickle_suite_function_or_incorrect_signature {};
inline void must_be_derived_from_pickle_suite(pickle_suite const&) {}
}
namespace detail { struct pickle_suite_registration; }
struct pickle_suite
{
private:
struct inaccessible {};
friend struct detail::pickle_suite_registration;
public:
static inaccessible* getinitargs() { return 0; }
static inaccessible* getstate() { return 0; }
static inaccessible* setstate() { return 0; }
static bool getstate_manages_dict() { return false; }
};
namespace detail {
struct pickle_suite_registration
{
typedef pickle_suite::inaccessible inaccessible;
template <class Class_, class Tgetinitargs>
static
void
register_(
Class_& cl,
tuple (*getinitargs_fn)(Tgetinitargs),
inaccessible* (* /*getstate_fn*/)(),
inaccessible* (* /*setstate_fn*/)(),
bool)
{
cl.enable_pickling_(false);
cl.def("__getinitargs__", getinitargs_fn);
}
template <class Class_,
class Rgetstate, class Tgetstate,
class Tsetstate, class Ttuple>
static
void
register_(
Class_& cl,
inaccessible* (* /*getinitargs_fn*/)(),
Rgetstate (*getstate_fn)(Tgetstate),
void (*setstate_fn)(Tsetstate, Ttuple),
bool getstate_manages_dict)
{
cl.enable_pickling_(getstate_manages_dict);
cl.def("__getstate__", getstate_fn);
cl.def("__setstate__", setstate_fn);
}
template <class Class_,
class Tgetinitargs,
class Rgetstate, class Tgetstate,
class Tsetstate, class Ttuple>
static
void
register_(
Class_& cl,
tuple (*getinitargs_fn)(Tgetinitargs),
Rgetstate (*getstate_fn)(Tgetstate),
void (*setstate_fn)(Tsetstate, Ttuple),
bool getstate_manages_dict)
{
cl.enable_pickling_(getstate_manages_dict);
cl.def("__getinitargs__", getinitargs_fn);
cl.def("__getstate__", getstate_fn);
cl.def("__setstate__", setstate_fn);
}
template <class Class_>
static
void
register_(
Class_&,
...)
{
typedef typename
error_messages::missing_pickle_suite_function_or_incorrect_signature<
Class_>::error_type error_type;
}
};
template <typename PickleSuiteType>
struct pickle_suite_finalize
: PickleSuiteType,
pickle_suite_registration
{};
} // namespace detail
}} // namespace boost::python
#endif // BOOST_PYTHON_OBJECT_PICKLE_SUPPORT_RWGK20020603_HPP
/////////////////////////////////////////////////
// vnDev.Games - Trong.LIVE - DAO VAN TRONG //
////////////////////////////////////////////////////////////////////////////////
| [
"adm.fael.hs@gmail.com"
] | adm.fael.hs@gmail.com |
7f467a3f5616e71886d6403ccac65715e080aace | eb13ed97957a1a69f8a3fb73be62880c380a9b2a | /libSetReplace/Event.hpp | c0640f21f99bf648dce5d28f7e5449e8d4471bb2 | [
"MIT"
] | permissive | Advanced-Research-Centre/SetReplace | b42aa017224aaf8c53c2a9438d94af9cf4f04388 | d40cb49712852c17e17b1260385f9dbb9aafe691 | refs/heads/master | 2022-11-30T18:50:06.472948 | 2020-08-10T16:33:14 | 2020-08-10T16:33:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,321 | hpp | #ifndef LIBSETREPLACE_EVENT_HPP_
#define LIBSETREPLACE_EVENT_HPP_
#include <memory>
#include <vector>
#include "IDTypes.hpp"
namespace SetReplace {
/** @brief Event is an instantiated replacement that has taken place in the system.
*/
struct Event {
/** @brief ID for the rule this event corresponds to.
*/
const RuleID rule;
/** @brief Expressions matching the rule inputs.
*/
const std::vector<ExpressionID> inputExpressions;
/** @brief Expressions created from the rule outputs.
*/
const std::vector<ExpressionID> outputExpressions;
/** @brief Layer of the causal graph this event belongs to.
*/
const Generation generation;
};
/** @brief CausalGraph keeps track of causal relationships between events and expressions.
@details It does not care and does not know about atoms at all because they are only used for matching. Expressions are
only identified by IDs.
*/
class CausalGraph {
public:
/** @brief Creates a new CausalGraph with a given number of initial expressions.
*/
explicit CausalGraph(int initialExpressionsCount);
/** @brief Adds a new event, names its output expressions, and returns their IDs.
*/
std::vector<ExpressionID> addEvent(RuleID ruleID,
const std::vector<ExpressionID>& inputExpressions,
int outputExpressionsCount);
/** @brief Yields a vector of all events throughout history.
@details This includes the initial event, so the size of the result is one larger than eventsCount().
*/
const std::vector<Event>& events() const;
/** @brief Total number of events.
*/
size_t eventsCount() const;
/** @brief Yields a vector of IDs for all expressions in the causal graph.
*/
std::vector<ExpressionID> allExpressionIDs() const;
/** @brief Total number of expressions.
*/
size_t expressionsCount() const;
/** @brief Generation for a given expression.
* @details This is the same as the generation of its creator event.
*/
Generation expressionGeneration(ExpressionID id) const;
/** @brief Largest generation of any event.
*/
Generation largestGeneration() const;
private:
class Implementation;
std::shared_ptr<Implementation> implementation_;
};
} // namespace SetReplace
#endif // LIBSETREPLACE_EVENT_HPP_
| [
"noreply@github.com"
] | noreply@github.com |
5cb9c7343ab9dfbb3374b2ec23d30a8bec11bcde | 73ac2e74e527cc906330ba45f2cd9c105613fffb | /Blood_Bowl_Dual_Timer.ino | ec8905ffcaecd0ad4d8b6e589285034e8838626c | [] | no_license | smolz/Blood_Bowl_Dual_Timer | 22289b6a273590c0fcb7c92616899c8241050a43 | 399cc927dd31d050f623683ac8321e6fe8e54619 | refs/heads/master | 2021-01-23T06:20:32.386263 | 2017-03-27T16:28:58 | 2017-03-27T16:28:59 | 86,356,829 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,578 | ino | #include <SoftwareSerial.h>
#include <elapsedMillis.h>
#include <LiquidCrystal.h>
elapsedMillis timeElapsedClock; //For Tracking Seconds Countdown
elapsedMillis timeElapsedTooLong; //For Tracking When Unit has been left on too long
const byte CLR = 12; const byte Line2 = 148; const byte Line1 = 128; const byte Note1 = 220; const byte Note2 = 222; const byte Note3 = 224; // Vars for Making lcd Commands Eaiser
int Timer1Mins; byte Timer1Secs; int Timer2Mins; byte Timer2Secs; //Vars for storing Time
byte Timer1Counting = 0; byte Timer1InAlarm = 0; byte Timer2InAlarm = 0; byte Timer2Counting = 0; byte OnTooLong = 0; //Vars for tracking running status
int Timer1Countdown = 0; int Timer2Countdown = 0; //Vars for Counting down
int Timer1AlarmTracking; int Timer2AlarmTracking; //Vars for Alarms
int TooLongAlarm = 0;
const byte Timer1Button = 3; const byte Timer2Button = 4; const byte Timer1LED = 5; const byte Timer2LED = 6; //Setup Inputs & Outputs Pins
const int buzzer = 2;
const int AlarmDuration = 2; // Sets How long the Alarm goes on for (This is NOT Seconds or Milliseconds This number is program loop count)
const int Timer1Time = 240; const int Timer2Time = 240; //Seconds to countdown from for each timer
const long LeftOnTooLong = 600; //Seconds till alarm goes off for being turned on too long with no fresh inputs (Currently set for 30 seconds after last timer went off)
//SoftwareSerial lcd = SoftwareSerial(255, lcdPin); // Setup for lcd Communications
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
void setup(void)
{
Serial.begin(9600); // Start Serial Output for Diagnostics
pinMode(buzzer, OUTPUT); //Set buzer - pin 2 as an output
pinMode(Timer1Button, INPUT_PULLUP); pinMode(Timer2Button, INPUT_PULLUP); // Sets pins for Input with Pull Up Resistor Internally
pinMode(Timer1LED, OUTPUT); pinMode(Timer2LED, OUTPUT); // Sets pins for Output
lcd.begin(16, 2); // Start lcd Communications
lcd.clear(); lcd.noBlink(); delay (100); // Sets system to on with no cursor, Turn backlight on, Clear
Timer1Countdown = Timer1Time; Timer2Countdown = Timer2Time; // Sets The wanted countdown Secs into the vars that do the counting
lcd.write(CLR);
}
void loop(void)
{
ReadButtons(); // Go check inputs for button presses
UpdateTime(); // Go update the countdowns if needed
if (OnTooLong == 0) {
Updatelcd(); //Show the Screen For Counting down if it has not been on too long
}
else {
lcdTooLong(); //Display shutdown screen because unit was left on too long
}
TimerAlarms(); // Go see if either timer is in Alarm if so then run alarm
TooLong(); // Go check to see if the unit has been on too long
}
void ReadButtons()
{
if (digitalRead(Timer1Button) == LOW) {
Timer1Countdown = Timer1Time; // Timer 1 Start
Timer1InAlarm = 0;
Timer1Counting = 1;
timeElapsedTooLong = 0;
OnTooLong = 0;
}
if (digitalRead(Timer2Button) == LOW) {
Timer2Countdown = Timer2Time; // Timer 2 Start
Timer2InAlarm = 0;
Timer2Counting = 1;
timeElapsedTooLong = 0;
OnTooLong = 0;
}
}
void Updatelcd()
{
if (Timer1Secs < 10) {
//lcd.write(Line1); //If below 10 seconds then pad extra :0x
lcd.setCursor(0,0);
lcd.print ("Player1 = ");
lcd.print (Timer1Mins);
lcd.print(":0");
lcd.print(Timer1Secs);
lcd.print(" ");
}
else {
//lcd.write(Line1); // Print Time Left
lcd.setCursor(0,0);
lcd.print ("Player1 = ");
lcd.print (Timer1Mins);
lcd.print(":");
lcd.print(Timer1Secs);
lcd.print(" ");
}
if (Timer2Secs < 10) {
//lcd.write(Line2); //If below 10 seconds then pad extra :0x
lcd.setCursor(0,1);
lcd.print ("Player2 = ");
lcd.print (Timer2Mins);
lcd.print(":0");
lcd.print(Timer2Secs);
lcd.print(" ");
}
else {
//lcd.write(Line2); // Print Time Left
lcd.setCursor(0,1);
lcd.print ("Player2 = ");
lcd.print (Timer2Mins);
lcd.print(":");
lcd.print(Timer2Secs);
lcd.print(" ");
}
}
void UpdateTime()
{
if (timeElapsedClock >= 1000) // If 1 second has passed since the last second counted then run code to update times andremove one second
{
if (Timer1Counting == 1) // If Timer 1 is running then run the code to subtract time
{
digitalWrite(Timer1LED, HIGH); Timer1Mins = floor(Timer1Countdown / 60); Timer1Secs = (Timer1Countdown - (Timer1Mins * 60)); // Compute how much time left vs how much passed
Timer1Countdown --; // Subtract 1 Second from the clock Var
if (Timer1Countdown < 0) {
Timer1Counting = 0; // If time is up then stop the timer and turn on the alarm
Timer1InAlarm = 1;
digitalWrite(Timer1LED, LOW);
}
}
if (Timer2Counting == 1) // If timer 2 is running then run the code to subtract time
{
digitalWrite(Timer2LED, HIGH); Timer2Mins = floor(Timer2Countdown / 60); Timer2Secs = (Timer2Countdown - (Timer2Mins * 60)); // Compute how much time left vs how much passed
Timer2Countdown --; // Subtract 1 Second from the clock Var
if (Timer2Countdown < 0) {
Timer2Counting = 0; // If time is up then stop the timer and turn on the alarm
Timer2InAlarm = 1;
digitalWrite(Timer2LED, LOW);
}
}
timeElapsedClock = 0; //1 second has passed now so reset the millisecond count again.
}
}
void TimerAlarms ()
{
if (Timer1InAlarm == 1) //If timer 1 is in alarm then flash the light and play notes on lcd
{
if (timeElapsedClock <= 300) {
digitalWrite(Timer1LED, LOW);
}
if (timeElapsedClock >= 700) {
digitalWrite(Timer1LED, HIGH);
Timer1AlarmTracking++;
tone(buzzer, Note2);
delay(1000);
noTone(buzzer);
}
if (Timer1AlarmTracking >= AlarmDuration) {
digitalWrite(Timer1LED, LOW); //If alarm duration has been met then stop the alarm
Timer1AlarmTracking = 0;
Timer1InAlarm = 0;
}
}
if (Timer2InAlarm == 1) //If timer 2 is in alarm then flash the light and play notes on lcd
{
if (timeElapsedClock <= 400) {
digitalWrite(Timer2LED, LOW);
}
if (timeElapsedClock >= 800) {
digitalWrite(Timer2LED, HIGH);
Timer2AlarmTracking++;
tone(buzzer, Note2);
delay(1000);
noTone(buzzer);
}
if (Timer2AlarmTracking >= AlarmDuration) {
digitalWrite(Timer2LED, LOW); //If alarm duration has been met then stop the alarm
Timer2AlarmTracking = 0;
Timer2InAlarm = 0;
}
}
}
void TooLong ()
{
if (Timer1Counting == 1 || Timer2Counting == 1) {
timeElapsedTooLong = 0; // If either timer is running then keep reseting the TooLong timer so it is not counting time when the time in use
TooLongAlarm = 0;
}
if (timeElapsedTooLong > (LeftOnTooLong * 1000)) // If it's been too long since the last alarm or keypress then go into too long alarm
{
OnTooLong = 1;
if (timeElapsedClock <= 200) {
digitalWrite(Timer2LED, LOW);
digitalWrite(Timer1LED, HIGH);
}
if (timeElapsedClock >= 800) {
digitalWrite(Timer2LED, HIGH);
digitalWrite(Timer1LED, LOW);
if (TooLongAlarm <= 3) {
tone(buzzer, Note3);
delay(1000);
noTone(buzzer);
TooLongAlarm++;
}
//tone(buzzer, Note3);
//delay(1000);
//noTone(buzzer);
}
}
}
void lcdTooLong ()
{
//lcd.write(Line1); // Change Display to msg until turned off or or another timer is started
lcd.setCursor(0,0);
lcd.print(" You Forgot Me! ");
//lcd.write(Line2);
lcd.setCursor(0,1);
lcd.print(" Turn Me Off! ");
}
| [
"iamsmolz@gmail.com"
] | iamsmolz@gmail.com |
9ac9573796014418909212d583c76884aed4716b | 810edea964dbef93cd47fa61f50efbf41528be7e | /university/usc_csci_530_secuirty_systems/project1/basedump.cc | a94731e826eb4dbf7bb530dd2bc77f5f9d056053 | [
"MIT"
] | permissive | sanjnair/projects | 2cee6e3c5f34d348067a34dc4be7535bc3b050df | 9d7fce9a9d219b7e63a06bb57d16f23e20eb4dc3 | refs/heads/master | 2021-01-20T00:09:05.448898 | 2017-04-27T07:33:06 | 2017-04-27T07:33:06 | 89,086,374 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,936 | cc | #include "basedump.h"
#include "hwconstant.h"
#include "hwutil.h"
/**
* C'tor.
*
* @param filePath File path
*/
BaseDump::BaseDump(std::string filePath) {
_filePath = filePath;
_fp = NULL;
}
/**
* Virtual D'tor.
*/
BaseDump::~BaseDump() {}
/**
* Opens the input file. If the file path is valid and open is successful,
* this methid creates a valid file pointer and keeps it. In this case, the
* return code will be 0. Otherwise, return code will be non-zero.
*
*/
int BaseDump::openInputFile() {
int status = 0;
if( _filePath.length() > 0 ) {
_fp = fopen(_filePath.c_str(), "rb");
} else{
_fp = stdin;
}
if( NULL == _fp ) {
std::string msg = "Error: Unable to open input file \"";
msg += _filePath;
msg += "\" for reading.";
HwUtil::setLastErrorMessage(msg);
status = HwConstant::ERROR_FILE_OPEN;;
}
return status;
}
/**
* Opens the input file. If the file path is valid and open is successful,
* this methid creates a valid file pointer and keeps it. In this case, the
* return code will be 0. Otherwise, return code will be non-zero.
*
*/
int BaseDump::closeInputFile() {
int status = 0;
if( NULL != _fp ) {
if( _filePath.length() > 0 ) {
status = fclose(_fp);
}
if( 0 != status ) {
std::string msg = "Error: Unable to close input file \"";
msg += _filePath;
msg += "\"";
HwUtil::setLastErrorMessage(msg);
status = HwConstant::ERROR_FILE_CLOSE;
}
}
return status;
}
/**
* Checks the read status of the file. If the read status is not
* correct, this method will update the error message and returns
* error code.
*/
int BaseDump::checkFileReadStatus() {
int status = 0;
if( NULL != _fp ) {
if( ferror(_fp) ) {
std::string msg = "Error: Reading from input resulted in error.";
HwUtil::setLastErrorMessage(msg);
status = HwConstant::ERROR_FILE_READ;
}
}
return status;
}
/**
* Creates the buffer and returns the pointer to buffer.
* If the buffer could not be created, this method returns
* error code and buffer pointer will points to NULL.
*
* NOTE: Caller need to de-allocate the memory after use.
*
* @param size Size of the buffer
* @param buffer_ptr Reference to buffer pointer
*/
int BaseDump::createBuffer( int size, unsigned char *& buffer_ptr ) const {
int status = 0;
buffer_ptr = NULL;
buffer_ptr = new unsigned char[size];
if( NULL == buffer_ptr ) {
std::string msg = "Unable to allocate memory for the buffer [";
msg += HwUtil::getString(size);
msg += "]";
HwUtil::setLastErrorMessage(msg);
status = HwConstant::ERROR_OUT_OF_MEMORY;
}
return status;
}
| [
"ssnair@gmail.com"
] | ssnair@gmail.com |
8166ac3a6de39247b1dd5a95da893adda40c5f85 | 8ac9ebed1775280fa42e722597272c2d62cbdc27 | /cpp/cpp_santa/includes/IObject.hh | 3202ad9d28937e199da6b7199d923a07cf48748c | [] | no_license | GabrielForteville/Epitech | 1147f0c84ea9e66eb7cf899fb4b91f10ae344fc6 | b8b3aa484390822e4a72c6a671b6a91e038831e6 | refs/heads/master | 2023-01-20T04:41:42.397935 | 2020-11-19T10:33:49 | 2020-11-19T10:33:49 | 298,345,123 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 575 | hh | //
// IObject.hh for in /home/hurlu/rendu/cpp_santa
//
// Made by Hugo Willaume
// Login <willau_h@epitech.net>
//
// Started on Sat Jan 14 13:38:37 2017 Hugo Willaume
// Last update Sun Jan 15 00:23:34 2017 Hugo Willaume
//
#ifndef IOBJECT_HH_
# define IOBJECT_HH_
#include <string>
class IObject{
private:
protected:
public:
virtual ~IObject() {};
virtual const std::string & getClass() const = 0;
virtual const std::string & getTitle() const = 0;
virtual void isTaken() const = 0;
virtual IObject *clone() const = 0;
};
#endif /* IOBJECT_HH_ */
| [
"gabriel.forteville@epitech.eu"
] | gabriel.forteville@epitech.eu |
de258134b02fb209b7c16ecb22ef973feb9fc6ab | f7730679928a1d2ff8c6801f89dff095b2230e36 | /Gouravjeet/b.cpp | 0102590256552787a871638e154aafbea5e4b3db | [] | no_license | gouravjeet/InterviewPreparation | 180105f6568d66a11c293d770e520555ed2cd217 | 4d9044a7d974238357c41ff078f1a5231003f5e7 | refs/heads/master | 2021-01-18T18:08:05.472047 | 2014-11-28T21:13:43 | 2014-11-28T21:13:43 | 20,082,107 | 0 | 0 | null | 2014-10-02T23:04:16 | 2014-05-23T00:50:17 | Java | UTF-8 | C++ | false | false | 103 | cpp | //b.cpp
#include "a.h"
#include <iostream>
using namespace std;
int main()
{
cout << foo;
return 0;
} | [
"gouravjeet@gmail.com"
] | gouravjeet@gmail.com |
497fb19f9a75e35ecc4996d516a171e36ce3126c | eddfe20e81069da60627a388028994e438b1786b | /include/gate.h | 6d5a5c8b7350e7ec128efa1638c0ce50e9791202 | [] | no_license | 2izo/Gates-Simulator | 9fed2262e63402c710afef2958f406e317e3bc7b | e4bc05dd7c2b7645a4f86645ab54eae4193bb38c | refs/heads/main | 2023-08-22T09:22:24.805408 | 2021-10-26T00:44:41 | 2021-10-26T00:44:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 792 | h | #ifndef GATE_H
#define GATE_H
#include "struct.h"
class gate
{
protected:
node *input1 = new node[1];
node *input2 = new node[1];
node *output = new node[1];
public:
virtual void GetOutput() = 0;
void setnames(string name1, string name2, string name3);
void setinput1(bool x, string name1);
void setinput2(bool y, string name2);
void setad1(node *ptr);
void setad2(node *ptr);
void setad3(node *ptr);
bool getinput1value();
bool getinput2value();
bool getoutputvalue();
string getinput1name();
string getinput2name();
string getoutputname();
int getinput1flag();
int getinput2flag();
bool print()
{
return output->value;
}
node *ipt1();
node *ipt2();
node *opt();
};
#endif // GATE_H
| [
"helloworld69069@yahoo.com"
] | helloworld69069@yahoo.com |
f1c75773ce272e459e8eb68dcc3e45e1870094b5 | 189f52bf5454e724d5acc97a2fa000ea54d0e102 | /ras/fluidisedBed/1.39/T.air | f29aff35e8c3d588cb61242cd4f9bfe1f82bde39 | [] | no_license | pyotr777/openfoam_samples | 5399721dd2ef57545ffce68215d09c49ebfe749d | 79c70ac5795decff086dd16637d2d063fde6ed0d | refs/heads/master | 2021-01-12T16:52:18.126648 | 2016-11-05T08:30:29 | 2016-11-05T08:30:29 | 71,456,654 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45,460 | air | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1606+ |
| \\ / A nd | Web: www.OpenFOAM.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "1.39";
object T.air;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 1 0 0 0];
internalField nonuniform List<scalar>
6000
(
526.632
529.422
530.707
532.189
532.046
529.777
527.653
526.756
526.975
527.695
528.999
529.504
529.252
528.858
528.721
528.84
528.68
527.924
527.601
527.787
529.3
531.703
534.342
536.654
537.306
538.545
538.395
537.538
536.287
533.072
590.35
593.567
593.9
593.704
592.868
590.239
583.504
580.97
582.26
583.779
586.137
587.777
587.484
585.826
585.332
585.439
584.462
581.687
580.221
581.371
586.169
591.723
593.945
594.972
595.302
595.499
595.633
595.804
596.013
594.249
598.279
599.378
599.483
599.328
598.867
597.12
591.182
588.984
590.85
593.76
595.833
596.893
596.473
594.944
594.612
594.669
593.6
591.064
589.317
589.668
593.859
598.152
599.239
599.539
599.624
599.667
599.703
599.735
599.65
599.135
599.563
599.843
599.875
599.81
599.597
598.8
594.787
591.956
592.621
595.467
597.414
598.396
598.438
597.655
597.304
597.268
596.333
594.503
593.154
593.058
595.492
598.874
599.719
599.896
599.928
599.936
599.938
599.934
599.902
599.811
599.858
599.918
599.927
599.909
599.849
599.595
598.002
594.49
593.709
594.89
596.866
598.227
598.871
598.762
598.449
598.395
597.834
596.774
595.843
595.458
596.325
598.916
599.776
599.93
599.952
599.956
599.956
599.954
599.948
599.936
599.934
599.946
599.948
599.945
599.936
599.866
599.315
597.048
595.062
595.172
596.131
597.744
598.842
599.124
599.045
598.999
598.729
598.191
597.703
597.33
597.515
599.014
599.82
599.937
599.955
599.962
599.964
599.964
599.963
599.962
599.961
599.963
599.963
599.962
599.959
599.932
599.747
598.785
596.804
596.119
596.488
597.7
598.881
599.327
599.365
599.352
599.244
598.975
598.752
598.507
598.538
599.271
599.838
599.932
599.952
599.966
599.971
599.972
599.971
599.97
599.972
599.972
599.972
599.972
599.968
599.944
599.838
599.413
598.067
597.42
597.584
598.408
599.232
599.554
599.597
599.593
599.549
599.42
599.324
599.193
599.186
599.511
599.832
599.911
599.942
599.966
599.974
599.975
599.974
599.973
599.978
599.978
599.978
599.977
599.971
599.935
599.819
599.533
598.69
598.494
598.794
599.295
599.603
599.723
599.746
599.746
599.727
599.67
599.627
599.57
599.561
599.683
599.817
599.879
599.925
599.961
599.975
599.978
599.978
599.977
599.981
599.982
599.981
599.979
599.968
599.907
599.757
599.543
599.171
599.208
599.445
599.646
599.758
599.809
599.824
599.825
599.815
599.793
599.774
599.753
599.748
599.778
599.824
599.862
599.905
599.953
599.973
599.979
599.981
599.98
599.984
599.984
599.984
599.98
599.96
599.872
599.697
599.549
599.456
599.538
599.678
599.78
599.838
599.865
599.873
599.872
599.865
599.853
599.843
599.836
599.834
599.839
599.849
599.863
599.883
599.93
599.965
599.979
599.983
599.983
599.986
599.986
599.985
599.978
599.942
599.821
599.668
599.589
599.623
599.713
599.802
599.86
599.89
599.903
599.908
599.906
599.901
599.894
599.889
599.888
599.89
599.894
599.897
599.898
599.896
599.913
599.946
599.974
599.983
599.985
599.988
599.988
599.986
599.975
599.927
599.801
599.708
599.729
599.787
599.844
599.885
599.906
599.917
599.924
599.928
599.93
599.927
599.922
599.918
599.916
599.919
599.922
599.923
599.924
599.921
599.924
599.938
599.964
599.982
599.986
599.99
599.99
599.987
599.972
599.921
599.837
599.811
599.854
599.882
599.901
599.913
599.92
599.924
599.928
599.933
599.939
599.938
599.934
599.929
599.926
599.927
599.928
599.93
599.932
599.931
599.931
599.937
599.955
599.979
599.986
599.991
599.992
599.989
599.969
599.923
599.879
599.878
599.896
599.908
599.916
599.921
599.925
599.928
599.931
599.935
599.941
599.942
599.939
599.934
599.931
599.931
599.932
599.934
599.937
599.937
599.937
599.941
599.953
599.976
599.986
599.993
599.993
599.989
599.965
599.925
599.905
599.907
599.915
599.92
599.924
599.926
599.928
599.931
599.934
599.937
599.943
599.944
599.941
599.937
599.935
599.934
599.935
599.937
599.939
599.942
599.943
599.946
599.953
599.974
599.985
599.994
599.995
599.989
599.962
599.932
599.921
599.922
599.925
599.927
599.928
599.929
599.93
599.932
599.936
599.939
599.944
599.945
599.943
599.939
599.937
599.937
599.937
599.939
599.943
599.946
599.947
599.95
599.955
599.973
599.984
599.995
599.995
599.988
599.962
599.94
599.931
599.931
599.932
599.932
599.932
599.932
599.932
599.935
599.938
599.941
599.945
599.946
599.944
599.941
599.94
599.939
599.94
599.943
599.947
599.951
599.953
599.954
599.958
599.972
599.984
599.996
599.995
599.988
599.963
599.946
599.94
599.939
599.938
599.937
599.935
599.935
599.935
599.938
599.941
599.943
599.947
599.948
599.946
599.944
599.943
599.942
599.944
599.949
599.954
599.958
599.96
599.962
599.964
599.975
599.984
599.997
599.996
599.988
599.966
599.953
599.948
599.946
599.944
599.941
599.939
599.939
599.939
599.942
599.944
599.946
599.948
599.949
599.948
599.947
599.945
599.945
599.95
599.957
599.962
599.965
599.967
599.968
599.971
599.978
599.985
599.997
599.996
599.99
599.974
599.961
599.956
599.952
599.949
599.946
599.944
599.943
599.944
599.947
599.948
599.949
599.95
599.951
599.95
599.949
599.948
599.95
599.956
599.962
599.966
599.969
599.971
599.973
599.975
599.979
599.985
599.997
599.996
599.991
599.98
599.968
599.962
599.957
599.953
599.95
599.948
599.948
599.949
599.951
599.952
599.952
599.953
599.953
599.952
599.951
599.951
599.955
599.961
599.967
599.97
599.973
599.974
599.976
599.977
599.98
599.985
599.998
599.997
599.993
599.987
599.977
599.969
599.962
599.957
599.954
599.953
599.953
599.954
599.956
599.956
599.955
599.955
599.955
599.954
599.954
599.955
599.961
599.967
599.971
599.974
599.976
599.977
599.978
599.98
599.982
599.986
599.997
599.997
599.994
599.991
599.985
599.974
599.966
599.961
599.959
599.958
599.959
599.959
599.96
599.96
599.959
599.958
599.957
599.957
599.956
599.959
599.966
599.971
599.975
599.977
599.979
599.98
599.981
599.982
599.983
599.986
599.997
599.997
599.995
599.992
599.988
599.98
599.971
599.966
599.964
599.964
599.964
599.964
599.965
599.964
599.962
599.961
599.96
599.959
599.959
599.965
599.971
599.975
599.978
599.98
599.981
599.982
599.983
599.984
599.985
599.987
599.997
599.997
599.995
599.992
599.989
599.983
599.976
599.971
599.969
599.969
599.968
599.969
599.969
599.968
599.966
599.965
599.963
599.962
599.963
599.969
599.974
599.977
599.98
599.981
599.983
599.984
599.985
599.985
599.986
599.987
599.997
599.997
599.995
599.992
599.989
599.985
599.98
599.975
599.974
599.973
599.973
599.973
599.973
599.973
599.971
599.969
599.968
599.965
599.967
599.973
599.977
599.979
599.981
599.983
599.984
599.985
599.986
599.987
599.987
599.988
599.997
599.996
599.994
599.992
599.99
599.986
599.981
599.978
599.976
599.976
599.977
599.977
599.977
599.977
599.975
599.975
599.974
599.97
599.972
599.975
599.978
599.98
599.982
599.984
599.985
599.986
599.987
599.988
599.988
599.988
599.997
599.996
599.995
599.993
599.991
599.988
599.982
599.979
599.978
599.978
599.979
599.98
599.981
599.981
599.981
599.981
599.98
599.975
599.975
599.977
599.979
599.981
599.983
599.984
599.986
599.987
599.988
599.989
599.989
599.989
599.997
599.996
599.996
599.994
599.993
599.989
599.984
599.981
599.98
599.981
599.981
599.983
599.984
599.985
599.987
599.987
599.985
599.98
599.978
599.978
599.98
599.982
599.984
599.985
599.986
599.988
599.989
599.989
599.99
599.99
599.998
599.997
599.997
599.996
599.993
599.991
599.986
599.984
599.983
599.983
599.984
599.985
599.987
599.989
599.991
599.992
599.989
599.984
599.982
599.981
599.981
599.983
599.984
599.986
599.988
599.989
599.99
599.99
599.991
599.992
599.998
599.998
599.998
599.995
599.993
599.992
599.99
599.988
599.986
599.986
599.987
599.989
599.99
599.992
599.994
599.995
599.993
599.989
599.986
599.985
599.985
599.985
599.986
599.988
599.989
599.99
599.991
599.991
599.992
599.992
599.999
599.998
599.996
599.992
599.99
599.99
599.988
599.987
599.987
599.989
599.99
599.991
599.993
599.994
599.995
599.996
599.995
599.992
599.99
599.989
599.988
599.987
599.987
599.988
599.989
599.991
599.992
599.993
599.993
599.994
599.999
599.998
599.996
599.995
599.997
599.995
599.992
599.989
599.987
599.987
599.989
599.992
599.994
599.995
599.994
599.993
599.991
599.989
599.988
599.987
599.987
599.989
599.992
599.995
599.994
599.993
599.993
599.994
599.994
599.995
599.998
599.998
599.997
599.999
600.002
600.001
599.998
599.996
599.995
599.993
599.993
599.993
599.994
599.995
599.996
599.995
599.993
599.992
599.991
599.991
599.993
599.995
599.998
599.999
599.998
599.995
599.994
599.995
599.995
599.996
599.998
599.998
599.997
600.001
600.004
600.004
600.001
600
599.999
599.999
599.998
599.998
599.998
599.998
599.998
599.998
599.998
599.997
599.997
599.997
599.998
599.999
600
600.001
600
599.998
599.995
599.996
599.997
599.997
599.998
599.998
599.997
600.002
600.005
600.004
600.002
600.001
600.001
600.001
600
600
600
600
600
600
600
600
600
600
600
600
600.001
600.001
600.001
600
599.996
599.997
599.997
599.998
599.998
599.997
599.999
600.003
600.004
600.003
600.002
600.001
600.001
600.001
600
600
600
600
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
599.999
599.998
599.998
599.999
599.998
599.997
600
600.003
600.003
600.002
600.001
600.001
600
600
600
599.999
599.999
599.999
599.999
600
600
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
599.999
599.998
599.999
599.997
599.998
600
600.002
600.002
600.001
600
600
600
600
599.999
599.999
599.999
599.999
599.999
600
600
600
600
600
600
600
600
600
600
600.001
600.001
600
599.999
599.999
599.998
599.999
600
600.001
600.001
600
600
599.999
599.999
599.999
599.999
599.999
599.998
599.999
599.999
600
600
600
600
600
600
600
600
600
600
600.001
600.001
600
599.999
599.999
599.998
599.999
599.999
600
600
600
599.999
599.999
599.999
599.999
599.999
599.998
599.998
599.999
599.999
599.999
600
599.999
599.999
599.999
599.999
599.999
599.999
599.999
600
600
600.001
599.999
599.999
599.999
599.998
599.998
599.999
600
600
600
600
599.999
599.999
599.999
599.998
599.998
599.998
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
600
600
600.001
599.999
599.999
599.999
599.998
599.999
599.999
600
600
600
600
599.999
599.999
599.999
599.998
599.998
599.998
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
600
600
600.001
599.999
599.999
599.999
599.998
599.999
599.999
600
600
600
600
600
599.999
599.999
599.998
599.998
599.998
599.999
599.999
600
599.999
599.999
599.999
599.999
599.999
599.999
599.999
600
600
600
600.001
599.999
599.999
599.999
599.999
599.999
599.999
599.999
600
600
600
600
600
599.999
599.999
599.998
599.999
599.999
600
600
600
600
599.999
599.999
599.999
600
600
600
600
600.001
600.001
600
599.999
599.999
599.999
599.999
599.999
599.999
600
600
600
600
600
600
599.999
599.999
599.999
599.999
600
600
600
600
600
600
600
600
600
600
600.001
600.001
600.001
600
599.999
599.999
599.999
599.999
599.999
599.999
599.999
600
600
600
600
600
600
599.999
599.999
600
600
600
600
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
600
600
600
600
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
600
600
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
599.999
599.999
600
599.999
599.999
599.999
599.999
599.999
599.999
600
600
600
599.999
599.999
600
600
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.001
600.001
600.001
600
600
600
600
600
600
600
599.999
599.999
599.999
599.999
599.999
600
600
599.999
599.999
599.999
599.999
599.999
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
600
600
600
600
600
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
600
600
600.001
600.001
600.001
600.001
600.001
600
600
600
600
600
600
600
600
600
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
600
600
600
600
600.001
600
600
600
600
600
600
600
600
600
600
600
600
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
599.999
599.999
599.999
599.999
600
599.999
599.999
599.999
599.999
599.999
600
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
599.999
599.999
599.999
599.999
599.999
600
599.999
599.999
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
599.999
599.999
599.999
599.999
599.999
599.999
599.999
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
599.999
599.996
600
599.999
599.999
599.999
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
599.999
600.002
599.998
599.999
599.999
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
599.999
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
599.999
600
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
599.995
599.999
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
599.995
599.996
599.998
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
599.996
599.996
599.997
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
599.999
599.998
599.998
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600.001
600
600
599.999
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600.001
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600.001
600
600
600
600
600
600
600
600
600
600
600
600
600.001
600
600.001
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
600
600
600
600
600
600
600
600
600.001
600
600
600
600
600
600
600
600.001
600
600
600.001
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
600
600
600
600
600
600
600
600.001
600
600.001
600
600
600
600
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
600
600
600
600
600.003
600.001
600.001
600.001
600.001
600.001
600.001
600
600
600.001
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600.004
600.003
600
600.001
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.004
600.001
600.001
600.001
600.001
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.004
600.001
600.001
600.002
600.001
600.001
600.001
600.001
600.001
600
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600.001
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.001
600.001
600.001
600.002
600.001
600.001
600.001
600
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.001
600
600.001
600.002
600.002
600.002
600.002
600.001
600.001
600.002
600.002
600.001
600.001
600.001
600.001
600.002
600.001
600
600.001
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.002
600.001
600.002
600.002
600.001
600.001
600.002
600.002
600.002
600.002
600.002
600.001
600.001
600.002
599.999
600.002
600.001
600.001
600.001
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.001
600.001
600.001
600.002
600.002
600.002
600.002
600.002
600.001
600.002
600.003
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.002
600.002
600.002
600.001
600.001
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600.001
600.001
600.001
600.002
600.002
600.002
600.002
600.002
600.002
600.001
600.002
600.002
600.003
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.002
600.002
600.002
600.002
600.001
600.001
600.002
600.002
600
600.004
600.002
600.002
600.002
600.002
600.002
600.002
600.003
600.002
600.002
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600.001
600.001
600.001
600.002
600.002
599.999
600
599.998
599.994
599.987
599.973
600.002
600.002
600.002
600.002
600.002
600.002
600.003
600.002
600.002
600.002
600.002
600.002
600.002
600.001
600.002
600.002
600.002
600.002
600.002
600.002
600.001
600.002
600.002
600.001
599.994
599.983
599.97
599.953
599.935
599.912
600.002
600.002
600.002
600.002
600.002
600.002
600.003
600.002
600.002
600.002
600.002
600.002
600.001
600.002
600.002
600.002
600.001
600.001
600.001
600.001
600.001
600
599.996
599.986
599.967
599.959
599.96
599.96
599.963
599.957
600.003
600.003
600.001
600
599.997
599.995
599.998
600.001
600.002
600.002
600.002
600.003
600.002
600.001
599.999
599.996
599.992
599.992
599.994
599.993
599.991
599.984
599.972
599.959
599.967
599.994
600.008
600.01
600.009
600.007
600.018
600.019
600.013
600.008
600.002
599.998
599.999
600.004
600.004
600.002
600.003
600.002
600.002
599.998
599.989
599.978
599.975
599.978
599.979
599.976
599.97
599.966
599.969
599.984
600.01
600.036
600.05
600.051
600.045
600.039
600.026
600.035
600.03
600.025
600.019
600.015
600.01
600.009
600.004
600.003
600.003
600.002
600.001
599.991
599.979
599.981
599.989
599.994
599.995
599.993
599.994
599.999
600.01
600.026
600.047
600.069
600.081
600.081
600.071
600.056
600.026
600.038
600.034
600.029
600.024
600.02
600.015
600.006
600.003
600.003
600.003
600.002
599.998
599.982
599.98
599.996
600.009
600.018
600.022
600.024
600.027
600.034
600.044
600.059
600.075
600.09
600.1
600.101
600.092
600.073
600.025
600.038
600.032
600.027
600.023
600.017
600.008
600.003
600.003
600.003
600.002
600.001
599.992
599.974
599.982
600.005
600.021
600.032
600.038
600.043
600.048
600.056
600.066
600.077
600.09
600.101
600.109
600.111
600.105
600.09
600.022
600.034
600.027
600.022
600.019
600.015
600.008
600.001
600.002
600.002
600.001
600.001
599.987
599.973
599.987
600.01
600.026
600.036
600.043
600.048
600.055
600.064
600.074
600.085
600.096
600.106
600.112
600.115
600.111
600.103
600.018
600.026
600.02
600.016
600.014
600.012
600.011
600.005
600
600
600
599.998
599.985
599.976
599.992
600.013
600.028
600.037
600.042
600.047
600.053
600.062
600.073
600.085
600.096
600.105
600.111
600.114
600.111
600.105
600.014
600.019
600.014
600.011
600.009
600.008
600.008
600.008
600.004
600.005
600.004
599.997
599.99
599.981
599.994
600.014
600.028
600.036
600.039
600.042
600.047
600.055
600.067
600.08
600.092
600.101
600.108
600.11
600.108
600.103
600.009
600.012
600.008
600.006
600.005
600.004
600.005
600.006
600.006
600.008
600.006
600.003
599.992
599.979
599.991
600.012
600.026
600.033
600.036
600.037
600.04
600.046
600.057
600.071
600.084
600.094
600.101
600.104
600.103
600.097
600.006
600.008
600.004
600.003
600.003
600.002
600.003
600.003
600.004
600.005
600.006
600.003
599.991
599.975
599.984
600.007
600.022
600.03
600.033
600.033
600.034
600.037
600.046
600.059
600.073
600.084
600.092
600.096
600.095
600.089
600.006
600.006
600.002
600.002
600.001
600.001
600.001
600.002
600.002
600.003
600.004
600.002
599.992
599.973
599.977
600
600.017
600.026
600.029
600.029
600.028
600.03
600.035
600.046
600.06
600.073
600.081
600.086
600.085
600.08
599.996
600.004
600.003
600.001
600
600.001
600.001
600.001
600.001
600.001
600.002
600.003
599.995
599.973
599.97
599.992
600.01
600.02
600.024
600.025
600.024
600.024
600.026
600.034
600.046
600.059
600.068
600.073
600.074
600.07
600
599.997
600.003
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.003
599.997
599.978
599.967
599.986
600.004
600.014
600.018
600.02
600.02
600.019
600.019
600.024
600.033
600.043
600.052
600.058
600.059
600.057
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
599.998
599.984
599.969
599.984
599.998
600.007
600.012
600.015
600.016
600.015
600.014
600.015
600.02
600.028
600.035
600.04
600.041
600.042
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600.001
599.999
599.989
599.974
599.984
599.995
600.002
600.005
600.008
600.01
600.01
600.009
600.009
600.011
600.015
600.02
600.023
600.023
600.024
600
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600
600
600
599.999
599.992
599.981
599.987
599.994
599.997
599.999
600.002
600.004
600.006
600.006
600.006
600.006
600.007
600.009
600.01
600.01
600.009
599.999
600.001
600.001
600.001
600
600
600
600
600
600
600
599.999
599.999
599.995
599.99
599.992
599.994
599.995
599.995
599.996
599.998
600.002
600.003
600.003
600.002
600.002
600.003
600.003
600.002
600
600.001
600
600
600
599.999
600
599.999
599.999
599.999
599.999
599.999
599.999
600
600.003
599.997
599.994
599.994
599.993
599.992
599.992
599.993
599.996
599.999
600.001
600.001
600
599.999
599.999
599.998
599.997
600.012
600.006
600
600
600
599.998
599.998
599.998
599.998
599.998
599.998
600
600.004
600.014
599.999
599.994
599.993
599.992
599.991
599.99
599.99
599.991
599.994
599.997
599.998
599.998
599.998
599.997
599.996
599.995
600.001
600.002
599.998
599.999
599.998
599.998
599.997
599.997
599.998
599.999
600.002
600.008
600.022
600.006
599.997
599.993
599.992
599.991
599.99
599.989
599.988
599.988
599.99
599.994
599.996
599.997
599.997
599.996
599.995
599.995
599.998
599.993
599.997
599.997
599.997
599.996
599.995
599.997
600
600.006
600.017
600.032
600.023
600.004
599.994
599.991
599.99
599.99
599.99
599.99
599.989
599.987
599.988
599.99
599.993
599.995
599.996
599.995
599.995
599.994
599.99
599.982
599.997
599.997
599.996
599.995
599.997
600.002
600.014
600.033
600.048
600.041
600.015
599.998
599.99
599.988
599.988
599.99
599.99
599.991
599.99
599.988
599.987
599.988
599.99
599.993
599.994
599.994
599.994
599.993
599.989
599.99
599.998
599.997
599.997
599.998
600.007
600.026
600.049
600.059
600.045
600.021
600.001
599.989
599.985
599.985
599.986
599.989
599.99
599.992
599.991
599.99
599.988
599.987
599.988
599.99
599.992
599.992
599.992
599.992
599.993
599.995
599.998
599.997
599.998
600.008
600.038
600.066
600.064
600.042
600.018
599.999
599.988
599.982
599.981
599.982
599.984
599.987
599.99
599.992
599.993
599.993
599.991
599.989
599.988
599.989
599.99
599.992
599.991
599.99
599.995
599.996
599.998
599.997
600.003
600.038
600.076
600.067
600.038
600.012
599.995
599.985
599.98
599.978
599.978
599.98
599.982
599.985
599.989
599.993
599.996
599.996
599.994
599.991
599.989
599.988
599.989
599.989
599.989
599.989
599.996
599.996
599.998
599.999
600.016
600.066
600.062
600.028
600.005
599.99
599.981
599.977
599.975
599.975
599.976
599.977
599.979
599.983
599.988
599.993
599.997
599.999
599.998
599.994
599.991
599.989
599.988
599.989
599.988
599.988
599.997
599.995
599.998
600
600.025
600.049
600.022
599.999
599.986
599.978
599.975
599.974
599.973
599.973
599.973
599.975
599.978
599.983
599.989
599.994
599.998
600
599.999
599.997
599.993
599.99
599.989
599.989
599.987
599.986
599.997
599.996
599.998
600.001
600.022
600.019
599.996
599.982
599.976
599.973
599.973
599.972
599.972
599.972
599.972
599.975
599.979
599.985
599.991
599.996
599.999
600
600
599.998
599.995
599.991
599.988
599.986
599.986
599.985
599.996
599.998
600
600.002
600.01
599.995
599.98
599.973
599.972
599.971
599.972
599.972
599.972
599.972
599.973
599.977
599.982
599.989
599.995
599.998
599.999
599.999
599.999
599.998
599.994
599.992
599.989
599.984
599.985
599.984
599.998
600.006
600.002
600.001
599.99
599.969
599.966
599.967
599.969
599.97
599.972
599.973
599.973
599.974
599.976
599.981
599.987
599.994
599.998
600
599.999
599.998
599.998
599.998
599.998
599.994
599.99
599.986
599.984
599.983
600
600.015
600.006
600.001
599.992
599.967
599.959
599.963
599.967
599.97
599.972
599.974
599.975
599.977
599.981
599.986
599.993
599.998
600.001
600.001
599.999
599.997
599.996
599.996
599.996
599.994
599.991
599.987
599.985
599.983
600.001
600.019
600.016
600.004
599.996
599.982
599.961
599.963
599.968
599.971
599.974
599.976
599.978
599.982
599.986
599.991
599.998
600.002
600.002
600
599.998
599.995
599.995
599.995
599.995
599.994
599.992
599.988
599.985
599.983
599.999
600.045
600.029
600.014
600
599.993
599.971
599.967
599.971
599.975
599.977
599.98
599.983
599.987
599.992
599.997
600.001
600.003
600.002
599.998
599.995
599.993
599.993
599.994
599.995
599.993
599.993
599.99
599.986
599.983
600.015
599.999
600.003
600.013
600.003
599.999
599.986
599.974
599.976
599.98
599.983
599.985
599.987
599.991
599.995
600
600.003
600.003
600
599.995
599.992
599.992
599.993
599.994
599.995
599.996
599.994
599.991
599.987
599.984
600.015
599.983
599.995
600.003
600.002
599.999
599.994
599.979
599.981
599.986
599.989
599.991
599.993
599.996
599.999
600.003
600.004
600.001
599.997
599.993
599.991
599.991
599.993
599.994
599.995
599.995
599.994
599.992
599.988
599.984
600.005
599.992
599.991
599.998
599.999
600
599.997
599.984
599.985
599.992
599.996
599.997
599.997
599.999
600.001
600.003
600.002
599.998
599.994
599.991
599.991
599.992
599.993
599.995
599.996
599.996
599.994
599.993
599.99
599.985
600
599.994
599.99
599.997
600.001
600
599.998
599.988
599.988
599.998
600.002
600.002
600.001
600.001
600.001
600.002
599.999
599.995
599.991
599.99
599.991
599.992
599.994
599.995
599.997
599.997
599.997
599.994
599.991
599.986
599.984
599.977
599.99
599.997
600
600.002
599.999
599.993
599.991
600.001
600.006
600.005
600.003
600.002
600.001
599.999
599.995
599.992
599.99
599.99
599.992
599.993
599.994
599.996
599.998
599.998
599.997
599.994
599.993
599.987
599.995
599.989
599.99
599.993
600.004
600.004
600
599.997
599.993
600.002
600.008
600.007
600.004
600.001
599.999
599.995
599.992
599.99
599.99
599.99
599.992
599.993
599.995
599.997
599.999
599.999
599.999
599.998
599.99
599.989
600
599.999
599.994
599.991
599.993
599.999
599.999
599.999
599.997
600.003
600.008
600.006
600.003
599.999
599.996
599.993
599.991
599.99
599.99
599.99
599.991
599.993
599.996
599.998
600
600
600
599.999
600
599.994
599.999
600
599.999
599.996
599.994
599.997
599.999
599.999
599.998
600.002
600.006
600.004
600
599.997
599.994
599.992
599.991
599.99
599.99
599.991
599.992
599.994
599.997
600
600.001
600.001
600.001
600
599.998
599.994
599.999
600
600
599.999
599.997
599.997
599.999
599.999
599.999
600.002
600.004
600.002
599.998
599.995
599.993
599.992
599.991
599.991
599.991
599.991
599.993
599.996
599.999
600.001
600.002
600.002
600.001
599.999
599.998
600
599.999
600
600
600
599.999
599.998
599.998
599.999
600
600.001
600.001
599.999
599.997
599.995
599.993
599.992
599.992
599.992
599.992
599.993
599.995
599.998
600.001
600.002
600.003
600.002
600
599.998
599.997
599.998
600
600.003
600.004
599.998
599.999
599.999
599.997
599.997
600
600
600
599.998
599.997
599.995
599.994
599.993
599.993
599.993
599.993
599.995
599.998
600
600.002
600.003
600.003
600.001
599.999
599.997
599.996
599.996
600
600.004
600
599.998
600
600
599.999
599.997
599.998
599.999
599.999
599.998
599.997
599.996
599.994
599.994
599.993
599.994
599.994
599.996
599.999
600.001
600.002
600.002
600.002
600
599.997
599.995
599.995
599.994
600.002
599.996
600.002
599.997
600.001
600.005
600.003
599.997
599.997
599.999
599.999
599.999
599.997
599.996
599.994
599.994
599.994
599.994
599.995
599.998
600
600.001
600.002
600.001
600
599.998
599.995
599.993
599.993
599.993
600.001
600.001
599.997
600.001
600.006
600.018
600.006
599.996
599.995
599.998
600.001
600.001
599.999
599.996
599.995
599.994
599.994
599.994
599.996
599.998
600
600.001
600
600
599.999
599.996
599.992
599.989
599.989
599.991
600
600.001
600.001
600.004
600.014
600.016
600.004
599.993
599.992
599.995
600.001
600.005
600.004
599.999
599.995
599.994
599.994
599.995
599.996
599.999
600
600
599.999
599.998
599.997
599.994
599.99
599.986
599.984
599.986
600
600
600.002
600.005
600.009
600.008
599.999
599.99
599.988
599.992
599.999
600.007
600.01
600.006
600
599.996
599.995
599.996
599.997
599.999
600
599.999
599.998
599.998
599.996
599.993
599.989
599.985
599.981
599.979
599.999
599.998
600.001
600.003
600.005
600.003
599.996
599.987
599.984
599.987
599.995
600.004
600.013
600.016
600.01
600.001
599.997
599.997
599.998
600
600
600
599.999
599.998
599.996
599.993
599.989
599.985
599.981
599.979
599.999
599.998
600
600.002
600.004
600.002
599.994
599.985
599.981
599.982
599.988
599.997
600.007
600.017
600.021
600.013
600.001
599.999
599.999
600
600.001
600.002
600.002
600
599.997
599.992
599.988
599.986
599.983
599.98
599.999
599.998
599.998
600.003
600.004
600
599.992
599.983
599.978
599.977
599.981
599.989
599.998
600.007
600.015
600.016
600.006
600
600
600.001
600.002
600.003
600.004
600.002
599.998
599.992
599.988
599.985
599.984
599.981
599.999
599.998
600.001
600.003
600.002
599.997
599.989
599.981
599.974
599.973
599.975
599.98
599.987
599.995
600.001
600.003
600.002
600
599.999
600.003
600.003
600.005
600.006
600.004
599.999
599.992
599.987
599.985
599.983
599.982
599.999
599.998
600
600.002
600
599.993
599.984
599.975
599.97
599.968
599.969
599.973
599.978
599.983
599.987
599.989
599.989
599.994
600.001
599.999
600.003
600.005
600.007
600.005
599.999
599.993
599.988
599.986
599.984
599.983
599.999
599.998
599.999
600.001
599.999
599.992
599.981
599.971
599.965
599.964
599.964
599.967
599.97
599.974
599.977
599.978
599.978
599.984
599.997
600.002
600.003
600.005
600.007
600.005
600
599.994
599.99
599.988
599.987
599.987
599.999
599.999
599.997
600
599.999
599.991
599.978
599.967
599.962
599.96
599.96
599.962
599.965
599.967
599.969
599.97
599.97
599.975
599.992
600
600.003
600.005
600.006
600.005
600
599.995
599.993
599.992
599.992
599.993
599.999
599.999
600.002
600
599.999
599.992
599.977
599.965
599.959
599.957
599.957
599.958
599.96
599.963
599.964
599.965
599.966
599.97
599.987
599.999
600.002
600.003
600.004
600.003
600
599.997
599.996
599.996
599.996
599.999
600
599.999
600
600.001
600.001
599.994
599.977
599.964
599.957
599.955
599.955
599.956
599.958
599.96
599.962
599.964
599.966
599.972
599.986
599.997
600.001
600.002
600.002
600
599.999
599.998
599.998
599.998
600
600.004
600
599.999
600
600.001
600.002
599.996
599.978
599.964
599.957
599.955
599.955
599.956
599.958
599.96
599.961
599.964
599.968
599.976
599.989
599.998
600.003
600
599.999
599.998
599.997
599.997
599.998
600
600.002
599.999
600
600
600
600.001
600.002
599.996
599.979
599.965
599.958
599.957
599.956
599.957
599.959
599.96
599.962
599.965
599.97
599.98
599.997
600.006
599.998
600
599.998
599.997
599.996
599.996
599.997
600
600.003
600.004
600
600
600
600.001
600.002
599.997
599.981
599.967
599.961
599.959
599.959
599.96
599.961
599.962
599.964
599.967
599.972
599.982
599.998
600.014
600.005
600
599.998
599.997
599.996
599.996
599.997
599.999
600.003
600.006
600.001
600.001
600.001
600.001
600.002
599.997
599.982
599.97
599.965
599.963
599.963
599.963
599.964
599.965
599.966
599.968
599.973
599.981
599.998
600.02
600.011
600.001
599.999
599.998
599.997
599.996
599.997
599.999
600.002
600.001
600.001
600.001
600.001
600.001
600.002
599.997
599.983
599.973
599.969
599.967
599.966
599.966
599.967
599.967
599.968
599.97
599.973
599.98
599.993
600.013
600.024
600.006
600
599.999
599.998
599.997
599.997
599.998
600
600.002
600.002
600.002
600.001
600.001
600.001
599.996
599.984
599.976
599.972
599.97
599.969
599.969
599.97
599.97
599.97
599.971
599.973
599.978
599.989
600.006
600.026
600.012
600.001
599.999
599.999
599.999
599.998
599.998
599.998
599.998
600.001
600.003
600.002
600.001
600.001
599.996
599.985
599.978
599.975
599.973
599.972
599.972
599.972
599.972
599.972
599.973
599.974
599.977
599.984
599.998
600.014
600.014
600.003
600
600
599.999
599.999
599.998
599.998
599.996
600
600.002
600.002
600.001
600.001
599.996
599.986
599.981
599.978
599.976
599.975
599.975
599.975
599.975
599.974
599.975
599.975
599.977
599.981
599.99
600.003
600.009
600.002
600
600
600
600
599.999
599.998
599.997
600
600.001
600.001
600.001
600.001
599.997
599.989
599.984
599.981
599.979
599.977
599.977
599.977
599.977
599.976
599.976
599.977
599.977
599.98
599.987
599.997
600.004
600.001
600
600
600
600
600
599.999
599.998
600
600
600.001
600.001
600.001
599.999
599.992
599.987
599.984
599.981
599.98
599.979
599.979
599.979
599.978
599.978
599.978
599.978
599.98
599.986
599.996
600.004
600
599.999
600
600
600
600
600
600
600
600
600
600.001
600.001
600
599.995
599.99
599.986
599.984
599.982
599.982
599.981
599.981
599.98
599.98
599.98
599.98
599.981
599.987
599.999
600.008
600.002
599.999
599.999
600
600
600
600
600
600.001
600
600
600.001
600.001
600
599.997
599.993
599.989
599.986
599.984
599.984
599.983
599.983
599.982
599.981
599.981
599.981
599.982
599.988
600.001
600.015
600.006
600
599.999
599.999
600
600
600
600
599.99
599.997
600
600.001
600.001
600
599.999
599.996
599.992
599.989
599.987
599.986
599.985
599.984
599.984
599.983
599.983
599.983
599.983
599.989
600.002
600.018
600.013
600.002
599.999
599.999
599.999
599.999
600
600
599.981
599.988
599.995
599.999
600
599.999
600.001
599.999
599.995
599.991
599.989
599.988
599.987
599.986
599.985
599.985
599.984
599.984
599.984
599.989
600
600.015
600.018
600.004
600
599.999
599.999
600
600
600
600
599.991
599.989
599.994
599.997
600
600.003
600.002
599.998
599.994
599.991
599.99
599.988
599.988
599.987
599.986
599.986
599.985
599.985
599.988
599.997
600.01
600.016
600.006
600
599.999
599.999
600
600
600
600.004
599.999
599.99
599.99
599.997
600.001
600.003
600.003
600.001
599.997
599.994
599.992
599.99
599.989
599.989
599.988
599.987
599.987
599.986
599.988
599.994
600.005
600.012
600.005
600
599.999
599.999
600
600
600
600.003
600.001
599.996
599.993
599.995
599.999
600.002
600.003
600.003
599.999
599.996
599.993
599.992
599.991
599.99
599.99
599.989
599.988
599.988
599.988
599.993
600.002
600.008
600.002
599.999
599.999
599.999
600
600
600
600.003
600.001
599.998
599.994
599.994
599.998
600
600.002
600.003
600.001
599.998
599.995
599.994
599.993
599.992
599.991
599.991
599.99
599.989
599.99
599.993
600.002
600.007
600.001
600
599.999
600
600
600
600.001
599.997
600.001
599.999
599.996
599.994
599.995
599.999
600.001
600.002
600.002
600
599.997
599.995
599.995
599.994
599.993
599.993
599.992
599.991
599.991
599.994
600.002
600.007
600.001
600
600
600.001
600
600.001
600.001
600.04
600.003
600
599.997
599.995
599.994
599.996
599.999
600.001
600.002
600.001
599.999
599.997
599.996
599.995
599.995
599.994
599.994
599.993
599.993
599.995
600.002
600.007
600.001
600
599.998
600.001
600
600.001
600.001
600.007
600.003
600
599.998
599.996
599.994
599.995
599.998
600
600.001
600.001
600
599.999
599.998
599.997
599.997
599.996
599.996
599.995
599.995
599.997
600.002
600.007
600.001
600
600.001
600
600.001
600.002
600.001
599.991
600.002
600
599.999
599.998
599.996
599.995
599.996
599.998
600.001
600.002
600.001
600
599.999
599.999
599.998
599.998
599.997
599.997
599.997
599.999
600.003
600.005
600.001
600
600
600.001
600.001
600.001
600.001
599.993
600.001
600
600
599.999
599.997
599.995
599.996
599.998
600
600.001
600.002
600.001
600.001
600
600
599.999
599.999
599.999
600
600.001
600.004
600.003
600
600
600
600.001
600.001
600.001
600.001
599.999
600.001
600
600
600
599.999
599.997
599.996
599.997
599.999
600.001
600.002
600.002
600.002
600.002
600.001
600.001
600.001
600.001
600.002
600.004
600.004
600.002
600
600
600
600.001
600.001
600.001
600.001
599.994
600.001
600
600.001
600.001
600
599.999
599.997
599.997
599.999
600
600.002
600.003
600.003
600.003
600.003
600.003
600.003
600.003
600.005
600.006
600.004
600.001
599.999
600
600.001
600.001
600.001
600.001
600.001
599.978
600.001
600.001
600.001
600.001
600.001
600
599.999
599.998
599.999
600
600.001
600.003
600.003
600.003
600.003
600.003
600.004
600.004
600.005
600.005
600.003
600
599.999
600
600.001
600.001
600.002
600.002
600.003
600.001
600.003
600.003
600.002
600.002
600.002
600.002
600.001
600
600
600
600.001
600.002
600.003
600.003
600.003
600.003
600.004
600.004
600.005
600.004
600.002
600
599.999
600
600.001
600.001
600.001
599.998
599.983
600.007
600.006
600.005
600.004
600.003
600.003
600.003
600.003
600.003
600.002
600.001
600.001
600.002
600.002
600.003
600.003
600.003
600.003
600.004
600.003
600.002
600.001
600.001
600
600
600
600.001
600
599.991
599.989
600.014
600.01
600.007
600.005
600.005
600.004
600.004
600.004
600.004
600.003
600.002
600.001
600.001
600.002
600.002
600.002
600.002
600.003
600.003
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
599.993
599.986
599.995
600.016
600.013
600.01
600.008
600.007
600.008
600.007
600.006
600.005
600.004
600.002
600.001
600.001
600.001
600.002
600.002
600.002
600.002
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.002
599.999
599.991
599.999
600.005
600.015
600.016
600.014
600.012
600.012
600.012
600.012
600.008
600.005
600.003
600.002
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.001
600.002
600.002
600
599.996
600.005
600.021
600.01
600.013
600.017
600.016
600.016
600.014
600.011
600.007
600.004
600.003
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.001
600.001
600.001
599.999
599.999
600
600
599.999
600.003
600.016
600.015
600.016
600.004
600.006
600.014
600.014
600.013
600.01
600.005
600.002
600.002
600.001
600.002
600.002
600.002
600.002
600.002
600.002
600.002
600.001
600
599.998
599.995
599.991
599.993
599.997
600.004
600.011
600.047
600.064
600.044
600.037
600.005
600.004
600.005
600.007
600.006
600.004
600
599.997
599.995
599.994
599.994
599.996
599.998
599.999
600
600
599.999
599.997
599.996
599.994
599.999
600.021
600.049
600.071
600.09
600.105
600.126
600.13
600.104
600.077
600
599.994
599.996
599.999
599.994
599.986
599.975
599.965
599.96
599.959
599.964
599.972
599.98
599.986
599.991
599.992
599.992
599.999
600.021
600.059
600.099
600.134
600.165
600.189
600.206
600.216
600.22
600.21
600.181
600.141
599.942
599.928
599.949
599.955
599.945
599.928
599.919
599.928
599.948
599.967
599.983
599.992
599.998
600.004
600.015
600.036
600.07
600.114
600.159
600.203
600.242
600.274
600.301
600.32
600.332
600.336
600.33
600.309
600.271
600.212
599.776
599.83
599.865
599.892
599.913
599.941
599.982
600.021
600.06
600.094
600.12
600.138
600.151
600.164
600.182
600.211
600.247
600.288
600.328
600.365
600.397
600.422
600.442
600.456
600.462
600.46
600.449
600.425
600.384
600.318
599.863
599.92
599.954
599.986
600.025
600.069
600.12
600.172
600.221
600.261
600.292
600.316
600.336
600.355
600.376
600.402
600.433
600.467
600.499
600.527
600.552
600.571
600.585
600.594
600.596
600.59
600.576
600.551
600.512
600.447
600.033
600.092
600.125
600.159
600.202
600.25
600.299
600.348
600.393
600.433
600.466
600.494
600.517
600.539
600.561
600.585
600.611
600.638
600.663
600.685
600.703
600.718
600.727
600.732
600.731
600.724
600.709
600.686
600.651
600.598
600.285
600.313
600.337
600.364
600.398
600.438
600.48
600.523
600.564
600.602
600.634
600.663
600.688
600.711
600.732
600.755
600.777
600.798
600.818
600.836
600.85
600.86
600.867
600.869
600.866
600.859
600.845
600.825
600.799
600.762
600.511
600.523
600.539
600.561
600.589
600.621
600.657
600.694
600.73
600.764
600.795
600.823
600.847
600.869
600.89
600.91
600.93
600.948
600.964
600.978
600.99
600.998
601.002
601.003
601
600.993
600.981
600.967
600.949
600.93
600.715
600.719
600.73
600.747
600.769
600.796
600.826
600.857
600.889
600.919
600.947
600.972
600.995
601.016
601.036
601.054
601.071
601.087
601.101
601.113
601.122
601.128
601.132
601.132
601.129
601.123
601.115
601.106
601.097
601.094
600.901
600.9
600.907
600.92
600.938
600.96
600.985
601.011
601.038
601.064
601.089
601.112
601.133
601.152
601.17
601.187
601.202
601.216
601.228
601.238
601.246
601.252
601.255
601.255
601.253
601.249
601.244
601.239
601.237
601.246
601.071
601.067
601.071
601.081
601.095
601.112
601.133
601.155
601.177
601.2
601.221
601.241
601.26
601.277
601.294
601.309
601.323
601.335
601.346
601.355
601.363
601.368
601.371
601.372
601.371
601.369
601.367
601.365
601.368
601.384
601.226
601.218
601.22
601.227
601.238
601.252
601.269
601.287
601.306
601.324
601.343
601.36
601.377
601.392
601.407
601.421
601.433
601.445
601.455
601.464
601.471
601.476
601.48
601.481
601.482
601.481
601.481
601.482
601.488
601.506
601.363
601.355
601.355
601.36
601.368
601.379
601.393
601.407
601.423
601.438
601.454
601.469
601.483
601.497
601.511
601.523
601.535
601.546
601.556
601.564
601.571
601.577
601.581
601.583
601.585
601.586
601.587
601.59
601.597
601.615
601.486
601.477
601.476
601.479
601.485
601.494
601.504
601.516
601.528
601.541
601.555
601.568
601.581
601.593
601.605
601.617
601.628
601.638
601.648
601.656
601.664
601.67
601.675
601.678
601.681
601.683
601.686
601.689
601.696
601.711
601.593
601.586
601.584
601.585
601.59
601.596
601.604
601.613
601.624
601.635
601.646
601.657
601.669
601.68
601.691
601.702
601.713
601.723
601.733
601.741
601.749
601.756
601.761
601.766
601.77
601.773
601.776
601.78
601.786
601.798
601.694
601.683
601.68
601.68
601.682
601.687
601.693
601.7
601.709
601.718
601.728
601.738
601.748
601.759
601.769
601.78
601.79
601.8
601.81
601.819
601.828
601.835
601.842
601.847
601.852
601.857
601.861
601.865
601.871
601.88
601.783
601.771
601.765
601.763
601.764
601.767
601.772
601.777
601.784
601.792
601.801
601.81
601.819
601.829
601.84
601.85
601.86
601.871
601.881
601.89
601.899
601.908
601.915
601.922
601.928
601.934
601.939
601.945
601.951
601.961
601.873
601.851
601.842
601.838
601.837
601.838
601.841
601.846
601.851
601.858
601.866
601.874
601.883
601.892
601.902
601.913
601.923
601.934
601.944
601.954
601.964
601.973
601.982
601.991
601.998
602.006
602.013
602.021
602.03
602.044
601.945
601.922
601.909
601.903
601.901
601.9
601.902
601.905
601.91
601.916
601.923
601.93
601.939
601.948
601.958
601.968
601.978
601.989
602
602.011
602.022
602.032
602.043
602.053
602.062
602.072
602.082
602.092
602.106
602.126
602.026
601.987
601.97
601.961
601.956
601.955
601.955
601.957
601.96
601.965
601.971
601.978
601.986
601.995
602.004
602.014
602.025
602.036
602.048
602.06
602.071
602.083
602.095
602.107
602.119
602.132
602.145
602.161
602.181
602.22
602.073
602.039
602.022
602.011
602.004
602
601.998
601.998
602
602.004
602.009
602.015
602.022
602.031
602.04
602.05
602.061
602.073
602.085
602.097
602.11
602.123
602.137
602.152
602.167
602.183
602.202
602.223
602.248
602.284
602.149
602.098
602.068
602.05
602.038
602.031
602.026
602.025
602.025
602.028
602.032
602.037
602.044
602.052
602.061
602.071
602.082
602.094
602.106
602.119
602.133
602.148
602.163
602.179
602.198
602.218
602.243
602.275
602.321
602.399
)
;
boundaryField
{
inlet
{
type fixedValue;
value uniform 300;
}
outlet
{
type inletOutlet;
phi phi.air;
inletValue uniform 300;
value nonuniform List<scalar>
30
(
602.149
602.098
602.068
602.05
602.038
602.03
602.026
602.025
602.025
602.028
602.032
602.037
602.044
602.052
602.061
602.071
602.082
602.094
602.106
602.119
602.133
602.148
602.163
602.179
602.197
602.218
602.243
602.275
602.321
602.399
)
;
}
walls
{
type zeroGradient;
}
frontAndBackPlanes
{
type empty;
}
}
// ************************************************************************* //
| [
"peterbryz@yahoo.com"
] | peterbryz@yahoo.com |
8e95a81b347ac63898c3fdd4989e33c5f0882688 | 3cf9e141cc8fee9d490224741297d3eca3f5feff | /C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-19717.cpp | c7a176ce846b73412c44ce043c483ebe78d866a1 | [] | no_license | TeamVault/tauCFI | e0ac60b8106fc1bb9874adc515fc01672b775123 | e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10 | refs/heads/master | 2023-05-30T20:57:13.450360 | 2021-06-14T09:10:24 | 2021-06-14T09:10:24 | 154,563,655 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,579 | cpp | struct c0;
void __attribute__ ((noinline)) tester0(c0* p);
struct c0
{
bool active0;
c0() : active0(true) {}
virtual ~c0()
{
tester0(this);
active0 = false;
}
virtual void f0(){}
};
void __attribute__ ((noinline)) tester0(c0* p)
{
p->f0();
}
struct c1;
void __attribute__ ((noinline)) tester1(c1* p);
struct c1 : virtual c0
{
bool active1;
c1() : active1(true) {}
virtual ~c1()
{
tester1(this);
c0 *p0_0 = (c0*)(c1*)(this);
tester0(p0_0);
active1 = false;
}
virtual void f1(){}
};
void __attribute__ ((noinline)) tester1(c1* p)
{
p->f1();
if (p->active0)
p->f0();
}
struct c2;
void __attribute__ ((noinline)) tester2(c2* p);
struct c2 : virtual c1, virtual c0
{
bool active2;
c2() : active2(true) {}
virtual ~c2()
{
tester2(this);
c0 *p0_0 = (c0*)(c1*)(c2*)(this);
tester0(p0_0);
c0 *p0_1 = (c0*)(c2*)(this);
tester0(p0_1);
c1 *p1_0 = (c1*)(c2*)(this);
tester1(p1_0);
active2 = false;
}
virtual void f2(){}
};
void __attribute__ ((noinline)) tester2(c2* p)
{
p->f2();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
}
struct c3;
void __attribute__ ((noinline)) tester3(c3* p);
struct c3 : virtual c1, virtual c2
{
bool active3;
c3() : active3(true) {}
virtual ~c3()
{
tester3(this);
c0 *p0_0 = (c0*)(c1*)(c3*)(this);
tester0(p0_0);
c0 *p0_1 = (c0*)(c1*)(c2*)(c3*)(this);
tester0(p0_1);
c0 *p0_2 = (c0*)(c2*)(c3*)(this);
tester0(p0_2);
c1 *p1_0 = (c1*)(c3*)(this);
tester1(p1_0);
c1 *p1_1 = (c1*)(c2*)(c3*)(this);
tester1(p1_1);
c2 *p2_0 = (c2*)(c3*)(this);
tester2(p2_0);
active3 = false;
}
virtual void f3(){}
};
void __attribute__ ((noinline)) tester3(c3* p)
{
p->f3();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
if (p->active2)
p->f2();
}
struct c4;
void __attribute__ ((noinline)) tester4(c4* p);
struct c4 : virtual c1, virtual c0, c2
{
bool active4;
c4() : active4(true) {}
virtual ~c4()
{
tester4(this);
c0 *p0_0 = (c0*)(c1*)(c4*)(this);
tester0(p0_0);
c0 *p0_1 = (c0*)(c4*)(this);
tester0(p0_1);
c0 *p0_2 = (c0*)(c1*)(c2*)(c4*)(this);
tester0(p0_2);
c0 *p0_3 = (c0*)(c2*)(c4*)(this);
tester0(p0_3);
c1 *p1_0 = (c1*)(c4*)(this);
tester1(p1_0);
c1 *p1_1 = (c1*)(c2*)(c4*)(this);
tester1(p1_1);
c2 *p2_0 = (c2*)(c4*)(this);
tester2(p2_0);
active4 = false;
}
virtual void f4(){}
};
void __attribute__ ((noinline)) tester4(c4* p)
{
p->f4();
if (p->active2)
p->f2();
if (p->active0)
p->f0();
if (p->active1)
p->f1();
}
int __attribute__ ((noinline)) inc(int v) {return ++v;}
int main()
{
c0* ptrs0[25];
ptrs0[0] = (c0*)(new c0());
ptrs0[1] = (c0*)(c1*)(new c1());
ptrs0[2] = (c0*)(c1*)(c2*)(new c2());
ptrs0[3] = (c0*)(c2*)(new c2());
ptrs0[4] = (c0*)(c1*)(c3*)(new c3());
ptrs0[5] = (c0*)(c1*)(c2*)(c3*)(new c3());
ptrs0[6] = (c0*)(c2*)(c3*)(new c3());
ptrs0[7] = (c0*)(c1*)(c4*)(new c4());
ptrs0[8] = (c0*)(c4*)(new c4());
ptrs0[9] = (c0*)(c1*)(c2*)(c4*)(new c4());
ptrs0[10] = (c0*)(c2*)(c4*)(new c4());
for (int i=0;i<11;i=inc(i))
{
tester0(ptrs0[i]);
delete ptrs0[i];
}
c1* ptrs1[25];
ptrs1[0] = (c1*)(new c1());
ptrs1[1] = (c1*)(c2*)(new c2());
ptrs1[2] = (c1*)(c3*)(new c3());
ptrs1[3] = (c1*)(c2*)(c3*)(new c3());
ptrs1[4] = (c1*)(c4*)(new c4());
ptrs1[5] = (c1*)(c2*)(c4*)(new c4());
for (int i=0;i<6;i=inc(i))
{
tester1(ptrs1[i]);
delete ptrs1[i];
}
c2* ptrs2[25];
ptrs2[0] = (c2*)(new c2());
ptrs2[1] = (c2*)(c3*)(new c3());
ptrs2[2] = (c2*)(c4*)(new c4());
for (int i=0;i<3;i=inc(i))
{
tester2(ptrs2[i]);
delete ptrs2[i];
}
c3* ptrs3[25];
ptrs3[0] = (c3*)(new c3());
for (int i=0;i<1;i=inc(i))
{
tester3(ptrs3[i]);
delete ptrs3[i];
}
c4* ptrs4[25];
ptrs4[0] = (c4*)(new c4());
for (int i=0;i<1;i=inc(i))
{
tester4(ptrs4[i]);
delete ptrs4[i];
}
return 0;
}
| [
"ga72foq@mytum.de"
] | ga72foq@mytum.de |
71ad9f1943e91ed89166dbc1a069c8b2da9fc8d7 | dddea3e6b5cb6b7c71e4d8239b7bd8c97e182000 | /ClassHierarchy/ClassHierarchy.cpp | 1dbfa49147af5717b3c7c97c81677daf2070d047 | [] | no_license | shrilakshmidesai2000/C-C- | fab0f9acd27a7aed89a363a253b70bf246e27043 | c0bd7e81c2c50545d0c9d5818421fcfe2102458c | refs/heads/master | 2020-09-15T22:02:22.226180 | 2019-11-23T11:26:35 | 2019-11-23T11:26:35 | 223,566,039 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,443 | cpp | #include<iostream>
using namespace std;
class Manager{
protected :
string name;
string dept;
int empid;
int bonus;
public :
void getdata()
{
cout<<"Enter name : "<<endl;
cin>>name;
cout<<"Enter Department : "<<endl;
cin>>dept;
cout<<"Enter empid : "<<endl;
cin>>empid;
}
void setbonus(int b)
{
bonus=b;
cout<<"\nDepartment : "<<dept<<"\nBonus : "<<bonus<<endl;
}
void display(int n)
{
cout<<"\n Name : "<<name<<endl;
cout<<"\n Department : "<<dept<<endl;
cout<<"\n No. of employees : "<<n<<endl;
cout<<"\n Bonus : "<<bonus<<endl;
}
}; //class manager
class prodman : public Manager{
int noOfsup;
public :
void manageprod(int n)
{
noOfsup=n;
cout<<"\nNo. of supervisors : "<<noOfsup<<endl;
display(noOfsup);
}
}; // derived class prodman
class salesman : public Manager{
int noOfsalesmen;
public :
void managesales(int n)
{
noOfsalesmen=n;
cout<<"\nNo. of salesmen : "<<noOfsalesmen<<endl;
display(noOfsalesmen);
}
}; //derived class salesman
int main()
{
prodman p; //object of prodman
salesman s; //object of salesman
p.getdata();
s.getdata();
p.setbonus(5000);
s.setbonus(3000);
p.manageprod(100);
s.managesales(50);
}
| [
"noreply@github.com"
] | noreply@github.com |
0d6041d965d8c749d2cfd34d5cd0279ef0ec8233 | 4a2a0be6c0168f918726d77b22f33d9374ed1e0b | /C++/20191106/Point.cpp | 2c4cd3f2f13f73b369c619d5fc47f55c37d24a90 | [] | no_license | intfreedom/C | 677108ca6f471d614c7945d73a41d293283ac2b6 | 746406c426e1b716d31f48f839987257db708330 | refs/heads/master | 2022-04-09T06:17:48.753088 | 2020-03-05T07:09:20 | 2020-03-05T07:09:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 496 | cpp | #include <stdio.h>
class Point{
public:
int i;
void init(int x, int y);
void print() const;
Point();
void move(int dx, int dy);
void f();
private:
int x;
int y;
};
Point::Point()
{
i=0;
printf("Point::Point()--this=%p\n", this);
}
void Point::f()
{
this->i = 20;
printf("A::f()--&i=%p\n", &i);
printf("this=%p\n", this);
}
int main(){
Point a;
Point aa;
a.i=10;
printf("&a=%p\n", &a);
printf("&a.i=%p\n", &(a.i));
a.f();
printf("&aa=%p\n", &aa);
aa.f();
return 0;
}
| [
"liuwenjunxjtu@163.com"
] | liuwenjunxjtu@163.com |
890da7597553ec4d310bae5b195a893fd9fe32c0 | b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2 | /source/graphics/core/win32/opengl/vertexshaderopengl.h | 0c9a745ea5bc2e13423871be593790d7332c15f0 | [] | no_license | roxygen/maid2 | 230319e05d6d6e2f345eda4c4d9d430fae574422 | 455b6b57c4e08f3678948827d074385dbc6c3f58 | refs/heads/master | 2021-01-23T17:19:44.876818 | 2010-07-02T02:43:45 | 2010-07-02T02:43:45 | 38,671,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 660 | h | #ifndef maid2_graphics_core_win32_opengl_vertexshaderopengl_h
#define maid2_graphics_core_win32_opengl_vertexshaderopengl_h
#include"../../../../config/define.h"
#include"../../ivertexshader.h"
#include"common.h"
namespace Maid { namespace Graphics {
class VertexShaderOpenGL
: public IVertexShader
, public IOpenGLObject
{
public:
VertexShaderOpenGL();
~VertexShaderOpenGL();
void Initialize( const void* pData, size_t length );
void Finalize();
GLuint GetID() const;
private:
GLuint m_ID;
};
typedef boost::shared_ptr<VertexShaderOpenGL> SPVERTEXSHADEROPENGL;
}}
#endif | [
"renji2000@471aaf9e-aa7b-11dd-9b86-41075523de00"
] | renji2000@471aaf9e-aa7b-11dd-9b86-41075523de00 |
b6b83125f22f69f00e0ca57c1d9229fee88ab82a | 8e33c54fc9c09df9c59ed83bcbeadb72dc8914a7 | /src/cryptonote_core/cryptonote_basic.cpp | 65470749a76465c7073dfda9b462a61e4576e254 | [
"MIT"
] | permissive | Camellia73/cryonote | d718ef9f0acf800e609839503297e6184b1573b2 | f1cf0779507226ad8b411321e3e4d9f4122f1d61 | refs/heads/master | 2020-06-26T04:24:14.080120 | 2018-12-20T19:47:09 | 2018-12-20T19:47:09 | 160,942,686 | 0 | 0 | NOASSERTION | 2018-12-08T13:37:11 | 2018-12-08T13:37:11 | null | UTF-8 | C++ | false | false | 5,943 | cpp | // Copyright (c) 2014-2015 The Pebblecoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "common/stl-util.h"
#include "include_base_utils.h"
#include "cryptonote_basic.h"
#include "cryptonote_basic_impl.h"
#include "visitors.h"
using tools::const_get;
namespace cryptonote {
namespace {
struct input_type_version_visitor: tx_input_visitor_base_opt<size_t, 666>
{
using tx_input_visitor_base_opt<size_t, 666>::operator();
size_t operator()(const txin_gen& inp) const { return VANILLA_TRANSACTION_VERSION; }
size_t operator()(const txin_to_key& inp) const { return VANILLA_TRANSACTION_VERSION; }
size_t operator()(const txin_mint& inp) const { return CURRENCY_TRANSACTION_VERSION; }
size_t operator()(const txin_remint& inp) const { return CURRENCY_TRANSACTION_VERSION; }
size_t operator()(const txin_create_contract& inp) const { return CONTRACT_TRANSACTION_VERSION; }
size_t operator()(const txin_mint_contract& inp) const { return CONTRACT_TRANSACTION_VERSION; }
size_t operator()(const txin_grade_contract& inp) const { return CONTRACT_TRANSACTION_VERSION; }
size_t operator()(const txin_resolve_bc_coins& inp) const { return CONTRACT_TRANSACTION_VERSION; }
size_t operator()(const txin_fuse_bc_coins& inp) const { return CONTRACT_TRANSACTION_VERSION; }
size_t operator()(const txin_register_delegate& inp) const { return DPOS_TRANSACTION_VERSION; }
size_t operator()(const txin_vote& inp) const { return DPOS_TRANSACTION_VERSION; }
};
struct output_type_version_visitor: tx_output_visitor_base_opt<size_t, 666>
{
using tx_output_visitor_base_opt<size_t, 666>::operator();
size_t operator()(const txout_to_key& inp) const { return VANILLA_TRANSACTION_VERSION; }
};
}
size_t inp_minimum_tx_version(const txin_v& inp)
{
return boost::apply_visitor(input_type_version_visitor(), inp);
}
size_t outp_minimum_tx_version(const tx_out& outp)
{
return boost::apply_visitor(output_type_version_visitor(), outp.target);
}
bool transaction_prefix::has_valid_in_out_types() const
{
BOOST_FOREACH(const auto& inp, vin) {
if (inp_minimum_tx_version(inp) > version)
{
LOG_ERROR("Invalid tx version " << version << " for input " << inp.which()
<< " requires min version " << inp_minimum_tx_version(inp));
return false;
}
}
BOOST_FOREACH(const auto& outp, vout) {
if (outp_minimum_tx_version(outp) > version)
{
LOG_ERROR("Invalid tx version " << version << " for output " << outp.target.which()
<< " requires min version " << outp_minimum_tx_version(outp));
return false;
}
}
return true;
}
bool transaction_prefix::has_valid_coin_types() const
{
if (vin.size() != vin_coin_types.size() || vout.size() != vout_coin_types.size())
{
LOG_ERROR("vin.size()=" << vin.size() << ", vin_coin_types.size()=" << vin_coin_types.size() <<
", vout.size()=" << vout.size() << ", vout_coin_types.size()=" << vout_coin_types.size());
return false;
}
BOOST_FOREACH(const auto& ct, vin_coin_types)
{
if (!ct.is_valid_tx_version(version))
{
LOG_ERROR("invalid version " << version << " for coin type " << ct);
return false;
}
}
BOOST_FOREACH(const auto& ct, vout_coin_types)
{
if (!ct.is_valid_tx_version(version))
{
LOG_ERROR("invalid version " << version << " for coin type " << ct);
return false;
}
}
return true;
}
void transaction_prefix::clear_ins()
{
vin.clear();
vin_coin_types.clear();
}
void transaction_prefix::clear_outs()
{
vout.clear();
vout_coin_types.clear();
}
void transaction_prefix::replace_vote_seqs(const std::map<crypto::key_image, uint64_t> &key_image_seqs)
{
for (auto& inp : vin)
{
if (inp.type() == typeid(txin_vote))
{
auto& inv = boost::get<txin_vote>(inp);
uint64_t new_seq = const_get(key_image_seqs, inv.ink.k_image);
if (inv.seq != new_seq)
{
LOG_PRINT_YELLOW("WARNING: Wallet generated wrong vote sequence number", LOG_LEVEL_0);
}
inv.seq = new_seq;
}
}
}
transaction::transaction()
{
set_null();
}
transaction::~transaction()
{
//set_null();
}
void transaction::set_null()
{
version = 0;
unlock_time = 0;
clear_ins();
clear_outs();
extra.clear();
signatures.clear();
}
size_t transaction::get_signature_size(const txin_v& tx_in)
{
struct txin_signature_size_visitor : public boost::static_visitor<size_t>
{
size_t operator()(const txin_gen& txin) const{return 0;}
size_t operator()(const txin_to_script& txin) const{return 0;}
size_t operator()(const txin_to_scripthash& txin) const{return 0;}
size_t operator()(const txin_to_key& txin) const {return txin.key_offsets.size();}
size_t operator()(const txin_mint& txin) const{return 0;}
size_t operator()(const txin_remint& txin) const{return 0;}
size_t operator()(const txin_create_contract& txin) const{return 0;}
size_t operator()(const txin_mint_contract& txin) const{return 0;}
size_t operator()(const txin_grade_contract& txin) const{return 0;}
size_t operator()(const txin_resolve_bc_coins& txin) const{return 0;}
size_t operator()(const txin_fuse_bc_coins& txin) const{return 0;}
size_t operator()(const txin_register_delegate& txin) const{return 0;}
size_t operator()(const txin_vote& txin) const{return txin.ink.key_offsets.size();}
};
return boost::apply_visitor(txin_signature_size_visitor(), tx_in);
}
} // namespace cryptonote
| [
"anythingtechpro@gmail.com"
] | anythingtechpro@gmail.com |
ab2673fbc880d0070838906704fc209449f689c3 | c5b9f0fabffb6b2d13c6e350c8187a922709ac60 | /devel/.private/pal_detection_msgs/include/pal_detection_msgs/AddTexturedObjectResponse.h | cb710cfa49507979281dc8165b517fb331d4364a | [] | no_license | MohamedEhabHafez/Sorting_Aruco_Markers | cae079fdce4a14561f5e092051771d299b06e789 | 0f820921c9f42b39867565441ed6ea108663ef6c | refs/heads/master | 2020-12-09T02:43:00.731223 | 2020-01-15T17:31:29 | 2020-01-15T17:31:29 | 233,154,293 | 0 | 0 | null | 2020-10-13T18:46:44 | 2020-01-11T00:41:38 | Makefile | UTF-8 | C++ | false | false | 5,912 | h | // Generated by gencpp from file pal_detection_msgs/AddTexturedObjectResponse.msg
// DO NOT EDIT!
#ifndef PAL_DETECTION_MSGS_MESSAGE_ADDTEXTUREDOBJECTRESPONSE_H
#define PAL_DETECTION_MSGS_MESSAGE_ADDTEXTUREDOBJECTRESPONSE_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace pal_detection_msgs
{
template <class ContainerAllocator>
struct AddTexturedObjectResponse_
{
typedef AddTexturedObjectResponse_<ContainerAllocator> Type;
AddTexturedObjectResponse_()
: result(false) {
}
AddTexturedObjectResponse_(const ContainerAllocator& _alloc)
: result(false) {
(void)_alloc;
}
typedef uint8_t _result_type;
_result_type result;
typedef boost::shared_ptr< ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator> const> ConstPtr;
}; // struct AddTexturedObjectResponse_
typedef ::pal_detection_msgs::AddTexturedObjectResponse_<std::allocator<void> > AddTexturedObjectResponse;
typedef boost::shared_ptr< ::pal_detection_msgs::AddTexturedObjectResponse > AddTexturedObjectResponsePtr;
typedef boost::shared_ptr< ::pal_detection_msgs::AddTexturedObjectResponse const> AddTexturedObjectResponseConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace pal_detection_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg'], 'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'pal_detection_msgs': ['/home/mohamed/tiago_public_ws/src/pal_msgs/pal_detection_msgs/msg', '/home/mohamed/tiago_public_ws/devel/.private/pal_detection_msgs/share/pal_detection_msgs/msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator> >
{
static const char* value()
{
return "eb13ac1f1354ccecb7941ee8fa2192e8";
}
static const char* value(const ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xeb13ac1f1354ccecULL;
static const uint64_t static_value2 = 0xb7941ee8fa2192e8ULL;
};
template<class ContainerAllocator>
struct DataType< ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator> >
{
static const char* value()
{
return "pal_detection_msgs/AddTexturedObjectResponse";
}
static const char* value(const ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator> >
{
static const char* value()
{
return "bool result\n\
\n\
\n\
\n\
";
}
static const char* value(const ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.result);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct AddTexturedObjectResponse_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::pal_detection_msgs::AddTexturedObjectResponse_<ContainerAllocator>& v)
{
s << indent << "result: ";
Printer<uint8_t>::stream(s, indent + " ", v.result);
}
};
} // namespace message_operations
} // namespace ros
#endif // PAL_DETECTION_MSGS_MESSAGE_ADDTEXTUREDOBJECTRESPONSE_H
| [
"mohamed@radiirobotics.com"
] | mohamed@radiirobotics.com |
d00a5bf9256767e199fdc94f1429d2a2a1bde942 | 5bb8f335fd53f2ee2aabeaa52728d3b0ec9c4945 | /filewatcher.cpp | d94de65e367d531361c4a3955ce464e2a65efb97 | [] | no_license | th3architect/AutoGitUp | f6e30d133f8c0bda2368099cfde4f4a12104e561 | 01c09b284308a1a8107d0befbd7eb671f00a477e | refs/heads/master | 2020-12-14T18:42:51.660628 | 2012-06-11T09:42:49 | 2012-06-11T09:42:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 546 | cpp | #include "filewatcher.h"
FileWatcher::FileWatcher(QObject *parent) : QObject(parent) {
connect(watcher, SIGNAL(directoryChanged(const QString)), SLOT(dirChanged(const QString)));
connect(watcher, SIGNAL(fileChanged(const QString)), SLOT(fChanged(const QString)));
}
/** Slot which is executed when directory is changed
* @param path Path of modified directory
*/
void dirChanged(const QString path) {
}
/** Slot which is executed when directory is changed
* @param path Path of modified file
*/
void fChanged(const QString path) {
}
| [
"phanective@gmail.com"
] | phanective@gmail.com |
cc564e7897224f0df46ca39fa0853fd716676dbe | b0e233b9b173a866cf78f6e74a9b95c1e64eeb51 | /Code/Server/AutoLuaBind/cpp/LuaBind_GameLogic_EffectScript.cpp | 1208fdc15e097ea8383e058e53f5f001b9bda8a4 | [] | no_license | xiaol-luo/Utopia | 47a6e987ebd6aaebb7759b736a4590859a6c4eb3 | 798741067114467680c6bcf9d22301f12f127f02 | refs/heads/master | 2021-07-10T13:21:24.547069 | 2019-01-14T14:03:31 | 2019-01-14T14:03:31 | 100,261,666 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,847 | cpp | #include "SolLuaBindUtils.h"
#include <sol.hpp>
#include "Logic/LogicModules/GameLogic/Scene/Effects/EffectBase.h"
#include "Logic/LogicModules/GameLogic/Scene/SceneModule/SceneEffects/SceneEffects.h"
#include "Logic/LogicModules/GameLogic/Scene/Effects/EffectScript/EffectScript.h"
#include "Logic/LogicModules/GameLogic/Scene/Effects/EffectScript/EffectScriptConfig.h"
#include "Logic/LogicModules/GameLogic/Scene/SceneUnit/SceneUnit.h"
#include "Logic/LogicModules/GameLogic/Scene/Effects/EffectConfigBase.h"
#include "Logic/LogicModules/GameLogic/Scene/Effects/EffectScript/LuaSubscribeEventDetail.h"
namespace SolLuaBind
{
void LuaBind_GameLogic_EffectScript(lua_State *L)
{
struct LuaBindImpl
{
struct ForOverloadFns
{
};
struct ForPropertyField
{
};
static void DoLuaBind(lua_State *L)
{
std::string name = "EffectScript";
std::string name_space = "GameLogic";
{
sol::usertype<GameLogic::EffectScript> meta_table(
sol::constructors<
GameLogic::EffectScript(const GameLogic::EffectConfigBase *, GameLogic::SceneEffects *, uint64_t)
>(),
"__StructName__", sol::property([]() {return "EffectScript"; })
,"SubscribeSuEvent", &GameLogic::EffectScript::SubscribeSuEvent
,"RemoveSuEvent", &GameLogic::EffectScript::RemoveSuEvent
,"CancelAllSuEvent", &GameLogic::EffectScript::CancelAllSuEvent
,"GetSu", &GameLogic::EffectScript::GetSu
, sol::base_classes, sol::bases<
GameLogic::EffectBase
>()
);
SolLuaBindUtils::BindLuaUserType(sol::state_view(L), meta_table, name, name_space);
}
{
sol::table ns_table = SolLuaBindUtils::GetOrNewLuaNameSpaceTable(sol::state_view(L), name_space)[name];
}
}
};
LuaBindImpl::DoLuaBind(L);
}
} | [
"xiaol.luo@163.com"
] | xiaol.luo@163.com |
0cd79b7524a8757e609dddde9f562fda6f755e5f | 539dfcd8d797d4fce2ec269feb6f0c728403efe3 | /src/E6DetectorConstruction.cpp | 50b0aa42711aa571beaefd8c3579712352b34abd | [] | no_license | aogaki/E6Window | cfd55f277cb2ed2852a59fc021c789c2b3603842 | be845902031c182c10dddcf97a0973fe15a2c5e3 | refs/heads/master | 2020-04-21T00:33:03.043523 | 2019-02-12T07:12:37 | 2019-02-12T07:12:37 | 169,199,908 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,334 | cpp | #include <G4Box.hh>
#include <G4LogicalVolume.hh>
#include <G4LogicalVolumeStore.hh>
#include <G4NistManager.hh>
#include <G4PVPlacement.hh>
#include <G4PVReplica.hh>
#include <G4RunManager.hh>
#include <G4SDManager.hh>
#include <G4SystemOfUnits.hh>
#include <G4Tubs.hh>
#include "E6DetectorConstruction.hpp"
#include "E6SD.hpp"
E6DetectorConstruction::E6DetectorConstruction()
: fVacuumMat(nullptr),
fWindowMat(nullptr),
fAirMat(nullptr),
fWindowPV(nullptr),
fMessenger(nullptr)
{
fCheckOverlap = true;
fWindowT = 3. * mm;
DefineMaterials();
DefineCommands();
}
E6DetectorConstruction::~E6DetectorConstruction() {}
void E6DetectorConstruction::DefineMaterials()
{
G4NistManager *manager = G4NistManager::Instance();
// NIST database materials
fVacuumMat = manager->FindOrBuildMaterial("G4_Galactic");
fWindowMat = manager->FindOrBuildMaterial("G4_POLYCARBONATE");
fAirMat = manager->FindOrBuildMaterial("G4_AIR");
}
G4VPhysicalVolume *E6DetectorConstruction::Construct()
{
// world volume
G4double worldX = 0.1 * m;
G4double worldY = 0.1 * m;
G4double worldZ = 3. * m;
G4Box *worldS = new G4Box("World", worldX / 2., worldY / 2., worldZ / 2.);
G4LogicalVolume *worldLV = new G4LogicalVolume(worldS, fVacuumMat, "World");
G4VisAttributes *visAttributes = new G4VisAttributes(G4Colour::White());
visAttributes->SetVisibility(false);
worldLV->SetVisAttributes(visAttributes);
fVisAttributes.push_back(visAttributes);
// Air layer
G4double airW = worldX;
G4double airH = worldY;
G4double airT = 1. * m;
G4Box *airS = new G4Box("Air", airW / 2., airH / 2., airT / 2.);
G4LogicalVolume *airLV = new G4LogicalVolume(airS, fAirMat, "Air");
visAttributes = new G4VisAttributes(G4Colour::Magenta());
airLV->SetVisAttributes(visAttributes);
fVisAttributes.push_back(visAttributes);
G4double airZPos = airT / 2.;
G4ThreeVector airPos = G4ThreeVector(0., 0., airZPos);
new G4PVPlacement(nullptr, airPos, airLV, "Air", worldLV, false, 0,
fCheckOverlap);
// Window
G4double windowW = airW;
G4double windowH = airH;
G4Box *windowS =
new G4Box("Window", windowW / 2., windowH / 2., fWindowT / 2.);
G4LogicalVolume *windowLV =
new G4LogicalVolume(windowS, fWindowMat, "Window");
visAttributes = new G4VisAttributes(G4Colour::Green());
windowLV->SetVisAttributes(visAttributes);
fVisAttributes.push_back(visAttributes);
G4double windowZPos = -fWindowT / 2.;
G4ThreeVector windowPos = G4ThreeVector(0., 0., windowZPos);
fWindowPV = new G4PVPlacement(nullptr, windowPos, windowLV, "Window", worldLV,
false, 0, fCheckOverlap);
G4VPhysicalVolume *worldPV = new G4PVPlacement(
nullptr, G4ThreeVector(), worldLV, "World", 0, false, 0, fCheckOverlap);
return worldPV;
}
void E6DetectorConstruction::ConstructSDandField()
{
// Sensitive Detectors
G4VSensitiveDetector *SD = new E6SD("SD", "HC");
G4SDManager::GetSDMpointer()->AddNewDetector(SD);
G4LogicalVolumeStore *lvStore = G4LogicalVolumeStore::GetInstance();
for (auto &&lv : *lvStore) {
if (lv->GetName().contains("Air")) SetSensitiveDetector(lv->GetName(), SD);
}
}
void E6DetectorConstruction::DefineCommands()
{
fMessenger = new G4GenericMessenger(this, "/E6/Geometry/", "For geometries");
G4GenericMessenger::Command &windowTCmd = fMessenger->DeclareMethodWithUnit(
"WindowThickness", "mm", &E6DetectorConstruction::SetWindowT,
"Set the thickness of the window.");
windowTCmd.SetParameterName("thickness", true);
windowTCmd.SetRange("thickness>=0. && thickness<=2000.");
windowTCmd.SetDefaultValue("3.0");
}
void E6DetectorConstruction::SetWindowT(G4double t)
{
fWindowT = t;
if (t > 0.) {
G4Box *window = (G4Box *)(fWindowPV->GetLogicalVolume()->GetSolid());
window->SetZHalfLength(fWindowT / 2.);
// change position
G4ThreeVector windowPos = G4ThreeVector(0., 0., -fWindowT / 2.);
fWindowPV->SetTranslation(windowPos);
} else { // temporary. exit is better?
G4cout << "No thickness? OK, material of window is changed to vacuum."
<< G4endl;
G4LogicalVolume *windowLV = fWindowPV->GetLogicalVolume();
windowLV->SetMaterial(fVacuumMat);
}
G4RunManager::GetRunManager()->GeometryHasBeenModified();
}
| [
"sohichiroh.aogaki@eli-np.ro"
] | sohichiroh.aogaki@eli-np.ro |
98f76877eac3a0a7ba7d43ee655c8dd9791695ca | 9324cb559c509753d3a2f6467ccb6616de58af05 | /fboss/agent/hw/sai/api/LoggingUtil.h | 57d199ad793238ab020f0883ec41840b21932aea | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | rsunkad/fboss | 4b39eefa3851bd9e415403d28a28290838dea22f | 760255f88fdaeb7f12d092a41362acf1e9a45bbb | refs/heads/main | 2023-07-24T10:39:48.865411 | 2021-09-08T18:58:30 | 2021-09-08T18:59:40 | 404,465,680 | 0 | 0 | NOASSERTION | 2021-09-08T19:09:20 | 2021-09-08T19:09:19 | null | UTF-8 | C++ | false | false | 8,211 | h | /*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
* * This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#pragma once
#include "fboss/agent/hw/sai/api/SaiAttribute.h"
#include "fboss/lib/TupleUtils.h"
#include <fmt/format.h>
extern "C" {
#include <sai.h>
}
namespace facebook::fboss {
folly::StringPiece saiApiTypeToString(sai_api_t apiType);
folly::StringPiece saiObjectTypeToString(sai_object_type_t objectType);
folly::StringPiece saiStatusToString(sai_status_t status);
sai_log_level_t saiLogLevelFromString(const std::string& logLevel);
} // namespace facebook::fboss
/*
* fmt specializations for the types that we use in SaiApi
* specifically:
* any c++ value types used in attributes without one (e.g., folly::MacAddress)
* sai attribute id enums
* SaiAttribute itself
* std::tuple (of attributes, ostensibly)
*/
namespace fmt {
// Formatting for folly::MacAddress
template <>
struct formatter<folly::MacAddress> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const folly::MacAddress& mac, FormatContext& ctx) {
return format_to(ctx.out(), "{}", mac.toString());
}
};
// Formatting for folly::IpAddress
template <>
struct formatter<folly::IPAddress> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const folly::IPAddress& ip, FormatContext& ctx) {
return format_to(ctx.out(), "{}", ip.str());
}
};
// Formatting for AdapterKeys which are SAI entry structs
template <typename AdapterKeyType>
struct formatter<
AdapterKeyType,
char,
typename std::enable_if_t<
facebook::fboss::IsSaiEntryStruct<AdapterKeyType>::value>> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const AdapterKeyType& key, FormatContext& ctx) {
return format_to(ctx.out(), "{}", key.toString());
}
};
// Formatting for std::variant
template <typename... Ts>
struct formatter<std::variant<Ts...>> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const std::variant<Ts...>& var, FormatContext& ctx) {
auto formatVariant = [&ctx](auto&& val) {
return format_to(ctx.out(), "{}", val);
};
return std::visit(formatVariant, var);
}
};
// Formatting for SaiAttributes
template <
typename AttrEnumT,
AttrEnumT AttrEnum,
typename DataT,
typename DefaultGetterT>
struct formatter<
facebook::fboss::
SaiAttribute<AttrEnumT, AttrEnum, DataT, DefaultGetterT, void>> {
using AttrT = facebook::fboss::
SaiAttribute<AttrEnumT, AttrEnum, DataT, DefaultGetterT, void>;
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const AttrT& attr, FormatContext& ctx) {
return format_to(
ctx.out(),
"{}: {}",
facebook::fboss::AttributeName<AttrT>::value,
attr.value());
}
};
// Formatting for std::monostate
template <>
struct formatter<std::monostate> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const std::monostate& unit, FormatContext& ctx) {
return format_to(ctx.out(), "(monostate)");
}
};
// Formatting for empty std::tuple
template <>
struct formatter<std::tuple<>> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const std::tuple<>& tup, FormatContext& ctx) {
return format_to(ctx.out(), "()");
}
};
// Formatting for std::optional<SaiAttribute>
template <typename T>
struct formatter<std::optional<T>> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const std::optional<T>& opt, FormatContext& ctx) {
static_assert(
facebook::fboss::IsSaiAttribute<T>::value,
"format(std::optional) only valid for SaiAttributes");
if (opt) {
return format_to(ctx.out(), "{}", opt.value());
} else {
return format_to(ctx.out(), "nullopt");
}
}
};
// Formatting for sai_qos_map_t
template <>
struct formatter<sai_qos_map_t> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const sai_qos_map_t& qosMap, FormatContext& ctx) {
return format_to(
ctx.out(),
"(qos_mapping: key.dscp: {}, key.tc: {}, "
"value.tc: {}, value.queue_index: {})",
qosMap.key.dscp,
qosMap.key.tc,
qosMap.value.tc,
qosMap.value.queue_index);
}
};
// Formatting for AclEntryField<T>
template <typename T>
struct formatter<facebook::fboss::AclEntryField<T>> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(
const facebook::fboss::AclEntryField<T>& aclEntryField,
FormatContext& ctx) {
return format_to(ctx.out(), "{}", aclEntryField.str());
}
};
// Formatting for AclEntryAction<T>
template <typename T>
struct formatter<facebook::fboss::AclEntryAction<T>> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(
const facebook::fboss::AclEntryAction<T>& aclEntryAction,
FormatContext& ctx) {
return format_to(ctx.out(), "{}", aclEntryAction.str());
}
};
// Formatting for sai_u32_range_t
template <>
struct formatter<sai_u32_range_t> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const sai_u32_range_t& u32Range, FormatContext& ctx) {
return format_to(
ctx.out(), "u32 range: min: {}, max: {}", u32Range.min, u32Range.max);
}
};
// Formatting for sai_s32_range_t
template <>
struct formatter<sai_s32_range_t> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const sai_s32_range_t& s32Range, FormatContext& ctx) {
return format_to(
ctx.out(), "s32 range: min: {}, max: {}", s32Range.min, s32Range.max);
}
};
// formatter for extension attributes
template <typename T>
struct formatter<
T,
char,
std::enable_if_t<facebook::fboss::IsSaiExtensionAttribute<T>::value>> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const T& attr, FormatContext& ctx) {
// TODO: implement this
return format_to(
ctx.out(),
"{}: {}",
facebook::fboss::AttributeName<T>::value,
attr.value());
}
};
// Formatting for char[32]
template <>
struct formatter<SaiCharArray32> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const SaiCharArray32& data, FormatContext& ctx) {
return format_to(ctx.out(), "{}", std::string(data.begin(), data.end()));
}
};
template <>
struct formatter<facebook::fboss::SaiPortDescriptor> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(
const facebook::fboss::SaiPortDescriptor& port,
FormatContext& ctx) {
return format_to(ctx.out(), "{}", port.str());
}
};
} // namespace fmt
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
31b3070a5577ceed53d932dd7c670d25404007ce | 111c3ebecfa9eac954bde34b38450b0519c45b86 | /SDK_Perso/include/inter/Include/edModel/inl/IGraphModel.inl | 797957c78076d41adba107266d44ffdfae905b5d | [] | no_license | 1059444127/NH90 | 25db189bb4f3b7129a3c6d97acb415265339dab7 | a97da9d49b4d520ad169845603fd47c5ed870797 | refs/heads/master | 2021-05-29T14:14:33.309737 | 2015-10-05T17:06:10 | 2015-10-05T17:06:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,835 | inl | #include "edModel/IGraphModel.h"
#ifndef EDGE
#include "Modeler/ModelParamsImpl.h"
#else
#include "Graphics/ModelParamsImpl.h"
#endif
inline model::InstanceParams* model::IGraphModel::createInstanceParams(const IModelParams *params)const
{
InstanceParams *ip = nullptr;
if(params == nullptr){
static const ModelParamsImpl mpi;
ip = new(frame_heap) InstanceParams(mpi);
}else{
ip = new(frame_heap) InstanceParams(*params);
}
unsigned int nMatrices = base()->getNumTransformNodes();
ip->transformMatrices = new(frame_heap) osg::Matrixd[nMatrices];
ip->nMatrices = nMatrices;
return ip;
}
inline model::InstanceParams* model::IGraphModel::cloneInstanceParams(const InstanceParams &ip)const
{
InstanceParams *p = new(frame_heap) InstanceParams(ip);
return p;
}
inline model::FlatShadowInfo* model::IGraphModel::createFlatShadowInfo(const osg::Vec3d& p, const osg::Vec3f& n, float shadowStrength)
{
FlatShadowInfo* fsi = new(frame_heap) FlatShadowInfo(p, n, shadowStrength);
return fsi;
}
inline bool model::IGraphModel::dropFlatShadow(const edge::Context& ctx)const
{
return (ctx.getPass()->getType() == edge::Pass::LOCKON || ctx.getPass()->getType() == edge::Pass::DEFERRED);
}
inline void model::IGraphModel::render(const osg::Matrixd& modelPos,edge::Context& context,edge::IQueue& opaque,edge::IQueue& transparent, const IModelParams *params)
{
InstanceParams *ip = createInstanceParams(params);
render(modelPos, context, opaque, transparent, ip);
}
inline void model::IGraphModel::render(const osg::Matrixd& modelPos,edge::Context& context,edge::IQueue& opaque,edge::IQueue& transparent)
{
InstanceParams *ip = createInstanceParams(nullptr);
render(modelPos, context, opaque, transparent, ip);
}
inline void model::IGraphModel::cullAndRender(const osg::Matrixd& modelPos, edge::Context& ctx, const IModelParams *params)
{
const edge::Camera &cam = *ctx.getCamera();
const osg::BoundingBoxf& box = base()->getBoundingBox();
InstanceParams *ip = NULL;
osg::Polytope pt;
#ifdef EDGE_SPLIT_CAMERA
const osg::Polytope& v1=cam.getFrustum(edge::CAMERA_FAR);
pt.setAndTransformProvidingInverse(v1,modelPos);
if(pt.contains(box))
{
ip = createInstanceParams(params);
render(modelPos, ctx, *ctx.getPipeline()->far_opaque, *ctx.getPipeline()->far_transparent, ip);
}
const osg::Polytope& v2=cam.getFrustum(edge::CAMERA_NEAR);
pt.setAndTransformProvidingInverse(v2,modelPos);
if(pt.contains(box))
{
if(ip == NULL){
ip = createInstanceParams(params);
}
render(modelPos, ctx, *ctx.getPipeline()->near_opaque, *ctx.getPipeline()->near_transparent, ip);
}
#else
const osg::Polytope& v1=cam.getFrustum();
pt.setAndTransformProvidingInverse(v1,modelPos);
if(pt.contains(box))
{
ip = createInstanceParams(params);
edge::IQueue* opaque = ctx.getPipeline()->getQueue(edge::Q_OPAQUE);
edge::IQueue* transparent = ctx.getPipeline()->getQueue(edge::Q_TRANSPARENT);
if(opaque && transparent)
render(modelPos, ctx, *opaque, *transparent, ip);
}
#endif
}
/// Cut model by frustum and render flat shadows only
inline void model::IGraphModel::cullAndRenderFlatShadowOnly(const osg::Matrixd& modelPos, edge::Context& ctx, const osg::Vec3d& shadowPos, const osg::Vec3f& shadowNormal, const IModelParams *params)
{
// flat shadow
if(!dropFlatShadow(ctx)) return;
const osg::BoundingBoxf& box = base()->getBoundingBox();
// get sun dir
edge::lightarray_const_ref_t ld = edge::ILightVisitor::instance()->getDirLights();
if(ld.empty()) return;
const osg::Vec3d &sunDir = ld[0].dir;
// box
osg::BoundingBox bb(ed::transformBbox(box, modelPos));
// camera
const osg::Vec3d mPos((bb._min.x() + bb._max.x()) * 0.5, (bb._min.y() + bb._max.y()) * 0.5, (bb._min.z() + bb._max.z()) * 0.5);
osg::Vec3d c(shadowPos);
const osg::Vec3f &n(shadowNormal);
if(std::abs(n.y()) < FLAT_SHADOW_NORMAL_MAX_VERT_BIAS) return;
double cosSunDir = sunDir * n;
if(cosSunDir < MIN_FLAT_SHADOW_ANGLE) return;
// calc density
double dist = ed::distance(mPos, c);
if(dist > FLAT_SHADOW_VISIBILITY_DIST) return;
float blend = calcFlatShadowAttenuation(cosSunDir, ctx.isOvercast());
// rotate|scale
ed::rotateBbox(box, bb, modelPos);
// expand box by sun
bb._min /= cosSunDir;
bb._max /= cosSunDir;
// move to shadow position
ed::moveBboxTo(bb, c);
drawFlatShadow(modelPos, bb, c, n, blend, ctx, params);
}
inline void model::IGraphModel::drawFlatShadow(const osg::Matrixd& modelPos, const osg::BoundingBox &bb, const osg::Vec3d& c, const osg::Vec3f& n, float blend, edge::Context& ctx, const IModelParams *params)
{
const edge::Camera &cam = *ctx.getCamera();
InstanceParams *ip = NULL;
#ifdef EDGE_SPLIT_CAMERA
const osg::Polytope& v1=cam.getFrustum(edge::CAMERA_FAR);
if(v1.contains(bb))
{
ip = createInstanceParams(params);
ip->flatShadowInfo = createFlatShadowInfo(c, n, blend);
render(modelPos, ctx, *ctx.getPipeline()->far_flat_shadows_opaque, *ctx.getPipeline()->far_flat_shadows_transparent, ip);
}
const osg::Polytope& v2=cam.getFrustum(edge::CAMERA_NEAR);
if(v2.contains(bb))
{
if(ip == NULL){
ip = createInstanceParams(params);
ip->flatShadowInfo = createFlatShadowInfo(c, n, blend);
}else{
ip = cloneInstanceParams(*ip);
ip->flatShadowInfo = createFlatShadowInfo(c, n, blend);
}
render(modelPos, ctx, *ctx.getPipeline()->near_flat_shadows_opaque, *ctx.getPipeline()->near_flat_shadows_transparent, ip);
}
#else
const osg::Polytope& v1=cam.getFrustum();
if(v1.contains(bb))
{
ip = createInstanceParams(params);
ip->flatShadowInfo = createFlatShadowInfo(c, n, blend);
edge::IQueue* flat_shadows_opaque = ctx.getPipeline()->getQueue(edge::Q_FLAT_SHADOWS_OPAQUE);
edge::IQueue* flat_shadows_transparent = ctx.getPipeline()->getQueue(edge::Q_FLAT_SHADOWS_TRANSPARENT);
render(modelPos, ctx, *flat_shadows_opaque, *flat_shadows_transparent, ip);
}
#endif
}
inline void model::IGraphModel::cullAndRenderWithFlatShadow(const osg::Matrixd& modelPos, edge::Context& ctx,const IModelParams *params, bool drapOnWater)
{
cullAndRender(modelPos, ctx, params);
// flat shadow
if(!dropFlatShadow(ctx)) return;
const osg::BoundingBoxf& box = base()->getBoundingBox();
// get sun dir
edge::lightarray_const_ref_t ld = edge::ILightVisitor::instance()->getDirLights();
if(ld.empty()) return;
const osg::Vec3d &sunDir = ld[0].dir;
// box
osg::BoundingBox bb(ed::transformBbox(box, modelPos));
// camera
const osg::Vec3d mPos((bb._min.x() + bb._max.x()) * 0.5, (bb._min.y() + bb._max.y()) * 0.5, (bb._min.z() + bb._max.z()) * 0.5);
landscape::lPointOnSurface lpos;
osg::Vec3d c;
// we need use center of bounding box due to trees. As their positions may be in common triangles point.
osg::Vec3d a(mPos), b(a);
a -= sunDir * ed::distance(box._min, box._max) * (-0.5);
b += sunDir * (-FLAT_SHADOW_VISIBILITY_DIST);
if(!lpos.intersection(a, b, &c)){
return;
}
if(!drapOnWater){
if((lpos.getType() & (smaSea | smaLake | smaRiver)) != 0){
return;
}
}
osg::Vec3f n = lpos.getNormal();
if(std::abs(n.y()) < FLAT_SHADOW_NORMAL_MAX_VERT_BIAS) return;
double cosSunDir = sunDir * n;
if(cosSunDir < MIN_FLAT_SHADOW_ANGLE) return;
// calc density
float blend = calcFlatShadowAttenuation(cosSunDir, ctx.isOvercast());
// rotate|scale
ed::rotateBbox(box, bb, modelPos);
// expand box by sun
bb._min /= cosSunDir;
bb._max /= cosSunDir;
// move to shadow position
ed::moveBboxTo(bb, c);
drawFlatShadow(modelPos, bb, c, n, blend, ctx, params);
}
inline void model::IGraphModel::cullAndRenderWithFlatShadow(const osg::Matrixd& modelPos, edge::Context& ctx, const osg::Vec3d& shadowPos, const osg::Vec3f& shadowNormal, const IModelParams *params)
{
cullAndRender(modelPos, ctx, params);
// flat shadow
if(!dropFlatShadow(ctx)) return;
const osg::BoundingBoxf& box = base()->getBoundingBox();
// get sun dir
edge::lightarray_const_ref_t ld = edge::ILightVisitor::instance()->getDirLights();
if(ld.empty()) return;
const osg::Vec3d &sunDir = ld[0].dir;
// box
osg::BoundingBox bb(ed::transformBbox(box, modelPos));
// camera
const osg::Vec3d mPos((bb._min.x() + bb._max.x()) * 0.5, (bb._min.y() + bb._max.y()) * 0.5, (bb._min.z() + bb._max.z()) * 0.5);
osg::Vec3d c(shadowPos);
const osg::Vec3f &n(shadowNormal);
if(std::abs(n.y()) < FLAT_SHADOW_NORMAL_MAX_VERT_BIAS) return;
double cosSunDir = sunDir * n;
if(cosSunDir < MIN_FLAT_SHADOW_ANGLE) return;
// calc density
double dist = ed::distance(mPos, c);
if(dist > FLAT_SHADOW_VISIBILITY_DIST) return;
float blend = calcFlatShadowAttenuation(cosSunDir, ctx.isOvercast());
// rotate|scale
ed::rotateBbox(box, bb, modelPos);
// expand box by sun
bb._min /= cosSunDir;
bb._max /= cosSunDir;
// move to shadow position
ed::moveBboxTo(bb, c);
drawFlatShadow(modelPos, bb, c, n, blend, ctx, params);
}
| [
"hashmaaal@gmail.com"
] | hashmaaal@gmail.com |
3d9e62ab6b3c1bf18122a6d8ed58881f89dbe07c | 1736f4a1717e6bff983afe91f96d8ee3fd332a0f | /uri/1002.cpp | 5263aaeb5a28c2070581d0ea623e6d70d4352636 | [
"MIT"
] | permissive | heittpr/lalp | 867c59e7c9f615564fcffa29c963d200f0920f60 | fd8a427dbfef8aaf1d595de5ff958dd00cd767da | refs/heads/master | 2023-01-10T00:08:37.735468 | 2020-11-12T01:51:40 | 2020-11-12T01:51:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 177 | cpp | // Área do Círculo
#include <iostream>
using namespace std;
int main() {
double r;
cin >> r;
cout.precision(4);
cout << fixed << "A=" << 3.14159 * r * r << endl;
}
| [
"heitorleite.dev@gmail.com"
] | heitorleite.dev@gmail.com |
cede5b207b92ed44f9282684a631444fe96c3ae8 | d6eee67fc9fb0db48e8f240f72a72a58e7544dcd | /code/lib/jomjol_flowcontroll/ClassFlowAnalog.h | ce41f17fb545c557b16622c6aef3aecd6659959c | [
"MIT"
] | permissive | remspoor/AI-on-the-edge-device | 806641da766ab8f843c660b5f47fde2e3d8b1a4d | 8f518954aabcaef97b54e81a1b45bdd2bd4b8294 | refs/heads/master | 2023-01-07T15:38:33.109909 | 2020-10-14T16:46:46 | 2020-10-14T16:46:46 | 300,066,618 | 0 | 0 | MIT | 2020-09-30T21:24:04 | 2020-09-30T21:24:03 | null | UTF-8 | C++ | false | false | 876 | h | #pragma once
#include "ClassFlow.h"
// #include "CTfLiteClass.h"
struct roianalog {
int posx, posy, deltax, deltay;
float result;
string name;
};
class ClassFlowAnalog :
public ClassFlow
{
protected:
string LogImageLocation;
bool isLogImage;
std::vector<roianalog*> ROI;
string cnnmodelfile;
int modelxsize, modelysize;
int ZeigerEval(float zahl, int ziffer_vorgaenger);
public:
ClassFlowAnalog();
ClassFlowAnalog(std::vector<ClassFlow*>* lfc);
bool ReadParameter(FILE* pfile, string& aktparamgraph);
bool doFlow(string time);
string getHTMLSingleStep(string host);
string getReadout();
bool doNeuralNetwork(string time);
bool doAlignAndCut(string time);
std::vector<HTMLInfo*> GetHTMLInfo();
int AnzahlROIs(){return ROI.size();};
string name(){return "ClassFlowAnalog";};
};
| [
"30766535+jomjol@users.noreply.github.com"
] | 30766535+jomjol@users.noreply.github.com |
d25c309ff8e59e230860b15422a468d9438c94cb | 9f3641aa21f10f79512a0ce0d6c3e884a522490e | /Basic_Algorithms/Strings/UkkonenSuffixTree.cpp | 42f8914a2807059dbaee8f13853d8d6baa2eb7a4 | [] | no_license | eashandash/Basic_algorithms | 02e880be7c778085e73ca398434b911970fab179 | 77abb506646388c98fbfbb0c973e72e295411ea7 | refs/heads/master | 2020-04-09T19:08:28.121940 | 2018-12-05T14:59:24 | 2018-12-05T14:59:24 | 160,534,599 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,401 | cpp | /************************************************************************
Suffix Tree. Ukkonen's algorithm using sibling lists — O(N).
This code counts number of different substrings in the string.
Based on problem I from here: http://codeforces.ru/gym/100133
************************************************************************/
#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <cstring>
#include <cassert>
#include <utility>
#include <iomanip>
using namespace std;
#define root 1
const int MAXN = 105000;
const int inf = 1000 * 1000 * 1000;
struct node {
int from, to, link;
int child, bro;
};
int n, len, nk, pos;
string s;
vector <node> tree;
int active_e, active_node, active_len, needSL, rem;
int add_node(int from, int to) {
nk++;
node temp;
temp.from = from; temp.to = to; temp.link = 0;
temp.child = 0; temp.bro = 0;
tree.push_back(temp);
return nk;
}
void st_init() {
nk = -1;
pos = -1;
rem = active_e = active_len = needSL = 0;
active_node = root;
add_node(-1, -1);
add_node(-1, -1);
}
void addSL(int v) {
if (needSL) tree[needSL].link = v;
needSL = v;
}
int find_edge(int v, int c) {
v = tree[v].child;
while (v) {
if (s[tree[v].from] == c)
return v;
v = tree[v].bro;
}
return 0;
}
void insert_edge(int v, int to) {
int temp = tree[v].child;
tree[v].child = to;
tree[to].bro = temp;
}
void change_edge(int v, int c, int to) {
int next = tree[v].child;
if (s[tree[next].from] == c) {
tree[v].child = to;
tree[to].bro = tree[next].bro;
return;
}
v = next;
while (v) {
next = tree[v].bro;
if (s[tree[next].from] == c) {
tree[v].bro = to;
tree[to].bro = tree[next].bro;
return;
}
v = next;
}
}
bool walk_down(int v) {
int elen = tree[v].to - tree[v].from;
if (tree[v].from + active_len >= tree[v].to) {
active_node = v;
active_len -= elen;
active_e += elen;
return true;
}
return false;
}
int active_edge() {
return s[active_e];
}
void st_insert(int c) {
pos++;
needSL = 0; rem++;
while (rem) {
if (active_len == 0) active_e = pos;
int go = find_edge(active_node, active_edge());
if (go == 0) {
int leaf = add_node(pos, inf);
insert_edge(active_node, leaf);
addSL(active_node);
}
else {
if (walk_down(go))
continue;
if (s[tree[go].from + active_len] == c) {
active_len++;
addSL(active_node);
break;
}
int split = add_node(tree[go].from, tree[go].from + active_len);
int leaf = add_node(pos, inf);
change_edge(active_node, active_edge(), split);
insert_edge(split, go);
insert_edge(split, leaf);
tree[go].from = tree[go].from + active_len;
addSL(split);
}
rem--;
if (active_node == root && active_len) {
active_len--;
active_e = pos - rem + 1;
}
else {
if (tree[active_node].link)
active_node = tree[active_node].link;
else
active_node = root;
}
}
}
int count_diff() {
int result = 0;
for (int i = 2; i <= nk; i++)
result += min(tree[i].to, n) - tree[i].from;
return result;
}
int main() {
freopen("substr.in","r",stdin);
freopen("substr.out","w",stdout);
getline(cin, s);
n = (int) s.length();
st_init();
for (int i = 0; i < n; i++)
st_insert(s[i]);
printf("%d", count_diff());
return 0;
} | [
"dash.eashan@gmail.com"
] | dash.eashan@gmail.com |
6271786d0c81890aee3e37a18d23dd9ebb43a393 | 3ef56b1144e1086009877e18ca602fa8bc1c5b33 | /srchybrid/DirectDownloadDlg.cpp | 1e20b9d37502110b23c6931b34a4cd870c41a3a8 | [] | no_license | rusingineer/StulleMule | 54569fc5c1d829afd755c24aa8dc248f6413f252 | a8444d55d87834e0a2ef7918a0fe428e3003c136 | refs/heads/master | 2020-04-02T05:17:54.831491 | 2010-12-25T18:43:36 | 2010-12-25T18:43:36 | 61,437,191 | 0 | 0 | null | null | null | null | ISO-8859-10 | C++ | false | false | 7,493 | cpp | //this file is part of eMule
//Copyright (C)2002-2008 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net )
//
//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., 675 Mass Ave, Cambridge, MA 02139, USA.
#include "stdafx.h"
#include "emule.h"
#include "DirectDownloadDlg.h"
#include "OtherFunctions.h"
#include "emuleDlg.h"
#include "DownloadQueue.h"
#include "ED2KLink.h"
#include "Preferences.h"
// emulEspaņa: Added by Announ [MoNKi: -Check already downloaded files-]
#include "KnownFileList.h"
// End emulEspaņa
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define PREF_INI_SECTION _T("DirectDownloadDlg")
IMPLEMENT_DYNAMIC(CDirectDownloadDlg, CDialog)
BEGIN_MESSAGE_MAP(CDirectDownloadDlg, CResizableDialog)
ON_EN_KILLFOCUS(IDC_ELINK, OnEnKillfocusElink)
ON_EN_UPDATE(IDC_ELINK, OnEnUpdateElink)
ON_NOTIFY(NM_CLICK, IDC_CATS, OnNMClickCats) //MORPH - Added by SiRoB, Selection category support
END_MESSAGE_MAP()
CDirectDownloadDlg::CDirectDownloadDlg(CWnd* pParent /*=NULL*/)
: CResizableDialog(CDirectDownloadDlg::IDD, pParent)
{
m_icnWnd = NULL;
}
CDirectDownloadDlg::~CDirectDownloadDlg()
{
if (m_icnWnd)
VERIFY( DestroyIcon(m_icnWnd) );
}
void CDirectDownloadDlg::DoDataExchange(CDataExchange* pDX)
{
CResizableDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_DDOWN_FRM, m_ctrlDirectDlFrm);
DDX_Control(pDX, IDC_CATS, m_cattabs);
}
void CDirectDownloadDlg::UpdateControls()
{
GetDlgItem(IDOK)->EnableWindow(GetDlgItem(IDC_ELINK)->GetWindowTextLength() > 0);
}
void CDirectDownloadDlg::OnEnUpdateElink()
{
UpdateControls();
}
void CDirectDownloadDlg::OnEnKillfocusElink()
{
CString strLinks;
GetDlgItem(IDC_ELINK)->GetWindowText(strLinks);
if (strLinks.IsEmpty() || strLinks.Find(_T('\n')) == -1)
return;
strLinks.Replace(_T("\n"), _T("\r\n"));
strLinks.Replace(_T("\r\r"), _T("\r"));
GetDlgItem(IDC_ELINK)->SetWindowText(strLinks);
}
void CDirectDownloadDlg::OnOK()
{
CString strLinks;
GetDlgItem(IDC_ELINK)->GetWindowText(strLinks);
int curPos = 0;
CString strTok = strLinks.Tokenize(_T(" \t\r\n"), curPos); // tokenize by whitespaces
while (!strTok.IsEmpty())
{
if (strTok.Right(1) != _T("/"))
strTok += _T("/");
try
{
CED2KLink* pLink = CED2KLink::CreateLinkFromUrl(strTok.Trim());// Morph trim
if (pLink)
{
if (pLink->GetKind() == CED2KLink::kFile)
{
//MORPH START - Changed by SiRoB, Selection category support khaos::categorymod+
/*
theApp.downloadqueue->AddFileLinkToDownload(pLink->GetFileLink(), (thePrefs.GetCatCount() == 0) ? 0 : m_cattabs.GetCurSel());
*/
CED2KFileLink* pFileLink = (CED2KFileLink*)CED2KLink::CreateLinkFromUrl(strTok.Trim());
//EastShare START - Modified by Pretender, [MoNKi: -Check already downloaded files-]
if(theApp.knownfiles->CheckAlreadyDownloadedFileQuestion(pLink->GetFileLink()->GetHashKey(),pLink->GetFileLink()->GetName()))
//EastShare END
//khaos::categorymod+
/*
theApp.downloadqueue->AddFileLinkToDownload(pFileLink, (thePrefs.GetCatCount()==0)?-1 : m_cattabs.GetCurSel(), true);
*/
theApp.downloadqueue->AddFileLinkToDownload(pFileLink, (thePrefs.GetCatCount()==1)?-1 : m_cattabs.GetCurSel(), true);
//khaos::categorymod-
//MORPH END - Changed by SiRoB, Selection category support khaos::categorymod-
}
else
{
delete pLink;
throw CString(_T("bad link"));
}
delete pLink;
}
}
catch(CString error)
{
TCHAR szBuffer[200];
_sntprintf(szBuffer, _countof(szBuffer), GetResString(IDS_ERR_INVALIDLINK), error);
szBuffer[_countof(szBuffer) - 1] = _T('\0');
CString strError;
strError.Format(GetResString(IDS_ERR_LINKERROR), szBuffer);
AfxMessageBox(strError);
return;
}
strTok = strLinks.Tokenize(_T(" \t\r\n"), curPos); // tokenize by whitespaces
}
CResizableDialog::OnOK();
}
BOOL CDirectDownloadDlg::OnInitDialog()
{
CResizableDialog::OnInitDialog();
InitWindowStyles(this);
SetIcon(m_icnWnd = theApp.LoadIcon(_T("PasteLink")), FALSE);
if (theApp.IsVistaThemeActive())
m_cattabs.ModifyStyle(0, TCS_HOTTRACK);
AddAnchor(IDC_DDOWN_FRM, TOP_LEFT, BOTTOM_RIGHT);
AddAnchor(IDC_ELINK, TOP_LEFT, BOTTOM_RIGHT);
AddAnchor(IDCANCEL, BOTTOM_RIGHT);
AddAnchor(IDOK, BOTTOM_RIGHT);
AddAnchor(IDC_CATLABEL, BOTTOM_LEFT);
AddAnchor(IDC_CATS, BOTTOM_LEFT,BOTTOM_RIGHT);
EnableSaveRestore(PREF_INI_SECTION);
SetWindowText(GetResString(IDS_SW_DIRECTDOWNLOAD));
m_ctrlDirectDlFrm.SetIcon(_T("Download"));
m_ctrlDirectDlFrm.SetWindowText(GetResString(IDS_SW_DIRECTDOWNLOAD));
GetDlgItem(IDOK)->SetWindowText(GetResString(IDS_DOWNLOAD));
GetDlgItem(IDC_FSTATIC2)->SetWindowText(GetResString(IDS_SW_LINK));
GetDlgItem(IDC_CATLABEL)->SetWindowText(GetResString(IDS_CAT)+_T(":"));
GetDlgItem(IDOK)->SetWindowText(GetResString(IDS_DOWNLOAD));
GetDlgItem(IDCANCEL)->SetWindowText(GetResString(IDS_CANCEL));
//khaos::categorymod+
/*
if (thePrefs.GetCatCount()==0) {
*/
if (thePrefs.GetCatCount()==1) {
//khaos::categorymod-
GetDlgItem(IDC_CATLABEL)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_CATS)->ShowWindow(SW_HIDE);
}
else {
UpdateCatTabs();
if (theApp.m_fontSymbol.m_hObject){
GetDlgItem(IDC_CATLABEL)->SetFont(&theApp.m_fontSymbol);
GetDlgItem(IDC_CATLABEL)->SetWindowText(GetExStyle() & WS_EX_LAYOUTRTL ? _T("3") : _T("4")); // show a right-arrow
}
}
UpdateControls();
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CDirectDownloadDlg::UpdateCatTabs() {
int oldsel=m_cattabs.GetCurSel();
m_cattabs.DeleteAllItems();
for (int ix=0;ix<thePrefs.GetCatCount();ix++) {
//MORPH START - Changed by SiRoB, Selection category support
/*
CString label=(ix==0)?GetResString(IDS_ALL):thePrefs.GetCategory(ix)->strTitle;
label.Replace(_T("&"),_T("&&"));
m_cattabs.InsertItem(ix,label);
}
if (oldsel>=m_cattabs.GetItemCount() || oldsel==-1)
oldsel=0;
*/
CString label=thePrefs.GetCategory(ix)->strTitle;
label.Replace(_T("&"),_T("&&"));
m_cattabs.InsertItem(ix,label);
}
if (oldsel>=m_cattabs.GetItemCount())
oldsel=-1;
//MORPH END - Changed by SiRoB, Selection category support
m_cattabs.SetCurSel(oldsel);
}
//MORPH START - Added by SiRoB, Selection category support
void CDirectDownloadDlg::OnNMClickCats(NMHDR* /*pNMHDR*/, LRESULT *pResult)
{
POINT point;
::GetCursorPos(&point);
CPoint pt(point);
TCHITTESTINFO hitinfo;
CRect rect;
m_cattabs.GetWindowRect(&rect);
pt.Offset(0-rect.left,0-rect.top);
hitinfo.pt = pt;
// Find the destination tab...
int nTab = m_cattabs.HitTest( &hitinfo );
if( hitinfo.flags != TCHT_NOWHERE )
if(nTab==m_cattabs.GetCurSel())
{
m_cattabs.DeselectAll(false);
}
*pResult = 0;
}
//MORPH END - Added by SiRoB, Selection category support | [
"stulleamgym@gmx.net"
] | stulleamgym@gmx.net |
042f4ffa867c06438bb0bcfc69390719f9ca5202 | 9240ceb15f7b5abb1e4e4644f59d209b83d70066 | /sp/src/game/client/replay/vgui/replayperformanceeditor.cpp | 071d1320b8e9d5c5f30f7331c8ebf63d031cdfec | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Margen67/blamod | 13e5cd9f7f94d1612eb3f44a2803bf2f02a3dcbe | d59b5f968264121d013a81ae1ba1f51432030170 | refs/heads/master | 2023-04-16T12:05:12.130933 | 2019-02-20T10:23:04 | 2019-02-20T10:23:04 | 264,556,156 | 2 | 0 | NOASSERTION | 2020-05-17T00:47:56 | 2020-05-17T00:47:55 | null | UTF-8 | C++ | false | false | 78,143 | cpp | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#if defined( REPLAY_ENABLED )
#include "replayperformanceeditor.h"
#include "replay/replay.h"
#include "replay/ireplayperformanceeditor.h"
#include "replay/ireplayperformancecontroller.h"
#include "replay/performance.h"
#include "ienginevgui.h"
#include "iclientmode.h"
#include "vgui_controls/ImagePanel.h"
#include "vgui_controls/TextImage.h"
#include "vgui_controls/Slider.h"
#include "vgui_controls/Menu.h"
#include "vgui/ILocalize.h"
#include "vgui/IImage.h"
#include "c_team.h"
#include "vgui_avatarimage.h"
#include "vgui/ISurface.h"
#include "vgui/IInput.h"
#include "replay/replaycamera.h"
#include "replay/ireplaymanager.h"
#include "replay/iclientreplaycontext.h"
#include "confirm_dialog.h"
#include "replayperformancesavedlg.h"
#include "replay/irecordingsessionmanager.h"
#include "achievementmgr.h"
#include "c_playerresource.h"
#include "replay/gamedefs.h"
// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>
extern CAchievementMgr g_AchievementMgrTF;
//-----------------------------------------------------------------------------
using namespace vgui;
//-----------------------------------------------------------------------------
extern IReplayPerformanceController *g_pReplayPerformanceController;
//-----------------------------------------------------------------------------
// Hack-y global bool to communicate when we are rewinding for map load screens.
// Order of operations issues preclude the use of engine->IsPlayingDemo().
bool g_bIsReplayRewinding = false;
//-----------------------------------------------------------------------------
// TODO: Make these archive? Right now, the tips are reset every time the game starts
ConVar replay_perftip_count_enter( "replay_perftip_count_enter", "0", FCVAR_CLIENTDLL | FCVAR_DONTRECORD | FCVAR_HIDDEN, "", true, 0, false, 0 );
ConVar replay_perftip_count_exit( "replay_perftip_count_exit", "0", FCVAR_CLIENTDLL | FCVAR_DONTRECORD | FCVAR_HIDDEN, "", true, 0, false, 0 );
ConVar replay_perftip_count_freecam_enter( "replay_perftip_count_freecam_enter", "0", FCVAR_CLIENTDLL | FCVAR_DONTRECORD | FCVAR_HIDDEN, "", true, 0, false, 0 );
ConVar replay_perftip_count_freecam_exit( "replay_perftip_count_freecam_exit", "0", FCVAR_CLIENTDLL | FCVAR_DONTRECORD | FCVAR_HIDDEN, "", true, 0, false, 0 );
ConVar replay_perftip_count_freecam_exit2( "replay_perftip_count_freecam_exit2", "0", FCVAR_CLIENTDLL | FCVAR_DONTRECORD | FCVAR_HIDDEN, "", true, 0, false, 0 );
ConVar replay_editor_fov_mousewheel_multiplier( "replay_editor_fov_mousewheel_multiplier", "5", FCVAR_ARCHIVE | FCVAR_CLIENTDLL | FCVAR_DONTRECORD, "The multiplier on mousewheel input for adjusting camera FOV in the replay editor." );
ConVar replay_editor_fov_mousewheel_invert( "replay_editor_fov_mousewheel_invert", "0", FCVAR_ARCHIVE | FCVAR_CLIENTDLL | FCVAR_DONTRECORD, "Invert FOV zoom/unzoom on mousewheel in the replay editor." );
ConVar replay_replayeditor_rewindmsgcounter( "replay_replayeditor_rewindmsgcounter", "0", FCVAR_ARCHIVE | FCVAR_CLIENTDLL | FCVAR_DONTRECORD | FCVAR_HIDDEN, "" );
//-----------------------------------------------------------------------------
#define MAX_TIP_DISPLAYS 1
//-----------------------------------------------------------------------------
#define TIMESCALE_MIN 0.01f
#define TIMESCALE_MAX 3.0f
//-----------------------------------------------------------------------------
#define SLIDER_RANGE_MAX 10000.0f
//-----------------------------------------------------------------------------
#define REPLAY_SOUND_DIALOG_POPUP "replay\\replaydialog_warn.wav"
//-----------------------------------------------------------------------------
static const char *gs_pCamNames[ NCAMS ] =
{
"free",
"third",
"first",
"timescale",
};
static const char *gs_pBaseComponentNames[ NCAMS ] =
{
"replay/replay_camera_%s%s",
"replay/replay_camera_%s%s",
"replay/replay_camera_%s%s",
"replay/replay_%s%s",
};
//-----------------------------------------------------------------------------
void PlayDemo()
{
engine->ClientCmd_Unrestricted( "demo_resume" );
}
void PauseDemo()
{
engine->ClientCmd_Unrestricted( "demo_pause" );
}
//-----------------------------------------------------------------------------
inline float SCurve( float t )
{
t = clamp( t, 0.0f, 1.0f );
return t * t * (3 - 2*t);
}
inline float CubicEaseIn( float t )
{
t = clamp( t, 0.0f, 1.0f );
return t * t * t;
}
inline float LerpScale( float flIn, float flInMin, float flInMax, float flOutMin, float flOutMax )
{
float flDenom = flInMax - flInMin;
if ( flDenom == 0.0f )
return 0.0f;
float t = clamp( ( flIn - flInMin ) / flDenom, 0.0f, 1.0f );
return Lerp( t, flOutMin, flOutMax );
}
//-----------------------------------------------------------------------------
void HighlightTipWords( Label *pLabel )
{
// Setup coloring - get # of words that should be highlighted
wchar_t *pwNumWords = g_pVGuiLocalize->Find( "#Replay_PerfTip_Highlight_NumWords" );
if ( !pwNumWords )
return;
// Get the current label text
wchar_t wszLabelText[512];
pLabel->GetText( wszLabelText, sizeof( wszLabelText ) );
pLabel->GetTextImage()->ClearColorChangeStream();
pLabel->GetTextImage()->AddColorChange( pLabel->GetFgColor(), 0 );
int nNumWords = _wtoi( pwNumWords );
for ( int i = 0; i < nNumWords; ++i )
{
char szWordFindStr[64];
V_snprintf( szWordFindStr, sizeof( szWordFindStr ), "#Replay_PerfTip_Highlight_Word%i", i );
wchar_t *pwWord = g_pVGuiLocalize->Find( szWordFindStr );
if ( !pwWord )
continue;
const int nWordLen = wcslen( pwWord );
// Find any instance of the word in the label text and highlight it in red
const wchar_t *p = wszLabelText;
do
{
const wchar_t *pInst = wcsstr( p, pwWord );
if ( !pInst )
break;
// Highlight the text
int nStartPos = pInst - wszLabelText;
int nEndPos = nStartPos + nWordLen;
// If start pos is non-zero, clear color changes
bool bChangeColor = true;
if ( nStartPos == 0 )
{
pLabel->GetTextImage()->ClearColorChangeStream();
}
else if ( iswalpha( wszLabelText[ nStartPos - 1 ] ) )
{
// If this is not the beginning of the string, check the previous character. If it's
// not whitespace, etc, we found an instance of a keyword within another word. Skip.
bChangeColor = false;
}
if ( bChangeColor )
{
pLabel->GetTextImage()->AddColorChange( Color(200,80,60,255), nStartPos );
pLabel->GetTextImage()->AddColorChange( pLabel->GetFgColor(), nEndPos );
}
p = pInst + nWordLen;
} while ( 1 );
}
}
//-----------------------------------------------------------------------------
class CSavingDialog : public CGenericWaitingDialog
{
DECLARE_CLASS_SIMPLE( CSavingDialog, CGenericWaitingDialog );
public:
CSavingDialog( CReplayPerformanceEditorPanel *pEditorPanel )
: CGenericWaitingDialog( pEditorPanel )
{
m_pEditorPanel = pEditorPanel;
}
virtual void OnTick()
{
BaseClass::OnTick();
if ( !g_pReplayPerformanceController )
return;
// Update async save
if ( g_pReplayPerformanceController->IsSaving() )
{
g_pReplayPerformanceController->SaveThink();
}
else
{
if ( m_pEditorPanel.Get() )
{
m_pEditorPanel->OnSaveComplete();
}
Close();
}
}
private:
CConfirmDialog *m_pLoginDialog;
vgui::DHANDLE< CReplayPerformanceEditorPanel > m_pEditorPanel;
};
//-----------------------------------------------------------------------------
class CReplayTipLabel : public Label
{
DECLARE_CLASS_SIMPLE( CReplayTipLabel, Label );
public:
CReplayTipLabel( Panel *pParent, const char *pName, const char *pText )
: BaseClass( pParent, pName, pText )
{
}
virtual void ApplySchemeSettings( IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
HighlightTipWords( this );
}
};
DECLARE_BUILD_FACTORY_DEFAULT_TEXT( CReplayTipLabel, Label );
//-----------------------------------------------------------------------------
class CPerformanceTip : public EditablePanel
{
DECLARE_CLASS_SIMPLE( CPerformanceTip, EditablePanel );
public:
static DHANDLE< CPerformanceTip > s_pTip;
static CPerformanceTip *CreateInstance( const char *pText )
{
if ( s_pTip )
{
s_pTip->SetVisible( false );
s_pTip->MarkForDeletion();
s_pTip = NULL;
}
s_pTip = SETUP_PANEL( new CPerformanceTip( pText ) );
return s_pTip;
}
CPerformanceTip( const char *pText )
: BaseClass( g_pClientMode->GetViewport(), "Tip" ),
m_flBornTime( gpGlobals->realtime ),
m_flAge( 0.0f ),
m_flShowDuration( 15.0f )
{
m_pTextLabel = new CReplayTipLabel( this, "TextLabel", pText );
}
virtual void OnThink()
{
// Delete the panel if life exceeded
const float flEndTime = m_flBornTime + m_flShowDuration;
if ( gpGlobals->realtime >= flEndTime )
{
SetVisible( false );
MarkForDeletion();
s_pTip = NULL;
return;
}
SetVisible( true );
const float flFadeDuration = .4f;
float flAlpha;
// Fade out?
if ( gpGlobals->realtime >= flEndTime - flFadeDuration )
{
flAlpha = LerpScale( gpGlobals->realtime, flEndTime - flFadeDuration, flEndTime, 1.0f, 0.0f );
}
// Fade in?
else if ( gpGlobals->realtime <= m_flBornTime + flFadeDuration )
{
flAlpha = LerpScale( gpGlobals->realtime, m_flBornTime, m_flBornTime + flFadeDuration, 0.0f, 1.0f );
}
// Otherwise, we must be in between fade in/fade out
else
{
flAlpha = 1.0f;
}
SetAlpha( 255 * SCurve( flAlpha ) );
}
virtual void ApplySchemeSettings( IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
LoadControlSettings( "resource/ui/replayperformanceeditor/tip.res", "GAME" );
// Center relative to parent
const int nScreenW = ScreenWidth();
const int nScreenH = ScreenHeight();
int aContentSize[2];
m_pTextLabel->GetContentSize( aContentSize[0], aContentSize[1] );
const int nLabelHeight = aContentSize[1];
SetBounds(
0,
3 * nScreenH / 4 - nLabelHeight / 2,
nScreenW,
nLabelHeight + 2 * m_nTopBottomMargin
);
m_pTextLabel->SetBounds(
m_nLeftRightMarginWidth,
m_nTopBottomMargin,
nScreenW - 2 * m_nLeftRightMarginWidth,
nLabelHeight
);
}
static void Cleanup()
{
if ( s_pTip )
{
s_pTip->MarkForDeletion();
s_pTip = NULL;
}
}
CPanelAnimationVarAliasType( int, m_nLeftRightMarginWidth, "left_right_margin", "0", "proportional_xpos" );
CPanelAnimationVarAliasType( int, m_nTopBottomMargin , "top_bottom_margin", "0", "proportional_ypos" );
CReplayTipLabel *m_pTextLabel;
float m_flBornTime;
float m_flAge;
float m_flShowDuration;
};
DHANDLE< CPerformanceTip > CPerformanceTip::s_pTip;
// Display the performance tip if we haven't already displayed it nMaxTimesToDisplay times or more
inline void DisplayPerformanceTip( const char *pText, ConVar* pCountCv = NULL, int nMaxTimesToDisplay = -1 )
{
// Already displayed too many times? Get out.
if ( pCountCv && nMaxTimesToDisplay >= 0 )
{
int nCount = pCountCv->GetInt();
if ( nCount >= nMaxTimesToDisplay )
return;
// Incremement count cvar
pCountCv->SetValue( nCount + 1 );
}
// Display the tip
CPerformanceTip::CreateInstance( pText );
}
//-----------------------------------------------------------------------------
inline float GetPlaybackTime()
{
CReplay *pPlayingReplay = g_pReplayManager->GetPlayingReplay();
return gpGlobals->curtime - TICKS_TO_TIME( pPlayingReplay->m_nSpawnTick );
}
//-----------------------------------------------------------------------------
class CPlayerCell : public CExImageButton
{
DECLARE_CLASS_SIMPLE( CPlayerCell, CExImageButton );
public:
CPlayerCell( Panel *pParent, const char *pName, int *pCurTargetPlayerIndex )
: CExImageButton( pParent, pName, "" ),
m_iPlayerIndex( -1 ),
m_pCurTargetPlayerIndex( pCurTargetPlayerIndex )
{
}
virtual void ApplySchemeSettings( IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
GetImage()->SetImage( "" );
SetFont( pScheme->GetFont( "ReplaySmall" ) );
SetContentAlignment( Label::a_center );
}
MESSAGE_FUNC( DoClick, "PressButton" )
{
ReplayCamera()->SetPrimaryTarget( m_iPlayerIndex );
*m_pCurTargetPlayerIndex = m_iPlayerIndex;
float flCurTime = GetPlaybackTime();
extern IReplayPerformanceController *g_pReplayPerformanceController;
g_pReplayPerformanceController->AddEvent_Camera_ChangePlayer( flCurTime, m_iPlayerIndex );
}
int m_iPlayerIndex;
int *m_pCurTargetPlayerIndex; // Allow the button to write current target in outer class when pressed
};
//-----------------------------------------------------------------------------
/*
class CReplayEditorSlider : public Slider
{
DECLARE_CLASS_SIMPLE( CReplayEditorSlider, Slider );
public:
CReplayEditorSlider( Panel *pParent, const char *pName )
: Slider( pParent, pName )
{
}
virtual void SetDefault( float flDefault ) { m_flDefault = flDefault; }
ON_MESSAGE( Reset, OnReset )
{
SetValue(
}
private:
float m_flDefault;
};
*/
//-----------------------------------------------------------------------------
class CCameraOptionsPanel : public EditablePanel
{
DECLARE_CLASS_SIMPLE( CCameraOptionsPanel, EditablePanel );
public:
CCameraOptionsPanel( Panel *pParent, const char *pName, const char *pTitle )
: EditablePanel( pParent, pName ),
m_bControlsAdded( false )
{
m_pTitleLabel = new CExLabel( this, "TitleLabel", pTitle );
AddControlToLayout( m_pTitleLabel );
}
~CCameraOptionsPanel()
{
m_lstSliderInfos.PurgeAndDeleteElements();
}
void AddControlToLayout( Panel *pControl )
{
if ( pControl )
{
m_lstControls.AddToTail( pControl );
pControl->SetMouseInputEnabled( true );
}
}
// NOTE: Default value is assumed to be stored in flOut
void AddSliderToLayout( int nId, Slider *pSlider, const char *pLabelText,
float flMinValue, float flMaxValue, float &flOut )
{
SliderInfo_t *pNewSliderInfo = new SliderInfo_t;
pNewSliderInfo->m_nId = nId;
pNewSliderInfo->m_pSlider = pSlider;
pNewSliderInfo->m_flRange[ 0 ] = flMinValue;
pNewSliderInfo->m_flRange[ 1 ] = flMaxValue;
pNewSliderInfo->m_flDefault = flOut;
pNewSliderInfo->m_pValueOut = &flOut;
m_lstSliderInfos.AddToTail( pNewSliderInfo );
AddControlToLayout( new EditablePanel( this, "Buffer" ) );
AddControlToLayout( NewLabel( pLabelText ) );
AddControlToLayout( NewSetDefaultButton( nId ) );
AddControlToLayout( pSlider );
pSlider->AddActionSignalTarget( this );
}
void ResetSlider( int nId )
{
const SliderInfo_t *pSliderInfo = FindSliderInfoFromId( nId );
if ( !pSliderInfo )
return;
SetValue( pSliderInfo, pSliderInfo->m_flDefault );
}
void SetValue( int nId, float flValue )
{
const SliderInfo_t *pSliderInfo = FindSliderInfoFromId( nId );
if ( !pSliderInfo )
return;
SetValue( pSliderInfo, flValue );
}
virtual void ApplySchemeSettings( IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
// Setup border
SetBorder( pScheme->GetBorder( "ButtonBorder" ) );
HFont hFont = pScheme->GetFont( "ReplayBrowserSmallest", true );
m_pTitleLabel->SetFont( hFont );
m_pTitleLabel->SizeToContents();
m_pTitleLabel->SetTall( YRES( 20 ) );
m_pTitleLabel->SetColorStr( "235 235 235 255" );
if ( !m_bControlsAdded )
{
const char *pResFile = GetResFile();
if ( pResFile )
{
LoadControlSettings( pResFile, "GAME" );
}
AddControls();
m_bControlsAdded = true;
}
FOR_EACH_LL( m_lstSliderInfos, it )
{
SliderInfo_t *pInfo = m_lstSliderInfos[ it ];
Slider *pSlider = pInfo->m_pSlider;
pSlider->SetRange( 0, SLIDER_RANGE_MAX );
pSlider->SetNumTicks( 10 );
float flDenom = fabs( pInfo->m_flRange[1] - pInfo->m_flRange[0] );
pSlider->SetValue( SLIDER_RANGE_MAX * fabs( pInfo->m_flDefault - pInfo->m_flRange[0] ) / flDenom );
}
}
virtual void PerformLayout()
{
BaseClass::PerformLayout();
int nWidth = XRES( 140 );
int nMargins[2] = { XRES( 5 ), YRES( 5 ) };
int nVBuf = YRES( 0 );
int nLastY = -1;
int nY = nMargins[1];
Panel *pPrevPanel = NULL;
int nLastCtrlHeight = 0;
FOR_EACH_LL( m_lstControls, i )
{
Panel *pPanel = m_lstControls[ i ];
if ( !pPanel->IsVisible() )
continue;
int aPos[2];
pPanel->GetPos( aPos[0], aPos[1] );
if ( pPrevPanel && aPos[1] >= 0 )
{
nY += pPrevPanel->GetTall() + nVBuf;
}
// Gross hack to see if the control is a default button
if ( dynamic_cast< CExButton * >( pPanel ) )
{
pPanel->SetWide( XRES( 36 ) );
pPanel->SetPos( pPrevPanel ? ( GetWide() - nMargins[0] - pPanel->GetWide() ) : 0, nLastY );
}
else
{
pPanel->SetWide( nWidth - 2 * nMargins[0] );
pPanel->SetPos( nMargins[0], nY );
}
nLastY = nY;
pPrevPanel = pPanel;
nLastCtrlHeight = MAX( nLastCtrlHeight, pPanel->GetTall() );
}
SetSize( nWidth, nY + nLastCtrlHeight + 2 * YRES( 3 ) );
}
virtual void OnCommand( const char *pCommand )
{
if ( !V_strnicmp( pCommand, "reset_", 6 ) )
{
const int nSliderInfoId = atoi( pCommand + 6 );
ResetSlider( nSliderInfoId );
}
else
{
BaseClass::OnCommand( pCommand );
}
}
Label *NewLabel( const char *pText )
{
Label *pLabel = new Label( this, "Label", pText );
pLabel->SetTall( YRES( 9 ) );
pLabel->SetPos( -1, 0 ); // Use default x and accumulated y
// Set font
IScheme *pScheme = vgui::scheme()->GetIScheme( GetScheme() );
HFont hFont = pScheme->GetFont( "DefaultVerySmall", true );
pLabel->SetFont( hFont );
return pLabel;
}
CExButton *NewSetDefaultButton( int nSliderInfoId )
{
CExButton *pButton = new CExButton( this, "DefaultButton", "#Replay_SetDefaultSetting" );
pButton->SetTall( YRES( 11 ) );
pButton->SetPos( XRES( 30 ), -1 ); // Set y to -1 so it will stay on the same line
pButton->SetContentAlignment( Label::a_center );
CFmtStr fmtResetCommand( "reset_%i", nSliderInfoId );
pButton->SetCommand( fmtResetCommand.Access() );
pButton->AddActionSignalTarget( this );
// Set font
IScheme *pScheme = vgui::scheme()->GetIScheme( GetScheme() );
HFont hFont = pScheme->GetFont( "DefaultVerySmall", true );
pButton->SetFont( hFont );
return pButton;
}
protected:
MESSAGE_FUNC_PARAMS( OnSliderMoved, "SliderMoved", pParams )
{
Panel *pSlider = (Panel *)pParams->GetPtr( "panel" );
float flPercent = pParams->GetInt( "position" ) / SLIDER_RANGE_MAX;
FOR_EACH_LL( m_lstSliderInfos, it )
{
SliderInfo_t *pInfo = m_lstSliderInfos[ it ];
if ( pSlider == pInfo->m_pSlider )
{
*pInfo->m_pValueOut = Lerp( flPercent, pInfo->m_flRange[0], pInfo->m_flRange[1] );
}
}
}
virtual const char *GetResFile() { return NULL; }
virtual void AddControls()
{
}
struct SliderInfo_t
{
Slider *m_pSlider;
float m_flRange[2];
float m_flDefault;
int m_nId;
float *m_pValueOut;
};
const SliderInfo_t *FindSliderInfoFromId( int nId )
{
FOR_EACH_LL( m_lstSliderInfos, it )
{
SliderInfo_t *pInfo = m_lstSliderInfos[ it ];
if ( pInfo->m_nId == nId )
return pInfo;
}
AssertMsg( 0, "Should always find a slider here." );
return NULL;
}
void SetValue( const SliderInfo_t *pSliderInfo, float flValue )
{
if ( !pSliderInfo )
{
AssertMsg( 0, "This should not happen." );
return;
}
// Calculate the range
const float flRange = fabs( pSliderInfo->m_flRange[1] - pSliderInfo->m_flRange[0] );
AssertMsg( flRange > 0, "Bad slider range!" );
// Calculate the percentile based on the specified value and the range.
const float flPercent = fabs( flValue - pSliderInfo->m_flRange[0] ) / flRange;
pSliderInfo->m_pSlider->SetValue( flPercent * SLIDER_RANGE_MAX, true );
}
CUtlLinkedList< Panel * > m_lstControls;
CUtlLinkedList< SliderInfo_t *, int > m_lstSliderInfos;
CExLabel *m_pTitleLabel;
bool m_bControlsAdded;
};
//-----------------------------------------------------------------------------
class CTimeScaleOptionsPanel : public CCameraOptionsPanel
{
DECLARE_CLASS_SIMPLE( CTimeScaleOptionsPanel, CCameraOptionsPanel );
public:
CTimeScaleOptionsPanel( Panel *pParent, float *pTimeScaleProxy )
: BaseClass( pParent, "TimeScaleSettings", "#Replay_TimeScale" ),
m_pTimeScaleSlider( NULL ),
m_pTimeScaleProxy( pTimeScaleProxy )
{
}
virtual const char *GetResFile()
{
return "resource/ui/replayperformanceeditor/settings_timescale.res";
}
virtual void AddControls()
{
m_pTimeScaleSlider = dynamic_cast< Slider * >( FindChildByName( "TimeScaleSlider" ) );
AddSliderToLayout( SLIDER_TIMESCALE, m_pTimeScaleSlider, "#Replay_Scale", TIMESCALE_MIN, TIMESCALE_MAX, *m_pTimeScaleProxy );
}
enum FreeCamSliders_t
{
SLIDER_TIMESCALE,
};
Slider *m_pTimeScaleSlider;
float *m_pTimeScaleProxy;
};
//-----------------------------------------------------------------------------
class CCameraOptionsPanel_Free : public CCameraOptionsPanel
{
DECLARE_CLASS_SIMPLE( CCameraOptionsPanel_Free, CCameraOptionsPanel );
public:
CCameraOptionsPanel_Free( Panel *pParent )
: BaseClass( pParent, "FreeCameraSettings", "#Replay_FreeCam" ),
m_pAccelSlider( NULL ),
m_pSpeedSlider( NULL ),
m_pFovSlider( NULL ),
m_pRotFilterSlider( NULL ),
m_pShakeSpeedSlider( NULL ),
m_pShakeAmountSlider( NULL )
{
}
virtual const char *GetResFile()
{
return "resource/ui/replayperformanceeditor/camsettings_free.res";
}
virtual void AddControls()
{
m_pAccelSlider = dynamic_cast< Slider * >( FindChildByName( "AccelSlider" ) );
m_pSpeedSlider = dynamic_cast< Slider * >( FindChildByName( "SpeedSlider" ) );
m_pFovSlider = dynamic_cast< Slider * >( FindChildByName( "FovSlider" ) );
m_pRotFilterSlider = dynamic_cast< Slider * >( FindChildByName( "RotFilterSlider" ) );
m_pShakeSpeedSlider = dynamic_cast< Slider * >( FindChildByName( "ShakeSpeedSlider" ) );
m_pShakeAmountSlider = dynamic_cast< Slider * >( FindChildByName( "ShakeAmountSlider" ) );
m_pShakeDirSlider = dynamic_cast< Slider * >( FindChildByName( "ShakeDirSlider" ) );
AddSliderToLayout( SLIDER_ACCEL, m_pAccelSlider, "#Replay_Accel", FREE_CAM_ACCEL_MIN, FREE_CAM_ACCEL_MAX, ReplayCamera()->m_flRoamingAccel );
AddSliderToLayout( SLIDER_SPEED, m_pSpeedSlider, "#Replay_Speed", FREE_CAM_SPEED_MIN, FREE_CAM_SPEED_MAX, ReplayCamera()->m_flRoamingSpeed );
AddSliderToLayout( SLIDER_FOV, m_pFovSlider, "#Replay_Fov", FREE_CAM_FOV_MIN, FREE_CAM_FOV_MAX, ReplayCamera()->m_flRoamingFov[1] );
AddSliderToLayout( SLIDER_ROTFILTER, m_pRotFilterSlider, "#Replay_RotFilter", FREE_CAM_ROT_FILTER_MIN, FREE_CAM_ROT_FILTER_MAX, ReplayCamera()->m_flRoamingRotFilterFactor );
AddSliderToLayout( SLIDER_SHAKE_SPEED, m_pShakeSpeedSlider, "#Replay_ShakeSpeed", FREE_CAM_SHAKE_SPEED_MIN, FREE_CAM_SHAKE_SPEED_MAX, ReplayCamera()->m_flRoamingShakeSpeed );
AddSliderToLayout( SLIDER_SHAKE_AMOUNT, m_pShakeAmountSlider, "#Replay_ShakeAmount", FREE_CAM_SHAKE_AMOUNT_MIN, FREE_CAM_SHAKE_AMOUNT_MAX, ReplayCamera()->m_flRoamingShakeAmount );
AddSliderToLayout( SLIDER_SHAKE_DIR, m_pShakeDirSlider, "#Replay_ShakeDir", FREE_CAM_SHAKE_DIR_MIN, FREE_CAM_SHAKE_DIR_MAX, ReplayCamera()->m_flRoamingShakeDir );
}
enum FreeCamSliders_t
{
SLIDER_ACCEL,
SLIDER_SPEED,
SLIDER_FOV,
SLIDER_ROTFILTER,
SLIDER_SHAKE_SPEED,
SLIDER_SHAKE_AMOUNT,
SLIDER_SHAKE_DIR,
};
Slider *m_pAccelSlider;
Slider *m_pSpeedSlider;
Slider *m_pFovSlider;
Slider *m_pRotFilterSlider;
Slider *m_pShakeSpeedSlider;
Slider *m_pShakeAmountSlider;
Slider *m_pShakeDirSlider;
};
//-----------------------------------------------------------------------------
class CReplayButton : public CExImageButton
{
DECLARE_CLASS_SIMPLE( CReplayButton, CExImageButton );
public:
CReplayButton( Panel *pParent, const char *pName, const char *pText )
: BaseClass( pParent, pName, pText ),
m_pTipText( NULL )
{
}
virtual void ApplySettings( KeyValues *pInResourceData )
{
BaseClass::ApplySettings( pInResourceData );
const char *pTipName = pInResourceData->GetString( "tipname" );
if ( pTipName && pTipName[0] )
{
const wchar_t *pTipText = g_pVGuiLocalize->Find( pTipName );
if ( pTipText && pTipText[0] )
{
const int nTipLength = V_wcslen( pTipText );
m_pTipText = new wchar_t[ nTipLength + 1 ];
V_wcsncpy( m_pTipText, pTipText, sizeof(wchar_t) * ( nTipLength + 1 ) );
m_pTipText[ nTipLength ] = L'\0';
}
}
}
virtual void OnCursorEntered()
{
BaseClass::OnCursorEntered();
CReplayPerformanceEditorPanel *pEditor = ReplayUI_GetPerformanceEditor();
if ( pEditor && m_pTipText )
{
pEditor->SetButtonTip( m_pTipText, this );
pEditor->ShowButtonTip( true );
}
}
virtual void OnCursorExited()
{
BaseClass::OnCursorExited();
CReplayPerformanceEditorPanel *pEditor = ReplayUI_GetPerformanceEditor();
if ( pEditor && m_pTipText )
{
pEditor->ShowButtonTip( false );
}
}
private:
wchar_t *m_pTipText;
};
DECLARE_BUILD_FACTORY_DEFAULT_TEXT( CReplayButton, CExImageButton );
//-----------------------------------------------------------------------------
#define MAX_FF_RAMP_TIME 8.0f // The amount of time until we ramp to max scale value.
class CReplayEditorFastForwardButton : public CReplayButton
{
DECLARE_CLASS_SIMPLE( CReplayEditorFastForwardButton, CReplayButton );
public:
CReplayEditorFastForwardButton( Panel *pParent, const char *pName, const char *pText )
: BaseClass( pParent, pName, pText ),
m_flPressTime( 0.0f )
{
m_pHostTimescale = cvar->FindVar( "host_timescale" );
AssertMsg( m_pHostTimescale, "host_timescale lookup failed!" );
ivgui()->AddTickSignal( GetVPanel(), 10 );
}
~CReplayEditorFastForwardButton()
{
ivgui()->RemoveTickSignal( GetVPanel() );
// Avoid a non-1.0 host_timescale after replay edit, which can happen if
// the user is still holding downt he FF button at the end of the replay.
if ( m_pHostTimescale )
{
m_pHostTimescale->SetValue( 1.0f );
}
// Resume demo playback so that any demo played later won't start paused.
PlayDemo();
}
virtual void OnMousePressed( MouseCode code )
{
m_flPressTime = gpGlobals->realtime;
PlayDemo();
BaseClass::OnMousePressed( code );
}
virtual void OnMouseReleased( MouseCode code )
{
m_flPressTime = 0.0f;
PauseDemo();
BaseClass::OnMouseReleased( code );
}
void OnTick()
{
float flScale;
if ( m_flPressTime == 0.0f )
{
flScale = 1.0f;
}
else
{
const float flElapsed = clamp( gpGlobals->realtime - m_flPressTime, 0.0f, MAX_FF_RAMP_TIME );
const float t = CubicEaseIn( flElapsed / MAX_FF_RAMP_TIME );
// If a shift key is down...
if ( input()->IsKeyDown( KEY_LSHIFT ) || input()->IsKeyDown( KEY_RSHIFT ) )
{
// ...slow down host_timescale.
flScale = .1f + .4f * t;
}
// If alt key down...
else if ( input()->IsKeyDown( KEY_LALT ) || input()->IsKeyDown( KEY_RALT ) )
{
// ...FF very quickly, ramp from 5 to 10.
flScale = 5.0f + 5.0f * t;
}
else
{
// Otherwise, start at 1.5 and ramp upwards over time.
flScale = 1.5f + 3.5f * t;
}
}
// Set host_timescale.
if ( m_pHostTimescale )
{
m_pHostTimescale->SetValue( flScale );
}
}
private:
float m_flPressTime;
ConVar *m_pHostTimescale;
};
DECLARE_BUILD_FACTORY_DEFAULT_TEXT( CReplayEditorFastForwardButton, CExImageButton );
//-----------------------------------------------------------------------------
class CRecLightPanel : public EditablePanel
{
DECLARE_CLASS_SIMPLE( CRecLightPanel, vgui::EditablePanel );
public:
CRecLightPanel( Panel *pParent )
: EditablePanel( pParent, "RecLightPanel" ),
m_flPlayPauseTime( 0.0f ),
m_bPaused( false ),
m_bPerforming( false )
{
m_pRecLights[ 0 ] = NULL;
m_pRecLights[ 1 ] = NULL;
m_pPlayPause[ 0 ] = NULL;
m_pPlayPause[ 1 ] = NULL;
}
virtual void ApplySchemeSettings( IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
LoadControlSettings( "resource/ui/replayperformanceeditor/reclight.res", "GAME" );
m_pRecLights[ 0 ] = dynamic_cast< ImagePanel * >( FindChildByName( "RecLightOffImg" ) );
m_pRecLights[ 1 ] = dynamic_cast< ImagePanel * >( FindChildByName( "RecLightOnImg" ) );
m_pPlayPause[ 0 ] = dynamic_cast< ImagePanel * >( FindChildByName( "PlayImg" ) );
m_pPlayPause[ 1 ] = dynamic_cast< ImagePanel * >( FindChildByName( "PauseImg" ) );
m_pCameraFringe = dynamic_cast< ImagePanel *>( FindChildByName( "CameraFringe" ) );
m_pCameraCrosshair = dynamic_cast< ImagePanel *>( FindChildByName( "CameraCrosshair" ) );
}
virtual void PerformLayout()
{
BaseClass::PerformLayout();
SetVisible( m_bPerforming );
const int nScreenWidth = ScreenWidth();
const int nRecLightW = m_pRecLights[ 0 ]->GetWide();
int nXPos = nScreenWidth - nRecLightW + XRES( 6 );
int nYPos = -YRES( 8 );
m_pRecLights[ 0 ]->SetPos( nXPos, nYPos );
m_pRecLights[ 1 ]->SetPos( nXPos, nYPos );
const int nWidth = GetWide();
const int nHeight = GetTall();
// Setup camera fringe height
if ( m_pCameraFringe )
{
m_pCameraFringe->SetSize( nWidth, nHeight );
m_pCameraFringe->InstallMouseHandler( this );
}
// Setup camera cross hair height
if ( m_pCameraCrosshair )
{
int aImageSize[2];
IImage *pImage = m_pCameraCrosshair->GetImage();
pImage->GetSize( aImageSize[0], aImageSize[1] );
aImageSize[0] = m_pCameraCrosshair->GetWide();
aImageSize[1] = m_pCameraCrosshair->GetTall();
const int nStartY = YRES( 13 );
m_pCameraCrosshair->SetBounds(
nStartY + ( nWidth - aImageSize[0] ) / 2,
nStartY + ( nHeight - aImageSize[1] ) / 2,
aImageSize[0] - 2 * nStartY,
aImageSize[1] - 2 * nStartY
);
m_pCameraCrosshair->InstallMouseHandler( this );
}
}
void UpdateBackgroundVisibility()
{
m_pCameraCrosshair->SetVisible( m_bPaused );
m_pCameraFringe->SetVisible( m_bPaused );
}
virtual void OnThink()
{
const float flTime = gpGlobals->realtime;
bool bPauseAnimating = m_flPlayPauseTime > 0.0f &&
flTime >= m_flPlayPauseTime &&
flTime < ( m_flPlayPauseTime + m_flAnimTime );
// Setup light visibility
int nOnOff = fmod( flTime * 2.0f, 2.0f );
bool bOnLightVisible = (bool)nOnOff;
bool bRecording = g_pReplayPerformanceController->IsRecording();
m_pRecLights[ 0 ]->SetVisible( m_bPaused || ( bRecording && !bOnLightVisible ) );
m_pRecLights[ 1 ]->SetVisible( bRecording && ( !m_bPaused && bOnLightVisible ) );
// Deal with fringe and crosshair vis
UpdateBackgroundVisibility();
int iPlayPauseActive = (int)m_bPaused;
// Animate the pause icon
if ( bPauseAnimating )
{
const float t = clamp( ( flTime - m_flPlayPauseTime ) / m_flAnimTime, 0.0f, 1.0f );
const float s = SCurve( t );
const int nSize = (int)Lerp( s, 60.0f, 60.0f * m_nAnimScale );
int aCrossHairPos[2];
m_pCameraCrosshair->GetPos( aCrossHairPos[0], aCrossHairPos[1] );
const int nScreenXCenter = aCrossHairPos[0] + m_pCameraCrosshair->GetWide() / 2;
const int nScreenYCenter = aCrossHairPos[1] + m_pCameraCrosshair->GetTall() / 2;
m_pPlayPause[ iPlayPauseActive ]->SetBounds(
nScreenXCenter - nSize / 2,
nScreenYCenter - nSize / 2,
nSize,
nSize
);
m_pPlayPause[ iPlayPauseActive ]->SetAlpha( (int)( MIN( 0.5f, 1.0f - s ) * 255) );
}
m_pPlayPause[ iPlayPauseActive ]->SetVisible( bPauseAnimating );
m_pPlayPause[ !iPlayPauseActive ]->SetVisible( false );
}
void UpdatePauseState( bool bPaused )
{
if ( bPaused == m_bPaused )
return;
m_bPaused = bPaused;
m_flPlayPauseTime = gpGlobals->realtime;
}
void SetPerforming( bool bPerforming )
{
if ( bPerforming == m_bPerforming )
return;
m_bPerforming = bPerforming;
InvalidateLayout( true, false );
}
float m_flPlayPauseTime;
bool m_bPaused;
bool m_bPerforming;
ImagePanel *m_pPlayPause[2]; // 0=play, 1=pause
ImagePanel *m_pRecLights[2]; // 0=off, 1=on
ImagePanel *m_pCameraFringe;
ImagePanel *m_pCameraCrosshair;
CPanelAnimationVar( int, m_nAnimScale, "anim_scale", "4" );
CPanelAnimationVar( float, m_flAnimTime, "anim_time", "1.5" );
};
//-----------------------------------------------------------------------------
CReplayPerformanceEditorPanel::CReplayPerformanceEditorPanel( Panel *parent, ReplayHandle_t hReplay )
: EditablePanel( parent, "ReplayPerformanceEditor" ),
m_hReplay( hReplay ),
m_flLastTime( -1 ),
m_nRedBlueLabelRightX( 0 ),
m_nBottomPanelStartY( 0 ),
m_nBottomPanelHeight( 0 ),
m_nLastRoundedTime( -1 ),
m_flSpaceDownStart( 0.0f ),
m_flOldFps( -1.0f ),
m_flLastTimeSpaceBarPressed( 0.0f ),
m_flActiveTimeInEditor( 0.0f ),
m_flTimeScaleProxy( 1.0f ),
m_iCameraSelection( CAM_FIRST ),
m_bMousePressed( false ),
m_bMouseDown( false ),
m_nMouseClickedOverCameraSettingsPanel( CAM_INVALID ),
m_bShownAtLeastOnce( false ),
m_bAchievementAwarded( false ),
m_pImageList( NULL ),
m_pCurTimeLabel( NULL ),
m_pTotalTimeLabel( NULL ),
m_pPlayerNameLabel( NULL ),
m_pMouseTargetPanel( NULL ),
m_pSlowMoButton( NULL ),
m_pRecLightPanel( NULL ),
m_pPlayerCellData( NULL ),
m_pBottom( NULL ),
m_pMenuButton( NULL ),
m_pMenu( NULL ),
m_pPlayerCellsPanel( NULL ),
m_pButtonTip( NULL ),
m_pSavingDlg( NULL )
{
V_memset( m_pCameraButtons, 0, sizeof( m_pCameraButtons ) );
V_memset( m_pCtrlButtons, 0, sizeof( m_pCtrlButtons ) );
V_memset( m_pCameraOptionsPanels, NULL, sizeof( m_pCameraOptionsPanels ) );
m_pCameraOptionsPanels[ CAM_FREE ] = new CCameraOptionsPanel_Free( this );
m_pCameraOptionsPanels[ COMPONENT_TIMESCALE ] = new CTimeScaleOptionsPanel( this, &m_flTimeScaleProxy );
m_nRedBlueSigns[0] = -1;
m_nRedBlueSigns[1] = 1;
m_iCurPlayerTarget = -1;
m_pImageList = new ImageList( false );
SetParent( g_pClientMode->GetViewport() );
HScheme hScheme = scheme()->LoadSchemeFromFileEx( enginevgui->GetPanel( PANEL_CLIENTDLL ), "resource/ClientScheme.res", "ClientScheme" );
SetScheme( hScheme );
ivgui()->AddTickSignal( GetVPanel(), 16 ); // Roughly 60hz
MakePopup( true );
SetMouseInputEnabled( true );
// Create bottom
m_pBottom = new EditablePanel( this, "BottomPanel" );
// Add player cells
m_pPlayerCellsPanel = new EditablePanel( m_pBottom, "PlayerCellsPanel" );
for ( int i = 0; i < 2; ++i )
{
for ( int j = 0; j <= MAX_PLAYERS; ++j )
{
m_pPlayerCells[i][j] = new CPlayerCell( m_pPlayerCellsPanel, "PlayerCell", &m_iCurPlayerTarget );
m_pPlayerCells[i][j]->SetVisible( false );
AddPanelKeyboardInputDisableList( m_pPlayerCells[i][j] );
}
}
// Create rec light panel
m_pRecLightPanel = SETUP_PANEL( new CRecLightPanel( g_pClientMode->GetViewport() ) );
// Display "enter performance mode" tip
DisplayPerformanceTip( "#Replay_PerfTip_EnterPerfMode", &replay_perftip_count_enter, MAX_TIP_DISPLAYS );
// Create menu
m_pMenu = new Menu( this, "Menu" );
m_aMenuItemIds[ MENU_SAVE ] = m_pMenu->AddMenuItem( "#Replay_Save", "menu_save", this );
m_aMenuItemIds[ MENU_SAVEAS ] = m_pMenu->AddMenuItem( "#Replay_SaveAs", "menu_saveas", this );
m_pMenu->AddSeparator();
m_aMenuItemIds[ MENU_EXIT ] = m_pMenu->AddMenuItem( "#Replay_Exit", "menu_exit", this );
m_pMenu->EnableUseMenuManager( false ); // The menu manager doesn't play nice with the menu button
}
CReplayPerformanceEditorPanel::~CReplayPerformanceEditorPanel()
{
m_pRecLightPanel->MarkForDeletion();
m_pRecLightPanel = NULL;
m_pButtonTip->MarkForDeletion();
m_pButtonTip = NULL;
g_bIsReplayRewinding = false;
surface()->PlaySound( "replay\\performanceeditorclosed.wav" );
CPerformanceTip::Cleanup();
ClearPlayerCellData();
}
void CReplayPerformanceEditorPanel::ClearPlayerCellData()
{
if ( m_pPlayerCellData )
{
m_pPlayerCellData->deleteThis();
m_pPlayerCellData = NULL;
}
}
void CReplayPerformanceEditorPanel::AddPanelKeyboardInputDisableList( Panel *pPanel )
{
m_lstDisableKeyboardInputPanels.AddToTail( pPanel );
}
void CReplayPerformanceEditorPanel::ApplySchemeSettings( IScheme *pScheme )
{
BaseClass::ApplySchemeSettings( pScheme );
LoadControlSettings( "resource/ui/replayperformanceeditor/main.res", "GAME" );
m_lstDisableKeyboardInputPanels.RemoveAll();
int nParentWidth = GetParent()->GetWide();
int nParentHeight = GetParent()->GetTall();
// Set size of this panel
SetSize( nParentWidth, nParentHeight );
// Layout bottom
if ( m_pBottom )
{
m_nBottomPanelHeight = m_pBottom->GetTall(); // Get from .res
m_nBottomPanelStartY = nParentHeight - m_nBottomPanelHeight;
m_pBottom->SetBounds( 0, m_nBottomPanelStartY, nParentWidth, m_nBottomPanelHeight );
}
// Layout rec light panel - don't overlap bottom panel
m_pRecLightPanel->SetBounds( 0, 0, ScreenWidth(), m_nBottomPanelStartY );
// Setup camera buttons
const int nNumCameraButtons = NCAMS;
const char *pCameraButtonNames[nNumCameraButtons] = { "CameraFree", "CameraThird", "CameraFirst", "TimeScaleButton" };
int nCurButtonX = nParentWidth - m_nRightMarginWidth;
int nLeftmostCameraButtonX = 0;
for ( int i = 0; i < nNumCameraButtons; ++i )
{
m_pCameraButtons[i] = dynamic_cast< CExImageButton * >( FindChildByName( pCameraButtonNames[ i ] ) );
if ( m_pCameraButtons[i] )
{
CExImageButton *pCurButton = m_pCameraButtons[ i ];
if ( !pCurButton )
continue;
nCurButtonX -= pCurButton->GetWide();
int nX, nY;
pCurButton->GetPos( nX, nY );
pCurButton->SetPos( nCurButtonX, nY );
pCurButton->SetParent( m_pBottom );
pCurButton->AddActionSignalTarget( this );
#if !defined( TF_CLIENT_DLL )
pCurButton->SetPaintBorderEnabled( false );
#endif
AddPanelKeyboardInputDisableList( pCurButton );
}
}
nLeftmostCameraButtonX = nCurButtonX;
static const char *s_pControlButtonNames[NUM_CTRLBUTTONS] = {
"InButton", "GotoBeginningButton", "RewindButton",
"PlayButton",
"FastForwardButton", "GotoEndButton", "OutButton"
};
for ( int i = 0; i < NUM_CTRLBUTTONS; ++i )
{
CExImageButton *pCurButton = dynamic_cast< CExImageButton * >( FindChildByName( s_pControlButtonNames[ i ] ) ); Assert( pCurButton );
if ( !pCurButton )
continue;
pCurButton->SetParent( m_pBottom );
pCurButton->AddActionSignalTarget( this );
AddPanelKeyboardInputDisableList( pCurButton );
#if !defined( TF_CLIENT_DLL )
pCurButton->SetPaintBorderEnabled( false );
#endif
m_pCtrlButtons[ i ] = pCurButton;
}
// If the performance in tick is set, highlight the in point button
{
CReplayPerformance *pSavedPerformance = GetSavedPerformance();
m_pCtrlButtons[ CTRLBUTTON_IN ]->SetSelected( pSavedPerformance && pSavedPerformance->HasInTick() );
m_pCtrlButtons[ CTRLBUTTON_OUT ]->SetSelected( pSavedPerformance && pSavedPerformance->HasOutTick() );
}
// Select first-person camera by default.
UpdateCameraSelectionPosition( CAM_FIRST );
// Position time label
m_pCurTimeLabel = dynamic_cast< CExLabel * >( FindChildByName( "CurTimeLabel" ) );
m_pTotalTimeLabel = dynamic_cast< CExLabel * >( FindChildByName( "TotalTimeLabel" ) );
m_pCurTimeLabel->SetParent( m_pBottom );
m_pTotalTimeLabel->SetParent( m_pBottom );
// Get player name label
m_pPlayerNameLabel = dynamic_cast< CExLabel * >( FindChildByName( "PlayerNameLabel" ) );
// Get mouse target panel
m_pMouseTargetPanel = dynamic_cast< EditablePanel * >( FindChildByName( "MouseTargetPanel" ) );
for ( int i = 0; i < 2; ++i )
{
for ( int j = 0; j <= MAX_PLAYERS; ++j )
{
m_pPlayerCells[i][j]->SetMouseInputEnabled( true );
}
}
// Get menu button
m_pMenuButton = dynamic_cast< CExImageButton * >( FindChildByName( "MenuButton" ) );
AddPanelKeyboardInputDisableList( m_pMenuButton );
m_pMenuButton->SetMouseInputEnabled( true );
#if !defined( TF_CLIENT_DLL )
m_pMenuButton->SetPaintBorderEnabled( false );
#endif
// Get button tip
m_pButtonTip = dynamic_cast< CReplayTipLabel * >( FindChildByName( "ButtonTip" ) );
m_pButtonTip->SetParent( g_pClientMode->GetViewport() );
}
static void Replay_GotoTick( bool bConfirmed, void *pContext )
{
if ( bConfirmed )
{
int nGotoTick = (int)pContext;
CFmtStr fmtCmd( "demo_gototick %i\ndemo_pause\n", nGotoTick );
engine->ClientCmd_Unrestricted( fmtCmd.Access() );
}
}
void CReplayPerformanceEditorPanel::OnSliderMoved( KeyValues *pParams )
{
}
void CReplayPerformanceEditorPanel::OnInGameMouseWheelEvent( int nDelta )
{
HandleMouseWheel( nDelta );
}
void CReplayPerformanceEditorPanel::HandleMouseWheel( int nDelta )
{
if ( ReplayCamera()->GetMode() == OBS_MODE_ROAMING )
{
// Invert mousewheel input if necessary
if ( replay_editor_fov_mousewheel_invert.GetBool() )
{
nDelta *= -1;
}
float &flFov = ReplayCamera()->m_flRoamingFov[1];
flFov = clamp( flFov - nDelta * replay_editor_fov_mousewheel_multiplier.GetFloat(), FREE_CAM_FOV_MIN, FREE_CAM_FOV_MAX );
// Update FOV slider in free camera settings
CCameraOptionsPanel_Free *pFreeCamOptions = static_cast< CCameraOptionsPanel_Free * >( m_pCameraOptionsPanels[ CAM_FREE ] );
pFreeCamOptions->m_pFovSlider->SetValue( flFov - FREE_CAM_FOV_MIN, false );
}
}
void CReplayPerformanceEditorPanel::ApplySettings( KeyValues *pInResourceData )
{
BaseClass::ApplySettings( pInResourceData );
ClearPlayerCellData();
KeyValues *pPlayerCellData = pInResourceData->FindKey( "PlayerCell" );
if ( pPlayerCellData )
{
m_pPlayerCellData = new KeyValues( "PlayerCell" );
pPlayerCellData->CopySubkeys( m_pPlayerCellData );
}
}
CameraMode_t CReplayPerformanceEditorPanel::IsMouseOverActiveCameraOptionsPanel( int nMouseX, int nMouseY )
{
// In one of the camera options panels?
for ( int i = 0; i < NCAMS; ++i )
{
CCameraOptionsPanel *pCurPanel = m_pCameraOptionsPanels[ i ];
if ( pCurPanel && pCurPanel->IsVisible() && pCurPanel->IsWithin( nMouseX, nMouseY ) )
return (CameraMode_t)i;
}
return CAM_INVALID;
}
void CReplayPerformanceEditorPanel::OnMouseWheeled( int nDelta )
{
HandleMouseWheel( nDelta );
}
void CReplayPerformanceEditorPanel::OnTick()
{
BaseClass::OnTick();
// engine->Con_NPrintf( 0, "timescale: %f", g_pReplayPerformanceController->GetPlaybackTimeScale() );
C_ReplayCamera *pCamera = ReplayCamera();
if ( !pCamera )
return;
// Calc elapsed time
float flElapsed = gpGlobals->realtime - m_flLastTime;
m_flLastTime = gpGlobals->realtime;
// If this is the first time we're running and camera is valid, get primary target
if ( m_iCurPlayerTarget < 0 )
{
m_iCurPlayerTarget = pCamera->GetPrimaryTargetIndex();
}
// NOTE: Third-person is not "controllable" yet
int nCameraMode = pCamera->GetMode();
bool bInAControllableCameraMode = nCameraMode == OBS_MODE_ROAMING || nCameraMode == OBS_MODE_CHASE;
// Get mouse cursor pos
int nMouseX, nMouseY;
input()->GetCursorPos( nMouseX, nMouseY );
// Toggle in and out of camera control if appropriate
// Mouse pressed?
bool bMouseDown = input()->IsMouseDown( MOUSE_LEFT );
m_bMousePressed = bMouseDown && !m_bMouseDown;
m_bMouseDown = bMouseDown;
// Reset this flag if mouse is no longer down
if ( !m_bMouseDown )
{
m_nMouseClickedOverCameraSettingsPanel = CAM_INVALID;
}
bool bNoDialogsUp = TFModalStack()->IsEmpty();
bool bMouseCursorOverPerfEditor = nMouseY >= m_nBottomPanelStartY;
bool bMouseOverMenuButton = m_pMenuButton->IsWithin( nMouseX, nMouseY );
bool bMouseOverMenu = m_pMenu->IsWithin( nMouseX, nMouseY );
bool bRecording = g_pReplayPerformanceController->IsRecording();
if ( IsVisible() && m_bMousePressed )
{
CameraMode_t nActiveOptionsPanel = IsMouseOverActiveCameraOptionsPanel( nMouseX, nMouseY );
if ( nActiveOptionsPanel != CAM_INVALID )
{
m_nMouseClickedOverCameraSettingsPanel = nActiveOptionsPanel;
}
else if ( m_pMenu->IsVisible() && !m_pMenu->IsWithin( nMouseX, nMouseY ) )
{
ToggleMenu();
}
else if ( bInAControllableCameraMode && !bMouseCursorOverPerfEditor && !bMouseOverMenuButton &&
!bMouseOverMenu && bNoDialogsUp )
{
if ( bRecording )
{
bool bMouseInputEnabled = IsMouseInputEnabled();
// Already in a controllable camera mode?
if ( bMouseInputEnabled )
{
DisplayPerformanceTip( "#Replay_PerfTip_ExitFreeCam", &replay_perftip_count_freecam_exit, MAX_TIP_DISPLAYS );
surface()->PlaySound( "replay\\cameracontrolmodeentered.wav" );
}
else
{
DisplayPerformanceTip( "#Replay_PerfTip_EnterFreeCam", &replay_perftip_count_freecam_enter, MAX_TIP_DISPLAYS );
surface()->PlaySound( "replay\\cameracontrolmodeexited.wav" );
}
SetMouseInputEnabled( !bMouseInputEnabled );
}
else
{
// Play an error sound
surface()->PlaySound( "replay\\cameracontrolerror.wav" );
}
}
}
// Show panel if space key bar is down
bool bSpaceDown = bNoDialogsUp && !enginevgui->IsGameUIVisible() && input()->IsKeyDown( KEY_SPACE );
m_bSpacePressed = bSpaceDown && !m_bSpaceDown;
m_bSpaceDown = bSpaceDown;
// Modify visibility?
bool bShow = IsVisible();
if ( m_bSpacePressed )
{
bShow = !IsVisible();
}
// Set visibility?
if ( IsVisible() != bShow )
{
ShowPanel( bShow );
m_bShownAtLeastOnce = true;
// For achievements:
Achievements_OnSpaceBarPressed();
}
// Factor in host_timescale.
float flScaledElapsed = flElapsed;
ConVarRef host_timescale( "host_timescale" );
if ( host_timescale.GetFloat() > 0 )
{
flScaledElapsed *= host_timescale.GetFloat();
}
// Do FOV smoothing
ReplayCamera()->SmoothFov( flScaledElapsed );
// Don't do any more processing if not needed
if ( !m_bShownAtLeastOnce )
return;
// Update time text if necessary
UpdateTimeLabels();
// Make all player cells invisible
int nTeamCounts[2] = {0,0};
int nCurTeam = 0;
for ( int i = 0; i < 2; ++i )
for ( int j = 0; j <= MAX_PLAYERS; ++j )
{
m_pPlayerCells[i][j]->SetVisible( false );
}
int iMouseOverPlayerIndex = -1;
CPlayerCell *pMouseOverCell = NULL;
// Update player cells
bool bLayoutPlayerCells = true; // TODO: only layout when necessary
C_ReplayGame_PlayerResource_t *pGamePlayerResource = dynamic_cast< C_ReplayGame_PlayerResource_t * >( g_PR );
for ( int iPlayer = 1; iPlayer <= MAX_PLAYERS; ++iPlayer )
{
IGameResources *pGR = GameResources();
if ( !pGR || !pGR->IsConnected( iPlayer ) )
continue;
// Which team?
int iTeam = pGR->GetTeam( iPlayer );
switch ( iTeam )
{
case REPLAY_TEAM_TEAM0:
++nTeamCounts[0];
nCurTeam = 0;
break;
case REPLAY_TEAM_TEAM1:
++nTeamCounts[1];
nCurTeam = 1;
break;
default:
nCurTeam = -1;
break;
}
if ( nCurTeam < 0 )
continue;
#if !defined( CSTRIKE_DLL )
int iPlayerClass = pGamePlayerResource->GetPlayerClass( iPlayer );
if ( iPlayerClass == REPLAY_CLASS_UNDEFINED )
continue;
#endif
int nCurTeamCount = nTeamCounts[ nCurTeam ];
CPlayerCell* pCell = m_pPlayerCells[ nCurTeam ][ nCurTeamCount-1 ];
// Cache the player index
pCell->m_iPlayerIndex = iPlayer;
// Make visible
pCell->SetVisible( true );
// Show leaderboard icon
#if defined( TF_CLIENT_DLL )
char szClassImg[64];
extern const char *g_aPlayerClassNames_NonLocalized[ REPLAY_NUM_CLASSES ];
char const *pClassName = iPlayerClass == TF_CLASS_DEMOMAN
? "demo"
: g_aPlayerClassNames_NonLocalized[ iPlayerClass ];
V_snprintf( szClassImg, sizeof( szClassImg ), "../HUD/leaderboard_class_%s", pClassName );
// Show dead icon instead?
if ( !pGamePlayerResource->IsAlive( iPlayer ) )
{
V_strcat( szClassImg, "_d", sizeof( szClassImg ) );
}
IImage *pImage = scheme()->GetImage( szClassImg, true );
if ( pImage )
{
pImage->SetSize( 32, 32 );
pCell->GetImage()->SetImage( pImage );
}
#elif defined( CSTRIKE_DLL )
// TODO - create and use class icons
char szText[16];
V_snprintf( szText, sizeof( szText ), "%i", nTeamCounts[ nCurTeam ] );
pCell->SetText( szText );
#endif
// Display player name if mouse is over the current cell
if ( pCell->IsWithin( nMouseX, nMouseY ) )
{
iMouseOverPlayerIndex = iPlayer;
pMouseOverCell = pCell;
}
}
// Check to see if we're hovering over a camera-mode, and if so, display its options panel if it has one
if ( bRecording )
{
for ( int i = 0; i < NCAMS; ++i )
{
CCameraOptionsPanel *pCurOptionsPanel = m_pCameraOptionsPanels[ i ];
if ( !pCurOptionsPanel )
continue;
bool bMouseOverButton = m_pCameraButtons[ i ]->IsWithin( nMouseX, nMouseY );
bool bMouseOverOptionsPanel = pCurOptionsPanel->IsWithin( nMouseX, nMouseY );
bool bInCameraModeThatMouseIsOver = ReplayCamera()->GetMode() == GetCameraModeFromButtonIndex( (CameraMode_t)i );
bool bDontCareAboutCameraMode = i == COMPONENT_TIMESCALE;
bool bActivate = ( i == m_nMouseClickedOverCameraSettingsPanel ) ||
( ( ( bInCameraModeThatMouseIsOver || bDontCareAboutCameraMode ) && bMouseOverButton ) || ( bMouseOverOptionsPanel && pCurOptionsPanel->IsVisible() ) );
pCurOptionsPanel->SetVisible( bActivate );
}
}
if ( bLayoutPlayerCells )
{
LayoutPlayerCells();
}
// Setup player name label and temporary camera view
if ( m_pPlayerNameLabel && pGamePlayerResource && pMouseOverCell )
{
m_pPlayerNameLabel->SetText( pGamePlayerResource->GetPlayerName( iMouseOverPlayerIndex ) );
m_pPlayerNameLabel->SizeToContents();
int nCellPos[2];
pMouseOverCell->GetPos( nCellPos[0], nCellPos[1] );
int nLabelX = MAX(
nCellPos[0],
m_nRedBlueLabelRightX
);
int nLabelY = m_nBottomPanelStartY + ( m_nBottomPanelHeight - m_pPlayerNameLabel->GetTall() ) / 2;
m_pPlayerNameLabel->SetPos( nLabelX, nLabelY );
m_pPlayerNameLabel->SetVisible( true );
// Setup camera
pCamera->SetPrimaryTarget( iMouseOverPlayerIndex );
}
else
{
m_pPlayerNameLabel->SetVisible( false );
// Set camera to last valid target
Assert( m_iCurPlayerTarget >= 0 );
pCamera->SetPrimaryTarget( m_iCurPlayerTarget );
}
// If user clicked, assume it was the selected cell and set primary target in camera
if ( iMouseOverPlayerIndex >= 0 )
{
pCamera->SetPrimaryTarget( iMouseOverPlayerIndex );
}
else
{
pCamera->SetPrimaryTarget( m_iCurPlayerTarget );
}
// If in free-cam mode, add set view event if we're not paused
if ( bInAControllableCameraMode && m_bShownAtLeastOnce && bRecording )
{
AddSetViewEvent();
AddTimeScaleEvent( m_flTimeScaleProxy );
}
// Set paused state in rec light
const bool bPaused = IsPaused();
m_pRecLightPanel->UpdatePauseState( bPaused );
Achievements_Think( flElapsed );
}
void CReplayPerformanceEditorPanel::Achievements_OnSpaceBarPressed()
{
m_flLastTimeSpaceBarPressed = gpGlobals->realtime;
}
void CReplayPerformanceEditorPanel::Achievements_Think( float flElapsed )
{
// engine->Con_NPrintf( 10, "total time: %f", m_flActiveTimeInEditor );
// engine->Con_NPrintf( 11, "last time space bar pressed: %f", m_flLastTimeSpaceBarPressed );
// Already awarded one this editing session?
if ( m_bAchievementAwarded )
return;
// Too much idle time since last activity?
if ( gpGlobals->realtime - m_flLastTimeSpaceBarPressed > 60.0f )
{
m_flActiveTimeInEditor = 0.0f;
return;
}
// Accumulate active time
m_flActiveTimeInEditor += flElapsed;
// Award now if three-minutes of non-idle time has passed
const float flMinutes = 60.0f * 3.0f;
if ( m_flActiveTimeInEditor < flMinutes )
return;
Achievements_Grant();
}
void CReplayPerformanceEditorPanel::Achievements_Grant()
{
#if defined( TF_CLIENT_DLL )
g_AchievementMgrTF.AwardAchievement( ACHIEVEMENT_TF_REPLAY_EDIT_TIME );
#endif
// Awarded
m_bAchievementAwarded = true;
}
bool CReplayPerformanceEditorPanel::IsPaused()
{
return IsVisible();
}
CReplayPerformance *CReplayPerformanceEditorPanel::GetPerformance() const
{
return g_pReplayPerformanceController->GetPerformance();
}
CReplayPerformance *CReplayPerformanceEditorPanel::GetSavedPerformance() const
{
return g_pReplayPerformanceController->GetSavedPerformance();
}
int CReplayPerformanceEditorPanel::GetCameraModeFromButtonIndex( CameraMode_t iCamera )
{
switch ( iCamera )
{
case CAM_FREE: return OBS_MODE_ROAMING;
case CAM_THIRD: return OBS_MODE_CHASE;
case CAM_FIRST: return OBS_MODE_IN_EYE;
}
return CAM_INVALID;
}
void CReplayPerformanceEditorPanel::UpdateTimeLabels()
{
CReplay *pPlayingReplay = g_pReplayManager->GetPlayingReplay();
if ( !pPlayingReplay || !m_pCurTimeLabel || !m_pTotalTimeLabel )
return;
float flCurTime, flTotalTime;
g_pClientReplayContext->GetPlaybackTimes( flCurTime, flTotalTime, pPlayingReplay, GetPerformance() );
int nCurRoundedTime = (int)flCurTime; // Essentially floor'd
if ( nCurRoundedTime == m_nLastRoundedTime )
return;
m_nLastRoundedTime = nCurRoundedTime;
// Set current time text
char szTimeText[64];
V_snprintf( szTimeText, sizeof( szTimeText ), "%s", CReplayTime::FormatTimeString( nCurRoundedTime ) );
m_pCurTimeLabel->SetText( szTimeText );
// Set total time text
V_snprintf( szTimeText, sizeof( szTimeText ), "%s", CReplayTime::FormatTimeString( (int)flTotalTime ) );
m_pTotalTimeLabel->SetText( szTimeText );
// Center between left-most camera button and play/pause button
m_pCurTimeLabel->SizeToContents();
m_pTotalTimeLabel->SizeToContents();
}
void CReplayPerformanceEditorPanel::UpdateCameraSelectionPosition( CameraMode_t nCameraMode )
{
Assert( nCameraMode >= 0 && nCameraMode < NCAMS );
m_iCameraSelection = nCameraMode;
UpdateCameraButtonImages();
}
void CReplayPerformanceEditorPanel::UpdateFreeCamSettings( const SetViewParams_t ¶ms )
{
CCameraOptionsPanel_Free *pSettingsPanel = dynamic_cast< CCameraOptionsPanel_Free * >( m_pCameraOptionsPanels[ CAM_FREE ] );
if ( !pSettingsPanel )
return;
pSettingsPanel->SetValue( CCameraOptionsPanel_Free::SLIDER_ACCEL, params.m_flAccel );
pSettingsPanel->SetValue( CCameraOptionsPanel_Free::SLIDER_SPEED, params.m_flSpeed );
pSettingsPanel->SetValue( CCameraOptionsPanel_Free::SLIDER_FOV, params.m_flFov );
pSettingsPanel->SetValue( CCameraOptionsPanel_Free::SLIDER_ROTFILTER, params.m_flRotationFilter );
}
void CReplayPerformanceEditorPanel::UpdateTimeScale( float flScale )
{
CTimeScaleOptionsPanel *pSettingsPanel = dynamic_cast< CTimeScaleOptionsPanel * >( m_pCameraOptionsPanels[ COMPONENT_TIMESCALE ] );
if ( !pSettingsPanel )
return;
pSettingsPanel->SetValue( CTimeScaleOptionsPanel::SLIDER_TIMESCALE, flScale );
}
void CReplayPerformanceEditorPanel::LayoutPlayerCells()
{
int nPanelHeight = m_pPlayerCellsPanel->GetTall();
int nCellBuffer = XRES(1);
for ( int i = 0; i < 2; ++i )
{
int nCurX = m_nRedBlueLabelRightX;
for ( int j = 0; j <= MAX_PLAYERS; ++j )
{
CPlayerCell *pCurCell = m_pPlayerCells[i][j];
if ( !pCurCell->IsVisible() )
continue;
// Apply cached settings from .res file
if ( m_pPlayerCellData )
{
pCurCell->ApplySettings( m_pPlayerCellData );
}
const int nY = nPanelHeight/2 + m_nRedBlueSigns[i] * nPanelHeight/4 - pCurCell->GetTall()/2;
pCurCell->SetPos(
nCurX,
nY
);
nCurX += pCurCell->GetWide() + nCellBuffer;
}
}
}
void CReplayPerformanceEditorPanel::PerformLayout()
{
int w = ScreenWidth(), h = ScreenHeight();
SetBounds(0,0,w,h);
// Layout camera options panels
for ( int i = 0; i < NCAMS; ++i )
{
CCameraOptionsPanel *pCurOptionsPanel = m_pCameraOptionsPanels[ i ];
if ( !pCurOptionsPanel )
continue;
CExImageButton *pCurCameraButton = m_pCameraButtons[ i ];
if ( !pCurCameraButton )
continue;
// Get camera button position
int aCameraButtonPos[2];
int aBottomPos[2];
pCurCameraButton->GetPos( aCameraButtonPos[ 0 ], aCameraButtonPos[ 1 ] );
m_pBottom->GetPos( aBottomPos[ 0 ], aBottomPos[ 1 ] );
// Layout the panel now - it should set its own size, which we need to know to position it properly
pCurOptionsPanel->InvalidateLayout( true, true );
// Position it
pCurOptionsPanel->SetPos(
aBottomPos[ 0 ] + aCameraButtonPos[ 0 ] + pCurCameraButton->GetWide() - pCurOptionsPanel->GetWide() - XRES( 3 ),
aBottomPos[ 1 ] + aCameraButtonPos[ 1 ] - pCurOptionsPanel->GetTall()
);
}
// Setup menu position relative to menu button
int aMenuButtonPos[2];
m_pMenuButton->GetPos( aMenuButtonPos[0], aMenuButtonPos[1] );
m_pMenu->SetPos( aMenuButtonPos[0], aMenuButtonPos[1] + m_pMenuButton->GetTall() );
// Set player cell panel to be the size of half the bottom panel
int aBottomSize[2];
m_pBottom->GetSize( aBottomSize[0], aBottomSize[1] );
m_pPlayerCellsPanel->SetBounds( 0, 0, aBottomSize[0] / 2, m_pPlayerCellsPanel->GetTall() );
CExLabel *pRedBlueLabels[2] = {
dynamic_cast< CExLabel * >( m_pPlayerCellsPanel->FindChildByName( "RedLabel" ) ),
dynamic_cast< CExLabel * >( m_pPlayerCellsPanel->FindChildByName( "BlueLabel" ) )
};
int nMargins[2] = { XRES( 5 ), YRES( 2 ) };
for ( int i = 0; i < 2; ++i )
{
pRedBlueLabels[i]->SizeToContents();
const int nY = m_pPlayerCellsPanel->GetTall()/2 + m_nRedBlueSigns[i] * m_pPlayerCellsPanel->GetTall()/4 - pRedBlueLabels[i]->GetTall()/2;
pRedBlueLabels[i]->SetPos( nMargins[0], nY );
m_nRedBlueLabelRightX = MAX( m_nRedBlueLabelRightX, nMargins[0] + pRedBlueLabels[i]->GetWide() + nMargins[0] );
}
// Position player cells
LayoutPlayerCells();
BaseClass::PerformLayout();
}
bool CReplayPerformanceEditorPanel::OnStateChangeRequested( const char *pEventStr )
{
// If we're already recording, allow the change.
if ( g_pReplayPerformanceController->IsRecording() )
return true;
// If we aren't recording and there is no forthcoming data in the playback stream, allow the change.
if ( !g_pReplayPerformanceController->IsPlaybackDataLeft() )
return true;
// Otherwise, record the event string and show a dialog asking the user if they're sure they want to nuke.
V_strncpy( m_szSuspendedEvent, pEventStr, sizeof( m_szSuspendedEvent ) );
ShowConfirmDialog( "#Replay_Warning", "#Replay_NukePerformanceChanges", "#GameUI_Confirm", "#GameUI_CancelBold", OnConfirmDestroyChanges, this, this, REPLAY_SOUND_DIALOG_POPUP );
return false;
}
void CReplayPerformanceEditorPanel::SetButtonTip( wchar_t *pTipText, Panel *pContextPanel )
{
// Set the text
m_pButtonTip->SetText( pTipText );
m_pButtonTip->InvalidateLayout( true, true );
// Center relative to context panel
int aPos[2];
ipanel()->GetAbsPos( pContextPanel->GetVPanel(), aPos[0], aPos[1] );
const int nX = clamp(
aPos[0] - m_pButtonTip->GetWide() / 2,
0,
ScreenWidth() - m_pButtonTip->GetWide() - (int) XRES( 40 )
);
const int nY = m_nBottomPanelStartY - m_pButtonTip->GetTall() - (int) YRES( 2 );
m_pButtonTip->SetPos( nX, nY );
}
void CReplayPerformanceEditorPanel::ShowButtonTip( bool bShow )
{
m_pButtonTip->SetVisible( bShow );
}
void CReplayPerformanceEditorPanel::ShowSavingDialog()
{
Assert( !m_pSavingDlg );
m_pSavingDlg = new CSavingDialog( ReplayUI_GetPerformanceEditor() );
ShowWaitingDialog( m_pSavingDlg, "#Replay_Saving", true, false, -1 );
}
void CReplayPerformanceEditorPanel::ShowPanel( bool bShow )
{
if ( bShow == IsVisible() )
return;
if ( bShow )
{
// We are now performing.
m_pRecLightPanel->SetPerforming( true );
// Disable keyboard input on all panels added to the list
FOR_EACH_LL( m_lstDisableKeyboardInputPanels, it )
{
m_lstDisableKeyboardInputPanels[ it ]->SetKeyBoardInputEnabled( false );
}
DisplayPerformanceTip( "#Replay_PerfTip_ExitPerfMode", &replay_perftip_count_exit, MAX_TIP_DISPLAYS );
// Fire a message the game DLL can intercept (for achievements, etc).
IGameEvent *event = gameeventmanager->CreateEvent( "entered_performance_mode" );
if ( event )
{
gameeventmanager->FireEventClientSide( event );
}
// Play a sound
surface()->PlaySound( "replay\\enterperformancemode.wav" );
}
else
{
// Display a tip
DisplayPerformanceTip( "#Replay_PerfTip_EnterPerfMode", &replay_perftip_count_enter, MAX_TIP_DISPLAYS );
// Play a sound
surface()->PlaySound( "replay\\exitperformancemode.wav" );
}
// Show mouse cursor
SetMouseInputEnabled( bShow );
SetVisible( bShow );
MakePopup( bShow );
// Avoid waiting for next OnThink() to hide background images
m_pRecLightPanel->UpdatePauseState( bShow );
m_pRecLightPanel->UpdateBackgroundVisibility();
// Play or pause
if ( bShow )
{
PauseDemo();
}
else
{
PlayDemo();
}
// Keep controller informed about pause state so that it can throw away unimportant events during pause if it's recording.
g_pReplayPerformanceController->NotifyPauseState( bShow );
}
bool CReplayPerformanceEditorPanel::OnEndOfReplayReached()
{
if ( m_bShownAtLeastOnce )
{
ShowPanel( true );
DisplayPerformanceTip( "#Replay_PerfTip_EndOfReplayReached" );
// Don't end demo playback yet.
return true;
}
// Let the demo player end demo playback
return false;
}
void CReplayPerformanceEditorPanel::AddSetViewEvent()
{
if ( !g_pReplayManager->GetPlayingReplay() )
return;
if ( !g_pReplayPerformanceController )
return;
Vector pos;
QAngle angles;
float fov;
ReplayCamera()->GetCachedView( pos, angles, fov );
SetViewParams_t params;
params.m_flTime = GetPlaybackTime();
params.m_flFov = fov;
params.m_pOrigin = &pos;
params.m_pAngles = &angles;
params.m_flAccel = ReplayCamera()->m_flRoamingAccel;
params.m_flSpeed = ReplayCamera()->m_flRoamingSpeed;
params.m_flRotationFilter = ReplayCamera()->m_flRoamingRotFilterFactor;
g_pReplayPerformanceController->AddEvent_Camera_SetView( params );
}
// Input should be in [0,1]
void CReplayPerformanceEditorPanel::AddTimeScaleEvent( float flTimeScale )
{
if ( !g_pReplayManager->GetPlayingReplay() )
return;
if ( !g_pReplayPerformanceController )
return;
g_pReplayPerformanceController->AddEvent_TimeScale( GetPlaybackTime(), flTimeScale );
}
void CReplayPerformanceEditorPanel::UpdateCameraButtonImages( bool bForceUnselected/*=false*/ )
{
CReplayPerformance *pPerformance = GetPerformance();
for ( int i = 0; i < NCAMS; ++i )
{
CFmtStr fmtFile(
gs_pBaseComponentNames[i],
gs_pCamNames[i],
( !bForceUnselected && ( !pPerformance || g_pReplayPerformanceController->IsRecording() ) && i == m_iCameraSelection ) ? "_selected" : ""
);
if ( m_pCameraButtons[ i ] )
{
m_pCameraButtons[ i ]->SetSubImage( fmtFile.Access() );
}
}
}
void CReplayPerformanceEditorPanel::EnsureRecording( bool bShouldSnip )
{
// Not recording?
if ( !g_pReplayPerformanceController->IsRecording() )
{
// Start recording - snip if needed.
g_pReplayPerformanceController->StartRecording( GetReplay(), bShouldSnip );
}
}
void CReplayPerformanceEditorPanel::ToggleMenu()
{
if ( !m_pMenu )
return;
// Show/hide
const bool bShow = !m_pMenu->IsVisible();
m_pMenu->SetVisible( bShow );
}
void CReplayPerformanceEditorPanel::SaveAs( const wchar_t *pTitle )
{
if ( !g_pReplayPerformanceController->SaveAsAsync( pTitle ) )
{
DisplaySavedTip( false );
}
ShowSavingDialog();
}
/*static*/ void CReplayPerformanceEditorPanel::OnConfirmSaveAs( bool bShouldSave, wchar_t *pTitle, void *pContext )
{
// NOTE: Assumes that overwriting has already been confirmed by the user.
if ( !bShouldSave )
return;
CReplayPerformanceEditorPanel *pThis = (CReplayPerformanceEditorPanel *)pContext;
pThis->SaveAs( pTitle );
surface()->PlaySound( "replay\\saved_take.wav" );
}
void CReplayPerformanceEditorPanel::ShowRewindConfirmMessage()
{
ShowMessageBox( "#Replay_RewindWarningTitle", "#Replay_RewindWarningMsg", "#GameUI_OK", OnConfirmRewind, NULL, (void *)this );
surface()->PlaySound( "replay\\replaydialog_warn.wav" );
}
/*static*/ void CReplayPerformanceEditorPanel::OnConfirmRewind( bool bConfirmed, void *pContext )
{
if ( bConfirmed )
{
if ( pContext )
{
CReplayPerformanceEditorPanel *pEditor = (CReplayPerformanceEditorPanel *)pContext;
pEditor->OnCommand( "goto_back" );
}
}
}
void CReplayPerformanceEditorPanel::OnMenuCommand_Save( bool bExitEditorWhenDone/*=false*/ )
{
// If this is the first time we're saving this performance, do a save-as.
if ( !g_pReplayPerformanceController->HasSavedPerformance() )
{
OnMenuCommand_SaveAs( bExitEditorWhenDone );
return;
}
// Regular save
if ( !g_pReplayPerformanceController->SaveAsync() )
{
DisplaySavedTip( false );
}
// Show saving dialog
ShowSavingDialog();
// Exit editor?
if ( bExitEditorWhenDone )
{
OnMenuCommand_Exit();
}
}
void CReplayPerformanceEditorPanel::OnMenuCommand_SaveAs( bool bExitEditorWhenDone/*=false*/ )
{
ReplayUI_ShowPerformanceSaveDlg( OnConfirmSaveAs, this, GetReplay(), bExitEditorWhenDone );
}
void CReplayPerformanceEditorPanel::DisplaySavedTip( bool bSucceess )
{
DisplayPerformanceTip( bSucceess ? "#Replay_PerfTip_Saved" : "#Replay_PerfTip_SaveFailed" );
}
void CReplayPerformanceEditorPanel::OnSaveComplete()
{
DisplaySavedTip( g_pReplayPerformanceController->GetLastSaveStatus() );
m_pSavingDlg = NULL;
}
void CReplayPerformanceEditorPanel::HandleUiToggle()
{
if ( !TFModalStack()->IsEmpty() )
return;
PauseDemo();
Exit_ShowDialogs();
}
void CReplayPerformanceEditorPanel::Exit()
{
engine->ClientCmd_Unrestricted( "disconnect" );
}
void CReplayPerformanceEditorPanel::Exit_ShowDialogs()
{
if ( g_pReplayPerformanceController->IsDirty() )
{
ShowConfirmDialog( "#Replay_DiscardTitle", "#Replay_DiscardChanges", "#Replay_Discard", "#Replay_Cancel", OnConfirmDiscard, NULL, this, REPLAY_SOUND_DIALOG_POPUP );
}
else
{
ShowConfirmDialog( "#Replay_ExitEditorTitle", "#Replay_BackToReplays", "#GameUI_Confirm", "#Replay_Cancel", OnConfirmExit, NULL, this, REPLAY_SOUND_DIALOG_POPUP );
}
}
void CReplayPerformanceEditorPanel::OnMenuCommand_Exit()
{
Exit_ShowDialogs();
}
void CReplayPerformanceEditorPanel::OnCommand( const char *command )
{
float flCurTime = GetPlaybackTime();
g_bIsReplayRewinding = false;
if ( !V_stricmp( command, "toggle_menu" ) )
{
ToggleMenu();
}
else if ( !V_strnicmp( command, "menu_", 5 ) )
{
const char *pMenuCommand = command + 5;
if ( !V_stricmp( pMenuCommand, "save" ) )
{
OnMenuCommand_Save();
}
else if ( !V_stricmp( pMenuCommand, "saveas" ) )
{
OnMenuCommand_SaveAs();
}
else if ( !V_stricmp( pMenuCommand, "exit" ) )
{
OnMenuCommand_Exit();
}
}
else if ( !V_stricmp( command, "close" ) )
{
ShowPanel( false );
MarkForDeletion();
return;
}
else if ( !V_stricmp( command, "play" ) )
{
ShowPanel( false );
return;
}
else if ( !V_stricmp( command, "pause" ) )
{
ShowPanel( true );
return;
}
else if ( !V_strnicmp( command, "timescale_", 10 ) )
{
const char *pTimeScaleCmd = command + 10;
if ( !V_stricmp( pTimeScaleCmd, "showpanel" ) )
{
// If we're playing back, pop up a dialog asking if the user is sure they want to nuke the
// rest of whatever is playing back.
if ( !OnStateChangeRequested( command ) )
return;
EnsureRecording();
}
}
else if ( !V_strnicmp( command, "settick_", 8 ) )
{
const char *pSetType = command + 8;
const int nCurTick = engine->GetDemoPlaybackTick();
if ( !V_stricmp( pSetType, "in" ) )
{
SetOrRemoveInTick( nCurTick, true );
}
else if ( !V_stricmp( pSetType, "out" ) )
{
SetOrRemoveOutTick( nCurTick, true );
}
// Save the replay
CReplay *pReplay = GetReplay();
if ( pReplay )
{
g_pReplayManager->FlagReplayForFlush( pReplay, true );
}
return;
}
else if ( !V_strnicmp( command, "goto_", 5 ) )
{
const char *pGotoType = command + 5;
CReplay *pReplay = GetReplay();
if ( pReplay )
{
const CReplayPerformance *pScratchPerformance = g_pReplayPerformanceController->GetPerformance();
const CReplayPerformance *pSavedPerformance = g_pReplayPerformanceController->GetSavedPerformance();
const CReplayPerformance *pPerformance = pScratchPerformance ? pScratchPerformance : pSavedPerformance;
const int nCurTick = engine->GetDemoPlaybackTick();
// If in or out ticks are set in the performance, use those for the 'full' rewind/fast-forward
const int nStartTick = MAX( 0, ( pPerformance && pPerformance->HasInTick() ) ? pPerformance->m_nTickIn : pReplay->m_nSpawnTick );
const int nEndTick = MAX( // The MAX() here will keep us from going back in time if we're already past the "end" tick
nCurTick,
( ( pPerformance && pPerformance->HasOutTick() ) ?
pPerformance->m_nTickOut :
( nStartTick + TIME_TO_TICKS( pReplay->m_flLength ) ) )
- TIME_TO_TICKS( 0.1f )
);
int nGotoTick = 0;
bool bGoingBack = false;
if ( !V_stricmp( pGotoType, "start" ) )
{
bGoingBack = true;
nGotoTick = nStartTick;
}
else if ( !V_stricmp( pGotoType, "back" ) )
{
// If this is the first time rewinding, display a message
if ( !replay_replayeditor_rewindmsgcounter.GetBool() )
{
replay_replayeditor_rewindmsgcounter.SetValue( 1 );
ShowRewindConfirmMessage();
return;
}
bGoingBack = true;
nGotoTick = nCurTick - TIME_TO_TICKS( 10.0f );
}
else if ( !V_stricmp( pGotoType, "end" ) )
{
nGotoTick = nEndTick; // Don't go back in time
}
// Clamp it
nGotoTick = clamp( nGotoTick, nStartTick, nEndTick );
// If going back...
if ( bGoingBack )
{
// ...and notify the recorder that we're skipping, which we only need to do if we're going backwards
g_pReplayPerformanceController->NotifyRewinding();
g_bIsReplayRewinding = true;
}
// Go to the given tick and pause
CFmtStr fmtCmd( "demo_gototick %i\ndemo_pause\n", nGotoTick );
engine->ClientCmd_Unrestricted( fmtCmd.Access() );
}
return;
}
else if ( !V_strnicmp( command, "setcamera_", 10 ) )
{
const char *pCamType = command + 10;
int nEntIndex = ReplayCamera()->GetPrimaryTargetIndex();
// If we're playing back, pop up a dialog asking if the user is sure they want to nuke the
// rest of whatever is playing back.
if ( !OnStateChangeRequested( command ) )
return;
EnsureRecording();
if ( !V_stricmp( pCamType, "first" ) )
{
ReplayCamera()->SetMode( OBS_MODE_IN_EYE );
UpdateCameraSelectionPosition( CAM_FIRST );
g_pReplayPerformanceController->AddEvent_Camera_Change_FirstPerson( flCurTime, nEntIndex );
}
else if ( !V_stricmp( pCamType, "third" ) )
{
ReplayCamera()->SetMode( OBS_MODE_CHASE );
UpdateCameraSelectionPosition( CAM_THIRD );
g_pReplayPerformanceController->AddEvent_Camera_Change_ThirdPerson( flCurTime, nEntIndex );
AddSetViewEvent();
}
else if ( !V_stricmp( pCamType, "free" ) )
{
ReplayCamera()->SetMode( OBS_MODE_ROAMING );
UpdateCameraSelectionPosition( CAM_FREE );
g_pReplayPerformanceController->AddEvent_Camera_Change_Free( flCurTime );
AddSetViewEvent();
DisplayPerformanceTip( "#Replay_PerfTip_EnterFreeCam", &replay_perftip_count_freecam_enter, MAX_TIP_DISPLAYS );
}
return;
}
else
{
engine->ClientCmd( const_cast<char *>( command ) );
return;
}
BaseClass::OnCommand( command );
}
void CReplayPerformanceEditorPanel::OnConfirmDestroyChanges( bool bConfirmed, void *pContext )
{
AssertMsg( pContext, "Should have a context! Fix me!" );
if ( pContext && bConfirmed )
{
CReplayPerformanceEditorPanel *pEditorPanel = (CReplayPerformanceEditorPanel *)pContext;
if ( bConfirmed )
{
CReplay *pReplay = pEditorPanel->GetReplay();
g_pReplayPerformanceController->StartRecording( pReplay, true );
// Reissue the command.
pEditorPanel->OnCommand( pEditorPanel->m_szSuspendedEvent );
// Play a sound
surface()->PlaySound( "replay\\snip.wav" );
}
// Clear suspended event
pEditorPanel->m_szSuspendedEvent[ 0 ] = '\0';
// Make sure mouse is free
pEditorPanel->SetMouseInputEnabled( true );
DisplayPerformanceTip( "#Replay_PerfTip_Snip" );
}
}
/*static*/ void CReplayPerformanceEditorPanel::OnConfirmDiscard( bool bConfirmed, void *pContext )
{
CReplayPerformanceEditorPanel *pEditor = (CReplayPerformanceEditorPanel *)pContext;
if ( bConfirmed )
{
pEditor->Exit();
}
else
{
if ( !pEditor->IsVisible() )
{
PlayDemo();
}
}
}
/*static*/ void CReplayPerformanceEditorPanel::OnConfirmExit( bool bConfirmed, void *pContext )
{
CReplayPerformanceEditorPanel *pEditor = (CReplayPerformanceEditorPanel *)pContext;
if ( bConfirmed )
{
pEditor->Exit();
}
else
{
if ( !pEditor->IsVisible() )
{
PlayDemo();
}
}
}
void CReplayPerformanceEditorPanel::SetOrRemoveInTick( int nTick, bool bRemoveIfSet )
{
SetOrRemoveTick( nTick, true, bRemoveIfSet );
}
void CReplayPerformanceEditorPanel::SetOrRemoveOutTick( int nTick, bool bRemoveIfSet )
{
SetOrRemoveTick( nTick, false, bRemoveIfSet );
}
void CReplayPerformanceEditorPanel::SetOrRemoveTick( int nTick, bool bUseInTick, bool bRemoveIfSet )
{
CReplayPerformance *pPerformance = GetPerformance();
AssertMsg( pPerformance, "Performance should always be valid by this point." );
ControlButtons_t iButton;
int *pResultTick;
const char *pSetTickKey;
const char *pUnsetTickKey;
if ( bUseInTick )
{
pResultTick = &pPerformance->m_nTickIn;
iButton = CTRLBUTTON_IN;
pSetTickKey = "#Replay_PerfTip_InPointSet";
pUnsetTickKey = "#Replay_PerfTip_InPointRemoved";
}
else
{
pResultTick = &pPerformance->m_nTickOut;
iButton = CTRLBUTTON_OUT;
pSetTickKey = "#Replay_PerfTip_OutPointSet";
pUnsetTickKey = "#Replay_PerfTip_OutPointRemoved";
}
// Tick explicitly being removed? Caller passing in -1?
const bool bRemoving = nTick < 0;
// If tick already exists and we want to remove, remove it
bool bSetting;
if ( ( *pResultTick >= 0 && bRemoveIfSet ) || bRemoving )
{
*pResultTick = -1;
bSetting = false;
}
else
{
*pResultTick = nTick;
bSetting = true;
}
// Display the appropriate tip
DisplayPerformanceTip( bSetting ? pSetTickKey : pUnsetTickKey );
// Select/unselect button
CExImageButton *pButton = m_pCtrlButtons[ iButton ];
pButton->SetSelected( bSetting );
pButton->InvalidateLayout( true, true ); // Without this, buttons don't update immediately
// Mark the performance as dirty
g_pReplayPerformanceController->NotifyDirty();
}
CReplay *CReplayPerformanceEditorPanel::GetReplay()
{
return g_pReplayManager->GetReplay( m_hReplay );
}
void CReplayPerformanceEditorPanel::OnRewindComplete()
{
// Get rid of any "selected" icon - this will happen as soon as we actually start playing back
// events, but if we aren't playing back events yet we need to explicitly tell the icons not
// to display their "selected" versions.
UpdateCameraButtonImages( true );
}
//-----------------------------------------------------------------------------
static DHANDLE<CReplayPerformanceEditorPanel> g_ReplayPerformanceEditorPanel;
//-----------------------------------------------------------------------------
CReplayPerformanceEditorPanel *ReplayUI_InitPerformanceEditor( ReplayHandle_t hReplay )
{
if ( !g_ReplayPerformanceEditorPanel.Get() )
{
g_ReplayPerformanceEditorPanel = SETUP_PANEL( new CReplayPerformanceEditorPanel( NULL, hReplay ) );
g_ReplayPerformanceEditorPanel->InvalidateLayout( false, true );
}
// Notify recorder of editor
g_pReplayPerformanceController->SetEditor( g_ReplayPerformanceEditorPanel.Get() );
return g_ReplayPerformanceEditorPanel;
}
void ReplayUI_ClosePerformanceEditor()
{
if ( g_ReplayPerformanceEditorPanel )
{
g_ReplayPerformanceEditorPanel->MarkForDeletion();
g_ReplayPerformanceEditorPanel = NULL;
}
}
CReplayPerformanceEditorPanel *ReplayUI_GetPerformanceEditor()
{
return g_ReplayPerformanceEditorPanel;
}
#if _DEBUG
CON_COMMAND_F( replay_showperfeditor, "Show performance editor", FCVAR_CLIENTDLL )
{
ReplayUI_ClosePerformanceEditor();
ReplayUI_InitPerformanceEditor( REPLAY_HANDLE_INVALID );
}
CON_COMMAND_F( replay_tiptest, "", FCVAR_CLIENTDLL )
{
DisplayPerformanceTip( "#Replay_PerfTip_EnterFreeCam" );
}
#endif
#endif
| [
"joe@valvesoftware.com"
] | joe@valvesoftware.com |
7ac0e19fdd3fdfc3cb2cedce6d8faea69888ebc9 | 1d26a2a5761a36279c293403a839536b6de911b7 | /Crow/src/Crow/graphics/PostEffect.h | c4fca591c8e138601618a99709ec07689fdfa42c | [
"Apache-2.0"
] | permissive | quesswho/Crow | 919f97a1ff6a2d5da1d27c774c7a50672ad9ba01 | c57df8fe6dc323acd2c5e7b14b0b65d34b4a6e94 | refs/heads/master | 2020-07-09T17:23:37.081282 | 2020-05-02T22:22:23 | 2020-05-02T22:22:23 | 204,032,891 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 353 | h | #pragma once
#include "Crow/Common.h"
#ifdef CROW_OGL
#include "Platform/GraphicAPI/OpenGL/OpenGLPostEffect.h"
namespace Crow { typedef Crow::Platform::OpenGLPostEffect PostEffect; }
#elif defined(CROW_DX11)
#include "Platform/GraphicAPI/DirectX11/DirectX11PostEffect.h"
namespace Crow { typedef Crow::Platform::DirectX11PostEffect PostEffect; }
#endif | [
"sebastianmiles@live.com"
] | sebastianmiles@live.com |
9e5ee1d56999388207cc1635408e8ebc832b4fbc | 3dccdad4d3ac4091c611b4804b58099b3a72e180 | /examples/mavlink/check_digicam.cpp | 2ddbbd64b5169278b105edd0f8d08abc8d51d03c | [] | no_license | Vigasto/ArduPilot_EXIF_Autogen | 560cd0c97520b6c71bd8e5d49a1502353a698b5b | 579162033b469cb412a319ae899b40f363c21370 | refs/heads/master | 2022-02-01T13:19:54.590553 | 2019-07-24T13:54:44 | 2019-07-24T13:54:44 | 198,368,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,855 | cpp | #include <iostream>
#include <string>
#include "serial/serial.h"
#include "serial/impl/unix.h"
#include <common/mavlink.h>
mavlink_status_t status;
mavlink_message_t msg;
int chan = MAVLINK_COMM_1;
uint8_t buffer[MAVLINK_CORE_HEADER_LEN+1];
bool found = false;
int main()
{
serial::Serial port("/dev/ttyACM0",115200,serial::Timeout::simpleTimeout(1000));
if (port.isOpen())
{
std::cout << "Port opened successfully" << std::endl;
while(!found)
{
if (port.available())
{
port.read(buffer, 1);
if (mavlink_parse_char(chan, buffer[0], &msg, &status))
{
switch(msg.msgid)
{
case MAVLINK_MSG_ID_HEARTBEAT:
{
found = true;
std::cout << "Heartbeat found" << std::endl;
}
break;
default:
break;
}
}
}
}
found = false;
mavlink_msg_command_long_pack(0,0,&msg,0,0,MAV_CMD_DO_DIGICAM_CONTROL,0,0,0,0,0,1,0,0);
mavlink_msg_to_send_buffer(buffer, &msg);
if (port.write(buffer,MAVLINK_CORE_HEADER_LEN+1) == MAVLINK_CORE_HEADER_LEN+1)
std::cout << "Command sent" <<std::endl;
else
{
std::cout << "Write error..." << std::endl;
return -1;
}
while(!found)
{
if (port.available())
{
port.read(buffer, 1);
if (mavlink_parse_char(chan, buffer[0], &msg, &status))
{
switch(msg.msgid)
{
case MAVLINK_MSG_ID_COMMAND_LONG:
{
mavlink_command_long_t command;
mavlink_msg_command_long_decode(&msg, &command);
if (command.command == MAV_CMD_DO_DIGICAM_CONTROL)
{
found = true;
std::cout << "Digicam control feedback found" << std::endl;
}
else
{
std::cout << "Other command ID found: " << command.command << std::endl;
}
}
break;
case MAVLINK_MSG_ID_COMMAND_ACK:
{
mavlink_command_ack_t ack;
mavlink_msg_command_ack_decode(&msg, &ack);
if (ack.command == MAV_CMD_DO_DIGICAM_CONTROL)
{
found = true;
std::cout << "Digicam control ack found" << std::endl;
}
else
{
std::cout << "Other ack ID found: " << ack.command << std::endl;
}
}
break;
case MAVLINK_MSG_ID_HEARTBEAT:
{
//std::cout << "Heartbeat still exists..." << std::endl;
}
default:
break;
}
}
}
}
}
else
std::cout << "Port isn't open..." << std::endl;
return 0;
}
| [
"alief.iw@gmail.com"
] | alief.iw@gmail.com |
e6d901eb4ff35bc93cb6a215a163a393158415af | 4e5be3ef225ee54782e4eb6cd6fa79f672ee8501 | /Breakout/SpriteRenderer.h | d80bf95a691f24f6670a74f2e2dc3e6250002f17 | [] | no_license | JiaoJianing/Breakout | 02953b4440866bca6688530f850c54163084bcb0 | 326e33d28c98399dbd46141eee265096e90d5a09 | refs/heads/master | 2021-08-19T22:48:39.961820 | 2021-06-28T06:14:48 | 2021-06-28T06:14:48 | 127,378,215 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 396 | h | #pragma once
#include "Shader.h"
#include "Texture.h"
class SpriteRenderer
{
public:
SpriteRenderer(Shader shader);
~SpriteRenderer();
void DrawSprite(Texture texture, glm::vec2 position, glm::vec2 size = glm::vec2(10, 10),
float rotate = 0.0f, glm::vec3 color = glm::vec3(1.0f));
private:
void initRenderData();
private:
Shader m_Shader;
unsigned int m_VAO;
unsigned int m_VBO;
};
| [
"jiaojn@skong.com"
] | jiaojn@skong.com |
4dad277a1ce31e75afb57222ce63cb351adc9c36 | 7622359e2e4099d24bef9ae0ac83c96ca4ac8da0 | /src/Zipper.cpp | 2886553ccaa0b0b9f70e84e3d42e6daeed91132f | [] | no_license | lingnand/Helium | 23300a13dbef3d0a6ce31db92a1c2e4344374aa3 | d1f8fab6eb5d60e35b3287f6ea35cd1fae71f816 | refs/heads/master | 2023-04-04T10:44:03.009166 | 2021-04-16T01:48:05 | 2021-04-16T01:48:05 | 358,439,449 | 10 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 98 | cpp | /*
* Zipper.cpp
*
* Created on: Jul 28, 2015
* Author: lingnan
*/
#include <Zipper.h>
| [
"lingnan.d@gmail.com"
] | lingnan.d@gmail.com |
6c2cdfb303642a479a0f86c2fa27a9243fd7ae1b | 97480955e513d6dfe3828fd32f01d5b6598d5654 | /Asteroids/include/shoot.hpp | b8594dd2acc15ba1e6e621e3ee99b52cfa8ae0e1 | [] | no_license | GustavoAC/SFML-Practicing | 3834ee351dfaeb918a58f975404ba1eb1afd0c7f | b5d371de9e019ef068e9e25abc50c2f0bea10572 | refs/heads/master | 2021-01-20T19:29:52.009877 | 2016-07-18T02:24:42 | 2016-07-18T02:24:42 | 62,468,355 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 845 | hpp | #ifndef _SHOOT_HPP_
#define _SHOOT_HPP_
#include "entity.hpp"
#include "player.hpp"
#include "saucer.hpp"
#include "collision.hpp"
class Shoot : public Entity {
public:
Shoot(const Shoot&) = delete;
Shoot& operator=(const Shoot&) = delete;
using Entity::Entity;
virtual void update(sf::Time deltaTime);
protected:
sf::Time _duration;
};
class ShootPlayer : public Shoot {
public:
ShootPlayer(const ShootPlayer&) = delete;
ShootPlayer& operator=(const ShootPlayer&) = delete;
ShootPlayer(Player& from);
virtual bool isCollide(const Entity& other)const;
};
class ShootSaucer : public Shoot {
public:
ShootSaucer(const ShootSaucer&) = delete;
ShootSaucer& operator=(const ShootSaucer&) = delete;
ShootSaucer(Saucer& from);
virtual bool isCollide(const Entity& other)const;
};
#endif
| [
"guga.a.carvalho@gmail.com"
] | guga.a.carvalho@gmail.com |
281666764fdb913a17a4dab17d315c5dc3e8d7d6 | 2bca246e73ef16f30a522e6b70e4a4394b6d881b | /QtGUI/include/ENavigatorWindow.h | 1857db9849abb2c74ee00084be721afc92110c30 | [
"MIT"
] | permissive | lulzzz/ESsistMe | 8968558fd2814f970b701441b0d794c655bf30ce | 936cf32032b79212d8116125ebb81c79c0892558 | refs/heads/master | 2021-04-18T18:48:01.031766 | 2017-02-03T04:40:21 | 2017-02-03T04:40:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 546 | h | #ifndef ESsistMe_NAVIGATORWINDOW_H
#define ESsistMe_NAVIGATORWINDOW_H
#include <QMainWindow>
#include "qcustomplot.h"
#include "ESsistMe_mainwindow.h"
class ESsistMe_MainWindow;
class ESsistMe_NavigatorWindow : public QCustomPlot
{
Q_OBJECT
public:
explicit ESsistMe_NavigatorWindow( QWidget *parent);
~ESsistMe_NavigatorWindow();
void setupSincScatterDemo(QCustomPlot *customPlot);
public slots:
void setLupe(const QCPRange &range);
private:
// QCustomPlot* navigatorPlot;
};
#endif // ESsistMe_NAVIGATORWINDOW_H
| [
"Vegh.Janos@gmail.com"
] | Vegh.Janos@gmail.com |
7c898ade271b55403460f8074caf3ea656cd520f | 557c28eb91e5021c8e5e41a87513af8980b69c70 | /cpp/06/doorbell_pnp.cpp | 17c56ad3ae77d066b86719a376c261cdd254ca88 | [] | no_license | TimelikeClosure/freenove_pi_prototypes | 3f40f4dfb0ef2f2873ceb06c0aad4c80a822c3db | f1237b29a1e93659e37909d8f21c55e976ba1786 | refs/heads/master | 2020-03-28T18:21:44.945800 | 2018-10-09T14:51:22 | 2018-10-09T14:51:22 | 148,874,972 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 443 | cpp | #include <wiringPi.h>
#include <iostream>
#define buzzerPin 0
#define buttonPin 1
int main(void){
if (wiringPiSetup() == -1){
std::cout << "setup wiringPi failed." << std::endl;
return 1;
}
pinMode(buzzerPin, OUTPUT);
pinMode(buttonPin, INPUT);
pullUpDnControl(buttonPin, PUD_UP);
while(1){
if (digitalRead(buttonPin) == LOW){
digitalWrite(buzzerPin, LOW);
} else {
digitalWrite(buzzerPin, HIGH);
}
}
return 0;
}
| [
"TimelikeClosure@users.noreply.github.com"
] | TimelikeClosure@users.noreply.github.com |
fc5685b35be79690f5f5ef46186d878e59551e69 | 314ee4489eb7edfb386663ec34ec700dcca9b7e3 | /src/qt/paymentserver.cpp | c394790b652121bc513d3f4ff9e1be8ae3a520ca | [
"MIT"
] | permissive | OurEarthCoin/OECoin | 5195b739ccde61663b8e84606c98a63618ef8831 | 0bba6003c381b1b04a79077bd4c9fe2996afe36b | refs/heads/master | 2022-09-03T13:52:22.836845 | 2020-05-27T10:41:52 | 2020-05-27T10:41:52 | 267,262,680 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,090 | cpp | // Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "paymentserver.h"
#include "bitcoinunits.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "base58.h"
#include "chainparams.h"
#include "policy/policy.h"
#include "ui_interface.h"
#include "util.h"
#include "wallet/wallet.h"
#include <cstdlib>
#include <openssl/x509_vfy.h>
#include <QApplication>
#include <QByteArray>
#include <QDataStream>
#include <QDateTime>
#include <QDebug>
#include <QFile>
#include <QFileOpenEvent>
#include <QHash>
#include <QList>
#include <QLocalServer>
#include <QLocalSocket>
#include <QNetworkAccessManager>
#include <QNetworkProxy>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QSslCertificate>
#include <QSslError>
#include <QSslSocket>
#include <QStringList>
#include <QTextDocument>
#if QT_VERSION < 0x050000
#include <QUrl>
#else
#include <QUrlQuery>
#endif
const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds
const QString BITCOIN_IPC_PREFIX("ourearth:");
// BIP70 payment protocol messages
const char* BIP70_MESSAGE_PAYMENTACK = "PaymentACK";
const char* BIP70_MESSAGE_PAYMENTREQUEST = "PaymentRequest";
// BIP71 payment protocol media types
const char* BIP71_MIMETYPE_PAYMENT = "application/ourearth-payment";
const char* BIP71_MIMETYPE_PAYMENTACK = "application/ourearth-paymentack";
const char* BIP71_MIMETYPE_PAYMENTREQUEST = "application/ourearth-paymentrequest";
struct X509StoreDeleter {
void operator()(X509_STORE* b) {
X509_STORE_free(b);
}
};
struct X509Deleter {
void operator()(X509* b) { X509_free(b); }
};
namespace // Anon namespace
{
std::unique_ptr<X509_STORE, X509StoreDeleter> certStore;
}
//
// Create a name that is unique for:
// testnet / non-testnet
// data directory
//
static QString ipcServerName()
{
QString name("OurearthQt");
// Append a simple hash of the datadir
// Note that GetDataDir(true) returns a different path
// for -testnet versus main net
QString ddir(GUIUtil::boostPathToQString(GetDataDir(true)));
name.append(QString::number(qHash(ddir)));
return name;
}
//
// We store payment URIs and requests received before
// the main GUI window is up and ready to ask the user
// to send payment.
static QList<QString> savedPaymentRequests;
static void ReportInvalidCertificate(const QSslCertificate& cert)
{
#if QT_VERSION < 0x050000
qDebug() << QString("%1: Payment server found an invalid certificate: ").arg(__func__) << cert.serialNumber() << cert.subjectInfo(QSslCertificate::CommonName) << cert.subjectInfo(QSslCertificate::OrganizationalUnitName);
#else
qDebug() << QString("%1: Payment server found an invalid certificate: ").arg(__func__) << cert.serialNumber() << cert.subjectInfo(QSslCertificate::CommonName) << cert.subjectInfo(QSslCertificate::DistinguishedNameQualifier) << cert.subjectInfo(QSslCertificate::OrganizationalUnitName);
#endif
}
//
// Load OpenSSL's list of root certificate authorities
//
void PaymentServer::LoadRootCAs(X509_STORE* _store)
{
// Unit tests mostly use this, to pass in fake root CAs:
if (_store)
{
certStore.reset(_store);
return;
}
// Normal execution, use either -rootcertificates or system certs:
certStore.reset(X509_STORE_new());
// Note: use "-system-" default here so that users can pass -rootcertificates=""
// and get 'I don't like X.509 certificates, don't trust anybody' behavior:
QString certFile = QString::fromStdString(gArgs.GetArg("-rootcertificates", "-system-"));
// Empty store
if (certFile.isEmpty()) {
qDebug() << QString("PaymentServer::%1: Payment request authentication via X.509 certificates disabled.").arg(__func__);
return;
}
QList<QSslCertificate> certList;
if (certFile != "-system-") {
qDebug() << QString("PaymentServer::%1: Using \"%2\" as trusted root certificate.").arg(__func__).arg(certFile);
certList = QSslCertificate::fromPath(certFile);
// Use those certificates when fetching payment requests, too:
QSslSocket::setDefaultCaCertificates(certList);
} else
certList = QSslSocket::systemCaCertificates();
int nRootCerts = 0;
const QDateTime currentTime = QDateTime::currentDateTime();
for (const QSslCertificate& cert : certList) {
// Don't log NULL certificates
if (cert.isNull())
continue;
// Not yet active/valid, or expired certificate
if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate()) {
ReportInvalidCertificate(cert);
continue;
}
#if QT_VERSION >= 0x050000
// Blacklisted certificate
if (cert.isBlacklisted()) {
ReportInvalidCertificate(cert);
continue;
}
#endif
QByteArray certData = cert.toDer();
const unsigned char *data = (const unsigned char *)certData.data();
std::unique_ptr<X509, X509Deleter> x509(d2i_X509(0, &data, certData.size()));
if (x509 && X509_STORE_add_cert(certStore.get(), x509.get()))
{
// Note: X509_STORE increases the reference count to the X509 object,
// we still have to release our reference to it.
++nRootCerts;
}
else
{
ReportInvalidCertificate(cert);
continue;
}
}
qWarning() << "PaymentServer::LoadRootCAs: Loaded " << nRootCerts << " root certificates";
// Project for another day:
// Fetch certificate revocation lists, and add them to certStore.
// Issues to consider:
// performance (start a thread to fetch in background?)
// privacy (fetch through tor/proxy so IP address isn't revealed)
// would it be easier to just use a compiled-in blacklist?
// or use Qt's blacklist?
// "certificate stapling" with server-side caching is more efficient
}
//
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
//
// Warning: ipcSendCommandLine() is called early in init,
// so don't use "Q_EMIT message()", but "QMessageBox::"!
//
void PaymentServer::ipcParseCommandLine(int argc, char* argv[])
{
for (int i = 1; i < argc; i++)
{
QString arg(argv[i]);
if (arg.startsWith("-"))
continue;
// If the bitcoin: URI contains a payment request, we are not able to detect the
// network as that would require fetching and parsing the payment request.
// That means clicking such an URI which contains a testnet payment request
// will start a mainnet instance and throw a "wrong network" error.
if (arg.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // bitcoin: URI
{
savedPaymentRequests.append(arg);
SendCoinsRecipient r;
if (GUIUtil::parseBitcoinURI(arg, &r) && !r.address.isEmpty())
{
CBitcoinAddress address(r.address.toStdString());
auto tempChainParams = CreateChainParams(CBaseChainParams::MAIN);
if (address.IsValid(*tempChainParams))
{
SelectParams(CBaseChainParams::MAIN);
}
else {
tempChainParams = CreateChainParams(CBaseChainParams::TESTNET);
if (address.IsValid(*tempChainParams))
SelectParams(CBaseChainParams::TESTNET);
}
}
}
else if (QFile::exists(arg)) // Filename
{
savedPaymentRequests.append(arg);
PaymentRequestPlus request;
if (readPaymentRequestFromFile(arg, request))
{
if (request.getDetails().network() == "main")
{
SelectParams(CBaseChainParams::MAIN);
}
else if (request.getDetails().network() == "test")
{
SelectParams(CBaseChainParams::TESTNET);
}
}
}
else
{
// Printing to debug.log is about the best we can do here, the
// GUI hasn't started yet so we can't pop up a message box.
qWarning() << "PaymentServer::ipcSendCommandLine: Payment request file does not exist: " << arg;
}
}
}
//
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
//
bool PaymentServer::ipcSendCommandLine()
{
bool fResult = false;
for (const QString& r : savedPaymentRequests)
{
QLocalSocket* socket = new QLocalSocket();
socket->connectToServer(ipcServerName(), QIODevice::WriteOnly);
if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT))
{
delete socket;
socket = nullptr;
return false;
}
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << r;
out.device()->seek(0);
socket->write(block);
socket->flush();
socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT);
socket->disconnectFromServer();
delete socket;
socket = nullptr;
fResult = true;
}
return fResult;
}
PaymentServer::PaymentServer(QObject* parent, bool startLocalServer) :
QObject(parent),
saveURIs(true),
uriServer(0),
netManager(0),
optionsModel(0)
{
// Verify that the version of the library that we linked against is
// compatible with the version of the headers we compiled against.
GOOGLE_PROTOBUF_VERIFY_VERSION;
// Install global event filter to catch QFileOpenEvents
// on Mac: sent when you click bitcoin: links
// other OSes: helpful when dealing with payment request files
if (parent)
parent->installEventFilter(this);
QString name = ipcServerName();
// Clean up old socket leftover from a crash:
QLocalServer::removeServer(name);
if (startLocalServer)
{
uriServer = new QLocalServer(this);
if (!uriServer->listen(name)) {
// constructor is called early in init, so don't use "Q_EMIT message()" here
QMessageBox::critical(0, tr("Payment request error"),
tr("Cannot start ourearth: click-to-pay handler"));
}
else {
connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection()));
connect(this, SIGNAL(receivedPaymentACK(QString)), this, SLOT(handlePaymentACK(QString)));
}
}
}
PaymentServer::~PaymentServer()
{
google::protobuf::ShutdownProtobufLibrary();
}
//
// OSX-specific way of handling bitcoin: URIs and PaymentRequest mime types.
// Also used by paymentservertests.cpp and when opening a payment request file
// via "Open URI..." menu entry.
//
bool PaymentServer::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::FileOpen) {
QFileOpenEvent *fileEvent = static_cast<QFileOpenEvent*>(event);
if (!fileEvent->file().isEmpty())
handleURIOrFile(fileEvent->file());
else if (!fileEvent->url().isEmpty())
handleURIOrFile(fileEvent->url().toString());
return true;
}
return QObject::eventFilter(object, event);
}
void PaymentServer::initNetManager()
{
if (!optionsModel)
return;
if (netManager != nullptr)
delete netManager;
// netManager is used to fetch paymentrequests given in bitcoin: URIs
netManager = new QNetworkAccessManager(this);
QNetworkProxy proxy;
// Query active SOCKS5 proxy
if (optionsModel->getProxySettings(proxy)) {
netManager->setProxy(proxy);
qDebug() << "PaymentServer::initNetManager: Using SOCKS5 proxy" << proxy.hostName() << ":" << proxy.port();
}
else
qDebug() << "PaymentServer::initNetManager: No active proxy server found.";
connect(netManager, SIGNAL(finished(QNetworkReply*)),
this, SLOT(netRequestFinished(QNetworkReply*)));
connect(netManager, SIGNAL(sslErrors(QNetworkReply*, const QList<QSslError> &)),
this, SLOT(reportSslErrors(QNetworkReply*, const QList<QSslError> &)));
}
void PaymentServer::uiReady()
{
initNetManager();
saveURIs = false;
for (const QString& s : savedPaymentRequests)
{
handleURIOrFile(s);
}
savedPaymentRequests.clear();
}
void PaymentServer::handleURIOrFile(const QString& s)
{
if (saveURIs)
{
savedPaymentRequests.append(s);
return;
}
if (s.startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive)) // bitcoin: URI
{
#if QT_VERSION < 0x050000
QUrl uri(s);
#else
QUrlQuery uri((QUrl(s)));
#endif
if (uri.hasQueryItem("r")) // payment request URI
{
QByteArray temp;
temp.append(uri.queryItemValue("r"));
QString decoded = QUrl::fromPercentEncoding(temp);
QUrl fetchUrl(decoded, QUrl::StrictMode);
if (fetchUrl.isValid())
{
qDebug() << "PaymentServer::handleURIOrFile: fetchRequest(" << fetchUrl << ")";
fetchRequest(fetchUrl);
}
else
{
qWarning() << "PaymentServer::handleURIOrFile: Invalid URL: " << fetchUrl;
Q_EMIT message(tr("URI handling"),
tr("Payment request fetch URL is invalid: %1").arg(fetchUrl.toString()),
CClientUIInterface::ICON_WARNING);
}
return;
}
else // normal URI
{
SendCoinsRecipient recipient;
if (GUIUtil::parseBitcoinURI(s, &recipient))
{
CBitcoinAddress address(recipient.address.toStdString());
if (!address.IsValid()) {
Q_EMIT message(tr("URI handling"), tr("Invalid payment address %1").arg(recipient.address),
CClientUIInterface::MSG_ERROR);
}
else
Q_EMIT receivedPaymentRequest(recipient);
}
else
Q_EMIT message(tr("URI handling"),
tr("URI cannot be parsed! This can be caused by an invalid Ourearth address or malformed URI parameters."),
CClientUIInterface::ICON_WARNING);
return;
}
}
if (QFile::exists(s)) // payment request file
{
PaymentRequestPlus request;
SendCoinsRecipient recipient;
if (!readPaymentRequestFromFile(s, request))
{
Q_EMIT message(tr("Payment request file handling"),
tr("Payment request file cannot be read! This can be caused by an invalid payment request file."),
CClientUIInterface::ICON_WARNING);
}
else if (processPaymentRequest(request, recipient))
Q_EMIT receivedPaymentRequest(recipient);
return;
}
}
void PaymentServer::handleURIConnection()
{
QLocalSocket *clientConnection = uriServer->nextPendingConnection();
while (clientConnection->bytesAvailable() < (int)sizeof(quint32))
clientConnection->waitForReadyRead();
connect(clientConnection, SIGNAL(disconnected()),
clientConnection, SLOT(deleteLater()));
QDataStream in(clientConnection);
in.setVersion(QDataStream::Qt_4_0);
if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) {
return;
}
QString msg;
in >> msg;
handleURIOrFile(msg);
}
//
// Warning: readPaymentRequestFromFile() is used in ipcSendCommandLine()
// so don't use "Q_EMIT message()", but "QMessageBox::"!
//
bool PaymentServer::readPaymentRequestFromFile(const QString& filename, PaymentRequestPlus& request)
{
QFile f(filename);
if (!f.open(QIODevice::ReadOnly)) {
qWarning() << QString("PaymentServer::%1: Failed to open %2").arg(__func__).arg(filename);
return false;
}
// BIP70 DoS protection
if (!verifySize(f.size())) {
return false;
}
QByteArray data = f.readAll();
return request.parse(data);
}
bool PaymentServer::processPaymentRequest(const PaymentRequestPlus& request, SendCoinsRecipient& recipient)
{
if (!optionsModel)
return false;
if (request.IsInitialized()) {
// Payment request network matches client network?
if (!verifyNetwork(request.getDetails())) {
Q_EMIT message(tr("Payment request rejected"), tr("Payment request network doesn't match client network."),
CClientUIInterface::MSG_ERROR);
return false;
}
// Make sure any payment requests involved are still valid.
// This is re-checked just before sending coins in WalletModel::sendCoins().
if (verifyExpired(request.getDetails())) {
Q_EMIT message(tr("Payment request rejected"), tr("Payment request expired."),
CClientUIInterface::MSG_ERROR);
return false;
}
} else {
Q_EMIT message(tr("Payment request error"), tr("Payment request is not initialized."),
CClientUIInterface::MSG_ERROR);
return false;
}
recipient.paymentRequest = request;
recipient.message = GUIUtil::HtmlEscape(request.getDetails().memo());
request.getMerchant(certStore.get(), recipient.authenticatedMerchant);
QList<std::pair<CScript, CAmount> > sendingTos = request.getPayTo();
QStringList addresses;
for (const std::pair<CScript, CAmount>& sendingTo : sendingTos) {
// Extract and check destination addresses
CTxDestination dest;
if (ExtractDestination(sendingTo.first, dest)) {
// Append destination address
addresses.append(QString::fromStdString(CBitcoinAddress(dest).ToString()));
}
else if (!recipient.authenticatedMerchant.isEmpty()) {
// Unauthenticated payment requests to custom bitcoin addresses are not supported
// (there is no good way to tell the user where they are paying in a way they'd
// have a chance of understanding).
Q_EMIT message(tr("Payment request rejected"),
tr("Unverified payment requests to custom payment scripts are unsupported."),
CClientUIInterface::MSG_ERROR);
return false;
}
// Bitcoin amounts are stored as (optional) uint64 in the protobuf messages (see paymentrequest.proto),
// but CAmount is defined as int64_t. Because of that we need to verify that amounts are in a valid range
// and no overflow has happened.
if (!verifyAmount(sendingTo.second)) {
Q_EMIT message(tr("Payment request rejected"), tr("Invalid payment request."), CClientUIInterface::MSG_ERROR);
return false;
}
// Extract and check amounts
CTxOut txOut(sendingTo.second, sendingTo.first);
if (IsDust(txOut, ::dustRelayFee)) {
Q_EMIT message(tr("Payment request error"), tr("Requested payment amount of %1 is too small (considered dust).")
.arg(BitcoinUnits::formatWithUnit(optionsModel->getDisplayUnit(), sendingTo.second)),
CClientUIInterface::MSG_ERROR);
return false;
}
recipient.amount += sendingTo.second;
// Also verify that the final amount is still in a valid range after adding additional amounts.
if (!verifyAmount(recipient.amount)) {
Q_EMIT message(tr("Payment request rejected"), tr("Invalid payment request."), CClientUIInterface::MSG_ERROR);
return false;
}
}
// Store addresses and format them to fit nicely into the GUI
recipient.address = addresses.join("<br />");
if (!recipient.authenticatedMerchant.isEmpty()) {
qDebug() << "PaymentServer::processPaymentRequest: Secure payment request from " << recipient.authenticatedMerchant;
}
else {
qDebug() << "PaymentServer::processPaymentRequest: Insecure payment request to " << addresses.join(", ");
}
return true;
}
void PaymentServer::fetchRequest(const QUrl& url)
{
QNetworkRequest netRequest;
netRequest.setAttribute(QNetworkRequest::User, BIP70_MESSAGE_PAYMENTREQUEST);
netRequest.setUrl(url);
netRequest.setRawHeader("User-Agent", CLIENT_NAME.c_str());
netRequest.setRawHeader("Accept", BIP71_MIMETYPE_PAYMENTREQUEST);
netManager->get(netRequest);
}
void PaymentServer::fetchPaymentACK(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction)
{
const payments::PaymentDetails& details = recipient.paymentRequest.getDetails();
if (!details.has_payment_url())
return;
QNetworkRequest netRequest;
netRequest.setAttribute(QNetworkRequest::User, BIP70_MESSAGE_PAYMENTACK);
netRequest.setUrl(QString::fromStdString(details.payment_url()));
netRequest.setHeader(QNetworkRequest::ContentTypeHeader, BIP71_MIMETYPE_PAYMENT);
netRequest.setRawHeader("User-Agent", CLIENT_NAME.c_str());
netRequest.setRawHeader("Accept", BIP71_MIMETYPE_PAYMENTACK);
payments::Payment payment;
payment.set_merchant_data(details.merchant_data());
payment.add_transactions(transaction.data(), transaction.size());
// Create a new refund address, or re-use:
QString account = tr("Refund from %1").arg(recipient.authenticatedMerchant);
std::string strAccount = account.toStdString();
std::set<CTxDestination> refundAddresses = wallet->GetAccountAddresses(strAccount);
if (!refundAddresses.empty()) {
CScript s = GetScriptForDestination(*refundAddresses.begin());
payments::Output* refund_to = payment.add_refund_to();
refund_to->set_script(&s[0], s.size());
}
else {
CPubKey newKey;
if (wallet->GetKeyFromPool(newKey)) {
CKeyID keyID = newKey.GetID();
wallet->SetAddressBook(keyID, strAccount, "refund");
CScript s = GetScriptForDestination(keyID);
payments::Output* refund_to = payment.add_refund_to();
refund_to->set_script(&s[0], s.size());
}
else {
// This should never happen, because sending coins should have
// just unlocked the wallet and refilled the keypool.
qWarning() << "PaymentServer::fetchPaymentACK: Error getting refund key, refund_to not set";
}
}
int length = payment.ByteSize();
netRequest.setHeader(QNetworkRequest::ContentLengthHeader, length);
QByteArray serData(length, '\0');
if (payment.SerializeToArray(serData.data(), length)) {
netManager->post(netRequest, serData);
}
else {
// This should never happen, either.
qWarning() << "PaymentServer::fetchPaymentACK: Error serializing payment message";
}
}
void PaymentServer::netRequestFinished(QNetworkReply* reply)
{
reply->deleteLater();
// BIP70 DoS protection
if (!verifySize(reply->size())) {
Q_EMIT message(tr("Payment request rejected"),
tr("Payment request %1 is too large (%2 bytes, allowed %3 bytes).")
.arg(reply->request().url().toString())
.arg(reply->size())
.arg(BIP70_MAX_PAYMENTREQUEST_SIZE),
CClientUIInterface::MSG_ERROR);
return;
}
if (reply->error() != QNetworkReply::NoError) {
QString msg = tr("Error communicating with %1: %2")
.arg(reply->request().url().toString())
.arg(reply->errorString());
qWarning() << "PaymentServer::netRequestFinished: " << msg;
Q_EMIT message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR);
return;
}
QByteArray data = reply->readAll();
QString requestType = reply->request().attribute(QNetworkRequest::User).toString();
if (requestType == BIP70_MESSAGE_PAYMENTREQUEST)
{
PaymentRequestPlus request;
SendCoinsRecipient recipient;
if (!request.parse(data))
{
qWarning() << "PaymentServer::netRequestFinished: Error parsing payment request";
Q_EMIT message(tr("Payment request error"),
tr("Payment request cannot be parsed!"),
CClientUIInterface::MSG_ERROR);
}
else if (processPaymentRequest(request, recipient))
Q_EMIT receivedPaymentRequest(recipient);
return;
}
else if (requestType == BIP70_MESSAGE_PAYMENTACK)
{
payments::PaymentACK paymentACK;
if (!paymentACK.ParseFromArray(data.data(), data.size()))
{
QString msg = tr("Bad response from server %1")
.arg(reply->request().url().toString());
qWarning() << "PaymentServer::netRequestFinished: " << msg;
Q_EMIT message(tr("Payment request error"), msg, CClientUIInterface::MSG_ERROR);
}
else
{
Q_EMIT receivedPaymentACK(GUIUtil::HtmlEscape(paymentACK.memo()));
}
}
}
void PaymentServer::reportSslErrors(QNetworkReply* reply, const QList<QSslError> &errs)
{
Q_UNUSED(reply);
QString errString;
for (const QSslError& err : errs) {
qWarning() << "PaymentServer::reportSslErrors: " << err;
errString += err.errorString() + "\n";
}
Q_EMIT message(tr("Network request error"), errString, CClientUIInterface::MSG_ERROR);
}
void PaymentServer::setOptionsModel(OptionsModel *_optionsModel)
{
this->optionsModel = _optionsModel;
}
void PaymentServer::handlePaymentACK(const QString& paymentACKMsg)
{
// currently we don't further process or store the paymentACK message
Q_EMIT message(tr("Payment acknowledged"), paymentACKMsg, CClientUIInterface::ICON_INFORMATION | CClientUIInterface::MODAL);
}
bool PaymentServer::verifyNetwork(const payments::PaymentDetails& requestDetails)
{
bool fVerified = requestDetails.network() == Params().NetworkIDString();
if (!fVerified) {
qWarning() << QString("PaymentServer::%1: Payment request network \"%2\" doesn't match client network \"%3\".")
.arg(__func__)
.arg(QString::fromStdString(requestDetails.network()))
.arg(QString::fromStdString(Params().NetworkIDString()));
}
return fVerified;
}
bool PaymentServer::verifyExpired(const payments::PaymentDetails& requestDetails)
{
bool fVerified = (requestDetails.has_expires() && (int64_t)requestDetails.expires() < GetTime());
if (fVerified) {
const QString requestExpires = QString::fromStdString(DateTimeStrFormat("%Y-%m-%d %H:%M:%S", (int64_t)requestDetails.expires()));
qWarning() << QString("PaymentServer::%1: Payment request expired \"%2\".")
.arg(__func__)
.arg(requestExpires);
}
return fVerified;
}
bool PaymentServer::verifySize(qint64 requestSize)
{
bool fVerified = (requestSize <= BIP70_MAX_PAYMENTREQUEST_SIZE);
if (!fVerified) {
qWarning() << QString("PaymentServer::%1: Payment request too large (%2 bytes, allowed %3 bytes).")
.arg(__func__)
.arg(requestSize)
.arg(BIP70_MAX_PAYMENTREQUEST_SIZE);
}
return fVerified;
}
bool PaymentServer::verifyAmount(const CAmount& requestAmount)
{
bool fVerified = MoneyRange(requestAmount);
if (!fVerified) {
qWarning() << QString("PaymentServer::%1: Payment request amount out of allowed range (%2, allowed 0 - %3).")
.arg(__func__)
.arg(requestAmount)
.arg(MAX_MONEY);
}
return fVerified;
}
X509_STORE* PaymentServer::getCertStore()
{
return certStore.get();
}
| [
"39472404+goodstardust@users.noreply.github.com"
] | 39472404+goodstardust@users.noreply.github.com |
bdfebba39f394807935d57439ae1cc39285eadd3 | 3d15bc15a50b828c393fcc3564f7f5da692e406a | /include/Util/File.h | fddbebd46864214bb026d0259e979173cdf2665f | [] | no_license | alexvia/Odin | 9b7ed733a2a8cff4925757f73912bd1f3988d33f | b1c28bd6bc34421c709d2a3116bb4634c0cb0fbb | refs/heads/master | 2021-01-09T05:58:10.556886 | 2017-10-12T12:00:35 | 2017-10-12T12:00:35 | 80,854,179 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 170 | h | #pragma once
#include <string>
namespace File
{
std::string Read(const std::string& filename);
void Write(const std::string& filename, const std::string& contents);
} | [
"alexvia.software@gmail.com"
] | alexvia.software@gmail.com |
4a8ad3d633c5b0b04380ce22159a6867d971b05a | d2249116413e870d8bf6cd133ae135bc52021208 | /pks/Common/CIMAGE/SRC/trans.cpp | 58a38b08dd7ef77c166b3f539220d5127baf20df | [] | no_license | Unknow-man/mfc-4 | ecbdd79cc1836767ab4b4ca72734bc4fe9f5a0b5 | b58abf9eb4c6d90ef01b9f1203b174471293dfba | refs/heads/master | 2023-02-17T18:22:09.276673 | 2021-01-20T07:46:14 | 2021-01-20T07:46:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,208 | cpp | // trans.c
//#include <windows.h>
#include <stdafx.h>
// DrawTransparentBitmap - Chris Becke / Raja Segar / Troels K.
static BOOL DrawTransparentHelper(HDC hdcDst, HBITMAP bmpMask,
int xDst , int yDst ,
int cxDst, int cyDst,
HDC hdcImage,
int xSrc , int ySrc ,
int cxSrc, int cySrc
)
{
// We are going to paint the two DDB's in sequence to the destination.
// 1st the monochrome bitmap will be blitted using an AND operation to
// cut a hole in the destination. The color image will then be ORed
// with the destination, filling it into the hole, but leaving the
// surrounding area untouched.
HDC dcMem = CreateCompatibleDC(NULL);
HGDIOBJ old = SelectObject(dcMem, bmpMask);
BOOL bOK = SetStretchBltMode(hdcDst,COLORONCOLOR);
bOK = bOK && StretchBlt(hdcDst, xDst, yDst, cxDst, cyDst, dcMem , xSrc, ySrc, cxSrc, cySrc, SRCAND );
// Now, clean up.
SelectObject(dcMem, old);
DeleteDC(dcMem); dcMem = NULL;
// Also note the use of SRCPAINT rather than SRCCOPY.
// Might fail with 'huge' cxDst/cyDst (Out of storage), if printing.
bOK = bOK && StretchBlt(hdcDst, xDst, yDst, cxDst, cyDst, hdcImage, xSrc, ySrc, cxSrc, cySrc, SRCPAINT);
return bOK;
}
EXTERN_C BOOL WINAPI DrawTransparentBitmap(HDC hdcDst, HDC hdcImage, COLORREF crTransparent, int xDst, int yDst, int cxDst, int cyDst, int cxSrc, int cySrc)
{
BOOL bOK;
// PREPARE MASK BEGIN
HDC hdcMask = CreateCompatibleDC(NULL);
HBITMAP bmpMask = CreateBitmap(cxSrc, cySrc, 1, 1, NULL);
// Load the bitmaps into memory DC
HGDIOBJ oldMask = SelectObject(hdcMask, bmpMask);
// Change the background to trans color
COLORREF clrSaveBk = SetBkColor(hdcImage, crTransparent);
// This call sets up the bmpMask bitmap.
BOOL bGDI = BitBlt(hdcMask, 0, 0, cxSrc, cySrc, hdcImage,0,0,SRCCOPY);
// Now, we need to paint onto the original image, making
// sure that the "transparent" area is set to black. What
// we do is AND the monochrome image onto the color Image
// first. When blitting from mono to color, the monochrome
// pixel is first transformed as follows:
// if 1 (black) it is mapped to the color set by SetTextColor().
// if 0 (white) is is mapped to the color set by SetBkColor().
// Only then is the raster operation performed.
COLORREF clrSaveText = SetTextColor(hdcImage, RGB(255,255,255));
SetBkColor(hdcImage, RGB(0,0,0));
bGDI = bGDI && BitBlt(hdcImage, 0, 0, cxSrc, cySrc, hdcMask, 0, 0, SRCAND);
// Clean up by deselecting any objects, and delete the DC's.
SelectObject(hdcMask, oldMask); // clean up
DeleteDC(hdcMask); hdcMask = NULL;
SetBkColor (hdcImage, clrSaveBk); // restore
SetTextColor(hdcImage, clrSaveText);
// PREPARE MASK END
bOK = DrawTransparentHelper( hdcDst, bmpMask, // The destination DC.
xDst, // Where to draw
yDst,
cxDst, // Width & Height
cyDst,
hdcImage, // the DC holding the bmp
0,
0,
cxSrc,
cySrc);
bGDI = bGDI && DeleteObject(bmpMask);
return bOK;
}
/*
Does somebody know how to implement this better using TRANSPARENTROP?
#define TRANSPARENTROP 0xb8074a
EXTERN_C BOOL WINAPI DrawTransparentBitmap(HDC hdc, HDC dcSrc, COLORREF crTransparent, int xDst, int yDst, int cxDst, int cyDst, int cxSrc, int cySrc)
{
// Now draw the checkmark transparently
HBRUSH hbrush = CreateSolidBrush(crTransparent);
HGDIOBJ old = SelectObject(hdc, hbrush);
COLORREF cBG = SetBkColor(hdc, RGB(255,255,255));
BOOL bOK = StretchBlt(hdc, xDst, yDst, cxDst, cyDst, dcSrc, 0, 0, cxSrc, cySrc, TRANSPARENTROP);
SetBkColor(hdc, cBG);
SelectObject(hdc, old);
DeleteObject(hbrush);
return bOK;
}
*/
| [
"chenchao0632@163.com"
] | chenchao0632@163.com |
16f74df87dc563ecf552e860a3b6139fc38fa667 | 32ac043d48d7d0950d43d75d199ce29427f8f7ef | /include/bunsan/binlogs/LogReader.hpp | 7760c55473e36a7228c47bd2db9c320797e9f90e | [] | no_license | sarum9in/bunsan_binlogs | 963bbb54c2f3a94dc40fa58ff65246630eff1ff2 | aca8472a2c992c3a9939b3669f4dd6ef3f3eb0a4 | refs/heads/master | 2016-08-03T06:23:25.584238 | 2013-09-27T11:16:04 | 2013-09-27T11:16:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,466 | hpp | #pragma once
#include <bunsan/binlogs/BaseReader.hpp>
#include <bunsan/binlogs/MessageTypePool.hpp>
#include <bunsan/binlogs/MessageType.hpp>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/message.h>
#include <memory>
namespace bunsan {
namespace binlogs {
class LogReader: public BaseReader {
public:
/// Allocate and read message of appropriate type.
std::unique_ptr<google::protobuf::Message> read();
/// False means EOF.
bool read(const std::unique_ptr<google::protobuf::Message> &message);
/// False means EOF.
virtual bool read(google::protobuf::Message &message)=0;
/*!
* \brief What message will be read next (if available)?
*
* \warning Pointer is only valid until next call to read().
* \note Subsequent calls to nextMessageType() will return the same pointer.
*
* \return nullptr on EOF
*/
virtual const MessageType *nextMessageType()=0;
/// \warning May change during log reading.
virtual const MessageTypePool &messageTypePool() const=0;
/*!
* \brief Check stream's format in fastest way possible.
*
* \note Implementation may omit messages consistency check
* and treat them as byte arrays.
*
* Consumes entire stream.
*
* \note Default implementation reads all messages to the EOF.
* Should be reimplemented in subclass for faster implementation.
*/
virtual void fastCheck();
};
}
}
| [
"sarum9in@gmail.com"
] | sarum9in@gmail.com |
880f94a170a795ec7a88b8d02e1529a2ede37916 | 31d7717e3aa8da831e439ced3b061933c0ce0988 | /OpenHome/Net/Bindings/Cpp/Device/Providers/DvAvOpenhomeOrgWebResamplerConfig1Std.cpp | 89e527267d2b3d8863e8380725dec4c527a74721 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | imateev/Lightning-ohNet | 586f5d7b1e29c6c61269a064085ca11078ed5092 | bd8ea0ef4f5237820f445951574818f6e7dfff9c | refs/heads/master | 2021-12-25T23:07:13.914882 | 2018-01-02T01:11:27 | 2018-01-02T01:11:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,926 | cpp | #include "DvAvOpenhomeOrgWebResamplerConfig1.h"
#include <OpenHome/Types.h>
#include <OpenHome/Net/Private/DviService.h>
#include <OpenHome/Net/Private/Service.h>
#include <OpenHome/Net/Private/FunctorDviInvocation.h>
#include <OpenHome/Net/Cpp/DvInvocation.h>
#include <OpenHome/Net/Private/DviStack.h>
using namespace OpenHome;
using namespace OpenHome::Net;
bool DvProviderAvOpenhomeOrgWebResamplerConfig1Cpp::SetPropertyResamplerConfig(const std::string& aValue)
{
ASSERT(iPropertyResamplerConfig != NULL);
Brn buf((const TByte*)aValue.c_str(), (TUint)aValue.length());
return SetPropertyString(*iPropertyResamplerConfig, buf);
}
void DvProviderAvOpenhomeOrgWebResamplerConfig1Cpp::GetPropertyResamplerConfig(std::string& aValue)
{
ASSERT(iPropertyResamplerConfig != NULL);
const Brx& val = iPropertyResamplerConfig->Value();
aValue.assign((const char*)val.Ptr(), val.Bytes());
}
DvProviderAvOpenhomeOrgWebResamplerConfig1Cpp::DvProviderAvOpenhomeOrgWebResamplerConfig1Cpp(DvDeviceStd& aDevice)
: DvProvider(aDevice.Device(), "av.openhome.org", "WebResamplerConfig", 1)
{
iPropertyResamplerConfig = NULL;
}
void DvProviderAvOpenhomeOrgWebResamplerConfig1Cpp::EnablePropertyResamplerConfig()
{
iPropertyResamplerConfig = new PropertyString(new ParameterString("ResamplerConfig"));
iService->AddProperty(iPropertyResamplerConfig); // passes ownership
}
void DvProviderAvOpenhomeOrgWebResamplerConfig1Cpp::EnableActionGetResamplerConfig()
{
OpenHome::Net::Action* action = new OpenHome::Net::Action("GetResamplerConfig");
action->AddOutputParameter(new ParameterRelated("ResamplerConfig", *iPropertyResamplerConfig));
FunctorDviInvocation functor = MakeFunctorDviInvocation(*this, &DvProviderAvOpenhomeOrgWebResamplerConfig1Cpp::DoGetResamplerConfig);
iService->AddAction(action, functor);
}
void DvProviderAvOpenhomeOrgWebResamplerConfig1Cpp::EnableActionSetResamplerConfig()
{
OpenHome::Net::Action* action = new OpenHome::Net::Action("SetResamplerConfig");
action->AddInputParameter(new ParameterRelated("ResamplerConfig", *iPropertyResamplerConfig));
FunctorDviInvocation functor = MakeFunctorDviInvocation(*this, &DvProviderAvOpenhomeOrgWebResamplerConfig1Cpp::DoSetResamplerConfig);
iService->AddAction(action, functor);
}
void DvProviderAvOpenhomeOrgWebResamplerConfig1Cpp::DoGetResamplerConfig(IDviInvocation& aInvocation)
{
aInvocation.InvocationReadStart();
aInvocation.InvocationReadEnd();
std::string respResamplerConfig;
DvInvocationStd invocation(aInvocation);
GetResamplerConfig(invocation, respResamplerConfig);
aInvocation.InvocationWriteStart();
DviInvocationResponseString respWriterResamplerConfig(aInvocation, "ResamplerConfig");
Brn buf_ResamplerConfig((const TByte*)respResamplerConfig.c_str(), (TUint)respResamplerConfig.length());
respWriterResamplerConfig.Write(buf_ResamplerConfig);
aInvocation.InvocationWriteStringEnd("ResamplerConfig");
aInvocation.InvocationWriteEnd();
}
void DvProviderAvOpenhomeOrgWebResamplerConfig1Cpp::DoSetResamplerConfig(IDviInvocation& aInvocation)
{
aInvocation.InvocationReadStart();
Brhz buf_ResamplerConfig;
aInvocation.InvocationReadString("ResamplerConfig", buf_ResamplerConfig);
std::string ResamplerConfig((const char*)buf_ResamplerConfig.Ptr(), buf_ResamplerConfig.Bytes());
aInvocation.InvocationReadEnd();
DvInvocationStd invocation(aInvocation);
SetResamplerConfig(invocation, ResamplerConfig);
aInvocation.InvocationWriteStart();
aInvocation.InvocationWriteEnd();
}
void DvProviderAvOpenhomeOrgWebResamplerConfig1Cpp::GetResamplerConfig(IDvInvocationStd& /*aInvocation*/, std::string& /*aResamplerConfig*/)
{
ASSERTS();
}
void DvProviderAvOpenhomeOrgWebResamplerConfig1Cpp::SetResamplerConfig(IDvInvocationStd& /*aInvocation*/, const std::string& /*aResamplerConfig*/)
{
ASSERTS();
}
| [
"875679109@qq.com"
] | 875679109@qq.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.