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
1e29e7513257305cc5edabf872713b5ee9582778
e9a8fffb05b32e8332f15d4dea96761261c0353c
/image-compression/compression.cpp
cbe935ab6ee868186775c93baea6b355ca2b5f5a
[]
no_license
brightnesss/image-processing
7590933547519ba551d2b6df630a92437a329f7a
450914d04d33020e1868d800f2fe2e7896397da2
refs/heads/master
2020-05-23T08:10:40.040189
2017-01-13T12:02:09
2017-01-13T12:02:09
70,224,402
0
0
null
null
null
null
GB18030
C++
false
false
3,928
cpp
//8*8矩阵的zigzag行程压缩编码示意 #include <iostream> #include <opencv2\opencv.hpp> #include <math.h> #include <vector> #include <algorithm> #define PLUS 1 #define MINUS 0 using namespace std; using namespace cv; void InitMat(Mat &img, float(*pf)[8]) { for (unsigned short i = 0;i < img.rows;++i) for (unsigned short j = 0;j < img.cols;++j) img.at<float>(i, j) = *(*(pf + i) + j); } void MoveImg(Mat &src, Mat &dst, bool flag) { for (unsigned short i = 0;i < src.rows;++i) for (unsigned short j = 0;j < src.cols;++j) dst.at<float>(i, j) = flag ? src.at<float>(i, j) + 128 : src.at<float>(i, j) - 128; } void WriteImg(Mat &img) { for (unsigned short i = 0;i < img.rows;++i) { for (unsigned short j = 0;j < img.cols;++j) { cout << img.at<float>(i, j) << " "; } cout << endl; } } void round(Mat &src,Mat &dst) { for (unsigned short i = 0;i < src.rows;++i) for (unsigned short j = 0;j < src.cols;++j) dst.at<float>(i, j) = round(src.at<float>(i, j)); } void quantification(Mat &src, Mat &dst, Mat &model) { if ((src.rows != model.rows) || (src.cols != model.cols)) { return; } for (unsigned short i = 0;i < src.rows;++i) for (unsigned short j = 0;j < src.cols;++j) dst.at<float>(i, j) = src.at<float>(i, j) / model.at<float>(i, j); round(dst, dst); } void dequantification(Mat &src, Mat &dst, Mat &model) { if ((src.rows != model.rows) || (src.cols != model.cols)) { return; } for (unsigned short i = 0;i < src.rows;++i) for (unsigned short j = 0;j < src.cols;++j) dst.at<float>(i, j) = src.at<float>(i, j) * model.at<float>(i, j); } vector<int> zigzag(Mat &img) { //8*8矩阵的zigzag系数排列矩阵 vector<int> ans; int count = 0; int i = 0; //行标号 int j = 0; //列标号 int count_j = 1; int count_i = 2; ans.push_back(img.at<float>(i, j)); ++count; ++j; while (count != 64) { while ((j != -1) && (i != 8)) { ans.push_back(img.at<float>(i++, j--)); ++count; } if (i == 8) { i = 7; j = count_j; count_j += 2; } else j = 0; while ((i != -1) && (j != 8)) { ans.push_back(img.at<float>(i--, j++)); ++count; } if (j == 8) { j = 7; i = count_i; count_i += 2; } else i = 0; } while (*ans.rbegin() == 0) ans.pop_back(); return ans; } float calculateError(Mat &img1, Mat &img2) { float error = 0; for (unsigned short i = 0;i != img1.rows;++i) for (unsigned short j = 0;j != img1.cols;++j) error = error + pow((img1.at<float>(i, j) - img2.at<float>(i, j)), 2); error = error / (img1.rows*img1.cols); return sqrt(error); } int main() { float f_img[][8] = { 52,55,61,66,70,61,64,73, 63,59,66,90,109,85,69,72, 62,59,68,113,144,104,66,73, 63,58,71,122,154,106,70,69, 67,61,68,104,126,88,68,70, 79,65,60,70,77,68,58,75, 85,71,64,59,55,61,65,83, 87,79,69,68,65,76,78,94 }; Mat img(8, 8, CV_32FC1); InitMat(img, f_img); Mat moveImg(8, 8, CV_32FC1); MoveImg(img, moveImg, MINUS); Mat dctImg(8, 8, CV_32FC1); dct(moveImg, dctImg); round(dctImg, dctImg); float f_model[][8] = { 16,11,10,16,24,40,51,61, 12,12,14,19,26,58,60,55, 14,13,16,24,40,57,69,56, 14,17,22,29,51,87,80,62, 18,22,37,56,68,109,103,77, 24,35,55,64,81,104,113,92, 49,64,78,87,103,121,120,101, 72,92,95,98,112,100,103,99 }; Mat model(8, 8, CV_32FC1); InitMat(model, f_model); Mat compressImg(8, 8, CV_32FC1); quantification(dctImg, compressImg, model); vector<int> zigzagVec; zigzagVec = zigzag(compressImg); for (vector<int>::const_iterator iter = zigzagVec.begin();iter != zigzagVec.end();++iter) { cout << *iter << " "; } cout << "EOB" << endl << endl; Mat decode(8, 8, CV_32FC1); dequantification(compressImg, decode, model); Mat idctImg(8, 8, CV_32FC1); idct(decode, idctImg); round(idctImg, idctImg); Mat removeImg(8, 8, CV_32FC1); MoveImg(idctImg, removeImg, PLUS); float error = calculateError(img, removeImg); cout << error << endl; }
[ "brightness_j@hotmail.com" ]
brightness_j@hotmail.com
e7820c344e997399de0e161fa13f2b383210532f
d4faf438bd3f8e94178acdd31157d03d955c582b
/src/Utils/FBX_Importer.h
759a910069e1b49bb741af0d9bd49e06d6f142b9
[]
no_license
luoxz-ai/cpp_game_engine
19684a3c235fb7738b2988ed73dbaab08e2e5c2d
f25c950c9c312cc239e27acaeda85b5f852e8a01
refs/heads/master
2023-04-12T13:55:31.426366
2021-05-05T20:11:40
2021-05-05T20:11:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,223
h
#pragma once #include <Windows.h> #include <stdio.h> #include <iostream> #include <string> #include <sstream> #include <vector> #include "Structs.h" #include "Entity/Mesh/Mesh.h" #include "Entity/Mesh/MeshDeformer/Animation/Animation.h" // Utils #include "fbxsdk.h" struct FBX_LoadResult { bool success = false; bool binormaltangent_Loaded = false; }; class FBX_Importer { public: static FBX_LoadResult Load( Mesh* pMesh, const char* fileName, const char* mainMeshName, Vertex*& _vertices, unsigned int*& _indices, unsigned int& _vertices_count, unsigned int& _indices_count, Joint**& _joints, unsigned int& _jointCount, Animation**& _animations, unsigned int& _animationCount, std::map<int, int>& _indexed_vertices, std::map<int, std::map<int, float>>& _indexed_joint_weights ); static void printNode(FbxNode* node, unsigned int level = 0); static Joint* getJointByName(const char* jointName, Joint** joints, unsigned int jointCount); static void Triangulate(FbxNode* node, FbxGeometryConverter& geometryConverter); static FbxNode* getMainMeshNode(FbxNode* node, const char* mainMeshName); // FBX to DX matrix/vector conversions static dx::XMFLOAT4X4* MatrixFBXtoDX(FbxAMatrix fbxMatrix); };
[ "fmehmetun3@gmail.com" ]
fmehmetun3@gmail.com
6ec8d304fd26a61d2effef62a2239c1f6c11884e
7619f1f54f8a1f7b11dc1dbb840fd15677a10855
/playertwo/cmake-build-debug/playertwo_autogen/EWIEGA46WW/moc_Player.cpp
a3bc45f8640e6634c9e9c8e0e4524d496c17869b
[]
no_license
kbyun03/4122FinalProject
b52ffd6f3f09161c2523f48dd6e061e130ea2554
83a414c3ebe49d03b0e90a8b515c81fa1666891c
refs/heads/master
2020-03-10T15:13:30.964122
2018-05-03T18:22:36
2018-05-03T18:22:36
129,444,228
0
0
null
null
null
null
UTF-8
C++
false
false
3,541
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'Player.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.10.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../../Player.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'Player.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.10.1. 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 QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_Player_t { QByteArrayData data[5]; char stringdata0[18]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_Player_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_Player_t qt_meta_stringdata_Player = { { QT_MOC_LITERAL(0, 0, 6), // "Player" QT_MOC_LITERAL(1, 7, 5), // "spawn" QT_MOC_LITERAL(2, 13, 0), // "" QT_MOC_LITERAL(3, 14, 1), // "x" QT_MOC_LITERAL(4, 16, 1) // "y" }, "Player\0spawn\0\0x\0y" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_Player[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 2, 19, 2, 0x0a /* Public */, // slots: parameters QMetaType::Void, QMetaType::Int, QMetaType::Int, 3, 4, 0 // eod }; void Player::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Player *_t = static_cast<Player *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->spawn((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; default: ; } } } QT_INIT_METAOBJECT const QMetaObject Player::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_Player.data, qt_meta_data_Player, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *Player::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *Player::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_Player.stringdata0)) return static_cast<void*>(this); if (!strcmp(_clname, "QGraphicsPixmapItem")) return static_cast< QGraphicsPixmapItem*>(this); return QObject::qt_metacast(_clname); } int Player::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 1) qt_static_metacall(this, _c, _id, _a); _id -= 1; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 1) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 1; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "tzeng.a@gmail.com" ]
tzeng.a@gmail.com
15cf0b87bfc035b27021c2a3dfb125420b23527d
1f013e822124dfe9b4611f1fe08675a23871566e
/home/akielczewska/z1/tro.cpp
96a7d0afb9c43832fc3df50ae45c2c0fbce2429e
[]
no_license
dtraczewski/zpk2014
a1d9a26d25ff174561e3b20c8660901178d827a5
548970bc5a9a02215687cb143d2f3f44307ff252
refs/heads/master
2021-01-21T06:06:32.044028
2015-09-06T12:17:07
2015-09-06T12:17:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
188
cpp
#include <iostream> using namespace std; main() { int a,b,c; cin >> a >> b >> c; if (a+b>c && a+c>b && b+c>a) cout << "TAK" << endl; else cout << "NIE" << endl; }
[ "aneta.kielczewska@student.uw.edu.pl" ]
aneta.kielczewska@student.uw.edu.pl
8f2195874ab869da11fe15fa5c70102ef01b4a9b
43a2fbc77f5cea2487c05c7679a30e15db9a3a50
/Cpp/External (Offsets Only)/SDK/BP_msc_hurdygurdy_pio_01_a_ItemDesc_classes.h
82fec60f39c50589d4d8837a2324442017ddafd7
[]
no_license
zH4x/SoT-Insider-SDK
57e2e05ede34ca1fd90fc5904cf7a79f0259085c
6bff738a1b701c34656546e333b7e59c98c63ad7
refs/heads/main
2023-06-09T23:10:32.929216
2021-07-07T01:34:27
2021-07-07T01:34:27
383,638,719
0
0
null
null
null
null
UTF-8
C++
false
false
867
h
#pragma once // Name: SoT-Insider, Version: 1.102.2382.0 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_msc_hurdygurdy_pio_01_a_ItemDesc.BP_msc_hurdygurdy_pio_01_a_ItemDesc_C // 0x0000 (FullSize[0x0130] - InheritedSize[0x0130]) class UBP_msc_hurdygurdy_pio_01_a_ItemDesc_C : public UItemDesc { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_msc_hurdygurdy_pio_01_a_ItemDesc.BP_msc_hurdygurdy_pio_01_a_ItemDesc_C"); return ptr; } void AfterRead(); void BeforeDelete(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "Massimo.linker@gmail.com" ]
Massimo.linker@gmail.com
35e5a5651241d6561f29a640d3b3b2f6bf154417
d09945668f19bb4bc17087c0cb8ccbab2b2dd688
/atcoder/abc251-300/abc282/h.cpp
ff41ae325bad8c630c66d30fb5858e4ead9e7f67
[]
no_license
kmjp/procon
27270f605f3ae5d80fbdb28708318a6557273a57
8083028ece4be1460150aa3f0e69bdb57e510b53
refs/heads/master
2023-09-04T11:01:09.452170
2023-09-03T15:25:21
2023-09-03T15:25:21
30,825,508
23
2
null
2023-08-18T14:02:07
2015-02-15T11:25:23
C++
UTF-8
C++
false
false
1,757
cpp
#include <bits/stdc++.h> using namespace std; typedef signed long long ll; #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x,to) for(x=0;x<(to);x++) #define FORR(x,arr) for(auto& x:arr) #define FORR2(x,y,arr) for(auto& [x,y]:arr) #define ALL(a) (a.begin()),(a.end()) #define ZERO(a) memset(a,0,sizeof(a)) #define MINUS(a) memset(a,0xff,sizeof(a)) template<class T> bool chmax(T &a, const T &b) { if(a<b){a=b;return 1;}return 0;} template<class T> bool chmin(T &a, const T &b) { if(a>b){a=b;return 1;}return 0;} //------------------------------------------------------- int N; ll S; ll A[252525],B[252525]; ll BS[252525]; void solve() { int i,j,k,l,r,x,y; string s; cin>>N>>S; set<int> did={0,N+1}; vector<pair<ll,int>> V; FOR(i,N) { cin>>A[i+1]; V.push_back({A[i+1],i+1}); } FOR(i,N) { cin>>B[i+1]; BS[i+1]=BS[i]+B[i+1]; } ll ret=0; sort(ALL(V)); FORR2(v,i,V) { auto it=did.lower_bound(i); int R=*it; int L=*--it; did.insert(i); if(R-i<=i-L) { ll a=A[i]; for(x=i;x<R;x++) { a+=B[x]; if(a>S) break; int TL=i; for(y=20;y>=0;y--) { if(TL-(1<<y)<=L) continue; if(BS[x]-BS[TL-(1<<y)-1]+A[i]<=S) TL-=1<<y; } ret+=i-TL+1; } } else { ll a=A[i]; for(x=i;x>L;x--) { a+=B[x]; if(a>S) break; int TR=i; for(y=20;y>=0;y--) { if(TR+(1<<y)>=R) continue; if(a+BS[TR+(1<<y)]-BS[i]<=S) TR+=1<<y; } ret+=TR-i+1; } } } cout<<ret<<endl; } int main(int argc,char** argv){ string s;int i; if(argc==1) ios::sync_with_stdio(false), cin.tie(0); FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin); cout.tie(0); solve(); return 0; }
[ "kmjp@users.noreply.github.com" ]
kmjp@users.noreply.github.com
6137213523d3ddd397365b81fe30a82fce77eccb
095b7832c29a9225b83f9f4ff8355ef6a6543b0d
/Miscellaneous/BinaryTreeZigZagTraversal.cpp
191fc1ca50e3913bcc670415f192f6b1997872b8
[]
no_license
I-Venkatesh/Data-structures-and-algorithms
a459b2a45fe0b5d2399e4f287bb83ea5d1742fac
0d05ee80d0e6dd5f376b843975f3c70abac1457f
refs/heads/master
2023-08-13T20:19:52.214023
2021-09-11T14:36:30
2021-09-11T14:36:30
323,447,201
0
0
null
null
null
null
UTF-8
C++
false
false
1,503
cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { queue<TreeNode* > q; vector<vector<int>> ans; if(root==NULL) { return ans; } int level=0; q.push(root); while(!q.empty()) { vector<int> temp; int n=q.size(); for(int i=0;i<n;i++) { if(q.front()->left!=NULL) { q.push(q.front()->left); } if(q.front()->right!=NULL) { q.push(q.front()->right); } if(q.front()!=NULL) { temp.push_back(q.front()->val); } if(!q.empty()) { q.pop(); } } if(level&1) { reverse(temp.begin(),temp.end()); ans.push_back(temp); } else{ ans.push_back(temp); } level++; } return ans; } };
[ "venkatesh.i18@iiits.in" ]
venkatesh.i18@iiits.in
00554c1b359ed4d05a729f6915fdca3655b76a48
019b1b4fc4a0c8bf0f65f5bec2431599e5de5300
/content/browser/tracing/tracing_controller_impl_data_sinks.cc
1ee6327893aad4cbbf028b0de0034db24642d901
[ "BSD-3-Clause" ]
permissive
wyrover/downloader
bd61b858d82ad437df36fbbaaf58d293f2f77445
a2239a4de6b8b545d6d88f6beccaad2b0c831e07
refs/heads/master
2020-12-30T14:45:13.193034
2017-04-23T07:39:04
2017-04-23T07:39:04
91,083,169
1
2
null
2017-05-12T11:06:42
2017-05-12T11:06:42
null
UTF-8
C++
false
false
12,000
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <utility> #include "base/bind.h" #include "base/files/file_util.h" #include "base/json/json_writer.h" #include "base/macros.h" #include "base/strings/pattern.h" #include "content/browser/tracing/tracing_controller_impl.h" #include "content/public/browser/browser_thread.h" #include "third_party/zlib/zlib.h" namespace content { namespace { const char kChromeTraceLabel[] = "traceEvents"; const char kMetadataTraceLabel[] = "metadata"; class StringTraceDataEndpoint : public TracingController::TraceDataEndpoint { public: typedef base::Callback<void(scoped_ptr<const base::DictionaryValue>, base::RefCountedString*)> CompletionCallback; explicit StringTraceDataEndpoint(CompletionCallback callback) : completion_callback_(callback) {} void ReceiveTraceFinalContents( scoped_ptr<const base::DictionaryValue> metadata, const std::string& contents) override { std::string tmp = contents; scoped_refptr<base::RefCountedString> str = base::RefCountedString::TakeString(&tmp); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(completion_callback_, base::Passed(std::move(metadata)), base::RetainedRef(str))); } private: ~StringTraceDataEndpoint() override {} CompletionCallback completion_callback_; DISALLOW_COPY_AND_ASSIGN(StringTraceDataEndpoint); }; class FileTraceDataEndpoint : public TracingController::TraceDataEndpoint { public: explicit FileTraceDataEndpoint(const base::FilePath& trace_file_path, const base::Closure& callback) : file_path_(trace_file_path), completion_callback_(callback), file_(NULL) {} void ReceiveTraceChunk(const std::string& chunk) override { std::string tmp = chunk; scoped_refptr<base::RefCountedString> chunk_ptr = base::RefCountedString::TakeString(&tmp); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&FileTraceDataEndpoint::ReceiveTraceChunkOnFileThread, this, chunk_ptr)); } void ReceiveTraceFinalContents( scoped_ptr<const base::DictionaryValue> , const std::string& contents) override { BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&FileTraceDataEndpoint::CloseOnFileThread, this)); } private: ~FileTraceDataEndpoint() override { DCHECK(file_ == NULL); } void ReceiveTraceChunkOnFileThread( const scoped_refptr<base::RefCountedString> chunk) { if (!OpenFileIfNeededOnFileThread()) return; ignore_result( fwrite(chunk->data().c_str(), chunk->data().size(), 1, file_)); } bool OpenFileIfNeededOnFileThread() { if (file_ != NULL) return true; file_ = base::OpenFile(file_path_, "w"); if (file_ == NULL) { LOG(ERROR) << "Failed to open " << file_path_.value(); return false; } return true; } void CloseOnFileThread() { if (OpenFileIfNeededOnFileThread()) { base::CloseFile(file_); file_ = NULL; } BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&FileTraceDataEndpoint::FinalizeOnUIThread, this)); } void FinalizeOnUIThread() { completion_callback_.Run(); } base::FilePath file_path_; base::Closure completion_callback_; FILE* file_; DISALLOW_COPY_AND_ASSIGN(FileTraceDataEndpoint); }; class StringTraceDataSink : public TracingController::TraceDataSink { public: explicit StringTraceDataSink( scoped_refptr<TracingController::TraceDataEndpoint> endpoint) : endpoint_(endpoint) {} void AddTraceChunk(const std::string& chunk) override { std::string trace_string; if (trace_.empty()) trace_string = "{\"" + std::string(kChromeTraceLabel) + "\":["; else trace_string = ","; trace_string += chunk; AddTraceChunkAndPassToEndpoint(trace_string); } void AddTraceChunkAndPassToEndpoint(const std::string& chunk) { trace_ += chunk; endpoint_->ReceiveTraceChunk(chunk); } void Close() override { AddTraceChunkAndPassToEndpoint("]"); for (auto const &it : GetAgentTrace()) AddTraceChunkAndPassToEndpoint(",\"" + it.first + "\": " + it.second); std::string metadataJSON; if (base::JSONWriter::Write(*GetMetadataCopy(), &metadataJSON) && !metadataJSON.empty()) { AddTraceChunkAndPassToEndpoint( ",\"" + std::string(kMetadataTraceLabel) + "\": " + metadataJSON); } AddTraceChunkAndPassToEndpoint("}"); endpoint_->ReceiveTraceFinalContents(GetMetadataCopy(), trace_); } private: ~StringTraceDataSink() override {} scoped_refptr<TracingController::TraceDataEndpoint> endpoint_; std::string trace_; DISALLOW_COPY_AND_ASSIGN(StringTraceDataSink); }; class CompressedStringTraceDataSink : public TracingController::TraceDataSink { public: explicit CompressedStringTraceDataSink( scoped_refptr<TracingController::TraceDataEndpoint> endpoint) : endpoint_(endpoint), already_tried_open_(false) {} void AddTraceChunk(const std::string& chunk) override { std::string tmp = chunk; scoped_refptr<base::RefCountedString> chunk_ptr = base::RefCountedString::TakeString(&tmp); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&CompressedStringTraceDataSink::AddTraceChunkOnFileThread, this, chunk_ptr)); } void Close() override { BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&CompressedStringTraceDataSink::CloseOnFileThread, this)); } private: ~CompressedStringTraceDataSink() override {} bool OpenZStreamOnFileThread() { DCHECK_CURRENTLY_ON(BrowserThread::FILE); if (stream_) return true; if (already_tried_open_) return false; already_tried_open_ = true; stream_.reset(new z_stream); *stream_ = {0}; stream_->zalloc = Z_NULL; stream_->zfree = Z_NULL; stream_->opaque = Z_NULL; int result = deflateInit2(stream_.get(), Z_DEFAULT_COMPRESSION, Z_DEFLATED, // 16 is added to produce a gzip header + trailer. MAX_WBITS + 16, 8, // memLevel = 8 is default. Z_DEFAULT_STRATEGY); return result == 0; } void AddTraceChunkOnFileThread( const scoped_refptr<base::RefCountedString> chunk_ptr) { DCHECK_CURRENTLY_ON(BrowserThread::FILE); std::string trace; if (compressed_trace_data_.empty()) trace = "{\"" + std::string(kChromeTraceLabel) + "\":["; else trace = ","; trace += chunk_ptr->data(); AddTraceChunkAndCompressOnFileThread(trace, false); } void AddTraceChunkAndCompressOnFileThread(const std::string& chunk, bool finished) { DCHECK_CURRENTLY_ON(BrowserThread::FILE); if (!OpenZStreamOnFileThread()) return; const int kChunkSize = 0x4000; char buffer[kChunkSize]; int err; stream_->avail_in = chunk.size(); stream_->next_in = (unsigned char*)chunk.data(); do { stream_->avail_out = kChunkSize; stream_->next_out = (unsigned char*)buffer; err = deflate(stream_.get(), finished ? Z_FINISH : Z_NO_FLUSH); if (err != Z_OK && (err != Z_STREAM_END && finished)) { stream_.reset(); return; } int bytes = kChunkSize - stream_->avail_out; if (bytes) { std::string compressed_chunk = std::string(buffer, bytes); compressed_trace_data_ += compressed_chunk; endpoint_->ReceiveTraceChunk(compressed_chunk); } } while (stream_->avail_out == 0); } void CloseOnFileThread() { DCHECK_CURRENTLY_ON(BrowserThread::FILE); if (!OpenZStreamOnFileThread()) return; if (compressed_trace_data_.empty()) { AddTraceChunkAndCompressOnFileThread( "{\"" + std::string(kChromeTraceLabel) + "\":[", false); } AddTraceChunkAndCompressOnFileThread("]", false); for (auto const &it : GetAgentTrace()) { AddTraceChunkAndCompressOnFileThread( ",\"" + it.first + "\": " + it.second, false); } std::string metadataJSON; if (base::JSONWriter::Write(*GetMetadataCopy(), &metadataJSON) && !metadataJSON.empty()) { AddTraceChunkAndCompressOnFileThread( ",\"" + std::string(kMetadataTraceLabel) + "\": " + metadataJSON, false); } AddTraceChunkAndCompressOnFileThread("}", true); deflateEnd(stream_.get()); stream_.reset(); endpoint_->ReceiveTraceFinalContents(GetMetadataCopy(), compressed_trace_data_); } scoped_refptr<TracingController::TraceDataEndpoint> endpoint_; scoped_ptr<z_stream> stream_; bool already_tried_open_; std::string compressed_trace_data_; DISALLOW_COPY_AND_ASSIGN(CompressedStringTraceDataSink); }; } // namespace TracingController::TraceDataSink::TraceDataSink() {} TracingController::TraceDataSink::~TraceDataSink() {} void TracingController::TraceDataSink::AddAgentTrace( const std::string& trace_label, const std::string& trace_data) { DCHECK(additional_tracing_agent_trace_.find(trace_label) == additional_tracing_agent_trace_.end()); additional_tracing_agent_trace_[trace_label] = trace_data; } const std::map<std::string, std::string>& TracingController::TraceDataSink::GetAgentTrace() const { return additional_tracing_agent_trace_; } void TracingController::TraceDataSink::AddMetadata( const base::DictionaryValue& data) { metadata_.MergeDictionary(&data); } void TracingController::TraceDataSink::SetMetadataFilterPredicate( const MetadataFilterPredicate& metadata_filter_predicate) { metadata_filter_predicate_ = metadata_filter_predicate; } scoped_ptr<const base::DictionaryValue> TracingController::TraceDataSink::GetMetadataCopy() const { if (metadata_filter_predicate_.is_null()) return scoped_ptr<const base::DictionaryValue>(metadata_.DeepCopy()); scoped_ptr<base::DictionaryValue> metadata_copy(new base::DictionaryValue); for (base::DictionaryValue::Iterator it(metadata_); !it.IsAtEnd(); it.Advance()) { if (metadata_filter_predicate_.Run(it.key())) metadata_copy->Set(it.key(), it.value().DeepCopy()); else metadata_copy->SetString(it.key(), "__stripped__"); } return std::move(metadata_copy); } scoped_refptr<TracingController::TraceDataSink> TracingController::CreateStringSink( const base::Callback<void(scoped_ptr<const base::DictionaryValue>, base::RefCountedString*)>& callback) { return new StringTraceDataSink(new StringTraceDataEndpoint(callback)); } scoped_refptr<TracingController::TraceDataSink> TracingController::CreateCompressedStringSink( scoped_refptr<TracingController::TraceDataEndpoint> endpoint) { return new CompressedStringTraceDataSink(endpoint); } scoped_refptr<TracingController::TraceDataSink> TracingController::CreateFileSink(const base::FilePath& file_path, const base::Closure& callback) { return new StringTraceDataSink( CreateFileEndpoint(file_path, callback)); } scoped_refptr<TracingController::TraceDataEndpoint> TracingController::CreateCallbackEndpoint(const base::Callback< void(scoped_ptr<const base::DictionaryValue>, base::RefCountedString*)>& callback) { return new StringTraceDataEndpoint(callback); } scoped_refptr<TracingController::TraceDataEndpoint> TracingController::CreateFileEndpoint(const base::FilePath& file_path, const base::Closure& callback) { return new FileTraceDataEndpoint(file_path, callback); } } // namespace content
[ "wangpp_os@sari.ac.cn" ]
wangpp_os@sari.ac.cn
aa12e239d41a9ee497b2e97df0453b6729800804
c980768b06aed339b2d6b47fc0d13507f068537c
/GhCore/ghApp.h
4fa3402a08aa5c8d87e7bf529bd000dd78e8fb10
[]
no_license
jiaco/genehuggers
f4a3b99cdfea59cbaf56fc29a26f0230db69dcbb
30c3ba1f07aa7a9832385b2d2847d051e77cfd28
refs/heads/master
2021-01-01T05:51:38.865068
2012-04-16T07:57:40
2012-04-16T07:57:40
32,718,214
0
0
null
null
null
null
UTF-8
C++
false
false
1,994
h
#ifndef GH_APP_H #define GH_APP_H 1 #include <QtCore> #include "ghDef.h" #include "ghVariant.h" #include "ghParam.h" #include "ghOfp.h" #include "ghErrorprone.h" namespace GH { inline QMap<QString,QString> Args( const int argc, char** argv ) { QMap<QString,QString> rv; for( int ac = 1; ac < argc; ++ac ) { QString aname = argv[ ac ]; QString avalue = "true"; if( ac + 1 < argc ) { avalue = argv[ ac + 1 ]; if( avalue.startsWith( '-' ) ) { avalue = "true"; } else { ++ac; } } if( aname.startsWith( '-' ) ) { rv.insert( aname.mid( 1 ), avalue ); } } return( rv ); } class GH_DLL_EXPORT App : public GH::Errorprone { public: App( int argc, char** argv ); void usage(); QString arg0() const; bool isGui() const; void showError() const; const QMap<QString,QString> args() const; bool hasParam( const QString& name ) const; bool addParam( Param param ); bool addParam( const QString& name, const QString& defaultValue = QString(), const Param::ParamType& type = Param::UndefParam, const QString& displayName = QString() ); Param param( const QString& name ); Param* pparam( const QString& name ); QVariant paramValue( const QString& name ) const; QStringList paramNames() const; bool checkArgs(); // in ObjApp there are 2 signals // void paramChanged() // void message() // in ObjApp these become slots void setParam( const QString& name, const QVariant& value, const bool& silent = true ); void guiSetParam( const QString& name, const QVariant& value ); protected: bool _isGui; QString _arg0; QMap<QString,QString> _args; QMap<QString,Param> _param; QStringList _paramNames; QString USAGE; }; } // GH namespace #endif // GH_APP_H
[ "jiacov@gmail.com" ]
jiacov@gmail.com
f2bcacd71d462cf0bdaef301cc87e2cc42df506d
436adbbd309a6d2d283a4e9fe2e7c5c671ce0db7
/Classes/UIWidgets/LuaExtensionsDS.cpp
27966b4584bdcb073317745e07b72dc64e07d7f2
[]
no_license
daxingyou/q_card
87077b343445acf04132cdd0701952d941f19036
3b458ee32ec03509f293324ab8de88efad3d2501
refs/heads/master
2021-12-23T19:59:58.341338
2017-11-21T06:36:57
2017-11-21T06:36:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,185
cpp
/* ** Lua binding: Cocos2d ** Generated automatically by tolua++-1.0.92 on 02/10/14 14:41:11. */ /**************************************************************************** Copyright (c) 2011 cocos2d-x.org http://www.cocos2d-x.org 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. ****************************************************************************/ extern "C" { #include "tolua_fix.h" } #include <map> #include <string> #include "cocos2d.h" #include "CCLuaEngine.h" #include "SimpleAudioEngine.h" #include "cocos-ext.h" #include "string.h" #ifdef __cplusplus extern "C" { #endif #include "tolua++.h" #ifdef __cplusplus } #endif #include "Common/CommonDefine.h" #include "UIWidgets/DSMask.h" #include "UIWidgets/RichLabel.h" #include "UIWidgets/GuideLayer.h" #include "UIWidgets/GraySprite.h" using namespace cocos2d; using namespace cocos2d::extension; using namespace CocosDenshion; using namespace DianshiTech; /* function to register type */ static void tolua_reg_types (lua_State* tolua_S) { tolua_usertype(tolua_S,"CCLayerRGBA"); tolua_usertype(tolua_S,"CCSize"); tolua_usertype(tolua_S,"ccColor3B"); tolua_usertype(tolua_S,"RichLabel"); tolua_usertype(tolua_S,"GuideLayer"); tolua_usertype(tolua_S,"DSMask"); tolua_usertype(tolua_S,"CCSprite"); tolua_usertype(tolua_S,"CCLayerColor"); tolua_usertype(tolua_S,"GraySprite"); tolua_usertype(tolua_S,"DrawCricleMask"); } /* method: create of class RichLabel */ #ifndef TOLUA_DISABLE_tolua_Cocos2d_RichLabel_create00 static int tolua_Cocos2d_RichLabel_create00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertable(tolua_S,1,"RichLabel",0,&tolua_err) || !tolua_isstring(tolua_S,2,0,&tolua_err) || !tolua_isstring(tolua_S,3,0,&tolua_err) || !tolua_isnumber(tolua_S,4,0,&tolua_err) || (tolua_isvaluenil(tolua_S,5,&tolua_err) || !tolua_isusertype(tolua_S,5,"CCSize",0,&tolua_err)) || !tolua_isboolean(tolua_S,6,1,&tolua_err) || !tolua_isboolean(tolua_S,7,1,&tolua_err) || !tolua_isnoobj(tolua_S,8,&tolua_err) ) goto tolua_lerror; else #endif { const char* str = ((const char*) tolua_tostring(tolua_S,2,0)); const char* fontName = ((const char*) tolua_tostring(tolua_S,3,0)); const int fontSize = ((const int) tolua_tonumber(tolua_S,4,0)); CCSize labelSize = *((CCSize*) tolua_tousertype(tolua_S,5,0)); bool appendString = ((bool) tolua_toboolean(tolua_S,6,false)); bool enableShadow = ((bool) tolua_toboolean(tolua_S,7,true)); { RichLabel* tolua_ret = (RichLabel*) RichLabel::create(str,fontName,fontSize,labelSize,appendString,enableShadow); tolua_pushusertype(tolua_S,(void*)tolua_ret,"RichLabel"); } } return 1; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'create'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* method: setColor of class RichLabel */ #ifndef TOLUA_DISABLE_tolua_Cocos2d_RichLabel_setColor00 static int tolua_Cocos2d_RichLabel_setColor00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype(tolua_S,1,"RichLabel",0,&tolua_err) || (tolua_isvaluenil(tolua_S,2,&tolua_err) || !tolua_isusertype(tolua_S,2,"const ccColor3B",0,&tolua_err)) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) goto tolua_lerror; else #endif { RichLabel* self = (RichLabel*) tolua_tousertype(tolua_S,1,0); const ccColor3B* color3 = ((const ccColor3B*) tolua_tousertype(tolua_S,2,0)); #ifndef TOLUA_RELEASE if (!self) tolua_error(tolua_S,"invalid 'self' in function 'setColor'", NULL); #endif { self->setColor(*color3); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'setColor'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* method: getString of class RichLabel */ #ifndef TOLUA_DISABLE_tolua_Cocos2d_RichLabel_getString00 static int tolua_Cocos2d_RichLabel_getString00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype(tolua_S,1,"RichLabel",0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; else #endif { RichLabel* self = (RichLabel*) tolua_tousertype(tolua_S,1,0); #ifndef TOLUA_RELEASE if (!self) tolua_error(tolua_S,"invalid 'self' in function 'getString'", NULL); #endif { char* tolua_ret = (char*) self->getString(); tolua_pushstring(tolua_S,(const char*)tolua_ret); } } return 1; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'getString'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* method: getTextSize of class RichLabel */ #ifndef TOLUA_DISABLE_tolua_Cocos2d_RichLabel_getTextSize00 static int tolua_Cocos2d_RichLabel_getTextSize00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype(tolua_S,1,"RichLabel",0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; else #endif { RichLabel* self = (RichLabel*) tolua_tousertype(tolua_S,1,0); #ifndef TOLUA_RELEASE if (!self) tolua_error(tolua_S,"invalid 'self' in function 'getTextSize'", NULL); #endif { CCSize tolua_ret = (CCSize) self->getTextSize(); { #ifdef __cplusplus void* tolua_obj = Mtolua_new((CCSize)(tolua_ret)); tolua_pushusertype(tolua_S,tolua_obj,"CCSize"); tolua_register_gc(tolua_S,lua_gettop(tolua_S)); #else void* tolua_obj = tolua_copy(tolua_S,(void*)&tolua_ret,sizeof(CCSize)); tolua_pushusertype(tolua_S,tolua_obj,"CCSize"); tolua_register_gc(tolua_S,lua_gettop(tolua_S)); #endif } } } return 1; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'getTextSize'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* method: createMask of class DSMask */ #ifndef TOLUA_DISABLE_tolua_Cocos2d_DSMask_createMask00 static int tolua_Cocos2d_DSMask_createMask00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertable(tolua_S,1,"DSMask",0,&tolua_err) || (tolua_isvaluenil(tolua_S,2,&tolua_err) || !tolua_isusertype(tolua_S,2,"CCSize",0,&tolua_err)) || !tolua_isusertype(tolua_S,3,"CCSprite",0,&tolua_err) || !tolua_isnoobj(tolua_S,4,&tolua_err) ) goto tolua_lerror; else #endif { CCSize contentSize = *((CCSize*) tolua_tousertype(tolua_S,2,0)); CCSprite* bg = ((CCSprite*) tolua_tousertype(tolua_S,3,0)); { DSMask* tolua_ret = (DSMask*) DSMask::createMask(contentSize,bg); tolua_pushusertype(tolua_S,(void*)tolua_ret,"DSMask"); } } return 1; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'createMask'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* method: createMask of class DSMask */ #ifndef TOLUA_DISABLE_tolua_Cocos2d_DSMask_createMask01 static int tolua_Cocos2d_DSMask_createMask01(lua_State* tolua_S) { tolua_Error tolua_err; if ( !tolua_isusertable(tolua_S,1,"DSMask",0,&tolua_err) || (tolua_isvaluenil(tolua_S,2,&tolua_err) || !tolua_isusertype(tolua_S,2,"CCSize",0,&tolua_err)) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) goto tolua_lerror; else { CCSize contentSize = *((CCSize*) tolua_tousertype(tolua_S,2,0)); { DSMask* tolua_ret = (DSMask*) DSMask::createMask(contentSize); tolua_pushusertype(tolua_S,(void*)tolua_ret,"DSMask"); } } return 1; tolua_lerror: return tolua_Cocos2d_DSMask_createMask00(tolua_S); } #endif //#ifndef TOLUA_DISABLE /* method: createGuideLayer of class GuideLayer */ #ifndef TOLUA_DISABLE_tolua_Cocos2d_GuideLayer_createGuideLayer00 static int tolua_Cocos2d_GuideLayer_createGuideLayer00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertable(tolua_S,1,"GuideLayer",0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; else #endif { { GuideLayer* tolua_ret = (GuideLayer*) GuideLayer::createGuideLayer(); tolua_pushusertype(tolua_S,(void*)tolua_ret,"GuideLayer"); } } return 1; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'createGuideLayer'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* method: setMaskRect of class GuideLayer */ #ifndef TOLUA_DISABLE_tolua_Cocos2d_GuideLayer_setMaskRect00 static int tolua_Cocos2d_GuideLayer_setMaskRect00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype(tolua_S,1,"GuideLayer",0,&tolua_err) || (tolua_isvaluenil(tolua_S,2,&tolua_err) || !tolua_isusertype(tolua_S,2,"CCRect",0,&tolua_err)) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) goto tolua_lerror; else #endif { GuideLayer* self = (GuideLayer*) tolua_tousertype(tolua_S,1,0); CCRect rect = *((CCRect*) tolua_tousertype(tolua_S,2,0)); #ifndef TOLUA_RELEASE if (!self) tolua_error(tolua_S,"invalid 'self' in function 'setMaskRect'", NULL); #endif { self->setMaskRect(rect); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'setMaskRect'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* method: setMaskPicturePath of class GuideLayer */ #ifndef TOLUA_DISABLE_tolua_Cocos2d_GuideLayer_setMaskPicturePath00 static int tolua_Cocos2d_GuideLayer_setMaskPicturePath00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype(tolua_S,1,"GuideLayer",0,&tolua_err) || !tolua_isstring(tolua_S,2,0,&tolua_err) || !tolua_isstring(tolua_S,3,0,&tolua_err) || (tolua_isvaluenil(tolua_S,4,&tolua_err) || !tolua_isusertype(tolua_S,4,"CCPoint",0,&tolua_err)) || !tolua_isnumber(tolua_S,5,0,&tolua_err) || !tolua_isnumber(tolua_S,6,0,&tolua_err) || !tolua_isnoobj(tolua_S,7,&tolua_err) ) goto tolua_lerror; else #endif { GuideLayer* self = (GuideLayer*) tolua_tousertype(tolua_S,1,0); const char* guideInfo = ((const char*) tolua_tostring(tolua_S,2,0)); const char* guideTips = ((const char*) tolua_tostring(tolua_S,3,0)); CCPoint poxPoint = *((CCPoint*) tolua_tousertype(tolua_S,4,0)); emStandDir dirStand = ((emStandDir) (int) tolua_tonumber(tolua_S,5,0)); emPromptDirection dir = ((emPromptDirection) (int) tolua_tonumber(tolua_S,6,0)); #ifndef TOLUA_RELEASE if (!self) tolua_error(tolua_S,"invalid 'self' in function 'setMaskPicturePath'", NULL); #endif { self->setMaskPicturePath(guideInfo,guideTips,poxPoint,dirStand,dir); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'setMaskPicturePath'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* method: skip of class GuideLayer */ #ifndef TOLUA_DISABLE_tolua_Cocos2d_GuideLayer_skip00 static int tolua_Cocos2d_GuideLayer_skip00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertype(tolua_S,1,"GuideLayer",0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; else #endif { GuideLayer* self = (GuideLayer*) tolua_tousertype(tolua_S,1,0); #ifndef TOLUA_RELEASE if (!self) tolua_error(tolua_S,"invalid 'self' in function 'skip'", NULL); #endif { self->skip(); } } return 0; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'skip'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* method: create of class GraySprite */ #ifndef TOLUA_DISABLE_tolua_Cocos2d_GraySprite_create00 static int tolua_Cocos2d_GraySprite_create00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertable(tolua_S,1,"GraySprite",0,&tolua_err) || !tolua_isstring(tolua_S,2,0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) goto tolua_lerror; else #endif { const char* pszFileName = ((const char*) tolua_tostring(tolua_S,2,0)); { GraySprite* tolua_ret = (GraySprite*) GraySprite::create(pszFileName); tolua_pushusertype(tolua_S,(void*)tolua_ret,"GraySprite"); } } return 1; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'create'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* method: createWithSpriteFrameName of class GraySprite */ #ifndef TOLUA_DISABLE_tolua_Cocos2d_GraySprite_createWithSpriteFrameName00 static int tolua_Cocos2d_GraySprite_createWithSpriteFrameName00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertable(tolua_S,1,"GraySprite",0,&tolua_err) || !tolua_isstring(tolua_S,2,0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) goto tolua_lerror; else #endif { const char* pszSpriteFrameName = ((const char*) tolua_tostring(tolua_S,2,0)); { GraySprite* tolua_ret = (GraySprite*) GraySprite::createWithSpriteFrameName(pszSpriteFrameName); tolua_pushusertype(tolua_S,(void*)tolua_ret,"GraySprite"); } } return 1; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'createWithSpriteFrameName'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* method: createWithTexture of class GraySprite */ #ifndef TOLUA_DISABLE_tolua_Cocos2d_GraySprite_createWithTexture00 static int tolua_Cocos2d_GraySprite_createWithTexture00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertable(tolua_S,1,"GraySprite",0,&tolua_err) || !tolua_isusertype(tolua_S,2,"CCTexture2D",0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) goto tolua_lerror; else #endif { CCTexture2D* pTexture = ((CCTexture2D*) tolua_tousertype(tolua_S,2,0)); { GraySprite* tolua_ret = (GraySprite*) GraySprite::createWithTexture(pTexture); tolua_pushusertype(tolua_S,(void*)tolua_ret,"GraySprite"); } } return 1; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'createWithTexture'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* method: create of class DrawCricleMask */ #ifndef TOLUA_DISABLE_tolua_Cocos2d_DrawCricleMask_create00 static int tolua_Cocos2d_DrawCricleMask_create00(lua_State* tolua_S) { #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( !tolua_isusertable(tolua_S,1,"DrawCricleMask",0,&tolua_err) || !tolua_isnumber(tolua_S,2,0,&tolua_err) || !tolua_isusertype(tolua_S,3,"CCNode",0,&tolua_err) || !tolua_isnoobj(tolua_S,4,&tolua_err) ) goto tolua_lerror; else #endif { float fRadius = ((float) tolua_tonumber(tolua_S,2,0)); CCNode* node = ((CCNode*) tolua_tousertype(tolua_S,3,0)); { DrawCricleMask* tolua_ret = (DrawCricleMask*) DrawCricleMask::create(fRadius,node); tolua_pushusertype(tolua_S,(void*)tolua_ret,"DrawCricleMask"); } } return 1; #ifndef TOLUA_RELEASE tolua_lerror: tolua_error(tolua_S,"#ferror in function 'create'.",&tolua_err); return 0; #endif } #endif //#ifndef TOLUA_DISABLE /* Open function */ TOLUA_API int tolua_Cocos2d_open_for_ExtensionsDS (lua_State* tolua_S) { tolua_open(tolua_S); tolua_reg_types(tolua_S); tolua_module(tolua_S,NULL,0); tolua_beginmodule(tolua_S,NULL); tolua_cclass(tolua_S,"RichLabel","RichLabel","CCLayerRGBA",NULL); tolua_beginmodule(tolua_S,"RichLabel"); tolua_function(tolua_S,"create",tolua_Cocos2d_RichLabel_create00); tolua_function(tolua_S,"setColor",tolua_Cocos2d_RichLabel_setColor00); tolua_function(tolua_S,"getString",tolua_Cocos2d_RichLabel_getString00); tolua_function(tolua_S,"getTextSize",tolua_Cocos2d_RichLabel_getTextSize00); tolua_endmodule(tolua_S); tolua_cclass(tolua_S,"DSMask","DSMask","CCLayerColor",NULL); tolua_beginmodule(tolua_S,"DSMask"); tolua_function(tolua_S,"createMask",tolua_Cocos2d_DSMask_createMask00); tolua_function(tolua_S,"createMask",tolua_Cocos2d_DSMask_createMask01); tolua_endmodule(tolua_S); tolua_constant(tolua_S,"emUpArrow",emUpArrow); tolua_constant(tolua_S,"emDownArrow",emDownArrow); tolua_constant(tolua_S,"emLeftArrow",emLeftArrow); tolua_constant(tolua_S,"emRightArrow",emRightArrow); tolua_constant(tolua_S,"emLeft",emLeft); tolua_constant(tolua_S,"emRight",emRight); tolua_cclass(tolua_S,"GuideLayer","GuideLayer","CCLayer",NULL); tolua_beginmodule(tolua_S,"GuideLayer"); tolua_function(tolua_S,"createGuideLayer",tolua_Cocos2d_GuideLayer_createGuideLayer00); tolua_function(tolua_S,"setMaskRect",tolua_Cocos2d_GuideLayer_setMaskRect00); tolua_function(tolua_S,"setMaskPicturePath",tolua_Cocos2d_GuideLayer_setMaskPicturePath00); tolua_function(tolua_S,"skip",tolua_Cocos2d_GuideLayer_skip00); tolua_endmodule(tolua_S); tolua_cclass(tolua_S,"GraySprite","GraySprite","CCSprite",NULL); tolua_beginmodule(tolua_S,"GraySprite"); tolua_function(tolua_S,"create",tolua_Cocos2d_GraySprite_create00); tolua_function(tolua_S,"createWithSpriteFrameName",tolua_Cocos2d_GraySprite_createWithSpriteFrameName00); tolua_function(tolua_S,"createWithTexture",tolua_Cocos2d_GraySprite_createWithTexture00); tolua_endmodule(tolua_S); tolua_cclass(tolua_S,"DrawCricleMask","DrawCricleMask","CCNode",NULL); tolua_beginmodule(tolua_S,"DrawCricleMask"); tolua_function(tolua_S,"create",tolua_Cocos2d_DrawCricleMask_create00); tolua_endmodule(tolua_S); tolua_endmodule(tolua_S); return 1; }
[ "chenhlb8055@gmail.com" ]
chenhlb8055@gmail.com
cef497f735fbabddfd787d44d52843c202c02f06
734431ff4768b4129450523319ba80ea3e2a5898
/test/flip.cpp
45faf408155b591c6e984ae2799838d2bcb21b45
[]
no_license
dopic/Fit
5b9b8ea8b5505eb585575d3c1c57c34e7b189eb0
d895d531fb27e9ac642158851d6782553d94b9d3
refs/heads/master
2020-12-30T22:09:02.318221
2015-03-18T22:34:02
2015-03-18T22:34:02
33,482,242
1
0
null
2015-04-06T13:04:42
2015-04-06T13:04:42
null
UTF-8
C++
false
false
215
cpp
#include <fit/flip.h> #include <fit/placeholders.h> #include "test.h" FIT_TEST_CASE() { FIT_TEST_CHECK(3 == fit::flip(fit::_ - fit::_)(2, 5)); FIT_STATIC_TEST_CHECK(3 == fit::flip(fit::_ - fit::_)(2, 5)); }
[ "pfultz2@yahoo.com" ]
pfultz2@yahoo.com
e9ae623dc7570ac6dee58c45760afa2438624337
9808c0970f80c3260d1b91a226580aba3e52e2d5
/valdes-engineering/src/investigations/bulkDiffusivityMeasurements2015/beamExpander/adiabatic_rear/aluminum_target/sept24/fit_models.h
9a0e0155ccc7e3d1c83d634a693089187992951e
[]
no_license
raymondvaldes/tat
5d519732efb5ed379be1ac2579a6dbf7ac67e52f
0fa3a1902cf81682d741fe0063435c6b61bac148
refs/heads/master
2021-01-18T15:42:09.009818
2015-10-30T16:55:23
2015-10-30T16:55:23
13,633,268
2
0
null
null
null
null
UTF-8
C++
false
false
972
h
// // asdf.h // tat // // Created by Raymond Valdes on 9/24/15. // Copyright © 2015 Raymond Valdes. All rights reserved. // #ifndef fit_models_asdf_h #define fit_models_asdf_h #include "run1_rear_70degC.h" #include "fit_a_b1_b2_RC.h" namespace investigations{ namespace bulkDiffusivityMeasurements2015{ namespace beamExpander{ namespace adiabatic_rear{ namespace aluminum_target{ namespace sept24{ inline auto fit_models( void ) noexcept -> void { using namespace units; using std::vector; using thermal::experimental::observations::Slab; auto const specimens = vector< Slab >( { run1_rear_70degC(), } ) ; auto const detector_radius = quantity< length >( .25 * millimeters ) ; fit_a_b1_b2_RC( specimens, detector_radius ); } } // namespace sept24 } // namespace aluminum_target } // namesapce adiabatic_rear } // namespace beamExpander } // namespace bulkDiffusivityMeasurements2015 } // namespace investigations #endif /* asdf_h */
[ "raymondvaldes@gmail.com" ]
raymondvaldes@gmail.com
94a434f969372b613b73094534ce370f783953bc
85515970843a39d6ddae0476320c4027aa050e49
/iptux0.5.3/src/SendFileData.cpp
e1c1843423a141f483d700a4764ebd62485390ed
[]
no_license
zzqhost/iptux
ed0ddea05e0ca7bb683e878d97ab4710c4baba21
48a722ea8d76f0df83e69e4e5b5cd2f2b2cc8800
refs/heads/master
2020-05-26T21:50:08.358593
2013-04-09T07:44:21
2013-04-09T07:44:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,131
cpp
// // C++ Implementation: SendFileData // // Description: // // // Author: Jally <jallyx@163.com>, (C) 2009 // // Copyright: See COPYING file that comes with this distribution // // #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include "SendFileData.h" #include "ProgramData.h" #include "MainWindow.h" #include "LogSystem.h" #include "SoundSystem.h" #include "AnalogFS.h" #include "wrapper.h" #include "utils.h" extern ProgramData progdt; extern MainWindow mwin; extern LogSystem lgsys; extern SoundSystem sndsys; /** * 类构造函数. * @param sk tcp socket * @param fl 文件信息数据 */ SendFileData::SendFileData(int sk, FileInfo *fl):sock(sk), file(fl), para(NULL), terminate(false), sumsize(0) { g_datalist_init(&para); gettimeofday(&tasktime, NULL); /* gettimeofday(&filetime, NULL);//个人感觉没必要 */ } /** * 类析构函数. */ SendFileData::~SendFileData() { g_datalist_clear(&para); } /** * 发送文件数据入口. */ void SendFileData::SendFileDataEntry() { /* 创建UI参考数据,并将数据主动加入UI */ gdk_threads_enter(); CreateUIPara(); mwin.UpdateItemToTransTree(&para); if (FLAG_ISSET(progdt.flags, 5)) mwin.OpenTransWindow(); gdk_threads_leave(); /* 分类处理 */ switch (GET_MODE(file->fileattr)) { case IPMSG_FILE_REGULAR: SendRegularFile(); break; case IPMSG_FILE_DIR: SendDirFiles(); break; default: break; } /* 主动更新UI */ gdk_threads_enter(); UpdateUIParaToOver(); mwin.UpdateItemToTransTree(&para); gdk_threads_leave(); /* 处理成功则播放提示音 */ if (!terminate && FLAG_ISSET(progdt.sndfgs, 2)) sndsys.Playing(progdt.transtip); } /** * 获取UI参考数据. * @return UI参考数据 */ GData **SendFileData::GetTransFilePara() { return &para; } /** * 终止过程处理. */ void SendFileData::TerminateTrans() { terminate = true; } /** * 创建UI参考数据. */ void SendFileData::CreateUIPara() { GtkIconTheme *theme; GdkPixbuf *pixbuf; struct in_addr addr; theme = gtk_icon_theme_get_default(); if ((pixbuf = gtk_icon_theme_load_icon(theme, "tip-send", MAX_ICONSIZE, GtkIconLookupFlags(0), NULL))) g_datalist_set_data_full(&para, "status", pixbuf, GDestroyNotify(g_object_unref)); g_datalist_set_data(&para, "task", (gpointer)(_("send"))); g_datalist_set_data_full(&para, "peer", g_strdup(file->fileown->name), GDestroyNotify(g_free)); addr.s_addr = file->fileown->ipv4; g_datalist_set_data_full(&para, "ip", g_strdup(inet_ntoa(addr)), GDestroyNotify(g_free)); g_datalist_set_data_full(&para, "filename", ipmsg_get_filename_me(file->filepath, NULL), GDestroyNotify(g_free)); g_datalist_set_data_full(&para, "filelength", numeric_to_size(file->filesize), GDestroyNotify(g_free)); g_datalist_set_data(&para, "finishlength", (gpointer)("0B")); g_datalist_set_data(&para, "progress", GINT_TO_POINTER(0)); g_datalist_set_data(&para, "pro-text", (gpointer)("0.0%")); g_datalist_set_data(&para, "cost", (gpointer)("00:00:00")); g_datalist_set_data(&para, "remain", (gpointer)(_("unknown"))); g_datalist_set_data(&para, "rate", (gpointer)("0B/s")); g_datalist_set_data(&para, "data", this); } /** * 发送常规文件. */ void SendFileData::SendRegularFile() { int64_t finishsize; int fd; /* 打开文件 */ if ((fd = open(file->filepath, O_RDONLY | O_LARGEFILE)) == -1) { terminate = true; //标记处理过程失败 return; } /* 发送文件数据 */ gettimeofday(&filetime, NULL); finishsize = SendData(fd, file->filesize); close(fd); sumsize += finishsize; /* 考察处理结果 */ if (finishsize < file->filesize) { terminate = true; lgsys.SystemLog(_("Failed to send the file \"%s\" to %s!"), file->filepath, file->fileown->name); } else { lgsys.SystemLog(_("Send the file \"%s\" to %s successfully!"), file->filepath, file->fileown->name); } } /** * 发送目录文件. */ void SendFileData::SendDirFiles() { AnalogFS afs; GQueue dirstack = G_QUEUE_INIT; struct stat64 st; struct dirent *dirt, vdirt; DIR *dir; gchar *dirname, *pathname, *filename; int64_t finishsize; uint32_t headsize; int fd; bool result; /* 转到上传目录位置 */ dirname = ipmsg_get_filename_me(file->filepath, &pathname); afs.chdir(pathname); g_free(pathname); strcpy(vdirt.d_name, dirname); dirt = &vdirt; g_free(dirname); result = false; //预设任务处理失败 dir = NULL; //预设当前目录流无效 goto start; while (!g_queue_is_empty(&dirstack)) { /* 取出最后一次压入堆栈的目录流 */ dir = (DIR *)g_queue_pop_head(&dirstack); /* 发送目录流中的下属数据 */ while (dir && (dirt = readdir(dir))) { if (strcmp(dirt->d_name, ".") == 0 || strcmp(dirt->d_name, "..") == 0) continue; /* 检查文件是否可用 */ start: if (afs.stat(dirt->d_name, &st) == -1 || !(S_ISREG(st.st_mode) || S_ISDIR(st.st_mode))) continue; /* 更新UI参考值 */ g_datalist_set_data_full(&para, "filename", g_strdup(dirt->d_name), GDestroyNotify(g_free)); g_datalist_set_data_full(&para, "filelength", numeric_to_size(st.st_size), GDestroyNotify(g_free)); g_datalist_set_data(&para, "finishlength", (gpointer)("0B")); g_datalist_set_data(&para, "progress", GINT_TO_POINTER(0)); g_datalist_set_data(&para, "pro-text", (gpointer)("0.0%")); g_datalist_set_data(&para, "cost", (gpointer)("00:00:00")); g_datalist_set_data(&para, "remain", (gpointer)(_("unknown"))); g_datalist_set_data(&para, "rate", (gpointer)("0B/s")); /* 转码 */ if (strcasecmp(file->fileown->encode, "utf-8") != 0 && (filename = convert_encode(dirt->d_name, file->fileown->encode, "utf-8"))) { dirname = ipmsg_get_filename_pal(filename); g_free(filename); } else dirname = ipmsg_get_filename_pal(dirt->d_name); /* 构造数据头并发送 */ snprintf(buf, MAX_SOCKLEN, "0000:%s:%.9" PRIx64 ":%lx:%lx=%lx:%lx=%lx:", dirname, S_ISREG(st.st_mode) ? st.st_size :0, S_ISREG(st.st_mode) ? IPMSG_FILE_REGULAR : IPMSG_FILE_DIR, IPMSG_FILE_MTIME,st.st_mtime,IPMSG_FILE_CREATETIME,st.st_ctime); g_free(dirname); headsize = strlen(buf); snprintf(buf, MAX_SOCKLEN, "%.4" PRIx32, headsize); *(buf + 4) = ':'; if (xwrite(sock, buf, headsize) == -1) goto end; /* 选择处理方案 */ gettimeofday(&filetime, NULL); if (S_ISREG(st.st_mode)) { //常规文件 if ((fd = afs.open(dirt->d_name, O_RDONLY | O_LARGEFILE)) == -1) goto end; finishsize = SendData(fd, st.st_size); close(fd); if (finishsize < st.st_size) goto end; sumsize += finishsize; } else if (S_ISDIR(st.st_mode)) { //目录文件 if (dir) //若当前目录流有效则须压入堆栈 g_queue_push_head(&dirstack, dir); /* 打开下属目录 */ if (!(dir = afs.opendir(dirt->d_name))) goto end; /* 本地端也须转至下属目录 */ afs.chdir(dirt->d_name); } } /* 目录流有效才可向上转 */ if (dir) { /* 关闭当前操作的目录流 */ closedir(dir); dir = NULL; /* 构造向上转的数据头并发送 */ snprintf(buf, MAX_SOCKLEN, "0000:.:0:%lx:%lx=%lx:%lx=%lx:", IPMSG_FILE_RETPARENT, IPMSG_FILE_MTIME,st.st_mtime,IPMSG_FILE_CREATETIME,st.st_ctime); headsize = strlen(buf); snprintf(buf, MAX_SOCKLEN, "%.4" PRIx32, headsize); *(buf + 4) = ':'; if (xwrite(sock, buf, headsize) == -1) goto end; /* 本地端也须向上转一层 */ afs.chdir(".."); } } result = true; /* 考察处理结果 */ end: if (!result) { /* 若当前目录流有效,则必须关闭 */ if (dir) closedir(dir); /* 关闭堆栈中所有的目录流,并清空堆栈 */ g_queue_foreach(&dirstack, GFunc(closedir), NULL); g_queue_clear(&dirstack); lgsys.SystemLog(_("Failed to send the directory \"%s\" to %s!"), file->filepath, file->fileown->name); } else { lgsys.SystemLog(_("Send the directory \"%s\" to %s successfully!"), file->filepath, file->fileown->name); } } /** * 发送文件数据. * @param fd file descriptor * @param filesize 文件总长度 * @return 完成数据量 */ int64_t SendFileData::SendData(int fd, int64_t filesize) { int64_t tmpsize, finishsize; struct timeval val1, val2; float difftime, progress; uint32_t rate; ssize_t size; /* 如果文件长度为0,则无须再进一步处理 */ if (filesize == 0) return 0; tmpsize = finishsize = 0; //初始化已完成数据量 gettimeofday(&val1, NULL); //初始化起始时间 do { /* 读取文件数据并发送 */ size = MAX_SOCKLEN < filesize - finishsize ? MAX_SOCKLEN : filesize - finishsize; if ((size = xread(fd, buf, MAX_SOCKLEN)) == -1) return finishsize; if (size > 0 && xwrite(sock, buf, size) == -1) return finishsize; finishsize += size; /* 判断是否需要更新UI参考值 */ gettimeofday(&val2, NULL); difftime = difftimeval(val2, val1); if (difftime >= 1) { /* 更新UI参考值 */ progress = percent(finishsize, filesize); rate = (uint32_t)((finishsize - tmpsize) / difftime); g_datalist_set_data_full(&para, "finishlength", numeric_to_size(finishsize), GDestroyNotify(g_free)); g_datalist_set_data(&para, "progress", GINT_TO_POINTER(GINT(progress))); g_datalist_set_data_full(&para, "pro-text", g_strdup_printf("%.1f", progress), GDestroyNotify(g_free)); g_datalist_set_data_full(&para, "cost", numeric_to_time( (uint32_t)(difftimeval(val2, filetime))), GDestroyNotify(g_free)); g_datalist_set_data_full(&para, "remain", numeric_to_time( (uint32_t)((filesize - finishsize) / rate)), GDestroyNotify(g_free)); g_datalist_set_data_full(&para, "rate", numeric_to_rate(rate), GDestroyNotify(g_free)); val1 = val2; //更新时间参考点 tmpsize = finishsize; //更新下载量 } } while (!terminate && size && finishsize < filesize); return finishsize; } /** * 更新UI参考数据到任务结束. */ void SendFileData::UpdateUIParaToOver() { GtkIconTheme *theme; GdkPixbuf *pixbuf; struct timeval time; const char *statusfile; theme = gtk_icon_theme_get_default(); statusfile = terminate ? "tip-error" : "tip-finish"; if ( (pixbuf = gtk_icon_theme_load_icon(theme, statusfile, MAX_ICONSIZE, GtkIconLookupFlags(0), NULL))) g_datalist_set_data_full(&para, "status", pixbuf, GDestroyNotify(g_object_unref)); if (!terminate && GET_MODE(file->fileattr) == IPMSG_FILE_DIR) { g_datalist_set_data_full(&para, "filename", ipmsg_get_filename_me(file->filepath, NULL), GDestroyNotify(g_free)); g_datalist_set_data_full(&para, "filelength", numeric_to_size(sumsize), GDestroyNotify(g_free)); } if (!terminate) { gettimeofday(&time, NULL); g_datalist_set_data_full(&para, "finishlength", numeric_to_size(sumsize), GDestroyNotify(g_free)); g_datalist_set_data(&para, "progress", GINT_TO_POINTER(100)); g_datalist_set_data(&para, "pro-text", (gpointer)("100%")); g_datalist_set_data_full(&para, "cost", numeric_to_time( (uint32_t)(difftimeval(time, tasktime))), GDestroyNotify(g_free)); g_datalist_set_data(&para, "remain", NULL); g_datalist_set_data(&para, "rate", NULL); } g_datalist_set_data(&para, "data", NULL); }
[ "b649@borqs.com" ]
b649@borqs.com
4cd32807cffd98f94f1276eee77893ee61de3e3b
2f0c70013cb2e8f3815694ae75dd9b73fdf22d33
/spectrum/models/genericE6SSM/genericE6SSM_two_scale_soft_beta_TYd.cpp
ff52d8cc917d9aa0a22a282839b612a222bbea22
[]
no_license
azedarach/E6SSM-Tuning
9d3e0fffb3fe5979b8735a2907219eb944fcfeae
62f8050e814db2e4468b868cb31bcb63ee1dbda2
refs/heads/master
2021-05-31T00:07:01.359375
2016-01-03T22:34:23
2016-01-03T22:34:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,711
cpp
// ==================================================================== // This file is part of FlexibleSUSY. // // FlexibleSUSY is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // FlexibleSUSY is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with FlexibleSUSY. If not, see // <http://www.gnu.org/licenses/>. // ==================================================================== // File generated at Sun 15 Jun 2014 19:16:29 #include "genericE6SSM_two_scale_soft_parameters.hpp" #include "wrappers.hpp" namespace flexiblesusy { #define INPUT(parameter) input.parameter #define TRACE_STRUCT soft_traces /** * Calculates the one-loop beta function of TYd. * * @return one-loop beta function */ Eigen::Matrix<double,3,3> genericE6SSM_soft_parameters::calc_beta_TYd_one_loop(const Soft_traces& soft_traces) const { const auto Qdp = INPUT(Qdp); const auto QH1p = INPUT(QH1p); const auto QQp = INPUT(QQp); const double traceAdjYdTYd = TRACE_STRUCT.traceAdjYdTYd; const double traceAdjYeTYe = TRACE_STRUCT.traceAdjYeTYe; const double traceYdAdjYd = TRACE_STRUCT.traceYdAdjYd; const double traceYeAdjYe = TRACE_STRUCT.traceYeAdjYe; Eigen::Matrix<double,3,3> beta_TYd; beta_TYd = oneOver16PiSqr*(3*traceYdAdjYd*TYd + traceYeAdjYe*TYd + AbsSqr(Lambdax)*TYd - 0.4666666666666667*Sqr(g1)*TYd - 3*Sqr(g2)*TYd - 5.333333333333333*Sqr(g3)*TYd - 2*Sqr(gN)*Sqr(Qdp)*TYd - 2*Sqr(gN)*Sqr( QH1p)*TYd - 2*Sqr(gN)*Sqr(QQp)*TYd + Yd*(6*traceAdjYdTYd + 2* traceAdjYeTYe + 0.9333333333333333*MassB*Sqr(g1) + 6*MassWB*Sqr(g2) + 10.666666666666666*MassG*Sqr(g3) + 4*MassBp*Sqr(gN)*Sqr(Qdp) + 4*MassBp* Sqr(gN)*Sqr(QH1p) + 4*MassBp*Sqr(gN)*Sqr(QQp) + 2*Conj(Lambdax)*TLambdax) + 4*(Yd*Yd.adjoint()*TYd) + 2*(Yd*Yu.adjoint()*TYu) + 5*(TYd*Yd.adjoint( )*Yd) + TYd*Yu.adjoint()*Yu); return beta_TYd; } /** * Calculates the two-loop beta function of TYd. * * @return two-loop beta function */ Eigen::Matrix<double,3,3> genericE6SSM_soft_parameters::calc_beta_TYd_two_loop(const Soft_traces& soft_traces) const { const auto Qdp = INPUT(Qdp); const auto QDxbarp = INPUT(QDxbarp); const auto QDxp = INPUT(QDxp); const auto Qep = INPUT(Qep); const auto QH1p = INPUT(QH1p); const auto QH2p = INPUT(QH2p); const auto QHpbarp = INPUT(QHpbarp); const auto QHpp = INPUT(QHpp); const auto QLp = INPUT(QLp); const auto QQp = INPUT(QQp); const auto QSp = INPUT(QSp); const auto Qup = INPUT(Qup); const double traceYdAdjYd = TRACE_STRUCT.traceYdAdjYd; const double traceYeAdjYe = TRACE_STRUCT.traceYeAdjYe; const double traceAdjYdTYd = TRACE_STRUCT.traceAdjYdTYd; const double traceAdjYeTYe = TRACE_STRUCT.traceAdjYeTYe; const double traceYuAdjYu = TRACE_STRUCT.traceYuAdjYu; const double traceKappaAdjKappa = TRACE_STRUCT.traceKappaAdjKappa; const double traceLambda12AdjLambda12 = TRACE_STRUCT.traceLambda12AdjLambda12; const double traceAdjYuTYu = TRACE_STRUCT.traceAdjYuTYu; const double traceAdjKappaTKappa = TRACE_STRUCT.traceAdjKappaTKappa; const double traceAdjLambda12TLambda12 = TRACE_STRUCT.traceAdjLambda12TLambda12; const double traceYdAdjYdTYdAdjYd = TRACE_STRUCT.traceYdAdjYdTYdAdjYd; const double traceYdAdjYuTYuAdjYd = TRACE_STRUCT.traceYdAdjYuTYuAdjYd; const double traceYeAdjYeTYeAdjYe = TRACE_STRUCT.traceYeAdjYeTYeAdjYe; const double traceYuAdjYdTYdAdjYu = TRACE_STRUCT.traceYuAdjYdTYdAdjYu; const double traceYdAdjYdYdAdjYd = TRACE_STRUCT.traceYdAdjYdYdAdjYd; const double traceYdAdjYuYuAdjYd = TRACE_STRUCT.traceYdAdjYuYuAdjYd; const double traceYeAdjYeYeAdjYe = TRACE_STRUCT.traceYeAdjYeYeAdjYe; Eigen::Matrix<double,3,3> beta_TYd; beta_TYd = twoLoop*(4.588888888888889*Power(g1,4)*TYd + 16.5*Power(g2, 4)*TYd + 14.222222222222221*Power(g3,4)*TYd + 22*Power(gN,4)*Power(Qdp,4) *TYd + 16*Power(gN,4)*Power(QH1p,4)*TYd + 40*Power(gN,4)*Power(QQp,4)*TYd - 9*traceYdAdjYdYdAdjYd*TYd - 3*traceYdAdjYuYuAdjYd*TYd - 3* traceYeAdjYeYeAdjYe*TYd - 3*traceKappaAdjKappa*AbsSqr(Lambdax)*TYd - 2* traceLambda12AdjLambda12*AbsSqr(Lambdax)*TYd - 3*traceYuAdjYu*AbsSqr( Lambdax)*TYd - 0.4*traceYdAdjYd*Sqr(g1)*TYd + 1.2*traceYeAdjYe*Sqr(g1)* TYd + Sqr(g1)*Sqr(g2)*TYd + 16*traceYdAdjYd*Sqr(g3)*TYd + 0.8888888888888888*Sqr(g1)*Sqr(g3)*TYd + 8*Sqr(g2)*Sqr(g3)*TYd + 6* traceYdAdjYd*Sqr(gN)*Sqr(Qdp)*TYd + 0.5333333333333333*Sqr(g1)*Sqr(gN)* Sqr(Qdp)*TYd + 10.666666666666666*Sqr(g3)*Sqr(gN)*Sqr(Qdp)*TYd + 18*Power (gN,4)*Sqr(Qdp)*Sqr(QDxbarp)*TYd + 18*Power(gN,4)*Sqr(Qdp)*Sqr(QDxp)*TYd + 2*traceYeAdjYe*Sqr(gN)*Sqr(Qep)*TYd + 6*Power(gN,4)*Sqr(Qdp)*Sqr(Qep)* TYd - 6*traceYdAdjYd*Sqr(gN)*Sqr(QH1p)*TYd - 2*traceYeAdjYe*Sqr(gN)*Sqr( QH1p)*TYd - 2*AbsSqr(Lambdax)*Sqr(gN)*Sqr(QH1p)*TYd + 1.2*Sqr(g1)*Sqr(gN) *Sqr(QH1p)*TYd + 6*Sqr(g2)*Sqr(gN)*Sqr(QH1p)*TYd + 30*Power(gN,4)*Sqr(Qdp )*Sqr(QH1p)*TYd + 18*Power(gN,4)*Sqr(QDxbarp)*Sqr(QH1p)*TYd + 18*Power(gN ,4)*Sqr(QDxp)*Sqr(QH1p)*TYd + 6*Power(gN,4)*Sqr(Qep)*Sqr(QH1p)*TYd + 2* AbsSqr(Lambdax)*Sqr(gN)*Sqr(QH2p)*TYd + 12*Power(gN,4)*Sqr(Qdp)*Sqr(QH2p) *TYd + 12*Power(gN,4)*Sqr(QH1p)*Sqr(QH2p)*TYd + 4*Power(gN,4)*Sqr(Qdp)* Sqr(QHpbarp)*TYd + 4*Power(gN,4)*Sqr(QH1p)*Sqr(QHpbarp)*TYd + 4*Power(gN, 4)*Sqr(Qdp)*Sqr(QHpp)*TYd + 4*Power(gN,4)*Sqr(QH1p)*Sqr(QHpp)*TYd + 2* traceYeAdjYe*Sqr(gN)*Sqr(QLp)*TYd + 12*Power(gN,4)*Sqr(Qdp)*Sqr(QLp)*TYd + 12*Power(gN,4)*Sqr(QH1p)*Sqr(QLp)*TYd + 6*traceYdAdjYd*Sqr(gN)*Sqr(QQp) *TYd + 0.13333333333333333*Sqr(g1)*Sqr(gN)*Sqr(QQp)*TYd + 6*Sqr(g2)*Sqr( gN)*Sqr(QQp)*TYd + 10.666666666666666*Sqr(g3)*Sqr(gN)*Sqr(QQp)*TYd + 54* Power(gN,4)*Sqr(Qdp)*Sqr(QQp)*TYd + 18*Power(gN,4)*Sqr(QDxbarp)*Sqr(QQp)* TYd + 18*Power(gN,4)*Sqr(QDxp)*Sqr(QQp)*TYd + 6*Power(gN,4)*Sqr(Qep)*Sqr( QQp)*TYd + 48*Power(gN,4)*Sqr(QH1p)*Sqr(QQp)*TYd + 12*Power(gN,4)*Sqr( QH2p)*Sqr(QQp)*TYd + 4*Power(gN,4)*Sqr(QHpbarp)*Sqr(QQp)*TYd + 4*Power(gN ,4)*Sqr(QHpp)*Sqr(QQp)*TYd + 12*Power(gN,4)*Sqr(QLp)*Sqr(QQp)*TYd + 2* AbsSqr(Lambdax)*Sqr(gN)*Sqr(QSp)*TYd + 6*Power(gN,4)*Sqr(Qdp)*Sqr(QSp)* TYd + 6*Power(gN,4)*Sqr(QH1p)*Sqr(QSp)*TYd + 6*Power(gN,4)*Sqr(QQp)*Sqr( QSp)*TYd + 18*Power(gN,4)*Sqr(Qdp)*Sqr(Qup)*TYd + 18*Power(gN,4)*Sqr(QH1p )*Sqr(Qup)*TYd + 18*Power(gN,4)*Sqr(QQp)*Sqr(Qup)*TYd - 3*Sqr(Conj( Lambdax))*Sqr(Lambdax)*TYd - 0.044444444444444446*Yd*(413*Power(g1,4)* MassB + 1280*Power(g3,4)*MassG + 1485*Power(g2,4)*MassWB + 1980*Power(gN, 4)*MassBp*Power(Qdp,4) + 1440*Power(gN,4)*MassBp*Power(QH1p,4) + 3600* Power(gN,4)*MassBp*Power(QQp,4) + 810*traceYdAdjYdTYdAdjYd + 135* traceYdAdjYuTYuAdjYd + 270*traceYeAdjYeTYeAdjYe + 135* traceYuAdjYdTYdAdjYu + 18*traceAdjYdTYd*Sqr(g1) - 54*traceAdjYeTYe*Sqr(g1 ) + 54*MassB*traceYeAdjYe*Sqr(g1) + 45*MassB*Sqr(g1)*Sqr(g2) + 45*MassWB* Sqr(g1)*Sqr(g2) - 720*traceAdjYdTYd*Sqr(g3) + 40*MassB*Sqr(g1)*Sqr(g3) + 40*MassG*Sqr(g1)*Sqr(g3) + 360*MassG*Sqr(g2)*Sqr(g3) + 360*MassWB*Sqr(g2) *Sqr(g3) - 270*traceAdjYdTYd*Sqr(gN)*Sqr(Qdp) + 24*MassB*Sqr(g1)*Sqr(gN)* Sqr(Qdp) + 24*MassBp*Sqr(g1)*Sqr(gN)*Sqr(Qdp) + 480*MassBp*Sqr(g3)*Sqr(gN )*Sqr(Qdp) + 480*MassG*Sqr(g3)*Sqr(gN)*Sqr(Qdp) + 1620*Power(gN,4)*MassBp *Sqr(Qdp)*Sqr(QDxbarp) + 1620*Power(gN,4)*MassBp*Sqr(Qdp)*Sqr(QDxp) - 90* traceAdjYeTYe*Sqr(gN)*Sqr(Qep) + 90*MassBp*traceYeAdjYe*Sqr(gN)*Sqr(Qep) + 540*Power(gN,4)*MassBp*Sqr(Qdp)*Sqr(Qep) + 270*traceAdjYdTYd*Sqr(gN)* Sqr(QH1p) + 90*traceAdjYeTYe*Sqr(gN)*Sqr(QH1p) - 90*MassBp*traceYeAdjYe* Sqr(gN)*Sqr(QH1p) + 54*MassB*Sqr(g1)*Sqr(gN)*Sqr(QH1p) + 54*MassBp*Sqr(g1 )*Sqr(gN)*Sqr(QH1p) + 270*MassBp*Sqr(g2)*Sqr(gN)*Sqr(QH1p) + 270*MassWB* Sqr(g2)*Sqr(gN)*Sqr(QH1p) + 2700*Power(gN,4)*MassBp*Sqr(Qdp)*Sqr(QH1p) + 1620*Power(gN,4)*MassBp*Sqr(QDxbarp)*Sqr(QH1p) + 1620*Power(gN,4)*MassBp* Sqr(QDxp)*Sqr(QH1p) + 540*Power(gN,4)*MassBp*Sqr(Qep)*Sqr(QH1p) + 1080* Power(gN,4)*MassBp*Sqr(Qdp)*Sqr(QH2p) + 1080*Power(gN,4)*MassBp*Sqr(QH1p) *Sqr(QH2p) + 360*Power(gN,4)*MassBp*Sqr(Qdp)*Sqr(QHpbarp) + 360*Power(gN, 4)*MassBp*Sqr(QH1p)*Sqr(QHpbarp) + 360*Power(gN,4)*MassBp*Sqr(Qdp)*Sqr( QHpp) + 360*Power(gN,4)*MassBp*Sqr(QH1p)*Sqr(QHpp) - 90*traceAdjYeTYe*Sqr (gN)*Sqr(QLp) + 90*MassBp*traceYeAdjYe*Sqr(gN)*Sqr(QLp) + 1080*Power(gN,4 )*MassBp*Sqr(Qdp)*Sqr(QLp) + 1080*Power(gN,4)*MassBp*Sqr(QH1p)*Sqr(QLp) - 270*traceAdjYdTYd*Sqr(gN)*Sqr(QQp) + 6*MassB*Sqr(g1)*Sqr(gN)*Sqr(QQp) + 6*MassBp*Sqr(g1)*Sqr(gN)*Sqr(QQp) + 270*MassBp*Sqr(g2)*Sqr(gN)*Sqr(QQp) + 270*MassWB*Sqr(g2)*Sqr(gN)*Sqr(QQp) + 480*MassBp*Sqr(g3)*Sqr(gN)*Sqr(QQp ) + 480*MassG*Sqr(g3)*Sqr(gN)*Sqr(QQp) + 4860*Power(gN,4)*MassBp*Sqr(Qdp) *Sqr(QQp) + 1620*Power(gN,4)*MassBp*Sqr(QDxbarp)*Sqr(QQp) + 1620*Power(gN ,4)*MassBp*Sqr(QDxp)*Sqr(QQp) + 540*Power(gN,4)*MassBp*Sqr(Qep)*Sqr(QQp) + 4320*Power(gN,4)*MassBp*Sqr(QH1p)*Sqr(QQp) + 1080*Power(gN,4)*MassBp* Sqr(QH2p)*Sqr(QQp) + 360*Power(gN,4)*MassBp*Sqr(QHpbarp)*Sqr(QQp) + 360* Power(gN,4)*MassBp*Sqr(QHpp)*Sqr(QQp) + 1080*Power(gN,4)*MassBp*Sqr(QLp)* Sqr(QQp) - 18*traceYdAdjYd*(MassB*Sqr(g1) - 5*(8*MassG*Sqr(g3) + 3*MassBp *Sqr(gN)*(Sqr(Qdp) - Sqr(QH1p) + Sqr(QQp)))) + 540*Power(gN,4)*MassBp*Sqr (Qdp)*Sqr(QSp) + 540*Power(gN,4)*MassBp*Sqr(QH1p)*Sqr(QSp) + 540*Power(gN ,4)*MassBp*Sqr(QQp)*Sqr(QSp) + 1620*Power(gN,4)*MassBp*Sqr(Qdp)*Sqr(Qup) + 1620*Power(gN,4)*MassBp*Sqr(QH1p)*Sqr(Qup) + 1620*Power(gN,4)*MassBp* Sqr(QQp)*Sqr(Qup) + 270*Lambdax*Sqr(Conj(Lambdax))*TLambdax - 45*Conj( Lambdax)*(Lambdax*(-3*traceAdjKappaTKappa - 2*traceAdjLambda12TLambda12 - 3*traceAdjYuTYu + 2*MassBp*Sqr(gN)*Sqr(QH1p) - 2*MassBp*Sqr(gN)*Sqr(QH2p ) - 2*MassBp*Sqr(gN)*Sqr(QSp)) - (3*traceKappaAdjKappa + 2* traceLambda12AdjLambda12 + 3*traceYuAdjYu + 2*Sqr(gN)*Sqr(QH1p) - 2*Sqr( gN)*Sqr(QH2p) - 2*Sqr(gN)*Sqr(QSp))*TLambdax)) - 0.4*(45*traceAdjYdTYd + 15*traceAdjYeTYe + 4*MassB*Sqr(g1) + 30*MassWB*Sqr(g2) - 10*MassBp*Sqr(gN )*Sqr(Qdp) + 30*MassBp*Sqr(gN)*Sqr(QH1p) + 10*MassBp*Sqr(gN)*Sqr(QQp) + 15*Conj(Lambdax)*TLambdax)*(Yd*Yd.adjoint()*Yd) - 12*traceYdAdjYd*(Yd* Yd.adjoint()*TYd) - 4*traceYeAdjYe*(Yd*Yd.adjoint()*TYd) - 4*AbsSqr( Lambdax)*(Yd*Yd.adjoint()*TYd) + 1.2*Sqr(g1)*(Yd*Yd.adjoint()*TYd) + 6* Sqr(g2)*(Yd*Yd.adjoint()*TYd) + 8*Sqr(gN)*Sqr(QH1p)*(Yd*Yd.adjoint()*TYd) - 6*traceAdjYuTYu*(Yd*Yu.adjoint()*Yu) - 1.6*MassB*Sqr(g1)*(Yd* Yu.adjoint()*Yu) - 4*MassBp*Sqr(gN)*Sqr(QH2p)*(Yd*Yu.adjoint()*Yu) + 4* MassBp*Sqr(gN)*Sqr(QQp)*(Yd*Yu.adjoint()*Yu) - 4*MassBp*Sqr(gN)*Sqr(Qup)* (Yd*Yu.adjoint()*Yu) - 2*Conj(Lambdax)*TLambdax*(Yd*Yu.adjoint()*Yu) - 6* traceYuAdjYu*(Yd*Yu.adjoint()*TYu) - 2*AbsSqr(Lambdax)*(Yd*Yu.adjoint()* TYu) + 1.6*Sqr(g1)*(Yd*Yu.adjoint()*TYu) + 4*Sqr(gN)*Sqr(QH2p)*(Yd* Yu.adjoint()*TYu) - 4*Sqr(gN)*Sqr(QQp)*(Yd*Yu.adjoint()*TYu) + 4*Sqr(gN)* Sqr(Qup)*(Yd*Yu.adjoint()*TYu) - 15*traceYdAdjYd*(TYd*Yd.adjoint()*Yd) - 5*traceYeAdjYe*(TYd*Yd.adjoint()*Yd) - 5*AbsSqr(Lambdax)*(TYd*Yd.adjoint( )*Yd) + 1.2*Sqr(g1)*(TYd*Yd.adjoint()*Yd) + 12*Sqr(g2)*(TYd*Yd.adjoint()* Yd) - 6*Sqr(gN)*Sqr(Qdp)*(TYd*Yd.adjoint()*Yd) + 10*Sqr(gN)*Sqr(QH1p)*( TYd*Yd.adjoint()*Yd) + 6*Sqr(gN)*Sqr(QQp)*(TYd*Yd.adjoint()*Yd) - 3* traceYuAdjYu*(TYd*Yu.adjoint()*Yu) - AbsSqr(Lambdax)*(TYd*Yu.adjoint()*Yu ) + 0.8*Sqr(g1)*(TYd*Yu.adjoint()*Yu) + 2*Sqr(gN)*Sqr(QH2p)*(TYd* Yu.adjoint()*Yu) - 2*Sqr(gN)*Sqr(QQp)*(TYd*Yu.adjoint()*Yu) + 2*Sqr(gN)* Sqr(Qup)*(TYd*Yu.adjoint()*Yu) - 6*(Yd*Yd.adjoint()*Yd*Yd.adjoint()*TYd) - 8*(Yd*Yd.adjoint()*TYd*Yd.adjoint()*Yd) - 2*(Yd*Yu.adjoint()*Yu* Yd.adjoint()*TYd) - 4*(Yd*Yu.adjoint()*Yu*Yu.adjoint()*TYu) - 4*(Yd* Yu.adjoint()*TYu*Yd.adjoint()*Yd) - 4*(Yd*Yu.adjoint()*TYu*Yu.adjoint()* Yu) - 6*(TYd*Yd.adjoint()*Yd*Yd.adjoint()*Yd) - 4*(TYd*Yu.adjoint()*Yu* Yd.adjoint()*Yd) - 2*(TYd*Yu.adjoint()*Yu*Yu.adjoint()*Yu)); return beta_TYd; } } // namespace flexiblesusy
[ "dylan.harries@adelaide.edu.au" ]
dylan.harries@adelaide.edu.au
ed920c83d7b4584a0fcb0fc0fea55f795d3fb57c
1a9bb62b32771102c0b32ffefe305ca702bea268
/tide/core/configuration/Configuration.h
297ff1b68fc9def56ed0641fcb4aab1edb2a207e
[ "BSD-2-Clause" ]
permissive
BlueBrain/Tide
9fa3a5b802026f204491eb625653d6e431c2bea8
e35a8952b3c8ea86db098602f2d95fb4ba542dae
refs/heads/master
2022-05-07T01:14:44.308665
2022-04-27T13:47:18
2022-04-27T13:47:18
54,562,203
52
21
BSD-2-Clause
2022-04-27T13:47:19
2016-03-23T13:33:25
C++
UTF-8
C++
false
false
6,568
h
/*********************************************************************/ /* Copyright (c) 2013-2018, EPFL/Blue Brain Project */ /* Raphael Dumusc <raphael.dumusc@epfl.ch> */ /* All rights reserved. */ /* */ /* Redistribution and use in source and binary forms, with or */ /* without modification, are permitted provided that the following */ /* conditions are met: */ /* */ /* 1. Redistributions of source code must retain the above */ /* copyright notice, this list of conditions and the following */ /* disclaimer. */ /* */ /* 2. Redistributions in binary form must reproduce the above */ /* copyright notice, this list of conditions and the following */ /* disclaimer in the documentation and/or other materials */ /* provided with the distribution. */ /* */ /* THIS SOFTWARE IS PROVIDED BY THE ECOLE POLYTECHNIQUE */ /* FEDERALE DE LAUSANNE ''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 ECOLE */ /* POLYTECHNIQUE FEDERALE DE LAUSANNE 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. */ /* */ /* The views and conclusions contained in the software and */ /* documentation are those of the authors and should not be */ /* interpreted as representing official policies, either expressed */ /* or implied, of Ecole polytechnique federale de Lausanne. */ /*********************************************************************/ #ifndef CONFIGURATION_H #define CONFIGURATION_H #include "configuration/Process.h" #include "configuration/Screen.h" #include "configuration/SurfaceConfig.h" /** * The Configuration manages all the parameters needed to setup the processes. * * @warning: this class can only be used AFTER creating a QApplication. */ class Configuration { public: /** Default constructor used for deserialization. */ Configuration() = default; /** * Constructor * @param filename \see Configuration * @throw std::runtime_error if the file could not be read */ Configuration(const QString& filename); /** The list of display surfaces. */ std::vector<SurfaceConfig> surfaces; /** The list of render processes. */ std::vector<Process> processes; struct Folders { /** Root directory for opening contents. */ QString contents; /** Sessions directory. */ QString sessions; /** Directory for uploading temporay contents via web interface. */ QString tmp; /** Directory for saving session contents uploaded via web interface. */ QString upload; } folders; struct Global { SwapSync swapsync = SwapSync::software; } global; struct Launcher { /** DISPLAY identifier in string format for the Launcher. */ QString display; /** URL of Rendering Resources Manager's API for the demo service. */ QString demoServiceUrl; } launcher; struct Master { /** Hostname where the application is running. */ QString hostname; /** Display identifier in string format matching DISPLAY env_var. */ QString display; /** Master application is headless (no visible window) */ bool headless = false; /** Serial port used to control Planar equipment. */ QString planarSerialPort; /** Port for the WebService server to listen for incoming requests. */ uint16_t webservicePort = 8888; } master; struct Settings { /** Informative name of the installation. */ QString infoName; /** Timeout in minutes after which the screens should be turned off. */ uint inactivityTimeout = 60; /** Number of touch points required to power on screens. */ uint touchpointsToWakeup = 1; /** Maximum scaling factor for bitmap contents. */ double contentMaxScale = 0.0; /** Maximum scaling factor for vectorial contents. */ double contentMaxScaleVectorial = 0.0; } settings; struct Webbrowser { /** URL used as start page when opening a Web Browser. */ QString defaultUrl; /** Default size to use when opening a Web Browser. */ QSize defaultSize{1280, 1024}; } webbrowser; struct Whiteboard { /** Directory used for saving whiteboard images. */ QString saveDir; /** Default size to use when opening a Web Browser. */ QSize defaultSize{1920, 1080}; } whiteboard; /** * Save background changes to the current file. * @return true on success, false on failure. */ bool saveBackgroundChanges() const; /** * Save background changes to the specified file. * @param filename destination file. * @return true on success, false on failure. */ bool saveBackgroundChanges(const QString& filename) const; /** @return a default configuration, useful for comparing default values. */ static Configuration defaults(); private: QString _filename; bool _isXml() const; void _loadJson(); void _loadXml(); bool _saveJson(const QString& saveFilename) const; bool _saveXml(const QString& saveFilename) const; void _setDefaults(); }; #endif
[ "raphael.dumusc@epfl.ch" ]
raphael.dumusc@epfl.ch
fcb02db4a7cc309e81b6c76bd0b5b5913660dc50
b1905a6fff073d63ca9a9f93475d35758b5a9c76
/src/names/mempool.cpp
c27060d4dc725ff53ea1de4cba4eb5a1a36d90d7
[ "MIT" ]
permissive
transferdeer/namecoin-core
3800be405bb4ee7536a571040a6b73f92c1a8d91
d42521bf1364dac0efa6b38b1355dd13a8298207
refs/heads/master
2023-05-29T13:10:02.092814
2021-06-07T08:23:28
2021-06-07T08:23:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,915
cpp
// Copyright (c) 2014-2021 Daniel Kraft // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <names/mempool.h> #include <coins.h> #include <logging.h> #include <names/encoding.h> #include <script/names.h> #include <txmempool.h> #include <util/strencodings.h> #include <validation.h> /* ************************************************************************** */ unsigned CNameMemPool::pendingChainLength (const valtype& name) const { unsigned res = 0; if (registersName (name)) ++res; const auto mit = updates.find (name); if (mit != updates.end ()) res += mit->second.size (); return res; } namespace { /** * Returns the outpoint matching the name operation in a given mempool tx, if * there is any. The txid must be for an entry in the mempool. */ COutPoint getNameOutput (const CTxMemPool& pool, const uint256& txid) { AssertLockHeld (pool.cs); const auto mit = pool.mapTx.find (txid); assert (mit != pool.mapTx.end ()); const auto& vout = mit->GetTx ().vout; for (unsigned i = 0; i != vout.size (); ++i) { const CNameScript nameOp(vout[i].scriptPubKey); if (nameOp.isNameOp ()) return COutPoint (txid, i); } return COutPoint (); } } // anonymous namespace COutPoint CNameMemPool::lastNameOutput (const valtype& name) const { const auto itUpd = updates.find (name); if (itUpd != updates.end ()) { /* From all the pending updates, we have to find the last one. This is the unique outpoint that is not also spent by some other transaction. Thus, we keep track of all the transactions spent as well, and then remove those from the sets of candidates. Doing so by txid (rather than outpoint) is enough, as those transactions must be in a "chain" anyway. */ const std::set<uint256>& candidateTxids = itUpd->second; std::set<uint256> spentTxids; for (const auto& txid : candidateTxids) { const auto mit = pool.mapTx.find (txid); assert (mit != pool.mapTx.end ()); for (const auto& in : mit->GetTx ().vin) spentTxids.insert (in.prevout.hash); } COutPoint res; for (const auto& txid : candidateTxids) { if (spentTxids.count (txid) > 0) continue; assert (res.IsNull ()); res = getNameOutput (pool, txid); } assert (!res.IsNull ()); return res; } const auto itReg = mapNameRegs.find (name); if (itReg != mapNameRegs.end ()) return getNameOutput (pool, itReg->second); return COutPoint (); } void CNameMemPool::addUnchecked (const CTxMemPoolEntry& entry) { AssertLockHeld (pool.cs); const uint256& txHash = entry.GetTx ().GetHash (); if (entry.isNameNew ()) { const valtype& newHash = entry.getNameNewHash (); const auto mit = mapNameNews.find (newHash); if (mit != mapNameNews.end ()) assert (mit->second == txHash); else mapNameNews.insert (std::make_pair (newHash, txHash)); } if (entry.isNameRegistration ()) { const valtype& name = entry.getName (); assert (mapNameRegs.count (name) == 0); mapNameRegs.insert (std::make_pair (name, txHash)); } if (entry.isNameUpdate ()) { const valtype& name = entry.getName (); const auto mit = updates.find (name); if (mit == updates.end ()) updates.emplace (name, std::set<uint256> ({txHash})); else mit->second.insert (txHash); } } void CNameMemPool::remove (const CTxMemPoolEntry& entry) { AssertLockHeld (pool.cs); if (entry.isNameRegistration ()) { const auto mit = mapNameRegs.find (entry.getName ()); assert (mit != mapNameRegs.end ()); mapNameRegs.erase (mit); } if (entry.isNameUpdate ()) { const auto itName = updates.find (entry.getName ()); assert (itName != updates.end ()); auto& txids = itName->second; const auto itTxid = txids.find (entry.GetTx ().GetHash ()); assert (itTxid != txids.end ()); txids.erase (itTxid); if (txids.empty ()) updates.erase (itName); } } void CNameMemPool::removeConflicts (const CTransaction& tx) { AssertLockHeld (pool.cs); if (!tx.IsNamecoin ()) return; for (const auto& txout : tx.vout) { const CNameScript nameOp(txout.scriptPubKey); if (nameOp.isNameOp () && nameOp.getNameOp () == OP_NAME_FIRSTUPDATE) { const valtype& name = nameOp.getOpName (); const auto mit = mapNameRegs.find (name); if (mit != mapNameRegs.end ()) { const auto mit2 = pool.mapTx.find (mit->second); assert (mit2 != pool.mapTx.end ()); pool.removeRecursive (mit2->GetTx (), MemPoolRemovalReason::NAME_CONFLICT); } } } } void CNameMemPool::removeUnexpireConflicts (const std::set<valtype>& unexpired) { AssertLockHeld (pool.cs); for (const auto& name : unexpired) { LogPrint (BCLog::NAMES, "unexpired: %s, mempool: %u\n", EncodeNameForMessage (name), mapNameRegs.count (name)); const auto mit = mapNameRegs.find (name); if (mit != mapNameRegs.end ()) { const CTxMemPool::txiter mit2 = pool.mapTx.find (mit->second); assert (mit2 != pool.mapTx.end ()); pool.removeRecursive (mit2->GetTx (), MemPoolRemovalReason::NAME_CONFLICT); } } } void CNameMemPool::removeExpireConflicts (const std::set<valtype>& expired) { AssertLockHeld (pool.cs); for (const auto& name : expired) { LogPrint (BCLog::NAMES, "expired: %s\n", EncodeNameForMessage (name)); const auto mit = updates.find (name); if (mit == updates.end ()) continue; /* We need to make sure that we keep our copy of txids even when the transactions are removed one by one. */ const std::set<uint256> txidsCopy = mit->second; for (const auto& txid : txidsCopy) { const CTxMemPool::txiter mit2 = pool.mapTx.find (txid); assert (mit2 != pool.mapTx.end ()); pool.removeRecursive (mit2->GetTx (), MemPoolRemovalReason::NAME_CONFLICT); } assert (updates.count (name) == 0); } } void CNameMemPool::check (ChainstateManager& chainman, CChainState& active_chainstate) const { AssertLockHeld (pool.cs); const auto& coins = active_chainstate.CoinsTip (); const uint256 blockHash = coins.GetBestBlock (); int nHeight; if (blockHash.IsNull()) nHeight = 0; else nHeight = chainman.BlockIndex ().find (blockHash)->second->nHeight; std::set<valtype> nameRegs; std::map<valtype, unsigned> nameUpdates; for (const auto& entry : pool.mapTx) { const uint256 txHash = entry.GetTx ().GetHash (); if (entry.isNameNew ()) { const valtype& newHash = entry.getNameNewHash (); const auto mit = mapNameNews.find (newHash); assert (mit != mapNameNews.end ()); assert (mit->second == txHash); } if (entry.isNameRegistration ()) { const valtype& name = entry.getName (); const auto mit = mapNameRegs.find (name); assert (mit != mapNameRegs.end ()); assert (mit->second == txHash); assert (nameRegs.count (name) == 0); nameRegs.insert (name); /* The old name should be expired already. Note that we use nHeight+1 for the check, because that's the height at which the mempool tx will actually be mined. */ CNameData data; if (coins.GetName (name, data)) assert (data.isExpired (nHeight + 1)); } if (entry.isNameUpdate ()) { const valtype& name = entry.getName (); const auto mit = updates.find (name); assert (mit != updates.end ()); assert (mit->second.count (txHash) > 0); ++nameUpdates[name]; /* As above, use nHeight+1 for the expiration check. */ CNameData data; if (coins.GetName (name, data)) assert (!data.isExpired (nHeight + 1)); else assert (registersName (name)); } } assert (nameRegs.size () == mapNameRegs.size ()); assert (nameUpdates.size () == updates.size ()); for (const auto& upd : nameUpdates) assert (updates.at (upd.first).size () == upd.second); } bool CNameMemPool::checkTx (const CTransaction& tx) const { AssertLockHeld (pool.cs); if (!tx.IsNamecoin ()) return true; for (const auto& txout : tx.vout) { const CNameScript nameOp(txout.scriptPubKey); if (!nameOp.isNameOp ()) continue; switch (nameOp.getNameOp ()) { case OP_NAME_NEW: { const valtype& newHash = nameOp.getOpHash (); std::map<valtype, uint256>::const_iterator mi; mi = mapNameNews.find (newHash); if (mi != mapNameNews.end () && mi->second != tx.GetHash ()) return false; break; } case OP_NAME_FIRSTUPDATE: { const valtype& name = nameOp.getOpName (); if (registersName (name)) return false; break; } case OP_NAME_UPDATE: /* Multiple updates of the same name in a chain are perfectly fine. The main mempool logic takes care that updates are ordered properly and really a chain, as this is automatic due to the coloured-coin nature of names. */ break; default: assert (false); } } return true; }
[ "d@domob.eu" ]
d@domob.eu
a39da48198dd89cd99930e80b97855e3fd33a20b
c8e3da287e92eb3e24b7f1dbefddde083053754a
/src/SerializableArray.h
f4b035f53eb61f986fb1bc983ceb4e93be75cb94
[]
no_license
rvishna/flow-shop-scheduler
e55269cdfbcc2a69ad32569cbccbc6fbddbb59b1
d36d52c0bf56d47be9c8d556f3a7b7229fb86915
refs/heads/master
2023-03-25T19:24:33.868554
2021-03-23T06:10:22
2021-03-23T06:10:22
348,830,865
1
0
null
null
null
null
UTF-8
C++
false
false
2,054
h
#ifndef SERIALIZABLE_ARRAY_H #define SERIALIZABLE_ARRAY_H #include "DataContext.h" namespace flow_shop_scheduler { template<typename T> class SerializableArray : public JSONSerializable { public: virtual void set(json&) const override; virtual void get(const json&, std::shared_ptr<DataContext> dataContext = nullptr) override; std::size_t size() const { return data_.size(); } bool empty() const { return data_.empty(); } T& operator[](std::size_t i) { return data_[i]; } const T& operator[](std::size_t i) const { return data_[i]; } typedef typename std::vector<T>::iterator iterator; typedef typename std::vector<T>::const_iterator const_iterator; iterator begin() noexcept { return data_.begin(); } iterator end() noexcept { return data_.end(); } const_iterator begin() const noexcept { return data_.begin(); } const_iterator end() const noexcept { return data_.end(); } void push_back(const T& val) { data_.push_back(val); } private: std::vector<T> data_; }; template<typename T> void SerializableArray<T>::set(json& j) const { j = data_; } template<typename T> void SerializableArray<T>::get(const json& j, std::shared_ptr<DataContext> dataContext) { if(!j.is_array()) { std::ostringstream oss; oss << "Deserializing to " << T::Name(true) << " requires a JSON array."; throw Exception(oss.str()); } for(const auto& o : j) { try { data_.push_back(o.get<T>()); } catch(const json::type_error& e) { if(e.id == 302) throw InvalidType::Create(T::Name(), o, e.what()); else throw; } catch(const json::out_of_range& e) { if(e.id == 403) throw MandatoryFieldMissing::Create(T::Name(), o, e.what()); else throw; } if(dataContext) data_.back().setDataContext(dataContext); } } } // namespace flow_shop_scheduler #endif
[ "rvishnampet@gmail.com" ]
rvishnampet@gmail.com
bc0b5fb2921833ec34fad9ba1af60d8cb87d43b1
b1d02643a70ce076f167a84eb1ff36bfcdb5b704
/e/time.h
ff0fd4006f0a49da19279ae4f58926109ea4acdb
[]
no_license
cnangel/libe
b534b90c8710243f37f407b360200bb215572df3
9e2c6af24b4ca5b388243af882ea8fdbb8a0583b
refs/heads/master
2021-01-20T18:43:30.808316
2016-05-30T09:36:31
2016-05-30T09:36:31
59,999,009
0
0
null
null
null
null
UTF-8
C++
false
false
1,723
h
// Copyright (c) 2011, Robert Escriva // 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. // * Neither the name of this project nor the names of its contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifndef e_time_h_ #define e_time_h_ // C #include <stdint.h> namespace e { uint64_t time(); } // namespace e #endif // e_time_h_
[ "cnangel@gmail.com" ]
cnangel@gmail.com
bca7c2163b5e24c1392c716253f18bb4bdef6063
5363c29a3631ddf7739e03bce9f8eec7733300bf
/Reme/src/Reme/Events/ApplicationEvent.h
c699b598c22fac99955b147c10980ebe3e3e6f38
[]
no_license
remtori/Reme
a6b8e3aa9c9785a6e0d11ba3f4b80a38cc7e3251
ba85a9bf98dfb0ff553b470daf34ed807f30333a
refs/heads/master
2021-02-17T14:49:12.409353
2020-04-27T02:48:38
2020-04-27T02:48:38
245,104,489
2
0
null
2020-04-27T02:48:39
2020-03-05T08:10:39
C++
UTF-8
C++
false
false
1,284
h
#pragma once #include "Reme/Events/Event.h" namespace Reme { class WindowResizeEvent : public Event { public: WindowResizeEvent(unsigned int width, unsigned int height) : m_Width(width), m_Height(height) {} inline unsigned int GetWidth() const { return m_Width; } inline unsigned int GetHeight() const { return m_Height; } std::string ToString() const override { std::stringstream ss; ss << "WindowResizeEvent: " << m_Width << ", " << m_Height; return ss.str(); } EVENT_CLASS_TYPE(WindowResize) EVENT_CLASS_CATEGORY(EventCategoryApplication) private: unsigned int m_Width, m_Height; }; class WindowCloseEvent : public Event { public: WindowCloseEvent() = default; EVENT_CLASS_TYPE(WindowClose) EVENT_CLASS_CATEGORY(EventCategoryApplication) }; class AppTickEvent : public Event { public: AppTickEvent() = default; EVENT_CLASS_TYPE(AppTick) EVENT_CLASS_CATEGORY(EventCategoryApplication) }; class AppUpdateEvent : public Event { public: AppUpdateEvent() = default; EVENT_CLASS_TYPE(AppUpdate) EVENT_CLASS_CATEGORY(EventCategoryApplication) }; class AppRenderEvent : public Event { public: AppRenderEvent() = default; EVENT_CLASS_TYPE(AppRender) EVENT_CLASS_CATEGORY(EventCategoryApplication) }; }
[ "lqv.remtori@gmail.com" ]
lqv.remtori@gmail.com
92eac32f9362139f98ca92273c5b56c18c748f61
5031748db8679263b080e625bcd71b8324dc2e45
/polymorphism_virtual/source/static_local_obj.h
8052068ed7be2b7b2cfcd91284bece6fd6c78a7d
[]
no_license
MingYueRuYa/cpp_inside_object
d9e40092a6e4f39a2d89ed61287958903a9e2788
a142c27de275e994333e60434f92c170640ca842
refs/heads/master
2021-06-09T16:25:58.594969
2021-05-23T04:38:50
2021-05-23T04:38:50
180,293,312
2
2
null
null
null
null
UTF-8
C++
false
false
860
h
/**************************************************************************** ** ** Copyright (C) 2019 635672377@qq.com ** All rights reserved. ** ****************************************************************************/ #ifndef static_local_obj_h #define static_local_obj_h #include <Windows.h> #include <iostream> #include <thread> using std::cout; using std::endl; using std::thread; namespace static_local_obj { class Obj { public: Obj() { ++number; } int number = 0; }; void static_local_obj() { static Obj obj; obj.number = 1; cout << obj.number << endl; } void test_static_local_obj() { // for (;;) { // Sleep(5000); // for (int i = 0; i < 10; ++i) { // thread t1(static_local_obj); // t1.detach(); // } // } static_local_obj(); } } #endif // virtual_fun_table_h
[ "liushixiong@flash.cn" ]
liushixiong@flash.cn
93bce8db60f0b5c5f6a547f18e5ea477664bb386
363ed21924ca293ce9f7a375840eb70a0d1900a4
/utility/geoip/geoip_deprecated.cpp
187e09eb07faf603fc070fab1234e9a6b2214c6f
[]
no_license
voseventosixm/porchswingchair
a4577227a93fb941ddb14ff3587772f488249c2e
6bc4466d8522612cbac069fa28fdc00f33246ce2
refs/heads/master
2021-01-23T08:15:22.607557
2017-03-28T17:28:26
2017-03-28T17:28:26
86,490,216
0
0
null
null
null
null
UTF-8
C++
false
false
7,538
cpp
#include "geoip_internal.h" char * GeoIP_org_by_ipnum(GeoIP * gi, unsigned long ipnum) { GeoIPLookup gl; return GeoIP_name_by_ipnum_gl(gi, ipnum, &gl); } char * GeoIP_org_by_ipnum_v6(GeoIP * gi, geoipv6_t ipnum) { GeoIPLookup gl; return GeoIP_name_by_ipnum_v6_gl(gi, ipnum, &gl); } char * GeoIP_org_by_addr(GeoIP * gi, const char *addr) { GeoIPLookup gl; return GeoIP_name_by_addr_gl(gi, addr, &gl); } char * GeoIP_org_by_addr_v6(GeoIP * gi, const char *addr) { GeoIPLookup gl; return GeoIP_name_by_addr_v6_gl(gi, addr, &gl); } char * GeoIP_org_by_name(GeoIP * gi, const char *name) { GeoIPLookup gl; return GeoIP_name_by_name_gl(gi, name, &gl); } char * GeoIP_org_by_name_v6(GeoIP * gi, const char *name) { GeoIPLookup gl; return GeoIP_name_by_name_v6_gl(gi, name, &gl); } int GeoIP_last_netmask(GeoIP * gi) { return gi->netmask; } unsigned int _GeoIP_seek_record_v6(GeoIP * gi, geoipv6_t ipnum) { GeoIPLookup gl; return _GeoIP_seek_record_v6_gl(gi, ipnum, &gl); } unsigned int _GeoIP_seek_record(GeoIP * gi, unsigned long ipnum) { GeoIPLookup gl; return _GeoIP_seek_record_gl(gi, ipnum, &gl); } const char * GeoIP_country_code_by_name_v6(GeoIP * gi, const char *name) { GeoIPLookup gl; return GeoIP_country_code_by_name_v6_gl(gi, name, &gl); } const char * GeoIP_country_code_by_name(GeoIP * gi, const char *name) { GeoIPLookup gl; return GeoIP_country_code_by_name_gl(gi, name, &gl); } const char * GeoIP_country_code3_by_name_v6(GeoIP * gi, const char *name) { GeoIPLookup gl; return GeoIP_country_code3_by_name_v6_gl(gi, name, &gl); } const char * GeoIP_country_code3_by_name(GeoIP * gi, const char *name) { GeoIPLookup gl; return GeoIP_country_code3_by_name_gl(gi, name, &gl); } const char * GeoIP_country_name_by_name_v6(GeoIP * gi, const char *name) { GeoIPLookup gl; return GeoIP_country_name_by_name_v6_gl(gi, name, &gl); } const char * GeoIP_country_name_by_name(GeoIP * gi, const char *name) { GeoIPLookup gl; return GeoIP_country_name_by_name_gl(gi, name, &gl); } int GeoIP_id_by_name(GeoIP * gi, const char *name) { GeoIPLookup gl; return GeoIP_id_by_name_gl(gi, name, &gl); } int GeoIP_id_by_name_v6(GeoIP * gi, const char *name) { GeoIPLookup gl; return GeoIP_id_by_name_v6_gl(gi, name, &gl); } const char * GeoIP_country_code_by_addr_v6(GeoIP * gi, const char *addr) { GeoIPLookup gl; return GeoIP_country_code_by_addr_v6_gl(gi, addr, &gl); } const char * GeoIP_country_code_by_addr(GeoIP * gi, const char *addr) { GeoIPLookup gl; return GeoIP_country_code_by_addr_gl(gi, addr, &gl); } const char * GeoIP_country_code3_by_addr_v6(GeoIP * gi, const char *addr) { GeoIPLookup gl; return GeoIP_country_code3_by_addr_v6_gl(gi, addr, &gl); } const char * GeoIP_country_code3_by_addr(GeoIP * gi, const char *addr) { GeoIPLookup gl; return GeoIP_country_code3_by_addr_gl(gi, addr, &gl); } const char * GeoIP_country_name_by_addr_v6(GeoIP * gi, const char *addr) { GeoIPLookup gl; return GeoIP_country_name_by_addr_v6_gl(gi, addr, &gl); } const char * GeoIP_country_name_by_addr(GeoIP * gi, const char *addr) { GeoIPLookup gl; return GeoIP_country_name_by_addr_gl(gi, addr, &gl); } const char * GeoIP_country_name_by_ipnum(GeoIP * gi, unsigned long ipnum) { GeoIPLookup gl; return GeoIP_country_name_by_ipnum_gl(gi, ipnum, &gl); } const char * GeoIP_country_name_by_ipnum_v6(GeoIP * gi, geoipv6_t ipnum) { GeoIPLookup gl; return GeoIP_country_name_by_ipnum_v6_gl(gi, ipnum, &gl); } const char * GeoIP_country_code_by_ipnum_v6(GeoIP * gi, geoipv6_t ipnum) { GeoIPLookup gl; return GeoIP_country_code_by_ipnum_v6_gl(gi, ipnum, &gl); } const char * GeoIP_country_code_by_ipnum(GeoIP * gi, unsigned long ipnum) { GeoIPLookup gl; return GeoIP_country_code_by_ipnum_gl(gi, ipnum, &gl); } const char * GeoIP_country_code3_by_ipnum(GeoIP * gi, unsigned long ipnum) { GeoIPLookup gl; return GeoIP_country_code3_by_ipnum_gl(gi, ipnum, &gl); } const char * GeoIP_country_code3_by_ipnum_v6(GeoIP * gi, geoipv6_t ipnum) { GeoIPLookup gl; return GeoIP_country_code3_by_ipnum_v6_gl(gi, ipnum, &gl); } int GeoIP_country_id_by_addr_v6(GeoIP * gi, const char *addr) { GeoIPLookup gl; return GeoIP_id_by_addr_v6_gl(gi, addr, &gl); } int GeoIP_country_id_by_addr(GeoIP * gi, const char *addr) { GeoIPLookup gl; return GeoIP_id_by_addr_gl(gi, addr, &gl); } int GeoIP_country_id_by_name_v6(GeoIP * gi, const char *host) { GeoIPLookup gl; return GeoIP_id_by_name_v6_gl(gi, host, &gl); } int GeoIP_country_id_by_name(GeoIP * gi, const char *host) { GeoIPLookup gl; return GeoIP_id_by_name_gl(gi, host, &gl); } int GeoIP_id_by_addr_v6(GeoIP * gi, const char *addr) { GeoIPLookup gl; return GeoIP_id_by_addr_v6_gl(gi, addr, &gl); } int GeoIP_id_by_addr(GeoIP * gi, const char *addr) { GeoIPLookup gl; return GeoIP_id_by_addr_gl(gi, addr, &gl); } int GeoIP_id_by_ipnum_v6(GeoIP * gi, geoipv6_t ipnum) { GeoIPLookup gl; return GeoIP_id_by_ipnum_v6_gl(gi, ipnum, &gl); } int GeoIP_id_by_ipnum(GeoIP * gi, unsigned long ipnum) { GeoIPLookup gl; return GeoIP_id_by_ipnum_gl(gi, ipnum, &gl); } void GeoIP_assign_region_by_inetaddr(GeoIP * gi, unsigned long inetaddr, GeoIPRegion * region) { GeoIPLookup gl; GeoIP_assign_region_by_inetaddr_gl(gi, inetaddr, region, &gl); } void GeoIP_assign_region_by_inetaddr_v6(GeoIP * gi, geoipv6_t inetaddr, GeoIPRegion * region) { GeoIPLookup gl; GeoIP_assign_region_by_inetaddr_v6_gl(gi, inetaddr, region, &gl); } GeoIPRegion * GeoIP_region_by_addr(GeoIP * gi, const char *addr) { GeoIPLookup gl; return GeoIP_region_by_addr_gl(gi, addr, &gl); } GeoIPRegion * GeoIP_region_by_addr_v6(GeoIP * gi, const char *addr) { GeoIPLookup gl; return GeoIP_region_by_addr_v6_gl(gi, addr, &gl); } GeoIPRegion * GeoIP_region_by_name(GeoIP * gi, const char *name) { GeoIPLookup gl; return GeoIP_region_by_name_gl(gi, name, &gl); } GeoIPRegion * GeoIP_region_by_name_v6(GeoIP * gi, const char *name) { GeoIPLookup gl; return GeoIP_region_by_name_v6_gl(gi, name, &gl); } GeoIPRegion * GeoIP_region_by_ipnum(GeoIP * gi, unsigned long ipnum) { GeoIPLookup gl; return GeoIP_region_by_ipnum_gl(gi, ipnum, &gl); } GeoIPRegion * GeoIP_region_by_ipnum_v6(GeoIP * gi, geoipv6_t ipnum) { GeoIPLookup gl; return GeoIP_region_by_ipnum_v6_gl(gi, ipnum, &gl); } char ** GeoIP_range_by_ip(GeoIP * gi, const char *addr) { GeoIPLookup gl; return GeoIP_range_by_ip_gl(gi, addr, &gl); } char * GeoIP_name_by_ipnum(GeoIP * gi, unsigned long ipnum) { GeoIPLookup gl; return GeoIP_name_by_ipnum_gl(gi, ipnum, &gl); } char * GeoIP_name_by_ipnum_v6(GeoIP * gi, geoipv6_t ipnum) { GeoIPLookup gl; return GeoIP_name_by_ipnum_v6_gl(gi, ipnum, &gl); } char * GeoIP_name_by_addr(GeoIP * gi, const char *addr) { GeoIPLookup gl; return GeoIP_name_by_addr_gl(gi, addr, &gl); } char * GeoIP_name_by_addr_v6(GeoIP * gi, const char *addr) { GeoIPLookup gl; return GeoIP_name_by_addr_v6_gl(gi, addr, &gl); } char * GeoIP_name_by_name(GeoIP * gi, const char *name) { GeoIPLookup gl; return GeoIP_name_by_name_gl(gi, name, &gl); } char * GeoIP_name_by_name_v6(GeoIP * gi, const char *name) { GeoIPLookup gl; return GeoIP_name_by_name_v6_gl(gi, name, &gl); }
[ "zhouyu2410@gmail.com" ]
zhouyu2410@gmail.com
bf9e7bfe7409151ecd76df7a38451d06befb68db
afef6fbfdc966ef99b1a5fe670d7221bbf825639
/intersections/intersectionkdtreegeometrymedian.cpp
5f53418c1d5c4088f241e05e433468a2736ba88a
[]
no_license
poechsel/raytracer
3886a3b3f7cbb088aae78da9b8089eac5b661319
31c49f6b0688ae6cf01289602184dd255d92d449
refs/heads/master
2021-07-03T00:41:40.323621
2017-09-23T21:25:50
2017-09-23T21:25:50
104,599,919
1
0
null
null
null
null
UTF-8
C++
false
false
1,332
cpp
#include "intersectionkdtreegeometrymedian.h" IntersectionKdTreeGeometryMedian::IntersectionKdTreeGeometryMedian(Scene *scene, bool a): IntersectionKdTree(scene, a) { //ctor } SplitPlane IntersectionKdTreeGeometryMedian::heuristic(BoundingBox &bb, std::vector<uint> &T, uint depth) { //std::cout<<T.size()<<"\n"; SplitPlane plane; if (depth%3 == 0) { plane.axis = X; plane.pos = (bb.M.x - bb.m.x) * 0.5 + bb.m.x; } else if (depth%3 == 1) { plane.axis = Y; plane.pos = (bb.M.y - bb.m.y) * 0.5 + bb.m.y; } else { plane.axis = Z; plane.pos = (bb.M.z - bb.m.z) * 0.5 + bb.m.z; } std::vector<Real> temp; for (uint t: T) { Triangle &tri = _scene->triangles[t]; BoundingBox tri_bb (_scene, &tri); tri_bb.clip(bb); temp.push_back(tri_bb.getCenter()[plane.axis]); } std::nth_element(temp.begin(), temp.begin()+temp.size() / 2, temp.end()); if (temp.size()) plane.pos = temp[temp.size()/2]; plane.side = BOTH; return plane; } IntersectionKdTreeGeometryMedian::~IntersectionKdTreeGeometryMedian() { //dtor }
[ "pierre.oechsel@gmail.com" ]
pierre.oechsel@gmail.com
24ad28795c3e5c26021ecba8228850c23bf5321a
e8a7ceb8962d118a5dd816ac14b1e3c94e5c7f8b
/spepcpp/src/spep/ipc/Engine.cpp
bdd8c4dcfd10786c527c57557791e10007049dae
[ "Apache-2.0" ]
permissive
axilotl/esoeproject
dcfa73cb10b3977728fe2a76f24417837614a3b0
42348b232559a5013314863dc506948c2353f0e8
refs/heads/master
2020-12-25T00:09:23.529134
2012-02-13T05:13:04
2012-02-13T05:13:04
1,539,359
1
0
null
null
null
null
UTF-8
C++
false
false
1,306
cpp
/* Copyright 2006-2007, Queensland University of Technology * 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. * * Author: Shaun Mangelsdorf * Creation Date: 07/03/2007 * * Purpose: Implements the non-templated methods of spep::ipc::Engine. */ #include "spep/ipc/Engine.h" spep::ipc::MessageHeader spep::ipc::Engine::getRequestHeader() { MessageHeader requestHeader; getObject(requestHeader); return requestHeader; } void spep::ipc::Engine::sendErrorResponseHeader() { MessageHeader responseHeader( SPEPIPC_RESPONSE_ERROR, std::string() ); _archive.out() << responseHeader; } void spep::ipc::Engine::sendResponseHeader() { MessageHeader responseHeader( SPEPIPC_RESPONSE, std::string() ); _archive.out() << responseHeader; }
[ "s.mangelsdorf@gmail.com" ]
s.mangelsdorf@gmail.com
43d45e2b9e81492779ed297d6f0346fa8c48107f
c6c1b91615287a431581d3e71d87eda3aed5713a
/Demos/iOS/UnicodeDemo/Classes/UnicodeDemoController.h
8a483d5b3859aa7576aa897fc61e00151d1709d4
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
sloopdoom/ftgles-gles2
a813eaf57d98ef33c976c0c700444946d000f4b6
13aa7b45ecc890efc6703abcb0cbdd59ffb5cde3
refs/heads/master
2021-01-15T18:50:43.125598
2013-05-07T08:17:32
2013-05-07T08:17:32
9,907,253
0
1
MIT
2018-10-01T03:54:29
2013-05-07T08:18:24
C
UTF-8
C++
false
false
1,449
h
/* Copyright (c) 2010 David Petrie 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. */ #ifndef UNICODE_DEMO_CONTROLLER_H #define UNICODE_DEMO_CONTROLLER_H #include <OpenGLES/ES1/gl.h> #include <OpenGLES/ES1/glext.h> /* * FTGL Includes */ #include "FTGL/ftgles.h" class UnicodeDemoController { public: UnicodeDemoController(const char* path, float width, float height, float scale); ~UnicodeDemoController(); void Draw(); }; #endif
[ "yeetan@gmail.com" ]
yeetan@gmail.com
2c141e0a8dbd034e3a30fc5d5c44a85ff02c4cbe
3e5ae9b260b16fcc86bb0669c1bd4e56912b5433
/VCB600ENU1/MSDN_VCB/SAMPLES/VC98/MFC/GENERAL/SNAPVW/SNAPPS.H
01f7981508fc0a467886e459561a64b889340833
[]
no_license
briancpark/deitel-cpp
e8612c7011c9d9d748290419ae2708d2f3f11543
90cdae5661718e65ab945bcf45fe6adff30c1e10
refs/heads/main
2023-06-14T14:07:05.497253
2021-07-05T01:46:04
2021-07-05T01:46:04
382,984,213
0
0
null
null
null
null
UTF-8
C++
false
false
1,480
h
#if !defined(AFX_SNAPPS_H__E2FD70FC_605F_11D1_A346_00C04FD91807__INCLUDED_) #define AFX_SNAPPS_H__E2FD70FC_605F_11D1_A346_00C04FD91807__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // SnapPs.h : header file // ///////////////////////////////////////////////////////////////////////////// // CSnapPropertySheet class CSnapPropertySheet : public CPropertySheet { DECLARE_DYNAMIC(CSnapPropertySheet) // Construction public: CSnapPropertySheet() : CPropertySheet() { } CSnapPropertySheet(UINT nIDCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0); CSnapPropertySheet(LPCTSTR pszCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0); // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CSnapPropertySheet) public: virtual BOOL PreTranslateMessage(MSG* pMsg); //}}AFX_VIRTUAL // Implementation public: virtual ~CSnapPropertySheet(); // Generated message map functions protected: //{{AFX_MSG(CSnapPropertySheet) // NOTE - the ClassWizard will add and remove member functions here. //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_SNAPPS_H__E2FD70FC_605F_11D1_A346_00C04FD91807__INCLUDED_)
[ "briancpark@berkeley.edu" ]
briancpark@berkeley.edu
3ea8fdf0f1d8fdccfde60f5ced1edf7a5792a09d
95b4c39aa258a484e867027328efc9ff6010b1db
/util/Ext/typeid_cast.h
bc6034db180a44631b50bd0660c217778eda8af7
[]
no_license
wusihang/db
d9d1067d4e4a145a56682cffaab64371079833a4
2d17871abd6135fbf60cd3083e78a6f79e7584ea
refs/heads/master
2020-03-13T06:57:04.561319
2018-11-27T00:51:12
2018-11-27T00:51:12
131,015,240
0
1
null
2018-11-27T00:51:13
2018-04-25T14:01:22
C
UTF-8
C++
false
false
664
h
#pragma once #include <type_traits> #include <typeinfo> #include <string> #include<Poco/Exception.h> template <typename To, typename From> typename std::enable_if<std::is_reference<To>::value, To>::type typeid_cast(From & from) { if (typeid(from) == typeid(To)) return static_cast<To>(from); else throw Poco::Exception("Bad cast from type " + std::string(typeid(from).name()) + " to " + std::string(typeid(To).name())); } template <typename To, typename From> To typeid_cast(From * from) { if (typeid(*from) == typeid(typename std::remove_pointer<To>::type)) return static_cast<To>(from); else return nullptr; }
[ "wusihang9@139.com" ]
wusihang9@139.com
cdbfa32e9d1832828f4dd0abcd2c523571e46cfa
6336483e4cb8bff0f0cf2ecbb70a88c57d6f9c87
/SDXEngine/SDXRenderer.h
1e84814175683ebdc2777204282fe866dc90ec60
[]
no_license
hoisin/SDXEngine
8deef9f456bf41ac0c420c5a1498176abc44cb94
7d5cb792657a19ef4055f159a1d8d645e950db93
refs/heads/master
2022-08-10T19:21:16.553728
2022-08-01T20:43:51
2022-08-01T20:43:51
139,254,558
0
0
null
2022-07-30T14:46:04
2018-06-30T14:09:33
C++
UTF-8
C++
false
false
1,448
h
//-------------------------------------------------------------------------- // // Renderer class // //-------------------------------------------------------------------------- #pragma once #include <list> #include "SDXDirectX.h" #include "SDXDirect2D.h" #include "SDXCameraFP.h" #include "SDXRasterState.h" #include "SDXMesh.h" namespace SDXEngine { struct SDXDrawItem { XMFLOAT3 worldPos = XMFLOAT3(0.f, 0.f, 0.f); XMFLOAT3 rotation = XMFLOAT3(0.f, 0.f, 0.f); XMFLOAT3 scale = XMFLOAT3(1.f, 1.f, 1.f); SDXMesh* mesh = nullptr; }; class SDXRenderer { public: SDXRenderer(); ~SDXRenderer(); SDXErrorId Initialise(const SDXDirectXInfo& info); void BeginDraw(); void EndDraw(); void Render(SDXDrawItem* drawItem); void Render(const std::list<SDXDrawItem*>& drawList); void UpdateProjectionMatrix(const XMFLOAT4X4& proj); void UpdateViewMatrix(const XMFLOAT4X4& view); void RenderText(UINT x, UINT y, const std::string& text); // Tester methods SDXErrorId CreateViewAndPerspective(); void UpdateTest(); void RenderCube(); void EnableWireFrame(bool bEnable); SDXDirectX* GetDirectX(); private: SDXDirectX m_directX; SDXDirect2D m_direct2D; // Testing ID3D11Buffer* m_vertexBuffer; ID3D11Buffer* m_indexBuffer; int m_indexCount; ConstantBufferStruct m_worldViewProj; int m_testFrameCount; SDXRasterState m_fillState; SDXRasterState m_wireFrame; }; }
[ "mwctsang@gmail.com" ]
mwctsang@gmail.com
fbab7dfdc2b5e4a7ad4d47e9e08373704ee5705a
c237a84cbb8ce7742233249391ac57324bd50ee9
/Neo_Study/0828_API_03_BLOCKGAME/SceneManager.cpp
2d56d45cef34d8855ebcdf373b281078f8959731
[]
no_license
JongHyunP/PJH
f7e0b597594520a2dc82eed249a87da599c38a17
621bf2385197cd2ba445ae1b5dcb38489aa5d6ed
refs/heads/master
2020-07-07T06:48:47.162030
2019-10-24T00:06:07
2019-10-24T00:06:07
203,282,005
0
0
null
null
null
null
UHC
C++
false
false
626
cpp
#include "SceneManager.h" SceneManager::SceneManager() { } SceneManager::~SceneManager() { } void SceneManager::registerScene(const string & sceneName, Scene * scene) { sceneContainer.insert(pair<string,Scene*>(sceneName, scene)); } void SceneManager::reserveChangeScene(const string & sceneName) { map<string, Scene*>::iterator iter; iter = sceneContainer.find(sceneName); } void SceneManager::Update(int sceneUpdatenum) //입력 받으면 바꿔주고 { switch (sceneUpdatenum) { case 1: break; case 2: break; default: break; } } void SceneManager::Render(HDC hdc, float dt) // 그려준다. { }
[ "Administrator@DESKTOP-UPBBAIM" ]
Administrator@DESKTOP-UPBBAIM
f0f2cf8c0240b1b4e6f6c889b1434985304cfb63
67110b6ee81e0958ae7150687d78a279ddc9a133
/cl_dll/hud.cpp
08b76aeeeb3abb7a720e5d100f2942f724ae96eb
[]
no_license
ataceyhun/LeakNet-SDK
c383fb8fa555d33c5d3a9e9283590a3a28244745
aeedaf894a3f5e749e59e80c39600c5fd3e89779
refs/heads/master
2020-06-13T19:38:15.198904
2016-11-18T11:25:56
2016-11-18T11:25:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,731
cpp
/*** * * Copyright (c) 1999, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * Use, distribution, and modification of this source code and/or resulting * object code is restricted to non-commercial enhancements to products from * Valve LLC. All other use, distribution, or modification is prohibited * without written permission from Valve LLC. * ****/ // // hud.cpp // // implementation of CHud class // #include "cbase.h" #include "hud_macros.h" #include "history_resource.h" #include "parsemsg.h" #include "iinput.h" #include "clientmode.h" #include "in_buttons.h" #include <vgui_controls/Controls.h> #include <vgui/ISurface.h> #include <KeyValues.h> #include "itextmessage.h" #include "mempool.h" #include <KeyValues.h> #include "filesystem.h" #include <vgui_controls/AnimationController.h> // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" void __MsgFunc_ClearDecals(const char *pszName, int iSize, void *pbuf); static CClassMemoryPool< CHudTexture > g_HudTextureMemoryPool( 128 ); ConVar hud_autoreloadscript("hud_autoreloadscript", "0", FCVAR_ARCHIVE, "Automatically reloads the animation script each time one is ran"); #if defined( HL2_CLIENT_DLL ) ConVar hud_enableoldhud("hud_enableoldhud", "1", FCVAR_ARCHIVE, "Enables old HUD seen in early HL2 development screenshots"); // VXP #endif //----------------------------------------------------------------------------- // Purpose: Parses the weapon txt files to get the sprites needed. //----------------------------------------------------------------------------- void LoadHudTextures( CUtlDict< CHudTexture *, int >& list, char *psz ) { KeyValues *pTemp, *pTextureSection; KeyValues *pKeyValuesData = new KeyValues( "WeaponDatafile" ); if ( pKeyValuesData->LoadFromFile( filesystem, psz ) ) { pTextureSection = pKeyValuesData->FindKey( "TextureData" ); if ( pTextureSection ) { // Read the sprite data pTemp = pTextureSection->GetFirstSubKey(); while ( pTemp ) { CHudTexture *tex = new CHudTexture(); // Key Name is the sprite name strcpy( tex->szShortName, pTemp->GetName() ); strcpy( tex->szTextureFile, pTemp->GetString( "file" ) ); tex->rc.left = pTemp->GetInt( "x", 0 ); tex->rc.top = pTemp->GetInt( "y", 0 ); tex->rc.right = pTemp->GetInt( "width", 0 ) + tex->rc.left; tex->rc.bottom = pTemp->GetInt( "height", 0 ) + tex->rc.top; list.Insert( tex->szShortName, tex ); pTemp = pTemp->GetNextKey(); } } } // Failed for some reason. Delete the Key data and abort. pKeyValuesData->deleteThis(); } //----------------------------------------------------------------------------- // Purpose: // Input : * - // list - //----------------------------------------------------------------------------- void FreeHudTextureList( CUtlDict< CHudTexture *, int >& list ) { int c = list.Count(); for ( int i = 0; i < c; i++ ) { CHudTexture *tex = list[ i ]; delete tex; } list.RemoveAll(); } // Globally-used fonts vgui::HFont g_hFontTrebuchet24 = vgui::INVALID_FONT; vgui::HFont g_hFontTrebuchet40 = vgui::INVALID_FONT; //======================================================================================================================= // Hud Element Visibility handling //======================================================================================================================= typedef struct hudelement_hidden_s { char *sElementName; int iHiddenBits; // Bits in which this hud element is hidden } hudelement_hidden_t; hudelement_hidden_t sHudHiddenArray[] = { { "CHudHealth", HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD | HIDEHUD_NEEDSUIT }, { "CHudWeaponSelection", HIDEHUD_WEAPONS | HIDEHUD_NEEDSUIT | HIDEHUD_PLAYERDEAD }, { "CHudHistoryResource", HIDEHUD_MISCSTATUS }, { "CHudTrain", HIDEHUD_MISCSTATUS }, { "ScorePanel", 0 }, { "CVProfPanel", 0 }, { "CBudgetPanel", 0 }, { "CPDumpPanel", 0 }, { "CHudMOTD", 0 }, { "CHudMessage", 0 }, { "CHudMenu", HIDEHUD_MISCSTATUS }, { "CHudChat", HIDEHUD_CHAT }, { "CHudDeathNotice", HIDEHUD_MISCSTATUS }, { "CHudCloseCaption", 0 }, // Never hidden if needed { "CHudAnimationInfo", 0 }, // For debugging, never hidden if visible { "CHudDamageIndicator", HIDEHUD_HEALTH }, // HL2 hud elements { "CHudBattery", HIDEHUD_HEALTH | HIDEHUD_NEEDSUIT }, { "CHudSuitPower", HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD | HIDEHUD_NEEDSUIT }, { "CHudFlashlight", HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD | HIDEHUD_NEEDSUIT }, { "CHudGeiger", HIDEHUD_HEALTH }, { "CHudAmmo", HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD | HIDEHUD_NEEDSUIT }, { "CHudSecondaryAmmo", HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD | HIDEHUD_NEEDSUIT }, { "CHudZoom", HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD | HIDEHUD_NEEDSUIT }, { "CHUDQuickInfo", 0 }, // TF2 hud elements { "CHudResources", HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD }, { "CHudResourcesPickup", HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD }, { "CTargetID", HIDEHUD_MISCSTATUS }, { "CHudOrderList", HIDEHUD_MISCSTATUS | HIDEHUD_PLAYERDEAD }, { "CHudObjectStatuses", HIDEHUD_MISCSTATUS | HIDEHUD_PLAYERDEAD }, { "CHudEMP", HIDEHUD_HEALTH }, { "CHudMortar", HIDEHUD_PLAYERDEAD }, { "CHudWeaponFlashHelper", HIDEHUD_MISCSTATUS | HIDEHUD_PLAYERDEAD }, { "CVehicleRoleHudElement", HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD }, { "CHudTimer", HIDEHUD_MISCSTATUS }, { "CHudVehicleHealth", HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD }, { "CMinimapPanel", 0 }, { "CHudAmmoPrimary", HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD }, { "CHudAmmoPrimaryClip", HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD }, { "CHudAmmoSecondary", HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD }, { "CHudVehicle", HIDEHUD_PLAYERDEAD }, { "CHudCrosshair", HIDEHUD_PLAYERDEAD }, { "CHudWeapon", HIDEHUD_PLAYERDEAD | HIDEHUD_WEAPONS }, { "CHudProgressBar", HIDEHUD_PLAYERDEAD | HIDEHUD_WEAPONS }, // Counter-Strike hud elements. { "CHudRoundTimer", 0 }, { "CHudAccount", HIDEHUD_PLAYERDEAD }, { "CHudShoppingCart", HIDEHUD_PLAYERDEAD }, { "CHudC4", HIDEHUD_PLAYERDEAD }, { "CHudArmor", HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD }, // Old HL2 HUD elements { "CHudHealthOld", HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD | HIDEHUD_NEEDSUIT }, { "CHudBatteryOld", HIDEHUD_HEALTH | HIDEHUD_NEEDSUIT }, { "CHudAmmoOld", HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD | HIDEHUD_NEEDSUIT }, { "CHudSecondaryAmmoOld", HIDEHUD_HEALTH | HIDEHUD_PLAYERDEAD | HIDEHUD_NEEDSUIT }, { NULL, 0 }, }; ConVar hidehud( "hidehud", "0", 0 ); //======================================================================================================================= // CHudElement // All hud elements are derived from this class. //======================================================================================================================= //----------------------------------------------------------------------------- // Purpose: Registers the hud element in a global list, in CHud //----------------------------------------------------------------------------- CHudElement::CHudElement( const char *pElementName ) { m_bActive = false; m_iHiddenBits = 0; m_pElementName = pElementName; SetNeedsRemove( false ); } //----------------------------------------------------------------------------- // Purpose: Remove this hud element from the global list in CHUD //----------------------------------------------------------------------------- CHudElement::~CHudElement() { if ( m_bNeedsRemove ) { gHUD.RemoveHudElement( this ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHudElement::SetActive( bool bActive ) { m_bActive = bActive; } //----------------------------------------------------------------------------- // Purpose: // Input : needsremove - //----------------------------------------------------------------------------- void CHudElement::SetNeedsRemove( bool needsremove ) { m_bNeedsRemove = needsremove; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHudElement::SetHiddenBits( int iBits ) { m_iHiddenBits = iBits; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CHudElement::ShouldDraw( void ) { return !gHUD.IsHidden( m_iHiddenBits ); } /*============================================ CHud class definition ============================================*/ CHud gHUD; // global HUD object DECLARE_MESSAGE(gHUD, ResetHUD); DECLARE_MESSAGE(gHUD, InitHUD); DECLARE_MESSAGE(gHUD, GameMode); DECLARE_MESSAGE(gHUD, TeamChange); CHud::CHud() { } //----------------------------------------------------------------------------- // Purpose: This is called every time the DLL is loaded //----------------------------------------------------------------------------- void CHud::Init( void ) { HOOK_MESSAGE( ResetHUD ); HOOK_MESSAGE( GameMode ); HOOK_MESSAGE( InitHUD ); HOOK_MESSAGE( TeamChange ); HOOK_MESSAGE( ClearDecals ); InitFonts(); // Create all the Hud elements and then tell them to initialise CHudElementHelper::CreateAllElements(); for ( int i = 0; i < m_HudList.Size(); i++ ) { m_HudList[i]->Init(); } MsgFunc_ResetHUD( 0, 0, NULL ); m_bHudTexturesLoaded = false; KeyValues *kv = new KeyValues( "layout" ); if ( kv ) { if ( kv->LoadFromFile( filesystem, "scripts/HudLayout.res" ) ) { for ( int i = 0; i < m_HudList.Size(); i++ ) { vgui::Panel *pPanel = dynamic_cast<vgui::Panel*>(m_HudList[i]); if ( !pPanel ) { Msg( "Non-vgui hud element %s\n", m_HudList[i]->GetName() ); continue; } KeyValues *key = kv->FindKey( pPanel->GetName(), false ); if ( !key ) { Msg( "Hud element '%s' doesn't have an entry '%s' in scripts/HudLayout.res\n", m_HudList[i]->GetName(), pPanel->GetName() ); } if ( !pPanel->GetParent() ) { Msg( "Hud element '%s'/'%s' doesn't have a parent\n", m_HudList[i]->GetName(), pPanel->GetName() ); } } } kv->deleteThis(); } if ( m_bHudTexturesLoaded ) return; m_bHudTexturesLoaded = true; CUtlDict< CHudTexture *, int > textureList; // check to see if we have sprites for this res; if not, step down LoadHudTextures( textureList, VarArgs("scripts/hud_textures.txt" ) ); LoadHudTextures( textureList, VarArgs("scripts/mod_textures.txt" ) ); int c = textureList.Count(); for ( int index = 0; index < c; index++ ) { CHudTexture* tex = textureList[ index ]; AddSearchableHudIconToList( *tex ); } FreeHudTextureList( textureList ); } //----------------------------------------------------------------------------- // Purpose: Init Hud global colors // Input : *scheme - //----------------------------------------------------------------------------- void CHud::InitColors( vgui::IScheme *scheme ) { m_clrNormal = scheme->GetColor( "Normal", Color( 255, 208, 64 ,255 ) ); m_clrCaution = scheme->GetColor( "Caution", Color( 255, 48, 0, 255 ) ); m_clrYellowish = scheme->GetColor( "Yellowish", Color( 255, 160, 0, 255 ) ); } //----------------------------------------------------------------------------- // Initializes fonts //----------------------------------------------------------------------------- void CHud::InitFonts() { g_hFontTrebuchet24 = vgui::surface()->CreateFont(); vgui::surface()->AddGlyphSetToFont( g_hFontTrebuchet24, "Trebuchet MS", 24, 900, 0, 0, 0, 0x0, 0x7F ); g_hFontTrebuchet40 = vgui::surface()->CreateFont(); vgui::surface()->AddGlyphSetToFont( g_hFontTrebuchet40, "Trebuchet MS", 40, 900, 0, 0, 0, 0x0, 0x7F ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHud::Shutdown( void ) { // Delete all the Hud elements int iMax = m_HudList.Size(); for ( int i = iMax-1; i >= 0; i-- ) { delete m_HudList[i]; } m_HudList.Purge(); m_bHudTexturesLoaded = false; } //----------------------------------------------------------------------------- // Purpose: LevelInit's called whenever a new level's starting //----------------------------------------------------------------------------- void CHud::LevelInit( void ) { // Tell all the registered hud elements to LevelInit for ( int i = 0; i < m_HudList.Size(); i++ ) { m_HudList[i]->SetGameRestored( false ); m_HudList[i]->LevelInit(); } } //----------------------------------------------------------------------------- // Purpose: LevelShutdown's called whenever a level's finishing //----------------------------------------------------------------------------- void CHud::LevelShutdown( void ) { // Tell all the registered hud elements to LevelInit for ( int i = 0; i < m_HudList.Size(); i++ ) { m_HudList[i]->LevelShutdown(); m_HudList[i]->SetGameRestored( false ); } } //----------------------------------------------------------------------------- // Purpose: cleans up memory allocated for m_rg* arrays //----------------------------------------------------------------------------- CHud::~CHud() { int c = m_Icons.Count(); for ( int i = c - 1; i >= 0; i-- ) { CHudTexture *tex = m_Icons[ i ]; g_HudTextureMemoryPool.Free( tex ); } m_Icons.Purge(); } void CHudTexture::DrawSelf( int x, int y, Color& clr ) const { DrawSelf( x, y, Width(), Height(), clr ); } void CHudTexture::DrawSelf( int x, int y, int w, int h, Color& clr ) const { if ( textureId == -1 ) return; vgui::surface()->DrawSetTexture( textureId ); vgui::surface()->DrawSetColor( clr ); vgui::surface()->DrawTexturedSubRect( x, y, x + w, y + h, texCoords[ 0 ], texCoords[ 1 ], texCoords[ 2 ], texCoords[ 3 ] ); } void CHudTexture::DrawSelfCropped( int x, int y, int cropx, int cropy, int cropw, int croph, Color& clr ) const { if ( textureId == -1 ) return; float fw = (float)Width(); float fh = (float)Height(); float twidth = texCoords[ 2 ] - texCoords[ 0 ]; float theight = texCoords[ 3 ] - texCoords[ 1 ]; // Interpolate coords float tCoords[ 4 ]; tCoords[ 0 ] = texCoords[ 0 ] + ( (float)cropx / fw ) * twidth; tCoords[ 1 ] = texCoords[ 1 ] + ( (float)cropy / fh ) * theight; tCoords[ 2 ] = texCoords[ 0 ] + ( (float)(cropx + cropw ) / fw ) * twidth; tCoords[ 3 ] = texCoords[ 1 ] + ( (float)(cropy + croph ) / fh ) * theight; vgui::surface()->DrawSetTexture( textureId ); vgui::surface()->DrawSetColor( clr ); vgui::surface()->DrawTexturedSubRect( x, y, x + cropw, y + croph, tCoords[ 0 ], tCoords[ 1 ], tCoords[ 2 ], tCoords[ 3 ] ); } //----------------------------------------------------------------------------- // Purpose: // Input : *t - //----------------------------------------------------------------------------- void CHud::SetupNewHudTexture( CHudTexture *t ) { // Set up texture id and texture coordinates t->textureId = vgui::surface()->CreateNewTextureID(); vgui::surface()->DrawSetTextureFile( t->textureId, t->szTextureFile, false, false ); int wide, tall; vgui::surface()->DrawGetTextureSize( t->textureId, wide, tall ); t->texCoords[ 0 ] = (float)(t->rc.left + 0.5f) / (float)wide; t->texCoords[ 1 ] = (float)(t->rc.top + 0.5f) / (float)tall; t->texCoords[ 2 ] = (float)(t->rc.right - 0.5f) / (float)wide; t->texCoords[ 3 ] = (float)(t->rc.bottom - 0.5f) / (float)tall; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CHudTexture *CHud::AddUnsearchableHudIconToList( CHudTexture& texture ) { // These names are composed based on the texture file name char composedName[ 512 ]; Q_snprintf( composedName, sizeof( composedName ), "%s_%i_%i_%i_%i", texture.szTextureFile, texture.rc.left, texture.rc.top, texture.rc.right, texture.rc.bottom ); CHudTexture *icon = GetIcon( composedName ); if ( icon ) { return icon; } CHudTexture *newTexture = ( CHudTexture * )g_HudTextureMemoryPool.Alloc(); *newTexture = texture; SetupNewHudTexture( newTexture ); int idx = m_Icons.Insert( composedName, newTexture ); return m_Icons[ idx ]; } //----------------------------------------------------------------------------- // Purpose: // Input : texture - // Output : CHudTexture //----------------------------------------------------------------------------- CHudTexture *CHud::AddSearchableHudIconToList( CHudTexture& texture ) { CHudTexture *icon = GetIcon( texture.szShortName ); if ( icon ) { return icon; } CHudTexture *newTexture = ( CHudTexture * )g_HudTextureMemoryPool.Alloc(); *newTexture = texture; SetupNewHudTexture( newTexture ); int idx = m_Icons.Insert( texture.szShortName, newTexture ); return m_Icons[ idx ]; } //----------------------------------------------------------------------------- // Purpose: returns a pointer to an icon in the list // Input : *szIcon - // Output : CHudTexture //----------------------------------------------------------------------------- CHudTexture *CHud::GetIcon( const char *szIcon ) { int i = m_Icons.Find( szIcon ); if ( i == m_Icons.InvalidIndex() ) return NULL; return m_Icons[ i ]; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHud::RefreshHudTextures() { if ( !m_bHudTexturesLoaded ) { Assert( 0 ); return; } CUtlDict< CHudTexture *, int > textureList; // check to see if we have sprites for this res; if not, step down LoadHudTextures( textureList, VarArgs("scripts/hud_textures.txt" ) ); LoadHudTextures( textureList, VarArgs("scripts/mod_textures.txt" ) ); int c = textureList.Count(); for ( int index = 0; index < c; index++ ) { CHudTexture *tex = textureList[ index ]; Assert( tex ); CHudTexture *icon = GetIcon( tex->szShortName ); if ( !icon ) continue; // Update file strcpy( icon->szTextureFile, tex->szTextureFile ); // Update subrect icon->rc = tex->rc; // Keep existing texture id, but now update texture file and texture coordinates vgui::surface()->DrawSetTextureFile( icon->textureId, icon->szTextureFile, false, false ); // Get new texture dimensions in case it changed int wide, tall; vgui::surface()->DrawGetTextureSize( icon->textureId, wide, tall ); // Assign coords icon->texCoords[ 0 ] = (float)(icon->rc.left + 0.5f) / (float)wide; icon->texCoords[ 1 ] = (float)(icon->rc.top + 0.5f) / (float)tall; icon->texCoords[ 2 ] = (float)(icon->rc.right - 0.5f) / (float)wide; icon->texCoords[ 3 ] = (float)(icon->rc.bottom - 0.5f) / (float)tall; } FreeHudTextureList( textureList ); } void CHud::OnRestore() { for ( int i = 0; i < m_HudList.Size(); i++ ) { m_HudList[i]->SetGameRestored( true ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CHud::VidInit( void ) { for ( int i = 0; i < m_HudList.Size(); i++ ) { m_HudList[i]->VidInit(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CHudElement *CHud::FindElement( const char *pName ) { for ( int i = 0; i < m_HudList.Size(); i++ ) { if ( stricmp( m_HudList[i]->GetName(), pName ) == 0 ) return m_HudList[i]; } DevWarning(1, "Could not find Hud Element: %s\n", pName ); assert(0); return NULL; } //----------------------------------------------------------------------------- // Purpose: Adds a member to the HUD //----------------------------------------------------------------------------- void CHud::AddHudElement( CHudElement *pHudElement ) { // Add the hud element to the end of the array m_HudList.AddToTail( pHudElement ); pHudElement->SetNeedsRemove( true ); // Set the hud element's visibility int i = 0; while ( sHudHiddenArray[i].sElementName ) { if ( !strcmp( sHudHiddenArray[i].sElementName, pHudElement->GetName() ) ) { pHudElement->SetHiddenBits( sHudHiddenArray[i].iHiddenBits ); return; } i++; } // Couldn't find the hud element's entry in the hidden array // Add an entry for your new hud element to the sHudHiddenArray array at the top of this file. Assert( 0 ); } //----------------------------------------------------------------------------- // Purpose: Remove an element from the HUD //----------------------------------------------------------------------------- void CHud::RemoveHudElement( CHudElement *pHudElement ) { m_HudList.FindAndRemove( pHudElement ); } //----------------------------------------------------------------------------- // Purpose: Returns current mouse sensitivity setting // Output : float - the return value //----------------------------------------------------------------------------- float CHud::GetSensitivity( void ) { return m_flMouseSensitivity; } //----------------------------------------------------------------------------- // Purpose: Return true if the passed in sections of the HUD shouldn't be drawn //----------------------------------------------------------------------------- bool CHud::IsHidden( int iHudFlags ) { // Not in game? if ( !engine->IsInGame() ) return true; // No local player yet? C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer(); if ( !pPlayer ) return true; // Get current hidden flags int iHideHud = pPlayer->m_Local.m_iHideHUD; if ( hidehud.GetInt() ) { iHideHud = hidehud.GetInt(); } // Everything hidden? if ( iHideHud & HIDEHUD_ALL ) return true; // Local player dead? if ( ( iHudFlags & HIDEHUD_PLAYERDEAD ) && ( pPlayer->GetHealth() <= 0 ) ) return true; // Need the HEV suit ( HL2 ) if ( ( iHudFlags & HIDEHUD_NEEDSUIT ) && ( !pPlayer->IsSuitEquipped() ) ) return true; return ( ( iHudFlags & iHideHud ) != 0); } //----------------------------------------------------------------------------- // Purpose: Allows HUD to modify input data //----------------------------------------------------------------------------- void CHud::ProcessInput( bool bActive ) { if ( bActive ) { m_iKeyBits = input->GetButtonBits( 0 ); // Weaponbits need to be sent down as a UserMsg now. gHUD.Think(); if ( !C_BasePlayer::GetLocalPlayer() ) { extern ConVar default_fov; engine->SetFieldOfView( default_fov.GetFloat() ); } } } //----------------------------------------------------------------------------- // Purpose: Allows HUD to Think and modify input data // Input : *cdata - // time - // Output : int - 1 if there were changes, 0 otherwise //----------------------------------------------------------------------------- void CHud::UpdateHud( bool bActive ) { // clear the weapon bits. gHUD.m_iKeyBits &= (~(IN_WEAPON1|IN_WEAPON2)); g_pClientMode->Update(); } //----------------------------------------------------------------------------- // Purpose: Force a Hud UI anim to play //----------------------------------------------------------------------------- void TestHudAnim_f( void ) { if (engine->Cmd_Argc() != 2) { Msg("Usage:\n testhudanim <anim name>\n"); return; } g_pClientMode->GetViewportAnimationController()->StartAnimationSequence( engine->Cmd_Argv(1) ); } static ConCommand testhudanim( "testhudanim", TestHudAnim_f, "Test a hud element animation.\n\tArguments: <anim name>\n", FCVAR_CHEAT );
[ "uavxp29@gmail.com" ]
uavxp29@gmail.com
6877ce8b88cee81dc5d4c0c4e92b3df63c062472
170dd8b4d93da1f3431054a97cad2e7fabfffd09
/libredex/ControlFlow.cpp
ece4f112f9069d8218cafafc6e396a1d2b7e2964
[ "MIT" ]
permissive
urantialife/redex
37959427c167df8d92622e3ad67c4ba8ae4e32d5
7c970695c7bb1ca3720c6843de7abcb0175faa8f
refs/heads/master
2020-06-01T14:18:23.771227
2019-06-07T00:09:34
2019-06-07T00:22:25
190,811,580
1
0
null
2019-06-07T21:36:30
2019-06-07T21:36:29
null
UTF-8
C++
false
false
78,112
cpp
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "ControlFlow.h" #include <boost/dynamic_bitset.hpp> #include <boost/numeric/conversion/cast.hpp> #include <iterator> #include <stack> #include <utility> #include "DexUtil.h" #include "Transform.h" #include "WeakTopologicalOrdering.h" namespace { // return true if `it` should be the last instruction of this block bool end_of_block(const IRList* ir, IRList::iterator it, bool in_try) { auto next = std::next(it); if (next == ir->end()) { return true; } // End the block before the first target in a contiguous sequence of targets. if (next->type == MFLOW_TARGET && it->type != MFLOW_TARGET) { return true; } // End the block before the first catch marker in a contiguous sequence of // catch markers. if (next->type == MFLOW_CATCH && it->type != MFLOW_CATCH) { return true; } // End the block before a TRY_START // and after a TRY_END if ((next->type == MFLOW_TRY && next->tentry->type == TRY_START) || (it->type == MFLOW_TRY && it->tentry->type == TRY_END)) { return true; } if (in_try && it->type == MFLOW_OPCODE && opcode::may_throw(it->insn->opcode())) { return true; } if (it->type != MFLOW_OPCODE) { return false; } if (is_branch(it->insn->opcode()) || is_return(it->insn->opcode()) || it->insn->opcode() == OPCODE_THROW) { return true; } return false; } bool ends_with_may_throw(cfg::Block* p) { for (auto last = p->rbegin(); last != p->rend(); ++last) { if (last->type != MFLOW_OPCODE) { continue; } return opcode::can_throw(last->insn->opcode()); } return false; } bool cannot_throw(cfg::Block* b) { for (const auto& mie : InstructionIterable(b)) { auto op = mie.insn->opcode(); if (opcode::can_throw(op)) { return false; } } return true; } /* * Return true if the block does not contain any instruction. */ bool is_effectively_empty(cfg::Block* b) { return b->get_first_insn() == b->end(); } /* * Return an iterator to the first instruction (except move-result* and goto) if * it occurs before the first position. Otherwise return end. */ IRList::iterator insn_before_position(cfg::Block* b) { for (auto it = b->begin(); it != b->end(); ++it) { if (it->type == MFLOW_OPCODE) { auto op = it->insn->opcode(); if (!is_move_result(op) && !opcode::is_move_result_pseudo(op) && !is_goto(op)) { return it; } } else if (it->type == MFLOW_POSITION) { return b->end(); } } return b->end(); } /* * Given an output ordering, Find adjacent positions that are exact duplicates * and delete the extras. Make sure not to delete any positions that are * referenced by a parent pointer. */ void remove_duplicate_positions(IRList* ir) { std::unordered_set<DexPosition*> keep; for (auto& mie : *ir) { if (mie.type == MFLOW_POSITION && mie.pos->parent != nullptr) { keep.insert(mie.pos->parent); } } DexPosition* prev = nullptr; for (auto it = ir->begin(); it != ir->end();) { if (it->type == MFLOW_POSITION) { DexPosition* curr = it->pos.get(); if (prev != nullptr && *curr == *prev && keep.count(curr) == 0) { it = ir->erase_and_dispose(it); continue; } else { prev = curr; } } ++it; } } } // namespace namespace cfg { IRList::iterator Block::begin() { if (m_parent->editable()) { return m_entries.begin(); } else { return m_begin; } } IRList::iterator Block::end() { if (m_parent->editable()) { return m_entries.end(); } else { return m_end; } } IRList::const_iterator Block::begin() const { if (m_parent->editable()) { return m_entries.begin(); } else { return m_begin; } } IRList::const_iterator Block::end() const { if (m_parent->editable()) { return m_entries.end(); } else { return m_end; } } bool Block::is_catch() const { return m_parent->get_pred_edge_of_type(this, EDGE_THROW) != nullptr; } bool Block::same_try(const Block* other) const { always_assert(other->m_parent == this->m_parent); return m_parent->blocks_are_in_same_try(this, other); } void Block::remove_insn(const InstructionIterator& it) { always_assert(m_parent->editable()); m_parent->remove_insn(it); } void Block::remove_insn(const ir_list::InstructionIterator& it) { always_assert(m_parent->editable()); remove_insn(to_cfg_instruction_iterator(it)); } void Block::remove_insn(const IRList::iterator& it) { always_assert(m_parent->editable()); remove_insn(to_cfg_instruction_iterator(it)); } opcode::Branchingness Block::branchingness() { // TODO (cnli): put back 'always_assert(m_parent->editable());' // once ModelMethodMerger::sink_common_ctor_to_return_block update // to editable CFG. const auto& last = get_last_insn(); if (succs().empty() || (succs().size() == 1 && m_parent->get_succ_edge_of_type(this, EDGE_GHOST) != nullptr)) { if (last != end()) { auto op = last->insn->opcode(); if (is_return(op)) { return opcode::BRANCH_RETURN; } else if (op == OPCODE_THROW) { return opcode::BRANCH_THROW; } } return opcode::BRANCH_NONE; } if (m_parent->get_succ_edge_of_type(this, EDGE_THROW) != nullptr) { return opcode::BRANCH_THROW; } if (m_parent->get_succ_edge_of_type(this, EDGE_BRANCH) != nullptr) { always_assert(last != end()); auto br = opcode::branchingness(last->insn->opcode()); always_assert(br == opcode::BRANCH_IF || br == opcode::BRANCH_SWITCH); return br; } if (m_parent->get_succ_edge_of_type(this, EDGE_GOTO) != nullptr) { return opcode::BRANCH_GOTO; } return opcode::BRANCH_NONE; } uint32_t Block::num_opcodes() const { always_assert(m_parent->editable()); return m_entries.count_opcodes(); } uint32_t Block::sum_opcode_sizes() const { always_assert(m_parent->editable()); return m_entries.sum_opcode_sizes(); } // shallowly copy pointers (edges and parent cfg) // but deeply copy MethodItemEntries Block::Block(const Block& b, MethodItemEntryCloner* cloner) : m_id(b.m_id), m_preds(b.m_preds), m_succs(b.m_succs), m_parent(b.m_parent) { // only for editable, don't worry about m_begin and m_end always_assert(m_parent->editable()); for (const auto& mie : b.m_entries) { m_entries.push_back(*cloner->clone(&mie)); } } bool Block::has_pred(Block* b, EdgeType t) const { const auto& edges = preds(); return std::find_if(edges.begin(), edges.end(), [b, t](const Edge* edge) { return edge->src() == b && (t == EDGE_TYPE_SIZE || edge->type() == t); }) != edges.end(); } bool Block::has_succ(Block* b, EdgeType t) const { const auto& edges = succs(); return std::find_if(edges.begin(), edges.end(), [b, t](const Edge* edge) { return edge->target() == b && (t == EDGE_TYPE_SIZE || edge->type() == t); }) != edges.end(); } IRList::iterator Block::get_conditional_branch() { for (auto it = rbegin(); it != rend(); ++it) { if (it->type == MFLOW_OPCODE) { auto op = it->insn->opcode(); if (is_conditional_branch(op) || is_switch(op)) { return std::prev(it.base()); } } } return end(); } IRList::iterator Block::get_last_insn() { for (auto it = rbegin(); it != rend(); ++it) { if (it->type == MFLOW_OPCODE) { // Reverse iterators have a member base() which returns a corresponding // forward iterator. Beware that this isn't an iterator that refers to the // same object - it actually refers to the next object in the sequence. // This is so that rbegin() corresponds with end() and rend() corresponds // with begin(). Copied from https://stackoverflow.com/a/2037917 return std::prev(it.base()); } } return end(); } IRList::iterator Block::get_first_insn() { for (auto it = begin(); it != end(); ++it) { if (it->type == MFLOW_OPCODE) { return it; } } return end(); } bool Block::starts_with_move_result() { auto first_it = get_first_insn(); if (first_it != end()) { auto first_op = first_it->insn->opcode(); if (is_move_result(first_op) || opcode::is_move_result_pseudo(first_op)) { return true; } } return false; } Block* Block::goes_to() const { const Edge* e = m_parent->get_succ_edge_of_type(this, EDGE_GOTO); if (e != nullptr) { return e->target(); } return nullptr; } Block* Block::goes_to_only_edge() const { const auto& s = succs(); if (s.size() == 1) { const auto& e = s[0]; if (e->type() == EDGE_GOTO) { return e->target(); } } return nullptr; } std::vector<Edge*> Block::get_outgoing_throws_in_order() const { std::vector<Edge*> result = m_parent->get_succ_edges_of_type(this, EDGE_THROW); std::sort(result.begin(), result.end(), [](const Edge* e1, const Edge* e2) { return e1->m_throw_info->index < e2->m_throw_info->index; }); return result; } // We remove the first matching target because multiple switch cases can point // to the same block. We use this function to move information from the target // entries to the CFG edges. The two edges are identical, save the case key, so // it doesn't matter which target is taken. We arbitrarily choose to process the // targets in forward order. boost::optional<Edge::CaseKey> Block::remove_first_matching_target( MethodItemEntry* branch) { for (auto it = m_entries.begin(); it != m_entries.end(); ++it) { auto& mie = *it; if (mie.type == MFLOW_TARGET && mie.target->src == branch) { boost::optional<Edge::CaseKey> result; if (mie.target->type == BRANCH_MULTI) { always_assert_log(is_switch(branch->insn->opcode()), "block %d in %s\n", id(), SHOW(*m_parent)); result = mie.target->case_key; } m_entries.erase_and_dispose(it); return result; } } always_assert_log(false, "block %d has no targets matching %s:\n%s", id(), SHOW(branch->insn), SHOW(&m_entries)); not_reached(); } // These assume that the iterator is inside this block cfg::InstructionIterator Block::to_cfg_instruction_iterator( const ir_list::InstructionIterator& list_it) { if (ControlFlowGraph::DEBUG && list_it.unwrap() != end()) { bool inside = false; auto needle = list_it.unwrap(); for (auto it = begin(); it != end(); ++it) { if (it == needle) { inside = true; } } always_assert(inside); } return cfg::InstructionIterator(*m_parent, this, list_it); } cfg::InstructionIterator Block::to_cfg_instruction_iterator( const IRList::iterator& list_it) { always_assert(list_it == this->end() || list_it->type == MFLOW_OPCODE); return to_cfg_instruction_iterator( ir_list::InstructionIterator(list_it, this->end())); } cfg::InstructionIterator Block::to_cfg_instruction_iterator( MethodItemEntry& mie) { always_assert(m_parent->editable()); return to_cfg_instruction_iterator(m_entries.iterator_to(mie)); } // Forward the insertion methods to the parent CFG. bool Block::insert_before(const InstructionIterator& position, const std::vector<IRInstruction*>& insns) { always_assert(position.block() == this); return m_parent->insert_before(position, insns); } bool Block::insert_before(const InstructionIterator& position, IRInstruction* insn) { always_assert(position.block() == this); return m_parent->insert_before(position, insn); } bool Block::insert_after(const InstructionIterator& position, const std::vector<IRInstruction*>& insns) { always_assert(position.block() == this); return m_parent->insert_after(position, insns); } bool Block::insert_after(const InstructionIterator& position, IRInstruction* insn) { always_assert(position.block() == this); return m_parent->insert_after(position, insn); } bool Block::push_front(const std::vector<IRInstruction*>& insns) { return m_parent->push_front(this, insns); } bool Block::push_front(IRInstruction* insn) { return m_parent->push_front(this, insn); } bool Block::push_back(const std::vector<IRInstruction*>& insns) { return m_parent->push_back(this, insns); } bool Block::push_back(IRInstruction* insn) { return m_parent->push_back(this, insn); } std::ostream& operator<<(std::ostream& os, const Edge& e) { switch (e.type()) { case EDGE_GOTO: { os << "goto"; break; } case EDGE_BRANCH: { os << "branch"; const auto& key = e.case_key(); if (key) { os << " " << *key; } break; } case EDGE_THROW: { os << "throw"; break; } default: { break; } } return os; } ControlFlowGraph::ControlFlowGraph(IRList* ir, uint16_t registers_size, bool editable) : m_registers_size(registers_size), m_editable(editable) { always_assert_log(ir->size() > 0, "IRList contains no instructions"); BranchToTargets branch_to_targets; TryEnds try_ends; TryCatches try_catches; find_block_boundaries(ir, branch_to_targets, try_ends, try_catches); connect_blocks(branch_to_targets); add_catch_edges(try_ends, try_catches); if (m_editable) { remove_try_catch_markers(); // Often, the `registers_size` parameter passed into this constructor is // incorrect. We recompute here to safeguard against this. // TODO: fix the optimizations that don't track registers size correctly. recompute_registers_size(); TRACE(CFG, 5, "before simplify:\n%s", SHOW(*this)); simplify(); TRACE(CFG, 5, "after simplify:\n%s", SHOW(*this)); } else { remove_unreachable_succ_edges(); } TRACE(CFG, 5, "editable %d, %s", m_editable, SHOW(*this)); } void ControlFlowGraph::find_block_boundaries(IRList* ir, BranchToTargets& branch_to_targets, TryEnds& try_ends, TryCatches& try_catches) { // create the entry block auto* block = create_block(); IRList::iterator block_begin; if (m_editable) { block_begin = ir->begin(); } else { block->m_begin = ir->begin(); } set_entry_block(block); bool in_try = false; IRList::iterator next; DexPosition* current_position = nullptr; DexPosition* last_pos_before_this_block = nullptr; for (auto it = ir->begin(); it != ir->end(); it = next) { next = std::next(it); if (it->type == MFLOW_TRY) { if (it->tentry->type == TRY_START) { // Assumption: TRY_STARTs are only at the beginning of blocks always_assert(!m_editable || it == block_begin); always_assert(m_editable || it == block->m_begin); in_try = true; } else if (it->tentry->type == TRY_END) { try_ends.emplace_back(it->tentry, block); in_try = false; } } else if (it->type == MFLOW_CATCH) { try_catches[it->centry] = block; } else if (it->type == MFLOW_TARGET) { branch_to_targets[it->target->src].push_back(block); } else if (it->type == MFLOW_POSITION) { current_position = it->pos.get(); } if (!end_of_block(ir, it, in_try)) { continue; } // End the current block. if (m_editable) { // Steal the code from the ir and put it into the block. // This is safe to do while iterating in ir because iterators in ir now // point to elements of block->m_entries (and we already computed next). block->m_entries.splice_selection(block->m_entries.end(), *ir, block_begin, next); if (last_pos_before_this_block != nullptr) { auto first_insn = insn_before_position(block); if (first_insn != block->end()) { // DexPositions apply to every instruction in the linear stream until // the next DexPosition. Because we're breaking up the linear stream // into many small blocks, we need to make sure that instructions stay // associated with the same DexPosition as they were in the input // IRList. // // This creates duplicate positions, but we will remove any extras at // linearize time. block->m_entries.insert_before( first_insn, std::make_unique<DexPosition>(*last_pos_before_this_block)); } } } else { block->m_end = next; } if (next == ir->end()) { break; } // Start a new block at the next MethodItem. block = create_block(); if (m_editable) { last_pos_before_this_block = current_position; block_begin = next; } else { block->m_begin = next; } } TRACE(CFG, 5, " build: boundaries found"); } // Link the blocks together with edges. If the CFG is editable, also insert // fallthrough goto instructions and delete MFLOW_TARGETs. void ControlFlowGraph::connect_blocks(BranchToTargets& branch_to_targets) { for (auto it = m_blocks.begin(); it != m_blocks.end(); ++it) { // Set outgoing edge if last MIE falls through Block* b = it->second; auto& last_mie = *b->rbegin(); bool fallthrough = true; if (last_mie.type == MFLOW_OPCODE) { auto last_op = last_mie.insn->opcode(); if (is_branch(last_op)) { fallthrough = !is_goto(last_op); auto const& target_blocks = branch_to_targets[&last_mie]; for (auto target_block : target_blocks) { if (m_editable) { // The the branch information is stored in the edges, we don't need // the targets inside the blocks anymore auto case_key = target_block->remove_first_matching_target(&last_mie); if (case_key != boost::none) { add_edge(b, target_block, *case_key); continue; } } auto edge_type = is_goto(last_op) ? EDGE_GOTO : EDGE_BRANCH; add_edge(b, target_block, edge_type); } if (m_editable && is_goto(last_op)) { // We don't need the gotos in editable mode because the edges // fully encode that information b->m_entries.erase_and_dispose(b->m_entries.iterator_to(last_mie)); } } else if (is_return(last_op) || last_op == OPCODE_THROW) { fallthrough = false; } } auto next = std::next(it); Block* next_b = next->second; if (fallthrough && next != m_blocks.end()) { TRACE(CFG, 6, "adding fallthrough goto %d -> %d", b->id(), next_b->id()); add_edge(b, next_b, EDGE_GOTO); } } TRACE(CFG, 5, " build: edges added"); } void ControlFlowGraph::add_catch_edges(TryEnds& try_ends, TryCatches& try_catches) { /* * Every block inside a try-start/try-end region * gets an edge to every catch block. This simplifies dataflow analysis * since you can always get the exception state by looking at successors, * without any additional analysis. * * NB: This algorithm assumes that a try-start/try-end region will consist of * sequentially-numbered blocks, which is guaranteed because catch regions * are contiguous in the bytecode, and we generate blocks in bytecode order. */ for (auto tep : try_ends) { auto try_end = tep.first; auto tryendblock = tep.second; size_t bid = tryendblock->id(); while (true) { Block* block = m_blocks.at(bid); if (ends_with_may_throw(block)) { uint32_t i = 0; for (auto mie = try_end->catch_start; mie != nullptr; mie = mie->centry->next) { auto catchblock = try_catches.at(mie->centry); // Create a throw edge with the information from this catch entry add_edge(block, catchblock, mie->centry->catch_type, i); ++i; } } auto block_begin = block->begin(); if (block_begin != block->end() && block_begin->type == MFLOW_TRY) { auto tentry = block_begin->tentry; if (tentry->type == TRY_START) { always_assert_log(tentry->catch_start == try_end->catch_start, "%s", SHOW(*this)); break; } } always_assert_log(bid > 0, "No beginning of try region found"); --bid; } } TRACE(CFG, 5, " build: catch edges added"); } BlockId ControlFlowGraph::next_block_id() const { // Choose the next largest id. Note that we can't use m_block.size() because // we may have deleted some blocks from the cfg. const auto& rbegin = m_blocks.rbegin(); return (rbegin == m_blocks.rend()) ? 0 : (rbegin->first + 1); } void ControlFlowGraph::remove_unreachable_succ_edges() { // Remove edges between unreachable blocks and their succ blocks. if (m_blocks.empty()) { return; } const auto& visited = visit(); if (visited.all()) { // All blocks are visited. No blocks need to have their succ edges removed. return; } for (auto it = m_blocks.begin(); it != m_blocks.end(); ++it) { Block* b = it->second; if (visited.test(b->id())) { continue; } TRACE(CFG, 5, " build: removing succ edges from block %d", b->id()); delete_succ_edges(b); } TRACE(CFG, 5, " build: unreachables removed"); } /* * Traverse the graph, starting from the entry node. Return a bitset with IDs of * reachable blocks having 1 and IDs of unreachable blocks (or unused IDs) * having 0. */ boost::dynamic_bitset<> ControlFlowGraph::visit() const { std::stack<const cfg::Block*> to_visit; boost::dynamic_bitset<> visited{next_block_id()}; to_visit.push(entry_block()); while (!to_visit.empty()) { const cfg::Block* b = to_visit.top(); to_visit.pop(); if (visited.test_set(b->id())) { continue; } for (Edge* e : b->succs()) { to_visit.push(e->target()); } } return visited; } void ControlFlowGraph::simplify() { remove_unreachable_blocks(); remove_empty_blocks(); } // remove blocks with no predecessors uint32_t ControlFlowGraph::remove_unreachable_blocks() { uint32_t num_insns_removed = 0; remove_unreachable_succ_edges(); std::unordered_set<DexPosition*> deleted_positions; bool need_register_size_fix = false; for (auto it = m_blocks.begin(); it != m_blocks.end();) { Block* b = it->second; const auto& preds = b->preds(); if (preds.empty() && b != entry_block()) { for (const auto& mie : *b) { if (mie.type == MFLOW_POSITION) { deleted_positions.insert(mie.pos.get()); } else if (mie.type == MFLOW_OPCODE) { auto insn = mie.insn; if (insn->dests_size()) { // +1 because registers start at zero auto size_required = insn->dest() + insn->dest_is_wide() + 1; if (size_required >= m_registers_size) { // We're deleting an instruction that may have been the max // register of the entire function. need_register_size_fix = true; } } } } num_insns_removed += b->num_opcodes(); always_assert(b->succs().empty()); always_assert(b->preds().empty()); delete b; it = m_blocks.erase(it); } else { ++it; } } if (need_register_size_fix) { recompute_registers_size(); } remove_dangling_parents(deleted_positions); return num_insns_removed; } void ControlFlowGraph::remove_dangling_parents( const std::unordered_set<DexPosition*>& deleted_positions) { // We don't want to leave any dangling dex parent pointers behind if (!deleted_positions.empty()) { for (const auto& entry : m_blocks) { for (const auto& mie : *entry.second) { if (mie.type == MFLOW_POSITION && mie.pos->parent != nullptr && deleted_positions.count(mie.pos->parent)) { mie.pos->parent = nullptr; } } } } } void ControlFlowGraph::remove_empty_blocks() { always_assert(editable()); std::unordered_set<DexPosition*> deleted_positions; for (auto it = m_blocks.begin(); it != m_blocks.end();) { Block* b = it->second; if (!is_effectively_empty(b) || b == exit_block()) { ++it; continue; } const auto& succs = get_succ_edges_if( b, [](const Edge* e) { return e->type() != EDGE_GHOST; }); if (succs.size() > 0) { always_assert_log(succs.size() == 1, "too many successors for empty block %d:\n%s", it->first, SHOW(*this)); const auto& succ_edge = succs[0]; Block* succ = succ_edge->target(); if (b == succ) { // `b` follows itself: an infinite loop ++it; continue; } // b is empty. Reorganize the edges so we can remove it // Remove the one goto edge from b to succ delete_edges_between(b, succ); // If b was a predecessor of the exit block (for example, part of an // infinite loop) we need to transfer that info to `succ` because `b` will // be made unreachable and deleted by simplify auto ghost = get_succ_edge_of_type(b, EDGE_GHOST); if (ghost != nullptr) { set_edge_source(ghost, succ); } // Redirect from b's predecessors to b's successor (skipping b). We // can't move edges around while we iterate through the edge list // though. std::vector<Edge*> need_redirect(b->m_preds.begin(), b->m_preds.end()); for (Edge* pred_edge : need_redirect) { set_edge_target(pred_edge, succ); } if (b == entry_block()) { m_entry_block = succ; } } for (const auto& mie : *b) { if (mie.type == MFLOW_POSITION) { deleted_positions.insert(mie.pos.get()); } } delete b; it = m_blocks.erase(it); } remove_dangling_parents(deleted_positions); } void ControlFlowGraph::no_unreferenced_edges() const { EdgeSet referenced; for (const auto& entry : m_blocks) { Block* b = entry.second; for (Edge* e : b->preds()) { referenced.insert(e); } for (Edge* e : b->succs()) { referenced.insert(e); } } always_assert(referenced == m_edges); } // Verify that // * MFLOW_TARGETs are gone // * OPCODE_GOTOs are gone // * Correct number of outgoing edges void ControlFlowGraph::sanity_check() const { if (m_editable) { for (const auto& entry : m_blocks) { Block* b = entry.second; if (DEBUG) { // No targets or gotos for (const auto& mie : *b) { always_assert_log(mie.type != MFLOW_TARGET, "failed to remove all targets. block %d in\n%s", b->id(), SHOW(*this)); if (mie.type == MFLOW_OPCODE) { always_assert_log(!is_goto(mie.insn->opcode()), "failed to remove all gotos. block %d in\n%s", b->id(), SHOW(*this)); } } } // Last instruction matches outgoing edges auto num_goto_succs = get_succ_edges_of_type(b, EDGE_GOTO).size(); auto last_it = b->get_last_insn(); auto num_preds = b->preds().size(); auto num_succs = get_succ_edges_if( b, [](const Edge* e) { return e->type() != EDGE_GHOST; }) .size(); if (last_it != b->end()) { auto op = last_it->insn->opcode(); if (is_conditional_branch(op)) { always_assert_log(num_succs == 2, "block %d, %s", b->id(), SHOW(*this)); } else if (is_switch(op)) { always_assert_log(num_succs > 1, "block %d, %s", b->id(), SHOW(*this)); } else if (is_return(op)) { // Make sure we don't have any outgoing edges (except EDGE_GHOST) always_assert_log(num_succs == 0, "block %d, %s", b->id(), SHOW(*this)); } else if (is_throw(op)) { // A throw could end the method or go to a catch handler. // Make sure this block has no outgoing non-throwing edges auto non_throw_edge = get_succ_edge_if(b, [](const Edge* e) { return e->type() != EDGE_THROW && e->type() != EDGE_GHOST; }); always_assert_log(non_throw_edge == nullptr, "block %d, %s", b->id(), SHOW(*this)); } if (num_preds > 0 && !(is_return(op) || is_throw(op))) { // Control Flow shouldn't just fall off the end of a block, unless // it's an orphan block that's unreachable anyway always_assert_log(num_succs > 0, "block %d, %s", b->id(), SHOW(*this)); always_assert_log(num_goto_succs == 1, "block %d, %s", b->id(), SHOW(*this)); } } else if (num_preds > 0 && b != exit_block()) { // no instructions in this block. Control Flow shouldn't just fall off // the end always_assert_log(num_succs > 0, "block %d, %s", b->id(), SHOW(*this)); always_assert_log(num_goto_succs == 1, "block %d, %s", b->id(), SHOW(*this)); } always_assert_log(num_goto_succs < 2, "block %d, %s", b->id(), SHOW(*this)); } } for (const auto& entry : m_blocks) { Block* b = entry.second; // make sure the edge list in both blocks agree for (const auto e : b->succs()) { const auto& reverse_edges = e->target()->preds(); always_assert_log(std::find(reverse_edges.begin(), reverse_edges.end(), e) != reverse_edges.end(), "block %d -> %d, %s", b->id(), e->target()->id(), SHOW(*this)); } for (const auto e : b->preds()) { const auto& forward_edges = e->src()->succs(); always_assert_log(std::find(forward_edges.begin(), forward_edges.end(), e) != forward_edges.end(), "block %d -> %d, %s", e->src()->id(), b->id(), SHOW(*this)); } const auto& throws = b->get_outgoing_throws_in_order(); bool last = true; // Only the last throw edge can have a null catch type. for (auto it = throws.rbegin(); it != throws.rend(); ++it) { Edge* e = *it; if (!last) { always_assert_log( e->m_throw_info->catch_type != nullptr, "Can't have a catchall (%d -> %d) that isn't last. %s", e->src()->id(), e->target()->id(), SHOW(*this)); } last = false; } } if (m_editable) { auto used_regs = compute_registers_size(); always_assert_log(used_regs <= m_registers_size, "used regs %d > registers size %d. %s", used_regs, m_registers_size, SHOW(*this)); } no_dangling_dex_positions(); if (DEBUG) { no_unreferenced_edges(); } } uint16_t ControlFlowGraph::compute_registers_size() const { uint16_t num_regs = 0; for (const auto& mie : cfg::ConstInstructionIterable(*this)) { auto insn = mie.insn; if (insn->dests_size()) { // +1 because registers start at v0 uint16_t size_required = insn->dest() + insn->dest_is_wide() + 1; num_regs = std::max(size_required, num_regs); } } // We don't check the source registers because we shouldn't ever be using an // undefined register. If the input code is well-formed, there shouldn't be a // source register without an equivalent dest register. This is true for our // IR because of the load-param opcodes. return num_regs; } void ControlFlowGraph::recompute_registers_size() { m_registers_size = compute_registers_size(); } void ControlFlowGraph::no_dangling_dex_positions() const { std::unordered_map<DexPosition*, bool> parents; for (const auto& entry : m_blocks) { Block* b = entry.second; for (const auto& mie : *b) { if (mie.type == MFLOW_POSITION && mie.pos->parent != nullptr) { parents.emplace(mie.pos->parent, false); } } } for (const auto& entry : m_blocks) { Block* b = entry.second; for (const auto& mie : *b) { if (mie.type == MFLOW_POSITION) { auto search = parents.find(mie.pos.get()); if (search != parents.end()) { search->second = true; } } } } for (const auto& entry : parents) { always_assert_log(entry.second, "%lu is a dangling parent pointer in %s", entry.first, SHOW(*this)); } } uint32_t ControlFlowGraph::num_opcodes() const { uint32_t result = 0; for (const auto& entry : m_blocks) { result += entry.second->num_opcodes(); } return result; } uint32_t ControlFlowGraph::sum_opcode_sizes() const { uint32_t result = 0; for (const auto& entry : m_blocks) { result += entry.second->sum_opcode_sizes(); } return result; } boost::sub_range<IRList> ControlFlowGraph::get_param_instructions() { // Find the first block that has instructions Block* block = entry_block(); while (block->get_first_insn() == block->end()) { const auto& succs = block->succs(); always_assert(succs.size() == 1); const auto& out = succs[0]; always_assert(out->type() == EDGE_GOTO); block = out->target(); } return block->m_entries.get_param_instructions(); } void ControlFlowGraph::gather_catch_types(std::vector<DexType*>& types) const { always_assert(editable()); std::unordered_set<DexType*> seen; // get the catch types of all the incoming edges to all the catch blocks for (const auto& entry : m_blocks) { const Block* b = entry.second; if (b->is_catch()) { for (const cfg::Edge* e : b->preds()) { if (e->type() == cfg::EDGE_THROW) { DexType* t = e->throw_info()->catch_type; const auto pair = seen.insert(t); bool insertion_occured = pair.second; if (insertion_occured) { types.push_back(t); } } } } } } void ControlFlowGraph::gather_strings(std::vector<DexString*>& strings) const { always_assert(editable()); for (const auto& entry : m_blocks) { entry.second->m_entries.gather_strings(strings); } } void ControlFlowGraph::gather_types(std::vector<DexType*>& types) const { always_assert(editable()); gather_catch_types(types); for (const auto& entry : m_blocks) { entry.second->m_entries.gather_types(types); } } void ControlFlowGraph::gather_fields(std::vector<DexFieldRef*>& fields) const { always_assert(editable()); for (const auto& entry : m_blocks) { entry.second->m_entries.gather_fields(fields); } } void ControlFlowGraph::gather_methods( std::vector<DexMethodRef*>& methods) const { always_assert(editable()); for (const auto& entry : m_blocks) { entry.second->m_entries.gather_methods(methods); } } cfg::InstructionIterator ControlFlowGraph::primary_instruction_of_move_result( const cfg::InstructionIterator& it) { auto move_result_insn = it->insn; always_assert( opcode::is_move_result_or_move_result_pseudo(move_result_insn->opcode())); auto block = const_cast<Block*>(it.block()); if (block->get_first_insn()->insn == move_result_insn) { auto& preds = block->preds(); always_assert(preds.size() == 1); auto previous_block = preds.front()->src(); auto res = previous_block->to_cfg_instruction_iterator( previous_block->get_last_insn()); auto insn = res->insn; always_assert(insn->has_move_result() || insn->has_move_result_pseudo()); return res; } else { auto res = std::prev(it.unwrap()); auto insn = res->insn; always_assert(insn->has_move_result() || insn->has_move_result_pseudo()); return block->to_cfg_instruction_iterator(res); } } cfg::InstructionIterator ControlFlowGraph::move_result_of( const cfg::InstructionIterator& it) { auto next_insn = std::next(it); auto end = cfg::InstructionIterable(*this).end(); if (next_insn != end && it.block() == next_insn.block()) { // The easy case where the move result is in the same block auto op = next_insn->insn->opcode(); if (opcode::is_move_result_pseudo(op) || is_move_result(op)) { always_assert(primary_instruction_of_move_result(next_insn) == it); return next_insn; } } else { auto next_block = it.block()->goes_to(); if (next_block != nullptr && next_block->starts_with_move_result()) { next_insn = next_block->to_cfg_instruction_iterator(next_block->get_first_insn()); always_assert(primary_instruction_of_move_result(next_insn) == it); return next_insn; } } return end; } /* * fill `new_cfg` with a copy of `this` */ void ControlFlowGraph::deep_copy(ControlFlowGraph* new_cfg) const { always_assert(editable()); new_cfg->m_editable = true; new_cfg->set_registers_size(this->get_registers_size()); std::unordered_map<const Edge*, Edge*> old_edge_to_new; size_t num_edges = this->m_edges.size(); new_cfg->m_edges.reserve(num_edges); old_edge_to_new.reserve(num_edges); for (const Edge* old_edge : this->m_edges) { // this shallowly copies block pointers inside, then we patch them later Edge* new_edge = new Edge(*old_edge); new_cfg->m_edges.insert(new_edge); old_edge_to_new.emplace(old_edge, new_edge); } // copy the code itself MethodItemEntryCloner cloner; for (const auto& entry : this->m_blocks) { const Block* block = entry.second; // this shallowly copies edge pointers inside, then we patch them later Block* new_block = new Block(*block, &cloner); new_block->m_parent = new_cfg; new_cfg->m_blocks.emplace(new_block->id(), new_block); } // We need a second pass because parent position pointers may refer to // positions in a block that would be processed later. cloner.fix_parent_positions(); // patch the edge pointers in the blocks to their new cfg counterparts for (auto& entry : new_cfg->m_blocks) { Block* b = entry.second; for (Edge*& e : b->m_preds) { e = old_edge_to_new.at(e); } for (Edge*& e : b->m_succs) { e = old_edge_to_new.at(e); } } // patch the block pointers in the edges to their new cfg counterparts for (Edge* e : new_cfg->m_edges) { e->m_src = new_cfg->m_blocks.at(e->m_src->id()); e->m_target = new_cfg->m_blocks.at(e->m_target->id()); } // update the entry and exit block pointers to their new cfg counterparts new_cfg->m_entry_block = new_cfg->m_blocks.at(this->m_entry_block->id()); if (this->m_exit_block != nullptr) { new_cfg->m_exit_block = new_cfg->m_blocks.at(this->m_exit_block->id()); } } InstructionIterator ControlFlowGraph::find_insn(IRInstruction* needle, Block* hint) { if (hint != nullptr) { auto ii = ir_list::InstructionIterable(hint); for (auto it = ii.begin(); it != ii.end(); ++it) { if (it->insn == needle) { return hint->to_cfg_instruction_iterator(it); } } } auto iterable = InstructionIterable(*this); for (auto it = iterable.begin(); it != iterable.end(); ++it) { if (it->insn == needle) { return it; } } return iterable.end(); } std::vector<Block*> ControlFlowGraph::order() { // We must simplify first to remove any unreachable blocks simplify(); // This is a modified Weak Topological Ordering (WTO). We create "chains" of // blocks that will be kept together, then feed these chains to WTO for it to // choose the ordering of the chains. Then, we deconstruct the chains to get // an ordering of the blocks. // hold the chains of blocks here, though they mostly will be accessed via the // map std::vector<std::unique_ptr<Chain>> chains; // keep track of which blocks are in each chain, for quick lookup. std::unordered_map<Block*, Chain*> block_to_chain; block_to_chain.reserve(m_blocks.size()); build_chains(&chains, &block_to_chain); const auto& result = wto_chains(block_to_chain); always_assert_log(result.size() == m_blocks.size(), "result has %lu blocks, m_blocks has %lu", result.size(), m_blocks.size()); return result; } void ControlFlowGraph::build_chains( std::vector<std::unique_ptr<Chain>>* chains, std::unordered_map<Block*, Chain*>* block_to_chain) { for (const auto& entry : m_blocks) { Block* b = entry.second; if (block_to_chain->count(b) != 0) { continue; } always_assert_log(!DEBUG || !b->starts_with_move_result(), "%d is wrong %s", b->id(), SHOW(*this)); auto unique = std::make_unique<Chain>(); Chain* chain = unique.get(); chains->push_back(std::move(unique)); chain->push_back(b); block_to_chain->emplace(b, chain); auto goto_edge = get_succ_edge_of_type(b, EDGE_GOTO); while (goto_edge != nullptr) { // make sure we handle a chain of blocks that all start with move-results auto goto_block = goto_edge->target(); always_assert_log(!DEBUG || m_blocks.count(goto_block->id()) > 0, "bogus block reference %d -> %d in %s", goto_edge->src()->id(), goto_block->id(), SHOW(*this)); if (goto_block->starts_with_move_result() || goto_block->same_try(b)) { // If the goto edge leads to a block with a move-result(-pseudo), then // that block must be placed immediately after this one because we can't // insert anything between an instruction and its move-result(-pseudo). // // We also add gotos that are in the same try because we can minimize // instructions (by using fallthroughs) without adding another try // region. This is not required, but empirical evidence shows that it // generates smaller dex files. const auto& pair = block_to_chain->emplace(goto_block, chain); bool was_already_there = !pair.second; if (was_already_there) { break; } chain->push_back(goto_block); goto_edge = get_succ_edge_of_type(goto_block, EDGE_GOTO); } else { break; } } } } std::vector<Block*> ControlFlowGraph::wto_chains( const std::unordered_map<Block*, Chain*>& block_to_chain) { sparta::WeakTopologicalOrdering<Chain*> wto( block_to_chain.at(entry_block()), [&block_to_chain](Chain* const& chain) { // The chain successor function returns all the outgoing edges' target // chains. Where outgoing means that the edge does not go to this chain. // // FIXME: this algorithm ignores real infinite loops in the block graph std::vector<Chain*> result; result.reserve(chain->size()); // TODO: Sort the outputs by edge type, case key, and throw index // * We may be able to use fewer debug positions if we emit case blocks // in the original order. // * Right now, it seems the switches are being output in reverse // order, which is annoying for writing tests. const auto& end = chain->end(); for (auto it = chain->begin(); it != end;) { Block* b = *it; const auto& next_it = std::next(it); Block* next = (next_it == end) ? nullptr : *next_it; for (Edge* e : b->succs()) { if (e->target() == next) { // The most common intra-chain edge is a GOTO to the very next // block. Let's cheaply detect this case and filter it early, // before we have to do an expensive map lookup. continue; } const auto& succ_chain = block_to_chain.at(e->target()); // Filter out any edges within this chain. We don't want to // erroneously create infinite loops in the chain graph that don't // exist in the block graph. if (succ_chain != chain) { result.push_back(succ_chain); } } it = next_it; } return result; }); // recursively iterate through the wto order and collect the blocks here // This is a depth first traversal. TODO: would breadth first be better? std::vector<Block*> wto_order; std::function<void(const sparta::WtoComponent<Chain*>&)> get_order; get_order = [&get_order, &wto_order](const sparta::WtoComponent<Chain*>& v) { for (Block* b : *v.head_node()) { wto_order.push_back(b); } if (v.is_scc()) { for (const auto& inner : v) { get_order(inner); } } }; for (const auto& v : wto) { get_order(v); } return wto_order; } // Add an MFLOW_TARGET at the end of each edge. // Insert GOTOs where necessary. void ControlFlowGraph::insert_branches_and_targets( const std::vector<Block*>& ordering) { for (auto it = ordering.begin(); it != ordering.end(); ++it) { Block* b = *it; for (const Edge* edge : b->succs()) { if (edge->type() == EDGE_BRANCH) { auto branch_it = b->get_conditional_branch(); always_assert_log(branch_it != b->end(), "block %d %s", b->id(), SHOW(*this)); auto& branch_mie = *branch_it; BranchTarget* bt = edge->m_case_key != boost::none ? new BranchTarget(&branch_mie, *edge->m_case_key) : new BranchTarget(&branch_mie); auto target_mie = new MethodItemEntry(bt); edge->target()->m_entries.push_front(*target_mie); } else if (edge->type() == EDGE_GOTO) { auto next_it = std::next(it); if (next_it != ordering.end()) { Block* next = *next_it; if (edge->target() == next) { // Don't need a goto because this will fall through to `next` continue; } } auto branch_mie = new MethodItemEntry(new IRInstruction(OPCODE_GOTO)); auto target_mie = new MethodItemEntry(new BranchTarget(branch_mie)); edge->src()->m_entries.push_back(*branch_mie); edge->target()->m_entries.push_front(*target_mie); } } } } // remove all try and catch markers because we may reorder the blocks void ControlFlowGraph::remove_try_catch_markers() { always_assert(m_editable); for (const auto& entry : m_blocks) { Block* b = entry.second; b->m_entries.remove_and_dispose_if([](const MethodItemEntry& mie) { return mie.type == MFLOW_TRY || mie.type == MFLOW_CATCH; }); } } IRList* ControlFlowGraph::linearize() { always_assert(m_editable); sanity_check(); IRList* result = new IRList; TRACE(CFG, 5, "before linearize:\n%s", SHOW(*this)); const std::vector<Block*>& ordering = order(); insert_branches_and_targets(ordering); insert_try_catch_markers(ordering); for (Block* b : ordering) { result->splice(result->end(), b->m_entries); } remove_duplicate_positions(result); return result; } void ControlFlowGraph::insert_try_catch_markers( const std::vector<Block*>& ordering) { // add back the TRY START, TRY_ENDS, and, MFLOW_CATCHes const auto& insert_try_marker_between = [this](Block* prev, MethodItemEntry* new_try_marker, Block* b) { auto first_it = b->get_first_insn(); if (first_it != b->end() && opcode::is_move_result_pseudo(first_it->insn->opcode())) { // Make sure we don't split up a move-result-pseudo and its primary // instruction by placing the marker after the move-result-pseudo // // TODO: relax the constraint that move-result-pseudo must be // immediately after its partner, allowing non-opcode // MethodItemEntries between b->m_entries.insert_after(first_it, *new_try_marker); } else if (new_try_marker->tentry->type == TRY_START) { if (prev == nullptr && b == entry_block()) { // Parameter loading instructions come before a TRY_START auto params = b->m_entries.get_param_instructions(); b->m_entries.insert_before(params.end(), *new_try_marker); } else { // TRY_START belongs at the front of a block b->m_entries.push_front(*new_try_marker); } } else { // TRY_END belongs at the end of a block prev->m_entries.push_back(*new_try_marker); } }; std::unordered_map<MethodItemEntry*, Block*> catch_to_containing_block; Block* prev = nullptr; MethodItemEntry* active_catch = nullptr; for (auto it = ordering.begin(); it != ordering.end(); prev = *(it++)) { Block* b = *it; MethodItemEntry* new_catch = create_catch(b, &catch_to_containing_block); if (new_catch == nullptr && cannot_throw(b) && !b->is_catch()) { // Generate fewer try regions by merging blocks that cannot throw into the // previous try region. // // But, we have to be careful to not include the catch block of this try // region, which would create invalid Dex Try entries. For any given try // region, none of its catches may be inside that region. continue; } if (active_catch != new_catch) { // If we're switching try regions between these blocks, the TRY_END must // come first then the TRY_START. We insert the TRY_START earlier because // we're using `insert_after` which inserts things in reverse order if (new_catch != nullptr) { // Start a new try region before b auto new_start = new MethodItemEntry(TRY_START, new_catch); insert_try_marker_between(prev, new_start, b); } if (active_catch != nullptr) { // End the current try region before b auto new_end = new MethodItemEntry(TRY_END, active_catch); insert_try_marker_between(prev, new_end, b); } active_catch = new_catch; } } if (active_catch != nullptr) { always_assert_log(active_catch->centry->next != active_catch, "Invalid cycle: %s", SHOW(active_catch)); ordering.back()->m_entries.push_back( *new MethodItemEntry(TRY_END, active_catch)); } } MethodItemEntry* ControlFlowGraph::create_catch( Block* block, std::unordered_map<MethodItemEntry*, Block*>* catch_to_containing_block) { always_assert(m_editable); using EdgeVector = std::vector<Edge*>; EdgeVector throws = get_succ_edges_of_type(block, EDGE_THROW); if (throws.empty()) { // No need to create a catch if there are no throws return nullptr; } std::sort(throws.begin(), throws.end(), [](const Edge* e1, const Edge* e2) { return e1->m_throw_info->index < e2->m_throw_info->index; }); const auto& throws_end = throws.end(); // recurse through `throws` adding catch entries to blocks at the ends of // throw edges and connecting the catch entry `next` pointers according to the // throw edge indices. // // We stop early if we find find an equivalent linked list of catch entries std::function<MethodItemEntry*(const EdgeVector::iterator&)> add_catch; add_catch = [this, &add_catch, &throws_end, catch_to_containing_block]( const EdgeVector::iterator& it) -> MethodItemEntry* { if (it == throws_end) { return nullptr; } auto edge = *it; auto catch_block = edge->target(); for (auto& mie : *catch_block) { // Is there already a catch here that's equivalent to the catch we would // create? if (mie.type == MFLOW_CATCH && catch_entries_equivalent_to_throw_edges(&mie, it, throws_end, *catch_to_containing_block)) { // The linked list of catch entries starting at `mie` is equivalent to // the rest of `throws` from `it` to `end`. So we don't need to create // another one, use the existing list. return &mie; } } // We recurse and find the next catch before creating this catch because // otherwise, we could create a cycle of the catch entries. MethodItemEntry* next = add_catch(std::next(it)); // create a new catch entry and insert it into the bytecode auto new_catch = new MethodItemEntry(edge->m_throw_info->catch_type); new_catch->centry->next = next; catch_block->m_entries.push_front(*new_catch); catch_to_containing_block->emplace(new_catch, catch_block); return new_catch; }; return add_catch(throws.begin()); } // Follow the catch entry linked list starting at `first_mie` and check if the // throw edges (pointed to by `it`) are equivalent to the linked list. The throw // edges should be sorted by their indices. // // This function is useful in avoiding generating multiple identical catch // entries bool ControlFlowGraph::catch_entries_equivalent_to_throw_edges( MethodItemEntry* first_mie, std::vector<Edge*>::iterator it, std::vector<Edge*>::iterator end, const std::unordered_map<MethodItemEntry*, Block*>& catch_to_containing_block) { for (auto mie = first_mie; mie != nullptr; mie = mie->centry->next) { always_assert(mie->type == MFLOW_CATCH); if (it == end) { return false; } auto edge = *it; if (mie->centry->catch_type != edge->m_throw_info->catch_type) { return false; } const auto& search = catch_to_containing_block.find(mie); always_assert_log(search != catch_to_containing_block.end(), "%s not found in %s", SHOW(*mie), SHOW(*this)); if (search->second != edge->target()) { return false; } ++it; } return it == end; } std::vector<Block*> ControlFlowGraph::blocks() const { std::vector<Block*> result; result.reserve(m_blocks.size()); for (const auto& entry : m_blocks) { Block* b = entry.second; result.emplace_back(b); } return result; } // Uses a standard depth-first search ith a side table of already-visited nodes. std::vector<Block*> ControlFlowGraph::blocks_post_helper(bool reverse) const { std::stack<Block*> stack; for (const auto& entry : m_blocks) { // include unreachable blocks too Block* b = entry.second; if (b != entry_block() && b->preds().empty()) { stack.push(b); } } stack.push(entry_block()); std::vector<Block*> postorder; postorder.reserve(m_blocks.size()); std::unordered_set<Block*> visited; visited.reserve(m_blocks.size()); while (!stack.empty()) { const auto& curr = stack.top(); visited.insert(curr); bool all_succs_visited = [&] { for (auto const& s : curr->succs()) { if (!visited.count(s->target())) { stack.push(s->target()); return false; } } return true; }(); if (all_succs_visited) { redex_assert(curr == stack.top()); postorder.push_back(curr); stack.pop(); } } if (reverse) { std::reverse(postorder.begin(), postorder.end()); } return postorder; } std::vector<Block*> ControlFlowGraph::blocks_reverse_post() const { return blocks_post_helper(true); } std::vector<Block*> ControlFlowGraph::blocks_post() const { return blocks_post_helper(false); } ControlFlowGraph::~ControlFlowGraph() { for (const auto& entry : m_blocks) { Block* b = entry.second; delete b; } for (Edge* e : m_edges) { delete e; } } Block* ControlFlowGraph::create_block() { size_t id = next_block_id(); Block* b = new Block(this, id); m_blocks.emplace(id, b); return b; } Block* ControlFlowGraph::duplicate_block(Block* original) { Block* copy = create_block(); MethodItemEntryCloner cloner; for (const auto& mie : *original) { copy->m_entries.push_back(*cloner.clone(&mie)); } return copy; } // We create a small class here (instead of a recursive lambda) so we can // label visit with NO_SANITIZE_ADDRESS class ExitBlocks { private: uint32_t next_dfn{0}; std::stack<const Block*> stack; // Depth-first number. Special values: // 0 - unvisited // UINT32_MAX - visited and determined to be in a separate SCC std::unordered_map<const Block*, uint32_t> dfns; static constexpr uint32_t VISITED = std::numeric_limits<uint32_t>::max(); // This is basically Tarjan's algorithm for finding SCCs. I pass around an // extra has_exit value to determine if a given SCC has any successors. using t = std::pair<uint32_t, bool>; public: std::vector<Block*> exit_blocks; NO_SANITIZE_ADDRESS // because of deep recursion. ASAN uses too much memory. t visit(const Block* b) { stack.push(b); uint32_t head = dfns[b] = ++next_dfn; // whether any vertex in the current SCC has a successor edge that points // outside itself bool has_exit{false}; for (auto& succ : b->succs()) { uint32_t succ_dfn = dfns[succ->target()]; uint32_t min; if (succ_dfn == 0) { bool succ_has_exit; std::tie(min, succ_has_exit) = visit(succ->target()); has_exit |= succ_has_exit; } else { has_exit |= succ_dfn == VISITED; min = succ_dfn; } head = std::min(min, head); } if (head == dfns[b]) { const Block* top{nullptr}; if (!has_exit) { exit_blocks.push_back(const_cast<Block*>(b)); has_exit = true; } do { top = stack.top(); stack.pop(); dfns[top] = VISITED; } while (top != b); } return t(head, has_exit); } }; std::vector<Block*> ControlFlowGraph::real_exit_blocks( bool include_infinite_loops) { std::vector<Block*> result; if (m_exit_block != nullptr && include_infinite_loops) { auto ghosts = get_pred_edges_of_type(m_exit_block, EDGE_GHOST); if (!ghosts.empty()) { // The exit block is a ghost block, ignore it and get the real exit // points. for (auto e : ghosts) { result.push_back(e->src()); } } else { // Empty ghosts means the method has a single exit point and // calculate_exit_block didn't add a ghost block. result.push_back(m_exit_block); } } else { always_assert_log(!include_infinite_loops, "call calculate_exit_block first"); for (const auto& entry : m_blocks) { Block* block = entry.second; const auto& b = block->branchingness(); if (b == opcode::BRANCH_RETURN || b == opcode::BRANCH_THROW) { result.push_back(block); } } } return result; } std::vector<Block*> ControlFlowGraph::return_blocks() const { std::vector<Block*> result; for (const auto& entry : m_blocks) { Block* block = entry.second; const auto& b = block->branchingness(); if (b == opcode::BRANCH_RETURN) { result.push_back(block); } } return result; } /* * Find all exit blocks. Note that it's not as simple as looking for Blocks with * return or throw opcodes; infinite loops are a valid way of terminating dex * bytecode too. As such, we need to find all strongly connected components * (SCCs) and vertices that lack successors. For SCCs that lack successors, any * one of its vertices can be treated as an exit block; this implementation * picks the head of the SCC. */ void ControlFlowGraph::calculate_exit_block() { if (m_exit_block != nullptr) { if (!m_editable) { return; } if (get_pred_edge_of_type(m_exit_block, EDGE_GHOST) != nullptr) { // Need to clear old exit block before recomputing the exit of a CFG // with multiple exit points remove_block(m_exit_block); m_exit_block = nullptr; } } ExitBlocks eb; eb.visit(entry_block()); if (eb.exit_blocks.size() == 1) { m_exit_block = eb.exit_blocks[0]; } else { m_exit_block = create_block(); for (Block* b : eb.exit_blocks) { add_edge(b, m_exit_block, EDGE_GHOST); } } } // public API edge removal functions void ControlFlowGraph::delete_edge(Edge* edge) { remove_edge(edge); free_edge(edge); } void ControlFlowGraph::delete_succ_edges(Block* b) { free_edges(remove_succ_edges(b)); } void ControlFlowGraph::delete_pred_edges(Block* b) { free_edges(remove_pred_edges(b)); } // private edge removal functions // These are raw removal, they don't free the edge. ControlFlowGraph::EdgeSet ControlFlowGraph::remove_edges_between(Block* p, Block* s, bool cleanup) { return remove_edge_if(p, s, [](const Edge*) { return true; }, cleanup); } void ControlFlowGraph::delete_edges_between(Block* p, Block* s) { free_edges(remove_edges_between(p, s)); } void ControlFlowGraph::remove_edge(Edge* edge, bool cleanup) { remove_edge_if(edge->src(), edge->target(), [edge](const Edge* e) { return edge == e; }, cleanup); } // After `edges` have been removed from the graph, // * Turn BRANCHes/SWITCHes with one outgoing edge into GOTOs void ControlFlowGraph::cleanup_deleted_edges(const EdgeSet& edges) { for (Edge* e : edges) { auto pred_block = e->src(); auto last_it = pred_block->get_last_insn(); if (last_it != pred_block->end()) { auto last_insn = last_it->insn; auto op = last_insn->opcode(); auto remaining_forward_edges = pred_block->succs(); if ((is_conditional_branch(op) || is_switch(op)) && remaining_forward_edges.size() == 1) { pred_block->m_entries.erase_and_dispose(last_it); remaining_forward_edges.at(0)->m_type = EDGE_GOTO; } } } } void ControlFlowGraph::free_edge(Edge* edge) { m_edges.erase(edge); delete edge; } void ControlFlowGraph::free_edges(const EdgeSet& edges) { for (Edge* e : edges) { free_edge(e); } } Edge* ControlFlowGraph::get_pred_edge_of_type(const Block* block, EdgeType type) const { return get_pred_edge_if(block, [type](const Edge* e) { return e->type() == type; }); } Edge* ControlFlowGraph::get_succ_edge_of_type(const Block* block, EdgeType type) const { return get_succ_edge_if(block, [type](const Edge* e) { return e->type() == type; }); } std::vector<Edge*> ControlFlowGraph::get_pred_edges_of_type( const Block* block, EdgeType type) const { return get_pred_edges_if(block, [type](const Edge* e) { return e->type() == type; }); } std::vector<Edge*> ControlFlowGraph::get_succ_edges_of_type( const Block* block, EdgeType type) const { return get_succ_edges_if(block, [type](const Edge* e) { return e->type() == type; }); } Block* ControlFlowGraph::split_block(const cfg::InstructionIterator& it) { always_assert(editable()); always_assert(!it.is_end()); // old_block will be the predecessor Block* old_block = it.block(); // new_block will be the successor Block* new_block = create_block(); const IRList::iterator& raw_it = it.unwrap(); // move the rest of the instructions after the split point into the new block new_block->m_entries.splice_selection(new_block->begin(), old_block->m_entries, std::next(raw_it), old_block->end()); // make the outgoing edges come from the new block... std::vector<Edge*> to_move(old_block->succs().begin(), old_block->succs().end()); for (auto e : to_move) { // ... except if we didn't move the branching/throwing instruction; in that // case, just rewire the goto, as we are going to create a new one if (new_block->empty() && e->type() != EDGE_GOTO) { continue; } set_edge_source(e, new_block); } // connect the halves of the block we just split up add_edge(old_block, new_block, EDGE_GOTO); return new_block; } void ControlFlowGraph::merge_blocks(Block* pred, Block* succ) { const auto& not_throws = [](const Edge* e) { return e->type() != EDGE_THROW; }; { const auto& forwards = get_succ_edges_if(pred, not_throws); always_assert(forwards.size() == 1); auto forward_edge = forwards[0]; always_assert(forward_edge->target() == succ); always_assert(forward_edge->type() == EDGE_GOTO); const auto& reverses = succ->preds(); always_assert(reverses.size() == 1); auto reverse_edge = reverses[0]; always_assert(forward_edge == reverse_edge); } delete_edges_between(pred, succ); // move succ's code into pred pred->m_entries.splice(pred->m_entries.end(), succ->m_entries); // move succ's outgoing edges to pred. // Intentionally copy the vector of edges because set_edge_source edits the // edge vectors auto succs = get_succ_edges_if(succ, not_throws); for (auto succ_edge : succs) { set_edge_source(succ_edge, pred); } // remove the succ block delete_pred_edges(succ); delete_succ_edges(succ); m_blocks.erase(succ->id()); delete succ; } void ControlFlowGraph::set_edge_target(Edge* edge, Block* new_target) { move_edge(edge, nullptr, new_target); } void ControlFlowGraph::set_edge_source(Edge* edge, Block* new_source) { move_edge(edge, new_source, nullptr); } // Move this edge out of the vectors between its old blocks // and into the vectors between the new blocks void ControlFlowGraph::move_edge(Edge* edge, Block* new_source, Block* new_target) { // remove this edge from the graph temporarily but do not delete it because // we're going to move it elsewhere remove_edge(edge, /* cleanup */ false); if (new_source != nullptr) { edge->m_src = new_source; } if (new_target != nullptr) { edge->m_target = new_target; } edge->src()->m_succs.push_back(edge); edge->target()->m_preds.push_back(edge); } bool ControlFlowGraph::blocks_are_in_same_try(const Block* b1, const Block* b2) const { const auto& throws1 = b1->get_outgoing_throws_in_order(); const auto& throws2 = b2->get_outgoing_throws_in_order(); if (throws1.size() != throws2.size()) { return false; } auto it1 = throws1.begin(); auto it2 = throws2.begin(); for (; it1 != throws1.end(); ++it1, ++it2) { auto e1 = *it1; auto e2 = *it2; if (e1->target() != e2->target() || e1->m_throw_info->catch_type != e2->m_throw_info->catch_type) { return false; } } return true; } bool ControlFlowGraph::replace_insns(const InstructionIterator& it, const std::vector<IRInstruction*>& insns) { return replace_insns(it, insns.begin(), insns.end()); } bool ControlFlowGraph::replace_insn(const InstructionIterator& it, IRInstruction* insn) { return replace_insns(it, {insn}); } void ControlFlowGraph::remove_insn(const InstructionIterator& it) { always_assert(m_editable); MethodItemEntry& mie = *it; auto insn = mie.insn; auto op = insn->opcode(); always_assert_log(op != OPCODE_GOTO, "There are no GOTO instructions in the CFG"); Block* block = it.block(); auto last_it = block->get_last_insn(); always_assert_log(last_it != block->end(), "cannot remove from empty block"); if (is_conditional_branch(op) || is_switch(op)) { // Remove all outgoing EDGE_BRANCHes // leaving behind only an EDGE_GOTO (and maybe an EDGE_THROW?) // // Don't cleanup because we're deleting the instruction at the end of this // function free_edges(remove_succ_edge_if( block, [](const Edge* e) { return e->type() == EDGE_BRANCH; }, /* cleanup */ false)); } else if (insn->has_move_result_pseudo()) { // delete the move-result-pseudo too if (insn == last_it->insn) { // The move-result-pseudo is in the next (runtime) block. // We follow the goto edge to the block that should have the // move-result-pseudo. // // We can't use std::next because that goes to the next block in ID order, // which may not be the next runtime block. auto move_result_block = block->goes_to(); always_assert_log(move_result_block != nullptr, "Cannot follow goto of B%u in %s", block->id(), SHOW(*this)); auto first_it = move_result_block->get_first_insn(); always_assert(first_it != move_result_block->end()); always_assert_log(opcode::is_move_result_pseudo(first_it->insn->opcode()), "%d -> %d in %s", block->id(), move_result_block->id(), SHOW(*this)); // We can safely delete this move-result-pseudo because it cannot be the // move-result-pseudo of more than one primary instruction. A CFG with // multiple edges to a block beginning with a move-result-pseudo is a // malformed CFG. always_assert_log(move_result_block->preds().size() == 1, "Multiple edges to a move-result-pseudo in %d. %s", move_result_block->id(), SHOW(*this)); move_result_block->m_entries.erase_and_dispose(first_it); } else { // The move-result-pseudo is in the same block as this one. // This occurs when we're not in a try region. auto mrp_it = std::next(it); always_assert(mrp_it.block() == block); block->m_entries.erase_and_dispose(mrp_it.unwrap()); } } if (insn == last_it->insn && (opcode::may_throw(op) || op == OPCODE_THROW)) { // We're deleting the last instruction that may throw, this block no longer // throws. We should remove the throw edges delete_succ_edge_if(block, [](const Edge* e) { return e->type() == EDGE_THROW; }); } // delete the requested instruction block->m_entries.erase_and_dispose(it.unwrap()); } void ControlFlowGraph::create_branch(Block* b, IRInstruction* insn, Block* fls, Block* tru) { create_branch(b, insn, fls, {{1, tru}}); } void ControlFlowGraph::create_branch( Block* b, IRInstruction* insn, Block* goto_block, const std::vector<std::pair<int32_t, Block*>>& case_to_block) { auto op = insn->opcode(); always_assert(m_editable); always_assert_log(is_branch(op), "%s is not a branch instruction", SHOW(op)); always_assert_log(!is_goto(op), "There are no gotos in the editable CFG. Use add_edge()"); auto existing_last = b->get_last_insn(); if (existing_last != b->end()) { auto last_op = existing_last->insn->opcode(); always_assert_log( !(is_branch(last_op) || is_throw(last_op) || is_return(last_op)), "Can't add branch after %s in Block %d in %s", SHOW(existing_last->insn), b->id(), SHOW(*this)); } auto existing_goto_edge = get_succ_edge_of_type(b, EDGE_GOTO); if (goto_block != nullptr) { if (existing_goto_edge != nullptr) { // redirect it set_edge_target(existing_goto_edge, goto_block); } else { add_edge(b, goto_block, EDGE_GOTO); } } else { always_assert_log(existing_goto_edge != nullptr, "%s must have a false case", SHOW(insn)); } b->m_entries.push_back(*new MethodItemEntry(insn)); if (is_switch(op)) { for (const auto& entry : case_to_block) { add_edge(b, entry.second, entry.first); } } else { always_assert(is_conditional_branch(op)); always_assert_log(case_to_block.size() == 1, "Wrong number of non-goto cases (%d) for %s", case_to_block.size(), SHOW(op)); const auto& entry = case_to_block[0]; always_assert_log(entry.first == 1, "%s only has boolean case key values", SHOW(op)); add_edge(b, entry.second, EDGE_BRANCH); } } void ControlFlowGraph::copy_succ_edges(Block* from, Block* to, EdgeType type) { const auto& edges = get_succ_edges_of_type(from, type); for (const Edge* e : edges) { Edge* copy = new Edge(*e); copy->m_src = to; add_edge(copy); } } bool ControlFlowGraph::insert_before(const InstructionIterator& position, const std::vector<IRInstruction*>& insns) { return insert_before(position, insns.begin(), insns.end()); } bool ControlFlowGraph::insert_after(const InstructionIterator& position, const std::vector<IRInstruction*>& insns) { return insert_after(position, insns.begin(), insns.end()); } bool ControlFlowGraph::push_front(Block* b, const std::vector<IRInstruction*>& insns) { return push_front(b, insns.begin(), insns.end()); } bool ControlFlowGraph::push_back(Block* b, const std::vector<IRInstruction*>& insns) { return push_back(b, insns.begin(), insns.end()); } bool ControlFlowGraph::insert_before(const InstructionIterator& position, IRInstruction* insn) { return insert_before(position, std::vector<IRInstruction*>{insn}); } bool ControlFlowGraph::insert_after(const InstructionIterator& position, IRInstruction* insn) { return insert_after(position, std::vector<IRInstruction*>{insn}); } bool ControlFlowGraph::push_front(Block* b, IRInstruction* insn) { return push_front(b, std::vector<IRInstruction*>{insn}); } bool ControlFlowGraph::push_back(Block* b, IRInstruction* insn) { return push_back(b, std::vector<IRInstruction*>{insn}); } void ControlFlowGraph::remove_block(Block* block) { if (block == entry_block()) { always_assert(block->succs().size() == 1); set_entry_block(block->succs()[0]->target()); } delete_pred_edges(block); delete_succ_edges(block); std::unordered_set<DexPosition*> deleted_positions; for (const auto& mie : *block) { if (mie.type == MFLOW_POSITION) { deleted_positions.insert(mie.pos.get()); } } remove_dangling_parents(deleted_positions); auto id = block->id(); auto num_removed = m_blocks.erase(id); always_assert_log(num_removed == 1, "Block %d wasn't in CFG. Attempted double delete?", id); block->m_entries.clear_and_dispose(); delete block; } // delete old_block and reroute its predecessors to new_block void ControlFlowGraph::replace_block(Block* old_block, Block* new_block) { std::vector<Edge*> to_redirect = old_block->preds(); for (auto e : to_redirect) { set_edge_target(e, new_block); } remove_block(old_block); } std::ostream& ControlFlowGraph::write_dot_format(std::ostream& o) const { o << "digraph {\n"; for (auto* block : blocks()) { for (auto& succ : block->succs()) { o << block->id() << " -> " << succ->target()->id() << "\n"; } } o << "}\n"; return o; } Block* ControlFlowGraph::idom_intersect( const std::unordered_map<Block*, DominatorInfo>& postorder_dominator, Block* block1, Block* block2) const { auto finger1 = block1; auto finger2 = block2; while (finger1 != finger2) { while (postorder_dominator.at(finger1).postorder < postorder_dominator.at(finger2).postorder) { finger1 = postorder_dominator.at(finger1).dom; } while (postorder_dominator.at(finger2).postorder < postorder_dominator.at(finger1).postorder) { finger2 = postorder_dominator.at(finger2).dom; } } return finger1; } // Finding immediate dominator for each blocks in ControlFlowGraph. // Theory from: // K. D. Cooper et.al. A Simple, Fast Dominance Algorithm. std::unordered_map<Block*, DominatorInfo> ControlFlowGraph::immediate_dominators() const { // Get postorder of blocks and create map of block to postorder number. std::unordered_map<Block*, DominatorInfo> postorder_dominator; const auto& postorder_blocks = blocks_post(); for (size_t i = 0; i < postorder_blocks.size(); ++i) { postorder_dominator[postorder_blocks[i]].postorder = i; } // Initialize immediate dominators. Having value as nullptr means it has // not been processed yet. for (Block* block : blocks()) { if (block->preds().empty()) { // Entry block's immediate dominator is itself. postorder_dominator[block].dom = block; } else { postorder_dominator[block].dom = nullptr; } } bool changed = true; while (changed) { changed = false; // Traverse block in reverse postorder. for (auto rit = postorder_blocks.rbegin(); rit != postorder_blocks.rend(); ++rit) { Block* ordered_block = *rit; if (ordered_block->preds().empty()) { continue; } Block* new_idom = nullptr; // Pick one random processed block as starting point. for (auto& pred : ordered_block->preds()) { if (postorder_dominator[pred->src()].dom != nullptr) { new_idom = pred->src(); break; } } always_assert(new_idom != nullptr); for (auto& pred : ordered_block->preds()) { if (pred->src() != new_idom && postorder_dominator[pred->src()].dom != nullptr) { new_idom = idom_intersect(postorder_dominator, new_idom, pred->src()); } } if (postorder_dominator[ordered_block].dom != new_idom) { postorder_dominator[ordered_block].dom = new_idom; changed = true; } } } return postorder_dominator; } ControlFlowGraph::EdgeSet ControlFlowGraph::remove_succ_edges(Block* b, bool cleanup) { return remove_succ_edge_if(b, [](const Edge*) { return true; }, cleanup); } ControlFlowGraph::EdgeSet ControlFlowGraph::remove_pred_edges(Block* b, bool cleanup) { return remove_pred_edge_if(b, [](const Edge*) { return true; }, cleanup); } } // namespace cfg
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
4de4d446c75776fb8e30e043fbdb19a35617595e
62c5835005ce84cd7f18cefb1ad3b5ee46e20ecc
/src/Eta.h
2e0d576c34f02c339223c60c35a7cd5b254c2f0f
[]
no_license
s-jeong/MSBS
b5ca0a938ab0c13c7d7e76a1267ecc3c788d2a76
d911084bba137867cffd68241d41115f4c3a4847
refs/heads/master
2023-07-09T13:41:44.479595
2021-08-21T15:40:31
2021-08-21T15:40:31
286,003,613
0
0
null
null
null
null
UTF-8
C++
false
false
814
h
#ifndef _ETA_H #define _ETA_H #include <RcppArmadillo.h> using namespace Rcpp; // [[Rcpp::depends(RcppArmadillo)]] // [[Rcpp::export]] IntegerVector Eta(List delta, IntegerVector gamma, int p, int q) { int total_length = 0; for (int i = 0; i < p; ++i){ total_length += Rf_length(delta[i]); } IntegerVector ind(p); ind[gamma[Range(0,p-1)]==2] = 1; int index = 0; IntegerVector vecdelta(total_length+q); for(int i = 0; i < p; i++) { IntegerVector tempdelta=as<IntegerVector>(wrap(delta[i]))*ind(i); if(gamma[i]==1) { tempdelta[0]=1; } std::copy(tempdelta.begin(), tempdelta.end(), vecdelta.begin() + index); index += tempdelta.size(); } if(q > 0.5){ std::copy(gamma[Range(p,p+q-1)].begin(), gamma[Range(p,p+q-1)].end(), vecdelta.begin() + index); } return vecdelta; } #else #endif
[ "sjeong823@gmail.com" ]
sjeong823@gmail.com
4d73cc07efeb029b65692723e40d589e8fd725ef
eb1d2c439aa39a699efbe67221d2ce60355ee334
/main.cpp
d2c135a35b0841fa051c3dc1493836c711cfbcac
[]
no_license
ruthbijaoui/hw9
2ba73642061c29858d9ed5fb31aa098242d4738d
fc43e590330d995306c97b1d0b643a3d6c77d3fe
refs/heads/main
2023-02-23T18:45:08.044951
2021-01-30T16:21:19
2021-01-30T16:21:19
333,941,916
0
0
null
null
null
null
UTF-8
C++
false
false
1,166
cpp
#include <iostream> #include <cstring> #include "ip.h" #include "port.h" extern int check_args(int, char**); extern void parse_input(Field&); int main(int argc, char** argv) { String* output; size_t size = 0; /* Check that the parameters of main method are correct */ if (check_args(argc, argv) != 0) { return -1; } String new_rule(argv[1]); new_rule.split("=", &output, &size); String new_rule_name(output[0].trim()); String new_rule_val(output[1].trim()); /* Check if the command is IP */ if ((new_rule_name.equals("src-ip")) || (new_rule_name.equals("dst-ip"))) { Ip ip(new_rule_name); ip.set_value(new_rule_val); parse_input(ip); /* Receives a reference to IP objects */ } /* and print the captured packets that */ /* meet the defined rules. */ /* Check if the command is port */ if((new_rule_name.equals("src-port")) || (new_rule_name.equals("dst-port"))) { Port port(new_rule_name); port.set_value(new_rule_val); parse_input(port); /* Receives a reference to port objects */ } /* and print the captured packets that */ delete[] output; /* meet the defined rules. */ return 0; }
[ "ruthbijaoui" ]
ruthbijaoui
0592ba078b8772fbbce1d2ec29ba1990b58e6d5a
ccddbc9b140b5630212f75f1654073edfdf8cfd9
/Third/ExCode/bigNumber.cpp
533936fab61bf334db0ff0543c1d000884f4fcb0
[]
no_license
ksunchikk/oop
fd974d436dd6ab5bef4f078e9a537e101b075655
2530c625e224fad0df1e5e0cb545105edd0b5e5b
refs/heads/master
2023-02-13T13:33:56.688722
2021-01-09T09:49:51
2021-01-09T09:49:51
296,397,165
0
1
null
null
null
null
UTF-8
C++
false
false
8,418
cpp
#include "bigNumber.h" #include <cstdio> #include <iostream> namespace Prog3a { bigDecNum::bigDecNum() { //знак +, все цифры - нули for (int i = 0; i < SZ + 1; ++i) Num[i] = 0; n = 1; //количество разрядов } //формирование из типа long int bigDecNum::bigDecNum(long int x) { //устанавливаем знак if (x < 0) Num[0] = 1; else Num[0] = 0; long int a = abs(x); int i = 1; n = 0; while (a) { ++n; //считаем количество разрядов Num[i] = (a % 10); a /= 10; i++; if (n > SZ) throw std::invalid_argument("Overflow"); } for (int j = SZ; j >= SZ - n + 1; j--) Num[j] = 0; //заполнение лидирующими нулями } //конструирование большого числа из строки bigDecNum::bigDecNum(const char* str) { Set(str); } bigDecNum& bigDecNum::Set(const char* str) { std::string STR = str; //определяем длину строки int l = STR.std::string::length(); if (l > SZ + 1) throw std::invalid_argument("Too many chars!"); n = l; if (str[0] == '-') { Num[0] = 1; n--; } else Num[0] = 0; //проверка, есть ли в строке нецифровые символы int pr1 = STR.std::string::find_first_not_of("-0123456789"); if (pr1 >= 0) { bigDecNum a; *this = a; throw std::invalid_argument("Incorrect data. Your can only have 0-9 chars"); } int z = 0; int i = str[0] == '-' ? 1 : 0; if ((str[0] == '-' && str[1] == '0') || str[0] == '0') { while (str[i] == '0') { //считаем лидирующие нули i++; z++; } if (i == l) { //если вся строка состоит из нулей, то создаем ноль нашего класса Num[0] = 0; n = 1; for (int i = 1; i < SZ + 1; ++i) Num[i] = 0; return *this; } } n -= z; //количество разрядов не учитывает лидирующие нули i = l - 1; //идем со старших разрядов for (int k = 1; k <= n; k++) { Num[k] = str[i] - '0'; i--; } //заполнение лидирующими нулями for (int k = SZ; k >= n + 1; k--) Num[k] = 0; return *this; } bigDecNum bigDecNum::AddCode() const { bigDecNum a; if (Num[0] == 0) return *this; int pr = 1; for (int i = 1; i <= SZ; i++) { if (pr && Num[i] != 0) { a.Num[i] = 10 - Num[i]; pr = 0; } else if (!pr) a.Num[i] = 9 - Num[i]; } a.n = n; if (Num[1] == 0) a.Num[1] = 0; a.Num[0] = Num[0]; return a; } bool bigDecNum::Large(const bigDecNum& t) const { if (n > t.n) return true; if (t.n > n) return false; if (t.n == n) { for (int i = n; i >= 1; i--) { if (Num[i] > t.Num[i]) return true; if (t.Num[i] > Num[i]) return false; } } return true; } bigDecNum bigDecNum::Sum(const bigDecNum& t)const { int dop = 0; bool index = (Num[0] == t.Num[0]); int j = n >= t.n ? n : t.n; bigDecNum s1 = (this)->AddCode(), s2(t.AddCode()); for (int i = 0; i <= SZ; i++) { if (s1.Num[i] + s2.Num[i] + dop < 10) { s1.Num[i] = s1.Num[i] + s2.Num[i] + dop; dop = 0; } else { s1.Num[i] = s1.Num[i] + s2.Num[i] + dop - 10; dop = 1; } } if ((dop > 0) && index && ((Num[SZ] != 0) || (t.Num[SZ] != 0))) throw std::invalid_argument("Overflow!"); if (!index) { if ((this)->Large(t)) { s1.Num[0] = Num[0]; } else if (t.Large(*this)) { s1.Num[0] = t.Num[0]; } else { s1.Num[0] = 0; s1.n = 1; return s1; } } else s1.Num[0] = Num[0]; s1 = s1.AddCode(); if (j < SZ) j += 1; for (int i = j; i > 0; i--) { if (s1.Num[i] != 0) { s1.n = i; break; } } return s1; } bigDecNum bigDecNum::Sub(bigDecNum t) const { bigDecNum s2 = t, s1 = *this; if (s2.Num[0] == 0) s2.Num[0] = 1; else s2.Num[0] = 0; s1 = s1.Sum(s2); return s1; } bigDecNum bigDecNum::Inc10() const { bigDecNum inc; inc.n = n + 1; if (n == 1 && Num[1] == 0) { inc.n = 1; return inc; } if (Num[SZ] != 0) throw std::invalid_argument("Overflow!"); inc.Num[0] = Num[0]; inc.Num[1] = 0; for (int i = n; i >= 1; i--) inc.Num[i + 1] = Num[i]; return inc; } bigDecNum bigDecNum::Dec10() const { bigDecNum inc; inc.n = n - 1; if (n == 1) { inc.n = 1; return inc; } inc.Num[0] = Num[0]; for (int i = n; i >= 2; i--) inc.Num[i - 1] = Num[i]; return inc; } bigDecNum bigDecNum::Input() const { const char* ptr = ""; std::string ss; std::cin >> ss; if (ss.std::string::length() > SZ + 1) throw std::invalid_argument("Overflow!"); ptr = ss.c_str(); std::cin.clear(); bigDecNum decNum(ptr); std::cout << std::endl; return decNum; } void bigDecNum::Print() const { if (Num[0] == 1) std::cout << "-"; bool k = false; if (n == 1) { if (Num[1] == 0) k = true; } if (k) std::cout << 0; if (n == 1 && Num[1] == 0) std::cout << 0; else { for (int i = n; i >= 1; i--) { int t = Num[i]; std::cout << t; } } std::cout << std::endl; } //для тестов int bigDecNum::ToInt() const { int i = 0; int pow = 1; if (n > 50) throw std::invalid_argument("Too many chars!"); for (int k = 1; k <= n; k++) { i += Num[k] * pow; pow *= 10; } i = Num[0] == 0 ? i : -i; return i; } /// dialog functions int dialog(const char* msgs[], int N) { std::string errmsg; int rc, n; do { std::cout << errmsg; errmsg = "You are wrong. Repeat, please\n"; for (int j = 0; j < N; ++j) puts(msgs[j]); puts("Make your choice: --> "); n = getInt(rc); if (n == 0) rc = 0; } while (rc < 0 || rc >= N); return rc; } int dialog_getAddCode(bigDecNum& f) { try { std::cout << "There is an add-code for your first num: "; f.AddCode().Print(); } catch (std::exception& ex) { std::cout << ex.what() << std::endl; } return 1; } int dialog_inc10(bigDecNum& f) { try { bigDecNum f1 = f.Inc10(); std::cout << "Received number: "; f1.Print(); std::cout << std::endl; } catch (const std::exception& msg) { std::cout << msg.what() << std::endl; } return 1; } int dialog_dec10(bigDecNum& f) { try { bigDecNum f1 = f.Dec10(); std::cout << "Received number: "; f1.Print(); std::cout << std::endl; } catch (const std::exception& msg) { std::cout << msg.what() << std::endl; } return 1; } /// }
[ "k151201@yandex.ru" ]
k151201@yandex.ru
9890d3a178eda9ed7d21fb9173a577d04c71417b
cdd954c874762b94828dac7c29f185804403b4b2
/RocketPlugin/buildmode/RocketScenePackager.h
584e0cc6fe475b6af799cd658b99a72f73842eae
[ "Apache-2.0" ]
permissive
Adminotech/meshmoon-plugins
cd2c898bcae0fbab796e9829c48754c81be4644a
32043ef783bdf137860d7d01eb22de564628e572
refs/heads/master
2021-01-13T00:44:55.012875
2016-03-07T14:58:03
2016-03-07T14:58:03
52,879,540
4
2
null
null
null
null
UTF-8
C++
false
false
8,573
h
/** @author Adminotech Ltd. Copyright Adminotech Ltd. All rights reserved. @file @brief */ #pragma once #include "RocketFwd.h" #include "FrameworkFwd.h" #include "SceneFwd.h" #include "CoreDefines.h" #include "qts3/QS3Fwd.h" #include "utils/RocketZipWorker.h" #include "IAttribute.h" #include "AssetAPI.h" #include "AssetReference.h" #include "ui_RocketSceneOptimizerWidget.h" #include <QObject> #include <QDir> #include <QTime> #include <QFileInfo> #include <QHash> class QFile; class EC_Mesh; class EC_Material; /// @cond PRIVATE class RocketScenePackager : public QObject { Q_OBJECT public: explicit RocketScenePackager(RocketPlugin *plugin); ~RocketScenePackager(); struct AssetFileInfo { AssetReference ref; QString bundleAssetRef; QString diskSourceAbsolutePath; QFileInfo diskSource; bool dontProcess; bool texturesProcessed; bool texturePostProcessed; AssetFileInfo(const QString &_ref, const QString &_type) : dontProcess(false), texturesProcessed(false), texturePostProcessed(false), ref(_ref, _type) { } void SetDiskSource(const QString absoluteDiskSource) { diskSourceAbsolutePath = absoluteDiskSource; diskSource = QFileInfo(diskSourceAbsolutePath); } }; struct TextureInfo { int iTech; int iPass; int iTexUnit; QString ref; TextureInfo() : iTech(-1), iPass(-1), iTexUnit(-1) {} }; typedef QList<TextureInfo> TextureList; struct TextureProcessing { bool process; QString convertToFormat; QString mipmapGeneration; uint rescaleMode; uint maxSize; uint maxMipmaps; uint quality; uint totalProcessed; uint totalConverted; uint totalResized; uint totalRescaled; QStringList supportedInputFormats; TextureProcessing() : process(false), mipmapGeneration("UseSource"), rescaleMode(0), maxSize(0), maxMipmaps(1), quality(255), totalProcessed(0), totalConverted(0), totalResized(0), totalRescaled(0) { } void Disable() { Reset(); } void Reset() { *this = TextureProcessing(); } bool IsEnabled() const { if (!process) return false; if (convertToFormat != "") return true; if (mipmapGeneration != "" && mipmapGeneration != "UseSource") return true; if (rescaleMode != 0) return true; if (maxSize != 0) return true; return false; } }; struct State { uint maxPackagerThreads; bool storageAuthenticated; bool waitingForAssetBundleUploads; bool bundleStorageUploadsOk; bool bundlesUploading; uint entitiesProcessed; uint entitiesEmptyRemoved; uint totalConvertedRefs; uint bundledMeshRefs; uint bundledMaterialRefs; uint bundledTextureRefs; uint bundledTextureGeneratedRefs; uint currentMeshBundleIndex; uint currentTextureBundleIndex; uint currentTextureGeneratedBundleIndex; qint64 totalFileSize; qint64 totalFileSizeMesh; qint64 totalFileSizeMat; qint64 totalFileSizeTex; qint64 totalFileSizeTexGen; qint64 nowFileSizeMesh; qint64 nowFileSizeTex; qint64 nowFileSizeTexGen; qint64 bundleSplitSize; qint64 filesCopied; uint foundMaxTexWidth; uint foundMaxTexHeight; bool processMeshes; bool processMaterials; bool processGeneratedMaterials; bool processScriptEnts; bool processContentToolsEnts; bool removeEmptyEntities; bool rewriteAssetReferences; QFile *logFile; bool logDebug; TextureProcessing texProcessing; QString txmlRef; QString txmlBaseUrl; QString txmlForcedBaseUrl; QString outputTxmlFile; QString bundlePrefix; QString textureTool; QDir outputDir; QList<AssetFileInfo*> assetsInfo; QHash<QString, QString> assetBaseToUuid; QSet<QString> rewriteUuidFilenames; QHash<QString, QString> oldToNewGeneraterMaterial; QList<RocketZipWorker*> packagers; QList<QPair<AttributeWeakPtr, QString> > changedAttributes; QSet<QString> optimizedAssetRefs; QTime time; State() : logFile(0), storageAuthenticated(false) { Reset(); } void Reset(); QFile *OpenLog(); }; public slots: void Show(); void Hide(); /// Returns if the tool is running. bool IsRunning() const; /// Returns if the tool is stopping. bool IsStopping() const; /// Requests the tool to be stopped, if the tool is running. /** This is not a synchronous operation, we need to stop processing tools etc. over a short period of time. Connect to Stopped signals to be notified. @note This will prompt a main window modal dialog to ask the user if he wants to stop, the result will be returned as a bool. @return True if user wanted to stop the packager, false otherwise. */ bool RequestStop(); QWidget *Widget() const; signals: void Started(); void Stopped(); private slots: void Start(); bool CheckStopping(); void AuthenticateStorate(); void BackupCompleted(QS3CopyObjectResponse *response); void Run(); void Stop(); void TryStartProcessing(); void Process(); void EnableInterface(bool enabled); void StorageAuthCompleted(); void StorageAuthCanceled(); void ReadConfig(); void SaveConfig(); void StartAssetBundleUploads(); void ReplicateChangesToServer(); RocketZipWorker *StartPackager(const QString &destinationFilePath, const QString &inputDirPath, RocketZipWorker::Compression compression = RocketZipWorker::Normal); uint RunningPackagers() const; uint PendingPackagers() const; void Log(const QString &message, bool logToConsole = false, bool errorChannel = false, bool warningChannel = false, const QString &color = QString(), bool logToFile = true); void LogProgress(const QString &action, int progress = -1, bool updateButton = false); void OnProcessTexturesChanged(); void OnProcessMipmapGenerationChanged(); void OnBrowseOutputDir(); void OnToggleLogDocking(); void OnPackagerThreadCompleted(); void OnAssetBundleUploadOperationProgress(QS3PutObjectResponse *response, qint64 completed, qint64 total, MeshmoonStorageOperationMonitor *operation); void OnAssetBundlesUploaded(MeshmoonStorageOperationMonitor *monitor); void ProcessGeneratedMaterial(Entity *ent, EC_Material *comp); void ProcessMeshRef(Entity *ent, EC_Mesh *comp); void ProcessMaterialRefs(Entity *ent, EC_Mesh *comp); void ProcessTextures(AssetFileInfo *materialAssetInfo, const TextureList &textures); RocketScenePackager::AssetFileInfo *GetOrCreateAssetFileInfo(const QString &ref, const QString &type, AssetAPI::AssetRefType refType, const QString &basePath, const QString &fileName, const QString &subAssetName); RocketScenePackager::AssetFileInfo *GetAssetFileInfo(const QString &ref); void TrimBaseStorageUrl(QString &ref); TextureList GetTextures(const QString &materialRef); void PostProcessTexture(AssetFileInfo *textureInfo, const QString &type); bool CreateOrClearWorkingDirectory(); bool ClearDirectoryWithConfirmation(const QDir &dir); void RemoveAllFilesRecursive(const QDir &dir, bool onlyTxmlFromRoot = true); protected: template <typename T> std::vector<T*> GetTargets(std::vector<shared_ptr<T> > candidates) const; bool eventFilter(QObject *obj, QEvent *e); private: RocketPlugin *plugin_; Framework *framework_; QString LC_; QString contentToolsDataCompName_; SceneWeakPtr scene_; State state_; bool running_; bool stopping_; QWidget *widget_; QWidget *logWindow_; Ui::RocketSceneOptimizerWidget ui_; }; /// @endcond
[ "jonne@adminotech.com" ]
jonne@adminotech.com
a56741b839854b815bc2c9af710b293492279984
41b4e949f031f189ac27f16cb45fc29801c1cebb
/frameworks/base/services/surfaceflinger/Layer.cpp
307ef5531dc183934df2fab827070be809e70e83
[ "Apache-2.0", "LicenseRef-scancode-unicode" ]
permissive
MeteorOS-project/android_gingerbread_inspiration
b9d498c79ace82c6dd1a0ec9f26aedca8e9804d5
80269edd6df74514e37d87cfabd3570123cd80f1
refs/heads/master
2023-05-23T04:42:55.879988
2015-02-22T06:14:57
2015-02-22T06:14:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
34,385
cpp
/* * Copyright (C) 2007 The Android Open Source Project * Copyright (C) 2010, Code Aurora Forum. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdlib.h> #include <stdint.h> #include <sys/types.h> #include <cutils/properties.h> #include <cutils/native_handle.h> #include <utils/Errors.h> #include <utils/Log.h> #include <utils/StopWatch.h> #include <ui/GraphicBuffer.h> #include <ui/PixelFormat.h> #include <surfaceflinger/Surface.h> #include "clz.h" #include "GLExtensions.h" #include "Layer.h" #include "SurfaceFlinger.h" #include "DisplayHardware/DisplayHardware.h" #if defined(TARGET_USES_OVERLAY) #include "overlayLib.h" #endif #define DEBUG_RESIZE 0 namespace android { template <typename T> inline T min(T a, T b) { return a<b ? a : b; } // --------------------------------------------------------------------------- Layer::Layer(SurfaceFlinger* flinger, DisplayID display, const sp<Client>& client) : LayerBaseClient(flinger, display, client), mGLExtensions(GLExtensions::getInstance()), mNeedsBlending(true), mNeedsDithering(false), mSecure(false), mTextureManager(), mBufferManager(mTextureManager), mWidth(0), mHeight(0), mNeedsScaling(false), mFixedSize(false), mBypassState(false) { } Layer::~Layer() { // FIXME: must be called from the main UI thread EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay()); mBufferManager.destroy(dpy); // we can use getUserClientUnsafe here because we know we're // single-threaded at that point. sp<UserClient> ourClient(mUserClientRef.getUserClientUnsafe()); if (ourClient != 0) { ourClient->detachLayer(this); } if(getStereoscopic3DFormat()) { const DisplayHardware& hw(mFlinger->graphicPlane(0).displayHardware()); hw.videoOverlayStarted(false); mFlinger->enableOverlayOpt(true); } } status_t Layer::setToken(const sp<UserClient>& userClient, SharedClient* sharedClient, int32_t token) { int numbuffers = mBufferManager.getDefaultBufferCount(); #if defined(SF_BYPASS) if (getLayerInitFlags() & ISurfaceComposer::eFullScreen) { numbuffers = 3; mBufferManager.resize(numbuffers); } #endif sp<SharedBufferServer> lcblk = new SharedBufferServer( sharedClient, token, numbuffers, getIdentity()); status_t err = mUserClientRef.setToken(userClient, lcblk, token); LOGE_IF(err != NO_ERROR, "ClientRef::setToken(%p, %p, %u) failed", userClient.get(), lcblk.get(), token); if (err == NO_ERROR) { // we need to free the buffers associated with this surface } return err; } int32_t Layer::getToken() const { return mUserClientRef.getToken(); } sp<UserClient> Layer::getClient() const { return mUserClientRef.getClient(); } // called with SurfaceFlinger::mStateLock as soon as the layer is entered // in the purgatory list void Layer::onRemoved() { ClientRef::Access sharedClient(mUserClientRef); SharedBufferServer* lcblk(sharedClient.get()); if (lcblk) { // wake up the condition lcblk->setStatus(NO_INIT); } // If original resolution surface, close current VG channels. // Notify gralloc of the end of current playback. if(getUseOriginalSurfaceResolution()) { const DisplayHardware& hw(graphicPlane(0).displayHardware()); hw.stopOrigResDisplay(); freeBypassBuffers(); } } sp<LayerBaseClient::Surface> Layer::createSurface() const { return mSurface; } status_t Layer::ditch() { // NOTE: Called from the main UI thread // the layer is not on screen anymore. free as much resources as possible mFreezeLock.clear(); EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay()); mBufferManager.destroy(dpy); mSurface.clear(); Mutex::Autolock _l(mLock); mWidth = mHeight = 0; return NO_ERROR; } status_t Layer::setBuffers( uint32_t w, uint32_t h, PixelFormat format, uint32_t flags) { // this surfaces pixel format PixelFormatInfo info; status_t err = getPixelFormatInfo(format, &info); if (err) return err; // the display's pixel format const DisplayHardware& hw(graphicPlane(0).displayHardware()); uint32_t const maxSurfaceDims = min( hw.getMaxTextureSize(), hw.getMaxViewportDims()); // never allow a surface larger than what our underlying GL implementation // can handle. if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) { return BAD_VALUE; } PixelFormatInfo displayInfo; getPixelFormatInfo(hw.getFormat(), &displayInfo); const uint32_t hwFlags = hw.getFlags(); mFormat = format; mWidth = w; mHeight = h; mReqFormat = format; mReqWidth = w; mReqHeight = h; mSecure = (flags & ISurfaceComposer::eSecure) ? true : false; mNeedsBlending = (info.h_alpha - info.l_alpha) > 0; // we use the red index int displayRedSize = displayInfo.getSize(PixelFormatInfo::INDEX_RED); int layerRedsize = info.getSize(PixelFormatInfo::INDEX_RED); mNeedsDithering = layerRedsize > displayRedSize; mSurface = new SurfaceLayer(mFlinger, this); return NO_ERROR; } void Layer::reloadTexture(const Region& dirty) { sp<GraphicBuffer> buffer(mBufferManager.getActiveBuffer()); if (buffer == NULL) { // this situation can happen if we ran out of memory for instance. // not much we can do. continue to use whatever texture was bound // to this context. return; } if (mGLExtensions.haveDirectTexture()) { EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay()); if (mBufferManager.initEglImage(dpy, buffer) != NO_ERROR) { // not sure what we can do here... goto slowpath; } } else { slowpath: GGLSurface t; if (buffer->usage & GRALLOC_USAGE_SW_READ_MASK) { status_t res = buffer->lock(&t, GRALLOC_USAGE_SW_READ_OFTEN); LOGE_IF(res, "error %d (%s) locking buffer %p", res, strerror(res), buffer.get()); if (res == NO_ERROR) { mBufferManager.loadTexture(dirty, t); buffer->unlock(); } } else { // we can't do anything } } } void Layer::drawForSreenShot() const { const bool currentFiltering = mNeedsFiltering; const_cast<Layer*>(this)->mNeedsFiltering = true; LayerBase::drawForSreenShot(); const_cast<Layer*>(this)->mNeedsFiltering = currentFiltering; } status_t Layer::freeBypassBuffers() const { if (!isOverlayUsed()) return NO_ERROR; ClientRef::Access sharedClient(mUserClientRef); SharedBufferServer* lcblk(sharedClient.get()); if (lcblk) lcblk->setInUseBypass(-1); setOverlayUsed(false); return NO_ERROR; } status_t Layer::freeBypassBuffers(bool clearOverlayFlag) const { if (!isOverlayUsed()) return NO_ERROR; ClientRef::Access sharedClient(mUserClientRef); SharedBufferServer* lcblk(sharedClient.get()); if (lcblk) lcblk->setInUseBypass(-1); if (clearOverlayFlag) setOverlayUsed(false); return NO_ERROR; } status_t Layer::setBufferInUse() const { Texture tex(mBufferManager.getActiveTexture()); if (tex.image == EGL_NO_IMAGE_KHR) return INVALID_OPERATION; GLuint textureName = tex.name; if (UNLIKELY(textureName == -1LU)) { return INVALID_OPERATION; } ClientRef::Access sharedClient(mUserClientRef); SharedBufferServer* lcblk(sharedClient.get()); if (lcblk) { int buf = mBufferManager.getActiveBufferIndex(); if (buf >= 0) lcblk->setInUseBypass(buf); } return NO_ERROR; } status_t Layer::drawWithOverlay(const Region& clip, bool hdmiConnected, bool ignoreFB) const { #if defined(TARGET_USES_OVERLAY) Texture tex(mBufferManager.getActiveTexture()); if (tex.image == EGL_NO_IMAGE_KHR) return INVALID_OPERATION; GLuint textureName = tex.name; if (UNLIKELY(textureName == -1LU)) { return INVALID_OPERATION; } const DisplayHardware& hw(graphicPlane(0).displayHardware()); if(getUseOriginalSurfaceResolution()){ sp<GraphicBuffer> buffer(mBufferManager.getActiveBuffer()); buffer_handle_t handle = (buffer->getNativeBuffer())->handle; hw.postOrigResBuffer(handle, mWidth, mHeight, mFormat, getOrientation()); setOverlayUsed(true); setBufferInUse(); return NO_ERROR; } overlay::Overlay* temp = hw.getOverlayObject(); int s3dFormat = getStereoscopic3DFormat(); if (s3dFormat) { hw.videoOverlayStarted(true); } if (!temp->setSource(mWidth, mHeight, mFormat|s3dFormat, getOrientation(), hdmiConnected, ignoreFB, mBufferManager.getNumBuffers())) return INVALID_OPERATION; if ((s3dFormat) && !temp->setCrop(0, 0, mWidth, mHeight)) return INVALID_OPERATION; const Rect bounds(mTransformedBounds); int x = bounds.left; int y = bounds.top; int w = bounds.width(); int h = bounds.height(); int ovpos_x, ovpos_y; uint32_t ovpos_w, ovpos_h; bool ret; if (ret = temp->getPosition(ovpos_x, ovpos_y, ovpos_w, ovpos_h)) { if ((ovpos_x != x) || (ovpos_y != y) || (ovpos_w != w) || (ovpos_h != h)) { ret = temp->setPosition(x, y, w, h); } } else ret = temp->setPosition(x, y, w, h); if (!ret) return INVALID_OPERATION; int orientation; if (ret = temp->getOrientation(orientation)) { if (orientation != getOrientation()) ret = temp->setParameter(OVERLAY_TRANSFORM, getOrientation()); } else ret = temp->setParameter(OVERLAY_TRANSFORM, getOrientation()); if (!ret) return INVALID_OPERATION; sp<GraphicBuffer> buffer(mBufferManager.getActiveBuffer()); buffer_handle_t handle = (buffer->getNativeBuffer())->handle; ret = temp->queueBuffer(handle); if (!ret) return INVALID_OPERATION; if (!ignoreFB) clearWithOpenGL(clip); setOverlayUsed(true); return NO_ERROR; #endif return INVALID_OPERATION; } void Layer::onDraw(const Region& clip) const { Texture tex(mBufferManager.getActiveTexture()); if (tex.name == -1LU) { // the texture has not been created yet, this Layer has // in fact never been drawn into. This happens frequently with // SurfaceView because the WindowManager can't know when the client // has drawn the first time. // If there is nothing under us, we paint the screen in black, otherwise // we just skip this update. // figure out if there is something below us Region under; const SurfaceFlinger::LayerVector& drawingLayers(mFlinger->mDrawingState.layersSortedByZ); const size_t count = drawingLayers.size(); for (size_t i=0 ; i<count ; ++i) { const sp<LayerBase>& layer(drawingLayers[i]); if (layer.get() == static_cast<LayerBase const*>(this)) break; under.orSelf(layer->visibleRegionScreen); } // if not everything below us is covered, we plug the holes! Region holes(clip.subtract(under)); if (!holes.isEmpty()) { clearWithOpenGL(holes, 0, 0, 0, 1); } return; } drawWithOpenGL(clip, tex); const DisplayHardware& hw(mFlinger->graphicPlane(0).displayHardware()); if(hw.getDumpframe()){ const_cast<DumpFrame&>(mDumpFrame).dump(this, clip); } } bool Layer::needsFiltering() const { if (!(mFlags & DisplayHardware::SLOW_CONFIG)) { // if our buffer is not the same size than ourselves, // we need filtering. Mutex::Autolock _l(mLock); if (mNeedsScaling) return true; } return LayerBase::needsFiltering(); } status_t Layer::setBufferCount(int bufferCount) { ClientRef::Access sharedClient(mUserClientRef); SharedBufferServer* lcblk(sharedClient.get()); if (!lcblk) { // oops, the client is already gone return DEAD_OBJECT; } // NOTE: lcblk->resize() is protected by an internal lock status_t err = lcblk->resize(bufferCount); if (err == NO_ERROR) mBufferManager.resize(bufferCount); return err; } sp<GraphicBuffer> Layer::requestBuffer(int index, uint32_t reqWidth, uint32_t reqHeight, uint32_t reqFormat, uint32_t usage) { sp<GraphicBuffer> buffer; if (int32_t(reqWidth | reqHeight | reqFormat) < 0) return buffer; if ((!reqWidth && reqHeight) || (reqWidth && !reqHeight)) return buffer; // this ensures our client doesn't go away while we're accessing // the shared area. ClientRef::Access sharedClient(mUserClientRef); SharedBufferServer* lcblk(sharedClient.get()); if (!lcblk) { // oops, the client is already gone return buffer; } /* * This is called from the client's Surface::dequeue(). This can happen * at any time, especially while we're in the middle of using the * buffer 'index' as our front buffer. */ uint32_t w, h, f, bypass; { // scope for the lock Mutex::Autolock _l(mLock); bypass = mBypassState; // zero means default mFixedSize = reqWidth && reqHeight; if (!reqFormat) reqFormat = mFormat; if (!reqWidth) reqWidth = mWidth; if (!reqHeight) reqHeight = mHeight; w = reqWidth; h = reqHeight; f = reqFormat; if ((reqWidth != mReqWidth) || (reqHeight != mReqHeight) || (reqFormat != mReqFormat)) { mReqWidth = reqWidth; mReqHeight = reqHeight; mReqFormat = reqFormat; mNeedsScaling = mWidth != mReqWidth || mHeight != mReqHeight; lcblk->reallocateAllExcept(index); } } // here we have to reallocate a new buffer because the buffer could be // used as the front buffer, or by a client in our process // (eg: status bar), and we can't release the handle under its feet. uint32_t effectiveUsage = getEffectiveUsage(usage); status_t err = NO_MEMORY; if (err != NO_ERROR) { buffer = new GraphicBuffer(w, h, f, effectiveUsage); err = buffer->initCheck(); } if (err || buffer->handle == 0) { GraphicBuffer::dumpAllocationsToSystemLog(); LOGE_IF(err || buffer->handle == 0, "Layer::requestBuffer(this=%p), index=%d, w=%d, h=%d failed (%s)", this, index, w, h, strerror(-err)); } else { LOGD_IF(DEBUG_RESIZE, "Layer::requestBuffer(this=%p), index=%d, w=%d, h=%d, handle=%p", this, index, w, h, buffer->handle); } if (err == NO_ERROR && buffer->handle != 0) { Mutex::Autolock _l(mLock); mBufferManager.attachBuffer(index, buffer); } return buffer; } uint32_t Layer::getEffectiveUsage(uint32_t usage) const { /* * buffers used for software rendering, but h/w composition * are allocated with SW_READ_OFTEN | SW_WRITE_OFTEN | HW_TEXTURE * * buffers used for h/w rendering and h/w composition * are allocated with HW_RENDER | HW_TEXTURE * * buffers used with h/w rendering and either NPOT or no egl_image_ext * are allocated with SW_READ_RARELY | HW_RENDER * */ if (mSecure) { // secure buffer, don't store it into the GPU usage = GraphicBuffer::USAGE_SW_READ_OFTEN | GraphicBuffer::USAGE_SW_WRITE_OFTEN; } else { // it's allowed to modify the usage flags here, but generally // the requested flags should be honored. // request EGLImage for all buffers usage |= GraphicBuffer::USAGE_HW_TEXTURE; } return usage; } bool Layer::setBypass(bool enable) { #if defined(SF_BYPASS) const DisplayHardware& hw(mFlinger->graphicPlane(0).displayHardware()); if (!hw.isOverlayUIEnabled() || getStereoscopic3DFormat() || getUseOriginalSurfaceResolution()) return false; Mutex::Autolock _l(mLock); if (mNeedsScaling || mNeedsFiltering) { return false; } if (mBufferManager.getNumBuffers() <= mBufferManager.getDefaultBufferCount()) return false; if (mBypassState != enable) { mBypassState = enable; ClientRef::Access sharedClient(mUserClientRef); SharedBufferServer* lcblk(sharedClient.get()); if (lcblk && enable) { // all buffers need reallocation lcblk->reallocateAll(); } } return true; #endif return false; } void Layer::updateBuffersOrientation() { sp<GraphicBuffer> buffer(getBypassBuffer()); if (buffer != NULL && mOrientation != buffer->transform) { ClientRef::Access sharedClient(mUserClientRef); SharedBufferServer* lcblk(sharedClient.get()); if (lcblk) { // all buffers need reallocation lcblk->reallocateAll(); } } } uint32_t Layer::doTransaction(uint32_t flags) { const Layer::State& front(drawingState()); const Layer::State& temp(currentState()); const bool sizeChanged = (front.requested_w != temp.requested_w) || (front.requested_h != temp.requested_h); if (sizeChanged) { // the size changed, we need to ask our client to request a new buffer LOGD_IF(DEBUG_RESIZE, "resize (layer=%p), requested (%dx%d), drawing (%d,%d)", this, int(temp.requested_w), int(temp.requested_h), int(front.requested_w), int(front.requested_h)); if (!isFixedSize()) { // we're being resized and there is a freeze display request, // acquire a freeze lock, so that the screen stays put // until we've redrawn at the new size; this is to avoid // glitches upon orientation changes. if (mFlinger->hasFreezeRequest()) { // if the surface is hidden, don't try to acquire the // freeze lock, since hidden surfaces may never redraw if (!(front.flags & ISurfaceComposer::eLayerHidden)) { mFreezeLock = mFlinger->getFreezeLock(); } } // this will make sure LayerBase::doTransaction doesn't update // the drawing state's size Layer::State& editDraw(mDrawingState); editDraw.requested_w = temp.requested_w; editDraw.requested_h = temp.requested_h; // record the new size, form this point on, when the client request // a buffer, it'll get the new size. setBufferSize(temp.requested_w, temp.requested_h); ClientRef::Access sharedClient(mUserClientRef); SharedBufferServer* lcblk(sharedClient.get()); if (lcblk) { // all buffers need reallocation lcblk->reallocateAll(); } } else { // record the new size setBufferSize(temp.requested_w, temp.requested_h); } } if (temp.sequence != front.sequence) { if (temp.flags & ISurfaceComposer::eLayerHidden || temp.alpha == 0) { // this surface is now hidden, so it shouldn't hold a freeze lock // (it may never redraw, which is fine if it is hidden) mFreezeLock.clear(); } } return LayerBase::doTransaction(flags); } void Layer::setBufferSize(uint32_t w, uint32_t h) { Mutex::Autolock _l(mLock); mWidth = w; mHeight = h; mNeedsScaling = mWidth != mReqWidth || mHeight != mReqHeight; } bool Layer::isFixedSize() const { Mutex::Autolock _l(mLock); return mFixedSize; } // ---------------------------------------------------------------------------- // pageflip handling... // ---------------------------------------------------------------------------- void Layer::lockPageFlip(bool& recomputeVisibleRegions) { ClientRef::Access sharedClient(mUserClientRef); SharedBufferServer* lcblk(sharedClient.get()); if (!lcblk) { // client died recomputeVisibleRegions = true; return; } ssize_t buf = lcblk->retireAndLock(); mNothingToUpdate = false; if (buf == NOT_ENOUGH_DATA) { // NOTE: This is not an error, it simply means there is nothing to // retire. The buffer is locked because we will use it // for composition later in the loop mNothingToUpdate = true; return; } if (buf < NO_ERROR) { LOGE("retireAndLock() buffer index (%d) out of range", int(buf)); mPostedDirtyRegion.clear(); return; } // we retired a buffer, which becomes the new front buffer if (mBufferManager.setActiveBufferIndex(buf) < NO_ERROR) { LOGE("retireAndLock() buffer index (%d) out of range", int(buf)); mPostedDirtyRegion.clear(); return; } sp<GraphicBuffer> newFrontBuffer(getBuffer(buf)); if (newFrontBuffer != NULL) { // get the dirty region // compute the posted region const Region dirty(lcblk->getDirtyRegion(buf)); mPostedDirtyRegion = dirty.intersect( newFrontBuffer->getBounds() ); // update the layer size and release freeze-lock const Layer::State& front(drawingState()); if (newFrontBuffer->getWidth() == front.requested_w && newFrontBuffer->getHeight() == front.requested_h) { if ((front.w != front.requested_w) || (front.h != front.requested_h)) { // Here we pretend the transaction happened by updating the // current and drawing states. Drawing state is only accessed // in this thread, no need to have it locked Layer::State& editDraw(mDrawingState); editDraw.w = editDraw.requested_w; editDraw.h = editDraw.requested_h; // We also need to update the current state so that we don't // end-up doing too much work during the next transaction. // NOTE: We actually don't need hold the transaction lock here // because State::w and State::h are only accessed from // this thread Layer::State& editTemp(currentState()); editTemp.w = editDraw.w; editTemp.h = editDraw.h; // recompute visible region recomputeVisibleRegions = true; } // we now have the correct size, unfreeze the screen mFreezeLock.clear(); } // get the crop region setBufferCrop( lcblk->getCrop(buf) ); // get the transformation setBufferTransform( lcblk->getTransform(buf) ); } else { // this should not happen unless we ran out of memory while // allocating the buffer. we're hoping that things will get back // to normal the next time the app tries to draw into this buffer. // meanwhile, pretend the screen didn't update. mPostedDirtyRegion.clear(); } if (lcblk->getQueuedCount()) { // signal an event if we have more buffers waiting mFlinger->signalEvent(); } /* a buffer was posted, so we need to call reloadTexture(), which * will update our internal data structures (eg: EGLImageKHR or * texture names). we need to do this even if mPostedDirtyRegion is * empty -- it's orthogonal to the fact that a new buffer was posted, * for instance, a degenerate case could be that the user did an empty * update but repainted the buffer with appropriate content (after a * resize for instance). */ reloadTexture( mPostedDirtyRegion ); } void Layer::unlockPageFlip( const Transform& planeTransform, Region& outDirtyRegion) { Region dirtyRegion(mPostedDirtyRegion); if (!dirtyRegion.isEmpty()) { mPostedDirtyRegion.clear(); // The dirty region is given in the layer's coordinate space // transform the dirty region by the surface's transformation // and the global transformation. const Layer::State& s(drawingState()); const Transform tr(planeTransform * s.transform); dirtyRegion = tr.transform(dirtyRegion); // At this point, the dirty region is in screen space. // Make sure it's constrained by the visible region (which // is in screen space as well). dirtyRegion.andSelf(visibleRegionScreen); outDirtyRegion.orSelf(dirtyRegion); } if (visibleRegionScreen.isEmpty()) { // an invisible layer should not hold a freeze-lock // (because it may never be updated and therefore never release it) mFreezeLock.clear(); } } void Layer::dump(String8& result, char* buffer, size_t SIZE) const { LayerBaseClient::dump(result, buffer, SIZE); ClientRef::Access sharedClient(mUserClientRef); SharedBufferServer* lcblk(sharedClient.get()); uint32_t totalTime = 0; if (lcblk) { SharedBufferStack::Statistics stats = lcblk->getStats(); totalTime= stats.totalTime; result.append( lcblk->dump(" ") ); } sp<const GraphicBuffer> buf0(getBuffer(0)); sp<const GraphicBuffer> buf1(getBuffer(1)); uint32_t w0=0, h0=0, s0=0; uint32_t w1=0, h1=0, s1=0; if (buf0 != 0) { w0 = buf0->getWidth(); h0 = buf0->getHeight(); s0 = buf0->getStride(); } if (buf1 != 0) { w1 = buf1->getWidth(); h1 = buf1->getHeight(); s1 = buf1->getStride(); } snprintf(buffer, SIZE, " " "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u]," " freezeLock=%p, bypass=%d, dq-q-time=%u us\n", mFormat, w0, h0, s0, w1, h1, s1, getFreezeLock().get(), mBypassState, totalTime); result.append(buffer); } // --------------------------------------------------------------------------- Layer::ClientRef::ClientRef() : mControlBlock(0), mToken(-1) { } Layer::ClientRef::~ClientRef() { } int32_t Layer::ClientRef::getToken() const { Mutex::Autolock _l(mLock); return mToken; } sp<UserClient> Layer::ClientRef::getClient() const { Mutex::Autolock _l(mLock); return mUserClient.promote(); } status_t Layer::ClientRef::setToken(const sp<UserClient>& uc, const sp<SharedBufferServer>& sharedClient, int32_t token) { Mutex::Autolock _l(mLock); { // scope for strong mUserClient reference sp<UserClient> userClient(mUserClient.promote()); if (mUserClient != 0 && mControlBlock != 0) { mControlBlock->setStatus(NO_INIT); } } mUserClient = uc; mToken = token; mControlBlock = sharedClient; return NO_ERROR; } sp<UserClient> Layer::ClientRef::getUserClientUnsafe() const { return mUserClient.promote(); } // this class gives us access to SharedBufferServer safely // it makes sure the UserClient (and its associated shared memory) // won't go away while we're accessing it. Layer::ClientRef::Access::Access(const ClientRef& ref) : mControlBlock(0) { Mutex::Autolock _l(ref.mLock); mUserClientStrongRef = ref.mUserClient.promote(); if (mUserClientStrongRef != 0) mControlBlock = ref.mControlBlock; } Layer::ClientRef::Access::~Access() { } // --------------------------------------------------------------------------- Layer::BufferManager::BufferManager(TextureManager& tm) : mNumBuffers(NUM_BUFFERS), mTextureManager(tm), mActiveBuffer(-1), mFailover(false) { } Layer::BufferManager::~BufferManager() { } status_t Layer::BufferManager::resize(size_t size) { Mutex::Autolock _l(mLock); mNumBuffers = size; return NO_ERROR; } // only for debugging sp<GraphicBuffer> Layer::BufferManager::getBuffer(size_t index) const { return mBufferData[index].buffer; } status_t Layer::BufferManager::setActiveBufferIndex(size_t index) { mActiveBuffer = index; return NO_ERROR; } size_t Layer::BufferManager::getActiveBufferIndex() const { return mActiveBuffer; } Texture Layer::BufferManager::getActiveTexture() const { Texture res; if (mFailover || mActiveBuffer<0) { res = mFailoverTexture; } else { static_cast<Image&>(res) = mBufferData[mActiveBuffer].texture; } return res; } sp<GraphicBuffer> Layer::BufferManager::getActiveBuffer() const { sp<GraphicBuffer> result; const ssize_t activeBuffer = mActiveBuffer; if (activeBuffer >= 0) { BufferData const * const buffers = mBufferData; Mutex::Autolock _l(mLock); result = buffers[activeBuffer].buffer; } return result; } sp<GraphicBuffer> Layer::BufferManager::detachBuffer(size_t index) { BufferData* const buffers = mBufferData; sp<GraphicBuffer> buffer; Mutex::Autolock _l(mLock); buffer = buffers[index].buffer; buffers[index].buffer = 0; return buffer; } status_t Layer::BufferManager::attachBuffer(size_t index, const sp<GraphicBuffer>& buffer) { BufferData* const buffers = mBufferData; Mutex::Autolock _l(mLock); buffers[index].buffer = buffer; buffers[index].texture.dirty = true; return NO_ERROR; } status_t Layer::BufferManager::destroy(EGLDisplay dpy) { BufferData* const buffers = mBufferData; size_t num; { // scope for the lock Mutex::Autolock _l(mLock); num = mNumBuffers; for (size_t i=0 ; i<num ; i++) { buffers[i].buffer = 0; } } for (size_t i=0 ; i<num ; i++) { destroyTexture(&buffers[i].texture, dpy); } destroyTexture(&mFailoverTexture, dpy); return NO_ERROR; } status_t Layer::BufferManager::initEglImage(EGLDisplay dpy, const sp<GraphicBuffer>& buffer) { status_t err = NO_INIT; ssize_t index = mActiveBuffer; if (index >= 0) { if (!mFailover) { { // Without that lock, there is a chance of race condition // where while composing a specific index, requestBuf // with the same index can be executed and touch the same data // that is being used in initEglImage. // (e.g. dirty flag in texture) Mutex::Autolock _l(mLock); Image& texture(mBufferData[index].texture); err = mTextureManager.initEglImage(&texture, dpy, buffer); } // if EGLImage fails, we switch to regular texture mode, and we // free all resources associated with using EGLImages. if (err == NO_ERROR) { mFailover = false; destroyTexture(&mFailoverTexture, dpy); } else { mFailover = true; const size_t num = mNumBuffers; for (size_t i=0 ; i<num ; i++) { destroyTexture(&mBufferData[i].texture, dpy); } } } else { // we failed once, don't try again err = BAD_VALUE; } } return err; } status_t Layer::BufferManager::loadTexture( const Region& dirty, const GGLSurface& t) { return mTextureManager.loadTexture(&mFailoverTexture, dirty, t); } status_t Layer::BufferManager::destroyTexture(Image* tex, EGLDisplay dpy) { if (tex->name != -1U) { glDeleteTextures(1, &tex->name); tex->name = -1U; } if (tex->image != EGL_NO_IMAGE_KHR) { eglDestroyImageKHR(dpy, tex->image); tex->image = EGL_NO_IMAGE_KHR; } return NO_ERROR; } // --------------------------------------------------------------------------- Layer::SurfaceLayer::SurfaceLayer(const sp<SurfaceFlinger>& flinger, const sp<Layer>& owner) : Surface(flinger, owner->getIdentity(), owner) { } Layer::SurfaceLayer::~SurfaceLayer() { } sp<GraphicBuffer> Layer::SurfaceLayer::requestBuffer(int index, uint32_t w, uint32_t h, uint32_t format, uint32_t usage) { sp<GraphicBuffer> buffer; sp<Layer> owner(getOwner()); if (owner != 0) { /* * requestBuffer() cannot be called from the main thread * as it could cause a dead-lock, since it may have to wait * on conditions updated my the main thread. */ buffer = owner->requestBuffer(index, w, h, format, usage); } return buffer; } status_t Layer::SurfaceLayer::setBufferCount(int bufferCount) { status_t err = DEAD_OBJECT; sp<Layer> owner(getOwner()); if (owner != 0) { /* * setBufferCount() cannot be called from the main thread * as it could cause a dead-lock, since it may have to wait * on conditions updated my the main thread. */ err = owner->setBufferCount(bufferCount); } return err; } status_t Layer::SurfaceLayer::setStereoscopic3DFormat(int format) { sp<Layer> owner(getOwner()); if (owner != 0) { owner->setStereoscopic3DFormat(format); } return 0; } status_t Layer::SurfaceLayer::useOriginalSurfaceResolution(bool flag) { sp<Layer> owner(getOwner()); if (LIKELY(owner != 0)) { owner->useOriginalSurfaceResolution(flag); const DisplayHardware& hw(owner->graphicPlane(0).displayHardware()); hw.startOrigResDisplay(); } return 0; } // --------------------------------------------------------------------------- }; // namespace android
[ "xdtianyu@gmail.com" ]
xdtianyu@gmail.com
d9a2ff812cfdef3b3287f75d7ecc730bb1b54808
5e4a548b4531f68eb55af8804b3fe12499195179
/frameworks/base/core/jni/android_hardware_camera2_legacy_LegacyCameraDevice.cpp
d349f3881bf7c47bd1e10854e0dbdbf724559eab
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
ytjojo/Framwork8.1
41f9264e0023377646b116d9635fc81440f8cf6a
564fb59e980c1e41d5b07ecdd29dac7f3ae90e58
refs/heads/master
2020-03-23T09:03:04.962984
2017-10-28T06:40:48
2017-10-28T06:40:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,418
cpp
/* * Copyright (C) 2014 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. */ #define LOG_TAG "Legacy-CameraDevice-JNI" // #define LOG_NDEBUG 0 #include <utils/Log.h> #include <utils/Errors.h> #include <utils/Trace.h> #include <camera/CameraUtils.h> #include "jni.h" #include <nativehelper/JNIHelp.h> #include "core_jni_helpers.h" #include "android_runtime/android_view_Surface.h" #include "android_runtime/android_graphics_SurfaceTexture.h" #include <gui/Surface.h> #include <gui/IGraphicBufferProducer.h> #include <gui/IProducerListener.h> #include <ui/GraphicBuffer.h> #include <system/window.h> #include <hardware/camera3.h> #include <system/camera_metadata.h> #include <stdint.h> #include <inttypes.h> using namespace android; // fully-qualified class name #define CAMERA_DEVICE_CLASS_NAME "android/hardware/camera2/legacy/LegacyCameraDevice" #define CAMERA_DEVICE_BUFFER_SLACK 3 #define DONT_CARE 0 #define ARRAY_SIZE(a) (sizeof(a)/sizeof(*(a))) #define ALIGN(x, mask) ( ((x) + (mask) - 1) & ~((mask) - 1) ) /** * Convert from RGB 888 to Y'CbCr using the conversion specified in JFIF v1.02 */ static void rgbToYuv420(uint8_t* rgbBuf, size_t width, size_t height, uint8_t* yPlane, uint8_t* crPlane, uint8_t* cbPlane, size_t chromaStep, size_t yStride, size_t chromaStride) { uint8_t R, G, B; size_t index = 0; for (size_t j = 0; j < height; j++) { uint8_t* cr = crPlane; uint8_t* cb = cbPlane; uint8_t* y = yPlane; bool jEven = (j & 1) == 0; for (size_t i = 0; i < width; i++) { R = rgbBuf[index++]; G = rgbBuf[index++]; B = rgbBuf[index++]; *y++ = (77 * R + 150 * G + 29 * B) >> 8; if (jEven && (i & 1) == 0) { *cb = (( -43 * R - 85 * G + 128 * B) >> 8) + 128; *cr = (( 128 * R - 107 * G - 21 * B) >> 8) + 128; cr += chromaStep; cb += chromaStep; } // Skip alpha index++; } yPlane += yStride; if (jEven) { crPlane += chromaStride; cbPlane += chromaStride; } } } static void rgbToYuv420(uint8_t* rgbBuf, size_t width, size_t height, android_ycbcr* ycbcr) { size_t cStep = ycbcr->chroma_step; size_t cStride = ycbcr->cstride; size_t yStride = ycbcr->ystride; ALOGV("%s: yStride is: %zu, cStride is: %zu, cStep is: %zu", __FUNCTION__, yStride, cStride, cStep); rgbToYuv420(rgbBuf, width, height, reinterpret_cast<uint8_t*>(ycbcr->y), reinterpret_cast<uint8_t*>(ycbcr->cr), reinterpret_cast<uint8_t*>(ycbcr->cb), cStep, yStride, cStride); } static status_t connectSurface(const sp<Surface>& surface, int32_t maxBufferSlack) { status_t err = NO_ERROR; err = surface->connect(NATIVE_WINDOW_API_CAMERA, /*listener*/NULL); if (err != OK) { ALOGE("%s: Unable to connect to surface, error %s (%d).", __FUNCTION__, strerror(-err), err); return err; } err = native_window_set_usage(surface.get(), GRALLOC_USAGE_SW_WRITE_OFTEN); if (err != NO_ERROR) { ALOGE("%s: Failed to set native window usage flag, error %s (%d).", __FUNCTION__, strerror(-err), err); return err; } int minUndequeuedBuffers; err = static_cast<ANativeWindow*>(surface.get())->query(surface.get(), NATIVE_WINDOW_MIN_UNDEQUEUED_BUFFERS, &minUndequeuedBuffers); if (err != NO_ERROR) { ALOGE("%s: Failed to get native window min undequeued buffers, error %s (%d).", __FUNCTION__, strerror(-err), err); return err; } ALOGV("%s: Setting buffer count to %d", __FUNCTION__, maxBufferSlack + 1 + minUndequeuedBuffers); err = native_window_set_buffer_count(surface.get(), maxBufferSlack + 1 + minUndequeuedBuffers); if (err != NO_ERROR) { ALOGE("%s: Failed to set native window buffer count, error %s (%d).", __FUNCTION__, strerror(-err), err); return err; } return NO_ERROR; } /** * Produce a frame in the given surface. * * Args: * anw - a surface to produce a frame in. * pixelBuffer - image buffer to generate a frame from. * width - width of the pixelBuffer in pixels. * height - height of the pixelBuffer in pixels. * pixelFmt - format of the pixelBuffer, one of: * HAL_PIXEL_FORMAT_YCrCb_420_SP, * HAL_PIXEL_FORMAT_YCbCr_420_888, * HAL_PIXEL_FORMAT_BLOB * bufSize - the size of the pixelBuffer in bytes. */ static status_t produceFrame(const sp<ANativeWindow>& anw, uint8_t* pixelBuffer, int32_t bufWidth, // Width of the pixelBuffer int32_t bufHeight, // Height of the pixelBuffer int32_t pixelFmt, // Format of the pixelBuffer int32_t bufSize) { ATRACE_CALL(); status_t err = NO_ERROR; ANativeWindowBuffer* anb; ALOGV("%s: Dequeue buffer from %p %dx%d (fmt=%x, size=%x)", __FUNCTION__, anw.get(), bufWidth, bufHeight, pixelFmt, bufSize); if (anw == 0) { ALOGE("%s: anw must not be NULL", __FUNCTION__); return BAD_VALUE; } else if (pixelBuffer == NULL) { ALOGE("%s: pixelBuffer must not be NULL", __FUNCTION__); return BAD_VALUE; } else if (bufWidth < 0) { ALOGE("%s: width must be non-negative", __FUNCTION__); return BAD_VALUE; } else if (bufHeight < 0) { ALOGE("%s: height must be non-negative", __FUNCTION__); return BAD_VALUE; } else if (bufSize < 0) { ALOGE("%s: bufSize must be non-negative", __FUNCTION__); return BAD_VALUE; } size_t width = static_cast<size_t>(bufWidth); size_t height = static_cast<size_t>(bufHeight); size_t bufferLength = static_cast<size_t>(bufSize); // TODO: Switch to using Surface::lock and Surface::unlockAndPost err = native_window_dequeue_buffer_and_wait(anw.get(), &anb); if (err != NO_ERROR) return err; sp<GraphicBuffer> buf(GraphicBuffer::from(anb)); uint32_t grallocBufWidth = buf->getWidth(); uint32_t grallocBufHeight = buf->getHeight(); uint32_t grallocBufStride = buf->getStride(); if (grallocBufWidth != width || grallocBufHeight != height) { ALOGE("%s: Received gralloc buffer with bad dimensions %" PRIu32 "x%" PRIu32 ", expecting dimensions %zu x %zu", __FUNCTION__, grallocBufWidth, grallocBufHeight, width, height); return BAD_VALUE; } int32_t bufFmt = 0; err = anw->query(anw.get(), NATIVE_WINDOW_FORMAT, &bufFmt); if (err != NO_ERROR) { ALOGE("%s: Error while querying surface pixel format %s (%d).", __FUNCTION__, strerror(-err), err); return err; } uint64_t tmpSize = (pixelFmt == HAL_PIXEL_FORMAT_BLOB) ? grallocBufWidth : 4 * grallocBufHeight * grallocBufWidth; if (bufFmt != pixelFmt) { if (bufFmt == HAL_PIXEL_FORMAT_RGBA_8888 && pixelFmt == HAL_PIXEL_FORMAT_BLOB) { ALOGV("%s: Using BLOB to RGBA format override.", __FUNCTION__); tmpSize = 4 * (grallocBufWidth + grallocBufStride * (grallocBufHeight - 1)); } else { ALOGW("%s: Format mismatch in produceFrame: expecting format %#" PRIx32 ", but received buffer with format %#" PRIx32, __FUNCTION__, pixelFmt, bufFmt); } } if (tmpSize > SIZE_MAX) { ALOGE("%s: Overflow calculating size, buffer with dimens %zu x %zu is absurdly large...", __FUNCTION__, width, height); return BAD_VALUE; } size_t totalSizeBytes = tmpSize; ALOGV("%s: Pixel format chosen: %x", __FUNCTION__, pixelFmt); switch(pixelFmt) { case HAL_PIXEL_FORMAT_YCrCb_420_SP: { if (bufferLength < totalSizeBytes) { ALOGE("%s: PixelBuffer size %zu too small for given dimensions", __FUNCTION__, bufferLength); return BAD_VALUE; } uint8_t* img = NULL; ALOGV("%s: Lock buffer from %p for write", __FUNCTION__, anw.get()); err = buf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, (void**)(&img)); if (err != NO_ERROR) return err; uint8_t* yPlane = img; uint8_t* uPlane = img + height * width; uint8_t* vPlane = uPlane + 1; size_t chromaStep = 2; size_t yStride = width; size_t chromaStride = width; rgbToYuv420(pixelBuffer, width, height, yPlane, uPlane, vPlane, chromaStep, yStride, chromaStride); break; } case HAL_PIXEL_FORMAT_YV12: { if (bufferLength < totalSizeBytes) { ALOGE("%s: PixelBuffer size %zu too small for given dimensions", __FUNCTION__, bufferLength); return BAD_VALUE; } if ((width & 1) || (height & 1)) { ALOGE("%s: Dimens %zu x %zu are not divisible by 2.", __FUNCTION__, width, height); return BAD_VALUE; } uint8_t* img = NULL; //!++ ALOGI("%s: Lock buffer from %p for write", __FUNCTION__, anw.get()); //!-- err = buf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, (void**)(&img)); if (err != NO_ERROR) { ALOGE("%s: Error %s (%d) while locking gralloc buffer for write.", __FUNCTION__, strerror(-err), err); return err; } uint32_t stride = buf->getStride(); ALOGV("%s: stride is: %" PRIu32, __FUNCTION__, stride); LOG_ALWAYS_FATAL_IF(stride % 16, "Stride is not 16 pixel aligned %d", stride); uint32_t cStride = ALIGN(stride / 2, 16); size_t chromaStep = 1; uint8_t* yPlane = img; uint8_t* crPlane = img + static_cast<uint32_t>(height) * stride; uint8_t* cbPlane = crPlane + cStride * static_cast<uint32_t>(height) / 2; rgbToYuv420(pixelBuffer, width, height, yPlane, crPlane, cbPlane, chromaStep, stride, cStride); break; } case HAL_PIXEL_FORMAT_YCbCr_420_888: { // Software writes with YCbCr_420_888 format are unsupported // by the gralloc module for now if (bufferLength < totalSizeBytes) { ALOGE("%s: PixelBuffer size %zu too small for given dimensions", __FUNCTION__, bufferLength); return BAD_VALUE; } android_ycbcr ycbcr = android_ycbcr(); ALOGV("%s: Lock buffer from %p for write", __FUNCTION__, anw.get()); err = buf->lockYCbCr(GRALLOC_USAGE_SW_WRITE_OFTEN, &ycbcr); if (err != NO_ERROR) { ALOGE("%s: Failed to lock ycbcr buffer, error %s (%d).", __FUNCTION__, strerror(-err), err); return err; } rgbToYuv420(pixelBuffer, width, height, &ycbcr); break; } case HAL_PIXEL_FORMAT_BLOB: { int8_t* img = NULL; struct camera3_jpeg_blob footer = { .jpeg_blob_id = CAMERA3_JPEG_BLOB_ID, .jpeg_size = (uint32_t)bufferLength }; size_t totalJpegSize = bufferLength + sizeof(footer); totalJpegSize = (totalJpegSize + 3) & ~0x3; // round up to nearest octonibble if (totalJpegSize > totalSizeBytes) { ALOGE("%s: Pixel buffer needs size %zu, cannot fit in gralloc buffer of size %zu", __FUNCTION__, totalJpegSize, totalSizeBytes); return BAD_VALUE; } err = buf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, (void**)(&img)); if (err != NO_ERROR) { ALOGE("%s: Failed to lock buffer, error %s (%d).", __FUNCTION__, strerror(-err), err); return err; } memcpy(img, pixelBuffer, bufferLength); memcpy(img + totalSizeBytes - sizeof(footer), &footer, sizeof(footer)); break; } default: { ALOGE("%s: Invalid pixel format in produceFrame: %x", __FUNCTION__, pixelFmt); return BAD_VALUE; } } ALOGV("%s: Unlock buffer from %p", __FUNCTION__, anw.get()); err = buf->unlock(); if (err != NO_ERROR) { ALOGE("%s: Failed to unlock buffer, error %s (%d).", __FUNCTION__, strerror(-err), err); return err; } //!++ ALOGI("%s: Queue buffer to %p", __FUNCTION__, anw.get()); //!-- err = anw->queueBuffer(anw.get(), buf->getNativeBuffer(), /*fenceFd*/-1); if (err != NO_ERROR) { ALOGE("%s: Failed to queue buffer, error %s (%d).", __FUNCTION__, strerror(-err), err); return err; } return NO_ERROR; } static sp<ANativeWindow> getNativeWindow(JNIEnv* env, jobject surface) { sp<ANativeWindow> anw; if (surface) { anw = android_view_Surface_getNativeWindow(env, surface); if (env->ExceptionCheck()) { return NULL; } } else { jniThrowNullPointerException(env, "surface"); return NULL; } if (anw == NULL) { ALOGE("%s: Surface had no valid native window.", __FUNCTION__); return NULL; } return anw; } static sp<ANativeWindow> getNativeWindowFromTexture(JNIEnv* env, jobject surfaceTexture) { sp<ANativeWindow> anw; if (surfaceTexture) { anw = android_SurfaceTexture_getNativeWindow(env, surfaceTexture); if (env->ExceptionCheck()) { return NULL; } } else { jniThrowNullPointerException(env, "surfaceTexture"); return NULL; } if (anw == NULL) { jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException", "SurfaceTexture had no valid native window."); return NULL; } return anw; } static sp<Surface> getSurface(JNIEnv* env, jobject surface) { sp<Surface> s; if (surface) { s = android_view_Surface_getSurface(env, surface); if (env->ExceptionCheck()) { return NULL; } } else { jniThrowNullPointerException(env, "surface"); return NULL; } if (s == NULL) { jniThrowExceptionFmt(env, "java/lang/IllegalArgumentException", "Surface had no valid native Surface."); return NULL; } return s; } extern "C" { static jint LegacyCameraDevice_nativeDetectSurfaceType(JNIEnv* env, jobject thiz, jobject surface) { ALOGV("nativeDetectSurfaceType"); sp<ANativeWindow> anw; if ((anw = getNativeWindow(env, surface)) == NULL) { ALOGE("%s: Could not retrieve native window from surface.", __FUNCTION__); return BAD_VALUE; } int32_t fmt = 0; status_t err = anw->query(anw.get(), NATIVE_WINDOW_FORMAT, &fmt); if(err != NO_ERROR) { ALOGE("%s: Error while querying surface pixel format %s (%d).", __FUNCTION__, strerror(-err), err); return err; } return fmt; } static jint LegacyCameraDevice_nativeDetectSurfaceDataspace(JNIEnv* env, jobject thiz, jobject surface) { ALOGV("nativeDetectSurfaceDataspace"); sp<ANativeWindow> anw; if ((anw = getNativeWindow(env, surface)) == NULL) { ALOGE("%s: Could not retrieve native window from surface.", __FUNCTION__); return BAD_VALUE; } int32_t fmt = 0; status_t err = anw->query(anw.get(), NATIVE_WINDOW_DEFAULT_DATASPACE, &fmt); if(err != NO_ERROR) { ALOGE("%s: Error while querying surface dataspace %s (%d).", __FUNCTION__, strerror(-err), err); return err; } return fmt; } static jint LegacyCameraDevice_nativeDetectSurfaceDimens(JNIEnv* env, jobject thiz, jobject surface, jintArray dimens) { ALOGV("nativeGetSurfaceDimens"); if (dimens == NULL) { ALOGE("%s: Null dimens argument passed to nativeDetectSurfaceDimens", __FUNCTION__); return BAD_VALUE; } if (env->GetArrayLength(dimens) < 2) { ALOGE("%s: Invalid length of dimens argument in nativeDetectSurfaceDimens", __FUNCTION__); return BAD_VALUE; } sp<ANativeWindow> anw; if ((anw = getNativeWindow(env, surface)) == NULL) { ALOGE("%s: Could not retrieve native window from surface.", __FUNCTION__); return BAD_VALUE; } int32_t dimenBuf[2]; status_t err = anw->query(anw.get(), NATIVE_WINDOW_WIDTH, dimenBuf); if(err != NO_ERROR) { ALOGE("%s: Error while querying surface width %s (%d).", __FUNCTION__, strerror(-err), err); return err; } err = anw->query(anw.get(), NATIVE_WINDOW_HEIGHT, dimenBuf + 1); if(err != NO_ERROR) { ALOGE("%s: Error while querying surface height %s (%d).", __FUNCTION__, strerror(-err), err); return err; } env->SetIntArrayRegion(dimens, /*start*/0, /*length*/ARRAY_SIZE(dimenBuf), dimenBuf); return NO_ERROR; } static jint LegacyCameraDevice_nativeDetectSurfaceUsageFlags(JNIEnv* env, jobject thiz, jobject surface) { ALOGV("nativeDetectSurfaceUsageFlags"); sp<ANativeWindow> anw; if ((anw = getNativeWindow(env, surface)) == NULL) { jniThrowException(env, "Ljava/lang/UnsupportedOperationException;", "Could not retrieve native window from surface."); return BAD_VALUE; } int32_t usage = 0; status_t err = anw->query(anw.get(), NATIVE_WINDOW_CONSUMER_USAGE_BITS, &usage); if(err != NO_ERROR) { jniThrowException(env, "Ljava/lang/UnsupportedOperationException;", "Error while querying surface usage bits"); return err; } return usage; } static jint LegacyCameraDevice_nativeDisconnectSurface(JNIEnv* env, jobject thiz, jobject surface) { ALOGV("nativeDisconnectSurface"); if (surface == nullptr) return NO_ERROR; sp<ANativeWindow> anw; if ((anw = getNativeWindow(env, surface)) == NULL) { ALOGV("Buffer queue has already been abandoned."); return NO_ERROR; } status_t err = native_window_api_disconnect(anw.get(), NATIVE_WINDOW_API_CAMERA); if(err != NO_ERROR) { jniThrowException(env, "Ljava/lang/UnsupportedOperationException;", "Error while disconnecting surface"); return err; } return NO_ERROR; } static jint LegacyCameraDevice_nativeDetectTextureDimens(JNIEnv* env, jobject thiz, jobject surfaceTexture, jintArray dimens) { ALOGV("nativeDetectTextureDimens"); sp<ANativeWindow> anw; if ((anw = getNativeWindowFromTexture(env, surfaceTexture)) == NULL) { ALOGE("%s: Could not retrieve native window from SurfaceTexture.", __FUNCTION__); return BAD_VALUE; } int32_t dimenBuf[2]; status_t err = anw->query(anw.get(), NATIVE_WINDOW_WIDTH, dimenBuf); if(err != NO_ERROR) { ALOGE("%s: Error while querying SurfaceTexture width %s (%d)", __FUNCTION__, strerror(-err), err); return err; } err = anw->query(anw.get(), NATIVE_WINDOW_HEIGHT, dimenBuf + 1); if(err != NO_ERROR) { ALOGE("%s: Error while querying SurfaceTexture height %s (%d)", __FUNCTION__, strerror(-err), err); return err; } env->SetIntArrayRegion(dimens, /*start*/0, /*length*/ARRAY_SIZE(dimenBuf), dimenBuf); if (env->ExceptionCheck()) { return BAD_VALUE; } return NO_ERROR; } static jint LegacyCameraDevice_nativeConnectSurface(JNIEnv* env, jobject thiz, jobject surface) { ALOGV("nativeConnectSurface"); sp<Surface> s; if ((s = getSurface(env, surface)) == NULL) { ALOGE("%s: Could not retrieve surface.", __FUNCTION__); return BAD_VALUE; } status_t err = connectSurface(s, CAMERA_DEVICE_BUFFER_SLACK); if (err != NO_ERROR) { ALOGE("%s: Error while configuring surface %s (%d).", __FUNCTION__, strerror(-err), err); return err; } return NO_ERROR; } static jint LegacyCameraDevice_nativeProduceFrame(JNIEnv* env, jobject thiz, jobject surface, jbyteArray pixelBuffer, jint width, jint height, jint pixelFormat) { ALOGV("nativeProduceFrame"); sp<ANativeWindow> anw; if ((anw = getNativeWindow(env, surface)) == NULL) { ALOGE("%s: Could not retrieve native window from surface.", __FUNCTION__); return BAD_VALUE; } if (pixelBuffer == NULL) { jniThrowNullPointerException(env, "pixelBuffer"); return DONT_CARE; } int32_t bufSize = static_cast<int32_t>(env->GetArrayLength(pixelBuffer)); jbyte* pixels = env->GetByteArrayElements(pixelBuffer, /*is_copy*/NULL); if (pixels == NULL) { jniThrowNullPointerException(env, "pixels"); return DONT_CARE; } status_t err = produceFrame(anw, reinterpret_cast<uint8_t*>(pixels), width, height, pixelFormat, bufSize); env->ReleaseByteArrayElements(pixelBuffer, pixels, JNI_ABORT); if (err != NO_ERROR) { ALOGE("%s: Error while producing frame %s (%d).", __FUNCTION__, strerror(-err), err); return err; } return NO_ERROR; } static jint LegacyCameraDevice_nativeSetSurfaceFormat(JNIEnv* env, jobject thiz, jobject surface, jint pixelFormat) { ALOGV("nativeSetSurfaceType"); sp<ANativeWindow> anw; if ((anw = getNativeWindow(env, surface)) == NULL) { ALOGE("%s: Could not retrieve native window from surface.", __FUNCTION__); return BAD_VALUE; } status_t err = native_window_set_buffers_format(anw.get(), pixelFormat); if (err != NO_ERROR) { ALOGE("%s: Error while setting surface format %s (%d).", __FUNCTION__, strerror(-err), err); return err; } return NO_ERROR; } static jint LegacyCameraDevice_nativeSetSurfaceDimens(JNIEnv* env, jobject thiz, jobject surface, jint width, jint height) { ALOGV("nativeSetSurfaceDimens"); sp<ANativeWindow> anw; if ((anw = getNativeWindow(env, surface)) == NULL) { ALOGE("%s: Could not retrieve native window from surface.", __FUNCTION__); return BAD_VALUE; } // Set user dimensions only // The producer dimensions are owned by GL status_t err = native_window_set_buffers_user_dimensions(anw.get(), width, height); if (err != NO_ERROR) { ALOGE("%s: Error while setting surface user dimens %s (%d).", __FUNCTION__, strerror(-err), err); return err; } return NO_ERROR; } static jlong LegacyCameraDevice_nativeGetSurfaceId(JNIEnv* env, jobject thiz, jobject surface) { ALOGV("nativeGetSurfaceId"); sp<Surface> s; if ((s = getSurface(env, surface)) == NULL) { ALOGE("%s: Could not retrieve native Surface from surface.", __FUNCTION__); return 0; } sp<IGraphicBufferProducer> gbp = s->getIGraphicBufferProducer(); if (gbp == NULL) { ALOGE("%s: Could not retrieve IGraphicBufferProducer from surface.", __FUNCTION__); return 0; } sp<IBinder> b = IInterface::asBinder(gbp); if (b == NULL) { ALOGE("%s: Could not retrieve IBinder from surface.", __FUNCTION__); return 0; } /* * FIXME: Use better unique ID for surfaces than native IBinder pointer. Fix also in the camera * service (CameraDeviceClient.h). */ return reinterpret_cast<jlong>(b.get()); } static jint LegacyCameraDevice_nativeSetSurfaceOrientation(JNIEnv* env, jobject thiz, jobject surface, jint facing, jint orientation) { ALOGV("nativeSetSurfaceOrientation"); sp<ANativeWindow> anw; if ((anw = getNativeWindow(env, surface)) == NULL) { ALOGE("%s: Could not retrieve native window from surface.", __FUNCTION__); return BAD_VALUE; } status_t err = NO_ERROR; CameraMetadata staticMetadata; int32_t orientVal = static_cast<int32_t>(orientation); uint8_t facingVal = static_cast<uint8_t>(facing); staticMetadata.update(ANDROID_SENSOR_ORIENTATION, &orientVal, 1); staticMetadata.update(ANDROID_LENS_FACING, &facingVal, 1); int32_t transform = 0; if ((err = CameraUtils::getRotationTransform(staticMetadata, /*out*/&transform)) != NO_ERROR) { ALOGE("%s: Invalid rotation transform %s (%d)", __FUNCTION__, strerror(-err), err); return err; } ALOGV("%s: Setting buffer sticky transform to %d", __FUNCTION__, transform); if ((err = native_window_set_buffers_sticky_transform(anw.get(), transform)) != NO_ERROR) { ALOGE("%s: Unable to configure surface transform, error %s (%d)", __FUNCTION__, strerror(-err), err); return err; } return NO_ERROR; } static jint LegacyCameraDevice_nativeSetNextTimestamp(JNIEnv* env, jobject thiz, jobject surface, jlong timestamp) { ALOGV("nativeSetNextTimestamp"); sp<ANativeWindow> anw; if ((anw = getNativeWindow(env, surface)) == NULL) { ALOGE("%s: Could not retrieve native window from surface.", __FUNCTION__); return BAD_VALUE; } status_t err = NO_ERROR; if ((err = native_window_set_buffers_timestamp(anw.get(), static_cast<int64_t>(timestamp))) != NO_ERROR) { ALOGE("%s: Unable to set surface timestamp, error %s (%d)", __FUNCTION__, strerror(-err), err); return err; } return NO_ERROR; } static jint LegacyCameraDevice_nativeSetScalingMode(JNIEnv* env, jobject thiz, jobject surface, jint mode) { ALOGV("nativeSetScalingMode"); sp<ANativeWindow> anw; if ((anw = getNativeWindow(env, surface)) == NULL) { ALOGE("%s: Could not retrieve native window from surface.", __FUNCTION__); return BAD_VALUE; } status_t err = NO_ERROR; if ((err = native_window_set_scaling_mode(anw.get(), static_cast<int>(mode))) != NO_ERROR) { ALOGE("%s: Unable to set surface scaling mode, error %s (%d)", __FUNCTION__, strerror(-err), err); return err; } return NO_ERROR; } static jint LegacyCameraDevice_nativeGetJpegFooterSize(JNIEnv* env, jobject thiz) { ALOGV("nativeGetJpegFooterSize"); return static_cast<jint>(sizeof(struct camera3_jpeg_blob)); } } // extern "C" static const JNINativeMethod gCameraDeviceMethods[] = { { "nativeDetectSurfaceType", "(Landroid/view/Surface;)I", (void *)LegacyCameraDevice_nativeDetectSurfaceType }, { "nativeDetectSurfaceDataspace", "(Landroid/view/Surface;)I", (void *)LegacyCameraDevice_nativeDetectSurfaceDataspace }, { "nativeDetectSurfaceDimens", "(Landroid/view/Surface;[I)I", (void *)LegacyCameraDevice_nativeDetectSurfaceDimens }, { "nativeConnectSurface", "(Landroid/view/Surface;)I", (void *)LegacyCameraDevice_nativeConnectSurface }, { "nativeProduceFrame", "(Landroid/view/Surface;[BIII)I", (void *)LegacyCameraDevice_nativeProduceFrame }, { "nativeSetSurfaceFormat", "(Landroid/view/Surface;I)I", (void *)LegacyCameraDevice_nativeSetSurfaceFormat }, { "nativeSetSurfaceDimens", "(Landroid/view/Surface;II)I", (void *)LegacyCameraDevice_nativeSetSurfaceDimens }, { "nativeGetSurfaceId", "(Landroid/view/Surface;)J", (void *)LegacyCameraDevice_nativeGetSurfaceId }, { "nativeDetectTextureDimens", "(Landroid/graphics/SurfaceTexture;[I)I", (void *)LegacyCameraDevice_nativeDetectTextureDimens }, { "nativeSetSurfaceOrientation", "(Landroid/view/Surface;II)I", (void *)LegacyCameraDevice_nativeSetSurfaceOrientation }, { "nativeSetNextTimestamp", "(Landroid/view/Surface;J)I", (void *)LegacyCameraDevice_nativeSetNextTimestamp }, { "nativeGetJpegFooterSize", "()I", (void *)LegacyCameraDevice_nativeGetJpegFooterSize }, { "nativeDetectSurfaceUsageFlags", "(Landroid/view/Surface;)I", (void *)LegacyCameraDevice_nativeDetectSurfaceUsageFlags }, { "nativeSetScalingMode", "(Landroid/view/Surface;I)I", (void *)LegacyCameraDevice_nativeSetScalingMode }, { "nativeDisconnectSurface", "(Landroid/view/Surface;)I", (void *)LegacyCameraDevice_nativeDisconnectSurface }, }; // Get all the required offsets in java class and register native functions int register_android_hardware_camera2_legacy_LegacyCameraDevice(JNIEnv* env) { // Register native functions return RegisterMethodsOrDie(env, CAMERA_DEVICE_CLASS_NAME, gCameraDeviceMethods, NELEM(gCameraDeviceMethods)); }
[ "xiangchunhua8888@163.com" ]
xiangchunhua8888@163.com
7fc04c794ab80b01acb34b7a63b9bdbb86444e1b
2eecc41bc8ae893490b30e3abd9808bbd2bd6bdb
/Source/DirectX11Texture.cpp
278a4cd13f1a17ac6ce27b97da5abbd3c9e725ff
[]
no_license
shadercoder/scge
d991230860573a56a44f3ecac2de38c4f25a67f3
cec2bb285aa284206b4d41b9bbbf129a151bf200
refs/heads/master
2021-01-10T04:20:19.240225
2012-11-05T22:50:20
2012-11-05T22:50:20
44,643,412
0
0
null
null
null
null
UTF-8
C++
false
false
1,637
cpp
#include "scge\Graphics\DirectX11\DirectX11Texture.h" #include <string> #include <fstream> #include <sstream> DirectX11TextureData::DirectX11TextureData(ID3D11Device *d3d11Device, Console &console, FileSystem &fileSystem, bool multiThreadLoad, const std::string &arguments) : TextureResourceData(fileSystem) , mConsole(console) , mD3D11Device(d3d11Device) , mMultiThreadLoad(multiThreadLoad) { mFileName = arguments; } std::unique_ptr<Resource> DirectX11TextureData::createResource() const { return std::unique_ptr<Resource>(new DirectX11Texture(this)); } bool DirectX11Texture::Load() { std::ifstream file = mResourceData->mFileSystem.OpenFileRead(mResourceData->mFileName, true); if(!file || !file.is_open()) return true; file.seekg(0, std::ios::end); std::ifstream::pos_type length = file.tellg(); file.seekg(0, std::ios::beg); if(length <= 0) return true; mLoadingData.resize((unsigned int)length); file.read(mLoadingData.data(), length); return mResourceData->mMultiThreadLoad && finaliseLoad(); } bool DirectX11Texture::Finalise() { if(!mResourceData->mMultiThreadLoad && finaliseLoad()) return true; registerForChanges(); return false; } bool DirectX11Texture::finaliseLoad() { if(FAILED(D3DX11CreateShaderResourceViewFromMemory(mResourceData->mD3D11Device, mLoadingData.data(), mLoadingData.size(), nullptr, nullptr, mTextureSRV.getModifiablePointer(), nullptr))) return true; mLoadingData.clear(); return false; } void DirectX11Texture::Release() { unregisterForChanges(); mTextureSRV.Release(); mLoadingData.clear(); }
[ "quaver.smith@0469fb3b-1f0d-998d-8d12-02512b85cd7a" ]
quaver.smith@0469fb3b-1f0d-998d-8d12-02512b85cd7a
247b288bd8c17df8885928057c7739b8e3c9aee0
7292047e5cf82bfeec921ac1623ea3038a564ff3
/GraphicManager.cpp
c49b3d64a6216e6705bda9878e861108aef2e326
[]
no_license
kokojae/MultiMapEngine
9e756fd21e20cbae9b811d247e3048b825aeb4eb
60783f59441e84e7989351fe488d16c03defef7c
refs/heads/master
2022-11-22T02:01:26.395661
2020-07-25T08:28:34
2020-07-25T08:28:34
282,165,144
0
0
null
null
null
null
UHC
C++
false
false
1,994
cpp
#include "DXUT.h" #include "GraphicManager.h" #include "MultiMapEngine.h" LPD3DXSPRITE GraphicManager::sprite = nullptr; ID3DXFont* GraphicManager::font = nullptr; void GraphicManager::Init() { D3DXCreateSprite(DXUTGetD3D9Device(), &sprite); D3DXCreateFont( DXUTGetD3D9Device(), 70, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial", &font); } void GraphicManager::Render() { sprite->Begin(D3DXSPRITE_ALPHABLEND); ObjectManager::Render(); sprite->End(); } void GraphicManager::Release() { sprite->Release(); font->Release(); } void GraphicManager::TextureRender(TextureInfo info, D3DXVECTOR2 position) { D3DXMATRIX mat, center, pos, scale, degree; D3DXMatrixTranslation(&center, -info.center.x, -info.center.y, 0); D3DXMatrixTranslation(&pos, position.x, position.y, 0); D3DXMatrixScaling(&scale, info.scale.x, info.scale.y, 1); D3DXMatrixRotationZ(&degree, D3DXToRadian(info.degree)); mat = center * scale * degree * pos; if (info.camOn) mat *= Camera::GetCameraMatrix(); sprite->SetTransform(&mat); // 도트겜에 사용 DXUTGetD3D9Device()->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_POINT); DXUTGetD3D9Device()->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_POINT); DXUTGetD3D9Device()->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT); RECT rc = { (LONG)info.index * (LONG)info.size.x, 0, (LONG)(info.index + 1) * (LONG)info.size.x, (LONG)info.size.y }; sprite->Draw(info.texture, &rc, NULL, NULL, info.color); } void GraphicManager::TextRender(std::wstring text, D3DXVECTOR2 position, D3DXVECTOR2 scale, bool isUI) { D3DXMATRIX mat, pos, sca; D3DXMatrixTranslation(&pos, (int)position.x, (int)position.y, 0); D3DXMatrixScaling(&sca, scale.x, scale.y, 1); mat = sca * pos; if (!isUI) mat *= Camera::GetCameraMatrix(); sprite->SetTransform(&mat); font->DrawText(sprite, text.c_str(), -1, NULL, DT_NOCLIP, D3DCOLOR_XRGB(0, 0, 0)); }
[ "54296776+kokojae@users.noreply.github.com" ]
54296776+kokojae@users.noreply.github.com
4a749cb60b637b01dbd5ed6da0898f7c7ddf8bdc
6a2b431dbccff26a1a092ed506bebdfa4ae261b8
/VectTypes/VectVert.hpp
a7bb4aa5c0c97a76da9f1a96f4375114359cb6bd
[]
no_license
l-GlebaTi-l/VectHoriVert
e75781bb7955d6550b62d57c91a0687183814ef3
ddbf976420ee026fd4ca57fdae0518b1518294b3
refs/heads/master
2022-09-18T16:53:40.507211
2020-06-03T12:01:22
2020-06-03T12:01:22
269,068,309
0
0
null
null
null
null
UTF-8
C++
false
false
274
hpp
class CStringVert : public CString { public: using CString::operator=; CStringVert(char *str) : CString(str){} int output(); }; class FactoryCStringVert : public CFabricData{ public: CString* Create(char *str){ return new CStringVert(str); } };
[ "gleban37@rambler.ru" ]
gleban37@rambler.ru
6cb53157b9dfeb0cf3351cd1075f43053653f031
9413ac384ca5a94484b0cfe11a95d09d01bd1015
/main.cpp
e0d9138cec7088969dfb44edac3bc4fc4899bae5
[]
no_license
peerasakp/demo2
ae75106758b864b64a5c68f0ad851301ee666001
f3ab8b296d90cebeffcf9a6be0633f05d4a8292a
refs/heads/master
2022-12-28T15:54:08.788643
2020-10-15T06:54:32
2020-10-15T06:54:32
304,235,276
0
0
null
null
null
null
UTF-8
C++
false
false
208
cpp
#include <iostream> using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char** argv) { cout << "hello"; return 0; }
[ "peerasakp@gmail.com" ]
peerasakp@gmail.com
3e6d26dfd305babd712138badda5af72a4d2cf91
cc034592d1eeb2a1d8a5bfbb96346a3da7f812f2
/Sail/src/graphics/text/Text.cpp
f16ac205025499b5aca08e1375f7f0d552596831
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
tofb15/Sail
63187e070b8bc45cc216e1975e3224c30e52c26b
ce3162a7336a4ef77221eac9a7e96ac2e4f8de0b
refs/heads/master
2020-06-13T03:37:26.946324
2019-02-05T22:36:36
2019-02-05T22:36:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
784
cpp
#include "pch.h" #include "Text.h" #include "SailFont.h" #include "../shader/ShaderSet.h" using namespace DirectX::SimpleMath; Text::Ptr Text::Create(const std::wstring& text, const Vector2& pos, const Vector4& color) { return std::make_unique<Text>(text, pos, color); } Text::Text(const std::wstring& text, const Vector2& pos, const Vector4& color) : m_text(text) , m_pos(pos) , m_color(color) { } void Text::setText(const std::wstring& text) { m_text = text; } const std::wstring& Text::getText() const { return m_text; } void Text::setPosition(const Vector2& pos) { m_pos = pos; } const Vector2& Text::getPosition() const { return m_pos; } void Text::setColor(const Vector4& color) { m_color = color; } const Vector4& Text::getColor() const { return m_color; }
[ "alexander.wester@gmail.com" ]
alexander.wester@gmail.com
d808cf570c37eaf7d975d2382f8882ba4a37cdb9
82996d1c42874a5e75ebde51189e086126162774
/screenshot.cpp
ab86c9beb1f14f1d951ff47ca7bd29435820a269
[ "MIT" ]
permissive
Happy-Ferret/GLCollection
804f7c85e322ff83d725ad12247fc4f7305739b5
13d7a60e7e7a4bd099195fe4d3d35d9c08c31a62
refs/heads/master
2020-06-02T21:13:56.982206
2018-12-14T19:53:47
2018-12-14T19:53:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,602
cpp
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <time.h> #include "gl.h" #include "glfw_utilities.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include <stb_image_write.h> // https://github.com/nothings/stb void flipVertically(int width, int height, char *data) { char rgb[3]; for (int y = 0; y < height / 2; ++y) { for (int x = 0; x < width; ++x) { int top = (x + y * width) * 3; int bottom = (x + (height - y - 1) * width) * 3; memcpy(rgb, data + top, sizeof(rgb)); memcpy(data + top, data + bottom, sizeof(rgb)); memcpy(data + bottom, rgb, sizeof(rgb)); } } } int saveScreenshot(const char *filename) { GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); int x = viewport[0]; int y = viewport[1]; int width = viewport[2]; int height = viewport[3]; char *data = (char*) malloc((size_t) (width * height * 3)); // 3 components (R, G, B) if (!data) return 0; glPixelStorei(GL_PACK_ALIGNMENT, 1); glReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, data); flipVertically(width, height, data); int saved = stbi_write_png(filename, width, height, 3, data, 0); free(data); return saved; } const char* createScreenshotBasename() { static char basename[30]; time_t t = time(NULL); strftime(basename, 30, "%Y%m%d_%H%M%S.png", localtime(&t)); return basename; } int captureScreenshot() { char filename[50]; strcpy(filename, "screenshots/"); strcat(filename, createScreenshotBasename()); int saved = saveScreenshot(filename); if (saved) printf("Successfully Saved Image: %s\n", filename); else fprintf(stderr, "Failed Saving Image: %s\n", filename); return saved; } int main(int argc, char *argv[]) { // flipVertically in saveScreenshot // or // stbi_flip_vertically_on_write(1); if (!glfwInit()) { fprintf(stderr, "Failed initializing GLFW\n"); return EXIT_FAILURE; } glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); GLFWwindow *window = glfwCreateWindow(640, 480, "Screenshot - GLCollection", NULL, NULL); if (!window) { fprintf(stderr, "Failed creating window\n"); glfwTerminate(); return EXIT_FAILURE; } glcCenterWindow(window, glcGetBestMonitor(window)); glfwShowWindow(window); glfwMakeContextCurrent(window); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { fprintf(stderr, "Failed loading OpenGL functions and extensions\n"); glfwTerminate(); return EXIT_FAILURE; } glEnable(GL_SCISSOR_TEST); bool repeated = false; while (!glfwWindowShouldClose(window)) { int down = glfwGetKey(window, GLFW_KEY_F5); if (down && !repeated) { captureScreenshot(); repeated = true; } else if (!down) repeated = false; int viewportWidth, viewportHeight; glfwGetFramebufferSize(window, &viewportWidth, &viewportHeight); glViewport(0, 0, viewportWidth, viewportHeight); glScissor(0, viewportHeight / 2, viewportWidth / 2, viewportHeight / 2); glClearColor(1.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glScissor(viewportWidth / 2, viewportHeight / 2, viewportWidth / 2, viewportHeight / 2); glClearColor(0.0f, 1.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glScissor(0, 0, viewportWidth / 2, viewportHeight / 2); glClearColor(0.0f, 0.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glScissor(viewportWidth / 2, 0, viewportWidth / 2, viewportHeight / 2); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); return EXIT_SUCCESS; }
[ "vallentinsource@gmail.com" ]
vallentinsource@gmail.com
7f568f1b1cefcd2c3d315456368f8ccf99a36cb6
eeedc65ef99590d8316963717d1012cc6c90c9c5
/src/qt/addresstablemodel.cpp
c85306b81d7557a7d4c5dcd2cc205287826833ef
[ "MIT" ]
permissive
BayerTM/DraftCoinZ
e277353042c908373738bce65716c38ab0cbc0ff
217db2822a320d278d93dda4d3cd5dc4d01764f2
refs/heads/main
2023-06-01T00:54:12.511923
2021-06-09T21:35:24
2021-06-09T21:35:24
362,256,925
0
0
MIT
2021-04-27T22:23:49
2021-04-27T21:33:59
null
UTF-8
C++
false
false
14,640
cpp
// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2014-2020 The DFTz Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "addresstablemodel.h" #include "guiutil.h" #include "walletmodel.h" #include "base58.h" #include "wallet/wallet.h" #include <QFont> #include <QDebug> const QString AddressTableModel::Send = "S"; const QString AddressTableModel::Receive = "R"; struct AddressTableEntry { enum Type { Sending, Receiving, Hidden /* QSortFilterProxyModel will filter these out */ }; Type type; QString label; QString address; AddressTableEntry() {} AddressTableEntry(Type _type, const QString &_label, const QString &_address): type(_type), label(_label), address(_address) {} }; struct AddressTableEntryLessThan { bool operator()(const AddressTableEntry &a, const AddressTableEntry &b) const { return a.address < b.address; } bool operator()(const AddressTableEntry &a, const QString &b) const { return a.address < b; } bool operator()(const QString &a, const AddressTableEntry &b) const { return a < b.address; } }; /* Determine address type from address purpose */ static AddressTableEntry::Type translateTransactionType(const QString &strPurpose, bool isMine) { AddressTableEntry::Type addressType = AddressTableEntry::Hidden; // "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all. if (strPurpose == "send") addressType = AddressTableEntry::Sending; else if (strPurpose == "receive") addressType = AddressTableEntry::Receiving; else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending); return addressType; } // Private implementation class AddressTablePriv { public: CWallet *wallet; QList<AddressTableEntry> cachedAddressTable; AddressTableModel *parent; AddressTablePriv(CWallet *_wallet, AddressTableModel *_parent): wallet(_wallet), parent(_parent) {} void refreshAddressTable() { cachedAddressTable.clear(); { LOCK(wallet->cs_wallet); for (const std::pair<CTxDestination, CAddressBookData>& item : wallet->mapAddressBook) { const CBitcoinAddress& address = item.first; bool fMine = IsMine(*wallet, address.Get()); AddressTableEntry::Type addressType = translateTransactionType( QString::fromStdString(item.second.purpose), fMine); const std::string& strName = item.second.name; cachedAddressTable.append(AddressTableEntry(addressType, QString::fromStdString(strName), QString::fromStdString(address.ToString()))); } } // qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order // Even though the map is already sorted this re-sorting step is needed because the originating map // is sorted by binary address, not by base58() address. qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan()); } void updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status) { // Find address / label in model QList<AddressTableEntry>::iterator lower = qLowerBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); QList<AddressTableEntry>::iterator upper = qUpperBound( cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan()); int lowerIndex = (lower - cachedAddressTable.begin()); int upperIndex = (upper - cachedAddressTable.begin()); bool inModel = (lower != upper); AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine); switch(status) { case CT_NEW: if(inModel) { qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_NEW, but entry is already in model"; break; } parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex); cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address)); parent->endInsertRows(); break; case CT_UPDATED: if(!inModel) { qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_UPDATED, but entry is not in model"; break; } lower->type = newEntryType; lower->label = label; parent->emitDataChanged(lowerIndex); break; case CT_DELETED: if(!inModel) { qWarning() << "AddressTablePriv::updateEntry: Warning: Got CT_DELETED, but entry is not in model"; break; } parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1); cachedAddressTable.erase(lower, upper); parent->endRemoveRows(); break; } } int size() { return cachedAddressTable.size(); } AddressTableEntry *index(int idx) { if(idx >= 0 && idx < cachedAddressTable.size()) { return &cachedAddressTable[idx]; } else { return 0; } } }; AddressTableModel::AddressTableModel(CWallet *_wallet, WalletModel *parent) : QAbstractTableModel(parent),walletModel(parent),wallet(_wallet),priv(0) { columns << tr("Label") << tr("Address"); priv = new AddressTablePriv(wallet, this); priv->refreshAddressTable(); } AddressTableModel::~AddressTableModel() { delete priv; } int AddressTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return priv->size(); } int AddressTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); return columns.length(); } QVariant AddressTableModel::data(const QModelIndex &index, int role) const { if(!index.isValid()) return QVariant(); AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); if(role == Qt::DisplayRole || role == Qt::EditRole) { switch(index.column()) { case Label: if(rec->label.isEmpty() && role == Qt::DisplayRole) { return tr("(no label)"); } else { return rec->label; } case Address: return rec->address; } } else if (role == Qt::FontRole) { QFont font; if(index.column() == Address) { font = GUIUtil::fixedPitchFont(); } return font; } else if (role == TypeRole) { switch(rec->type) { case AddressTableEntry::Sending: return Send; case AddressTableEntry::Receiving: return Receive; default: break; } } return QVariant(); } bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, int role) { if(!index.isValid()) return false; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive"); editStatus = OK; if(role == Qt::EditRole) { LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */ CTxDestination curAddress = CBitcoinAddress(rec->address.toStdString()).Get(); if(index.column() == Label) { // Do nothing, if old label == new label if(rec->label == value.toString()) { editStatus = NO_CHANGES; return false; } wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose); } else if(index.column() == Address) { CTxDestination newAddress = CBitcoinAddress(value.toString().toStdString()).Get(); // Refuse to set invalid address, set error status and return false if(boost::get<CNoDestination>(&newAddress)) { editStatus = INVALID_ADDRESS; return false; } // Do nothing, if old address == new address else if(newAddress == curAddress) { editStatus = NO_CHANGES; return false; } // Check for duplicate addresses to prevent accidental deletion of addresses, if you try // to paste an existing address over another address (with a different label) else if(wallet->mapAddressBook.count(newAddress)) { editStatus = DUPLICATE_ADDRESS; return false; } // Double-check that we're not overwriting a receiving address else if(rec->type == AddressTableEntry::Sending) { // Remove old entry wallet->DelAddressBook(curAddress); // Add new entry with new address wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose); } } return true; } return false; } QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const { if(orientation == Qt::Horizontal) { if(role == Qt::DisplayRole && section < columns.size()) { return columns[section]; } } return QVariant(); } Qt::ItemFlags AddressTableModel::flags(const QModelIndex &index) const { if(!index.isValid()) return 0; AddressTableEntry *rec = static_cast<AddressTableEntry*>(index.internalPointer()); Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled; // Can edit address and label for sending addresses, // and only label for receiving addresses. if(rec->type == AddressTableEntry::Sending || (rec->type == AddressTableEntry::Receiving && index.column()==Label)) { retval |= Qt::ItemIsEditable; } return retval; } QModelIndex AddressTableModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent); AddressTableEntry *data = priv->index(row); if(data) { return createIndex(row, column, priv->index(row)); } else { return QModelIndex(); } } void AddressTableModel::updateEntry(const QString &address, const QString &label, bool isMine, const QString &purpose, int status) { // Update address book model from DFTz core priv->updateEntry(address, label, isMine, purpose, status); } QString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address) { std::string strLabel = label.toStdString(); std::string strAddress = address.toStdString(); editStatus = OK; if(type == Send) { if(!walletModel->validateAddress(address)) { editStatus = INVALID_ADDRESS; return QString(); } // Check for duplicate addresses { LOCK(wallet->cs_wallet); if(wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get())) { editStatus = DUPLICATE_ADDRESS; return QString(); } } } else if(type == Receive) { // Generate a new address to associate with given label CPubKey newKey; if(!wallet->GetKeyFromPool(newKey, false)) { WalletModel::UnlockContext ctx(walletModel->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet failed or was cancelled editStatus = WALLET_UNLOCK_FAILURE; return QString(); } if(!wallet->GetKeyFromPool(newKey, false)) { editStatus = KEY_GENERATION_FAILURE; return QString(); } } strAddress = CBitcoinAddress(newKey.GetID()).ToString(); } else { return QString(); } // Add entry { LOCK(wallet->cs_wallet); wallet->SetAddressBook(CBitcoinAddress(strAddress).Get(), strLabel, (type == Send ? "send" : "receive")); } return QString::fromStdString(strAddress); } bool AddressTableModel::removeRows(int row, int count, const QModelIndex &parent) { Q_UNUSED(parent); AddressTableEntry *rec = priv->index(row); if(count != 1 || !rec || rec->type == AddressTableEntry::Receiving) { // Can only remove one row at a time, and cannot remove rows not in model. // Also refuse to remove receiving addresses. return false; } { LOCK(wallet->cs_wallet); wallet->DelAddressBook(CBitcoinAddress(rec->address.toStdString()).Get()); } return true; } /* Look up label for address in address book, if not found return empty string. */ QString AddressTableModel::labelForAddress(const QString &address) const { CBitcoinAddress address_parsed(address.toStdString()); return labelForAddress(address_parsed); } QString AddressTableModel::labelForAddress(const CBitcoinAddress &address) const { return labelForDestination(address.Get()); } QString AddressTableModel::labelForDestination(const CTxDestination &dest) const { { LOCK(wallet->cs_wallet); std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(dest); if (mi != wallet->mapAddressBook.end()) { return QString::fromStdString(mi->second.name); } } return QString(); } int AddressTableModel::lookupAddress(const QString &address) const { QModelIndexList lst = match(index(0, Address, QModelIndex()), Qt::EditRole, address, 1, Qt::MatchExactly); if(lst.isEmpty()) { return -1; } else { return lst.at(0).row(); } } void AddressTableModel::emitDataChanged(int idx) { Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex())); }
[ "james@xmc.com" ]
james@xmc.com
de0ea780bde278519d98386257e3ca0a1532af17
8a0fa8913bd6fc1dc0573c3bd1178083f9c7cbdc
/排序/归并排序/归并排序.cpp
60962ac5d44a22f3321ba88e799937f1a5f28b68
[]
no_license
zhenghao-peng13/first
18469c813080941cfb125413f261f6659b202fac
2ca015baf634a414d65555b76951fd3f9433aa15
refs/heads/master
2023-04-25T11:09:18.274625
2021-05-14T11:33:46
2021-05-14T11:33:46
330,086,776
0
0
null
null
null
null
UTF-8
C++
false
false
256
cpp
#include <iostream> #include<random> using namespace std; int main() { srand((unsigned)time(NULL)); int a[10]; for (int i = 0; i < 10; i++) { a[i] = rand() % 50; cout << a[i]<<'\t'; } cout << endl; return 0; }
[ "3120001535@mail2.gdut.edu.cn" ]
3120001535@mail2.gdut.edu.cn
f469b2a95a3d505457d0a3873898a94f90ed9607
cce5c0e483c887dea4a32da7bcdd7118d437987c
/Forest Simulator/ForestSim/ForestSimApp.cpp
23201c0fb2179bde08c0bafe627ed3cbfc1de50d
[]
no_license
PotatoesBasket/AIE-AIForGames
7f79a929da820313877937d4a4de38f2eb9cbe98
2bc1a2f0226d5e2a008da1f721eebf2a9ffd9f83
refs/heads/master
2021-08-06T03:58:08.253386
2021-07-13T04:58:43
2021-07-13T04:58:43
221,143,227
0
0
null
null
null
null
UTF-8
C++
false
false
4,367
cpp
#include "ForestSimApp.h" #include "Texture.h" #include "Font.h" #include "Input.h" #include "ScreenDefines.h" #include <time.h> bool ForestSimApp::startup() { RNG& rng = RNG::getInstance(); rng.setSeed((int)time); m_2dRenderer = std::make_unique<aie::Renderer2D>(); m_map = std::make_unique<Map>(); initCamera(); return true; } void ForestSimApp::update(float deltaTime) { camControls(cappedDeltaTime(deltaTime)); m_map->update(cappedDeltaTime(deltaTime)); m_debug.getInput(); m_debug.printData(); } void ForestSimApp::draw() { clearScreen(); m_2dRenderer->begin(); m_map->draw(m_2dRenderer.get()); m_2dRenderer->end(); } void ForestSimApp::initCamera() { // init cam pan speed m_currentPanSpeed = m_panSpeed; // position camera in centre of map m_camPos = glm::vec2( (m_map->getMapWidthPx() - SCR_WIDTH) * 0.5f, (m_map->getMapHeightPx() - SCR_HEIGHT) * 0.5f); // set initial camera scale to medium zoom m_2dRenderer->setCameraScale(1.5f); } void ForestSimApp::camControls(float deltaTime) { aie::Input* getInput = aie::Input::getInstance(); // press escape to quit if (getInput->isKeyDown(aie::INPUT_KEY_ESCAPE)) quit(); //// press space to toggle zoom //if (getInput->isKeyDown(aie::INPUT_KEY_SPACE)) // m_zoomInputPressed = true; //else if (m_zoomInputPressed) //{ // m_zoomInputPressed = false; // // set zoom and realign camera // switch (m_zoomLevel) // { // case 0: // m_2dRenderer->setCameraScale(1.0f); // ++m_zoomLevel; // break; // case 1: // m_2dRenderer->setCameraScale(1.5f); // ++m_zoomLevel; // break; // case 2: // m_2dRenderer->setCameraScale(0.5f); // m_zoomLevel = 0; // } //} // left/right pan if (getInput->isKeyDown(aie::INPUT_KEY_A) || getInput->isKeyDown(aie::INPUT_KEY_LEFT)) m_camPos.x -= m_currentPanSpeed * deltaTime; else if (getInput->isKeyDown(aie::INPUT_KEY_D) || getInput->isKeyDown(aie::INPUT_KEY_RIGHT)) m_camPos.x += m_currentPanSpeed * deltaTime; // up/down pan if (getInput->isKeyDown(aie::INPUT_KEY_S) || getInput->isKeyDown(aie::INPUT_KEY_DOWN)) m_camPos.y -= m_currentPanSpeed * deltaTime; else if (getInput->isKeyDown(aie::INPUT_KEY_W) || getInput->isKeyDown(aie::INPUT_KEY_UP)) m_camPos.y += m_currentPanSpeed * deltaTime; // hold shift to speed up camera panning if (getInput->isKeyDown(aie::INPUT_KEY_LEFT_SHIFT) || getInput->isKeyDown(aie::INPUT_KEY_RIGHT_SHIFT)) m_currentPanSpeed = m_fastPanSpeed * m_2dRenderer->getCameraScale(); else m_currentPanSpeed = m_panSpeed * m_2dRenderer->getCameraScale(); // restrict camera position to map boundaries // its weird and i hate it float halfTileSize = m_map->getTileSize() * 0.5f; switch (m_zoomLevel) { case 0: if (m_camPos.x < 0.0f - SCR_WIDTH * 0.25f - halfTileSize) m_camPos.x = 0.0f - SCR_WIDTH * 0.25f - halfTileSize; if (m_camPos.x > m_map->getMapWidthPx() - SCR_WIDTH * 0.75f - halfTileSize) m_camPos.x = m_map->getMapWidthPx() - SCR_WIDTH * 0.75f - halfTileSize; if (m_camPos.y < 0.0f - SCR_HEIGHT * 0.25f + halfTileSize) m_camPos.y = 0.0f - SCR_HEIGHT * 0.25f + halfTileSize; if (m_camPos.y > m_map->getMapHeightPx() - SCR_HEIGHT * 0.75f + halfTileSize) m_camPos.y = m_map->getMapHeightPx() - SCR_HEIGHT * 0.75f + halfTileSize; break; case 1: if (m_camPos.x < 0.0f - halfTileSize) m_camPos.x = 0.0f - halfTileSize; if (m_camPos.x > m_map->getMapWidthPx() - SCR_WIDTH - halfTileSize) m_camPos.x = m_map->getMapWidthPx() - SCR_WIDTH - halfTileSize; if (m_camPos.y < 0.0f + halfTileSize) m_camPos.y = 0.0f + halfTileSize; if (m_camPos.y > m_map->getMapHeightPx() - SCR_HEIGHT + halfTileSize) m_camPos.y = m_map->getMapHeightPx() - SCR_HEIGHT + halfTileSize; break; case 2: if (m_camPos.x < 0.0f + SCR_WIDTH * 0.25f - halfTileSize) m_camPos.x = 0.0f + SCR_WIDTH * 0.25f - halfTileSize; if (m_camPos.x > m_map->getMapWidthPx() - SCR_WIDTH * 1.25f - halfTileSize) m_camPos.x = m_map->getMapWidthPx() - SCR_WIDTH * 1.25f - halfTileSize; if (m_camPos.y < 0.0f + SCR_HEIGHT * 0.25f + halfTileSize) m_camPos.y = 0.0f + SCR_HEIGHT * 0.25f + halfTileSize; if (m_camPos.y > m_map->getMapHeightPx() - SCR_HEIGHT * 1.25f + halfTileSize) m_camPos.y = m_map->getMapHeightPx() - SCR_HEIGHT * 1.25f + halfTileSize; break; } // update camera pos m_2dRenderer->setCameraPos(m_camPos.x, m_camPos.y); }
[ "PotatoesBasket@hotmail.com" ]
PotatoesBasket@hotmail.com
e7c31c7808d3ffd0e8ad54a248ca63a7d2ae8a89
417f0d1edc5e77c5a0073ac88e274cf97b4768a1
/Basketball_demo/src/Regulator.h
b186ad706712a22129900ed35c090a717b422f4a
[]
no_license
lyback/LGameAI
c559dea9f77c24c216fd3f4bff953a927b4309e5
4751a6fa699f77379eb56565139e96b40ad89b11
refs/heads/master
2021-01-05T14:25:50.448823
2017-07-23T08:16:46
2017-07-23T08:16:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,794
h
// @Name : REGULATOR_H // // @Author : Yukang Chen (moorekang@gmail.com) // @Date : 2011-09-04 21:56:19 // // @Brief : this is defination of Regulator, // : be used by those requested more time distance computations #if !defined(REGULATOR_H) #define REGULATOR_H #include "PrecisionTimer.h" class Regulator { private: double m_UpdatePeriod; //the time diff requested double m_ElapseTime; //the time have elapsed timeval prevTime; public: //@ countPerSecond: counts in one seconds Regulator(int countPerSecond) { assert(countPerSecond > 0 && "countPerSecond>0"); m_ElapseTime = 0.0; gettimeofday(&prevTime, NULL); if (countPerSecond > 0){ m_UpdatePeriod = 1000.0 / countPerSecond; } else if (isEqual(0.0, countPerSecond)){ m_UpdatePeriod = 0.0; } } Regulator(double periodTime)//in seconds { assert(periodTime>0 && "periodTime must larger than 0"); m_ElapseTime = 0.0; gettimeofday(&prevTime, NULL); m_UpdatePeriod = 1000.0*periodTime; } //return true iff elapsed time is more than m_dUpdatePeriod //reset elapsed time to zero bool isReady() { if( m_ElapseTime > m_UpdatePeriod ){ //m_ElapseTime = 0; return true; } timeval nowTime; gettimeofday(&nowTime, NULL); m_ElapseTime += TIMER->TimeDiff(&prevTime, &nowTime); //prevTime = nowTime; gettimeofday(&prevTime, NULL); return false; } double getElapseTime() { return m_ElapseTime; } }; #endif
[ "laiyierjiangsu@gmail.com" ]
laiyierjiangsu@gmail.com
a361b74378c300f6c8497fc181e09278f2737d19
9f32ed58a8c9c1fb390d5f5b27542bdc534dbc6b
/astgen/src/ast_utils.cpp
ee4c387c7ab9dcfaf8131ef9ebcbbd9b57944cc0
[]
no_license
bgyss/cppmm
f97fb52cf3c90f8a49ecaba10f8cdafe35989231
cf6506283625256d1e61356b8986e8db98eb1962
refs/heads/main
2023-08-19T23:55:27.813763
2021-10-22T21:25:08
2021-10-22T21:25:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,639
cpp
#include "ast_utils.hpp" #include "pystring.h" namespace ps = pystring; #include "base64.hpp" #include <clang/AST/ASTContext.h> #include <clang/AST/Attr.h> #include <clang/Basic/ExceptionSpecificationType.h> #include <clang/Basic/SourceManager.h> #define SPDLOG_ACTIVE_LEVEL TRACE #include <spdlog/fmt/fmt.h> #include <spdlog/fmt/ostr.h> #include <spdlog/spdlog.h> using namespace clang; namespace cppmm { /// Get any annotation attributes on the given Decl and return their values as /// a vector of strings std::vector<std::string> get_attrs(const clang::Decl* decl) { std::vector<std::string> attrs; if (decl->hasAttrs()) { clang::ASTContext& ctx = decl->getASTContext(); for (const auto& attr : decl->attrs()) { const clang::AnnotateAttr* ann = clang::dyn_cast<const clang::AnnotateAttr>(attr); if (ann) { attrs.push_back(ann->getAnnotation().str()); } } } return attrs; } /// Strip the type kinds off the front of a type name in the given string std::string strip_name_kinds(std::string s) { s = pystring::replace(s, "class ", ""); s = pystring::replace(s, "struct ", ""); s = pystring::replace(s, "enum ", ""); s = pystring::replace(s, "union ", ""); return s; } /// Get a nice, qualified name for the given record std::string get_record_name(const CXXRecordDecl* crd) { // we have to do this dance to get the template parameters in the name, // otherwise they're omitted return strip_name_kinds(crd->getCanonicalDecl() ->getTypeForDecl() ->getCanonicalTypeInternal() .getAsString()); } /// Get the full namespace path as a string std::string get_namespace_path(const DeclContext* dc) { std::string result; auto* parent = dc->getParent(); while (parent) { if (parent->isNamespace()) { const clang::NamespaceDecl* ns = static_cast<const clang::NamespaceDecl*>(parent); result = ns->getNameAsString() + "::" + result; } else if (parent->isRecord()) { const clang::CXXRecordDecl* crd = static_cast<const clang::CXXRecordDecl*>(parent); result = crd->getNameAsString() + "::" + result; } parent = parent->getParent(); } return result; } std::string mangle_type(const QualType& qt) { std::string const_ = ""; if (qt.isConstQualified()) { const_ = "const "; } if (qt->isPointerType() || qt->isReferenceType()) { std::string pointee = mangle_type(qt->getPointeeType()); std::string ptr = "*"; if (qt->isReferenceType()) { ptr = "&"; } else if (qt->isRValueReferenceType()) { ptr = "&&"; } return fmt::format("{}{}{}", const_, pointee, ptr); } else if (qt->isConstantArrayType()) { const ConstantArrayType* cat = dyn_cast<ConstantArrayType>(qt.getTypePtr()); std::string element = mangle_type(cat->getElementType()); return fmt::format("{}{}[{}]", const_, element, cat->getSize().getLimitedValue()); } else if (qt->isRecordType()) { auto crd = qt->getAsCXXRecordDecl(); return fmt::format("{}{}", const_, mangle_decl(crd)); } else if (qt->isBuiltinType()) { return fmt::format("{}{}", const_, qt.getUnqualifiedType().getAsString()); } else if (qt->isEnumeralType()) { auto ed = qt->getAsTagDecl(); return fmt::format("{}{}", const_, mangle_decl(ed)); } else if (qt->isFunctionProtoType()) { const auto type_name = qt.getUnqualifiedType().getAsString(); return fmt::format("{}{}", const_, type_name); } else { const auto type_name = qt.getUnqualifiedType().getAsString(); SPDLOG_WARN("Unhandled type in mangling {}", type_name); return fmt::format("{}{}", const_, type_name); } } std::vector<std::string> mangle_template_args(const TemplateArgumentList& args) { std::vector<std::string> result; for (int i = 0; i < args.size(); ++i) { const auto& arg = args[i]; if (arg.getKind() == TemplateArgument::ArgKind::Null) { result.push_back("Null"); } else if (arg.getKind() == TemplateArgument::ArgKind::Type) { result.push_back(mangle_type(arg.getAsType())); } else if (arg.getKind() == TemplateArgument::ArgKind::Declaration) { result.push_back("Declaration"); } else if (arg.getKind() == TemplateArgument::ArgKind::NullPtr) { result.push_back("NullPtr"); } else if (arg.getKind() == TemplateArgument::ArgKind::Integral) { result.push_back( ps::replace(arg.getAsIntegral().toString(10), "-", "neg")); } else if (arg.getKind() == TemplateArgument::ArgKind::Template) { result.push_back("Template"); } else if (arg.getKind() == TemplateArgument::ArgKind::TemplateExpansion) { result.push_back("TemplateExpansion"); } else if (arg.getKind() == TemplateArgument::ArgKind::Expression) { result.push_back("Expression"); } else { result.push_back("Pack"); } } return result; } std::string mangle_decl(const TagDecl* crd) { std::string namespace_path = get_namespace_path(crd); if (const auto* ctd = dyn_cast<ClassTemplateSpecializationDecl>(crd)) { auto args = mangle_template_args(ctd->getTemplateArgs()); return fmt::format("{}::{}<{}>", namespace_path, ctd->getNameAsString(), ps::join(", ", args)); } else { return fmt::format("{}::{}", namespace_path, crd->getNameAsString()); } } std::string get_comment(const clang::Decl* decl) { ASTContext& ctx = decl->getASTContext(); SourceManager& sm = ctx.getSourceManager(); const RawComment* rc = ctx.getRawCommentForDeclNoCache(decl); if (rc) { // Found comment! SourceRange range = rc->getSourceRange(); PresumedLoc startPos = sm.getPresumedLoc(range.getBegin()); PresumedLoc endPos = sm.getPresumedLoc(range.getEnd()); return rc->getFormattedText(sm, sm.getDiagnostics()); } return ""; } std::string get_comment_base64(const clang::Decl* decl) { return base64::base64_encode(get_comment(decl)); } bool is_noexcept(const clang::FunctionDecl* fd) { return isNoexceptExceptionSpec(fd->getExceptionSpecType()); } } // namespace cppmm
[ "anderslanglands@gmail.com" ]
anderslanglands@gmail.com
9254a860f87e923fb8403077c9aae5c7704a5444
e41bbc5c02ccea33b7904ff0799c7d16ab48c6d5
/client/AuctionWidget.hpp
ba927aa6eec268b1d4dca9740d8a9f64693422e1
[]
no_license
dbertha/quidditch-man
a1a53ae2cfb5bdf1b588340df57ee31644547f84
91dc4938c2e1b4acd488e7888cde076125f915ad
refs/heads/master
2020-03-30T08:05:37.019366
2014-04-08T09:08:40
2014-04-08T09:08:40
30,409,519
0
0
null
null
null
null
UTF-8
C++
false
false
1,437
hpp
#ifndef AUCTIONWIDGET_H #define AUCTIONWIDGET_H #include <iostream> #include <stdio.h> #include <stdlib.h> #include <QMainWindow> #include <QAction> #include <QMenuBar> #include <QMenu> #include <QMessageBox> #include <QStringList> #include <QProgressDialog> #include <QSocketNotifier> #include <QTimer> #include <QLabel> #include <QApplication> #include <QtGui> #include <vector> #include "Client.hpp" #include "MainWindow.hpp" #include "ListAuctionsWidget.hpp" class ListAuctionsWidget; class AuctionWidget : public QWidget { Q_OBJECT public: AuctionWidget(Client* client, QWidget* parent); void paintEvent(QPaintEvent*); void pause(); void resume(); void maskLabel(); void startTurn(); void endOfTurn(); void makeJoinable(); void updateLabels(); public slots: void init(); void join(); void bid(); void quit(); void prepareForNextTurn(); void prepareForEndOfTurn(); void changeLabel(); public: Client* _client; QWidget* _parent; bool _inAuction; ListAuctionsWidget* _listAuctionsWidget; QTimer* _endOfTurnTimer,*_nextTurnTimer,*_updater; int _startingPrice,_turnPrice,_timeBeforeEndOfTurn,_timeBeforeTurn,_timeLeft,_currentTurn; bool _hasBidden,_hasLeft; int _currentPrice,_nbOfBidders,_auctionID; QPushButton* _bidButton; QPushButton* _quitButton; QPushButton* _joinButton; QLabel* _priceLabel; QLabel* _biddersLabel; QHBoxLayout* _zone; QStackedWidget* _stack; QLabel* _errorLabel; }; #endif
[ "manolegr@ulb.ac.be" ]
manolegr@ulb.ac.be
8d233de45ba7a1e22720382a48b39438077f424f
a4a8b3219ff36ce2d945c50f01e3fedd2796446a
/muduo/net/http/HttpRequest.h
6714fd72b0fccd69559b0bbac2011001ddf812f6
[ "BSD-3-Clause" ]
permissive
HhTtLllL/muduo
9883bc0c1ce9004cbff1695b6884c30718446c47
5250f18c2efda4cac7d8a03eb0b37b2a2f0a64b4
refs/heads/master
2021-05-18T11:03:33.570737
2020-08-10T05:17:56
2020-08-10T05:17:56
251,220,297
2
0
null
null
null
null
UTF-8
C++
false
false
4,053
h
// Copyright 2010, Shuo Chen. All rights reserved. // http://code.google.com/p/muduo/ // // Use of this source code is governed by a BSD-style license // that can be found in the License file. // Author: Shuo Chen (chenshuo at chenshuo dot com) // // This is a public header file, it must only include public header files. #ifndef MUDUO_NET_HTTP_HTTPREQUEST_H #define MUDUO_NET_HTTP_HTTPREQUEST_H #include "muduo/base/copyable.h" #include "muduo/base/Timestamp.h" #include "muduo/base/Types.h" #include <map> #include <assert.h> #include <stdio.h> namespace muduo { namespace net { //http请求类的封装 class HttpRequest : public muduo::copyable { public: enum Method { //kInvaild 无效的方法, 其他为 当前支持的方法 kInvalid, kGet, kPost, kHead, kPut, kDelete }; //http 协议版本 enum Version { kUnknown, kHttp10, kHttp11 }; HttpRequest() : method_(kInvalid), version_(kUnknown) { } // 设置请求版本 void setVersion(Version v) { version_ = v; } // 获取请求版本 Version getVersion() const { return version_; } //设置方法 bool setMethod(const char* start, const char* end) { assert(method_ == kInvalid); string m(start, end); if (m == "GET") { method_ = kGet; } else if (m == "POST") { method_ = kPost; } else if (m == "HEAD") { method_ = kHead; } else if (m == "PUT") { method_ = kPut; } else if (m == "DELETE") { method_ = kDelete; } else { method_ = kInvalid; } return method_ != kInvalid; } Method method() const { return method_; } //返回 请求放阿飞 const char* methodString() const { const char* result = "UNKNOWN"; switch(method_) { case kGet: result = "GET"; break; case kPost: result = "POST"; break; case kHead: result = "HEAD"; break; case kPut: result = "PUT"; break; case kDelete: result = "DELETE"; break; default: break; } return result; } // 设置路径 void setPath(const char* start, const char* end) { path_.assign(start, end); } //返回路径 const string& path() const { return path_; } void setQuery(const char* start, const char* end) { query_.assign(start, end); } const string& query() const { return query_; } //设置接受时间 void setReceiveTime(Timestamp t) { receiveTime_ = t; } //返回接受时间 Timestamp receiveTime() const { return receiveTime_; } //添加一个头部信息 void addHeader(const char* start, const char* colon, const char* end) { string field(start, colon); //header 域 ++colon; //取出左空格 while (colon < end && isspace(*colon)) { ++colon; } string value(colon, end); //header 值 //取出右空格 while (!value.empty() && isspace(value[value.size()-1])) { value.resize(value.size()-1); } headers_[field] = value; } // 获取头部信息 string getHeader(const string& field) const { string result; std::map<string, string>::const_iterator it = headers_.find(field); if (it != headers_.end()) { result = it->second; } return result; } const std::map<string, string>& headers() const { return headers_; } // 交换数据成员 void swap(HttpRequest& that) { std::swap(method_, that.method_); std::swap(version_, that.version_); path_.swap(that.path_); query_.swap(that.query_); receiveTime_.swap(that.receiveTime_); headers_.swap(that.headers_); } private: Method method_; //请求方法 Version version_; //协议版本 1.0/1.1 string path_; //请求路径 string query_; Timestamp receiveTime_; //请求时间 std::map<string, string> headers_; //header 列表 }; } // namespace net } // namespace muduo #endif // MUDUO_NET_HTTP_HTTPREQUEST_H
[ "1430249706@qq.com" ]
1430249706@qq.com
289fa46965c3730d770a63fd67a294e8432ded8d
72b7c060297cb81101047f5e2e575b6f532541ca
/src/Open3D/Geometry/EstimateNormals.cpp
d4ce195490d47a8b9f130754a7b0fac402114132
[]
no_license
iwanbok/INFOMR_Project
cfd0d56401f448d64f647bc1e7f4399001b2b3f0
5c8317f36304e45ca279f7bec069faeb55a2bef5
refs/heads/master
2022-03-15T20:44:43.865180
2019-11-10T11:18:34
2019-11-10T11:21:27
206,776,943
0
0
null
null
null
null
UTF-8
C++
false
false
12,496
cpp
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018 www.open3d.org // // 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 <Eigen/Eigenvalues> // #include "Open3D/Geometry/KDTreeFlann.h" #include "PointCloud.h" // #include "Open3D/Utility/Console.h" namespace open3d { namespace { using namespace geometry; Eigen::Vector3d ComputeEigenvector0(const Eigen::Matrix3d &A, double eval0) { Eigen::Vector3d row0(A(0, 0) - eval0, A(0, 1), A(0, 2)); Eigen::Vector3d row1(A(0, 1), A(1, 1) - eval0, A(1, 2)); Eigen::Vector3d row2(A(0, 2), A(1, 2), A(2, 2) - eval0); Eigen::Vector3d r0xr1 = row0.cross(row1); Eigen::Vector3d r0xr2 = row0.cross(row2); Eigen::Vector3d r1xr2 = row1.cross(row2); double d0 = r0xr1.dot(r0xr1); double d1 = r0xr2.dot(r0xr2); double d2 = r1xr2.dot(r1xr2); double dmax = d0; int imax = 0; if (d1 > dmax) { dmax = d1; imax = 1; } if (d2 > dmax) { imax = 2; } if (imax == 0) { return r0xr1 / std::sqrt(d0); } else if (imax == 1) { return r0xr2 / std::sqrt(d1); } else { return r1xr2 / std::sqrt(d2); } } Eigen::Vector3d ComputeEigenvector1(const Eigen::Matrix3d &A, const Eigen::Vector3d &evec0, double eval1) { Eigen::Vector3d U, V; if (std::abs(evec0(0)) > std::abs(evec0(1))) { double inv_length = 1 / std::sqrt(evec0(0) * evec0(0) + evec0(2) * evec0(2)); U << -evec0(2) * inv_length, 0, evec0(0) * inv_length; } else { double inv_length = 1 / std::sqrt(evec0(1) * evec0(1) + evec0(2) * evec0(2)); U << 0, evec0(2) * inv_length, -evec0(1) * inv_length; } V = evec0.cross(U); Eigen::Vector3d AU(A(0, 0) * U(0) + A(0, 1) * U(1) + A(0, 2) * U(2), A(0, 1) * U(0) + A(1, 1) * U(1) + A(1, 2) * U(2), A(0, 2) * U(0) + A(1, 2) * U(1) + A(2, 2) * U(2)); Eigen::Vector3d AV = {A(0, 0) * V(0) + A(0, 1) * V(1) + A(0, 2) * V(2), A(0, 1) * V(0) + A(1, 1) * V(1) + A(1, 2) * V(2), A(0, 2) * V(0) + A(1, 2) * V(1) + A(2, 2) * V(2)}; double m00 = U(0) * AU(0) + U(1) * AU(1) + U(2) * AU(2) - eval1; double m01 = U(0) * AV(0) + U(1) * AV(1) + U(2) * AV(2); double m11 = V(0) * AV(0) + V(1) * AV(1) + V(2) * AV(2) - eval1; double absM00 = std::abs(m00); double absM01 = std::abs(m01); double absM11 = std::abs(m11); double max_abs_comp; if (absM00 >= absM11) { max_abs_comp = std::max(absM00, absM01); if (max_abs_comp > 0) { if (absM00 >= absM01) { m01 /= m00; m00 = 1 / std::sqrt(1 + m01 * m01); m01 *= m00; } else { m00 /= m01; m01 = 1 / std::sqrt(1 + m00 * m00); m00 *= m01; } return m01 * U - m00 * V; } else { return U; } } else { max_abs_comp = std::max(absM11, absM01); if (max_abs_comp > 0) { if (absM11 >= absM01) { m01 /= m11; m11 = 1 / std::sqrt(1 + m01 * m01); m01 *= m11; } else { m11 /= m01; m01 = 1 / std::sqrt(1 + m11 * m11); m11 *= m01; } return m11 * U - m01 * V; } else { return U; } } } Eigen::Vector3d FastEigen3x3(Eigen::Matrix3d &A) { // Previous version based on: // https://en.wikipedia.org/wiki/Eigenvalue_algorithm#3.C3.973_matrices // Current version based on // https://www.geometrictools.com/Documentation/RobustEigenSymmetric3x3.pdf // which handles edge cases like points on a plane double max_coeff = A.maxCoeff(); if (max_coeff == 0) { return Eigen::Vector3d::Zero(); } A /= max_coeff; double norm = A(0, 1) * A(0, 1) + A(0, 2) * A(0, 2) + A(1, 2) * A(1, 2); if (norm > 0) { Eigen::Vector3d eval; Eigen::Vector3d evec0; Eigen::Vector3d evec1; Eigen::Vector3d evec2; double q = (A(0, 0) + A(1, 1) + A(2, 2)) / 3; double b00 = A(0, 0) - q; double b11 = A(1, 1) - q; double b22 = A(2, 2) - q; double p = std::sqrt((b00 * b00 + b11 * b11 + b22 * b22 + norm * 2) / 6); double c00 = b11 * b22 - A(1, 2) * A(1, 2); double c01 = A(0, 1) * b22 - A(1, 2) * A(0, 2); double c02 = A(0, 1) * A(1, 2) - b11 * A(0, 2); double det = (b00 * c00 - A(0, 1) * c01 + A(0, 2) * c02) / (p * p * p); double half_det = det * 0.5; half_det = std::min(std::max(half_det, -1.0), 1.0); double angle = std::acos(half_det) / (double)3; double const two_thirds_pi = 2.09439510239319549; double beta2 = std::cos(angle) * 2; double beta0 = std::cos(angle + two_thirds_pi) * 2; double beta1 = -(beta0 + beta2); eval(0) = q + p * beta0; eval(1) = q + p * beta1; eval(2) = q + p * beta2; if (half_det >= 0) { evec2 = ComputeEigenvector0(A, eval(2)); if (eval(2) < eval(0) && eval(2) < eval(1)) { A *= max_coeff; return evec2; } evec1 = ComputeEigenvector1(A, evec2, eval(1)); A *= max_coeff; if (eval(1) < eval(0) && eval(1) < eval(2)) { return evec1; } evec0 = evec1.cross(evec2); return evec0; } else { evec0 = ComputeEigenvector0(A, eval(0)); if (eval(0) < eval(1) && eval(0) < eval(2)) { A *= max_coeff; return evec0; } evec1 = ComputeEigenvector1(A, evec0, eval(1)); A *= max_coeff; if (eval(1) < eval(0) && eval(1) < eval(2)) { return evec1; } evec2 = evec0.cross(evec1); return evec2; } } else { A *= max_coeff; if (A(0, 0) < A(1, 1) && A(0, 0) < A(2, 2)) { return Eigen::Vector3d(1, 0, 0); } else if (A(1, 1) < A(0, 0) && A(1, 1) < A(2, 2)) { return Eigen::Vector3d(0, 1, 0); } else { return Eigen::Vector3d(0, 0, 1); } } } Eigen::Vector3d ComputeNormal(const PointCloud &cloud, const std::vector<int> &indices, bool fast_normal_computation) { if (indices.size() == 0) { return Eigen::Vector3d::Zero(); } Eigen::Matrix3d covariance; Eigen::Matrix<double, 9, 1> cumulants; cumulants.setZero(); for (size_t i = 0; i < indices.size(); i++) { const Eigen::Vector3d &point = cloud.points_[indices[i]]; cumulants(0) += point(0); cumulants(1) += point(1); cumulants(2) += point(2); cumulants(3) += point(0) * point(0); cumulants(4) += point(0) * point(1); cumulants(5) += point(0) * point(2); cumulants(6) += point(1) * point(1); cumulants(7) += point(1) * point(2); cumulants(8) += point(2) * point(2); } cumulants /= (double)indices.size(); covariance(0, 0) = cumulants(3) - cumulants(0) * cumulants(0); covariance(1, 1) = cumulants(6) - cumulants(1) * cumulants(1); covariance(2, 2) = cumulants(8) - cumulants(2) * cumulants(2); covariance(0, 1) = cumulants(4) - cumulants(0) * cumulants(1); covariance(1, 0) = covariance(0, 1); covariance(0, 2) = cumulants(5) - cumulants(0) * cumulants(2); covariance(2, 0) = covariance(0, 2); covariance(1, 2) = cumulants(7) - cumulants(1) * cumulants(2); covariance(2, 1) = covariance(1, 2); if (fast_normal_computation) { return FastEigen3x3(covariance); } else { Eigen::SelfAdjointEigenSolver<Eigen::Matrix3d> solver; solver.compute(covariance, Eigen::ComputeEigenvectors); return solver.eigenvectors().col(0); } } } // unnamed namespace namespace geometry { // bool PointCloud::EstimateNormals( // const KDTreeSearchParam &search_param /* = KDTreeSearchParamKNN()*/, // bool fast_normal_computation /* = true */) { // bool has_normal = HasNormals(); // if (HasNormals() == false) { // normals_.resize(points_.size()); // } // KDTreeFlann kdtree; // kdtree.SetGeometry(*this); // #ifdef _OPENMP // #pragma omp parallel for schedule(static) // #endif // for (int i = 0; i < (int)points_.size(); i++) { // std::vector<int> indices; // std::vector<double> distance2; // Eigen::Vector3d normal; // if (kdtree.Search(points_[i], search_param, indices, distance2) >= 3) { // normal = ComputeNormal(*this, indices, fast_normal_computation); // if (normal.norm() == 0.0) { // if (has_normal) { // normal = normals_[i]; // } else { // normal = Eigen::Vector3d(0.0, 0.0, 1.0); // } // } // if (has_normal && normal.dot(normals_[i]) < 0.0) { // normal *= -1.0; // } // normals_[i] = normal; // } else { // normals_[i] = Eigen::Vector3d(0.0, 0.0, 1.0); // } // } // return true; // } bool PointCloud::OrientNormalsToAlignWithDirection( const Eigen::Vector3d &orientation_reference /* = Eigen::Vector3d(0.0, 0.0, 1.0)*/) { if (HasNormals() == false) { printf( "[OrientNormalsToAlignWithDirection] No normals in the " "PointCloud. Call EstimateNormals() first.\n"); } #ifdef _OPENMP #pragma omp parallel for schedule(static) #endif for (int i = 0; i < (int)points_.size(); i++) { auto &normal = normals_[i]; if (normal.norm() == 0.0) { normal = orientation_reference; } else if (normal.dot(orientation_reference) < 0.0) { normal *= -1.0; } } return true; } bool PointCloud::OrientNormalsTowardsCameraLocation( const Eigen::Vector3d &camera_location /* = Eigen::Vector3d::Zero()*/) { if (HasNormals() == false) { printf( "[OrientNormalsTowardsCameraLocation] No normals in the " "PointCloud. Call EstimateNormals() first.\n"); } #ifdef _OPENMP #pragma omp parallel for schedule(static) #endif for (int i = 0; i < (int)points_.size(); i++) { Eigen::Vector3d orientation_reference = camera_location - points_[i]; auto &normal = normals_[i]; if (normal.norm() == 0.0) { normal = orientation_reference; if (normal.norm() == 0.0) { normal = Eigen::Vector3d(0.0, 0.0, 1.0); } else { normal.normalize(); } } else if (normal.dot(orientation_reference) < 0.0) { normal *= -1.0; } } return true; } } // namespace geometry } // namespace open3d
[ "iwan.boksebeld@gmail.com" ]
iwan.boksebeld@gmail.com
196df46724cbedbc46d6503fad0507c5ab170929
7719e2ae617b3bd0a444444707682d75c379c82d
/Labirintas/Priesai.cpp
070b1d283b030419b8b5b2a7fad237f8d0146cf4
[]
no_license
deivunis/Labirintas
d599db168eca8b38cc410ef3a9736b08b4402bb7
45b6806d30d185dd5afad1cb319ce3620721bcbf
refs/heads/master
2023-04-20T01:20:44.277461
2021-05-14T16:36:23
2021-05-14T16:36:23
364,684,556
0
0
null
null
null
null
UTF-8
C++
false
false
1,052
cpp
#include "Priesai.h" using namespace std; /*/void Goblinas::Monstras() { mx = 7; my = 1; monstras = { 4 }; }*/ int Goblinas::Damage() { srand((unsigned)time(0)); int dmg = 1 + (rand() % 30); return dmg; } int Goblinas::Exhaustion() { srand((unsigned)time(0)); int exh = 1 + (rand() % 30); return exh; } int Goblinas::goblino_Pinigai() { srand((unsigned)time(0)); int money = 1 + (rand() % 100); return money; } int Vilkolakis::Damage() { srand((unsigned)time(0)); int dmg = 1 + (rand() % 50); return dmg; } int Vilkolakis::Exhaustion() { srand((unsigned)time(0)); int exh = 1 + (rand() % 15); return exh; } int Vilkolakis::vilkolakio_Eleksyras() { srand((unsigned)time(0)); int hp = 1 + (rand() % 20); return hp; } int Skeletonas::Damage() { srand((unsigned)time(0)); int dmg = 1 + (rand() % 30); return dmg; } int Skeletonas::Exhaustion() { srand((unsigned)time(0)); int exh = 1 + (rand() % 50); return exh; } int Skeletonas::skeletono_Eleksyras() { srand((unsigned)time(0)); int pwr = 1 + (rand() % 20); return pwr; }
[ "d3ivunis@gmail.com" ]
d3ivunis@gmail.com
e774613e5bb5e7e77921eb67f01f7eeb3f36929c
a46973289535ae19034b148fa54c2e91db3f4436
/15 Geometry Shader Beginning/Effects.h
faabeade92e97759e27a93f70763367ee472b442
[ "MIT" ]
permissive
SunIcey/DirectX11-With-Windows-SDK
2ba4e77cdf07ec3d49c9f1cbba26d8910849f44d
a0bb4fd618c6d9e1b4a35b46f2f94a289072a8e9
refs/heads/master
2020-04-30T00:57:59.161013
2019-03-17T04:31:27
2019-03-17T04:31:27
null
0
0
null
null
null
null
GB18030
C++
false
false
2,529
h
//*************************************************************************************** // Effects.h by X_Jun(MKXJun) (C) 2018-2019 All Rights Reserved. // Licensed under the MIT License. // // 简易特效管理框架 // Simple effect management framework. //*************************************************************************************** #ifndef EFFECTS_H #define EFFECTS_H #include <memory> #include "LightHelper.h" #include "RenderStates.h" class IEffect { public: // 使用模板别名(C++11)简化类型名 template <class T> using ComPtr = Microsoft::WRL::ComPtr<T>; IEffect() = default; // 不支持复制构造 IEffect(const IEffect&) = delete; IEffect& operator=(const IEffect&) = delete; // 允许转移 IEffect(IEffect&& moveFrom) = default; IEffect& operator=(IEffect&& moveFrom) = default; virtual ~IEffect() = default; // 更新并绑定常量缓冲区 virtual void Apply(ComPtr<ID3D11DeviceContext> deviceContext) = 0; }; class BasicEffect : public IEffect { public: BasicEffect(); virtual ~BasicEffect() override; BasicEffect(BasicEffect&& moveFrom); BasicEffect& operator=(BasicEffect&& moveFrom); // 获取单例 static BasicEffect& Get(); // 初始化Basic.hlsli所需资源并初始化渲染状态 bool InitAll(ComPtr<ID3D11Device> device); // // 渲染模式的变更 // // 绘制三角形分裂 void SetRenderSplitedTriangle(ComPtr<ID3D11DeviceContext> deviceContext); // 绘制无上下盖的圆柱体 void SetRenderCylinderNoCap(ComPtr<ID3D11DeviceContext> deviceContext); // 绘制所有顶点的法向量 void SetRenderNormal(ComPtr<ID3D11DeviceContext> deviceContext); // // 矩阵设置 // void XM_CALLCONV SetWorldMatrix(DirectX::FXMMATRIX W); void XM_CALLCONV SetViewMatrix(DirectX::FXMMATRIX V); void XM_CALLCONV SetProjMatrix(DirectX::FXMMATRIX P); // // 光照、材质和纹理相关设置 // // 各种类型灯光允许的最大数目 static const int maxLights = 5; void SetDirLight(size_t pos, const DirectionalLight& dirLight); void SetPointLight(size_t pos, const PointLight& pointLight); void SetSpotLight(size_t pos, const SpotLight& spotLight); void SetMaterial(const Material& material); void XM_CALLCONV SetEyePos(DirectX::FXMVECTOR eyePos); // 设置圆柱体侧面高度 void SetCylinderHeight(float height); // 应用常量缓冲区和纹理资源的变更 void Apply(ComPtr<ID3D11DeviceContext> deviceContext); private: class Impl; std::unique_ptr<Impl> pImpl; }; #endif
[ "757919340@qq.com" ]
757919340@qq.com
55b6ada0906ca3825603842a71a9f597cb58a473
17c9968d84be9a156d4717248b44bb0ea133233e
/SS_Dll/Misc.cpp
6c4e3aa5bab5053b8b04b38fa87994ba28bc9546
[]
no_license
NamoPark/Sample
b0f48f4b977c22456c8e615f2be98736fa263ff8
ccc873db51bce9fd16084474232630b9d9d036d6
refs/heads/master
2021-01-15T05:24:47.277293
2020-02-25T02:16:15
2020-02-25T02:16:15
242,889,282
0
0
null
null
null
null
UTF-8
C++
false
false
3,831
cpp
#include "stdafx.h" #include "Misc.h" #include <WS2tcpip.h> #include "SS_Interface.h" #define UNSIGNED_BYTE_0 85; #define UNSIGNED_BYTE_1 83; #define SIGNED_BYTE_0 83; #define SIGNED_BYTE_1 73; static char ix_Mutex[cVaU3_MaxMutexID + 1]; void SleepMsg(DWORD dwMilliseconds) { DWORD dwStart = 0; MSG msg = { 0, }; dwStart = GetTickCount(); while (GetTickCount() - dwStart < dwMilliseconds) { while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } // Lower CPU Usage Sleep(10); } } BOOL FileRW(BOOL Method, const TCHAR *AFName, int ASize, void *Buf, BOOL AMsgBox) { HANDLE qF = CreateFile(AFName, Method ? GENERIC_WRITE : GENERIC_READ, Method ? 0 : FILE_SHARE_READ, NULL, Method ? CREATE_ALWAYS : OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); DWORD qNumRW; if (qF == INVALID_HANDLE_VALUE) { qNumRW = 0; while (++qNumRW < 3 && GetLastError() == ERROR_SHARING_VIOLATION) { Sleep(200); qF = CreateFile(AFName, Method ? GENERIC_WRITE : GENERIC_READ, Method ? 0 : FILE_SHARE_READ, NULL, Method ? CREATE_ALWAYS : OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (qF != INVALID_HANDLE_VALUE) goto Label_Begin; }; return FALSE; }; Label_Begin: if (!Method) { int qFSize = GetFileSize(qF, NULL); if (ASize <= 0) ASize = qFSize; else if (ASize != qFSize) { CloseHandle(qF); return FALSE; }; }; if (Method) WriteFile(qF, Buf, ASize, &qNumRW, NULL); else ReadFile(qF, Buf, ASize, &qNumRW, NULL); if ((int)qNumRW != ASize) { CloseHandle(qF); return FALSE; }; CloseHandle(qF); return TRUE; } ULONG VAU3_InetAddrTCHAR(const TCHAR *AAddr) { char qAddr[40]; ULONG Ret; memset(qAddr, sizeof(qAddr), 0); #ifdef UNICODE WideCharToMultiByte(CP_ACP, 0, AAddr, -1, qAddr, sizeof(qAddr), NULL, NULL); #else _tcsncpy(qAddr, AAddr, sizeof(qAddr) - 1); #endif //return inet_addr(qAddr); if (inet_pton(AF_INET, qAddr, &Ret) != 0) return Ret; else return -1; } void VaU3_MutexCreate(int AMutexID) { ix_Mutex[AMutexID] = 0; } BOOL VaU3_MutexGet(int AMutexID) { int qWaitCount = 0; while (ix_Mutex[AMutexID]) { Sleep(1); if (++qWaitCount > 10 && !VaU3_MutexLocked(AMutexID)) return FALSE; if (ix_Mutex[AMutexID] == 2) { return 2; } }; ix_Mutex[AMutexID] = 1; return TRUE; } void VaU3_MutexRelease(int AMutexID) { ix_Mutex[AMutexID] = 0; } void VaU3_MutexDelete(int AMutexID) { ix_Mutex[AMutexID] = 0; } void VaU3_MutexLock(int AMutexID) { ix_Mutex[AMutexID] = 2; } BOOL VaU3_MutexLocked(int AMutexID) { return ix_Mutex[AMutexID] == 2; } void VaU3_CloseThreadHandle(HANDLE *AThread, int ADelay) { HANDLE qHandle = *AThread; if (qHandle) { *AThread = NULL; if (WaitForSingleObject(qHandle, ADelay) == WAIT_TIMEOUT) TerminateThread(qHandle, 255); CloseHandle(qHandle); }; } void CreateDir(TCHAR* Path) { TCHAR DirName[256]; TCHAR* p = Path; TCHAR* q = DirName; while (*p) { if (('\\' == *p) || ('/' == *p)) { if (':' != *(p - 1)) CreateDirectory(DirName, NULL); } *q++ = *p++; *q = '\0'; } CreateDirectory(DirName, NULL); } int CropFrame(UINT16* Src, UINT16* Dst, tVaU_ImgDim* pImgDim) { if ((pImgDim->rFrameHeight - pImgDim->rImgCutBottom - pImgDim->rImgCutTop) <= 0) return 0; if ((pImgDim->rFrameWidth - pImgDim->rImgCutLeft - pImgDim->rImgCutRight) <= 0) return 0; UINT16 *rowSrc, *rowDst; int widthCropped = pImgDim->rFrameWidth - pImgDim->rImgCutLeft - pImgDim->rImgCutRight; for (int y = pImgDim->rImgCutTop; y < (pImgDim->rFrameHeight - pImgDim->rImgCutBottom); y++) { rowSrc = (Src + (pImgDim->rFrameWidth * y) + pImgDim->rImgCutLeft); rowDst = (Dst + (widthCropped * (y - pImgDim->rImgCutTop))); memcpy_s(rowDst, sizeof(UINT16)*widthCropped, rowSrc, sizeof(UINT16)*widthCropped); } return 0; }
[ "nhpark@DESKTOP-F13BD6F" ]
nhpark@DESKTOP-F13BD6F
797f0ca69040d4f031ccbcf79ab26195a1ef2da7
f299ad78e0760d64dc2a9cb78ccba99f0f5353de
/src/RDSParser.cpp
3752ad231fe4670c89fbe8a445dcfb894bc378be
[ "BSD-3-Clause" ]
permissive
mathertel/Radio
20f98fc4afe64cffb7a8134b31d38e95b1138f28
470badc405b07cb52340c860024bc84027fe1e46
refs/heads/master
2023-02-13T18:12:54.391452
2023-02-11T15:03:15
2023-02-11T15:03:15
23,551,116
274
101
BSD-3-Clause
2023-02-03T19:02:28
2014-09-01T18:05:11
C++
UTF-8
C++
false
false
5,702
cpp
/// /// \file RDSParser.cpp /// \brief RDS Parser class implementation. /// /// \author Matthias Hertel, http://www.mathertel.de /// \copyright Copyright (c) 2014 by Matthias Hertel.\n /// This work is licensed under a BSD style license.\n /// See http://www.mathertel.de/License.aspx /// /// \details /// /// More documentation and source code is available at http://www.mathertel.de/Arduino /// /// ChangeLog see RDSParser.h. #include "RDSParser.h" #define DEBUG_FUNC0(fn) \ { \ Serial.print(fn); \ Serial.println("()"); \ } /// Setup the RDS object and initialize private variables to 0. RDSParser::RDSParser() { memset(this, 0, sizeof(RDSParser)); } // RDSParser() void RDSParser::init() { strcpy(_PSName1, "11111111"); strcpy(_PSName2, "22222222"); strcpy(_PSName3, "33333333"); strcpy(programServiceName, " "); strcpy(lastServiceName, " "); memset(_RDSText, 0, sizeof(_RDSText)); _lastTextIDX = 0; } // init() void RDSParser::attachServiceNameCallback(receiveServiceNameFunction newFunction) { _sendServiceName = newFunction; } // attachServiceNameCallback void RDSParser::attachTextCallback(receiveTextFunction newFunction) { _sendText = newFunction; } // attachTextCallback void RDSParser::attachTimeCallback(receiveTimeFunction newFunction) { _sendTime = newFunction; } // attachTimeCallback void RDSParser::processData(uint16_t block1, uint16_t block2, uint16_t block3, uint16_t block4) { // DEBUG_FUNC0("process"); uint8_t idx; // index of rdsText char c1, c2; uint16_t mins; ///< RDS time in minutes uint8_t off; ///< RDS time offset and sign // Serial.print('('); Serial.print(block1, HEX); Serial.print(' '); Serial.print(block2, HEX); Serial.print(' '); Serial.print(block3, HEX); Serial.print(' '); Serial.println(block4, HEX); if (block1 == 0) { // reset all the RDS info. init(); // Send out empty data if (_sendServiceName) _sendServiceName(programServiceName); if (_sendText) _sendText(""); return; } // if // analyzing Block 2 rdsGroupType = 0x0A | ((block2 & 0xF000) >> 8) | ((block2 & 0x0800) >> 11); rdsTP = (block2 & 0x0400); rdsPTY = (block2 & 0x0400); switch (rdsGroupType) { case 0x0A: case 0x0B: // The data received is part of the Service Station Name idx = 2 * (block2 & 0x0003); // idx = 0, 2, 4, 6 // new data is 2 chars from block 4 c1 = block4 >> 8; c2 = block4 & 0x00FF; // Serial.printf(">%d %c%c %02x %02x\n", idx, c1, c2, c1, c2); // shift new data into _PSNameN _PSName3[idx] = _PSName2[idx]; _PSName2[idx] = _PSName1[idx]; _PSName1[idx] = c1; _PSName3[idx+1] = _PSName2[idx+1]; _PSName2[idx+1] = _PSName1[idx+1]; _PSName1[idx+1] = c2; // check that the data was received successfully twice // before publishing the station name if (idx == 6) { bool isGood = true; // create programServiceName with 2 of 3 for (int n= 0; n < 8; n++) { if ((_PSName1[n] == _PSName2[n]) || (_PSName1[n] == _PSName3[n])) { programServiceName[n] = _PSName1[n]; } else if (_PSName2[n] == _PSName3[n]) { programServiceName[n] = _PSName2[n]; } else { isGood = false; } } if ((isGood) && (strcmp(lastServiceName, programServiceName) != 0)) { strcpy(lastServiceName, programServiceName); if (_sendServiceName) _sendServiceName(programServiceName); } } // if break; case 0x2A: // The data received is part of the RDS Text. _textAB = (block2 & 0x0010); idx = 4 * (block2 & 0x000F); if (idx < _lastTextIDX) { // the existing text might be complete because the index is starting at the beginning again. // now send it to the possible listener. if (_sendText) _sendText(_RDSText); } _lastTextIDX = idx; if (_textAB != _last_textAB) { // when this bit is toggled the whole buffer should be cleared. _last_textAB = _textAB; memset(_RDSText, 0, sizeof(_RDSText)); // Serial.println("T>CLEAR"); } // if // new data is 2 chars from block 3 _RDSText[idx] = (block3 >> 8); idx++; _RDSText[idx] = (block3 & 0x00FF); idx++; // new data is 2 chars from block 4 _RDSText[idx] = (block4 >> 8); idx++; _RDSText[idx] = (block4 & 0x00FF); idx++; // Serial.print(' '); Serial.println(_RDSText); // Serial.print("T>"); Serial.println(_RDSText); break; case 0x4A: // Clock time and date off = (block4)&0x3F; // 6 bits mins = (block4 >> 6) & 0x3F; // 6 bits mins += 60 * (((block3 & 0x0001) << 4) | ((block4 >> 12) & 0x0F)); // adjust offset if (off & 0x20) { mins -= 30 * (off & 0x1F); } else { mins += 30 * (off & 0x1F); } if ((_sendTime) && (mins != _lastRDSMinutes)) { _lastRDSMinutes = mins; _sendTime(mins / 60, mins % 60); } // if break; case 0x6A: // IH break; case 0x8A: // TMC break; case 0xAA: // TMC break; case 0xCA: // TMC break; case 0xEA: // IH break; default: // Serial.print("RDS_GRP:"); Serial.println(rdsGroupType, HEX); break; } } // processData() // End.
[ "mathertel@hotmail.com" ]
mathertel@hotmail.com
30b3c7d54d1c1210d296287bc65e31b594a6f02b
bbeaadef08cccb872c9a1bb32ebac7335d196318
/Fontes/Patamar/TFormPatamar.h
c3eb60a9132d04bbc2c22734a6e1a06442ad7c9b
[]
no_license
danilodesouzapereira/plataformasinap_exportaopendss
d0e529b493f280aefe91b37e893359a373557ef8
c624e9e078dce4b9bcc8e5b03dd4d9ea71c29b3f
refs/heads/master
2023-03-20T20:37:21.948550
2021-03-12T17:53:12
2021-03-12T17:53:12
347,150,304
0
0
null
null
null
null
ISO-8859-2
C++
false
false
2,815
h
//--------------------------------------------------------------------------- #ifndef TFormPatamarH #define TFormPatamarH //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <ActnList.hpp> #include <ComCtrls.hpp> #include <ExtCtrls.hpp> #include <ImgList.hpp> #include <ToolWin.hpp> #include <CheckLst.hpp> #include <Grids.hpp> #include <System.Actions.hpp> #include <System.ImageList.hpp> //--------------------------------------------------------------------------- class VTApl; class VTPatamar; //--------------------------------------------------------------------------- class TFormPatamar : public TForm { __published: // IDE-managed Components TRadioGroup *RGroupPatamares; TToolBar *ToolBar1; TToolButton *butConfirma; TToolButton *butCancela; TImageList *ImageList1; TActionList *ActionList1; TAction *ActionCancela; TAction *ActionConfirma; TAction *ActionEnablePatamar; TAction *ActionDisablePatamar; TPageControl *PageControl; TTabSheet *TabSheetHoraCal; TTabSheet *TabSheetHabilita; TGroupBox *GroupBoxHabilitar; TCheckListBox *CLBoxPatamar; TToolBar *ToolBarPatamar; TToolButton *ToolButton1; TToolButton *ToolButton2; TStringGrid *StringGridConfig; void __fastcall ActionCancelaExecute(TObject *Sender); void __fastcall ActionConfirmaExecute(TObject *Sender); void __fastcall RGroupPatamaresClick(TObject *Sender); void __fastcall ActionEnablePatamarExecute(TObject *Sender); void __fastcall ActionDisablePatamarExecute(TObject *Sender); void __fastcall CLBoxPatamarClickCheck(TObject *Sender); public: // User declarations __fastcall TFormPatamar(TComponent* Owner, VTApl *apl); __fastcall ~TFormPatamar(void); private: //métodos bool __fastcall AtualizaPatamar(VTPatamar *patamar, TDateTime date_time_ini,TDateTime date_time_fim,TDateTime date_time_cal); void __fastcall CLBoxPatamarInicia(void); void __fastcall CriaPatamares(void); void __fastcall FormIniciaPosicao(void); void __fastcall LimpaTStringGrid(TStringGrid *StringGrid); void __fastcall RGroupPatamarInicia(void); bool __fastcall SalvaPatamares(void); bool __fastcall SalvaValores(void); bool __fastcall SalvaValoresInfoset(AnsiString nome_pat, TDateTime date_time_ini,TDateTime date_time_fim,TDateTime date_time_cal); void __fastcall StringGridConfigInicia(void); bool __fastcall ValidaHoraMinutoCalculo(VTPatamar *patamar, TDateTime date_time_cal); bool __fastcall ValidaValores(AnsiString *pat1, AnsiString *pat2); private: //objetos externos VTApl *apl; private: //dados locais TList *lisPAT; }; //--------------------------------------------------------------------------- #endif //eof
[ "danilopereira@usp.br" ]
danilopereira@usp.br
6143f3d82fc58dc22669d41a127e4d47c562d521
10883f9d5286249c155c01292e090320e09da1f7
/DeviceGateway/serialport/myserialport.h
e4ac4a3f6210c1737585790824245bd9b93c1744
[]
no_license
ZJPJAY/QT_Quick_Project
004bb1b52640704ef8cebfd5e34d25cbd1c6e6a6
e00ebc40912adacc00fd336684a29963fedbe761
refs/heads/main
2023-06-16T22:01:29.547663
2021-07-16T13:32:28
2021-07-16T13:32:28
384,033,166
0
0
null
null
null
null
UTF-8
C++
false
false
1,375
h
#ifndef MYSERIALPORT_H #define MYSERIALPORT_H #include <QSerialPort> #include <QTimer> #include <QStringList> class MySerialPort : public QSerialPort { Q_OBJECT protected: explicit MySerialPort(QObject *parent = nullptr); public: static MySerialPort *getObject(); QStringList getPortList(); void requestTeAndHu(); void requestLig(); void requestUlt(); void requestCo2(); void requestPm(); void controlLight(unsigned char con);//开关警报灯 void controlAlert(unsigned char con);//开关警报铃 protected slots: void readyReadSlot(); void sendTimeoutSlot(); void appendTimeoutSlot(); //void pushTimeroutSlot();若数据都在一个表里面使用这个定时信号槽函数 protected: static MySerialPort *mspObj; void handleData(QByteArray data);//解析传输数据格式 void handleFrame(QByteArray data);//解析数据内容 QByteArray temp;//缓冲区 QList<QByteArray> sendList; QTimer *sendTimer; QTimer *appendTimer; //QTimer *pushTimer;若数据都在一个表里面使用这个定时器,时间为上面appendTimer的时间间隔,一次性发送所有数据 double te; double hu; double lig; int co2; int ur; int pm; signals: public slots: }; #endif // MYSERIALPORT_H
[ "563902816@qq.com" ]
563902816@qq.com
e6fb6f4685c46f5af54a6ab2ebb93dc2201a4ff9
c8cadfa6aca222ac8d7f8f54c9c18c6fa463309a
/zlibrary/core/src/language/ZLLanguageDetector.h
44435adf900a370b1370d31d7adf6fae1a5db518
[]
no_license
justsoso8/fbreader-0.8.17
9f402e4796b5d9eb0eb008d40f38d28f19a73cfa
9aab2bbcb3db1ac0c4927919cdcfd24cfa2abe4b
refs/heads/master
2021-01-22T23:21:22.120929
2010-11-11T03:59:00
2010-11-11T03:59:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,594
h
/* * Copyright (C) 2007-2008 Geometer Plus <contact@geometerplus.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #ifndef __ZLLANGUAGEDETECTOR_H__ #define __ZLLANGUAGEDETECTOR_H__ #include <vector> #include <string> #include <shared_ptr.h> class ZLWordBasedMatcher; class ZLChineseMatcher; class ZLLanguageDetector { public: struct LanguageInfo { LanguageInfo(const std::string &language, const std::string &encoding); const std::string Language; const std::string Encoding; }; public: ZLLanguageDetector(); ~ZLLanguageDetector(); shared_ptr<LanguageInfo> findInfo(const char *buffer, size_t length, int matchingCriterion = 0); private: typedef std::vector<shared_ptr<ZLWordBasedMatcher> > WBVector; typedef std::vector<shared_ptr<ZLChineseMatcher> > ZHVector; WBVector myUtf8Matchers; WBVector myNonUtf8Matchers; ZHVector myChineseMatchers; }; #endif /* __ZLLANGUAGEDETECTOR_H__ */
[ "Justsoso8@gmail.com" ]
Justsoso8@gmail.com
f1b2d8711664ef90eded1c74bd147f3a1e32ad0c
659d99d090479506b63b374831a049dba5d70fcf
/xray-svn-trunk/xrNetServer/NET_Client.cpp
96b27ed91435f13d94683fa52958d3ac65daa281
[]
no_license
ssijonson/Rengen_Luch
a9312fed06dd08c7de19f36e5fd5e476881beb85
9bd0ff54408a890d4bdac1c493d67ce26b964555
refs/heads/main
2023-05-03T13:09:58.983176
2021-05-19T10:04:47
2021-05-19T10:04:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,620
cpp
#include "stdafx.h" #include "NET_Common.h" #include "net_client.h" #include "net_server.h" #include "net_messages.h" #include "NET_Log.h" #pragma warning(push) #pragma warning(disable:4995) #include <malloc.h> #include "dxerr.h" //#pragma warning(pop) // {0218FA8B-515B-4bf2-9A5F-2F079D1759F3} static const GUID NET_GUID = { 0x218fa8b, 0x515b, 0x4bf2, { 0x9a, 0x5f, 0x2f, 0x7, 0x9d, 0x17, 0x59, 0xf3 } }; // {8D3F9E5E-A3BD-475b-9E49-B0E77139143C} static const GUID CLSID_NETWORKSIMULATOR_DP8SP_TCPIP = { 0x8d3f9e5e, 0xa3bd, 0x475b, { 0x9e, 0x49, 0xb0, 0xe7, 0x71, 0x39, 0x14, 0x3c } }; const GUID CLSID_DirectPlay8Client = { 0x743f1dc6, 0x5aba, 0x429f, { 0x8b, 0xdf, 0xc5, 0x4d, 0x03, 0x25, 0x3d, 0xc2 } }; // {DA825E1B-6830-43d7-835D-0B5AD82956A2} const GUID CLSID_DirectPlay8Server = { 0xda825e1b, 0x6830, 0x43d7, { 0x83, 0x5d, 0x0b, 0x5a, 0xd8, 0x29, 0x56, 0xa2 } }; // {286F484D-375E-4458-A272-B138E2F80A6A} const GUID CLSID_DirectPlay8Peer = { 0x286f484d, 0x375e, 0x4458, { 0xa2, 0x72, 0xb1, 0x38, 0xe2, 0xf8, 0x0a, 0x6a } }; // CLSIDs added for DirectX 9 // {FC47060E-6153-4b34-B975-8E4121EB7F3C} const GUID CLSID_DirectPlay8ThreadPool = { 0xfc47060e, 0x6153, 0x4b34, { 0xb9, 0x75, 0x8e, 0x41, 0x21, 0xeb, 0x7f, 0x3c } }; // {E4C1D9A2-CBF7-48bd-9A69-34A55E0D8941} const GUID CLSID_DirectPlay8NATResolver = { 0xe4c1d9a2, 0xcbf7, 0x48bd, { 0x9a, 0x69, 0x34, 0xa5, 0x5e, 0x0d, 0x89, 0x41 } }; /**************************************************************************** * * DirectPlay8 Interface IIDs * ****************************************************************************/ typedef REFIID DP8REFIID; // {5102DACD-241B-11d3-AEA7-006097B01411} const GUID IID_IDirectPlay8Client = { 0x5102dacd, 0x241b, 0x11d3, { 0xae, 0xa7, 0x00, 0x60, 0x97, 0xb0, 0x14, 0x11 } }; // {5102DACE-241B-11d3-AEA7-006097B01411} const GUID IID_IDirectPlay8Server = { 0x5102dace, 0x241b, 0x11d3, { 0xae, 0xa7, 0x00, 0x60, 0x97, 0xb0, 0x14, 0x11 } }; // {5102DACF-241B-11d3-AEA7-006097B01411} const GUID IID_IDirectPlay8Peer = { 0x5102dacf, 0x241b, 0x11d3, { 0xae, 0xa7, 0x00, 0x60, 0x97, 0xb0, 0x14, 0x11 } }; // IIDs added for DirectX 9 // {0D22EE73-4A46-4a0d-89B2-045B4D666425} const GUID IID_IDirectPlay8ThreadPool = { 0xd22ee73, 0x4a46, 0x4a0d, { 0x89, 0xb2, 0x04, 0x5b, 0x4d, 0x66, 0x64, 0x25 } }; // {A9E213F2-9A60-486f-BF3B-53408B6D1CBB} const GUID IID_IDirectPlay8NATResolver = { 0xa9e213f2, 0x9a60, 0x486f, { 0xbf, 0x3b, 0x53, 0x40, 0x8b, 0x6d, 0x1c, 0xbb } }; // {53934290-628D-11D2-AE0F-006097B01411} const GUID CLSID_DP8SP_IPX = { 0x53934290, 0x628d, 0x11d2, { 0xae, 0x0f, 0x00, 0x60, 0x97, 0xb0, 0x14, 0x11 } }; // {6D4A3650-628D-11D2-AE0F-006097B01411} const GUID CLSID_DP8SP_MODEM = { 0x6d4a3650, 0x628d, 0x11d2, { 0xae, 0x0f, 0x00, 0x60, 0x97, 0xb0, 0x14, 0x11 } }; // {743B5D60-628D-11D2-AE0F-006097B01411} const GUID CLSID_DP8SP_SERIAL = { 0x743b5d60, 0x628d, 0x11d2, { 0xae, 0x0f, 0x00, 0x60, 0x97, 0xb0, 0x14, 0x11 } }; // {EBFE7BA0-628D-11D2-AE0F-006097B01411} const GUID CLSID_DP8SP_TCPIP = { 0xebfe7ba0, 0x628d, 0x11d2, { 0xae, 0x0f, 0x00, 0x60, 0x97, 0xb0, 0x14, 0x11 } }; // Service providers added for DirectX 9 // {995513AF-3027-4b9a-956E-C772B3F78006} const GUID CLSID_DP8SP_BLUETOOTH = { 0x995513af, 0x3027, 0x4b9a, { 0x95, 0x6e, 0xc7, 0x72, 0xb3, 0xf7, 0x80, 0x06 } }; const GUID CLSID_DirectPlay8Address = { 0x934a9523, 0xa3ca, 0x4bc5, { 0xad, 0xa0, 0xd6, 0xd9, 0x5d, 0x97, 0x94, 0x21 } }; const GUID IID_IDirectPlay8Address = { 0x83783300, 0x4063, 0x4c8a, { 0x9d, 0xb3, 0x82, 0x83, 0x0a, 0x7f, 0xeb, 0x31 } }; static INetLog* pClNetLog = NULL; void dump_URL (LPCSTR p, IDirectPlay8Address* A) { string256 aaaa; DWORD aaaa_s = sizeof(aaaa); R_CHK (A->GetURLA(aaaa,&aaaa_s)); Log (p,aaaa); } // INetQueue::INetQueue() { unused.reserve (128); for (int i=0; i<16; i++) unused.push_back (xr_new <NET_Packet>()); } INetQueue::~INetQueue() { cs.Enter (); u32 it; for (it=0; it<unused.size(); it++) xr_delete(unused[it]); for (it=0; it<ready.size(); it++) xr_delete(ready[it]); cs.Leave (); } static u32 LastTimeCreate = 0; NET_Packet* INetQueue::Create () { NET_Packet* P = 0; //cs.Enter (); //#ifdef _DEBUG // Msg ("- INetQueue::Create - ready %d, unused %d", ready.size(), unused.size()); //#endif if (unused.empty()) { ready.push_back (xr_new <NET_Packet> ()); P = ready.back (); //--------------------------------------------- LastTimeCreate = GetTickCount(); //--------------------------------------------- } else { ready.push_back (unused.back()); unused.pop_back (); P = ready.back (); } //cs.Leave (); return P; } NET_Packet* INetQueue::Create (const NET_Packet& _other) { NET_Packet* P = 0; cs.Enter (); //#ifdef _DEBUG // Msg ("- INetQueue::Create - ready %d, unused %d", ready.size(), unused.size()); //#endif if (unused.empty()) { ready.push_back (xr_new <NET_Packet>()); P = ready.back (); //--------------------------------------------- LastTimeCreate = GetTickCount(); //--------------------------------------------- } else { ready.push_back (unused.back()); unused.pop_back (); P = ready.back (); } CopyMemory (P,&_other,sizeof(NET_Packet)); cs.Leave (); return P; } NET_Packet* INetQueue::Retreive () { NET_Packet* P = 0; //cs.Enter (); //#ifdef _DEBUG // Msg ("INetQueue::Retreive - ready %d, unused %d", ready.size(), unused.size()); //#endif if (!ready.empty()) P = ready.front(); //--------------------------------------------- else { u32 tmp_time = GetTickCount()-60000; u32 size = unused.size(); if ((LastTimeCreate < tmp_time) && (size > 32)) { xr_delete(unused.back()); unused.pop_back(); } } //--------------------------------------------- //cs.Leave (); return P; } void INetQueue::Release () { //cs.Enter (); //#ifdef _DEBUG // Msg ("INetQueue::Release - ready %d, unused %d", ready.size(), unused.size()); //#endif VERIFY (!ready.empty()); //--------------------------------------------- u32 tmp_time = GetTickCount()-60000; u32 size = unused.size(); ready.front()->B.count = 0; if ((LastTimeCreate < tmp_time) && (size > 32)) { xr_delete(ready.front()); } else unused.push_back(ready.front()); //--------------------------------------------- ready.pop_front (); //cs.Leave (); } // const u32 syncQueueSize = 512; const int syncSamples = 256; class XRNETSERVER_API syncQueue { u32 table [syncQueueSize]; u32 write; u32 count; public: syncQueue() { clear(); } IC void push (u32 value) { table[write++] = value; if (write == syncQueueSize) write = 0; if (count <= syncQueueSize) count++; } IC u32* begin () { return table; } IC u32* end () { return table+count; } IC u32 size () { return count; } IC void clear () { write=0; count=0; } } net_DeltaArray; //------- XRNETSERVER_API Flags32 psNET_Flags = {0}; /**************************************************************************** * * DirectPlay8 Service Provider GUIDs * ****************************************************************************/ void IPureClient::_SendTo_LL( const void* data, u32 size, u32 flags, u32 timeout ) { IPureClient::SendTo_LL( const_cast<void*>(data), size, flags, timeout ); } //------------------------------------------------------------------------------ void IPureClient::_Recieve( const void* data, u32 data_size, u32 /*param*/ ) { MSYS_PING* cfg = (MSYS_PING*)data; net_Statistic.dwBytesReceived += data_size; if( (data_size>=2*sizeof(u32)) && (cfg->sign1==0x12071980) && (cfg->sign2==0x26111975) ) { // Internal system message if( (data_size == sizeof(MSYS_PING)) ) { // It is reverted(server) ping u32 time = TimerAsync( device_timer ); u32 ping = time - (cfg->dwTime_ClientSend); u32 delta = cfg->dwTime_Server + ping/2 - time; net_DeltaArray.push ( delta ); Sync_Average (); return; } if ( data_size == sizeof(MSYS_CONFIG) ) { net_Connected = EnmConnectionCompleted; return; } Msg( "! Unknown system message" ); return; } else if( net_Connected == EnmConnectionCompleted ) { // one of the messages - decompress it if( psNET_Flags.test( NETFLAG_LOG_CL_PACKETS ) ) { if( !pClNetLog ) pClNetLog = xr_new <INetLog>("logs\\net_cl_log.log", timeServer()); if( pClNetLog ) pClNetLog->LogData( timeServer(), const_cast<void*>(data), data_size, TRUE ); } OnMessage( const_cast<void*>(data), data_size ); } } //============================================================================== IPureClient::IPureClient (CTimer* timer): net_Statistic(timer) { NET = NULL; net_Address_server = NULL; net_Address_device = NULL; device_timer = timer; net_TimeDelta_User = 0; net_Time_LastUpdate = 0; net_TimeDelta = 0; net_TimeDelta_Calculated = 0; pClNetLog = NULL;//xr_new<INetLog>("logs\\net_cl_log.log", timeServer()); } IPureClient::~IPureClient () { xr_delete(pClNetLog); pClNetLog = NULL; } BOOL IPureClient::Connect (LPCSTR options) { R_ASSERT (options); net_Disconnected = FALSE; // Sync net_TimeDelta = 0; return TRUE; } void IPureClient::Disconnect() { if( NET ) NET->Close(0); // Clean up Host _list_ net_csEnumeration.Enter (); for (u32 i=0; i<net_Hosts.size(); i++) { HOST_NODE& N = net_Hosts[i]; _RELEASE (N.pHostAddress); } net_Hosts.clear (); net_csEnumeration.Leave (); // Release interfaces _SHOW_REF ("cl_netADR_Server",net_Address_server); _RELEASE (net_Address_server); _SHOW_REF ("cl_netADR_Device",net_Address_device); _RELEASE (net_Address_device); _SHOW_REF ("cl_netCORE",NET); _RELEASE (NET); net_Connected = EnmConnectionWait; net_Syncronised = FALSE; } HRESULT IPureClient::net_Handler(u32 dwMessageType, PVOID pMessage) { // HRESULT hr = S_OK; switch (dwMessageType) { case DPN_MSGID_ENUM_HOSTS_RESPONSE: { PDPNMSG_ENUM_HOSTS_RESPONSE pEnumHostsResponseMsg; const DPN_APPLICATION_DESC* pDesc; // HOST_NODE* pHostNode = NULL; // WCHAR* pwszSession = NULL; pEnumHostsResponseMsg = (PDPNMSG_ENUM_HOSTS_RESPONSE) pMessage; pDesc = pEnumHostsResponseMsg->pApplicationDescription; if (pDesc->dwApplicationReservedDataSize && pDesc->pvApplicationReservedData) { R_ASSERT(pDesc->dwApplicationReservedDataSize == sizeof(m_game_description)); CopyMemory(&m_game_description, pDesc->pvApplicationReservedData, pDesc->dwApplicationReservedDataSize); } // Insert each host response if it isn't already present net_csEnumeration.Enter (); BOOL bHostRegistered = FALSE; for (u32 I=0; I<net_Hosts.size(); I++) { HOST_NODE& N = net_Hosts [I]; if ( pDesc->guidInstance == N.dpAppDesc.guidInstance) { // This host is already in the list bHostRegistered = TRUE; break; } } if (!bHostRegistered) { // This host session is not in the list then so insert it. HOST_NODE NODE; ZeroMemory (&NODE, sizeof(HOST_NODE)); // Copy the Host Address R_CHK (pEnumHostsResponseMsg->pAddressSender->Duplicate(&NODE.pHostAddress ) ); CopyMemory(&NODE.dpAppDesc,pDesc,sizeof(DPN_APPLICATION_DESC)); // Null out all the pointers we aren't copying NODE.dpAppDesc.pwszSessionName = NULL; NODE.dpAppDesc.pwszPassword = NULL; NODE.dpAppDesc.pvReservedData = NULL; NODE.dpAppDesc.dwReservedDataSize = 0; NODE.dpAppDesc.pvApplicationReservedData = NULL; NODE.dpAppDesc.dwApplicationReservedDataSize = 0; if( pDesc->pwszSessionName) { string4096 dpSessionName; R_CHK (WideCharToMultiByte(CP_ACP,0,pDesc->pwszSessionName,-1,dpSessionName,sizeof(dpSessionName),0,0)); NODE.dpSessionName = (char*)(&dpSessionName[0]); } net_Hosts.push_back (NODE); } net_csEnumeration.Leave (); } break; case DPN_MSGID_RECEIVE: { PDPNMSG_RECEIVE pMsg = (PDPNMSG_RECEIVE) pMessage; MultipacketReciever::RecievePacket( pMsg->pReceiveData, pMsg->dwReceiveDataSize ); } break; case DPN_MSGID_TERMINATE_SESSION: { PDPNMSG_TERMINATE_SESSION pMsg = (PDPNMSG_TERMINATE_SESSION ) pMessage; char* m_data = (char*)pMsg->pvTerminateData; u32 m_size = pMsg->dwTerminateDataSize; HRESULT m_hResultCode = pMsg->hResultCode; net_Disconnected = TRUE; if (m_size != 0) { OnSessionTerminate(m_data); #ifdef DEBUG Msg("- Session terminated : %s", m_data); #endif } else { #ifdef DEBUG OnSessionTerminate( (::Debug.error2string(m_hResultCode))); Msg("- Session terminated : %s", (::Debug.error2string(m_hResultCode))); #endif } }; break; default: { #if 1 LPSTR msg = ""; switch (dwMessageType) { case DPN_MSGID_ADD_PLAYER_TO_GROUP: msg = "DPN_MSGID_ADD_PLAYER_TO_GROUP"; break; case DPN_MSGID_ASYNC_OP_COMPLETE: msg = "DPN_MSGID_ASYNC_OP_COMPLETE"; break; case DPN_MSGID_CLIENT_INFO: msg = "DPN_MSGID_CLIENT_INFO"; break; case DPN_MSGID_CONNECT_COMPLETE: { PDPNMSG_CONNECT_COMPLETE pMsg = (PDPNMSG_CONNECT_COMPLETE)pMessage; #ifdef DEBUG // const char* x = DXGetErrorString9(pMsg->hResultCode); if (pMsg->hResultCode != S_OK) { string1024 tmp=""; DXTRACE_ERR(tmp, pMsg->hResultCode); } #endif if (pMsg->dwApplicationReplyDataSize) { string256 ResStr = ""; strncpy_s(ResStr, (char*)(pMsg->pvApplicationReplyData), pMsg->dwApplicationReplyDataSize); Msg("Connection result : %s", ResStr); } else msg = "DPN_MSGID_CONNECT_COMPLETE"; }break; case DPN_MSGID_CREATE_GROUP: msg = "DPN_MSGID_CREATE_GROUP"; break; case DPN_MSGID_CREATE_PLAYER: msg = "DPN_MSGID_CREATE_PLAYER"; break; case DPN_MSGID_DESTROY_GROUP: msg = "DPN_MSGID_DESTROY_GROUP"; break; case DPN_MSGID_DESTROY_PLAYER: msg = "DPN_MSGID_DESTROY_PLAYER"; break; case DPN_MSGID_ENUM_HOSTS_QUERY: msg = "DPN_MSGID_ENUM_HOSTS_QUERY"; break; case DPN_MSGID_GROUP_INFO: msg = "DPN_MSGID_GROUP_INFO"; break; case DPN_MSGID_HOST_MIGRATE: msg = "DPN_MSGID_HOST_MIGRATE"; break; case DPN_MSGID_INDICATE_CONNECT: msg = "DPN_MSGID_INDICATE_CONNECT"; break; case DPN_MSGID_INDICATED_CONNECT_ABORTED: msg = "DPN_MSGID_INDICATED_CONNECT_ABORTED"; break; case DPN_MSGID_PEER_INFO: msg = "DPN_MSGID_PEER_INFO"; break; case DPN_MSGID_REMOVE_PLAYER_FROM_GROUP: msg = "DPN_MSGID_REMOVE_PLAYER_FROM_GROUP"; break; case DPN_MSGID_RETURN_BUFFER: msg = "DPN_MSGID_RETURN_BUFFER"; break; case DPN_MSGID_SEND_COMPLETE: msg = "DPN_MSGID_SEND_COMPLETE"; break; case DPN_MSGID_SERVER_INFO: msg = "DPN_MSGID_SERVER_INFO"; break; case DPN_MSGID_TERMINATE_SESSION: msg = "DPN_MSGID_TERMINATE_SESSION"; break; default: msg = "???"; break; } //Msg("! ************************************ : %s",msg); #endif } break; } return S_OK; } void IPureClient::OnMessage(void* data, u32 size) { // One of the messages - decompress it net_Queue.Lock(); NET_Packet* P = net_Queue.Create(); P->construct( data, size ); P->timeReceive = timeServer_Async();//TimerAsync (device_timer); u16 m_type; P->r_begin (m_type); net_Queue.Unlock(); } void IPureClient::timeServer_Correct(u32 sv_time, u32 cl_time) { u32 ping = net_Statistic.getPing(); u32 delta = sv_time + ping/2 - cl_time; net_DeltaArray.push (delta); Sync_Average (); } void IPureClient::SendTo_LL(void* data, u32 size, u32 dwFlags, u32 dwTimeout) { if( net_Disconnected ) return; if( psNET_Flags.test(NETFLAG_LOG_CL_PACKETS) ) { if( !pClNetLog) pClNetLog = xr_new <INetLog>( "logs\\net_cl_log.log", timeServer() ); if( pClNetLog ) pClNetLog->LogData( timeServer(), data, size ); } DPN_BUFFER_DESC desc; desc.dwBufferSize = size; desc.pBufferData = (BYTE*)data; net_Statistic.dwBytesSended += size; // verify VERIFY(desc.dwBufferSize); VERIFY(desc.pBufferData); VERIFY(NET); DPNHANDLE hAsync = 0; HRESULT hr = NET->Send( &desc, 1, dwTimeout, 0, &hAsync, dwFlags | DPNSEND_COALESCE ); // Msg("- Client::SendTo_LL [%d]", size); if( FAILED(hr) ) { Msg ("! ERROR: Failed to send net-packet, reason: %s",::Debug.error2string(hr)); // const char* x = DXGetErrorString9(hr); string1024 tmp=""; DXTRACE_ERR(tmp, hr); } } void IPureClient::Send( NET_Packet& packet, u32 dwFlags, u32 dwTimeout ) { MultipacketSender::SendPacket( packet.B.data, packet.B.count, dwFlags, dwTimeout ); } void IPureClient::Flush_Send_Buffer () { MultipacketSender::FlushSendBuffer( 0 ); } void IPureClient::Sync_Thread () { MSYS_PING clPing; //***** Ping server net_DeltaArray.clear(); R_ASSERT (NET); for (; NET && !net_Disconnected; ) { // Waiting for queue empty state if (net_Syncronised) break; // Sleep(2000); else { DWORD dwPending=0; do { R_CHK (NET->GetSendQueueInfo(&dwPending,0,0)); Sleep (1); } while (dwPending); } // Construct message clPing.sign1 = 0x12071980; clPing.sign2 = 0x26111975; clPing.dwTime_ClientSend = TimerAsync(device_timer); // Send it __try { DPN_BUFFER_DESC desc; DPNHANDLE hAsync=0; desc.dwBufferSize = sizeof(clPing); desc.pBufferData = LPBYTE(&clPing); if (0==NET || net_Disconnected) break; if (FAILED(NET->Send(&desc,1,0,0,&hAsync,net_flags(FALSE,FALSE,TRUE)))) { Msg("* CLIENT: SyncThread: EXIT. (failed to send - disconnected?)"); break; } } __except (EXCEPTION_EXECUTE_HANDLER) { Msg("* CLIENT: SyncThread: EXIT. (failed to send - disconnected?)"); break; } // Waiting for reply-packet to arrive if (!net_Syncronised) { u32 old_size = net_DeltaArray.size(); u32 timeBegin = TimerAsync(device_timer); while ((net_DeltaArray.size()==old_size)&&(TimerAsync(device_timer)-timeBegin<5000)) Sleep(1); if (net_DeltaArray.size()>=syncSamples) { net_Syncronised = TRUE; net_TimeDelta = net_TimeDelta_Calculated; // Msg ("* CL_TimeSync: DELTA: %d",net_TimeDelta); } } } } void IPureClient::Sync_Average () { //***** Analyze results s64 summary_delta = 0; s32 size = net_DeltaArray.size(); u32* I = net_DeltaArray.begin(); u32* E = I+size; for (; I!=E; I++) summary_delta += *((int*)I); s64 frac = s64(summary_delta) % s64(size); if (frac<0) frac=-frac; summary_delta /= s64(size); if (frac>s64(size/2)) summary_delta += (summary_delta<0)?-1:1; net_TimeDelta_Calculated= s32(summary_delta); net_TimeDelta = (net_TimeDelta*5+net_TimeDelta_Calculated)/6; // Msg("* CLIENT: d(%d), dc(%d), s(%d)",net_TimeDelta,net_TimeDelta_Calculated,size); } void sync_thread(void* P) { SetThreadPriority (GetCurrentThread(),THREAD_PRIORITY_TIME_CRITICAL); IPureClient* C = (IPureClient*)P; C->Sync_Thread (); } void IPureClient::net_Syncronize () { net_Syncronised = FALSE; net_DeltaArray.clear(); thread_spawn (sync_thread,"network-time-sync",0,this); } BOOL IPureClient::net_IsSyncronised() { return net_Syncronised; } #include <WINSOCK2.H> #include <Ws2tcpip.h> bool IPureClient::GetServerAddress (ip_address& pAddress, DWORD* pPort) { *pPort = 0; if (!net_Address_server) return false; WCHAR wstrHostname[ 2048 ] = {0}; DWORD dwHostNameSize = sizeof(wstrHostname); DWORD dwHostNameDataType = DPNA_DATATYPE_STRING; CHK_DX(net_Address_server->GetComponentByName( DPNA_KEY_HOSTNAME, wstrHostname, &dwHostNameSize, &dwHostNameDataType )); string2048 HostName; CHK_DX(WideCharToMultiByte(CP_ACP,0,wstrHostname,-1,HostName,sizeof(HostName),0,0)); hostent* pHostEnt = gethostbyname(HostName); char* localIP; localIP = inet_ntoa (*(struct in_addr *)*pHostEnt->h_addr_list); pHostEnt = gethostbyname(pHostEnt->h_name); localIP = inet_ntoa (*(struct in_addr *)*pHostEnt->h_addr_list); pAddress.set (localIP); //. pAddress[0] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_net; //. pAddress[1] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_host; //. pAddress[2] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_lh; //. pAddress[3] = (char)(*(struct in_addr *)*pHostEnt->h_addr_list).s_impno; DWORD dwPort = 0; DWORD dwPortSize = sizeof(dwPort); DWORD dwPortDataType = DPNA_DATATYPE_DWORD; CHK_DX(net_Address_server->GetComponentByName( DPNA_KEY_PORT, &dwPort, &dwPortSize, &dwPortDataType )); *pPort = dwPort; return true; };
[ "16670637+KRodinn@users.noreply.github.com" ]
16670637+KRodinn@users.noreply.github.com
0c7e412c1bb7d289b054db0581581c8870fbda15
c6b2a8cd924e89e484a2b00b8cc5c8e8a6ed349e
/ArkTransactions.ino
13d10f5311d1f5b0c9afe4154a53534008eb6ed9
[]
no_license
PhillipJacobsen/Ark_IOT_BasicDemo1
058e1c1080d48b0f1b390d1b0cc94e53a699c87b
3fba6c96715df914f0f02ee5c5a7b18c9871c1e2
refs/heads/master
2020-05-01T12:26:10.263811
2019-03-24T23:23:28
2019-03-24T23:23:28
177,465,556
0
0
null
null
null
null
UTF-8
C++
false
false
12,202
ino
/******************************************************************************** This file contains functions that interact with Ark client C++ API code here is a hack right now. Just learning the API and working on basic program flow and function ********************************************************************************/ /******************************************************************************** This routine searches the block chain with receive address and page as input parameters It returns details for 1 transaction if available. Returns '0' if no transaction exist returns parameters in id -> transaction ID amount -> amount of Arktoshi senderAddress -> transaction sender address vendorfield -> 64 Byte vendor field ********************************************************************************/ int searchReceivedTransaction(const char *const address, int page, const char* &id, int &amount, const char* &senderAddress, const char* &vendorField ) { //Serial.print("\nSearch Received Address: "); //Serial.println(address); //Serial.print("\nSearch page: "); //Serial.println(page ); //const std::map<std::string, std::string>& body_parameters, int limit = 5, std::string vendorFieldHexString; vendorFieldHexString = "6964647955"; //std::string transactionSearchResponse = connection.api.transactions.search( {{"vendorFieldHex", vendorFieldHexString}, {"orderBy", "timestamp:asc"} },1,1); //-------------------------------------------- //peform the API //sort by oldest transactions first. For simplicity set limit = 1 so we only get 1 transaction returned std::string transactionSearchResponse = connection.api.transactions.search( {{"recipientId", address}, {"orderBy", "timestamp:asc"} }, 1, page); /** transactionSearchResponse return response is a json-formatted object The "pretty print" version would look something like this: { "meta": { "count": 1, "pageCount": 16, "totalCount": 16, "next": "/api/v2/transactions/search?page=2&limit=1", "previous": null, "self": "/api/v2/transactions/search?page=1&limit=1", "first": "/api/v2/transactions/search?page=1&limit=1", "last": "/api/v2/transactions/search?page=16&limit=1" }, "data": [ { "id": "cf1aad5e14f4edb134269e0dc7f9457093f458a9785ea03914effa3932e7dffe", "blockId": "1196453921719185829", "version": 1, "type": 0, "amount": 1000000000, "fee": 1000000, "sender": "DFcWwEGwBaYCNb1wxGErGN1TJu8QdQYgCt", "recipient": "DHy5z5XNKXhxztLDpT88iD2ozR7ab5Sw2w", "signature": "3045022100d55a219edd8690e89a368399084aa8a468629b570e332e0e618e0af83b1a474602200f57b67e628389533b78db915b1139d8529fee133b9198576b30b98ea5a1ce28", "confirmations": 21771, "timestamp": { "epoch": 62689306, "unix": 1552790506, "human": "2019-03-17T02:41:46.000Z" } } ] } */ //-------------------------------------------- // Print the entire return response string // Serial.print("\nSearch Result Transactions: "); // Serial.println(transactionSearchResponse.c_str()); // The response is a 'std::string', to Print on Arduino, we need the c_string type. //-------------------------------------------- // Deserialize the returned JSON // All of the returned parameters are parsed which is not necessary but may be usefull for testing. const size_t capacity = JSON_ARRAY_SIZE(1) + JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(8) + JSON_OBJECT_SIZE(11) + 810; DynamicJsonBuffer jsonBuffer(capacity); //this is an exapmle of the JSON string that is returned //const char* json = "{\"meta\":{\"count\":1,\"pageCount\":16,\"totalCount\":16,\"next\":\"/api/v2/transactions/search?page=2&limit=1\",\"previous\":null,\"self\":\"/api/v2/transactions/search?page=1&limit=1\",\"first\":\"/api/v2/transactions/search?page=1&limit=1\",\"last\":\"/api/v2/transactions/search?page=16&limit=1\"},\"data\":[{\"id\":\"cf1aad5e14f4edb134269e0dc7f9457093f458a9785ea03914effa3932e7dffe\",\"blockId\":\"1196453921719185829\",\"version\":1,\"type\":0,\"amount\":1000000000,\"fee\":1000000,\"sender\":\"DFcWwEGwBaYCNb1wxGErGN1TJu8QdQYgCt\",\"recipient\":\"DHy5z5XNKXhxztLDpT88iD2ozR7ab5Sw2w\",\"signature\":\"3045022100d55a219edd8690e89a368399084aa8a468629b570e332e0e618e0af83b1a474602200f57b67e628389533b78db915b1139d8529fee133b9198576b30b98ea5a1ce28\",\"confirmations\":21771,\"timestamp\":{\"epoch\":62689306,\"unix\":1552790506,\"human\":\"2019-03-17T02:41:46.000Z\"}}]}"; JsonObject& root = jsonBuffer.parseObject(transactionSearchResponse.c_str()); JsonObject& meta = root["meta"]; int meta_count = meta["count"]; // 1 int meta_pageCount = meta["pageCount"]; // 16 int meta_totalCount = meta["totalCount"]; // 16 const char* meta_next = meta["next"]; // "/api/v2/transactions/search?page=3&limit=1" const char* meta_previous = meta["previous"]; // "/api/v2/transactions/search?page=1&limit=1" const char* meta_self = meta["self"]; // "/api/v2/transactions/search?page=2&limit=1" const char* meta_first = meta["first"]; // "/api/v2/transactions/search?page=1&limit=1" const char* meta_last = meta["last"]; // "/api/v2/transactions/search?page=16&limit=1" JsonObject& data_0 = root["data"][0]; const char* data_0_id = data_0["id"]; // "8990a1c7772731c1cc8f2671f070fb7919d1cdac54dc5de619447a6e88899585" const char* data_0_blockId = data_0["blockId"]; // "3154443675765724828" int data_0_version = data_0["version"]; // 1 int data_0_type = data_0["type"]; // 0 int data_0_amount = data_0["amount"]; // 1 long data_0_fee = data_0["fee"]; // 10000000 const char* data_0_sender = data_0["sender"]; // "DFcWwEGwBaYCNb1wxGErGN1TJu8QdQYgCt" const char* data_0_recipient = data_0["recipient"]; // "DHy5z5XNKXhxztLDpT88iD2ozR7ab5Sw2w" const char* data_0_signature = data_0["signature"]; // "30450221008ef28fe9020e1dd26836fc6a1c4d576c022bde9cc14278bc4d6779339c080f7902204946a3c3b2b37fbe4767a9e3d7cb4514faf194c89595cdb280d74af52a76ad21" const char* data_0_vendorField = data_0["vendorField"]; // "e2620f612a9b9abb96fee4d03391c51e597f8ffbefd7c8db2fbf84e6a5e26c99" long data_0_confirmations = data_0["confirmations"]; // 74713 JsonObject& data_0_timestamp = data_0["timestamp"]; long data_0_timestamp_epoch = data_0_timestamp["epoch"]; // 62262442 long data_0_timestamp_unix = data_0_timestamp["unix"]; // 1552363642 const char* data_0_timestamp_human = data_0_timestamp["human"]; // "2019-03-12T04:07:22.000Z" //-------------------------------------------- // The meta parameters that are returned are currently not reliable and are "estimates". Apparently this is due to lower performance nodes // For this reason I will not use any of the meta parameters //-------------------------------------------- // the data_0_id parameter will be used to determine if a valid transaction was found. if (data_0_id == nullptr) { Serial.print("\n data_0_id is null"); return 0; //no transaction found } else { // Serial.print("\n data_0_id is available"); id = data_0_id; amount = data_0_amount; senderAddress = data_0_sender; vendorField = data_0_vendorField; } return 1; //transaction found } /******************************************************************************** This routine checks to see if Ark node is syncronized to the chain. This is a maybe a good way to see if node communication is working correctly. This might be a good routine to run periodically Returns True if node is synced ********************************************************************************/ bool checkArkNodeStatus() { /** The following method can be used to get the Status of a Node. This is equivalant to calling '167.114.29.49:4003/api/v2/node/status' The response should be a json-formatted object The "pretty print" version would look something like this: { "data": { "synced": true, "now": 1178395, "blocksCount": 0 } } */ const auto nodeStatus = connection.api.node.status(); Serial.print("\nNode Status: "); Serial.println(nodeStatus.c_str()); // The response is a 'std::string', to Print on Arduino, we need the c_string type. const size_t capacity = JSON_OBJECT_SIZE(1) + JSON_OBJECT_SIZE(3) + 50; DynamicJsonBuffer jsonBuffer(capacity); JsonObject& root = jsonBuffer.parseObject(nodeStatus.c_str()); JsonObject& data = root["data"]; bool data_synced = data["synced"]; // true //long data_now = data["now"]; // 1178395 //int data_blocksCount = data["blocksCount"]; // 0 return data_synced; /****************************************/ } /******************************************************************************** This routine will search through all the received transactions of ArkAddress wallet starting from the oldest. "searching wallet + page#" will be displayed. text will toggle between red/white every received transaction The page number of the last transaction in the search will be displayed. This is the page to the most newest receive transaction on the chain. The final page number is also equal to the total number of received transactions in the wallet. The routine returns the page number of the most recent transaction. Empty wallet will return '0' (NOT YET TESTED) ********************************************************************************/ int getMostRecentReceivedTransaction() { Serial.print("\n\n\nHere are all the transactions in a wallet\n"); int CursorXtemp; int CursorYtemp; int page = 1; while ( searchReceivedTransaction(ArkAddress, page, id, amount, senderAddress, vendorField) ) { Serial.print("Page: "); Serial.println(page); // Serial.print("Transaction id: "); // Serial.println(id); // Serial.print("Amount(Arktoshi): "); // Serial.println(amount); // Serial.print("Amount(Ark): "); // Serial.println(float(amount) / 100000000, 8); // Serial.print("Sender address: "); // Serial.println(senderAddress); Serial.print("Vendor Field: "); Serial.println(vendorField); tft.setCursor(CursorX, CursorY); if ( (page & 0x01) == 0) { tft.setTextColor(ILI9341_WHITE); tft.print("searching wallet: "); CursorXtemp = tft.getCursorX(); CursorYtemp = tft.getCursorY(); tft.setTextColor(ILI9341_BLACK); tft.print(page - 1); tft.setCursor(CursorXtemp, CursorYtemp); tft.setTextColor(ILI9341_WHITE); tft.println(page); } else { tft.setTextColor(ILI9341_RED); tft.print("searching wallet: "); CursorXtemp = tft.getCursorX(); CursorYtemp = tft.getCursorY(); tft.setTextColor(ILI9341_BLACK); tft.print(page - 1); tft.setCursor(CursorXtemp, CursorYtemp); tft.setTextColor(ILI9341_RED); tft.println(page); //We need to clear the pixels around the page number every time we refresh. } page++; }; tft.setCursor(CursorXtemp, CursorYtemp); tft.setTextColor(ILI9341_BLACK); tft.println(page - 1); Serial.print("No more Transactions "); Serial.print("\nThe most recent transaction was page #: "); Serial.println(page - 1); return page - 1; } //quick test routine. void searchTransaction() { //const std::map<std::string, std::string>& body_parameters, int limit = 5, std::string vendorFieldHexString; vendorFieldHexString = "6964647955"; //std::string transactionSearchResponse = connection.api.transactions.search( {{"vendorFieldHex", vendorFieldHexString}, {"orderBy", "timestamp:asc"} },1,1); std::string transactionSearchResponse = connection.api.transactions.search( {{"recipientId", ArkAddress}, {"orderBy", "timestamp:asc"} }, 1, 1); Serial.print("\nSearch Result Transactions: "); Serial.println(transactionSearchResponse.c_str()); // The response is a 'std::string', to Print on Arduino, we need the c_string type. }
[ "33669966+PhillipJacobsen@users.noreply.github.com" ]
33669966+PhillipJacobsen@users.noreply.github.com
3c4d8280dc09d6e5bc323ede7fe86a41107c8287
d6cf7e3a1a58fd3185e2619419f6aa66e8e9a9da
/3.6.7 Cyclic process. Working with numbers in number/9/main.cpp
ce0abb202045bce0c497a2731fa39e7c85b34228
[]
no_license
Nkeyka/Qt-Creator-Cpp-Book
6ba92cdb0eda0b844c83815266756c7e18d285e1
dcbfaf86bd0ece7c0e5642e03ab5796e2a68c916
refs/heads/main
2023-02-23T08:52:16.902547
2021-02-02T05:21:36
2021-02-02T05:21:36
319,847,831
0
0
null
null
null
null
UTF-8
C++
false
false
299
cpp
#include <iostream> using namespace std; int main() { int N, N2; cout << "N = "; cin >> N; cout << "N2 = "; cin >> N2; while (N != N2) { if (N > N2) N -= N2; else N2 -= N; } (N == 1) ? cout << "Yes" : cout << "No"; return 0; }
[ "nkeyka@gmail.com" ]
nkeyka@gmail.com
c8e487cbfecf24e8f60c12a2732b7298a49ffe24
0674a19a60ed1e2c16cd8eeae4306de2bcf44e92
/dialog.cpp
c974c2a43a2fde5be671d20fcd9887307bf4612c
[ "MIT" ]
permissive
ashumeow/SchoolSystem
e5ca45ba5cf5db1231d6f00a68f65e775f4cc25c
5bd9ed8e6c32246293cc70a7a75d2e67986bf7bd
refs/heads/master
2021-01-15T05:43:46.274299
2014-04-25T22:02:33
2014-04-25T22:02:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,329
cpp
#include "dialog.h" Dialog::Dialog(const QStringList &m_listSubject, QDialog *parent): QDialog(parent), gLayout(new QGridLayout), labelSubject(new QLabel("Subject")), labelGrade(new QLabel("Grade")), comboBoxSubject(new QComboBox), comboBoxGrade(new QComboBox), ok(new QPushButton("Accept")), cancel(new QPushButton("Cancel")) { //setAttribute(Qt::WA_DeleteOnClose); QStringList listSubject, listGrade; if(m_listSubject.size() == 0){ listSubject << "English Language" << "Mathematics" << "Biology" << "Agricultural Science" << "Physics" << "Chemistry" << "Economics" << "Yoruba" << "Geography" << "Government" << "Account" << "Literature in English" << "Commerce" << "Civic Education" << "CRK" << "CRS" << "Further Maths" << "Igbo" << "Hausa"; } else { listSubject.append(m_listSubject); } listGrade << "A1" << "B2" << "B3" << "C4" << "C5" << "C6" << "D7" << "E8" << "F9"; listSubject.sort(Qt::CaseInsensitive); comboBoxSubject->addItems(listSubject); comboBoxGrade->addItems(listGrade); gLayout->addWidget(labelSubject, 0, 0); gLayout->addWidget(labelGrade, 1, 0); gLayout->addWidget(comboBoxSubject, 0, 1); gLayout->addWidget(comboBoxGrade, 1, 1); gLayout->addWidget(ok, 2, 1); gLayout->addWidget(cancel, 2, 2); this->setLayout(gLayout); QObject::connect(cancel, SIGNAL(clicked()), this, SLOT(close())); QObject::connect(ok, SIGNAL(clicked()), this, SLOT(accept())); QObject::connect(comboBoxSubject, SIGNAL(activated(QString)), this, SLOT(setSubject(QString))); QObject::connect(comboBoxGrade, SIGNAL(activated(QString)), this, SLOT(setGrade(QString))); } const QString& Dialog::subject() const { return m_subject; } const QString& Dialog::grade() const { return m_grade; } void Dialog::setGrade(const QString &text) { if(text == m_grade || text == "") return; m_grade = text; emit gradeChanged(text); } void Dialog::setSubject(const QString &text) { if(text == m_subject || text == "") return; m_subject = text; emit subjectChanged(text); } void Dialog::setSubjectList(const QStringList &subjectList) { comboBoxSubject->clear(); comboBoxSubject->addItems(subjectList); }
[ "ogunyinkajoshua@yahoo.com" ]
ogunyinkajoshua@yahoo.com
c76901b79ddc1fde28ec5b381a51268310540deb
5b4613175235957af30f4982b26f58ca7e0d126e
/source/GcLib/directx/VertexBuffer.hpp
4ffb6df07bdf3bfd8ac74c43be84f856e18db866
[]
no_license
illusion-star/Touhou-Danmakufu-ph3sx-2
b6b8596a6fa15a98768239d1ec5ae4f537f2de60
3a0f5329aae41f9191ec28c67191882ea303f24f
refs/heads/master
2023-08-01T18:04:09.349811
2021-10-05T03:12:03
2021-10-05T03:12:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,436
hpp
#pragma once #include "../pch.h" #include "DxConstant.hpp" namespace directx { struct BufferLockParameter { UINT lockOffset = 0U; DWORD lockFlag = 0U; void* data = nullptr; size_t dataCount = 0U; size_t dataStride = 1U; BufferLockParameter() { lockOffset = 0U; lockFlag = 0U; data = nullptr; dataCount = 0U; dataStride = 1U; }; BufferLockParameter(DWORD _lockFlag) { lockOffset = 0U; lockFlag = _lockFlag; data = nullptr; dataCount = 0U; dataStride = 1U; }; BufferLockParameter(void* _data, size_t _count, size_t _stride, DWORD _lockFlag) { lockOffset = 0U; lockFlag = _lockFlag; data = 0U; dataCount = _count; dataStride = _stride; }; template<typename T> void SetSource(T& vecSrc, size_t countMax, size_t _stride) { data = vecSrc.data(); dataCount = std::min(countMax, vecSrc.size()); dataStride = _stride; } }; class VertexBufferManager; template<typename T> class BufferBase { static_assert(std::is_base_of<IDirect3DResource9, T>::value, "T must be a Direct3D resource"); public: BufferBase(); BufferBase(IDirect3DDevice9* device); virtual ~BufferBase(); inline void Release() { ptr_release(buffer_); } HRESULT UpdateBuffer(BufferLockParameter* pLock); virtual HRESULT Create() = 0; T* GetBuffer() { return buffer_; } size_t GetSize() { return size_; } size_t GetSizeInBytes() { return sizeInBytes_; } protected: IDirect3DDevice9* pDevice_; T* buffer_; size_t size_; size_t stride_; size_t sizeInBytes_; }; class FixedVertexBuffer : public BufferBase<IDirect3DVertexBuffer9> { public: FixedVertexBuffer(IDirect3DDevice9* device); virtual ~FixedVertexBuffer(); virtual void Setup(size_t iniSize, size_t stride, DWORD fvf); virtual HRESULT Create(); private: DWORD fvf_; }; class FixedIndexBuffer : public BufferBase<IDirect3DIndexBuffer9> { public: FixedIndexBuffer(IDirect3DDevice9* device); virtual ~FixedIndexBuffer(); virtual void Setup(size_t iniSize, size_t stride, D3DFORMAT format); virtual HRESULT Create(); private: D3DFORMAT format_; }; template<typename T> class GrowableBuffer : public BufferBase<T> { public: GrowableBuffer(IDirect3DDevice9* device); virtual ~GrowableBuffer(); virtual HRESULT Create() = 0; virtual void Expand(size_t newSize) = 0; }; class GrowableVertexBuffer : public GrowableBuffer<IDirect3DVertexBuffer9> { public: GrowableVertexBuffer(IDirect3DDevice9* device); virtual ~GrowableVertexBuffer(); virtual void Setup(size_t iniSize, size_t stride, DWORD fvf); virtual HRESULT Create(); virtual void Expand(size_t newSize); private: DWORD fvf_; }; class GrowableIndexBuffer : public GrowableBuffer<IDirect3DIndexBuffer9> { public: GrowableIndexBuffer(IDirect3DDevice9* device); virtual ~GrowableIndexBuffer(); virtual void Setup(size_t iniSize, size_t stride, D3DFORMAT format); virtual HRESULT Create(); virtual void Expand(size_t newSize); private: D3DFORMAT format_; }; class DirectGraphics; class VertexBufferManager : public DirectGraphicsListener { static VertexBufferManager* thisBase_; public: enum : size_t { MAX_STRIDE_STATIC = 65536U, }; VertexBufferManager(); ~VertexBufferManager(); static VertexBufferManager* GetBase() { return thisBase_; } virtual void ReleaseDxResource(); virtual void RestoreDxResource(); virtual bool Initialize(DirectGraphics* graphics); virtual void Release(); FixedVertexBuffer* GetVertexBufferTLX() { return vertexBuffers_[0]; } FixedVertexBuffer* GetVertexBufferLX() { return vertexBuffers_[1]; } FixedVertexBuffer* GetVertexBufferNX() { return vertexBuffers_[2]; } FixedIndexBuffer* GetIndexBuffer() { return indexBuffer_; } GrowableVertexBuffer* GetGrowableVertexBuffer() { return vertexBufferGrowable_; } GrowableIndexBuffer* GetGrowableIndexBuffer() { return indexBufferGrowable_; } GrowableVertexBuffer* GetInstancingVertexBuffer() { return vertexBuffer_HWInstancing_; } static void AssertBuffer(HRESULT hr, const std::wstring& bufferID); private: /* * 0 -> TLX * 1 -> LX * 2 -> NX */ std::vector<FixedVertexBuffer*> vertexBuffers_; FixedIndexBuffer* indexBuffer_; GrowableVertexBuffer* vertexBufferGrowable_; GrowableIndexBuffer* indexBufferGrowable_; GrowableVertexBuffer* vertexBuffer_HWInstancing_; virtual void CreateBuffers(IDirect3DDevice9* device); }; }
[ "32347635+Natashi@users.noreply.github.com" ]
32347635+Natashi@users.noreply.github.com
94a9f361206b04755a7660397ce84d06744a6353
0865e1c71ad4ceb5502377d1d94e672f9ab8b08d
/Greatest_Common_Divisor.cpp
796187e04528bcf0eea919eb4986fbf042541ab3
[]
no_license
xznxzy/Algorithm
c57cf9824c7ee96b487851842aa7362ed0adccaf
7eedb7460e860a735e89e2f6a50054a6e93ba1a5
refs/heads/master
2021-09-18T20:35:36.869818
2018-07-19T15:27:09
2018-07-19T15:27:09
105,955,013
0
0
null
null
null
null
UTF-8
C++
false
false
2,213
cpp
// // main.cpp // Greatest_Common_Divisor // 最大公约数 // 1.题目描述:求解两个整数(不能是负数)的最大公约数(要求两数不能同时为0) // 2.方法: // (1)穷举法 // (2)相减法 // (3)欧几里得辗转相除法 // (4)欧几里得辗转相除法:递归实现 // Created by zhangying on 10/5/17. // Copyright © 2017 zhangying. All rights reserved. // //穷举法 unsigned long GCD1(unsigned long a, unsigned long b){ if (a == 0) { return b; } else if(b == 0){ return a; } else if(a == b){ return a; } unsigned long gcd = a > b ? b : a; while (gcd > 1) { if ((a%gcd==0) && (b%gcd==0)) { return gcd; } gcd--; } return gcd; } //相减法 unsigned long GCD2(unsigned long a, unsigned long b){ if (a == 0) { return b; } else if(b == 0){ return a; } else if(a == b){ return a; } unsigned long gcd = 0; while (a != b) { //用较大的一个减去较小的一个,直到两者相等,就得到了最大公约数 gcd = a > b ? (a-=b) : (b-=a); } return gcd; } //欧几里得辗转相除法 unsigned long GCD3(unsigned long a, unsigned long b){ if (a == 0) { return b; } else if(b == 0){ return a; } else if(a == b){ return a; } unsigned long mod = a % b; while (mod != 0) { a = b; b = mod; mod = a % b; } return b; } //欧几里得辗转相除法:递归实现 unsigned long GCD4(unsigned long a, unsigned long b){ if (b == 0) { return a; } else { return GCD4(b, a % b); } } #include <iostream> using namespace std; int main(int argc, const char * argv[]) { unsigned long a, b; cout << "Please input a and b: "; cin >> a >> b; unsigned long gcd; gcd = GCD1(a, b); cout << "1.gcd = " << gcd << endl; gcd = GCD2(a, b); cout << "2.gcd = " << gcd << endl; gcd = GCD3(a, b); cout << "3.gcd = " << gcd << endl; gcd = GCD4(a, b); cout << "4.gcd = " << gcd << endl; return 0; }
[ "ying5@g.clemson.edu" ]
ying5@g.clemson.edu
9f6409b4ad031fd1090c6ffab3f56cda5f9fe999
1bcb966740f47c0edc23e9b05afec55f2bcae36a
/client/cplusplus/loginregister/LayerLogin.h
12718b2ecc2884e87d36f3e0954e405c91a08027
[]
no_license
East196/diabloworld
0d2e9dbf650aa86fcc7b9fc1ef49912e79adb954
d7a83a21287ed66aea690ecb6b73588569478be6
refs/heads/master
2021-05-09T12:15:31.640065
2018-02-04T15:16:54
2018-02-04T15:16:54
119,007,609
3
2
null
null
null
null
UTF-8
C++
false
false
1,283
h
#ifndef Client_LayerLogin_h #define Client_LayerLogin_h #include"cocos2d.h" #include"cocos-ext.h" #include "SocketClient.h" #include "CData.h" #include "LodingLayer.h" #include "TeXiao.h" USING_NS_CC; USING_NS_CC_EXT; using namespace std; class LayerLogin:public CCLayer { public: CREATE_FUNC(LayerLogin); virtual bool init(); virtual void onExit(); ~LayerLogin(); CCSprite * texiao; bool hasRole; Loading * load; CCSprite * logo; CCSize winSize; char * denglu1; void removeLoader(); void receiveLoginData(); void sendPersonalData(); void receivePersonalData(); void receiveCityData(); void jiumiaoshanyou(); void firefly(); void callNull1(); void callNull2(); void zhenping(); char * sendData; private: void initUI(); void loadRes(); // bool init(); void menuItemCallbackLogin(CCObject* pSender); void menuItemCallbackStart(CCObject* pSender); void menuItemCallbackSelector(CCObject* pSender); //CCLabelTTF *label1; //CCLabelTTF *label2; CCMenuItemImage *url1,*url2; CCSprite *pSpriteDialogLogin; CCEditBox* editBoxUsername; CCEditBox* editBoxPassword; }; #endif
[ "2901180515@qq.com" ]
2901180515@qq.com
a4f6d0e543c002fa28f2ef1867a35dc5e5bf21e6
b146b54363a20726b3e1dc0ef0fadc82051234f9
/Lodestar/symbolic/OrdinaryDifferentialEquation.hpp
8b4520a185ba000261308d0981d36d96e4bc0ccb
[ "BSD-3-Clause" ]
permissive
helkebir/Lodestar
90a795bbbd7e496313c54e34f68f3527134b88ce
465eef7fe3994339f29d8976a321715441e28c84
refs/heads/master
2022-03-12T23:16:03.981989
2022-03-03T05:08:42
2022-03-03T05:08:42
361,901,401
4
1
null
null
null
null
UTF-8
C++
false
false
6,916
hpp
// // Created by Hamza El-Kebir on 5/8/21. // #ifndef LODESTAR_ORDINARYDIFFERENTIALEQUATION_HPP #define LODESTAR_ORDINARYDIFFERENTIALEQUATION_HPP #ifdef LS_USE_GINAC #include <Eigen/Dense> #include "ginac/ginac.h" #include "Lodestar/systems/StateSpace.hpp" #include <string> #include <deque> namespace ls { namespace symbolic { class OrdinaryDifferentialEquation { public: OrdinaryDifferentialEquation() : functions_(GiNaC::lst{GiNaC::ex(0)}), states_(GiNaC::lst{GiNaC::symbol("x")}), inputs_(GiNaC::lst{GiNaC::symbol("u")}), time_(GiNaC::symbol("t")) { makeSymbolMap(); } OrdinaryDifferentialEquation(const GiNaC::lst &functions, const GiNaC::lst &states, const GiNaC::lst &inputs) : functions_(functions), states_(states), inputs_(inputs), time_(GiNaC::symbol("t")) { makeSymbolMap(); } OrdinaryDifferentialEquation(const GiNaC::lst &functions, const GiNaC::lst &states, const GiNaC::lst &inputs, const GiNaC::symbol &time) : functions_(functions), states_(states), inputs_(inputs), time_(time) { makeSymbolMap(); } GiNaC::exmap generateExpressionMap() const; GiNaC::exmap generateExpressionMap( const std::vector<GiNaC::relational> &relationals) const; GiNaC::exmap generateExpressionMap(const std::vector<double> &states, const std::vector<double> &inputs) const; GiNaC::exmap generateExpressionMap(double t, const std::vector<double> &states, const std::vector<double> &inputs) const; GiNaC::symbol getSymbol(const std::string &symbolName) const; GiNaC::symbol getStateSymbol(unsigned int i) const; GiNaC::symbol getInputSymbol(unsigned int i) const; GiNaC::symbol getTimeSymbol() const; const GiNaC::lst &getFunctions() const; void setFunctions(const GiNaC::lst &functions); const GiNaC::lst &getStates() const; void setStates(const GiNaC::lst &states); const GiNaC::lst &getInputs() const; void setInputs(const GiNaC::lst &inputs); Eigen::MatrixXd evalf(const GiNaC::exmap &m) const; Eigen::MatrixXd evalf(const std::vector<double> &states, const std::vector<double> &inputs) const; Eigen::MatrixXd evalf(double t, const std::vector<double> &states, const std::vector<double> &inputs) const; GiNaC::matrix generateJacobian(const GiNaC::lst &variables) const; GiNaC::matrix generateJacobianStates() const; std::string generateJacobianStatesCppFunc(const std::string &functionName, const bool dynamicType = false) const; std::string generateJacobianStatesArrayInputCppFunc(const std::string &functionName, const bool dynamicType = false) const; GiNaC::matrix generateJacobianInputs() const; std::string generateJacobianInputsCppFunc(const std::string &functionName, const bool dynamicType = false) const; std::string generateJacobianInputsArrayInputCppFunc(const std::string &functionName, const bool dynamicType = false) const; Eigen::MatrixXd generateJacobianMatrix(const GiNaC::lst &variables, const GiNaC::exmap &exmap) const; Eigen::MatrixXd generateJacobianMatrix(const GiNaC::matrix &jacobian, const GiNaC::exmap &exmap) const; Eigen::MatrixXd generateJacobianMatrixStates(const GiNaC::exmap &exmap) const; Eigen::MatrixXd generateJacobianMatrixInputs(const GiNaC::exmap &exmap) const; std::string generateMatrixCppFunc(const GiNaC::matrix &ginacMatrix, const std::string &functionName, const bool dynamicType = false) const; std::string generateMatrixArrayInputCppFunc(const GiNaC::matrix &ginacMatrix, const std::string &functionName, const bool dynamicType = false) const; systems::StateSpace<> linearize(const GiNaC::exmap &exmap) const; systems::StateSpace<> linearize(const std::vector<double> &states, const std::vector<double> &inputs) const; systems::StateSpace<> linearize(double t, const std::vector<double> &states, const std::vector<double> &inputs) const; systems::StateSpace<> linearize(const GiNaC::matrix &jacobianStates, const GiNaC::matrix &jacobianInputs, const GiNaC::exmap &exmap) const; systems::StateSpace<> linearize(const GiNaC::matrix &jacobianStates, const GiNaC::matrix &jacobianInputs, const std::vector<double> &states, const std::vector<double> &inputs) const; systems::StateSpace<> linearize(const GiNaC::matrix &jacobianStates, const GiNaC::matrix &jacobianInputs, double t, const std::vector<double> &states, const std::vector<double> &inputs) const; static Eigen::MatrixXd matrixToMatrixXd(const GiNaC::matrix &mat); static Eigen::MatrixXd matrixToMatrixXd(const GiNaC::ex &ex); protected: GiNaC::lst functions_; GiNaC::symbol time_; GiNaC::lst states_; GiNaC::lst inputs_; std::map<std::string, GiNaC::symbol> symbolMap_; void makeSymbolMap(); static void replaceString(std::string &str, const std::string &source, const std::string &dest); static void replaceStringAll(std::string &str, const std::string &source, const std::string &dest); static std::string stripWhiteSpace(std::string &str); }; } } #endif #endif //LODESTAR_ORDINARYDIFFERENTIALEQUATION_HPP
[ "ha.elkebir@gmail.com" ]
ha.elkebir@gmail.com
cc2dcfea52939245f47000c480e053e21ef0e4b9
9a3f8c3d4afe784a34ada757b8c6cd939cac701d
/leetFindCorrNodeOfTreeInClone.cpp
8750b92a73c27e8c0e4e63a06a93df7154ee98d7
[]
no_license
madhav-bits/Coding_Practice
62035a6828f47221b14b1d2a906feae35d3d81a8
f08d6403878ecafa83b3433dd7a917835b4f1e9e
refs/heads/master
2023-08-17T04:58:05.113256
2023-08-17T02:00:53
2023-08-17T02:00:53
106,217,648
1
1
null
null
null
null
UTF-8
C++
false
false
2,344
cpp
/* * //******************************1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree.****************************** https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/description/ *******************************************************************TEST CASES:************************************************************ //These are the examples I had tweaked and worked on. [7,4,3,null,null,6,19] 3 [8,null,6,null,5,null,4,null,3,null,2,null,1] 4 // Time Complexity: O(n). // Space Complexity: O(1). // n- total #nodes in the tree. //********************************************************THIS IS LEET ACCEPTED CODE.*************************************************** */ //************************************************************Solution 1:************************************************************ //*****************************************************THIS IS LEET ACCEPTED CODE.*********************************************** // Time Complexity: O(n). // Space Complexity: O(1). // n- total #nodes in the tree. // This algorithm is iteration based. Here, we iter. over both the trees parallely, whenever we found target node in orig. tree, we // return the curr. node from the duplicate tree iter. /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* iterateTree(TreeNode* node1, TreeNode* node2, TreeNode* target){ // Iter. parallelly on both trees. if(node1==NULL) return NULL; if(node1==target) return node2; // If target node found, dup's curr. node is returned. TreeNode* lt=iterateTree(node1->left, node2->left, target); if(lt) return lt; // If left subtree has ans, we return ans from the child. return iterateTree(node1->right, node2->right, target); // If left don't have ans, we return right child's response. } TreeNode* getTargetCopy(TreeNode* original, TreeNode* cloned, TreeNode* target) { return iterateTree(original, cloned, target); // Func. call to start iter. on two trees parallelly. } };
[ "kasamsaimadhavk@gmail.com" ]
kasamsaimadhavk@gmail.com
6863f703f8a40aa48fb126df24b08bada6792cb7
a5f35d0dfaddb561d3595c534b6b47f304dbb63d
/Source/BansheeCore/Resources/BsResourceHandle.h
88e80c13582a6729171af50d4b67fdd846238c81
[]
no_license
danielkrupinski/BansheeEngine
3ff835e59c909853684d4985bd21bcfa2ac86f75
ae820eb3c37b75f2998ddeaf7b35837ceb1bbc5e
refs/heads/master
2021-05-12T08:30:30.564763
2018-01-27T12:55:25
2018-01-27T12:55:25
117,285,819
1
0
null
2018-01-12T20:38:41
2018-01-12T20:38:41
null
UTF-8
C++
false
false
11,174
h
//********************************** Banshee Engine (www.banshee3d.com) **************************************************// //**************** Copyright (c) 2016 Marko Pintera (marko.pintera@gmail.com). All rights reserved. **********************// #pragma once #include "Reflection/BsIReflectable.h" #include "Utility/BsUUID.h" namespace bs { /** @addtogroup Implementation * @{ */ /** Data that is shared between all resource handles. */ struct BS_CORE_EXPORT ResourceHandleData { ResourceHandleData() :mIsCreated(false), mRefCount(0) { } SPtr<Resource> mPtr; UUID mUUID; bool mIsCreated; UINT32 mRefCount; }; /** * Represents a handle to a resource. Handles are similar to a smart pointers, but they have two advantages: * - When loading a resource asynchronously you can be immediately returned the handle that you may use throughout * the engine. The handle will be made valid as soon as the resource is loaded. * - Handles can be serialized and deserialized, therefore saving/restoring references to their original resource. */ class BS_CORE_EXPORT ResourceHandleBase : public IReflectable { public: virtual ~ResourceHandleBase(); /** * Checks if the resource is loaded. Until resource is loaded this handle is invalid and you may not get the * internal resource from it. * * @param[in] checkDependencies If true, and if resource has any dependencies, this method will also check if * they are loaded. */ bool isLoaded(bool checkDependencies = true) const; /** * Blocks the current thread until the resource is fully loaded. * * @note Careful not to call this on the thread that does the loading. */ void blockUntilLoaded(bool waitForDependencies = true) const; /** * Releases an internal reference to this resource held by the resources system, if there is one. * * @see Resources::release(ResourceHandleBase&) */ void release(); /** Returns the UUID of the resource the handle is referring to. */ const UUID& getUUID() const { return mData != nullptr ? mData->mUUID : UUID::EMPTY; } public: // ***** INTERNAL ****** /** @name Internal * @{ */ /** Gets the handle data. For internal use only. */ const SPtr<ResourceHandleData>& getHandleData() const { return mData; } /** @} */ protected: ResourceHandleBase(); /** Destroys the resource the handle is pointing to. */ void destroy(); /** * Sets the created flag to true and assigns the resource pointer. Called by the constructors, or if you * constructed just using a UUID, then you need to call this manually before you can access the resource from * this handle. * * @note * This is needed because two part construction is required due to multithreaded nature of resource loading. * @note * Internal method. */ void setHandleData(const SPtr<Resource>& ptr, const UUID& uuid); /** Increments the reference count of the handle. Only to be used by Resources for keeping internal references. */ void addInternalRef(); /** Decrements the reference count of the handle. Only to be used by Resources for keeping internal references. */ void removeInternalRef(); /** * @note * All handles to the same source must share this same handle data. Otherwise things like counting number of * references or replacing pointed to resource become impossible without additional logic. */ SPtr<ResourceHandleData> mData; private: friend class Resources; static Signal mResourceCreatedCondition; static Mutex mResourceCreatedMutex; protected: void throwIfNotLoaded() const; }; /** * @copydoc ResourceHandleBase * * Handles differences in reference counting depending if the handle is normal or weak. */ template <bool WeakHandle> class BS_CORE_EXPORT TResourceHandleBase : public ResourceHandleBase { }; /** Specialization of TResourceHandleBase for weak handles. Weak handles do no reference counting. */ template<> class BS_CORE_EXPORT TResourceHandleBase<true> : public ResourceHandleBase { public: virtual ~TResourceHandleBase() { } protected: void addRef() { }; void releaseRef() { }; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class WeakResourceHandleRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** Specialization of TResourceHandleBase for normal (non-weak) handles. */ template<> class BS_CORE_EXPORT TResourceHandleBase<false> : public ResourceHandleBase { public: virtual ~TResourceHandleBase() { } protected: void addRef() { if (mData) mData->mRefCount++; }; void releaseRef() { if (mData) { mData->mRefCount--; if (mData->mRefCount == 0) destroy(); } }; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class WeakResourceHandleRTTI; friend class ResourceHandleRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** @copydoc ResourceHandleBase */ template <typename T, bool WeakHandle> class TResourceHandle : public TResourceHandleBase<WeakHandle> { public: TResourceHandle() { } /** Copy constructor. */ TResourceHandle(const TResourceHandle<T, WeakHandle>& ptr) { this->mData = ptr.getHandleData(); this->addRef(); } virtual ~TResourceHandle() { this->releaseRef(); } /** Converts a specific handle to generic Resource handle. */ operator TResourceHandle<Resource, WeakHandle>() const { TResourceHandle<Resource, WeakHandle> handle; handle.setHandleData(this->getHandleData()); return handle; } /** * Returns internal resource pointer. * * @note Throws exception if handle is invalid. */ T* operator->() const { return get(); } /** * Returns internal resource pointer and dereferences it. * * @note Throws exception if handle is invalid. */ T& operator*() const { return *get(); } /** Clears the handle making it invalid and releases any references held to the resource. */ TResourceHandle<T, WeakHandle>& operator=(std::nullptr_t ptr) { this->releaseRef(); this->mData = nullptr; return *this; } /** Normal assignment operator. */ TResourceHandle<T, WeakHandle>& operator=(const TResourceHandle<T, WeakHandle>& rhs) { setHandleData(rhs.getHandleData()); return *this; } template<class _Ty> struct Bool_struct { int _Member; }; /** * Allows direct conversion of handle to bool. * * @note This is needed because we can't directly convert to bool since then we can assign pointer to bool and * that's weird. */ operator int Bool_struct<T>::*() const { return ((this->mData != nullptr && !this->mData->mUUID.empty()) ? &Bool_struct<T>::_Member : 0); } /** * Returns internal resource pointer and dereferences it. * * @note Throws exception if handle is invalid. */ T* get() const { this->throwIfNotLoaded(); return reinterpret_cast<T*>(this->mData->mPtr.get()); } /** * Returns the internal shared pointer to the resource. * * @note Throws exception if handle is invalid. */ SPtr<T> getInternalPtr() const { this->throwIfNotLoaded(); return std::static_pointer_cast<T>(this->mData->mPtr); } /** Converts a handle into a weak handle. */ TResourceHandle<T, true> getWeak() const { TResourceHandle<T, true> handle; handle.setHandleData(this->getHandleData()); return handle; } protected: friend Resources; template<class _T, bool _Weak> friend class TResourceHandle; template<class _Ty1, class _Ty2, bool Weak> friend TResourceHandle<_Ty1, Weak> static_resource_cast(const TResourceHandle<_Ty2, Weak>& other); /** * Constructs a new valid handle for the provided resource with the provided UUID. * * @note Handle will take ownership of the provided resource pointer, so make sure you don't delete it elsewhere. */ explicit TResourceHandle(T* ptr, const UUID& uuid) :TResourceHandleBase<WeakHandle>() { this->mData = bs_shared_ptr_new<ResourceHandleData>(); this->addRef(); this->setHandleData(SPtr<Resource>(ptr), uuid); } /** * Constructs an invalid handle with the specified UUID. You must call setHandleData() with the actual resource * pointer to make the handle valid. */ TResourceHandle(const UUID& uuid) { this->mData = bs_shared_ptr_new<ResourceHandleData>(); this->mData->mUUID = uuid; this->addRef(); } /** Constructs a new valid handle for the provided resource with the provided UUID. */ TResourceHandle(const SPtr<T> ptr, const UUID& uuid) { this->mData = bs_shared_ptr_new<ResourceHandleData>(); this->addRef(); setHandleData(ptr, uuid); } /** Replaces the internal handle data pointer, effectively transforming the handle into a different handle. */ void setHandleData(const SPtr<ResourceHandleData>& data) { this->releaseRef(); this->mData = data; this->addRef(); } /** Converts a weak handle into a normal handle. */ TResourceHandle<T, false> lock() const { TResourceHandle<Resource, false> handle; handle.setHandleData(this->getHandleData()); return handle; } using ResourceHandleBase::setHandleData; }; /** Checks if two handles point to the same resource. */ template<class _Ty1, bool _Weak1, class _Ty2, bool _Weak2> bool operator==(const TResourceHandle<_Ty1, _Weak1>& _Left, const TResourceHandle<_Ty2, _Weak2>& _Right) { if(_Left.getHandleData() != nullptr && _Right.getHandleData() != nullptr) return _Left.getHandleData()->mPtr == _Right.getHandleData()->mPtr; return _Left.getHandleData() == _Right.getHandleData(); } /** Checks if a handle is null. */ template<class _Ty1, bool _Weak1, class _Ty2, bool _Weak2> bool operator==(const TResourceHandle<_Ty1, _Weak1>& _Left, std::nullptr_t _Right) { return _Left.getHandleData() == nullptr || _Left.getHandleData()->mUUID.empty(); } template<class _Ty1, bool _Weak1, class _Ty2, bool _Weak2> bool operator!=(const TResourceHandle<_Ty1, _Weak1>& _Left, const TResourceHandle<_Ty2, _Weak2>& _Right) { return (!(_Left == _Right)); } /** @} */ /** @addtogroup Resources * @{ */ /** @copydoc ResourceHandleBase */ template <typename T> using ResourceHandle = TResourceHandle<T, false>; /** * @copydoc ResourceHandleBase * * Weak handles don't prevent the resource from being unloaded. */ template <typename T> using WeakResourceHandle = TResourceHandle<T, true>; /** Casts one resource handle to another. */ template<class _Ty1, class _Ty2, bool Weak> TResourceHandle<_Ty1, Weak> static_resource_cast(const TResourceHandle<_Ty2, Weak>& other) { TResourceHandle<_Ty1, Weak> handle; handle.setHandleData(other.getHandleData()); return handle; } /** @} */ }
[ "bearishsun@gmail.com" ]
bearishsun@gmail.com
7de5d53b837d791d3125a432884b505633281464
855521b1d4bbc4a2f42b91bd1c2bf3c0b68c439c
/source/engine/Component.cpp
62b5ec8a4159291ef98a3e70170e5f930948c63d
[]
no_license
asam139/gameEngine
30995b6eb64a8679b1daeda8e2746795d3375f08
55257426bc02ad3a2292d782d841a5474a6ca900
refs/heads/master
2021-09-07T15:01:21.988625
2018-02-24T12:12:11
2018-02-24T12:12:11
115,192,409
1
0
null
null
null
null
UTF-8
C++
false
false
358
cpp
// // Created by Saul Moreno Abril on 04/02/2018. // #include "Component.h" #import "GameObject.h" const std::size_t Component::Type = std::hash<std::string>()(TO_STRING(Component)); bool Component::IsClassType(const std::size_t classType) const { return classType == Type; } GameObject& Component::getGameObject() const { return *_gameObject; }
[ "sam6.13.93@hotmail.com" ]
sam6.13.93@hotmail.com
7aed2890b7fa7e77d35496cb1eb12528826bd04d
3c4a127a1c76be81d47eb45f417808ecf0d21f23
/3 parcial/Arboles/pruebas/5-Arbol AVL con doble apuntador.cpp
c039adee742379d2d566fd09ba591ff36496de7b
[]
no_license
Wicho1313/Estructuras-de-datos
cc9b02d93bcab1a8884ac7ec1e9850e0d184267c
21166885ef72def9f37a4ae6f89f728d9a614622
refs/heads/master
2023-06-09T17:43:54.011511
2021-07-02T20:28:57
2021-07-02T20:28:57
309,032,966
0
0
null
null
null
null
UTF-8
C++
false
false
7,110
cpp
#include <stdio.h> #include <conio.h> #include <stdlib.h> struct nodo{ int dato; int bal; struct nodo *ptrDer; struct nodo *ptrIzq; }; struct nodo *crearnodo(int dato1){ struct nodo *ptrN; ptrN=(struct nodo*)malloc(sizeof(struct nodo)); ptrN->dato=dato1; ptrN->ptrDer=NULL; ptrN->ptrIzq=NULL; return ptrN; } int altura(struct nodo **ptr){ if(*ptr==NULL) return 0; else return ((*ptr)->bal); } int maximo(int a, int b){ if (a>b) return a; else return b; } void calculaAltura(struct nodo **p){ (*p)->bal=1+maximo(altura(&(*p)->ptrIzq),altura(&(*p)->ptrDer)); } struct nodo *rotaIzq(struct nodo **ptr){ struct nodo *temp; temp=(*ptr)->ptrDer; (*ptr)->ptrDer=temp->ptrIzq; temp->ptrIzq=(*ptr); calculaAltura(&(*ptr)); calculaAltura(&temp); return temp; } struct nodo *rotaDer(struct nodo **ptr){ struct nodo *temp; temp=(*ptr)->ptrIzq; (*ptr)->ptrIzq=temp->ptrDer; temp->ptrDer=(*ptr); calculaAltura(&(*ptr)); calculaAltura(&temp); return temp; } struct nodo *balancear(struct nodo **ptr){ calculaAltura(&(*ptr)); if(altura(&(*ptr)->ptrIzq)-altura(&(*ptr)->ptrDer)==2){ printf("Se rota\n"); if(altura(&(*ptr)->ptrIzq->ptrDer)> altura(&(*ptr)->ptrIzq->ptrIzq)){ (*ptr)->ptrIzq=rotaIzq(&(*ptr)->ptrIzq); return rotaDer(&(*ptr)); } } else if(altura(&(*ptr)->ptrDer)-altura(&(*ptr)->ptrIzq)==2){ printf("se rota\n"); if(altura(&(*ptr)->ptrDer->ptrIzq)>altura(&(*ptr)->ptrDer->ptrDer)){ (*ptr)->ptrDer=rotaDer(&(*ptr)->ptrDer); return rotaIzq(&(*ptr)); } } printf("\n %d",(*ptr)->bal); return (*ptr); } struct nodo * insertar(struct nodo **ptrRaiz, int miDato1){ if(*ptrRaiz==NULL){ return crearnodo(miDato1); } else if(miDato1<(*ptrRaiz)->dato){ (*ptrRaiz)->ptrIzq=insertar(&((*ptrRaiz)->ptrIzq),miDato1); } else if(miDato1>(*ptrRaiz)->dato ){ (*ptrRaiz)->ptrDer=insertar(&((*ptrRaiz)->ptrDer),miDato1); } else (*ptrRaiz)->dato=miDato1; return balancear(&(*ptrRaiz)); } void recorrerPunt(struct nodo **ptr, struct nodo **ptrH,struct nodo *ptrA){ if((*ptrH)->ptrDer!=NULL){ recorrerPunt(ptr,&(*ptrH)->ptrDer,ptrA); } else{ (*ptr)->dato=(*ptrH)->dato; ptrA=(*ptrH); *ptrH=(*ptrH)->ptrIzq; } } struct nodo * eliminar(struct nodo **ptr, int clave){ if(*ptr==NULL){ printf("No esta en el arbol"); } else if(clave<(*ptr)->dato) { eliminar(&(*ptr)->ptrIzq, clave); } else if(clave>(*ptr)->dato){ eliminar(&(*ptr)->ptrDer, clave); } else { struct nodo *aux; aux=(*ptr); if (aux->ptrIzq==NULL){ (*ptr)=aux->ptrDer; } else if(aux->ptrDer==NULL){ (*ptr)=aux->ptrDer; } else{ recorrerPunt(ptr,&(*ptr)->ptrIzq,aux); free(aux); } } (*ptr)->dato=clave; balancear(&(*ptr)); } void imprimirArbol(struct nodo **ptrRaiz, int contador){ int i,j; i=contador; if(*ptrRaiz!=NULL){ imprimirArbol(&(*ptrRaiz)->ptrDer, i+1); printf("\n"); for(j=1;j<i;j++) printf("-"); printf("%d \n",(*ptrRaiz)->dato); imprimirArbol(&(*ptrRaiz)->ptrIzq,i+1); } } int maxProfundidad(struct nodo **ptrRaiz){ if(*ptrRaiz!=NULL){ int profIzq, profDer; profIzq=maxProfundidad(&(*ptrRaiz)->ptrIzq); profDer=maxProfundidad(&(*ptrRaiz)->ptrDer); if (profIzq>profDer){ return(profIzq+1); } else{ return (profDer+1); } } else return 0; } struct nodo * busca(struct nodo **ptr, int clave){ if(*ptr==NULL) return NULL; else if(clave==(*ptr)->dato) return (*ptr); else if(clave<(*ptr)->dato) return busca(&(*ptr)->ptrIzq,clave); else return busca(&(*ptr)->ptrDer,clave); } void in_orden(struct nodo **ptrRaiz){ if(*ptrRaiz==NULL) return; in_orden(&(*ptrRaiz)->ptrIzq); printf(" %d ",(*ptrRaiz)->dato); in_orden(&(*ptrRaiz)->ptrDer); } void post_orden(struct nodo **ptrRaiz){ if (*ptrRaiz==NULL)return; post_orden(&(*ptrRaiz)->ptrIzq); post_orden(&(*ptrRaiz)->ptrDer); printf(" %d ",(*ptrRaiz)->dato); } void pre_orden(struct nodo **ptrRaiz){ if(*ptrRaiz==NULL)return; printf(" %d ",(*ptrRaiz)->dato); pre_orden(&(*ptrRaiz)->ptrIzq); pre_orden(&(*ptrRaiz)->ptrDer); } int main (){ int datoEnt, opc; struct nodo *ptrc=NULL; struct nodo **ptrc2; ptrc2=&ptrc; do{ fflush(stdin); printf ("\n 1.- Meter en el Arbol \n "); printf ("\n 2.- sacar del Arbol \n "); printf ("\n 3.- Maxima profundidad del Arbol \n "); printf ("\n 4.- Imprimir en in-orden el Arbol \n "); printf ("\n 5.- Imprimir en post-orden el Arbol \n "); printf ("\n 6.- Imprimir en pre-orden el Arbol \n "); printf ("\n 7.- Visualizar Arbol \n "); printf ("\n 8.- Buscar un dato \n "); printf ("\n 9.- Verificar si es hoja \n "); printf ("\n 10.- Salir \n "); scanf ("%d", &opc); switch (opc){ case 1: system("cls"); printf("Ingrese entero: "); scanf("%d",&datoEnt); insertar(ptrc2, datoEnt); imprimirArbol(ptrc2, datoEnt); system("pause"); system("cls"); break; case 2: system("cls"); printf("Que dato quieres sacar? "); scanf("%d",&datoEnt); eliminar(ptrc2,datoEnt); imprimirArbol(ptrc2, datoEnt); system("pause"); system("cls"); break; case 3: system("cls"); maxProfundidad(ptrc2); system("pause"); system("cls"); break; case 4: system("cls"); imprimirArbol(ptrc2, datoEnt); printf("\n En in-orden: \n"); in_orden(ptrc2); system("pause"); system("cls"); break; case 5: system("cls"); imprimirArbol(ptrc2, datoEnt); printf("\n En post-orden: \n"); post_orden(ptrc2); system("pause"); system("cls"); break; case 6: system("cls"); imprimirArbol(ptrc2, datoEnt); printf("\n En pre-orden: \n"); pre_orden(ptrc2); system("pause"); system("cls"); break; case 7: system("cls"); imprimirArbol(ptrc2, datoEnt); system("pause"); system("cls"); break; case 8: printf("ingresa un valor para buscar: "); scanf("%d",&datoEnt); if(busca(ptrc2,datoEnt)!=NULL) printf("\n Si esta en el arbol\n"); else printf("\n No se encontro \n "); break; case 9: //if(eshoja(ptrc2)==1) // printf("El dato es hoja"); // else // printf("no es hoja"); // break; case 10: exit (0); break; } }while(opc!=10); }
[ "lrojase1@gmail.com" ]
lrojase1@gmail.com
66109cb2333938dafed6f1d1d81d550ce957bbb6
a1c82112744d7bab6055d723b7fc648ef484e064
/Employee/Source.cpp
d8eb62aaefcfdf308686b35c92bdfdffb42dcfe5
[]
no_license
Aashutoshh/Tut5-Employee
aa663760ca8ecee8c8a4e275f3bf8800c775ec96
5c6e90b8e8a158f0ec50f7731c70f879cb86a4dc
refs/heads/master
2021-01-13T00:42:44.707998
2016-03-23T14:50:50
2016-03-23T14:50:50
54,557,615
0
0
null
null
null
null
UTF-8
C++
false
false
606
cpp
#include "Employee.h" #include "CommisionEmployee.h" #include "HourlyEmployee.h" #include "SalaryEmployee.h" int main() {//array of employees //commision employee CommisionEmployee cEmp("Tom", 1); cEmp.setBaseSalary(20000.00); cEmp.setRate(500.00); cEmp.setRevenue(5000.00); float sal1 = cEmp.salary(); //Hourly empolyee HourlyEmployee hEmp("Jane",2); hEmp.setHourlyRate(1000.00); hEmp.setHoursWorked(50); float sal2 = hEmp.salary(); //Salary employeee SalaryEmployee sEmp("MerryM" ,3); sEmp.setSalary(50000.00); float sal3 = sEmp.salary(); //store into arrays //display }
[ "214506607@stu.ukzn.ac.za" ]
214506607@stu.ukzn.ac.za
c5583dc9e366bbf48c27d1fd9bb21327b3b524ec
c7be52078daa48f8e2efa3102782d3be99bf6478
/HidEngine/HidEngine.cpp
68b74a70a4d2463632f27452545b8886164fa2ef
[]
no_license
ogatatsu/HID-Playground-Lib
db36d447397ce494ca33cc62f7e6bbabd0c4a249
22d71b98a35446b4762c4d4a1708377cf268a7b3
refs/heads/master
2022-12-07T21:38:55.843618
2022-11-27T08:33:01
2022-11-30T13:59:26
187,300,341
5
1
null
null
null
null
UTF-8
C++
false
false
23,507
cpp
/* The MIT License (MIT) Copyright (c) 2019 ogatatsu. 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 "HidEngine.h" #include "ArduinoMacro.h" #include "CommandTapper.h" #include "HidCore.h" #include "HidEngineTask.h" #include "utility.h" namespace hidpg { namespace Internal { etl::span<Key> HidEngineClass::_keymap; etl::span<KeyShift> HidEngineClass::_key_shift_map; etl::span<Combo> HidEngineClass::_combo_map; etl::span<Gesture> HidEngineClass::_gesture_map; etl::span<Encoder> HidEngineClass::_encoder_map; etl::span<EncoderShift> HidEngineClass::_encoder_shift_map; HidEngineClass::read_pointer_delta_callback_t HidEngineClass::_read_pointer_delta_cb = nullptr; HidEngineClass::read_encoder_step_callback_t HidEngineClass::_read_encoder_step_cb = nullptr; HidEngineClass::ComboInterruptionEvent HidEngineClass::_combo_interruption_event; etl::intrusive_list<Key> HidEngineClass::_pressed_key_list; etl::intrusive_list<KeyShiftIdLink> HidEngineClass::_started_key_shift_id_list; etl::intrusive_list<GestureIdLink> HidEngineClass::_started_gesture_id_list; etl::intrusive_list<EncoderShiftIdLink> HidEngineClass::_started_encoder_shift_id_list; void HidEngineClass::setKeymap(etl::span<Key> keymap) { _keymap = keymap; } void HidEngineClass::setKeyShiftMap(etl::span<KeyShift> key_shift_map) { _key_shift_map = key_shift_map; } void HidEngineClass::setComboMap(etl::span<Combo> combo_map) { _combo_map = combo_map; } void HidEngineClass::setGestureMap(etl::span<Gesture> gesture_map) { _gesture_map = gesture_map; } void HidEngineClass::setEncoderMap(etl::span<Encoder> encoder_map) { _encoder_map = encoder_map; } void HidEngineClass::setEncoderShiftMap(etl::span<EncoderShift> encoder_shift_map) { _encoder_shift_map = encoder_shift_map; } void HidEngineClass::setHidReporter(HidReporter *hid_reporter) { Hid.setReporter(hid_reporter); } void HidEngineClass::start() { HidEngineTask.start(); } void HidEngineClass::applyToKeymap(const Set &key_ids) { EventData evt{ApplyToKeymapEventData{key_ids}}; HidEngineTask.enqueEvent(evt); } void HidEngineClass::movePointer(PointingDeviceId pointing_device_id) { EventData evt{MovePointerEventData{pointing_device_id}}; HidEngineTask.enqueEvent(evt); } void HidEngineClass::rotateEncoder(EncoderId encoder_id) { EventData evt{RotateEncoderEventData{encoder_id}}; HidEngineTask.enqueEvent(evt); } void HidEngineClass::setReadPointerDeltaCallback(read_pointer_delta_callback_t cb) { _read_pointer_delta_cb = cb; } void HidEngineClass::setReadEncoderStepCallback(read_encoder_step_callback_t cb) { _read_encoder_step_cb = cb; } //------------------------------------------------------------------+ // ApplyToKeymap //------------------------------------------------------------------+ void HidEngineClass::applyToKeymap_impl(Set &key_ids) { static Set prev_ids; { Set press_ids = key_ids - prev_ids; uint8_t arr[press_ids.count()]; press_ids.toArray(arr); for (uint8_t key_id : arr) { processComboAndKey(Action::Press, key_id); } } { Set release_ids = prev_ids - key_ids; uint8_t arr[release_ids.count()]; release_ids.toArray(arr); for (uint8_t key_id : arr) { processComboAndKey(Action::Release, key_id); } } prev_ids = key_ids; } void HidEngineClass::processComboAndKey(Action action, etl::optional<uint8_t> key_id) { static etl::optional<uint8_t> first_commbo_id; static etl::intrusive_list<Combo> success_combo_list; switch (action) { case Action::Press: { // コンボ実行中のid(片方のキーだけreleaseされて再度pressされた。)の場合は新しいコンボを開始しないで通常のKeyPress for (auto &combo : success_combo_list) { if (combo.first_id == key_id || combo.second_id == key_id) { performKeyPress(key_id.value()); return; } } // first_id check if (first_commbo_id.has_value() == false) { for (auto &combo : _combo_map) { if (combo.isMatchFirstId(key_id.value())) { // first_id success first_commbo_id = key_id; _combo_interruption_event.start(combo.combo_term_ms); return; } } // first_id failure performKeyPress(key_id.value()); return; } // second_id check for (auto &combo : _combo_map) { if (combo.isMatchIds(first_commbo_id.value(), key_id.value())) { // combo success _combo_interruption_event.stop(); combo.first_id_rereased = false; combo.second_id_rereased = false; combo.command->press(); success_combo_list.push_back(combo); first_commbo_id = etl::nullopt; return; } } // second_id failure _combo_interruption_event.stop(); performKeyPress(first_commbo_id.value()); performKeyPress(key_id.value()); first_commbo_id = etl::nullopt; } break; case Action::Release: { // combo実行中のidがreleaseされた場合 for (auto &combo : success_combo_list) { if (combo.first_id == key_id && combo.first_id_rereased == false) { combo.first_id_rereased = true; if ((combo.isFastRelease() && combo.second_id_rereased == false) || (combo.isSlowRelease() && combo.second_id_rereased)) { combo.command->release(); } if (combo.second_id_rereased) { auto i_item = etl::intrusive_list<Combo>::iterator(combo); success_combo_list.erase(i_item); } return; } if (combo.second_id == key_id && combo.second_id_rereased == false) { combo.second_id_rereased = true; if ((combo.isFastRelease() && combo.first_id_rereased == false) || (combo.isSlowRelease() && combo.first_id_rereased)) { combo.command->release(); } if (combo.first_id_rereased) { auto i_item = etl::intrusive_list<Combo>::iterator(combo); success_combo_list.erase(i_item); } return; } } // first_idがタップされた場合 if (first_commbo_id == key_id) { _combo_interruption_event.stop(); first_commbo_id = etl::nullopt; performKeyPress(key_id.value()); performKeyRelease(key_id.value()); return; } // first_idより前に押されていたidがreleaseされた場合 if (first_commbo_id.has_value()) { _combo_interruption_event.stop(); performKeyPress(first_commbo_id.value()); performKeyRelease(key_id.value()); first_commbo_id = etl::nullopt; return; } // 他 performKeyRelease(key_id.value()); } break; case Action::ComboInterruption: { _combo_interruption_event.stop(); if (first_commbo_id.has_value()) { performKeyPress(first_commbo_id.value()); first_commbo_id = etl::nullopt; } } break; default: break; } } void HidEngineClass::performKeyPress(uint8_t key_id) { for (auto &key : _pressed_key_list) { if (key.key_id == key_id) { return; } } BeforeOtherKeyPressEventListener::_notifyBeforeOtherKeyPress(key_id); auto tpl = getCurrentKey(key_id); auto key_shift = std::get<0>(tpl); auto key = std::get<1>(tpl); if (key == nullptr) { return; } if (key_shift != nullptr && key_shift->pre_command.has_value() && key_shift->pre_command.value().is_pressed == false) { key_shift->pre_command.value().is_pressed = true; key_shift->pre_command.value().command->press(); if (key_shift->pre_command.value().timing == Timing::InsteadOfFirstAction) { return; } } _pressed_key_list.push_front(*key); key->command->press(); } void HidEngineClass::performKeyRelease(uint8_t key_id) { for (auto &key : _pressed_key_list) { if (key.key_id == key_id) { auto i_item = etl::intrusive_list<Key>::iterator(key); _pressed_key_list.erase(i_item); key.command->release(); return; } } } std::tuple<KeyShift *, Key *> HidEngineClass::getCurrentKey(uint8_t key_id) { for (auto &started_key_shift_id : _started_key_shift_id_list) { for (auto &key_shift : _key_shift_map) { if (key_shift.key_shift_id.value == started_key_shift_id.value) { for (auto &key : key_shift.keymap) { if (key.key_id == key_id) { return {&key_shift, &key}; } } if (key_shift.keymap_overlay == KeymapOverlay::Disable) { return {&key_shift, nullptr}; } } } } for (auto &key : _keymap) { if (key.key_id == key_id) { return {nullptr, &key}; } } return {nullptr, nullptr}; } void HidEngineClass::startKeyShift(KeyShiftIdLink &key_shift_id) { if (key_shift_id.is_linked()) { return; } _started_key_shift_id_list.push_front(key_shift_id); // pre_command for (auto &key_shift : _key_shift_map) { if (key_shift.key_shift_id.value == key_shift_id.value && key_shift.pre_command.has_value() && key_shift.pre_command.value().timing == Timing::Immediately && key_shift.pre_command.value().is_pressed == false) { key_shift.pre_command.value().is_pressed = true; key_shift.pre_command.value().command->press(); } } } void HidEngineClass::stopKeyShift(KeyShiftIdLink &key_shift_id) { if (key_shift_id.is_linked() == false) { return; } auto i_item = etl::intrusive_list<KeyShiftIdLink>::iterator(key_shift_id); _started_key_shift_id_list.erase(i_item); key_shift_id.clear(); // 同じidが同時に押されることもあり得るので最後に押されていたかチェック for (auto &started_key_shift_id : _started_key_shift_id_list) { if (started_key_shift_id.value == key_shift_id.value) { return; } } // 最後のidならclean up for (auto &key_shift : _key_shift_map) { if (key_shift.key_shift_id.value == key_shift_id.value && key_shift.pre_command.has_value() && key_shift.pre_command.value().is_pressed == true) { key_shift.pre_command.value().is_pressed = false; key_shift.pre_command.value().command->release(); } } } //------------------------------------------------------------------+ // MovePointer //------------------------------------------------------------------+ void HidEngineClass::movePointer_impl(PointingDeviceId pointing_device_id) { if (_read_pointer_delta_cb == nullptr) { return; } Hid.waitReady(); int16_t delta_x = 0, delta_y = 0; _read_pointer_delta_cb(pointing_device_id, delta_x, delta_y); if (delta_x == 0 && delta_y == 0) { return; } BeforeMovePointerEventListener::_notifyBeforeMovePointer(pointing_device_id, delta_x, delta_y); Gesture *gesture = getCurrentGesture(pointing_device_id); if (gesture != nullptr) { processGesture(*gesture, delta_x, delta_y); } else { Hid.mouseMove(delta_x, delta_y); } } Gesture *HidEngineClass::getCurrentGesture(PointingDeviceId pointing_device_id) { for (auto &started_gesture_id : _started_gesture_id_list) { for (auto &gesture : _gesture_map) { if ((started_gesture_id.value == gesture.gesture_id.value) && (gesture.pointing_device_id == pointing_device_id)) { return &gesture; } } } return nullptr; } void HidEngineClass::processGesture(Gesture &gesture, int16_t delta_x, int16_t delta_y) { #if (HID_ENGINE_WAIT_TIME_AFTER_INSTEAD_OF_FIRST_GESTURE_MS != 0) if (gesture.instead_of_first_gesture_millis.has_value()) { uint32_t curr_millis = millis(); if (static_cast<uint32_t>(curr_millis - gesture.instead_of_first_gesture_millis.value()) <= HID_ENGINE_WAIT_TIME_AFTER_INSTEAD_OF_FIRST_GESTURE_MS) { return; } gesture.instead_of_first_gesture_millis = etl::nullopt; } #endif // 逆方向に動いたら距離をリセット if (bitRead(gesture.total_distance_x ^ static_cast<int32_t>(delta_x), 31)) { gesture.total_distance_x = 0; } if (bitRead(gesture.total_distance_y ^ static_cast<int32_t>(delta_y), 31)) { gesture.total_distance_y = 0; } // 距離を足す gesture.total_distance_x += delta_x; gesture.total_distance_y += delta_y; // 直近のマウスの移動距離の大きさによって実行する順序を変える if (abs(delta_x) >= abs(delta_y)) { processGestureX(gesture); processGestureY(gesture); } else { processGestureY(gesture); processGestureX(gesture); } } void HidEngineClass::processGestureX(Gesture &gesture) { uint8_t n_times = std::min<int32_t>(abs(gesture.total_distance_x / gesture.distance), UINT8_MAX); if (n_times == 0) { return; } BeforeGestureEventListener::_notifyBeforeGesture(gesture.gesture_id, gesture.pointing_device_id); bool is_right = gesture.total_distance_x > 0; gesture.total_distance_x %= gesture.distance; if (gesture.angle_snap == AngleSnap::Enable) { gesture.total_distance_y = 0; } processGesturePreCommand(gesture, n_times); if (n_times == 0) { return; } if (is_right) { CommandTapper.tap(gesture.right_command, n_times); } else { CommandTapper.tap(gesture.left_command, n_times); } } void HidEngineClass::processGestureY(Gesture &gesture) { uint8_t n_times = std::min<int32_t>(abs(gesture.total_distance_y / gesture.distance), UINT8_MAX); if (n_times == 0) { return; } BeforeGestureEventListener::_notifyBeforeGesture(gesture.gesture_id, gesture.pointing_device_id); bool is_down = gesture.total_distance_y > 0; gesture.total_distance_y %= gesture.distance; if (gesture.angle_snap == AngleSnap::Enable) { gesture.total_distance_x = 0; } processGesturePreCommand(gesture, n_times); if (n_times == 0) { return; } if (is_down > 0) { CommandTapper.tap(gesture.down_command, n_times); } else { CommandTapper.tap(gesture.up_command, n_times); } } void HidEngineClass::processGesturePreCommand(Gesture &gesture, uint8_t &n_timse) { if (gesture.pre_command.has_value() && gesture.pre_command.value().is_pressed == false) { gesture.pre_command.value().is_pressed = true; gesture.pre_command.value().command->press(); if (gesture.pre_command.value().timing == Timing::InsteadOfFirstAction) { n_timse--; gesture.instead_of_first_gesture_millis = millis(); } } } void HidEngineClass::startGesture(GestureIdLink &gesture_id) { if (gesture_id.is_linked()) { return; } _started_gesture_id_list.push_front(gesture_id); // pre_command for (auto &gesture : _gesture_map) { if (gesture.gesture_id.value == gesture_id.value && gesture.pre_command.has_value() && gesture.pre_command.value().timing == Timing::Immediately && gesture.pre_command.value().is_pressed == false) { gesture.pre_command.value().is_pressed = true; gesture.pre_command.value().command->press(); } } } void HidEngineClass::stopGesture(GestureIdLink &gesture_id) { if (gesture_id.is_linked() == false) { return; } auto i_item = etl::intrusive_list<GestureIdLink>::iterator(gesture_id); _started_gesture_id_list.erase(i_item); gesture_id.clear(); // 同じidが同時に押されることもあり得るので最後に押されていたかチェック for (auto &started_gesture_id : _started_gesture_id_list) { if (started_gesture_id.value == gesture_id.value) { return; } } // 最後のidならclean up for (auto &gesture : _gesture_map) { if (gesture.gesture_id.value == gesture_id.value) { if (gesture.pre_command.has_value() && gesture.pre_command.value().is_pressed == true) { gesture.pre_command.value().is_pressed = false; gesture.pre_command.value().command->release(); gesture.instead_of_first_gesture_millis = etl::nullopt; } gesture.total_distance_x = 0; gesture.total_distance_y = 0; } } } //------------------------------------------------------------------+ // RotateEncoder //------------------------------------------------------------------+ void HidEngineClass::rotateEncoder_impl(EncoderId encoder_id) { if (_read_encoder_step_cb == nullptr) { return; } Hid.waitReady(); int16_t step = 0; _read_encoder_step_cb(encoder_id, step); if (step == 0) { return; } BeforeRotateEncoderEventListener::_notifyBeforeRotateEncoder(encoder_id, step); EncoderShift *encoder = getCurrentEncoder(encoder_id); if (encoder == nullptr) { return; } encoder->total_step = etl::clamp(encoder->total_step + step, INT32_MIN, INT32_MAX); uint8_t n_times = std::min<int32_t>(abs(encoder->total_step) / encoder->step, UINT8_MAX); if (n_times == 0) { return; } encoder->total_step %= encoder->step; if (encoder->pre_command.has_value() && encoder->pre_command.value().is_pressed == false) { encoder->pre_command.value().is_pressed = true; encoder->pre_command.value().command->press(); if (encoder->pre_command.value().timing == Timing::InsteadOfFirstAction) { n_times--; if (n_times == 0) { return; } } } if (step > 0) { CommandTapper.tap(encoder->clockwise_command, n_times); } else { CommandTapper.tap(encoder->counterclockwise_command, n_times); } } EncoderShift *HidEngineClass::getCurrentEncoder(EncoderId encoder_id) { for (auto &started_encoder_shift_id : _started_encoder_shift_id_list) { for (auto &encoder : _encoder_shift_map) { if ((started_encoder_shift_id.value == encoder.encoder_shift_id.value) && (encoder.encoder_id == encoder_id)) { return &encoder; } } } for (auto &encoder : _encoder_map) { if (encoder.encoder_id == encoder_id) { return &encoder; } } return nullptr; } void HidEngineClass::startEncoderShift(EncoderShiftIdLink &encoder_shift_id) { if (encoder_shift_id.is_linked()) { return; } _started_encoder_shift_id_list.push_front(encoder_shift_id); // pre_command for (auto &encoder : _encoder_shift_map) { if (encoder.encoder_shift_id.value == encoder_shift_id.value && encoder.pre_command.has_value() && encoder.pre_command.value().timing == Timing::Immediately && encoder.pre_command.value().is_pressed == false) { encoder.pre_command.value().is_pressed = true; encoder.pre_command.value().command->press(); } } } void HidEngineClass::stopEncoderShift(EncoderShiftIdLink &encoder_shift_id) { if (encoder_shift_id.is_linked() == false) { return; } auto i_item = etl::intrusive_list<EncoderShiftIdLink>::iterator(encoder_shift_id); _started_encoder_shift_id_list.erase(i_item); encoder_shift_id.clear(); // 同じidが同時に押されることもあり得るので最後に押されていたかチェック for (auto &started_encoder_id : _started_encoder_shift_id_list) { if (started_encoder_id.value == encoder_shift_id.value) { return; } } // 最後のidならclean up for (auto &encoder : _encoder_shift_map) { if (encoder.encoder_shift_id.value == encoder_shift_id.value) { if (encoder.pre_command.has_value() && encoder.pre_command.value().is_pressed == true) { encoder.pre_command.value().is_pressed = false; encoder.pre_command.value().command->release(); } encoder.total_step = 0; } } } } // namespace Internal Internal::HidEngineClass HidEngine; } // namespace hidpg
[ "ogwrtty@gmail.com" ]
ogwrtty@gmail.com
4d6d965dc0f04d54144e9f9ad66a33bbf96f6111
30e1dc84fe8c54d26ef4a1aff000a83af6f612be
/src/external/boost/boost_1_68_0/libs/bimap/test/test_structured_pair.cpp
2d4fbdc5cc5609c5683a7cefc3300c075f9c53c2
[ "BSD-3-Clause", "BSL-1.0" ]
permissive
Sitispeaks/turicreate
0bda7c21ee97f5ae7dc09502f6a72abcb729536d
d42280b16cb466a608e7e723d8edfbe5977253b6
refs/heads/main
2023-05-19T17:55:21.938724
2021-06-14T17:53:17
2021-06-14T17:53:17
385,034,849
1
0
BSD-3-Clause
2021-07-11T19:23:21
2021-07-11T19:23:20
null
UTF-8
C++
false
false
2,328
cpp
// Boost.Bimap // // Copyright (c) 2006-2007 Matias Capeletto // // 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) // VC++ 8.0 warns on usage of certain Standard Library and API functions that // can be cause buffer overruns or other possible security issues if misused. // See http://msdn.microsoft.com/msdnmag/issues/05/05/SafeCandC/default.aspx // But the wording of the warning is misleading and unsettling, there are no // portable alternative functions, and VC++ 8.0's own libraries use the // functions in question. So turn off the warnings. #define _CRT_SECURE_NO_DEPRECATE #define _SCL_SECURE_NO_DEPRECATE #include <boost/config.hpp> // Boost.Test #include <boost/test/minimal.hpp> // std #include <utility> #include <cstddef> // Boost.Static_assert #include <boost/static_assert.hpp> // Boost.Bimap #include <boost/bimap/detail/test/check_metadata.hpp> #include <boost/bimap/relation/structured_pair.hpp> BOOST_BIMAP_TEST_STATIC_FUNCTION( static_metadata_test ) { using namespace boost::bimaps::relation; struct data_a { char data; }; struct data_b { double data; }; typedef structured_pair < data_a, data_b, normal_layout > sp_ab; typedef structured_pair < data_b, data_a, mirror_layout > sp_ba; BOOST_BIMAP_CHECK_METADATA(sp_ab, first_type , data_a); BOOST_BIMAP_CHECK_METADATA(sp_ab, second_type, data_b); BOOST_BIMAP_CHECK_METADATA(sp_ba, first_type , data_b); BOOST_BIMAP_CHECK_METADATA(sp_ba, second_type, data_a); } void test_basic() { using namespace boost::bimaps::relation; // Instanciate two pairs and test the storage alignmentDataData typedef structured_pair< short, double, normal_layout > pair_type; typedef structured_pair< double, short, mirror_layout > mirror_type; pair_type pa( 2, 3.1416 ); mirror_type pb( 3.1416, 2 ); BOOST_CHECK( pa.first == pb.second ); BOOST_CHECK( pa.second == pb.first ); } int test_main( int, char* [] ) { BOOST_BIMAP_CALL_TEST_STATIC_FUNCTION( static_are_storage_compatible_test ); BOOST_BIMAP_CALL_TEST_STATIC_FUNCTION( static_metadata_test ); test_basic(); return 0; }
[ "znation@apple.com" ]
znation@apple.com
c4d7311e9d80171e618ccd892cfbd0717b383483
16aa5d7812bb7a18cdfb85d0eaf1773d15b4284f
/type_to_enum.cpp
ae6a6e87e8ef7fffee9a64f70c61a7d6d8061264
[]
no_license
strvert/cpp-playground
b56339a565832319166ed3c78286876a6a3de670
bcdb154fcb80b01af13da4a595570d7e725e03e5
refs/heads/master
2023-07-27T14:56:06.472613
2021-09-07T14:26:52
2021-09-07T14:26:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,447
cpp
#include <iostream> #include <map> enum class TypeEnum : uint8_t { Unknown = 1, Int, Float, Double, Char, }; template<typename T> struct Mapper { struct MTable; using ET = TypeEnum; using enum ET; template<ET E> struct ToEnum { char _[static_cast<std::underlying_type_t<ET>>(E)]; }; inline static constexpr const ET Value = static_cast<ET>(sizeof(MTable::From(static_cast<T*>(nullptr)))); template<typename NP> using Type = std::add_pointer_t<NP>; struct MTable { static ToEnum<Unknown> From(...); static ToEnum<Int> From(Type<int>); static ToEnum<Float> From(Type<float>); static ToEnum<Double> From(Type<double>); static ToEnum<Char> From(Type<char>); }; }; template<typename T> TypeEnum MapperV = Mapper<T>::Value; int main() { const std::map<TypeEnum, const char*> ToString = { { TypeEnum::Unknown, "Unknown" }, { TypeEnum::Int, "Int" }, { TypeEnum::Float, "Float" }, { TypeEnum::Double, "Double" }, { TypeEnum::Char, "Char" }, }; std::cout << ToString.at(MapperV<int>) << std::endl; std::cout << ToString.at(MapperV<float>) << std::endl; std::cout << ToString.at(MapperV<double>) << std::endl; std::cout << ToString.at(MapperV<char>) << std::endl; std::cout << ToString.at(MapperV<bool>) << std::endl; std::cout << ToString.at(MapperV<TypeEnum>) << std::endl; }
[ "strv13570@gmail.com" ]
strv13570@gmail.com
9df4f84464466d05b097655f6435504762d6bb5a
b0c1a37e3cf5cb08541a045e2f9f3120e1af4fce
/LinearRemapFV.h
a437f671de416c257587305f79ef4f30a59a2011
[]
no_license
mmundt/MRMtempestremap
6678fb228716762a3ee6b8c9f0111c33f9268ddc
a995c919638bd298b5d038a6d1454c43ade7f128
refs/heads/master
2021-01-15T23:27:17.046170
2015-07-30T15:33:19
2015-07-30T15:33:19
30,560,664
0
0
null
null
null
null
UTF-8
C++
false
false
2,905
h
/////////////////////////////////////////////////////////////////////////////// /// /// \file LinearRemapFV.h /// \author Paul Ullrich /// \version September 1, 2014 /// /// <remarks> /// Copyright 2000-2014 Paul Ullrich /// /// This file is distributed as part of the Tempest source code package. /// Permission is granted to use, copy, modify and distribute this /// source code and its documentation under the terms of the GNU General /// Public License. This software is provided "as is" without express /// or implied warranty. /// </remarks> #ifndef _LINEARREMAPFV_H_ #define _LINEARREMAPFV_H_ #include "DataMatrix3D.h" /////////////////////////////////////////////////////////////////////////////// class Mesh; class OfflineMap; /////////////////////////////////////////////////////////////////////////////// /// <summary> /// Generate the OfflineMap for remapping from finite volumes to finite /// volumes. /// </summary> void LinearRemapFVtoFV( const Mesh & meshInput, const Mesh & meshOutput, const Mesh & meshOverlap, int nOrder, OfflineMap & mapRemap ); /////////////////////////////////////////////////////////////////////////////// /// <summary> /// Generate the OfflineMap for remapping from finite volumes to finite /// elements using simple sampling of the FV reconstruction. /// </summary> void LinearRemapFVtoGLL_Simple( const Mesh & meshInput, const Mesh & meshOutput, const Mesh & meshOverlap, const DataMatrix3D<int> & dataGLLNodes, const DataMatrix3D<double> & dataGLLJacobian, const DataVector<double> & dataGLLNodalArea, int nOrder, OfflineMap & mapRemap, bool fMonotone, bool fContinuous ); /////////////////////////////////////////////////////////////////////////////// /// <summary> /// Generate the OfflineMap for remapping from finite volumes to finite /// elements. /// </summary> void LinearRemapFVtoGLL( const Mesh & meshInput, const Mesh & meshOutput, const Mesh & meshOverlap, const DataMatrix3D<int> & dataGLLNodes, const DataMatrix3D<double> & dataGLLJacobian, const DataVector<double> & dataGLLNodalArea, int nOrder, OfflineMap & mapRemap, bool fMonotone, bool fContinuous ); /////////////////////////////////////////////////////////////////////////////// /* /// <summary> /// Generate the OfflineMap for remapping from finite elements to finite /// elements. /// </summary> void LinearRemapGLLtoGLL( const Mesh & meshInput, const Mesh & meshOutput, const Mesh & meshOverlap, const DataMatrix3D<int> & dataGLLNodesIn, const DataMatrix3D<double> & dataGLLJacobianIn, const DataMatrix3D<int> & dataGLLNodesOut, const DataMatrix3D<double> & dataGLLJacobianOut, const DataVector<double> & dataNodalAreaOut, int nPin, int nPout, OfflineMap & mapRemap, bool fMonotone, bool fContinuousIn, bool fContinuousOut ); */ /////////////////////////////////////////////////////////////////////////////// #endif
[ "paullrich@ucdavis.edu" ]
paullrich@ucdavis.edu
7c1304b2248d87b3af516d31b8e7a6e0e0bebd53
1381d80073068f122672484273142687d7e2479a
/execises/Network-Uva.cpp
bf5ce83a2c3eb88d0dfdd7b97fcad008484e81e5
[]
no_license
Guilherme26/algorithm_practices
17c313745f692934ef6a976bee99259cbf0787d0
ac3c65969173f6cc754b98e6fb3ae48d45e3c3c5
refs/heads/master
2021-06-27T21:46:50.087521
2020-09-22T14:40:48
2020-09-22T14:40:48
131,619,766
0
0
null
null
null
null
UTF-8
C++
false
false
1,098
cpp
#include <bits/stdc++.h> using namespace std; #define WHITE 1 #define BLACK 0 typedef struct{ int color; vector<int> adjs; } Vertex; Vertex graph[111]; void initialize(bool clear){ for(int i = 0; i < 111; ++i){ graph[i].color = WHITE; if(clear) graph[i].adjs.clear(); } } void DFS(int initial){ // printf("%d\n", initial); graph[initial].color = BLACK; for(int i = 0; i < graph[initial].adjs.size(); ++i){ int curVertex = graph[initial].adjs[i]; if(graph[curVertex].color) DFS(curVertex); } } int main(){ int N; while(cin >> N and N){ int V, VNg, criticals = 0; char scape; initialize(true); while(cin >> V and V){ while(scanf("%d%c", &VNg, &scape) == 2){ graph[V].adjs.push_back(VNg); graph[VNg].adjs.push_back(V); if(scape == '\n') break; } } for(int i = 1; i <= N; ++i){ int calls = 0; graph[i].color = BLACK; for(int j = 1; j <= N; ++j){ if(graph[j].color){ DFS(j); calls += 1; } } initialize(false); if(calls > 1) criticals += 1; } printf("%d\n", criticals); } return 0; }
[ "guilherme.hra26@gmail.com" ]
guilherme.hra26@gmail.com
f1e8046f4fd8a4e81e69cd2187dec7ecc7b168e3
fb72a82827496e66e04ecb29abbca788a1ea0525
/src/rpc/rawtransaction.cpp
b130783db6f85798a215a9edd3192c0d6f6dff61
[ "MIT" ]
permissive
exiliumcore/exilium
92631c2e7abeeae6a80debbb699441d6b56e2fee
6aa88fe0c40fe72850e5bdb265741a375b2ab766
refs/heads/master
2020-03-14T05:50:41.214608
2018-05-13T01:00:24
2018-05-13T01:00:24
131,472,364
0
1
null
null
null
null
UTF-8
C++
false
false
39,585
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Copyright (c) 2018 The Exilium Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "chain.h" #include "coins.h" #include "consensus/validation.h" #include "core_io.h" #include "init.h" #include "keystore.h" #include "validation.h" #include "merkleblock.h" #include "net.h" #include "policy/policy.h" #include "primitives/transaction.h" #include "rpc/server.h" #include "script/script.h" #include "script/script_error.h" #include "script/sign.h" #include "script/standard.h" #include "txmempool.h" #include "uint256.h" #include "utilstrencodings.h" #include "instantx.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #endif #include <stdint.h> #include <boost/assign/list_of.hpp> #include <univalue.h> using namespace std; void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex) { txnouttype type; vector<CTxDestination> addresses; int nRequired; out.push_back(Pair("asm", ScriptToAsmStr(scriptPubKey))); if (fIncludeHex) out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.push_back(Pair("type", GetTxnOutputType(type))); return; } out.push_back(Pair("reqSigs", nRequired)); out.push_back(Pair("type", GetTxnOutputType(type))); UniValue a(UniValue::VARR); BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); out.push_back(Pair("addresses", a)); } void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry) { uint256 txid = tx.GetHash(); entry.push_back(Pair("txid", txid.GetHex())); entry.push_back(Pair("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION))); entry.push_back(Pair("version", tx.nVersion)); entry.push_back(Pair("locktime", (int64_t)tx.nLockTime)); UniValue vin(UniValue::VARR); BOOST_FOREACH(const CTxIn& txin, tx.vin) { UniValue in(UniValue::VOBJ); if (tx.IsCoinBase()) in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); else { in.push_back(Pair("txid", txin.prevout.hash.GetHex())); in.push_back(Pair("vout", (int64_t)txin.prevout.n)); UniValue o(UniValue::VOBJ); o.push_back(Pair("asm", ScriptToAsmStr(txin.scriptSig, true))); o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); in.push_back(Pair("scriptSig", o)); // Add address and value info if spentindex enabled CSpentIndexValue spentInfo; CSpentIndexKey spentKey(txin.prevout.hash, txin.prevout.n); if (GetSpentIndex(spentKey, spentInfo)) { in.push_back(Pair("value", ValueFromAmount(spentInfo.satoshis))); in.push_back(Pair("valueSat", spentInfo.satoshis)); if (spentInfo.addressType == 1) { in.push_back(Pair("address", CBitcoinAddress(CKeyID(spentInfo.addressHash)).ToString())); } else if (spentInfo.addressType == 2) { in.push_back(Pair("address", CBitcoinAddress(CScriptID(spentInfo.addressHash)).ToString())); } } } in.push_back(Pair("sequence", (int64_t)txin.nSequence)); vin.push_back(in); } entry.push_back(Pair("vin", vin)); UniValue vout(UniValue::VARR); for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; UniValue out(UniValue::VOBJ); out.push_back(Pair("value", ValueFromAmount(txout.nValue))); out.push_back(Pair("valueSat", txout.nValue)); out.push_back(Pair("n", (int64_t)i)); UniValue o(UniValue::VOBJ); ScriptPubKeyToJSON(txout.scriptPubKey, o, true); out.push_back(Pair("scriptPubKey", o)); // Add spent information if spentindex is enabled CSpentIndexValue spentInfo; CSpentIndexKey spentKey(txid, i); if (GetSpentIndex(spentKey, spentInfo)) { out.push_back(Pair("spentTxId", spentInfo.txid.GetHex())); out.push_back(Pair("spentIndex", (int)spentInfo.inputIndex)); out.push_back(Pair("spentHeight", spentInfo.blockHeight)); } vout.push_back(out); } entry.push_back(Pair("vout", vout)); if (!hashBlock.IsNull()) { entry.push_back(Pair("blockhash", hashBlock.GetHex())); BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (chainActive.Contains(pindex)) { entry.push_back(Pair("height", pindex->nHeight)); entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight)); entry.push_back(Pair("time", pindex->GetBlockTime())); entry.push_back(Pair("blocktime", pindex->GetBlockTime())); } else { entry.push_back(Pair("height", -1)); entry.push_back(Pair("confirmations", 0)); } } } } UniValue getrawtransaction(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getrawtransaction \"txid\" ( verbose )\n" "\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n" "or there is an unspent output in the utxo for this transaction. To make it always work,\n" "you need to maintain a transaction index, using the -txindex command line option.\n" "\nReturn the raw transaction data.\n" "\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n" "If verbose is non-zero, returns an Object with information about 'txid'.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. verbose (numeric, optional, default=0) If 0, return a string, other return a json object\n" "\nResult (if verbose is not set or set to 0):\n" "\"data\" (string) The serialized, hex-encoded data for 'txid'\n" "\nResult (if verbose > 0):\n" "{\n" " \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n" " \"txid\" : \"id\", (string) The transaction id (same as provided)\n" " \"size\" : n, (numeric) The transaction size\n" " \"version\" : n, (numeric) The version\n" " \"locktime\" : ttt, (numeric) The lock time\n" " \"vin\" : [ (array of json objects)\n" " {\n" " \"txid\": \"id\", (string) The transaction id\n" " \"vout\": n, (numeric) \n" " \"scriptSig\": { (json object) The script\n" " \"asm\": \"asm\", (string) asm\n" " \"hex\": \"hex\" (string) hex\n" " },\n" " \"sequence\": n (numeric) The script sequence number\n" " }\n" " ,...\n" " ],\n" " \"vout\" : [ (array of json objects)\n" " {\n" " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n" " \"n\" : n, (numeric) index\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"asm\", (string) the asm\n" " \"hex\" : \"hex\", (string) the hex\n" " \"reqSigs\" : n, (numeric) The required sigs\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " \"addresses\" : [ (json array of string)\n" " \"exiliumaddress\" (string) exilium address\n" " ,...\n" " ]\n" " }\n" " }\n" " ,...\n" " ],\n" " \"blockhash\" : \"hash\", (string) the block hash\n" " \"confirmations\" : n, (numeric) The confirmations\n" " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n" " \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n" "}\n" "\nExamples:\n" + HelpExampleCli("getrawtransaction", "\"mytxid\"") + HelpExampleCli("getrawtransaction", "\"mytxid\" 1") + HelpExampleRpc("getrawtransaction", "\"mytxid\", 1") ); LOCK(cs_main); uint256 hash = ParseHashV(params[0], "parameter 1"); bool fVerbose = false; if (params.size() > 1) fVerbose = (params[1].get_int() != 0); CTransaction tx; uint256 hashBlock; if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, true)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); string strHex = EncodeHexTx(tx); if (!fVerbose) return strHex; UniValue result(UniValue::VOBJ); result.push_back(Pair("hex", strHex)); TxToJSON(tx, hashBlock, result); return result; } UniValue gettxoutproof(const UniValue& params, bool fHelp) { if (fHelp || (params.size() != 1 && params.size() != 2)) throw runtime_error( "gettxoutproof [\"txid\",...] ( blockhash )\n" "\nReturns a hex-encoded proof that \"txid\" was included in a block.\n" "\nNOTE: By default this function only works sometimes. This is when there is an\n" "unspent output in the utxo for this transaction. To make it always work,\n" "you need to maintain a transaction index, using the -txindex command line option or\n" "specify the block in which the transaction is included in manually (by blockhash).\n" "\nReturn the raw transaction data.\n" "\nArguments:\n" "1. \"txids\" (string) A json array of txids to filter\n" " [\n" " \"txid\" (string) A transaction hash\n" " ,...\n" " ]\n" "2. \"block hash\" (string, optional) If specified, looks for txid in the block with this hash\n" "\nResult:\n" "\"data\" (string) A string that is a serialized, hex-encoded data for the proof.\n" "\nExamples:\n" + HelpExampleCli("gettxoutproof", "'[\"mytxid\",...]'") + HelpExampleCli("gettxoutproof", "'[\"mytxid\",...]' \"blockhash\"") + HelpExampleRpc("gettxoutproof", "[\"mytxid\",...], \"blockhash\"") ); set<uint256> setTxids; uint256 oneTxid; UniValue txids = params[0].get_array(); for (unsigned int idx = 0; idx < txids.size(); idx++) { const UniValue& txid = txids[idx]; if (txid.get_str().length() != 64 || !IsHex(txid.get_str())) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid txid ")+txid.get_str()); uint256 hash(uint256S(txid.get_str())); if (setTxids.count(hash)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated txid: ")+txid.get_str()); setTxids.insert(hash); oneTxid = hash; } LOCK(cs_main); CBlockIndex* pblockindex = NULL; uint256 hashBlock; if (params.size() > 1) { hashBlock = uint256S(params[1].get_str()); if (!mapBlockIndex.count(hashBlock)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); pblockindex = mapBlockIndex[hashBlock]; } else { const Coin& coin = AccessByTxid(*pcoinsTip, oneTxid); if (!coin.IsSpent() && coin.nHeight > 0 && coin.nHeight <= chainActive.Height()) { pblockindex = chainActive[coin.nHeight]; } } if (pblockindex == NULL) { CTransaction tx; if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block"); if (!mapBlockIndex.count(hashBlock)) throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt"); pblockindex = mapBlockIndex[hashBlock]; } CBlock block; if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus())) throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk"); unsigned int ntxFound = 0; BOOST_FOREACH(const CTransaction&tx, block.vtx) if (setTxids.count(tx.GetHash())) ntxFound++; if (ntxFound != setTxids.size()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "(Not all) transactions not found in specified block"); CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION); CMerkleBlock mb(block, setTxids); ssMB << mb; std::string strHex = HexStr(ssMB.begin(), ssMB.end()); return strHex; } UniValue verifytxoutproof(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "verifytxoutproof \"proof\"\n" "\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n" "and throwing an RPC error if the block is not in our best chain\n" "\nArguments:\n" "1. \"proof\" (string, required) The hex-encoded proof generated by gettxoutproof\n" "\nResult:\n" "[\"txid\"] (array, strings) The txid(s) which the proof commits to, or empty array if the proof is invalid\n" "\nExamples:\n" + HelpExampleCli("verifytxoutproof", "\"proof\"") + HelpExampleRpc("gettxoutproof", "\"proof\"") ); CDataStream ssMB(ParseHexV(params[0], "proof"), SER_NETWORK, PROTOCOL_VERSION); CMerkleBlock merkleBlock; ssMB >> merkleBlock; UniValue res(UniValue::VARR); vector<uint256> vMatch; if (merkleBlock.txn.ExtractMatches(vMatch) != merkleBlock.header.hashMerkleRoot) return res; LOCK(cs_main); if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()])) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain"); BOOST_FOREACH(const uint256& hash, vMatch) res.push_back(hash.GetHex()); return res; } UniValue createrawtransaction(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 2 || params.size() > 3) throw runtime_error( "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,\"data\":\"hex\",...} ( locktime )\n" "\nCreate a transaction spending the given inputs and creating new outputs.\n" "Outputs can be addresses or data.\n" "Returns hex-encoded raw transaction.\n" "Note that the transaction's inputs are not signed, and\n" "it is not stored in the wallet or transmitted to the network.\n" "\nArguments:\n" "1. \"transactions\" (string, required) A json array of json objects\n" " [\n" " {\n" " \"txid\":\"id\", (string, required) The transaction id\n" " \"vout\":n (numeric, required) The output number\n" " }\n" " ,...\n" " ]\n" "2. \"outputs\" (string, required) a json object with outputs\n" " {\n" " \"address\": x.xxx (numeric or string, required) The key is the exilium address, the numeric value (can be string) is the " + CURRENCY_UNIT + " amount\n" " \"data\": \"hex\", (string, required) The key is \"data\", the value is hex encoded data\n" " ...\n" " }\n" "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n" "\nResult:\n" "\"transaction\" (string) hex string of the transaction\n" "\nExamples\n" + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"") + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"data\\\":\\\"00010203\\\"}\"") + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"") + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"data\\\":\\\"00010203\\\"}\"") ); LOCK(cs_main); RPCTypeCheck(params, boost::assign::list_of(UniValue::VARR)(UniValue::VOBJ)(UniValue::VNUM), true); if (params[0].isNull() || params[1].isNull()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null"); UniValue inputs = params[0].get_array(); UniValue sendTo = params[1].get_obj(); CMutableTransaction rawTx; if (params.size() > 2 && !params[2].isNull()) { int64_t nLockTime = params[2].get_int64(); if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range"); rawTx.nLockTime = nLockTime; } for (unsigned int idx = 0; idx < inputs.size(); idx++) { const UniValue& input = inputs[idx]; const UniValue& o = input.get_obj(); uint256 txid = ParseHashO(o, "txid"); const UniValue& vout_v = find_value(o, "vout"); if (!vout_v.isNum()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); uint32_t nSequence = (rawTx.nLockTime ? std::numeric_limits<uint32_t>::max() - 1 : std::numeric_limits<uint32_t>::max()); CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence); rawTx.vin.push_back(in); } set<CBitcoinAddress> setAddress; vector<string> addrList = sendTo.getKeys(); BOOST_FOREACH(const string& name_, addrList) { if (name_ == "data") { std::vector<unsigned char> data = ParseHexV(sendTo[name_].getValStr(),"Data"); CTxOut out(0, CScript() << OP_RETURN << data); rawTx.vout.push_back(out); } else { CBitcoinAddress address(name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid exilium address: ")+name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_); setAddress.insert(address); CScript scriptPubKey = GetScriptForDestination(address.Get()); CAmount nAmount = AmountFromValue(sendTo[name_]); CTxOut out(nAmount, scriptPubKey); rawTx.vout.push_back(out); } } return EncodeHexTx(rawTx); } UniValue decoderawtransaction(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decoderawtransaction \"hexstring\"\n" "\nReturn a JSON object representing the serialized, hex-encoded transaction.\n" "\nArguments:\n" "1. \"hex\" (string, required) The transaction hex string\n" "\nResult:\n" "{\n" " \"txid\" : \"id\", (string) The transaction id\n" " \"size\" : n, (numeric) The transaction size\n" " \"version\" : n, (numeric) The version\n" " \"locktime\" : ttt, (numeric) The lock time\n" " \"vin\" : [ (array of json objects)\n" " {\n" " \"txid\": \"id\", (string) The transaction id\n" " \"vout\": n, (numeric) The output number\n" " \"scriptSig\": { (json object) The script\n" " \"asm\": \"asm\", (string) asm\n" " \"hex\": \"hex\" (string) hex\n" " },\n" " \"sequence\": n (numeric) The script sequence number\n" " }\n" " ,...\n" " ],\n" " \"vout\" : [ (array of json objects)\n" " {\n" " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n" " \"n\" : n, (numeric) index\n" " \"scriptPubKey\" : { (json object)\n" " \"asm\" : \"asm\", (string) the asm\n" " \"hex\" : \"hex\", (string) the hex\n" " \"reqSigs\" : n, (numeric) The required sigs\n" " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n" " \"addresses\" : [ (json array of string)\n" " \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwg\" (string) exilium address\n" " ,...\n" " ]\n" " }\n" " }\n" " ,...\n" " ],\n" "}\n" "\nExamples:\n" + HelpExampleCli("decoderawtransaction", "\"hexstring\"") + HelpExampleRpc("decoderawtransaction", "\"hexstring\"") ); LOCK(cs_main); RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)); CTransaction tx; if (!DecodeHexTx(tx, params[0].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); UniValue result(UniValue::VOBJ); TxToJSON(tx, uint256(), result); return result; } UniValue decodescript(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decodescript \"hex\"\n" "\nDecode a hex-encoded script.\n" "\nArguments:\n" "1. \"hex\" (string) the hex encoded script\n" "\nResult:\n" "{\n" " \"asm\":\"asm\", (string) Script public key\n" " \"hex\":\"hex\", (string) hex encoded public key\n" " \"type\":\"type\", (string) The output type\n" " \"reqSigs\": n, (numeric) The required signatures\n" " \"addresses\": [ (json array of string)\n" " \"address\" (string) exilium address\n" " ,...\n" " ],\n" " \"p2sh\",\"address\" (string) address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH).\n" "}\n" "\nExamples:\n" + HelpExampleCli("decodescript", "\"hexstring\"") + HelpExampleRpc("decodescript", "\"hexstring\"") ); RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)); UniValue r(UniValue::VOBJ); CScript script; if (params[0].get_str().size() > 0){ vector<unsigned char> scriptData(ParseHexV(params[0], "argument")); script = CScript(scriptData.begin(), scriptData.end()); } else { // Empty scripts are valid } ScriptPubKeyToJSON(script, r, false); UniValue type; type = find_value(r, "type"); if (type.isStr() && type.get_str() != "scripthash") { // P2SH cannot be wrapped in a P2SH. If this script is already a P2SH, // don't return the address for a P2SH of the P2SH. r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString())); } return r; } /** Pushes a JSON object for script verification or signing errors to vErrorsRet. */ static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage) { UniValue entry(UniValue::VOBJ); entry.push_back(Pair("txid", txin.prevout.hash.ToString())); entry.push_back(Pair("vout", (uint64_t)txin.prevout.n)); entry.push_back(Pair("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); entry.push_back(Pair("sequence", (uint64_t)txin.nSequence)); entry.push_back(Pair("error", strMessage)); vErrorsRet.push_back(entry); } UniValue signrawtransaction(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 4) throw runtime_error( "signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n" "\nSign inputs for raw transaction (serialized, hex-encoded).\n" "The second optional argument (may be null) is an array of previous transaction outputs that\n" "this transaction depends on but may not yet be in the block chain.\n" "The third optional argument (may be null) is an array of base58-encoded private\n" "keys that, if given, will be the only keys used to sign the transaction.\n" #ifdef ENABLE_WALLET + HelpRequiringPassphrase() + "\n" #endif "\nArguments:\n" "1. \"hexstring\" (string, required) The transaction hex string\n" "2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n" " [ (json array of json objects, or 'null' if none provided)\n" " {\n" " \"txid\":\"id\", (string, required) The transaction id\n" " \"vout\":n, (numeric, required) The output number\n" " \"scriptPubKey\": \"hex\", (string, required) script key\n" " \"redeemScript\": \"hex\" (string, required for P2SH) redeem script\n" " }\n" " ,...\n" " ]\n" "3. \"privatekeys\" (string, optional) A json array of base58-encoded private keys for signing\n" " [ (json array of strings, or 'null' if none provided)\n" " \"privatekey\" (string) private key in base58-encoding\n" " ,...\n" " ]\n" "4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n" " \"ALL\"\n" " \"NONE\"\n" " \"SINGLE\"\n" " \"ALL|ANYONECANPAY\"\n" " \"NONE|ANYONECANPAY\"\n" " \"SINGLE|ANYONECANPAY\"\n" "\nResult:\n" "{\n" " \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n" " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n" " \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n" " {\n" " \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n" " \"vout\" : n, (numeric) The index of the output to spent and used as input\n" " \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n" " \"sequence\" : n, (numeric) Script sequence number\n" " \"error\" : \"text\" (string) Verification or signing error related to the input\n" " }\n" " ,...\n" " ]\n" "}\n" "\nExamples:\n" + HelpExampleCli("signrawtransaction", "\"myhex\"") + HelpExampleRpc("signrawtransaction", "\"myhex\"") ); #ifdef ENABLE_WALLET LOCK2(cs_main, pwalletMain ? &pwalletMain->cs_wallet : NULL); #else LOCK(cs_main); #endif RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VSTR), true); vector<unsigned char> txData(ParseHexV(params[0], "argument 1")); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); vector<CMutableTransaction> txVariants; while (!ssData.empty()) { try { CMutableTransaction tx; ssData >> tx; txVariants.push_back(tx); } catch (const std::exception&) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } } if (txVariants.empty()) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction"); // mergedTx will end up with all the signatures; it // starts as a clone of the rawtx: CMutableTransaction mergedTx(txVariants[0]); // Fetch previous transactions (inputs): CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); { LOCK(mempool.cs); CCoinsViewCache &viewChain = *pcoinsTip; CCoinsViewMemPool viewMempool(&viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) { view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail. } view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long } bool fGivenKeys = false; CBasicKeyStore tempKeystore; if (params.size() > 2 && !params[2].isNull()) { fGivenKeys = true; UniValue keys = params[2].get_array(); for (unsigned int idx = 0; idx < keys.size(); idx++) { UniValue k = keys[idx]; CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(k.get_str()); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key"); CKey key = vchSecret.GetKey(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); tempKeystore.AddKey(key); } } #ifdef ENABLE_WALLET else if (pwalletMain) EnsureWalletIsUnlocked(); #endif // Add previous txouts given in the RPC call: if (params.size() > 1 && !params[1].isNull()) { UniValue prevTxs = params[1].get_array(); for (unsigned int idx = 0; idx < prevTxs.size(); idx++) { const UniValue& p = prevTxs[idx]; if (!p.isObject()) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}"); UniValue prevOut = p.get_obj(); RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR)); uint256 txid = ParseHashO(prevOut, "txid"); int nOut = find_value(prevOut, "vout").get_int(); if (nOut < 0) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive"); COutPoint out(txid, nOut); vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey")); CScript scriptPubKey(pkData.begin(), pkData.end()); { const Coin& coin = view.AccessCoin(out); if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) { string err("Previous output scriptPubKey mismatch:\n"); err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+ ScriptToAsmStr(scriptPubKey); throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err); } Coin newcoin; newcoin.out.scriptPubKey = scriptPubKey; newcoin.out.nValue = 0; newcoin.nHeight = 1; view.AddCoin(out, std::move(newcoin), true); } // if redeemScript given and not using the local wallet (private keys // given), add redeemScript to the tempKeystore so it can be signed: if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) { RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR)("redeemScript",UniValue::VSTR)); UniValue v = find_value(prevOut, "redeemScript"); if (!v.isNull()) { vector<unsigned char> rsData(ParseHexV(v, "redeemScript")); CScript redeemScript(rsData.begin(), rsData.end()); tempKeystore.AddCScript(redeemScript); } } } } #ifdef ENABLE_WALLET const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain); #else const CKeyStore& keystore = tempKeystore; #endif int nHashType = SIGHASH_ALL; if (params.size() > 3 && !params[3].isNull()) { static map<string, int> mapSigHashValues = boost::assign::map_list_of (string("ALL"), int(SIGHASH_ALL)) (string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)) (string("NONE"), int(SIGHASH_NONE)) (string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)) (string("SINGLE"), int(SIGHASH_SINGLE)) (string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)) ; string strHashType = params[3].get_str(); if (mapSigHashValues.count(strHashType)) nHashType = mapSigHashValues[strHashType]; else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param"); } bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); // Script verification errors UniValue vErrors(UniValue::VARR); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; const Coin& coin = view.AccessCoin(txin.prevout); if (coin.IsSpent()) { TxInErrorToJSON(txin, vErrors, "Input not found or already spent"); continue; } const CScript& prevPubKey = coin.out.scriptPubKey; txin.scriptSig.clear(); // Only sign SIGHASH_SINGLE if there's a corresponding output: if (!fHashSingle || (i < mergedTx.vout.size())) SignSignature(keystore, prevPubKey, mergedTx, i, nHashType); // ... and merge in other signatures: BOOST_FOREACH(const CMutableTransaction& txv, txVariants) { txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig); } ScriptError serror = SCRIPT_ERR_OK; if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i), &serror)) { TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror)); } } bool fComplete = vErrors.empty(); UniValue result(UniValue::VOBJ); result.push_back(Pair("hex", EncodeHexTx(mergedTx))); result.push_back(Pair("complete", fComplete)); if (!vErrors.empty()) { result.push_back(Pair("errors", vErrors)); } return result; } UniValue sendrawtransaction(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "sendrawtransaction \"hexstring\" ( allowhighfees instantsend )\n" "\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n" "\nAlso see createrawtransaction and signrawtransaction calls.\n" "\nArguments:\n" "1. \"hexstring\" (string, required) The hex string of the raw transaction)\n" "2. allowhighfees (boolean, optional, default=false) Allow high fees\n" "3. instantsend (boolean, optional, default=false) Use InstantSend to send this transaction\n" "\nResult:\n" "\"hex\" (string) The transaction hash in hex\n" "\nExamples:\n" "\nCreate a transaction\n" + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") + "Sign the transaction, and get back the hex\n" + HelpExampleCli("signrawtransaction", "\"myhex\"") + "\nSend the transaction (signed hex)\n" + HelpExampleCli("sendrawtransaction", "\"signedhex\"") + "\nAs a json rpc call\n" + HelpExampleRpc("sendrawtransaction", "\"signedhex\"") ); LOCK(cs_main); RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL)(UniValue::VBOOL)); // parse hex string from parameter CTransaction tx; if (!DecodeHexTx(tx, params[0].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); uint256 hashTx = tx.GetHash(); bool fOverrideFees = false; if (params.size() > 1) fOverrideFees = params[1].get_bool(); bool fInstantSend = false; if (params.size() > 2) fInstantSend = params[2].get_bool(); CCoinsViewCache &view = *pcoinsTip; bool fHaveChain = false; for (size_t o = 0; !fHaveChain && o < tx.vout.size(); o++) { const Coin& existingCoin = view.AccessCoin(COutPoint(hashTx, o)); fHaveChain = !existingCoin.IsSpent(); } bool fHaveMempool = mempool.exists(hashTx); if (!fHaveMempool && !fHaveChain) { // push to local node and sync with wallets if (fInstantSend && !instantsend.ProcessTxLockRequest(tx, *g_connman)) { throw JSONRPCError(RPC_TRANSACTION_ERROR, "Not a valid InstantSend transaction, see debug.log for more info"); } CValidationState state; bool fMissingInputs; if (!AcceptToMemoryPool(mempool, state, tx, false, &fMissingInputs, false, !fOverrideFees)) { if (state.IsInvalid()) { throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason())); } else { if (fMissingInputs) { throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs"); } throw JSONRPCError(RPC_TRANSACTION_ERROR, state.GetRejectReason()); } } } else if (fHaveChain) { throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain"); } if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); g_connman->RelayTransaction(tx); return hashTx.GetHex(); }
[ "devexilium@gmail.com" ]
devexilium@gmail.com
16f4640694be942494c95e736078113659b21422
501ab25fa68690556d90d528b0c8fb6ef5b0eeee
/Белый пояс/Неделя 1/Второе вхождение/Vtor.vhoz.cpp
90f262061b86a95882481de0084254b8e45c0ebc
[]
no_license
spectrdort/kurs_yandex
2ec6badf4532eb2ae70a44c54bfafabe7f9f7407
3c2571720947f9b508bd577f8c4fd435cd984193
refs/heads/master
2023-06-09T14:09:08.869588
2021-06-15T19:55:38
2021-06-15T19:55:38
366,669,939
0
0
null
2021-06-15T19:55:39
2021-05-12T09:58:06
C++
UTF-8
C++
false
false
360
cpp
#include <iostream> #include <vector> #include <string> #include <algorithm> int main() { std::string n; std::cin >> n; int x = 0; for (int i = 0; i < n.size(); ++i) { if (n[i] == 'f') { x++; if (x >= 2) { std::cout << i; return 0; } } } if (x == 0) { std::cout << "-2"; } else { std::cout << "-1"; } return 0; }
[ "sms1995@rocketmail.com" ]
sms1995@rocketmail.com
38205e65b5eaadbc45cdfa297a42b7641655cc81
67b7a7085447b7561208ed6df95dd3133df580e2
/may01/macri/src/Shaders/IawShader.h
e6e7246ce818462111b776ce5a4961a18d47d258
[ "LicenseRef-scancode-other-permissive" ]
permissive
dwilliamson/GDMagArchive
81fd5b708417697bfb2caf8a983dd3ad7decdaf7
701948bbd74b7ae765be8cdaf4ae0f875e2bbf8e
refs/heads/master
2021-06-07T23:41:08.343776
2016-10-31T14:42:20
2016-10-31T14:42:20
72,441,821
74
4
null
null
null
null
WINDOWS-1252
C++
false
false
10,904
h
// IawShader.h App Wizard Version 2.0 Beta 1 // ---------------------------------------------------------------------- // // Copyright © 2001 Intel Corporation // All Rights Reserved // // Permission is granted to use, copy, distribute and prepare derivative works of this // software for any purpose and without fee, provided, that the above copyright notice // and this statement appear in all copies. Intel makes no representations about the // suitability of this software for any purpose. This software is provided "AS IS." // // Intel specifically disclaims all warranties, express or implied, and all liability, // including consequential and other indirect damages, for the use of this software, // including liability for infringement of any proprietary rights, and including the // warranties of merchantability and fitness for a particular purpose. Intel does not // assume any responsibility for any errors which may appear in this software nor any // responsibility to update it. // ---------------------------------------------------------------------- // Authors: Kim Pallister,Dean Macri - Intel Technology Diffusion Team // ---------------------------------------------------------------------- #if !defined(IawShader_h) #define IawShader_h #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 /* //This class is used encapsulate a component of a shader pass. class IawShaderComponent { //public methods public: IawShaderComponent(char* strname = "Unnamed"); virtual ~IawShaderComponent(); HRESULT ActivateShaderComponent(); HRESULT SetStateBlock(DWORD dwSB); HRESULT SetVertexShader(DWORD dwVS); HRESULT SetPixelShader(DWORD dwPS); HRESULT SetMatrix(IawMatrix mx, DWORD mxtype); HRESULT SetName(char *strname); inline DWORD GetComponentType () {return m_dwComponentType}; inline DWORD GetStateBlock () {return m_dwStateBlock}; inline DWORD GetVertexShader () {return m_dwVertexShader}; inline DWORD GetPixelShader () {return m_dwPixelShader}; inline IawMatrix GetMatrix() {return m_mxMat}; inline DWORD GetMatrixType() {return m_dwMatType}; HRESULT AddChild(IawShaderComponent *pComponent); inline IawShaderComponent* GetChild() {return m_pNext;} void TargetChanging(); void CheckProperties(CD3DWrapper *pD3DWrapper, bool &b_alpha); HRESULT Activate(); //private methods & member vars private: char m_strShaderComponentName[255]; DWORD m_dwShaderComponentType; DWORD m_dwStateBlock; DWORD m_dwVertexShader; DWORD m_dwPixelShader; IawMatrix m_mxMat; DWORD m_dwMatType; bool m_bValidOnCurrentDevice; // IawShaderComponent *m_pNext; HRESULT CheckAgainstChildren(IawShaderComponent *pPotentialParent, IawShaderComponent *pPotentialChild); }; */ /** * This class describes a shader element. */ class IawShaderElement { public: /** * Constructor. * @param Id The Id for this element. * @param name A name for this element. */ IawShaderElement(int Id, char* name = "Unnamed Element"); /** Destructor */ virtual ~IawShaderElement(); /** Set the element name */ HRESULT SetName(char* name); //@{ /** Access method */ IawShaderElement* GetNext() {return mpNext;} void SetNext(IawShaderElement* pTemp) {mpNext = pTemp;} int GetId() {return mElementId;} char* GetName() {return mElementName;} void SetValid(bool valid) {mValid = valid;} bool GetValid() {return mValid;} HRESULT SetStateBlock(DWORD stateBlock, DWORD flags); DWORD GetStateBlock() {return mStateBlock;} //@} /** * Delete the state block for this element. * @param pWrapper The wrapper for the device this element as a state block on */ HRESULT DeleteStateBlock(IawD3dWrapper* pWrapper); /** * Add a child to this element's hierarchy. */ HRESULT AddChild(IawShaderElement* pChildElement); /** Flag this element as a state block */ static const int STATE_BLOCK; /** Flag this element as a vertex shader */ static const int VERTEX_SHADER; /** Flag this element as a pixel shader */ static const int PIXEL_SHADER; /** Flag this element as a matrix */ static const int MATRIX; private: char mElementName[255]; int mElementId; DWORD mStateBlock; DWORD mFlags; bool mValid; IawShaderElement* mpNext; HRESULT CheckAgainstChildren(IawShaderElement* pPotentialParent, IawShaderElement* pPotentialChild); }; /** * This class encapsulates a component of a shader pass. */ class IawShaderComponent { public: /** * Constructor. * @param Id The Id for this component. * @param name A name for this component. * @param flags Any flags (END_OF_PASS, NEGATING,etc...). */ IawShaderComponent(int Id, char* name = "Unnamed Component", DWORD flags = 0); /** Destructor */ virtual ~IawShaderComponent(); /** Set the component name */ HRESULT SetName(char* name); //@{ /** Access method */ IawShaderComponent* GetNext() {return mpNext;} void SetNext(IawShaderComponent* pTemp) {mpNext = pTemp;} int GetId() {return mComponentId;} char* GetName() {return mComponentName;} DWORD GetFlags() {return mFlags;} IawShaderElement* GetElement() {return mpElement;} void SetElement(IawShaderElement* pElement) {mpElement = pElement;} //@} /** Add a child to this component hierarchy */ HRESULT AddChild(IawShaderComponent* pChildComponent); //void TargetChanging(); //void CheckProperties(CD3DWrapper *pD3DWrapper, bool &b_alpha); //bool Validate(); //bool Activate(); /** Flags the end of a shader for a render pass */ static const int END_OF_PASS; /** Component negating */ static const int NEGATING; private: char mComponentName[255]; int mComponentId; // int mNumIds; IawShaderElement* mpElement; DWORD mFlags; IawShaderComponent* mpNext; //bool mValidOnCurrentDevice; HRESULT CheckAgainstChildren(IawShaderComponent* pPotentialParent, IawShaderComponent* pPotentialChild); }; /** * A shader implementation. * An implementation may be made up of one or more render passes. * * Each implementation may also have a string of "exit components" * * Each render pass is comprised of one or more components, the final one of * which is flagged as 'END_OF_PASS'. */ class IawShaderImplementation { public: /** * Constructor. * @param Id An Id for the implementation. * @param name A name for the implementation. */ IawShaderImplementation(int Id, char* name = "Unnamed"); /** Destructor */ virtual ~IawShaderImplementation(); /** Set the implementation name */ HRESULT SetName(char* name); /** * Create a component for this implementation * @param pId The Id number that will be assigned to the component. * @param name The component name. * @param flags Any additional flags. */ HRESULT CreateComponent(int *pId, char* name = "Unnamed Shader Component", DWORD flags = 0); //@{ /** Access method */ IawShaderImplementation* GetNext() {return mpNext;} IawShaderComponent* GetFirstComponent() {return mpFirstComponent;} IawShaderComponent* GetFirstNegatingComponent() {return mpFirstNegatingComponent;} void SetNext(IawShaderImplementation* pTemp) {mpNext = pTemp;} int GetId() {return mImplementationId;} char* GetName() {return mImplementationName;} IawShaderComponent* GetComponentPtr(int componentId); //@} /** Add a child to this implementation hierarchy */ HRESULT AddChild(IawShaderImplementation* pChildImplementation); // void TargetChanging(); // void CheckProperties(CD3DWrapper *pD3DWrapper, bool &b_alpha); // bool Validate(); //bool Activate(); // inline int GetNumPasses() {return mNumPasses}; private: char mImplementationName[255]; int mImplementationId; int mNumIds; //total number handed out int mNumPasses; int mNumComponents; IawShaderComponent* mpFirstComponent; IawShaderComponent* mpFirstNegatingComponent; //IawShaderComponent *mpFirstStateResetComponent; IawShaderImplementation* mpNext; //bool mValidOnCurrentDevice; HRESULT CheckAgainstChildren(IawShaderImplementation* pPotentialParent, IawShaderImplementation* pPotentialChild); }; /** * This class encapsulates a shader. * * Each shader can have more than one implementation, and each implementation * may be made up of one or more render passes. * * Each implementation may also have a string of "exit components" * * Each render pass is comprised of one or more components, the final one of * which is flagged as 'END_OF_PASS'. * * @see IawShaderImplementation * @see IawShaderComponent * @see IawShaderElement */ class IawShader { public: /** * Constructor. * @param Id The shader id number. * @param name A name for the shader. */ IawShader(int Id, char* name = "Unnamed"); /** Destructor */ virtual ~IawShader(); /** Set the shader name */ HRESULT SetName(char* name); /** Create an implementation for this shader */ HRESULT CreateImplementation(int* pId, char* name = "Unnamed Shader Implementation"); /** * Delete a specified implementation of this shader. * @param Id The Id number of the implementation to delete. */ HRESULT DeleteImplementation(int Id); /** * Create a component for this shader. * @param implementationId The Id of the implementation this component will belong to. * @param pId The Id number that will be assigned to the component. * @param name A name for the component. * @param flags Any additional flags for the component. */ HRESULT CreateComponent(int implementationId, int *pId, char* name = "Unnamed Shader Component", DWORD flags = 0); //@{ /** Access method */ IawShader* GetNext() {return mpNext;} IawShaderImplementation* GetFirstImplementation() {return mpFirstImplementation;} IawShaderImplementation* GetActiveImplementation() {return mpActiveImplementation;} void SetActiveImplementation(IawShaderImplementation* pTemp) {mpActiveImplementation = pTemp;} void SetNext(IawShader* pTemp) {mpNext = pTemp;} int GetId() {return mShaderId;} char* GetName() {return mShaderName;} int GetImplementationId(char* name); IawShaderImplementation* GetImplementationPtr(int implementationId); //@} /** Add a child to this shader hierarchy */ HRESULT AddChild(IawShader* pChildShader); // void CheckProperties(CD3DWrapper *pD3DWrapper, bool &b_alpha); // bool Validate(); // bool Activate(); // inline int GetNumPasses() {return miNumPasses;} private: char mShaderName[255]; int mShaderId; int mNumImplementations; int mNumIds; IawShaderImplementation* mpFirstImplementation; IawShaderImplementation* mpActiveImplementation; IawShader* mpNext; HRESULT CheckAgainstChildren(IawShader* pPotentialParent, IawShader* pPotentialChild); }; #endif // IawShader_h
[ "dwilliamson_coder@hotmail.com" ]
dwilliamson_coder@hotmail.com
022c23cfebf067463df682437ea2ccd30aeec772
9ae5d2ce9daed564edbe9502872477cbc623ad27
/ThirdPersonTest/Source/ThirdPersonTest/ThirdPersonTestCharacter.cpp
3f6edd7798a381f19cd64e88b2a751244a543157
[]
no_license
homeguatlla/UnrealGASTest
d4b1f88a8d12c59dd68b1c00420d7209ca066e60
decf8fd3215fb6c770d2fffb5eda5fca9b732c81
refs/heads/main
2023-03-25T03:08:46.962309
2021-03-05T18:44:27
2021-03-05T18:44:27
340,334,270
0
0
null
null
null
null
UTF-8
C++
false
false
8,604
cpp
// Copyright Epic Games, Inc. All Rights Reserved. #include "ThirdPersonTestCharacter.h" #include "AttributeSet.h" #include "HeadMountedDisplayFunctionLibrary.h" #include "MyPlayerState.h" #include "Utils.h" #include "Camera/CameraComponent.h" #include "Components/CapsuleComponent.h" #include "Components/InputComponent.h" #include "GameFramework/CharacterMovementComponent.h" #include "GameFramework/Controller.h" #include "GameFramework/SpringArmComponent.h" #include "GAS/AbilityInputDefinition.h" #include "GAS/Attributes/AttributeSetHealth.h" ////////////////////////////////////////////////////////////////////////// // AThirdPersonTestCharacter AThirdPersonTestCharacter::AThirdPersonTestCharacter() { if(HasAuthority()) { UE_LOG(LogTemp, Error, TEXT("SERVER:")); } else { UE_LOG(LogTemp, Warning, TEXT("CLIENT:")); } UE_LOG(LogTemp, Warning, TEXT("AThirdPersonTestCharacter::AThirdPersonTestCharacter %s"), *GetName()); UE_LOG(LogTemp, Warning, TEXT("Role: %s Remote Role: %s"), *TransformRoleToFString(GetLocalRole()), *TransformRoleToFString(GetRemoteRole())); // Set size for collision capsule GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f); // set our turn rates for input BaseTurnRate = 45.f; BaseLookUpRate = 45.f; // Don't rotate when the controller rotates. Let that just affect the camera. bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; // Configure character movement GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input... GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate GetCharacterMovement()->JumpZVelocity = 600.f; GetCharacterMovement()->AirControl = 0.2f; // Create a camera boom (pulls in towards the player if there is a collision) CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); CameraBoom->SetupAttachment(RootComponent); CameraBoom->TargetArmLength = 300.0f; // The camera follows at this distance behind the character CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller // Create a follow camera FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera")); FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm // Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character) // are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++) } void AThirdPersonTestCharacter::BeginPlay() { Super::BeginPlay(); if(GetWorld()->IsServer()) { UE_LOG(LogTemp, Error, TEXT("SERVER:")); } else { UE_LOG(LogTemp, Warning, TEXT("CLIENT:")); } UE_LOG(LogTemp, Warning, TEXT("AThirdPersonTestCharacter::BeginPlay %s"), *GetName()); UE_LOG(LogTemp, Warning, TEXT("Role: %s Remote Role: %s"), *TransformRoleToFString(GetLocalRole()), *TransformRoleToFString(GetRemoteRole())); } void AThirdPersonTestCharacter::PossessedBy(AController* NewController) { //Server only Super::PossessedBy(NewController); if(GetWorld()->IsServer()) { UE_LOG(LogTemp, Error, TEXT("SERVER:")); } else { UE_LOG(LogTemp, Warning, TEXT("CLIENT:")); } UE_LOG(LogTemp, Warning, TEXT("AThirdPersonTestCharacter::PossessedBy character: %s possessed by player controller: %s"), *GetName(), *NewController->GetName()); UE_LOG(LogTemp, Warning, TEXT("Role: %s Remote Role: %s"), *TransformRoleToFString(GetLocalRole()), *TransformRoleToFString(GetRemoteRole())); if(GetAbilitySystemComponent()) { GetAbilitySystemComponent()->InitAbilityActorInfo(GetPlayerState(), this); } } void AThirdPersonTestCharacter::UnPossessed() { if(GetWorld()->IsServer()) { UE_LOG(LogTemp, Error, TEXT("SERVER:")); } else { UE_LOG(LogTemp, Warning, TEXT("CLIENT:")); } auto controller = GetController(); UE_LOG(LogTemp, Warning, TEXT("AThirdPersonTestCharacter::UnPossessed possessed by %s"), *controller->GetName()); Super::UnPossessed(); UE_LOG(LogTemp, Warning, TEXT("AThirdPersonTestCharacter::UnPossessed %s"), *GetName()); UE_LOG(LogTemp, Warning, TEXT("Role: %s Remote Role: %s"), *TransformRoleToFString(GetLocalRole()), *TransformRoleToFString(GetRemoteRole())); } void AThirdPersonTestCharacter::OnRep_PlayerState() { Super::OnRep_PlayerState(); //Client only if(GetWorld()->IsServer()) { UE_LOG(LogTemp, Error, TEXT("SERVER:")); } else { UE_LOG(LogTemp, Warning, TEXT("CLIENT:")); } UE_LOG(LogTemp, Warning, TEXT("AThirdPersonTestCharacter::OnRep_PlayerState character: %s"), *GetName()); UE_LOG(LogTemp, Warning, TEXT("Role: %s Remote Role: %s"), *TransformRoleToFString(GetLocalRole()), *TransformRoleToFString(GetRemoteRole())); if(GetAbilitySystemComponent()) { GetAbilitySystemComponent()->InitAbilityActorInfo(GetPlayerState(), this); } } ////////////////////////////////////////////////////////////////////////// // Input void AThirdPersonTestCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); // Set up gameplay key bindings PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump); PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping); PlayerInputComponent->BindAxis("MoveForward", this, &AThirdPersonTestCharacter::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &AThirdPersonTestCharacter::MoveRight); // We have 2 versions of the rotation bindings to handle different kinds of devices differently // "turn" handles devices that provide an absolute delta, such as a mouse. // "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput); PlayerInputComponent->BindAxis("TurnRate", this, &AThirdPersonTestCharacter::TurnAtRate); PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput); PlayerInputComponent->BindAxis("LookUpRate", this, &AThirdPersonTestCharacter::LookUpAtRate); // handle touch devices PlayerInputComponent->BindTouch(IE_Pressed, this, &AThirdPersonTestCharacter::TouchStarted); PlayerInputComponent->BindTouch(IE_Released, this, &AThirdPersonTestCharacter::TouchStopped); if(GetWorld()->IsServer()) { UE_LOG(LogTemp, Error, TEXT("SERVER:")); } else { UE_LOG(LogTemp, Warning, TEXT("CLIENT:")); } UE_LOG(LogTemp, Warning, TEXT("AThirdPersonTestCharacter::SetupPlayerInputComponent %s"), *GetName()); const auto playerState = Cast<AMyPlayerState>(GetPlayerState()); mAbilitySystemComponent = playerState ? playerState->GetAbilitySystemComponent() : nullptr; mAbilitySystemComponentBuilder.WithInputComponent(PlayerInputComponent) .WithPlayerState(playerState) .WithCharacter(this) .Build(); } void AThirdPersonTestCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location) { Jump(); } void AThirdPersonTestCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location) { StopJumping(); } void AThirdPersonTestCharacter::TurnAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds()); } void AThirdPersonTestCharacter::LookUpAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds()); } void AThirdPersonTestCharacter::MoveForward(float Value) { if ((Controller != nullptr) && (Value != 0.0f)) { // find out which way is forward const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get forward vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); AddMovementInput(Direction, Value); } } void AThirdPersonTestCharacter::MoveRight(float Value) { if ( (Controller != nullptr) && (Value != 0.0f) ) { // find out which way is right const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get right vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); // add movement in that direction AddMovementInput(Direction, Value); } }
[ "dguerrero_bcn@hotmail.com" ]
dguerrero_bcn@hotmail.com
92bf3bdaba1a0005629063db4643d4158d4faec8
f739df1f252d7c961ed881be3b8babaf62ff4170
/softs/SCADAsoft/5.3.2/ACE_Wrappers/ace/os_include/os_dirent.h
2a881e40b0901b1dcad507128c42de8695adfd93
[]
no_license
billpwchan/SCADA-nsl
739484691c95181b262041daa90669d108c54234
1287edcd38b2685a675f1261884f1035f7f288db
refs/heads/master
2023-04-30T09:15:49.104944
2021-01-10T21:53:10
2021-01-10T21:53:10
328,486,982
0
0
null
2023-04-22T07:10:56
2021-01-10T21:53:19
C++
UTF-8
C++
false
false
2,826
h
// -*- C++ -*- //============================================================================= /** * @file os_dirent.h * * format of directory entries * * $Id: os_dirent.h 935 2008-12-10 21:47:27Z mitza $ * * @author Don Hinton <dhinton@dresystems.com> * @author This code was originally in various places including ace/OS.h. */ //============================================================================= #ifndef ACE_OS_INCLUDE_OS_DIRENT_H #define ACE_OS_INCLUDE_OS_DIRENT_H #include /**/ "ace/pre.h" #include /**/ "ace/config-all.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ #include "ace/os_include/sys/os_types.h" #include "ace/os_include/os_limits.h" #if defined (ACE_VXWORKS) && (ACE_VXWORKS < 0x620) # include "ace/os_include/os_unistd.h" // VxWorks needs this to compile #endif /* ACE_VXWORKS */ #if !defined (ACE_LACKS_DIRENT_H) # include /**/ <dirent.h> #endif /* !ACE_LACKS_DIRENT_H */ // Place all additions (especially function declarations) within extern "C" {} #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #if !defined (MAXNAMLEN) # define MAXNAMLEN NAME_MAX #endif /* !MAXNAMLEN */ // At least compile on some of the platforms without <ACE_DIR> info yet. #if !defined (ACE_HAS_DIRENT) typedef int ACE_DIR; struct dirent { }; #endif /* ACE_HAS_DIRENT */ #if defined (ACE_LACKS_STRUCT_DIR) struct dirent { unsigned short d_ino; unsigned short d_off; unsigned short d_reclen; // This must be a ACE_TCHAR * and not a one element // ACE_TCHAR array. It causes problems on wide // character builds with Visual C++ 6.0. ACE_TCHAR *d_name; }; #define ACE_DIRENT dirent #define ACE_HAS_TCHAR_DIRENT struct ACE_DIR { /// The name of the directory we are looking into ACE_TCHAR *directory_name_; /// Remember the handle between calls. HANDLE current_handle_; /// The struct for the results ACE_DIRENT *dirent_; /// The struct for intermediate results. ACE_TEXT_WIN32_FIND_DATA fdata_; /// A flag to remember if we started reading already. int started_reading_; }; #elif defined (ACE_WIN32) && (__BORLANDC__) && defined (ACE_USES_WCHAR) #define ACE_HAS_TCHAR_DIRENT #define ACE_DIRENT wdirent typedef wDIR ACE_DIR; #else #define ACE_DIRENT dirent typedef DIR ACE_DIR; #endif /* ACE_LACKS_STRUCT_DIR */ #if defined (ACE_LACKS_SCANDIR_PROTOTYPE) int scandir (const char *, struct dirent ***, int (*) (const struct dirent *), int (*) (const void *, const void *)); #endif /* ACE_LACKS_SCANDIR_PROTOTYPE */ #if defined (ACE_LACKS_ALPHASORT_PROTOTYPE) int alphasort (const void *, const void *); #endif /* ACE_LACKS_ALPHASORT_PROTOTYPE */ #ifdef __cplusplus } #endif /* __cplusplus */ #include /**/ "ace/post.h" #endif /* ACE_OS_INCLUDE_OS_DIRENT_H */
[ "billpwchan@hotmail.com" ]
billpwchan@hotmail.com
19688079901577c712eab4620050ba201f779d0a
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/c++/ClickHouse/2017/8/ASTLiteral.cpp
bd88a90a301382cb3b948a25b67a24466b144457
[ "BSL-1.0" ]
permissive
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
C++
false
false
810
cpp
#include <Common/SipHash.h> #include <Core/FieldVisitors.h> #include <Parsers/ASTLiteral.h> #include <IO/WriteHelpers.h> namespace DB { String ASTLiteral::getColumnNameImpl() const { /// Special case for very large arrays. Instead of listing all elements, will use hash of them. /// (Otherwise column name will be too long, that will lead to significant slowdown of expression analysis.) if (value.getType() == Field::Types::Array && value.get<const Array &>().size() > 100) /// 100 - just arbitary value. { SipHash hash; applyVisitor(FieldVisitorHash(hash), value); UInt64 low, high; hash.get128(low, high); return "__array_" + toString(low) + "_" + toString(high); } return applyVisitor(FieldVisitorToString(), value); } }
[ "rodrigosoaresilva@gmail.com" ]
rodrigosoaresilva@gmail.com
9131de57b8b629101b0fad4e2b340203867d00de
5370b9e27da3064f35a59610b7746a263204e621
/CodeForces/Div3/Round498/b.cpp
9c2fdeb07f274250d7440d2c6e024720ca372538
[]
no_license
Paryul10/Competetive-Coding
4619d84b282d58303dc5db9cb8bdad769fc3176d
3cc06f80dfffe4dc742fd5d8a4b427a9de778d85
refs/heads/master
2020-04-02T11:12:49.838056
2018-08-02T11:36:04
2018-08-02T11:36:04
154,376,787
0
1
null
2019-10-19T12:00:45
2018-10-23T18:22:09
C++
UTF-8
C++
false
false
1,086
cpp
#include "bits/stdc++.h" #include "string" using namespace std; int main() { int n, k; cin >> n >> k; int arr[n]; for (int i=0; i<n; i++) cin >> arr[i]; vector <pair<int, int> > ind; for (int i=0; i<n; i++) { ind.push_back(make_pair(arr[i], i)); } sort(ind.begin(), ind.end()); int inx[k]; long long max = 0; int x = 0; for (int i=(n-1); i>=(n-k); i--) { inx[x] = ind[i].second; max += ind[i].first; x++; } cout << max << endl; sort(inx, inx+k); if (k == 1) cout << n << endl; else { cout << inx[0] + 1 << " "; for (int i=1; i<k; i++) { if (inx[k-1]!=(n-1)) { if (i!=(k-1)) cout << inx[i] - inx[i-1] << " "; else cout << (n-1) - inx[k-2] << " "; } else { if (i!=(k-1)) cout << inx[i] - inx[i-1] << " "; else cout << inx[k-1] - inx[k-2] << " "; } } cout << endl; } return 0; }
[ "eeshadutta99@gmail.com" ]
eeshadutta99@gmail.com
b103ce66cecc09bea2dba14a61e6519267f4af60
1aaa697e8a716ee1dee3a8fb9f67d8c6432c1320
/Framework/Shared/Camp/CampBindings.h
04f76383dc8616fe3a175b1c75ab8ef0b0e002c8
[]
no_license
MelvinRook/Diversia
a4a6d0dd6ec1e8509a0839e8a0ab1a9d4fd5a596
6e7bfbfa48bbd733da5c786dfad8e7d3a3645b42
refs/heads/master
2021-01-20T20:36:24.736608
2012-02-05T19:36:16
2012-02-05T19:36:16
60,241,791
1
1
null
null
null
null
UTF-8
C++
false
false
2,745
h
/* ----------------------------------------------------------------------------- Copyright (c) 2008-2010 Diversia This file is part of Diversia. 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. ----------------------------------------------------------------------------- */ #ifndef DIVERSIA_SHARED_CAMPBINDINGS_H #define DIVERSIA_SHARED_CAMPBINDINGS_H #include "Shared/Platform/Prerequisites.h" namespace Diversia { namespace Shared { namespace Bindings { //------------------------------------------------------------------------------ class DIVERSIA_SHARED_API CampBindings { public: static void bindPluginManager(); static void bindPlugin(); static void bindServerInfo(); static void bindServerNeighbors(); static void bindDirection(); static void bindPluginTypeEnum(); static void bindComponentTypeEnum(); static void bindResourceInfo(); static void bindTerrainTypeEnum(); static void bindHeightmapTypeEnum(); static void bindLayerInstance(); static void bindUserInfo(); static void bindPhysicsType(); static void bindPhysicsShape(); static void bindLuaManager(); static void bindLuaSecurityLevel(); static void bindCrashReporter(); #if DIVERSIA_PLATFORM == DIVERSIA_PLATFORM_WIN32 static void bindWindowsCrashReporter(); #endif static void bindPermission(); static void bindPropertySynchronization(); static void bindGraphicsShape(); static void bindResourceLocationType(); static void bindResourceType(); static void bindSkyType(); static void bindLightType(); }; //------------------------------------------------------------------------------ } // Namespace Bindings } // Namespace Shared } // Namespace Diversia #endif // DIVERSIA_SHARED_CAMPBINDINGS_H
[ "gabrielkonat@gmail.com" ]
gabrielkonat@gmail.com
bcc04f8fe31e868237a1153c5a4bf70468d7f7e6
a679dba6ef0364962b94ed65d0caad1a88da6c43
/OrginalServerCode/OrginalCode/labixiaoxin/ACE_wrappers/ASNMP/asnmp/oid.cpp
8cbd4c661616d3ba19249529ccc77fa67550b63a
[ "MIT-CMU", "LicenseRef-scancode-hp-snmp-pp" ]
permissive
w5762847/Learn
7f84933fe664e6cf52089a9f4b9140fca8b9a783
a5494181ea791fd712283fa8e78ca0287bf05318
refs/heads/master
2020-08-27T05:43:35.496579
2016-12-02T12:16:12
2016-12-02T12:16:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,829
cpp
// $Id: oid.cpp 91670 2010-09-08 18:02:26Z johnnyw $ // ============================================================================ // // = LIBRARY // asnmp // // = FILENAME // oid.cpp // // = DESCRIPTION // This module contains the implementation of the oid class. This // includes all protected and public member functions. The oid class // may be compiled stand alone without the use of any other library. // // = AUTHOR // Peter E Mellquist // Michael R MacFaden mrm@cisco.com - rework & ACE port // ============================================================================ /*=================================================================== Copyright (c) 1996 Hewlett-Packard Company ATTENTION: USE OF THIS SOFTWARE IS SUBJECT TO THE FOLLOWING TERMS. Permission to use, copy, modify, distribute and/or sell this software and/or its documentation is hereby granted without fee. User agrees to display the above copyright notice and this license notice in all copies of the software and any documentation of the software. User agrees to assume all liability for the use of the software; Hewlett-Packard makes no representations about the suitability of this software for any purpose. It is provided "AS-IS" without warranty of any kind,either express or implied. User hereby grants a royalty-free license to any and all derivatives based upon this software code base. =====================================================================*/ //---------[ external C libaries used ]-------------------------------- #include "asnmp/oid.h" // include def for oid class #include "ace/OS_NS_string.h" #include "ace/OS_NS_stdio.h" #include "ace/OS_Memory.h" #include "ace/OS_NS_ctype.h" enum Defs {SNMPBUFFSIZE=300, SNMPCHARSIZE=15}; // max oid value (4294967295UL) #define NO_MEM_STR "ERROR: Oid::to_string: memory allocation failure" //=============[Oid::get_syntax(void)]==================================== SmiUINT32 Oid::get_syntax() { return sNMP_SYNTAX_OID; } //=============[Oid::Oid( const char *dotted_string ]===================== // constructor using a dotted string // // do a string to oid using the string passed in Oid::Oid( const char * dotted_oid_string, size_t size) { // can't init enum SmiValue so just memset it clean set_null(); size_t z; if ((z = ACE_OS::strlen(dotted_oid_string)) == 0) { set_invalid(); return; } if (size == (unsigned int)-1) size = z; if (size > z) size = z; char *ptr = (char *)dotted_oid_string;; if (size < z) { // create new buffer if needed ACE_NEW(ptr, char [size]); // sz should be in StrToOid? ACE_OS::memcpy( (void *)ptr, dotted_oid_string, size); } size_t byte_counter; if (StrToOid( (char *) ptr, &smival.value.oid, byte_counter) < 0) set_invalid(); if (ptr != dotted_oid_string) delete [] ptr; } //=============[Oid::Oid( const Oid &oid) ]================================ // constructor using another oid object // // do an oid copy using the oid object passed in Oid::Oid ( const Oid &oid) : SnmpSyntax (oid) { set_null(); // allocate some memory for the oid // in this case the size to allocate is the same // size as the source oid if (oid.smival.value.oid.len) { ACE_NEW(smival.value.oid.ptr, SmiUINT32[ oid.smival.value.oid.len]); size_t byte_counter; OidCopy( (SmiLPOID) &(oid.smival.value.oid),(SmiLPOID) &smival.value.oid, byte_counter); } } //=============[Oid::Oid( const unsigned long *raw_oid, int oid_len) ]==== // constructor using raw numeric form // // copy the integer values into the private member Oid::Oid(const unsigned long *raw_oid, size_t oid_len) { set_null(); smival.syntax = sNMP_SYNTAX_OID; set_invalid(); if (raw_oid && oid_len > 0) { ACE_NEW(smival.value.oid.ptr, SmiUINT32[ oid_len]); smival.value.oid.len = oid_len; for (size_t i=0; i < oid_len; i++) smival.value.oid.ptr[i] = raw_oid[i]; } } //=============[Oid::~Oid]============================================== // destructor // // free up the descriptor space Oid::~Oid() { // free up the octet deep memory if ( smival.value.oid.ptr ) { set_invalid(); } // free up the output string if ( iv_str != 0) delete [] iv_str; } //=============[Oid::operator = const char * dotted_string ]============== // assignment to a string operator overloaded // // free the existing oid // create the new oid from the string // return this object void Oid::set_data( const char *dotted_oid_string) { // delete the old value if ( smival.value.oid.ptr ) { set_invalid(); } // assign the new value size_t byte_counter; if (StrToOid( (char *) dotted_oid_string, &smival.value.oid, byte_counter) <0) set_invalid(); } //=============[Oid:: operator = const Oid &oid ]========================== // assignment to another oid object overloaded // // free the existing oid // create a new one from the object passed in // TODO: measure perf vs memory of no realloc in case where len >= oid.len Oid& Oid::operator=( const Oid &oid) { // protect against assignment from self if ( this == &oid) return *this; set_invalid(); // check for zero len on source if ( oid.smival.value.oid.len == 0) return *this; const SmiLPOID srcOid = (SmiLPOID) &(oid.smival.value.oid); init_value(srcOid, oid.smival.value.oid.len); return *this; } // assign this object the oid, set to invalid if copy fails void Oid::init_value(const SmiLPOID srcOid, size_t len) { // allocate some memory for the oid ACE_NEW(smival.value.oid.ptr, SmiUINT32[ len]); size_t byte_counter; OidCopy( srcOid, (SmiLPOID) &smival.value.oid, byte_counter); } void Oid::init_value(const unsigned long *raw_oid, size_t oid_len) { if (smival.value.oid.ptr) delete [] smival.value.oid.ptr; ACE_NEW(smival.value.oid.ptr, SmiUINT32[ oid_len]); ACE_OS::memcpy((SmiLPBYTE) smival.value.oid.ptr, (SmiLPBYTE) raw_oid, (size_t) (oid_len * sizeof(SmiUINT32))); smival.value.oid.len = oid_len; } //==============[Oid:: operator += const char *a ]========================= // append operator, appends a string // // allocate some space for a max oid string // extract current string into space // concat new string // free up existing oid // make a new oid from string // delete allocated space Oid& Oid::operator+=( const char *a) { unsigned long n; if (!a) return *this; if ( *a=='.') a++; size_t sz = ACE_OS::strlen(a); if (valid()) { n = (smival.value.oid.len *SNMPCHARSIZE) + smival.value.oid.len + 1 + sz; char *ptr; ACE_NEW_RETURN(ptr, char[ n], *this); size_t byte_counter; if (OidToStr(&smival.value.oid, n,ptr, byte_counter) > 0) { delete [] ptr; set_invalid(); return *this; } if (ACE_OS::strlen(ptr)) ACE_OS::strcat(ptr,"."); ACE_OS::strcat(ptr,a); if ( smival.value.oid.len !=0) { set_invalid(); } if (StrToOid( (char *) ptr, &smival.value.oid, byte_counter) < 0) { set_invalid(); } delete [] ptr; } else { size_t byte_counter; if (StrToOid( (char *) a, &smival.value.oid, byte_counter) < 0) { set_invalid(); } } return *this; } //=============[ bool operator == oid,oid ]================================= // equivlence operator overloaded bool operator==( const Oid &lhs, const Oid &rhs) { // ensure same len, then use left_comparison if (rhs.length() != lhs.length()) return false; if( lhs.left_comparison( rhs.length(), rhs) == 0) return true; else return false; } //==============[ bool operator!=( Oid &x,Oid &y) ]======================= //not equivlence operator overloaded bool operator!=( const Oid &lhs,const Oid &rhs) { return (!(lhs == rhs)); } //==============[ bool operator<( Oid &x,Oid &y) ]======================== // less than < overloaded bool operator<( const Oid &lhs,const Oid &rhs) { int result; // call left_comparison with the current // Oidx, Oidy and len of Oidx if ((result = lhs.left_comparison( rhs.length(), rhs)) < 0) return true; else if (result > 0) return false; else{ // if here, equivalent substrings, call the shorter one < if (lhs.length() < rhs.length()) return true; else return false; } } //==============[ bool operator<=( Oid &x,Oid &y) ]======================= // less than <= overloaded bool operator<=( const Oid &x,const Oid &y) { if ( (x < y) || (x == y) ) return true; else return false; } //==============[ bool operator>( Oid &x,Oid &y) ]======================== // greater than > overloaded bool operator>( const Oid &x,const Oid &y) { // just invert existing <= if (!(x<=y)) return true; else return false; } //==============[ bool operator>=( Oid &x,Oid &y) ]======================= // greater than >= overloaded bool operator>=( const Oid &x,const Oid &y) { // just invert existing < if (!(x<y)) return true; else return false; } //===============[Oid::oidval ]============================================= // return the WinSnmp oid part SmiLPOID Oid::oidval() { return (SmiLPOID) &smival.value.oid; } //===============[Oid::set_data ]==---===================================== // copy data from raw form... void Oid::set_data( const unsigned long *raw_oid, const size_t oid_len) { if (smival.value.oid.len < oid_len) { if ( smival.value.oid.ptr) { set_invalid(); } } init_value(raw_oid, oid_len); } //===============[Oid::len ]================================================ // return the len of the oid size_t Oid::length() const { return smival.value.oid.len; } //===============[Oid::trim( unsigned int) ]============================ // trim off the n leftmost values of an oid // Note!, does not adjust actual space for // speed void Oid::trim( const size_t n) { // verify that n is legal if ((n<=smival.value.oid.len)&&(n>0)) { smival.value.oid.len -= n; if (smival.value.oid.len == 0) { set_invalid(); } } } //===============[Oid::set_invalid() ]==================== // make this object invalid by resetting all values void Oid::set_invalid() { delete [] smival.value.oid.ptr; smival.value.oid.ptr = 0; smival.value.oid.len = 0; delete [] iv_str; iv_str = 0; } //===============[Oid::set_null() ]==================== void Oid::set_null() { smival.syntax = sNMP_SYNTAX_OID; smival.value.oid.ptr = 0; smival.value.oid.len = 0; iv_str = 0; } //===============[Oid::operator += const unsigned int) ]==================== // append operator, appends an int // // allocate some space for a max oid string // extract current string into space // concat new string // free up existing oid // make a new oid from string // delete allocated space Oid& Oid::operator+=( const unsigned long i) { unsigned long n = (smival.value.oid.len * SNMPCHARSIZE) + ( smival.value.oid.len -1) + 1 + 4; char buffer[SNMPBUFFSIZE]; // two cases: null oid, existing oid if (valid()) { // allocate some temporary space char *ptr; ACE_NEW_RETURN(ptr, char[ n], *this); size_t byte_counter; if (OidToStr(&smival.value.oid, n, ptr, byte_counter) < 0) { set_invalid(); delete [] ptr; return *this; } if (ACE_OS::strlen(ptr)) ACE_OS::strcat(ptr,"."); if (ACE_OS::sprintf( buffer,"%lu",i) != -1) { ACE_OS::strcat(ptr, buffer); if ( smival.value.oid.ptr ) { set_invalid(); } if (StrToOid( (char *) ptr, &smival.value.oid, byte_counter) < 0) { set_invalid(); } delete [] ptr; } } else { init_value((const unsigned long *)&i, (size_t)1); } return *this; } //===============[Oid::operator += const Oid) ]======================== // append operator, appends an Oid // // allocate some space for a max oid string // extract current string into space // concat new string // free up existing oid // make a new oid from string // delete allocated space Oid& Oid::operator+=( const Oid &o) { SmiLPUINT32 new_oid; if (o.smival.value.oid.len == 0) return *this; ACE_NEW_RETURN(new_oid, SmiUINT32[ smival.value.oid.len + o.smival.value.oid.len], *this); if (smival.value.oid.ptr) { ACE_OS::memcpy((SmiLPBYTE) new_oid, (SmiLPBYTE) smival.value.oid.ptr, (size_t) (smival.value.oid.len*sizeof(SmiUINT32))); delete [] smival.value.oid.ptr; } // out with the old, in with the new... smival.value.oid.ptr = new_oid; ACE_OS::memcpy((SmiLPBYTE) &new_oid[smival.value.oid.len], (SmiLPBYTE) o.smival.value.oid.ptr, (size_t) (o.smival.value.oid.len*sizeof(SmiUINT32))); smival.value.oid.len += o.smival.value.oid.len; return *this; } // return string portion of the oid // const char * Oid::to_string() { unsigned long n; if (!valid()) return ""; // be consistent with other classes // the worst case char len of an oid can be.. // oid.len*3 + dots in between if each oid is XXXX // so.. size = (len*4) + (len-1) + 1 , extra for a null n = (smival.value.oid.len *SNMPCHARSIZE) + ( smival.value.oid.len -1) + 1 ; if (n == 0) n = 1; // need at least 1 byte for a null string // adjust the len of output array in case size was adjusted if ( iv_str != 0) delete [] iv_str; // allocate some space for the output string ACE_NEW_RETURN(iv_str, char[ n], ""); // convert to an output string size_t how_many; if ( valid() && iv_str != 0) if (OidToStr(&smival.value.oid,n,iv_str, how_many) < 0) return "ERROR: Oid::OidToStr failed"; return iv_str; } //==============[Oid::suboid( unsigned int start, n) ]============= int Oid::suboid(Oid& new_oid, size_t start, size_t how_many) { if (how_many == 0) return 0; else if (how_many == (size_t)-1) how_many = length(); else if (how_many > length()) how_many = length(); // reset new_oid new_oid.set_invalid(); size_t new_size = how_many - start; if (new_size == 0) new_size++; new_oid.smival.value.oid.len = new_size; ACE_NEW_RETURN(new_oid.smival.value.oid.ptr, SmiUINT32 [ new_oid.smival.value.oid.len], -1); // copy source to destination ACE_OS::memcpy( (SmiLPBYTE) new_oid.smival.value.oid.ptr, (SmiLPBYTE) (smival.value.oid.ptr + start), new_size * sizeof(SmiLPBYTE)); return 0; } //=============[Oid::StrToOid( char *string, SmiLPOID dst) ]============== // convert a string to an oid int Oid::StrToOid( const char *string, SmiLPOID dstOid, size_t& how_many) { size_t index = 0; size_t number = 0; // make a temp buffer to copy the data into first SmiLPUINT32 temp; unsigned long nz; if (string && *string) { nz = ACE_OS::strlen( string); } else { dstOid->len = 0; dstOid->ptr = 0; return -1; } ACE_NEW_RETURN(temp, SmiUINT32[ nz], -1); while (*string!=0 && index<nz) { // init the number for each token number = 0; // skip over the dot if (*string=='.') string++; // grab a digit token and convert it to a long int while (ACE_OS::ace_isdigit(*string)) number=number*10 + *(string++)-'0'; // check for invalid chars if (*string!=0 && *string!='.') { // Error: Invalid character in string delete [] temp; return -1; } // stuff the value into the array temp[index] = number; index++; // bump the counter } // get some space for the real oid ACE_NEW_RETURN(dstOid->ptr, SmiUINT32[ index], -1); // TODO: make tmp autoptr type delete [] temp to prevent leak // copy in the temp data ACE_OS::memcpy((SmiLPBYTE) dstOid->ptr, (SmiLPBYTE) temp, (size_t) (index*sizeof(SmiUINT32))); // set the len of the oid dstOid->len = index; // free up temp data delete [] temp; how_many = index; return 0; } //===============[Oid::OidCopy( source, destination) ]==================== // Copy an oid, return bytes copied int Oid::OidCopy( SmiLPOID srcOid, SmiLPOID dstOid, size_t& how_many_bytes) { // check source len ! zero if (srcOid->len == 0) return -1; // copy source to destination ACE_OS::memcpy((SmiLPBYTE) dstOid->ptr, (SmiLPBYTE) srcOid->ptr, (size_t) (srcOid->len * sizeof(SmiUINT32))); //set the new len dstOid->len = srcOid->len; how_many_bytes = srcOid->len; return 0; } //===============[Oid::left_comparison( n, Oid) ]================================= // compare the n leftmost values of two oids ( left-to_right ) // // self == Oid then return 0, they are equal // self < Oid then return -1, < // self > Oid then return 1, > int Oid::left_comparison( const unsigned long n, const Oid &o) const { unsigned long z; unsigned long len = n; int reduced_len = 0; // 1st case they both are null if (( len==0)&&( this->smival.value.oid.len==0)) return 0; // equal // verify that n is valid, must be >= 0 if ( len <=0) return 1; // ! equal // only compare for the minimal length if (len > this->smival.value.oid.len) { len = this->smival.value.oid.len; reduced_len = 1; } if (len > o.smival.value.oid.len) { len = o.smival.value.oid.len; reduced_len = 1; } z = 0; while(z < len) { if ( this->smival.value.oid.ptr[z] < o.smival.value.oid.ptr[z]) return -1; // less than if ( this->smival.value.oid.ptr[z] > o.smival.value.oid.ptr[z]) return 1; // greater than z++; } // if we truncated the len then these may not be equal if (reduced_len) { if (this->smival.value.oid.len < o.smival.value.oid.len) return -1; if (this->smival.value.oid.len > o.smival.value.oid.len) return 1; } return 0; // equal } //===============[Oid::left_comparison( n, Oid) ]================================= // compare the n rightmost bytes (right-to-left) // returns 0, equal // returns -1, < // returns 1 , > int Oid::right_comparison( const unsigned long n, const Oid &o) const { // oid to compare must have at least the same number // of sub-ids to comparison else the argument Oid is // less than THIS if ( o.length() < n) return -1; // also can't compare argument oid for sub-ids which // THIS does not have if ( this->length() < n) return -1; int start = (int) this->length(); int end = (int) start - (int) n; for ( int z=start;z< end;z--) { if ( o.smival.value.oid.ptr[z] < this->smival.value.oid.ptr[z]) return -1; if ( o.smival.value.oid.ptr[z] > this->smival.value.oid.ptr[z]) return 1; } return 0; // they are equal } //================[ Oid::valid() ]======================================== // is the Oid object valid // returns validity int Oid::valid() const { return ( smival.value.oid.ptr ? 1 : 0 ); } //================[Oid::OidToStr ]========================================= // convert an oid to a string int Oid::OidToStr( SmiLPOID srcOid, unsigned long size, char *string, size_t& how_many_bytes) { unsigned long index = 0; unsigned totLen = 0; char szNumber[SNMPBUFFSIZE]; // init the string string[totLen] = 0; // verify there is something to copy if (srcOid->len == 0) return -1; // loop through and build up a string for (index=0; index < srcOid->len; index++) { // convert data element to a string if (ACE_OS::sprintf( szNumber,"%lu", srcOid->ptr[index]) == -1) return -1; // verify len is not over if (totLen + ACE_OS::strlen(szNumber) + 1 >= size) return -2; // if not at end, pad with a dot if (totLen!=0) string[totLen++] = '.'; // copy the string token into the main string ACE_OS::strcpy(string + totLen, szNumber); // adjust the total len totLen += ACE_OS::strlen(szNumber); } how_many_bytes = totLen + 1; return 0; } //================[ general Value = operator ]======================== SnmpSyntax& Oid::operator=( SnmpSyntax &val) { // protect against assignment from self if ( this == &val ) return *this; // blow away old value smival.value.oid.len = 0; if (smival.value.oid.ptr) { set_invalid(); } // assign new value if (val.valid()) { switch (val.get_syntax()) { case sNMP_SYNTAX_OID: set_data( ((Oid &)val).smival.value.oid.ptr, (unsigned int)((Oid &)val).smival.value.oid.len); break; } } return *this; } //================[ [] operator ]===================================== unsigned long& Oid::operator[](size_t position) { return smival.value.oid.ptr[position]; } //================[ clone ]=========================================== SnmpSyntax *Oid::clone() const { return (SnmpSyntax *) new Oid(*this); }
[ "flyer_son@126.com" ]
flyer_son@126.com
5b2191d22e7ff9d4dd1fbddc170ef623bb6ca102
e3ceca6a34bf3426b90b3952782d4fd94c54d08a
/b問題/b_chocolate.cpp
c19b4db14f1c3a0cbc38383eeb4d9561086c74c3
[]
no_license
THEosusi/atcoder
ede5bffb44d59e266c6c4763a64cddeed8d8101f
0e9a17a82562e469198a6cc81922db5ac13efa6d
refs/heads/master
2023-06-21T06:45:28.128553
2021-07-27T09:02:55
2021-07-27T09:02:55
336,729,745
0
0
null
null
null
null
UTF-8
C++
false
false
518
cpp
#include <bits/stdc++.h> using namespace std; int main() { int N,D,X; cin >> N >> D >>X; vector<int> vec(N); for(int i=0;i<N;i++){ cin >>vec.at(i); } int count=0; for(int j=0;j<N;j++){ if(vec.at(j)==1){ if(N==1){ count++; continue; } count += D; continue; } count += D/vec.at(j); count ++; if(D%vec.at(j)==0){ count--; } } cout << count+X << endl; }
[ "bp20129shibaura-it.ac.j@shibaura-it.ac.jp" ]
bp20129shibaura-it.ac.j@shibaura-it.ac.jp
e662c436eb642e7a44130d20688dbfa5e6a14778
dc61e8c951f9e91930c2edff8a53c32d7a99bb94
/include/inviwo/qt/widgets/properties/lightpropertywidgetqt.h
5ba7c43bbe9afa60e4aa53659c3b4fd42487c66d
[ "BSD-2-Clause" ]
permissive
johti626/inviwo
d4b2766742522d3c8d57c894a60e345ec35beafc
c429a15b972715157b99f3686b05d581d3e89e92
refs/heads/master
2021-01-17T08:14:10.118104
2016-05-25T14:38:33
2016-05-25T14:46:31
31,444,269
2
0
null
2015-02-27T23:45:02
2015-02-27T23:45:01
null
UTF-8
C++
false
false
2,762
h
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #ifndef IVW_LIGHTPROPERTYWIDGETQT_H #define IVW_LIGHTPROPERTYWIDGETQT_H #include <inviwo/qt/widgets/inviwoqtwidgetsdefine.h> #include <inviwo/core/properties/ordinalproperty.h> #include <inviwo/qt/widgets/customdoublespinboxqt.h> #include <inviwo/qt/widgets/editablelabelqt.h> #include <inviwo/qt/widgets/lightpositionwidgetqt.h> #include <inviwo/qt/widgets/properties/propertywidgetqt.h> #include <warn/push> #include <warn/ignore/all> #include <QtCore/qmath.h> #include <QSpinBox> #include <warn/pop> namespace inviwo { class IVW_QTWIDGETS_API LightPropertyWidgetQt : public PropertyWidgetQt { #include <warn/push> #include <warn/ignore/all> Q_OBJECT #include <warn/pop> public: LightPropertyWidgetQt(FloatVec3Property* property); virtual ~LightPropertyWidgetQt(); void updateFromProperty(); private: FloatVec3Property* property_; LightPositionWidgetQt* lightWidget_; CustomDoubleSpinBoxQt* radiusSpinBox_; EditableLabelQt* label_; void generateWidget(); public slots: void onPositionLightWidgetChanged(); void onRadiusSpinBoxChanged(double radius); }; } // namespace #endif // IVW_LightPropertyWidgetQt_H
[ "eriksunden85@gmail.com" ]
eriksunden85@gmail.com
a86a3cdb105058cf4b7a43042198ce12b29eb609
88026fecc64f11bb17c4c7f938fc3ff60c80e72f
/src/wallet/rpcwallet.cpp
af0f90db3709ce5b018f47f4ce6ba9978d41a441
[ "MIT" ]
permissive
docharlow/spoomy
59c54e9a97fd91e54cdf46daafb50215edcc0025
794c5cbed698857d1078efede59bad1e73d4af8d
refs/heads/master
2020-04-16T10:49:30.187434
2019-01-13T15:24:22
2019-01-13T15:24:22
165,518,257
0
0
null
null
null
null
UTF-8
C++
false
false
121,387
cpp
// Copyright (c) 2009-2018 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Developers // Copyright (c) 2014-2018 The Dash Core Developers // Copyright (c) 2017-2018 Spoomy Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "amount.h" #include "base58.h" #include "chain.h" #include "core_io.h" #include "init.h" #include "keepass.h" #include "main.h" #include "net.h" #include "netbase.h" #include "policy/rbf.h" #include "rpcserver.h" #include "timedata.h" #include "util.h" #include "utilmoneystr.h" #include "wallet.h" #include "walletdb.h" #include <univalue.h> #include <stdint.h> #include <boost/assign/list_of.hpp> int64_t nWalletUnlockTime; static CCriticalSection cs_nWalletUnlockTime; std::string HelpRequiringPassphrase() { return pwalletMain && pwalletMain->IsCrypted() ? "\nRequires wallet passphrase to be set with walletpassphrase call." : ""; } bool EnsureWalletIsAvailable(bool avoidException) { if (!pwalletMain) { if (!avoidException) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)"); else return false; } return true; } void EnsureWalletIsUnlocked() { if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); } void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry) { int confirms = wtx.GetDepthInMainChain(false); int confirmsTotal = GetISConfirmations(wtx.GetHash()) + confirms; entry.push_back(Pair("confirmations", confirmsTotal)); entry.push_back(Pair("bcconfirmations", confirms)); if (wtx.IsCoinBase()) entry.push_back(Pair("generated", true)); if (confirms > 0) { entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex())); entry.push_back(Pair("blockindex", wtx.nIndex)); entry.push_back(Pair("blocktime", mapBlockIndex[wtx.hashBlock]->GetBlockTime())); } else { entry.push_back(Pair("trusted", wtx.IsTrusted())); } uint256 hash = wtx.GetHash(); entry.push_back(Pair("txid", hash.GetHex())); UniValue conflicts(UniValue::VARR); BOOST_FOREACH(const uint256& conflict, wtx.GetConflicts()) conflicts.push_back(conflict.GetHex()); entry.push_back(Pair("walletconflicts", conflicts)); entry.push_back(Pair("time", wtx.GetTxTime())); entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived)); // Add opt-in RBF status std::string rbfStatus = "no"; if (confirms <= 0) { LOCK(mempool.cs); if (!mempool.exists(hash)) { if (SignalsOptInRBF(wtx)) { rbfStatus = "yes"; } else { rbfStatus = "unknown"; } } else if (IsRBFOptIn(*mempool.mapTx.find(hash), mempool)) { rbfStatus = "yes"; } } entry.push_back(Pair("bip125-replaceable", rbfStatus)); BOOST_FOREACH(const PAIRTYPE(std::string,std::string)& item, wtx.mapValue) entry.push_back(Pair(item.first, item.second)); } std::string AccountFromValue(const UniValue& value) { std::string strAccount = value.get_str(); if (strAccount == "*") throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name"); return strAccount; } UniValue getnewaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 1) throw std::runtime_error( "getnewaddress ( \"account\" )\n" "\nReturns a new Spoomy address for receiving payments.\n" "If 'account' is specified (DEPRECATED), it is added to the address book \n" "so payments received with the address will be credited to 'account'.\n" "\nArguments:\n" "1. \"account\" (string, optional) DEPRECATED. The account name for the address to be linked to. If not provided, the default account \"\" is used. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created if there is no account by the given name.\n" "\nResult:\n" "\"zumyaddress\" (string) The new spoomy address\n" "\nExamples:\n" + HelpExampleCli("getnewaddress", "") + HelpExampleRpc("getnewaddress", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); // Parse the account first so we don't generate a key if there's an error std::string strAccount; if (params.size() > 0) strAccount = AccountFromValue(params[0]); if (!pwalletMain->IsLocked(true)) pwalletMain->TopUpKeyPool(); // Generate a new key that is added to wallet CPubKey newKey; if (!pwalletMain->GetKeyFromPool(newKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); CKeyID keyID = newKey.GetID(); pwalletMain->SetAddressBook(keyID, strAccount, "receive"); return CSpoomyAddress(keyID).ToString(); } CSpoomyAddress GetAccountAddress(std::string strAccount, bool bForceNew=false) { CWalletDB walletdb(pwalletMain->strWalletFile); CAccount account; walletdb.ReadAccount(strAccount, account); bool bKeyUsed = false; // Check if the current key has been used if (account.vchPubKey.IsValid()) { CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID()); for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); ++it) { const CWalletTx& wtx = (*it).second; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) bKeyUsed = true; } } // Generate a new key if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) { if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive"); walletdb.WriteAccount(strAccount, account); } return CSpoomyAddress(account.vchPubKey.GetID()); } UniValue getaccountaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 1) throw std::runtime_error( "getaccountaddress \"account\"\n" "\nDEPRECATED. Returns the current Spoomy address for receiving payments to this account.\n" "\nArguments:\n" "1. \"account\" (string, required) The account name for the address. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created and a new address created if there is no account by the given name.\n" "\nResult:\n" "\"zumyaddress\" (string) The account spoomy address\n" "\nExamples:\n" + HelpExampleCli("getaccountaddress", "") + HelpExampleCli("getaccountaddress", "\"\"") + HelpExampleCli("getaccountaddress", "\"myaccount\"") + HelpExampleRpc("getaccountaddress", "\"myaccount\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); // Parse the account first so we don't generate a key if there's an error std::string strAccount = AccountFromValue(params[0]); UniValue ret(UniValue::VSTR); ret = GetAccountAddress(strAccount).ToString(); return ret; } UniValue getrawchangeaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 1) throw std::runtime_error( "getrawchangeaddress\n" "\nReturns a new Spoomy address, for receiving change.\n" "This is for use with raw transactions, NOT normal use.\n" "\nResult:\n" "\"address\" (string) The address\n" "\nExamples:\n" + HelpExampleCli("getrawchangeaddress", "") + HelpExampleRpc("getrawchangeaddress", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (!pwalletMain->IsLocked(true)) pwalletMain->TopUpKeyPool(); CReserveKey reservekey(pwalletMain); CPubKey vchPubKey; if (!reservekey.GetReservedKey(vchPubKey, true)) throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first"); reservekey.KeepKey(); CKeyID keyID = vchPubKey.GetID(); return CSpoomyAddress(keyID).ToString(); } UniValue setaccount(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 2) throw std::runtime_error( "setaccount \"zumyaddress\" \"account\"\n" "\nDEPRECATED. Sets the account associated with the given address.\n" "\nArguments:\n" "1. \"zumyaddress\" (string, required) The spoomy address to be associated with an account.\n" "2. \"account\" (string, required) The account to assign the address to.\n" "\nExamples:\n" + HelpExampleCli("setaccount", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" \"tabby\"") + HelpExampleRpc("setaccount", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\", \"tabby\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); CSpoomyAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Spoomy address"); std::string strAccount; if (params.size() > 1) strAccount = AccountFromValue(params[1]); // Only add the account if the address is yours. if (IsMine(*pwalletMain, address.Get())) { // Detect when changing the account of an address that is the 'unused current key' of another account: if (pwalletMain->mapAddressBook.count(address.Get())) { std::string strOldAccount = pwalletMain->mapAddressBook[address.Get()].name; if (address == GetAccountAddress(strOldAccount)) GetAccountAddress(strOldAccount, true); } pwalletMain->SetAddressBook(address.Get(), strAccount, "receive"); } else throw JSONRPCError(RPC_MISC_ERROR, "setaccount can only be used with own address"); return NullUniValue; } UniValue getaccount(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 1) throw std::runtime_error( "getaccount \"zumyaddress\"\n" "\nDEPRECATED. Returns the account associated with the given address.\n" "\nArguments:\n" "1. \"zumyaddress\" (string, required) The spoomy address for account lookup.\n" "\nResult:\n" "\"accountname\" (string) the account address\n" "\nExamples:\n" + HelpExampleCli("getaccount", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\"") + HelpExampleRpc("getaccount", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); CSpoomyAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Spoomy address"); std::string strAccount; std::map<CTxDestination, CAddressBookData>::iterator mi = pwalletMain->mapAddressBook.find(address.Get()); if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.name.empty()) strAccount = (*mi).second.name; return strAccount; } UniValue getaddressesbyaccount(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 1) throw std::runtime_error( "getaddressesbyaccount \"account\"\n" "\nDEPRECATED. Returns the list of addresses for the given account.\n" "\nArguments:\n" "1. \"account\" (string, required) The account name.\n" "\nResult:\n" "[ (json array of string)\n" " \"zumyaddress\" (string) a spoomy address associated with the given account\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getaddressesbyaccount", "\"tabby\"") + HelpExampleRpc("getaddressesbyaccount", "\"tabby\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); std::string strAccount = AccountFromValue(params[0]); // Find all addresses that have the given account UniValue ret(UniValue::VARR); BOOST_FOREACH(const PAIRTYPE(CSpoomyAddress, CAddressBookData)& item, pwalletMain->mapAddressBook) { const CSpoomyAddress& address = item.first; const std::string& strName = item.second.name; if (strName == strAccount) ret.push_back(address.ToString()); } return ret; } static void SendMoney(const CTxDestination &address, CAmount nValue, bool fSubtractFeeFromAmount, CWalletTx& wtxNew, bool fUseInstantSend=false, bool fUsePrivateSend=false) { CAmount curBalance = pwalletMain->GetBalance(); // Check amount if (nValue <= 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount"); if (nValue > curBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds"); // Parse Spoomy address CScript scriptPubKey = GetScriptForDestination(address); // Create and send the transaction CReserveKey reservekey(pwalletMain); CAmount nFeeRequired; std::string strError; std::vector<CRecipient> vecSend; int nChangePosRet = -1; CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount}; vecSend.push_back(recipient); if (!pwalletMain->CreateTransaction(vecSend, wtxNew, reservekey, nFeeRequired, nChangePosRet, strError, NULL, true, fUsePrivateSend ? ONLY_DENOMINATED : ALL_COINS, fUseInstantSend)) { if (!fSubtractFeeFromAmount && nValue + nFeeRequired > pwalletMain->GetBalance()) strError = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!", FormatMoney(nFeeRequired)); throw JSONRPCError(RPC_WALLET_ERROR, strError); } if (!pwalletMain->CommitTransaction(wtxNew, reservekey, fUseInstantSend ? NetMsgType::TXLOCKREQUEST : NetMsgType::TX)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); } UniValue sendtoaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 2 || params.size() > 7) throw std::runtime_error( "sendtoaddress \"zumyaddress\" amount ( \"comment\" \"comment-to\" subtractfeefromamount use_is use_ps )\n" "\nSend an amount to a given address.\n" + HelpRequiringPassphrase() + "\nArguments:\n" "1. \"zumyaddress\" (string, required) The spoomy address to send to.\n" "2. \"amount\" (numeric or string, required) The amount in " + CURRENCY_UNIT + " to send. eg 0.1\n" "3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n" " This is not part of the transaction, just kept in your wallet.\n" "4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n" " to which you're sending the transaction. This is not part of the \n" " transaction, just kept in your wallet.\n" "5. subtractfeefromamount (boolean, optional, default=false) The fee will be deducted from the amount being sent.\n" " The recipient will receive less Spoomy than you enter in the amount field.\n" "6. \"use_is\" (bool, optional) Send this transaction as InstantSend (default: false)\n" "7. \"use_ps\" (bool, optional) Use anonymized funds only (default: false)\n" "\nResult:\n" "\"transactionid\" (string) The transaction id.\n" "\nExamples:\n" + HelpExampleCli("sendtoaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 0.1") + HelpExampleCli("sendtoaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 0.1 \"donation\" \"seans outpost\"") + HelpExampleCli("sendtoaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 0.1 \"\" \"\" true") + HelpExampleRpc("sendtoaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\", 0.1, \"donation\", \"seans outpost\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); CSpoomyAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Spoomy address"); // Amount CAmount nAmount = AmountFromValue(params[1]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); // Wallet comments CWalletTx wtx; if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); bool fSubtractFeeFromAmount = false; if (params.size() > 4) fSubtractFeeFromAmount = params[4].get_bool(); bool fUseInstantSend = false; bool fUsePrivateSend = false; if (params.size() > 5) fUseInstantSend = params[5].get_bool(); if (params.size() > 6) fUsePrivateSend = params[6].get_bool(); EnsureWalletIsUnlocked(); SendMoney(address.Get(), nAmount, fSubtractFeeFromAmount, wtx, fUseInstantSend, fUsePrivateSend); return wtx.GetHash().GetHex(); } UniValue instantsendtoaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 2 || params.size() > 5) throw std::runtime_error( "instantsendtoaddress \"zumyaddress\" amount ( \"comment\" \"comment-to\" subtractfeefromamount )\n" "\nSend an amount to a given address. The amount is a real and is rounded to the nearest 0.00000001\n" + HelpRequiringPassphrase() + "\nArguments:\n" "1. \"zumyaddress\" (string, required) The spoomy address to send to.\n" "2. \"amount\" (numeric, required) The amount in btc to send. eg 0.1\n" "3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n" " This is not part of the transaction, just kept in your wallet.\n" "4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n" " to which you're sending the transaction. This is not part of the \n" " transaction, just kept in your wallet.\n" "5. subtractfeefromamount (boolean, optional, default=false) The fee will be deducted from the amount being sent.\n" " The recipient will receive less Spoomy than you enter in the amount field.\n" "\nResult:\n" "\"transactionid\" (string) The transaction id.\n" "\nExamples:\n" + HelpExampleCli("instantsendtoaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 0.1") + HelpExampleCli("instantsendtoaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 0.1 \"donation\" \"seans outpost\"") + HelpExampleCli("instantsendtoaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 0.1 \"\" \"\" true") + HelpExampleRpc("instantsendtoaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\", 0.1, \"donation\", \"seans outpost\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); CSpoomyAddress address(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Spoomy address"); // Amount CAmount nAmount = AmountFromValue(params[1]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); // Wallet comments CWalletTx wtx; if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty()) wtx.mapValue["comment"] = params[2].get_str(); if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty()) wtx.mapValue["to"] = params[3].get_str(); bool fSubtractFeeFromAmount = false; if (params.size() > 4) fSubtractFeeFromAmount = params[4].get_bool(); EnsureWalletIsUnlocked(); SendMoney(address.Get(), nAmount, fSubtractFeeFromAmount, wtx, true); return wtx.GetHash().GetHex(); } UniValue listaddressgroupings(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp) throw std::runtime_error( "listaddressgroupings\n" "\nLists groups of addresses which have had their common ownership\n" "made public by common use as inputs or as the resulting change\n" "in past transactions\n" "\nResult:\n" "[\n" " [\n" " [\n" " \"zumyaddress\", (string) The spoomy address\n" " amount, (numeric) The amount in " + CURRENCY_UNIT + "\n" " \"account\" (string, optional) The account (DEPRECATED)\n" " ]\n" " ,...\n" " ]\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("listaddressgroupings", "") + HelpExampleRpc("listaddressgroupings", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); UniValue jsonGroupings(UniValue::VARR); std::map<CTxDestination, CAmount> balances = pwalletMain->GetAddressBalances(); BOOST_FOREACH(std::set<CTxDestination> grouping, pwalletMain->GetAddressGroupings()) { UniValue jsonGrouping(UniValue::VARR); BOOST_FOREACH(CTxDestination address, grouping) { UniValue addressInfo(UniValue::VARR); addressInfo.push_back(CSpoomyAddress(address).ToString()); addressInfo.push_back(ValueFromAmount(balances[address])); { if (pwalletMain->mapAddressBook.find(CSpoomyAddress(address).Get()) != pwalletMain->mapAddressBook.end()) addressInfo.push_back(pwalletMain->mapAddressBook.find(CSpoomyAddress(address).Get())->second.name); } jsonGrouping.push_back(addressInfo); } jsonGroupings.push_back(jsonGrouping); } return jsonGroupings; } UniValue signmessage(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 2) throw std::runtime_error( "signmessage \"zumyaddress\" \"message\"\n" "\nSign a message with the private key of an address" + HelpRequiringPassphrase() + "\n" "\nArguments:\n" "1. \"zumyaddress\" (string, required) The spoomy address to use for the private key.\n" "2. \"message\" (string, required) The message to create a signature of.\n" "\nResult:\n" "\"signature\" (string) The signature of the message encoded in base 64\n" "\nExamples:\n" "\nUnlock the wallet for 30 seconds\n" + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") + "\nCreate the signature\n" + HelpExampleCli("signmessage", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" \"my message\"") + "\nVerify the signature\n" + HelpExampleCli("verifymessage", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" \"signature\" \"my message\"") + "\nAs json rpc\n" + HelpExampleRpc("signmessage", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\", \"my message\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); std::string strAddress = params[0].get_str(); std::string strMessage = params[1].get_str(); CSpoomyAddress addr(strAddress); if (!addr.IsValid()) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address"); CKeyID keyID; if (!addr.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key"); CKey key; if (!pwalletMain->GetKey(keyID, key)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available"); CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << strMessage; std::vector<unsigned char> vchSig; if (!key.SignCompact(ss.GetHash(), vchSig)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed"); return EncodeBase64(&vchSig[0], vchSig.size()); } UniValue getreceivedbyaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 2) throw std::runtime_error( "getreceivedbyaddress \"zumyaddress\" ( minconf )\n" "\nReturns the total amount received by the given zumyaddress in transactions with at least minconf confirmations.\n" "\nArguments:\n" "1. \"zumyaddress\" (string, required) The spoomy address for transactions.\n" "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n" "\nResult:\n" "amount (numeric) The total amount in " + CURRENCY_UNIT + " received at this address.\n" "\nExamples:\n" "\nThe amount from transactions with at least 1 confirmation\n" + HelpExampleCli("getreceivedbyaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\"") + "\nThe amount including unconfirmed transactions, zero confirmations\n" + HelpExampleCli("getreceivedbyaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 0") + "\nThe amount with at least 10 confirmation, very safe\n" + HelpExampleCli("getreceivedbyaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 10") + "\nAs a json rpc call\n" + HelpExampleRpc("getreceivedbyaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\", 10") ); LOCK2(cs_main, pwalletMain->cs_wallet); // Spoomy address CSpoomyAddress address = CSpoomyAddress(params[0].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Spoomy address"); CScript scriptPubKey = GetScriptForDestination(address.Get()); if (!IsMine(*pwalletMain, scriptPubKey)) return ValueFromAmount(0); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Tally CAmount nAmount = 0; for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !CheckFinalTx(wtx)) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) if (txout.scriptPubKey == scriptPubKey) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } return ValueFromAmount(nAmount); } UniValue getreceivedbyaccount(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 2) throw std::runtime_error( "getreceivedbyaccount \"account\" ( minconf )\n" "\nDEPRECATED. Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.\n" "\nArguments:\n" "1. \"account\" (string, required) The selected account, may be the default account using \"\".\n" "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n" "\nResult:\n" "amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n" "\nExamples:\n" "\nAmount received by the default account with at least 1 confirmation\n" + HelpExampleCli("getreceivedbyaccount", "\"\"") + "\nAmount received at the tabby account including unconfirmed amounts with zero confirmations\n" + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 0") + "\nThe amount with at least 10 confirmation, very safe\n" + HelpExampleCli("getreceivedbyaccount", "\"tabby\" 10") + "\nAs a json rpc call\n" + HelpExampleRpc("getreceivedbyaccount", "\"tabby\", 10") ); LOCK2(cs_main, pwalletMain->cs_wallet); // Minimum confirmations int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); // Get the set of pub keys assigned to account std::string strAccount = AccountFromValue(params[0]); std::set<CTxDestination> setAddress = pwalletMain->GetAccountAddresses(strAccount); // Tally CAmount nAmount = 0; for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !CheckFinalTx(wtx)) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address)) if (wtx.GetDepthInMainChain() >= nMinDepth) nAmount += txout.nValue; } } return ValueFromAmount(nAmount); } UniValue getbalance(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 3) throw std::runtime_error( "getbalance ( \"account\" minconf includeWatchonly )\n" "\nIf account is not specified, returns the server's total available balance.\n" "If account is specified (DEPRECATED), returns the balance in the account.\n" "Note that the account \"\" is not the same as leaving the parameter out.\n" "The server total may be different to the balance in the default \"\" account.\n" "\nArguments:\n" "1. \"account\" (string, optional) DEPRECATED. The selected account, or \"*\" for entire wallet. It may be the default account using \"\".\n" "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n" "3. includeWatchonly (bool, optional, default=false) Also include balance in watchonly addresses (see 'importaddress')\n" "\nResult:\n" "amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this account.\n" "\nExamples:\n" "\nThe total amount in the wallet\n" + HelpExampleCli("getbalance", "") + "\nThe total amount in the wallet at least 5 blocks confirmed\n" + HelpExampleCli("getbalance", "\"*\" 10") + "\nAs a json rpc call\n" + HelpExampleRpc("getbalance", "\"*\", 10") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (params.size() == 0) return ValueFromAmount(pwalletMain->GetBalance()); int nMinDepth = 1; if (params.size() > 1) nMinDepth = params[1].get_int(); isminefilter filter = ISMINE_SPENDABLE; if(params.size() > 2) if(params[2].get_bool()) filter = filter | ISMINE_WATCH_ONLY; if (params[0].get_str() == "*") { // Calculate total balance a different way from GetBalance() // (GetBalance() sums up all unspent TxOuts) // getbalance and "getbalance * 1 true" should return the same number CAmount nBalance = 0; for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0) continue; CAmount allFee; std::string strSentAccount; std::list<COutputEntry> listReceived; std::list<COutputEntry> listSent; wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount, filter); if (wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const COutputEntry& r, listReceived) nBalance += r.amount; } BOOST_FOREACH(const COutputEntry& s, listSent) nBalance -= s.amount; nBalance -= allFee; } return ValueFromAmount(nBalance); } std::string strAccount = AccountFromValue(params[0]); CAmount nBalance = pwalletMain->GetAccountBalance(strAccount, nMinDepth, filter); return ValueFromAmount(nBalance); } UniValue getunconfirmedbalance(const UniValue &params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 0) throw std::runtime_error( "getunconfirmedbalance\n" "Returns the server's total unconfirmed balance\n"); LOCK2(cs_main, pwalletMain->cs_wallet); return ValueFromAmount(pwalletMain->GetUnconfirmedBalance()); } UniValue movecmd(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 3 || params.size() > 5) throw std::runtime_error( "move \"fromaccount\" \"toaccount\" amount ( minconf \"comment\" )\n" "\nDEPRECATED. Move a specified amount from one account in your wallet to another.\n" "\nArguments:\n" "1. \"fromaccount\" (string, required) The name of the account to move funds from. May be the default account using \"\".\n" "2. \"toaccount\" (string, required) The name of the account to move funds to. May be the default account using \"\".\n" "3. amount (numeric) Quantity of " + CURRENCY_UNIT + " to move between accounts.\n" "4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n" "5. \"comment\" (string, optional) An optional comment, stored in the wallet only.\n" "\nResult:\n" "true|false (boolean) true if successful.\n" "\nExamples:\n" "\nMove 0.01 " + CURRENCY_UNIT + " from the default account to the account named tabby\n" + HelpExampleCli("move", "\"\" \"tabby\" 0.01") + "\nMove 0.01 " + CURRENCY_UNIT + " timotei to akiko with a comment and funds have 10 confirmations\n" + HelpExampleCli("move", "\"timotei\" \"akiko\" 0.01 10 \"happy birthday!\"") + "\nAs a json rpc call\n" + HelpExampleRpc("move", "\"timotei\", \"akiko\", 0.01, 10, \"happy birthday!\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); std::string strFrom = AccountFromValue(params[0]); std::string strTo = AccountFromValue(params[1]); CAmount nAmount = AmountFromValue(params[2]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); if (params.size() > 3) // unused parameter, used to be nMinDepth, keep type-checking it though (void)params[3].get_int(); std::string strComment; if (params.size() > 4) strComment = params[4].get_str(); CWalletDB walletdb(pwalletMain->strWalletFile); if (!walletdb.TxnBegin()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); int64_t nNow = GetAdjustedTime(); // Debit CAccountingEntry debit; debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); debit.strAccount = strFrom; debit.nCreditDebit = -nAmount; debit.nTime = nNow; debit.strOtherAccount = strTo; debit.strComment = strComment; pwalletMain->AddAccountingEntry(debit, walletdb); // Credit CAccountingEntry credit; credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb); credit.strAccount = strTo; credit.nCreditDebit = nAmount; credit.nTime = nNow; credit.strOtherAccount = strFrom; credit.strComment = strComment; pwalletMain->AddAccountingEntry(credit, walletdb); if (!walletdb.TxnCommit()) throw JSONRPCError(RPC_DATABASE_ERROR, "database error"); return true; } UniValue sendfrom(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 3 || params.size() > 6) throw std::runtime_error( "sendfrom \"fromaccount\" \"tozumyaddress\" amount ( minconf \"comment\" \"comment-to\" )\n" "\nDEPRECATED (use sendtoaddress). Sent an amount from an account to a spoomy address." + HelpRequiringPassphrase() + "\n" "\nArguments:\n" "1. \"fromaccount\" (string, required) The name of the account to send funds from. May be the default account using \"\".\n" "2. \"tozumyaddress\" (string, required) The spoomy address to send funds to.\n" "3. amount (numeric or string, required) The amount in " + CURRENCY_UNIT + " (transaction fee is added on top).\n" "4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n" "5. \"comment\" (string, optional) A comment used to store what the transaction is for. \n" " This is not part of the transaction, just kept in your wallet.\n" "6. \"comment-to\" (string, optional) An optional comment to store the name of the person or organization \n" " to which you're sending the transaction. This is not part of the transaction, \n" " it is just kept in your wallet.\n" "\nResult:\n" "\"transactionid\" (string) The transaction id.\n" "\nExamples:\n" "\nSend 0.01 " + CURRENCY_UNIT + " from the default account to the address, must have at least 1 confirmation\n" + HelpExampleCli("sendfrom", "\"\" \"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 0.01") + "\nSend 0.01 from the tabby account to the given address, funds must have at least 10 confirmations\n" + HelpExampleCli("sendfrom", "\"tabby\" \"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 0.01 10 \"donation\" \"seans outpost\"") + "\nAs a json rpc call\n" + HelpExampleRpc("sendfrom", "\"tabby\", \"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\", 0.01, 10, \"donation\", \"seans outpost\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); std::string strAccount = AccountFromValue(params[0]); CSpoomyAddress address(params[1].get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Spoomy address"); CAmount nAmount = AmountFromValue(params[2]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); int nMinDepth = 1; if (params.size() > 3) nMinDepth = params[3].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 4 && !params[4].isNull() && !params[4].get_str().empty()) wtx.mapValue["comment"] = params[4].get_str(); if (params.size() > 5 && !params[5].isNull() && !params[5].get_str().empty()) wtx.mapValue["to"] = params[5].get_str(); EnsureWalletIsUnlocked(); // Check funds CAmount nBalance = pwalletMain->GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE); if (nAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); SendMoney(address.Get(), nAmount, false, wtx); return wtx.GetHash().GetHex(); } UniValue sendmany(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 2 || params.size() > 7) throw std::runtime_error( "sendmany \"fromaccount\" {\"address\":amount,...} ( minconf \"comment\" [\"address\",...] subtractfeefromamount use_is use_ps )\n" "\nSend multiple times. Amounts are double-precision floating point numbers." + HelpRequiringPassphrase() + "\n" "\nArguments:\n" "1. \"fromaccount\" (string, required) DEPRECATED. The account to send the funds from. Should be \"\" for the default account\n" "2. \"amounts\" (string, required) A json object with addresses and amounts\n" " {\n" " \"address\":amount (numeric or string) The spoomy address is the key, the numeric amount (can be string) in " + CURRENCY_UNIT + " is the value\n" " ,...\n" " }\n" "3. minconf (numeric, optional, default=1) Only use the balance confirmed at least this many times.\n" "4. \"comment\" (string, optional) A comment\n" "5. subtractfeefromamount (string, optional) A json array with addresses.\n" " The fee will be equally deducted from the amount of each selected address.\n" " Those recipients will receive less Spoomy than you enter in their corresponding amount field.\n" " If no addresses are specified here, the sender pays the fee.\n" " [\n" " \"address\" (string) Subtract fee from this address\n" " ,...\n" " ]\n" "6. \"use_is\" (bool, optional) Send this transaction as InstantSend (default: false)\n" "7. \"use_ps\" (bool, optional) Use anonymized funds only (default: false)\n" "\nResult:\n" "\"transactionid\" (string) The transaction id for the send. Only 1 transaction is created regardless of \n" " the number of addresses.\n" "\nExamples:\n" "\nSend two amounts to two different addresses:\n" + HelpExampleCli("sendmany", "\"tabby\" \"{\\\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\":0.01,\\\"C1MfcDTf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\":0.02}\"") + "\nSend two amounts to two different addresses setting the confirmation and comment:\n" + HelpExampleCli("sendmany", "\"tabby\" \"{\\\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\":0.01,\\\"C1MfcDTf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\":0.02}\" 10 \"testing\"") + "\nAs a json rpc call\n" + HelpExampleRpc("sendmany", "\"tabby\", \"{\\\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\":0.01,\\\"C1MfcDTf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\":0.02}\", 10, \"testing\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); std::string strAccount = AccountFromValue(params[0]); UniValue sendTo = params[1].get_obj(); int nMinDepth = 1; if (params.size() > 2) nMinDepth = params[2].get_int(); CWalletTx wtx; wtx.strFromAccount = strAccount; if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty()) wtx.mapValue["comment"] = params[3].get_str(); UniValue subtractFeeFromAmount(UniValue::VARR); if (params.size() > 4) subtractFeeFromAmount = params[4].get_array(); std::set<CSpoomyAddress> setAddress; std::vector<CRecipient> vecSend; CAmount totalAmount = 0; std::vector<std::string> keys = sendTo.getKeys(); BOOST_FOREACH(const std::string& name_, keys) { CSpoomyAddress address(name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Spoomy address: ")+name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+name_); setAddress.insert(address); CScript scriptPubKey = GetScriptForDestination(address.Get()); CAmount nAmount = AmountFromValue(sendTo[name_]); if (nAmount <= 0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send"); totalAmount += nAmount; bool fSubtractFeeFromAmount = false; for (unsigned int idx = 0; idx < subtractFeeFromAmount.size(); idx++) { const UniValue& addr = subtractFeeFromAmount[idx]; if (addr.get_str() == name_) fSubtractFeeFromAmount = true; } CRecipient recipient = {scriptPubKey, nAmount, fSubtractFeeFromAmount}; vecSend.push_back(recipient); } EnsureWalletIsUnlocked(); // Check funds CAmount nBalance = pwalletMain->GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE); if (totalAmount > nBalance) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send CReserveKey keyChange(pwalletMain); CAmount nFeeRequired = 0; int nChangePosRet = -1; std::string strFailReason; bool fUseInstantSend = false; bool fUsePrivateSend = false; if (params.size() > 5) fUseInstantSend = params[5].get_bool(); if (params.size() > 6) fUsePrivateSend = params[6].get_bool(); bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nChangePosRet, strFailReason, NULL, true, fUsePrivateSend ? ONLY_DENOMINATED : ALL_COINS, fUseInstantSend); if (!fCreated) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason); if (!pwalletMain->CommitTransaction(wtx, keyChange, fUseInstantSend ? NetMsgType::TXLOCKREQUEST : NetMsgType::TX)) throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed"); return wtx.GetHash().GetHex(); } // Defined in rpcmisc.cpp extern CScript _createmultisig_redeemScript(const UniValue& params); UniValue addmultisigaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 2 || params.size() > 3) { std::string msg = "addmultisigaddress nrequired [\"key\",...] ( \"account\" )\n" "\nAdd a nrequired-to-sign multisignature address to the wallet.\n" "Each key is a Spoomy address or hex-encoded public key.\n" "If 'account' is specified (DEPRECATED), assign address to that account.\n" "\nArguments:\n" "1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n" "2. \"keysobject\" (string, required) A json array of spoomy addresses or hex-encoded public keys\n" " [\n" " \"address\" (string) spoomy address or hex-encoded public key\n" " ...,\n" " ]\n" "3. \"account\" (string, optional) DEPRECATED. An account to assign the addresses to.\n" "\nResult:\n" "\"zumyaddress\" (string) A spoomy address associated with the keys.\n" "\nExamples:\n" "\nAdd a multisig address from 2 addresses\n" + HelpExampleCli("addmultisigaddress", "2 \"[\\\"D8RHNF9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\",\\\"D2sMrF9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\"]\"") + "\nAs json rpc call\n" + HelpExampleRpc("addmultisigaddress", "2, \"[\\\"D8RHNF9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\",\\\"D2sMrF9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\"]\"") ; throw std::runtime_error(msg); } LOCK2(cs_main, pwalletMain->cs_wallet); std::string strAccount; if (params.size() > 2) strAccount = AccountFromValue(params[2]); // Construct using pay-to-script-hash: CScript inner = _createmultisig_redeemScript(params); CScriptID innerID(inner); pwalletMain->AddCScript(inner); pwalletMain->SetAddressBook(innerID, strAccount, "send"); return CSpoomyAddress(innerID).ToString(); } struct tallyitem { CAmount nAmount; int nConf; int nBCConf; std::vector<uint256> txids; bool fIsWatchonly; tallyitem() { nAmount = 0; nConf = std::numeric_limits<int>::max(); nBCConf = std::numeric_limits<int>::max(); fIsWatchonly = false; } }; UniValue ListReceived(const UniValue& params, bool fByAccounts) { // Minimum confirmations int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); // Whether to include empty accounts bool fIncludeEmpty = false; if (params.size() > 1) fIncludeEmpty = params[1].get_bool(); isminefilter filter = ISMINE_SPENDABLE; if(params.size() > 2) if(params[2].get_bool()) filter = filter | ISMINE_WATCH_ONLY; // Tally std::map<CSpoomyAddress, tallyitem> mapTally; for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; if (wtx.IsCoinBase() || !CheckFinalTx(wtx)) continue; int nDepth = wtx.GetDepthInMainChain(); int nBCDepth = wtx.GetDepthInMainChain(false); if (nDepth < nMinDepth) continue; BOOST_FOREACH(const CTxOut& txout, wtx.vout) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) continue; isminefilter mine = IsMine(*pwalletMain, address); if(!(mine & filter)) continue; tallyitem& item = mapTally[address]; item.nAmount += txout.nValue; item.nConf = std::min(item.nConf, nDepth); item.nBCConf = std::min(item.nBCConf, nBCDepth); item.txids.push_back(wtx.GetHash()); if (mine & ISMINE_WATCH_ONLY) item.fIsWatchonly = true; } } // Reply UniValue ret(UniValue::VARR); std::map<std::string, tallyitem> mapAccountTally; BOOST_FOREACH(const PAIRTYPE(CSpoomyAddress, CAddressBookData)& item, pwalletMain->mapAddressBook) { const CSpoomyAddress& address = item.first; const std::string& strAccount = item.second.name; std::map<CSpoomyAddress, tallyitem>::iterator it = mapTally.find(address); if (it == mapTally.end() && !fIncludeEmpty) continue; CAmount nAmount = 0; int nConf = std::numeric_limits<int>::max(); int nBCConf = std::numeric_limits<int>::max(); bool fIsWatchonly = false; if (it != mapTally.end()) { nAmount = (*it).second.nAmount; nConf = (*it).second.nConf; nBCConf = (*it).second.nBCConf; fIsWatchonly = (*it).second.fIsWatchonly; } if (fByAccounts) { tallyitem& _item = mapAccountTally[strAccount]; _item.nAmount += nAmount; _item.nConf = std::min(_item.nConf, nConf); _item.nBCConf = std::min(_item.nBCConf, nBCConf); _item.fIsWatchonly = fIsWatchonly; } else { UniValue obj(UniValue::VOBJ); if(fIsWatchonly) obj.push_back(Pair("involvesWatchonly", true)); obj.push_back(Pair("address", address.ToString())); obj.push_back(Pair("account", strAccount)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); obj.push_back(Pair("bcconfirmations", (nBCConf == std::numeric_limits<int>::max() ? 0 : nBCConf))); if (!fByAccounts) obj.push_back(Pair("label", strAccount)); UniValue transactions(UniValue::VARR); if (it != mapTally.end()) { BOOST_FOREACH(const uint256& _item, (*it).second.txids) { transactions.push_back(_item.GetHex()); } } obj.push_back(Pair("txids", transactions)); ret.push_back(obj); } } if (fByAccounts) { for (std::map<std::string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) { CAmount nAmount = (*it).second.nAmount; int nConf = (*it).second.nConf; int nBCConf = (*it).second.nBCConf; UniValue obj(UniValue::VOBJ); if((*it).second.fIsWatchonly) obj.push_back(Pair("involvesWatchonly", true)); obj.push_back(Pair("account", (*it).first)); obj.push_back(Pair("amount", ValueFromAmount(nAmount))); obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf))); obj.push_back(Pair("bcconfirmations", (nBCConf == std::numeric_limits<int>::max() ? 0 : nBCConf))); ret.push_back(obj); } } return ret; } UniValue listreceivedbyaddress(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 3) throw std::runtime_error( "listreceivedbyaddress ( minconf includeempty includeWatchonly)\n" "\nList balances by receiving address.\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n" "2. includeempty (bool, optional, default=false) Whether to include addresses that haven't received any payments.\n" "3. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n" "\nResult:\n" "[\n" " {\n" " \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n" " \"address\" : \"receivingaddress\", (string) The receiving address\n" " \"account\" : \"accountname\", (string) DEPRECATED. The account of the receiving address. The default account is \"\".\n" " \"amount\" : x.xxx, (numeric) The total amount in " + CURRENCY_UNIT + " received by the address\n" " \"confirmations\" : n, (numeric) The number of confirmations of the most recent transaction included\n" " \"bcconfirmations\" : n (numeric) The number of blockchain confirmations of the most recent transaction included\n" " \"label\" : \"label\" (string) A comment for the address/transaction, if any\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("listreceivedbyaddress", "") + HelpExampleCli("listreceivedbyaddress", "10 true") + HelpExampleRpc("listreceivedbyaddress", "10, true, true") ); LOCK2(cs_main, pwalletMain->cs_wallet); return ListReceived(params, false); } UniValue listreceivedbyaccount(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 3) throw std::runtime_error( "listreceivedbyaccount ( minconf includeempty includeWatchonly)\n" "\nDEPRECATED. List balances by account.\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n" "2. includeempty (bool, optional, default=false) Whether to include accounts that haven't received any payments.\n" "3. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n" "\nResult:\n" "[\n" " {\n" " \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n" " \"account\" : \"accountname\", (string) The account name of the receiving account\n" " \"amount\" : x.xxx, (numeric) The total amount received by addresses with this account\n" " \"confirmations\" : n (numeric) The number of confirmations of the most recent transaction included\n" " \"bcconfirmations\" : n (numeric) The number of blockchain confirmations of the most recent transaction included\n" " \"label\" : \"label\" (string) A comment for the address/transaction, if any\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("listreceivedbyaccount", "") + HelpExampleCli("listreceivedbyaccount", "10 true") + HelpExampleRpc("listreceivedbyaccount", "10, true, true") ); LOCK2(cs_main, pwalletMain->cs_wallet); return ListReceived(params, true); } static void MaybePushAddress(UniValue & entry, const CTxDestination &dest) { CSpoomyAddress addr; if (addr.Set(dest)) entry.push_back(Pair("address", addr.ToString())); } void ListTransactions(const CWalletTx& wtx, const std::string& strAccount, int nMinDepth, bool fLong, UniValue& ret, const isminefilter& filter) { CAmount nFee; std::string strSentAccount; std::list<COutputEntry> listReceived; std::list<COutputEntry> listSent; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, filter); bool fAllAccounts = (strAccount == std::string("*")); bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY); // Sent if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) { BOOST_FOREACH(const COutputEntry& s, listSent) { UniValue entry(UniValue::VOBJ); if(involvesWatchonly || (::IsMine(*pwalletMain, s.destination) & ISMINE_WATCH_ONLY)) entry.push_back(Pair("involvesWatchonly", true)); entry.push_back(Pair("account", strSentAccount)); MaybePushAddress(entry, s.destination); std::map<std::string, std::string>::const_iterator it = wtx.mapValue.find("PS"); entry.push_back(Pair("category", (it != wtx.mapValue.end() && it->second == "1") ? "privatesend" : "send")); entry.push_back(Pair("amount", ValueFromAmount(-s.amount))); if (pwalletMain->mapAddressBook.count(s.destination)) entry.push_back(Pair("label", pwalletMain->mapAddressBook[s.destination].name)); entry.push_back(Pair("vout", s.vout)); entry.push_back(Pair("fee", ValueFromAmount(-nFee))); if (fLong) WalletTxToJSON(wtx, entry); entry.push_back(Pair("abandoned", wtx.isAbandoned())); ret.push_back(entry); } } // Received if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) { BOOST_FOREACH(const COutputEntry& r, listReceived) { std::string account; if (pwalletMain->mapAddressBook.count(r.destination)) account = pwalletMain->mapAddressBook[r.destination].name; if (fAllAccounts || (account == strAccount)) { UniValue entry(UniValue::VOBJ); if(involvesWatchonly || (::IsMine(*pwalletMain, r.destination) & ISMINE_WATCH_ONLY)) entry.push_back(Pair("involvesWatchonly", true)); entry.push_back(Pair("account", account)); MaybePushAddress(entry, r.destination); if (wtx.IsCoinBase()) { if (wtx.GetDepthInMainChain() < 1) entry.push_back(Pair("category", "orphan")); else if (wtx.GetBlocksToMaturity() > 0) entry.push_back(Pair("category", "immature")); else entry.push_back(Pair("category", "generate")); } else { entry.push_back(Pair("category", "receive")); } entry.push_back(Pair("amount", ValueFromAmount(r.amount))); if (pwalletMain->mapAddressBook.count(r.destination)) entry.push_back(Pair("label", account)); entry.push_back(Pair("vout", r.vout)); if (fLong) WalletTxToJSON(wtx, entry); ret.push_back(entry); } } } } void AcentryToJSON(const CAccountingEntry& acentry, const std::string& strAccount, UniValue& ret) { bool fAllAccounts = (strAccount == std::string("*")); if (fAllAccounts || acentry.strAccount == strAccount) { UniValue entry(UniValue::VOBJ); entry.push_back(Pair("account", acentry.strAccount)); entry.push_back(Pair("category", "move")); entry.push_back(Pair("time", acentry.nTime)); entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit))); entry.push_back(Pair("otheraccount", acentry.strOtherAccount)); entry.push_back(Pair("comment", acentry.strComment)); ret.push_back(entry); } } UniValue listtransactions(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 4) throw std::runtime_error( "listtransactions ( \"account\" count from includeWatchonly)\n" "\nReturns up to 'count' most recent transactions skipping the first 'from' transactions for account 'account'.\n" "\nArguments:\n" "1. \"account\" (string, optional) DEPRECATED. The account name. Should be \"*\".\n" "2. count (numeric, optional, default=10) The number of transactions to return\n" "3. from (numeric, optional, default=0) The number of transactions to skip\n" "4. includeWatchonly (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')\n" "\nResult:\n" "[\n" " {\n" " \"account\":\"accountname\", (string) DEPRECATED. The account name associated with the transaction. \n" " It will be \"\" for the default account.\n" " \"address\":\"zumyaddress\", (string) The spoomy address of the transaction. Not present for \n" " move transactions (category = move).\n" " \"category\":\"send|receive|move\", (string) The transaction category. 'move' is a local (off blockchain)\n" " transaction between accounts, and not associated with an address,\n" " transaction id or block. 'send' and 'receive' transactions are \n" " associated with an address, transaction id and block details\n" " \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the\n" " 'move' category for moves outbound. It is positive for the 'receive' category,\n" " and for the 'move' category for inbound funds.\n" " \"vout\": n, (numeric) the vout value\n" " \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n" " 'send' category of transactions.\n" " \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and \n" " 'receive' category of transactions. Negative confirmations indicate the\n" " transation conflicts with the block chain\n" " \"bcconfirmations\": n, (numeric) The number of blockchain confirmations for the transaction. Available for 'send' and \n" " 'receive' category of transactions. Negative confirmations indicate the\n" " transation conflicts with the block chain\n" " \"trusted\": xxx (bool) Whether we consider the outputs of this unconfirmed transaction safe to spend.\n" " \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive'\n" " category of transactions.\n" " \"blockindex\": n, (numeric) The index of the transaction in the block that includes it. Available for 'send' and 'receive'\n" " category of transactions.\n" " \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n" " \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n" " \"time\": xxx, (numeric) The transaction time in seconds since epoch (midnight Jan 1 1970 GMT).\n" " \"timereceived\": xxx, (numeric) The time received in seconds since epoch (midnight Jan 1 1970 GMT). Available \n" " for 'send' and 'receive' category of transactions.\n" " \"comment\": \"...\", (string) If a comment is associated with the transaction.\n" " \"label\": \"label\" (string) A comment for the address/transaction, if any\n" " \"otheraccount\": \"accountname\", (string) For the 'move' category of transactions, the account the funds came \n" " from (for receiving funds, positive amounts), or went to (for sending funds,\n" " negative amounts).\n" " \"bip125-replaceable\": \"yes|no|unknown\" (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n" " may be unknown for unconfirmed transactions not in the mempool\n" " }\n" "]\n" "\nExamples:\n" "\nList the most recent 10 transactions in the systems\n" + HelpExampleCli("listtransactions", "") + "\nList transactions 100 to 120\n" + HelpExampleCli("listtransactions", "\"*\" 20 100") + "\nAs a json rpc call\n" + HelpExampleRpc("listtransactions", "\"*\", 20, 100") ); LOCK2(cs_main, pwalletMain->cs_wallet); std::string strAccount = "*"; if (params.size() > 0) strAccount = params[0].get_str(); int nCount = 10; if (params.size() > 1) nCount = params[1].get_int(); int nFrom = 0; if (params.size() > 2) nFrom = params[2].get_int(); isminefilter filter = ISMINE_SPENDABLE; if(params.size() > 3) if(params[3].get_bool()) filter = filter | ISMINE_WATCH_ONLY; if (nCount < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count"); if (nFrom < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from"); UniValue ret(UniValue::VARR); const CWallet::TxItems & txOrdered = pwalletMain->wtxOrdered; // iterate backwards until we have nCount items to return: for (CWallet::TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx *const pwtx = (*it).second.first; if (pwtx != 0) ListTransactions(*pwtx, strAccount, 0, true, ret, filter); CAccountingEntry *const pacentry = (*it).second.second; if (pacentry != 0) AcentryToJSON(*pacentry, strAccount, ret); if ((int)ret.size() >= (nCount+nFrom)) break; } // ret is newest to oldest if (nFrom > (int)ret.size()) nFrom = ret.size(); if ((nFrom + nCount) > (int)ret.size()) nCount = ret.size() - nFrom; std::vector<UniValue> arrTmp = ret.getValues(); std::vector<UniValue>::iterator first = arrTmp.begin(); std::advance(first, nFrom); std::vector<UniValue>::iterator last = arrTmp.begin(); std::advance(last, nFrom+nCount); if (last != arrTmp.end()) arrTmp.erase(last, arrTmp.end()); if (first != arrTmp.begin()) arrTmp.erase(arrTmp.begin(), first); std::reverse(arrTmp.begin(), arrTmp.end()); // Return oldest to newest ret.clear(); ret.setArray(); ret.push_backV(arrTmp); return ret; } UniValue listaccounts(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 2) throw std::runtime_error( "listaccounts ( minconf includeWatchonly)\n" "\nDEPRECATED. Returns Object that has account names as keys, account balances as values.\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) Only include transactions with at least this many confirmations\n" "2. includeWatchonly (bool, optional, default=false) Include balances in watchonly addresses (see 'importaddress')\n" "\nResult:\n" "{ (json object where keys are account names, and values are numeric balances\n" " \"account\": x.xxx, (numeric) The property name is the account name, and the value is the total balance for the account.\n" " ...\n" "}\n" "\nExamples:\n" "\nList account balances where there at least 1 confirmation\n" + HelpExampleCli("listaccounts", "") + "\nList account balances including zero confirmation transactions\n" + HelpExampleCli("listaccounts", "0") + "\nList account balances for 10 or more confirmations\n" + HelpExampleCli("listaccounts", "10") + "\nAs json rpc call\n" + HelpExampleRpc("listaccounts", "10") ); LOCK2(cs_main, pwalletMain->cs_wallet); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); isminefilter includeWatchonly = ISMINE_SPENDABLE; if(params.size() > 1) if(params[1].get_bool()) includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY; std::map<std::string, CAmount> mapAccountBalances; BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& entry, pwalletMain->mapAddressBook) { if (IsMine(*pwalletMain, entry.first) & includeWatchonly) // This address belongs to me mapAccountBalances[entry.second.name] = 0; } for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) { const CWalletTx& wtx = (*it).second; CAmount nFee; std::string strSentAccount; std::list<COutputEntry> listReceived; std::list<COutputEntry> listSent; int nDepth = wtx.GetDepthInMainChain(); if (wtx.GetBlocksToMaturity() > 0 || nDepth < 0) continue; wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, includeWatchonly); mapAccountBalances[strSentAccount] -= nFee; BOOST_FOREACH(const COutputEntry& s, listSent) mapAccountBalances[strSentAccount] -= s.amount; if (nDepth >= nMinDepth) { BOOST_FOREACH(const COutputEntry& r, listReceived) if (pwalletMain->mapAddressBook.count(r.destination)) mapAccountBalances[pwalletMain->mapAddressBook[r.destination].name] += r.amount; else mapAccountBalances[""] += r.amount; } } const std::list<CAccountingEntry> & acentries = pwalletMain->laccentries; BOOST_FOREACH(const CAccountingEntry& entry, acentries) mapAccountBalances[entry.strAccount] += entry.nCreditDebit; UniValue ret(UniValue::VOBJ); BOOST_FOREACH(const PAIRTYPE(std::string, CAmount)& accountBalance, mapAccountBalances) { ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second))); } return ret; } UniValue listsinceblock(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp) throw std::runtime_error( "listsinceblock ( \"blockhash\" target-confirmations includeWatchonly)\n" "\nGet all transactions in blocks since block [blockhash], or all transactions if omitted\n" "\nArguments:\n" "1. \"blockhash\" (string, optional) The block hash to list transactions since\n" "2. target-confirmations: (numeric, optional) The confirmations required, must be 1 or more\n" "3. includeWatchonly: (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')" "\nResult:\n" "{\n" " \"transactions\": [\n" " \"account\":\"accountname\", (string) DEPRECATED. The account name associated with the transaction. Will be \"\" for the default account.\n" " \"address\":\"zumyaddress\", (string) The spoomy address of the transaction. Not present for move transactions (category = move).\n" " \"category\":\"send|receive\", (string) The transaction category. 'send' has negative amounts, 'receive' has positive amounts.\n" " \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the 'move' category for moves \n" " outbound. It is positive for the 'receive' category, and for the 'move' category for inbound funds.\n" " \"vout\" : n, (numeric) the vout value\n" " \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the 'send' category of transactions.\n" " \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n" " \"bcconfirmations\" : n, (numeric) The number of blockchain confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n" " \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive' category of transactions.\n" " \"blockindex\": n, (numeric) The index of the transaction in the block that includes it. Available for 'send' and 'receive' category of transactions.\n" " \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n" " \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n" " \"time\": xxx, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT).\n" " \"timereceived\": xxx, (numeric) The time received in seconds since epoch (Jan 1 1970 GMT). Available for 'send' and 'receive' category of transactions.\n" " \"comment\": \"...\", (string) If a comment is associated with the transaction.\n" " \"label\" : \"label\" (string) A comment for the address/transaction, if any\n" " \"to\": \"...\", (string) If a comment to is associated with the transaction.\n" " ],\n" " \"lastblock\": \"lastblockhash\" (string) The hash of the last block\n" "}\n" "\nExamples:\n" + HelpExampleCli("listsinceblock", "") + HelpExampleCli("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\" 10") + HelpExampleRpc("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\", 10") ); LOCK2(cs_main, pwalletMain->cs_wallet); CBlockIndex *pindex = NULL; int target_confirms = 1; isminefilter filter = ISMINE_SPENDABLE; if (params.size() > 0) { uint256 blockId; blockId.SetHex(params[0].get_str()); BlockMap::iterator it = mapBlockIndex.find(blockId); if (it != mapBlockIndex.end()) pindex = it->second; else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid blockhash"); } if (params.size() > 1) { target_confirms = params[1].get_int(); if (target_confirms < 1) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); } if(params.size() > 2) if(params[2].get_bool()) filter = filter | ISMINE_WATCH_ONLY; int depth = pindex ? (1 + chainActive.Height() - pindex->nHeight) : -1; UniValue transactions(UniValue::VARR); for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) { CWalletTx tx = (*it).second; if (depth == -1 || tx.GetDepthInMainChain(false) < depth) ListTransactions(tx, "*", 0, true, transactions, filter); } CBlockIndex *pblockLast = chainActive[chainActive.Height() + 1 - target_confirms]; uint256 lastblock = pblockLast ? pblockLast->GetBlockHash() : uint256(); UniValue ret(UniValue::VOBJ); ret.push_back(Pair("transactions", transactions)); ret.push_back(Pair("lastblock", lastblock.GetHex())); return ret; } UniValue gettransaction(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 2) throw std::runtime_error( "gettransaction \"txid\" ( includeWatchonly )\n" "\nGet detailed information about in-wallet transaction <txid>\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "2. \"includeWatchonly\" (bool, optional, default=false) Whether to include watchonly addresses in balance calculation and details[]\n" "\nResult:\n" "{\n" " \"amount\" : x.xxx, (numeric) The transaction amount in " + CURRENCY_UNIT + "\n" " \"confirmations\" : n, (numeric) The number of confirmations\n" " \"bcconfirmations\" : n, (numeric) The number of blockchain confirmations\n" " \"blockhash\" : \"hash\", (string) The block hash\n" " \"blockindex\" : xx, (numeric) The index of the transaction in the block that includes it\n" " \"blocktime\" : ttt, (numeric) The time in seconds since epoch (1 Jan 1970 GMT)\n" " \"txid\" : \"transactionid\", (string) The transaction id.\n" " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (1 Jan 1970 GMT)\n" " \"timereceived\" : ttt, (numeric) The time received in seconds since epoch (1 Jan 1970 GMT)\n" " \"bip125-replaceable\": \"yes|no|unknown\" (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n" " may be unknown for unconfirmed transactions not in the mempool\n" " \"details\" : [\n" " {\n" " \"account\" : \"accountname\", (string) DEPRECATED. The account name involved in the transaction, can be \"\" for the default account.\n" " \"address\" : \"zumyaddress\", (string) The spoomy address involved in the transaction\n" " \"category\" : \"send|receive\", (string) The category, either 'send' or 'receive'\n" " \"amount\" : x.xxx, (numeric) The amount in " + CURRENCY_UNIT + "\n" " \"label\" : \"label\", (string) A comment for the address/transaction, if any\n" " \"vout\" : n, (numeric) the vout value\n" " }\n" " ,...\n" " ],\n" " \"hex\" : \"data\" (string) Raw data for transaction\n" "}\n" "\nExamples:\n" + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\" true") + HelpExampleRpc("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); uint256 hash; hash.SetHex(params[0].get_str()); isminefilter filter = ISMINE_SPENDABLE; if(params.size() > 1) if(params[1].get_bool()) filter = filter | ISMINE_WATCH_ONLY; UniValue entry(UniValue::VOBJ); if (!pwalletMain->mapWallet.count(hash)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id"); const CWalletTx& wtx = pwalletMain->mapWallet[hash]; CAmount nCredit = wtx.GetCredit(filter); CAmount nDebit = wtx.GetDebit(filter); CAmount nNet = nCredit - nDebit; CAmount nFee = (wtx.IsFromMe(filter) ? wtx.GetValueOut() - nDebit : 0); entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee))); if (wtx.IsFromMe(filter)) entry.push_back(Pair("fee", ValueFromAmount(nFee))); WalletTxToJSON(wtx, entry); UniValue details(UniValue::VARR); ListTransactions(wtx, "*", 0, false, details, filter); entry.push_back(Pair("details", details)); std::string strHex = EncodeHexTx(static_cast<CTransaction>(wtx)); entry.push_back(Pair("hex", strHex)); return entry; } UniValue abandontransaction(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 1) throw std::runtime_error( "abandontransaction \"txid\"\n" "\nMark in-wallet transaction <txid> as abandoned\n" "This will mark this transaction and all its in-wallet descendants as abandoned which will allow\n" "for their inputs to be respent. It can be used to replace \"stuck\" or evicted transactions.\n" "It only works on transactions which are not included in a block and are not currently in the mempool.\n" "It has no effect on transactions which are already conflicted or abandoned.\n" "\nArguments:\n" "1. \"txid\" (string, required) The transaction id\n" "\nResult:\n" "\nExamples:\n" + HelpExampleCli("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") + HelpExampleRpc("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); uint256 hash; hash.SetHex(params[0].get_str()); if (!pwalletMain->mapWallet.count(hash)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id"); if (!pwalletMain->AbandonTransaction(hash)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not eligible for abandonment"); return NullUniValue; } UniValue backupwallet(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 1) throw std::runtime_error( "backupwallet \"destination\"\n" "\nSafely copies wallet.dat to destination, which can be a directory or a path with filename.\n" "\nArguments:\n" "1. \"destination\" (string) The destination directory or file\n" "\nExamples:\n" + HelpExampleCli("backupwallet", "\"backup.dat\"") + HelpExampleRpc("backupwallet", "\"backup.dat\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); std::string strDest = params[0].get_str(); if (!BackupWallet(*pwalletMain, strDest)) throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); return NullUniValue; } UniValue keypoolrefill(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 1) throw std::runtime_error( "keypoolrefill ( newsize )\n" "\nFills the keypool." + HelpRequiringPassphrase() + "\n" "\nArguments\n" "1. newsize (numeric, optional, default=" + itostr(DEFAULT_KEYPOOL_SIZE) + ") The new keypool size\n" "\nExamples:\n" + HelpExampleCli("keypoolrefill", "") + HelpExampleRpc("keypoolrefill", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); // 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool unsigned int kpSize = 0; if (params.size() > 0) { if (params[0].get_int() < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size."); kpSize = (unsigned int)params[0].get_int(); } EnsureWalletIsUnlocked(); pwalletMain->TopUpKeyPool(kpSize); if (pwalletMain->GetKeyPoolSize() < (pwalletMain->IsHDEnabled() ? kpSize * 2 : kpSize)) throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool."); return NullUniValue; } static void LockWallet(CWallet* pWallet) { LOCK(cs_nWalletUnlockTime); nWalletUnlockTime = 0; pWallet->Lock(); } UniValue walletpassphrase(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3)) throw std::runtime_error( "walletpassphrase \"passphrase\" timeout ( mixingonly )\n" "\nStores the wallet decryption key in memory for 'timeout' seconds.\n" "This is needed prior to performing transactions related to private keys such as sending Spoomy\n" "\nArguments:\n" "1. \"passphrase\" (string, required) The wallet passphrase\n" "2. timeout (numeric, required) The time to keep the decryption key in seconds.\n" "3. mixingonly (boolean, optional, default=false) If is true sending functions are disabled." "\nNote:\n" "Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock\n" "time that overrides the old one.\n" "\nExamples:\n" "\nUnlock the wallet for 60 seconds\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60") + "\nUnlock the wallet for 60 seconds but allow PrivateSend mixing only\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60 true") + "\nLock the wallet again (before 60 seconds)\n" + HelpExampleCli("walletlock", "") + "\nAs json rpc call\n" + HelpExampleRpc("walletpassphrase", "\"my pass phrase\", 60") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called."); // Note that the walletpassphrase is stored in params[0] which is not mlock()ed SecureString strWalletPass; strWalletPass.reserve(100); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. strWalletPass = params[0].get_str().c_str(); int64_t nSleepTime = params[1].get_int64(); bool fForMixingOnly = false; if (params.size() >= 3) fForMixingOnly = params[2].get_bool(); if (fForMixingOnly && !pwalletMain->IsLocked(true) && pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked for mixing only."); if (!pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already fully unlocked."); if (!pwalletMain->Unlock(strWalletPass, fForMixingOnly)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); pwalletMain->TopUpKeyPool(); LOCK(cs_nWalletUnlockTime); nWalletUnlockTime = GetTime() + nSleepTime; RPCRunLater("lockwallet", boost::bind(LockWallet, pwalletMain), nSleepTime); return NullUniValue; } UniValue walletpassphrasechange(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2)) throw std::runtime_error( "walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n" "\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n" "\nArguments:\n" "1. \"oldpassphrase\" (string) The current passphrase\n" "2. \"newpassphrase\" (string) The new passphrase\n" "\nExamples:\n" + HelpExampleCli("walletpassphrasechange", "\"old one\" \"new one\"") + HelpExampleRpc("walletpassphrasechange", "\"old one\", \"new one\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called."); // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strOldWalletPass; strOldWalletPass.reserve(100); strOldWalletPass = params[0].get_str().c_str(); SecureString strNewWalletPass; strNewWalletPass.reserve(100); strNewWalletPass = params[1].get_str().c_str(); if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1) throw std::runtime_error( "walletpassphrasechange <oldpassphrase> <newpassphrase>\n" "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>."); if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect."); return NullUniValue; } UniValue walletlock(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0)) throw std::runtime_error( "walletlock\n" "\nRemoves the wallet encryption key from memory, locking the wallet.\n" "After calling this method, you will need to call walletpassphrase again\n" "before being able to call any methods which require the wallet to be unlocked.\n" "\nExamples:\n" "\nSet the passphrase for 2 minutes to perform a transaction\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 120") + "\nPerform a send (requires passphrase set)\n" + HelpExampleCli("sendtoaddress", "\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\" 1.0") + "\nClear the passphrase since we are done before 2 minutes is up\n" + HelpExampleCli("walletlock", "") + "\nAs json rpc call\n" + HelpExampleRpc("walletlock", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (fHelp) return true; if (!pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called."); { LOCK(cs_nWalletUnlockTime); pwalletMain->Lock(); nWalletUnlockTime = 0; } return NullUniValue; } UniValue encryptwallet(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1)) throw std::runtime_error( "encryptwallet \"passphrase\"\n" "\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n" "After this, any calls that interact with private keys such as sending or signing \n" "will require the passphrase to be set prior the making these calls.\n" "Use the walletpassphrase call for this, and then walletlock call.\n" "If the wallet is already encrypted, use the walletpassphrasechange call.\n" "Note that this will shutdown the server.\n" "\nArguments:\n" "1. \"passphrase\" (string) The pass phrase to encrypt the wallet with. It must be at least 1 character, but should be long.\n" "\nExamples:\n" "\nEncrypt you wallet\n" + HelpExampleCli("encryptwallet", "\"my pass phrase\"") + "\nNow set the passphrase to use the wallet, such as for signing or sending spoomy\n" + HelpExampleCli("walletpassphrase", "\"my pass phrase\"") + "\nNow we can so something like sign\n" + HelpExampleCli("signmessage", "\"zumyaddress\" \"test message\"") + "\nNow lock the wallet again by removing the passphrase\n" + HelpExampleCli("walletlock", "") + "\nAs a json rpc call\n" + HelpExampleRpc("encryptwallet", "\"my pass phrase\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (fHelp) return true; if (pwalletMain->IsCrypted()) throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called."); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make params[0] mlock()'d to begin with. SecureString strWalletPass; strWalletPass.reserve(100); strWalletPass = params[0].get_str().c_str(); if (strWalletPass.length() < 1) throw std::runtime_error( "encryptwallet <passphrase>\n" "Encrypts the wallet with <passphrase>."); if (!pwalletMain->EncryptWallet(strWalletPass)) throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet."); // BDB seems to have a bad habit of writing old data into // slack space in .dat files; that is bad if the old data is // unencrypted private keys. So: StartShutdown(); return "Wallet encrypted; Spoomy server stopping, restart to run with encrypted wallet. The keypool has been flushed and a new HD seed was generated (if you are using HD). You need to make a new backup."; } UniValue lockunspent(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 2) throw std::runtime_error( "lockunspent unlock [{\"txid\":\"txid\",\"vout\":n},...]\n" "\nUpdates list of temporarily unspendable outputs.\n" "Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n" "A locked transaction output will not be chosen by automatic coin selection, when spending Spoomy.\n" "Locks are stored in memory only. Nodes start with zero locked outputs, and the locked output list\n" "is always cleared (by virtue of process exit) when a node stops or fails.\n" "Also see the listunspent call\n" "\nArguments:\n" "1. unlock (boolean, required) Whether to unlock (true) or lock (false) the specified transactions\n" "2. \"transactions\" (string, required) A json array of objects. Each object the txid (string) vout (numeric)\n" " [ (json array of json objects)\n" " {\n" " \"txid\":\"id\", (string) The transaction id\n" " \"vout\": n (numeric) The output number\n" " }\n" " ,...\n" " ]\n" "\nResult:\n" "true|false (boolean) Whether the command was successful or not\n" "\nExamples:\n" "\nList the unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nLock an unspent transaction\n" + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") + "\nList the locked transactions\n" + HelpExampleCli("listlockunspent", "") + "\nUnlock the transaction again\n" + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") + "\nAs a json rpc call\n" + HelpExampleRpc("lockunspent", "false, \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") ); LOCK2(cs_main, pwalletMain->cs_wallet); if (params.size() == 1) RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL)); else RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL)(UniValue::VARR)); bool fUnlock = params[0].get_bool(); if (params.size() == 1) { if (fUnlock) pwalletMain->UnlockAllCoins(); return true; } UniValue outputs = params[1].get_array(); for (unsigned int idx = 0; idx < outputs.size(); idx++) { const UniValue& output = outputs[idx]; if (!output.isObject()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected object"); const UniValue& o = output.get_obj(); RPCTypeCheckObj(o, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)); std::string txid = find_value(o, "txid").get_str(); if (!IsHex(txid)) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid"); int nOutput = find_value(o, "vout").get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); COutPoint outpt(uint256S(txid), nOutput); if (fUnlock) pwalletMain->UnlockCoin(outpt); else pwalletMain->LockCoin(outpt); } return true; } UniValue listlockunspent(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 0) throw std::runtime_error( "listlockunspent\n" "\nReturns list of temporarily unspendable outputs.\n" "See the lockunspent call to lock and unlock transactions for spending.\n" "\nResult:\n" "[\n" " {\n" " \"txid\" : \"transactionid\", (string) The transaction id locked\n" " \"vout\" : n (numeric) The vout value\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" "\nList the unspent transactions\n" + HelpExampleCli("listunspent", "") + "\nLock an unspent transaction\n" + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") + "\nList the locked transactions\n" + HelpExampleCli("listlockunspent", "") + "\nUnlock the transaction again\n" + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") + "\nAs a json rpc call\n" + HelpExampleRpc("listlockunspent", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); std::vector<COutPoint> vOutpts; pwalletMain->ListLockedCoins(vOutpts); UniValue ret(UniValue::VARR); BOOST_FOREACH(COutPoint &outpt, vOutpts) { UniValue o(UniValue::VOBJ); o.push_back(Pair("txid", outpt.hash.GetHex())); o.push_back(Pair("vout", (int)outpt.n)); ret.push_back(o); } return ret; } UniValue settxfee(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 1) throw std::runtime_error( "settxfee amount\n" "\nSet the transaction fee per kB. Overwrites the paytxfee parameter.\n" "\nArguments:\n" "1. amount (numeric or sting, required) The transaction fee in " + CURRENCY_UNIT + "/kB\n" "\nResult\n" "true|false (boolean) Returns true if successful\n" "\nExamples:\n" + HelpExampleCli("settxfee", "0.00001") + HelpExampleRpc("settxfee", "0.00001") ); LOCK2(cs_main, pwalletMain->cs_wallet); // Amount CAmount nAmount = AmountFromValue(params[0]); payTxFee = CFeeRate(nAmount, 1000); return true; } UniValue getwalletinfo(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 0) throw std::runtime_error( "getwalletinfo\n" "Returns an object containing various wallet state info.\n" "\nResult:\n" "{\n" " \"walletversion\": xxxxx, (numeric) the wallet version\n" " \"balance\": xxxxxxx, (numeric) the total confirmed balance of the wallet in " + CURRENCY_UNIT + "\n" " \"unconfirmed_balance\": xxx, (numeric) the total unconfirmed balance of the wallet in " + CURRENCY_UNIT + "\n" " \"immature_balance\": xxxxxx, (numeric) the total immature balance of the wallet in " + CURRENCY_UNIT + "\n" " \"txcount\": xxxxxxx, (numeric) the total number of transactions in the wallet\n" " \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n" " \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated (only counts external keys)\n" " \"keypoolsize_hd_internal\": xxxx, (numeric) how many new keys are pre-generated for internal use (used for change outputs, only appears if the wallet is using this feature, otherwise external keys are used)\n" " \"keys_left\": xxxx, (numeric) how many new keys are left since last automatic backup\n" " \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n" " \"paytxfee\": x.xxxx, (numeric) the transaction fee configuration, set in " + CURRENCY_UNIT + "/kB\n" " \"hdchainid\": \"<hash>\", (string) the ID of the HD chain\n" " \"hdaccountcount\": xxx, (numeric) how many accounts of the HD chain are in this wallet\n" " [\n" " {\n" " \"hdaccountindex\": xxx, (numeric) the index of the account\n" " \"hdexternalkeyindex\": xxxx, (numeric) current external childkey index\n" " \"hdinternalkeyindex\": xxxx, (numeric) current internal childkey index\n" " }\n" " ,...\n" " ]\n" "}\n" "\nExamples:\n" + HelpExampleCli("getwalletinfo", "") + HelpExampleRpc("getwalletinfo", "") ); LOCK2(cs_main, pwalletMain->cs_wallet); CHDChain hdChainCurrent; bool fHDEnabled = pwalletMain->GetHDChain(hdChainCurrent); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("walletversion", pwalletMain->GetVersion())); obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance()))); obj.push_back(Pair("unconfirmed_balance", ValueFromAmount(pwalletMain->GetUnconfirmedBalance()))); obj.push_back(Pair("immature_balance", ValueFromAmount(pwalletMain->GetImmatureBalance()))); obj.push_back(Pair("txcount", (int)pwalletMain->mapWallet.size())); obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime())); obj.push_back(Pair("keypoolsize", (int64_t)pwalletMain->KeypoolCountExternalKeys())); if (fHDEnabled) { obj.push_back(Pair("keypoolsize_hd_internal", (int64_t)(pwalletMain->KeypoolCountInternalKeys()))); } obj.push_back(Pair("keys_left", pwalletMain->nKeysLeftSinceAutoBackup)); if (pwalletMain->IsCrypted()) obj.push_back(Pair("unlocked_until", nWalletUnlockTime)); obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK()))); if (fHDEnabled) { obj.push_back(Pair("hdchainid", hdChainCurrent.GetID().GetHex())); obj.push_back(Pair("hdaccountcount", (int64_t)hdChainCurrent.CountAccounts())); UniValue accounts(UniValue::VARR); for (size_t i = 0; i < hdChainCurrent.CountAccounts(); ++i) { CHDAccount acc; UniValue account(UniValue::VOBJ); account.push_back(Pair("hdaccountindex", (int64_t)i)); if(hdChainCurrent.GetAccount(i, acc)) { account.push_back(Pair("hdexternalkeyindex", (int64_t)acc.nExternalChainCounter)); account.push_back(Pair("hdinternalkeyindex", (int64_t)acc.nInternalChainCounter)); } else { account.push_back(Pair("error", strprintf("account %d is missing", i))); } accounts.push_back(account); } obj.push_back(Pair("hdaccounts", accounts)); } return obj; } UniValue keepass(const UniValue& params, bool fHelp) { std::string strCommand; if (params.size() >= 1) strCommand = params[0].get_str(); if (fHelp || (strCommand != "genkey" && strCommand != "init" && strCommand != "setpassphrase")) throw std::runtime_error( "keepass <genkey|init|setpassphrase>\n"); if (strCommand == "genkey") { SecureString sResult; // Generate RSA key SecureString sKey = CKeePassIntegrator::generateKeePassKey(); sResult = "Generated Key: "; sResult += sKey; return sResult.c_str(); } else if(strCommand == "init") { // Generate base64 encoded 256 bit RSA key and associate with KeePassHttp SecureString sResult; SecureString sKey; std::string strId; keePassInt.rpcAssociate(strId, sKey); sResult = "Association successful. Id: "; sResult += strId.c_str(); sResult += " - Key: "; sResult += sKey.c_str(); return sResult.c_str(); } else if(strCommand == "setpassphrase") { if(params.size() != 2) { return "setlogin: invalid number of parameters. Requires a passphrase"; } SecureString sPassphrase = SecureString(params[1].get_str().c_str()); keePassInt.updatePassphrase(sPassphrase); return "setlogin: Updated credentials."; } return "Invalid command"; } UniValue resendwallettransactions(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() != 0) throw std::runtime_error( "resendwallettransactions\n" "Immediately re-broadcast unconfirmed wallet transactions to all peers.\n" "Intended only for testing; the wallet code periodically re-broadcasts\n" "automatically.\n" "Returns array of transaction ids that were re-broadcast.\n" ); LOCK2(cs_main, pwalletMain->cs_wallet); std::vector<uint256> txids = pwalletMain->ResendWalletTransactionsBefore(GetTime()); UniValue result(UniValue::VARR); BOOST_FOREACH(const uint256& txid, txids) { result.push_back(txid.ToString()); } return result; } UniValue listunspent(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() > 3) throw std::runtime_error( "listunspent ( minconf maxconf [\"address\",...] )\n" "\nReturns array of unspent transaction outputs\n" "with between minconf and maxconf (inclusive) confirmations.\n" "Optionally filter to only include txouts paid to specified addresses.\n" "Results are an array of Objects, each of which has:\n" "{txid, vout, scriptPubKey, amount, confirmations}\n" "\nArguments:\n" "1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n" "2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n" "3. \"addresses\" (string) A json array of spoomy addresses to filter\n" " [\n" " \"address\" (string) spoomy address\n" " ,...\n" " ]\n" "\nResult\n" "[ (array of json object)\n" " {\n" " \"txid\" : \"txid\", (string) the transaction id \n" " \"vout\" : n, (numeric) the vout value\n" " \"address\" : \"address\", (string) the Spoomy address\n" " \"account\" : \"account\", (string) DEPRECATED. The associated account, or \"\" for the default account\n" " \"scriptPubKey\" : \"key\", (string) the script key\n" " \"amount\" : x.xxx, (numeric) the transaction amount in " + CURRENCY_UNIT + "\n" " \"confirmations\" : n (numeric) The number of confirmations\n" " \"ps_rounds\" : n (numeric) The number of PS round\n" " \"spendable\" : true|false (boolean) True if spendable\n" " }\n" " ,...\n" "]\n" "\nExamples\n" + HelpExampleCli("listunspent", "") + HelpExampleCli("listunspent", "10 9999999 \"[\\\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\",\\\"C1MfcDTf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\"]\"") + HelpExampleRpc("listunspent", "10, 9999999 \"[\\\"C5nRy9Tf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\",\\\"C1MfcDTf7Zsef8gMGL2fhWA9ZslrP4K5tf\\\"]\"") ); RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM)(UniValue::VNUM)(UniValue::VARR)); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); int nMaxDepth = 9999999; if (params.size() > 1) nMaxDepth = params[1].get_int(); std::set<CSpoomyAddress> setAddress; if (params.size() > 2) { UniValue inputs = params[2].get_array(); for (unsigned int idx = 0; idx < inputs.size(); idx++) { const UniValue& input = inputs[idx]; CSpoomyAddress address(input.get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Spoomy address: ")+input.get_str()); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+input.get_str()); setAddress.insert(address); } } UniValue results(UniValue::VARR); std::vector<COutput> vecOutputs; assert(pwalletMain != NULL); LOCK2(cs_main, pwalletMain->cs_wallet); pwalletMain->AvailableCoins(vecOutputs, false, NULL, true); BOOST_FOREACH(const COutput& out, vecOutputs) { if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth) continue; if (setAddress.size()) { CTxDestination address; if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) continue; if (!setAddress.count(address)) continue; } CAmount nValue = out.tx->vout[out.i].nValue; const CScript& pk = out.tx->vout[out.i].scriptPubKey; UniValue entry(UniValue::VOBJ); entry.push_back(Pair("txid", out.tx->GetHash().GetHex())); entry.push_back(Pair("vout", out.i)); CTxDestination address; if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { entry.push_back(Pair("address", CSpoomyAddress(address).ToString())); if (pwalletMain->mapAddressBook.count(address)) entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name)); } entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end()))); if (pk.IsPayToScriptHash()) { CTxDestination address; if (ExtractDestination(pk, address)) { const CScriptID& hash = boost::get<CScriptID>(address); CScript redeemScript; if (pwalletMain->GetCScript(hash, redeemScript)) entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end()))); } } entry.push_back(Pair("amount",ValueFromAmount(nValue))); entry.push_back(Pair("confirmations",out.nDepth)); entry.push_back(Pair("ps_rounds", pwalletMain->GetInputPrivateSendRounds(CTxIn(out.tx->GetHash(), out.i)))); entry.push_back(Pair("spendable", out.fSpendable)); results.push_back(entry); } return results; } UniValue fundrawtransaction(const UniValue& params, bool fHelp) { if (!EnsureWalletIsAvailable(fHelp)) return NullUniValue; if (fHelp || params.size() < 1 || params.size() > 2) throw std::runtime_error( "fundrawtransaction \"hexstring\" includeWatching\n" "\nAdd inputs to a transaction until it has enough in value to meet its out value.\n" "This will not modify existing inputs, and will add one change output to the outputs.\n" "Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n" "The inputs added will not be signed, use signrawtransaction for that.\n" "Note that all existing inputs must have their previous output transaction be in the wallet.\n" "Note that all inputs selected must be of standard form and P2SH scripts must be" "in the wallet using importaddress or addmultisigaddress (to calculate fees).\n" "Only pay-to-pubkey, multisig, and P2SH versions thereof are currently supported for watch-only\n" "\nArguments:\n" "1. \"hexstring\" (string, required) The hex string of the raw transaction\n" "2. includeWatching (boolean, optional, default false) Also select inputs which are watch only\n" "\nResult:\n" "{\n" " \"hex\": \"value\", (string) The resulting raw transaction (hex-encoded string)\n" " \"fee\": n, (numeric) Fee the resulting transaction pays\n" " \"changepos\": n (numeric) The position of the added change output, or -1\n" "}\n" "\"hex\" \n" "\nExamples:\n" "\nCreate a transaction with no inputs\n" + HelpExampleCli("createrawtransaction", "\"[]\" \"{\\\"myaddress\\\":0.01}\"") + "\nAdd sufficient unsigned inputs to meet the output value\n" + HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") + "\nSign the transaction\n" + HelpExampleCli("signrawtransaction", "\"fundedtransactionhex\"") + "\nSend the transaction\n" + HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"") ); RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL)); // parse hex string from parameter CTransaction origTx; if (!DecodeHexTx(origTx, params[0].get_str())) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); if (origTx.vout.size() == 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "TX must have at least one output"); bool includeWatching = false; if (params.size() > 1) includeWatching = params[1].get_bool(); CMutableTransaction tx(origTx); CAmount nFee; std::string strFailReason; int nChangePos = -1; if(!pwalletMain->FundTransaction(tx, nFee, nChangePos, strFailReason, includeWatching)) throw JSONRPCError(RPC_INTERNAL_ERROR, strFailReason); UniValue result(UniValue::VOBJ); result.push_back(Pair("hex", EncodeHexTx(tx))); result.push_back(Pair("changepos", nChangePos)); result.push_back(Pair("fee", ValueFromAmount(nFee))); return result; } UniValue makekeypair(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) throw std::runtime_error( "makekeypair [prefix]\n" "Make a public/private key pair.\n" "[prefix] is optional preferred prefix for the public key.\n"); std::string strPrefix = ""; if (params.size() > 0) strPrefix = params[0].get_str(); CKey key; int nCount = 0; do { key.MakeNewKey(false); nCount++; } while (nCount < 10000 && strPrefix != HexStr(key.GetPubKey()).substr(0, strPrefix.size())); if (strPrefix != HexStr(key.GetPubKey()).substr(0, strPrefix.size())) return NullUniValue; CPrivKey vchPrivKey = key.GetPrivKey(); UniValue result(UniValue::VOBJ); result.push_back(Pair("PrivateKey", HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end()))); result.push_back(Pair("PublicKey", HexStr(key.GetPubKey()))); return result; }
[ "dev@zumy.co" ]
dev@zumy.co
90640ee2452c5ce91e3109819e6ee41710e6c52e
a2973e7238e0dc8c7b70da7d92e3c5712af0f4ae
/graphicsProgramming/runaway shapes rasist/MacGraphicsStarter/Triangle.h
470169203cbebbbbb154a24097ed9910ccaa1f84
[]
no_license
codybrowncit/C-plus-plus
581487db5e3b35ee9388f1a110a40d27c38cf343
2cea4d315b96f0537a598e16fcbcb430e1bd47a4
refs/heads/master
2020-12-25T19:04:11.471095
2015-05-14T23:16:57
2015-05-14T23:16:57
31,285,389
0
0
null
null
null
null
UTF-8
C++
false
false
535
h
// // Triangle.h // MacGraphicsStarter // // Created by Cody Brown on 11/2/14. // // #ifndef _TRIANGLE_H_ #define _TRIANGLE_H_ #include "Shape.h" #include <stdio.h> #ifdef _WIN32 #include "glut.h" #else #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glut.h> #endif #endif class Triangle : public Shape { public: Triangle(double x1, double y1, double x2, double y2, double x3, double y3, double red, double green, double blue, bool solid); void draw(); }; #endif /* defined(__MacGraphicsStarter__Triangle__) */
[ "codybrowncit@gmail.com" ]
codybrowncit@gmail.com
fcb4311f6f18fc608b4a938e55d3cee38192f212
c075cfe521103977789d600b61ad05b605f4fb10
/PI/ZAD_A.cpp
accad407d4909894943044aaeb2058198318eac3
[]
no_license
igoroogle/codeforces
dd3c99b6a5ceb19d7d9495b370d4b2ef8949f534
579cd1d2aa30a0b0b4cc61d104a02499c69ac152
refs/heads/master
2020-07-20T12:37:07.225539
2019-09-05T19:21:27
2019-09-05T19:35:26
206,639,451
0
0
null
null
null
null
UTF-8
C++
false
false
630
cpp
#include <iostream> #include <iomanip> #include <cstdio> #include <algorithm> #include <cstdlib> #include <vector> #include <set> #include <cmath> #include <map> using namespace std; typedef long long ll; const ll INF = 1000000000000000000; ll a[100010]; int main() { ll n, i, x, y; cin >> n; for (i = 0; i < n; i++) scanf("%I64d", &a[i]); for (i = 0; i < n; i++) { x = INF; if (i - 1 >= 0) x = abs(a[i - 1] - a[i]); y = INF; if (i + 1 < n) y = abs(a[i + 1] - a[i]); printf("%I64d %I64d\n", min(x, y), max(abs(a[0] - a[i]), abs(a[n - 1] - a[i]))); } return 0; }
[ "160698qnigor98" ]
160698qnigor98
97e466ef9ce9ec11921d28b127559626f374a82d
d75c8f301f369fde8ef2ad1b54168978906f129f
/tajadac/Tajada/AST/Expression.hh
d95b501a1ccbf248efeccc2233a64c85203e169e
[]
no_license
mgomezch/Tajada
efb006b64f278725fc8a542d613574e6c43e7776
4fc9ca6e93632ad2a2c73588582235627d6faae1
refs/heads/master
2016-09-06T19:07:42.782966
2012-07-12T23:04:49
2012-07-12T23:04:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,389
hh
#ifndef TAJADA_AST_EXPRESSION_HH #define TAJADA_AST_EXPRESSION_HH #include <string> // Superclasses: #include "Tajada/AST/AST.hh" #include "Tajada/Code/Block.hh" #include "Tajada/Code/Intermediate/Address/Address.hh" #include "Tajada/Type/Type.hh" namespace Tajada { namespace AST { class Expression: public virtual Tajada::AST::AST { public: Tajada::Type::Type * type; bool is_lvalue; Expression( Tajada::Type::Type * type, bool is_lvalue ); // TODO: make this pure virtual once all subclasses have their implementation virtual Tajada::Code::Intermediate::Address::Address * genl( Tajada::Code::Block * b ); // TODO: make this pure virtual once all subclasses have their implementation virtual Tajada::Code::Intermediate::Address::Address * genr( Tajada::Code::Block * b ); }; } } #endif
[ "targen@gmail.com" ]
targen@gmail.com
92c6b2d5de2bdbec5503462c3736bb14137f32e8
8d672a07b0f1182471aefea80e26bfdac4d2eac5
/Repo Server/Repo Server/Pro2/Version/version.cpp
2e8dd8b42fe8ad0a32b9aeb14210d6c06b49ce45
[]
no_license
nileshivam/Repo_Build_server
80a80770934a330ee229daa01d21286e71b9ab43
218fc0bae7c3edc6d31918a9f8213637efcaea09
refs/heads/master
2020-03-18T16:45:10.590787
2018-05-28T22:49:42
2018-05-28T22:49:42
134,984,583
0
0
null
null
null
null
UTF-8
C++
false
false
1,104
cpp
////////////////////////////////////////////////////////////////////// // Version.cpp - Implements Version Functionalities // // ver 1.0 // // Source: Jim Jawcett // // Dwivedi Nilesh, CSE687 - Object Oriented Design, Spring 2018 // ////////////////////////////////////////////////////////////////////// #include<string> #include "version.h" #include "../../FileSystem-Windows/FileSystemDemo/FileSystem.h" using namespace RepoCore; //----<Return the Latest Version of File>---------- int Version::getLatestVersion(std::string fileName) { int ver = 0; while (repo_.db().contains(fileName + "." + std::to_string(ver + 1))) { ver++; } return ver; } //----<Function to test Functionality of Version>---------- bool TestRepoCore::testVersion(RepositoryCore& r) { RepoCore::Version v(r); std::cout << "Getting the latest version of C::C.h ---> " << v.getLatestVersion("C::C.h") << std::endl; return true; } #ifdef TEST_VERSION //----<Entry Point of Version>---------- int main() { RepositoryCore r; TestRepoCore::testVersion(r); } #endif
[ "dwivedinilesh11@gmail.com" ]
dwivedinilesh11@gmail.com
04daa99c37f017fcb6dbf4599f4486580c24d74f
7e458c5c0b8c2953ccd7618bd534bd783513fbf3
/mod/ls/LSCompiler.cpp
9b9b43d16ab9ff9c5052fab821b4ed6353ecbfa2
[ "LicenseRef-scancode-public-domain", "Unlicense" ]
permissive
WindowxDeveloper/L
bdf2fac26861d5b3ae62039a5975a12837190655
0d390a6931a8121c9c6b38c363878e475f33211f
refs/heads/master
2021-04-21T12:57:22.392499
2020-03-11T21:04:42
2020-03-11T21:04:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,101
cpp
#include "LSCompiler.h" #include <L/src/stream/CFileStream.h> #include "ls.h" using namespace L; static const Symbol local_symbol("local"), set_symbol("set"), object_symbol("{object}"), array_symbol("[array]"), fun_symbol("fun"), return_symbol("return"), foreach_symbol("foreach"), do_symbol("do"), if_symbol("if"), self_symbol("self"), switch_symbol("switch"), while_symbol("while"), and_symbol("and"), or_symbol("or"), not_symbol("not"), add_symbol("+"), sub_symbol("-"), mul_symbol("*"), div_symbol("/"), mod_symbol("%"), add_assign_symbol("+="), sub_assign_symbol("-="), mul_assign_symbol("*="), div_assign_symbol("/="), mod_assign_symbol("%="), less_symbol("<"), less_equal_symbol("<="), equal_symbol("="), greater_symbol(">"), greater_equal_symbol(">="), not_equal_symbol("<>"); bool LSCompiler::read(const char* text, size_t size) { return _parser.read(_context, text, size); } bool LSCompiler::compile(ScriptFunction& script_function) { { // Clean previous state for(Function* function : _functions) { Memory::delete_type(function); } _functions.clear(); _script = ref<Script>(); } { // Compiling Function& main_function(make_function(_parser.finish())); resolve_locals(main_function, main_function.code); if(!compile_function(main_function)) { return false; } } { // Bundling functions together for(Function* function : _functions) { function->bytecode.push(ScriptInstruction {Return}); // Better safe than sorry function->bytecode_offset = uint32_t(_script->bytecode.size()); _script->bytecode.insertArray(_script->bytecode.size(), function->bytecode); } } { // Linking for(ScriptInstruction& inst : _script->bytecode) { if(inst.opcode == LoadFun) { inst.bc16 = int16_t(_functions[inst.bc16]->bytecode_offset); } } } // Use for debugging //_script->print(out); script_function.script = _script; script_function.offset = 0; return true; } LSCompiler::Function& LSCompiler::make_function(const Var& code, Function* parent) { _functions.push(); Function*& function(_functions.back()); function = Memory::new_type<Function>(); function->parent = parent; function->code = code; function->local_count = 2; // Account for return value and self function->local_table[self_symbol] = 1; // Self is always at offset 1 return *function; } bool LSCompiler::find_outer(Function& func, const Symbol& symbol, uint8_t& outer) { if(func.parent) { if(const Symbol* outer_ptr = func.outers.find(symbol)) { outer = uint8_t(outer_ptr - func.outers.begin()); return true; } else if(func.parent->local_table.find(symbol)) { outer = uint8_t(func.outers.size()); func.outers.push(symbol); return true; } else if(find_outer(*func.parent, symbol, outer)) { outer = uint8_t(func.outers.size()); func.outers.push(symbol); return true; } } return false; } void LSCompiler::resolve_locals(Function& func, const L::Var& v) { if(v.is<Array<Var>>()) { const Array<Var>& array(v.as<Array<Var>>()); L_ASSERT(array.size() > 0); if(array[0].is<Symbol>()) { // May be a special construct or a function call Symbol sym(array[0].as<Symbol>()); if(sym == local_symbol) { // Local var declaration L_ASSERT(array[1].is<Symbol>()); func.local_table[array[1].as<Symbol>()] = func.local_count++; } else if(sym == foreach_symbol) { if(array.size() >= 4) // Value only func.local_table[array[1].as<Symbol>()] = func.local_count++; if(array.size() >= 5) // Key value func.local_table[array[2].as<Symbol>()] = func.local_count++; } else if(sym == fun_symbol) { return; } } for(const Var& e : array) resolve_locals(func, e); } } bool LSCompiler::compile(Function& func, const Var& v, uint8_t offset) { if(v.is<Array<Var>>()) { const Array<Var>& array(v.as<Array<Var>>()); L_ASSERT(array.size() > 0); if(array[0].is<Symbol>()) { // May be a special construct or a function call const Symbol sym(array[0].as<Symbol>()); if(sym == set_symbol || sym == local_symbol) { if(array.size() >= 3) { compile(func, array[2], offset); compile_assignment(func, array[1], offset, offset + 1); } } else if(sym == object_symbol) { func.bytecode.push(ScriptInstruction {MakeObject, offset}); for(uintptr_t i = 1; i < array.size(); i += 2) { compile(func, array[i], offset + 1); // Key compile(func, array[i + 1], offset + 2); // Value func.bytecode.push(ScriptInstruction {SetItem, offset, uint8_t(offset + 1), uint8_t(offset + 2)}); } } else if(sym == array_symbol) { func.bytecode.push(ScriptInstruction {MakeArray, offset}); for(uintptr_t i = 1; i < array.size(); i++) { compile(func, array[i], offset + 1); // Value func.bytecode.push(ScriptInstruction {PushItem, offset, uint8_t(offset + 1)}); } } else if(sym == if_symbol) { // If for(uintptr_t i(1); i < array.size() - 1; i += 2) { compile(func, array[i], offset); // Put condition result at offset // If the result is true, jump right afterwards func.bytecode.push(ScriptInstruction {CondJump, offset}); func.bytecode.back().bc16 = 1; // If the result is false, jump after the execution block (will get updated after compilation) func.bytecode.push(ScriptInstruction {Jump}); const uintptr_t if_not_jump(func.bytecode.size() - 1); compile(func, array[i + 1], offset); // Handle else branch const bool else_branch(!(array.size() & 1) && i == array.size() - 3); if(else_branch) { // If the result is false, jump after the execution block (will get updated after compilation) func.bytecode.push(ScriptInstruction {Jump}); const uintptr_t else_avoid_jump(func.bytecode.size() - 1); // This is where we jump if the condition hasn't been met before func.bytecode[if_not_jump].bc16 = int16_t(func.bytecode.size() - if_not_jump) - 1; compile(func, array.back(), offset); // This is where we jump to avoid the else branch (condition was met before) func.bytecode[else_avoid_jump].bc16 = int16_t(func.bytecode.size() - else_avoid_jump) - 1; } else { // No else branch // This is where we jump if the condition hasn't been met before func.bytecode[if_not_jump].bc16 = int16_t(func.bytecode.size() - if_not_jump) - 1; } } } else if(sym == while_symbol) { // While const uintptr_t start_index(func.bytecode.size()); // Compute condition at offset compile(func, array[1], offset); // If the result is true, jump right afterwards func.bytecode.push(ScriptInstruction {CondJump, offset}); func.bytecode.back().bc16 = 1; // If the result is false, jump after the execution block (will get updated after compilation) func.bytecode.push(ScriptInstruction {Jump}); const uintptr_t if_not_jump(func.bytecode.size() - 1); compile(func, array[2], offset); // Jump back to the start func.bytecode.push(ScriptInstruction {Jump}); func.bytecode.back().bc16 = int16_t(start_index) - int16_t(func.bytecode.size()); // This is where we jump if the condition hasn't been met before func.bytecode[if_not_jump].bc16 = int16_t(func.bytecode.size() - if_not_jump) - 1; } else if(sym == foreach_symbol) { if(array.size() < 4) { warning("ls: %s:%d: foreach is missing parameters: (foreach [key] value iterable statement)", _context.begin(), 0); return false; } const Var& key = array.size() == 4 ? array[1] : array[1]; const Var& value = array.size() == 4 ? array[1] : array[2]; const Var& iterable = array.size() == 4 ? array[2] : array[3]; const Var& statement = array.size() == 4 ? array[3] : array[4]; // Compute object at offset compile(func, iterable, offset); func.bytecode.push(ScriptInstruction {MakeIterator, uint8_t(offset + 1), offset}); // If the iteration has ended, jump after the loop func.bytecode.push(ScriptInstruction {IterEndJump, uint8_t(offset + 1)}); const uintptr_t end_jump(func.bytecode.size() - 1); // Get next key/value pair const uint8_t key_local(*func.local_table.find(key.as<Symbol>())); const uint8_t value_local(*func.local_table.find(value.as<Symbol>())); func.bytecode.push(ScriptInstruction {Iterate, key_local, value_local, uint8_t(offset + 1)}); // Execute loop body compile(func, statement, offset + 2); // Jump back to beginning of loop func.bytecode.push(ScriptInstruction {Jump}); func.bytecode.back().bc16 = int16_t(end_jump) - int16_t(func.bytecode.size()); // This is where we jump if the iterator has reached the end func.bytecode[end_jump].bc16 = int16_t(func.bytecode.size() - end_jump) - 1; } else if(sym == switch_symbol) { // Switch // Put first compare value at offset compile(func, array[1], offset); Array<uintptr_t> cond_jumps; // Will jump to appropriate code block if condition was met Array<uintptr_t> end_jumps; // Will jump *after* the switch // Start by doing comparisons until one matches for(uintptr_t i(2); i < array.size() - 1; i += 2) { // Put second compare value at offset+1 compile(func, array[i], offset + 1); // Replace second compare value by comparison result func.bytecode.push(ScriptInstruction {Equal, uint8_t(offset + 1), offset, uint8_t(offset + 1)}); // Use result to jump conditionally func.bytecode.push(ScriptInstruction {CondJump, uint8_t(offset + 1)}); cond_jumps.push(func.bytecode.size() - 1); } // Compile the default case if there's one // We'll fallthrough here if none of the conditions were met if((array.size() & 1) != 0) { // Default case is always at the end of the switch compile(func, array.back(), offset); } // Jump to after the switch func.bytecode.push(ScriptInstruction {Jump}); end_jumps.push(func.bytecode.size() - 1); // Compile other cases for(uintptr_t i(2); i < array.size() - 1; i += 2) { // Update corresponding conditional jump to jump here const uintptr_t cond_jump(cond_jumps[(i - 2) / 2]); func.bytecode[cond_jump].bc16 = int16_t(func.bytecode.size() - cond_jump) - 1; // Compile the code compile(func, array[i + 1], offset); // Jump to after the switch func.bytecode.push(ScriptInstruction {Jump}); end_jumps.push(func.bytecode.size() - 1); } // Update all end jumps to jump here for(uintptr_t end_jump : end_jumps) { func.bytecode[end_jump].bc16 = int16_t(func.bytecode.size() - end_jump) - 1; } } else if(sym == and_symbol) { // And Array<uintptr_t> end_jumps; // Will jump *after* the and for(uintptr_t i(1); i < array.size(); i++) { compile(func, array[i], offset); func.bytecode.push(ScriptInstruction {CondNotJump, offset}); end_jumps.push(func.bytecode.size() - 1); } // Update all end jumps to jump here for(uintptr_t end_jump : end_jumps) { func.bytecode[end_jump].bc16 = int16_t(func.bytecode.size() - end_jump) - 1; } } else if(sym == or_symbol) { // Or Array<uintptr_t> end_jumps; // Will jump *after* the or for(uintptr_t i(1); i < array.size(); i++) { compile(func, array[i], offset); func.bytecode.push(ScriptInstruction {CondJump, offset}); end_jumps.push(func.bytecode.size() - 1); } // Update all end jumps to jump here for(uintptr_t end_jump : end_jumps) { func.bytecode[end_jump].bc16 = int16_t(func.bytecode.size() - end_jump) - 1; } } else if(sym == not_symbol) { // Not compile(func, array[1], offset); func.bytecode.push(ScriptInstruction {Not, offset}); } else if(sym == fun_symbol) { // Function if(array.size() > 1) { // Make a new function from the last item of the array // because the last part is always the code Function& new_function(make_function(array.back(), &func)); { // Deal with potential parameters for(uintptr_t i = 1; i < array.size() - 1; i++) { if(array[i].is<Symbol>()) { new_function.local_table[array[i].as<Symbol>()] = new_function.local_count++; } else { warning("ls: %s:%d: Function parameter names must be symbols", _context.begin(), 0); return false; } } } // Save index of function in LoadFun to allow linking later func.bytecode.push(ScriptInstruction {LoadFun, offset}); func.bytecode.back().bc16 = int16_t(_functions.size() - 1); resolve_locals(new_function, new_function.code); compile_function(new_function); // Capture outers for(const Symbol& symbol : new_function.outers) { if(const uint8_t* local = func.local_table.find(symbol)) { func.bytecode.push(ScriptInstruction {CaptLocal, offset, *local}); } else if(const Symbol* outer_ptr = func.outers.find(symbol)) { func.bytecode.push(ScriptInstruction {CaptOuter, offset, uint8_t(outer_ptr - func.outers.begin())}); } } } return true; } else if(sym == return_symbol) { for(uintptr_t i = 1; i < array.size(); i++) { compile(func, array[i], uint8_t(offset + i - 1)); } for(uintptr_t i = 1; i < array.size(); i++) { func.bytecode.push(ScriptInstruction {CopyLocal, uint8_t(i - 1), uint8_t(offset + i - 1)}); } func.bytecode.push(ScriptInstruction {Return}); } else if(sym == add_assign_symbol) { compile_op_assign(func, array, offset, Add); } else if(sym == sub_assign_symbol) { compile_op_assign(func, array, offset, Sub); } else if(sym == mul_assign_symbol) { compile_op_assign(func, array, offset, Mul); } else if(sym == div_assign_symbol) { compile_op_assign(func, array, offset, Div); } else if(sym == mod_assign_symbol) { compile_op_assign(func, array, offset, Mod); } else if(sym == add_symbol) { // Addition compile_operator(func, array, offset, Add); } else if(sym == sub_symbol) { // Subtraction and invert if(array.size() > 2) { compile_operator(func, array, offset, Sub); } else { compile(func, array[1], offset); func.bytecode.push(ScriptInstruction {Inv, offset}); } } else if(sym == mul_symbol) { // Multiplication compile_operator(func, array, offset, Mul); } else if(sym == div_symbol) { // Division compile_operator(func, array, offset, Div); } else if(sym == mod_symbol) { // Modulo compile_operator(func, array, offset, Mod); } else if(sym == less_symbol) { // Less compile_comparison(func, array, offset, LessThan); } else if(sym == less_equal_symbol) { // Less equal compile_comparison(func, array, offset, LessEqual); } else if(sym == equal_symbol) { // Equal compile_comparison(func, array, offset, Equal); } else if(sym == greater_symbol) { // Greater compile_comparison(func, array, offset, LessEqual, true); } else if(sym == greater_equal_symbol) { // Greater equal compile_comparison(func, array, offset, LessThan, true); } else if(sym == not_equal_symbol) { // Not equal compile_comparison(func, array, offset, Equal, true); } else if(sym == do_symbol) { for(uint32_t i(1); i < array.size(); i++) { compile(func, array[i], offset); } } else { // It's a function call compile_function_call(func, array, offset); } } else { // It's also a function call compile_function_call(func, array, offset); } } else if(v.is<AccessChain>()) { compile_access_chain(func, v.as<AccessChain>().array, offset, true); } else if(v.is<Symbol>()) { uint8_t outer; if(const uint8_t* local = func.local_table.find(v.as<Symbol>())) { func.bytecode.push(ScriptInstruction {CopyLocal, offset, *local}); } else if(find_outer(func, v.as<Symbol>(), outer)) { func.bytecode.push(ScriptInstruction {LoadOuter, offset, outer}); } else { func.bytecode.push(ScriptInstruction {LoadGlobal, offset}); func.bytecode.back().bcu16 = _script->global(v.as<Symbol>()); } } else { Var cst(v); if(v.is<RawSymbol>()) { const Symbol sym(v.as<RawSymbol>().sym); cst = sym; } func.bytecode.push(ScriptInstruction {LoadConst, offset}); func.bytecode.back().bcu16 = _script->constant(cst); } return true; } bool LSCompiler::compile_function(Function& func) { // Use local_count as start offset to avoid overwriting parameters const uint8_t func_offset(func.local_count); if(!compile(func, func.code, func_offset)) { return false; } // We're compiling to target func_offset as a return value, // copy that to the actual return value (0) func.bytecode.push(ScriptInstruction {CopyLocal, 0, func_offset}); return true; } void LSCompiler::compile_access_chain(Function& func, const Array<Var>& array, uint8_t offset, bool get) { L_ASSERT(array.size() >= 2); compile(func, array[0], offset + 1); // Object compile(func, array[1], offset + 2); // Index for(uint32_t i(2); i < array.size(); i++) { // Put Object[Index] where Object was func.bytecode.push(ScriptInstruction {GetItem, uint8_t(offset + 1), uint8_t(offset + 2), uint8_t(offset + 1)}); // Replace Index with next index in array compile(func, array[i], offset + 2); } if(get) { // Do final access func.bytecode.push(ScriptInstruction {GetItem, uint8_t(offset + 1), uint8_t(offset + 2), offset}); } else { func.bytecode.push(ScriptInstruction {CopyLocal, offset, uint8_t(offset + 2)}); } } void LSCompiler::compile_function_call(Function& func, const Array<Var>& array, uint8_t offset) { compile(func, array[0], offset); // Self should already be at offset+1 if specified for(uint32_t i(1); i < array.size(); i++) { compile(func, array[i], uint8_t(offset + i + 1)); } func.bytecode.push(ScriptInstruction {Call, offset, uint8_t(array.size() - 1)}); } void LSCompiler::compile_assignment(Function& func, const L::Var& dst, uint8_t src, uint8_t offset) { if(dst.is<Symbol>()) { uint8_t outer; if(const uint8_t* local = func.local_table.find(dst.as<Symbol>())) { func.bytecode.push(ScriptInstruction {CopyLocal, *local, src}); } else if(find_outer(func, dst.as<Symbol>(), outer)) { func.bytecode.push(ScriptInstruction {StoreOuter, outer, src}); } else { func.bytecode.push(ScriptInstruction {StoreGlobal, src}); func.bytecode.back().bcu16 = _script->global(dst.as<Symbol>()); } } else if(dst.is<AccessChain>()) { const Array<Var>& access_chain(dst.as<AccessChain>().array); compile_access_chain(func, access_chain, offset, false); func.bytecode.push(ScriptInstruction {SetItem, uint8_t(offset + 1), offset, src}); } else { error("Trying to set a literal value or something?"); } } void LSCompiler::compile_operator(Function& func, const L::Array<L::Var>& array, uint8_t offset, ScriptOpCode opcode) { L_ASSERT(array.size() > 1); compile(func, array[1], offset); for(uint32_t i(2); i < array.size(); i++) { compile(func, array[i], offset + 1); func.bytecode.push(ScriptInstruction {opcode, offset, uint8_t(offset + 1)}); } } void LSCompiler::compile_op_assign(Function& func, const Array<Var>& array, uint8_t offset, ScriptOpCode opcode) { L_ASSERT(array.size() >= 3); // There's a special case for local targets but otherwise we'll do a copy, operate on it, then assign it back // To be honest this special case could be dealt with during optimization later if(array[1].is<Symbol>()) { if(uint8_t* found = func.local_table.find(array[1].as<Symbol>())) { for(uintptr_t i(2); i < array.size(); i++) { compile(func, array[i], offset); func.bytecode.push(ScriptInstruction {opcode, *found, offset}); } return; } } compile(func, array[1], offset); for(uintptr_t i(2); i < array.size(); i++) { compile(func, array[i], offset + 1); func.bytecode.push(ScriptInstruction {opcode, offset, uint8_t(offset + 1)}); } compile_assignment(func, array[1], offset, offset + 1); } void LSCompiler::compile_comparison(Function& func, const L::Array<L::Var>& array, uint8_t offset, ScriptOpCode cmp, bool not) { L_ASSERT(array.size() >= 3); if(array.size() >= 3) { Array<uintptr_t> end_jumps; // Will jump *after* the comparison compile(func, array[1], offset + 1); for(uintptr_t i(2); i < array.size(); i++) { compile(func, array[i], uint8_t(offset + i)); func.bytecode.push(ScriptInstruction {cmp, offset, uint8_t(offset + i - 1), uint8_t(offset + i)}); if(not) { func.bytecode.push(ScriptInstruction {Not, offset}); } func.bytecode.push(ScriptInstruction {CondNotJump, offset}); end_jumps.push(func.bytecode.size() - 1); } // Update all end jumps to jump here for(uintptr_t end_jump : end_jumps) { func.bytecode[end_jump].bc16 = int16_t(func.bytecode.size() - end_jump) - 1; } } else { error("Comparisons need at least two operands"); } }
[ "lutopia@hotmail.fr" ]
lutopia@hotmail.fr
ce3d89925dfbc340b2ceed86c6459b05d4c28928
1066b428e123f4212431cd124bc5b71b60a3bf90
/src/util/xmlsettings/xmlsettings.cpp
4916d9c044a083fd90c0b9301eb94b78e68d4f6d
[]
no_license
amigomcu/bterm
54523c9ceb15538cb8d93ec8161deb8e81db609c
a92bd0dcd31e82beda0fbe8b205ddfd5927eb502
refs/heads/master
2021-06-11T16:18:06.508638
2016-12-25T11:39:48
2016-12-25T11:39:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,818
cpp
/****************************************************************************** * Description: See class declaration in header file * ******************************************************************************/ /****************************************************************************************** * INCLUDED FILES *****************************************************************************************/ #include "xmlsettings.h" #include <QDomDocument> #include <QDebug> #include <QDataStream> #include <QRect> #include <QSize> #include <QByteArray> #include <QStringList> /****************************************************************************************** * PRIVATE DATA *****************************************************************************************/ const QString XmlSettings::XML_TAG_NAME__ROOT = "root"; const QString XmlSettings::XML_ATTR_NAME__ITEM__VALUE = "value"; /****************************************************************************************** * DEFINITIONS *****************************************************************************************/ /****************************************************************************************** * CONSTRUCTOR, DESTRUCTOR *****************************************************************************************/ /* public */ XmlSettings::XmlSettings( QString fname ) { if ( fname.isEmpty() ){ fname = "noname.xml"; } static const QSettings::Format XmlFormat = QSettings::registerFormat("xml", readXmlFile, writeXmlFile); p_settings = std::shared_ptr<QSettings>(new QSettings( fname, XmlFormat )); } /****************************************************************************************** * STATIC METHODS *****************************************************************************************/ /* private */ bool XmlSettings::readXmlFile(QIODevice &device, QSettings::SettingsMap &map) { QDomDocument doc(""); if ( !doc.setContent( &device ) ) return false; //-- get the root element of the document (which is XML_TAG_NAME__ROOT actually) QDomElement root = doc.documentElement(); //-- handle all the root children { QDomNodeList children = root.childNodes(); for (int i = 0; i < children.count(); ++i){ QDomElement currentChild = children.item(i).toElement(); processReadKey("", map, currentChild); } } return true; } bool XmlSettings::writeXmlFile(QIODevice &device, const QSettings::SettingsMap &map) { QDomDocument doc(""); QDomElement root = doc.createElement(XML_TAG_NAME__ROOT); doc.appendChild(root); QMapIterator<QString, QVariant> i(map); while ( i.hasNext() ) { i.next(); QString sKey = i.key(); QVariant value = i.value(); processWriteKey( doc, root, sKey, i.value() ); }; QDomNode xmlNode = doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"UTF-8\""); doc.insertBefore(xmlNode, doc.firstChild()); QTextStream out( &device ); doc.save(out, 3); return true; } void XmlSettings::processWriteKey( QDomDocument& doc, QDomElement& domElement, QString key, const QVariant& value ) { int slashPos = key.indexOf( '/' ); if (slashPos < 0){ //-- given key is a param (not folder) QDomElement item_element = doc.createElement(key); item_element.setAttribute(XML_ATTR_NAME__ITEM__VALUE, XmlSettings::variantToString(value)); domElement.appendChild(item_element); } else { //-- given key is a folder //-- get the name of the group for appropriate xml node QString groupName = key.left( slashPos ); //-- get/create node for the key QDomElement groupElement; QDomNode foundGroupNode = domElement.namedItem( groupName ); if ( foundGroupNode.isNull() ){ groupElement = doc.createElement( groupName ); domElement.appendChild( groupElement ); } else { groupElement = foundGroupNode.toElement(); } //-- create truncated part of the key key = key.right( key.size() - slashPos - 1 ); //-- continue handling (creation/looking_for groups), // until it is eventually succeed processWriteKey( doc, groupElement, key, value ); } } void XmlSettings::processReadKey( QString parentKey, QSettings::SettingsMap &map, QDomElement& domElement ) { QString currentKey = parentKey + domElement.tagName(); QString currentKeyForChildren = currentKey + "/"; QDomNamedNodeMap namedNodeMap = domElement.attributes(); QDomNode value_node = namedNodeMap.namedItem(XML_ATTR_NAME__ITEM__VALUE); if (!value_node.isNull()){ //-- value is set for this item. Let's add it to the resulting map. map.insert(currentKey, stringToVariant(value_node.nodeValue())); } //-- handle all the children { QDomNodeList children = domElement.childNodes(); for (int i = 0; i < children.count(); ++i){ QDomElement currentChild = children.item(i).toElement(); processReadKey(currentKeyForChildren, map, currentChild); } } } /** * This function is copied from Qt src/corelib/io/qsettings.cpp */ QString XmlSettings::variantToString(const QVariant &v) { QString result; switch (v.type()) { case QVariant::Invalid: result = QLatin1String("@Invalid()"); break; case QVariant::ByteArray: { QByteArray a = v.toByteArray(); result = QLatin1String("@ByteArray("); result += QString::fromLatin1(a.constData(), a.size()); result += QLatin1Char(')'); break; } case QVariant::String: case QVariant::LongLong: case QVariant::ULongLong: case QVariant::Int: case QVariant::UInt: case QVariant::Bool: case QVariant::Double: case QVariant::KeySequence: { result = v.toString(); if (result.startsWith(QLatin1Char('@'))) result.prepend(QLatin1Char('@')); break; } case QVariant::Rect: { QRect r = qvariant_cast<QRect>(v); result += QLatin1String("@Rect("); result += QString::number(r.x()); result += QLatin1Char(' '); result += QString::number(r.y()); result += QLatin1Char(' '); result += QString::number(r.width()); result += QLatin1Char(' '); result += QString::number(r.height()); result += QLatin1Char(')'); break; } case QVariant::Size: { QSize s = qvariant_cast<QSize>(v); result += QLatin1String("@Size("); result += QString::number(s.width()); result += QLatin1Char(' '); result += QString::number(s.height()); result += QLatin1Char(')'); break; } case QVariant::Point: { QPoint p = qvariant_cast<QPoint>(v); result += QLatin1String("@Point("); result += QString::number(p.x()); result += QLatin1Char(' '); result += QString::number(p.y()); result += QLatin1Char(')'); break; } default: { QByteArray a; { QDataStream s(&a, QIODevice::WriteOnly); s.setVersion(QDataStream::Qt_4_0); s << v; } result = QLatin1String("@Variant("); result += QString::fromLatin1(a.constData(), a.size()); result += QLatin1Char(')'); break; } } return result; } /** * This function is copied from Qt src/corelib/io/qsettings.cpp */ QVariant XmlSettings::stringToVariant(const QString &s) { if (s.startsWith(QLatin1Char('@'))) { if (s.endsWith(QLatin1Char(')'))) { if (s.startsWith(QLatin1String("@ByteArray("))) { return QVariant(s.toLatin1().mid(11, s.size() - 12)); } else if (s.startsWith(QLatin1String("@Variant("))) { QByteArray a(s.toLatin1().mid(9)); QDataStream stream(&a, QIODevice::ReadOnly); stream.setVersion(QDataStream::Qt_4_0); QVariant result; stream >> result; return result; } else if (s.startsWith(QLatin1String("@Rect("))) { QStringList args = XmlSettings::splitArgs(s, 5); if (args.size() == 4) return QVariant(QRect(args[0].toInt(), args[1].toInt(), args[2].toInt(), args[3].toInt())); } else if (s.startsWith(QLatin1String("@Size("))) { QStringList args = XmlSettings::splitArgs(s, 5); if (args.size() == 2) return QVariant(QSize(args[0].toInt(), args[1].toInt())); } else if (s.startsWith(QLatin1String("@Point("))) { QStringList args = XmlSettings::splitArgs(s, 6); if (args.size() == 2) return QVariant(QPoint(args[0].toInt(), args[1].toInt())); } else if (s == QLatin1String("@Invalid()")) { return QVariant(); } } if (s.startsWith(QLatin1String("@@"))) return QVariant(s.mid(1)); } return QVariant(s); } /** * This function is copied from Qt src/corelib/io/qsettings.cpp */ QStringList XmlSettings::splitArgs(const QString &s, int idx) { int l = s.length(); Q_ASSERT(l > 0); Q_ASSERT(s.at(idx) == QLatin1Char('(')); Q_ASSERT(s.at(l - 1) == QLatin1Char(')')); QStringList result; QString item; for (++idx; idx < l; ++idx) { QChar c = s.at(idx); if (c == QLatin1Char(')')) { Q_ASSERT(idx == l - 1); result.append(item); } else if (c == QLatin1Char(' ')) { result.append(item); item.clear(); } else { item.append(c); } } return result; } /* protected */ /* public */ /****************************************************************************************** * METHODS *****************************************************************************************/ /* private */ /* protected */ /* public */ QVariant XmlSettings::value( const QString & key, const QVariant & defaultValue ) { if ( !settings().contains( key ) ){ settings().setValue( key, defaultValue ); } return settings().value( key ); } void XmlSettings::setValue ( const QString & key, const QVariant & value ) { settings().setValue( key, value ); }
[ "dimon.frank@gmail.com" ]
dimon.frank@gmail.com
510efa5ce86b2b9878848b0688d003617704d6dc
0b66e8133c28fd50e2ffddba741710bdc7756cb4
/1.BinaryTree/1325. Delete Leaves With a Given Value.cc
a96f6632253a9479a5828cc6cd4a674af0b98e0d
[]
no_license
tonyxwz/leetcode
21abed951622ed3606fc89c580cd32cda7b84a2f
1b7d06e638c0ff278c62d3bae27076b0881b5fde
refs/heads/master
2023-04-05T07:10:18.342010
2021-04-13T11:45:58
2021-04-13T11:45:58
71,467,875
0
0
null
null
null
null
UTF-8
C++
false
false
980
cc
// https:// leetcode.com/problems/delete-leaves-with-a-given-value/ #include "leetcode.h" // 思路:后序遍历树如果左孩子和右孩子都是空且root // ->val等于target,那么删除当前节点。删除的方式是返回空值即可。 // ```cpp /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), * left(left), right(right) {} * }; */ class Solution { public: TreeNode* removeLeafNodes(TreeNode* root, int target) { // dfs if (!root) return root; root->left = removeLeafNodes(root->left, target); root->right = removeLeafNodes(root->right, target); if (!root->left && !root->right && root->val == target) { return nullptr; } return root; } }; // ```
[ "tonyxwz@yahoo.com" ]
tonyxwz@yahoo.com
698d50530f487ef794ba0e80419aff41e27b02f8
7e1e036af3a15dd1d1c0940109f5943010144f7e
/Aula 03/Pos-Aula 03.cpp
5217a95611494b9ecef15c9ffa978e114079ad39
[]
no_license
GustaFreitas/AulasAED
7ecb1f03c70c1eac91aa83d1833d5b84f29b947f
5ed05ecf1bca04a9f24ca1bdbd1ae7fa5f55a6c9
refs/heads/master
2021-03-04T23:21:21.890940
2020-06-01T21:31:46
2020-06-01T21:31:46
246,075,313
0
0
null
null
null
null
ISO-8859-1
C++
false
false
2,825
cpp
#include <math.h> #include <conio.h> #include <stdio.h> #include <locale.h> #include <stdlib.h> #include <string.h> struct Bolsa { char Nom[50], Are[20]; float Val_Atu, Val_Ant, Dif; double Var; }; float Media (float x) { return (x / 5); } float Novo (float x, float y) { return (x + y); } int main (void) { setlocale (LC_ALL, "Portuguese"); struct Bolsa V[6]; char Aux = '%'; for (int i = 1; i <= 5; i++) { printf ("Informe o nome da compania: "); scanf ("%s", &V[i].Nom); fflush (stdin); printf ("Informe a área de atuação da compania: "); scanf ("%s", &V[i].Are); fflush (stdin); printf ("Informe o valor atual das ações: "); scanf ("%f", &V[i].Val_Atu); fflush (stdin); printf ("Informe o valor anterior das ações: "); scanf ("%f", &V[i].Val_Ant); fflush (stdin); V[i].Dif = V[i].Val_Atu - V[i].Val_Ant; V[i].Var = (V[i].Dif * 100) / V[i].Val_Ant; if (V[i].Dif < 0) { printf ("A compania %s do ramo de %s teve uma queda de %.2lf%c desde a abertura da bolsa.\n", V[i].Nom, V[i].Are, V[i].Var, Aux); } else { printf ("\n\n A compania %s do ramo de %s teve um aumento de %.2lf%C desde a abertura da bolsa.\n", V[i].Nom, V[i].Are, V[i].Var, Aux); } printf ("----------------------------------------------------------------------------------\n"); } system ("pause"); system ("cls"); float Val, Med, Par; printf ("Informe um valor de ação: "); scanf ("%f", &Val); printf ("As seguintes ações estão do indicado:\n"); for (int i = 1; i <= 5; i++) { if (Val > V[i].Val_Atu) { printf ("Compania: %s\n", V[i].Nom); printf ("Valor das ações: %.2f\n\n", V[i].Val_Atu); } Med = Med + V[i].Val_Atu; } system ("pause"); system ("cls"); printf ("A média das ações é: %.2f\n\n", Media (Med)); system ("pause"); system ("cls"); printf ("Escolha um novo parametro para alterar as acões de todas as companias: "); scanf ("%f", &Par); ("----------------------------------------------------------------------------------\n\n"); for (int i = 1; i <= 5; i++) { V[i].Val_Atu = Novo (Par, V[i].Val_Atu); V[i].Dif = V[i].Val_Atu - V[i].Val_Ant; V[i].Var = (V[i].Dif * 100) / V[i].Val_Ant; printf ("Compania: %s\n", V[i].Nom); printf ("Novo valor de ações: %.2f\n", V[i].Val_Atu); if (V[i].Dif < 0) { printf ("A compania %s do ramo de %s teve uma queda de %.2lf%c desde a abertura da bolsa.\n", V[i].Nom, V[i].Are, V[i].Var, Aux); } else { printf ("\n\n A compania %s do ramo de %s teve um aumento de %.2lf%C desde a abertura da bolsa.\n", V[i].Nom, V[i].Are, V[i].Var, Aux); } printf ("----------------------------------------------------------------------------------\n"); } getch(); return 0; }
[ "gustavoluizdefreitas@hotmail.com.br" ]
gustavoluizdefreitas@hotmail.com.br
eee188f0c7bcfe9c81187469b2ed11b178ab890c
57126f65a47d4b8ccd8932425178c6717639c989
/external/glbinding-2.0.0/source/glbinding/include/glbinding/gl31/enum.h
ffb1de207180ecc648d1c87b621d998d12dd9fda
[ "MIT" ]
permissive
3d-scan/rgbd-recon
4c435e06ecee867fd7bd365363eff92ef7513a39
c4a5614eaa55dd93c74da70d6fb3d813d74f2903
refs/heads/master
2020-03-22T16:09:56.569088
2018-04-28T10:58:51
2018-04-28T10:58:51
140,307,666
1
0
MIT
2018-07-09T15:47:26
2018-07-09T15:47:26
null
UTF-8
C++
false
false
49,577
h
#pragma once #include <glbinding/nogl.h> #include <glbinding/gl/enum.h> namespace gl31 { // import enums to namespace // AccumOp using gl::GL_ACCUM; using gl::GL_LOAD; using gl::GL_RETURN; using gl::GL_MULT; using gl::GL_ADD; // AlphaFunction using gl::GL_NEVER; using gl::GL_LESS; using gl::GL_EQUAL; using gl::GL_LEQUAL; using gl::GL_GREATER; using gl::GL_NOTEQUAL; using gl::GL_GEQUAL; using gl::GL_ALWAYS; // BlendEquationModeEXT using gl::GL_LOGIC_OP; // BlendingFactorDest using gl::GL_ZERO; using gl::GL_SRC_COLOR; using gl::GL_ONE_MINUS_SRC_COLOR; using gl::GL_SRC_ALPHA; using gl::GL_ONE_MINUS_SRC_ALPHA; using gl::GL_DST_ALPHA; using gl::GL_ONE_MINUS_DST_ALPHA; using gl::GL_ONE; // BlendingFactorSrc // using gl::GL_ZERO; // reuse BlendingFactorDest // using gl::GL_SRC_ALPHA; // reuse BlendingFactorDest // using gl::GL_ONE_MINUS_SRC_ALPHA; // reuse BlendingFactorDest // using gl::GL_DST_ALPHA; // reuse BlendingFactorDest // using gl::GL_ONE_MINUS_DST_ALPHA; // reuse BlendingFactorDest using gl::GL_DST_COLOR; using gl::GL_ONE_MINUS_DST_COLOR; using gl::GL_SRC_ALPHA_SATURATE; // using gl::GL_ONE; // reuse BlendingFactorDest // ClipPlaneName using gl::GL_CLIP_DISTANCE0; using gl::GL_CLIP_PLANE0; using gl::GL_CLIP_DISTANCE1; using gl::GL_CLIP_PLANE1; using gl::GL_CLIP_DISTANCE2; using gl::GL_CLIP_PLANE2; using gl::GL_CLIP_DISTANCE3; using gl::GL_CLIP_PLANE3; using gl::GL_CLIP_DISTANCE4; using gl::GL_CLIP_PLANE4; using gl::GL_CLIP_DISTANCE5; using gl::GL_CLIP_PLANE5; using gl::GL_CLIP_DISTANCE6; using gl::GL_CLIP_DISTANCE7; // ColorMaterialFace using gl::GL_FRONT; using gl::GL_BACK; using gl::GL_FRONT_AND_BACK; // ColorMaterialParameter using gl::GL_AMBIENT; using gl::GL_DIFFUSE; using gl::GL_SPECULAR; using gl::GL_EMISSION; using gl::GL_AMBIENT_AND_DIFFUSE; // ColorPointerType using gl::GL_BYTE; using gl::GL_UNSIGNED_BYTE; using gl::GL_SHORT; using gl::GL_UNSIGNED_SHORT; using gl::GL_INT; using gl::GL_UNSIGNED_INT; using gl::GL_FLOAT; using gl::GL_DOUBLE; // CullFaceMode // using gl::GL_FRONT; // reuse ColorMaterialFace // using gl::GL_BACK; // reuse ColorMaterialFace // using gl::GL_FRONT_AND_BACK; // reuse ColorMaterialFace // DepthFunction // using gl::GL_NEVER; // reuse AlphaFunction // using gl::GL_LESS; // reuse AlphaFunction // using gl::GL_EQUAL; // reuse AlphaFunction // using gl::GL_LEQUAL; // reuse AlphaFunction // using gl::GL_GREATER; // reuse AlphaFunction // using gl::GL_NOTEQUAL; // reuse AlphaFunction // using gl::GL_GEQUAL; // reuse AlphaFunction // using gl::GL_ALWAYS; // reuse AlphaFunction // DrawBufferMode using gl::GL_NONE; using gl::GL_FRONT_LEFT; using gl::GL_FRONT_RIGHT; using gl::GL_BACK_LEFT; using gl::GL_BACK_RIGHT; // using gl::GL_FRONT; // reuse ColorMaterialFace // using gl::GL_BACK; // reuse ColorMaterialFace using gl::GL_LEFT; using gl::GL_RIGHT; // using gl::GL_FRONT_AND_BACK; // reuse ColorMaterialFace using gl::GL_AUX0; using gl::GL_AUX1; using gl::GL_AUX2; using gl::GL_AUX3; // EnableCap using gl::GL_POINT_SMOOTH; using gl::GL_LINE_SMOOTH; using gl::GL_LINE_STIPPLE; using gl::GL_POLYGON_SMOOTH; using gl::GL_POLYGON_STIPPLE; using gl::GL_CULL_FACE; using gl::GL_LIGHTING; using gl::GL_COLOR_MATERIAL; using gl::GL_FOG; using gl::GL_DEPTH_TEST; using gl::GL_STENCIL_TEST; using gl::GL_NORMALIZE; using gl::GL_ALPHA_TEST; using gl::GL_DITHER; using gl::GL_BLEND; using gl::GL_INDEX_LOGIC_OP; using gl::GL_COLOR_LOGIC_OP; using gl::GL_SCISSOR_TEST; using gl::GL_TEXTURE_GEN_S; using gl::GL_TEXTURE_GEN_T; using gl::GL_TEXTURE_GEN_R; using gl::GL_TEXTURE_GEN_Q; using gl::GL_AUTO_NORMAL; using gl::GL_MAP1_COLOR_4; using gl::GL_MAP1_INDEX; using gl::GL_MAP1_NORMAL; using gl::GL_MAP1_TEXTURE_COORD_1; using gl::GL_MAP1_TEXTURE_COORD_2; using gl::GL_MAP1_TEXTURE_COORD_3; using gl::GL_MAP1_TEXTURE_COORD_4; using gl::GL_MAP1_VERTEX_3; using gl::GL_MAP1_VERTEX_4; using gl::GL_MAP2_COLOR_4; using gl::GL_MAP2_INDEX; using gl::GL_MAP2_NORMAL; using gl::GL_MAP2_TEXTURE_COORD_1; using gl::GL_MAP2_TEXTURE_COORD_2; using gl::GL_MAP2_TEXTURE_COORD_3; using gl::GL_MAP2_TEXTURE_COORD_4; using gl::GL_MAP2_VERTEX_3; using gl::GL_MAP2_VERTEX_4; using gl::GL_TEXTURE_1D; using gl::GL_TEXTURE_2D; using gl::GL_POLYGON_OFFSET_POINT; using gl::GL_POLYGON_OFFSET_LINE; // using gl::GL_CLIP_PLANE0; // reuse ClipPlaneName // using gl::GL_CLIP_PLANE1; // reuse ClipPlaneName // using gl::GL_CLIP_PLANE2; // reuse ClipPlaneName // using gl::GL_CLIP_PLANE3; // reuse ClipPlaneName // using gl::GL_CLIP_PLANE4; // reuse ClipPlaneName // using gl::GL_CLIP_PLANE5; // reuse ClipPlaneName using gl::GL_LIGHT0; using gl::GL_LIGHT1; using gl::GL_LIGHT2; using gl::GL_LIGHT3; using gl::GL_LIGHT4; using gl::GL_LIGHT5; using gl::GL_LIGHT6; using gl::GL_LIGHT7; using gl::GL_POLYGON_OFFSET_FILL; using gl::GL_VERTEX_ARRAY; using gl::GL_NORMAL_ARRAY; using gl::GL_COLOR_ARRAY; using gl::GL_INDEX_ARRAY; using gl::GL_TEXTURE_COORD_ARRAY; using gl::GL_EDGE_FLAG_ARRAY; // ErrorCode using gl::GL_NO_ERROR; using gl::GL_INVALID_ENUM; using gl::GL_INVALID_VALUE; using gl::GL_INVALID_OPERATION; using gl::GL_STACK_OVERFLOW; using gl::GL_STACK_UNDERFLOW; using gl::GL_OUT_OF_MEMORY; using gl::GL_INVALID_FRAMEBUFFER_OPERATION; // FeedBackToken using gl::GL_PASS_THROUGH_TOKEN; using gl::GL_POINT_TOKEN; using gl::GL_LINE_TOKEN; using gl::GL_POLYGON_TOKEN; using gl::GL_BITMAP_TOKEN; using gl::GL_DRAW_PIXEL_TOKEN; using gl::GL_COPY_PIXEL_TOKEN; using gl::GL_LINE_RESET_TOKEN; // FeedbackType using gl::GL_2D; using gl::GL_3D; using gl::GL_3D_COLOR; using gl::GL_3D_COLOR_TEXTURE; using gl::GL_4D_COLOR_TEXTURE; // FogCoordinatePointerType // using gl::GL_FLOAT; // reuse ColorPointerType // using gl::GL_DOUBLE; // reuse ColorPointerType // FogMode using gl::GL_EXP; using gl::GL_EXP2; using gl::GL_LINEAR; // FogParameter using gl::GL_FOG_INDEX; using gl::GL_FOG_DENSITY; using gl::GL_FOG_START; using gl::GL_FOG_END; using gl::GL_FOG_MODE; using gl::GL_FOG_COLOR; // FogPointerTypeEXT // using gl::GL_FLOAT; // reuse ColorPointerType // using gl::GL_DOUBLE; // reuse ColorPointerType // FogPointerTypeIBM // using gl::GL_FLOAT; // reuse ColorPointerType // using gl::GL_DOUBLE; // reuse ColorPointerType // FrontFaceDirection using gl::GL_CW; using gl::GL_CCW; // GetMapQuery using gl::GL_COEFF; using gl::GL_ORDER; using gl::GL_DOMAIN; // GetPName using gl::GL_CURRENT_COLOR; using gl::GL_CURRENT_INDEX; using gl::GL_CURRENT_NORMAL; using gl::GL_CURRENT_TEXTURE_COORDS; using gl::GL_CURRENT_RASTER_COLOR; using gl::GL_CURRENT_RASTER_INDEX; using gl::GL_CURRENT_RASTER_TEXTURE_COORDS; using gl::GL_CURRENT_RASTER_POSITION; using gl::GL_CURRENT_RASTER_POSITION_VALID; using gl::GL_CURRENT_RASTER_DISTANCE; // using gl::GL_POINT_SMOOTH; // reuse EnableCap using gl::GL_POINT_SIZE; using gl::GL_POINT_SIZE_RANGE; using gl::GL_SMOOTH_POINT_SIZE_RANGE; using gl::GL_POINT_SIZE_GRANULARITY; using gl::GL_SMOOTH_POINT_SIZE_GRANULARITY; // using gl::GL_LINE_SMOOTH; // reuse EnableCap using gl::GL_LINE_WIDTH; using gl::GL_LINE_WIDTH_RANGE; using gl::GL_SMOOTH_LINE_WIDTH_RANGE; using gl::GL_LINE_WIDTH_GRANULARITY; using gl::GL_SMOOTH_LINE_WIDTH_GRANULARITY; // using gl::GL_LINE_STIPPLE; // reuse EnableCap using gl::GL_LINE_STIPPLE_PATTERN; using gl::GL_LINE_STIPPLE_REPEAT; using gl::GL_LIST_MODE; using gl::GL_MAX_LIST_NESTING; using gl::GL_LIST_BASE; using gl::GL_LIST_INDEX; using gl::GL_POLYGON_MODE; // using gl::GL_POLYGON_SMOOTH; // reuse EnableCap // using gl::GL_POLYGON_STIPPLE; // reuse EnableCap using gl::GL_EDGE_FLAG; // using gl::GL_CULL_FACE; // reuse EnableCap using gl::GL_CULL_FACE_MODE; using gl::GL_FRONT_FACE; // using gl::GL_LIGHTING; // reuse EnableCap using gl::GL_LIGHT_MODEL_LOCAL_VIEWER; using gl::GL_LIGHT_MODEL_TWO_SIDE; using gl::GL_LIGHT_MODEL_AMBIENT; using gl::GL_SHADE_MODEL; using gl::GL_COLOR_MATERIAL_FACE; using gl::GL_COLOR_MATERIAL_PARAMETER; // using gl::GL_COLOR_MATERIAL; // reuse EnableCap // using gl::GL_FOG; // reuse EnableCap // using gl::GL_FOG_INDEX; // reuse FogParameter // using gl::GL_FOG_DENSITY; // reuse FogParameter // using gl::GL_FOG_START; // reuse FogParameter // using gl::GL_FOG_END; // reuse FogParameter // using gl::GL_FOG_MODE; // reuse FogParameter // using gl::GL_FOG_COLOR; // reuse FogParameter using gl::GL_DEPTH_RANGE; // using gl::GL_DEPTH_TEST; // reuse EnableCap using gl::GL_DEPTH_WRITEMASK; using gl::GL_DEPTH_CLEAR_VALUE; using gl::GL_DEPTH_FUNC; using gl::GL_ACCUM_CLEAR_VALUE; // using gl::GL_STENCIL_TEST; // reuse EnableCap using gl::GL_STENCIL_CLEAR_VALUE; using gl::GL_STENCIL_FUNC; using gl::GL_STENCIL_VALUE_MASK; using gl::GL_STENCIL_FAIL; using gl::GL_STENCIL_PASS_DEPTH_FAIL; using gl::GL_STENCIL_PASS_DEPTH_PASS; using gl::GL_STENCIL_REF; using gl::GL_STENCIL_WRITEMASK; using gl::GL_MATRIX_MODE; // using gl::GL_NORMALIZE; // reuse EnableCap using gl::GL_VIEWPORT; using gl::GL_MODELVIEW_STACK_DEPTH; using gl::GL_PROJECTION_STACK_DEPTH; using gl::GL_TEXTURE_STACK_DEPTH; using gl::GL_MODELVIEW_MATRIX; using gl::GL_PROJECTION_MATRIX; using gl::GL_TEXTURE_MATRIX; using gl::GL_ATTRIB_STACK_DEPTH; using gl::GL_CLIENT_ATTRIB_STACK_DEPTH; // using gl::GL_ALPHA_TEST; // reuse EnableCap using gl::GL_ALPHA_TEST_FUNC; using gl::GL_ALPHA_TEST_REF; // using gl::GL_DITHER; // reuse EnableCap using gl::GL_BLEND_DST; using gl::GL_BLEND_SRC; // using gl::GL_BLEND; // reuse EnableCap using gl::GL_LOGIC_OP_MODE; // using gl::GL_INDEX_LOGIC_OP; // reuse EnableCap // using gl::GL_LOGIC_OP; // reuse BlendEquationModeEXT // using gl::GL_COLOR_LOGIC_OP; // reuse EnableCap using gl::GL_AUX_BUFFERS; using gl::GL_DRAW_BUFFER; using gl::GL_READ_BUFFER; using gl::GL_SCISSOR_BOX; // using gl::GL_SCISSOR_TEST; // reuse EnableCap using gl::GL_INDEX_CLEAR_VALUE; using gl::GL_INDEX_WRITEMASK; using gl::GL_COLOR_CLEAR_VALUE; using gl::GL_COLOR_WRITEMASK; using gl::GL_INDEX_MODE; using gl::GL_RGBA_MODE; using gl::GL_DOUBLEBUFFER; using gl::GL_STEREO; using gl::GL_RENDER_MODE; using gl::GL_PERSPECTIVE_CORRECTION_HINT; using gl::GL_POINT_SMOOTH_HINT; using gl::GL_LINE_SMOOTH_HINT; using gl::GL_POLYGON_SMOOTH_HINT; using gl::GL_FOG_HINT; // using gl::GL_TEXTURE_GEN_S; // reuse EnableCap // using gl::GL_TEXTURE_GEN_T; // reuse EnableCap // using gl::GL_TEXTURE_GEN_R; // reuse EnableCap // using gl::GL_TEXTURE_GEN_Q; // reuse EnableCap using gl::GL_PIXEL_MAP_I_TO_I_SIZE; using gl::GL_PIXEL_MAP_S_TO_S_SIZE; using gl::GL_PIXEL_MAP_I_TO_R_SIZE; using gl::GL_PIXEL_MAP_I_TO_G_SIZE; using gl::GL_PIXEL_MAP_I_TO_B_SIZE; using gl::GL_PIXEL_MAP_I_TO_A_SIZE; using gl::GL_PIXEL_MAP_R_TO_R_SIZE; using gl::GL_PIXEL_MAP_G_TO_G_SIZE; using gl::GL_PIXEL_MAP_B_TO_B_SIZE; using gl::GL_PIXEL_MAP_A_TO_A_SIZE; using gl::GL_UNPACK_SWAP_BYTES; using gl::GL_UNPACK_LSB_FIRST; using gl::GL_UNPACK_ROW_LENGTH; using gl::GL_UNPACK_SKIP_ROWS; using gl::GL_UNPACK_SKIP_PIXELS; using gl::GL_UNPACK_ALIGNMENT; using gl::GL_PACK_SWAP_BYTES; using gl::GL_PACK_LSB_FIRST; using gl::GL_PACK_ROW_LENGTH; using gl::GL_PACK_SKIP_ROWS; using gl::GL_PACK_SKIP_PIXELS; using gl::GL_PACK_ALIGNMENT; using gl::GL_MAP_COLOR; using gl::GL_MAP_STENCIL; using gl::GL_INDEX_SHIFT; using gl::GL_INDEX_OFFSET; using gl::GL_RED_SCALE; using gl::GL_RED_BIAS; using gl::GL_ZOOM_X; using gl::GL_ZOOM_Y; using gl::GL_GREEN_SCALE; using gl::GL_GREEN_BIAS; using gl::GL_BLUE_SCALE; using gl::GL_BLUE_BIAS; using gl::GL_ALPHA_SCALE; using gl::GL_ALPHA_BIAS; using gl::GL_DEPTH_SCALE; using gl::GL_DEPTH_BIAS; using gl::GL_MAX_EVAL_ORDER; using gl::GL_MAX_LIGHTS; using gl::GL_MAX_CLIP_DISTANCES; using gl::GL_MAX_CLIP_PLANES; using gl::GL_MAX_TEXTURE_SIZE; using gl::GL_MAX_PIXEL_MAP_TABLE; using gl::GL_MAX_ATTRIB_STACK_DEPTH; using gl::GL_MAX_MODELVIEW_STACK_DEPTH; using gl::GL_MAX_NAME_STACK_DEPTH; using gl::GL_MAX_PROJECTION_STACK_DEPTH; using gl::GL_MAX_TEXTURE_STACK_DEPTH; using gl::GL_MAX_VIEWPORT_DIMS; using gl::GL_MAX_CLIENT_ATTRIB_STACK_DEPTH; using gl::GL_SUBPIXEL_BITS; using gl::GL_INDEX_BITS; using gl::GL_RED_BITS; using gl::GL_GREEN_BITS; using gl::GL_BLUE_BITS; using gl::GL_ALPHA_BITS; using gl::GL_DEPTH_BITS; using gl::GL_STENCIL_BITS; using gl::GL_ACCUM_RED_BITS; using gl::GL_ACCUM_GREEN_BITS; using gl::GL_ACCUM_BLUE_BITS; using gl::GL_ACCUM_ALPHA_BITS; using gl::GL_NAME_STACK_DEPTH; // using gl::GL_AUTO_NORMAL; // reuse EnableCap // using gl::GL_MAP1_COLOR_4; // reuse EnableCap // using gl::GL_MAP1_INDEX; // reuse EnableCap // using gl::GL_MAP1_NORMAL; // reuse EnableCap // using gl::GL_MAP1_TEXTURE_COORD_1; // reuse EnableCap // using gl::GL_MAP1_TEXTURE_COORD_2; // reuse EnableCap // using gl::GL_MAP1_TEXTURE_COORD_3; // reuse EnableCap // using gl::GL_MAP1_TEXTURE_COORD_4; // reuse EnableCap // using gl::GL_MAP1_VERTEX_3; // reuse EnableCap // using gl::GL_MAP1_VERTEX_4; // reuse EnableCap // using gl::GL_MAP2_COLOR_4; // reuse EnableCap // using gl::GL_MAP2_INDEX; // reuse EnableCap // using gl::GL_MAP2_NORMAL; // reuse EnableCap // using gl::GL_MAP2_TEXTURE_COORD_1; // reuse EnableCap // using gl::GL_MAP2_TEXTURE_COORD_2; // reuse EnableCap // using gl::GL_MAP2_TEXTURE_COORD_3; // reuse EnableCap // using gl::GL_MAP2_TEXTURE_COORD_4; // reuse EnableCap // using gl::GL_MAP2_VERTEX_3; // reuse EnableCap // using gl::GL_MAP2_VERTEX_4; // reuse EnableCap using gl::GL_MAP1_GRID_DOMAIN; using gl::GL_MAP1_GRID_SEGMENTS; using gl::GL_MAP2_GRID_DOMAIN; using gl::GL_MAP2_GRID_SEGMENTS; // using gl::GL_TEXTURE_1D; // reuse EnableCap // using gl::GL_TEXTURE_2D; // reuse EnableCap using gl::GL_FEEDBACK_BUFFER_SIZE; using gl::GL_FEEDBACK_BUFFER_TYPE; using gl::GL_SELECTION_BUFFER_SIZE; using gl::GL_POLYGON_OFFSET_UNITS; // using gl::GL_POLYGON_OFFSET_POINT; // reuse EnableCap // using gl::GL_POLYGON_OFFSET_LINE; // reuse EnableCap // using gl::GL_CLIP_PLANE0; // reuse ClipPlaneName // using gl::GL_CLIP_PLANE1; // reuse ClipPlaneName // using gl::GL_CLIP_PLANE2; // reuse ClipPlaneName // using gl::GL_CLIP_PLANE3; // reuse ClipPlaneName // using gl::GL_CLIP_PLANE4; // reuse ClipPlaneName // using gl::GL_CLIP_PLANE5; // reuse ClipPlaneName // using gl::GL_LIGHT0; // reuse EnableCap // using gl::GL_LIGHT1; // reuse EnableCap // using gl::GL_LIGHT2; // reuse EnableCap // using gl::GL_LIGHT3; // reuse EnableCap // using gl::GL_LIGHT4; // reuse EnableCap // using gl::GL_LIGHT5; // reuse EnableCap // using gl::GL_LIGHT6; // reuse EnableCap // using gl::GL_LIGHT7; // reuse EnableCap // using gl::GL_POLYGON_OFFSET_FILL; // reuse EnableCap using gl::GL_POLYGON_OFFSET_FACTOR; using gl::GL_TEXTURE_BINDING_1D; using gl::GL_TEXTURE_BINDING_2D; using gl::GL_TEXTURE_BINDING_3D; // using gl::GL_VERTEX_ARRAY; // reuse EnableCap // using gl::GL_NORMAL_ARRAY; // reuse EnableCap // using gl::GL_COLOR_ARRAY; // reuse EnableCap // using gl::GL_INDEX_ARRAY; // reuse EnableCap // using gl::GL_TEXTURE_COORD_ARRAY; // reuse EnableCap // using gl::GL_EDGE_FLAG_ARRAY; // reuse EnableCap using gl::GL_VERTEX_ARRAY_SIZE; using gl::GL_VERTEX_ARRAY_TYPE; using gl::GL_VERTEX_ARRAY_STRIDE; using gl::GL_NORMAL_ARRAY_TYPE; using gl::GL_NORMAL_ARRAY_STRIDE; using gl::GL_COLOR_ARRAY_SIZE; using gl::GL_COLOR_ARRAY_TYPE; using gl::GL_COLOR_ARRAY_STRIDE; using gl::GL_INDEX_ARRAY_TYPE; using gl::GL_INDEX_ARRAY_STRIDE; using gl::GL_TEXTURE_COORD_ARRAY_SIZE; using gl::GL_TEXTURE_COORD_ARRAY_TYPE; using gl::GL_TEXTURE_COORD_ARRAY_STRIDE; using gl::GL_EDGE_FLAG_ARRAY_STRIDE; using gl::GL_LIGHT_MODEL_COLOR_CONTROL; using gl::GL_ALIASED_POINT_SIZE_RANGE; using gl::GL_ALIASED_LINE_WIDTH_RANGE; // GetPixelMap using gl::GL_PIXEL_MAP_I_TO_I; using gl::GL_PIXEL_MAP_S_TO_S; using gl::GL_PIXEL_MAP_I_TO_R; using gl::GL_PIXEL_MAP_I_TO_G; using gl::GL_PIXEL_MAP_I_TO_B; using gl::GL_PIXEL_MAP_I_TO_A; using gl::GL_PIXEL_MAP_R_TO_R; using gl::GL_PIXEL_MAP_G_TO_G; using gl::GL_PIXEL_MAP_B_TO_B; using gl::GL_PIXEL_MAP_A_TO_A; // GetPointervPName using gl::GL_FEEDBACK_BUFFER_POINTER; using gl::GL_SELECTION_BUFFER_POINTER; using gl::GL_VERTEX_ARRAY_POINTER; using gl::GL_NORMAL_ARRAY_POINTER; using gl::GL_COLOR_ARRAY_POINTER; using gl::GL_INDEX_ARRAY_POINTER; using gl::GL_TEXTURE_COORD_ARRAY_POINTER; using gl::GL_EDGE_FLAG_ARRAY_POINTER; // GetTextureParameter using gl::GL_TEXTURE_WIDTH; using gl::GL_TEXTURE_HEIGHT; using gl::GL_TEXTURE_COMPONENTS; using gl::GL_TEXTURE_INTERNAL_FORMAT; using gl::GL_TEXTURE_BORDER_COLOR; using gl::GL_TEXTURE_BORDER; using gl::GL_TEXTURE_MAG_FILTER; using gl::GL_TEXTURE_MIN_FILTER; using gl::GL_TEXTURE_WRAP_S; using gl::GL_TEXTURE_WRAP_T; using gl::GL_TEXTURE_RED_SIZE; using gl::GL_TEXTURE_GREEN_SIZE; using gl::GL_TEXTURE_BLUE_SIZE; using gl::GL_TEXTURE_ALPHA_SIZE; using gl::GL_TEXTURE_LUMINANCE_SIZE; using gl::GL_TEXTURE_INTENSITY_SIZE; using gl::GL_TEXTURE_PRIORITY; using gl::GL_TEXTURE_RESIDENT; // HintMode using gl::GL_DONT_CARE; using gl::GL_FASTEST; using gl::GL_NICEST; // HintTarget // using gl::GL_PERSPECTIVE_CORRECTION_HINT; // reuse GetPName // using gl::GL_POINT_SMOOTH_HINT; // reuse GetPName // using gl::GL_LINE_SMOOTH_HINT; // reuse GetPName // using gl::GL_POLYGON_SMOOTH_HINT; // reuse GetPName // using gl::GL_FOG_HINT; // reuse GetPName using gl::GL_GENERATE_MIPMAP_HINT; using gl::GL_TEXTURE_COMPRESSION_HINT; using gl::GL_FRAGMENT_SHADER_DERIVATIVE_HINT; // IndexPointerType // using gl::GL_SHORT; // reuse ColorPointerType // using gl::GL_INT; // reuse ColorPointerType // using gl::GL_FLOAT; // reuse ColorPointerType // using gl::GL_DOUBLE; // reuse ColorPointerType // InterleavedArrayFormat using gl::GL_V2F; using gl::GL_V3F; using gl::GL_C4UB_V2F; using gl::GL_C4UB_V3F; using gl::GL_C3F_V3F; using gl::GL_N3F_V3F; using gl::GL_C4F_N3F_V3F; using gl::GL_T2F_V3F; using gl::GL_T4F_V4F; using gl::GL_T2F_C4UB_V3F; using gl::GL_T2F_C3F_V3F; using gl::GL_T2F_N3F_V3F; using gl::GL_T2F_C4F_N3F_V3F; using gl::GL_T4F_C4F_N3F_V4F; // InternalFormat using gl::GL_R3_G3_B2; using gl::GL_ALPHA4; using gl::GL_ALPHA8; using gl::GL_ALPHA12; using gl::GL_ALPHA16; using gl::GL_LUMINANCE4; using gl::GL_LUMINANCE8; using gl::GL_LUMINANCE12; using gl::GL_LUMINANCE16; using gl::GL_LUMINANCE4_ALPHA4; using gl::GL_LUMINANCE6_ALPHA2; using gl::GL_LUMINANCE8_ALPHA8; using gl::GL_LUMINANCE12_ALPHA4; using gl::GL_LUMINANCE12_ALPHA12; using gl::GL_LUMINANCE16_ALPHA16; using gl::GL_INTENSITY; using gl::GL_INTENSITY4; using gl::GL_INTENSITY8; using gl::GL_INTENSITY12; using gl::GL_INTENSITY16; using gl::GL_RGB4; using gl::GL_RGB5; using gl::GL_RGB8; using gl::GL_RGB10; using gl::GL_RGB12; using gl::GL_RGB16; using gl::GL_RGBA2; using gl::GL_RGBA4; using gl::GL_RGB5_A1; using gl::GL_RGBA8; using gl::GL_RGB10_A2; using gl::GL_RGBA12; using gl::GL_RGBA16; // LightEnvModeSGIX // using gl::GL_ADD; // reuse AccumOp using gl::GL_REPLACE; using gl::GL_MODULATE; // LightModelColorControl using gl::GL_SINGLE_COLOR; using gl::GL_SEPARATE_SPECULAR_COLOR; // LightModelParameter // using gl::GL_LIGHT_MODEL_LOCAL_VIEWER; // reuse GetPName // using gl::GL_LIGHT_MODEL_TWO_SIDE; // reuse GetPName // using gl::GL_LIGHT_MODEL_AMBIENT; // reuse GetPName // using gl::GL_LIGHT_MODEL_COLOR_CONTROL; // reuse GetPName // LightName // using gl::GL_LIGHT0; // reuse EnableCap // using gl::GL_LIGHT1; // reuse EnableCap // using gl::GL_LIGHT2; // reuse EnableCap // using gl::GL_LIGHT3; // reuse EnableCap // using gl::GL_LIGHT4; // reuse EnableCap // using gl::GL_LIGHT5; // reuse EnableCap // using gl::GL_LIGHT6; // reuse EnableCap // using gl::GL_LIGHT7; // reuse EnableCap // LightParameter // using gl::GL_AMBIENT; // reuse ColorMaterialParameter // using gl::GL_DIFFUSE; // reuse ColorMaterialParameter // using gl::GL_SPECULAR; // reuse ColorMaterialParameter using gl::GL_POSITION; using gl::GL_SPOT_DIRECTION; using gl::GL_SPOT_EXPONENT; using gl::GL_SPOT_CUTOFF; using gl::GL_CONSTANT_ATTENUATION; using gl::GL_LINEAR_ATTENUATION; using gl::GL_QUADRATIC_ATTENUATION; // ListMode using gl::GL_COMPILE; using gl::GL_COMPILE_AND_EXECUTE; // ListNameType // using gl::GL_BYTE; // reuse ColorPointerType // using gl::GL_UNSIGNED_BYTE; // reuse ColorPointerType // using gl::GL_SHORT; // reuse ColorPointerType // using gl::GL_UNSIGNED_SHORT; // reuse ColorPointerType // using gl::GL_INT; // reuse ColorPointerType // using gl::GL_UNSIGNED_INT; // reuse ColorPointerType // using gl::GL_FLOAT; // reuse ColorPointerType using gl::GL_2_BYTES; using gl::GL_3_BYTES; using gl::GL_4_BYTES; // LogicOp using gl::GL_CLEAR; using gl::GL_AND; using gl::GL_AND_REVERSE; using gl::GL_COPY; using gl::GL_AND_INVERTED; using gl::GL_NOOP; using gl::GL_XOR; using gl::GL_OR; using gl::GL_NOR; using gl::GL_EQUIV; using gl::GL_INVERT; using gl::GL_OR_REVERSE; using gl::GL_COPY_INVERTED; using gl::GL_OR_INVERTED; using gl::GL_NAND; using gl::GL_SET; // MapTarget // using gl::GL_MAP1_COLOR_4; // reuse EnableCap // using gl::GL_MAP1_INDEX; // reuse EnableCap // using gl::GL_MAP1_NORMAL; // reuse EnableCap // using gl::GL_MAP1_TEXTURE_COORD_1; // reuse EnableCap // using gl::GL_MAP1_TEXTURE_COORD_2; // reuse EnableCap // using gl::GL_MAP1_TEXTURE_COORD_3; // reuse EnableCap // using gl::GL_MAP1_TEXTURE_COORD_4; // reuse EnableCap // using gl::GL_MAP1_VERTEX_3; // reuse EnableCap // using gl::GL_MAP1_VERTEX_4; // reuse EnableCap // using gl::GL_MAP2_COLOR_4; // reuse EnableCap // using gl::GL_MAP2_INDEX; // reuse EnableCap // using gl::GL_MAP2_NORMAL; // reuse EnableCap // using gl::GL_MAP2_TEXTURE_COORD_1; // reuse EnableCap // using gl::GL_MAP2_TEXTURE_COORD_2; // reuse EnableCap // using gl::GL_MAP2_TEXTURE_COORD_3; // reuse EnableCap // using gl::GL_MAP2_TEXTURE_COORD_4; // reuse EnableCap // using gl::GL_MAP2_VERTEX_3; // reuse EnableCap // using gl::GL_MAP2_VERTEX_4; // reuse EnableCap // MaterialFace // using gl::GL_FRONT; // reuse ColorMaterialFace // using gl::GL_BACK; // reuse ColorMaterialFace // using gl::GL_FRONT_AND_BACK; // reuse ColorMaterialFace // MaterialParameter // using gl::GL_AMBIENT; // reuse ColorMaterialParameter // using gl::GL_DIFFUSE; // reuse ColorMaterialParameter // using gl::GL_SPECULAR; // reuse ColorMaterialParameter // using gl::GL_EMISSION; // reuse ColorMaterialParameter using gl::GL_SHININESS; // using gl::GL_AMBIENT_AND_DIFFUSE; // reuse ColorMaterialParameter using gl::GL_COLOR_INDEXES; // MatrixMode using gl::GL_MODELVIEW; using gl::GL_PROJECTION; using gl::GL_TEXTURE; // MeshMode1 using gl::GL_POINT; using gl::GL_LINE; // MeshMode2 // using gl::GL_POINT; // reuse MeshMode1 // using gl::GL_LINE; // reuse MeshMode1 using gl::GL_FILL; // NormalPointerType // using gl::GL_BYTE; // reuse ColorPointerType // using gl::GL_SHORT; // reuse ColorPointerType // using gl::GL_INT; // reuse ColorPointerType // using gl::GL_FLOAT; // reuse ColorPointerType // using gl::GL_DOUBLE; // reuse ColorPointerType // PixelCopyType using gl::GL_COLOR; using gl::GL_DEPTH; using gl::GL_STENCIL; // PixelFormat // using gl::GL_UNSIGNED_SHORT; // reuse ColorPointerType // using gl::GL_UNSIGNED_INT; // reuse ColorPointerType using gl::GL_COLOR_INDEX; using gl::GL_STENCIL_INDEX; using gl::GL_DEPTH_COMPONENT; using gl::GL_RED; using gl::GL_GREEN; using gl::GL_BLUE; using gl::GL_ALPHA; using gl::GL_RGB; using gl::GL_RGBA; using gl::GL_LUMINANCE; using gl::GL_LUMINANCE_ALPHA; // PixelMap // using gl::GL_PIXEL_MAP_I_TO_I; // reuse GetPixelMap // using gl::GL_PIXEL_MAP_S_TO_S; // reuse GetPixelMap // using gl::GL_PIXEL_MAP_I_TO_R; // reuse GetPixelMap // using gl::GL_PIXEL_MAP_I_TO_G; // reuse GetPixelMap // using gl::GL_PIXEL_MAP_I_TO_B; // reuse GetPixelMap // using gl::GL_PIXEL_MAP_I_TO_A; // reuse GetPixelMap // using gl::GL_PIXEL_MAP_R_TO_R; // reuse GetPixelMap // using gl::GL_PIXEL_MAP_G_TO_G; // reuse GetPixelMap // using gl::GL_PIXEL_MAP_B_TO_B; // reuse GetPixelMap // using gl::GL_PIXEL_MAP_A_TO_A; // reuse GetPixelMap // PixelStoreParameter // using gl::GL_UNPACK_SWAP_BYTES; // reuse GetPName // using gl::GL_UNPACK_LSB_FIRST; // reuse GetPName // using gl::GL_UNPACK_ROW_LENGTH; // reuse GetPName // using gl::GL_UNPACK_SKIP_ROWS; // reuse GetPName // using gl::GL_UNPACK_SKIP_PIXELS; // reuse GetPName // using gl::GL_UNPACK_ALIGNMENT; // reuse GetPName // using gl::GL_PACK_SWAP_BYTES; // reuse GetPName // using gl::GL_PACK_LSB_FIRST; // reuse GetPName // using gl::GL_PACK_ROW_LENGTH; // reuse GetPName // using gl::GL_PACK_SKIP_ROWS; // reuse GetPName // using gl::GL_PACK_SKIP_PIXELS; // reuse GetPName // using gl::GL_PACK_ALIGNMENT; // reuse GetPName using gl::GL_PACK_SKIP_IMAGES; using gl::GL_PACK_IMAGE_HEIGHT; using gl::GL_UNPACK_SKIP_IMAGES; using gl::GL_UNPACK_IMAGE_HEIGHT; // PixelTexGenMode // using gl::GL_NONE; // reuse DrawBufferMode // using gl::GL_RGB; // reuse PixelFormat // using gl::GL_RGBA; // reuse PixelFormat // using gl::GL_LUMINANCE; // reuse PixelFormat // using gl::GL_LUMINANCE_ALPHA; // reuse PixelFormat // PixelTransferParameter // using gl::GL_MAP_COLOR; // reuse GetPName // using gl::GL_MAP_STENCIL; // reuse GetPName // using gl::GL_INDEX_SHIFT; // reuse GetPName // using gl::GL_INDEX_OFFSET; // reuse GetPName // using gl::GL_RED_SCALE; // reuse GetPName // using gl::GL_RED_BIAS; // reuse GetPName // using gl::GL_GREEN_SCALE; // reuse GetPName // using gl::GL_GREEN_BIAS; // reuse GetPName // using gl::GL_BLUE_SCALE; // reuse GetPName // using gl::GL_BLUE_BIAS; // reuse GetPName // using gl::GL_ALPHA_SCALE; // reuse GetPName // using gl::GL_ALPHA_BIAS; // reuse GetPName // using gl::GL_DEPTH_SCALE; // reuse GetPName // using gl::GL_DEPTH_BIAS; // reuse GetPName // PixelType // using gl::GL_BYTE; // reuse ColorPointerType // using gl::GL_UNSIGNED_BYTE; // reuse ColorPointerType // using gl::GL_SHORT; // reuse ColorPointerType // using gl::GL_UNSIGNED_SHORT; // reuse ColorPointerType // using gl::GL_INT; // reuse ColorPointerType // using gl::GL_UNSIGNED_INT; // reuse ColorPointerType // using gl::GL_FLOAT; // reuse ColorPointerType using gl::GL_BITMAP; using gl::GL_UNSIGNED_BYTE_3_3_2; using gl::GL_UNSIGNED_SHORT_4_4_4_4; using gl::GL_UNSIGNED_SHORT_5_5_5_1; using gl::GL_UNSIGNED_INT_8_8_8_8; using gl::GL_UNSIGNED_INT_10_10_10_2; // PointParameterNameSGIS using gl::GL_POINT_SIZE_MIN; using gl::GL_POINT_SIZE_MAX; using gl::GL_POINT_FADE_THRESHOLD_SIZE; using gl::GL_POINT_DISTANCE_ATTENUATION; // PolygonMode // using gl::GL_POINT; // reuse MeshMode1 // using gl::GL_LINE; // reuse MeshMode1 // using gl::GL_FILL; // reuse MeshMode2 // PrimitiveType using gl::GL_POINTS; using gl::GL_LINES; using gl::GL_LINE_LOOP; using gl::GL_LINE_STRIP; using gl::GL_TRIANGLES; using gl::GL_TRIANGLE_STRIP; using gl::GL_TRIANGLE_FAN; using gl::GL_QUADS; using gl::GL_QUAD_STRIP; using gl::GL_POLYGON; // ReadBufferMode // using gl::GL_FRONT_LEFT; // reuse DrawBufferMode // using gl::GL_FRONT_RIGHT; // reuse DrawBufferMode // using gl::GL_BACK_LEFT; // reuse DrawBufferMode // using gl::GL_BACK_RIGHT; // reuse DrawBufferMode // using gl::GL_FRONT; // reuse ColorMaterialFace // using gl::GL_BACK; // reuse ColorMaterialFace // using gl::GL_LEFT; // reuse DrawBufferMode // using gl::GL_RIGHT; // reuse DrawBufferMode // using gl::GL_AUX0; // reuse DrawBufferMode // using gl::GL_AUX1; // reuse DrawBufferMode // using gl::GL_AUX2; // reuse DrawBufferMode // using gl::GL_AUX3; // reuse DrawBufferMode // RenderingMode using gl::GL_RENDER; using gl::GL_FEEDBACK; using gl::GL_SELECT; // ShadingModel using gl::GL_FLAT; using gl::GL_SMOOTH; // StencilFunction // using gl::GL_NEVER; // reuse AlphaFunction // using gl::GL_LESS; // reuse AlphaFunction // using gl::GL_EQUAL; // reuse AlphaFunction // using gl::GL_LEQUAL; // reuse AlphaFunction // using gl::GL_GREATER; // reuse AlphaFunction // using gl::GL_NOTEQUAL; // reuse AlphaFunction // using gl::GL_GEQUAL; // reuse AlphaFunction // using gl::GL_ALWAYS; // reuse AlphaFunction // StencilOp // using gl::GL_ZERO; // reuse BlendingFactorDest // using gl::GL_INVERT; // reuse LogicOp using gl::GL_KEEP; // using gl::GL_REPLACE; // reuse LightEnvModeSGIX using gl::GL_INCR; using gl::GL_DECR; // StringName using gl::GL_VENDOR; using gl::GL_RENDERER; using gl::GL_VERSION; using gl::GL_EXTENSIONS; // TexCoordPointerType // using gl::GL_SHORT; // reuse ColorPointerType // using gl::GL_INT; // reuse ColorPointerType // using gl::GL_FLOAT; // reuse ColorPointerType // using gl::GL_DOUBLE; // reuse ColorPointerType // TextureCoordName using gl::GL_S; using gl::GL_T; using gl::GL_R; using gl::GL_Q; // TextureEnvMode // using gl::GL_ADD; // reuse AccumOp // using gl::GL_BLEND; // reuse EnableCap // using gl::GL_MODULATE; // reuse LightEnvModeSGIX using gl::GL_DECAL; // TextureEnvParameter using gl::GL_TEXTURE_ENV_MODE; using gl::GL_TEXTURE_ENV_COLOR; // TextureEnvTarget using gl::GL_TEXTURE_ENV; // TextureGenMode using gl::GL_EYE_LINEAR; using gl::GL_OBJECT_LINEAR; using gl::GL_SPHERE_MAP; // TextureGenParameter using gl::GL_TEXTURE_GEN_MODE; using gl::GL_OBJECT_PLANE; using gl::GL_EYE_PLANE; // TextureMagFilter using gl::GL_NEAREST; // using gl::GL_LINEAR; // reuse FogMode // TextureMinFilter // using gl::GL_NEAREST; // reuse TextureMagFilter // using gl::GL_LINEAR; // reuse FogMode using gl::GL_NEAREST_MIPMAP_NEAREST; using gl::GL_LINEAR_MIPMAP_NEAREST; using gl::GL_NEAREST_MIPMAP_LINEAR; using gl::GL_LINEAR_MIPMAP_LINEAR; // TextureParameterName // using gl::GL_TEXTURE_BORDER_COLOR; // reuse GetTextureParameter // using gl::GL_TEXTURE_MAG_FILTER; // reuse GetTextureParameter // using gl::GL_TEXTURE_MIN_FILTER; // reuse GetTextureParameter // using gl::GL_TEXTURE_WRAP_S; // reuse GetTextureParameter // using gl::GL_TEXTURE_WRAP_T; // reuse GetTextureParameter // using gl::GL_TEXTURE_PRIORITY; // reuse GetTextureParameter using gl::GL_TEXTURE_WRAP_R; using gl::GL_GENERATE_MIPMAP; // TextureTarget // using gl::GL_TEXTURE_1D; // reuse EnableCap // using gl::GL_TEXTURE_2D; // reuse EnableCap using gl::GL_PROXY_TEXTURE_1D; using gl::GL_PROXY_TEXTURE_2D; using gl::GL_TEXTURE_3D; using gl::GL_PROXY_TEXTURE_3D; using gl::GL_TEXTURE_MIN_LOD; using gl::GL_TEXTURE_MAX_LOD; using gl::GL_TEXTURE_BASE_LEVEL; using gl::GL_TEXTURE_MAX_LEVEL; // TextureWrapMode using gl::GL_CLAMP; using gl::GL_REPEAT; using gl::GL_CLAMP_TO_BORDER; using gl::GL_CLAMP_TO_EDGE; // VertexPointerType // using gl::GL_SHORT; // reuse ColorPointerType // using gl::GL_INT; // reuse ColorPointerType // using gl::GL_FLOAT; // reuse ColorPointerType // using gl::GL_DOUBLE; // reuse ColorPointerType // __UNGROUPED__ using gl::GL_HALF_FLOAT; using gl::GL_CONSTANT_COLOR; using gl::GL_ONE_MINUS_CONSTANT_COLOR; using gl::GL_CONSTANT_ALPHA; using gl::GL_ONE_MINUS_CONSTANT_ALPHA; using gl::GL_FUNC_ADD; using gl::GL_MIN; using gl::GL_MAX; using gl::GL_BLEND_EQUATION_RGB; using gl::GL_FUNC_SUBTRACT; using gl::GL_FUNC_REVERSE_SUBTRACT; using gl::GL_RESCALE_NORMAL; using gl::GL_TEXTURE_DEPTH; using gl::GL_MAX_3D_TEXTURE_SIZE; using gl::GL_MULTISAMPLE; using gl::GL_SAMPLE_ALPHA_TO_COVERAGE; using gl::GL_SAMPLE_ALPHA_TO_ONE; using gl::GL_SAMPLE_COVERAGE; using gl::GL_SAMPLE_BUFFERS; using gl::GL_SAMPLES; using gl::GL_SAMPLE_COVERAGE_VALUE; using gl::GL_SAMPLE_COVERAGE_INVERT; using gl::GL_BLEND_DST_RGB; using gl::GL_BLEND_SRC_RGB; using gl::GL_BLEND_DST_ALPHA; using gl::GL_BLEND_SRC_ALPHA; using gl::GL_BGR; using gl::GL_BGRA; using gl::GL_MAX_ELEMENTS_VERTICES; using gl::GL_MAX_ELEMENTS_INDICES; using gl::GL_DEPTH_COMPONENT16; using gl::GL_DEPTH_COMPONENT24; using gl::GL_DEPTH_COMPONENT32; using gl::GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING; using gl::GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE; using gl::GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE; using gl::GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE; using gl::GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE; using gl::GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE; using gl::GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE; using gl::GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE; using gl::GL_FRAMEBUFFER_DEFAULT; using gl::GL_FRAMEBUFFER_UNDEFINED; using gl::GL_DEPTH_STENCIL_ATTACHMENT; using gl::GL_MAJOR_VERSION; using gl::GL_MINOR_VERSION; using gl::GL_NUM_EXTENSIONS; using gl::GL_CONTEXT_FLAGS; using gl::GL_INDEX; using gl::GL_COMPRESSED_RED; using gl::GL_COMPRESSED_RG; using gl::GL_RG; using gl::GL_RG_INTEGER; using gl::GL_R8; using gl::GL_R16; using gl::GL_RG8; using gl::GL_RG16; using gl::GL_R16F; using gl::GL_R32F; using gl::GL_RG16F; using gl::GL_RG32F; using gl::GL_R8I; using gl::GL_R8UI; using gl::GL_R16I; using gl::GL_R16UI; using gl::GL_R32I; using gl::GL_R32UI; using gl::GL_RG8I; using gl::GL_RG8UI; using gl::GL_RG16I; using gl::GL_RG16UI; using gl::GL_RG32I; using gl::GL_RG32UI; using gl::GL_UNSIGNED_BYTE_2_3_3_REV; using gl::GL_UNSIGNED_SHORT_5_6_5; using gl::GL_UNSIGNED_SHORT_5_6_5_REV; using gl::GL_UNSIGNED_SHORT_4_4_4_4_REV; using gl::GL_UNSIGNED_SHORT_1_5_5_5_REV; using gl::GL_UNSIGNED_INT_8_8_8_8_REV; using gl::GL_UNSIGNED_INT_2_10_10_10_REV; using gl::GL_MIRRORED_REPEAT; using gl::GL_FOG_COORDINATE_SOURCE; using gl::GL_FOG_COORD_SRC; using gl::GL_FOG_COORD; using gl::GL_FOG_COORDINATE; using gl::GL_FRAGMENT_DEPTH; using gl::GL_CURRENT_FOG_COORD; using gl::GL_CURRENT_FOG_COORDINATE; using gl::GL_FOG_COORDINATE_ARRAY_TYPE; using gl::GL_FOG_COORD_ARRAY_TYPE; using gl::GL_FOG_COORDINATE_ARRAY_STRIDE; using gl::GL_FOG_COORD_ARRAY_STRIDE; using gl::GL_FOG_COORDINATE_ARRAY_POINTER; using gl::GL_FOG_COORD_ARRAY_POINTER; using gl::GL_FOG_COORDINATE_ARRAY; using gl::GL_FOG_COORD_ARRAY; using gl::GL_COLOR_SUM; using gl::GL_CURRENT_SECONDARY_COLOR; using gl::GL_SECONDARY_COLOR_ARRAY_SIZE; using gl::GL_SECONDARY_COLOR_ARRAY_TYPE; using gl::GL_SECONDARY_COLOR_ARRAY_STRIDE; using gl::GL_SECONDARY_COLOR_ARRAY_POINTER; using gl::GL_SECONDARY_COLOR_ARRAY; using gl::GL_CURRENT_RASTER_SECONDARY_COLOR; using gl::GL_TEXTURE0; using gl::GL_TEXTURE1; using gl::GL_TEXTURE2; using gl::GL_TEXTURE3; using gl::GL_TEXTURE4; using gl::GL_TEXTURE5; using gl::GL_TEXTURE6; using gl::GL_TEXTURE7; using gl::GL_TEXTURE8; using gl::GL_TEXTURE9; using gl::GL_TEXTURE10; using gl::GL_TEXTURE11; using gl::GL_TEXTURE12; using gl::GL_TEXTURE13; using gl::GL_TEXTURE14; using gl::GL_TEXTURE15; using gl::GL_TEXTURE16; using gl::GL_TEXTURE17; using gl::GL_TEXTURE18; using gl::GL_TEXTURE19; using gl::GL_TEXTURE20; using gl::GL_TEXTURE21; using gl::GL_TEXTURE22; using gl::GL_TEXTURE23; using gl::GL_TEXTURE24; using gl::GL_TEXTURE25; using gl::GL_TEXTURE26; using gl::GL_TEXTURE27; using gl::GL_TEXTURE28; using gl::GL_TEXTURE29; using gl::GL_TEXTURE30; using gl::GL_TEXTURE31; using gl::GL_ACTIVE_TEXTURE; using gl::GL_CLIENT_ACTIVE_TEXTURE; using gl::GL_MAX_TEXTURE_UNITS; using gl::GL_TRANSPOSE_MODELVIEW_MATRIX; using gl::GL_TRANSPOSE_PROJECTION_MATRIX; using gl::GL_TRANSPOSE_TEXTURE_MATRIX; using gl::GL_TRANSPOSE_COLOR_MATRIX; using gl::GL_SUBTRACT; using gl::GL_MAX_RENDERBUFFER_SIZE; using gl::GL_COMPRESSED_ALPHA; using gl::GL_COMPRESSED_LUMINANCE; using gl::GL_COMPRESSED_LUMINANCE_ALPHA; using gl::GL_COMPRESSED_INTENSITY; using gl::GL_COMPRESSED_RGB; using gl::GL_COMPRESSED_RGBA; using gl::GL_TEXTURE_RECTANGLE; using gl::GL_TEXTURE_BINDING_RECTANGLE; using gl::GL_PROXY_TEXTURE_RECTANGLE; using gl::GL_MAX_RECTANGLE_TEXTURE_SIZE; using gl::GL_DEPTH_STENCIL; using gl::GL_UNSIGNED_INT_24_8; using gl::GL_MAX_TEXTURE_LOD_BIAS; using gl::GL_TEXTURE_FILTER_CONTROL; using gl::GL_TEXTURE_LOD_BIAS; using gl::GL_INCR_WRAP; using gl::GL_DECR_WRAP; using gl::GL_NORMAL_MAP; using gl::GL_REFLECTION_MAP; using gl::GL_TEXTURE_CUBE_MAP; using gl::GL_TEXTURE_BINDING_CUBE_MAP; using gl::GL_TEXTURE_CUBE_MAP_POSITIVE_X; using gl::GL_TEXTURE_CUBE_MAP_NEGATIVE_X; using gl::GL_TEXTURE_CUBE_MAP_POSITIVE_Y; using gl::GL_TEXTURE_CUBE_MAP_NEGATIVE_Y; using gl::GL_TEXTURE_CUBE_MAP_POSITIVE_Z; using gl::GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; using gl::GL_PROXY_TEXTURE_CUBE_MAP; using gl::GL_MAX_CUBE_MAP_TEXTURE_SIZE; using gl::GL_COMBINE; using gl::GL_COMBINE_RGB; using gl::GL_COMBINE_ALPHA; using gl::GL_RGB_SCALE; using gl::GL_ADD_SIGNED; using gl::GL_INTERPOLATE; using gl::GL_CONSTANT; using gl::GL_PRIMARY_COLOR; using gl::GL_PREVIOUS; using gl::GL_SOURCE0_RGB; using gl::GL_SRC0_RGB; using gl::GL_SOURCE1_RGB; using gl::GL_SRC1_RGB; using gl::GL_SOURCE2_RGB; using gl::GL_SRC2_RGB; using gl::GL_SOURCE0_ALPHA; using gl::GL_SRC0_ALPHA; using gl::GL_SOURCE1_ALPHA; using gl::GL_SRC1_ALPHA; using gl::GL_SOURCE2_ALPHA; using gl::GL_SRC2_ALPHA; using gl::GL_OPERAND0_RGB; using gl::GL_OPERAND1_RGB; using gl::GL_OPERAND2_RGB; using gl::GL_OPERAND0_ALPHA; using gl::GL_OPERAND1_ALPHA; using gl::GL_OPERAND2_ALPHA; using gl::GL_VERTEX_ARRAY_BINDING; using gl::GL_VERTEX_ATTRIB_ARRAY_ENABLED; using gl::GL_VERTEX_ATTRIB_ARRAY_SIZE; using gl::GL_VERTEX_ATTRIB_ARRAY_STRIDE; using gl::GL_VERTEX_ATTRIB_ARRAY_TYPE; using gl::GL_CURRENT_VERTEX_ATTRIB; using gl::GL_PROGRAM_POINT_SIZE; using gl::GL_VERTEX_PROGRAM_POINT_SIZE; using gl::GL_VERTEX_PROGRAM_TWO_SIDE; using gl::GL_VERTEX_ATTRIB_ARRAY_POINTER; using gl::GL_TEXTURE_COMPRESSED_IMAGE_SIZE; using gl::GL_TEXTURE_COMPRESSED; using gl::GL_NUM_COMPRESSED_TEXTURE_FORMATS; using gl::GL_COMPRESSED_TEXTURE_FORMATS; using gl::GL_DOT3_RGB; using gl::GL_DOT3_RGBA; using gl::GL_BUFFER_SIZE; using gl::GL_BUFFER_USAGE; using gl::GL_STENCIL_BACK_FUNC; using gl::GL_STENCIL_BACK_FAIL; using gl::GL_STENCIL_BACK_PASS_DEPTH_FAIL; using gl::GL_STENCIL_BACK_PASS_DEPTH_PASS; using gl::GL_RGBA32F; using gl::GL_RGB32F; using gl::GL_RGBA16F; using gl::GL_RGB16F; using gl::GL_MAX_DRAW_BUFFERS; using gl::GL_DRAW_BUFFER0; using gl::GL_DRAW_BUFFER1; using gl::GL_DRAW_BUFFER2; using gl::GL_DRAW_BUFFER3; using gl::GL_DRAW_BUFFER4; using gl::GL_DRAW_BUFFER5; using gl::GL_DRAW_BUFFER6; using gl::GL_DRAW_BUFFER7; using gl::GL_DRAW_BUFFER8; using gl::GL_DRAW_BUFFER9; using gl::GL_DRAW_BUFFER10; using gl::GL_DRAW_BUFFER11; using gl::GL_DRAW_BUFFER12; using gl::GL_DRAW_BUFFER13; using gl::GL_DRAW_BUFFER14; using gl::GL_DRAW_BUFFER15; using gl::GL_BLEND_EQUATION_ALPHA; using gl::GL_TEXTURE_DEPTH_SIZE; using gl::GL_DEPTH_TEXTURE_MODE; using gl::GL_TEXTURE_COMPARE_MODE; using gl::GL_TEXTURE_COMPARE_FUNC; using gl::GL_COMPARE_REF_TO_TEXTURE; using gl::GL_COMPARE_R_TO_TEXTURE; using gl::GL_POINT_SPRITE; using gl::GL_COORD_REPLACE; using gl::GL_QUERY_COUNTER_BITS; using gl::GL_CURRENT_QUERY; using gl::GL_QUERY_RESULT; using gl::GL_QUERY_RESULT_AVAILABLE; using gl::GL_MAX_VERTEX_ATTRIBS; using gl::GL_VERTEX_ATTRIB_ARRAY_NORMALIZED; using gl::GL_MAX_TEXTURE_COORDS; using gl::GL_MAX_TEXTURE_IMAGE_UNITS; using gl::GL_ARRAY_BUFFER; using gl::GL_ELEMENT_ARRAY_BUFFER; using gl::GL_ARRAY_BUFFER_BINDING; using gl::GL_ELEMENT_ARRAY_BUFFER_BINDING; using gl::GL_VERTEX_ARRAY_BUFFER_BINDING; using gl::GL_NORMAL_ARRAY_BUFFER_BINDING; using gl::GL_COLOR_ARRAY_BUFFER_BINDING; using gl::GL_INDEX_ARRAY_BUFFER_BINDING; using gl::GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING; using gl::GL_EDGE_FLAG_ARRAY_BUFFER_BINDING; using gl::GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING; using gl::GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING; using gl::GL_FOG_COORD_ARRAY_BUFFER_BINDING; using gl::GL_WEIGHT_ARRAY_BUFFER_BINDING; using gl::GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING; using gl::GL_READ_ONLY; using gl::GL_WRITE_ONLY; using gl::GL_READ_WRITE; using gl::GL_BUFFER_ACCESS; using gl::GL_BUFFER_MAPPED; using gl::GL_BUFFER_MAP_POINTER; using gl::GL_STREAM_DRAW; using gl::GL_STREAM_READ; using gl::GL_STREAM_COPY; using gl::GL_STATIC_DRAW; using gl::GL_STATIC_READ; using gl::GL_STATIC_COPY; using gl::GL_DYNAMIC_DRAW; using gl::GL_DYNAMIC_READ; using gl::GL_DYNAMIC_COPY; using gl::GL_PIXEL_PACK_BUFFER; using gl::GL_PIXEL_UNPACK_BUFFER; using gl::GL_PIXEL_PACK_BUFFER_BINDING; using gl::GL_PIXEL_UNPACK_BUFFER_BINDING; using gl::GL_DEPTH24_STENCIL8; using gl::GL_TEXTURE_STENCIL_SIZE; using gl::GL_VERTEX_ATTRIB_ARRAY_INTEGER; using gl::GL_MAX_ARRAY_TEXTURE_LAYERS; using gl::GL_MIN_PROGRAM_TEXEL_OFFSET; using gl::GL_MAX_PROGRAM_TEXEL_OFFSET; using gl::GL_SAMPLES_PASSED; using gl::GL_CLAMP_VERTEX_COLOR; using gl::GL_CLAMP_FRAGMENT_COLOR; using gl::GL_CLAMP_READ_COLOR; using gl::GL_FIXED_ONLY; using gl::GL_UNIFORM_BUFFER; using gl::GL_UNIFORM_BUFFER_BINDING; using gl::GL_UNIFORM_BUFFER_START; using gl::GL_UNIFORM_BUFFER_SIZE; using gl::GL_MAX_VERTEX_UNIFORM_BLOCKS; using gl::GL_MAX_GEOMETRY_UNIFORM_BLOCKS; using gl::GL_MAX_FRAGMENT_UNIFORM_BLOCKS; using gl::GL_MAX_COMBINED_UNIFORM_BLOCKS; using gl::GL_MAX_UNIFORM_BUFFER_BINDINGS; using gl::GL_MAX_UNIFORM_BLOCK_SIZE; using gl::GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS; using gl::GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS; using gl::GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS; using gl::GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT; using gl::GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH; using gl::GL_ACTIVE_UNIFORM_BLOCKS; using gl::GL_UNIFORM_TYPE; using gl::GL_UNIFORM_SIZE; using gl::GL_UNIFORM_NAME_LENGTH; using gl::GL_UNIFORM_BLOCK_INDEX; using gl::GL_UNIFORM_OFFSET; using gl::GL_UNIFORM_ARRAY_STRIDE; using gl::GL_UNIFORM_MATRIX_STRIDE; using gl::GL_UNIFORM_IS_ROW_MAJOR; using gl::GL_UNIFORM_BLOCK_BINDING; using gl::GL_UNIFORM_BLOCK_DATA_SIZE; using gl::GL_UNIFORM_BLOCK_NAME_LENGTH; using gl::GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS; using gl::GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES; using gl::GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER; using gl::GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER; using gl::GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER; using gl::GL_FRAGMENT_SHADER; using gl::GL_VERTEX_SHADER; using gl::GL_MAX_FRAGMENT_UNIFORM_COMPONENTS; using gl::GL_MAX_VERTEX_UNIFORM_COMPONENTS; using gl::GL_MAX_VARYING_COMPONENTS; using gl::GL_MAX_VARYING_FLOATS; using gl::GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS; using gl::GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS; using gl::GL_SHADER_TYPE; using gl::GL_FLOAT_VEC2; using gl::GL_FLOAT_VEC3; using gl::GL_FLOAT_VEC4; using gl::GL_INT_VEC2; using gl::GL_INT_VEC3; using gl::GL_INT_VEC4; using gl::GL_BOOL; using gl::GL_BOOL_VEC2; using gl::GL_BOOL_VEC3; using gl::GL_BOOL_VEC4; using gl::GL_FLOAT_MAT2; using gl::GL_FLOAT_MAT3; using gl::GL_FLOAT_MAT4; using gl::GL_SAMPLER_1D; using gl::GL_SAMPLER_2D; using gl::GL_SAMPLER_3D; using gl::GL_SAMPLER_CUBE; using gl::GL_SAMPLER_1D_SHADOW; using gl::GL_SAMPLER_2D_SHADOW; using gl::GL_SAMPLER_2D_RECT; using gl::GL_SAMPLER_2D_RECT_SHADOW; using gl::GL_FLOAT_MAT2x3; using gl::GL_FLOAT_MAT2x4; using gl::GL_FLOAT_MAT3x2; using gl::GL_FLOAT_MAT3x4; using gl::GL_FLOAT_MAT4x2; using gl::GL_FLOAT_MAT4x3; using gl::GL_DELETE_STATUS; using gl::GL_COMPILE_STATUS; using gl::GL_LINK_STATUS; using gl::GL_VALIDATE_STATUS; using gl::GL_INFO_LOG_LENGTH; using gl::GL_ATTACHED_SHADERS; using gl::GL_ACTIVE_UNIFORMS; using gl::GL_ACTIVE_UNIFORM_MAX_LENGTH; using gl::GL_SHADER_SOURCE_LENGTH; using gl::GL_ACTIVE_ATTRIBUTES; using gl::GL_ACTIVE_ATTRIBUTE_MAX_LENGTH; using gl::GL_SHADING_LANGUAGE_VERSION; using gl::GL_ACTIVE_PROGRAM_EXT; using gl::GL_CURRENT_PROGRAM; using gl::GL_TEXTURE_RED_TYPE; using gl::GL_TEXTURE_GREEN_TYPE; using gl::GL_TEXTURE_BLUE_TYPE; using gl::GL_TEXTURE_ALPHA_TYPE; using gl::GL_TEXTURE_LUMINANCE_TYPE; using gl::GL_TEXTURE_INTENSITY_TYPE; using gl::GL_TEXTURE_DEPTH_TYPE; using gl::GL_UNSIGNED_NORMALIZED; using gl::GL_TEXTURE_1D_ARRAY; using gl::GL_PROXY_TEXTURE_1D_ARRAY; using gl::GL_TEXTURE_2D_ARRAY; using gl::GL_PROXY_TEXTURE_2D_ARRAY; using gl::GL_TEXTURE_BINDING_1D_ARRAY; using gl::GL_TEXTURE_BINDING_2D_ARRAY; using gl::GL_TEXTURE_BUFFER; using gl::GL_MAX_TEXTURE_BUFFER_SIZE; using gl::GL_TEXTURE_BINDING_BUFFER; using gl::GL_TEXTURE_BUFFER_DATA_STORE_BINDING; using gl::GL_R11F_G11F_B10F; using gl::GL_UNSIGNED_INT_10F_11F_11F_REV; using gl::GL_RGB9_E5; using gl::GL_UNSIGNED_INT_5_9_9_9_REV; using gl::GL_TEXTURE_SHARED_SIZE; using gl::GL_SRGB; using gl::GL_SRGB8; using gl::GL_SRGB_ALPHA; using gl::GL_SRGB8_ALPHA8; using gl::GL_SLUMINANCE_ALPHA; using gl::GL_SLUMINANCE8_ALPHA8; using gl::GL_SLUMINANCE; using gl::GL_SLUMINANCE8; using gl::GL_COMPRESSED_SRGB; using gl::GL_COMPRESSED_SRGB_ALPHA; using gl::GL_COMPRESSED_SLUMINANCE; using gl::GL_COMPRESSED_SLUMINANCE_ALPHA; using gl::GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH; using gl::GL_TRANSFORM_FEEDBACK_BUFFER_MODE; using gl::GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS; using gl::GL_TRANSFORM_FEEDBACK_VARYINGS; using gl::GL_TRANSFORM_FEEDBACK_BUFFER_START; using gl::GL_TRANSFORM_FEEDBACK_BUFFER_SIZE; using gl::GL_PRIMITIVES_GENERATED; using gl::GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN; using gl::GL_RASTERIZER_DISCARD; using gl::GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS; using gl::GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS; using gl::GL_INTERLEAVED_ATTRIBS; using gl::GL_SEPARATE_ATTRIBS; using gl::GL_TRANSFORM_FEEDBACK_BUFFER; using gl::GL_TRANSFORM_FEEDBACK_BUFFER_BINDING; using gl::GL_POINT_SPRITE_COORD_ORIGIN; using gl::GL_LOWER_LEFT; using gl::GL_UPPER_LEFT; using gl::GL_STENCIL_BACK_REF; using gl::GL_STENCIL_BACK_VALUE_MASK; using gl::GL_STENCIL_BACK_WRITEMASK; using gl::GL_DRAW_FRAMEBUFFER_BINDING; using gl::GL_FRAMEBUFFER_BINDING; using gl::GL_RENDERBUFFER_BINDING; using gl::GL_READ_FRAMEBUFFER; using gl::GL_DRAW_FRAMEBUFFER; using gl::GL_READ_FRAMEBUFFER_BINDING; using gl::GL_RENDERBUFFER_SAMPLES; using gl::GL_DEPTH_COMPONENT32F; using gl::GL_DEPTH32F_STENCIL8; using gl::GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE; using gl::GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME; using gl::GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL; using gl::GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE; using gl::GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER; using gl::GL_FRAMEBUFFER_COMPLETE; using gl::GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT; using gl::GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT; using gl::GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER; using gl::GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER; using gl::GL_FRAMEBUFFER_UNSUPPORTED; using gl::GL_MAX_COLOR_ATTACHMENTS; using gl::GL_COLOR_ATTACHMENT0; using gl::GL_COLOR_ATTACHMENT1; using gl::GL_COLOR_ATTACHMENT2; using gl::GL_COLOR_ATTACHMENT3; using gl::GL_COLOR_ATTACHMENT4; using gl::GL_COLOR_ATTACHMENT5; using gl::GL_COLOR_ATTACHMENT6; using gl::GL_COLOR_ATTACHMENT7; using gl::GL_COLOR_ATTACHMENT8; using gl::GL_COLOR_ATTACHMENT9; using gl::GL_COLOR_ATTACHMENT10; using gl::GL_COLOR_ATTACHMENT11; using gl::GL_COLOR_ATTACHMENT12; using gl::GL_COLOR_ATTACHMENT13; using gl::GL_COLOR_ATTACHMENT14; using gl::GL_COLOR_ATTACHMENT15; using gl::GL_COLOR_ATTACHMENT16; using gl::GL_COLOR_ATTACHMENT17; using gl::GL_COLOR_ATTACHMENT18; using gl::GL_COLOR_ATTACHMENT19; using gl::GL_COLOR_ATTACHMENT20; using gl::GL_COLOR_ATTACHMENT21; using gl::GL_COLOR_ATTACHMENT22; using gl::GL_COLOR_ATTACHMENT23; using gl::GL_COLOR_ATTACHMENT24; using gl::GL_COLOR_ATTACHMENT25; using gl::GL_COLOR_ATTACHMENT26; using gl::GL_COLOR_ATTACHMENT27; using gl::GL_COLOR_ATTACHMENT28; using gl::GL_COLOR_ATTACHMENT29; using gl::GL_COLOR_ATTACHMENT30; using gl::GL_COLOR_ATTACHMENT31; using gl::GL_DEPTH_ATTACHMENT; using gl::GL_STENCIL_ATTACHMENT; using gl::GL_FRAMEBUFFER; using gl::GL_RENDERBUFFER; using gl::GL_RENDERBUFFER_WIDTH; using gl::GL_RENDERBUFFER_HEIGHT; using gl::GL_RENDERBUFFER_INTERNAL_FORMAT; using gl::GL_STENCIL_INDEX1; using gl::GL_STENCIL_INDEX4; using gl::GL_STENCIL_INDEX8; using gl::GL_STENCIL_INDEX16; using gl::GL_RENDERBUFFER_RED_SIZE; using gl::GL_RENDERBUFFER_GREEN_SIZE; using gl::GL_RENDERBUFFER_BLUE_SIZE; using gl::GL_RENDERBUFFER_ALPHA_SIZE; using gl::GL_RENDERBUFFER_DEPTH_SIZE; using gl::GL_RENDERBUFFER_STENCIL_SIZE; using gl::GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE; using gl::GL_MAX_SAMPLES; using gl::GL_RGBA32UI; using gl::GL_RGB32UI; using gl::GL_RGBA16UI; using gl::GL_RGB16UI; using gl::GL_RGBA8UI; using gl::GL_RGB8UI; using gl::GL_RGBA32I; using gl::GL_RGB32I; using gl::GL_RGBA16I; using gl::GL_RGB16I; using gl::GL_RGBA8I; using gl::GL_RGB8I; using gl::GL_RED_INTEGER; using gl::GL_GREEN_INTEGER; using gl::GL_BLUE_INTEGER; using gl::GL_ALPHA_INTEGER; using gl::GL_RGB_INTEGER; using gl::GL_RGBA_INTEGER; using gl::GL_BGR_INTEGER; using gl::GL_BGRA_INTEGER; using gl::GL_FLOAT_32_UNSIGNED_INT_24_8_REV; using gl::GL_FRAMEBUFFER_SRGB; using gl::GL_COMPRESSED_RED_RGTC1; using gl::GL_COMPRESSED_SIGNED_RED_RGTC1; using gl::GL_COMPRESSED_RG_RGTC2; using gl::GL_COMPRESSED_SIGNED_RG_RGTC2; using gl::GL_SAMPLER_1D_ARRAY; using gl::GL_SAMPLER_2D_ARRAY; using gl::GL_SAMPLER_BUFFER; using gl::GL_SAMPLER_1D_ARRAY_SHADOW; using gl::GL_SAMPLER_2D_ARRAY_SHADOW; using gl::GL_SAMPLER_CUBE_SHADOW; using gl::GL_UNSIGNED_INT_VEC2; using gl::GL_UNSIGNED_INT_VEC3; using gl::GL_UNSIGNED_INT_VEC4; using gl::GL_INT_SAMPLER_1D; using gl::GL_INT_SAMPLER_2D; using gl::GL_INT_SAMPLER_3D; using gl::GL_INT_SAMPLER_CUBE; using gl::GL_INT_SAMPLER_2D_RECT; using gl::GL_INT_SAMPLER_1D_ARRAY; using gl::GL_INT_SAMPLER_2D_ARRAY; using gl::GL_INT_SAMPLER_BUFFER; using gl::GL_UNSIGNED_INT_SAMPLER_1D; using gl::GL_UNSIGNED_INT_SAMPLER_2D; using gl::GL_UNSIGNED_INT_SAMPLER_3D; using gl::GL_UNSIGNED_INT_SAMPLER_CUBE; using gl::GL_UNSIGNED_INT_SAMPLER_2D_RECT; using gl::GL_UNSIGNED_INT_SAMPLER_1D_ARRAY; using gl::GL_UNSIGNED_INT_SAMPLER_2D_ARRAY; using gl::GL_UNSIGNED_INT_SAMPLER_BUFFER; using gl::GL_QUERY_WAIT; using gl::GL_QUERY_NO_WAIT; using gl::GL_QUERY_BY_REGION_WAIT; using gl::GL_QUERY_BY_REGION_NO_WAIT; using gl::GL_COPY_READ_BUFFER; using gl::GL_COPY_READ_BUFFER_BINDING; using gl::GL_COPY_WRITE_BUFFER; using gl::GL_COPY_WRITE_BUFFER_BINDING; using gl::GL_R8_SNORM; using gl::GL_RG8_SNORM; using gl::GL_RGB8_SNORM; using gl::GL_RGBA8_SNORM; using gl::GL_R16_SNORM; using gl::GL_RG16_SNORM; using gl::GL_RGB16_SNORM; using gl::GL_RGBA16_SNORM; using gl::GL_SIGNED_NORMALIZED; using gl::GL_PRIMITIVE_RESTART; using gl::GL_PRIMITIVE_RESTART_INDEX; using gl::GL_BUFFER_ACCESS_FLAGS; using gl::GL_BUFFER_MAP_LENGTH; using gl::GL_BUFFER_MAP_OFFSET; } // namespace gl31
[ "jakob.wagner@uni-weimar.de" ]
jakob.wagner@uni-weimar.de
8a6c8c4c56f8907cf18522567ea1c6402e847703
12d3908fc4a374e056041df306e383d95d8ff047
/Programs/prog14.cpp
9c65a7e36a4f92e0db39b5f7b581dc3f34539d9a
[ "MIT" ]
permissive
rux616/c201
aca5898c506aeb1792aa8b1f9dcf3d797a1cd888
d8509e8d49e52e7326486249ad8d567560bf4ad4
refs/heads/master
2021-01-01T16:14:44.747670
2017-07-20T05:14:24
2017-07-20T05:14:24
97,792,948
0
0
null
null
null
null
UTF-8
C++
false
false
1,940
cpp
/* Prog14.cpp Shows how to pass command line arguments to a function and how to reference individual characters of command line arguments. ------------------------------------------------------------------------*/ #include <iostream> #include <string> using namespace std; void ShowCommandLineArgs (int ArgCount, char* Argument[]); //************************** main ************************************* void main (int argc, char* argv[]) // Allow command line args { ShowCommandLineArgs (argc, argv); } /********************** ShowCommandLineArgs ***************************** Reveals some information about command line arguments that have been passed to main(). - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/ void ShowCommandLineArgs (int ArgCount, char* Argument[]) { cout << "\nNumber of command line args: " << ArgCount << "\n\nHere's what you entered on the command line: \n\n"; for ( int N = 0; N < ArgCount ; ++N ) cout << Argument[N] << " "; cout << "\n\nThe first character of argv[1] is '" << Argument[1][0] << "'" << "\nThe third character of argv[1] is '" << Argument[1][2] << "'" << "\n\nThe length of the second argument is " << strlen(Argument[1]); } /********************* program notes ***************************** 1) Refer to prog12.cpp for introductory comments on command line args. 2) If the user ran this program via the command, "prog14 /abc def" the program would output: Number of command line args: 3 Here's what you entered on the command line: PROG14.EXE /abd def The first character of argv[1] is '/' The third character of argv[1] is 'b' The length of the second argument is 4 3) A careful reading of the function ShowCommandLineArgs will yield insights into how to send command line info to a function and how to process command line info. */
[ "dan.cassidy.1983@gmail.com" ]
dan.cassidy.1983@gmail.com
fabb85fc1d7896ddecd72a73d69997a9de63a946
622974cd61d5a4c6cb90ce39775198989e0a2b4c
/cuda/io/include/pcl/cuda/io/predicate.h
2d4d9ae11b9c4d551ec565852ecbed9f574053b5
[ "BSD-3-Clause" ]
permissive
kalectro/pcl_groovy
bd996ad15a7f6581c79fedad94bc7aaddfbaea0a
10b2f11a1d3b10b4ffdd575950f8c1977f92a83c
refs/heads/master
2021-01-22T21:00:10.455119
2013-05-13T02:44:37
2013-05-13T02:44:37
8,296,825
2
0
null
null
null
null
UTF-8
C++
false
false
3,013
h
/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * 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. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id: predicate.h 6459 2012-07-18 07:50:37Z dpb $ * */ #ifndef PCL_CUDA_PREDICATE_H_ #define PCL_CUDA_PREDICATE_H_ //#if THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC //#undef __MMX__ #include <pcl/cuda/point_cloud.h> #include <pcl/cuda/point_types.h> //#else //#endif namespace pcl { namespace cuda { template <class T> struct isNotZero { __inline__ __host__ __device__ bool operator()(T x) { return (x != 0); } }; struct isInlier { __inline__ __host__ __device__ bool operator()(int x) { return (x != -1); } }; struct isNotInlier { __inline__ __host__ __device__ bool operator()(int x) { return (x == -1); } }; struct SetColor { SetColor (const OpenNIRGB& color) : color_(color) {} __inline__ __host__ __device__ void operator()(PointXYZRGB& point) { point.rgb.r = color_.r; point.rgb.g = color_.g; point.rgb.b = color_.b;} OpenNIRGB color_; }; struct ChangeColor { ChangeColor (const OpenNIRGB& color) : color_(color) {} __inline__ __host__ __device__ PointXYZRGB& operator()(PointXYZRGB& point) { point.rgb.r = color_.r; point.rgb.g = color_.g; point.rgb.b = color_.b; return point; } OpenNIRGB color_; }; } // namespace } // namespace #endif //#ifndef PCL_CUDA_PREDICATE_H_
[ "jkammerl@rbh.willowgarage.com" ]
jkammerl@rbh.willowgarage.com
f0cbe107198ae902d704935269727cb7c2e1ccbb
e7aadf0214af5077d3516f7201a9c7e753c22e5b
/extensions/ringqt/gdial.cpp
f3bc029389e82587ef0b12498bae6bc761516e39
[ "MIT" ]
permissive
sethgreen23/ring
7e45524a946e41af8bf6dda488b6e2e6d7d7fc60
2c4e0717a30f056ce677b2cce5e0b0a2a7680787
refs/heads/master
2020-06-17T20:23:56.435446
2016-11-26T09:11:57
2016-11-26T09:11:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,909
cpp
/* Copyright (c) 2013-2016 Mahmoud Fayed <msfclipper@yahoo.com> */ extern "C" { #include "ring.h" } #include "gdial.h" GDial::GDial(QWidget *parent,VM *pVM) : QDial(parent) { this->pVM = pVM; this->pParaList = ring_list_new(0); strcpy(this->cactionTriggeredEvent,""); strcpy(this->crangeChangedEvent,""); strcpy(this->csliderMovedEvent,""); strcpy(this->csliderPressedEvent,""); strcpy(this->csliderReleasedEvent,""); strcpy(this->cvalueChangedEvent,""); QObject::connect(this, SIGNAL(actionTriggered(int)),this, SLOT(actionTriggeredSlot())); QObject::connect(this, SIGNAL(rangeChanged(int,int)),this, SLOT(rangeChangedSlot())); QObject::connect(this, SIGNAL(sliderMoved(int)),this, SLOT(sliderMovedSlot())); QObject::connect(this, SIGNAL(sliderPressed()),this, SLOT(sliderPressedSlot())); QObject::connect(this, SIGNAL(sliderReleased()),this, SLOT(sliderReleasedSlot())); QObject::connect(this, SIGNAL(valueChanged(int)),this, SLOT(valueChangedSlot())); } GDial::~GDial() { ring_list_delete(this->pParaList); } void GDial::geteventparameters(void) { void *pPointer; pPointer = this->pVM; RING_API_RETLIST(this->pParaList); } void GDial::setactionTriggeredEvent(const char *cStr) { if (strlen(cStr)<100) strcpy(this->cactionTriggeredEvent,cStr); } void GDial::setrangeChangedEvent(const char *cStr) { if (strlen(cStr)<100) strcpy(this->crangeChangedEvent,cStr); } void GDial::setsliderMovedEvent(const char *cStr) { if (strlen(cStr)<100) strcpy(this->csliderMovedEvent,cStr); } void GDial::setsliderPressedEvent(const char *cStr) { if (strlen(cStr)<100) strcpy(this->csliderPressedEvent,cStr); } void GDial::setsliderReleasedEvent(const char *cStr) { if (strlen(cStr)<100) strcpy(this->csliderReleasedEvent,cStr); } void GDial::setvalueChangedEvent(const char *cStr) { if (strlen(cStr)<100) strcpy(this->cvalueChangedEvent,cStr); } void GDial::actionTriggeredSlot() { if (strcmp(this->cactionTriggeredEvent,"")==0) return ; ring_vm_runcode(this->pVM,this->cactionTriggeredEvent); } void GDial::rangeChangedSlot() { if (strcmp(this->crangeChangedEvent,"")==0) return ; ring_vm_runcode(this->pVM,this->crangeChangedEvent); } void GDial::sliderMovedSlot() { if (strcmp(this->csliderMovedEvent,"")==0) return ; ring_vm_runcode(this->pVM,this->csliderMovedEvent); } void GDial::sliderPressedSlot() { if (strcmp(this->csliderPressedEvent,"")==0) return ; ring_vm_runcode(this->pVM,this->csliderPressedEvent); } void GDial::sliderReleasedSlot() { if (strcmp(this->csliderReleasedEvent,"")==0) return ; ring_vm_runcode(this->pVM,this->csliderReleasedEvent); } void GDial::valueChangedSlot() { if (strcmp(this->cvalueChangedEvent,"")==0) return ; ring_vm_runcode(this->pVM,this->cvalueChangedEvent); }
[ "msfclipper@yahoo.com" ]
msfclipper@yahoo.com
2aa6ef371aa6cf24afd6510cb495a41fb2e377fc
62d4601d67c3f86287f107843d800e1c4dd09c9c
/code/main.cpp
85b6eb8d9b74784c7661f99194469a1327051872
[]
no_license
JorgeBarcena3/SDL2-Base-project
c7549743f8559d753cdecb1b41c5f083655be1bf
616b8bb6e90049f3d8e74ce58991443a863087f0
refs/heads/master
2020-09-08T22:57:53.627280
2020-03-25T02:44:24
2020-03-25T02:44:24
221,268,448
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
2,264
cpp
// File: main.cpp // Description : Proyecto base con la libreria de SDL2 // Author: Jorge Bárcena Lumbreras // © Copyright (C) 2019 Jorge Bárcena Lumbreras // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include <SDL.h> #include <SDL_main.h> extern "C" int main(int numer_of_arguments, char * arguments[]) { SDL_Window* window; // Declare a pointer SDL_Init(SDL_INIT_VIDEO); // Initialize SDL2 // Create an application window with the following settings: window = SDL_CreateWindow( "SDL EXAMPLE WINDOW", // window title SDL_WINDOWPOS_UNDEFINED, // initial x position SDL_WINDOWPOS_UNDEFINED, // initial y position 640, // width, in pixels 480, // height, in pixels SDL_WINDOW_OPENGL // flags - see below ); // Check that the window was successfully created if (window == NULL) { // In the case that the window could not be made... return 1; } // The window is open: could enter program loop here (see SDL_PollEvent()) //Main loop flag bool quit = false; //Event handler SDL_Event e; //While application is running while (!quit) { //Handle events on queue while (SDL_PollEvent(&e) != 0) { //User requests quit if (e.type == SDL_QUIT) { quit = true; } } } // Close and destroy the window SDL_DestroyWindow(window); // Clean up SDL_Quit(); return 0; }
[ "j.barcenalumbreras@gmail.com" ]
j.barcenalumbreras@gmail.com