blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
58cc94cc6cf3d72639343965e308a3679dfbae8f | 85983068d42318310065e40f43f7d9c6ad8a1114 | /Line Tracking Robot/LineTrackingRobot/LineTrackingRobot.ino | afd245ae99c3878ef2778d257ef00c019733262d | [] | no_license | WindyCityLab/equinoxLabs | 5df9b6ac0a859967ebcf623a6dd0de54e8f9c597 | 6d51a084aabfef7b5ce3f5789321d7108711da67 | refs/heads/master | 2021-01-22T15:50:55.694642 | 2015-07-19T15:49:14 | 2015-07-19T15:49:14 | 38,978,111 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,319 | ino | #include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_PWMServoDriver.h"
#include "TypesAndDeclarations.h"
Adafruit_MotorShield AFMS = Adafruit_MotorShield(); // Initialize the Shield
Adafruit_DCMotor *motorFL = AFMS.getMotor(1);
Adafruit_DCMotor *motorFR = AFMS.getMotor(4);
Adafruit_DCMotor *motorBL = AFMS.getMotor(2);
Adafruit_DCMotor *motorBR = AFMS.getMotor(3);
void setMotor(Adafruit_DCMotor *motor, bool On, String motorName)
{
Serial.print(motorName); Serial.print(" ");
if (On) {
Serial.println("ON");
motor->run(FORWARD);
motor->setSpeed(DEFAULT_MOTOR_SPEED);
}
else {
Serial.println("OFF");
motor->run(BACKWARD);
motor->setSpeed(DEFAULT_MOTOR_SPEED);
}
}
void setMotors(uint8_t toSpeed)
{
switch (toSpeed) {
case BOTH_MOTORS : {
setMotor(motorFL,true, "FL");
setMotor(motorFR,true, "FR");
setMotor(motorBL,true, "BL");
setMotor(motorBR,true, "BR");
}
break;
case RIGHT_MOTOR_ONLY : {
setMotor(motorFL,false, "FL");
setMotor(motorFR,true, "FR");
setMotor(motorBL,false, "BL");
setMotor(motorBR,true, "BR");
}
break;
case LEFT_MOTOR_ONLY : {
setMotor(motorFL,true, "FL");
setMotor(motorFR,false, "FR");
setMotor(motorBL,true, "BL");
setMotor(motorBR,false, "BR");
}
break;
}
}
PossibleInputs currentRelationshipToLine() {
if ((analogRead(A0) < CENTER_LEFT_SENSOR) && (analogRead(A1) < CENTER_RIGHT_SENSOR))
{
return ON_LINE;
}
if ((analogRead(A0) < CENTER_LEFT_SENSOR) && (analogRead(A1) > CENTER_RIGHT_SENSOR))
{
return OFF_TO_THE_RIGHT;
}
if ((analogRead(A0) > CENTER_LEFT_SENSOR) && (analogRead(A1) < CENTER_RIGHT_SENSOR))
{
return OFF_TO_THE_LEFT;
}
return LOST;
}
uint8_t currentState = CENTER;
void setup() {
Serial.begin(115200);
AFMS.begin();
motorFL->run(FORWARD);
motorFR->run(FORWARD);
motorBL->run(FORWARD);
motorBR->run(FORWARD);
}
void loop() {
while (1) {
setMotors(fsm[currentState].output);
delay(fsm[currentState].timeDelay);
currentState = fsm[currentState].nextState[currentRelationshipToLine()];
Serial.print("Current state: ");
Serial.print(currentState);
Serial.print(" Input -> ");
Serial.println(currentRelationshipToLine());
}
}
| [
"kevinmcquown@me.com"
] | kevinmcquown@me.com |
3ba96dd105aa816b78d5d5f37bd4479f1106ab2d | 375c093f555bddd1ce10e80530dba9119cc24306 | /BOJ/20361.cpp | 1ff903190b2cffd779ebfa73eebabbd48b0fa611 | [] | no_license | Seojeonguk/Algorithm_practice | e8c2add155a1341087e4c528f5346c8711525f96 | b29a1a7421edf2a9968229822dcbdc5a7926e2f5 | refs/heads/master | 2023-08-25T11:40:40.076347 | 2023-08-25T09:07:45 | 2023-08-25T09:07:45 | 154,248,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 382 | cpp | #ifdef _DEBUG
#include "bits_stdc++.h"
#else
#include "bits/stdc++.h"
#endif
#pragma warning(disable:4996)
using namespace std;
int n, x, k,a,b;
int main() {
#ifdef _CONSOLE
freopen("sample.txt", "r", stdin);
#endif
scanf("%d %d %d", &n, &x, &k);
for (int i = 0; i < k; i++) {
scanf("%d %d", &a, &b);
if (a == x) x = b;
else if (b == x) x = a;
}
printf("%d\n", x);
} | [
"uk7880@naver.com"
] | uk7880@naver.com |
2866bf78789666c3a9e0154debcc386652e07eb3 | f0a739dda86d11b615d4225662dcd89b65b3d01a | /MapEditor/Direct3D/TestModel/ModelPart.h | feb18dfff571ad7cf641bf72ddd2d9a8aa34ade7 | [] | no_license | kbm0818/Portfolio | 173d3de48902083cf575c3231448fb6dc0ab4bc3 | dc4df24bb629379d55bfa15a84cd0fc6e8dc757f | refs/heads/master | 2020-03-28T22:49:21.942143 | 2018-10-02T07:33:35 | 2018-10-02T07:33:35 | 149,260,142 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,362 | h | #pragma once
#include "../Shaders/Shader.h"
#include "BinaryInputOutputHandler.h"
class Model;
class ModelMaterial;
class ModelBoneWeights;
class ModelBuffer;
class ModelPart : public Shader, public BinaryInputOutputHandler
{
public:
ModelPart(Model* model);
ModelPart(Model* model, ModelMaterial* material);
ModelPart(ModelPart& otherModel);
~ModelPart();
void Update(bool isAnimation);
void Render();
void SetModel(Model* model) { this->model = model; }
//void SetModelBuffer(ModelBuffer* modelBuffer) { this->modelBuffer = modelBuffer; }
void AddVertex(D3DXVECTOR3& position, D3DXVECTOR3& normal, D3DXVECTOR2& uv, const ModelBoneWeights& boneWeights);
void CreateData();
void CreateBuffer();
ModelMaterial* GetMaterial() { return material; }
void SetMaterial(ModelMaterial* material) { this->material = material; }
void Export(BinaryWriter* bw);
void Import(BinaryReader* br);
private:
void CalculateTangents();
Model* model;
bool isSkinnedModel;
vector<D3DXVECTOR3> positions;
vector<D3DXVECTOR3> normals;
vector<D3DXVECTOR3> tangents;
vector<D3DXVECTOR2> uvs;
vector<UINT> indices;
vector<ModelBoneWeights> boneWeights;
ModelMaterial* material;
UINT materialIndex;
UINT vertexCount;
VertexTextureNormalTangentBlend* vertex;
ID3D11Buffer* vertexBuffer;
UINT indexCount;
UINT* index;
ID3D11Buffer* indexBuffer;
}; | [
"kbm0818@naver.com"
] | kbm0818@naver.com |
9dcd2658a2e7ed1e90eec791899226b4bbc592fa | 71a0a5bffa4bfd8ed0b398c79f09c48705a2ae27 | /smart_feeder/smart_feeder.ino | f791c1ca605105c83a140636c8a472393f076eaa | [] | no_license | ariyanki/esp8266 | 4eaad9b9b73e68c37805624044335305acd83ee3 | e4b3fed4b79cec27f529327ad8bfe304d6554eb0 | refs/heads/master | 2023-02-13T07:39:06.047761 | 2021-01-03T10:07:32 | 2021-01-03T10:07:32 | 273,612,869 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,849 | ino | // Load Wi-Fi library
#include <ESP8266WiFi.h>
#include <Servo.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <EEPROM.h>
#include <ArduinoOTA.h>
Servo servo;
int servoFrom = 0;
int servoTo = 0;
// #### Network Configuration ####
// Access Point network credentials
const char* hostname = "pakanikan1";
const char* ap_ssid = "pakanikan1";
const char* ap_password = "esp826612345";
bool wifiConnected = false;
// Set web server port number to 80
ESP8266WebServer server(80);
// #### NTP Configuration ####
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
String months[12]={"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "id.pool.ntp.org", (7*3600));
// #### Time ####
unsigned long timeNow = 0;
unsigned long timeLast = 0;
int startingHour = 0;
int seconds = 0;
int minutes = 0;
int hours = startingHour;
String currentDate = "";
String currentDay = "";
// #### Timer Configuration ####
#define TIMER_LIMIT 24 // for 24 times setting, each time 9 char *24
String timer[TIMER_LIMIT];
// #### EEPROM to store Data ####
// character length setting
int singleLength = 1;
int ssidLength = 32;
int pwdLength = 32;
int ipLength=15;
int timeLength=9*TIMER_LIMIT;
// Address Position setting
int ssidAddr = 0;
int pwdAddr = ssidAddr+ssidLength;
int ipAddr = pwdAddr+pwdLength;
int ipSubnetAddr = ipAddr+ipLength;
int ipGatewayAddr = ipSubnetAddr+ipLength;
int ipDNSAddr = ipGatewayAddr+ipLength;
int gpioAddr = ipDNSAddr+ipLength;
int servoWriteFromAddr = gpioAddr+singleLength;
int servoWriteToAddr = servoWriteFromAddr+singleLength;
int timeAddr = servoWriteToAddr+singleLength;
int eepromSize=timeAddr+timeLength;
void eeprom_write(String buffer, int addr, int length) {
String curVal = eeprom_read(addr, length);
// Check before write to minimize eeprom write operation
if(curVal!=buffer){
int bufferLength = buffer.length();
EEPROM.begin(eepromSize);
delay(10);
for (int L = addr; L < addr+bufferLength; ++L) {
EEPROM.write(L, buffer[L-addr]);
}
//set empty
for (int L = addr+bufferLength; L < addr+length; ++L) {
EEPROM.write(L, 255);
}
EEPROM.commit();
}
}
String eeprom_read(int addr, int length) {
EEPROM.begin(eepromSize);
String buffer="";
delay(10);
for (int L = addr; L < addr+length; ++L){
if (isAscii(EEPROM.read(L)))
buffer += char(EEPROM.read(L));
}
return buffer;
}
void eeprom_write_single(int value, int addr) {
int curVal = eeprom_read_single(addr);
// Check before write to minimize eeprom write operation
if(curVal!=value){
EEPROM.begin(eepromSize);
EEPROM.write(addr, value);
EEPROM.commit();
}
}
int eeprom_read_single(int addr) {
EEPROM.begin(eepromSize);
return EEPROM.read(addr);
}
// #### HTTP Configuration ####
String logStr = "";
String headerHtml = "<!DOCTYPE html><html>"
"<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
"<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css\" integrity=\"sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu\" crossorigin=\"anonymous\">"
"<link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.7.2/css/all.css\" integrity=\"sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr\" crossorigin=\"anonymous\">"
"<style>"
"html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}"
"body {margin:0px}"
".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;"
"text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}"
".button { background-color: #195B6A; border: none; color: white; padding: 16px 40px;text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}"
".button2 {background-color: #77878A;border-radius: 15px; display: inline-grid;text-decoration: none;}"
".header {background-color: black; color: white;padding: 20px;margin: 0px; margin-bottom: 20px;}"
".switch {position: relative; display: inline-block; width: 120px; height: 68px} "
".switch input {display: none}"
".slider {position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; border-radius: 34px}"
".slider:before {position: absolute; content: \"\"; height: 52px; width: 52px; left: 8px; bottom: 8px; background-color: #fff; -webkit-transition: .4s; transition: .4s; border-radius: 68px}"
"input:checked+.slider {background-color: #2196F3}"
"input:checked+.slider:before {-webkit-transform: translateX(52px); -ms-transform: translateX(52px); transform: translateX(52px)}"
"</style></head>";
String footerHtml = "<script src=\"https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js\" integrity=\"sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd\" crossorigin=\"anonymous\"></script>"
"<html>";
String redirectToRootHtml = "<!DOCTYPE html><html>"
"<head><script>window.location.href = \"/\";</script></head>"
"<body></body></html>";
String savedNotifHtml = headerHtml + "<body><br/><br/>"
"<p>Your configuration has been saved, if you are sure with your configuration then please restart your device</p>"
"<p><a href=\"#\"><button class=\"button button2\" onclick=\"restart()\"><i class=\"fas fa-redo\"></i> Restart</button></a></p>"
"<p><a href=\"/\"><button class=\"button button2\"><i class=\"fas fa-arrow-left\"></i> Back to home</button></a></p>"
"<script>"
"function restart(element) {"
"var xhr = new XMLHttpRequest();"
"xhr.open(\"GET\", \"/restart\", true);"
"xhr.send();"
"}"
"</script>"
"</body>"+footerHtml;
void handleRoot() {
String htmlRes = headerHtml + "<body><h1 class=\"header\">Smart Feeder</h1>"
"<h3 style=\"margin-bottom: 20px;\">"+currentDay+", "+currentDate+" "+hours+":"+minutes+":"+seconds+"</h3><hr>"
"<p>"+logStr+"</p>"
"<p><button class=\"button button2\" onclick=\"testFeed()\">Feeding Test</button></p>"
"<p>To make this timer work, please make sure your wifi connected to the internet to get time from NTP Server.</p>"
"<p>If the datetime above correct then your wifi configuration is correct.</p>"
"<p style=\"margin-top: 40px;\"><a href=\"/settings\"><button class=\"button button2\"><i class=\"fas fa-cogs\"></i> Settings</button></a></p>"
"<script>function testFeed() {"
"var xhr = new XMLHttpRequest();"
"xhr.open(\"GET\", \"/feeding\", true);"
"xhr.send();"
"}"
"</script>"
"</body>"+footerHtml;
server.send(200, "text/html", htmlRes);
}
void handleSettings() {
String htmlRes = headerHtml + "<body><h1 class=\"header\">Settings</h1>"
"<h3 style=\"margin-bottom: 20px;\">"+currentDay+", "+currentDate+" "+hours+":"+minutes+":"+seconds+"</h3><hr>"
"<p><a href=\"/wificonfig\"><button class=\"button button2\"><i class=\"fas fa-wifi\"></i> Wifi Config</button></a></p>"
"<p><a href=\"/servoconfig\"><button class=\"button button2\"><i class=\"fas fa-plug\"></i> Servo Config</button></a></p>"
"<p><a href=\"/timerconfig\"><button class=\"button button2\"><i class=\"fas fa-clock\"></i> Timer Config</button></a></p>"
"<p><a href=\"#\"><button class=\"button button2\" onclick=\"synctime()\"><i class=\"fas fa-clock\"></i> Sync Time</button></a></p>"
"<p><a href=\"#\"><button class=\"button button2\" onclick=\"restart()\"><i class=\"fas fa-redo\"></i> Restart</button></a></p>"
"<p><a href=\"/\"><button class=\"button button2\"><i class=\"fas fa-arrow-left\"></i> Back to home</button></a></p>"
"<p></p>"
"<script>"
"function restart(element) {"
"var xhr = new XMLHttpRequest();"
"xhr.open(\"GET\", \"/restart\", true);"
"xhr.send();"
"}"
"function synctime(element) {"
"var xhr = new XMLHttpRequest();"
"xhr.open(\"GET\", \"/synctime\", true);"
"xhr.send();"
"}"
"</script>"
"</body>"+footerHtml;
server.send(200, "text/html", htmlRes);
}
void handleFeeding() {
servoWrite();
server.send(200, "text/plain", "OK");
}
void handleWifiConfigForm() {
String ssid = eeprom_read(ssidAddr, ssidLength);
String password = eeprom_read(pwdAddr, pwdLength);
String strIp = eeprom_read(ipAddr, ipLength);
String strSubnet = eeprom_read(ipSubnetAddr, ipLength);
String strGateway = eeprom_read(ipGatewayAddr, ipLength);
String strDNS = eeprom_read(ipDNSAddr, ipLength);
String htmlRes = headerHtml + "<body><h1 class=\"header\">Wifi Config</h1>"
"<form method=post action=\"/savewificonfig\" style=\"margin: 20px\">"
"<p><b>SSID</b><br/><input type=text class=\"form-control\" name=ssid id=ssid value=\""+ssid+"\"><br/>(max 32 character)</p>"
"<p><b>Password</b><br/><input type=text class=\"form-control\" name=password id=password value=\""+password+"\"><br/>(max 32 character)</p>"
"<p>Manual Setting IP<br/>(leave empty if you want to use DHCP)</p>"
"<p><b>IP Address</b><br/><input type=text class=\"form-control\" name=ip id=ip value=\""+strIp+"\"></p>"
"<p><b>Subnet</b><br/><input type=text class=\"form-control\" name=subnet id=subnet value=\""+strSubnet+"\"></p>"
"<p><b>Gateway</b><br/><input type=text class=\"form-control\" name=gateway id=gateway value=\""+strGateway+"\"></p>"
"<p><b>DNS</b><br/><input type=text class=\"form-control\" name=dns id=dns value=\""+strDNS+"\"></p>"
"<p><button type=submit value=Save class=\"button button2\"><i class=\"fas fa-save\"></i> Save</button> <button type=\"button\" onclick=\"window.location.href = '/';\" class=\"button button2\"><i class=\"fas fa-arrow-left\"></i> Cancel</button></p>"
"</form>"
"</body>"+footerHtml;
server.send(200, "text/html", htmlRes);
}
void handleSaveWifiConfigForm() {
eeprom_write(server.arg("ssid"), ssidAddr,ssidLength);
eeprom_write(server.arg("password"), pwdAddr,pwdLength);
eeprom_write(server.arg("ip"), ipAddr,ipLength);
eeprom_write(server.arg("subnet"), ipSubnetAddr,ipLength);
eeprom_write(server.arg("gateway"), ipGatewayAddr,ipLength);
eeprom_write(server.arg("dns"), ipDNSAddr,ipLength);
server.send(200, "text/html", savedNotifHtml);
}
void handleServoConfigForm() {
String strGPIO = String(eeprom_read_single(gpioAddr));
String strWriteFrom = String(eeprom_read_single(servoWriteFromAddr));
String strWriteTo = String(eeprom_read_single(servoWriteToAddr));
String htmlRes = headerHtml + "<body><h1 class=\"header\">Servo Config</h1>"
"<form method=post action=\"/saveservoconfig\" style=\"margin: 20px\">"
"<p><b>GPIO Number</b></br><input type=text class=\"form-control\" name=gpio id=gpio value=\""+strGPIO+"\"></p>"
"<p><b>Write From</b></br><input type=text class=\"form-control\" name=write_from id=write_from value=\""+strWriteFrom+"\"></p>"
"<p><b>Write To</b></br><input type=text class=\"form-control\" name=write_to id=write_to value=\""+strWriteTo+"\"></p>"
"<p><button type=submit value=Save class=\"button button2\"><i class=\"fas fa-save\"></i> Save</button> <button type=\"button\" onclick=\"window.location.href = '/';\" class=\"button button2\"><i class=\"fas fa-arrow-left\"></i> Cancel</button></p>"
"</form>"
"</body>"+footerHtml;
server.send(200, "text/html", htmlRes);
}
void handleSaveServoConfigForm() {
eeprom_write_single(server.arg("gpio").toInt(), gpioAddr);
eeprom_write_single(server.arg("write_from").toInt(), servoWriteFromAddr);
eeprom_write_single (server.arg("write_to").toInt(), servoWriteToAddr);
server.send(200, "text/html", savedNotifHtml);
}
void handleTimerConfigForm() {
String strTimer = eeprom_read(timeAddr, timeLength);
String htmlRes = headerHtml + "<body><h1 class=\"header\">Timer Config</h1>"
"<form method=post action=\"/savetimerconfig\" style=\"margin: 20px\">"
"<p>Format hour:minute:second without \"0\"<br/>"
"For multiple time input with \";\" delimitier<br/>"
"To save memory it has limit "+String(TIMER_LIMIT)+" times setting maximum<br/>"
"<b>Example:</b> 1:30:0;6:8:0;18:7:12</p>"
"<p><b>Timer</b></br><input type=text class=\"form-control\" name=timer id=timer value=\""+strTimer+"\"></p>"
"<p><button type=submit value=Save class=\"button button2\"><i class=\"fas fa-save\"></i> Save</button> <button type=\"button\" onclick=\"window.location.href = '/';\" class=\"button button2\"><i class=\"fas fa-arrow-left\"></i> Cancel</button></p>"
"</form>"
"</body>"+footerHtml;
server.send(200, "text/html", htmlRes);
}
void handleSaveTimerConfigForm() {
eeprom_write(server.arg("timer"), timeAddr,timeLength);
readTimer();
server.send(200, "text/html", redirectToRootHtml);
}
void handleRestart() {
ESP.restart();
}
void handleSyncTime() {
syncTime();
}
void servoWrite() {
// Total delay must be more than 1000 milisecond when using timer
servo.write(servoTo);
delay(500);
servo.write(servoFrom);
delay(2000);
}
void connectToWifi(){
// GET Wifi Config from EEPROM
String ssid = eeprom_read(ssidAddr, ssidLength);
Serial.println("EEPROM "+String(eepromSize)+" Config:");
Serial.println(ssid);
if(ssid.length()>0){
String password = eeprom_read(pwdAddr, pwdLength);
Serial.println(password);
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
int i = 0;
while (WiFi.status() != WL_CONNECTED) {
i++;
if(i>20) break;
delay(500);
Serial.print(".");
}
if(i>20) {
Serial.println("WiFi not connected. Please use \""+String(ap_ssid)+"\" AP to config");
}else{
//Set Static IP
String strIp = eeprom_read(ipAddr, ipLength);
Serial.println(strIp);
IPAddress local_IP;
if(local_IP.fromString(strIp)){
Serial.println("IP Parsed");
String strSubnet = eeprom_read(ipSubnetAddr, ipLength);
String strGateway = eeprom_read(ipGatewayAddr, ipLength);
String strDNS = eeprom_read(ipDNSAddr, ipLength);
Serial.println(strSubnet);
Serial.println(strGateway);
Serial.println(strDNS);
IPAddress gateway;
IPAddress subnet;
IPAddress dns;
if(gateway.fromString(strSubnet)){
Serial.println("Gateway Parsed");
}
if(subnet.fromString(strGateway)){
Serial.println("Subnet Parsed");
}
if(dns.fromString(strDNS)){
Serial.println("DNS Parsed");
}
if (!WiFi.config(local_IP, dns, gateway, subnet)) {
Serial.println("STA Failed to configure");
}
}
Serial.println("WiFi connected.");
//Set hostname
if (!MDNS.begin(hostname)) {
Serial.println("Error setting up MDNS responder!");
}
wifiConnected = true;
timeClient.begin();
syncTime();
}
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
}
void readTimer(){
// GET timer for EEPROM
String strTime = eeprom_read(timeAddr, timeLength);
int f = 0, r=0;
for (int i=0; i < strTime.length(); i++)
{
if(strTime.charAt(i) == ';')
{
timer[f] = strTime.substring(r, i);
r=(i+1);
f++;
}
}
}
void syncTime(){
if (wifiConnected){
timeClient.update();
seconds = timeClient.getSeconds();
minutes = timeClient.getMinutes();
hours = timeClient.getHours();
timeLast = millis();
unsigned long epochTime = timeClient.getEpochTime();
struct tm *ptm = gmtime ((time_t *)&epochTime);
int monthDay = ptm->tm_mday;
int currentMonth = ptm->tm_mon+1;
String currentMonthName = months[currentMonth-1];
int currentYear = ptm->tm_year+1900;
currentDay = String(daysOfTheWeek[timeClient.getDay()]);
currentDate = String(monthDay) + " " + String(currentMonthName) + " " + String(currentYear);
}
}
void updateTime(){
timeNow = millis();
if (timeNow >= timeLast+1000){
timeLast=timeNow;
seconds = seconds + 1;
if (seconds == 60) {
seconds = 0;
minutes = minutes + 1;
}
if (minutes == 60){
minutes = 0;
hours = hours + 1;
}
if (hours == 24){
hours = 0;
}
}
}
void setup() {
Serial.begin(115200);
delay(100);
// Initialize servo pin
servo.attach(eeprom_read_single(gpioAddr));
servoFrom = eeprom_read_single(servoWriteFromAddr);
servoTo = eeprom_read_single(servoWriteToAddr);
servo.write(servoFrom);
// Initialize Access Point
WiFi.softAP(ap_ssid, ap_password);
Serial.print("visit: \n");
Serial.println(WiFi.softAPIP());
connectToWifi();
readTimer();
// start web server
server.on("/", handleRoot);
server.on("/settings", handleSettings);
server.on("/feeding", handleFeeding);
server.on("/wificonfig", handleWifiConfigForm);
server.on("/savewificonfig", HTTP_POST, handleSaveWifiConfigForm);
server.on("/servoconfig", handleServoConfigForm);
server.on("/saveservoconfig", HTTP_POST, handleSaveServoConfigForm);
server.on("/timerconfig", handleTimerConfigForm);
server.on("/savetimerconfig", HTTP_POST, handleSaveTimerConfigForm);
server.on("/restart", HTTP_GET, handleRestart);
server.on("/synctime", HTTP_GET, handleSyncTime);
server.begin();
ArduinoOTA.onStart([]() {
Serial.println("Start");
});
ArduinoOTA.onEnd([]() {
Serial.println("\nEnd");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
}
long lastMilis = 0;
void loop(){
server.handleClient();
updateTime();
ArduinoOTA.handle();
// execute in second
if (millis() >= lastMilis+1000){
lastMilis=millis();
if (seconds == 30 and !wifiConnected){
connectToWifi();
}
// Execute Timer
String checkTime = String(hours)+":"+String(minutes)+":"+String(seconds);
for (int i=0;i<TIMER_LIMIT;i++){
if (timer[i] == checkTime) {
servoWrite();
}
}
}
}
| [
"ariyanki.bahtiar@gmail.com"
] | ariyanki.bahtiar@gmail.com |
1d960042dd25ff02d954baeb89b66b4040bd25e6 | fc74816e1cfbef9f3a15f3955bfe608b2605c44b | /count.cpp | 073b09c00ae768cf8805564d6d4b93b9073c7c8e | [] | no_license | marklance/work | 5e90b5a7808228269e526516a152912bc7b1afdd | ff089d1644e5f99175b7828903b9047996935843 | refs/heads/master | 2021-04-28T09:17:27.555380 | 2018-06-03T15:52:41 | 2018-06-03T15:52:41 | 121,955,775 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 673 | cpp | #include <iostream>
#include <fstream>
#include <cstdlib>
int main(int argc, char * argv[])
{
using namespace std;
if (argc == 1)
{
cerr << "Usage: " << argv[0] << " filename[s]\n";
exit(EXIT_FAILURE);
}
ifstream fin;
long count;
long total = 0;
char ch;
for (int file = 1; file < argc; file++)
{
fin.open(argv[file]);
if (!fin.is_open())
{
cerr << "Could not open " << argv[file] << endl;
fin.clear();
continue;
}
count = 0;
while (fin.get(ch))
count++;
cout << count << " characters in " << argv[file] << endl;
total += count;
fin.clear();
fin.close();
}
cout << total << " characters in all file\n";
return 0;
}
| [
"2927295165@qq.com"
] | 2927295165@qq.com |
804c2545f58436e1df2eaca999344c6c3eb7344e | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/collectd/gumtree/collectd_repos_function_308_collectd-5.6.3.cpp | 59bef3734378a6afdb92c73c674bdf8dab83f14a | [] | 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 | 963 | cpp | static void aggregate(gauge_t *sum_by_state) /* {{{ */
{
for (size_t state = 0; state < COLLECTD_CPU_STATE_MAX; state++)
sum_by_state[state] = NAN;
for (size_t cpu_num = 0; cpu_num < global_cpu_num; cpu_num++) {
cpu_state_t *this_cpu_states = get_cpu_state(cpu_num, 0);
this_cpu_states[COLLECTD_CPU_STATE_ACTIVE].rate = NAN;
for (size_t state = 0; state < COLLECTD_CPU_STATE_ACTIVE; state++) {
if (!this_cpu_states[state].has_value)
continue;
RATE_ADD(sum_by_state[state], this_cpu_states[state].rate);
if (state != COLLECTD_CPU_STATE_IDLE)
RATE_ADD(this_cpu_states[COLLECTD_CPU_STATE_ACTIVE].rate,
this_cpu_states[state].rate);
}
if (!isnan(this_cpu_states[COLLECTD_CPU_STATE_ACTIVE].rate))
this_cpu_states[COLLECTD_CPU_STATE_ACTIVE].has_value = 1;
RATE_ADD(sum_by_state[COLLECTD_CPU_STATE_ACTIVE],
this_cpu_states[COLLECTD_CPU_STATE_ACTIVE].rate);
}
} | [
"993273596@qq.com"
] | 993273596@qq.com |
e1fb7c5cddefd14837917de3d08c4963b0ac5ca8 | c901b8389d196012f3cd1a3230ead6c2fc46a89b | /code/Substractive Synth/synth_with_tunings/synth_with_tunings.ino | d209cd700197a438de6fd5ac788f0430bc82d381 | [] | no_license | Marquets/SMC-Master-Thesis | 99ec41ec69bf3a40a168a8f334f65e10f0989ac3 | 675ace2cd14dfeb4151baf9b901f69a042bf03a1 | refs/heads/master | 2023-01-31T10:35:27.432119 | 2020-12-17T13:55:57 | 2020-12-17T13:55:57 | 296,834,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,928 | ino | // Waveform Example - Create 2 waveforms with adjustable
// frequency and phase
//
// This example is meant to be used with 3 buttons (pin 0,
// 1, 2) and 2 knobs (pins 16/A2, 17/A3), which are present
// on the audio tutorial kit.
// https://www.pjrc.com/store/audio_tutorial_kit.html
//
// Use an oscilloscope to view the 2 waveforms.
//
// Button0 changes the waveform shape
//
// Knob A2 changes the frequency of both waveforms
// You should see both waveforms "stretch" as you turn
//
// Knob A3 changes the phase of waveform #1
// You should see the waveform shift horizontally
//
// This example code is in the public domain.
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>
#include <ResponsiveAnalogRead.h>
// GUItool: begin automatically generated code
AudioSynthWaveform waveform1; //xy=392,118
AudioSynthWaveform waveform2; //xy=410,177
AudioMixer4 mixer3;
AudioFilterStateVariable filter1; //xy=758,136
AudioOutputI2S i2s2; //xy=931,198
AudioConnection patchCord1(waveform1, 0, mixer3, 0);
AudioConnection patchCord2(waveform2, 0, mixer3, 1);
AudioConnection patchCord5(mixer3, 0, filter1, 0);
AudioConnection patchCord6(filter1, 1, i2s2, 0);
AudioConnection patchCord7(filter1, 1, i2s2, 1);
AudioControlSGTL5000 sgtl5000_1; //xy=239,232
//Mux control pins for analog signal (Sig_pin)
const int S0 = 0;
const int S1 = 1;
const int S2 = 2;
const int S3 = 3;
// Mux in "SIG" pin default
const int SIG_PIN = A0;
//Mux 1 control pins for analog signal (Sig_pin)
const int W0 = 19;
const int W1 = 18;
const int W2 = 17;
const int W3 = 16;
// Mux 1 in "SIG" pin default
const int WIG_PIN = 22;
int current_waveform1 = 0;
int current_waveform2 = 0;
int waveforms[] = {WAVEFORM_SINE,WAVEFORM_SAWTOOTH, WAVEFORM_TRIANGLE, WAVEFORM_SQUARE,WAVEFORM_SAWTOOTH_REVERSE,WAVEFORM_PULSE};
float lowestNotes[] = {41.204 * 4,55 * 4,73.416 * 4,97.999 * 4};
//Array of values for selecting the disered channel of the multiplexers
const boolean muxChannel[16][4] = {
{0, 0, 0, 0}, //channel 0
{1, 0, 0, 0}, //channel 1
{0, 1, 0, 0}, //channel 2
{1, 1, 0, 0}, //channel 3
{0, 0, 1, 0}, //channel 4
{1, 0, 1, 0}, //channel 5
{0, 1, 1, 0}, //channel 6
{1, 1, 1, 0}, //channel 7
{0, 0, 0, 1}, //channel 8
{1, 0, 0, 1}, //channel 9
{0, 1, 0, 1}, //channel 10
{1, 1, 0, 1}, //channel 11
{0, 0, 1, 1}, //channel 12
{1, 0, 1, 1}, //channel 13
{0, 1, 1, 1}, //channel 14
{1, 1, 1, 1} //channel 15
};
float just_intonation[] = {1,(float)256/243,(float)9/8,(float)32/27,(float)81/64,(float)4/3,(float)729/512,(float)3/2,(float)128/81,(float)27/16,(float)16/9,(float)243/128,2};
float shruti[] = {1,(float)256/243,(float)16/15,(float)10/9,(float)9/8,(float)32/27,(float)6/5,(float)5/4,(float)81/64,(float)4/3,(float)27/20,(float)45/32,(float)729/512,(float)3/2,
(float)128/81, (float)8/5, (float) 5/3, (float)27/16, (float)16/9, (float)9/5, (float)15/8, (float)243/128,2};
float quarter_tone[] = {1,(float)33/32,(float)17/16,(float)12/11,(float)9/8,(float)22/19,(float)19/16,(float)11/9,(float)24/19,(float) 22/17,(float)4/3,(float)11/8,(float)17/12,(float)16/11,
(float)3/2, (float)17/11, (float) 19/12, (float)18/11, (float)32/19, (float)16/9, (float)11/6, (float)33/17,2};
void setup() {
Serial.begin(9600);
pinMode(S0, OUTPUT);
pinMode(S1, OUTPUT);
pinMode(S2, OUTPUT);
pinMode(S3, OUTPUT);
pinMode(SIG_PIN, INPUT);
pinMode(W0, OUTPUT);
pinMode(W1, OUTPUT);
pinMode(W2, OUTPUT);
pinMode(W3, OUTPUT);
//pinMode(WIG_PIN, INPUT);
digitalWrite(S0, LOW);
digitalWrite(S1, LOW);
digitalWrite(S2, LOW);
digitalWrite(S3, LOW);
digitalWrite(W0, LOW);
digitalWrite(W1, LOW);
digitalWrite(W2, LOW);
digitalWrite(W3, LOW);
// Audio connections require memory to work. For more
// detailed information, see the MemoryAndCpuUsage example
AudioMemory(20);
// Comment these out if not using the audio adaptor board.
// This may wait forever if the SDA & SCL pins lack
// pullup resistors
sgtl5000_1.enable();
sgtl5000_1.volume(0.5); // caution: very loud - use oscilloscope only!
current_waveform1 = WAVEFORM_SINE;
waveform1.begin(current_waveform1);
current_waveform2 = WAVEFORM_SINE;
waveform2.begin(current_waveform2);
}
void loop() {
// Read the buttons and knobs, scale knobs to 0-1.0
float freq = 0.0;
int i = 0;
while( i < 4) {
int index = map(readMux(0 + i*3), 0, 1023,0,21);
int cut_off = (readMux(1 + i*3) / 1023.0) * 200.0;
int cut_off2 = (readMux(2 + i*3) / 1023.0) * 1000.0;
double pitchbend = map(readMux(2 + i*3), 500, 1023,0.000,21.000);
// float general_vol = map(readMux2(0), 0, 1023, 0, 0.7);
int wave = map(readMux2(0), 0, 1023, 0, 5);
int wave2 = map(readMux2(7), 0, 1023, 0, 5);
Serial.println(readMux2(1));
freq = lowestNotes[i] * shruti[index];
if (freq != lowestNotes[i]) {
filter1.frequency(cut_off2);
filter1.resonance(1);
waveform1.begin(waveforms[wave]);
waveform1.frequency(freq/2);
waveform1.amplitude(1.0);
waveform2.begin(waveforms[wave2]);
waveform2.frequency(freq*2);
waveform2.amplitude(1);
//sgtl5000_1.volume(general_vol);
}
else {
waveform1.amplitude(0);
waveform2.amplitude(0);
sgtl5000_1.disable();
i++;
}
}
// if (analog5.hasChanged()) {
// waveform1.begin(waveforms[wave]);
// }
//
// if (analog6.hasChanged()) {
// waveform2.begin(waveforms[wave2]);
// }
//
// if (analog7.hasChanged()) {
// waveform1.phase(analog7.getValue() * 360.0);
// }
//AudioNoInterrupts();
// use Knob A2 to adjust the frequency of both waveforms
//waveform1.frequency(100.0 + knob_A2 * 900.0);
//waveform2.frequency(100.0 + knob_A2 * 900.0);
// use Knob A3 to adjust the phase of only waveform #1
//waveform1.phase(knob_A3 * 360.0);
//AudioInterrupts();
//Serial.println(analog4.getValue());
//Serial.println(readMux(3));
delay(5);
}
int readMux(byte channel){
byte controlPin[] = {S0, S1, S2, S3};
//byte controlPin2[] = {W0, W1, W2, W3};
for(int i = 0; i < 4; i ++){
digitalWrite(controlPin[i], muxChannel[channel][i]);
}
//read the value at the SIG pin
delayMicroseconds(50);
int val = analogRead(SIG_PIN);
//return the value
return val;
}
int readMux2(byte channel){
byte controlPin[] = {W0, W1, W2, W3};
for(int i = 0; i < 4; i ++){
digitalWrite(controlPin[i], muxChannel[channel][i]);
//Serial.println(muxChannel[channel][i]);
}
//read the value at the SIG pin
delayMicroseconds(50);
int val = analogRead(WIG_PIN);
Serial.println(analogRead(WIG_PIN));
//return the value
return val;
}
| [
"marcog07@ucm.es"
] | marcog07@ucm.es |
879d107ab1cc6c6cb7b4f9a64cc2a4bb8007e470 | e5c0b38c9cc0c0e6155c9d626e299c7b03affd1e | /trunk/Code/Engine/Graphics/StaticMeshes/StaticMesh.cpp | 8e9bb78979af5033d8a1d660a0c4d21c5a8405d0 | [] | no_license | BGCX261/zombigame-svn-to-git | 4e5ec3ade52da3937e2b7d395424c40939657743 | aa9fb16789f1721557085deae123771f5aefc4dd | refs/heads/master | 2020-05-26T21:56:40.088036 | 2015-08-25T15:33:27 | 2015-08-25T15:33:27 | 41,597,035 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,893 | cpp | #include "StaticMesh.h"
#include "RenderManager.h"
#include "Texture/Texture.h"
#include "Vertex/VertexType.h"
#include "Vertex/IndexedVertex.h"
#include "Core.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include "Texture/TextureManager.h"
#include "Shaders/EffectManager.h"
#include "Shaders/EffectTechnique.h"
#include "Exceptions/Exception.h"
#if defined( _DEBUG )
#include "Memory/MemLeaks.h"
#endif // defined( _DEBUG )
using namespace std;
#define _HEADER 0xFF77
#define _FOOTER 0x77FF
CStaticMesh::CStaticMesh()
: m_TechniqueName("")
, m_FileName("")
, m_NumVertexs(0)
, m_NumFaces(0)
, m_Textures(NULL)
, m_Techniques(NULL)
, m_RVs(NULL)
, m_VertexBufferPhysX(0)
, m_IndexBufferPhysX(0)
, m_pV3fSelfIlluminationColor(0)
{
}
CStaticMesh::~CStaticMesh()
{
CHECKED_DELETE(m_pV3fSelfIlluminationColor)
m_Techniques.clear();
m_Textures.clear();
Release();
}
bool CStaticMesh::Load(const std::string &FileName)
{
m_FileName = FileName;
ifstream l_File(m_FileName.c_str(), ios::in|ios::binary);
if(l_File.is_open())
{
unsigned short l_Header = 0;
unsigned short l_CantMateriales = 0;
//unsigned short l_CantIndices = 0;
unsigned short l_VertexType = 0;
unsigned short l_CountTextures = 0;
unsigned short l_CantVertices = 0;
unsigned short l_IndexCount = 0;
unsigned short l_Footer = 0;
std::vector<unsigned short> l_vVertexTypes;
//Lectura del Header
l_File.read((char *)&l_Header, sizeof(unsigned short));
if(l_Header != _HEADER)
{
LOGGER->AddNewLog(ELL_WARNING, "CStaticMesh::Load Encabezado incorrecto al leer el archivo '%'",m_FileName);
l_File.close();
return false;
}
//Cantidad de materiales
l_File.read((char *)&l_CantMateriales, sizeof(unsigned short));
std::string l_TechniqueName;
//ciclo para cada material
for(int j = 0; j < l_CantMateriales; j++)
{
//Lectura del Vertex Type
l_File.read((char *)&l_VertexType, sizeof(unsigned short));
//se verifica si tiene alpha_test
if (l_VertexType & ALPHA_TEST)
{
l_VertexType = l_VertexType ^ ALPHA_TEST;
l_TechniqueName=CORE->GetEffectManager()->GetTechniqueEffectNameByVertexDefault(l_VertexType);
if (m_pV3fSelfIlluminationColor != NULL)
{
m_Techniques.push_back(CORE->GetEffectManager()->GetEffectTechnique(l_TechniqueName + "_SI_AT"));
}
else
{
m_Techniques.push_back(CORE->GetEffectManager()->GetEffectTechnique(l_TechniqueName + "_AT"));
}
}
else if(l_VertexType & ALPHA_BLEND)
{
l_VertexType = l_VertexType ^ ALPHA_BLEND;
l_TechniqueName=CORE->GetEffectManager()->GetTechniqueEffectNameByVertexDefault(l_VertexType);
if (m_pV3fSelfIlluminationColor != NULL)
{
m_Techniques.push_back(CORE->GetEffectManager()->GetEffectTechnique(l_TechniqueName + "_SI_AB"));
}
else
{
m_Techniques.push_back(CORE->GetEffectManager()->GetEffectTechnique(l_TechniqueName + "_AB"));
}
}
else // en los otros casos en los que no hay transparencias
{
l_TechniqueName = CORE->GetEffectManager()->GetTechniqueEffectNameByVertexDefault(l_VertexType);
if (m_pV3fSelfIlluminationColor != NULL)
{
m_Techniques.push_back(CORE->GetEffectManager()->GetEffectTechnique(l_TechniqueName + "_SI"));
}
else
{
m_Techniques.push_back(CORE->GetEffectManager()->GetEffectTechnique(l_TechniqueName));
}
}
l_vVertexTypes.push_back(l_VertexType);
//Cantidad de texturas
l_File.read((char *)&l_CountTextures, sizeof(unsigned short));
//Lectura de materiales. Se leen "l_CountTextures" materiales.
m_Textures.push_back(std::vector<CTexture *>());
for(int i = 0; i < l_CountTextures; i++)
{
//Path Size
unsigned short l_pathSize = 0;
l_File.read((char *)&l_pathSize, sizeof(unsigned short));
//Reading Path
char * l_pathMaterial = new char[l_pathSize+1];
int temp = sizeof(l_pathMaterial);
l_File.read(l_pathMaterial, sizeof(char) * (l_pathSize+1));
//Carga la textura y la introduce en su vector
CTexture *l_Texture=CORE->GetTextureManager()->GetTexture(l_pathMaterial);
m_Textures[j].push_back(l_Texture);
CHECKED_DELETE_ARRAY(l_pathMaterial);
}
}//fin de ciclo para cada material
//l_File.read((char *)&l_CantIndices, sizeof(unsigned short));
for(int j = 0; j < l_CantMateriales; j++)
{
l_File.read((char *)&l_CantVertices, sizeof(unsigned short));
int l_Size=0;
l_VertexType = l_vVertexTypes.at(j);
if(l_VertexType == TNORMAL_TEXTURE1_VERTEX::GetVertexType())
{
l_Size=sizeof(TNORMAL_TEXTURE1_VERTEX);
}
else if(l_VertexType == TNORMAL_TEXTURE2_VERTEX::GetVertexType())
{
l_Size=sizeof(TNORMAL_TEXTURE2_VERTEX);
}
else if(l_VertexType == TNORMAL_COLORED_VERTEX::GetVertexType())
{
l_Size=sizeof(TNORMAL_COLORED_VERTEX);
}
else if(l_VertexType == TNORMAL_TANGENT_BINORMAL_TEXTURED::GetVertexType())
{
l_Size=sizeof(TNORMAL_TANGENT_BINORMAL_TEXTURED);
}
else if(l_VertexType == TNORMAL_TANGENT_BINORMAL_TEXTURED2::GetVertexType())
{
l_Size=sizeof(TNORMAL_TANGENT_BINORMAL_TEXTURED2);
}
char *l_Vtxs=new char[l_Size*l_CantVertices];
l_File.read((char *)&l_Vtxs[0],l_Size*l_CantVertices);
l_File.read((char *)&l_IndexCount, sizeof(unsigned short));
unsigned short *l_Indxs = new unsigned short[l_IndexCount];
l_File.read((char *)&l_Indxs[0],sizeof(unsigned short)*l_IndexCount);
CRenderableVertexs * l_RV;
//-----------------------------------
if(l_VertexType == TNORMAL_TEXTURE1_VERTEX::GetVertexType())
{
l_RV = new CIndexedVertex<TNORMAL_TEXTURE1_VERTEX>(CORE->GetRenderManager(), l_Vtxs, l_Indxs, l_CantVertices, l_IndexCount);
}
else if(l_VertexType == TNORMAL_TEXTURE2_VERTEX::GetVertexType())
{
l_RV = new CIndexedVertex<TNORMAL_TEXTURE2_VERTEX>(CORE->GetRenderManager(), l_Vtxs, l_Indxs, l_CantVertices, l_IndexCount);
}
else if(l_VertexType == TNORMAL_COLORED_VERTEX::GetVertexType())
{
l_RV = new CIndexedVertex<TNORMAL_COLORED_VERTEX>(CORE->GetRenderManager(), l_Vtxs, l_Indxs, l_CantVertices, l_IndexCount);
}
else if(l_VertexType == TNORMAL_TANGENT_BINORMAL_TEXTURED::GetVertexType())
{
//calcular en el vertex buffer las tangenciales y binormales
CalcTangentsAndBinormals(l_Vtxs, l_Indxs, l_CantVertices, l_IndexCount, sizeof(TNORMAL_TANGENT_BINORMAL_TEXTURED), 0, 12, 28, 44, 60);
TNORMAL_TANGENT_BINORMAL_TEXTURED *l_HackVtxs=(TNORMAL_TANGENT_BINORMAL_TEXTURED *)&l_Vtxs[0];
Vect3f l_Min, l_Max;
for(int b=0;b<l_CantVertices;++b)
{
if(b==0)
{
l_Min=Vect3f(l_HackVtxs[b].x,l_HackVtxs[b].y,l_HackVtxs[b].z);
l_Max=Vect3f(l_HackVtxs[b].x,l_HackVtxs[b].y,l_HackVtxs[b].z);
}
if(l_HackVtxs[b].x<l_Min.x)
l_Min.x=l_HackVtxs[b].x;
if(l_HackVtxs[b].y<l_Min.y)
l_Min.y=l_HackVtxs[b].y;
if(l_HackVtxs[b].z<l_Min.z)
l_Min.z=l_HackVtxs[b].z;
if(l_HackVtxs[b].x>l_Max.x)
l_Max.x=l_HackVtxs[b].x;
if(l_HackVtxs[b].y>l_Max.y)
l_Max.y=l_HackVtxs[b].y;
if(l_HackVtxs[b].z>l_Max.z)
l_Max.z=l_HackVtxs[b].z;
}
l_RV = new CIndexedVertex<TNORMAL_TANGENT_BINORMAL_TEXTURED>(CORE->GetRenderManager(), l_Vtxs, l_Indxs, l_CantVertices, l_IndexCount);
}
else if(l_VertexType == TNORMAL_TANGENT_BINORMAL_TEXTURED2::GetVertexType())
{
//calcular en el vertex buffer las tangenciales y binormales
CalcTangentsAndBinormals(l_Vtxs, l_Indxs, l_CantVertices, l_IndexCount, sizeof(TNORMAL_TANGENT_BINORMAL_TEXTURED2), 0, 12, 28, 44, 60);
l_RV = new CIndexedVertex<TNORMAL_TANGENT_BINORMAL_TEXTURED2>(CORE->GetRenderManager(), l_Vtxs, l_Indxs, l_CantVertices, l_IndexCount);
}
//CRenderableVertexs *l_RV = new CIndexedVertex<TNORMAL_COLORED_TEXTURE1_VERTEX>(CORE->GetRenderManager(), l_Vtxs, l_Indxs, l_CantVertices, l_IndexCount);
this->m_NumVertexs = l_IndexCount;
this->m_NumFaces = l_IndexCount / 3;
m_RVs.push_back(l_RV);
//-----------------------------------
//Prueba PhysX
for(int i = 0; i < l_CantVertices; i++)
{
D3DXVECTOR3 *v1=(D3DXVECTOR3 *) &l_Vtxs[i*l_Size];
m_VertexBufferPhysX.push_back(Vect3f(v1->x,v1->y,v1->z));
}
uint32 l_Index;
for(int i = 0; i < l_IndexCount; i++)
{
l_Index = (uint32) l_Indxs[i];
m_IndexBufferPhysX.push_back(l_Index);
}
//-----------------------------------
CHECKED_DELETE_ARRAY(l_Vtxs);
CHECKED_DELETE_ARRAY(l_Indxs);
}
l_File.read((char *)&l_Footer, sizeof(unsigned short));
if(l_Footer != _FOOTER)
{
LOGGER->AddNewLog(ELL_ERROR, "CStaticMesh::Load->Pie de archivo incorrecto al leer el archivo '%s'",m_FileName.c_str());
l_File.close();
return false;
}
l_File.close();
}
else
{
std::string msg_error = "CStaticMesh::Load->Error al abrir el archivo. El archivo no existe: ";
msg_error.append(m_FileName.c_str());
LOGGER->AddNewLog(ELL_ERROR, msg_error.c_str());
//throw CException(__FILE__, __LINE__, msg_error);
return false;
}
return true;
}
bool CStaticMesh::ReLoad()
{
Release();
return Load(m_FileName);
}
void CStaticMesh::Render(CRenderManager *RM) const
{
vector<CRenderableVertexs*>::const_iterator l_Iter = this->m_RVs.begin();
for(int i=0;l_Iter != m_RVs.end();++i, ++l_Iter)
{
for(size_t j=0;j<m_Textures[i].size();++j)
{
m_Textures[i][j]->Activate(j);
}
CEffectTechnique *l_Technique=CORE->GetEffectManager()->GetStaticMeshTechnique();
if(l_Technique==NULL)
l_Technique=m_Techniques[i];
if(l_Technique!=NULL)
{
l_Technique->BeginRender(m_pV3fSelfIlluminationColor);
(*l_Iter)->Render(RM, l_Technique);
}
}
}
void CStaticMesh::Release()
{
vector<CRenderableVertexs*>::iterator l_Iter = m_RVs.begin();
while(l_Iter != m_RVs.end())
{
CHECKED_DELETE(*l_Iter);
++l_Iter;
}
m_RVs.clear();
}
| [
"you@example.com"
] | you@example.com |
29fde03134c5cf12e5099bbe300a2db94d4c3a97 | 22c04c1d53f4bb526766c38619261da4b3f2494a | /Scoreboard_v1.0/Scoreboard_v1.0.ino | cf687621220d0b3b719fde744e19988a8540eaf1 | [] | no_license | educoay/Scoreboard_rev.Arduino | 3fd48440ac8289d759868b6de32088709956cd84 | 2dcee8fb37852a81b36cc318e49b6dbe11507c35 | refs/heads/master | 2020-12-20T11:21:12.230193 | 2019-12-27T23:10:05 | 2019-12-27T23:10:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,671 | ino | /*
Скетч к проекту "Бегущая строка"
Страница проекта (схемы, описания): https://alexgyver.ru/GyverString/
Исходники на GitHub: https://github.com/AlexGyver/GyverString/
Нравится, как написан код? Поддержи автора! https://alexgyver.ru/support_alex/
Автор: AlexGyver, AlexGyver Technologies, 2019
https://AlexGyver.ru/
Версия 1.1: прошивка оптимизирована под широкие матрицы (до 80 пикс)
Версия 1.3: исправлен баг с красным цветом
*/
#define C_BLACK 0x000000
#define C_GREEN 0x00FF00
#define C_RED 0xFF0000
#define C_BLUE 0x0000FF
#define C_PURPLE 0xFF00FF
#define C_YELLOW 0xFFFF00
#define C_CYAN 0x00FFFF
#define C_WHITE 0xFFFFFF
/*
String text1 = "READYBOX FOR: ";
#define COLOR1 C_GREEN
String text2 = "Andreas HERIG, Vladimir SOSHNIN, Radovan PLCH ";
#define COLOR2 C_PURPLE
String text3 = "BE READY: ";
#define COLOR3 C_YELLOW
String text4 = "Michael MISHIN ";
#define COLOR4 C_PURPLE
String text5 = "ON START: ";
#define COLOR5 C_RED
String text6 = "Vladyslav CHEBANOV ";
#define COLOR6 C_PURPLE
String text7 = "";
#define COLOR7 C_YELLOW
String text8 = "";
#define COLOR8 C_PURPLE
String text9 = "Wind speed and direction: ";
#define COLOR9 C_CYAN
String text10 = "12 m/s, 17 deg. ";
#define COLOR10 C_PURPLE
*/
String text1 = "READYBOX FOR: ";
#define COLOR1 C_GREEN
String text2 = "A. HERIG ";
#define COLOR2 C_PURPLE
String text3 = "BE READY: ";
#define COLOR3 C_YELLOW
String text4 = "M. MISHIN ";
#define COLOR4 C_PURPLE
String text5 = "ON START: ";
#define COLOR5 C_RED
String text6 = "V. CHEBANOV ";
#define COLOR6 C_PURPLE
String text7 = "";
#define COLOR7 C_YELLOW
String text8 = "";
#define COLOR8 C_PURPLE
String text9 = "Wind: ";
#define COLOR9 C_CYAN
String text10 = "12 m/s ";
#define COLOR10 C_PURPLE
String statictxt1 = "0123456789";
String statictxt2 = "ABCDEFGHIJ";
// ================ НАСТРОЙКИ ================
#define BRIGHTNESS 120 // стандартная яркость (0-255)
#define D_TEXT_SPEED 10 // скорость бегущего текста по умолчанию (мс)
#define CURRENT_LIMIT 2000 // лимит по току в миллиамперах, автоматически управляет яркостью (пожалей свой блок питания!) 0 - выключить лимит
#define WIDTH 60 // ширина матрицы
#define HEIGHT 8 // высота матрицы
#define SEGMENTS 1 // диодов в одном "пикселе" (для создания матрицы из кусков ленты)
#define COLOR_ORDER GRB // порядок цветов на ленте. Если цвет отображается некорректно - меняйте. Начать можно с RGB
#define MATRIX_TYPE 0 // тип матрицы: 0 - зигзаг, 1 - параллельная
#define CONNECTION_ANGLE 0 // угол подключения: 0 - левый нижний, 1 - левый верхний, 2 - правый верхний, 3 - правый нижний
#define STRIP_DIRECTION 0 // направление ленты из угла: 0 - вправо, 1 - вверх, 2 - влево, 3 - вниз
// при неправильной настрйоке матрицы вы получите предупреждение "Wrong matrix parameters! Set to default"
// шпаргалка по настройке матрицы здесь! https://alexgyver.ru/matrix_guide/
// ============ ДЛЯ РАЗРАБОТЧИКОВ ============
// ПИНЫ
#define LED_PIN 4
// БИБЛИОТЕКИ
//#include <FastLED.h>
#define COLOR_DEBTH 2 // цветовая глубина: 1, 2, 3 (в байтах)
#define ORDER_GRB // ORDER_GRB / ORDER_RGB
#include "microLED.h"
#include "fonts.h"
const int NUM_LEDS = WIDTH * HEIGHT * SEGMENTS;
LEDdata leds[NUM_LEDS];
microLED strip(leds, NUM_LEDS, LED_PIN); // объект лента
uint32_t scrollTimer;
String runningText = "";
boolean loadingFlag, fullTextFlag;
const uint32_t textColors[] PROGMEM = {
COLOR1,
COLOR2,
COLOR3,
COLOR4,
COLOR5,
COLOR6,
COLOR7,
COLOR8,
COLOR9,
COLOR10,
};
int colorChange[10];
void setup() {
//Serial.begin(9600);
randomSeed(analogRead(0));
// настройки ленты
//strip.addLeds<WS2812, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
strip.setBrightness(BRIGHTNESS);
//if (CURRENT_LIMIT > 0) strip.setMaxPowerInVoltsAndMilliamps(5, CURRENT_LIMIT);
strip.clear();
strip.show();
runningText = String(text1) + text2 + text3 + text4 + text5 + text6 + text7 + text8 + text9 + text10;
colorChange[0] = stringLength(text1);
colorChange[1] = colorChange[0] + stringLength(text2);
colorChange[2] = colorChange[1] + stringLength(text3);
colorChange[3] = colorChange[2] + stringLength(text4);
colorChange[4] = colorChange[3] + stringLength(text5);
colorChange[5] = colorChange[4] + stringLength(text6);
colorChange[6] = colorChange[5] + stringLength(text7);
colorChange[7] = colorChange[6] + stringLength(text8);
colorChange[8] = colorChange[7] + stringLength(text9);
colorChange[9] = colorChange[8] + stringLength(text10);
}
void loop() {
// fillString(runningText);
// delay(1000);
// fillString(statictxt1);
// delay(5000);
// fillString(statictxt2);
// delay(5000);
fillFrame(statictxt1);
delay(5000);
fillFrame(statictxt2);
delay(5000);
}
| [
"dyagilev@gmail.com"
] | dyagilev@gmail.com |
87f28394715944e36b38429726920ac0944b32b0 | 8abbb97e460df68c4bed5ccaa04983bfceb9b29d | /practicas/mergeSort.cpp | 594f438e25506c6f991c68a86783acc2e80bce26 | [] | no_license | JReneHS/Comp-Programming | e89c64c0d240d95fbf36358097ab15166a3b977b | 7af46dd8682ffc96245730669399194c9412c5ce | refs/heads/main | 2023-09-02T09:09:06.672628 | 2021-11-23T21:18:35 | 2021-11-23T21:18:35 | 354,477,551 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,918 | cpp | #include <bits/stdc++.h>
using namespace std;
void merge(vector<int> &arr,int lef,int rig, int mid) {
//Variables de uso muliple
int i,j,k,n1,n2;
//Pivotes para control de los bucles
n1 = mid-lef+1;
n2 = rig-mid;
//Arrays auxiliares
vector<int> auxL(n1);
vector<int> auxR(n2);
//Copia de los valores a las array auxiliares
for(i = 0; i < n1;++i) auxL[i] = arr[lef+i];
for(j = 0; j < n2;++j) auxR[j] = arr[mid+1+j];
i = j = 0;
k = lef;
//Comparacion y ordenamiento usando las arrays auxiliares
while(i < n1 && j < n2) {
if(auxL[i] <= auxR[j]) {
arr[k] = auxL[i];
i++;
} else {
arr[k] = auxR[j];
j++;
}
k++;
}
//Copiando los elementos restantes de los auxiliares en caso que haya alguno
while(i < n1) {
arr[k] = auxL[i];
k++;
i++;
}
while(j < n2) {
arr[k] = auxR[j];
k++;
j++;
}
}
void mergeSort(vector<int> &arr,int lef,int rig){
//Mientras el valor de left sea menor al de right
if(lef < rig) {
//entero para obtener el valor medio del array
auto mid = lef + (rig - lef)/2;
//LLamada recursiva a mergeSort para array Izquierdo
mergeSort(arr, lef,mid);
//LLamada recursiva a mergeSort para arrya Derecho
mergeSort(arr, mid+1,rig);
//LLamada a la funcion de mezcla
merge(arr,lef,rig,mid);
}
}
int main() {
//array que se va a ordenar
vector<int> arr;
//entero auxiliar para leer de la entrada estandar
int c;
//mientras haya que leer en el buffer almacena en arr
while(cin>>c)arr.push_back(c);
//Impresion de los valores leidos
for(auto x: arr)cout<<x<<" ";
cout<<'\n'<<endl;
//Llamada a la funcion merge sort
mergeSort(arr,0,arr.size()-1);
//Impresion de los valores leidos
for(auto x: arr)cout<<x<<" ";
cout<<'\n'<<endl;
return 0;
}
| [
"jhernandezs1509@alumno.ipn.mx"
] | jhernandezs1509@alumno.ipn.mx |
d0f6d40fe1fff56d3fc975026372e3ee8ec17efa | bd2ba8f1364a12dc0ea10003a98c4ef24f34b9bc | /src/make_sift_descriptor_file.cpp | 7acceea534469a970e7e8c34987ef2baf33381af | [] | no_license | kumpakri/registration-in-dynamic-environment | 921f92c0b823abe74d791f65be95994180b963c7 | 155bf0b94674a22cb27234d9d451905d284ceb39 | refs/heads/master | 2020-08-29T10:00:34.059880 | 2019-10-28T09:31:47 | 2019-10-28T09:36:56 | 217,998,679 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,249 | cpp | /**
* \file make_sift_descriptor_file.cpp
*
* \brief Creates SIFT descriptor file.
*
* \param 1 nFeatures
* \param 2 nOctaveLayers
* \param 3 contrastThreshold
* \param 4 edgeThreshold
* \param 5 sigma
* \param 6 path to positions file
* \param 7 path to image folder
* \param 8 output path for used positions file
* \param 9 output path for descriptors file
*
* \author kristyna kumpanova
*
* Contact: kumpakri@gmail.com
*
* Created on: July 02 2018
*/
#include <opencv2/opencv.hpp>
#include "Data_processing.h"
#include "Utils.h"
int main(int argc, char **argv)
{
// check if arguments ok
if ( ! (argc>9 && file_exists(argv[6]) && file_exists(argv[7]) ) )
{
std::cout << "Error: missing arguments or invalid file path.\n";
return -1;
}
//SIFT detector setting
float nFeatures = atof(argv[1]);
float nOctaveLayers = atof(argv[2]);
float contrastThreshold = atof(argv[3]);
float edgeThreshold = atof(argv[4]);
float sigma = atof(argv[5]);
cv::Mat all_descriptors;
cv::FeatureDetector* detector;
detector = new cv::SiftFeatureDetector( nFeatures, nOctaveLayers, contrastThreshold, edgeThreshold, sigma);
make_descriptor_file(argv[6], argv[7], argv[9], argv[8], &all_descriptors, detector);
return 0;
} | [
"kumpakri@gmail.com"
] | kumpakri@gmail.com |
3c0d836107f7b77c3fad63d1dbb630fe9450afa3 | 03ff59ad83be606ce82349173765ca2e5ab3c914 | /BFS_7562_나이트의이동.cpp | 7d70ee3ed7241605f4feed9629e0273eba69523d | [] | no_license | koreantique/CodingStudy | d59ada31fc6af3e1b39583a99df1fc27be11c0c4 | 405c5bfb79bd7f656751c77794d4a703c2172470 | refs/heads/master | 2022-07-28T07:47:28.609203 | 2020-05-22T06:46:24 | 2020-05-22T06:46:24 | 259,563,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,019 | cpp | #include <iostream>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;
int d[301][301];
int c[301][301];
int dx[] = {-2,-1,1,2,-2,-1,1,2};
int dy[] = {-1,-2,-2,-1,1,2,2,1};
int n;
int cnt = 0;
void bfs(int x, int y, int cnt){
queue<pair<int,int>> q;
q.push(make_pair(x,y));
while(!q.empty()){
int x = q.front().first;
int y = q.front().second;
q.pop();
for(int k=0; k<8; k++){
int nx = x + dx[k];
int ny = y + dy[k];
if(0 <= nx && nx < n && 0 <= ny && ny < n){
if(d[nx][ny] == 0 && c[nx][ny] != 0){
q.push(make_pair(nx,ny));
cnt += 1;
}
}
}
}
}
int main(){
int t;
int q,w,e,r;
cin >> t;
while(t--){
cin >> n;
memset(d,-1,sizeof(d));
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
d[i][j] = 0;
}
}
}
} | [
"koreantique_@naver.com"
] | koreantique_@naver.com |
995dafd25e152defc978ef66ea666665ccdaddeb | ed444c4a0ed1fe679da64b81ec6aa1ddf885a185 | /Foundation/System/Thread/Thread.h | a35ae338c6c8567cb7a5a51a7d4e7f78208ab2b4 | [] | no_license | swaphack/CodeLib | 54e07db129d38be0fd55504ef917bbe522338aa6 | fff8ed54afc334e1ff5e3dd34ec5cfcf6ce7bdc9 | refs/heads/master | 2022-05-16T20:31:45.123321 | 2022-05-12T03:38:45 | 2022-05-12T03:38:45 | 58,099,874 | 1 | 0 | null | 2016-05-11T09:46:07 | 2016-05-05T02:57:24 | C++ | GB18030 | C++ | false | false | 998 | h | #pragma once
#include <functional>
#include <thread>
namespace sys
{
// 线程
class Thread
{
public:
friend class ThreadPool;
// 无效的线程id
static const int32_t INVALID_THREAD_ID = -1;
public:
Thread();
~Thread();
public:
// 执行
template<class _Fn, class... _Args>
void startWithParams(_Fn&& handler, _Args&&... _Ax);
// 执行
void start(const std::function<void()>& handler);
// 剥离执行
bool detach();
// 堵塞执行
bool join();
// 停止
bool isFinish() const;
// 获取线程id
int32_t getID() const;
private:
// 控制线程
std::thread m_pThread;
// 线程id
size_t m_nID = 0;
// 是否结束
bool m_bFinish = false;
};
template<class _Fn, class... _Args>
void Thread::startWithParams(_Fn&& handler, _Args&&... _Ax)
{
m_pThread = std::thread([=](_Args&&... _Bx){
do
{
handler(_Bx...);
m_bFinish = true;
} while (0);
}, _Ax...);
m_nID = m_pThread.get_id().hash();
m_bFinish = false;
}
} | [
"809406730@qq.com"
] | 809406730@qq.com |
7581acb310afb7c5277669879a62f11c9ff80d7e | 0c9958ed35900fffb025aa6526527e7fc63a38b0 | /glengine.cpp | 42a04687744e75ef3e31884b029645c67815abe9 | [] | no_license | on62/fltk_opengl | 7dbea0bfe7a02cf1123a8a2dadf2905decbbca76 | db0e97aa447f41b85c5dd46961232a67c5bf6c86 | refs/heads/master | 2021-05-27T23:18:32.537044 | 2014-08-16T14:06:22 | 2014-08-16T14:06:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,683 | cpp | #include "glengine.h"
void GLEngine::InitializeProgram(std::vector<shaderName> & shaderNames)
{
// std::string strVertexShader = getFile("v.perspective.shader");
// std::string strFragmentShader = getFile("fragment.shader");
std::vector<GLuint> shaderList;
std::vector<shaderName>::iterator it;
for( it = shaderNames.begin(); it != shaderNames.end(); it++) {
std::string strShader(getFile(it->second.c_str()));
shaderList.push_back(CreateShader(it->first,strShader));
}
// shaderList.push_back(CreateShader(GL_VERTEX_SHADER, strVertexShader));
// shaderList.push_back(CreateShader(GL_FRAGMENT_SHADER, strFragmentShader));
theProgram = CreateProgram(shaderList);
std::for_each(shaderList.begin(), shaderList.end(), glDeleteShader);
// glUseProgram(0);
//Perspective Uniform Matrix.
// perspectiveMatrixUnif = glGetUniformLocation(theProgram, "perspectiveMatrix");
// SetPerspective();
}
GLuint GLEngine::CreateShader(GLenum eShaderType, const std::string &strShaderFile) {
GLuint shader = glCreateShader(eShaderType);
const char *strFileData = strShaderFile.c_str();
glShaderSource(shader, 1, &strFileData, NULL);
glCompileShader(shader);
GLint status;
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE) {
GLint infoLogLength;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar *strInfoLog = new GLchar[infoLogLength + 1];
glGetShaderInfoLog(shader, infoLogLength, NULL, strInfoLog);
const char *strShaderType = NULL;
switch(eShaderType) {
case GL_VERTEX_SHADER: strShaderType = "vertex"; break;
case GL_GEOMETRY_SHADER: strShaderType = "geometry"; break;
case GL_FRAGMENT_SHADER: strShaderType = "fragment"; break;
}
fprintf(stderr, "Compile failure in %s shader:\n%s\n", strShaderType, strInfoLog);
delete[] strInfoLog;
}
return shader;
}
GLuint GLEngine::CreateProgram(const std::vector<GLuint> &shaderList) {
GLuint program = glCreateProgram();
for(size_t iLoop = 0; iLoop < shaderList.size(); iLoop++)
glAttachShader(program, shaderList[iLoop]);
glLinkProgram(program);
CheckProgram(program);
for( size_t iLoop = 0; iLoop < shaderList.size(); iLoop++)
glDetachShader(program, shaderList[iLoop]);
return program;
}
void GLEngine::CheckProgram(GLuint & program) {
GLint status;
glGetProgramiv (program, GL_LINK_STATUS, &status);
if (status == GL_FALSE) {
GLint infoLogLength;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar *strInfoLog = new GLchar[infoLogLength + 1];
glGetProgramInfoLog(program, infoLogLength, NULL, strInfoLog);
fprintf(stderr, "Linker failure: %s\n", strInfoLog);
delete[] strInfoLog;
}
}
| [
"j.gleesawn@gmail.com"
] | j.gleesawn@gmail.com |
c848896d11028cfa4fa9bd48a142ca941566ac1f | 69312fc3709f1e0007e9def5523cd0988081a7d2 | /sources/Crossword/app/console.h | 8f68300d3b42c10b9d10c2aa00cefae3680d3d6e | [] | no_license | Olieaw/--Crossword---Mini--Game-- | 792444dfc8a440d51745e999802a378a6f4ecd79 | 65cee2e85a12a4e556d216a643b09b6612a40239 | refs/heads/master | 2021-01-18T22:05:55.977251 | 2016-10-05T12:59:47 | 2016-10-05T12:59:47 | 52,116,312 | 2 | 3 | null | 2016-04-30T14:31:00 | 2016-02-19T21:04:41 | C++ | UTF-8 | C++ | false | false | 375 | h | #ifndef CONSOLE_H
#define CONSOLE_H
#include "vocalbulary.h"
#include "field.h"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <cstring>
class Console
{
public:
Console();
void Menu();
void PrintWords(std::vector<std::string> str);
void PrintField(std::vector<std::vector<std::string>> field);
};
#endif // CONSOLE_H
| [
"olieaw1998@yandex.ru"
] | olieaw1998@yandex.ru |
aaabceaa5b153e75119855bb8377a8135d77a9b7 | 3cf1c3336e48023d06cd3fbaf6e1a157030f6f4b | /Eigen/src/SVD/BDCSVD.h | e8bfa26c0df8bef8fd5d769ec43f9466923897c9 | [] | no_license | pochemuto/MaterialSolver | e55399d7ad2e03fc55214007565c4e7d0da4b694 | aaeea0bf1ead818801111a6467fa9789d53c8dc9 | refs/heads/master | 2021-01-25T03:49:40.147690 | 2015-05-20T21:49:51 | 2015-05-20T21:49:51 | 33,502,329 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45,101 | h | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// We used the "A Divide-And-Conquer Algorithm for the Bidiagonal SVD"
// research report written by Ming Gu and Stanley C.Eisenstat
// The code variable names correspond to the names they used in their
// report
//
// Copyright (C) 2013 Gauthier Brun <brun.gauthier@gmail.com>
// Copyright (C) 2013 Nicolas Carre <nicolas.carre@ensimag.fr>
// Copyright (C) 2013 Jean Ceccato <jean.ceccato@ensimag.fr>
// Copyright (C) 2013 Pierre Zoppitelli <pierre.zoppitelli@ensimag.fr>
// Copyright (C) 2013 Jitse Niesen <jitse@maths.leeds.ac.uk>
// Copyright (C) 2014 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#ifndef EIGEN_BDCSVD_H
#define EIGEN_BDCSVD_H
// #define EIGEN_BDCSVD_DEBUG_VERBOSE
// #define EIGEN_BDCSVD_SANITY_CHECKS
namespace Eigen {
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
IOFormat bdcsvdfmt(8, 0, ", ", "\n", " [", "]");
#endif
template<typename _MatrixType> class BDCSVD;
namespace internal {
template<typename _MatrixType>
struct traits<BDCSVD<_MatrixType> >
{
typedef _MatrixType MatrixType;
};
} // end namespace internal
/** \ingroup SVD_Module
*
*
* \class BDCSVD
*
* \brief class Bidiagonal Divide and Conquer SVD
*
* \param MatrixType the type of the matrix of which we are computing the SVD decomposition
* We plan to have a very similar interface to JacobiSVD on this class.
* It should be used to speed up the calcul of SVD for big matrices.
*/
template<typename _MatrixType>
class BDCSVD : public SVDBase<BDCSVD<_MatrixType> >
{
typedef SVDBase<BDCSVD> Base;
public:
using Base::rows;
using Base::cols;
using Base::computeU;
using Base::computeV;
typedef _MatrixType MatrixType;
typedef typename MatrixType::Scalar Scalar;
typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;
enum {
RowsAtCompileTime = MatrixType::RowsAtCompileTime,
ColsAtCompileTime = MatrixType::ColsAtCompileTime,
DiagSizeAtCompileTime = EIGEN_SIZE_MIN_PREFER_DYNAMIC(RowsAtCompileTime, ColsAtCompileTime),
MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime,
MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime,
MaxDiagSizeAtCompileTime = EIGEN_SIZE_MIN_PREFER_FIXED(MaxRowsAtCompileTime, MaxColsAtCompileTime),
MatrixOptions = MatrixType::Options
};
typedef typename Base::MatrixUType MatrixUType;
typedef typename Base::MatrixVType MatrixVType;
typedef typename Base::SingularValuesType SingularValuesType;
typedef Matrix<Scalar, Dynamic, Dynamic> MatrixX;
typedef Matrix<RealScalar, Dynamic, Dynamic> MatrixXr;
typedef Matrix<RealScalar, Dynamic, 1> VectorType;
typedef Array<RealScalar, Dynamic, 1> ArrayXr;
typedef Array<Index,1,Dynamic> ArrayXi;
/** \brief Default Constructor.
*
* The default constructor is useful in cases in which the user intends to
* perform decompositions via BDCSVD::compute(const MatrixType&).
*/
BDCSVD() : m_algoswap(16), m_numIters(0)
{}
/** \brief Default Constructor with memory preallocation
*
* Like the default constructor but with preallocation of the internal data
* according to the specified problem size.
* \sa BDCSVD()
*/
BDCSVD(Index rows, Index cols, unsigned int computationOptions = 0)
: m_algoswap(16), m_numIters(0)
{
allocate(rows, cols, computationOptions);
}
/** \brief Constructor performing the decomposition of given matrix.
*
* \param matrix the matrix to decompose
* \param computationOptions optional parameter allowing to specify if you want full or thin U or V unitaries to be computed.
* By default, none is computed. This is a bit - field, the possible bits are #ComputeFullU, #ComputeThinU,
* #ComputeFullV, #ComputeThinV.
*
* Thin unitaries are only available if your matrix type has a Dynamic number of columns (for example MatrixXf). They also are not
* available with the (non - default) FullPivHouseholderQR preconditioner.
*/
BDCSVD(const MatrixType& matrix, unsigned int computationOptions = 0)
: m_algoswap(16), m_numIters(0)
{
compute(matrix, computationOptions);
}
~BDCSVD()
{
}
/** \brief Method performing the decomposition of given matrix using custom options.
*
* \param matrix the matrix to decompose
* \param computationOptions optional parameter allowing to specify if you want full or thin U or V unitaries to be computed.
* By default, none is computed. This is a bit - field, the possible bits are #ComputeFullU, #ComputeThinU,
* #ComputeFullV, #ComputeThinV.
*
* Thin unitaries are only available if your matrix type has a Dynamic number of columns (for example MatrixXf). They also are not
* available with the (non - default) FullPivHouseholderQR preconditioner.
*/
BDCSVD& compute(const MatrixType& matrix, unsigned int computationOptions);
/** \brief Method performing the decomposition of given matrix using current options.
*
* \param matrix the matrix to decompose
*
* This method uses the current \a computationOptions, as already passed to the constructor or to compute(const MatrixType&, unsigned int).
*/
BDCSVD& compute(const MatrixType& matrix)
{
return compute(matrix, this->m_computationOptions);
}
void setSwitchSize(int s)
{
eigen_assert(s>3 && "BDCSVD the size of the algo switch has to be greater than 3");
m_algoswap = s;
}
private:
void allocate(Index rows, Index cols, unsigned int computationOptions);
void divide(Index firstCol, Index lastCol, Index firstRowW, Index firstColW, Index shift);
void computeSVDofM(Index firstCol, Index n, MatrixXr& U, VectorType& singVals, MatrixXr& V);
void computeSingVals(const ArrayXr& col0, const ArrayXr& diag, const ArrayXi& perm, VectorType& singVals, ArrayXr& shifts, ArrayXr& mus);
void perturbCol0(const ArrayXr& col0, const ArrayXr& diag, const ArrayXi& perm, const VectorType& singVals, const ArrayXr& shifts, const ArrayXr& mus, ArrayXr& zhat);
void computeSingVecs(const ArrayXr& zhat, const ArrayXr& diag, const ArrayXi& perm, const VectorType& singVals, const ArrayXr& shifts, const ArrayXr& mus, MatrixXr& U, MatrixXr& V);
void deflation43(Index firstCol, Index shift, Index i, Index size);
void deflation44(Index firstColu , Index firstColm, Index firstRowW, Index firstColW, Index i, Index j, Index size);
void deflation(Index firstCol, Index lastCol, Index k, Index firstRowW, Index firstColW, Index shift);
template<typename HouseholderU, typename HouseholderV, typename NaiveU, typename NaiveV>
void copyUV(const HouseholderU &householderU, const HouseholderV &householderV, const NaiveU &naiveU, const NaiveV &naivev);
static void structured_update(Block<MatrixXr,Dynamic,Dynamic> A, const MatrixXr &B, Index n1);
static RealScalar secularEq(RealScalar x, const ArrayXr& col0, const ArrayXr& diag, const ArrayXi &perm, const ArrayXr& diagShifted, RealScalar shift);
protected:
MatrixXr m_naiveU, m_naiveV;
MatrixXr m_computed;
Index m_nRec;
int m_algoswap;
bool m_isTranspose, m_compU, m_compV;
using Base::m_singularValues;
using Base::m_diagSize;
using Base::m_computeFullU;
using Base::m_computeFullV;
using Base::m_computeThinU;
using Base::m_computeThinV;
using Base::m_matrixU;
using Base::m_matrixV;
using Base::m_isInitialized;
using Base::m_nonzeroSingularValues;
public:
int m_numIters;
}; //end class BDCSVD
// Method to allocate and initialize matrix and attributes
template<typename MatrixType>
void BDCSVD<MatrixType>::allocate(Index rows, Index cols, unsigned int computationOptions)
{
m_isTranspose = (cols > rows);
if (Base::allocate(rows, cols, computationOptions))
return;
m_computed = MatrixXr::Zero(m_diagSize + 1, m_diagSize );
m_compU = computeV();
m_compV = computeU();
if (m_isTranspose)
std::swap(m_compU, m_compV);
if (m_compU) m_naiveU = MatrixXr::Zero(m_diagSize + 1, m_diagSize + 1 );
else m_naiveU = MatrixXr::Zero(2, m_diagSize + 1 );
if (m_compV) m_naiveV = MatrixXr::Zero(m_diagSize, m_diagSize);
}// end allocate
template<typename MatrixType>
BDCSVD<MatrixType>& BDCSVD<MatrixType>::compute(const MatrixType& matrix, unsigned int computationOptions)
{
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "\n\n\n======================================================================================================================\n\n\n";
#endif
allocate(matrix.rows(), matrix.cols(), computationOptions);
using std::abs;
//**** step -1 - If the problem is too small, directly falls back to JacobiSVD and return
if(matrix.cols() < m_algoswap)
{
JacobiSVD<MatrixType> jsvd(matrix,computationOptions);
if(computeU()) m_matrixU = jsvd.matrixU();
if(computeV()) m_matrixV = jsvd.matrixV();
m_singularValues = jsvd.singularValues();
m_nonzeroSingularValues = jsvd.nonzeroSingularValues();
m_isInitialized = true;
return *this;
}
//**** step 0 - Copy the input matrix and apply scaling to reduce over/under-flows
RealScalar scale = matrix.cwiseAbs().maxCoeff();
if(scale==RealScalar(0)) scale = RealScalar(1);
MatrixX copy;
if (m_isTranspose) copy = matrix.adjoint()/scale;
else copy = matrix/scale;
//**** step 1 - Bidiagonalization
internal::UpperBidiagonalization<MatrixX> bid(copy);
//**** step 2 - Divide & Conquer
m_naiveU.setZero();
m_naiveV.setZero();
m_computed.topRows(m_diagSize) = bid.bidiagonal().toDenseMatrix().transpose();
m_computed.template bottomRows<1>().setZero();
divide(0, m_diagSize - 1, 0, 0, 0);
//**** step 3 - Copy singular values and vectors
for (int i=0; i<m_diagSize; i++)
{
RealScalar a = abs(m_computed.coeff(i, i));
m_singularValues.coeffRef(i) = a * scale;
if (a == 0)
{
m_nonzeroSingularValues = i;
m_singularValues.tail(m_diagSize - i - 1).setZero();
break;
}
else if (i == m_diagSize - 1)
{
m_nonzeroSingularValues = i + 1;
break;
}
}
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
// std::cout << "m_naiveU\n" << m_naiveU << "\n\n";
// std::cout << "m_naiveV\n" << m_naiveV << "\n\n";
#endif
if(m_isTranspose) copyUV(bid.householderV(), bid.householderU(), m_naiveV, m_naiveU);
else copyUV(bid.householderU(), bid.householderV(), m_naiveU, m_naiveV);
m_isInitialized = true;
return *this;
}// end compute
template<typename MatrixType>
template<typename HouseholderU, typename HouseholderV, typename NaiveU, typename NaiveV>
void BDCSVD<MatrixType>::copyUV(const HouseholderU &householderU, const HouseholderV &householderV, const NaiveU &naiveU, const NaiveV &naiveV)
{
// Note exchange of U and V: m_matrixU is set from m_naiveV and vice versa
if (computeU())
{
Index Ucols = m_computeThinU ? m_diagSize : householderU.cols();
m_matrixU = MatrixX::Identity(householderU.cols(), Ucols);
m_matrixU.topLeftCorner(m_diagSize, m_diagSize) = naiveV.template cast<Scalar>().topLeftCorner(m_diagSize, m_diagSize);
householderU.applyThisOnTheLeft(m_matrixU);
}
if (computeV())
{
Index Vcols = m_computeThinV ? m_diagSize : householderV.cols();
m_matrixV = MatrixX::Identity(householderV.cols(), Vcols);
m_matrixV.topLeftCorner(m_diagSize, m_diagSize) = naiveU.template cast<Scalar>().topLeftCorner(m_diagSize, m_diagSize);
householderV.applyThisOnTheLeft(m_matrixV);
}
}
/** \internal
* Performs A = A * B exploiting the special structure of the matrix A. Splitting A as:
* A = [A1]
* [A2]
* such that A1.rows()==n1, then we assume that at least half of the columns of A1 and A2 are zeros.
* We can thus pack them prior to the the matrix product. However, this is only worth the effort if the matrix is large
* enough.
*/
template<typename MatrixType>
void BDCSVD<MatrixType>::structured_update(Block<MatrixXr,Dynamic,Dynamic> A, const MatrixXr &B, Index n1)
{
Index n = A.rows();
if(n>100)
{
// If the matrices are large enough, let's exploit the sparse structure of A by
// splitting it in half (wrt n1), and packing the non-zero columns.
Index n2 = n - n1;
MatrixXr A1(n1,n), A2(n2,n), B1(n,n), B2(n,n);
Index k1=0, k2=0;
for(Index j=0; j<n; ++j)
{
if( (A.col(j).head(n1).array()!=0).any() )
{
A1.col(k1) = A.col(j).head(n1);
B1.row(k1) = B.row(j);
++k1;
}
if( (A.col(j).tail(n2).array()!=0).any() )
{
A2.col(k2) = A.col(j).tail(n2);
B2.row(k2) = B.row(j);
++k2;
}
}
A.topRows(n1).noalias() = A1.leftCols(k1) * B1.topRows(k1);
A.bottomRows(n2).noalias() = A2.leftCols(k2) * B2.topRows(k2);
}
else
A *= B; // FIXME this requires a temporary
}
// The divide algorithm is done "in place", we are always working on subsets of the same matrix. The divide methods takes as argument the
// place of the submatrix we are currently working on.
//@param firstCol : The Index of the first column of the submatrix of m_computed and for m_naiveU;
//@param lastCol : The Index of the last column of the submatrix of m_computed and for m_naiveU;
// lastCol + 1 - firstCol is the size of the submatrix.
//@param firstRowW : The Index of the first row of the matrix W that we are to change. (see the reference paper section 1 for more information on W)
//@param firstRowW : Same as firstRowW with the column.
//@param shift : Each time one takes the left submatrix, one must add 1 to the shift. Why? Because! We actually want the last column of the U submatrix
// to become the first column (*coeff) and to shift all the other columns to the right. There are more details on the reference paper.
template<typename MatrixType>
void BDCSVD<MatrixType>::divide (Index firstCol, Index lastCol, Index firstRowW, Index firstColW, Index shift)
{
// requires nbRows = nbCols + 1;
using std::pow;
using std::sqrt;
using std::abs;
const Index n = lastCol - firstCol + 1;
const Index k = n/2;
RealScalar alphaK;
RealScalar betaK;
RealScalar r0;
RealScalar lambda, phi, c0, s0;
VectorType l, f;
// We use the other algorithm which is more efficient for small
// matrices.
if (n < m_algoswap)
{
JacobiSVD<MatrixXr> b(m_computed.block(firstCol, firstCol, n + 1, n), ComputeFullU | (m_compV ? ComputeFullV : 0)) ;
if (m_compU)
m_naiveU.block(firstCol, firstCol, n + 1, n + 1).real() = b.matrixU();
else
{
m_naiveU.row(0).segment(firstCol, n + 1).real() = b.matrixU().row(0);
m_naiveU.row(1).segment(firstCol, n + 1).real() = b.matrixU().row(n);
}
if (m_compV) m_naiveV.block(firstRowW, firstColW, n, n).real() = b.matrixV();
m_computed.block(firstCol + shift, firstCol + shift, n + 1, n).setZero();
m_computed.diagonal().segment(firstCol + shift, n) = b.singularValues().head(n);
return;
}
// We use the divide and conquer algorithm
alphaK = m_computed(firstCol + k, firstCol + k);
betaK = m_computed(firstCol + k + 1, firstCol + k);
// The divide must be done in that order in order to have good results. Divide change the data inside the submatrices
// and the divide of the right submatrice reads one column of the left submatrice. That's why we need to treat the
// right submatrix before the left one.
divide(k + 1 + firstCol, lastCol, k + 1 + firstRowW, k + 1 + firstColW, shift);
divide(firstCol, k - 1 + firstCol, firstRowW, firstColW + 1, shift + 1);
if (m_compU)
{
lambda = m_naiveU(firstCol + k, firstCol + k);
phi = m_naiveU(firstCol + k + 1, lastCol + 1);
}
else
{
lambda = m_naiveU(1, firstCol + k);
phi = m_naiveU(0, lastCol + 1);
}
r0 = sqrt((abs(alphaK * lambda) * abs(alphaK * lambda)) + abs(betaK * phi) * abs(betaK * phi));
if (m_compU)
{
l = m_naiveU.row(firstCol + k).segment(firstCol, k);
f = m_naiveU.row(firstCol + k + 1).segment(firstCol + k + 1, n - k - 1);
}
else
{
l = m_naiveU.row(1).segment(firstCol, k);
f = m_naiveU.row(0).segment(firstCol + k + 1, n - k - 1);
}
if (m_compV) m_naiveV(firstRowW+k, firstColW) = 1;
if (r0 == 0)
{
c0 = 1;
s0 = 0;
}
else
{
c0 = alphaK * lambda / r0;
s0 = betaK * phi / r0;
}
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(m_naiveU.allFinite());
assert(m_naiveV.allFinite());
assert(m_computed.allFinite());
#endif
if (m_compU)
{
MatrixXr q1 (m_naiveU.col(firstCol + k).segment(firstCol, k + 1));
// we shiftW Q1 to the right
for (Index i = firstCol + k - 1; i >= firstCol; i--)
m_naiveU.col(i + 1).segment(firstCol, k + 1) = m_naiveU.col(i).segment(firstCol, k + 1);
// we shift q1 at the left with a factor c0
m_naiveU.col(firstCol).segment( firstCol, k + 1) = (q1 * c0);
// last column = q1 * - s0
m_naiveU.col(lastCol + 1).segment(firstCol, k + 1) = (q1 * ( - s0));
// first column = q2 * s0
m_naiveU.col(firstCol).segment(firstCol + k + 1, n - k) = m_naiveU.col(lastCol + 1).segment(firstCol + k + 1, n - k) * s0;
// q2 *= c0
m_naiveU.col(lastCol + 1).segment(firstCol + k + 1, n - k) *= c0;
}
else
{
RealScalar q1 = m_naiveU(0, firstCol + k);
// we shift Q1 to the right
for (Index i = firstCol + k - 1; i >= firstCol; i--)
m_naiveU(0, i + 1) = m_naiveU(0, i);
// we shift q1 at the left with a factor c0
m_naiveU(0, firstCol) = (q1 * c0);
// last column = q1 * - s0
m_naiveU(0, lastCol + 1) = (q1 * ( - s0));
// first column = q2 * s0
m_naiveU(1, firstCol) = m_naiveU(1, lastCol + 1) *s0;
// q2 *= c0
m_naiveU(1, lastCol + 1) *= c0;
m_naiveU.row(1).segment(firstCol + 1, k).setZero();
m_naiveU.row(0).segment(firstCol + k + 1, n - k - 1).setZero();
}
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(m_naiveU.allFinite());
assert(m_naiveV.allFinite());
assert(m_computed.allFinite());
#endif
m_computed(firstCol + shift, firstCol + shift) = r0;
m_computed.col(firstCol + shift).segment(firstCol + shift + 1, k) = alphaK * l.transpose().real();
m_computed.col(firstCol + shift).segment(firstCol + shift + k + 1, n - k - 1) = betaK * f.transpose().real();
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
ArrayXr tmp1 = (m_computed.block(firstCol+shift, firstCol+shift, n, n)).jacobiSvd().singularValues();
#endif
// Second part: try to deflate singular values in combined matrix
deflation(firstCol, lastCol, k, firstRowW, firstColW, shift);
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
ArrayXr tmp2 = (m_computed.block(firstCol+shift, firstCol+shift, n, n)).jacobiSvd().singularValues();
std::cout << "\n\nj1 = " << tmp1.transpose().format(bdcsvdfmt) << "\n";
std::cout << "j2 = " << tmp2.transpose().format(bdcsvdfmt) << "\n\n";
std::cout << "err: " << ((tmp1-tmp2).abs()>1e-12*tmp2.abs()).transpose() << "\n";
static int count = 0;
std::cout << "# " << ++count << "\n\n";
assert((tmp1-tmp2).matrix().norm() < 1e-14*tmp2.matrix().norm());
// assert(count<681);
// assert(((tmp1-tmp2).abs()<1e-13*tmp2.abs()).all());
#endif
// Third part: compute SVD of combined matrix
MatrixXr UofSVD, VofSVD;
VectorType singVals;
computeSVDofM(firstCol + shift, n, UofSVD, singVals, VofSVD);
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(UofSVD.allFinite());
assert(VofSVD.allFinite());
#endif
if (m_compU) structured_update(m_naiveU.block(firstCol, firstCol, n + 1, n + 1), UofSVD, (n+2)/2);
else m_naiveU.middleCols(firstCol, n + 1) *= UofSVD; // FIXME this requires a temporary, and exploit that there are 2 rows at compile time
if (m_compV) structured_update(m_naiveV.block(firstRowW, firstColW, n, n), VofSVD, (n+1)/2);
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(m_naiveU.allFinite());
assert(m_naiveV.allFinite());
assert(m_computed.allFinite());
#endif
m_computed.block(firstCol + shift, firstCol + shift, n, n).setZero();
m_computed.block(firstCol + shift, firstCol + shift, n, n).diagonal() = singVals;
}// end divide
// Compute SVD of m_computed.block(firstCol, firstCol, n + 1, n); this block only has non-zeros in
// the first column and on the diagonal and has undergone deflation, so diagonal is in increasing
// order except for possibly the (0,0) entry. The computed SVD is stored U, singVals and V, except
// that if m_compV is false, then V is not computed. Singular values are sorted in decreasing order.
//
// TODO Opportunities for optimization: better root finding algo, better stopping criterion, better
// handling of round-off errors, be consistent in ordering
// For instance, to solve the secular equation using FMM, see http://www.stat.uchicago.edu/~lekheng/courses/302/classics/greengard-rokhlin.pdf
template <typename MatrixType>
void BDCSVD<MatrixType>::computeSVDofM(Index firstCol, Index n, MatrixXr& U, VectorType& singVals, MatrixXr& V)
{
// TODO Get rid of these copies (?)
// FIXME at least preallocate them
ArrayXr col0 = m_computed.col(firstCol).segment(firstCol, n);
ArrayXr diag = m_computed.block(firstCol, firstCol, n, n).diagonal();
diag(0) = 0;
// Allocate space for singular values and vectors
singVals.resize(n);
U.resize(n+1, n+1);
if (m_compV) V.resize(n, n);
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
if (col0.hasNaN() || diag.hasNaN())
std::cout << "\n\nHAS NAN\n\n";
#endif
// Many singular values might have been deflated, the zero ones have been moved to the end,
// but others are interleaved and we must ignore them at this stage.
// To this end, let's compute a permutation skipping them:
Index actual_n = n;
while(actual_n>1 && diag(actual_n-1)==0) --actual_n;
Index m = 0; // size of the deflated problem
ArrayXi perm(actual_n);
for(Index k=0;k<actual_n;++k)
if(col0(k)!=0)
perm(m++) = k;
perm.conservativeResize(m);
ArrayXr shifts(n), mus(n), zhat(n);
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "computeSVDofM using:\n";
std::cout << " z: " << col0.transpose() << "\n";
std::cout << " d: " << diag.transpose() << "\n";
#endif
// Compute singVals, shifts, and mus
computeSingVals(col0, diag, perm, singVals, shifts, mus);
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << " j: " << (m_computed.block(firstCol, firstCol, n, n)).jacobiSvd().singularValues().transpose().reverse() << "\n\n";
std::cout << " sing-val: " << singVals.transpose() << "\n";
std::cout << " mu: " << mus.transpose() << "\n";
std::cout << " shift: " << shifts.transpose() << "\n";
{
Index actual_n = n;
while(actual_n>1 && col0(actual_n-1)==0) --actual_n;
std::cout << "\n\n mus: " << mus.head(actual_n).transpose() << "\n\n";
std::cout << " check1 (expect0) : " << ((singVals.array()-(shifts+mus)) / singVals.array()).head(actual_n).transpose() << "\n\n";
std::cout << " check2 (>0) : " << ((singVals.array()-diag) / singVals.array()).head(actual_n).transpose() << "\n\n";
std::cout << " check3 (>0) : " << ((diag.segment(1,actual_n-1)-singVals.head(actual_n-1).array()) / singVals.head(actual_n-1).array()).transpose() << "\n\n\n";
std::cout << " check4 (>0) : " << ((singVals.segment(1,actual_n-1)-singVals.head(actual_n-1))).transpose() << "\n\n\n";
}
#endif
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(singVals.allFinite());
assert(mus.allFinite());
assert(shifts.allFinite());
#endif
// Compute zhat
perturbCol0(col0, diag, perm, singVals, shifts, mus, zhat);
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << " zhat: " << zhat.transpose() << "\n";
#endif
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(zhat.allFinite());
#endif
computeSingVecs(zhat, diag, perm, singVals, shifts, mus, U, V);
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "U^T U: " << (U.transpose() * U - MatrixXr(MatrixXr::Identity(U.cols(),U.cols()))).norm() << "\n";
std::cout << "V^T V: " << (V.transpose() * V - MatrixXr(MatrixXr::Identity(V.cols(),V.cols()))).norm() << "\n";
#endif
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(U.allFinite());
assert(V.allFinite());
assert((U.transpose() * U - MatrixXr(MatrixXr::Identity(U.cols(),U.cols()))).norm() < 1e-14 * n);
assert((V.transpose() * V - MatrixXr(MatrixXr::Identity(V.cols(),V.cols()))).norm() < 1e-14 * n);
assert(m_naiveU.allFinite());
assert(m_naiveV.allFinite());
assert(m_computed.allFinite());
#endif
// Because of deflation, the singular values might not be completely sorted.
// Fortunately, reordering them is a O(n) problem
for(Index i=0; i<actual_n-1; ++i)
{
if(singVals(i)>singVals(i+1))
{
using std::swap;
swap(singVals(i),singVals(i+1));
U.col(i).swap(U.col(i+1));
if(m_compV) V.col(i).swap(V.col(i+1));
}
}
// Reverse order so that singular values in increased order
// Because of deflation, the zeros singular-values are already at the end
singVals.head(actual_n).reverseInPlace();
U.leftCols(actual_n) = U.leftCols(actual_n).rowwise().reverse().eval(); // FIXME this requires a temporary
if (m_compV) V.leftCols(actual_n) = V.leftCols(actual_n).rowwise().reverse().eval(); // FIXME this requires a temporary
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
JacobiSVD<MatrixXr> jsvd(m_computed.block(firstCol, firstCol, n, n) );
std::cout << " * j: " << jsvd.singularValues().transpose() << "\n\n";
std::cout << " * sing-val: " << singVals.transpose() << "\n";
// std::cout << " * err: " << ((jsvd.singularValues()-singVals)>1e-13*singVals.norm()).transpose() << "\n";
#endif
}
template <typename MatrixType>
typename BDCSVD<MatrixType>::RealScalar BDCSVD<MatrixType>::secularEq(RealScalar mu, const ArrayXr& col0, const ArrayXr& diag, const ArrayXi &perm, const ArrayXr& diagShifted, RealScalar shift)
{
Index m = perm.size();
RealScalar res = 1;
for(Index i=0; i<m; ++i)
{
Index j = perm(i);
res += numext::abs2(col0(j)) / ((diagShifted(j) - mu) * (diag(j) + shift + mu));
}
return res;
}
template <typename MatrixType>
void BDCSVD<MatrixType>::computeSingVals(const ArrayXr& col0, const ArrayXr& diag, const ArrayXi &perm,
VectorType& singVals, ArrayXr& shifts, ArrayXr& mus)
{
using std::abs;
using std::swap;
Index n = col0.size();
Index actual_n = n;
while(actual_n>1 && col0(actual_n-1)==0) --actual_n;
for (Index k = 0; k < n; ++k)
{
if (col0(k) == 0 || actual_n==1)
{
// if col0(k) == 0, then entry is deflated, so singular value is on diagonal
// if actual_n==1, then the deflated problem is already diagonalized
singVals(k) = k==0 ? col0(0) : diag(k);
mus(k) = 0;
shifts(k) = k==0 ? col0(0) : diag(k);
continue;
}
// otherwise, use secular equation to find singular value
RealScalar left = diag(k);
RealScalar right; // was: = (k != actual_n-1) ? diag(k+1) : (diag(actual_n-1) + col0.matrix().norm());
if(k==actual_n-1)
right = (diag(actual_n-1) + col0.matrix().norm());
else
{
// Skip deflated singular values
Index l = k+1;
while(col0(l)==0) { ++l; eigen_internal_assert(l<actual_n); }
right = diag(l);
}
// first decide whether it's closer to the left end or the right end
RealScalar mid = left + (right-left) / 2;
RealScalar fMid = secularEq(mid, col0, diag, perm, diag, 0);
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << right-left << "\n";
std::cout << "fMid = " << fMid << " " << secularEq(mid-left, col0, diag, perm, diag-left, left) << " " << secularEq(mid-right, col0, diag, perm, diag-right, right) << "\n";
std::cout << " = " << secularEq(0.1*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.2*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.3*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.4*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.49*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.5*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.51*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.6*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.7*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.8*(left+right), col0, diag, perm, diag, 0)
<< " " << secularEq(0.9*(left+right), col0, diag, perm, diag, 0) << "\n";
#endif
RealScalar shift = (k == actual_n-1 || fMid > 0) ? left : right;
// measure everything relative to shift
ArrayXr diagShifted = diag - shift;
// initial guess
RealScalar muPrev, muCur;
if (shift == left)
{
muPrev = (right - left) * 0.1;
if (k == actual_n-1) muCur = right - left;
else muCur = (right - left) * 0.5;
}
else
{
muPrev = -(right - left) * 0.1;
muCur = -(right - left) * 0.5;
}
RealScalar fPrev = secularEq(muPrev, col0, diag, perm, diagShifted, shift);
RealScalar fCur = secularEq(muCur, col0, diag, perm, diagShifted, shift);
if (abs(fPrev) < abs(fCur))
{
swap(fPrev, fCur);
swap(muPrev, muCur);
}
// rational interpolation: fit a function of the form a / mu + b through the two previous
// iterates and use its zero to compute the next iterate
bool useBisection = fPrev*fCur>0;
while (fCur!=0 && abs(muCur - muPrev) > 8 * NumTraits<RealScalar>::epsilon() * numext::maxi(abs(muCur), abs(muPrev)) && abs(fCur - fPrev)>NumTraits<RealScalar>::epsilon() && !useBisection)
{
++m_numIters;
// Find a and b such that the function f(mu) = a / mu + b matches the current and previous samples.
RealScalar a = (fCur - fPrev) / (1/muCur - 1/muPrev);
RealScalar b = fCur - a / muCur;
// And find mu such that f(mu)==0:
RealScalar muZero = -a/b;
RealScalar fZero = secularEq(muZero, col0, diag, perm, diagShifted, shift);
muPrev = muCur;
fPrev = fCur;
muCur = muZero;
fCur = fZero;
if (shift == left && (muCur < 0 || muCur > right - left)) useBisection = true;
if (shift == right && (muCur < -(right - left) || muCur > 0)) useBisection = true;
if (abs(fCur)>abs(fPrev)) useBisection = true;
}
// fall back on bisection method if rational interpolation did not work
if (useBisection)
{
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "useBisection for k = " << k << ", actual_n = " << actual_n << "\n";
#endif
RealScalar leftShifted, rightShifted;
if (shift == left)
{
leftShifted = RealScalar(1)/NumTraits<RealScalar>::highest();
// I don't understand why the case k==0 would be special there:
// if (k == 0) rightShifted = right - left; else
rightShifted = (k==actual_n-1) ? right : ((right - left) * 0.6); // theoretically we can take 0.5, but let's be safe
}
else
{
leftShifted = -(right - left) * 0.6;
rightShifted = -RealScalar(1)/NumTraits<RealScalar>::highest();
}
RealScalar fLeft = secularEq(leftShifted, col0, diag, perm, diagShifted, shift);
RealScalar fRight = secularEq(rightShifted, col0, diag, perm, diagShifted, shift);
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
if(!(fLeft * fRight<0))
std::cout << k << " : " << fLeft << " * " << fRight << " == " << fLeft * fRight << " ; " << left << " - " << right << " -> " << leftShifted << " " << rightShifted << " shift=" << shift << "\n";
#endif
eigen_internal_assert(fLeft * fRight < 0);
while (rightShifted - leftShifted > 2 * NumTraits<RealScalar>::epsilon() * numext::maxi(abs(leftShifted), abs(rightShifted)))
{
RealScalar midShifted = (leftShifted + rightShifted) / 2;
RealScalar fMid = secularEq(midShifted, col0, diag, perm, diagShifted, shift);
if (fLeft * fMid < 0)
{
rightShifted = midShifted;
fRight = fMid;
}
else
{
leftShifted = midShifted;
fLeft = fMid;
}
}
muCur = (leftShifted + rightShifted) / 2;
}
singVals[k] = shift + muCur;
shifts[k] = shift;
mus[k] = muCur;
// perturb singular value slightly if it equals diagonal entry to avoid division by zero later
// (deflation is supposed to avoid this from happening)
// - this does no seem to be necessary anymore -
// if (singVals[k] == left) singVals[k] *= 1 + NumTraits<RealScalar>::epsilon();
// if (singVals[k] == right) singVals[k] *= 1 - NumTraits<RealScalar>::epsilon();
}
}
// zhat is perturbation of col0 for which singular vectors can be computed stably (see Section 3.1)
template <typename MatrixType>
void BDCSVD<MatrixType>::perturbCol0
(const ArrayXr& col0, const ArrayXr& diag, const ArrayXi &perm, const VectorType& singVals,
const ArrayXr& shifts, const ArrayXr& mus, ArrayXr& zhat)
{
using std::sqrt;
Index n = col0.size();
Index m = perm.size();
if(m==0)
{
zhat.setZero();
return;
}
Index last = perm(m-1);
// The offset permits to skip deflated entries while computing zhat
for (Index k = 0; k < n; ++k)
{
if (col0(k) == 0) // deflated
zhat(k) = 0;
else
{
// see equation (3.6)
RealScalar dk = diag(k);
RealScalar prod = (singVals(last) + dk) * (mus(last) + (shifts(last) - dk));
for(Index l = 0; l<m; ++l)
{
Index i = perm(l);
if(i!=k)
{
Index j = i<k ? i : perm(l-1);
prod *= ((singVals(j)+dk) / ((diag(i)+dk))) * ((mus(j)+(shifts(j)-dk)) / ((diag(i)-dk)));
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
if(i!=k && std::abs(((singVals(j)+dk)*(mus(j)+(shifts(j)-dk)))/((diag(i)+dk)*(diag(i)-dk)) - 1) > 0.9 )
std::cout << " " << ((singVals(j)+dk)*(mus(j)+(shifts(j)-dk)))/((diag(i)+dk)*(diag(i)-dk)) << " == (" << (singVals(j)+dk) << " * " << (mus(j)+(shifts(j)-dk))
<< ") / (" << (diag(i)+dk) << " * " << (diag(i)-dk) << ")\n";
#endif
}
}
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "zhat(" << k << ") = sqrt( " << prod << ") ; " << (singVals(last) + dk) << " * " << mus(last) + shifts(last) << " - " << dk << "\n";
#endif
RealScalar tmp = sqrt(prod);
zhat(k) = col0(k) > 0 ? tmp : -tmp;
}
}
}
// compute singular vectors
template <typename MatrixType>
void BDCSVD<MatrixType>::computeSingVecs
(const ArrayXr& zhat, const ArrayXr& diag, const ArrayXi &perm, const VectorType& singVals,
const ArrayXr& shifts, const ArrayXr& mus, MatrixXr& U, MatrixXr& V)
{
Index n = zhat.size();
Index m = perm.size();
for (Index k = 0; k < n; ++k)
{
if (zhat(k) == 0)
{
U.col(k) = VectorType::Unit(n+1, k);
if (m_compV) V.col(k) = VectorType::Unit(n, k);
}
else
{
U.col(k).setZero();
for(Index l=0;l<m;++l)
{
Index i = perm(l);
U(i,k) = zhat(i)/(((diag(i) - shifts(k)) - mus(k)) )/( (diag(i) + singVals[k]));
}
U(n,k) = 0;
U.col(k).normalize();
if (m_compV)
{
V.col(k).setZero();
for(Index l=1;l<m;++l)
{
Index i = perm(l);
V(i,k) = diag(i) * zhat(i) / (((diag(i) - shifts(k)) - mus(k)) )/( (diag(i) + singVals[k]));
}
V(0,k) = -1;
V.col(k).normalize();
}
}
}
U.col(n) = VectorType::Unit(n+1, n);
}
// page 12_13
// i >= 1, di almost null and zi non null.
// We use a rotation to zero out zi applied to the left of M
template <typename MatrixType>
void BDCSVD<MatrixType>::deflation43(Index firstCol, Index shift, Index i, Index size)
{
using std::abs;
using std::sqrt;
using std::pow;
Index start = firstCol + shift;
RealScalar c = m_computed(start, start);
RealScalar s = m_computed(start+i, start);
RealScalar r = sqrt(numext::abs2(c) + numext::abs2(s));
if (r == 0)
{
m_computed(start+i, start+i) = 0;
return;
}
m_computed(start,start) = r;
m_computed(start+i, start) = 0;
m_computed(start+i, start+i) = 0;
JacobiRotation<RealScalar> J(c/r,-s/r);
if (m_compU) m_naiveU.middleRows(firstCol, size+1).applyOnTheRight(firstCol, firstCol+i, J);
else m_naiveU.applyOnTheRight(firstCol, firstCol+i, J);
}// end deflation 43
// page 13
// i,j >= 1, i!=j and |di - dj| < epsilon * norm2(M)
// We apply two rotations to have zj = 0;
// TODO deflation44 is still broken and not properly tested
template <typename MatrixType>
void BDCSVD<MatrixType>::deflation44(Index firstColu , Index firstColm, Index firstRowW, Index firstColW, Index i, Index j, Index size)
{
using std::abs;
using std::sqrt;
using std::conj;
using std::pow;
RealScalar c = m_computed(firstColm+i, firstColm);
RealScalar s = m_computed(firstColm+j, firstColm);
RealScalar r = sqrt(numext::abs2(c) + numext::abs2(s));
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "deflation 4.4: " << i << "," << j << " -> " << c << " " << s << " " << r << " ; "
<< m_computed(firstColm + i-1, firstColm) << " "
<< m_computed(firstColm + i, firstColm) << " "
<< m_computed(firstColm + i+1, firstColm) << " "
<< m_computed(firstColm + i+2, firstColm) << "\n";
std::cout << m_computed(firstColm + i-1, firstColm + i-1) << " "
<< m_computed(firstColm + i, firstColm+i) << " "
<< m_computed(firstColm + i+1, firstColm+i+1) << " "
<< m_computed(firstColm + i+2, firstColm+i+2) << "\n";
#endif
if (r==0)
{
m_computed(firstColm + i, firstColm + i) = m_computed(firstColm + j, firstColm + j);
return;
}
c/=r;
s/=r;
m_computed(firstColm + i, firstColm) = r;
m_computed(firstColm + j, firstColm + j) = m_computed(firstColm + i, firstColm + i);
m_computed(firstColm + j, firstColm) = 0;
JacobiRotation<RealScalar> J(c,-s);
if (m_compU) m_naiveU.middleRows(firstColu, size+1).applyOnTheRight(firstColu + i, firstColu + j, J);
else m_naiveU.applyOnTheRight(firstColu+i, firstColu+j, J);
if (m_compV) m_naiveV.middleRows(firstRowW, size).applyOnTheRight(firstColW + i, firstColW + j, J);
}// end deflation 44
// acts on block from (firstCol+shift, firstCol+shift) to (lastCol+shift, lastCol+shift) [inclusive]
template <typename MatrixType>
void BDCSVD<MatrixType>::deflation(Index firstCol, Index lastCol, Index k, Index firstRowW, Index firstColW, Index shift)
{
using std::sqrt;
using std::abs;
const Index length = lastCol + 1 - firstCol;
Block<MatrixXr,Dynamic,1> col0(m_computed, firstCol+shift, firstCol+shift, length, 1);
Diagonal<MatrixXr> fulldiag(m_computed);
VectorBlock<Diagonal<MatrixXr>,Dynamic> diag(fulldiag, firstCol+shift, length);
RealScalar maxDiag = diag.tail((std::max)(Index(1),length-1)).cwiseAbs().maxCoeff();
RealScalar epsilon_strict = NumTraits<RealScalar>::epsilon() * maxDiag;
RealScalar epsilon_coarse = 8 * NumTraits<RealScalar>::epsilon() * numext::maxi(col0.cwiseAbs().maxCoeff(), maxDiag);
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(m_naiveU.allFinite());
assert(m_naiveV.allFinite());
assert(m_computed.allFinite());
#endif
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "\ndeflate:" << diag.head(k+1).transpose() << " | " << diag.segment(k+1,length-k-1).transpose() << "\n";
#endif
//condition 4.1
if (diag(0) < epsilon_coarse)
{
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "deflation 4.1, because " << diag(0) << " < " << epsilon_coarse << "\n";
#endif
diag(0) = epsilon_coarse;
}
//condition 4.2
for (Index i=1;i<length;++i)
if (abs(col0(i)) < epsilon_strict)
{
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "deflation 4.2, set z(" << i << ") to zero because " << abs(col0(i)) << " < " << epsilon_strict << " (diag(" << i << ")=" << diag(i) << ")\n";
#endif
col0(i) = 0;
}
//condition 4.3
for (Index i=1;i<length; i++)
if (diag(i) < epsilon_coarse)
{
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "deflation 4.3, cancel z(" << i << ")=" << col0(i) << " because diag(" << i << ")=" << diag(i) << " < " << epsilon_coarse << "\n";
#endif
deflation43(firstCol, shift, i, length);
}
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(m_naiveU.allFinite());
assert(m_naiveV.allFinite());
assert(m_computed.allFinite());
#endif
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "to be sorted: " << diag.transpose() << "\n\n";
#endif
{
// Check for total deflation
// If we have a total deflation, then we have to consider col0(0)==diag(0) as a singular value during sorting
bool total_deflation = (col0.tail(length-1).array()==RealScalar(0)).all();
// Sort the diagonal entries, since diag(1:k-1) and diag(k:length) are already sorted, let's do a sorted merge.
// First, compute the respective permutation.
Index *permutation = new Index[length]; // FIXME avoid repeated dynamic memory allocation
{
permutation[0] = 0;
Index p = 1;
// Move deflated diagonal entries at the end.
for(Index i=1; i<length; ++i)
if(diag(i)==0)
permutation[p++] = i;
Index i=1, j=k+1;
for( ; p < length; ++p)
{
if (i > k) permutation[p] = j++;
else if (j >= length) permutation[p] = i++;
else if (diag(i) < diag(j)) permutation[p] = j++;
else permutation[p] = i++;
}
}
// If we have a total deflation, then we have to insert diag(0) at the right place
if(total_deflation)
{
for(Index i=1; i<length; ++i)
{
Index pi = permutation[i];
if(diag(pi)==0 || diag(0)<diag(pi))
permutation[i-1] = permutation[i];
else
{
permutation[i-1] = 0;
break;
}
}
}
// Current index of each col, and current column of each index
Index *realInd = new Index[length]; // FIXME avoid repeated dynamic memory allocation
Index *realCol = new Index[length]; // FIXME avoid repeated dynamic memory allocation
for(int pos = 0; pos< length; pos++)
{
realCol[pos] = pos;
realInd[pos] = pos;
}
for(Index i = total_deflation?0:1; i < length; i++)
{
const Index pi = permutation[length - (total_deflation ? i+1 : i)];
const Index J = realCol[pi];
using std::swap;
// swap diagonal and first column entries:
swap(diag(i), diag(J));
if(i!=0 && J!=0) swap(col0(i), col0(J));
// change columns
if (m_compU) m_naiveU.col(firstCol+i).segment(firstCol, length + 1).swap(m_naiveU.col(firstCol+J).segment(firstCol, length + 1));
else m_naiveU.col(firstCol+i).segment(0, 2) .swap(m_naiveU.col(firstCol+J).segment(0, 2));
if (m_compV) m_naiveV.col(firstColW + i).segment(firstRowW, length).swap(m_naiveV.col(firstColW + J).segment(firstRowW, length));
//update real pos
const Index realI = realInd[i];
realCol[realI] = J;
realCol[pi] = i;
realInd[J] = realI;
realInd[i] = pi;
}
delete[] permutation;
delete[] realInd;
delete[] realCol;
}
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "sorted: " << diag.transpose().format(bdcsvdfmt) << "\n";
std::cout << " : " << col0.transpose() << "\n\n";
#endif
//condition 4.4
{
Index i = length-1;
while(i>0 && (diag(i)==0 || col0(i)==0)) --i;
for(; i>1;--i)
if( (diag(i) - diag(i-1)) < NumTraits<RealScalar>::epsilon()*maxDiag )
{
#ifdef EIGEN_BDCSVD_DEBUG_VERBOSE
std::cout << "deflation 4.4 with i = " << i << " because " << (diag(i) - diag(i-1)) << " < " << NumTraits<RealScalar>::epsilon()*diag(i) << "\n";
#endif
eigen_internal_assert(abs(diag(i) - diag(i-1))<epsilon_coarse && " diagonal entries are not properly sorted");
deflation44(firstCol, firstCol + shift, firstRowW, firstColW, i-1, i, length);
}
}
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
for(Index j=2;j<length;++j)
assert(diag(j-1)<=diag(j) || diag(j)==0);
#endif
#ifdef EIGEN_BDCSVD_SANITY_CHECKS
assert(m_naiveU.allFinite());
assert(m_naiveV.allFinite());
assert(m_computed.allFinite());
#endif
}//end deflation
#ifndef __CUDACC__
/** \svd_module
*
* \return the singular value decomposition of \c *this computed by Divide & Conquer algorithm
*
* \sa class BDCSVD
*/
template<typename Derived>
BDCSVD<typename MatrixBase<Derived>::PlainObject>
MatrixBase<Derived>::bdcSvd(unsigned int computationOptions) const
{
return BDCSVD<PlainObject>(*this, computationOptions);
}
#endif
} // end namespace Eigen
#endif
| [
"pochemuto@gmail.com"
] | pochemuto@gmail.com |
e5b3e13f8616bb527621fd382fdb92cd59ef95b8 | 96ccf2b290d2a289d2f5173a71f58173d457bbf1 | /code_analyser/llvm/tools/clang/include/clang/AST/ExprCXX.h | 9361011ff4fef16f4af4efce6f77a8cc7cc5b586 | [
"NCSA"
] | permissive | ProframFiles/cs410-octo-nemesis | b08244b741cb489392ee167afcf1673f41e493d1 | b14e565f32ad401ece41c58d8d3e0bba8c351041 | refs/heads/master | 2016-09-15T19:55:30.173078 | 2013-11-22T10:49:50 | 2013-11-22T10:49:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 152,841 | h | //===--- ExprCXX.h - Classes for representing expressions -------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// \brief Defines the clang::Expr interface and subclasses for C++ expressions.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_EXPRCXX_H
#define LLVM_CLANG_AST_EXPRCXX_H
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/TemplateBase.h"
#include "clang/AST/UnresolvedSet.h"
#include "clang/Basic/ExpressionTraits.h"
#include "clang/Basic/Lambda.h"
#include "clang/Basic/TypeTraits.h"
#include "llvm/Support/Compiler.h"
namespace clang {
class CXXConstructorDecl;
class CXXDestructorDecl;
class CXXMethodDecl;
class CXXTemporary;
class MSPropertyDecl;
class TemplateArgumentListInfo;
class UuidAttr;
//===--------------------------------------------------------------------===//
// C++ Expressions.
//===--------------------------------------------------------------------===//
/// \brief A call to an overloaded operator written using operator
/// syntax.
///
/// Represents a call to an overloaded operator written using operator
/// syntax, e.g., "x + y" or "*p". While semantically equivalent to a
/// normal call, this AST node provides better information about the
/// syntactic representation of the call.
///
/// In a C++ template, this expression node kind will be used whenever
/// any of the arguments are type-dependent. In this case, the
/// function itself will be a (possibly empty) set of functions and
/// function templates that were found by name lookup at template
/// definition time.
class CXXOperatorCallExpr : public CallExpr {
/// \brief The overloaded operator.
OverloadedOperatorKind Operator;
SourceRange Range;
// Record the FP_CONTRACT state that applies to this operator call. Only
// meaningful for floating point types. For other types this value can be
// set to false.
unsigned FPContractable : 1;
SourceRange getSourceRangeImpl() const LLVM_READONLY;
public:
CXXOperatorCallExpr(ASTContext& C, OverloadedOperatorKind Op, Expr *fn,
ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
SourceLocation operatorloc, bool fpContractable)
: CallExpr(C, CXXOperatorCallExprClass, fn, 0, args, t, VK,
operatorloc),
Operator(Op), FPContractable(fpContractable) {
Range = getSourceRangeImpl();
}
explicit CXXOperatorCallExpr(ASTContext& C, EmptyShell Empty) :
CallExpr(C, CXXOperatorCallExprClass, Empty) { }
/// \brief Returns the kind of overloaded operator that this
/// expression refers to.
OverloadedOperatorKind getOperator() const { return Operator; }
/// \brief Returns the location of the operator symbol in the expression.
///
/// When \c getOperator()==OO_Call, this is the location of the right
/// parentheses; when \c getOperator()==OO_Subscript, this is the location
/// of the right bracket.
SourceLocation getOperatorLoc() const { return getRParenLoc(); }
SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
SourceRange getSourceRange() const { return Range; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXOperatorCallExprClass;
}
// Set the FP contractability status of this operator. Only meaningful for
// operations on floating point types.
void setFPContractable(bool FPC) { FPContractable = FPC; }
// Get the FP contractability status of this operator. Only meaningful for
// operations on floating point types.
bool isFPContractable() const { return FPContractable; }
friend class ASTStmtReader;
friend class ASTStmtWriter;
};
/// Represents a call to a member function that
/// may be written either with member call syntax (e.g., "obj.func()"
/// or "objptr->func()") or with normal function-call syntax
/// ("func()") within a member function that ends up calling a member
/// function. The callee in either case is a MemberExpr that contains
/// both the object argument and the member function, while the
/// arguments are the arguments within the parentheses (not including
/// the object argument).
class CXXMemberCallExpr : public CallExpr {
public:
CXXMemberCallExpr(ASTContext &C, Expr *fn, ArrayRef<Expr*> args,
QualType t, ExprValueKind VK, SourceLocation RP)
: CallExpr(C, CXXMemberCallExprClass, fn, 0, args, t, VK, RP) {}
CXXMemberCallExpr(ASTContext &C, EmptyShell Empty)
: CallExpr(C, CXXMemberCallExprClass, Empty) { }
/// \brief Retrieves the implicit object argument for the member call.
///
/// For example, in "x.f(5)", this returns the sub-expression "x".
Expr *getImplicitObjectArgument() const;
/// \brief Retrieves the declaration of the called method.
CXXMethodDecl *getMethodDecl() const;
/// \brief Retrieves the CXXRecordDecl for the underlying type of
/// the implicit object argument.
///
/// Note that this is may not be the same declaration as that of the class
/// context of the CXXMethodDecl which this function is calling.
/// FIXME: Returns 0 for member pointer call exprs.
CXXRecordDecl *getRecordDecl() const;
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXMemberCallExprClass;
}
};
/// \brief Represents a call to a CUDA kernel function.
class CUDAKernelCallExpr : public CallExpr {
private:
enum { CONFIG, END_PREARG };
public:
CUDAKernelCallExpr(ASTContext &C, Expr *fn, CallExpr *Config,
ArrayRef<Expr*> args, QualType t, ExprValueKind VK,
SourceLocation RP)
: CallExpr(C, CUDAKernelCallExprClass, fn, END_PREARG, args, t, VK, RP) {
setConfig(Config);
}
CUDAKernelCallExpr(ASTContext &C, EmptyShell Empty)
: CallExpr(C, CUDAKernelCallExprClass, END_PREARG, Empty) { }
const CallExpr *getConfig() const {
return cast_or_null<CallExpr>(getPreArg(CONFIG));
}
CallExpr *getConfig() { return cast_or_null<CallExpr>(getPreArg(CONFIG)); }
void setConfig(CallExpr *E) { setPreArg(CONFIG, E); }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CUDAKernelCallExprClass;
}
};
/// \brief Abstract class common to all of the C++ "named"/"keyword" casts.
///
/// This abstract class is inherited by all of the classes
/// representing "named" casts: CXXStaticCastExpr for \c static_cast,
/// CXXDynamicCastExpr for \c dynamic_cast, CXXReinterpretCastExpr for
/// reinterpret_cast, and CXXConstCastExpr for \c const_cast.
class CXXNamedCastExpr : public ExplicitCastExpr {
private:
SourceLocation Loc; // the location of the casting op
SourceLocation RParenLoc; // the location of the right parenthesis
SourceRange AngleBrackets; // range for '<' '>'
protected:
CXXNamedCastExpr(StmtClass SC, QualType ty, ExprValueKind VK,
CastKind kind, Expr *op, unsigned PathSize,
TypeSourceInfo *writtenTy, SourceLocation l,
SourceLocation RParenLoc,
SourceRange AngleBrackets)
: ExplicitCastExpr(SC, ty, VK, kind, op, PathSize, writtenTy), Loc(l),
RParenLoc(RParenLoc), AngleBrackets(AngleBrackets) {}
explicit CXXNamedCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
: ExplicitCastExpr(SC, Shell, PathSize) { }
friend class ASTStmtReader;
public:
const char *getCastName() const;
/// \brief Retrieve the location of the cast operator keyword, e.g.,
/// \c static_cast.
SourceLocation getOperatorLoc() const { return Loc; }
/// \brief Retrieve the location of the closing parenthesis.
SourceLocation getRParenLoc() const { return RParenLoc; }
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
SourceRange getAngleBrackets() const LLVM_READONLY { return AngleBrackets; }
static bool classof(const Stmt *T) {
switch (T->getStmtClass()) {
case CXXStaticCastExprClass:
case CXXDynamicCastExprClass:
case CXXReinterpretCastExprClass:
case CXXConstCastExprClass:
return true;
default:
return false;
}
}
};
/// \brief A C++ \c static_cast expression (C++ [expr.static.cast]).
///
/// This expression node represents a C++ static cast, e.g.,
/// \c static_cast<int>(1.0).
class CXXStaticCastExpr : public CXXNamedCastExpr {
CXXStaticCastExpr(QualType ty, ExprValueKind vk, CastKind kind, Expr *op,
unsigned pathSize, TypeSourceInfo *writtenTy,
SourceLocation l, SourceLocation RParenLoc,
SourceRange AngleBrackets)
: CXXNamedCastExpr(CXXStaticCastExprClass, ty, vk, kind, op, pathSize,
writtenTy, l, RParenLoc, AngleBrackets) {}
explicit CXXStaticCastExpr(EmptyShell Empty, unsigned PathSize)
: CXXNamedCastExpr(CXXStaticCastExprClass, Empty, PathSize) { }
public:
static CXXStaticCastExpr *Create(const ASTContext &Context, QualType T,
ExprValueKind VK, CastKind K, Expr *Op,
const CXXCastPath *Path,
TypeSourceInfo *Written, SourceLocation L,
SourceLocation RParenLoc,
SourceRange AngleBrackets);
static CXXStaticCastExpr *CreateEmpty(const ASTContext &Context,
unsigned PathSize);
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXStaticCastExprClass;
}
};
/// \brief A C++ @c dynamic_cast expression (C++ [expr.dynamic.cast]).
///
/// This expression node represents a dynamic cast, e.g.,
/// \c dynamic_cast<Derived*>(BasePtr). Such a cast may perform a run-time
/// check to determine how to perform the type conversion.
class CXXDynamicCastExpr : public CXXNamedCastExpr {
CXXDynamicCastExpr(QualType ty, ExprValueKind VK, CastKind kind,
Expr *op, unsigned pathSize, TypeSourceInfo *writtenTy,
SourceLocation l, SourceLocation RParenLoc,
SourceRange AngleBrackets)
: CXXNamedCastExpr(CXXDynamicCastExprClass, ty, VK, kind, op, pathSize,
writtenTy, l, RParenLoc, AngleBrackets) {}
explicit CXXDynamicCastExpr(EmptyShell Empty, unsigned pathSize)
: CXXNamedCastExpr(CXXDynamicCastExprClass, Empty, pathSize) { }
public:
static CXXDynamicCastExpr *Create(const ASTContext &Context, QualType T,
ExprValueKind VK, CastKind Kind, Expr *Op,
const CXXCastPath *Path,
TypeSourceInfo *Written, SourceLocation L,
SourceLocation RParenLoc,
SourceRange AngleBrackets);
static CXXDynamicCastExpr *CreateEmpty(const ASTContext &Context,
unsigned pathSize);
bool isAlwaysNull() const;
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXDynamicCastExprClass;
}
};
/// \brief A C++ @c reinterpret_cast expression (C++ [expr.reinterpret.cast]).
///
/// This expression node represents a reinterpret cast, e.g.,
/// @c reinterpret_cast<int>(VoidPtr).
///
/// A reinterpret_cast provides a differently-typed view of a value but
/// (in Clang, as in most C++ implementations) performs no actual work at
/// run time.
class CXXReinterpretCastExpr : public CXXNamedCastExpr {
CXXReinterpretCastExpr(QualType ty, ExprValueKind vk, CastKind kind,
Expr *op, unsigned pathSize,
TypeSourceInfo *writtenTy, SourceLocation l,
SourceLocation RParenLoc,
SourceRange AngleBrackets)
: CXXNamedCastExpr(CXXReinterpretCastExprClass, ty, vk, kind, op,
pathSize, writtenTy, l, RParenLoc, AngleBrackets) {}
CXXReinterpretCastExpr(EmptyShell Empty, unsigned pathSize)
: CXXNamedCastExpr(CXXReinterpretCastExprClass, Empty, pathSize) { }
public:
static CXXReinterpretCastExpr *Create(const ASTContext &Context, QualType T,
ExprValueKind VK, CastKind Kind,
Expr *Op, const CXXCastPath *Path,
TypeSourceInfo *WrittenTy, SourceLocation L,
SourceLocation RParenLoc,
SourceRange AngleBrackets);
static CXXReinterpretCastExpr *CreateEmpty(const ASTContext &Context,
unsigned pathSize);
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXReinterpretCastExprClass;
}
};
/// \brief A C++ \c const_cast expression (C++ [expr.const.cast]).
///
/// This expression node represents a const cast, e.g.,
/// \c const_cast<char*>(PtrToConstChar).
///
/// A const_cast can remove type qualifiers but does not change the underlying
/// value.
class CXXConstCastExpr : public CXXNamedCastExpr {
CXXConstCastExpr(QualType ty, ExprValueKind VK, Expr *op,
TypeSourceInfo *writtenTy, SourceLocation l,
SourceLocation RParenLoc, SourceRange AngleBrackets)
: CXXNamedCastExpr(CXXConstCastExprClass, ty, VK, CK_NoOp, op,
0, writtenTy, l, RParenLoc, AngleBrackets) {}
explicit CXXConstCastExpr(EmptyShell Empty)
: CXXNamedCastExpr(CXXConstCastExprClass, Empty, 0) { }
public:
static CXXConstCastExpr *Create(const ASTContext &Context, QualType T,
ExprValueKind VK, Expr *Op,
TypeSourceInfo *WrittenTy, SourceLocation L,
SourceLocation RParenLoc,
SourceRange AngleBrackets);
static CXXConstCastExpr *CreateEmpty(const ASTContext &Context);
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXConstCastExprClass;
}
};
/// \brief A call to a literal operator (C++11 [over.literal])
/// written as a user-defined literal (C++11 [lit.ext]).
///
/// Represents a user-defined literal, e.g. "foo"_bar or 1.23_xyz. While this
/// is semantically equivalent to a normal call, this AST node provides better
/// information about the syntactic representation of the literal.
///
/// Since literal operators are never found by ADL and can only be declared at
/// namespace scope, a user-defined literal is never dependent.
class UserDefinedLiteral : public CallExpr {
/// \brief The location of a ud-suffix within the literal.
SourceLocation UDSuffixLoc;
public:
UserDefinedLiteral(const ASTContext &C, Expr *Fn, ArrayRef<Expr*> Args,
QualType T, ExprValueKind VK, SourceLocation LitEndLoc,
SourceLocation SuffixLoc)
: CallExpr(C, UserDefinedLiteralClass, Fn, 0, Args, T, VK, LitEndLoc),
UDSuffixLoc(SuffixLoc) {}
explicit UserDefinedLiteral(const ASTContext &C, EmptyShell Empty)
: CallExpr(C, UserDefinedLiteralClass, Empty) {}
/// The kind of literal operator which is invoked.
enum LiteralOperatorKind {
LOK_Raw, ///< Raw form: operator "" X (const char *)
LOK_Template, ///< Raw form: operator "" X<cs...> ()
LOK_Integer, ///< operator "" X (unsigned long long)
LOK_Floating, ///< operator "" X (long double)
LOK_String, ///< operator "" X (const CharT *, size_t)
LOK_Character ///< operator "" X (CharT)
};
/// \brief Returns the kind of literal operator invocation
/// which this expression represents.
LiteralOperatorKind getLiteralOperatorKind() const;
/// \brief If this is not a raw user-defined literal, get the
/// underlying cooked literal (representing the literal with the suffix
/// removed).
Expr *getCookedLiteral();
const Expr *getCookedLiteral() const {
return const_cast<UserDefinedLiteral*>(this)->getCookedLiteral();
}
SourceLocation getLocStart() const {
if (getLiteralOperatorKind() == LOK_Template)
return getRParenLoc();
return getArg(0)->getLocStart();
}
SourceLocation getLocEnd() const { return getRParenLoc(); }
/// \brief Returns the location of a ud-suffix in the expression.
///
/// For a string literal, there may be multiple identical suffixes. This
/// returns the first.
SourceLocation getUDSuffixLoc() const { return UDSuffixLoc; }
/// \brief Returns the ud-suffix specified for this literal.
const IdentifierInfo *getUDSuffix() const;
static bool classof(const Stmt *S) {
return S->getStmtClass() == UserDefinedLiteralClass;
}
friend class ASTStmtReader;
friend class ASTStmtWriter;
};
/// \brief A boolean literal, per ([C++ lex.bool] Boolean literals).
///
class CXXBoolLiteralExpr : public Expr {
bool Value;
SourceLocation Loc;
public:
CXXBoolLiteralExpr(bool val, QualType Ty, SourceLocation l) :
Expr(CXXBoolLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
false, false),
Value(val), Loc(l) {}
explicit CXXBoolLiteralExpr(EmptyShell Empty)
: Expr(CXXBoolLiteralExprClass, Empty) { }
bool getValue() const { return Value; }
void setValue(bool V) { Value = V; }
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
SourceLocation getLocation() const { return Loc; }
void setLocation(SourceLocation L) { Loc = L; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXBoolLiteralExprClass;
}
// Iterators
child_range children() { return child_range(); }
};
/// \brief The null pointer literal (C++11 [lex.nullptr])
///
/// Introduced in C++11, the only literal of type \c nullptr_t is \c nullptr.
class CXXNullPtrLiteralExpr : public Expr {
SourceLocation Loc;
public:
CXXNullPtrLiteralExpr(QualType Ty, SourceLocation l) :
Expr(CXXNullPtrLiteralExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
false, false),
Loc(l) {}
explicit CXXNullPtrLiteralExpr(EmptyShell Empty)
: Expr(CXXNullPtrLiteralExprClass, Empty) { }
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
SourceLocation getLocation() const { return Loc; }
void setLocation(SourceLocation L) { Loc = L; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXNullPtrLiteralExprClass;
}
child_range children() { return child_range(); }
};
/// \brief Implicit construction of a std::initializer_list<T> object from an
/// array temporary within list-initialization (C++11 [dcl.init.list]p5).
class CXXStdInitializerListExpr : public Expr {
Stmt *SubExpr;
CXXStdInitializerListExpr(EmptyShell Empty)
: Expr(CXXStdInitializerListExprClass, Empty), SubExpr(0) {}
public:
CXXStdInitializerListExpr(QualType Ty, Expr *SubExpr)
: Expr(CXXStdInitializerListExprClass, Ty, VK_RValue, OK_Ordinary,
Ty->isDependentType(), SubExpr->isValueDependent(),
SubExpr->isInstantiationDependent(),
SubExpr->containsUnexpandedParameterPack()),
SubExpr(SubExpr) {}
Expr *getSubExpr() { return static_cast<Expr*>(SubExpr); }
const Expr *getSubExpr() const { return static_cast<const Expr*>(SubExpr); }
SourceLocation getLocStart() const LLVM_READONLY {
return SubExpr->getLocStart();
}
SourceLocation getLocEnd() const LLVM_READONLY {
return SubExpr->getLocEnd();
}
SourceRange getSourceRange() const LLVM_READONLY {
return SubExpr->getSourceRange();
}
static bool classof(const Stmt *S) {
return S->getStmtClass() == CXXStdInitializerListExprClass;
}
child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
friend class ASTReader;
friend class ASTStmtReader;
};
/// A C++ \c typeid expression (C++ [expr.typeid]), which gets
/// the \c type_info that corresponds to the supplied type, or the (possibly
/// dynamic) type of the supplied expression.
///
/// This represents code like \c typeid(int) or \c typeid(*objPtr)
class CXXTypeidExpr : public Expr {
private:
llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
SourceRange Range;
public:
CXXTypeidExpr(QualType Ty, TypeSourceInfo *Operand, SourceRange R)
: Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary,
// typeid is never type-dependent (C++ [temp.dep.expr]p4)
false,
// typeid is value-dependent if the type or expression are dependent
Operand->getType()->isDependentType(),
Operand->getType()->isInstantiationDependentType(),
Operand->getType()->containsUnexpandedParameterPack()),
Operand(Operand), Range(R) { }
CXXTypeidExpr(QualType Ty, Expr *Operand, SourceRange R)
: Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary,
// typeid is never type-dependent (C++ [temp.dep.expr]p4)
false,
// typeid is value-dependent if the type or expression are dependent
Operand->isTypeDependent() || Operand->isValueDependent(),
Operand->isInstantiationDependent(),
Operand->containsUnexpandedParameterPack()),
Operand(Operand), Range(R) { }
CXXTypeidExpr(EmptyShell Empty, bool isExpr)
: Expr(CXXTypeidExprClass, Empty) {
if (isExpr)
Operand = (Expr*)0;
else
Operand = (TypeSourceInfo*)0;
}
/// Determine whether this typeid has a type operand which is potentially
/// evaluated, per C++11 [expr.typeid]p3.
bool isPotentiallyEvaluated() const;
bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
/// \brief Retrieves the type operand of this typeid() expression after
/// various required adjustments (removing reference types, cv-qualifiers).
QualType getTypeOperand() const;
/// \brief Retrieve source information for the type operand.
TypeSourceInfo *getTypeOperandSourceInfo() const {
assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
return Operand.get<TypeSourceInfo *>();
}
void setTypeOperandSourceInfo(TypeSourceInfo *TSI) {
assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)");
Operand = TSI;
}
Expr *getExprOperand() const {
assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)");
return static_cast<Expr*>(Operand.get<Stmt *>());
}
void setExprOperand(Expr *E) {
assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)");
Operand = E;
}
SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
SourceRange getSourceRange() const LLVM_READONLY { return Range; }
void setSourceRange(SourceRange R) { Range = R; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXTypeidExprClass;
}
// Iterators
child_range children() {
if (isTypeOperand()) return child_range();
Stmt **begin = reinterpret_cast<Stmt**>(&Operand);
return child_range(begin, begin + 1);
}
};
/// \brief A member reference to an MSPropertyDecl.
///
/// This expression always has pseudo-object type, and therefore it is
/// typically not encountered in a fully-typechecked expression except
/// within the syntactic form of a PseudoObjectExpr.
class MSPropertyRefExpr : public Expr {
Expr *BaseExpr;
MSPropertyDecl *TheDecl;
SourceLocation MemberLoc;
bool IsArrow;
NestedNameSpecifierLoc QualifierLoc;
public:
MSPropertyRefExpr(Expr *baseExpr, MSPropertyDecl *decl, bool isArrow,
QualType ty, ExprValueKind VK,
NestedNameSpecifierLoc qualifierLoc,
SourceLocation nameLoc)
: Expr(MSPropertyRefExprClass, ty, VK, OK_Ordinary,
/*type-dependent*/ false, baseExpr->isValueDependent(),
baseExpr->isInstantiationDependent(),
baseExpr->containsUnexpandedParameterPack()),
BaseExpr(baseExpr), TheDecl(decl),
MemberLoc(nameLoc), IsArrow(isArrow),
QualifierLoc(qualifierLoc) {}
MSPropertyRefExpr(EmptyShell Empty) : Expr(MSPropertyRefExprClass, Empty) {}
SourceRange getSourceRange() const LLVM_READONLY {
return SourceRange(getLocStart(), getLocEnd());
}
bool isImplicitAccess() const {
return getBaseExpr() && getBaseExpr()->isImplicitCXXThis();
}
SourceLocation getLocStart() const {
if (!isImplicitAccess())
return BaseExpr->getLocStart();
else if (QualifierLoc)
return QualifierLoc.getBeginLoc();
else
return MemberLoc;
}
SourceLocation getLocEnd() const { return getMemberLoc(); }
child_range children() {
return child_range((Stmt**)&BaseExpr, (Stmt**)&BaseExpr + 1);
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == MSPropertyRefExprClass;
}
Expr *getBaseExpr() const { return BaseExpr; }
MSPropertyDecl *getPropertyDecl() const { return TheDecl; }
bool isArrow() const { return IsArrow; }
SourceLocation getMemberLoc() const { return MemberLoc; }
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
friend class ASTStmtReader;
};
/// A Microsoft C++ @c __uuidof expression, which gets
/// the _GUID that corresponds to the supplied type or expression.
///
/// This represents code like @c __uuidof(COMTYPE) or @c __uuidof(*comPtr)
class CXXUuidofExpr : public Expr {
private:
llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
SourceRange Range;
public:
CXXUuidofExpr(QualType Ty, TypeSourceInfo *Operand, SourceRange R)
: Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary,
false, Operand->getType()->isDependentType(),
Operand->getType()->isInstantiationDependentType(),
Operand->getType()->containsUnexpandedParameterPack()),
Operand(Operand), Range(R) { }
CXXUuidofExpr(QualType Ty, Expr *Operand, SourceRange R)
: Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary,
false, Operand->isTypeDependent(),
Operand->isInstantiationDependent(),
Operand->containsUnexpandedParameterPack()),
Operand(Operand), Range(R) { }
CXXUuidofExpr(EmptyShell Empty, bool isExpr)
: Expr(CXXUuidofExprClass, Empty) {
if (isExpr)
Operand = (Expr*)0;
else
Operand = (TypeSourceInfo*)0;
}
bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
/// \brief Retrieves the type operand of this __uuidof() expression after
/// various required adjustments (removing reference types, cv-qualifiers).
QualType getTypeOperand() const;
/// \brief Retrieve source information for the type operand.
TypeSourceInfo *getTypeOperandSourceInfo() const {
assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
return Operand.get<TypeSourceInfo *>();
}
void setTypeOperandSourceInfo(TypeSourceInfo *TSI) {
assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)");
Operand = TSI;
}
Expr *getExprOperand() const {
assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)");
return static_cast<Expr*>(Operand.get<Stmt *>());
}
void setExprOperand(Expr *E) {
assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)");
Operand = E;
}
StringRef getUuidAsStringRef(ASTContext &Context) const;
SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
SourceRange getSourceRange() const LLVM_READONLY { return Range; }
void setSourceRange(SourceRange R) { Range = R; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXUuidofExprClass;
}
/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
/// a single GUID.
static UuidAttr *GetUuidAttrOfType(QualType QT,
bool *HasMultipleGUIDsPtr = 0);
// Iterators
child_range children() {
if (isTypeOperand()) return child_range();
Stmt **begin = reinterpret_cast<Stmt**>(&Operand);
return child_range(begin, begin + 1);
}
};
/// \brief Represents the \c this expression in C++.
///
/// This is a pointer to the object on which the current member function is
/// executing (C++ [expr.prim]p3). Example:
///
/// \code
/// class Foo {
/// public:
/// void bar();
/// void test() { this->bar(); }
/// };
/// \endcode
class CXXThisExpr : public Expr {
SourceLocation Loc;
bool Implicit : 1;
public:
CXXThisExpr(SourceLocation L, QualType Type, bool isImplicit)
: Expr(CXXThisExprClass, Type, VK_RValue, OK_Ordinary,
// 'this' is type-dependent if the class type of the enclosing
// member function is dependent (C++ [temp.dep.expr]p2)
Type->isDependentType(), Type->isDependentType(),
Type->isInstantiationDependentType(),
/*ContainsUnexpandedParameterPack=*/false),
Loc(L), Implicit(isImplicit) { }
CXXThisExpr(EmptyShell Empty) : Expr(CXXThisExprClass, Empty) {}
SourceLocation getLocation() const { return Loc; }
void setLocation(SourceLocation L) { Loc = L; }
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
bool isImplicit() const { return Implicit; }
void setImplicit(bool I) { Implicit = I; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXThisExprClass;
}
// Iterators
child_range children() { return child_range(); }
};
/// \brief A C++ throw-expression (C++ [except.throw]).
///
/// This handles 'throw' (for re-throwing the current exception) and
/// 'throw' assignment-expression. When assignment-expression isn't
/// present, Op will be null.
class CXXThrowExpr : public Expr {
Stmt *Op;
SourceLocation ThrowLoc;
/// \brief Whether the thrown variable (if any) is in scope.
unsigned IsThrownVariableInScope : 1;
friend class ASTStmtReader;
public:
// \p Ty is the void type which is used as the result type of the
// expression. The \p l is the location of the throw keyword. \p expr
// can by null, if the optional expression to throw isn't present.
CXXThrowExpr(Expr *expr, QualType Ty, SourceLocation l,
bool IsThrownVariableInScope) :
Expr(CXXThrowExprClass, Ty, VK_RValue, OK_Ordinary, false, false,
expr && expr->isInstantiationDependent(),
expr && expr->containsUnexpandedParameterPack()),
Op(expr), ThrowLoc(l), IsThrownVariableInScope(IsThrownVariableInScope) {}
CXXThrowExpr(EmptyShell Empty) : Expr(CXXThrowExprClass, Empty) {}
const Expr *getSubExpr() const { return cast_or_null<Expr>(Op); }
Expr *getSubExpr() { return cast_or_null<Expr>(Op); }
SourceLocation getThrowLoc() const { return ThrowLoc; }
/// \brief Determines whether the variable thrown by this expression (if any!)
/// is within the innermost try block.
///
/// This information is required to determine whether the NRVO can apply to
/// this variable.
bool isThrownVariableInScope() const { return IsThrownVariableInScope; }
SourceLocation getLocStart() const LLVM_READONLY { return ThrowLoc; }
SourceLocation getLocEnd() const LLVM_READONLY {
if (getSubExpr() == 0)
return ThrowLoc;
return getSubExpr()->getLocEnd();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXThrowExprClass;
}
// Iterators
child_range children() {
return child_range(&Op, Op ? &Op+1 : &Op);
}
};
/// \brief A default argument (C++ [dcl.fct.default]).
///
/// This wraps up a function call argument that was created from the
/// corresponding parameter's default argument, when the call did not
/// explicitly supply arguments for all of the parameters.
class CXXDefaultArgExpr : public Expr {
/// \brief The parameter whose default is being used.
///
/// When the bit is set, the subexpression is stored after the
/// CXXDefaultArgExpr itself. When the bit is clear, the parameter's
/// actual default expression is the subexpression.
llvm::PointerIntPair<ParmVarDecl *, 1, bool> Param;
/// \brief The location where the default argument expression was used.
SourceLocation Loc;
CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *param)
: Expr(SC,
param->hasUnparsedDefaultArg()
? param->getType().getNonReferenceType()
: param->getDefaultArg()->getType(),
param->getDefaultArg()->getValueKind(),
param->getDefaultArg()->getObjectKind(), false, false, false, false),
Param(param, false), Loc(Loc) { }
CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *param,
Expr *SubExpr)
: Expr(SC, SubExpr->getType(),
SubExpr->getValueKind(), SubExpr->getObjectKind(),
false, false, false, false),
Param(param, true), Loc(Loc) {
*reinterpret_cast<Expr **>(this + 1) = SubExpr;
}
public:
CXXDefaultArgExpr(EmptyShell Empty) : Expr(CXXDefaultArgExprClass, Empty) {}
// \p Param is the parameter whose default argument is used by this
// expression.
static CXXDefaultArgExpr *Create(const ASTContext &C, SourceLocation Loc,
ParmVarDecl *Param) {
return new (C) CXXDefaultArgExpr(CXXDefaultArgExprClass, Loc, Param);
}
// \p Param is the parameter whose default argument is used by this
// expression, and \p SubExpr is the expression that will actually be used.
static CXXDefaultArgExpr *Create(const ASTContext &C, SourceLocation Loc,
ParmVarDecl *Param, Expr *SubExpr);
// Retrieve the parameter that the argument was created from.
const ParmVarDecl *getParam() const { return Param.getPointer(); }
ParmVarDecl *getParam() { return Param.getPointer(); }
// Retrieve the actual argument to the function call.
const Expr *getExpr() const {
if (Param.getInt())
return *reinterpret_cast<Expr const * const*> (this + 1);
return getParam()->getDefaultArg();
}
Expr *getExpr() {
if (Param.getInt())
return *reinterpret_cast<Expr **> (this + 1);
return getParam()->getDefaultArg();
}
/// \brief Retrieve the location where this default argument was actually
/// used.
SourceLocation getUsedLocation() const { return Loc; }
/// Default argument expressions have no representation in the
/// source, so they have an empty source range.
SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXDefaultArgExprClass;
}
// Iterators
child_range children() { return child_range(); }
friend class ASTStmtReader;
friend class ASTStmtWriter;
};
/// \brief A use of a default initializer in a constructor or in aggregate
/// initialization.
///
/// This wraps a use of a C++ default initializer (technically,
/// a brace-or-equal-initializer for a non-static data member) when it
/// is implicitly used in a mem-initializer-list in a constructor
/// (C++11 [class.base.init]p8) or in aggregate initialization
/// (C++1y [dcl.init.aggr]p7).
class CXXDefaultInitExpr : public Expr {
/// \brief The field whose default is being used.
FieldDecl *Field;
/// \brief The location where the default initializer expression was used.
SourceLocation Loc;
CXXDefaultInitExpr(const ASTContext &C, SourceLocation Loc, FieldDecl *Field,
QualType T);
CXXDefaultInitExpr(EmptyShell Empty) : Expr(CXXDefaultInitExprClass, Empty) {}
public:
/// \p Field is the non-static data member whose default initializer is used
/// by this expression.
static CXXDefaultInitExpr *Create(const ASTContext &C, SourceLocation Loc,
FieldDecl *Field) {
return new (C) CXXDefaultInitExpr(C, Loc, Field, Field->getType());
}
/// \brief Get the field whose initializer will be used.
FieldDecl *getField() { return Field; }
const FieldDecl *getField() const { return Field; }
/// \brief Get the initialization expression that will be used.
const Expr *getExpr() const { return Field->getInClassInitializer(); }
Expr *getExpr() { return Field->getInClassInitializer(); }
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXDefaultInitExprClass;
}
// Iterators
child_range children() { return child_range(); }
friend class ASTReader;
friend class ASTStmtReader;
};
/// \brief Represents a C++ temporary.
class CXXTemporary {
/// \brief The destructor that needs to be called.
const CXXDestructorDecl *Destructor;
explicit CXXTemporary(const CXXDestructorDecl *destructor)
: Destructor(destructor) { }
public:
static CXXTemporary *Create(const ASTContext &C,
const CXXDestructorDecl *Destructor);
const CXXDestructorDecl *getDestructor() const { return Destructor; }
void setDestructor(const CXXDestructorDecl *Dtor) {
Destructor = Dtor;
}
};
/// \brief Represents binding an expression to a temporary.
///
/// This ensures the destructor is called for the temporary. It should only be
/// needed for non-POD, non-trivially destructable class types. For example:
///
/// \code
/// struct S {
/// S() { } // User defined constructor makes S non-POD.
/// ~S() { } // User defined destructor makes it non-trivial.
/// };
/// void test() {
/// const S &s_ref = S(); // Requires a CXXBindTemporaryExpr.
/// }
/// \endcode
class CXXBindTemporaryExpr : public Expr {
CXXTemporary *Temp;
Stmt *SubExpr;
CXXBindTemporaryExpr(CXXTemporary *temp, Expr* SubExpr)
: Expr(CXXBindTemporaryExprClass, SubExpr->getType(),
VK_RValue, OK_Ordinary, SubExpr->isTypeDependent(),
SubExpr->isValueDependent(),
SubExpr->isInstantiationDependent(),
SubExpr->containsUnexpandedParameterPack()),
Temp(temp), SubExpr(SubExpr) { }
public:
CXXBindTemporaryExpr(EmptyShell Empty)
: Expr(CXXBindTemporaryExprClass, Empty), Temp(0), SubExpr(0) {}
static CXXBindTemporaryExpr *Create(const ASTContext &C, CXXTemporary *Temp,
Expr* SubExpr);
CXXTemporary *getTemporary() { return Temp; }
const CXXTemporary *getTemporary() const { return Temp; }
void setTemporary(CXXTemporary *T) { Temp = T; }
const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
Expr *getSubExpr() { return cast<Expr>(SubExpr); }
void setSubExpr(Expr *E) { SubExpr = E; }
SourceLocation getLocStart() const LLVM_READONLY {
return SubExpr->getLocStart();
}
SourceLocation getLocEnd() const LLVM_READONLY { return SubExpr->getLocEnd();}
// Implement isa/cast/dyncast/etc.
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXBindTemporaryExprClass;
}
// Iterators
child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
};
/// \brief Represents a call to a C++ constructor.
class CXXConstructExpr : public Expr {
public:
enum ConstructionKind {
CK_Complete,
CK_NonVirtualBase,
CK_VirtualBase,
CK_Delegating
};
private:
CXXConstructorDecl *Constructor;
SourceLocation Loc;
SourceRange ParenOrBraceRange;
unsigned NumArgs : 16;
bool Elidable : 1;
bool HadMultipleCandidates : 1;
bool ListInitialization : 1;
bool ZeroInitialization : 1;
unsigned ConstructKind : 2;
Stmt **Args;
protected:
CXXConstructExpr(const ASTContext &C, StmtClass SC, QualType T,
SourceLocation Loc,
CXXConstructorDecl *d, bool elidable,
ArrayRef<Expr *> Args,
bool HadMultipleCandidates,
bool ListInitialization,
bool ZeroInitialization,
ConstructionKind ConstructKind,
SourceRange ParenOrBraceRange);
/// \brief Construct an empty C++ construction expression.
CXXConstructExpr(StmtClass SC, EmptyShell Empty)
: Expr(SC, Empty), Constructor(0), NumArgs(0), Elidable(false),
HadMultipleCandidates(false), ListInitialization(false),
ZeroInitialization(false), ConstructKind(0), Args(0)
{ }
public:
/// \brief Construct an empty C++ construction expression.
explicit CXXConstructExpr(EmptyShell Empty)
: Expr(CXXConstructExprClass, Empty), Constructor(0),
NumArgs(0), Elidable(false), HadMultipleCandidates(false),
ListInitialization(false), ZeroInitialization(false),
ConstructKind(0), Args(0)
{ }
static CXXConstructExpr *Create(const ASTContext &C, QualType T,
SourceLocation Loc,
CXXConstructorDecl *D, bool Elidable,
ArrayRef<Expr *> Args,
bool HadMultipleCandidates,
bool ListInitialization,
bool ZeroInitialization,
ConstructionKind ConstructKind,
SourceRange ParenOrBraceRange);
CXXConstructorDecl* getConstructor() const { return Constructor; }
void setConstructor(CXXConstructorDecl *C) { Constructor = C; }
SourceLocation getLocation() const { return Loc; }
void setLocation(SourceLocation Loc) { this->Loc = Loc; }
/// \brief Whether this construction is elidable.
bool isElidable() const { return Elidable; }
void setElidable(bool E) { Elidable = E; }
/// \brief Whether the referred constructor was resolved from
/// an overloaded set having size greater than 1.
bool hadMultipleCandidates() const { return HadMultipleCandidates; }
void setHadMultipleCandidates(bool V) { HadMultipleCandidates = V; }
/// \brief Whether this constructor call was written as list-initialization.
bool isListInitialization() const { return ListInitialization; }
void setListInitialization(bool V) { ListInitialization = V; }
/// \brief Whether this construction first requires
/// zero-initialization before the initializer is called.
bool requiresZeroInitialization() const { return ZeroInitialization; }
void setRequiresZeroInitialization(bool ZeroInit) {
ZeroInitialization = ZeroInit;
}
/// \brief Determine whether this constructor is actually constructing
/// a base class (rather than a complete object).
ConstructionKind getConstructionKind() const {
return (ConstructionKind)ConstructKind;
}
void setConstructionKind(ConstructionKind CK) {
ConstructKind = CK;
}
typedef ExprIterator arg_iterator;
typedef ConstExprIterator const_arg_iterator;
arg_iterator arg_begin() { return Args; }
arg_iterator arg_end() { return Args + NumArgs; }
const_arg_iterator arg_begin() const { return Args; }
const_arg_iterator arg_end() const { return Args + NumArgs; }
Expr **getArgs() const { return reinterpret_cast<Expr **>(Args); }
unsigned getNumArgs() const { return NumArgs; }
/// \brief Return the specified argument.
Expr *getArg(unsigned Arg) {
assert(Arg < NumArgs && "Arg access out of range!");
return cast<Expr>(Args[Arg]);
}
const Expr *getArg(unsigned Arg) const {
assert(Arg < NumArgs && "Arg access out of range!");
return cast<Expr>(Args[Arg]);
}
/// \brief Set the specified argument.
void setArg(unsigned Arg, Expr *ArgExpr) {
assert(Arg < NumArgs && "Arg access out of range!");
Args[Arg] = ArgExpr;
}
SourceLocation getLocStart() const LLVM_READONLY;
SourceLocation getLocEnd() const LLVM_READONLY;
SourceRange getParenOrBraceRange() const { return ParenOrBraceRange; }
void setParenOrBraceRange(SourceRange Range) { ParenOrBraceRange = Range; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXConstructExprClass ||
T->getStmtClass() == CXXTemporaryObjectExprClass;
}
// Iterators
child_range children() {
return child_range(&Args[0], &Args[0]+NumArgs);
}
friend class ASTStmtReader;
};
/// \brief Represents an explicit C++ type conversion that uses "functional"
/// notation (C++ [expr.type.conv]).
///
/// Example:
/// \code
/// x = int(0.5);
/// \endcode
class CXXFunctionalCastExpr : public ExplicitCastExpr {
SourceLocation LParenLoc;
SourceLocation RParenLoc;
CXXFunctionalCastExpr(QualType ty, ExprValueKind VK,
TypeSourceInfo *writtenTy,
CastKind kind, Expr *castExpr, unsigned pathSize,
SourceLocation lParenLoc, SourceLocation rParenLoc)
: ExplicitCastExpr(CXXFunctionalCastExprClass, ty, VK, kind,
castExpr, pathSize, writtenTy),
LParenLoc(lParenLoc), RParenLoc(rParenLoc) {}
explicit CXXFunctionalCastExpr(EmptyShell Shell, unsigned PathSize)
: ExplicitCastExpr(CXXFunctionalCastExprClass, Shell, PathSize) { }
public:
static CXXFunctionalCastExpr *Create(const ASTContext &Context, QualType T,
ExprValueKind VK,
TypeSourceInfo *Written,
CastKind Kind, Expr *Op,
const CXXCastPath *Path,
SourceLocation LPLoc,
SourceLocation RPLoc);
static CXXFunctionalCastExpr *CreateEmpty(const ASTContext &Context,
unsigned PathSize);
SourceLocation getLParenLoc() const { return LParenLoc; }
void setLParenLoc(SourceLocation L) { LParenLoc = L; }
SourceLocation getRParenLoc() const { return RParenLoc; }
void setRParenLoc(SourceLocation L) { RParenLoc = L; }
SourceLocation getLocStart() const LLVM_READONLY;
SourceLocation getLocEnd() const LLVM_READONLY;
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXFunctionalCastExprClass;
}
};
/// @brief Represents a C++ functional cast expression that builds a
/// temporary object.
///
/// This expression type represents a C++ "functional" cast
/// (C++[expr.type.conv]) with N != 1 arguments that invokes a
/// constructor to build a temporary object. With N == 1 arguments the
/// functional cast expression will be represented by CXXFunctionalCastExpr.
/// Example:
/// \code
/// struct X { X(int, float); }
///
/// X create_X() {
/// return X(1, 3.14f); // creates a CXXTemporaryObjectExpr
/// };
/// \endcode
class CXXTemporaryObjectExpr : public CXXConstructExpr {
TypeSourceInfo *Type;
public:
CXXTemporaryObjectExpr(const ASTContext &C, CXXConstructorDecl *Cons,
TypeSourceInfo *Type,
ArrayRef<Expr *> Args,
SourceRange ParenOrBraceRange,
bool HadMultipleCandidates,
bool ListInitialization,
bool ZeroInitialization);
explicit CXXTemporaryObjectExpr(EmptyShell Empty)
: CXXConstructExpr(CXXTemporaryObjectExprClass, Empty), Type() { }
TypeSourceInfo *getTypeSourceInfo() const { return Type; }
SourceLocation getLocStart() const LLVM_READONLY;
SourceLocation getLocEnd() const LLVM_READONLY;
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXTemporaryObjectExprClass;
}
friend class ASTStmtReader;
};
/// \brief A C++ lambda expression, which produces a function object
/// (of unspecified type) that can be invoked later.
///
/// Example:
/// \code
/// void low_pass_filter(std::vector<double> &values, double cutoff) {
/// values.erase(std::remove_if(values.begin(), values.end(),
/// [=](double value) { return value > cutoff; });
/// }
/// \endcode
///
/// C++11 lambda expressions can capture local variables, either by copying
/// the values of those local variables at the time the function
/// object is constructed (not when it is called!) or by holding a
/// reference to the local variable. These captures can occur either
/// implicitly or can be written explicitly between the square
/// brackets ([...]) that start the lambda expression.
///
/// C++1y introduces a new form of "capture" called an init-capture that
/// includes an initializing expression (rather than capturing a variable),
/// and which can never occur implicitly.
class LambdaExpr : public Expr {
enum {
/// \brief Flag used by the Capture class to indicate that the given
/// capture was implicit.
Capture_Implicit = 0x01,
/// \brief Flag used by the Capture class to indicate that the
/// given capture was by-copy.
///
/// This includes the case of a non-reference init-capture.
Capture_ByCopy = 0x02
};
/// \brief The source range that covers the lambda introducer ([...]).
SourceRange IntroducerRange;
/// \brief The source location of this lambda's capture-default ('=' or '&').
SourceLocation CaptureDefaultLoc;
/// \brief The number of captures.
unsigned NumCaptures : 16;
/// \brief The default capture kind, which is a value of type
/// LambdaCaptureDefault.
unsigned CaptureDefault : 2;
/// \brief Whether this lambda had an explicit parameter list vs. an
/// implicit (and empty) parameter list.
unsigned ExplicitParams : 1;
/// \brief Whether this lambda had the result type explicitly specified.
unsigned ExplicitResultType : 1;
/// \brief Whether there are any array index variables stored at the end of
/// this lambda expression.
unsigned HasArrayIndexVars : 1;
/// \brief The location of the closing brace ('}') that completes
/// the lambda.
///
/// The location of the brace is also available by looking up the
/// function call operator in the lambda class. However, it is
/// stored here to improve the performance of getSourceRange(), and
/// to avoid having to deserialize the function call operator from a
/// module file just to determine the source range.
SourceLocation ClosingBrace;
// Note: The capture initializers are stored directly after the lambda
// expression, along with the index variables used to initialize by-copy
// array captures.
public:
/// \brief Describes the capture of a variable or of \c this, or of a
/// C++1y init-capture.
class Capture {
llvm::PointerIntPair<Decl *, 2> DeclAndBits;
SourceLocation Loc;
SourceLocation EllipsisLoc;
friend class ASTStmtReader;
friend class ASTStmtWriter;
public:
/// \brief Create a new capture of a variable or of \c this.
///
/// \param Loc The source location associated with this capture.
///
/// \param Kind The kind of capture (this, byref, bycopy), which must
/// not be init-capture.
///
/// \param Implicit Whether the capture was implicit or explicit.
///
/// \param Var The local variable being captured, or null if capturing
/// \c this.
///
/// \param EllipsisLoc The location of the ellipsis (...) for a
/// capture that is a pack expansion, or an invalid source
/// location to indicate that this is not a pack expansion.
Capture(SourceLocation Loc, bool Implicit,
LambdaCaptureKind Kind, VarDecl *Var = 0,
SourceLocation EllipsisLoc = SourceLocation());
/// \brief Create a new init-capture.
Capture(FieldDecl *Field);
/// \brief Determine the kind of capture.
LambdaCaptureKind getCaptureKind() const;
/// \brief Determine whether this capture handles the C++ \c this
/// pointer.
bool capturesThis() const { return DeclAndBits.getPointer() == 0; }
/// \brief Determine whether this capture handles a variable.
bool capturesVariable() const {
return dyn_cast_or_null<VarDecl>(DeclAndBits.getPointer());
}
/// \brief Determine whether this is an init-capture.
bool isInitCapture() const { return getCaptureKind() == LCK_Init; }
/// \brief Retrieve the declaration of the local variable being
/// captured.
///
/// This operation is only valid if this capture is a variable capture
/// (other than a capture of \c this).
VarDecl *getCapturedVar() const {
assert(capturesVariable() && "No variable available for 'this' capture");
return cast<VarDecl>(DeclAndBits.getPointer());
}
/// \brief Retrieve the field for an init-capture.
///
/// This works only for an init-capture. To retrieve the FieldDecl for
/// a captured variable or for a capture of \c this, use
/// LambdaExpr::getLambdaClass and CXXRecordDecl::getCaptureFields.
FieldDecl *getInitCaptureField() const {
assert(getCaptureKind() == LCK_Init && "no field for non-init-capture");
return cast<FieldDecl>(DeclAndBits.getPointer());
}
/// \brief Determine whether this was an implicit capture (not
/// written between the square brackets introducing the lambda).
bool isImplicit() const { return DeclAndBits.getInt() & Capture_Implicit; }
/// \brief Determine whether this was an explicit capture (written
/// between the square brackets introducing the lambda).
bool isExplicit() const { return !isImplicit(); }
/// \brief Retrieve the source location of the capture.
///
/// For an explicit capture, this returns the location of the
/// explicit capture in the source. For an implicit capture, this
/// returns the location at which the variable or \c this was first
/// used.
SourceLocation getLocation() const { return Loc; }
/// \brief Determine whether this capture is a pack expansion,
/// which captures a function parameter pack.
bool isPackExpansion() const { return EllipsisLoc.isValid(); }
/// \brief Retrieve the location of the ellipsis for a capture
/// that is a pack expansion.
SourceLocation getEllipsisLoc() const {
assert(isPackExpansion() && "No ellipsis location for a non-expansion");
return EllipsisLoc;
}
};
private:
/// \brief Construct a lambda expression.
LambdaExpr(QualType T, SourceRange IntroducerRange,
LambdaCaptureDefault CaptureDefault,
SourceLocation CaptureDefaultLoc,
ArrayRef<Capture> Captures,
bool ExplicitParams,
bool ExplicitResultType,
ArrayRef<Expr *> CaptureInits,
ArrayRef<VarDecl *> ArrayIndexVars,
ArrayRef<unsigned> ArrayIndexStarts,
SourceLocation ClosingBrace,
bool ContainsUnexpandedParameterPack);
/// \brief Construct an empty lambda expression.
LambdaExpr(EmptyShell Empty, unsigned NumCaptures, bool HasArrayIndexVars)
: Expr(LambdaExprClass, Empty),
NumCaptures(NumCaptures), CaptureDefault(LCD_None), ExplicitParams(false),
ExplicitResultType(false), HasArrayIndexVars(true) {
getStoredStmts()[NumCaptures] = 0;
}
Stmt **getStoredStmts() const {
return reinterpret_cast<Stmt **>(const_cast<LambdaExpr *>(this) + 1);
}
/// \brief Retrieve the mapping from captures to the first array index
/// variable.
unsigned *getArrayIndexStarts() const {
return reinterpret_cast<unsigned *>(getStoredStmts() + NumCaptures + 1);
}
/// \brief Retrieve the complete set of array-index variables.
VarDecl **getArrayIndexVars() const {
unsigned ArrayIndexSize =
llvm::RoundUpToAlignment(sizeof(unsigned) * (NumCaptures + 1),
llvm::alignOf<VarDecl*>());
return reinterpret_cast<VarDecl **>(
reinterpret_cast<char*>(getArrayIndexStarts()) + ArrayIndexSize);
}
public:
/// \brief Construct a new lambda expression.
static LambdaExpr *Create(const ASTContext &C,
CXXRecordDecl *Class,
SourceRange IntroducerRange,
LambdaCaptureDefault CaptureDefault,
SourceLocation CaptureDefaultLoc,
ArrayRef<Capture> Captures,
bool ExplicitParams,
bool ExplicitResultType,
ArrayRef<Expr *> CaptureInits,
ArrayRef<VarDecl *> ArrayIndexVars,
ArrayRef<unsigned> ArrayIndexStarts,
SourceLocation ClosingBrace,
bool ContainsUnexpandedParameterPack);
/// \brief Construct a new lambda expression that will be deserialized from
/// an external source.
static LambdaExpr *CreateDeserialized(const ASTContext &C,
unsigned NumCaptures,
unsigned NumArrayIndexVars);
/// \brief Determine the default capture kind for this lambda.
LambdaCaptureDefault getCaptureDefault() const {
return static_cast<LambdaCaptureDefault>(CaptureDefault);
}
/// \brief Retrieve the location of this lambda's capture-default, if any.
SourceLocation getCaptureDefaultLoc() const {
return CaptureDefaultLoc;
}
/// \brief An iterator that walks over the captures of the lambda,
/// both implicit and explicit.
typedef const Capture *capture_iterator;
/// \brief Retrieve an iterator pointing to the first lambda capture.
capture_iterator capture_begin() const;
/// \brief Retrieve an iterator pointing past the end of the
/// sequence of lambda captures.
capture_iterator capture_end() const;
/// \brief Determine the number of captures in this lambda.
unsigned capture_size() const { return NumCaptures; }
/// \brief Retrieve an iterator pointing to the first explicit
/// lambda capture.
capture_iterator explicit_capture_begin() const;
/// \brief Retrieve an iterator pointing past the end of the sequence of
/// explicit lambda captures.
capture_iterator explicit_capture_end() const;
/// \brief Retrieve an iterator pointing to the first implicit
/// lambda capture.
capture_iterator implicit_capture_begin() const;
/// \brief Retrieve an iterator pointing past the end of the sequence of
/// implicit lambda captures.
capture_iterator implicit_capture_end() const;
/// \brief Iterator that walks over the capture initialization
/// arguments.
typedef Expr **capture_init_iterator;
/// \brief Retrieve the first initialization argument for this
/// lambda expression (which initializes the first capture field).
capture_init_iterator capture_init_begin() const {
return reinterpret_cast<Expr **>(getStoredStmts());
}
/// \brief Retrieve the iterator pointing one past the last
/// initialization argument for this lambda expression.
capture_init_iterator capture_init_end() const {
return capture_init_begin() + NumCaptures;
}
/// \brief Retrieve the initializer for an init-capture.
Expr *getInitCaptureInit(capture_iterator Capture) {
assert(Capture >= explicit_capture_begin() &&
Capture <= explicit_capture_end() && Capture->isInitCapture());
return capture_init_begin()[Capture - capture_begin()];
}
const Expr *getInitCaptureInit(capture_iterator Capture) const {
return const_cast<LambdaExpr*>(this)->getInitCaptureInit(Capture);
}
/// \brief Retrieve the set of index variables used in the capture
/// initializer of an array captured by copy.
///
/// \param Iter The iterator that points at the capture initializer for
/// which we are extracting the corresponding index variables.
ArrayRef<VarDecl *> getCaptureInitIndexVars(capture_init_iterator Iter) const;
/// \brief Retrieve the source range covering the lambda introducer,
/// which contains the explicit capture list surrounded by square
/// brackets ([...]).
SourceRange getIntroducerRange() const { return IntroducerRange; }
/// \brief Retrieve the class that corresponds to the lambda.
///
/// This is the "closure type" (C++1y [expr.prim.lambda]), and stores the
/// captures in its fields and provides the various operations permitted
/// on a lambda (copying, calling).
CXXRecordDecl *getLambdaClass() const;
/// \brief Retrieve the function call operator associated with this
/// lambda expression.
CXXMethodDecl *getCallOperator() const;
/// \brief Retrieve the body of the lambda.
CompoundStmt *getBody() const;
/// \brief Determine whether the lambda is mutable, meaning that any
/// captures values can be modified.
bool isMutable() const;
/// \brief Determine whether this lambda has an explicit parameter
/// list vs. an implicit (empty) parameter list.
bool hasExplicitParameters() const { return ExplicitParams; }
/// \brief Whether this lambda had its result type explicitly specified.
bool hasExplicitResultType() const { return ExplicitResultType; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == LambdaExprClass;
}
SourceLocation getLocStart() const LLVM_READONLY {
return IntroducerRange.getBegin();
}
SourceLocation getLocEnd() const LLVM_READONLY { return ClosingBrace; }
child_range children() {
return child_range(getStoredStmts(), getStoredStmts() + NumCaptures + 1);
}
friend class ASTStmtReader;
friend class ASTStmtWriter;
};
/// An expression "T()" which creates a value-initialized rvalue of type
/// T, which is a non-class type. See (C++98 [5.2.3p2]).
class CXXScalarValueInitExpr : public Expr {
SourceLocation RParenLoc;
TypeSourceInfo *TypeInfo;
friend class ASTStmtReader;
public:
/// \brief Create an explicitly-written scalar-value initialization
/// expression.
CXXScalarValueInitExpr(QualType Type,
TypeSourceInfo *TypeInfo,
SourceLocation rParenLoc ) :
Expr(CXXScalarValueInitExprClass, Type, VK_RValue, OK_Ordinary,
false, false, Type->isInstantiationDependentType(), false),
RParenLoc(rParenLoc), TypeInfo(TypeInfo) {}
explicit CXXScalarValueInitExpr(EmptyShell Shell)
: Expr(CXXScalarValueInitExprClass, Shell) { }
TypeSourceInfo *getTypeSourceInfo() const {
return TypeInfo;
}
SourceLocation getRParenLoc() const { return RParenLoc; }
SourceLocation getLocStart() const LLVM_READONLY;
SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXScalarValueInitExprClass;
}
// Iterators
child_range children() { return child_range(); }
};
/// \brief Represents a new-expression for memory allocation and constructor
/// calls, e.g: "new CXXNewExpr(foo)".
class CXXNewExpr : public Expr {
/// Contains an optional array size expression, an optional initialization
/// expression, and any number of optional placement arguments, in that order.
Stmt **SubExprs;
/// \brief Points to the allocation function used.
FunctionDecl *OperatorNew;
/// \brief Points to the deallocation function used in case of error. May be
/// null.
FunctionDecl *OperatorDelete;
/// \brief The allocated type-source information, as written in the source.
TypeSourceInfo *AllocatedTypeInfo;
/// \brief If the allocated type was expressed as a parenthesized type-id,
/// the source range covering the parenthesized type-id.
SourceRange TypeIdParens;
/// \brief Range of the entire new expression.
SourceRange Range;
/// \brief Source-range of a paren-delimited initializer.
SourceRange DirectInitRange;
/// Was the usage ::new, i.e. is the global new to be used?
bool GlobalNew : 1;
/// Do we allocate an array? If so, the first SubExpr is the size expression.
bool Array : 1;
/// If this is an array allocation, does the usual deallocation
/// function for the allocated type want to know the allocated size?
bool UsualArrayDeleteWantsSize : 1;
/// The number of placement new arguments.
unsigned NumPlacementArgs : 13;
/// What kind of initializer do we have? Could be none, parens, or braces.
/// In storage, we distinguish between "none, and no initializer expr", and
/// "none, but an implicit initializer expr".
unsigned StoredInitializationStyle : 2;
friend class ASTStmtReader;
friend class ASTStmtWriter;
public:
enum InitializationStyle {
NoInit, ///< New-expression has no initializer as written.
CallInit, ///< New-expression has a C++98 paren-delimited initializer.
ListInit ///< New-expression has a C++11 list-initializer.
};
CXXNewExpr(const ASTContext &C, bool globalNew, FunctionDecl *operatorNew,
FunctionDecl *operatorDelete, bool usualArrayDeleteWantsSize,
ArrayRef<Expr*> placementArgs,
SourceRange typeIdParens, Expr *arraySize,
InitializationStyle initializationStyle, Expr *initializer,
QualType ty, TypeSourceInfo *AllocatedTypeInfo,
SourceRange Range, SourceRange directInitRange);
explicit CXXNewExpr(EmptyShell Shell)
: Expr(CXXNewExprClass, Shell), SubExprs(0) { }
void AllocateArgsArray(const ASTContext &C, bool isArray,
unsigned numPlaceArgs, bool hasInitializer);
QualType getAllocatedType() const {
assert(getType()->isPointerType());
return getType()->getAs<PointerType>()->getPointeeType();
}
TypeSourceInfo *getAllocatedTypeSourceInfo() const {
return AllocatedTypeInfo;
}
/// \brief True if the allocation result needs to be null-checked.
///
/// C++11 [expr.new]p13:
/// If the allocation function returns null, initialization shall
/// not be done, the deallocation function shall not be called,
/// and the value of the new-expression shall be null.
///
/// An allocation function is not allowed to return null unless it
/// has a non-throwing exception-specification. The '03 rule is
/// identical except that the definition of a non-throwing
/// exception specification is just "is it throw()?".
bool shouldNullCheckAllocation(const ASTContext &Ctx) const;
FunctionDecl *getOperatorNew() const { return OperatorNew; }
void setOperatorNew(FunctionDecl *D) { OperatorNew = D; }
FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
void setOperatorDelete(FunctionDecl *D) { OperatorDelete = D; }
bool isArray() const { return Array; }
Expr *getArraySize() {
return Array ? cast<Expr>(SubExprs[0]) : 0;
}
const Expr *getArraySize() const {
return Array ? cast<Expr>(SubExprs[0]) : 0;
}
unsigned getNumPlacementArgs() const { return NumPlacementArgs; }
Expr **getPlacementArgs() {
return reinterpret_cast<Expr **>(SubExprs + Array + hasInitializer());
}
Expr *getPlacementArg(unsigned i) {
assert(i < NumPlacementArgs && "Index out of range");
return getPlacementArgs()[i];
}
const Expr *getPlacementArg(unsigned i) const {
assert(i < NumPlacementArgs && "Index out of range");
return const_cast<CXXNewExpr*>(this)->getPlacementArg(i);
}
bool isParenTypeId() const { return TypeIdParens.isValid(); }
SourceRange getTypeIdParens() const { return TypeIdParens; }
bool isGlobalNew() const { return GlobalNew; }
/// \brief Whether this new-expression has any initializer at all.
bool hasInitializer() const { return StoredInitializationStyle > 0; }
/// \brief The kind of initializer this new-expression has.
InitializationStyle getInitializationStyle() const {
if (StoredInitializationStyle == 0)
return NoInit;
return static_cast<InitializationStyle>(StoredInitializationStyle-1);
}
/// \brief The initializer of this new-expression.
Expr *getInitializer() {
return hasInitializer() ? cast<Expr>(SubExprs[Array]) : 0;
}
const Expr *getInitializer() const {
return hasInitializer() ? cast<Expr>(SubExprs[Array]) : 0;
}
/// \brief Returns the CXXConstructExpr from this new-expression, or null.
const CXXConstructExpr* getConstructExpr() const {
return dyn_cast_or_null<CXXConstructExpr>(getInitializer());
}
/// Answers whether the usual array deallocation function for the
/// allocated type expects the size of the allocation as a
/// parameter.
bool doesUsualArrayDeleteWantSize() const {
return UsualArrayDeleteWantsSize;
}
typedef ExprIterator arg_iterator;
typedef ConstExprIterator const_arg_iterator;
arg_iterator placement_arg_begin() {
return SubExprs + Array + hasInitializer();
}
arg_iterator placement_arg_end() {
return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
}
const_arg_iterator placement_arg_begin() const {
return SubExprs + Array + hasInitializer();
}
const_arg_iterator placement_arg_end() const {
return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
}
typedef Stmt **raw_arg_iterator;
raw_arg_iterator raw_arg_begin() { return SubExprs; }
raw_arg_iterator raw_arg_end() {
return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
}
const_arg_iterator raw_arg_begin() const { return SubExprs; }
const_arg_iterator raw_arg_end() const {
return SubExprs + Array + hasInitializer() + getNumPlacementArgs();
}
SourceLocation getStartLoc() const { return Range.getBegin(); }
SourceLocation getEndLoc() const { return Range.getEnd(); }
SourceRange getDirectInitRange() const { return DirectInitRange; }
SourceRange getSourceRange() const LLVM_READONLY {
return Range;
}
SourceLocation getLocStart() const LLVM_READONLY { return getStartLoc(); }
SourceLocation getLocEnd() const LLVM_READONLY { return getEndLoc(); }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXNewExprClass;
}
// Iterators
child_range children() {
return child_range(raw_arg_begin(), raw_arg_end());
}
};
/// \brief Represents a \c delete expression for memory deallocation and
/// destructor calls, e.g. "delete[] pArray".
class CXXDeleteExpr : public Expr {
/// Points to the operator delete overload that is used. Could be a member.
FunctionDecl *OperatorDelete;
/// The pointer expression to be deleted.
Stmt *Argument;
/// Location of the expression.
SourceLocation Loc;
/// Is this a forced global delete, i.e. "::delete"?
bool GlobalDelete : 1;
/// Is this the array form of delete, i.e. "delete[]"?
bool ArrayForm : 1;
/// ArrayFormAsWritten can be different from ArrayForm if 'delete' is applied
/// to pointer-to-array type (ArrayFormAsWritten will be false while ArrayForm
/// will be true).
bool ArrayFormAsWritten : 1;
/// Does the usual deallocation function for the element type require
/// a size_t argument?
bool UsualArrayDeleteWantsSize : 1;
public:
CXXDeleteExpr(QualType ty, bool globalDelete, bool arrayForm,
bool arrayFormAsWritten, bool usualArrayDeleteWantsSize,
FunctionDecl *operatorDelete, Expr *arg, SourceLocation loc)
: Expr(CXXDeleteExprClass, ty, VK_RValue, OK_Ordinary, false, false,
arg->isInstantiationDependent(),
arg->containsUnexpandedParameterPack()),
OperatorDelete(operatorDelete), Argument(arg), Loc(loc),
GlobalDelete(globalDelete),
ArrayForm(arrayForm), ArrayFormAsWritten(arrayFormAsWritten),
UsualArrayDeleteWantsSize(usualArrayDeleteWantsSize) { }
explicit CXXDeleteExpr(EmptyShell Shell)
: Expr(CXXDeleteExprClass, Shell), OperatorDelete(0), Argument(0) { }
bool isGlobalDelete() const { return GlobalDelete; }
bool isArrayForm() const { return ArrayForm; }
bool isArrayFormAsWritten() const { return ArrayFormAsWritten; }
/// Answers whether the usual array deallocation function for the
/// allocated type expects the size of the allocation as a
/// parameter. This can be true even if the actual deallocation
/// function that we're using doesn't want a size.
bool doesUsualArrayDeleteWantSize() const {
return UsualArrayDeleteWantsSize;
}
FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
Expr *getArgument() { return cast<Expr>(Argument); }
const Expr *getArgument() const { return cast<Expr>(Argument); }
/// \brief Retrieve the type being destroyed.
///
/// If the type being destroyed is a dependent type which may or may not
/// be a pointer, return an invalid type.
QualType getDestroyedType() const;
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY {return Argument->getLocEnd();}
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXDeleteExprClass;
}
// Iterators
child_range children() { return child_range(&Argument, &Argument+1); }
friend class ASTStmtReader;
};
/// \brief Stores the type being destroyed by a pseudo-destructor expression.
class PseudoDestructorTypeStorage {
/// \brief Either the type source information or the name of the type, if
/// it couldn't be resolved due to type-dependence.
llvm::PointerUnion<TypeSourceInfo *, IdentifierInfo *> Type;
/// \brief The starting source location of the pseudo-destructor type.
SourceLocation Location;
public:
PseudoDestructorTypeStorage() { }
PseudoDestructorTypeStorage(IdentifierInfo *II, SourceLocation Loc)
: Type(II), Location(Loc) { }
PseudoDestructorTypeStorage(TypeSourceInfo *Info);
TypeSourceInfo *getTypeSourceInfo() const {
return Type.dyn_cast<TypeSourceInfo *>();
}
IdentifierInfo *getIdentifier() const {
return Type.dyn_cast<IdentifierInfo *>();
}
SourceLocation getLocation() const { return Location; }
};
/// \brief Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
///
/// A pseudo-destructor is an expression that looks like a member access to a
/// destructor of a scalar type, except that scalar types don't have
/// destructors. For example:
///
/// \code
/// typedef int T;
/// void f(int *p) {
/// p->T::~T();
/// }
/// \endcode
///
/// Pseudo-destructors typically occur when instantiating templates such as:
///
/// \code
/// template<typename T>
/// void destroy(T* ptr) {
/// ptr->T::~T();
/// }
/// \endcode
///
/// for scalar types. A pseudo-destructor expression has no run-time semantics
/// beyond evaluating the base expression.
class CXXPseudoDestructorExpr : public Expr {
/// \brief The base expression (that is being destroyed).
Stmt *Base;
/// \brief Whether the operator was an arrow ('->'); otherwise, it was a
/// period ('.').
bool IsArrow : 1;
/// \brief The location of the '.' or '->' operator.
SourceLocation OperatorLoc;
/// \brief The nested-name-specifier that follows the operator, if present.
NestedNameSpecifierLoc QualifierLoc;
/// \brief The type that precedes the '::' in a qualified pseudo-destructor
/// expression.
TypeSourceInfo *ScopeType;
/// \brief The location of the '::' in a qualified pseudo-destructor
/// expression.
SourceLocation ColonColonLoc;
/// \brief The location of the '~'.
SourceLocation TildeLoc;
/// \brief The type being destroyed, or its name if we were unable to
/// resolve the name.
PseudoDestructorTypeStorage DestroyedType;
friend class ASTStmtReader;
public:
CXXPseudoDestructorExpr(const ASTContext &Context,
Expr *Base, bool isArrow, SourceLocation OperatorLoc,
NestedNameSpecifierLoc QualifierLoc,
TypeSourceInfo *ScopeType,
SourceLocation ColonColonLoc,
SourceLocation TildeLoc,
PseudoDestructorTypeStorage DestroyedType);
explicit CXXPseudoDestructorExpr(EmptyShell Shell)
: Expr(CXXPseudoDestructorExprClass, Shell),
Base(0), IsArrow(false), QualifierLoc(), ScopeType(0) { }
Expr *getBase() const { return cast<Expr>(Base); }
/// \brief Determines whether this member expression actually had
/// a C++ nested-name-specifier prior to the name of the member, e.g.,
/// x->Base::foo.
bool hasQualifier() const { return QualifierLoc.hasQualifier(); }
/// \brief Retrieves the nested-name-specifier that qualifies the type name,
/// with source-location information.
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
/// \brief If the member name was qualified, retrieves the
/// nested-name-specifier that precedes the member name. Otherwise, returns
/// null.
NestedNameSpecifier *getQualifier() const {
return QualifierLoc.getNestedNameSpecifier();
}
/// \brief Determine whether this pseudo-destructor expression was written
/// using an '->' (otherwise, it used a '.').
bool isArrow() const { return IsArrow; }
/// \brief Retrieve the location of the '.' or '->' operator.
SourceLocation getOperatorLoc() const { return OperatorLoc; }
/// \brief Retrieve the scope type in a qualified pseudo-destructor
/// expression.
///
/// Pseudo-destructor expressions can have extra qualification within them
/// that is not part of the nested-name-specifier, e.g., \c p->T::~T().
/// Here, if the object type of the expression is (or may be) a scalar type,
/// \p T may also be a scalar type and, therefore, cannot be part of a
/// nested-name-specifier. It is stored as the "scope type" of the pseudo-
/// destructor expression.
TypeSourceInfo *getScopeTypeInfo() const { return ScopeType; }
/// \brief Retrieve the location of the '::' in a qualified pseudo-destructor
/// expression.
SourceLocation getColonColonLoc() const { return ColonColonLoc; }
/// \brief Retrieve the location of the '~'.
SourceLocation getTildeLoc() const { return TildeLoc; }
/// \brief Retrieve the source location information for the type
/// being destroyed.
///
/// This type-source information is available for non-dependent
/// pseudo-destructor expressions and some dependent pseudo-destructor
/// expressions. Returns null if we only have the identifier for a
/// dependent pseudo-destructor expression.
TypeSourceInfo *getDestroyedTypeInfo() const {
return DestroyedType.getTypeSourceInfo();
}
/// \brief In a dependent pseudo-destructor expression for which we do not
/// have full type information on the destroyed type, provides the name
/// of the destroyed type.
IdentifierInfo *getDestroyedTypeIdentifier() const {
return DestroyedType.getIdentifier();
}
/// \brief Retrieve the type being destroyed.
QualType getDestroyedType() const;
/// \brief Retrieve the starting location of the type being destroyed.
SourceLocation getDestroyedTypeLoc() const {
return DestroyedType.getLocation();
}
/// \brief Set the name of destroyed type for a dependent pseudo-destructor
/// expression.
void setDestroyedType(IdentifierInfo *II, SourceLocation Loc) {
DestroyedType = PseudoDestructorTypeStorage(II, Loc);
}
/// \brief Set the destroyed type.
void setDestroyedType(TypeSourceInfo *Info) {
DestroyedType = PseudoDestructorTypeStorage(Info);
}
SourceLocation getLocStart() const LLVM_READONLY {return Base->getLocStart();}
SourceLocation getLocEnd() const LLVM_READONLY;
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXPseudoDestructorExprClass;
}
// Iterators
child_range children() { return child_range(&Base, &Base + 1); }
};
/// \brief Represents a GCC or MS unary type trait, as used in the
/// implementation of TR1/C++11 type trait templates.
///
/// Example:
/// \code
/// __is_pod(int) == true
/// __is_enum(std::string) == false
/// \endcode
class UnaryTypeTraitExpr : public Expr {
/// \brief The trait. A UnaryTypeTrait enum in MSVC compatible unsigned.
unsigned UTT : 31;
/// The value of the type trait. Unspecified if dependent.
bool Value : 1;
/// \brief The location of the type trait keyword.
SourceLocation Loc;
/// \brief The location of the closing paren.
SourceLocation RParen;
/// \brief The type being queried.
TypeSourceInfo *QueriedType;
public:
UnaryTypeTraitExpr(SourceLocation loc, UnaryTypeTrait utt,
TypeSourceInfo *queried, bool value,
SourceLocation rparen, QualType ty)
: Expr(UnaryTypeTraitExprClass, ty, VK_RValue, OK_Ordinary,
false, queried->getType()->isDependentType(),
queried->getType()->isInstantiationDependentType(),
queried->getType()->containsUnexpandedParameterPack()),
UTT(utt), Value(value), Loc(loc), RParen(rparen), QueriedType(queried) { }
explicit UnaryTypeTraitExpr(EmptyShell Empty)
: Expr(UnaryTypeTraitExprClass, Empty), UTT(0), Value(false),
QueriedType() { }
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return RParen; }
UnaryTypeTrait getTrait() const { return static_cast<UnaryTypeTrait>(UTT); }
QualType getQueriedType() const { return QueriedType->getType(); }
TypeSourceInfo *getQueriedTypeSourceInfo() const { return QueriedType; }
bool getValue() const { return Value; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == UnaryTypeTraitExprClass;
}
// Iterators
child_range children() { return child_range(); }
friend class ASTStmtReader;
};
/// \brief Represents a GCC or MS binary type trait, as used in the
/// implementation of TR1/C++11 type trait templates.
///
/// Example:
/// \code
/// __is_base_of(Base, Derived) == true
/// \endcode
class BinaryTypeTraitExpr : public Expr {
/// \brief The trait. A BinaryTypeTrait enum in MSVC compatible unsigned.
unsigned BTT : 8;
/// The value of the type trait. Unspecified if dependent.
bool Value : 1;
/// \brief The location of the type trait keyword.
SourceLocation Loc;
/// \brief The location of the closing paren.
SourceLocation RParen;
/// \brief The lhs type being queried.
TypeSourceInfo *LhsType;
/// \brief The rhs type being queried.
TypeSourceInfo *RhsType;
public:
BinaryTypeTraitExpr(SourceLocation loc, BinaryTypeTrait btt,
TypeSourceInfo *lhsType, TypeSourceInfo *rhsType,
bool value, SourceLocation rparen, QualType ty)
: Expr(BinaryTypeTraitExprClass, ty, VK_RValue, OK_Ordinary, false,
lhsType->getType()->isDependentType() ||
rhsType->getType()->isDependentType(),
(lhsType->getType()->isInstantiationDependentType() ||
rhsType->getType()->isInstantiationDependentType()),
(lhsType->getType()->containsUnexpandedParameterPack() ||
rhsType->getType()->containsUnexpandedParameterPack())),
BTT(btt), Value(value), Loc(loc), RParen(rparen),
LhsType(lhsType), RhsType(rhsType) { }
explicit BinaryTypeTraitExpr(EmptyShell Empty)
: Expr(BinaryTypeTraitExprClass, Empty), BTT(0), Value(false),
LhsType(), RhsType() { }
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return RParen; }
BinaryTypeTrait getTrait() const {
return static_cast<BinaryTypeTrait>(BTT);
}
QualType getLhsType() const { return LhsType->getType(); }
QualType getRhsType() const { return RhsType->getType(); }
TypeSourceInfo *getLhsTypeSourceInfo() const { return LhsType; }
TypeSourceInfo *getRhsTypeSourceInfo() const { return RhsType; }
bool getValue() const { assert(!isTypeDependent()); return Value; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == BinaryTypeTraitExprClass;
}
// Iterators
child_range children() { return child_range(); }
friend class ASTStmtReader;
};
/// \brief A type trait used in the implementation of various C++11 and
/// Library TR1 trait templates.
///
/// \code
/// __is_trivially_constructible(vector<int>, int*, int*)
/// \endcode
class TypeTraitExpr : public Expr {
/// \brief The location of the type trait keyword.
SourceLocation Loc;
/// \brief The location of the closing parenthesis.
SourceLocation RParenLoc;
// Note: The TypeSourceInfos for the arguments are allocated after the
// TypeTraitExpr.
TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
ArrayRef<TypeSourceInfo *> Args,
SourceLocation RParenLoc,
bool Value);
TypeTraitExpr(EmptyShell Empty) : Expr(TypeTraitExprClass, Empty) { }
/// \brief Retrieve the argument types.
TypeSourceInfo **getTypeSourceInfos() {
return reinterpret_cast<TypeSourceInfo **>(this+1);
}
/// \brief Retrieve the argument types.
TypeSourceInfo * const *getTypeSourceInfos() const {
return reinterpret_cast<TypeSourceInfo * const*>(this+1);
}
public:
/// \brief Create a new type trait expression.
static TypeTraitExpr *Create(const ASTContext &C, QualType T,
SourceLocation Loc, TypeTrait Kind,
ArrayRef<TypeSourceInfo *> Args,
SourceLocation RParenLoc,
bool Value);
static TypeTraitExpr *CreateDeserialized(const ASTContext &C,
unsigned NumArgs);
/// \brief Determine which type trait this expression uses.
TypeTrait getTrait() const {
return static_cast<TypeTrait>(TypeTraitExprBits.Kind);
}
bool getValue() const {
assert(!isValueDependent());
return TypeTraitExprBits.Value;
}
/// \brief Determine the number of arguments to this type trait.
unsigned getNumArgs() const { return TypeTraitExprBits.NumArgs; }
/// \brief Retrieve the Ith argument.
TypeSourceInfo *getArg(unsigned I) const {
assert(I < getNumArgs() && "Argument out-of-range");
return getArgs()[I];
}
/// \brief Retrieve the argument types.
ArrayRef<TypeSourceInfo *> getArgs() const {
return ArrayRef<TypeSourceInfo *>(getTypeSourceInfos(), getNumArgs());
}
typedef TypeSourceInfo **arg_iterator;
arg_iterator arg_begin() {
return getTypeSourceInfos();
}
arg_iterator arg_end() {
return getTypeSourceInfos() + getNumArgs();
}
typedef TypeSourceInfo const * const *arg_const_iterator;
arg_const_iterator arg_begin() const { return getTypeSourceInfos(); }
arg_const_iterator arg_end() const {
return getTypeSourceInfos() + getNumArgs();
}
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == TypeTraitExprClass;
}
// Iterators
child_range children() { return child_range(); }
friend class ASTStmtReader;
friend class ASTStmtWriter;
};
/// \brief An Embarcadero array type trait, as used in the implementation of
/// __array_rank and __array_extent.
///
/// Example:
/// \code
/// __array_rank(int[10][20]) == 2
/// __array_extent(int, 1) == 20
/// \endcode
class ArrayTypeTraitExpr : public Expr {
virtual void anchor();
/// \brief The trait. An ArrayTypeTrait enum in MSVC compat unsigned.
unsigned ATT : 2;
/// \brief The value of the type trait. Unspecified if dependent.
uint64_t Value;
/// \brief The array dimension being queried, or -1 if not used.
Expr *Dimension;
/// \brief The location of the type trait keyword.
SourceLocation Loc;
/// \brief The location of the closing paren.
SourceLocation RParen;
/// \brief The type being queried.
TypeSourceInfo *QueriedType;
public:
ArrayTypeTraitExpr(SourceLocation loc, ArrayTypeTrait att,
TypeSourceInfo *queried, uint64_t value,
Expr *dimension, SourceLocation rparen, QualType ty)
: Expr(ArrayTypeTraitExprClass, ty, VK_RValue, OK_Ordinary,
false, queried->getType()->isDependentType(),
(queried->getType()->isInstantiationDependentType() ||
(dimension && dimension->isInstantiationDependent())),
queried->getType()->containsUnexpandedParameterPack()),
ATT(att), Value(value), Dimension(dimension),
Loc(loc), RParen(rparen), QueriedType(queried) { }
explicit ArrayTypeTraitExpr(EmptyShell Empty)
: Expr(ArrayTypeTraitExprClass, Empty), ATT(0), Value(false),
QueriedType() { }
virtual ~ArrayTypeTraitExpr() { }
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return RParen; }
ArrayTypeTrait getTrait() const { return static_cast<ArrayTypeTrait>(ATT); }
QualType getQueriedType() const { return QueriedType->getType(); }
TypeSourceInfo *getQueriedTypeSourceInfo() const { return QueriedType; }
uint64_t getValue() const { assert(!isTypeDependent()); return Value; }
Expr *getDimensionExpression() const { return Dimension; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == ArrayTypeTraitExprClass;
}
// Iterators
child_range children() { return child_range(); }
friend class ASTStmtReader;
};
/// \brief An expression trait intrinsic.
///
/// Example:
/// \code
/// __is_lvalue_expr(std::cout) == true
/// __is_lvalue_expr(1) == false
/// \endcode
class ExpressionTraitExpr : public Expr {
/// \brief The trait. A ExpressionTrait enum in MSVC compatible unsigned.
unsigned ET : 31;
/// \brief The value of the type trait. Unspecified if dependent.
bool Value : 1;
/// \brief The location of the type trait keyword.
SourceLocation Loc;
/// \brief The location of the closing paren.
SourceLocation RParen;
/// \brief The expression being queried.
Expr* QueriedExpression;
public:
ExpressionTraitExpr(SourceLocation loc, ExpressionTrait et,
Expr *queried, bool value,
SourceLocation rparen, QualType resultType)
: Expr(ExpressionTraitExprClass, resultType, VK_RValue, OK_Ordinary,
false, // Not type-dependent
// Value-dependent if the argument is type-dependent.
queried->isTypeDependent(),
queried->isInstantiationDependent(),
queried->containsUnexpandedParameterPack()),
ET(et), Value(value), Loc(loc), RParen(rparen),
QueriedExpression(queried) { }
explicit ExpressionTraitExpr(EmptyShell Empty)
: Expr(ExpressionTraitExprClass, Empty), ET(0), Value(false),
QueriedExpression() { }
SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
SourceLocation getLocEnd() const LLVM_READONLY { return RParen; }
ExpressionTrait getTrait() const { return static_cast<ExpressionTrait>(ET); }
Expr *getQueriedExpression() const { return QueriedExpression; }
bool getValue() const { return Value; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == ExpressionTraitExprClass;
}
// Iterators
child_range children() { return child_range(); }
friend class ASTStmtReader;
};
/// \brief A reference to an overloaded function set, either an
/// \c UnresolvedLookupExpr or an \c UnresolvedMemberExpr.
class OverloadExpr : public Expr {
/// \brief The common name of these declarations.
DeclarationNameInfo NameInfo;
/// \brief The nested-name-specifier that qualifies the name, if any.
NestedNameSpecifierLoc QualifierLoc;
/// The results. These are undesugared, which is to say, they may
/// include UsingShadowDecls. Access is relative to the naming
/// class.
// FIXME: Allocate this data after the OverloadExpr subclass.
DeclAccessPair *Results;
unsigned NumResults;
protected:
/// \brief Whether the name includes info for explicit template
/// keyword and arguments.
bool HasTemplateKWAndArgsInfo;
/// \brief Return the optional template keyword and arguments info.
ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo(); // defined far below.
/// \brief Return the optional template keyword and arguments info.
const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
return const_cast<OverloadExpr*>(this)->getTemplateKWAndArgsInfo();
}
OverloadExpr(StmtClass K, const ASTContext &C,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs,
UnresolvedSetIterator Begin, UnresolvedSetIterator End,
bool KnownDependent,
bool KnownInstantiationDependent,
bool KnownContainsUnexpandedParameterPack);
OverloadExpr(StmtClass K, EmptyShell Empty)
: Expr(K, Empty), QualifierLoc(), Results(0), NumResults(0),
HasTemplateKWAndArgsInfo(false) { }
void initializeResults(const ASTContext &C,
UnresolvedSetIterator Begin,
UnresolvedSetIterator End);
public:
struct FindResult {
OverloadExpr *Expression;
bool IsAddressOfOperand;
bool HasFormOfMemberPointer;
};
/// \brief Finds the overloaded expression in the given expression \p E of
/// OverloadTy.
///
/// \return the expression (which must be there) and true if it has
/// the particular form of a member pointer expression
static FindResult find(Expr *E) {
assert(E->getType()->isSpecificBuiltinType(BuiltinType::Overload));
FindResult Result;
E = E->IgnoreParens();
if (isa<UnaryOperator>(E)) {
assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
E = cast<UnaryOperator>(E)->getSubExpr();
OverloadExpr *Ovl = cast<OverloadExpr>(E->IgnoreParens());
Result.HasFormOfMemberPointer = (E == Ovl && Ovl->getQualifier());
Result.IsAddressOfOperand = true;
Result.Expression = Ovl;
} else {
Result.HasFormOfMemberPointer = false;
Result.IsAddressOfOperand = false;
Result.Expression = cast<OverloadExpr>(E);
}
return Result;
}
/// \brief Gets the naming class of this lookup, if any.
CXXRecordDecl *getNamingClass() const;
typedef UnresolvedSetImpl::iterator decls_iterator;
decls_iterator decls_begin() const { return UnresolvedSetIterator(Results); }
decls_iterator decls_end() const {
return UnresolvedSetIterator(Results + NumResults);
}
/// \brief Gets the number of declarations in the unresolved set.
unsigned getNumDecls() const { return NumResults; }
/// \brief Gets the full name info.
const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
/// \brief Gets the name looked up.
DeclarationName getName() const { return NameInfo.getName(); }
/// \brief Gets the location of the name.
SourceLocation getNameLoc() const { return NameInfo.getLoc(); }
/// \brief Fetches the nested-name qualifier, if one was given.
NestedNameSpecifier *getQualifier() const {
return QualifierLoc.getNestedNameSpecifier();
}
/// \brief Fetches the nested-name qualifier with source-location
/// information, if one was given.
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
/// \brief Retrieve the location of the template keyword preceding
/// this name, if any.
SourceLocation getTemplateKeywordLoc() const {
if (!HasTemplateKWAndArgsInfo) return SourceLocation();
return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
}
/// \brief Retrieve the location of the left angle bracket starting the
/// explicit template argument list following the name, if any.
SourceLocation getLAngleLoc() const {
if (!HasTemplateKWAndArgsInfo) return SourceLocation();
return getTemplateKWAndArgsInfo()->LAngleLoc;
}
/// \brief Retrieve the location of the right angle bracket ending the
/// explicit template argument list following the name, if any.
SourceLocation getRAngleLoc() const {
if (!HasTemplateKWAndArgsInfo) return SourceLocation();
return getTemplateKWAndArgsInfo()->RAngleLoc;
}
/// \brief Determines whether the name was preceded by the template keyword.
bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
/// \brief Determines whether this expression had explicit template arguments.
bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
// Note that, inconsistently with the explicit-template-argument AST
// nodes, users are *forbidden* from calling these methods on objects
// without explicit template arguments.
ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
assert(hasExplicitTemplateArgs());
return *getTemplateKWAndArgsInfo();
}
const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
return const_cast<OverloadExpr*>(this)->getExplicitTemplateArgs();
}
TemplateArgumentLoc const *getTemplateArgs() const {
return getExplicitTemplateArgs().getTemplateArgs();
}
unsigned getNumTemplateArgs() const {
return getExplicitTemplateArgs().NumTemplateArgs;
}
/// \brief Copies the template arguments into the given structure.
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
getExplicitTemplateArgs().copyInto(List);
}
/// \brief Retrieves the optional explicit template arguments.
///
/// This points to the same data as getExplicitTemplateArgs(), but
/// returns null if there are no explicit template arguments.
const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
if (!hasExplicitTemplateArgs()) return 0;
return &getExplicitTemplateArgs();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == UnresolvedLookupExprClass ||
T->getStmtClass() == UnresolvedMemberExprClass;
}
friend class ASTStmtReader;
friend class ASTStmtWriter;
};
/// \brief A reference to a name which we were able to look up during
/// parsing but could not resolve to a specific declaration.
///
/// This arises in several ways:
/// * we might be waiting for argument-dependent lookup;
/// * the name might resolve to an overloaded function;
/// and eventually:
/// * the lookup might have included a function template.
///
/// These never include UnresolvedUsingValueDecls, which are always class
/// members and therefore appear only in UnresolvedMemberLookupExprs.
class UnresolvedLookupExpr : public OverloadExpr {
/// True if these lookup results should be extended by
/// argument-dependent lookup if this is the operand of a function
/// call.
bool RequiresADL;
/// True if these lookup results are overloaded. This is pretty
/// trivially rederivable if we urgently need to kill this field.
bool Overloaded;
/// The naming class (C++ [class.access.base]p5) of the lookup, if
/// any. This can generally be recalculated from the context chain,
/// but that can be fairly expensive for unqualified lookups. If we
/// want to improve memory use here, this could go in a union
/// against the qualified-lookup bits.
CXXRecordDecl *NamingClass;
UnresolvedLookupExpr(const ASTContext &C,
CXXRecordDecl *NamingClass,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
bool RequiresADL, bool Overloaded,
const TemplateArgumentListInfo *TemplateArgs,
UnresolvedSetIterator Begin, UnresolvedSetIterator End)
: OverloadExpr(UnresolvedLookupExprClass, C, QualifierLoc, TemplateKWLoc,
NameInfo, TemplateArgs, Begin, End, false, false, false),
RequiresADL(RequiresADL),
Overloaded(Overloaded), NamingClass(NamingClass)
{}
UnresolvedLookupExpr(EmptyShell Empty)
: OverloadExpr(UnresolvedLookupExprClass, Empty),
RequiresADL(false), Overloaded(false), NamingClass(0)
{}
friend class ASTStmtReader;
public:
static UnresolvedLookupExpr *Create(const ASTContext &C,
CXXRecordDecl *NamingClass,
NestedNameSpecifierLoc QualifierLoc,
const DeclarationNameInfo &NameInfo,
bool ADL, bool Overloaded,
UnresolvedSetIterator Begin,
UnresolvedSetIterator End) {
return new(C) UnresolvedLookupExpr(C, NamingClass, QualifierLoc,
SourceLocation(), NameInfo,
ADL, Overloaded, 0, Begin, End);
}
static UnresolvedLookupExpr *Create(const ASTContext &C,
CXXRecordDecl *NamingClass,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
bool ADL,
const TemplateArgumentListInfo *Args,
UnresolvedSetIterator Begin,
UnresolvedSetIterator End);
static UnresolvedLookupExpr *CreateEmpty(const ASTContext &C,
bool HasTemplateKWAndArgsInfo,
unsigned NumTemplateArgs);
/// True if this declaration should be extended by
/// argument-dependent lookup.
bool requiresADL() const { return RequiresADL; }
/// True if this lookup is overloaded.
bool isOverloaded() const { return Overloaded; }
/// Gets the 'naming class' (in the sense of C++0x
/// [class.access.base]p5) of the lookup. This is the scope
/// that was looked in to find these results.
CXXRecordDecl *getNamingClass() const { return NamingClass; }
SourceLocation getLocStart() const LLVM_READONLY {
if (NestedNameSpecifierLoc l = getQualifierLoc())
return l.getBeginLoc();
return getNameInfo().getLocStart();
}
SourceLocation getLocEnd() const LLVM_READONLY {
if (hasExplicitTemplateArgs())
return getRAngleLoc();
return getNameInfo().getLocEnd();
}
child_range children() { return child_range(); }
static bool classof(const Stmt *T) {
return T->getStmtClass() == UnresolvedLookupExprClass;
}
};
/// \brief A qualified reference to a name whose declaration cannot
/// yet be resolved.
///
/// DependentScopeDeclRefExpr is similar to DeclRefExpr in that
/// it expresses a reference to a declaration such as
/// X<T>::value. The difference, however, is that an
/// DependentScopeDeclRefExpr node is used only within C++ templates when
/// the qualification (e.g., X<T>::) refers to a dependent type. In
/// this case, X<T>::value cannot resolve to a declaration because the
/// declaration will differ from on instantiation of X<T> to the
/// next. Therefore, DependentScopeDeclRefExpr keeps track of the
/// qualifier (X<T>::) and the name of the entity being referenced
/// ("value"). Such expressions will instantiate to a DeclRefExpr once the
/// declaration can be found.
class DependentScopeDeclRefExpr : public Expr {
/// \brief The nested-name-specifier that qualifies this unresolved
/// declaration name.
NestedNameSpecifierLoc QualifierLoc;
/// \brief The name of the entity we will be referencing.
DeclarationNameInfo NameInfo;
/// \brief Whether the name includes info for explicit template
/// keyword and arguments.
bool HasTemplateKWAndArgsInfo;
/// \brief Return the optional template keyword and arguments info.
ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
if (!HasTemplateKWAndArgsInfo) return 0;
return reinterpret_cast<ASTTemplateKWAndArgsInfo*>(this + 1);
}
/// \brief Return the optional template keyword and arguments info.
const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
return const_cast<DependentScopeDeclRefExpr*>(this)
->getTemplateKWAndArgsInfo();
}
DependentScopeDeclRefExpr(QualType T,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *Args);
public:
static DependentScopeDeclRefExpr *Create(const ASTContext &C,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &NameInfo,
const TemplateArgumentListInfo *TemplateArgs);
static DependentScopeDeclRefExpr *CreateEmpty(const ASTContext &C,
bool HasTemplateKWAndArgsInfo,
unsigned NumTemplateArgs);
/// \brief Retrieve the name that this expression refers to.
const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
/// \brief Retrieve the name that this expression refers to.
DeclarationName getDeclName() const { return NameInfo.getName(); }
/// \brief Retrieve the location of the name within the expression.
SourceLocation getLocation() const { return NameInfo.getLoc(); }
/// \brief Retrieve the nested-name-specifier that qualifies the
/// name, with source location information.
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
/// \brief Retrieve the nested-name-specifier that qualifies this
/// declaration.
NestedNameSpecifier *getQualifier() const {
return QualifierLoc.getNestedNameSpecifier();
}
/// \brief Retrieve the location of the template keyword preceding
/// this name, if any.
SourceLocation getTemplateKeywordLoc() const {
if (!HasTemplateKWAndArgsInfo) return SourceLocation();
return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
}
/// \brief Retrieve the location of the left angle bracket starting the
/// explicit template argument list following the name, if any.
SourceLocation getLAngleLoc() const {
if (!HasTemplateKWAndArgsInfo) return SourceLocation();
return getTemplateKWAndArgsInfo()->LAngleLoc;
}
/// \brief Retrieve the location of the right angle bracket ending the
/// explicit template argument list following the name, if any.
SourceLocation getRAngleLoc() const {
if (!HasTemplateKWAndArgsInfo) return SourceLocation();
return getTemplateKWAndArgsInfo()->RAngleLoc;
}
/// Determines whether the name was preceded by the template keyword.
bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
/// Determines whether this lookup had explicit template arguments.
bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
// Note that, inconsistently with the explicit-template-argument AST
// nodes, users are *forbidden* from calling these methods on objects
// without explicit template arguments.
ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
assert(hasExplicitTemplateArgs());
return *reinterpret_cast<ASTTemplateArgumentListInfo*>(this + 1);
}
/// Gets a reference to the explicit template argument list.
const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
assert(hasExplicitTemplateArgs());
return *reinterpret_cast<const ASTTemplateArgumentListInfo*>(this + 1);
}
/// \brief Retrieves the optional explicit template arguments.
///
/// This points to the same data as getExplicitTemplateArgs(), but
/// returns null if there are no explicit template arguments.
const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
if (!hasExplicitTemplateArgs()) return 0;
return &getExplicitTemplateArgs();
}
/// \brief Copies the template arguments (if present) into the given
/// structure.
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
getExplicitTemplateArgs().copyInto(List);
}
TemplateArgumentLoc const *getTemplateArgs() const {
return getExplicitTemplateArgs().getTemplateArgs();
}
unsigned getNumTemplateArgs() const {
return getExplicitTemplateArgs().NumTemplateArgs;
}
SourceLocation getLocStart() const LLVM_READONLY {
return QualifierLoc.getBeginLoc();
}
SourceLocation getLocEnd() const LLVM_READONLY {
if (hasExplicitTemplateArgs())
return getRAngleLoc();
return getLocation();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == DependentScopeDeclRefExprClass;
}
child_range children() { return child_range(); }
friend class ASTStmtReader;
friend class ASTStmtWriter;
};
/// Represents an expression -- generally a full-expression -- that
/// introduces cleanups to be run at the end of the sub-expression's
/// evaluation. The most common source of expression-introduced
/// cleanups is temporary objects in C++, but several other kinds of
/// expressions can create cleanups, including basically every
/// call in ARC that returns an Objective-C pointer.
///
/// This expression also tracks whether the sub-expression contains a
/// potentially-evaluated block literal. The lifetime of a block
/// literal is the extent of the enclosing scope.
class ExprWithCleanups : public Expr {
public:
/// The type of objects that are kept in the cleanup.
/// It's useful to remember the set of blocks; we could also
/// remember the set of temporaries, but there's currently
/// no need.
typedef BlockDecl *CleanupObject;
private:
Stmt *SubExpr;
ExprWithCleanups(EmptyShell, unsigned NumObjects);
ExprWithCleanups(Expr *SubExpr, ArrayRef<CleanupObject> Objects);
CleanupObject *getObjectsBuffer() {
return reinterpret_cast<CleanupObject*>(this + 1);
}
const CleanupObject *getObjectsBuffer() const {
return reinterpret_cast<const CleanupObject*>(this + 1);
}
friend class ASTStmtReader;
public:
static ExprWithCleanups *Create(const ASTContext &C, EmptyShell empty,
unsigned numObjects);
static ExprWithCleanups *Create(const ASTContext &C, Expr *subexpr,
ArrayRef<CleanupObject> objects);
ArrayRef<CleanupObject> getObjects() const {
return ArrayRef<CleanupObject>(getObjectsBuffer(), getNumObjects());
}
unsigned getNumObjects() const { return ExprWithCleanupsBits.NumObjects; }
CleanupObject getObject(unsigned i) const {
assert(i < getNumObjects() && "Index out of range");
return getObjects()[i];
}
Expr *getSubExpr() { return cast<Expr>(SubExpr); }
const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
/// As with any mutator of the AST, be very careful
/// when modifying an existing AST to preserve its invariants.
void setSubExpr(Expr *E) { SubExpr = E; }
SourceLocation getLocStart() const LLVM_READONLY {
return SubExpr->getLocStart();
}
SourceLocation getLocEnd() const LLVM_READONLY { return SubExpr->getLocEnd();}
// Implement isa/cast/dyncast/etc.
static bool classof(const Stmt *T) {
return T->getStmtClass() == ExprWithCleanupsClass;
}
// Iterators
child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
};
/// \brief Describes an explicit type conversion that uses functional
/// notion but could not be resolved because one or more arguments are
/// type-dependent.
///
/// The explicit type conversions expressed by
/// CXXUnresolvedConstructExpr have the form <tt>T(a1, a2, ..., aN)</tt>,
/// where \c T is some type and \c a1, \c a2, ..., \c aN are values, and
/// either \c T is a dependent type or one or more of the <tt>a</tt>'s is
/// type-dependent. For example, this would occur in a template such
/// as:
///
/// \code
/// template<typename T, typename A1>
/// inline T make_a(const A1& a1) {
/// return T(a1);
/// }
/// \endcode
///
/// When the returned expression is instantiated, it may resolve to a
/// constructor call, conversion function call, or some kind of type
/// conversion.
class CXXUnresolvedConstructExpr : public Expr {
/// \brief The type being constructed.
TypeSourceInfo *Type;
/// \brief The location of the left parentheses ('(').
SourceLocation LParenLoc;
/// \brief The location of the right parentheses (')').
SourceLocation RParenLoc;
/// \brief The number of arguments used to construct the type.
unsigned NumArgs;
CXXUnresolvedConstructExpr(TypeSourceInfo *Type,
SourceLocation LParenLoc,
ArrayRef<Expr*> Args,
SourceLocation RParenLoc);
CXXUnresolvedConstructExpr(EmptyShell Empty, unsigned NumArgs)
: Expr(CXXUnresolvedConstructExprClass, Empty), Type(), NumArgs(NumArgs) { }
friend class ASTStmtReader;
public:
static CXXUnresolvedConstructExpr *Create(const ASTContext &C,
TypeSourceInfo *Type,
SourceLocation LParenLoc,
ArrayRef<Expr*> Args,
SourceLocation RParenLoc);
static CXXUnresolvedConstructExpr *CreateEmpty(const ASTContext &C,
unsigned NumArgs);
/// \brief Retrieve the type that is being constructed, as specified
/// in the source code.
QualType getTypeAsWritten() const { return Type->getType(); }
/// \brief Retrieve the type source information for the type being
/// constructed.
TypeSourceInfo *getTypeSourceInfo() const { return Type; }
/// \brief Retrieve the location of the left parentheses ('(') that
/// precedes the argument list.
SourceLocation getLParenLoc() const { return LParenLoc; }
void setLParenLoc(SourceLocation L) { LParenLoc = L; }
/// \brief Retrieve the location of the right parentheses (')') that
/// follows the argument list.
SourceLocation getRParenLoc() const { return RParenLoc; }
void setRParenLoc(SourceLocation L) { RParenLoc = L; }
/// \brief Retrieve the number of arguments.
unsigned arg_size() const { return NumArgs; }
typedef Expr** arg_iterator;
arg_iterator arg_begin() { return reinterpret_cast<Expr**>(this + 1); }
arg_iterator arg_end() { return arg_begin() + NumArgs; }
typedef const Expr* const * const_arg_iterator;
const_arg_iterator arg_begin() const {
return reinterpret_cast<const Expr* const *>(this + 1);
}
const_arg_iterator arg_end() const {
return arg_begin() + NumArgs;
}
Expr *getArg(unsigned I) {
assert(I < NumArgs && "Argument index out-of-range");
return *(arg_begin() + I);
}
const Expr *getArg(unsigned I) const {
assert(I < NumArgs && "Argument index out-of-range");
return *(arg_begin() + I);
}
void setArg(unsigned I, Expr *E) {
assert(I < NumArgs && "Argument index out-of-range");
*(arg_begin() + I) = E;
}
SourceLocation getLocStart() const LLVM_READONLY;
SourceLocation getLocEnd() const LLVM_READONLY {
assert(RParenLoc.isValid() || NumArgs == 1);
return RParenLoc.isValid() ? RParenLoc : getArg(0)->getLocEnd();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXUnresolvedConstructExprClass;
}
// Iterators
child_range children() {
Stmt **begin = reinterpret_cast<Stmt**>(this+1);
return child_range(begin, begin + NumArgs);
}
};
/// \brief Represents a C++ member access expression where the actual
/// member referenced could not be resolved because the base
/// expression or the member name was dependent.
///
/// Like UnresolvedMemberExprs, these can be either implicit or
/// explicit accesses. It is only possible to get one of these with
/// an implicit access if a qualifier is provided.
class CXXDependentScopeMemberExpr : public Expr {
/// \brief The expression for the base pointer or class reference,
/// e.g., the \c x in x.f. Can be null in implicit accesses.
Stmt *Base;
/// \brief The type of the base expression. Never null, even for
/// implicit accesses.
QualType BaseType;
/// \brief Whether this member expression used the '->' operator or
/// the '.' operator.
bool IsArrow : 1;
/// \brief Whether this member expression has info for explicit template
/// keyword and arguments.
bool HasTemplateKWAndArgsInfo : 1;
/// \brief The location of the '->' or '.' operator.
SourceLocation OperatorLoc;
/// \brief The nested-name-specifier that precedes the member name, if any.
NestedNameSpecifierLoc QualifierLoc;
/// \brief In a qualified member access expression such as t->Base::f, this
/// member stores the resolves of name lookup in the context of the member
/// access expression, to be used at instantiation time.
///
/// FIXME: This member, along with the QualifierLoc, could
/// be stuck into a structure that is optionally allocated at the end of
/// the CXXDependentScopeMemberExpr, to save space in the common case.
NamedDecl *FirstQualifierFoundInScope;
/// \brief The member to which this member expression refers, which
/// can be name, overloaded operator, or destructor.
///
/// FIXME: could also be a template-id
DeclarationNameInfo MemberNameInfo;
/// \brief Return the optional template keyword and arguments info.
ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() {
if (!HasTemplateKWAndArgsInfo) return 0;
return reinterpret_cast<ASTTemplateKWAndArgsInfo*>(this + 1);
}
/// \brief Return the optional template keyword and arguments info.
const ASTTemplateKWAndArgsInfo *getTemplateKWAndArgsInfo() const {
return const_cast<CXXDependentScopeMemberExpr*>(this)
->getTemplateKWAndArgsInfo();
}
CXXDependentScopeMemberExpr(const ASTContext &C, Expr *Base,
QualType BaseType, bool IsArrow,
SourceLocation OperatorLoc,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateKWLoc,
NamedDecl *FirstQualifierFoundInScope,
DeclarationNameInfo MemberNameInfo,
const TemplateArgumentListInfo *TemplateArgs);
public:
CXXDependentScopeMemberExpr(const ASTContext &C, Expr *Base,
QualType BaseType, bool IsArrow,
SourceLocation OperatorLoc,
NestedNameSpecifierLoc QualifierLoc,
NamedDecl *FirstQualifierFoundInScope,
DeclarationNameInfo MemberNameInfo);
static CXXDependentScopeMemberExpr *
Create(const ASTContext &C, Expr *Base, QualType BaseType, bool IsArrow,
SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,
DeclarationNameInfo MemberNameInfo,
const TemplateArgumentListInfo *TemplateArgs);
static CXXDependentScopeMemberExpr *
CreateEmpty(const ASTContext &C, bool HasTemplateKWAndArgsInfo,
unsigned NumTemplateArgs);
/// \brief True if this is an implicit access, i.e. one in which the
/// member being accessed was not written in the source. The source
/// location of the operator is invalid in this case.
bool isImplicitAccess() const;
/// \brief Retrieve the base object of this member expressions,
/// e.g., the \c x in \c x.m.
Expr *getBase() const {
assert(!isImplicitAccess());
return cast<Expr>(Base);
}
QualType getBaseType() const { return BaseType; }
/// \brief Determine whether this member expression used the '->'
/// operator; otherwise, it used the '.' operator.
bool isArrow() const { return IsArrow; }
/// \brief Retrieve the location of the '->' or '.' operator.
SourceLocation getOperatorLoc() const { return OperatorLoc; }
/// \brief Retrieve the nested-name-specifier that qualifies the member
/// name.
NestedNameSpecifier *getQualifier() const {
return QualifierLoc.getNestedNameSpecifier();
}
/// \brief Retrieve the nested-name-specifier that qualifies the member
/// name, with source location information.
NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
/// \brief Retrieve the first part of the nested-name-specifier that was
/// found in the scope of the member access expression when the member access
/// was initially parsed.
///
/// This function only returns a useful result when member access expression
/// uses a qualified member name, e.g., "x.Base::f". Here, the declaration
/// returned by this function describes what was found by unqualified name
/// lookup for the identifier "Base" within the scope of the member access
/// expression itself. At template instantiation time, this information is
/// combined with the results of name lookup into the type of the object
/// expression itself (the class type of x).
NamedDecl *getFirstQualifierFoundInScope() const {
return FirstQualifierFoundInScope;
}
/// \brief Retrieve the name of the member that this expression
/// refers to.
const DeclarationNameInfo &getMemberNameInfo() const {
return MemberNameInfo;
}
/// \brief Retrieve the name of the member that this expression
/// refers to.
DeclarationName getMember() const { return MemberNameInfo.getName(); }
// \brief Retrieve the location of the name of the member that this
// expression refers to.
SourceLocation getMemberLoc() const { return MemberNameInfo.getLoc(); }
/// \brief Retrieve the location of the template keyword preceding the
/// member name, if any.
SourceLocation getTemplateKeywordLoc() const {
if (!HasTemplateKWAndArgsInfo) return SourceLocation();
return getTemplateKWAndArgsInfo()->getTemplateKeywordLoc();
}
/// \brief Retrieve the location of the left angle bracket starting the
/// explicit template argument list following the member name, if any.
SourceLocation getLAngleLoc() const {
if (!HasTemplateKWAndArgsInfo) return SourceLocation();
return getTemplateKWAndArgsInfo()->LAngleLoc;
}
/// \brief Retrieve the location of the right angle bracket ending the
/// explicit template argument list following the member name, if any.
SourceLocation getRAngleLoc() const {
if (!HasTemplateKWAndArgsInfo) return SourceLocation();
return getTemplateKWAndArgsInfo()->RAngleLoc;
}
/// Determines whether the member name was preceded by the template keyword.
bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
/// \brief Determines whether this member expression actually had a C++
/// template argument list explicitly specified, e.g., x.f<int>.
bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
/// \brief Retrieve the explicit template argument list that followed the
/// member template name, if any.
ASTTemplateArgumentListInfo &getExplicitTemplateArgs() {
assert(hasExplicitTemplateArgs());
return *reinterpret_cast<ASTTemplateArgumentListInfo *>(this + 1);
}
/// \brief Retrieve the explicit template argument list that followed the
/// member template name, if any.
const ASTTemplateArgumentListInfo &getExplicitTemplateArgs() const {
return const_cast<CXXDependentScopeMemberExpr *>(this)
->getExplicitTemplateArgs();
}
/// \brief Retrieves the optional explicit template arguments.
///
/// This points to the same data as getExplicitTemplateArgs(), but
/// returns null if there are no explicit template arguments.
const ASTTemplateArgumentListInfo *getOptionalExplicitTemplateArgs() const {
if (!hasExplicitTemplateArgs()) return 0;
return &getExplicitTemplateArgs();
}
/// \brief Copies the template arguments (if present) into the given
/// structure.
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
getExplicitTemplateArgs().copyInto(List);
}
/// \brief Initializes the template arguments using the given structure.
void initializeTemplateArgumentsFrom(const TemplateArgumentListInfo &List) {
getExplicitTemplateArgs().initializeFrom(List);
}
/// \brief Retrieve the template arguments provided as part of this
/// template-id.
const TemplateArgumentLoc *getTemplateArgs() const {
return getExplicitTemplateArgs().getTemplateArgs();
}
/// \brief Retrieve the number of template arguments provided as part of this
/// template-id.
unsigned getNumTemplateArgs() const {
return getExplicitTemplateArgs().NumTemplateArgs;
}
SourceLocation getLocStart() const LLVM_READONLY {
if (!isImplicitAccess())
return Base->getLocStart();
if (getQualifier())
return getQualifierLoc().getBeginLoc();
return MemberNameInfo.getBeginLoc();
}
SourceLocation getLocEnd() const LLVM_READONLY {
if (hasExplicitTemplateArgs())
return getRAngleLoc();
return MemberNameInfo.getEndLoc();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXDependentScopeMemberExprClass;
}
// Iterators
child_range children() {
if (isImplicitAccess()) return child_range();
return child_range(&Base, &Base + 1);
}
friend class ASTStmtReader;
friend class ASTStmtWriter;
};
/// \brief Represents a C++ member access expression for which lookup
/// produced a set of overloaded functions.
///
/// The member access may be explicit or implicit:
/// \code
/// struct A {
/// int a, b;
/// int explicitAccess() { return this->a + this->A::b; }
/// int implicitAccess() { return a + A::b; }
/// };
/// \endcode
///
/// In the final AST, an explicit access always becomes a MemberExpr.
/// An implicit access may become either a MemberExpr or a
/// DeclRefExpr, depending on whether the member is static.
class UnresolvedMemberExpr : public OverloadExpr {
/// \brief Whether this member expression used the '->' operator or
/// the '.' operator.
bool IsArrow : 1;
/// \brief Whether the lookup results contain an unresolved using
/// declaration.
bool HasUnresolvedUsing : 1;
/// \brief The expression for the base pointer or class reference,
/// e.g., the \c x in x.f.
///
/// This can be null if this is an 'unbased' member expression.
Stmt *Base;
/// \brief The type of the base expression; never null.
QualType BaseType;
/// \brief The location of the '->' or '.' operator.
SourceLocation OperatorLoc;
UnresolvedMemberExpr(const ASTContext &C, bool HasUnresolvedUsing,
Expr *Base, QualType BaseType, bool IsArrow,
SourceLocation OperatorLoc,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &MemberNameInfo,
const TemplateArgumentListInfo *TemplateArgs,
UnresolvedSetIterator Begin, UnresolvedSetIterator End);
UnresolvedMemberExpr(EmptyShell Empty)
: OverloadExpr(UnresolvedMemberExprClass, Empty), IsArrow(false),
HasUnresolvedUsing(false), Base(0) { }
friend class ASTStmtReader;
public:
static UnresolvedMemberExpr *
Create(const ASTContext &C, bool HasUnresolvedUsing,
Expr *Base, QualType BaseType, bool IsArrow,
SourceLocation OperatorLoc,
NestedNameSpecifierLoc QualifierLoc,
SourceLocation TemplateKWLoc,
const DeclarationNameInfo &MemberNameInfo,
const TemplateArgumentListInfo *TemplateArgs,
UnresolvedSetIterator Begin, UnresolvedSetIterator End);
static UnresolvedMemberExpr *
CreateEmpty(const ASTContext &C, bool HasTemplateKWAndArgsInfo,
unsigned NumTemplateArgs);
/// \brief True if this is an implicit access, i.e., one in which the
/// member being accessed was not written in the source.
///
/// The source location of the operator is invalid in this case.
bool isImplicitAccess() const;
/// \brief Retrieve the base object of this member expressions,
/// e.g., the \c x in \c x.m.
Expr *getBase() {
assert(!isImplicitAccess());
return cast<Expr>(Base);
}
const Expr *getBase() const {
assert(!isImplicitAccess());
return cast<Expr>(Base);
}
QualType getBaseType() const { return BaseType; }
/// \brief Determine whether the lookup results contain an unresolved using
/// declaration.
bool hasUnresolvedUsing() const { return HasUnresolvedUsing; }
/// \brief Determine whether this member expression used the '->'
/// operator; otherwise, it used the '.' operator.
bool isArrow() const { return IsArrow; }
/// \brief Retrieve the location of the '->' or '.' operator.
SourceLocation getOperatorLoc() const { return OperatorLoc; }
/// \brief Retrieve the naming class of this lookup.
CXXRecordDecl *getNamingClass() const;
/// \brief Retrieve the full name info for the member that this expression
/// refers to.
const DeclarationNameInfo &getMemberNameInfo() const { return getNameInfo(); }
/// \brief Retrieve the name of the member that this expression
/// refers to.
DeclarationName getMemberName() const { return getName(); }
// \brief Retrieve the location of the name of the member that this
// expression refers to.
SourceLocation getMemberLoc() const { return getNameLoc(); }
// \brief Return the preferred location (the member name) for the arrow when
// diagnosing a problem with this expression.
SourceLocation getExprLoc() const LLVM_READONLY { return getMemberLoc(); }
SourceLocation getLocStart() const LLVM_READONLY {
if (!isImplicitAccess())
return Base->getLocStart();
if (NestedNameSpecifierLoc l = getQualifierLoc())
return l.getBeginLoc();
return getMemberNameInfo().getLocStart();
}
SourceLocation getLocEnd() const LLVM_READONLY {
if (hasExplicitTemplateArgs())
return getRAngleLoc();
return getMemberNameInfo().getLocEnd();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == UnresolvedMemberExprClass;
}
// Iterators
child_range children() {
if (isImplicitAccess()) return child_range();
return child_range(&Base, &Base + 1);
}
};
/// \brief Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
///
/// The noexcept expression tests whether a given expression might throw. Its
/// result is a boolean constant.
class CXXNoexceptExpr : public Expr {
bool Value : 1;
Stmt *Operand;
SourceRange Range;
friend class ASTStmtReader;
public:
CXXNoexceptExpr(QualType Ty, Expr *Operand, CanThrowResult Val,
SourceLocation Keyword, SourceLocation RParen)
: Expr(CXXNoexceptExprClass, Ty, VK_RValue, OK_Ordinary,
/*TypeDependent*/false,
/*ValueDependent*/Val == CT_Dependent,
Val == CT_Dependent || Operand->isInstantiationDependent(),
Operand->containsUnexpandedParameterPack()),
Value(Val == CT_Cannot), Operand(Operand), Range(Keyword, RParen)
{ }
CXXNoexceptExpr(EmptyShell Empty)
: Expr(CXXNoexceptExprClass, Empty)
{ }
Expr *getOperand() const { return static_cast<Expr*>(Operand); }
SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
SourceRange getSourceRange() const LLVM_READONLY { return Range; }
bool getValue() const { return Value; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == CXXNoexceptExprClass;
}
// Iterators
child_range children() { return child_range(&Operand, &Operand + 1); }
};
/// \brief Represents a C++11 pack expansion that produces a sequence of
/// expressions.
///
/// A pack expansion expression contains a pattern (which itself is an
/// expression) followed by an ellipsis. For example:
///
/// \code
/// template<typename F, typename ...Types>
/// void forward(F f, Types &&...args) {
/// f(static_cast<Types&&>(args)...);
/// }
/// \endcode
///
/// Here, the argument to the function object \c f is a pack expansion whose
/// pattern is \c static_cast<Types&&>(args). When the \c forward function
/// template is instantiated, the pack expansion will instantiate to zero or
/// or more function arguments to the function object \c f.
class PackExpansionExpr : public Expr {
SourceLocation EllipsisLoc;
/// \brief The number of expansions that will be produced by this pack
/// expansion expression, if known.
///
/// When zero, the number of expansions is not known. Otherwise, this value
/// is the number of expansions + 1.
unsigned NumExpansions;
Stmt *Pattern;
friend class ASTStmtReader;
friend class ASTStmtWriter;
public:
PackExpansionExpr(QualType T, Expr *Pattern, SourceLocation EllipsisLoc,
Optional<unsigned> NumExpansions)
: Expr(PackExpansionExprClass, T, Pattern->getValueKind(),
Pattern->getObjectKind(), /*TypeDependent=*/true,
/*ValueDependent=*/true, /*InstantiationDependent=*/true,
/*ContainsUnexpandedParameterPack=*/false),
EllipsisLoc(EllipsisLoc),
NumExpansions(NumExpansions? *NumExpansions + 1 : 0),
Pattern(Pattern) { }
PackExpansionExpr(EmptyShell Empty) : Expr(PackExpansionExprClass, Empty) { }
/// \brief Retrieve the pattern of the pack expansion.
Expr *getPattern() { return reinterpret_cast<Expr *>(Pattern); }
/// \brief Retrieve the pattern of the pack expansion.
const Expr *getPattern() const { return reinterpret_cast<Expr *>(Pattern); }
/// \brief Retrieve the location of the ellipsis that describes this pack
/// expansion.
SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
/// \brief Determine the number of expansions that will be produced when
/// this pack expansion is instantiated, if already known.
Optional<unsigned> getNumExpansions() const {
if (NumExpansions)
return NumExpansions - 1;
return None;
}
SourceLocation getLocStart() const LLVM_READONLY {
return Pattern->getLocStart();
}
SourceLocation getLocEnd() const LLVM_READONLY { return EllipsisLoc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == PackExpansionExprClass;
}
// Iterators
child_range children() {
return child_range(&Pattern, &Pattern + 1);
}
};
inline ASTTemplateKWAndArgsInfo *OverloadExpr::getTemplateKWAndArgsInfo() {
if (!HasTemplateKWAndArgsInfo) return 0;
if (isa<UnresolvedLookupExpr>(this))
return reinterpret_cast<ASTTemplateKWAndArgsInfo*>
(cast<UnresolvedLookupExpr>(this) + 1);
else
return reinterpret_cast<ASTTemplateKWAndArgsInfo*>
(cast<UnresolvedMemberExpr>(this) + 1);
}
/// \brief Represents an expression that computes the length of a parameter
/// pack.
///
/// \code
/// template<typename ...Types>
/// struct count {
/// static const unsigned value = sizeof...(Types);
/// };
/// \endcode
class SizeOfPackExpr : public Expr {
/// \brief The location of the \c sizeof keyword.
SourceLocation OperatorLoc;
/// \brief The location of the name of the parameter pack.
SourceLocation PackLoc;
/// \brief The location of the closing parenthesis.
SourceLocation RParenLoc;
/// \brief The length of the parameter pack, if known.
///
/// When this expression is value-dependent, the length of the parameter pack
/// is unknown. When this expression is not value-dependent, the length is
/// known.
unsigned Length;
/// \brief The parameter pack itself.
NamedDecl *Pack;
friend class ASTStmtReader;
friend class ASTStmtWriter;
public:
/// \brief Create a value-dependent expression that computes the length of
/// the given parameter pack.
SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl *Pack,
SourceLocation PackLoc, SourceLocation RParenLoc)
: Expr(SizeOfPackExprClass, SizeType, VK_RValue, OK_Ordinary,
/*TypeDependent=*/false, /*ValueDependent=*/true,
/*InstantiationDependent=*/true,
/*ContainsUnexpandedParameterPack=*/false),
OperatorLoc(OperatorLoc), PackLoc(PackLoc), RParenLoc(RParenLoc),
Length(0), Pack(Pack) { }
/// \brief Create an expression that computes the length of
/// the given parameter pack, which is already known.
SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl *Pack,
SourceLocation PackLoc, SourceLocation RParenLoc,
unsigned Length)
: Expr(SizeOfPackExprClass, SizeType, VK_RValue, OK_Ordinary,
/*TypeDependent=*/false, /*ValueDependent=*/false,
/*InstantiationDependent=*/false,
/*ContainsUnexpandedParameterPack=*/false),
OperatorLoc(OperatorLoc), PackLoc(PackLoc), RParenLoc(RParenLoc),
Length(Length), Pack(Pack) { }
/// \brief Create an empty expression.
SizeOfPackExpr(EmptyShell Empty) : Expr(SizeOfPackExprClass, Empty) { }
/// \brief Determine the location of the 'sizeof' keyword.
SourceLocation getOperatorLoc() const { return OperatorLoc; }
/// \brief Determine the location of the parameter pack.
SourceLocation getPackLoc() const { return PackLoc; }
/// \brief Determine the location of the right parenthesis.
SourceLocation getRParenLoc() const { return RParenLoc; }
/// \brief Retrieve the parameter pack.
NamedDecl *getPack() const { return Pack; }
/// \brief Retrieve the length of the parameter pack.
///
/// This routine may only be invoked when the expression is not
/// value-dependent.
unsigned getPackLength() const {
assert(!isValueDependent() &&
"Cannot get the length of a value-dependent pack size expression");
return Length;
}
SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == SizeOfPackExprClass;
}
// Iterators
child_range children() { return child_range(); }
};
/// \brief Represents a reference to a non-type template parameter
/// that has been substituted with a template argument.
class SubstNonTypeTemplateParmExpr : public Expr {
/// \brief The replaced parameter.
NonTypeTemplateParmDecl *Param;
/// \brief The replacement expression.
Stmt *Replacement;
/// \brief The location of the non-type template parameter reference.
SourceLocation NameLoc;
friend class ASTReader;
friend class ASTStmtReader;
explicit SubstNonTypeTemplateParmExpr(EmptyShell Empty)
: Expr(SubstNonTypeTemplateParmExprClass, Empty) { }
public:
SubstNonTypeTemplateParmExpr(QualType type,
ExprValueKind valueKind,
SourceLocation loc,
NonTypeTemplateParmDecl *param,
Expr *replacement)
: Expr(SubstNonTypeTemplateParmExprClass, type, valueKind, OK_Ordinary,
replacement->isTypeDependent(), replacement->isValueDependent(),
replacement->isInstantiationDependent(),
replacement->containsUnexpandedParameterPack()),
Param(param), Replacement(replacement), NameLoc(loc) {}
SourceLocation getNameLoc() const { return NameLoc; }
SourceLocation getLocStart() const LLVM_READONLY { return NameLoc; }
SourceLocation getLocEnd() const LLVM_READONLY { return NameLoc; }
Expr *getReplacement() const { return cast<Expr>(Replacement); }
NonTypeTemplateParmDecl *getParameter() const { return Param; }
static bool classof(const Stmt *s) {
return s->getStmtClass() == SubstNonTypeTemplateParmExprClass;
}
// Iterators
child_range children() { return child_range(&Replacement, &Replacement+1); }
};
/// \brief Represents a reference to a non-type template parameter pack that
/// has been substituted with a non-template argument pack.
///
/// When a pack expansion in the source code contains multiple parameter packs
/// and those parameter packs correspond to different levels of template
/// parameter lists, this node is used to represent a non-type template
/// parameter pack from an outer level, which has already had its argument pack
/// substituted but that still lives within a pack expansion that itself
/// could not be instantiated. When actually performing a substitution into
/// that pack expansion (e.g., when all template parameters have corresponding
/// arguments), this type will be replaced with the appropriate underlying
/// expression at the current pack substitution index.
class SubstNonTypeTemplateParmPackExpr : public Expr {
/// \brief The non-type template parameter pack itself.
NonTypeTemplateParmDecl *Param;
/// \brief A pointer to the set of template arguments that this
/// parameter pack is instantiated with.
const TemplateArgument *Arguments;
/// \brief The number of template arguments in \c Arguments.
unsigned NumArguments;
/// \brief The location of the non-type template parameter pack reference.
SourceLocation NameLoc;
friend class ASTReader;
friend class ASTStmtReader;
explicit SubstNonTypeTemplateParmPackExpr(EmptyShell Empty)
: Expr(SubstNonTypeTemplateParmPackExprClass, Empty) { }
public:
SubstNonTypeTemplateParmPackExpr(QualType T,
NonTypeTemplateParmDecl *Param,
SourceLocation NameLoc,
const TemplateArgument &ArgPack);
/// \brief Retrieve the non-type template parameter pack being substituted.
NonTypeTemplateParmDecl *getParameterPack() const { return Param; }
/// \brief Retrieve the location of the parameter pack name.
SourceLocation getParameterPackLocation() const { return NameLoc; }
/// \brief Retrieve the template argument pack containing the substituted
/// template arguments.
TemplateArgument getArgumentPack() const;
SourceLocation getLocStart() const LLVM_READONLY { return NameLoc; }
SourceLocation getLocEnd() const LLVM_READONLY { return NameLoc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == SubstNonTypeTemplateParmPackExprClass;
}
// Iterators
child_range children() { return child_range(); }
};
/// \brief Represents a reference to a function parameter pack that has been
/// substituted but not yet expanded.
///
/// When a pack expansion contains multiple parameter packs at different levels,
/// this node is used to represent a function parameter pack at an outer level
/// which we have already substituted to refer to expanded parameters, but where
/// the containing pack expansion cannot yet be expanded.
///
/// \code
/// template<typename...Ts> struct S {
/// template<typename...Us> auto f(Ts ...ts) -> decltype(g(Us(ts)...));
/// };
/// template struct S<int, int>;
/// \endcode
class FunctionParmPackExpr : public Expr {
/// \brief The function parameter pack which was referenced.
ParmVarDecl *ParamPack;
/// \brief The location of the function parameter pack reference.
SourceLocation NameLoc;
/// \brief The number of expansions of this pack.
unsigned NumParameters;
FunctionParmPackExpr(QualType T, ParmVarDecl *ParamPack,
SourceLocation NameLoc, unsigned NumParams,
Decl * const *Params);
friend class ASTReader;
friend class ASTStmtReader;
public:
static FunctionParmPackExpr *Create(const ASTContext &Context, QualType T,
ParmVarDecl *ParamPack,
SourceLocation NameLoc,
ArrayRef<Decl *> Params);
static FunctionParmPackExpr *CreateEmpty(const ASTContext &Context,
unsigned NumParams);
/// \brief Get the parameter pack which this expression refers to.
ParmVarDecl *getParameterPack() const { return ParamPack; }
/// \brief Get the location of the parameter pack.
SourceLocation getParameterPackLocation() const { return NameLoc; }
/// \brief Iterators over the parameters which the parameter pack expanded
/// into.
typedef ParmVarDecl * const *iterator;
iterator begin() const { return reinterpret_cast<iterator>(this+1); }
iterator end() const { return begin() + NumParameters; }
/// \brief Get the number of parameters in this parameter pack.
unsigned getNumExpansions() const { return NumParameters; }
/// \brief Get an expansion of the parameter pack by index.
ParmVarDecl *getExpansion(unsigned I) const { return begin()[I]; }
SourceLocation getLocStart() const LLVM_READONLY { return NameLoc; }
SourceLocation getLocEnd() const LLVM_READONLY { return NameLoc; }
static bool classof(const Stmt *T) {
return T->getStmtClass() == FunctionParmPackExprClass;
}
child_range children() { return child_range(); }
};
/// \brief Represents a prvalue temporary that is written into memory so that
/// a reference can bind to it.
///
/// Prvalue expressions are materialized when they need to have an address
/// in memory for a reference to bind to. This happens when binding a
/// reference to the result of a conversion, e.g.,
///
/// \code
/// const int &r = 1.0;
/// \endcode
///
/// Here, 1.0 is implicitly converted to an \c int. That resulting \c int is
/// then materialized via a \c MaterializeTemporaryExpr, and the reference
/// binds to the temporary. \c MaterializeTemporaryExprs are always glvalues
/// (either an lvalue or an xvalue, depending on the kind of reference binding
/// to it), maintaining the invariant that references always bind to glvalues.
///
/// Reference binding and copy-elision can both extend the lifetime of a
/// temporary. When either happens, the expression will also track the
/// declaration which is responsible for the lifetime extension.
class MaterializeTemporaryExpr : public Expr {
public:
/// \brief The temporary-generating expression whose value will be
/// materialized.
Stmt *Temporary;
/// \brief The declaration which lifetime-extended this reference, if any.
/// Either a VarDecl, or (for a ctor-initializer) a FieldDecl.
const ValueDecl *ExtendingDecl;
friend class ASTStmtReader;
friend class ASTStmtWriter;
public:
MaterializeTemporaryExpr(QualType T, Expr *Temporary,
bool BoundToLvalueReference,
const ValueDecl *ExtendedBy)
: Expr(MaterializeTemporaryExprClass, T,
BoundToLvalueReference? VK_LValue : VK_XValue, OK_Ordinary,
Temporary->isTypeDependent(), Temporary->isValueDependent(),
Temporary->isInstantiationDependent(),
Temporary->containsUnexpandedParameterPack()),
Temporary(Temporary), ExtendingDecl(ExtendedBy) {
}
MaterializeTemporaryExpr(EmptyShell Empty)
: Expr(MaterializeTemporaryExprClass, Empty) { }
/// \brief Retrieve the temporary-generating subexpression whose value will
/// be materialized into a glvalue.
Expr *GetTemporaryExpr() const { return static_cast<Expr *>(Temporary); }
/// \brief Retrieve the storage duration for the materialized temporary.
StorageDuration getStorageDuration() const {
if (!ExtendingDecl)
return SD_FullExpression;
// FIXME: This is not necessarily correct for a temporary materialized
// within a default initializer.
if (isa<FieldDecl>(ExtendingDecl))
return SD_Automatic;
return cast<VarDecl>(ExtendingDecl)->getStorageDuration();
}
/// \brief Get the declaration which triggered the lifetime-extension of this
/// temporary, if any.
const ValueDecl *getExtendingDecl() const { return ExtendingDecl; }
void setExtendingDecl(const ValueDecl *ExtendedBy) {
ExtendingDecl = ExtendedBy;
}
/// \brief Determine whether this materialized temporary is bound to an
/// lvalue reference; otherwise, it's bound to an rvalue reference.
bool isBoundToLvalueReference() const {
return getValueKind() == VK_LValue;
}
SourceLocation getLocStart() const LLVM_READONLY {
return Temporary->getLocStart();
}
SourceLocation getLocEnd() const LLVM_READONLY {
return Temporary->getLocEnd();
}
static bool classof(const Stmt *T) {
return T->getStmtClass() == MaterializeTemporaryExprClass;
}
// Iterators
child_range children() { return child_range(&Temporary, &Temporary + 1); }
};
} // end namespace clang
#endif
| [
"aleksy.jones@gmail.com"
] | aleksy.jones@gmail.com |
7e3f9dbcf4d1ba126e2f0643c5ecb70f5df38da8 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /third_party/WebKit/Source/platform/graphics/CompositorMutableState.cpp | 6313cbfe2c1f4822de8ce4bb795b76426d3954a5 | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 2,983 | cpp | // Copyright 2016 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 "platform/graphics/CompositorMutableState.h"
#include "cc/layers/layer_impl.h"
#include "cc/trees/layer_tree_impl.h"
#include "platform/graphics/CompositorMutation.h"
namespace blink {
CompositorMutableState::CompositorMutableState(CompositorMutation* mutation,
cc::LayerImpl* main,
cc::LayerImpl* scroll)
: m_mutation(mutation), m_mainLayer(main), m_scrollLayer(scroll) {}
CompositorMutableState::~CompositorMutableState() {}
double CompositorMutableState::opacity() const {
return m_mainLayer->Opacity();
}
void CompositorMutableState::setOpacity(double opacity) {
if (!m_mainLayer)
return;
m_mainLayer->layer_tree_impl()
->property_trees()
->effect_tree.OnOpacityAnimated(opacity, m_mainLayer->effect_tree_index(),
m_mainLayer->layer_tree_impl());
m_mutation->setOpacity(opacity);
}
const SkMatrix44& CompositorMutableState::transform() const {
return m_mainLayer ? m_mainLayer->Transform().matrix() : SkMatrix44::I();
}
void CompositorMutableState::setTransform(const SkMatrix44& matrix) {
if (!m_mainLayer)
return;
m_mainLayer->layer_tree_impl()
->property_trees()
->transform_tree.OnTransformAnimated(gfx::Transform(matrix),
m_mainLayer->transform_tree_index(),
m_mainLayer->layer_tree_impl());
m_mutation->setTransform(matrix);
}
double CompositorMutableState::scrollLeft() const {
return m_scrollLayer ? m_scrollLayer->CurrentScrollOffset().x() : 0.0;
}
void CompositorMutableState::setScrollLeft(double scrollLeft) {
if (!m_scrollLayer)
return;
gfx::ScrollOffset offset = m_scrollLayer->CurrentScrollOffset();
offset.set_x(scrollLeft);
m_scrollLayer->layer_tree_impl()
->property_trees()
->scroll_tree.OnScrollOffsetAnimated(
m_scrollLayer->id(), m_scrollLayer->transform_tree_index(),
m_scrollLayer->scroll_tree_index(), offset,
m_scrollLayer->layer_tree_impl());
m_mutation->setScrollLeft(scrollLeft);
}
double CompositorMutableState::scrollTop() const {
return m_scrollLayer ? m_scrollLayer->CurrentScrollOffset().y() : 0.0;
}
void CompositorMutableState::setScrollTop(double scrollTop) {
if (!m_scrollLayer)
return;
gfx::ScrollOffset offset = m_scrollLayer->CurrentScrollOffset();
offset.set_y(scrollTop);
m_scrollLayer->layer_tree_impl()
->property_trees()
->scroll_tree.OnScrollOffsetAnimated(
m_scrollLayer->id(), m_scrollLayer->transform_tree_index(),
m_scrollLayer->scroll_tree_index(), offset,
m_scrollLayer->layer_tree_impl());
m_mutation->setScrollTop(scrollTop);
}
} // namespace blink
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
d5324d3af26b485a3ae139b372bad4c2536b6c8e | 6ff80a1dc6d0895f701c33723397caff9d7005f5 | /include/Instancia.h | 51c2a18f57a677fc3e7457a8c468dd251a6cb53e | [] | no_license | arielsonalt/Construtivo-Guloso | 03853558cb24347984c3de8099ff9e6effbe1b1b | aa6e154a1ec63cedf63326ed93061fc5e55dfa28 | refs/heads/master | 2020-03-13T02:03:29.374932 | 2018-04-24T21:39:46 | 2018-04-24T21:39:46 | 130,916,798 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 481 | h | #ifndef INSTANCIA_H
#define INSTANCIA_H
#include "../include/Distancias.h"
#include "../include/Cliente.h"
#include "../include/CT.h"
#include <vector>
class Instancia
{
public:
Instancia();
void lerDistancias();
void lerCTs();
void lerClientes();
void imprimirDistancias();
void imprimirCTs();
void imprimirClientes();
vector <Distancias> vetorDistancias;
vector <Cliente> vetorClientes;
vector <CT> vetorCTs;
};
#endif // INSTANCIA_H
| [
"32400603+arielsonalt@users.noreply.github.com"
] | 32400603+arielsonalt@users.noreply.github.com |
8b0df76c33486f7c17f8d577c79b0784d72f0d78 | 3433813671624fa5bb0a8a43ed9ae4f62c8ebb6f | /QuestionSet/VirtualJudge/ShortestPath/TiltheCowsComeHome.cpp | 37e0c8b837ecf53cdd94f714fa3cf6a20dbad71e | [] | no_license | Devildyw/DSA | d4310c6c7ce9eab4ab7897419e5a91f115ee6b9e | 969e62264fab5ecf15852895ce74973b13ce477d | refs/heads/main | 2023-08-29T21:41:33.202543 | 2021-10-30T15:44:14 | 2021-10-30T15:44:14 | 423,408,758 | 1 | 0 | null | 2021-11-01T09:35:19 | 2021-11-01T09:35:19 | null | UTF-8 | C++ | false | false | 1,404 | cpp | /*
* @Author: FANG
* @Date: 2021-08-22 23:25:42
* @LastEditTime: 2021-08-23 12:43:59
* @Description: https://vjudge.ppsucxtt.cn/problem/POJ-2387
* @FilePath: \DSA\QuestionSet\VirtualJudge\ShortestPath\TiltheCowsComeHome.cpp
*/
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 1e4 + 5;
struct Edge {
int to;
int w;
int next;
} edge[N];
int head[N], cnt, dis[N], t, n;
bool vis[N];
void add(int u, int v, int w) {
++cnt;
edge[cnt].to = v;
edge[cnt].w = w;
edge[cnt].next = head[u];
head[u] = cnt;
}
priority_queue<pair<int, int> > q;
int main() {
memset(head, -1, sizeof(head));
memset(dis, INF, sizeof(dis));
cin >> t >> n;
for (int i=1; i<=t; i++) {
int u, v, w;
cin >> u >> v >> w;
add(u, v, w);
add(v, u, w);
}
// vis[n] = true;
dis[n] = 0;
q.push(make_pair(0, n));
while (!q.empty()) {
int x = q.top().second;
q.pop();
if (vis[x]) continue;
vis[x] = true;
for (int i=head[x]; ~i; i=edge[i].next) {
if (dis[edge[i].to] > dis[x] + edge[i].w) {
dis[edge[i].to] = dis[x] + edge[i].w;
q.push(make_pair(-dis[edge[i].to], edge[i].to));
}
}
}
cout << dis[1] << endl;
return 0;
} | [
"1639579565@qq.com"
] | 1639579565@qq.com |
1eb850fce25590db76e4893353d22f7cb14a8f96 | 92fb6d1d4d4928e556537ee719430e89faa65850 | /Cpp-Exerceise/chap06-析构函数/06-2_deconstructor.cpp | 9463d4621679ac0ed9c4ad2157512a7df4d9fdcf | [] | no_license | lekjons/Linux-Cpp-Development-Advanced-Learning | ebe825d3424e7d15bbff2e226de251db11ebf882 | 9ca47d6b1bb4719b919cae1f9d0e74a0f70e88f2 | refs/heads/master | 2023-02-19T05:59:55.584696 | 2021-01-04T11:43:54 | 2021-01-04T11:43:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 434 | cpp | //
// Created by Yang Shuangzhen on 2020/10/3.
//
#include <stdio.h>
class Test
{
int mi;
public:
Test(int i)
{
mi = i;
printf("Test(): %d\n", mi);
}
~Test()
{
printf("~Test(): %d\n", mi);
}
};
int main()
{
Test t(1); // 构造 Test(1)
Test* pt = new Test(2); // 构造Test(2)
delete pt; // 析构Test(2)
// 析构Test(1)
return 0;
}
| [
"dreamre21@gmail.com"
] | dreamre21@gmail.com |
97b1a6204c20277ed8d9d97d5db95f642ba0db33 | c6beef27373e962d246e0ca59e60930f33068d9a | /lab2/01_studentgroup/academicgroup.hpp | 58bcb5ed1216a59c0ba77563d0d5a87bb54efbee | [] | no_license | aganur-ahundov/oop-ki14 | 260cd3b343185d27a0aba61cedd6fc91b0e4fbef | 78d8fb653d7f7891d97a2ea0afc32ba1b7364660 | refs/heads/master | 2021-01-18T00:41:21.681434 | 2016-01-14T12:04:09 | 2016-01-14T12:04:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 898 | hpp | // (C) 2013-2015, Sergei Zaychenko, KNURE, Kharkiv, Ukraine
#ifndef _ACADEMICGROUP_HPP_
#define _ACADEMICGROUP_HPP_
/*****************************************************************************/
class Student;
/*****************************************************************************/
class AcademicGroup
{
/*-----------------------------------------------------------------*/
public:
/*-----------------------------------------------------------------*/
// TODO put your public methods here
/*-----------------------------------------------------------------*/
private:
/*-----------------------------------------------------------------*/
// TODO put your private fields / methods here
/*-----------------------------------------------------------------*/
};
/*****************************************************************************/
#endif // _ACADEMICGROUP_HPP_
| [
"zaychenko.sergei@gmail.com"
] | zaychenko.sergei@gmail.com |
978df33c8b0891d61bcef8fc46222f6e0961ff12 | 66eb3d9cdd1a66843942a71386ccc46fb0045d32 | /sort/quick_sort/quicksort.cpp | 5050b60e16a2091ee0ba04531dbe36adbc795eb3 | [] | no_license | KJTang/Algorithm | 764309818f004a25ae94be3e2cef38241873f91f | 29ae44edd462f59495338d965c92245787581f69 | refs/heads/master | 2021-01-10T18:46:51.610103 | 2017-06-30T05:42:02 | 2017-06-30T05:42:02 | 27,213,776 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,079 | cpp | #include <iostream>
#include <cstdlib>
using namespace std;
const int LENGTH = 10;
// int arr[LENGTH] = {3, 2, 7, 9, 8, 1, 0, 4, 6, 5};
int arr[LENGTH] = {9, 8, 7, 2, 5, 2, 3, 2, 1, 0};
void quickSort(int arr[], int front, int end);
void test(int arr[]) {
for (int i = 0; i != LENGTH; ++i) {
cout<<arr[i]<<" ";
}
cout<<endl;
}
int main() {
test(arr);
srand(time(0));
quickSort(arr, 0, LENGTH-1);
test(arr);
return 0;
}
void quickSort(int arr[], int front, int end) {
if (front >= end) {
return;
}
// random select
int random = rand()%(end-front+1)+front;
int temp = arr[end];
arr[end] = arr[random];
arr[random] = temp;
// sort
int key = arr[end];
int i = front-1, j = front;
for ( ; j != end; ++j) {
if (arr[j] <= key) {
++i;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
temp = arr[i+1];
arr[i+1] = arr[end];
arr[end] = temp;
quickSort(arr, front, i);
quickSort(arr, i+2, end);
} | [
"kaijietang@outlook.com"
] | kaijietang@outlook.com |
0ceda72c0a288268c794af2669933eeeb7f71b21 | 4b73addaed825276738d4c1e0ec7e96bb9b6c497 | /src/mr-controller.cpp | 4df5aef687992b6623c379b3dc8ebd7021f4c939 | [] | no_license | OohmdoO/mobile-robot-controller | 778eedc55f95c638b0c69cd5a2b49bb54663bb1b | 512b73b305c74abfa1b8f44d9eb66969f6349833 | refs/heads/master | 2023-03-17T12:04:18.522689 | 2020-09-27T11:53:12 | 2020-09-27T11:53:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,706 | cpp | #include "ros/ros.h"
#include <tf/tf.h>
#include "nav_msgs/Odometry.h"
#include <geometry_msgs/Pose2D.h>
#include <geometry_msgs/Twist.h>
#include <sensor_msgs/LaserScan.h>
#include <cmath>
#include "hybridAutomata.h"
double x_d=3.0, y_d=-2.0; //target goal location
//initializing and declaring variables for robot's current pose
double x=0,y=0,roll=0,pitch=0,yaw=0;
double range[360];
void readLaserCallback(const sensor_msgs::LaserScan::ConstPtr& msg)
{
for(int i=0;i<360;i++)
{
if(msg->ranges[i] > msg->range_max)
range[i] = 4.0;
else
range[i]=msg->ranges[i];
}
}
void robotPoseCallback(const nav_msgs::Odometry::ConstPtr& msg)
{
x=msg->pose.pose.position.x;
y=msg->pose.pose.position.y;
tf::Quaternion q(
msg->pose.pose.orientation.x,
msg->pose.pose.orientation.y,
msg->pose.pose.orientation.z,
msg->pose.pose.orientation.w);
tf::Matrix3x3 m(q);
m.getRPY(roll, pitch, yaw);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "mr_controller");
ros::NodeHandle n;
ros::Subscriber odometry = n.subscribe("odom", 1000, robotPoseCallback);
ros::Subscriber laserScan = n.subscribe("scan", 10, readLaserCallback);
// Command Velocity Publisher
ros::Publisher vel_pub = n.advertise<geometry_msgs::Twist>("cmd_vel", 100);
//Running at 10Hz
ros::Rate loop_rate(10);
while(ros::ok())
{
hybrid_automata HA;
geometry_msgs::Twist velo = HA.switcher(x,y,yaw,x_d,y_d,range);
vel_pub.publish(velo);
//For running the callbacks
ros::spinOnce();
//wait till 10Hz loop rate is satified.
loop_rate.sleep();
}
return 0;
} | [
"f20171569@hyderabad.bits-pilani.ac.in"
] | f20171569@hyderabad.bits-pilani.ac.in |
8cf404733987f076fd539e23316480de1cfbc63c | 9f156c1282493ddc322c9a352c54a06f6a72bf45 | /sum.cpp | 5c5b9d763d8910096db092a18d3fa89c88a6a35e | [] | no_license | notetook/sum_test | 1cda6da888864f2daa218544145b332d965b48ab | 5ac36aacd90b50080d59698b4982195f8f11aca0 | refs/heads/master | 2020-06-26T18:15:30.605743 | 2016-09-08T08:00:20 | 2016-09-08T08:00:20 | 67,676,804 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45 | cpp | int sum ( int n )
{
return n * (n+1) / 2;
}
| [
"notetake@korea.ac.kr"
] | notetake@korea.ac.kr |
47541dec62e93a5baf4e857e2b1f4e669f40cd6b | f999711a794bd8f28b3365fa9333403df179fd90 | /hust C语言学习/第七章/trim().cpp | 83aa43b00fe182957e9a80f58f14cc03ddd1edf6 | [] | no_license | Hanray-Zhong/Computer-Science | 2423222addff275e5822a1390b43c44c1b24a252 | dfea9d3ee465c36a405e50f53589bdacbd6d2ae2 | refs/heads/master | 2021-07-04T21:35:43.730153 | 2020-08-07T09:56:58 | 2020-08-07T09:56:58 | 145,799,254 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 570 | cpp | #include <stdio.h>
int strlen(char []);
int trim(char []);
int main(void)
{
char s[30];
scanf("%s",s);
printf("%d words: %s",trim(s),s);
return 0;
}
/***********trim()********/
int trim(char s[])
{
int i,num,j=0,k=0,l=strlen(s);
while(s[j]==' '||s[j]=='\n'||s[j]=='\t'||s[j]=='\r') j++;
i=l-1;
while(s[i-k]==' '||s[i-k]=='\n'||s[i-k]=='\t'||s[i-k]=='\r') k++;
num=l-k-j;
for(i=0;i<num;i++)
{
s[i]=s[i+j];
}
s[num]='\0';
return strlen(s);
}
/***************strlen()****************/
int strlen(char s[])
{
int j=0;
while(s[j]!='\0') j++;
return j;
}
| [
"646374316@qq.com"
] | 646374316@qq.com |
dce6e0fa6920856073d61d902d120135e2e6c566 | 276845ee0f0dfe0050a191dd94c55531cf71a839 | /mc15-smaract/smaractApp/src/O.linux-x86_64/smaract_registerRecordDeviceDriver.cpp | 06ad21fa10410a01f0d1e428280ac0a7d7de58b6 | [] | no_license | NSLS-II-LIX/xf16idc-ioc1 | fb2113d044e14e0bd4c96e9efea20668a1cbb51e | f04e6266fd4ad0ad7ad6caead7252f7e0d67e45d | refs/heads/master | 2021-07-06T22:42:49.120813 | 2021-04-27T12:51:52 | 2021-04-27T12:51:52 | 91,277,754 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,600 | cpp | /* THIS IS A GENERATED FILE. DO NOT EDIT! */
/* Generated from ../O.Common/smaract.dbd */
#include <string.h>
#include "epicsStdlib.h"
#include "iocsh.h"
#include "iocshRegisterCommon.h"
#include "registryCommon.h"
extern "C" {
epicsShareExtern rset *pvar_rset_aaiRSET;
epicsShareExtern int (*pvar_func_aaiRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_aaoRSET;
epicsShareExtern int (*pvar_func_aaoRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_aiRSET;
epicsShareExtern int (*pvar_func_aiRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_aoRSET;
epicsShareExtern int (*pvar_func_aoRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_aSubRSET;
epicsShareExtern int (*pvar_func_aSubRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_biRSET;
epicsShareExtern int (*pvar_func_biRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_boRSET;
epicsShareExtern int (*pvar_func_boRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_calcRSET;
epicsShareExtern int (*pvar_func_calcRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_calcoutRSET;
epicsShareExtern int (*pvar_func_calcoutRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_compressRSET;
epicsShareExtern int (*pvar_func_compressRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_dfanoutRSET;
epicsShareExtern int (*pvar_func_dfanoutRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_eventRSET;
epicsShareExtern int (*pvar_func_eventRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_fanoutRSET;
epicsShareExtern int (*pvar_func_fanoutRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_histogramRSET;
epicsShareExtern int (*pvar_func_histogramRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_longinRSET;
epicsShareExtern int (*pvar_func_longinRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_longoutRSET;
epicsShareExtern int (*pvar_func_longoutRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_mbbiRSET;
epicsShareExtern int (*pvar_func_mbbiRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_mbbiDirectRSET;
epicsShareExtern int (*pvar_func_mbbiDirectRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_mbboRSET;
epicsShareExtern int (*pvar_func_mbboRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_mbboDirectRSET;
epicsShareExtern int (*pvar_func_mbboDirectRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_permissiveRSET;
epicsShareExtern int (*pvar_func_permissiveRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_selRSET;
epicsShareExtern int (*pvar_func_selRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_seqRSET;
epicsShareExtern int (*pvar_func_seqRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_stateRSET;
epicsShareExtern int (*pvar_func_stateRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_stringinRSET;
epicsShareExtern int (*pvar_func_stringinRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_stringoutRSET;
epicsShareExtern int (*pvar_func_stringoutRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_subRSET;
epicsShareExtern int (*pvar_func_subRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_subArrayRSET;
epicsShareExtern int (*pvar_func_subArrayRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_waveformRSET;
epicsShareExtern int (*pvar_func_waveformRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_asynRSET;
epicsShareExtern int (*pvar_func_asynRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_motorRSET;
epicsShareExtern int (*pvar_func_motorRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_transformRSET;
epicsShareExtern int (*pvar_func_transformRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_scalcoutRSET;
epicsShareExtern int (*pvar_func_scalcoutRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_acalcoutRSET;
epicsShareExtern int (*pvar_func_acalcoutRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_sseqRSET;
epicsShareExtern int (*pvar_func_sseqRecordSizeOffset)(dbRecordType *pdbRecordType);
epicsShareExtern rset *pvar_rset_swaitRSET;
epicsShareExtern int (*pvar_func_swaitRecordSizeOffset)(dbRecordType *pdbRecordType);
static const char * const recordTypeNames[36] = {
"aai",
"aao",
"ai",
"ao",
"aSub",
"bi",
"bo",
"calc",
"calcout",
"compress",
"dfanout",
"event",
"fanout",
"histogram",
"longin",
"longout",
"mbbi",
"mbbiDirect",
"mbbo",
"mbboDirect",
"permissive",
"sel",
"seq",
"state",
"stringin",
"stringout",
"sub",
"subArray",
"waveform",
"asyn",
"motor",
"transform",
"scalcout",
"acalcout",
"sseq",
"swait"
};
static const recordTypeLocation rtl[36] = {
{pvar_rset_aaiRSET, pvar_func_aaiRecordSizeOffset},
{pvar_rset_aaoRSET, pvar_func_aaoRecordSizeOffset},
{pvar_rset_aiRSET, pvar_func_aiRecordSizeOffset},
{pvar_rset_aoRSET, pvar_func_aoRecordSizeOffset},
{pvar_rset_aSubRSET, pvar_func_aSubRecordSizeOffset},
{pvar_rset_biRSET, pvar_func_biRecordSizeOffset},
{pvar_rset_boRSET, pvar_func_boRecordSizeOffset},
{pvar_rset_calcRSET, pvar_func_calcRecordSizeOffset},
{pvar_rset_calcoutRSET, pvar_func_calcoutRecordSizeOffset},
{pvar_rset_compressRSET, pvar_func_compressRecordSizeOffset},
{pvar_rset_dfanoutRSET, pvar_func_dfanoutRecordSizeOffset},
{pvar_rset_eventRSET, pvar_func_eventRecordSizeOffset},
{pvar_rset_fanoutRSET, pvar_func_fanoutRecordSizeOffset},
{pvar_rset_histogramRSET, pvar_func_histogramRecordSizeOffset},
{pvar_rset_longinRSET, pvar_func_longinRecordSizeOffset},
{pvar_rset_longoutRSET, pvar_func_longoutRecordSizeOffset},
{pvar_rset_mbbiRSET, pvar_func_mbbiRecordSizeOffset},
{pvar_rset_mbbiDirectRSET, pvar_func_mbbiDirectRecordSizeOffset},
{pvar_rset_mbboRSET, pvar_func_mbboRecordSizeOffset},
{pvar_rset_mbboDirectRSET, pvar_func_mbboDirectRecordSizeOffset},
{pvar_rset_permissiveRSET, pvar_func_permissiveRecordSizeOffset},
{pvar_rset_selRSET, pvar_func_selRecordSizeOffset},
{pvar_rset_seqRSET, pvar_func_seqRecordSizeOffset},
{pvar_rset_stateRSET, pvar_func_stateRecordSizeOffset},
{pvar_rset_stringinRSET, pvar_func_stringinRecordSizeOffset},
{pvar_rset_stringoutRSET, pvar_func_stringoutRecordSizeOffset},
{pvar_rset_subRSET, pvar_func_subRecordSizeOffset},
{pvar_rset_subArrayRSET, pvar_func_subArrayRecordSizeOffset},
{pvar_rset_waveformRSET, pvar_func_waveformRecordSizeOffset},
{pvar_rset_asynRSET, pvar_func_asynRecordSizeOffset},
{pvar_rset_motorRSET, pvar_func_motorRecordSizeOffset},
{pvar_rset_transformRSET, pvar_func_transformRecordSizeOffset},
{pvar_rset_scalcoutRSET, pvar_func_scalcoutRecordSizeOffset},
{pvar_rset_acalcoutRSET, pvar_func_acalcoutRecordSizeOffset},
{pvar_rset_sseqRSET, pvar_func_sseqRecordSizeOffset},
{pvar_rset_swaitRSET, pvar_func_swaitRecordSizeOffset}
};
epicsShareExtern dset *pvar_dset_devAaiSoft;
epicsShareExtern dset *pvar_dset_devAaoSoft;
epicsShareExtern dset *pvar_dset_devAiSoft;
epicsShareExtern dset *pvar_dset_devAiSoftRaw;
epicsShareExtern dset *pvar_dset_devTimestampAI;
epicsShareExtern dset *pvar_dset_devAiGeneralTime;
epicsShareExtern dset *pvar_dset_asynAiInt32;
epicsShareExtern dset *pvar_dset_asynAiInt32Average;
epicsShareExtern dset *pvar_dset_asynAiFloat64;
epicsShareExtern dset *pvar_dset_asynAiFloat64Average;
epicsShareExtern dset *pvar_dset_devAoSoft;
epicsShareExtern dset *pvar_dset_devAoSoftRaw;
epicsShareExtern dset *pvar_dset_devAoSoftCallback;
epicsShareExtern dset *pvar_dset_asynAoInt32;
epicsShareExtern dset *pvar_dset_asynAoFloat64;
epicsShareExtern dset *pvar_dset_devBiSoft;
epicsShareExtern dset *pvar_dset_devBiSoftRaw;
epicsShareExtern dset *pvar_dset_devBiASStatus;
epicsShareExtern dset *pvar_dset_asynBiInt32;
epicsShareExtern dset *pvar_dset_asynBiUInt32Digital;
epicsShareExtern dset *pvar_dset_devBoSoft;
epicsShareExtern dset *pvar_dset_devBoSoftRaw;
epicsShareExtern dset *pvar_dset_devBoSoftCallback;
epicsShareExtern dset *pvar_dset_devBoGeneralTime;
epicsShareExtern dset *pvar_dset_asynBoInt32;
epicsShareExtern dset *pvar_dset_asynBoUInt32Digital;
epicsShareExtern dset *pvar_dset_devCalcoutSoft;
epicsShareExtern dset *pvar_dset_devCalcoutSoftCallback;
epicsShareExtern dset *pvar_dset_devEventSoft;
epicsShareExtern dset *pvar_dset_devHistogramSoft;
epicsShareExtern dset *pvar_dset_devLiSoft;
epicsShareExtern dset *pvar_dset_devLiGeneralTime;
epicsShareExtern dset *pvar_dset_devLiASSum;
epicsShareExtern dset *pvar_dset_asynLiInt32;
epicsShareExtern dset *pvar_dset_asynLiUInt32Digital;
epicsShareExtern dset *pvar_dset_devLoSoft;
epicsShareExtern dset *pvar_dset_devLoSoftCallback;
epicsShareExtern dset *pvar_dset_asynLoInt32;
epicsShareExtern dset *pvar_dset_asynLoUInt32Digital;
epicsShareExtern dset *pvar_dset_devMbbiSoft;
epicsShareExtern dset *pvar_dset_devMbbiSoftRaw;
epicsShareExtern dset *pvar_dset_asynMbbiInt32;
epicsShareExtern dset *pvar_dset_asynMbbiUInt32Digital;
epicsShareExtern dset *pvar_dset_devMbbiDirectSoft;
epicsShareExtern dset *pvar_dset_devMbbiDirectSoftRaw;
epicsShareExtern dset *pvar_dset_asynMbbiDirectUInt32Digital;
epicsShareExtern dset *pvar_dset_devMbboSoft;
epicsShareExtern dset *pvar_dset_devMbboSoftRaw;
epicsShareExtern dset *pvar_dset_devMbboSoftCallback;
epicsShareExtern dset *pvar_dset_asynMbboInt32;
epicsShareExtern dset *pvar_dset_asynMbboUInt32Digital;
epicsShareExtern dset *pvar_dset_devMbboDirectSoft;
epicsShareExtern dset *pvar_dset_devMbboDirectSoftRaw;
epicsShareExtern dset *pvar_dset_devMbboDirectSoftCallback;
epicsShareExtern dset *pvar_dset_asynMbboDirectUInt32Digital;
epicsShareExtern dset *pvar_dset_devSiSoft;
epicsShareExtern dset *pvar_dset_devTimestampSI;
epicsShareExtern dset *pvar_dset_devSiGeneralTime;
epicsShareExtern dset *pvar_dset_asynSiOctetCmdResponse;
epicsShareExtern dset *pvar_dset_asynSiOctetWriteRead;
epicsShareExtern dset *pvar_dset_asynSiOctetRead;
epicsShareExtern dset *pvar_dset_devSoSoft;
epicsShareExtern dset *pvar_dset_devSoSoftCallback;
epicsShareExtern dset *pvar_dset_devSoStdio;
epicsShareExtern dset *pvar_dset_asynSoOctetWrite;
epicsShareExtern dset *pvar_dset_devSASoft;
epicsShareExtern dset *pvar_dset_devWfSoft;
epicsShareExtern dset *pvar_dset_asynWfOctetCmdResponse;
epicsShareExtern dset *pvar_dset_asynWfOctetWriteRead;
epicsShareExtern dset *pvar_dset_asynWfOctetRead;
epicsShareExtern dset *pvar_dset_asynWfOctetWrite;
epicsShareExtern dset *pvar_dset_asynInt8ArrayWfIn;
epicsShareExtern dset *pvar_dset_asynInt8ArrayWfOut;
epicsShareExtern dset *pvar_dset_asynInt16ArrayWfIn;
epicsShareExtern dset *pvar_dset_asynInt16ArrayWfOut;
epicsShareExtern dset *pvar_dset_asynInt32ArrayWfIn;
epicsShareExtern dset *pvar_dset_asynInt32ArrayWfOut;
epicsShareExtern dset *pvar_dset_asynInt32TimeSeries;
epicsShareExtern dset *pvar_dset_asynFloat32ArrayWfIn;
epicsShareExtern dset *pvar_dset_asynFloat32ArrayWfOut;
epicsShareExtern dset *pvar_dset_asynFloat64ArrayWfIn;
epicsShareExtern dset *pvar_dset_asynFloat64ArrayWfOut;
epicsShareExtern dset *pvar_dset_asynFloat64TimeSeries;
epicsShareExtern dset *pvar_dset_asynRecordDevice;
epicsShareExtern dset *pvar_dset_devMotorAsyn;
epicsShareExtern dset *pvar_dset_devsCalcoutSoft;
epicsShareExtern dset *pvar_dset_devaCalcoutSoft;
epicsShareExtern dset *pvar_dset_devSWaitIoEvent;
static const char * const deviceSupportNames[88] = {
"devAaiSoft",
"devAaoSoft",
"devAiSoft",
"devAiSoftRaw",
"devTimestampAI",
"devAiGeneralTime",
"asynAiInt32",
"asynAiInt32Average",
"asynAiFloat64",
"asynAiFloat64Average",
"devAoSoft",
"devAoSoftRaw",
"devAoSoftCallback",
"asynAoInt32",
"asynAoFloat64",
"devBiSoft",
"devBiSoftRaw",
"devBiASStatus",
"asynBiInt32",
"asynBiUInt32Digital",
"devBoSoft",
"devBoSoftRaw",
"devBoSoftCallback",
"devBoGeneralTime",
"asynBoInt32",
"asynBoUInt32Digital",
"devCalcoutSoft",
"devCalcoutSoftCallback",
"devEventSoft",
"devHistogramSoft",
"devLiSoft",
"devLiGeneralTime",
"devLiASSum",
"asynLiInt32",
"asynLiUInt32Digital",
"devLoSoft",
"devLoSoftCallback",
"asynLoInt32",
"asynLoUInt32Digital",
"devMbbiSoft",
"devMbbiSoftRaw",
"asynMbbiInt32",
"asynMbbiUInt32Digital",
"devMbbiDirectSoft",
"devMbbiDirectSoftRaw",
"asynMbbiDirectUInt32Digital",
"devMbboSoft",
"devMbboSoftRaw",
"devMbboSoftCallback",
"asynMbboInt32",
"asynMbboUInt32Digital",
"devMbboDirectSoft",
"devMbboDirectSoftRaw",
"devMbboDirectSoftCallback",
"asynMbboDirectUInt32Digital",
"devSiSoft",
"devTimestampSI",
"devSiGeneralTime",
"asynSiOctetCmdResponse",
"asynSiOctetWriteRead",
"asynSiOctetRead",
"devSoSoft",
"devSoSoftCallback",
"devSoStdio",
"asynSoOctetWrite",
"devSASoft",
"devWfSoft",
"asynWfOctetCmdResponse",
"asynWfOctetWriteRead",
"asynWfOctetRead",
"asynWfOctetWrite",
"asynInt8ArrayWfIn",
"asynInt8ArrayWfOut",
"asynInt16ArrayWfIn",
"asynInt16ArrayWfOut",
"asynInt32ArrayWfIn",
"asynInt32ArrayWfOut",
"asynInt32TimeSeries",
"asynFloat32ArrayWfIn",
"asynFloat32ArrayWfOut",
"asynFloat64ArrayWfIn",
"asynFloat64ArrayWfOut",
"asynFloat64TimeSeries",
"asynRecordDevice",
"devMotorAsyn",
"devsCalcoutSoft",
"devaCalcoutSoft",
"devSWaitIoEvent"
};
static const dset * const devsl[88] = {
pvar_dset_devAaiSoft,
pvar_dset_devAaoSoft,
pvar_dset_devAiSoft,
pvar_dset_devAiSoftRaw,
pvar_dset_devTimestampAI,
pvar_dset_devAiGeneralTime,
pvar_dset_asynAiInt32,
pvar_dset_asynAiInt32Average,
pvar_dset_asynAiFloat64,
pvar_dset_asynAiFloat64Average,
pvar_dset_devAoSoft,
pvar_dset_devAoSoftRaw,
pvar_dset_devAoSoftCallback,
pvar_dset_asynAoInt32,
pvar_dset_asynAoFloat64,
pvar_dset_devBiSoft,
pvar_dset_devBiSoftRaw,
pvar_dset_devBiASStatus,
pvar_dset_asynBiInt32,
pvar_dset_asynBiUInt32Digital,
pvar_dset_devBoSoft,
pvar_dset_devBoSoftRaw,
pvar_dset_devBoSoftCallback,
pvar_dset_devBoGeneralTime,
pvar_dset_asynBoInt32,
pvar_dset_asynBoUInt32Digital,
pvar_dset_devCalcoutSoft,
pvar_dset_devCalcoutSoftCallback,
pvar_dset_devEventSoft,
pvar_dset_devHistogramSoft,
pvar_dset_devLiSoft,
pvar_dset_devLiGeneralTime,
pvar_dset_devLiASSum,
pvar_dset_asynLiInt32,
pvar_dset_asynLiUInt32Digital,
pvar_dset_devLoSoft,
pvar_dset_devLoSoftCallback,
pvar_dset_asynLoInt32,
pvar_dset_asynLoUInt32Digital,
pvar_dset_devMbbiSoft,
pvar_dset_devMbbiSoftRaw,
pvar_dset_asynMbbiInt32,
pvar_dset_asynMbbiUInt32Digital,
pvar_dset_devMbbiDirectSoft,
pvar_dset_devMbbiDirectSoftRaw,
pvar_dset_asynMbbiDirectUInt32Digital,
pvar_dset_devMbboSoft,
pvar_dset_devMbboSoftRaw,
pvar_dset_devMbboSoftCallback,
pvar_dset_asynMbboInt32,
pvar_dset_asynMbboUInt32Digital,
pvar_dset_devMbboDirectSoft,
pvar_dset_devMbboDirectSoftRaw,
pvar_dset_devMbboDirectSoftCallback,
pvar_dset_asynMbboDirectUInt32Digital,
pvar_dset_devSiSoft,
pvar_dset_devTimestampSI,
pvar_dset_devSiGeneralTime,
pvar_dset_asynSiOctetCmdResponse,
pvar_dset_asynSiOctetWriteRead,
pvar_dset_asynSiOctetRead,
pvar_dset_devSoSoft,
pvar_dset_devSoSoftCallback,
pvar_dset_devSoStdio,
pvar_dset_asynSoOctetWrite,
pvar_dset_devSASoft,
pvar_dset_devWfSoft,
pvar_dset_asynWfOctetCmdResponse,
pvar_dset_asynWfOctetWriteRead,
pvar_dset_asynWfOctetRead,
pvar_dset_asynWfOctetWrite,
pvar_dset_asynInt8ArrayWfIn,
pvar_dset_asynInt8ArrayWfOut,
pvar_dset_asynInt16ArrayWfIn,
pvar_dset_asynInt16ArrayWfOut,
pvar_dset_asynInt32ArrayWfIn,
pvar_dset_asynInt32ArrayWfOut,
pvar_dset_asynInt32TimeSeries,
pvar_dset_asynFloat32ArrayWfIn,
pvar_dset_asynFloat32ArrayWfOut,
pvar_dset_asynFloat64ArrayWfIn,
pvar_dset_asynFloat64ArrayWfOut,
pvar_dset_asynFloat64TimeSeries,
pvar_dset_asynRecordDevice,
pvar_dset_devMotorAsyn,
pvar_dset_devsCalcoutSoft,
pvar_dset_devaCalcoutSoft,
pvar_dset_devSWaitIoEvent
};
epicsShareExtern drvet *pvar_drvet_drvAsyn;
static const char *driverSupportNames[1] = {
"drvAsyn"
};
static struct drvet *drvsl[1] = {
pvar_drvet_drvAsyn
};
epicsShareExtern void (*pvar_func_asSub)(void);
epicsShareExtern void (*pvar_func_asynRegister)(void);
epicsShareExtern void (*pvar_func_asynInterposeFlushRegister)(void);
epicsShareExtern void (*pvar_func_asynInterposeEosRegister)(void);
epicsShareExtern void (*pvar_func_motorUtilRegister)(void);
epicsShareExtern void (*pvar_func_motorRegister)(void);
epicsShareExtern void (*pvar_func_asynMotorControllerRegister)(void);
epicsShareExtern void (*pvar_func_drvAsynIPPortRegisterCommands)(void);
epicsShareExtern void (*pvar_func_drvAsynIPServerPortRegisterCommands)(void);
epicsShareExtern void (*pvar_func_drvAsynSerialPortRegisterCommands)(void);
epicsShareExtern void (*pvar_func_smarActMCSMotorRegister)(void);
epicsShareExtern void (*pvar_func_save_restoreRegister)(void);
epicsShareExtern void (*pvar_func_dbrestoreRegister)(void);
epicsShareExtern void (*pvar_func_asInitHooksRegister)(void);
epicsShareExtern void (*pvar_func_configMenuRegistrar)(void);
epicsShareExtern void (*pvar_func_subAveRegister)(void);
epicsShareExtern void (*pvar_func_interpRegister)(void);
epicsShareExtern void (*pvar_func_arrayTestRegister)(void);
epicsShareExtern int *pvar_int_asCaDebug;
epicsShareExtern int *pvar_int_dbRecordsOnceOnly;
epicsShareExtern int *pvar_int_dbBptNotMonotonic;
epicsShareExtern int *pvar_int_save_restoreDebug;
epicsShareExtern int *pvar_int_save_restoreNumSeqFiles;
epicsShareExtern int *pvar_int_save_restoreSeqPeriodInSeconds;
epicsShareExtern int *pvar_int_save_restoreIncompleteSetsOk;
epicsShareExtern int *pvar_int_save_restoreDatedBackupFiles;
epicsShareExtern int *pvar_int_save_restoreRemountThreshold;
epicsShareExtern int *pvar_int_configMenuDebug;
epicsShareExtern int *pvar_int_debugSubAve;
epicsShareExtern int *pvar_int_sCalcPostfixDebug;
epicsShareExtern int *pvar_int_sCalcPerformDebug;
epicsShareExtern int *pvar_int_sCalcoutRecordDebug;
epicsShareExtern int *pvar_int_devsCalcoutSoftDebug;
epicsShareExtern int *pvar_int_sCalcStackHW;
epicsShareExtern int *pvar_int_sCalcStackLW;
epicsShareExtern int *pvar_int_sCalcLoopMax;
epicsShareExtern int *pvar_int_aCalcPostfixDebug;
epicsShareExtern int *pvar_int_aCalcPerformDebug;
epicsShareExtern int *pvar_int_aCalcoutRecordDebug;
epicsShareExtern int *pvar_int_devaCalcoutSoftDebug;
epicsShareExtern int *pvar_int_aCalcLoopMax;
epicsShareExtern int *pvar_int_aCalcAsyncThreshold;
epicsShareExtern int *pvar_int_transformRecordDebug;
epicsShareExtern int *pvar_int_interpDebug;
epicsShareExtern int *pvar_int_arrayTestDebug;
epicsShareExtern int *pvar_int_sseqRecDebug;
epicsShareExtern int *pvar_int_swaitRecordDebug;
static struct iocshVarDef vardefs[] = {
{"asCaDebug", iocshArgInt, (void * const)pvar_int_asCaDebug},
{"dbRecordsOnceOnly", iocshArgInt, (void * const)pvar_int_dbRecordsOnceOnly},
{"dbBptNotMonotonic", iocshArgInt, (void * const)pvar_int_dbBptNotMonotonic},
{"save_restoreDebug", iocshArgInt, (void * const)pvar_int_save_restoreDebug},
{"save_restoreNumSeqFiles", iocshArgInt, (void * const)pvar_int_save_restoreNumSeqFiles},
{"save_restoreSeqPeriodInSeconds", iocshArgInt, (void * const)pvar_int_save_restoreSeqPeriodInSeconds},
{"save_restoreIncompleteSetsOk", iocshArgInt, (void * const)pvar_int_save_restoreIncompleteSetsOk},
{"save_restoreDatedBackupFiles", iocshArgInt, (void * const)pvar_int_save_restoreDatedBackupFiles},
{"save_restoreRemountThreshold", iocshArgInt, (void * const)pvar_int_save_restoreRemountThreshold},
{"configMenuDebug", iocshArgInt, (void * const)pvar_int_configMenuDebug},
{"debugSubAve", iocshArgInt, (void * const)pvar_int_debugSubAve},
{"sCalcPostfixDebug", iocshArgInt, (void * const)pvar_int_sCalcPostfixDebug},
{"sCalcPerformDebug", iocshArgInt, (void * const)pvar_int_sCalcPerformDebug},
{"sCalcoutRecordDebug", iocshArgInt, (void * const)pvar_int_sCalcoutRecordDebug},
{"devsCalcoutSoftDebug", iocshArgInt, (void * const)pvar_int_devsCalcoutSoftDebug},
{"sCalcStackHW", iocshArgInt, (void * const)pvar_int_sCalcStackHW},
{"sCalcStackLW", iocshArgInt, (void * const)pvar_int_sCalcStackLW},
{"sCalcLoopMax", iocshArgInt, (void * const)pvar_int_sCalcLoopMax},
{"aCalcPostfixDebug", iocshArgInt, (void * const)pvar_int_aCalcPostfixDebug},
{"aCalcPerformDebug", iocshArgInt, (void * const)pvar_int_aCalcPerformDebug},
{"aCalcoutRecordDebug", iocshArgInt, (void * const)pvar_int_aCalcoutRecordDebug},
{"devaCalcoutSoftDebug", iocshArgInt, (void * const)pvar_int_devaCalcoutSoftDebug},
{"aCalcLoopMax", iocshArgInt, (void * const)pvar_int_aCalcLoopMax},
{"aCalcAsyncThreshold", iocshArgInt, (void * const)pvar_int_aCalcAsyncThreshold},
{"transformRecordDebug", iocshArgInt, (void * const)pvar_int_transformRecordDebug},
{"interpDebug", iocshArgInt, (void * const)pvar_int_interpDebug},
{"arrayTestDebug", iocshArgInt, (void * const)pvar_int_arrayTestDebug},
{"sseqRecDebug", iocshArgInt, (void * const)pvar_int_sseqRecDebug},
{"swaitRecordDebug", iocshArgInt, (void * const)pvar_int_swaitRecordDebug},
{NULL, iocshArgInt, NULL}
};
int smaract_registerRecordDeviceDriver(DBBASE *pbase)
{
const char *bldTop = "/epics/iocs/mc15-smaract";
const char *envTop = getenv("TOP");
if (envTop && strcmp(envTop, bldTop)) {
printf("Warning: IOC is booting with TOP = \"%s\"\n"
" but was built with TOP = \"%s\"\n",
envTop, bldTop);
}
if (!pbase) {
printf("pdbbase is NULL; you must load a DBD file first.\n");
return -1;
}
registerRecordTypes(pbase, 36, recordTypeNames, rtl);
registerDevices(pbase, 88, deviceSupportNames, devsl);
registerDrivers(pbase, 1, driverSupportNames, drvsl);
(*pvar_func_asSub)();
(*pvar_func_asynRegister)();
(*pvar_func_asynInterposeFlushRegister)();
(*pvar_func_asynInterposeEosRegister)();
(*pvar_func_motorUtilRegister)();
(*pvar_func_motorRegister)();
(*pvar_func_asynMotorControllerRegister)();
(*pvar_func_drvAsynIPPortRegisterCommands)();
(*pvar_func_drvAsynIPServerPortRegisterCommands)();
(*pvar_func_drvAsynSerialPortRegisterCommands)();
(*pvar_func_smarActMCSMotorRegister)();
(*pvar_func_save_restoreRegister)();
(*pvar_func_dbrestoreRegister)();
(*pvar_func_asInitHooksRegister)();
(*pvar_func_configMenuRegistrar)();
(*pvar_func_subAveRegister)();
(*pvar_func_interpRegister)();
(*pvar_func_arrayTestRegister)();
iocshRegisterVariable(vardefs);
return 0;
}
/* registerRecordDeviceDriver */
static const iocshArg registerRecordDeviceDriverArg0 =
{"pdbbase",iocshArgPdbbase};
static const iocshArg *registerRecordDeviceDriverArgs[1] =
{®isterRecordDeviceDriverArg0};
static const iocshFuncDef registerRecordDeviceDriverFuncDef =
{"smaract_registerRecordDeviceDriver",1,registerRecordDeviceDriverArgs};
static void registerRecordDeviceDriverCallFunc(const iocshArgBuf *)
{
smaract_registerRecordDeviceDriver(*iocshPpdbbase);
}
} // extern "C"
/*
* Register commands on application startup
*/
static int Registration() {
iocshRegisterCommon();
iocshRegister(®isterRecordDeviceDriverFuncDef,
registerRecordDeviceDriverCallFunc);
return 0;
}
static int done = Registration();
| [
"lyang@bnl.gov"
] | lyang@bnl.gov |
3052984719aa91f18615c7937861c07a526b5082 | 2cae54fe441ad0e84b8df6917153bbe3c81ae986 | /conundrum/conundrum.cpp | 13b67d8c57c560523a8b1f629fd64b8b6202748a | [
"MIT"
] | permissive | omarchehab98/open.kattis.com-problems | 3cb08a475ca4fb156462904a221362b98c2813c9 | 0523e2e641151dad719ef05cc9811a8ef5c6a278 | refs/heads/master | 2020-03-31T04:23:06.415280 | 2019-10-29T00:50:08 | 2019-10-29T00:50:08 | 151,903,075 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 260 | cpp | #include <iostream>
using namespace std;
int main() {
string cipherText;
cin >> cipherText;
int numberOfDays = 0;
for (int i = 0; i < cipherText.size(); i++) {
if (cipherText[i] != ("PER")[i % 3]) numberOfDays++;
}
cout << numberOfDays;
} | [
"omarchehab98@gmail.com"
] | omarchehab98@gmail.com |
c6736e136dc0c5cf9feb61c3e784acd048ecb732 | 77c7744d0b303165f0418eaef588939b561c98f2 | /Module 2/Chapter03/chapter03/scenetoon.h | 2509b531c5178c556ef2bac1ba496329aca75545 | [
"MIT"
] | permissive | PacktPublishing/OpenGL-Build-High-Performance-Graphics | 3e5f0dcae0b0c60b8c41d52aa32b20fe6aacc5dc | 7e68e1f2cf1b0a02c82786c6fde93b34b42f2b86 | refs/heads/master | 2023-02-16T04:21:45.656668 | 2023-01-30T10:14:51 | 2023-01-30T10:14:51 | 88,623,563 | 81 | 26 | null | null | null | null | UTF-8 | C++ | false | false | 650 | h | #ifndef SCENETOON_H
#define SCENETOON_H
#include "scene.h"
#include "glslprogram.h"
#include "vboplane.h"
#include "vboteapot.h"
#include "vbotorus.h"
#include "cookbookogl.h"
#include <glm/glm.hpp>
using glm::mat4;
class SceneToon : public Scene
{
private:
GLSLProgram prog;
int width, height;
VBOPlane *plane;
VBOTeapot *teapot;
VBOTorus *torus;
mat4 model;
mat4 view;
mat4 projection;
float angle;
void setMatrices();
void compileAndLinkShader();
public:
SceneToon();
void initScene();
void update( float t );
void render();
void resize(int, int);
};
#endif // SCENETOON_H
| [
"jijom@packtpub.com"
] | jijom@packtpub.com |
dee7efed53b60b78fbaef400ec19a88743d9f9e0 | 25adfb6b9406f64781535eed760272a104b3bb98 | /src/hailstone/stdafx.cpp | b9bf850878fb3db7720a9a8b96c3172a2cf0b3a1 | [] | no_license | shanfeng094/DSA | cf00d9981fbdbdf690061377a8cd615284102e27 | 3fcce6f128d7771602fa2f9809b06ee06329d006 | refs/heads/master | 2020-03-29T06:09:31.087389 | 2016-07-26T14:38:44 | 2016-07-26T14:38:44 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 262 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// hailstone.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中
// 引用任何所需的附加头文件,而不是在此文件中引用
| [
"wanglinzhizhi@hotmail.com"
] | wanglinzhizhi@hotmail.com |
7bda8d0e3c66f839bba4cecff1c2c49fb1de3403 | 7f18180685eb683cc46edd9ad73306a365e501cd | /Romulus/Source/Utility/SceneToSTL.cpp | 62fabcfdeb255b401550f2f6567e24573434b853 | [] | no_license | jfhamlin/perry | fab62ace7d80cb4d661c26b901263d4ad56b0ac2 | 2ff74d5c71c254b8857f1d7fac8499eee56ea5ab | refs/heads/master | 2021-09-05T04:15:57.545952 | 2018-01-24T04:35:29 | 2018-01-24T04:35:29 | 118,711,533 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,834 | cpp | #include "Render/IScene.h"
#include "Math/Matrix.h"
#include "Math/Vector.h"
#include "Utility/SceneToSTL.h"
#include <map>
namespace romulus
{
using namespace render;
using namespace math;
namespace
{
void GeometryChunkInstanceToSTL(const GeometryChunkInstance& gci,
std::ostream& out)
{
const Matrix44& xform = gci.Transform();
const GeometryChunk* gc = gci.GeometryChunk();
const ushort_t* ind = gc->Indices();
for (uint_t index = 0; index < gc->IndexCount(); index += 3)
{
if (ind[index] == ind[index + 1] && ind[index] == ind[index + 2])
continue;
Vector3 v0, v1, v2;
v0 = gc->Vertices()[ind[index]];
v1 = gc->Vertices()[ind[index + 1]];
v2 = gc->Vertices()[ind[index + 2]];
Vector3 normal = Normal(Cross(Normal(v1 - v0), Normal(v2 - v1)));
normal = Submatrix<3, 3, 0, 0>(xform) * normal;
out << " facet normal " << normal[0] << ' ' << normal[1] <<
' ' << normal[2] << '\n';
out << " outer loop\n";
for (uint_t i = 0; i < 3; ++i)
{
Vector4 vert(gc->Vertices()[ind[index + i]], 1);
vert = xform * vert;
out << " vertex " << vert[0] << ' ' << vert[1] <<
' ' << vert[2] << '\n';
}
out << " endloop\n";
out << " endfacet\n";
}
}
} // namespace
void SceneFrameToSTL(const render::IScene& scene, std::ostream& out)
{
out << "solid FOO\n";
IScene::GeometryCollection geo;
scene.Geometry(geo);
// Emit the geometry chunk instances.
for (IScene::GeometryCollection::iterator it = geo.begin();
it != geo.end(); ++it)
{
GeometryChunkInstanceToSTL(**it, out);
}
out << "endsolid FOO\n";
}
} // namespace romulus
| [
"james@goforward.com"
] | james@goforward.com |
d43a966ba619d1c0c28b8df20dcad4412968fae2 | cc6d2210ef75079ebb9d3569cb228d1709434a73 | /Arduino/NTP/NTP.ino | e5eb58e1cce3f232db35193742e52e3cf6c0eb49 | [] | no_license | kkulkarni32/Martiny | bf0257079a983b3aa01485d9612ab5961e82ea39 | 7d812af1a343437c5afc2ee0557c344993f843f8 | refs/heads/master | 2023-04-06T17:54:00.160361 | 2021-04-19T21:43:34 | 2021-04-19T21:43:34 | 302,507,912 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,504 | ino | #include <ESP8266WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
// Replace with your network credentials
const char *ssid = "TP-Link_82DE";
const char *password = "67244737";
// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org");
//Week Days
String weekDays[7]={"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
//Month names
String months[12]={"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
void setup() {
// Initialize Serial Monitor
Serial.begin(115200);
// Connect to Wi-Fi
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Initialize a NTPClient to get time
timeClient.begin();
// Set offset time in seconds to adjust for your timezone, for example:
// GMT +1 = 3600
// GMT +8 = 28800
// GMT -1 = -3600
// GMT 0 = 0
timeClient.setTimeOffset(-25200);
}
void loop() {
timeClient.update();
unsigned long epochTime = timeClient.getEpochTime();
Serial.print("Epoch Time: ");
Serial.println(epochTime);
String formattedTime = timeClient.getFormattedTime();
Serial.print("Formatted Time: ");
Serial.println(formattedTime);
int currentHour = timeClient.getHours();
Serial.print("Hour: ");
Serial.println(currentHour);
int currentMinute = timeClient.getMinutes();
Serial.print("Minutes: ");
Serial.println(currentMinute);
int currentSecond = timeClient.getSeconds();
Serial.print("Seconds: ");
Serial.println(currentSecond);
String weekDay = weekDays[timeClient.getDay()];
Serial.print("Week Day: ");
Serial.println(weekDay);
//Get a time structure
struct tm *ptm = gmtime ((time_t *)&epochTime);
int monthDay = ptm->tm_mday;
Serial.print("Month day: ");
Serial.println(monthDay);
int currentMonth = ptm->tm_mon+1;
Serial.print("Month: ");
Serial.println(currentMonth);
String currentMonthName = months[currentMonth-1];
Serial.print("Month name: ");
Serial.println(currentMonthName);
int currentYear = ptm->tm_year+1900;
Serial.print("Year: ");
Serial.println(currentYear);
//Print complete date:
String currentDate = String(currentYear) + "-" + String(currentMonth) + "-" + String(monthDay);
Serial.print("Current date: ");
Serial.println(currentDate);
Serial.println("");
delay(2000);
}
| [
"kkulkar4@asu.edu"
] | kkulkar4@asu.edu |
2981f5b7723db2c9dad0ecca3c4b790961fe5191 | 57789c0479da2d7a25478a1689ff892613ce4945 | /Classes/WXPanel.h | 5cebc8e0d8e434242d637ae9c00c956a3ab4ddbf | [] | no_license | niujianlong/Nodie | 0c83c2e762e816b3b1e25284d6379b7347361b04 | 45e25c86292a5635312b1c55545d9358fd6be7dd | refs/heads/master | 2020-04-16T22:20:56.707466 | 2015-11-12T04:29:45 | 2015-11-12T04:29:45 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,593 | h | #pragma once
#include "WXSimplePanel.h"
//移动类型
typedef enum
{
tween_type_only_start,//只从开始到结束tween
tween_type_only_end,//只从结束到开始tween
tween_type_both,//从开始到结束,结束到开始都tween
}TweenType;
class WXSimpleButton;
class WXPanel: public WXSimplePanel
{
public:
WXPanel(void);
~WXPanel(void);
virtual void initPanel();
//开关面板
virtual void toggle();
//面板移动
virtual void tween(bool isShow=true);
//创建一个关闭按钮
virtual void createCloseBtn(const char* normalName, const char* selectedName);
//关闭按钮touchBegan
virtual bool closeBtnTouchBegan(cocos2d::CCTouch* pTouch, cocos2d::CCEvent *pEvent);
//关闭按钮touchEnded
virtual bool closeBtnTouchEnded(cocos2d::CCTouch* pTouch, cocos2d::CCEvent *pEvent);
CC_SYNTHESIZE(cocos2d::CCPoint, m_startPos, StartPos);//移动开始位置
CC_SYNTHESIZE(cocos2d::CCPoint, m_endPos, EndPos);//移动停止位置
CC_SYNTHESIZE(float, m_tweenDuration, TweenDuration);//移动耗时
CC_SYNTHESIZE(bool, m_canTween, CanTween);//能否移动
CC_SYNTHESIZE(float, m_closeBtnGap, CloseBtnGap);//关闭按钮偏移
CC_SYNTHESIZE(TweenType, m_tweenType, TweenType);//滚动方式
CREATE_FUNC(WXPanel);
protected:
//tween回调(start->end)
virtual void tweenCallback();
//tween回调(end->start)
virtual void tweenBackCallback();
//关闭按钮回调
virtual void closeCallback(cocos2d::CCObject* pSender);
protected:
cocos2d::CCAction* m_tweenAction;//移动的action
WXSimpleButton* m_closeBtn;
bool m_isTweenning;//是否正在移动
};
| [
"543062527@qq.com"
] | 543062527@qq.com |
0b2a77f1b17bf891c59abad499a5b5103a0038e6 | 3da93763bbc39692ef6f468a91c42b335674af44 | /src/producer.cc | dd13a5291213fcc8c122342514c9fca0645a30ec | [] | no_license | mbirostris/cpt | 59f5fd0a45bf2c044b55156835dbb1c5c460ee84 | 5bae5d82647e271e686f892b0b762425563f1e50 | refs/heads/master | 2020-06-06T03:07:26.096708 | 2015-06-23T08:04:12 | 2015-06-23T08:04:12 | 27,839,425 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,214 | cc | #include "../interface/producer.h"
#include "../interface/counter.h"
chain producer::get(chain ch){
chain result = ch;
for (std::vector<std::string >::size_type i = 0; i != ch.getSize(); i++){
// czytamy oryginalny plik z drzewem
TFile *file = new TFile((ch.getFolder(i)+ch.getFilename(i)).c_str());
TTree *tree = (TTree*)file->Get(ch.getBranch(i).c_str());
// robimy odpowiedni plik z selekcja
// f->GetListOfKeys()->Print();
std::string outputFileName("./temp/");
outputFileName += ch.getFilename(i);
TFile *f = new TFile(outputFileName.c_str(),"UPDATE");
std::string key = "0";
while(f->GetKey(key.c_str())){
int inn = rand() % 10000;
key = std::to_string(inn);
}
result.setInn(key);
//tree for new cut
TTree *to = new TTree(result.getInn(),"");
// to->SetMakeClass(1); // Mowi, ze w branchu sa tylko typy podstawowe, jak float, int itp.
TTree *cut = 0;
if(f->GetKey(ch.getInn())){
cut = (TTree*)f->Get(ch.getInn());
}
this->produce(tree, to, cut);
delete to;
// f->Close();
delete f, file;
}
return result;
}
| [
"olszewski.mikael@gmail.com"
] | olszewski.mikael@gmail.com |
c4d79421bd19d57235ed92c6b8e9bc081d823a1e | 352abb7b0c7cada5248183549d24e1619bbe4dc5 | /arbi5_runing/NameConverter.cpp | bedb2af24adbd6dda87c80d861054352e40313c9 | [] | no_license | 15831944/arbi6 | 048c181196305c483e94729356c3d48c57eddb62 | 86a8e673ef2b9e79c39fa1667e52ee2ffdc4f082 | refs/heads/master | 2023-03-19T11:56:24.148575 | 2015-07-13T08:06:11 | 2015-07-13T08:06:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,412 | cpp | #include "NameConverter.h"
NameConverter* NameConverter::m_pNC=NULL;
NameConverter* NameConverter::getInstance()
{
if(m_pNC==NULL)
{
m_pNC = new NameConverter();
m_pNC->init();
}
return m_pNC;
}
string& NameConverter::trim_string(string &s, const char *chars/*=NULL*/)
{
if (s.length() > 0)
{
if (chars == NULL)
chars = " \t\r\n";
while ((::strchr(chars, *s.begin())) && (s.length() > 0))
s.erase(s.begin());
while ((::strchr(chars, *s.rbegin())) && (s.length() > 0))
s.erase((s.end())-1);
}
return s;
}
void NameConverter::divide_string(const char *str, strings &parts, const char *chars/*=NULL*/, bool allow_empty_part/*=FALSE*/)
{
if (! chars)
chars = " \t";
string s = str;
parts.clear();
while (s.length())
{
int i;
string v;
i = s.find_first_of(chars);
if (i != string::npos)
{
v.assign(s, 0, i);
s.erase(0, i+1);
}
else
{
v = s;
s.erase();
}
trim_string(v);
if ((v.length() > 0) || allow_empty_part)
parts.push_back(v);
}
}
NameConverter::NameConverter(void)
{
InitializeCriticalSection(&cs);
rohonMap.clear();
rohonRevertMap.clear();
rohonMonthMap.clear();
rohonRevertMonthMap.clear();
}
NameConverter::~NameConverter(void)
{
DeleteCriticalSection(&cs);
}
void NameConverter::init(void)
{
rohonMonthMap["01"] = "JAN";
rohonMonthMap["02"] = "FEB";
rohonMonthMap["03"] = "MAR";
rohonMonthMap["04"] = "APR";
rohonMonthMap["05"] = "MAY";
rohonMonthMap["06"] = "JUN";
rohonMonthMap["07"] = "JUL";
rohonMonthMap["08"] = "AUG";
rohonMonthMap["09"] = "SEP";
rohonMonthMap["10"] = "OCT";
rohonMonthMap["11"] = "NOV";
rohonMonthMap["12"] = "DEC";
rohonRevertMonthMap["JAN"]="01";
rohonRevertMonthMap["FEB"]="02";
rohonRevertMonthMap["MAR"]="03";
rohonRevertMonthMap["APR"]="04";
rohonRevertMonthMap["MAY"]="05";
rohonRevertMonthMap["JUN"]="06";
rohonRevertMonthMap["JUL"]="07";
rohonRevertMonthMap["AUG"]="08";
rohonRevertMonthMap["SEP"]="09";
rohonRevertMonthMap["OCT"]="10";
rohonRevertMonthMap["NOV"]="11";
rohonRevertMonthMap["DEC"]="12";
// The following will be changed to read info from file later.
EnterCriticalSection(&cs);
rohonMap["ZS@CBOT"]="CME_CBT SOYBEAN";
rohonMap["ZC@CBOT"]="CME_CBT CORN";
rohonMap["ZM@CBOT"]="CME_CBT SOYMEAL";
rohonMap["ZL@CBOT"]="CME_CBT SOYOIL";
rohonMap["ZW@CBOT"]="CME_CBT WHEAT";
rohonMap["CT@NBOT"]="NYBOT NB COTT";
rohonMap["SB@NBOT"]="NYBOT NB SU11";
rohonMap["HG@NYMEX"]="CME CMX COP";
rohonMap["GC@NYMEX"]="CME CMX GLD";
rohonMap["CL@NYMEX"]="CME CRUDE";
rohonMap["PL@NYMEX"]="CME NYM PAL";
rohonMap["SI@NYMEX"]="CME CMX SIL";
rohonMap["LCA@LME"]="LME CA";
rohonMap["LZS@LME"]="LME ZS";
rohonMap["LAH@LME"]="LME AH";
rohonMap["SN@LME"]="LME SN";
rohonRevertMap["CME_CBT SOYBEAN"]="ZS@CBOT";
rohonRevertMap["CME_CBT CORN"]="ZC@CBOT";
rohonRevertMap["CME_CBT SOYMEAL"]="ZM@CBOT";
rohonRevertMap["CME_CBT SOYOIL"]="ZL@CBOT";
rohonRevertMap["CME_CBT WHEAT"]="ZW@CBOT";
rohonRevertMap["NYBOT NB COTT"]="CT@NBOT";
rohonRevertMap["NYBOT NB SU11"]="SB@NBOT";
rohonRevertMap["CME CMX COP"]="HG@NYMEX";
rohonRevertMap["CME CMX GLD"]="GC@NYMEX";
rohonRevertMap["CME CRUDE"]="CL@NYMEX";
rohonRevertMap["CME NYM PAL"]="PL@NYMEX";
rohonRevertMap["CME CMX SIL"]="SI@NYMEX";
rohonRevertMap["LME CA"]="LCA@LME";
rohonRevertMap["LME ZS"]="LZS@LME";
rohonRevertMap["LME AH"]="LAH@LME";
rohonRevertMap["LME SN"]="SN@LME";
LeaveCriticalSection(&cs);
}
string NameConverter::base2RohonName(string baseName)
{
string ret = "";
string comodity="";
string exchange="";
string month="";
strings pars;
divide_string(baseName.c_str(),pars,"@");
if(pars.size()!=2) return ret;
exchange=pars[1];
int size1 = pars[0].length();
if(pars[1]=="LME"&&pars[0].length()>2)
{
comodity = pars[0].substr(0,size1-2);
month = pars[0].substr(size1-2);
}
else if(pars[0].length()>6)
{
comodity = pars[0].substr(0,size1-6);
month = pars[0].substr(size1-6);
}
else return ret;
map<string, string>::iterator iter = rohonMap.find(comodity+"@"+exchange);
if(iter == rohonMap.end()) return ret;
string rohonExchangeComodity = iter->second;
string rohonMonth = "";
if(exchange=="LME")
{
rohonMonth = month;
}
else
{
map<string, string>::iterator monthIter = rohonMonthMap.find(month.substr(4));
if(monthIter == rohonMonthMap.end()) return ret;
rohonMonth = monthIter->second + month.substr(2,2);
}
return rohonExchangeComodity + " " + rohonMonth;
}
string NameConverter::rohon2BaseName(string rohonName)
{
string ret = "";
strings pars;
divide_string(rohonName.c_str(),pars," ");
if(pars.size()<3) return ret;
string rohonMonth=pars[pars.size()-1];
string baseMonth="";
if(pars[0]=="LME")
{
baseMonth=rohonMonth;
}
else
{
map<string, string>::iterator revertMonthIter = rohonRevertMonthMap.find(rohonMonth.substr(0,3));
if(revertMonthIter == rohonRevertMonthMap.end()) return ret;
baseMonth = "20"+ rohonMonth.substr(3) + revertMonthIter->second;
}
string rohonExchangeComodity = rohonName.substr(0,rohonName.find_last_of(" "));
map<string, string>::iterator revertIter = rohonRevertMap.find(rohonExchangeComodity);
if(revertIter == rohonRevertMap.end()) return ret;
string baseExchangeComodity = revertIter->second;
strings basePars;
divide_string(baseExchangeComodity.c_str(),basePars,"@");
if(basePars.size()!=2) return ret;
return basePars[0]+"-" + baseMonth + "@"+basePars[1];
} | [
"sunhao@sanss.com"
] | sunhao@sanss.com |
a23e7ace9ea99cdb56e58ab77b377c0406359e74 | cc051fc770f7dce5b19750cf8eade652fe03f17c | /depthCameraPcl.h | 137f8889b4168553d3bfd7e4c8fb39b8f2ade219 | [] | no_license | underdoeg/godot-depth-camera-test | f0778f0b1444775924a28d51443b8768f5988547 | f823b0fcbc4fe74c1e88196cd2288a07aaabcf8d | refs/heads/master | 2021-01-19T20:12:15.411608 | 2017-03-11T22:33:16 | 2017-03-11T22:33:16 | 84,684,085 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 332 | h | #ifndef DEPTHCAMERAPCL_H
#define DEPTHCAMERAPCL_H
#include "depthCamera.h"
class DepthCameraPcl: public DepthCamera{
OBJ_TYPE(DepthCameraPcl, DepthCamera)
public:
DepthCameraPcl();
bool startGrabbingImpl();
bool stopGrabbingImpl();
private:
std::shared_ptr<pcl::io::OpenNI2Grabber> grabber;
};
#endif // DEPTHCAMERAPCL_H
| [
"philip@undef.ch"
] | philip@undef.ch |
9b054940c7234e0fb6f166d49f485391caebcd21 | 9e0d6d3cff2e03ab4487269f295dc872e07544e4 | /src/main.h | dacb3d07593e205e788304167fcaeb117276d78d | [
"MIT"
] | permissive | gyun0526/ESRcoin | b39c6776f6b767e6f87d57b227b1233201219515 | 25a418f88f7554a00f60a9cbfcb875f07d2c75fc | refs/heads/master | 2021-05-03T11:34:53.617508 | 2018-02-07T03:12:29 | 2018-02-07T03:12:29 | 120,550,930 | 1 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 72,423 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_MAIN_H
#define BITCOIN_MAIN_H
#include "bignum.h"
#include "sync.h"
#include "net.h"
#include "script.h"
#include "scrypt.h"
#include <list>
class CWallet;
class CBlock;
class CBlockIndex;
class CKeyItem;
class CReserveKey;
class CAddress;
class CInv;
class CNode;
struct CBlockIndexWorkComparator;
/** The maximum allowed size for a serialized block, in bytes (network rule) */
static const unsigned int MAX_BLOCK_SIZE = 1000000; // 1000KB block hard limit
/** Obsolete: maximum size for mined blocks */
static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/4; // 250KB block soft limit
/** Default for -blockmaxsize, maximum size for mined blocks **/
static const unsigned int DEFAULT_BLOCK_MAX_SIZE = 250000;
/** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/
static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = 17000;
/** The maximum size for transactions we're willing to relay/mine */
static const unsigned int MAX_STANDARD_TX_SIZE = 100000;
/** The maximum allowed number of signature check operations in a block (network rule) */
static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
/** Default for -maxorphantx, maximum number of orphan transactions kept in memory */
static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 25;
/** The maximum size of a blk?????.dat file (since 0.8) */
static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
/** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
/** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
/** Fake height value used in CCoins to signify they are only in the memory pool (since 0.8) */
static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF;
/** Dust Soft Limit, allowed with additional fee per output */
static const int64 DUST_SOFT_LIMIT = 100000; // 0.001 ESRC
/** Dust Hard Limit, ignored as wallet inputs (mininput default) */
static const int64 DUST_HARD_LIMIT = 1000; // 0.00001 ESRC mininput
/** No amount larger than this (in satoshi) is valid */
static const int64 MAX_MONEY = 144000000 * COIN;
inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
/** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */
static const int COINBASE_MATURITY = 20;
/** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
/** Maximum number of script-checking threads allowed */
static const int MAX_SCRIPTCHECK_THREADS = 16;
#ifdef USE_UPNP
static const int fHaveUPnP = true;
#else
static const int fHaveUPnP = false;
#endif
extern CScript COINBASE_FLAGS;
extern CCriticalSection cs_main;
extern std::map<uint256, CBlockIndex*> mapBlockIndex;
extern std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid;
extern uint256 hashGenesisBlock;
extern CBlockIndex* pindexGenesisBlock;
extern int nBestHeight;
extern uint256 nBestChainWork;
extern uint256 nBestInvalidWork;
extern uint256 hashBestChain;
extern CBlockIndex* pindexBest;
extern unsigned int nTransactionsUpdated;
extern uint64 nLastBlockTx;
extern uint64 nLastBlockSize;
extern const std::string strMessageMagic;
extern double dHashesPerSec;
extern int64 nHPSTimerStart;
extern int64 nTimeBestReceived;
extern CCriticalSection cs_setpwalletRegistered;
extern std::set<CWallet*> setpwalletRegistered;
extern unsigned char pchMessageStart[4];
extern bool fImporting;
extern bool fReindex;
extern bool fBenchmark;
extern int nScriptCheckThreads;
extern bool fTxIndex;
extern unsigned int nCoinCacheSize;
// Settings
extern int64 nTransactionFee;
extern int64 nMinimumInputValue;
// Minimum disk space required - used in CheckDiskSpace()
static const uint64 nMinDiskSpace = 52428800;
class CReserveKey;
class CCoinsDB;
class CBlockTreeDB;
struct CDiskBlockPos;
class CCoins;
class CTxUndo;
class CCoinsView;
class CCoinsViewCache;
class CScriptCheck;
class CValidationState;
struct CBlockTemplate;
/** Register a wallet to receive updates from core */
void RegisterWallet(CWallet* pwalletIn);
/** Unregister a wallet from core */
void UnregisterWallet(CWallet* pwalletIn);
/** Push an updated transaction to all registered wallets */
void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false);
/** Process an incoming block */
bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL);
/** Check whether enough disk space is available for an incoming block */
bool CheckDiskSpace(uint64 nAdditionalBytes = 0);
/** Open a block file (blk?????.dat) */
FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false);
/** Open an undo file (rev?????.dat) */
FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false);
/** Import blocks from an external file */
bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL);
/** Initialize a new block tree database + block data on disk */
bool InitBlockIndex();
/** Load the block tree and coins database from disk */
bool LoadBlockIndex();
/** Unload database information */
void UnloadBlockIndex();
/** Verify consistency of the block and coin databases */
bool VerifyDB(int nCheckLevel, int nCheckDepth);
/** Print the loaded block tree */
void PrintBlockTree();
/** Find a block by height in the currently-connected chain */
CBlockIndex* FindBlockByHeight(int nHeight);
/** Process protocol messages received from a given node */
bool ProcessMessages(CNode* pfrom);
/** Send queued protocol messages to be sent to a give node */
bool SendMessages(CNode* pto, bool fSendTrickle);
/** Run an instance of the script checking thread */
void ThreadScriptCheck();
/** Run the miner threads */
void GenerateBitcoins(bool fGenerate, CWallet* pwallet);
/** Generate a new block, without valid proof-of-work */
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn);
CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey);
/** Modify the extranonce in a block */
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce);
/** Do mining precalculation */
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1);
/** Check mined block */
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey);
/** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */
bool CheckProofOfWork(uint256 hash, unsigned int nBits);
/** Calculate the minimum amount of work a received block needs, without knowing its direct parent */
unsigned int ComputeMinWork(unsigned int nBase, int64 nTime);
/** Get the number of active peers */
int GetNumBlocksOfPeers();
/** Check whether we are doing an initial block download (synchronizing from disk or network) */
bool IsInitialBlockDownload();
/** Format a string that describes several potential problems detected by the core */
std::string GetWarnings(std::string strFor);
/** Retrieve a transaction (from memory pool, or from disk, if possible) */
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false);
/** Connect/disconnect blocks until pindexNew is the new tip of the active block chain */
bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew);
/** Find the best known block, and make it the tip of the block chain */
bool ConnectBestBlock(CValidationState &state);
/** Create a new block index entry for a given block hash */
CBlockIndex * InsertBlockIndex(uint256 hash);
/** Verify a signature */
bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType);
/** Abort with a message */
bool AbortNode(const std::string &msg);
bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
struct CDiskBlockPos
{
int nFile;
unsigned int nPos;
IMPLEMENT_SERIALIZE(
READWRITE(VARINT(nFile));
READWRITE(VARINT(nPos));
)
CDiskBlockPos() {
SetNull();
}
CDiskBlockPos(int nFileIn, unsigned int nPosIn) {
nFile = nFileIn;
nPos = nPosIn;
}
friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) {
return (a.nFile == b.nFile && a.nPos == b.nPos);
}
friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) {
return !(a == b);
}
void SetNull() { nFile = -1; nPos = 0; }
bool IsNull() const { return (nFile == -1); }
};
struct CDiskTxPos : public CDiskBlockPos
{
unsigned int nTxOffset; // after header
IMPLEMENT_SERIALIZE(
READWRITE(*(CDiskBlockPos*)this);
READWRITE(VARINT(nTxOffset));
)
CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) {
}
CDiskTxPos() {
SetNull();
}
void SetNull() {
CDiskBlockPos::SetNull();
nTxOffset = 0;
}
};
/** An inpoint - a combination of a transaction and an index n into its vin */
class CInPoint
{
public:
CTransaction* ptx;
unsigned int n;
CInPoint() { SetNull(); }
CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
void SetNull() { ptx = NULL; n = (unsigned int) -1; }
bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
};
/** An outpoint - a combination of a transaction hash and an index n into its vout */
class COutPoint
{
public:
uint256 hash;
unsigned int n;
COutPoint() { SetNull(); }
COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
void SetNull() { hash = 0; n = (unsigned int) -1; }
bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
friend bool operator<(const COutPoint& a, const COutPoint& b)
{
return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
}
friend bool operator==(const COutPoint& a, const COutPoint& b)
{
return (a.hash == b.hash && a.n == b.n);
}
friend bool operator!=(const COutPoint& a, const COutPoint& b)
{
return !(a == b);
}
std::string ToString() const
{
return strprintf("COutPoint(%s, %u)", hash.ToString().c_str(), n);
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** An input of a transaction. It contains the location of the previous
* transaction's output that it claims and a signature that matches the
* output's public key.
*/
class CTxIn
{
public:
COutPoint prevout;
CScript scriptSig;
unsigned int nSequence;
CTxIn()
{
nSequence = std::numeric_limits<unsigned int>::max();
}
explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
{
prevout = prevoutIn;
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
{
prevout = COutPoint(hashPrevTx, nOut);
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
IMPLEMENT_SERIALIZE
(
READWRITE(prevout);
READWRITE(scriptSig);
READWRITE(nSequence);
)
bool IsFinal() const
{
return (nSequence == std::numeric_limits<unsigned int>::max());
}
friend bool operator==(const CTxIn& a, const CTxIn& b)
{
return (a.prevout == b.prevout &&
a.scriptSig == b.scriptSig &&
a.nSequence == b.nSequence);
}
friend bool operator!=(const CTxIn& a, const CTxIn& b)
{
return !(a == b);
}
std::string ToString() const
{
std::string str;
str += "CTxIn(";
str += prevout.ToString();
if (prevout.IsNull())
str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
else
str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
if (nSequence != std::numeric_limits<unsigned int>::max())
str += strprintf(", nSequence=%u", nSequence);
str += ")";
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** An output of a transaction. It contains the public key that the next input
* must be able to sign with to claim it.
*/
class CTxOut
{
public:
int64 nValue;
CScript scriptPubKey;
CTxOut()
{
SetNull();
}
CTxOut(int64 nValueIn, CScript scriptPubKeyIn)
{
nValue = nValueIn;
scriptPubKey = scriptPubKeyIn;
}
IMPLEMENT_SERIALIZE
(
READWRITE(nValue);
READWRITE(scriptPubKey);
)
void SetNull()
{
nValue = -1;
scriptPubKey.clear();
}
bool IsNull() const
{
return (nValue == -1);
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
friend bool operator==(const CTxOut& a, const CTxOut& b)
{
return (a.nValue == b.nValue &&
a.scriptPubKey == b.scriptPubKey);
}
friend bool operator!=(const CTxOut& a, const CTxOut& b)
{
return !(a == b);
}
bool IsDust() const;
std::string ToString() const
{
return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
enum GetMinFee_mode
{
GMF_BLOCK,
GMF_RELAY,
GMF_SEND,
};
/** The basic transaction that is broadcasted on the network and contained in
* blocks. A transaction can contain multiple inputs and outputs.
*/
class CTransaction
{
public:
static int64 nMinTxFee;
static int64 nMinRelayTxFee;
static const int CURRENT_VERSION=1;
int nVersion;
std::vector<CTxIn> vin;
std::vector<CTxOut> vout;
unsigned int nLockTime;
CTransaction()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(vin);
READWRITE(vout);
READWRITE(nLockTime);
)
void SetNull()
{
nVersion = CTransaction::CURRENT_VERSION;
vin.clear();
vout.clear();
nLockTime = 0;
}
bool IsNull() const
{
return (vin.empty() && vout.empty());
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
uint256 GetNormalizedHash() const
{
return SignatureHash(CScript(), *this, 0, SIGHASH_ALL);
}
bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const
{
// Time based nLockTime implemented in 0.1.6
if (nLockTime == 0)
return true;
if (nBlockHeight == 0)
nBlockHeight = nBestHeight;
if (nBlockTime == 0)
nBlockTime = GetAdjustedTime();
if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime))
return true;
BOOST_FOREACH(const CTxIn& txin, vin)
if (!txin.IsFinal())
return false;
return true;
}
bool IsNewerThan(const CTransaction& old) const
{
if (vin.size() != old.vin.size())
return false;
for (unsigned int i = 0; i < vin.size(); i++)
if (vin[i].prevout != old.vin[i].prevout)
return false;
bool fNewer = false;
unsigned int nLowest = std::numeric_limits<unsigned int>::max();
for (unsigned int i = 0; i < vin.size(); i++)
{
if (vin[i].nSequence != old.vin[i].nSequence)
{
if (vin[i].nSequence <= nLowest)
{
fNewer = false;
nLowest = vin[i].nSequence;
}
if (old.vin[i].nSequence < nLowest)
{
fNewer = true;
nLowest = old.vin[i].nSequence;
}
}
}
return fNewer;
}
bool IsCoinBase() const
{
return (vin.size() == 1 && vin[0].prevout.IsNull());
}
/** Check for standard transaction types
@return True if all outputs (scriptPubKeys) use only standard transaction forms
*/
bool IsStandard(std::string& strReason) const;
bool IsStandard() const
{
std::string strReason;
return IsStandard(strReason);
}
/** Check for standard transaction types
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return True if all inputs (scriptSigs) use only standard transaction forms
*/
bool AreInputsStandard(CCoinsViewCache& mapInputs) const;
/** Count ECDSA signature operations the old-fashioned (pre-0.6) way
@return number of sigops this transaction's outputs will produce when spent
*/
unsigned int GetLegacySigOpCount() const;
/** Count ECDSA signature operations in pay-to-script-hash inputs.
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return maximum number of sigops required to validate this transaction's inputs
*/
unsigned int GetP2SHSigOpCount(CCoinsViewCache& mapInputs) const;
/** Amount of bitcoins spent by this transaction.
@return sum of all outputs (note: does not include fees)
*/
int64 GetValueOut() const
{
int64 nValueOut = 0;
BOOST_FOREACH(const CTxOut& txout, vout)
{
nValueOut += txout.nValue;
if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
}
return nValueOut;
}
/** Amount of bitcoins coming in to this transaction
Note that lightweight clients may not know anything besides the hash of previous transactions,
so may not be able to calculate this.
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return Sum of value of all inputs (scriptSigs)
*/
int64 GetValueIn(CCoinsViewCache& mapInputs) const;
static bool AllowFree(double dPriority)
{
// Large (in bytes) low-priority (new, small-coin) transactions
// need a fee.
return dPriority > COIN * 576 / 250;
}
// Apply the effects of this transaction on the UTXO set represented by view
void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash);
int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const;
friend bool operator==(const CTransaction& a, const CTransaction& b)
{
return (a.nVersion == b.nVersion &&
a.vin == b.vin &&
a.vout == b.vout &&
a.nLockTime == b.nLockTime);
}
friend bool operator!=(const CTransaction& a, const CTransaction& b)
{
return !(a == b);
}
std::string ToString() const
{
std::string str;
str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%u)\n",
GetHash().ToString().c_str(),
nVersion,
vin.size(),
vout.size(),
nLockTime);
for (unsigned int i = 0; i < vin.size(); i++)
str += " " + vin[i].ToString() + "\n";
for (unsigned int i = 0; i < vout.size(); i++)
str += " " + vout[i].ToString() + "\n";
return str;
}
void print() const
{
printf("%s", ToString().c_str());
}
// Check whether all prevouts of this transaction are present in the UTXO set represented by view
bool HaveInputs(CCoinsViewCache &view) const;
// Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
// This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
// instead of being performed inline.
bool CheckInputs(CValidationState &state, CCoinsViewCache &view, bool fScriptChecks = true,
unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC,
std::vector<CScriptCheck> *pvChecks = NULL) const;
// Apply the effects of this transaction on the UTXO set represented by view
void UpdateCoins(CValidationState &state, CCoinsViewCache &view, CTxUndo &txundo, int nHeight, const uint256 &txhash) const;
// Context-independent validity checks
bool CheckTransaction(CValidationState &state) const;
// Try to accept this transaction into the memory pool
bool AcceptToMemoryPool(CValidationState &state, bool fCheckInputs=true, bool fLimitFree = true, bool* pfMissingInputs=NULL, bool fRejectInsaneFee = false);
protected:
static const CTxOut &GetOutputFor(const CTxIn& input, CCoinsViewCache& mapInputs);
};
/** wrapper for CTxOut that provides a more compact serialization */
class CTxOutCompressor
{
private:
CTxOut &txout;
public:
static uint64 CompressAmount(uint64 nAmount);
static uint64 DecompressAmount(uint64 nAmount);
CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { }
IMPLEMENT_SERIALIZE(({
if (!fRead) {
uint64 nVal = CompressAmount(txout.nValue);
READWRITE(VARINT(nVal));
} else {
uint64 nVal = 0;
READWRITE(VARINT(nVal));
txout.nValue = DecompressAmount(nVal);
}
CScriptCompressor cscript(REF(txout.scriptPubKey));
READWRITE(cscript);
});)
};
/** Undo information for a CTxIn
*
* Contains the prevout's CTxOut being spent, and if this was the
* last output of the affected transaction, its metadata as well
* (coinbase or not, height, transaction version)
*/
class CTxInUndo
{
public:
CTxOut txout; // the txout data before being spent
bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase
unsigned int nHeight; // if the outpoint was the last unspent: its height
int nVersion; // if the outpoint was the last unspent: its version
CTxInUndo() : txout(), fCoinBase(false), nHeight(0), nVersion(0) {}
CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), nHeight(nHeightIn), nVersion(nVersionIn) { }
unsigned int GetSerializeSize(int nType, int nVersion) const {
return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) +
(nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) +
::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion);
}
template<typename Stream>
void Serialize(Stream &s, int nType, int nVersion) const {
::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion);
if (nHeight > 0)
::Serialize(s, VARINT(this->nVersion), nType, nVersion);
::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion);
}
template<typename Stream>
void Unserialize(Stream &s, int nType, int nVersion) {
unsigned int nCode = 0;
::Unserialize(s, VARINT(nCode), nType, nVersion);
nHeight = nCode / 2;
fCoinBase = nCode & 1;
if (nHeight > 0)
::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion);
}
};
/** Undo information for a CTransaction */
class CTxUndo
{
public:
// undo information for all txins
std::vector<CTxInUndo> vprevout;
IMPLEMENT_SERIALIZE(
READWRITE(vprevout);
)
};
/** Undo information for a CBlock */
class CBlockUndo
{
public:
std::vector<CTxUndo> vtxundo; // for all but the coinbase
IMPLEMENT_SERIALIZE(
READWRITE(vtxundo);
)
bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock)
{
// Open history file to append
CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION);
if (!fileout)
return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(*this);
fileout << FLATDATA(pchMessageStart) << nSize;
// Write undo data
long fileOutPos = ftell(fileout);
if (fileOutPos < 0)
return error("CBlockUndo::WriteToDisk() : ftell failed");
pos.nPos = (unsigned int)fileOutPos;
fileout << *this;
// calculate & write checksum
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
hasher << hashBlock;
hasher << *this;
fileout << hasher.GetHash();
// Flush stdio buffers and commit to disk before returning
fflush(fileout);
if (!IsInitialBlockDownload())
FileCommit(fileout);
return true;
}
bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock)
{
// Open history file to read
CAutoFile filein = CAutoFile(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CBlockUndo::ReadFromDisk() : OpenBlockFile failed");
// Read block
uint256 hashChecksum;
try {
filein >> *this;
filein >> hashChecksum;
}
catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
// Verify checksum
CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION);
hasher << hashBlock;
hasher << *this;
if (hashChecksum != hasher.GetHash())
return error("CBlockUndo::ReadFromDisk() : checksum mismatch");
return true;
}
};
/** pruned version of CTransaction: only retains metadata and unspent transaction outputs
*
* Serialized format:
* - VARINT(nVersion)
* - VARINT(nCode)
* - unspentness bitvector, for vout[2] and further; least significant byte first
* - the non-spent CTxOuts (via CTxOutCompressor)
* - VARINT(nHeight)
*
* The nCode value consists of:
* - bit 1: IsCoinBase()
* - bit 2: vout[0] is not spent
* - bit 4: vout[1] is not spent
* - The higher bits encode N, the number of non-zero bytes in the following bitvector.
* - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at
* least one non-spent output).
*
* Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e
* <><><--------------------------------------------><---->
* | \ | /
* version code vout[1] height
*
* - version = 1
* - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow)
* - unspentness bitvector: as 0 non-zero bytes follow, it has length 0
* - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35
* * 8358: compact amount representation for 60000000000 (600 BTC)
* * 00: special txout type pay-to-pubkey-hash
* * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160
* - height = 203998
*
*
* Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b
* <><><--><--------------------------------------------------><----------------------------------------------><---->
* / \ \ | | /
* version code unspentness vout[4] vout[16] height
*
* - version = 1
* - code = 9 (coinbase, neither vout[0] or vout[1] are unspent,
* 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow)
* - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent
* - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee
* * 86ef97d579: compact amount representation for 234925952 (2.35 BTC)
* * 00: special txout type pay-to-pubkey-hash
* * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160
* - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4
* * bbd123: compact amount representation for 110397 (0.001 BTC)
* * 00: special txout type pay-to-pubkey-hash
* * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160
* - height = 120891
*/
class CCoins
{
public:
// whether transaction is a coinbase
bool fCoinBase;
// unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped
std::vector<CTxOut> vout;
// at which height this transaction was included in the active block chain
int nHeight;
// version of the CTransaction; accesses to this value should probably check for nHeight as well,
// as new tx version will probably only be introduced at certain heights
int nVersion;
// construct a CCoins from a CTransaction, at a given height
CCoins(const CTransaction &tx, int nHeightIn) : fCoinBase(tx.IsCoinBase()), vout(tx.vout), nHeight(nHeightIn), nVersion(tx.nVersion) { }
// empty constructor
CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { }
// remove spent outputs at the end of vout
void Cleanup() {
while (vout.size() > 0 && vout.back().IsNull())
vout.pop_back();
if (vout.empty())
std::vector<CTxOut>().swap(vout);
}
void swap(CCoins &to) {
std::swap(to.fCoinBase, fCoinBase);
to.vout.swap(vout);
std::swap(to.nHeight, nHeight);
std::swap(to.nVersion, nVersion);
}
// equality test
friend bool operator==(const CCoins &a, const CCoins &b) {
return a.fCoinBase == b.fCoinBase &&
a.nHeight == b.nHeight &&
a.nVersion == b.nVersion &&
a.vout == b.vout;
}
friend bool operator!=(const CCoins &a, const CCoins &b) {
return !(a == b);
}
// calculate number of bytes for the bitmask, and its number of non-zero bytes
// each bit in the bitmask represents the availability of one output, but the
// availabilities of the first two outputs are encoded separately
void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const {
unsigned int nLastUsedByte = 0;
for (unsigned int b = 0; 2+b*8 < vout.size(); b++) {
bool fZero = true;
for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) {
if (!vout[2+b*8+i].IsNull()) {
fZero = false;
continue;
}
}
if (!fZero) {
nLastUsedByte = b + 1;
nNonzeroBytes++;
}
}
nBytes += nLastUsedByte;
}
bool IsCoinBase() const {
return fCoinBase;
}
unsigned int GetSerializeSize(int nType, int nVersion) const {
unsigned int nSize = 0;
unsigned int nMaskSize = 0, nMaskCode = 0;
CalcMaskSize(nMaskSize, nMaskCode);
bool fFirst = vout.size() > 0 && !vout[0].IsNull();
bool fSecond = vout.size() > 1 && !vout[1].IsNull();
assert(fFirst || fSecond || nMaskCode);
unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
// version
nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion);
// size of header code
nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion);
// spentness bitmask
nSize += nMaskSize;
// txouts themself
for (unsigned int i = 0; i < vout.size(); i++)
if (!vout[i].IsNull())
nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion);
// height
nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion);
return nSize;
}
template<typename Stream>
void Serialize(Stream &s, int nType, int nVersion) const {
unsigned int nMaskSize = 0, nMaskCode = 0;
CalcMaskSize(nMaskSize, nMaskCode);
bool fFirst = vout.size() > 0 && !vout[0].IsNull();
bool fSecond = vout.size() > 1 && !vout[1].IsNull();
assert(fFirst || fSecond || nMaskCode);
unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0);
// version
::Serialize(s, VARINT(this->nVersion), nType, nVersion);
// header code
::Serialize(s, VARINT(nCode), nType, nVersion);
// spentness bitmask
for (unsigned int b = 0; b<nMaskSize; b++) {
unsigned char chAvail = 0;
for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++)
if (!vout[2+b*8+i].IsNull())
chAvail |= (1 << i);
::Serialize(s, chAvail, nType, nVersion);
}
// txouts themself
for (unsigned int i = 0; i < vout.size(); i++) {
if (!vout[i].IsNull())
::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion);
}
// coinbase height
::Serialize(s, VARINT(nHeight), nType, nVersion);
}
template<typename Stream>
void Unserialize(Stream &s, int nType, int nVersion) {
unsigned int nCode = 0;
// version
::Unserialize(s, VARINT(this->nVersion), nType, nVersion);
// header code
::Unserialize(s, VARINT(nCode), nType, nVersion);
fCoinBase = nCode & 1;
std::vector<bool> vAvail(2, false);
vAvail[0] = nCode & 2;
vAvail[1] = nCode & 4;
unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
// spentness bitmask
while (nMaskCode > 0) {
unsigned char chAvail = 0;
::Unserialize(s, chAvail, nType, nVersion);
for (unsigned int p = 0; p < 8; p++) {
bool f = (chAvail & (1 << p)) != 0;
vAvail.push_back(f);
}
if (chAvail != 0)
nMaskCode--;
}
// txouts themself
vout.assign(vAvail.size(), CTxOut());
for (unsigned int i = 0; i < vAvail.size(); i++) {
if (vAvail[i])
::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion);
}
// coinbase height
::Unserialize(s, VARINT(nHeight), nType, nVersion);
Cleanup();
}
// mark an outpoint spent, and construct undo information
bool Spend(const COutPoint &out, CTxInUndo &undo) {
if (out.n >= vout.size())
return false;
if (vout[out.n].IsNull())
return false;
undo = CTxInUndo(vout[out.n]);
vout[out.n].SetNull();
Cleanup();
if (vout.size() == 0) {
undo.nHeight = nHeight;
undo.fCoinBase = fCoinBase;
undo.nVersion = this->nVersion;
}
return true;
}
// mark a vout spent
bool Spend(int nPos) {
CTxInUndo undo;
COutPoint out(0, nPos);
return Spend(out, undo);
}
// check whether a particular output is still available
bool IsAvailable(unsigned int nPos) const {
return (nPos < vout.size() && !vout[nPos].IsNull());
}
// check whether the entire CCoins is spent
// note that only !IsPruned() CCoins can be serialized
bool IsPruned() const {
BOOST_FOREACH(const CTxOut &out, vout)
if (!out.IsNull())
return false;
return true;
}
};
/** Closure representing one script verification
* Note that this stores references to the spending transaction */
class CScriptCheck
{
private:
CScript scriptPubKey;
const CTransaction *ptxTo;
unsigned int nIn;
unsigned int nFlags;
int nHashType;
public:
CScriptCheck() {}
CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) :
scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { }
bool operator()() const;
void swap(CScriptCheck &check) {
scriptPubKey.swap(check.scriptPubKey);
std::swap(ptxTo, check.ptxTo);
std::swap(nIn, check.nIn);
std::swap(nFlags, check.nFlags);
std::swap(nHashType, check.nHashType);
}
};
/** A transaction with a merkle branch linking it to the block chain. */
class CMerkleTx : public CTransaction
{
private:
int GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const;
public:
uint256 hashBlock;
std::vector<uint256> vMerkleBranch;
int nIndex;
// memory only
mutable bool fMerkleVerified;
CMerkleTx()
{
Init();
}
CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
{
Init();
}
void Init()
{
hashBlock = 0;
nIndex = -1;
fMerkleVerified = false;
}
IMPLEMENT_SERIALIZE
(
nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
nVersion = this->nVersion;
READWRITE(hashBlock);
READWRITE(vMerkleBranch);
READWRITE(nIndex);
)
int SetMerkleBranch(const CBlock* pblock=NULL);
// Return depth of transaction in blockchain:
// -1 : not in blockchain, and not in memory pool (conflicted transaction)
// 0 : in memory pool, waiting to be included in a block
// >=1 : this many blocks deep in the main chain
int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
bool IsInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; }
int GetBlocksToMaturity() const;
bool AcceptToMemoryPool(bool fCheckInputs=true, bool fLimitFree=true);
};
/** Data structure that represents a partial merkle tree.
*
* It respresents a subset of the txid's of a known block, in a way that
* allows recovery of the list of txid's and the merkle root, in an
* authenticated way.
*
* The encoding works as follows: we traverse the tree in depth-first order,
* storing a bit for each traversed node, signifying whether the node is the
* parent of at least one matched leaf txid (or a matched txid itself). In
* case we are at the leaf level, or this bit is 0, its merkle node hash is
* stored, and its children are not explorer further. Otherwise, no hash is
* stored, but we recurse into both (or the only) child branch. During
* decoding, the same depth-first traversal is performed, consuming bits and
* hashes as they written during encoding.
*
* The serialization is fixed and provides a hard guarantee about the
* encoded size:
*
* SIZE <= 10 + ceil(32.25*N)
*
* Where N represents the number of leaf nodes of the partial tree. N itself
* is bounded by:
*
* N <= total_transactions
* N <= 1 + matched_transactions*tree_height
*
* The serialization format:
* - uint32 total_transactions (4 bytes)
* - varint number of hashes (1-3 bytes)
* - uint256[] hashes in depth-first order (<= 32*N bytes)
* - varint number of bytes of flag bits (1-3 bytes)
* - byte[] flag bits, packed per 8 in a byte, least significant bit first (<= 2*N-1 bits)
* The size constraints follow from this.
*/
class CPartialMerkleTree
{
protected:
// the total number of transactions in the block
unsigned int nTransactions;
// node-is-parent-of-matched-txid bits
std::vector<bool> vBits;
// txids and internal hashes
std::vector<uint256> vHash;
// flag set when encountering invalid data
bool fBad;
// helper function to efficiently calculate the number of nodes at given height in the merkle tree
unsigned int CalcTreeWidth(int height) {
return (nTransactions+(1 << height)-1) >> height;
}
// calculate the hash of a node in the merkle tree (at leaf level: the txid's themself)
uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid);
// recursive function that traverses tree nodes, storing the data as bits and hashes
void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
// recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild.
// it returns the hash of the respective node.
uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch);
public:
// serialization implementation
IMPLEMENT_SERIALIZE(
READWRITE(nTransactions);
READWRITE(vHash);
std::vector<unsigned char> vBytes;
if (fRead) {
READWRITE(vBytes);
CPartialMerkleTree &us = *(const_cast<CPartialMerkleTree*>(this));
us.vBits.resize(vBytes.size() * 8);
for (unsigned int p = 0; p < us.vBits.size(); p++)
us.vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0;
us.fBad = false;
} else {
vBytes.resize((vBits.size()+7)/8);
for (unsigned int p = 0; p < vBits.size(); p++)
vBytes[p / 8] |= vBits[p] << (p % 8);
READWRITE(vBytes);
}
)
// Construct a partial merkle tree from a list of transaction id's, and a mask that selects a subset of them
CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch);
CPartialMerkleTree();
// extract the matching txid's represented by this partial merkle tree.
// returns the merkle root, or 0 in case of failure
uint256 ExtractMatches(std::vector<uint256> &vMatch);
};
/** Nodes collect new transactions into a block, hash them into a hash tree,
* and scan through nonce values to make the block's hash satisfy proof-of-work
* requirements. When they solve the proof-of-work, they broadcast the block
* to everyone and the block is added to the block chain. The first transaction
* in the block is a special one that creates a new coin owned by the creator
* of the block.
*/
class CBlockHeader
{
public:
// header
static const int CURRENT_VERSION=2;
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
CBlockHeader()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(hashPrevBlock);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
)
void SetNull()
{
nVersion = CBlockHeader::CURRENT_VERSION;
hashPrevBlock = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
}
bool IsNull() const
{
return (nBits == 0);
}
uint256 GetHash() const
{
return Hash(BEGIN(nVersion), END(nNonce));
}
int64 GetBlockTime() const
{
return (int64)nTime;
}
void UpdateTime(const CBlockIndex* pindexPrev);
};
class CBlock : public CBlockHeader
{
public:
// network and disk
std::vector<CTransaction> vtx;
// memory only
mutable std::vector<uint256> vMerkleTree;
CBlock()
{
SetNull();
}
CBlock(const CBlockHeader &header)
{
SetNull();
*((CBlockHeader*)this) = header;
}
IMPLEMENT_SERIALIZE
(
READWRITE(*(CBlockHeader*)this);
READWRITE(vtx);
)
void SetNull()
{
CBlockHeader::SetNull();
vtx.clear();
vMerkleTree.clear();
}
uint256 GetPoWHash() const
{
uint256 thash;
scrypt_1024_1_1_256(BEGIN(nVersion), BEGIN(thash));
return thash;
}
CBlockHeader GetBlockHeader() const
{
CBlockHeader block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrevBlock;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
uint256 BuildMerkleTree() const
{
vMerkleTree.clear();
BOOST_FOREACH(const CTransaction& tx, vtx)
vMerkleTree.push_back(tx.GetHash());
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
for (int i = 0; i < nSize; i += 2)
{
int i2 = std::min(i+1, nSize-1);
vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
}
j += nSize;
}
return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
}
const uint256 &GetTxHash(unsigned int nIndex) const {
assert(vMerkleTree.size() > 0); // BuildMerkleTree must have been called first
assert(nIndex < vtx.size());
return vMerkleTree[nIndex];
}
std::vector<uint256> GetMerkleBranch(int nIndex) const
{
if (vMerkleTree.empty())
BuildMerkleTree();
std::vector<uint256> vMerkleBranch;
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
int i = std::min(nIndex^1, nSize-1);
vMerkleBranch.push_back(vMerkleTree[j+i]);
nIndex >>= 1;
j += nSize;
}
return vMerkleBranch;
}
static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
{
if (nIndex == -1)
return 0;
BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
{
if (nIndex & 1)
hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
else
hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
nIndex >>= 1;
}
return hash;
}
bool WriteToDisk(CDiskBlockPos &pos)
{
// Open history file to append
CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION);
if (!fileout)
return error("CBlock::WriteToDisk() : OpenBlockFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(*this);
fileout << FLATDATA(pchMessageStart) << nSize;
// Write block
long fileOutPos = ftell(fileout);
if (fileOutPos < 0)
return error("CBlock::WriteToDisk() : ftell failed");
pos.nPos = (unsigned int)fileOutPos;
fileout << *this;
// Flush stdio buffers and commit to disk before returning
fflush(fileout);
if (!IsInitialBlockDownload())
FileCommit(fileout);
return true;
}
bool ReadFromDisk(const CDiskBlockPos &pos)
{
SetNull();
// Open history file to read
CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
// Read block
try {
filein >> *this;
}
catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
// Check the header
if (!CheckProofOfWork(GetPoWHash(), nBits))
return error("CBlock::ReadFromDisk() : errors in block header");
return true;
}
void print() const
{
printf("CBlock(hash=%s, input=%s, PoW=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu")\n",
GetHash().ToString().c_str(),
HexStr(BEGIN(nVersion),BEGIN(nVersion)+80,false).c_str(),
GetPoWHash().ToString().c_str(),
nVersion,
hashPrevBlock.ToString().c_str(),
hashMerkleRoot.ToString().c_str(),
nTime, nBits, nNonce,
vtx.size());
for (unsigned int i = 0; i < vtx.size(); i++)
{
printf(" ");
vtx[i].print();
}
printf(" vMerkleTree: ");
for (unsigned int i = 0; i < vMerkleTree.size(); i++)
printf("%s ", vMerkleTree[i].ToString().c_str());
printf("\n");
}
/** Undo the effects of this block (with given index) on the UTXO set represented by coins.
* In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
* will be true if no problems were found. Otherwise, the return value will be false in case
* of problems. Note that in any case, coins may be modified. */
bool DisconnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool *pfClean = NULL);
// Apply the effects of this block (with given index) on the UTXO set represented by coins
bool ConnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool fJustCheck=false);
// Read a block from disk
bool ReadFromDisk(const CBlockIndex* pindex);
// Add this block to the block index, and if necessary, switch the active block chain to this
bool AddToBlockIndex(CValidationState &state, const CDiskBlockPos &pos);
// Context-independent validity checks
bool CheckBlock(CValidationState &state, bool fCheckPOW=true, bool fCheckMerkleRoot=true) const;
// Store block on disk
// if dbp is provided, the file is known to already reside on disk
bool AcceptBlock(CValidationState &state, CDiskBlockPos *dbp = NULL);
};
class CBlockFileInfo
{
public:
unsigned int nBlocks; // number of blocks stored in file
unsigned int nSize; // number of used bytes of block file
unsigned int nUndoSize; // number of used bytes in the undo file
unsigned int nHeightFirst; // lowest height of block in file
unsigned int nHeightLast; // highest height of block in file
uint64 nTimeFirst; // earliest time of block in file
uint64 nTimeLast; // latest time of block in file
IMPLEMENT_SERIALIZE(
READWRITE(VARINT(nBlocks));
READWRITE(VARINT(nSize));
READWRITE(VARINT(nUndoSize));
READWRITE(VARINT(nHeightFirst));
READWRITE(VARINT(nHeightLast));
READWRITE(VARINT(nTimeFirst));
READWRITE(VARINT(nTimeLast));
)
void SetNull() {
nBlocks = 0;
nSize = 0;
nUndoSize = 0;
nHeightFirst = 0;
nHeightLast = 0;
nTimeFirst = 0;
nTimeLast = 0;
}
CBlockFileInfo() {
SetNull();
}
std::string ToString() const {
return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst).c_str(), DateTimeStrFormat("%Y-%m-%d", nTimeLast).c_str());
}
// update statistics (does not update nSize)
void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) {
if (nBlocks==0 || nHeightFirst > nHeightIn)
nHeightFirst = nHeightIn;
if (nBlocks==0 || nTimeFirst > nTimeIn)
nTimeFirst = nTimeIn;
nBlocks++;
if (nHeightIn > nHeightFirst)
nHeightLast = nHeightIn;
if (nTimeIn > nTimeLast)
nTimeLast = nTimeIn;
}
};
extern CCriticalSection cs_LastBlockFile;
extern CBlockFileInfo infoLastBlockFile;
extern int nLastBlockFile;
enum BlockStatus {
BLOCK_VALID_UNKNOWN = 0,
BLOCK_VALID_HEADER = 1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future
BLOCK_VALID_TREE = 2, // parent found, difficulty matches, timestamp >= median previous, checkpoint
BLOCK_VALID_TRANSACTIONS = 3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root
BLOCK_VALID_CHAIN = 4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30
BLOCK_VALID_SCRIPTS = 5, // scripts/signatures ok
BLOCK_VALID_MASK = 7,
BLOCK_HAVE_DATA = 8, // full block available in blk*.dat
BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat
BLOCK_HAVE_MASK = 24,
BLOCK_FAILED_VALID = 32, // stage after last reached validness failed
BLOCK_FAILED_CHILD = 64, // descends from failed block
BLOCK_FAILED_MASK = 96
};
/** The block chain is a tree shaped structure starting with the
* genesis block at the root, with each block potentially having multiple
* candidates to be the next block. pprev and pnext link a path through the
* main/longest chain. A blockindex may have multiple pprev pointing back
* to it, but pnext will only point forward to the longest branch, or will
* be null if the block is not part of the longest chain.
*/
class CBlockIndex
{
public:
// pointer to the hash of the block, if any. memory is owned by this CBlockIndex
const uint256* phashBlock;
// pointer to the index of the predecessor of this block
CBlockIndex* pprev;
// (memory only) pointer to the index of the *active* successor of this block
CBlockIndex* pnext;
// height of the entry in the chain. The genesis block has height 0
int nHeight;
// Which # file this block is stored in (blk?????.dat)
int nFile;
// Byte offset within blk?????.dat where this block's data is stored
unsigned int nDataPos;
// Byte offset within rev?????.dat where this block's undo data is stored
unsigned int nUndoPos;
// (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block
uint256 nChainWork;
// Number of transactions in this block.
// Note: in a potential headers-first mode, this number cannot be relied upon
unsigned int nTx;
// (memory only) Number of transactions in the chain up to and including this block
unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030
// Verification status of this block. See enum BlockStatus
unsigned int nStatus;
// block header
int nVersion;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
CBlockIndex()
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nHeight = 0;
nFile = 0;
nDataPos = 0;
nUndoPos = 0;
nChainWork = 0;
nTx = 0;
nChainTx = 0;
nStatus = 0;
nVersion = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
}
CBlockIndex(CBlockHeader& block)
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nHeight = 0;
nFile = 0;
nDataPos = 0;
nUndoPos = 0;
nChainWork = 0;
nTx = 0;
nChainTx = 0;
nStatus = 0;
nVersion = block.nVersion;
hashMerkleRoot = block.hashMerkleRoot;
nTime = block.nTime;
nBits = block.nBits;
nNonce = block.nNonce;
}
CDiskBlockPos GetBlockPos() const {
CDiskBlockPos ret;
if (nStatus & BLOCK_HAVE_DATA) {
ret.nFile = nFile;
ret.nPos = nDataPos;
}
return ret;
}
CDiskBlockPos GetUndoPos() const {
CDiskBlockPos ret;
if (nStatus & BLOCK_HAVE_UNDO) {
ret.nFile = nFile;
ret.nPos = nUndoPos;
}
return ret;
}
CBlockHeader GetBlockHeader() const
{
CBlockHeader block;
block.nVersion = nVersion;
if (pprev)
block.hashPrevBlock = pprev->GetBlockHash();
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
uint256 GetBlockHash() const
{
return *phashBlock;
}
int64 GetBlockTime() const
{
return (int64)nTime;
}
CBigNum GetBlockWork() const
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
if (bnTarget <= 0)
return 0;
return (CBigNum(1)<<256) / (bnTarget+1);
}
bool IsInMainChain() const
{
return (pnext || this == pindexBest);
}
bool CheckIndex() const
{
/** Scrypt is used for block proof-of-work, but for purposes of performance the index internally uses sha256.
* This check was considered unneccessary given the other safeguards like the genesis and checkpoints. */
return true; // return CheckProofOfWork(GetBlockHash(), nBits);
}
enum { nMedianTimeSpan=11 };
int64 GetMedianTimePast() const
{
int64 pmedian[nMedianTimeSpan];
int64* pbegin = &pmedian[nMedianTimeSpan];
int64* pend = &pmedian[nMedianTimeSpan];
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
*(--pbegin) = pindex->GetBlockTime();
std::sort(pbegin, pend);
return pbegin[(pend - pbegin)/2];
}
int64 GetMedianTime() const
{
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan/2; i++)
{
if (!pindex->pnext)
return GetBlockTime();
pindex = pindex->pnext;
}
return pindex->GetMedianTimePast();
}
/**
* Returns true if there are nRequired or more blocks of minVersion or above
* in the last nToCheck blocks, starting at pstart and going backwards.
*/
static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
unsigned int nRequired, unsigned int nToCheck);
std::string ToString() const
{
return strprintf("CBlockIndex(pprev=%p, pnext=%p, nHeight=%d, merkle=%s, hashBlock=%s)",
pprev, pnext, nHeight,
hashMerkleRoot.ToString().c_str(),
GetBlockHash().ToString().c_str());
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
struct CBlockIndexWorkComparator
{
bool operator()(CBlockIndex *pa, CBlockIndex *pb) {
if (pa->nChainWork > pb->nChainWork) return false;
if (pa->nChainWork < pb->nChainWork) return true;
if (pa->GetBlockHash() < pb->GetBlockHash()) return false;
if (pa->GetBlockHash() > pb->GetBlockHash()) return true;
return false; // identical blocks
}
};
/** Used to marshal pointers into hashes for db storage. */
class CDiskBlockIndex : public CBlockIndex
{
public:
uint256 hashPrev;
CDiskBlockIndex() {
hashPrev = 0;
}
explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) {
hashPrev = (pprev ? pprev->GetBlockHash() : 0);
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(VARINT(nVersion));
READWRITE(VARINT(nHeight));
READWRITE(VARINT(nStatus));
READWRITE(VARINT(nTx));
if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO))
READWRITE(VARINT(nFile));
if (nStatus & BLOCK_HAVE_DATA)
READWRITE(VARINT(nDataPos));
if (nStatus & BLOCK_HAVE_UNDO)
READWRITE(VARINT(nUndoPos));
// block header
READWRITE(this->nVersion);
READWRITE(hashPrev);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
)
uint256 GetBlockHash() const
{
CBlockHeader block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrev;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block.GetHash();
}
std::string ToString() const
{
std::string str = "CDiskBlockIndex(";
str += CBlockIndex::ToString();
str += strprintf("\n hashBlock=%s, hashPrev=%s)",
GetBlockHash().ToString().c_str(),
hashPrev.ToString().c_str());
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** Capture information about block/transaction validation */
class CValidationState {
private:
enum mode_state {
MODE_VALID, // everything ok
MODE_INVALID, // network rule violation (DoS value may be set)
MODE_ERROR, // run-time error
} mode;
int nDoS;
bool corruptionPossible;
public:
CValidationState() : mode(MODE_VALID), nDoS(0), corruptionPossible(false) {}
bool DoS(int level, bool ret = false, bool corruptionIn = false) {
if (mode == MODE_ERROR)
return ret;
nDoS += level;
mode = MODE_INVALID;
corruptionPossible = corruptionIn;
return ret;
}
bool Invalid(bool ret = false) {
return DoS(0, ret);
}
bool Error() {
mode = MODE_ERROR;
return false;
}
bool Abort(const std::string &msg) {
AbortNode(msg);
return Error();
}
bool IsValid() {
return mode == MODE_VALID;
}
bool IsInvalid() {
return mode == MODE_INVALID;
}
bool IsError() {
return mode == MODE_ERROR;
}
bool IsInvalid(int &nDoSOut) {
if (IsInvalid()) {
nDoSOut = nDoS;
return true;
}
return false;
}
bool CorruptionPossible() {
return corruptionPossible;
}
};
/** Describes a place in the block chain to another node such that if the
* other node doesn't have the same branch, it can find a recent common trunk.
* The further back it is, the further before the fork it may be.
*/
class CBlockLocator
{
protected:
std::vector<uint256> vHave;
public:
CBlockLocator()
{
}
explicit CBlockLocator(const CBlockIndex* pindex)
{
Set(pindex);
}
explicit CBlockLocator(uint256 hashBlock)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end())
Set((*mi).second);
}
CBlockLocator(const std::vector<uint256>& vHaveIn)
{
vHave = vHaveIn;
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vHave);
)
void SetNull()
{
vHave.clear();
}
bool IsNull()
{
return vHave.empty();
}
void Set(const CBlockIndex* pindex)
{
vHave.clear();
int nStep = 1;
while (pindex)
{
vHave.push_back(pindex->GetBlockHash());
// Exponentially larger steps back
for (int i = 0; pindex && i < nStep; i++)
pindex = pindex->pprev;
if (vHave.size() > 10)
nStep *= 2;
}
vHave.push_back(hashGenesisBlock);
}
int GetDistanceBack()
{
// Retrace how far back it was in the sender's branch
int nDistance = 0;
int nStep = 1;
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return nDistance;
}
nDistance += nStep;
if (nDistance > 10)
nStep *= 2;
}
return nDistance;
}
CBlockIndex* GetBlockIndex()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return pindex;
}
}
return pindexGenesisBlock;
}
uint256 GetBlockHash()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return hash;
}
}
return hashGenesisBlock;
}
int GetHeight()
{
CBlockIndex* pindex = GetBlockIndex();
if (!pindex)
return 0;
return pindex->nHeight;
}
};
class CTxMemPool
{
public:
mutable CCriticalSection cs;
std::map<uint256, CTransaction> mapTx;
std::map<COutPoint, CInPoint> mapNextTx;
bool accept(CValidationState &state, CTransaction &tx, bool fCheckInputs, bool fLimitFree, bool* pfMissingInputs, bool fRejectInsaneFee = false);
bool addUnchecked(const uint256& hash, const CTransaction &tx);
bool remove(const CTransaction &tx, bool fRecursive = false);
bool removeConflicts(const CTransaction &tx);
void clear();
void queryHashes(std::vector<uint256>& vtxid);
void pruneSpent(const uint256& hash, CCoins &coins);
unsigned long size()
{
LOCK(cs);
return mapTx.size();
}
bool exists(uint256 hash)
{
return (mapTx.count(hash) != 0);
}
CTransaction& lookup(uint256 hash)
{
return mapTx[hash];
}
};
extern CTxMemPool mempool;
struct CCoinsStats
{
int nHeight;
uint256 hashBlock;
uint64 nTransactions;
uint64 nTransactionOutputs;
uint64 nSerializedSize;
uint256 hashSerialized;
int64 nTotalAmount;
CCoinsStats() : nHeight(0), hashBlock(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), hashSerialized(0), nTotalAmount(0) {}
};
/** Abstract view on the open txout dataset. */
class CCoinsView
{
public:
// Retrieve the CCoins (unspent transaction outputs) for a given txid
virtual bool GetCoins(const uint256 &txid, CCoins &coins);
// Modify the CCoins for a given txid
virtual bool SetCoins(const uint256 &txid, const CCoins &coins);
// Just check whether we have data for a given txid.
// This may (but cannot always) return true for fully spent transactions
virtual bool HaveCoins(const uint256 &txid);
// Retrieve the block index whose state this CCoinsView currently represents
virtual CBlockIndex *GetBestBlock();
// Modify the currently active block index
virtual bool SetBestBlock(CBlockIndex *pindex);
// Do a bulk modification (multiple SetCoins + one SetBestBlock)
virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
// Calculate statistics about the unspent transaction output set
virtual bool GetStats(CCoinsStats &stats);
// As we use CCoinsViews polymorphically, have a virtual destructor
virtual ~CCoinsView() {}
};
/** CCoinsView backed by another CCoinsView */
class CCoinsViewBacked : public CCoinsView
{
protected:
CCoinsView *base;
public:
CCoinsViewBacked(CCoinsView &viewIn);
bool GetCoins(const uint256 &txid, CCoins &coins);
bool SetCoins(const uint256 &txid, const CCoins &coins);
bool HaveCoins(const uint256 &txid);
CBlockIndex *GetBestBlock();
bool SetBestBlock(CBlockIndex *pindex);
void SetBackend(CCoinsView &viewIn);
bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
bool GetStats(CCoinsStats &stats);
};
/** CCoinsView that adds a memory cache for transactions to another CCoinsView */
class CCoinsViewCache : public CCoinsViewBacked
{
protected:
CBlockIndex *pindexTip;
std::map<uint256,CCoins> cacheCoins;
public:
CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false);
// Standard CCoinsView methods
bool GetCoins(const uint256 &txid, CCoins &coins);
bool SetCoins(const uint256 &txid, const CCoins &coins);
bool HaveCoins(const uint256 &txid);
CBlockIndex *GetBestBlock();
bool SetBestBlock(CBlockIndex *pindex);
bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex);
// Return a modifiable reference to a CCoins. Check HaveCoins first.
// Many methods explicitly require a CCoinsViewCache because of this method, to reduce
// copying.
CCoins &GetCoins(const uint256 &txid);
// Push the modifications applied to this cache to its base.
// Failure to call this method before destruction will cause the changes to be forgotten.
bool Flush();
// Calculate the size of the cache (in number of transactions)
unsigned int GetCacheSize();
private:
std::map<uint256,CCoins>::iterator FetchCoins(const uint256 &txid);
};
/** CCoinsView that brings transactions from a memorypool into view.
It does not check for spendings by memory pool transactions. */
class CCoinsViewMemPool : public CCoinsViewBacked
{
protected:
CTxMemPool &mempool;
public:
CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn);
bool GetCoins(const uint256 &txid, CCoins &coins);
bool HaveCoins(const uint256 &txid);
};
/** Global variable that points to the active CCoinsView (protected by cs_main) */
extern CCoinsViewCache *pcoinsTip;
/** Global variable that points to the active block tree (protected by cs_main) */
extern CBlockTreeDB *pblocktree;
struct CBlockTemplate
{
CBlock block;
std::vector<int64_t> vTxFees;
std::vector<int64_t> vTxSigOps;
};
#if defined(_M_IX86) || defined(__i386__) || defined(__i386) || defined(_M_X64) || defined(__x86_64__) || defined(_M_AMD64)
extern unsigned int cpuid_edx;
#endif
/** Used to relay blocks as header + vector<merkle branch>
* to filtered nodes.
*/
class CMerkleBlock
{
public:
// Public only for unit testing
CBlockHeader header;
CPartialMerkleTree txn;
public:
// Public only for unit testing and relay testing
// (not relayed)
std::vector<std::pair<unsigned int, uint256> > vMatchedTxn;
// Create from a CBlock, filtering transactions according to filter
// Note that this will call IsRelevantAndUpdate on the filter for each transaction,
// thus the filter will likely be modified.
CMerkleBlock(const CBlock& block, CBloomFilter& filter);
IMPLEMENT_SERIALIZE
(
READWRITE(header);
READWRITE(txn);
)
};
#endif
| [
"gyun0526@gmail.com"
] | gyun0526@gmail.com |
55fe439f98391de265ef74844cdb4454ac346bf1 | 1b0818c047ac532e38f153497de6ebcebc596359 | /src/build_tree.cpp | 30d403dc89e380e2a1f1ee3ef4eca91172fab696 | [] | no_license | peipei2015/3d_model | fbe5f7f0df736b09263b0816eebf4908ae18d4c1 | 0e4a04d6e647b395b7dc3939262d5c2609a59598 | refs/heads/master | 2021-01-20T20:36:40.304043 | 2016-06-24T11:31:33 | 2016-06-24T11:31:33 | 61,878,023 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,807 | cpp | #include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/console/parse.h>
#include <pcl/console/print.h>
#include <pcl/io/pcd_io.h>
#include <boost/filesystem.hpp>
#include <flann/flann.h>
#include <flann/io/hdf5.h>
#include <fstream>
typedef std::pair<std::string, std::vector<float> > vfh_model;
/** \brief Loads an n-D histogram file as a VFH signature
* \param path the input file name
* \param vfh the resultant VFH model
*/
bool loadHist (const boost::filesystem::path &path, vfh_model &vfh)
{
int vfh_idx;
// Load the file as a PCD
try
{
pcl::PCLPointCloud2 cloud;
int version;
Eigen::Vector4f origin;
Eigen::Quaternionf orientation;
pcl::PCDReader r;
int type; unsigned int idx;
r.readHeader (path.string (), cloud, origin, orientation, version, type, idx);
vfh_idx = pcl::getFieldIndex (cloud, "vfh");
if (vfh_idx == -1)
return (false);
if ((int)cloud.width * cloud.height != 1)
return (false);
}
catch (const pcl::InvalidConversionException&)
{
return (false);
}
// Treat the VFH signature as a single Point Cloud
pcl::PointCloud <pcl::VFHSignature308> point;
pcl::io::loadPCDFile (path.string (), point);
vfh.second.resize (308);
std::vector <pcl::PCLPointField> fields;
pcl::getFieldIndex (point, "vfh", fields);
for (size_t i = 0; i < fields[vfh_idx].count; ++i)
{
vfh.second[i] = point.points[0].histogram[i];
}
vfh.first = path.string ();
return (true);
}
/** \brief Load a set of VFH features that will act as the model (training data)
* \param argc the number of arguments (pass from main ())
* \param argv the actual command line arguments (pass from main ())
* \param extension the file extension containing the VFH features
* \param models the resultant vector of histogram models
*/
void loadFeatureModels (const boost::filesystem::path &base_dir, const std::string &extension,
std::vector<vfh_model> &models)
{
if (!boost::filesystem::exists (base_dir) && !boost::filesystem::is_directory (base_dir))
return;
for (boost::filesystem::directory_iterator it (base_dir); it != boost::filesystem::directory_iterator (); ++it)
{
if (boost::filesystem::is_directory (it->status ()))
{
std::stringstream ss;
ss << it->path ();
pcl::console::print_highlight ("Loading %s (%lu models loaded so far).\n", ss.str ().c_str (), (unsigned long)models.size ());
loadFeatureModels (it->path (), extension, models);
}
if (boost::filesystem::is_regular_file (it->status ()) && boost::filesystem::extension (it->path ()) == extension)
{
vfh_model m;
if (loadHist (base_dir / it->path ().filename (), m))
models.push_back (m);
}
}
}
int main (int argc, char** argv)
{
if (argc < 2)
{
PCL_ERROR ("Need at least two parameters! Syntax is: %s [model_directory] [options]\n", argv[0]);
return (-1);
}
std::string extension (".pcd");
transform (extension.begin (), extension.end (), extension.begin (), (int(*)(int))tolower);
std::string kdtree_idx_file_name = "kdtree.idx";
std::string training_data_h5_file_name = "training_data.h5";
std::string training_data_list_file_name = "training_data.list";
std::vector<vfh_model> models;
// Load the model histograms
loadFeatureModels (argv[1], extension, models);
pcl::console::print_highlight ("Loaded %d VFH models. Creating training data %s/%s.\n",
(int)models.size (), training_data_h5_file_name.c_str (), training_data_list_file_name.c_str ());
// Convert data into FLANN format
flann::Matrix<float> data (new float[models.size () * models[0].second.size ()], models.size (), models[0].second.size ());
for (size_t i = 0; i < data.rows; ++i)
for (size_t j = 0; j < data.cols; ++j)
data[i][j] = models[i].second[j];
// Save data to disk (list of models)
flann::save_to_file (data, training_data_h5_file_name, "training_data");
std::ofstream fs;
fs.open (training_data_list_file_name.c_str ());
for (size_t i = 0; i < models.size (); ++i)
fs << models[i].first << "\n";
fs.close ();
// Build the tree index and save it to disk
pcl::console::print_error ("Building the kdtree index (%s) for %d elements...\n", kdtree_idx_file_name.c_str (), (int)data.rows);
flann::Index<flann::ChiSquareDistance<float> > index (data, flann::LinearIndexParams ());
//flann::Index<flann::ChiSquareDistance<float> > index (data, flann::KDTreeIndexParams (4));
index.buildIndex ();
index.save (kdtree_idx_file_name);
delete[] data.ptr ();
return (0);
}
| [
"1607458232@qq.com"
] | 1607458232@qq.com |
bdcb896691484a4220377546bbc51070c2c22a85 | 4c23be1a0ca76f68e7146f7d098e26c2bbfb2650 | /ic8h18/0.0045/IC3H7COC3H6-I | a7b7e569448bbb037bcb48e3fdfa5118f9cf424a | [] | no_license | labsandy/OpenFOAM_workspace | a74b473903ddbd34b31dc93917e3719bc051e379 | 6e0193ad9dabd613acf40d6b3ec4c0536c90aed4 | refs/heads/master | 2022-02-25T02:36:04.164324 | 2019-08-23T02:27:16 | 2019-08-23T02:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 846 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.0045";
object IC3H7COC3H6-I;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField uniform 9.92881e-12;
boundaryField
{
boundary
{
type empty;
}
}
// ************************************************************************* //
| [
"jfeatherstone123@gmail.com"
] | jfeatherstone123@gmail.com | |
db605cc7c5b71033d40eca34b9f241b0e0a0c3f6 | 38c10c01007624cd2056884f25e0d6ab85442194 | /chrome/browser/extensions/api/sync_file_system/sync_file_system_api.cc | 0b9aafc547c3634fae05f95eb0a23642f37a44ab | [
"BSD-3-Clause"
] | permissive | zenoalbisser/chromium | 6ecf37b6c030c84f1b26282bc4ef95769c62a9b2 | e71f21b9b4b9b839f5093301974a45545dad2691 | refs/heads/master | 2022-12-25T14:23:18.568575 | 2016-07-14T21:49:52 | 2016-07-23T08:02:51 | 63,980,627 | 0 | 2 | BSD-3-Clause | 2022-12-12T12:43:41 | 2016-07-22T20:14:04 | null | UTF-8 | C++ | false | false | 13,764 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/sync_file_system/sync_file_system_api.h"
#include <string>
#include <utility>
#include "base/bind.h"
#include "base/logging.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/extensions/api/sync_file_system/extension_sync_event_observer.h"
#include "chrome/browser/extensions/api/sync_file_system/sync_file_system_api_helpers.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync_file_system/sync_file_status.h"
#include "chrome/browser/sync_file_system/sync_file_system_service.h"
#include "chrome/browser/sync_file_system/sync_file_system_service_factory.h"
#include "chrome/common/extensions/api/sync_file_system.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/common/content_client.h"
#include "storage/browser/fileapi/file_system_context.h"
#include "storage/browser/fileapi/file_system_url.h"
#include "storage/browser/quota/quota_manager.h"
#include "storage/common/fileapi/file_system_types.h"
#include "storage/common/fileapi/file_system_util.h"
using content::BrowserContext;
using content::BrowserThread;
using sync_file_system::ConflictResolutionPolicy;
using sync_file_system::SyncFileStatus;
using sync_file_system::SyncFileSystemServiceFactory;
using sync_file_system::SyncStatusCode;
namespace extensions {
namespace {
// Error messages.
const char kErrorMessage[] = "%s (error code: %d).";
const char kUnsupportedConflictResolutionPolicy[] =
"Policy %s is not supported.";
sync_file_system::SyncFileSystemService* GetSyncFileSystemService(
Profile* profile) {
sync_file_system::SyncFileSystemService* service =
SyncFileSystemServiceFactory::GetForProfile(profile);
if (!service)
return nullptr;
ExtensionSyncEventObserver* observer =
ExtensionSyncEventObserver::GetFactoryInstance()->Get(profile);
if (!observer)
return nullptr;
observer->InitializeForService(service);
return service;
}
std::string ErrorToString(SyncStatusCode code) {
return base::StringPrintf(
kErrorMessage,
sync_file_system::SyncStatusCodeToString(code),
static_cast<int>(code));
}
} // namespace
bool SyncFileSystemDeleteFileSystemFunction::RunAsync() {
std::string url;
EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &url));
scoped_refptr<storage::FileSystemContext> file_system_context =
BrowserContext::GetStoragePartition(
GetProfile(), render_frame_host()->GetSiteInstance())
->GetFileSystemContext();
storage::FileSystemURL file_system_url(
file_system_context->CrackURL(GURL(url)));
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
Bind(&storage::FileSystemContext::DeleteFileSystem,
file_system_context,
source_url().GetOrigin(),
file_system_url.type(),
Bind(&SyncFileSystemDeleteFileSystemFunction::DidDeleteFileSystem,
this)));
return true;
}
void SyncFileSystemDeleteFileSystemFunction::DidDeleteFileSystem(
base::File::Error error) {
// Repost to switch from IO thread to UI thread for SendResponse().
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
Bind(&SyncFileSystemDeleteFileSystemFunction::DidDeleteFileSystem, this,
error));
return;
}
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (error != base::File::FILE_OK) {
error_ = ErrorToString(sync_file_system::FileErrorToSyncStatusCode(error));
SetResult(new base::FundamentalValue(false));
SendResponse(false);
return;
}
SetResult(new base::FundamentalValue(true));
SendResponse(true);
}
bool SyncFileSystemRequestFileSystemFunction::RunAsync() {
// SyncFileSystem initialization is done in OpenFileSystem below, but we call
// GetSyncFileSystemService here too to initialize sync event observer for
// extensions API.
if (!GetSyncFileSystemService(GetProfile()))
return false;
// Initializes sync context for this extension and continue to open
// a new file system.
BrowserThread::PostTask(BrowserThread::IO,
FROM_HERE,
Bind(&storage::FileSystemContext::OpenFileSystem,
GetFileSystemContext(),
source_url().GetOrigin(),
storage::kFileSystemTypeSyncable,
storage::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT,
base::Bind(&self::DidOpenFileSystem, this)));
return true;
}
storage::FileSystemContext*
SyncFileSystemRequestFileSystemFunction::GetFileSystemContext() {
DCHECK(render_frame_host());
return BrowserContext::GetStoragePartition(
GetProfile(), render_frame_host()->GetSiteInstance())
->GetFileSystemContext();
}
void SyncFileSystemRequestFileSystemFunction::DidOpenFileSystem(
const GURL& root_url,
const std::string& file_system_name,
base::File::Error error) {
// Repost to switch from IO thread to UI thread for SendResponse().
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
Bind(&SyncFileSystemRequestFileSystemFunction::DidOpenFileSystem,
this, root_url, file_system_name, error));
return;
}
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (error != base::File::FILE_OK) {
error_ = ErrorToString(sync_file_system::FileErrorToSyncStatusCode(error));
SendResponse(false);
return;
}
base::DictionaryValue* dict = new base::DictionaryValue();
SetResult(dict);
dict->SetString("name", file_system_name);
dict->SetString("root", root_url.spec());
SendResponse(true);
}
bool SyncFileSystemGetFileStatusFunction::RunAsync() {
std::string url;
EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &url));
scoped_refptr<storage::FileSystemContext> file_system_context =
BrowserContext::GetStoragePartition(
GetProfile(), render_frame_host()->GetSiteInstance())
->GetFileSystemContext();
storage::FileSystemURL file_system_url(
file_system_context->CrackURL(GURL(url)));
sync_file_system::SyncFileSystemService* sync_file_system_service =
GetSyncFileSystemService(GetProfile());
if (!sync_file_system_service)
return false;
sync_file_system_service->GetFileSyncStatus(
file_system_url,
Bind(&SyncFileSystemGetFileStatusFunction::DidGetFileStatus, this));
return true;
}
void SyncFileSystemGetFileStatusFunction::DidGetFileStatus(
const SyncStatusCode sync_status_code,
const SyncFileStatus sync_file_status) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (sync_status_code != sync_file_system::SYNC_STATUS_OK) {
error_ = ErrorToString(sync_status_code);
SendResponse(false);
return;
}
// Convert from C++ to JavaScript enum.
results_ = api::sync_file_system::GetFileStatus::Results::Create(
SyncFileStatusToExtensionEnum(sync_file_status));
SendResponse(true);
}
SyncFileSystemGetFileStatusesFunction::SyncFileSystemGetFileStatusesFunction() {
}
SyncFileSystemGetFileStatusesFunction::~SyncFileSystemGetFileStatusesFunction(
) {}
bool SyncFileSystemGetFileStatusesFunction::RunAsync() {
// All FileEntries converted into array of URL Strings in JS custom bindings.
base::ListValue* file_entry_urls = NULL;
EXTENSION_FUNCTION_VALIDATE(args_->GetList(0, &file_entry_urls));
scoped_refptr<storage::FileSystemContext> file_system_context =
BrowserContext::GetStoragePartition(
GetProfile(), render_frame_host()->GetSiteInstance())
->GetFileSystemContext();
// Map each file path->SyncFileStatus in the callback map.
// TODO(calvinlo): Overload GetFileSyncStatus to take in URL array.
num_expected_results_ = file_entry_urls->GetSize();
num_results_received_ = 0;
file_sync_statuses_.clear();
sync_file_system::SyncFileSystemService* sync_file_system_service =
GetSyncFileSystemService(GetProfile());
if (!sync_file_system_service)
return false;
for (unsigned int i = 0; i < num_expected_results_; i++) {
std::string url;
file_entry_urls->GetString(i, &url);
storage::FileSystemURL file_system_url(
file_system_context->CrackURL(GURL(url)));
sync_file_system_service->GetFileSyncStatus(
file_system_url,
Bind(&SyncFileSystemGetFileStatusesFunction::DidGetFileStatus,
this, file_system_url));
}
return true;
}
void SyncFileSystemGetFileStatusesFunction::DidGetFileStatus(
const storage::FileSystemURL& file_system_url,
SyncStatusCode sync_status_code,
SyncFileStatus sync_file_status) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
num_results_received_++;
DCHECK_LE(num_results_received_, num_expected_results_);
file_sync_statuses_[file_system_url] =
std::make_pair(sync_status_code, sync_file_status);
// Keep mapping file statuses until all of them have been received.
// TODO(calvinlo): Get rid of this check when batch version of
// GetFileSyncStatus(GURL urls[]); is added.
if (num_results_received_ < num_expected_results_)
return;
// All results received. Dump array of statuses into extension enum values.
// Note that the enum types need to be set as strings manually as the
// autogenerated Results::Create function thinks the enum values should be
// returned as int values.
base::ListValue* status_array = new base::ListValue();
for (URLToStatusMap::iterator it = file_sync_statuses_.begin();
it != file_sync_statuses_.end(); ++it) {
base::DictionaryValue* dict = new base::DictionaryValue();
status_array->Append(dict);
storage::FileSystemURL url = it->first;
SyncStatusCode file_error = it->second.first;
api::sync_file_system::FileStatus file_status =
SyncFileStatusToExtensionEnum(it->second.second);
dict->Set("entry", CreateDictionaryValueForFileSystemEntry(
url, sync_file_system::SYNC_FILE_TYPE_FILE));
dict->SetString("status", ToString(file_status));
if (file_error == sync_file_system::SYNC_STATUS_OK)
continue;
dict->SetString("error", ErrorToString(file_error));
}
SetResult(status_array);
SendResponse(true);
}
bool SyncFileSystemGetUsageAndQuotaFunction::RunAsync() {
std::string url;
EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &url));
scoped_refptr<storage::FileSystemContext> file_system_context =
BrowserContext::GetStoragePartition(
GetProfile(), render_frame_host()->GetSiteInstance())
->GetFileSystemContext();
storage::FileSystemURL file_system_url(
file_system_context->CrackURL(GURL(url)));
scoped_refptr<storage::QuotaManager> quota_manager =
BrowserContext::GetStoragePartition(
GetProfile(), render_frame_host()->GetSiteInstance())
->GetQuotaManager();
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
Bind(&storage::QuotaManager::GetUsageAndQuotaForWebApps,
quota_manager,
source_url().GetOrigin(),
storage::FileSystemTypeToQuotaStorageType(file_system_url.type()),
Bind(&SyncFileSystemGetUsageAndQuotaFunction::DidGetUsageAndQuota,
this)));
return true;
}
void SyncFileSystemGetUsageAndQuotaFunction::DidGetUsageAndQuota(
storage::QuotaStatusCode status,
int64 usage,
int64 quota) {
// Repost to switch from IO thread to UI thread for SendResponse().
if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
Bind(&SyncFileSystemGetUsageAndQuotaFunction::DidGetUsageAndQuota, this,
status, usage, quota));
return;
}
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (status != storage::kQuotaStatusOk) {
error_ = QuotaStatusCodeToString(status);
SendResponse(false);
return;
}
api::sync_file_system::StorageInfo info;
info.usage_bytes = usage;
info.quota_bytes = quota;
results_ = api::sync_file_system::GetUsageAndQuota::Results::Create(info);
SendResponse(true);
}
bool SyncFileSystemSetConflictResolutionPolicyFunction::RunSync() {
std::string policy_string;
EXTENSION_FUNCTION_VALIDATE(args_->GetString(0, &policy_string));
ConflictResolutionPolicy policy = ExtensionEnumToConflictResolutionPolicy(
api::sync_file_system::ParseConflictResolutionPolicy(policy_string));
if (policy != sync_file_system::CONFLICT_RESOLUTION_POLICY_LAST_WRITE_WIN) {
SetError(base::StringPrintf(kUnsupportedConflictResolutionPolicy,
policy_string.c_str()));
return false;
}
return true;
}
bool SyncFileSystemGetConflictResolutionPolicyFunction::RunSync() {
SetResult(new base::StringValue(
api::sync_file_system::ToString(
api::sync_file_system::CONFLICT_RESOLUTION_POLICY_LAST_WRITE_WIN)));
return true;
}
bool SyncFileSystemGetServiceStatusFunction::RunSync() {
sync_file_system::SyncFileSystemService* service =
GetSyncFileSystemService(GetProfile());
if (!service)
return false;
results_ = api::sync_file_system::GetServiceStatus::Results::Create(
SyncServiceStateToExtensionEnum(service->GetSyncServiceState()));
return true;
}
} // namespace extensions
| [
"zeno.albisser@hemispherian.com"
] | zeno.albisser@hemispherian.com |
5834e2a9503c0334f18f0a723119cbc5a6b7abf0 | 12efddb38fd5bd1c2b2b3bb1b672714b694d5602 | /lualib/lualib_sharedmemory.cpp | d6fd98f2a39527474253ba79e1e322e44740cdc0 | [] | no_license | chenxp-github/SmallToolsV2 | 884d61200f556379551477030aa06c64593ce9d4 | 1a8aa863d0bc3744d376284ace85c7503b871f45 | refs/heads/master | 2022-06-01T05:19:25.417439 | 2022-04-30T05:31:53 | 2022-04-30T05:31:53 | 210,530,450 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,263 | cpp | #include "lualib_sharedmemory.h"
#include "mem_tool.h"
#include "sys_log.h"
#include "lualib_stream.h"
LUA_IS_VALID_USER_DATA_FUNC(CSharedMemory,sharedmemory)
LUA_GET_OBJ_FROM_USER_DATA_FUNC(CSharedMemory,sharedmemory)
LUA_NEW_USER_DATA_FUNC(CSharedMemory,sharedmemory,SHAREDMEMORY)
LUA_GC_FUNC(CSharedMemory,sharedmemory)
LUA_IS_SAME_FUNC(CSharedMemory,sharedmemory)
LUA_TO_STRING_FUNC(CSharedMemory,sharedmemory)
bool is_sharedmemory(lua_State *L, int idx)
{
const char* ud_names[] = {
LUA_USERDATA_SHAREDMEMORY,
};
lua_userdata *ud = NULL;
for(size_t i = 0; i < sizeof(ud_names)/sizeof(ud_names[0]); i++)
{
ud = (lua_userdata*)luaL_testudata(L, idx, ud_names[i]);
if(ud)break;
}
return sharedmemory_is_userdata_valid(ud);
}
/****************************************************/
static status_t sharedmemory_new(lua_State *L)
{
CSharedMemory *psharedmemory;
NEW(psharedmemory,CSharedMemory);
psharedmemory->Init();
sharedmemory_new_userdata(L,psharedmemory,0);
return 1;
}
static status_t sharedmemory_zero(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
status_t ret0 = psharedmemory->Zero();
lua_pushboolean(L,ret0);
return 1;
}
static status_t sharedmemory_getsize(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
int ret0 = psharedmemory->GetSize();
lua_pushinteger(L,ret0);
return 1;
}
static status_t sharedmemory_openreadwrite(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
status_t ret0 = psharedmemory->OpenReadWrite();
lua_pushboolean(L,ret0);
return 1;
}
static status_t sharedmemory_openreadonly(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
status_t ret0 = psharedmemory->OpenReadOnly();
lua_pushboolean(L,ret0);
return 1;
}
static status_t sharedmemory_opencreate(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
int size = (int)lua_tointeger(L,2);
status_t ret0 = psharedmemory->OpenCreate(size);
lua_pushboolean(L,ret0);
return 1;
}
static status_t sharedmemory_setname(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
int name = (int)lua_tointeger(L,2);
status_t ret0 = psharedmemory->SetName(name);
lua_pushboolean(L,ret0);
return 1;
}
static status_t sharedmemory_unlink(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
status_t ret0 = psharedmemory->Unlink();
lua_pushboolean(L,ret0);
return 1;
}
static status_t sharedmemory_close(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
status_t ret0 = psharedmemory->Close();
lua_pushboolean(L,ret0);
return 1;
}
static status_t sharedmemory_destroy(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
status_t ret0 = psharedmemory->Destroy();
lua_pushboolean(L,ret0);
return 1;
}
static status_t sharedmemory_stream(lua_State *L)
{
CSharedMemory *psharedmemory = get_sharedmemory(L,1);
ASSERT(psharedmemory);
if(psharedmemory->GetData() == NULL)
return 0;
if(psharedmemory->GetSize() == 0)
return 0;
CStream *stream;
NEW(stream,CStream);
stream->Init();
stream->SetRawBuf(psharedmemory->GetData(),psharedmemory->GetSize(),false);
stream_new_userdata(L,stream,0);
return 1;
}
/****************************************************/
static const luaL_Reg sharedmemory_funcs_[] = {
{"__gc",sharedmemory_gc_},
{"__tostring",sharedmemory_tostring_},
{"__is_same",sharedmemory_issame_},
{"new",sharedmemory_new},
{"Zero",sharedmemory_zero},
{"GetSize",sharedmemory_getsize},
{"OpenReadWrite",sharedmemory_openreadwrite},
{"OpenReadOnly",sharedmemory_openreadonly},
{"OpenCreate",sharedmemory_opencreate},
{"SetName",sharedmemory_setname},
{"Unlink",sharedmemory_unlink},
{"Close",sharedmemory_close},
{"Destroy",sharedmemory_destroy},
{"Stream",sharedmemory_stream},
{NULL,NULL},
};
const luaL_Reg* get_sharedmemory_funcs()
{
return sharedmemory_funcs_;
}
static int luaL_register_sharedmemory(lua_State *L)
{
static luaL_Reg _sharedmemory_funcs_[MAX_LUA_FUNCS];
int _index = 0;
CLuaVm::CombineLuaFuncTable(_sharedmemory_funcs_,&_index,get_sharedmemory_funcs(),true);
luaL_newmetatable(L, LUA_USERDATA_SHAREDMEMORY);
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_setfuncs(L,_sharedmemory_funcs_,0);
lua_pop(L, 1);
luaL_newlib(L,_sharedmemory_funcs_);
return 1;
}
int luaopen_sharedmemory(lua_State *L)
{
luaL_requiref(L, "SharedMemory",luaL_register_sharedmemory,1);
lua_pop(L, 1);
return 0;
}
| [
"xiangpeng_chen@126.com"
] | xiangpeng_chen@126.com |
782c0973bbac9ce229c8cacca512e2321b4200c0 | 111d82bef126e3a6fb86c0dc59ded74705932213 | /src/marker.cpp | 682ad08fe2fcfa94f6f458d599e567f56ea5d011 | [] | no_license | Mekanikles/pyzzlix-c | 67919cdd0e1f1b11993aa7b26c76556b7f7a5269 | 8db46d88930a5987286f81ed7114b71dd948a520 | refs/heads/master | 2021-03-12T20:14:46.095897 | 2011-01-18T09:51:34 | 2011-01-18T09:51:34 | 1,109,821 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | cpp | #include "marker.h"
#include "animation.h"
Marker::Marker()
{
this->setAnimation(new Animation("marker", 32, 32));
this->boardx = 0;
this->boardy = 0;
//this->movesound = Resources().getSound("markermove");
//self.turnsound = Resources().getSound("markerturn")
//self.failsound = Resources().getSound("markerfail")
this->center = Point(16.0f, 16.0f);
}
| [
"joel@crunchbang.(none)"
] | joel@crunchbang.(none) |
034367cb1dc13be1e08fd1780d3092a5818127de | b9c8edc82ab483ba0f0f3e94ebad9409829da73f | /Vulkan_Win32/src/renderer/modelbuffer.h | 77ef132265aa3aef063eefad7f22fea7faff04f6 | [] | no_license | vectorlist/Vulkan_Application | 27b4e2161bfc91827d3e3a94dffa3891d5406357 | f24e6b344c8b76fff7c363f7241aeefc26588536 | refs/heads/master | 2021-01-12T03:18:06.729988 | 2017-01-12T01:04:55 | 2017-01-12T01:04:55 | 78,179,141 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,370 | h | #pragma once
#include <renderer.h>
class ModelBuffer : public Renderer
{
public:
ModelBuffer(Window* window);
virtual~ModelBuffer();
void buildProcedural() VK_OVERRIDE;
void buildPipeline() VK_OVERRIDE;
void buildFrameBuffers() VK_OVERRIDE;
void buildCommandPool() VK_OVERRIDE;
void buildCommandBuffers() VK_OVERRIDE;
void buildSemaphores() VK_OVERRIDE;
//additional
void buildVertexBuffers();
void buildIndiceBuffers();
void render() VK_OVERRIDE;
/*MODEL*/
void buildModel(const std::string &filename);
/*DEPTH STENCIL*/
void buildDeapthStencil();
VDeleter<VkImage> m_depth_image{ m_device, vkDestroyImage };
VDeleter<VkImageView> m_depth_image_view{ m_device, vkDestroyImageView };
VDeleter<VkDeviceMemory> m_depth_image_memory{ m_device,vkFreeMemory };
/*TEXTURE BUFFER*/
void buildTextureImage();
void buildTextureImageView();
void buildTextureSampler();
VDeleter<VkImage> m_texture_image{ m_device, vkDestroyImage };
VDeleter<VkDeviceMemory> m_texture_image_memory{ m_device, vkFreeMemory };
VDeleter<VkImageView> m_texture_image_view{ m_device,vkDestroyImageView };
VDeleter<VkSampler> m_textureSampler{ m_device, vkDestroySampler };
/*UNIFORM BUFFER*/
UBO m_ubo;
void buildDescriptorSetLayout();
void buildDescriptorPool();
void buildDescriptorSet();
void buildUniformBuffer();
void updateUniformBuffer() VK_OVERRIDE;
VDeleter<VkDescriptorSetLayout> m_descriptorSetLayout{ m_device,vkDestroyDescriptorSetLayout };
//VDeleter<VkPipelineLayout> m_pipelineLayout{ m_device,vkDestroyPipelineLayout };
VDeleter<VkBuffer> m_uniform_staging_buffer{ m_device,vkDestroyBuffer };
VDeleter<VkDeviceMemory> m_uinform_staging_buffer_memory{ m_device,vkFreeMemory };
VDeleter<VkBuffer> m_uniform_buffer{ m_device,vkDestroyBuffer };
VDeleter<VkDeviceMemory> m_uinform_buffer_memory{ m_device,vkFreeMemory };
VDeleter<VkDescriptorPool> m_descriptor_pool{ m_device,vkDestroyDescriptorPool };
VkDescriptorSet m_descriptor_set;
/*VERTEX BUFFER*/
std::vector<Vertex> m_vertices;
VDeleter<VkBuffer> m_vertex_buffer{ m_device, vkDestroyBuffer };
VDeleter<VkDeviceMemory> m_vertex_buffer_memory{ m_device,vkFreeMemory };
/*INDEX BUFFER*/
std::vector<uint32_t> m_indices;
VDeleter<VkBuffer> m_indice_buffer{ m_device, vkDestroyBuffer };
VDeleter<VkDeviceMemory> m_indice_buffer_memory{ m_device,vkFreeMemory };
};
| [
"xarchx80@gmail.com"
] | xarchx80@gmail.com |
f370f3f568c68629f421999f4244fadc9b9f80db | cd2e994213caff60377b6fb6157651952a8241a5 | /source_code/component/animator/motion_state/knight/knight_skill_motion_state.cpp | 1be2daead9f4b30a42966d0b91d8010a69d456f9 | [] | no_license | KodFreedom/KF_Framework | 80af743da70e63c3f117d8b29aff4154d7b3af1b | ca7fadb04c12f0f39d1d40ede3729de79f844adc | refs/heads/master | 2020-12-30T16:01:49.674244 | 2018-02-25T09:54:07 | 2018-02-25T09:54:07 | 91,193,033 | 6 | 0 | null | 2018-02-25T09:54:08 | 2017-05-13T17:56:31 | C++ | UTF-8 | C++ | false | false | 945 | cpp | //--------------------------------------------------------------------------------
// knight_skill_motion_state.cpp
// this is a motion state class which is auto-created by KF_ModelAnalyzer
//--------------------------------------------------------------------------------
#include "knight_skill_motion_state.h"
#include "../../animator.h"
#include "../../../../resources/motion_data.h"
#include "knight_idle_motion_state.h"
#include "knight_death_motion_state.h"
void KnightSkillMotionState::ChangeMotion(Animator& animator)
{
if (current_frame_counter_ >= frame_to_exit_)
{
current_frame_counter_ = frame_to_exit_ - 1;
animator.Change(MY_NEW BlendMotionState(current_motion_name_, MY_NEW KnightIdleMotionState(0), current_frame_counter_, 10));
return;
}
if(animator.GetIsDead() == true)
{
animator.Change(MY_NEW BlendMotionState(current_motion_name_, MY_NEW KnightDeathMotionState(0), current_frame_counter_, 5));
return;
}
} | [
"kodfreedom@gmail.com"
] | kodfreedom@gmail.com |
60bf434358dff62c8ee13a6964c72d2a5da97abb | 047f7a970e17ab992d0a534eeb52ee893b1313a2 | /src/game/components/Player.hpp | c614e4d3990212f3855910b4e55554d54f182ac6 | [] | no_license | hhsaez/judgementday | 39607848af87f0e046c4b310e838545893fab214 | 704dabffdc053f708395a4f471f19ddbeb7319e4 | refs/heads/master | 2020-03-12T08:14:38.457364 | 2018-04-25T14:53:18 | 2018-04-25T14:53:18 | 130,523,259 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,436 | hpp | #ifndef JUDGEMENT_DAY_COMPONENTS_PLAYER_
#define JUDGEMENT_DAY_COMPONENTS_PLAYER_
#include "JudgementDayCommon.hpp"
namespace judgementday {
class Action;
namespace messaging {
struct SpawnPlayer {
crimild::Node *board;
};
}
namespace components {
class Board;
class Navigation;
class Player :
public crimild::NodeComponent,
public crimild::Messenger,
public crimild::DynamicSingleton< Player > {
CRIMILD_IMPLEMENT_RTTI( judgementday::components::Player )
public:
explicit Player( crimild::scripting::ScriptEvaluator & );
virtual ~Player( void );
virtual void start( void ) override;
void setCurrentWaypoint( crimild::Node *wp ) { _currentWaypoint = wp; }
crimild::Node *getCurrentWaypoint( void ) { return _currentWaypoint; }
void loot( crimild::containers::Array< crimild::SharedPointer< Action >> &actions );
private:
void onTurnBegan( void );
void onActionSelected( Action *action );
void onHit( crimild::Int16 damage );
private:
Board *_board = nullptr;
Navigation *_navigation = nullptr;
crimild::Node *_currentWaypoint = nullptr;
};
}
}
#endif
| [
"hhsaez@gmail.com"
] | hhsaez@gmail.com |
b483be9c08f48bb560285bde6d3819b4b5a065f9 | c30962f9ae130128d0cc7b4946828d40643dd703 | /src/base/MDDiscreteDistribution.cc | d58b10b6b0c6276fc257668e8a5710001ddf41a5 | [
"Apache-2.0"
] | permissive | SoonyangZhang/hmdp | e3a5bfa4582c0c238cdd26517bfcd2f1ff1a101d | 8a11c1563ad75ed4cdd29c52479c5aa98b678e07 | refs/heads/master | 2022-03-03T10:44:28.111223 | 2019-08-26T10:18:10 | 2019-08-26T10:18:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,370 | cc | /**
* Copyright 2014 Emmanuel Benazera beniz@droidnik.fr
*
* 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 "MDDiscreteDistribution.h"
#include "Alg.h" /* double precision */
#include "ContinuousStateDistribution.h"
#include <algorithm> /* min */
#include <stdlib.h>
#include <assert.h>
#include <iostream>
//#define DEBUG 1
namespace hmdp_base
{
int MDDiscreteDistribution::m_counterpoints = -1;
MDDiscreteDistribution::MDDiscreteDistribution (const int &dim, const int &npoints)
: m_dimension (dim), m_nPoints (npoints)
{
//m_dist = new std::pair<double,double*>();
m_dist.resize(m_nPoints);
//= (std::pair<double,double*> *) malloc (m_nPoints * sizeof (std::pair<double, double*>));
m_intervals = new double[m_dimension];//(double *) calloc (m_dimension, sizeof (double));
m_dimPoints = new int[m_dimension]();//(int *) calloc (m_dimension, sizeof (int));
}
MDDiscreteDistribution::MDDiscreteDistribution (const int &dim,
double *lowPos, double *highPos,
double *intervals)
: m_dimension (dim), m_nPoints (1)
{
m_intervals = new double[m_dimension];//(double *) calloc (m_dimension, sizeof (double));
m_dimPoints = new int[m_dimension]();//(int *) calloc (m_dimension, sizeof (int));
for (int d=0; d<m_dimension; d++)
{
m_intervals [d] = intervals[d];
#if !defined __GNUC__ || __GNUC__ < 3
m_dimPoints[d] = static_cast<int> (ceil ((highPos[d] - lowPos[d]) / m_intervals[d]));
#else
m_dimPoints[d] = lround ((highPos[d] - lowPos[d]) / m_intervals[d]);
#endif
if (m_dimPoints[d] == 0) m_dimPoints[0] = 1;
m_nPoints *= m_dimPoints[d];
}
//m_dist = new std::pair<double,double*>();
/*m_dist
= (std::pair<double,double*> *) malloc (m_nPoints * sizeof (std::pair<double, double*>));*/
m_dist.resize(m_nPoints);
/* discretize */
discretize (lowPos, highPos);
}
MDDiscreteDistribution::MDDiscreteDistribution (const MDDiscreteDistribution &mdd)
: m_dimension (mdd.getDimension ()), m_nPoints (mdd.getNPoints ())
{
/* copy the distribution and intervals */
//m_dist = new std::pair<double,double*>();
m_dist.resize(m_nPoints);
//= (std::pair<double,double*> *) malloc (m_nPoints * sizeof (std::pair<double, double*>));
m_intervals = new double[m_dimension];//(double *) calloc (m_dimension, sizeof (double));
m_dimPoints = new int[m_dimension]();//(int *) calloc (m_dimension, sizeof (int));
/*m_dist = (std::pair<double,double*> *) malloc (m_nPoints * sizeof (std::pair<double,double*>));
m_intervals = (double*) calloc (m_dimension, sizeof (double));
m_dimPoints = (int *) calloc (m_dimension, sizeof (int));*/
for (int i=0; i<m_dimension; i++)
{
m_intervals[i] = mdd.getDiscretizationInterval (i);
m_dimPoints[i] = mdd.getDimPoints (i);
}
for (int i=0; i<m_nPoints; i++)
{
double prob = mdd.getProbability (i);
double *tab = (double*) malloc (m_dimension * sizeof (double));
for (int j=0; j<m_dimension; j++)
tab[j] = mdd.getPosition (i,j);
m_dist[i] = std::pair<double,double*> (prob, tab);
}
}
MDDiscreteDistribution::MDDiscreteDistribution (ContinuousStateDistribution *csd,
double *low, double *high)
: m_dimension (csd->getSpaceDimension ()), m_nPoints (0)
{
/* count csd leaves */
int dist_size = csd->countPositiveLeaves ();
//m_dist = (std::pair<double, double*> *) malloc (dist_size * sizeof (std::pair<double,double*>));
m_dist.resize(dist_size);
m_intervals = (double*) calloc (m_dimension, sizeof (double));
m_dimPoints = (int*) malloc (m_dimension * sizeof (int));
for (int i=0; i<m_dimension; i++)
m_dimPoints[i] = -1;
/* convert leaves */
convertContinuousStateDistribution (csd, low, high);
}
MDDiscreteDistribution::~MDDiscreteDistribution ()
{
/*for (int i=0; i<m_nPoints; i++)
delete[] m_dist[i].second;
delete[] m_dist;*/
delete[] m_intervals;
delete[] m_dimPoints;
}
void MDDiscreteDistribution::createMDDiscreteBin (const int &pt, const double &proba, double *pos)
{
m_dist[pt] = std::pair<double, double*> (proba, pos);
}
void MDDiscreteDistribution::convertContinuousStateDistribution (ContinuousStateDistribution *csd, double *low, double *high)
{
if (csd->isLeaf () && csd->getProbability ())
{
double *pos = (double*) malloc (getDimension () * sizeof (double));
for (int i=0; i<getDimension (); i++)
{
pos[i] = (high[i] + low[i]) / 2.0;
/* the discretization interval in dimension i is set to the size
of the smallest cell (in that dimension). Beware, in fact the discretization
interval is not uniform in a given dimension (following the bsp tree...). */
if (m_intervals[i])
m_intervals[i] = std::min (m_intervals[i], high[i] - low[i]);
else m_intervals[i] = high[i] - low[i];
}
m_dist[m_nPoints++] = std::pair<double, double*> (csd->getProbability (), pos);
}
else if (csd->isLeaf ()) {}
else
{
m_dimPoints[csd->getDimension ()]++;
double b=high[csd->getDimension ()];
high[csd->getDimension ()] = csd->getPosition ();
ContinuousStateDistribution *csdlt = static_cast<ContinuousStateDistribution*> (csd->getLowerTree ());
convertContinuousStateDistribution (csdlt, low, high);
high[csd->getDimension ()] = b;
b = low[csd->getDimension ()];
low[csd->getDimension ()] = csd->getPosition ();
ContinuousStateDistribution *csdge = static_cast<ContinuousStateDistribution*> (csd->getGreaterTree ());
convertContinuousStateDistribution (csdge, low, high);
low[csd->getDimension ()] = b;
}
}
/* static version */
std::pair<double, double*> MDDiscreteDistribution::createMDDiscreteBinS (const double &proba,
double *pos)
{
return std::pair<double, double*> (proba, pos);
}
void MDDiscreteDistribution::discretize (double *lowPos, double *highPos)
{
double bins[m_dimension], counters[m_dimension], pts[m_dimension];
for (int d=0; d<m_dimension; d++)
{
if (d == 0)
bins[d] = 1;
else bins[d] = m_dimPoints[d] * bins[d-1];
counters[d] = 0; pts[d] = 0;
#ifdef DEBUG
//debug
std::cout << "d: " << d << std::endl;
std::cout << "interval: " << m_intervals[d]
<< " -- dimPoints: " << m_dimPoints[d]
<< " -- bins: " << bins[d] << std::endl;
//debug
#endif
}
int count = 0;
while (count < m_nPoints)
{
double *pos = (double*) malloc (m_dimension * sizeof (double));
for (int d=m_dimension-1; d>=0; d--)
{
counters[d]++;
if (count == 0)
{
//pos[d] = lowPos[d] + m_intervals[d] / 2.0;
pos[d] = lowPos[d];
pts[d]++;
counters[d] = 0;
}
else if (counters[d] == bins[d])
{
counters[d] = 0;
//pos[d] = lowPos[d] + m_intervals[d] * (2.0 * pts[d] + 1) / 2.0;
pos[d] = lowPos[d] + m_intervals[d] * pts[d];
pts[d]++;
if (d > 0)
/* pts[d-1] = 0; */
for (int j=0; j<d; j++)
pts[j] = 0;
}
else if (count > 0) pos[d] = getPosition (count-1, d); /* remain at the same position
in this dimension */
}
createMDDiscreteBin (count, 0.0, pos);
count++;
}
}
/* TODO: speed up */
double MDDiscreteDistribution::getProbability (double *pos) const
{
bool not_in_bounds = true;
for (int i=0; i<m_dimension; i++)
{
if (pos[i] > getMinPosition (i) - m_intervals[i]/2.0
&& pos[i] < getMaxPosition (i) + m_intervals[i]/2.0)
{
not_in_bounds = false;
break;
}
}
if (not_in_bounds)
return 0.0;
for (int i=0; i<m_nPoints; i++)
{
int d = 0;
while (d < m_dimension)
{
if (m_dist[i].second[d] - m_intervals[d] / 2.0 <= pos[d]
&& m_dist[i].second[d] + m_intervals[d] / 2.0 >= pos[d])
d++;
else break;
if (d == m_dimension)
{
return m_dist[i].first;
}
}
}
return 0.0;
}
/* static methods */
int MDDiscreteDistribution::jointIndependentDiscretePoints (const int &nDists, DiscreteDistribution **dists)
{
int jDpts = 1;
for (int i=0; i<nDists; i++)
jDpts *= dists[i]->getNBins ();
return jDpts;
}
MDDiscreteDistribution* MDDiscreteDistribution::jointDiscreteDistribution (const int &nDists,
DiscreteDistribution **dists)
{
MDDiscreteDistribution::m_counterpoints = -1;
int jidd = MDDiscreteDistribution::jointIndependentDiscretePoints (nDists, dists);
MDDiscreteDistribution *jointD = new MDDiscreteDistribution (nDists, jidd);
//double *pos = (double *) malloc (nDists * sizeof (double));
double *pos = new double[nDists];
jointD = MDDiscreteDistribution::jointDiscreteDistribution (dists, 0, pos, 1.0, jointD);
if (MDDiscreteDistribution::m_counterpoints+1 != jidd)
{
jointD->reallocPoints (MDDiscreteDistribution::m_counterpoints+1);
}
for (int i=0; i<nDists; i++)
{
jointD->setDimPoint (i, dists[i]->getNBins ());
jointD->setDiscretizationInterval (i, dists[i]->getInterval ());
}
delete[] pos;
return jointD;
}
MDDiscreteDistribution* MDDiscreteDistribution::jointDiscreteDistribution (DiscreteDistribution **dists,
const int &d, double *pos,
const double &prob,
MDDiscreteDistribution *mdd)
{
double pr;
for (int i=0; i<dists[d]->getNBins (); i++) /* iterate points in dimension d */
{
pos[d]=dists[d]->getXAtBin (i);
pr = prob * dists[d]->getProbaAtBin (i);
if (d == mdd->getDimension () - 1) /* end of a joint product */
{
if (pr > 0.0)
{
double *positions = (double *) malloc (mdd->getDimension () * sizeof (double));
for (int j=0; j<mdd->getDimension (); j++)
positions[j] = pos[j];
mdd->createMDDiscreteBin (++m_counterpoints, pr, positions);
}
}
else MDDiscreteDistribution::jointDiscreteDistribution (dists, d+1, pos, pr, mdd);
}
return mdd;
}
MDDiscreteDistribution* MDDiscreteDistribution::resizeDiscretization (const MDDiscreteDistribution &mddist,
double *lowPos, double *highPos,
double *intervals)
{
MDDiscreteDistribution *rmddist = new MDDiscreteDistribution (mddist.getDimension (), lowPos, highPos,
intervals);
//std::cout << "rmddist: " << *rmddist << std::endl;
//double pos[rmddist->getDimension ()];
double sum = 0.0;
for (int pt=0; pt<rmddist->getNPoints (); pt++)
{
/* for (int d=0; d<rmddist->getDimension (); d++)
pos[d] = rmddist->getPosition (pt, d); */
//rmddist->setProbability (pt, mddist.getProbability (pos));
rmddist->setProbability (pt, mddist.getProbability (rmddist->getPosition (pt)));
sum += rmddist->getProbability (pt);
}
if (sum != 1.0)
rmddist->normalize (sum);
return rmddist;
}
MDDiscreteDistribution* MDDiscreteDistribution::convoluteMDDiscreteDistributions (const MDDiscreteDistribution &mddist1,
const MDDiscreteDistribution &mddist2,
double *low, double *high,
double *lowPos1, double *highPos1,
double *lowPos2, double *highPos2)
{
if (mddist1.getDimension () != mddist2.getDimension ())
{
std::cout << "[Error]:MDDiscreteDistribution::convoluteMDDiscreteDistributions: distributions are on continuous spaces of different dimensions. Exiting...\n";
exit (-1);
}
int dim = mddist1.getDimension ();
/* create multi-dimensional distribution of proper size */
double interval[dim], convLowPos[dim], convHighPos[dim];
bool nullprob = false;
for (int i=0; i<dim; i++)
{
#ifdef DEBUG
//debug
std::cout << i << " mddist1 min: " << mddist1.getMinPosition (i)
<< " -- mddist2 min: " << mddist2.getMinPosition (i)
<< " -- lowPos1: " << lowPos1[i] << " -- lowPos2: " << lowPos2[i]
<< std::endl;
std::cout << i << " mddist1 max: " << mddist1.getMaxPosition (i)
<< " -- mddist2 max: " << mddist2.getMaxPosition (i)
<< " -- highPos1: " << highPos1[i] << " -- highPos2: " << highPos2[i]
<< std::endl;
//debug
#endif
/* bounds */
convLowPos[i] = std::max (std::max (mddist1.getMinPosition (i) - mddist1.getDiscretizationInterval (i)/2.0
+ mddist2.getMinPosition (i) - mddist2.getDiscretizationInterval (i)/2.0,
lowPos1[i] + lowPos2[i]), low[i]);
convHighPos[i] = std::min (std::min (mddist1.getMaxPosition (i) + mddist1.getDiscretizationInterval (i)/2.0
+ mddist2.getMaxPosition (i) + mddist2.getDiscretizationInterval (i)/2.0,
highPos1[i] + highPos2[i]), high[i]);
/* select the minimal discretization interval */
interval[i] = std::min (mddist1.getDiscretizationInterval (i),
mddist2.getDiscretizationInterval (i));
#ifdef DEBUG
//debug
std::cout << i << " convLowPos: " << convLowPos[i]
<< " -- convHighPos: " << convHighPos[i]
<< " -- inverval: " << interval[i]
<< std::endl;
//debug
#endif
if (nullprob
|| convLowPos[i] >= convHighPos[i])
{
nullprob = true;
convLowPos[i] = low[i];
convHighPos[i] = high[i];
#if !defined __GNUC__ || __GNUC__ < 3
interval[i] = ceil (high[i] - low[i]);
#else
interval[i] = lround (high[i] - low[i]);
#endif
}
}
/* we consider that if probability is null on a dimension, then
it should be null over the full continuous space. Therefore we return
an empty distribution over the full space. */
/* TODO: should not be empty. Should proceed with the convolution. */
if (nullprob)
{
//debug
//std::cout << "returning 'zero' convolution\n";
//debug
return new MDDiscreteDistribution (dim, convLowPos, convHighPos, interval);
}
MDDiscreteDistribution *cmddist = new MDDiscreteDistribution (dim, convLowPos,
convHighPos, interval);
#ifdef DEBUG
//debug
std::cout << "discrete convolution points: " << cmddist->getNPoints () << std::endl;
/* std::cout << *cmddist << std::endl; */
//debug
#endif
/* sync discrete distributions and prepare for the convolution */
double lowConv[dim], highConv[dim], intervalsConv[dim];
int bins[dim], counters[dim];
for (int j=0; j<dim; j++)
{
lowConv[j] = std::min (lowPos1[j], lowPos2[j]); /* lower bounds for convolving values. */
highConv[j] = std::max (highPos1[j], highPos2[j]);
intervalsConv[j] = std::min (mddist1.getDiscretizationInterval (j),
mddist2.getDiscretizationInterval (j)); /* sync the discretization intervals */
//debug
/* std::cout << "rsc " << j << ": lowConv: " << lowConv[j]
<< " -- highConv: " << highConv[j] << " -- interval: " << intervalsConv[j]
<< std::endl; */
//debug
}
/* resize discrete distributions: cmddist1, cmddist2 */
/* MDDiscreteDistribution *cmddist1
= MDDiscreteDistribution::resizeDiscretization (mddist1, low, high, intervalsConv); */
/* MDDiscreteDistribution *cmddist2
= MDDiscreteDistribution::resizeDiscretization (mddist2, lowConv, highConv, intervalsConv); */
MDDiscreteDistribution *cmddist1
= MDDiscreteDistribution::resizeDiscretization (mddist1, lowPos1, highPos1, intervalsConv);
/* MDDiscreteDistribution *cmddist2
= MDDiscreteDistribution::resizeDiscretization (mddist2, lowPos2, highPos2, intervalsConv); */
/* MDDiscreteDistribution *cmddist1 = new MDDiscreteDistribution (mddist1); */
MDDiscreteDistribution *cmddist2 = new MDDiscreteDistribution (mddist2);
//debug
//std::cout << "resizing: " << *cmddist1 << *cmddist2 << std::endl;
//debug
for (int j=0; j<dim; j++)
{
if (j == 0)
bins[j] = 1;
else
bins[j] = cmddist1->getDimPoints (j) * bins[j-1];
counters[j] = 0;
//debug
//std::cout << "bins " << j << ": " << bins[j] << std::endl;
//debug
}
int totalPos = cmddist1->getNPoints ();
double sum = 0.0;
#ifdef DEBUG
//debug
std::cout << "convolute: totalPos: " << totalPos << std::endl;
//debug
#endif
/* multi-dimensional convolution in between bounds */
for (int p=0; p<cmddist->getNPoints (); p++) /* iterate points */
{
/* std::cout << "point: " << p << " -- position: "
<< cmddist->getPosition (p, 0) << ", " << cmddist->getPosition (p, 1)
<< std::endl; */
/* initialization */
double val = 0.0;
double pos1[dim], pos2[dim];
for (int j=0; j<dim; j++)
{
pos1[j] = cmddist1->getMinPosition (j);
//pos2[j] = cmddist->getPosition (p, j) - cmddist1->getMinPosition (j);
pos2[j] = cmddist->getPosition (p, j) - pos1[j];
}
int count = 0;
while (count < totalPos)
{
double val1 = cmddist1->getProbability (pos1);
double val2 = cmddist2->getProbability (pos2);
val += val1 * val2;
/* std::cout << "pos1: " << pos1[0] << ", " << pos1[1] << std::endl;
std::cout << "pos2: " << pos2[0] << ", " << pos2[1] << std::endl;
std::cout << "val1: " << val1 << " -- val2: " << val2 << std::endl; */
for (int i=dim-1; i>=0; i--)
{
counters[i]++;
if (counters[i] == bins[i])
{
counters[i] = 0;
pos1[i] += cmddist1->getDiscretizationInterval (i);
//pos2[i] -= cmddist2->getDiscretizationInterval (i);
pos2[i] = cmddist->getPosition (p,i) - pos1[i];
if (i > 0)
{
for (int j=0; j<i; j++)
{
counters[j] = 0;
pos1[j] = cmddist1->getMinPosition (j);
pos2[j] = cmddist->getPosition (p, j) - cmddist1->getMinPosition (j);
}
/* pos1[i-1] = cmddist1->getMinPosition (i-1);
pos2[i-1] = cmddist->getPosition (p, i-1) - cmddist1->getMinPosition (i-1); */
break;
}
}
} /* end for */
count++;
}
//std::cout << " -- val: " << val << std::endl;
sum += val;
cmddist->setProbability (p, val);
}
/* normalize */
if (sum)
cmddist->normalize (sum);
//debug
/* std::cout << "MDDiscreteDistribution::convolute: result: "
<< *cmddist << std::endl; */
//debug
delete cmddist1; delete cmddist2;
return cmddist;
}
void MDDiscreteDistribution::normalize (const double &sum)
{
for (int i=0; i<m_nPoints; i++)
setProbability (i, getProbability (i) / sum);
}
double MDDiscreteDistribution::getProbMass () const
{
double mass = 0.0;
for (int i=0; i<m_nPoints; i++)
{
mass += getProbMass (i);
}
return mass;
}
double MDDiscreteDistribution::getProbMass (const int &i) const
{
double volume = 1.0;
for (int j=0; j<m_dimension; j++)
volume *= m_intervals[j];
return volume * getProbability (i);
}
std::pair<double, double*>* MDDiscreteDistribution::getPointAndBinMass (const int &i) const
{
std::pair<double, double*> *res
= new std::pair<double, double*> (std::pair<double, double*> (getProbMass (i), m_dist[i].second));
return res;
}
void MDDiscreteDistribution::reallocPoints (const int &nnpoints)
{
m_nPoints = nnpoints;
//m_dist = (std::pair<double,double*> *) realloc (m_dist, nnpoints * sizeof (std::pair<double, double*>));
m_dist.resize(m_nPoints);
}
std::ostream& MDDiscreteDistribution::print (std::ostream &output)
{
output << "nPoints: " << getNPoints ()
<< " -- dim: " << getDimension () << '\n';
output << "intervals: ";
for (int j=0; j<getDimension (); j++)
output << "(" << j << ", " << m_intervals[j] << ") ";
output << std::endl;
for (int i=0; i<getNPoints (); i++) /* iterate discrete points */
{
output << i << ": proba: " << getProbability (i) << " [";
for (int j=0; j<getDimension (); j++)
output << getPosition (i, j) << ' ';
output << "]\n";
}
#ifdef DEBUG
std::cout << "total probability mass: " << getProbMass () << std::endl;
#endif
return output;
}
std::ostream &operator<<(std::ostream &output, MDDiscreteDistribution &mdd)
{
return mdd.print (output);
}
std::ostream &operator<<(std::ostream &output, MDDiscreteDistribution *mdd)
{
return mdd->print (output);
}
} /* end of namespace */
| [
"emmanuel.benazera@xplr.com"
] | emmanuel.benazera@xplr.com |
d2a2085762d2bd36918036f8f6c8a9028b22b2ee | 9d364070c646239b2efad7abbab58f4ad602ef7b | /platform/external/chromium_org/ppapi/proxy/ppp_messaging_proxy.h | ced608a08c96a6ecd69e01296bd6a962103b41c3 | [
"BSD-3-Clause",
"LicenseRef-scancode-khronos"
] | permissive | denix123/a32_ul | 4ffe304b13c1266b6c7409d790979eb8e3b0379c | b2fd25640704f37d5248da9cc147ed267d4771c2 | refs/heads/master | 2021-01-17T20:21:17.196296 | 2016-08-16T04:30:53 | 2016-08-16T04:30:53 | 65,786,970 | 0 | 2 | null | 2020-03-06T22:00:52 | 2016-08-16T04:15:54 | null | UTF-8 | C++ | false | false | 1,113 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PPAPI_PROXY_PPP_MESSAGING_PROXY_H_
#define PPAPI_PROXY_PPP_MESSAGING_PROXY_H_
#include "base/compiler_specific.h"
#include "ppapi/c/pp_instance.h"
#include "ppapi/c/ppp_messaging.h"
#include "ppapi/proxy/interface_proxy.h"
namespace ppapi {
namespace proxy {
class SerializedVarReceiveInput;
class PPP_Messaging_Proxy : public InterfaceProxy {
public:
PPP_Messaging_Proxy(Dispatcher* dispatcher);
virtual ~PPP_Messaging_Proxy();
virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;
private:
void OnMsgHandleMessage(PP_Instance instance,
SerializedVarReceiveInput data);
void OnMsgHandleBlockingMessage(PP_Instance instance,
SerializedVarReceiveInput data,
IPC::Message* reply);
const PPP_Messaging* ppp_messaging_impl_;
DISALLOW_COPY_AND_ASSIGN(PPP_Messaging_Proxy);
};
}
}
#endif
| [
"allegrant@mail.ru"
] | allegrant@mail.ru |
98a1a792acf95b145c2230ee01d1f85fa2816369 | 9030ce2789a58888904d0c50c21591632eddffd7 | /SDK/ARKSurvivalEvolved_DinoColorSet_TekStrider_parameters.hpp | 45b0688d16887c5ded82675b63cdec3e17aea557 | [
"MIT"
] | permissive | 2bite/ARK-SDK | 8ce93f504b2e3bd4f8e7ced184980b13f127b7bf | ce1f4906ccf82ed38518558c0163c4f92f5f7b14 | refs/heads/master | 2022-09-19T06:28:20.076298 | 2022-09-03T17:21:00 | 2022-09-03T17:21:00 | 232,411,353 | 14 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 740 | hpp | #pragma once
// ARKSurvivalEvolved (332.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_DinoColorSet_TekStrider_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function DinoColorSet_TekStrider.DinoColorSet_TekStrider_C.ExecuteUbergraph_DinoColorSet_TekStrider
struct UDinoColorSet_TekStrider_C_ExecuteUbergraph_DinoColorSet_TekStrider_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
7a2e0661f38ee59346bac14376f1c821c6efba57 | 409de9ad0fa66bb905908c3de39997690524336e | /trunk/src/virtual_network.cc | c3bc965abad65ba8e4fda579d33ed76e329afe81 | [
"MIT"
] | permissive | saumitraaditya/Tincan | 0dcba7708f32ddfc4ab061aef79680f834fd1153 | 51b7b554b8c32faa04b1704e28cbab1d7ce3d8bf | refs/heads/master | 2019-07-17T03:43:04.071976 | 2017-11-27T03:25:30 | 2017-11-27T03:25:30 | 69,046,620 | 0 | 0 | null | 2016-09-23T17:30:42 | 2016-09-23T17:30:42 | null | UTF-8 | C++ | false | false | 21,166 | cc | /*
* ipop-project
* Copyright 2016, University of Florida
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "virtual_network.h"
#include "webrtc/base/base64.h"
#include "tincan_control.h"
namespace tincan
{
VirtualNetwork::VirtualNetwork(
unique_ptr<VnetDescriptor> descriptor,
shared_ptr<IpopControllerLink> ctrl_handle) :
tdev_(nullptr),
peer_network_(nullptr),
descriptor_(move(descriptor)),
ctrl_link_(ctrl_handle)
{
tdev_ = new TapDev();
peer_network_ = new PeerNetwork(descriptor->name);
}
VirtualNetwork::~VirtualNetwork()
{
delete peer_network_;
delete tdev_;
}
void
VirtualNetwork::Configure()
{
TapDescriptor ip_desc = {
descriptor_->name,
descriptor_->vip4,
descriptor_->prefix4,
descriptor_->mtu4
};
//initialize the Tap Device
tdev_->Open(ip_desc);
//create X509 identity for secure connections
string sslid_name = descriptor_->name + descriptor_->uid;
sslid_.reset(SSLIdentity::Generate(sslid_name, rtc::KT_RSA));
if(!sslid_)
throw TCEXCEPT("Failed to generate SSL Identity");
local_fingerprint_.reset(
SSLFingerprint::Create(rtc::DIGEST_SHA_1, sslid_.get()));
if(!local_fingerprint_)
throw TCEXCEPT("Failed to create the local finger print");
}
void
VirtualNetwork::Start()
{
net_worker_.Start();
sig_worker_.Start();
if(descriptor_->l2tunnel_enabled)
{
tdev_->read_completion_.connect(this, &VirtualNetwork::TapReadCompleteL2);
tdev_->write_completion_.connect(this, &VirtualNetwork::TapWriteCompleteL2);
}
else
{
tdev_->read_completion_.connect(this, &VirtualNetwork::TapReadComplete);
tdev_->write_completion_.connect(this, &VirtualNetwork::TapWriteComplete);
}
tdev_->Up();
peer_net_thread_.Start(peer_network_);
}
void
VirtualNetwork::Shutdown()
{
tdev_->Down();
tdev_->Close();
peer_net_thread_.Stop();
}
void
VirtualNetwork::StartTunnel(
int)
{
lock_guard<mutex> lg(vn_mtx_);
for(uint8_t i = 0; i < kLinkConcurrentAIO; i++)
{
unique_ptr<TapFrame> tf = make_unique<TapFrame>();
tf->Initialize();
tf->BufferToTransfer(tf->Payload());
tf->BytesToTransfer(tf->PayloadCapacity());
tdev_->Read(*tf.release());
}
}
void
VirtualNetwork::UpdateRoute(
MacAddressType mac_dest,
MacAddressType mac_path)
{
peer_network_->UpdateRoute(mac_dest, mac_path);
}
unique_ptr<VirtualLink>
VirtualNetwork::CreateVlink(
unique_ptr<VlinkDescriptor> vlink_desc,
unique_ptr<PeerDescriptor> peer_desc,
cricket::IceRole ice_role)
{
vlink_desc->stun_addr = descriptor_->stun_addr;
vlink_desc->turn_addr = descriptor_->turn_addr;
vlink_desc->turn_user = descriptor_->turn_user;
vlink_desc->turn_pass = descriptor_->turn_pass;
unique_ptr<VirtualLink> vl = make_unique<VirtualLink>(
move(vlink_desc), move(peer_desc), &sig_worker_, &net_worker_);
unique_ptr<SSLIdentity> sslid_copy(sslid_->GetReference());
vl->Initialize(net_manager_, move(sslid_copy), *local_fingerprint_.get(),
ice_role);
if(descriptor_->l2tunnel_enabled)
{
vl->SignalMessageReceived.connect(this, &VirtualNetwork::VlinkReadCompleteL2);
}
else
{
vl->SignalMessageReceived.connect(this, &VirtualNetwork::ProcessIncomingFrame);
}
vl->SignalLinkUp.connect(this, &VirtualNetwork::StartTunnel);
return vl;
}
shared_ptr<VirtualLink>
VirtualNetwork::CreateTunnel(
unique_ptr<PeerDescriptor> peer_desc,
unique_ptr<VlinkDescriptor> vlink_desc)
{
shared_ptr<VirtualLink> vl;
MacAddressType mac;
shared_ptr<Tunnel> tnl;
string mac_str = peer_desc->mac_address;
StringToByteArray(peer_desc->mac_address, mac.begin(), mac.end());
if(peer_network_->IsAdjacent(mac))
{
tnl = peer_network_->GetTunnel(mac);
}
else
{
tnl = make_shared<Tunnel>();
tnl->Id(mac);
}
vl = CreateVlink(move(vlink_desc), move(peer_desc),
cricket::ICEROLE_CONTROLLED);
if(vl)
{
tnl->AddVlinkEndpoint(vl);
peer_network_->Add(tnl);
LOG(LS_INFO) << "Created CONTROLLED vlink w/ Tunnel ID (" <<
mac_str << ")";
}
else throw TCEXCEPT("The CreateTunnelEndpoint operation failed.");
return vl;
}
void
VirtualNetwork::ConnectTunnel(
unique_ptr<PeerDescriptor> peer_desc,
unique_ptr<VlinkDescriptor> vlink_desc)
{
MacAddressType mac;
shared_ptr<Tunnel> tnl;
string mac_str = peer_desc->mac_address;
StringToByteArray(peer_desc->mac_address, mac.begin(), mac.end());
if(peer_network_->IsAdjacent(mac))
{
tnl = peer_network_->GetTunnel(mac);
}
else
{
tnl = make_shared<Tunnel>();
tnl->Id(mac);
}
shared_ptr<VirtualLink> vl = CreateVlink(move(vlink_desc), move(peer_desc),
cricket::ICEROLE_CONTROLLING);
if(vl)
{
tnl->AddVlinkEndpoint(vl);
vl->StartConnections();
peer_network_->Add(tnl);
LOG(LS_INFO) << "Created CONTROLLING vlink w/ Tunnel ID (" <<
mac_str << ")";
}
else throw TCEXCEPT("The ConnectTunnel operation failed.");
}
void VirtualNetwork::TerminateTunnel(
const string & tnl_id)
{
MacAddressType mac;
StringToByteArray(tnl_id, mac.begin(), mac.end());
if(peer_network_->IsAdjacent(mac))
{
peer_network_->Remove(mac);
}
}
void VirtualNetwork::TerminateLink(
const string & tnl_id,
const string & link_role)
{
MacAddressType mac;
StringToByteArray(tnl_id, mac.begin(), mac.end());
if(peer_network_->IsAdjacent(mac))
{
shared_ptr<Tunnel> tnl = peer_network_->GetTunnel(mac);
if(link_role == TincanControl::Controlling.c_str())
{
tnl->ReleaseLink(cricket::ICEROLE_CONTROLLING);
}
else if (link_role == TincanControl::Controlled.c_str())
{
tnl->ReleaseLink(cricket::ICEROLE_CONTROLLED);
}
}
}
VnetDescriptor &
VirtualNetwork::Descriptor()
{
return *descriptor_.get();
}
string
VirtualNetwork::Name()
{
return descriptor_->name;
}
string
VirtualNetwork::MacAddress()
{
MacAddressType mac = tdev_->MacAddress();
return ByteArrayToString(mac.begin(), mac.end(), 0);
}
string
VirtualNetwork::Fingerprint()
{
return local_fingerprint_->ToString();
}
void
VirtualNetwork::IgnoredNetworkInterfaces(
const vector<string>& ignored_list)
{
net_manager_.set_network_ignore_list(ignored_list);
}
void VirtualNetwork::QueryTunnelStats(
const string & node_mac,
Json::Value & node_info)
{
MacAddressType mac;
StringToByteArray(node_mac, mac.begin(), mac.end());
if(peer_network_->IsAdjacent(mac))
{
shared_ptr<VirtualLink> vl = peer_network_->GetTunnel(mac)->Controlling();
if(vl && vl->IsReady())
{
LinkStatsMsgData md;
md.vl = vl;
net_worker_.Post(RTC_FROM_HERE, this, MSGID_QUERY_NODE_INFO, &md);
md.msg_event.Wait(Event::kForever);
node_info[TincanControl::Controlling][TincanControl::Stats].swap(md.stats);
node_info[TincanControl::Controlling][TincanControl::Status] = "online";
}
else
{
node_info[TincanControl::Controlling][TincanControl::Status] = "offline";
node_info[TincanControl::Controlling][TincanControl::Stats] = Json::Value(Json::arrayValue);
}
vl = peer_network_->GetTunnel(mac)->Controlled();
if(vl && vl->IsReady())
{
LinkStatsMsgData md;
md.vl = vl;
net_worker_.Post(RTC_FROM_HERE, this, MSGID_QUERY_NODE_INFO, &md);
md.msg_event.Wait(Event::kForever);
node_info[TincanControl::Controlled][TincanControl::Stats].swap(md.stats);
node_info[TincanControl::Controlled][TincanControl::Status] = "online";
}
else
{
node_info[TincanControl::Controlled][TincanControl::Status] = "offline";
node_info[TincanControl::Controlled][TincanControl::Stats] = Json::Value(Json::arrayValue);
}
}
else
{
node_info[TincanControl::Controlling][TincanControl::MAC] = node_mac;
node_info[TincanControl::Controlling][TincanControl::Status] = "unknown";
node_info[TincanControl::Controlling][TincanControl::Stats] = Json::Value(Json::arrayValue);
node_info[TincanControl::Controlled][TincanControl::MAC] = node_mac;
node_info[TincanControl::Controlled][TincanControl::Status] = "unknown";
node_info[TincanControl::Controlled][TincanControl::Stats] = Json::Value(Json::arrayValue);
}
}
void VirtualNetwork::QueryNodeInfo(
const string & node_mac,
Json::Value & node_info)
{
MacAddressType mac;
StringToByteArray(node_mac, mac.begin(), mac.end());
if(peer_network_->IsAdjacent(mac))
{
shared_ptr<VirtualLink> vl = peer_network_->GetTunnel(mac)->Vlink();
node_info[TincanControl::UID] = vl->PeerInfo().uid;
node_info[TincanControl::VIP4] = vl->PeerInfo().vip4;
//node_info[TincanControl::VIP6] = vl->PeerInfo().vip6;
node_info[TincanControl::MAC] = vl->PeerInfo().mac_address;
node_info[TincanControl::Fingerprint] = vl->PeerInfo().fingerprint;
if(vl->IsReady())
{
node_info[TincanControl::Status] = "online";
}
else
{
node_info[TincanControl::Status] = "offline";
}
////////////////////////////////////////////////////////////////////////////
vl = peer_network_->GetTunnel(mac)->Controlled();
if(vl)
{
node_info[TincanControl::Controlling][TincanControl::UID] =
vl->PeerInfo().uid;
node_info[TincanControl::Controlling][TincanControl::VIP4] =
vl->PeerInfo().vip4;
node_info[TincanControl::Controlling][TincanControl::MAC] =
vl->PeerInfo().mac_address;
node_info[TincanControl::Controlling][TincanControl::Fingerprint] =
vl->PeerInfo().fingerprint;
if(vl->IsReady())
{
node_info[TincanControl::Controlling][TincanControl::Status] = "online";
}
else
{
node_info[TincanControl::Controlling][TincanControl::Status] =
"offline";
}
}
else
{
node_info[TincanControl::Controlling][TincanControl::MAC] = node_mac;
node_info[TincanControl::Controlled][TincanControl::MAC] = node_mac;
}
vl = peer_network_->GetTunnel(mac)->Controlling();
if(vl)
{
node_info[TincanControl::Controlled][TincanControl::UID] =
vl->PeerInfo().uid;
node_info[TincanControl::Controlled][TincanControl::VIP4] =
vl->PeerInfo().vip4;
node_info[TincanControl::Controlled][TincanControl::MAC] =
vl->PeerInfo().mac_address;
node_info[TincanControl::Controlled][TincanControl::Fingerprint] =
vl->PeerInfo().fingerprint;
if(vl->IsReady())
{
node_info[TincanControl::Controlled][TincanControl::Status] =
"online";
}
else
{
node_info[TincanControl::Controlled][TincanControl::Status] =
"offline";
}
}
else
{
node_info[TincanControl::Controlling][TincanControl::Status] =
"unknown";
node_info[TincanControl::Controlled][TincanControl::Status] =
"unknown";
}
}
else
{
node_info[TincanControl::MAC] = node_mac;
node_info[TincanControl::Controlling][TincanControl::MAC] = node_mac;
node_info[TincanControl::Controlled][TincanControl::MAC] = node_mac;
node_info[TincanControl::Status] = "unknown";
node_info[TincanControl::Controlling][TincanControl::Status] = "unknown";
node_info[TincanControl::Controlled][TincanControl::Status] = "unknown";
}
}
void VirtualNetwork::QueryTunnelCas(
const string & tnl_id, //peer mac address
Json::Value & cas_info)
{
shared_ptr<Tunnel> tnl = peer_network_->GetTunnel(tnl_id);
tnl->QueryCas(cas_info);
}
void
VirtualNetwork::SendIcc(
const string & recipient_mac,
const string & data)
{
unique_ptr<IccMessage> icc = make_unique<IccMessage>();
icc->Message((uint8_t*)data.c_str(), (uint16_t)data.length());
unique_ptr<TransmitMsgData> md = make_unique<TransmitMsgData>();
md->frm = move(icc);
MacAddressType mac;
StringToByteArray(recipient_mac, mac.begin(), mac.end());
md->tnl = peer_network_->GetTunnel(mac);
net_worker_.Post(RTC_FROM_HERE, this, MSGID_SEND_ICC, md.release());
}
/*
Incoming frames off the vlink are one of:
pure ethernet frame - to be delivered to the TAP device
icc message - to be delivered to the local controller
The implementing entity needs access to the TAP and controller instances to
transmit the frame. These can be provided at initialization.
Responsibility: Identify the received frame type, perfrom a transformation of
the frame
if needed and transmit it.
- Is this my ARP? Deliver to TAP.
- Is this an ICC? Send to controller.
Types of Transformation:
*/
void
VirtualNetwork::VlinkReadCompleteL2(
uint8_t * data,
uint32_t data_len,
VirtualLink &)
{
unique_ptr<TapFrame> frame = make_unique<TapFrame>(data, data_len);
TapFrameProperties fp(*frame);
if(fp.IsIccMsg())
{ // this is an ICC message, deliver to the ipop-controller
unique_ptr<TincanControl> ctrl = make_unique<TincanControl>();
ctrl->SetControlType(TincanControl::CTTincanRequest);
Json::Value & req = ctrl->GetRequest();
req[TincanControl::Command] = TincanControl::ICC;
req[TincanControl::InterfaceName] = descriptor_->name;
req[TincanControl::Data] = string((char*)frame->Payload(), frame->PayloadLength());
//LOG(TC_DBG) << " Delivering ICC to ctrl, data=\n" << req[TincanControl::Data].asString();
ctrl_link_->Deliver(move(ctrl));
}
else if(fp.IsFwdMsg())
{ // a frame to be routed on the overlay
if(peer_network_->IsRouteExists(fp.DestinationMac()))
{
shared_ptr<Tunnel> tnl = peer_network_->GetRoute(fp.DestinationMac());
TransmitMsgData *md = new TransmitMsgData;
md->frm = move(frame);
md->tnl = tnl;
net_worker_.Post(RTC_FROM_HERE, this, MSGID_FWD_FRAME, md);
}
else
{ //no route found, send to controller
unique_ptr<TincanControl> ctrl = make_unique<TincanControl>();
ctrl->SetControlType(TincanControl::CTTincanRequest);
Json::Value & req = ctrl->GetRequest();
req[TincanControl::Command] = TincanControl::UpdateRoutes;
req[TincanControl::InterfaceName] = descriptor_->name;
req[TincanControl::Data] = ByteArrayToString(frame->Payload(),
frame->PayloadEnd());
LOG(TC_DBG) << "FWDing frame to ctrl, data=\n" <<
req[TincanControl::Data].asString();
ctrl_link_->Deliver(move(ctrl));
}
}
else if (fp.IsDtfMsg())
{
frame->Dump("Frame from vlink");
frame->BufferToTransfer(frame->Payload()); //write frame payload to TAP
frame->BytesToTransfer(frame->PayloadLength());
frame->SetWriteOp();
tdev_->Write(*frame.release());
}
else
{
LOG(LS_ERROR) << "Unknown frame type received!";
frame->Dump("Invalid header");
}
}
//
//AsyncIOCompletion Routines for TAP device
/*
Frames read from the TAP device are handled here. This is an ethernet frame
from the networking stack. The implementing entity needs access to the
recipient - via its vlink, or to the controller - when there is no
vlink to the recipient.
Responsibility: Identify the recipient of the frame and route accordingly.
- Is this an ARP? Send to controller.
- Is this an IP packet? Use MAC to lookup vlink and forwrd or send to
controller.
- Is this for a device behind an IPOP switch
Note: Avoid exceptions on the IO loop
*/
void
VirtualNetwork::TapReadCompleteL2(
AsyncIo * aio_rd)
{
TapFrame * frame = static_cast<TapFrame*>(aio_rd->context_);
if(!aio_rd->good_)
{
frame->Initialize();
frame->BufferToTransfer(frame->Payload());
frame->BytesToTransfer(frame->PayloadCapacity());
if(0 != tdev_->Read(*frame))
delete frame;
return;
}
frame->PayloadLength(frame->BytesTransferred());
TapFrameProperties fp(*frame);
MacAddressType mac = fp.DestinationMac();
frame->BufferToTransfer(frame->Begin()); //write frame header + PL to vlink
frame->BytesToTransfer(frame->Length());
if(peer_network_->IsAdjacent(mac))
{
frame->Header(kDtfMagic);
frame->Dump("Unicast");
shared_ptr<Tunnel> tnl = peer_network_->GetTunnel(mac);
TransmitMsgData *md = new TransmitMsgData;
md->frm.reset(frame);
md->tnl = tnl;
net_worker_.Post(RTC_FROM_HERE, this, MSGID_TRANSMIT, md);
}
else if(peer_network_->IsRouteExists(mac))
{
frame->Header(kFwdMagic);
frame->Dump("Frame FWD");
TransmitMsgData *md = new TransmitMsgData;
md->frm.reset(frame);
md->tnl = peer_network_->GetRoute(mac);
net_worker_.Post(RTC_FROM_HERE, this, MSGID_FWD_FRAME, md);
}
else
{
frame->Header(kIccMagic);
if(fp.IsArpRequest())
{
frame->Dump("ARP Request");
}
else if(fp.IsArpResponse())
{
frame->Dump("ARP Response");
}
else if (memcmp(fp.DestinationMac().data(),"\xff\xff\xff\xff\xff\xff", 6) != 0)
{
frame->Dump("No Route Unicast");
}
//Send to IPOP Controller to find a route for this frame
unique_ptr<TincanControl> ctrl = make_unique<TincanControl>();
ctrl->SetControlType(TincanControl::CTTincanRequest);
Json::Value & req = ctrl->GetRequest();
req[TincanControl::Command] = TincanControl::UpdateRoutes;
req[TincanControl::InterfaceName] = descriptor_->name;
req[TincanControl::Data] = ByteArrayToString(frame->Payload(),
frame->PayloadEnd());
ctrl_link_->Deliver(move(ctrl));
//Post a new TAP read request
frame->Initialize(frame->Payload(), frame->PayloadCapacity());
if(0 != tdev_->Read(*frame))
delete frame;
}
}
void
VirtualNetwork::TapWriteCompleteL2(
AsyncIo * aio_wr)
{
TapFrame * frame = static_cast<TapFrame*>(aio_wr->context_);
if(frame->IsGood())
frame->Dump("TAP Write Completed");
else
LOG(LS_WARNING) << "Tap Write FAILED completion";
delete frame;
}
void VirtualNetwork::OnMessage(Message * msg)
{
switch(msg->message_id)
{
case MSGID_TRANSMIT:
{
unique_ptr<TapFrame> frame = move(((TransmitMsgData*)msg->pdata)->frm);
shared_ptr<Tunnel> tnl = ((TransmitMsgData*)msg->pdata)->tnl;
tnl->Transmit(*frame);
delete msg->pdata;
frame->Initialize(frame->Payload(), frame->PayloadCapacity());
if(0 == tdev_->Read(*frame))
frame.release();
}
break;
case MSGID_SEND_ICC:
{
unique_ptr<TapFrame> frame = move(((TransmitMsgData*)msg->pdata)->frm);
shared_ptr<Tunnel> tnl = ((TransmitMsgData*)msg->pdata)->tnl;
tnl->Transmit(*frame);
//LOG(TC_DBG) << "Sent ICC to=" <<vl->PeerInfo().vip4 << " data=\n" <<
// string((char*)(frame->begin()+4), *(uint16_t*)(frame->begin()+2));
delete msg->pdata;
}
break;
case MSGID_QUERY_NODE_INFO:
{
shared_ptr<VirtualLink> vl = ((LinkStatsMsgData*)msg->pdata)->vl;
vl->GetStats(((LinkStatsMsgData*)msg->pdata)->stats);
((LinkStatsMsgData*)msg->pdata)->msg_event.Set();
}
break;
case MSGID_FWD_FRAME:
case MSGID_FWD_FRAME_RD:
{
unique_ptr<TapFrame> frame = move(((TransmitMsgData*)msg->pdata)->frm);
shared_ptr<Tunnel> tnl = ((TransmitMsgData*)msg->pdata)->tnl;
tnl->Transmit(*frame);
//LOG(TC_DBG) << "FWDing frame to " << vl->PeerInfo().vip4;
if(msg->message_id == MSGID_FWD_FRAME_RD)
{
frame->Initialize(frame->Payload(), frame->PayloadCapacity());
if(0 == tdev_->Read(*frame))
frame.release();
}
delete msg->pdata;
}
break;
}
}
void
VirtualNetwork::ProcessIncomingFrame(
uint8_t *,
uint32_t ,
VirtualLink &)
{
}
void
VirtualNetwork::TapReadComplete(
AsyncIo *)
{
}
void
VirtualNetwork::TapWriteComplete(
AsyncIo *)
{
}
void
VirtualNetwork::InjectFame(
string && data)
{
unique_ptr<TapFrame> tf = make_unique<TapFrame>();
tf->Initialize();
if(data.length() > 2 * kTapBufferSize)
{
stringstream oss;
oss << "Inject Frame operation failed - frame size " << data.length() / 2 <<
" is larger than maximum accepted " << kTapBufferSize;
throw TCEXCEPT(oss.str().c_str());
}
size_t len = StringToByteArray(data, tf->Payload(), tf->End());
if(len != data.length() / 2)
throw TCEXCEPT("Inject Frame operation failed - ICC decode failure");
tf->SetWriteOp();
tf->PayloadLength((uint32_t)len);
tf->BufferToTransfer(tf->Payload());
tf->BytesTransferred((uint32_t)len);
tf->BytesToTransfer((uint32_t)len);
tdev_->Write(*tf.release());
//LOG(TC_DBG) << "Frame injected=\n" << data;
}
} //namespace tincan
| [
"kcratie@users.noreply.github.com"
] | kcratie@users.noreply.github.com |
a946c079a3440b612b92e482817e846b4f0ac199 | 931544d66c832c092e0b0b0c6baabbecfe0d47d0 | /solutions/hackerrank/array-left-rotation.cpp | 7c87d26614d23ea86a62ffb37426ffbd3c7c7519 | [
"MIT"
] | permissive | rahulsah123/CodeMonk | 99f006e963d2618ad29987e690e275660877179c | 700d500b56566b63252a51bac8fe30949403d243 | refs/heads/master | 2020-06-13T01:07:37.147814 | 2016-11-27T17:16:40 | 2016-11-27T17:16:40 | 75,470,634 | 1 | 0 | null | 2016-12-03T11:50:46 | 2016-12-03T11:50:46 | null | UTF-8 | C++ | false | false | 799 | cpp | /**
* @author yangyanzhan
* @email yangyanzhan@gmail.com
* @homepage http://www.yangyanzhan.com
* @github_project https://github.com/yangyanzhan/CodeMonk
* @online_judge hackerrank
* @problem_id array-left-rotation
* @problem_address https://www.hackerrank.com/challenges/array-left-rotation
**/
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <iterator>
#include <map>
#include <queue>
#include <regex>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char *argv[]) {
int n, d;
cin >> n >> d;
int nums[n];
for (int i = 0; i < n; i++)
cin >> nums[i];
for (int i = 0; i < n; i++) {
cout << nums[(i + d) % n] << " ";
}
return 0;
}
| [
"yangyanzhan@gmail.com"
] | yangyanzhan@gmail.com |
8043c4205c720f0b9955915f3a6664b445e6bc24 | b4aee1d85320b398555b3782e872773044d4d685 | /practice/11.1/randwalk.cpp | 156aab4514fcfc05bd93b1236a896179e04c1394 | [] | no_license | crazyqipython/Cpp-primer-plus | 5a455ef0e16d461d963d659ff28a61eb27374269 | 0ebfe6feec17c5e920ff56b658464685cef26af1 | refs/heads/master | 2021-01-09T06:23:22.692388 | 2016-08-29T13:09:53 | 2016-08-29T13:09:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,737 | cpp | #include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include "vect.h"
int main()
{
using namespace std;
using VECTOR::Vector;
srand(time(0));
double direction;
Vector step;
Vector result(0.0, 0.0);
unsigned long steps = 0;
double target;
double dstep;
ofstream fout;
fout.open("the walk.txt");
cout << "Enter target distance (q to quit): ";
while (cin >> target)
{
cout << "Enter step length: ";
if (!(cin >> dstep)) break;
fout << "Target Distance: " << target
<< ", Step Size: " << dstep << endl;
while (result.magval() < target)
{
direction = rand() % 360;
step.reset(dstep, direction, Vector::POL);
result = result + step;
fout << steps << ": " << result << endl;
++steps;
}
cout << "After " << steps << " steps, the subject"
<< "has the following location:\n";
fout << "After " << steps << " steps, the subject"
<< "has the following location:\n";
cout << result << endl;
fout << result << endl;
result.polar_mode();
cout << " or\n" << result << endl;
fout << " or\n" << result << endl;
cout << "Average outward distance per step = "
<< result.magval() / steps << endl << endl;
fout << "Average outward distance per step = "
<< result.magval() / steps << endl << endl;
steps = 0;
result.reset(0.0, 0.0);
cout << "Enter target distance (q to quit): ";
}
cout << "Bye\n";
cin.clear();
while (cin.get() != '\n')
continue;
fout.close();
return 0;
}
| [
"hblee12294@gmail.com"
] | hblee12294@gmail.com |
158440f78aac2c4880d01eb933291266822cdba7 | 3285e052b9d7e492160c91116a698193a6337d28 | /Graphic_base/formgraph.cpp | 27b8a682f8f78ef79158fd1b608558c9da5e4738 | [] | no_license | Schuka48/Ghost | 483771b362fb4d11d7ed55bb8e45667526d77e8d | e9313ff359faba9e258d724839842f88231dc36d | refs/heads/main | 2023-06-21T20:04:33.462765 | 2021-07-21T15:18:52 | 2021-07-21T15:18:52 | 381,788,581 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,180 | cpp | #include "formgraph.h"
#include "ui_formgraph.h"
#include <QJsonDocument>
FormGraph::FormGraph(QWidget *parent) :
QWidget(parent), ui(new Ui::FormGraph),
_source(nullptr), connFlag(false)
{
ui->setupUi(this);
dlgInput = new DlgInput();
connect(ui->btnCreateNode, &QPushButton::clicked, this, &FormGraph::onBtnCreateNodeClicked);
connect(ui->btnConnectNode, &QPushButton::clicked, this, &FormGraph::onBtnConnectNodeClicked);
connect(ui->btnDelete, &QPushButton::clicked, this, &FormGraph::onBtnDeleteClicked);
connect(ui->grafViewScene->scene(), &QGraphicsScene::selectionChanged, this, &FormGraph::sceneSelectionChanged);
connect(dlgInput->btnApply, &QPushButton::clicked, this, &FormGraph::onBtnApplyClicked);
connect(ui->grafViewScene, &GraphWidget::editItem, this, &FormGraph::showInput);
}
FormGraph::~FormGraph()
{
ui->grafViewScene->scene()->clearSelection();
nodes.clear();
edges.clear();
delete ui;
delete dlgInput;
}
void FormGraph::closeEvent(QCloseEvent */*event*/)
{
dlgInput->close();
// Важно! disconnect нужен для корректного выхода из приложения!
disconnect(ui->grafViewScene->scene(), nullptr, nullptr, nullptr);
}
void FormGraph::showInput()
{
if (ui->grafViewScene->scene()->selectedItems().size() == 0) { // nullptr
// Ничего не выделено
dlgInput->lTipInput->clear();
dlgInput->eInput->clear();
//dlgInput->eInput->setEnabled(false);
dlgInput->hide();
} else {
QGraphicsItem *it;
it = ui->grafViewScene->scene()->selectedItems().at(0);
//dlgInput->eInput->setEnabled(true);
if (Node *n = dynamic_cast<Node *>(it)) {
dlgInput->lTipInput->setText("Введите текст");
dlgInput->eInput->setText(n->textContent());
} else if (EdgeParent *e = dynamic_cast<EdgeParent *>(it)) {
dlgInput->lTipInput->setText("Введи текст");
dlgInput->eInput->setText(e->textContent());
}
//dlgInput->show();
//dlgInput->raise();
//dlgInput->activateWindow();
dlgInput->exec();
}
}
void FormGraph::onBtnCreateNodeClicked()
{
ui->btnConnectNode->setChecked(false);
int x, y; // расположение вершины на сцене
int numNode = 0;
bool flFinding = false; // флаг нахождения, при решение с каким состоянием создавать вершину
Node *node;
node = new Node(ui->grafViewScene);
numNode = node->id();
// Определяет сколько вершин будут появлятся на одной оси У
int nodeInRow = 6;
x = - 2 * (2 * Node::Radius + 10) +
((!flFinding ? numNode : nodes.size()) % nodeInRow)
* (2 * Node::Radius + 10);
y = -100 + 2 * Node::Radius + 10 +
((!flFinding ? numNode : nodes.size()) / nodeInRow)
* (2 * Node::Radius + 10);
nodes.append(node);
node->setPos(x, y);
_source = nullptr;
connFlag = 0;
ui->lTip->setText("Добавлена вершина.");
if (nodes.size()==9){
ui->btnCreateNode->setEnabled(false);
}
}
void FormGraph::onBtnConnectNodeClicked()
{
if (ui->grafViewScene->scene()->selectedItems().size() > 0) {
_source = dynamic_cast<Node *> (ui->grafViewScene->scene()->selectedItems().at(0));
if (_source) {
ui->grafViewScene->scene()->clearSelection();
ui->lTip->setText("Выберите, куда будет проведена дуга.");
connFlag = 2;
} else {
ui->lTip->clear();
connFlag = 0;
}
}
/* if (!_source) {
if (connFlag == 0) { // это условие не обязательное
lTip->setText("Выберите вершину источник, потом получатель дуги");
connFlag = 1;
grafViewScene->scene()->clearSelection();
}
}*/
}
void FormGraph::onBtnDeleteClicked()
{
if (ui->grafViewScene->scene()->selectedItems().size()) {
_source = nullptr;
connFlag = 0;
auto i = ui->grafViewScene->scene()->selectedItems().at(0);
if (Node* n = dynamic_cast<Node*>(i)) {
foreach (auto e, n->edges()) {
edges.removeAll(e);
}
if (n) {
nodes.removeAll(n);
} else {
qDebug() << "dynamic_cast returned 0";
}
ui->btnCreateNode->setEnabled(true);
ui->lTip->setText("Вершина удалена.");
} else if (EdgeParent *e = dynamic_cast<EdgeParent*>(i)) {
if (e) {
edges.removeAll(e);
} else {
qDebug() << "dynamic_cast returned 0";
}
ui->lTip->setText("Дуга удалена.");
} else {
qDebug() << tr("I don't know what it is. type == %1").arg(i->type());
}
ui->grafViewScene->scene()->removeItem(i);
delete i;
}
}
void FormGraph::eInputTextChange()
{
if(dlgInput->eInput->text().size() != 0 && dlgInput->eInput->hasAcceptableInput()) {
dlgInput->btnApply->setEnabled(true);
} else {
dlgInput->btnApply->setEnabled(false);
}
}
void FormGraph::onBtnApplyClicked()
{
if (dlgInput->eInput->hasAcceptableInput()){
if (ui->grafViewScene->scene()->selectedItems().size() != 1) {
qDebug() << "grafViewScene->scene()->selectedItems().size() == "
<< ui->grafViewScene->scene()->selectedItems().size();
return;
}
auto it = ui->grafViewScene->scene()->selectedItems().at(0);
NodeEdgeParent *nodeEdge = dynamic_cast<NodeEdgeParent*>(it);
if (nodeEdge) {
nodeEdge->setTextContent(dlgInput->eInput->text());
} else { // if (it->type() == Edge::Type) {
qDebug() << "It does not NodeEdgeParent";
}
dlgInput->hide();
} else {
dlgInput->lTipInput->setText("Неверный формат.");
}
}
void FormGraph::sceneSelectionChanged()
{
dlgInput->hide();
QList<QGraphicsItem *> l = ui->grafViewScene->scene()->selectedItems();
if (l.size() == 1) {
ui->lTip->setText("Выделена вершина.");
if (Node *node = dynamic_cast<Node *>(l.at(0))) {
// Выделена вершина!
ui->btnConnectNode->setEnabled(true);
if (connFlag == 1) {
// Назначен "Источник"
_source = node;
connFlag = 2;
ui->lTip->setText("Выберите вершину куда будет проведена дуга.");
} else if (connFlag == 2) {
// Нужно соединить с новой вершиной
EdgeParent *e;
if (_source == node) {
e = new EdgeCircle(_source);
} else {
e = new Edge(_source, node);
}
edges.append(e);
ui->btnConnectNode->setChecked(false);
connFlag = 0;
_source = nullptr;
} else if (connFlag==3){
}
} else {
// Выделена стрелка
ui->lTip->setText("Выделена дуга.");
ui->btnConnectNode->setEnabled(false);
connFlag = false;
_source = nullptr;
}
ui->btnDelete->setEnabled(true);
} else if (l.size() > 1) {
// Всегда должено быть выделено не более 1ого элемента
qDebug() << "grafViewScene->scene()->selectedItems().size() == " << l.size();
} else {
// Пропало выделение (после удаления или нажатия на "Соединить")
ui->lTip->setText("");
ui->btnDelete->setEnabled(false);
ui->btnConnectNode->setEnabled(false);
}
}
void FormGraph::savePng(QString fileName) const
{
QPixmap pixMap = QPixmap::grabWidget(ui->grafViewScene);
pixMap.save(fileName);
}
bool FormGraph::saveGraph(QString fileName, bool jsonFormat) const
{
QFile saveFile(fileName);
if (!saveFile.open(QIODevice::WriteOnly)) {
qWarning("Couldn't open save file.");
return false;
}
QJsonObject graphJson;
// automat->writeToJson(graphJson); // automat
ui->grafViewScene->writeToJson(graphJson); // scene
QJsonArray jsonNodes;
std::for_each(nodes.begin(), nodes.end(), [&] (Node *n) {
QJsonObject json;
n->writeToJson(json);
jsonNodes.append(json); });
graphJson["nodes"] = jsonNodes; // nodes
QJsonArray jsonEdges;
std::for_each(edges.begin(), edges.end(), [&] (EdgeParent *e) {
QJsonObject json;
e->writeToJson(json);
jsonEdges.append(json); });
graphJson["edges"] = jsonEdges; // edges
QJsonDocument saveDoc(graphJson);
saveFile.write(jsonFormat ?
saveDoc.toJson()
: saveDoc.toBinaryData());
saveFile.close();
return true;
}
void FormGraph::keyPressEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_Delete:
onBtnDeleteClicked();
break;
case Qt::Key_N:
case 1058:
onBtnCreateNodeClicked();
break;
case Qt::Key_C:
case 1057:
onBtnConnectNodeClicked();
break;
default:
break;
}
QWidget::keyPressEvent(event);
}
FormGraph *FormGraph::openGraph(QString fileName, bool jsonFormat) {
QFile loadFile(fileName);
if (!loadFile.open(QIODevice::ReadOnly)) {
qWarning("Couldn't open graph file.");
return nullptr;
}
QByteArray saveData = loadFile.readAll();
QJsonDocument loadDoc(jsonFormat ?
QJsonDocument::fromJson(saveData)
: QJsonDocument::fromBinaryData(saveData));
const QJsonObject json = loadDoc.object(); // тут всё
FormGraph *g = new FormGraph;
g->ui->grafViewScene->readFromJson(json); // scene
if (missKeys(json, QStringList { "nodes", "edges" })) {
delete g;
return nullptr;
}
QJsonArray jsonNodes = json["nodes"].toArray();
std::for_each(jsonNodes.begin(), jsonNodes.end(), [&] (QJsonValue j) {
Node *n = new Node(g->ui->grafViewScene);
n->readFromJson(j.toObject());
g->nodes.append(n);
});
QJsonArray jsonEdges = json["edges"].toArray();
std::for_each(jsonEdges.begin(), jsonEdges.end(), [&] (QJsonValue j) {
EdgeParent *e = EdgeParent::create(j.toObject(), g->ui->grafViewScene);
g->edges.append(e);
});
g->ui->btnConnectNode->setEnabled(false);
g->ui->btnDelete->setEnabled(false);
return g;
}
| [
"artem.shchukin.2000@mail.ru"
] | artem.shchukin.2000@mail.ru |
7bfb7731f842553cd1c512716a0cb1ea41896e38 | e64de6e15e83104511203b19cddf533ab0b83858 | /test/parser-util.h | 0e10b83ba26b2c6a4b9e27afba687a176c20c9c0 | [] | no_license | brn/yatsc | 49b998ed4a55795fd28bd6a6a3964957e1740316 | d3fe64ea4b979ef93c9239b46bc8f9672faabe98 | refs/heads/master | 2021-01-01T19:00:44.883959 | 2015-03-30T00:53:09 | 2015-03-30T00:53:09 | 20,675,007 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,810 | h | /*
* The MIT License (MIT)
*
* Copyright (c) 2013 Taketoshi Aono(brn)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "../src/ir/node.h"
#include "../src/parser/parser.h"
#include "../src/parser/literalbuffer.h"
#include "../src/parser/error-reporter.h"
#include "../src/parser/error-formatter.h"
#include "../src/parser/error-descriptor.h"
#include "../src/utils/stl.h"
#include "../src/utils/notificator.h"
#include "./compare-node.h"
#include "./unicode-util.h"
bool print_stack_trace = true;
bool compare_node = true;
#define PARSER_TEST(name, method_expr, type, code, expected_str, error) { int line_num = __LINE__; \
YatscParserTest(name, [&](yatsc::Parser<yatsc::SourceStream::iterator>* p){return p->method_expr;}, type, code, expected_str, error, line_num); \
}
#define WRAP_PARSER_TEST(name, method_expr, type, code, expected_str, error) { int line_num = __LINE__; \
YatscParserTest(name, [&](yatsc::Parser<yatsc::SourceStream::iterator>* p){return p->method_expr;}, type, code, expected_str, error, line_num); \
}
template <typename T>
void YatscParserTest(const char* name,
T fn,
yatsc::LanguageMode type,
const char* code,
const char* expected_str,
bool error,
int line_num) {
using namespace yatsc;
typedef yatsc::SourceStream::iterator Iterator;
auto module_info = Heap::NewHandle<ModuleInfo>(String(name), String(code), true);
CompilerOption compiler_option;
compiler_option.set_language_mode(type);
auto lb = Heap::NewHandle<yatsc::LiteralBuffer>();
auto global_scope = Heap::NewHandle<yatsc::ir::GlobalScope>(lb);
auto irfactory = Heap::NewHandle<ir::IRFactory>();
Scanner<Iterator> scanner(module_info->source_stream()->begin(), module_info->source_stream()->end(), lb.Get(), compiler_option);
Notificator<void(const yatsc::String&)> notificator;
Parser<Iterator> parser(compiler_option, &scanner, notificator, irfactory, module_info, global_scope);
ErrorFormatter error_formatter(module_info);
ParseResult result;
try {
result = fn(&parser);
} catch(const FatalParseError& fpe) {}
if (!error) {
if (!module_info->HasError() && result && result.value() && compare_node) {
yatsc::testing::CompareNode(line_num, result.value()->ToStringTree(), yatsc::String(expected_str));
} else {
if (print_stack_trace) {
parser.PrintStackTrace();
}
error_formatter.Print(stderr, module_info->error_reporter());
}
} else {
ASSERT_TRUE(module_info->error_reporter()->HasError());
}
print_stack_trace = true;
compare_node = true;
}
| [
"dobaw20@gmail.com"
] | dobaw20@gmail.com |
2dce4897b7da98d999fca1c1983f4a8c41c82376 | de4a7f00df913bec160e91e2b255e41d0518eabe | /http_asio/connection.cpp | 119da6267fa189f914d3673bb21ebadd3a542452 | [] | no_license | octocat9lee/practical-network-programming | 67fd7b923d3826461b7aa3c4f77ff3be67614781 | 66707ed0523254cebe62baad6fdf4856857125f7 | refs/heads/master | 2021-05-12T06:44:36.494923 | 2019-03-08T04:00:33 | 2019-03-08T04:00:33 | 117,224,864 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,994 | cpp | //
// connection.cpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2010 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "connection.h"
#include <vector>
#include <boost/bind.hpp>
#include "request_handler.h"
namespace http
{
namespace server2
{
connection::connection(boost::asio::io_service& io_service,
request_handler& handler)
: socket_(io_service),
request_handler_(handler)
{
}
boost::asio::ip::tcp::socket& connection::socket()
{
return socket_;
}
void connection::start()
{
socket_.async_read_some(boost::asio::buffer(buffer_),
boost::bind(&connection::handle_read, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void connection::handle_read(const boost::system::error_code& e,
std::size_t bytes_transferred)
{
if(!e)
{
boost::tribool result;
boost::tie(result, boost::tuples::ignore) = request_parser_.parse(
request_, buffer_.data(), buffer_.data() + bytes_transferred);
if(result)
{
request_handler_.handle_request(request_, reply_);
boost::asio::async_write(socket_, reply_.to_buffers(),
boost::bind(&connection::handle_write, shared_from_this(),
boost::asio::placeholders::error));
}
else if(!result)
{
reply_ = reply::stock_reply(reply::bad_request);
boost::asio::async_write(socket_, reply_.to_buffers(),
boost::bind(&connection::handle_write, shared_from_this(),
boost::asio::placeholders::error));
}
else
{
socket_.async_read_some(boost::asio::buffer(buffer_),
boost::bind(&connection::handle_read, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
}
// If an error occurs then no new asynchronous operations are started. This
// means that all shared_ptr references to the connection object will
// disappear and the object will be destroyed automatically after this
// handler returns. The connection class's destructor closes the socket.
}
void connection::handle_write(const boost::system::error_code& e)
{
if(!e)
{
// Initiate graceful connection closure.
boost::system::error_code ignored_ec;
socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec);
}
// No new asynchronous operations are started. This means that all shared_ptr
// references to the connection object will disappear and the object will be
// destroyed automatically after this handler returns. The connection class's
// destructor closes the socket.
}
} // namespace server2
} // namespace http | [
"295861542@qq.com"
] | 295861542@qq.com |
c4a725819c6e4da2f55dcf678a198a64f2ee3de1 | de841c20a88755e0a90d32add9948bb1c2f86f1c | /SimpleGame/SimpleGame/Classes/GameOverScene.cpp | 6cd09a2561d53bd7650205b00a7c5f7fc25b4f53 | [] | no_license | childhood/Cocos2dxLib | bad07deceb2408757ee29a8165a154e32e0d6113 | 9aecf86921df191ec1a5695546d4d517f92063b9 | refs/heads/master | 2020-12-25T04:35:49.859848 | 2012-03-08T16:09:49 | 2012-03-08T16:09:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,165 | cpp | //
// GameOverScene.m
// SimpleGame
//
// Created by kdanmobile09 on 12-3-8.
// Copyright 2012年 __MyCompanyName__. All rights reserved.
//
#import "GameOverScene.h"
#import"HelloWorldScene.h"
CCScene* GameOverScene::scene()
{
CCScene *scene = CCScene::node();
GameOverScene *layer = GameOverScene::node();
scene->addChild(layer);
return scene;
}
GameOverScene::~GameOverScene()
{
}
bool GameOverScene::init()
{
if (!CCLayerColor::initWithColor(ccc4(255, 255, 255, 255))) {
return false;
}
this->setLabel(CCLabelTTF::labelWithString("11", "Arial", 32));
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
this->getLabel()->setPosition(ccp(winSize.width / 2.0f, winSize.height / 2.0f));
this->getLabel()->setColor(ccc3(0, 0, 0));
this->addChild(_label);
_label->runAction(CCSequence::actions(CCDelayTime::actionWithDuration(3.0f),CCCallFunc::actionWithTarget(this, callfunc_selector(GameOverScene::gameOverDone)),NULL));
return true;
}
void GameOverScene::gameOverDone()
{
CCDirector::sharedDirector()->replaceScene(HelloWorld::scene());
}
| [
"guanghui8827@126.com"
] | guanghui8827@126.com |
93ef035a42a7ba146d4a0abfd7af4ed709b3c046 | 415b65fc161ca9dc99b99c409c039864471fe131 | /Customer/customer.h | 878346d9a3241ca321624621166184245d207e12 | [] | no_license | Austin0077/Cpp | c87bf9e9821d729faea328eeec8215209e18ed0c | 862753680a83d12d86b877e6de8baee74d3fc1c3 | refs/heads/master | 2021-09-03T23:06:14.455575 | 2018-01-12T18:20:29 | 2018-01-12T18:20:29 | 105,043,560 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 288 | h | # include<iostream>
#include <string>
using namespace std;
class Customer
{
private:
int Id;
string Fname;
string Sname;
double Credit;
public:
void setid(int);
void setFname(string);
void setSname(string);
void setCredit(double);
void Display();
};
| [
"austinqweyu@gmail.com"
] | austinqweyu@gmail.com |
4e785bee270622fff1f27aa657fb53efd679a9e2 | f47b84753c54723afa751f08060b1dab39b9bd0d | /src/goto-diff/change_impact.cpp | 381cbd7e3be2fac8d99b338d7d70458a2a044ae8 | [
"BSD-4-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | pkesseli-archive/cbmc-legacy | 9d8fac56c56902cd3bc22216c37f220699348c0a | 81f06d59850db7fc2603f06d54a8736d8c596194 | refs/heads/master | 2021-05-01T17:42:37.368349 | 2016-08-12T14:04:10 | 2016-08-12T14:04:10 | 52,523,903 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,335 | cpp | /*******************************************************************\
Module: Data and control-dependencies of syntactic diff
Author: Michael Tautschnig
Date: April 2016
\*******************************************************************/
#include <iostream>
#include <goto-programs/goto_model.h>
#include <analyses/dependence_graph.h>
#include "unified_diff.h"
#include "change_impact.h"
#if 0
struct cfg_nodet
{
cfg_nodet():node_required(false)
{
}
bool node_required;
#ifdef DEBUG_FULL_SLICERT
std::set<unsigned> required_by;
#endif
};
typedef cfg_baset<cfg_nodet> cfgt;
cfgt cfg;
typedef std::vector<cfgt::entryt> dep_node_to_cfgt;
typedef std::stack<cfgt::entryt> queuet;
inline void add_to_queue(
queuet &queue,
const cfgt::entryt &entry,
goto_programt::const_targett reason)
{
#ifdef DEBUG_FULL_SLICERT
cfg[entry].required_by.insert(reason->location_number);
#endif
queue.push(entry);
}
/*******************************************************************\
Function: full_slicert::operator()
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void full_slicert::operator()(
goto_functionst &goto_functions,
const namespacet &ns,
slicing_criteriont &criterion)
{
// build the CFG data structure
cfg(goto_functions);
// fill queue with according to slicing criterion
queuet queue;
// gather all unconditional jumps as they may need to be included
jumpst jumps;
// declarations or dead instructions may be necessary as well
decl_deadt decl_dead;
for(cfgt::entry_mapt::iterator
e_it=cfg.entry_map.begin();
e_it!=cfg.entry_map.end();
e_it++)
{
if(criterion(e_it->first))
add_to_queue(queue, e_it->second, e_it->first);
else if(implicit(e_it->first))
add_to_queue(queue, e_it->second, e_it->first);
else if((e_it->first->is_goto() && e_it->first->guard.is_true()) ||
e_it->first->is_throw())
jumps.push_back(e_it->second);
else if(e_it->first->is_decl())
{
const exprt &s=to_code_decl(e_it->first->code).symbol();
decl_dead[to_symbol_expr(s).get_identifier()].push(e_it->second);
}
else if(e_it->first->is_dead())
{
const exprt &s=to_code_dead(e_it->first->code).symbol();
decl_dead[to_symbol_expr(s).get_identifier()].push(e_it->second);
}
}
// compute program dependence graph (and post-dominators)
dependence_grapht dep_graph(ns);
dep_graph(goto_functions, ns);
// compute the fixedpoint
fixedpoint(goto_functions, queue, jumps, decl_dead, dep_graph);
// now replace those instructions that are not needed
// by skips
Forall_goto_functions(f_it, goto_functions)
if(f_it->second.body_available())
{
Forall_goto_program_instructions(i_it, f_it->second.body)
{
const cfgt::entryt &e=cfg.entry_map[i_it];
if(!i_it->is_end_function() && // always retained
!cfg[e].node_required)
i_it->make_skip();
#ifdef DEBUG_FULL_SLICERT
else
{
std::string c="ins:"+i2string(i_it->location_number);
c+=" req by:";
for(std::set<unsigned>::const_iterator
req_it=cfg[e].required_by.begin();
req_it!=cfg[e].required_by.end();
++req_it)
{
if(req_it!=cfg[e].required_by.begin()) c+=",";
c+=i2string(*req_it);
}
i_it->source_location.set_column(c); // for show-goto-functions
i_it->source_location.set_comment(c); // for dump-c
}
#endif
}
}
// remove the skips
remove_skip(goto_functions);
goto_functions.update();
}
/*******************************************************************\
Function: full_slicert::fixedpoint
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void full_slicert::fixedpoint(
goto_functionst &goto_functions,
queuet &queue,
jumpst &jumps,
decl_deadt &decl_dead,
const dependence_grapht &dep_graph)
{
std::vector<cfgt::entryt> dep_node_to_cfg;
dep_node_to_cfg.reserve(dep_graph.size());
for(unsigned i=0; i<dep_graph.size(); ++i)
{
cfgt::entry_mapt::const_iterator entry=
cfg.entry_map.find(dep_graph[i].PC);
assert(entry!=cfg.entry_map.end());
dep_node_to_cfg.push_back(entry->second);
}
// process queue until empty
while(!queue.empty())
{
while(!queue.empty())
{
cfgt::entryt e=queue.top();
cfgt::nodet &node=cfg[e];
queue.pop();
// already done by some earlier iteration?
if(node.node_required)
continue;
// node is required
node.node_required=true;
// add data and control dependencies of node
add_dependencies(node, queue, dep_graph, dep_node_to_cfg);
// retain all calls of the containing function
add_function_calls(node, queue, goto_functions);
// find all the symbols it uses to add declarations
add_decl_dead(node, queue, decl_dead);
}
// add any required jumps
add_jumps(queue, jumps, dep_graph.cfg_post_dominators());
}
}
/*******************************************************************\
Function: full_slicert::add_dependencies
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void full_slicert::add_dependencies(
const cfgt::nodet &node,
queuet &queue,
const dependence_grapht &dep_graph,
const dep_node_to_cfgt &dep_node_to_cfg)
{
const dependence_grapht::nodet &d_node=
dep_graph[dep_graph[node.PC].get_node_id()];
for(dependence_grapht::edgest::const_iterator
it=d_node.in.begin();
it!=d_node.in.end();
++it)
add_to_queue(queue, dep_node_to_cfg[it->first], node.PC);
}
#endif
class change_impactt
{
public:
change_impactt(
const goto_modelt &model_old,
const goto_modelt &model_new);
void operator()();
protected:
const goto_functionst &old_goto_functions;
const namespacet ns_old;
const goto_functionst &new_goto_functions;
const namespacet ns_new;
unified_difft unified_diff;
dependence_grapht old_dep_graph;
dependence_grapht new_dep_graph;
typedef enum
{
SAME=0,
NEW=1<<0,
DELETED=1<<1,
NEW_DATA_DEP=1<<2,
DEL_DATA_DEP=1<<3,
NEW_CTRL_DEP=1<<4,
DEL_CTRL_DEP=1<<5
} mod_flagt;
typedef std::map<goto_programt::const_targett, unsigned>
goto_program_change_impactt;
typedef std::map<irep_idt, goto_program_change_impactt>
goto_functions_change_impactt;
goto_functions_change_impactt old_change_impact, new_change_impact;
void change_impact(const irep_idt &function);
void change_impact(
const goto_programt &old_goto_program,
const goto_programt &new_goto_program,
const unified_difft::goto_program_difft &diff,
goto_program_change_impactt &old_impact,
goto_program_change_impactt &new_impact);
void output_change_impact(
const irep_idt &function,
const goto_program_change_impactt &c_i,
const goto_functionst &goto_functions,
const namespacet &ns) const;
void output_change_impact(
const irep_idt &function,
const goto_program_change_impactt &o_c_i,
const goto_functionst &o_goto_functions,
const namespacet &o_ns,
const goto_program_change_impactt &n_c_i,
const goto_functionst &n_goto_functions,
const namespacet &n_ns) const;
};
/*******************************************************************\
Function: change_impactt::change_impactt
Inputs:
Outputs:
Purpose:
\*******************************************************************/
change_impactt::change_impactt(
const goto_modelt &model_old,
const goto_modelt &model_new):
old_goto_functions(model_old.goto_functions),
ns_old(model_old.symbol_table),
new_goto_functions(model_new.goto_functions),
ns_new(model_new.symbol_table),
unified_diff(model_old, model_new),
old_dep_graph(ns_old),
new_dep_graph(ns_new)
{
// syntactic difference?
if(!unified_diff())
return;
// compute program dependence graph of old code
old_dep_graph(old_goto_functions, ns_old);
// compute program dependence graph of new code
new_dep_graph(new_goto_functions, ns_new);
}
/*******************************************************************\
Function: change_impactt::change_impact
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void change_impactt::change_impact(const irep_idt &function)
{
unified_difft::goto_program_difft diff;
unified_diff.get_diff(function, diff);
if(diff.empty())
return;
goto_functionst::function_mapt::const_iterator old_fit=
old_goto_functions.function_map.find(function);
goto_functionst::function_mapt::const_iterator new_fit=
new_goto_functions.function_map.find(function);
goto_programt empty;
const goto_programt &old_goto_program=
old_fit==old_goto_functions.function_map.end() ?
empty :
old_fit->second.body;
const goto_programt &new_goto_program=
new_fit==new_goto_functions.function_map.end() ?
empty :
new_fit->second.body;
change_impact(
old_goto_program,
new_goto_program,
diff,
old_change_impact[function],
new_change_impact[function]);
}
/*******************************************************************\
Function: change_impactt::change_impact
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void change_impactt::change_impact(
const goto_programt &old_goto_program,
const goto_programt &new_goto_program,
const unified_difft::goto_program_difft &diff,
goto_program_change_impactt &old_impact,
goto_program_change_impactt &new_impact)
{
goto_programt::const_targett o_it=
old_goto_program.instructions.begin();
goto_programt::const_targett n_it=
new_goto_program.instructions.begin();
for(const auto &d : diff)
{
switch(d.second)
{
case unified_difft::differencet::SAME:
assert(o_it!=old_goto_program.instructions.end());
assert(n_it!=new_goto_program.instructions.end());
old_impact[o_it]|=SAME;
++o_it;
assert(n_it==d.first);
new_impact[n_it]|=SAME;
++n_it;
break;
case unified_difft::differencet::DELETED:
assert(o_it!=old_goto_program.instructions.end());
assert(o_it==d.first);
{
const dependence_grapht::nodet &d_node=
old_dep_graph[old_dep_graph[o_it].get_node_id()];
for(dependence_grapht::edgest::const_iterator
it=d_node.in.begin();
it!=d_node.in.end();
++it)
{
goto_programt::const_targett src=
old_dep_graph[it->first].PC;
if(it->second.get()==dep_edget::DATA ||
it->second.get()==dep_edget::BOTH)
old_change_impact[src->function][src]|=DEL_DATA_DEP;
else
old_change_impact[src->function][src]|=DEL_CTRL_DEP;
}
for(dependence_grapht::edgest::const_iterator
it=d_node.out.begin();
it!=d_node.out.end();
++it)
{
goto_programt::const_targett src=
old_dep_graph[it->first].PC;
if(it->second.get()==dep_edget::DATA ||
it->second.get()==dep_edget::BOTH)
old_change_impact[src->function][src]|=DEL_DATA_DEP;
else
old_change_impact[src->function][src]|=DEL_CTRL_DEP;
}
}
old_impact[o_it]|=DELETED;
++o_it;
break;
case unified_difft::differencet::NEW:
assert(n_it!=new_goto_program.instructions.end());
assert(n_it==d.first);
{
const dependence_grapht::nodet &d_node=
new_dep_graph[new_dep_graph[n_it].get_node_id()];
for(dependence_grapht::edgest::const_iterator
it=d_node.in.begin();
it!=d_node.in.end();
++it)
{
goto_programt::const_targett src=
new_dep_graph[it->first].PC;
if(it->second.get()==dep_edget::DATA ||
it->second.get()==dep_edget::BOTH)
new_change_impact[src->function][src]|=NEW_DATA_DEP;
else
new_change_impact[src->function][src]|=NEW_CTRL_DEP;
}
for(dependence_grapht::edgest::const_iterator
it=d_node.out.begin();
it!=d_node.out.end();
++it)
{
goto_programt::const_targett dst=
new_dep_graph[it->first].PC;
if(it->second.get()==dep_edget::DATA ||
it->second.get()==dep_edget::BOTH)
new_change_impact[dst->function][dst]|=NEW_DATA_DEP;
else
new_change_impact[dst->function][dst]|=NEW_CTRL_DEP;
}
}
new_impact[n_it]|=NEW;
++n_it;
break;
}
}
}
/*******************************************************************\
Function: change_impactt::operator()
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void change_impactt::operator()()
{
// sorted iteration over intersection(old functions, new functions)
typedef std::map<irep_idt,
goto_functionst::function_mapt::const_iterator>
function_mapt;
function_mapt old_funcs, new_funcs;
forall_goto_functions(it, old_goto_functions)
old_funcs.insert(std::make_pair(it->first, it));
forall_goto_functions(it, new_goto_functions)
new_funcs.insert(std::make_pair(it->first, it));
function_mapt::const_iterator ito=old_funcs.begin();
for(function_mapt::const_iterator itn=new_funcs.begin();
itn!=new_funcs.end();
++itn)
{
while(ito!=old_funcs.end() && ito->first<itn->first)
++ito;
if(ito!=old_funcs.end() && itn->first==ito->first)
{
change_impact(itn->first);
++ito;
}
}
goto_functions_change_impactt::const_iterator oc_it=
old_change_impact.begin();
for(goto_functions_change_impactt::const_iterator
nc_it=new_change_impact.begin();
nc_it!=new_change_impact.end();
++nc_it)
{
for( ;
oc_it!=old_change_impact.end() && oc_it->first<nc_it->first;
++oc_it)
output_change_impact(
oc_it->first,
oc_it->second,
old_goto_functions,
ns_old);
if(oc_it==old_change_impact.end() || nc_it->first<oc_it->first)
output_change_impact(
nc_it->first,
nc_it->second,
new_goto_functions,
ns_new);
else
{
assert(oc_it->first==nc_it->first);
output_change_impact(
nc_it->first,
oc_it->second,
old_goto_functions,
ns_old,
nc_it->second,
new_goto_functions,
ns_new);
++oc_it;
}
}
}
/*******************************************************************\
Function: change_impact::output_change_impact
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void change_impactt::output_change_impact(
const irep_idt &function,
const goto_program_change_impactt &c_i,
const goto_functionst &goto_functions,
const namespacet &ns) const
{
goto_functionst::function_mapt::const_iterator f_it=
goto_functions.function_map.find(function);
assert(f_it!=goto_functions.function_map.end());
const goto_programt &goto_program=f_it->second.body;
std::cout << "/** " << function << " **/\n";
forall_goto_program_instructions(target, goto_program)
{
goto_program_change_impactt::const_iterator c_entry=
c_i.find(target);
const unsigned mod_flags=
c_entry==c_i.end() ? SAME : c_entry->second;
char prefix;
// syntactic changes are preferred over data/control-dependence
// modifications
if(mod_flags==SAME)
prefix=' ';
else if(mod_flags&DELETED)
prefix='-';
else if(mod_flags&NEW)
prefix='+';
else if(mod_flags&NEW_DATA_DEP)
prefix='D';
else if(mod_flags&NEW_CTRL_DEP)
prefix='C';
else if(mod_flags&DEL_DATA_DEP)
prefix='d';
else if(mod_flags&DEL_CTRL_DEP)
prefix='c';
else
assert(false);
std::cout << prefix;
goto_program.output_instruction(ns, function, std::cout, target);
}
}
/*******************************************************************\
Function: change_impact::output_change_impact
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void change_impactt::output_change_impact(
const irep_idt &function,
const goto_program_change_impactt &o_c_i,
const goto_functionst &o_goto_functions,
const namespacet &o_ns,
const goto_program_change_impactt &n_c_i,
const goto_functionst &n_goto_functions,
const namespacet &n_ns) const
{
goto_functionst::function_mapt::const_iterator o_f_it=
o_goto_functions.function_map.find(function);
assert(o_f_it!=o_goto_functions.function_map.end());
const goto_programt &old_goto_program=o_f_it->second.body;
goto_functionst::function_mapt::const_iterator f_it=
n_goto_functions.function_map.find(function);
assert(f_it!=n_goto_functions.function_map.end());
const goto_programt &goto_program=f_it->second.body;
std::cout << "/** " << function << " **/\n";
goto_programt::const_targett o_target=
old_goto_program.instructions.begin();
forall_goto_program_instructions(target, goto_program)
{
goto_program_change_impactt::const_iterator o_c_entry=
o_c_i.find(o_target);
const unsigned old_mod_flags=
o_c_entry==o_c_i.end() ? SAME : o_c_entry->second;
if(old_mod_flags&DELETED)
{
std::cout << '-';
goto_program.output_instruction(
o_ns,
function,
std::cout,
o_target);
++o_target;
continue;
}
goto_program_change_impactt::const_iterator c_entry=
n_c_i.find(target);
const unsigned mod_flags=
c_entry==n_c_i.end() ? SAME : c_entry->second;
char prefix;
// syntactic changes are preferred over data/control-dependence
// modifications
if(mod_flags==SAME)
{
if(old_mod_flags==SAME)
prefix=' ';
else if(old_mod_flags&DEL_DATA_DEP)
prefix='d';
else if(old_mod_flags&DEL_CTRL_DEP)
prefix='c';
else
assert(false);
++o_target;
}
else if(mod_flags&DELETED)
assert(false);
else if(mod_flags&NEW)
prefix='+';
else if(mod_flags&NEW_DATA_DEP)
{
prefix='D';
assert(old_mod_flags==SAME ||
old_mod_flags&DEL_DATA_DEP ||
old_mod_flags&DEL_CTRL_DEP);
++o_target;
}
else if(mod_flags&NEW_CTRL_DEP)
{
prefix='C';
assert(old_mod_flags==SAME ||
old_mod_flags&DEL_DATA_DEP ||
old_mod_flags&DEL_CTRL_DEP);
++o_target;
}
else
assert(false);
std::cout << prefix;
goto_program.output_instruction(n_ns, function, std::cout, target);
}
for( ;
o_target!=old_goto_program.instructions.end();
++o_target)
{
goto_program_change_impactt::const_iterator o_c_entry=
o_c_i.find(o_target);
const unsigned old_mod_flags=
o_c_entry==o_c_i.end() ? SAME : o_c_entry->second;
char prefix;
// syntactic changes are preferred over data/control-dependence
// modifications
if(old_mod_flags==SAME)
assert(false);
else if(old_mod_flags&DELETED)
prefix='-';
else if(old_mod_flags&NEW)
assert(false);
else if(old_mod_flags&DEL_DATA_DEP)
prefix='d';
else if(old_mod_flags&DEL_CTRL_DEP)
prefix='c';
else
assert(false);
std::cout << prefix;
goto_program.output_instruction(o_ns, function, std::cout, o_target);
}
}
/*******************************************************************\
Function: change_impact
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void change_impact(
const goto_modelt &model_old,
const goto_modelt &model_new)
{
change_impactt c(model_old, model_new);
c();
}
| [
"peter.schrammel@cs.ox.ac.uk"
] | peter.schrammel@cs.ox.ac.uk |
79c771f8062a9908ca3fcb7cfb360e1f4d875931 | ae86cda3dbbfe821694b0d59e0c9b8d83cc4aacc | /Practicas/PFinal/letras/src/diccionario.cpp | 0801c428bd0d8f30109d64d4a334ad0512bdb786 | [
"MIT"
] | permissive | josepadial/ED | 1624376d0d8fbe4923d23c6c2e14fd8faa07fea6 | c095e65843e695e05cbb4d0ae34652d223c45425 | refs/heads/master | 2020-08-11T03:57:35.319909 | 2020-04-05T18:39:40 | 2020-04-05T18:39:40 | 214,486,158 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,950 | cpp | /*
Curso: 2018/2019
Asignatura: Estructura de datos
Autores: Jose Antonio Padial Molina
Elena Ortiz Moreno
Practica: Final "Letras"
*/
#include "diccionario.h"
istream& operator>>(istream &is, Diccionario &dic){
string aux;
while(getline(is,aux)){
dic.datos.insert(aux);
}
return is;
}
ostream& operator<<(ostream &os, const Diccionario &dic){
Diccionario::const_iterator it = dic.begin();
while(it != dic.end()){
os << *it << endl;
it++;
}
return os;
}
int Diccionario::getApariciones(const char c){
int apariciones=0;
iterator it = begin();
while(it != end()){
string aux = *it;
for(int i = 0; i < aux.size(); i++){
if(aux.at(i) == c){
apariciones++;
}
}
it++;
}
return apariciones;
}
int Diccionario::getTotalLetras(){
int apariciones=0;
iterator it = begin();
while(it != end()){
string aux = *it;
apariciones += aux.size();
it++;
}
return apariciones;
}
vector<string> Diccionario::palabrasLongitud(int longitud){
vector<string> palabras;
for (iterator it_dic = begin(); it_dic != end(); ++it_dic){
if ((*it_dic).size() == longitud)
palabras.push_back(*it_dic);
}
return palabras;
}
vector<string> Diccionario::palabrasCon(const string &p){
iterator it = begin();
vector<string> v;
string aux;
while(it != end()){
aux = *it;
if(aux.find(p) != -1)
v.push_back(aux);
it++;
}
return v;
}
Diccionario& Diccionario::operator=(const Diccionario &dic){
if(this != &dic)
datos = dic.datos;
return *this;
}
string Diccionario::operator[](int n){
string s = "";
if(n >= 0 && n < datos.size()){
iterator it = datos.begin();
for(int i = 0; it != datos.end() && i < n; i++,it++){}
s = *it;
}
return s;
} | [
"joseismael511@gmail.com"
] | joseismael511@gmail.com |
8ff3a3dc29e81cceed58f4f04d1c2b1300c64cfa | af52fd80f18ca6b33e5abff650f23bd437087e10 | /top4000/3163-pdftotext-2.1.6/pdftotext.cpp | 9f9e3ad3b61c32259dcec1762ce9494e604f3f16 | [
"MIT"
] | permissive | hpyproject/top4000-pypi-packages | 8338ee316ab073bfba022c4c0d3f24256b01bfc6 | 0cd919943a007f95f4bf8510e667cfff5bd059fc | refs/heads/master | 2023-05-11T22:26:04.188536 | 2021-06-03T09:56:00 | 2021-06-03T09:56:00 | 372,450,555 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,379 | cpp | #include <Python.h>
#include <poppler/cpp/poppler-document.h>
#include <poppler/cpp/poppler-global.h>
#include <poppler/cpp/poppler-page.h>
#include <algorithm>
#include <climits>
#include <string>
#include <vector>
static PyObject* PdftotextError;
typedef struct {
PyObject_HEAD
int page_count;
bool raw;
PyObject* data;
poppler::document* doc;
} PDF;
static void PDF_clear(PDF* self) {
self->page_count = 0;
self->raw = false;
delete self->doc;
self->doc = NULL;
Py_CLEAR(self->data);
}
static int PDF_set_raw(PDF* self, int raw) {
if (raw == 0) {
self->raw = false;
} else if (raw == 1) {
self->raw = true;
} else {
PyErr_Format(PyExc_ValueError, "a boolean is required");
return -1;
}
return 0;
}
static int PDF_load_data(PDF* self, PyObject* file) {
#if PY_MAJOR_VERSION >= 3
self->data = PyObject_CallMethod(file, "read", NULL);
#else
self->data = PyObject_CallMethod(file, (char*)"read", NULL);
#endif
if (self->data == NULL) {
return -1;
}
return 0;
}
static int PDF_create_doc(PDF* self) {
Py_ssize_t len;
char* buf;
if (PyBytes_AsStringAndSize(self->data, &buf, &len) < 0) {
return -1;
}
if (len > INT_MAX) {
PyErr_Format(PdftotextError, "invalid buffer length %zd", len);
return -1;
}
self->doc = poppler::document::load_from_raw_data(buf, (int)len);
if (self->doc == NULL) {
PyErr_Format(PdftotextError, "poppler error creating document");
return -1;
}
return 0;
}
static int PDF_unlock(PDF* self, char* password) {
if (self->doc->unlock(std::string(password), std::string(password))) {
PyErr_Format(PdftotextError, "failed to unlock document");
return -1;
}
return 0;
}
static int PDF_init(PDF* self, PyObject* args, PyObject* kwds) {
PyObject* pdf_file;
char* password = (char*)"";
int raw = 0;
static char* kwlist[] = {(char*)"pdf_file", (char*)"password", (char*)"raw", NULL};
PDF_clear(self);
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si", kwlist, &pdf_file, &password, &raw)) {
goto error;
}
if (PDF_set_raw(self, raw) < 0) {
goto error;
}
if (PDF_load_data(self, pdf_file) < 0) {
goto error;
}
if (PDF_create_doc(self) < 0) {
goto error;
}
if (PDF_unlock(self, password) < 0) {
goto error;
}
self->page_count = self->doc->pages();
return 0;
error:
PDF_clear(self);
return -1;
}
static void PDF_dealloc(PDF* self) {
PDF_clear(self);
Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject* PDF_read_page(PDF* self, int page_number) {
const poppler::page* page;
poppler::page::text_layout_enum layout_mode;
std::vector<char> page_utf8;
page = self->doc->create_page(page_number);
if (page == NULL) {
return PyErr_Format(PdftotextError, "poppler error creating page");
}
layout_mode = poppler::page::physical_layout;
if (self->raw) {
layout_mode = poppler::page::raw_order_layout;
}
#if POPPLER_CPP_AT_LEAST_0_58_0
page_utf8 = page->text(poppler::rectf(0, 0, 0, 0), layout_mode).to_utf8();
#else
// Workaround for poppler bug #94517, fixed in poppler 0.58.0, released 2017-09-01
const poppler::rectf rect = page->page_rect();
const int min = std::min(rect.left(), rect.top());
const int max = std::max(rect.right(), rect.bottom());
page_utf8 = page->text(poppler::rectf(min, min, max, max), layout_mode).to_utf8();
#endif
delete page;
return PyUnicode_DecodeUTF8(page_utf8.data(), page_utf8.size(), NULL);
}
static Py_ssize_t PDF_len(PyObject* obj) {
PDF* self = (PDF*)obj;
return self->page_count;
}
static PyObject* PDF_getitem(PyObject* obj, Py_ssize_t i) {
PDF* self = (PDF*)obj;
if (i < 0 || i >= self->page_count) {
return PyErr_Format(PyExc_IndexError, "index out of range");
}
return PDF_read_page(self, (int)i);
}
static PySequenceMethods PDF_sequence_methods = {
PDF_len, // sq_length (__len__)
0, // sq_concat
0, // sq_repeat
PDF_getitem, // sq_item (__getitem__)
};
static PyTypeObject PDFType = {
PyVarObject_HEAD_INIT(NULL, 0)
"pdftotext.PDF", // tp_name
sizeof(PDF), // tp_basicsize
0, // tp_itemsize
(destructor)PDF_dealloc, // tp_dealloc
0, // tp_print
0, // tp_getattr
0, // tp_setattr
0, // tp_reserved
0, // tp_repr
0, // tp_as_number
&PDF_sequence_methods, // tp_as_sequence
0, // tp_as_mapping
0, // tp_hash
0, // tp_call
0, // tp_str
0, // tp_getattro
0, // tp_setattro
0, // tp_as_buffer
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, // tp_flags
"PDF(pdf_file, password=\"\", raw=False)\n"
"\n"
"Args:\n"
" pdf_file: A file opened for reading in binary mode.\n"
" password: Unlocks the document, if required. Either the owner\n"
" password or the user password works.\n"
" raw: If True, page text is output in the order it appears in the\n"
" content stream, rather than in the order it appears on the\n"
" page.\n"
"\n"
"Example:\n"
" with open(\"doc.pdf\", \"rb\") as f:\n"
" pdf = PDF(f)\n"
" for page in pdf:\n"
" print(page)", // tp_doc
0, // tp_traverse
0, // tp_clear
0, // tp_richcompare
0, // tp_weaklistoffset
0, // tp_iter
0, // tp_iternext
0, // tp_methods
0, // tp_members
0, // tp_getset
0, // tp_base
0, // tp_dict
0, // tp_descr_get
0, // tp_descr_set
0, // tp_dictoffset
(initproc)PDF_init, // tp_init
};
#if POPPLER_CPP_AT_LEAST_0_30_0
static void do_nothing(const std::string&, void*) {}
#endif
#if PY_MAJOR_VERSION >= 3
static PyModuleDef pdftotextmodule = {
PyModuleDef_HEAD_INIT,
"pdftotext",
"Simple PDF text extraction.",
};
PyMODINIT_FUNC PyInit_pdftotext() {
PyObject* module;
PDFType.tp_new = PyType_GenericNew;
if (PyType_Ready(&PDFType) < 0) {
return NULL;
}
module = PyModule_Create(&pdftotextmodule);
if (module == NULL) {
return NULL;
}
Py_INCREF(&PDFType);
PyModule_AddObject(module, "PDF", (PyObject*)&PDFType);
PdftotextError = PyErr_NewExceptionWithDoc(
"pdftotext.Error", "PDF error.", NULL, NULL);
Py_INCREF(PdftotextError);
PyModule_AddObject(module, "Error", PdftotextError);
#if POPPLER_CPP_AT_LEAST_0_30_0
poppler::set_debug_error_function(do_nothing, NULL);
#endif
return module;
}
#else
PyMODINIT_FUNC initpdftotext() {
PyObject* module;
PDFType.tp_new = PyType_GenericNew;
if (PyType_Ready(&PDFType) < 0) {
return;
}
module = Py_InitModule3("pdftotext", NULL, "Simple PDF text extraction.");
if (module == NULL) {
return;
}
Py_INCREF(&PDFType);
PyModule_AddObject(module, "PDF", (PyObject*)&PDFType);
PdftotextError = PyErr_NewExceptionWithDoc(
(char*)"pdftotext.Error", (char*)"PDF error.", NULL, NULL);
Py_INCREF(PdftotextError);
PyModule_AddObject(module, "Error", PdftotextError);
#if POPPLER_CPP_AT_LEAST_0_30_0
poppler::set_debug_error_function(do_nothing, NULL);
#endif
}
#endif
| [
"anto.cuni@gmail.com"
] | anto.cuni@gmail.com |
bf4f97fe8ddaf060f64d90d9d0acdf243fb15212 | b800fcf6bc5b78a5f84c9da4c3bab74cb8693a3d | /pgm7/Wheat.cpp | a06326ab08129f75ebf0d3f319edae8dd2a947fb | [] | no_license | billymeli/CS311 | 15f3f42259cd5df0c2cf6cd1521c21456225569f | 47f4d26963a85f42b31b45bac71bf56837ec5227 | refs/heads/master | 2021-05-09T16:11:37.693620 | 2018-05-02T01:17:39 | 2018-05-02T01:17:39 | 119,101,152 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,317 | cpp | // File Name: Wheat.cpp
// Author: Billy Meli
// Student ID: w882x457
// Assignment Number: 7
#include <iostream>
#include <string>
#include "Wheat.hpp"
using namespace std;
namespace {
const double AVG_WEIGHT_PER_BUSHEL = 60.0;
const double IDEAL_MOISTURE_LEVEL = 13.5;
}
// Default constructor (initializes all member variables to 0)
Wheat::Wheat() : Grain()
{}
// Constructor allowing caller to specify sample's moisture level (%) and foreign material (%)
Wheat::Wheat(double moistureLevel, double foreignMaterial)
: Grain(moistureLevel, foreignMaterial)
{}
// returns a pointer pointing to a copy of the grain sample
Wheat* Wheat::clone() const
{
Wheat* clonePtr = new Wheat(this->moistureLevel, this->foreignMaterial);
return clonePtr;
}
// returns an integer representing the grain type
int Wheat::getTypeVal() const
{
int grainTypeVal = 1;
return grainTypeVal;
}
// returns string representing the grain type
string Wheat::getType() const
{
string grainType = "Wheat";
return grainType;
}
// Accessor to return grain's average test weight (lbs/bushel)
const double Wheat::getAverageTestWeight() const
{
return AVG_WEIGHT_PER_BUSHEL;
}
// Accessor to return grain's ideal moisture level (percent)
const double Wheat::getIdealMoistureLevel() const
{
return IDEAL_MOISTURE_LEVEL;
}
| [
"mstevebilly@yahoo.com"
] | mstevebilly@yahoo.com |
3fef0e346a3753fe53285831951acd515e45c13e | cccfb7be281ca89f8682c144eac0d5d5559b2deb | /components/history_clusters/core/history_clusters_db_tasks_unittest.cc | a48de270a04385b4258af1dbf8dda33dc7b3d5c8 | [
"BSD-3-Clause"
] | permissive | SREERAGI18/chromium | 172b23d07568a4e3873983bf49b37adc92453dd0 | fd8a8914ca0183f0add65ae55f04e287543c7d4a | refs/heads/master | 2023-08-27T17:45:48.928019 | 2021-11-11T22:24:28 | 2021-11-11T22:24:28 | 428,659,250 | 1 | 0 | BSD-3-Clause | 2021-11-16T13:08:14 | 2021-11-16T13:08:14 | null | UTF-8 | C++ | false | false | 2,579 | cc | // Copyright 2021 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 "components/history_clusters/core/history_clusters_db_tasks.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace history_clusters {
TEST(HistoryClustersDBTasksTest, BeginTimeCalculation) {
struct TestData {
base::Time::Exploded end_time_exploded;
base::Time::Exploded expected_begin_time_exploded;
} test_data[] = {
// Afternoon times yield a 4AM same day `begin_time`.
// 2013-10-11 at 5:30PM and 15 seconds and 400 milliseconds.
{
{2013, 10, 6, 11, 17, 30, 15, 400},
{2013, 10, 6, 11, 4, 0, 0, 0},
},
// Early afternoon times such as 2:00PM also yield 4AM the same day.
{
{2013, 10, 6, 11, 14, 0, 0, 0},
{2013, 10, 6, 11, 4, 0, 0, 0},
},
// Morning times like 10:15AM yield 4AM the day before.
{
{2013, 10, 6, 11, 10, 15, 0, 0},
{2013, 10, 5, 10, 4, 0, 0, 0},
},
// Early morning times such as 2:10AM also yield 4AM the day before.
// Just a sanity check here.
{
{2013, 10, 6, 11, 2, 10, 0, 0},
{2013, 10, 5, 10, 4, 0, 0, 0},
},
};
for (size_t i = 0; i < base::size(test_data); ++i) {
SCOPED_TRACE(base::StringPrintf("Testing case i=%d", int(i)));
auto& test_case = test_data[i];
ASSERT_TRUE(test_case.end_time_exploded.HasValidValues());
base::Time end_time;
ASSERT_TRUE(
base::Time::FromLocalExploded(test_case.end_time_exploded, &end_time));
base::Time begin_time =
GetAnnotatedVisitsToCluster::GetBeginTimeOnDayBoundary(end_time);
base::Time::Exploded begin_exploded;
begin_time.LocalExplode(&begin_exploded);
auto& expected_begin = test_case.expected_begin_time_exploded;
EXPECT_EQ(begin_exploded.year, expected_begin.year);
EXPECT_EQ(begin_exploded.month, expected_begin.month);
// We specifically ignore day-of-week, because it uses UTC, and we don't
// actually care about which day of the week it is.
EXPECT_EQ(begin_exploded.day_of_month, expected_begin.day_of_month);
EXPECT_EQ(begin_exploded.hour, expected_begin.hour);
EXPECT_EQ(begin_exploded.minute, expected_begin.minute);
EXPECT_EQ(begin_exploded.second, expected_begin.second);
EXPECT_EQ(begin_exploded.millisecond, expected_begin.millisecond);
}
}
} // namespace history_clusters
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
32f56ed8ee3266d588edc9f946f355b01579dae0 | a615c4057ddb49f14dca11a45947fdacfebb5c1c | /Graphics/XYQ/Sprite2.h | bf9376c518abae61c3bea2b69d4dfb0e8dd5a839 | [] | no_license | oceancx/XYQEngine | 6dae130cbb997f585fd9b2a5a8965c3d7fddc3cd | 6f93e788d5df2d34774f51f6cae2ff52b3024094 | refs/heads/master | 2021-01-12T04:44:34.328169 | 2017-02-28T13:23:18 | 2017-02-28T13:23:18 | 77,779,051 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 491 | h | #ifndef SPRITE2_H
#define SPRITE2_H
#include "../../defines.h"
#include <vector>
/*
一个动画序列组
*/
class Sprite2
{
public:
Sprite2();
~Sprite2();
int mGroupSize; //方向数
int mFrameSize; //帧数
int mWidth; //宽度
int mHeight; //高度
int mKeyX; //关键帧X
int mKeyY; //关键帧Y
struct Sequence
{
int key_x;
int key_y;
int width;
int height;
uint32 format;
uint32* src;
};
Sequence** mFrames;
void SaveImage(int index);
};
#endif | [
"oceancx@gmail.com"
] | oceancx@gmail.com |
f19b63ace7a50acef5ec5e3fef9f5bc8cd7d51c6 | ceeddddcf3e99e909c4af5ff2b9fad4a8ecaeb2a | /tags/release-1.5.2/source/Irrlicht/CQuake3ShaderSceneNode.h | 7ffc7b6d024aa58da8238832c8f45aa19b8cd5fe | [
"LicenseRef-scancode-other-permissive",
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | jivibounty/irrlicht | d9d6993bd0aee00dce2397a887b7f547ade74fbb | c5c80cde40b6d14fe5661440638d36a16b41d7ab | refs/heads/master | 2021-01-18T02:56:08.844268 | 2015-07-21T08:02:25 | 2015-07-21T08:02:25 | 39,405,895 | 0 | 0 | null | 2015-07-20T20:07:06 | 2015-07-20T20:07:06 | null | UTF-8 | C++ | false | false | 2,223 | h | // Copyright (C) 2002-2009 Nikolaus Gebhardt / Thomas Alten
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __C_QUAKE3_SCENE_NODE_H_INCLUDED__
#define __C_QUAKE3_SCENE_NODE_H_INCLUDED__
#include "ISceneNode.h"
#include "IQ3Shader.h"
#include "IFileSystem.h"
#include "SMeshBuffer.h"
#include "SMeshBufferLightMap.h"
namespace irr
{
namespace scene
{
//! Scene node which is a quake3 shader.
class CQuake3ShaderSceneNode : public scene::ISceneNode
{
public:
CQuake3ShaderSceneNode( ISceneNode* parent, ISceneManager* mgr,s32 id,
io::IFileSystem *fileSystem,IMeshBuffer *buffer,
const quake3::SShader * shader);
virtual ~CQuake3ShaderSceneNode();
virtual void OnRegisterSceneNode();
virtual void render();
virtual void OnAnimate(u32 timeMs);
virtual const core::aabbox3d<f32>& getBoundingBox() const;
virtual u32 getMaterialCount() const;
virtual video::SMaterial& getMaterial(u32 i);
private:
SMeshBuffer* MeshBuffer;
SMeshBufferLightMap* Original;
const quake3::SShader* Shader;
struct SQ3Texture
{
SQ3Texture () :
TextureIndex ( 0 ),
TextureFrequency(0.f),
TextureAddressMode( video::ETC_REPEAT ) {}
quake3::tTexArray Texture;
u32 TextureIndex;
f32 TextureFrequency;
video::E_TEXTURE_CLAMP TextureAddressMode; // Wrapping/Clamping
};
core::array< SQ3Texture > Q3Texture;
void loadTextures ( io::IFileSystem * fileSystem );
void cloneBuffer ( scene::SMeshBufferLightMap * buffer );
void vertextransform_wave ( f32 dt, quake3::SModifierFunction &function );
void vertextransform_bulge( f32 dt, quake3::SModifierFunction &function );
void vertextransform_autosprite( f32 dt, quake3::SModifierFunction &function );
void vertextransform_tcgen ( f32 dt, quake3::SModifierFunction &function );
void vertextransform_rgbgen ( f32 dt, quake3::SModifierFunction &function );
void transformtex ( const core::matrix4 &m, const u32 clamp );
f32 TimeAbs;
void animate( u32 stage, core::matrix4 &texture );
bool isTransparent() const;
};
} // end namespace scene
} // end namespace irr
#endif
| [
"hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475"
] | hybrid@dfc29bdd-3216-0410-991c-e03cc46cb475 |
f788cf77c7d4cd5cc276aaff0ddd69d3eb657494 | e60bec80c00cd484a5acec538bb9b419bce734a5 | /2023/tmb/scaa_mod_age_dir.cpp | 23962d734240af8390e4cf27c0b11b030e41e813 | [] | no_license | commfish/seak_sablefish | cd63c84c271765242abd3476880f80a9704576ee | 8828847b3f352b9b9a260b58dbf68cccce39a5b1 | refs/heads/master | 2023-09-01T01:31:42.213887 | 2023-08-23T17:37:30 | 2023-08-23T17:37:30 | 104,012,945 | 8 | 6 | null | 2023-01-10T18:55:16 | 2017-09-19T01:57:03 | R | UTF-8 | C++ | false | false | 61,566 | cpp |
// Sex-structured statistical catch-at-age model for NSEI sablefish that
// includes catch, fishery and survey CPUE, mark-recapture abundance estimates,
// fishery and survey weight-at-age, survey data about maturity-at-age and
// proportions-at-age, and fishery and survey age and length compositions.
// Original Author: Jane Sullivan, ummjane@gmail.com
// Current Driver: Phil Joy, philip.joy@alaska.gov
// Last updated March 2023
#include <TMB.hpp>
#include <numeric>
template <class Type> Type square(Type x){return x*x;}
// template <class Type> Type sumVec(vector<Type> vec){return std::accumulate(vec.begin(), vec.end(), 0.0);}
// template <class Type> Type mean(vector<Type> vec){return std::accumulate(vec.begin(), vec.end(), 0.0) / vec.size();}
template<class Type>
Type objective_function<Type>::operator() ()
{
// **DATA SECTION**
// Model dimensions
DATA_INTEGER(nyr) // number of years in the model (year indexed as i)
DATA_INTEGER(nage) // number of ages in the model (age indexed as j)
DATA_INTEGER(nsex) // controls whether model is sex-structured or not (sex indexed as k)
DATA_INTEGER(nlenbin) // number of length bins (indexed as l)
DATA_VECTOR(lenbin) // length bins
// Switch for recruitment estimate: 0 = penalized likelihood (fixed sigma_r), 1
// = random effects
DATA_INTEGER(random_rec)
// Switch for selectivity type: 0 = a50, a95 logistic; 1 = a50, slope logistic
DATA_INTEGER(slx_type)
// Swtich for age composition type (hopefully one day length too): 0 = multinomial; 1 = Dirichlet-multinomial
DATA_INTEGER(comp_type)
// Switch for assumption on SPR equilibrium recruitment. 0 = arithmetic mean
// (same as Federal assessment), 1 = geometric mean, 2 = median (2 not coded
// yet)
DATA_INTEGER(spr_rec_type)
// Prior for natural mortality
DATA_INTEGER(M_type) // switch to fix M (0) or estimate with prior (1)
DATA_SCALAR(p_log_M) // mean M=0.1
DATA_SCALAR(p_sigma_M) // CV or sigma = 0.1
// Time varying parameter blocks (indexed as h) - each vector contains the terminal years of
// each time block. Used for both selectivity and catchability
DATA_IVECTOR(fsh_blks) // fishery
DATA_IVECTOR(srv_blks) // survey
// Fixed parameters
DATA_ARRAY(dmr) // discard mortality in the fishery by year, age, and sex. assume constant dmr 0 or 0.16
DATA_ARRAY(retention) // probability of retaining a fish, sex- and age-based
// Fxx levels that correspond with log_spr_Fxx in Parameter section (indexed as x)
DATA_VECTOR(Fxx_levels) // e.g. F35=0.35, F40=0.40, and F50=0.50
// Priors ("p_" denotes prior)
DATA_VECTOR(p_fsh_q) // prior fishery catchability coefficient (on natural scale)
DATA_VECTOR(sigma_fsh_q) // sigma for fishery q
DATA_SCALAR(p_srv_q) // prior on survey catchability coefficient (on natural scale)
DATA_SCALAR(sigma_srv_q) // sigma for survey q
DATA_SCALAR(p_mr_q) // prior on mark-recapture catchability coefficient (on natural scale)
DATA_SCALAR(sigma_mr_q) // sigma for mark-recapture q
// Weights on likelihood componets("wt_" denotes weight)
DATA_SCALAR(wt_catch) // catch
DATA_SCALAR(wt_fsh_cpue) // fishery cpue
DATA_SCALAR(wt_srv_cpue) // soak survey
DATA_SCALAR(wt_mr) // mark-recapture abundance
DATA_SCALAR(wt_fsh_age) // fishery age comps
DATA_SCALAR(wt_srv_age) // survey age comps
DATA_SCALAR(wt_fsh_len) // fishery length comps
DATA_SCALAR(wt_srv_len) // survey length comps
DATA_SCALAR(wt_rec_like) // penalty on recruitment deviations
DATA_SCALAR(wt_fpen) // penality on fishing mortality deviations
DATA_SCALAR(wt_spr) // penalty on spawner per recruit calcs
// INDICES OF ABUNDANCE
// Catch
DATA_VECTOR(data_catch) // vector of landed catch estimates
DATA_VECTOR(sigma_catch) // assumed CV of 5% for catch
// Mark-recapture estimates
DATA_INTEGER(nyr_mr) // number of years
DATA_IVECTOR(yrs_mr) // vector of years
DATA_VECTOR(data_mr) // vector of estimates
DATA_VECTOR(sigma_mr) // posterior SDs for mark-recapture estimates
// Fishery cpue
DATA_INTEGER(nyr_fsh_cpue) // number of years
DATA_IVECTOR(yrs_fsh_cpue) // vector of years
DATA_VECTOR(data_fsh_cpue) // vector of estimates
DATA_VECTOR(sigma_fsh_cpue) // vector of fishery cpue SDs
// Survey cpue
DATA_INTEGER(nyr_srv_cpue) // number of years
DATA_IVECTOR(yrs_srv_cpue) // vector of years
DATA_VECTOR(data_srv_cpue) // vector of estimates
DATA_VECTOR(sigma_srv_cpue) // vector of survey cpue SDs
// BIOLOGICAL DATA
// Timing in months (e.g. January = 1/12 = 0.083)
DATA_SCALAR(spawn_month) // month when spawning occurs (February)
DATA_SCALAR(srv_month) // month when survey begins (July)
DATA_SCALAR(fsh_month) // month when fishery begins (August)
// Proportion mature at age (rows = 1, cols = nage); the rows could one day
// represent annual or time-varying maturity
DATA_MATRIX(prop_mature)
// Proportion female at age in the survey (all years combined) applied in
// calculation of spawning biomass. When nsex=2, the N matrix is
// already split by sex, so you don't need prop_fem in spawning biomass calculation
// (it will be a vector of 1's).
DATA_VECTOR(prop_fem)
// Sex ratio in survey (all years combined) used to split N matrix by sex.
// First row is males at age, second row is females at age. The underlying
// data underpins prop_fem and sex_ratio; this redundancy serves to
// accommodate single sex and sex-structured versions of this model. When
// nsex=1, the sex_ratio is a matrix of 1's so the N matrix doesn't get split
// by sex.
DATA_MATRIX(sex_ratio)
// Weight-at-age (rows = 1, all years combined; cols = nage; matrices = 0 for
// males, 1 for females); the rows could one day represent annual or
// time-varying weight-at-age
DATA_ARRAY(data_fsh_waa) // Fishery (sex-specific)
DATA_ARRAY(data_srv_waa) // Survey (sex-specific)
//std::cout << data_srv_waa << "\n";
// Fishery age comps
DATA_INTEGER(nyr_fsh_age) // number of years
DATA_IVECTOR(yrs_fsh_age) // vector of years
DATA_MATRIX(data_fsh_age) // matrix of observations (year, age)
DATA_VECTOR(n_fsh_age) // raw sample size for age comps
DATA_VECTOR(effn_fsh_age) // effective sample size
// Survey age comps
DATA_INTEGER(nyr_srv_age) // number of years
DATA_IVECTOR(yrs_srv_age) // vector of years
DATA_MATRIX(data_srv_age) // matrix of observations (year, age)
DATA_VECTOR(n_srv_age) // raw sample size for age comps
DATA_VECTOR(effn_srv_age) // effective sample size
// Fishery length comps
DATA_INTEGER(nyr_fsh_len) // number of years
DATA_IVECTOR(yrs_fsh_len) // vector of years
DATA_ARRAY(data_fsh_len) // observations (nyr, nlenbin, nsex)
DATA_ARRAY(n_fsh_len) // raw sample size for length comps (nyr, 1, nsex)
DATA_ARRAY(effn_fsh_len) // effective sample size (nyr, 1, nsex)
// Survey length comps
DATA_INTEGER(nyr_srv_len) // number of years
DATA_IVECTOR(yrs_srv_len) // vector of years
DATA_ARRAY(data_srv_len) // observations (nyr, nlenbin, nsex)
DATA_ARRAY(n_srv_len) // raw sample size for length comps (nyr, 1, nsex)
DATA_ARRAY(effn_srv_len) // effective sample size (nyr, 1, nsex)
// Ageing error transition matrix (proportion at reader age given true age)
DATA_MATRIX(ageing_error)
// Age-length transition matrices
DATA_ARRAY(agelen_key_fsh) // Fishery (nage, nlenbin, nsex)
DATA_ARRAY(agelen_key_srv) // Survey (nage, nlenbin, nsex)
// **PARAMETER SECTION**
// Dummy variable for troubleshooting
PARAMETER(dummy);
// Natural mortality
PARAMETER(log_M); // M_type = 0 is fixed, 1 is estimated
Type M = exp(log_M);
// Selectivity
PARAMETER_ARRAY(log_fsh_slx_pars); // Fishery selectivity (slx_type controls parameterization)
PARAMETER_ARRAY(log_srv_slx_pars); // Survey selectivity (slx_type controls parameterization)
// Catchability
PARAMETER_VECTOR(fsh_logq); // fishery
PARAMETER(srv_logq); // survey
PARAMETER(mr_logq); // mark-recapture
// Recruitment (rec_devs include a parameter for all ages in the inital yr plus age-2 in all yrs)
PARAMETER(log_rbar); // Mean recruitment
PARAMETER_VECTOR(log_rec_devs); // Annual recruitment deviations (formerly nyr+nage-2, now nyr)
PARAMETER(log_rinit); // Mean initial numbers-at-age in syr
PARAMETER_VECTOR(log_rinit_devs); // Age-specific deviations from log_rinit (nage-2)
PARAMETER(log_sigma_r); // Variability in rec_devs and rinits, only estimated when using random effects (random_rec=1)
// Fishing mortality
PARAMETER(log_Fbar); // Mean F on log scale
PARAMETER_VECTOR(log_F_devs); // Annual deviations from log_Fbar (nyr)
// SPR-based fishing mortality rates, i.e. the F at which the spawning biomass
// per recruit is reduced to xx% of its value in an unfished stock
PARAMETER_VECTOR(log_spr_Fxx); // e.g. F35, F40, F50
// Parameter related to effective sample size for Dirichlet-multinomial
// likelihood used for composition data. Eqn 11 in Thorson et al. 2017.
PARAMETER(log_fsh_theta); //ages... u
PARAMETER(log_srv_theta); //ages
// **DERIVED QUANTITIES**
// Predicted indices of catch and abundance
vector<Type> pred_catch(nyr); // Total catch biomass
vector<Type> pred_landed(nyr); // Landed catch biomass
vector<Type> pred_wastage(nyr); // Discarded biomass assumed dead
vector<Type> pred_mr(nyr_mr); // Mark-recapture index of abundance (only years with an estimate)
vector<Type> pred_mr_all(nyr); // Mark-recapture index of abundance (all years!)
vector<Type> pred_fsh_cpue(nyr_fsh_cpue); // Fishery cpue
vector<Type> pred_srv_cpue(nyr_srv_cpue); // Survey cpue
pred_catch.setZero();
pred_landed.setZero();
pred_wastage.setZero();
pred_mr.setZero();
pred_mr_all.setZero();
pred_fsh_cpue.setZero();
pred_srv_cpue.setZero();
// Predicted age compositions
matrix<Type> pred_fsh_age(nyr_fsh_age, nage); // Fishery (with ageing error)
matrix<Type> pred_srv_age(nyr_srv_age, nage); // Survey (with ageing error)
pred_fsh_age.setZero();
pred_srv_age.setZero();
// Predicted length compositions
array<Type> pred_fsh_obsage(nyr_fsh_len, nage, nsex); // Fishery (before age-length transition)
array<Type> pred_srv_obsage(nyr_srv_len, nage, nsex); // Survey (before age-length transition)
array<Type> pred_fsh_len(nyr_fsh_len, nlenbin, nsex); // Fishery
array<Type> pred_srv_len(nyr_srv_len, nlenbin, nsex); // Survey
pred_fsh_len.setZero();
pred_srv_len.setZero();
pred_fsh_obsage.setZero();
pred_srv_obsage.setZero();
// Predicted selectivity
array<Type> fsh_slx(nyr, nage, nsex); // Fishery selectivity-at-age by sex (on natural scale)
array<Type> srv_slx(nyr, nage, nsex); // Survey selectivity-at-age by sex(on natural scale)
fsh_slx.setZero();
srv_slx.setZero();
// Predicted annual fishing mortality
vector<Type> Fmort(nyr); // On natural scale
Fmort.setZero();
// Derived matrices by year, age, and sex
array<Type> N(nyr+1, nage, nsex); // Abundance-at-age, projected 1 year forward
array<Type> Z(nyr, nage, nsex); // Total mortality
array<Type> F(nyr, nage, nsex); // Fishing mortality
array<Type> S(nyr, nage, nsex); // Total survivorship (natural + fishing)
array<Type> C(nyr, nage, nsex); // Total catch in numbers
array<Type> L(nyr, nage, nsex); // Total landed catch in numbers
array<Type> D(nyr, nage, nsex); // Total discards in numbers assumed to die post-release
N.setZero();
Z.setZero();
F.setZero();
S.setZero();
C.setZero();
L.setZero();
D.setZero();
// Derived time series of recruitment, biomass, and abundance (+ projected values)
vector<Type> pred_rec(nyr); // Predicted age-2 recruitment
pred_rec.setZero();
array<Type> biom(nyr+1, nage, nsex); // Biomass by year, age, and sex, projected 1 year forward
vector<Type> tot_biom(nyr+1); // Summed over age and sex
biom.setZero();
tot_biom.setZero();
array<Type> expl_biom(nyr+1, nage, nsex); // Exploitable biomass to fishery at the beginning of the fishery, projected 1 year forward
array<Type> expl_abd(nyr+1, nage, nsex); // Exploitable abundance to fishery at the beginning of the fishery, projected 1 year forward
vector<Type> tot_expl_biom(nyr+1); // Summed over age and sex
vector<Type> tot_expl_abd(nyr+1); // Summed over age and sex
expl_biom.setZero();
tot_expl_biom.setZero();
expl_abd.setZero();
tot_expl_abd.setZero();
array<Type> vuln_abd(nyr+1, nage, nsex); // Vulnerable abundance to survey at the beginning of the survey, projected 1 year forward
vector<Type> tot_vuln_abd(nyr+1); // Summed over age and sex
vuln_abd.setZero();
tot_vuln_abd.setZero();
matrix<Type> spawn_biom(nyr+1, nage); // Spawning biomass, just females
vector<Type> tot_spawn_biom(nyr+1); // Summed over age
spawn_biom.setZero();
tot_spawn_biom.setZero();
// Other derived and projected values
array<Type> survival_srv(nyr, nage, nsex); // Survival at time of survey
array<Type> survival_fsh(nyr, nage, nsex); // Survival at time of fishery
array<Type> survival_spawn(nyr, nage, nsex); // Survival at time of spawning
Type pred_rbar; // Predicted mean recruitment
Type sigma_r = exp(log_sigma_r); // Estimated recruitment on natural scale
survival_srv.setZero();
survival_fsh.setZero();
survival_spawn.setZero();
// SPR-based equilibrium reference points
int n_Fxx = Fxx_levels.size(); // Number of Fs estimated
vector<Type> Fxx(n_Fxx + 1); // Separate Fxx vector that is scaled to fully selected values (+1 includes F=0)
matrix<Type> Nspr(n_Fxx + 1, nage); // Matrix of spawning numbers-at-age *FLAG* number of rows = number of estimated F_xx% (e.g. 3 = F35,F40,F50)
vector<Type> SBPR(n_Fxx + 1); // Spawning biomass per recruit at various fishing levels
vector<Type> SB(n_Fxx + 1); // Equilibrium spawning biomass at various fishing levels
Fxx.setZero();
Nspr.setZero();
SBPR.setZero();
SB.setZero();
// ABC calculation
array<Type> sel_Fxx(n_Fxx, nage, nsex); // Age-specific fully-selected fishing mortality at each Fxx%
array<Type> Z_Fxx(n_Fxx, nage, nsex); // Total mortality at each Fxx%
array<Type> S_Fxx(n_Fxx, nage, nsex); // Total survivorship at each Fxx%
matrix<Type> ABC(nyr+1, n_Fxx); // ABCs at each F_xx%, retrospectively estimated for past years
matrix<Type> wastage(nyr+1, n_Fxx); // Discarded catch assumed to die under each F_xx%, retrospectively estimated for past years
sel_Fxx.setZero();
Z_Fxx.setZero();
S_Fxx.setZero();
ABC.setZero();
wastage.setZero();
// Priors, likelihoods, offsets, and penalty functions
vector<Type> priors(3); // Priors for catchability coefficients
priors.setZero();
Type prior_M = 0; // Prior on natural mortality if estimated
Type catch_like = 0; // Catch
Type rec_like = 0; // Recruitment
Type fpen = 0; // Penality for Fmort regularity
Type spr_pen = 0; // Penality for SPR-based reference points
vector<Type> index_like(3); // Fishery cpue, survey cpue, MR estimates
index_like.setZero();
vector<Type> age_like(2); // Fishery and survey age comps
vector<Type> fsh_len_like(nsex); // Fishery length comps
vector<Type> srv_len_like(nsex); // Survey length comps
age_like.setZero();
fsh_len_like.setZero();
srv_len_like.setZero();
// Offset for multinomial distribution that lets likelihood equal zero when obs = pred
vector<Type> offset(2); // Age comps (both fsh and srv)
vector<Type> offset_fsh_len(nsex); // Fishery length comps (sex-specific)
vector<Type> offset_srv_len(nsex); // Survey length comp (sex-specific)
offset.setZero();
offset_fsh_len.setZero();
offset_srv_len.setZero();
Type obj_fun = 0; // Objective function
Type c = 0.00001; // Tiny constant to prevent likelihoods from going to 0
// **MODEL**
// Indexing: i = year, j = age, l = length bin, k = sex, h = time block, x = Fxx level
// Fishery selectivity
// Number of parameters in the chosen selectivity type:
int npar_slx = log_fsh_slx_pars.dim(1); // dim = array dimensions; 1 = # columns in array = # params in slx_type
// std::cout << npar_slx << "\n number of params for slx type\n";
// Preliminary calcs to bring parameters out of log space
array<Type> fsh_slx_pars(log_fsh_slx_pars.dim);
fsh_slx_pars.setZero();
for (int k = 0; k < nsex; k++) {
for (int h = 0; h < fsh_blks.size(); h++) {
for (int n = 0; n < npar_slx; n++) {
fsh_slx_pars(h,n,k) = exp(log_fsh_slx_pars(h,n,k));
}
}
}
// std::cout << fsh_slx_pars << "\n slx out of log space\n";
// Notes on the following syntax: the do while allows you to estimate parameters within a time block. It
// "does" the looping over year and age "while" within the time block, then
// iterates to the next block. Year is not in a for loop because it is
// iterated by the do statement.
// The switch for slx_type allows you to change parameterization. This could
// easily be expanded to accomodate any selectivity type (the fsh_slx_pars
// allows for a flexible number of parameters and time blocks)
int i = 0;
for(int h = 0; h < fsh_blks.size(); h++){
do{
for (int k = 0; k < nsex; k++) {
for (int j = 0; j < nage; j++) {
// Selectivity switch (case 0 or 1 references the value of slx_type)
switch (slx_type) {
case 0: // Logistic with a50 and a95, where fsh_slx_pars(h,0,k) = a50 and fsh_slx_pars(h,1,k) = a95
fsh_slx(i,j,k) = Type(1.0) / ( Type(1.0) + exp(-log(Type(19)) * (j - fsh_slx_pars(h,0,k)) / (fsh_slx_pars(h,1,k) - fsh_slx_pars(h,0,k))) );
break;
case 1: // Logistic with a50 and slope, where fsh_slx_pars(h,0,k) = a50 and fsh_slx_pars(h,1,k) = slope.
// *This is the preferred logistic parameterization b/c it reduces parameter correlation*
fsh_slx(i,j,k) = Type(1.0) / ( Type(1.0) + exp( Type(-1.0) * fsh_slx_pars(h,1,k) * (j - fsh_slx_pars(h,0,k)) ) );
break;
}
}
}
i++;
} while (i <= fsh_blks(h));
}
// std::cout << fsh_slx(1,1,1) << "\n Fishery selectivity \n";
// Survey selectivity - see notes on syntax in fishery selectivity section
// Preliminary calcs to bring parameters out of log space
array<Type> srv_slx_pars(log_srv_slx_pars.dim);
srv_slx_pars.setZero();
for (int k = 0; k < nsex; k++) {
for (int h = 0; h < srv_blks.size(); h++) {
for (int n = 0; n < npar_slx; n++) {
srv_slx_pars(h,n,k) = exp(log_srv_slx_pars(h,n,k));
}
}
}
i = 0; // re-set i to 0 (do not redeclare)
for(int h = 0; h < srv_blks.size(); h++){
do{
for (int k = 0; k < nsex; k++) {
for (int j = 0; j < nage; j++) {
// Selectivity switch (case 0 or 1 references the value of slx_type)
switch (slx_type) {
case 0: // Logistic with a50 and a95, where srv_slx_pars(h,0,k) = a50 and srv_slx_pars(h,1,k) = a95
srv_slx(i,j,k) = Type(1.0) / ( Type(1.0) + exp(-log(Type(19)) * (j - srv_slx_pars(h,0,k)) / (srv_slx_pars(h,1,k) - fsh_slx_pars(h,0,k))) );
break;
case 1: // Logistic with a50 and slope, where srv_slx_pars(h,0,k) = a50 and srv_slx_pars(h,1,k) = slope.
// *This is the preferred logistic parameterization b/c it reduces parameter correlation*
srv_slx(i,j,k) = Type(1.0) / ( Type(1.0) + exp( Type(-1.0) * srv_slx_pars(h,1,k) * (j - srv_slx_pars(h,0,k)) ) );
break;
}
}
}
i++;
} while (i <= srv_blks(h));
}
// std::cout << srv_slx << "\n Survey selectivity \n";
// Mortality and survivorship
for (int i = 0; i < nyr; i++) {
Fmort(i) = exp(log_Fbar + log_F_devs(i)); // Total annual fishing mortality
}
for (int k = 0; k < nsex; k++) {
for (int i = 0; i < nyr; i++) {
for (int j = 0; j < nage; j++) {
// Fishing mortality by year, age, and sex. If discard mortality (dmr)
// and retention probability = 1, this eqn collapses to Fmort(i) *
// fsh_slx(i,j,k)
F(i,j,k) = Fmort(i) * fsh_slx(i,j,k) * (retention(0,j,k) + dmr(i,j,k) * (Type(1.0) - retention(0,j,k)));
// Total mortality by year, age, and sex
Z(i,j,k) = M + F(i,j,k);
// Survivorship by year, age, and sex
S(i,j,k) = exp(Type(-1.0) * Z(i,j,k));
}
}
}
// std::cout << Fmort << "\n";
// std::cout << F << "\n";
// std::cout << Z << "\n";
// std::cout << S << "\n";
// Survival at time of survey, fishery, and spawning (fraction
// surviving from beginning of year to the time of survey and fishery). These
// quantities have the flexibility to vary by year, age, or sex, but currently
// do not. Includes F because this model assumes continuous F.
for (int k = 0; k < nsex; k++) {
for (int i = 0; i < nyr; i++) {
for (int j = 0; j < nage; j++) {
survival_srv(i,j,k) = exp(Type(-1.0) * srv_month * (M + F(i,j,k)));
survival_fsh(i,j,k) = exp(Type(-1.0) * fsh_month * (M + F(i,j,k)));
survival_spawn(i,j,k) = exp(Type(-1.0) * spawn_month * (M + F(i,j,k)));
}
}
}
// std::cout << survival_srv << "\n";
// std::cout << survival_fsh << "\n";
// Abundance and recruitment
// Start year: initial numbers-at-age (sage + 1 to plus group - 1). *FLAG*
// Nijk here I've assumed the sex ratio from the survey. Could also use 0.5
// (assuming 50/50 sex ratio). Don't know what the standard practice is here.
for (int k = 0; k < nsex; k++) {
for (int j = 1; j < nage-1; j++) {
N(0,j,k) = exp(log_rinit - M * Type(j) + log_rinit_devs(j-1)) * Type(0.5); //sex_ratio(k,j);
}
}
// Start year: plus group *FLAG* sex ratio from survey or 50/50 or ?
for (int k = 0; k < nsex; k++) {
N(0,nage-1,k) = exp(log_rinit - M * Type(nage-1)) / (1 - exp(-M)) * Type(0.5); //sex_ratio(k,nage-1);
}
// Recruitment in all years (except the projected year) *FLAG* sex ratio from
// survey or 50/50 or ?
for (int k = 0; k < nsex; k++) {
for (int i = 0; i < nyr; i++) {
N(i,0,k) = exp(log_rbar + log_rec_devs(i)) * Type(0.5); //sex_ratio(k,0);
}
}
// Project remaining N matrix
for (int k = 0; k < nsex; k++) {
for (int i = 0; i < nyr; i++) {
for (int j=0; j < nage-1; j++) {
N(i+1,j+1,k) = N(i,j,k) * S(i,j,k); // S is total survivorship
}
}
}
// Plus group for start year + 1 to final year + 1 (sum of cohort survivors and
// surviving memebers of last year's plus group)
for (int k = 0; k < nsex; k++) {
for (int i = 0; i < nyr; i++) {
N(i+1,nage-1,k) += N(i,nage-1,k) * S(i,nage-1,k);
}
}
// Projected recruitment (average over recent 15 years, excluding most recent
// 2 years), where the indexing of log_rec_devs(0,nyr+nage-3) *FLAG* sex ratio from
// survey or 50/50 or ?
for (int k = 0; k < nsex; k++) {
for (int i = nyr-16; i <= nyr-2; i++) {
N(nyr,0,k) += exp(log_rbar + log_rec_devs(i)) * Type(0.5); //sex_ratio(k,0);
}
N(nyr,0,k) /= Type(15.0);
}
// FLAG - Alternative way using mean(). Want to find a way to sum() over
// vector
// vector<Type> tmp = exp(log_rbar + log_rec_devs(nyr+nage-3-16, nyr+nage-3-2));
// N(nyr,0) = mean(tmp);
// std::cout << N << "\n";
// In numbers-at-age: Total catch (C), landed catch (L), and discarded catch
// assumed to die (D). Currently assuming continuous F, but may want to add
// discrete F in the future. F is fully-selected, S is total survivorship. The
// 0 in data_srv_waa(0,j,k) is a place holder if you ever wanted time-varying
// weight-at-age.
for (int k = 0; k < nsex; k++) {
for (int i = 0; i < nyr; i++) {
for (int j = 0; j < nage; j++) {
// Total catch in numbers and summed to get a total catch biomass by year
C(i,j,k) = N(i,j,k) * F(i,j,k) * (Type(1.0) - S(i,j,k)) / Z(i,j,k);
// Landed catch in numbers and summed to get total landed catch in
// biomass by year
L(i,j,k) = retention(0,j,k) * N(i,j,k) * F(i,j,k) * (Type(1.0) - S(i,j,k)) / Z(i,j,k);
pred_landed(i) += L(i,j,k) * data_fsh_waa(0,j,k) / Type(1e3) ; // in mt
// Discarded catch in numbers and summed to get total biomass of dead
// discards by year
D(i,j,k) = dmr(i,j,k) * (Type(1.0) - retention(0,j,k)) * N(i,j,k) * F(i,j,k) * (Type(1.0) - S(i,j,k)) / Z(i,j,k);
pred_wastage(i) += D(i,j,k) * data_srv_waa(0,j,k) / Type(1e3) ; // in mt
}
}
}
// Total catch summed to get a total catch biomass by year
for (int i = 0; i < nyr; i++) {
pred_catch(i) += pred_landed(i) + pred_wastage(i);
}
// std::cout << C << "\nTotal catch in numbers-at-age\n";
// std::cout << pred_catch << "\nPredicted total catch biomass\n"
// std::cout << L << "\nLanded catch in numbers-at-age\n";
// std::cout << pred_landed << "\nPredicted landed catch biomass\n"
// std::cout << D << "\nDead discards in numbers-at-age\n";
// std::cout << pred_wastage << "\nPredicted dead discarded biomass\n"
// Predicted recruitment by year, summed over the sexes
//for (int i = 0; i < nyr; i++) { // alternative approach... same answer.
// pred_rec(i) = exp(log_rbar + log_rec_devs(i));
// }
for (int k = 0; k < nsex; k++) {
for (int i = 0; i < nyr; i++) {
pred_rec(i) += N(i,0,k);
}
}
// std::cout << "Predicted recruitment\n" << pred_rec << "\n";
// Mean recruitment
Type len_rec = pred_rec.size();
Type sum_rec = 0; // temporary variable (sum over predicted recruitment values)
for (int i = 0; i < nyr; i++) {
sum_rec += pred_rec(i);
}
pred_rbar = sum_rec / len_rec;
// std::cout << "sum_rec\n" << sum_rec << "\n";
// std::cout << "pred_rbar\n" << pred_rbar << "\n";
// Various flavors of projected biomass estimates [Note: the 0 in
// data_srv_waa(0,j,k) and prop_mature(0,k) is a place holder if you ever
// wanted time blocks or annual variation in weight-at-age or maturity]
for (int k = 0; k < nsex; k++) {
for (int i = 0; i < nyr; i++) {
for (int j = 0; j < nage; j++) {
// Total biomass at time of longline survey
biom(i,j,k) = data_srv_waa(0,j,k) * N(i,j,k) * survival_srv(i,j,k);
// Exploitable biomass to the fishery at the beginning of the fishery
expl_biom(i,j,k) = data_srv_waa(0,j,k) * fsh_slx(i,j,k) * retention(0,j,k) * N(i,j,k) * survival_fsh(i,j,k);
// Exploitable abundance to the fishery at the beginning of the fishery
expl_abd(i,j,k) = fsh_slx(i,j,k) * retention(0,j,k) * N(i,j,k) * survival_fsh(i,j,k);
// Vulnerable abundance to the survey at the beginning of the survey
vuln_abd(i,j,k) = srv_slx(i,j,k) * N(i,j,k) * survival_srv(i,j,k);
}
}
}
// Project those values into the next year
for (int k = 0; k < nsex; k++) {
for (int j = 0; j < nage; j++) {
biom(nyr,j,k) = data_srv_waa(0,j,k) * N(nyr,j,k) * survival_srv(nyr-1,j,k);
expl_biom(nyr,j,k) = data_srv_waa(0,j,k) * fsh_slx(nyr-1,j,k) * retention(0,j,k) * N(nyr,j,k) * survival_fsh(nyr-1,j,k);
expl_abd(nyr,j,k) = fsh_slx(nyr-1,j,k) * retention(0,j,k) * N(nyr,j,k) * survival_fsh(nyr-1,j,k);
vuln_abd(nyr,j,k) = srv_slx(nyr-1,j,k) * N(nyr,j,k) * survival_srv(nyr-1,j,k);
}
}
// std::cout << "Predicted biomass by age and sex \n" << biom << "\n";
// std::cout << "Predicted exploited biomass by age and sex \n" << expl_biom << "\n";
// std::cout << "Predicted vulnerable abundance by age and sex \n" << vuln_abd << "\n";
// Sum variables to get an annual total
for (int k = 0; k < nsex; k++) {
for (int i = 0; i <= nyr; i++) { // include projection year
for (int j = 0; j < nage; j++) {
// Total biomass at time of longline survey
tot_biom(i) += biom(i,j,k);
// Exploitable biomass to the fishery at the beginning of the fishery
tot_expl_biom(i) += expl_biom(i,j,k);
// Exploitable abundance to the fishery at the beginning of the fishery
tot_expl_abd(i) += expl_abd(i,j,k);
// Vulnerable abundance to the survey at the beginning of the survey
tot_vuln_abd(i) += vuln_abd(i,j,k);
}
}
}
// std::cout << "Annual predicted biomass \n" << tot_biom << "\n";
// std::cout << "Annual predicted exploited biomass\n" << tot_expl_biom << "\n";
// std::cout << "Annual predicted vulnerable abundance\n" << tot_vuln_abd << "\n";
// Female spawning biomass: Calculated a little differently if model is
// single-sex or sex-structured
if (nsex == 1) {
// By year and age
for (int i = 0; i < nyr; i++) {
for (int j = 0; j < nage; j++) {
spawn_biom(i,j) = data_srv_waa(0,j,0) * N(i,j,0) * survival_spawn(i,j,0) * prop_fem(j) * prop_mature(0,j);
}
}
// Projected
for (int j = 0; j < nage; j++) {
spawn_biom(nyr,j) = data_srv_waa(0,j,0) * N(nyr,j,0) * survival_spawn(nyr-1,j,0) * prop_fem(j) * prop_mature(0,j);
}
// Annual totals, summed over age
for (int i = 0; i <= nyr; i++) { // include projection year
for (int j = 0; j < nage; j++) {
tot_spawn_biom(i) += spawn_biom(i,j);
}
}
}
if (nsex == 2) {
// By year and age
for (int i = 0; i < nyr; i++) {
for (int j = 0; j < nage; j++) {
spawn_biom(i,j) = data_srv_waa(0,j,1) * N(i,j,1) * survival_spawn(i,j,1) * prop_mature(0,j);
}
}
// Projected
for (int j = 0; j < nage; j++) {
spawn_biom(nyr,j) = data_srv_waa(0,j,1) * N(nyr,j,1) * survival_spawn(nyr-1,j,1) * prop_mature(0,j);
}
// Annual totals, summed over age
for (int i = 0; i <= nyr; i++) { // include projection year
for (int j = 0; j < nage; j++) {
tot_spawn_biom(i) += spawn_biom(i,j);
}
}
}
// std::cout << "Predicted spawning biomass by age\n" << spawn_biom << "\n";
// std::cout << "Annual predicted spawning biomass\n" << tot_spawn_biom << "\n";
// Predicted values
// Mark-recapture catchability and predicted abundance (in millions)
Type mr_q = exp(mr_logq);
for (int i = 0; i < nyr_mr; i++) {
pred_mr(i) = mr_q * (tot_expl_abd(yrs_mr(i)) / Type(1e6)); // Just in years with a MR estimate
}
// std::cout << "Predicted MR \n" << pred_mr << "\n";
for (int i = 0; i < nyr; i++) {
pred_mr_all(i) = mr_q * (tot_expl_abd(i) / Type(1e6)); // All years
}
// std::cout << "Predicted MR for all years\n" << pred_mr_all << "\n";
// Fishery catchability and predicted cpue - blocks for fishery correspond to
// pre- and post- Equal Quota Share
vector<Type> fsh_q(fsh_blks.size());
for (int h = 0; h < fsh_blks.size(); h++){
fsh_q(h) = exp(fsh_logq(h));
}
i = 0;
for(int h = 0; h < fsh_blks.size(); h++){
while (i < yrs_fsh_cpue.size() && yrs_fsh_cpue(i) <= fsh_blks(h)) {
pred_fsh_cpue(i) = fsh_q(h) * tot_expl_biom(yrs_fsh_cpue(i));
i++;
}
}
// std::cout << "Predicted fishery cpue\n" << pred_fsh_cpue << "\n";
// Survey catchability and predicted survey cpue
Type srv_q = exp(srv_logq);
for (int i = 0; i < nyr_srv_cpue; i++) {
pred_srv_cpue(i) = srv_q * tot_vuln_abd(yrs_srv_cpue(i));
}
// std::cout << "Predicted srv cpue\n" << pred_srv_cpue << "\n";
// Predicted fishery age compositions - for landed portion of the catch
// Temporary variables for age comp calcs
Type sumL = 0;
vector<Type> sumL_age(nage);
vector<Type> sumN_age(nage);
for (int i = 0; i < nyr_fsh_age; i++) {
// sumL = temporary variable, landed catch in numbers summed over age and
// sex in a given year
sumL = 0;
for (int k = 0; k < nsex; k++) {
for (int j = 0; j < nage; j++) {
sumL += L(yrs_fsh_age(i),j,k);
}
}
// sumL_age = temporary vector of landed catch in numbers by age in a given
// year (combine sexes since we currently do not have sex-structured age
// comps)
sumL_age.setZero();
for (int k = 0; k < nsex; k++) {
for (int j = 0; j < nage; j++) {
sumL_age(j) += L(yrs_fsh_age(i),j,k);
}
}
// Get predicted age comps (proportions-at-age)
for (int j = 0; j < nage; j++) {
pred_fsh_age(i,j) = sumL_age(j) / sumL;
}
// Loop over each year i
}
pred_fsh_age = pred_fsh_age * ageing_error; // apply ageing error matrix
// std::cout << "Predicted fishery age comps\n" << pred_fsh_age << "\n";
// Test do the predicted age comps sum to 1
// vector<Type> tst(nyr_fsh_age);
// for (int i = 0; i < nyr_fsh_age; i++) {
// for (int j = 0; j < nage; j++) {
// tst(i) += pred_fsh_age(i,j);
// }
// }
// std::cout << "Do the comps sum to 1?\n" << tst << "\n";
//
// Type tst_n = tst.size();
// std::cout << "Length of tst vector\n" << tst_n << "\n";
// Predicted survey age compositions
for (int i = 0; i < nyr_srv_age; i++) {
// sumN_age = temporary vector of catch in numbers by age in a given year
// (combine sexes since we currently do not have sex-structured age comps)
sumN_age.setZero();
for (int k = 0; k < nsex; k++) {
for (int j = 0; j < nage; j++) {
sumN_age(j) += vuln_abd(yrs_srv_age(i),j,k);
}
}
// Get predicted age comps (proportions-at-age)
for (int j = 0; j < nage; j++) {
pred_srv_age(i,j) = sumN_age(j) / tot_vuln_abd(yrs_srv_age(i));
}
// Loop over each year i
}
pred_srv_age = pred_srv_age * ageing_error; // apply ageing error matrix
// // Test do the predicted age comps sum to 1
// vector<Type> tst(nyr_srv_age);
// for (int i = 0; i < nyr_srv_age; i++) {
// for (int j = 0; j < nage; j++) {
// tst(i) += pred_srv_age(i,j);
// }
// }
// std::cout << "Do the age comps sum to 1?\n" << tst << "\n";
// Type tst_n = tst.size();
// std::cout << "Length of tst vector\n" << tst_n << "\n";
// FLAG - would like to know the TMB syntax to do the age comps in fewer
// lines, for example:
// for (int i = 0; i < nyr_srv_age; i++) {
// for (int j = 0; j < nage; j++) {
// pred_srv_age(i,j) = N(yrs_srv_age(i),j) * srv_slx(j) / sum(N(yrs_srv_age(i)) * srv_slx(j));
// }
// }
// Predicted fishery length compositions (for landed portion of catch)- *FLAG*
// early in development, would like to streamline
matrix<Type> sumL_jk(nage,nsex);
vector<Type> sumL_k(nsex);
for (int i = 0; i < nyr_fsh_len; i++) {
sumL_k.setZero(); // tmp variable for each year
sumL_jk.setZero();
for (int k = 0; k < nsex; k++) {
for (int j = 0; j < nage; j++) {
sumL_k(k) += L(yrs_fsh_len(i),j,k); // numbers by sex
sumL_jk(j,k) += L(yrs_fsh_len(i),j,k); // numbers by sex and age
}
}
for (int k = 0; k < nsex; k++) {
for (int j = 0; j < nage; j++) {
pred_fsh_obsage(i,j,k) = sumL_jk(j,k) / sumL_k(k); // Get predicted age comps (proportions-at-age)
}
}
}
matrix<Type> tmp_pred_fsh_obsage(nyr_fsh_len,nage);
matrix<Type> tmp_fsh_agelen(nage,nlenbin);
matrix<Type> tmp_pred_fsh_len(nyr_srv_len,nlenbin);
for (int k = 0; k < nsex; k++) {
tmp_pred_fsh_obsage.setZero();
for (int i = 0; i < nyr_fsh_len; i++) {
for (int j = 0; j < nage; j++) {
tmp_pred_fsh_obsage(i,j) = pred_fsh_obsage(i,j,k); // Extract nyr x nage matrix
}
}
tmp_fsh_agelen.setZero();
for (int j = 0; j < nage; j++) {
for (int l = 0; l < nlenbin; l++) {
tmp_fsh_agelen(j,l) = agelen_key_fsh(j,l,k); // Extract age-length key
}
}
tmp_pred_fsh_len.setZero();
tmp_pred_fsh_len = tmp_pred_fsh_obsage * tmp_fsh_agelen; // Apply age-length key
for (int i = 0; i < nyr_fsh_len; i++) {
for (int l = 0; l < nlenbin; l++) {
pred_fsh_len(i,l,k) = tmp_pred_fsh_len(i,l); // Put everything back in the arry
}
}
}
// Test do the initial observed age comps sum to 1
// vector<Type> tst2(nyr_fsh_len);
// for (int i = 0; i < nyr_fsh_len; i++) {
// for (int l = 0; l < nlenbin; l++) {
// tst2(i) += pred_fsh_len(i,l,0);
// }
// }
// std::cout << "Do the length comps sum to 1?\n" << tst2 << "\n";
// Predicted survey length compositions - *FLAG* would like to streamline this
matrix<Type> sumN_jk(nage,nsex);
vector<Type> sumN_k(nsex);
for (int i = 0; i < nyr_srv_len; i++) {
sumN_k.setZero(); // tmp variable for each year
sumN_jk.setZero();
for (int k = 0; k < nsex; k++) {
for (int j = 0; j < nage; j++) {
sumN_k(k) += vuln_abd(yrs_srv_len(i),j,k); // numbers by sex
sumN_jk(j,k) += vuln_abd(yrs_srv_len(i),j,k); // numbers by sex and age
}
}
for (int k = 0; k < nsex; k++) {
for (int j = 0; j < nage; j++) {
pred_srv_obsage(i,j,k) = sumN_jk(j,k) / sumN_k(k); // Get predicted age comps (proportions-at-age)
}
}
}
matrix<Type> tmp_pred_obsage(nyr_srv_len,nage);
matrix<Type> tmp_agelen(nage,nlenbin);
matrix<Type> tmp_pred_len(nyr_srv_len,nlenbin);
for (int k = 0; k < nsex; k++) {
tmp_pred_obsage.setZero();
for (int i = 0; i < nyr_srv_len; i++) {
for (int j = 0; j < nage; j++) {
tmp_pred_obsage(i,j) = pred_srv_obsage(i,j,k); // Extract nyr x nage matrix
}
}
tmp_agelen.setZero();
for (int j = 0; j < nage; j++) {
for (int l = 0; l < nlenbin; l++) {
tmp_agelen(j,l) = agelen_key_srv(j,l,k); // Extract age-length key
}
}
tmp_pred_len.setZero();
tmp_pred_len = tmp_pred_obsage * tmp_agelen; // Apply age-length key
for (int i = 0; i < nyr_srv_len; i++) {
for (int l = 0; l < nlenbin; l++) {
pred_srv_len(i,l,k) = tmp_pred_len(i,l); // Put everything back in the array
}
}
}
// Test do the initial observed age comps sum to 1
// vector<Type> tst3(nyr_srv_len);
// for (int i = 0; i < nyr_srv_len; i++) {
// for (int l = 0; l < nlenbin; l++) {
// tst3(i) += pred_srv_len(i,l,0);
// }
// }
// std::cout << "Do the length comps sum to 1?\n" << tst3 << "\n";
// Compute SPR rates and spawning biomass under different Fxx levels. Note
// that biological reference points are only for the female component of the
// population.
// Preliminary calcs, get Fs out of log space
vector<Type> spr_Fxx(n_Fxx+1);
spr_Fxx(0) = 0; // No fishing
for(int x = 1; x <= n_Fxx; x++) {
spr_Fxx(x) = exp(log_spr_Fxx(x-1));
}
// For SPR calculations, use only female fishery selectivity in the most recent time block for all calculations. The 'nsex-1' should work
// for both single sex and sex-structured versions
vector<Type> spr_fsh_slx(nage);
for (int j = 0; j < nage; j++) {
spr_fsh_slx(j) = fsh_slx(nyr-1,j,nsex-1);
}
// std::cout << "spr fishery selectivity\n" << spr_fsh_slx << "\n";
Fxx(0) = 0; // No fishing
// Scale Fxx to fully selected values (not necessary for logistic selectivity
// b/c max is 1 but may be needed for other selectivity types in future
// development).
for(int x = 1; x <= n_Fxx; x++) {
Fxx(x) = spr_Fxx(x) * max(spr_fsh_slx);
}
// std::cout << "Fxx\n" << Fxx << "\n";
// Populate numbers of potential spawners at age matrix - Note: for the Nspr
// and SBPR calculations, the Federal assessment uses the equivalent of
// spr_Fxx instead of the scales Fxx. Not sure why.
for(int x = 0; x <= n_Fxx; x++) {
Nspr(x,0) = Type(1.0); // Initialize SPR with 1
// Survival equation by age
for(int j = 1; j < nage - 1; j++) {
Nspr(x,j) = Nspr(x,j-1) * exp(Type(-1.0) * (Fxx(x) * spr_fsh_slx(j-1) + M));
}
// Plus group
Nspr(x,nage-1) = Nspr(x,nage-2) * exp(Type(-1.0) * (Fxx(x) * spr_fsh_slx(nage-2) + M)) /
(Type(1.0) - exp(Type(-1.0) * (Fxx(x) * spr_fsh_slx(nage-1) + M)));
}
// std::cout << "Number of spawners\n" << Nspr << "\n";
// Unfished spawning biomass per recruit
for(int j = 0; j < nage; j++) {
SBPR(0) += Nspr(0,j) * prop_mature(j) * data_srv_waa(0,j,1) * survival_spawn(nyr-1,j,nsex-1); //Type(0.5) *
}
// Remaining spawning biomass per recruit matrix
for(int x = 1; x <= n_Fxx; x++) {
for(int j = 0; j < nage; j++) {
if (nsex == 1) { // single sex model uses prop_fem vector
SBPR(x) += Nspr(x,j) * prop_mature(j) * data_srv_waa(0,j,1) * exp(Type(-1.0) * spawn_month * (M + Fxx(x) * spr_fsh_slx(j))); //prop_fem(j) *
}
if (nsex == 2) { // sex-structured model uses sex_ratio matrix
SBPR(x) += Nspr(x,j) * prop_mature(0,j) * data_srv_waa(0,j,1) * exp(Type(-1.0) * spawn_month * (M + Fxx(x) * spr_fsh_slx(j))); //sex_ratio(nsex-1,j) *
}
}
}
// std::cout << "Spawning biomass per recruit\n" << SBPR << "\n";
// Mean recruitment, where spr_rec_type is a switch for different assumptions
// of what the "mean" should be
Type mean_rec;
switch (spr_rec_type) {
case 0: // Arithmentic mean
mean_rec = 0;
for (int i = 0; i < nyr; i++) {
mean_rec += pred_rec(i);
}
mean_rec /= nyr;
break;
case 1: // Geometric mean
mean_rec = 1;
for (int i = 0; i < nyr; i++) {
mean_rec *= pred_rec(i);
}
mean_rec = pow(mean_rec, Type(1)/nyr);
break;
// case 2: // Median *FLAG* future development
}
// Virgin female spawning biomass (no fishing), assuming 50:50 sex ratio for
// recruitment (equivalent to B_100)
// SB(0) = SBPR(0) * mean_rec;
// Spawning biomass as a fraction of virgin spawning biomass - FLAG check this
// for(int x = 1; x <= n_Fxx; x++) {
// SB(x) = Fxx_levels(x-1) * SB(0);
// }
for(int x = 0; x <= n_Fxx; x++) {
SB(x) = Type(0.5) * SBPR(x) * mean_rec; //
}
// std::cout << "Spawning biomass\n" << SB << "\n";
// Get Allowable Biological Catch and wastage estimates for different Fxx levels: all of
// these should be sex-structured, then final ABC will be summed across sexes
for(int x = 0; x < n_Fxx; x++) {
for(int k = 0; k < nsex; k++) {
for(int j = 0; j < nage; j++) {
// Fully selected fishing mortality by age and sex. If discard mortality
// (dmr) and retention probability = 1, this eqn collapses to Fmort *
// fsh_slx)
sel_Fxx(x,j,k) = Fxx(x+1) * fsh_slx(nyr-1,j,k) * (retention(0,j,k) + dmr(nyr-1,j,k) * (Type(1.0) - retention(0,j,k)));
Z_Fxx(x,j,k) = M + sel_Fxx(x,j,k); // Total instantaneous mortality at age
S_Fxx(x,j,k) = exp(-Z_Fxx(x,j,k)); // Total survival at age
}
}
}
for(int i = 0; i <= nyr; i++) { // include forecast year
for(int x = 0; x < n_Fxx; x++) {
for(int k = 0; k < nsex; k++) {
for(int j = 0; j < nage; j++) {
// ABC calculation (landed catch under Fxx) using projected abundance
ABC(i,x) += data_srv_waa(0,j,k) * retention(0,j,k) * N(i,j,k) * sel_Fxx(x,j,k) * (Type(1.0) - S_Fxx(x,j,k)) / Z_Fxx(x,j,k);
// Discarded catch assumed to die under Fxx
wastage(i,x) += data_srv_waa(0,j,k) * dmr(nyr-1,j,k) * (Type(1.0) - retention(0,j,k)) * N(i,j,k) * sel_Fxx(x,j,k) * (Type(1.0) - S_Fxx(x,j,k)) / Z_Fxx(x,j,k);
}
}
}
}
// The final ABC is then the difference between the preliminary ABC and wastage estimates
for(int i = 0; i <= nyr; i++) {
for(int x = 0; x < n_Fxx; x++) {
ABC(i,x) = ABC(i,x) - wastage(i,x);
}
}
// std::cout << "ABC\n" << ABC << "\n";
// std::cout << "Wastage\n" << wastage << "\n";
// Get sex-specific numbers-at-length for Luke Rogers data request
array<Type> Nlen(nyr+1,nlenbin,nsex);
matrix<Type> tmp_N(nyr+1,nage);
matrix<Type> tmp_Nlen(nyr+1,nage);
// matrix<Type> tmp_agelen(nage,nlenbin); // already defined when predicting len comps
for (int k = 0; k < nsex; k++) {
tmp_N.setZero();
for (int i = 0; i < nyr+1; i++) {
for (int j = 0; j < nage; j++) {
tmp_N(i,j) = N(i,j,k); // Extract nyr+1 x nage matrix
}
}
tmp_agelen.setZero();
for (int j = 0; j < nage; j++) {
for (int l = 0; l < nlenbin; l++) {
tmp_agelen(j,l) = agelen_key_srv(j,l,k); // Extract sex-specific age-length key
}
}
tmp_Nlen.setZero();
tmp_Nlen = tmp_N * tmp_agelen; // Apply age-length key
for (int i = 0; i < nyr+1; i++) {
for (int l = 0; l < nlenbin; l++) {
Nlen(i,l,k) = tmp_Nlen(i,l); // Put everything into array
}
}
}
// Priors
// Fishery cpue catchability coefficient
for (int h = 0; h < fsh_blks.size(); h++){
priors(0) += square( log(fsh_q(h) / p_fsh_q(h)) ) / ( Type(2.0) * square(sigma_fsh_q(h)) );
}
// Survey catchability coefficient
priors(1) = square( log(srv_q / p_srv_q) ) / ( Type(2.0) * square(sigma_srv_q) );
// Mark-recapture abundance estimate catchability coefficient
priors(2) = square( log(mr_q / p_mr_q) ) / ( Type(2.0) * square(sigma_mr_q) );
// std::cout << "priors\n" << priors << "\n";
// Only calculate prior for M if estimated (M_type = 1), otherwise stays 0 and
// adds nothing to objective function
if(M_type == 1) {
prior_M += square(log_M - p_log_M) / (Type(2.0) * square(p_sigma_M));
}
// Catch: normal (check)
// for (int i = 0; i < nyr; i++) {
// catch_like += square( (data_catch(i) - pred_landed(i)) / pred_landed(i)) /
// (Type(2.0) * square(sigma_catch(i)));
// }
// Catch: lognormal
// for (int i = 0; i < nyr; i++) {
// catch_like += square( log((data_catch(i) + c) / (pred_landed(i) + c)) )/
// Type(2.0) * square(sigma_catch(i));
// }
// Catch: lognormal alternative (these should be equivalent)
for (int i = 0; i < nyr; i++) {
catch_like += square( log(data_catch(i) + c) - log(pred_landed(i) + c) )/
(Type(2.0) * square(sigma_catch(i)));
}
catch_like *= wt_catch; // Likelihood weight
// std::cout << "Catch likelihood\n" << catch_like << "\n";
// Fishery CPUE: lognormal
for (int i = 0; i < nyr_fsh_cpue; i++) {
index_like(0) += square( log((data_fsh_cpue(i) + c) / (pred_fsh_cpue(i) + c)) ) /
(Type(2.0) * square(sigma_fsh_cpue(i)));
}
index_like(0) *= wt_fsh_cpue; // Likelihood weight
// Survey CPUE: lognormal
for (int i = 0; i < nyr_srv_cpue; i++) {
index_like(1) += square( log((data_srv_cpue(i) + c) / (pred_srv_cpue(i) + c)) ) /
(Type(2.0) * square(sigma_srv_cpue(i)));
}
index_like(1) *= wt_srv_cpue; // Likelihood weight
// Mark-recapture index: lognormal
for (int i = 0; i < nyr_mr; i++) {
index_like(2) += square( log((data_mr(i) + c) / (pred_mr(i) + c)) ) /
(Type(2.0) * square(sigma_mr(i)));
}
index_like(2) *= wt_mr; // Likelihood weight
// std::cout << "Index likelihoods\n" << index_like << "\n";
// Likelihood for fishery age compositions
Type fsh_theta = exp(log_fsh_theta); // Dirichlet-multinomial parameter
vector<Type> sum1_fsh(nyr_fsh_age); // First sum in D-M likelihood (log of Eqn 10, Thorson et al. 2017)
vector<Type> sum2_fsh(nyr_fsh_age); // Second sum in D-M likelihood (log of Eqn 10, Thorson et al. 2017)
//fsh_theta.setZero();
sum1_fsh.setZero();
sum2_fsh.setZero();
// Switch for composition likelihood (case 0 or 1 references the value of comp_type)
switch (comp_type) {
case 0: // Multinomial
for (int i = 0; i < nyr_fsh_age; i++) {
for (int j = 0; j < nage; j++) {
// Offset
offset(0) -= effn_fsh_age(i) * (data_fsh_age(i,j) + c) * log(data_fsh_age(i,j) + c);
// Likelihood
age_like(0) -= effn_fsh_age(i) * (data_fsh_age(i,j) + c) * log(pred_fsh_age(i,j) + c);
}
}
age_like(0) -= offset(0); // subtract offset
age_like(0) *= wt_fsh_age; // likelihood weight
break;
case 1: // Dirichlet-multinomial (D-M)
for (int i = 0; i < nyr_fsh_age; i++) {
// Preliminary calcs
for (int j = 0; j < nage; j++) {
// First sum in D-M likelihood (log of Eqn 10, Thorson et al. 2017)
sum1_fsh(i) += lgamma( n_fsh_age(i) * data_fsh_age(i,j) + Type(1.0) );
// Second sum in D-M likelihood (log of Eqn 10, Thorson et al. 2017)
//sum2_fsh(i) += lgamma( n_fsh_age(i) + data_fsh_age(i,j) + fsh_theta * n_fsh_age(i) * pred_fsh_age(i,j) ) -
// lgamma( fsh_theta * n_fsh_age(i) - pred_fsh_age(i,j) );
sum2_fsh(i) += lgamma( n_fsh_age(i) * data_fsh_age(i,j) + fsh_theta * n_fsh_age(i) * pred_fsh_age(i,j) ) -
lgamma( fsh_theta * n_fsh_age(i) * pred_fsh_age(i,j) ); // second n_fsh_age(i) should be big N in Thorso which is not specified an may be a typo?
//sum2_fsh(i) += lgamma( n_fsh_age(i) * data_fsh_age(i,j) + fsh_theta * bigN * pred_fsh_age(i,j) ) -
// lgamma( fsh_theta * n_fsh_age(i) * pred_fsh_age(i,j) );
}
// Full nll for D-M, Eqn 10, Thorson et al. 2017
//age_like(0) -= lgamma(n_fsh_age(i) + Type(1.0)) - sum1_fsh(i) + lgamma(fsh_theta * n_fsh_age(i)) -
// lgamma(n_fsh_age(i) + fsh_theta * n_fsh_age(i)) + sum2_fsh(i);
age_like(0) -= lgamma(n_fsh_age(i) + Type(1.0)) - sum1_fsh(i) + lgamma(fsh_theta * n_fsh_age(i)) -
lgamma(n_fsh_age(i) + fsh_theta * n_fsh_age(i)) + sum2_fsh(i);
}
break;
// case 2: // Multivariate logistic (MVL) - future development
}
// Likelihood for survey age compositions
Type srv_theta = exp(log_srv_theta); // Dirichlet-multinomial parameter
vector<Type> sum1_srv(nyr_srv_age); // First sum in D-M likelihood (log of Eqn 10, Thorson et al. 2017)
vector<Type> sum2_srv(nyr_srv_age); // Second sum in D-M likelihood (log of Eqn 10, Thorson et al. 2017)
//srv_theta.setZero();
sum1_srv.setZero();
sum2_srv.setZero();
// Switch for composition likelihood (case 0 or 1 references the value of comp_type)
switch (comp_type) {
case 0: // Multinomial
for (int i = 0; i < nyr_srv_age; i++) {
for (int j = 0; j < nage; j++) {
// Offset
offset(1) -= effn_srv_age(i) * (data_srv_age(i,j) + c) * log(data_srv_age(i,j) + c);
// Likelihood
age_like(1) -= effn_srv_age(i) * (data_srv_age(i,j) + c) * log(pred_srv_age(i,j) + c);
}
}
age_like(1) -= offset(1); // subtract offset
age_like(1) *= wt_srv_age; // likelihood weight
break;
case 1: // Dirichlet-multinomial (D-M)
for (int i = 0; i < nyr_srv_age; i++) {
// Preliminary calcs
for (int j = 0; j < nage; j++) {
// First sum in D-M likelihood (log of Eqn 10, Thorson et al. 2017)
sum1_srv(i) += lgamma( n_srv_age(i) * data_srv_age(i,j) + Type(1.0) );
// Second sum in D-M likelihood (log of Eqn 10, Thorson et al. 2017)
//sum2_srv(i) += lgamma( n_srv_age(i) + data_srv_age(i,j) + srv_theta * n_srv_age(i) * pred_srv_age(i,j) ) -
// lgamma( srv_theta * n_srv_age(i) - pred_srv_age(i,j) );
sum2_srv(i) += lgamma( n_srv_age(i) * data_srv_age(i,j) + srv_theta * n_srv_age(i) * pred_srv_age(i,j) ) -
lgamma( srv_theta * n_srv_age(i) * pred_srv_age(i,j) ); //switch - to * ??
}
// Full nll for D-M, Eqn 10, Thorson et al. 2017
//age_like(1) -= lgamma(n_srv_age(i) + Type(1.0)) - sum1_srv(i) + lgamma(srv_theta * n_srv_age(i)) -
// lgamma(n_srv_age(i) + srv_theta * n_srv_age(i)) + sum2_srv(i);
age_like(1) -= lgamma(n_srv_age(i) + Type(1.0)) - sum1_srv(i) + lgamma(srv_theta * n_srv_age(i)) -
lgamma(n_srv_age(i) + srv_theta * n_srv_age(i)) + sum2_srv(i);
}
break;
// case 2: // Multivariate logistic - future development
}
// std::cout << "Age comp offset\n" << offset << "\n";
// std::cout << "Age comp likelihoods\n" << age_like << "\n";
// Multinomial likelihood for fishery length comps.
for (int k = 0; k < nsex; k++) {
for (int i = 0; i < nyr_fsh_len; i++) {
for (int l = 0; l < nlenbin; l++) {
// Offset
offset_fsh_len(k) -= effn_fsh_len(i,0,k) * (data_fsh_len(i,l,k) + c) * log(data_fsh_len(i,l,k) + c);
// Likelihood
fsh_len_like(k) -= effn_fsh_len(i,0,k) * (data_fsh_len(i,l,k) + c) * log(pred_fsh_len(i,l,k) + c);
}
}
fsh_len_like(k) -= offset_fsh_len(k); // subtract offset
fsh_len_like(k) *= wt_fsh_len; // likelihood weight
}
// Multinomial likelihood for survey length comps.
for (int k = 0; k < nsex; k++) {
for (int i = 0; i < nyr_srv_len; i++) {
for (int l = 0; l < nlenbin; l++) {
// Offset
offset_srv_len(k) -= effn_srv_len(i,0,k) * (data_srv_len(i,l,k) + c) * log(data_srv_len(i,l,k) + c);
// Likelihood
srv_len_like(k) -= effn_srv_len(i,0,k) * (data_srv_len(i,l,k) + c) * log(pred_srv_len(i,l,k) + c);
}
}
srv_len_like(k) -= offset_srv_len(k); // subtract offset
srv_len_like(k) *= wt_srv_len; // likelihood weight
}
// Recruitment - random_rec switches between penalized likelihood and random
// effects. Shared sigma_r between rinit_devs and rec_devs, rinit_devs are the
// same as the rec_devs but have been reduced by mortality. They were kept
// separate to help with accounting.
// Penalized likelihood, sigma_r fixed, bias correction for lognormal
// likelihood (-0.5*sigma^2) needed to get mean instead of median from
// distribution
if (random_rec == 0) {
// Annual recruitment deviations
for (int i = 0; i < nyr; i++) {
rec_like += square(log_rec_devs(i) - Type(0.5) * square(sigma_r));
}
// Initial numbers-at-age (sage + 1 to plus group - 1)
for (int j = 0; j < nage - 2; j++) {
rec_like += square(log_rinit_devs(j) - Type(0.5) * square(sigma_r));
}
rec_like *= wt_rec_like; // weight
}
// Random effects: mean = 0, sigma_r estimated, same bias correction as
// penalized likelihood for lognormal distribution
if (random_rec == 1) {
// Recruitment deviations
for (int i = 0; i < nyr; i++) {
rec_like += log(sigma_r) + Type(0.5) * square(log_rec_devs(i) - Type(0.5) * square(sigma_r)) / square(sigma_r);
// Should be equivalent to: rec_like -= dnorm(log_rec_dev(i) - Type(0.5) * square(sigma_r) , Type(0.0), sigma_r, true);
}
// Initial numbers-at-age (sage + 1 to plus group - 1)
for (int j = 0; j < nage - 2; j++) {
rec_like += log(sigma_r) + Type(0.5) * square(log_rinit_devs(j) - Type(0.5) * square(sigma_r)) / square(sigma_r);
}
rec_like *= wt_rec_like; // weight
}
// std::cout << "Log recruitment deviations\n" << log_rec_devs << "\n";
// std::cout << "Log deviations for initial numbers-at-age\n" << log_rinit_devs << "\n";
// std::cout << "Recruitment likelihood\n" << rec_like << "\n";
// Regularity penalty on fishing mortality
for (int i = 0; i < nyr; i++) {
fpen += square(log_F_devs(i));
}
fpen *= wt_fpen; // weight
// Large penalty on SPR calculations
for(int x = 1; x <= n_Fxx; x++) {
spr_pen += wt_spr * square(SBPR(x) / SBPR(0) - Fxx_levels(x-1));
}
// std::cout << "Log fishing mortality deviations\n" << log_F_devs << "\n";
// std::cout << "Penality for fishing mortality\n" << fpen << "\n";
// std::cout << "Penality for SPR calcs\n" << spr_pen << "\n";
// Sum likelihood components
obj_fun += priors(0); // Fishery q
obj_fun += priors(1); // Survey q
obj_fun += priors(2); // Mark-recapture abndance index q
obj_fun += prior_M; // prior for natural mortality (if fixed this is 0)
obj_fun += catch_like; // Catch
obj_fun += index_like(0); // Fishery cpue
obj_fun += index_like(1); // Survey cpue
obj_fun += index_like(2); // Mark-recapture abundance index
obj_fun += age_like(0); // Fishery age compositions
obj_fun += age_like(1); // Survey age compositions
for (int k = 0; k < nsex; k++) {
obj_fun += fsh_len_like(k); // Fishery length comps
obj_fun += srv_len_like(k); // Survey length comps
}
obj_fun += rec_like; // Recruitment deviations
obj_fun += fpen; // Fishing mortality deviations
obj_fun += spr_pen; // SPR calculations
// std::cout << "Objective function\n" << obj_fun << "\n";
// obj_fun = dummy*dummy; // Uncomment when debugging code
// REPORT SECTION
// Predicted indices of catch and abundance
REPORT(pred_catch); // Total catch
REPORT(pred_landed); // Landed catch
REPORT(pred_wastage); // Discarded catch assumed to die
REPORT(pred_mr); // Mark-recapture index of abundance (only years with an estimate)
REPORT(pred_mr_all); // Mark-recapture index of abundance (all years)
REPORT(pred_fsh_cpue); // Fishery cpue
REPORT(pred_srv_cpue); // Survey cpue
// Predicted compositions
REPORT(pred_fsh_age); // Fishery
REPORT(pred_srv_age); // Survey
REPORT(pred_fsh_len); // Fishery
REPORT(pred_srv_len); // Survey
// Predicted selectivity-at-age
REPORT(fsh_slx); // Fishery
REPORT(srv_slx); // Survey
// Predicted annual fishing mortality
REPORT(Fmort);
// Derived matrices by year and age
REPORT(N); // Abundance-at-age, projected 1 year forward
REPORT(Nlen); // Abundance-at-length, projected 1 year forward
REPORT(Z); // Total mortality
REPORT(F); // Fishing mortality
REPORT(S); // Survivorship
REPORT(C); // Catch in numbers at age
// Derived vectors by year
ADREPORT(pred_rec); // Predicted age-2 recruitment
REPORT(pred_rec); // Predicted age-2 recruitment
REPORT(tot_biom); // Total age-2+ biomass
REPORT(tot_expl_biom); // Vulnerable biomass to fishery at the beginning of the fishery
REPORT(tot_expl_abd); // Vulnerable abundance to fishery at the beginning of the fishery
REPORT(tot_vuln_abd); // Vulnerable abundance to survey at the beginning of the survey
REPORT(tot_spawn_biom); // Female spawning biomass
// Derived arrays by year, age, sex
REPORT(biom); // Total age-2+ biomass
REPORT(expl_biom); // Vulnerable biomass to fishery at the beginning of the fishery
REPORT(expl_abd); // Vulnerable abundance to fishery at the beginning of the fishery
REPORT(vuln_abd); // Vulnerable abundance to survey at the beginning of the survey
REPORT(spawn_biom); // Spawning biomass
// // SPR-based biological reference points and ABC
REPORT(Fxx); // Vector of Fs scaled to fully selected values
REPORT(sel_Fxx); // Fishery selectivity used in ABC calcs
REPORT(SBPR); // Vector of spawning biomass per recruit at various Fxx levels
REPORT(mean_rec); // Mean recruitment assumed to be equilibrium recruitment
REPORT(SB); // Vector of spawning biomass at various Fxx levels
REPORT(ABC); // ABC at various Fxx levels
REPORT(wastage); // Dead discarded catch at various Fxx levels
// Other derived and projected values
REPORT(survival_srv); // Survival at time of survey
REPORT(survival_fsh); // Survival at time of fishery
REPORT(survival_spawn); // Survival at time of spawning
REPORT(pred_rbar); // Predicted mean recruitment
// Priors, likelihoods, offsets, and penalty functions
REPORT(priors); // q priors
REPORT(prior_M); // M prior
REPORT(catch_like); // Catch
REPORT(index_like); // Abundance indices
REPORT(age_like); // Age compositions
REPORT(srv_len_like); // Survey length composition likelihoods
REPORT(fsh_len_like); // Fishery length composition likelihoods
REPORT(rec_like); // Recruitment deviations
REPORT(fpen); // Fishing mortality deviations
REPORT(spr_pen); // SPR penalty
REPORT(obj_fun); // Total objective function
REPORT(offset); // Offsets for age comp multinomial
REPORT(offset_srv_len); // Offsets for survey length comp multinomial
REPORT(offset_fsh_len); // Offsets for fishery length comp multinomial
return(obj_fun);
}
| [
"philip.joy@alaska.gov"
] | philip.joy@alaska.gov |
21b9f4df87a2d67d7e659724c2870a35d576e07e | 72b0b2328a1749d25c0ebb5c51a7a202fb35b382 | /leetcode/8.cpp | 2ae12aff7a1ebf4c5233e345643af678c16ccbbd | [] | no_license | bluarry/prepare | 5140b57612fab19b8b24573012bf796d2c0def31 | c9c94fa7970b40b6f828d2f2e31267acaecbc07c | refs/heads/master | 2021-05-22T01:10:29.998403 | 2020-05-05T04:25:22 | 2020-05-05T04:25:22 | 252,900,366 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,672 | cpp | #include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
class Solution {
public:
bool isEffect(char c){
if(c=='-'||c=='+'||(c>='0'&& c<='9')) return true;
return false;
}
bool isnum(char c){
if(c>='0'&& c<='9') return true;
return false;
}
string trim(string str){
int index=0;
while(str[index++]==' ');
return str.substr(index-1);
}
int myAtoi(string str) {
str=trim(str);
//cout << str<<endl;
int flag=0,ans=0,len=str.length(),p=0,n=0;
if(len==0) return 0;
if(isEffect(str[0]))
p=0;
else
return 0;
if(str[0]=='-') flag=1,p++;
else if(str[0]=='+') p++;
//cout << "len= " <<len<<endl;
for(int i=p;i<len;i++){
if(isnum(str[i])){
n=i;
}else
{
break;
}
}
//cout << p << " " << n <<endl;
// 当正数处理
int flag2=0;
int c=0;
for(int i=p;i<=n;i++){
c=str[i]-'0';
if( ans > INT32_MAX/10 ||(ans==INT32_MAX/10 && c>7)){
flag2=1;
ans=INT32_MAX;
break;
}
ans=ans*10+c;
}
if(flag){
if(flag2) ans=INT32_MIN;
else ans=-ans;
}
return ans;
}
};
int main(){
Solution ss;
string s="-2147483648" ;
cout << ss.myAtoi(s)<<endl;
return 0;
}
| [
"root@winpc_bluarry.localdomain"
] | root@winpc_bluarry.localdomain |
4ad1472a84ba67cdd52887a530ed36762ab5874c | cfbe32d3c679487610e0a8e924c33ab6aa64f3d1 | /topcoder/programs/PilingRectsDiv2.cpp | 2de48e3d098db1405a65cbda63508e62f1aee8ac | [] | no_license | hophacker/algorithm_coding | 6062fafd00e276baeb5ef92198c6c1dab66b6184 | bfc9a124ed21eabf241590b90105427f0a2b6573 | refs/heads/master | 2020-06-04T00:41:25.378594 | 2014-07-07T00:50:35 | 2014-07-07T00:50:35 | 18,478,412 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,450 | cpp | #include <sstream>
/*
*/
#define debuging
#ifdef debuging
#define FIN {freopen("new.in" , "r" , stdin) ;}
#define FOUT {freopen("new.out" , "w" , stdout) ;}
#define OUT(x) {cout<< #x << " : " << x <<endl ;}
#define ERR(x) {cout<<"#error: "<< x ; while(1) ;}
#endif
// END CUT HERE
#ifndef debuging
#define FIN ;
#define FOUT ;
#define OUT(x) ;
#define ERR(x) ;
#endif
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <list>
using namespace std ;
#define For(i , n) for(int i = 0 ; i < (n) ; ++i)
#define SZ(x) (int)((x).size())
typedef long long lint ;
const int maxint = -1u>>2 ;
const double eps = 1e-6 ;
class PilingRectsDiv2
{
list<int> link[50];
bool unSearched[50];
public:
int search(int x){
int ret = 0;
for (list<int>::iterator it=link[x].begin(); it != link[x].end(); ++it){
int y = *it;
if (unSearched[y]){
unSearched[y] = 0;
cout << "->" << y;
ret = max(ret, 1+search(y));
unSearched[y] = 1;
}
}
cout << endl;
return ret;
}
int getmax(vector <int> X, vector <int> Y, int limit){
unsigned n = X.size();
for (unsigned i = 0; i < n; i++) link[i].clear();
for (unsigned i = 0; i < n; i++) {
for (unsigned j = i+1; j < n; j++){
if (min(X[i],X[j])*min(Y[i],Y[j]) >= limit || min(X[i],Y[j]) * min(X[j],Y[i]) >= limit){
link[i].push_back(j);
link[j].push_back(i);
cout << i << ' ' << j << endl;
}
}
}
int maxN = -1;
memset(unSearched, true, sizeof(unSearched));
for (unsigned i = 0; i < X.size(); i++) cout << i << ':' << link[i].size() << endl;
for (unsigned i = 0; i < X.size(); i++) if (X[i]*Y[i] >= limit){
unSearched[i] = 0;
cout << i;
maxN = max(maxN, 1+search(i));
cout << maxN << endl;
unSearched[i] = 1;
}
return maxN;
return int() ;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {1,2,3,1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {3,2,4,4}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; int Arg3 = 3; verify_case(0, Arg3, getmax(Arg0, Arg1, Arg2)); }
void test_case_1() { int Arr0[] = {4,7}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {7,4}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 25; int Arg3 = 2; verify_case(1, Arg3, getmax(Arg0, Arg1, Arg2)); }
void test_case_2() { int Arr0[] = {10}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {10}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 9999; int Arg3 = -1; verify_case(2, Arg3, getmax(Arg0, Arg1, Arg2)); }
void test_case_3() { int Arr0[] = {10}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 30; int Arg3 = 1; verify_case(3, Arg3, getmax(Arg0, Arg1, Arg2)); }
void test_case_4() { int Arr0[] = {3,6,5,8,2,9,14}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {14,6,13,8,15,6,3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 27; int Arg3 = 4; verify_case(4, Arg3, getmax(Arg0, Arg1, Arg2)); }
void test_case_5() { int Arr0[] = {121,168,86,106,36,10,125,97,53,26,148,129,41,18,173,55,13,73,91,174,177,190,28,164,122,92,5,26,58,188,14,67,48,196,41,94,24,89,54,117,12,6,155,103,200,128,184,29,92,149}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {199,182,43,191,2,145,15,53,38,37,61,45,157,129,119,123,177,178,183,188,132,108,112,137,92,59,75,196,102,152,114,121,181,93,32,3,24,116,4,163,96,159,196,43,59,150,79,113,20,146}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 5345; int Arg3 = 24; verify_case(5, Arg3, getmax(Arg0, Arg1, Arg2)); }
// END CUT HERE
};// BEGIN CUT HERE
int main(){
PilingRectsDiv2 ___test;
___test.run_test(0);
return 0;
}
// END CUT HERE
| [
"jokerfeng2010@gmail.com"
] | jokerfeng2010@gmail.com |
b76554fcebe4c4eb3e962a9663c32f7e3e59e548 | 6ae1105a9ee4ec00eaf4a7c8d29af03e218ae68c | /Home_Automation_Slave_2/Home_Automation_Slave_2.ino | 8c0f042464e6b2b4ad5013666a16a362fca75070 | [] | no_license | kaustubhcs/Home-Automation | e2c49b3f7f3a9a704739277837f910361db41c03 | 192a52ea3c1af677c8f76b3ebc5917d2a574ea38 | refs/heads/master | 2021-01-22T21:13:09.958546 | 2015-10-22T15:48:32 | 2015-10-22T15:48:32 | 41,579,976 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,327 | ino | #include <SoftwareSerial.h>
#define relay_0 2 // T
#define relay_1 3 // E
#define relay_2 11 // C
#define relay_3 6 // H
#define relay_4 4 // N
#define relay_5 45 // O
#define relay_6 47 // V
#define relay_7 52 // A
#define relay_8 51 // N
#define relay_9 53 // Z
#define relay_10 49// A
#define cfl relay_0
#define tubes relay_1
#define fan relay_2
#define night_lamp relay_3
//#define
#define table_plug_2 relay_5
#define table_plug_1 relay_6
#define bell relay_7
#define master_plug relay_8
#define tv relay_9
//#define
#define buzzer 35
#define passage_door_open_led 23
#define passage_door_lock_led 25
#define passage_door_open_ldr A8
#define passage_door_lock_ldr A7
#define passage_door_bell_led 27
#define passage_door_bell_switch A6
#define pir_1 A5
#define pir_2 A4
#define pir_3 A3
#define living_room_door_open_led 29
#define living_room_door_lock_led 31
#define living_room_door_lock_ldr A2
#define living_room_door_open_ldr A1
#define gallery_door_open_led 33
#define gallery_door_open_ldr A0
SoftwareSerial master(10,14);
int relay[11] = {
2,3,11,6,4,45,47,52,51,53,49};
int commands[15] ={
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int bell_t=0;
unsigned long time=0;
int gmode=0;
int fmode=0;
unsigned long y= 0;
unsigned long x= 0;
unsigned long str = millis();
unsigned long md = 0;
unsigned long me = 0;
unsigned long mn = 0;
unsigned long ms = 0;
unsigned long adder=3000;
void setup()
{
initialise_pins();
Serial.begin(9600);
master.begin(9600);
digitalWrite(master_plug,HIGH);
}
void loop()
{
// adder_setter();
mode();
bell_detect();
// delay(1000);
// tests();
}
void tests()
{
// sensor_test();
// sensor_test_2();
//pir_test_3();
// comm_test();
//relay_test();
//pir_test_2();
//analog_pir();
/*
pir(1);
pir(2);
pir(3);
*/
}
void initialise_pins()
{
for (int i=0;i<11;i++)
{
pinMode(relay[i],OUTPUT);
digitalWrite(relay[i],LOW);
}
pinMode(buzzer,OUTPUT);
pinMode(passage_door_open_led,OUTPUT);
pinMode(passage_door_lock_led,OUTPUT);
pinMode(passage_door_open_ldr,INPUT);
pinMode(passage_door_lock_ldr,INPUT);
pinMode(passage_door_bell_led,OUTPUT);
pinMode(passage_door_bell_switch,INPUT);
pinMode(pir_1,INPUT);
pinMode(pir_2,INPUT);
pinMode(pir_3,INPUT);
pinMode(living_room_door_open_led,OUTPUT);
pinMode(living_room_door_lock_led,OUTPUT);
pinMode(living_room_door_lock_ldr,INPUT);
pinMode(living_room_door_open_ldr,INPUT);
pinMode(gallery_door_open_led,OUTPUT);
pinMode(gallery_door_open_ldr,INPUT);
digitalWrite(buzzer,LOW);
digitalWrite(passage_door_open_led,HIGH);
digitalWrite(passage_door_lock_led,HIGH);
analogWrite(passage_door_open_ldr,1023);
analogWrite(passage_door_lock_ldr,1023);
digitalWrite(passage_door_bell_led,HIGH);
analogWrite(passage_door_bell_switch,1023);
analogWrite(pir_1,1023);
analogWrite(pir_2,1023);
analogWrite(pir_3,1023);
digitalWrite(living_room_door_open_led,HIGH);
digitalWrite(living_room_door_lock_led,HIGH);
analogWrite(living_room_door_lock_ldr,1023);
analogWrite(living_room_door_open_ldr,1023);
digitalWrite(gallery_door_open_led,HIGH);
analogWrite(gallery_door_open_ldr,1023);
analogWrite(pir_1,0);
analogWrite(pir_2,0);
analogWrite(pir_3,0);
}
| [
"kaustubhcs07@gmail.com"
] | kaustubhcs07@gmail.com |
9153725d9e48f9cfc269bc6c7d30a863262d7e14 | 496bfb693a5f9a25b3f368eaae3358fd06cd5429 | /Framework/Framework/modules/FreeBird/include/AndGate.h | fef36d1925f6c08ec8c409353127d4db73510f13 | [] | no_license | Aideng666/Project-Poultry-Game | a32cc911ab18673c33ec469a944cb666ea8cc78d | 7e27c67939f789202d87ae720f2a6bc8b84c7593 | refs/heads/Master | 2023-04-04T06:49:32.352043 | 2021-04-09T16:41:11 | 2021-04-09T16:41:11 | 300,339,278 | 0 | 1 | null | 2021-01-17T20:05:11 | 2020-10-01T16:03:30 | C++ | UTF-8 | C++ | false | false | 207 | h | #pragma once
#include "LogicGate.h"
namespace freebird
{
class AndGate : public LogicGate
{
public:
AndGate(Entity ent1, Entity ent2, Entity out);
void Update();
private:
};
}
| [
"aiden.gimpel@ontariotechu.net"
] | aiden.gimpel@ontariotechu.net |
0a60922bd0bcfdfec8d29c63173d454de64bdec3 | be55b78c5ec4d90b5c9f91122a64ab486d615814 | /qt/KDSqlDatabaseTransaction/KDSqlDatabaseTransaction.h | 2292770f644a2a67599c083032c47a1f020e06df | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | elProxy/KDToolBox | 4f2724b44622e5ca090115409fe81f9fd2afb448 | bd538894347d8630458dccce054ac7f698cd1c16 | refs/heads/master | 2023-08-12T15:12:29.230802 | 2021-09-21T12:09:11 | 2021-09-21T12:46:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,418 | h | /****************************************************************************
** MIT License
**
** Copyright (C) 2019-2021 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
**
** This file is part of KDToolBox (https://github.com/KDAB/KDToolBox).
**
** 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 (including the next paragraph)
** 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.
****************************************************************************/
#ifndef KDTOOLBOX_KDSQLDATABASETRANSACTION_H
#define KDTOOLBOX_KDSQLDATABASETRANSACTION_H
#include <QSqlDatabase>
#include <QSqlDriver>
#include <QLoggingCategory>
#include <QtDebug>
namespace KDToolBox
{
namespace Private {
// `inline` logging category; Qt doesn't support them.
inline const QLoggingCategory &kdsqllc()
{
static const QLoggingCategory category("KDToolBox.KDSqlDatabaseTransaction", QtWarningMsg);
return category;
}
} // namespace Private
class Q_REQUIRED_RESULT KDSqlDatabaseTransaction
{
Q_DISABLE_COPY(KDSqlDatabaseTransaction)
public:
/*!
* \brief Begins a new transaction. The transaction will be
* committed when commit() is called (and returns true), otherwise
* it will be automatically rolled back.
*
* \param database is the database connection to use. The connection
* must be opened before use.
*/
explicit KDSqlDatabaseTransaction(const QSqlDatabase &database = QSqlDatabase::database())
: m_db(database)
, m_shouldRollback(true)
{
if (!m_db.isOpen()) {
qCWarning(Private::kdsqllc) << "The database" << m_db << "is not open";
m_shouldRollback = false;
} else if (!m_db.driver()->hasFeature(QSqlDriver::Transactions)) {
qCWarning(Private::kdsqllc) << "The database" << m_db << "does not support transactions";
m_shouldRollback = false;
} else if (!m_db.transaction()) {
qCWarning(Private::kdsqllc) << "Could not begin a new transaction";
m_shouldRollback = false;
}
}
/*!
* \brief Destroys the transaction object. If it has not been committed
* by calling commit(), the transaction will be rolled back.
*/
~KDSqlDatabaseTransaction()
{
if (m_shouldRollback) {
m_db.rollback();
}
}
KDSqlDatabaseTransaction(KDSqlDatabaseTransaction &&other) noexcept
: m_db(std::move(other.m_db))
, m_shouldRollback(std::exchange(other.m_shouldRollback, false))
{}
KDSqlDatabaseTransaction &operator=(KDSqlDatabaseTransaction &&other) noexcept
{
KDSqlDatabaseTransaction moved(std::move(other));
swap(moved);
return *this;
}
void swap(KDSqlDatabaseTransaction &other) noexcept
{
qSwap(m_db, other.m_db);
qSwap(m_shouldRollback, other.m_shouldRollback);
}
/*!
* \brief Commits the transaction. If the commit fails, the
* KDSqlDatabaseTransaction object will roll back the transaction
* when it gets destroyed.
*
* \return True if committing succeeded, false if it failed.
*/
bool commit()
{
if (!m_shouldRollback) {
qCWarning(Private::kdsqllc) << "commit() / rollback() already called on this object";
return false;
}
const bool result = m_db.commit();
if (result) {
m_shouldRollback = false;
}
return result;
}
/*!
* \brief Rolls back the transaction. If the rollback fails, the
* KDSqlDatabaseTransaction object will NOT roll back the transaction
* again when it gets destroyed.
*
* \return True if rollback succeeded, false if it failed.
*/
bool rollback()
{
if (!m_shouldRollback) {
qCWarning(Private::kdsqllc) << "commit() / rollback() already called on this object";
return false;
}
// in case rollback fails, what can we do? should we try again?
m_shouldRollback = false;
return m_db.rollback();
}
/*!
* \brief Returns the database connection used by this object.
* \return The database connection.
*/
const QSqlDatabase &database() const
{
return m_db;
}
private:
QSqlDatabase m_db;
bool m_shouldRollback;
};
} // namespace KDToolBox
#endif // KDTOOLBOX_KDSQLDATABASETRANSACTION_H
| [
"giuseppe.dangelo@kdab.com"
] | giuseppe.dangelo@kdab.com |
80446ed73f8abe7b81030d8f01fc4727f1acaf80 | 4cc7c74b4bb7b818562bedffd026a86f9ec78f41 | /chrome/browser/safe_browsing/test_safe_browsing_service.cc | f6949cf8f0707cb2e76c4a82f4e4a725e970294c | [
"BSD-3-Clause"
] | permissive | jennyb2911/chromium | 1e03c9e5a63af1cf82832e0e99e0028e255872bd | 62b48b4fdb3984762f4d2fd3690f02f167920f52 | refs/heads/master | 2023-01-10T01:08:34.961976 | 2018-09-28T03:36:36 | 2018-09-28T03:36:36 | 150,682,761 | 1 | 0 | NOASSERTION | 2018-09-28T03:49:28 | 2018-09-28T03:49:27 | null | UTF-8 | C++ | false | false | 5,906 | cc | // Copyright (c) 2016 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/safe_browsing/test_safe_browsing_service.h"
#include "base/strings/string_util.h"
#include "chrome/browser/safe_browsing/download_protection/download_protection_service.h"
#include "chrome/browser/safe_browsing/incident_reporting/incident_reporting_service.h"
#include "chrome/browser/safe_browsing/ui_manager.h"
#include "components/safe_browsing/db/database_manager.h"
#include "components/safe_browsing/db/test_database_manager.h"
#include "components/safe_browsing/db/v4_feature_list.h"
namespace safe_browsing {
// TestSafeBrowsingService functions:
TestSafeBrowsingService::TestSafeBrowsingService()
: SafeBrowsingService(),
serialized_download_report_(base::EmptyString()),
use_v4_local_db_manager_(false) {
#if defined(FULL_SAFE_BROWSING)
services_delegate_ = ServicesDelegate::CreateForTest(this, this);
#endif // defined(FULL_SAFE_BROWSING)
}
TestSafeBrowsingService::~TestSafeBrowsingService() {}
V4ProtocolConfig TestSafeBrowsingService::GetV4ProtocolConfig() const {
if (v4_protocol_config_)
return *v4_protocol_config_;
return SafeBrowsingService::GetV4ProtocolConfig();
}
void TestSafeBrowsingService::UseV4LocalDatabaseManager() {
use_v4_local_db_manager_ = true;
}
std::string TestSafeBrowsingService::serilized_download_report() {
return serialized_download_report_;
}
void TestSafeBrowsingService::ClearDownloadReport() {
serialized_download_report_.clear();
}
void TestSafeBrowsingService::SetDatabaseManager(
TestSafeBrowsingDatabaseManager* database_manager) {
SetDatabaseManagerForTest(database_manager);
}
void TestSafeBrowsingService::SetUIManager(
TestSafeBrowsingUIManager* ui_manager) {
ui_manager->SetSafeBrowsingService(this);
ui_manager_ = ui_manager;
}
SafeBrowsingUIManager* TestSafeBrowsingService::CreateUIManager() {
if (ui_manager_)
return ui_manager_.get();
return SafeBrowsingService::CreateUIManager();
}
void TestSafeBrowsingService::SendSerializedDownloadReport(
const std::string& report) {
serialized_download_report_ = report;
}
const scoped_refptr<SafeBrowsingDatabaseManager>&
TestSafeBrowsingService::database_manager() const {
if (test_database_manager_)
return test_database_manager_;
return SafeBrowsingService::database_manager();
}
void TestSafeBrowsingService::SetV4ProtocolConfig(
V4ProtocolConfig* v4_protocol_config) {
v4_protocol_config_.reset(v4_protocol_config);
}
// ServicesDelegate::ServicesCreator:
bool TestSafeBrowsingService::CanCreateDatabaseManager() {
return !use_v4_local_db_manager_;
}
bool TestSafeBrowsingService::CanCreateDownloadProtectionService() {
return false;
}
bool TestSafeBrowsingService::CanCreateIncidentReportingService() {
return true;
}
bool TestSafeBrowsingService::CanCreateResourceRequestDetector() {
return false;
}
SafeBrowsingDatabaseManager* TestSafeBrowsingService::CreateDatabaseManager() {
DCHECK(!use_v4_local_db_manager_);
#if defined(FULL_SAFE_BROWSING)
return new TestSafeBrowsingDatabaseManager();
#else
NOTIMPLEMENTED();
return nullptr;
#endif // defined(FULL_SAFE_BROWSING)
}
DownloadProtectionService*
TestSafeBrowsingService::CreateDownloadProtectionService() {
NOTIMPLEMENTED();
return nullptr;
}
IncidentReportingService*
TestSafeBrowsingService::CreateIncidentReportingService() {
#if defined(FULL_SAFE_BROWSING)
return new IncidentReportingService(nullptr);
#else
NOTIMPLEMENTED();
return nullptr;
#endif // defined(FULL_SAFE_BROWSING)
}
ResourceRequestDetector*
TestSafeBrowsingService::CreateResourceRequestDetector() {
NOTIMPLEMENTED();
return nullptr;
}
// TestSafeBrowsingServiceFactory functions:
TestSafeBrowsingServiceFactory::TestSafeBrowsingServiceFactory()
: test_safe_browsing_service_(nullptr), use_v4_local_db_manager_(false) {}
TestSafeBrowsingServiceFactory::~TestSafeBrowsingServiceFactory() {}
SafeBrowsingService*
TestSafeBrowsingServiceFactory::CreateSafeBrowsingService() {
// Instantiate TestSafeBrowsingService.
test_safe_browsing_service_ = new TestSafeBrowsingService();
// Plug-in test member clases accordingly.
if (use_v4_local_db_manager_)
test_safe_browsing_service_->UseV4LocalDatabaseManager();
if (test_ui_manager_)
test_safe_browsing_service_->SetUIManager(test_ui_manager_.get());
if (test_database_manager_) {
test_safe_browsing_service_->SetDatabaseManager(
test_database_manager_.get());
}
return test_safe_browsing_service_;
}
TestSafeBrowsingService*
TestSafeBrowsingServiceFactory::test_safe_browsing_service() {
return test_safe_browsing_service_;
}
void TestSafeBrowsingServiceFactory::SetTestUIManager(
TestSafeBrowsingUIManager* ui_manager) {
test_ui_manager_ = ui_manager;
}
void TestSafeBrowsingServiceFactory::SetTestDatabaseManager(
TestSafeBrowsingDatabaseManager* database_manager) {
test_database_manager_ = database_manager;
}
void TestSafeBrowsingServiceFactory::UseV4LocalDatabaseManager() {
use_v4_local_db_manager_ = true;
}
// TestSafeBrowsingUIManager functions:
TestSafeBrowsingUIManager::TestSafeBrowsingUIManager()
: SafeBrowsingUIManager(nullptr) {}
TestSafeBrowsingUIManager::TestSafeBrowsingUIManager(
const scoped_refptr<SafeBrowsingService>& service)
: SafeBrowsingUIManager(service) {}
void TestSafeBrowsingUIManager::SetSafeBrowsingService(
SafeBrowsingService* sb_service) {
sb_service_ = sb_service;
}
void TestSafeBrowsingUIManager::SendSerializedThreatDetails(
const std::string& serialized) {
details_.push_back(serialized);
}
std::list<std::string>* TestSafeBrowsingUIManager::GetThreatDetails() {
return &details_;
}
TestSafeBrowsingUIManager::~TestSafeBrowsingUIManager() {}
} // namespace safe_browsing
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
76a22172829ff41aba3eecf2ca8b2b1440114363 | 07306d96ba61d744cb54293d75ed2e9a09228916 | /External/NaturalMotion/morpheme/SDK/euphoriaCoreBehaviours/AutoGenerated/SteppingBalancePackaging.h | fea38e4d5a40da784411a68c012d658deb64293a | [] | no_license | D34Dspy/warz-client | e57783a7c8adab1654f347f389c1dace35b81158 | 5262ea65e0baaf3f37ffaede5f41c9b7eafee7c1 | refs/heads/master | 2023-03-17T00:56:46.602407 | 2015-12-20T16:43:00 | 2015-12-20T16:43:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,871 | h | #pragma once
/*
* Copyright (c) 2013 NaturalMotion Ltd. All rights reserved.
*
* Not to be copied, adapted, modified, used, distributed, sold,
* licensed or commercially exploited in any manner without the
* written consent of NaturalMotion.
*
* All non public elements of this software are the confidential
* information of NaturalMotion and may not be disclosed to any
* person nor used for any purpose not expressly approved by
* NaturalMotion in writing.
*
*/
//----------------------------------------------------------------------------------------------------------------------
// This file is auto-generated
//----------------------------------------------------------------------------------------------------------------------
#ifndef NM_MDF_STEPPINGBALANCE_PKG_H
#define NM_MDF_STEPPINGBALANCE_PKG_H
// include definition file to create project dependency
#include "./Definition/Modules/SteppingBalance.module"
#include "SteppingBalanceData.h"
#include "BalanceManagementPackaging.h"
namespace MR
{
class InstanceDebugInterface;
}
namespace NM_BEHAVIOUR_LIB_NAMESPACE
{
//----------------------------------------------------------------------------------------------------------------------
// API Packaging
struct SteppingBalanceAPIBase
{
SteppingBalanceAPIBase(
const SteppingBalanceData* const _data,
const SteppingBalanceInputs* const _in,
const SteppingBalanceFeedbackInputs* const _feedIn,
const BalanceManagementAPIBase* const _owner ) :data(_data) ,in(_in) ,feedIn(_feedIn) ,owner(_owner) {}
const SteppingBalanceData* const data;
const SteppingBalanceInputs* const in;
const SteppingBalanceFeedbackInputs* const feedIn;
const BalanceManagementAPIBase* const owner;
SteppingBalanceAPIBase(const SteppingBalanceAPIBase& rhs);
SteppingBalanceAPIBase& operator = (const SteppingBalanceAPIBase& rhs);
};
//----------------------------------------------------------------------------------------------------------------------
// Update Packaging
struct SteppingBalanceUpdatePackage : public SteppingBalanceAPIBase
{
SteppingBalanceUpdatePackage(
SteppingBalanceData* const _data,
const SteppingBalanceInputs* const _in,
const SteppingBalanceFeedbackInputs* const _feedIn,
SteppingBalanceOutputs* const _out,
const BalanceManagementAPIBase* const _owner ) : SteppingBalanceAPIBase(_data ,_in ,_feedIn ,_owner ), data(_data), out(_out)
{
}
SteppingBalanceData* const data;
SteppingBalanceOutputs* const out;
// module update entrypoint
void update(float timeStep, MR::InstanceDebugInterface* pDebugDrawInst);
SteppingBalanceUpdatePackage(const SteppingBalanceUpdatePackage& rhs);
SteppingBalanceUpdatePackage& operator = (const SteppingBalanceUpdatePackage& rhs);
};
//----------------------------------------------------------------------------------------------------------------------
// Feedback Packaging
struct SteppingBalanceFeedbackPackage : public SteppingBalanceAPIBase
{
SteppingBalanceFeedbackPackage(
SteppingBalanceData* const _data,
const SteppingBalanceFeedbackInputs* const _feedIn,
const SteppingBalanceInputs* const _in,
SteppingBalanceFeedbackOutputs* const _feedOut,
const BalanceManagementAPIBase* const _owner ) : SteppingBalanceAPIBase(_data ,_in ,_feedIn ,_owner ), data(_data), feedOut(_feedOut)
{
}
SteppingBalanceData* const data;
SteppingBalanceFeedbackOutputs* const feedOut;
// module feedback entrypoint
void feedback(float timeStep, MR::InstanceDebugInterface* pDebugDrawInst);
SteppingBalanceFeedbackPackage(const SteppingBalanceFeedbackPackage& rhs);
SteppingBalanceFeedbackPackage& operator = (const SteppingBalanceFeedbackPackage& rhs);
};
} // namespace NM_BEHAVIOUR_LIB_NAMESPACE
#endif // NM_MDF_STEPPINGBALANCE_PKG_H
| [
"hasan@openkod.com"
] | hasan@openkod.com |
37db6cba98ee35dbd915bd98ad6b25de160e1c59 | 43fd0cc577bea4c611657b728e3c3036796d3aa6 | /profilclassic.cpp | 410bfe4163a8b68c2424e1963eb07cba20680ac8 | [] | no_license | SnowKiss/TTVQTB | 358be31da650dfdf64996168047f2e4ab75d9045 | 372540e0a48e7a75e805ecd9804894553da8eeff | refs/heads/master | 2021-05-02T16:29:32.627933 | 2018-02-10T10:44:41 | 2018-02-10T10:44:41 | 120,677,474 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 64 | cpp | #include "profilclassic.h"
ProfilClassic::ProfilClassic()
{
}
| [
"john.schmitt9@gmail.com"
] | john.schmitt9@gmail.com |
e45cb321bce6a88a4e167a27b69c5ae4d21cbb54 | 74a99fb7d20dc4e9312268c1e2936e97607cc62e | /Sea_Chain/helpers/astar.cpp | a2b1c58b83d7c4c11965d04a46ee51813f8d9676 | [
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-4.0",
"MIT"
] | permissive | Vvaridus/SeaChain | fa6c674e6decbd5fe7d7da5058b053f8849b8d04 | 5e48925161e6244245f3af21bd8a1cb7a7acfbd4 | refs/heads/main | 2023-04-25T04:13:57.507698 | 2021-05-03T21:11:48 | 2021-05-03T21:11:48 | 350,384,241 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,389 | cpp | #include "astar.h"
#include <LevelSystem.h>
#include <array>
#include <queue>
class Node {
private:
sf::Vector2i _pos;
int _level;
int _priority;
public:
Node() = default;
Node(const sf::Vector2i& pos, int level, int priority) : _pos(pos), _level(level), _priority(priority) { }
const sf::Vector2i& getPos() const { return _pos; }
int getLevel() const { return _level; }
int getPriority() const { return _priority; }
unsigned int estimate(const sf::Vector2i& dest) const {
sf::Vector2i delta = dest - _pos;
return static_cast<unsigned int>(length(delta));
}
void updatePriority(const sf::Vector2i& dest) {
_priority = _level + estimate(dest) * 100;
}
void nextLevel() { _level += 10; }
bool operator<(const Node& other) const {
return _priority > other._priority;
}
};
std::vector<sf::Vector2i> pathFind(sf::Vector2i start, sf::Vector2i finish) {
static std::array<sf::Vector2i, 4> directions = {
sf::Vector2i(1, 0), sf::Vector2i(0, 1), sf::Vector2i(-1, 0), sf::Vector2i(0, -1) };
std::vector<std::vector<bool>> closed_nodes_map(ls::getWidth());
std::vector<std::vector<int>> open_nodes_map(ls::getWidth());
std::vector<std::vector<sf::Vector2i>> direction_map(ls::getWidth());
std::priority_queue<Node> queue[2];
size_t queue_index = 0;
for (size_t y = 0; y < ls::getHeight(); ++y) {
for (size_t x = 0; x < ls::getWidth(); ++x) {
closed_nodes_map[x].push_back(false);
open_nodes_map[x].push_back(0);
direction_map[x].emplace_back(sf::Vector2i(0, 0));
}
}
Node n0(start, 0, 0);
n0.updatePriority(finish);
queue[queue_index].push(n0);
open_nodes_map[start.x][start.y] = n0.getPriority();
while (!queue[queue_index].empty())
{
auto tmp = queue[queue_index].top();
n0 = Node(tmp.getPos(), tmp.getLevel(), tmp.getPriority());
auto pos = n0.getPos();
queue[queue_index].pop();
open_nodes_map[pos.x][pos.y] = 0;
closed_nodes_map[pos.x][pos.y] = true;
if (pos == finish) {
std::vector<sf::Vector2i> path;
while (!(pos == start)) {
auto dir = direction_map[pos.x][pos.y];
path.push_back(pos);
pos += dir;
}
reverse(begin(path), end(path));
return path;
}
for (auto& dir : directions) {
auto next = pos + dir;
if (!(next.x < 0 || next.x > ls::getWidth() || next.y < 0 || next.y > ls::getWidth() || ls::getTile(sf::Vector2ul(next.x, next.y)) == ls::WALL || closed_nodes_map[next.x][next.y])) {
Node m0(next, n0.getLevel(), n0.getPriority());
m0.nextLevel();
m0.updatePriority(finish);
if (open_nodes_map[next.x][next.y] == 0) {
open_nodes_map[next.x][next.y] = m0.getPriority();
queue[queue_index].push(m0);
direction_map[next.x][next.y] = dir * -1;
}
else if (open_nodes_map[next.x][next.y] > m0.getPriority()) {
direction_map[next.x][next.y] = dir * -1;
while (queue[queue_index].top().getPos() != next) {
queue[1 - queue_index].push(queue[queue_index].top());
queue[queue_index].pop();
}
queue[queue_index].pop();
if (queue[queue_index].size() > queue[1 - queue_index].size())
queue_index = 1 - queue_index;
while (!queue[queue_index].empty()) {
queue[1 - queue_index].push(queue[queue_index].top());
queue[queue_index].pop();
}
queue_index = 1 - queue_index;
queue[queue_index].push(m0);
}
}
}
}
return std::vector<sf::Vector2i>();
} | [
"40429124@live.napier.ac.uk"
] | 40429124@live.napier.ac.uk |
8ab982013d723f7b09c0150999de9e288d170a3b | 8c0e6d4343241603a1221e26cda4c30beed60a80 | /Synth/SysExMessage.cpp | 8439f63bf8693e6afd57d5977c0c1e8e699248ab | [] | no_license | Luiz-Monad/synth | f24ccb01da63e3e4ba2ed2db21eb3cf7d629290b | 0baf844f5d4b53868ee4a9187ff6d443289f3213 | refs/heads/master | 2021-05-27T03:00:37.319603 | 2014-08-19T14:49:59 | 2014-08-19T14:49:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,219 | cpp | //REGION(License)
/* Copyright (c) 2005 Leslie Sanford
*
* 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.
*/
//ENDREGION()
//REGION(Contact)
/*
* Leslie Sanford
* Email: jabberdabber@hotmail.com
*/
//ENDREGION()
#include "SysExMessage.h"
#include "Exception.h"
namespace Sanford { namespace Multimedia { namespace Midi {
typedef SysExMessageClass cls;
void cls::init()
{
this->Length = Functor::New(this, &cls::get_Length);
this->SysExType = Functor::New(this, &cls::get_SysExType);
this->Status = Functor::New(this, &cls::get_Status);
this->MessageType = Functor::New(this, &cls::get_MessageType);
this->data = bytebufferclass::null;
}
REGION(Construction)
/// <summary>
/// Initializes a new instance of the SysExMessageEventArgs class with the
/// specified system exclusive data.
/// </summary>
/// <param name="data">
/// The system exclusive data.
/// </param>
/// <remarks>
/// The system exclusive data's status byte, the first byte in the
/// data, must have a value of 0xF0 or 0xF7.
/// </remarks>
SysExMessageClass::SysExMessageClass(bytebuffer data) :
data(data)
{
init();
REGION(Require)
if(data.Length < 1)
{
throw new ArgumentException(
"System exclusive data is too short.", "data");
}
else if(data[0] != (byte)SysExType::Start &&
data[0] != (byte)SysExType::Continuation)
{
throw new ArgumentException(
"Unknown status value.", "data");
}
ENDREGION()
this->data = bytebufferclass(data.Length);
data.CopyTo(this->data, 0);
}
ENDREGION()
REGION(Methods)
bytebuffer SysExMessageClass::GetBytes()
{
return data.Clone();
}
void SysExMessageClass::CopyTo(bytebuffer buffer, int index)
{
data.CopyTo(buffer, index);
}
bool SysExMessageClass::Equals(IEquatable obj)
{
REGION(Guard)
if(!(isinst<SysExMessage>(obj)))
{
return false;
}
ENDREGION()
SysExMessage message = (SysExMessage)obj;
bool equals = true;
if(this->Length != message.Length)
{
equals = false;
}
for(int i = 0; i < this->Length && equals; i++)
{
if((*this)[i] != message[i])
{
equals = false;
}
}
return equals;
}
int SysExMessageClass::GetHashCode()
{
return data.GetHashCode();
}
ENDREGION()
REGION(Properties)
/// <summary>
/// Gets the element at the specified index.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">
/// If index is less than zero or greater than or equal to the length
/// of the message.
/// </exception>
const byte& SysExMessageClass::operator [](int index)
{
REGION(Require)
if(index < 0 || index >= Length)
{
throw new ArgumentOutOfRangeException("index", index,
"Index into system exclusive message out of range.");
}
ENDREGION()
return data[index];
}
/// <summary>
/// Gets the length of the system exclusive data.
/// </summary>
int SysExMessageClass::get_Length()
{
return data.Length;
}
/// <summary>
/// Gets the system exclusive type.
/// </summary>
SysExType SysExMessageClass::get_SysExType()
{
return (Midi::SysExType)(data[0]);
}
ENDREGION()
ENDREGION()
/// <summary>
/// Gets the status value.
/// </summary>
int SysExMessageClass::get_Status()
{
return (int)data[0];
}
/// <summary>
/// Gets the MessageType.
/// </summary>
MessageType SysExMessageClass::get_MessageType()
{
return MessageType::SystemExclusive;
}
REGION(IEnumerable Members)
bytebufferclass::iterator SysExMessageClass::GetIterator()
{
return data.GetIterator();
}
ENDREGION()
}}}
| [
"luizfelipestang@gmail.com"
] | luizfelipestang@gmail.com |
6114ee868a181c5ef7ac64ba4a57b32ccf501238 | 639aa908a9cfc8cd7b969e328e092d3e847187ee | /devel/include/ros_arduino_msgs/Digital.h | c306000313ae1f5870a670827a98b8913c471abc | [] | no_license | pengboyemo/Ros | 4f34eea65d8154bd2eb248bf62712deb1b059864 | a2ca990fff76414d83ca5c3a622f53493e2deb9b | refs/heads/master | 2022-05-01T10:53:34.194307 | 2022-04-01T07:44:03 | 2022-04-01T07:44:03 | 228,379,978 | 0 | 0 | null | 2019-12-16T12:14:14 | 2019-12-16T12:14:13 | null | UTF-8 | C++ | false | false | 5,993 | h | // Generated by gencpp from file ros_arduino_msgs/Digital.msg
// DO NOT EDIT!
#ifndef ROS_ARDUINO_MSGS_MESSAGE_DIGITAL_H
#define ROS_ARDUINO_MSGS_MESSAGE_DIGITAL_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>
#include <std_msgs/Header.h>
namespace ros_arduino_msgs
{
template <class ContainerAllocator>
struct Digital_
{
typedef Digital_<ContainerAllocator> Type;
Digital_()
: header()
, value(0) {
}
Digital_(const ContainerAllocator& _alloc)
: header(_alloc)
, value(0) {
(void)_alloc;
}
typedef ::std_msgs::Header_<ContainerAllocator> _header_type;
_header_type header;
typedef uint8_t _value_type;
_value_type value;
typedef boost::shared_ptr< ::ros_arduino_msgs::Digital_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::ros_arduino_msgs::Digital_<ContainerAllocator> const> ConstPtr;
}; // struct Digital_
typedef ::ros_arduino_msgs::Digital_<std::allocator<void> > Digital;
typedef boost::shared_ptr< ::ros_arduino_msgs::Digital > DigitalPtr;
typedef boost::shared_ptr< ::ros_arduino_msgs::Digital const> DigitalConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::ros_arduino_msgs::Digital_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::ros_arduino_msgs::Digital_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace ros_arduino_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True}
// {'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg'], 'ros_arduino_msgs': ['/home/ewenwan/ewenwan/catkin_ws/src/ros_arduino_bridge/ros_arduino_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< ::ros_arduino_msgs::Digital_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::ros_arduino_msgs::Digital_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::ros_arduino_msgs::Digital_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::ros_arduino_msgs::Digital_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::ros_arduino_msgs::Digital_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::ros_arduino_msgs::Digital_<ContainerAllocator> const>
: TrueType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::ros_arduino_msgs::Digital_<ContainerAllocator> >
{
static const char* value()
{
return "90539346f3c3c8fc47f159ab9a6ff208";
}
static const char* value(const ::ros_arduino_msgs::Digital_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x90539346f3c3c8fcULL;
static const uint64_t static_value2 = 0x47f159ab9a6ff208ULL;
};
template<class ContainerAllocator>
struct DataType< ::ros_arduino_msgs::Digital_<ContainerAllocator> >
{
static const char* value()
{
return "ros_arduino_msgs/Digital";
}
static const char* value(const ::ros_arduino_msgs::Digital_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::ros_arduino_msgs::Digital_<ContainerAllocator> >
{
static const char* value()
{
return "# Reading on a digital pin\n\
Header header\n\
uint8 value\n\
\n\
\n\
================================================================================\n\
MSG: std_msgs/Header\n\
# Standard metadata for higher-level stamped data types.\n\
# This is generally used to communicate timestamped data \n\
# in a particular coordinate frame.\n\
# \n\
# sequence ID: consecutively increasing ID \n\
uint32 seq\n\
#Two-integer timestamp that is expressed as:\n\
# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\
# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\
# time-handling sugar is provided by the client library\n\
time stamp\n\
#Frame this data is associated with\n\
# 0: no frame\n\
# 1: global frame\n\
string frame_id\n\
";
}
static const char* value(const ::ros_arduino_msgs::Digital_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::ros_arduino_msgs::Digital_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.header);
stream.next(m.value);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct Digital_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::ros_arduino_msgs::Digital_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::ros_arduino_msgs::Digital_<ContainerAllocator>& v)
{
s << indent << "header: ";
s << std::endl;
Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header);
s << indent << "value: ";
Printer<uint8_t>::stream(s, indent + " ", v.value);
}
};
} // namespace message_operations
} // namespace ros
#endif // ROS_ARDUINO_MSGS_MESSAGE_DIGITAL_H
| [
"18817776414@yeah.net"
] | 18817776414@yeah.net |
6e9eea5703e03c881e8a5f4fb67c1732c4a9fc77 | 8dbf8e350b809ac68435ad0e49ce17b98d20895f | /cpp_src/HelperFuncs.cpp | da5c8c7798441fde958cdb0faaca8254cdb14362 | [] | no_license | oralmer/algo_proj | c621967886fb95801e264e55d008b29c8d6394e8 | 7b6925c7a498e8457abc2713b756191b7048f9cc | refs/heads/master | 2020-04-06T07:38:47.436648 | 2019-08-10T19:15:49 | 2019-08-10T19:15:49 | 157,280,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 211 | cpp | #include "HelperFuncs.h"
std::ostream &operator<<(std::ostream &s, std::vector<char> t) {
for (const char i : t) {
if (i == '\0') {
break;
}
s << i;
}
return s;
} | [
"almer1or@gmail.com"
] | almer1or@gmail.com |
68481af64cbe538e311f0dae57711fc4c4c18a8d | af2b9daade951d0239c56468e31ac924aad2d7db | /StandardRound/r231div2-394/394-B-a.cpp | 3a0f902666bf3c83d989b5b77d7dcbd5ca1872b4 | [] | no_license | zentorwie/codeforces-solutions | 75446e153a95cb48fe8ce1ad7a214a9b16017c68 | 6ed365fff441f4b53294d7f4deb89e09fa8ea52e | refs/heads/master | 2020-05-18T07:10:42.245670 | 2014-08-01T12:51:11 | 2014-08-01T12:51:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 872 | cpp | #include <stdio.h>
#include <string>
int main()
{
int p, x;
char n[1000010] = {0};
int b = 0;
int t = 0; // to store
int next = 0;
int ptr = 0; // place
int ok = 0;
scanf("%d%d", &p, &x);
if (x == 1) {
for (int i = 0; i < p; i++) {
printf("1");
}
printf("\n");
return 0;
}
for (b = 1; b <= 9; b++) { //from 1 to 9
if (ok)
break;
n[0] = b;
next = 0;
t = 0;
for (ptr = 0; ptr < p; ptr++) {
next = n[ptr] * x + t;
t = next / 10;
// printf("next = %d\n", next);
if (ptr == p-1) {
if (t == 0 && (next % 10 == n[0]) && n[p-1] != 0) {
ok = 1;
}
}
else {
n[ptr+1] = next % 10;
}
}
}
if (ok) {
for (int i = p - 1; i >= 0; i--) {
printf("%d", n[i]);
}
printf("\n");
}
else
printf("Impossible\n");
return 0;
}
| [
"zentorwie@gmail.com"
] | zentorwie@gmail.com |
c869ca02eac219044f6b47c6d82bc3f3a8f7aaf8 | c7ad1dd84604e275ebfc5a7e354b23ceb598fca5 | /include/algo/structure/cd_utils/cuDmAlignedOptimalScore.hpp | 7583c980a69d05e87f5065eb9ba2eb8674f513bd | [] | no_license | svn2github/ncbi_tk | fc8cfcb75dfd79840e420162a8ae867826a3d922 | c9580988f9e5f7c770316163adbec8b7a40f89ca | refs/heads/master | 2023-09-03T12:30:52.531638 | 2017-05-15T14:17:27 | 2017-05-15T14:17:27 | 60,197,012 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,462 | hpp | #ifndef CU_DM_ALIGNED_OPTIMAL_SCORE__HPP
#define CU_DM_ALIGNED_OPTIMAL_SCORE__HPP
/* $Id$
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Chris Lanczycki
*
* File Description: cdt_dm_alignedscore.hpp
*
* Concrete distance matrix class.
* Distance is computed based on a scoring matrix, where the
* score is based on an existing alignment in a CD. A pair of parameters
* to extend an alignment at the N-terminal and C-terminal end can be specified.
* Different substitution matrices can be defined (see
* cdt_scoring_matrices.hpp for the supported scoring matrices).
*
*/
#include <algo/structure/cd_utils/cuDistmat.hpp>
#include <algo/structure/cd_utils/cuAlignedDM.hpp>
#include <algo/structure/cd_utils/cuBlockExtender.hpp>
BEGIN_NCBI_SCOPE
USING_SCOPE(objects);
BEGIN_SCOPE(cd_utils)
// The pairwise score between two rows in an alignment is the sum over the
// scores of each pair of aligned residues:
//
// d[i][j] = max_Score_for_CD - sum(k)( scoring_matrix(i_k, j_k))
//
// where x_k is the kth aligned residue of row x. The offset is to make
// high scores map to short distances. Although note that each row will
// in general have a different score for an exact match, making d=0 ambiguous.
class NCBI_CDUTILS_EXPORT DMAlignedOptimalScore : public AlignedDM {
static const EDistMethod DIST_METHOD;
public:
DMAlignedOptimalScore(EScoreMatrixType type = GLOBAL_DEFAULT_SCORE_MATRIX);
void setBlockExtender(BlockExtender* be);
virtual bool ComputeMatrix(pProgressFunction pFunc);
virtual ~DMAlignedOptimalScore();
private:
//the pair of block and sequence index
/* moved to algBlockExtender.hpp
typedef pair<Block, int> ScoringTerm;
double scoreBlockPair(const ScoringTerm& term1, const ScoringTerm& term, int** ppScores);
bool getScoringTerm(int row, int blockNum, int nExt, int cExt, ScoringTerm& st);
double optimizeBlockScore(int row1, int row2, int block, int** ppScores);
double scoreOneRowPair(int row1, int row2, int** ppScores); */
void convertScoreToDistance();
void initDMAlignedScore(EScoreMatrixType type, int nTermExt, int cTermExt);
BlockExtender* m_blockExtender;
};
END_SCOPE(cd_utils)
END_NCBI_SCOPE
#endif /* CU_DM_ALIGNED_OPTIMAL_SCORE__HPP */
| [
"lanczyck@112efe8e-fc92-43c6-89b6-d25c299ce97b"
] | lanczyck@112efe8e-fc92-43c6-89b6-d25c299ce97b |
6dbeb85c6cbb815057d90f4762f5565a3c34d33d | 357607a0cf01d44ecf97feaf047f7a9bad9a0be5 | /13.前端project/0.4/src/mappoint.cpp | d6fb1358264c7da9cde9b818178ba23330ce6031 | [
"DOC",
"GPL-3.0-or-later",
"MIT"
] | permissive | sunnieeee/VSLAM | 7699602cd2a8b3086660352fa9158d81c19badc7 | a0f58b7990f0706ff569481aadac81bb227f3332 | refs/heads/master | 2020-03-28T21:23:07.158817 | 2018-11-20T14:58:03 | 2018-11-20T14:58:03 | 149,150,830 | 0 | 0 | MIT | 2018-09-17T15:56:51 | 2018-09-17T15:56:51 | null | UTF-8 | C++ | false | false | 1,783 | cpp | /*=================================================================================
* Copyleft! 2018 William Yu
* Some rights reserved:CC(creativecommons.org)BY-NC-SA
* Copyleft! 2018 William Yu
* 版权部分所有,遵循CC(creativecommons.org)BY-NC-SA协议授权方式使用
*
* Filename :
* Description : 视觉SLAM十四讲 学习记录
* Reference :
* Programmer(s) : William Yu, windmillyucong@163.com
* Company : HUST, DMET国家重点实验室FOCUS团队
* Modification History : ver1.0, 2018.04.26, William Yu
* ver1.1, 2018.05.12, William Yu, add notes
=================================================================================*/
#include "myslam/common_include.h"
#include "myslam/mappoint.h"
namespace myslam
{
MapPoint::MapPoint()
: id_(-1), pos_(Vector3d(0,0,0)), norm_(Vector3d(0,0,0)), good_(true), visible_times_(0), matched_times_(0)
{
}
MapPoint::MapPoint ( long unsigned int id, const Vector3d& position, const Vector3d& norm, Frame* frame, const Mat& descriptor )
: id_(id), pos_(position), norm_(norm), good_(true), visible_times_(1), matched_times_(1), descriptor_(descriptor)
{
observed_frames_.push_back(frame);
}
MapPoint::Ptr MapPoint::createMapPoint()
{
return MapPoint::Ptr(
new MapPoint( factory_id_++, Vector3d(0,0,0), Vector3d(0,0,0) )
);
}
MapPoint::Ptr MapPoint::createMapPoint (
const Vector3d& pos_world,
const Vector3d& norm,
const Mat& descriptor,
Frame* frame )
{
return MapPoint::Ptr(
new MapPoint( factory_id_++, pos_world, norm, frame, descriptor )
);
}
unsigned long MapPoint::factory_id_ = 0;
}
| [
"windmillyucong@163.com"
] | windmillyucong@163.com |
4d4eae743c3bfe9be4774bcb3377e2f1309f818e | 9eff4a0c6890bc8571bb1115d14159ce93c2f5a7 | /include/kspp/utils/concurrent_queue.h | 28deb3aae43e8c05a759e8e97ca567a0b0edb1b4 | [
"BSL-1.0"
] | permissive | bitbouncer/kspp | d06865e46a1e3820e65d24edb951a48a996dffbf | 8539f359e32bd3dd1360ac4616eab88e79aab607 | refs/heads/master | 2022-10-20T22:45:11.118381 | 2022-09-28T14:50:00 | 2022-09-28T14:50:00 | 73,604,579 | 136 | 27 | BSL-1.0 | 2022-05-16T19:20:41 | 2016-11-13T08:42:34 | C++ | UTF-8 | C++ | false | false | 1,521 | h | #include <chrono>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#pragma once
template<typename T>
class concurrent_queue {
public:
concurrent_queue() = default;
concurrent_queue(const concurrent_queue &) = delete;
concurrent_queue &operator=(const concurrent_queue &) = delete;
void push(const T &item) {
std::unique_lock<std::mutex> lk(cv_m_);
queue_.push(item);
lk.unlock();
cv_.notify_one();
}
inline bool empty() const {
std::unique_lock<std::mutex> lk(cv_m_);
return queue_.empty();
}
T pop() {
std::unique_lock<std::mutex> lk(cv_m_);
while (queue_.empty())
cv_.wait(lk);
auto val = queue_.front();
queue_.pop();
return val;
}
void pop(T &item) {
std::unique_lock<std::mutex> lk(cv_m_);
while (queue_.empty())
cv_.wait(lk);
item = queue_.front();
queue_.pop();
}
bool try_pop(T &item) {
std::unique_lock<std::mutex> lk(cv_m_);
if (queue_.empty())
return false;
item = queue_.front();
queue_.pop();
return true;
}
template<class Rep, class Period>
bool try_pop(T &item, const std::chrono::duration<Rep, Period> &rel_time) {
std::unique_lock<std::mutex> lk(cv_m_);
while (queue_.empty()) {
if (cv_.wait_for(lk, rel_time) == std::cv_status::timeout)
return false;
}
item = queue_.front();
queue_.pop();
return true;
}
private:
std::queue<T> queue_;
std::mutex cv_m_;
std::condition_variable cv_;
}; | [
"svante.karlsson@csi.se"
] | svante.karlsson@csi.se |
7a71739778bfe25d00a2b26a4ec3343e2c57914c | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /net/base/network_interfaces_unittest.cc | 1469b49fbb537b05784fbe48f8853f5dd76b3a68 | [
"BSD-3-Clause"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 2,737 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/base/network_interfaces.h"
#include <ostream>
#include <string>
#include <unordered_set>
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "net/base/ip_endpoint.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(OS_POSIX) && !defined(OS_ANDROID)
#include <net/if.h>
#elif defined(OS_WIN)
#include <iphlpapi.h>
#include <objbase.h>
#endif
namespace net {
namespace {
// Verify GetNetworkList().
TEST(NetworkInterfacesTest, GetNetworkList) {
NetworkInterfaceList list;
ASSERT_TRUE(GetNetworkList(&list, INCLUDE_HOST_SCOPE_VIRTUAL_INTERFACES));
for (NetworkInterfaceList::iterator it = list.begin();
it != list.end(); ++it) {
// Verify that the names are not empty.
EXPECT_FALSE(it->name.empty());
EXPECT_FALSE(it->friendly_name.empty());
// Verify that the address is correct.
EXPECT_TRUE(it->address.IsValid()) << "Invalid address of size "
<< it->address.size();
EXPECT_FALSE(it->address.IsZero());
EXPECT_GT(it->prefix_length, 1u);
EXPECT_LE(it->prefix_length, it->address.size() * 8);
#if defined(OS_WIN)
// On Windows |name| is NET_LUID.
NET_LUID luid;
EXPECT_EQ(static_cast<DWORD>(NO_ERROR),
ConvertInterfaceIndexToLuid(it->interface_index, &luid));
GUID guid;
EXPECT_EQ(static_cast<DWORD>(NO_ERROR),
ConvertInterfaceLuidToGuid(&luid, &guid));
LPOLESTR name;
StringFromCLSID(guid, &name);
EXPECT_STREQ(base::UTF8ToWide(it->name).c_str(), name);
CoTaskMemFree(name);
if (it->type == NetworkChangeNotifier::CONNECTION_WIFI) {
EXPECT_NE(WIFI_PHY_LAYER_PROTOCOL_NONE, GetWifiPHYLayerProtocol());
}
#elif defined(OS_POSIX) && !defined(OS_ANDROID)
char name[IF_NAMESIZE];
EXPECT_TRUE(if_indextoname(it->interface_index, name));
EXPECT_STREQ(it->name.c_str(), name);
#endif
}
}
TEST(NetworkInterfacesTest, GetWifiSSID) {
// We can't check the result of GetWifiSSID() directly, since the result
// will differ across machines. Simply exercise the code path and hope that it
// doesn't crash.
EXPECT_NE((const char*)NULL, GetWifiSSID().c_str());
}
TEST(NetworkInterfacesTest, GetHostName) {
// We can't check the result of GetHostName() directly, since the result
// will differ across machines. Our goal here is to simply exercise the
// code path, and check that things "look about right".
std::string hostname = GetHostName();
EXPECT_FALSE(hostname.empty());
}
} // namespace
} // namespace net
| [
"jacob-chen@iotwrt.com"
] | jacob-chen@iotwrt.com |
b7aa80cb3fcff2c107bc9fc650b642bfe9ae500f | a421d742de106725206384622dcf774913357d11 | /include/inviwo/qt/widgets/inviwodockwidget.h | 97ed938ecbc2792fef643533b55fa7844dc80177 | [
"BSD-2-Clause"
] | permissive | sarbi127/inviwo | b91d0d57704a40faf720b4d9e2d29200f150a1cc | ae61d33d61128f584c08a704696bb4b3d0cc5eec | refs/heads/master | 2021-01-17T05:35:59.982468 | 2015-09-18T10:42:55 | 2015-09-18T10:43:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,435 | h | /*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2012-2015 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#ifndef IVW_INVIWODOCKWIDGET_H
#define IVW_INVIWODOCKWIDGET_H
#include <inviwo/qt/widgets/inviwoqtwidgetsdefine.h>
#include <QDockWidget>
class QKeyEvent;
class QLayout;
namespace inviwo {
class InviwoDockWidgetTitleBar;
class IVW_QTWIDGETS_API InviwoDockWidget : public QDockWidget {
Q_OBJECT
public:
InviwoDockWidget(QString title, QWidget* parent);
virtual ~InviwoDockWidget();
virtual void showEvent(QShowEvent* showEvent) override;
virtual void keyPressEvent(QKeyEvent* keyEvent) override;
void setSticky(bool sticky);
bool isSticky() const;
void setContents(QWidget *widget);
void setContents(QLayout *layout);
protected slots:
void updateWindowTitle(const QString &string);
private:
InviwoDockWidgetTitleBar* dockWidgetTitleBar_;
};
} // namespace
#endif // IVW_INVIWODOCKWIDGET_H
| [
"eriksunden85@gmail.com"
] | eriksunden85@gmail.com |
8d379faa2793030d5a6cb551ee0acd9c73bfe0db | ac51dce98cb821df7334619d2fd25c26757d17d4 | /eg2512554/Future_Value_Function/main.cpp | 30b0bfb30b42e01dd3a5a73316ccf5a5cc9ee404 | [] | no_license | Riverside-City-College-Computer-Science/CSC5_Winter_2014_40375 | a85aa5ef80ca44a0968fdbae52a5cd0c0a3ed621 | 853b40e40086ab97ef3075df4287b34a536c6573 | refs/heads/master | 2021-01-01T06:27:43.574978 | 2014-02-13T04:21:23 | 2014-02-13T04:21:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,537 | cpp | /*
* File: main.cpp
* Author: Edwin Gibbs
* Created on January 21, 2014, 8:49 AM
* Future Value Function
*/
//System Libraries
#include <iostream>
#include<cmath>
using namespace std;
//Global Constants
//Functional pro
float fv1(float, float, int);
float fv2(float, float, int);
float fv3(float, float, int);
float fv4(float, float, int);
float fv5(float, float, int);
int main(int argc, char** argv) {
//Execution begins here
//declare variables
float prin, interest;
int periods;
//Read in variables
cout<<"Principal = $'s"<<endl;
cin>>prin;
cout<<"Interest in %/year"<<endl;
cin>>interest;
cout<<"Number of compounding periods(yrs)"<<endl;
cin>>periods;
//run the function
cout<<"Future value =$"<<fv1(prin,interest,periods)<<endl;
cout<<"Future value =$"<<fv2(prin,interest,periods)<<endl;
cout<<"Future value =$"<<fv3(prin,interest,periods)<<endl;
cout<<"Future value =$"<<fv4(prin,interest,periods)<<endl;
cout<<"Future value =$"<<fv5(prin,interest,periods)<<endl;
return 0;
}
//Future value function
//input
//pv->Present value $'s
//iRate->Interest rate %
//n->Number of compounding periods (years)
//output
//future value in $'s
float fv5(float pv, float iRate, int n){
float save=pv;
for(int years=n;years>=1;years--){
save*=(1+iRate/100);
}
return save;
}
//Future value function
//input
//pv->Present value $'s
//iRate->Interest rate %
//n->Number of compounding periods (years)
//output
//future value in $'s
float fv4(float pv, float iRate, int n){
if(n==0)return pv;
else return fv4(pv,iRate,n-1)*(1+iRate/100);
}
//Future value function
//input
//pv->Present value $'s
//iRate->Interest rate %
//n->Number of compounding periods (years)
//output
//future value in $'s
float fv3(float pv, float iRate, int n){
return static_cast<float>(pv*exp(n*log(1.0+iRate/100.0)));
}
//Future value function
//input
//pv->Present value $'s
//iRate->Interest rate %
//n->Number of compounding periods (years)
//output
//future value in $'s
float fv2(float pv, float iRate, int n){
return static_cast<float>(pv*exp(n*log(1.0+iRate/100.0)));
}
//Future value function
//input
//pv->Present value $'s
//iRate->Interest rate %
//n->Number of compounding periods (years)
//output
//future value in $'s
float fv1(float pv, float iRate, int n){
float save=pv;
for(int years=1;years<=n;years++){
save*=(1+iRate/100);
}
return save;
}
| [
"eddygibbs007@yahoo.com"
] | eddygibbs007@yahoo.com |
46b29b845775d2221650855a97a523ccc84c4a95 | da6a4172a23472d1eb54722203452555745c4354 | /lib/tinyxml2/xmltest.cpp | 663f6aa5ea4b208808ec9e7cb9003d9c4e9ff9e4 | [
"Zlib"
] | permissive | HenrikSte/esp32msi | ec380dc5cd1b245f10ab1594e3c8eb7d9615bf4c | a12295eb7e97f0dd4fb5a484f7654b0cfe2b0883 | refs/heads/master | 2021-11-08T03:04:25.374338 | 2019-11-13T08:22:47 | 2019-11-13T08:22:47 | 150,953,418 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 76,693 | cpp | #if defined( _MSC_VER )
#if !defined( _CRT_SECURE_NO_WARNINGS )
#define _CRT_SECURE_NO_WARNINGS // This test file is not intended to be secure.
#endif
#endif
#include "tinyxml2.h"
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <ctime>
#if defined( _MSC_VER ) || defined (WIN32)
#include <crtdbg.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
_CrtMemState startMemState;
_CrtMemState endMemState;
#else
#include <sys/stat.h>
#include <sys/types.h>
#endif
using namespace tinyxml2;
using namespace std;
int gPass = 0;
int gFail = 0;
bool XMLTest (const char* testString, const char* expected, const char* found, bool echo=true, bool extraNL=false )
{
bool pass;
if ( !expected && !found )
pass = true;
else if ( !expected || !found )
pass = false;
else
pass = !strcmp( expected, found );
if ( pass )
printf ("[pass]");
else
printf ("[fail]");
if ( !echo ) {
printf (" %s\n", testString);
}
else {
if ( extraNL ) {
printf( " %s\n", testString );
printf( "%s\n", expected );
printf( "%s\n", found );
}
else {
printf (" %s [%s][%s]\n", testString, expected, found);
}
}
if ( pass )
++gPass;
else
++gFail;
return pass;
}
bool XMLTest(const char* testString, XMLError expected, XMLError found, bool echo = true, bool extraNL = false)
{
return XMLTest(testString, XMLDocument::ErrorIDToName(expected), XMLDocument::ErrorIDToName(found), echo, extraNL);
}
bool XMLTest(const char* testString, bool expected, bool found, bool echo = true, bool extraNL = false)
{
return XMLTest(testString, expected ? "true" : "false", found ? "true" : "false", echo, extraNL);
}
template< class T > bool XMLTest( const char* testString, T expected, T found, bool echo=true )
{
bool pass = ( expected == found );
if ( pass )
printf ("[pass]");
else
printf ("[fail]");
if ( !echo )
printf (" %s\n", testString);
else
printf (" %s [%d][%d]\n", testString, static_cast<int>(expected), static_cast<int>(found) );
if ( pass )
++gPass;
else
++gFail;
return pass;
}
void NullLineEndings( char* p )
{
while( p && *p ) {
if ( *p == '\n' || *p == '\r' ) {
*p = 0;
return;
}
++p;
}
}
int example_1()
{
XMLDocument doc;
doc.LoadFile( "resources/dream.xml" );
return doc.ErrorID();
}
/** @page Example_1 Load an XML File
* @dontinclude ./xmltest.cpp
* Basic XML file loading.
* The basic syntax to load an XML file from
* disk and check for an error. (ErrorID()
* will return 0 for no error.)
* @skip example_1()
* @until }
*/
int example_2()
{
static const char* xml = "<element/>";
XMLDocument doc;
doc.Parse( xml );
return doc.ErrorID();
}
/** @page Example_2 Parse an XML from char buffer
* @dontinclude ./xmltest.cpp
* Basic XML string parsing.
* The basic syntax to parse an XML for
* a char* and check for an error. (ErrorID()
* will return 0 for no error.)
* @skip example_2()
* @until }
*/
int example_3()
{
static const char* xml =
"<?xml version=\"1.0\"?>"
"<!DOCTYPE PLAY SYSTEM \"play.dtd\">"
"<PLAY>"
"<TITLE>A Midsummer Night's Dream</TITLE>"
"</PLAY>";
XMLDocument doc;
doc.Parse( xml );
XMLElement* titleElement = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" );
const char* title = titleElement->GetText();
printf( "Name of play (1): %s\n", title );
XMLText* textNode = titleElement->FirstChild()->ToText();
title = textNode->Value();
printf( "Name of play (2): %s\n", title );
return doc.ErrorID();
}
/** @page Example_3 Get information out of XML
@dontinclude ./xmltest.cpp
In this example, we navigate a simple XML
file, and read some interesting text. Note
that this example doesn't use error
checking; working code should check for null
pointers when walking an XML tree, or use
XMLHandle.
(The XML is an excerpt from "dream.xml").
@skip example_3()
@until </PLAY>";
The structure of the XML file is:
<ul>
<li>(declaration)</li>
<li>(dtd stuff)</li>
<li>Element "PLAY"</li>
<ul>
<li>Element "TITLE"</li>
<ul>
<li>Text "A Midsummer Night's Dream"</li>
</ul>
</ul>
</ul>
For this example, we want to print out the
title of the play. The text of the title (what
we want) is child of the "TITLE" element which
is a child of the "PLAY" element.
We want to skip the declaration and dtd, so the
method FirstChildElement() is a good choice. The
FirstChildElement() of the Document is the "PLAY"
Element, the FirstChildElement() of the "PLAY" Element
is the "TITLE" Element.
@until ( "TITLE" );
We can then use the convenience function GetText()
to get the title of the play.
@until title );
Text is just another Node in the XML DOM. And in
fact you should be a little cautious with it, as
text nodes can contain elements.
@verbatim
Consider: A Midsummer Night's <b>Dream</b>
@endverbatim
It is more correct to actually query the Text Node
if in doubt:
@until title );
Noting that here we use FirstChild() since we are
looking for XMLText, not an element, and ToText()
is a cast from a Node to a XMLText.
*/
bool example_4()
{
static const char* xml =
"<information>"
" <attributeApproach v='2' />"
" <textApproach>"
" <v>2</v>"
" </textApproach>"
"</information>";
XMLDocument doc;
doc.Parse( xml );
int v0 = 0;
int v1 = 0;
XMLElement* attributeApproachElement = doc.FirstChildElement()->FirstChildElement( "attributeApproach" );
attributeApproachElement->QueryIntAttribute( "v", &v0 );
XMLElement* textApproachElement = doc.FirstChildElement()->FirstChildElement( "textApproach" );
textApproachElement->FirstChildElement( "v" )->QueryIntText( &v1 );
printf( "Both values are the same: %d and %d\n", v0, v1 );
return !doc.Error() && ( v0 == v1 );
}
/** @page Example_4 Read attributes and text information.
@dontinclude ./xmltest.cpp
There are fundamentally 2 ways of writing a key-value
pair into an XML file. (Something that's always annoyed
me about XML.) Either by using attributes, or by writing
the key name into an element and the value into
the text node wrapped by the element. Both approaches
are illustrated in this example, which shows two ways
to encode the value "2" into the key "v":
@skip example_4()
@until "</information>";
TinyXML-2 has accessors for both approaches.
When using an attribute, you navigate to the XMLElement
with that attribute and use the QueryIntAttribute()
group of methods. (Also QueryFloatAttribute(), etc.)
@skip XMLElement* attributeApproachElement
@until &v0 );
When using the text approach, you need to navigate
down one more step to the XMLElement that contains
the text. Note the extra FirstChildElement( "v" )
in the code below. The value of the text can then
be safely queried with the QueryIntText() group
of methods. (Also QueryFloatText(), etc.)
@skip XMLElement* textApproachElement
@until &v1 );
*/
int main( int argc, const char ** argv )
{
#if defined( _MSC_VER ) && defined( TINYXML2_DEBUG )
_CrtMemCheckpoint( &startMemState );
// Enable MS Visual C++ debug heap memory leaks dump on exit
_CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF);
{
int leaksOnStart = _CrtDumpMemoryLeaks();
XMLTest( "No leaks on start?", FALSE, leaksOnStart );
}
#endif
{
TIXMLASSERT( true );
}
if ( argc > 1 ) {
XMLDocument* doc = new XMLDocument();
clock_t startTime = clock();
doc->LoadFile( argv[1] );
clock_t loadTime = clock();
int errorID = doc->ErrorID();
delete doc; doc = 0;
clock_t deleteTime = clock();
printf( "Test file '%s' loaded. ErrorID=%d\n", argv[1], errorID );
if ( !errorID ) {
printf( "Load time=%u\n", (unsigned)(loadTime - startTime) );
printf( "Delete time=%u\n", (unsigned)(deleteTime - loadTime) );
printf( "Total time=%u\n", (unsigned)(deleteTime - startTime) );
}
exit(0);
}
FILE* fp = fopen( "resources/dream.xml", "r" );
if ( !fp ) {
printf( "Error opening test file 'dream.xml'.\n"
"Is your working directory the same as where \n"
"the xmltest.cpp and dream.xml file are?\n\n"
#if defined( _MSC_VER )
"In windows Visual Studio you may need to set\n"
"Properties->Debugging->Working Directory to '..'\n"
#endif
);
exit( 1 );
}
fclose( fp );
XMLTest( "Example_1", 0, example_1() );
XMLTest( "Example_2", 0, example_2() );
XMLTest( "Example_3", 0, example_3() );
XMLTest( "Example_4", true, example_4() );
/* ------ Example 2: Lookup information. ---- */
{
static const char* test[] = { "<element />",
"<element></element>",
"<element><subelement/></element>",
"<element><subelement></subelement></element>",
"<element><subelement><subsub/></subelement></element>",
"<!--comment beside elements--><element><subelement></subelement></element>",
"<!--comment beside elements, this time with spaces--> \n <element> <subelement> \n </subelement> </element>",
"<element attrib1='foo' attrib2=\"bar\" ></element>",
"<element attrib1='foo' attrib2=\"bar\" ><subelement attrib3='yeehaa' /></element>",
"<element>Text inside element.</element>",
"<element><b></b></element>",
"<element>Text inside and <b>bolded</b> in the element.</element>",
"<outer><element>Text inside and <b>bolded</b> in the element.</element></outer>",
"<element>This & That.</element>",
"<element attrib='This<That' />",
0
};
for( int i=0; test[i]; ++i ) {
XMLDocument doc;
doc.Parse( test[i] );
XMLTest( "Element test", false, doc.Error() );
doc.Print();
printf( "----------------------------------------------\n" );
}
}
#if 1
{
static const char* test = "<!--hello world\n"
" line 2\r"
" line 3\r\n"
" line 4\n\r"
" line 5\r-->";
XMLDocument doc;
doc.Parse( test );
XMLTest( "Hello world declaration", false, doc.Error() );
doc.Print();
}
{
// This test is pre-test for the next one
// (where Element1 is inserted "after itself".
// This code didn't use to crash.
XMLDocument doc;
XMLElement* element1 = doc.NewElement("Element1");
XMLElement* element2 = doc.NewElement("Element2");
doc.InsertEndChild(element1);
doc.InsertEndChild(element2);
doc.InsertAfterChild(element2, element2);
doc.InsertAfterChild(element2, element2);
}
{
XMLDocument doc;
XMLElement* element1 = doc.NewElement("Element1");
XMLElement* element2 = doc.NewElement("Element2");
doc.InsertEndChild(element1);
doc.InsertEndChild(element2);
// This insertion "after itself"
// used to cause invalid memory access and crash
doc.InsertAfterChild(element1, element1);
doc.InsertAfterChild(element1, element1);
doc.InsertAfterChild(element2, element2);
doc.InsertAfterChild(element2, element2);
}
{
static const char* test = "<element>Text before.</element>";
XMLDocument doc;
doc.Parse( test );
XMLTest( "Element text before", false, doc.Error() );
XMLElement* root = doc.FirstChildElement();
XMLElement* newElement = doc.NewElement( "Subelement" );
root->InsertEndChild( newElement );
doc.Print();
}
{
XMLDocument* doc = new XMLDocument();
static const char* test = "<element><sub/></element>";
doc->Parse( test );
XMLTest( "Element with sub element", false, doc->Error() );
delete doc;
}
{
// Test: Programmatic DOM nodes insertion return values
XMLDocument doc;
XMLNode* first = doc.NewElement( "firstElement" );
XMLTest( "New element", true, first != 0 );
XMLNode* firstAfterInsertion = doc.InsertFirstChild( first );
XMLTest( "New element inserted first", true, firstAfterInsertion == first );
XMLNode* last = doc.NewElement( "lastElement" );
XMLTest( "New element", true, last != 0 );
XMLNode* lastAfterInsertion = doc.InsertEndChild( last );
XMLTest( "New element inserted last", true, lastAfterInsertion == last );
XMLNode* middle = doc.NewElement( "middleElement" );
XMLTest( "New element", true, middle != 0 );
XMLNode* middleAfterInsertion = doc.InsertAfterChild( first, middle );
XMLTest( "New element inserted middle", true, middleAfterInsertion == middle );
}
{
// Test: Programmatic DOM
// Build:
// <element>
// <!--comment-->
// <sub attrib="1" />
// <sub attrib="2" />
// <sub attrib="3" >& Text!</sub>
// <element>
XMLDocument* doc = new XMLDocument();
XMLNode* element = doc->InsertEndChild( doc->NewElement( "element" ) );
XMLElement* sub[3] = { doc->NewElement( "sub" ), doc->NewElement( "sub" ), doc->NewElement( "sub" ) };
for( int i=0; i<3; ++i ) {
sub[i]->SetAttribute( "attrib", i );
}
element->InsertEndChild( sub[2] );
const int dummyInitialValue = 1000;
int dummyValue = dummyInitialValue;
XMLNode* comment = element->InsertFirstChild( doc->NewComment( "comment" ) );
comment->SetUserData(&dummyValue);
element->InsertAfterChild( comment, sub[0] );
element->InsertAfterChild( sub[0], sub[1] );
sub[2]->InsertFirstChild( doc->NewText( "& Text!" ));
doc->Print();
XMLTest( "Programmatic DOM", "comment", doc->FirstChildElement( "element" )->FirstChild()->Value() );
XMLTest( "Programmatic DOM", "0", doc->FirstChildElement( "element" )->FirstChildElement()->Attribute( "attrib" ) );
XMLTest( "Programmatic DOM", 2, doc->FirstChildElement()->LastChildElement( "sub" )->IntAttribute( "attrib" ) );
XMLTest( "Programmatic DOM", "& Text!",
doc->FirstChildElement()->LastChildElement( "sub" )->FirstChild()->ToText()->Value() );
XMLTest("User data - pointer", true, &dummyValue == comment->GetUserData(), false);
XMLTest("User data - value behind pointer", dummyInitialValue, dummyValue, false);
// And now deletion:
element->DeleteChild( sub[2] );
doc->DeleteNode( comment );
element->FirstChildElement()->SetAttribute( "attrib", true );
element->LastChildElement()->DeleteAttribute( "attrib" );
XMLTest( "Programmatic DOM", true, doc->FirstChildElement()->FirstChildElement()->BoolAttribute( "attrib" ) );
const int defaultIntValue = 10;
const int replacementIntValue = 20;
int value1 = defaultIntValue;
int value2 = doc->FirstChildElement()->LastChildElement()->IntAttribute( "attrib", replacementIntValue );
XMLError result = doc->FirstChildElement()->LastChildElement()->QueryIntAttribute( "attrib", &value1 );
XMLTest( "Programmatic DOM", XML_NO_ATTRIBUTE, result );
XMLTest( "Programmatic DOM", defaultIntValue, value1 );
XMLTest( "Programmatic DOM", replacementIntValue, value2 );
doc->Print();
{
XMLPrinter streamer;
doc->Print( &streamer );
printf( "%s", streamer.CStr() );
}
{
XMLPrinter streamer( 0, true );
doc->Print( &streamer );
XMLTest( "Compact mode", "<element><sub attrib=\"true\"/><sub/></element>", streamer.CStr(), false );
}
doc->SaveFile( "./resources/out/pretty.xml" );
XMLTest( "Save pretty.xml", false, doc->Error() );
doc->SaveFile( "./resources/out/compact.xml", true );
XMLTest( "Save compact.xml", false, doc->Error() );
delete doc;
}
{
// Test: Dream
// XML1 : 1,187,569 bytes in 31,209 allocations
// XML2 : 469,073 bytes in 323 allocations
//int newStart = gNew;
XMLDocument doc;
doc.LoadFile( "resources/dream.xml" );
XMLTest( "Load dream.xml", false, doc.Error() );
doc.SaveFile( "resources/out/dreamout.xml" );
XMLTest( "Save dreamout.xml", false, doc.Error() );
doc.PrintError();
XMLTest( "Dream", "xml version=\"1.0\"",
doc.FirstChild()->ToDeclaration()->Value() );
XMLTest( "Dream", true, doc.FirstChild()->NextSibling()->ToUnknown() != 0 );
XMLTest( "Dream", "DOCTYPE PLAY SYSTEM \"play.dtd\"",
doc.FirstChild()->NextSibling()->ToUnknown()->Value() );
XMLTest( "Dream", "And Robin shall restore amends.",
doc.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() );
XMLTest( "Dream", "And Robin shall restore amends.",
doc.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() );
XMLDocument doc2;
doc2.LoadFile( "resources/out/dreamout.xml" );
XMLTest( "Load dreamout.xml", false, doc2.Error() );
XMLTest( "Dream-out", "xml version=\"1.0\"",
doc2.FirstChild()->ToDeclaration()->Value() );
XMLTest( "Dream-out", true, doc2.FirstChild()->NextSibling()->ToUnknown() != 0 );
XMLTest( "Dream-out", "DOCTYPE PLAY SYSTEM \"play.dtd\"",
doc2.FirstChild()->NextSibling()->ToUnknown()->Value() );
XMLTest( "Dream-out", "And Robin shall restore amends.",
doc2.LastChild()->LastChild()->LastChild()->LastChild()->LastChildElement()->GetText() );
//gNewTotal = gNew - newStart;
}
{
const char* error = "<?xml version=\"1.0\" standalone=\"no\" ?>\n"
"<passages count=\"006\" formatversion=\"20020620\">\n"
" <wrong error>\n"
"</passages>";
XMLDocument doc;
doc.Parse( error );
XMLTest( "Bad XML", XML_ERROR_PARSING_ATTRIBUTE, doc.ErrorID() );
const char* errorStr = doc.ErrorStr();
XMLTest("Formatted error string",
"Error=XML_ERROR_PARSING_ATTRIBUTE ErrorID=7 (0x7) Line number=3: XMLElement name=wrong",
errorStr);
}
{
const char* str = "<doc attr0='1' attr1='2.0' attr2='foo' />";
XMLDocument doc;
doc.Parse( str );
XMLTest( "Top level attributes", false, doc.Error() );
XMLElement* ele = doc.FirstChildElement();
int iVal;
XMLError result;
double dVal;
result = ele->QueryDoubleAttribute( "attr0", &dVal );
XMLTest( "Query attribute: int as double", XML_SUCCESS, result);
XMLTest( "Query attribute: int as double", 1, (int)dVal );
XMLTest( "Query attribute: int as double", 1, (int)ele->DoubleAttribute("attr0"));
result = ele->QueryDoubleAttribute( "attr1", &dVal );
XMLTest( "Query attribute: double as double", XML_SUCCESS, result);
XMLTest( "Query attribute: double as double", 2.0, dVal );
XMLTest( "Query attribute: double as double", 2.0, ele->DoubleAttribute("attr1") );
result = ele->QueryIntAttribute( "attr1", &iVal );
XMLTest( "Query attribute: double as int", XML_SUCCESS, result);
XMLTest( "Query attribute: double as int", 2, iVal );
result = ele->QueryIntAttribute( "attr2", &iVal );
XMLTest( "Query attribute: not a number", XML_WRONG_ATTRIBUTE_TYPE, result );
XMLTest( "Query attribute: not a number", 4.0, ele->DoubleAttribute("attr2", 4.0) );
result = ele->QueryIntAttribute( "bar", &iVal );
XMLTest( "Query attribute: does not exist", XML_NO_ATTRIBUTE, result );
XMLTest( "Query attribute: does not exist", true, ele->BoolAttribute("bar", true) );
}
{
const char* str = "<doc/>";
XMLDocument doc;
doc.Parse( str );
XMLTest( "Empty top element", false, doc.Error() );
XMLElement* ele = doc.FirstChildElement();
int iVal, iVal2;
double dVal, dVal2;
ele->SetAttribute( "str", "strValue" );
ele->SetAttribute( "int", 1 );
ele->SetAttribute( "double", -1.0 );
const char* cStr = ele->Attribute( "str" );
{
XMLError queryResult = ele->QueryIntAttribute( "int", &iVal );
XMLTest( "Query int attribute", XML_SUCCESS, queryResult);
}
{
XMLError queryResult = ele->QueryDoubleAttribute( "double", &dVal );
XMLTest( "Query double attribute", XML_SUCCESS, queryResult);
}
{
int queryResult = ele->QueryAttribute( "int", &iVal2 );
XMLTest( "Query int attribute generic", (int)XML_SUCCESS, queryResult);
}
{
int queryResult = ele->QueryAttribute( "double", &dVal2 );
XMLTest( "Query double attribute generic", (int)XML_SUCCESS, queryResult);
}
XMLTest( "Attribute match test", "strValue", ele->Attribute( "str", "strValue" ) );
XMLTest( "Attribute round trip. c-string.", "strValue", cStr );
XMLTest( "Attribute round trip. int.", 1, iVal );
XMLTest( "Attribute round trip. double.", -1, (int)dVal );
XMLTest( "Alternate query", true, iVal == iVal2 );
XMLTest( "Alternate query", true, dVal == dVal2 );
XMLTest( "Alternate query", true, iVal == ele->IntAttribute("int") );
XMLTest( "Alternate query", true, dVal == ele->DoubleAttribute("double") );
}
{
XMLDocument doc;
doc.LoadFile( "resources/utf8test.xml" );
XMLTest( "Load utf8test.xml", false, doc.Error() );
// Get the attribute "value" from the "Russian" element and check it.
XMLElement* element = doc.FirstChildElement( "document" )->FirstChildElement( "Russian" );
const unsigned char correctValue[] = { 0xd1U, 0x86U, 0xd0U, 0xb5U, 0xd0U, 0xbdU, 0xd0U, 0xbdU,
0xd0U, 0xbeU, 0xd1U, 0x81U, 0xd1U, 0x82U, 0xd1U, 0x8cU, 0 };
XMLTest( "UTF-8: Russian value.", (const char*)correctValue, element->Attribute( "value" ) );
const unsigned char russianElementName[] = { 0xd0U, 0xa0U, 0xd1U, 0x83U,
0xd1U, 0x81U, 0xd1U, 0x81U,
0xd0U, 0xbaU, 0xd0U, 0xb8U,
0xd0U, 0xb9U, 0 };
const char russianText[] = "<\xD0\xB8\xD0\xBC\xD0\xB5\xD0\xB5\xD1\x82>";
XMLText* text = doc.FirstChildElement( "document" )->FirstChildElement( (const char*) russianElementName )->FirstChild()->ToText();
XMLTest( "UTF-8: Browsing russian element name.",
russianText,
text->Value() );
// Now try for a round trip.
doc.SaveFile( "resources/out/utf8testout.xml" );
XMLTest( "UTF-8: Save testout.xml", false, doc.Error() );
// Check the round trip.
bool roundTripOkay = false;
FILE* saved = fopen( "resources/out/utf8testout.xml", "r" );
XMLTest( "UTF-8: Open utf8testout.xml", true, saved != 0 );
FILE* verify = fopen( "resources/utf8testverify.xml", "r" );
XMLTest( "UTF-8: Open utf8testverify.xml", true, verify != 0 );
if ( saved && verify )
{
roundTripOkay = true;
char verifyBuf[256];
while ( fgets( verifyBuf, 256, verify ) )
{
char savedBuf[256];
fgets( savedBuf, 256, saved );
NullLineEndings( verifyBuf );
NullLineEndings( savedBuf );
if ( strcmp( verifyBuf, savedBuf ) )
{
printf( "verify:%s<\n", verifyBuf );
printf( "saved :%s<\n", savedBuf );
roundTripOkay = false;
break;
}
}
}
if ( saved )
fclose( saved );
if ( verify )
fclose( verify );
XMLTest( "UTF-8: Verified multi-language round trip.", true, roundTripOkay );
}
// --------GetText()-----------
{
const char* str = "<foo>This is text</foo>";
XMLDocument doc;
doc.Parse( str );
XMLTest( "Double whitespace", false, doc.Error() );
const XMLElement* element = doc.RootElement();
XMLTest( "GetText() normal use.", "This is text", element->GetText() );
str = "<foo><b>This is text</b></foo>";
doc.Parse( str );
XMLTest( "Bold text simulation", false, doc.Error() );
element = doc.RootElement();
XMLTest( "GetText() contained element.", element->GetText() == 0, true );
}
// --------SetText()-----------
{
const char* str = "<foo></foo>";
XMLDocument doc;
doc.Parse( str );
XMLTest( "Empty closed element", false, doc.Error() );
XMLElement* element = doc.RootElement();
element->SetText("darkness.");
XMLTest( "SetText() normal use (open/close).", "darkness.", element->GetText() );
element->SetText("blue flame.");
XMLTest( "SetText() replace.", "blue flame.", element->GetText() );
str = "<foo/>";
doc.Parse( str );
XMLTest( "Empty self-closed element", false, doc.Error() );
element = doc.RootElement();
element->SetText("The driver");
XMLTest( "SetText() normal use. (self-closing)", "The driver", element->GetText() );
element->SetText("<b>horses</b>");
XMLTest( "SetText() replace with tag-like text.", "<b>horses</b>", element->GetText() );
//doc.Print();
str = "<foo><bar>Text in nested element</bar></foo>";
doc.Parse( str );
XMLTest( "Text in nested element", false, doc.Error() );
element = doc.RootElement();
element->SetText("wolves");
XMLTest( "SetText() prefix to nested non-text children.", "wolves", element->GetText() );
str = "<foo/>";
doc.Parse( str );
XMLTest( "Empty self-closed element round 2", false, doc.Error() );
element = doc.RootElement();
element->SetText( "str" );
XMLTest( "SetText types", "str", element->GetText() );
element->SetText( 1 );
XMLTest( "SetText types", "1", element->GetText() );
element->SetText( 1U );
XMLTest( "SetText types", "1", element->GetText() );
element->SetText( true );
XMLTest( "SetText types", "true", element->GetText() );
element->SetText( 1.5f );
XMLTest( "SetText types", "1.5", element->GetText() );
element->SetText( 1.5 );
XMLTest( "SetText types", "1.5", element->GetText() );
}
// ---------- Attributes ---------
{
static const int64_t BIG = -123456789012345678;
XMLDocument doc;
XMLElement* element = doc.NewElement("element");
doc.InsertFirstChild(element);
{
element->SetAttribute("attrib", int(-100));
{
int v = 0;
XMLError queryResult = element->QueryIntAttribute("attrib", &v);
XMLTest("Attribute: int", XML_SUCCESS, queryResult, true);
XMLTest("Attribute: int", -100, v, true);
}
{
int v = 0;
int queryResult = element->QueryAttribute("attrib", &v);
XMLTest("Attribute: int", (int)XML_SUCCESS, queryResult, true);
XMLTest("Attribute: int", -100, v, true);
}
XMLTest("Attribute: int", -100, element->IntAttribute("attrib"), true);
}
{
element->SetAttribute("attrib", unsigned(100));
{
unsigned v = 0;
XMLError queryResult = element->QueryUnsignedAttribute("attrib", &v);
XMLTest("Attribute: unsigned", XML_SUCCESS, queryResult, true);
XMLTest("Attribute: unsigned", unsigned(100), v, true);
}
{
unsigned v = 0;
int queryResult = element->QueryAttribute("attrib", &v);
XMLTest("Attribute: unsigned", (int)XML_SUCCESS, queryResult, true);
XMLTest("Attribute: unsigned", unsigned(100), v, true);
}
{
const char* v = "failed";
XMLError queryResult = element->QueryStringAttribute("not-attrib", &v);
XMLTest("Attribute: string default", false, queryResult == XML_SUCCESS);
queryResult = element->QueryStringAttribute("attrib", &v);
XMLTest("Attribute: string", XML_SUCCESS, queryResult, true);
XMLTest("Attribute: string", "100", v);
}
XMLTest("Attribute: unsigned", unsigned(100), element->UnsignedAttribute("attrib"), true);
}
{
element->SetAttribute("attrib", BIG);
{
int64_t v = 0;
XMLError queryResult = element->QueryInt64Attribute("attrib", &v);
XMLTest("Attribute: int64_t", XML_SUCCESS, queryResult, true);
XMLTest("Attribute: int64_t", BIG, v, true);
}
{
int64_t v = 0;
int queryResult = element->QueryAttribute("attrib", &v);
XMLTest("Attribute: int64_t", (int)XML_SUCCESS, queryResult, true);
XMLTest("Attribute: int64_t", BIG, v, true);
}
XMLTest("Attribute: int64_t", BIG, element->Int64Attribute("attrib"), true);
}
{
element->SetAttribute("attrib", true);
{
bool v = false;
XMLError queryResult = element->QueryBoolAttribute("attrib", &v);
XMLTest("Attribute: bool", XML_SUCCESS, queryResult, true);
XMLTest("Attribute: bool", true, v, true);
}
{
bool v = false;
int queryResult = element->QueryAttribute("attrib", &v);
XMLTest("Attribute: bool", (int)XML_SUCCESS, queryResult, true);
XMLTest("Attribute: bool", true, v, true);
}
XMLTest("Attribute: bool", true, element->BoolAttribute("attrib"), true);
}
{
element->SetAttribute("attrib", true);
const char* result = element->Attribute("attrib");
XMLTest("Bool true is 'true'", "true", result);
XMLUtil::SetBoolSerialization("1", "0");
element->SetAttribute("attrib", true);
result = element->Attribute("attrib");
XMLTest("Bool true is '1'", "1", result);
XMLUtil::SetBoolSerialization(0, 0);
}
{
element->SetAttribute("attrib", 100.0);
{
double v = 0;
XMLError queryResult = element->QueryDoubleAttribute("attrib", &v);
XMLTest("Attribute: double", XML_SUCCESS, queryResult, true);
XMLTest("Attribute: double", 100.0, v, true);
}
{
double v = 0;
int queryResult = element->QueryAttribute("attrib", &v);
XMLTest("Attribute: bool", (int)XML_SUCCESS, queryResult, true);
XMLTest("Attribute: double", 100.0, v, true);
}
XMLTest("Attribute: double", 100.0, element->DoubleAttribute("attrib"), true);
}
{
element->SetAttribute("attrib", 100.0f);
{
float v = 0;
XMLError queryResult = element->QueryFloatAttribute("attrib", &v);
XMLTest("Attribute: float", XML_SUCCESS, queryResult, true);
XMLTest("Attribute: float", 100.0f, v, true);
}
{
float v = 0;
int queryResult = element->QueryAttribute("attrib", &v);
XMLTest("Attribute: float", (int)XML_SUCCESS, queryResult, true);
XMLTest("Attribute: float", 100.0f, v, true);
}
XMLTest("Attribute: float", 100.0f, element->FloatAttribute("attrib"), true);
}
{
element->SetText(BIG);
int64_t v = 0;
XMLError queryResult = element->QueryInt64Text(&v);
XMLTest("Element: int64_t", XML_SUCCESS, queryResult, true);
XMLTest("Element: int64_t", BIG, v, true);
}
}
// ---------- XMLPrinter stream mode ------
{
{
FILE* printerfp = fopen("resources/out/printer.xml", "w");
XMLTest("Open printer.xml", true, printerfp != 0);
XMLPrinter printer(printerfp);
printer.OpenElement("foo");
printer.PushAttribute("attrib-text", "text");
printer.PushAttribute("attrib-int", int(1));
printer.PushAttribute("attrib-unsigned", unsigned(2));
printer.PushAttribute("attrib-int64", int64_t(3));
printer.PushAttribute("attrib-bool", true);
printer.PushAttribute("attrib-double", 4.0);
printer.CloseElement();
fclose(printerfp);
}
{
XMLDocument doc;
doc.LoadFile("resources/out/printer.xml");
XMLTest("XMLPrinter Stream mode: load", XML_SUCCESS, doc.ErrorID(), true);
const XMLDocument& cdoc = doc;
const XMLAttribute* attrib = cdoc.FirstChildElement("foo")->FindAttribute("attrib-text");
XMLTest("attrib-text", "text", attrib->Value(), true);
attrib = cdoc.FirstChildElement("foo")->FindAttribute("attrib-int");
XMLTest("attrib-int", int(1), attrib->IntValue(), true);
attrib = cdoc.FirstChildElement("foo")->FindAttribute("attrib-unsigned");
XMLTest("attrib-unsigned", unsigned(2), attrib->UnsignedValue(), true);
attrib = cdoc.FirstChildElement("foo")->FindAttribute("attrib-int64");
XMLTest("attrib-int64", int64_t(3), attrib->Int64Value(), true);
attrib = cdoc.FirstChildElement("foo")->FindAttribute("attrib-bool");
XMLTest("attrib-bool", true, attrib->BoolValue(), true);
attrib = cdoc.FirstChildElement("foo")->FindAttribute("attrib-double");
XMLTest("attrib-double", 4.0, attrib->DoubleValue(), true);
}
}
// ---------- CDATA ---------------
{
const char* str = "<xmlElement>"
"<![CDATA["
"I am > the rules!\n"
"...since I make symbolic puns"
"]]>"
"</xmlElement>";
XMLDocument doc;
doc.Parse( str );
XMLTest( "CDATA symbolic puns round 1", false, doc.Error() );
doc.Print();
XMLTest( "CDATA parse.", "I am > the rules!\n...since I make symbolic puns",
doc.FirstChildElement()->FirstChild()->Value(),
false );
}
// ----------- CDATA -------------
{
const char* str = "<xmlElement>"
"<![CDATA["
"<b>I am > the rules!</b>\n"
"...since I make symbolic puns"
"]]>"
"</xmlElement>";
XMLDocument doc;
doc.Parse( str );
XMLTest( "CDATA symbolic puns round 2", false, doc.Error() );
doc.Print();
XMLTest( "CDATA parse. [ tixml1:1480107 ]",
"<b>I am > the rules!</b>\n...since I make symbolic puns",
doc.FirstChildElement()->FirstChild()->Value(),
false );
}
// InsertAfterChild causes crash.
{
// InsertBeforeChild and InsertAfterChild causes crash.
XMLDocument doc;
XMLElement* parent = doc.NewElement( "Parent" );
doc.InsertFirstChild( parent );
XMLElement* childText0 = doc.NewElement( "childText0" );
XMLElement* childText1 = doc.NewElement( "childText1" );
XMLNode* childNode0 = parent->InsertEndChild( childText0 );
XMLTest( "InsertEndChild() return", true, childNode0 == childText0 );
XMLNode* childNode1 = parent->InsertAfterChild( childNode0, childText1 );
XMLTest( "InsertAfterChild() return", true, childNode1 == childText1 );
XMLTest( "Test InsertAfterChild on empty node. ", true, ( childNode1 == parent->LastChild() ) );
}
{
// Entities not being written correctly.
// From Lynn Allen
const char* passages =
"<?xml version=\"1.0\" standalone=\"no\" ?>"
"<passages count=\"006\" formatversion=\"20020620\">"
"<psg context=\"Line 5 has "quotation marks" and 'apostrophe marks'."
" It also has <, >, and &, as well as a fake copyright ©.\"> </psg>"
"</passages>";
XMLDocument doc;
doc.Parse( passages );
XMLTest( "Entity transformation parse round 1", false, doc.Error() );
XMLElement* psg = doc.RootElement()->FirstChildElement();
const char* context = psg->Attribute( "context" );
const char* expected = "Line 5 has \"quotation marks\" and 'apostrophe marks'. It also has <, >, and &, as well as a fake copyright \xC2\xA9.";
XMLTest( "Entity transformation: read. ", expected, context, true );
const char* textFilePath = "resources/out/textfile.txt";
FILE* textfile = fopen( textFilePath, "w" );
XMLTest( "Entity transformation: open text file for writing", true, textfile != 0, true );
if ( textfile )
{
XMLPrinter streamer( textfile );
bool acceptResult = psg->Accept( &streamer );
fclose( textfile );
XMLTest( "Entity transformation: Accept", true, acceptResult );
}
textfile = fopen( textFilePath, "r" );
XMLTest( "Entity transformation: open text file for reading", true, textfile != 0, true );
if ( textfile )
{
char buf[ 1024 ];
fgets( buf, 1024, textfile );
XMLTest( "Entity transformation: write. ",
"<psg context=\"Line 5 has "quotation marks" and 'apostrophe marks'."
" It also has <, >, and &, as well as a fake copyright \xC2\xA9.\"/>\n",
buf, false );
fclose( textfile );
}
}
{
// Suppress entities.
const char* passages =
"<?xml version=\"1.0\" standalone=\"no\" ?>"
"<passages count=\"006\" formatversion=\"20020620\">"
"<psg context=\"Line 5 has "quotation marks" and 'apostrophe marks'.\">Crazy &ttk;</psg>"
"</passages>";
XMLDocument doc( false );
doc.Parse( passages );
XMLTest( "Entity transformation parse round 2", false, doc.Error() );
XMLTest( "No entity parsing.",
"Line 5 has "quotation marks" and 'apostrophe marks'.",
doc.FirstChildElement()->FirstChildElement()->Attribute( "context" ) );
XMLTest( "No entity parsing.", "Crazy &ttk;",
doc.FirstChildElement()->FirstChildElement()->FirstChild()->Value() );
doc.Print();
}
{
const char* test = "<?xml version='1.0'?><a.elem xmi.version='2.0'/>";
XMLDocument doc;
doc.Parse( test );
XMLTest( "dot in names", false, doc.Error() );
XMLTest( "dot in names", "a.elem", doc.FirstChildElement()->Name() );
XMLTest( "dot in names", "2.0", doc.FirstChildElement()->Attribute( "xmi.version" ) );
}
{
const char* test = "<element><Name>1.1 Start easy ignore fin thickness
</Name></element>";
XMLDocument doc;
doc.Parse( test );
XMLTest( "fin thickness", false, doc.Error() );
XMLText* text = doc.FirstChildElement()->FirstChildElement()->FirstChild()->ToText();
XMLTest( "Entity with one digit.",
"1.1 Start easy ignore fin thickness\n", text->Value(),
false );
}
{
// DOCTYPE not preserved (950171)
//
const char* doctype =
"<?xml version=\"1.0\" ?>"
"<!DOCTYPE PLAY SYSTEM 'play.dtd'>"
"<!ELEMENT title (#PCDATA)>"
"<!ELEMENT books (title,authors)>"
"<element />";
XMLDocument doc;
doc.Parse( doctype );
XMLTest( "PLAY SYSTEM parse", false, doc.Error() );
doc.SaveFile( "resources/out/test7.xml" );
XMLTest( "PLAY SYSTEM save", false, doc.Error() );
doc.DeleteChild( doc.RootElement() );
doc.LoadFile( "resources/out/test7.xml" );
XMLTest( "PLAY SYSTEM load", false, doc.Error() );
doc.Print();
const XMLUnknown* decl = doc.FirstChild()->NextSibling()->ToUnknown();
XMLTest( "Correct value of unknown.", "DOCTYPE PLAY SYSTEM 'play.dtd'", decl->Value() );
}
{
// Comments do not stream out correctly.
const char* doctype =
"<!-- Somewhat<evil> -->";
XMLDocument doc;
doc.Parse( doctype );
XMLTest( "Comment somewhat evil", false, doc.Error() );
XMLComment* comment = doc.FirstChild()->ToComment();
XMLTest( "Comment formatting.", " Somewhat<evil> ", comment->Value() );
}
{
// Double attributes
const char* doctype = "<element attr='red' attr='blue' />";
XMLDocument doc;
doc.Parse( doctype );
XMLTest( "Parsing repeated attributes.", XML_ERROR_PARSING_ATTRIBUTE, doc.ErrorID() ); // is an error to tinyxml (didn't use to be, but caused issues)
doc.PrintError();
}
{
// Embedded null in stream.
const char* doctype = "<element att\0r='red' attr='blue' />";
XMLDocument doc;
doc.Parse( doctype );
XMLTest( "Embedded null throws error.", true, doc.Error() );
}
{
// Empty documents should return TIXML_XML_ERROR_PARSING_EMPTY, bug 1070717
const char* str = "";
XMLDocument doc;
doc.Parse( str );
XMLTest( "Empty document error", XML_ERROR_EMPTY_DOCUMENT, doc.ErrorID() );
// But be sure there is an error string!
const char* errorStr = doc.ErrorStr();
XMLTest("Error string should be set",
"Error=XML_ERROR_EMPTY_DOCUMENT ErrorID=13 (0xd) Line number=0",
errorStr);
}
{
// Documents with all whitespaces should return TIXML_XML_ERROR_PARSING_EMPTY, bug 1070717
const char* str = " ";
XMLDocument doc;
doc.Parse( str );
XMLTest( "All whitespaces document error", XML_ERROR_EMPTY_DOCUMENT, doc.ErrorID() );
}
{
// Low entities
XMLDocument doc;
doc.Parse( "<test></test>" );
XMLTest( "Hex values", false, doc.Error() );
const char result[] = { 0x0e, 0 };
XMLTest( "Low entities.", result, doc.FirstChildElement()->GetText() );
doc.Print();
}
{
// Attribute values with trailing quotes not handled correctly
XMLDocument doc;
doc.Parse( "<foo attribute=bar\" />" );
XMLTest( "Throw error with bad end quotes.", true, doc.Error() );
}
{
// [ 1663758 ] Failure to report error on bad XML
XMLDocument xml;
xml.Parse("<x>");
XMLTest("Missing end tag at end of input", true, xml.Error());
xml.Parse("<x> ");
XMLTest("Missing end tag with trailing whitespace", true, xml.Error());
xml.Parse("<x></y>");
XMLTest("Mismatched tags", XML_ERROR_MISMATCHED_ELEMENT, xml.ErrorID() );
}
{
// [ 1475201 ] TinyXML parses entities in comments
XMLDocument xml;
xml.Parse("<!-- declarations for <head> & <body> -->"
"<!-- far & away -->" );
XMLTest( "Declarations for head and body", false, xml.Error() );
XMLNode* e0 = xml.FirstChild();
XMLNode* e1 = e0->NextSibling();
XMLComment* c0 = e0->ToComment();
XMLComment* c1 = e1->ToComment();
XMLTest( "Comments ignore entities.", " declarations for <head> & <body> ", c0->Value(), true );
XMLTest( "Comments ignore entities.", " far & away ", c1->Value(), true );
}
{
XMLDocument xml;
xml.Parse( "<Parent>"
"<child1 att=''/>"
"<!-- With this comment, child2 will not be parsed! -->"
"<child2 att=''/>"
"</Parent>" );
XMLTest( "Comments iteration", false, xml.Error() );
xml.Print();
int count = 0;
for( XMLNode* ele = xml.FirstChildElement( "Parent" )->FirstChild();
ele;
ele = ele->NextSibling() )
{
++count;
}
XMLTest( "Comments iterate correctly.", 3, count );
}
{
// trying to repro ]1874301]. If it doesn't go into an infinite loop, all is well.
unsigned char buf[] = "<?xml version=\"1.0\" encoding=\"utf-8\"?><feed><![CDATA[Test XMLblablablalblbl";
buf[60] = 239;
buf[61] = 0;
XMLDocument doc;
doc.Parse( (const char*)buf);
XMLTest( "Broken CDATA", true, doc.Error() );
}
{
// bug 1827248 Error while parsing a little bit malformed file
// Actually not malformed - should work.
XMLDocument xml;
xml.Parse( "<attributelist> </attributelist >" );
XMLTest( "Handle end tag whitespace", false, xml.Error() );
}
{
// This one must not result in an infinite loop
XMLDocument xml;
xml.Parse( "<infinite>loop" );
XMLTest( "No closing element", true, xml.Error() );
XMLTest( "Infinite loop test.", true, true );
}
#endif
{
const char* pub = "<?xml version='1.0'?> <element><sub/></element> <!--comment--> <!DOCTYPE>";
XMLDocument doc;
doc.Parse( pub );
XMLTest( "Trailing DOCTYPE", false, doc.Error() );
XMLDocument clone;
for( const XMLNode* node=doc.FirstChild(); node; node=node->NextSibling() ) {
XMLNode* copy = node->ShallowClone( &clone );
clone.InsertEndChild( copy );
}
clone.Print();
int count=0;
const XMLNode* a=clone.FirstChild();
const XMLNode* b=doc.FirstChild();
for( ; a && b; a=a->NextSibling(), b=b->NextSibling() ) {
++count;
XMLTest( "Clone and Equal", true, a->ShallowEqual( b ));
}
XMLTest( "Clone and Equal", 4, count );
}
{
// Deep Cloning of root element.
XMLDocument doc2;
XMLPrinter printer1;
{
// Make sure doc1 is deleted before we test doc2
const char* xml =
"<root>"
" <child1 foo='bar'/>"
" <!-- comment thing -->"
" <child2 val='1'>Text</child2>"
"</root>";
XMLDocument doc;
doc.Parse(xml);
XMLTest( "Parse before deep cloning root element", false, doc.Error() );
doc.Print(&printer1);
XMLNode* root = doc.RootElement()->DeepClone(&doc2);
doc2.InsertFirstChild(root);
}
XMLPrinter printer2;
doc2.Print(&printer2);
XMLTest("Deep clone of element.", printer1.CStr(), printer2.CStr(), true);
}
{
// Deep Cloning of sub element.
XMLDocument doc2;
XMLPrinter printer1;
{
// Make sure doc1 is deleted before we test doc2
const char* xml =
"<?xml version ='1.0'?>"
"<root>"
" <child1 foo='bar'/>"
" <!-- comment thing -->"
" <child2 val='1'>Text</child2>"
"</root>";
XMLDocument doc;
doc.Parse(xml);
XMLTest( "Parse before deep cloning sub element", false, doc.Error() );
const XMLElement* subElement = doc.FirstChildElement("root")->FirstChildElement("child2");
bool acceptResult = subElement->Accept(&printer1);
XMLTest( "Accept before deep cloning", true, acceptResult );
XMLNode* clonedSubElement = subElement->DeepClone(&doc2);
doc2.InsertFirstChild(clonedSubElement);
}
XMLPrinter printer2;
doc2.Print(&printer2);
XMLTest("Deep clone of sub-element.", printer1.CStr(), printer2.CStr(), true);
}
{
// Deep cloning of document.
XMLDocument doc2;
XMLPrinter printer1;
{
// Make sure doc1 is deleted before we test doc2
const char* xml =
"<?xml version ='1.0'?>"
"<!-- Top level comment. -->"
"<root>"
" <child1 foo='bar'/>"
" <!-- comment thing -->"
" <child2 val='1'>Text</child2>"
"</root>";
XMLDocument doc;
doc.Parse(xml);
XMLTest( "Parse before deep cloning document", false, doc.Error() );
doc.Print(&printer1);
doc.DeepCopy(&doc2);
}
XMLPrinter printer2;
doc2.Print(&printer2);
XMLTest("DeepCopy of document.", printer1.CStr(), printer2.CStr(), true);
}
{
// This shouldn't crash.
XMLDocument doc;
if(XML_SUCCESS != doc.LoadFile( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ))
{
doc.PrintError();
}
XMLTest( "Error in snprinf handling.", true, doc.Error() );
}
{
// Attribute ordering.
static const char* xml = "<element attrib1=\"1\" attrib2=\"2\" attrib3=\"3\" />";
XMLDocument doc;
doc.Parse( xml );
XMLTest( "Parse for attribute ordering", false, doc.Error() );
XMLElement* ele = doc.FirstChildElement();
const XMLAttribute* a = ele->FirstAttribute();
XMLTest( "Attribute order", "1", a->Value() );
a = a->Next();
XMLTest( "Attribute order", "2", a->Value() );
a = a->Next();
XMLTest( "Attribute order", "3", a->Value() );
XMLTest( "Attribute order", "attrib3", a->Name() );
ele->DeleteAttribute( "attrib2" );
a = ele->FirstAttribute();
XMLTest( "Attribute order", "1", a->Value() );
a = a->Next();
XMLTest( "Attribute order", "3", a->Value() );
ele->DeleteAttribute( "attrib1" );
ele->DeleteAttribute( "attrib3" );
XMLTest( "Attribute order (empty)", true, ele->FirstAttribute() == 0 );
}
{
// Make sure an attribute with a space in it succeeds.
static const char* xml0 = "<element attribute1= \"Test Attribute\"/>";
static const char* xml1 = "<element attribute1 =\"Test Attribute\"/>";
static const char* xml2 = "<element attribute1 = \"Test Attribute\"/>";
XMLDocument doc0;
doc0.Parse( xml0 );
XMLTest( "Parse attribute with space 1", false, doc0.Error() );
XMLDocument doc1;
doc1.Parse( xml1 );
XMLTest( "Parse attribute with space 2", false, doc1.Error() );
XMLDocument doc2;
doc2.Parse( xml2 );
XMLTest( "Parse attribute with space 3", false, doc2.Error() );
XMLElement* ele = 0;
ele = doc0.FirstChildElement();
XMLTest( "Attribute with space #1", "Test Attribute", ele->Attribute( "attribute1" ) );
ele = doc1.FirstChildElement();
XMLTest( "Attribute with space #2", "Test Attribute", ele->Attribute( "attribute1" ) );
ele = doc2.FirstChildElement();
XMLTest( "Attribute with space #3", "Test Attribute", ele->Attribute( "attribute1" ) );
}
{
// Make sure we don't go into an infinite loop.
static const char* xml = "<doc><element attribute='attribute'/><element attribute='attribute'/></doc>";
XMLDocument doc;
doc.Parse( xml );
XMLTest( "Parse two elements with attribute", false, doc.Error() );
XMLElement* ele0 = doc.FirstChildElement()->FirstChildElement();
XMLElement* ele1 = ele0->NextSiblingElement();
bool equal = ele0->ShallowEqual( ele1 );
XMLTest( "Infinite loop in shallow equal.", true, equal );
}
// -------- Handles ------------
{
static const char* xml = "<element attrib='bar'><sub>Text</sub></element>";
XMLDocument doc;
doc.Parse( xml );
XMLTest( "Handle, parse element with attribute and nested element", false, doc.Error() );
{
XMLElement* ele = XMLHandle( doc ).FirstChildElement( "element" ).FirstChild().ToElement();
XMLTest( "Handle, non-const, element is found", true, ele != 0 );
XMLTest( "Handle, non-const, element name matches", "sub", ele->Value() );
}
{
XMLHandle docH( doc );
XMLElement* ele = docH.FirstChildElement( "noSuchElement" ).FirstChildElement( "element" ).ToElement();
XMLTest( "Handle, non-const, element not found", true, ele == 0 );
}
{
const XMLElement* ele = XMLConstHandle( doc ).FirstChildElement( "element" ).FirstChild().ToElement();
XMLTest( "Handle, const, element is found", true, ele != 0 );
XMLTest( "Handle, const, element name matches", "sub", ele->Value() );
}
{
XMLConstHandle docH( doc );
const XMLElement* ele = docH.FirstChildElement( "noSuchElement" ).FirstChildElement( "element" ).ToElement();
XMLTest( "Handle, const, element not found", true, ele == 0 );
}
}
{
// Default Declaration & BOM
XMLDocument doc;
doc.InsertEndChild( doc.NewDeclaration() );
doc.SetBOM( true );
XMLPrinter printer;
doc.Print( &printer );
static const char* result = "\xef\xbb\xbf<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
XMLTest( "BOM and default declaration", result, printer.CStr(), false );
XMLTest( "CStrSize", 42, printer.CStrSize(), false );
}
{
const char* xml = "<ipxml ws='1'><info bla=' /></ipxml>";
XMLDocument doc;
doc.Parse( xml );
XMLTest( "Ill formed XML", true, doc.Error() );
}
// QueryXYZText
{
const char* xml = "<point> <x>1.2</x> <y>1</y> <z>38</z> <valid>true</valid> </point>";
XMLDocument doc;
doc.Parse( xml );
XMLTest( "Parse points", false, doc.Error() );
const XMLElement* pointElement = doc.RootElement();
{
int intValue = 0;
XMLError queryResult = pointElement->FirstChildElement( "y" )->QueryIntText( &intValue );
XMLTest( "QueryIntText result", XML_SUCCESS, queryResult, false );
XMLTest( "QueryIntText", 1, intValue, false );
}
{
unsigned unsignedValue = 0;
XMLError queryResult = pointElement->FirstChildElement( "y" )->QueryUnsignedText( &unsignedValue );
XMLTest( "QueryUnsignedText result", XML_SUCCESS, queryResult, false );
XMLTest( "QueryUnsignedText", (unsigned)1, unsignedValue, false );
}
{
float floatValue = 0;
XMLError queryResult = pointElement->FirstChildElement( "x" )->QueryFloatText( &floatValue );
XMLTest( "QueryFloatText result", XML_SUCCESS, queryResult, false );
XMLTest( "QueryFloatText", 1.2f, floatValue, false );
}
{
double doubleValue = 0;
XMLError queryResult = pointElement->FirstChildElement( "x" )->QueryDoubleText( &doubleValue );
XMLTest( "QueryDoubleText result", XML_SUCCESS, queryResult, false );
XMLTest( "QueryDoubleText", 1.2, doubleValue, false );
}
{
bool boolValue = false;
XMLError queryResult = pointElement->FirstChildElement( "valid" )->QueryBoolText( &boolValue );
XMLTest( "QueryBoolText result", XML_SUCCESS, queryResult, false );
XMLTest( "QueryBoolText", true, boolValue, false );
}
}
{
const char* xml = "<element><_sub/><:sub/><sub:sub/><sub-sub/></element>";
XMLDocument doc;
doc.Parse( xml );
XMLTest( "Non-alpha element lead letter parses.", false, doc.Error() );
}
{
const char* xml = "<element _attr1=\"foo\" :attr2=\"bar\"></element>";
XMLDocument doc;
doc.Parse( xml );
XMLTest("Non-alpha attribute lead character parses.", false, doc.Error());
}
{
const char* xml = "<3lement></3lement>";
XMLDocument doc;
doc.Parse( xml );
XMLTest("Element names with lead digit fail to parse.", true, doc.Error());
}
{
const char* xml = "<element/>WOA THIS ISN'T GOING TO PARSE";
XMLDocument doc;
doc.Parse( xml, 10 );
XMLTest( "Set length of incoming data", false, doc.Error() );
}
{
XMLDocument doc;
XMLTest( "Document is initially empty", true, doc.NoChildren() );
doc.Clear();
XMLTest( "Empty is empty after Clear()", true, doc.NoChildren() );
doc.LoadFile( "resources/dream.xml" );
XMLTest( "Load dream.xml", false, doc.Error() );
XMLTest( "Document has something to Clear()", false, doc.NoChildren() );
doc.Clear();
XMLTest( "Document Clear()'s", true, doc.NoChildren() );
}
{
XMLDocument doc;
XMLTest( "No error initially", false, doc.Error() );
XMLError error = doc.Parse( "This is not XML" );
XMLTest( "Error after invalid XML", true, doc.Error() );
XMLTest( "Error after invalid XML", error, doc.ErrorID() );
doc.Clear();
XMLTest( "No error after Clear()", false, doc.Error() );
}
// ----------- Whitespace ------------
{
const char* xml = "<element>"
"<a> This \nis ' text ' </a>"
"<b> This is ' text ' \n</b>"
"<c>This is ' \n\n text '</c>"
"</element>";
XMLDocument doc( true, COLLAPSE_WHITESPACE );
doc.Parse( xml );
XMLTest( "Parse with whitespace collapsing and &apos", false, doc.Error() );
const XMLElement* element = doc.FirstChildElement();
for( const XMLElement* parent = element->FirstChildElement();
parent;
parent = parent->NextSiblingElement() )
{
XMLTest( "Whitespace collapse", "This is ' text '", parent->GetText() );
}
}
#if 0
{
// Passes if assert doesn't fire.
XMLDocument xmlDoc;
xmlDoc.NewDeclaration();
xmlDoc.NewComment("Configuration file");
XMLElement *root = xmlDoc.NewElement("settings");
root->SetAttribute("version", 2);
}
#endif
{
const char* xml = "<element> </element>";
XMLDocument doc( true, COLLAPSE_WHITESPACE );
doc.Parse( xml );
XMLTest( "Parse with all whitespaces", false, doc.Error() );
XMLTest( "Whitespace all space", true, 0 == doc.FirstChildElement()->FirstChild() );
}
{
// An assert should not fire.
const char* xml = "<element/>";
XMLDocument doc;
doc.Parse( xml );
XMLTest( "Parse with self-closed element", false, doc.Error() );
XMLElement* ele = doc.NewElement( "unused" ); // This will get cleaned up with the 'doc' going out of scope.
XMLTest( "Tracking unused elements", true, ele != 0, false );
}
{
const char* xml = "<parent><child>abc</child></parent>";
XMLDocument doc;
doc.Parse( xml );
XMLTest( "Parse for printing of sub-element", false, doc.Error() );
XMLElement* ele = doc.FirstChildElement( "parent")->FirstChildElement( "child");
XMLPrinter printer;
bool acceptResult = ele->Accept( &printer );
XMLTest( "Accept of sub-element", true, acceptResult );
XMLTest( "Printing of sub-element", "<child>abc</child>\n", printer.CStr(), false );
}
{
XMLDocument doc;
XMLError error = doc.LoadFile( "resources/empty.xml" );
XMLTest( "Loading an empty file", XML_ERROR_EMPTY_DOCUMENT, error );
XMLTest( "Loading an empty file and ErrorName as string", "XML_ERROR_EMPTY_DOCUMENT", doc.ErrorName() );
doc.PrintError();
}
{
// BOM preservation
static const char* xml_bom_preservation = "\xef\xbb\xbf<element/>\n";
{
XMLDocument doc;
XMLTest( "BOM preservation (parse)", XML_SUCCESS, doc.Parse( xml_bom_preservation ), false );
XMLPrinter printer;
doc.Print( &printer );
XMLTest( "BOM preservation (compare)", xml_bom_preservation, printer.CStr(), false, true );
doc.SaveFile( "resources/bomtest.xml" );
XMLTest( "Save bomtest.xml", false, doc.Error() );
}
{
XMLDocument doc;
doc.LoadFile( "resources/bomtest.xml" );
XMLTest( "Load bomtest.xml", false, doc.Error() );
XMLTest( "BOM preservation (load)", true, doc.HasBOM(), false );
XMLPrinter printer;
doc.Print( &printer );
XMLTest( "BOM preservation (compare)", xml_bom_preservation, printer.CStr(), false, true );
}
}
{
// Insertion with Removal
const char* xml = "<?xml version=\"1.0\" ?>"
"<root>"
"<one>"
"<subtree>"
"<elem>element 1</elem>text<!-- comment -->"
"</subtree>"
"</one>"
"<two/>"
"</root>";
const char* xmlInsideTwo = "<?xml version=\"1.0\" ?>"
"<root>"
"<one/>"
"<two>"
"<subtree>"
"<elem>element 1</elem>text<!-- comment -->"
"</subtree>"
"</two>"
"</root>";
const char* xmlAfterOne = "<?xml version=\"1.0\" ?>"
"<root>"
"<one/>"
"<subtree>"
"<elem>element 1</elem>text<!-- comment -->"
"</subtree>"
"<two/>"
"</root>";
const char* xmlAfterTwo = "<?xml version=\"1.0\" ?>"
"<root>"
"<one/>"
"<two/>"
"<subtree>"
"<elem>element 1</elem>text<!-- comment -->"
"</subtree>"
"</root>";
XMLDocument doc;
doc.Parse(xml);
XMLTest( "Insertion with removal parse round 1", false, doc.Error() );
XMLElement* subtree = doc.RootElement()->FirstChildElement("one")->FirstChildElement("subtree");
XMLElement* two = doc.RootElement()->FirstChildElement("two");
two->InsertFirstChild(subtree);
XMLPrinter printer1(0, true);
bool acceptResult = doc.Accept(&printer1);
XMLTest("Move node from within <one> to <two> - Accept()", true, acceptResult);
XMLTest("Move node from within <one> to <two>", xmlInsideTwo, printer1.CStr());
doc.Parse(xml);
XMLTest( "Insertion with removal parse round 2", false, doc.Error() );
subtree = doc.RootElement()->FirstChildElement("one")->FirstChildElement("subtree");
two = doc.RootElement()->FirstChildElement("two");
doc.RootElement()->InsertAfterChild(two, subtree);
XMLPrinter printer2(0, true);
acceptResult = doc.Accept(&printer2);
XMLTest("Move node from within <one> after <two> - Accept()", true, acceptResult);
XMLTest("Move node from within <one> after <two>", xmlAfterTwo, printer2.CStr(), false);
doc.Parse(xml);
XMLTest( "Insertion with removal parse round 3", false, doc.Error() );
XMLNode* one = doc.RootElement()->FirstChildElement("one");
subtree = one->FirstChildElement("subtree");
doc.RootElement()->InsertAfterChild(one, subtree);
XMLPrinter printer3(0, true);
acceptResult = doc.Accept(&printer3);
XMLTest("Move node from within <one> after <one> - Accept()", true, acceptResult);
XMLTest("Move node from within <one> after <one>", xmlAfterOne, printer3.CStr(), false);
doc.Parse(xml);
XMLTest( "Insertion with removal parse round 4", false, doc.Error() );
subtree = doc.RootElement()->FirstChildElement("one")->FirstChildElement("subtree");
two = doc.RootElement()->FirstChildElement("two");
doc.RootElement()->InsertEndChild(subtree);
XMLPrinter printer4(0, true);
acceptResult = doc.Accept(&printer4);
XMLTest("Move node from within <one> after <two> - Accept()", true, acceptResult);
XMLTest("Move node from within <one> after <two>", xmlAfterTwo, printer4.CStr(), false);
}
{
const char* xml = "<svg width = \"128\" height = \"128\">"
" <text> </text>"
"</svg>";
XMLDocument doc;
doc.Parse(xml);
XMLTest( "Parse svg with text", false, doc.Error() );
doc.Print();
}
{
// Test that it doesn't crash.
const char* xml = "<?xml version=\"1.0\"?><root><sample><field0><1</field0><field1>2</field1></sample></root>";
XMLDocument doc;
doc.Parse(xml);
XMLTest( "Parse root-sample-field0", true, doc.Error() );
doc.PrintError();
}
#if 1
// the question being explored is what kind of print to use:
// https://github.com/leethomason/tinyxml2/issues/63
{
//const char* xml = "<element attrA='123456789.123456789' attrB='1.001e9' attrC='1.0e-10' attrD='1001000000.000000' attrE='0.1234567890123456789'/>";
const char* xml = "<element/>";
XMLDocument doc;
doc.Parse( xml );
XMLTest( "Parse self-closed empty element", false, doc.Error() );
doc.FirstChildElement()->SetAttribute( "attrA-f64", 123456789.123456789 );
doc.FirstChildElement()->SetAttribute( "attrB-f64", 1.001e9 );
doc.FirstChildElement()->SetAttribute( "attrC-f64", 1.0e9 );
doc.FirstChildElement()->SetAttribute( "attrC-f64", 1.0e20 );
doc.FirstChildElement()->SetAttribute( "attrD-f64", 1.0e-10 );
doc.FirstChildElement()->SetAttribute( "attrD-f64", 0.123456789 );
doc.FirstChildElement()->SetAttribute( "attrA-f32", 123456789.123456789f );
doc.FirstChildElement()->SetAttribute( "attrB-f32", 1.001e9f );
doc.FirstChildElement()->SetAttribute( "attrC-f32", 1.0e9f );
doc.FirstChildElement()->SetAttribute( "attrC-f32", 1.0e20f );
doc.FirstChildElement()->SetAttribute( "attrD-f32", 1.0e-10f );
doc.FirstChildElement()->SetAttribute( "attrD-f32", 0.123456789f );
doc.Print();
/* The result of this test is platform, compiler, and library version dependent. :("
XMLPrinter printer;
doc.Print( &printer );
XMLTest( "Float and double formatting.",
"<element attrA-f64=\"123456789.12345679\" attrB-f64=\"1001000000\" attrC-f64=\"1e+20\" attrD-f64=\"0.123456789\" attrA-f32=\"1.2345679e+08\" attrB-f32=\"1.001e+09\" attrC-f32=\"1e+20\" attrD-f32=\"0.12345679\"/>\n",
printer.CStr(),
true );
*/
}
#endif
{
// Issue #184
// If it doesn't assert, it passes. Caused by objects
// getting created during parsing which are then
// inaccessible in the memory pools.
const char* xmlText = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><test>";
{
XMLDocument doc;
doc.Parse(xmlText);
XMLTest( "Parse hex no closing tag round 1", true, doc.Error() );
}
{
XMLDocument doc;
doc.Parse(xmlText);
XMLTest( "Parse hex no closing tag round 2", true, doc.Error() );
doc.Clear();
}
}
{
// If this doesn't assert in TINYXML2_DEBUG, all is well.
tinyxml2::XMLDocument doc;
tinyxml2::XMLElement *pRoot = doc.NewElement("Root");
doc.DeleteNode(pRoot);
}
{
XMLDocument doc;
XMLElement* root = doc.NewElement( "Root" );
XMLTest( "Node document before insertion", true, &doc == root->GetDocument() );
doc.InsertEndChild( root );
XMLTest( "Node document after insertion", true, &doc == root->GetDocument() );
}
{
// If this doesn't assert in TINYXML2_DEBUG, all is well.
XMLDocument doc;
XMLElement* unlinkedRoot = doc.NewElement( "Root" );
XMLElement* linkedRoot = doc.NewElement( "Root" );
doc.InsertFirstChild( linkedRoot );
unlinkedRoot->GetDocument()->DeleteNode( linkedRoot );
unlinkedRoot->GetDocument()->DeleteNode( unlinkedRoot );
}
{
// Should not assert in TINYXML2_DEBUG
XMLPrinter printer;
}
{
// Issue 291. Should not crash
const char* xml = "�</a>";
XMLDocument doc;
doc.Parse( xml );
XMLTest( "Parse hex with closing tag", false, doc.Error() );
XMLPrinter printer;
doc.Print( &printer );
}
{
// Issue 299. Can print elements that are not linked in.
// Will crash if issue not fixed.
XMLDocument doc;
XMLElement* newElement = doc.NewElement( "printme" );
XMLPrinter printer;
bool acceptResult = newElement->Accept( &printer );
XMLTest( "printme - Accept()", true, acceptResult );
// Delete the node to avoid possible memory leak report in debug output
doc.DeleteNode( newElement );
}
{
// Issue 302. Clear errors from LoadFile/SaveFile
XMLDocument doc;
XMLTest( "Issue 302. Should be no error initially", "XML_SUCCESS", doc.ErrorName() );
doc.SaveFile( "./no/such/path/pretty.xml" );
XMLTest( "Issue 302. Fail to save", "XML_ERROR_FILE_COULD_NOT_BE_OPENED", doc.ErrorName() );
doc.SaveFile( "./resources/out/compact.xml", true );
XMLTest( "Issue 302. Subsequent success in saving", "XML_SUCCESS", doc.ErrorName() );
}
{
// If a document fails to load then subsequent
// successful loads should clear the error
XMLDocument doc;
XMLTest( "Should be no error initially", false, doc.Error() );
doc.LoadFile( "resources/no-such-file.xml" );
XMLTest( "No such file - should fail", true, doc.Error() );
doc.LoadFile( "resources/dream.xml" );
XMLTest( "Error should be cleared", false, doc.Error() );
}
{
// Check that declarations are allowed only at beginning of document
const char* xml0 = "<?xml version=\"1.0\" ?>"
" <!-- xml version=\"1.1\" -->"
"<first />";
const char* xml1 = "<?xml version=\"1.0\" ?>"
"<?xml-stylesheet type=\"text/xsl\" href=\"Anything.xsl\"?>"
"<first />";
const char* xml2 = "<first />"
"<?xml version=\"1.0\" ?>";
const char* xml3 = "<first></first>"
"<?xml version=\"1.0\" ?>";
const char* xml4 = "<first><?xml version=\"1.0\" ?></first>";
XMLDocument doc;
doc.Parse(xml0);
XMLTest("Test that the code changes do not affect normal parsing", false, doc.Error() );
doc.Parse(xml1);
XMLTest("Test that the second declaration is allowed", false, doc.Error() );
doc.Parse(xml2);
XMLTest("Test that declaration after self-closed child is not allowed", XML_ERROR_PARSING_DECLARATION, doc.ErrorID() );
doc.Parse(xml3);
XMLTest("Test that declaration after a child is not allowed", XML_ERROR_PARSING_DECLARATION, doc.ErrorID() );
doc.Parse(xml4);
XMLTest("Test that declaration inside a child is not allowed", XML_ERROR_PARSING_DECLARATION, doc.ErrorID() );
}
{
// No matter - before or after successfully parsing a text -
// calling XMLDocument::Value() used to cause an assert in debug.
// Null must be returned.
const char* validXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
"<first />"
"<second />";
XMLDocument* doc = new XMLDocument();
XMLTest( "XMLDocument::Value() returns null?", NULL, doc->Value() );
doc->Parse( validXml );
XMLTest( "Parse to test XMLDocument::Value()", false, doc->Error());
XMLTest( "XMLDocument::Value() returns null?", NULL, doc->Value() );
delete doc;
}
{
XMLDocument doc;
for( int i = 0; i < XML_ERROR_COUNT; i++ ) {
const XMLError error = static_cast<XMLError>(i);
const char* name = XMLDocument::ErrorIDToName(error);
XMLTest( "ErrorName() not null after ClearError()", true, name != 0 );
if( name == 0 ) {
// passing null pointer into strlen() is undefined behavior, so
// compiler is allowed to optimise away the null test above if it's
// as reachable as the strlen() call
continue;
}
XMLTest( "ErrorName() not empty after ClearError()", true, strlen(name) > 0 );
}
}
{
const char* html("<!DOCTYPE html><html><body><p>test</p><p><br/></p></body></html>");
XMLDocument doc(false);
doc.Parse(html);
XMLPrinter printer(0, true);
doc.Print(&printer);
XMLTest(html, html, printer.CStr());
}
{
// Evil memory leaks.
// If an XMLElement (etc) is allocated via NewElement() (etc.)
// and NOT added to the XMLDocument, what happens?
//
// Previously (buggy):
// The memory would be free'd when the XMLDocument is
// destructed. But the XMLElement destructor wasn't called, so
// memory allocated for the XMLElement text would not be free'd.
// In practice this meant strings allocated for the XMLElement
// text would be leaked. An edge case, but annoying.
// Now:
// The XMLElement destructor is called. But the unlinked nodes
// have to be tracked using a list. This has a minor performance
// impact that can become significant if you have a lot of
// unlinked nodes. (But why would you do that?)
// The only way to see this bug was in a Visual C++ runtime debug heap
// leak tracker. This is compiled in by default on Windows Debug and
// enabled with _CRTDBG_LEAK_CHECK_DF parameter passed to _CrtSetDbgFlag().
{
XMLDocument doc;
doc.NewElement("LEAK 1");
}
{
XMLDocument doc;
XMLElement* ele = doc.NewElement("LEAK 2");
doc.DeleteNode(ele);
}
}
{
// Bad bad crash. Parsing error results in stack overflow, if uncaught.
const char* TESTS[] = {
"./resources/xmltest-5330.xml",
"./resources/xmltest-4636783552757760.xml",
"./resources/xmltest-5720541257269248.xml",
0
};
for (int i=0; TESTS[i]; ++i) {
XMLDocument doc;
doc.LoadFile(TESTS[i]);
XMLTest("Stack overflow prevented.", XML_ELEMENT_DEPTH_EXCEEDED, doc.ErrorID());
}
}
{
// Crashing reported via email.
const char* xml =
"<playlist id='playlist1'>"
"<property name='track_name'>voice</property>"
"<property name='audio_track'>1</property>"
"<entry out = '604' producer = '4_playlist1' in = '0' />"
"<blank length = '1' />"
"<entry out = '1625' producer = '3_playlist' in = '0' />"
"<blank length = '2' />"
"<entry out = '946' producer = '2_playlist1' in = '0' />"
"<blank length = '1' />"
"<entry out = '128' producer = '1_playlist1' in = '0' />"
"</playlist>";
// It's not a good idea to delete elements as you walk the
// list. I'm not sure this technically should work; but it's
// an interesting test case.
XMLDocument doc;
XMLError err = doc.Parse(xml);
XMLTest("Crash bug parsing", XML_SUCCESS, err );
XMLElement* playlist = doc.FirstChildElement("playlist");
XMLTest("Crash bug parsing", true, playlist != 0);
{
const char* elementName = "entry";
XMLElement* entry = playlist->FirstChildElement(elementName);
XMLTest("Crash bug parsing", true, entry != 0);
while (entry) {
XMLElement* todelete = entry;
entry = entry->NextSiblingElement(elementName);
playlist->DeleteChild(todelete);
}
entry = playlist->FirstChildElement(elementName);
XMLTest("Crash bug parsing", true, entry == 0);
}
{
const char* elementName = "blank";
XMLElement* blank = playlist->FirstChildElement(elementName);
XMLTest("Crash bug parsing", true, blank != 0);
while (blank) {
XMLElement* todelete = blank;
blank = blank->NextSiblingElement(elementName);
playlist->DeleteChild(todelete);
}
XMLTest("Crash bug parsing", true, blank == 0);
}
tinyxml2::XMLPrinter printer;
const bool acceptResult = playlist->Accept(&printer);
XMLTest("Crash bug parsing - Accept()", true, acceptResult);
printf("%s\n", printer.CStr());
// No test; it only need to not crash.
// Still, wrap it up with a sanity check
int nProperty = 0;
for (const XMLElement* p = playlist->FirstChildElement("property"); p; p = p->NextSiblingElement("property")) {
nProperty++;
}
XMLTest("Crash bug parsing", 2, nProperty);
}
// ----------- Line Number Tracking --------------
{
struct TestUtil: XMLVisitor
{
TestUtil() : str() {}
void TestParseError(const char *testString, const char *docStr, XMLError expected_error, int expectedLine)
{
XMLDocument doc;
const XMLError parseError = doc.Parse(docStr);
XMLTest(testString, parseError, doc.ErrorID());
XMLTest(testString, true, doc.Error());
XMLTest(testString, expected_error, parseError);
XMLTest(testString, expectedLine, doc.ErrorLineNum());
};
void TestStringLines(const char *testString, const char *docStr, const char *expectedLines)
{
XMLDocument doc;
doc.Parse(docStr);
XMLTest(testString, false, doc.Error());
TestDocLines(testString, doc, expectedLines);
}
void TestFileLines(const char *testString, const char *file_name, const char *expectedLines)
{
XMLDocument doc;
doc.LoadFile(file_name);
XMLTest(testString, false, doc.Error());
TestDocLines(testString, doc, expectedLines);
}
private:
DynArray<char, 10> str;
void Push(char type, int lineNum)
{
str.Push(type);
str.Push(char('0' + (lineNum / 10)));
str.Push(char('0' + (lineNum % 10)));
}
bool VisitEnter(const XMLDocument& doc)
{
Push('D', doc.GetLineNum());
return true;
}
bool VisitEnter(const XMLElement& element, const XMLAttribute* firstAttribute)
{
Push('E', element.GetLineNum());
for (const XMLAttribute *attr = firstAttribute; attr != 0; attr = attr->Next())
Push('A', attr->GetLineNum());
return true;
}
bool Visit(const XMLDeclaration& declaration)
{
Push('L', declaration.GetLineNum());
return true;
}
bool Visit(const XMLText& text)
{
Push('T', text.GetLineNum());
return true;
}
bool Visit(const XMLComment& comment)
{
Push('C', comment.GetLineNum());
return true;
}
bool Visit(const XMLUnknown& unknown)
{
Push('U', unknown.GetLineNum());
return true;
}
void TestDocLines(const char *testString, XMLDocument &doc, const char *expectedLines)
{
str.Clear();
const bool acceptResult = doc.Accept(this);
XMLTest(testString, true, acceptResult);
str.Push(0);
XMLTest(testString, expectedLines, str.Mem());
}
} tester;
tester.TestParseError("ErrorLine-Parsing", "\n<root>\n foo \n<unclosed/>", XML_ERROR_PARSING, 2);
tester.TestParseError("ErrorLine-Declaration", "<root>\n<?xml version=\"1.0\"?>", XML_ERROR_PARSING_DECLARATION, 2);
tester.TestParseError("ErrorLine-Mismatch", "\n<root>\n</mismatch>", XML_ERROR_MISMATCHED_ELEMENT, 2);
tester.TestParseError("ErrorLine-CData", "\n<root><![CDATA[ \n foo bar \n", XML_ERROR_PARSING_CDATA, 2);
tester.TestParseError("ErrorLine-Text", "\n<root>\n foo bar \n", XML_ERROR_PARSING_TEXT, 3);
tester.TestParseError("ErrorLine-Comment", "\n<root>\n<!-- >\n", XML_ERROR_PARSING_COMMENT, 3);
tester.TestParseError("ErrorLine-Declaration", "\n<root>\n<? >\n", XML_ERROR_PARSING_DECLARATION, 3);
tester.TestParseError("ErrorLine-Unknown", "\n<root>\n<! \n", XML_ERROR_PARSING_UNKNOWN, 3);
tester.TestParseError("ErrorLine-Element", "\n<root>\n<unclosed \n", XML_ERROR_PARSING_ELEMENT, 3);
tester.TestParseError("ErrorLine-Attribute", "\n<root>\n<unclosed \n att\n", XML_ERROR_PARSING_ATTRIBUTE, 4);
tester.TestParseError("ErrorLine-ElementClose", "\n<root>\n<unclosed \n/unexpected", XML_ERROR_PARSING_ELEMENT, 3);
tester.TestStringLines(
"LineNumbers-String",
"<?xml version=\"1.0\"?>\n" // 1 Doc, DecL
"<root a='b' \n" // 2 Element Attribute
"c='d'> d <blah/> \n" // 3 Attribute Text Element
"newline in text \n" // 4 Text
"and second <zxcv/><![CDATA[\n" // 5 Element Text
" cdata test ]]><!-- comment -->\n" // 6 Comment
"<! unknown></root>", // 7 Unknown
"D01L01E02A02A03T03E03T04E05T05C06U07");
tester.TestStringLines(
"LineNumbers-CRLF",
"\r\n" // 1 Doc (arguably should be line 2)
"<?xml version=\"1.0\"?>\n" // 2 DecL
"<root>\r\n" // 3 Element
"\n" // 4
"text contining new line \n" // 5 Text
" and also containing crlf \r\n" // 6
"<sub><![CDATA[\n" // 7 Element Text
"cdata containing new line \n" // 8
" and also containing cflr\r\n" // 9
"]]></sub><sub2/></root>", // 10 Element
"D01L02E03T05E07T07E10");
tester.TestFileLines(
"LineNumbers-File",
"resources/utf8test.xml",
"D01L01E02E03A03A03T03E04A04A04T04E05A05A05T05E06A06A06T06E07A07A07T07E08A08A08T08E09T09E10T10");
}
{
const char* xml = "<Hello>Text</Error>";
XMLDocument doc;
doc.Parse(xml);
XMLTest("Test mismatched elements.", true, doc.Error());
XMLTest("Test mismatched elements.", XML_ERROR_MISMATCHED_ELEMENT, doc.ErrorID());
// For now just make sure calls work & doesn't crash.
// May solidify the error output in the future.
printf("%s\n", doc.ErrorStr());
doc.PrintError();
}
// ----------- Performance tracking --------------
{
#if defined( _MSC_VER )
__int64 start, end, freq;
QueryPerformanceFrequency((LARGE_INTEGER*)&freq);
#endif
FILE* perfFP = fopen("resources/dream.xml", "r");
XMLTest("Open dream.xml", true, perfFP != 0);
fseek(perfFP, 0, SEEK_END);
long size = ftell(perfFP);
fseek(perfFP, 0, SEEK_SET);
char* mem = new char[size + 1];
memset(mem, 0xfe, size);
size_t bytesRead = fread(mem, 1, size, perfFP);
XMLTest("Read dream.xml", true, uint32_t(size) >= uint32_t(bytesRead));
fclose(perfFP);
mem[size] = 0;
#if defined( _MSC_VER )
QueryPerformanceCounter((LARGE_INTEGER*)&start);
#else
clock_t cstart = clock();
#endif
bool parseDreamXmlFailed = false;
static const int COUNT = 10;
for (int i = 0; i < COUNT; ++i) {
XMLDocument doc;
doc.Parse(mem);
parseDreamXmlFailed = parseDreamXmlFailed || doc.Error();
}
#if defined( _MSC_VER )
QueryPerformanceCounter((LARGE_INTEGER*)&end);
#else
clock_t cend = clock();
#endif
XMLTest( "Parse dream.xml", false, parseDreamXmlFailed );
delete[] mem;
static const char* note =
#ifdef TINYXML2_DEBUG
"DEBUG";
#else
"Release";
#endif
#if defined( _MSC_VER )
const double duration = 1000.0 * (double)(end - start) / ((double)freq * (double)COUNT);
#else
const double duration = (double)(cend - cstart) / (double)COUNT;
#endif
printf("\nParsing dream.xml (%s): %.3f milli-seconds\n", note, duration);
}
#if defined( _MSC_VER ) && defined( TINYXML2_DEBUG )
{
_CrtMemCheckpoint( &endMemState );
_CrtMemState diffMemState;
_CrtMemDifference( &diffMemState, &startMemState, &endMemState );
_CrtMemDumpStatistics( &diffMemState );
{
int leaksBeforeExit = _CrtDumpMemoryLeaks();
XMLTest( "No leaks before exit?", FALSE, leaksBeforeExit );
}
}
#endif
printf ("\nPass %d, Fail %d\n", gPass, gFail);
return gFail;
}
| [
"42669863+HenrikSte@users.noreply.github.com"
] | 42669863+HenrikSte@users.noreply.github.com |
8b54daf45bd29928ca307311ff1ab1bcd6960e86 | c39ae78fd4450b9972ef2b49ab9a94306656bb32 | /Examples/src/WarpingDemo.cc | a0c9bc10517bb8ffed04e73c25baed08b1a4b0dc | [
"BSD-3-Clause"
] | permissive | mingliangfu/MTF | a206cf78008585e229a74dbeb03a591736ee37a5 | d9f60de242b92d4a6db76563f3d940b8b34d4302 | refs/heads/master | 2021-01-25T09:20:27.111448 | 2017-06-03T02:33:39 | 2017-06-03T02:33:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,762 | cc | //#include <mtf/SM/ESM.h>
//#include<mtf/AM/NCC.h>
//#include <mtf/SSM/Homography.h>
#include <mtf/mtf.h>
#include <mtf/Tools/pipeline.h>
#include <mtf/Tools/cvUtils.h>
#include <mtf/Utilities/miscUtils.h>
// typedef mtf::RKLT<mtf::NCC, mtf::Homography> TrackerType;
typedef mtf::CompositeSM<mtf::NCC, mtf::Homography> TrackerType;
int main(int argc, char * argv[]){
if(!readParams(argc, argv)){ return EXIT_FAILURE; }
enable_nt = 0;
//ESM<NCC, Homography> tracker;
// TrackerType *tracker = static_cast<TrackerType*>(mtf::getTracker("rklt", "ncc", "8", "0"));
TrackerType *tracker = dynamic_cast<TrackerType*>(mtf::getTracker("nnic", "ncc", "8", "0"));
// TrackerType *tracker = static_cast<TrackerType*>(mtf::getTracker("pffc", "ncc", "8", "0"));
if(!tracker){
printf("Dynamic casting failed.\n");
return EXIT_FAILURE;
}
// mtf::Homography &ssm = tracker->templ_tracker->getSSM();
mtf::Homography &ssm = tracker->getSSM();
InputCV input('u');
GaussianSmoothing pre_proc(tracker->inputType());
input.initialize();
pre_proc.initialize(input.getFrame());
tracker->setImage(pre_proc.getFrame());
CVUtils cv_utils;
cv_utils.selectObjects(&input, 1);
tracker->initialize(cv_utils.getObj().corners);
while(input.update()){
pre_proc.update(input.getFrame());
tracker->update(pre_proc.getFrame());
mtf::utils::printMatrix(ssm.getState(), "Homography Params");
Matrix3d warp_mat;
ssm.getWarpFromState(warp_mat, ssm.getState());
mtf::utils::printMatrix(warp_mat, "Homography Matrix");
utils::drawRegion(input.getFrame(MUTABLE), tracker->getRegion());
cv::imshow("Tracker Location", input.getFrame());
if(cv::waitKey(1) == 27){ break; }
}
cv::destroyAllWindows();
return 0;
}
| [
"asingh1@ualberta.ca"
] | asingh1@ualberta.ca |
ff8514b5868b691e4742448f660fb7b94adeee60 | b8487f927d9fb3fa5529ad3686535714c687dd50 | /lib/AST/SemanticValidator.h | ad193bbbcde5cbe101857272b313e782f3636419 | [
"MIT"
] | permissive | hoangtuanhedspi/hermes | 4a1399f05924f0592c36a9d4b3fd1f804f383c14 | 02dbf3c796da4d09ec096ae1d5808dcb1b6062bf | refs/heads/master | 2020-07-12T21:21:53.781167 | 2019-08-27T22:58:17 | 2019-08-27T22:59:55 | 204,908,743 | 1 | 0 | MIT | 2019-08-28T17:44:49 | 2019-08-28T10:44:49 | null | UTF-8 | C++ | false | false | 8,841 | h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the LICENSE
* file in the root directory of this source tree.
*/
#ifndef HERMES_AST_SEMANTICVALIDATOR_H
#define HERMES_AST_SEMANTICVALIDATOR_H
#include "hermes/AST/SemValidate.h"
#include "RecursiveVisitor.h"
namespace hermes {
namespace sem {
using namespace hermes::ESTree;
// Forward declarations
class FunctionContext;
class SemanticValidator;
//===----------------------------------------------------------------------===//
// Keywords
class Keywords {
public:
/// Identifier for "arguments".
const UniqueString *const identArguments;
/// Identifier for "eval".
const UniqueString *const identEval;
/// Identifier for "delete".
const UniqueString *const identDelete;
/// Identifier for "use strict".
const UniqueString *const identUseStrict;
/// Identifier for "var".
const UniqueString *const identVar;
/// Identifier for "let".
const UniqueString *const identLet;
/// Identifier for "const".
const UniqueString *const identConst;
Keywords(Context &astContext);
};
//===----------------------------------------------------------------------===//
// SemanticValidator
/// Class the performs all semantic validation
class SemanticValidator {
friend class FunctionContext;
Context &astContext_;
/// A copy of Context::getSM() for easier access.
SourceErrorManager &sm_;
/// All semantic tables are persisted here.
SemContext &semCtx_;
/// Save the initial error count so we know whether we generated any errors.
const unsigned initialErrorCount_;
/// Keywords we will be checking for.
Keywords kw_;
/// The current function context.
FunctionContext *funcCtx_{};
#ifndef NDEBUG
/// Our parser detects strictness and initializes the flag in every node,
/// but if we are reading an external AST, we must look for "use strict" and
/// initialize the flag ourselves here.
/// For consistency we always perform the detection, but in debug mode we also
/// want to ensure that our results match what the parser generated. This
/// flag indicates whether strictness is preset or not.
bool strictnessIsPreset_{false};
#endif
public:
explicit SemanticValidator(Context &astContext, sem::SemContext &semCtx);
// Perform the validation on whole AST.
bool doIt(Node *rootNode);
/// Perform the validation on an individual function.
bool doFunction(Node *function, bool strict);
/// Handle the default case for all nodes which we ignore, but we still want
/// to visit their children.
void visit(Node *node) {
visitESTreeChildren(*this, node);
}
void visit(ProgramNode *node);
void visit(FunctionDeclarationNode *funcDecl);
void visit(FunctionExpressionNode *funcExpr);
void visit(ArrowFunctionExpressionNode *arrowFunc);
void visit(VariableDeclaratorNode *varDecl, Node *parent);
void visit(MetaPropertyNode *metaProp);
void visit(IdentifierNode *identifier);
void visit(ForInStatementNode *forIn);
void visit(ForOfStatementNode *forOf);
void visitForInOf(LoopStatementNode *loopNode, Node *left);
void visit(AssignmentExpressionNode *assignment);
void visit(UpdateExpressionNode *update);
void visit(LabeledStatementNode *labelStmt);
void visit(RegExpLiteralNode *regexp);
void visit(TryStatementNode *tryStatement);
void visit(DoWhileStatementNode *loop);
void visit(ForStatementNode *loop);
void visit(WhileStatementNode *loop);
void visit(SwitchStatementNode *switchStmt);
void visit(BreakStatementNode *breakStmt);
void visit(ContinueStatementNode *continueStmt);
void visit(ReturnStatementNode *returnStmt);
void visit(YieldExpressionNode *yieldExpr);
void visit(UnaryExpressionNode *unaryExpr);
void visit(ArrayPatternNode *arrayPat);
void visit(SpreadElementNode *S, Node *parent);
void visit(ClassExpressionNode *node);
void visit(ClassDeclarationNode *node);
void visit(ImportDeclarationNode *importDecl);
void visit(ImportDefaultSpecifierNode *importDecl);
void visit(ImportNamespaceSpecifierNode *importDecl);
void visit(ImportSpecifierNode *importDecl);
void visit(ExportNamedDeclarationNode *exportDecl);
void visit(ExportDefaultDeclarationNode *exportDecl);
void visit(ExportAllDeclarationNode *exportDecl);
void visit(CoverEmptyArgsNode *CEA);
void visit(CoverTrailingCommaNode *CTC);
void visit(CoverInitializerNode *CI);
void visit(CoverRestElementNode *R);
private:
inline bool haveActiveContext() const {
return funcCtx_ != nullptr;
}
inline FunctionContext *curFunction() {
assert(funcCtx_ && "No active function context");
return funcCtx_;
}
inline const FunctionContext *curFunction() const {
assert(funcCtx_ && "No active function context");
return funcCtx_;
}
/// Process a function declaration by creating a new FunctionContext. Update
/// the context with the strictness of the function.
/// \param node the current node
/// \param id if not null, the associated name (for validation)
/// \param params the parameter list
/// \param body the body. It may be a BlockStatementNode, an EmptyNode (for
/// lazy functions), or an expression (for simple arrow functions).
void
visitFunction(FunctionLikeNode *node, Node *id, NodeList ¶ms, Node *body);
/// Scan a list of directives in the beginning of a program of function
/// (see ES5.1 4.1 - a directive is a statement consisting of a single
/// string literal).
/// Update the flags in the function context to reflect the directives. (We
/// currently only recognize "use strict".)
/// \return the node containing "use strict" or nullptr.
Node *scanDirectivePrologue(NodeList &body);
/// Determine if the argument is something that can be assigned to: a
/// variable or a property. 'arguments' cannot be assigned to in strict mode,
/// but we don't support code generation for assigning to it in any mode.
bool isLValue(const Node *node) const;
/// In strict mode 'arguments' and 'eval' cannot be used in declarations.
bool isValidDeclarationName(const IdentifierNode *idNode) const;
/// Ensure that the declared identifier(s) is valid to be used in a
/// declaration and append them to the specified list.
/// \param node is one of nullptr, EmptyNode, IdentifierNode, PatternNode.
/// \param idents if not-null, all identifiers are appended there.
void validateDeclarationNames(
FunctionInfo::VarDecl::Kind declKind,
Node *node,
llvm::SmallVectorImpl<FunctionInfo::VarDecl> *idents);
/// Ensure that the specified node is a valid target for an assignment, in
/// other words it is an l-value, a Pattern (checked recursively) or an Empty
/// (used by elision).
void validateAssignmentTarget(const Node *node);
/// A debugging method to set the strictness of a function-like node to
/// the curent strictness, asserting that it doesn't change if it had been
/// preset.
void updateNodeStrictness(FunctionLikeNode *node);
/// Get the LabelDecorationBase depending on the node type.
static LabelDecorationBase *getLabelDecorationBase(StatementNode *node);
/// Collapse array pattern rest elements into their parent:
/// [a, ...[b, c]] => [a, b, c].
static void collapseNestedAP(NodeList &elements);
};
//===----------------------------------------------------------------------===//
// FunctionContext
/// Holds all per-function state, specifically label tables. Should always be
/// constructed on the stack.
class FunctionContext {
SemanticValidator *validator_;
FunctionContext *oldContextValue_;
public:
struct Label {
/// Where it was declared.
IdentifierNode *declarationNode;
/// Statement targeted by the label. It is either a LoopStatement or a
/// LabeledStatement.
StatementNode *targetStatement;
};
/// The associated seminfo object
sem::FunctionInfo *const semInfo;
/// The most nested active loop statement.
LoopStatementNode *activeLoop = nullptr;
/// The most nested active loop or switch statement.
StatementNode *activeSwitchOrLoop = nullptr;
/// Is this function in strict mode.
bool strictMode = false;
/// The currently active labels in the function.
llvm::DenseMap<NodeLabel, Label> labelMap;
explicit FunctionContext(
SemanticValidator *validator,
bool strictMode,
FunctionLikeNode *node);
~FunctionContext();
/// \return true if this is the "global scope" function context, in other
/// words not a real function.
bool isGlobalScope() const {
return !oldContextValue_;
}
/// Allocate a new label in the current context.
unsigned allocateLabel() {
return semInfo->allocateLabel();
}
};
} // namespace sem
} // namespace hermes
#endif // HERMES_AST_SEMANTICVALIDATOR_H
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
e210164bee6230dfd20869bcf763adc0c4befc37 | f158527ea88ebc7b2b8221d3d3dac4fd687e8a86 | /AVS/avs.cpp | 3dae24d42514784db8c19aca9c73848eee3a0613 | [] | no_license | zlvb/dshowsample | 7b2487f41bcce19e960546b8334ba39bec082e52 | 7ad79396b782dd10f5bf5c18dfecd537076b86a1 | refs/heads/master | 2021-01-20T23:23:57.105398 | 2015-07-25T00:44:09 | 2015-07-25T00:44:09 | 32,433,973 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 10,290 | cpp | #pragma warning(disable: 4819)
#include "avs.h"
namespace AVS{
Manager::Manager()
:m_Graph(NULL)
,m_MediaControl(NULL)
,m_Event(NULL)
,m_BasicVideo(NULL)
,m_BasicAudio(NULL)
,m_VideoWindow(NULL)
,m_Seeking(NULL)
,m_ObjectTableEntry(0)
{
}
Manager::~Manager()
{
Close();
}
BOOL Manager::Create(void)
{
if (!m_Graph)
{
if (SUCCEEDED(CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
IID_IGraphBuilder, (void **)&m_Graph)))
{
AddToObjectTable();
return QueryInterfaces();
}
m_Graph = 0;
}
return FALSE;
}
BOOL Manager::QueryInterfaces(void)
{
if (m_Graph)
{
HRESULT hr = NOERROR;
hr |= m_Graph->QueryInterface(IID_IMediaControl, (void **)&m_MediaControl);
hr |= m_Graph->QueryInterface(IID_IMediaEventEx, (void **)&m_Event);
hr |= m_Graph->QueryInterface(IID_IBasicVideo, (void **)&m_BasicVideo);
hr |= m_Graph->QueryInterface(IID_IBasicAudio, (void **)&m_BasicAudio);
hr |= m_Graph->QueryInterface(IID_IVideoWindow, (void **)&m_VideoWindow);
hr |= m_Graph->QueryInterface(IID_IMediaSeeking, (void **)&m_Seeking);
if (m_Seeking)
{
m_Seeking->SetTimeFormat(&TIME_FORMAT_MEDIA_TIME);
}
return SUCCEEDED(hr);
}
return FALSE;
}
void Manager::Close(void)
{
if (m_Seeking)
{
m_Seeking->Release();
m_Seeking = NULL;
}
if (m_MediaControl)
{
m_MediaControl->Release();
m_MediaControl = NULL;
}
if (m_Event)
{
m_Event->Release();
m_Event = NULL;
}
if (m_BasicVideo)
{
m_BasicVideo->Release();
m_BasicVideo = NULL;
}
if (m_BasicAudio)
{
m_BasicAudio->Release();
m_BasicAudio = NULL;
}
if (m_VideoWindow)
{
m_VideoWindow->put_Visible(OAFALSE);
m_VideoWindow->put_MessageDrain((OAHWND)NULL);
m_VideoWindow->put_Owner(OAHWND(0));
m_VideoWindow->Release();
m_VideoWindow = NULL;
}
RemoveFromObjectTable();
if (m_Graph)
{
m_Graph->Release();
m_Graph = NULL;
}
}
BOOL Manager::Attach(IGraphBuilder * inGraphBuilder)
{
Close();
if (inGraphBuilder)
{
inGraphBuilder->AddRef();
m_Graph = inGraphBuilder;
AddToObjectTable();
return QueryInterfaces();
}
return TRUE;
}
IGraphBuilder * Manager::GetGraph(void)
{
return m_Graph;
}
IMediaEventEx * Manager::GetEventHandle(void)
{
return m_Event;
}
BOOL Manager::ConnectFilters(IPin * inOutputPin, IPin * inInputPin,
const AM_MEDIA_TYPE * inMediaType)
{
if (m_Graph && inOutputPin && inInputPin)
{
HRESULT hr = m_Graph->ConnectDirect(inOutputPin, inInputPin, inMediaType);
return SUCCEEDED(hr) ? TRUE : FALSE;
}
return FALSE;
}
void Manager::DisconnectFilters(IPin * inOutputPin)
{
if (m_Graph && inOutputPin)
{
HRESULT hr = m_Graph->Disconnect(inOutputPin);
}
}
BOOL Manager::SetDisplayWindow()
{
if (m_VideoWindow)
{
m_VideoWindow->put_Visible(OAFALSE);
m_VideoWindow->put_Owner((OAHWND)m_Window);
RECT windowRect;
::GetClientRect(m_Window, &windowRect);
m_VideoWindow->put_Left(0);
m_VideoWindow->put_Top(0);
m_VideoWindow->put_Width(windowRect.right - windowRect.left);
m_VideoWindow->put_Height(windowRect.bottom - windowRect.top);
m_VideoWindow->put_WindowStyle(WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS);
m_VideoWindow->put_MessageDrain((OAHWND) m_Window);
if (m_Window != NULL)
{
m_VideoWindow->put_Visible(OATRUE);
}
else
{
m_VideoWindow->put_Visible(OAFALSE);
}
return TRUE;
}
return FALSE;
}
BOOL Manager::ResizeVideoWindow(long inLeft, long inTop, long inWidth, long inHeight)
{
if (m_VideoWindow)
{
long lVisible = OATRUE;
m_VideoWindow->get_Visible(&lVisible);
m_VideoWindow->put_Visible(OAFALSE);
m_VideoWindow->put_Left(inLeft);
m_VideoWindow->put_Top(inTop);
m_VideoWindow->put_Width(inWidth);
m_VideoWindow->put_Height(inHeight);
m_VideoWindow->put_Visible(lVisible);
return TRUE;
}
return FALSE;
}
BOOL Manager::SetNotifyWindow()
{
if (m_Event)
{
m_Event->SetNotifyWindow((OAHWND)m_Window, WM_GRAPHNOTIFY, 0);
return TRUE;
}
return FALSE;
}
void Manager::HandleEvent(WPARAM inWParam, LPARAM inLParam)
{
if (m_Event)
{
LONG eventCode = 0, eventParam1 = 0, eventParam2 = 0;
while (SUCCEEDED(m_Event->GetEvent(&eventCode, &eventParam1, &eventParam2, 0)))
{
m_Event->FreeEventParams(eventCode, eventParam1, eventParam2);
switch (eventCode)
{
case EC_COMPLETE:
break;
case EC_USERABORT:
case EC_ERRORABORT:
break;
default:
break;
}
}
}
}
BOOL Manager::Play(void)
{
if (m_Graph && m_MediaControl)
{
if (!IsPlaying())
{
if (SUCCEEDED(m_MediaControl->Run()))
{
return TRUE;
}
}
else
{
return TRUE;
}
}
return FALSE;
}
BOOL Manager::Stop(void)
{
if (m_Graph && m_MediaControl)
{
if (!IsStopped())
{
if (SUCCEEDED(m_MediaControl->Stop()))
{
return TRUE;
}
}
else
{
return TRUE;
}
}
return FALSE;
}
BOOL Manager::Pause(void)
{
if (m_Graph && m_MediaControl)
{
if (!IsPaused())
{
if (SUCCEEDED(m_MediaControl->Pause()))
{
return TRUE;
}
}
else
{
return TRUE;
}
}
return FALSE;
}
BOOL Manager::IsPlaying(void)
{
if (m_Graph && m_MediaControl)
{
OAFilterState state = State_Stopped;
if (SUCCEEDED(m_MediaControl->GetState(10, &state)))
{
return state == State_Running;
}
}
return FALSE;
}
BOOL Manager::IsStopped(void)
{
if (m_Graph && m_MediaControl)
{
OAFilterState state = State_Stopped;
if (SUCCEEDED(m_MediaControl->GetState(10, &state)))
{
return state == State_Stopped;
}
}
return FALSE;
}
BOOL Manager::IsPaused(void)
{
if (m_Graph && m_MediaControl)
{
OAFilterState state = State_Stopped;
if (SUCCEEDED(m_MediaControl->GetState(10, &state)))
{
return state == State_Paused;
}
}
return FALSE;
}
BOOL Manager::SetFullScreen(BOOL inEnabled)
{
if (m_VideoWindow)
{
HRESULT hr = m_VideoWindow->put_FullScreenMode(inEnabled ? OATRUE : OAFALSE);
return SUCCEEDED(hr);
}
return FALSE;
}
BOOL Manager::isFullScreen(void)
{
if (m_VideoWindow)
{
long fullScreenMode = OAFALSE;
m_VideoWindow->get_FullScreenMode(&fullScreenMode);
return (fullScreenMode == OATRUE);
}
return FALSE;
}
BOOL Manager::GetCurrentPosition(double * outPosition)
{
if (m_Seeking)
{
__int64 position = 0;
if (SUCCEEDED(m_Seeking->GetCurrentPosition(&position)))
{
*outPosition = ((double)position) / 10000000.;
return TRUE;
}
}
return FALSE;
}
BOOL Manager::GetStopPosition(double * outPosition)
{
if (m_Seeking)
{
__int64 position = 0;
if (SUCCEEDED(m_Seeking->GetStopPosition(&position)))
{
*outPosition = ((double)position) / 10000000.;
return TRUE;
}
}
return FALSE;
}
BOOL Manager::SetCurrentPosition(double inPosition)
{
if (m_Seeking)
{
__int64 one = 10000000;
__int64 position = (__int64)(one * inPosition);
HRESULT hr = m_Seeking->SetPositions(&position, AM_SEEKING_AbsolutePositioning | AM_SEEKING_SeekToKeyFrame,
0, AM_SEEKING_NoPositioning);
return SUCCEEDED(hr);
}
return FALSE;
}
BOOL Manager::SetStartStopPosition(double inStart, double inStop)
{
if (m_Seeking)
{
__int64 one = 10000000;
__int64 startPos = (__int64)(one * inStart);
__int64 stopPos = (__int64)(one * inStop);
HRESULT hr = m_Seeking->SetPositions(&startPos, AM_SEEKING_AbsolutePositioning | AM_SEEKING_SeekToKeyFrame,
&stopPos, AM_SEEKING_AbsolutePositioning | AM_SEEKING_SeekToKeyFrame);
return SUCCEEDED(hr);
}
return FALSE;
}
BOOL Manager::GetDuration(double * outDuration)
{
if (m_Seeking)
{
__int64 length = 0;
if (SUCCEEDED(m_Seeking->GetDuration(&length)))
{
*outDuration = ((double)length) / 10000000.;
return TRUE;
}
}
return FALSE;
}
BOOL Manager::SetPlaybackRate(double inRate)
{
if (m_Seeking)
{
if (SUCCEEDED(m_Seeking->SetRate(inRate)))
{
return TRUE;
}
}
return FALSE;
}
BOOL Manager::SetAudioVolume(long inVolume)
{
if (m_BasicAudio)
{
HRESULT hr = m_BasicAudio->put_Volume(inVolume);
return SUCCEEDED(hr);
}
return FALSE;
}
long Manager::GetAudioVolume(void)
{
long volume = 0;
if (m_BasicAudio)
{
m_BasicAudio->get_Volume(&volume);
}
return volume;
}
BOOL Manager::SetAudioBalance(long inBalance)
{
if (m_BasicAudio)
{
HRESULT hr = m_BasicAudio->put_Balance(inBalance);
return SUCCEEDED(hr);
}
return FALSE;
}
long Manager::GetAudioBalance(void)
{
long balance = 0;
if (m_BasicAudio)
{
m_BasicAudio->get_Balance(&balance);
}
return balance;
}
BOOL Manager::OpenMedia(const char * inFile)
{
strcpy(filename,inFile);
Create ();
if (m_Graph)
{
WCHAR szFilePath[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, inFile, -1, szFilePath, MAX_PATH);
if (SUCCEEDED(m_Graph->RenderFile(szFilePath, NULL)))
{
SetDisplayWindow ();
SetNotifyWindow ();
return TRUE;
}
}
return FALSE;
}
char* Manager::GetFileName(char* outFileName)
{
strcpy(outFileName,filename);
return outFileName;
}
void Manager::ReOpen()
{
Stop();
Close();
Create();
OpenMedia (filename);
}
void Manager::AddToObjectTable(void)
{
IMoniker * pMoniker = 0;
IRunningObjectTable * objectTable = 0;
if (SUCCEEDED(GetRunningObjectTable(0, &objectTable)))
{
WCHAR wsz[256];
wsprintfW(wsz, L"FilterGraph %08p pid %08x", (DWORD_PTR)m_Graph, GetCurrentProcessId());
HRESULT hr = CreateItemMoniker(L"!", wsz, &pMoniker);
if (SUCCEEDED(hr))
{
hr = objectTable->Register(0, m_Graph, pMoniker, &m_ObjectTableEntry);
pMoniker->Release();
}
objectTable->Release();
}
}
void Manager::RemoveFromObjectTable(void)
{
IRunningObjectTable * objectTable = 0;
if (SUCCEEDED(GetRunningObjectTable(0, &objectTable)))
{
objectTable->Revoke(m_ObjectTableEntry);
objectTable->Release();
m_ObjectTableEntry = 0;
}
}
void Manager::RePlay ()
{
ReOpen ();
Play ();
}
} | [
"zlvbvbzl@b1507354-4840-11de-ba0e-b5da6ac7b600"
] | zlvbvbzl@b1507354-4840-11de-ba0e-b5da6ac7b600 |
d7be4930565f94d62d0256f8a356d961075ad3f9 | 68b763fe498c4572e39155926a7fdd97e4b06389 | /cpp/data_structure/self_implemented/hashtable/hashtable.cpp | 365ae9dce50a1e815c74d46ec27031a2ea758a4b | [] | no_license | alfchung/coding_practice | 64eff671fc6a4c73e4bf47916526791413dd1357 | 24c0e270b780145f42199ddf324085d3b55e3970 | refs/heads/master | 2021-01-18T17:28:00.550167 | 2013-01-19T03:28:49 | 2013-01-19T03:28:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,162 | cpp |
/*
* keys are unique
*/
#include<stdlib.h>
#include<stdint.h>
#include<math.h>
#include<iostream>
#include<string>
#include<map>
#include<vector>
#include<typeinfo>
using namespace std;
const int default_table_size = 277;
const int error_exit_wrong_key_type = -1;
const int put_status_insert_new = 0;
const int put_status_insert_overwritten = 1;
const int put_status_insert_fail = -1;
const int get_not_found = -1;
const int get_found = 0;
template <class Key, class Value>
class record {
public:
Key key;
Value value;
record* next;
bool empty;
};
template <class Key, class Value>
class primary_record {
public:
primary_record() {
empty = true;
record_root = NULL;
}
bool empty;
record<Key, Value> *record_root;
};
template <class Key, class Value>
class hashtable {
public:
hashtable() {
table_size = default_table_size;
table.resize(default_table_size); //default table size
for (int i=0; i<table_size; i++) {
primary_record<Key, Value> pr;
table.push_back(pr);
}
}
hashtable(int size) {
table_size = size;
table.resize(size); //default table size
for (int i=0; i<table_size; i++) {
primary_record<Key, Value> pr;
table.push_bash(pr);
}
}
int put(Key key, Value value) {
int hashkey;
int position;
hashkey = static_cast<int>(key);
//hashkey = key;
position = hash(hashkey);
if (table[position].empty == true) {
table[position].record_root = new record<Key, Value>;
table[position].record_root->key = key;
table[position].record_root->value = value;
table[position].record_root->next = NULL;
table[position].empty = false;
return put_status_insert_new;
}
record<Key,Value> *pRecord = table[position].record_root;
record<Key,Value> *last;
while (pRecord != NULL) {
if (key == pRecord->key) {
pRecord->value = value;
return put_status_insert_overwritten;
}
last = pRecord;
pRecord = pRecord->next;
}
//go through the chain, no dupliated keys found
last->next = new record<Key, Value>;
last->next->key = key;
last->next->value = value;
return put_status_insert_new;
}
int get( Key key, Value *value ) {
int hashkey;
int position;
hashkey = static_cast<int>(key);
//hashkey = key;
position = hash(hashkey);
if (table[position].empty == true) {
return get_not_found;
}
record<Key,Value> *pRecord = table[position].record_root;
while (pRecord != NULL) {
if (key == pRecord->key) {
*value = pRecord->value;
return get_found;
}
}
//go through the chain, no dupliated keys found
return get_not_found;
}
int hash(int key) {
return key%table_size;
}
private:
int table_size;
vector< primary_record <Key, Value> > table;
};
class hashable_string:public string {
public:
hashable_string() {
}
hashable_string(string s) {
str = s;
}
operator int() const {
int ret = 0;
int size = str.size();
for (int i=0; i<size; i++) {
ret += static_cast<int>(str[i]) * (i%10);
}
return ret;
}
operator string() {
return str;
}
string to_string() {
return str;
}
string str;
private:
};
int main() {
hashtable<int, int> ht;
ht.put(2,20);
ht.put(7,7);
ht.put(3,3);
ht.put(1,1);
ht.put(8,8);
ht.put(9,9);
hashtable<hashable_string, string> ht2;
hashable_string s1("Alfred");
ht2.put(s1, "731 Lexington Ave");
hashable_string s3("Wang");
ht2.put(s3,"100 ABC drive");
int ret1;
if ( ht.get(3, &ret1) == get_found )
cout<<"in ht,key 3 returns value "<<ret1<<endl;
else
cout<<"in ht,key 3 not found."<<endl;
if ( ht.get(8, &ret1) == get_found )
cout<<"in ht,key 8 returns value "<<ret1<<endl;
else
cout<<"in ht,key 8 not found."<<endl;
if ( ht.get(99, &ret1) == get_found )
cout<<"in ht,key 99 returns value "<<ret1<<endl;
else
cout<<"in ht,key 99 not found."<<endl;
string ret2;
if ( ht2.get(s1, &ret2) == get_found )
cout<<"in ht,key "<<(string)(s1)<<" returns value "<<ret2<<endl;
else
cout<<"in ht,key"<<s1.to_string()<<" not found."<<endl;
return 0;
}
| [
"az@cs.brown.edu"
] | az@cs.brown.edu |
fcc9c4f520dcc229424922457c47f4b903d32419 | f95c500f5bd6e8d283e47a9a7ca383c6ed7566d7 | /src/fingerprint_probe.h | 842ba56e7db8478c06ef4ef81b9aea3965404f44 | [] | no_license | smrt28/sonoff-s26-blynk-firmware | ebd201f37b73bd0b4c7ce5e8bea6f67b4dc3fb19 | ef79bc1e92f79882c6c41fdf087cf7231c0130b8 | refs/heads/master | 2023-04-04T08:33:22.005740 | 2021-03-12T18:27:30 | 2021-03-12T18:27:30 | 347,151,941 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 255 | h | #ifndef fingerprint_probe_h
#define fingerprint_probe_h
namespace s28 {
struct Fingerprint {
uint8_t raw[20];
String to_string();
};
int probe(const String &host, int port, Fingerprint *fp);
} // namespace s28
#endif /* fingerprint_probe_h */ | [
"oholecek@purestorage.com"
] | oholecek@purestorage.com |
17e5bf532d7ba25a66a3154607b3873063ec29b5 | b13b51704390ee6af926a85ab8e7890b6aa8976e | /Flatten_Binary_Tree_to_Linked_List.cpp | 98fd3dfe224067050e8d74020ce4f62e62954971 | [] | no_license | kxingit/LeetCode | 7308eb306fe899e3f68a7cf90b43a37da46416cc | a0ef8e5454bd29076b50ffedc5b1720dd7273a9d | refs/heads/master | 2021-01-14T08:03:20.811221 | 2017-03-20T19:25:56 | 2017-03-20T19:25:56 | 35,183,062 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,536 | cpp | /**
* Given a binary tree, flatten it to a linked list in-place.
*/
class Solution {
public:
void flatten(TreeNode* root) {
if(root == NULL) return;
if(root->left) flatten(root->left);
if(root->right) flatten(root->right);
TreeNode* p = root->left;
if(p == NULL) return;
while(p->right) p = p->right; // while(p): X
p->right = root->right;
root->right = root->left;
root->left = NULL;
}
};
// v2
class Solution {
public:
void flatten(TreeNode* root) {
if(!root) return;
TreeNode* left = root->left;
TreeNode* right = root->right;
flatten(left);
flatten(right);
if(!left) return;
while(left->right) left = left->right;
left->right = root->right;
root->right = root->left;
root->left = NULL;
}
};
// v3
class Solution {
public:
void flatten(TreeNode* root) {
if(!root) return;
auto left = root->left;
auto right = root->right;
flatten(left);
flatten(right);
auto p = left;
if(!p) return; // important
while(p->right) p = p->right;
p->right = root->right;
root->right = left;
root->left = NULL;
}
};
// v4
class Solution {
public:
void flatten(TreeNode* root) {
if(!root) return;
flatten(root->left);
flatten(root->right);
auto p = root->left;
if(!p) return;
while(p->right) p = p->right;
p->right = root->right;
root->right = root->left;
root->left = NULL;
}
};
| [
"kxin@me.com"
] | kxin@me.com |
1a2455d8e4df4bbaf4f1af510257967471a5c424 | 1dbb60db92072801e3e7eaf6645ef776e2a26b29 | /server/src/common/resource/r_formationindexdata.h | 637902efac43243d2c1d58ea7bb92c905da1a163 | [] | no_license | atom-chen/phone-code | 5a05472fcf2852d1943ad869b37603a4901749d5 | c0c0f112c9a2570cc0390703b1bff56d67508e89 | refs/heads/master | 2020-07-05T01:15:00.585018 | 2015-06-17T08:52:21 | 2015-06-17T08:52:21 | 202,480,234 | 0 | 1 | null | 2019-08-15T05:36:11 | 2019-08-15T05:36:09 | null | UTF-8 | C++ | false | false | 739 | h | #ifndef IMMORTAL_COMMON_RESOURCE_R_FORMATIONINDEXDATA_H_
#define IMMORTAL_COMMON_RESOURCE_R_FORMATIONINDEXDATA_H_
#include "proto/common.h"
#include "r_basedata.h"
#include "resource.h"
class CFormationIndexData : public CBaseData
{
public:
struct SData
{
uint32 index;
uint32 level;
};
typedef std::map<uint32, SData*> UInt32FormationIndexMap;
CFormationIndexData();
virtual ~CFormationIndexData();
virtual void LoadData(void);
void ClearData(void);
SData * Find( uint32 index );
protected:
UInt32FormationIndexMap id_formationindex_map;
void Add(SData* formationindex);
};
#endif //IMMORTAL_COMMON_RESOURCE_R_FORMATIONINDEXMGR_H_
| [
"757690733@qq.com"
] | 757690733@qq.com |
b1c6881c383bc3ffc601c10eb52d87c59256cb11 | 9c942fe75218d6018f8390c926f0b693e36ceaad | /cpp/0088_MergeSortedArray.cpp | 8fee056ae04334afbe1808772090b3256e504f3f | [] | no_license | joy-yjl/leetcode_yjl | 5878113ae6cb81d1f735fa812b13e7f7b31883f6 | 1def24ac4ef723ecfd1e4dc50ced677809bc942c | refs/heads/master | 2022-07-31T04:42:45.845904 | 2022-07-20T03:35:20 | 2022-07-20T03:35:20 | 206,940,495 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 421 | cpp | class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int right=m+n-1;
int r1=m-1;
for(int i=n-1;i>=0;i--)
{
while(r1>=0 && nums1[r1]>nums2[i])
{
nums1[right]=nums1[r1];
r1--;
right--;
}
nums1[right]=nums2[i];
right--;
}
}
};
| [
"yangjiali94@126.com"
] | yangjiali94@126.com |
01f31a4ede39bae7a6c50833f96b717af7ed29f9 | ab431740965416a1f0de857cd54771a4558e6b64 | /lunchTime.cpp | 64a840ec1b750ceef781d35d780a4814e03b56c3 | [] | no_license | dycha0430/Algorithm_Problem_Solving_Strategies | eb0c84b9560b5439d2cc8e3f9db6cdc302ffef04 | a2a5e2cb1d1414ece4b8800a1aad63cc516c4e92 | refs/heads/master | 2023-03-10T08:52:37.520188 | 2021-02-24T15:45:08 | 2021-02-24T15:45:08 | 333,058,649 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,229 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int N;
int M[10000];
vector<pair<int, int>> lunchTime;
bool compare(pair<int, int> a, pair<int, int> b) {
return a.first > b.first;
}
int minimized_lunch();
int main() {
int T, E;
cin >> T;
for (int test_case = 0; test_case < T; ++test_case) {
cin >> N;
lunchTime.clear();
for (int i = 0; i < N; ++i) cin >> M[i];
for (int i = 0; i < N; ++i) {
cin >> E;
lunchTime.push_back(make_pair(E, M[i]));
}
// Sort by Eating time in descending order.
sort(lunchTime.begin(), lunchTime.end(), compare);
cout << minimized_lunch() << endl;
}
}
/* Return minimized lunch time */
int minimized_lunch() {
int i, partSum = 0;
vector<pair<int, int>>::reverse_iterator iter;
int Answer = 0;
/* Find the maximum amount of time to eat a food
* that exceeds the microwave usage time required
* after that food has been heated.
*/
for (i = 0, iter = lunchTime.rbegin(); i < N; ++i, ++iter) {
Answer = max(Answer, (*iter).first - partSum);
partSum = partSum + (*iter).second;
}
/* Minimized lunch time is the sum of the total usage time
* of the microwave and the value obtained above.
*/
return partSum + Answer;
} | [
"2019056799@hanyang.ac.kr"
] | 2019056799@hanyang.ac.kr |
0ab3208da33345c8baf1bc53ef4984af3fe268ff | f9b81e12421955fbfcf5d7dd987f1b5dcfb236f6 | /demos/设计模式之命令模式/CommandPattern/CommandPattern.h | 88d5dd7de4762492f0506194024385981ff4af3d | [] | no_license | lichangke/DesignPattern | f3aec170f6f3f54a84060143fba8f3c51514ceb8 | a47738505177aeea05a977a8ffb12fff070d80c9 | refs/heads/main | 2023-02-17T07:05:30.906338 | 2021-01-12T13:51:53 | 2021-01-12T13:51:53 | 324,113,049 | 9 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 4,357 | h | //
// Created by leacock on 2021/1/5.
//
#ifndef COMMANDPATTERN_COMMANDPATTERN_H
#define COMMANDPATTERN_COMMANDPATTERN_H
#include <iostream>
#include <vector>
/// Command(抽象命令类): Command
class Command {
public:
virtual ~Command() = default;
// 声明抽象接口:执行命令
virtual void execute() = 0;
protected:
Command() = default;
};
/// Receiver(接收者): Lamp 、 Fan
class Lamp {
public:
Lamp() {
lampState = false;
std::cout << "Lamp Hello" << std::endl;
}
~Lamp() {
std::cout << "Lamp Bye" << std::endl;
}
void lampOn() {
lampState = true;
std::cout << "Lamp On" << std::endl;
}
void lampOff() {
lampState = false;
std::cout << "Lamp Off" << std::endl;
}
bool getLampState(){
return lampState;
}
private:
bool lampState;
};
class Fan {
public:
Fan() {
fanState = false;
std::cout << "Fan Hello" << std::endl;
}
~Fan() {
std::cout << "Fan Bye" << std::endl;
}
void fanOn() {
fanState = true;
std::cout << "Fan On" << std::endl;
}
void fanOff() {
fanState = false;
std::cout << "Fan Off" << std::endl;
}
bool getFanState(){
return fanState;
}
private:
bool fanState;
};
/// ConcreteCommand(具体命令类): LampCommand 、 FanCommand
class LampCommand : public Command {
public:
LampCommand() {
std::cout << "LampCommand Hello" << std::endl;
lamp = new Lamp();
}
~LampCommand() override {
std::cout << "LampCommand Bye" << std::endl;
delete lamp;
}
void execute() override{
if(lamp->getLampState()) { // true
lamp->lampOff(); // false
} else {
lamp->lampOn();
}
}
private:
Lamp *lamp;
};
class FanCommand : public Command {
public:
FanCommand() {
std::cout << "FanCommand Hello" << std::endl;
fan = new Fan();
}
~FanCommand() override {
std::cout << "FanCommand Bye" << std::endl;
delete fan;
}
void execute() override{
if(fan->getFanState()) { // true
fan->fanOff(); // false
} else {
fan->fanOn();
}
}
private:
Fan *fan;
};
/// Invoker(调用者):Switch
class Switch {
public:
Switch() {
std::cout << "Switch Hello" << std::endl;
command = nullptr;
}
~Switch() {
std::cout << "Switch Bye" << std::endl;
delete command;
}
// 设值注入具体命令类对象
void setCommand(Command *cmd){
delete command;// 删除之前命令
command = cmd;
}
// 发送命令:切换开关
void touch(){
std::cout << "切换开关:" << std::endl;
command->execute();
}
private:
Command *command;
};
/// CommandVector 命令集合 示例
class CommandVector {
public:
CommandVector() {
std::cout << "CommandVector Hello" << std::endl;
}
~CommandVector() {
std::cout << "CommandVector Bye" << std::endl;
for(auto command : commandVector) {
delete command;
}
}
void addCommand(Command *cmd) {
commandVector.push_back(cmd);
}
void execute() { // 直接调用 commandVector 中元素 的 execute
for(auto command : commandVector) {
command->execute();
}
}
private:
std::vector<Command *> commandVector;
};
/// Invoker(调用者):SwitchVector 处理 CommandVector 命令集合
class SwitchVector {
public:
SwitchVector() {
std::cout << "SwitchVector Hello" << std::endl;
commandVector = nullptr;
}
~SwitchVector() {
std::cout << "SwitchVector Bye" << std::endl;
delete commandVector;
}
// 设值注入具体命令类对象
void setCommandVector(CommandVector *vector){
commandVector = vector;
}
// 发送命令:切换开关
void touch(){
if(nullptr!=commandVector) {
std::cout << "切换开关:" << std::endl;
commandVector->execute();
} else {
std::cout << "commandVector 为空" << std::endl;
}
}
private:
CommandVector *commandVector;
};
#endif //COMMANDPATTERN_COMMANDPATTERN_H
| [
"986740304@qq.com"
] | 986740304@qq.com |
4352e74546bf129f8ec6f376bfccbdfb927ec41c | 09b172fda28355214e237da62d4635b61617b4d6 | /heater-with-display/heater-with-display.ino | da57604ebbdc5c4bffd4b5bf93ad0fd439e27863 | [
"Apache-2.0"
] | permissive | lgv2018/filament-joiner | 1c787b9d0d930e1d1eed099158abc2b4d83ae525 | abd1bd5fdf2063e904306e7a222540911ba23f4f | refs/heads/master | 2021-03-26T02:37:16.087382 | 2020-03-16T00:40:27 | 2020-03-16T00:40:27 | 247,667,197 | 0 | 1 | Apache-2.0 | 2020-03-16T09:58:01 | 2020-03-16T09:58:00 | null | UTF-8 | C++ | false | false | 4,256 | ino | /*
* heater-with-display.ino
*
* Copyright 2020 Victor Chew
*
* 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.
*/
// Libraries required:
// - NTC_Thermister (Yurii Salimov) [Source: Arduino Library Manager]
// - PID (Brett Beuuregard) [Source: Arduino Library Manager]
// - ss_oled (Larry Bank) [Source: Arduino Library Manager]
// - TimerOne (Paul Stoffregen et al.) [Source: Arduino Library Manager]
// - ClickEncoder (0xPIT) [Source: https://github.com/0xPIT/encoder/tree/arduino]
#include <ss_oled.h>
#include <TimerOne.h>
#include <ClickEncoder.h>
#include <NTC_Thermistor.h>
#include <SmoothThermistor.h>
#include <PID_v1.h>
#define KP 17.07
#define KI 0.75
#define KD 96.57
#define SMOOTHING_WINDOW 5
#define MOSFET_GATE_PIN 3
#define THERMISTOR_PIN A6
#define KY040_CLK 9
#define KY040_DT 8
#define KY040_SW 2
#define KY040_STEPS_PER_NOTCH 2
bool heaterOn = false, pOnM = false;
double pwmOut, curTemp, setTemp = 0;
NTC_Thermistor* thermistor = new NTC_Thermistor(THERMISTOR_PIN, 10000, 100000, 25, 3950);
SmoothThermistor* sthermistor = new SmoothThermistor(thermistor, SMOOTHING_WINDOW);
PID pid(&curTemp, &pwmOut, &setTemp, KP, KI, KD, P_ON_E, DIRECT);
ClickEncoder encoder(KY040_CLK, KY040_DT, KY040_SW, KY040_STEPS_PER_NOTCH);
void refreshDisplay() {
oledFill(0, 1);
char msg[64];
sprintf(msg, "Hotend: %dc", (int)curTemp);
oledWriteString(0, 0, 1, msg, FONT_NORMAL, 0, 1);
sprintf(msg, "Target: %dc", (int)setTemp);
oledWriteString(0, 0, 3, msg, FONT_NORMAL, 0, 1);
oledWriteString(0, 0, 6, heaterOn ? "Heating..." : "- Heater off -", FONT_NORMAL, heaterOn ? 1 : 0, 1);
}
void encoderISR() {
encoder.service();
}
void setup() {
Serial.begin(115200);
pinMode(MOSFET_GATE_PIN, OUTPUT);
pid.SetMode(AUTOMATIC);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
encoder.setAccelerationEnabled(true);
Timer1.initialize(10000);
Timer1.attachInterrupt(encoderISR);
oledInit(OLED_128x64, 0, 0, -1, -1, -1, 400000L);
refreshDisplay();
}
void loop() {
// Get rotary encoder values and update display
int _curTemp = sthermistor->readCelsius();
int _setTemp = setTemp - encoder.getValue()*5; // minus because signal from this rotary switch works in the opposite direction
_setTemp = min(300, max(0, _setTemp));
bool _heaterOn = heaterOn;
if (encoder.getButton() == ClickEncoder::Clicked) {
_heaterOn = !_heaterOn;
if (!_heaterOn) _setTemp = 0;
}
// Update display only if something changes
if (_curTemp != curTemp || _setTemp != setTemp || _heaterOn != heaterOn) {
curTemp = _curTemp;
setTemp = _setTemp;
heaterOn = _heaterOn;
refreshDisplay();
}
// Turn on LED if we are within 1% of target temperature
digitalWrite(LED_BUILTIN, heaterOn ? abs(_curTemp-setTemp)/setTemp <= 0.01 : LOW);
// To speed things up, only switch to proportional-on-measurement when we are near target temperature
// See: http://brettbeauregard.com/blog/2017/06/introducing-proportional-on-measurement/
if (!pOnM && abs(curTemp-setTemp) <= max(curTemp, setTemp)*0.2) {
pOnM = true;
pid.SetTunings(KP, KI, KD, P_ON_M);
Serial.println("P_ON_M activated.");
}
// Prevent thermal overrun in case of PID malfunction
pid.Compute();
if (curTemp < 300) {
analogWrite(MOSFET_GATE_PIN, heaterOn ? pwmOut : 0);
}
else {
analogWrite(MOSFET_GATE_PIN, 0);
Serial.println("Thermal overrun detected!");
}
// Display stats
//Serial.print("pwmOut = "); Serial.print(pwmOut); Serial.print(", ");
//Serial.print("diff = "); Serial.print(setTemp - curTemp); Serial.print(", ");
//Serial.print("curTemp = "); Serial.print(round(curTemp));
//Serial.print(" / "); Serial.println(round(setTemp));
delay(200);
}
| [
"victor.chew@gmail.com"
] | victor.chew@gmail.com |
893737be26cdbf3faf2bd73d3336ccd5be2379da | 64e4fabf9b43b6b02b14b9df7e1751732b30ad38 | /src/chromium/mojo_TODO/public/cpp/bindings/lib/string_serialization.h | ef6d57fa183223dc2c4206d2053409d0fe4e7b9a | [
"BSD-3-Clause"
] | permissive | ivan-kits/skia-opengl-emscripten | 8a5ee0eab0214c84df3cd7eef37c8ba54acb045e | 79573e1ee794061bdcfd88cacdb75243eff5f6f0 | refs/heads/master | 2023-02-03T16:39:20.556706 | 2020-12-25T14:00:49 | 2020-12-25T14:00:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,722 | h | // 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.
#ifndef MOJO_PUBLIC_CPP_BINDINGS_LIB_STRING_SERIALIZATION_H_
#define MOJO_PUBLIC_CPP_BINDINGS_LIB_STRING_SERIALIZATION_H_
#include <stddef.h>
#include <string.h>
#include "mojo/public/cpp/bindings/lib/array_internal.h"
#include "mojo/public/cpp/bindings/lib/serialization_forward.h"
#include "mojo/public/cpp/bindings/lib/serialization_util.h"
#include "mojo/public/cpp/bindings/string_data_view.h"
#include "mojo/public/cpp/bindings/string_traits.h"
namespace mojo {
namespace internal {
//#if defined(ENABLE_GIPC)
template <typename MaybeConstUserType>
struct Serializer<StringDataView, MaybeConstUserType> {
using UserType = typename std::remove_const<MaybeConstUserType>::type;
using Traits = StringTraits<UserType>;
static void Serialize(MaybeConstUserType& input,
Buffer* buffer,
String_Data::BufferWriter* writer,
SerializationContext* context) {
if (CallIsNullIfExists<Traits>(input))
return;
auto r = Traits::GetUTF8(input);
writer->Allocate(r.size(), buffer);
memcpy((*writer)->storage(), r.data(), r.size());
}
static bool Deserialize(String_Data* input,
UserType* output,
SerializationContext* context) {
if (!input)
return CallSetToNullIfExists<Traits>(output);
return Traits::Read(StringDataView(input, context), output);
}
};
//#endif // ENABLE_GIPC
} // namespace internal
} // namespace mojo
#endif // MOJO_PUBLIC_CPP_BINDINGS_LIB_STRING_SERIALIZATION_H_
| [
"trofimov_d_a@magnit.ru"
] | trofimov_d_a@magnit.ru |
52e68ec90aa33155477dad0e14bf94301112f9f5 | 24b2ad530cbeba558a799c005f34df0d3337300a | /pvVision_DL0120/process_face/UltraLightFastGenericGaceDetector1MB.cpp | 58d6bd4ab82dff2324d44165fd3b1b46381dde82 | [] | no_license | lishang06/code_test | e27bd3ab158214fb32b636b445d1bc9507d9a0ca | a4f431c6c436924a2fda2f9bf7d0e94f11e55277 | refs/heads/main | 2023-06-10T01:33:13.453353 | 2021-01-20T06:38:38 | 2021-01-20T06:38:38 | 331,214,565 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,187 | cpp | #include <algorithm>
#include <map>
#include "UltraLightFastGenericGaceDetector1MB.h"
#include "faceLUT.h"
#include <iostream>
#include "unistd.h"
#include "stdio.h"
#include "stdlib.h"
#include <sys/stat.h>
UltraLightFastGenericGaceDetector1MB::UltraLightFastGenericGaceDetector1MB()
{ }
UltraLightFastGenericGaceDetector1MB::~UltraLightFastGenericGaceDetector1MB()
{ }
void UltraLightFastGenericGaceDetector1MB::load(const std::string &model_path, int num_thread)
{
// std::vector<std::string> tmpp = { model_path + "/faceDetector_V2.mnn" }; //RFB_v1_dev255_BGR
std::vector<std::string> tmpp = { model_path + "/RFB_v1_dev255_BGR.mnn" }; //RFB_v1_dev255_BGR
//std::vector<std::string> tmpp = { model_path + "/faceDetector.mnn" };
net.load_param(tmpp, num_thread);
}
void UltraLightFastGenericGaceDetector1MB::detectInternal(cv::Mat& img_, std::vector<cv::Rect> &faces, std::vector<landmarkFace> &landmarkBoxResult, int detectState)
{
faces.clear();
img = img_;
if( detectState==1 )
{
net.Ultra_infer_img(img,conf_threshold, nms_threshold,OUTPUT_NUM, center_variance, size_variance, anchors,faces, landmarkBoxResult);
}else if( detectState==2 )
{
net.Ultra_infer_img_160(img,conf_threshold, nms_threshold,OUTPUT_NUM_160, center_variance, size_variance, anchors_160,faces, landmarkBoxResult);
}else
{
net.Ultra_infer_img_80(img,conf_threshold, nms_threshold,OUTPUT_NUM_80, center_variance, size_variance, anchors_80,faces, landmarkBoxResult);
}
return;
}
void UltraLightFastGenericGaceDetector1MB::detect(const cv::Mat& img_, std::vector<cv::Rect> &faces, std::vector<landmarkFace> &landmarkBoxResult, int detectState)
{
if (img_.empty()) return;
cv::Mat testImg;
// resize and normal
if( detectState==1 )
{
cv::resize(img_, testImg, cv::Size(320,240)); //320 240
}else if( detectState==2 )
{
cv::resize(img_, testImg, cv::Size(160,120)); //320 240
}else{
cv::resize(img_, testImg, cv::Size(80,60)); //320 240
}
// detect face
detectInternal(testImg, faces, landmarkBoxResult, detectState);
return;
}
| [
"1540002025@qq.com"
] | 1540002025@qq.com |
cd62640a737a9d87623885c8f8c510a9af7028e0 | 33fb56658c522ba250049b8f49e403daec843184 | /src/log/tLog_Category_A.h | 02bde87bfcffd698ad631d3f75c6d77cfa757ce5 | [] | no_license | rleofield/previewbox | 2551ee60a38fec29c2e6a366bf6b88a1d2345f1b | 43f6439701568164c0b65f9e18a9a23f6633cd02 | refs/heads/master | 2021-05-16T02:29:00.998654 | 2019-09-18T21:39:50 | 2019-09-18T21:39:50 | 18,600,083 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,094 | h | /* --------------------------------------------------------------------------
Copyright 2012 by Richard Albrecht
richard.albrecht@rleofield.de
www.rleofield.de
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------------
*/
#ifndef TLOG_DEFINE_A_H
#define TLOG_DEFINE_A_H
#include <iostream>
#include "tLog.h"
#include "tLogCategories.h"
// wird bei Auslieferung in 'tLog.h' eingestellt
#ifdef L_A_DEBUG
// bei Auslieferung auskommentiert
//#undef L_A_DEBUG
#endif
#ifndef L_A_DEBUG
// bei Auslieferung auskommentiert
//#define L_A_DEBUG
#endif
using namespace rlf_tlog;
// logline in Code
#ifdef L_A_DEBUG
#define LOGT_A_DEBUG(exp) (logger().log( LfmCL(__LINE__,__FILE__,__FUNCTION__, eCategory::Cat_A, eLevel::LDEBUG, (exp) ) ) )
#define LOGT_A_INFO(exp) (logger().log( LfmCL(__LINE__,__FILE__,__FUNCTION__, eCategory::Cat_A, eLevel::INFO, (exp) ) ) )
#define LOGT_A_WARN(exp) (logger().log( LfmCL(__LINE__,__FILE__,__FUNCTION__, eCategory::Cat_A, eLevel::WARN, (exp) )))
#define LOGT_A_ERROR(exp) (logger().log( LfmCL(__LINE__,__FILE__,__FUNCTION__, eCategory::Cat_A, eLevel::LERROR, (exp) )))
#define LOGT_A_FATAL(exp) (logger().log( LfmCL(__LINE__,__FILE__,__FUNCTION__, eCategory::Cat_A, eLevel::FATAL, (exp) )))
#else
#define LOGT_A_DEBUG(exp) {}
#define LOGT_INFO(exp) {}
#define LOGT_A_WARN(exp) {}
#define LOGT_A_ERROR(exp) {}
#define LOGT_A_FATAL(exp) {}
#endif
#endif // TLOG_DEFINE_A_H
//EOF
| [
"richard@rleofield.de"
] | richard@rleofield.de |
e507e5310f74cc6495783be9f0cea79a6997afe4 | bc62956b6b32eaeff1527dbc1e22127e6afe95e4 | /assign6&7/src/main.cpp | e93dbba7b5971088acbbd8b9107209dda3463714 | [] | no_license | Prakhar0409/Basic_Programming | 93af5f4553fb0b0913d5ba9ab5c3074daa52204c | a1ff560c4c6f1298c98f1b2fab367c794b3ad1e1 | refs/heads/master | 2016-08-12T14:47:40.053715 | 2015-10-29T11:33:04 | 2015-10-29T11:33:04 | 45,177,283 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,773 | cpp | #include <iostream> // Allows input output operations
#include <iomanip>
#include<math.h>
//user defined headers
#include "matrix_functions.h"
#include "map_functions.h"
#include "print_functions.h"
#include "compare_functions.h"
using namespace std;
#define N 200
#define ARRAY_SIZE (N*N)
#define M 100
// Mapping is defined for [a-z] , [A-Z] , [0-9]
// {'A','6'} maps A to 6
//
// Define functionality for the following functions
// And call them in main()
/*For calculating Determinant of the Matrix */
// Donot modify the functions below(upto main)
void keygen(float key[N][N], int marker)
{
int i,j;
for(i=0;i<marker;i++){
for(j=0;j<marker;j++){
if(i != j)
key[i][j] = marker;
else
key[i][j] = marker + 1;
}
}
}
int main() {
/*********** DO NOT CHANGE VARIABLE NAMES ************/
char plain_text[ARRAY_SIZE];
char plain_text_zero_padded[ARRAY_SIZE];
char mapped_array[ARRAY_SIZE];
float mapped_array_in_2D[N][N];
int marker;
char inv_mapped_array[ARRAY_SIZE];
char decrypt_plain_text_zero_padded[ARRAY_SIZE];
float key[N][N];
float cipher_text[N][N];
float invkey[N][N];
char decrypt_plain_text[ARRAY_SIZE];
/***************Get User Input***************/
cout << "Enter the plain text" << endl;
cin >> plain_text;
cout << "Enter the marker" << endl;
cin >> marker;
// Creating a key matrix of size (marker x marker)
keygen(key,marker);
/***************End User Input***************/
/*---------------------------------------------*/
// Please add your code here
//getting string or plain text length.
int length=0; //length of the plain text.
for(int i=0;plain_text[i]!='\0';i++)
{
plain_text_zero_padded[i]=plain_text[i];
length++;
}
// cout<<length<<endl; //output length of input string
// Step 1---Padding with zeros-0's
int tmp=(length%marker);
if(tmp!=0)tmp=marker-tmp;
for(int i=0;i<tmp;i++)
plain_text_zero_padded[length+i]='0';
length=length+tmp;
plain_text_zero_padded[length]='\0';
/* //OUTPUT length and plain text zero padded
cout<<length<<endl;
for(int i=0;i<length;i++)
cout<<plain_text_zero_padded[i];
cout<<endl;
*/
//Step 2---mapping 0 padded plain text (stored in plain text) into mapped_array
array_map(mapped_array, plain_text_zero_padded);
/* //OUTPUT mapped array
for(int i=0;i<length;i++)
{
cout<<mapped_array[i];
}
cout<<endl;
*/
//step 3--generating cipher text
//3.1)---writing mapped_array in 2 D form
mapped_array[length]='\0';
int j1=0;
for(int i=0;mapped_array[i*marker+j1]!='\0';i++)
{
for(j1=0;j1<marker;j1++)
{
mapped_array_in_2D[i][j1]=mapped_array[i*marker+j1];
}
j1=0;
}
/* //OUTPUT 2D array
for(int i=0;mapped_array[i]!='\0';i++)
{
for(int j=0;j<marker;j++)
{
cout<<mapped_array_in_2D[i][j];
}
cout<<endl;
}
*/
//create cipher text
for(int i=0;i<(length/marker);i++)
{
for(int j=0;j<marker;j++)
{
cipher_text[i][j]=0;
for(int k=0;k<marker;k++)
{
cipher_text[i][j]+=mapped_array_in_2D[i][k]*key[k][j];
}
}
}
inverse(invkey,key,marker);
//transpose
for(int i=0;i<marker;i++)
{
for(int j=0;j<i;j++)
{
invkey[i][j]+=invkey[j][i];
invkey[j][i]=invkey[i][j]-invkey[j][i];
invkey[i][j]=invkey[i][j]-invkey[j][i];
}
}
for(int i=0;i<(length/marker);i++)
{
for(int j=0;j<marker;j++)
{
mapped_array_in_2D[i][j]='\0';
for(int k=0;k<marker;k++)
{
mapped_array_in_2D[i][j]+=cipher_text[i][k]*invkey[k][j];
}
mapped_array_in_2D[i][j]=round(mapped_array_in_2D[i][j]);
}
}
/* //OUTPUT array mapped in 2D
cout<<"array mapped in 2d"<<endl;
for(int i=0;i<length/marker;i++)
{
for(int j=0;j<marker;j++)
{
cout<<mapped_array_in_2D[i][j];
}
cout<<endl;
}
*/
//from 2d array to a single 1D array with inverse mappings.
for(int i=0;i<(length/marker);i++)
{
for(int j=0;j<marker;j++)
{
inv_mapped_array[(i*marker)+j]=mapped_array_in_2D[i][j];
}
}
inv_mapped_array[length]='\0';
/* // OUTPUT inverse mapped array
cout<<"inverse mapped array"<<endl;
for(int i=0;i<length;i++)
{
cout<<inv_mapped_array[i];
}
*/
inv_array_map(inv_mapped_array, decrypt_plain_text_zero_padded);
/* //OUTPUT decrypted plain text zero padded
cout<<"decrypt plain text zero padded"<<endl;
for(int i=0;i<length;i++)
{
cout<<decrypt_plain_text_zero_padded[i];
}
*/
int x=length-1;
while(decrypt_plain_text_zero_padded[x]=='0')
{
x--;
}
for(int i=0;i<=x;i++){
decrypt_plain_text[i]=decrypt_plain_text_zero_padded[i];
}
/* // OUTPUT decrypted plain text
cout<<"decrypted plain text"<<endl;
for(int i=0;i<=x;i++){
cout<<decrypt_plain_text[i];
}
cout<<endl;
*/
/*---------------------------------------------*/
// Donot modify
//
int length_of_input;
for (length_of_input = 0;plain_text[length_of_input];length_of_input++);
cout << "Plain Text entered" << endl;
cout << plain_text<< "\n";
cout << "Key Used" << endl;
print(key,marker,marker);
cout << "Cipher Text " << endl;
print(cipher_text,(int)ceil((float)length_of_input/marker),marker);
cout << "Key Inverse" << endl;
print(invkey,marker,marker);
cout << "Decrypted Text" << endl;
cout << decrypt_plain_text << "\n";
compare(plain_text,decrypt_plain_text,length_of_input);
return 0;
}
| [
"prakhar0409@gmail.com"
] | prakhar0409@gmail.com |
58e0b067f42e056858067a72f5e23bcf400912c9 | 89e001f757cd6257bf24c3daf362fb9d2d49a320 | /include/futex_semaphore.hpp | 67480f7c8cad015403f5b6da1ce4145a2535442c | [] | no_license | 4ertovwig/dummy_futex | 503e82ff67bf802314416919be3122f6ea8f0a4a | 760083b3876081aa48c7b724930910939a8e556f | refs/heads/main | 2023-08-31T20:59:59.698306 | 2021-09-22T23:50:11 | 2021-09-22T23:50:11 | 409,363,881 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,712 | hpp | #ifndef FUTEX_SEMAPHORE_HPP_
#define FUTEX_SEMAPHORE_HPP_
#include "futex_mutex.hpp"
#include "futex_condition_variable.hpp"
//! Simple and naive semaphore realization with own mutex and condition variable
//! Semantics are similar to <semaphore.h>
template< shared_policy policy >
class futex_semaphore : boost::noncopyable
{
//! Internal types
using mutex_t = futex_mutex< policy >;
using condition_t = futex_condition_variable< policy >;
public:
explicit futex_semaphore(std::int32_t maximum_simultaneous_workers) : m_limit(maximum_simultaneous_workers), m_waiters(0u)
{
if (m_limit <= 0u)
THROW_EXCEPTION(std::runtime_error, "Maximum waiters must be greater than zero");
}
void wait()
{
futex_mutex_unique_lock< mutex_t > lk(m_mutex);
++m_waiters;
m_cond.wait(lk, [&](){ return m_waiters.load() <= m_limit; });
}
template< typename Rep, typename Period >
bool wait_for(const std::chrono::duration< Rep, Period >& waited_time)
{
futex_mutex_unique_lock< mutex_t > lk(m_mutex);
++m_waiters;
if (!m_cond.wait_for(lk, waited_time, [&](){ return m_waiters.load() <= m_limit; }))
{
--m_waiters;
return false;
}
return true;
}
void post()
{
futex_mutex_lock_guard< decltype(m_mutex) > lk(m_mutex);
if (m_waiters.load() == 0u)
return;
--m_waiters;
m_cond.notify_one();
}
private:
const std::uint32_t m_limit;
std::atomic< std::int32_t > m_waiters;
//! Synchronized mutex
mutex_t m_mutex;
//! Condition variable
condition_t m_cond;
};
//! Mutex 'analog' with 1 maximum worker
template< shared_policy policy >
class binary_semaphore : public futex_semaphore< policy >
{
public:
binary_semaphore() : futex_semaphore< policy >(1u) {}
};
#endif
| [
"i.korotkov@iva-tech.ru"
] | i.korotkov@iva-tech.ru |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.