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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
fbdc5177ac9c49fb3c7afefb53a4d3b6018f350c | 2124d0b0d00c3038924f5d2ad3fe14b35a1b8644 | /source/GamosCore/GamosScoring/Scorers/src/GmPSLET_dEdx_unrestrD.cc | d32e8b41e13aa1ef9d16ff1f24e2b34e9b8d41e1 | [] | no_license | arceciemat/GAMOS | 2f3059e8b0992e217aaf98b8591ef725ad654763 | 7db8bd6d1846733387b6cc946945f0821567662b | refs/heads/master | 2023-07-08T13:31:01.021905 | 2023-06-26T10:57:43 | 2023-06-26T10:57:43 | 21,818,258 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,835 | cc | //#define VERBOSE_DOSEDEP
#include "GmPSLET_dEdx_unrestrD.hh"
#include "G4VPrimitiveScorer.hh"
#include "GamosCore/GamosScoring/Management/include/GmScoringVerbosity.hh"
#include "GamosCore/GamosUtils/include/GmGenUtils.hh"
#include "GamosCore/GamosBase/Base/include/GmParameterMgr.hh"
#include "G4EmParameters.hh"
#include "G4ProcessType.hh"
#include "G4VProcess.hh"
//--------------------------------------------------------------------
GmPSLET_dEdx_unrestrD::GmPSLET_dEdx_unrestrD(G4String name)
:GmCompoundScorer(name)
{
theUnit = 1;
theUnitName = "MeV/mm";
bInitialized = false;
// theNEventsType = SNET_ByNFilled;
G4EmParameters::Instance()->SetBuildCSDARange(true); // to build G4VEnergyLossProcess::theDEDXunRestrictedTable
}
//--------------------------------------------------------------------
G4bool GmPSLET_dEdx_unrestrD::ProcessHits(G4Step* aStep,G4TouchableHistory* th)
{
G4ProcessType procType = aStep->GetPostStepPoint()->GetProcessDefinedStep()->GetProcessType();
if( procType == fTransportation || procType == fElectromagnetic ) {
GmCompoundScorer::ProcessHits(aStep,th);
return true;
} else {
return false;
}
}
//--------------------------------------------------------------------
void GmPSLET_dEdx_unrestrD::SetParameters( const std::vector<G4String>& params)
{
if( params.size() != 0 ){
G4String parastr;
for( unsigned int ii = 0; ii < params.size(); ii++ ){
parastr += params[ii] + " ";
}
G4Exception("GmPSLET_dEdx_unrestrD::SetParameters",
"There should no parameters",FatalErrorInArgument,G4String("They are: "+parastr).c_str());
}
std::vector<G4String> paramsNC;
paramsNC.push_back("GmPSDose_LET_dEdx_unrestr/GmPSdEdxElectronicELoss"); // GmPSElectronicELoss unrestricted E lost
GmCompoundScorer::SetParameters(paramsNC);
}
| [
"pedro.arce@ciemat.es"
] | pedro.arce@ciemat.es |
8b2d4b355db7e2032137d2edb91486c2c248e9d6 | 19ad692a3b1f7cadc8e94e2ad544190dd8aa48d1 | /assignment 2/Solved/time.h | ce5061c71d1311393233c0667ae608f3b37d20ff | [] | no_license | mabdullahkhalil/Data-Structures | 96f473c612efb3e730c5a171dcabdf8fb8e29222 | c635d77e1d2ef851d830bdc68946b073dff4fe7e | refs/heads/master | 2020-03-27T06:38:11.203952 | 2018-08-25T19:10:18 | 2018-08-25T19:10:18 | 146,122,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,194 | h | #include <sys/time.h>
#include <iostream>
using namespace std;
int timeval_subtract (struct timeval *result, struct timeval *x, struct timeval *y)
{
/* Perform the carry for the later subtraction by updating y. */
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
/* Compute the time remaining to wait.
tv_usec is certainly positive. */
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
// printf(result->tv_sec);
/* Return 1 if result is negative. */
return 0;
}
struct timeval t1, t2;
struct timezone tz;
void startTimer()
{
gettimeofday(&t1, &tz);
}
void stopTimer()
{
gettimeofday(&t2, &tz);
cout<<"It took "<< t2.tv_sec - t1.tv_sec <<" seconds and "<< t2.tv_usec - t1.tv_usec<<" microseconds"<<endl;;
}
// call "startTimer()" to start timer
// call "stopTimer()" to stop timer and print total time in microseconds.
| [
"muhammadabdullahkhalil@gmail.com"
] | muhammadabdullahkhalil@gmail.com |
7cbe456fbefdd6e4d5d268558782cd777324249b | 2eec9db7c8890de85eaa2140b59116e573dd0b53 | /src/qt/modaloverlay.h | 5228ffd1e0a0f49958959ac6f6810399a5c301b6 | [
"MIT"
] | permissive | Alonewolf-123/PaydayCoin-Core | 45bca042a8014f4486977f951bc2083728d8fb5e | d807d95550d955bfa9ffda2b39cad745422224e5 | refs/heads/master | 2023-01-13T15:33:54.226987 | 2019-12-16T04:54:53 | 2019-12-16T04:54:53 | 227,445,703 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,512 | h | // Copyright (c) 2016-2018 The PaydayCoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef PAYDAYCOIN_QT_MODALOVERLAY_H
#define PAYDAYCOIN_QT_MODALOVERLAY_H
#include <QDateTime>
#include <QWidget>
//! The required delta of headers to the estimated number of available headers until we show the IBD progress
static constexpr int HEADER_HEIGHT_DELTA_SYNC = 24;
namespace Ui {
class ModalOverlay;
}
/** Modal overlay to display information about the chain-sync state */
class ModalOverlay : public QWidget
{
Q_OBJECT
public:
explicit ModalOverlay(QWidget *parent);
~ModalOverlay();
public Q_SLOTS:
void tipUpdate(int count, const QDateTime& blockDate, double nVerificationProgress);
void setKnownBestHeight(int count, const QDateTime& blockDate);
void toggleVisibility();
// will show or hide the modal layer
void showHide(bool hide = false, bool userRequested = false);
void closeClicked();
bool isLayerVisible() const { return layerIsVisible; }
protected:
bool eventFilter(QObject * obj, QEvent * ev);
bool event(QEvent* ev);
private:
Ui::ModalOverlay *ui;
int bestHeaderHeight; //best known height (based on the headers)
QDateTime bestHeaderDate;
QVector<QPair<qint64, double> > blockProcessTime;
bool layerIsVisible;
bool userClosed;
void UpdateHeaderSyncLabel();
};
#endif // PAYDAYCOIN_QT_MODALOVERLAY_H
| [
"alonewolf2ksk@gmail.com"
] | alonewolf2ksk@gmail.com |
a64e093d5d373559c712cb30cd4f734a20b4f052 | b0c8bc79873ca7136c19b62adbe07107fcbf7cd8 | /types/Body.cpp | b8bc1bdcff41c4474146a6daeaa94cb1bc32d243 | [] | no_license | Giulianos/ss-2018b-tp4 | 3de51cf709013acc74169e2ad617157866131462 | dd6d8408b66628a9931ef49f996df5424d45db15 | refs/heads/master | 2020-05-29T18:03:14.186634 | 2018-11-11T23:49:59 | 2018-11-11T23:49:59 | 189,294,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,966 | cpp | //
// Created by Giuliano Scaglioni on 05/11/2018.
//
#include "Body.h"
#include <cmath>
#include <cstdio>
int Body::next_id = 0;
double
Body::get_radius() const
{
return radius;
}
double
Body::get_mass() const
{
return mass;
}
Body::Body(double x, double y, double vx, double vy, double radius, double mass)
: current_x(x)
, previous_x(x)
, current_y(y)
, previous_y(y)
, current_vx(vx)
, current_vy(vy)
, previous_vx(vx)
, previous_vy(vy)
, current_ax(0)
, current_ay(0)
, previous_ax(0)
, previous_ay(0)
, radius(radius)
, mass(mass)
, id(Body::next_id++)
{}
double
Body::get_x() const
{
return current_x;
}
double
Body::get_y() const
{
return current_y;
}
double
Body::get_vx() const
{
return current_vx;
}
double
Body::get_vy() const
{
return current_vy;
}
double
Body::get_ax() const
{
return current_ax;
}
double
Body::get_ay() const
{
return current_ay;
}
double
Body::get_previous_ax() const
{
return previous_ax;
}
double
Body::get_previous_ay() const
{
return previous_ay;
}
int
Body::get_id() const
{
return id;
}
void
Body::set_x(double x)
{
Body::future_x = x;
}
void
Body::set_y(double y)
{
Body::future_y = y;
}
void
Body::set_vx(double vx)
{
Body::future_vx = vx;
}
void
Body::set_vy(double vy)
{
Body::future_vy = vy;
}
void
Body::set_ax(double ax)
{
Body::future_ax = ax;
}
void
Body::set_ay(double ay)
{
Body::future_ay = ay;
}
void
Body::update()
{
/** Update position */
previous_x = current_x;
previous_y = current_y;
current_x = future_x;
current_y = future_y;
future_x = NAN;
future_y = NAN;
/** Update velocity */
previous_vx = current_vx;
previous_vy = current_vy;
current_vx = future_vx;
current_vy = future_vy;
future_vx = NAN;
future_vy = NAN;
/** Update acceleration */
previous_ax = current_ax;
previous_ay = current_ay;
current_ax = future_ax;
current_ay = future_ay;
future_ax = NAN;
future_ay = NAN;
}
| [
"scaglionigiuliano@gmail.com"
] | scaglionigiuliano@gmail.com |
4372154864296e19770387a4cac9032f2a6ce47e | c8533e38289deff74c37b2759137424762e28242 | /CTCI/ch2/5b.cpp | 359bcd14ef1e31bda94a05e87801896f8f1ff9b8 | [] | no_license | rhb2/playground | 0ab19416deca8961ec5279b1b962fe2aa01a3cfc | 306257143152a76f01eedb3274c71f04bac414aa | refs/heads/master | 2023-05-11T19:11:26.317693 | 2021-06-03T22:44:46 | 2021-06-03T22:44:46 | 334,799,168 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,413 | cpp | #include <iostream>
#include <cassert>
#include "../util/sll.h"
using namespace std;
linkedlist<int> *
sumlists(linkedlist<int> &l1, linkedlist<int> &l2)
{
linkedlist<int> *result = new linkedlist<int>;
int sum;
int carry = 0;
node<int> *pn1, *pn2;
l1.reverse();
l2.reverse();
pn1 = l1.head;
pn2 = l2.head;
while (pn1 != NULL && pn2 != NULL) {
int res = pn1->val + pn2->val + carry;
sum = res % 10;
carry = res / 10;
result->push_front(sum);
pn1 = pn1->next;
pn2 = pn2->next;
}
while (pn1 != NULL) {
int res = pn1->val + carry;
sum = res % 10;
carry = res / 10;
result->push_front(sum);
pn1 = pn1->next;
}
while (pn2 != NULL) {
int res = pn2->val + carry;
sum = res % 10;
carry = res / 10;
result->push_front(sum);
pn2 = pn2->next;
}
if (carry > 0)
result->push_front(carry);
return (result);
}
int main(int argc, char **argv)
{
linkedlist<int> ll1, ll2;
int len1, len2;
int i;
assert(argc == 3);
len1 = atoi(argv[1]);
len2 = atoi(argv[2]);
for (i = 0; i < len1 - 1; i++)
ll1.push_front(rand() % 10);
/* The most significant digit must be non-zero. */
ll1.push_front((rand() % 9) + 1);
for (i = 0; i < len2 - 1; i++)
ll2.push_front(rand() % 10);
/* The most significant digit must be non-zero. */
ll2.push_front((rand() % 9) + 1);
cout << ll1 << endl;
cout << ll2 << endl;
cout << *(sumlists(ll1, ll2)) << endl;
return (0);
}
| [
"robert.bogart@joyent.com"
] | robert.bogart@joyent.com |
e91dbf012f8644c94b5e87a8a9878e7b6b9d37a4 | 8de5fa2abac197367077f8aae43c16c3ce2f9ad2 | /1010. Radix (25).cpp | 07d045461518bce47ab9bb83c0f7dc4f54598909 | [] | no_license | zhoujf620/PAT-Practice | 2220435e9a27cbbe8230263f7ad0b5572138e3fb | c2b856f530af1f4ea38dfb4992eb974081a4890b | refs/heads/master | 2020-12-04T23:24:56.252091 | 2020-01-20T14:48:01 | 2020-01-20T14:48:01 | 231,934,012 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,310 | cpp | // 1010. Radix (25)
// Given a pair of positive integers, for example, 6 and 110, can this equation 6 = 110 be true? The answer is "yes", if 6 is a decimal number and 110 is a binary number.
// Now for any pair of positive integers N1 and N2, your task is to find the radix of one number while that of the other is given.
// Input Specification:
// Each input file contains one test case. Each case occupies a line which contains 4 positive integers:<br/>
// N1 N2 tag radix<br/>
// Here N1 and N2 each has no more than 10 digits. A digit is less than its radix and is chosen from the set {0-9, a-z} where 0-9 represent the decimal numbers 0-9, and a-z represent the decimal numbers 10-35. The last number "radix" is the radix of N1 if "tag" is 1, or of N2 if "tag" is 2.
// Output Specification:
// For each test case, print in one line the radix of the other number so that the equation N1 = N2 is true. If the equation is impossible, print "Impossible". If the solution is not unique, output the smallest possible radix.
// Sample Input 1:
// 6 110 1 10
// Sample Output 1:
// 2
// Sample Input 2:
// 1 ab 1 2
// Sample Output 2:
// Impossible
#include <iostream>
#include <algorithm>
#include<math.h>
using namespace std;
long long convert(string n, int radix) {
long long sum = 0;
int index = 0, temp = 0;
for (auto it = n.rbegin(); it != n.rend(); it++) {
temp = isdigit(*it) ? *it - '0' : *it - 'a' + 10;
sum += temp * pow(radix, index++);
}
return sum;
}
long long find_radix(string n, long long num) {
char it = *max_element(n.begin(), n.end());
long long low = (isdigit(it) ? it - '0': it - 'a' + 10) + 1;
long long high = max(num, low);
while (low <= high) {
long long mid = (low + high) / 2;
long long t = convert(n, mid);
if (t < 0 || t > num) high = mid - 1;
else if (t == num) return mid;
else low = mid + 1;
}
return -1;
}
int main() {
string N1, N2;
int tag = 0, radix = 0, result_radix;
cin >> N1 >> N2 >> tag >> radix;
result_radix = tag == 1 ? find_radix(N2, convert(N1, radix)) : find_radix(N1, convert(N2, radix));
if (result_radix != -1) {
printf("%d", result_radix);
} else {
printf("Impossible");
}
return 0;
} | [
"zhoujf620@zju.edu.cn"
] | zhoujf620@zju.edu.cn |
5b1ca8adfc4cc8c5e62109714d4b9004789812cc | 4c25432a6d82aaebd82fd48e927317b15a6bf6ab | /data/dataset_2017/dataset_2017_8/ss1h2a3tw/5304486_5760761888505856_ss1h2a3tw.cpp | 2912af530b40ae4bc2009b57cba2a4b914ae51c6 | [] | no_license | wzj1988tv/code-imitator | dca9fb7c2e7559007e5dbadbbc0d0f2deeb52933 | 07a461d43e5c440931b6519c8a3f62e771da2fc2 | refs/heads/master | 2020-12-09T05:33:21.473300 | 2020-01-09T15:29:24 | 2020-01-09T15:29:24 | 231,937,335 | 1 | 0 | null | 2020-01-05T15:28:38 | 2020-01-05T15:28:37 | null | UTF-8 | C++ | false | false | 1,804 | cpp | #include <cstdio>
#include <algorithm>
using namespace std;
char cake[30][30];
int r,c;
int main (){
int T;
scanf("%d",&T);
for(int I = 1 ; I <= T ; I++){
scanf("%d%d",&r,&c);
for(int i = 0 ; i < r ; i ++){
scanf("%s",cake[i]);
}
bool firstempty=true;
for(int i = 0 ; i < c ; i ++){
if(cake[0][i]!='?')firstempty=false;
}
if(firstempty){
int nonempty=0;
for(int i = 0 ; i < r ; i ++){
bool empty=true;
for(int j = 0 ; j < c ; j ++){
if(cake[i][j]!='?')empty=false;
}
if(!empty){
nonempty=i;
break;
}
}
for(int i = 0 ; i < c ; i ++){
cake[0][i]=cake[nonempty][i];
}
}
for(int i = 1 ; i < r ; i ++){
bool empty=true;
for(int j = 0 ; j < c ; j ++){
if(cake[i][j]!='?')empty=false;
}
if(empty){
for(int j = 0 ; j < c ; j ++){
cake[i][j]=cake[i-1][j];
}
}
}
for(int i = 0 ; i < r ; i ++){
if(cake[i][0]=='?'){
for(int j = 0 ; j < c ; j ++ ){
if(cake[i][j]!='?'){
cake[i][0]=cake[i][j];
break;
}
}
}
for(int j = 0 ; j < c ; j ++){
if(cake[i][j]=='?'){
cake[i][j]=cake[i][j-1];
}
}
}
printf("Case #%d:\n",I);
for(int i = 0 ; i < r ; i ++){
printf("%s\n",cake[i]);
}
}
}
| [
"e.quiring@tu-bs.de"
] | e.quiring@tu-bs.de |
2d5f06a73a8becc601aab6f1fe95b7438e270d85 | 3ca7dd1e368194aa2f884139d01f802073cbbe0d | /Codeforces/solved/20C/20C.cpp | e46ba3d0d2b577fce5b47ede86f0fe7e77d0b6ba | [] | no_license | callistusystan/Algorithms-and-Data-Structures | 07fd1a87ff3cfb07326f9f18513386a575359447 | 560e860ca1e546b7e7930d4e1bf2dd7c3acbcbc5 | refs/heads/master | 2023-02-17T17:29:21.678463 | 2023-02-11T09:12:40 | 2023-02-11T09:12:40 | 113,574,821 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,181 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pii;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
int N, M; cin >> N >> M;
vector<vector<pair<int, ll>>> adjList(N+5);
for (int i=0;i<M;i++) {
int u,v,w; cin >> u >> v >> w;
adjList[u].push_back({v,w});
adjList[v].push_back({u,w});
}
vector<ll> dist(N+5, -1);
priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> pq;
vi parent(N+5, -1);
dist[1] = 0;
pq.push({0,1});
while (!pq.empty()) {
auto top = pq.top(); pq.pop();
ll d = top.first;
int cur = top.second;
if (d > dist[cur]) continue;
for (auto e : adjList[cur]) {
int v = e.first; ll w = e.second;
if (dist[v] == -1 || d+w < dist[v]) {
parent[v] = cur;
dist[v] = d+w;
pq.push({ d+w, v });
}
}
}
if (dist[N] == -1) cout << -1 << endl;
else {
vi ans;
int cur = N;
while (cur != -1) {
ans.push_back(cur);
cur = parent[cur];
}
while (ans.size()) {
cout << ans.back() << " ";
ans.pop_back();
}
cout << endl;
}
return 0;
}
| [
"callistusystan@gmail.com"
] | callistusystan@gmail.com |
2a4461a0a4dd9e7b399b32c016fa48e998d883ae | cc9ae71207dc667c2e0be27671ced5c86f2f71a3 | /test/oldstudy/class_array.cpp | d0663fe13534f156229ae4051ec3c7a7b4702414 | [] | no_license | xm0629/c-study | aed8480aa30b35637bfca307e009eb8b827b328d | 26183be9c91b2b53bd71b6693fe6d39823bc5d63 | refs/heads/master | 2020-04-09T11:35:48.047562 | 2019-03-30T15:27:01 | 2019-03-30T15:27:01 | 160,316,327 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 613 | cpp | // 对象数组
# include <iostream>
using namespace std;
class Box
{
public:
Box(int h=10, int w=12, int len=15):height(h),width(w),length(len){}
int volume();
private:
int height;
int width;
int length;
};
int Box::volume()
{
return (height*width*length);
}
int main()
{
Box a[3] = {
Box(10,12,15),
Box(15,15,15),
Box(20,10,15)
};
cout << "volume of a[0] is " << a[0].volume() << endl;
cout << "volume of a[1] is " << a[1].volume() << endl;
cout << "volume of a[2] is " << a[2].volume() << endl;
return 0;
}
| [
"920972751@qq.com"
] | 920972751@qq.com |
8c5166c1e4948cf10f1e75871e54dca34ff52d73 | 68c2c9f85e79fb2ce4fd3bb90d857b8be5bf9520 | /mathclass/src/subtraction.cpp | 601b946109a928df196456c796f38afe85b59430 | [
"LicenseRef-scancode-other-permissive",
"MIT"
] | permissive | mori-inj/Graphics | 556e6b7f7f722ec71f5ec5ede462e2e2b132f6a9 | 4923736e43f782e242f835074e8f67cb7653afd9 | refs/heads/master | 2021-01-01T16:47:37.426078 | 2019-06-13T20:25:47 | 2019-06-13T20:25:47 | 97,922,371 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,110 | cpp |
#include "mathclass.h"
namespace jhm {
unit_vector operator-( unit_vector const& a )
{
unit_vector b;
b.p[0] = - a.p[0];
b.p[1] = - a.p[1];
b.p[2] = - a.p[2];
return b;
}
vector operator-( vector const& a )
{
vector b;
b.p[0] = - a.p[0];
b.p[1] = - a.p[1];
b.p[2] = - a.p[2];
return b;
}
position& operator-=( position& a, vector const& b )
{
a.p[0] -= b.p[0];
a.p[1] -= b.p[1];
a.p[2] -= b.p[2];
return a;
}
vector& operator-=( vector& a, vector const& b )
{
a.p[0] -= b.p[0];
a.p[1] -= b.p[1];
a.p[2] -= b.p[2];
return a;
}
vector operator-( vector const& a, vector const& b )
{
vector c;
c.p[0] = a.p[0] - b.p[0];
c.p[1] = a.p[1] - b.p[1];
c.p[2] = a.p[2] - b.p[2];
return c;
}
vector operator-( position const& a, position const& b )
{
return vector( a.p[0] - b.p[0], a.p[1] - b.p[1], a.p[2] - b.p[2] );
}
position operator-( position const& a, vector const& b )
{
position c;
c.p[0] = a.p[0] - b.p[0];
c.p[1] = a.p[1] - b.p[1];
c.p[2] = a.p[2] - b.p[2];
return c;
}
} | [
"leokim1022@snu.ac.kr"
] | leokim1022@snu.ac.kr |
89602e597f50b469bb7dfa05a9a5317c6f75d1d7 | 6a13fa167b2d4bcea80358562dfde6164ff29693 | /Scripts/Character.cpp | 270faa38d303816f56f96861b68fd5622e29a151 | [] | no_license | scrapzero/RPG-Zero-70 | 1e4130f38e42030bbf85c64177db188dc32fa5f7 | 19e95aff37b15949878458cae1f0f107b2ba7787 | refs/heads/master | 2023-06-30T08:09:28.794552 | 2023-06-15T15:30:40 | 2023-06-15T15:30:40 | 92,604,803 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 61,161 | cpp | #include "Character.h"
#include "MyScene.h"
#include "math.h"
bool KeyOK();
bool KeyCancel();
bool KeyRight();
bool KeyLeft();
bool KeyUp();
bool KeyDown();
CEffect1::CEffect1()
{
Effect[0] = "zero/BattleEffect1.png";
}
CEffect1::~CEffect1()
{
}
void CEffect1::PushEffect(CCharacterBase * fromChar, CCharacterBase * toChar)
{
SEffect bufSEf;
if (fromChar->enemyF == false) {
bufSEf.x = fromChar->x+15;
bufSEf.y = fromChar->y;
}
else {
bufSEf.x = fromChar->x;
bufSEf.y = fromChar->y;
}
if (toChar->enemyF == false) {
bufSEf.vx = (toChar->x+15 - bufSEf.x) / effectTime1;
bufSEf.vy = (toChar->y - bufSEf.y) / effectTime1;
}
else {
bufSEf.vx = (toChar->x - bufSEf.x) / effectTime1;
bufSEf.vy = (toChar->y - bufSEf.y) / effectTime1;
}
bufSEf.drawTime = 0;
vSEffect.push_back(bufSEf);
}
void CEffect1::DrawEffect()
{
for (int i = 0; i < vSEffect.size(); i++) {
vSEffect[i].x += vSEffect[i].vx;
vSEffect[i].y += vSEffect[i].vy;
vSEffect[i].y -= cos(DX_PI * vSEffect[i].drawTime / effectTime1)*3;
vSEffect[i].drawTime++;
if (vSEffect[i].drawTime > effectTime1) {
vSEffect.erase(vSEffect.begin());
i--;
}
else {
DxLib::SetDrawBlendMode(DX_BLENDMODE_ADD, 200);
Effect[0].DrawRota(vSEffect[i].x, vSEffect[i].y, vSEffect[i].y/300, 0);
DxLib::SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 255);
}
}
}
CCharacterBase::CCharacterBase()
{
live = true;
yuusya = false;
enemyF = false;
nusunda = false;
PDamageCut = 0;
HPBar = "zero/HPBar.png";
MPBar = "zero/MPBar.png";
smallHPBar = "zero/SmallHPBar.png";
smallMPBar = "zero/SmallMPBar.png";
Window[0]= "zero/ItemSelectWindow3.png";
Window[1] = "zero/StatusWindow2.png";
for (int i = 0; i < 8; i++) {
statusHenka[i] = 0;
}
for (int i = 0; i < 10; i++) {
skill[i].targetNum = 100;
}
doku = false;
mahi = false;
housin = false;
huchi = false;
hirumi = false;
damageDisplayTime = 121;
displayDamage = 0;
cureDisplayTime = 121;
displayCure = 0;
damageMPDisplayTime = 121;
displayDamageMP = 0;
cureMPDisplayTime = 121;
displayCureMP = 0;
statusChangeDisplayTime=121;
displayStatusChange =0;
damageCut[0] = 0;
damageCut[1] = 0;
skill30 = false;
skill50 = false;
for (int i = 0; i < 10; i++)
{
skill[i].useChar = this;
skill[i].Point = -1;
skill[i].cardNum = -1;
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
dropItem[i][j] = 0;
}
}
for (int i = 0; i < 4; i++) {
jikiSkillCard[i] = NULL;
}
normalAtack.useChar = this;
normalDefence.useChar = this;
}
CCharacterBase::~CCharacterBase()
{
}
void CCharacterBase::Reset()
{
doku = false;
mahi = false;
housin = false;
huchi = false;
hirumi = false;
damageDisplayTime = 121;
displayDamage = 0;
cureDisplayTime = 121;
displayCure = 0;
damageMPDisplayTime = 121;
displayDamageMP = 0;
cureMPDisplayTime = 121;
displayCureMP = 0;
statusChangeDisplayTime = 121;
displayStatusChange = 0;
tenmetsu = 121;
damageCut[0] = 0;
damageCut[1] = 0;
for (int i = 0; i < 8; i++) {
statusHenka[i] = 0;
}
}
void CCharacterBase::Loop()
{
}
void CCharacterBase::Draw(int x, int y)
{
}
void CCharacterBase::Draw(int x,int y, bool nameZurasi)
{
}
void CCharacterBase::statusHenkaReset()
{
for (int i = 0; i < 8; i++) {
statusHenka[i] = 0;
}
}
void CCharacterBase::GiveDamge(int amount,CTextWindow *textWindow)
{
Status[0] -= amount;
DethJudge(textWindow);
tenmetsu = effectTime1*-1;
damageDisplayTime = effectTime1*-1;
displayDamage = amount;
}
void CCharacterBase::GiveCureHP(int amount, CTextWindow * textWindow)
{
int bufI = 0;
bufI = Status[0];
Status[0] += amount;
if (Status[0] > MaxHP) {
Status[0] = MaxHP;
}
cureDisplayTime = effectTime1*-1;
displayCure = Status[0]-bufI;
}
void CCharacterBase::GiveDamgeMP(int amount, CTextWindow * textWindow)
{
Status[1] -= amount;
if (Status[1] < 0) {
Status[1] = 0;
}
damageMPDisplayTime = effectTime1*-1;
displayDamageMP = amount;
}
void CCharacterBase::GiveCureMP(int amount, CTextWindow * textWindow)
{
int bufI = 0;
bufI = Status[1];
Status[1] += amount;
if (Status[1] > MaxMP) {
Status[1] = MaxMP;
}
cureMPDisplayTime = effectTime1*-1;
displayCureMP = Status[1] - bufI;
}
void CCharacterBase::GiveButuriDamge(CCharacterBase *atackChar, Skill *atackSkill,int skillNum ,CTextWindow *textWindow, bool *hazureta)
{
int damage=0;
int bufI = 0;
int buffI = 1;
stringstream bufSS;
string bufS;
bufI = (float)Status[8] * 250/ atackChar->Status[7] /33;
if (atackChar->statusHenka[5] > 0) {
bufI *= (float)(10 - statusHenka[5]) / 10;
}
if (atackChar->statusHenka[5] < 0) {
bufI *= (float)(10 - statusHenka[5] * 2) / 10;
}
if (statusHenka[6] > 0) {
bufI *= (float)(10 + statusHenka[6] * 2) / 10;
}
if (statusHenka[6] < 0) {
bufI *= (float)(10 + statusHenka[6]) / 10;
}
bufI+=1;
if (bufI < GetRand(255) && *hazureta == false) {
effect1.PushEffect(atackChar, this);
damage = (float)atackSkill->power[skillNum] * atackChar->Atc * atackChar->Atc / Def / 100;
if (atackSkill->content[skillNum] == 1) {
damage = (float)atackSkill->power[skillNum] * atackChar->MAtc * atackChar->Atc / Def / 100;
}
if (atackSkill->content[skillNum] == 2) {
damage = (float)atackSkill->power[skillNum] * atackChar->Spd * atackChar->Atc / Def / 100;
}
switch (atackSkill->element)
{
case 0:break;
case 1:damage *= (260 - FireDef); break;
case 2:damage *= (260 - WoodDef); break;
case 3:damage *= (260 - WaterDef); break;
case 4:damage *= (260 - LightDef); break;
case 5:damage *= (260 - DarkDef) ; break;
default:
break;
}
if (atackSkill->element > 0) {
damage /= 200;
}
bufI = atackChar->Luck;
if (atackChar->statusHenka[7] > 0) {
bufI *= (float)(10 + statusHenka[7] * 4) / 10;
//bufI /= 10;
}
if (atackChar->statusHenka[7] < 0) {
bufI *= (float)(10 + statusHenka[7] / 10) / 10;
//bufI /= 10;
}
buffI = 1;
if (atackSkill->content[skillNum] == 3) {
buffI = 8;
}
if ((float)GetRand(100) < (float)buffI *(10 + bufI) / 15) {
damage *= 2.8;
textWindow->PushText("クリティカルヒット!");
}
if (atackChar->statusHenka[0] > 0) {
damage *= (float)(10 + atackChar->statusHenka[0] * 2) / 10;
//damage /= 10;
}
if (atackChar->statusHenka[0] < 0) {
damage *= (float)(10 + atackChar->statusHenka[0]) / 10;
//damage /= 10;
}
if (statusHenka[1] < 0) {
damage *= (float)(10 - statusHenka[1] * 2) / 10;
//damage /= 10;
}
if (statusHenka[1] > 0) {
damage *= (float)(10 - statusHenka[1]) / 10;
//damage /= 10;
}
damage *= (float)(GetRand(15) + 100)/100;
damage *= (float)(100 - damageCut[0])/100;
if (atackSkill->PMode == 0) {
damage *= (float)(20+atackSkill->Point)/20;
//damage /= 20;
}
if (yuusya == true) {
damage *= (float)(100 - PDamageCut*2) / 100;
}
if (atackSkill->PMode == 15 && atackSkill->Point >= 10) {
damage *= 2.8;
textWindow->PushText("渾身の一撃!");
}
if (damage <= 0) {
damage = 1;
}
bufSS << name.c_str();
bufSS<< "に";
bufSS << damage;
bufSS << "ダメージ与えた。";
textWindow->PushText(bufSS.str().c_str());
GiveDamge(damage, textWindow);
if (atackSkill->content[skillNum] == 4) {
atackChar->GiveCureHP((float)damage*0.12 + 1,textWindow);
bufS = atackChar->name.c_str();
bufS += "はHPを回復した。";
textWindow->PushText(bufS.c_str());
}
if (atackSkill->content[skillNum] == 5) {
atackChar->GiveCureMP((float)damage*0.06 + 1, textWindow);
bufS = atackChar->name.c_str();
bufS += "はMP回復した。";
textWindow->PushText(bufS.c_str());
}
if (atackSkill->content[skillNum] == 8) {
atackChar->GiveDamge((float)damage*0.06, textWindow);
bufS = atackChar->name.c_str();
bufS += "は反動でダメージを受けた。";
damageDisplayTime = 0;
textWindow->PushText(bufS.c_str());
}
}
else {
bufS += "攻撃が外れた。";
textWindow->PushText(bufS.c_str());
*hazureta = true;
}
}
void CCharacterBase::GiveMahouDamge(CCharacterBase * atackChar, Skill * atackSkill, int skillNum, CTextWindow * textWindow, bool *hazureta)
{
int damage = 0;
int bufI = 0;
int buffI = 1;
stringstream bufSS;
string bufS;
bufI = (float)Status[8] * 250 / atackChar->Status[7] / 33;
if (atackChar->statusHenka[5] > 0) {
bufI *= (float)(10 - statusHenka[5]) / 10;
}
if (atackChar->statusHenka[5] < 0) {
bufI *= (float)(10 - statusHenka[5] * 2) / 10;
}
if (statusHenka[6] > 0) {
bufI *= (float)(10 + statusHenka[6] * 2) / 10;
}
if (statusHenka[6] < 0) {
bufI *= (float)(10 + statusHenka[6]) / 10;
}
bufI += 1;
if (bufI < GetRand(255) && *hazureta==false) {
effect1.PushEffect(atackChar, this);
damage = (float)atackSkill->power[skillNum] * atackChar->MAtc * atackChar->MAtc / MDef / 100;
if (atackSkill->content[skillNum] == 1) {
damage = (float)atackSkill->power[skillNum] * atackChar->Atc * atackChar->MAtc / MDef / 100;
}
if (atackSkill->content[skillNum] == 2) {
damage = (float)atackSkill->power[skillNum] * atackChar->Atc * atackChar->Spd / MDef / 100;
}
switch (atackSkill->element)
{
case 0:break;
case 1:damage *= (260 - FireDef); break;
case 2:damage *= (260 - WoodDef); break;
case 3:damage *= (260 - WaterDef); break;
case 4:damage *= (260 - LightDef); break;
case 5:damage *= (260 - DarkDef); break;
default:
break;
}
if (atackSkill->element > 0) {
damage /= 200;
}
bufI = atackChar->Luck;
if (atackChar->statusHenka[7] > 0) {
bufI *= (float)(10 + statusHenka[7] * 4) / 10;
//bufI / 10;
}
if (atackChar->statusHenka[7] < 0) {
bufI *= (float)(10 + statusHenka[7]) / 10;
//bufI /= 10;
}
buffI = 1;
if (atackSkill->content[skillNum] == 3) {
buffI = 8;
}
if ((float)GetRand(100) < (float)buffI * (10 + bufI) / 15) {
damage *= 2.8;
textWindow->PushText("クリティカルヒット!");
}
if (atackChar->statusHenka[2] > 0) {
damage *= (float)(10 + atackChar->statusHenka[2] * 2) / 10;
//damage /= 10;
}
if (atackChar->statusHenka[2] < 0) {
damage *= (float)(10 + atackChar->statusHenka[2] / 10);
//damage /= 10;
}
if (statusHenka[3] < 0) {
damage *= (float)(10 - statusHenka[3] * 2) / 10;
//damage /= 10;
}
if (statusHenka[3] > 0) {
damage *= (float)(10 - statusHenka[3]) / 10;
//damage /= 10;
}
damage *= (float)(GetRand(15) + 100)/100;
damage *= (float)(100 - damageCut[1])/100;
if (atackSkill->PMode == 0) {
damage *= (20+atackSkill->Point);
damage /= 20;
}
if (yuusya == true) {
damage *= (float)(100 - PDamageCut * 2) / 100;
}
if (atackSkill->PMode == 15 && atackSkill->Point>=10) {
textWindow->PushText("渾身の一撃!");
damage *= 2.8;
}
if (damage <= 0) {
damage = 1;
}
bufSS << name.c_str();
bufSS << "に";
bufSS << damage;
bufSS << "ダメージ与えた。";
textWindow->PushText(bufSS.str().c_str());
GiveDamge(damage, textWindow);
bufSS.clear();
if (atackSkill->content[skillNum] == 4) {
atackChar->GiveCureHP((float)damage*0.12 + 1, textWindow);
bufS = atackChar->name.c_str();
bufS += "はHPを回復した。";
textWindow->PushText(bufS.c_str());
}
if (atackSkill->content[skillNum] == 5) {
atackChar->GiveCureMP((float)damage*0.06 + 1, textWindow);
bufS = atackChar->name.c_str();
bufS += "はMPを回復した。";
textWindow->PushText(bufS.c_str());
}
if (atackSkill->content[skillNum] == 8) {
atackChar->GiveDamge((float)damage*0.06, textWindow);
bufS = atackChar->name.c_str();
bufS += "は反動でダメージを受けた。";
damageDisplayTime = 0;
textWindow->PushText(bufS.c_str());
}
}
else {
bufS += "攻撃が外れた。";
textWindow->PushText(bufS.c_str());
*hazureta = true;
}
}
void CCharacterBase::Cure(Skill * atackSkill, int skillNum, CTextWindow * textWindow)
{
int bufI=0;
string bufS = name.c_str();
bufS += "の";
stringstream bufSS;
bufSS << name.c_str();
bufSS << "の";
float bufF = 1.000;
if (atackSkill->useChar->yuusya == true &&atackSkill->PMode==10) {
bufF = (float)(30 + atackSkill->Point)/30;
}
if (atackSkill->content[skillNum] <= 1 && huchi) {
bufS = name.c_str();
bufS += "は不治状態のためHPは回復しない。";
textWindow->PushText(bufS.c_str());
}
else {
switch (atackSkill->content[skillNum])
{
case 0:
bufI = Status[0];
GiveCureHP(bufF * MaxHP*atackSkill->power[skillNum] / 100, textWindow);
bufSS << "HPが";
bufSS << (Status[0] - bufI);
bufSS << "回復した。";
break;
case 1:
bufI = Status[0];
GiveCureHP(bufF * atackSkill->power[skillNum], textWindow);
bufSS << "HPが";
bufSS << (Status[0] - bufI);
bufSS << "回復した。";
break;
case 2:
bufI = Status[1];
GiveCureMP(bufF * MaxMP*atackSkill->power[skillNum] / 100, textWindow);
bufSS << "MPが";
bufSS << (Status[1] - bufI);
bufSS << "回復した。";
break;
case 3:
bufI = Status[1];
GiveCureMP(bufF * atackSkill->power[skillNum], textWindow);
bufSS << "MPが";
bufSS << (Status[1] - bufI);
bufSS << "回復した。";
break;
case 4:
bufS = "毒の状態が治った。";
doku = false;
break;
case 5:
bufS = "麻痺の状態が治った。";
mahi = false;
break;
case 6:
bufS = "放心の状態が治った。";
housin = false;
break;
case 7:
bufS = "不治の状態が治った。";
huchi = false;
break;
case 9:
bufS = "全ての状態以上が治った。";
doku = false;
mahi = false;
housin = false;
huchi = false;
break;
case 10:
bufS = name.c_str();
if (live == false) {
bufS += "が復活した。";
Status[0] = MaxHP *atackSkill->power[skillNum] / 100;
}
else
{
bufS += "は倒れていないので復活の効果がなかった。";
}
live = true;
break;
default:
break;
}
if (atackSkill->content[skillNum] <= 3) {
textWindow->PushText(bufSS.str().c_str());
}
else {
textWindow->PushText(bufS.c_str());
}
}
}
void CCharacterBase::statusChange(Skill *atackSkill, int skillNum, CTextWindow *textWindow)
{
int kind = atackSkill->content[skillNum];
int amount = atackSkill->power[skillNum];
int bufI = statusHenka[kind];
int buffI = 0;
char koreijou = 0;
stringstream bufSS;
if (kind <= 7) {
if (statusHenka[kind] >= 5) {
koreijou = 1;
}
if (statusHenka[kind] <= -5) {
koreijou=2;
}
statusHenka[kind] += amount;
if (statusHenka[kind] >= 5) {
statusHenka[kind] = 5;
}
if (statusHenka[kind] <= -5) {
statusHenka[kind] = -5;
}
buffI = statusHenka[kind] - bufI;
bufSS << name.c_str();
bufSS << "の";
switch (kind)
{
case 0: bufSS << "物攻"; break;
case 1: bufSS << "物防"; break;
case 2: bufSS << "魔攻"; break;
case 3: bufSS << "魔防"; break;
case 4: bufSS << "速さ"; break;
case 5: bufSS << "命中"; break;
case 6: bufSS << "回避"; break;
case 7: bufSS << "運"; break;
default:
break;
}
if (koreijou == 1) {
bufSS << "はこれ以上上がらない。";
}
else if (koreijou == 2) {
bufSS << "はこれ以上下がらない。";
}
else if (buffI > 0) {
statusChangeDisplayTime = 0;
displayStatusChange = bufI;
bufSS << "が";
bufSS << buffI;
bufSS << "上がった。";
displayStatusChange = buffI;
statusChangeDisplayTime = 0;
}
else if (buffI < 0)
{
displayStatusChange = bufI;
buffI *= -1;
statusChangeDisplayTime = 0;
bufSS << "が";
bufSS << buffI;
bufSS << "下がった。";
buffI *= -1;
displayStatusChange = buffI;
statusChangeDisplayTime = 0;
}
else {
bufSS << "が変化しなった。";
}
}
if (16 <= kind && kind <= 20) {
bufSS << name.c_str();
if (kind == 16) {
for (int i = 0; i < 8; i++) {
if (statusHenka[i] > 0) {
statusHenka[i] = 0;
}
}
bufSS << "のプラスのステータス変化が0になった。";
}
if (kind == 17) {
bufSS << "のマイナスのステータス変化効果が0になった。";
for (int i = 0; i < 8; i++) {
if (statusHenka[i] < 0) {
statusHenka[i] = 0;
}
}
}
if (kind == 18) {
for (int i = 0; i < 8; i++) {
statusHenka[i] = 0;
}
bufSS << "の全てのステータス変化効果が0になった。";
}
if (kind == 19) {
bufSS << "の全てのステータスが";
bufSS << amount;
bufSS << "上がった。(5が最大)";
displayStatusChange=amount;
statusChangeDisplayTime = 0;
for (int i = 0; i < 8; i++) {
statusHenka[i] += amount;
if (statusHenka[i] >= 5) {
statusHenka[i] = 5;
}
}
}
if (kind == 20) {
bufSS << "の全てのステータスが";
bufSS << amount *-1;
bufSS << "下がった。(-5が最小)";
displayStatusChange = amount*-1;
statusChangeDisplayTime = 0;
for (int i = 0; i < 8; i++) {
statusHenka[i] -= amount;
if (statusHenka[i] <= -5 ) {
statusHenka[i] = -5;
}
}
}
}
textWindow->PushText(bufSS.str().c_str());
}
void CCharacterBase::JoutaiIjou(Skill *atackSkill, int skillNum, CTextWindow *textWindow)
{
string bufS=name.c_str();
int bufI =atackSkill->power[skillNum] * 255 / 100;
float bufF = 0;
if (atackSkill->useChar->yuusya == true && atackSkill->PMode == 13) {
bufF = (float)(30 + atackSkill->Point) / 30;
bufI *= bufF;
}
if (bufI >= GetRand(255)) {
switch (atackSkill->content[skillNum])
{
case 0:bufS+="は毒状態になった。"; break;
case 1:bufS += "は麻痺状態になった。"; break;
//case 2:bufS += "は放心状態になった。"; break;
case 3:bufS += "は不治状態になった。"; break;
case 4:bufS += "はひるんだ。"; break;
case 5:
bufS += "は毒、麻痺、不治になった。";
break;
default:
break;
}
switch (atackSkill->content[skillNum])
{
case 0:doku = true; break;
case 1:mahi = true; break;
case 2:housin = true; break;
case 3:huchi = true; break;
case 4:hirumi = true; break;
case 5:
doku = true;
mahi = true;
housin = true;
huchi = true;
break;
default:
break;
}
}
else {
switch (atackSkill->content[skillNum])
{
case 0:bufS += "は毒状態にならなかった。"; break;
case 1:bufS += "は麻痺状態にならなかった。"; break;
//case 2:bufS += "は放心状態にならなかった。"; break;
case 3:bufS += "は不治状態になならなかった。"; break;
case 4:bufS += "はひるまなかった。"; break;
case 5:
bufS += "は毒、麻痺、不治にならなかった。";
break;
default:
break;
}
}
textWindow->PushText(bufS.c_str());
}
void CCharacterBase::Tokusyu(CCharacterBase * atackChar, Skill * atackSkill, int skillNum, CTextWindow * textWindow)
{
int bufI = 0;
int bufSyahhuru[4] = { -1,-1,-1,-1 };
bool syahhuruOK = false;
string bufS = name.c_str();
bufS += "の";
stringstream bufSS;
bufSS << name.c_str();
bufSS << "の";
int maisuu = atackSkill->power[skillNum];
switch (atackSkill->content[skillNum])
{
case 0:
if (atackSkill->cardNum >= 0) {
if (atackSkill->power[skillNum] >= 4) {
for (int i = 0; i < 4; i++) {
bufSyahhuru[i] = i;
}
}
else {
for (int i = 0; i < atackSkill->power[skillNum]; i++) {
for (int j = 0; j < 300; j++) {
syahhuruOK = true;
bufSyahhuru[i] = GetRand(3);
for (int k = 0; k < i; k++) {
if (bufSyahhuru[k] == bufSyahhuru[i]) {
syahhuruOK = false;
}
}
if (atackSkill->cardNum == bufSyahhuru[i]) {
syahhuruOK = false;
}
if (syahhuruOK) {
break;
}
if (j == 299) {
for (int l = 0; l < 4; l++) {
syahhuruOK = true;
bufSyahhuru[i] = l;
for (int k = 0; k < i; k++) {
if (bufSyahhuru[k] == bufSyahhuru[i]) {
syahhuruOK = false;
}
}
if (atackSkill->cardNum == bufSyahhuru[i]) {
syahhuruOK = false;
}
if (syahhuruOK) {
break;
}
}
}
//
}
}
}
}
else {
if (atackSkill->power[skillNum] >= 4) {
for (int i = 0; i < 4; i++) {
bufSyahhuru[i] = i;
}
}
else {
for (int i = 0; i < atackSkill->power[skillNum]; i++) {
for (int j = 0; j < 300; j++) {
syahhuruOK = true;
bufSyahhuru[i] = GetRand(3);
for (int k = 0; k < i; k++) {
if (bufSyahhuru[k] == bufSyahhuru[i]) {
syahhuruOK = false;
}
}
if (syahhuruOK) {
break;
}
if (j == 299) {
for (int l = 0; l < 4; l++) {
syahhuruOK = true;
bufSyahhuru[i] = l;
for (int k = 0; k < i; k++) {
if (bufSyahhuru[k] == bufSyahhuru[i]) {
syahhuruOK = false;
}
}
if (syahhuruOK) {
break;
}
}
}
//
}
}
}
}
for (int i = 0; i < atackSkill->power[skillNum]; i++) {
if (i > 3) {
break;
}
SkillSpeadRand();
*jikiSkillCard[bufSyahhuru[i]] = skill[GetRand(5)];
jikiSkillCard[bufSyahhuru[i]]->Point = GetRand(9) + 1;
jikiSkillCard[bufSyahhuru[i]]->cardNum = bufSyahhuru[i];
}
if (maisuu > 4) {
maisuu = 4;
}
bufSS << "スキルカードを";
bufSS << maisuu;
bufSS << "枚シャッフルした。";
textWindow->PushText(bufSS.str().c_str());
break;
case 1:
for (int i = 0; i < 4; i++) {
jikiSkillCard[i]->Point += atackSkill->power[skillNum];
if (jikiSkillCard[i]->Point > 10) {
jikiSkillCard[i]->Point = 10;
}
if (jikiSkillCard[i]->Point < 1) {
jikiSkillCard[i]->Point = 1;
}
}
bufSS << "スキルカードのポイントが";
if (atackSkill->power[skillNum] >= 0) {
bufSS << atackSkill->power[skillNum];
bufSS << "上昇した。(最大は10)";
}
else {
bufSS << atackSkill->power[skillNum]*-1;
bufSS << "減少した。(最小は1)";
}
textWindow->PushText(bufSS.str().c_str());
break;
case 2:
break;
case 3:
bufI = MaxHP*atackSkill->power[skillNum] / 100;
GiveDamge(MaxHP*atackSkill->power[skillNum] / 100 , textWindow);
bufSS << "HPが";
bufSS << bufI;
bufSS << "減少した。";
textWindow->PushText(bufSS.str().c_str());
break;
case 4:
bufI = atackSkill->power[skillNum];
GiveDamge(atackSkill->power[skillNum] , textWindow);
bufSS << "HPが";
bufSS << bufI;
bufSS << "減少した。";
textWindow->PushText(bufSS.str().c_str());
break;
case 5:
bufI = MaxMP*atackSkill->power[skillNum] / 100;
GiveDamgeMP(MaxMP*atackSkill->power[skillNum] / 100 , textWindow);
bufSS << "MPが";
bufSS << bufI;
bufSS << "減少した。";
textWindow->PushText(bufSS.str().c_str());
break;
case 6:
bufI = atackSkill->power[skillNum];
GiveDamgeMP(atackSkill->power[skillNum], textWindow);
bufSS << "MPが";
bufSS << bufI;
bufSS << "減少した。";
textWindow->PushText(bufSS.str().c_str());
break;
case 7:
bufS = "このターン";
bufS += name.c_str();
bufS += "への物理ダメージが減っている。";
textWindow->PushText(bufS.c_str());
break;
case 8:
bufS = "このターン";
bufS += name.c_str();
bufS += "への魔法ダメージが減っている。";
textWindow->PushText(bufS.c_str());
break;
case 9:
bufS = "このターン";
bufS += name.c_str();
bufS += "へのダメージが減っている。";
textWindow->PushText(bufS.c_str());
break;
case 10:
if (enemyF == true) {
bufS = name.c_str();
if (nusunda == false) {
if (atackSkill->power[skillNum] > GetRand(99)) {
bufS += "から";
bufS += dropItemName[6].c_str();
bufS += "を盗んだ。";
nusunda = true;
switch (dropItem[6][0])
{
case 0:
mySaveData->sorce[dropItem[6][1]]++;
if (mySaveData->sorce[dropItem[6][1]] > 9999) {
mySaveData->sorce[dropItem[6][1]] = 9999;
}
break;
case 1:
mySaveData->tool[dropItem[6][1]]++;
if (mySaveData->tool[dropItem[6][1]] > 9999) {
mySaveData->tool[dropItem[6][1]] = 9999;
}
break;
case 2:
mySaveData->food[dropItem[6][1]]++;
if (mySaveData->food[dropItem[6][1]] > 9999) {
mySaveData->food[dropItem[6][1]] = 9999;
}
break;
default:
break;
}
}
else {
bufS += "から物を盗めなかった。";
}
}
else {
bufS += "からはもう盗む物がない!";
}
textWindow->PushText(bufS.c_str());
}
break;
case 11:
bufS = "このターン";
bufS += name.c_str();
bufS += "は仲間をかばっている。";
textWindow->PushText(bufS.c_str());
break;
}
}
void CCharacterBase::DethJudge(CTextWindow *textWindow)
{
string bufS =name.c_str();
bufS += "は倒れた。";
if (Status[0] <= 0) {
Status[0] = 0;
live = false;
textWindow->PushText(bufS.c_str());
Reset();
}
}
void CCharacterBase::PStatusUp(int pKind, CTextWindow *txWindo)
{
effect1.PushEffect(this, this);
int bufI = statusHenka[pKind-2];
int buffI = 0;
char koreijou = 0;
stringstream bufSS;
if (statusHenka[pKind-2] >= 5) {
koreijou = 1;
}
if (statusHenka[pKind-2] <= -5) {
koreijou = 2;
}
statusHenka[pKind-2]++;
if (statusHenka[pKind-2] >= 5) {
statusHenka[pKind-2] = 5;
}
if (statusHenka[pKind-2] <= -5) {
statusHenka[pKind-2] = -5;
}
buffI = statusHenka[pKind-2] - bufI;
txWindo->PushText("スキルポイントの効果!");
bufSS << name.c_str();
bufSS << "の";
switch (pKind-2)
{
case 0: bufSS << "物攻"; break;
case 1: bufSS << "物防"; break;
case 2: bufSS << "魔攻"; break;
case 3: bufSS << "魔防"; break;
case 4: bufSS << "速さ"; break;
case 5: bufSS << "命中"; break;
case 6: bufSS << "回避"; break;
case 7: bufSS << "運"; break;
default:
break;
}
if (koreijou == 1) {
bufSS << "はこれ以上上がらない。";
}
else if (koreijou == 2) {
bufSS << "はこれ以上下がらない。";
}
else if (buffI > 0) {
statusChangeDisplayTime = 0;
displayStatusChange = bufI;
bufSS << "が";
bufSS << buffI;
bufSS << "上がった。";
displayStatusChange = buffI;
statusChangeDisplayTime = 0;
}
else if (buffI < 0)
{
displayStatusChange = bufI;
buffI *= -1;
statusChangeDisplayTime = 0;
bufSS << "が";
bufSS << buffI;
bufSS << "下がった。";
buffI *= -1;
displayStatusChange = buffI;
statusChangeDisplayTime = 0;
}
else {
bufSS << "が変化しなった。";
}
txWindo->PushText(bufSS.str().c_str());
}
void CCharacterBase::GiveDokuDamage(CTextWindow * textWindow,bool boss)
{
stringstream bufSS;
int damage=0;
if (bigBoss && boss == true) {
damage = (float)MaxHP * 0.008;
}
else if(boss==true && enemyF==true){
damage = (float)MaxHP * 0.016;
}
else if (enemyF == true) {
damage = (float)MaxHP * 0.080;
}
else {
damage = (float)MaxHP * 0.040;
}
bufSS << name.c_str();
bufSS << "は毒によって";
bufSS << damage;
bufSS << "ダメージを受けた。";
textWindow->PushText(bufSS.str().c_str());
Status[0] -= damage;
if (Status[0] < 0) {
Status[0] = 0;
}
drawHP = Status[0];
displayDamage = damage;
damageDisplayTime = 0;
DethJudge(textWindow);
}
Skill CCharacterBase::returnSkill()
{
int bufI = GetRand(9);
int buffI=0;
int totalChange=0;
if (bigBoss == false) {
if (bufI < 4) {
buffI = 0;
}
else if (bufI < 6)
{
buffI = 1;
}
else if (bufI < 8)
{
buffI = 2;
}
else if (bufI < 9)
{
buffI = 3;
}
else
{
buffI = 4;
}
skill[buffI].speed = (float)Spd*(1 - GetRand(20)*0.01);
if (statusHenka[4] > 0) {
skill[buffI].speed *= (float)(10 + statusHenka[4] * 2) / 10;
}
if (statusHenka[4] < 0) {
skill[buffI].speed *= (float)(10 - statusHenka[4]) / 10;
}
return skill[buffI];
}
else {
if (skill50 == false && Status[0] <= (float)MaxHP*0.5) {
skill50 = true;
return skill[0];
}
if (skill30 == false && Status[0] <= (float)MaxHP*0.3) {
skill30 = true;
return skill[1];
}
if (doku || huchi || mahi) {
if (GetRand(19) < 2) {
return normalAtack;
}
}
for (int i = 0; i < 8; i++) {
if (statusHenka[i] < 0) {
totalChange += statusHenka[i] * -1;
}
else {
totalChange += statusHenka[i] /2;
}
}
if (totalChange * 3 >= GetRand(100)) {
return normalDefence;
}
if (bufI < 2) {
buffI = 2;
if (Status[0] <= (float)MaxHP*0.5) {
buffI = 8;
}
}
else if (bufI < 4)
{
buffI = 3;
if (Status[0] <= (float)MaxHP*0.3) {
buffI = 9;
}
}
else if (bufI < 6)
{
buffI = 4;
}
else if (bufI < 8)
{
buffI = 5;
}
else if(bufI<9)
{
buffI = 6;
}
else {
buffI = 7;
}
skill[buffI].speed = (float)Spd*(1 - GetRand(20)*0.01);
if (statusHenka[4] > 0) {
skill[buffI].speed *= (float)(10 + statusHenka[4] * 2) / 10;
}
if (statusHenka[4] < 0) {
skill[buffI].speed *= (float)(10 - statusHenka[4]) / 10;
}
return skill[buffI];
}
}
int CCharacterBase::returnSpead()
{
int buf = (float)Spd*(1 - GetRand(20)*0.01);
return buf;
}
void CCharacterBase::SkillSpeadRand()
{
for (int i = 0; i < 10; i++) {
skill[i].speed = (float)Spd*(1 - GetRand(20)*0.01);
if (statusHenka[4] > 0) {
skill[i].speed *= (float)(10 + statusHenka[4] * 2) / 10;
}
if (statusHenka[4] < 0) {
skill[i].speed *= (float)(10 + statusHenka[4]) / 10;
}
}
normalAtack.speed = (float)Spd*(1 - GetRand(20)*0.01);
if (statusHenka[4] > 0) {
normalAtack.speed *= (float)(10 + statusHenka[4] * 2) / 10;
}
if (statusHenka[4] < 0) {
normalAtack.speed *= (float)(10 + statusHenka[4]) / 10;
}
normalDefence.speed = (float)Spd*(1 - GetRand(20)*0.01);
if (statusHenka[4] > 0) {
normalDefence.speed *= (float)(10 + statusHenka[4] * 2) / 10;
}
if (statusHenka[4] < 0) {
normalDefence.speed *= (float)(10 + statusHenka[4]) / 10;
}
}
void CCharacterBase::skillHatudou(CCharacterBase *atackChar, Skill *atackSkill, int skillNum, CTextWindow *textWindow, bool *oneMore, bool *hazureta)
{
*oneMore = false;
string bufS;
if (atackSkill->useChar->live) {
if (atackSkill->hajime) {
atackSkill->hajime = false;
bufS = atackChar->name.c_str();
if (atackSkill->item) {
bufS += "は";
bufS += atackSkill->neme.c_str();
bufS += "を使った。";
}
else {
bufS += "の";
bufS += atackSkill->neme.c_str();
}
textWindow->PushText(bufS.c_str());
}
else {
if (live && *hazureta == false) {
effect1.PushEffect(atackChar, this);
switch (atackSkill->classify[skillNum])
{
case 0:
GiveButuriDamge(atackChar, atackSkill, skillNum, textWindow, hazureta);
break;
case 1:
GiveMahouDamge(atackChar, atackSkill, skillNum, textWindow, hazureta);
break;
case 2:
Cure(atackSkill, skillNum, textWindow);
break;
case 3:
JoutaiIjou(atackSkill, skillNum, textWindow);
break;
case 4:
statusChange(atackSkill, skillNum, textWindow);
break;
case 5:
Tokusyu(atackChar, atackSkill, skillNum, textWindow);
break;
default:
break;
}
}
else if (atackSkill->classify[skillNum] == 2 && atackSkill->content[skillNum] == 10 && *hazureta == false) {
Cure(atackSkill, skillNum, textWindow);
effect1.PushEffect(atackChar, this);
}
else
{
*oneMore = true;
}
}
}
else {
*oneMore=true;
atackSkill->hajime = false;
}
}
void CCharacterBase::DrawHPBar(int x, int y, bool onlyLive)
{
if (onlyLive == false || live == true) {
int bufI = 125 * Status[0] / Status[15];
HPBar.Draw(x, y);
if (Status[0] <= MaxHP*0.2) {
DrawBox(x + 50, y + 4, x + 50 + bufI, y + 20, RED_B, true);
}
else if (Status[0] <= MaxHP*0.5) {
DrawBox(x + 50, y + 4, x + 50 + bufI, y + 20, YELLOW_B, true);
}
else {
DrawBox(x + 50, y + 4, x + 50 + bufI, y + 20, GREEN_B, true);
}
}
}
void CCharacterBase::DrawMPBar(int x, int y, bool onlyLive)
{
if (onlyLive == false || live == true) {
int bufI = 125 * Status[1] / Status[16];
MPBar.Draw(x, y);
DrawBox(x + 50, y + 4, x + 50 + bufI, y + 20, BLUE_B, true);
}
}
void CCharacterBase::DrawStatusWindow(int x, int y)
{
string bufS="";
Window[1].DrawExtend(x, y, x + 200, y + 410);
DrawFormatString(x+10, y+10, BLACK, "%s",name.c_str());
for (int i = 0; i < 15; i++) {
switch (i)
{
case 0: bufS = "HP"; break;
case 1: bufS = "MP"; break;
case 2: bufS = "攻"; break;
case 3: bufS = "防"; break;
case 4: bufS = "魔攻"; break;
case 5: bufS = "魔防"; break;
case 6: bufS = "速"; break;
case 7: bufS = "命中"; break;
case 8: bufS = "回避"; break;
case 9: bufS = "運"; break;
case 10:bufS = "火防"; break;
case 11:bufS = "木防"; break;
case 12:bufS = "水防"; break;
case 13:bufS = "光防"; break;
case 14:bufS = "闇防"; break;
case 15:bufS = "所持金"; break;
default:
break;
}
if (i == 0) {
DrawFormatString(x+10, y + 40, BLACK, "%s;%d / %d", bufS.c_str(), Status[i], Status[i + 15]);
DrawHPBar(x+10, y + 60 ,false);
}
else if (i == 1) {
DrawFormatString(x+10, y + 90, BLACK, "%s;%d / %d", bufS.c_str(), Status[i],Status[i+15]);
DrawMPBar(x+10, y + 110,false);
}
else {
DrawFormatString(x+10, y + 100 + 20 * i , BLACK, "%s;%d", bufS.c_str(), Status[i]);
}
}
}
void CCharacterBase::DrawSmallHPBar(int x, int y, bool onlyLive)
{
if (damageDisplayTime == 0 || cureDisplayTime == 0) {
drawHP = Status[0];
}
if (damageDisplayTime >= 120 && cureDisplayTime >= 120) {
drawHP = Status[0];
}
int bufI = 82 * drawHP / Status[15];
//if (onlyLive == false ) {
smallHPBar.Draw(x, y);
if (drawHP <= MaxHP*0.2) {
DrawBox(x + 34, y + 4, x + 34 + bufI, y + 16, RED_B, true);
}
else if (drawHP <= MaxHP*0.5) {
DrawBox(x + 34, y + 4, x + 34 + bufI, y + 16, YELLOW_B, true);
}
else {
DrawBox(x + 34, y + 4, x + 34 + bufI, y + 16, GREEN_B, true);
}
//}
}
void CCharacterBase::DrawSmallMPBar(int x, int y, bool onlyLive)
{
if (damageDisplayTime == 0 || cureDisplayTime == 0) {
drawMP = Status[1];
}
if (damageDisplayTime >= 120 && cureDisplayTime >= 120) {
drawMP = Status[1];
}
int bufI = 82 * drawMP / Status[16];
if (onlyLive == false || live == true) {
smallMPBar.Draw(x, y);
DrawBox(x + 34, y + 4, x + 34 + bufI, y + 16, BLUE_B, true);
}
}
void CCharacterBase::DrawDamageAndCure()
{
int bufI= damageDisplayTime / 2;
if (bufI > 40) {
bufI = 40;
}
if (damageDisplayTime <= 120) {
damageDisplayTime++;
if (damageDisplayTime >= 0) {
DrawFormatString(x + 15, y - 15 - bufI, RED, "%d", displayDamage*-1);
}
}
bufI = cureDisplayTime / 2;
if (bufI > 40) {
bufI = 40;
}
if (cureDisplayTime <= 120) {
cureDisplayTime++;
if (cureDisplayTime >= 0) {
DrawFormatString(x + 15, y - 15 - bufI, GREEN_B, "+%d", displayCure);
}
}
bufI = damageMPDisplayTime / 2;
if (bufI > 40) {
bufI = 40;
}
if (damageMPDisplayTime <= 120) {
damageMPDisplayTime++;
if (damageMPDisplayTime >= 0) {
DrawFormatString(x + 15, y - 15 - bufI, RED, "%d", displayDamageMP*-1);
}
}
bufI = cureMPDisplayTime / 2;
if (bufI > 40) {
bufI = 40;
}
if (cureMPDisplayTime <= 120 ) {
cureMPDisplayTime++;
if (cureMPDisplayTime >= 0) {
DrawFormatString(x + 15, y - 15 - bufI, BLUE_B, "+%d", displayCureMP);
}
}
bufI = statusChangeDisplayTime / 2;
if (bufI > 40) {
bufI = 40;
}
if (statusChangeDisplayTime <= 120 && statusChangeDisplayTime>=0) {
statusChangeDisplayTime++;
if (displayStatusChange > 0) {
DrawFormatString(x + 30, y - 15 - bufI, ORANGE, "↑%d", displayStatusChange);
}
else if (displayStatusChange < 0) {
DrawFormatString(x + 30, y - 15 - bufI, BLUE_S, "↓%d", displayStatusChange);
}
}
effect1.DrawEffect();
}
void CCharacterBase::DrawStatusHenkaWindow(int x, int y)
{
string bufS = "";
if (enemyF == true) {
x -= 60;
y -= 60;
}
Window[0].DrawExtend(x, y, x + 136, y + 120);
for (int i = 0; i < 8;i++) {
switch (i)
{
case 0:bufS = "物攻"; break;
case 1:bufS = "物防"; break;
case 2:bufS = "魔攻"; break;
case 3:bufS = "魔防"; break;
case 4:bufS = "速"; break;
case 5:bufS = "命中"; break;
case 6:bufS = "回避"; break;
case 7:bufS = "運"; break;
default:
break;
}
if (statusHenka[i] > 0) {
DrawFormatString(x +3 + (i%2)*70, y + 5 + (i/2) * 25, ORANGE, "%s+%d", bufS.c_str(), statusHenka[i]);
}
else if (statusHenka[i] < 0) {
DrawFormatString(x + 3 + (i % 2) * 70, y + 5 + (i / 2) * 25, BLUE_S, "%s%d", bufS.c_str(), statusHenka[i]);
}
else {
DrawFormatString(x + 3 + (i % 2) * 70, y + 5 + (i / 2) * 25, BLACK, "%s±%d", bufS.c_str(), statusHenka[i]);
}
}
}
CJiki::CJiki(CMySaveData *mySD)
{
mySaveData = mySD;
name = "勇者";
charGraph = "zero/jiki1.png";
int equipmentKind = 0;
int num = 0;
int buf = 0;
int Level=0;
enemyF = false;
bigBoss = false;
for (int i = 0; i < 17; i++) {
Status[i] = 0;
}
mySaveData = mySD;
for (int i = 0; i < 5; i++) {
equipManager = new CEquipmentManager(mySaveData, mySaveData->wearEquipmentLocate[i][0]);
equipmentKind = mySaveData->wearEquipmentLocate[i][0];
buf = mySaveData->wearEquipmentLocate[i][1];
num = equipManager->haveEquipmentNumLevel[equipmentKind][buf].first;
Level = equipManager->haveEquipmentNumLevel[equipmentKind][buf].second;
wearWeaponNumLevel[i][0] = equipmentKind;
wearWeaponNumLevel[i][1] = num;
wearWeaponNumLevel[i][2] = Level;
switch (equipmentKind)
{
case 0: equipmentInfo = new CSV("zero/ZeroData/Soad.csv"); break;
case 1: equipmentInfo = new CSV("zero/ZeroData/Arrow.csv"); break;
case 2: equipmentInfo = new CSV("zero/ZeroData/Wand.csv"); break;
case 3: equipmentInfo = new CSV("zero/ZeroData/Shield.csv"); break;
case 4: equipmentInfo = new CSV("zero/ZeroData/Protecter.csv"); break;
case 5: equipmentInfo = new CSV("zero/ZeroData/Shoes.csv"); break;
case 6: equipmentInfo = new CSV("zero/ZeroData/Accessory.csv"); break;
}
MaxHP = (*equipmentInfo)[num - 1][2];
MaxMP = (*equipmentInfo)[num - 1][3];
Atc = (*equipmentInfo)[num - 1][4];
Def = (*equipmentInfo)[num - 1][5];
MAtc = (*equipmentInfo)[num - 1][6];
MDef = (*equipmentInfo)[num - 1][7];
Spd = (*equipmentInfo)[num - 1][8];
Hit = (*equipmentInfo)[num - 1][9];
Escape = (*equipmentInfo)[num - 1][10];
Luck = (*equipmentInfo)[num - 1][11];
if (equipmentKind <= 2) {
Element = (*equipmentInfo)[num - 1][12];
FireDef = (*equipmentInfo)[num - 1][13];
WoodDef = (*equipmentInfo)[num - 1][14];
WaterDef = (*equipmentInfo)[num - 1][15];
LightDef = (*equipmentInfo)[num - 1][16];
DarkDef = (*equipmentInfo)[num - 1][17];
}
else {
FireDef = (*equipmentInfo)[num - 1][12];
WoodDef = (*equipmentInfo)[num - 1][13];
WaterDef = (*equipmentInfo)[num - 1][14];
LightDef = (*equipmentInfo)[num - 1][15];
DarkDef = (*equipmentInfo)[num - 1][16];
}
MaxHP *= (1.0 + 0.1*Level);
MaxMP *= (1.0 + 0.1*Level);
Atc *= (1.0 + 0.1*Level);
Def *= (1.0 + 0.1*Level);
MAtc *= (1.0 + 0.1*Level);
MDef *= (1.0 + 0.1*Level);
Spd *= (1.0 + 0.1*Level);
Hit *= (1.0 + 0.1*Level);
Escape *= (1.0 + 0.1*Level);
Luck *= (1.0 + 0.1*Level);
FireDef *= (1.0 + 0.1*Level);
WoodDef *= (1.0 + 0.1*Level);
WaterDef *= (1.0 + 0.1*Level);
LightDef *= (1.0 + 0.1*Level);
DarkDef *= (1.0 + 0.1*Level);
HP = MaxHP;
MP = MaxMP;
Status[0] += HP;
Status[1] += MP;
Status[2] += Atc;
Status[3] += Def;
Status[4] += MAtc;
Status[5] += MDef;
Status[6] += Spd;
Status[7] += Hit;
Status[8] += Escape;
Status[9] += Luck;
Status[10] += FireDef;
Status[11] += WoodDef;
Status[12] += WaterDef;
Status[13] += LightDef;
Status[14] += DarkDef;
Status[15] += MaxHP;
Status[16] += MaxMP;
if (i == 0) {
skillNum[0] = (*equipmentInfo)[num - 1][19];
skillNum[1] = (*equipmentInfo)[num - 1][20];
}
else {
skillNum[i+1] = (*equipmentInfo)[num - 1][18];
}
delete equipmentInfo;
delete equipManager;
equipmentInfo = NULL;
equipManager = NULL;
}
HP = Status[0];
MP = Status[1];
Atc = Status[2];
Def = Status[3];
MAtc = Status[4];
MDef = Status[5];
Spd = Status[6];
Hit = Status[7];
Escape = Status[8];
Luck = Status[9];
FireDef = Status[10];
WoodDef = Status[11];
WaterDef = Status[12];
LightDef = Status[13];
DarkDef = Status[14];
MaxHP = Status[15];
MaxMP= Status[16];
equipmentKind = mySaveData->wearEquipmentLocate[0][0];
skillInfo = new CSV("zero/ZeroData/Skill.csv");
for (int i = 0; i < 6; i++) {
skill[i].ene = false;
skill[i].useChar = this;
skill[i].num = skillNum[i];
skill[i].neme = (*skillInfo)[skillNum[i] - 1][1];
skill[i].MP = (*skillInfo)[skillNum[i] - 1][2];
skill[i].element = (*skillInfo)[skillNum[i] - 1][3];
skill[i].PMode = (*skillInfo)[skillNum[i] - 1][4];
skill[i].times = (*skillInfo)[skillNum[i] - 1][5];
skill[i].classifyNum = (*skillInfo)[skillNum[i] - 1][6];
for (int j = 0; j < 3; j++) {
skill[i].target[j] = (*skillInfo)[skillNum[i] - 1][7+j*4];
skill[i].classify[j] = (*skillInfo)[skillNum[i] - 1][8+j*4];
skill[i].content[j] = (*skillInfo)[skillNum[i] - 1][9+j*4];
skill[i].power[j] = (*skillInfo)[skillNum[i] - 1][10+j*4];
}
skill[i].experience = (*skillInfo)[skillNum[i] - 1][19];
}
normalAtack.ene = false;
normalDefence.ene = false;
if (equipmentKind <= 1) {
normalAtack.num = Element + 1;
normalAtack.neme = (*skillInfo)[normalAtack.num - 1][1];
normalAtack.MP = (*skillInfo)[normalAtack.num - 1][2];
normalAtack.element = (*skillInfo)[normalAtack.num - 1][3];
normalAtack.PMode = (*skillInfo)[normalAtack.num - 1][4];
normalAtack.times = (*skillInfo)[normalAtack.num - 1][5];
normalAtack.classifyNum = (*skillInfo)[normalAtack.num - 1][6];
for (int j = 0; j < 3; j++) {
normalAtack.target[j] = (*skillInfo)[normalAtack.num - 1][7 + j * 4];
normalAtack.classify[j] = (*skillInfo)[normalAtack.num - 1][8 + j * 4];
normalAtack.content[j] = (*skillInfo)[normalAtack.num - 1][9 + j * 4];
normalAtack.power[j] = (*skillInfo)[normalAtack.num - 1][10 + j * 4];
}
normalAtack.experience = (*skillInfo)[normalAtack.num - 1][19];
}
else {
normalAtack.num = Element + 7;
normalAtack.useChar = this;
normalAtack.neme = (*skillInfo)[normalAtack.num - 1][1];
normalAtack.MP = (*skillInfo)[normalAtack.num - 1][2];
normalAtack.element = (*skillInfo)[normalAtack.num - 1][3];
normalAtack.PMode = (*skillInfo)[normalAtack.num - 1][4];
normalAtack.times = (*skillInfo)[normalAtack.num - 1][5];
normalAtack.classifyNum = (*skillInfo)[normalAtack.num - 1][6];
for (int j = 0; j < 3; j++) {
normalAtack.target[j] = (*skillInfo)[normalAtack.num - 1][7 + j * 4];
normalAtack.classify[j] = (*skillInfo)[normalAtack.num - 1][8 + j * 4];
normalAtack.content[j] = (*skillInfo)[normalAtack.num - 1][9 + j * 4];
normalAtack.power[j] = (*skillInfo)[normalAtack.num - 1][10 + j * 4];
}
normalAtack.experience = (*skillInfo)[normalAtack.num - 1][19];
}
normalDefence.num = 13;
normalDefence.useChar = this;
normalDefence.neme = (*skillInfo)[normalDefence.num - 1][1];
normalDefence.MP = (*skillInfo)[normalDefence.num - 1][2];
normalDefence.element = (*skillInfo)[normalDefence.num - 1][3];
normalDefence.PMode = (*skillInfo)[normalDefence.num - 1][4];
normalDefence.times = (*skillInfo)[normalDefence.num - 1][5];
normalDefence.classifyNum = (*skillInfo)[normalDefence.num - 1][6];
for (int j = 0; j < 3; j++) {
normalDefence.target[j] = (*skillInfo)[normalDefence.num - 1][7 + j * 4];
normalDefence.classify[j] = (*skillInfo)[normalDefence.num - 1][8 + j * 4];
normalDefence.content[j] = (*skillInfo)[normalDefence.num - 1][9 + j * 4];
normalDefence.power[j] = (*skillInfo)[normalDefence.num - 1][10 + j * 4];
}
normalDefence.experience = (*skillInfo)[normalDefence.num - 1][19];
PDamageCut = 0;
yuusya = true;
delete skillInfo;
skillInfo = NULL;
drawHP = MaxHP;
drawMP = MaxMP;
}
CJiki::~CJiki()
{
}
void CJiki::Draw(int x, int y)
{
this->x = x;
this->y = y;
DrawFormatString(x+35, y, BLACK, "%s", name.c_str());
if (tenmetsu > 60 || tenmetsu % 30 <= 15 || tenmetsu<0) {
charGraph.Draw(x, y);
}
if (tenmetsu < 110) {
tenmetsu++;
}
DrawSmallHPBar(x , y + 35, false);
DrawFormatString(x + 124, y + 37, BLACKNESS, "%d/%d", drawHP, Status[15]);
DrawSmallMPBar(x , y + 35 + 23, false);
DrawFormatString(x + 124, y + 37 + 23, BLACKNESS, "%d/%d", drawMP, Status[16]);
if (doku) {
DrawFormatString(x, y + 81, RED, "毒");
}
if (mahi) {
DrawFormatString(x + 22, y + 81, RED, "麻痺");
}
if (huchi) {
DrawFormatString(x + 66, y + 81, RED, "不治");
}
if (hirumi) {
DrawFormatString(x + 110, y + 81, RED, "ひるみ");
}
}
CHaniwa::CHaniwa(CMySaveData * mySD,int kind)
{
mySaveData = mySD;
this->kind = kind;
Level = mySaveData->haniwaLevel[kind - 1];
enemyF = false;
bigBoss = false;
haniwaInfo = new CSV("zero/ZeroData/Haniwa.csv");
float bufFlo;
int bufI;
stringstream bufSS;
bufSS << "zero/hani";
bufSS << this->kind;
bufSS << ".png";
charGraph = bufSS.str().c_str();
name = (*haniwaInfo)[kind - 1][1];
for (int i = 0; i < 15; i++) {
bufI = (*haniwaInfo)[kind - 1][2 + i];
bufFlo = (*haniwaInfo)[kind - 1][17 + i];
switch (i)
{
case 0:
HP = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][0];
MaxHP = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind-1][0];
break;
case 1:
MP = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][1];
MaxMP = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][1];
break;
case 2:
Atc = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][2];
break;
case 3:
Def = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][3];
break;
case 4:
MAtc = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][4];
break;
case 5:
MDef = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][5];
break;
case 6:
Spd = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][6];
break;
case 7:
Hit = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][7];
break;
case 8:
Escape = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][8];
break;
case 9:
Luck = bufI + bufFlo*Level + mySaveData->haniStatusPlus[kind - 1][9];
break;
case 10:
FireDef = bufI + bufFlo*Level;
break;
case 11:
WoodDef = bufI + bufFlo*Level;
break;
case 12:
WaterDef = bufI + bufFlo*Level;
break;
case 13:
LightDef = bufI + bufFlo*Level;
break;
case 14:
DarkDef = bufI + bufFlo*Level;
break;
default:
break;
}
}
Status[0] = HP;
Status[1] = MP;
Status[2] = Atc;
Status[3] = Def;
Status[4] = MAtc;
Status[5] = MDef;
Status[6] = Spd;
Status[7] = Hit;
Status[8] = Escape;
Status[9] = Luck;
Status[10] = FireDef;
Status[11] = WoodDef;
Status[12] = WaterDef;
Status[13] = LightDef;
Status[14] = DarkDef;
Status[15] = MaxHP;
Status[16] = MaxMP;
for (int i = 0; i < 4; i++) {
skillNum[i] = (this->kind - 1) * 4 + i + 1;
}
delete haniwaInfo;
haniwaInfo = NULL;
haniwaSkillInfo = new CSV("zero/ZeroData/HaniwaSkill.csv");
for (int i = 0; i < 4; i++) {
skill[i].ene = false;
skill[i].useChar = this;
skill[i].num = skillNum[i];
skill[i].neme = (*haniwaSkillInfo)[skillNum[i] - 1][1];
if (Level < 30) {
skill[i].MP = (*haniwaSkillInfo)[skillNum[i] - 1][2];
}
else if (Level < 50) {
skill[i].MP = (*haniwaSkillInfo)[skillNum[i] - 1][3];
}
else if (Level < 70) {
skill[i].MP = (*haniwaSkillInfo)[skillNum[i] - 1][4];
}
else {
skill[i].MP = (*haniwaSkillInfo)[skillNum[i] - 1][5];
}
skill[i].element = (*haniwaSkillInfo)[skillNum[i] - 1][6];
skill[i].times = (*haniwaSkillInfo)[skillNum[i] - 1][7];
skill[i].classifyNum = (*haniwaSkillInfo)[skillNum[i] - 1][8];
for (int j = 0; j < 3; j++) {
skill[i].target[j] = (*haniwaSkillInfo)[skillNum[i] - 1][9 + j * 7];
skill[i].classify[j] = (*haniwaSkillInfo)[skillNum[i] - 1][10 + j * 7];
skill[i].content[j] = (*haniwaSkillInfo)[skillNum[i] - 1][11 + j * 7];
if (Level < 30) {
skill[i].power[j] = (*haniwaSkillInfo)[skillNum[i] - 1][12 + j * 7];
}
else if (Level < 50) {
skill[i].power[j] = (*haniwaSkillInfo)[skillNum[i] - 1][13 + j * 7];
}
else if (Level < 70) {
skill[i].power[j] = (*haniwaSkillInfo)[skillNum[i] - 1][14 + j * 7];
}
else {
skill[i].power[j] = (*haniwaSkillInfo)[skillNum[i] - 1][15 + j * 7];
}
}
skill[i].experience = (*haniwaSkillInfo)[skillNum[i] - 1][30];
}
delete haniwaSkillInfo;
haniwaSkillInfo = NULL;
skillInfo = new CSV("zero/ZeroData/Skill.csv");
normalAtack.num = 1;
normalAtack.ene = false;
normalDefence.ene = false;
normalAtack.neme = (*skillInfo)[normalAtack.num - 1][1];
normalAtack.MP = (*skillInfo)[normalAtack.num - 1][2];
normalAtack.element = (*skillInfo)[normalAtack.num - 1][3];
normalAtack.times = (*skillInfo)[normalAtack.num - 1][5];
normalAtack.classifyNum = (*skillInfo)[normalAtack.num - 1][6];
normalAtack.useChar = this;
for (int j = 0; j < 3; j++) {
normalAtack.target[j] = (*skillInfo)[normalAtack.num - 1][7 + j * 4];
normalAtack.classify[j] = (*skillInfo)[normalAtack.num - 1][8 + j * 4];
normalAtack.content[j] = (*skillInfo)[normalAtack.num - 1][9 + j * 4];
normalAtack.power[j] = (*skillInfo)[normalAtack.num - 1][10 + j * 4];
}
normalAtack.experience = (*skillInfo)[normalAtack.num - 1][19];
normalDefence.num = 13;
normalDefence.neme = (*skillInfo)[normalDefence.num - 1][1];
normalDefence.MP = (*skillInfo)[normalDefence.num - 1][2];
normalDefence.element = (*skillInfo)[normalDefence.num - 1][3];
normalDefence.times = (*skillInfo)[normalDefence.num - 1][5];
normalDefence.classifyNum = (*skillInfo)[normalDefence.num - 1][6];
normalDefence.useChar = this;
for (int j = 0; j < 3; j++) {
normalDefence.target[j] = (*skillInfo)[normalDefence.num - 1][7 + j * 4];
normalDefence.classify[j] = (*skillInfo)[normalDefence.num - 1][8 + j * 4];
normalDefence.content[j] = (*skillInfo)[normalDefence.num - 1][9 + j * 4];
normalDefence.power[j] = (*skillInfo)[normalDefence.num - 1][10 + j * 4];
}
normalDefence.experience = (*skillInfo)[normalDefence.num - 1][19];
delete skillInfo;
skillInfo = NULL;
drawHP = MaxHP;
drawMP = MaxMP;
}
CHaniwa::~CHaniwa()
{
}
void CHaniwa::Draw(int x, int y)
{
this->x = x;
this->y = y;
DrawFormatString(x + 35 , y, BLACK, "%s", name.c_str());
if (tenmetsu > 60 || tenmetsu % 30 <= 15 || tenmetsu<0) {
charGraph.Draw(x, y);
}
if (tenmetsu < 110) {
tenmetsu++;
}
DrawSmallHPBar(x , y + 35, false);
DrawFormatString(x + 124, y +37, BLACKNESS, "%d/%d",drawHP,MaxHP);
DrawSmallMPBar(x, y + 35 + 23, false);
DrawFormatString(x + 124, y + 37 + 23, BLACKNESS, "%d/%d", drawMP, MaxMP);
if (doku) {
DrawFormatString(x, y + 81, RED, "毒");
}
if (mahi) {
DrawFormatString(x + 22, y + 81, RED, "麻痺");
}
if (huchi) {
DrawFormatString(x + 66, y + 81, RED, "不治");
}
if (hirumi) {
DrawFormatString(x + 110, y + 81, RED, "ひるみ");
}
}
CEnemy::CEnemy(CMySaveData * mySD, int kind, bool bigBoss)
{
mySaveData = mySD;
this->kind = kind;
this->bigBoss = bigBoss;
float bufFlo;
int bufI;
string bufS;
if (bigBoss == false) {
enemyInfo = new CSV("zero/ZeroData/Enemy.csv");
enemyF = true;
name = (*enemyInfo)[kind-1][1];
bufS = (*enemyInfo)[kind - 1][2];
charGraph = bufS.c_str();
for (int i = 0; i < 15; i++) {
bufI = (*enemyInfo)[kind-1][3 + i];
switch (i)
{
case 0:
HP = bufI ;
MaxHP = bufI ;
break;
case 1:
Atc = bufI;
break;
case 2:
Def = bufI;
break;
case 3:
MAtc = bufI;
break;
case 4:
MDef = bufI;
break;
case 5:
Spd = bufI;
break;
case 6:
Hit = bufI;
break;
case 7:
Escape = bufI ;
break;
case 8:
Luck = bufI ;
break;
case 9:
FireDef = bufI ;
break;
case 10:
WoodDef = bufI ;
break;
case 11:
WaterDef = bufI ;
break;
case 12:
LightDef = bufI ;
break;
case 13:
DarkDef = bufI ;
break;
default:
break;
}
}
Status[0] = HP;
Status[1] = MP;
Status[2] = Atc;
Status[3] = Def;
Status[4] = MAtc;
Status[5] = MDef;
Status[6] = Spd;
Status[7] = Hit;
Status[8] = Escape;
Status[9] = Luck;
Status[10] = FireDef;
Status[11] = WoodDef;
Status[12] = WaterDef;
Status[13] = LightDef;
Status[14] = DarkDef;
Status[15] = MaxHP;
Status[16] = MaxMP;
for (int i = 0; i < 5; i++) {
skillNum[i] = (*enemyInfo)[kind - 1][17 + i];
if (skillNum[i] <= 0) {
skillNum[i] = 1;
}
}
for (int i = 0; i < 7; i++) {
bufI = GetRand(19);
if (bufI < 8) {
dropItem[i][0] = (*enemyInfo)[kind - 1][22 + 0 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][23 + 0 * 2];
}
else if (bufI < 14) {
dropItem[i][0] = (*enemyInfo)[kind - 1][22 + 1 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][23 + 1 * 2];
}
else if (bufI < 18) {
dropItem[i][0] = (*enemyInfo)[kind - 1][22 + 2 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][23 + 2 * 2];
}
else {
dropItem[i][0] = (*enemyInfo)[kind - 1][22 + 3 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][23 + 3 * 2];
}
}
delete enemyInfo;
enemyInfo = NULL;
for (int i = 0; i < 7; i++) {
switch (dropItem[i][0]) {
case 0:
itemInfo = new CSV("zero/ZeroData/Sorce.csv");
break;
case 1:
itemInfo = new CSV("zero/ZeroData/Tool.csv");
break;
case 2:
itemInfo = new CSV("zero/ZeroData/Food.csv");
break;
}
dropItemName[i] = (*itemInfo)[dropItem[i][1] - 1][1];
delete itemInfo;
itemInfo = NULL;
}
skillInfo = new CSV("zero/ZeroData/Skill.csv");
for (int i = 0; i < 5; i++) {
skill[i].ene = true;
skill[i].useChar = this;
skill[i].num = skillNum[i];
if (skillNum[i] > 0) {
skill[i].neme = (*skillInfo)[skillNum[i] - 1][1];
skill[i].MP = (*skillInfo)[skillNum[i] - 1][2];
skill[i].element = (*skillInfo)[skillNum[i] - 1][3];
skill[i].PMode = (*skillInfo)[skillNum[i] - 1][4];
skill[i].times = (*skillInfo)[skillNum[i] - 1][5];
skill[i].classifyNum = (*skillInfo)[skillNum[i] - 1][6];
for (int j = 0; j < 3; j++) {
skill[i].target[j] = (*skillInfo)[skillNum[i] - 1][7 + j * 4];
skill[i].classify[j] = (*skillInfo)[skillNum[i] - 1][8 + j * 4];
skill[i].content[j] = (*skillInfo)[skillNum[i] - 1][9 + j * 4];
skill[i].power[j] = (*skillInfo)[skillNum[i] - 1][10 + j * 4];
}
skill[i].experience = (*skillInfo)[skillNum[i] - 1][19];
}
}
delete skillInfo;
skillInfo = NULL;
}
else {
enemyInfo = new CSV("zero/ZeroData/BigBoss.csv");
enemyF = true;
name = (*enemyInfo)[kind - 1][1];
bufS = (*enemyInfo)[kind - 1][2];
charGraph = bufS.c_str();
for (int i = 0; i < 15; i++) {
bufI = (*enemyInfo)[kind - 1][3 + i];
switch (i)
{
case 0:
HP = bufI;
MaxHP = bufI;
break;
case 1:
Atc = bufI;
break;
case 2:
Def = bufI;
break;
case 3:
MAtc = bufI;
break;
case 4:
MDef = bufI;
break;
case 5:
Spd = bufI;
break;
case 6:
Hit = bufI;
break;
case 7:
Escape = bufI;
break;
case 8:
Luck = bufI;
break;
case 9:
FireDef = bufI;
break;
case 10:
WoodDef = bufI;
break;
case 11:
WaterDef = bufI;
break;
case 12:
LightDef = bufI;
break;
case 13:
DarkDef = bufI;
break;
default:
break;
}
}
Status[0] = HP;
Status[1] = MP;
Status[2] = Atc;
Status[3] = Def;
Status[4] = MAtc;
Status[5] = MDef;
Status[6] = Spd;
Status[7] = Hit;
Status[8] = Escape;
Status[9] = Luck;
Status[10] = FireDef;
Status[11] = WoodDef;
Status[12] = WaterDef;
Status[13] = LightDef;
Status[14] = DarkDef;
Status[15] = MaxHP;
Status[16] = MaxMP;
actTimes=(*enemyInfo)[kind - 1][17];
for (int i = 0; i <10; i++) {
skillNum[i] = (*enemyInfo)[kind - 1][18 + i];
if (skillNum[i] <= 0) {
skillNum[i] = 1;
}
}
for (int i = 0; i < 7; i++) {
bufI = GetRand(19);
if (bufI < 5) {
dropItem[i][0] = (*enemyInfo)[kind - 1][28 + 0 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][29 + 0 * 2];
}
else if (bufI < 9) {
dropItem[i][0] = (*enemyInfo)[kind - 1][28 + 1 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][29 + 1 * 2];
}
else if (bufI < 11) {
dropItem[i][0] = (*enemyInfo)[kind - 1][28 + 2 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][29 + 2 * 2];
}
else if (bufI < 13) {
dropItem[i][0] = (*enemyInfo)[kind - 1][28 + 3 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][29 + 3 * 2];
}
else if (bufI < 15) {
dropItem[i][0] = (*enemyInfo)[kind - 1][28 + 4 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][29 + 4 * 2];
}
else if (bufI < 17) {
dropItem[i][0] = (*enemyInfo)[kind - 1][28 + 5 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][29 + 5 * 2];
}
else if (bufI < 19) {
dropItem[i][0] = (*enemyInfo)[kind - 1][28 + 6 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][29 + 6 * 2];
}
else{
dropItem[i][0] = (*enemyInfo)[kind - 1][28 + 7 * 2];
dropItem[i][1] = (*enemyInfo)[kind - 1][29 + 7 * 2];
}
}
delete enemyInfo;
enemyInfo = NULL;
for (int i = 0; i < 7; i++) {
switch (dropItem[i][0]) {
case 0:
itemInfo = new CSV("zero/ZeroData/Sorce.csv");
break;
case 1:
itemInfo = new CSV("zero/ZeroData/Tool.csv");
break;
case 2:
itemInfo = new CSV("zero/ZeroData/Food.csv");
break;
}
dropItemName[i] = (*itemInfo)[dropItem[i][1] - 1][1];
delete itemInfo;
itemInfo = NULL;
}
skillInfo = new CSV("zero/ZeroData/Skill.csv");
for (int i = 0; i < 10; i++) {
skill[i].ene = true;
skill[i].useChar = this;
skill[i].num = skillNum[i];
if (skillNum[i] > 0) {
skill[i].neme = (*skillInfo)[skillNum[i] - 1][1];
skill[i].MP = (*skillInfo)[skillNum[i] - 1][2];
skill[i].element = (*skillInfo)[skillNum[i] - 1][3];
skill[i].PMode = (*skillInfo)[skillNum[i] - 1][4];
skill[i].times = (*skillInfo)[skillNum[i] - 1][5];
skill[i].classifyNum = (*skillInfo)[skillNum[i] - 1][6];
for (int j = 0; j < 3; j++) {
skill[i].target[j] = (*skillInfo)[skillNum[i] - 1][7 + j * 4];
skill[i].classify[j] = (*skillInfo)[skillNum[i] - 1][8 + j * 4];
skill[i].content[j] = (*skillInfo)[skillNum[i] - 1][9 + j * 4];
skill[i].power[j] = (*skillInfo)[skillNum[i] - 1][10 + j * 4];
}
skill[i].experience = (*skillInfo)[skillNum[i] - 1][19];
}
}
normalAtack.ene = true;
normalAtack.useChar = this;
normalAtack.num = 14;
normalAtack.neme = (*skillInfo)[14 - 1][1];
normalAtack.MP = (*skillInfo)[14 - 1][2];
normalAtack.element = (*skillInfo)[14 - 1][3];
normalAtack.PMode = (*skillInfo)[14 - 1][4];
normalAtack.times = (*skillInfo)[14 - 1][5];
normalAtack.classifyNum = (*skillInfo)[14 - 1][6];
for (int j = 0; j < 3; j++) {
normalAtack.target[j] = (*skillInfo)[14 - 1][7 + j * 4];
normalAtack.classify[j] = (*skillInfo)[14 - 1][8 + j * 4];
normalAtack.content[j] = (*skillInfo)[14 - 1][9 + j * 4];
normalAtack.power[j] = (*skillInfo)[14 - 1][10 + j * 4];
}
normalAtack.experience = (*skillInfo)[14 - 1][19];
normalDefence.ene = true;
normalDefence.useChar = this;
normalDefence.num = 15;
normalDefence.neme = (*skillInfo)[15 - 1][1];
normalDefence.MP = (*skillInfo)[15 - 1][2];
normalDefence.element = (*skillInfo)[15 - 1][3];
normalDefence.PMode = (*skillInfo)[15 - 1][4];
normalDefence.times = (*skillInfo)[15 - 1][5];
normalDefence.classifyNum = (*skillInfo)[15 - 1][6];
for (int j = 0; j < 3; j++) {
normalDefence.target[j] = (*skillInfo)[15 - 1][7 + j * 4];
normalDefence.classify[j] = (*skillInfo)[15 - 1][8 + j * 4];
normalDefence.content[j] = (*skillInfo)[15 - 1][9 + j * 4];
normalDefence.power[j] = (*skillInfo)[15 - 1][10 + j * 4];
}
normalDefence.experience = (*skillInfo)[15 - 1][19];
delete skillInfo;
skillInfo = NULL;
}
tenmetsu = 121;
drawHP = MaxHP;
drawMP = MaxMP;
nusunda = false;
}
CEnemy::~CEnemy()
{
}
void CEnemy::Draw(int x, int y, bool nameZurasi)
{
this->x = x+60;
this->y = y+60;
if (live == true || damageDisplayTime<=0 ||cureDisplayTime<=0 || damageMPDisplayTime<=0 || cureMPDisplayTime<=0) {
if (tenmetsu > 90 || tenmetsu % 30 <= 15 || tenmetsu<0) {
charGraph.DrawRota(this->x,this->y,1.00,0);
}
if (tenmetsu < 110) {
tenmetsu++;
}
DrawSmallHPBar(x, y - 24, true);
if (nameZurasi == false) {
DrawFormatString(x-5, y - 44, BLACK, name.c_str());
}
else
{
DrawFormatString(x, y - 64, BLACK, name.c_str());
}
if (doku) {
DrawFormatString(x-6, y - 84, RED, "毒");
}
if (mahi) {
DrawFormatString(x + 14, y - 84, RED, "麻痺");
}
if (huchi) {
DrawFormatString(x + 54, y - 84, RED, "不治");
}
if (hirumi) {
DrawFormatString(x -6, y -105 , RED, "ひるみ");
}
}
}
| [
"doragontuinatomikku@gmail.com"
] | doragontuinatomikku@gmail.com |
6cbf9d74c62652e42e372bf9fdba97dde802d950 | 6104eba97327b09b0d5f084c990b3bf50ef20ca6 | /STL_Univ/STL_Univ/unodered_set 과 map.cpp | 136e2cab3b514202d44c1f0e9421c80714ddcf01 | [
"MIT"
] | permissive | LeeKangW/CPP_Study | 03caf637d3cc797f6d8f5ed3121228f9e23f3232 | 897cd33ddeca79bbef6c4a084c309b40c6733334 | refs/heads/master | 2021-07-13T00:40:25.666219 | 2021-06-24T02:01:46 | 2021-06-24T02:01:46 | 222,482,593 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 1,203 | cpp | #include<iostream>
#include<unordered_set>
#include<random>
#include<thread>
#include"String.h"
#include"save.h"
using namespace std;
//2020.5.25 월
//
// unordered_set / unordered_map
//
// unordered associative container
// 1. 순서가 없다.
// 2. 메모리 구조를 출력
// 3. String을 이 컨테이너의 원소로 되도록 하려면
// hash 함수를 쓰기 때문에 찾을 때 O(1) 이 걸린다.
int main() {
/* initializer_list<int> x = { 1,2,3,4,5,6,7 };
// -> 클래스 생성자로 많이 씀.
// auto x = { 1,2,3,4,5,6,7 };
// cout << typeid(x).name() << endl;
*/
unordered_set<int> us{ 1,2,3,4,5,6,7,9 };
/*
hash 함수 설계 ( 아주 중요하다. )
-> hash<int>(); // 이름 없는 객체
*/
/*
for (int i = 0; i < 10; ++i)
{
// cout << hash<int>().operator()(i) << endl; // <- 원래 표기 법
cout << hash<int>()(i) << endl; // <- 좀 더 쉬운 표기 법
}
*/
// unordered_set의 메모리 모양을 화면에 출력한다.
/*
*/
for (int i = 0; i < us.bucket_count(); ++i) {
cout << "[" << i << "]";
if (us.bucket_size(i)) {
for (auto p = us.begin(i); p != us.end(i); ++p)
cout << " --> " << *p;
}
cout << endl;
}
} | [
"leegw1371@gmail.com"
] | leegw1371@gmail.com |
7a71b6a4d0506a37bc222e9612eaa9758bc01194 | 4cc4d9d488939dde56fda368faf58d8564047673 | /test/vts/compilation_tools/vtsc/code_gen/fuzzer/HalHidlFuzzerCodeGen.cpp | 6bb6176a6d99f7e945f00043e56ca4aa91131e96 | [] | no_license | Tosotada/android-8.0.0_r4 | 24b3e4590c9c0b6c19f06127a61320061e527685 | 7b2a348b53815c068a960fe7243b9dc9ba144fa6 | refs/heads/master | 2020-04-01T11:39:03.926512 | 2017-08-28T16:26:25 | 2017-08-28T16:26:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,150 | cpp | /*
* Copyright 2016 The Android Open Source Project
*
* 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 "HalHidlFuzzerCodeGen.h"
#include "VtsCompilerUtils.h"
#include "code_gen/common/HalHidlCodeGenUtils.h"
#include "utils/InterfaceSpecUtil.h"
#include "utils/StringUtil.h"
using std::cerr;
using std::cout;
using std::endl;
using std::vector;
namespace android {
namespace vts {
void HalHidlFuzzerCodeGen::GenerateSourceIncludeFiles(Formatter &out) {
out << "#include <iostream>\n\n";
out << "#include \"FuncFuzzerUtils.h\"\n";
string package_path = comp_spec_.package();
ReplaceSubString(package_path, ".", "/");
string comp_version = GetVersionString(comp_spec_.component_type_version());
string comp_name = comp_spec_.component_name();
out << "#include <" << package_path << "/" << comp_version << "/" << comp_name
<< ".h>\n";
out << "\n";
}
void HalHidlFuzzerCodeGen::GenerateUsingDeclaration(Formatter &out) {
out << "using std::cerr;\n";
out << "using std::endl;\n";
out << "using std::string;\n\n";
string package_path = comp_spec_.package();
ReplaceSubString(package_path, ".", "::");
string comp_version =
GetVersionString(comp_spec_.component_type_version(), true);
out << "using namespace ::" << package_path << "::" << comp_version << ";\n";
out << "using namespace ::android::hardware;\n";
out << "\n";
}
void HalHidlFuzzerCodeGen::GenerateGlobalVars(Formatter &out) {
out << "static string target_func;\n\n";
}
void HalHidlFuzzerCodeGen::GenerateLLVMFuzzerInitialize(Formatter &out) {
out << "extern \"C\" int LLVMFuzzerInitialize(int *argc, char ***argv) "
"{\n";
out.indent();
out << "FuncFuzzerParams params{ExtractFuncFuzzerParams(*argc, *argv)};\n";
out << "target_func = params.target_func_;\n";
out << "return 0;\n";
out.unindent();
out << "}\n\n";
}
void HalHidlFuzzerCodeGen::GenerateLLVMFuzzerTestOneInput(Formatter &out) {
out << "extern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t "
"size) {\n";
out.indent();
out << "static ::android::sp<" << comp_spec_.component_name() << "> "
<< GetHalPointerName() << " = " << comp_spec_.component_name()
<< "::getService(true);\n";
out << "if (" << GetHalPointerName() << " == nullptr) {\n";
out.indent();
out << "cerr << \"" << comp_spec_.component_name()
<< "::getService() failed\" << endl;\n";
out << "exit(1);\n";
out.unindent();
out << "}\n\n";
for (const auto &func_spec : comp_spec_.interface().api()) {
GenerateHalFunctionCall(out, func_spec);
}
out << "{\n";
out.indent();
out << "cerr << \"No such function: \" << target_func << endl;\n";
out << "exit(1);\n";
out.unindent();
out << "}\n";
out.unindent();
out << "}\n\n";
}
string HalHidlFuzzerCodeGen::GetHalPointerName() {
string prefix = "android.hardware.";
string hal_pointer_name = comp_spec_.package().substr(prefix.size());
ReplaceSubString(hal_pointer_name, ".", "_");
return hal_pointer_name;
}
void HalHidlFuzzerCodeGen::GenerateReturnCallback(
Formatter &out, const FunctionSpecificationMessage &func_spec) {
if (CanElideCallback(func_spec)) {
return;
}
out << "// No-op. Only need this to make HAL function call.\n";
out << "auto " << return_cb_name << " = [](";
size_t num_cb_arg = func_spec.return_type_hidl_size();
for (size_t i = 0; i < num_cb_arg; ++i) {
const auto &return_val = func_spec.return_type_hidl(i);
out << GetCppVariableType(return_val, nullptr,
IsConstType(return_val.type()));
out << " arg" << i << ((i != num_cb_arg - 1) ? ", " : "");
}
out << "){};\n\n";
}
void HalHidlFuzzerCodeGen::GenerateHalFunctionCall(
Formatter &out, const FunctionSpecificationMessage &func_spec) {
string func_name = func_spec.name();
out << "if (target_func == \"" << func_name << "\") {\n";
out.indent();
GenerateReturnCallback(out, func_spec);
vector<string> types{GetFuncArgTypes(func_spec)};
for (size_t i = 0; i < types.size(); ++i) {
out << "size_t type_size" << i << " = sizeof(" << types[i] << ");\n";
out << "if (size < type_size" << i << ") { return 0; }\n";
out << "size -= type_size" << i << ";\n";
out << types[i] << " arg" << i << ";\n";
out << "memcpy(&arg" << i << ", data, type_size" << i << ");\n";
out << "data += type_size" << i << ";\n\n";
}
out << GetHalPointerName() << "->" << func_spec.name() << "(";
for (size_t i = 0; i < types.size(); ++i) {
out << "arg" << i << ((i != types.size() - 1) ? ", " : "");
}
if (!CanElideCallback(func_spec)) {
if (func_spec.arg_size() > 0) {
out << ", ";
}
out << return_cb_name;
}
out << ");\n";
out << "return 0;\n";
out.unindent();
out << "} else ";
}
bool HalHidlFuzzerCodeGen::CanElideCallback(
const FunctionSpecificationMessage &func_spec) {
if (func_spec.return_type_hidl_size() == 0) {
return true;
}
// Can't elide callback for void or tuple-returning methods
if (func_spec.return_type_hidl_size() != 1) {
return false;
}
const VariableType &type = func_spec.return_type_hidl(0).type();
if (type == TYPE_ARRAY || type == TYPE_VECTOR || type == TYPE_REF) {
return false;
}
return IsElidableType(type);
}
vector<string> HalHidlFuzzerCodeGen::GetFuncArgTypes(
const FunctionSpecificationMessage &func_spec) {
vector<string> types{};
for (const auto &var_spec : func_spec.arg()) {
string type = GetCppVariableType(var_spec);
types.emplace_back(GetCppVariableType(var_spec));
}
return types;
}
} // namespace vts
} // namespace android
| [
"xdtianyu@gmail.com"
] | xdtianyu@gmail.com |
2cb63511678f4ee4ca3e068f7b21bf81a78ee107 | 1a9df829cfba53d1032a4e4fd60f40e998af2924 | /src/predict_pseudo.cpp | a7c164e20b52f1b1978e441e54dff1e2c04bfd66 | [] | no_license | X4vier/MC-AIXI-CTW | bf30c2610ed5435e4ba741e6daa741c8176a3789 | ea2e98e95352166f8d707a200e67fb0e30690376 | refs/heads/master | 2020-04-04T15:41:17.541126 | 2018-11-04T04:17:40 | 2018-11-04T04:17:40 | 156,047,993 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,438 | cpp | #include "predict_pseudo.hpp"
#include <cassert>
#include <ctime>
#include <cmath>
#include "util.hpp"
// create a context tree of specified maximum depth
ContextTree::ContextTree(size_t depth) { return; }
ContextTree::~ContextTree(void) { return; }
// clear the entire context tree
void ContextTree::clear(void) { return; }
void ContextTree::update(const symbol_t sym) { return; }
void ContextTree::update(const symbol_list_t &symbol_list)
{
if (symbol_list.size() == 1)
{
last_action = symbol_list[0];
}
return;
}
// updates the history statistics, without touching the context tree
void ContextTree::updateHistory(const symbol_list_t &symbol_list) { return; }
// removes the most recently observed symbol from the context tree
void ContextTree::revert(void) { return; }
// shrinks the history down to a former size
// NOTE: this method keeps the old observations and discards the most recent bits
void ContextTree::revertHistory(size_t newsize) { return; }
// generate a specified number of random symbols
// distributed according to the context tree statistics
void ContextTree::genRandomSymbols(symbol_list_t &symbols, size_t bits)
{
genRandomSymbolsAndUpdate(symbols, bits);
}
// generate a specified number of random symbols distributed according to
// the context tree statistics and update the context tree (and history) with the newly
// generated bits
void ContextTree::genRandomSymbolsAndUpdate(symbol_list_t &symbols, size_t bits)
{
//srand(time(0)); Please don't call srand here.
//In general we should call srand once in the main,
//maybe srand(time(0)) by default and provide an option
//to manually specify the seed so that
//we can reproduce the exact behaviour when testing.
if (rand01() < 0.7)
{
symbols.push_back(1);
if (last_action)
{
symbols.push_back(1);
}
else
{
symbols.push_back(0);
}
}
else
{
symbols.push_back(0);
if (last_action)
{
symbols.push_back(0);
}
else
{
symbols.push_back(1);
}
}
}
// the logarithm of the block probability of the whole sequence
double ContextTree::logBlockProbability(void) { return 0.0; }
// get the n'th most recent history symbol, NULL if doesn't exist
const symbol_t *ContextTree::nthHistorySymbol(size_t n) const { return NULL; }
| [
"xavier.orourke@gmail.com"
] | xavier.orourke@gmail.com |
7608bccbf96cc36f9fc49a0202c905a139838fec | 64058e1019497fbaf0f9cbfab9de4979d130416b | /c++/src/app/blastdb/blastdbcp.cpp | f5a5ea06f3bc8d507c65afcf25da25f36af4ed0f | [
"MIT"
] | permissive | OpenHero/gblastn | 31e52f3a49e4d898719e9229434fe42cc3daf475 | 1f931d5910150f44e8ceab81599428027703c879 | refs/heads/master | 2022-10-26T04:21:35.123871 | 2022-10-20T02:41:06 | 2022-10-20T02:41:06 | 12,407,707 | 38 | 21 | null | 2020-12-08T07:14:32 | 2013-08-27T14:06:00 | C++ | UTF-8 | C++ | false | false | 11,559 | cpp | /* $Id: blastdbcp.cpp 347262 2011-12-15 14:16:31Z fongah2 $
* ===========================================================================
*
* 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.
*
* ===========================================================================
*/
/** @file blastdbcp.cpp
* @author Christiam Camacho
*/
#include <ncbi_pch.hpp>
#include <corelib/ncbiapp.hpp>
#include <algo/blast/blastinput/cmdline_flags.hpp>
#include <objtools/blast/seqdb_writer/build_db.hpp>
USING_NCBI_SCOPE;
USING_SCOPE(blast);
/////////////////////////////////////////////////////////////////////////////
// BlastdbCopyApplication::
class BlastdbCopyApplication : public CNcbiApplication
{
public:
BlastdbCopyApplication();
private: /* Private Methods */
virtual void Init(void);
virtual int Run(void);
virtual void Exit(void);
bool x_ShouldParseSeqIds(const string& dbname,
CSeqDB::ESeqType seq_type) const;
bool x_ShouldCopyPIGs(const string& dbname,
CSeqDB::ESeqType seq_type) const;
private: /* Private Data */
bool m_bCheckOnly;
};
/////////////////////////////////////////////////////////////////////////////
// Constructor
BlastdbCopyApplication::BlastdbCopyApplication()
: m_bCheckOnly(false)
{
CRef<CVersion> version(new CVersion());
version->SetVersionInfo(1, 0);
SetFullVersion(version);
}
/////////////////////////////////////////////////////////////////////////////
// Init test for all different types of arguments
void BlastdbCopyApplication::Init(void)
{
// Create command-line argument descriptions class
auto_ptr<CArgDescriptions> arg_desc(new CArgDescriptions);
// Specify USAGE context
arg_desc->SetUsageContext(GetArguments().GetProgramBasename(),
"Performs a (deep) copy of a subset of a BLAST database");
arg_desc->SetCurrentGroup("BLAST database options");
arg_desc->AddDefaultKey(kArgDb, "dbname", "BLAST database name",
CArgDescriptions::eString, "nr");
arg_desc->AddDefaultKey(kArgDbType, "molecule_type",
"Molecule type stored in BLAST database",
CArgDescriptions::eString, "prot");
arg_desc->SetConstraint(kArgDbType, &(*new CArgAllow_Strings,
"nucl", "prot", "guess"));
arg_desc->SetCurrentGroup("Configuration options");
arg_desc->AddOptionalKey(kArgDbTitle, "database_title",
"Title for BLAST database",
CArgDescriptions::eString);
arg_desc->AddKey(kArgGiList, "input_file",
"Text or binary gi file to restrict the BLAST "
"database provided in -db argument",
CArgDescriptions::eString);
arg_desc->AddFlag("membership_bits", "Copy the membershi bits", true);
arg_desc->SetCurrentGroup("Output options");
arg_desc->AddOptionalKey(kArgOutput, "database_name",
"Name of BLAST database to be created",
CArgDescriptions::eString);
HideStdArgs(fHideConffile | fHideFullVersion | fHideXmlHelp | fHideDryRun);
SetupArgDescriptions(arg_desc.release());
}
class CBlastDbBioseqSource : public IBioseqSource
{
public:
CBlastDbBioseqSource(CRef<CSeqDBExpert> blastdb,
CRef<CSeqDBGiList> gilist,
bool copy_membership_bits = false)
{
CStopWatch total_timer, bioseq_timer, memb_timer;
total_timer.Start();
for (int i = 0; i < gilist->GetNumGis(); i++) {
const CSeqDBGiList::SGiOid& elem = gilist->GetGiOid(i);
int oid = 0;
if ( !blastdb->GiToOid(elem.gi, oid)) {
// not found on source BLASTDB, skip
continue;
}
if (m_Oids2Copy.insert(oid).second == false) {
// don't add the same OID twice to avoid duplicates
continue;
}
bioseq_timer.Start();
CConstRef<CBioseq> bs(&*blastdb->GetBioseq(oid));
m_Bioseqs.push_back(bs);
bioseq_timer.Stop();
if (copy_membership_bits == false)
continue;
memb_timer.Start();
CRef<CBlast_def_line_set> hdr = CSeqDB::ExtractBlastDefline(*bs);
ITERATE(CBlast_def_line_set::Tdata, itr, hdr->Get()) {
CRef<CBlast_def_line> bdl = *itr;
if (bdl->CanGetMemberships() &&
!bdl->GetMemberships().empty()) {
int memb_bits = bdl->GetMemberships().front();
if (memb_bits == 0) {
continue;
}
const string id = bdl->GetSeqid().front()->AsFastaString();
m_MembershipBits[memb_bits].push_back(id);
}
}
memb_timer.Stop();
}
total_timer.Stop();
ERR_POST(Info << "Will extract " << m_Bioseqs.size()
<< " sequences from the source database");
ERR_POST(Info << "Processed all input data in " << total_timer.AsSmartString());
ERR_POST(Info << "Processed bioseqs in " << bioseq_timer.AsSmartString());
ERR_POST(Info << "Processed membership bits in " << memb_timer.AsSmartString());
}
const TLinkoutMap GetMembershipBits() const {
return m_MembershipBits;
}
virtual CConstRef<CBioseq> GetNext()
{
if (m_Bioseqs.empty()) {
return CConstRef<CBioseq>(0);
}
CConstRef<CBioseq> retval = m_Bioseqs.back();
m_Bioseqs.pop_back();
return retval;
}
private:
typedef list< CConstRef<CBioseq> > TBioseqs;
TBioseqs m_Bioseqs;
set<int> m_Oids2Copy;
TLinkoutMap m_MembershipBits;
};
bool BlastdbCopyApplication::x_ShouldParseSeqIds(const string& dbname,
CSeqDB::ESeqType seq_type) const
{
vector<string> file_paths;
CSeqDB::FindVolumePaths(dbname, seq_type, file_paths);
const char type = (seq_type == CSeqDB::eProtein ? 'p' : 'n');
bool retval = false;
const char* isam_extensions[] = { "si", "sd", "ni", "nd", NULL };
ITERATE(vector<string>, f, file_paths) {
for (int i = 0; isam_extensions[i] != NULL; i++) {
CNcbiOstrstream oss;
oss << *f << "." << type << isam_extensions[i];
const string fname = CNcbiOstrstreamToString(oss);
CFile file(fname);
if (file.Exists() && file.GetLength() > 0) {
retval = true;
break;
}
}
if (retval) break;
}
return retval;
}
bool BlastdbCopyApplication::x_ShouldCopyPIGs(const string& dbname,
CSeqDB::ESeqType seq_type) const
{
if(CSeqDB::eProtein != seq_type)
return false;
vector<string> file_paths;
CSeqDB::FindVolumePaths(dbname, CSeqDB::eProtein, file_paths);
ITERATE(vector<string>, f, file_paths) {
CNcbiOstrstream oss;
oss << *f << "." << "ppd";
const string fname = CNcbiOstrstreamToString(oss);
CFile file(fname);
if (file.Exists() && file.GetLength() > 0)
return true;
}
return false;
}
/////////////////////////////////////////////////////////////////////////////
// Run the program
int BlastdbCopyApplication::Run(void)
{
int retval = 0;
const CArgs& args = GetArgs();
// Setup Logging
if (args["logfile"]) {
SetDiagPostLevel(eDiag_Info);
SetDiagPostFlag(eDPF_All);
time_t now = time(0);
LOG_POST( Info << string(72,'-') << "\n" << "NEW LOG - " << ctime(&now) );
}
CSeqDB::ESeqType seq_type = CSeqDB::eUnknown;
try {{
seq_type = ParseMoleculeTypeString(args[kArgDbType].AsString());
CRef<CSeqDBGiList> gilist(new CSeqDBFileGiList(args[kArgGiList].AsString()));
CRef<CSeqDBExpert> sourcedb(new CSeqDBExpert(args[kArgDb].AsString(), seq_type));
string title;
if (args[kArgDbTitle].HasValue()) {
title = args[kArgDbTitle].AsString();
} else {
CNcbiOstrstream oss;
oss << "Copy of '" << sourcedb->GetDBNameList() << "': " << sourcedb->GetTitle();
title = CNcbiOstrstreamToString(oss);
}
const bool kCopyPIGs = x_ShouldCopyPIGs(args[kArgDb].AsString(),
seq_type);
CBlastDbBioseqSource bioseq_source(sourcedb, gilist,
args["membership_bits"]);
const bool kIsSparse = false;
const bool kParseSeqids = x_ShouldParseSeqIds(args[kArgDb].AsString(),
seq_type);
const bool kUseGiMask = false;
CStopWatch timer;
timer.Start();
CBuildDatabase destdb(args[kArgOutput].AsString(), title,
static_cast<bool>(seq_type == CSeqDB::eProtein),
kIsSparse, kParseSeqids, kUseGiMask,
&(args["logfile"].HasValue()
? args["logfile"].AsOutputFile() : cerr));
destdb.SetUseRemote(false);
//destdb.SetVerbosity(true);
destdb.SetSourceDb(sourcedb);
destdb.StartBuild();
destdb.SetMembBits(bioseq_source.GetMembershipBits(), false);
destdb.AddSequences(bioseq_source, kCopyPIGs);
destdb.EndBuild();
timer.Stop();
ERR_POST(Info << "Created BLAST database in " << timer.AsSmartString());
}}
catch (const CException& ex) {
LOG_POST( Error << ex );
DeleteBlastDb(args[kArgOutput].AsString(), seq_type);
retval = -1;
}
catch (...) {
LOG_POST( Error << "Unknown error in BlastdbCopyApplication::Run()" );
DeleteBlastDb(args[kArgOutput].AsString(), seq_type);
retval = -2;
}
return retval;
}
/////////////////////////////////////////////////////////////////////////////
// Cleanup
void BlastdbCopyApplication::Exit(void)
{
SetDiagStream(0);
}
/////////////////////////////////////////////////////////////////////////////
// MAIN
int main(int argc, const char* argv[])
{
// Execute main application function
return BlastdbCopyApplication().AppMain(argc, argv, 0, eDS_Default, 0);
}
| [
"zhao.kaiyong@gmail.com"
] | zhao.kaiyong@gmail.com |
bdc964416783c8d74b581f21943c873fb97c6434 | 1a0c8311f35111b275b7fa32db7581b8c9915211 | /soundGEN/classes/sndanalyzer.h | 8d23ca073a50d14c60257ddf24dd1daefdae9c79 | [] | no_license | deus-amd/Sgen | 485ffcafafeb992a5d40d07bfcda352790189c67 | f7223bef1d7a85de64d50eb6436d9ba20dce923d | refs/heads/master | 2020-12-13T21:52:11.541195 | 2014-10-26T10:57:29 | 2014-10-26T10:57:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,378 | h | #ifndef SNDANALYZER_H
#define SNDANALYZER_H
#include <math.h>
#include <QVector>
#include <qDebug>
#include "../abstractsndcontroller.h"
#include "../kiss_fft/kiss_fftr.h"
#include "../kiss_fft/_kiss_fft_guts.h"
struct HarmonicInfo {
double freq;
double amp;
};
class SndAnalyzer
{
public:
SndAnalyzer();
~SndAnalyzer();
void function_fft_top_only(GenSoundFunction fct, PlaySoundFunction pfct, double t1, double t2, double freq, unsigned int points);
void function_fft_base(GenSoundFunction fct, PlaySoundFunction pfct, double t1, double t2, double freq, unsigned int points);
double getInstFrequency();
double getInstAmp();
unsigned int getTop_harmonic() const;
void setTop_harmonic(unsigned int value);
bool getSkip_zero_frequency() const;
void setSkip_zero_frequency(bool value);
QVector<HarmonicInfo>* getHarmonics();
void clearHarmonics();
QVector<HarmonicInfo> *getTopHarmonics();
void clearTopHarmonics();
double getAmp_filter() const;
void setAmp_filter(double value);
private:
double result_freq, result_amp;
double amp_filter;
bool skip_zero_frequency;
unsigned int top_harmonic;
QVector<HarmonicInfo>* harmonics;
QVector<HarmonicInfo>* top_harmonics;
void function_fft_calc_top(kiss_fft_cpx* cout, unsigned int points, double timelen);
};
#endif // SNDANALYZER_H
| [
"posedelov@rusoft.ru"
] | posedelov@rusoft.ru |
046cb79e430eaa717be3e074028817a2f461d1da | 2e619c8e2b667640989c6703a39fde3e4485679b | /2. Leetcode/easy level/375. kth distinct string in an array.cpp | cd700c6c1ae7fccaa9c2507efebfc0ecec2a6ede | [] | no_license | satyampandey9811/competitive-programming | 76957cde72ba217894ba18370f6489d7c481ba55 | 8ca1e2608f5d221f4be87529052c8eb3b0713386 | refs/heads/master | 2022-10-14T11:13:16.704203 | 2022-09-20T18:24:09 | 2022-09-20T18:24:09 | 203,355,790 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 503 | cpp | // link to question - https://leetcode.com/problems/kth-distinct-string-in-an-array/
class Solution {
public:
string kthDistinct(vector<string>& a, int k) {
map<string, int> m;
int n = a.size(), ct = 0;
for(int i = 0; i < n; i++) {
m[a[i]]++;
}
for(int i = 0; i < n; i++) {
if(m[a[i]] == 1) {
ct++;
if(ct == k) return a[i];
}
}
return "";
}
}; | [
"satyampandey9811@gmail.com"
] | satyampandey9811@gmail.com |
dc22d51a8bf9cc33337873826a0a7a7cf3e4a0dd | 14a925dcf097319834778c8b3010a7c786748199 | /include/parser_utils.h | df50293d5110452d1322419273f70e441d6bc2f6 | [
"MIT"
] | permissive | toaderandrei/cppnd-udacity-system-monitor | a410a194633dc0d786281df653a5ab08e7ded228 | 011f95e63452a7a7f7d0821c0131186a871a1ee9 | refs/heads/master | 2022-04-20T07:51:50.943096 | 2020-04-18T12:45:13 | 2020-04-18T12:45:13 | 256,291,666 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,429 | h | //
// Created by toaderst on 08-03-20.
//
#ifndef MONITOR_PARSER_UTILS_H
#define MONITOR_PARSER_UTILS_H
#include <fstream>
#include <iostream>
#include <sstream>
namespace ParserUtils {
inline void CloseStream(std::ifstream *stream) {
if (stream != NULL && stream->is_open()) {
stream->close();
}
}
template <typename T>
T GetValueByKey(const std::string &directory, const std::string &filename,
const std::string &filter) {
std::string key, line;
T value;
std::ifstream stream(directory + filename);
if (stream.is_open()) {
while (getline(stream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == filter) {
return value;
}
}
}
}
CloseStream(&stream);
return value;
}
template <typename T>
T GetFirstValueByKey(const std::string &directory, const std::string &filename,
const size_t &total_characters = 40) {
std::string key, line;
T value;
std::ifstream stream(directory + filename);
if (stream.is_open()) {
if (getline(stream, line)) {
std::istringstream linestream(line);
linestream >> key;
if (key.size() > total_characters) {
key.resize(total_characters);
key = key + "...";
}
return key;
}
}
CloseStream(&stream);
return value;
}
} // namespace ParserUtils
#endif // MONITOR_PARSER_UTILS_H
| [
"andrei.toader-stanescu@tomtom.com"
] | andrei.toader-stanescu@tomtom.com |
f1023d10c90caacf68b692d37b47e5600b6ecd43 | da8d1b8255feb551e9dc36853cd680da113791a4 | /include/AvbApi_FunctionList.hpp | 4f5c29c51c3fa26e73e267ad0dab1363a7506096 | [
"BSD-2-Clause"
] | permissive | jdkoftinoff/jdksavbapi | a577285fde064d7be0de8d78bddcf2ac18a89128 | 431ee094ed22d05fc5ec7bc0b91f216e33466aae | refs/heads/master | 2020-05-18T17:23:21.335287 | 2014-10-07T20:57:39 | 2014-10-07T20:57:39 | 24,826,923 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,186 | hpp | #pragma once
/*
Copyright (c) 2014, Jeff Koftinoff
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "AvbApi_world.hpp"
namespace AvbApi2014
{
typedef uint32_t FunctionId;
class FunctionListBase
{
public:
FunctionId nextId() { return m_nextFunctionId++; }
virtual void remove( FunctionId fid ) = 0;
private:
std::atomic<FunctionId> m_nextFunctionId;
};
template <typename F>
class FunctionList : public FunctionListBase
{
public:
using function_type = std::function<F>;
using item_type = pair<FunctionId, function_type>;
template <typename... Args>
void operator()( Args... args ) const
{
for ( auto &i : m_functions )
{
i.second( args... );
}
}
FunctionId add( function_type f )
{
FunctionId fid = nextId();
m_functions.emplace_back( make_pair( fid, f ) );
return fid;
}
virtual void remove( FunctionId fid )
{
m_functions.erase( std::remove_if( m_functions.begin(),
m_functions.end(),
[&]( item_type const &item )
{
return item.first == fid;
} ),
m_functions.end() );
}
std::vector<item_type> m_functions;
class Registrar
{
public:
Registrar( FunctionList &functionList, function_type func )
: m_functionList( functionList ), m_fid( m_functionList.add( func ) )
{
}
~Registrar() { m_functionList.remove( m_fid ); }
FunctionList &m_functionList;
FunctionId m_fid;
};
};
template <typename FunctionListT>
auto registerFunction( FunctionListT &functionList, typename FunctionListT::function_type func )
-> typename FunctionListT::Registrar
{
return typename FunctionListT::Registrar( functionList, func );
}
}
| [
"jeffk@jdkoftinoff.com"
] | jeffk@jdkoftinoff.com |
2680efc3a2611a45fe87974c975071e244ad8eb4 | fd47ed69443b69ff56316cbc81131782f5c460a5 | /LogitechLcdWinamp/gen_lglcd/DrawableText.h | 6f0dcde0a06706344cd139863a2f473d65d560b8 | [] | no_license | koson/jawsper-projects | 820b436f89415e2de3176168c489447d1f26bb34 | d750c293ad33b568d304d27d81ed61d02a1ac1ae | refs/heads/master | 2021-01-18T05:54:34.359533 | 2013-01-31T15:35:41 | 2013-01-31T15:35:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 477 | h | #pragma once
#include "Fonts.h"
class DrawableText
{
bool m_Changed;
int m_X, m_Y, m_Width, m_MaxWidth;
wchar_t m_Str[MAX_PATH];
Font* m_Font;
int prev_len;
public:
DrawableText(int a_X, int a_Y, int a_Width, Font* a_Font ) :
m_X(a_X), m_Y(a_Y), m_Width(a_Width), m_MaxWidth(a_Width), m_Changed(false), m_Font(a_Font)
{ wcscpy_s( m_Str, MAX_PATH, L"" ); prev_len = -1; }
void SetText( const wchar_t* a_Str );
bool Draw( Surface* a_Surface );
}; | [
"jawsper@gmail.com@aa725750-22df-18b2-2580-202d682e9b9e"
] | jawsper@gmail.com@aa725750-22df-18b2-2580-202d682e9b9e |
260a83d7146c1912a69ffd7f2ab4d546607d46c9 | 485faf9d4ec7def9a505149c6a491d6133e68750 | /include/wxviz/VizRender.H | 2112f6859a0b7ce0eca1192d40ed39db9b00bc5e | [
"LicenseRef-scancode-warranty-disclaimer",
"ECL-2.0"
] | permissive | ohlincha/ECCE | af02101d161bae7e9b05dc7fe6b10ca07f479c6b | 7461559888d829338f29ce5fcdaf9e1816042bfe | refs/heads/master | 2020-06-25T20:59:27.882036 | 2017-06-16T10:45:21 | 2017-06-16T10:45:21 | 94,240,259 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,547 | h | /**
* @file
*
*/
#ifndef VIZRENDER_H_
#define VIZRENDER_H_
#include <string>
using std::string;
class ChemistryTask;
class SbViewportRegion;
class SoNode;
class SoOffscreenRenderer;
class SGContainer;
class SGViewer;
class SFile;
class VizRender
{
public:
static bool thumbnail(const string& urlstr, int width = 64, int height = 64,
double r = 0.0, double g = 0.0, double b = 0.0);
static bool thumbnail(SoNode *root, ChemistryTask *task,
int width = 64, int height = 64,
double r = 0.0, double g = 0.0, double b = 0.0);
static bool file(SoNode *root, SFile *file, string type = "RGB",
int width = 64, int height = 64,
double r = 0.0, double g = 0.0, double b = 0.0);
static string msg();
protected:
static void loadAtomColors(SGContainer *sg);
static void loadAtomRadii(SGContainer *sg);
static void loadDisplayStyle(SGViewer *viewer, SGContainer *sg);
private:
// For making a movie, you run out of X
// connections if the render area isn't static. In my testing, I
// ran out on about the 70th invocation even though I was
// deleting the object! But if we just have one static, the user
// can't change width/height.
static SbViewportRegion *p_viewport;
static SoOffscreenRenderer *p_renderer;
static string p_msg;
static int p_oldWidth;
static int p_oldHeight;
};
#endif // VIZRENDER_H_
| [
"andre.ohlin@umu.se"
] | andre.ohlin@umu.se |
e2601ab2802eef6f7c83cb1ea5c9f695bdaf69a5 | c7ec870ad42a8ef1b4721e83f636d4533717d8a6 | /src/wallet/wallet.cpp | 0888d381cd941f60083d85980fe08eedb3ca5386 | [
"MIT"
] | permissive | TheRinger/Atlascoin | dcdab93e74e151d62e1efc8f4bb35f3e7b2d72ac | 21f6f2372e841fd3ba89e91086cbd5add3e4ef9b | refs/heads/master | 2020-04-06T22:16:48.957176 | 2018-11-16T07:43:21 | 2018-11-16T07:43:21 | 157,830,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 177,444 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2016 The Bitcoin Core developers
// Copyright (c) 2017 The Atlas Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "wallet/wallet.h"
#include "base58.h"
#include "checkpoints.h"
#include "chain.h"
#include "wallet/coincontrol.h"
#include "consensus/consensus.h"
#include "consensus/validation.h"
#include "fs.h"
#include "init.h"
#include "key.h"
#include "keystore.h"
#include "validation.h"
#include "net.h"
#include "policy/fees.h"
#include "policy/policy.h"
#include "policy/rbf.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "script/sign.h"
#include "scheduler.h"
#include "timedata.h"
#include "txmempool.h"
#include "util.h"
#include "ui_interface.h"
#include "utilmoneystr.h"
#include "wallet/fees.h"
#include <assert.h>
#include <boost/algorithm/string/replace.hpp>
#include <boost/thread.hpp>
#include <tinyformat.h>
#include "assets/assets.h"
std::vector<CWalletRef> vpwallets;
/** Transaction fee set by the user */
CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
bool bSpendZeroConfChange = DEFAULT_SPEND_ZEROCONF_CHANGE;
bool fWalletRbf = DEFAULT_WALLET_RBF;
const char * DEFAULT_WALLET_DAT = "wallet.dat";
const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
/**
* Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
* Override with -mintxfee
*/
CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
/**
* If fee estimation does not have enough data to provide estimates, use this fee instead.
* Has no effect if not using fee estimation
* Override with -fallbackfee
*/
CFeeRate CWallet::fallbackFee = CFeeRate(DEFAULT_FALLBACK_FEE);
CFeeRate CWallet::m_discard_rate = CFeeRate(DEFAULT_DISCARD_FEE);
const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
/** @defgroup mapWallet
*
* @{
*/
struct CompareValueOnly
{
bool operator()(const CInputCoin& t1,
const CInputCoin& t2) const
{
return t1.txout.nValue < t2.txout.nValue;
}
};
struct CompareAssetValueOnly
{
bool operator()(const std::pair<CInputCoin, CAmount>& t1,
const std::pair<CInputCoin, CAmount>& t2) const
{
return t1.second < t2.second;
}
};
std::string COutput::ToString() const
{
return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
}
class CAffectedKeysVisitor : public boost::static_visitor<void> {
private:
const CKeyStore &keystore;
std::vector<CKeyID> &vKeys;
public:
CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
void Process(const CScript &script) {
txnouttype type;
std::vector<CTxDestination> vDest;
int nRequired;
if (ExtractDestinations(script, type, vDest, nRequired)) {
for (const CTxDestination &dest : vDest)
boost::apply_visitor(*this, dest);
}
}
void operator()(const CKeyID &keyId) {
if (keystore.HaveKey(keyId))
vKeys.push_back(keyId);
}
void operator()(const CScriptID &scriptId) {
CScript script;
if (keystore.GetCScript(scriptId, script))
Process(script);
}
void operator()(const CNoDestination &none) {}
};
const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
if (it == mapWallet.end())
return nullptr;
return &(it->second);
}
CPubKey CWallet::GenerateNewKey(CWalletDB &walletdb, bool internal)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
CKey secret;
// Create new metadata
int64_t nCreationTime = GetTime();
CKeyMetadata metadata(nCreationTime);
// use HD key derivation if HD was enabled during wallet creation
if (IsHDEnabled()) {
DeriveNewChildKey(walletdb, metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
} else {
secret.MakeNewKey(fCompressed);
}
// Compressed public keys were introduced in version 0.6.0
if (fCompressed) {
SetMinVersion(FEATURE_COMPRPUBKEY);
}
CPubKey pubkey = secret.GetPubKey();
assert(secret.VerifyPubKey(pubkey));
mapKeyMetadata[pubkey.GetID()] = metadata;
UpdateTimeFirstKey(nCreationTime);
if (!AddKeyPubKeyWithDB(walletdb, secret, pubkey)) {
throw std::runtime_error(std::string(__func__) + ": AddKey failed");
}
return pubkey;
}
void CWallet::DeriveNewChildKey(CWalletDB &walletdb, CKeyMetadata& metadata, CKey& secret, bool internal)
{
// for now we use a fixed keypath scheme of m/0'/0'/k
CKey seed; //seed (256bit)
CExtKey masterKey; //hd master key
CExtKey accountKey; //key at m/0'
CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
CExtKey childKey; //key at m/0'/0'/<n>'
// try to get the seed
if (!GetKey(hdChain.seed_id, seed))
throw std::runtime_error(std::string(__func__) + ": seed not found");
masterKey.SetSeed(seed.begin(), seed.size());
// derive m/0'
// use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
// derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
assert(internal ? CanSupportFeature(FEATURE_HD_SPLIT) : true);
accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
// derive child key at next index, skip keys already known to the wallet
do {
// always derive hardened keys
// childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
// example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
if (internal) {
chainChildKey.Derive(childKey, hdChain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
metadata.hdKeypath = "m/0'/1'/" + std::to_string(hdChain.nInternalChainCounter) + "'";
hdChain.nInternalChainCounter++;
}
else {
chainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
metadata.hdKeypath = "m/0'/0'/" + std::to_string(hdChain.nExternalChainCounter) + "'";
hdChain.nExternalChainCounter++;
}
} while (HaveKey(childKey.key.GetPubKey().GetID()));
secret = childKey.key;
metadata.hd_seed_id = hdChain.seed_id;
// update the chain model in the database
if (!walletdb.WriteHDChain(hdChain))
throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
}
bool CWallet::AddKeyPubKeyWithDB(CWalletDB &walletdb, const CKey& secret, const CPubKey &pubkey)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
// CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey
// which is overridden below. To avoid flushes, the database handle is
// tunneled through to it.
bool needsDB = !pwalletdbEncryption;
if (needsDB) {
pwalletdbEncryption = &walletdb;
}
if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) {
if (needsDB) pwalletdbEncryption = nullptr;
return false;
}
if (needsDB) pwalletdbEncryption = nullptr;
// check if we need to remove from watch-only
CScript script;
script = GetScriptForDestination(pubkey.GetID());
if (HaveWatchOnly(script)) {
RemoveWatchOnly(script);
}
script = GetScriptForRawPubKey(pubkey);
if (HaveWatchOnly(script)) {
RemoveWatchOnly(script);
}
if (!IsCrypted()) {
return walletdb.WriteKey(pubkey,
secret.GetPrivKey(),
mapKeyMetadata[pubkey.GetID()]);
}
return true;
}
bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
{
CWalletDB walletdb(*dbw);
return CWallet::AddKeyPubKeyWithDB(walletdb, secret, pubkey);
}
bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
const std::vector<unsigned char> &vchCryptedSecret)
{
if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
return false;
{
LOCK(cs_wallet);
if (pwalletdbEncryption)
return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
vchCryptedSecret,
mapKeyMetadata[vchPubKey.GetID()]);
else
return CWalletDB(*dbw).WriteCryptedKey(vchPubKey,
vchCryptedSecret,
mapKeyMetadata[vchPubKey.GetID()]);
}
}
bool CWallet::LoadKeyMetadata(const CTxDestination& keyID, const CKeyMetadata &meta)
{
AssertLockHeld(cs_wallet); // mapKeyMetadata
UpdateTimeFirstKey(meta.nCreateTime);
mapKeyMetadata[keyID] = meta;
return true;
}
bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
{
return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
}
/**
* Update wallet first key creation time. This should be called whenever keys
* are added to the wallet, with the oldest key creation time.
*/
void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
{
AssertLockHeld(cs_wallet);
if (nCreateTime <= 1) {
// Cannot determine birthday information, so set the wallet birthday to
// the beginning of time.
nTimeFirstKey = 1;
} else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
nTimeFirstKey = nCreateTime;
}
}
bool CWallet::AddCScript(const CScript& redeemScript)
{
if (!CCryptoKeyStore::AddCScript(redeemScript))
return false;
return CWalletDB(*dbw).WriteCScript(Hash160(redeemScript), redeemScript);
}
bool CWallet::LoadCScript(const CScript& redeemScript)
{
/* A sanity check was added in pull #3843 to avoid adding redeemScripts
* that never can be redeemed. However, old wallets may still contain
* these. Do not add them to the wallet and warn. */
if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
{
std::string strAddr = EncodeDestination(CScriptID(redeemScript));
LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
__func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
return true;
}
return CCryptoKeyStore::AddCScript(redeemScript);
}
bool CWallet::AddWatchOnly(const CScript& dest)
{
if (!CCryptoKeyStore::AddWatchOnly(dest))
return false;
const CKeyMetadata& meta = mapKeyMetadata[CScriptID(dest)];
UpdateTimeFirstKey(meta.nCreateTime);
NotifyWatchonlyChanged(true);
return CWalletDB(*dbw).WriteWatchOnly(dest, meta);
}
bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
{
mapKeyMetadata[CScriptID(dest)].nCreateTime = nCreateTime;
return AddWatchOnly(dest);
}
bool CWallet::RemoveWatchOnly(const CScript &dest)
{
AssertLockHeld(cs_wallet);
if (!CCryptoKeyStore::RemoveWatchOnly(dest))
return false;
if (!HaveWatchOnly())
NotifyWatchonlyChanged(false);
if (!CWalletDB(*dbw).EraseWatchOnly(dest))
return false;
return true;
}
bool CWallet::LoadWatchOnly(const CScript &dest)
{
return CCryptoKeyStore::AddWatchOnly(dest);
}
bool CWallet::Unlock(const SecureString& strWalletPassphrase)
{
CCrypter crypter;
CKeyingMaterial _vMasterKey;
{
LOCK(cs_wallet);
for (const MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
{
if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
continue; // try another master key
if (CCryptoKeyStore::Unlock(_vMasterKey))
return true;
}
}
return false;
}
bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
{
bool fWasLocked = IsLocked();
{
LOCK(cs_wallet);
Lock();
CCrypter crypter;
CKeyingMaterial _vMasterKey;
for (MasterKeyMap::value_type& pMasterKey : mapMasterKeys)
{
if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
return false;
if (CCryptoKeyStore::Unlock(_vMasterKey))
{
int64_t nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
if (pMasterKey.second.nDeriveIterations < 25000)
pMasterKey.second.nDeriveIterations = 25000;
LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
return false;
if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
return false;
CWalletDB(*dbw).WriteMasterKey(pMasterKey.first, pMasterKey.second);
if (fWasLocked)
Lock();
return true;
}
}
}
return false;
}
void CWallet::SetBestChain(const CBlockLocator& loc)
{
CWalletDB walletdb(*dbw);
walletdb.WriteBestBlock(loc);
}
bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
{
LOCK(cs_wallet); // nWalletVersion
if (nWalletVersion >= nVersion)
return true;
// when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
if (fExplicit && nVersion > nWalletMaxVersion)
nVersion = FEATURE_LATEST;
nWalletVersion = nVersion;
if (nVersion > nWalletMaxVersion)
nWalletMaxVersion = nVersion;
{
CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(*dbw);
if (nWalletVersion > 40000)
pwalletdb->WriteMinVersion(nWalletVersion);
if (!pwalletdbIn)
delete pwalletdb;
}
return true;
}
bool CWallet::SetMaxVersion(int nVersion)
{
LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
// cannot downgrade below current version
if (nWalletVersion > nVersion)
return false;
nWalletMaxVersion = nVersion;
return true;
}
std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
{
std::set<uint256> result;
AssertLockHeld(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
if (it == mapWallet.end())
return result;
const CWalletTx& wtx = it->second;
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
for (const CTxIn& txin : wtx.tx->vin)
{
if (mapTxSpends.count(txin.prevout) <= 1)
continue; // No conflict if zero or one spends
range = mapTxSpends.equal_range(txin.prevout);
for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
result.insert(_it->second);
}
return result;
}
bool CWallet::HasWalletSpend(const uint256& txid) const
{
AssertLockHeld(cs_wallet);
auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
return (iter != mapTxSpends.end() && iter->first.hash == txid);
}
void CWallet::Flush(bool shutdown)
{
dbw->Flush(shutdown);
}
void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
{
// We want all the wallet transactions in range to have the same metadata as
// the oldest (smallest nOrderPos).
// So: find smallest nOrderPos:
int nMinOrderPos = std::numeric_limits<int>::max();
const CWalletTx* copyFrom = nullptr;
for (TxSpends::iterator it = range.first; it != range.second; ++it)
{
const uint256& hash = it->second;
int n = mapWallet[hash].nOrderPos;
if (n < nMinOrderPos)
{
nMinOrderPos = n;
copyFrom = &mapWallet[hash];
}
}
// Now copy data from copyFrom to rest:
for (TxSpends::iterator it = range.first; it != range.second; ++it)
{
const uint256& hash = it->second;
CWalletTx* copyTo = &mapWallet[hash];
if (copyFrom == copyTo) continue;
assert(copyFrom && "Oldest wallet transaction in range assumed to have been found.");
if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
copyTo->mapValue = copyFrom->mapValue;
copyTo->vOrderForm = copyFrom->vOrderForm;
// fTimeReceivedIsTxTime not copied on purpose
// nTimeReceived not copied on purpose
copyTo->nTimeSmart = copyFrom->nTimeSmart;
copyTo->fFromMe = copyFrom->fFromMe;
copyTo->strFromAccount = copyFrom->strFromAccount;
// nOrderPos not copied on purpose
// cached members not copied on purpose
}
}
/**
* Outpoint is spent if any non-conflicted transaction
* spends it:
*/
bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
{
const COutPoint outpoint(hash, n);
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
range = mapTxSpends.equal_range(outpoint);
for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
{
const uint256& wtxid = it->second;
std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
if (mit != mapWallet.end()) {
int depth = mit->second.GetDepthInMainChain();
if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
return true; // Spent
}
}
return false;
}
void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
{
mapTxSpends.insert(std::make_pair(outpoint, wtxid));
std::pair<TxSpends::iterator, TxSpends::iterator> range;
range = mapTxSpends.equal_range(outpoint);
SyncMetaData(range);
}
void CWallet::AddToSpends(const uint256& wtxid)
{
auto it = mapWallet.find(wtxid);
assert(it != mapWallet.end());
CWalletTx& thisTx = it->second;
if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
return;
for (const CTxIn& txin : thisTx.tx->vin)
AddToSpends(txin.prevout, wtxid);
}
bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
{
if (IsCrypted())
return false;
CKeyingMaterial _vMasterKey;
_vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
CMasterKey kMasterKey;
kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
CCrypter crypter;
int64_t nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = static_cast<unsigned int>(2500000 / ((double)(GetTimeMillis() - nStartTime)));
nStartTime = GetTimeMillis();
crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + static_cast<unsigned int>(kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime)))) / 2;
if (kMasterKey.nDeriveIterations < 25000)
kMasterKey.nDeriveIterations = 25000;
LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
return false;
if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
return false;
{
LOCK(cs_wallet);
mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
assert(!pwalletdbEncryption);
pwalletdbEncryption = new CWalletDB(*dbw);
if (!pwalletdbEncryption->TxnBegin()) {
delete pwalletdbEncryption;
pwalletdbEncryption = nullptr;
return false;
}
pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
if (!EncryptKeys(_vMasterKey))
{
pwalletdbEncryption->TxnAbort();
delete pwalletdbEncryption;
// We now probably have half of our keys encrypted in memory, and half not...
// die and let the user reload the unencrypted wallet.
assert(false);
}
// Encryption was introduced in version 0.4.0
SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
if (!pwalletdbEncryption->TxnCommit()) {
delete pwalletdbEncryption;
// We now have keys encrypted in memory, but not on disk...
// die to avoid confusion and let the user reload the unencrypted wallet.
assert(false);
}
delete pwalletdbEncryption;
pwalletdbEncryption = nullptr;
Lock();
Unlock(strWalletPassphrase);
// if we are using HD, replace the HD seed with a new one
if (IsHDEnabled()) {
if (!SetHDSeed(GenerateNewSeed())) {
return false;
}
}
NewKeyPool();
Lock();
// Need to completely rewrite the wallet file; if we don't, bdb might keep
// bits of the unencrypted private key in slack space in the database file.
dbw->Rewrite();
}
NotifyStatusChanged(this);
return true;
}
DBErrors CWallet::ReorderTransactions()
{
LOCK(cs_wallet);
CWalletDB walletdb(*dbw);
// Old wallets didn't have any defined order for transactions
// Probably a bad idea to change the output of this
// First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
typedef std::multimap<int64_t, TxPair > TxItems;
TxItems txByTime;
for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
CWalletTx* wtx = &((*it).second);
txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, nullptr)));
}
std::list<CAccountingEntry> acentries;
walletdb.ListAccountCreditDebit("", acentries);
for (CAccountingEntry& entry : acentries)
{
txByTime.insert(std::make_pair(entry.nTime, TxPair(nullptr, &entry)));
}
nOrderPosNext = 0;
std::vector<int64_t> nOrderPosOffsets;
for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
CAccountingEntry *const pacentry = (*it).second.second;
int64_t& nOrderPos = (pwtx != nullptr) ? pwtx->nOrderPos : pacentry->nOrderPos;
if (nOrderPos == -1)
{
nOrderPos = nOrderPosNext++;
nOrderPosOffsets.push_back(nOrderPos);
if (pwtx)
{
if (!walletdb.WriteTx(*pwtx))
return DB_LOAD_FAIL;
}
else
if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DB_LOAD_FAIL;
}
else
{
int64_t nOrderPosOff = 0;
for (const int64_t& nOffsetStart : nOrderPosOffsets)
{
if (nOrderPos >= nOffsetStart)
++nOrderPosOff;
}
nOrderPos += nOrderPosOff;
nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
if (!nOrderPosOff)
continue;
// Since we're changing the order, write it back
if (pwtx)
{
if (!walletdb.WriteTx(*pwtx))
return DB_LOAD_FAIL;
}
else
if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
return DB_LOAD_FAIL;
}
}
walletdb.WriteOrderPosNext(nOrderPosNext);
return DB_LOAD_OK;
}
int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
{
AssertLockHeld(cs_wallet); // nOrderPosNext
int64_t nRet = nOrderPosNext++;
if (pwalletdb) {
pwalletdb->WriteOrderPosNext(nOrderPosNext);
} else {
CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
}
return nRet;
}
bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
{
CWalletDB walletdb(*dbw);
if (!walletdb.TxnBegin())
return false;
int64_t nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
AddAccountingEntry(debit, &walletdb);
// Credit
CAccountingEntry credit;
credit.nOrderPos = IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
AddAccountingEntry(credit, &walletdb);
if (!walletdb.TxnCommit())
return false;
return true;
}
bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
{
CWalletDB walletdb(*dbw);
CAccount account;
walletdb.ReadAccount(strAccount, account);
if (!bForceNew) {
if (!account.vchPubKey.IsValid())
bForceNew = true;
else {
// Check if the current key has been used
CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
it != mapWallet.end() && account.vchPubKey.IsValid();
++it)
for (const CTxOut& txout : (*it).second.tx->vout)
if (txout.scriptPubKey == scriptPubKey) {
bForceNew = true;
break;
}
}
}
// Generate a new key
if (bForceNew) {
if (!GetKeyFromPool(account.vchPubKey, false))
return false;
SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
walletdb.WriteAccount(strAccount, account);
}
pubKey = account.vchPubKey;
return true;
}
void CWallet::MarkDirty()
{
{
LOCK(cs_wallet);
for (std::pair<const uint256, CWalletTx>& item : mapWallet)
item.second.MarkDirty();
}
}
bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
{
LOCK(cs_wallet);
auto mi = mapWallet.find(originalHash);
// There is a bug if MarkReplaced is not called on an existing wallet transaction.
assert(mi != mapWallet.end());
CWalletTx& wtx = (*mi).second;
// Ensure for now that we're not overwriting data
assert(wtx.mapValue.count("replaced_by_txid") == 0);
wtx.mapValue["replaced_by_txid"] = newHash.ToString();
CWalletDB walletdb(*dbw, "r+");
bool success = true;
if (!walletdb.WriteTx(wtx)) {
LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
success = false;
}
NotifyTransactionChanged(this, originalHash, CT_UPDATED);
return success;
}
bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
{
LOCK(cs_wallet);
CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
uint256 hash = wtxIn.GetHash();
// Inserts only if not already there, returns tx inserted or tx found
std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
CWalletTx& wtx = (*ret.first).second;
wtx.BindWallet(this);
bool fInsertedNew = ret.second;
if (fInsertedNew)
{
wtx.nTimeReceived = GetAdjustedTime();
wtx.nOrderPos = IncOrderPosNext(&walletdb);
wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
wtx.nTimeSmart = ComputeTimeSmart(wtx);
AddToSpends(hash);
}
bool fUpdated = false;
if (!fInsertedNew)
{
// Merge
if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
{
wtx.hashBlock = wtxIn.hashBlock;
fUpdated = true;
}
// If no longer abandoned, update
if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
{
wtx.hashBlock = wtxIn.hashBlock;
fUpdated = true;
}
if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
{
wtx.nIndex = wtxIn.nIndex;
fUpdated = true;
}
if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
{
wtx.fFromMe = wtxIn.fFromMe;
fUpdated = true;
}
// If we have a witness-stripped version of this transaction, and we
// see a new version with a witness, then we must be upgrading a pre-segwit
// wallet. Store the new version of the transaction with the witness,
// as the stripped-version must be invalid.
// TODO: Store all versions of the transaction, instead of just one.
if (wtxIn.tx->HasWitness() && !wtx.tx->HasWitness()) {
wtx.SetTx(wtxIn.tx);
fUpdated = true;
}
}
//// debug print
LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
// Write to disk
if (fInsertedNew || fUpdated)
if (!walletdb.WriteTx(wtx))
return false;
// Break debit/credit balance caches:
wtx.MarkDirty();
// Notify UI of new or updated transaction
NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
// notify an external script when a wallet transaction comes in or is updated
std::string strCmd = gArgs.GetArg("-walletnotify", "");
if (!strCmd.empty())
{
boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
return true;
}
bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
{
uint256 hash = wtxIn.GetHash();
mapWallet[hash] = wtxIn;
CWalletTx& wtx = mapWallet[hash];
wtx.BindWallet(this);
wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, nullptr)));
AddToSpends(hash);
for (const CTxIn& txin : wtx.tx->vin) {
auto it = mapWallet.find(txin.prevout.hash);
if (it != mapWallet.end()) {
CWalletTx& prevtx = it->second;
if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
MarkConflicted(prevtx.hashBlock, wtx.GetHash());
}
}
}
return true;
}
/**
* Add a transaction to the wallet, or update it. pIndex and posInBlock should
* be set when the transaction was known to be included in a block. When
* pIndex == nullptr, then wallet state is not updated in AddToWallet, but
* notifications happen and cached balances are marked dirty.
*
* If fUpdate is true, existing transactions will be updated.
* TODO: One exception to this is that the abandoned state is cleared under the
* assumption that any further notification of a transaction that was considered
* abandoned is an indication that it is not safe to be considered abandoned.
* Abandoned state should probably be more carefully tracked via different
* posInBlock signals or by checking mempool presence when necessary.
*/
bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
{
const CTransaction& tx = *ptx;
{
AssertLockHeld(cs_wallet);
if (pIndex != nullptr) {
for (const CTxIn& txin : tx.vin) {
std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
while (range.first != range.second) {
if (range.first->second != tx.GetHash()) {
LogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), pIndex->GetBlockHash().ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
MarkConflicted(pIndex->GetBlockHash(), range.first->second);
}
range.first++;
}
}
}
bool fExisted = mapWallet.count(tx.GetHash()) != 0;
if (fExisted && !fUpdate) return false;
if (fExisted || IsMine(tx) || IsFromMe(tx))
{
/* Check if any keys in the wallet keypool that were supposed to be unused
* have appeared in a new transaction. If so, remove those keys from the keypool.
* This can happen when restoring an old wallet backup that does not contain
* the mostly recently created transactions from newer versions of the wallet.
*/
// loop though all outputs
for (const CTxOut& txout: tx.vout) {
// extract addresses and check if they match with an unused keypool key
std::vector<CKeyID> vAffected;
CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
for (const CKeyID &keyid : vAffected) {
std::map<CKeyID, int64_t>::const_iterator mi = m_pool_key_to_index.find(keyid);
if (mi != m_pool_key_to_index.end()) {
LogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__);
MarkReserveKeysAsUsed(mi->second);
if (!TopUpKeyPool()) {
LogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__);
}
}
}
}
CWalletTx wtx(this, ptx);
// Get merkle branch if transaction was found in a block
if (pIndex != nullptr)
wtx.SetMerkleBranch(pIndex, posInBlock);
return AddToWallet(wtx, false);
}
}
return false;
}
bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
{
LOCK2(cs_main, cs_wallet);
const CWalletTx* wtx = GetWalletTx(hashTx);
return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
}
bool CWallet::AbandonTransaction(const uint256& hashTx)
{
LOCK2(cs_main, cs_wallet);
CWalletDB walletdb(*dbw, "r+");
std::set<uint256> todo;
std::set<uint256> done;
// Can't mark abandoned if confirmed or in mempool
auto it = mapWallet.find(hashTx);
assert(it != mapWallet.end());
CWalletTx& origtx = it->second;
if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
return false;
}
todo.insert(hashTx);
while (!todo.empty()) {
uint256 now = *todo.begin();
todo.erase(now);
done.insert(now);
auto it = mapWallet.find(now);
assert(it != mapWallet.end());
CWalletTx& wtx = it->second;
int currentconfirm = wtx.GetDepthInMainChain();
// If the orig tx was not in block, none of its spends can be
assert(currentconfirm <= 0);
// if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
if (currentconfirm == 0 && !wtx.isAbandoned()) {
// If the orig tx was not in block/mempool, none of its spends can be in mempool
assert(!wtx.InMempool());
wtx.nIndex = -1;
wtx.setAbandoned();
wtx.MarkDirty();
walletdb.WriteTx(wtx);
NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
// Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
while (iter != mapTxSpends.end() && iter->first.hash == now) {
if (!done.count(iter->second)) {
todo.insert(iter->second);
}
iter++;
}
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be recomputed
for (const CTxIn& txin : wtx.tx->vin)
{
auto it = mapWallet.find(txin.prevout.hash);
if (it != mapWallet.end()) {
it->second.MarkDirty();
}
}
}
}
return true;
}
void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
{
LOCK2(cs_main, cs_wallet);
int conflictconfirms = 0;
if (mapBlockIndex.count(hashBlock)) {
CBlockIndex* pindex = mapBlockIndex[hashBlock];
if (chainActive.Contains(pindex)) {
conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
}
}
// If number of conflict confirms cannot be determined, this means
// that the block is still unknown or not yet part of the main chain,
// for example when loading the wallet during a reindex. Do nothing in that
// case.
if (conflictconfirms >= 0)
return;
// Do not flush the wallet here for performance reasons
CWalletDB walletdb(*dbw, "r+", false);
std::set<uint256> todo;
std::set<uint256> done;
todo.insert(hashTx);
while (!todo.empty()) {
uint256 now = *todo.begin();
todo.erase(now);
done.insert(now);
auto it = mapWallet.find(now);
assert(it != mapWallet.end());
CWalletTx& wtx = it->second;
int currentconfirm = wtx.GetDepthInMainChain();
if (conflictconfirms < currentconfirm) {
// Block is 'more conflicted' than current confirm; update.
// Mark transaction as conflicted with this block.
wtx.nIndex = -1;
wtx.hashBlock = hashBlock;
wtx.MarkDirty();
walletdb.WriteTx(wtx);
// Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
while (iter != mapTxSpends.end() && iter->first.hash == now) {
if (!done.count(iter->second)) {
todo.insert(iter->second);
}
iter++;
}
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be recomputed
for (const CTxIn& txin : wtx.tx->vin) {
auto it = mapWallet.find(txin.prevout.hash);
if (it != mapWallet.end()) {
it->second.MarkDirty();
}
}
}
}
}
void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
const CTransaction& tx = *ptx;
if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
return; // Not one of ours
// If a transaction changes 'conflicted' state, that changes the balance
// available of the outputs it spends. So force those to be
// recomputed, also:
for (const CTxIn& txin : tx.vin) {
auto it = mapWallet.find(txin.prevout.hash);
if (it != mapWallet.end()) {
it->second.MarkDirty();
}
}
}
void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
LOCK2(cs_main, cs_wallet);
SyncTransaction(ptx);
}
void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
LOCK2(cs_main, cs_wallet);
// TODO: Temporarily ensure that mempool removals are notified before
// connected transactions. This shouldn't matter, but the abandoned
// state of transactions in our wallet is currently cleared when we
// receive another notification and there is a race condition where
// notification of a connected conflict might cause an outside process
// to abandon a transaction and then have it inadvertently cleared by
// the notification that the conflicted transaction was evicted.
for (const CTransactionRef& ptx : vtxConflicted) {
SyncTransaction(ptx);
}
for (size_t i = 0; i < pblock->vtx.size(); i++) {
SyncTransaction(pblock->vtx[i], pindex, i);
}
}
void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
LOCK2(cs_main, cs_wallet);
for (const CTransactionRef& ptx : pblock->vtx) {
SyncTransaction(ptx);
}
}
isminetype CWallet::IsMine(const CTxIn &txin) const
{
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.tx->vout.size())
return IsMine(prev.tx->vout[txin.prevout.n]);
}
}
return ISMINE_NO;
}
CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const {
CAssetOutputEntry assetData;
return GetDebit(txin, filter, assetData);
}
// Note that this function doesn't distinguish between a 0-valued input,
// and a not-"is mine" (according to the filter) input.
CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter, CAssetOutputEntry& assetData) const
{
{
LOCK(cs_wallet);
std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
if (mi != mapWallet.end())
{
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n < prev.tx->vout.size())
if (IsMine(prev.tx->vout[txin.prevout.n]) & filter) {
// if asset get that assets data from the scriptPubKey
if (prev.tx->vout[txin.prevout.n].scriptPubKey.IsAssetScript())
GetAssetData(prev.tx->vout[txin.prevout.n].scriptPubKey, assetData);
return prev.tx->vout[txin.prevout.n].nValue;
}
}
}
return 0;
}
isminetype CWallet::IsMine(const CTxOut& txout) const
{
return ::IsMine(*this, txout.scriptPubKey);
}
CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
{
if (!MoneyRange(txout.nValue))
throw std::runtime_error(std::string(__func__) + ": value out of range");
return ((IsMine(txout) & filter) ? txout.nValue : 0);
}
bool CWallet::IsChange(const CTxOut& txout) const
{
// TODO: fix handling of 'change' outputs. The assumption is that any
// payment to a script that is ours, but is not in the address book
// is change. That assumption is likely to break when we implement multisignature
// wallets that return change back into a multi-signature-protected address;
// a better way of identifying which outputs are 'the send' and which are
// 'the change' will need to be implemented (maybe extend CWalletTx to remember
// which output, if any, was change).
if (::IsMine(*this, txout.scriptPubKey))
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address))
return true;
LOCK(cs_wallet);
if (!mapAddressBook.count(address))
return true;
}
return false;
}
CAmount CWallet::GetChange(const CTxOut& txout) const
{
if (!MoneyRange(txout.nValue))
throw std::runtime_error(std::string(__func__) + ": value out of range");
return (IsChange(txout) ? txout.nValue : 0);
}
bool CWallet::IsMine(const CTransaction& tx) const
{
for (const CTxOut& txout : tx.vout)
if (IsMine(txout))
return true;
return false;
}
bool CWallet::IsFromMe(const CTransaction& tx) const
{
return (GetDebit(tx, ISMINE_ALL) > 0);
}
CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
{
CAmount nDebit = 0;
for (const CTxIn& txin : tx.vin)
{
nDebit += GetDebit(txin, filter);
if (!MoneyRange(nDebit))
throw std::runtime_error(std::string(__func__) + ": value out of range");
}
return nDebit;
}
bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
{
LOCK(cs_wallet);
for (const CTxIn& txin : tx.vin)
{
auto mi = mapWallet.find(txin.prevout.hash);
if (mi == mapWallet.end())
return false; // any unknown inputs can't be from us
const CWalletTx& prev = (*mi).second;
if (txin.prevout.n >= prev.tx->vout.size())
return false; // invalid input!
if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
return false;
}
return true;
}
CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
{
CAmount nCredit = 0;
for (const CTxOut& txout : tx.vout)
{
nCredit += GetCredit(txout, filter);
if (!MoneyRange(nCredit))
throw std::runtime_error(std::string(__func__) + ": value out of range");
}
return nCredit;
}
CAmount CWallet::GetChange(const CTransaction& tx) const
{
CAmount nChange = 0;
for (const CTxOut& txout : tx.vout)
{
nChange += GetChange(txout);
if (!MoneyRange(nChange))
throw std::runtime_error(std::string(__func__) + ": value out of range");
}
return nChange;
}
CPubKey CWallet::GenerateNewSeed()
{
CKey key;
key.MakeNewKey(true);
return DeriveNewSeed(key);
}
CPubKey CWallet::DeriveNewSeed(const CKey& key)
{
int64_t nCreationTime = GetTime();
CKeyMetadata metadata(nCreationTime);
// calculate the seed
CPubKey seed = key.GetPubKey();
assert(key.VerifyPubKey(seed));
// set the hd keypath to "s" -> Seed, refers the seed to itself
metadata.hdKeypath = "s";
metadata.hd_seed_id = seed.GetID();
{
LOCK(cs_wallet);
// mem store the metadata
mapKeyMetadata[seed.GetID()] = metadata;
// write the key&metadata to the database
if (!AddKeyPubKey(key, seed))
throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
}
return seed;
}
bool CWallet::SetHDSeed(const CPubKey& seed)
{
LOCK(cs_wallet);
// store the keyid (hash160) together with
// the child index counter in the database
// as a hdchain object
CHDChain newHdChain;
newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
newHdChain.seed_id = seed.GetID();
SetHDChain(newHdChain, false);
return true;
}
bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
{
LOCK(cs_wallet);
if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
throw std::runtime_error(std::string(__func__) + ": writing chain failed");
hdChain = chain;
return true;
}
bool CWallet::IsHDEnabled() const
{
return !hdChain.seed_id.IsNull();
}
int64_t CWalletTx::GetTxTime() const
{
int64_t n = nTimeSmart;
return n ? n : nTimeReceived;
}
int CWalletTx::GetRequestCount() const
{
// Returns -1 if it wasn't being tracked
int nRequests = -1;
{
LOCK(pwallet->cs_wallet);
if (IsCoinBase())
{
// Generated block
if (!hashUnset())
{
std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
if (mi != pwallet->mapRequestCount.end())
nRequests = (*mi).second;
}
}
else
{
// Did anyone request this transaction?
std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
if (mi != pwallet->mapRequestCount.end())
{
nRequests = (*mi).second;
// How about the block it's in?
if (nRequests == 0 && !hashUnset())
{
std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
if (_mi != pwallet->mapRequestCount.end())
nRequests = (*_mi).second;
else
nRequests = 1; // If it's in someone else's block it must have got out
}
}
}
}
return nRequests;
}
void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const {
std::list<CAssetOutputEntry> assetsReceived;
std::list<CAssetOutputEntry> assetsSent;
GetAmounts(listReceived, listSent, nFee, strSentAccount, filter, assetsReceived, assetsSent);
}
void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter, std::list<CAssetOutputEntry>& assetsReceived, std::list<CAssetOutputEntry>& assetsSent) const
{
nFee = 0;
listReceived.clear();
listSent.clear();
strSentAccount = strFromAccount;
// Compute fee:
CAmount nDebit = GetDebit(filter);
if (nDebit > 0) // debit>0 means we signed/sent this transaction
{
CAmount nValueOut = tx->GetValueOut();
nFee = nDebit - nValueOut;
}
// Sent/received.
for (unsigned int i = 0; i < tx->vout.size(); ++i)
{
const CTxOut& txout = tx->vout[i];
isminetype fIsMine = pwallet->IsMine(txout);
// Only need to handle txouts if AT LEAST one of these is true:
// 1) they debit from us (sent)
// 2) the output is to us (received)
if (nDebit > 0)
{
// Don't report 'change' txouts
if (pwallet->IsChange(txout))
continue;
}
else if (!(fIsMine & filter))
continue;
// In either case, we need to get the destination address
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
{
LogPrintf("%s: Failing on the %d tx\n", __func__, i);
LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
this->GetHash().ToString());
address = CNoDestination();
}
if (!txout.scriptPubKey.IsAssetScript()) {
COutputEntry output = {address, txout.nValue, (int) i};
// If we are debited by the transaction, add the output as a "sent" entry
if (nDebit > 0)
listSent.push_back(output);
// If we are receiving the output, add it as a "received" entry
if (fIsMine & filter)
listReceived.push_back(output);
}
/** ATL START */
if (AreAssetsDeployed()) {
if (txout.scriptPubKey.IsAssetScript()) {
CAssetOutputEntry assetoutput;
assetoutput.vout = i;
GetAssetData(txout.scriptPubKey, assetoutput);
// The only asset type we send is transfer_asset. We need to skip all other types for the sent category
if (nDebit > 0 && assetoutput.type == TX_TRANSFER_ASSET)
assetsSent.emplace_back(assetoutput);
if (fIsMine & filter)
assetsReceived.emplace_back(assetoutput);
}
}
/** ATL END */
}
}
/**
* Scan active chain for relevant transactions after importing keys. This should
* be called whenever new keys are added to the wallet, with the oldest key
* creation time.
*
* @return Earliest timestamp that could be successfully scanned from. Timestamp
* returned will be higher than startTime if relevant blocks could not be read.
*/
int64_t CWallet::RescanFromTime(int64_t startTime, bool update)
{
AssertLockHeld(cs_main);
AssertLockHeld(cs_wallet);
// Find starting block. May be null if nCreateTime is greater than the
// highest blockchain timestamp, in which case there is nothing that needs
// to be scanned.
CBlockIndex* const startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW);
LogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0);
if (startBlock) {
const CBlockIndex* const failedBlock = ScanForWalletTransactions(startBlock, nullptr, update);
if (failedBlock) {
return failedBlock->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1;
}
}
return startTime;
}
/**
* Scan the block chain (starting in pindexStart) for transactions
* from or to us. If fUpdate is true, found transactions that already
* exist in the wallet will be updated.
*
* Returns null if scan was successful. Otherwise, if a complete rescan was not
* possible (due to pruning or corruption), returns pointer to the most recent
* block that could not be scanned.
*
* If pindexStop is not a nullptr, the scan will stop at the block-index
* defined by pindexStop
*/
CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, CBlockIndex* pindexStop, bool fUpdate)
{
int64_t nNow = GetTime();
const CChainParams& chainParams = Params();
if (pindexStop) {
assert(pindexStop->nHeight >= pindexStart->nHeight);
}
CBlockIndex* pindex = pindexStart;
CBlockIndex* ret = nullptr;
{
LOCK2(cs_main, cs_wallet);
fAbortRescan = false;
fScanningWallet = true;
ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
while (pindex && !fAbortRescan)
{
if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
if (GetTime() >= nNow + 60) {
nNow = GetTime();
LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
}
CBlock block;
if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
}
} else {
ret = pindex;
}
if (pindex == pindexStop) {
break;
}
pindex = chainActive.Next(pindex);
}
if (pindex && fAbortRescan) {
LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
}
ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
fScanningWallet = false;
}
return ret;
}
void CWallet::ReacceptWalletTransactions()
{
// If transactions aren't being broadcasted, don't let them into local mempool either
if (!fBroadcastTransactions)
return;
LOCK2(cs_main, cs_wallet);
std::map<int64_t, CWalletTx*> mapSorted;
// Sort pending wallet transactions based on their initial wallet insertion order
for (std::pair<const uint256, CWalletTx>& item : mapWallet)
{
const uint256& wtxid = item.first;
CWalletTx& wtx = item.second;
assert(wtx.GetHash() == wtxid);
int nDepth = wtx.GetDepthInMainChain();
if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
}
}
// Try to add wallet transactions to memory pool
for (std::pair<const int64_t, CWalletTx*>& item : mapSorted)
{
CWalletTx& wtx = *(item.second);
LOCK(mempool.cs);
CValidationState state;
wtx.AcceptToMemoryPool(maxTxFee, state);
}
}
bool CWalletTx::RelayWalletTransaction(CConnman* connman)
{
assert(pwallet->GetBroadcastTransactions());
if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
{
/* GetDepthInMainChain already catches known conflicts. */
CValidationState state;
if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
LogPrintf("Relaying wtx %s\n", GetHash().ToString());
if (connman) {
CInv inv(MSG_TX, GetHash());
connman->ForEachNode([&inv](CNode* pnode)
{
pnode->PushInventory(inv);
});
return true;
}
}
}
return false;
}
std::set<uint256> CWalletTx::GetConflicts() const
{
std::set<uint256> result;
if (pwallet != nullptr)
{
uint256 myHash = GetHash();
result = pwallet->GetConflicts(myHash);
result.erase(myHash);
}
return result;
}
CAmount CWalletTx::GetDebit(const isminefilter& filter) const
{
if (tx->vin.empty())
return 0;
CAmount debit = 0;
if(filter & ISMINE_SPENDABLE)
{
if (fDebitCached)
debit += nDebitCached;
else
{
nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
fDebitCached = true;
debit += nDebitCached;
}
}
if(filter & ISMINE_WATCH_ONLY)
{
if(fWatchDebitCached)
debit += nWatchDebitCached;
else
{
nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
fWatchDebitCached = true;
debit += nWatchDebitCached;
}
}
return debit;
}
CAmount CWalletTx::GetCredit(const isminefilter& filter) const
{
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
CAmount credit = 0;
if (filter & ISMINE_SPENDABLE)
{
// GetBalance can assume transactions in mapWallet won't change
if (fCreditCached)
credit += nCreditCached;
else
{
nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
fCreditCached = true;
credit += nCreditCached;
}
}
if (filter & ISMINE_WATCH_ONLY)
{
if (fWatchCreditCached)
credit += nWatchCreditCached;
else
{
nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
fWatchCreditCached = true;
credit += nWatchCreditCached;
}
}
return credit;
}
CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
{
if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
{
if (fUseCache && fImmatureCreditCached)
return nImmatureCreditCached;
nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
fImmatureCreditCached = true;
return nImmatureCreditCached;
}
return 0;
}
CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
{
if (pwallet == nullptr)
return 0;
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
if (fUseCache && fAvailableCreditCached)
return nAvailableCreditCached;
CAmount nCredit = 0;
uint256 hashTx = GetHash();
for (unsigned int i = 0; i < tx->vout.size(); i++)
{
if (!pwallet->IsSpent(hashTx, i))
{
const CTxOut &txout = tx->vout[i];
nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
if (!MoneyRange(nCredit))
throw std::runtime_error(std::string(__func__) + " : value out of range");
}
}
nAvailableCreditCached = nCredit;
fAvailableCreditCached = true;
return nCredit;
}
CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
{
if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
{
if (fUseCache && fImmatureWatchCreditCached)
return nImmatureWatchCreditCached;
nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
fImmatureWatchCreditCached = true;
return nImmatureWatchCreditCached;
}
return 0;
}
CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
{
if (pwallet == nullptr)
return 0;
// Must wait until coinbase is safely deep enough in the chain before valuing it
if (IsCoinBase() && GetBlocksToMaturity() > 0)
return 0;
if (fUseCache && fAvailableWatchCreditCached)
return nAvailableWatchCreditCached;
CAmount nCredit = 0;
for (unsigned int i = 0; i < tx->vout.size(); i++)
{
if (!pwallet->IsSpent(GetHash(), i))
{
const CTxOut &txout = tx->vout[i];
nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
if (!MoneyRange(nCredit))
throw std::runtime_error(std::string(__func__) + ": value out of range");
}
}
nAvailableWatchCreditCached = nCredit;
fAvailableWatchCreditCached = true;
return nCredit;
}
CAmount CWalletTx::GetChange() const
{
if (fChangeCached)
return nChangeCached;
nChangeCached = pwallet->GetChange(*this);
fChangeCached = true;
return nChangeCached;
}
bool CWalletTx::InMempool() const
{
LOCK(mempool.cs);
return mempool.exists(GetHash());
}
bool CWalletTx::IsTrusted() const
{
// Quick answer in most cases
if (!CheckFinalTx(*this))
return false;
int nDepth = GetDepthInMainChain();
if (nDepth >= 1)
return true;
if (nDepth < 0)
return false;
if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
return false;
// Don't trust unconfirmed transactions from us unless they are in the mempool.
if (!InMempool())
return false;
// Trusted if all inputs are from us and are in the mempool:
for (const CTxIn& txin : tx->vin)
{
// Transactions not sent by us: not trusted
const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
if (parent == nullptr)
return false;
const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
return false;
}
return true;
}
bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
{
CMutableTransaction tx1 = *this->tx;
CMutableTransaction tx2 = *_tx.tx;
for (auto& txin : tx1.vin) txin.scriptSig = CScript();
for (auto& txin : tx2.vin) txin.scriptSig = CScript();
return CTransaction(tx1) == CTransaction(tx2);
}
std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
{
std::vector<uint256> result;
LOCK(cs_wallet);
// Sort them in chronological order
std::multimap<unsigned int, CWalletTx*> mapSorted;
for (std::pair<const uint256, CWalletTx>& item : mapWallet)
{
CWalletTx& wtx = item.second;
// Don't rebroadcast if newer than nTime:
if (wtx.nTimeReceived > nTime)
continue;
mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
}
for (std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
{
CWalletTx& wtx = *item.second;
if (wtx.RelayWalletTransaction(connman))
result.push_back(wtx.GetHash());
}
return result;
}
void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
{
// Do this infrequently and randomly to avoid giving away
// that these are our transactions.
if (GetTime() < nNextResend || !fBroadcastTransactions)
return;
bool fFirst = (nNextResend == 0);
nNextResend = GetTime() + GetRand(30 * 60);
if (fFirst)
return;
// Only do it if there's been a new block since last time
if (nBestBlockTime < nLastResend)
return;
nLastResend = GetTime();
// Rebroadcast unconfirmed txes older than 5 minutes before the last
// block was found:
std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
if (!relayed.empty())
LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
}
/** @} */ // end of mapWallet
/** @defgroup Actions
*
* @{
*/
CAmount CWallet::GetBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted())
nTotal += pcoin->GetAvailableCredit();
}
}
return nTotal;
}
CAmount CWallet::GetUnconfirmedBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
nTotal += pcoin->GetAvailableCredit();
}
}
return nTotal;
}
CAmount CWallet::GetImmatureBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
nTotal += pcoin->GetImmatureCredit();
}
}
return nTotal;
}
CAmount CWallet::GetWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (pcoin->IsTrusted())
nTotal += pcoin->GetAvailableWatchOnlyCredit();
}
}
return nTotal;
}
CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
nTotal += pcoin->GetAvailableWatchOnlyCredit();
}
}
return nTotal;
}
CAmount CWallet::GetImmatureWatchOnlyBalance() const
{
CAmount nTotal = 0;
{
LOCK2(cs_main, cs_wallet);
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
{
const CWalletTx* pcoin = &(*it).second;
nTotal += pcoin->GetImmatureWatchOnlyCredit();
}
}
return nTotal;
}
// Calculate total balance in a different way from GetBalance. The biggest
// difference is that GetBalance sums up all unspent TxOuts paying to the
// wallet, while this sums up both spent and unspent TxOuts paying to the
// wallet, and then subtracts the values of TxIns spending from the wallet. This
// also has fewer restrictions on which unconfirmed transactions are considered
// trusted.
CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
{
LOCK2(cs_main, cs_wallet);
CAmount balance = 0;
for (const auto& entry : mapWallet) {
const CWalletTx& wtx = entry.second;
const int depth = wtx.GetDepthInMainChain();
if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
continue;
}
// Loop through tx outputs and add incoming payments. For outgoing txs,
// treat change outputs specially, as part of the amount debited.
CAmount debit = wtx.GetDebit(filter);
const bool outgoing = debit > 0;
for (const CTxOut& out : wtx.tx->vout) {
if (outgoing && IsChange(out)) {
debit -= out.nValue;
} else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
balance += out.nValue;
}
}
// For outgoing txs, subtract amount debited.
if (outgoing && (!account || *account == wtx.strFromAccount)) {
balance -= debit;
}
}
if (account) {
balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
}
return balance;
}
CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
{
LOCK2(cs_main, cs_wallet);
CAmount balance = 0;
std::vector<COutput> vCoins;
AvailableCoins(vCoins, true, coinControl);
for (const COutput& out : vCoins) {
if (out.fSpendable) {
balance += out.tx->tx->vout[out.i].nValue;
}
}
return balance;
}
void CWallet::AvailableCoins(std::vector<COutput> &vCoins, bool fOnlySafe, const CCoinControl *coinControl, const CAmount &nMinimumAmount, const CAmount &nMaximumAmount, const CAmount &nMinimumSumAmount, const uint64_t &nMaximumCount, const int &nMinDepth, const int &nMaxDepth) const
{
std::map<std::string, std::vector<COutput> > mapAssetCoins;
AvailableCoinsAll(vCoins, mapAssetCoins, true, false, fOnlySafe, coinControl, nMinimumAmount, nMaximumAmount, nMinimumSumAmount, nMaximumCount, nMinDepth, nMaxDepth);
}
void CWallet::AvailableAssets(std::map<std::string, std::vector<COutput> > &mapAssetCoins, bool fOnlySafe,
const CCoinControl *coinControl, const CAmount &nMinimumAmount,
const CAmount &nMaximumAmount, const CAmount &nMinimumSumAmount,
const uint64_t &nMaximumCount, const int &nMinDepth, const int &nMaxDepth) const
{
if (!AreAssetsDeployed())
return;
std::vector<COutput> vCoins;
AvailableCoinsAll(vCoins, mapAssetCoins, false, true, fOnlySafe, coinControl, nMinimumAmount, nMaximumAmount, nMinimumSumAmount, nMaximumCount, nMinDepth, nMaxDepth);
}
void CWallet::AvailableCoinsWithAssets(std::vector<COutput> &vCoins, std::map<std::string, std::vector<COutput> > &mapAssetCoins,
bool fOnlySafe, const CCoinControl *coinControl, const CAmount &nMinimumAmount,
const CAmount &nMaximumAmount, const CAmount &nMinimumSumAmount,
const uint64_t &nMaximumCount, const int &nMinDepth, const int &nMaxDepth) const
{
AvailableCoinsAll(vCoins, mapAssetCoins, true, AreAssetsDeployed(), fOnlySafe, coinControl, nMinimumAmount, nMaximumAmount, nMinimumSumAmount, nMaximumCount, nMinDepth, nMaxDepth);
}
void CWallet::AvailableCoinsAll(std::vector<COutput>& vCoins, std::map<std::string, std::vector<COutput> >& mapAssetCoins, bool fGetATL, bool fGetAssets, bool fOnlySafe, const CCoinControl *coinControl, const CAmount& nMinimumAmount, const CAmount& nMaximumAmount, const CAmount& nMinimumSumAmount, const uint64_t& nMaximumCount, const int& nMinDepth, const int& nMaxDepth) const {
vCoins.clear();
{
LOCK2(cs_main, cs_wallet);
CAmount nTotal = 0;
/** ATL START */
bool fATLLimitHit = false;
// A set of the hashes that have already been used
std::set<uint256> usedMempoolHashes;
std::map<std::string, CAmount> mapAssetTotals;
std::map<uint256, COutPoint> mapOutPoints;
std::set<std::string> setAssetMaxFound;
// Turn the OutPoints into a map that is easily interatable.
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) {
const uint256 &wtxid = it->first;
const CWalletTx *pcoin = &(*it).second;
if (!CheckFinalTx(*pcoin))
continue;
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
continue;
int nDepth = pcoin->GetDepthInMainChain();
if (nDepth < 0)
continue;
// We should not consider coins which aren't at least in our mempool
// It's possible for these to be conflicted via ancestors which we may never be able to detect
if (nDepth == 0 && !pcoin->InMempool())
continue;
bool safeTx = pcoin->IsTrusted();
// We should not consider coins from transactions that are replacing
// other transactions.
//
// Example: There is a transaction A which is replaced by bumpfee
// transaction B. In this case, we want to prevent creation of
// a transaction B' which spends an output of B.
//
// Reason: If transaction A were initially confirmed, transactions B
// and B' would no longer be valid, so the user would have to create
// a new transaction C to replace B'. However, in the case of a
// one-block reorg, transactions B' and C might BOTH be accepted,
// when the user only wanted one of them. Specifically, there could
// be a 1-block reorg away from the chain where transactions A and C
// were accepted to another chain where B, B', and C were all
// accepted.
if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
safeTx = false;
}
// Similarly, we should not consider coins from transactions that
// have been replaced. In the example above, we would want to prevent
// creation of a transaction A' spending an output of A, because if
// transaction B were initially confirmed, conflicting with A and
// A', we wouldn't want to the user to create a transaction D
// intending to replace A', but potentially resulting in a scenario
// where A, A', and D could all be accepted (instead of just B and
// D, or just A and A' like the user would want).
if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
safeTx = false;
}
if (fOnlySafe && !safeTx) {
continue;
}
if (nDepth < nMinDepth || nDepth > nMaxDepth)
continue;
for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
int nType;
bool fIsOwner;
bool isAssetScript = pcoin->tx->vout[i].scriptPubKey.IsAssetScript(nType, fIsOwner);
if (coinControl && !isAssetScript && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint((*it).first, i)))
continue;
if (coinControl && isAssetScript && coinControl->HasAssetSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsAssetSelected(COutPoint((*it).first, i)))
continue;
if (IsLockedCoin((*it).first, i))
continue;
if (IsSpent(wtxid, i))
continue;
isminetype mine = IsMine(pcoin->tx->vout[i]);
if (mine == ISMINE_NO) {
continue;
}
bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) ||
(coinControl && coinControl->fAllowWatchOnly &&
(mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
std::string address;
CAssetTransfer assetTransfer;
CNewAsset asset;
CReissueAsset reissue;
std::string ownerName;
bool fWasNewAssetOutPoint = false;
bool fWasTransferAssetOutPoint = false;
bool fWasOwnerAssetOutPoint = false;
bool fWasReissueAssetOutPoint = false;
std::string strAssetName;
// Looking for Asset Tx OutPoints Only
if (fGetAssets && AreAssetsDeployed() && isAssetScript) {
if ( nType == TX_TRANSFER_ASSET) {
if (TransferAssetFromScript(pcoin->tx->vout[i].scriptPubKey, assetTransfer, address)) {
strAssetName = assetTransfer.strName;
fWasTransferAssetOutPoint = true;
}
} else if ( nType == TX_NEW_ASSET && !fIsOwner) {
if (AssetFromScript(pcoin->tx->vout[i].scriptPubKey, asset, address)) {
strAssetName = asset.strName;
fWasNewAssetOutPoint = true;
}
} else if ( nType == TX_NEW_ASSET && fIsOwner) {
if (OwnerAssetFromScript(pcoin->tx->vout[i].scriptPubKey, ownerName, address)) {
strAssetName = ownerName;
fWasOwnerAssetOutPoint = true;
}
} else if ( nType == TX_REISSUE_ASSET) {
if (ReissueAssetFromScript(pcoin->tx->vout[i].scriptPubKey, reissue, address)) {
strAssetName = reissue.strName;
fWasReissueAssetOutPoint = true;
}
} else {
continue;
}
if (fWasNewAssetOutPoint || fWasTransferAssetOutPoint || fWasOwnerAssetOutPoint || fWasReissueAssetOutPoint) {
// If we already have the maximum amount or size for this asset, skip it
if (setAssetMaxFound.count(strAssetName))
continue;
// Initialize the map vector is it doesn't exist yet
if (!mapAssetCoins.count(strAssetName)) {
std::vector<COutput> vOutput;
mapAssetCoins.insert(std::make_pair(strAssetName, vOutput));
}
// Add the COutput to the map of available Asset Coins
mapAssetCoins.at(strAssetName).push_back(
COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
// Initialize the map of current asset totals
if (!mapAssetTotals.count(strAssetName))
mapAssetTotals[strAssetName] = 0;
// Update the map of totals depending the which type of asset tx we are looking at
if (fWasNewAssetOutPoint)
mapAssetTotals[strAssetName] += asset.nAmount;
else if (fWasTransferAssetOutPoint)
mapAssetTotals[strAssetName] += assetTransfer.nAmount;
else if (fWasReissueAssetOutPoint)
mapAssetTotals[strAssetName] += reissue.nAmount;
else if (fWasOwnerAssetOutPoint)
mapAssetTotals[strAssetName] = OWNER_ASSET_AMOUNT;
// Checks the sum amount of all UTXO's, and adds to the set of assets that we found the max for
if (nMinimumSumAmount != MAX_MONEY) {
if (mapAssetTotals[strAssetName] >= nMinimumSumAmount)
setAssetMaxFound.insert(strAssetName);
}
// Checks the maximum number of UTXO's, and addes to set of of asset that we found the max for
if (nMaximumCount > 0 && mapAssetCoins[strAssetName].size() >= nMaximumCount) {
setAssetMaxFound.insert(strAssetName);
}
}
}
if (fGetATL) { // Looking for ATL Tx OutPoints Only
if (fATLLimitHit) // We hit our limit
continue;
// We only want ATL OutPoints. Don't include Asset OutPoints
if (isAssetScript)
continue;
vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
// Checks the sum amount of all UTXO's.
if (nMinimumSumAmount != MAX_MONEY) {
nTotal += pcoin->tx->vout[i].nValue;
if (nTotal >= nMinimumSumAmount) {
fATLLimitHit = true;
}
}
// Checks the maximum number of UTXO's.
if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
fATLLimitHit = true;
}
continue;
}
}
}
/** ATL END */
}
}
/** ATL START */
std::map<CTxDestination, std::vector<COutput>> CWallet::ListAssets() const
{
// TODO: Add AssertLockHeld(cs_wallet) here.
//
// Because the return value from this function contains pointers to
// CWalletTx objects, callers to this function really should acquire the
// cs_wallet lock before calling it. However, the current caller doesn't
// acquire this lock yet. There was an attempt to add the missing lock in
// https://github.com/AtlasProject/Atlascoin/pull/10340, but that change has been
// postponed until after https://github.com/AtlasProject/Atlascoin/pull/10244 to
// avoid adding some extra complexity to the Qt code.
std::map<CTxDestination, std::vector<COutput>> result;
std::map<std::string, std::vector<COutput> > mapAssets;
AvailableAssets(mapAssets);
LOCK2(cs_main, cs_wallet);
for (auto asset : mapAssets) {
for (auto &coin : asset.second) {
CTxDestination address;
if (coin.fSpendable &&
ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
result[address].emplace_back(std::move(coin));
}
}
}
std::vector<COutPoint> lockedCoins;
ListLockedCoins(lockedCoins);
for (const auto& output : lockedCoins) {
auto it = mapWallet.find(output.hash);
if (it != mapWallet.end()) {
if (!it->second.tx->vout[output.n].scriptPubKey.IsAssetScript()) // If not an asset script skip it
continue;
int depth = it->second.GetDepthInMainChain();
if (depth >= 0 && output.n < it->second.tx->vout.size() &&
IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
CTxDestination address;
if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
result[address].emplace_back(
&it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
}
}
}
}
return result;
}
/** ATL END */
std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
{
// TODO: Add AssertLockHeld(cs_wallet) here.
//
// Because the return value from this function contains pointers to
// CWalletTx objects, callers to this function really should acquire the
// cs_wallet lock before calling it. However, the current caller doesn't
// acquire this lock yet. There was an attempt to add the missing lock in
// https://github.com/AtlasProject/Atlascoin/pull/10340, but that change has been
// postponed until after https://github.com/AtlasProject/Atlascoin/pull/10244 to
// avoid adding some extra complexity to the Qt code.
std::map<CTxDestination, std::vector<COutput>> result;
std::vector<COutput> availableCoins;
AvailableCoins(availableCoins);
LOCK2(cs_main, cs_wallet);
for (auto& coin : availableCoins) {
CTxDestination address;
if (coin.fSpendable &&
ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
result[address].emplace_back(std::move(coin));
}
}
std::vector<COutPoint> lockedCoins;
ListLockedCoins(lockedCoins);
for (const auto& output : lockedCoins) {
auto it = mapWallet.find(output.hash);
if (it != mapWallet.end()) {
int depth = it->second.GetDepthInMainChain();
if (depth >= 0 && output.n < it->second.tx->vout.size() &&
IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
CTxDestination address;
if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
result[address].emplace_back(
&it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
}
}
}
}
return result;
}
const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
{
const CTransaction* ptx = &tx;
int n = output;
while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
const COutPoint& prevout = ptx->vin[0].prevout;
auto it = mapWallet.find(prevout.hash);
if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
!IsMine(it->second.tx->vout[prevout.n])) {
break;
}
ptx = it->second.tx.get();
n = prevout.n;
}
return ptx->vout[n];
}
static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
{
std::vector<char> vfIncluded;
vfBest.assign(vValue.size(), true);
nBest = nTotalLower;
FastRandomContext insecure_rand;
for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
{
vfIncluded.assign(vValue.size(), false);
CAmount nTotal = 0;
bool fReachedTarget = false;
for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
{
for (unsigned int i = 0; i < vValue.size(); i++)
{
//The solver here uses a randomized algorithm,
//the randomness serves no real security purpose but is just
//needed to prevent degenerate behavior and it is important
//that the rng is fast. We do not use a constant random sequence,
//because there may be some privacy improvement by making
//the selection random.
if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
{
nTotal += vValue[i].txout.nValue;
vfIncluded[i] = true;
if (nTotal >= nTargetValue)
{
fReachedTarget = true;
if (nTotal < nBest)
{
nBest = nTotal;
vfBest = vfIncluded;
}
nTotal -= vValue[i].txout.nValue;
vfIncluded[i] = false;
}
}
}
}
}
}
static void ApproximateBestAssetSubset(const std::vector<std::pair<CInputCoin, CAmount> >& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
{
std::vector<char> vfIncluded;
vfBest.assign(vValue.size(), true);
nBest = nTotalLower;
FastRandomContext insecure_rand;
for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
{
vfIncluded.assign(vValue.size(), false);
CAmount nTotal = 0;
bool fReachedTarget = false;
for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
{
for (unsigned int i = 0; i < vValue.size(); i++)
{
//The solver here uses a randomized algorithm,
//the randomness serves no real security purpose but is just
//needed to prevent degenerate behavior and it is important
//that the rng is fast. We do not use a constant random sequence,
//because there may be some privacy improvement by making
//the selection random.
if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
{
nTotal += vValue[i].second;
vfIncluded[i] = true;
if (nTotal >= nTargetValue)
{
fReachedTarget = true;
if (nTotal < nBest)
{
nBest = nTotal;
vfBest = vfIncluded;
}
nTotal -= vValue[i].second;
vfIncluded[i] = false;
}
}
}
}
}
}
bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
{
setCoinsRet.clear();
nValueRet = 0;
// List of values less than target
boost::optional<CInputCoin> coinLowestLarger;
std::vector<CInputCoin> vValue;
CAmount nTotalLower = 0;
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
for (const COutput &output : vCoins)
{
if (!output.fSpendable)
continue;
const CWalletTx *pcoin = output.tx;
if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
continue;
if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
continue;
int i = output.i;
CInputCoin coin = CInputCoin(pcoin, i);
if (coin.txout.nValue == nTargetValue)
{
setCoinsRet.insert(coin);
nValueRet += coin.txout.nValue;
return true;
}
else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
{
vValue.push_back(coin);
nTotalLower += coin.txout.nValue;
}
else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
{
coinLowestLarger = coin;
}
}
if (nTotalLower == nTargetValue)
{
for (const auto& input : vValue)
{
setCoinsRet.insert(input);
nValueRet += input.txout.nValue;
}
return true;
}
if (nTotalLower < nTargetValue)
{
if (!coinLowestLarger)
return false;
setCoinsRet.insert(coinLowestLarger.get());
nValueRet += coinLowestLarger->txout.nValue;
return true;
}
// Solve subset sum by stochastic approximation
std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
std::reverse(vValue.begin(), vValue.end());
std::vector<char> vfBest;
CAmount nBest;
ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
// If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
// or the next bigger coin is closer), return the bigger coin
if (coinLowestLarger &&
((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
{
setCoinsRet.insert(coinLowestLarger.get());
nValueRet += coinLowestLarger->txout.nValue;
}
else {
for (unsigned int i = 0; i < vValue.size(); i++)
if (vfBest[i])
{
setCoinsRet.insert(vValue[i]);
nValueRet += vValue[i].txout.nValue;
}
if (LogAcceptCategory(BCLog::SELECTCOINS)) {
LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
for (unsigned int i = 0; i < vValue.size(); i++) {
if (vfBest[i]) {
LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
}
}
LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
}
}
return true;
}
bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
{
std::vector<COutput> vCoins(vAvailableCoins);
// coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
{
for (const COutput& out : vCoins)
{
if (!out.fSpendable)
continue;
nValueRet += out.tx->tx->vout[out.i].nValue;
setCoinsRet.insert(CInputCoin(out.tx, out.i));
}
return (nValueRet >= nTargetValue);
}
// calculate value from preset inputs and store them
std::set<CInputCoin> setPresetCoins;
CAmount nValueFromPresetInputs = 0;
std::vector<COutPoint> vPresetInputs;
if (coinControl)
coinControl->ListSelected(vPresetInputs);
for (const COutPoint& outpoint : vPresetInputs)
{
std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
if (it != mapWallet.end())
{
const CWalletTx* pcoin = &it->second;
// Clearly invalid input, fail
if (pcoin->tx->vout.size() <= outpoint.n)
return false;
nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
} else
return false; // TODO: Allow non-wallet inputs
}
// remove preset inputs from vCoins
for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
{
if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
it = vCoins.erase(it);
else
++it;
}
size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
bool res = nTargetValue <= nValueFromPresetInputs ||
SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
(bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
(bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
(bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
(bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
(bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
// because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
// add preset inputs to the total value selected
nValueRet += nValueFromPresetInputs;
return res;
}
/** ATL START */
bool CWallet::CreateNewChangeAddress(CReserveKey& reservekey, CKeyID& keyID, std::string& strFailReason)
{
// Called with coin control doesn't have a change_address
// no coin control: send change to newly generated address
// Note: We use a new key here to keep it from being obvious which side is the change.
// The drawback is that by not reusing a previous key, the change may be lost if a
// backup is restored, if the backup doesn't have the new private key for the change.
// If we reused the old key, it would be possible to add code to look for and
// rediscover unknown transactions that were written with keys of ours to recover
// post-backup change.
// Reserve a new key pair from key pool
CPubKey vchPubKey;
bool ret;
ret = reservekey.GetReservedKey(vchPubKey, true);
if (!ret)
{
strFailReason = _("Keypool ran out, please call keypoolrefill first");
return false;
}
keyID = vchPubKey.GetID();
return true;
}
bool CWallet::SelectAssetsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, const std::string& strAssetName, std::vector<COutput> vCoins,
std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
{
setCoinsRet.clear();
nValueRet = 0;
// List of values less than target
boost::optional<CInputCoin> coinLowestLarger;
boost::optional<CAmount> coinLowestLargerAmount;
std::vector<std::pair<CInputCoin, CAmount> > vValue;
std::map<COutPoint, CAmount> mapValueAmount;
CAmount nTotalLower = 0;
random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
for (const COutput &output : vCoins)
{
if (!output.fSpendable)
continue;
const CWalletTx *pcoin = output.tx;
if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
continue;
if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
continue;
int i = output.i;
CInputCoin coin = CInputCoin(pcoin, i);
//-------------------------------
int nType = -1;
bool fIsOwner = false;
if (!coin.txout.scriptPubKey.IsAssetScript(nType, fIsOwner)) {
// TODO - Remove std::cout this before mainnet release
std::cout << "This shouldn't be occuring: Non Asset Script pub key made it to the SelectAssetsMinConf function call. Look into this!" << std::endl;
continue;
}
CAmount nTempAmount = 0;
if (nType == TX_NEW_ASSET && !fIsOwner) { // Root/Sub Asset
CNewAsset assetTemp;
std::string address;
if (!AssetFromScript(coin.txout.scriptPubKey, assetTemp, address))
continue;
nTempAmount = assetTemp.nAmount;
} else if (nType == TX_TRANSFER_ASSET) { // Transfer Asset
CAssetTransfer transferTemp;
std::string address;
if (!TransferAssetFromScript(coin.txout.scriptPubKey, transferTemp, address))
continue;
nTempAmount = transferTemp.nAmount;
} else if (nType == TX_NEW_ASSET && fIsOwner) { // Owner Asset
std::string ownerName;
std::string address;
if (!OwnerAssetFromScript(coin.txout.scriptPubKey, ownerName, address))
continue;
nTempAmount = OWNER_ASSET_AMOUNT;
} else if (nType == TX_REISSUE_ASSET) { // Reissue Asset
CReissueAsset reissueTemp;
std::string address;
if (!ReissueAssetFromScript(coin.txout.scriptPubKey, reissueTemp, address))
continue;
nTempAmount = reissueTemp.nAmount;
} else {
continue;
}
if (nTempAmount == nTargetValue)
{
setCoinsRet.insert(coin);
nValueRet += nTempAmount;
return true;
}
else if (nTempAmount < nTargetValue + MIN_CHANGE)
{
vValue.push_back(std::make_pair(coin, nTempAmount));
nTotalLower += nTempAmount;
}
else if (!coinLowestLarger || !coinLowestLargerAmount || nTempAmount < coinLowestLargerAmount)
{
coinLowestLarger = coin;
coinLowestLargerAmount = nTempAmount;
}
}
if (nTotalLower == nTargetValue)
{
for (const auto& pair : vValue)
{
setCoinsRet.insert(pair.first);
nValueRet += pair.second;
}
return true;
}
if (nTotalLower < nTargetValue)
{
if (!coinLowestLarger || !coinLowestLargerAmount)
return false;
setCoinsRet.insert(coinLowestLarger.get());
nValueRet += coinLowestLargerAmount.get();
return true;
}
// Solve subset sum by stochastic approximation
std::sort(vValue.begin(), vValue.end(), CompareAssetValueOnly());
std::reverse(vValue.begin(), vValue.end());
std::vector<char> vfBest;
CAmount nBest;
ApproximateBestAssetSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
ApproximateBestAssetSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
// If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
// or the next bigger coin is closer), return the bigger coin
if (coinLowestLarger && coinLowestLargerAmount &&
((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLargerAmount <= nBest))
{
setCoinsRet.insert(coinLowestLarger.get());
nValueRet += coinLowestLargerAmount.get();
}
else {
for (unsigned int i = 0; i < vValue.size(); i++)
if (vfBest[i])
{
setCoinsRet.insert(vValue[i].first);
nValueRet += vValue[i].second;
}
if (LogAcceptCategory(BCLog::SELECTCOINS)) {
LogPrint(BCLog::SELECTCOINS, "SelectAssets() best subset: ");
for (unsigned int i = 0; i < vValue.size(); i++) {
if (vfBest[i]) {
LogPrint(BCLog::SELECTCOINS, "%s : %s", strAssetName, FormatMoney(vValue[i].second));
}
}
LogPrint(BCLog::SELECTCOINS, "total %s : %s\n", strAssetName, FormatMoney(nBest));
}
}
return true;
}
bool CWallet::SelectAssets(const std::map<std::string, std::vector<COutput> >& mapAvailableAssets, const std::map<std::string, CAmount>& mapAssetTargetValue, std::set<CInputCoin>& setCoinsRet, std::map<std::string, CAmount>& mapValueRet) const
{
if (!AreAssetsDeployed())
return false;
size_t nMaxChainLength = std::min(gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
bool fRejectLongChains = gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
for (auto assetVector : mapAvailableAssets) {
// Setup temporay variables
std::vector<COutput> vAssets(assetVector.second);
std::set<CInputCoin> tempCoinsRet;
CAmount nTempAmountRet;
CAmount nTempTargetValue;
std::string strAssetName = assetVector.first;
CAmount nValueFromPresetInputs = 0; // This is used with coincontrol, which assets doesn't support yet
// If we dont have a target value for this asset, don't select coins for it
if (!mapAssetTargetValue.count(strAssetName))
continue;
// If we dont have a target value greater than zero, don't select coins for it
if (mapAssetTargetValue.at(strAssetName) <= 0)
continue;
// Add the starting value into the mapValueRet
if (!mapValueRet.count(strAssetName))
mapValueRet.insert(std::make_pair(strAssetName, 0));
// assign our temporary variable
nTempAmountRet = mapValueRet.at(strAssetName);
nTempTargetValue = mapAssetTargetValue.at(strAssetName);
bool res = nTempTargetValue <= nValueFromPresetInputs ||
SelectAssetsMinConf(nTempTargetValue - nValueFromPresetInputs, 1, 6, 0, strAssetName, vAssets, tempCoinsRet, nTempAmountRet) ||
SelectAssetsMinConf(nTempTargetValue - nValueFromPresetInputs, 1, 1, 0, strAssetName, vAssets, tempCoinsRet, nTempAmountRet) ||
(bSpendZeroConfChange && SelectAssetsMinConf(nTempTargetValue - nValueFromPresetInputs, 0, 1, 2, strAssetName, vAssets, tempCoinsRet, nTempAmountRet)) ||
(bSpendZeroConfChange && SelectAssetsMinConf(nTempTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), strAssetName, vAssets, tempCoinsRet, nTempAmountRet)) ||
(bSpendZeroConfChange && SelectAssetsMinConf(nTempTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, strAssetName, vAssets, tempCoinsRet, nTempAmountRet)) ||
(bSpendZeroConfChange && SelectAssetsMinConf(nTempTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, strAssetName, vAssets, tempCoinsRet, nTempAmountRet)) ||
(bSpendZeroConfChange && !fRejectLongChains && SelectAssetsMinConf(nTempTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), strAssetName, vAssets, tempCoinsRet, nTempAmountRet));
if (res) {
setCoinsRet.insert(tempCoinsRet.begin(), tempCoinsRet.end());
mapValueRet.at(strAssetName) = nTempAmountRet + nValueFromPresetInputs;
} else {
return false;
}
}
return true;
}
/** ATL END */
bool CWallet::SignTransaction(CMutableTransaction &tx)
{
AssertLockHeld(cs_wallet); // mapWallet
// sign the new tx
CTransaction txNewConst(tx);
int nIn = 0;
for (const auto& input : tx.vin) {
std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
return false;
}
const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
SignatureData sigdata;
if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
return false;
}
UpdateTransaction(tx, nIn, sigdata);
nIn++;
}
return true;
}
bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl)
{
std::vector<CRecipient> vecSend;
// Turn the txout set into a CRecipient vector
for (size_t idx = 0; idx < tx.vout.size(); idx++)
{
const CTxOut& txOut = tx.vout[idx];
CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
vecSend.push_back(recipient);
}
coinControl.fAllowOtherInputs = true;
for (const CTxIn& txin : tx.vin)
coinControl.Select(txin.prevout);
CReserveKey reservekey(this);
CWalletTx wtx;
if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl, false)) {
return false;
}
if (nChangePosInOut != -1) {
tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
// we don't have the normal Create/Commit cycle, and don't want to risk reusing change,
// so just remove the key from the keypool here.
reservekey.KeepKey();
}
// Copy output sizes from new transaction; they may have had the fee subtracted from them
for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
// Add new txins (keeping original txin scriptSig/order)
for (const CTxIn& txin : wtx.tx->vin)
{
if (!coinControl.IsSelected(txin.prevout))
{
tx.vin.push_back(txin);
if (lockUnspents)
{
LOCK2(cs_main, cs_wallet);
LockCoin(txin.prevout);
}
}
}
return true;
}
bool CWallet::CreateTransactionWithAssets(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
std::string& strFailReason, const CCoinControl& coin_control, const std::vector<CNewAsset> assets, const CTxDestination destination, const AssetType& type, bool sign)
{
CReissueAsset reissueAsset;
return CreateTransactionAll(vecSend, wtxNew, reservekey, nFeeRet, nChangePosInOut, strFailReason, coin_control, true, assets, destination, false, false, reissueAsset, type, sign);
}
bool CWallet::CreateTransactionWithTransferAsset(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
std::string& strFailReason, const CCoinControl& coin_control, bool sign)
{
CNewAsset asset;
CReissueAsset reissueAsset;
CTxDestination destination;
AssetType assetType = AssetType::INVALID;
return CreateTransactionAll(vecSend, wtxNew, reservekey, nFeeRet, nChangePosInOut, strFailReason, coin_control, false, asset, destination, true, false, reissueAsset, assetType, sign);
}
bool CWallet::CreateTransactionWithReissueAsset(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
std::string& strFailReason, const CCoinControl& coin_control, const CReissueAsset& reissueAsset, const CTxDestination destination, bool sign)
{
CNewAsset asset;
AssetType assetType = AssetType::REISSUE;
return CreateTransactionAll(vecSend, wtxNew, reservekey, nFeeRet, nChangePosInOut, strFailReason, coin_control, false, asset, destination, false, true, reissueAsset, assetType, sign);
}
bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, int& nChangePosInOut,
std::string& strFailReason, const CCoinControl& coin_control, bool sign)
{
CNewAsset asset;
CReissueAsset reissueAsset;
CTxDestination destination;
AssetType assetType = AssetType::INVALID;
return CreateTransactionAll(vecSend, wtxNew, reservekey, nFeeRet, nChangePosInOut, strFailReason, coin_control, false, asset, destination, false, false, reissueAsset, assetType, sign);
}
bool CWallet::CreateTransactionAll(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey,
CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason,
const CCoinControl& coin_control, bool fNewAsset, const CNewAsset& asset,
const CTxDestination destination, bool fTransferAsset, bool fReissueAsset,
const CReissueAsset& reissueAsset, const AssetType& assetType, bool sign)
{
std::vector<CNewAsset> assets;
assets.push_back(asset);
return CreateTransactionAll(vecSend, wtxNew, reservekey, nFeeRet, nChangePosInOut, strFailReason, coin_control,
fNewAsset, assets, destination, fTransferAsset, fReissueAsset, reissueAsset, assetType,
sign);
}
bool CWallet::CreateTransactionAll(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey,
CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason,
const CCoinControl& coin_control, bool fNewAsset,
const std::vector<CNewAsset> assets, const CTxDestination destination,
bool fTransferAsset, bool fReissueAsset, const CReissueAsset& reissueAsset,
const AssetType& assetType, bool sign)
{
/** ATL START */
if (!AreAssetsDeployed() && (fTransferAsset || fNewAsset || fReissueAsset))
return false;
if (fNewAsset && (assets.size() < 1 || !IsValidDestination(destination)))
return error("%s : Tried creating a new asset transaction and the asset was null or the destination was invalid", __func__);
if ((fNewAsset && fTransferAsset) || (fReissueAsset && fTransferAsset) || (fReissueAsset && fNewAsset))
return error("%s : Only one type of asset transaction allowed per transaction");
if (fReissueAsset && (reissueAsset.IsNull() || !IsValidDestination(destination)))
return error("%s : Tried reissuing an asset and the reissue data was null or the destination was invalid", __func__);
/** ATL END */
CAmount nValue = 0;
std::map<std::string, CAmount> mapAssetValue;
int nChangePosRequest = nChangePosInOut;
unsigned int nSubtractFeeFromAmount = 0;
for (const auto& recipient : vecSend)
{
/** ATL START */
if (fTransferAsset || fReissueAsset || assetType == AssetType::SUB || assetType == AssetType::UNIQUE) {
CAssetTransfer assetTransfer;
std::string address;
if (TransferAssetFromScript(recipient.scriptPubKey, assetTransfer, address)) {
if (!mapAssetValue.count(assetTransfer.strName))
mapAssetValue[assetTransfer.strName] = 0;
if (assetTransfer.nAmount <= 0) {
strFailReason = _("Asset Transfer amounts must be greater than 0");
return false;
}
mapAssetValue[assetTransfer.strName] += assetTransfer.nAmount;
}
}
/** ATL END */
if (nValue < 0 || recipient.nAmount < 0)
{
strFailReason = _("Transaction amounts must not be negative");
return false;
}
nValue += recipient.nAmount;
if (recipient.fSubtractFeeFromAmount)
nSubtractFeeFromAmount++;
}
if (vecSend.empty())
{
strFailReason = _("Transaction must have at least one recipient");
return false;
}
wtxNew.fTimeReceivedIsTxTime = true;
wtxNew.BindWallet(this);
CMutableTransaction txNew;
// Discourage fee sniping.
//
// For a large miner the value of the transactions in the best block and
// the mempool can exceed the cost of deliberately attempting to mine two
// blocks to orphan the current best block. By setting nLockTime such that
// only the next block can include the transaction, we discourage this
// practice as the height restricted and limited blocksize gives miners
// considering fee sniping fewer options for pulling off this attack.
//
// A simple way to think about this is from the wallet's point of view we
// always want the blockchain to move forward. By setting nLockTime this
// way we're basically making the statement that we only want this
// transaction to appear in the next block; we don't want to potentially
// encourage reorgs by allowing transactions to appear at lower heights
// than the next block in forks of the best chain.
//
// Of course, the subsidy is high enough, and transaction volume low
// enough, that fee sniping isn't a problem yet, but by implementing a fix
// now we ensure code won't be written that makes assumptions about
// nLockTime that preclude a fix later.
txNew.nLockTime = chainActive.Height();
// Secondly occasionally randomly pick a nLockTime even further back, so
// that transactions that are delayed after signing for whatever reason,
// e.g. high-latency mix networks and some CoinJoin implementations, have
// better privacy.
if (GetRandInt(10) == 0)
txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
FeeCalculation feeCalc;
CAmount nFeeNeeded;
unsigned int nBytes;
{
std::set<CInputCoin> setCoins;
std::set<CInputCoin> setAssets;
LOCK2(cs_main, cs_wallet);
{
/** ATL START */
std::vector<COutput> vAvailableCoins;
std::map<std::string, std::vector<COutput> > mapAssetCoins;
if (fTransferAsset || fReissueAsset || assetType == AssetType::SUB || assetType == AssetType::UNIQUE)
AvailableCoinsWithAssets(vAvailableCoins, mapAssetCoins, true, &coin_control);
else
AvailableCoins(vAvailableCoins, true, &coin_control);
/** ATL END */
// Create change script that will be used if we need change
// TODO: pass in scriptChange instead of reservekey so
// change transaction isn't always pay-to-atlas-address
CScript scriptChange;
// coin control: send change to custom address
if (!boost::get<CNoDestination>(&coin_control.destChange)) {
scriptChange = GetScriptForDestination(coin_control.destChange);
} else {
// no coin control: send change to newly generated address
CKeyID keyID;
if (!CreateNewChangeAddress(reservekey, keyID, strFailReason))
return false;
scriptChange = GetScriptForDestination(keyID);
}
CTxOut change_prototype_txout(0, scriptChange);
size_t change_prototype_size = GetSerializeSize(change_prototype_txout, SER_DISK, 0);
CFeeRate discard_rate = GetDiscardRate(::feeEstimator);
nFeeRet = 0;
bool pick_new_inputs = true;
CAmount nValueIn = 0;
// Start with no fee and loop until there is enough fee
while (true)
{
std::map<std::string, CAmount> mapAssetsIn;
nChangePosInOut = nChangePosRequest;
txNew.vin.clear();
txNew.vout.clear();
wtxNew.fFromMe = true;
bool fFirst = true;
CAmount nValueToSelect = nValue;
if (nSubtractFeeFromAmount == 0)
nValueToSelect += nFeeRet;
// vouts to the payees
for (const auto& recipient : vecSend)
{
CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
if (recipient.fSubtractFeeFromAmount)
{
assert(nSubtractFeeFromAmount != 0);
txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
if (fFirst) // first receiver pays the remainder not divisible by output count
{
fFirst = false;
txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
}
}
if (IsDust(txout, ::dustRelayFee) && !IsScriptTransferAsset(recipient.scriptPubKey)) /** ATL START */ /** ATL END */
{
if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
{
if (txout.nValue < 0)
strFailReason = _("The transaction amount is too small to pay the fee");
else
strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
}
else {
strFailReason = _("Transaction amount too small");
}
return false;
}
txNew.vout.push_back(txout);
}
// Choose coins to use
if (pick_new_inputs) {
nValueIn = 0;
setCoins.clear();
if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, &coin_control))
{
strFailReason = _("Insufficient funds");
return false;
}
/** ATL START */
if (AreAssetsDeployed()) {
setAssets.clear();
mapAssetsIn.clear();
if (!SelectAssets(mapAssetCoins, mapAssetValue, setAssets, mapAssetsIn)) {
strFailReason = _("Insufficient asset funds");
return false;
}
}
/** ATL END */
}
const CAmount nChange = nValueIn - nValueToSelect;
/** ATL START */
if (AreAssetsDeployed()) {
// Add the change for the assets
std::map<std::string, CAmount> mapAssetChange;
for (auto asset : mapAssetValue) {
if (mapAssetsIn.count(asset.first))
mapAssetChange.insert(
std::make_pair(asset.first, (mapAssetsIn.at(asset.first) - asset.second)));
}
for (auto assetChange : mapAssetChange) {
if (assetChange.second > 0) {
CScript scriptAssetChange = scriptChange;
CAssetTransfer assetTransfer(assetChange.first, assetChange.second);
assetTransfer.ConstructTransaction(scriptAssetChange);
CTxOut newAssetTxOut(0, scriptAssetChange);
txNew.vout.emplace_back(newAssetTxOut);
}
}
}
/** ATL END */
if (nChange > 0)
{
// Fill a vout to ourself
CTxOut newTxOut(nChange, scriptChange);
// Never create dust outputs; if we would, just
// add the dust to the fee.
if (IsDust(newTxOut, discard_rate))
{
nChangePosInOut = -1;
nFeeRet += nChange;
}
else
{
if (nChangePosInOut == -1)
{
// Insert change txn at random position:
nChangePosInOut = GetRandInt(txNew.vout.size()+1);
}
else if ((unsigned int)nChangePosInOut > txNew.vout.size())
{
strFailReason = _("Change index out of range");
return false;
}
std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
txNew.vout.insert(position, newTxOut);
}
} else {
nChangePosInOut = -1;
}
/** ATL START */
if (AreAssetsDeployed()) {
if (fNewAsset) {
for (auto asset : assets) {
// Create the owner token output for non-unique assets
if (assetType != AssetType::UNIQUE) {
CScript ownerScript = GetScriptForDestination(destination);
asset.ConstructOwnerTransaction(ownerScript);
CTxOut ownerTxOut(0, ownerScript);
txNew.vout.push_back(ownerTxOut);
}
// Create the asset transaction and push it back so it is the last CTxOut in the transaction
CScript scriptPubKey = GetScriptForDestination(destination);
asset.ConstructTransaction(scriptPubKey);
CTxOut newTxOut(0, scriptPubKey);
txNew.vout.push_back(newTxOut);
}
} else if (fReissueAsset) {
// Create the asset transaction and push it back so it is the last CTxOut in the transaction
CScript reissueScript = GetScriptForDestination(destination);
// Create the scriptPubKeys for the reissue data, and that owner asset
reissueAsset.ConstructTransaction(reissueScript);
CTxOut reissueTxOut(0, reissueScript);
txNew.vout.push_back(reissueTxOut);
}
}
/** ATL END */
// Fill vin
//
// Note how the sequence number is set to non-maxint so that
// the nLockTime set above actually works.
//
// BIP125 defines opt-in RBF as any nSequence < maxint-1, so
// we use the highest possible value in that range (maxint-2)
// to avoid conflicting with other possible uses of nSequence,
// and in the spirit of "smallest possible change from prior
// behavior."
// const uint32_t nSequence = coin_control.signalRbf ? MAX_BIP125_RBF_SEQUENCE : (CTxIn::SEQUENCE_FINAL - 1);
const uint32_t nSequence = CTxIn::SEQUENCE_FINAL - 1;
for (const auto& coin : setCoins)
txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
nSequence));
/** ATL START */
if (AreAssetsDeployed()) {
for (const auto &asset : setAssets)
txNew.vin.push_back(CTxIn(asset.outpoint, CScript(),
nSequence));
}
/** ATL END */
// Add the new asset inputs into the tempSet so the dummysigntx will add the correct amount of sigsß
std::set<CInputCoin> tempSet = setCoins;
tempSet.insert(setAssets.begin(), setAssets.end());
// Fill in dummy signatures for fee calculation.
if (!DummySignTx(txNew, tempSet)) {
strFailReason = _("Signing transaction for fee calculation failed");
return false;
}
nBytes = GetVirtualTransactionSize(txNew);
// Remove scriptSigs to eliminate the fee calculation dummy signatures
for (auto& vin : txNew.vin) {
vin.scriptSig = CScript();
vin.scriptWitness.SetNull();
}
nFeeNeeded = GetMinimumFee(nBytes, coin_control, ::mempool, ::feeEstimator, &feeCalc);
// If we made it here and we aren't even able to meet the relay fee on the next pass, give up
// because we must be at the maximum allowed fee.
if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
{
strFailReason = _("Transaction too large for fee policy");
return false;
}
if (nFeeRet >= nFeeNeeded) {
// Reduce fee to only the needed amount if possible. This
// prevents potential overpayment in fees if the coins
// selected to meet nFeeNeeded result in a transaction that
// requires less fee than the prior iteration.
// If we have no change and a big enough excess fee, then
// try to construct transaction again only without picking
// new inputs. We now know we only need the smaller fee
// (because of reduced tx size) and so we should add a
// change output. Only try this once.
if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
unsigned int tx_size_with_change = nBytes + change_prototype_size + 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
CAmount fee_needed_with_change = GetMinimumFee(tx_size_with_change, coin_control, ::mempool, ::feeEstimator, nullptr);
CAmount minimum_value_for_change = GetDustThreshold(change_prototype_txout, discard_rate);
if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
pick_new_inputs = false;
nFeeRet = fee_needed_with_change;
continue;
}
}
// If we have change output already, just increase it
if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
CAmount extraFeePaid = nFeeRet - nFeeNeeded;
std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
change_position->nValue += extraFeePaid;
nFeeRet -= extraFeePaid;
}
break; // Done, enough fee included.
}
else if (!pick_new_inputs) {
// This shouldn't happen, we should have had enough excess
// fee to pay for the new output and still meet nFeeNeeded
// Or we should have just subtracted fee from recipients and
// nFeeNeeded should not have changed
strFailReason = _("Transaction fee and change calculation failed");
return false;
}
// Try to reduce change to include necessary fee
if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
// Only reduce change if remaining amount is still a large enough output.
if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
change_position->nValue -= additionalFeeNeeded;
nFeeRet += additionalFeeNeeded;
break; // Done, able to increase fee from change
}
}
// If subtracting fee from recipients, we now know what fee we
// need to subtract, we have no reason to reselect inputs
if (nSubtractFeeFromAmount > 0) {
pick_new_inputs = false;
}
// Include more fee and try again.
nFeeRet = nFeeNeeded;
continue;
}
}
if (nChangePosInOut == -1) reservekey.ReturnKey(); // Return any reserved key if we don't have change
if (sign)
{
CTransaction txNewConst(txNew);
int nIn = 0;
for (const auto& coin : setCoins)
{
const CScript& scriptPubKey = coin.txout.scriptPubKey;
SignatureData sigdata;
if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
{
strFailReason = _("Signing transaction failed");
return false;
} else {
UpdateTransaction(txNew, nIn, sigdata);
}
nIn++;
}
/** ATL START */
if (AreAssetsDeployed()) {
for (const auto &asset : setAssets) {
const CScript &scriptPubKey = asset.txout.scriptPubKey;
SignatureData sigdata;
if (!ProduceSignature(
TransactionSignatureCreator(this, &txNewConst, nIn, asset.txout.nValue, SIGHASH_ALL),
scriptPubKey, sigdata)) {
strFailReason = _("Signing asset transaction failed");
return false;
} else {
UpdateTransaction(txNew, nIn, sigdata);
}
nIn++;
}
}
/** ATL END */
}
// Embed the constructed transaction data in wtxNew.
wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
// Limit size
if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
{
strFailReason = _("Transaction too large");
return false;
}
}
if (gArgs.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
// Lastly, ensure this tx will pass the mempool's chain limits
LockPoints lp;
CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
CTxMemPool::setEntries setAncestors;
size_t nLimitAncestors = gArgs.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
size_t nLimitDescendants = gArgs.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
std::string errString;
if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
strFailReason = _("Transaction has too long of a mempool chain");
return false;
}
}
LogPrintf("Fee Calculation: Fee:%d Bytes:%u Needed:%d Tgt:%d (requested %d) Reason:\"%s\" Decay %.5f: Estimation: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out) Fail: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out)\n",
nFeeRet, nBytes, nFeeNeeded, feeCalc.returnedTarget, feeCalc.desiredTarget, StringForFeeReason(feeCalc.reason), feeCalc.est.decay,
feeCalc.est.pass.start, feeCalc.est.pass.end,
100 * feeCalc.est.pass.withinTarget / (feeCalc.est.pass.totalConfirmed + feeCalc.est.pass.inMempool + feeCalc.est.pass.leftMempool),
feeCalc.est.pass.withinTarget, feeCalc.est.pass.totalConfirmed, feeCalc.est.pass.inMempool, feeCalc.est.pass.leftMempool,
feeCalc.est.fail.start, feeCalc.est.fail.end,
100 * feeCalc.est.fail.withinTarget / (feeCalc.est.fail.totalConfirmed + feeCalc.est.fail.inMempool + feeCalc.est.fail.leftMempool),
feeCalc.est.fail.withinTarget, feeCalc.est.fail.totalConfirmed, feeCalc.est.fail.inMempool, feeCalc.est.fail.leftMempool);
return true;
}
/**
* Call after CreateTransaction unless you want to abort
*/
bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
{
{
LOCK2(cs_main, cs_wallet);
LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
{
// Take key pair from key pool so it won't be used again
reservekey.KeepKey();
// Add tx to wallet, because if it has change it's also ours,
// otherwise just for transaction history.
AddToWallet(wtxNew);
// Notify that old coins are spent
for (const CTxIn& txin : wtxNew.tx->vin)
{
CWalletTx &coin = mapWallet[txin.prevout.hash];
coin.BindWallet(this);
NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
}
}
// Track how many getdata requests our transaction gets
mapRequestCount[wtxNew.GetHash()] = 0;
if (fBroadcastTransactions)
{
// Broadcast
if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
// TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
AbandonTransaction(wtxNew.tx->GetHash());
return false;
} else {
wtxNew.RelayWalletTransaction(connman);
}
}
}
return true;
}
void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
CWalletDB walletdb(*dbw);
return walletdb.ListAccountCreditDebit(strAccount, entries);
}
bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
{
CWalletDB walletdb(*dbw);
return AddAccountingEntry(acentry, &walletdb);
}
bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
{
if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
return false;
}
laccentries.push_back(acentry);
CAccountingEntry & entry = laccentries.back();
wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair(nullptr, &entry)));
return true;
}
DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
{
LOCK2(cs_main, cs_wallet);
fFirstRunRet = false;
DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
if (nLoadWalletRet == DB_NEED_REWRITE)
{
if (dbw->Rewrite("\x04pool"))
{
setInternalKeyPool.clear();
setExternalKeyPool.clear();
m_pool_key_to_index.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// that requires a new key.
}
}
// This wallet is in its first run if all of these are empty
fFirstRunRet = mapKeys.empty() && mapCryptedKeys.empty() && mapWatchKeys.empty() && setWatchOnly.empty() && mapScripts.empty();
if (nLoadWalletRet != DB_LOAD_OK)
return nLoadWalletRet;
uiInterface.LoadWallet(this);
return DB_LOAD_OK;
}
DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
{
AssertLockHeld(cs_wallet); // mapWallet
DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
for (uint256 hash : vHashOut)
mapWallet.erase(hash);
if (nZapSelectTxRet == DB_NEED_REWRITE)
{
if (dbw->Rewrite("\x04pool"))
{
setInternalKeyPool.clear();
setExternalKeyPool.clear();
m_pool_key_to_index.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// that requires a new key.
}
}
if (nZapSelectTxRet != DB_LOAD_OK)
return nZapSelectTxRet;
MarkDirty();
return DB_LOAD_OK;
}
DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
{
DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
if (nZapWalletTxRet == DB_NEED_REWRITE)
{
if (dbw->Rewrite("\x04pool"))
{
LOCK(cs_wallet);
setInternalKeyPool.clear();
setExternalKeyPool.clear();
m_pool_key_to_index.clear();
// Note: can't top-up keypool here, because wallet is locked.
// User will be prompted to unlock wallet the next operation
// that requires a new key.
}
}
if (nZapWalletTxRet != DB_LOAD_OK)
return nZapWalletTxRet;
return DB_LOAD_OK;
}
bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
{
bool fUpdated = false;
{
LOCK(cs_wallet); // mapAddressBook
std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
fUpdated = mi != mapAddressBook.end();
mapAddressBook[address].name = strName;
if (!strPurpose.empty()) /* update purpose only if requested */
mapAddressBook[address].purpose = strPurpose;
}
NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(EncodeDestination(address), strPurpose))
return false;
return CWalletDB(*dbw).WriteName(EncodeDestination(address), strName);
}
bool CWallet::DelAddressBook(const CTxDestination& address)
{
{
LOCK(cs_wallet); // mapAddressBook
// Delete destdata tuples associated with address
std::string strAddress = EncodeDestination(address);
for (const std::pair<std::string, std::string> &item : mapAddressBook[address].destdata)
{
CWalletDB(*dbw).EraseDestData(strAddress, item.first);
}
mapAddressBook.erase(address);
}
NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
CWalletDB(*dbw).ErasePurpose(EncodeDestination(address));
return CWalletDB(*dbw).EraseName(EncodeDestination(address));
}
const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
{
CTxDestination address;
if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
auto mi = mapAddressBook.find(address);
if (mi != mapAddressBook.end()) {
return mi->second.name;
}
}
// A scriptPubKey that doesn't have an entry in the address book is
// associated with the default account ("").
const static std::string DEFAULT_ACCOUNT_NAME;
return DEFAULT_ACCOUNT_NAME;
}
/**
* Mark old keypool keys as used,
* and generate all new keys
*/
bool CWallet::NewKeyPool()
{
{
LOCK(cs_wallet);
CWalletDB walletdb(*dbw);
for (int64_t nIndex : setInternalKeyPool) {
walletdb.ErasePool(nIndex);
}
setInternalKeyPool.clear();
for (int64_t nIndex : setExternalKeyPool) {
walletdb.ErasePool(nIndex);
}
setExternalKeyPool.clear();
m_pool_key_to_index.clear();
if (!TopUpKeyPool()) {
return false;
}
LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
}
return true;
}
size_t CWallet::KeypoolCountExternalKeys()
{
AssertLockHeld(cs_wallet); // setExternalKeyPool
return setExternalKeyPool.size();
}
void CWallet::LoadKeyPool(int64_t nIndex, const CKeyPool &keypool)
{
AssertLockHeld(cs_wallet);
if (keypool.fInternal) {
setInternalKeyPool.insert(nIndex);
} else {
setExternalKeyPool.insert(nIndex);
}
m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
m_pool_key_to_index[keypool.vchPubKey.GetID()] = nIndex;
// If no metadata exists yet, create a default with the pool key's
// creation time. Note that this may be overwritten by actually
// stored metadata for that key later, which is fine.
CKeyID keyid = keypool.vchPubKey.GetID();
if (mapKeyMetadata.count(keyid) == 0)
mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime);
}
bool CWallet::TopUpKeyPool(unsigned int kpSize)
{
{
LOCK(cs_wallet);
if (IsLocked())
return false;
// Top up key pool
unsigned int nTargetSize;
if (kpSize > 0)
nTargetSize = kpSize;
else
nTargetSize = std::max(gArgs.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
// count amount of available keys (internal, external)
// make sure the keypool of external and internal keys fits the user selected target (-keypool)
int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setInternalKeyPool.size(), (int64_t) 0);
if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
{
// don't create extra internal keys
missingInternal = 0;
}
bool internal = false;
CWalletDB walletdb(*dbw);
for (int64_t i = missingInternal + missingExternal; i--;)
{
if (i < missingInternal) {
internal = true;
}
assert(m_max_keypool_index < std::numeric_limits<int64_t>::max()); // How in the hell did you use so many keys?
int64_t index = ++m_max_keypool_index;
CPubKey pubkey(GenerateNewKey(walletdb, internal));
if (!walletdb.WritePool(index, CKeyPool(pubkey, internal))) {
throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
}
if (internal) {
setInternalKeyPool.insert(index);
} else {
setExternalKeyPool.insert(index);
}
m_pool_key_to_index[pubkey.GetID()] = index;
}
if (missingInternal + missingExternal > 0) {
LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal + missingExternal, missingInternal, setInternalKeyPool.size() + setExternalKeyPool.size(), setInternalKeyPool.size());
}
}
return true;
}
void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool fRequestedInternal)
{
nIndex = -1;
keypool.vchPubKey = CPubKey();
{
LOCK(cs_wallet);
if (!IsLocked())
TopUpKeyPool();
bool fReturningInternal = IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT) && fRequestedInternal;
std::set<int64_t>& setKeyPool = fReturningInternal ? setInternalKeyPool : setExternalKeyPool;
// Get the oldest key
if(setKeyPool.empty())
return;
CWalletDB walletdb(*dbw);
auto it = setKeyPool.begin();
nIndex = *it;
setKeyPool.erase(it);
if (!walletdb.ReadPool(nIndex, keypool)) {
throw std::runtime_error(std::string(__func__) + ": read failed");
}
if (!HaveKey(keypool.vchPubKey.GetID())) {
throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
}
if (keypool.fInternal != fReturningInternal) {
throw std::runtime_error(std::string(__func__) + ": keypool entry misclassified");
}
assert(keypool.vchPubKey.IsValid());
m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
LogPrintf("keypool reserve %d\n", nIndex);
}
}
void CWallet::KeepKey(int64_t nIndex)
{
// Remove from key pool
CWalletDB walletdb(*dbw);
walletdb.ErasePool(nIndex);
LogPrintf("keypool keep %d\n", nIndex);
}
void CWallet::ReturnKey(int64_t nIndex, bool fInternal, const CPubKey& pubkey)
{
// Return to key pool
{
LOCK(cs_wallet);
if (fInternal) {
setInternalKeyPool.insert(nIndex);
} else {
setExternalKeyPool.insert(nIndex);
}
m_pool_key_to_index[pubkey.GetID()] = nIndex;
}
LogPrintf("keypool return %d\n", nIndex);
}
bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
{
CKeyPool keypool;
{
LOCK(cs_wallet);
int64_t nIndex = 0;
ReserveKeyFromKeyPool(nIndex, keypool, internal);
if (nIndex == -1)
{
if (IsLocked()) return false;
CWalletDB walletdb(*dbw);
result = GenerateNewKey(walletdb, internal);
return true;
}
KeepKey(nIndex);
result = keypool.vchPubKey;
}
return true;
}
static int64_t GetOldestKeyTimeInPool(const std::set<int64_t>& setKeyPool, CWalletDB& walletdb) {
if (setKeyPool.empty()) {
return GetTime();
}
CKeyPool keypool;
int64_t nIndex = *(setKeyPool.begin());
if (!walletdb.ReadPool(nIndex, keypool)) {
throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
}
assert(keypool.vchPubKey.IsValid());
return keypool.nTime;
}
int64_t CWallet::GetOldestKeyPoolTime()
{
LOCK(cs_wallet);
CWalletDB walletdb(*dbw);
// load oldest key from keypool, get time and return
int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, walletdb);
if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT)) {
oldestKey = std::max(GetOldestKeyTimeInPool(setInternalKeyPool, walletdb), oldestKey);
}
return oldestKey;
}
std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
{
std::map<CTxDestination, CAmount> balances;
{
LOCK(cs_wallet);
for (const auto& walletEntry : mapWallet)
{
const CWalletTx *pcoin = &walletEntry.second;
if (!pcoin->IsTrusted())
continue;
if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
continue;
int nDepth = pcoin->GetDepthInMainChain();
if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
continue;
for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
{
CTxDestination addr;
if (!IsMine(pcoin->tx->vout[i]))
continue;
if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
continue;
CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
if (!balances.count(addr))
balances[addr] = 0;
balances[addr] += n;
}
}
}
return balances;
}
std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
{
AssertLockHeld(cs_wallet); // mapWallet
std::set< std::set<CTxDestination> > groupings;
std::set<CTxDestination> grouping;
for (const auto& walletEntry : mapWallet)
{
const CWalletTx *pcoin = &walletEntry.second;
if (pcoin->tx->vin.size() > 0)
{
bool any_mine = false;
// group all input addresses with each other
for (CTxIn txin : pcoin->tx->vin)
{
CTxDestination address;
if(!IsMine(txin)) /* If this input isn't mine, ignore it */
continue;
if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
continue;
grouping.insert(address);
any_mine = true;
}
// group change with input addresses
if (any_mine)
{
for (CTxOut txout : pcoin->tx->vout)
if (IsChange(txout))
{
CTxDestination txoutAddr;
if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
continue;
grouping.insert(txoutAddr);
}
}
if (grouping.size() > 0)
{
groupings.insert(grouping);
grouping.clear();
}
}
// group lone addrs by themselves
for (const auto& txout : pcoin->tx->vout)
if (IsMine(txout))
{
CTxDestination address;
if(!ExtractDestination(txout.scriptPubKey, address))
continue;
grouping.insert(address);
groupings.insert(grouping);
grouping.clear();
}
}
std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
for (std::set<CTxDestination> _grouping : groupings)
{
// make a set of all the groups hit by this new group
std::set< std::set<CTxDestination>* > hits;
std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
for (CTxDestination address : _grouping)
if ((it = setmap.find(address)) != setmap.end())
hits.insert((*it).second);
// merge all hit groups into a new single group and delete old groups
std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
for (std::set<CTxDestination>* hit : hits)
{
merged->insert(hit->begin(), hit->end());
uniqueGroupings.erase(hit);
delete hit;
}
uniqueGroupings.insert(merged);
// update setmap
for (CTxDestination element : *merged)
setmap[element] = merged;
}
std::set< std::set<CTxDestination> > ret;
for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
{
ret.insert(*uniqueGrouping);
delete uniqueGrouping;
}
return ret;
}
std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
{
LOCK(cs_wallet);
std::set<CTxDestination> result;
for (const std::pair<CTxDestination, CAddressBookData>& item : mapAddressBook)
{
const CTxDestination& address = item.first;
const std::string& strName = item.second.name;
if (strName == strAccount)
result.insert(address);
}
return result;
}
bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
{
if (nIndex == -1)
{
CKeyPool keypool;
pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
if (nIndex != -1)
vchPubKey = keypool.vchPubKey;
else {
return false;
}
fInternal = keypool.fInternal;
}
assert(vchPubKey.IsValid());
pubkey = vchPubKey;
return true;
}
void CReserveKey::KeepKey()
{
if (nIndex != -1)
pwallet->KeepKey(nIndex);
nIndex = -1;
vchPubKey = CPubKey();
}
void CReserveKey::ReturnKey()
{
if (nIndex != -1) {
pwallet->ReturnKey(nIndex, fInternal, vchPubKey);
}
nIndex = -1;
vchPubKey = CPubKey();
}
void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id)
{
AssertLockHeld(cs_wallet);
bool internal = setInternalKeyPool.count(keypool_id);
if (!internal) assert(setExternalKeyPool.count(keypool_id));
std::set<int64_t> *setKeyPool = internal ? &setInternalKeyPool : &setExternalKeyPool;
auto it = setKeyPool->begin();
CWalletDB walletdb(*dbw);
while (it != std::end(*setKeyPool)) {
const int64_t& index = *(it);
if (index > keypool_id) break; // set*KeyPool is ordered
CKeyPool keypool;
if (walletdb.ReadPool(index, keypool)) { //TODO: This should be unnecessary
m_pool_key_to_index.erase(keypool.vchPubKey.GetID());
}
walletdb.ErasePool(index);
LogPrintf("keypool index %d removed\n", index);
it = setKeyPool->erase(it);
}
}
void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
{
std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
CPubKey pubkey;
if (!rKey->GetReservedKey(pubkey))
{
return;
}
script = rKey;
script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
}
void CWallet::LockCoin(const COutPoint& output)
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.insert(output);
}
void CWallet::UnlockCoin(const COutPoint& output)
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.erase(output);
}
void CWallet::UnlockAllCoins()
{
AssertLockHeld(cs_wallet); // setLockedCoins
setLockedCoins.clear();
}
bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
{
AssertLockHeld(cs_wallet); // setLockedCoins
COutPoint outpt(hash, n);
return (setLockedCoins.count(outpt) > 0);
}
void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
{
AssertLockHeld(cs_wallet); // setLockedCoins
for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
it != setLockedCoins.end(); it++) {
COutPoint outpt = (*it);
vOutpts.push_back(outpt);
}
}
/** @} */ // end of Actions
void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
AssertLockHeld(cs_wallet); // mapKeyMetadata
mapKeyBirth.clear();
// get birth times for keys with metadata
for (const auto& entry : mapKeyMetadata) {
if (entry.second.nCreateTime) {
mapKeyBirth[entry.first] = entry.second.nCreateTime;
}
}
// map in which we'll infer heights of other keys
CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
for (const CKeyID &keyid : GetKeys()) {
if (mapKeyBirth.count(keyid) == 0)
mapKeyFirstBlock[keyid] = pindexMax;
}
// if there are no such keys, we're done
if (mapKeyFirstBlock.empty())
return;
// find first block that affects those keys, if there are any left
std::vector<CKeyID> vAffected;
for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
// iterate over all wallet transactions...
const CWalletTx &wtx = (*it).second;
BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
// ... which are already in a block
int nHeight = blit->second->nHeight;
for (const CTxOut &txout : wtx.tx->vout) {
// iterate over all their outputs
CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
for (const CKeyID &keyid : vAffected) {
// ... and all their affected keys
std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
rit->second = blit->second;
}
vAffected.clear();
}
}
}
// Extract block timestamps for those keys
for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
mapKeyBirth[it->first] = it->second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
}
/**
* Compute smart timestamp for a transaction being added to the wallet.
*
* Logic:
* - If sending a transaction, assign its timestamp to the current time.
* - If receiving a transaction outside a block, assign its timestamp to the
* current time.
* - If receiving a block with a future timestamp, assign all its (not already
* known) transactions' timestamps to the current time.
* - If receiving a block with a past timestamp, before the most recent known
* transaction (that we care about), assign all its (not already known)
* transactions' timestamps to the same timestamp as that most-recent-known
* transaction.
* - If receiving a block with a past timestamp, but after the most recent known
* transaction, assign all its (not already known) transactions' timestamps to
* the block time.
*
* For more information see CWalletTx::nTimeSmart,
* https://atlastalk.org/?topic=54527, or
* https://github.com/AtlasProject/Atlascoin/pull/1393.
*/
unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
{
unsigned int nTimeSmart = wtx.nTimeReceived;
if (!wtx.hashUnset()) {
if (mapBlockIndex.count(wtx.hashBlock)) {
int64_t latestNow = wtx.nTimeReceived;
int64_t latestEntry = 0;
// Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
int64_t latestTolerated = latestNow + 300;
const TxItems& txOrdered = wtxOrdered;
for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
CWalletTx* const pwtx = it->second.first;
if (pwtx == &wtx) {
continue;
}
CAccountingEntry* const pacentry = it->second.second;
int64_t nSmartTime;
if (pwtx) {
nSmartTime = pwtx->nTimeSmart;
if (!nSmartTime) {
nSmartTime = pwtx->nTimeReceived;
}
} else {
nSmartTime = pacentry->nTime;
}
if (nSmartTime <= latestTolerated) {
latestEntry = nSmartTime;
if (nSmartTime > latestNow) {
latestNow = nSmartTime;
}
break;
}
}
int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
} else {
LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
}
}
return nTimeSmart;
}
bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
{
if (boost::get<CNoDestination>(&dest))
return false;
mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
return CWalletDB(*dbw).WriteDestData(EncodeDestination(dest), key, value);
}
bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
{
if (!mapAddressBook[dest].destdata.erase(key))
return false;
return CWalletDB(*dbw).EraseDestData(EncodeDestination(dest), key);
}
bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
{
mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
return true;
}
bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
{
std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
if(i != mapAddressBook.end())
{
CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
if(j != i->second.destdata.end())
{
if(value)
*value = j->second;
return true;
}
}
return false;
}
std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
{
LOCK(cs_wallet);
std::vector<std::string> values;
for (const auto& address : mapAddressBook) {
for (const auto& data : address.second.destdata) {
if (!data.first.compare(0, prefix.size(), prefix)) {
values.emplace_back(data.second);
}
}
}
return values;
}
CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
{
// needed to restore wallet transaction meta data after -zapwallettxes
std::vector<CWalletTx> vWtx;
if (gArgs.GetBoolArg("-zapwallettxes", false)) {
uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
std::unique_ptr<CWallet> tempWallet(new CWallet(std::move(dbw)));
DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
if (nZapWalletRet != DB_LOAD_OK) {
InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
return nullptr;
}
}
uiInterface.InitMessage(_("Loading wallet..."));
int64_t nStart = GetTimeMillis();
bool fFirstRun = true;
std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
CWallet *walletInstance = new CWallet(std::move(dbw));
DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT) {
InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
return nullptr;
}
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."),
walletFile));
}
else if (nLoadWalletRet == DB_TOO_NEW) {
InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
return nullptr;
}
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
return nullptr;
}
else {
InitError(strprintf(_("Error loading %s"), walletFile));
return nullptr;
}
}
if (gArgs.GetBoolArg("-upgradewallet", fFirstRun))
{
int nMaxVersion = gArgs.GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
}
else
LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < walletInstance->GetVersion())
{
InitError(_("Cannot downgrade wallet"));
return nullptr;
}
walletInstance->SetMaxVersion(nMaxVersion);
}
if (fFirstRun)
{
// ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
if (!gArgs.GetBoolArg("-usehd", true)) {
InitError(strprintf(_("Error creating %s: You can't create non-HD wallets with this version."), walletFile));
return nullptr;
}
walletInstance->SetMinVersion(FEATURE_NO_DEFAULT_KEY);
// generate a new seed
CPubKey seed = walletInstance->GenerateNewSeed();
if (!walletInstance->SetHDSeed(seed))
throw std::runtime_error(std::string(__func__) + ": Storing HD seed failed");
// Top up the keypool
if (!walletInstance->TopUpKeyPool()) {
InitError(_("Unable to generate initial keys") += "\n");
return nullptr;
}
walletInstance->SetBestChain(chainActive.GetLocator());
}
else if (gArgs.IsArgSet("-usehd")) {
bool useHD = gArgs.GetBoolArg("-usehd", true);
if (walletInstance->IsHDEnabled() && !useHD) {
InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile));
return nullptr;
}
if (!walletInstance->IsHDEnabled() && useHD) {
InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile));
return nullptr;
}
}
LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
RegisterValidationInterface(walletInstance);
// Try to top up keypool. No-op if the wallet is locked.
walletInstance->TopUpKeyPool();
CBlockIndex *pindexRescan = chainActive.Genesis();
if (!gArgs.GetBoolArg("-rescan", false))
{
CWalletDB walletdb(*walletInstance->dbw);
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = FindForkInGlobalIndex(chainActive, locator);
}
if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
{
//We can't rescan beyond non-pruned blocks, stop and throw an error
//this might happen if a user uses an old wallet within a pruned node
// or if he ran -disablewallet for a longer time, then decided to re-enable
if (fPruneMode)
{
CBlockIndex *block = chainActive.Tip();
while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
block = block->pprev;
if (pindexRescan != block) {
InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
return nullptr;
}
}
uiInterface.InitMessage(_("Rescanning..."));
LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
// No need to read and scan block if block was created before
// our wallet birthday (as adjusted for block time variability)
while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
pindexRescan = chainActive.Next(pindexRescan);
}
nStart = GetTimeMillis();
walletInstance->ScanForWalletTransactions(pindexRescan, nullptr, true);
LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
walletInstance->SetBestChain(chainActive.GetLocator());
walletInstance->dbw->IncrementUpdateCounter();
// Restore wallet transaction metadata after -zapwallettxes=1
if (gArgs.GetBoolArg("-zapwallettxes", false) && gArgs.GetArg("-zapwallettxes", "1") != "2")
{
CWalletDB walletdb(*walletInstance->dbw);
for (const CWalletTx& wtxOld : vWtx)
{
uint256 hash = wtxOld.GetHash();
std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
if (mi != walletInstance->mapWallet.end())
{
const CWalletTx* copyFrom = &wtxOld;
CWalletTx* copyTo = &mi->second;
copyTo->mapValue = copyFrom->mapValue;
copyTo->vOrderForm = copyFrom->vOrderForm;
copyTo->nTimeReceived = copyFrom->nTimeReceived;
copyTo->nTimeSmart = copyFrom->nTimeSmart;
copyTo->fFromMe = copyFrom->fFromMe;
copyTo->strFromAccount = copyFrom->strFromAccount;
copyTo->nOrderPos = copyFrom->nOrderPos;
walletdb.WriteTx(*copyTo);
}
}
}
}
walletInstance->SetBroadcastTransactions(gArgs.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
{
LOCK(walletInstance->cs_wallet);
LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
}
return walletInstance;
}
std::atomic<bool> CWallet::fFlushScheduled(false);
void CWallet::postInitProcess(CScheduler& scheduler)
{
// Add wallet transactions that aren't already in a block to mempool
// Do this here as mempool requires genesis block to be loaded
ReacceptWalletTransactions();
// Run a thread to flush wallet periodically
if (!CWallet::fFlushScheduled.exchange(true)) {
scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
}
}
bool CWallet::BackupWallet(const std::string& strDest)
{
return dbw->Backup(strDest);
}
CKeyPool::CKeyPool()
{
nTime = GetTime();
fInternal = false;
}
CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
{
nTime = GetTime();
vchPubKey = vchPubKeyIn;
fInternal = internalIn;
}
CWalletKey::CWalletKey(int64_t nExpires)
{
nTimeCreated = (nExpires ? GetTime() : 0);
nTimeExpires = nExpires;
}
void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
{
// Update the tx's hashBlock
hashBlock = pindex->GetBlockHash();
// set the position of the transaction in the block
nIndex = posInBlock;
}
int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
{
if (hashUnset())
return 0;
AssertLockHeld(cs_main);
// Find the block it claims to be in
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !chainActive.Contains(pindex))
return 0;
pindexRet = pindex;
return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!IsCoinBase())
return 0;
return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
}
bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
{
return ::AcceptToMemoryPool(mempool, state, tx, nullptr /* pfMissingInputs */,
nullptr /* plTxnReplaced */, false /* bypass_limits */, nAbsurdFee);
}
| [
"tytek2012@gmail.com"
] | tytek2012@gmail.com |
76250cfc3e8d3fdee22df78981ee158920f82865 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /ash/touch/touch_uma.cc | 4ae3adcf97ee2383a8429db685e84d602ae1d86f | [
"BSD-3-Clause"
] | 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 | 10,965 | 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 "ash/touch/touch_uma.h"
#include "ash/common/wm_shell.h"
#include "base/metrics/histogram.h"
#include "base/strings/stringprintf.h"
#include "ui/aura/env.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/aura/window_property.h"
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/views/widget/widget.h"
#if defined(USE_X11)
#include <X11/extensions/XInput2.h>
#include <X11/Xlib.h>
#endif
namespace {
struct WindowTouchDetails {
// Move and start times of the touch points. The key is the touch-id.
std::map<int, base::TimeTicks> last_move_time_;
std::map<int, base::TimeTicks> last_start_time_;
// The first and last positions of the touch points.
std::map<int, gfx::Point> start_touch_position_;
std::map<int, gfx::Point> last_touch_position_;
// Last time-stamp of the last touch-end event.
base::TimeTicks last_release_time_;
// Stores the time of the last touch released on this window (if there was a
// multi-touch gesture on the window, then this is the release-time of the
// last touch on the window).
base::TimeTicks last_mt_time_;
};
DEFINE_OWNED_WINDOW_PROPERTY_KEY(WindowTouchDetails, kWindowTouchDetails, NULL);
}
DECLARE_WINDOW_PROPERTY_TYPE(WindowTouchDetails*);
namespace ash {
// static
TouchUMA* TouchUMA::GetInstance() {
return base::Singleton<TouchUMA>::get();
}
void TouchUMA::RecordGestureEvent(aura::Window* target,
const ui::GestureEvent& event) {
GestureActionType action = FindGestureActionType(target, event);
RecordGestureAction(action);
if (event.type() == ui::ET_GESTURE_END &&
event.details().touch_points() == 2) {
WindowTouchDetails* details = target->GetProperty(kWindowTouchDetails);
if (!details) {
LOG(ERROR) << "Window received gesture events without receiving any touch"
" events";
return;
}
details->last_mt_time_ = event.time_stamp();
}
}
void TouchUMA::RecordGestureAction(GestureActionType action) {
if (action == GESTURE_UNKNOWN || action >= GESTURE_ACTION_COUNT)
return;
UMA_HISTOGRAM_ENUMERATION("Ash.GestureTarget", action, GESTURE_ACTION_COUNT);
}
void TouchUMA::RecordTouchEvent(aura::Window* target,
const ui::TouchEvent& event) {
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Ash.TouchRadius",
static_cast<int>(std::max(event.pointer_details().radius_x,
event.pointer_details().radius_y)),
1, 500, 100);
UpdateTouchState(event);
WindowTouchDetails* details = target->GetProperty(kWindowTouchDetails);
if (!details) {
details = new WindowTouchDetails;
target->SetProperty(kWindowTouchDetails, details);
}
// Record the location of the touch points.
const int kBucketCountForLocation = 100;
const gfx::Rect bounds = target->GetRootWindow()->bounds();
const int bucket_size_x =
std::max(1, bounds.width() / kBucketCountForLocation);
const int bucket_size_y =
std::max(1, bounds.height() / kBucketCountForLocation);
gfx::Point position = event.root_location();
// Prefer raw event location (when available) over calibrated location.
if (event.HasNativeEvent()) {
position = ui::EventLocationFromNative(event.native_event());
position = gfx::ScaleToFlooredPoint(
position, 1.f / target->layer()->device_scale_factor());
}
position.set_x(std::min(bounds.width() - 1, std::max(0, position.x())));
position.set_y(std::min(bounds.height() - 1, std::max(0, position.y())));
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Ash.TouchPositionX", position.x() / bucket_size_x, 1,
kBucketCountForLocation, kBucketCountForLocation + 1);
UMA_HISTOGRAM_CUSTOM_COUNTS(
"Ash.TouchPositionY", position.y() / bucket_size_y, 1,
kBucketCountForLocation, kBucketCountForLocation + 1);
if (event.type() == ui::ET_TOUCH_PRESSED) {
WmShell::Get()->RecordUserMetricsAction(UMA_TOUCHSCREEN_TAP_DOWN);
details->last_start_time_[event.touch_id()] = event.time_stamp();
details->start_touch_position_[event.touch_id()] = event.root_location();
details->last_touch_position_[event.touch_id()] = event.location();
if (details->last_release_time_.ToInternalValue()) {
// Measuring the interval between a touch-release and the next
// touch-start is probably less useful when doing multi-touch (e.g.
// gestures, or multi-touch friendly apps). So count this only if the user
// hasn't done any multi-touch during the last 30 seconds.
base::TimeDelta diff = event.time_stamp() - details->last_mt_time_;
if (diff.InSeconds() > 30) {
base::TimeDelta gap = event.time_stamp() - details->last_release_time_;
UMA_HISTOGRAM_COUNTS_10000("Ash.TouchStartAfterEnd",
gap.InMilliseconds());
}
}
// Record the number of touch-points currently active for the window.
const int kMaxTouchPoints = 10;
UMA_HISTOGRAM_CUSTOM_COUNTS("Ash.ActiveTouchPoints",
details->last_start_time_.size(), 1,
kMaxTouchPoints, kMaxTouchPoints + 1);
} else if (event.type() == ui::ET_TOUCH_RELEASED) {
if (details->last_start_time_.count(event.touch_id())) {
base::TimeDelta duration =
event.time_stamp() - details->last_start_time_[event.touch_id()];
// Look for touches that were [almost] stationary for a long time.
const double kLongStationaryTouchDuration = 10;
const int kLongStationaryTouchDistanceSquared = 100;
if (duration.InSecondsF() > kLongStationaryTouchDuration) {
gfx::Vector2d distance =
event.root_location() -
details->start_touch_position_[event.touch_id()];
if (distance.LengthSquared() < kLongStationaryTouchDistanceSquared) {
UMA_HISTOGRAM_CUSTOM_COUNTS("Ash.StationaryTouchDuration",
duration.InSeconds(),
kLongStationaryTouchDuration, 1000, 20);
}
}
}
details->last_start_time_.erase(event.touch_id());
details->last_move_time_.erase(event.touch_id());
details->start_touch_position_.erase(event.touch_id());
details->last_touch_position_.erase(event.touch_id());
details->last_release_time_ = event.time_stamp();
} else if (event.type() == ui::ET_TOUCH_MOVED) {
int distance = 0;
if (details->last_touch_position_.count(event.touch_id())) {
gfx::Point lastpos = details->last_touch_position_[event.touch_id()];
distance =
std::abs(lastpos.x() - event.x()) + std::abs(lastpos.y() - event.y());
}
if (details->last_move_time_.count(event.touch_id())) {
base::TimeDelta move_delay =
event.time_stamp() - details->last_move_time_[event.touch_id()];
UMA_HISTOGRAM_CUSTOM_COUNTS("Ash.TouchMoveInterval",
move_delay.InMilliseconds(), 1, 50, 25);
}
UMA_HISTOGRAM_CUSTOM_COUNTS("Ash.TouchMoveSteps", distance, 1, 1000, 50);
details->last_move_time_[event.touch_id()] = event.time_stamp();
details->last_touch_position_[event.touch_id()] = event.location();
}
}
TouchUMA::TouchUMA()
: is_single_finger_gesture_(false),
touch_in_progress_(false),
burst_length_(0) {}
TouchUMA::~TouchUMA() {}
void TouchUMA::UpdateTouchState(const ui::TouchEvent& event) {
if (event.type() == ui::ET_TOUCH_PRESSED) {
if (!touch_in_progress_) {
is_single_finger_gesture_ = true;
base::TimeDelta difference = event.time_stamp() - last_touch_down_time_;
if (difference > base::TimeDelta::FromMilliseconds(250)) {
if (burst_length_) {
UMA_HISTOGRAM_COUNTS_100("Ash.TouchStartBurst",
std::min(burst_length_, 100));
}
burst_length_ = 1;
} else {
++burst_length_;
}
} else {
is_single_finger_gesture_ = false;
}
touch_in_progress_ = true;
last_touch_down_time_ = event.time_stamp();
} else if (event.type() == ui::ET_TOUCH_RELEASED) {
if (!aura::Env::GetInstance()->is_touch_down())
touch_in_progress_ = false;
}
}
GestureActionType TouchUMA::FindGestureActionType(
aura::Window* window,
const ui::GestureEvent& event) {
if (!window || window->GetRootWindow() == window) {
if (event.type() == ui::ET_GESTURE_SCROLL_BEGIN)
return GESTURE_BEZEL_SCROLL;
if (event.type() == ui::ET_GESTURE_BEGIN)
return GESTURE_BEZEL_DOWN;
return GESTURE_UNKNOWN;
}
std::string name = window ? window->name() : std::string();
const char kWallpaperView[] = "WallpaperView";
if (name == kWallpaperView) {
if (event.type() == ui::ET_GESTURE_SCROLL_BEGIN)
return GESTURE_DESKTOP_SCROLL;
if (event.type() == ui::ET_GESTURE_PINCH_BEGIN)
return GESTURE_DESKTOP_PINCH;
return GESTURE_UNKNOWN;
}
const char kWebPage[] = "RenderWidgetHostViewAura";
if (name == kWebPage) {
if (event.type() == ui::ET_GESTURE_PINCH_BEGIN)
return GESTURE_WEBPAGE_PINCH;
if (event.type() == ui::ET_GESTURE_SCROLL_BEGIN)
return GESTURE_WEBPAGE_SCROLL;
if (event.type() == ui::ET_GESTURE_TAP)
return GESTURE_WEBPAGE_TAP;
return GESTURE_UNKNOWN;
}
views::Widget* widget = views::Widget::GetWidgetForNativeView(window);
if (!widget)
return GESTURE_UNKNOWN;
// |widget| may be in the process of destroying if it has ownership
// views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET and |event| was
// dispatched as part of gesture state cleanup. In this case the RootView
// of |widget| may no longer exist, so check before calling into any
// RootView methods.
if (!widget->GetRootView())
return GESTURE_UNKNOWN;
views::View* view =
widget->GetRootView()->GetEventHandlerForPoint(event.location());
if (!view)
return GESTURE_UNKNOWN;
name = view->GetClassName();
const char kTabStrip[] = "TabStrip";
const char kTab[] = "BrowserTab";
if (name == kTabStrip || name == kTab) {
if (event.type() == ui::ET_GESTURE_SCROLL_BEGIN)
return GESTURE_TABSTRIP_SCROLL;
if (event.type() == ui::ET_GESTURE_PINCH_BEGIN)
return GESTURE_TABSTRIP_PINCH;
if (event.type() == ui::ET_GESTURE_TAP)
return GESTURE_TABSTRIP_TAP;
return GESTURE_UNKNOWN;
}
const char kOmnibox[] = "BrowserOmniboxViewViews";
if (name == kOmnibox) {
if (event.type() == ui::ET_GESTURE_SCROLL_BEGIN)
return GESTURE_OMNIBOX_SCROLL;
if (event.type() == ui::ET_GESTURE_PINCH_BEGIN)
return GESTURE_OMNIBOX_PINCH;
return GESTURE_UNKNOWN;
}
return GESTURE_UNKNOWN;
}
} // namespace ash
| [
"enrico.weigelt@gr13.net"
] | enrico.weigelt@gr13.net |
e2b7d2f823ded9be5bbd11c2b9a8d846aef07bf2 | 4e7300d79bbdcaa9f70fff786fe0d8dc71cf3635 | /source/group.cpp | 74306c18056ea7e3b37791ac68afcc2244db993e | [] | no_license | busratican/ComputerGraphics-Assign3 | 4173ec5876f05ac49a49d4e752fdd8fdb2cc40c5 | 93f107b13d832efbdd406dc4a5971511edc79c8e | refs/heads/master | 2021-01-01T06:36:29.440181 | 2017-07-17T11:08:02 | 2017-07-17T11:08:02 | 97,467,174 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 423 | cpp | #include "group.h"
Group::Group(int n) { numObjects = n; index.resize(n); }
Group::~Group() { index.clear(); }
bool Group::intersect(const Ray &r, Hit &h, float tmin)
{
bool __r = false;
for(int i=0;i<numObjects;i++)
{
if(index[i]->intersect(r,h,tmin))
__r = true;
}
return __r;
}
void Group::addObject(int i, Object3D *obj)
{
assert(i < numObjects);
index[i] = obj;
}
| [
"gulbusra55@gmail.com"
] | gulbusra55@gmail.com |
f437506ef4b516b0bc805de5ed43b1d527332389 | ce920bd897afa6135f3f1a3c777416eb390555cb | /include/sqlite.hh | 3729743518c20bf55abec57b1cd2a69c12937e61 | [] | no_license | ivankp/server_old_1 | 64095f03ed58c8599ebf1d5e9709a657a4f70e2e | fa7e4bb53751190057aabe571b8bfb7dbb1e8f03 | refs/heads/master | 2023-05-01T00:08:17.345373 | 2021-05-18T17:46:30 | 2021-05-18T17:46:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,305 | hh | #ifndef IVANP_SQLITE_HH
#define IVANP_SQLITE_HH
#include <iostream>
#include <iomanip>
#include <concepts>
#include "sqlite3/sqlite3.h"
// https://sqlite.org/cintro.html
#include "base64.hh"
#include "error.hh"
#define THROW_SQLITE(...) ERROR(__VA_ARGS__,": ",errmsg())
class sqlite {
sqlite3* db = nullptr;
public:
const char* errmsg() const noexcept { return sqlite3_errmsg(db); }
sqlite(const char* filename) {
if (sqlite3_open(filename,&db) != SQLITE_OK)
THROW_SQLITE("sqlite3_open()");
}
~sqlite() {
if (sqlite3_close(db) != SQLITE_OK)
std::cerr << IVANP_ERROR_PREF "sqlite3_close()"
<< errmsg() << std::endl;
}
sqlite(const sqlite&) = delete;
sqlite& operator=(const sqlite&) = delete;
sqlite& operator=(sqlite&& o) noexcept {
std::swap(db,o.db);
return *this;
}
sqlite(sqlite&& o) noexcept { std::swap(db,o.db); }
sqlite3* operator+() noexcept { return db; }
const sqlite3* operator+() const noexcept { return db; }
class value {
sqlite3_value* p = nullptr;
public:
value() noexcept = default;
value(sqlite3_value* p) noexcept: p(sqlite3_value_dup(p)) { }
~value() { sqlite3_value_free(p); }
value(const value& o) noexcept: value(o.p) { }
value(value&& o) noexcept { std::swap(p,o.p); }
value& operator=(const value& o) noexcept {
p = sqlite3_value_dup(o.p);
return *this;
}
value& operator=(value&& o) noexcept {
std::swap(p,o.p);
return *this;
}
sqlite3_value* operator+() noexcept { return p; }
const sqlite3_value* operator+() const noexcept { return p; }
int type() const noexcept { return sqlite3_value_type(p); }
int bytes() const noexcept { return sqlite3_value_bytes(p); }
int as_int() const noexcept { return sqlite3_value_int(p); }
sqlite3_int64 as_int64() const noexcept { return sqlite3_value_int64(p); }
double as_double() const noexcept { return sqlite3_value_double(p); }
const void* as_blob() const noexcept { return sqlite3_value_blob(p); }
const char* as_text() const noexcept {
return reinterpret_cast<const char*>(sqlite3_value_text(p));
}
template <typename T> requires std::integral<T>
T as() const noexcept {
if constexpr (sizeof(T) < 8) return as_int();
else return as_int64();
}
template <typename T> requires std::floating_point<T>
T as() const noexcept { return as_double(); }
template <typename T> requires std::constructible_from<T,const char*>
T as() const noexcept { return T(as_text()); }
template <typename T> requires std::same_as<T,const void*>
T as() const noexcept { return as_blob(); }
bool operator==(const value& o) const noexcept {
const auto len = bytes();
return (o.bytes() == len) && !memcmp(as_blob(),o.as_blob(),len);
}
bool operator<(const value& o) const noexcept {
const auto len = bytes();
const auto len_o = o.bytes();
auto cmp = memcmp(as_blob(),o.as_blob(),(len < len_o ? len : len_o));
return cmp ? (cmp < 0) : (len < len_o);
}
bool operator!=(const value& o) const noexcept { return !((*this) == o); }
bool operator!() const noexcept {
return !p || type() == SQLITE_NULL;
}
};
class stmt {
sqlite3_stmt *p = nullptr;
public:
sqlite3* db_handle() const noexcept { return sqlite3_db_handle(p); }
const char* errmsg() const noexcept { return sqlite3_errmsg(db_handle()); }
stmt(sqlite3 *db, const char* sql, bool persist=false) {
if (sqlite3_prepare_v3(
db, sql, -1,
persist ? SQLITE_PREPARE_PERSISTENT : 0,
&p, nullptr
) != SQLITE_OK) THROW_SQLITE("sqlite3_prepare_v3()");
}
stmt(sqlite3 *db, std::string_view sql, bool persist=false) {
if (sqlite3_prepare_v3(
db, sql.data(), sql.size(),
persist ? SQLITE_PREPARE_PERSISTENT : 0,
&p, nullptr
) != SQLITE_OK) THROW_SQLITE("sqlite3_prepare_v3()");
}
~stmt() {
if (sqlite3_finalize(p) != SQLITE_OK)
std::cerr << IVANP_ERROR_PREF "sqlite3_finalize()"
<< errmsg() << std::endl;
}
stmt(const stmt&) = delete;
stmt& operator=(const stmt&) = delete;
stmt& operator=(stmt&& o) noexcept {
std::swap(p,o.p);
return *this;
}
stmt(stmt&& o) noexcept { std::swap(p,o.p); }
sqlite3_stmt* operator+() noexcept { return p; }
const sqlite3_stmt* operator+() const noexcept { return p; }
bool step() {
switch (sqlite3_step(p)) {
case SQLITE_ROW: return true;
case SQLITE_DONE: return false;
default: THROW_SQLITE("sqlite3_step()");
}
}
stmt& reset() {
if (sqlite3_reset(p) != SQLITE_OK)
THROW_SQLITE("sqlite3_reset()");
return *this;
}
// bind ---------------------------------------------------------
stmt& bind(int i, std::floating_point auto x) {
if (sqlite3_bind_double(p, i, x) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_double()");
return *this;
}
template <std::integral T>
stmt& bind(int i, T x) {
if constexpr (sizeof(T) < 8) {
if (sqlite3_bind_int(p, i, x) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_int()");
} else {
if (sqlite3_bind_int64(p, i, x) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_int64()");
}
return *this;
}
stmt& bind(int i) {
if (sqlite3_bind_null(p, i) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_null()");
return *this;
}
stmt& bind(int i, std::nullptr_t) {
if (sqlite3_bind_null(p, i) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_null()");
return *this;
}
stmt& bind(int i, const char* x, int n=-1, bool trans=true) {
if (sqlite3_bind_text(p, i, x, n,
trans ? SQLITE_TRANSIENT : SQLITE_STATIC
) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_text()");
return *this;
}
stmt& bind(int i, std::string_view x, bool trans=true) {
if (sqlite3_bind_text(p, i, x.data(), x.size(),
trans ? SQLITE_TRANSIENT : SQLITE_STATIC
) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_text()");
return *this;
}
stmt& bind(int i, const void* x, int n, bool trans=true) {
if (sqlite3_bind_blob(p, i, x, n,
trans ? SQLITE_TRANSIENT : SQLITE_STATIC
) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_blob()");
return *this;
}
stmt& bind(int i, std::nullptr_t, int n) {
if (sqlite3_bind_zeroblob(p, i, n) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_zeroblob()");
return *this;
}
stmt& bind(int i, const value& x) {
if (sqlite3_bind_value(p, i, +x) != SQLITE_OK)
THROW_SQLITE("sqlite3_bind_value()");
return *this;
}
template <typename... T>
stmt& bind_all(T&&... x) {
int i = 0;
return (bind(++i,std::forward<T>(x)), ...);
}
// column -------------------------------------------------------
int column_count() noexcept {
return sqlite3_column_count(p);
}
double column_double(int i) noexcept {
return sqlite3_column_double(p, i);
}
int column_int(int i) noexcept {
return sqlite3_column_int(p, i);
}
sqlite3_int64 column_int64(int i) noexcept {
return sqlite3_column_int64(p, i);
}
const char* column_text(int i) noexcept {
return reinterpret_cast<const char*>(sqlite3_column_text(p, i));
}
const void* column_blob(int i) noexcept {
return sqlite3_column_blob(p, i);
}
value column_value(int i) noexcept {
return sqlite3_column_value(p, i);
}
int column_bytes(int i) noexcept {
return sqlite3_column_bytes(p, i);
}
int column_type(int i) noexcept {
// SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB, or SQLITE_NULL
return sqlite3_column_type(p, i);
}
const char* column_name(int i) noexcept {
return sqlite3_column_name(p, i);
}
template <typename T> requires std::integral<T>
T column(int i) noexcept {
if constexpr (sizeof(T) < 8) return column_int(i);
else return column_int64(i);
}
template <typename T> requires std::floating_point<T>
T column(int i) noexcept { return column_double(i); }
template <typename T> requires std::constructible_from<T,const char*>
T column(int i) noexcept { return T(column_text(i)); }
template <typename T> requires std::same_as<T,const void*>
T column(int i) noexcept { return column_blob(i); }
std::string json() {
std::stringstream ss;
ss << '[';
for (int i=0, n=column_count(); i<n; ++i) {
if (i) ss << ',';
switch (column_type(i)) {
case SQLITE_INTEGER:
ss << column_int(i);
break;
case SQLITE_FLOAT:
ss << column_double(i);
break;
case SQLITE_TEXT:
ss << std::quoted(column_text(i));
break;
case SQLITE_BLOB: {
ss << '"' << base64_encode(
reinterpret_cast<const char*>(column_blob(i)),
column_bytes(i)
) << '"';
}; break;
case SQLITE_NULL:
ss << "null";
break;
}
}
ss << ']';
return std::move(ss).str();
}
};
stmt prepare(auto sql, bool persist=false) { return { db, sql, persist }; }
template <typename F>
sqlite& exec(const char* sql, F&& f) {
char* err;
if (sqlite3_exec(db,sql,
+[](
void* arg, // 4th argument of sqlite3_exec()
int ncol, // number of columns
char** row, // pointers to strings obtained as if from sqlite3_column_text()
char** cols_names // names of columns
) -> int {
(*reinterpret_cast<F*>(arg))(ncol,row,cols_names);
return 0;
}, reinterpret_cast<void*>(&f), &err
) != SQLITE_OK) ERROR("sqlite3_exec(): ",err);
return *this;
}
sqlite& exec(const char* sql) {
char* err;
if (sqlite3_exec(db,sql,nullptr,nullptr,&err) != SQLITE_OK)
ERROR("sqlite3_exec(): ",err);
return *this;
}
template <typename... F> requires (sizeof...(F)<2)
sqlite& operator()(const char* sql, F&&... f) {
return exec(sql,std::forward<F>(f)...);
}
};
#endif
| [
"ivan.pogrebnyak@gmail.com"
] | ivan.pogrebnyak@gmail.com |
0a2d0c2057b402d1c28069e126e3e033aa15a34e | a4008ca31634dcafe53137267d7b2df4572605bc | /reco/HitClustering/STClusterizerCurveTrack.hh | 0ef04685a69e412eb0b07515292e0903f7de6ac8 | [] | no_license | SpiRIT-Collaboration/SpiRITROOT | 416f766d59110b23f14b3f8c5647c649d5c42efb | 0f5154b75e5db0d736373386e1481caa7c2ff03c | refs/heads/develop | 2023-03-10T15:25:16.906623 | 2022-01-21T17:42:01 | 2022-01-21T17:42:01 | 19,332,445 | 6 | 3 | null | 2018-12-19T09:04:44 | 2014-05-01T01:20:47 | C++ | UTF-8 | C++ | false | false | 873 | hh | #ifndef STCLUSTERIZERCURVETRACK
#define STCLUSTERIZERCURVETRACK
#include "STClusterizer.hh"
#include "STCurveTrackFitter.hh"
#include "STCircleFitter.hh"
#include "STRiemannFitter.hh"
#include "STHitCluster.hh"
#include "TMath.h"
#include "TVector3.h"
class STClusterizerCurveTrack : public STClusterizer
{
public:
STClusterizerCurveTrack();
~STClusterizerCurveTrack();
void AnalyzeTrack(TClonesArray* trackArray, STEvent* eventOut);
void AnalyzeTrack(TClonesArray *trackArray, TClonesArray *clusterArray);
void AnalyzeSingleTrack(STCurveTrack *track, TClonesArray *clusterArray);
private:
STHitCluster* NewCluster(STHit* hit, TClonesArray *array);
TClonesArray *fClusterArray;
STCurveTrackFitter *fTrackFitter;
STRiemannFitter *fRiemannFitter;
STCurveTrack *fTracker;
ClassDef(STClusterizerCurveTrack, 1)
};
#endif
| [
"phyjics@gmail.com"
] | phyjics@gmail.com |
e32fb1861165772e7f2ae4bb2e750049e3b48ea2 | 35155c04e6eb4d65737cfc5477990479d40f47a6 | /scripts/x-test-fem/x-test-neb/test-case-1-sin-buckle/src/murty95.cpp | 8f7b0c843be13783acc76981988d780422e89d38 | [] | no_license | XiaohanZhangCMU/mdGpy | b1476fb829e95c21ff0bb86ad2047e280dc2c796 | 90916bfb9cb2604b6f3341c8b7c5b37380a6679d | refs/heads/master | 2020-03-20T18:40:06.092597 | 2018-06-16T17:56:39 | 2018-06-16T17:56:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,587 | cpp | /*
murty95.h
by Keonwook Kang kwkang75@yonsei.ac.kr
Last Modified :
FUNCTION :
Reference: M. V. Ramana Murty and Harry A. Atwater
"Empirical interatomic potential for Si-H interactions"
Phys. Rev. B, 51, 4889 (1995)
Si-Si interaction is based on
J. Tersoff, Empirical interatomic potential for silicon
with improved elastic properties
Phys. Rev. B, 38, 9902 (1988), Si(C)
H-H interaction is based on
D. W. Brenner, "Empirical potential for hydrogen for use
in simulating the chemical vapor deposition of diamond films"
Phys. Rev. B, 42, 9458 (1990)
Note: Implemented by modifying tersoff.cpp
The cut-off fuction f_c in eqn.(4) is identical expression
with the cut-off function in Tersoff PRB 39 5566(1989).
Just, R_{ij} = R-D and S_{ij} = R+D or
R = (R_{ij} + S_{ij})/2, D = - (R_{ij} - S_{ij})/2
*/
#include "murty95.h"
inline double spline(double spline_coeff[4], double func[], int ind, double x)
{
/* cubic spline based on Lagrange polynomials
f(x) = a_i/(6*h_i)*(x_{i+1} - x)^3 + a_{i+1}/(6*h_i)*(x-x_i)^3
+ (y_i/h_i-a_i*h_i/6)*(x_{i+1}-x)
+ (y_{i+1}/h_i-a_{i+1}*h_i/6)*(x-x_i)
where h_i = x_{i+1}-x_i
*/
int xi, xip1;
double a, b, fi, fip1, f;
double pp, pp2, pp3;
double qq, qq2, qq3;
xi = ind; xip1 = ind+1;
a = spline_coeff[ind];
b = spline_coeff[ind+1];
fi = func[ind]; fip1 = func[ind+1];
pp = x-xi; pp2 = pp*pp; pp3=pp2*pp;
qq = xip1-x; qq2=qq*qq; qq3=qq2*qq;
f=a/6.0*qq3+b/6.0*pp3+(fi-a/6.0)*qq+(fip1-b/6.0)*pp;
return f;
}
void compute_spline_coeff(int ngrd, double func[],double h, double spline_coeff[])
{
int i,ind,n=ngrd-2;
if (n<1) ERROR("Increase ngrd in murty95.h");
double dia[n], adia[n-1], bdia[n-1], B[n], x[n];
/* Thomas algorithm to solve Ax=B
A = [2h h 0 0 ...
h 2h h 0 ...
0 h 2h h ...
...
h 2h ] */
for (i=0;i<n;i++)
{
dia[i]=2.0*h; B[i] = 6.0*(func[i+2]-func[i])/h;
}
for (i=0;i<(n-1);i++)
{
adia[i]=h; // above diagonal
bdia[i]=h; // below diagonal
}
adia[0]=adia[0]/dia[0];
B[0]=B[0]/dia[0];
for (i=1;i<(n-1);i++)
{
adia[i]=adia[i]/(dia[i]-bdia[i-1]*adia[i-1]);
B[i]=(B[i]-bdia[i-1]*B[i-1])/(dia[i]-bdia[i-1]*adia[i-1]);
}
B[n-1]=(B[n-1]-bdia[n-2]*B[n-2])/(dia[n-1]-bdia[n-2]*adia[n-2]);
x[n-1]=B[n-1];
for (i=n-2;i>=0;i--)
x[i]=B[i]-adia[i]*x[i+1];
/* natural cubic spline :
the 2nd derivatives at the endpoints are zero */
spline_coeff[0] = 0.0;
for(ind=1;ind<ngrd-1;ind++)
{
spline_coeff[ind] = x[ind-1];
}
spline_coeff[ngrd-1] = 0.0;
}
void Murty95Frame::initvars()
{
#ifdef _MA_ORIG
/* Fitting parameters for Si-Si, PRB 51 4889 (1995) */
A_SiSi = 1.8308e3; // A (eV)
B_SiSi = 4.7118e2; // B (eV)
Lam_SiSi = 2.4799; // lambda_1 (1/\AA)
Mu_SiSi = 1.7322; // lambda_2 (1/\AA)
Alpha_SiSi = 5.1975; //
Beta_SiSi = 3.0; // beta
R0_SiSi = 2.35; // equilibrium distance to 1nn (\AA)
R_SiSi = 2.85; // R (\AA)
D_SiSi = 0.15; // D (\AA)
cTf_SiSi = 0.0; // c
dTf_SiSi = 0.160; // d
hTf_SiSi =-5.9826e-1; // h
eta_SiSi = 7.8734e-1;
delta_SiSi = 0.635;
F1_SiSi = 1.0;
F2_SiSi = 1.0;
/* Fitting parameters for H-H, PRB 51 4889 (1995) */
A_HH = 80.07;
B_HH = 31.38;
Lam_HH = 4.2075;
Mu_HH = 1.7956;
Alpha_HH = 3.0;
Beta_HH = 1.0; // beta
R0_HH = 0.74;
R_HH = 1.40;
D_HH = 0.30;
cTf_HH = 4.0; // c
dTf_HH = 0.0; // d
hTf_HH = 0.0; // h
eta_HH = 1.0;
delta_HH = 0.80469;
F1_HH = 1.0;
F2_HH = 1.0;
#else
#if 1
/* Fitting parameters for Si-Si,
M.S. Kim and B.C Lee EPL 102 (2013) 33002 */
A_SiSi = 2.0119e3; // A (eV)
B_SiSi = 7.1682e1; // B (eV)
Lam_SiSi = 3.0145; // lambda_1 (1/\AA)
Mu_SiSi = 1.1247; // lambda_2 (1/\AA)
Alpha_SiSi = 3.27; //
Beta_SiSi = 2.0; // beta
R0_SiSi = 2.37; // equilibrium distance to 1nn (\AA)
R_SiSi = 3.33; // R (\AA)
D_SiSi = 0.15; // D (\AA)
cTf_SiSi = 0.01123; // c
dTf_SiSi = 0.18220; // d
hTf_SiSi =-3.3333e-1; // h
eta_SiSi = 5.2772e-1;
delta_SiSi = 1.0;
F1_SiSi = 1.0;
F2_SiSi = 1.0;
#else
/* new fitting Nov 28, 2014 */
A_SiSi = 8025.195302116495; // A (eV)
B_SiSi = 40.701115782280240;// B (eV)
Lam_SiSi = 3.909594726562502; // lambda_1 (1/\AA)
Mu_SiSi = 0.867186853088723; // lambda_2 (1/\AA)
Alpha_SiSi = 0.001; //
Beta_SiSi = 2.0; // beta
R0_SiSi = 2.37; // equilibrium distance to 1nn (\AA)
R_SiSi = 3.33; // R (\AA)
D_SiSi = 0.15; // D (\AA)
cTf_SiSi = 0.233029307210524; // c
dTf_SiSi = 1.072002775222063; // d
hTf_SiSi =-0.448928185468685; // h
eta_SiSi = 1.08671875;
delta_SiSi = 0.761787281185388;
F1_SiSi = 1.0;
F2_SiSi = 1.0;
#endif
/* Fitting parameters for H-H,
M.S. Kim and B.C. Lee EPL 102 (2013) 33002 */
A_HH = 66.8276;
B_HH = 21.5038;
Lam_HH = 4.4703;
Mu_HH = 1.1616;
Alpha_HH = 3.0;
Beta_HH = 1.0; // beta
R0_HH = 0.75;
R_HH = 3.50;
D_HH = 0.50;
cTf_HH = 0.9481; // c
dTf_HH = 0.0; // d
hTf_HH = 0.0; // h
eta_HH = 1.6183;
delta_HH = 0.8684;
F1_HH = 1.0;
F2_HH = 1.0;
#endif
/* Fitting parameters for Si-H, PRB 51 4889 (1995) */
A_SiH = 323.54;
B_SiH = 84.18;
Lam_SiH = 2.9595;
Mu_SiH = 1.6158;
Alpha_SiH = 4.0; Alpha_SiH2 = 0.00;
Beta_SiH = 3.0; Beta_SiH2 = 0.00;
R0_SiH = 1.475;
R_SiH = 1.85;
D_SiH = 0.15;
cTf_SiH = 0.0216; cTf_SiH2 = 0.70;
dTf_SiH = 0.27; dTf_SiH2 = 1.00;
eta_SiH = 1.0;
delta_SiH = 0.80469;
hTf_SiH[0] = -0.040; hTf_SiH2 =-1.00;
hTf_SiH[1] = -0.040;
hTf_SiH[2] = -0.040;
hTf_SiH[3] = -0.276;
hTf_SiH[4] = -0.47;
F1_SiH[0] = 0.0;
F1_SiH[1] = 1.005;
F1_SiH[2] = 1.109;
F1_SiH[3] = 0.953;
F1_SiH[4] = 1.0;
F2_SiH[0] = 0.0;
F2_SiH[1] = 0.930;
F2_SiH[2] = 1.035;
F2_SiH[3] = 0.934;
F2_SiH[4] = 1.0;
acut=max(R_SiSi+D_SiSi,R_HH+D_HH);
acut=max(acut,R_SiH+D_SiH)*1.0;
_RLIST=acut*1.1;
_SKIN=_RLIST-acut;
acutsq=acut*acut;
strcpy(incnfile,"../si.cn");
DUMP(HIG"Murty95Frame initvars"NOR);
MDFrame::initvars();
}
void Murty95Frame::murty()
{
#ifndef NNM /* need to be taken care of later */
#define NNM 60
#endif
/* Multi process function */
int i,j,k,ipt,jpt,kpt,neg,n1nn=0;
int species_ipt,species_jpt,species_kpt;
Vector3 sij,rij,f3i,fZ,fTheta;
double fC, fA, fR, dfCdr, dfAdr, dfRdr;
double Arg1, Arg2, temp, Z, CosTheta, dCosTheta, gTheta, gR, dgRdr, Zeta, Zeta1, bij;
double r2ij, rrij, r, neff1nn;
double V, dVdr, dVdZ;
double rr[NNM], Re[NNM], Neff1NN[_NP];
//double Asave[NNM], Bsave[NNM], Musave[NNM], Lamsave[NNM];
//double Rsave[NNM], Ssave[NNM];
double fCsave[NNM], dfCdrsave[NNM], fAsave[NNM], dfAdrsave[NNM];
double fRsave[NNM], dfRdrsave[NNM], dZdCosTheta[NNM];
double dZdrij, dZdrik[NNM];
Vector3 rg[NNM], rt[NNM];
int list2[NNM];
int n0, n1;
DUMP("Murty & Atwater 95");
refreshneighborlist();
/* _EPOT, _F, _EPOT_IND, _VIRIAL all local */
_EPOT=0;
for(i=0;i<_NP;i++)
{ _F[i].clear(); _EPOT_IND[i]=0;}
_VIRIAL.clear();
n0=0;
n1=_NP;
compute_spline_coeff(NGRD,F1_SiH,1.0,F1_csp);
compute_spline_coeff(NGRD,F2_SiH,1.0,F2_csp);
compute_spline_coeff(NGRD,hTf_SiH,1.0,H_csp);
memset(Neff1NN,0,sizeof(double)*_NP);
/* 1st iteration to calculate coordination of Si atoms */
for(ipt=n0;ipt<n1;ipt++)
{
if(fixed[ipt]==-1) continue; /* ignore atom if -1 */
species_ipt=species[ipt];
//if(species_ipt==1) continue; /* ignore if atom is H */
neff1nn = 0;
for(j=0;j<nn[ipt];j++)
{
jpt=nindex[ipt][j];
if(fixed[jpt]==-1) continue; /* ignore atom if -1 */
sij.subtract(_SR[jpt],_SR[ipt]);
sij.subint();
_H.multiply(sij,rij);
r2ij=rij.norm2();
if(r2ij>acutsq) continue;
rrij=sqrt(r2ij);
r = rrij;
species_jpt=species[jpt];
/* set potential parameters */
if (species_ipt==0 && species_jpt==0)
{ // Si-Si interaction
R = R_SiSi; D = D_SiSi;
}
else if (species_ipt==1 && species_jpt==1)
{ // H-H interaction
R = R_HH; D = D_HH;
}
else if ((species_ipt==0&&species_jpt==1)
|| (species_ipt==1&&species_jpt==0))
{ // Si-H interaction
R = R_SiH; D = D_SiH;
}
if (r>=(R+D)) continue;
if(r<=(R-D))
fC = 1;
else if (r<(R+D))
{
Arg1 = M_PI*(r-R)/(2*D);
Arg2 = 3.0*Arg1;
fC = 0.5-9.0/16.0*sin(Arg1)-1/16.0*sin(Arg2);
}
else
fC = 0;
neff1nn+=fC;
}
Neff1NN[ipt]=neff1nn;
//INFO("neff1nn="<<neff1nn);
}
/* 2nd iteration to calculate individual energy and force */
for(ipt=n0;ipt<n1;ipt++)
{
if(fixed[ipt]==-1) continue; /* ignore atom if -1 */
species_ipt=species[ipt];
memset(fCsave,0,sizeof(double)*NNM);
memset(dfCdrsave,0,sizeof(double)*NNM);
memset(fAsave,0,sizeof(double)*NNM);
memset(dfAdrsave,0,sizeof(double)*NNM);
memset(fRsave,0,sizeof(double)*NNM);
memset(dfRdrsave,0,sizeof(double)*NNM);
memset(dZdrik,0,sizeof(double)*NNM);
memset(dZdCosTheta,0,sizeof(double)*NNM);
memset(rr,0,sizeof(double)*NNM);
memset(Re,0,sizeof(double)*NNM);
memset(list2,0,sizeof(int)*NNM);
for(j=0;j<NNM;j++)
{
rg[j].clear(); rt[j].clear();
}
neg = 0;
for(j=0;j<nn[ipt];j++)
{
jpt=nindex[ipt][j];
if(fixed[jpt]==-1) continue; /* ignore atom if -1 */
sij.subtract(_SR[jpt],_SR[ipt]);
sij.subint();
_H.multiply(sij,rij);
r2ij=rij.norm2();
if(r2ij>acutsq) continue;
rrij=sqrt(r2ij);
r = rrij;
species_jpt=species[jpt];
/* set potential parameters */
if (species_ipt==0 && species_jpt==0)
{ // Si-Si interaction
A = A_SiSi; B = B_SiSi;
Lam = Lam_SiSi; Mu = Mu_SiSi;
R0 = R0_SiSi; R = R_SiSi; D = D_SiSi;
}
else if (species_ipt==1 && species_jpt==1)
{ // H-H interaction
A = A_HH; B = B_HH;
Lam = Lam_HH; Mu = Mu_HH;
R0 = R0_HH; R = R_HH; D = D_HH;
}
else if ((species_ipt==0&&species_jpt==1)
|| (species_ipt==1&&species_jpt==0))
{
A = A_SiH; B = B_SiH;
Lam = Lam_SiH; Mu = Mu_SiH;
R0 = R0_SiH; R = R_SiH; D = D_SiH;
}
if (r>=(R+D)) continue;
if(r<=(R-D))
{
fC = 1;
dfCdr = 0;
}
else if (r<(R+D))
{
Arg1 = M_PI*(r-R)/(2.0*D);
Arg2 = 3.0*Arg1;
fC = 0.5-9.0/16.0*sin(Arg1)-1.0/16.0*sin(Arg2);
dfCdr = -3.0/16.0*(3.0*cos(Arg1)+cos(Arg2))*M_PI/(2.0*D);
}
else
{
fC = 0;
dfCdr = 0;
}
/* Repulsion, fR = A*F1*exp(-Lam*r) */
fR = A*exp(-Lam*r);
dfRdr = -Lam*fR;
/* Attraction, fA = -B*F2*exp(-Mu*r) */
fA = -B*exp(-Mu*r);
dfAdr = -Mu*fA;
/* save all neighbors of i */
rg[neg]=rij; /* displacement vector */
rt[neg]=rij; rt[neg]/=rrij; /* unit vector */
rr[neg]=rrij; /* distance */
list2[neg]=jpt; /* neighbor index */
Re[neg]=R0; /* equilibrium distance between i and j */
fCsave[neg]=fC;
dfCdrsave[neg]=dfCdr;
fAsave[neg]=fA;
dfAdrsave[neg]=dfAdr;
fRsave[neg]=fR;
dfRdrsave[neg]=dfRdr;
neg++;
}
//INFO_Printf("neg=%d\n",neg);
/* going through the neighbors of atom i again */
for(j=0;j<neg;j++)
{
jpt=list2[j];
if(fixed[jpt]==-1) continue; /* ignore atom if -1 */
species_jpt=species[jpt];
/* set potential parameters */
if (species_ipt==0 && species_jpt==0 )
{ // Si-Si interaction
A = A_SiSi; B = B_SiSi;
Lam = Lam_SiSi; Mu = Mu_SiSi;
Alpha = Alpha_SiSi; Beta = Beta_SiSi;
cTf = cTf_SiSi; dTf = dTf_SiSi; hTf = hTf_SiSi;
R0 = R0_SiSi; R = R_SiSi; D = D_SiSi;
eta = eta_SiSi; delta = delta_SiSi;
F1 = F1_SiSi; F2 = F2_SiSi;
}
else if (species_ipt==1 && species_jpt==1 )
{ // H-H interaction
A = A_HH; B = B_HH;
Lam = Lam_HH; Mu = Mu_HH;
Alpha = Alpha_HH; Beta = Beta_HH;
R0 = R0_HH; cTf = cTf_HH; dTf = dTf_HH;
hTf = hTf_HH; R = R_HH; D = D_HH;
eta = eta_HH; delta = delta_HH;
F1 = F1_HH; F2 = F2_HH;
}
else if ((species_ipt==0&&species_jpt==1)
||(species_ipt==1&&species_jpt==0))
{ // Si-H interaction
A = A_SiH; B = B_SiH;
Lam = Lam_SiH; Mu = Mu_SiH;
Alpha = Alpha_SiH; Beta = Beta_SiH;
R0 = R0_SiH; R = R_SiH; D = D_SiH;
cTf = cTf_SiH; dTf = dTf_SiH;
eta = eta_SiH; delta = delta_SiH;
/* Assign the effective coordination of Si */
if (species_ipt==0) neff1nn=Neff1NN[ipt];
if (species_ipt==1) neff1nn=Neff1NN[jpt];
if (neff1nn>=4.0)
{
hTf = hTf_SiH[NGRD-1]; F1 = F1_SiH[NGRD-1]; F2 = F2_SiH[NGRD-1];
}
else if (neff1nn<4.0)
{
n1nn = (int)neff1nn;
F1 = spline(F1_csp,F1_SiH,n1nn,neff1nn);
F2 = spline(F2_csp,F2_SiH,n1nn,neff1nn);
/* hTf will be obtained in the three-body loop. */
}
}
//INFO("neff1nn = "<<neff1nn);
//INFO("F1 = "<<F1);
//INFO("F2 = "<<F2);
//INFO("H = "<<hTf);
dZdrij=0.0;
Z = 0.0; /* bond order for attractive term */
/* three body loop */
for(k=0;k<neg;k++)
{
if(k==j) continue; /* k and j are different neighbors */
kpt=list2[k];
/* if fixed == -1, simply ignore this atom */
if(fixed[kpt]==-1) continue; /* ignore atom if -1 */
species_kpt=species[kpt];
/* Calculate F1(N), F2(N) and hTf using cubic spline */
/* consider triplet (i,j,k)
j k
V
i */
if(species_ipt==0&&species_jpt==0&&species_kpt==0)
{ //(i,j,k) = (Si,Si,Si) I
Alpha = Alpha_SiSi; Beta = Beta_SiSi;
cTf = cTf_SiSi; dTf = dTf_SiSi; hTf = hTf_SiSi;
}
if(species_ipt==0&&species_jpt==0&&species_kpt==1)
{ //(Si,Si,H) IIa
Alpha = Alpha_SiH; Beta = Beta_SiH;
cTf = cTf_SiH; dTf = dTf_SiH;
hTf = spline(H_csp,hTf_SiH,(int)Neff1NN[ipt],Neff1NN[ipt]);
}
if(species_ipt==0&&species_jpt==1&&species_kpt==0)
{ //(Si,H,Si) IIa
Alpha = Alpha_SiH; Beta = Beta_SiH;
cTf = cTf_SiH; dTf = dTf_SiH;
hTf = spline(H_csp,hTf_SiH,(int)Neff1NN[ipt],Neff1NN[ipt]);
}
if(species_ipt==0&&species_jpt==1&&species_kpt==1)
{ //(Si,H,H) IIa
Alpha = Alpha_SiH; Beta = Beta_SiH;
cTf = cTf_SiH; dTf = dTf_SiH;
hTf = spline(H_csp,hTf_SiH,(int)Neff1NN[ipt],Neff1NN[ipt]);
}
if(species_ipt==1&&species_jpt==0&&species_kpt==0)
{ //(H,Si,Si) IIb
Alpha = Alpha_SiH2; Beta = Beta_SiH2;
cTf = cTf_SiH2; dTf = dTf_SiH2; hTf = hTf_SiH2;
}
if(species_ipt==1&&species_jpt==0&&species_kpt==1)
{ //(H,Si,H) III
Alpha = Alpha_HH; Beta = Beta_HH;
cTf = cTf_HH; dTf = dTf_HH; hTf = hTf_HH;
}
if(species_ipt==1&&species_jpt==1&&species_kpt==0)
{ //(H,H,Si) III
Alpha = Alpha_HH; Beta = Beta_HH;
cTf = cTf_HH; dTf = dTf_HH; hTf = hTf_HH;
}
if(species_ipt==1&&species_jpt==1&&species_kpt==1)
{ //(H,H,H) III
Alpha = Alpha_HH; Beta = Beta_HH;
cTf = cTf_HH; dTf = dTf_HH; hTf = hTf_HH;
}
//INFO("H = "<<hTf);
/* cos(theta_ijk): angle between bond ij and bond ik */
CosTheta=rt[j]*rt[k];
/* h-cos(theta_ijk) */
dCosTheta = (hTf-CosTheta);
/* g(theta)=c+d*(h-cos(theta_ijk))^2 */
gTheta = cTf+dTf*dCosTheta*dCosTheta;
/* g(r) = exp[alpha*{(r_ij-R0_ij)-(r_ik-R0_ik)}^beta] */
gR = exp(Alpha*pow((rr[j]-Re[j]-rr[k]+Re[k]),Beta));
Z += fCsave[k]*gTheta*gR;
/* d(gR)/d(r_ik) */
//dgRdr = gR*(-1.0)*Alpha*Beta*pow((rr[j]-Re[j]-rr[k]+Re[k]),Beta-1);
/* d(gR)/d(r_ij) */
dgRdr = gR*Alpha*Beta*pow((rr[j]-Re[j]-rr[k]+Re[k]),Beta-1);
dZdrij+=fCsave[k]*gTheta*dgRdr;
dZdrik[k] = dfCdrsave[k]*gTheta*gR-fCsave[k]*gTheta*dgRdr;
dZdCosTheta[k] = (fCsave[k]*gR)*(-2.0)*dTf*(hTf-CosTheta);
//INFO("g(theta)="<<gTheta<<", g(r)="<<gR);
}
fC = fCsave[j];
dfCdr = dfCdrsave[j];
fA = fAsave[j];
dfAdr = dfAdrsave[j];
fR = fRsave[j];
dfRdr = dfRdrsave[j];
Zeta = pow(Z,eta);
Zeta1 = pow(Z,eta-1);
if(neg==1) Zeta1=0.0;
bij = pow((1.0+Zeta),(-1.0)*delta);
V = 0.5*fC*(F1*fR+bij*F2*fA);
//INFO("Z="<<Z<<", bij = "<<bij);
//INFO("V="<<V<<" (eV)");
#if 0
// Debug
FILE *fp;
if(ipt==0)
{
INFO("write energy.dat");
if(j==0) fp=fopen("energy.dat","w");
else fp=fopen("energy.dat","a");
if(fp==NULL) FATAL("open file failure");
fprintf(fp, "%d %d %12.10e %12.10e %12.10e %12.10e %12.10e %12.10e\n", ipt,jpt,fC, F1, F2, fR,fA,bij);
fclose(fp);
}
#endif
_EPOT += V;
_EPOT_IND[ipt] += V;
dVdZ = 0.5*fC*F2*fA*(-bij*(delta*eta*Zeta1)/(1+Zeta));
dVdr = 0.5*dfCdr*(F1*fR+bij*F2*fA) + 0.5*fC*(F1*dfRdr+bij*F2*dfAdr) + dVdZ*dZdrij;
f3i=rt[j]*dVdr;
_F[ipt]+=f3i;
_F[jpt]-=f3i;
_VIRIAL.addnvv(-1.,f3i,rg[j]);
if (SURFTEN==1 && (curstep%savepropfreq)==1) AddnvvtoPtPn(_SR[jpt],f3i,rg[j],-1.0);
// INFO_Printf(" bij = %e V = %e dVdr = %e f3i=(%e,%e,%e)\n",bij,V,dVdr,f3i.x,f3i.y,f3i.z);
// INFO_Printf(" bij = %e rt[j]=(%e,%e,%e)\n",bij,rt[j].x,rt[j].y,rt[j].z);
/* three body loop */
for(k=0;k<neg;k++)
{
if(k==j) continue; /* k and j are different neighbors */
kpt=list2[k];
if(fixed[kpt]==-1) continue; /* ignore atom if -1 */
/* Forces due to derivatives with respect to Z, then rik */
temp = dVdZ*dZdrik[k];
fZ = rt[k]*temp;
_F[ipt]+=fZ;
_F[kpt]-=fZ;
_VIRIAL.addnvv(-1.,fZ,rg[k]);
if (SURFTEN==1 && (curstep%savepropfreq)==1) AddnvvtoPtPn(_SR[kpt],fZ,rg[k],-1.0);
/* cos(theta_ijk): angle between bond ij and bond ik */
CosTheta=rt[j]*rt[k];
/* Forces due to derivatives with respect to cosTheta */
temp = dVdZ*dZdCosTheta[k];
fTheta = (rt[j]*CosTheta-rt[k])*(-temp/rr[j]);
_F[ipt]+=fTheta;
_F[jpt]-=fTheta;
_VIRIAL.addnvv(-1.,fTheta,rg[j]);
if (SURFTEN==1 && (curstep%savepropfreq)==1) AddnvvtoPtPn(_SR[jpt],fTheta,rg[j],-1.0);
fTheta = (rt[k]*CosTheta-rt[j])*(-temp/rr[k]);
_F[ipt]+=fTheta;
_F[kpt]-=fTheta;
_VIRIAL.addnvv(-1.,fTheta,rg[k]);
if (SURFTEN==1 && (curstep%savepropfreq)==1) AddnvvtoPtPn(_SR[kpt],fTheta,rg[k],-1.0);
}
}
}
}
void Murty95Frame::potential()
{
murty();
}
#ifdef _TEST
/* Main Program Begins */
class Murty95Frame sim;
/* The main program is defined here */
#include "main.cpp"
#endif//_TEST
| [
"xiaohanzhang.cmu@gmail.com"
] | xiaohanzhang.cmu@gmail.com |
f2e17f79958df1a967867dd00c1600ac1513da5e | 6a1eda4d8653fbe54afc5e473ce48de5434cf6b2 | /taiji/v1.0/Taiji/TRedis/RedisClientSet.cpp | 09e050be07e642e651f690f196a74353d11ffb99 | [] | no_license | helloworldyuhaiyang/cdk | 8263f5ddd211fdfc55dec05e4d9d0469f3967f67 | 7ace68f48ca0439dfe3ff451dec32354d4ddc54d | refs/heads/master | 2023-07-19T07:51:03.615697 | 2021-09-07T07:09:07 | 2021-09-07T07:09:07 | 403,876,936 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,864 | cpp |
#include "Command.h"
#include "CRedisClient.h"
namespace Taiji {
namespace TRedis {
uint64_t CRedisClient::sadd(const string &key, const VecString &members)
{
Command cmd( "SADD" );
cmd << key;
VecString::const_iterator it = members.begin();
VecString::const_iterator end = members.end();
for ( ; it != end ; ++it )
{
cmd << *it;
}
int64_t num;
_getInt( cmd , num );
return num;
}
uint64_t CRedisClient::scard(const string &key)
{
Command cmd( "SCARD" );
cmd << key;
int64_t num;
_getInt( cmd , num );
return num;
}
uint64_t CRedisClient::sdiff(const VecString &keys, VecString &values)
{
Command cmd( "SDIFF" );
VecString::const_iterator it = keys.begin();
VecString::const_iterator end = keys.end();
for ( ; it != end; ++it )
{
cmd << *it;
}
uint64_t num = 0;
_getArry( cmd, values , num);
return num;
}
uint64_t CRedisClient::sdiffstore(const string &destKey, const VecString &keys )
{
Command cmd( "SDIFFSTORE" );
cmd << destKey;
VecString::const_iterator it = keys.begin();
VecString::const_iterator end = keys.end();
for ( ; it != end; ++it )
{
cmd << *it;
}
int64_t num = 0;
_getInt( cmd, num );
return num;
}
uint64_t CRedisClient::sinter(const VecString &keys, VecString &values)
{
Command cmd( "SINTER" );
VecString::const_iterator it = keys.begin();
VecString::const_iterator end = keys.end();
for ( ; it != end; ++it )
{
cmd << *it;
}
uint64_t num = 0;
_getArry( cmd, values, num );
return num;
}
uint64_t CRedisClient::sinterstore( const string& destKey ,const VecString &keys )
{
Command cmd( "SINTERSTORE" );
cmd << destKey;
VecString::const_iterator it = keys.begin();
VecString::const_iterator end = keys.end();
for ( ; it != end; ++it )
{
cmd << *it;
}
int64_t num = 0;
_getInt( cmd, num );
return num;
}
bool CRedisClient::sismember(const string &key, const string &member)
{
Command cmd( "SISMEMBER" );
cmd << key << member;
int64_t num = 0;
_getInt( cmd, num );
return ( num == 1 ? true: false );
}
uint64_t CRedisClient::smembers( const string &key, VecString &members )
{
Command cmd( "SMEMBERS" );
cmd << key;
uint64_t num = 0;
_getArry( cmd, members,num );
return num;
}
bool CRedisClient::smove(const string &source, const string &dest, const string &member)
{
Command cmd( "SMOVE" );
cmd << source << dest << member;
int64_t num;
_getInt( cmd, num );
return ( num==0 ? false : true );
}
bool CRedisClient::spop(const string &key, string &member)
{
member.clear();
Command cmd( "SPOP" );
cmd << key;
return ( _getString( cmd, member ) );
}
bool CRedisClient::srandmember(const string &key, string &member)
{
Command cmd ( "SRANDMEMBER" );
cmd << key;
return ( _getString( cmd, member) );
}
uint64_t CRedisClient::srandmember(const string &key, int count, VecString &members)
{
Command cmd( "SRANDMEMBER" );
cmd << key << count ;
uint64_t num = 0;
_getArry( cmd, members, num );
return num;
}
uint64_t CRedisClient::srem(const string &key,const VecString &members)
{
Command cmd ( "SREM" );
cmd << key;
VecString::const_iterator it = members.begin();
VecString::const_iterator end = members.end();
for ( ; it != end; ++it )
{
cmd << *it;
}
int64_t num;
_getInt( cmd, num );
return num;
}
uint64_t CRedisClient::sunion(const VecString &keys , VecString &members)
{
Command cmd( "SUNION" );
VecString::const_iterator it = keys.begin();
VecString::const_iterator end = keys.end();
for ( ; it != end; ++it )
{
cmd << *it;
}
uint64_t num = 0;
_getArry( cmd, members, num );
return num;
}
uint64_t CRedisClient::sunionstroe(const string &dest, const VecString &keys)
{
Command cmd( "SUNIONSTORE" );
cmd << dest;
VecString::const_iterator it = keys.begin();
VecString::const_iterator end = keys.end();
for ( ; it != end; ++it )
{
cmd << *it;
}
int64_t num;
_getInt( cmd, num );
return num;
}
bool CRedisClient::sscan(const string &key, int64_t &cursor, VecString &values, const string &match, uint64_t count)
{
CResult result;
Command cmd( "SSCAN" );
cmd << key << cursor;
if ( "" != match )
{
cmd << "MATCH" << match;
}
if ( 0 != count )
{
cmd << "COUNT" << count;
}
_getArry( cmd, result );
CResult::ListCResult::const_iterator it = result.getArry().begin();
cursor = _valueFromString<uint64_t>( it->getString() );
++ it;
_getStringVecFromArry( it->getArry(), values );
return ( cursor == 0 ? false : true );
}
}
}
| [
"18989893637@189.cn"
] | 18989893637@189.cn |
87951a10f99844c1b3c2c51f151120c2a97668b9 | 2eda515fba1767e517d0f6dc84f84590352a54ef | /ZF/ZFUIWidget/zfsrc/ZFUIWidget/ZFUIPageBasic.h | cbacad63895dbefc77a87ce0b3224992851b297b | [
"MIT"
] | permissive | yeshuopp123/ZFFramework | cb43ec281015b563618931c3972ef522a2e535c9 | 6cf2e78fed9e5ef1f35ad8402dbcb56cfd88ad9e | refs/heads/master | 2021-05-01T05:38:03.739214 | 2017-01-22T16:48:47 | 2017-01-22T16:48:47 | 79,763,020 | 1 | 0 | null | 2017-01-23T02:34:41 | 2017-01-23T02:34:40 | null | UTF-8 | C++ | false | false | 7,514 | h | /* ====================================================================== *
* Copyright (c) 2010-2016 ZFFramework
* home page: http://ZFFramework.com
* blog: http://zsaber.com
* contact: master@zsaber.com (Chinese and English only)
* Distributed under MIT license:
* https://github.com/ZFFramework/ZFFramework/blob/master/license/license.txt
* ====================================================================== */
/**
* @file ZFUIPageBasic.h
* @brief basic #ZFUIPage with animation logic
*/
#ifndef _ZFI_ZFUIPageBasic_h_
#define _ZFI_ZFUIPageBasic_h_
#include "ZFUIPage.h"
ZF_NAMESPACE_GLOBAL_BEGIN
// ============================================================
zfclassFwd ZFUIPageManagerBasic;
zfclassFwd _ZFP_ZFUIPageManagerBasicPrivate;
zfclassFwd _ZFP_ZFUIPageBasicPrivate;
/**
* @brief basic page with animation logic,
* see #ZFUIPageManager and #ZFUIPageManagerBasic for how to use
*/
zfabstract ZF_ENV_EXPORT ZFUIPageBasic : zfextends ZFObject, zfimplements ZFUIPage
{
ZFOBJECT_DECLARE_ABSTRACT(ZFUIPageBasic, ZFObject)
ZFIMPLEMENTS_DECLARE(ZFUIPage)
// ============================================================
// observers
public:
/**
* @brief see #ZFObject::observerNotify
*
* called when page about to start animation,
* ensured called even if no animation to start for convenient\n
* param0 is the animation to start or null if no animation to start,
* param1 is the #ZFUIPagePauseReason or #ZFUIPageResumeReason
*/
ZFOBSERVER_EVENT(PageAniOnStart)
/**
* @brief see #ZFObject::observerNotify
*
* called when page about to stop animation,
* ensured called even if no animation to start for convenient\n
* param0 is the animation to stop or null if no animation to stop,
* param1 is the #ZFUIPagePauseReason or #ZFUIPageResumeReason
*/
ZFOBSERVER_EVENT(PageAniOnStop)
// ============================================================
// pageAni
public:
/**
* @brief page's animation
*
* we have these animations for page to setup:
* - pageAniResumeByRequest / pagePauseAniToBackground:
* used when a page is resumed by user request,
* and the previous resume page would be sent to background
* - pageAniResumeFromBackground / pagePauseAniBeforeDestroy:
* used when a foreground page is destroyed by user request,
* and background page would result to be moved to foreground
*
* see #pageAniOnUpdateForResume for more info
*/
ZFPROPERTY_RETAIN(ZFAnimation *, pageAniResumeByRequest)
/**
* @brief page's animation, see #pageAniResumeByRequest
*/
ZFPROPERTY_RETAIN(ZFAnimation *, pageAniResumeFromBackground)
/**
* @brief page's animation, see #pageAniResumeByRequest
*/
ZFPROPERTY_RETAIN(ZFAnimation *, pageAniPauseToBackground)
/**
* @brief page's animation, see #pageAniResumeByRequest
*/
ZFPROPERTY_RETAIN(ZFAnimation *, pageAniPauseBeforeDestroy)
private:
zfbool _ZFP_ZFUIPage_pageAniCanChange;
public:
/**
* @brief the final animation being used when page stack changed, null to disable animation
*
* by default, this value would be updated by #pageAniOnUpdateForSiblingPageResume and #pageAniOnUpdateForResume,
* you may override default value whenever you can,
* to override animation\n
* the recommended way is to override #pageAniOnUpdateForSiblingPageResume and/or #pageAniOnUpdateForResume
* to change this value\n
* this value would be reset to null when animation stopped or page destroyed\n
* see #pageAniOnUpdateForResume for more info
*/
virtual void pageAniSet(ZF_IN ZFAnimation *pageAni);
/**
* @brief see #pageAniSet
*/
virtual ZFAnimation *pageAni(void);
public:
/**
* @brief whether this page need higher priority for animation,
* typically a higher priority animation would have its view on the top
*/
zfbool pageAniPriorityNeedHigher;
protected:
/**
* @brief used to update animation by priority, do nothing by default
*/
virtual void pageAniPriorityOnUpdate(ZF_IN zfbool priorityHigher)
{
}
protected:
/**
* @brief see #pageAniOnUpdateForResume
*/
virtual void pageAniOnUpdateForSiblingPageResume(ZF_IN ZFUIPageResumeReasonEnum reason,
ZF_IN ZFUIPageBasic *siblingResumePageOrNull);
/**
* @brief for page to update it's final animation
*
* the actual animation should be saved to #pageAniSet,
* by this page or by sibling page\n
* \n
* the actual animation logic is achieved by this:
* @code
* ZFUIPageBasic *pausePage = xxx; // page to pause
* ZFUIPageBasic *resumePage = xxx; // page to resume
* pausePage->pageAniOnUpdateForSiblingPageResume(reason, resumePage);
* resumePage->pageAniOnUpdateForResume(reason, pausePage, pauseAniHasHigherPriority);
* zfbool pausePageHasHigherPriority = (!resumePage->pageAniPriorityNeedHigher && pausePage->pageAniPriorityNeedHigher);
* pausePage->pageAniPriorityOnUpdate(pausePageHasHigherPriority);
* resumePage->pageAniPriorityOnUpdate(!pausePageHasHigherPriority);
* @endcode
* by default, #pageAniOnUpdateForSiblingPageResume and #pageAniOnUpdateForResume
* would update page animation
* by #pageAniResumeByRequest/#pageAniResumeFromBackground/#pageAniPauseToBackground/#pageAniPauseBeforeDestroy
* accorrding to page's resume and pause reason,
* and page requested by user would have higher animation priority (request resume or request destroy)
*/
virtual void pageAniOnUpdateForResume(ZF_IN ZFUIPageResumeReasonEnum reason,
ZF_IN ZFUIPageBasic *siblingPausePageOrNull);
/**
* @brief called to update animation's target, do nothing by default
*/
virtual void pageAniOnUpdateAniTarget(ZF_IN ZFAnimation *pageAni)
{
}
// ============================================================
// event
protected:
/** @brief see #EventPageAniOnStart */
virtual void pageAniOnStart(ZF_IN ZFAnimation *pageAni,
ZF_IN ZFEnum *pagePauseReasonOrResumeReason)
{
this->observerNotify(ZFUIPageBasic::EventPageAniOnStart(),
pageAni, pagePauseReasonOrResumeReason);
}
/** @brief see #EventPageAniOnStop */
virtual void pageAniOnStop(ZF_IN ZFAnimation *pageAni,
ZF_IN ZFEnum *pagePauseReasonOrResumeReason)
{
this->observerNotify(ZFUIPageBasic::EventPageAniOnStop(),
pageAni, pagePauseReasonOrResumeReason);
}
// ============================================================
// override
protected:
zfoverride
virtual void pageOnCreate(void);
zfoverride
virtual void pageOnResume(ZF_IN ZFUIPageResumeReasonEnum reason);
zfoverride
virtual void pageOnPause(ZF_IN ZFUIPagePauseReasonEnum reason);
zfoverride
virtual void pageOnDestroy(void);
protected:
zfoverride
virtual void pageDelayDestroyOnCheck(void);
private:
_ZFP_ZFUIPageBasicPrivate *d;
friend zfclassFwd ZFUIPageManagerBasic;
friend zfclassFwd _ZFP_ZFUIPageManagerBasicPrivate;
friend zfclassFwd _ZFP_ZFUIPageBasicPrivate;
};
ZF_NAMESPACE_GLOBAL_END
#endif // #ifndef _ZFI_ZFUIPageBasic_h_
| [
"z@zsaber.com"
] | z@zsaber.com |
f6858cf32b9dac91e3e30c3b2a4dadccb088455e | b5e00c7392791f982cc5a26d588d5ffc5cf9eb74 | /Breakout/Ball.cpp | 14b84c1b5090a68ef918ef9c6d703b1793f7c202 | [] | no_license | Gareton/OpenGL_Learning | 24643a4a2066158af16ed891dd54067fae8f8384 | eeb8086af2006e42a684c3f5a6e429963d1ffb55 | refs/heads/master | 2020-06-16T01:50:03.271263 | 2019-07-20T14:02:12 | 2019-07-20T14:02:12 | 195,448,194 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,029 | cpp | #include "Ball.h"
#include <glad/glad.h>
Ball::Ball()
: GameObject(), Radius(12.5f), Stuck(true) { }
Ball::Ball(glm::vec2 pos, GLfloat radius, glm::vec2 velocity, Texture2D sprite)
: GameObject(pos, glm::vec2(radius * 2, radius * 2), sprite, glm::vec3(1.0f), velocity), Radius(radius), Stuck(true), PassThrough(false), Sticky(false) { }
glm::vec2 Ball::Move(GLfloat dt, GLuint window_width)
{
if (!Stuck)
{
Position += Velocity * dt;
if (this->Position.x <= 0.0f)
{
this->Velocity.x = -this->Velocity.x;
this->Position.x = 0.0f;
}
else if (this->Position.x + this->Size.x >= window_width)
{
this->Velocity.x = -this->Velocity.x;
this->Position.x = window_width - this->Size.x;
}
if (this->Position.y <= 0.0f)
{
this->Velocity.y = -this->Velocity.y;
this->Position.y = 0.0f;
}
}
return Position;
}
void Ball::Reset(glm::vec2 position, glm::vec2 velocity)
{
this->Position = position;
this->Velocity = velocity;
this->Stuck = true;
} | [
"fghftftrdrrdrdrdr65656hj56h@gmail.com"
] | fghftftrdrrdrdrdr65656hj56h@gmail.com |
223f7df63e9ecdec7736e77f1348f1dc183c8248 | 220846e017a9992e596bd1ea806d527e3aeea243 | /162_Find_Peak_Element.cpp | 618e82ebc8f572dcbf0cf7ddf9e0f7dd0bcccb78 | [] | no_license | anzhe-yang/Leetcode | bfa443b7a74ddbd441348c364ee00004173ddd86 | fe9eb16136035f25f31bddb37c6b4884cd7f6904 | refs/heads/master | 2020-04-08T14:49:04.781848 | 2019-10-25T02:39:22 | 2019-10-25T02:39:22 | 159,453,173 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,049 | cpp | /** 问题描述:
* 如果某个元素大于它周围的元素,则称为山顶元素。
* 给定一个数组,数组中相邻两个元素不相等,找到其中的山顶元素并返回位置索引。
* 数组可能包含多个山顶元素,可以任意返回某一个。
* 可以假设数组的 -1 索引和 n 索引的值为负无穷。
* 算法复杂度为 O(logN) 。
*/
#include <iostream>
#include <vector>
using namespace std;
int findPeakElement(vector<int>& nums)
{
/*
二分法。
比较当前mid值和下一个值。
如果小于它,则说明山顶值在右方,否则在左方。
*/
int len = nums.size();
int left = 0, right = len-1;
int mid = 0;
while (left < right)
{
mid = left + ((right-left) >> 1);
if (nums[mid] < nums[mid+1])
left = mid + 1;
else
right = mid;
}
return left;
}
int main(int argc, char const *argv[])
{
vector<int> nums{};
cout << findPeakElement(nums);
return 0;
}
| [
"yaz951114@gmail.com"
] | yaz951114@gmail.com |
f29ac0e4bed17dfe8db9f25ded80d9695fa59af1 | a4d518ddd989bad8b2dde807b2d3111eff00e356 | /Project/libs/StarEngine/include/Scenes/SlideScene.h | d969a9191dde7875e3abecc76b36a2cd2516adcc | [
"MIT"
] | permissive | GlenDC/StarEngine-downloads | 84269ea6ada832a82af4022a5dbaa1475fdc8924 | b52a065b76df9b41327d20cde133ebad5e65adcd | refs/heads/master | 2021-01-23T17:31:00.220517 | 2013-12-15T22:46:24 | 2013-12-15T22:46:24 | 15,191,686 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,595 | h | #pragma once
#include "../defines.h"
#include "../Logger.h"
#include "../Context.h"
#include "../Scenes/BaseScene.h"
#include "../Graphics/UI/Index.h"
namespace star
{
class SlideScene : public BaseScene
{
public:
SlideScene(const tstring& name, const tstring & nextScene);
virtual ~SlideScene();
virtual void CreateObjects();
virtual void AfterInitializedObjects();
virtual void OnActivate();
virtual void OnDeactivate();
virtual void Update(const star::Context& context);
virtual void Draw();
int16 AddSlide(
const tstring & file,
float32 active_time
);
int16 AddSlide(
const tstring & file,
float32 active_time,
const Color & fade_in_start_color,
const Color & fade_in_end_color,
float32 fade_in_time
);
int16 AddSlide(
const tstring & file,
float32 active_time,
const Color & fade_in_start_color,
const Color & fade_in_end_color,
float32 fade_in_time,
const Color & fade_out_start_color,
const Color & fade_out_end_color,
float32 fade_out_time
);
void SetKeyboardInputEnabled(bool enable);
void SetFingerInputEnabled(bool enable);
protected:
star::UIDock * m_pSlideMenu;
std::vector<tstring> m_Slides;
private:
void GoNextSlide();
uint8 m_CurrentSlide;
float32 m_TotalTime;
tstring m_NextScene;
bool m_AllowKeyboardInput,
m_AllowFingerInput;
SlideScene(const SlideScene& t);
SlideScene(SlideScene&& t);
SlideScene& operator=(const SlideScene& t);
SlideScene& operator=(SlideScene&& t);
};
}
| [
"decauwsemaecker.glen@gmail.com"
] | decauwsemaecker.glen@gmail.com |
86c28b5d79a7b3a62e6010f0794768bba40bff6d | 303b225245d9d090849fe89b32d46e171bbcb125 | /C++/final/final1.1_fixed/input.h | 5e2a564281654747d599a6b1390d4467808e0339 | [] | no_license | Trouble404/Undergraduate-courseworks | cb3e70923168e4312d5a90e4d4bca0ee705ddeea | 1e8b49f343c60c2756b701806ee97a3a8b0bbe5f | refs/heads/master | 2021-09-05T01:51:16.309069 | 2018-01-23T15:07:42 | 2018-01-23T15:07:42 | 118,033,958 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 284 | h | #ifndef _INPUT_H
#define _INPUT_H
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cstring>
using namespace std;
int choose(int c); //菜单中的选择函数
int inte_Input(); //输入数字
string str_Input();//输入字符串
#endif | [
"362914124@qq.com"
] | 362914124@qq.com |
8591089edf128a2bb8e9aab1b7f6a1e84d6c704b | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /content/common/input/synthetic_web_input_event_builders.h | 3247d0d243ddf02fe47ecb4e1bfd62c6a02fb2dc | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 3,758 | h | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_COMMON_INPUT_SYNTHETIC_WEB_INPUT_EVENT_BUILDERS_H_
#define CONTENT_COMMON_INPUT_SYNTHETIC_WEB_INPUT_EVENT_BUILDERS_H_
#include "base/time/time.h"
#include "content/common/content_export.h"
#include "third_party/blink/public/platform/web_gesture_event.h"
#include "third_party/blink/public/platform/web_input_event.h"
#include "third_party/blink/public/platform/web_keyboard_event.h"
#include "third_party/blink/public/platform/web_mouse_wheel_event.h"
#include "third_party/blink/public/platform/web_touch_event.h"
// Provides sensible creation of default WebInputEvents for testing purposes.
namespace content {
class CONTENT_EXPORT SyntheticWebMouseEventBuilder {
public:
static blink::WebMouseEvent Build(blink::WebInputEvent::Type type);
static blink::WebMouseEvent Build(
blink::WebInputEvent::Type type,
float window_x,
float window_y,
int modifiers,
blink::WebPointerProperties::PointerType pointer_type =
blink::WebPointerProperties::PointerType::kMouse);
};
class CONTENT_EXPORT SyntheticWebMouseWheelEventBuilder {
public:
static blink::WebMouseWheelEvent Build(
blink::WebMouseWheelEvent::Phase phase);
static blink::WebMouseWheelEvent Build(float x,
float y,
float dx,
float dy,
int modifiers,
bool precise);
static blink::WebMouseWheelEvent Build(float x,
float y,
float global_x,
float global_y,
float dx,
float dy,
int modifiers,
bool precise);
};
class CONTENT_EXPORT SyntheticWebKeyboardEventBuilder {
public:
static blink::WebKeyboardEvent Build(blink::WebInputEvent::Type type);
};
class CONTENT_EXPORT SyntheticWebGestureEventBuilder {
public:
static blink::WebGestureEvent Build(blink::WebInputEvent::Type type,
blink::WebGestureDevice source_device,
int modifiers = 0);
static blink::WebGestureEvent BuildScrollBegin(
float dx_hint,
float dy_hint,
blink::WebGestureDevice source_device,
int pointer_count = 1);
static blink::WebGestureEvent BuildScrollUpdate(
float dx,
float dy,
int modifiers,
blink::WebGestureDevice source_device);
static blink::WebGestureEvent BuildPinchUpdate(
float scale,
float anchor_x,
float anchor_y,
int modifiers,
blink::WebGestureDevice source_device);
static blink::WebGestureEvent BuildFling(
float velocity_x,
float velocity_y,
blink::WebGestureDevice source_device);
};
class CONTENT_EXPORT SyntheticWebTouchEvent : public blink::WebTouchEvent {
public:
SyntheticWebTouchEvent();
// Mark all the points as stationary, and remove any released points.
void ResetPoints();
// Adds an additional point to the touch list, returning the point's index.
int PressPoint(float x, float y);
void MovePoint(int index, float x, float y);
void ReleasePoint(int index);
void CancelPoint(int index);
void SetTimestamp(base::TimeTicks timestamp);
int FirstFreeIndex();
};
} // namespace content
#endif // CONTENT_COMMON_INPUT_SYNTHETIC_WEB_INPUT_EVENT_BUILDERS_H_
| [
"arnaud@geometry.ee"
] | arnaud@geometry.ee |
15f854947c9db5775945a5b4426165166e010e8e | b1708eb6995a2bdfc22cee18d2897bd5d8e1bc50 | /x11hash.cc | 789765812311ef50c949b1dc54d3200a3e60bc3f | [] | no_license | n-johnson/node-x11-hash-algo | 6351f15b9fc906b33149bdaf95d58df72f4237d4 | df95aa1442b09e719ad130e5595e0100d734ca0c | refs/heads/master | 2021-01-16T08:55:00.308080 | 2014-08-11T08:23:35 | 2014-08-11T08:23:35 | 22,830,404 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 960 | cc | #include <node.h>
#include <node_buffer.h>
#include <v8.h>
#include <stdint.h>
extern "C" {
#include "x11.h"
}
using namespace node;
using namespace v8;
Handle<Value> except(const char* msg) {
return ThrowException(Exception::Error(String::New(msg)));
}
Handle<Value> hash(const Arguments& args) {
HandleScope scope;
if (args.Length() < 1)
return except("You must provide one argument.");
Local<Object> target = args[0]->ToObject();
if(!Buffer::HasInstance(target))
return except("Argument should be a buffer object.");
char * input = Buffer::Data(target);
char output[32];
uint32_t input_len = Buffer::Length(target);
x11_hash(input, output, input_len);
Buffer* buff = Buffer::New(output, 32);
return scope.Close(buff->handle_);
}
void init(Handle<Object> exports) {
exports->Set(String::NewSymbol("hash"), FunctionTemplate::New(hash)->GetFunction());
}
NODE_MODULE(x11, init) | [
"node@njohnson.me"
] | node@njohnson.me |
da2502bb64ee7e00ecef996437758ada18e57a5b | 5a60d60fca2c2b8b44d602aca7016afb625bc628 | /aws-cpp-sdk-appconfig/source/model/GetConfigurationProfileResult.cpp | 9018b52076701d7d7635dbe68984d0863b5ee42a | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | yuatpocketgems/aws-sdk-cpp | afaa0bb91b75082b63236cfc0126225c12771ed0 | a0dcbc69c6000577ff0e8171de998ccdc2159c88 | refs/heads/master | 2023-01-23T10:03:50.077672 | 2023-01-04T22:42:53 | 2023-01-04T22:42:53 | 134,497,260 | 0 | 1 | null | 2018-05-23T01:47:14 | 2018-05-23T01:47:14 | null | UTF-8 | C++ | false | false | 1,964 | cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/appconfig/model/GetConfigurationProfileResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::AppConfig::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
GetConfigurationProfileResult::GetConfigurationProfileResult()
{
}
GetConfigurationProfileResult::GetConfigurationProfileResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
GetConfigurationProfileResult& GetConfigurationProfileResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("ApplicationId"))
{
m_applicationId = jsonValue.GetString("ApplicationId");
}
if(jsonValue.ValueExists("Id"))
{
m_id = jsonValue.GetString("Id");
}
if(jsonValue.ValueExists("Name"))
{
m_name = jsonValue.GetString("Name");
}
if(jsonValue.ValueExists("Description"))
{
m_description = jsonValue.GetString("Description");
}
if(jsonValue.ValueExists("LocationUri"))
{
m_locationUri = jsonValue.GetString("LocationUri");
}
if(jsonValue.ValueExists("RetrievalRoleArn"))
{
m_retrievalRoleArn = jsonValue.GetString("RetrievalRoleArn");
}
if(jsonValue.ValueExists("Validators"))
{
Aws::Utils::Array<JsonView> validatorsJsonList = jsonValue.GetArray("Validators");
for(unsigned validatorsIndex = 0; validatorsIndex < validatorsJsonList.GetLength(); ++validatorsIndex)
{
m_validators.push_back(validatorsJsonList[validatorsIndex].AsObject());
}
}
if(jsonValue.ValueExists("Type"))
{
m_type = jsonValue.GetString("Type");
}
return *this;
}
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
8d8564d9a498e18607bf1a694729ef2a27b7fb96 | cfad33a05c9d942060f05417521fe6512d3470e0 | /python/cc/simple_output_stream_adapter_test.cc | b2e5efc1824a2e08a78d19155190b853be0b1806 | [
"Apache-2.0"
] | permissive | code-machina/tink | fe2d3772e9b12ceaaef18c0789af2cdcd3ee6b9a | 6db4f1846642e7f631043770ea80cf56caec723b | refs/heads/master | 2020-07-18T15:42:40.824615 | 2019-09-03T19:15:21 | 2019-09-03T19:15:49 | 206,271,110 | 1 | 0 | Apache-2.0 | 2019-09-04T08:34:19 | 2019-09-04T08:33:30 | null | UTF-8 | C++ | false | false | 7,857 | cc | // 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 "tink/python/cc/simple_output_stream_adapter.h"
#include <memory>
#include "gtest/gtest.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "tink/subtle/random.h"
#include "tink/util/status.h"
#include "tink/util/statusor.h"
#include "tink/python/cc/simple_output_stream.h"
namespace crypto {
namespace tink {
namespace {
// SimpleOutputStream for testing.
class TestSimpleOutputStream : public SimpleOutputStream {
public:
util::StatusOr<int> Write(absl::string_view data) override {
buffer_ += std::string(data);
return data.size();
}
util::Status Close() override { return util::OkStatus(); }
int64_t Position() const override { return buffer_.size(); }
std::string* GetBuffer() { return &buffer_; }
private:
std::string buffer_;
};
// Writes 'contents' to the specified 'output_stream', and closes the stream.
// Returns the status of output_stream->Close()-operation, or a non-OK status
// of a prior output_stream->Next()-operation, if any.
util::Status WriteToStream(SimpleOutputStreamAdapter* output_stream,
absl::string_view contents) {
void* buffer;
int pos = 0;
int remaining = contents.length();
int available_space = 0;
int available_bytes = 0;
while (remaining > 0) {
auto next_result = output_stream->Next(&buffer);
if (!next_result.ok()) return next_result.status();
available_space = next_result.ValueOrDie();
available_bytes = std::min(available_space, remaining);
memcpy(buffer, contents.data() + pos, available_bytes);
remaining -= available_bytes;
pos += available_bytes;
}
if (available_space > available_bytes) {
output_stream->BackUp(available_space - available_bytes);
}
return output_stream->Close();
}
TEST(SimpleOutputStreamAdapterTest, WritingStreams) {
for (size_t stream_size : {0, 10, 100, 1000, 10000, 100000, 1000000}) {
SCOPED_TRACE(absl::StrCat("stream_size = ", stream_size));
std::string stream_contents = subtle::Random::GetRandomBytes(stream_size);
auto output = absl::make_unique<TestSimpleOutputStream>();
std::string* output_buffer = output->GetBuffer();
auto output_stream =
absl::make_unique<SimpleOutputStreamAdapter>(std::move(output));
auto status = WriteToStream(output_stream.get(), stream_contents);
EXPECT_TRUE(status.ok()) << status;
EXPECT_EQ(stream_size, output_buffer->size());
EXPECT_EQ(stream_contents, *output_buffer);
}
}
TEST(SimpleOutputStreamAdapterTest, CustomBufferSizes) {
int stream_size = 1024 * 1024;
std::string stream_contents = subtle::Random::GetRandomBytes(stream_size);
for (int buffer_size : {1, 10, 100, 1000, 10000, 100000, 1000000}) {
SCOPED_TRACE(absl::StrCat("buffer_size = ", buffer_size));
auto output = absl::make_unique<TestSimpleOutputStream>();
std::string* output_buffer = output->GetBuffer();
auto output_stream = absl::make_unique<SimpleOutputStreamAdapter>(
std::move(output), buffer_size);
void* buffer;
auto next_result = output_stream->Next(&buffer);
EXPECT_TRUE(next_result.ok()) << next_result.status();
EXPECT_EQ(buffer_size, next_result.ValueOrDie());
output_stream->BackUp(buffer_size);
auto status = WriteToStream(output_stream.get(), stream_contents);
EXPECT_TRUE(status.ok()) << status;
EXPECT_EQ(stream_size, output_buffer->size());
EXPECT_EQ(stream_contents, *output_buffer);
}
}
TEST(SimpleOutputStreamAdapterTest, BackupAndPosition) {
int stream_size = 1024 * 1024;
int buffer_size = 1234;
void* buffer;
std::string stream_contents = subtle::Random::GetRandomBytes(stream_size);
auto output = absl::make_unique<TestSimpleOutputStream>();
std::string* output_buffer = output->GetBuffer();
// Prepare the stream and do the first call to Next().
auto output_stream = absl::make_unique<SimpleOutputStreamAdapter>(
std::move(output), buffer_size);
EXPECT_EQ(0, output_stream->Position());
auto next_result = output_stream->Next(&buffer);
EXPECT_TRUE(next_result.ok()) << next_result.status();
EXPECT_EQ(buffer_size, next_result.ValueOrDie());
EXPECT_EQ(buffer_size, output_stream->Position());
std::memcpy(buffer, stream_contents.data(), buffer_size);
// BackUp several times, but in total fewer bytes than returned by Next().
int total_backup_size = 0;
for (int backup_size : {0, 1, 5, 0, 10, 100, -42, 400, 20, -100}) {
SCOPED_TRACE(absl::StrCat("backup_size = ", backup_size));
output_stream->BackUp(backup_size);
total_backup_size += std::max(backup_size, 0);
EXPECT_EQ(buffer_size - total_backup_size, output_stream->Position());
}
EXPECT_LT(total_backup_size, next_result.ValueOrDie());
// Call Next(), it should succeed.
next_result = output_stream->Next(&buffer);
EXPECT_TRUE(next_result.ok()) << next_result.status();
// BackUp() some bytes, again fewer than returned by Next().
total_backup_size = 0;
for (int backup_size : {0, 72, -94, 37, 82}) {
SCOPED_TRACE(absl::StrCat("backup_size = ", backup_size));
output_stream->BackUp(backup_size);
total_backup_size += std::max(0, backup_size);
EXPECT_EQ(buffer_size - total_backup_size, output_stream->Position());
}
EXPECT_LT(total_backup_size, next_result.ValueOrDie());
// Call Next(), it should succeed;
next_result = output_stream->Next(&buffer);
EXPECT_TRUE(next_result.ok()) << next_result.status();
// Call Next() again, it should return a full block.
auto prev_position = output_stream->Position();
next_result = output_stream->Next(&buffer);
EXPECT_TRUE(next_result.ok()) << next_result.status();
EXPECT_EQ(buffer_size, next_result.ValueOrDie());
EXPECT_EQ(prev_position + buffer_size, output_stream->Position());
std::memcpy(buffer, stream_contents.data() + buffer_size, buffer_size);
// BackUp a few times, with total over the returned buffer_size.
total_backup_size = 0;
for (int backup_size :
{0, 72, -100, buffer_size / 2, 200, -25, buffer_size / 2, 42}) {
SCOPED_TRACE(absl::StrCat("backup_size = ", backup_size));
output_stream->BackUp(backup_size);
total_backup_size = std::min(buffer_size,
total_backup_size + std::max(backup_size, 0));
EXPECT_EQ(prev_position + buffer_size - total_backup_size,
output_stream->Position());
}
EXPECT_EQ(total_backup_size, buffer_size);
EXPECT_EQ(prev_position, output_stream->Position());
// Call Next() again, it should return a full block.
next_result = output_stream->Next(&buffer);
EXPECT_TRUE(next_result.ok()) << next_result.status();
EXPECT_EQ(buffer_size, next_result.ValueOrDie());
EXPECT_EQ(prev_position + buffer_size, output_stream->Position());
std::memcpy(buffer, stream_contents.data() + buffer_size, buffer_size);
// Write the remaining stream contents to stream.
auto status = WriteToStream(
output_stream.get(), stream_contents.substr(output_stream->Position()));
EXPECT_TRUE(status.ok()) << status;
EXPECT_EQ(stream_size, output_buffer->size());
EXPECT_EQ(stream_contents, *output_buffer);
}
} // namespace
} // namespace tink
} // namespace crypto
| [
"copybara-worker@google.com"
] | copybara-worker@google.com |
7948a3902ef01507cd163f841c114927d960fdd7 | 117aaf186609e48230bff9f4f4e96546d3484963 | /questions/48534529-1/main.cpp | 74d870d60db7287710a8d015971c1023e39ecd7f | [
"MIT"
] | permissive | eyllanesc/stackoverflow | 8d1c4b075e578496ea8deecbb78ef0e08bcc092e | db738fbe10e8573b324d1f86e9add314f02c884d | refs/heads/master | 2022-08-19T22:23:34.697232 | 2022-08-10T20:59:17 | 2022-08-10T20:59:17 | 76,124,222 | 355 | 433 | MIT | 2022-08-10T20:59:18 | 2016-12-10T16:29:34 | C++ | UTF-8 | C++ | false | false | 548 | cpp | #include "filemodel.h"
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QTimer>
#include <QDebug>
int main(int argc, char *argv[]) {
#if defined(Q_OS_WIN)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
qmlRegisterType<FileModel>("com.eyllanesc.filemodel", 1, 0, "FileModel");
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
| [
"e.yllanescucho@gmail.com"
] | e.yllanescucho@gmail.com |
a1d90bfc62e9c1ddd465f51b592519e18f02aa7d | d9714160fd222bc49ef52a56edb7aeb82a591549 | /bench/lib/exp/scalar/hkth1d6hkth3d4.cpp | f65ed039a55d50f6b0335eed169d5fa9b7365ed9 | [
"MIT"
] | permissive | timocafe/poly | c2fb195a196f68c406fa10130c71e29d90bc125c | 3931892bcd04f9ebfc0fde202db34d50973bc73b | refs/heads/master | 2021-01-13T00:34:32.027241 | 2020-10-02T18:42:03 | 2020-10-02T18:42:03 | 41,051,374 | 0 | 0 | null | 2020-10-02T15:27:08 | 2015-08-19T18:08:26 | C++ | UTF-8 | C++ | false | false | 1,756 | cpp | //
// hkth1d6hkth3d4_test.cpp
//
// Created by Ewart Timothée, 2/3/2016
// Copyright (c) Ewart Timothée. All rights reserved.
//
// This file is generated automatically, do not edit!
// TAG: hkth1d6hkth3d4
// Helper:
// h = Horner, e = Estrin, b = BruteForce
// The number indicates the order for Horner
// e.g. h1h3 indicates a produce of polynomial with Horner order 1 and 3
//
#include <limits>
#include <string.h>
#include <cmath>
#include <iostream>
#include "poly/poly.h"
namespace poly {
inline double sse_floor(double a) {
double b;
#ifdef __x86_64__
asm ("roundsd $1,%1,%0 " :"=x"(b) :"x"(a));
#endif
#ifdef __PPC64__
asm ("frim %0,%1 " :"=d"(b) :"d"(a));
#endif
return b;
}
static inline uint64_t as_uint64(double x) {
uint64_t i;
memcpy(&i,&x,8);
return i;
}
static inline double as_double(uint64_t i) {
double x;
memcpy(&x,&i,8);
return x;
}
double exp(double x){
uint64_t mask1 = (fabs(x) > 700);
mask1 = (mask1-1);
uint64_t mask2 = (x < 700);
mask2 = ~(mask2-1);
uint64_t mask3 = as_uint64(std::numeric_limits<double>::infinity());
const long long int tmp((long long int)sse_floor(1.4426950408889634 * x));
const long long int twok = (1023 + tmp) << 52;
x -= ((double)(tmp))*6.93145751953125E-1;
x -= ((double)(tmp))*1.42860682030941723212E-6;
double y = poly::horner_kth<poly::coeffP6,1>(x)*poly::horner_kth<poly::coeffP4_3,3>(x)* (*(double *)(&twok));
uint64_t n = as_uint64(y);
n &= mask1;
mask3 &= ~mask2;
n |= mask3;
return as_double(n);
}
} //end namespace
| [
"timothee.ewart@epfl.ch"
] | timothee.ewart@epfl.ch |
41e702ec33255a127c309654a3e85b58ca50e12c | 7a3fe1dccd3560a402dfb8f5c0ece7b3c4a054c0 | /ConsoleApplication1/Game.cpp | d04bd55df27fc4320281094507009ee40def4887 | [] | no_license | hasahmed/shapegame_cpp_win | 95b761d65c19a6b67b429a04b04c7501bd4c91c9 | db70d15e05a5ab379597576682e6843a9bb21b8d | refs/heads/master | 2021-10-02T22:02:47.976511 | 2018-12-01T11:35:04 | 2018-12-01T11:35:04 | 159,936,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,153 | cpp | #include <exception>
#include "shapegame"
using namespace shapegame;
Game* Game::_inst = nullptr;
shapegame::Game::Game(
unsigned int windowWidth,
unsigned int windowHeight,
std::string windowTitle
){
if (Game::_inst) {
throw std::runtime_error("Game can only be constructed once");
}
this->_window = std::make_unique<Window>(windowWidth, windowHeight, windowTitle);
this->scene = std::make_unique<Scene>();
this->_glHandler = std::make_unique<GLHandler>(_window.get(), *scene);
this->_vertexGenerator = std::make_unique<VertexGenerator>(_window.get());
Game::_inst = this;
}
shapegame::Game::Game() : Game(480, 480, "ShapeGame") {}
void shapegame::Game::run() {
std::cout << this->_window->info_string() << std::endl;
this->_glHandler->run();
}
shapegame::Window const* shapegame::Game::getWindow() {
return this->_window.get();
}
shapegame::Game& shapegame::Game::inst() {
if (Game::_inst) {
return *Game::_inst;
} else {
throw std::runtime_error("Instance of game cannot be returned before one was constructed");
}
} | [
"hasahmed@umail.iu.edu"
] | hasahmed@umail.iu.edu |
738cbb87b3f5b277d6ac7b6f1c2acc100305dede | 9f010ed20064f81fb6cb84b4bff7df848a987488 | /A1090/main.cpp | 32b09725432001f77df83da83e5acccf3b03ed8b | [] | no_license | specular-zxy/PAT-code | cd847db9c25c5a753028729950691163e8680c30 | d49b2557ae6105f13a8dc04d70bbaedd4951b044 | refs/heads/master | 2021-05-27T12:57:28.304496 | 2020-06-28T13:43:52 | 2020-06-28T13:43:52 | 254,268,749 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 857 | cpp | #include <cstdio>
#include <cmath>
#include <vector>
using namespace std;
const int maxn = 100010;
vector<int> child[maxn];
double p, r;
int n, maxDepth = 0, num = 0;
void DFS(int index, int depth) {
if (child[index].size() == 0) {
if (depth > maxDepth) {
maxDepth = depth;
num = 1;
} else if (depth == maxDepth) {
num++;
}
return;
}
for (int i = 0; i < child[index].size(); i++) {
DFS(child[index][i], depth + 1);
}
}
int main() {
int father, root;
scanf("%d%lf%lf", &n, &p, &r);
r /= 100;
for (int i = 0; i < n; i++) {
scanf("%d", &father);
if (father != -1) {
child[father].push_back(i);
} else {
root = i;
}
}
DFS(root, 0);
printf("%.2f %d\n", p * pow(1 + r, maxDepth), num);
} | [
"zhouxinyan33@gmail.com"
] | zhouxinyan33@gmail.com |
100661eddd0b8fec35f42efd387a379d459f61ac | dd1e33b7a6abe5e991b0f7f99bbcb06ffc8b36d1 | /Source/PresetTable.cpp | 6bc3e871ed0a62a9195dff25234c7b785fd74494 | [] | no_license | n-wave/Akateko | 45a1bb7a26d925510a00928e905816c696f1f318 | f227a8f47c497bf33dabac0ab139a9740fc5073c | refs/heads/master | 2020-03-23T14:54:32.947581 | 2018-06-29T14:45:06 | 2018-06-29T14:45:06 | 141,707,326 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,581 | cpp | /*
==============================================================================
PresetTable.cpp
Created: 27 Apr 2018 10:06:13pm
Author: mario
==============================================================================
*/
#include "PresetTable.h"
#include <algorithm>
using std::vector;
using std::sort;
using akateko::PresetRow;
PresetTable::PresetTable(vector<PresetRow> presets) :
numRows(16),
cellWidth(0.f),
cellHeight(0.f),
activeRow(-1),
currentPresets(presets),
outlineColour(Colour(0xFF70C099)),
highLightColour(Colour(0x6F20AA9A))
{
if(!currentPresets.empty()){
numRows = currentPresets.size();
}
sortPresets(nameSortAscending);
setColour(backgroundColourId, Colours::black);
}
PresetTable::~PresetTable(){
}
void PresetTable::setLookAndFeel(LookAndFeel *laf){
getHeader().setLookAndFeel(laf);
}
void PresetTable::initialiseHeader(float width, float height){
cellWidth = width*0.3333;
cellHeight = height*0.085;
getHeader().addColumn("Preset", 1, cellWidth, cellWidth, -1, TableHeaderComponent::visible, -1);
getHeader().addColumn("Category", 2, cellWidth, cellWidth, -1, TableHeaderComponent::visible, -1 );
getHeader().addColumn("Author", 3, cellWidth, cellWidth, -1, TableHeaderComponent::visible, -1);
numColums = getHeader().getNumColumns(false);
getHeader().setStretchToFitActive(true);
getHeader().setPopupMenuActive(false);
getViewport()->setScrollBarsShown(false,false,true,false); //enable mouse scrolling for now
setHeaderHeight(cellHeight);
setRowHeight(cellHeight);
setModel(this);
}
int PresetTable::getNumRows(){
return numRows;
}
void PresetTable::paintRowBackground(Graphics &g, int rowNumber, int width, int height, bool rowIsSelected){
if(rowNumber < numRows){
Colour colour = Colours::black;
if(rowIsSelected){
colour = (highLightColour);
}
g.fillAll( colour );
// draw the cell bottom divider beween rows
g.setColour( Colours::white);
g.drawLine( 0, height, width, height );
}
}
void PresetTable::paintCell(Graphics &g, int rowNumber, int columnId, int width, int height, bool rowIsSelected){
g.setColour(outlineColour);
g.fillRect(0, height-1, width, 1);
String tmpCell;
if(rowNumber < currentPresets.size()){
switch(columnId){
case 1:
tmpCell = currentPresets[rowNumber].name;
g.fillRect(0, 0, 1, height);
g.fillRect(width-1, 0, 1, height);
break;
case 2:
tmpCell = currentPresets[rowNumber].category;
g.fillRect(width-1, 0, 1, height);
break;
case 3:
tmpCell = currentPresets[rowNumber].author;
g.fillRect(width-1, 0, 1, height);
break;
}
}
g.drawText(tmpCell, 0, 0, width, height, Justification::centred);
}
void PresetTable::cellClicked(int rowNumber, int columnId, const MouseEvent &){
activeRow = rowNumber;
}
// Todo if the category or Author colum is double clicked
// Prompt the user with a window for changing
// the category or Author
void PresetTable::cellDoubleClicked(int rowNumber, int columnId, const MouseEvent &){
if(rowNumber < currentPresets.size()){
cellPosition = getCellPosition(columnId,rowNumber, true);
activeRow = rowNumber;
dClickRow = rowNumber;
dClickCol = columnId;
getParentComponent()->postCommandMessage(requestTextEditor);
}
}
void PresetTable::setCurrentPresets(std::vector<akateko::PresetRow> presets){
currentPresets.clear();
currentPresets = vector<PresetRow>(presets);
numRows = currentPresets.size();
}
void PresetTable::changeName(int rowNumber, const String name){
if(rowNumber < currentPresets.size()){
currentPresets[rowNumber].name = name;
}
}
void PresetTable::changeAuthor(int rowNumber, const String author){
if(rowNumber < currentPresets.size()){
currentPresets[rowNumber].author = author;
}
}
void PresetTable::changeCategory(int rowNumber, const String category){
if(rowNumber < currentPresets.size()){
currentPresets[rowNumber].category = category;
}
}
Rectangle<int> PresetTable::getClickedCellPosition(){
return cellPosition;
}
int PresetTable::getActiveRow(){
return activeRow;
}
void PresetTable::resetActiveRow(){
activeRow = -1;
}
int PresetTable::getClickedRow(){
return dClickRow;
}
int PresetTable::getClickedColumn(){
return dClickCol;
}
File PresetTable::getFile(int rowNum){
File tmpFile;
if(rowNum < currentPresets.size()){
tmpFile = currentPresets[rowNum].file;
}
return tmpFile;
}
String PresetTable::getName(int rowNum){
String tmpName = String();
if(rowNum < currentPresets.size()){
tmpName = currentPresets[rowNum].name;
}
return tmpName;
}
bool PresetTable::getPresetRow(int rowNum, PresetRow &result){
if(rowNum < currentPresets.size()){
result.file = currentPresets[rowNum].file;
result.name = currentPresets[rowNum].name;
result.category = currentPresets[rowNum].category;
result.author = currentPresets[rowNum].author;
return true;
}
return false;
}
void PresetTable::sortPresets(Sort order){
switch(order){
case nameSortAscending:
sort(currentPresets.begin(), currentPresets.end(), &akateko::nameSortAscending);
break;
case nameSortDescending:
sort(currentPresets.begin(), currentPresets.end(), &akateko::nameSortDescending);
break;
case categorySortAscending:
sort(currentPresets.begin(), currentPresets.end(), &akateko::categorySortAscending);
break;
case categorySortDescending:
sort(currentPresets.begin(), currentPresets.end(), &akateko::categorySortDescending);
break;
case authorSortAscending:
sort(currentPresets.begin(), currentPresets.end(), &akateko::authorSortAscending);
break;
case autherSortDescending:
sort(currentPresets.begin(), currentPresets.end(), &akateko::authorSortDescending);
break;
}
}
| [
"info@n-wave.systems"
] | info@n-wave.systems |
135b3473f8b452f11df2da65ae2052c1d6d4575f | b54829c3408a645bb0a13bccd4cc89df853ea3b3 | /ReactionGameWithArcadianStyleLed.cydsn/Generated_Source/PSoC5/ErikaOS_1_ee_as_internal.inc | 507c65267fd352bb524fee47dac6cc18c8557378 | [] | no_license | aadarshkumar-singh/ReactionGameWithArcadianLeds | e023b437cf2b5735fc578ff981cab3b395e83688 | f4b3e44e8dfa05c9fca23d32691c119ca7279577 | refs/heads/master | 2022-06-06T17:24:39.638079 | 2020-04-26T16:09:55 | 2020-04-26T16:09:55 | 259,063,626 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,849 | inc | /* ###*B*###
* ERIKA Enterprise - a tiny RTOS for small microcontrollers
*
* Copyright (C) 2002-2012 Evidence Srl
*
* This file is part of ERIKA Enterprise.
*
* ERIKA Enterprise is free software; you can redistribute it
* and/or modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation,
* (with a special exception described below).
*
* Linking this code statically or dynamically with other modules is
* making a combined work based on this code. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this code with independent modules to produce an
* executable, regardless of the license terms of these independent
* modules, and to copy and distribute the resulting executable under
* terms of your choice, provided that you also meet, for each linked
* independent module, the terms and conditions of the license of that
* module. An independent module is a module which is not derived from
* or based on this library. If you modify this code, you may extend
* this exception to your version of the code, but you are not
* obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*
* ERIKA Enterprise is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License version 2 for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with ERIKA Enterprise; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
* ###*E*### */
/** @file ee_as_internal.h
* @brief Internals for Autosar layer
* @author Errico Guidieri
* @date 2012
*/
/*
* PSoC Port and API Generation
* Carlos Fernando Meier Martinez
* Hochschule Darmstadt, Germany. 2017.
*/
#ifndef PKG_KERNEL_AS_INC_EE_AS_INTERNAL_H
#define PKG_KERNEL_AS_INC_EE_AS_INTERNAL_H
#include "ErikaOS_1_ee_as_kernel.inc"
#ifdef EE_AS_USER_SPINLOCKS__
/*******************************************************************************
* Spinlock Internal Clean-Up
******************************************************************************/
__INLINE__ EE_TYPEBOOL
EE_as_has_spinlocks_locked( EE_TID tid )
{
SpinlockIdType const spinlock_id = EE_as_spinlocks_last[EE_CURRENTCPU];
return ( (spinlock_id != INVALID_SPINLOCK) &&
(EE_as_spinlocks_locker_task_or_isr2[spinlock_id] == tid) );
}
/* Internal Clean-up function */
SpinlockIdType EE_as_release_all_spinlocks( EE_TID tid );
#else /* EE_AS_USER_SPINLOCKS__ */
#define EE_as_release_all_spinlocks(tid) ((void)0U)
#endif /* EE_AS_USER_SPINLOCKS__ */
/*******************************************************************************
* Schedule Tables Utilities
******************************************************************************/
#ifdef EE_AS_SCHEDULETABLES__
/* Utilities inline functions to check ticks and deviation values */
__INLINE__ TickType EE_as_tick_min( TickType t1, TickType t2 )
{
if ( t1 <= t2 ) {
return t1;
} else {
return t2;
}
}
__INLINE__ EE_UREG EE_as_abs( TickType t )
{
if ( t < EE_TYPETICK_HALF_VALUE ) {
return t;
} else {
return -t;
}
}
#endif /* EE_AS_SCHEDULETABLES__ */
#ifdef EE_AS_RPC__
/*******************************************************************************
* Synchronous Remote Procedure Calls
******************************************************************************/
/** @brief Macro used to check if an id is a remote id */
#define EE_AS_ID_REMOTE(id) ((((EE_UINT32)(id)) & \
(EE_UINT32)EE_REMOTE_TID) != 0U)
/** @brief Macro used to unmark a remote id */
#define EE_AS_UNMARK_REMOTE_ID(id) (((EE_UINT32)(id)) & (~EE_REMOTE_TID))
/** @brief define that identify an invalid ServiceId */
#define INVALID_SERVICE_ID ((OSServiceIdType)-1)
#define INVALID_ERROR ((StatusType)-1)
/** @brief RPC Handler to be called inside IIRQ handler */
extern void EE_as_rpc_handler( void );
/* If MemMap.h support is enabled (i.e. because memory protection): use it */
#ifdef EE_SUPPORT_MEMMAP_H
/* The following code belong to ERIKA API section ee_api_text */
#define API_START_SEC_CODE
#include "MemMap.inc"
#endif /* EE_SUPPORT_MEMMAP_H */
#ifdef __EE_MEMORY_PROTECTION__
/** @brief The following implement a synchronous RPC kernel primitive from
"user space" (so it's a syscall). */
extern StatusType EE_as_rpc_from_us( OSServiceIdType ServiceId,
EE_os_param param1, EE_os_param param2, EE_os_param param3 );
#else /* __EE_MEMORY_PROTECTION__ */
__INLINE__ StatusType EE_as_rpc_from_us( OSServiceIdType
ServiceId, EE_os_param param1, EE_os_param param2, EE_os_param param3 )
{
StatusType ev;
register EE_FREG const flag = EE_hal_begin_nested_primitive();
ev = EE_as_rpc(ServiceId, param1, param2, param3);
EE_hal_end_nested_primitive(flag);
return ev;
}
#endif /* __EE_MEMORY_PROTECTION__ */
#ifdef EE_SUPPORT_MEMMAP_H
#define API_STOP_SEC_CODE
#include "MemMap.inc"
#endif /* EE_SUPPORT_MEMMAP_H */
#endif /* EE_AS_RPC__ */
#ifdef EE_AS_OSAPPLICATIONS__
/*******************************************************************************
* OSApplication Utilities
******************************************************************************/
/** @brief Used to terminate current OS-Application. */
void EE_as_terminate_current_app_task( void );
/** @brief Used to terminate current OS-Application. */
#if defined(EE_MAX_ISR2) && (EE_MAX_ISR2 > 0)
__INLINE__ void EE_as_terminate_current_app( void )
{
if ( EE_hal_get_IRQ_nesting_level() == 0U ) {
/* We are in a TASK */
EE_as_terminate_current_app_task();
} else {
/* We are in the an ISR2 */
(void)EE_as_TerminateISR2();
}
}
#else /* EE_MAX_ISR2 > 0 */
__INLINE__ void EE_as_terminate_current_app( void )
{
/* There are no ISR2: We are in a TASK */
EE_as_terminate_current_app_task();
}
#endif /* EE_MAX_ISR2 > 0 */
/**
* @brief Supposed to be called by EE_as_TerminateISR2 to restore trackin
* OSApplication global variable and eventually terminate stacked.
*/
void EE_as_after_IRQ_interrupted_app ( ApplicationType interrupted_app );
/* @brief Function determines the currently running OS-Application.
* (a unique identifier has to be allocated to each application).
*/
#if 0
ApplicationType EE_as_GetApplicationID_internal( void );
#endif
/** @brief his service determines if the OS-Applications, given by ApplID, is
* allowed to use the IDs of a Task, ISR, Resource, Counter, Alarm or
* Schedule Table in API calls. */
ObjectAccessType EE_as_CheckObjectAccess_internal( ApplicationType ApplID,
ObjectTypeType ObjectType, EE_UTID ObjectID );
/** @brief his service determines the OS-Applications to which the
ID of a Task, ISR, Resource, Counter, Alarm or Schedule Table belong to. */
ApplicationType EE_as_CheckObjectOwnership_internal( ObjectTypeType ObjectType,
EE_os_param_id ObjectID );
/** @brief Internal part of TerminateApplication service */
void EE_as_TerminateApplication_internal( ApplicationType Application,
RestartType RestartOption );
/* THESE HAL FUNCTIONS DECLARATION ARE PUT HERE BECAUSE SIGNATURE DEPENDS ON
AS KERNEL TYPES */
/** @brief Call application hook with right privileges */
void EE_hal_call_app_hook( EE_HOOKTYPE hook, ApplicationType app );
/** @brief Call status application hook with right privileges */
void EE_hal_call_app_status_hook( StatusType Error, EE_STATUSHOOKTYPE
status_hook, ApplicationType app );
/** @brief Utility macro used to transform a Application ID in a bit mask */
#define EE_APP_TO_MASK(app_id) ((EE_TYPEACCESSMASK)1U << (app_id))
#ifdef EE_SERVICE_PROTECTION__
/*******************************************************************************
* OSApplication Service Protection Access Data Structures
******************************************************************************/
/* [OS056] If an OS-object identifier is the parameter of an Operating System
module's system service, and no sufficient access rights have been assigned
to this OS-object at configuration time
(Parameter Os[...]AccessingApplication) to the calling Task/Category 2 ISR,
the Operating System module's system service shall return E_OS_ACCESS.
(BSW11001, BSW11010, BSW11013) */
/* [OS448]: The Operating System module shall prevent access of OS-Applications,
trusted or non-trusted, to objects not belonging to this OS-Application,
except access rights for such objects are explicitly granted by
configuration.
*/
/* [OS504] The Operating System module shall deny access to Operating System
objects from other OS-Applications to an OS-Application which is not in
state APPLICATION_ACCESSIBLE. */
/* [OS509] If a service call is made on an Operating System object that is owned
by another OS-Application without state APPLICATION_ACCESSIBLE,
then the Operating System module shall return E_OS_ACCESS. */
/** @var Contains access rules for TASKs */
extern EE_TYPEACCESSMASK const EE_as_task_access_rules[/*EE_MAX_TASK*/];
/** @var Contains access rules for ISRs */
extern EE_TYPEACCESSMASK const EE_as_isr_access_rules[/*EE_MAX_ISR_ID*/];
#ifndef __OO_NO_RESOURCES__
/** @var Contains access rules for RESOURCESs */
extern EE_TYPEACCESSMASK const EE_as_resource_access_rules[/*EE_MAX_RESOURCE*/];
#endif /* !__OO_NO_RESOURCES__ */
#if (!defined(__OO_NO_ALARMS__)) || defined(EE_AS_SCHEDULETABLES__)
/** @var Contains access rules for COUNTERs */
extern EE_TYPEACCESSMASK const EE_as_counter_access_rules[/*EE_MAX_COUNTER*/];
#endif /* !__OO_NO_ALARMS__ || !EE_AS_SCHEDULETABLES__ */
#ifndef __OO_NO_ALARMS__
/** @var Contains access rules for ALARMs */
extern EE_TYPEACCESSMASK const EE_as_alarm_access_rules[/*EE_MAX_ALARM*/];
#endif /* !__OO_NO_ALARMS__ */
#ifdef EE_AS_SCHEDULETABLES__
/** @var Contains access rules for SCHEDULE TABLEs */
extern EE_TYPEACCESSMASK const
EE_as_scheduletable_access_rules[/*EE_MAX_SCHEDULETABLE*/];
#endif /* EE_AS_SCHEDULETABLES__ */
#ifdef EE_AS_USER_SPINLOCKS__
/** @var Contains access rules for SCHEDULE TABLEs */
extern EE_TYPEACCESSMASK const
EE_as_spinlock_access_rules[/*EE_MAX_SPINLOCK_USER*/];
#endif /* EE_AS_USER_SPINLOCKS__ */
/* OSApplication Objects belog to active Macros */
#define EE_OSAPP_TASK_ACCESS(TaskID) (EE_as_Application_RAM[\
EE_th_app[(TaskID + 1U)]].ApplState == APPLICATION_ACCESSIBLE)
#define EE_OSAPP_ISR_ACCESS(ISRID) (EE_as_Application_RAM[\
EE_as_ISR_ROM[ISRID].ApplID].ApplState == APPLICATION_ACCESSIBLE)
#define EE_OSAPP_COUNTER_ACCESS(CounterID) (EE_as_Application_RAM[\
EE_counter_ROM[CounterID].ApplID].ApplState == APPLICATION_ACCESSIBLE)
#define EE_OSAPP_ALARM_ACCESS(AlarmID) (EE_as_Application_RAM[\
EE_alarm_ROM[AlarmID].ApplID].ApplState == APPLICATION_ACCESSIBLE)
#define EE_OSAPP_SCHED_TABLE_ACCESS(SchedTableID) (EE_as_Application_RAM[\
EE_as_Schedule_Table_ROM[SchedTableID].ApplID].ApplState == \
APPLICATION_ACCESSIBLE)
/* Access Macros */
#define EE_TASK_ACCESS(TaskID, ApplID) (((EE_as_task_access_rules[TaskID] & \
EE_APP_TO_MASK(ApplID)) && EE_OSAPP_TASK_ACCESS(TaskID)))
#define EE_ISR_ACCESS(ISRID, ApplID) (((EE_as_isr_access_rules[ISRID] & \
EE_APP_TO_MASK(ApplID)) && EE_OSAPP_ISR_ACCESS(ISRID)))
#define EE_COUNTER_ACCESS(CounterID, ApplID) \
(((EE_as_counter_access_rules[CounterID] & EE_APP_TO_MASK(ApplID)) && \
EE_OSAPP_COUNTER_ACCESS(CounterID)))
#define EE_ALARM_ACCESS(AlarmID, ApplID) (((EE_as_alarm_access_rules[\
AlarmID] & EE_APP_TO_MASK(ApplID)) && EE_OSAPP_ALARM_ACCESS(AlarmID)))
#define EE_SCHED_TABLE_ACCESS(SchedTableID, ApplID) \
(((EE_as_scheduletable_access_rules[SchedTableID] & EE_APP_TO_MASK(ApplID)) \
&& EE_OSAPP_SCHED_TABLE_ACCESS(SchedTableID)))
#define EE_RESOURCE_ACCESS(ResourceID, ApplID) \
((EE_as_resource_access_rules[ResourceID] & EE_APP_TO_MASK(ApplID)))
#define EE_SPINLOCK_ACCESS(SpinlockID, ApplID) \
((EE_as_spinlock_access_rules[SpinlockID] & EE_APP_TO_MASK(ApplID)))
/* Error Macros */
#define EE_TASK_ACCESS_ERR(TaskID, ApplID) (!EE_TASK_ACCESS(TaskID, ApplID))
#define EE_ISR_ACCESS_ERR(ISRID, ApplID) (!EE_ISR_ACCESS(ISRID, ApplID))
#define EE_COUNTER_ACCESS_ERR(CounterID, ApplID) (!EE_COUNTER_ACCESS(CounterID,\
ApplID))
#define EE_ALARM_ACCESS_ERR(AlarmID, ApplID) (!EE_ALARM_ACCESS(AlarmID, \
ApplID))
#define EE_SCHED_TABLE_ACCESS_ERR(SchedTableID, ApplID) \
(!EE_SCHED_TABLE_ACCESS(SchedTableID, ApplID))
#define EE_RESOURCE_ACCESS_ERR(ResourceID, ApplID) \
(!EE_RESOURCE_ACCESS(ResourceID, ApplID))
#define EE_SPINLOCK_ACCESS_ERR(SpinlockID, ApplID) \
(!EE_SPINLOCK_ACCESS(SpinlockID, ApplID))
#endif /* EE_SERVICE_PROTECTION__ */
#endif /* EE_AS_OSAPPLICATIONS__ */
#ifdef EE_AS_HAS_PROTECTIONHOOK__
/*******************************************************************************
* ProtectionHook Internal Support
******************************************************************************/
#ifdef EE_AS_OSAPPLICATIONS__
/**
* @brief This function wraps the call to the protection hook.
* Also, it does what is required to do according to what the ProtectionHook
* returns.
* @param error_app the OS-Application that caused the error
* @param error the error to send to the ProtectionHook function
*/
void EE_as_handle_protection_error( ApplicationType error_app,
StatusType error );
#else /* EE_AS_OSAPPLICATIONS__ */
/**
* @brief This function wraps the call to the protection hook.
* Also, it does what is required to do according to what the ProtectionHook
* returns.
* @param error the error to send to the ProtectionHook function
*/
void EE_as_handle_protection_error( StatusType error );
#endif /* EE_AS_OSAPPLICATIONS__ */
#endif /* EE_AS_HAS_PROTECTIONHOOK__ */
#ifdef __EE_MEMORY_PROTECTION__
/*******************************************************************************
* Memory Protection Internal Support
******************************************************************************/
/** Syscall table */
extern EE_FADDR const EE_syscall_table[/*EE_SYSCALL_NR*/];
/** @typedef for TRUSTED Function pointers */
typedef StatusType (*EE_TRUSTEDFUNCTYPE)(TrustedFunctionIndexType,
TrustedFunctionParameterRefType);
/* THIS HAL FUNCTIONS DECLARATION ARE PUT HERE BECAUSE SIGNATURE DEPENDS ON
AS KERNEL TYPES */
/**
* Return the access permission for the given memory area. Defined in the CPU
* layer. */
AccessType EE_hal_get_app_mem_access(ApplicationType app,
MemoryStartAddressType beg, MemorySizeType size);
#if defined(EE_SYSCALL_NR) && defined(EE_MAX_SYS_SERVICEID) &&\
(EE_SYSCALL_NR > EE_MAX_SYS_SERVICEID)
__INLINE__ EE_TYPEBOOL
EE_as_active_app_is_inside_trusted_function_call ( void )
{
return EE_as_Application_RAM[EE_as_active_app].
TrustedFunctionCallsCounter != 0U;
}
#else /* EE_SYSCALL_NR > EE_MAX_SYS_SERVICEID */
#define EE_as_active_app_is_inside_trusted_function_call() EE_FALSE
#endif /* EE_SYSCALL_NR > EE_MAX_SYS_SERVICEID */
#else /* __EE_MEMORY_PROTECTION__ */
#define EE_as_active_app_is_inside_trusted_function_call() EE_FALSE
#endif /* __EE_MEMORY_PROTECTION__ */
/*******************************************************************************
* Stack Monitoring Internal Support
******************************************************************************/
#ifdef EE_STACK_MONITORING__
#ifdef EE_AS_OSAPPLICATIONS__
/* Functions used to check and handle Stack Overflow, with short cut to
pass current application */
void EE_as_check_and_handle_stack_overflow( ApplicationType appid,
EE_UREG stktop );
#else /* EE_AS_OSAPPLICATIONS__ */
/* Functions used to check and handle Stack Overflow. Have to be to be
implemented in each porting that support stack monitoring */
void EE_as_check_and_handle_stack_overflow( EE_UREG stktop );
#endif /* EE_AS_OSAPPLICATIONS__ */
/* Used Internally in Kernel primitives */
void EE_as_monitoring_the_stack( void );
#else /* EE_STACK_MONITORING__ */
#ifdef EE_AS_OSAPPLICATIONS__
__INLINE__ void
EE_as_check_and_handle_stack_overflow( ApplicationType appid, EE_UREG stktop ) {}
#else /* EE_AS_OSAPPLICATIONS__ */
__INLINE__ void
EE_as_check_and_handle_stack_overflow( EE_UREG stktop ) {}
#endif /* EE_AS_OSAPPLICATIONS__ */
__INLINE__ void EE_as_monitoring_the_stack( void ) {}
#endif /* EE_STACK_MONITORING__ */
/* Used to select witch system ERROR handling function call */
#ifdef EE_AS_HAS_PROTECTIONHOOK__
#ifdef EE_AS_OSAPPLICATIONS__
#define EE_as_call_protection_error(app, error) \
EE_as_handle_protection_error(app, error)
#else /* EE_AS_OSAPPLICATIONS__ */
#define EE_as_call_protection_error(app, error) \
EE_as_handle_protection_error(error)
#endif /* EE_AS_OSAPPLICATIONS__ */
#else /* EE_AS_HAS_PROTECTIONHOOK__ */
#define EE_as_call_protection_error(app, error) \
EE_oo_ShutdownOS_internal(error)
#endif /* EE_AS_HAS_PROTECTIONHOOK__ */
#endif /* INCLUDE_EE_KERNEL_AS_INTERNAL__ */
| [
"aadarshxp@gmail.com"
] | aadarshxp@gmail.com |
c96be9f1489b7cbe34c981e06957adea97e23dbd | bb7d3a8c005d2dd14c22651b89ae7ca4ddaad37e | /2/main.cpp | 23537971c4dab2b9b678881287ed8c1caf9e5dcb | [] | no_license | gheome/TemaIP123 | 45e700c7ccea927c4f8253944bae84d7e9aa69f6 | 4d6887e464a98fbb6820cf274fae2c422d9f0f8b | refs/heads/master | 2021-01-11T01:11:24.412464 | 2016-10-16T20:04:21 | 2016-10-16T20:04:21 | 71,071,062 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 303 | cpp | #include <iostream>
using namespace std;
unsigned char sumBinaryFigure(unsigned long long number)
{
int nr;
nr=0;
while(number>0)
{
if (number%2==1)
nr++;
number=number/2;
}
return nr;
}
int main()
{
return sumBinaryFigure(111111222211);
return 0;
}
| [
"alexandru_gh97@yahoo.co.uk"
] | alexandru_gh97@yahoo.co.uk |
57c31a802f9aad39bc088ff9a39be85ae1dc2788 | dc888595f079eade0807235c1880642600974d95 | /seven day_1/build-gridLayout-Desktop_Qt_5_7_0_MinGW_32bit-Debug/debug/moc_widget.cpp | 0d029dcb973488f7f56de84cf6964c13872bc0a0 | [] | no_license | WenchaoZhang/qt_learing | 53377594e4102a68ddcadfab121d502ffab72a53 | 33e4dbdbd3a2c35e124c923b850e6e244aab320b | refs/heads/master | 2021-01-23T19:29:10.871224 | 2017-09-30T04:40:22 | 2017-09-30T04:40:22 | 102,826,803 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,550 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'widget.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.7.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../gridLayout/widget.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'widget.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.7.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_Widget_t {
QByteArrayData data[1];
char stringdata0[7];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_Widget_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_Widget_t qt_meta_stringdata_Widget = {
{
QT_MOC_LITERAL(0, 0, 6) // "Widget"
},
"Widget"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_Widget[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void Widget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObject Widget::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_Widget.data,
qt_meta_data_Widget, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *Widget::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *Widget::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_Widget.stringdata0))
return static_cast<void*>(const_cast< Widget*>(this));
return QWidget::qt_metacast(_clname);
}
int Widget::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| [
"269426626@qq.com"
] | 269426626@qq.com |
3b561abe183d2204efc29915f5292126b9f512d3 | 0b69a011c9ffee099841c140be95ed93c704fb07 | /problemsets/UVA/993.cpp | 4155c9820d3017be5cf27aff3c41814b35a1317e | [
"Apache-2.0"
] | permissive | juarezpaulino/coderemite | 4bd03f4f2780eb6013f07c396ba16aa7dbbceea8 | a4649d3f3a89d234457032d14a6646b3af339ac1 | refs/heads/main | 2023-01-31T11:35:19.779668 | 2020-12-18T01:33:46 | 2020-12-18T01:33:46 | 320,931,351 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 619 | cpp | /**
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
*/
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
int main() {
int T, N;
scanf("%d", &T);
while (T--) {
scanf("%d", &N);
if (N < 10) { printf("%d\n", N); continue; }
int C[10] = {0};
for (int c = 9; c >= 2; c--)
while (N%c == 0) { C[c]++; N /= c; }
if (N != 1) puts("-1");
else {
for (int c = 2; c < 10; c++) for (int i = 0; i < C[c]; i++) putchar(c+'0');
putchar('\n');
}
}
return 0;
}
| [
"juarez.paulino@gmail.com"
] | juarez.paulino@gmail.com |
31214f42b2431a53de5e9505d1dd105c9b7f1a49 | f3ee233dc76c097134931f4988b1b5c94ce6879e | /WeatherStation_CPP/Src/cpp_Light_Sensor.cpp | 5faf3f5b9c8ecdc28aa2d66ffc28099f9648fa6e | [] | no_license | mitea1/WeatherStation_Cpp | d5ee59799718da080779ec5e8acb6c425d42f631 | 47ae8995a41c9179f36e7d1b5c056e4ab9fe9a20 | refs/heads/master | 2016-09-12T10:55:39.837159 | 2016-04-29T22:48:03 | 2016-04-29T22:48:03 | 56,344,920 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 885 | cpp | /*
* Light_Sensor_CPP.cpp
*
* Created on: Apr 20, 2016
* Author: Simon
*/
/*----- Header-Files -------------------------------------------------------*/
#include "cpp_Light_Sensor.hpp"
/*----- Macros -------------------------------------------------------------*/
/*----- Data types ---------------------------------------------------------*/
/*----- Data ---------------------------------------------------------------*/
/*----- Implementation -----------------------------------------------------*/
/**
* @brief Constructor for Light_Sensor class
*/
Light_Sensor::Light_Sensor(){
LIGHT_SENSOR_init();
}
/**
* @brief Destructor for Light_Sensor class
*/
Light_Sensor::~Light_Sensor(){
}
/**
* @brief Gets Lux form Light Sensor
* @return Brightness in Lux
*/
double Light_Sensor::getLux(){
return LIGHT_SENSOR_getLux();
}
| [
"bolzs2@bfh.ch"
] | bolzs2@bfh.ch |
604f72ad2a5a8078f411d0a809875b7d4a9cb2b8 | 4d9bbd510b0af8778daba54fe2b1809216463fa6 | /build/Android/Debug/app/src/main/include/Fuse.Scripting.JSObjectUtils.h | 9d76447f80d5acfc3d200b971f3180c654411126 | [] | no_license | Koikka/mood_cal | c80666c4930bd8091e7fbe4869f5bad2f60953c1 | 9bf73aab2998aa7aa9e830aefb6dd52e25db710a | refs/heads/master | 2021-06-23T20:24:14.150644 | 2020-09-04T09:25:54 | 2020-09-04T09:25:54 | 137,458,064 | 0 | 0 | null | 2020-12-13T05:23:20 | 2018-06-15T07:53:15 | C++ | UTF-8 | C++ | false | false | 1,596 | h | // This file was generated based on node_modules/@fuse-open/fuselibs/Source/build/Fuse.Scripting/1.12.0/JSObjectUtils.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.h>
namespace g{namespace Fuse{namespace Scripting{struct Context;}}}
namespace g{namespace Fuse{namespace Scripting{struct JSObjectUtils;}}}
namespace g{namespace Fuse{namespace Scripting{struct Object;}}}
namespace g{
namespace Fuse{
namespace Scripting{
// public static class JSObjectUtils
// {
uClassType* JSObjectUtils_typeof();
void JSObjectUtils__Freeze_fn(::g::Fuse::Scripting::Object* ob, ::g::Fuse::Scripting::Context* c);
void JSObjectUtils__ValueOrDefault_fn(uType* __type, ::g::Fuse::Scripting::Object* obj, uString* name, void* defaultValue, uTRef __retval);
void JSObjectUtils__ValueOrDefault1_fn(uType* __type, uArray* args, int32_t* index, void* defaultValue, uTRef __retval);
struct JSObjectUtils : uObject
{
static void Freeze(::g::Fuse::Scripting::Object* ob, ::g::Fuse::Scripting::Context* c);
template<class T>
static T ValueOrDefault(uType* __type, ::g::Fuse::Scripting::Object* obj, uString* name, T defaultValue) { T __retval; return JSObjectUtils__ValueOrDefault_fn(__type, obj, name, uConstrain(__type->U(0), defaultValue), &__retval), __retval; }
template<class T>
static T ValueOrDefault1(uType* __type, uArray* args, int32_t index, T defaultValue) { T __retval; return JSObjectUtils__ValueOrDefault1_fn(__type, args, &index, uConstrain(__type->U(0), defaultValue), &__retval), __retval; }
};
// }
}}} // ::g::Fuse::Scripting
| [
"antti.koivisto@samk.fi"
] | antti.koivisto@samk.fi |
cb318f5136d99c6a2d67e0a080b0a7529f8714a0 | b904263df73ce56b3c6f7e05b2bafb5abf46f21a | /gdipp_demo_render/commandline.cpp | 4dc7daba3681d44d27bd540d8db4288742e1993e | [
"MIT"
] | permissive | dbautsch/gdipp-conf-editor | cc1c9fbf8dfda81a80da927b4044d0c7ce340547 | 817acdc9464db172782f465a44b27bfa917ef86f | refs/heads/master | 2021-07-02T14:56:02.149213 | 2020-12-21T18:26:14 | 2020-12-21T18:26:14 | 208,060,372 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,183 | cpp | /*
Copyright (c) 2019 Dawid Bautsch
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 "commandline.h"
#include <iostream>
#include "../gdipp-conf-editor/util.h"
CommandLine::CommandLine()
{
ParseCommands();
}
void CommandLine::ParseCommands()
{
LPWSTR * commandsList = NULL;
int argc;
commandsList = CommandLineToArgvW(GetCommandLineW(), &argc);
if (commandsList == NULL)
{
throw std::runtime_error("Unable to obtain program arguments list.");
}
for (int i = 0; i < argc; ++i)
{
try
{
LPWSTR argument = commandsList[i];
std::pair<MetaString, MetaString> programArgument =
SplitArgument(argument);
commands.insert(programArgument);
}
catch (const std::exception & e)
{
std::cerr << e.what() << std::endl;
}
}
LocalFree(commandsList);
}
MetaString CommandLine::Get(const MetaString & name) const
{
CommandEntities::const_iterator it = commands.find(name);
if (it == commands.end())
{
return MetaString();
}
return it->second;
}
std::pair<MetaString, MetaString> CommandLine::SplitArgument(LPWSTR argument) const
{
std::pair<MetaString, MetaString> result;
MetaString argumentStr = Util::CreateMetaString(argument);
size_t equalSignPos = argumentStr.find(TEXT("="));
if (equalSignPos == MetaString::npos)
{
// no equal sign, key is the same as the value
// this is type of `flag` argument
result = std::make_pair(Unquote(argumentStr), Unquote(argumentStr));
}
else
{
MetaString key = Unquote(argumentStr.substr(0, equalSignPos));
MetaString value = Unquote(argumentStr.substr(equalSignPos + 1, argumentStr.length() - equalSignPos - 1));
result = std::make_pair(key, value);
}
return result;
}
MetaString CommandLine::Unquote(const MetaString & text) const
{
if (text[0] == TEXT('\"') && text[text.length() - 1] == TEXT('\"'))
{
// trim quotes
return text.substr(1, text.length() - 2);
}
return text;
}
| [
"dawid@bautsch.pl"
] | dawid@bautsch.pl |
000384326b414cc12fde586ff73a5ec5e224f532 | 633842301cd36cad562767da691ed5297ccd559f | /Accepted/zerojudge/a034. 二進位制轉換.cpp | 643d1683c28f534d7835d148ab6ef72a0f26795d | [] | no_license | turtle11311/Codes | c5b87864f59802241b6784ccd5cd553fe5533748 | 7711679dffb421323ab2cc389662d106d50ab16c | refs/heads/master | 2020-04-06T05:20:33.810466 | 2014-12-24T12:20:13 | 2014-12-24T12:20:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 292 | cpp | #include <iostream>
#include <string>
using namespace std;
int main () {
long long int n, i;
char ans[60];
while (cin >> n) {
for (i=0;i<60;i++)
ans[i]=' ';
for (i=0;n != 0;n/=2,i++)
ans[i]=n%2+'0';
for (i-=1;i>=0;i--)
cout << ans[i];
cout << endl;
}
}
| [
"turtle11311@hotmail.com"
] | turtle11311@hotmail.com |
9cfd63ec381c30e60c8e82aac8f62958be1fe804 | d43c3fbfd149d2ac0a051a0074585dce345ae967 | /muduo/muduo/base/AsyncLogging.h | 8aaa827df955de6b60c0a78c461f5d93061cb52b | [
"BSD-3-Clause"
] | permissive | wuzhl2018/AnnotatedVersion | 3dad25b843a7ba5dd272dca61e9bde98483dd1af | bfdafa36e18e7212fac01762e628aef28633b9a4 | refs/heads/master | 2020-09-16T22:03:22.695817 | 2019-11-20T05:18:34 | 2019-11-20T05:18:34 | 223,900,026 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,706 | h | #ifndef MUDUO_BASE_ASYNCLOGGING_H
#define MUDUO_BASE_ASYNCLOGGING_H
#include <muduo/base/BlockingQueue.h>
#include <muduo/base/BoundedBlockingQueue.h>
#include <muduo/base/CountDownLatch.h>
#include <muduo/base/Mutex.h>
#include <muduo/base/Thread.h>
#include <muduo/base/LogStream.h>
#include <boost/bind.hpp>
#include <boost/noncopyable.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
namespace muduo
{
class AsyncLogging : boost::noncopyable
{
public:
AsyncLogging(const string& basename,
off_t rollSize,
int flushInterval = 3);
~AsyncLogging()
{
if (running_)
{
stop();
}
}
void append(const char* logline, int len);
void start()
{
running_ = true;
thread_.start();
latch_.wait();
}
void stop() NO_THREAD_SAFETY_ANALYSIS
{
running_ = false;
cond_.notify();
thread_.join();
}
private:
// declare but not define, prevent compiler-synthesized functions
AsyncLogging(const AsyncLogging&); // ptr_container
void operator=(const AsyncLogging&); // ptr_container
void threadFunc();
typedef muduo::detail::FixedBuffer<muduo::detail::kLargeBuffer> Buffer;
typedef boost::ptr_vector<Buffer> BufferVector;
typedef BufferVector::auto_type BufferPtr;
const int flushInterval_;
bool running_;
const string basename_;
const off_t rollSize_;
muduo::Thread thread_;
muduo::CountDownLatch latch_;
muduo::MutexLock mutex_;
muduo::Condition cond_ GUARDED_BY(mutex_);
BufferPtr currentBuffer_ GUARDED_BY(mutex_);
BufferPtr nextBuffer_ GUARDED_BY(mutex_);
BufferVector buffers_ GUARDED_BY(mutex_);
};
}
#endif // MUDUO_BASE_ASYNCLOGGING_H
| [
"805356546@qq.com"
] | 805356546@qq.com |
0dcc6931687b70e8737fbf4bf1b324537ebe98b5 | 563e3598843e0d7883c34d7d7fab130259cc0d60 | /PalindromePermutation.cpp | 89f7e88ea939c4ee42f408046b44d35f0560d3a1 | [] | no_license | rshah918/Cracking-the-Coding-Interview | a315ba17bf590f23ebb343fa231df6c02d49e07f | e8d2fe39975f3dcad44bb931b6baa44ab7b4a9f9 | refs/heads/master | 2023-08-18T12:10:46.766123 | 2021-10-07T22:23:25 | 2021-10-07T22:23:25 | 270,379,968 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 927 | cpp | #include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
bool palindromePermutation(string s){
unordered_map<char, int> char_count;
int num_odd_chars = 0;
for(int i = 0; i < s.length(); i++){
char curr = s[i];
//increment character count in hash table
if(char_count.find(curr) == char_count.end()){
char_count[curr] = 1;
}
else{
char_count[curr] = char_count[curr] + 1;
}
//update the number of odd characters
if(char_count[curr] % 2 != 0){
num_odd_chars += 1;
}
else{
num_odd_chars -= 1;
}
}
//not a palindrome unless there is either 1 or 0 characters with an odd char_count.
if(num_odd_chars <= 1){
return true;
}
else{
return false;
}
}
int main(){
cout << palindromePermutation("tactcoa") << endl;
}
| [
"rahulshah512@gmail.com"
] | rahulshah512@gmail.com |
c9e31faedac8f4b1781a1c72c7b3ee9a885248c3 | 1111ac58ece117d2cd96bb5cabe07ab41220ad25 | /class.h | f775453fb48ac05fcc2f9ae7ab64973378734389 | [
"MIT"
] | permissive | Sophie-Williams/TAK-Game-playing-bot | f51f2a2c3b3498ecbe5f8f67c0730e4b2315075b | ee30166749669a03f7ecbb64caa8832bfa52ebc0 | refs/heads/master | 2020-05-19T15:39:17.191448 | 2016-11-12T15:45:40 | 2016-11-12T15:45:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 368 | h | #include<bits/stdc++.h>
using namespace std;
class state{
public:
state* parent;
vector< vector< vector< int > > > boardState;
double eval ;
double alpha, beta ;
int depth;
string printM ;
//define a constructor function
//error vecotr
state(int size);
state() ;
bool operator < (const state& st) const
{
return (eval > st.eval);
}
};
| [
"singhmanish1997@gmail.com"
] | singhmanish1997@gmail.com |
cf1ab5a019e54fec47f920181ec845a62fca700b | fbf49ac1585c87725a0f5edcb80f1fe7a6c2041f | /SDK/BP_C058A_SkillMoveTeleport_classes.h | 5fea63434740597d23c72521a11a0294a7013833 | [] | no_license | zanzo420/DBZ-Kakarot-SDK | d5a69cd4b147d23538b496b7fa7ba4802fccf7ac | 73c2a97080c7ebedc7d538f72ee21b50627f2e74 | refs/heads/master | 2021-02-12T21:14:07.098275 | 2020-03-16T10:07:00 | 2020-03-16T10:07:00 | 244,631,123 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 699 | h | #pragma once
// Name: DBZKakarot, Version: 1.0.3
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_C058A_SkillMoveTeleport.BP_C058A_SkillMoveTeleport_C
// 0x0000 (0x0178 - 0x0178)
class UBP_C058A_SkillMoveTeleport_C : public UATActSkillMoveTeleport
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_C058A_SkillMoveTeleport.BP_C058A_SkillMoveTeleport_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
976290a73958d73cba75c59572bd703df53e2c98 | 0f23651b08fd5a8ce21b9e78e39e61618996073b | /tools/clang/test/Misc/ast-dump-decl.cpp | 0df8a5a2b8fb78765b51f6a8db062befe01e20c6 | [
"NCSA"
] | permissive | arcosuc3m/clang-contracts | 3983773f15872514f7b6ae72d7fea232864d7e3d | 99446829e2cd96116e4dce9496f88cc7df1dbe80 | refs/heads/master | 2021-07-04T03:24:03.156444 | 2018-12-12T11:41:18 | 2018-12-12T12:56:08 | 118,155,058 | 31 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 19,304 | cpp | // RUN: %clang_cc1 -std=c++11 -triple x86_64-linux-gnu -fms-extensions -ast-dump -ast-dump-filter Test %s | FileCheck -strict-whitespace %s
class testEnumDecl {
enum class TestEnumDeclScoped;
enum TestEnumDeclFixed : int;
};
// CHECK: EnumDecl{{.*}} class TestEnumDeclScoped 'int'
// CHECK: EnumDecl{{.*}} TestEnumDeclFixed 'int'
class testFieldDecl {
int TestFieldDeclInit = 0;
};
// CHECK: FieldDecl{{.*}} TestFieldDeclInit 'int'
// CHECK-NEXT: IntegerLiteral
namespace testVarDeclNRVO {
class A { };
A foo() {
A TestVarDeclNRVO;
return TestVarDeclNRVO;
}
}
// CHECK: VarDecl{{.*}} TestVarDeclNRVO 'class testVarDeclNRVO::A' nrvo
void testParmVarDeclInit(int TestParmVarDeclInit = 0);
// CHECK: ParmVarDecl{{.*}} TestParmVarDeclInit 'int'
// CHECK-NEXT: IntegerLiteral{{.*}}
namespace TestNamespaceDecl {
int i;
}
// CHECK: NamespaceDecl{{.*}} TestNamespaceDecl
// CHECK-NEXT: VarDecl
namespace TestNamespaceDecl {
int j;
}
// CHECK: NamespaceDecl{{.*}} TestNamespaceDecl
// CHECK-NEXT: original Namespace
// CHECK-NEXT: VarDecl
inline namespace TestNamespaceDeclInline {
}
// CHECK: NamespaceDecl{{.*}} TestNamespaceDeclInline inline
namespace testUsingDirectiveDecl {
namespace A {
}
}
namespace TestUsingDirectiveDecl {
using namespace testUsingDirectiveDecl::A;
}
// CHECK: NamespaceDecl{{.*}} TestUsingDirectiveDecl
// CHECK-NEXT: UsingDirectiveDecl{{.*}} Namespace{{.*}} 'A'
namespace testNamespaceAlias {
namespace A {
}
}
namespace TestNamespaceAlias = testNamespaceAlias::A;
// CHECK: NamespaceAliasDecl{{.*}} TestNamespaceAlias
// CHECK-NEXT: Namespace{{.*}} 'A'
using TestTypeAliasDecl = int;
// CHECK: TypeAliasDecl{{.*}} TestTypeAliasDecl 'int'
namespace testTypeAliasTemplateDecl {
template<typename T> class A;
template<typename T> using TestTypeAliasTemplateDecl = A<T>;
}
// CHECK: TypeAliasTemplateDecl{{.*}} TestTypeAliasTemplateDecl
// CHECK-NEXT: TemplateTypeParmDecl
// CHECK-NEXT: TypeAliasDecl{{.*}} TestTypeAliasTemplateDecl 'A<T>'
namespace testCXXRecordDecl {
class TestEmpty {};
// CHECK: CXXRecordDecl{{.*}} class TestEmpty
// CHECK-NEXT: DefinitionData pass_in_registers empty aggregate standard_layout trivially_copyable pod trivial literal has_constexpr_non_copy_move_ctor can_const_default_init
// CHECK-NEXT: DefaultConstructor exists trivial constexpr
// CHECK-NEXT: CopyConstructor simple trivial has_const_param
// CHECK-NEXT: MoveConstructor exists simple trivial
// CHECK-NEXT: CopyAssignment trivial has_const_param
// CHECK-NEXT: MoveAssignment exists simple trivial
// CHECK-NEXT: Destructor simple irrelevant trivial
class A { };
class B { };
class TestCXXRecordDecl : virtual A, public B {
int i;
};
}
// CHECK: CXXRecordDecl{{.*}} class TestCXXRecordDecl
// CHECK-NEXT: DefinitionData{{$}}
// CHECK-NEXT: DefaultConstructor exists non_trivial
// CHECK-NEXT: CopyConstructor simple non_trivial has_const_param
// CHECK-NEXT: MoveConstructor exists simple non_trivial
// CHECK-NEXT: CopyAssignment non_trivial has_const_param
// CHECK-NEXT: MoveAssignment exists simple non_trivial
// CHECK-NEXT: Destructor simple irrelevant trivial
// CHECK-NEXT: virtual private 'class testCXXRecordDecl::A'
// CHECK-NEXT: public 'class testCXXRecordDecl::B'
// CHECK-NEXT: CXXRecordDecl{{.*}} class TestCXXRecordDecl
// CHECK-NEXT: FieldDecl
template<class...T>
class TestCXXRecordDeclPack : public T... {
};
// CHECK: CXXRecordDecl{{.*}} class TestCXXRecordDeclPack
// CHECK: public 'T'...
// CHECK-NEXT: CXXRecordDecl{{.*}} class TestCXXRecordDeclPack
thread_local int TestThreadLocalInt;
// CHECK: TestThreadLocalInt {{.*}} tls_dynamic
class testCXXMethodDecl {
virtual void TestCXXMethodDeclPure() = 0;
void TestCXXMethodDeclDelete() = delete;
void TestCXXMethodDeclThrow() throw();
void TestCXXMethodDeclThrowType() throw(int);
};
// CHECK: CXXMethodDecl{{.*}} TestCXXMethodDeclPure 'void (void)' virtual pure
// CHECK: CXXMethodDecl{{.*}} TestCXXMethodDeclDelete 'void (void)' delete
// CHECK: CXXMethodDecl{{.*}} TestCXXMethodDeclThrow 'void (void) throw()'
// CHECK: CXXMethodDecl{{.*}} TestCXXMethodDeclThrowType 'void (void) throw(int)'
namespace testCXXConstructorDecl {
class A { };
class TestCXXConstructorDecl : public A {
int I;
TestCXXConstructorDecl(A &a, int i) : A(a), I(i) { }
TestCXXConstructorDecl(A &a) : TestCXXConstructorDecl(a, 0) { }
};
}
// CHECK: CXXConstructorDecl{{.*}} TestCXXConstructorDecl 'void {{.*}}'
// CHECK-NEXT: ParmVarDecl{{.*}} a
// CHECK-NEXT: ParmVarDecl{{.*}} i
// CHECK-NEXT: CXXCtorInitializer{{.*}}A
// CHECK-NEXT: Expr
// CHECK: CXXCtorInitializer{{.*}}I
// CHECK-NEXT: Expr
// CHECK: CompoundStmt
// CHECK: CXXConstructorDecl{{.*}} TestCXXConstructorDecl 'void {{.*}}'
// CHECK-NEXT: ParmVarDecl{{.*}} a
// CHECK-NEXT: CXXCtorInitializer{{.*}}TestCXXConstructorDecl
// CHECK-NEXT: CXXConstructExpr{{.*}}TestCXXConstructorDecl
class TestCXXDestructorDecl {
~TestCXXDestructorDecl() { }
};
// CHECK: CXXDestructorDecl{{.*}} ~TestCXXDestructorDecl 'void (void) noexcept'
// CHECK-NEXT: CompoundStmt
// Test that the range of a defaulted members is computed correctly.
class TestMemberRanges {
public:
TestMemberRanges() = default;
TestMemberRanges(const TestMemberRanges &Other) = default;
TestMemberRanges(TestMemberRanges &&Other) = default;
~TestMemberRanges() = default;
TestMemberRanges &operator=(const TestMemberRanges &Other) = default;
TestMemberRanges &operator=(TestMemberRanges &&Other) = default;
};
void SomeFunction() {
TestMemberRanges A;
TestMemberRanges B(A);
B = A;
A = static_cast<TestMemberRanges &&>(B);
TestMemberRanges C(static_cast<TestMemberRanges &&>(A));
}
// CHECK: CXXConstructorDecl{{.*}} <line:{{.*}}:3, col:30>
// CHECK: CXXConstructorDecl{{.*}} <line:{{.*}}:3, col:59>
// CHECK: CXXConstructorDecl{{.*}} <line:{{.*}}:3, col:54>
// CHECK: CXXDestructorDecl{{.*}} <line:{{.*}}:3, col:31>
// CHECK: CXXMethodDecl{{.*}} <line:{{.*}}:3, col:70>
// CHECK: CXXMethodDecl{{.*}} <line:{{.*}}:3, col:65>
class TestCXXConversionDecl {
operator int() { return 0; }
};
// CHECK: CXXConversionDecl{{.*}} operator int 'int (void)'
// CHECK-NEXT: CompoundStmt
namespace TestStaticAssertDecl {
static_assert(true, "msg");
}
// CHECK: NamespaceDecl{{.*}} TestStaticAssertDecl
// CHECK-NEXT: StaticAssertDecl{{.*> .*$}}
// CHECK-NEXT: CXXBoolLiteralExpr
// CHECK-NEXT: StringLiteral
namespace testFunctionTemplateDecl {
class A { };
class B { };
class C { };
class D { };
template<typename T> void TestFunctionTemplate(T) { }
// implicit instantiation
void bar(A a) { TestFunctionTemplate(a); }
// explicit specialization
template<> void TestFunctionTemplate(B);
// explicit instantiation declaration
extern template void TestFunctionTemplate(C);
// explicit instantiation definition
template void TestFunctionTemplate(D);
}
// CHECK: FunctionTemplateDecl{{.*}} TestFunctionTemplate
// CHECK-NEXT: TemplateTypeParmDecl
// CHECK-NEXT: FunctionDecl{{.*}} TestFunctionTemplate 'void (T)'
// CHECK-NEXT: ParmVarDecl{{.*}} 'T'
// CHECK-NEXT: CompoundStmt
// CHECK-NEXT: FunctionDecl{{.*}} TestFunctionTemplate {{.*}}A
// CHECK-NEXT: TemplateArgument
// CHECK-NEXT: ParmVarDecl
// CHECK-NEXT: CompoundStmt
// CHECK-NEXT: Function{{.*}} 'TestFunctionTemplate' {{.*}}B
// CHECK-NEXT: FunctionDecl{{.*}} TestFunctionTemplate {{.*}}C
// CHECK-NEXT: TemplateArgument
// CHECK-NEXT: ParmVarDecl
// CHECK-NEXT: FunctionDecl{{.*}} TestFunctionTemplate {{.*}}D
// CHECK-NEXT: TemplateArgument
// CHECK-NEXT: ParmVarDecl
// CHECK-NEXT: CompoundStmt
// CHECK: FunctionDecl{{.*}} TestFunctionTemplate {{.*}}B
// CHECK-NEXT: TemplateArgument
// CHECK-NEXT: ParmVarDecl
namespace testClassTemplateDecl {
class A { };
class B { };
class C { };
class D { };
template<typename T> class TestClassTemplate {
public:
TestClassTemplate();
~TestClassTemplate();
int j();
int i;
};
// implicit instantiation
TestClassTemplate<A> a;
// explicit specialization
template<> class TestClassTemplate<B> {
int j;
};
// explicit instantiation declaration
extern template class TestClassTemplate<C>;
// explicit instantiation definition
template class TestClassTemplate<D>;
// partial explicit specialization
template<typename T1, typename T2> class TestClassTemplatePartial {
int i;
};
template<typename T1> class TestClassTemplatePartial<T1, A> {
int j;
};
}
// CHECK: ClassTemplateDecl{{.*}} TestClassTemplate
// CHECK-NEXT: TemplateTypeParmDecl
// CHECK-NEXT: CXXRecordDecl{{.*}} class TestClassTemplate
// CHECK: CXXRecordDecl{{.*}} class TestClassTemplate
// CHECK-NEXT: AccessSpecDecl{{.*}} public
// CHECK-NEXT: CXXConstructorDecl{{.*}} <line:{{.*}}:5, col:23>
// CHECK-NEXT: CXXDestructorDecl{{.*}} <line:{{.*}}:5, col:24>
// CHECK-NEXT: CXXMethodDecl{{.*}} <line:{{.*}}:5, col:11>
// CHECK-NEXT: FieldDecl{{.*}} i
// CHECK-NEXT: ClassTemplateSpecializationDecl{{.*}} class TestClassTemplate
// CHECK: TemplateArgument{{.*}}A
// CHECK-NEXT: CXXRecordDecl{{.*}} class TestClassTemplate
// CHECK-NEXT: AccessSpecDecl{{.*}} public
// CHECK-NEXT: CXXConstructorDecl{{.*}} <line:{{.*}}:5, col:23>
// CHECK-NEXT: CXXDestructorDecl{{.*}} <line:{{.*}}:5, col:24>
// CHECK-NEXT: CXXMethodDecl{{.*}} <line:{{.*}}:5, col:11>
// CHECK-NEXT: FieldDecl{{.*}} i
// CHECK: ClassTemplateSpecialization{{.*}} 'TestClassTemplate'
// CHECK-NEXT: ClassTemplateSpecialization{{.*}} 'TestClassTemplate'
// CHECK-NEXT: ClassTemplateSpecialization{{.*}} 'TestClassTemplate'
// CHECK: ClassTemplateSpecializationDecl{{.*}} class TestClassTemplate
// CHECK-NEXT: DefinitionData
// CHECK: TemplateArgument{{.*}}B
// CHECK-NEXT: CXXRecordDecl{{.*}} class TestClassTemplate
// CHECK-NEXT: FieldDecl{{.*}} j
// CHECK: ClassTemplateSpecializationDecl{{.*}} class TestClassTemplate
// CHECK: TemplateArgument{{.*}}C
// CHECK-NEXT: CXXRecordDecl{{.*}} class TestClassTemplate
// CHECK-NEXT: AccessSpecDecl{{.*}} public
// CHECK-NEXT: CXXConstructorDecl{{.*}} <line:{{.*}}:5, col:23>
// CHECK-NEXT: CXXDestructorDecl{{.*}} <line:{{.*}}:5, col:24>
// CHECK-NEXT: CXXMethodDecl{{.*}} <line:{{.*}}:5, col:11>
// CHECK-NEXT: FieldDecl{{.*}} i
// CHECK: ClassTemplateSpecializationDecl{{.*}} class TestClassTemplate
// CHECK: TemplateArgument{{.*}}D
// CHECK-NEXT: CXXRecordDecl{{.*}} class TestClassTemplate
// CHECK-NEXT: AccessSpecDecl{{.*}} public
// CHECK-NEXT: CXXConstructorDecl{{.*}} <line:{{.*}}:5, col:23>
// CHECK-NEXT: CXXDestructorDecl{{.*}} <line:{{.*}}:5, col:24>
// CHECK-NEXT: CXXMethodDecl{{.*}} <line:{{.*}}:5, col:11>
// CHECK-NEXT: FieldDecl{{.*}} i
// CHECK: ClassTemplatePartialSpecializationDecl{{.*}} class TestClassTemplatePartial
// CHECK: TemplateArgument
// CHECK-NEXT: TemplateArgument{{.*}}A
// CHECK-NEXT: TemplateTypeParmDecl
// CHECK-NEXT: CXXRecordDecl{{.*}} class TestClassTemplatePartial
// CHECK-NEXT: FieldDecl{{.*}} j
// PR15220 dump instantiation only once
namespace testCanonicalTemplate {
class A {};
template<typename T> void TestFunctionTemplate(T);
template<typename T> void TestFunctionTemplate(T);
void bar(A a) { TestFunctionTemplate(a); }
// CHECK: FunctionTemplateDecl{{.*}} TestFunctionTemplate
// CHECK-NEXT: TemplateTypeParmDecl
// CHECK-NEXT: FunctionDecl{{.*}} TestFunctionTemplate 'void (T)'
// CHECK-NEXT: ParmVarDecl{{.*}} 'T'
// CHECK-NEXT: FunctionDecl{{.*}} TestFunctionTemplate {{.*}}A
// CHECK-NEXT: TemplateArgument
// CHECK-NEXT: ParmVarDecl
// CHECK: FunctionTemplateDecl{{.*}} TestFunctionTemplate
// CHECK-NEXT: TemplateTypeParmDecl
// CHECK-NEXT: FunctionDecl{{.*}} TestFunctionTemplate 'void (T)'
// CHECK-NEXT: ParmVarDecl{{.*}} 'T'
// CHECK-NEXT: Function{{.*}} 'TestFunctionTemplate'
// CHECK-NOT: TemplateArgument
template<typename T1> class TestClassTemplate {
template<typename T2> friend class TestClassTemplate;
};
TestClassTemplate<A> a;
// CHECK: ClassTemplateDecl{{.*}} TestClassTemplate
// CHECK-NEXT: TemplateTypeParmDecl
// CHECK-NEXT: CXXRecordDecl{{.*}} class TestClassTemplate
// CHECK: CXXRecordDecl{{.*}} class TestClassTemplate
// CHECK-NEXT: FriendDecl
// CHECK-NEXT: ClassTemplateDecl{{.*}} TestClassTemplate
// CHECK-NEXT: TemplateTypeParmDecl
// CHECK-NEXT: CXXRecordDecl{{.*}} class TestClassTemplate
// CHECK-NEXT: ClassTemplateSpecializationDecl{{.*}} class TestClassTemplate
// CHECK: TemplateArgument{{.*}}A
// CHECK-NEXT: CXXRecordDecl{{.*}} class TestClassTemplate
}
template <class T>
class TestClassScopeFunctionSpecialization {
template<class U> void foo(U a) { }
template<> void foo<int>(int a) { }
};
// CHECK: ClassScopeFunctionSpecializationDecl
// CHECK-NEXT: CXXMethod{{.*}} 'foo' 'void (int)'
// CHECK-NEXT: TemplateArgument{{.*}} 'int'
namespace TestTemplateTypeParmDecl {
template<typename ... T, class U = int> void foo();
}
// CHECK: NamespaceDecl{{.*}} TestTemplateTypeParmDecl
// CHECK-NEXT: FunctionTemplateDecl
// CHECK-NEXT: TemplateTypeParmDecl{{.*}} typename depth 0 index 0 ... T
// CHECK-NEXT: TemplateTypeParmDecl{{.*}} class depth 0 index 1 U
// CHECK-NEXT: TemplateArgument type 'int'
namespace TestNonTypeTemplateParmDecl {
template<int I = 1, int ... J> void foo();
}
// CHECK: NamespaceDecl{{.*}} TestNonTypeTemplateParmDecl
// CHECK-NEXT: FunctionTemplateDecl
// CHECK-NEXT: NonTypeTemplateParmDecl{{.*}} 'int' depth 0 index 0 I
// CHECK-NEXT: TemplateArgument expr
// CHECK-NEXT: IntegerLiteral{{.*}} 'int' 1
// CHECK-NEXT: NonTypeTemplateParmDecl{{.*}} 'int' depth 0 index 1 ... J
namespace TestTemplateTemplateParmDecl {
template<typename T> class A;
template <template <typename> class T = A, template <typename> class ... U> void foo();
}
// CHECK: NamespaceDecl{{.*}} TestTemplateTemplateParmDecl
// CHECK: FunctionTemplateDecl
// CHECK-NEXT: TemplateTemplateParmDecl{{.*}} T
// CHECK-NEXT: TemplateTypeParmDecl{{.*}} typename
// CHECK-NEXT: TemplateArgument{{.*}} template A
// CHECK-NEXT: TemplateTemplateParmDecl{{.*}} ... U
// CHECK-NEXT: TemplateTypeParmDecl{{.*}} typename
namespace TestTemplateArgument {
template<typename> class A { };
template<template<typename> class ...> class B { };
int foo();
template<typename> class testType { };
template class testType<int>;
// CHECK: ClassTemplateSpecializationDecl{{.*}} class testType
// CHECK: TemplateArgument{{.*}} type 'int'
template<int fp(void)> class testDecl { };
template class testDecl<foo>;
// CHECK: ClassTemplateSpecializationDecl{{.*}} class testDecl
// CHECK: TemplateArgument{{.*}} decl
// CHECK-NEXT: Function{{.*}}foo
template class testDecl<nullptr>;
// CHECK: ClassTemplateSpecializationDecl{{.*}} class testDecl
// CHECK: TemplateArgument{{.*}} nullptr
template<int> class testIntegral { };
template class testIntegral<1>;
// CHECK: ClassTemplateSpecializationDecl{{.*}} class testIntegral
// CHECK: TemplateArgument{{.*}} integral 1
template<template<typename> class> class testTemplate { };
template class testTemplate<A>;
// CHECK: ClassTemplateSpecializationDecl{{.*}} class testTemplate
// CHECK: TemplateArgument{{.*}} A
template<template<typename> class ...T> class C {
B<T...> testTemplateExpansion;
};
// FIXME: Need TemplateSpecializationType dumping to test TemplateExpansion.
template<int, int = 0> class testExpr;
template<int I> class testExpr<I> { };
// CHECK: ClassTemplatePartialSpecializationDecl{{.*}} class testExpr
// CHECK: TemplateArgument{{.*}} expr
// CHECK-NEXT: DeclRefExpr{{.*}}I
template<int, int ...> class testPack { };
template class testPack<0, 1, 2>;
// CHECK: ClassTemplateSpecializationDecl{{.*}} class testPack
// CHECK: TemplateArgument{{.*}} integral 0
// CHECK-NEXT: TemplateArgument{{.*}} pack
// CHECK-NEXT: TemplateArgument{{.*}} integral 1
// CHECK-NEXT: TemplateArgument{{.*}} integral 2
}
namespace testUsingDecl {
int i;
}
namespace TestUsingDecl {
using testUsingDecl::i;
}
// CHECK: NamespaceDecl{{.*}} TestUsingDecl
// CHECK-NEXT: UsingDecl{{.*}} testUsingDecl::i
// CHECK-NEXT: UsingShadowDecl{{.*}} Var{{.*}} 'i' 'int'
namespace testUnresolvedUsing {
class A { };
template<class T> class B {
public:
A a;
};
template<class T> class TestUnresolvedUsing : public B<T> {
using typename B<T>::a;
using B<T>::a;
};
}
// CHECK: CXXRecordDecl{{.*}} TestUnresolvedUsing
// CHECK: UnresolvedUsingTypenameDecl{{.*}} B<T>::a
// CHECK: UnresolvedUsingValueDecl{{.*}} B<T>::a
namespace TestLinkageSpecDecl {
extern "C" void test1();
extern "C++" void test2();
}
// CHECK: NamespaceDecl{{.*}} TestLinkageSpecDecl
// CHECK-NEXT: LinkageSpecDecl{{.*}} C
// CHECK-NEXT: FunctionDecl
// CHECK-NEXT: LinkageSpecDecl{{.*}} C++
// CHECK-NEXT: FunctionDecl
class TestAccessSpecDecl {
public:
private:
protected:
};
// CHECK: CXXRecordDecl{{.*}} class TestAccessSpecDecl
// CHECK: CXXRecordDecl{{.*}} class TestAccessSpecDecl
// CHECK-NEXT: AccessSpecDecl{{.*}} public
// CHECK-NEXT: AccessSpecDecl{{.*}} private
// CHECK-NEXT: AccessSpecDecl{{.*}} protected
template<typename T> class TestFriendDecl {
friend int foo();
friend class A;
friend T;
};
// CHECK: CXXRecord{{.*}} TestFriendDecl
// CHECK: CXXRecord{{.*}} TestFriendDecl
// CHECK-NEXT: FriendDecl
// CHECK-NEXT: FunctionDecl{{.*}} foo
// CHECK-NEXT: FriendDecl{{.*}} 'class A':'class A'
// CHECK-NEXT: FriendDecl{{.*}} 'T'
namespace TestFileScopeAsmDecl {
asm("ret");
}
// CHECK: NamespaceDecl{{.*}} TestFileScopeAsmDecl{{$}}
// CHECK: FileScopeAsmDecl{{.*> .*$}}
// CHECK-NEXT: StringLiteral
namespace TestFriendDecl2 {
void f();
struct S {
friend void f();
};
}
// CHECK: NamespaceDecl [[TestFriendDecl2:0x.*]] <{{.*}}> {{.*}} TestFriendDecl2
// CHECK: |-FunctionDecl [[TestFriendDecl2_f:0x.*]] <{{.*}}> {{.*}} f 'void (void)'
// CHECK: `-CXXRecordDecl {{.*}} struct S
// CHECK: |-CXXRecordDecl {{.*}} struct S
// CHECK: `-FriendDecl
// CHECK: `-FunctionDecl {{.*}} parent [[TestFriendDecl2]] prev [[TestFriendDecl2_f]] <{{.*}}> {{.*}} f 'void (void)'
namespace Comment {
extern int Test;
/// Something here.
extern int Test;
extern int Test;
}
// CHECK: VarDecl {{.*}} Test 'int' extern
// CHECK-NOT: FullComment
// CHECK: VarDecl {{.*}} Test 'int' extern
// CHECK: `-FullComment
// CHECK: `-ParagraphComment
// CHECK: `-TextComment
// CHECK: VarDecl {{.*}} Test 'int' extern
// CHECK-NOT: FullComment
| [
"jalopezg@inf.uc3m.es"
] | jalopezg@inf.uc3m.es |
58fbb260bec723b877a9cdf354dfeae517296cad | 31ff2096bcc62be7fcf929ad098c83367d8170d0 | /src/net.cpp | fb92ed4a7449682340b3e71914c9092bf38b3974 | [
"MIT"
] | permissive | puredev321/Decentronium | be59c538bea4d4b276789747489f3d27099b7120 | b0a4faff7f4a979f9a86ba8f7b93693bc8c3b39a | refs/heads/master | 2020-04-02T22:10:00.961056 | 2018-10-26T11:26:49 | 2018-10-26T11:26:49 | 154,823,724 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 66,352 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/decentronium-config.h"
#endif
#include "net.h"
#include "addrman.h"
#include "chainparams.h"
#include "clientversion.h"
#include "miner.h"
#include "obfuscation.h"
#include "primitives/transaction.h"
#include "ui_interface.h"
#include "wallet.h"
#ifdef WIN32
#include <string.h>
#else
#include <fcntl.h>
#endif
#ifdef USE_UPNP
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/miniwget.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#endif
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
// Dump addresses to peers.dat every 15 minutes (900s)
#define DUMP_ADDRESSES_INTERVAL 900
#if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
// Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h.
// Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version.
#ifdef WIN32
#ifndef PROTECTION_LEVEL_UNRESTRICTED
#define PROTECTION_LEVEL_UNRESTRICTED 10
#endif
#ifndef IPV6_PROTECTION_LEVEL
#define IPV6_PROTECTION_LEVEL 23
#endif
#endif
using namespace boost;
using namespace std;
namespace
{
const int MAX_OUTBOUND_CONNECTIONS = 16;
struct ListenSocket {
SOCKET socket;
bool whitelisted;
ListenSocket(SOCKET socket, bool whitelisted) : socket(socket), whitelisted(whitelisted) {}
};
}
//
// Global state variables
//
bool fDiscover = true;
bool fListen = true;
uint64_t nLocalServices = NODE_NETWORK;
CCriticalSection cs_mapLocalHost;
map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfReachable[NET_MAX] = {};
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
uint64_t nLocalHostNonce = 0;
static std::vector<ListenSocket> vhListenSocket;
CAddrMan addrman;
int nMaxConnections = 125;
bool fAddressesInitialized = false;
vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
map<CInv, CDataStream> mapRelay;
deque<pair<int64_t, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
limitedmap<CInv, int64_t> mapAlreadyAskedFor(MAX_INV_SZ);
static deque<string> vOneShots;
CCriticalSection cs_vOneShots;
set<CNetAddr> setservAddNodeAddresses;
CCriticalSection cs_setservAddNodeAddresses;
vector<std::string> vAddedNodes;
CCriticalSection cs_vAddedNodes;
NodeId nLastNodeId = 0;
CCriticalSection cs_nLastNodeId;
static CSemaphore* semOutbound = NULL;
boost::condition_variable messageHandlerCondition;
// Signals for message handling
static CNodeSignals g_signals;
CNodeSignals& GetNodeSignals() { return g_signals; }
void AddOneShot(string strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
}
unsigned short GetListenPort()
{
return (unsigned short)(GetArg("-port", Params().GetDefaultPort()));
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr* paddrPeer)
{
if (!fListen)
return false;
int nBestScore = -1;
int nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) {
int nScore = (*it).second.nScore;
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) {
addr = CService((*it).first, (*it).second.nPort);
nBestReachability = nReachability;
nBestScore = nScore;
}
}
}
return nBestScore >= 0;
}
// get best local address for a particular peer as a CAddress
// Otherwise, return the unroutable 0.0.0.0 but filled in with
// the normal parameters, since the IP may be changed to a useful
// one by discovery.
CAddress GetLocalAddress(const CNetAddr* paddrPeer)
{
CAddress ret(CService("0.0.0.0", GetListenPort()), 0);
CService addr;
if (GetLocal(addr, paddrPeer)) {
ret = CAddress(addr);
}
ret.nServices = nLocalServices;
ret.nTime = GetAdjustedTime();
return ret;
}
bool RecvLine(SOCKET hSocket, string& strLine)
{
strLine = "";
while (true) {
char c;
int nBytes = recv(hSocket, &c, 1, 0);
if (nBytes > 0) {
if (c == '\n')
continue;
if (c == '\r')
return true;
strLine += c;
if (strLine.size() >= 9000)
return true;
} else if (nBytes <= 0) {
boost::this_thread::interruption_point();
if (nBytes < 0) {
int nErr = WSAGetLastError();
if (nErr == WSAEMSGSIZE)
continue;
if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) {
MilliSleep(10);
continue;
}
}
if (!strLine.empty())
return true;
if (nBytes == 0) {
// socket closed
LogPrint("net", "socket closed\n");
return false;
} else {
// socket error
int nErr = WSAGetLastError();
LogPrint("net", "recv failed: %s\n", NetworkErrorString(nErr));
return false;
}
}
}
}
int GetnScore(const CService& addr)
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == LOCAL_NONE)
return 0;
return mapLocalHost[addr].nScore;
}
// Is our peer's addrLocal potentially useful as an external IP source?
bool IsPeerAddrLocalGood(CNode* pnode)
{
return fDiscover && pnode->addr.IsRoutable() && pnode->addrLocal.IsRoutable() &&
!IsLimited(pnode->addrLocal.GetNetwork());
}
// pushes our own address to a peer
void AdvertizeLocal(CNode* pnode)
{
if (fListen && pnode->fSuccessfullyConnected) {
CAddress addrLocal = GetLocalAddress(&pnode->addr);
// If discovery is enabled, sometimes give our peer the address it
// tells us that it sees us as in case it has a better idea of our
// address than we do.
if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() ||
GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8 : 2) == 0)) {
addrLocal.SetIP(pnode->addrLocal);
}
if (addrLocal.IsRoutable()) {
pnode->PushAddress(addrLocal);
}
}
}
void SetReachable(enum Network net, bool fFlag)
{
LOCK(cs_mapLocalHost);
vfReachable[net] = fFlag;
if (net == NET_IPV6 && fFlag)
vfReachable[NET_IPV4] = true;
}
// learn a new local address
bool AddLocal(const CService& addr, int nScore)
{
if (!addr.IsRoutable())
return false;
if (!fDiscover && nScore < LOCAL_MANUAL)
return false;
if (IsLimited(addr))
return false;
LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
{
LOCK(cs_mapLocalHost);
bool fAlready = mapLocalHost.count(addr) > 0;
LocalServiceInfo& info = mapLocalHost[addr];
if (!fAlready || nScore >= info.nScore) {
info.nScore = nScore + (fAlready ? 1 : 0);
info.nPort = addr.GetPort();
}
SetReachable(addr.GetNetwork());
}
return true;
}
bool AddLocal(const CNetAddr& addr, int nScore)
{
return AddLocal(CService(addr, GetListenPort()), nScore);
}
/** Make a particular network entirely off-limits (no automatic connects to it) */
void SetLimited(enum Network net, bool fLimited)
{
if (net == NET_UNROUTABLE)
return;
LOCK(cs_mapLocalHost);
vfLimited[net] = fLimited;
}
bool IsLimited(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfLimited[net];
}
bool IsLimited(const CNetAddr& addr)
{
return IsLimited(addr.GetNetwork());
}
/** vote for a local address */
bool SeenLocal(const CService& addr)
{
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0)
return false;
mapLocalHost[addr].nScore++;
}
return true;
}
/** check whether a given address is potentially local */
bool IsLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
return mapLocalHost.count(addr) > 0;
}
/** check whether a given network is one we can probably connect to */
bool IsReachable(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfReachable[net] && !vfLimited[net];
}
/** check whether a given address is in a network we can probably connect to */
bool IsReachable(const CNetAddr& addr)
{
enum Network net = addr.GetNetwork();
return IsReachable(net);
}
void AddressCurrentlyConnected(const CService& addr)
{
addrman.Connected(addr);
}
uint64_t CNode::nTotalBytesRecv = 0;
uint64_t CNode::nTotalBytesSent = 0;
CCriticalSection CNode::cs_totalBytesRecv;
CCriticalSection CNode::cs_totalBytesSent;
CNode* FindNode(const CNetAddr& ip)
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
return NULL;
}
CNode* FindNode(const std::string& addrName)
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
if (pnode->addrName == addrName)
return (pnode);
return NULL;
}
CNode* FindNode(const CService& addr)
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
if (Params().NetworkID() == CBaseChainParams::REGTEST) {
//if using regtest, just check the IP
if ((CNetAddr)pnode->addr == (CNetAddr)addr)
return (pnode);
} else {
if (pnode->addr == addr)
return (pnode);
}
}
return NULL;
}
CNode* ConnectNode(CAddress addrConnect, const char* pszDest, bool obfuScationMaster)
{
if (pszDest == NULL) {
// we clean masternode connections in CMasternodeMan::ProcessMasternodeConnections()
// so should be safe to skip this and connect to local Hot MN on CActiveMasternode::ManageStatus()
if (IsLocal(addrConnect) && !obfuScationMaster)
return NULL;
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
if (pnode) {
pnode->fObfuScationMaster = obfuScationMaster;
pnode->AddRef();
return pnode;
}
}
/// debug print
LogPrint("net", "trying connection %s lastseen=%.1fhrs\n",
pszDest ? pszDest : addrConnect.ToString(),
pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime) / 3600.0);
// Connect
SOCKET hSocket;
bool proxyConnectionFailed = false;
if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) :
ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed)) {
if (!IsSelectableSocket(hSocket)) {
LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
CloseSocket(hSocket);
return NULL;
}
addrman.Attempt(addrConnect);
// Add node
CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
pnode->nTimeConnected = GetTime();
if (obfuScationMaster) pnode->fObfuScationMaster = true;
return pnode;
} else if (!proxyConnectionFailed) {
// If connecting to the node failed, and failure is not caused by a problem connecting to
// the proxy, mark this as an attempt.
addrman.Attempt(addrConnect);
}
return NULL;
}
void CNode::CloseSocketDisconnect()
{
fDisconnect = true;
if (hSocket != INVALID_SOCKET) {
LogPrint("net", "disconnecting peer=%d\n", id);
CloseSocket(hSocket);
}
// in case this fails, we'll empty the recv buffer when the CNode is deleted
TRY_LOCK(cs_vRecvMsg, lockRecv);
if (lockRecv)
vRecvMsg.clear();
}
bool CNode::DisconnectOldProtocol(int nVersionRequired, string strLastCommand)
{
fDisconnect = false;
if (nVersion < nVersionRequired) {
LogPrintf("%s : peer=%d using obsolete version %i; disconnecting\n", __func__, id, nVersion);
PushMessage("reject", strLastCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", ActiveProtocol()));
fDisconnect = true;
}
return fDisconnect;
}
void CNode::PushVersion()
{
int nBestHeight = g_signals.GetHeight().get_value_or(0);
/// when NTP implemented, change to just nTime = GetAdjustedTime()
int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0", 0)));
CAddress addrMe = GetLocalAddress(&addr);
GetRandBytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
if (fLogIPs)
LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), id);
else
LogPrint("net", "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), id);
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight, true);
}
std::map<CNetAddr, int64_t> CNode::setBanned;
CCriticalSection CNode::cs_setBanned;
void CNode::ClearBanned()
{
setBanned.clear();
}
bool CNode::IsBanned(CNetAddr ip)
{
bool fResult = false;
{
LOCK(cs_setBanned);
std::map<CNetAddr, int64_t>::iterator i = setBanned.find(ip);
if (i != setBanned.end()) {
int64_t t = (*i).second;
if (GetTime() < t)
fResult = true;
}
}
return fResult;
}
bool CNode::Ban(const CNetAddr& addr)
{
int64_t banTime = GetTime() + GetArg("-bantime", 60 * 60 * 24); // Default 24-hour ban
{
LOCK(cs_setBanned);
if (setBanned[addr] < banTime)
setBanned[addr] = banTime;
}
return true;
}
std::vector<CSubNet> CNode::vWhitelistedRange;
CCriticalSection CNode::cs_vWhitelistedRange;
bool CNode::IsWhitelistedRange(const CNetAddr& addr)
{
LOCK(cs_vWhitelistedRange);
BOOST_FOREACH (const CSubNet& subnet, vWhitelistedRange) {
if (subnet.Match(addr))
return true;
}
return false;
}
void CNode::AddWhitelistedRange(const CSubNet& subnet)
{
LOCK(cs_vWhitelistedRange);
vWhitelistedRange.push_back(subnet);
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats& stats)
{
stats.nodeid = this->GetId();
X(nServices);
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(addrName);
X(nVersion);
X(cleanSubVer);
X(fInbound);
X(nStartingHeight);
X(nSendBytes);
X(nRecvBytes);
X(fWhitelisted);
// It is common for nodes with good ping times to suddenly become lagged,
// due to a new block arriving or other large transfer.
// Merely reporting pingtime might fool the caller into thinking the node was still responsive,
// since pingtime does not update until the ping is complete, which might take a while.
// So, if a ping is taking an unusually long time in flight,
// the caller can immediately detect that this is happening.
int64_t nPingUsecWait = 0;
if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
nPingUsecWait = GetTimeMicros() - nPingUsecStart;
}
// Raw ping time is in microseconds, but show it to user as whole seconds (DECN users should be well used to small numbers with many decimal places by now :)
stats.dPingTime = (((double)nPingUsecTime) / 1e6);
stats.dPingWait = (((double)nPingUsecWait) / 1e6);
// Leave string empty if addrLocal invalid (not filled in yet)
stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : "";
}
#undef X
// requires LOCK(cs_vRecvMsg)
bool CNode::ReceiveMsgBytes(const char* pch, unsigned int nBytes)
{
while (nBytes > 0) {
// get current incomplete message, or create a new one
if (vRecvMsg.empty() ||
vRecvMsg.back().complete())
vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion));
CNetMessage& msg = vRecvMsg.back();
// absorb network data
int handled;
if (!msg.in_data)
handled = msg.readHeader(pch, nBytes);
else
handled = msg.readData(pch, nBytes);
if (handled < 0)
return false;
if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) {
LogPrint("net", "Oversized message from peer=%i, disconnecting", GetId());
return false;
}
pch += handled;
nBytes -= handled;
if (msg.complete()) {
msg.nTime = GetTimeMicros();
messageHandlerCondition.notify_one();
}
}
return true;
}
int CNetMessage::readHeader(const char* pch, unsigned int nBytes)
{
// copy data to temporary parsing buffer
unsigned int nRemaining = 24 - nHdrPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
memcpy(&hdrbuf[nHdrPos], pch, nCopy);
nHdrPos += nCopy;
// if header incomplete, exit
if (nHdrPos < 24)
return nCopy;
// deserialize to CMessageHeader
try {
hdrbuf >> hdr;
} catch (const std::exception&) {
return -1;
}
// reject messages larger than MAX_SIZE
if (hdr.nMessageSize > MAX_SIZE)
return -1;
// switch state to reading message data
in_data = true;
return nCopy;
}
int CNetMessage::readData(const char* pch, unsigned int nBytes)
{
unsigned int nRemaining = hdr.nMessageSize - nDataPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
if (vRecv.size() < nDataPos + nCopy) {
// Allocate up to 256 KiB ahead, but never more than the total message size.
vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
}
memcpy(&vRecv[nDataPos], pch, nCopy);
nDataPos += nCopy;
return nCopy;
}
// requires LOCK(cs_vSend)
void SocketSendData(CNode* pnode)
{
std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin();
while (it != pnode->vSendMsg.end()) {
const CSerializeData& data = *it;
assert(data.size() > pnode->nSendOffset);
int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
if (nBytes > 0) {
pnode->nLastSend = GetTime();
pnode->nSendBytes += nBytes;
pnode->nSendOffset += nBytes;
pnode->RecordBytesSent(nBytes);
if (pnode->nSendOffset == data.size()) {
pnode->nSendOffset = 0;
pnode->nSendSize -= data.size();
it++;
} else {
// could not send full message; stop sending more
break;
}
} else {
if (nBytes < 0) {
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
pnode->CloseSocketDisconnect();
}
}
// couldn't send anything at all
break;
}
}
if (it == pnode->vSendMsg.end()) {
assert(pnode->nSendOffset == 0);
assert(pnode->nSendSize == 0);
}
pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
}
static list<CNode*> vNodesDisconnected;
void ThreadSocketHandler()
{
unsigned int nPrevNodeCount = 0;
while (true) {
//
// Disconnect nodes
//
{
LOCK(cs_vNodes);
// Disconnect unused nodes
vector<CNode*> vNodesCopy = vNodes;
BOOST_FOREACH (CNode* pnode, vNodesCopy) {
if (pnode->fDisconnect ||
(pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) {
// remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
// release outbound grant (if any)
pnode->grantOutbound.Release();
// close socket and cleanup
pnode->CloseSocketDisconnect();
// hold in disconnected pool until all refs are released
if (pnode->fNetworkNode || pnode->fInbound)
pnode->Release();
vNodesDisconnected.push_back(pnode);
}
}
}
{
// Delete disconnected nodes
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
BOOST_FOREACH (CNode* pnode, vNodesDisconnectedCopy) {
// wait until threads are done using it
if (pnode->GetRefCount() <= 0) {
bool fDelete = false;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend) {
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv) {
TRY_LOCK(pnode->cs_inventory, lockInv);
if (lockInv)
fDelete = true;
}
}
}
if (fDelete) {
vNodesDisconnected.remove(pnode);
delete pnode;
}
}
}
}
if (vNodes.size() != nPrevNodeCount) {
nPrevNodeCount = vNodes.size();
uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount);
}
//
// Find which sockets have data to receive
//
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50000; // frequency to poll pnode->vSend
fd_set fdsetRecv;
fd_set fdsetSend;
fd_set fdsetError;
FD_ZERO(&fdsetRecv);
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
SOCKET hSocketMax = 0;
bool have_fds = false;
BOOST_FOREACH (const ListenSocket& hListenSocket, vhListenSocket) {
FD_SET(hListenSocket.socket, &fdsetRecv);
hSocketMax = max(hSocketMax, hListenSocket.socket);
have_fds = true;
}
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
if (pnode->hSocket == INVALID_SOCKET)
continue;
FD_SET(pnode->hSocket, &fdsetError);
hSocketMax = max(hSocketMax, pnode->hSocket);
have_fds = true;
// Implement the following logic:
// * If there is data to send, select() for sending data. As this only
// happens when optimistic write failed, we choose to first drain the
// write buffer in this case before receiving more. This avoids
// needlessly queueing received data, if the remote peer is not themselves
// receiving data. This means properly utilizing TCP flow control signalling.
// * Otherwise, if there is no (complete) message in the receive buffer,
// or there is space left in the buffer, select() for receiving data.
// * (if neither of the above applies, there is certainly one message
// in the receiver buffer ready to be processed).
// Together, that means that at least one of the following is always possible,
// so we don't deadlock:
// * We send some data.
// * We wait for data to be received (and disconnect after timeout).
// * We process a message in the buffer (message handler thread).
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend && !pnode->vSendMsg.empty()) {
FD_SET(pnode->hSocket, &fdsetSend);
continue;
}
}
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv && (pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() ||
pnode->GetTotalRecvSize() <= ReceiveFloodSize()))
FD_SET(pnode->hSocket, &fdsetRecv);
}
}
}
int nSelect = select(have_fds ? hSocketMax + 1 : 0,
&fdsetRecv, &fdsetSend, &fdsetError, &timeout);
boost::this_thread::interruption_point();
if (nSelect == SOCKET_ERROR) {
if (have_fds) {
int nErr = WSAGetLastError();
LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
for (unsigned int i = 0; i <= hSocketMax; i++)
FD_SET(i, &fdsetRecv);
}
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
MilliSleep(timeout.tv_usec / 1000);
}
//
// Accept new connections
//
BOOST_FOREACH (const ListenSocket& hListenSocket, vhListenSocket) {
if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv)) {
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
int nInbound = 0;
if (hSocket != INVALID_SOCKET)
if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
LogPrintf("Warning: Unknown socket family\n");
bool whitelisted = hListenSocket.whitelisted || CNode::IsWhitelistedRange(addr);
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
if (pnode->fInbound)
nInbound++;
}
if (hSocket == INVALID_SOCKET) {
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK)
LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
} else if (!IsSelectableSocket(hSocket)) {
LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString());
CloseSocket(hSocket);
} else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS) {
LogPrint("net", "connection from %s dropped (full)\n", addr.ToString());
CloseSocket(hSocket);
} else if (CNode::IsBanned(addr) && !whitelisted) {
LogPrintf("connection from %s dropped (banned)\n", addr.ToString());
CloseSocket(hSocket);
} else {
CNode* pnode = new CNode(hSocket, addr, "", true);
pnode->AddRef();
pnode->fWhitelisted = whitelisted;
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
}
}
}
//
// Service each socket
//
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH (CNode* pnode, vNodesCopy)
pnode->AddRef();
}
BOOST_FOREACH (CNode* pnode, vNodesCopy) {
boost::this_thread::interruption_point();
//
// Receive
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) {
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv) {
{
// typical socket buffer is 8K-64K
char pchBuf[0x10000];
int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
if (nBytes > 0) {
if (!pnode->ReceiveMsgBytes(pchBuf, nBytes))
pnode->CloseSocketDisconnect();
pnode->nLastRecv = GetTime();
pnode->nRecvBytes += nBytes;
pnode->RecordBytesRecv(nBytes);
} else if (nBytes == 0) {
// socket closed gracefully
if (!pnode->fDisconnect)
LogPrint("net", "socket closed\n");
pnode->CloseSocketDisconnect();
} else if (nBytes < 0) {
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
if (!pnode->fDisconnect)
LogPrintf("socket recv error %s\n", NetworkErrorString(nErr));
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Send
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetSend)) {
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SocketSendData(pnode);
}
//
// Inactivity checking
//
int64_t nTime = GetTime();
if (nTime - pnode->nTimeConnected > 60) {
if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) {
LogPrint("net", "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->id);
pnode->fDisconnect = true;
} else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) {
LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend);
pnode->fDisconnect = true;
} else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90 * 60)) {
LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv);
pnode->fDisconnect = true;
} else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros()) {
LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart));
pnode->fDisconnect = true;
}
}
}
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodesCopy)
pnode->Release();
}
}
}
#ifdef USE_UPNP
void ThreadMapPort()
{
std::string port = strprintf("%u", GetListenPort());
const char* multicastif = 0;
const char* minissdpdpath = 0;
struct UPNPDev* devlist = 0;
char lanaddr[64];
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
#elif MINIUPNPC_API_VERSION < 14
/* miniupnpc 1.6 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
#else
/* miniupnpc 1.9.20150730 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error);
#endif
struct UPNPUrls urls;
struct IGDdatas data;
int r;
r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
if (r == 1) {
if (fDiscover) {
char externalIPAddress[40];
r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
if (r != UPNPCOMMAND_SUCCESS)
LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
else {
if (externalIPAddress[0]) {
LogPrintf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
} else
LogPrintf("UPnP: GetExternalIPAddress failed.\n");
}
}
string strDesc = "Decentronium " + FormatFullVersion();
try {
while (true) {
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if (r != UPNPCOMMAND_SUCCESS)
LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port, port, lanaddr, r, strupnperror(r));
else
LogPrintf("UPnP Port Mapping successful.\n");
;
MilliSleep(20 * 60 * 1000); // Refresh every 20 minutes
}
} catch (boost::thread_interrupted) {
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
LogPrintf("UPNP_DeletePortMapping() returned : %d\n", r);
freeUPNPDevlist(devlist);
devlist = 0;
FreeUPNPUrls(&urls);
throw;
}
} else {
LogPrintf("No valid UPnP IGDs found\n");
freeUPNPDevlist(devlist);
devlist = 0;
if (r != 0)
FreeUPNPUrls(&urls);
}
}
void MapPort(bool fUseUPnP)
{
static boost::thread* upnp_thread = NULL;
if (fUseUPnP) {
if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
}
upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort));
} else if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
upnp_thread = NULL;
}
}
#else
void MapPort(bool)
{
// Intentionally left blank.
}
#endif
void ThreadDNSAddressSeed()
{
// goal: only query DNS seeds if address need is acute
if ((addrman.size() > 0) &&
(!GetBoolArg("-forcednsseed", false))) {
MilliSleep(11 * 1000);
LOCK(cs_vNodes);
if (vNodes.size() >= 2) {
LogPrintf("P2P peers available. Skipped DNS seeding.\n");
return;
}
}
const vector<CDNSSeedData>& vSeeds = Params().DNSSeeds();
int found = 0;
LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
BOOST_FOREACH (const CDNSSeedData& seed, vSeeds) {
if (HaveNameProxy()) {
AddOneShot(seed.host);
} else {
vector<CNetAddr> vIPs;
vector<CAddress> vAdd;
if (LookupHost(seed.host.c_str(), vIPs)) {
BOOST_FOREACH (CNetAddr& ip, vIPs) {
int nOneDay = 24 * 3600;
CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()));
addr.nTime = GetTime() - 3 * nOneDay - GetRand(4 * nOneDay); // use a random age between 3 and 7 days old
vAdd.push_back(addr);
found++;
}
}
addrman.Add(vAdd, CNetAddr(seed.name, true));
}
}
LogPrintf("%d addresses found from DNS seeds\n", found);
}
void DumpAddresses()
{
int64_t nStart = GetTimeMillis();
CAddrDB adb;
adb.Write(addrman);
LogPrint("net", "Flushed %d addresses to peers.dat %dms\n",
addrman.size(), GetTimeMillis() - nStart);
}
void static ProcessOneShot()
{
string strDest;
{
LOCK(cs_vOneShots);
if (vOneShots.empty())
return;
strDest = vOneShots.front();
vOneShots.pop_front();
}
CAddress addr;
CSemaphoreGrant grant(*semOutbound, true);
if (grant) {
if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
AddOneShot(strDest);
}
}
void ThreadOpenConnections()
{
// Connect to specific addresses
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
for (int64_t nLoop = 0;; nLoop++) {
ProcessOneShot();
BOOST_FOREACH (string strAddr, mapMultiArgs["-connect"]) {
CAddress addr;
OpenNetworkConnection(addr, NULL, strAddr.c_str());
for (int i = 0; i < 10 && i < nLoop; i++) {
MilliSleep(500);
}
}
MilliSleep(500);
}
}
// Initiate network connections
int64_t nStart = GetTime();
while (true) {
ProcessOneShot();
MilliSleep(500);
CSemaphoreGrant grant(*semOutbound);
boost::this_thread::interruption_point();
// Add seed nodes if DNS seeds are all down (an infrastructure attack?).
if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
static bool done = false;
if (!done) {
LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
addrman.Add(Params().FixedSeeds(), CNetAddr("127.0.0.1"));
done = true;
}
}
//
// Choose an address to connect to based on most recently seen
//
CAddress addrConnect;
// Only connect out to one peer per network group (/16 for IPv4).
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
int nOutbound = 0;
set<vector<unsigned char> > setConnected;
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
if (!pnode->fInbound) {
setConnected.insert(pnode->addr.GetGroup());
nOutbound++;
}
}
}
int64_t nANow = GetAdjustedTime();
int nTries = 0;
while (true) {
CAddress addr = addrman.Select();
// if we selected an invalid address, restart
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
break;
// If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
// stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
// already-connected network ranges, ...) before trying new addrman addresses.
nTries++;
if (nTries > 100)
break;
if (IsLimited(addr))
continue;
// only consider very recently tried nodes after 30 failed attempts
if (nANow - addr.nLastTry < 600 && nTries < 30)
continue;
addrConnect = addr;
break;
}
if (addrConnect.IsValid())
OpenNetworkConnection(addrConnect, &grant);
}
}
void ThreadOpenAddedConnections()
{
{
LOCK(cs_vAddedNodes);
vAddedNodes = mapMultiArgs["-addnode"];
}
if (HaveNameProxy()) {
while (true) {
list<string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
BOOST_FOREACH (string& strAddNode, vAddedNodes)
lAddresses.push_back(strAddNode);
}
BOOST_FOREACH (string& strAddNode, lAddresses) {
CAddress addr;
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
MilliSleep(500);
}
MilliSleep(120000); // Retry every 2 minutes
}
}
for (unsigned int i = 0; true; i++) {
list<string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
BOOST_FOREACH (string& strAddNode, vAddedNodes)
lAddresses.push_back(strAddNode);
}
list<vector<CService> > lservAddressesToAdd(0);
BOOST_FOREACH (string& strAddNode, lAddresses) {
vector<CService> vservNode(0);
if (Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) {
lservAddressesToAdd.push_back(vservNode);
{
LOCK(cs_setservAddNodeAddresses);
BOOST_FOREACH (CService& serv, vservNode)
setservAddNodeAddresses.insert(serv);
}
}
}
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++)
BOOST_FOREACH (CService& addrNode, *(it))
if (pnode->addr == addrNode) {
it = lservAddressesToAdd.erase(it);
it--;
break;
}
}
BOOST_FOREACH (vector<CService>& vserv, lservAddressesToAdd) {
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant);
MilliSleep(500);
}
MilliSleep(120000); // Retry every 2 minutes
}
}
// if successful, this moves the passed grant to the constructed node
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant* grantOutbound, const char* pszDest, bool fOneShot)
{
//
// Initiate outbound network connection
//
boost::this_thread::interruption_point();
if (!pszDest) {
if (IsLocal(addrConnect) ||
FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
FindNode(addrConnect.ToStringIPPort()))
return false;
} else if (FindNode(pszDest))
return false;
CNode* pnode = ConnectNode(addrConnect, pszDest);
boost::this_thread::interruption_point();
if (!pnode)
return false;
if (grantOutbound)
grantOutbound->MoveTo(pnode->grantOutbound);
pnode->fNetworkNode = true;
if (fOneShot)
pnode->fOneShot = true;
return true;
}
void ThreadMessageHandler()
{
boost::mutex condition_mutex;
boost::unique_lock<boost::mutex> lock(condition_mutex);
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
while (true) {
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH (CNode* pnode, vNodesCopy) {
pnode->AddRef();
}
}
// Poll the connected nodes for messages
CNode* pnodeTrickle = NULL;
if (!vNodesCopy.empty())
pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
bool fSleep = true;
BOOST_FOREACH (CNode* pnode, vNodesCopy) {
if (pnode->fDisconnect)
continue;
// Receive messages
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv) {
if (!g_signals.ProcessMessages(pnode))
pnode->CloseSocketDisconnect();
if (pnode->nSendSize < SendBufferSize()) {
if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete())) {
fSleep = false;
}
}
}
}
boost::this_thread::interruption_point();
// Send messages
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
g_signals.SendMessages(pnode, pnode == pnodeTrickle || pnode->fWhitelisted);
}
boost::this_thread::interruption_point();
}
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodesCopy)
pnode->Release();
}
if (fSleep)
messageHandlerCondition.timed_wait(lock, boost::posix_time::microsec_clock::universal_time() + boost::posix_time::milliseconds(100));
}
}
// ppcoin: stake minter thread
void static ThreadStakeMinter()
{
boost::this_thread::interruption_point();
LogPrintf("ThreadStakeMinter started\n");
CWallet* pwallet = pwalletMain;
try {
BitcoinMiner(pwallet, true);
boost::this_thread::interruption_point();
} catch (std::exception& e) {
LogPrintf("ThreadStakeMinter() exception \n");
} catch (...) {
LogPrintf("ThreadStakeMinter() error \n");
}
LogPrintf("ThreadStakeMinter exiting,\n");
}
bool BindListenPort(const CService& addrBind, string& strError, bool fWhitelisted)
{
strError = "";
int nOne = 1;
// Create socket for listening for incoming connections
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString());
LogPrintf("%s\n", strError);
return false;
}
SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET) {
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
return false;
}
if (!IsSelectableSocket(hListenSocket)) {
strError = "Error: Couldn't create a listenable socket for incoming connections";
LogPrintf("%s\n", strError);
return false;
}
#ifndef WIN32
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
#endif
// Allow binding if the port is still in TIME_WAIT state after
// the program was closed and restarted. Not an issue on windows!
setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
#endif
// Set to non-blocking, incoming connections will also inherit this
if (!SetSocketNonBlocking(hListenSocket, true)) {
strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
return false;
}
// some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
// and enable it by default or not. Try to enable it, if possible.
if (addrBind.IsIPv6()) {
#ifdef IPV6_V6ONLY
#ifdef WIN32
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
#else
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
#endif
#endif
#ifdef WIN32
int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int));
#endif
}
if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) {
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf(_("Unable to bind to %s on this computer. Decentronium is probably already running."), addrBind.ToString());
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
LogPrintf("%s\n", strError);
CloseSocket(hListenSocket);
return false;
}
LogPrintf("Bound to %s\n", addrBind.ToString());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) {
strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
CloseSocket(hListenSocket);
return false;
}
vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted));
if (addrBind.IsRoutable() && fDiscover && !fWhitelisted)
AddLocal(addrBind, LOCAL_BIND);
return true;
}
void static Discover(boost::thread_group& threadGroup)
{
if (!fDiscover)
return;
#ifdef WIN32
// Get local host IP
char pszHostName[256] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) {
vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr)) {
BOOST_FOREACH (const CNetAddr& addr, vaddr) {
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString());
}
}
}
#else
// Get local host ip
struct ifaddrs* myaddrs;
if (getifaddrs(&myaddrs) == 0) {
for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (strcmp(ifa->ifa_name, "lo") == 0) continue;
if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
if (ifa->ifa_addr->sa_family == AF_INET) {
struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
} else if (ifa->ifa_addr->sa_family == AF_INET6) {
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
}
}
freeifaddrs(myaddrs);
}
#endif
}
void StartNode(boost::thread_group& threadGroup)
{
uiInterface.InitMessage(_("Loading addresses..."));
// Load addresses for peers.dat
int64_t nStart = GetTimeMillis();
{
CAddrDB adb;
if (!adb.Read(addrman))
LogPrintf("Invalid or missing peers.dat; recreating\n");
}
LogPrintf("Loaded %i addresses from peers.dat %dms\n",
addrman.size(), GetTimeMillis() - nStart);
fAddressesInitialized = true;
if (semOutbound == NULL) {
// initialize semaphore
int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections);
semOutbound = new CSemaphore(nMaxOutbound);
}
if (pnodeLocalHost == NULL)
pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
Discover(threadGroup);
//
// Start threads
//
if (!GetBoolArg("-dnsseed", true))
LogPrintf("DNS seeding disabled\n");
else
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed));
// Map ports with UPnP
MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
// Send and receive from sockets, accept connections
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler));
// Initiate outbound connections from -addnode
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections));
// Initiate outbound connections
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections));
// Process messages
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler));
// Dump network addresses
threadGroup.create_thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, DUMP_ADDRESSES_INTERVAL * 1000));
// ppcoin:mint proof-of-stake blocks in the background
if (GetBoolArg("-staking", true))
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "stakemint", &ThreadStakeMinter));
}
bool StopNode()
{
LogPrintf("StopNode()\n");
MapPort(false);
if (semOutbound)
for (int i = 0; i < MAX_OUTBOUND_CONNECTIONS; i++)
semOutbound->post();
if (fAddressesInitialized) {
DumpAddresses();
fAddressesInitialized = false;
}
return true;
}
class CNetCleanup
{
public:
CNetCleanup() {}
~CNetCleanup()
{
// Close sockets
BOOST_FOREACH (CNode* pnode, vNodes)
if (pnode->hSocket != INVALID_SOCKET)
CloseSocket(pnode->hSocket);
BOOST_FOREACH (ListenSocket& hListenSocket, vhListenSocket)
if (hListenSocket.socket != INVALID_SOCKET)
if (!CloseSocket(hListenSocket.socket))
LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
// clean up some globals (to help leak detection)
BOOST_FOREACH (CNode* pnode, vNodes)
delete pnode;
BOOST_FOREACH (CNode* pnode, vNodesDisconnected)
delete pnode;
vNodes.clear();
vNodesDisconnected.clear();
vhListenSocket.clear();
delete semOutbound;
semOutbound = NULL;
delete pnodeLocalHost;
pnodeLocalHost = NULL;
#ifdef WIN32
// Shutdown Windows Sockets
WSACleanup();
#endif
}
} instance_of_cnetcleanup;
void CExplicitNetCleanup::callCleanup()
{
// Explicit call to destructor of CNetCleanup because it's not implicitly called
// when the wallet is restarted from within the wallet itself.
CNetCleanup* tmp = new CNetCleanup();
delete tmp; // Stroustrup's gonna kill me for that
}
void RelayTransaction(const CTransaction& tx)
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(10000);
ss << tx;
RelayTransaction(tx, ss);
}
void RelayTransaction(const CTransaction& tx, const CDataStream& ss)
{
CInv inv(MSG_TX, tx.GetHash());
{
LOCK(cs_mapRelay);
// Expire old relay messages
while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) {
mapRelay.erase(vRelayExpiration.front().second);
vRelayExpiration.pop_front();
}
// Save original serialized message so newer versions are preserved
mapRelay.insert(std::make_pair(inv, ss));
vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
}
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
if (!pnode->fRelayTxes)
continue;
LOCK(pnode->cs_filter);
if (pnode->pfilter) {
if (pnode->pfilter->IsRelevantAndUpdate(tx))
pnode->PushInventory(inv);
} else
pnode->PushInventory(inv);
}
}
void RelayTransactionLockReq(const CTransaction& tx, bool relayToAll)
{
CInv inv(MSG_TXLOCK_REQUEST, tx.GetHash());
//broadcast the new lock
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
if (!relayToAll && !pnode->fRelayTxes)
continue;
pnode->PushMessage("ix", tx);
}
}
void RelayInv(CInv& inv)
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes){
if((pnode->nServices==NODE_BLOOM_WITHOUT_MN) && inv.IsMasterNodeType())continue;
if (pnode->nVersion >= ActiveProtocol())
pnode->PushInventory(inv);
}
}
void CNode::RecordBytesRecv(uint64_t bytes)
{
LOCK(cs_totalBytesRecv);
nTotalBytesRecv += bytes;
}
void CNode::RecordBytesSent(uint64_t bytes)
{
LOCK(cs_totalBytesSent);
nTotalBytesSent += bytes;
}
uint64_t CNode::GetTotalBytesRecv()
{
LOCK(cs_totalBytesRecv);
return nTotalBytesRecv;
}
uint64_t CNode::GetTotalBytesSent()
{
LOCK(cs_totalBytesSent);
return nTotalBytesSent;
}
void CNode::Fuzz(int nChance)
{
if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake
if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages
switch (GetRand(3)) {
case 0:
// xor a random byte with a random value:
if (!ssSend.empty()) {
CDataStream::size_type pos = GetRand(ssSend.size());
ssSend[pos] ^= (unsigned char)(GetRand(256));
}
break;
case 1:
// delete a random byte:
if (!ssSend.empty()) {
CDataStream::size_type pos = GetRand(ssSend.size());
ssSend.erase(ssSend.begin() + pos);
}
break;
case 2:
// insert a random byte at a random position
{
CDataStream::size_type pos = GetRand(ssSend.size());
char ch = (char)GetRand(256);
ssSend.insert(ssSend.begin() + pos, ch);
}
break;
}
// Chance of more than one change half the time:
// (more changes exponentially less likely):
Fuzz(2);
}
//
// CAddrDB
//
CAddrDB::CAddrDB()
{
pathAddr = GetDataDir() / "peers.dat";
}
bool CAddrDB::Write(const CAddrMan& addr)
{
// Generate random temporary filename
unsigned short randv = 0;
GetRandBytes((unsigned char*)&randv, sizeof(randv));
std::string tmpfn = strprintf("peers.dat.%04x", randv);
// serialize addresses, checksum data up to that point, then append csum
CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
ssPeers << FLATDATA(Params().MessageStart());
ssPeers << addr;
uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
ssPeers << hash;
// open output file, and associate with CAutoFile
boost::filesystem::path pathAddr = GetDataDir() / "peers.dat";
FILE* file = fopen(pathAddr.string().c_str(), "wb");
CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s : Failed to open file %s", __func__, pathAddr.string());
// Write and commit header, data
try {
fileout << ssPeers;
} catch (std::exception& e) {
return error("%s : Serialize or I/O error - %s", __func__, e.what());
}
FileCommit(fileout.Get());
fileout.fclose();
return true;
}
bool CAddrDB::Read(CAddrMan& addr)
{
// open input file, and associate with CAutoFile
FILE* file = fopen(pathAddr.string().c_str(), "rb");
CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
return error("%s : Failed to open file %s", __func__, pathAddr.string());
// use file size to size memory buffer
int fileSize = boost::filesystem::file_size(pathAddr);
int dataSize = fileSize - sizeof(uint256);
// Don't try to resize to a negative number if file is small
if (dataSize < 0)
dataSize = 0;
vector<unsigned char> vchData;
vchData.resize(dataSize);
uint256 hashIn;
// read data and checksum from file
try {
filein.read((char*)&vchData[0], dataSize);
filein >> hashIn;
} catch (std::exception& e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
filein.fclose();
CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
// verify stored checksum matches input data
uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
if (hashIn != hashTmp)
return error("%s : Checksum mismatch, data corrupted", __func__);
unsigned char pchMsgTmp[4];
try {
// de-serialize file header (network specific magic number) and ..
ssPeers >> FLATDATA(pchMsgTmp);
// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
return error("%s : Invalid network magic number", __func__);
// de-serialize address data into one CAddrMan object
ssPeers >> addr;
} catch (std::exception& e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
return true;
}
unsigned int ReceiveFloodSize() { return 1000 * GetArg("-maxreceivebuffer", 5 * 1000); }
unsigned int SendBufferSize() { return 1000 * GetArg("-maxsendbuffer", 1 * 1000); }
CNode::CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn, bool fInboundIn) : ssSend(SER_NETWORK, INIT_PROTO_VERSION), setAddrKnown(5000)
{
nServices = 0;
hSocket = hSocketIn;
nRecvVersion = INIT_PROTO_VERSION;
nLastSend = 0;
nLastRecv = 0;
nSendBytes = 0;
nRecvBytes = 0;
nTimeConnected = GetTime();
addr = addrIn;
addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
nVersion = 0;
strSubVer = "";
fWhitelisted = false;
fOneShot = false;
fClient = false; // set by version message
fInbound = fInboundIn;
fNetworkNode = false;
fSuccessfullyConnected = false;
fDisconnect = false;
nRefCount = 0;
nSendSize = 0;
nSendOffset = 0;
hashContinue = 0;
nStartingHeight = -1;
fGetAddr = false;
fRelayTxes = false;
setInventoryKnown.max_size(SendBufferSize() / 1000);
pfilter = new CBloomFilter();
nPingNonceSent = 0;
nPingUsecStart = 0;
nPingUsecTime = 0;
fPingQueued = false;
fObfuScationMaster = false;
{
LOCK(cs_nLastNodeId);
id = nLastNodeId++;
}
if (fLogIPs)
LogPrint("net", "Added connection to %s peer=%d\n", addrName, id);
else
LogPrint("net", "Added connection peer=%d\n", id);
// Be shy and don't send version until we hear
if (hSocket != INVALID_SOCKET && !fInbound)
PushVersion();
GetNodeSignals().InitializeNode(GetId(), this);
}
CNode::~CNode()
{
CloseSocket(hSocket);
if (pfilter)
delete pfilter;
GetNodeSignals().FinalizeNode(GetId());
}
void CNode::AskFor(const CInv& inv)
{
if (mapAskFor.size() > MAPASKFOR_MAX_SZ)
return;
// We're using mapAskFor as a priority queue,
// the key is the earliest time the request can be sent
int64_t nRequestTime;
limitedmap<CInv, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv);
if (it != mapAlreadyAskedFor.end())
nRequestTime = it->second;
else
nRequestTime = 0;
LogPrint("net", "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime / 1000000), id);
// Make sure not to reuse time indexes to keep things in the same order
int64_t nNow = GetTimeMicros() - 1000000;
static int64_t nLastTime;
++nLastTime;
nNow = std::max(nNow, nLastTime);
nLastTime = nNow;
// Each retry is 2 minutes after the last
nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
if (it != mapAlreadyAskedFor.end())
mapAlreadyAskedFor.update(it, nRequestTime);
else
mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime));
mapAskFor.insert(std::make_pair(nRequestTime, inv));
}
void CNode::BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend)
{
ENTER_CRITICAL_SECTION(cs_vSend);
assert(ssSend.size() == 0);
ssSend << CMessageHeader(pszCommand, 0);
LogPrint("net", "sending: %s ", SanitizeString(pszCommand));
}
void CNode::AbortMessage() UNLOCK_FUNCTION(cs_vSend)
{
ssSend.clear();
LEAVE_CRITICAL_SECTION(cs_vSend);
LogPrint("net", "(aborted)\n");
}
void CNode::EndMessage() UNLOCK_FUNCTION(cs_vSend)
{
// The -*messagestest options are intentionally not documented in the help message,
// since they are only used during development to debug the networking code and are
// not intended for end-users.
if (mapArgs.count("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 2)) == 0) {
LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n");
AbortMessage();
return;
}
if (mapArgs.count("-fuzzmessagestest"))
Fuzz(GetArg("-fuzzmessagestest", 10));
if (ssSend.size() == 0)
return;
// Set the size
unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE;
memcpy((char*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], &nSize, sizeof(nSize));
// Set the checksum
uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end());
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
assert(ssSend.size() >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum));
LogPrint("net", "(%d bytes) peer=%d\n", nSize, id);
std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData());
ssSend.GetAndClear(*it);
nSendSize += (*it).size();
// If write queue empty, attempt "optimistic write"
if (it == vSendMsg.begin())
SocketSendData(this);
LEAVE_CRITICAL_SECTION(cs_vSend);
}
| [
"puredev321@gmail.com"
] | puredev321@gmail.com |
9282485cafc454aa7bbdae8f65515af9af9f4d4b | 8ce1e9f1bef1a647f4c986a24df5340ffb17bc4e | /Linked List OO/LinkedListsOOPAssignment/LinkedListsOOPAssignment/Employee.h | a22ad6b25c73ef189d3ed24dee43fb4c1b93435b | [] | no_license | Nikhilvedi/University-Work | 54ac1b22c3dba8bb65f493962b0fbef3bd6cc526 | 118705add1d105e753af5f7814484a3388f6645e | refs/heads/master | 2021-01-10T15:06:22.126914 | 2015-10-17T16:12:04 | 2015-10-17T16:12:04 | 44,443,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 831 | h | #include "stdafx.h"
#include <string>
using namespace std;
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
class Employee
{
protected:
string name;
string startDate;
int empNumber;
int dept;
public:
Employee();
Employee(string, string, int, int);
string getName();
string getStartDate();
int getEmpNo();
int getDept();
void setDept(int);
void setName(string);
virtual ~Employee();
};
class Manager : public Employee
{
private:
int salary;
public:
Manager();
Manager(int,string, string, int, int);
int getSalary();
void setSalary(int);
virtual ~Manager();
};
class Staff : public Employee
{
private:
int hoursPerWeek;
double hourlyRate;
public:
Staff();
Staff(int, double, string, string, int, int);
void setHours(int);
void setRate(double);
double getWage();
double getRate();
virtual ~Staff();
};
#endif | [
"nv94@hotmail.co.uk"
] | nv94@hotmail.co.uk |
1e86a5fc01abe16157d2bf3c0f80fda6145a6255 | e61a0ebe93280719d9bb34cac52d772f0d814e5f | /hdoj1207.cpp | 3c6f23988b6b6fef0fddea83639ba9c787a9e0eb | [] | no_license | zhouwangyiteng/ACM_code | ba5df2215500a1482cf21362160ddbf71be0196d | ca3e888bd4908287dd822471333a38c24b0a05db | refs/heads/master | 2020-04-12T06:35:10.160246 | 2017-04-22T07:44:09 | 2017-04-22T07:44:09 | 61,373,600 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,049 | cpp | /*************************************************************************
> File Name: hdoj1207.cpp
> Author:
> Mail:
> Blog:
> Created Time: 2016年07月30日 星期六 19时50分41秒
************************************************************************/
#include <iostream>
#include <cstdio>
#include <vector>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <cmath>
#include <ctime>
#include <string>
#include <cstring>
#include <set>
#include <bitset>
using namespace std;
#define X first
#define Y second
#define ll long long
#define INF 0x3f3f3f3f
#define N 66
#define PB(X) push_back(X)
#define MP(X,Y) make_pair(X,Y)
#define REP(x,y) for(int x=0;x<y;x++)
#define RDP(x,y) for(int x=y;x>=0;x--)
#define RRP(x,L,R) for(int x=L;x<=R;x++)
#define CLR(A,X) memset(A,X,sizeof(A))
int n;
double ans[N];
int main()
{
ans[1]=1;
ans[2]=3;
for(int i=3;i<N;i++)
{
ans[i]=INF;
for(int j=1;j<i;j++)
ans[i]=min(ans[i],2*ans[j]+pow(2,i-j)-1);
}
while(cin>>n)
cout<<ans[n]<<endl;
return 0;
}
| [
"zhouwang122@qq.com"
] | zhouwang122@qq.com |
7002cdc385ab345c27679e593dfb72df3e69d413 | a63e739155d5b07bb9252501b64bf0d5de275087 | /Ejercicio 4/src/common/Resultado.cpp | 7329329f8038be5b00c8fdebf9220128a205a73d | [] | no_license | dario-ramos/testers-distribuidos7574 | 677b79588aadeb547d85f5f31f6c3912828cc8e4 | 5a8e992960f069a80491d49d270e52c4a8b95db6 | refs/heads/master | 2016-09-05T21:52:37.730168 | 2015-03-09T16:59:22 | 2015-03-09T16:59:22 | 33,097,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 178 | cpp | /*
* File: Resultado.cpp
* Author: knoppix
*
* Created on October 4, 2014, 10:28 PM
*/
#include "Resultado.h"
Resultado::Resultado() {
}
Resultado::~Resultado() {
}
| [
"dario.fenix@gmail.com@18dcfaaf-94c9-9b71-9433-3f00c941b258"
] | dario.fenix@gmail.com@18dcfaaf-94c9-9b71-9433-3f00c941b258 |
eb1955d5768754226c535e1f1fe360f376e88e7e | 4051dc0d87d36c889aefb2864ebe32cd21e9d949 | /practice/Level_order_non_recursive.cpp | 19bbb674602a60cb3aba6abcb765d893905ac265 | [] | no_license | adityax10/ProgrammingCodes | e239971db7f3c4de9f2b060434a073932925ba4d | 8c9bb45e1a2a82f76b66f375607c65037343dcd9 | refs/heads/master | 2021-01-22T22:53:01.382230 | 2014-11-07T10:35:00 | 2014-11-07T10:35:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 557 | cpp | #include<bits/stdc++.h>
using namespace std;
class node
{
public:
int data;
node *l,*r;
node(int data)
{
this->data = data;
l=r=0;
}
};
void levelorder(node *t)
{
queue<node*> v;
v.push(t);
while(!v.empty())
{
t = v.front();
v.pop();
cout<<t->data<<" ";
if(t->l)
v.push(t->l);
if(t->r)
v.push(t->r);
}
}
int main()
{
node *t;
t = new node(1);
t->l = new node(2);
t->r = new node(3);
t->l->l = new node(4);
t->l->r = new node(5);
t->r->l = new node(6);
t->r->r = new node(7);
levelorder(t);
return 0;
}
| [
"androidaditya@gmail.com"
] | androidaditya@gmail.com |
b9a0089e9ff15372c8809bae2153da632e3fc563 | 7f6d2df4f97ee88d8614881b5fa0e30d51617e61 | /武庆安/Experiment_3/SouceCode/example2_04-局部变量.cpp | 311b7cbb672a69dfd339860f01fdf4f1afa044e8 | [] | no_license | tsingke/Homework_Turing | 79d36b18692ec48b1b65cfb83fc21abf87fd53b0 | aa077a2ca830cdf14f4a0fd55e61822a4f99f01d | refs/heads/master | 2021-10-10T02:03:53.951212 | 2019-01-06T07:44:20 | 2019-01-06T07:44:20 | 148,451,853 | 15 | 25 | null | 2018-10-17T15:20:24 | 2018-09-12T09:01:50 | C++ | UTF-8 | C++ | false | false | 905 | cpp | // example2_04:局部变量示例
#include <stdio.h>
#include <windows.h>
int n = 10; //全局变量
void func(int n)
{
n = 20; //局部变量
printf("func n: %d\n", n);
}
void func1()
{
int n = 20; //局部变量
printf("func1 n: %d\n", n);
}
void func2(int n)
{
printf("func2 n: %d\n", n);
}
void func3()
{
printf("func3 n: %d\n", n);
}
int main()
{
int n = 30; //局部变量
func(n); //20 子函数有,传参,输出自己的wqa
func1(); //20 子函数有,不传参,输出自己的
func2(n); //30 子函数无,传参,输出mian()里的
func3(); //10 子函数无,不传参,输全局变量的
//代码块由{}包围
{
int n = 40; //局部变量
printf("block n: %d\n", n); //40 代码块包围,输出代码块里的
}
printf("main n: %d\n", n); //30 main---全局变量
system("pause");
return 0;
} | [
"201711010304@stu.sdnu.edu.cn"
] | 201711010304@stu.sdnu.edu.cn |
bc9d8bba86d16f2e545ac32ae3f79fe75999a993 | 85fcd407df2eb50ea6e015580986f950882f9fd4 | /basics/Arrays/sortInLinearTime.cpp | 0cf4cc6133c6ecf1846f1152302256f9f8e07e82 | [] | no_license | naveen700/CodingPractice | ff26c3901b8721cb0c6de32f8df246b999893471 | d4f7c756974a5eee16c79e8d98f86b546260aa6d | refs/heads/master | 2021-01-16T02:19:27.387955 | 2020-04-26T17:41:08 | 2020-04-26T17:41:08 | 242,941,499 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 708 | cpp | #include <iostream>
using namespace std;
void sortInLinearTime(int [],int);
int main(){
int len;
cin>>len;
int arr[len];
for(int i=0; i<len;i++){
cin>>arr[i];
}
sortInLinearTime(arr,len);
}
void sortInLinearTime(int arr[] , int len){
int a=0, b=0 ,c=0;
// to count no of zeroes ,ones, twos
for(int i =0; i <len;i++){
if(arr[i] == 0){
a++;
}else if(arr[i] == 1){
b++;
}else{
c++;
}
}
//print array
for(int i=0; i<a;i++){
cout<<"0"<<endl;
}
for(int i=0; i<b;i++){
cout<<"1"<<endl;
}
for(int i=0; i<c;i++){
cout<<"2"<<endl;
}
} | [
"naveenrana921@gmail.com"
] | naveenrana921@gmail.com |
55cac0b1df59f2c448c66ef59d722c32cd545e58 | 2a6a078d0073cfc78429f1f96370bac32bb5bd38 | /src/node.h | effd6b13ce3c3bb313049a9834ebfc19053b9d18 | [] | no_license | dieu-detruit/onnx2c | 0466386ad96ab4eab6c1ecd231e83dee2ebb9acc | 97e8d3913253e349b103c4dbdff30552d4137be0 | refs/heads/master | 2023-04-06T20:59:09.383733 | 2021-03-28T14:03:45 | 2021-03-31T19:39:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,089 | h | #pragma once
#include <string>
#include "error.h"
#include "onnx.pb.h"
#include "util.h"
namespace toC {
class Tensor;
/* The ONNX node, or computation kernel. *
* Node is a virtual parent class for each of the
* ONNX node "types" or "operands" (e.g. Add, Relu, ...)
* Each individual node in the graph is then an instance of
* these subclasses.
*/
class Node {
public:
bool isResolved;
const onnx::NodeProto *onnx_node;
std::string onnx_name; //ONNX name of the individual node
std::string op_name; //ONNX name of node type
static int64_t onnx_ir_version;
/* Create the C source name. Replace all non a-z,A-Z,0-9 or _
* characters. Also prefix name since ONNX allows tensors and nodes
* to have the same name */
std::string c_name(void) const
{
return "node_" + cify_name(onnx_name);
}
/* Print the C implmementation of the operator */
virtual void print(std::ostream &destination) const = 0;
/* Print comma-separated list of function parameters.
* Unused optional tensors skipped. e.g.:
* "tensior_X, tensor_Y"
* or decorated
* "float tensor_X[1][2][3], float tensor_Y[2][3][4]"
*/
virtual void print_parameters(std::ostream &destination, bool decorate ) const = 0;
/* Figure out in what format the output is in.
* Return values are pointers to Tensor values, allocated with new. Ownership given to caller.
* This function may not fail: call only with all inputs given & resolved */
virtual void resolveOutput(const std::vector< const Tensor*> &inputs, std::vector<Tensor *> &outputs) = 0;
/* Check if an optional output is used in the network.
* N is Nth output specified in the Operator.md specification for this node.
* Start counting N from 0. */
bool is_output_N_used(unsigned N);
/* Not all node types have attributes. Override where needed */
virtual void parseAttributes( onnx::NodeProto &node )
{
ERROR("Attribute parsing not implemented for node operation type " << op_name);
}
/* TODO: these should be part of class Tensor... */
/* Check input constraints, as used in
* https://github.com/onnx/onnx/blob/master/docs/Operators.md
*/
/* (u)int32, (u)int64, float16/32/64, bfloat*/
bool typeConstraint_highPrecisionNumeric(const Tensor *t) const;
/* float16/32/64, bfloat */
bool typeConstraint_allFloatingPoints(const Tensor *t) const;
/* float16/32/64, (not bfloat!) */
bool typeConstraint_plainFloatingPoints(const Tensor *t) const;
bool typeConstraint_int64(const Tensor *t) const;
/* int8 or uint8 */
bool typeConstraint_8bit(const Tensor *t) const;
/* any integer, signed or not */
bool typeConstraint_integers(const Tensor *t) const;
/* only unsigned integers */
bool typeConstraint_unsigned_integers(const Tensor *t) const;
/* only signed integers */
bool typeConstraint_signed_integers(const Tensor *t) const;
/* Do Multidirectional Broadcasting dimension extensions:
* https://github.com/onnx/onnx/blob/master/docs/Broadcasting.md
*/
void multidirectional_broadcast_size(
const std::vector<int> A,
const std::vector<int> B,
std::vector<int> &result) const;
};
}
| [
"kraiskil@iki.fi"
] | kraiskil@iki.fi |
d1ce092da27c2bfc9c353926f51085895022f3d9 | 95dcf1b68eb966fd540767f9315c0bf55261ef75 | /build/pc/Boost_1_50_0/output/include/boost-1_50/boost/mpl/multiset/aux_/item.hpp | 839c338e18241851ab2c45579dcdb96031efef79 | [
"BSL-1.0"
] | permissive | quinsmpang/foundations.github.com | 9860f88d1227ae4efd0772b3adcf9d724075e4d1 | 7dcef9ae54b7e0026fd0b27b09626571c65e3435 | refs/heads/master | 2021-01-18T01:57:54.298696 | 2012-10-14T14:44:38 | 2012-10-14T14:44:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,661 | hpp |
#ifndef BOOST_MPL_MULTISET_AUX_ITEM_HPP_INCLUDED
#define BOOST_MPL_MULTISET_AUX_ITEM_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2003-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: item.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-11 14:19:02 +0800 (星期六, 2008-10-11) $
// $Revision: 49267 $
#include <boost/mpl/multiset/aux_/tag.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/aux_/type_wrapper.hpp>
#include <boost/mpl/aux_/yes_no.hpp>
#include <boost/mpl/aux_/value_wknd.hpp>
#include <boost/mpl/aux_/static_cast.hpp>
#include <boost/mpl/aux_/config/arrays.hpp>
#include <boost/mpl/aux_/config/msvc.hpp>
#include <boost/mpl/aux_/config/workaround.hpp>
#if BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
# include <boost/mpl/eval_if.hpp>
# include <boost/mpl/next.hpp>
# include <boost/type_traits/is_same.hpp>
#endif
namespace boost { namespace mpl {
#if BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
template< typename T, typename Base >
struct ms_item
{
typedef aux::multiset_tag tag;
template< typename U > struct prior_count
{
enum { msvc70_wknd_ = sizeof(Base::key_count(BOOST_MPL_AUX_STATIC_CAST(U*,0))) };
typedef int_< msvc70_wknd_ > count_;
typedef typename eval_if< is_same<T,U>, next<count_>, count_ >::type c_;
#if defined(BOOST_MPL_CFG_NO_DEPENDENT_ARRAY_TYPES)
typedef typename aux::weighted_tag<BOOST_MPL_AUX_MSVC_VALUE_WKND(c_)::value>::type type;
#else
typedef char (&type)[BOOST_MPL_AUX_MSVC_VALUE_WKND(c_)::value];
#endif
};
template< typename U > struct prior_ref_count
{
typedef U (* u_)();
enum { msvc70_wknd_ = sizeof(Base::ref_key_count(BOOST_MPL_AUX_STATIC_CAST(u_,0))) };
typedef int_< msvc70_wknd_ > count_;
typedef typename eval_if< is_same<T,U>, next<count_>, count_ >::type c_;
#if defined(BOOST_MPL_CFG_NO_DEPENDENT_ARRAY_TYPES)
typedef typename aux::weighted_tag<BOOST_MPL_AUX_MSVC_VALUE_WKND(c_)::value>::type type;
#else
typedef char (&type)[BOOST_MPL_AUX_MSVC_VALUE_WKND(c_)::value];
#endif
};
template< typename U >
static typename prior_count<U>::type key_count(U*);
template< typename U >
static typename prior_ref_count<U>::type ref_key_count(U (*)());
};
#else // BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
namespace aux {
template< typename U, typename Base >
struct prior_key_count
{
enum { msvc71_wknd_ = sizeof(Base::key_count(BOOST_MPL_AUX_STATIC_CAST(aux::type_wrapper<U>*,0))) };
typedef int_< msvc71_wknd_ > count_;
#if defined(BOOST_MPL_CFG_NO_DEPENDENT_ARRAY_TYPES)
typedef typename aux::weighted_tag< BOOST_MPL_AUX_VALUE_WKND(count_)::value >::type type;
#else
typedef char (&type)[count_::value];
#endif
};
}
template< typename T, typename Base >
struct ms_item
{
typedef aux::multiset_tag tag;
enum { msvc71_wknd_ = sizeof(Base::key_count(BOOST_MPL_AUX_STATIC_CAST(aux::type_wrapper<T>*,0))) + 1 };
typedef int_< msvc71_wknd_ > count_;
#if defined(BOOST_MPL_CFG_NO_DEPENDENT_ARRAY_TYPES)
static
typename aux::weighted_tag< BOOST_MPL_AUX_VALUE_WKND(count_)::value >::type
key_count(aux::type_wrapper<T>*);
#else
static char (& key_count(aux::type_wrapper<T>*) )[count_::value];
#endif
template< typename U >
static typename aux::prior_key_count<U,Base>::type key_count(aux::type_wrapper<U>*);
};
#endif // BOOST_WORKAROUND(BOOST_MSVC, <= 1300)
}}
#endif // BOOST_MPL_MULTISET_AUX_ITEM_HPP_INCLUDED
| [
"wisbyme@yahoo.com"
] | wisbyme@yahoo.com |
dd59b9acea9bece9435b803d9b36c2b8f4e17a96 | af665e07d1c18a8a15b39a980b01b2a55a33bb78 | /kaldi/src/nnet3/nnet-descriptor.h | e2d2c41772d4ddb605875ba7faea7361c6cae716 | [
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | permissive | lyapple2008/SpeakerVerification_based_on_Kaldi | cd52721fcf9b6d05326df5a7fcabd0bf66db7f08 | 838b60e8a5be31909f7d17941999ad2fa6f32b4a | refs/heads/master | 2021-01-23T06:14:35.046951 | 2017-06-01T09:33:10 | 2017-06-01T09:33:10 | 93,015,037 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 26,845 | h | // nnet3/nnet-descriptor.h
// Copyright 2012-2015 Johns Hopkins University (author: Daniel Povey)
// See ../../COPYING for clarification regarding multiple authors
//
// 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#ifndef KALDI_NNET3_NNET_DESCRIPTOR_H_
#define KALDI_NNET3_NNET_DESCRIPTOR_H_
#include "base/kaldi-common.h"
#include "util/kaldi-io.h"
#include "matrix/matrix-lib.h"
#include "nnet3/nnet-common.h"
#include "nnet3/nnet-component-itf.h"
#include <iostream>
#include <sstream>
#include <vector>
#include <map>
namespace kaldi {
namespace nnet3 {
/**
\file nnet-descriptor.h
This file contains class definitions for classes ForwardingDescriptor,
SumDescriptor and Descriptor. Basically this is code that specifies how
we glue together the outputs of possibly several other network-nodes, as the
input of a particular network node (or as an output of the network). In the
neural-network code we refer to the top-level descriptor which is
Descriptor. The InputDescriptor is a concatenation of features; each part
is a SumDescriptor. The SumDescriptor is a summation over a set of features
of all the same dimension, each of which is represented by a
ForwardingDescriptor. A ForwardingDescriptor in the simplest case just
takes just points you to a particular network node, but in general can do
things like adding time offsets, and selecting different rows of its matrix
from different inputs. Unlike the other descriptors, a ForwardingDescriptor
is in general a bit like a parse tree, in that it can in general contain
other ForwardingDescriptors.
The following gives an overview of the expressions that can appear in
descriptors. Caution; this is a simplification that overgenerates
descriptors.
\verbatim
<descriptor> ::= <node-name> ;; node name of kInput or kComponent node.
<descriptor> ::= Append(<descriptor>, <descriptor> [, <descriptor> ... ] )
<descriptor> ::= Sum(<descriptor>, <descriptor>)
;; Failover or IfDefined might be useful for time t=-1 in a RNN, for instance.
<descriptor> ::= Failover(<descriptor>, <descriptor>) ;; 1st arg if computable, else 2nd
<descriptor> ::= IfDefined(<descriptor>) ;; the arg if defined, else zero.
<descriptor> ::= Offset(<descriptor>, <t-offset> [, <x-offset> ] ) ;; offsets are integers
;; Switch(...) is intended to be used in clockwork RNNs or similar schemes. It chooses
;; one argument based on the value of t (in the requested Index) modulo the number of
;; arguments
<descriptor> ::= Switch(<descriptor>, <descriptor> [, <descriptor> ...])
;; For use in clockwork RNNs or similar, Round() rounds the time-index t of the
;; requested Index to the next-lowest multiple of the integer <t-modulus>,
;; and evaluates the input argument for the resulting Index.
<descriptor> ::= Round(<descriptor>, <t-modulus>) ;; <t-modulus> is an integer
;; ReplaceIndex replaces some <variable-name> (t or x) in the requested Index
;; with a fixed integer <value>. E.g. might be useful when incorporating
;; iVectors; iVector would always have time-index t=0.
<descriptor> ::= ReplaceIndex(<descriptor>, <variable-name>, <value>)
\endverbatim
*/
// A ForwardingDescriptor describes how we copy data from another NetworkNode,
// or from multiple other NetworkNodes. In the simplest case this can just be
// equivalent to giving the name of another NetworkNode, but we also support
// things like time-offsets, selecting depending on the index from multiple
// different inputs, and things like that.
//
// note: nodes of type kOutput (i.e. output nodes of the network) cannot appear
// as inputs in any descriptor. This is to simplify compilation.
class ForwardingDescriptor {
public:
// Given an Index that's requested at the output of this descriptor, maps it
// to a (node_index, Index) pair that says where we are to get the data from.
virtual Cindex MapToInput(const Index &output) const = 0;
// Return the feature dimension.
virtual int32 Dim(const Nnet &nnet) const = 0;
virtual ForwardingDescriptor *Copy() const = 0;
/// This function is for use in things like clockwork RNNs, where shifting the
/// time of the inputs and outputs of the network by some multiple integer n
/// would leave things the same, but shifting by non-multiples would change the
/// network structure. It returns the smallest modulus to which this
/// descriptor is invariant; the lowest common multiple of all descriptors in
/// the network gives you the modulus for the whole network.
virtual int32 Modulus() const { return 1; }
// Write to string that will be one line of a config-file-like format. The
// opposite of Parse.
virtual void WriteConfig(std::ostream &os,
const std::vector<std::string> &node_names) const = 0;
/// This function appends to "node_indexes" all the node indexes
// that this descriptor may access.
virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const = 0;
virtual ~ForwardingDescriptor() { }
ForwardingDescriptor() { }
private:
KALDI_DISALLOW_COPY_AND_ASSIGN(ForwardingDescriptor);
};
// SimpleForwardingDescriptor is the base-case of ForwardingDescriptor,
class SimpleForwardingDescriptor: public ForwardingDescriptor {
public:
virtual Cindex MapToInput(const Index &index) const;
virtual int32 Dim(const Nnet &nnet) const;
virtual ForwardingDescriptor *Copy() const;
virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const;
// Write to string that will be one line of a config-file-like format. The
// opposite of Parse.
// written form is just the node-name of src_node_.
virtual void WriteConfig(std::ostream &os,
const std::vector<std::string> &node_names) const;
SimpleForwardingDescriptor(int32 src_node): src_node_(src_node) {
KALDI_ASSERT(src_node >= 0);
}
virtual ~SimpleForwardingDescriptor() { }
private:
int32 src_node_; // index of the source NetworkNode.
};
class OffsetForwardingDescriptor: public ForwardingDescriptor {
public:
virtual Cindex MapToInput(const Index &ind) const;
virtual int32 Dim(const Nnet &nnet) const { return src_->Dim(nnet); }
virtual ForwardingDescriptor *Copy() const;
// written form is: Offset(<src-written-form>, t-offset [, x-offset])
virtual void WriteConfig(std::ostream &os,
const std::vector<std::string> &node_names) const;
virtual int32 Modulus() const { return src_->Modulus(); }
virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const;
// takes ownership of src.
OffsetForwardingDescriptor(ForwardingDescriptor *src,
Index offset): src_(src), offset_(offset) { }
virtual ~OffsetForwardingDescriptor() { delete src_; }
private:
ForwardingDescriptor *src_; // Owned here.
Index offset_; // The index-offset to be added to the index.
};
// Chooses from different inputs based on the the time index modulo
// (the number of ForwardingDescriptors given as inputs).
class SwitchingForwardingDescriptor: public ForwardingDescriptor {
public:
virtual Cindex MapToInput(const Index &ind) const;
virtual int32 Dim(const Nnet &nnet) const { return src_[0]->Dim(nnet); }
virtual ForwardingDescriptor *Copy() const;
// Written form is "Switch(<written-form-of-src1>, <written-form-of-src2>, ... )"
virtual void WriteConfig(std::ostream &os,
const std::vector<std::string> &node_names) const;
virtual int32 Modulus() const;
/// This function appends to "node_indexes" all the node indexes
// that this descriptor may access.
virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const;
// takes ownership of items in src.
SwitchingForwardingDescriptor(std::vector<ForwardingDescriptor*> &src):
src_(src) { }
virtual ~SwitchingForwardingDescriptor() { DeletePointers(&src_); }
private:
// Pointers are owned here.
std::vector<ForwardingDescriptor*> src_;
};
/// For use in clockwork RNNs and the like, this forwarding-descriptor
/// rounds the time-index t down to the the closest t' <= t that is
/// an exact multiple of t_modulus_.
class RoundingForwardingDescriptor: public ForwardingDescriptor {
public:
virtual Cindex MapToInput(const Index &ind) const;
virtual int32 Dim(const Nnet &nnet) const { return src_->Dim(nnet); }
virtual ForwardingDescriptor *Copy() const;
// Written form is "Round(<written-form-of-src>, <t_modulus>)"
virtual void WriteConfig(std::ostream &os,
const std::vector<std::string> &node_names) const;
virtual int32 Modulus() const { return t_modulus_; }
/// This function appends to "node_indexes" all the node indexes
// that this descriptor may access.
virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const;
// takes ownership of src.
RoundingForwardingDescriptor(ForwardingDescriptor *src,
int32 t_modulus):
src_(src), t_modulus_(t_modulus) { }
virtual ~RoundingForwardingDescriptor() { delete src_; }
private:
ForwardingDescriptor *src_;
int32 t_modulus_;
};
/// This ForwardingDescriptor modifies the indexes (n, t, x) by replacing one
/// of them (normally t) with a constant value and keeping the rest.
class ReplaceIndexForwardingDescriptor: public ForwardingDescriptor {
public:
enum VariableName { kN = 0, kT = 1, kX = 2};
virtual Cindex MapToInput(const Index &ind) const;
virtual int32 Dim(const Nnet &nnet) const { return src_->Dim(nnet); }
virtual ForwardingDescriptor *Copy() const;
// Written form is "ReplaceIndex(<written-form-of-src>, <variable-name>, <value>)"
// where <variable-name> is either "t" or "x".
virtual void WriteConfig(std::ostream &os,
const std::vector<std::string> &node_names) const;
/// This function appends to "node_indexes" all the node indexes
// that this descriptor may access.
virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const;
// takes ownership of src.
ReplaceIndexForwardingDescriptor(ForwardingDescriptor *src,
VariableName variable_name,
int32 value):
src_(src), variable_name_(variable_name), value_(value) { }
virtual ~ReplaceIndexForwardingDescriptor() { delete src_; }
private:
ForwardingDescriptor *src_;
VariableName variable_name_;
int32 value_;
};
/// Forward declaration. This is declared in nnet-computation-graph.h.
class CindexSet;
/// This is an abstract base-class. In the normal case a SumDescriptor is a sum
/// over one or more terms, all each corresponding to a quantity of the same
/// dimension, each of which is a ForwardingDescriptor. However, it also allows
/// for logic for dealing with cases where only some terms in the sum are
/// present, and only some are included in the sum: for example, not just
/// expressions like A + B but also A + (B if present), or (A if present; if not,
// B).
class SumDescriptor {
public:
/// Given an Index at the output of this Descriptor, append to "dependencies"
/// a list of Cindexes that describes what inputs we potentially depend on.
/// The output list is not necessarily sorted, and this function doesn't make
/// sure that it's unique.
virtual void GetDependencies(const Index &ind,
std::vector<Cindex> *dependencies) const = 0;
/// This function exists to enable us to manage optional dependencies,
/// i.e. for making sense of expressions like (A + (B is present)) and (A if
/// present; if not, B). Suppose we are trying to compute the index "ind",
/// and the user represents that "cindex_set" is the set of Cindexes are
/// available to the computation; then this function will return true if we
/// can compute the expression given these inputs; and if so, will output to
/// "used_inputs" the list of Cindexes that this expression will be a
/// summation over.
///
/// @param [in] ind The index that we want to compute at the output of the
/// Descriptor.
/// @param [in] cindex_set The set of Cindexes that are available at the
/// input of the Descriptor.
/// @param [out] used_inputs If non-NULL, if this function returns true then
/// to this vector will be *appended* the inputs that will
/// actually participate in the computation. Else (if non-NULL) it
/// will be left unchanged.
/// @return Returns true if this output is computable given the provided
/// inputs.
virtual bool IsComputable(const Index &ind,
const CindexSet &cindex_set,
std::vector<Cindex> *used_inputs) const = 0;
virtual int32 Dim(const Nnet &nnet) const = 0;
virtual SumDescriptor *Copy() const = 0;
virtual ~SumDescriptor() { }
// This function appends to "node_indexes" a list (not necessarily sorted or
// unique) of all the node indexes that this descriptor may forward data from.
virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const = 0;
// see Modulus function of ForwardingDescriptor for explanation.
virtual int32 Modulus() const = 0;
/// Write in config-file format. Conventional Read and Write methods are not
/// supported.
virtual void WriteConfig(std::ostream &os,
const std::vector<std::string> &node_names) const = 0;
};
/// This is the case of class SumDescriptor, in which we contain just one term,
/// and that term is optional (an IfDefined() expression). That term is a
/// general SumDescriptor.
class OptionalSumDescriptor: public SumDescriptor {
public:
virtual void GetDependencies(const Index &ind,
std::vector<Cindex> *dependencies) const;
virtual bool IsComputable(const Index &ind,
const CindexSet &cindex_set,
std::vector<Cindex> *used_inputs) const {
return src_->IsComputable(ind, cindex_set, used_inputs) || true;
}
virtual int32 Dim(const Nnet &nnet) const;
// This function appends to "node_indexes" a list (not necessarily sorted or
// unique) of all the node indexes that this descriptor may forward data from.
virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const;
virtual int32 Modulus() const { return src_->Modulus(); }
/// written form is: if required_ == true, "<written-form-of-src>"
/// else "IfDefined(<written-form-of-src>)".
virtual void WriteConfig(std::ostream &os,
const std::vector<std::string> &node_names) const;
virtual SumDescriptor *Copy() const;
OptionalSumDescriptor(SumDescriptor *src): src_(src) { }
virtual ~OptionalSumDescriptor() { delete src_; }
private:
SumDescriptor *src_;
};
// This is the base-case of SumDescriptor which just wraps
// a ForwardingDescriptor.
class SimpleSumDescriptor: public SumDescriptor {
public:
virtual void GetDependencies(const Index &ind,
std::vector<Cindex> *dependencies) const;
virtual bool IsComputable(const Index &ind,
const CindexSet &cindex_set,
std::vector<Cindex> *used_inputs) const;
virtual int32 Dim(const Nnet &nnet) const;
// This function appends to "node_indexes" a list (not necessarily sorted or
// unique) of all the node indexes that this descriptor may forward data from.
virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const;
virtual int32 Modulus() const { return src_->Modulus(); }
/// written form is: if required_ == true, "<written-form-of-src>"
/// else "IfDefined(<written-form-of-src>)".
virtual void WriteConfig(std::ostream &os,
const std::vector<std::string> &node_names) const;
virtual SumDescriptor *Copy() const;
SimpleSumDescriptor(ForwardingDescriptor *src): src_(src) { }
virtual ~SimpleSumDescriptor() { delete src_; }
private:
ForwardingDescriptor *src_;
};
/// BinarySumDescriptor can represent either A + B, or (A if defined, else B).
/// Other expressions such as A + (B if defined, else zero), (A if defined, else
/// zero) + (B if defined, else zero), and (A if defined, else B if defined,
/// else zero) can be expressed using combinations of the two provided options
/// for BinarySumDescriptor and the variant
class BinarySumDescriptor: public SumDescriptor {
public:
enum Operation {
kSum, // A + B
kFailover, // A if defined, else B.
};
virtual void GetDependencies(const Index &ind,
std::vector<Cindex> *dependencies) const;
virtual bool IsComputable(const Index &ind,
const CindexSet &cindex_set,
std::vector<Cindex> *used_inputs) const;
virtual int32 Dim(const Nnet &nnet) const;
// This function appends to "node_indexes" a list (not necessarily sorted or
// unique) of all the node indexes that this descriptor may forward data from.
virtual void GetNodeDependencies(std::vector<int32> *node_indexes) const;
virtual int32 Modulus() const;
/// Written form is: if op_ == kSum then "Sum(<src1>, <src2>)";
/// if op_ == kFailover, then "Failover(<src1>, <src2>)"
/// If you need more than binary operations, just use Sum(a, Sum(b, c)).
virtual void WriteConfig(std::ostream &os,
const std::vector<std::string> &node_names) const;
virtual SumDescriptor *Copy() const;
BinarySumDescriptor(Operation op, SumDescriptor *src1, SumDescriptor *src2):
op_(op), src1_(src1), src2_(src2) {}
virtual ~BinarySumDescriptor() { delete src1_; delete src2_; }
private:
Operation op_;
SumDescriptor *src1_;
SumDescriptor *src2_;
};
// A Descriptor concatenates over its parts, so its feature-dimension will
// be the sum of the feature-dimensions of its parts. In a valid Descriptor,
// "parts" will be nonempty. Each part may be (in general) a summation, but
// usually a summation with just one term.
class Descriptor {
public:
int32 Dim(const Nnet &nnet) const;
// The Parse method is used for reading a config-file-style represenation.
// Internally this uses class GeneralDescriptor to read and normalize the
// input. Assumes the input has already been tokenized into an array of
// strings by DescriptorTokenize(); it moves the begin-pointer "next_token" to
// account for each token that it consumes. Prints warning and returns false on
// error (including if there was junk after the last token). The input tokens
// should be terminated with a token that says "end of input".
bool Parse(const std::vector<std::string> &node_names,
const std::string **next_token);
// Write in config-file format.
// if parts_.size() == 1, written form is just "<written-form-of-part0>"
// otherwise, written form is "Append(<written-form-of-part0>, <written-form-of-part1>, ... )".
void WriteConfig(std::ostream &os,
const std::vector<std::string> &node_names) const;
/// This function exists to enable us to manage optional dependencies,
/// i.e. for making sense of expressions like (A + (B is present)) and (A if
/// present; if not, B). Suppose we are trying to compute the index "ind",
/// and the user represents that "cindex_set" is the set of Cindexes are
/// available to the computation; then this function will return true if we
/// can compute the expression given these inputs; and if so, will output to
/// "used_inputs" the list of Cindexes (not necessarily unique) that this
/// expression will include. Otherwise it will return false and set
/// used_inputs to the empty vector.
///
/// @param [in] ind The index that we want to compute at the output of the
/// Descriptor.
/// @param [in] cindex_set The set of Cindexes that are available at the
/// input of the Descriptor.
/// @param [out] used_inputs If non-NULL, if this function returns true then
/// to this vector will be *appended* the inputs that will
/// actually participate in the computation. Else (if non-NULL) it
/// will be left unchanged.
/// @return Returns true if this output is computable given the provided
/// inputs.
void GetDependencies(const Index &index,
std::vector<Cindex> *used_inputs) const;
/// Has the same purpose and interface as the IsComputable function of the
/// SumDescriptor function. Outputs to used_inputs rather than appending
/// to it, though. used_inputs will not be sorted or have repeats removed.
bool IsComputable(const Index &ind,
const CindexSet &cindex_set,
std::vector<Cindex> *used_inputs) const;
// This function outputs to "node_indexes" a list (not necessarily sorted or
// unique) of all the node indexes that this descriptor may forward data from.
void GetNodeDependencies(std::vector<int32> *node_indexes) const;
// see Modulus function of ForwardingDescriptor for explanation.
int32 Modulus() const;
/// Returns the number of parts that are concatenated over.
int32 NumParts() const { return parts_.size(); }
/// returns the n'th part.
const SumDescriptor &Part(int32 n) const;
Descriptor() { }
/// Copy constructor
Descriptor(const Descriptor &other) { *this = other; }
/// Assignment operator.
Descriptor &operator = (const Descriptor &other);
/// Takes ownership of pointers in "parts".
Descriptor(const std::vector<SumDescriptor*> &parts):
parts_(parts) { }
/// Destructor
~Descriptor() { Destroy(); }
private:
void Destroy(); // empties parts_ after deleting its members.
// the elements of parts_ are owned here.
std::vector<SumDescriptor*> parts_;
};
/**
This class is only used when parsing Descriptors. It is useful for normalizing
descriptors that are structured in an invalid or redundant way, into a
form that can be turned into a real Descriptor.
*/
struct GeneralDescriptor {
enum DescriptorType { kAppend, kSum, kFailover, kIfDefined, kOffset, kSwitch,
kRound, kReplaceIndex, kNodeName };
// The Parse method is used for reading a config-file-style represenation.
// Assumes the input has already been tokenized into an array of strings, and
// it moves the begin-pointer "next_token" to account for token that it
// consumes. Calls KALDI_ERR on error. The list of tokens should be
// terminated with a string saying "end of input". Does not check that all
// the input has been consumed-- the caller should do that [check that
// **next_token == "end of input" after calling.]
static GeneralDescriptor *Parse(const std::vector<std::string> &node_names,
const std::string **next_token);
explicit GeneralDescriptor(DescriptorType t, int32 value1 = -1,
int32 value2 = -1):
descriptor_type_(t), value1_(value1), value2_(value2) { }
~GeneralDescriptor() { DeletePointers(&descriptors_); }
GeneralDescriptor *GetNormalizedDescriptor() const;
Descriptor *ConvertToDescriptor();
// prints in text form-- this is really only used for debug.
void Print(const std::vector<std::string> &node_names,
std::ostream &os);
private:
KALDI_DISALLOW_COPY_AND_ASSIGN(GeneralDescriptor);
DescriptorType descriptor_type_;
// the following is only relevant if descriptor_type == kReplaceIndex [1 for t, 2 for ]
// or kNodeName (the index of the node), or kOffset [the t offset].
int32 value1_;
// the following is only relevant if descriptor_type == kReplaceIndex [the value
// we replace the index with], or kOffset [the x offset]
int32 value2_;
// For any descriptor types that take args of type kDescriptor, a list of those
// args. Pointers owned here.
std::vector<GeneralDescriptor*> descriptors_;
// parses an Append() or Sum() or Switch() expression after the "Append(" or
// "Sum(" or "Switch(" has been read.
void ParseAppendOrSumOrSwitch(const std::vector<std::string> &node_names,
const std::string **next_token);
// parse an IfDefined() expression after the IfDefined( has already been
// read.
void ParseIfDefined(const std::vector<std::string> &node_names,
const std::string **next_token);
// ... and so on.
void ParseOffset(const std::vector<std::string> &node_names,
const std::string **next_token);
void ParseSwitch(const std::vector<std::string> &node_names,
const std::string **next_token);
void ParseFailover(const std::vector<std::string> &node_names,
const std::string **next_token);
void ParseRound(const std::vector<std::string> &node_names,
const std::string **next_token);
void ParseReplaceIndex(const std::vector<std::string> &node_names,
const std::string **next_token);
// Used inside NormalizeAppend(). Return the number of terms there
// would be in a single consolidated Append() expressions, and asserts that in
// whichever branch of any other expressions we take, the number of terms is
// the same.
int32 NumAppendTerms() const;
// Used inside NormalizeAppend(). Gets one of the appended terms from this
// descriptor, with 0 <= term < NumAppendTerms(). Answer is newly allocated.
GeneralDescriptor *GetAppendTerm(int32 term) const;
// Normalizes w.r.t. Append expressions by moving Append() to the outside.
// Called only at the top level.
GeneralDescriptor *NormalizeAppend() const;
// This call does all other types of normalization except for normalizing
// Append() expressions (which is assumed to have been done already). Returns
// true if anything was changed.
static bool Normalize(GeneralDescriptor *ptr);
SumDescriptor *ConvertToSumDescriptor() const;
ForwardingDescriptor *ConvertToForwardingDescriptor() const;
};
} // namespace nnet3
} // namespace kaldi
#endif
| [
"ly_apple_2008@163.com"
] | ly_apple_2008@163.com |
59ac289351f134ec667d5077222717aaea8e15ad | 225b9a9ce807b669f5da0224b374bbf496d0bc70 | /lg3402.cpp | ec94854b618165b84c6374b974c2163dc6141ae3 | [] | no_license | Kewth/OJStudy | 2ed55f9802d430fc65647d8931c028b974935c03 | 153708467133338a19d5537408750b4732d6a976 | refs/heads/master | 2022-08-15T06:18:48.271942 | 2022-07-25T02:18:20 | 2022-07-25T02:18:20 | 172,679,963 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 786 | cpp | #include <bits/stdc++.h>
inline long long input() { long long res ; scanf("%lld",&res); return res; }
int find(int x,int *fa)
{
if(fa[x] == x) return x;
return find(fa[x] , fa);
}
inline void add(int x,int y,int *fa,int *deep)
{
x = find(x , fa);
y = find(y , fa);
if(deep[x] < deep[y])
fa[x] = y;
else
fa[y] = x;
if(deep[x] == deep[y])
deep[x] ++;
}
bool together(int x,int y,int *fa)
{
x = find(x , fa);
y = find(y , fa);
return x == y;
}
int main()
{
int n = input() , q = input();
int *fa = new int [n + 1];
int *deep = new int [n + 1];
for(int i=1;i<=n;i++)
fa[i] = i ,
deep[i] = 1;
while(q --)
{
int typ = input() , x = input() , y = input();
if(typ == 1)
add(x , y , fa , deep);
else
together(x , y , fa) ? puts("Y") : puts("N");
}
}
| [
"wthdsg@foxmail.com"
] | wthdsg@foxmail.com |
16fba564cabd85a3f50fedaafec5b7e5d85d48f1 | 22153e138bb70e4ec27f121882971bdd28df3444 | /src/HuffyBool.cpp | 6b6a62d9fa927c0be9854ef0dd27b5c290f51c17 | [] | no_license | AndyKelly/Huffy | f9486fa097276ee253711743cbe5c19002d0eb4d | 0c67f012fe69edb03cb0377ec6666b7174ca21ac | refs/heads/master | 2021-01-01T16:55:19.200574 | 2013-01-14T08:07:01 | 2013-01-14T08:07:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,725 | cpp | /*
* HuffyBool.cpp
*
* Author: Andy Kelly
*/
#include "HuffyBool.h"
#include "HuffyConstants.h"
#include "HuffyManager.h"
using namespace std;
HuffyBool::HuffyBool(void)
{
m_Value = 0;
}
HuffyBool::HuffyBool(bool Value)
{
m_Value = Value;
}
HuffyBool::HuffyBool(bool Value, string UniqueID)
{
m_Value = Value;
m_Sendable = true;
m_UniqueID = UniqueID;
HuffyManager::RegisterHuffyTypeObject(m_UniqueID, this);
}
HuffyBool::~HuffyBool(void)
{
HuffyManager::RemoveType(m_UniqueID, e_HuffyBool);
}
int HuffyBool::GetType(void)const
{
return e_HuffyBool;
}
void HuffyBool::SetValue(bool NewValue)
{
UpdateHuffyManagaer();
m_Value = NewValue;
}
//Gets
std::string HuffyBool::GetID(void)
{
return m_UniqueID;
}
bool HuffyBool::GetValue_C(void)const
{
return m_Value;
}
bool HuffyBool::GetValue(void)
{
return m_Value;
}
bool HuffyBool::isBeingSent()
{
return m_Sendable;
}
void HuffyBool::UpdateHuffyManagaer()
{
if(m_Sendable)
{
HuffyManager::HuffyTypeModified(e_HuffyBool, m_UniqueID);
}
}
//Operator overloads
#pragma region HuffyBoolOverloads
HuffyBool HuffyBool::operator=(const HuffyBool& other)
{
UpdateHuffyManagaer();
m_Value = other.m_Value;
return *this;
}
bool HuffyBool::operator==(const HuffyBool& other)
{
return m_Value == other.m_Value;
}
bool HuffyBool::operator!=(const HuffyBool& other)
{
return m_Value != other.m_Value;
}
#pragma endregion
#pragma region BoolOverloads
HuffyBool HuffyBool::operator=(const bool& other)
{
UpdateHuffyManagaer();
m_Value = other;
return *this;
}
bool HuffyBool::operator==(const bool& other)
{
return m_Value == other;
}
bool HuffyBool::operator!=(const bool& other)
{
return m_Value != other;
}
#pragma endregion
| [
"andykelly@outlook.com"
] | andykelly@outlook.com |
cb1164868c280c40ce464048f09bf6512ff8cc4f | f0c9b902901b2e70c004e24e07f6a30defa9f84a | /src/World/World.cpp | 5fbfc72ecbbc1b0e65be701737d399b6e4bf1c1e | [] | no_license | lorenzofman/ComputerGraphicsTC | 4f45a19356bec91da523e204e0436f8bf8af568e | a79ad136c3b26db212869b02561c18437ab11b3b | refs/heads/master | 2022-06-02T14:55:18.850485 | 2020-05-05T16:52:22 | 2020-05-05T16:52:22 | 257,919,061 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 844 | cpp | #include "World.h"
World::World()
{
EventSystem::UpdateCallback.Register([this] {this->OnUpdate(); });
EventSystem::KeyDownCallback.Register([this] (int key) {this->OnKeyDown(key); });
bezier = new BezierCurve();
}
void World::OnUpdate()
{
Canvas2D::ClearScreen(Colors::Background);
bezier->Render();
DisplayFramesPerSeconds();
}
void World::DisplayFramesPerSeconds()
{
int fps = (int) (1.0 / EventSystem::LastFrameDuration);
char* str = new char[11];
sprintf(str, "%i", fps);
Canvas2D::DrawText(Float2::Zero, str);
}
void World::OnKeyDown(int key)
{
switch (key)
{
case ' ':
{
bezier->StartAnimation();
break;
}
case 'c':
{
bezier->SetDrawConstructionGraph();
break;
}
case 'f':
{
bezier->SetDrawBlendingFunctions();
break;
}
case 'g':
{
bezier->SetDrawControlGraph();
break;
}
default: break;
}
}
| [
"lorenzofman@gmail.com"
] | lorenzofman@gmail.com |
d26dd617bf6912fea72dde546fbc6ceb92c4a240 | 2ca167503b276a48f232c9c179ec43f2214194e9 | /InvokeTarget1/src/main.cpp | d64df089e13d910663e0e025199451796302ce87 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | ProLove365/Cascades-Community-Samples | 6f3f81bfdc61ec57b4d0218d2c1ed5b2f59ee53c | 4d723d37e5bf61df13a8fa7740acbdd1e422d230 | refs/heads/master | 2020-12-25T12:40:02.333653 | 2012-10-24T09:42:53 | 2012-10-24T09:42:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,467 | cpp | /* Copyright (c) 2012 Research In Motion Limited.
*
* 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 "app.hpp"
#include <bb/cascades/Application>
#include <QLocale>
#include <QTranslator>
using ::bb::cascades::Application;
int main(int argc, char **argv)
{
//-- this is where the server is started etc
Application app(argc, argv);
//-- localization support
QTranslator translator;
QString locale_string = QLocale().name();
QString filename = QString( "InvokeTarget_%1" ).arg( locale_string );
if (translator.load(filename, "app/native/qm")) {
app.installTranslator( &translator );
}
App mainApp;
//-- we complete the transaction started in the app constructor and start the client event loop here
return Application::exec();
//-- when loop is exited the Application deletes the scene which deletes all its children (per qt rules for children)
}
| [
"shaque@rim.com"
] | shaque@rim.com |
33bf8fa0e925509c71891a6eeb87339bcf66a4fc | 839aa2696f888cbe966f94614e11d8962cc27c74 | /utils/cpp/point_score.cpp | a535b6d27bebc000b921c32a0563220908743913 | [] | no_license | jiehanzheng/rpi_intercom | dfb254ecd42b12252c099ad036691982f1073931 | 5ec9109504f78afc8b30c26cc83d518a91967dc5 | refs/heads/master | 2016-09-08T01:29:46.455086 | 2013-02-22T06:48:06 | 2013-02-22T06:48:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 468 | cpp | #include <math.h>
score_info point_score(double x1, double y1, double x2, double y2) {
double dx = std::abs(x1-x2);
double y_ratio = y1/y2;
double y_margin = pow(std::max(y1,y2),2.2)/1000000;
double x_comp = pow((0.015*dx),4);
double y_comp = pow(std::max((double)0,abs(y_ratio-1)-y_margin),(double)5);
double point_weight = y_margin+1;
score_info result = {(1/(x_comp+y_comp+1))*point_weight,
point_weight};
return result;
}
| [
"zheng@jiehan.org"
] | zheng@jiehan.org |
e4592f4e8d5aae51a2be0ce2fa1da93e289dbf24 | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/AggregateRedundancyComponent/UNIX_AggregateRedundancyComponent_LINUX.hxx | 5d385a4adc902a9e9a28dbb4cd8fe37a866e560c | [
"MIT"
] | permissive | brunolauze/openpegasus-providers | 3244b76d075bc66a77e4ed135893437a66dd769f | f24c56acab2c4c210a8d165bb499cd1b3a12f222 | refs/heads/master | 2020-04-17T04:27:14.970917 | 2015-01-04T22:08:09 | 2015-01-04T22:08:09 | 19,707,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,841 | hxx | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#ifdef PEGASUS_OS_LINUX
#ifndef __UNIX_AGGREGATEREDUNDANCYCOMPONENT_PRIVATE_H
#define __UNIX_AGGREGATEREDUNDANCYCOMPONENT_PRIVATE_H
#endif
#endif
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
dc9ec1a25d7ab88f46d6e38fb016c6bbdfad80a8 | f7458f81055c5458ae619b8e5469e3e018f05b1f | /IO/SegY/vtkSegY3DReader.h | 06534530974e3bafbbc9996ef0a845280bb51710 | [
"BSD-3-Clause"
] | permissive | CDAT/VTK | f4e2d5920533eee2009044cff99d722290d14870 | 840dcb68621a8aeef2b49be4a3ba64c9f5061987 | refs/heads/uvcdat-master | 2022-04-07T07:13:44.287885 | 2017-08-18T16:25:07 | 2017-08-18T16:25:07 | 13,934,856 | 0 | 0 | NOASSERTION | 2020-02-28T07:53:21 | 2013-10-28T18:37:31 | C++ | UTF-8 | C++ | false | false | 1,504 | h | /*=========================================================================
Program: Visualization Toolkit
Module: vtkSegY3DReader.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#ifndef vtkSegY3DReader_h
#define vtkSegY3DReader_h
#include "vtkImageAlgorithm.h"
#include "vtkSegYReader.h" // For reader implementation
#include "vtkSmartPointer.h" // For smart pointer
#include <vtkIOSegYModule.h> // For export macro
// Forward declarations
class vtkImageData;
class VTKIOSEGY_EXPORT vtkSegY3DReader : public vtkImageAlgorithm
{
public:
static vtkSegY3DReader* New();
vtkTypeMacro(vtkSegY3DReader, vtkImageAlgorithm);
void PrintSelf(ostream& os, vtkIndent indent) VTK_OVERRIDE;
vtkSetStringMacro(FileName);
vtkGetStringMacro(FileName);
virtual vtkImageData* GetImage();
protected:
vtkSegY3DReader();
~vtkSegY3DReader();
char* FileName;
vtkSegYReader reader;
vtkSmartPointer<vtkImageData> image;
private:
vtkSegY3DReader(const vtkSegY3DReader&) VTK_DELETE_FUNCTION;
void operator=(const vtkSegY3DReader&) VTK_DELETE_FUNCTION;
};
#endif // vtkSegY3DReader_h
| [
"sankhesh.jhaveri@kitware.com"
] | sankhesh.jhaveri@kitware.com |
af588588282fb1ecdd9a6712a6fddb4e09f06a95 | 41a08c02f23996fb2d7aeb78764443a63eed15eb | /greeting_10_24.cc | 0bc1a58321df6799de73730a8fece1d150d74b06 | [] | no_license | kmad1729/acpp | b28407ab007d18126601c03a05e4386bc1ed470a | 7a933fbfa714c4459cff53d3fe364759118beb12 | refs/heads/master | 2020-04-29T02:18:11.154932 | 2014-01-05T18:45:27 | 2014-01-05T18:45:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 918 | cc | #include<iostream>
#include<string>
using std::cout; using std::cin;
using std::string; using std::endl;
int main()
{
cout << "Please enter your first name: ";
string name;
cin >> name;
const string greeting = "Hi, " + name + "! How are you";
const int pad = 5;
const int rows = 2 * pad + 3;
string::size_type cols = greeting.size() + 2 * pad + 2;
string::size_type c = 0;
for(int r = 0; r < rows; r++) {
for (c = 0; c < cols; c++) {
//if edge of the square, print *
if (r == 0 || r == rows - 1 || c == 0 || c == cols - 1) {
cout << "*";
} else {
//if time to write the greeting
if (r == pad + 1 && c == pad + 1) {
cout << greeting;
c += greeting.size();
}
cout << " ";
}
}
cout << endl;
}
}
| [
"kashyap.mad@gmail.com"
] | kashyap.mad@gmail.com |
02b5584684acbb23a3b18f28881499a34f68303a | 1dae79fb96f0dbbd03104eac106285e1aef88197 | /TI/Lab_2/UnitIDEA.h | a261e0fc89b5b2629e1f36f9345591e9effe2512 | [
"Apache-2.0"
] | permissive | ilyacoding/bsuir | 781e8f126d1f7d2db402b9d8083d1f4bcdcc6f4e | c1a09b63d5d66a3dc0f4545589608a18d1b5d9c9 | refs/heads/master | 2021-05-15T04:23:26.430221 | 2019-05-29T04:06:12 | 2019-05-29T04:06:12 | 75,403,020 | 0 | 0 | Apache-2.0 | 2021-04-21T19:34:52 | 2016-12-02T14:35:01 | Objective-C | UTF-8 | C++ | false | false | 1,903 | h | //---------------------------------------------------------------------------
#ifndef UnitIDEAH
#define UnitIDEAH
//---------------------------------------------------------------------------
#include <System.Classes.hpp>
#include <Vcl.Controls.hpp>
#include <Vcl.StdCtrls.hpp>
#include <Vcl.Forms.hpp>
#include <Vcl.WinXCtrls.hpp>
#include <Vcl.ComCtrls.hpp>
#include <Vcl.ToolWin.hpp>
#include <Vcl.Menus.hpp>
#include <Vcl.Dialogs.hpp>
#include <Vcl.Samples.Spin.hpp>
//---------------------------------------------------------------------------
class TFormIDEA : public TForm
{
__published: // IDE-managed Components
TMemo *MemoEncKey;
TMemo *MemoEncBlock;
TMemo *MemoDecKey;
TMemo *MemoDecBlock;
TMainMenu *MainMenu1;
TMenuItem *N3;
TMenuItem *File1;
TMenuItem *About1;
TMenuItem *N1;
TMenuItem *Create1;
TMenuItem *Load1;
TMenuItem *Select1;
TMenuItem *N4;
TMenuItem *N2;
TMenuItem *N5;
TEdit *EditKeyID;
TLabel *LabelKey;
TLabel *LabelKeyID;
TToggleSwitch *ToggleSwitchKey;
TOpenDialog *OpenDialogFile;
TButton *ButtonSelectFile;
TLabel *LabelFileName;
TButton *ButtonEncrypt;
TButton *ButtonDecrypt;
TLabel *LabelNameExpKey;
TLabel *LabelNameInvKey;
TLabel *LabelEncBlock;
TLabel *LabelDecBlock;
void __fastcall FormCreate(TObject *Sender);
void __fastcall Create1Click(TObject *Sender);
void __fastcall EditKeyIDChange(TObject *Sender);
void __fastcall ToggleSwitchKeyClick(TObject *Sender);
void __fastcall ButtonSelectFileClick(TObject *Sender);
void __fastcall ButtonEncryptClick(TObject *Sender);
void __fastcall ButtonDecryptClick(TObject *Sender);
private: // User declarations
public: // User declarations
__fastcall TFormIDEA(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TFormIDEA *FormIDEA;
//---------------------------------------------------------------------------
#endif
| [
"ilyacoding@yandex.com"
] | ilyacoding@yandex.com |
03e3044cae601707e8a4950b6517b30fbd989931 | 35fbe1678a2b52fed50c754e5e2fbe2f39ef44d6 | /windows/runner/main.cpp | 07c35159228a2d7b11a679857dddec9603250d47 | [] | no_license | deorwine/desktop-applications-with-flutter | 2ae1d5f006800a01cd6b0385fd68ff0c51741498 | ccc81e797b5ef1fb521959bc691d9e624639ca60 | refs/heads/master | 2023-06-20T11:44:14.246979 | 2021-07-23T06:58:22 | 2021-07-23T06:58:22 | 388,004,891 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,257 | cpp | #include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>
#include "flutter_window.h"
#include "run_loop.h"
#include "utils.h"
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
_In_ wchar_t *command_line, _In_ int show_command) {
// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
CreateAndAttachConsole();
}
// Initialize COM, so that it is available for use in the library and/or
// plugins.
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
RunLoop run_loop;
flutter::DartProject project(L"data");
std::vector<std::string> command_line_arguments =
GetCommandLineArguments();
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
FlutterWindow window(&run_loop, project);
Win32Window::Point origin(10, 10);
Win32Window::Size size(1280, 720);
if (!window.CreateAndShow(L"Paras", origin, size)) {
return EXIT_FAILURE;
}
window.SetQuitOnClose(true);
run_loop.Run();
::CoUninitialize();
return EXIT_SUCCESS;
}
| [
"paras.laxkar@deorwine.com"
] | paras.laxkar@deorwine.com |
f2e39736ddeea4453e1404016a9c9cb0be23245c | a78390c58814a59998f330adab061c7f7678725e | /sources/srm/src/include/BaseSRF.h | 3a832bfd854636bfc0b240eaa58f27142c155e1c | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | Geo4Win/sedris-dynamic | d632c3c496bdd111b8cb27d69de359cd7cc7c420 | cfb3b2f1605221bb1cfd86c8315ff0ca740767b8 | refs/heads/master | 2021-07-06T16:47:05.668696 | 2017-10-02T04:55:03 | 2017-10-02T04:55:03 | 105,417,233 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 61,355 | h | /** @file BaseSRF.h
@author Warren Macchi, David Shen
@brief Declaration of SRF base classes and includes of concrete SRF classes.
*/
// SRM SDK Release 4.1.4 - July 1, 2011
// - SRM spec. 4.1
/*
* NOTICE
*
* This software is provided openly and freely for use in representing and
* interchanging environmental data & databases.
*
* This software was developed for use by the United States Government with
* unlimited rights. The software was developed under contract
* DASG60-02-D-0006 TO-193 by Science Applications International Corporation.
* The software is unclassified and is deemed as Distribution A, approved
* for Public Release.
*
* Use by others is permitted only upon the ACCEPTANCE OF THE TERMS AND
* CONDITIONS, AS STIPULATED UNDER THE FOLLOWING PROVISIONS:
*
* 1. Recipient may make unlimited copies of this software and give
* copies to other persons or entities as long as the copies contain
* this NOTICE, and as long as the same copyright notices that
* appear on, or in, this software remain.
*
* 2. Trademarks. All trademarks belong to their respective trademark
* holders. Third-Party applications/software/information are
* copyrighted by their respective owners.
*
* 3. Recipient agrees to forfeit all intellectual property and
* ownership rights for any version created from the modification
* or adaptation of this software, including versions created from
* the translation and/or reverse engineering of the software design.
*
* 4. Transfer. Recipient may not sell, rent, lease, or sublicense
* this software. Recipient may, however enable another person
* or entity the rights to use this software, provided that this
* AGREEMENT and NOTICE is furnished along with the software and
* /or software system utilizing this software.
*
* All revisions, modifications, created by the Recipient, to this
* software and/or related technical data shall be forwarded by the
* Recipient to the Government at the following address:
*
* SMDC
* Attention SEDRIS (TO193) TPOC
* P.O. Box 1500
* Huntsville, AL 35807-3801
*
* or via electronic mail to: se-mgmt@sedris.org
*
* 5. No Warranty. This software is being delivered to you AS IS
* and there is no warranty, EXPRESS or IMPLIED, as to its use
* or performance.
*
* The RECIPIENT ASSUMES ALL RISKS, KNOWN AND UNKNOWN, OF USING
* THIS SOFTWARE. The DEVELOPER EXPRESSLY DISCLAIMS, and the
* RECIPIENT WAIVES, ANY and ALL PERFORMANCE OR RESULTS YOU MAY
* OBTAIN BY USING THIS SOFTWARE OR DOCUMENTATION. THERE IS
* NO WARRANTY, EXPRESS OR, IMPLIED, AS TO NON-INFRINGEMENT OF
* THIRD PARTY RIGHTS, MERCHANTABILITY, OR FITNESS FOR ANY
* PARTICULAR PURPOSE. IN NO EVENT WILL THE DEVELOPER, THE
* UNITED STATES GOVERNMENT OR ANYONE ELSE ASSOCIATED WITH THE
* DEVELOPMENT OF THIS SOFTWARE BE HELD LIABLE FOR ANY CONSEQUENTIAL,
* INCIDENTAL OR SPECIAL DAMAGES, INCLUDING ANY LOST PROFITS
* OR LOST SAVINGS WHATSOEVER.
*/
// $Id: BaseSRF.h,v 1.40.1.17 2009-11-05 16:17:06-05 worleym Exp $
/** @mainpage Spatial Reference Model (SRM) C++ API
@section Introduction
This is the documentation for the SRM C++ API.
The SRM classes provide the following functionality:
- Creation
- SRFs
- SRF templates (e.g., LSR 3D, TM, Celestiodetic, Celestiocentric)
- SRF set members (e.g., UTM zone 12, GTRS GCS cell 1234, UPS northern pole)
- SRFs (e.g., British National Grid Airy)
- Coordinates
- 2D coordinate
- 3D coordinate
- Surface coordinate
- Directions
- Orientations
- Conversion
- Coordinate conversion between SRFs
- Direction conversion between SRFs
- Orientation conversion between SRFs
- Validation
- Coordinate validation within a SRF
- Direction validation within a SRF
- Orientation validation within a SRF
- Calculations
- Euclidean distance
- Geodesic distance
- Point scale
- Vertical separation offset
- Convergence of the Meridian
- Map azimuth
A sample program to convert a Celestiodetic 3D coordinate to
a Celestiocentric 3D coordinate is as follows:
@code
#include "BaseSRF.h"
#include "srf_all.h"
#include "Exception.h"
#include <iostream>
using namespace std;
int main (int argc, char* argv[])
{
cout << "Running SRM Sample test program... \n" << endl;
srm::SRF_Celestiocentric* CC_SRF;
srm::SRF_Celestiodetic* CD_SRF;
try {
// create CC and CD SRFs
CC_SRF = srm::SRF_Celestiocentric::create( SRM_ORMCOD_WGS_1984, SRM_RTCOD_WGS_1984_IDENTITY );
CD_SRF = srm::SRF_Celestiodetic::create( SRM_ORMCOD_WGS_1984, SRM_RTCOD_WGS_1984_IDENTITY );
cout << "Source Celestiodetic SRF parameters: " << endl;
cout << CD_SRF->toString() << endl;
cout << "Target Celestiocentric SRF parameters: " << endl;
cout << CC_SRF->toString() << endl;
} catch ( srm::Exception( ex) ) {
cout << "Caught an exception=> " << ex.getWhat() << endl;
return 0;
}
// create CD and CC 3D coordinate
srm::Coord3D_Celestiodetic CD_Coord( CD_SRF, 0.0, 0.785398163397, 0.0 );
srm::Coord3D_Celestiocentric CC_Coord( CC_SRF );
// Convert from CD SRF to CC SRF
try {
CC_SRF->changeCoordinate3DSRF( CD_Coord, CC_Coord );
cout << "Executed changeCoordinate3DSRF" << endl;
}
catch ( srm::Exception& ex) {
cout << "Caught an exception=> " << ex.getWhat() << endl;
return 0;
}
// Print Celestiocentric coordinate values
cout << "Source Celestiodetic 3D coordinate: "
<< "[ " << CD_Coord.get_longitude() << ", " << CD_Coord.get_latitude()
<< ", " << CD_Coord.get_ellipsoidal_height() << " ]" << endl;
cout << "Target (converted) Celestiocentric 3D coordinate: "
<< "[ " << CC_Coord.get_u() << ", " << CC_Coord.get_v()
<< ", " << CC_Coord.get_w() << " ]" << endl << endl;
// Free SRFs
CC_SRF->release();
cout << "Released CC SRF" << endl;
CD_SRF->release();
cout << "Released CD SRF" << endl;
return 0;
}
@endcode
Running the sample program above will produce output as follows:
@verbatim
Running SRM Sample test program...
Source Celestiodetic SRF parameters:
orm=> 250
rt=> 341
Target Celestiocentric SRF parameters:
orm=> 250
rt=> 341
Executed changeCoordinate3DSRF
Source Celestiodetic 3D coordinate: [ 0, 0.785398, 0 ]
Target (converted) Celestiocentric 3D coordinate: [ 4.51759e+06, -8.24624e-08, 4.48735e+06 ]
Released CC SRF
Released CD SRF
@endverbatim
*/
#ifndef _BaseSRF_h
#define _BaseSRF_h
#if !defined(_WIN32)
#define EXPORT_SRM_CPP_DLL
#elif defined(BUILD_SRM_CPP) /* SRM CPP Case */
#if !defined(EXPORT_SRM_CPP_DLL)
#if defined(_LIB)
#define EXPORT_SRM_CPP_DLL
#elif defined(_USRDLL)
#define EXPORT_SRM_CPP_DLL __declspec(dllexport)
#else
#define EXPORT_SRM_CPP_DLL __declspec(dllimport)
#endif
#endif
#else /* SRM C Case */
#define EXPORT_SRM_CPP_DLL
#endif /* _WIN32 && EXPORT_DLL */
#include "srm_types.h"
// global variable - controls whether SRF cache is used to speed
// up coordinate conversion operations
extern bool g_fast_mode;
namespace srm
{
/// Forward referencing
class Coord;
class Coord2D;
class CoordSurf;
class Coord3D;
class Direction;
class Orientation;
class SRF_LocalTangentSpaceEuclidean;
/// Type for an array of two long float numbers
typedef SRM_Long_Float SRM_Vector_2D[2];
typedef SRM_Vector_2D Vector2;
typedef SRM_Vector_3D Vector3;
typedef SRM_Matrix_3x3 Matrix3x3;
/** The BaseSRF abstract class is the base class for all SRFs.
SRFs are allocated by the API, and when no longer needed they should be
released by calling the release() method.
@author Warren Macchi, David Shen
@see BaseSRF_2D, BaseSRF_3D
*/
class EXPORT_SRM_CPP_DLL BaseSRF
{
public:
/// The type of an SRF
enum SRF_ClassType
{
SRF_TYP_TWO_D,
SRF_TYP_THREE_D,
SRF_TYP_WITH_TANGENT_PLANE_SURFACE,
SRF_TYP_WITH_ELLIPSOIDAL_HEIGHT,
SRF_TYP_MAP_PROJECTION,
SRF_TYP_LSA,
SRF_TYP_CC,
SRF_TYP_CD,
SRF_TYP_CM,
SRF_TYP_EC,
SRF_TYP_EI,
SRF_TYP_HAEC,
SRF_TYP_HEEC,
SRF_TYP_HEEQ,
SRF_TYP_LCC,
SRF_TYP_LCE_3D,
SRF_TYP_LSR_2D,
SRF_TYP_LSR_3D,
SRF_TYP_LTSAS,
SRF_TYP_LTSC,
SRF_TYP_LTSE,
SRF_TYP_M,
SRF_TYP_OMS,
SRF_TYP_PD,
SRF_TYP_LSP,
SRF_TYP_PS,
SRF_TYP_SEC,
SRF_TYP_SEQ,
SRF_TYP_SME,
SRF_TYP_SMD,
SRF_TYP_TM
};
/** Creates a Standard SRF from its SRF code.
@note
An SRF can be directly created from: <ol>
<li>an SRF code and an RT code for a standard SRF (see createStandardSRF()),</li>
<li>an SRF set code info and an RT code (see createSRFSetMember()), or</li>
<li>a concrete template-based SRF class (see the concrete SRF classes).</li>
</ol>
@note The returned SRF should be freed by calling its release()
method.
@param srf_code in: the code for a standard SRF to create
@param rt_code in: the RT code to use in the created SRF
@return a pointer to an SRF if successful
@exception This method throws srm::Exception
*/
static BaseSRF *createStandardSRF( SRM_SRF_Code srf_code,
SRM_RT_Code rt_code );
/** Creates an SRF from a SRF set code, a set member code specific to
that set, and an ORM code.
@note
An SRF can be directly created from: <ol>
<li>an SRF code and an RT code for a standard SRF (see createStandardSRF()),</li>
<li>an SRF set code info and an RT code (see createSRFSetMember()), or</li>
<li>a concrete template-based SRF class (see the concrete SRF classes).</li>
</ol>
@note The returned SRF should be freed by calling its release()
method.
@param srfs_info in: the set code, member code and orm code.
@param rt in: the RT code to use in the created SRF
@return a pointer to an SRF set member if successful
@exception This method throws srm::Exception
*/
static BaseSRF *createSRFSetMember( SRM_SRFS_Info srfs_info,
SRM_RT_Code rt );
/** Releases the pointer to the SRF.
SRF classes are reference counted, since coordinates maintain a
reference to them. When all references to an SRF are released, the
SRF's memory is deleted.
@note If you need to store multiple pointers to an SRF, you should
use the clone() method to obtain each pointer, and then call
the release() method for each pointer when they are no longer
needed.
@exception This method throws srm::Exception
@see clone()
*/
virtual void release();
/** Returns the codes that identify this class.
An SRF can be directly created from: <ol>
<li>an SRF code for a standard SRF (see createStandardSRF()),</li>
<li>an SRF set code and a set member code (see createSRFSetMember()), or</li>
<li>a concrete template-based SRF class (see the concrete SRF classes).</li>
</ol>
All SRFs are intrinsically created from a template, hence the
appropriate template code will always be returned from this method.
However, if the SRF was created by either of 1) or 2) above, then
this method allows you to retrieve the codes used to create it.
If a code is not applicable, its value will be set to 0.
@param t_code out: the SRF Template code
@param srf_code out: the standard SRF code. It returns SRM_SRFCOD_UNSPECIFIED (0) if not
created using a Standard SRF Code
@param srfs_code_info out: the SRF Set and its Member code. It returns SRM_SRFSCOD_UNSPECIFIED (0)
if not created using a SRFS Code
*/
virtual void getCodes( SRM_SRFT_Code &t_code,
SRM_SRF_Code &srf_code,
SRM_SRFS_Code_Info &srfs_code_info ) const;
/** Returns the CS code.
@return a CS code
*/
virtual SRM_CS_Code getCSCode() const;
/** Returns this SRF's Object Reference Model code.
@return an ORM code
@note This method is deprecated. Use getOrm() method.
*/
virtual SRM_ORM_Code get_orm() const;
/** Returns this SRF's Object Reference Model code.
@return an ORM code
*/
virtual SRM_ORM_Code getOrm() const;
/** Returns this SRF's RT code.
@return an RT code
@note This method is deprecated. Use getRt() method.
*/
virtual SRM_RT_Code get_rt() const;
/** Returns this SRF's RT code.
@return an RT code
*/
virtual SRM_RT_Code getRt() const;
/** Returns this SRF's major semi-axis value (a).
@return a major semi-axis value
*/
virtual SRM_Long_Float getA() const;
/** Returns this SRF's flattening value (f).
@return a flattening value
*/
virtual SRM_Long_Float getF() const;
/** Queries for the SRFT support by the implementation.
@param srft_code in: the SRF Template code.
@return true if the SRFT is supported by this implementation.
@exception This method throws srm::Exception
*/
static bool querySRFTSupport( SRM_SRFT_Code srft_code );
/** Queries for the ORM/RT pair support by the implementation.
@param orm_code in: the object reference model code.
@param rt_code in: the reference transformation code.
@return true if the ORM/RT pair is supported by this implementation.
@exception This method throws srm::Exception
@note Not all the supported SRFTs is compatible with all the supported ORM/RT pairs.
*/
static bool queryORMSupport( SRM_ORM_Code orm_code,
SRM_RT_Code rt_code );
/** Returns the class type of this SRF instance.
You can use the return value of this method to cast a pointer to
an SRF to its concrete template-based class.
@return an SRF template code
*/
virtual SRF_ClassType getClassType() const = 0;
/** Returns true if this SRF is of the given class type
*/
virtual bool isA( SRF_ClassType type ) const;
/** Changes a coordinate's values to this SRF.
@note The destination coordinate must have been created using this SRF.
@param src_coord in: the source coordinate in some other SRF
@param des_coord out: the destination coordinate in this SRF
@return validity code for the destination coordinate
@exception This method throws srm::Exception
@note The source and destination coordinatesmust be of the same base coordinate
class. They have to be both Coord3D, Coord2D, or CoordSurf.
@note The conversion from one surface coordinate to another is a convenience
function equivalent to promoting the source surface coordinate to a 3D coordinate,
performing the conversion, then deriving the destination surface coordinate
from the resulting destination 3D coordinate.
*/
virtual SRM_Coordinate_Valid_Region changeCoordinateSRF( const Coord &src_coord, Coord &des_coord );
/** Checks a coordinate in this SRF for valid region.
@param src in: the coodinate in this SRF
@return validity code for the coordinate
@exception This method throws srm::Exception
*/
virtual SRM_Coordinate_Valid_Region checkCoordinate( const Coord &src );
/** Frees a coordinate in this SRF.
@exception This method throws srm::Exception
*/
virtual void freeCoordinate( Coord *coord );
/** Returns the euclidean distance (in metres) between two coordinates.
@exception This method throws srm::Exception
@note The input coordinates must be of the same dimension.
@note The input coordinates can be created from any SRF.
*/
static SRM_Long_Float calculateEuclideanDistance( const Coord &coord1,
const Coord &coord2 );
/** Sets the coordinate validation ON for the changeCoordinateSRF method
@note The coordinate validation is ON by default.
@note Users should not set the validation OFF unless the coordinates are known to be ALWAYS valid.
*/
void setCoordinateValidationOn();
/** Sets the coordinate validation OFF for the changeCoordinateSRF method
@note The coordinate validation is ON by default.
@note Users should not set the validation OFF unless the coordinates are known to be ALWAYS valid.
*/
void setCoordinateValidationOff();
/** Returns true is the coordinate validation is ON
*/
bool coordinateValidationIsOn();
/** Returns a string representation of this SRF.
*/
virtual const char *toString() = 0;
/** Returns a new reference to this SRF.
@see release()
@return a new pointer to this SRF
*/
virtual BaseSRF *clone();
/** Returns the creation identifier of this SRF.
@return the id
*/
SRM_Integer getId() const
{
return _id;
}
protected:
friend class Coord3D;
friend class BaseSRF_3D;
friend class BaseSRF_2D;
friend class BaseSRF_MapProjection;
friend class BaseSRF_WithEllipsoidalHeight;
friend class BaseSRF_WithTangentPlaneSurface;
BaseSRF( void *impl ); ///< No stack allocation
BaseSRF &operator =( const BaseSRF & ) { return *this; } ///< No copy constructor
virtual ~BaseSRF() {} ///< Use release()
/// Reference counting
unsigned int _ref_cnt;
/// ID for SRF creation identification
SRM_Integer _id;
/// Implementation data
void *_impl, *_cache;
bool _validate_coords;
void *getImpl() const { return _impl; }
};
inline BaseSRF *BaseSRF::clone()
{
++_ref_cnt;
return this;
}
inline bool BaseSRF::isA( SRF_ClassType type ) const
{
return false;
}
/** The BaseSRF_2D abstract class is the base class for the 2D SRFs.
SRFs are allocated by the API, and when no longer needed they should be
released by calling the release() method.
@author Warren Macchi, David Shen
@see BaseSRF, BaseSRF_3D
*/
class EXPORT_SRM_CPP_DLL BaseSRF_2D : public BaseSRF
{
public:
/** Returns true if this SRF is of the given class type
*/
virtual bool isA( SRF_ClassType type ) const;
/** Creates a 2D coordinate object.
@see freeCoordinate2D()
@return a 2D coordinate object
*/
virtual Coord2D *createCoordinate2D( SRM_Long_Float coord_comp1,
SRM_Long_Float coord_comp2 ) = 0;
/** Retrieves the 2D coordinate component values.
@exception This method throws srm::Exception
*/
virtual void getCoordinate2DValues( const Coord2D &coord,
SRM_Long_Float &coord_comp1,
SRM_Long_Float &coord_comp2 ) const;
/** Frees a 2D coordinate object.
@exception This method throws srm::Exception
*/
virtual void freeCoordinate2D( Coord2D *coord );
/** Changes a coordinate's values to this SRF.
@note The destination coordinate must have been created using this SRF.
@param src_coord in: the source coordinate in some other SRF
@param des_coord out: the destination coordinate in this SRF
@exception This method throws srm::Exception
*/
virtual void changeCoordinate2DSRF( const Coord2D &src_coord,
Coord2D &des_coord );
/** Changes an array of coordinate values to this SRF.
@note The destination coordinates must have been created using this SRF.
@note The source and destination arrays must be of same size.
@note All the coordinates in an array must be associated with the same SRF.
@note When an exception is raised, the index parameter is set to the offending coordinate.
@param src_coord_array in: the array of source coordinates in some other SRF
@param index in/out: (in) the array length/ (out) the array index of the offending coordinate
@param des_coord_array out: the array of destination coordinates in this SRF
@exception This method throws srm::Exception
*/
virtual void changeCoordinate2DArraySRF( Coord2D **src_coord_array,
SRM_Integer_Positive *index,
Coord2D **des_coord_array );
/** Changes a coordinate's values to this SRF using tranformation object.
@note The destination coordinate must have been created using this SRF.
@note The value of omega for hst must be within the range ( -2_PI, 2_PI ).
@note The value of delta_s for hst must be strictly greater than -1.0.
@param src_coord in: the source coordinate in some other SRF
@param hst in: the ORM 2D transformation
@param des_coord out: the destination coordinate in this SRF
@exception This method throws srm::Exception
*/
virtual void changeCoordinate2DSRFObject( const Coord2D &src_coord,
const SRM_ORM_Transformation_2D_Parameters hst,
Coord2D &des_coord );
/** Changes an array of coordinate values to this SRF using tranformation object.
@note The destination coordinates must have been created using this SRF.
@note The source and destination arrays must be of same size.
@note All the coordinates in an array must be associated with the same SRF.
@note The value of omega for hst must be within the range ( -2_PI, 2_PI ).
@note The value of delta_s for hst must be strictly greater than -1.0.
@note When an exception is raised, the index parameter is set to the offending coordinate.
@param src_coord_array in: the array of source coordinates in some other SRF
@param hst in: the ORM 2D transformation
@param index in/out: (in) the array length/ (out) the array index of the offending coordinate
@param des_coord_array out: the array of destination coordinates in this SRF
@exception This method throws srm::Exception
*/
virtual void changeCoordinate2DArraySRFObject( Coord2D **src_coord_array,
const SRM_ORM_Transformation_2D_Parameters hst,
SRM_Integer_Positive *index,
Coord2D **des_coord_array );
/** Returns the euclidean distance (in metres) between two 2D coordinates.
@note The input coordinates can be created from any SRF.
@exception This method throws srm::Exception
*/
static SRM_Long_Float calculateEuclideanDistance( const Coord2D &coord1,
const Coord2D &coord2 );
protected:
BaseSRF_2D( void *impl ) : BaseSRF(impl) {} ///< No stack allocation
BaseSRF_2D &operator =( const BaseSRF_2D & ) { return *this; } ///< No copy constructor
virtual ~BaseSRF_2D() {} ///< Use release()
};
inline bool BaseSRF_2D::isA( SRF_ClassType type ) const
{
if (type == BaseSRF::SRF_TYP_TWO_D)
return true;
else
return BaseSRF::isA(type);
}
/** The BaseSRF_3D abstract class is the base class for the 3D SRFs.
SRFs are allocated by the API, and when no longer needed they should be
released by calling the release() method.
@author Warren Macchi, David Shen
@see BaseSRF, BaseSRF_2D
*/
class EXPORT_SRM_CPP_DLL BaseSRF_3D : public BaseSRF
{
public:
/** Returns true if this SRF is of the given class type
*/
virtual bool isA( SRF_ClassType type ) const;
/** Creates a 3D coordinate object.
@see freeCoordinate3D()
@return a 3D coordinate object
@exception This method throws srm::Exception
*/
virtual Coord3D *createCoordinate3D( SRM_Long_Float coord_comp1,
SRM_Long_Float coord_comp2,
SRM_Long_Float coord_comp3 ) = 0;
/** Frees a 3D coordinate object.
@exception This method throws srm::Exception
*/
virtual void freeCoordinate3D( Coord3D *coord );
/** Retrieves the 3D coordinate component values.
@exception This method throws srm::Exception
*/
virtual void getCoordinate3DValues( const Coord3D &coord,
SRM_Long_Float &coord_comp1,
SRM_Long_Float &coord_comp2,
SRM_Long_Float &coord_comp3 ) const;
/** Changes a coordinate's values to this SRF.
@note The destination coordinate must have been created using this SRF.
@param src_coord in: the source coordinate in some other SRF
@param des_coord in/out: the destination coordinate in this SRF
@return validity code for the destination coordinate
@exception This method throws srm::Exception
*/
virtual SRM_Coordinate_Valid_Region changeCoordinate3DSRF( const Coord3D &src_coord,
Coord3D &des_coord );
/** Changes an array of coordinate values to this SRF using tranformation object.
@note The destination coordinates must have been created using this SRF.
@note The source and destination arrays must be of same size.
@note All the coordinates in an array must be associated with the same SRF.
@note When an exception is raised, the index parameter is set to the offending coordinate.
@param src_coord_array in: the array of source coordinates in some other SRF
@param index in/out: (in) the array length/ (out) the array index of the offending coordinate
@param des_coord_array out: the array of destination coordinate in this SRF
@param region_array out: the array of valid regions associated with the destination coordinate
@exception This method throws srm::Exception
*/
virtual void changeCoordinate3DArraySRF( Coord3D **src_coord_array,
SRM_Integer_Positive *index,
Coord3D **des_coord_array,
SRM_Coordinate_Valid_Region *region_array );
/** Changes a coordinate's values to this SRF using tranformation object.
@note The destination coordinate must have been created using this SRF.
@note The value of omega_1, omega_2 and omega_3 for hst must be within the range ( -2_PI, 2_PI ).
@note The value of delta_s for hst must be strictly greater than -1.0.
@param src_coord in: the source coordinate in some other SRF
@param hst in: the ORM 3D transformation
@param des_coord out: the destination coordinate in this SRF
@return validity code for the destination coordinate
@exception This method throws srm::Exception
*/
virtual SRM_Coordinate_Valid_Region changeCoordinate3DSRFObject( const Coord3D &src_coord,
const SRM_ORM_Transformation_3D_Parameters hst,
Coord3D &des_coord );
/** Changes an array of coordinate values to this SRF using tranformation object.
@note The destination coordinates must have been created using this SRF.
@note The source and destination arrays must be of same size.
@note All the coordinates in an array must be associated with the same SRF.
@note When an exception is raised, the index parameter is set to the offending coordinate.
@param src_coord_array in: the array of source coordinates in some other SRF
@param hst in: the ORM 3D transformation
@param index in/out: (in) the array length/ (out) the array index of the offending coordinate
@param des_coord_array out: the array of destination coordinate in this SRF
@param region_array out: the array of valid regions associated with the destination coordinate
@exception This method throws srm::Exception
*/
virtual void changeCoordinate3DArraySRFObject( Coord3D **src_coord_array,
const SRM_ORM_Transformation_3D_Parameters hst,
SRM_Integer_Positive *index,
Coord3D **des_coord_array,
SRM_Coordinate_Valid_Region *region_array );
/** Set the Valid Region for this SRF.
@note Given a coordinate component, the last invocation of this
method or the setExtendedValidRegion method determines
the valid and extended valid intervals of the coordinate
component values.
@note Upper or Lower value is ignored if the interval is a
semi-interval or unbounded.
@note The Lower value must be strictly less than the Upper value.
@param component in: the coordinate component (1, 2, or 3)
@param type in: the type of interval
@param lower in: the lower value of the interval
@param upper in: the upper value of the interval
@exception This method throws srm::Exception
*/
virtual void setValidRegion( const SRM_Integer component,
const SRM_Interval_Type type,
const SRM_Long_Float lower,
const SRM_Long_Float upper );
/** Set the Extended Valid Region for this SRF.
@note Given a coordinate component, the last invocation of this
method or the setValidRegion method determines
the valid and extended valid intervals of the coordinate
component values.
@note Upper or Lower value is ignored if the interval is a
semi-interval or unbounded.
@note The Lower value must be strictly less than the Upper value.
@note The Extended_Lower value must be strictly greater than the Lower value and
the Extended_Upper value must be strictly smaller than the Lower value.
@param component in: the coordinate component (1, 2, or 3)
@param type in: the type of interval
@param extended_lower in: the extended lower value of the interval
@param lower in: the lower value of the interval
@param upper in: the upper value of the interval
@param extended_upper in: the extended_upper value of the interval
@exception This method throws srm::Exception
*/
virtual void setExtendedValidRegion( const SRM_Integer component,
const SRM_Interval_Type type,
const SRM_Long_Float extended_lower,
const SRM_Long_Float lower,
const SRM_Long_Float upper,
const SRM_Long_Float extended_upper );
/** Get the Valid Region for this SRF.
@note Given a coordinate component, the last invocation of this
method or the setExtendedValidRegion method determines
the valid and extended valid intervals of the coordinate
component values.
@param component in: the coordinate component (1, 2, or 3)
@param type out: the type of interval
@param lower out: the lower value of the interval
@param upper out: the upper value of the interval
@exception This method throws srm::Exception
*/
virtual void getValidRegion( const SRM_Integer component,
SRM_Interval_Type &type,
SRM_Long_Float &lower,
SRM_Long_Float &upper );
/** Get the Extended Valid Region for this SRF.
@note Given a coordinate component, the last invocation of this
method or the setValidRegion method determines
the valid and extended valid intervals of the coordinate
component values.
@param component in: the coordinate component (1, 2, or 3)
@param type out: the type of interval
@param extended_lower out: the extended lower value of the interval
@param lower out: the lower value of the interval
@param upper out: the upper value of the interval
@param extended_upper out: the extended_upper value of the interval
@exception This method throws srm::Exception
*/
virtual void getExtendedValidRegion( const SRM_Integer component,
SRM_Interval_Type &type,
SRM_Long_Float &extended_lower,
SRM_Long_Float &lower,
SRM_Long_Float &upper,
SRM_Long_Float &extended_upper );
/** Creates a direction object.
@return a direction object
@exception This method throws srm::Exception
*/
virtual Direction *createDirection( const Coord3D &ref_coord,
const SRM_Vector_3D vec );
/** Creates a direction object.
@return a direction object
@exception This method throws srm::Exception
*/
virtual Direction *createDirection( const Coord3D &ref_coord,
const SRM_Long_Float vectorComp1,
const SRM_Long_Float vectorComp2,
const SRM_Long_Float vectorComp3 );
/** Creates a direction object.
@return a direction object
@exception This method throws srm::Exception
@note The returned "default" Direction object is intended to be used as the
destination direction for the changeDirectionSRF method. The "default"
reference location values cannot be changed except through that method.
*/
virtual Direction *createDirection();
/** Frees a direction object.
@exception This method throws srm::Exception
*/
virtual void freeDirection( Direction *direction );
/** Retrieves the direction component values.
@exception This method throws srm::Exception
*/
virtual void getDirectionValues( const Direction &direction,
Coord3D &ref_coord,
SRM_Vector_3D vec ) const;
/** Changes a direction's values to this SRF.
@note The destination direction must have been created using this SRF.
@param src_dir in: the source direction in some other SRF
@param des_dir out: the destination direction in this SRF
@return valid region category for the reference location associated with the destination direction
@exception This method throws srm::Exception
*/
virtual SRM_Coordinate_Valid_Region changeDirectionSRF( const Direction &src_dir, Direction &des_dir );
/** Changes a direction's values to this SRF using tranformation object.
@note The destination directions must have been created using this SRF.
@note The source and destination arrays must be of same size.
@note All the directions in an array must be associated with the same SRF.
@note When an exception is raised, the index parameter is set to the offending direction.
@param src_direction_array in: the array of source direction in some other SRF
@param index in/out: (in) the array length/ (out) the array index of the offending direction
@param des_direction_array out: the array of destination direction in this SRF
@param region_array out: the array of valid regions associated with the destination direction
@exception This method throws srm::Exception
*/
void changeDirectionArraySRF( Direction **src_direction_array,
SRM_Integer_Positive *index,
Direction **des_direction_array,
SRM_Coordinate_Valid_Region *region_array );
/** Changes a direction's values to this SRF using tranformation object.
@note The destination direction must have been created using this SRF.
@note The value of omega_1, omega_2 and omega_3 for hst must be within
the range ( -2_PI, 2_PI ).
@note The value of delta_s for hst must be strictly greater than -1.0.
@param src_dir in: the source direction in some other SRF
@param hst in: the ORM 3D transformation
@param des_dir out: the destination direction in this SRF
@return valid region category for the reference location associated
with the destination direction
@exception This method throws srm::Exception
*/
virtual SRM_Coordinate_Valid_Region changeDirectionSRFObject
(
const Direction &src_dir,
const SRM_ORM_Transformation_3D_Parameters hst,
Direction &des_dir
);
/** Changes a direction's values to this SRF using tranformation object.
@note The destination directions must have been created using this SRF.
@note The source and destination arrays must be of same size.
@note All the directions in an array must be associated with the same SRF.
@note The value of omega_1, omega_2 and omega_3 for hst must be within the range ( -2_PI, 2_PI ).
@note The value of delta_s for hst must be strictly greater than -1.0.
@note When an exception is raised, the index parameter is set to the offending direction.
@param src_direction_array in: the array of source direction in some other SRF
@param hst in: the ORM 3D transformation
@param index in/out: (in) the array length/ (out) the array index of
the offending direction
@param des_direction_array out: the array of destination direction in
this SRF
@param region_array out: the array of valid regions associated with the
destination direction
@exception This method throws srm::Exception
*/
void changeDirectionArraySRFObject
(
Direction **src_direction_array,
const SRM_ORM_Transformation_3D_Parameters hst,
SRM_Integer_Positive *index,
Direction **des_direction_array,
SRM_Coordinate_Valid_Region *region_array
);
/** Check a direction in this SRF.
*/
virtual SRM_Coordinate_Valid_Region checkDirection( const Direction &direction );
/** Creates an orientation object.
@param ref_coord in: the reference location for the orientation
@param mat in: the orientation matrix
@return an orientation object
@exception This method throws srm::Exception
*/
virtual Orientation *createOrientation( const Coord3D &ref_coord,
const SRM_Matrix_3x3 mat );
/** Creates an orientation object.
@param ref_coord in: the reference location for the orientation
@param vec1 in: the first component vector for the orientation matrix
@param vec2 in: the second component vector for the orientation matrix
@param vec3 in: the third component vector for the orientation matrix
@return an orientation object
@exception This method throws srm::Exception
*/
virtual Orientation *createOrientation( const Coord3D &ref_coord,
const SRM_Vector_3D vec1,
const SRM_Vector_3D vec2,
const SRM_Vector_3D vec3 );
/** Creates an orientation object.
@param dir1 in: the first component Direction for the orientation matrix
@param dir2 in: the second component Direction for the orientation matrix
@param dir3 in: the third component Direction for the orientation matrix
@return an orientation object
@exception This method throws srm::Exception
@note The reference location must be the same for three input Direction
objects.
*/
virtual Orientation *createOrientation( const Direction &dir1,
const Direction &dir2,
const Direction &dir3 );
/** Creates an orientation object.
@return an orientation object
@exception This method throws srm::Exception
@note The returned "default" Orientation object is intended to be used
as an output argument for the changeOrientationSRF method. The
"default" reference location values cannot be changed except
through that method.
*/
virtual Orientation *createOrientation();
/** Frees an orientation object.
@exception This method throws srm::Exception
*/
virtual void freeOrientation( Orientation *orientation );
/** Retrieves the orientation component values.
@exception This method throws srm::Exception
*/
virtual void getOrientationValues( const Orientation &orientation,
Coord3D &ref_coord,
SRM_Matrix_3x3 mat ) const;
/** Check an orientation in this SRF.
@exception This method throws srm::Exception
*/
virtual SRM_Coordinate_Valid_Region checkOrientation( const Orientation &orientation );
/** Changes an orientation's values to this SRF.
@note The destination orientation must have been created using this SRF.
@param src_orient in: the source orientation in some other SRF
@param des_orient in/out: the destination orientation in this SRF
@return valid region category for the reference location associated
with the destination orientation
@exception This method throws srm::Exception
*/
virtual SRM_Coordinate_Valid_Region changeOrientationSRF
(
const Orientation &src_orient,
Orientation &des_orient
);
/** Instances a 3D source coordinate and orientation into this SRF.
@exception This method throws srm::Exception
*/
virtual void instanceAbstractSpaceCoordinate( const Coord3D &src_coord,
const Orientation &orientation,
Coord3D &des_coord );
/** Computes the natural SRF Set member code (region) where the 3D
coordinate is located in the target SRF Set.
@param src_coord in : the source 3D coordinate in an SRF
@param orm_dst in : the ORM for the destination SRF Set
@param rt_dst in : the RT for the destination SRF Set
@param tgt_srfs in : the destination SRF Set Code
@return the SRF Set Member code for the destination SRF Set
@exception This method throws srm::Exception
*/
static SRM_SRFS_Code_Info getNaturalSRFSetMemberCode(const Coord3D &src_coord,
SRM_ORM_Code orm_dst,
SRM_RT_Code rt_dst,
SRM_SRFS_Code tgt_srfs);
/** Returns the natural SRF Set member instance that the 3D coordinate is
located in the target SRF Set.
@param src_coord in : the source 3D coordinate in an SRF
@param orm_dst in : the ORM for the destination SRF Set
@param rt_dst in : the RT for the destination SRF Set
@param tgt_srfs in : the destination SRF Set Code
@return the SRF Set Member instance for the destination SRF Set
@exception This method throws srm::Exception
*/
static BaseSRF_3D* getNaturalSRFSetMember( Coord3D &src_coord,
SRM_ORM_Code orm_dst,
SRM_RT_Code rt_dst,
SRM_SRFS_Code tgt_srfs);
/** Returns the euclidean distance (in metres) between two 3D coordinates.
@note The input coordinates can be created from any SRF.
@exception This method throws srm::Exception
*/
static SRM_Long_Float calculateEuclideanDistance( const Coord3D &coord1,
const Coord3D &coord2 );
protected:
BaseSRF_3D( void *impl ) : BaseSRF(impl) {} ///< No stack allocation
BaseSRF_3D &operator =( const BaseSRF_3D & ) { return *this; } ///< No copy constructor
virtual ~BaseSRF_3D() {} ///< Use release()
};
inline bool BaseSRF_3D::isA( SRF_ClassType type ) const
{
if (type == BaseSRF::SRF_TYP_THREE_D)
return true;
else
return BaseSRF::isA(type);
}
/** The BaseSRF_WithTangentPlaneSurface abstract class is the base class for
the 3D SRFs with tangent plane surfaces.
SRFs are allocated by the API, and when no longer needed they should be
released by calling the release() method.
@author
@see BaseSRF_3D, BaseSRF
*/
class EXPORT_SRM_CPP_DLL BaseSRF_WithTangentPlaneSurface : public BaseSRF_3D
{
public:
/** Returns true if this SRF is of the given class type
*/
virtual bool isA( SRF_ClassType type ) const;
/** Creates a surface coordinate object.
@exception This method throws srm::Exception
*/
virtual CoordSurf *createSurfaceCoordinate( SRM_Long_Float coord_surf_comp1,
SRM_Long_Float coord_surf_comp2 ) = 0;
/** Retrieves a coordinate surface component values
@exception This method throws srm::Exception
*/
virtual void getSurfaceCoordinateValues( const CoordSurf &coord_surf,
SRM_Long_Float &coord_surf_comp1,
SRM_Long_Float &coord_surf_comp2 ) const;
/** Frees a surface coordinate object.
@exception This method throws srm::Exception
*/
virtual void freeSurfaceCoordinate( CoordSurf *coord_surf );
/** Returns a surface coordinate associated with a 3D coordinate.
@exception This method throws srm::Exception
*/
virtual void getAssociatedSurfaceCoordinate( const Coord3D &coord,
CoordSurf &on_surface_coord );
/** Returns a 3D coordinate representing the same location as specified
by a surface coordinate.
@exception This method throws srm::Exception
*/
virtual void getPromotedSurfaceCoordinate( const CoordSurf &surf_coord,
Coord3D &three_d_coord );
/** Returns the euclidean distance (in metres) between two surface coordinates.
@note The input coordinates can be created from any SRF.
@exception This method throws srm::Exception
*/
static SRM_Long_Float calculateEuclideanDistance( const CoordSurf &coord1,
const CoordSurf &coord2 );
protected:
BaseSRF_WithTangentPlaneSurface( void *impl ) : BaseSRF_3D(impl) {} ///< No stack allocation
BaseSRF_WithTangentPlaneSurface &operator =( const BaseSRF_WithTangentPlaneSurface & ) { return *this; } ///< No copy constructor
virtual ~BaseSRF_WithTangentPlaneSurface() {} ///< Use release()
};
inline bool BaseSRF_WithTangentPlaneSurface::isA( SRF_ClassType type ) const
{
if (type == BaseSRF::SRF_TYP_WITH_TANGENT_PLANE_SURFACE)
return true;
else
return BaseSRF_3D::isA(type);
}
/** The BaseSRF_WithEllipsoidalHeight abstract class is the base class for
the 3D SRFs with ellipsoidal heights.
SRFs are allocated by the API, and when no longer needed they should be
released by calling the release() method.
@author Warren Macchi, David Shen
@see BaseSRF_3D, BaseSRF
*/
class EXPORT_SRM_CPP_DLL BaseSRF_WithEllipsoidalHeight : public BaseSRF_3D
{
public:
/** Returns true if this SRF is of the given class type
*/
virtual bool isA( SRF_ClassType type ) const;
/** Creates a surface coordinate object.
@exception This method throws srm::Exception
*/
virtual CoordSurf *createSurfaceCoordinate( SRM_Long_Float coord_surf_comp1,
SRM_Long_Float coord_surf_comp2 ) = 0;
/** Retrieves a coordinate surface component values
@exception This method throws srm::Exception
*/
virtual void getSurfaceCoordinateValues( const CoordSurf &coord_surf,
SRM_Long_Float &coord_surf_comp1,
SRM_Long_Float &coord_surf_comp2 ) const;
/** Frees a surface coordinate object.
@exception This method throws srm::Exception
*/
virtual void freeSurfaceCoordinate( CoordSurf *coord_surf );
/** Returns a surface coordinate associated with a 3D coordinate.
@exception This method throws srm::Exception
*/
virtual void getAssociatedSurfaceCoordinate( const Coord3D &coord,
CoordSurf &on_surface_coord );
/** Returns a 3D coordinate representing the same location as specified
by a surface coordinate.
@exception This method throws srm::Exception
*/
virtual void getPromotedSurfaceCoordinate( const CoordSurf &surf_coord,
Coord3D &three_d_coord );
/** Creates a Local Tangent Space Euclidean SRF with natural origin at a given
position.
@exception This method throws srm::Exception
*/
virtual SRF_LocalTangentSpaceEuclidean
*createLocalTangentSpaceEuclideanSRF(
const CoordSurf &surf_coord,
SRM_Long_Float azimuth,
SRM_Long_Float false_x_origin,
SRM_Long_Float false_y_origin,
SRM_Long_Float offset_height );
/** Computes the natural SRF Set member code (region) where the Surface coordinate is
located in the target SRF Set.
@param src_coord in : the source surface coordinate in an SRF
@param orm_dst in : the ORM for the destination SRF Set
@param rt_dst in : the RT for the destination SRF Set
@param tgt_srfs in : the destination SRF Set Code
@return the SRF Set Member code for the destination SRF Set
@exception This method throws srm::Exception
*/
static SRM_SRFS_Code_Info getNaturalSRFSetMemberCode( CoordSurf &src_coord,
SRM_ORM_Code orm_dst,
SRM_RT_Code rt_dst,
SRM_SRFS_Code tgt_srfs);
/** Computes the natural SRF Set member instance that the surface coordinate is
located in the target SRF Set.
@param src_coord in : the source surface coordinate in an SRF
@param orm_dst in : the ORM for the destination SRF Set
@param rt_dst in : the Hsr for the destination SRF Set
@param tgt_srfs in : the destination SRF Set Code
@return the SRF Set Member instance for the destination SRF Set
@exception This method throws srm::Exception
*/
static BaseSRF_3D* getNaturalSRFSetMember( CoordSurf &src_coord,
SRM_ORM_Code orm_dst,
SRM_RT_Code rt_dst,
SRM_SRFS_Code tgt_srfs);
/** Returns the euclidean distance (in metres) between two surface coordinates.
@note The input coordinates can be created from any SRF.
@exception This method throws srm::Exception
*/
static SRM_Long_Float calculateEuclideanDistance( const CoordSurf &coord1,
const CoordSurf &coord2 );
/** Returns the geodesic distance (in metres) between two surface
coordinates.
@exception This method throws srm::Exception
*/
static SRM_Long_Float calculateGeodesicDistance( const CoordSurf &src_coord,
const CoordSurf &des_coord );
/** Returns the vertical separation (in metres) at a position.
@exception This method throws srm::Exception
*/
virtual SRM_Long_Float calculateVerticalSeparationOffset( SRM_DSS_Code vos,
const CoordSurf &surf_coord );
protected:
BaseSRF_WithEllipsoidalHeight( void *impl ) : BaseSRF_3D(impl) {} ///< No stack allocation
BaseSRF_WithEllipsoidalHeight &operator =( const BaseSRF_WithEllipsoidalHeight & ) { return *this; } ///< No copy constructor
virtual ~BaseSRF_WithEllipsoidalHeight() {} ///< Use release()
};
inline bool BaseSRF_WithEllipsoidalHeight::isA( SRF_ClassType type ) const
{
if (type == BaseSRF::SRF_TYP_WITH_ELLIPSOIDAL_HEIGHT)
return true;
else
return BaseSRF_3D::isA(type);
}
/** The BaseSRF_MapProjection abstract class is the base class for the 2D
SRFs with map projections.
SRFs are allocated by the API, and when no longer needed they should be
released by calling the release() method.
@author Warren Macchi, David Shen
@see BaseSRF_WithEllipsoidalHeight, BaseSRF_3D
*/
class EXPORT_SRM_CPP_DLL BaseSRF_MapProjection : public BaseSRF_WithEllipsoidalHeight
{
public:
/** Returns true if this SRF is of the given class type
*/
virtual bool isA( SRF_ClassType type ) const;
/** Set the Valid Region for this SRF in geodetic coordinates (lon/lat).
@note Given a coordinate component, the last invocation of this
method or the setExtendedValidGeodeticRegion method determines
the valid and extended valid intervals of the coordinate
component values.
@note Upper or Lower value is ignored if the interval is a
semi-interval or unbounded.
@note The Lower value must be strictly less than the Upper value.
@param component in: the coordinate component (1 or 2)
@param type in: the type of interval
@param lower in: the lower value of the interval
@param upper in: the upper value of the interval
@exception This method throws srm::Exception
*/
virtual void setValidGeodeticRegion( const SRM_Integer component,
const SRM_Interval_Type type,
const SRM_Long_Float lower,
const SRM_Long_Float upper );
/** Set the Extended Valid Geodetic Region for this SRF.
@note Given a coordinate component, the last invocation of this
method or the setValidGeodeticRegion method determines
the valid and extended valid intervals of the coordinate
component values.
@note Upper or Lower value is ignored if the interval is a
semi-interval or unbounded.
@note The Lower value must be strictly less than the Upper value.
@note The Extended_Lower value must be strictly greater than the Lower value and
the Extended_Upper value must be strictly smaller than the Lower value.
@param component in: the coordinate component (1 or 2)
@param type in: the type of interval
@param extended_lower in: the extended lower value of the interval
@param lower in: the lower value of the interval
@param upper in: the upper value of the interval
@param extended_upper in: the extended_upper value of the interval
@exception This method throws srm::Exception
*/
virtual void setExtendedValidGeodeticRegion( const SRM_Integer component,
const SRM_Interval_Type type,
const SRM_Long_Float extended_lower,
const SRM_Long_Float lower,
const SRM_Long_Float upper,
const SRM_Long_Float extended_upper );
/** Get the Valid Geodetic Region for this SRF.
@note Given a coordinate component, the last invocation of this
method or the setExtendedValidGeodeticRegion method determines
the valid and extended valid intervals of the coordinate
component values.
@param component in: the coordinate component (1 or 2)
@param type out: the type of interval
@param lower out: the lower value of the interval
@param upper out: the upper value of the interval
@exception This method throws srm::Exception
*/
virtual void getValidGeodeticRegion( const SRM_Integer component,
SRM_Interval_Type &type,
SRM_Long_Float &lower,
SRM_Long_Float &upper );
/** Get the Extended Valid Geodetic Region for this SRF.
@note Given a coordinate component, the last invocation of this
method or the setValidGeodeticRegion method determines
the valid and extended valid intervals of the coordinate
component values.
@param component in: the coordinate component (1, 2, or 3)
@param type out: the type of interval
@param extended_lower out: the extended lower value of the interval
@param lower out: the lower value of the interval
@param upper out: the upper value of the interval
@param extended_upper out: the extended_upper value of the interval
@exception This method throws srm::Exception
*/
virtual void getExtendedValidGeodeticRegion( const SRM_Integer component,
SRM_Interval_Type &type,
SRM_Long_Float &extended_lower,
SRM_Long_Float &lower,
SRM_Long_Float &upper,
SRM_Long_Float &extended_upper );
/** Returns the Convergence of the Meridian in radians at a position on
the surface of the oblate spheroid RD.
@exception This method throws srm::Exception
*/
virtual SRM_Long_Float calculateConvergenceOfTheMeridian( const CoordSurf &surf_coord );
/** Returns the point distortion at a position on the surface of the ellipsoid RD.
@exception This method throws srm::Exception
*/
virtual SRM_Long_Float calculatePointDistortion( const CoordSurf &surf_coord );
/** Returns the map azimuth in radians between two surface coordinates.
@exception This method throws srm::Exception
*/
virtual SRM_Long_Float calculateMapAzimuth( const CoordSurf &src_coord,
const CoordSurf &des_coord );
protected:
BaseSRF_MapProjection( void *impl ) : BaseSRF_WithEllipsoidalHeight(impl) {} ///< No stack allocation
BaseSRF_MapProjection &operator =( const BaseSRF_MapProjection & ) { return *this; } ///< No copy constructor
virtual ~BaseSRF_MapProjection() {} ///< Use release()
};
inline bool BaseSRF_MapProjection::isA( SRF_ClassType type ) const
{
if (type == BaseSRF::SRF_TYP_MAP_PROJECTION)
return true;
else
return BaseSRF_WithEllipsoidalHeight::isA(type);
}
} // namespace srm
#endif // _BaseSRF_h
| [
"sysbender@gmail.com"
] | sysbender@gmail.com |
72b3e573176a4672dcad4570563a226c76ff0d60 | 64c64f19d6028d3948263a0acd1e7e86f5bf38b1 | /OJ/446.cpp | 78fd05df8b6f3088c8c152140365157fb6f0e27f | [] | no_license | xiejun5/HaiZei | f765f2462b63fe87efe754096c80c5f2ec5ea3df | 9f36757cadeb2f71434604eb16145dd5ef60e736 | refs/heads/master | 2020-09-22T08:16:44.318888 | 2020-08-11T15:25:10 | 2020-08-11T15:25:10 | 225,117,929 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,013 | cpp | /*************************************************************************
> File Name: 446.cpp
> Author:
> Mail:
> Created Time: 2020年01月08日 星期三 10时11分03秒
************************************************************************/
#include<iostream>
#include <cstring>
using namespace std;
#define N 100
int num[N][N];
int main() {
int n, p, q, t;
cin >> n;
p = 1;
q = n;
t = 1;
for (int j = 0; j <= n; j++, p++, q--) {
for (int i = p; i <= q; i++) {
num[p][i] = t;
}
for (int i = p; i <= q; i++) {
num[i][q] = t;
}
for (int i = n - j; i >= p; i--) {
num[q][i] = t;
}
for (int i = n - j; i >= p + 1; i--) {
num[i][p] = t;
}
t++;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
j - 1 && cout << " ";
cout << num[i][j];
}
cout << endl;
}
return 0;
}
| [
"3406505842@qq.com"
] | 3406505842@qq.com |
c5d382b88950e00ecb382799cb72d9bdaad953aa | 5fe2f231d31d86c2a18ea88303e08b95af94d19b | /line_follower.cpp | 97b2b2371faa0e511c2bfd1d4c79ab031bf1b968 | [] | no_license | abhishyantkhare/hibike | db608e33b8b98bec48c94e699e674091c2382c51 | c5aec317aa2393e8439758392cf12625fad7ca8b | refs/heads/master | 2021-01-16T01:07:12.057563 | 2015-08-27T07:50:01 | 2015-08-27T07:50:01 | 42,791,486 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,156 | cpp | #include "hibike_message.h"
#define IN_PIN 1
#define CONTROLLER_ID 0 // arbitrarily chosen for now
uint32_t data;
uint32_t subscriptionDelay;
HibikeMessage* m;
void setup() {
Serial.begin(115200);
pinMode(IN_PIN, INPUT);
}
void loop() {
data = digitalRead(IN_PIN);
// uncomment the line below for fun data spoofing
uint64_t currTime = millis();
data = (uint32_t) (currTime) & 0xFFFFFFFF;
if (subscriptionDelay) {
SensorUpdate(CONTROLLER_ID, SensorType::LineFollower, sizeof(data), (uint8_t*) &data).send();
delay(subscriptionDelay);
}
m = receiveHibikeMessage();
if (m) {
switch (m->getMessageId()) {
case HibikeMessageType::SubscriptionRequest:
{
subscriptionDelay = ((SubscriptionRequest*) m)->getSubscriptionDelay();
SubscriptionResponse(CONTROLLER_ID).send();
break;
}
case HibikeMessageType::SubscriptionResponse:
case HibikeMessageType::SensorUpdate:
case HibikeMessageType::Error:
default:
// TODO: implement error handling and retries
// TODO: implement other message types
break;
}
delete m;
}
}
| [
"vincentdonato@pioneers.berkeley.edu"
] | vincentdonato@pioneers.berkeley.edu |
bf2a301bc1493c0c56cf7538f3051af1edbad9bf | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/multimedia/directx/dinput/diconfig/idftest.h | d557f9b8a05c0eea1966d582b5d5e2a530777260 | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 943 | h | #ifndef __IDFTEST_H__
#define __IDFTEST_H__
typedef enum _TUI_CONFIGTYPE {
TUI_CONFIGTYPE_VIEW,
TUI_CONFIGTYPE_EDIT,
} TUI_CONFIGTYPE;
typedef enum _TUI_VIA {
TUI_VIA_DI,
TUI_VIA_CCI,
} TUI_VIA;
typedef enum _TUI_DISPLAY {
TUI_DISPLAY_GDI,
TUI_DISPLAY_DDRAW,
TUI_DISPLAY_D3D,
} TUI_DISPLAY;
typedef struct _TESTCONFIGUIPARAMS {
DWORD dwSize;
TUI_VIA eVia;
TUI_DISPLAY eDisplay;
TUI_CONFIGTYPE eConfigType;
int nNumAcFors;
LPCWSTR lpwszUserNames;
int nColorScheme;
BOOL bEditLayout;
WCHAR wszErrorText[MAX_PATH];
} TESTCONFIGUIPARAMS, FAR *LPTESTCONFIGUIPARAMS;
class IDirectInputConfigUITest : public IUnknown
{
public:
//IUnknown fns
STDMETHOD (QueryInterface) (REFIID iid, LPVOID *ppv) PURE;
STDMETHOD_(ULONG, AddRef) () PURE;
STDMETHOD_(ULONG, Release) () PURE;
//own fns
STDMETHOD (TestConfigUI) (LPTESTCONFIGUIPARAMS params) PURE;
};
#endif //__IDFTEST_H__se | [
"seta7D5@protonmail.com"
] | seta7D5@protonmail.com |
900979ef0cd13453fcfc9d446a6dc5ccd5857ad0 | 73f70fa0176d4b40fe88f146fa12de5cf18b9c5f | /designPatterns/singleton/multiton.cpp | d71cd6fe2ecfe4b52754d88cd22e85ca0071d90d | [] | no_license | MichalDUnda/Cpp | 93faf69e46b5f9155825addc447decdd0041b3bc | 77bfabe04ffd47a514b98adf66b2d943cd2d6a40 | refs/heads/master | 2023-07-13T23:08:50.327335 | 2023-07-03T08:11:15 | 2023-07-03T08:11:15 | 384,334,021 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,255 | cpp | #include <map>
#include <memory>
#include <iostream>
using namespace std;
//helper enum class for instances of multitone
enum class Importance
{
primary,
secondary,
tertiary
};
template <typename T, typename Key = std::string>
class Multiton
{
public:
static shared_ptr<T> get(const Key& key)
{
if(const auto it = instances.find(key);
it != instances.end())
{
return it->second;
}
auto instance = make_shared<T>();
instances[key] = instance;
return instance;
}
protected:
Multiton() = default;
virtual ~Multiton() = default;
private:
static map<Key, shared_ptr<T>> instances;
};
template <typename T, typename Key>
map<Key, shared_ptr<T>> Multiton<T, Key>::instances;
class Printer
{
public:
Printer()
{
++Printer::totalInstanceCount;
cout << "A total of " << Printer::totalInstanceCount << " instances created so far\n";
}
private:
static int totalInstanceCount;
};
int Printer::totalInstanceCount = 0;
int main()
{
using mt = Multiton<Printer, Importance>;
auto main = mt::get(Importance::primary);
auto aux = mt::get(Importance::secondary);
auto aux2 = mt::get(Importance::secondary);
} | [
"michal.dundo@gmail.com"
] | michal.dundo@gmail.com |
803cb938a6e7bc3ca561cda88d7a10aa5d11e631 | 90af79681ba010c6a2a0f4da3f04c175c5805180 | /C++_Basic/005继承重载等/三目运算符.cpp | 81372082cad0c9025f191e6833e523890ce0a07a | [] | no_license | minxin126/C_Basic | a184c2e6902397dfff99e1406b912caa3a894a20 | 2225a66bd3826c81658a86f3cbee4bb70a3014c6 | refs/heads/master | 2021-07-14T20:23:14.691028 | 2020-06-26T14:10:13 | 2020-06-26T14:10:13 | 177,624,168 | 1 | 2 | null | 2019-03-29T16:49:51 | 2019-03-25T16:28:49 | C++ | GB18030 | C++ | false | false | 294 | cpp | #include<iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
(a < b ? a : b)=30; //C++中三目运算符可以作为左值,返回的是变量本身。
cout << "a=" << a << endl; //左值是有内存空间的,寄存器没有内存空间。
cout << "b=" << b << endl;
} | [
"359676107@qq.com"
] | 359676107@qq.com |
dfe0bc8b82ef0d72a0797ecb955018c84d785065 | f76e43b84e0b624de8aed0a4b9f9bb0a9be22b92 | /src/dag-merger/BufferMaker.cpp | e999aabd23e5eab8f0ac68b8ebfa6bd91b57559a | [] | no_license | hansongfang/idb | 8c2603a3b37d55e0f17d9f815c56cfa27b416941 | 5c160553a83548df30fad5bc125cc4f27b01473f | refs/heads/master | 2021-09-13T04:52:29.246968 | 2018-04-25T05:33:26 | 2018-04-25T05:33:26 | 125,979,190 | 8 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,050 | cpp | #include "BufferMaker.h"
#include "dag-lib/Log.h"
#include "dag-lib/ViewPoint.h"
#include "dag-lib/ViewFacet.h"
#include <time.h>
#include <random>
#include <boost/filesystem.hpp>
#include <boost/serialization/serialization.hpp>
#include<boost/serialization/unordered_map.hpp>
#include<boost/serialization/set.hpp>
#include <boost/archive/text_iarchive.hpp>
#include<boost/archive/text_oarchive.hpp>
#include <fstream>
#include <time.h>
#include <math.h>
namespace fs = boost::filesystem;
BufferMaker::BufferMaker(ModelBase* pModel, DAGCenter* pDagCenter)
:_pModel(pModel)
,_pDagCenter(pDagCenter)
,_pViewModel(0)
{
}
BufferMaker::~BufferMaker()
{
if (_pDagMerger)
delete _pDagMerger;
if (_dagFanVCache)
delete _dagFanVCache;
if (_pViewModel)
delete _pViewModel;
}
void BufferMaker::init(int nSplit, int metric)
{
auto center = _pModel->getCenter3d();
auto radius = _pModel->getRadius();
_pViewModel = new SFViewFacet(center, 3.0*radius, nSplit);
_pViewModel->initViewNodes();
auto nDags = _pViewModel->getNumberOfNodes();
_pDagMerger = new DAGMerger(nDags, _pDagCenter,_pViewModel,metric);
}
void BufferMaker::merge()
{
while( _pDagMerger->hasQueue() ) {
_pDagMerger->mergeTop();
}
_pDagMerger->showResult();
}
void BufferMaker::updateClusters()
{
int nNodes = _pViewModel->getNumberOfNodes();
_pDagMerger->updateClusterNbs(_pViewModel->getViewEdges());
std::default_random_engine generator(std::time(0));
std::uniform_int_distribution<unsigned> distribution(0,nNodes-1);
int dagId = (int) distribution(generator);
int clusterId = _pDagMerger->getClusterId(dagId);
auto clusterNbs = _pDagMerger->getClusterNb(clusterId);
clusterNbs.insert(clusterId);
gLogInfo<<"relax cluster "<<clusterId;
// ship from 1-ring to 2-ring
for(auto cluster :clusterNbs){
if(cluster == clusterId)
continue;
std::unordered_map<int, std::set<int>> ignoreClusters;
while(_pDagMerger->shipBoundDag(cluster,clusterNbs, ignoreClusters)){}
}
// ship from center to 1-ring neighbor
std::set<int> temp{clusterId};
std::unordered_map<int, std::set<int>> ignoreClusters;
while(_pDagMerger->shipBoundDag(clusterId,temp,ignoreClusters)){}
_pDagMerger->cleanEmpty(clusterNbs);
}
int BufferMaker::getNClusters()
{
return _pDagMerger->getNumberOfClusters();
}
void BufferMaker::saveAssign(string cacheDir) const
{
string fileName = cacheDir +"/assignments.txt";
ofstream ofs(fileName);
auto assigns = _pDagMerger->getAssignments();
int nNodes = assigns.size();
auto center = _pModel->getCenter3d();
auto viewNodes = _pViewModel->getNodes();
for(int k=0;k<nNodes;k++){
auto tri = static_cast<const ViewNodeTriangle*>(viewNodes[k])->getTriangle();
auto triVec = (tri.getCenter() - center);
triVec.Normalize();
double theta = acos(triVec[2]);
double phi = atan2(triVec[1], triVec[0]);
if(k != nNodes -1)
ofs<< assigns[k]<<" "<< theta<<" "<<phi<<endl;
else
ofs<< assigns[k]<<" "<< theta<<" "<<phi;
}
ofs.close();
}
// DAGMerger need add getClusterIds
// DAGMerger move getClusterDag to public
// DAGMerger add clean clusterDag
void BufferMaker::vCacheOrder(string outDir)
{
_dagFanVCache = new DagFanVCache(_pModel->getNumberOfVertices(),_pModel->getNumberOfTriangles(),20);
vector<int> clusterIds = _pDagMerger->getClusterIds();
for(auto clusterId : clusterIds){
this->_vCacheOrder(clusterId, outDir);
//_pDagMerger->clearClusterDag(clusterId);
}
}
void BufferMaker::_vCacheOrder(int clusterId, string outDir)
{
// compute DAG
// Given a occlude b
// change to b--> a from a --> b
auto clusterDag = _pDagMerger->getClusterDag(clusterId);
auto occGraph = clusterDag->getDagGraph();
auto occMap = occGraph.getDagMap();
DagGraph tempGraph;
for(auto it = occMap.cbegin();it!= occMap.cend();it++){
for(auto innerIt = occMap.at(it->first).cbegin();innerIt != occMap.at(it->first).cend();innerIt++){
tempGraph.addEdge(innerIt->first,it->first,innerIt->second);
}
}
auto revertMap = tempGraph.getDagMap();
auto oldIndices = _pModel->getIndices();
_dagFanVCache->init(revertMap,oldIndices);
auto newIndices = _dagFanVCache->sort(oldIndices);
//log the indices out and render to see the result
//save the indices
string fileName = outDir +"/Indices_"+to_string(clusterId)+".txt";
gLogInfo<<"save "<<fileName;
std::ofstream fout(fileName);
for(auto vid : newIndices)
fout<<vid<<std::endl;
fout.close();
//save the triOrder used in order-upsample
auto triOrders = _dagFanVCache->getTriOrder();
fileName = outDir +"/triOrder_"+to_string(clusterId)+".txt";
gLogInfo<<"save "<<fileName;
fout.open(fileName);
for(auto triId : triOrders)
fout<<triId<<std::endl;
fout.close();
}
| [
"shanaf@ust.hk"
] | shanaf@ust.hk |
1c4d1474149a1281a811d815381d3aee57ecf79b | 0d87d119aa8aa2cc4d486f49b553116b9650da50 | /autom4te.cache/src/arith_uint256.h | 54fc1e46287e47d4cb8a5f490b4512ac550cfe82 | [
"MIT"
] | permissive | KingricharVD/Nests | af330cad884745cc68feb460d8b5547d3182e169 | 7b2ff6d27ccf19c94028973b7da20bdadef134a7 | refs/heads/main | 2023-07-07T12:21:09.232244 | 2021-08-05T01:25:23 | 2021-08-05T01:25:23 | 386,196,221 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,097 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2020-2021 The NestEgg Core Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_ARITH_UINT256_H
#define BITCOIN_ARITH_UINT256_H
#include "blob_uint256.h"
#include "uint512.h"
#include <assert.h>
#include <cstring>
#include <stdexcept>
#include <stdint.h>
#include <string>
#include <vector>
class blob_uint512;
class blob_uint256;
class uint256;
class uint512;
class uint_error : public std::runtime_error {
public:
explicit uint_error(const std::string& str) : std::runtime_error(str) {}
};
/** Template base class for unsigned big integers. */
template<unsigned int BITS>
class base_uint
{
public:
enum { WIDTH=BITS/32 };
uint32_t pn[WIDTH];
base_uint()
{
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
}
base_uint(const base_uint& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
}
base_uint& operator=(const base_uint& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
return *this;
}
base_uint(uint64_t b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
}
explicit base_uint(const std::string& str);
explicit base_uint(const std::vector<unsigned char>& vch);
bool operator!() const
{
for (int i = 0; i < WIDTH; i++)
if (pn[i] != 0)
return false;
return true;
}
const base_uint operator~() const
{
base_uint ret;
for (int i = 0; i < WIDTH; i++)
ret.pn[i] = ~pn[i];
return ret;
}
const base_uint operator-() const
{
base_uint ret;
for (int i = 0; i < WIDTH; i++)
ret.pn[i] = ~pn[i];
ret++;
return ret;
}
double getdouble() const;
base_uint& operator=(uint64_t b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
base_uint& operator^=(const base_uint& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] ^= b.pn[i];
return *this;
}
base_uint& operator&=(const base_uint& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] &= b.pn[i];
return *this;
}
base_uint& operator|=(const base_uint& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] |= b.pn[i];
return *this;
}
base_uint& operator^=(uint64_t b)
{
pn[0] ^= (unsigned int)b;
pn[1] ^= (unsigned int)(b >> 32);
return *this;
}
base_uint& operator|=(uint64_t b)
{
pn[0] |= (unsigned int)b;
pn[1] |= (unsigned int)(b >> 32);
return *this;
}
base_uint& operator<<=(unsigned int shift);
base_uint& operator>>=(unsigned int shift);
base_uint& operator+=(const base_uint& b)
{
uint64_t carry = 0;
for (int i = 0; i < WIDTH; i++)
{
uint64_t n = carry + pn[i] + b.pn[i];
pn[i] = n & 0xffffffff;
carry = n >> 32;
}
return *this;
}
base_uint& operator-=(const base_uint& b)
{
*this += -b;
return *this;
}
base_uint& operator+=(uint64_t b64)
{
base_uint b;
b = b64;
*this += b;
return *this;
}
base_uint& operator-=(uint64_t b64)
{
base_uint b;
b = b64;
*this += -b;
return *this;
}
base_uint& operator*=(uint32_t b32);
base_uint& operator*=(const base_uint& b);
base_uint& operator/=(const base_uint& b);
base_uint& operator++()
{
// prefix operator
int i = 0;
while (++pn[i] == 0 && i < WIDTH-1)
i++;
return *this;
}
const base_uint operator++(int)
{
// postfix operator
const base_uint ret = *this;
++(*this);
return ret;
}
base_uint& operator--()
{
// prefix operator
int i = 0;
while (--pn[i] == (uint32_t)-1 && i < WIDTH-1)
i++;
return *this;
}
const base_uint operator--(int)
{
// postfix operator
const base_uint ret = *this;
--(*this);
return ret;
}
int CompareTo(const base_uint& b) const;
bool EqualTo(uint64_t b) const;
friend inline const base_uint operator+(const base_uint& a, const base_uint& b) { return base_uint(a) += b; }
friend inline const base_uint operator-(const base_uint& a, const base_uint& b) { return base_uint(a) -= b; }
friend inline const base_uint operator*(const base_uint& a, const base_uint& b) { return base_uint(a) *= b; }
friend inline const base_uint operator/(const base_uint& a, const base_uint& b) { return base_uint(a) /= b; }
friend inline const base_uint operator|(const base_uint& a, const base_uint& b) { return base_uint(a) |= b; }
friend inline const base_uint operator&(const base_uint& a, const base_uint& b) { return base_uint(a) &= b; }
friend inline const base_uint operator^(const base_uint& a, const base_uint& b) { return base_uint(a) ^= b; }
friend inline const base_uint operator>>(const base_uint& a, int shift) { return base_uint(a) >>= shift; }
friend inline const base_uint operator<<(const base_uint& a, int shift) { return base_uint(a) <<= shift; }
friend inline const base_uint operator*(const base_uint& a, uint32_t b) { return base_uint(a) *= b; }
friend inline bool operator==(const base_uint& a, const base_uint& b) { return memcmp(a.pn, b.pn, sizeof(a.pn)) == 0; }
friend inline bool operator!=(const base_uint& a, const base_uint& b) { return memcmp(a.pn, b.pn, sizeof(a.pn)) != 0; }
friend inline bool operator>(const base_uint& a, const base_uint& b) { return a.CompareTo(b) > 0; }
friend inline bool operator<(const base_uint& a, const base_uint& b) { return a.CompareTo(b) < 0; }
friend inline bool operator>=(const base_uint& a, const base_uint& b) { return a.CompareTo(b) >= 0; }
friend inline bool operator<=(const base_uint& a, const base_uint& b) { return a.CompareTo(b) <= 0; }
friend inline bool operator==(const base_uint& a, uint64_t b) { return a.EqualTo(b); }
friend inline bool operator!=(const base_uint& a, uint64_t b) { return !a.EqualTo(b); }
std::string GetHex() const;
void SetHex(const char* psz);
void SetHex(const std::string& str);
std::string ToString() const;
std::string ToStringReverseEndian() const;
unsigned char* begin()
{
return (unsigned char*)&pn[0];
}
unsigned char* end()
{
return (unsigned char*)&pn[WIDTH];
}
const unsigned char* begin() const
{
return (unsigned char*)&pn[0];
}
const unsigned char* end() const
{
return (unsigned char*)&pn[WIDTH];
}
unsigned int size() const
{
return sizeof(pn);
}
uint64_t Get64(int n = 0) const
{
return pn[2 * n] | (uint64_t)pn[2 * n + 1] << 32;
}
uint32_t Get32(int n = 0) const
{
return pn[2 * n];
}
/**
* Returns the position of the highest bit set plus one, or zero if the
* value is zero.
*/
unsigned int bits() const;
uint64_t GetLow64() const
{
assert(WIDTH >= 2);
return pn[0] | (uint64_t)pn[1] << 32;
}
template<typename Stream>
void Serialize(Stream& s) const
{
s.write((char*)pn, sizeof(pn));
}
template<typename Stream>
void Unserialize(Stream& s)
{
s.read((char*)pn, sizeof(pn));
}
// Temporary for migration to blob160/256
uint64_t GetCheapHash() const
{
return GetLow64();
}
void SetNull()
{
memset(pn, 0, sizeof(pn));
}
bool IsNull() const
{
for (int i = 0; i < WIDTH; i++)
if (pn[i] != 0)
return false;
return true;
}
friend class uint160;
friend class uint256;
friend class uint512;
friend class arith_uint160;
friend class arith_uint256;
friend class arith_uint512;
};
/** 160-bit unsigned big integer. */
class arith_uint160 : public base_uint<160> {
public:
arith_uint160() {}
arith_uint160(const base_uint<160>& b) : base_uint<160>(b) {}
arith_uint160(uint64_t b) : base_uint<160>(b) {}
explicit arith_uint160(const std::string& str) : base_uint<160>(str) {}
explicit arith_uint160(const std::vector<unsigned char>& vch) : base_uint<160>(vch) {}
};
/** 256-bit unsigned big integer. */
class arith_uint256 : public base_uint<256> {
public:
arith_uint256() {}
arith_uint256(const base_uint<256>& b) : base_uint<256>(b) {}
arith_uint256(uint64_t b) : base_uint<256>(b) {}
explicit arith_uint256(const std::string& str) : base_uint<256>(str) {}
explicit arith_uint256(const std::vector<unsigned char>& vch) : base_uint<256>(vch) {}
/**
* The "compact" format is a representation of a whole
* number N using an unsigned 32bit number similar to a
* floating point format.
* The most significant 8 bits are the unsigned exponent of base 256.
* This exponent can be thought of as "number of bytes of N".
* The lower 23 bits are the mantissa.
* Bit number 24 (0x800000) represents the sign of N.
* N = (-1^sign) * mantissa * 256^(exponent-3)
*
* Satoshi's original implementation used BN_bn2mpi() and BN_mpi2bn().
* MPI uses the most significant bit of the first byte as sign.
* Thus 0x1234560000 is compact (0x05123456)
* and 0xc0de000000 is compact (0x0600c0de)
*
* Bitcoin only uses this "compact" format for encoding difficulty
* targets, which are unsigned 256bit quantities. Thus, all the
* complexities of the sign bit and using base 256 are probably an
* implementation accident.
*/
arith_uint256& SetCompact(uint32_t nCompact, bool *pfNegative = NULL, bool *pfOverflow = NULL);
uint32_t GetCompact(bool fNegative = false) const;
uint32_t Get32(int n = 0) const { return pn[2 * n]; }
};
/** 512-bit unsigned big integer. */
class arith_uint512 : public base_uint<512> {
public:
arith_uint512() {}
arith_uint512(const base_uint<512>& b) : base_uint<512>(b) {}
arith_uint512(uint64_t b) : base_uint<512>(b) {}
explicit arith_uint512(const std::string& str) : base_uint<512>(str) {}
explicit arith_uint512(const std::vector<unsigned char>& vch) : base_uint<512>(vch) {}
//friend arith_uint512 UintToArith512(const blob_uint512 &a);
//friend blob_uint512 ArithToUint512(const arith_uint512 &a);
};
/** Old classes definitions */
/** End classes definitions */
const arith_uint256 ARITH_UINT256_ZERO = arith_uint256();
#endif // BITCOIN_UINT256_H
| [
"northerncommunity1@gmail.com"
] | northerncommunity1@gmail.com |
98bf97e3e889e9da3b0bd53fdddd837f18f57695 | 5ae01ab82fcdedbdd70707b825313c40fb373fa3 | /src/evaluators/Charon_ThermodiffCoeff_Default_impl.hpp | 617a9633bd95bb0b77c5b7f3fd840f93ae94f5d3 | [] | no_license | worthenmanufacturing/tcad-charon | efc19f770252656ecf0850e7bc4e78fa4d62cf9e | 37f103306952a08d0e769767fe9391716246a83d | refs/heads/main | 2023-08-23T02:39:38.472864 | 2021-10-29T20:15:15 | 2021-10-29T20:15:15 | 488,068,897 | 0 | 0 | null | 2022-05-03T03:44:45 | 2022-05-03T03:44:45 | null | UTF-8 | C++ | false | false | 4,873 | hpp |
#ifndef CHARON_THERMODIFFCOEFF_DEFAULT_IMPL_HPP
#define CHARON_THERMODIFFCOEFF_DEFAULT_IMPL_HPP
#include <cmath>
#include "Panzer_Workset.hpp"
#include "Panzer_Workset_Utilities.hpp"
#include "Panzer_IntegrationRule.hpp"
#include "Panzer_BasisIRLayout.hpp"
#include "Charon_Names.hpp"
#include "Charon_Physical_Constants.hpp"
/*
The model implements the ion thermodiffusion coefficient as
D_{Ts} = u_{s} * T_{s} * S_{s} with all quantities in scaled units.
This model is used when "Ion Thermodiffusion Coefficient" is not specified in the
input xml file for DDIonLattice simulations. It is applicable to ions/vacancies only,
neither electrons nor holes.
*/
namespace charon {
///////////////////////////////////////////////////////////////////////////////
//
// Constructor
//
///////////////////////////////////////////////////////////////////////////////
template<typename EvalT, typename Traits>
ThermodiffCoeff_Default<EvalT, Traits>::
ThermodiffCoeff_Default(
const Teuchos::ParameterList& p)
{
using std::string;
using Teuchos::RCP;
using PHX::DataLayout;
using PHX::MDField;
using panzer::IntegrationRule;
using panzer::BasisIRLayout;
using Teuchos::ParameterList;
RCP<Teuchos::ParameterList> valid_params = this->getValidParameters();
p.validateParameters(*valid_params);
const charon::Names& n =
*(p.get< Teuchos::RCP<const charon::Names> >("Names"));
// retrieve data layout
RCP<DataLayout> scalar = p.get< RCP<DataLayout> >("Data Layout");
num_points = scalar->dimension(1);
num_edges = num_points; // initialization
// input from closure model factory
isEdgedl = p.get<bool>("Is Edge Data Layout");
// retrieve edge data layout if isEdgedl = true
RCP<DataLayout> output_dl = scalar;
if (isEdgedl)
{
RCP<BasisIRLayout> basis = p.get<RCP<BasisIRLayout> >("Basis");
RCP<const panzer::CellTopologyInfo> cellTopoInfo = basis->getCellTopologyInfo();
output_dl = cellTopoInfo->edge_scalar;
num_edges = output_dl->dimension(1);
cellType = cellTopoInfo->getCellTopology();
}
// evaluated field
thermodiff_coeff = MDField<ScalarT,Cell,Point>(n.field.ion_thermodiff_coeff,output_dl);
this->addEvaluatedField(thermodiff_coeff);
// dependent fields
mobility = MDField<const ScalarT,Cell,Point>(n.field.ion_mobility,output_dl);
soret_coeff = MDField<const ScalarT,Cell,Point>(n.field.ion_soret_coeff,output_dl);
latt_temp = MDField<const ScalarT,Cell,Point>(n.field.latt_temp,scalar);
this->addDependentField(mobility);
this->addDependentField(soret_coeff);
this->addDependentField(latt_temp);
std::string name = "Thermodiffusion_Coefficient_Default";
this->setName(name);
}
///////////////////////////////////////////////////////////////////////////////
//
// evaluateFields()
//
///////////////////////////////////////////////////////////////////////////////
template<typename EvalT, typename Traits>
void
ThermodiffCoeff_Default<EvalT, Traits>::
evaluateFields(
typename Traits::EvalData workset)
{
using panzer::index_t;
if (isEdgedl) // evaluate thermodiff. coeff. at edge midpoints
{
for (index_t cell = 0; cell < workset.num_cells; ++cell)
{
for (int edge = 0; edge < num_edges; ++edge)
{
// get local node ids: first index 1 for edge (0 for vertex, 2 for face, 3 for volume)
int node0 = cellType->getNodeMap(1,edge,0);
int node1 = cellType->getNodeMap(1,edge,1);
const ScalarT& latt = (latt_temp(cell,node0) + latt_temp(cell,node1)) / 2.0; // scaled
const ScalarT& mob = mobility(cell,edge); // scaled
const ScalarT& soret = soret_coeff(cell,edge);
thermodiff_coeff(cell,edge) = mob * latt * soret;
}
}
}
else // evaluate thermodiff. coeff. at IP or BASIS points
{
for (index_t cell = 0; cell < workset.num_cells; ++cell)
{
for (int point = 0; point < num_points; ++point)
{
const ScalarT& mob = mobility(cell,point); // scaled
const ScalarT& soret = soret_coeff(cell,point);
const ScalarT& latt = latt_temp(cell,point);
thermodiff_coeff(cell,point) = mob * latt * soret;
}
}
}
}
///////////////////////////////////////////////////////////////////////////////
//
// getValidParameters()
//
///////////////////////////////////////////////////////////////////////////////
template<typename EvalT, typename Traits>
Teuchos::RCP<Teuchos::ParameterList>
ThermodiffCoeff_Default<EvalT, Traits>::getValidParameters() const
{
Teuchos::RCP<Teuchos::ParameterList> p = Teuchos::rcp(new Teuchos::ParameterList);
Teuchos::RCP<const charon::Names> n;
p->set("Names", n);
Teuchos::RCP<PHX::DataLayout> dl;
p->set("Data Layout", dl);
p->set<bool>("Is Edge Data Layout", false);
Teuchos::RCP<panzer::BasisIRLayout> basis;
p->set("Basis", basis);
return p;
}
}
#endif
| [
"juan@tcad.com"
] | juan@tcad.com |
56297ae7e695111815692272683e8533b9c74c05 | 4416d4c599f175b68f54e0ee2aca97b18639567f | /DXBase/DXBase/sources/Field/MoveFloorRightLeft.h | 0a4f557d028917ddbb6083d644e4831b356e2563 | [] | no_license | kentatakiguchi/GameCompetition2016_2 | 292fa9ab574e581406ff146cc98b15efc0d66446 | df1eb6bf29aba263f46b850d268f49ef417a134b | refs/heads/master | 2021-01-11T18:21:34.377644 | 2017-03-03T08:25:39 | 2017-03-03T08:25:39 | 69,625,978 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,025 | h | #pragma once
#ifndef MOVE_FLOOR_RIGHT_LEFT_H_
#define MOVE_FLOOR_RIGHT_LEFT_H_
#include"../Actor/Base/Actor.h"
#include"../Define.h"
#include"MapChip.h"
class MoveFloorRightLeft :public MapChip {
public:
//空のMapChipを生成
MoveFloorRightLeft() {}
//マップチップの生成
MoveFloorRightLeft(IWorld* world, Vector2& position);
MoveFloorRightLeft(int spriteID,IWorld* world, Vector2& position);
MoveFloorRightLeft(std::shared_ptr<MoveFloorRightLeft> chip, IWorld* world, Vector2& position);
MoveFloorRightLeft(MoveFloorRightLeft& chip, IWorld* world, Vector2& position);
virtual void set(Vector2& pos);
MoveFloorRightLeft& operator = (std::shared_ptr<MoveFloorRightLeft> other) {
return MoveFloorRightLeft(other, world_, Vector2(0, 0));
};
private:
virtual void onUpdate(float deltaTime)override;
virtual void onDraw() const override;
virtual void onCollide(Actor& other)override;
private:
Vector2 defaultPos_;
float moveCount_;
float moveVelocity;
int spriteID_;
};
#endif // !MAPCHIP_H_
| [
"microbug7@gmail.com"
] | microbug7@gmail.com |
0cd1228640252d81f06a21c006aa52d318fbb1cd | 95c241df67572e94798a216a6b75e2bc1bb17319 | /Source.cpp | ee021c97af3ad92830973382c3e7e9e2af661a2b | [] | no_license | xhoic/GameY | 8bc0d96ff13643e304d81daea20f7d45d76202d4 | 85065e407d5e861a903989fb8c0c5292f823456f | refs/heads/main | 2023-02-17T21:04:09.183544 | 2021-01-18T02:36:45 | 2021-01-18T02:36:45 | 330,535,092 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,640 | cpp | //Xhoi Caveli
#include <iostream>
#include <map>
#include <set>
int main()
{
int diceNum;
std::map<int, int> diceRoll;
std::set<int> roll;
std::cout << "Enter 5 numbers in range 1 to 6." << std::endl;
for (int i = 1; i <= 5; i++)
{
std::cout << i << ". ";
std::cin >> diceNum;
while (diceNum < 1 or diceNum >6)
{
std::cout << "Invalid enty! Reenter a number in range 1 to 6." << std::endl;
std::cout << i << ". ";
std::cin >> diceNum;
}
++diceRoll[diceNum];
}
for (const std::pair<int, int>& dice : diceRoll)
{
roll.insert(dice.first);
}
if (roll.size() == 1)
{
std::cout << "Congrats! You have YATHZEE!!!" << std::endl;
}
else if (roll.size() == 2)
{
std::map<int, int>::reverse_iterator riter = diceRoll.rbegin();
if (diceRoll.begin()->second == 4 or riter->second == 4)
{
std::cout << "Congrats! You have 4 of a kind." << std::endl;
}
else
{
std::cout << "Congrats! You have a full house." << std::endl;
}
}
else if (roll.size() == 3)
{
std::map<int, int>::iterator iter = diceRoll.begin();
while (iter != diceRoll.end())
{
if (iter->second == 3)
{
std::cout << "Congrats! You have 3 of a kind!" << std::endl;
}
else if (iter->second == 2)
{
std::cout << "Oops! There is nothing!" << std::endl;
break;
}
iter++;
}
}
else if (roll.size() == 4)
{
bool flag = true;
std::map<int, int>::iterator iter = diceRoll.begin();
iter++;
std::map<int, int>::iterator iter1 = diceRoll.begin();
while (iter != diceRoll.end())
{
if (iter->first != iter1->first + 1)
{
flag = false;
}
iter++;
iter1++;
}
if (flag == true)
{
std::cout << "Congrats! You have a small straight!" << std::endl;
}
else
{
std::cout << "Oops! There is nothing!" << std::endl;
}
}
else
{
bool flag = true;
std::map<int, int>::iterator iter = diceRoll.begin();
iter++;
std::map<int, int>::iterator iter1 = diceRoll.begin();
while (iter != diceRoll.end())
{
if (iter->first != iter1->first + 1)
{
flag = false;
}
iter++;
iter1++;
}
if (flag == true)
{
std::cout << "Congrats! You have a large straight!" << std::endl;
}
else
{
flag = true;
iter = diceRoll.begin();
iter++;
iter1 = diceRoll.begin();
for (int i = 0; i < 3; i++)
{
if (iter->first != iter1->first + 1)
{
flag = false;
}
iter++;
iter1++;
}
if (flag == true)
{
std::cout << "Congrats! You have a small straight!" << std::endl;
}
else
{
std::cout << "Oops! There is nothing!" << std::endl;
}
}
}
system("PAUSE");
return 0;
} | [
"caveli.xhoi@gmail.com"
] | caveli.xhoi@gmail.com |
ff4c63f35fb5971280736ca30ce0334040d407db | ac9b37f9523f62c67c819fae44ec5a33e33f23e4 | /collatz_conjecture/collatz_OpenMP_MPI_CUDA.cpp | d0961deb8dde7807b851db3f55e060d0231fd54b | [] | no_license | M-Hernandez/Arcane-repo | 6fee76d11b634321a40b345875c1ffe90361fe12 | bfc0d678fdeccb1cb044882fcbd8a4e87e7b4dbb | refs/heads/master | 2021-09-23T11:14:29.370733 | 2021-09-14T02:52:44 | 2021-09-14T02:52:44 | 208,671,875 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,689 | cpp | /*
Collatz code for CS 4380 / CS 5351
Copyright (c) 2020 Texas State University. All rights reserved.
Redistribution in source or binary form, with or without modification,
is *not* permitted. Use in source or binary form, with or without
modification, is only permitted for academic use in CS 4380 or CS 5351
at Texas State University.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Author: Martin Burtscher
*/
#include <cstdio>
#include <algorithm>
#include <sys/time.h>
#include <mpi.h>
void GPU_Init(void);
void GPU_Exec(const long start, const long stop);
int GPU_Fini(void);
static int collatz(const long start, const long stop)
{
// compute sequence lengths
int maxlen = 0;
#pragma omp parallel for default(none) reduction(max : maxlen) schedule(static,1)
for (long i = start; i <= stop; i++) {
long val = i;
int len = 1;
while (val != 1) {
len++;
if ((val % 2) == 0) {
val /= 2; // even
} else {
val = 3 * val + 1; // odd
}
}
maxlen = std::max(maxlen, len);
}
// todo: OpenMP code with default(none), a reduction, and a cyclic schedule based on Project 4
return maxlen;
}
int main(int argc, char *argv[])
{
int comm_sz, my_rank;
MPI_Init(NULL, NULL);
MPI_Comm_size(MPI_COMM_WORLD, &comm_sz);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
if(my_rank == 0){
printf("Collatz v1.4\n");
printf("Num of processes: %d\n", comm_sz);
}
// check command line
if (argc != 3) {fprintf(stderr, "USAGE: %s upper_bound cpu_percentage\n", argv[0]); exit(-1);}
const long bound = atol(argv[1]);
if (bound < 1) {fprintf(stderr, "ERROR: upper_bound must be at least 1\n"); exit(-1);}
const int percentage = atoi(argv[2]);
if ((percentage < 0) || (percentage > 100)) {fprintf(stderr, "ERROR: cpu_percentage must be between 0 and 100\n"); exit(-1);}
const long cpu_start = 1 + my_rank * bound / comm_sz;
const long gpu_stop = 1 + (my_rank + 1) * bound / comm_sz;
const long my_range = gpu_stop - cpu_start;
const long cpu_stop = cpu_start + my_range * percentage / 100;
const long gpu_start = cpu_stop;
if(my_rank == 0){
printf("upper bound: %ld\n", bound);
printf("CPU percentage: %d\n", percentage);
}
GPU_Init();
// start time
timeval start, end;
MPI_Barrier(MPI_COMM_WORLD);
gettimeofday(&start, NULL);
// execute timed code
GPU_Exec(gpu_start, gpu_stop);
int globalMax;
const int cpu_maxlen = collatz(cpu_start, cpu_stop);
const int gpu_maxlen = GPU_Fini();
const int maxlen = std::max(cpu_maxlen, gpu_maxlen);
MPI_Reduce(&maxlen,&globalMax,1,MPI_INT,MPI_MAX,0,MPI_COMM_WORLD);
// end time
gettimeofday(&end, NULL);
const double runtime = end.tv_sec - start.tv_sec + (end.tv_usec - start.tv_usec) / 1000000.0;
// print result
if(my_rank == 0){
printf("compute time: %.6f s\n", runtime);
printf("longest sequence length: %d elements\n", globalMax);
}
MPI_Finalize();
return 0;
}
| [
"miguelhernandez@Miguels-MacBook-Pro.local"
] | miguelhernandez@Miguels-MacBook-Pro.local |
3490709c9d10c5f3a47928787cb12434bb27185e | e20b7293bba88babbd9b18ac731a2215cfac2c51 | /src/qt/test/uritests.cpp | 797bddb411771864f0d91c9a71c10f3a1b233258 | [
"MIT"
] | permissive | thachpv91/hanhcoin-clone | af57bcc042e3584fdaad2b585f32daf83153910d | d7bd7f4b88066d4a4ca545857db59ba673103af5 | refs/heads/master | 2020-06-23T14:27:56.971235 | 2016-11-24T06:59:38 | 2016-11-24T06:59:38 | 74,646,122 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,853 | cpp | #include "uritests.h"
#include "../guiutil.h"
#include "../walletmodel.h"
#include <QUrl>
void URITests::uriTests()
{
SendCoinsRecipient rv;
QUrl uri;
uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?req-dontexist="));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?dontexist="));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 0);
uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?label=Wikipedia Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString("Wikipedia Example Address"));
QVERIFY(rv.amount == 0);
uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=0.001"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 100000);
uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1.001"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
QVERIFY(rv.amount == 100100000);
uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=100&label=Wikipedia Example"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.amount == 10000000000LL);
QVERIFY(rv.label == QString("Wikipedia Example"));
uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?message=Wikipedia Example Address"));
QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
QVERIFY(GUIUtil::parseBitcoinURI("hanhcoin://LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?message=Wikipedia Example Address", &rv));
QVERIFY(rv.address == QString("LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9"));
QVERIFY(rv.label == QString());
// We currently don't implement the message parameter (ok, yea, we break spec...)
uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?req-message=Wikipedia Example Address"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1,000&label=Wikipedia Example"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
uri.setUrl(QString("hanhcoin:LQDPC5rbjDB72fGFVHu4enYhxGAZuRiFh9?amount=1,000.0&label=Wikipedia Example"));
QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv));
}
| [
"thachphanvan@gmail.com"
] | thachphanvan@gmail.com |
80862b2e4e75a0d761b2793bc2c2b29d42e0447c | 0441585e00e2d1ceddc2e4575e6c195075d6d3ca | /PersonItem.hpp | 0b8ac2bf298527dee103ac1174e14d1d66058e67 | [] | no_license | rherardi/ldif2pst | 9efc00f0ac4816934e5328030a0447b219b9342f | 766959056d448793240dcd0d199d47c122a37e28 | refs/heads/master | 2020-05-20T07:49:05.914074 | 2015-05-12T07:46:18 | 2015-05-12T07:46:18 | 35,469,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,492 | hpp | // MessageItem.hpp: interface for the CPersonItem class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_PERSONITEM_HPP__EC66FE86_817C_4257_84C8_5D4905E2CCBE__INCLUDED_)
#define AFX_PERSONITEM_HPP__EC66FE86_817C_4257_84C8_5D4905E2CCBE__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#ifdef NMAILXML_EXPORTS
#define NMAILXML_API __declspec(dllexport)
#else
#define NMAILXML_API __declspec(dllimport)
#endif
class CPersonItem
{
public:
CPersonItem();
virtual ~CPersonItem();
// Get/Set m_attribute
NMAILXML_API _TCHAR const * GetName();
NMAILXML_API void SetName(const _TCHAR *name);
// Get/Set m_value
NMAILXML_API _TCHAR const * GetValue();
NMAILXML_API void SetValue(const _TCHAR *value);
// Get/Set m_value
NMAILXML_API long const GetValueNumeric();
NMAILXML_API void SetValueNumeric(const long value);
// Get/Set m_numeric
NMAILXML_API bool const IsNumeric();
NMAILXML_API void SetNumeric(const bool value);
// Get/Set m_condition
NMAILXML_API _TCHAR const * GetCondition();
NMAILXML_API void SetCondition(const _TCHAR *value);
// Get/Set m_namedProperty
NMAILXML_API bool const IsNamedProperty();
NMAILXML_API void SetNamedProperty(const bool namedProperty);
protected:
_TCHAR m_name[128];
_TCHAR m_value[512];
long m_valuenum;
bool m_numeric;
_TCHAR m_condition[128];
bool m_namedProperty;
};
#endif // !defined(AFX_PERSONITEM_HPP__EC66FE86_817C_4257_84C8_5D4905E2CCBE__INCLUDED_)
| [
"rherardi@alumni.stanford.edu"
] | rherardi@alumni.stanford.edu |
566e77f8dd6a0cc6aa2ce2669134e1597586548c | fbb6b85ea717ddbbaa149a233213f59369c00780 | /src/governance-vote.h | dafbc6e6402f6851b04def7af1c30e45149b7c2d | [
"MIT"
] | permissive | agenanextproject/Agena | bd5368c554a0b0051f8ce98fd39a962e71cb6ec9 | 562aed54370e2d64921006f0f2e1ee5154c650d9 | refs/heads/master | 2020-03-21T03:45:36.170961 | 2018-03-15T18:18:10 | 2018-03-15T18:18:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,797 | h | // Copyright (c) 2014-2017 The Agena Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef GOVERNANCE_VOTE_H
#define GOVERNANCE_VOTE_H
#include "key.h"
#include "primitives/transaction.h"
#include <boost/lexical_cast.hpp>
using namespace std;
class CGovernanceVote;
// INTENTION OF MASTERNODES REGARDING ITEM
enum vote_outcome_enum_t {
VOTE_OUTCOME_NONE = 0,
VOTE_OUTCOME_YES = 1,
VOTE_OUTCOME_NO = 2,
VOTE_OUTCOME_ABSTAIN = 3
};
// SIGNAL VARIOUS THINGS TO HAPPEN:
enum vote_signal_enum_t {
VOTE_SIGNAL_NONE = 0,
VOTE_SIGNAL_FUNDING = 1, // -- fund this object for it's stated amount
VOTE_SIGNAL_VALID = 2, // -- this object checks out in sentinel engine
VOTE_SIGNAL_DELETE = 3, // -- this object should be deleted from memory entirely
VOTE_SIGNAL_ENDORSED = 4, // -- officially endorsed by the network somehow (delegation)
VOTE_SIGNAL_NOOP1 = 5, // FOR FURTHER EXPANSION
VOTE_SIGNAL_NOOP2 = 6,
VOTE_SIGNAL_NOOP3 = 7,
VOTE_SIGNAL_NOOP4 = 8,
VOTE_SIGNAL_NOOP5 = 9,
VOTE_SIGNAL_NOOP6 = 10,
VOTE_SIGNAL_NOOP7 = 11,
VOTE_SIGNAL_NOOP8 = 12,
VOTE_SIGNAL_NOOP9 = 13,
VOTE_SIGNAL_NOOP10 = 14,
VOTE_SIGNAL_NOOP11 = 15,
VOTE_SIGNAL_CUSTOM1 = 16, // SENTINEL CUSTOM ACTIONS
VOTE_SIGNAL_CUSTOM2 = 17, // 16-35
VOTE_SIGNAL_CUSTOM3 = 18,
VOTE_SIGNAL_CUSTOM4 = 19,
VOTE_SIGNAL_CUSTOM5 = 20,
VOTE_SIGNAL_CUSTOM6 = 21,
VOTE_SIGNAL_CUSTOM7 = 22,
VOTE_SIGNAL_CUSTOM8 = 23,
VOTE_SIGNAL_CUSTOM9 = 24,
VOTE_SIGNAL_CUSTOM10 = 25,
VOTE_SIGNAL_CUSTOM11 = 26,
VOTE_SIGNAL_CUSTOM12 = 27,
VOTE_SIGNAL_CUSTOM13 = 28,
VOTE_SIGNAL_CUSTOM14 = 29,
VOTE_SIGNAL_CUSTOM15 = 30,
VOTE_SIGNAL_CUSTOM16 = 31,
VOTE_SIGNAL_CUSTOM17 = 32,
VOTE_SIGNAL_CUSTOM18 = 33,
VOTE_SIGNAL_CUSTOM19 = 34,
VOTE_SIGNAL_CUSTOM20 = 35
};
static const int MAX_SUPPORTED_VOTE_SIGNAL = VOTE_SIGNAL_ENDORSED;
/**
* Governance Voting
*
* Static class for accessing governance data
*/
class CGovernanceVoting
{
public:
static vote_outcome_enum_t ConvertVoteOutcome(std::string strVoteOutcome);
static vote_signal_enum_t ConvertVoteSignal(std::string strVoteSignal);
static std::string ConvertOutcomeToString(vote_outcome_enum_t nOutcome);
static std::string ConvertSignalToString(vote_signal_enum_t nSignal);
};
//
// CGovernanceVote - Allow a masternode node to vote and broadcast throughout the network
//
class CGovernanceVote
{
friend bool operator==(const CGovernanceVote& vote1, const CGovernanceVote& vote2);
friend bool operator<(const CGovernanceVote& vote1, const CGovernanceVote& vote2);
private:
bool fValid; //if the vote is currently valid / counted
bool fSynced; //if we've sent this to our peers
int nVoteSignal; // see VOTE_ACTIONS above
CTxIn vinMasternode;
uint256 nParentHash;
int nVoteOutcome; // see VOTE_OUTCOMES above
int64_t nTime;
std::vector<unsigned char> vchSig;
public:
CGovernanceVote();
CGovernanceVote(CTxIn vinMasternodeIn, uint256 nParentHashIn, vote_signal_enum_t eVoteSignalIn, vote_outcome_enum_t eVoteOutcomeIn);
bool IsValid() const { return fValid; }
bool IsSynced() const { return fSynced; }
int64_t GetTimestamp() const { return nTime; }
vote_signal_enum_t GetSignal() const { return vote_signal_enum_t(nVoteSignal); }
vote_outcome_enum_t GetOutcome() const { return vote_outcome_enum_t(nVoteOutcome); }
const uint256& GetParentHash() const { return nParentHash; }
void SetTime(int64_t nTimeIn) { nTime = nTimeIn; }
void SetSignature(const std::vector<unsigned char>& vchSigIn) { vchSig = vchSigIn; }
bool Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode);
bool IsValid(bool fSignatureCheck) const;
void Relay() const;
std::string GetVoteString() const {
return CGovernanceVoting::ConvertOutcomeToString(GetOutcome());
}
CTxIn& GetVinMasternode() { return vinMasternode; }
const CTxIn& GetVinMasternode() const { return vinMasternode; }
/**
* GetHash()
*
* GET UNIQUE HASH WITH DETERMINISTIC VALUE OF THIS SPECIFIC VOTE
*/
uint256 GetHash() const
{
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << vinMasternode;
ss << nParentHash;
ss << nVoteSignal;
ss << nVoteOutcome;
ss << nTime;
return ss.GetHash();
}
std::string ToString() const
{
std::ostringstream ostr;
ostr << vinMasternode.ToString() << ":"
<< nTime << ":"
<< CGovernanceVoting::ConvertOutcomeToString(GetOutcome()) << ":"
<< CGovernanceVoting::ConvertSignalToString(GetSignal());
return ostr.str();
}
/**
* GetTypeHash()
*
* GET HASH WITH DETERMINISTIC VALUE OF MASTERNODE-VIN/PARENT-HASH/VOTE-SIGNAL
*
* This hash collides with previous masternode votes when they update their votes on governance objects.
* With 12.1 there's various types of votes (funding, valid, delete, etc), so this is the deterministic hash
* that will collide with the previous vote and allow the system to update.
*
* --
*
* We do not include an outcome, because that can change when a masternode updates their vote from yes to no
* on funding a specific project for example.
* We do not include a time because it will be updated each time the vote is updated, changing the hash
*/
uint256 GetTypeHash() const
{
// CALCULATE HOW TO STORE VOTE IN governance.mapVotes
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << vinMasternode;
ss << nParentHash;
ss << nVoteSignal;
// -- no outcome
// -- timeless
return ss.GetHash();
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(vinMasternode);
READWRITE(nParentHash);
READWRITE(nVoteOutcome);
READWRITE(nVoteSignal);
READWRITE(nTime);
READWRITE(vchSig);
}
};
/**
* 12.1.1 - CGovernanceVoteManager
* -------------------------------
*
GetVote(name, yes_no):
- caching function
- mark last accessed votes
- load serialized files from filesystem if needed
- calc answer
- return result
CacheUnused():
- Cache votes if lastused > 12h/24/48/etc
*/
#endif
| [
"agentaproject@gmail.com"
] | agentaproject@gmail.com |
dc294122141a13c2a1d104495d46351e6fd64ce4 | 11ac20402a3bde71126f8c6d8734174fbcc409af | /note/test_code/stm/phch_recv.cc | 7b66d3babe85148f98307b7db420de3fcd587789 | [] | no_license | learning-lte/read-srslte | aa0bb1a0e711b9f6ba2eae65d78e691ea7293889 | cfafa1df08a312bf467cb5c72bdc906849c07893 | refs/heads/master | 2021-10-11T22:57:28.892751 | 2019-01-30T11:14:05 | 2019-01-30T11:14:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 528 | cc | #include "phch_recv.h"
#include <stdio.h>
sync_state phy_state;
void * run_thread(void){
bool running = true;
while(running){
switch(phy_state.run_state()){
case sync_state::CELL_SEARCH:
printf("I'm in cell search\n");
phy_state.state_exit();
break;
case sync_state::SFN_SYNC:
printf("I'm in sfn_sync\n");
phy_state.state_exit();
break;
case sync_state::CAMPING:
printf("I'm in camping\n");
break;
case sync_state::IDLE:
printf("I'm in idle\n");
break;
}
}
}
| [
"651558476@qq.com"
] | 651558476@qq.com |
5596d53e7e53f5dce98fd0bf7d55396f29f59902 | 091afb7001e86146209397ea362da70ffd63a916 | /inst/include/nt2/constant/constants/maxexponent.hpp | 4d628719ac4d9bb420da3445baefd976802cd47a | [] | no_license | RcppCore/RcppNT2 | f156b58c08863243f259d1e609c9a7a8cf669990 | cd7e548daa2d679b6ccebe19744b9a36f1e9139c | refs/heads/master | 2021-01-10T16:15:16.861239 | 2016-02-02T22:18:25 | 2016-02-02T22:18:25 | 50,460,545 | 15 | 1 | null | 2019-11-15T22:08:50 | 2016-01-26T21:29:34 | C++ | UTF-8 | C++ | false | false | 1,185 | hpp | //==============================================================================
// Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_CONSTANT_CONSTANTS_MAXEXPONENT_HPP_INCLUDED
#define NT2_CONSTANT_CONSTANTS_MAXEXPONENT_HPP_INCLUDED
#include <boost/simd/constant/include/constants/maxexponent.hpp>
#include <nt2/include/functor.hpp>
namespace nt2
{
namespace tag
{
#ifdef DOXYGEN_ONLY
/*! \brief Same as \classref{boost::simd::tag::Maxexponent_} **/
struct maxexponent_ {};
#endif
using boost::simd::tag::Maxexponent;
}
#ifdef DOXYGEN_ONLY
/*! \brief Same as \funcref{boost::simd::Maxexponent} **/
template<class... Args>
details::unspecified maxexponent(Args&&... args);
#endif
using boost::simd::Maxexponent;
}
#include <nt2/constant/common.hpp>
#endif
| [
"kevinushey@gmail.com"
] | kevinushey@gmail.com |
37439e54d41ddbea6a3a5b025fe73197ba67938c | eb0b9c66976c0aa0b1a5506c0d500161a47294f7 | /WalkThrough/Queue.h | 8ef7e12e4650e6ce52adf73cc3b3e8272808b112 | [] | no_license | codeprecise/a-gentle-introduction-to-cpp | 46eb99ac46e0b39c7962e685abfdd8e50b623d61 | db933dee8fc06249437172a2b943a2b80f6e6de0 | refs/heads/master | 2020-06-02T17:51:40.529676 | 2019-06-11T05:09:10 | 2019-06-11T05:09:10 | 191,044,620 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 481 | h | #pragma once
#include "Mutex.h"
typedef void* ElementPtr;
class Queue
{
public:
Queue(int maxElementCount, int elementSize);
~Queue();
int GetSize();
bool Enqueue(ElementPtr element);
bool Dequeue(ElementPtr element);
private:
void IncrementIndex(int* index);
int _elementSize;
int _maxElementCount;
int _elementCount;
int _writeIndex;
int _readIndex;
char* _elements;
Mutex _mutex;
};
| [
"davids@codeprecise.com"
] | davids@codeprecise.com |
16a8823e1d2377f821d4075a7dc7aad3a4432ada | 0c46b2988021dacf063778be69c12cf9466ff379 | /INF/PrgT/Cpp/03-inheritance-and-polymorphism/diamond_problem/Boat.h | 0b8690e4acee4a5692111981440ce7cf02a0001b | [] | no_license | AL5624/TH-Rosenheim-Backup | 2db235cf2174b33f25758a36e83c3aa9150f72ee | fa01cb7459ab55cb25af79244912d8811a62f83f | refs/heads/master | 2023-01-21T06:57:58.155166 | 2023-01-19T08:36:57 | 2023-01-19T08:36:57 | 219,547,187 | 0 | 0 | null | 2022-05-25T23:29:08 | 2019-11-04T16:33:34 | C# | UTF-8 | C++ | false | false | 327 | h | #ifndef INC_03_INHERITANCE_AND_POLYMORPHISM_BOAT_H
#define INC_03_INHERITANCE_AND_POLYMORPHISM_BOAT_H
#include "Vehicle.h"
// TODO: Define the Boat class
class Boat : Vehicle {
public:
int maxKnots;
Boat(int serial, int yearOfManufacture, int maxKnots);
~Boat();
};
#endif //INC_03_INHERITANCE_AND_POLYMORPHISM_BOAT_H
| [
"anton.bertram@stud.fh-rosenheim.de"
] | anton.bertram@stud.fh-rosenheim.de |
e64a8543bc18e5018c4b735992b8ed19c9594fe6 | 27dbda0197096619145e80144f9a7bdc33099b08 | /Core/Assembler.h | 191bdee81301e110f4800c78b90f608c4be77643 | [] | no_license | unknownbrackets/armips | f58941bc2307e8b72a150a00d0ab7b3749783bcb | f53a0949d11a29bda810811fc8b7647ecb630c78 | refs/heads/master | 2022-11-05T18:03:52.751621 | 2014-11-23T20:04:24 | 2014-11-23T20:04:24 | 27,045,572 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 954 | h | #pragma once
#include "../Util/CommonClasses.h"
#include "../Util/FileClasses.h"
#include "../Util/Util.h"
#include "FileManager.h"
enum class ArmipsMode { File, Memory };
struct LabelDefinition
{
std::wstring name;
int value;
};
struct ArmipsArguments
{
// common
ArmipsMode mode;
int symFileVersion;
bool errorOnWarning;
bool silent;
StringList* errorsResult;
StringList equList;
std::vector<LabelDefinition> labels;
// file mode
std::wstring inputFileName;
std::wstring tempFileName;
std::wstring symFileName;
// memory mode
AssemblerFile* memoryFile;
std::wstring content;
ArmipsArguments()
{
mode = ArmipsMode::File;
errorOnWarning = false;
silent = false;
errorsResult = NULL;
}
};
bool runArmips(ArmipsArguments& arguments);
void parseMacroDefinition(TextFile& Input, std::wstring& Args);
void LoadAssemblyFile(const std::wstring& fileName, TextFile::Encoding encoding = TextFile::GUESS);
bool EncodeAssembly();
| [
"sorgts@googlemail.com"
] | sorgts@googlemail.com |
2fabb0fe19a9f48de6d164d1cda43172e1a503ea | f6f55778056b4c008bfd5897a028faf20c6927a7 | /src/qt/privacydialog.cpp | fd55a10cb40370b228b94c4b624e4db71f78be74 | [
"MIT"
] | permissive | bright-project/brightcoin | f3b3c140a669be11dfc54d797397a46c70c14cab | b42683d82a65b96861383d8b3e4c7d22b92acc70 | refs/heads/master | 2020-03-29T20:06:59.302242 | 2018-09-25T16:33:53 | 2018-09-25T16:33:53 | 150,296,212 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,569 | cpp | // Copyright (c) 2011-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.
#include "privacydialog.h"
#include "ui_privacydialog.h"
#include "addressbookpage.h"
#include "addresstablemodel.h"
#include "bitcoinunits.h"
#include "coincontroldialog.h"
#include "libzerocoin/Denominations.h"
#include "optionsmodel.h"
#include "sendcoinsentry.h"
#include "walletmodel.h"
#include "coincontrol.h"
#include "zbrightcoincontroldialog.h"
#include "spork.h"
#include <QClipboard>
#include <QSettings>
#include <utilmoneystr.h>
#include <QtWidgets>
PrivacyDialog::PrivacyDialog(QWidget* parent) : QDialog(parent),
ui(new Ui::PrivacyDialog),
walletModel(0),
currentBalance(-1)
{
nDisplayUnit = 0; // just make sure it's not unitialized
ui->setupUi(this);
// "Spending 999999 zBRIGHTCOIN ought to be enough for anybody." - Bill Gates, 2017
ui->zBRIGHTCOINpayAmount->setValidator( new QDoubleValidator(0.0, 21000000.0, 20, this) );
ui->labelMintAmountValue->setValidator( new QIntValidator(0, 999999, this) );
// Default texts for (mini-) coincontrol
ui->labelCoinControlQuantity->setText (tr("Coins automatically selected"));
ui->labelCoinControlAmount->setText (tr("Coins automatically selected"));
ui->labelzBRIGHTCOINSyncStatus->setText("(" + tr("out of sync") + ")");
// Sunken frame for minting messages
ui->TEMintStatus->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
ui->TEMintStatus->setLineWidth (2);
ui->TEMintStatus->setMidLineWidth (2);
ui->TEMintStatus->setPlainText(tr("Mint Status: Okay"));
// Coin Control signals
connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked()));
// Coin Control: clipboard actions
QAction* clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
QAction* clipboardAmountAction = new QAction(tr("Copy amount"), this);
connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity()));
connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount()));
ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
ui->labelCoinControlAmount->addAction(clipboardAmountAction);
// Denomination labels
ui->labelzDenom1Text->setText("Denom. with value <b>1</b>:");
ui->labelzDenom2Text->setText("Denom. with value <b>5</b>:");
ui->labelzDenom3Text->setText("Denom. with value <b>10</b>:");
ui->labelzDenom4Text->setText("Denom. with value <b>50</b>:");
ui->labelzDenom5Text->setText("Denom. with value <b>100</b>:");
ui->labelzDenom6Text->setText("Denom. with value <b>500</b>:");
ui->labelzDenom7Text->setText("Denom. with value <b>1000</b>:");
ui->labelzDenom8Text->setText("Denom. with value <b>5000</b>:");
// BRIGHTCOIN settings
QSettings settings;
if (!settings.contains("nSecurityLevel")){
nSecurityLevel = 42;
settings.setValue("nSecurityLevel", nSecurityLevel);
}
else{
nSecurityLevel = settings.value("nSecurityLevel").toInt();
}
if (!settings.contains("fMinimizeChange")){
fMinimizeChange = false;
settings.setValue("fMinimizeChange", fMinimizeChange);
}
else{
fMinimizeChange = settings.value("fMinimizeChange").toBool();
}
ui->checkBoxMinimizeChange->setChecked(fMinimizeChange);
// Start with displaying the "out of sync" warnings
showOutOfSyncWarning(true);
// Hide those placeholder elements needed for CoinControl interaction
ui->WarningLabel->hide(); // Explanatory text visible in QT-Creator
ui->dummyHideWidget->hide(); // Dummy widget with elements to hide
//temporary disable for maintenance
if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) {
ui->pushButtonMintzBRIGHTCOIN->setEnabled(false);
ui->pushButtonMintzBRIGHTCOIN->setToolTip(tr("zBRIGHTCOIN is currently disabled due to maintenance."));
ui->pushButtonSpendzBRIGHTCOIN->setEnabled(false);
ui->pushButtonSpendzBRIGHTCOIN->setToolTip(tr("zBRIGHTCOIN is currently disabled due to maintenance."));
}
}
PrivacyDialog::~PrivacyDialog()
{
delete ui;
}
void PrivacyDialog::setModel(WalletModel* walletModel)
{
this->walletModel = walletModel;
if (walletModel && walletModel->getOptionsModel()) {
// Keep up to date with wallet
setBalance(walletModel->getBalance(), walletModel->getUnconfirmedBalance(), walletModel->getImmatureBalance(),
walletModel->getZerocoinBalance(), walletModel->getUnconfirmedZerocoinBalance(), walletModel->getImmatureZerocoinBalance(),
walletModel->getWatchBalance(), walletModel->getWatchUnconfirmedBalance(), walletModel->getWatchImmatureBalance());
connect(walletModel, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this,
SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)));
ui->securityLevel->setValue(nSecurityLevel);
}
}
void PrivacyDialog::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void PrivacyDialog::on_addressBookButton_clicked()
{
if (!walletModel)
return;
AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(walletModel->getAddressTableModel());
if (dlg.exec()) {
ui->payTo->setText(dlg.getReturnValue());
ui->zBRIGHTCOINpayAmount->setFocus();
}
}
void PrivacyDialog::on_pushButtonMintzBRIGHTCOIN_clicked()
{
if (!walletModel || !walletModel->getOptionsModel())
return;
if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) {
QMessageBox::information(this, tr("Mint Zerocoin"),
tr("zBRIGHTCOIN is currently undergoing maintenance."), QMessageBox::Ok,
QMessageBox::Ok);
return;
}
// Reset message text
ui->TEMintStatus->setPlainText(tr("Mint Status: Okay"));
// Request unlock if wallet was locked or unlocked for mixing:
WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus();
if (encStatus == walletModel->Locked) {
WalletModel::UnlockContext ctx(walletModel->requestUnlock(true));
if (!ctx.isValid()) {
// Unlock wallet was cancelled
ui->TEMintStatus->setPlainText(tr("Error: Your wallet is locked. Please enter the wallet passphrase first."));
return;
}
}
QString sAmount = ui->labelMintAmountValue->text();
CAmount nAmount = sAmount.toInt() * COIN;
// Minting amount must be > 0
if(nAmount <= 0){
ui->TEMintStatus->setPlainText(tr("Message: Enter an amount > 0."));
return;
}
ui->TEMintStatus->setPlainText(tr("Minting ") + ui->labelMintAmountValue->text() + " zBRIGHTCOIN...");
ui->TEMintStatus->repaint ();
int64_t nTime = GetTimeMillis();
CWalletTx wtx;
vector<CZerocoinMint> vMints;
string strError = pwalletMain->MintZerocoin(nAmount, wtx, vMints, CoinControlDialog::coinControl);
// Return if something went wrong during minting
if (strError != ""){
ui->TEMintStatus->setPlainText(QString::fromStdString(strError));
return;
}
double fDuration = (double)(GetTimeMillis() - nTime)/1000.0;
// Minting successfully finished. Show some stats for entertainment.
QString strStatsHeader = tr("Successfully minted ") + ui->labelMintAmountValue->text() + tr(" zBRIGHTCOIN in ") +
QString::number(fDuration) + tr(" sec. Used denominations:\n");
// Clear amount to avoid double spending when accidentally clicking twice
ui->labelMintAmountValue->setText ("0");
QString strStats = "";
ui->TEMintStatus->setPlainText(strStatsHeader);
for (CZerocoinMint mint : vMints) {
boost::this_thread::sleep(boost::posix_time::milliseconds(100));
strStats = strStats + QString::number(mint.GetDenomination()) + " ";
ui->TEMintStatus->setPlainText(strStatsHeader + strStats);
ui->TEMintStatus->repaint ();
}
// Available balance isn't always updated, so force it.
setBalance(walletModel->getBalance(), walletModel->getUnconfirmedBalance(), walletModel->getImmatureBalance(),
walletModel->getZerocoinBalance(), walletModel->getUnconfirmedZerocoinBalance(), walletModel->getImmatureZerocoinBalance(),
walletModel->getWatchBalance(), walletModel->getWatchUnconfirmedBalance(), walletModel->getWatchImmatureBalance());
coinControlUpdateLabels();
return;
}
void PrivacyDialog::on_pushButtonMintReset_clicked()
{
if (!walletModel || !walletModel->getOptionsModel())
return;
ui->TEMintStatus->setPlainText(tr("Starting ResetMintZerocoin: rescanning complete blockchain, this will need up to 30 minutes depending on your hardware. \nPlease be patient..."));
ui->TEMintStatus->repaint ();
int64_t nTime = GetTimeMillis();
string strResetMintResult = pwalletMain->ResetMintZerocoin(false); // do not do the extended search from GUI
double fDuration = (double)(GetTimeMillis() - nTime)/1000.0;
ui->TEMintStatus->setPlainText(QString::fromStdString(strResetMintResult) + tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n"));
ui->TEMintStatus->repaint ();
return;
}
void PrivacyDialog::on_pushButtonSpentReset_clicked()
{
if (!walletModel || !walletModel->getOptionsModel())
return;
ui->TEMintStatus->setPlainText(tr("Starting ResetSpentZerocoin: "));
ui->TEMintStatus->repaint ();
int64_t nTime = GetTimeMillis();
string strResetSpentResult = pwalletMain->ResetSpentZerocoin();
double fDuration = (double)(GetTimeMillis() - nTime)/1000.0;
ui->TEMintStatus->setPlainText(QString::fromStdString(strResetSpentResult) + tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n"));
ui->TEMintStatus->repaint ();
return;
}
void PrivacyDialog::on_pushButtonSpendzBRIGHTCOIN_clicked()
{
if (!walletModel || !walletModel->getOptionsModel() || !pwalletMain)
return;
if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) {
QMessageBox::information(this, tr("Mint Zerocoin"),
tr("zBRIGHTCOIN is currently undergoing maintenance."), QMessageBox::Ok, QMessageBox::Ok);
return;
}
// Request unlock if wallet was locked or unlocked for mixing:
WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus();
if (encStatus == walletModel->Locked || encStatus == walletModel->UnlockedForAnonymizationOnly) {
WalletModel::UnlockContext ctx(walletModel->requestUnlock(true));
if (!ctx.isValid()) {
// Unlock wallet was cancelled
return;
}
// Wallet is unlocked now, sedn zBRIGHTCOIN
sendzBRIGHTCOIN();
return;
}
// Wallet already unlocked or not encrypted at all, send zBRIGHTCOIN
sendzBRIGHTCOIN();
}
void PrivacyDialog::on_pushButtonZBrightCoinControl_clicked()
{
ZBrightCoinControlDialog* zBrightCoinControl = new ZBrightCoinControlDialog(this);
zBrightCoinControl->setModel(walletModel);
zBrightCoinControl->exec();
}
void PrivacyDialog::setZBrightCoinControlLabels(int64_t nAmount, int nQuantity)
{
ui->labelzBrightCoinSelected_int->setText(QString::number(nAmount));
ui->labelQuantitySelected_int->setText(QString::number(nQuantity));
}
static inline int64_t roundint64(double d)
{
return (int64_t)(d > 0 ? d + 0.5 : d - 0.5);
}
void PrivacyDialog::sendzBRIGHTCOIN()
{
QSettings settings;
// Handle 'Pay To' address options
CBitcoinAddress address(ui->payTo->text().toStdString());
if(ui->payTo->text().isEmpty()){
QMessageBox::information(this, tr("Spend Zerocoin"), tr("No 'Pay To' address provided, creating local payment"), QMessageBox::Ok, QMessageBox::Ok);
}
else{
if (!address.IsValid()) {
QMessageBox::warning(this, tr("Spend Zerocoin"), tr("Invalid BrightCoin Address"), QMessageBox::Ok, QMessageBox::Ok);
ui->payTo->setFocus();
return;
}
}
// Double is allowed now
double dAmount = ui->zBRIGHTCOINpayAmount->text().toDouble();
CAmount nAmount = roundint64(dAmount* COIN);
// Check amount validity
if (!MoneyRange(nAmount) || nAmount <= 0.0) {
QMessageBox::warning(this, tr("Spend Zerocoin"), tr("Invalid Send Amount"), QMessageBox::Ok, QMessageBox::Ok);
ui->zBRIGHTCOINpayAmount->setFocus();
return;
}
// Convert change to zBRIGHTCOIN
bool fMintChange = ui->checkBoxMintChange->isChecked();
// Persist minimize change setting
fMinimizeChange = ui->checkBoxMinimizeChange->isChecked();
settings.setValue("fMinimizeChange", fMinimizeChange);
// Warn for additional fees if amount is not an integer and change as zBRIGHTCOIN is requested
bool fWholeNumber = floor(dAmount) == dAmount;
double dzFee = 0.0;
if(!fWholeNumber)
dzFee = 1.0 - (dAmount - floor(dAmount));
if(!fWholeNumber && fMintChange){
QString strFeeWarning = "You've entered an amount with fractional digits and want the change to be converted to Zerocoin.<br /><br /><b>";
strFeeWarning += QString::number(dzFee, 'f', 8) + " BRIGHTCOIN </b>will be added to the standard transaction fees!<br />";
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm additional Fees"),
strFeeWarning,
QMessageBox::Yes | QMessageBox::Cancel,
QMessageBox::Cancel);
if (retval != QMessageBox::Yes) {
// Sending canceled
ui->zBRIGHTCOINpayAmount->setFocus();
return;
}
}
// Persist Security Level for next start
nSecurityLevel = ui->securityLevel->value();
settings.setValue("nSecurityLevel", nSecurityLevel);
// Spend confirmation message box
// Add address info if available
QString strAddressLabel = "";
if(!ui->payTo->text().isEmpty() && !ui->addAsLabel->text().isEmpty()){
strAddressLabel = "<br />(" + ui->addAsLabel->text() + ") ";
}
// General info
QString strQuestionString = tr("Are you sure you want to send?<br /><br />");
QString strAmount = "<b>" + QString::number(dAmount, 'f', 8) + " zBRIGHTCOIN</b>";
QString strAddress = tr(" to address ") + QString::fromStdString(address.ToString()) + strAddressLabel + " <br />";
if(ui->payTo->text().isEmpty()){
// No address provided => send to local address
strAddress = tr(" to a newly generated (unused and therefore anonymous) local address <br />");
}
QString strSecurityLevel = tr("with Security Level ") + ui->securityLevel->text() + " ?";
strQuestionString += strAmount + strAddress + strSecurityLevel;
// Display message box
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
strQuestionString,
QMessageBox::Yes | QMessageBox::Cancel,
QMessageBox::Cancel);
if (retval != QMessageBox::Yes) {
// Sending canceled
return;
}
int64_t nTime = GetTimeMillis();
ui->TEMintStatus->setPlainText(tr("Spending Zerocoin.\nComputationally expensive, might need several minutes depending on the selected Security Level and your hardware. \nPlease be patient..."));
ui->TEMintStatus->repaint();
// use mints from zBrightCoin selector if applicable
vector<CZerocoinMint> vMintsSelected;
if (!ZBrightCoinControlDialog::listSelectedMints.empty()) {
vMintsSelected = ZBrightCoinControlDialog::GetSelectedMints();
}
// Spend zBRIGHTCOIN
CWalletTx wtxNew;
CZerocoinSpendReceipt receipt;
bool fSuccess = false;
if(ui->payTo->text().isEmpty()){
// Spend to newly generated local address
fSuccess = pwalletMain->SpendZerocoin(nAmount, nSecurityLevel, wtxNew, receipt, vMintsSelected, fMintChange, fMinimizeChange);
}
else {
// Spend to supplied destination address
fSuccess = pwalletMain->SpendZerocoin(nAmount, nSecurityLevel, wtxNew, receipt, vMintsSelected, fMintChange, fMinimizeChange, &address);
}
// Display errors during spend
if (!fSuccess) {
int nNeededSpends = receipt.GetNeededSpends(); // Number of spends we would need for this transaction
const int nMaxSpends = Params().Zerocoin_MaxSpendsPerTransaction(); // Maximum possible spends for one zBRIGHTCOIN transaction
if (nNeededSpends > nMaxSpends) {
QString strStatusMessage = tr("Too much inputs (") + QString::number(nNeededSpends, 10) + tr(") needed. \nMaximum allowed: ") + QString::number(nMaxSpends, 10);
strStatusMessage += tr("\nEither mint higher denominations (so fewer inputs are needed) or reduce the amount to spend.");
QMessageBox::warning(this, tr("Spend Zerocoin"), strStatusMessage.toStdString().c_str(), QMessageBox::Ok, QMessageBox::Ok);
ui->TEMintStatus->setPlainText(tr("Spend Zerocoin failed with status = ") +QString::number(receipt.GetStatus(), 10) + "\n" + "Message: " + QString::fromStdString(strStatusMessage.toStdString()));
}
else {
QMessageBox::warning(this, tr("Spend Zerocoin"), receipt.GetStatusMessage().c_str(), QMessageBox::Ok, QMessageBox::Ok);
ui->TEMintStatus->setPlainText(tr("Spend Zerocoin failed with status = ") +QString::number(receipt.GetStatus(), 10) + "\n" + "Message: " + QString::fromStdString(receipt.GetStatusMessage()));
}
ui->zBRIGHTCOINpayAmount->setFocus();
ui->TEMintStatus->repaint();
return;
}
// Clear zbrightcoin selector in case it was used
ZBrightCoinControlDialog::listSelectedMints.clear();
// Some statistics for entertainment
QString strStats = "";
CAmount nValueIn = 0;
int nCount = 0;
for (CZerocoinSpend spend : receipt.GetSpends()) {
strStats += tr("zBrightCoin Spend #: ") + QString::number(nCount) + ", ";
strStats += tr("denomination: ") + QString::number(spend.GetDenomination()) + ", ";
strStats += tr("serial: ") + spend.GetSerial().ToString().c_str() + "\n";
strStats += tr("Spend is 1 of : ") + QString::number(spend.GetMintCount()) + " mints in the accumulator\n";
nValueIn += libzerocoin::ZerocoinDenominationToAmount(spend.GetDenomination());
}
CAmount nValueOut = 0;
for (const CTxOut& txout: wtxNew.vout) {
strStats += tr("value out: ") + FormatMoney(txout.nValue).c_str() + " BrightCoin, ";
nValueOut += txout.nValue;
strStats += tr("address: ");
CTxDestination dest;
if(txout.scriptPubKey.IsZerocoinMint())
strStats += tr("zBrightCoin Mint");
else if(ExtractDestination(txout.scriptPubKey, dest))
strStats += tr(CBitcoinAddress(dest).ToString().c_str());
strStats += "\n";
}
double fDuration = (double)(GetTimeMillis() - nTime)/1000.0;
strStats += tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n");
strStats += tr("Sending successful, return code: ") + QString::number(receipt.GetStatus()) + "\n";
QString strReturn;
strReturn += tr("txid: ") + wtxNew.GetHash().ToString().c_str() + "\n";
strReturn += tr("fee: ") + QString::fromStdString(FormatMoney(nValueIn-nValueOut)) + "\n";
strReturn += strStats;
// Clear amount to avoid double spending when accidentally clicking twice
ui->zBRIGHTCOINpayAmount->setText ("0");
ui->TEMintStatus->setPlainText(strReturn);
ui->TEMintStatus->repaint();
}
void PrivacyDialog::on_payTo_textChanged(const QString& address)
{
updateLabel(address);
}
// Coin Control: copy label "Quantity" to clipboard
void PrivacyDialog::coinControlClipboardQuantity()
{
GUIUtil::setClipboard(ui->labelCoinControlQuantity->text());
}
// Coin Control: copy label "Amount" to clipboard
void PrivacyDialog::coinControlClipboardAmount()
{
GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
}
// Coin Control: button inputs -> show actual coin control dialog
void PrivacyDialog::coinControlButtonClicked()
{
CoinControlDialog dlg;
dlg.setModel(walletModel);
dlg.exec();
coinControlUpdateLabels();
}
// Coin Control: update labels
void PrivacyDialog::coinControlUpdateLabels()
{
if (!walletModel || !walletModel->getOptionsModel() || !walletModel->getOptionsModel()->getCoinControlFeatures())
return;
// set pay amounts
CoinControlDialog::payAmounts.clear();
if (CoinControlDialog::coinControl->HasSelected()) {
// Actual coin control calculation
CoinControlDialog::updateLabels(walletModel, this);
} else {
ui->labelCoinControlQuantity->setText (tr("Coins automatically selected"));
ui->labelCoinControlAmount->setText (tr("Coins automatically selected"));
}
}
bool PrivacyDialog::updateLabel(const QString& address)
{
if (!walletModel)
return false;
// Fill in label from address book, if address has an associated label
QString associatedLabel = walletModel->getAddressTableModel()->labelForAddress(address);
if (!associatedLabel.isEmpty()) {
ui->addAsLabel->setText(associatedLabel);
return true;
}
return false;
}
void PrivacyDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance,
const CAmount& zerocoinBalance, const CAmount& unconfirmedZerocoinBalance, const CAmount& immatureZerocoinBalance,
const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance)
{
currentBalance = balance;
currentUnconfirmedBalance = unconfirmedBalance;
currentImmatureBalance = immatureBalance;
currentZerocoinBalance = zerocoinBalance;
currentUnconfirmedZerocoinBalance = unconfirmedZerocoinBalance;
currentImmatureZerocoinBalance = immatureZerocoinBalance;
currentWatchOnlyBalance = watchOnlyBalance;
currentWatchUnconfBalance = watchUnconfBalance;
currentWatchImmatureBalance = watchImmatureBalance;
CWalletDB walletdb(pwalletMain->strWalletFile);
list<CZerocoinMint> listMints = walletdb.ListMintedCoins(true, false, true);
std::map<libzerocoin::CoinDenomination, CAmount> mapDenomBalances;
std::map<libzerocoin::CoinDenomination, int> mapUnconfirmed;
std::map<libzerocoin::CoinDenomination, int> mapImmature;
for (const auto& denom : libzerocoin::zerocoinDenomList){
mapDenomBalances.insert(make_pair(denom, 0));
mapUnconfirmed.insert(make_pair(denom, 0));
mapImmature.insert(make_pair(denom, 0));
}
for (auto& mint : listMints){
// All denominations
mapDenomBalances.at(mint.GetDenomination())++;
if (!mint.GetHeight() || chainActive.Height() - mint.GetHeight() <= Params().Zerocoin_MintRequiredConfirmations()) {
// All unconfirmed denominations
mapUnconfirmed.at(mint.GetDenomination())++;
}
else {
// After a denomination is confirmed it might still be immature because < 3 of the same denomination were minted after it
CBlockIndex *pindex = chainActive[mint.GetHeight() + 1];
int nMintsAdded = 0;
while (pindex->nHeight < chainActive.Height() - 30) { // 30 just to make sure that its at least 2 checkpoints from the top block
nMintsAdded += count(pindex->vMintDenominationsInBlock.begin(), pindex->vMintDenominationsInBlock.end(), mint.GetDenomination());
if (nMintsAdded >= Params().Zerocoin_RequiredAccumulation())
break;
pindex = chainActive[pindex->nHeight + 1];
}
if (nMintsAdded < Params().Zerocoin_RequiredAccumulation()){
// Immature denominations
mapImmature.at(mint.GetDenomination())++;
}
}
}
int64_t nCoins = 0;
int64_t nSumPerCoin = 0;
int64_t nUnconfirmed = 0;
int64_t nImmature = 0;
QString strDenomStats, strUnconfirmed = "";
for (const auto& denom : libzerocoin::zerocoinDenomList) {
nCoins = libzerocoin::ZerocoinDenominationToInt(denom);
nSumPerCoin = nCoins * mapDenomBalances.at(denom);
nUnconfirmed = mapUnconfirmed.at(denom);
nImmature = mapImmature.at(denom);
strUnconfirmed = "";
if (nUnconfirmed) {
strUnconfirmed += QString::number(nUnconfirmed) + QString(" unconf. ");
}
if(nImmature) {
strUnconfirmed += QString::number(nImmature) + QString(" immature ");
}
if(nImmature || nUnconfirmed) {
strUnconfirmed = QString("( ") + strUnconfirmed + QString(") ");
}
strDenomStats = strUnconfirmed + QString::number(mapDenomBalances.at(denom)) + " x " +
QString::number(nCoins) + " = <b>" +
QString::number(nSumPerCoin) + " zBRIGHTCOIN </b>";
switch (nCoins) {
case libzerocoin::CoinDenomination::ZQ_ONE:
ui->labelzDenom1Amount->setText(strDenomStats);
break;
case libzerocoin::CoinDenomination::ZQ_FIVE:
ui->labelzDenom2Amount->setText(strDenomStats);
break;
case libzerocoin::CoinDenomination::ZQ_TEN:
ui->labelzDenom3Amount->setText(strDenomStats);
break;
case libzerocoin::CoinDenomination::ZQ_FIFTY:
ui->labelzDenom4Amount->setText(strDenomStats);
break;
case libzerocoin::CoinDenomination::ZQ_ONE_HUNDRED:
ui->labelzDenom5Amount->setText(strDenomStats);
break;
case libzerocoin::CoinDenomination::ZQ_FIVE_HUNDRED:
ui->labelzDenom6Amount->setText(strDenomStats);
break;
case libzerocoin::CoinDenomination::ZQ_ONE_THOUSAND:
ui->labelzDenom7Amount->setText(strDenomStats);
break;
case libzerocoin::CoinDenomination::ZQ_FIVE_THOUSAND:
ui->labelzDenom8Amount->setText(strDenomStats);
break;
default:
// Error Case: don't update display
break;
}
}
CAmount matureZerocoinBalance = zerocoinBalance - immatureZerocoinBalance;
CAmount nLockedBalance = 0;
if (walletModel) {
nLockedBalance = walletModel->getLockedBalance();
}
ui->labelzAvailableAmount->setText(QString::number(zerocoinBalance/COIN) + QString(" zBRIGHTCOIN "));
ui->labelzAvailableAmount_2->setText(QString::number(matureZerocoinBalance/COIN) + QString(" zBRIGHTCOIN "));
ui->labelzBRIGHTCOINAmountValue->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance - immatureBalance - nLockedBalance, false, BitcoinUnits::separatorAlways));
}
void PrivacyDialog::updateDisplayUnit()
{
if (walletModel && walletModel->getOptionsModel()) {
nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit();
if (currentBalance != -1)
setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance,
currentZerocoinBalance, currentUnconfirmedZerocoinBalance, currentImmatureZerocoinBalance,
currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance);
}
}
void PrivacyDialog::showOutOfSyncWarning(bool fShow)
{
ui->labelzBRIGHTCOINSyncStatus->setVisible(fShow);
}
void PrivacyDialog::keyPressEvent(QKeyEvent* event)
{
if (event->key() != Qt::Key_Escape) // press esc -> ignore
{
this->QDialog::keyPressEvent(event);
} else {
event->ignore();
}
}
| [
"admin@brightcoin.cc"
] | admin@brightcoin.cc |
0495eeb126da1679a24b306efe5f4323feecf691 | 711e5c8b643dd2a93fbcbada982d7ad489fb0169 | /XPSP1/NT/inetsrv/iis/iisrearc/iisplus/ulatq/ipm_io_c.cxx | ea88b141030c06bf486a82d7bca0ea606b878895 | [] | no_license | aurantst/windows-XP-SP1 | 629a7763c082fd04d3b881e0d32a1cfbd523b5ce | d521b6360fcff4294ae6c5651c539f1b9a6cbb49 | refs/heads/master | 2023-03-21T01:08:39.870106 | 2020-09-28T08:10:11 | 2020-09-28T08:10:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,057 | cxx | /*++
Copyright (c) 1999 Microsoft Corporation
Module Name:
ipm_io_c.hxx
Abstract:
This module contains classes for doing async io in the
worker process.
Author:
Michael Courage (MCourage) 22-Feb-1999
Revision History:
--*/
#include "precomp.hxx"
#include "ipm.hxx"
#include "ipm_io_c.hxx"
/**
* IPMOverlappedCompletionRoutine()
* Callback function provided in ThreadPoolBindIoCompletionCallback.
* This function is called by NT thread pool.
*
* dwErrorCode Error Code
* dwNumberOfBytesTransfered Number of Bytes Transfered
* lpOverlapped Overlapped structure
*/
VOID
WINAPI
IPMOverlappedCompletionRoutine(
DWORD dwErrorCode,
DWORD dwNumberOfBytesTransfered,
LPOVERLAPPED lpOverlapped
)
{
IO_CONTEXT_C * pIoContext = NULL;
HRESULT hr = HRESULT_FROM_WIN32(dwErrorCode);
//
// get the context object
//
if (lpOverlapped != NULL)
{
pIoContext = CONTAINING_RECORD(lpOverlapped,
IO_CONTEXT_C,
m_Overlapped);
}
if ( pIoContext != NULL)
{
WpTrace(WPIPM, (
DBG_CONTEXT,
"\n IPMOverlappedCompletionRoutine(%d, %x, pIoContext %x) %s\n",
dwNumberOfBytesTransfered,
dwErrorCode,
pIoContext,
pIoContext->m_IoType == IPM_IO_WRITE ? "WRITE" : "READ"
));
//
// do the notification
//
switch (pIoContext->m_IoType) {
case IPM_IO_WRITE:
pIoContext->m_pContext->NotifyWriteCompletion(
pIoContext->m_pv,
dwNumberOfBytesTransfered,
hr
);
break;
case IPM_IO_READ:
pIoContext->m_pContext->NotifyReadCompletion(
pIoContext->m_pv,
dwNumberOfBytesTransfered,
hr
);
break;
default:
DBG_ASSERT(FALSE);
break;
}
delete pIoContext;
}
return;
}
/**
*
* Routine Description:
*
*
* Creates an i/o handler
*
* Arguments:
*
* hPipe - A handle to the named pipe to be handled
* ppPipeIoHandler - receives a pointer to the handler on success
*
* Return Value:
*
* HRESULT
*/
HRESULT
IO_FACTORY_C::CreatePipeIoHandler(
IN HANDLE hPipe,
OUT PIPE_IO_HANDLER ** ppPipeIoHandler
)
{
HRESULT hr = S_OK;
IO_HANDLER_C * pHandler;
//
// create the object
//
pHandler = new IO_HANDLER_C(hPipe);
if (pHandler)
{
BOOL fBind;
//
// bind handle to completion port
//
fBind = ThreadPoolBindIoCompletionCallback(
pHandler->GetAsyncHandle(),
IPMOverlappedCompletionRoutine,
0 );
if (fBind) {
*ppPipeIoHandler = pHandler;
InterlockedIncrement(&m_cPipes);
pHandler->Reference();
WpTrace(WPIPM, (
DBG_CONTEXT,
"Created IO_HANDLER_C (%x) - m_cPipes = %d\n",
pHandler,
m_cPipes
));
}
else
{
// Error in XspBindIoCompletionCallback()
LONG rc = GetLastError();
delete pHandler;
pHandler = NULL;
WpTrace(WPIPM, (DBG_CONTEXT, "Create IO_HANDLER_C failed, %d\n", rc));
hr = HRESULT_FROM_WIN32(rc);
}
}
else
{
hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
}
return hr;
}
/**
*
* Routine Description:
*
* Closes an i/o handler
*
* Arguments:
*
* pPipeIoHandler - pointer to the handler to be closed
*
* Return Value:
*
* HRESULT
*/
HRESULT
IO_FACTORY_C::ClosePipeIoHandler(
IN PIPE_IO_HANDLER * pPipeIoHandler
)
{
IO_HANDLER_C * pIoHandler = (IO_HANDLER_C *) pPipeIoHandler;
LONG cPipes;
if (pIoHandler) {
cPipes = InterlockedDecrement(&m_cPipes);
WpTrace(WPIPM, (
DBG_CONTEXT,
"Closed IO_HANDLER_C (%x) - m_cPipes = %d\n",
pPipeIoHandler,
m_cPipes
));
DBG_ASSERT( cPipes >= 0 );
pIoHandler->Dereference();
return S_OK;
} else {
return HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER);
}
}
/**
* Disconnect()
* Routine Description:
*
* Disconnects the named pipe
*
* Arguments:
*
* None.
*
* Return Value:
*
* HRESULT
*
*/
HRESULT
IO_HANDLER_C::Disconnect(
VOID
)
{
HRESULT hr = S_OK;
CheckSignature();
if (!CloseHandle(GetHandle())) {
hr = HRESULT_FROM_WIN32(GetLastError());
}
return hr;
}
/**
*
*Routine Description:
*
* Writes data to the pipe
*
*Arguments:
*
* pContext - the context to be notified on completion
* pv - a parameter passed to the context
* pBuff - the data to send
* cbBuff - number of bytes in the data
*
*Return Value:
*
* HRESULT
*/
HRESULT
IO_HANDLER_C::Write(
IN IO_CONTEXT * pContext,
IN PVOID pv,
IN const BYTE * pBuff,
IN DWORD cbBuff
)
{
HRESULT hr = S_OK;
IO_CONTEXT_C * pIoContext;
CheckSignature();
//
// create a context
//
pIoContext = new IO_CONTEXT_C;
if (pIoContext) {
pIoContext->m_pContext = pContext;
pIoContext->m_pv = pv;
pIoContext->m_IoType = IPM_IO_WRITE;
memset(&pIoContext->m_Overlapped, 0, sizeof(OVERLAPPED));
Reference();
//
// write to the pipe
//
hr = IpmWriteFile(
GetHandle(),
(PVOID) pBuff,
cbBuff,
&pIoContext->m_Overlapped
);
if (FAILED(hr))
{
Dereference();
}
} else {
hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
}
if (FAILED(hr)) {
delete pIoContext;
}
return hr;
}
/**
*
*Routine Description:
*
* Reads data from the pipe
*
*Arguments:
*
* pContext - the context to be notified on completion
* pv - a parameter passed to the context
* pBuff - the buffer that receives the data
* cbBuff - size of the buffer
*
*Return Value:
*
* HRESULT
*/
HRESULT
IO_HANDLER_C::Read(
IN IO_CONTEXT * pContext,
IN PVOID pv,
IN BYTE * pBuff,
IN DWORD cbBuff
)
{
HRESULT hr = S_OK;
IO_CONTEXT_C * pIoContext;
CheckSignature();
//
// create a context
//
pIoContext = new IO_CONTEXT_C;
if (pIoContext) {
pIoContext->m_pContext = pContext;
pIoContext->m_pv = pv;
pIoContext->m_IoType = IPM_IO_READ;
memset(&pIoContext->m_Overlapped, 0, sizeof(OVERLAPPED));
Reference();
//
// read from the pipe
//
hr = IpmReadFile(
GetHandle(),
pBuff,
cbBuff,
&pIoContext->m_Overlapped
);
if (FAILED(hr))
{
Dereference();
}
} else {
hr = HRESULT_FROM_WIN32(ERROR_NOT_ENOUGH_MEMORY);
}
if (FAILED(hr)) {
delete pIoContext;
}
return hr;
}
//
// end ipm_io_c.cxx
//
| [
"112426112@qq.com"
] | 112426112@qq.com |
5a9bdff4d70f193e5af9afd8974494c7bdca6536 | 874fd3e28319bf6042b72c580aad3018d2fa35fb | /src/binaryServer/logging/ClientSdkLoggerFactory.cpp | df8e22180be19037c7ef70935e52ba6b7fc8779b | [
"Apache-2.0"
] | permissive | menucha-de/OPC-UA.Server | 43e50962afe631765693575bf80f5c6a6467f004 | ebfafb0f9a1943fc1f2d44f20a0497a59e5bfd97 | refs/heads/main | 2023-03-24T16:29:13.864707 | 2021-03-19T14:28:36 | 2021-03-19T14:28:36 | 349,453,071 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,123 | cpp | #include "ClientSdkLoggerFactory.h"
#include "ClientSdkLogger.h"
#include <common/Mutex.h>
#include <common/MutexLock.h>
#include <stdio.h> // fprintf
#include <map>
using namespace CommonNamespace;
class ClientSdkLoggerFactoryPrivate {
friend class ClientSdkLoggerFactory;
private:
std::map<const char*, Logger*> loggers;
Mutex* mutex;
};
ClientSdkLoggerFactory::ClientSdkLoggerFactory() /*throws MutexException*/ {
d = new ClientSdkLoggerFactoryPrivate();
d->mutex = new Mutex(); // MutexException
}
ClientSdkLoggerFactory::~ClientSdkLoggerFactory() {
// delete loggers
for (std::map<const char*, Logger*>::const_iterator it = d->loggers.begin();
it != d->loggers.end(); it++) {
delete it->second;
}
delete d;
}
Logger* ClientSdkLoggerFactory::getLogger(const char* name) {
MutexLock lock(*d->mutex);
std::map<const char*, Logger*>::const_iterator it = d->loggers.find(name);
if (it == d->loggers.end()) {
Logger* logger = new ClientSdkLogger(name);
d->loggers[name] = logger;
return logger;
}
return it->second;
}
| [
"info@menucha.de"
] | info@menucha.de |
e584b825b28a6150ba63281630eb0edd4e54e0c1 | ecb2798c0529d23ed7e32f28578b23affd180ce1 | /Assignment 3/src/Demos/SierpinskiBungeeJumpGUI.cpp | c61d366135a02bbac6e9a7c9752b020b8a3e01f3 | [] | no_license | zjulsh/cs106b_2019 | 259305efbfce685ab91d5b771653a011b3aac478 | 9cd4a107fc24edfda18dc67372ce370b957d0404 | refs/heads/master | 2021-04-10T19:26:49.398285 | 2020-03-21T11:15:13 | 2020-03-21T11:15:13 | 248,958,721 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,445 | cpp | #include "ProblemHandler.h"
#include "Sierpinski.h"
#include "GUIUtils.h"
#include "GVector.h"
#include "gtimer.h"
#include <algorithm>
using namespace std;
namespace {
const string kBackgroundColor = "#FFFFFF";
const string kBorderColor = "#4C516D"; // Independence
/* Timing parameters. */
const int kFramesPerSecond = 100;
const double kPauseTime = 1000.0 / kFramesPerSecond;
const int kFramesPerAnimation = 100;
/* Triangle parameters. */
const int kOrder = 8;
/* Height of an equilateral triangle with unit side length. */
const double kEquilateralHeight = sqrt(3.0) / 2.0;
/* Computes the centroid of three points. */
GPoint centroidOf(const GPoint& p0, const GPoint& p1, const GPoint& p2) {
return {
(p0.getX() + p1.getX() + p2.getX()) / 3.0,
(p0.getY() + p1.getY() + p2.getY()) / 3.0
};
}
/* Problem handler to do a deep dive into the Sierpinski triangle. */
class SierpinskiBungeeJumpGUI: public ProblemHandler {
public:
SierpinskiBungeeJumpGUI(GWindow& window);
~SierpinskiBungeeJumpGUI();
void timerFired() override;
protected:
void repaint(GWindow& window) override;
private:
GTimer* mTimer;
int mFrame = 0; // Which animation frame we're on
GPoint mPoints[3]; // Control points of the triangle
GPoint mCentroid; // Centroid of rotation
};
}
SierpinskiBungeeJumpGUI::SierpinskiBungeeJumpGUI(GWindow& window) : mTimer(new GTimer(kPauseTime)) {
mTimer->start();
/* We want our triangle to be an equilateral triangle that's as large as possible
* while still fitting into the window. Compute the scale factor to use assuming we
* have a unit triangle.
*/
double scale = min(window.getCanvasWidth(), window.getCanvasHeight() / kEquilateralHeight);
double width = 1.0 * scale;
double height = kEquilateralHeight * scale;
/* Use that to compute our origin points. */
double baseX = (window.getCanvasWidth() - width) / 2.0;
double baseY = (window.getCanvasHeight() - height) / 2.0;
/* Compute the points of the corners of our triangle. */
mPoints[0] = { baseX, baseY + height };
mPoints[1] = { baseX + width, baseY + height };
mPoints[2] = { baseX + width / 2, baseY };
mCentroid = centroidOf(mPoints[0], mPoints[1], mPoints[2]);
}
SierpinskiBungeeJumpGUI::~SierpinskiBungeeJumpGUI() {
/* TODO: There seems to be a bug in GTimer that causes major problems if we use an
* actual GTimer object here rather than a pointer to one. Fix the leak and
* remove this destructor.
*/
mTimer->stop();
}
void SierpinskiBungeeJumpGUI::timerFired() {
if (mTimer->isStarted()) {
mFrame++;
if (mFrame == kFramesPerAnimation) mFrame = 0;
requestRepaint();
}
}
void SierpinskiBungeeJumpGUI::repaint(GWindow& window) {
clearDisplay(window, kBackgroundColor);
/* See where we are in this animation. */
double alpha = mFrame / double(kFramesPerAnimation);
/* Imagine we have this starting triangle
*
* p2
* /\
* /--\
* /\ /\
* /--\/--\
* /\ /\
* /--\ C/--\
* /\ /\ /\ /\
* /--\/--\/--\/--\
* p0 A^^^^B p1
*
* We want to end up such that
*
* point A ends up where p2 used to be,
* point B ends up where p0 used to be, and
* point C ends up where p1 used to be.
*
* This corresponds to
*
* 1. rotating the entire figure around the centroid of triangle ABC by 120 degrees, then
* 2. doubling the size of the entire figure, centering around the the centroid of ABC.
*
* We'll compute the rotation and scale based on the progress that we've made so far.
*
* There's one last effect to take into account. If we purely zoom into the center of this
* triangle, we'll end up looking in pure whitespace. We need to also slightly translate
* everything over a bit; specifically, so that the triangle in the top becomes the new
* center point.
*
* To do this, we'll compute the centroid of that new triangle and interpolate it over
* into position.
*/
GPoint sticky = mPoints[0];
auto anchor = centroidOf(mPoints[0] + (sticky - mPoints[0]) / 2,
mPoints[1] + (sticky - mPoints[1]) / 2,
mPoints[2] + (sticky - mPoints[2]) / 2);
/* Rotate everything around that point. */
double theta = alpha * 2 * M_PI / 3;
GPoint p0 = mCentroid + (rotate(mPoints[0] - mCentroid, theta));
GPoint p1 = mCentroid + (rotate(mPoints[1] - mCentroid, theta));
GPoint p2 = mCentroid + (rotate(mPoints[2] - mCentroid, theta));
anchor = mCentroid + (rotate(anchor - mCentroid, theta));
/* Scale everything around that point. */
p0 += alpha * (p0 - mCentroid);
p1 += alpha * (p1 - mCentroid);
p2 += alpha * (p2 - mCentroid);
anchor += alpha * (anchor - mCentroid);
/* Determine how much to shift everything over based on the anchor point. */
auto shift = (mCentroid - anchor) * alpha;
p0 += shift;
p1 += shift;
p2 += shift;
/* Draw our triangle! */
drawSierpinskiTriangle(window,
p0.getX(), p0.getY(),
p1.getX(), p1.getY(),
p2.getX(), p2.getY(),
kOrder);
/* Draw the borders to avoid revealing the detail that when the rotation finishes, the
* triangle isn't actually adjacent to bordering triangles in the same way that the original
* one was. :-)
*/
window.setColor(kBorderColor);
/* Sides */
window.fillRect(0, 0, mPoints[0].getX(), window.getCanvasHeight());
window.fillRect(mPoints[1].getX(), 0, window.getCanvasWidth() - mPoints[1].getX(), window.getCanvasHeight());
/* Top and bottom */
window.fillRect(0, 0, window.getCanvasWidth(), mPoints[2].getY());
window.fillRect(0, mPoints[0].getY(), window.getCanvasWidth(), window.getCanvasHeight() - mPoints[0].getY());
}
shared_ptr<ProblemHandler> makeBungeeJumpGUI(GWindow& window) {
return make_shared<SierpinskiBungeeJumpGUI>(window);
}
| [
"865835320@qq.com"
] | 865835320@qq.com |
369ff84ed0fe739311a8ea2971775372331315b3 | 5fd1de174f907a7625e798df35c8d07a7fce3f2b | /tests/formatstest.cpp | 25172101a671292b61d0504c3cc53a134b749381 | [
"BSD-3-Clause"
] | permissive | jeremyrearle/XtalOpt | 1172b1e2c6eff2d5b58eb03d46619d0c61706729 | a87aed2cf55db97d072db5f5a9fc03344c9ed46d | refs/heads/master | 2021-07-07T02:10:40.315890 | 2017-09-21T14:02:16 | 2017-09-21T14:04:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,010 | cpp | /**********************************************************************
Formats test - test our file format readers and writers
Copyright (C) 2017 Patrick Avery
This source code is released under the New BSD License, (the "License").
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 <globalsearch/formats/obconvert.h>
#include <globalsearch/formats/cmlformat.h>
#include <globalsearch/formats/poscarformat.h>
#include <globalsearch/formats/formats.h>
#include <globalsearch/structure.h>
#include <QDebug>
#include <QString>
#include <QtTest>
#include <sstream>
using GlobalSearch::Vector3;
class FormatsTest : public QObject
{
Q_OBJECT
// Members
GlobalSearch::Structure m_rutile;
GlobalSearch::Structure m_caffeine;
private slots:
/**
* Called before the first test function is executed.
*/
void initTestCase();
/**
* Called after the last test function is executed.
*/
void cleanupTestCase();
/**
* Called before each test function is executed.
*/
void init();
/**
* Called after every test function.
*/
void cleanup();
// Tests
void readPoscar();
void writePoscar();
void readCml();
void writeCml();
void OBConvert();
// Different optimizer formats
void readCastep();
void readGulp();
void readPwscf();
void readSiesta();
void readVasp();
};
void FormatsTest::initTestCase()
{
}
void FormatsTest::cleanupTestCase()
{
}
void FormatsTest::init()
{
}
void FormatsTest::cleanup()
{
}
void FormatsTest::readPoscar()
{
/**** Rutile ****/
QString rutileFileName = QString(TESTDATADIR) + "/data/rutile.POSCAR";
GlobalSearch::Structure rutile;
QVERIFY(GlobalSearch::Formats::read(&rutile, rutileFileName, "POSCAR"));
// Our structure should have a unit cell, 6 atoms, and no bonds
// The unit cell volume should be about 62.423
QVERIFY(rutile.hasUnitCell());
QVERIFY(rutile.numAtoms() == 6);
QVERIFY(rutile.numBonds() == 0);
QVERIFY(abs(62.4233 - rutile.unitCell().volume()) < 1.e-5);
// The sixth atom should be Ti and should have cartesian coordinates of
// (1.47906 2.29686 2.29686)
double tol = 1.e-5;
Vector3 rutileAtom2Pos(1.47906, 2.29686, 2.29686);
QVERIFY(rutile.atom(5).atomicNumber() == 22);
QVERIFY(GlobalSearch::fuzzyCompare(rutile.atom(5).pos(),
rutileAtom2Pos, tol));
// The first atom should be O and should have fractional coordinates of
// 0, 0.3053, 0.3053
tol = 1.e-5;
Vector3 rutileAtom3Ref =
rutile.unitCell().toFractional(rutile.atom(0).pos());
Vector3 rutileAtom3PosFrac(0.0, 0.3053, 0.3053);
QVERIFY(rutile.atom(0).atomicNumber() == 8);
QVERIFY(GlobalSearch::fuzzyCompare(rutileAtom3Ref, rutileAtom3PosFrac, tol));
// Let's set rutile to be used for the write test
m_rutile = rutile;
}
void FormatsTest::writePoscar()
{
// First, write the POSCAR file to a stringstream
std::stringstream ss;
QVERIFY(GlobalSearch::PoscarFormat::write(m_rutile, ss));
// Now read from it and run the same tests we tried above
/**** Rutile ****/
GlobalSearch::Structure rutile;
QVERIFY(GlobalSearch::PoscarFormat::read(rutile, ss));
// Our structure should have a unit cell, 6 atoms, and no bonds
// The unit cell volume should be about 62.423
QVERIFY(rutile.hasUnitCell());
QVERIFY(rutile.numAtoms() == 6);
QVERIFY(rutile.numBonds() == 0);
QVERIFY(abs(62.4233 - rutile.unitCell().volume()) < 1.e-5);
// The sixth atom should be Ti and should have cartesian coordinates of
// (1.47906 2.29686 2.29686)
double tol = 1.e-5;
Vector3 rutileAtom2Pos(1.47906, 2.29686, 2.29686);
QVERIFY(rutile.atom(5).atomicNumber() == 22);
QVERIFY(GlobalSearch::fuzzyCompare(rutile.atom(5).pos(),
rutileAtom2Pos, tol));
// The first atom should be O and should have fractional coordinates of
// 0, 0.3053, 0.3053
tol = 1.e-5;
Vector3 rutileAtom3Ref =
rutile.unitCell().toFractional(rutile.atom(0).pos());
Vector3 rutileAtom3PosFrac(0.0, 0.3053, 0.3053);
QVERIFY(rutile.atom(0).atomicNumber() == 8);
QVERIFY(GlobalSearch::fuzzyCompare(rutileAtom3Ref, rutileAtom3PosFrac, tol));
}
void FormatsTest::readCml()
{
/**** Rutile ****/
QString rutileFileName = QString(TESTDATADIR) + "/data/rutile.cml";
GlobalSearch::Structure rutile;
QVERIFY(GlobalSearch::Formats::read(&rutile, rutileFileName, "cml"));
// Our structure should have a unit cell, 6 atoms, and no bonds
// The unit cell volume should be about 62.423
QVERIFY(rutile.hasUnitCell());
QVERIFY(rutile.numAtoms() == 6);
QVERIFY(rutile.numBonds() == 0);
QVERIFY(abs(62.4233 - rutile.unitCell().volume()) < 1.e-5);
// The second atom should be Ti and should have cartesian coordinates of
// (1.47906 2.29686 2.29686)
double tol = 1.e-5;
Vector3 rutileAtom2Pos(1.47906, 2.29686, 2.29686);
QVERIFY(rutile.atom(1).atomicNumber() == 22);
QVERIFY(GlobalSearch::fuzzyCompare(rutile.atom(1).pos(),
rutileAtom2Pos, tol));
// The third atom should be O and should have fractional coordinates of
// 0, 0.3053, 0.3053
tol = 1.e-5;
Vector3 rutileAtom3Ref =
rutile.unitCell().toFractional(rutile.atom(2).pos());
Vector3 rutileAtom3PosFrac(0.0, 0.3053, 0.3053);
QVERIFY(rutile.atom(2).atomicNumber() == 8);
QVERIFY(GlobalSearch::fuzzyCompare(rutileAtom3Ref, rutileAtom3PosFrac, tol));
// Let's set rutile to be used for the write test
m_rutile = rutile;
/**** Ethane ****/
QString ethaneFileName = QString(TESTDATADIR) + "/data/ethane.cml";
GlobalSearch::Structure ethane;
QVERIFY(GlobalSearch::Formats::read(ðane, ethaneFileName, "cml"));
// Our structure should have no unit cell, 8 atoms, and 7 bonds
QVERIFY(!ethane.hasUnitCell());
QVERIFY(ethane.numAtoms() == 8);
QVERIFY(ethane.numBonds() == 7);
/**** Caffeine ****/
QString caffeineFileName = QString(TESTDATADIR) + "/data/caffeine.cml";
GlobalSearch::Structure caffeine;
QVERIFY(GlobalSearch::Formats::read(&caffeine, caffeineFileName, "cml"));
// Our structure should have no unit cell, 24 atoms, and 25 bonds
QVERIFY(!caffeine.hasUnitCell());
QVERIFY(caffeine.numAtoms() == 24);
QVERIFY(caffeine.numBonds() == 25);
// Caffeine should also have 4 double bonds. Make sure of this.
size_t numDoubleBonds = 0;
for (const GlobalSearch::Bond& bond: caffeine.bonds()) {
if (bond.bondOrder() == 2)
++numDoubleBonds;
}
QVERIFY(numDoubleBonds == 4);
m_caffeine = caffeine;
}
// A note: this test will also fail if readCml() doesn't work properly
// This function assumes that readCml() was already ran successfully, and
// it uses it to confirm that the CML was written properly
void FormatsTest::writeCml()
{
// First, write the cml file to a stringstream
std::stringstream ss;
QVERIFY(GlobalSearch::CmlFormat::write(m_rutile, ss));
// Now read from it and run the same tests we tried above
/**** Rutile ****/
GlobalSearch::Structure rutile;
QVERIFY(GlobalSearch::CmlFormat::read(rutile, ss));
// Our structure should have a unit cell, 6 atoms, and no bonds
// The unit cell volume should be about 62.423
QVERIFY(rutile.hasUnitCell());
QVERIFY(rutile.numAtoms() == 6);
QVERIFY(rutile.numBonds() == 0);
QVERIFY(abs(62.4233 - rutile.unitCell().volume()) < 1.e-5);
// The second atom should be Ti and should have cartesian coordinates of
// (1.47906 2.29686 2.29686)
double tol = 1.e-5;
Vector3 rutileAtom2Pos(1.47906, 2.29686, 2.29686);
QVERIFY(rutile.atom(1).atomicNumber() == 22);
QVERIFY(GlobalSearch::fuzzyCompare(rutile.atom(1).pos(),
rutileAtom2Pos, tol));
// The third atom should be O and should have fractional coordinates of
// 0, 0.3053, 0.3053
tol = 1.e-5;
Vector3 rutileAtom3Ref =
rutile.unitCell().toFractional(rutile.atom(2).pos());
Vector3 rutileAtom3PosFrac(0.0, 0.3053, 0.3053);
QVERIFY(rutile.atom(2).atomicNumber() == 8);
QVERIFY(GlobalSearch::fuzzyCompare(rutileAtom3Ref, rutileAtom3PosFrac, tol));
// Do the same thing with caffeine
std::stringstream css;
QVERIFY(GlobalSearch::CmlFormat::write(m_caffeine, css));
/**** Caffeine ****/
GlobalSearch::Structure caffeine;
QVERIFY(GlobalSearch::CmlFormat::read(caffeine, css));
// Our structure should have no unit cell, 24 atoms, and 25 bonds
QVERIFY(!caffeine.hasUnitCell());
QVERIFY(caffeine.numAtoms() == 24);
QVERIFY(caffeine.numBonds() == 25);
// Caffeine should also have 4 double bonds. Make sure of this.
size_t numDoubleBonds = 0;
for (const GlobalSearch::Bond& bond: caffeine.bonds()) {
if (bond.bondOrder() == 2)
++numDoubleBonds;
}
QVERIFY(numDoubleBonds == 4);
}
void FormatsTest::OBConvert()
{
/**** Caffeine PDB ****/
QString caffeineFileName = QString(TESTDATADIR) + "/data/caffeine.pdb";
QFile file(caffeineFileName);
QVERIFY(file.open(QIODevice::ReadOnly));
QByteArray caffeinePDBData(file.readAll());
// First, use OBConvert to convert it to cml
QByteArray caffeineCMLData;
QVERIFY(GlobalSearch::OBConvert::convertFormat("pdb", "cml",
caffeinePDBData,
caffeineCMLData));
std::stringstream css(caffeineCMLData.data());
// Now read it
GlobalSearch::Structure caffeine;
QVERIFY(GlobalSearch::CmlFormat::read(caffeine, css));
// Our structure should have no unit cell, 24 atoms, and 25 bonds
QVERIFY(!caffeine.hasUnitCell());
QVERIFY(caffeine.numAtoms() == 24);
QVERIFY(caffeine.numBonds() == 25);
// Caffeine should also have 4 double bonds. Make sure of this.
size_t numDoubleBonds = 0;
for (const GlobalSearch::Bond& bond: caffeine.bonds()) {
if (bond.bondOrder() == 2)
++numDoubleBonds;
}
QVERIFY(numDoubleBonds == 4);
// We can make sure the energy and enthalpy can be read correctly here
/**** Caffeine SDF ****/
caffeineFileName = QString(TESTDATADIR) + "/data/caffeine-mmff94.sdf";
QFile fileSDF(caffeineFileName);
QVERIFY(fileSDF.open(QIODevice::ReadOnly));
QByteArray caffeineSDFData(fileSDF.readAll());
// First, use OBConvert to convert it to cml
QByteArray caffeineCMLDataWithEnergy;
// If we want obabel to print the energy and enthalpy in the
// cml output, we HAVE to pass "-xp" to it.
QStringList options;
options << "-xp";
QVERIFY(GlobalSearch::OBConvert::convertFormat("sdf", "cml",
caffeineSDFData,
caffeineCMLDataWithEnergy,
options));
std::stringstream csdfss(caffeineCMLDataWithEnergy.data());
// Now read it
GlobalSearch::Structure caffeineSDF;
QVERIFY(GlobalSearch::CmlFormat::read(caffeineSDF, csdfss));
// Our structure should have no unit cell, 24 atoms, and 25 bonds
QVERIFY(!caffeineSDF.hasUnitCell());
QVERIFY(caffeineSDF.numAtoms() == 24);
QVERIFY(caffeineSDF.numBonds() == 25);
// Caffeine should also have 4 double bonds. Make sure of this.
numDoubleBonds = 0;
for (const GlobalSearch::Bond& bond: caffeineSDF.bonds()) {
if (bond.bondOrder() == 2)
++numDoubleBonds;
}
QVERIFY(numDoubleBonds == 4);
// We should have enthalpy here. It should be -122.350, and energy should
// be -122.351.
QVERIFY(caffeineSDF.hasEnthalpy());
QVERIFY(std::fabs(caffeineSDF.getEnthalpy() - -122.350) < 1.e-5);
QVERIFY(std::fabs(caffeineSDF.getEnergy() - -122.351) < 1.e-5);
}
void FormatsTest::readCastep()
{
/**** Some random CASTEP output ****/
QString fileName =
QString(TESTDATADIR) + "/data/optimizerSamples/castep/xtal.castep";
GlobalSearch::Structure s;
GlobalSearch::Formats::read(&s, fileName, "castep");
double tol = 1.e-5;
// b should be 2.504900, gamma should be 103.045287, and the volume should
// be 8.358635.
QVERIFY(fabs(s.unitCell().b() - 2.504900) < tol);
QVERIFY(fabs(s.unitCell().gamma() - 103.045287) < tol);
QVERIFY(fabs(s.unitCell().volume() - 8.358635) < tol);
// We should have two atoms
QVERIFY(s.numAtoms() == 2);
// Atom #1 should be H and have a fractional position of
// -0.037144, 0.000195, 0.088768
QVERIFY(s.atom(0).atomicNumber() == 1);
QVERIFY(GlobalSearch::fuzzyCompare(
s.unitCell().toFractional(s.atom(0).pos()),
GlobalSearch::Vector3(-0.037144, 0.000195, 0.088768),
tol
)
);
// Atom #2 should be H and have a fractional position of
// 0.474430, 0.498679, 0.850082
QVERIFY(s.atom(1).atomicNumber() == 1);
QVERIFY(GlobalSearch::fuzzyCompare(
s.unitCell().toFractional(s.atom(1).pos()),
GlobalSearch::Vector3(0.474430, 0.498679, 0.850082),
tol
)
);
// Energy should be -29.55686228188
QVERIFY(fabs(s.getEnergy() - -29.55686228188) < tol);
// Enthalpy should be -29.5566434
QVERIFY(fabs(s.getEnthalpy() - -29.5566434) < tol);
}
void FormatsTest::readGulp()
{
/**** Some random GULP output ****/
QString gulpFileName =
QString(TESTDATADIR) + "/data/optimizerSamples/gulp/xtal.got";
GlobalSearch::Structure s;
GlobalSearch::Formats::read(&s, gulpFileName, "gulp");
double tol = 1.e-5;
// b should be 4.3098, gamma should be 102.5730, and the volume should
// be 67.7333397.
QVERIFY(fabs(s.unitCell().b() - 3.398685) < tol);
QVERIFY(fabs(s.unitCell().gamma() - 120.000878) < tol);
QVERIFY(fabs(s.unitCell().volume() - 55.508520) < tol);
// NumAtoms should be 6
QVERIFY(s.numAtoms() == 6);
// Atom #2 should be Ti and have a fractional position of
// 0.499957, 0.999999, 0.500003
QVERIFY(s.atom(1).atomicNumber() == 22);
QVERIFY(GlobalSearch::fuzzyCompare(
s.unitCell().toFractional(s.atom(1).pos()),
GlobalSearch::Vector3(0.499957, 0.999999, 0.500003),
tol
)
);
// Atom #3 should be O and have a fractional position of
// 0.624991, 0.250020, 0.874996
QVERIFY(s.atom(2).atomicNumber() == 8);
QVERIFY(GlobalSearch::fuzzyCompare(
s.unitCell().toFractional(s.atom(2).pos()),
GlobalSearch::Vector3(0.624991, 0.250020, 0.874996),
tol
)
);
// Energy should be -78.44239332
QVERIFY(fabs(s.getEnergy() - -78.44239332) < tol);
}
void FormatsTest::readPwscf()
{
/**** Some random PWSCF output ****/
QString fileName =
QString(TESTDATADIR) + "/data/optimizerSamples/pwscf/xtal.out";
GlobalSearch::Structure s;
GlobalSearch::Formats::read(&s, fileName, "pwscf");
double tol = 1.e-5;
// b should be 4.13754, gamma should be 75.31465, and the volume should
// be 70.0484.
QVERIFY(fabs(s.unitCell().b() - 4.13754) < tol);
QVERIFY(fabs(s.unitCell().gamma() - 75.31465) < tol);
QVERIFY(fabs(s.unitCell().volume() - 70.0484) < tol);
// We should have two atoms
QVERIFY(s.numAtoms() == 2);
// Atom #1 should be O and have a fractional position of
// 0.040806225, 0.100970667, 0.003304159
QVERIFY(s.atom(0).atomicNumber() == 8);
QVERIFY(GlobalSearch::fuzzyCompare(
s.unitCell().toFractional(s.atom(0).pos()),
GlobalSearch::Vector3(0.040806225, 0.100970667, 0.003304159),
tol
)
);
// Atom #2 should be O and have a fractional position of
// 0.577212775, 0.316072333, 0.629713841
QVERIFY(s.atom(1).atomicNumber() == 8);
QVERIFY(GlobalSearch::fuzzyCompare(
s.unitCell().toFractional(s.atom(1).pos()),
GlobalSearch::Vector3(0.577212775, 0.316072333, 0.629713841),
tol
)
);
static const double RYDBERG_TO_EV = 13.605698066;
// We need to reduce the tolerance a little bit for these.
tol = 1.e-3;
// Energy should be -63.35870913 Rydbergs.
QVERIFY(fabs(s.getEnergy() - (-63.35870913 * RYDBERG_TO_EV)) < tol);
// Enthalpy should be -62.9446011092 Rydbergs
QVERIFY(fabs(s.getEnthalpy() - (-62.9446011092 * RYDBERG_TO_EV)) < tol);
}
void FormatsTest::readSiesta()
{
/**** Some random SIESTA output ****/
QString fileName =
QString(TESTDATADIR) + "/data/optimizerSamples/siesta/xtal.out";
GlobalSearch::Structure s;
GlobalSearch::Formats::read(&s, fileName, "siesta");
double tol = 1.e-4;
// b should be 3.874763, gamma should be 74.2726, and the volume should
// be 75.408578.
QVERIFY(fabs(s.unitCell().b() - 3.874763) < tol);
QVERIFY(fabs(s.unitCell().gamma() - 74.2726) < tol);
QVERIFY(fabs(s.unitCell().volume() - 75.408578) < tol);
// We should have six atoms
QVERIFY(s.numAtoms() == 6);
// Atom #2 should be Ti and have a fractional position of
// 0.40338285, 0.38896410, 0.75921162
QVERIFY(s.atom(1).atomicNumber() == 22);
QVERIFY(GlobalSearch::fuzzyCompare(
s.unitCell().toFractional(s.atom(1).pos()),
GlobalSearch::Vector3(0.40338285, 0.38896410, 0.75921162),
tol
)
);
// Atom #3 should be O and have a fractional position of
// 0.38568921, 0.74679127, 0.21473350
QVERIFY(s.atom(2).atomicNumber() == 8);
QVERIFY(GlobalSearch::fuzzyCompare(
s.unitCell().toFractional(s.atom(2).pos()),
GlobalSearch::Vector3(0.38568921, 0.74679127, 0.21473350),
tol
)
);
// Energy should be -2005.342641 eV
QVERIFY(fabs(s.getEnergy() - -2005.342641) < tol);
}
void FormatsTest::readVasp()
{
/**** Some random VASP output ****/
QString fileName =
QString(TESTDATADIR) + "/data/optimizerSamples/vasp/CONTCAR";
GlobalSearch::Structure s;
GlobalSearch::Formats::read(&s, fileName, "vasp");
double tol = 1.e-5;
// b should be 2.52221, gamma should be 86.32327, and the volume should
// be 6.01496.
QVERIFY(fabs(s.unitCell().b() - 2.52221) < tol);
QVERIFY(fabs(s.unitCell().gamma() - 86.32327) < tol);
QVERIFY(fabs(s.unitCell().volume() - 6.01496) < tol);
// We should have three atoms
QVERIFY(s.numAtoms() == 3);
// Atom #2 should be H and have a fractional position of
// 0.9317195263978, 0.20419595775, 0.4923304223199
QVERIFY(s.atom(1).atomicNumber() == 1);
QVERIFY(GlobalSearch::fuzzyCompare(
s.unitCell().toFractional(s.atom(1).pos()),
GlobalSearch::Vector3(0.9317195263978, 0.20419595775, 0.4923304223199),
tol
)
);
// Atom #3 should be O and have a fractional position of
// 0.087068957523, -0.1465596214494, 0.1524183445695
QVERIFY(s.atom(2).atomicNumber() == 8);
QVERIFY(GlobalSearch::fuzzyCompare(
s.unitCell().toFractional(s.atom(2).pos()),
GlobalSearch::Vector3(0.087068957523, -0.1465596214494, 0.1524183445695),
tol
)
);
// Energy should be 5.56502673 eV.
QVERIFY(fabs(s.getEnergy() - 5.56502673) < tol);
// Enthalpy should be 43.10746559 eV
QVERIFY(fabs(s.getEnthalpy() - 43.10746559) < tol);
}
QTEST_MAIN(FormatsTest)
#include "formatstest.moc"
| [
"psavery@buffalo.edu"
] | psavery@buffalo.edu |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.