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
2e0e24ae3ced5e30584e532a07e297f943b0244e
9a8c683054f2a34de10a6d5eba74d77d7d5ce832
/Arbitrary codes/doublydeletion.cpp
3df8ea6032170ec6dfb01518fe33d023761b31c8
[]
no_license
SKBshahriar/Codes
5f85a4e1220f25e4cf8d766482e04279d92a7645
bbf6ff3af37b9436ed75f23290cef60e88840fc2
refs/heads/master
2022-02-27T08:47:37.831842
2019-10-05T09:39:51
2019-10-05T09:39:51
116,161,613
0
0
null
null
null
null
UTF-8
C++
false
false
1,498
cpp
#include<stdio.h> struct list{ int data; struct list *back; struct list *next; }; typedef struct list node; void display(node *start) { node *temp; temp=start; while(temp!=NULL) { printf("%d ",temp->data); temp=temp->next; } } int main() { node *start,*temp,*prev; int i,j,ch,item; start=NULL; do { printf("Do You Want To Create A Node? "); scanf("%d",&ch); if(ch==1) { if(start==NULL) { start=new node(); start->next=NULL; start->back=NULL; printf("Enter Data For Node : "); scanf("%d",&start->data); prev=start; } else { temp=new node(); printf("Enter Data For Node : "); scanf("%d",&temp->data); prev->next=temp; temp->back=prev; prev=temp; } } }while(ch==1); display(start); printf("\nenter item :"); scanf("%d",&item); temp=start; while(temp!=NULL && temp->data!=item) temp=temp->next; if(temp==NULL) printf("\nnot found"); else { if(temp!=start) temp->back->next=temp->next; else start=temp->next; if(temp->next!=NULL) temp->next->back=temp->back; } printf("\n"); display(start); return 0; }
[ "34690284+SKBshahriar@users.noreply.github.com" ]
34690284+SKBshahriar@users.noreply.github.com
ed87a2ef3db941f55137e22b4c85a4a33dd72b85
4090222a5a1418ee607fe1fb86e7287b02f459df
/include/lstm/cell.hpp
57addc1cbf72ccf1b2ba452ebf1f552c180f515c
[ "MIT" ]
permissive
pcannon67/lstm-from-scratch
539ed7d3be0d7a31cc712d6346ace84c55e2b6d0
df61ded892ae7ef576a0c7cc572f6375dd13c99b
refs/heads/master
2020-12-03T10:04:52.907136
2018-12-08T21:39:46
2018-12-08T21:39:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,298
hpp
/** * MIT License * * Copyright (c) 2018 Prabhsimran Singh * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #include <algorithm> #include <cmath> #include <iostream> #include <Eigen/Dense> using namespace Eigen; #include "functions.hpp" #include "layers.hpp" #include "lstm/network.hpp" namespace nn { struct LSTMState { // hidden state MatrixXf h; // cell state MatrixXf c; }; class LSTMCell { private: int batch_size; int hidden_size; int embedding_dim; Dense i2h; Dense h2h; protected: LSTMState state; friend class LSTMNetwork; public: explicit LSTMCell(const int &, const int &, const int &); MatrixXf &operator()(const MatrixXf &); MatrixXf &forward(const MatrixXf &); // MatrixXf backward(const MatrixXf &, const MatrixXf &); }; /** * LSTMCell Constructor. * * @param hidden_size the size of the hidden state and cell state. * @param batch_size the size of batch used during training (for vectorization purposes). */ LSTMCell::LSTMCell(const int &hidden_size, const int &embedding_dim, const int &batch_size) : i2h(Dense(embedding_dim, 4 * hidden_size)), h2h(Dense(hidden_size, 4 * hidden_size)) { this->hidden_size = hidden_size; this->embedding_dim = embedding_dim; this->batch_size = batch_size; this->state = LSTMState{MatrixXf(batch_size, hidden_size).setRandom() * F::glorot_uniform(batch_size, hidden_size), MatrixXf(batch_size, hidden_size).setRandom() * F::glorot_uniform(batch_size, hidden_size)}; } MatrixXf &LSTMCell::operator()(const MatrixXf &xt) { return forward(xt); } /** * LSTMCell Forward Pass. * * @param xt the input vector at time-step t. * @returns the next hidden state for input into next lstm layer. */ MatrixXf &LSTMCell::forward(const MatrixXf &xt) { // i2h + h2h = [it_pre, ft_pre, ot_pre, x_pre] MatrixXf preactivations = i2h(xt) + h2h(state.h); // all pre sigmoid gates chunk MatrixXf pre_sigmoid_chunk = preactivations.block(0, 0, batch_size, 3 * hidden_size); // compute sigmoid on gates chunk MatrixXf all_gates = F::sigmoid(pre_sigmoid_chunk); // compute c_in (x_transform) i.e. information vector MatrixXf x_pre = preactivations.block(0, 3 * hidden_size, batch_size, hidden_size); MatrixXf x_transform = F::tanh(x_pre); // single out all the gates MatrixXf it = all_gates.block(0, 0, batch_size, hidden_size); MatrixXf ft = all_gates.block(0, hidden_size, batch_size, hidden_size); MatrixXf ot = all_gates.block(0, 2 * hidden_size, batch_size, hidden_size); // update cell state MatrixXf c_forget = ft.cwiseProduct(state.c); MatrixXf c_input = it.cwiseProduct(x_transform); state.c = c_forget + c_input; // compute next hidden state MatrixXf c_transform = F::tanh(state.c); state.h = ot.cwiseProduct(c_transform); return state.h; } /** * LSTMCell Backward Pass. * * @param inputs the input vector given at time-step t. * @param gradients the gradients from upper layers computed using chain rule. * @returns the output i.e. the hidden state at time-step t. */ // MatrixXf LSTMCell::backward(const MatrixXf &inputs, const MatrixXf &gradients) { // } } // namespace nn
[ "pskrunner14@gmail.com" ]
pskrunner14@gmail.com
e7ef6bba5aeeef65302cc9742b2792b3dfbab4c1
b54b6168ba35ce6ad34f5a26b5a4a3ab8afa124a
/kratos_3_0_1/kratos/linear_solvers/luc_solver.h
98ec95320ccf5b559ecb0963ed552524c60f683f
[]
no_license
svn2github/kratos
e2f3673db1d176896929b6e841c611932d6b9b63
96aa8004f145fff5ca6c521595cddf6585f9eccb
refs/heads/master
2020-04-04T03:56:50.018938
2017-02-12T20:34:24
2017-02-12T20:34:24
54,662,269
2
1
null
null
null
null
UTF-8
C++
false
false
25,514
h
/* ============================================================================== Kratos A General Purpose Software for Multi-Physics Finite Element Analysis Version 1.0 (Released on march 05, 2007). Copyright 2007 Pooyan Dadvand, Riccardo Rossi pooyan@cimne.upc.edu rrossi@cimne.upc.edu CIMNE (International Center for Numerical Methods in Engineering), Gran Capita' s/n, 08034 Barcelona, Spain 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 condition: Distribution of this code for any commercial purpose is permissible ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNER. 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. ============================================================================== */ // // Project Name: Kratos // Last Modified by: $Author: rrossi $ // Date: $Date: 2007-03-06 10:30:33 $ // Revision: $Revision: 1.3 $ // // #if !defined(KRATOS_LUC_SOLVER_H_INCLUDED ) #define KRATOS_LUC_SOLVER_H_INCLUDED // System includes #include <string> #include <iostream> #include <fstream> // External includes #include <boost/timer.hpp> // Project includes #include "includes/define.h" #include "linear_solvers/iterative_solver.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /// Short class definition. /** Detail class definition. */ template<class TSparseSpaceType, class TDenseSpaceType, class TReordererType = Reorderer<TSparseSpaceType, TDenseSpaceType> > class LUCSolver : public DirectSolver<TSparseSpaceType, TDenseSpaceType, TReordererType> { public: ///@name Type Definitions ///@{ /// Pointer definition of LUCSolver KRATOS_CLASS_POINTER_DEFINITION(LUCSolver); typedef DirectSolver<TSparseSpaceType, TDenseSpaceType, TReordererType> BaseType; typedef typename TSparseSpaceType::MatrixType SparseMatrixType; typedef typename TSparseSpaceType::VectorType VectorType; typedef typename TDenseSpaceType::MatrixType DenseMatrixType; typedef std::size_t IndexType; typedef std::vector<IndexType> IndicesVectorType; ///@} ///@name Life Cycle ///@{ /// Default constructor. LUCSolver() {} /// Constructor with specific reorderer. LUCSolver(typename TReordererType::Pointer pNewReorderer) : BaseType(pNewReorderer) {} /// Copy constructor. LUCSolver(const LUCSolver& Other) : BaseType(Other) {} /// Destructor. virtual ~LUCSolver() {} ///@} ///@name Operators ///@{ /// Assignment operator. LUCSolver& operator=(const LUCSolver& Other) { BaseType::operator=(Other); return *this; } ///@} ///@name Operations ///@{ /** Normal solve method. Solves the linear system Ax=b and puts the result on SystemVector& rX. @param rA. System matrix @param rX. Solution vector. it's also the initial guess for iterative linear solvers. @param rB. Right hand side vector. */ bool Solve(SparseMatrixType& rA, VectorType& rX, VectorType& rB) { GetReorderer()->Initialize(rA, rX, rB); std::cout << " Decomposing Matrix A..." << std::endl; boost::timer decomposing_timer; if(LUCDecompose(rA) != 0) return false; std::cout << " Decomposing time : " << decomposing_timer.elapsed() << std::endl; std::cout << " Solving L U X = B..." << std::endl; boost::timer lu_solve_timer; if(LUSolve(rA, rX, rB) == false) return false; std::cout << " Solving L U X = B time : " << lu_solve_timer.elapsed() << std::endl; return true; } /** Multi solve method for solving a set of linear systems with same coefficient matrix. Solves the linear system Ax=b and puts the result on SystemVector& rX. @param rA. System matrix @param rX. Solution vector. it's also the initial guess for iterative linear solvers. @param rB. Right hand side vector. */ bool Solve(SparseMatrixType& rA, DenseMatrixType& rX, DenseMatrixType& rB) { return false; } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. virtual std::string Info() const { std::stringstream buffer; buffer << "LUC linear solver"; return buffer.str(); } /// Print information about this object. virtual void PrintInfo(std::ostream& rOStream) const { rOStream << Info(); } /// Print object's data. virtual void PrintData(std::ostream& rOStream) const { BaseType::PrintData(rOStream); } ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ IndicesVectorType mIL, mJL, mIU, mJU; std::vector<double> mL, mU; ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ void ClearLU() { mIL.clear(); mJL.clear(); mIU.clear(); mJU.clear(); mL.clear(); mU.clear(); } void WriteMatrixForGid(std::string MatrixFileName, std::string MatrixName) { KRATOS_TRY //GiD_FILE matrix_file = GiD_fOpenPostMeshFile("matricesA.post.msh", GiD_PostAscii); std::ofstream matrix_file(MatrixFileName.c_str()); //GiD_fBeginMesh(matrix_file, "Kratos Matrix",GiD_2D,GiD_Point,1); matrix_file << "MESH \"" << MatrixName << "\" dimension 2 ElemType Point Nnode 1" << std::endl; //GiD_fBeginCoordinates(matrix_file); matrix_file << "Coordinates" << std::endl; std::vector<double> results; int index = 1; double SolutionTag=0; int size_1 = mIU.size() - 1; // Creating a node for each nonzero of matrix U for (unsigned int i = 0 ; i < size_1 ; i++) for (unsigned int j = mIU[i] ; j < mIU[i+1] ; j++) { //GiD_fWriteCoordinates(matrix_file, index++, i2.index1(), i2.index2(), 0); matrix_file << index++ << " " << i << " " << size_1 - mJU[j] << " 0" << std::endl; results.push_back(mU[j]); } // Creating a node for each nonzero of matrix L //for (unsigned int j = 0 ; j < mJL.size() - 1 ; j++) // for (unsigned int i = mJL[j] ; j < mJL[j+1] ; i++) // { // //GiD_fWriteCoordinates(matrix_file, index++, i2.index1(), i2.index2(), 0); // matrix_file << index++ << " " << mIL[i] << " " << size_1 - j << " 0" << std::endl; // results.push_back(mL[j]); // } // //GiD_fEndCoordinates(matrix_file); matrix_file << "End Coordinates" << std::endl; // Creating an element for each nonzero of matrix int nodes_id[1]; //GiD_fBeginElements(matrix_file); matrix_file << "Elements" << std::endl; for( int i = 1 ; i < index ; i++) { nodes_id[0] = i; //GiD_fWriteElement(matrix_file, i,nodes_id); matrix_file << i << " " << i << std::endl; } //GiD_fEndElements(matrix_file); matrix_file << "End Elements" << std::endl; //GiD_fEndMesh(matrix_file); //GiD_fClosePostMeshFile(matrix_file); //GiD_OpenPostResultFile("matrices.post.bin", GiD_PostBinary); //GiD_BeginResult( "Matrix", "Kratos", // SolutionTag, GiD_Scalar, // GiD_OnNodes, NULL, NULL, 0, NULL ); // //for( int i = 1 ; i < index ; i++) //{ // GiD_WriteScalar( i, results[i-1]); //} // //GiD_EndResult(); //GiD_ClosePostResultFile(); KRATOS_CATCH("") } /// Decomposes the Matrix A to L and U and store it in mL and mU std::size_t LUCDecompose(SparseMatrixType& rA) { typedef typename TSparseSpaceType::DataType DataType; const SizeType size = TSparseSpaceType::Size1(rA); VectorType z(size); // working vector for row k VectorType w(size); // working vector for column k VectorType temp(size); IndicesVectorType l_first(size, 0); // The pointer to the first element in each column of L with row index >= k (L is stored by columns) IndicesVectorType u_first(size, 0); // The pointer to the first element in each row of U with column index >= k (U is stored by rows) IndicesVectorType l_list(size, size+1); // The link list of elements in row k the L IndicesVectorType u_list(size, size+1); // The link list of elements in column k the U std::vector<typename SparseMatrixType::iterator2> a_first; // The pointer to the first element in each row of rA with column index >= k (U is stored by rows) typename SparseMatrixType::iterator1 a_iterator = rA.begin1(); for(SizeType i = 0 ; i < size ; i++) a_first.push_back((a_iterator++).begin()); // initializing the row_pointers of A ClearLU(); mJL.push_back(0); mIU.push_back(0); SizeType output_index = 0; for(SizeType k = 0 ; k < size ; k++) { //initializing z: z_1:k-1 = 0, z_k:n = rA_k,kn TSparseSpaceType::GetRow(k, rA, z); // NOTE: I don't need to set the first part to zero while I'm not using it! for(SizeType i = l_list[k] ; i < size ; i = l_list[i]) // loop over nonzeros in row k of L for(SizeType j = u_first[i] ; j < mIU[i+1] ; j++) // for all nonzeros in row i of U z[mJU[j]] -= mL[l_first[i]] * mU[j]; // z_j = Z_j - L_ki * U_ij //initializing w: w_1:k = 0, w_k:n = rA_k+1:n,k for(SizeType i = k ; i < size ; i++) { if(a_first[i].index2() < k) (a_first[i])++; if(a_first[i].index2() == k) w[i] = *(a_first[i]); else w[i] = 0; } for(SizeType i = u_list[k] ; i < size ; i = u_list[i]) // loop over nonzeros in column k of U for(SizeType j = l_first[i] ; j < mJL[i+1] ; j++) // for all nonzeros in column i of L w[mIL[j]] -= mU[u_first[i]] * mL[j]; // w_j = w_j - L_ki * U_ij // adding nonzeros of z to the U for(SizeType i = k ; i < size ; i++) { if(z[i] != 0.00) { mJU.push_back(i); mU.push_back(z[i]); } } mIU.push_back(mU.size()); double u_kk = z[k]; if(u_kk == 0.00) //{ // KRATOS_WATCH(k); // for(SizeType k1 = k + 1 ; k1 < size ; k1++) // if(rA(r_index_permutation[k1], r_index_permutation[k1]) != 0.00) // { // KRATOS_WATCH(k1); // SizeType temp_index = r_index_permutation[k1]; // r_index_permutation[k1] = r_index_permutation[k]; // r_index_permutation[k] = temp_index; // break; // } // k--; // continue; //} KRATOS_ERROR(std::runtime_error, "Zero pivot found in row ",k); // adding nonzeros of w to the L for(SizeType i = k + 1 ; i < size ; i++) { if(w[i] != 0.00) { mIL.push_back(i); mL.push_back(w[i]/u_kk); } } mJL.push_back(mL.size()); // updating the l_first, l_list for added column l_first[k] = mJL[k]; if(l_first[k] < mIL.size()) IndexPushBack(l_list, k, mIL[l_first[k]]); // updating l_first and l_list in this columns SizeType j = k; if(k + 1 < size) // not for the last column! { for(SizeType i = l_list[k] ; i < size ; i = l_list[i]) // loop over nonzeros in row k of L { l_list[j] = size + 1; // reseting the list l_first[i]++; if(l_first[i] < mJL[i+1]) { IndexPushBack(l_list, i, mIL[l_first[i]]); } j = i; } } // updating the u_first, u_list for added row u_first[k] = mIU[k]; if(u_first[k] < mJU.size()) IndexPushBack(u_list, k, mJU[u_first[k]]); // updating u_first and u_list in this columns j = k; if(k + 1 < size) // not for the last row! { for(SizeType i = u_list[k] ; i < size ; i = u_list[i]) // loop over nonzeros in column k of U { u_list[j] = size + 1; // reseting the list u_first[i]++; if(u_first[i] < mIU[i+1]) { IndexPushBack(u_list, i, mJU[u_first[i]]); } j = i; } } if(output_index++ >= (0.1 * size)) { std::cout << " " << int(double(k) / double(size) * 100.00) << " % : L nonzeros = " << mL.size() << " and U nonzeros = " << mU.size() << std::endl; output_index = 0; } //std::cout << "Finishing loop #" << k << " of " << size << std::endl; } std::cout << " " << 100 << " % : L nonzeros = " << mL.size() << " and U nonzeros = " << mU.size() << std::endl; // //Writing U //for(SizeType i = 0 ; i < size ; i++) //{ // int k = mIU[i]; // for(SizeType j = 0 ; j < size ; j++) // { // double value = 0.00; // if(mJU[k] == j) // { // value = mU[k]; // k++; // } // std::cout << value << ", "; // } // std::cout << std::endl; //} //// Writing L //for(SizeType i = 0 ; i < size ; i++) //{ // for(SizeType j = 0 ; j < i ; j++) // { // double value = 0.00; // for(SizeType k = mJL[j] ; k < mJL[j+1] ; k++) // if(mIL[k] == i) // value = mL[k]; // std::cout << value << ", "; // } // std::cout << std::endl; //} //WriteMatrixForGid("matrixLU.post.msh", "lu_matrix"); return 0; } void IndexPushBack(IndicesVectorType& ThisLinkList, IndexType ThisIndex, IndexType ThisRow) { SizeType i = ThisRow; // Loop to the end of the link list of row ThisRow for(; ThisLinkList[i] < ThisLinkList.size() ; i = ThisLinkList[i]); ThisLinkList[i] = ThisIndex; } std::size_t LUCPermuteAndDecompose(SparseMatrixType& rA) { typename TReordererType::IndexVectorType& r_index_permutation = GetReorderer()->GetIndexPermutation(); typedef typename TSparseSpaceType::DataType DataType; const SizeType size = TSparseSpaceType::Size1(rA); DataType* z = new DataType[size]; // working vector for row k VectorType w(size); // working vector for column k VectorType temp(size); IndicesVectorType l_first(size, 0); // The pointer to the first element in each column of L with row index >= k (L is stored by columns) IndicesVectorType u_first(size, 0); // The pointer to the first element in each row of U with column index >= k (U is stored by rows) std::vector<IndicesVectorType> l_rows(size,IndicesVectorType()); std::vector<IndicesVectorType> u_columns(size,IndicesVectorType()); mIL.clear(); mJL.clear(); mIU.clear(); mJU.clear(); mL.clear(); mU.clear(); mJL.push_back(0); mIU.push_back(0); // find inverse permutation typename TReordererType::IndexVectorType inverse_permutation(size); for (SizeType i=0; i<size; i++) inverse_permutation[r_index_permutation[i]]=i; SizeType output_index = 0; for(SizeType k = 0 ; k < size ; k++) { //KRATOS_WATCH(k); //initializing z: z_1:k-1 = 0, z_k:n = rA_k,kn // this has to be changed to be without temporary vector TSparseSpaceType::GetRow(r_index_permutation[k], rA, temp); for(SizeType i = 0 ; i < size ; i++) z[i] = temp[r_index_permutation[i]]; for(SizeType i = 0 ; i < k ; i++) z[i] = 0; for(SizeType h = 0 ; h < l_rows[k].size() ; h++) // iterating over nonzeros of row k of L { SizeType i = l_rows[k][h]; while((u_first[i] < mJU.size()) && (mJU[u_first[i]] < k)) // updating u_first u_first[i]++; while((l_first[i] < mIL.size()) && (mIL[l_first[i]] < k)) // updating l_first l_first[i]++; for(SizeType j = u_first[i] ; j < mIU[i+1] ; j++) // for all nonzeros in row i of U z[mJU[j]] -= mL[l_first[i]] * mU[j]; // z_j = Z_j - L_ki * U_ij } //initializing w: w_1:k = 0, w_k:n = rA_k+1:n,k // this has to be changed to be without temporary vector TSparseSpaceType::GetColumn(r_index_permutation[k], rA, temp); for(SizeType i = 0 ; i < size ; i++) w[i] = temp[r_index_permutation[i]]; for(SizeType i = 0 ; i < k ; i++) w[i] = 0; for(SizeType h = 0 ; h < u_columns[k].size() ; h++) // iterating over nonzeros of column k of U { SizeType i = u_columns[k][h]; while((u_first[i] < mJU.size()) && (mJU[u_first[i]] < k)) // updating u_first u_first[i]++; while((l_first[i] < mIL.size()) && (mIL[l_first[i]] < k)) // updating l_first l_first[i]++; for(SizeType j = l_first[i] ; j < mJL[i+1] ; j++) // for all nonzeros in column i of L w[mIL[j]] -= mU[u_first[i]] * mL[j]; // w_j = w_j - L_ki * U_ij } // adding nonzeros of z to the U for(SizeType i = k ; i < size ; i++) if(z[i] != 0.00) { u_columns[i].push_back(k); mJU.push_back(i); mU.push_back(z[i]); } mIU.push_back(mU.size()); double u_kk = z[k]; if(u_kk == 0.00) KRATOS_ERROR(std::runtime_error, "Zero pivot found in row ",k); // adding nonzeros of w to the L for(SizeType i = k + 1 ; i < size ; i++) if(w[i] != 0.00) { l_rows[i].push_back(k); mIL.push_back(i); mL.push_back(w[i]/u_kk); } mJL.push_back(mL.size()); l_first[k] = mJL[k]; u_first[k] = mIU[k]; if(output_index++ >= (0.1 * size)) { std::cout << " " << int(double(k) / double(size) * 100.00) << " % : L nonzeros = " << mL.size() << " and U nonzeros = " << mU.size() << std::endl; output_index = 0; } } std::cout << " " << 100 << " % : L nonzeros = " << mL.size() << " and U nonzeros = " << mU.size() << std::endl; delete [] z; WriteMatrixForGid("matrixLU.post.msh", "lu_matrix"); return 0; } template<class T> void WriteVector(std::string Name, std::vector<T>& Data) { std::cout << Name << " : "; for(int i = 0 ; i < Data.size() ; i++) std::cout << Data[i] << ", "; std::cout << std::endl; } bool LUSolve(SparseMatrixType& rA, VectorType& rX, VectorType& rB) { VectorType y = ZeroVector(rX.size()); std::cout << " Solving L Y = B..." << std::endl; boost::timer u_solve_timer; if(LSolve(rA, y, rB) == false) return false; std::cout << " Solving L Y = B time : " << u_solve_timer.elapsed() << std::endl; //KRATOS_WATCH(y); std::cout << " Solving U X = Y..." << std::endl; boost::timer l_solve_timer; if(USolve(rA, rX, y) == false) return false; std::cout << " Solving U X = Y time : " << l_solve_timer.elapsed() << std::endl; return true; } bool LSolve(SparseMatrixType& rA, VectorType& rX, VectorType& rB) { typename TReordererType::IndexVectorType& r_index_permutation = GetReorderer()->GetIndexPermutation(); SizeType size = rX.size(); for(SizeType i = 0 ; i < size ; i++) { rX[i] = rB[r_index_permutation[i]]; } for(SizeType i = 0 ; i < size ; i++) { for(SizeType j = mJL[i] ; j < mJL[i+1] ; j++) rX[mIL[j]] -= mL[j] * rX[i]; } return true; } bool USolve(SparseMatrixType& rA, VectorType& rX, VectorType& rY) { typename TReordererType::IndexVectorType& r_index_permutation = GetReorderer()->GetIndexPermutation(); SizeType size = rX.size(); VectorType x(size); for(SizeType i = 0 ; i < size ; i++) x[i] = 0.00; for(int i = size - 1 ; i >= 0 ; i--) { double temp = rY[i]; for(SizeType j = mIU[i] + 1 ; j < mIU[i+1] ; j++) temp -= mU[j] * x[mJU[j]]; x[i] = temp / mU[mIU[i]]; } for(SizeType i = 0 ; i < size ; i++) rX[r_index_permutation[i]] = x[i]; return true; } ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; // Class LUCSolver ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ /// input stream function template<class TSparseSpaceType, class TDenseSpaceType, class TPreconditionerType, class TReordererType> inline std::istream& operator >> (std::istream& IStream, LUCSolver<TSparseSpaceType, TDenseSpaceType, TReordererType>& rThis) { return IStream; } /// output stream function template<class TSparseSpaceType, class TDenseSpaceType, class TPreconditionerType, class TReordererType> inline std::ostream& operator << (std::ostream& OStream, const LUCSolver<TSparseSpaceType, TDenseSpaceType, TReordererType>& rThis) { rThis.PrintInfo(OStream); OStream << std::endl; rThis.PrintData(OStream); return OStream; } ///@} } // namespace Kratos. #endif // KRATOS_LUC_SOLVER_H_INCLUDED defined
[ "pooyan@4358b7d9-91ec-4505-bf62-c3060f61107a" ]
pooyan@4358b7d9-91ec-4505-bf62-c3060f61107a
de320e506ad6889a9fa1f28254dd8520f63b94a5
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/12_1292_16.cpp
48d6ee7afa86692a3d9bef7d3ad3a979be5764e1
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,978
cpp
#include <iostream> #include <set> #include <string> #include <vector> #include <deque> #include <queue> #include <stack> #include <list> #include <map> #include <math.h> #define PI 3.14159265 #define EPS .0000001 #define max(a,b) if((a)>(b)) return (a); else return (b); double min(double a, double b); double dist(double x1, double y1, double x2, double y2); bool compare(double a, double b, double eps); bool isDigit(char c); bool isAlpha(char c); void getFiles(int argc, char* argv[], FILE*& inF, FILE*& outF); class Point{ public: double x,y; Point(); ~Point(); bool operator==(const Point& rhs); bool operator!=(const Point& rhs); Point& operator=(const Point& rhs); double dist(Point& P2); }; class Circle{ public: Point center; double r; Circle(); ~Circle(); int findIntersection(Circle& C2, Point& P1, Point& P2); int contains(Circle& C2); double intersectionArea(Circle& C2); private: double lensArea(double R, double d); }; #define BUFSIZE 32768 class tokenizer{ private: FILE* dataFile; char line[BUFSIZE]; char* retval; char MOD_SEPS[32]; void setFile(FILE* fp); public: tokenizer(); tokenizer(FILE* fp); void setSEPS(const char*); char* getToken(); ~tokenizer(); char* context; }; class Node { Node* left; Node* right; public: Node(); ~Node(); }; #define BASE 10000 //for ease of printing #define BRANCHES 16 class bigNum{ private: unsigned int data[BRANCHES]; //4 digits per array item. 64 enough? too much? bool sign; char printable[BRANCHES*4 + 2]; //+2 for NULL and sign int topMismatch(const bigNum& rhs) const; void init(); public: bigNum(); bigNum(const bigNum& rhs); bigNum(const int rhs); bigNum(const char* rhs); ~bigNum(); bigNum& operator=(const bigNum& rhs); bigNum& operator=(const int rhs); bigNum& operator=(const char* rhs); bigNum operator+(const bigNum& rhs) const; bigNum operator-(const bigNum& rhs) const; bigNum operator*(const bigNum& rhs) const; bigNum operator/(const bigNum& rhs) const; bigNum operator%(const bigNum& rhs) const; bigNum operator^(const int exp) const; bigNum& operator+=(const bigNum& rhs); bigNum& operator-=(const bigNum& rhs); bigNum& operator*=(const bigNum& rhs); bigNum& operator/=(const bigNum& rhs); bigNum& operator%=(const bigNum& rhs); bigNum operator-() const; bigNum abs(const bigNum& rhs) const; bool operator==(const bigNum& rhs) const; bool operator!=(const bigNum& rhs) const; bool operator<(const bigNum& rhs) const; bool operator>(const bigNum& rhs) const; bool operator<=(const bigNum& rhs) const; bool operator>=(const bigNum& rhs) const; char* getStr(); }; template<class T> class fraction{ private: T numerator; T denominator; T gcd(T a, T b) { if(b==T(0)) return a; else return gcd(b, a%b); } void reduce() { T g = gcd(numerator,denominator); numerator=numerator/g; denominator=denominator/g; } public: fraction<T>() { } fraction<T>(const fraction<T>& rhs) { numerator = rhs.numerator; denominator=rhs.denominator; reduce(); } fraction<T>(const T& rhs) { numerator = rhs; denominator=T(1); reduce(); } ~fraction<T>() { } fraction<T>& operator=(const fraction<T>& rhs) { numerator = rhs.numerator; denominator = rhs.denominator; reduce(); return *this; } fraction<T>& operator=(T rhs) { numerator = rhs; denominator = T(1); return *this; } fraction<T> operator+(const fraction<T>& rhs) const { fraction<T> retval = *this; retval+=rhs; return retval; } fraction<T>& operator+=(const fraction<T>& rhs) { fraction<T> r = rhs; T g = gcd(denominator,r.denominator); denominator/=g; r.denominator/=g; numerator = numerator*r.denominator+denominator*r.numerator; denominator = denominator*r.denominator; reduce(); denominator*=g; reduce(); return *this; } fraction<T> operator-(const fraction<T>& rhs) const { fraction retval = *this; retval-=rhs; return retval; } fraction<T>& operator-=(const fraction<T>& rhs) { fraction<T> r = rhs; T g = gcd(denominator,r.denominator); denominator/=g; r.denominator/=g; numerator = numerator*r.denominator-denominator*r.numerator; denominator = denominator*r.denominator; reduce(); denominator*=g; reduce(); return *this; } fraction<T> operator*(const fraction<T>& rhs) const { fraction<T> retval = *this; retval*=rhs; return retval; } fraction<T>& operator*=(const fraction<T>& rhs) { fraction<T> r = rhs; T g = gcd(numerator,r.denominator); numerator=numerator/g; r.denominator=r.denominator/g; g = gcd(r.numerator,denominator); r.numerator=r.numerator/g; denominator=denominator/g; numerator = numerator*r.numerator; denominator = denominator*r.denominator; reduce(); return *this; } fraction<T> operator/(const fraction<T>& rhs) const { fraction<T> retval = *this; retval/=rhs; return retval; } fraction<T>& operator/=(const fraction<T>& rhs) { fraction<T> r = rhs; T g = gcd(numerator,r.numerator); numerator=numerator/g; r.numerator=r.numerator/g; g = gcd(denominator,r.denominator); r.denominator=r.denominator/g; denominator=denominator/g; numerator = numerator * r.denominator; denominator = denominator * r.numerator; reduce(); return *this; } bool operator==(const fraction<T>& rhs) const { if(numerator == rhs.numerator) if(numerator == 0 || denominator==rhs.denominator) return true; return false; } bool operator!=(const fraction<T>& rhs) const { return !(*this == rhs); } bool operator<(const fraction<T>& rhs) const { // a/b < c/d => ad < bc fraction<T> t = *this; t -= rhs; if(t.numerator<0 || t.denominator<0) //should really check for both here. return true; return false; } bool operator>(const fraction<T>& rhs) const { fraction<T> t = *this; t -= rhs; if(t.numerator>0) return true; return false; } bool operator<=(const fraction<T>& rhs) const { if(*this<rhs) return true; if(*this==rhs) return true; return false; } bool operator>=(const fraction<T>& rhs) const { if(*this>rhs) return true; if(*this==rhs) return true; return false; } T getNum() const { return numerator; } T getDen() const { return denominator; } void setNum(T num) { numerator = num; reduce(); } void setDen(T den) { denominator = den; reduce(); } void setFrac(T num, T den) { numerator = num; denominator = den; reduce(); } }; template<class T> std::ostream& operator<<(std::ostream& os, fraction<T>& f) { os<<f.getNum()<<'/'<<f.getDen(); return os; } template<class T> class Matrix{ protected: int rows; int cols; T* data; public: Matrix<T>() { } Matrix<T>(int numRows, int numCols) { rows = numRows; cols = numCols; data = new T[rows*cols]; } ~Matrix<T>() { delete[] data; } int getRows() const { return rows; } int getCols() const { return cols; } void setEntry(const int row, const int col, const T& rhs) { data[row*(rows+1)+col] = rhs; } T getEntry(int row, int col) const { return data[row*(rows+1)+col]; } void reSize(int newRows, int newCols) { delete[] data; rows = newRows; cols = newCols; data = new T[rows*cols]; } }; template<class T> class AugmentedMatrix : public Matrix<T>{ public: AugmentedMatrix<T>(int numRows) : Matrix<T>(numRows,numRows+1) { } void reSize(int newRows) { reSize(newRows,newRows+1); } void solve() { T divider; for(int currRow=0; currRow<rows; ++currRow) { divider = data[currRow*cols+currRow]; for(int col=0; col<cols; ++col) { data[currRow*cols+col]/=divider; } // now clear all lower rows for(int clearRow = currRow+1; clearRow<rows; ++clearRow) { divider = data[clearRow*cols+currRow]/data[currRow*cols+currRow]; for(int col=0; col<cols; ++col) { data[clearRow*cols+col]-=(divider*data[currRow*cols+col]); } } } for(int currRow = rows-1; currRow>0; --currRow) { for(int clearRow = currRow-1; clearRow>=0; --clearRow) { divider = data[clearRow*cols+currRow]; for(int col=0; col<cols; ++col) { data[clearRow*cols+col]-=(divider*data[currRow*cols+col]); } } } } }; template<class T> std::ostream& operator<<(std::ostream& os, Matrix<T>& a) { for(int i=0; i<a.getRows();++i) { for(int j=0; j<=a.getCols();++j) { os<<a.getEntry(i,j)<<'\t'; } os<<std::endl; } return os; } template<class T> inline T gcd (T a, T b) { T t; while (!(b == T(0))) { t = a % b; a = b; b = t; } return a; }
[ "nikola.mrzljak@fer.hr" ]
nikola.mrzljak@fer.hr
629a56fbae25c968c7e369ca6f7beb07c2b6cb09
44275f10c058d27f293a8fba86d4c4c79d8b8e6c
/src/lexical.cpp
214f17d4acd54bbb5b91616f050476ef212308f1
[]
no_license
sultanyaril/interpreter
813528a9b3549bb653544140490c14b321a37342
7ec32b0de5054989d527c0c8652d4aef09dbae7c
refs/heads/main
2023-04-09T04:45:54.126208
2021-04-30T16:33:11
2021-04-30T16:33:11
344,024,857
0
0
null
null
null
null
UTF-8
C++
false
false
2,390
cpp
#include <lexical.h> Lexem *get_oper(string & codeline, int & i) { for (int op = 0; op < NUMBER_OF_OPS; op++) { string subcodeline = codeline.substr(i, OPERTEXT[op].size()); if (OPERTEXT[op] == subcodeline) { i += OPERTEXT[op].size(); if (subcodeline == "if" || subcodeline == "else" || subcodeline == "while" || subcodeline == "endwhile" || subcodeline == "endif" || subcodeline == "function") return new Goto(static_cast<OPERATOR>(op)); return new Oper(subcodeline); } } return NULL; } Lexem *get_num(string &codeline, int & i) { if ((codeline[i] <= '9') and (codeline[i] >= '0')) { int numb = 0; while ((i < codeline.size()) and (codeline[i] <= '9') and (codeline[i] >= '0')) { numb = numb * 10 + codeline[i] - '0'; i++; } return new Number(numb); } return NULL; } Lexem *get_var(string & codeline, int & i) { if (((codeline[i] >= 'a') and (codeline[i] <= 'z')) or ((codeline[i] >= 'A') and (codeline[i] <= 'Z'))) { string name = ""; while ( (i < codeline.size()) and ( ((codeline[i] >= 'a') and (codeline[i] <= 'z')) or ((codeline[i] >= 'A') and (codeline[i] <= 'Z')) or ((codeline[i] >= '1') and (codeline[i] <= '9')) or (codeline[i] == '_') ) ) { name += codeline[i]; i++; } return new Variable(name); } return NULL; } vector<Lexem *> parseLexem(string & codeline) { vector<Lexem *> answ; for (int i = 0; i < codeline.size();) { if ((codeline[i] == ' ') or (codeline[i] == '\t') or (codeline[i] == '\n')) { i++; continue; } Lexem *lexem; lexem = get_oper(codeline, i); if (lexem != NULL) { answ.push_back(lexem); continue; } lexem = get_num(codeline, i); if (lexem != NULL) { answ.push_back(lexem); continue; } lexem = get_var(codeline, i); if (lexem != NULL) { answ.push_back(lexem); continue; } i++; } return answ; }
[ "sultanyaril@gmail.com" ]
sultanyaril@gmail.com
3ff198c6ff51a01c5e5376d456fceb400880efc0
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/09_16380_9.cpp
8ef2a298c89c956bd8ad7edf69e30ebb43657d56
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
859
cpp
#include<iostream> #include<list> #include<algorithm> #include<windows.h> #include<string> #include<dos.h> #include "math.h" using namespace std; int next(int num) { int mainarray[10]={0}; int num1; num1=num; int index; while(num1 != 0) { index = num1%10; mainarray[index]++; num1 /= 10; } while(1) { num++; int num2 = num; int checkarray[10] ={0}; while(num2!=0) { int index = num2%10; checkarray[index]++; num2/=10; } int flag=0; for(int i=1;i<=9;i++) { if(mainarray[i]!=checkarray[i]) { flag=1; break; } } if(flag==0) return num; } } int main(){ int nofinputs; cin>>nofinputs; for(int i=0;i<nofinputs;i++) { int num; cin>>num; int x= next(num); cout<<"Case #"<<i+1<<": "<<x<<endl; } return 0; }
[ "nikola.mrzljak@fer.hr" ]
nikola.mrzljak@fer.hr
67cf7124d5b6b0f9c6fc181e94e5a93333d9c92d
41f8be8ecd6a6b939f3d846a0cc0919ab2c8d638
/project/changeTheAPPColor/main/mainwindow.cpp
bd8a63164881efa4aa6d3ce2e07031c91cf3c057
[]
no_license
lsy1599/WorkSpace
4ca5132c7ebd2b3a9e9f2fdab5e13d69a51e28fc
680d03ddb6e35a22a43e103116d2949044cc4e02
refs/heads/master
2020-05-14T15:11:16.909045
2017-02-21T07:24:44
2017-02-21T07:24:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
329
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QToolButton> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->pushButton-> setAutoDefault(false); ui->pushButton->setText(tr("hello")); } MainWindow::~MainWindow() { delete ui; }
[ "qiankun@nfschina.com" ]
qiankun@nfschina.com
8f18c507803a8e48adcf98c4a96e5d79d90fbfed
e12d90df109ec398b42394e1e47c238853d4e4d4
/puru/Player.h
cead43cd2977a80e71d84fbe41eef7353567bca7
[]
no_license
Zwiterrion/Puru-SFML
82708f213c6d3eb42ef9efac3665641eb32bcad7
a13df7516ee52d6e31e8b3b5f03da969c2ae5378
refs/heads/master
2020-05-20T09:37:30.499799
2014-05-23T15:14:54
2014-05-23T15:14:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
700
h
// // Player.h // THE_PURU // // Created by sayw00t on 24/02/2014. // Copyright (c) 2014 sayw00t. All rights reserved. // #ifndef __THE_PURU__Player__ #define __THE_PURU__Player__ #include <iostream> #include "Case.h" #include "Position.h" class Player : public Case{ public: Player(); virtual ~Player(); Position get_position(); void setVie(int nb); void deplacement(int x, int y); void set_position(int x, int y); int getVie() const; void move_N(); void move_NE(); void move_E(); void move_SE(); void move_S(); void move_SO(); void move_O(); void move_NO(); private: int m_vie; }; #endif /* defined(__THE_PURU__Player__) */
[ "etianne@info-spadax.iut.bx1" ]
etianne@info-spadax.iut.bx1
83c2a8500c300725ffc2a9405fe7ea956cc53921
5c1d53b106586ff07bb9e62d8b09970a44c7149e
/college/seit/TERMSEM2/dsf/mad/TREEIMAG.CPP
a508c5c332bda7c39f1d697c5ca9f2488142793c
[]
no_license
knotverygood/CollegeCode
93de0021cc601989dbded8dee0d686ece15a77d3
dc96f63d7a635942ce519ff42d53b8da93c63a64
refs/heads/master
2020-12-29T03:19:40.111697
2011-07-01T06:41:48
2011-07-01T06:41:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,776
cpp
#include<iostream.h> #include<fstream.h> #include<process.h> #include<graphics.h> #include<conio.h> #include<stdio.h> #include<string.h> #include<dos.h> #include<stdlib.h> struct node { char a[10]; node*lt,*rt; }; char ch; void gettree(node*trev,int x,int y) { gotoxy(x,y); fflush(stdin); gets(trev->a); gotoxy(1,25); printf("want to enter the left node to %6s (y/n) \b",trev->a); fflush(stdin); ch=getche(); if(ch=='y'||ch=='Y') { gotoxy(x-1,y+1); printf("/"); gotoxy(x-2,y+2); printf("/"); node*temp; temp=(node*)malloc(sizeof(node)); trev->lt=temp; gettree(temp,x-3,y+3); } else trev->lt=NULL; gotoxy(1,25); printf("want to enter the right node to %6s (y/n) \b",trev->a); fflush(stdin); ch=getche(); if(ch=='y'||ch=='Y') { gotoxy(x+1,y+1); printf("\\"); gotoxy(x+2,y+2); printf("\\"); node*temp; temp=(node*)malloc(sizeof(node)); trev->rt=temp; gettree(temp,x+3,y+3); } else trev->rt=NULL; } void showtree(node*trev,int x,int y) { gotoxy(x,y); fflush(stdin); puts(trev->a); if(trev->lt!=NULL) { gotoxy(x-1,y+1); printf("/"); gotoxy(x-2,y+2); printf("/"); showtree(trev->lt,x-3,y+3); } if(trev->rt!=NULL) { gotoxy(x+1,y+1); printf("\\"); gotoxy(x+2,y+2); printf("\\"); showtree(trev->rt,x+3,y+3); } } void createig(node*trev,node*trev1) { strcpy(trev1->a,trev->a); trev1->lt=NULL; trev1->rt=NULL; if(trev->lt!=NULL) { trev1->rt=new node; createig(trev->lt,trev1->rt); } if(trev->rt!=NULL) { trev1->lt=new node; createig(trev->rt,trev1->lt); } } void main() { node*root,*root1; clrscr(); gotoxy(1,25); cout<<"enter the tree"; root=new node; gettree(root,40,1); cout<<"the tree loaded"; sound(200); delay(1000); nosound(); getch(); getch(); clrscr(); showtree(root,40,10); getch(); root1=new node; createig(root,root1); clrscr(); showtree(root1,40,10); getch(); }
[ "ahuja.madhur@gmail.com" ]
ahuja.madhur@gmail.com
4c0cff9d7e8ff060fc9c63e91639b970bc25c263
b2b298f4f3205e16e0491b26f81df7e352dddc7a
/include/opendis/Environment.h
d34bf9bfaa4327c703bf75f3dc18507e60653f9e
[]
no_license
mustafaemre06/tools
9e20ded4fb34a5494e15a9f630952133e4c15ec0
7135c1376b643d7d3730fb180dafa53dfb2cefe5
refs/heads/master
2020-12-12T06:23:53.718215
2017-07-05T14:55:58
2017-07-05T14:55:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,432
h
#ifndef ENVIRONMENT_H #define ENVIRONMENT_H #include <DIS/DataStream.h> #include <DIS/msLibMacro.h> namespace DIS { // Section 5.2.40. Information about a geometry, a state associated with a geometry, a bounding volume, or an associated entity ID. NOTE: this class requires hand coding. // Copyright (c) 2007-2012, MOVES Institute, Naval Postgraduate School. All rights reserved. // Licensed under the BSD open source license. See http://www.movesinstitute.org/licenses/bsd.html // // @author DMcG, jkg class EXPORT_MACRO Environment { protected: /** Record type */ unsigned int _environmentType; /** length, in bits */ unsigned char _length; /** Identify the sequentially numbered record index */ unsigned char _index; /** padding */ unsigned char _padding1; /** Geometry or state record */ unsigned char _geometry; /** padding to bring the total size up to a 64 bit boundry */ unsigned char _padding2; public: Environment(); virtual ~Environment(); virtual void marshal(DataStream& dataStream) const; virtual void unmarshal(DataStream& dataStream); unsigned int getEnvironmentType() const; void setEnvironmentType(unsigned int pX); unsigned char getLength() const; void setLength(unsigned char pX); unsigned char getIndex() const; void setIndex(unsigned char pX); unsigned char getPadding1() const; void setPadding1(unsigned char pX); unsigned char getGeometry() const; void setGeometry(unsigned char pX); unsigned char getPadding2() const; void setPadding2(unsigned char pX); virtual int getMarshalledSize() const; bool operator ==(const Environment& rhs) const; }; } #endif // Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // 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.
[ "tim.tisler@digitalglobe.com" ]
tim.tisler@digitalglobe.com
5d256fbc963c97ae29a77e0550eb9a9fd096633c
851047b48314011afab311c7089188044ebffcab
/src/chainparamsbase.cpp
12b560d762c8d870764ae18e082ec999e18279a7
[ "MIT" ]
permissive
splashgroup/splashfarms-master
25161f6e062a67dbe8a2c7ba030dd41faa9b212d
9cbf1246f46b71c657e032dd53cde1a68d06fa9f
refs/heads/master
2020-03-29T10:18:50.424689
2018-09-22T17:03:10
2018-09-22T17:03:10
149,798,603
0
0
null
null
null
null
UTF-8
C++
false
false
2,833
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2016-2017 The SPLASHFARMS developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparamsbase.h" #include "util.h" #include <assert.h> #include <boost/assign/list_of.hpp> using namespace boost::assign; /** * Main network */ class CBaseMainParams : public CBaseChainParams { public: CBaseMainParams() { networkID = CBaseChainParams::MAIN; nRPCPort = 27612; } }; static CBaseMainParams mainParams; /** * Testnet (v3) */ class CBaseTestNetParams : public CBaseMainParams { public: CBaseTestNetParams() { networkID = CBaseChainParams::TESTNET; nRPCPort = 51475; strDataDir = "testnet4"; } }; static CBaseTestNetParams testNetParams; /* * Regression test */ class CBaseRegTestParams : public CBaseTestNetParams { public: CBaseRegTestParams() { networkID = CBaseChainParams::REGTEST; strDataDir = "regtest"; } }; static CBaseRegTestParams regTestParams; /* * Unit test */ class CBaseUnitTestParams : public CBaseMainParams { public: CBaseUnitTestParams() { networkID = CBaseChainParams::UNITTEST; strDataDir = "unittest"; } }; static CBaseUnitTestParams unitTestParams; static CBaseChainParams* pCurrentBaseParams = 0; const CBaseChainParams& BaseParams() { assert(pCurrentBaseParams); return *pCurrentBaseParams; } void SelectBaseParams(CBaseChainParams::Network network) { switch (network) { case CBaseChainParams::MAIN: pCurrentBaseParams = &mainParams; break; case CBaseChainParams::TESTNET: pCurrentBaseParams = &testNetParams; break; case CBaseChainParams::REGTEST: pCurrentBaseParams = &regTestParams; break; case CBaseChainParams::UNITTEST: pCurrentBaseParams = &unitTestParams; break; default: assert(false && "Unimplemented network"); return; } } CBaseChainParams::Network NetworkIdFromCommandLine() { bool fRegTest = GetBoolArg("-regtest", false); bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet && fRegTest) return CBaseChainParams::MAX_NETWORK_TYPES; if (fRegTest) return CBaseChainParams::REGTEST; if (fTestNet) return CBaseChainParams::TESTNET; return CBaseChainParams::MAIN; } bool SelectBaseParamsFromCommandLine() { CBaseChainParams::Network network = NetworkIdFromCommandLine(); if (network == CBaseChainParams::MAX_NETWORK_TYPES) return false; SelectBaseParams(network); return true; } bool AreBaseParamsConfigured() { return pCurrentBaseParams != NULL; }
[ "vangyangpao@gmail.com" ]
vangyangpao@gmail.com
35af97ce5ead0856ef6cc0372146a195dc3dfd5d
03c6f14835bab9ce6bae28834a851ce044ca3d73
/Forelesning_2_Individuell_Arduinopakke/PLab-Analog-Buzzer-Continous.ino
9d6be2ac53577d673cbc70e83711d3166244de81
[]
no_license
IDI-PLab/Lecture-examples
4e466b63b88e286469a5026ad82997b3164cc883
f321bca3da10ecbbdfa9b2bb17a697d33dd59304
refs/heads/master
2021-01-17T13:34:10.087584
2017-03-21T15:21:52
2017-03-21T15:21:52
29,125,706
5
8
null
null
null
null
UTF-8
C++
false
false
996
ino
/* Reads an analog input on pin 0 and outputs a square wave with a frequency determined by the analog input. Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground. The same code works for photoresistor setup on Pin A0. Dag Svanæs, IDI, NTNU, 2015 This example code is in the public domain. */ int speakerOut = 9; // Put speaker through 220 ohm on pin 9. int frequency = 0; void setup() { pinMode(speakerOut, OUTPUT); } // Function to produce one square pulse of a // given frequency on a given pin: void playOneSquarePulse(int pin, int freq) { long int pulseLength = 500000 / freq; digitalWrite(pin, HIGH); delayMicroseconds(pulseLength); digitalWrite(pin, LOW); delayMicroseconds(pulseLength); } void loop() { // read the input on analog pin 0: int sensorValue = analogRead(A0); // Map sensor value 0..1023 to 100..3169 Hz. frequency = 100 + 3 * (sensorValue); playOneSquarePulse(speakerOut, frequency); }
[ "terjero@idi.ntnu.no" ]
terjero@idi.ntnu.no
c50e758fdb6715bab952d943e7640f19f1c3259f
b84719d7e648d7afee61d19dc62dd966c1c61c80
/include/importwizard.h
245af626380670d1b4489d7184e2523bb0ca0f4a
[ "MIT" ]
permissive
chipgw/depthview
45d6ce21fb23e9b4001adab3d069a252aa66206d
188a18df2758b8ca0416bdd1fb39bab838abc93d
refs/heads/master
2021-01-10T18:44:24.408915
2016-01-30T02:48:49
2016-01-30T02:48:49
8,889,302
1
0
null
null
null
null
UTF-8
C++
false
false
599
h
#pragma once #include <QWizard> #include <QDir> class ImportWizard : public QWizard { Q_OBJECT const QDir &currentDirectory; public: explicit ImportWizard(const QDir &directory, QWidget *parent = 0); int nextId() const; private: enum { Page_Intro, Page_SelectFile, Page_SideBySide, Page_TopBottom, Page_Seperate, Page_Conclusion }; QWizardPage *createIntroPage(); QWizardPage *createSelectFilePage(); QWizardPage *createSideBySidePage(); QWizardPage *createTopBottomPage(); QWizardPage *createSeperatePage(); QWizardPage *createConclusionPage(); };
[ "gw.chip.gw@gmail.com" ]
gw.chip.gw@gmail.com
bdc2376ce23007b37733b6f0ec61b5589a8f843b
94a70c240ca95b67368fc6fd41d3a4d942b68c44
/src/core/BSPParser.cpp
3f5711ce0524fc9c8c6ccb80afcaaec32b57a715
[ "BSD-2-Clause" ]
permissive
harubaru/AquaEngine
4197a8b792080e609859eebdd5a070ca6a5a84ae
12253d0de8a41071c0d1b001e39d64e1042a2ea7
refs/heads/master
2022-03-21T15:45:04.673719
2019-12-16T19:17:34
2019-12-16T19:17:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,578
cpp
#include <core/BSPParser.h> void BSPParser::Load(const std::string &path) { std::ifstream file(path, std::ios::in | std::ios::ate | std::ios::binary); unsigned char* data; size_t data_len; /* Get file size */ file.seekg(0, file.end); data_len = file.tellg(); file.seekg(0, file.beg); /* Read file into a buffer */ data = new unsigned char[data_len]; file.read((char*)data, data_len); file.close(); bool success = true; if (!processHeader(data, data_len)) success = false; delete data; } bool BSPParser::processHeader(unsigned char* data, size_t data_len) { bsp_header_t* header; if (sizeof(*header) > data_len) { LOG("Invalid BSP file\n"); return false; } /* Set header struct to point to its location in the file */ header = (bsp_header_t*)(data); if (header->file_identifier != BSP_FILE_IDENTIFIER) { LOG("Invalid BSP file identifier.\n"); return false; } if (header->version < 17 || header->version > 29) { LOG("Invalid BSP file version.\n"); return false; } for (int i=0; i < BSP_TOTAL_LUMPS; i++) processLump(data, data_len, i, &header->lumps[i]); return true; } void BSPParser::processLump(unsigned char* data, size_t data_len, uint32_t lump_type, bsp_lump_t* lump) { /* Make sure the location the lump indicates data is in is inside the file */ if (lump->file_offset >= data_len) { LOG("Not enough data in buffer to hold header\n"); } switch(lump_type) { case LUMP_VERTEXES: processVertexLump(data, data_len, lump); break; case LUMP_EDGES: processEdgeLump(data, data_len, lump); break; case LUMP_SURFEDGES: processSurfedgeLump(data, data_len, lump); break; case LUMP_FACES: processFaceLump(data, data_len, lump); break; case LUMP_ENTITIES: case LUMP_PLANES: case LUMP_TEXDATA: case LUMP_VISIBILITY: case LUMP_NODES: case LUMP_TEXINFO: case LUMP_LIGHTING: case LUMP_OCCLUSION: case LUMP_LEAFS: case LUMP_FACEIDS: case LUMP_MODELS: case LUMP_WORLDLIGHTS: case LUMP_LEAFFACES: case LUMP_LEAFBRUSHES: case LUMP_BRUSHES: case LUMP_BRUSHSIDES: case LUMP_AREAS: case LUMP_AREAPORTALS: //case LUMP_PORTALS: //case LUMP_UNUSED0: case LUMP_PROPCOLLISION: //case LUMP_CLUSTERS: //case LUMP_UNUSED1: case LUMP_PROPHULLS: //case LUMP_PORTALVERTS: //case LUMP_UNUSED2: case LUMP_PROPHULLVERTS: //case LUMP_CLUSTERPORTALS: //case LUMP_UNUSED3: case LUMP_PROPTRIS: case LUMP_DISPINFO: case LUMP_ORIGINALFACES: case LUMP_PHYSDISP: case LUMP_PHYSCOLLIDE: case LUMP_VERTNORMALS: case LUMP_VERTNORMALINDICES: case LUMP_DISP_LIGHTMAP_ALPHAS: case LUMP_DISP_VERTS: case LUMP_DISP_LIGHTMAP_SAMPLE_POSITIONS: case LUMP_GAME_LUMP: case LUMP_LEAFWATERDATA: case LUMP_PRIMITIVES: case LUMP_PRIMVERTS: case LUMP_PRIMINDICES: case LUMP_PAKFILE: case LUMP_CLIPPORTALVERTS: case LUMP_CUBEMAPS: case LUMP_TEXDATA_STRING_DATA: case LUMP_TEXDATA_STRING_TABLE: case LUMP_OVERLAYS: case LUMP_LEAFMINDISTTOWATER: case LUMP_FACE_MACRO_TEXTURE_INFO: case LUMP_DISP_TRIS: case LUMP_PHYSCOLLIDESURFACE: //case LUMP_PROP_BLOB: case LUMP_WATEROVERLAYS: case LUMP_LIGHTMAPPAGES: case LUMP_LEAF_AMBIENT_INDEX_HDR: case LUMP_LIGHTMAPPAGEINFOS: case LUMP_LEAF_AMBIENT_INDEX: case LUMP_LIGHTING_HDR: case LUMP_WORLDLIGHTS_HDR: case LUMP_LEAF_AMBIENT_LIGHTING_HDR: case LUMP_LEAF_AMBIENT_LIGHTING: case LUMP_XZIPPAKFILE: case LUMP_FACES_HDR: case LUMP_MAP_FLAGS: case LUMP_OVERLAY_FADES: case LUMP_DISP_MULTIBLEND: break; default: LOG("Encountered unknown lump type.\n"); } } void BSPParser::processVertexLump(unsigned char* data, size_t data_len, bsp_lump_t* lump) { bsp_vertex_t* verts; size_t number_verts; if (data_len < lump->file_offset + lump->size) LOG("Vertex lump doesn't seem to fit in the data buffer?\n"); if ((lump->size % sizeof(*verts)) != 0) LOG("Vertex lumps are uneven\n"); verts = (bsp_vertex_t*)(data + lump->file_offset); number_verts = lump->size / sizeof(*verts); for (size_t i = 0; i < number_verts; i++) vertices.push_back({ verts[i].x, verts[i].y, verts[i].z }); } void BSPParser::processEdgeLump(unsigned char* data, size_t data_len, bsp_lump_t* lump) { bsp_edge_t* edges; size_t number_edges; if (data_len < lump->file_offset + lump->size) LOG("Edge lump doesn't seem to fit in the data buffer?\n"); if ((lump->size % sizeof(*edges)) != 0) LOG("Edge lumps are uneven\n"); edges = (bsp_edge_t*)(data + lump->file_offset); number_edges = lump->size / sizeof(*edges); for (size_t i = 0; i < number_edges; i++) map_edges.push_back(edges[i]); } void BSPParser::processSurfedgeLump(unsigned char* data, size_t data_len, bsp_lump_t* lump) { bsp_surfedge_t* surfedges; size_t number_surfedges; if (data_len < lump->file_offset + lump->size) LOG("Surfedge lump doesn't seem to fit in the data buffer?\n"); if ((lump->size % sizeof(*surfedges)) != 0) LOG("Surfedge lumps are uneven\n"); surfedges = (bsp_surfedge_t*)(data + lump->file_offset); number_surfedges = lump->size / sizeof(*surfedges); for (size_t i = 0; i < number_surfedges; i++) { map_surfedges.push_back(surfedges[i]); } } void BSPParser::processFaceLump(unsigned char* data, size_t data_len, bsp_lump_t* lump) { bsp_face_t* faces; size_t number_faces; if (data_len < lump->file_offset + lump->size) LOG("Face lump doesn't seem to fit in the data buffer?\n"); if ((lump->size % sizeof(*faces)) != 0) LOG("Face lumps are uneven\n"); faces = (bsp_face_t*)(data + lump->file_offset); number_faces = lump->size / sizeof(*faces); for (size_t i = 0; i < number_faces; i++) { map_faces.push_back(faces[i]); } }
[ "tone121@cox.net" ]
tone121@cox.net
ec5695d88c9c35e5c44551c90cf4a179d0cde0d2
6230f26d35774e26c29e0ed40c7100da515ab158
/src/script/sign.cpp
e40494596c89787940890f9c74f2f921881817a0
[ "MIT" ]
permissive
CoinAge-DAO/solari
5dc8e8f064a7a9bacbbf090d1e618bd8ad7a7464
2d6cdf02c9a9e5ceb4f72364f81fce4c34e6c856
refs/heads/master
2020-05-18T00:02:41.459253
2015-04-11T18:50:01
2015-04-11T18:50:01
33,024,449
0
0
null
null
null
null
UTF-8
C++
false
false
9,605
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core Developers // Copyright (c) 2015 Solarminx // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "script/sign.h" #include "primitives/transaction.h" #include "key.h" #include "keystore.h" #include "script/standard.h" #include "uint256.h" #include <boost/foreach.hpp> using namespace std; typedef vector<unsigned char> valtype; TransactionSignatureCreator::TransactionSignatureCreator(const CKeyStore* keystoreIn, const CTransaction* txToIn, unsigned int nInIn, int nHashTypeIn) : BaseSignatureCreator(keystoreIn), txTo(txToIn), nIn(nInIn), nHashType(nHashTypeIn), checker(txTo, nIn) {} bool TransactionSignatureCreator::CreateSig(std::vector<unsigned char>& vchSig, const CKeyID& address, const CScript& scriptCode) const { CKey key; if (!keystore->GetKey(address, key)) return false; uint256 hash = SignatureHash(scriptCode, *txTo, nIn, nHashType); if (!key.Sign(hash, vchSig)) return false; vchSig.push_back((unsigned char)nHashType); return true; } static bool Sign1(const CKeyID& address, const BaseSignatureCreator& creator, const CScript& scriptCode, CScript& scriptSigRet) { vector<unsigned char> vchSig; if (!creator.CreateSig(vchSig, address, scriptCode)) return false; scriptSigRet << vchSig; return true; } static bool SignN(const vector<valtype>& multisigdata, const BaseSignatureCreator& creator, const CScript& scriptCode, CScript& scriptSigRet) { int nSigned = 0; int nRequired = multisigdata.front()[0]; for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++) { const valtype& pubkey = multisigdata[i]; CKeyID keyID = CPubKey(pubkey).GetID(); if (Sign1(keyID, creator, scriptCode, scriptSigRet)) ++nSigned; } return nSigned==nRequired; } /** * Sign scriptPubKey using signature made with creator. * Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed), * unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script. * Returns false if scriptPubKey could not be completely satisfied. */ static bool SignStep(const BaseSignatureCreator& creator, const CScript& scriptPubKey, CScript& scriptSigRet, txnouttype& whichTypeRet) { scriptSigRet.clear(); vector<valtype> vSolutions; if (!Solver(scriptPubKey, whichTypeRet, vSolutions)) return false; CKeyID keyID; switch (whichTypeRet) { case TX_NONSTANDARD: case TX_NULL_DATA: return false; case TX_PUBKEY: keyID = CPubKey(vSolutions[0]).GetID(); return Sign1(keyID, creator, scriptPubKey, scriptSigRet); case TX_PUBKEYHASH: keyID = CKeyID(uint160(vSolutions[0])); if (!Sign1(keyID, creator, scriptPubKey, scriptSigRet)) return false; else { CPubKey vch; creator.KeyStore().GetPubKey(keyID, vch); scriptSigRet << ToByteVector(vch); } return true; case TX_SCRIPTHASH: return creator.KeyStore().GetCScript(uint160(vSolutions[0]), scriptSigRet); case TX_MULTISIG: scriptSigRet << OP_0; // workaround CHECKMULTISIG bug return (SignN(vSolutions, creator, scriptPubKey, scriptSigRet)); } return false; } bool ProduceSignature(const BaseSignatureCreator& creator, const CScript& fromPubKey, CScript& scriptSig) { txnouttype whichType; if (!SignStep(creator, fromPubKey, scriptSig, whichType)) return false; if (whichType == TX_SCRIPTHASH) { // Solver returns the subscript that need to be evaluated; // the final scriptSig is the signatures from that // and then the serialized subscript: CScript subscript = scriptSig; txnouttype subType; bool fSolved = SignStep(creator, subscript, scriptSig, subType) && subType != TX_SCRIPTHASH; // Append serialized subscript whether or not it is completely signed: scriptSig << static_cast<valtype>(subscript); if (!fSolved) return false; } // Test solution return VerifyScript(scriptSig, fromPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker()); } bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, int nHashType) { assert(nIn < txTo.vin.size()); CTxIn& txin = txTo.vin[nIn]; CTransaction txToConst(txTo); TransactionSignatureCreator creator(&keystore, &txToConst, nIn, nHashType); return ProduceSignature(creator, fromPubKey, txin.scriptSig); } bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType) { assert(nIn < txTo.vin.size()); CTxIn& txin = txTo.vin[nIn]; assert(txin.prevout.n < txFrom.vout.size()); const CTxOut& txout = txFrom.vout[txin.prevout.n]; return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType); } static CScript PushAll(const vector<valtype>& values) { CScript result; BOOST_FOREACH(const valtype& v, values) result << v; return result; } static CScript CombineMultisig(const CScript& scriptPubKey, const BaseSignatureChecker& checker, const vector<valtype>& vSolutions, const vector<valtype>& sigs1, const vector<valtype>& sigs2) { // Combine all the signatures we've got: set<valtype> allsigs; BOOST_FOREACH(const valtype& v, sigs1) { if (!v.empty()) allsigs.insert(v); } BOOST_FOREACH(const valtype& v, sigs2) { if (!v.empty()) allsigs.insert(v); } // Build a map of pubkey -> signature by matching sigs to pubkeys: assert(vSolutions.size() > 1); unsigned int nSigsRequired = vSolutions.front()[0]; unsigned int nPubKeys = vSolutions.size()-2; map<valtype, valtype> sigs; BOOST_FOREACH(const valtype& sig, allsigs) { for (unsigned int i = 0; i < nPubKeys; i++) { const valtype& pubkey = vSolutions[i+1]; if (sigs.count(pubkey)) continue; // Already got a sig for this pubkey if (checker.CheckSig(sig, pubkey, scriptPubKey)) { sigs[pubkey] = sig; break; } } } // Now build a merged CScript: unsigned int nSigsHave = 0; CScript result; result << OP_0; // pop-one-too-many workaround for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++) { if (sigs.count(vSolutions[i+1])) { result << sigs[vSolutions[i+1]]; ++nSigsHave; } } // Fill any missing with OP_0: for (unsigned int i = nSigsHave; i < nSigsRequired; i++) result << OP_0; return result; } static CScript CombineSignatures(const CScript& scriptPubKey, const BaseSignatureChecker& checker, const txnouttype txType, const vector<valtype>& vSolutions, vector<valtype>& sigs1, vector<valtype>& sigs2) { switch (txType) { case TX_NONSTANDARD: case TX_NULL_DATA: // Don't know anything about this, assume bigger one is correct: if (sigs1.size() >= sigs2.size()) return PushAll(sigs1); return PushAll(sigs2); case TX_PUBKEY: case TX_PUBKEYHASH: // Signatures are bigger than placeholders or empty scripts: if (sigs1.empty() || sigs1[0].empty()) return PushAll(sigs2); return PushAll(sigs1); case TX_SCRIPTHASH: if (sigs1.empty() || sigs1.back().empty()) return PushAll(sigs2); else if (sigs2.empty() || sigs2.back().empty()) return PushAll(sigs1); else { // Recur to combine: valtype spk = sigs1.back(); CScript pubKey2(spk.begin(), spk.end()); txnouttype txType2; vector<vector<unsigned char> > vSolutions2; Solver(pubKey2, txType2, vSolutions2); sigs1.pop_back(); sigs2.pop_back(); CScript result = CombineSignatures(pubKey2, checker, txType2, vSolutions2, sigs1, sigs2); result << spk; return result; } case TX_MULTISIG: return CombineMultisig(scriptPubKey, checker, vSolutions, sigs1, sigs2); } return CScript(); } CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2) { TransactionSignatureChecker checker(&txTo, nIn); return CombineSignatures(scriptPubKey, checker, scriptSig1, scriptSig2); } CScript CombineSignatures(const CScript& scriptPubKey, const BaseSignatureChecker& checker, const CScript& scriptSig1, const CScript& scriptSig2) { txnouttype txType; vector<vector<unsigned char> > vSolutions; Solver(scriptPubKey, txType, vSolutions); vector<valtype> stack1; EvalScript(stack1, scriptSig1, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker()); vector<valtype> stack2; EvalScript(stack2, scriptSig2, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker()); return CombineSignatures(scriptPubKey, checker, txType, vSolutions, stack1, stack2); }
[ "chandradas@Chandras-MacBook-Air.local" ]
chandradas@Chandras-MacBook-Air.local
2d1e19b161486f047f70f13312386c8212f1b5d2
4daed53ef188fe57fc90771c9042dd137e306261
/WebKit/Source/WebKit/chromium/src/InspectorClientImpl.h
b16b6f46818c33ce4295e5f83a6a75c9b5e21d2c
[ "BSD-2-Clause", "Apache-2.0" ]
permissive
JavaScriptTesting/LJS
ece7d0537b514e06f7f6b26cb06a9ab4e6cd7e10
9818dbdb421036569fff93124ac2385d45d01c3a
refs/heads/master
2020-03-12T14:28:41.437178
2018-04-25T10:55:15
2018-04-25T10:55:15
130,668,210
1
0
null
null
null
null
UTF-8
C++
false
false
2,736
h
/* * Copyright (C) 2009 Google 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 Google 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. */ #ifndef InspectorClientImpl_h #define InspectorClientImpl_h #include "InspectorClient.h" #include "InspectorController.h" #include <wtf/OwnPtr.h> namespace WebKit { class WebDevToolsAgentClient; class WebDevToolsAgentImpl; class WebViewImpl; class InspectorClientImpl : public WebCore::InspectorClient { public: InspectorClientImpl(WebViewImpl*); ~InspectorClientImpl(); // InspectorClient methods: virtual void inspectorDestroyed(); virtual void openInspectorFrontend(WebCore::InspectorController*); virtual void closeInspectorFrontend(); virtual void bringFrontendToFront(); virtual void highlight(); virtual void hideHighlight(); virtual bool sendMessageToFrontend(const WTF::String&); virtual void updateInspectorStateCookie(const WTF::String&); virtual bool canClearBrowserCache(); virtual void clearBrowserCache(); virtual bool canClearBrowserCookies(); virtual void clearBrowserCookies(); private: WebDevToolsAgentImpl* devToolsAgent(); // The WebViewImpl of the page being inspected; gets passed to the constructor WebViewImpl* m_inspectedWebView; }; } // namespace WebKit #endif
[ "cumtcsgpf@gmail.com" ]
cumtcsgpf@gmail.com
0d1da1d0d26f0e8799fe9e8d4bcf706afad91d10
6f2496382ff79ea61cf19ac0371860a7ee3676bc
/src/particle_filter.cpp
962efb270913e91c2a3dc6ffad9ad3b5bd2aae38
[ "MIT" ]
permissive
nturumel/CarND-Kidnapped-Vehicle-Project
b3037a89998f87ac61dd6a636e050802637a0c58
79d4d502e6b6ee1704c662d33b53161e492d7cfe
refs/heads/master
2022-10-19T10:55:04.763612
2020-06-16T06:27:22
2020-06-16T06:27:22
272,379,967
0
0
null
null
null
null
UTF-8
C++
false
false
9,806
cpp
/** * particle_filter.cpp * * Created on: Dec 12, 2016 * Author: Tiffany Huang */ #include "particle_filter.h" #include <math.h> #include <algorithm> #include <iostream> #include <iterator> #include <numeric> #include <random> #include <string> #include <vector> #include <cmath> #include "helper_functions.h" #include <limits> #include <cfloat> #include <climits> #include <utility> using std::normal_distribution; std::default_random_engine gen; using std::string; using std::vector; void ParticleFilter::init(double x, double y, double theta, double std[]) { /** * TODO: Set the number of particles. Initialize all particles to * first position (based on estimates of x, y, theta and their uncertainties * from GPS) and all weights to 1. * TODO: Add random Gaussian noise to each particle. * NOTE: Consult particle_filter.h for more information about this method * (and others in this file). */ normal_distribution<double> dist_x(x, std[0]); normal_distribution<double> dist_y(y, std[1]); normal_distribution<double> dist_theta(theta, std[2]); num_particles = 1000; // TODO: Set the number of particles for(int i=0;i<num_particles;++i) { Particle p; p.id=i; p.x=dist_x(gen); p.y=dist_y(gen); p.theta=dist_theta(gen); particles.push_back(p); weights.push_back(1.00); } is_initialized=true; std::cout<<"Initialisation done"<<std::endl; return; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { /** * TODO: Add measurements to each particle and add random Gaussian noise. * NOTE: When adding noise you may find std::normal_distribution * and std::default_random_engine useful. * http://en.cppreference.com/w/cpp/numeric/random/normal_distribution * http://www.cplusplus.com/reference/random/default_random_engine/ */ // add noise normal_distribution<double> dist_x(0, std_pos[0]); normal_distribution<double> dist_y(0, std_pos[1]); normal_distribution<double> dist_theta(0, std_pos[2]); std::cout<<"Prediction step, num particles: "<<particles.size()<<std::endl; for(int i=0;i<num_particles;++i) { Particle current=particles[i]; // predict the noise double x=current.x+(velocity/yaw_rate)*(sin(current.theta+yaw_rate*delta_t)-sin(current.theta)); double y=current.y+(velocity/yaw_rate)*(-cos(current.theta+yaw_rate*delta_t)+cos(current.theta)); double theta=current.theta+yaw_rate*delta_t; x+=dist_x(gen); y+=dist_y(gen); theta+=dist_theta(gen); // assign it to the particle array particles[i].x=x; particles[i].y=y; particles[i].theta=theta; } return; } LandmarkObs findClosest(LandmarkObs observation,vector<LandmarkObs> predicted) { int distance=INT_MAX; int result; for(size_t i=0;i<predicted.size();++i) { if(distance>((predicted[i].x-observation.x)*(predicted[i].x-observation.x)+(predicted[i].y-observation.y)*(predicted[i].y-observation.y))) { distance=((predicted[i].x-observation.x)*(predicted[i].x-observation.x)+(predicted[i].y-observation.y)*(predicted[i].y-observation.y)); result=i; } } return predicted[result]; } void ParticleFilter::dataAssociation(vector<LandmarkObs> predicted, vector<LandmarkObs>& observations) { /** * TODO: Find the predicted measurement that is closest to each * observed measurement and assign the observed measurement to this * particular landmark. * NOTE: this method will NOT be called by the grading code. But you will * probably find it useful to implement this method and use it as a helper * during the updateWeights phase. */ // only assign id, that's it, don't update the x,y coordinate for(size_t i=0;i<observations.size();++i) { LandmarkObs closest=findClosest(observations[i],predicted); observations[i].id=closest.id; } } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const vector<LandmarkObs> &observations, const Map &map_landmarks) { /** * TODO: Update the weights of each particle using a mult-variate Gaussian * distribution. You can read more about this distribution here: * https://en.wikipedia.org/wiki/Multivariate_normal_distribution * NOTE: The observations are given in the VEHICLE'S coordinate system. * Your particles are located according to the MAP'S coordinate system. * You will need to transform between the two systems. Keep in mind that * this transformation requires both rotation AND translation (but no scaling). * The following is a good resource for the theory: * https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm * and the following is a good resource for the actual equation to implement * (look at equation 3.33) http://planning.cs.uiuc.edu/node99.html */ double normaliser= 1/(2*M_PI*std_landmark[0]*std_landmark[1]); for(int i=0;i<num_particles;++i) { Particle p = particles[i]; vector<LandmarkObs> predictions; for(auto & Landmark:map_landmarks.landmark_list) { bool withinRange=(sensor_range*sensor_range>=((p.x-Landmark.x_f)*(p.x-Landmark.x_f)+(p.y-Landmark.y_f)*(p.y-Landmark.y_f))); if(withinRange) { LandmarkObs l; l.id=Landmark.id_i; l.x=Landmark.x_f; l.y=Landmark.y_f; predictions.push_back(l); } } // transform vector<LandmarkObs> transformed_os; for(auto & observation:observations) { double t_x = cos(p.theta)*observation.x - sin(p.theta)*observation.y + p.x; double t_y = sin(p.theta)*observation.x + cos(p.theta)*observation.y + p.y; transformed_os.push_back(LandmarkObs{ observation.id, t_x, t_y }); } dataAssociation(predictions,transformed_os); particles[i].weight=1.0; for(auto & transformed:transformed_os) { for(auto & predicted:predictions) { if(transformed.id==predicted.id) { //std::cout<<"Tranformed: "<<transformed.x<<","<<transformed.y<<std::endl; //std::cout<<"predicted: "<<predicted.x<<","<<predicted.y<<std::endl; double xerror=pow(transformed.x-predicted.x,2)/(2*pow(std_landmark[0], 2)); double yerror=pow(transformed.y-predicted.y,2)/(2*pow(std_landmark[1], 2)); //std::cout<<"Sum: "<<xerror+yerror<<std::endl; double exponent=xerror+yerror; double error=exp(-exponent); //std::cout<<"Error: "<<error<<std::endl; particles[i].weight*= (normaliser* error); break; } } //std::cout<<"in here: "<<i<<" weight: "<<particles[i].weight<<std::endl; weights[i]=particles[i].weight; } } return; } void ParticleFilter::resample() { /** * TODO: Resample particles with replacement with probability proportional * to their weight. * NOTE: You may find std::discrete_distribution helpful here. * http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution */ // Step 1 Get all the weights and get the max weight double maxWeight=DBL_MIN; for(size_t i=0;i<weights.size();++i) { maxWeight=maxWeight>weights[i]?maxWeight:weights[i]; } // step two construct anpther vector and seed vector<Particle> resampled; double beta=0.0; srand( (unsigned)time( NULL ) ); int i=static_cast<int>((static_cast <float> (rand()) / static_cast <float> (RAND_MAX))*num_particles); for(int index=0;index<num_particles;++index) { beta=(static_cast <float> (rand()) / static_cast <float> (RAND_MAX))*2.0*maxWeight; //std::cout<<"We are in resample "<<"i: "<<i<<" beta: "<<beta<<std::endl; while (weights[i]<beta) { beta-=weights[i]; //std::cout<<"Value of beta: "<<beta<<std::endl; i=(i+1)%num_particles; // std::cout<<"value of i: "<<i<<std::endl; } resampled.push_back(particles[i]); } particles=resampled; return; } void ParticleFilter::SetAssociations(Particle& particle, const vector<int>& associations, const vector<double>& sense_x, const vector<double>& sense_y) { // particle: the particle to which assign each listed association, // and association's (x,y) world coordinates mapping // associations: The landmark id that goes along with each listed association // sense_x: the associations x mapping already converted to world coordinates // sense_y: the associations y mapping already converted to world coordinates particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; std::stringstream ss; copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseCoord(Particle best, string coord) { vector<double> v; if (coord == "X") { v = best.sense_x; } else { v = best.sense_y; } std::stringstream ss; copy(v.begin(), v.end(), std::ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; }
[ "nihar1912@live.com" ]
nihar1912@live.com
49a9493eb9f113e0bb1da6a7e8f414bb996e1f35
2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0
/fuzzedpackages/tmg/inst/include/magnet/math/spline.hpp
90f5eb1e951fa3fe5f0e5299362bd8fe9becdaa8
[]
no_license
akhikolla/testpackages
62ccaeed866e2194652b65e7360987b3b20df7e7
01259c3543febc89955ea5b79f3a08d3afe57e95
refs/heads/master
2023-02-18T03:50:28.288006
2021-01-18T13:23:32
2021-01-18T13:23:32
329,981,898
7
1
null
null
null
null
UTF-8
C++
false
false
9,205
hpp
/* dynamo:- Event driven molecular dynamics simulator http://www.dynamomd.org Copyright (C) 2011 Marcus N Campbell Bannerman <m.bannerman@gmail.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3 as published by the Free Software Foundation. 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 <http://www.gnu.org/licenses/>. */ #pragma once #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/vector_proxy.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/triangular.hpp> #include <boost/numeric/ublas/lu.hpp> #include <exception> namespace ublas = boost::numeric::ublas; namespace magnet { namespace math { class Spline : private std::vector<std::pair<double, double> > { public: //The boundary conditions available enum BC_type { FIXED_1ST_DERIV_BC, FIXED_2ND_DERIV_BC, PARABOLIC_RUNOUT_BC }; enum Spline_type { LINEAR, CUBIC }; //Constructor takes the boundary conditions as arguments, this //sets the first derivative (gradient) at the lower and upper //end points Spline(): _valid(false), _BCLow(FIXED_2ND_DERIV_BC), _BCHigh(FIXED_2ND_DERIV_BC), _BCLowVal(0), _BCHighVal(0), _type(CUBIC) {} typedef std::vector<std::pair<double, double> > base; typedef base::const_iterator const_iterator; //Standard STL read-only container stuff const_iterator begin() const { return base::begin(); } const_iterator end() const { return base::end(); } void clear() { _valid = false; base::clear(); _data.clear(); } size_t size() const { return base::size(); } size_t max_size() const { return base::max_size(); } size_t capacity() const { return base::capacity(); } bool empty() const { return base::empty(); } //Add a point to the spline, and invalidate it so its //recalculated on the next access inline void addPoint(double x, double y) { _valid = false; base::push_back(std::pair<double, double>(x,y)); } //Reset the boundary conditions inline void setLowBC(BC_type BC, double val = 0) { _BCLow = BC; _BCLowVal = val; _valid = false; } inline void setHighBC(BC_type BC, double val = 0) { _BCHigh = BC; _BCHighVal = val; _valid = false; } void setType(Spline_type type) { _type = type; _valid = false; } //Check if the spline has been calculated, then generate the //spline interpolated value double operator()(double xval) { if (!_valid) generate(); //Special cases when we're outside the range of the spline points if (xval <= x(0)) return lowCalc(xval); if (xval >= x(size()-1)) return highCalc(xval); //Check all intervals except the last one for (std::vector<SplineData>::const_iterator iPtr = _data.begin(); iPtr != _data.end()-1; ++iPtr) if ((xval >= iPtr->x) && (xval <= (iPtr+1)->x)) return splineCalc(iPtr, xval); return splineCalc(_data.end() - 1, xval); } private: ///////PRIVATE DATA MEMBERS struct SplineData { double x,a,b,c,d; }; //vector of calculated spline data std::vector<SplineData> _data; //Second derivative at each point ublas::vector<double> _ddy; //Tracks whether the spline parameters have been calculated for //the current set of points bool _valid; //The boundary conditions BC_type _BCLow, _BCHigh; //The values of the boundary conditions double _BCLowVal, _BCHighVal; Spline_type _type; ///////PRIVATE FUNCTIONS //Function to calculate the value of a given spline at a point xval inline double splineCalc(std::vector<SplineData>::const_iterator i, double xval) { const double lx = xval - i->x; return ((i->a * lx + i->b) * lx + i->c) * lx + i->d; } inline double lowCalc(double xval) { const double lx = xval - x(0); if (_type == LINEAR) return lx * _BCHighVal + y(0); const double firstDeriv = (y(1) - y(0)) / h(0) - 2 * h(0) * (_data[0].b + 2 * _data[1].b) / 6; switch(_BCLow) { case FIXED_1ST_DERIV_BC: return lx * _BCLowVal + y(0); case FIXED_2ND_DERIV_BC: return lx * lx * _BCLowVal + firstDeriv * lx + y(0); case PARABOLIC_RUNOUT_BC: return lx * lx * _ddy[0] + lx * firstDeriv + y(0); } throw std::runtime_error("Unknown BC"); } inline double highCalc(double xval) { const double lx = xval - x(size() - 1); if (_type == LINEAR) return lx * _BCHighVal + y(size() - 1); const double firstDeriv = 2 * h(size() - 2) * (_ddy[size() - 2] + 2 * _ddy[size() - 1]) / 6 + (y(size() - 1) - y(size() - 2)) / h(size() - 2); switch(_BCHigh) { case FIXED_1ST_DERIV_BC: return lx * _BCHighVal + y(size() - 1); case FIXED_2ND_DERIV_BC: return lx * lx * _BCHighVal + firstDeriv * lx + y(size() - 1); case PARABOLIC_RUNOUT_BC: return lx * lx * _ddy[size()-1] + lx * firstDeriv + y(size() - 1); } throw std::runtime_error("Unknown BC"); } //These just provide access to the point data in a clean way inline double x(size_t i) const { return operator[](i).first; } inline double y(size_t i) const { return operator[](i).second; } inline double h(size_t i) const { return x(i+1) - x(i); } //Invert a arbitrary matrix using the boost ublas library template<class T> bool InvertMatrix(ublas::matrix<T> A, ublas::matrix<T>& inverse) { using namespace ublas; // create a permutation matrix for the LU-factorization permutation_matrix<std::size_t> pm(A.size1()); // perform LU-factorization int res = lu_factorize(A,pm); if( res != 0 ) return false; // create identity matrix of "inverse" inverse.assign(ublas::identity_matrix<T>(A.size1())); // backsubstitute to get the inverse lu_substitute(A, pm, inverse); return true; } //This function will recalculate the spline parameters and store //them in _data, ready for spline interpolation void generate() { if (size() < 2) throw std::runtime_error("Spline requires at least 2 points"); //If any spline points are at the same x location, we have to //just slightly seperate them { bool testPassed(false); while (!testPassed) { testPassed = true; std::sort(base::begin(), base::end()); for (base::iterator iPtr = base::begin(); iPtr != base::end() - 1; ++iPtr) if (iPtr->first == (iPtr+1)->first) { if ((iPtr+1)->first != 0) (iPtr+1)->first += (iPtr+1)->first * std::numeric_limits<double>::epsilon() * 10; else (iPtr+1)->first = std::numeric_limits<double>::epsilon() * 10; testPassed = false; break; } } } const size_t e = size() - 1; switch (_type) { case LINEAR: { _data.resize(e); for (size_t i(0); i < e; ++i) { _data[i].x = x(i); _data[i].a = 0; _data[i].b = 0; _data[i].c = (y(i+1) - y(i)) / (x(i+1) - x(i)); _data[i].d = y(i); } break; } case CUBIC: { ublas::matrix<double> A(size(), size()); for (size_t yv(0); yv <= e; ++yv) for (size_t xv(0); xv <= e; ++xv) A(xv,yv) = 0; for (size_t i(1); i < e; ++i) { A(i-1,i) = h(i-1); A(i,i) = 2 * (h(i-1) + h(i)); A(i+1,i) = h(i); } ublas::vector<double> C(size()); for (size_t xv(0); xv <= e; ++xv) C(xv) = 0; for (size_t i(1); i < e; ++i) C(i) = 6 * ((y(i+1) - y(i)) / h(i) - (y(i) - y(i-1)) / h(i-1)); //Boundary conditions switch(_BCLow) { case FIXED_1ST_DERIV_BC: C(0) = 6 * ((y(1) - y(0)) / h(0) - _BCLowVal); A(0,0) = 2 * h(0); A(1,0) = h(0); break; case FIXED_2ND_DERIV_BC: C(0) = _BCLowVal; A(0,0) = 1; break; case PARABOLIC_RUNOUT_BC: C(0) = 0; A(0,0) = 1; A(1,0) = -1; break; } switch(_BCHigh) { case FIXED_1ST_DERIV_BC: C(e) = 6 * (_BCHighVal - (y(e) - y(e-1)) / h(e-1)); A(e,e) = 2 * h(e - 1); A(e-1,e) = h(e - 1); break; case FIXED_2ND_DERIV_BC: C(e) = _BCHighVal; A(e,e) = 1; break; case PARABOLIC_RUNOUT_BC: C(e) = 0; A(e,e) = 1; A(e-1,e) = -1; break; } ublas::matrix<double> AInv(size(), size()); InvertMatrix(A,AInv); _ddy = ublas::prod(C, AInv); _data.resize(size()-1); for (size_t i(0); i < e; ++i) { _data[i].x = x(i); _data[i].a = (_ddy(i+1) - _ddy(i)) / (6 * h(i)); _data[i].b = _ddy(i) / 2; _data[i].c = (y(i+1) - y(i)) / h(i) - _ddy(i+1) * h(i) / 6 - _ddy(i) * h(i) / 3; _data[i].d = y(i); } } } _valid = true; } }; } }
[ "akhilakollasrinu424jf@gmail.com" ]
akhilakollasrinu424jf@gmail.com
fceb55bc6d21b9f15eec72c607e1dddf641deb23
9cc213acfe71fabc9adb667abbf615e3b4ebbfe2
/06-templates-and-linked-lists/node.hpp
2f8fbf9d857fb7b2ce873ef18c9a16eced39ceca
[]
no_license
2021-spring-cop-3530-tth/lecture-code
0633ca2977cfb55e1b685785e6503cc892fb437e
fcd72b9720013cd5b6b378d52cc0be9040843c9a
refs/heads/main
2023-04-09T22:13:58.296645
2021-04-21T14:14:14
2021-04-21T14:14:14
330,843,702
1
0
null
null
null
null
UTF-8
C++
false
false
260
hpp
#ifndef NODE_HPP #define NODE_HPP template <typename DataType> class Node { private: DataType payload; Node<DataType>* next; public: Node (DataType data, Node<DataType>* next = nullptr); DataType GetData (); Node<DataType>* GetNext (); }; #endif
[ "sbitner@uwf.edu" ]
sbitner@uwf.edu
57c8d5570fd279ad5490bc116f4061d1682d5247
8834b745b49a9593507c7854804f982680733fc5
/中级算法/数组和字符串/三数之和/C++/citation.cpp
c56f2bfcd24f44fb31bd64c291a992817d99aa8d
[]
no_license
xingkaihao/Leetcode
739105eb6416d0480a36f532b8abf894980465d2
61b6a4ce0854b81e9a095b8ba0fba91fe92c60b5
refs/heads/master
2020-04-08T02:26:00.583629
2019-08-22T02:32:20
2019-08-22T02:32:20
158,935,556
0
0
null
null
null
null
GB18030
C++
false
false
1,397
cpp
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> result; int i = 0, j = 0, k = 0, target = 0; sort(nums.begin(),nums.end()); //对数组进行排序 for(i = 0; i < nums.size(); i ++){ if(nums[i] > 0) break; else if(i > 0 && nums[i] == nums[i - 1]) //跳过重复元素 continue; target = -nums[i]; //更新target,转换为两数之和为target的问题 j = i+1; k = nums.size() -1; while(j < k){ if(nums[j] + nums[k] == target){ result.push_back({nums[i],nums[j],nums[k]}); while(nums[j + 1] == nums[j] && j < k) ++j; //跳过重复元素 while(nums[k - 1] == nums[k] && j< k) --k; //跳过重复元素 ++j, --k; } else if(nums[j] + nums[k] > target) --k; else ++j; } } return result; } }; /* 三数之和就相当于两数之和的target的是变化的,所以先排序(从小到大),然后遍历数组, *获取target(注意去除重复元素),然后对该元素右侧的所有元素求两数之和为target的组合(注意去除重复元素)。 */
[ "18202419054@163.com" ]
18202419054@163.com
fd44e8e8b472c610a621c04448a928c185d39ee0
5ed358ac90e68e225a13d6b2a5749c7dc38e7b97
/chapter 12/12.27/query_result.h
501781868221eee28ede5dbece0c45f0559e250b
[]
no_license
zzzwind/cpp-primer-5th-exercises
202cc241000bd888d1d0b849f37328a593d83d01
404e4e0c5c0a055f7b8334b93a6b95f75b71501f
refs/heads/main
2023-06-06T16:27:28.981906
2021-07-13T07:15:25
2021-07-13T07:15:25
331,148,894
0
0
null
null
null
null
UTF-8
C++
false
false
619
h
#ifndef QUERYRESULT_H #define QUERYRESULT_H #include <fstream> #include <string> #include <vector> #include <map> #include <set> #include <memory> class QueryResult { friend std::ostream& print(std::ostream&, const QueryResult&); public: using line_no = std::vector<std::string>::size_type; QueryResult(std::string s, std::shared_ptr<std::set<line_no>> p, std::shared_ptr<std::vector<std::string>> f) : sought(s), lines(p), file(f) {} private: std::string sought; std::shared_ptr<std::set<line_no>>lines; std::shared_ptr<std::vector<std::string>>file; }; #endif
[ "zykblack@gmail.com" ]
zykblack@gmail.com
491ee780e0fca6edbea28de9838da82a7c098940
4c052882366dd86b06880d8e9908b30d627b8d2e
/0061_unique_paths/solution.cpp
0f7508a55477009c0370db522e3bbf38c4178209
[]
no_license
adithya-tp/leet_code
da93c9f4422d92c472e5595011abf898ae88586e
42204865cde865dd5b8306c3e1861b8086fb19e6
refs/heads/master
2022-08-31T14:28:54.711351
2022-08-11T15:18:04
2022-08-11T15:18:04
214,262,000
0
0
null
null
null
null
UTF-8
C++
false
false
624
cpp
class Solution { public: int uniquePaths(int m, int n) { vector<vector<int>> dp_grid(m, vector<int>(n,0)); dp_grid[0][0] = 1; for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(i > 0 && j > 0){ dp_grid[i][j] += dp_grid[i-1][j] + dp_grid[i][j-1]; } else if(i > 0){ dp_grid[i][j] += dp_grid[i-1][j]; } else if(j > 0){ dp_grid[i][j] += dp_grid[i][j-1]; } } } return dp_grid[m-1][n-1]; } };
[ "adithyatp@yahoo.com" ]
adithyatp@yahoo.com
2ed4ebf44820aa4bacdfc1a752033984f3605f67
c99563482d18ebb50c3bdd3feb3e3f821f7cccc4
/src/netbase.cpp
1e0c032b657607632fe6a4e7fb98b498bfee09c5
[ "MIT" ]
permissive
matsuiny2004/BookCoin
afa85971ae01a17a9d53c3fdcdc1cca7db05270e
23ad19110babe6b0cdd80b62eec314d3c270938b
refs/heads/master
2020-04-13T22:01:41.080231
2018-11-18T17:39:14
2018-11-18T17:39:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
43,753
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifdef HAVE_CONFIG_H #include "config/book-config.h" #endif #include "netbase.h" #include "hash.h" #include "sync.h" #include "uint256.h" #include "random.h" #include "util.h" #include "utilstrencodings.h" #ifdef HAVE_GETADDRINFO_A #include <netdb.h> #endif #ifndef WIN32 #if HAVE_INET_PTON #include <arpa/inet.h> #endif #include <fcntl.h> #endif #include <boost/algorithm/string/case_conv.hpp> // for to_lower() #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith() #include <boost/thread.hpp> #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL) #define MSG_NOSIGNAL 0 #endif // Settings static proxyType proxyInfo[NET_MAX]; static proxyType nameProxy; static CCriticalSection cs_proxyInfos; int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT; bool fNameLookup = DEFAULT_NAME_LOOKUP; static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff }; // Need ample time for negotiation for very slow proxies such as Tor (milliseconds) static const int SOCKS5_RECV_TIMEOUT = 20 * 1000; enum Network ParseNetwork(std::string net) { boost::to_lower(net); if (net == "ipv4") return NET_IPV4; if (net == "ipv6") return NET_IPV6; if (net == "tor" || net == "onion") return NET_TOR; return NET_UNROUTABLE; } std::string GetNetworkName(enum Network net) { switch(net) { case NET_IPV4: return "ipv4"; case NET_IPV6: return "ipv6"; case NET_TOR: return "onion"; default: return ""; } } void SplitHostPort(std::string in, int &portOut, std::string &hostOut) { size_t colon = in.find_last_of(':'); // if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator bool fHaveColon = colon != in.npos; bool fBracketed = fHaveColon && (in[0]=='[' && in[colon-1]==']'); // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe bool fMultiColon = fHaveColon && (in.find_last_of(':',colon-1) != in.npos); if (fHaveColon && (colon==0 || fBracketed || !fMultiColon)) { int32_t n; if (ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) { in = in.substr(0, colon); portOut = n; } } if (in.size()>0 && in[0] == '[' && in[in.size()-1] == ']') hostOut = in.substr(1, in.size()-2); else hostOut = in; } bool static LookupIntern(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup) { vIP.clear(); { CNetAddr addr; if (addr.SetSpecial(std::string(pszName))) { vIP.push_back(addr); return true; } } #ifdef HAVE_GETADDRINFO_A struct in_addr ipv4_addr; #ifdef HAVE_INET_PTON if (inet_pton(AF_INET, pszName, &ipv4_addr) > 0) { vIP.push_back(CNetAddr(ipv4_addr)); return true; } struct in6_addr ipv6_addr; if (inet_pton(AF_INET6, pszName, &ipv6_addr) > 0) { vIP.push_back(CNetAddr(ipv6_addr)); return true; } #else ipv4_addr.s_addr = inet_addr(pszName); if (ipv4_addr.s_addr != INADDR_NONE) { vIP.push_back(CNetAddr(ipv4_addr)); return true; } #endif #endif struct addrinfo aiHint; memset(&aiHint, 0, sizeof(struct addrinfo)); aiHint.ai_socktype = SOCK_STREAM; aiHint.ai_protocol = IPPROTO_TCP; aiHint.ai_family = AF_UNSPEC; #ifdef WIN32 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST; #else aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST; #endif struct addrinfo *aiRes = NULL; #ifdef HAVE_GETADDRINFO_A struct gaicb gcb, *query = &gcb; memset(query, 0, sizeof(struct gaicb)); gcb.ar_name = pszName; gcb.ar_request = &aiHint; int nErr = getaddrinfo_a(GAI_NOWAIT, &query, 1, NULL); if (nErr) return false; do { // Should set the timeout limit to a resonable value to avoid // generating unnecessary checking call during the polling loop, // while it can still response to stop request quick enough. // 2 seconds looks fine in our situation. struct timespec ts = { 2, 0 }; gai_suspend(&query, 1, &ts); boost::this_thread::interruption_point(); nErr = gai_error(query); if (0 == nErr) aiRes = query->ar_result; } while (nErr == EAI_INPROGRESS); #else int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes); #endif if (nErr) return false; struct addrinfo *aiTrav = aiRes; while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions)) { if (aiTrav->ai_family == AF_INET) { assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in)); vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr)); } if (aiTrav->ai_family == AF_INET6) { assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6)); vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr)); } aiTrav = aiTrav->ai_next; } freeaddrinfo(aiRes); return (vIP.size() > 0); } bool LookupHost(const char *pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup) { std::string strHost(pszName); if (strHost.empty()) return false; if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]")) { strHost = strHost.substr(1, strHost.size() - 2); } return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup); } bool Lookup(const char *pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions) { if (pszName[0] == 0) return false; int port = portDefault; std::string hostname = ""; SplitHostPort(std::string(pszName), port, hostname); std::vector<CNetAddr> vIP; bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup); if (!fRet) return false; vAddr.resize(vIP.size()); for (unsigned int i = 0; i < vIP.size(); i++) vAddr[i] = CService(vIP[i], port); return true; } bool Lookup(const char *pszName, CService& addr, int portDefault, bool fAllowLookup) { std::vector<CService> vService; bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1); if (!fRet) return false; addr = vService[0]; return true; } bool LookupNumeric(const char *pszName, CService& addr, int portDefault) { return Lookup(pszName, addr, portDefault, false); } struct timeval MillisToTimeval(int64_t nTimeout) { struct timeval timeout; timeout.tv_sec = nTimeout / 1000; timeout.tv_usec = (nTimeout % 1000) * 1000; return timeout; } /** * Read bytes from socket. This will either read the full number of bytes requested * or return False on error or timeout. * This function can be interrupted by boost thread interrupt. * * @param data Buffer to receive into * @param len Length of data to receive * @param timeout Timeout in milliseconds for receive operation * * @note This function requires that hSocket is in non-blocking mode. */ bool static InterruptibleRecv(char* data, size_t len, int timeout, SOCKET& hSocket) { int64_t curTime = GetTimeMillis(); int64_t endTime = curTime + timeout; // Maximum time to wait in one select call. It will take up until this time (in millis) // to break off in case of an interruption. const int64_t maxWait = 1000; while (len > 0 && curTime < endTime) { ssize_t ret = recv(hSocket, data, len, 0); // Optimistically try the recv first if (ret > 0) { len -= ret; data += ret; } else if (ret == 0) { // Unexpected disconnection return false; } else { // Other error or blocking int nErr = WSAGetLastError(); if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) { if (!IsSelectableSocket(hSocket)) { return false; } struct timeval tval = MillisToTimeval(std::min(endTime - curTime, maxWait)); fd_set fdset; FD_ZERO(&fdset); FD_SET(hSocket, &fdset); int nRet = select(hSocket + 1, &fdset, NULL, NULL, &tval); if (nRet == SOCKET_ERROR) { return false; } } else { return false; } } boost::this_thread::interruption_point(); curTime = GetTimeMillis(); } return len == 0; } struct ProxyCbooktials { std::string username; std::string password; }; /** Connect using SOCKS5 (as described in RFC1928) */ static bool Socks5(const std::string& strDest, int port, const ProxyCbooktials *auth, SOCKET& hSocket) { LogPrintf("SOCKS5 connecting %s\n", strDest); if (strDest.size() > 255) { CloseSocket(hSocket); return error("Hostname too long"); } // Accepted authentication methods std::vector<uint8_t> vSocks5Init; vSocks5Init.push_back(0x05); if (auth) { vSocks5Init.push_back(0x02); // # METHODS vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED vSocks5Init.push_back(0x02); // X'02' USERNAME/PASSWORD (RFC1929) } else { vSocks5Init.push_back(0x01); // # METHODS vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED } ssize_t ret = send(hSocket, (const char*)begin_ptr(vSocks5Init), vSocks5Init.size(), MSG_NOSIGNAL); if (ret != (ssize_t)vSocks5Init.size()) { CloseSocket(hSocket); return error("Error sending to proxy"); } char pchRet1[2]; if (!InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) { CloseSocket(hSocket); return error("Error reading proxy response"); } if (pchRet1[0] != 0x05) { CloseSocket(hSocket); return error("Proxy failed to initialize"); } if (pchRet1[1] == 0x02 && auth) { // Perform username/password authentication (as described in RFC1929) std::vector<uint8_t> vAuth; vAuth.push_back(0x01); if (auth->username.size() > 255 || auth->password.size() > 255) return error("Proxy username or password too long"); vAuth.push_back(auth->username.size()); vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end()); vAuth.push_back(auth->password.size()); vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end()); ret = send(hSocket, (const char*)begin_ptr(vAuth), vAuth.size(), MSG_NOSIGNAL); if (ret != (ssize_t)vAuth.size()) { CloseSocket(hSocket); return error("Error sending authentication to proxy"); } LogPrint("proxy", "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password); char pchRetA[2]; if (!InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) { CloseSocket(hSocket); return error("Error reading proxy authentication response"); } if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) { CloseSocket(hSocket); return error("Proxy authentication unsuccessful"); } } else if (pchRet1[1] == 0x00) { // Perform no authentication } else { CloseSocket(hSocket); return error("Proxy requested wrong authentication method %02x", pchRet1[1]); } std::vector<uint8_t> vSocks5; vSocks5.push_back(0x05); // VER protocol version vSocks5.push_back(0x01); // CMD CONNECT vSocks5.push_back(0x00); // RSV Reserved vSocks5.push_back(0x03); // ATYP DOMAINNAME vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end()); vSocks5.push_back((port >> 8) & 0xFF); vSocks5.push_back((port >> 0) & 0xFF); ret = send(hSocket, (const char*)begin_ptr(vSocks5), vSocks5.size(), MSG_NOSIGNAL); if (ret != (ssize_t)vSocks5.size()) { CloseSocket(hSocket); return error("Error sending to proxy"); } char pchRet2[4]; if (!InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) { CloseSocket(hSocket); return error("Error reading proxy response"); } if (pchRet2[0] != 0x05) { CloseSocket(hSocket); return error("Proxy failed to accept request"); } if (pchRet2[1] != 0x00) { CloseSocket(hSocket); switch (pchRet2[1]) { case 0x01: return error("Proxy error: general failure"); case 0x02: return error("Proxy error: connection not allowed"); case 0x03: return error("Proxy error: network unreachable"); case 0x04: return error("Proxy error: host unreachable"); case 0x05: return error("Proxy error: connection refused"); case 0x06: return error("Proxy error: TTL expired"); case 0x07: return error("Proxy error: protocol error"); case 0x08: return error("Proxy error: address type not supported"); default: return error("Proxy error: unknown"); } } if (pchRet2[2] != 0x00) { CloseSocket(hSocket); return error("Error: malformed proxy response"); } char pchRet3[256]; switch (pchRet2[3]) { case 0x01: ret = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break; case 0x04: ret = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break; case 0x03: { ret = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket); if (!ret) { CloseSocket(hSocket); return error("Error reading from proxy"); } int nRecv = pchRet3[0]; ret = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket); break; } default: CloseSocket(hSocket); return error("Error: malformed proxy response"); } if (!ret) { CloseSocket(hSocket); return error("Error reading from proxy"); } if (!InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) { CloseSocket(hSocket); return error("Error reading from proxy"); } LogPrintf("SOCKS5 connected %s\n", strDest); return true; } bool static ConnectSocketDirectly(const CService &addrConnect, SOCKET& hSocketRet, int nTimeout) { hSocketRet = INVALID_SOCKET; struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString()); return false; } SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hSocket == INVALID_SOCKET) return false; int set = 1; #ifdef SO_NOSIGPIPE // Different way of disabling SIGPIPE on BSD setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int)); #endif //Disable Nagle's algorithm #ifdef WIN32 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int)); #else setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&set, sizeof(int)); #endif // Set to non-blocking if (!SetSocketNonBlocking(hSocket, true)) return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError())); if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); // WSAEINVAL is here because some legacy version of winsock uses it if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) { struct timeval timeout = MillisToTimeval(nTimeout); fd_set fdset; FD_ZERO(&fdset); FD_SET(hSocket, &fdset); int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout); if (nRet == 0) { LogPrint("net", "connection to %s timeout\n", addrConnect.ToString()); CloseSocket(hSocket); return false; } if (nRet == SOCKET_ERROR) { LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError())); CloseSocket(hSocket); return false; } socklen_t nRetSize = sizeof(nRet); #ifdef WIN32 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR) #else if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR) #endif { LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError())); CloseSocket(hSocket); return false; } if (nRet != 0) { LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet)); CloseSocket(hSocket); return false; } } #ifdef WIN32 else if (WSAGetLastError() != WSAEISCONN) #else else #endif { LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError())); CloseSocket(hSocket); return false; } } hSocketRet = hSocket; return true; } bool SetProxy(enum Network net, const proxyType &addrProxy) { assert(net >= 0 && net < NET_MAX); if (!addrProxy.IsValid()) return false; LOCK(cs_proxyInfos); proxyInfo[net] = addrProxy; return true; } bool GetProxy(enum Network net, proxyType &proxyInfoOut) { assert(net >= 0 && net < NET_MAX); LOCK(cs_proxyInfos); if (!proxyInfo[net].IsValid()) return false; proxyInfoOut = proxyInfo[net]; return true; } bool SetNameProxy(const proxyType &addrProxy) { if (!addrProxy.IsValid()) return false; LOCK(cs_proxyInfos); nameProxy = addrProxy; return true; } bool GetNameProxy(proxyType &nameProxyOut) { LOCK(cs_proxyInfos); if(!nameProxy.IsValid()) return false; nameProxyOut = nameProxy; return true; } bool HaveNameProxy() { LOCK(cs_proxyInfos); return nameProxy.IsValid(); } bool IsProxy(const CNetAddr &addr) { LOCK(cs_proxyInfos); for (int i = 0; i < NET_MAX; i++) { if (addr == (CNetAddr)proxyInfo[i].proxy) return true; } return false; } static bool ConnectThroughProxy(const proxyType &proxy, const std::string& strDest, int port, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed) { SOCKET hSocket = INVALID_SOCKET; // first connect to proxy server if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) { if (outProxyConnectionFailed) *outProxyConnectionFailed = true; return false; } // do socks negotiation if (proxy.randomize_cbooktials) { ProxyCbooktials random_auth; random_auth.username = strprintf("%i", insecure_rand()); random_auth.password = strprintf("%i", insecure_rand()); if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket)) return false; } else { if (!Socks5(strDest, (unsigned short)port, 0, hSocket)) return false; } hSocketRet = hSocket; return true; } bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed) { proxyType proxy; if (outProxyConnectionFailed) *outProxyConnectionFailed = false; if (GetProxy(addrDest.GetNetwork(), proxy)) return ConnectThroughProxy(proxy, addrDest.ToStringIP(), addrDest.GetPort(), hSocketRet, nTimeout, outProxyConnectionFailed); else // no proxy needed (none set for target network) return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout); } bool ConnectSocketByName(CService &addr, SOCKET& hSocketRet, const char *pszDest, int portDefault, int nTimeout, bool *outProxyConnectionFailed) { std::string strDest; int port = portDefault; if (outProxyConnectionFailed) *outProxyConnectionFailed = false; SplitHostPort(std::string(pszDest), port, strDest); proxyType nameProxy; GetNameProxy(nameProxy); CService addrResolved(CNetAddr(strDest, fNameLookup && !HaveNameProxy()), port); if (addrResolved.IsValid()) { addr = addrResolved; return ConnectSocket(addr, hSocketRet, nTimeout); } addr = CService("0.0.0.0:0"); if (!HaveNameProxy()) return false; return ConnectThroughProxy(nameProxy, strDest, port, hSocketRet, nTimeout, outProxyConnectionFailed); } void CNetAddr::Init() { memset(ip, 0, sizeof(ip)); } void CNetAddr::SetIP(const CNetAddr& ipIn) { memcpy(ip, ipIn.ip, sizeof(ip)); } void CNetAddr::SetRaw(Network network, const uint8_t *ip_in) { switch(network) { case NET_IPV4: memcpy(ip, pchIPv4, 12); memcpy(ip+12, ip_in, 4); break; case NET_IPV6: memcpy(ip, ip_in, 16); break; default: assert(!"invalid network"); } } static const unsigned char pchOnionCat[] = {0xFD,0x87,0xD8,0x7E,0xEB,0x43}; bool CNetAddr::SetSpecial(const std::string &strName) { if (strName.size()>6 && strName.substr(strName.size() - 6, 6) == ".onion") { std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str()); if (vchAddr.size() != 16-sizeof(pchOnionCat)) return false; memcpy(ip, pchOnionCat, sizeof(pchOnionCat)); for (unsigned int i=0; i<16-sizeof(pchOnionCat); i++) ip[i + sizeof(pchOnionCat)] = vchAddr[i]; return true; } return false; } CNetAddr::CNetAddr() { Init(); } CNetAddr::CNetAddr(const struct in_addr& ipv4Addr) { SetRaw(NET_IPV4, (const uint8_t*)&ipv4Addr); } CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr) { SetRaw(NET_IPV6, (const uint8_t*)&ipv6Addr); } CNetAddr::CNetAddr(const char *pszIp, bool fAllowLookup) { Init(); std::vector<CNetAddr> vIP; if (LookupHost(pszIp, vIP, 1, fAllowLookup)) *this = vIP[0]; } CNetAddr::CNetAddr(const std::string &strIp, bool fAllowLookup) { Init(); std::vector<CNetAddr> vIP; if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup)) *this = vIP[0]; } unsigned int CNetAddr::GetByte(int n) const { return ip[15-n]; } bool CNetAddr::IsIPv4() const { return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0); } bool CNetAddr::IsIPv6() const { return (!IsIPv4() && !IsTor()); } bool CNetAddr::IsRFC1918() const { return IsIPv4() && ( GetByte(3) == 10 || (GetByte(3) == 192 && GetByte(2) == 168) || (GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31))); } bool CNetAddr::IsRFC2544() const { return IsIPv4() && GetByte(3) == 198 && (GetByte(2) == 18 || GetByte(2) == 19); } bool CNetAddr::IsRFC3927() const { return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254); } bool CNetAddr::IsRFC6598() const { return IsIPv4() && GetByte(3) == 100 && GetByte(2) >= 64 && GetByte(2) <= 127; } bool CNetAddr::IsRFC5737() const { return IsIPv4() && ((GetByte(3) == 192 && GetByte(2) == 0 && GetByte(1) == 2) || (GetByte(3) == 198 && GetByte(2) == 51 && GetByte(1) == 100) || (GetByte(3) == 203 && GetByte(2) == 0 && GetByte(1) == 113)); } bool CNetAddr::IsRFC3849() const { return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8; } bool CNetAddr::IsRFC3964() const { return (GetByte(15) == 0x20 && GetByte(14) == 0x02); } bool CNetAddr::IsRFC6052() const { static const unsigned char pchRFC6052[] = {0,0x64,0xFF,0x9B,0,0,0,0,0,0,0,0}; return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0); } bool CNetAddr::IsRFC4380() const { return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0); } bool CNetAddr::IsRFC4862() const { static const unsigned char pchRFC4862[] = {0xFE,0x80,0,0,0,0,0,0}; return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0); } bool CNetAddr::IsRFC4193() const { return ((GetByte(15) & 0xFE) == 0xFC); } bool CNetAddr::IsRFC6145() const { static const unsigned char pchRFC6145[] = {0,0,0,0,0,0,0,0,0xFF,0xFF,0,0}; return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0); } bool CNetAddr::IsRFC4843() const { return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10); } bool CNetAddr::IsTor() const { return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0); } bool CNetAddr::IsLocal() const { // IPv4 loopback if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0)) return true; // IPv6 loopback (::1/128) static const unsigned char pchLocal[16] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}; if (memcmp(ip, pchLocal, 16) == 0) return true; return false; } bool CNetAddr::IsMulticast() const { return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0) || (GetByte(15) == 0xFF); } bool CNetAddr::IsValid() const { // Cleanup 3-byte shifted addresses caused by garbage in size field // of addr messages from versions before 0.2.9 checksum. // Two consecutive addr messages look like this: // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26... // so if the first length field is garbled, it reads the second batch // of addr misaligned by 3 bytes. if (memcmp(ip, pchIPv4+3, sizeof(pchIPv4)-3) == 0) return false; // unspecified IPv6 address (::/128) unsigned char ipNone[16] = {}; if (memcmp(ip, ipNone, 16) == 0) return false; // documentation IPv6 address if (IsRFC3849()) return false; if (IsIPv4()) { // INADDR_NONE uint32_t ipNone = INADDR_NONE; if (memcmp(ip+12, &ipNone, 4) == 0) return false; // 0 ipNone = 0; if (memcmp(ip+12, &ipNone, 4) == 0) return false; } return true; } bool CNetAddr::IsRoutable() const { return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal()); } enum Network CNetAddr::GetNetwork() const { if (!IsRoutable()) return NET_UNROUTABLE; if (IsIPv4()) return NET_IPV4; if (IsTor()) return NET_TOR; return NET_IPV6; } std::string CNetAddr::ToStringIP(bool fUseGetnameinfo) const { if (IsTor()) return EncodeBase32(&ip[6], 10) + ".onion"; if (fUseGetnameinfo) { CService serv(*this, 0); struct sockaddr_storage sockaddr; socklen_t socklen = sizeof(sockaddr); if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) { char name[1025] = ""; if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST)) return std::string(name); } } if (IsIPv4()) return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0)); else return strprintf("%x:%x:%x:%x:%x:%x:%x:%x", GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12), GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8), GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4), GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0)); } std::string CNetAddr::ToString() const { return ToStringIP(); } bool operator==(const CNetAddr& a, const CNetAddr& b) { return (memcmp(a.ip, b.ip, 16) == 0); } bool operator!=(const CNetAddr& a, const CNetAddr& b) { return (memcmp(a.ip, b.ip, 16) != 0); } bool operator<(const CNetAddr& a, const CNetAddr& b) { return (memcmp(a.ip, b.ip, 16) < 0); } bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const { if (!IsIPv4()) return false; memcpy(pipv4Addr, ip+12, 4); return true; } bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const { memcpy(pipv6Addr, ip, 16); return true; } // get canonical identifier of an address' group // no two connections will be attempted to addresses with the same group std::vector<unsigned char> CNetAddr::GetGroup() const { std::vector<unsigned char> vchRet; int nClass = NET_IPV6; int nStartByte = 0; int nBits = 16; // all local addresses belong to the same group if (IsLocal()) { nClass = 255; nBits = 0; } // all unroutable addresses belong to the same group if (!IsRoutable()) { nClass = NET_UNROUTABLE; nBits = 0; } // for IPv4 addresses, '1' + the 16 higher-order bits of the IP // includes mapped IPv4, SIIT translated IPv4, and the well-known prefix else if (IsIPv4() || IsRFC6145() || IsRFC6052()) { nClass = NET_IPV4; nStartByte = 12; } // for 6to4 tunnelled addresses, use the encapsulated IPv4 address else if (IsRFC3964()) { nClass = NET_IPV4; nStartByte = 2; } // for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address else if (IsRFC4380()) { vchRet.push_back(NET_IPV4); vchRet.push_back(GetByte(3) ^ 0xFF); vchRet.push_back(GetByte(2) ^ 0xFF); return vchRet; } else if (IsTor()) { nClass = NET_TOR; nStartByte = 6; nBits = 4; } // for he.net, use /36 groups else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70) nBits = 36; // for the rest of the IPv6 network, use /32 groups else nBits = 32; vchRet.push_back(nClass); while (nBits >= 8) { vchRet.push_back(GetByte(15 - nStartByte)); nStartByte++; nBits -= 8; } if (nBits > 0) vchRet.push_back(GetByte(15 - nStartByte) | ((1 << (8 - nBits)) - 1)); return vchRet; } uint64_t CNetAddr::GetHash() const { uint256 hash = Hash(&ip[0], &ip[16]); uint64_t nRet; memcpy(&nRet, &hash, sizeof(nRet)); return nRet; } // private extensions to enum Network, only returned by GetExtNetwork, // and only used in GetReachabilityFrom static const int NET_UNKNOWN = NET_MAX + 0; static const int NET_TEREDO = NET_MAX + 1; int static GetExtNetwork(const CNetAddr *addr) { if (addr == NULL) return NET_UNKNOWN; if (addr->IsRFC4380()) return NET_TEREDO; return addr->GetNetwork(); } /** Calculates a metric for how reachable (*this) is from a given partner */ int CNetAddr::GetReachabilityFrom(const CNetAddr *paddrPartner) const { enum Reachability { REACH_UNREACHABLE, REACH_DEFAULT, REACH_TEREDO, REACH_IPV6_WEAK, REACH_IPV4, REACH_IPV6_STRONG, REACH_PRIVATE }; if (!IsRoutable()) return REACH_UNREACHABLE; int ourNet = GetExtNetwork(this); int theirNet = GetExtNetwork(paddrPartner); bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145(); switch(theirNet) { case NET_IPV4: switch(ourNet) { default: return REACH_DEFAULT; case NET_IPV4: return REACH_IPV4; } case NET_IPV6: switch(ourNet) { default: return REACH_DEFAULT; case NET_TEREDO: return REACH_TEREDO; case NET_IPV4: return REACH_IPV4; case NET_IPV6: return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled } case NET_TOR: switch(ourNet) { default: return REACH_DEFAULT; case NET_IPV4: return REACH_IPV4; // Tor users can connect to IPv4 as well case NET_TOR: return REACH_PRIVATE; } case NET_TEREDO: switch(ourNet) { default: return REACH_DEFAULT; case NET_TEREDO: return REACH_TEREDO; case NET_IPV6: return REACH_IPV6_WEAK; case NET_IPV4: return REACH_IPV4; } case NET_UNKNOWN: case NET_UNROUTABLE: default: switch(ourNet) { default: return REACH_DEFAULT; case NET_TEREDO: return REACH_TEREDO; case NET_IPV6: return REACH_IPV6_WEAK; case NET_IPV4: return REACH_IPV4; case NET_TOR: return REACH_PRIVATE; // either from Tor, or don't care about our address } } } void CService::Init() { port = 0; } CService::CService() { Init(); } CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn) { } CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn) { } CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn) { } CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port)) { assert(addr.sin_family == AF_INET); } CService::CService(const struct sockaddr_in6 &addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port)) { assert(addr.sin6_family == AF_INET6); } bool CService::SetSockAddr(const struct sockaddr *paddr) { switch (paddr->sa_family) { case AF_INET: *this = CService(*(const struct sockaddr_in*)paddr); return true; case AF_INET6: *this = CService(*(const struct sockaddr_in6*)paddr); return true; default: return false; } } CService::CService(const char *pszIpPort, bool fAllowLookup) { Init(); CService ip; if (Lookup(pszIpPort, ip, 0, fAllowLookup)) *this = ip; } CService::CService(const char *pszIpPort, int portDefault, bool fAllowLookup) { Init(); CService ip; if (Lookup(pszIpPort, ip, portDefault, fAllowLookup)) *this = ip; } CService::CService(const std::string &strIpPort, bool fAllowLookup) { Init(); CService ip; if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup)) *this = ip; } CService::CService(const std::string &strIpPort, int portDefault, bool fAllowLookup) { Init(); CService ip; if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup)) *this = ip; } unsigned short CService::GetPort() const { return port; } bool operator==(const CService& a, const CService& b) { return (CNetAddr)a == (CNetAddr)b && a.port == b.port; } bool operator!=(const CService& a, const CService& b) { return (CNetAddr)a != (CNetAddr)b || a.port != b.port; } bool operator<(const CService& a, const CService& b) { return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port); } bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t *addrlen) const { if (IsIPv4()) { if (*addrlen < (socklen_t)sizeof(struct sockaddr_in)) return false; *addrlen = sizeof(struct sockaddr_in); struct sockaddr_in *paddrin = (struct sockaddr_in*)paddr; memset(paddrin, 0, *addrlen); if (!GetInAddr(&paddrin->sin_addr)) return false; paddrin->sin_family = AF_INET; paddrin->sin_port = htons(port); return true; } if (IsIPv6()) { if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6)) return false; *addrlen = sizeof(struct sockaddr_in6); struct sockaddr_in6 *paddrin6 = (struct sockaddr_in6*)paddr; memset(paddrin6, 0, *addrlen); if (!GetIn6Addr(&paddrin6->sin6_addr)) return false; paddrin6->sin6_family = AF_INET6; paddrin6->sin6_port = htons(port); return true; } return false; } std::vector<unsigned char> CService::GetKey() const { std::vector<unsigned char> vKey; vKey.resize(18); memcpy(&vKey[0], ip, 16); vKey[16] = port / 0x100; vKey[17] = port & 0x0FF; return vKey; } std::string CService::ToStringPort() const { return strprintf("%u", port); } std::string CService::ToStringIPPort(bool fUseGetnameinfo) const { if (IsIPv4() || IsTor()) { return ToStringIP(fUseGetnameinfo) + ":" + ToStringPort(); } else { return "[" + ToStringIP(fUseGetnameinfo) + "]:" + ToStringPort(); } } std::string CService::ToString(bool fUseGetnameinfo) const { return ToStringIPPort(fUseGetnameinfo); } void CService::SetPort(unsigned short portIn) { port = portIn; } CSubNet::CSubNet(): valid(false) { memset(netmask, 0, sizeof(netmask)); } CSubNet::CSubNet(const std::string &strSubnet, bool fAllowLookup) { size_t slash = strSubnet.find_last_of('/'); std::vector<CNetAddr> vIP; valid = true; // Default to /32 (IPv4) or /128 (IPv6), i.e. match single address memset(netmask, 255, sizeof(netmask)); std::string strAddress = strSubnet.substr(0, slash); if (LookupHost(strAddress.c_str(), vIP, 1, fAllowLookup)) { network = vIP[0]; if (slash != strSubnet.npos) { std::string strNetmask = strSubnet.substr(slash + 1); int32_t n; // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n const int astartofs = network.IsIPv4() ? 12 : 0; if (ParseInt32(strNetmask, &n)) // If valid number, assume /24 symtex { if(n >= 0 && n <= (128 - astartofs*8)) // Only valid if in range of bits of address { n += astartofs*8; // Clear bits [n..127] for (; n < 128; ++n) netmask[n>>3] &= ~(1<<(7-(n&7))); } else { valid = false; } } else // If not a valid number, try full netmask syntax { if (LookupHost(strNetmask.c_str(), vIP, 1, false)) // Never allow lookup for netmask { // Copy only the *last* four bytes in case of IPv4, the rest of the mask should stay 1's as // we don't want pchIPv4 to be part of the mask. for(int x=astartofs; x<16; ++x) netmask[x] = vIP[0].ip[x]; } else { valid = false; } } } } else { valid = false; } // Normalize network according to netmask for(int x=0; x<16; ++x) network.ip[x] &= netmask[x]; } CSubNet::CSubNet(const CNetAddr &addr): valid(addr.IsValid()) { memset(netmask, 255, sizeof(netmask)); network = addr; } bool CSubNet::Match(const CNetAddr &addr) const { if (!valid || !addr.IsValid()) return false; for(int x=0; x<16; ++x) if ((addr.ip[x] & netmask[x]) != network.ip[x]) return false; return true; } static inline int NetmaskBits(uint8_t x) { switch(x) { case 0x00: return 0; break; case 0x80: return 1; break; case 0xc0: return 2; break; case 0xe0: return 3; break; case 0xf0: return 4; break; case 0xf8: return 5; break; case 0xfc: return 6; break; case 0xfe: return 7; break; case 0xff: return 8; break; default: return -1; break; } } std::string CSubNet::ToString() const { /* Parse binary 1{n}0{N-n} to see if mask can be represented as /n */ int cidr = 0; bool valid_cidr = true; int n = network.IsIPv4() ? 12 : 0; for (; n < 16 && netmask[n] == 0xff; ++n) cidr += 8; if (n < 16) { int bits = NetmaskBits(netmask[n]); if (bits < 0) valid_cidr = false; else cidr += bits; ++n; } for (; n < 16 && valid_cidr; ++n) if (netmask[n] != 0x00) valid_cidr = false; /* Format output */ std::string strNetmask; if (valid_cidr) { strNetmask = strprintf("%u", cidr); } else { if (network.IsIPv4()) strNetmask = strprintf("%u.%u.%u.%u", netmask[12], netmask[13], netmask[14], netmask[15]); else strNetmask = strprintf("%x:%x:%x:%x:%x:%x:%x:%x", netmask[0] << 8 | netmask[1], netmask[2] << 8 | netmask[3], netmask[4] << 8 | netmask[5], netmask[6] << 8 | netmask[7], netmask[8] << 8 | netmask[9], netmask[10] << 8 | netmask[11], netmask[12] << 8 | netmask[13], netmask[14] << 8 | netmask[15]); } return network.ToString() + "/" + strNetmask; } bool CSubNet::IsValid() const { return valid; } bool operator==(const CSubNet& a, const CSubNet& b) { return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16); } bool operator!=(const CSubNet& a, const CSubNet& b) { return !(a==b); } bool operator<(const CSubNet& a, const CSubNet& b) { return (a.network < b.network || (a.network == b.network && memcmp(a.netmask, b.netmask, 16) < 0)); } #ifdef WIN32 std::string NetworkErrorString(int err) { char buf[256]; buf[0] = 0; if(FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, sizeof(buf), NULL)) { return strprintf("%s (%d)", buf, err); } else { return strprintf("Unknown error (%d)", err); } } #else std::string NetworkErrorString(int err) { char buf[256]; const char *s = buf; buf[0] = 0; /* Too bad there are two incompatible implementations of the * thread-safe strerror. */ #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */ s = strerror_r(err, buf, sizeof(buf)); #else /* POSIX variant always returns message in buffer */ if (strerror_r(err, buf, sizeof(buf))) buf[0] = 0; #endif return strprintf("%s (%d)", s, err); } #endif bool CloseSocket(SOCKET& hSocket) { if (hSocket == INVALID_SOCKET) return false; #ifdef WIN32 int ret = closesocket(hSocket); #else int ret = close(hSocket); #endif hSocket = INVALID_SOCKET; return ret != SOCKET_ERROR; } bool SetSocketNonBlocking(SOCKET& hSocket, bool fNonBlocking) { if (fNonBlocking) { #ifdef WIN32 u_long nOne = 1; if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) { #else int fFlags = fcntl(hSocket, F_GETFL, 0); if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) { #endif CloseSocket(hSocket); return false; } } else { #ifdef WIN32 u_long nZero = 0; if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) { #else int fFlags = fcntl(hSocket, F_GETFL, 0); if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) { #endif CloseSocket(hSocket); return false; } } return true; }
[ "bookcoin@protonmail.com" ]
bookcoin@protonmail.com
df08f0e658bfdf865593802ac907f703b559499b
d1a4428dd57c7a5dbfa84dd04cb9054df2388a9c
/src/content/renderer/media/webrtc/webrtc_audio_renderer.h
e22078580953d32d663d1180e91fb69cb536c740
[ "BSD-3-Clause" ]
permissive
riverite/chromium
bfa4e354dc71fdbe942c648d311a7663533af379
458877c9b9a7e0f8ee55cb787cd12a1ecef3fe0f
refs/heads/master
2022-12-29T23:14:08.184892
2018-11-02T14:45:03
2018-11-02T14:45:03
154,111,141
1
5
null
2022-12-18T00:43:23
2018-10-22T08:36:22
null
UTF-8
C++
false
false
10,155
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_RENDERER_MEDIA_WEBRTC_WEBRTC_AUDIO_RENDERER_H_ #define CONTENT_RENDERER_MEDIA_WEBRTC_WEBRTC_AUDIO_RENDERER_H_ #include <stdint.h> #include <map> #include <memory> #include <string> #include <vector> #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/sequence_checker.h" #include "base/single_thread_task_runner.h" #include "base/synchronization/lock.h" #include "base/threading/thread_checker.h" #include "content/public/renderer/media_stream_audio_renderer.h" #include "content/renderer/media/webrtc/webrtc_audio_device_impl.h" #include "media/base/audio_decoder.h" #include "media/base/audio_pull_fifo.h" #include "media/base/audio_renderer_sink.h" #include "media/base/channel_layout.h" #include "third_party/blink/public/platform/web_media_stream.h" namespace webrtc { class AudioSourceInterface; } // namespace webrtc namespace content { class WebRtcAudioRendererSource; // This renderer handles calls from the pipeline and WebRtc ADM. It is used // for connecting WebRtc MediaStream with the audio pipeline. class CONTENT_EXPORT WebRtcAudioRenderer : public media::AudioRendererSink::RenderCallback, public MediaStreamAudioRenderer { public: // This is a little utility class that holds the configured state of an audio // stream. // It is used by both WebRtcAudioRenderer and SharedAudioRenderer (see cc // file) so a part of why it exists is to avoid code duplication and track // the state in the same way in WebRtcAudioRenderer and SharedAudioRenderer. class PlayingState { public: PlayingState() : playing_(false), volume_(1.0f) {} ~PlayingState() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); } bool playing() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return playing_; } void set_playing(bool playing) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); playing_ = playing; } float volume() const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); return volume_; } void set_volume(float volume) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); volume_ = volume; } private: bool playing_; float volume_; SEQUENCE_CHECKER(sequence_checker_); }; WebRtcAudioRenderer( const scoped_refptr<base::SingleThreadTaskRunner>& signaling_thread, const blink::WebMediaStream& media_stream, int source_render_frame_id, int session_id, const std::string& device_id); // Initialize function called by clients like WebRtcAudioDeviceImpl. // Stop() has to be called before |source| is deleted. bool Initialize(WebRtcAudioRendererSource* source); // When sharing a single instance of WebRtcAudioRenderer between multiple // users (e.g. WebMediaPlayerMS), call this method to create a proxy object // that maintains the Play and Stop states per caller. // The wrapper ensures that Play() won't be called when the caller's state // is "playing", Pause() won't be called when the state already is "paused" // etc and similarly maintains the same state for Stop(). // When Stop() is called or when the proxy goes out of scope, the proxy // will ensure that Pause() is called followed by a call to Stop(), which // is the usage pattern that WebRtcAudioRenderer requires. scoped_refptr<MediaStreamAudioRenderer> CreateSharedAudioRendererProxy( const blink::WebMediaStream& media_stream); // Used to DCHECK on the expected state. bool IsStarted() const; // Accessors to the sink audio parameters. int channels() const { return sink_params_.channels(); } int sample_rate() const { return sink_params_.sample_rate(); } int frames_per_buffer() const { return sink_params_.frames_per_buffer(); } // Returns true if called on rendering thread, otherwise false. bool CurrentThreadIsRenderingThread(); private: // MediaStreamAudioRenderer implementation. This is private since we want // callers to use proxy objects. // TODO(tommi): Make the MediaStreamAudioRenderer implementation a pimpl? void Start() override; void Play() override; void Pause() override; void Stop() override; void SetVolume(float volume) override; media::OutputDeviceInfo GetOutputDeviceInfo() override; base::TimeDelta GetCurrentRenderTime() const override; bool IsLocalRenderer() const override; void SwitchOutputDevice(const std::string& device_id, const media::OutputDeviceStatusCB& callback) override; // Called when an audio renderer, either the main or a proxy, starts playing. // Here we maintain a reference count of how many renderers are currently // playing so that the shared play state of all the streams can be reflected // correctly. void EnterPlayState(); // Called when an audio renderer, either the main or a proxy, is paused. // See EnterPlayState for more details. void EnterPauseState(); protected: ~WebRtcAudioRenderer() override; private: enum State { UNINITIALIZED, PLAYING, PAUSED, }; // Holds raw pointers to PlaingState objects. Ownership is managed outside // of this type. typedef std::vector<PlayingState*> PlayingStates; // Maps an audio source to a list of playing states that collectively hold // volume information for that source. typedef std::map<webrtc::AudioSourceInterface*, PlayingStates> SourcePlayingStates; // Used to DCHECK that we are called on the correct thread. THREAD_CHECKER(thread_checker_); // Flag to keep track the state of the renderer. State state_; // media::AudioRendererSink::RenderCallback implementation. // These two methods are called on the AudioOutputDevice worker thread. int Render(base::TimeDelta delay, base::TimeTicks delay_timestamp, int prior_frames_skipped, media::AudioBus* audio_bus) override; void OnRenderError() override; // Called by AudioPullFifo when more data is necessary. // This method is called on the AudioOutputDevice worker thread. void SourceCallback(int fifo_frame_delay, media::AudioBus* audio_bus); // Goes through all renderers for the |source| and applies the proper // volume scaling for the source based on the volume(s) of the renderer(s). void UpdateSourceVolume(webrtc::AudioSourceInterface* source); // Tracks a playing state. The state must be playing when this method // is called. // Returns true if the state was added, false if it was already being tracked. bool AddPlayingState(webrtc::AudioSourceInterface* source, PlayingState* state); // Removes a playing state for an audio source. // Returns true if the state was removed from the internal map, false if // it had already been removed or if the source isn't being rendered. bool RemovePlayingState(webrtc::AudioSourceInterface* source, PlayingState* state); // Called whenever the Play/Pause state changes of any of the renderers // or if the volume of any of them is changed. // Here we update the shared Play state and apply volume scaling to all audio // sources associated with the |media_stream| based on the collective volume // of playing renderers. void OnPlayStateChanged(const blink::WebMediaStream& media_stream, PlayingState* state); // Called when |state| is about to be destructed. void OnPlayStateRemoved(PlayingState* state); // Updates |sink_params_| and |audio_fifo_| based on |sink_|, and initializes // |sink_|. void PrepareSink(); // The RenderFrame in which the audio is rendered into |sink_|. const int source_render_frame_id_; const int session_id_; const scoped_refptr<base::SingleThreadTaskRunner> signaling_thread_; // The sink (destination) for rendered audio. scoped_refptr<media::AudioRendererSink> sink_; // The media stream that holds the audio tracks that this renderer renders. const blink::WebMediaStream media_stream_; // Audio data source from the browser process. WebRtcAudioRendererSource* source_; // Protects access to |state_|, |source_|, |audio_fifo_|, // |audio_delay_milliseconds_|, |fifo_delay_milliseconds_|, |current_time_|, // |sink_params_|, |render_callback_count_| and |max_render_time_|. mutable base::Lock lock_; // Ref count for the MediaPlayers which are playing audio. int play_ref_count_; // Ref count for the MediaPlayers which have called Start() but not Stop(). int start_ref_count_; // Used to buffer data between the client and the output device in cases where // the client buffer size is not the same as the output device buffer size. std::unique_ptr<media::AudioPullFifo> audio_fifo_; // Contains the accumulated delay estimate which is provided to the WebRTC // AEC. base::TimeDelta audio_delay_; base::TimeDelta current_time_; // Saved volume and playing state of the root renderer. PlayingState playing_state_; // Audio params used by the sink of the renderer. media::AudioParameters sink_params_; // The preferred device id of the output device or empty for the default // output device. Can change as a result of a SetSinkId() call. std::string output_device_id_; // Maps audio sources to a list of active audio renderers. // Pointers to PlayingState objects are only kept in this map while the // associated renderer is actually playing the stream. Ownership of the // state objects lies with the renderers and they must leave the playing state // before being destructed (PlayingState object goes out of scope). SourcePlayingStates source_playing_states_; // Stores the maximum time spent waiting for render data from the source. Used // for logging UMA data. Logged and reset when Stop() is called. base::TimeDelta max_render_time_; DISALLOW_IMPLICIT_CONSTRUCTORS(WebRtcAudioRenderer); }; } // namespace content #endif // CONTENT_RENDERER_MEDIA_WEBRTC_WEBRTC_AUDIO_RENDERER_H_
[ "sket0039@gmail.com" ]
sket0039@gmail.com
24f5a7b5a6550f0498d52889836e4df663d24f12
c09dc7a0a2cf63d9314c7353bf00cfd987dcc250
/SturdyGoggles/SturdyGoggles/InputLayout.h
96f5aa369f53ab6ae13be74cc532092b8dd3fd28
[ "MIT" ]
permissive
SenorChurro/sturdy-goggles
62b88227aef823799a7aa0e5bd1da25be099ccc7
6d242ec30668af3b95340d005bf0734538005dc6
refs/heads/master
2021-05-17T17:14:37.732756
2020-11-09T01:55:56
2020-11-09T01:55:56
250,890,507
0
0
MIT
2020-11-09T01:55:57
2020-03-28T20:48:01
C++
UTF-8
C++
false
false
317
h
#pragma once #include "Bindable.h" class InputLayout : public Bindable { public: InputLayout(Graphics& gfx, const std::vector<D3D11_INPUT_ELEMENT_DESC>& layout, ID3DBlob* pVertexShaderBytecode); void Bind(Graphics& gfx) noexcept override; protected: Microsoft::WRL::ComPtr<ID3D11InputLayout> pInputLayout; };
[ "parker.brian.dev@gmail.com" ]
parker.brian.dev@gmail.com
e095f4e44341daae2680f1ad5fd95b132a42b42c
002d74020e9ab301b712fb81d4d1ea56638aef27
/Exercises.h
4b9ada6b82331e79797b91cfae85fcc97dda95d4
[]
no_license
dongwookang95/C-practice
4b8896ddb6cc06a72b096e516903fceb68e260c9
82db95363a0bfb9dbba1e99e54d86a89311aff75
refs/heads/master
2020-07-24T10:20:32.129425
2019-09-11T19:40:53
2019-09-11T19:40:53
207,892,662
0
0
null
null
null
null
UTF-8
C++
false
false
1,250
h
#ifndef EXERCISES_H #define EXERCISES_H #include <list> #include <set> ////////////////// Exercise 1 //////////////////////////////////// std::pair<float, float> Statistics(const std::list<float>& values) { return std::pair<float, float>(0.f, 0.f); } ////////////////////////////////////////////////////////////////// ////////////////// Exercise 2 //////////////////////////////////// class TreeVisitor { public: float visitTree(const Tree& tree, bool countOnlyEvenLevels){ return 0.f; } }; ////////////////////////////////////////////////////////////////// ////////////////// Exercise 3 //////////////////////////////////// class Complex { public: Complex(float real, float imaginary){}; float real, im; }; ////////////////////////////////////////////////////////////////// ////////////////// Exercise 4 //////////////////////////////////// float WaterLevels(std::list<float> heights) { return 0; } ////////////////////////////////////////////////////////////////// ////////////////// Exercise 5 //////////////////////////////////// typedef std::pair<int, int> location; int Labyrinth(std::set<std::pair<location, location> > labyrinth, int size) { return 0; } ////////////////////////////////////////////////////////////////// #endif
[ "d.kang-1@student.tudelft.nl" ]
d.kang-1@student.tudelft.nl
52c9146a0c505553baa601d7756c47f9615b7290
127f962913f2366de4614311af41cd6f814f590e
/Image-processing-Lab-3/Image-processing-Lab-3/hough_circle.h
24b77e55d18d3f427fa0113d663a3e474aaf04a3
[]
no_license
Oleg-ui/Image-processing-Lab-3
cc110333d98f89a05806b6a5a1c3570d64b222e6
88797737b292fed0fe37557163bf4cce4a7e41e4
refs/heads/main
2023-01-28T13:35:42.016474
2020-12-06T17:29:32
2020-12-06T17:29:32
319,076,256
0
0
null
null
null
null
UTF-8
C++
false
false
439
h
#include <vector> namespace keymolen { class HoughCircle { public: HoughCircle(); virtual ~HoughCircle(); public: int Transform(unsigned char* img_data, int w, int h, int r); int GetCircles(int threshold, std::vector< std::pair< std::pair<int, int>, int> >& result ); const unsigned int* GetAccu(int *w, int *h); private: unsigned int* _accu; int _accu_w; int _accu_h; int _img_w; int _img_h; int _r; }; }
[ "olejka647@gmail.com" ]
olejka647@gmail.com
5ea481608956c06a2544a62ae553ce52e10a8429
5f231ebdb98e6c83e2e3586eec2820b36bd4dec8
/fx_graphics/PostprocessDemo.h
73f75a22407802cc7a132c59de525d9d5e00f83b
[]
no_license
uttumuttu/niwa
926583b4cc9b420b827d3cb991227f2b34486778
9e4fc79c469cf7db8b081e489df6e7d04140f336
refs/heads/master
2016-09-03T06:22:19.772697
2015-09-02T15:26:15
2015-09-02T15:26:15
40,969,355
0
0
null
null
null
null
UTF-8
C++
false
false
1,753
h
/** * @file * @author Mikko Kauppila * * Copyright (C) Mikko Kauppila 2009. */ #ifndef POSTPROCESSDEMO_H #define POSTPROCESSDEMO_H #include "niwa/demolib/AbstractEffect.h" namespace niwa { namespace graphics { class FrameBuffer; class Program; class Texture; } } #include <memory> #include <boost/shared_ptr.hpp> /** * A demonstration of post-processing effects. * Takes no parameters. */ class PostprocessDemo : public niwa::demolib::AbstractEffect { public: PostprocessDemo(); void render(niwa::demolib::IGraphics const&) const; void update(double secondsElapsed); private: double time_; std::auto_ptr<niwa::graphics::Program> differentialProgram_; std::auto_ptr<niwa::graphics::Program> flowProgram_; std::auto_ptr<niwa::graphics::Program> blurProgram_; mutable boost::shared_ptr<niwa::graphics::Texture> newTexture_; mutable boost::shared_ptr<niwa::graphics::Texture> oldTexture_; mutable boost::shared_ptr<niwa::graphics::Texture> newVelocityTexture_; mutable boost::shared_ptr<niwa::graphics::Texture> oldVelocityTexture_; boost::shared_ptr<niwa::graphics::Texture> differentialTexture_; boost::shared_ptr<niwa::graphics::Texture> blurTexture_; mutable boost::shared_ptr<niwa::graphics::FrameBuffer> newFrame_; mutable boost::shared_ptr<niwa::graphics::FrameBuffer> oldFrame_; mutable boost::shared_ptr<niwa::graphics::FrameBuffer> newVelocityFrame_; mutable boost::shared_ptr<niwa::graphics::FrameBuffer> oldVelocityFrame_; boost::shared_ptr<niwa::graphics::FrameBuffer> differentialFrame_; boost::shared_ptr<niwa::graphics::FrameBuffer> blurFrame_; }; #endif
[ "mikko.kauppila@oulu.fi" ]
mikko.kauppila@oulu.fi
f90130299fc5518373765dbcab659eefbd1b176c
99a34576627604d5e1bc97c4cac2f49a616dabe8
/test/test_xhighfive.cpp
06ba1a8a495e4454cc1d1a2e8f9e5720a4e9bfd3
[ "BSD-3-Clause" ]
permissive
ken012git/xtensor-io
0510a3603e076e792745a2601018086f55e497a4
2a77dcb600d24c8a74e77969732efbffecbe4217
refs/heads/master
2020-04-09T08:49:32.117748
2018-12-04T15:17:20
2018-12-04T15:17:20
160,209,740
0
0
BSD-3-Clause
2018-12-03T15:08:57
2018-12-03T15:08:56
null
UTF-8
C++
false
false
5,191
cpp
/*************************************************************************** * Copyright (c) 2016, Johan Mabille, Sylvain Corlay and Wolf Vollprecht * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #include <cstdint> #include <sstream> #include <exception> #include "gtest/gtest.h" #include "xtensor/xrandom.hpp" #include "xtensor-io/xhighfive.hpp" namespace xt { TEST(xhighfive, scalar) { HighFive::File file("test.h5", HighFive::File::Overwrite); double a = 1.2345; int b = 12345; std::string c = "12345"; xt::dump(file, "/path/to/a", a); xt::dump(file, "/path/to/b", b); xt::dump(file, "/path/to/c", c); double a_r = xt::load<double>(file, "/path/to/a"); int b_r = xt::load<int>(file, "/path/to/b"); std::string c_r = xt::load<std::string>(file, "/path/to/c"); EXPECT_TRUE(a == a_r); EXPECT_TRUE(b == b_r); EXPECT_TRUE(c == c_r); } TEST(xhighfive, xtensor) { HighFive::File file("test.h5", HighFive::File::Overwrite); xt::xtensor<double,2> A = 100. * xt::random::randn<double>({20,5}); xt::xtensor<int,2> B = A; xt::dump(file, "/path/to/A", A); xt::dump(file, "/path/to/B", B); xt::xtensor<double,2> A_r = xt::load<xt::xtensor<double,2>>(file, "/path/to/A"); xt::xtensor<int,2> B_r = xt::load<xt::xtensor<int,2>>(file, "/path/to/B"); EXPECT_TRUE(xt::allclose(A, A_r)); EXPECT_TRUE(xt::all(xt::equal(B, B_r))); } TEST(xhighfive, xarray) { HighFive::File file("test.h5", HighFive::File::Overwrite); xt::xarray<double> A = 100. * xt::random::randn<double>({20,5}); xt::xarray<int> B = A; xt::dump(file, "/path/to/A", A); xt::dump(file, "/path/to/B", B); xt::xarray<double> A_r = xt::load<xt::xarray<double>>(file, "/path/to/A"); xt::xarray<int> B_r = xt::load<xt::xarray<int>>(file, "/path/to/B"); EXPECT_TRUE(xt::allclose(A, A_r)); EXPECT_TRUE(xt::all(xt::equal(B, B_r))); } TEST(xhighfive, extend1d) { HighFive::File file("test.h5", HighFive::File::Overwrite); for (std::size_t i = 0; i < 10; ++i) { xt::dump(file, "/path/to/A", i, {i}); } xt::xarray<std::size_t> A = xt::arange<std::size_t>(10); xt::xarray<std::size_t> A_r = xt::load<xt::xarray<std::size_t>>(file, "/path/to/A"); std::size_t Amax = xt::load<std::size_t>(file, "/path/to/A", {9}); EXPECT_TRUE(xt::allclose(A, A_r)); EXPECT_TRUE(Amax == 9); } TEST(xhighfive, extend2d) { HighFive::File file("test.h5", HighFive::File::Overwrite); for (std::size_t i = 0; i < 10; ++i) { for (std::size_t j = 0; j < 5; ++j) { xt::dump(file, "/path/to/A", i*5+j, {i,j}); } } xt::xarray<std::size_t> A = xt::arange<std::size_t>(10*5); A.reshape({10,5}); xt::xarray<std::size_t> A_r = xt::load<xt::xarray<std::size_t>>(file, "/path/to/A"); std::size_t Amax = xt::load<std::size_t>(file, "/path/to/A", {9,4}); EXPECT_TRUE(xt::allclose(A, A_r)); EXPECT_TRUE(Amax == 49); } TEST(xhighfive, files) { double scalar_double = 12.345; int scalar_int = 12345; std::string scalar_string = "12345"; std::vector<double> vector_double = {1.1, 2.2, 3.3, 4.4, 5.5}; std::vector<int> vector_int = {1, 2, 3, 4, 5}; xt::xtensor<double,2> matrix_double = {{1.1, 2.2}, {3.3, 4.4}, {5.5, 6.6}}; xt::xtensor<int,2> matrix_int = {{1, 2}, {3, 4}, {5, 6}}; double scalar_double_r = xt::load_hdf5<double>("files/archive.h5", "/scalar/double"); int scalar_int_r = xt::load_hdf5<int>("files/archive.h5", "/scalar/int"); std::string scalar_string_r = xt::load_hdf5<std::string>("files/archive.h5", "/scalar/string"); std::vector<double> vector_double_r = xt::load_hdf5<std::vector<double>>("files/archive.h5", "/vector/double"); std::vector<int> vector_int_r = xt::load_hdf5<std::vector<int>>("files/archive.h5", "/vector/int"); xt::xtensor<double,2> matrix_double_r = xt::load_hdf5<xt::xtensor<double,2>>("files/archive.h5", "/matrix/double"); xt::xtensor<int,2> matrix_int_r = xt::load_hdf5<xt::xtensor<int,2>>("files/archive.h5", "/matrix/int"); EXPECT_TRUE(scalar_double == scalar_double_r); EXPECT_TRUE(scalar_int == scalar_int_r); EXPECT_TRUE(scalar_string == scalar_string_r); EXPECT_TRUE(vector_double == vector_double_r); EXPECT_TRUE(vector_int == vector_int_r); EXPECT_TRUE(xt::allclose(matrix_double, matrix_double_r)); EXPECT_TRUE(xt::allclose(matrix_int, matrix_int_r)); } }
[ "tom@geus.me" ]
tom@geus.me
a22a3ed11dbbc7c589625e3429d2dfe66ef91f6f
bef657345910dc788471ac375d8d280e9828876b
/external/tapir-0.3/src/problems/activetag/ActiveTagModel.hpp
1acf014ba5fcdfbb6211f4c5ef0dcd1fbeb52810
[]
no_license
isnanmulia/csipb-jamu-prj
47186d50cc8a101d92e8b00596c4b33840ce4efa
6fd95571267be32bbaf3efb84ff69e9612cfc6ee
refs/heads/master
2021-01-17T06:40:49.574352
2015-06-12T11:57:10
2015-06-12T11:57:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,320
hpp
/** @file ActiveTagModel.hpp * * Contains ActiveTagModel, which implements the core Model interface for the ActiveTag POMDP. */ #ifndef ACTIVETAGMODEL_HPP_ #define ACTIVETAGMODEL_HPP_ #include <memory> // for unique_ptr #include <ostream> // for ostream #include <string> // for string #include <utility> // for pair #include <vector> // for vector #include "global.hpp" // for RandomGenerator #include "problems/shared/GridPosition.hpp" // for GridPosition #include "problems/shared/ModelWithProgramOptions.hpp" // for ModelWithProgramOptions #include "solver/abstract-problem/Model.hpp" // for Model::StepResult, Model #include "solver/abstract-problem/ModelChange.hpp" // for ModelChange #include "solver/abstract-problem/TransitionParameters.hpp" #include "solver/abstract-problem/Action.hpp" // for Action #include "solver/abstract-problem/Observation.hpp" // for Observation #include "solver/abstract-problem/State.hpp" #include "solver/mappings/actions/enumerated_actions.hpp" #include "solver/mappings/observations/discrete_observations.hpp" #include "ActiveTagAction.hpp" #include "ActiveTagOptions.hpp" #include "ActiveTagMdpSolver.hpp" namespace solver { class StatePool; } /* namespace solver */ /** A namespace to hold the various classes used for the ActiveTag POMDP model. */ namespace activetag { class ActiveTagObservation; class ActiveTagState; /** Represents a change in the ActiveTag model. */ struct ActiveTagChange : public solver::ModelChange { /** The change type for this change - this should be one of: * - "Add Obstacles" - to add new obstacles to the ActiveTag problem. * - "Remove Obstacles" - to remove existing obstacles from the ActiveTag problem. */ std::string changeType = ""; /** The first row number where the change applies. */ long i0 = 0; /** The last row number where the change applies. */ long i1 = 0; /** The first column number where the change applies. */ long j0 = 0; /** The last column number where the change applies. */ long j1 = 0; }; /** A parser for a simple upper bound heuristic for ActiveTag. * * The actual function is defined in ActiveTagModel::getUpperBoundHeuristicValue; this parser allows * that heuristic to be selected by using the string "upper()" in the configuration file. */ class ActiveTagUBParser : public shared::Parser<solver::HeuristicFunction> { public: /** Creates a new ActiveTagUBParser associated with the given ActiveTagModel instance. */ ActiveTagUBParser(ActiveTagModel *model); virtual ~ActiveTagUBParser() = default; _NO_COPY_OR_MOVE(ActiveTagUBParser); virtual solver::HeuristicFunction parse(solver::Solver *solver, std::vector<std::string> args); private: /** The ActiveTagModel instance this heuristic parser is associated with. */ ActiveTagModel *model_; }; /** The implementation of the Model interface for the ActiveTag POMDP. * * See this paper http://www.cs.cmu.edu/~ggordon/jpineau-ggordon-thrun.ijcai03.pdf * for a description of the Tag problem. * * This class inherits from shared::ModelWithProgramOptions in order to use custom text-parsing * functionality to select many of the core ABT parameters, allowing the configuration options * to be changed easily via the configuration interface without having to recompile the code. */ class ActiveTagModel: public shared::ModelWithProgramOptions { friend class TagObservation; friend class ActiveTagMdpSolver; public: /** Constructs a new ActiveTagModel instance with the given random number engine, and the given set * of configuration options. */ ActiveTagModel(RandomGenerator *randGen, std::unique_ptr<ActiveTagOptions> options); ~ActiveTagModel() = default; _NO_COPY_OR_MOVE(ActiveTagModel); /** The cells are either empty or walls. */ enum class TagCellType : int { /** An empty cell. */ EMPTY = 0, /* A wall. */ WALL = -1 }; /** Get a vector of valid grid positions */ std::vector<GridPosition> getEmptyCells(); /******************** Added by Josh **************************/ /** Get 2D vector representing the current environment map */ inline const std::vector<std::vector<TagCellType>>& getEnvMap() { return envMap_; } /** * Returns proportion of belief particles about the target's * position for each grid position in the map */ std::vector<std::vector<float>> getBeliefProportions(solver::BeliefNode const *belief); /************************************************************/ /** Returns the resulting coordinates of an agent after it takes the given action type from the * given position. * * The boolean flag will be false if the agent's move represents an attempt to move into an * obstacle or off the edge of the map, which in the ActiveTag POMDP simply causes them to stay * in the same position. * * This flag is mostly not used as there is no penalty for this in ActiveTag, and the returned * position already reflects them staying still. */ std::pair<GridPosition, bool> getMovedPos(GridPosition const &position, ActionType action); /** Generates a new opponent position based on the current positions of the robot and the * opponent. */ GridPosition sampleNextOpponentPosition(GridPosition const &robotPos, GridPosition const &opponentPos); /* ---------- Custom getters for extra functionality ---------- */ /** Returns the number of rows in the map for this ActiveTagModel instance. */ long getNRows() const { return nRows_; } /** Returns the number of columns in the map for this ActiveTagModel instance. */ long getNCols() const { return nCols_; } /** Initializes a ActiveTagMdpSolver for this ActiveTagModel, which can then be used to return heuristic * values for each state. */ void makeMdpSolver() { mdpSolver_ = std::make_unique<ActiveTagMdpSolver>(this); mdpSolver_->solve(); } /** Returns the ActiveTagMdpSolver solver (if any) owned by this model. */ ActiveTagMdpSolver *getMdpSolver() { return mdpSolver_.get(); } /** Returns the distance within the map between the two given positions. */ int getMapDistance(GridPosition p1, GridPosition p2); /* --------------- The model interface proper ----------------- */ std::unique_ptr<solver::State> sampleAnInitState() override; std::unique_ptr<solver::State> sampleStateUninformed() override; bool isTerminal(solver::State const &state) override; bool isValid(solver::State const &state) override; /* -------------------- Black box dynamics ---------------------- */ virtual std::unique_ptr<solver::State> generateNextState( solver::State const &state, solver::Action const &action, solver::TransitionParameters const * /*tp*/) override; virtual std::unique_ptr<solver::Observation> generateObservation( solver::State const * /*state*/, solver::Action const &action, solver::TransitionParameters const * /*tp*/, solver::State const &nextState) override; virtual double generateReward( solver::State const &state, solver::Action const &action, solver::TransitionParameters const * /*tp*/, solver::State const * /*nextState*/) override; virtual Model::StepResult generateStep(solver::State const &state, solver::Action const &action) override; /* -------------- Methods for handling model changes ---------------- */ virtual void applyChanges(std::vector<std::unique_ptr<solver::ModelChange>> const &changes, solver::Solver *solver) override; /* ------------ Methods for handling particle depletion -------------- */ /** Generates particles for ActiveTag using a particle filter from the previous belief. * * For each previous particle, possible next states are calculated based on consistency with * the given action and observation. These next states are then added to the output vector * in accordance with their probability of having been generated. */ virtual std::vector<std::unique_ptr<solver::State>> generateParticles( solver::BeliefNode *previousBelief, solver::Action const &action, solver::Observation const &obs, long nParticles, std::vector<solver::State const *> const &previousParticles) override; /** Generates particles for ActiveTag according to an uninformed prior. * * Previous states are sampled uniformly at random, a single step is generated, and only states * consistent with the action and observation are kept. */ virtual std::vector<std::unique_ptr<solver::State>> generateParticles( solver::BeliefNode *previousBelief, solver::Action const &action, solver::Observation const &obs, long nParticles) override; /* --------------- Pretty printing methods ----------------- */ /** Prints a single cell of the map out to the given output stream. */ virtual void dispCell(TagCellType cellType, std::ostream &os); virtual void drawEnv(std::ostream &os) override; virtual void drawSimulationState(solver::BeliefNode const *belief, solver::State const &state, std::ostream &os) override; /* ---------------------- Basic customizations ---------------------- */ virtual double getDefaultHeuristicValue(solver::HistoryEntry const *entry, solver::State const *state, solver::HistoricalData const *data) override; /** Returns an upper bound heuristic value for the given state. * * This upper bound assumes that the opponent will not move, and hence the heuristic value * simply calculates the discounted total reward, including the cost of moving one square at a * time until the robot reaches the opponent's current square, and then the reward for tagging * the opponent at that time. */ virtual double getUpperBoundHeuristicValue(solver::State const &state); /* ------- Customization of more complex solver functionality --------- */ /** Returns all of the actions available for the ActiveTag POMDP, in the order of their enumeration * (as specified by activetag::ActionType). */ virtual std::vector<std::unique_ptr<solver::DiscretizedPoint>> getAllActionsInOrder(); virtual std::unique_ptr<solver::ActionPool> createActionPool(solver::Solver *solver) override; virtual std::unique_ptr<solver::Serializer> createSerializer(solver::Solver *solver) override; private: /** Calculates the distances from the given position to all other parts of the map. */ void calculateDistancesFrom(GridPosition position); /** Calculates all pairwise distances on the map. */ void calculatePairwiseDistances(); /** Initialises the required data structures and variables for this model. */ void initialize(); /** Generates a random empty grid cell. */ GridPosition randomEmptyCell(); /** Generates a next state for the given state and action, as well as a boolean flag that will * be true if the action moved into a wall, and false otherwise. * * Moving into a wall in ActiveTag simply means nothing happens - there is no associated penalty; * as such, this flag is mostly not used in the ActiveTag problem. */ std::pair<std::unique_ptr<ActiveTagState>, bool> makeNextState( solver::State const &state, solver::Action const &action); /** Generates an observation given the resulting next state, after the ActiveTag robot has made its * action. */ std::unique_ptr<solver::Observation> makeObservation(ActiveTagState const &nextState); /** Generates a distribution of possible actions the opponent may choose to take, based on the * current position of the robot and the opponent. * * This distribution is represented by a vector of four elements, because the opponent's * actions are always evenly distributed between four possibilities (some of which can be the * same). */ std::vector<ActionType> makeOpponentActions(GridPosition const &robotPos, GridPosition const &opponentPos); /** Generates a proper distribution for the possible positions the opponent could be in * after the current state. */ std::unordered_map<GridPosition, double> getNextOpponentPositionDistribution( GridPosition const &robotPos, GridPosition const &opponentPos); /** Returns true iff the given GridPosition represents a valid square that an agent could be * in - that is, the square must be empty, and within the bounds of the map. */ bool isValid(GridPosition const &pos); /** The ActiveTagOptions instance associated with this model. */ ActiveTagOptions *options_; /** The penalty for each movement action. */ double moveCost_; /** The reward for successfully tagging the opponent. */ double tagReward_; /** The penalty for failing a activetag attempt. */ double failedTagPenalty_; /** The probability that the opponent will stay still. */ double opponentStayProbability_; /** The number of rows in the map. */ long nRows_; /** The number of columns in the map. */ long nCols_; /** The environment map in text form. */ std::vector<std::string> mapText_; /** The environment map in vector form. */ std::vector<std::vector<TagCellType>> envMap_; /** The number of possible actions in the ActiveTag POMDP. */ long nActions_; /** Solver for the MDP version of the problem. */ std::unique_ptr<ActiveTagMdpSolver> mdpSolver_; /** The pairwise distances between each pair of cells in the map. */ std::vector<std::vector<std::vector<std::vector<int>>>> pairwiseDistances_; }; } /* namespace activetag */ #endif /* ACTIVETAGMODEL_HPP_ */
[ "vektor.dewanto@gmail.com" ]
vektor.dewanto@gmail.com
ac75246e743a01e9e6c7e8959341f440b79b8e05
627d4d432c86ad98f669214d9966ae2db1600b31
/src/scripttools/debugging/qscriptbreakpointswidgetinterface.cpp
14ab828424507bde8a3dfae542d7426aa9bab630
[]
no_license
fluxer/copperspice
6dbab905f71843b8a3f52c844b841cef17f71f3f
07e7d1315d212a4568589b0ab1bd6c29c06d70a1
refs/heads/cs-1.1
2021-01-17T21:21:54.176319
2015-08-26T15:25:29
2015-08-26T15:25:29
39,802,091
6
0
null
2015-07-27T23:04:01
2015-07-27T23:04:00
null
UTF-8
C++
false
false
1,626
cpp
/*********************************************************************** * * Copyright (c) 2012-2015 Barbara Geller * Copyright (c) 2012-2015 Ansel Sermersheim * Copyright (c) 2012-2014 Digia Plc and/or its subsidiary(-ies). * Copyright (c) 2008-2012 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * * This file is part of CopperSpice. * * CopperSpice is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * CopperSpice is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with CopperSpice. If not, see * <http://www.gnu.org/licenses/>. * ***********************************************************************/ #include "qscriptbreakpointswidgetinterface_p.h" #include "qscriptbreakpointswidgetinterface_p_p.h" QT_BEGIN_NAMESPACE QScriptBreakpointsWidgetInterfacePrivate::QScriptBreakpointsWidgetInterfacePrivate() { } QScriptBreakpointsWidgetInterfacePrivate::~QScriptBreakpointsWidgetInterfacePrivate() { } QScriptBreakpointsWidgetInterface::~QScriptBreakpointsWidgetInterface() { } QScriptBreakpointsWidgetInterface::QScriptBreakpointsWidgetInterface( QScriptBreakpointsWidgetInterfacePrivate &dd, QWidget *parent, Qt::WindowFlags flags) : QWidget(dd, parent, flags) { } QT_END_NAMESPACE
[ "ansel@copperspice.com" ]
ansel@copperspice.com
7518fabd8de7042e88bb08cd12f5db9646f20b97
337c9311a4e81368d434bb511a9a6bcfce9534e4
/SlothEngine/SlothEngine/Source/Graphics/SfmlDebugPhysicsRenderer.h
ea5f7071cce0428e57c9840cb945296c74339ab2
[]
no_license
mylescardiff/PCGUniverse
8c28a204e25725544d5d0078e18bdc92b19037e6
6ca222f96cacf4ade8efd639aa6106cbcd6e2c0d
refs/heads/master
2023-01-23T23:56:42.935881
2020-12-07T21:25:16
2020-12-07T21:25:16
263,781,376
0
0
null
null
null
null
UTF-8
C++
false
false
1,114
h
#pragma once #include <Box2D.h> #include <SFML/Graphics.hpp> #include <Common.h> // this file is from Dylan, just using it to fix my polygon woes namespace slth { class SfmlGraphics; class IGraphics; class SfmlDebugPhysicsRenderer : public b2Draw { private: sf::RenderWindow* m_pTarget; public: SLTH_API bool Init(IGraphics* pGraphics); // Inherited via DebugPhysicsRenderer virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) final override; virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) final override; virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) final override; virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) final override; virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) final override; virtual void DrawTransform(const b2Transform& xf) final override; virtual void DrawPoint(const b2Vec2& p, float32 size, const b2Color& color) final override; }; }
[ "myles@mylescardiff.com" ]
myles@mylescardiff.com
e5dad5cbcbf0f8ee977b108fe41814922873d4c8
6a2420e2a51bb3b37491ca7f3a79efbd48d97947
/benchmark/fileio.cpp
c978c5015b0177fb1ed2bf06ce68536f1fb683a8
[]
no_license
linuxaged/lxd
cc3599eb2f4a63999a8668f28f26e358c9ab24e7
647bac54c39e512c64c851ce0154f0688aed0419
refs/heads/master
2021-07-05T03:00:13.661389
2020-09-16T07:48:20
2020-09-16T07:48:20
177,797,619
1
1
null
null
null
null
UTF-8
C++
false
false
544
cpp
#include <benchmark/benchmark.h> #include "../src/numbers.h" #include <charconv> static void BM_SimpleAtof(benchmark::State& state) { for(auto _ : state) { float pi{}; lxd::SimpleAtof("3.1415926", &pi); } } BENCHMARK(BM_SimpleAtof); static void BM_fromChars(benchmark::State& state) { const char* str = "3.1415926"; auto size = strlen(str) - 1; for(auto _ : state) { float pi{}; std::from_chars(str, str + size, pi); } } BENCHMARK(BM_fromChars); BENCHMARK_MAIN();
[ "1991md@gmail.com" ]
1991md@gmail.com
2480fce72f0721582cfc2b69145ecf5ef87457e2
1e0d369a4b274771859b46f2d950ea9605d95f04
/FinalProject2020/Final/src/_enemyB.cpp
eec13bf1368e3079023e0092b2ab795a828eda76
[]
no_license
ccodecheff/game-development-project-opengl
b2c8a8417b18bd6b570b253e31d2a490aa55733e
f80a318c624f4aceec04d265d2e26b0243a99df8
refs/heads/main
2022-12-30T05:53:25.562071
2020-10-05T03:25:49
2020-10-05T03:25:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,876
cpp
#include "_enemyB.h" #include <windows.h> _enemyB::_enemyB() { xPos = -0.3; yPos = 0.0; zPos = -1.0; xSize = 0.19; ySize = 0.19; rotateX = 0.0; rotateY = 0.0; rotateZ = 0.0; xMove=0.01; speed = 0.01; aiType = 0; } _enemyB::~_enemyB() { //dtor } void _enemyB::Enemy2Init() { frames = 1.0; xMin = 0.0; yMin = 0.0; xMax = 1.0; yMax = 1.0; } void _enemyB::drawEnemy2() { glPushMatrix(); glTranslated(xPos,yPos,zPos); glRotated(rotateX,1,0,0); glRotated(rotateY,0,1,0); glRotated(rotateZ,0,0,1); glBindTexture(GL_TEXTURE_2D,EnemyTex2); glScaled(xSize,ySize,1.0); glBegin(GL_QUADS); glTexCoord2f(xMin,yMax); glVertex3f(1.0,0.0,-0.2); glTexCoord2f(xMax,yMax); glVertex3f(0.0,0.0, -0.2); glTexCoord2f(xMax,yMin); glVertex3f(0.0,1.0, -0.2); glTexCoord2f(xMin,yMin); glVertex3f(1.0,1.0, -0.2); glEnd(); glPopMatrix(); } void _enemyB::placeEnemy2(float x, float y, float z) { xPos = x; yPos = y; zPos = z; } void _enemyB::actions() { switch(action) { case 0: if(T3->getTicks()>60) { xMin +=1.0/(float)frames; xMax +=1.0/(float)frames; yMin = 0.0; yMax = 1.0; if(xMax>=1) { xMin=1.0; xMax = 0.0; T3->reset(); } T3->reset(); } break; case 1: if(T3->getTicks()>60) { xMin +=1.0/(float)frames; xMax +=1.0/(float)frames; yMin = 0.4; yMax = 0.6; if(xMax>=1) { xMin=0.0; xMax=1.0/(float)frames; T3->reset(); } T3->reset(); } break; } } void _enemyB::checkCollision(_player* ply) { float enmLeftBound = xPos + xSize * 0.1; float enmRightBound = xPos + xSize * 0.2; float plyLeftBound = ply->xPos + ply->xSize * 0.2; float plyRightBound = ply->xPos + ply->xSize * 0.6; float enmBottomBound = yPos + ySize * 0.2; float enmTopBound = yPos + ySize * 0.6; float plyBottomBound = ply->yPos + ply->ySize * 0.1; float plyTopBound = ply->yPos + ply->ySize * 0.6; if (enmRightBound >= plyLeftBound && plyRightBound >= enmLeftBound) { if (enmTopBound >= plyBottomBound && plyTopBound >= enmBottomBound) { if (ply->knockedBack == 0) { ply->knockedBack = 15; aiType = 0; } } } } void _enemyB::enemyMovement(_player* ply) { float xDif = (ply->xPos + (ply->xSize / 2.0)) - (xPos + (xSize / 2.0)); // x axis distance from player float yDif = (ply->yPos + (ply->ySize / 2.0)) - (yPos + (ySize / 2.0)); // y axis distance from player switch (aiType) { case 1: // follow player only on x axis if (xDif < -0.02 || xDif > 0.02) { if (xDif > 0) { xPos=xPos+speed; } else { xPos=xPos-speed; } } break; case 2: if (yDif < -0.02 || yDif > 0.02) { if (yDif > 0) { yPos=yPos+(speed / 2.2); } else { yPos=yPos-(speed / 2.2); } } break; case 3: // chase player, get slower when closer if (xDif > 0) { xPos=xPos+speed*3.0*((ply->xPos + (ply->xSize / 2.0)) - (xPos + (xSize / 2.0))); } else { xPos=xPos+speed*((ply->xPos + (ply->xSize / 2.0)) - (xPos + (xSize / 2.0))); } yPos=yPos+speed*((ply->yPos + (ply->ySize / 2.0)) - (yPos + (ySize / 2.0))); break; case 4: // chase player at consistent speed, tries to get in front of them if (xDif + 0.2 < -0.1 || xDif + 0.2 > 0.1) { if (xDif + 0.2 > 0) { xPos=xPos+(speed / 2); } else { xPos=xPos-speed; } } if (yDif < -0.1 || yDif > 0.1) { if (yDif > 0) { yPos=yPos+(speed / 1.1); } else { yPos=yPos-(speed / 1.1); } } break; default:; } }
[ "rathore.karan.sn1@gmail.com" ]
rathore.karan.sn1@gmail.com
ae5158edf6dc0cc7b664c7290aba6ce9d3395f05
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/old_hunk_6245.cpp
ca2f174dc7bc99f4d1d92ea2617003a82a49d795
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,465
cpp
static long fqdncache_low = 180; static long fqdncache_high = 200; static void fqdncacheEnqueue(fqdncache_entry * f) { static time_t last_warning = 0; struct fqdncacheQueueData *new = xcalloc(1, sizeof(struct fqdncacheQueueData)); new->f = f; *fqdncacheQueueTailP = new; fqdncacheQueueTailP = &new->next; queue_length++; if (queue_length < NDnsServersAlloc) return; if (squid_curtime - last_warning < 600) return; last_warning = squid_curtime; debug(35, 0) ("fqdncacheEnqueue: WARNING: All dnsservers are busy.\n"); debug(35, 0) ("fqdncacheEnqueue: WARNING: %d DNS lookups queued\n", queue_length); if (queue_length > NDnsServersAlloc * 2) fatal("Too many queued DNS lookups"); if (Config.dnsChildren >= DefaultDnsChildrenMax) return; debug(35, 1) ("fqdncacheEnqueue: Consider increasing 'dns_children' in your config file.\n"); } static void * fqdncacheDequeue(void) { struct fqdncacheQueueData *old = NULL; fqdncache_entry *f = NULL; if (fqdncacheQueueHead) { f = fqdncacheQueueHead->f; old = fqdncacheQueueHead; fqdncacheQueueHead = fqdncacheQueueHead->next; if (fqdncacheQueueHead == NULL) fqdncacheQueueTailP = &fqdncacheQueueHead; safe_free(old); queue_length--; } if (f && f->status != FQDN_PENDING) debug_trap("fqdncacheDequeue: status != FQDN_PENDING"); return f; } /* removes the given fqdncache entry */ static void fqdncache_release(fqdncache_entry * f)
[ "993273596@qq.com" ]
993273596@qq.com
e6d46238a7063296e234d869f2327a064ba8e3b4
d0ab80441b2e37cbafbbb43c107db3f566a8e45d
/Include/Core/NTypes.hpp
71be3cdc812b82ad23b6569490c90b857f435e65
[]
no_license
aeadara/muzima-fingerprint-android
653ad65ccbd60294afdef987522617ac5eef9e08
a82a9c836ce1518c27234668858f139a0d8ae06a
refs/heads/master
2020-12-03T10:37:23.712383
2015-08-11T15:30:10
2015-08-11T15:30:10
35,594,266
0
1
null
2015-05-14T06:11:44
2015-05-14T06:11:44
null
UTF-8
C++
false
false
74,460
hpp
#ifndef N_TYPES_HPP_INCLUDED #define N_TYPES_HPP_INCLUDED #include <stdarg.h> #include <iterator> #include <iostream> namespace Neurotec { #include <Core/NTypes.h> } #ifndef N_CPP #error Only C++ is supported. #endif #ifndef N_FRAMEWORK_NO_AUTO_DETECT // Try auto-detect the framework #if defined(_MFC_VER) #define N_FRAMEWORK_MFC #elif defined(wxMAJOR_VERSION) #define N_FRAMEWORK_WX #elif defined(QT_VERSION) #define N_FRAMEWORK_QT #else #endif #endif #if !defined(N_NO_CPP11) && (_MSC_VER >= 1700 || __cplusplus >= 201103L) #define N_CPP11 #endif #include <Core/NNoDeprecate.h> #if defined(N_CPP11) #include <unordered_map> #include <unordered_set> #define N_HASH_MAP ::std::unordered_map #define N_HASH_SET ::std::unordered_set #define N_HASH_NAMESPACE_BEGIN namespace std { #define N_HASH_NAMESPACE_END } #elif defined(N_MSVC) #if _MSC_VER >= 1600 #include <unordered_map> #include <unordered_set> #define N_HASH_MAP ::std::unordered_map #define N_HASH_SET ::std::unordered_set #define N_HASH_NAMESPACE_BEGIN namespace std { #define N_HASH_NAMESPACE_END } #elif _MSC_VER >= 1500 #include <unordered_map> #include <unordered_set> #define N_HASH_MAP ::std::tr1::unordered_map #define N_HASH_SET ::std::tr1::unordered_set #define N_HASH_NAMESPACE_BEGIN namespace std { namespace tr1 { #define N_HASH_NAMESPACE_END } } #else #include <hash_map> #include <hash_set> #define N_HASH_MAP ::stdext::hash_map #define N_HASH_SET ::stdext::hash_set #define N_HASH_NAMESPACE_BEGIN namespace stdext { #define N_HASH_NAMESPACE_END } #endif #elif defined(N_GCC) #if N_GCC_VERSION >= 40000 #include <tr1/unordered_map> #include <tr1/unordered_set> #define N_HASH_MAP ::std::tr1::unordered_map #define N_HASH_SET ::std::tr1::unordered_set #define N_NEED_HASH #define N_HASH_NAMESPACE_BEGIN namespace std { namespace tr1 { #define N_HASH_NAMESPACE_END } } #else #include <ext/hash_map> #include <ext/hash_set> #define N_HASH_MAP ::__gnu_cxx::hash_map #define N_HASH_SET ::__gnu_cxx::hash_set #define N_NEED_HASH #define N_HASH_NAMESPACE_BEGIN namespace __gnu_cxx { #define N_HASH_NAMESPACE_END } N_HASH_NAMESPACE_BEGIN template<typename T> struct hash<const T *> { size_t operator()(const T * const & k) const { return (size_t)k; } }; template<typename T> struct hash<T *> { size_t operator()(T * const & k) const { return (size_t)k; } }; N_HASH_NAMESPACE_END #endif #else #include <hash_map> #include <hash_set> #define N_HASH_MAP ::std::hash_map #define N_HASH_SET ::std::hash_set #endif #include <Core/NReDeprecate.h> #ifdef N_MSVC #define N_THROW(args) throw(...) #define N_THROW_NONE throw() #define N_THROW_ANY throw(...) #else #define N_THROW(args) throw args #define N_THROW_NONE throw() #define N_THROW_ANY throw(...) #endif namespace Neurotec { #undef N_UINT8_MIN #undef N_UINT8_MAX #undef N_INT8_MIN #undef N_INT8_MAX #undef N_UINT16_MIN #undef N_UINT16_MAX #undef N_INT16_MIN #undef N_INT16_MAX #undef N_UINT32_MIN #undef N_UINT32_MAX #undef N_INT32_MIN #undef N_INT32_MAX #ifndef N_NO_INT_64 #undef N_UINT64_MIN #undef N_UINT64_MAX #undef N_INT64_MIN #undef N_INT64_MAX #endif #undef N_BYTE_MIN #undef N_BYTE_MAX #undef N_SBYTE_MIN #undef N_SBYTE_MAX #undef N_USHORT_MIN #undef N_USHORT_MAX #undef N_SHORT_MIN #undef N_SHORT_MAX #undef N_UINT_MIN #undef N_UINT_MAX #undef N_INT_MIN #undef N_INT_MAX #ifndef N_NO_INT_64 #undef N_ULONG_MIN #undef N_ULONG_MAX #undef N_LONG_MIN #undef N_LONG_MAX #endif #ifndef N_NO_FLOAT #undef N_SINGLE_MIN #undef N_SINGLE_MAX #undef N_SINGLE_EPSILON #undef N_DOUBLE_MIN #undef N_DOUBLE_MAX #undef N_DOUBLE_EPSILON #undef N_FLOAT_MIN #undef N_FLOAT_MAX #undef N_FLOAT_EPSILON #endif #undef NTrue #undef NFalse #ifndef N_NO_UNICODE #undef N_WCHAR_SIZE #endif #undef N_SIZE_TYPE_MIN #undef N_SIZE_TYPE_MAX #undef N_SSIZE_TYPE_MIN #undef N_SSIZE_TYPE_MAX #undef NMakeByte #undef NHiNibble #undef NLoNibble #undef NSwapNibbles #undef NMakeWord #undef NHiByte #undef NLoByte #undef NMakeDWord #undef NHiWord #undef NLoWord #ifndef N_NO_INT_64 #undef NMakeQWord #undef NHiDWord #undef NLoDWord #endif #undef NSwapWord #undef NSwapDWord #ifndef N_NO_INT_64 #undef NSwapQWord #endif #undef NHostToNetworkWord #undef NHostToNetworkDWord #undef NNetworkToHostWord #undef NNetworkToHostDWord #undef NIsFlagSet #undef NSetFlag #undef NResetFlag #undef NSetFlagValue #undef NSetFlagIf #undef NResetFlagIf #undef NIsMoreThanOneFlagSet #undef NMax #undef NMin #undef NRound #undef NRoundP #undef NRoundF #undef NRoundFP #undef NSqr #undef N_SWAP #ifdef N_MSVC const NUInt8 N_UINT8_MIN = 0x00ui8; const NUInt8 N_UINT8_MAX = 0xFFui8; const NInt8 N_INT8_MIN = 0x80i8; const NInt8 N_INT8_MAX = 0x7Fi8; const NUInt16 N_UINT16_MIN = 0x0000ui16; const NUInt16 N_UINT16_MAX = 0xFFFFui16; const NInt16 N_INT16_MIN = 0x8000i16; const NInt16 N_INT16_MAX = 0x7FFFi16; const NUInt32 N_UINT32_MIN = 0x00000000ui32; const NUInt32 N_UINT32_MAX = 0xFFFFFFFFui32; const NInt32 N_INT32_MIN = 0x80000000i32; const NInt32 N_INT32_MAX = 0x7FFFFFFFi32; #else const NUInt8 N_UINT8_MIN = ((NUInt8)0x00u); const NUInt8 N_UINT8_MAX = ((NUInt8)0xFFu); const NInt8 N_INT8_MIN = ((NInt8)0x80); const NInt8 N_INT8_MAX = ((NInt8)0x7F); const NUInt16 N_UINT16_MIN = ((NUInt16)0x0000u); const NUInt16 N_UINT16_MAX = ((NUInt16)0xFFFFu); const NInt16 N_INT16_MIN = ((NInt16)0x8000); const NInt16 N_INT16_MAX = ((NInt16)0x7FFF); const NUInt32 N_UINT32_MIN = 0x00000000u; const NUInt32 N_UINT32_MAX = 0xFFFFFFFFu; const NInt32 N_INT32_MIN = 0x80000000; const NInt32 N_INT32_MAX = 0x7FFFFFFF; #endif #ifndef N_NO_INT_64 #ifdef N_MSVC const NUInt64 N_UINT64_MIN = 0x0000000000000000ui64; const NUInt64 N_UINT64_MAX = 0xFFFFFFFFFFFFFFFFui64; const NInt64 N_INT64_MIN = 0x8000000000000000i64; const NInt64 N_INT64_MAX = 0x7FFFFFFFFFFFFFFFi64; #else const NUInt64 N_UINT64_MIN = 0x0000000000000000ull; const NUInt64 N_UINT64_MAX = 0xFFFFFFFFFFFFFFFFull; const NInt64 N_INT64_MIN = 0x8000000000000000ll; const NInt64 N_INT64_MAX = 0x7FFFFFFFFFFFFFFFll; #endif #endif const NByte N_BYTE_MIN = N_UINT8_MIN; const NByte N_BYTE_MAX = N_UINT8_MAX; const NSByte N_SBYTE_MIN = N_INT8_MIN; const NSByte N_SBYTE_MAX = N_INT8_MAX; const NUShort N_USHORT_MIN = N_UINT16_MIN; const NUShort N_USHORT_MAX = N_UINT16_MAX; const NShort N_SHORT_MIN = N_INT16_MIN; const NShort N_SHORT_MAX = N_INT16_MAX; const NUInt N_UINT_MIN = N_UINT32_MIN; const NUInt N_UINT_MAX = N_UINT32_MAX; const NInt N_INT_MIN = N_INT32_MIN; const NInt N_INT_MAX = N_INT32_MAX; #ifndef N_NO_INT_64 const NULong N_ULONG_MIN = N_UINT64_MIN; const NULong N_ULONG_MAX = N_UINT64_MAX; const NLong N_LONG_MIN = N_INT64_MIN; const NLong N_LONG_MAX = N_INT64_MAX; #endif #ifndef N_NO_FLOAT const NSingle N_SINGLE_MIN = -3.402823466e+38F; const NSingle N_SINGLE_MAX = 3.402823466e+38F; const NSingle N_SINGLE_EPSILON = 1.192092896e-07F; const NDouble N_DOUBLE_MIN = -1.7976931348623158e+308; const NDouble N_DOUBLE_MAX = 1.7976931348623158e+308; const NDouble N_DOUBLE_EPSILON = 2.2204460492503131e-016; const NFloat N_FLOAT_MIN = N_SINGLE_MIN; const NFloat N_FLOAT_MAX = N_SINGLE_MAX; const NFloat N_FLOAT_EPSILON = N_SINGLE_EPSILON; #endif const NBool NTrue = 1; const NBool NFalse = 0; #ifndef N_NO_UNICODE #if defined(N_WINDOWS) || (defined(__SIZEOF_WCHAR_T__) && __SIZEOF_WCHAR_T__ == 2) #define N_WCHAR_SIZE 2 #else // !defined(N_WINDOWS) && (!defined(__SIZEOF_WCHAR_T__) || __SIZEOF_WCHAR_T__ != 2) #define N_WCHAR_SIZE 4 #endif // !defined(N_WINDOWS) && (!defined(__SIZEOF_WCHAR_T__) || __SIZEOF_WCHAR_T__ != 2) #endif // !N_NO_UNICODE #ifdef N_64 const NSizeType N_SIZE_TYPE_MIN = N_UINT64_MIN; const NSizeType N_SIZE_TYPE_MAX = N_UINT64_MAX; const NSSizeType N_SSIZE_TYPE_MIN = N_INT64_MIN; const NSSizeType N_SSIZE_TYPE_MAX = N_INT64_MAX; #else const NSizeType N_SIZE_TYPE_MIN = N_UINT32_MIN; const NSizeType N_SIZE_TYPE_MAX = N_UINT32_MAX; const NSSizeType N_SSIZE_TYPE_MIN = N_INT32_MIN; const NSSizeType N_SSIZE_TYPE_MAX = N_INT32_MAX; #endif inline NByte NMakeByte(NByte lowNibble, NByte highNibble) { return (NByte)((highNibble << 4) | (lowNibble & 0x0F)); } inline NByte NHiNibble(NByte value) { return (NByte)((value >> 4) & 0x0F); } inline NByte NLoNibble(NByte value) { return (NByte)(value & 0x0F); } inline NByte NSwapNibbles(NByte value) { return (NByte)((value << 4) | ((value >> 4) & 0x0F)); } inline NUShort NMakeWord(NByte low, NByte high) { return (NUShort)(low | (high << 8)); } inline NByte NHiByte(NUShort value) { return (NByte)(value >> 8); } inline NByte NLoByte(NUShort value) { return (NByte)value; } inline NUInt NMakeDWord(NUShort low, NUShort high) { return (NUInt)(low | (high << 16)); } inline NUShort NHiWord(NUInt value) { return (NUShort)(value >> 16); } inline NUShort NLoWord(NUInt value) { return (NUShort)value; } #ifndef N_NO_INT_64 inline NULong NMakeQWord(NUInt low, NUInt high) { return (NULong)(low | (((NULong)high) << 32)); } inline NUInt NHiDWord(NULong value) { return (NUInt)(value >> 32); } inline NUInt NLoDWord(NULong value) { return (NUInt)value; } #endif inline NUShort NSwapWord(NUShort value) { return (NUShort)((((NByte)value) << 8) | ((NByte)(value >> 8))); } inline NUInt NSwapDWord(NUInt value) { return (NUInt)((NSwapWord((NUShort)value) << 16) | NSwapWord((NUShort)(value >> 16))); } #ifndef N_NO_INT_64 inline NULong NSwapQWord(NULong value) { return (NULong)(((NULong)NSwapDWord((NUInt)value) << 32) | NSwapDWord((NUInt)(value >> 32))); } #endif inline NUShort NHostToNetworkWord(NUShort value) { #ifndef N_BIG_ENDIAN return NSwapWord(value); #else return value; #endif } inline NUInt NHostToNetworkDWord(NUInt value) { #ifndef N_BIG_ENDIAN return NSwapDWord(value); #else return value; #endif } inline NUShort NNetworkToHostWord(NUShort value) { #ifndef N_BIG_ENDIAN return NSwapWord(value); #else return value; #endif } inline NUInt NNetworkToHostDWord(NUInt value) { #ifndef N_BIG_ENDIAN return NSwapDWord(value); #else return value; #endif } inline bool NIsFlagSet(NUInt flags, NUInt flag) { return (flags & flag) == flag; } inline NUInt NSetFlag(NUInt & flags, NUInt flag) { return flags |= flag; } inline NUInt NResetFlag(NUInt & flags, NUInt flag) { return flags &= ~flag; } inline NUInt NSetFlagValue(NUInt & flags, NUInt flag, bool value) { return value ? NSetFlag(flags, flag) : NResetFlag(flags, flag); } inline NUInt NSetFlagIf(NUInt & flags, NUInt flag, bool condition) { return condition ? NSetFlag(flags, flag) : flags; } inline NUInt NResetFlagIf(NUInt & flags, NUInt flag, bool condition) { return condition ? NResetFlag(flags, flag) : flags; } inline bool NIsMoreThanOneFlagSet(NUInt value) { return (value & (value - 1)) != 0; } template<typename T> T NMax(T a, T b) { return b > a ? b : a; } template<typename T> T NMin(T a, T b) { return b < a ? b : a; } inline NInt NRound(NFloat x) { return (NInt)(x >= 0 ? x + 0.5f : x - 0.5f); } inline NUInt NRoundP(NFloat x) { return (NUInt)(x + 0.5f); } inline NInt NRound(NDouble x) { return (NInt)(x >= 0 ? x + 0.5 : x - 0.5); } inline NUInt NRoundP(NDouble x) { return (NUInt)(x + 0.5); } inline NInt NSqr(NInt x) { return x * x; } inline NFloat NSqr(NFloat x) { return x * x; } inline NDouble NSqr(NDouble x) { return x * x; } template<typename T> void NSwap(T & a, T & b) { T temp = a; a = b; b = temp; } } // Define various types #if defined(N_FRAMEWORK_MFC) #include <Core/NNoDeprecate.h> #include <afx.h> #include <Core/NReDeprecate.h> #elif defined(N_FRAMEWORK_WX) #include <Core/NNoDeprecate.h> #include <memory> #include <wx/string.h> #include <wx/object.h> #include <Core/NReDeprecate.h> #elif defined(N_FRAMEWORK_QT) #include <Core/NNoDeprecate.h> #include <memory> #include <QString> #include <QObject> #include <Core/NReDeprecate.h> #else #define N_FRAMEWORK_NATIVE #include <Core/NNoDeprecate.h> #include <memory> #include <string> #include <Core/NReDeprecate.h> #endif #define N_DECLARE_NON_COPYABLE(name) \ private:\ name(const name &);\ name & operator=(const name &); #define N_NATIVE_TYPE_OF(name) (name::NativeTypeOf()) #define N_DECLARE_TYPE_CLASS(name) \ public:\ static ::Neurotec::NType NativeTypeOf()\ {\ return ::Neurotec::NObject::GetObject< ::Neurotec::NType>(N_TYPE_OF(name), true);\ } #define N_DECLARE_PRIMITIVE_CLASS(name) \ N_DECLARE_NON_COPYABLE(name) #define N_DECLARE_BASIC_CLASS_EX(name, fieldAccess) \ N_DECLARE_TYPE_CLASS(name)\ fieldAccess:\ name##_ value;\ public:\ name(const name & other)\ : value(other.value)\ {\ }\ name & operator=(const name & other)\ {\ this->value = other.value;\ return *this;\ }\ explicit name(name##_ value)\ : value(value)\ {\ }\ name()\ {\ }\ bool operator==(const name & value) const\ {\ return this->value == value.value;\ }\ bool operator!=(const name & value) const\ {\ return this->value != value.value;\ }\ public:\ typedef name##_ NativeType;\ name##_ GetValue() const\ {\ return value;\ } #define N_DECLARE_COMPARABLE_BASIC_CLASS_EX(name, fieldAccess) \ N_DECLARE_BASIC_CLASS_EX(name, fieldAccess)\ public:\ bool operator>(const name & value) const\ {\ return this->value > value.value;\ }\ bool operator<(const name & value) const\ {\ return this->value < value.value;\ }\ bool operator>=(const name & value) const\ {\ return this->value > value.value;\ }\ bool operator<=(const name & value) const\ {\ return this->value < value.value;\ } #define N_DECLARE_BASIC_CLASS(name) N_DECLARE_BASIC_CLASS_EX(name, private) #define N_DECLARE_COMPARABLE_BASIC_CLASS(name) N_DECLARE_COMPARABLE_BASIC_CLASS_EX(name, private) #define N_DECLARE_BASIC_CLASS_BASE(name) N_DECLARE_BASIC_CLASS_EX(name, protected) #define N_DECLARE_COMPARABLE_BASIC_CLASS_BASE(name) N_DECLARE_COMPARABLE_BASIC_CLASS_EX(name, protected) #define N_DECLARE_BASIC_CLASS_DERIVED(name, baseName) \ N_DECLARE_TYPE_CLASS(name)\ public:\ name(const name & other)\ : baseName(other)\ {\ }\ name & operator=(const name & other)\ {\ return (name &)baseName::operator=(other);\ }\ explicit name(name##_ value)\ : baseName(value)\ {\ }\ name()\ {\ }\ bool operator==(const name & value) const\ {\ return baseName::operator==(value);\ }\ bool operator!=(const name & value) const\ {\ return baseName::operator!=(value);\ } #define N_DECLARE_COMPARABLE_BASIC_CLASS_DERIVED(name) \ N_DECLARE_BASIC_CLASS_DERIVED(name)\ public:\ bool operator>(const name & value) const\ {\ return baseName::operator>(value);\ }\ bool operator<(const name & value) const\ {\ return baseName::operator<(value);\ }\ bool operator>=(const name & value) const\ {\ return baseName::operator>=(value);\ }\ bool operator<=(const name & value) const\ {\ return baseName::operator<=(value);\ } #define N_DECLARE_STRUCT_CLASS(name) \ N_DECLARE_TYPE_CLASS(name)\ public:\ typedef struct name##_ NativeType;\ name()\ {\ }\ name(const struct name##_ & value)\ {\ memcpy(this, &value, sizeof(value));\ }\ name & operator=(const struct name##_ & value)\ {\ memcpy(this, &value, sizeof(value));\ return *this;\ } #ifdef N_CPP11 #define N_DISPOSABLE_STRUCT_MOVE_CONSTRUCTOR(name)\ name(name && other)\ {\ memcpy(this, &other, sizeof(other));\ memset(&other, 0, sizeof(other));\ }\ name& operator=(name && other)\ {\ if (this != &other)\ {\ NCheck(name##Dispose(this));\ memcpy(this, &other, sizeof(other));\ memset(&other, 0, sizeof(other));\ }\ return *this;\ } #else #define N_DISPOSABLE_STRUCT_MOVE_CONSTRUCTOR(name) #endif #define N_DECLARE_DISPOSABLE_STRUCT_CLASS(name) \ N_DECLARE_TYPE_CLASS(name)\ public:\ typedef struct name##_ NativeType;\ name()\ {\ memset(this, 0, sizeof(*this));\ }\ name(const name & other)\ {\ NCheck(name##Copy(&other, this));\ }\ N_DISPOSABLE_STRUCT_MOVE_CONSTRUCTOR(name)\ ~name()\ {\ NCheck(name##Dispose(this));\ }\ name & operator=(const name & other)\ {\ NCheck(name##Set(&other, this));\ return *this;\ } namespace Neurotec { class NObject; class NModule; class NType; class NValue; class NArray; class NString; class NStringWrapper; class NPropertyBag; class NObjectPart; namespace Text { class NStringBuilder; } class NException; namespace IO { class NBuffer; class NStream; } namespace Reflection { class NParameterInfo; class NMemberInfo; class NEnumConstantInfo; class NConstantInfo; class NMethodInfo; class NPropertyInfo; class NEventInfo; class NObjectPartInfo; class NCollectionInfo; class NDictionaryInfo; class NArrayCollectionInfo; } namespace Collections { class NCollection; class NDictionary; class NArrayCollection; } NInt NCheck(NResult result); void N_NO_RETURN NThrowArgumentNullException(const NStringWrapper & paramName); void N_NO_RETURN NThrowArgumentOutOfRangeException(const NStringWrapper & paramName); void N_NO_RETURN NThrowArgumentLessThanZeroException(const NStringWrapper & paramName); void N_NO_RETURN NThrowArgumentInsufficientException(const NStringWrapper & paramName); void N_NO_RETURN NThrowArgumentException(const NStringWrapper & paramName); void N_NO_RETURN NThrowInvalidOperationException(const NStringWrapper & message); void N_NO_RETURN NThrowInvalidOperationException(); void N_NO_RETURN NThrowArgumentNotImplementedException(); void N_NO_RETURN NThrowOverflowException(); void N_NO_RETURN NThrowNullReferenceException(); void N_NO_RETURN NThrowNotImplementedException(); void N_NO_RETURN NThrowNotSupportedException(); template<typename T, bool IsNObject = false> struct NTypeTraitsBase { typedef T NativeType; static NType GetNativeType(); static NativeType ToNative(const T & value) { return value; } static T FromNative(NativeType & value, bool claimHandle = true) { return value; N_UNREFERENCED_PARAMETER(claimHandle); } static void SetNative(const NativeType & sourceValue, NativeType * destinationValue) { *destinationValue = sourceValue; } static void FreeNative(NativeType & value) { N_UNREFERENCED_PARAMETER(value); } }; template <typename B, typename D> struct NIsBaseOf { typedef char(&yes)[1]; typedef char(&no)[2]; struct Host { operator B*() const; operator D*(); }; template <typename T> static yes check(D*, T); static no check(B*, int); static const bool value = sizeof(check(Host(), int())) == sizeof(yes); }; template<typename T> struct NTypeTraitsBase<T, true>; template<typename T> struct NTypeTraits : public NTypeTraitsBase<T, NIsBaseOf<NObject, T>::value > { }; #define N_DEFINE_ENUM_TYPE_TRAITS(typeNamespace, type) \ namespace Neurotec\ {\ template<> struct NTypeTraitsBase<typeNamespace::type>\ {\ typedef typeNamespace::type NativeType;\ static NType GetNativeType() { HNType hValue; NCheck(typeNamespace::N_TYPE_OF(type)(&hValue)); return NObject::FromHandle<NType>(hValue, true); }\ static typeNamespace::type ToNative(const typeNamespace::type & value) { return value; }\ static void SetNative(const NativeType & sourceValue, NativeType * destinationValue) { *destinationValue = sourceValue; }\ static typeNamespace::type FromNative(typeNamespace::type value, bool) { return value; }\ static void FreeNative(typeNamespace::type value) { N_UNREFERENCED_PARAMETER(value); }\ };\ } #define N_DEFINE_DISPOSABLE_STRUCT_TYPE_TRAITS(typeNamespace, type) \ namespace Neurotec\ {\ template<> struct NTypeTraitsBase<typeNamespace::type>\ {\ typedef typeNamespace::type##_ NativeType;\ static NType GetNativeType() { HNType hValue; NCheck(typeNamespace::N_TYPE_OF(type)(&hValue)); return NObject::FromHandle<NType>(hValue, true); }\ static NativeType ToNative(const typeNamespace::type & value) { return static_cast<NativeType>(value); }\ static void SetNative(const NativeType & sourceValue, NativeType * destinationValue) { NCheck(type##Set(&sourceValue, destinationValue)); }\ static typeNamespace::type FromNative(NativeType value, bool ownsHandle) { typeNamespace::type s; if (ownsHandle) memcpy(&s, &value, sizeof(NativeType)); else type##Set(&value, &s); return s; }\ static void FreeNative(NativeType & value) { type##Dispose(&value); }\ };\ } #define N_DEFINE_STRUCT_TYPE_TRAITS(typeNamespace, type) \ namespace Neurotec\ {\ template<> struct NTypeTraitsBase<typeNamespace::type>\ {\ typedef typeNamespace::type##_ NativeType;\ static NType GetNativeType() { HNType hValue; NCheck(typeNamespace::N_TYPE_OF(type)(&hValue)); return NObject::FromHandle<NType>(hValue, true); }\ static NativeType ToNative(const typeNamespace::type & value) { return static_cast<NativeType>(value); }\ static void SetNative(const NativeType & sourceValue, NativeType * destinationValue) { *destinationValue = sourceValue; }\ static typeNamespace::type FromNative(NativeType value, bool ownsHandle) { return static_cast<typeNamespace::type>(value); N_UNREFERENCED_PARAMETER(ownsHandle); }\ static void FreeNative(NativeType & value) { N_UNREFERENCED_PARAMETER(value); }\ };\ } } #include <Core/NString.hpp> #include <Core/NCallback.hpp> namespace Neurotec { class NObjectBase { protected: NObjectBase() { } NObjectBase(const NObjectBase&) { } NObjectBase& operator=(const NObjectBase&) { return *this; } public: virtual ~NObjectBase() { } }; #undef NCharTypeOf inline NResult N_API NCharTypeOf(HNType * phValue) { #ifdef N_UNICODE return NWCharTypeOf(phValue); #else return NACharTypeOf(phValue); #endif } class EventArgs { private: HNObject hObject; void * pParam; public: EventArgs(HNObject hObject, void * pParam) { this->hObject = hObject; this->pParam = pParam; } template<typename T> T GetObject() const { return T(hObject, false); } void * GetParam() const { return pParam; } }; template<typename F> class EventHandlerBase { public: F callback; void * pParam; EventHandlerBase(const F & callback) : callback(callback) { } private: static NResult N_API OnFree(void * ptr, void *) { delete static_cast<EventHandlerBase<F> *>(ptr); return 0; } static NResult N_API OnGetHashCode(void * ptr, NInt * pValue, void *) { EventHandlerBase<F> * pHandler = static_cast<EventHandlerBase<F> *>(ptr); #ifdef N_64 *pValue = (NInt)(NHiDWord((NSizeType)pHandler->callback) ^ NLoDWord((NSizeType)pHandler->callback)); #else *pValue = (NInt)(pHandler->callback); #endif return 0; } static NResult N_API OnEquals(void * ptr, void * otherPtr, NBool * pResult, void *) { EventHandlerBase<F> * pHandler = static_cast<EventHandlerBase<F> *>(ptr); EventHandlerBase<F> * pOtherHandler = static_cast<EventHandlerBase<F> *>(otherPtr); *pResult = (pHandler->callback == pOtherHandler->callback) ? NTrue : NFalse; return 0; } template<typename T> static NPointerGetHashCodeProc GetGetHashCodeProc(const T &) { return NULL; } template<typename T> static NPointerGetHashCodeProc GetGetHashCodeProc(T *) { return OnGetHashCode; } template<typename T> static NPointerEqualsProc GetEqualsProc(const T &) { return NULL; } template<typename T> static NPointerEqualsProc GetEqualsProc(T *) { return OnEquals; } friend class NTypes; }; class NTypes { public: struct CallbackParam { private: void * pParam; void * pCallback; void * pCallbackParam; public: CallbackParam(void * pParam, void * pCallback, void * pCallbackParam) : pParam(pParam), pCallback(pCallback), pCallbackParam(pCallbackParam) { } void * GetParam() const { return pParam; } void * GetCallback() const { return pCallback; } void * GetCallbackParam() const { return pCallbackParam; } operator size_t() const { return (size_t)pCallback ^ (size_t)pCallbackParam; } bool operator==(const CallbackParam & other) const { return this->pCallback == other.pCallback && this->pCallbackParam == other.pCallbackParam; } }; template<typename DelegateType, typename CallbackType> static NCallback CreateCallback(CallbackType callback, void * pParam) { std::auto_ptr<DelegateType> callbackDelegate(new DelegateType(callback)); callbackDelegate->pParam = pParam; NCallback cb(DelegateType::NativeCallback, callbackDelegate.get(), DelegateType::OnFree, DelegateType::GetGetHashCodeProc(callback), DelegateType::GetEqualsProc(callback)); callbackDelegate.release(); return cb; } private: static NResult N_API OnCallbackFree(void * ptr, void *); static NResult N_API OnCallbackGetHashCode(void * ptr, NInt * pValue, void *); static NResult N_API OnCallbackEquals(void * ptr, void * otherPtr, NBool * pResult, void *); template<typename T> static NResult N_API OnCallbackWrapperFree(void * ptr, void *); static NResult N_API PointerFreeProcImpl(void * ptr, void * pParam); static NResult N_API PointerGetHashCodeImpl(void * ptr, NInt * pValue, void * pParam); static NResult N_API PointerEqualsImpl(void * ptr, void * otherPtr, NBool * pResult, void * pParam); NTypes(); NTypes & operator=(const NTypes &); public: typedef void (* PointerFreeProc)(const void * ptr, void * pParam); typedef NInt (* PointerGetHashCodeProc)(void * ptr, void * pParam); typedef bool (* PointerEqualsProc)(void * ptr, void * otherPtr, void * pParam); template<typename TNative, typename T> static NCallback CreateCallback(TNative pNativeCallback, T pCallback, void * pCallbackParam) { return CreateCallback<TNative, T>(pNativeCallback, NULL, pCallback, pCallbackParam); } template<typename TNative, typename T> static NCallback CreateCallback(TNative pNativeCallback, void * pParam, T pCallback, void * pCallbackParam) { if (!pCallback) { if (pCallbackParam) NThrowArgumentNullException(N_T("pCallback")); return NCallback(); } ::std::auto_ptr<CallbackParam> p(new CallbackParam(pParam, reinterpret_cast<void *>(pCallback), pCallbackParam)); NCallback callback(pNativeCallback, p.get(), OnCallbackFree, OnCallbackGetHashCode, OnCallbackEquals); p.release(); return callback; } static NType NUInt8NativeTypeOf(); static NType NInt8NativeTypeOf(); static NType NUInt16NativeTypeOf(); static NType NInt16NativeTypeOf(); static NType NUInt32NativeTypeOf(); static NType NInt32NativeTypeOf(); static NType NUInt64NativeTypeOf(); static NType NInt64NativeTypeOf(); static NType NSingleNativeTypeOf(); static NType NDoubleNativeTypeOf(); static NType NBooleanNativeTypeOf(); static NType NSizeTypeNativeTypeOf(); static NType NSSizeTypeNativeTypeOf(); static NType NPointerNativeTypeOf(); static NType NResultNativeTypeOf(); static NType NACharNativeTypeOf(); #ifndef N_NO_UNICODE static NType NWCharNativeTypeOf(); #endif static NType NCharNativeTypeOf(); static NType NStringNativeTypeOf(); static NType NCallbackNativeTypeOf(); static NType NMemoryTypeNativeTypeOf(); static NType NAttributesNativeTypeOf(); static NType NOSFamilyNativeTypeOf(); static NType NativeTypeOf(); #ifndef N_NO_FLOAT static NSingle GetSinglePositiveInfinity() { return NSingleGetPositiveInfinity(); } static NSingle GetSingleNegativeInfinity() { return NSingleGetNegativeInfinity(); } static NSingle GetSingleNaN() { return NSingleGetNaN(); } static bool IsSingleInfinity(NSingle value) { return NSingleIsInfinity(value) != 0; } static bool IsSingleNegativeInfinity(NSingle value) { return NSingleIsNegativeInfinity(value) != 0; } static bool IsSinglePositiveInfinity(NSingle value) { return NSingleIsPositiveInfinity(value) != 0; } static bool IsSingleNaN(NSingle value) { return NSingleIsNaN(value) != 0; } static NDouble GetDoublePositiveInfinity() { return NDoubleGetPositiveInfinity(); } static NDouble GetDoubleNegativeInfinity() { return NDoubleGetNegativeInfinity(); } static NDouble GetDoubleNaN() { return NDoubleGetNaN(); } static bool IsDoubleInfinity(NDouble value) { return NDoubleIsInfinity(value) != 0; } static bool IsDoubleNegativeInfinity(NDouble value) { return NDoubleIsNegativeInfinity(value) != 0; } static bool IsDoublePositiveInfinity(NDouble value) { return NDoubleIsPositiveInfinity(value) != 0; } static bool IsDoubleNaN(NDouble value) { return NDoubleIsNaN(value) != 0; } #endif // !N_NO_FLOAT static NChar CharFromDigit(NInt value) { return NCharFromDigit(value); } static NChar CharFromHexDigit(NInt value, bool lowercase = false) { return NCharFromHexDigit(value, lowercase); } static NChar CharFromOctDigit(NInt value) { return NCharFromOctDigit(value); } static NChar CharFromBinDigit(NInt value) { return NCharFromBinDigit(value); } static NInt CharToChars(NChar value, const NChar * szFormat, NChar * arValue, NInt valueLength) { return NCheck(NCharToChars(value, szFormat, arValue, valueLength)); } static NInt UInt8ToChars(NUInt8 value, const NChar * szFormat, NChar * arValue, NInt valueLength) { return NCheck(NUInt8ToChars(value, szFormat, arValue, valueLength)); } static NInt Int8ToChars(NInt8 value, const NChar * szFormat, NChar * arValue, NInt valueLength) { return NCheck(NInt8ToChars(value, szFormat, arValue, valueLength)); } static NInt UInt16ToChars(NUInt16 value, const NChar * szFormat, NChar * arValue, NInt valueLength) { return NCheck(NUInt16ToChars(value, szFormat, arValue, valueLength)); } static NInt Int16ToChars(NInt16 value, const NChar * szFormat, NChar * arValue, NInt valueLength) { return NCheck(NInt16ToChars(value, szFormat, arValue, valueLength)); } static NInt UInt32ToChars(NUInt32 value, const NChar * szFormat, NChar * arValue, NInt valueLength) { return NCheck(NUInt32ToChars(value, szFormat, arValue, valueLength)); } static NInt Int32ToChars(NInt32 value, const NChar * szFormat, NChar * arValue, NInt valueLength) { return NCheck(NInt32ToChars(value, szFormat, arValue, valueLength)); } #ifndef N_NO_INT_64 static NInt UInt64ToChars(NUInt64 value, const NChar * szFormat, NChar * arValue, NInt valueLength) { return NCheck(NUInt64ToChars(value, szFormat, arValue, valueLength)); } static NInt Int64ToChars(NInt64 value, const NChar * szFormat, NChar * arValue, NInt valueLength) { return NCheck(NInt64ToChars(value, szFormat, arValue, valueLength)); } #endif // !N_NO_INT_64 static NInt SizeTypeToChars(NSizeType value, const NChar * szFormat, NChar * arValue, NInt valueLength) { return NCheck(NSizeTypeToChars(value, szFormat, arValue, valueLength)); } static NInt SSizeTypeToChars(NSSizeType value, const NChar * szFormat, NChar * arValue, NInt valueLength) { return NCheck(NSSizeTypeToChars(value, szFormat, arValue, valueLength)); } static NInt PointerToChars(const void * value, const NChar * szFormat, NChar * arValue, NInt valueLength) { return NCheck(NPointerToChars(value, szFormat, arValue, valueLength)); } #ifndef N_NO_FLOAT static NInt SingleToChars(NSingle value, const NChar * szFormat, NChar * arValue, NInt valueLength) { return NCheck(NSingleToChars(value, szFormat, arValue, valueLength)); } static NInt DoubleToChars(NDouble value, const NChar * szFormat, NChar * arValue, NInt valueLength) { return NCheck(NDoubleToChars(value, szFormat, arValue, valueLength)); } #endif // !N_NO_FLOAT static NInt BooleanToChars(NBoolean value, const NChar * szFormat, NChar * arValue, NInt valueLength) { return NCheck(NBooleanToChars(value, szFormat, arValue, valueLength)); } static NString CharToString(NChar value, const NStringWrapper & format = NString()) { HNString hValue; NCheck(NCharToStringN(value, format.GetHandle(), &hValue)); return NString(hValue, true); } static NString UInt8ToString(NUInt8 value, const NStringWrapper & format = NString()) { HNString hValue; NCheck(NUInt8ToStringN(value, format.GetHandle(), &hValue)); return NString(hValue, true); } static NString Int8ToString(NInt8 value, const NStringWrapper & format = NString()) { HNString hValue; NCheck(NInt8ToStringN(value, format.GetHandle(), &hValue)); return NString(hValue, true); } static NString UInt16ToString(NUInt16 value, const NStringWrapper & format = NString()) { HNString hValue; NCheck(NUInt16ToStringN(value, format.GetHandle(), &hValue)); return NString(hValue, true); } static NString Int16ToString(NInt16 value, const NStringWrapper & format = NString()) { HNString hValue; NCheck(NInt16ToStringN(value, format.GetHandle(), &hValue)); return NString(hValue, true); } static NString UInt32ToString(NUInt32 value, const NStringWrapper & format = NString()) { HNString hValue; NCheck(NUInt32ToStringN(value, format.GetHandle(), &hValue)); return NString(hValue, true); } static NString Int32ToString(NInt32 value, const NStringWrapper & format = NString()) { HNString hValue; NCheck(NInt32ToStringN(value, format.GetHandle(), &hValue)); return NString(hValue, true); } #ifndef N_NO_INT_64 static NString UInt64ToString(NUInt64 value, const NStringWrapper & format = NString()) { HNString hValue; NCheck(NUInt64ToStringN(value, format.GetHandle(), &hValue)); return NString(hValue, true); } static NString Int64ToString(NInt64 value, const NStringWrapper & format = NString()) { HNString hValue; NCheck(NInt64ToStringN(value, format.GetHandle(), &hValue)); return NString(hValue, true); } #endif // !N_NO_INT_64 static NString SizeTypeToString(NSizeType value, const NStringWrapper & format = NString()) { HNString hValue; NCheck(NSizeTypeToStringN(value, format.GetHandle(), &hValue)); return NString(hValue, true); } static NString SSizeTypeToString(NSSizeType value, const NStringWrapper & format = NString()) { HNString hValue; NCheck(NSSizeTypeToStringN(value, format.GetHandle(), &hValue)); return NString(hValue, true); } static NString PointerToString(const void * value, const NStringWrapper & format = NString()) { HNString hValue; NCheck(NPointerToStringN(value, format.GetHandle(), &hValue)); return NString(hValue, true); } #ifndef N_NO_FLOAT static NString SingleToString(NSingle value, const NStringWrapper & format = NString()) { HNString hValue; NCheck(NSingleToStringN(value, format.GetHandle(), &hValue)); return NString(hValue, true); } static NString DoubleToString(NDouble value, const NStringWrapper & format = NString()) { HNString hValue; NCheck(NDoubleToStringN(value, format.GetHandle(), &hValue)); return NString(hValue, true); } #endif // !N_NO_FLOAT static NString BooleanToString(NBoolean value, const NStringWrapper & format = NString()) { HNString hValue; NCheck(NBooleanToStringN(value, format.GetHandle(), &hValue)); return NString(hValue, true); } static bool CharIsWhiteSpace(NChar value) { return NCharIsWhiteSpace(value) != 0; } static bool CharIsAscii(NChar value) { return NCharIsAscii(value) != 0; } static bool CharIsLetter(NChar value) { return NCharIsLetter(value) != 0; } static bool CharIsLower(NChar value) { return NCharIsLower(value) != 0; } static bool CharIsUpper(NChar value) { return NCharIsUpper(value) != 0; } static bool CharIsDigit(NChar value) { return NCharIsDigit(value) != 0; } static bool CharIsHexDigit(NChar value) { return NCharIsHexDigit(value) != 0; } static bool CharIsOctDigit(NChar value) { return NCharIsOctDigit(value) != 0; } static bool CharIsBinDigit(NChar value) { return NCharIsBinDigit(value) != 0; } static NChar CharToLower(NChar value) { return NCharToLower(value); } static NChar CharToUpper(NChar value) { return NCharToUpper(value); } static NInt CharToDigit(NChar value) { return NCharToDigit(value); } static NInt CharToHexDigit(NChar value) { return NCharToHexDigit(value); } static NInt CharToOctDigit(NChar value) { return NCharToOctDigit(value); } static NInt CharToBinDigit(NChar value) { return NCharToBinDigit(value); } static bool CharTryParse(const NChar * arValue, NInt valueLength, const NChar * szFormat, NChar * pValue) { NBool result; NCheck(NCharTryParseStrOrChars(arValue, valueLength, szFormat, pValue, &result)); return result != 0; } static bool UInt8TryParse(const NChar * arValue, NInt valueLength, const NChar * szFormat, NUInt8 * pValue) { NBool result; NCheck(NUInt8TryParseStrOrChars(arValue, valueLength, szFormat, pValue, &result)); return result != 0; } static bool Int8TryParse(const NChar * arValue, NInt valueLength, const NChar * szFormat, NInt8 * pValue) { NBool result; NCheck(NInt8TryParseStrOrChars(arValue, valueLength, szFormat, pValue, &result)); return result != 0; } static bool UInt16TryParse(const NChar * arValue, NInt valueLength, const NChar * szFormat, NUInt16 * pValue) { NBool result; NCheck(NUInt16TryParseStrOrChars(arValue, valueLength, szFormat, pValue, &result)); return result != 0; } static bool Int16TryParse(const NChar * arValue, NInt valueLength, const NChar * szFormat, NInt16 * pValue) { NBool result; NCheck(NInt16TryParseStrOrChars(arValue, valueLength, szFormat, pValue, &result)); return result != 0; } static bool UInt32TryParse(const NChar * arValue, NInt valueLength, const NChar * szFormat, NUInt32 * pValue) { NBool result; NCheck(NUInt32TryParseStrOrChars(arValue, valueLength, szFormat, pValue, &result)); return result != 0; } static bool Int32TryParse(const NChar * arValue, NInt valueLength, const NChar * szFormat, NInt32 * pValue) { NBool result; NCheck(NInt32TryParseStrOrChars(arValue, valueLength, szFormat, pValue, &result)); return result != 0; } #ifndef N_NO_INT_64 static bool UInt64TryParse(const NChar * arValue, NInt valueLength, const NChar * szFormat, NUInt64 * pValue) { NBool result; NCheck(NUInt64TryParseStrOrChars(arValue, valueLength, szFormat, pValue, &result)); return result != 0; } static bool Int64TryParse(const NChar * arValue, NInt valueLength, const NChar * szFormat, NInt64 * pValue) { NBool result; NCheck(NInt64TryParseStrOrChars(arValue, valueLength, szFormat, pValue, &result)); return result != 0; } #endif // !N_NO_INT_64 static bool SizeTypeTryParse(const NChar * arValue, NInt valueLength, const NChar * szFormat, NSizeType * pValue) { NBool result; NCheck(NSizeTypeTryParseStrOrChars(arValue, valueLength, szFormat, pValue, &result)); return result != 0; } static bool SSizeTypeTryParse(const NChar * arValue, NInt valueLength, const NChar * szFormat, NSSizeType * pValue) { NBool result; NCheck(NSSizeTypeTryParseStrOrChars(arValue, valueLength, szFormat, pValue, &result)); return result != 0; } static bool PointerTryParse(const NChar * arValue, NInt valueLength, const NChar * szFormat, void * * pValue) { NBool result; NCheck(NPointerTryParseStrOrChars(arValue, valueLength, szFormat, pValue, &result)); return result != 0; } #ifndef N_NO_FLOAT static bool SingleTryParse(const NChar * arValue, NInt valueLength, const NChar * szFormat, NSingle * pValue) { NBool result; NCheck(NSingleTryParseStrOrChars(arValue, valueLength, szFormat, pValue, &result)); return result != 0; } static bool DoubleTryParse(const NChar * arValue, NInt valueLength, const NChar * szFormat, NDouble * pValue) { NBool result; NCheck(NDoubleTryParseStrOrChars(arValue, valueLength, szFormat, pValue, &result)); return result != 0; } #endif // !N_NO_FLOAT static bool BooleanTryParse(const NChar * arValue, NInt valueLength, const NChar * szFormat, NBoolean * pValue) { NBool result; NCheck(NBooleanTryParseStrOrChars(arValue, valueLength, szFormat, pValue, &result)); return result != 0; } static bool CharTryParse(const NStringWrapper & value, const NStringWrapper & format, NChar * pValue) { NBool result; NCheck(NCharTryParseN(value.GetHandle(), format.GetHandle(), pValue, &result)); return result != 0; } static bool CharTryParse(const NStringWrapper & value, NChar * pValue) { return CharTryParse(value, NString(), pValue); } static bool UInt8TryParse(const NStringWrapper & value, const NStringWrapper & format, NUInt8 * pValue) { NBool result; NCheck(NUInt8TryParseN(value.GetHandle(), format.GetHandle(), pValue, &result)); return result != 0; } static bool UInt8TryParse(const NStringWrapper & value, NUInt8 * pValue) { return UInt8TryParse(value, NString(), pValue); } static bool Int8TryParse(const NStringWrapper & value, const NStringWrapper & format, NInt8 * pValue) { NBool result; NCheck(NInt8TryParseN(value.GetHandle(), format.GetHandle(), pValue, &result)); return result != 0; } static bool Int8TryParse(const NStringWrapper & value, NInt8 * pValue) { return Int8TryParse(value, NString(), pValue); } static bool UInt16TryParse(const NStringWrapper & value, const NStringWrapper & format, NUInt16 * pValue) { NBool result; NCheck(NUInt16TryParseN(value.GetHandle(), format.GetHandle(), pValue, &result)); return result != 0; } static bool UInt16TryParse(const NStringWrapper & value, NUInt16 * pValue) { return UInt16TryParse(value, NString(), pValue); } static bool Int16TryParse(const NStringWrapper & value, const NStringWrapper & format, NInt16 * pValue) { NBool result; NCheck(NInt16TryParseN(value.GetHandle(), format.GetHandle(), pValue, &result)); return result != 0; } static bool Int16TryParse(const NStringWrapper & value, NInt16 * pValue) { return Int16TryParse(value, NString(), pValue); } static bool UInt32TryParse(const NStringWrapper & value, const NStringWrapper & format, NUInt32 * pValue) { NBool result; NCheck(NUInt32TryParseN(value.GetHandle(), format.GetHandle(), pValue, &result)); return result != 0; } static bool UInt32TryParse(const NStringWrapper & value, NUInt32 * pValue) { return UInt32TryParse(value, NString(), pValue); } static bool Int32TryParse(const NStringWrapper & value, const NStringWrapper & format, NInt32 * pValue) { NBool result; NCheck(NInt32TryParseN(value.GetHandle(), format.GetHandle(), pValue, &result)); return result != 0; } static bool Int32TryParse(const NStringWrapper & value, NInt32 * pValue) { return Int32TryParse(value, NString(), pValue); } #ifndef N_NO_INT_64 static bool UInt64TryParse(const NStringWrapper & value, const NStringWrapper & format, NUInt64 * pValue) { NBool result; NCheck(NUInt64TryParseN(value.GetHandle(), format.GetHandle(), pValue, &result)); return result != 0; } static bool UInt64TryParse(const NStringWrapper & value, NUInt64 * pValue) { return UInt64TryParse(value, NString(), pValue); } static bool Int64TryParse(const NStringWrapper & value, const NStringWrapper & format, NInt64 * pValue) { NBool result; NCheck(NInt64TryParseN(value.GetHandle(), format.GetHandle(), pValue, &result)); return result != 0; } static bool Int64TryParse(const NStringWrapper & value, NInt64 * pValue) { return Int64TryParse(value, NString(), pValue); } #endif // !N_NO_INT_64 static bool SizeTypeTryParse(const NStringWrapper & value, const NStringWrapper & format, NSizeType * pValue) { NBool result; NCheck(NSizeTypeTryParseN(value.GetHandle(), format.GetHandle(), pValue, &result)); return result != 0; } static bool SizeTypeTryParse(const NStringWrapper & value, NSizeType * pValue) { return SizeTypeTryParse(value, NString(), pValue); } static bool SSizeTypeTryParse(const NStringWrapper & value, const NStringWrapper & format, NSSizeType * pValue) { NBool result; NCheck(NSSizeTypeTryParseN(value.GetHandle(), format.GetHandle(), pValue, &result)); return result != 0; } static bool SSizeTypeTryParse(const NStringWrapper & value, NSSizeType * pValue) { return SSizeTypeTryParse(value, NString(), pValue); } static bool PointerTryParse(const NStringWrapper & value, const NStringWrapper & format, void * * pValue) { NBool result; NCheck(NPointerTryParseN(value.GetHandle(), format.GetHandle(), pValue, &result)); return result != 0; } static bool PointerTryParse(const NStringWrapper & value, void * * pValue) { return PointerTryParse(value, NString(), pValue); } #ifndef N_NO_FLOAT static bool SingleTryParse(const NStringWrapper & value, const NStringWrapper & format, NSingle * pValue) { NBool result; NCheck(NSingleTryParseN(value.GetHandle(), format.GetHandle(), pValue, &result)); return result != 0; } static bool SingleTryParse(const NStringWrapper & value, NSingle * pValue) { return SingleTryParse(value, NString(), pValue); } static bool DoubleTryParse(const NStringWrapper & value, const NStringWrapper & format, NDouble * pValue) { NBool result; NCheck(NDoubleTryParseN(value.GetHandle(), format.GetHandle(), pValue, &result)); return result != 0; } static bool DoubleTryParse(const NStringWrapper & value, NDouble * pValue) { return DoubleTryParse(value, NString(), pValue); } #endif // !N_NO_FLOAT static bool BooleanTryParse(const NStringWrapper & value, const NStringWrapper & format, NBoolean * pValue) { NBool result; NCheck(NBooleanTryParseN(value.GetHandle(), format.GetHandle(), pValue, &result)); return result != 0; } static bool BooleanTryParse(const NStringWrapper & value, NBoolean * pValue) { return BooleanTryParse(value, NString(), pValue); } static NChar CharParse(const NChar * arValue, NInt valueLength, const NChar * szFormat = NULL) { NChar value; NCheck(NCharParseStrOrChars(arValue, valueLength, szFormat, &value)); return value; } static NUInt8 UInt8Parse(const NChar * arValue, NInt valueLength, const NChar * szFormat = NULL) { NUInt8 value; NCheck(NUInt8ParseStrOrChars(arValue, valueLength, szFormat, &value)); return value; } static NInt8 Int8Parse(const NChar * arValue, NInt valueLength, const NChar * szFormat = NULL) { NInt8 value; NCheck(NInt8ParseStrOrChars(arValue, valueLength, szFormat, &value)); return value; } static NUInt16 UInt16Parse(const NChar * arValue, NInt valueLength, const NChar * szFormat = NULL) { NUInt16 value; NCheck(NUInt16ParseStrOrChars(arValue, valueLength, szFormat, &value)); return value; } static NInt16 Int16Parse(const NChar * arValue, NInt valueLength, const NChar * szFormat = NULL) { NInt16 value; NCheck(NInt16ParseStrOrChars(arValue, valueLength, szFormat, &value)); return value; } static NUInt32 UInt32Parse(const NChar * arValue, NInt valueLength, const NChar * szFormat = NULL) { NUInt32 value; NCheck(NUInt32ParseStrOrChars(arValue, valueLength, szFormat, &value)); return value; } static NInt32 Int32Parse(const NChar * arValue, NInt valueLength, const NChar * szFormat = NULL) { NInt32 value; NCheck(NInt32ParseStrOrChars(arValue, valueLength, szFormat, &value)); return value; } #ifndef N_NO_INT_64 static NUInt64 UInt64Parse(const NChar * arValue, NInt valueLength, const NChar * szFormat = NULL) { NUInt64 value; NCheck(NUInt64ParseStrOrChars(arValue, valueLength, szFormat, &value)); return value; } static NInt64 Int64Parse(const NChar * arValue, NInt valueLength, const NChar * szFormat = NULL) { NInt64 value; NCheck(NInt64ParseStrOrChars(arValue, valueLength, szFormat, &value)); return value; } #endif // !N_NO_INT_64 static NSizeType SizeTypeParse(const NChar * arValue, NInt valueLength, const NChar * szFormat = NULL) { NSizeType value; NCheck(NSizeTypeParseStrOrChars(arValue, valueLength, szFormat, &value)); return value; } static NSSizeType SSizeTypeParse(const NChar * arValue, NInt valueLength, const NChar * szFormat = NULL) { NSSizeType value; NCheck(NSSizeTypeParseStrOrChars(arValue, valueLength, szFormat, &value)); return value; } static void * PointerParse(const NChar * arValue, NInt valueLength, const NChar * szFormat = NULL) { void * value; NCheck(NPointerParseStrOrChars(arValue, valueLength, szFormat, &value)); return value; } #ifndef N_NO_FLOAT static NSingle SingleParse(const NChar * arValue, NInt valueLength, const NChar * szFormat = NULL) { NSingle value; NCheck(NSingleParseStrOrChars(arValue, valueLength, szFormat, &value)); return value; } static NDouble DoubleParse(const NChar * arValue, NInt valueLength, const NChar * szFormat = NULL) { NDouble value; NCheck(NDoubleParseStrOrChars(arValue, valueLength, szFormat, &value)); return value; } #endif // !N_NO_FLOAT static NBoolean BooleanParse(const NChar * arValue, NInt valueLength, const NChar * szFormat = NULL) { NBoolean value; NCheck(NBooleanParseStrOrChars(arValue, valueLength, szFormat, &value)); return value; } static NChar CharParse(const NStringWrapper & value, const NStringWrapper & format = NString()) { NChar result; NCheck(NCharParseN(value.GetHandle(), format.GetHandle(), &result)); return result; } static NUInt8 UInt8Parse(const NStringWrapper & value, const NStringWrapper & format = NString()) { NUInt8 result; NCheck(NUInt8ParseN(value.GetHandle(), format.GetHandle(), &result)); return result; } static NInt8 Int8Parse(const NStringWrapper & value, const NStringWrapper & format = NString()) { NInt8 result; NCheck(NInt8ParseN(value.GetHandle(), format.GetHandle(), &result)); return result; } static NUInt16 UInt16Parse(const NStringWrapper & value, const NStringWrapper & format = NString()) { NUInt16 result; NCheck(NUInt16ParseN(value.GetHandle(), format.GetHandle(), &result)); return result; } static NInt16 Int16Parse(const NStringWrapper & value, const NStringWrapper & format = NString()) { NInt16 result; NCheck(NInt16ParseN(value.GetHandle(), format.GetHandle(), &result)); return result; } static NUInt32 UInt32Parse(const NStringWrapper & value, const NStringWrapper & format = NString()) { NUInt32 result; NCheck(NUInt32ParseN(value.GetHandle(), format.GetHandle(), &result)); return result; } static NInt32 Int32Parse(const NStringWrapper & value, const NStringWrapper & format = NString()) { NInt32 result; NCheck(NInt32ParseN(value.GetHandle(), format.GetHandle(), &result)); return result; } #ifndef N_NO_INT_64 static NUInt64 UInt64Parse(const NStringWrapper & value, const NStringWrapper & format = NString()) { NUInt64 result; NCheck(NUInt64ParseN(value.GetHandle(), format.GetHandle(), &result)); return result; } static NInt64 Int64Parse(const NStringWrapper & value, const NStringWrapper & format = NString()) { NInt64 result; NCheck(NInt64ParseN(value.GetHandle(), format.GetHandle(), &result)); return result; } #endif // !N_NO_INT_64 static NSizeType SizeTypeParse(const NStringWrapper & value, const NStringWrapper & format = NString()) { NSizeType result; NCheck(NSizeTypeParseN(value.GetHandle(), format.GetHandle(), &result)); return result; } static NSSizeType SSizeTypeParse(const NStringWrapper & value, const NStringWrapper & format = NString()) { NSSizeType result; NCheck(NSSizeTypeParseN(value.GetHandle(), format.GetHandle(), &result)); return result; } static void * PointerParse(const NStringWrapper & value, const NStringWrapper & format = NString()) { void * result; NCheck(NPointerParseN(value.GetHandle(), format.GetHandle(), &result)); return result; } #ifndef N_NO_FLOAT static NSingle SingleParse(const NStringWrapper & value, const NStringWrapper & format = NString()) { NSingle result; NCheck(NSingleParseN(value.GetHandle(), format.GetHandle(), &result)); return result; } static NDouble DoubleParse(const NStringWrapper & value, const NStringWrapper & format = NString()) { NDouble result; NCheck(NDoubleParseN(value.GetHandle(), format.GetHandle(), &result)); return result; } #endif // !N_NO_FLOAT static NBoolean BooleanParse(const NStringWrapper & value, const NStringWrapper & format = NString()) { NBoolean result; NCheck(NBooleanParseN(value.GetHandle(), format.GetHandle(), &result)); return result; } static NOSFamily GetOSFamilyCurrent() { return NOSFamilyGetCurrent(); } friend class NValue; friend class NArray; friend class IO::NBuffer; }; #include <Core/NNoDeprecate.h> template<typename T> class NCollectionItemWrapper { private: NByte itemData[sizeof(T)]; bool containsItem; T * GetItemPtr() { return reinterpret_cast<T *>(itemData); } public: NCollectionItemWrapper() : containsItem(false) { } NCollectionItemWrapper(const NCollectionItemWrapper & other) : containsItem(false) { Set(other.Get()); } NCollectionItemWrapper& operator=(const NCollectionItemWrapper & other) { Set(other.Get()); return *this; } ~NCollectionItemWrapper() { Set(NULL); } T * Get() { return containsItem ? GetItemPtr() : NULL; } const T * Get() const { return containsItem ? reinterpret_cast<const T *>(itemData) : NULL; } void Set(const T * pValue) { if (containsItem) { GetItemPtr()->~T(); containsItem = false; } if (pValue) { new (GetItemPtr()) T(*pValue); containsItem = true; } } void Set(const T & value) { Set(&value); } }; template<typename TCollection, typename TElement> class NCollectionIterator : public std::iterator<std::input_iterator_tag, TElement> { private: const TCollection & collection; NCollectionItemWrapper<TElement> currentItem; bool reverse; NInt index; NInt count; public: NCollectionIterator(const TCollection & collection, NInt index, bool reverse = false) : collection(collection), reverse(reverse), index(index), count(collection.GetCount()) { } NCollectionIterator() : collection(), reverse(false), index(), count() { } NCollectionIterator & operator++() { if (reverse) index--; else index++; return *this; } NCollectionIterator & operator++(int) { if (reverse) index--; else index++; return *this; } NCollectionIterator & operator--() { if (reverse) index++; else index--; return *this; } NCollectionIterator & operator--(int) { if (reverse) index++; else index--; return *this; } TElement operator*() const { return collection.Get(index); } TElement * operator->() { currentItem.Set(collection.Get(index)); return currentItem.Get(); } bool operator==(const NCollectionIterator & value) const { return index == value.index; } bool operator!=(const NCollectionIterator & value) const { return index != value.index; } bool operator>(const NCollectionIterator & value) const { return index > value.index; } bool operator>=(const NCollectionIterator & value) const { return index >= value.index; } bool operator<(const NCollectionIterator & value) const { return index < value.index; } bool operator<=(const NCollectionIterator & value) const { return index <= value.index; } NCollectionIterator & operator=(const NCollectionIterator & value) { index = value.index; } }; template<typename TCollection, typename TElement> class NConstCollectionIterator : public NCollectionIterator<TCollection, TElement> { public: NConstCollectionIterator(const TCollection & collection, NInt index, bool reverse = false) : NCollectionIterator<TCollection, TElement>(collection, index, reverse) { } NConstCollectionIterator() { } const TElement operator*() const { return NCollectionIterator<TCollection, TElement>::operator*(); } const TElement * operator->() { return NCollectionIterator<TCollection, TElement>::operator->(); } }; template<typename T> class NArrayWrapper { public: typedef T value_type; typedef NCollectionIterator<NArrayWrapper, T> iterator; typedef NConstCollectionIterator<NArrayWrapper, T> const_iterator; typedef NCollectionIterator<NArrayWrapper, T> reverse_iterator; typedef NConstCollectionIterator<NArrayWrapper, T> reverse_const_iterator; private: typedef typename NTypeTraits<T>::NativeType THandle; THandle * arNativeValues; NInt count; bool ownsHandles; bool ownsPtr; static THandle * Alloc(NInt count) { if (count == 0) return NULL; if (count < 0) NThrowArgumentLessThanZeroException(N_T("count")); if (N_SIZE_TYPE_MAX / sizeof(THandle) < (NSizeType)count) NThrowOverflowException(); return reinterpret_cast<THandle *>(NCAlloc((NSizeType)count * sizeof(THandle))); } void ClearInternal() { if (ownsHandles) { for (int i = 0; i < count; i++) NTypeTraits<T>::FreeNative(arNativeValues[i]); } if (ownsPtr) NFree(arNativeValues); } public: explicit NArrayWrapper(NInt count, bool ownsHandles = true) : arNativeValues(Alloc(count)), count(count), ownsHandles(ownsHandles), ownsPtr(true) { } NArrayWrapper(THandle * arNativeValues, NInt count, bool ownsHandles = true, bool ownsPtr = true) : arNativeValues(arNativeValues), count(count), ownsHandles(ownsHandles), ownsPtr(ownsPtr) { } template<typename InputIt> NArrayWrapper(InputIt first, InputIt last) : arNativeValues(NULL), count(0), ownsHandles(true), ownsPtr(true) { NInt allocatedCount = 0; for (; first != last; ++first) { if (allocatedCount <= count) { NInt newCount = count == 0 ? 16 : count * 3 / 2; NSizeType newSize = (NSizeType)newCount * sizeof(THandle); arNativeValues = reinterpret_cast<THandle *>(NReAlloc(arNativeValues, newSize)); allocatedCount = newCount; } memset(&arNativeValues[count], 0, sizeof(arNativeValues[0])); NTypeTraits<T>::SetNative(NTypeTraits<T>::ToNative(*first), &arNativeValues[count]); count++; } } NArrayWrapper(const NArrayWrapper<T> & other) { this->count = other.count; this->ownsHandles = other.ownsHandles; this->ownsPtr = other.ownsPtr; if (other.ownsPtr) { arNativeValues = Alloc(other.count); if (other.ownsHandles) { for (int i = 0; i < count; i++) { NTypeTraits<T>::SetNative(other.arNativeValues[i], &arNativeValues[i]); } } else { memcpy(arNativeValues, other.arNativeValues, sizeof(other.arNativeValues[0]) * count); } } else { arNativeValues = other.arNativeValues; } } #ifdef N_CPP11 NArrayWrapper(NArrayWrapper<T> && other) : arNativeValues(other.arNativeValues), count(other.count), ownsHandles(other.ownsHandles), ownsPtr(other.ownsPtr) { other.arNativeValues = NULL; other.count = 0; other.ownsHandles = false; other.ownsPtr = false; } #endif NArrayWrapper<T>& operator=(NArrayWrapper<T> other) { std::swap(arNativeValues, other.arNativeValues); std::swap(count, other.count); std::swap(ownsHandles, other.ownsHandles); std::swap(ownsPtr, other.ownsPtr); return *this; } ~NArrayWrapper() { ClearInternal(); } void SetCount(int value) { if (ownsHandles) { for (int i = value; i < count; i++) NTypeTraits<T>::FreeNative(arNativeValues[i]); } count = value; } int GetCount() const { return count; } const THandle * GetPtr() const { return arNativeValues; } THandle * GetPtr() { return arNativeValues; } THandle * Release(NInt * pCount = NULL) { THandle * ptr = arNativeValues; if (pCount) *pCount = count; arNativeValues = NULL; count = 0; return ptr; } T Get(int index) const { if (index < 0 || index >= count) NThrowArgumentOutOfRangeException(N_T("index")); return NTypeTraits<T>::FromNative(arNativeValues[index], false); } T operator[](int index) const { return NTypeTraits<T>::FromNative(arNativeValues[index], false); } /* T * ToArray(NInt * pCount = NULL) { return ToArray(count, pCount); } T * ToArray(NInt realCount, NInt * pCount = NULL) { if (realCount < 0) NThrowArgumentLessThanZeroException(N_T("realCount")); auto_array<T> pObjects(realCount); CopyTo(pObjects.get(), realCount, realCount); if (pCount) *pCount = realCount; return pObjects.release(); } */ NInt CopyTo(T * arpValues, NInt valuesLength) { return CopyTo(arpValues, valuesLength, count); } NInt CopyTo(T * arpValues, NInt valuesLength, NInt realCount) const { if (!arpValues && valuesLength != 0) NThrowArgumentNullException(N_T("arpValues")); if (valuesLength < 0) NThrowArgumentLessThanZeroException(N_T("valuesLength")); if (valuesLength < realCount) NThrowArgumentInsufficientException(N_T("valuesLength")); if (realCount < 0) NThrowArgumentLessThanZeroException(N_T("realCount")); if (realCount > count) NThrowArgumentException(N_T("realCount is greater than count")); const THandle * phObject = arNativeValues; T * pObject = arpValues; NInt i = 0; for (; i < realCount; i++, phObject++, pObject++) { THandle hObject = *phObject; *pObject = NTypeTraits<T>::FromNative(hObject, false); } return realCount; } iterator begin() { return iterator(*this, 0); } const_iterator begin() const { return const_iterator(*this, 0); } iterator end() { return iterator(*this, GetCount()); } const_iterator end() const { return const_iterator(*this, GetCount()); } reverse_iterator rbegin() { return reverse_iterator(*this, GetCount() - 1, true); } reverse_const_iterator rbegin() const { return reverse_const_iterator(*this, GetCount() - 1, true); } reverse_iterator rend() { return reverse_iterator(*this, 0, true); } reverse_const_iterator rend() const { return reverse_const_iterator(*this, 0, true); } }; #include <Core/NReDeprecate.h> } #ifdef N_NEED_HASH N_HASH_NAMESPACE_BEGIN template<> struct hash< ::Neurotec::NTypes::CallbackParam> { size_t operator()(::Neurotec::NTypes::CallbackParam const & k) const { return (size_t)k; } }; N_HASH_NAMESPACE_END #endif #include <Core/NType.hpp> N_DEFINE_ENUM_TYPE_TRAITS(Neurotec, NAttributes) N_DEFINE_ENUM_TYPE_TRAITS(Neurotec, NOSFamily) N_DEFINE_ENUM_TYPE_TRAITS(Neurotec, NMemoryType) namespace Neurotec { template<typename T, bool IsNObject> inline NType NTypeTraitsBase<T, IsNObject>::GetNativeType() { return T::NativeTypeOf(); } inline NResult N_API NTypes::OnCallbackFree(void * ptr, void *) { delete reinterpret_cast<CallbackParam *>(ptr); return N_OK; } inline NResult N_API NTypes::OnCallbackGetHashCode(void * ptr, NInt * pValue, void *) { NResult result = N_OK; try { if (!pValue) NThrowArgumentNullException(N_T("pValue")); size_t hashCode = (size_t)*reinterpret_cast<CallbackParam *>(ptr); #ifdef N_64 *pValue = (NInt)((hashCode >> 32) ^ (hashCode & 0xFFFFFFFF)); #else *pValue = (NInt)hashCode; #endif } N_EXCEPTION_CATCH_AND_SET_LAST(result); return result; } inline NResult N_API NTypes::OnCallbackEquals(void * ptr, void * otherPtr, NBool * pResult, void *) { NResult result = N_OK; try { if (!pResult) NThrowArgumentNullException(N_T("pResult")); *pResult = *reinterpret_cast<CallbackParam *>(ptr) == *reinterpret_cast<CallbackParam *>(otherPtr); } N_EXCEPTION_CATCH_AND_SET_LAST(result); return result; } template<typename T> inline NResult N_API NTypes::OnCallbackWrapperFree(void * ptr, void *) { delete reinterpret_cast<T *>(ptr); return N_OK; } inline NResult N_API NTypes::PointerFreeProcImpl(void * ptr, void * pParam) { NResult result = N_OK; try { CallbackParam * p = reinterpret_cast<CallbackParam *>(pParam); reinterpret_cast<PointerFreeProc>(p->GetCallback())(ptr, p->GetCallbackParam()); } N_EXCEPTION_CATCH_AND_SET_LAST(result); return result; } inline NResult N_API NTypes::PointerGetHashCodeImpl(void * ptr, NInt * pValue, void * pParam) { NResult result = N_OK; try { if (!pValue) NThrowArgumentNullException(N_T("pValue")); CallbackParam * p = reinterpret_cast<CallbackParam *>(pParam); *pValue = reinterpret_cast<PointerGetHashCodeProc>(p->GetCallback())(ptr, p->GetCallbackParam()); } N_EXCEPTION_CATCH_AND_SET_LAST(result); return result; } inline NResult N_API NTypes::PointerEqualsImpl(void * ptr, void * otherPtr, NBool * pResult, void * pParam) { NResult result = N_OK; try { if (!pResult) NThrowArgumentNullException(N_T("pResult")); CallbackParam * p = reinterpret_cast<CallbackParam *>(pParam); *pResult = reinterpret_cast<PointerEqualsProc>(p->GetCallback())(ptr, otherPtr, p->GetCallbackParam()); } N_EXCEPTION_CATCH_AND_SET_LAST(result); return result; } inline NCallback::NCallback(void * pProc, const NObject & object) : handle(NULL) { NCheck(NCallbackCreateWithObjectRaw(pProc, object.GetHandle(), &handle)); } template<typename T> inline NCallback::NCallback(T pProc, const NObject & object) : handle(NULL) { NCheck(NCallbackCreateWithObject(pProc, object.GetHandle(), &handle)); } class NGuid : public NGuid_ { N_DECLARE_STRUCT_CLASS(NGuid) public: static bool TryParse(const NStringWrapper & value, const NStringWrapper & format, NGuid * pValue) { NBool result; NCheck(NGuidTryParseN(value.GetHandle(), format.GetHandle(), pValue, &result)); return result != 0; } static bool TryParse(const NStringWrapper & value, NGuid * pValue) { return TryParse(value, NString(), pValue); } static NGuid Parse(const NStringWrapper & value, const NStringWrapper & format = NString()) { NGuid theValue; NCheck(NGuidParseN(value.GetHandle(), format.GetHandle(), &theValue)); return theValue; } NString ToString(const NStringWrapper & format = NString()) const { HNString hValue; NCheck(NGuidToStringN(this, format.GetHandle(), &hValue)); return NString(hValue, true); } }; class NURational : public NURational_ { N_DECLARE_STRUCT_CLASS(NURational) public: NURational(NUInt numerator, NUInt denominator) { Numerator = numerator; Denominator = denominator; } NString ToString(const NStringWrapper & format = NString()) const { HNString hValue; NCheck(NURationalToStringN(this, format.GetHandle(), &hValue)); return NString(hValue, true); } }; class NRational : public NRational_ { N_DECLARE_STRUCT_CLASS(NRational) public: NRational(NInt numerator, NInt denominator) { Numerator = numerator; Denominator = denominator; } NString ToString(const NStringWrapper & format = NString()) const { HNString hValue; NCheck(NRationalToStringN(this, format.GetHandle(), &hValue)); return NString(hValue, true); } }; class NComplex : public NComplex_ { N_DECLARE_STRUCT_CLASS(NComplex) public: NComplex(NDouble real, NDouble imaginary) { Real = real; Imaginary = imaginary; } NString ToString(const NStringWrapper & format = NString()) const { HNString hValue; NCheck(NComplexToStringN(this, format.GetHandle(), &hValue)); return NString(hValue, true); } }; class NIndexPair : public NIndexPair_ { N_DECLARE_STRUCT_CLASS(NIndexPair) public: NIndexPair(NInt index1, NInt index2) { Index1 = index1; Index2 = index2; } NString ToString(const NStringWrapper & format = NString()) const { HNString hValue; NCheck(NIndexPairToStringN(this, format.GetHandle(), &hValue)); return NString(hValue, true); } }; class NRange : public NRange_ { N_DECLARE_STRUCT_CLASS(NRange) public: NRange(NInt from, NInt to) { From = from; To = to; } NString ToString(const NStringWrapper & format = NString()) const { HNString hValue; NCheck(NRangeToStringN(this, format.GetHandle(), &hValue)); return NString(hValue, true); } }; class NVersion { N_DECLARE_COMPARABLE_BASIC_CLASS(NVersion) public: NVersion(NInt major, NInt minor) : value(NVersionMake(major, minor)) { if (major < N_BYTE_MIN || major > N_BYTE_MAX) NThrowArgumentOutOfRangeException(N_T("major")); if (minor < N_BYTE_MIN || minor > N_BYTE_MAX) NThrowArgumentOutOfRangeException(N_T("minor")); } NString ToString(const NStringWrapper & format = NString()) const { HNString hValue; NCheck(NVersionToStringN(value, format.GetHandle(), &hValue)); return NString(hValue, true); } NInt GetMajor() const { return NVersionGetMajor(value); } NInt GetMinor() const { return NVersionGetMinor(value); } }; class NVersionRange { N_DECLARE_BASIC_CLASS(NVersionRange) public: static NVersionRange Intersect(const NVersionRange & value1, const NVersionRange & value2) { return NVersionRange(NVersionRangeIntersect(value1.value, value2.value)); } NVersionRange(const NVersion & from, const NVersion & to) : value(NVersionRangeMake(from.GetValue(), to.GetValue())) { } NString ToString(const NStringWrapper & format = NString()) const { HNString hValue; NCheck(NVersionRangeToStringN(value, format.GetHandle(), &hValue)); return NString(hValue, true); } bool Contains(const NVersion & value) const { return NVersionRangeContains(this->value, value.GetValue()) != 0; } bool Contains(const NVersionRange & value) const { return NVersionRangeContainsRange(this->value, value.value) != 0; } bool IntersectsWith(const NVersionRange & value) const { return NVersionRangeIntersectsWith(this->value, value.value) != 0; } NVersionRange Intersect(const NVersionRange & value) const { return Intersect(*this, value); } NVersion GetFrom() const { return NVersion(NVersionRangeGetFrom(value)); } NVersion GetTo() const { return NVersion(NVersionRangeGetTo(value)); } }; class NNameStringPair : public NNameStringPair_ { N_DECLARE_DISPOSABLE_STRUCT_CLASS(NNameStringPair) public: NNameStringPair(const NStringWrapper & key, const NStringWrapper & value) { NCheck(NNameStringPairCreateN(key.GetHandle(), value.GetHandle(), this)); } NString GetKey() const { return NString(hKey, false); } void SetName(const NStringWrapper & value) { NCheck(NStringSet(value.GetHandle(), &hKey)); } NString GetValue() const { return NString(hValue, false); } void SetValue(const NStringWrapper & value) { NCheck(NStringSet(value.GetHandle(), &hValue)); } }; inline NType NTypes::NUInt8NativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NUInt8), true); } inline NType NTypes::NInt8NativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NInt8), true); } inline NType NTypes::NUInt16NativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NUInt16), true); } inline NType NTypes::NInt16NativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NInt16), true); } inline NType NTypes::NUInt32NativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NUInt32), true); } inline NType NTypes::NInt32NativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NInt32), true); } inline NType NTypes::NUInt64NativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NUInt64), true); } inline NType NTypes::NInt64NativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NInt64), true); } inline NType NTypes::NSingleNativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NSingle), true); } inline NType NTypes::NDoubleNativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NDouble), true); } inline NType NTypes::NBooleanNativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NBoolean), true); } inline NType NTypes::NSizeTypeNativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NSizeType), true); } inline NType NTypes::NSSizeTypeNativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NSSizeType), true); } inline NType NTypes::NPointerNativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NPointer), true); } inline NType NTypes::NResultNativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NResult), true); } inline NType NTypes::NACharNativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NAChar), true); } #ifndef N_NO_UNICODE inline NType NTypes::NWCharNativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NAChar), true); } #endif inline NType NTypes::NCharNativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NChar), true); } inline NType NTypes::NStringNativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NString), true); } inline NType NTypes::NCallbackNativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NCallback), true); } inline NType NTypes::NMemoryTypeNativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NMemoryType), true); } inline NType NTypes::NAttributesNativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NAttributes), true); } inline NType NTypes::NOSFamilyNativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NOSFamily), true); } inline NType NTypes::NativeTypeOf() { return NObject::GetObject<NType>(N_TYPE_OF(NTypes), true); } } N_DEFINE_DISPOSABLE_STRUCT_TYPE_TRAITS(Neurotec, NNameStringPair); #endif // !N_TYPES_HPP_INCLUDED
[ "vikas.pandey06081986@gmail.com" ]
vikas.pandey06081986@gmail.com
d2bc25a529261e345a1b6da9bd1f449cd070d77d
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/ms/src/v20180408/model/SDKPlan.cpp
f4f51a2a39a0f7263c24e3f5e4e92aa925206412
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
1,953
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/ms/v20180408/model/SDKPlan.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Ms::V20180408::Model; using namespace std; SDKPlan::SDKPlan() : m_planIdHasBeenSet(false) { } CoreInternalOutcome SDKPlan::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("PlanId") && !value["PlanId"].IsNull()) { if (!value["PlanId"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `SDKPlan.PlanId` IsInt64=false incorrectly").SetRequestId(requestId)); } m_planId = value["PlanId"].GetInt64(); m_planIdHasBeenSet = true; } return CoreInternalOutcome(true); } void SDKPlan::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_planIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PlanId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_planId, allocator); } } int64_t SDKPlan::GetPlanId() const { return m_planId; } void SDKPlan::SetPlanId(const int64_t& _planId) { m_planId = _planId; m_planIdHasBeenSet = true; } bool SDKPlan::PlanIdHasBeenSet() const { return m_planIdHasBeenSet; }
[ "tencentcloudapi@tencent.com" ]
tencentcloudapi@tencent.com
329e945110a392e346223edb7814dbdee1ff117d
c17bfeb1d60a4bff2cddb3d556479fc8eaa18800
/thridparty/ANTLR/antlr3baserecognizer.inl
ce92bdb92525c7c82812aaf5998e292e035b4e89
[]
no_license
richardw347/STRP_V2
c62c9ff55640489c03dab4e7337a578c5ce012be
18d6925c8b4a6f1f5c6f30f2f55a773b79f2125e
refs/heads/master
2021-01-13T01:49:03.830488
2015-05-18T16:20:52
2015-05-18T16:20:52
35,823,427
0
0
null
null
null
null
UTF-8
C++
false
false
27,302
inl
ANTLR_BEGIN_NAMESPACE() template< class ImplTraits, class StreamType > BaseRecognizer<ImplTraits, StreamType>::BaseRecognizer(ANTLR_UINT32 sizeHint, RecognizerSharedStateType* state) { m_debugger = NULL; // If we have been supplied with a pre-existing recognizer state // then we just install it, otherwise we must create one from scratch // if (state == NULL) { m_state = new RecognizerSharedStateType(); m_state->set_sizeHint( sizeHint ); } else { // Install the one we were given, and do not reset it here // as it will either already have been initialized or will // be in a state that needs to be preserved. // m_state = state; } } template< class ImplTraits, class StreamType > ANTLR_INLINE typename BaseRecognizer<ImplTraits, StreamType>::SuperType* BaseRecognizer<ImplTraits, StreamType>::get_super() { return static_cast<SuperType*>(this); } template< class ImplTraits, class StreamType > ANTLR_INLINE typename BaseRecognizer<ImplTraits, StreamType>::RecognizerSharedStateType* BaseRecognizer<ImplTraits, StreamType>::get_state() const { return m_state; } template< class ImplTraits, class StreamType > ANTLR_INLINE typename BaseRecognizer<ImplTraits, StreamType>::DebugEventListenerType* BaseRecognizer<ImplTraits, StreamType>::get_debugger() const { return m_debugger; } template< class ImplTraits, class StreamType > ANTLR_INLINE void BaseRecognizer<ImplTraits, StreamType>::set_state( RecognizerSharedStateType* state ) { m_state = state; } template< class ImplTraits, class StreamType > ANTLR_INLINE void BaseRecognizer<ImplTraits, StreamType>::set_debugger( DebugEventListenerType* debugger ) { m_debugger = debugger; } template< class ImplTraits, class StreamType > const typename BaseRecognizer<ImplTraits, StreamType>::UnitType* BaseRecognizer<ImplTraits, StreamType>::match(ANTLR_UINT32 ttype, BitsetListType* follow) { SuperType* super = static_cast<SuperType*>(this); IntStreamType* is = super->get_istream(); // Pick up the current input token/node for assignment to labels // const UnitType* matchedSymbol = this->getCurrentInputSymbol(is); if (is->_LA(1) == ttype) { // The token was the one we were told to expect // is->consume(); // Consume that token from the stream m_state->set_errorRecovery(false); // Not in error recovery now (if we were) m_state->set_failed(false); // The match was a success return matchedSymbol; // We are done } // We did not find the expected token type, if we are backtracking then // we just set the failed flag and return. // if ( m_state->get_backtracking() > 0) { // Backtracking is going on // m_state->set_failed(true); return matchedSymbol; } // We did not find the expected token and there is no backtracking // going on, so we mismatch, which creates an exception in the recognizer exception // stack. // matchedSymbol = this->recoverFromMismatchedToken(ttype, follow); return matchedSymbol; } template< class ImplTraits, class StreamType > void BaseRecognizer<ImplTraits, StreamType>::matchAny() { SuperType* super = static_cast<SuperType*>(this); IntStreamType* is = super->get_istream(); is->consume(); m_state->set_errorRecovery(false); m_state->set_failed(false); return; } template< class ImplTraits, class StreamType > bool BaseRecognizer<ImplTraits, StreamType>::mismatchIsUnwantedToken(IntStreamType* is, ANTLR_UINT32 ttype) { ANTLR_UINT32 nextt = is->_LA(2); if (nextt == ttype) { if(m_state->get_exception() != NULL) m_state->get_exception()->set_expecting(nextt); return true; // This token is unknown, but the next one is the one we wanted } else return false; // Neither this token, nor the one following is the one we wanted } template< class ImplTraits, class StreamType > bool BaseRecognizer<ImplTraits, StreamType>::mismatchIsMissingToken(IntStreamType* is, BitsetListType* follow) { bool retcode; BitsetType* followClone; BitsetType* viableTokensFollowingThisRule; if (follow == NULL) { // There is no information about the tokens that can follow the last one // hence we must say that the current one we found is not a member of the // follow set and does not indicate a missing token. We will just consume this // single token and see if the parser works it out from there. // return false; } followClone = NULL; viableTokensFollowingThisRule = NULL; // The C bitset maps are laid down at compile time by the // C code generation. Hence we cannot remove things from them // and so on. So, in order to remove EOR (if we need to) then // we clone the static bitset. // followClone = follow->bitsetLoad(); if (followClone == NULL) return false; // Compute what can follow this grammar reference // if (followClone->isMember( ImplTraits::CommonTokenType::EOR_TOKEN_TYPE)) { // EOR can follow, but if we are not the start symbol, we // need to remove it. // followClone->remove(ImplTraits::CommonTokenType::EOR_TOKEN_TYPE); // Now compute the visiable tokens that can follow this rule, according to context // and make them part of the follow set. // viableTokensFollowingThisRule = this->computeCSRuleFollow(); followClone->borInPlace(viableTokensFollowingThisRule); } /// if current token is consistent with what could come after set /// then we know we're missing a token; error recovery is free to /// "insert" the missing token /// /// BitSet cannot handle negative numbers like -1 (EOF) so I leave EOR /// in follow set to indicate that the fall of the start symbol is /// in the set (EOF can follow). /// if ( followClone->isMember(is->_LA(1)) || followClone->isMember(ImplTraits::CommonTokenType::EOR_TOKEN_TYPE) ) { retcode = true; } else { retcode = false; } if (viableTokensFollowingThisRule != NULL) { delete viableTokensFollowingThisRule; } if (followClone != NULL) { delete followClone; } return retcode; } template< class ImplTraits, class StreamType > void BaseRecognizer<ImplTraits, StreamType>::mismatch(ANTLR_UINT32 ttype, BitsetListType* follow) { this->get_super()->mismatch( ttype, follow ); } template< class ImplTraits, class StreamType > void BaseRecognizer<ImplTraits, StreamType>::reportError() { this->reportError( ClassForwarder<SuperType>() ); } template< class ImplTraits, class StreamType > void BaseRecognizer<ImplTraits, StreamType>::reportError( ClassForwarder<LexerType> ) { // Indicate this recognizer had an error while processing. // m_state->inc_errorCount(); this->displayRecognitionError(m_state->get_tokenNames()); } template< class ImplTraits, class StreamType > template<typename CompType> void BaseRecognizer<ImplTraits, StreamType>::reportError(ClassForwarder<CompType> ) { // Invoke the debugger event if there is a debugger listening to us // if ( m_debugger != NULL) { m_debugger->recognitionException( m_state->get_exception() ); } if ( m_state->get_errorRecovery() == true) { // Already in error recovery so don't display another error while doing so // return; } // Signal we are in error recovery now // m_state->set_errorRecovery(true); // Indicate this recognizer had an error while processing. // m_state->inc_errorCount(); // Call the error display routine // this->displayRecognitionError( m_state->get_tokenNames() ); } template< class ImplTraits, class StreamType > void BaseRecognizer<ImplTraits, StreamType>::displayRecognitionError(ANTLR_UINT8** tokenNames) { // Retrieve some info for easy reading. // ExceptionBaseType* ex = m_state->get_exception(); StringType ttext; // See if there is a 'filename' we can use // SuperType* super = static_cast<SuperType*>(this); super->displayRecognitionError(tokenNames, ex); } template< class ImplTraits, class StreamType > ANTLR_UINT32 BaseRecognizer<ImplTraits, StreamType>::getNumberOfSyntaxErrors() { return m_state->get_errorCount(); } template< class ImplTraits, class StreamType > void BaseRecognizer<ImplTraits, StreamType>::recover() { SuperType* super = static_cast<SuperType*>(this); IntStreamType* is = super->get_parser_istream(); // Are we about to repeat the same error? // if ( m_state->get_lastErrorIndex() == is->index()) { // The last error was at the same token index point. This must be a case // where LT(1) is in the recovery token set so nothing is // consumed. Consume a single token so at least to prevent // an infinite loop; this is a failsafe. // is->consume(); } // Record error index position // m_state->set_lastErrorIndex( is->index() ); // Work out the follows set for error recovery // BitsetType* followSet = this->computeErrorRecoverySet(); // Call resync hook (for debuggers and so on) // this->beginResync(); // Consume tokens until we have resynced to something in the follows set // this->consumeUntilSet(followSet); // End resync hook // this->endResync(); // Destroy the temporary bitset we produced. // delete followSet; // Reset the inError flag so we don't re-report the exception // m_state->set_error(false); m_state->set_failed(false); } template< class ImplTraits, class StreamType > void BaseRecognizer<ImplTraits, StreamType>::beginResync() { if (m_debugger != NULL) { m_debugger->beginResync(); } } template< class ImplTraits, class StreamType > void BaseRecognizer<ImplTraits, StreamType>::endResync() { if (m_debugger != NULL) { m_debugger->endResync(); } } template< class ImplTraits, class StreamType > void BaseRecognizer<ImplTraits, StreamType>::beginBacktrack(ANTLR_UINT32 level) { if (m_debugger != NULL) { m_debugger->beginBacktrack(level); } } template< class ImplTraits, class StreamType > void BaseRecognizer<ImplTraits, StreamType>::endBacktrack(ANTLR_UINT32 level, bool successful) { if (m_debugger != NULL) { m_debugger->endBacktrack(level); } } template< class ImplTraits, class StreamType > typename BaseRecognizer<ImplTraits, StreamType>::BitsetType* BaseRecognizer<ImplTraits, StreamType>::computeErrorRecoverySet() { return this->combineFollows(false); } template< class ImplTraits, class StreamType > typename BaseRecognizer<ImplTraits, StreamType>::BitsetType* BaseRecognizer<ImplTraits, StreamType>::computeCSRuleFollow() { return this->combineFollows(false); } template< class ImplTraits, class StreamType > typename BaseRecognizer<ImplTraits, StreamType>::BitsetType* BaseRecognizer<ImplTraits, StreamType>::combineFollows(bool exact) { BitsetType* followSet; BitsetType* localFollowSet; ANTLR_UINT32 top; ANTLR_UINT32 i; top = static_cast<ANTLR_UINT32>( m_state->get_following().size() ); followSet = new BitsetType(0); localFollowSet = NULL; for (i = top; i>0; i--) { localFollowSet = m_state->get_following().at(i-1).bitsetLoad(); if (localFollowSet != NULL) { followSet->borInPlace(localFollowSet); if (exact == true) { if (localFollowSet->isMember( ImplTraits::CommonTokenType::EOR_TOKEN_TYPE) == false) { // Only leave EOR in the set if at top (start rule); this lets us know // if we have to include the follow(start rule); I.E., EOF // if (i>1) { followSet->remove(ImplTraits::CommonTokenType::EOR_TOKEN_TYPE); } } else { break; // Cannot see End Of Rule from here, just drop out } } delete localFollowSet; localFollowSet = NULL; } } if (localFollowSet != NULL) { delete localFollowSet; } return followSet; } template< class ImplTraits, class StreamType > const typename BaseRecognizer<ImplTraits, StreamType>::UnitType* BaseRecognizer<ImplTraits, StreamType>::recoverFromMismatchedToken( ANTLR_UINT32 ttype, BitsetListType* follow) { SuperType* super = static_cast<SuperType*>(this); IntStreamType* is = super->get_parser_istream(); const UnitType* matchedSymbol; // If the next token after the one we are looking at in the input stream // is what we are looking for then we remove the one we have discovered // from the stream by consuming it, then consume this next one along too as // if nothing had happened. // if ( this->mismatchIsUnwantedToken( is, ttype) == true) { // Create an exception if we need one // new ANTLR_Exception<ImplTraits, UNWANTED_TOKEN_EXCEPTION, StreamType>(this, ""); // Call resync hook (for debuggers and so on) // if (m_debugger != NULL) { m_debugger->beginResync(); } // "delete" the extra token // this->beginResync(); is->consume(); this->endResync(); // End resync hook // if (m_debugger != NULL) { m_debugger->endResync(); } // Print out the error after we consume so that ANTLRWorks sees the // token in the exception. // this->reportError(); // Return the token we are actually matching // matchedSymbol = this->getCurrentInputSymbol(is); // Consume the token that the rule actually expected to get as if everything // was hunky dory. // is->consume(); m_state->set_error(false); // Exception is not outstanding any more return matchedSymbol; } // Single token deletion (Unwanted above) did not work // so we see if we can insert a token instead by calculating which // token would be missing // if ( this->mismatchIsMissingToken(is, follow)) { // We can fake the missing token and proceed // new ANTLR_Exception<ImplTraits, MISSING_TOKEN_EXCEPTION, StreamType>(this, ""); matchedSymbol = this->getMissingSymbol( is, m_state->get_exception(), ttype, follow); m_state->get_exception()->set_token( matchedSymbol ); m_state->get_exception()->set_expecting(ttype); // Print out the error after we insert so that ANTLRWorks sees the // token in the exception. // this->reportError(); m_state->set_error(false); // Exception is not outstanding any more return matchedSymbol; } // Create an exception if we need one // new ANTLR_Exception<ImplTraits, RECOGNITION_EXCEPTION, StreamType>(this, ""); // Neither deleting nor inserting tokens allows recovery // must just report the exception. // m_state->set_error(true); return NULL; } template< class ImplTraits, class StreamType > const typename BaseRecognizer<ImplTraits, StreamType>::UnitType* BaseRecognizer<ImplTraits, StreamType>::recoverFromMismatchedSet(BitsetListType* follow) { SuperType* super = static_cast<SuperType*>(this); IntStreamType* is = super->get_parser_istream(); const UnitType* matchedSymbol; if (this->mismatchIsMissingToken(is, follow) == true) { // We can fake the missing token and proceed // new ANTLR_Exception<ImplTraits, MISSING_TOKEN_EXCEPTION, StreamType>(this); matchedSymbol = this->getMissingSymbol(is, m_state->get_exception(), follow); m_state->get_exception()->set_token(matchedSymbol); // Print out the error after we insert so that ANTLRWorks sees the // token in the exception. // this->reportError(); m_state->set_error(false); // Exception is not outstanding any more return matchedSymbol; } // TODO - Single token deletion like in recoverFromMismatchedToken() // m_state->set_error(true); m_state->set_failed(true); return NULL; } template< class ImplTraits, class StreamType > bool BaseRecognizer<ImplTraits, StreamType>::recoverFromMismatchedElement(BitsetListType* followBits) { SuperType* super = static_cast<SuperType*>(this); IntStreamType* is = super->get_parser_istream(); BitsetType* follow = followBits->load(); BitsetType* viableToksFollowingRule; if (follow == NULL) { /* The follow set is NULL, which means we don't know what can come * next, so we "hit and hope" by just signifying that we cannot * recover, which will just cause the next token to be consumed, * which might dig us out. */ return false; } /* We have a bitmap for the follow set, hence we can compute * what can follow this grammar element reference. */ if (follow->isMember( ImplTraits::CommonTokenType::EOR_TOKEN_TYPE) == true) { /* First we need to know which of the available tokens are viable * to follow this reference. */ viableToksFollowingRule = this->computeCSRuleFollow(); /* Remove the EOR token, which we do not wish to compute with */ follow->remove( ImplTraits::CommonTokenType::EOR_TOKEN_TYPE); delete viableToksFollowingRule; /* We now have the computed set of what can follow the current token */ } /* We can now see if the current token works with the set of tokens * that could follow the current grammar reference. If it looks like it * is consistent, then we can "insert" that token by not throwing * an exception and assuming that we saw it. */ if ( follow->isMember(is->_LA(1)) == true) { /* report the error, but don't cause any rules to abort and stuff */ this->reportError(); if (follow != NULL) { delete follow; } m_state->set_error(false); m_state->set_failed(false); return true; /* Success in recovery */ } if (follow != NULL) { delete follow; } /* We could not find anything viable to do, so this is going to * cause an exception. */ return false; } template< class ImplTraits, class StreamType > void BaseRecognizer<ImplTraits, StreamType>::consumeUntil(ANTLR_UINT32 tokenType) { SuperType* super = static_cast<SuperType*>(this); IntStreamType* is = super->get_parser_istream(); // What do have at the moment? // ANTLR_UINT32 ttype = is->_LA(1); // Start eating tokens until we get to the one we want. // while (ttype != ImplTraits::CommonTokenType::TOKEN_EOF && ttype != tokenType) { is->consume(); ttype = is->_LA(1); } } template< class ImplTraits, class StreamType > void BaseRecognizer<ImplTraits, StreamType>::consumeUntilSet(BitsetType* set) { ANTLR_UINT32 ttype; SuperType* super = static_cast<SuperType*>(this); IntStreamType* is = super->get_parser_istream(); // What do have at the moment? // ttype = is->_LA(1); // Start eating tokens until we get to one we want. // while (ttype != ImplTraits::CommonTokenType::TOKEN_EOF && set->isMember(ttype) == false) { is->consume(); ttype = is->_LA(1); } } template< class ImplTraits, class StreamType > ANTLR_MARKER BaseRecognizer<ImplTraits, StreamType>::getRuleMemoization( ANTLR_INTKEY ruleIndex, ANTLR_MARKER ruleParseStart) { /* The rule memos are an ANTLR3_LIST of ANTLR3_LIST. */ typedef IntTrie<ImplTraits, ANTLR_MARKER> RuleListType; typedef TrieEntry<ImplTraits, RuleListType*> EntryType; typedef TrieEntry<ImplTraits, ANTLR_MARKER> SubEntryType; ANTLR_MARKER stopIndex; EntryType* entry; /* See if we have a list in the ruleMemos for this rule, and if not, then create one * as we will need it eventually if we are being asked for the memo here. */ entry = m_state->get_ruleMemo()->get(ruleIndex); if (entry == NULL) { /* Did not find it, so create a new one for it, with a bit depth based on the * size of the input stream. We need the bit depth to incorporate the number if * bits required to represent the largest possible stop index in the input, which is the * last character. An int stream is free to return the largest 64 bit offset if it has * no idea of the size, but you should remember that this will cause the leftmost * bit match algorithm to run to 63 bits, which will be the whole time spent in the trie ;-) */ m_state->get_ruleMemo()->add( ruleIndex, new RuleListType(63) ); /* We cannot have a stopIndex in a trie we have just created of course */ return MEMO_RULE_UNKNOWN; } RuleListType* ruleList = entry->get_data(); /* See if there is a stop index associated with the supplied start index. */ stopIndex = 0; SubEntryType* sub_entry = ruleList->get(ruleParseStart); if (sub_entry != NULL) { stopIndex = sub_entry->get_data(); } if (stopIndex == 0) { return MEMO_RULE_UNKNOWN; } return stopIndex; } template< class ImplTraits, class StreamType > bool BaseRecognizer<ImplTraits, StreamType>::alreadyParsedRule(ANTLR_MARKER ruleIndex) { SuperType* super = static_cast<SuperType*>(this); IntStreamType* is = super->get_istream(); /* See if we have a memo marker for this. */ ANTLR_MARKER stopIndex = this->getRuleMemoization( ruleIndex, is->index() ); if (stopIndex == MEMO_RULE_UNKNOWN) { return false; } if (stopIndex == MEMO_RULE_FAILED) { m_state->set_failed(true); } else { is->seek(stopIndex+1); } /* If here then the rule was executed for this input already */ return true; } template< class ImplTraits, class StreamType > void BaseRecognizer<ImplTraits, StreamType>::memoize(ANTLR_MARKER ruleIndex, ANTLR_MARKER ruleParseStart) { /* The rule memos are an ANTLR3_LIST of ANTLR3_LIST. */ typedef IntTrie<ImplTraits, ANTLR_MARKER> RuleListType; typedef TrieEntry<ImplTraits, RuleListType*> EntryType; EntryType* entry; ANTLR_MARKER stopIndex; SuperType* super = static_cast<SuperType*>(this); IntStreamType* is = super->get_istream(); stopIndex = (m_state->get_failed() == true) ? MEMO_RULE_FAILED : is->index() - 1; entry = m_state->get_ruleMemo()->get(ruleIndex); if (entry != NULL) { RuleListType* ruleList = entry->get_data(); /* If we don't already have this entry, append it. The memoize trie does not * accept duplicates so it won't add it if already there and we just ignore the * return code as we don't care if it is there already. */ ruleList->add(ruleParseStart, stopIndex); } } template< class ImplTraits, class StreamType > const typename BaseRecognizer<ImplTraits, StreamType>::UnitType* BaseRecognizer<ImplTraits, StreamType>::getCurrentInputSymbol( IntStreamType* istream ) { return this->getCurrentInputSymbol( istream, ClassForwarder<SuperType>() ); } template< class ImplTraits, class StreamType > const typename BaseRecognizer<ImplTraits, StreamType>::UnitType* BaseRecognizer<ImplTraits, StreamType>::getCurrentInputSymbol(IntStreamType* istream, ClassForwarder<LexerType>) { return NULL; } template< class ImplTraits, class StreamType > const typename BaseRecognizer<ImplTraits, StreamType>::UnitType* BaseRecognizer<ImplTraits, StreamType>::getCurrentInputSymbol(IntStreamType* istream, ClassForwarder<ParserType>) { typedef typename ImplTraits::TokenStreamType TokenStreamType; TokenStreamType* token_stream = static_cast<TokenStreamType*>(istream); return token_stream->_LT(1); } template< class ImplTraits, class StreamType > const typename BaseRecognizer<ImplTraits, StreamType>::UnitType* BaseRecognizer<ImplTraits, StreamType>::getCurrentInputSymbol(IntStreamType* istream, ClassForwarder<TreeParserType>) { typedef typename ImplTraits::TreeNodeStreamType TreeNodeStreamType; TreeNodeStreamType* ctns = static_cast<TreeNodeStreamType*>(istream); return ctns->_LT(1); } template< class ImplTraits, class StreamType > typename BaseRecognizer<ImplTraits, StreamType>::UnitType* BaseRecognizer<ImplTraits, StreamType>::getMissingSymbol( IntStreamType* istream, ExceptionBaseType* e, ANTLR_UINT32 expectedTokenType, BitsetListType* follow) { return this->get_super()->getMissingSymbol( istream, e, expectedTokenType, follow ); } template< class ImplTraits, class StreamType > template<typename Predicate> bool BaseRecognizer<ImplTraits, StreamType>::synpred(ClassForwarder<Predicate> pred) { ANTLR_MARKER start; SuperType* super = static_cast<SuperType*>(this); IntStreamType* is = super->get_istream(); /* Begin backtracking so we can get back to where we started after trying out * the syntactic predicate. */ start = is->mark(); m_state->inc_backtracking(); /* Try the syntactical predicate */ this->get_super()->synpred( pred ); /* Reset */ is->rewind(start); m_state->dec_backtracking(); if ( m_state->get_failed() == true) { /* Predicate failed */ m_state->set_failed(false); return false; } else { /* Predicate was successful */ m_state->set_failed(false); return true; } } template< class ImplTraits, class StreamType > void BaseRecognizer<ImplTraits, StreamType>::exConstruct() { this->get_super()->exConstruct(); } template< class ImplTraits, class StreamType > void BaseRecognizer<ImplTraits, StreamType>::reset() { this->reset( ClassForwarder<SuperType>() ); } template< class ImplTraits, class StreamType > template< typename CompType > void BaseRecognizer<ImplTraits, StreamType>::reset( ClassForwarder<CompType> ) { typedef typename RecognizerSharedStateType::RuleMemoType RuleMemoType; m_state->get_following().clear(); // Reset the state flags // m_state->set_errorRecovery(false); m_state->set_lastErrorIndex(-1); m_state->set_failed(false); m_state->set_errorCount(0); m_state->set_backtracking(0); if (m_state->get_ruleMemo() != NULL) { delete m_state->get_ruleMemo(); m_state->set_ruleMemo( new RuleMemoType(15) ); /* 16 bit depth is enough for 32768 rules! */ } } template< class ImplTraits, class StreamType > void BaseRecognizer<ImplTraits, StreamType>::reset( ClassForwarder<LexerType> ) { m_state->set_token_present( false ); m_state->set_type( ImplTraits::CommonTokenType::TOKEN_INVALID ); m_state->set_channel( TOKEN_DEFAULT_CHANNEL ); m_state->set_tokenStartCharIndex( -1 ); m_state->set_tokenStartCharPositionInLine(-1); m_state->set_tokenStartLine( -1 ); m_state->set_text(""); } template< class ImplTraits, class StreamType > BaseRecognizer<ImplTraits, StreamType>::~BaseRecognizer() { // Did we have a state allocated? // if (m_state != NULL) { // Free any rule memoization we set up // if (m_state->get_ruleMemo() != NULL) { delete m_state->get_ruleMemo(); m_state->set_ruleMemo(NULL); } // Free any exception space we have left around // ExceptionBaseType* thisE = m_state->get_exception(); if (thisE != NULL) { delete thisE; } // Free the shared state memory // delete m_state; } // Free the actual recognizer space // } ANTLR_END_NAMESPACE()
[ "richardw347@gmail.com" ]
richardw347@gmail.com
3bfe58625e0282f6672efe814a5805fba45171b2
0de553bef21d03effa503c03481a8991dc426600
/Engine/UISystem/UIBox.hpp
c3dc69c056362b2fdb2190cf8a13e875f0bc75a8
[]
no_license
clayh7/Thesis
c7ef37cffcf6893bd0719915226f876ce02383e9
731e3587d72edc9ad432cb4a7dcd2ca01e3c0817
refs/heads/master
2020-04-27T10:20:39.716866
2020-03-24T22:16:51
2020-03-24T22:16:51
174,249,345
1
0
null
null
null
null
UTF-8
C++
false
false
1,988
hpp
#pragma once #include "Engine/UISystem/UIWidget.hpp" //------------------------------------------------------------------------------------------------- class Mesh; class MeshRenderer; class Transform; class UIWidgetRegistration; struct XMLNode; //------------------------------------------------------------------------------------------------- class UIBox : public UIWidget { //------------------------------------------------------------------------------------------------- // Static Members //------------------------------------------------------------------------------------------------- private: static UIWidgetRegistration s_UIBoxRegistration; public: static char const * PROPERTY_BORDER_COLOR; static char const * PROPERTY_BORDER_SIZE; static char const * PROPERTY_BACKGROUND_COLOR; //------------------------------------------------------------------------------------------------- // Static Functions //------------------------------------------------------------------------------------------------- public: static UIWidget * CreateWidgetFromXML( XMLNode const & node ); //------------------------------------------------------------------------------------------------- // Members //------------------------------------------------------------------------------------------------- public: Mesh * m_borderMesh; MeshRenderer * m_border; MeshRenderer * m_background; //------------------------------------------------------------------------------------------------- // Functions //------------------------------------------------------------------------------------------------- public: UIBox( std::string const & name = "" ); UIBox( XMLNode const & node ); virtual ~UIBox( ) override; virtual void Update( ) override; virtual void Render( ) const override; protected: void SetupRenderers( ); void UpdateRenderers( ); void CreateBorderMesh( Mesh * out_mesh ); Transform CalcBackgroundTransform( ); void PopulateFromXML( XMLNode const & node ); };
[ "clayh7@gmail.com" ]
clayh7@gmail.com
cadaa13395eeb87eeba6cde86fa416c05db3824f
45b63a923c15751e0abcdbdae67bfec1fa5d9937
/master/src/io/SessionHandler.cpp
9bad0e5909046b56a6b9617f8740b5cd8e674de0
[]
no_license
kzerbe/eos_daemon
e8e653aa22ee7f8d897b56baf92707525e88ea3f
dc8cceb6c1300869eab66976dbf7d39c3a95a319
refs/heads/master
2021-01-10T08:00:33.464874
2015-06-10T12:53:01
2015-06-10T12:53:01
36,790,493
0
0
null
null
null
null
UTF-8
C++
false
false
5,289
cpp
#include <assert.h> #include <unistd.h> #include <sys/socket.h> #include <errno.h> #include <cstring> #include "io/SessionHandler.h" SessionHandler::SessionHandler(size_t bufferSize) : m_bufferSize(bufferSize) , m_fd() , m_tracer("SessionHandler") { m_readBuffer = nullptr; m_writeBuffer = nullptr; m_bytesRead = 0; m_bytesToWrite = 0; m_fd = 0; m_nextMessageLength = 0; } SessionHandler::~SessionHandler() { WatchStream(m_fd, false); } void SessionHandler::WatchStream(int socketDescriptor, bool doWatch) { assert((m_fd != 0 && m_fd != socketDescriptor) == false); // only one stream for a socket if (doWatch) { m_tracer.trace0("watching socket %d", socketDescriptor); m_fd = socketDescriptor; watch_readable(m_fd, true); m_readBuffer = new char[m_bufferSize]; m_writeBuffer = new char[m_bufferSize]; m_bytesRead = 0; m_bytesToWrite = 0; OnConnect(); } else if (m_fd != 0) { m_tracer.trace0("cleaning up"); watch_readable(m_fd, false); watch_writable(m_fd, false); delete [] m_readBuffer; delete [] m_writeBuffer; m_readBuffer = nullptr; m_writeBuffer = nullptr; m_fd = 0; m_nextMessageLength = 0; } } void SessionHandler::SetNextMessageLength(size_t length) { assert(length > 0); m_tracer.trace4("message length set to %d bytes.", length); m_nextMessageLength = length; DrainReadBuffer(); } void SessionHandler::SendMessage(const char* buffer, size_t length) { if (m_bytesToWrite == 0) { auto bytesRemaining = SendData(buffer, length); if (bytesRemaining > 0) { length -= bytesRemaining; buffer += bytesRemaining; } else { return; } } assert((m_bytesToWrite + length > m_bufferSize) == false); memmove(m_writeBuffer + m_bytesToWrite, buffer, length); m_bytesToWrite += length; } int SessionHandler::FindNextMessageBreak(const char* buffer, size_t length) { if (m_nextMessageLength > 0) { return m_nextMessageLength <= length ? m_nextMessageLength : -1; } else { return -1; } } void SessionHandler::DrainReadBuffer() { m_tracer.trace8("searching read buffer for new messages"); auto bytesPassedToConsumer = 0; while(true) { auto messageBreak = FindNextMessageBreak(m_readBuffer + bytesPassedToConsumer, m_bytesRead - bytesPassedToConsumer); if (messageBreak == -1) { break; } m_tracer.trace8("message of length %d received.", messageBreak); OnMessage(m_readBuffer + bytesPassedToConsumer, messageBreak); bytesPassedToConsumer += messageBreak; if (m_bytesRead - bytesPassedToConsumer == 0) { break; } } m_bytesRead -= bytesPassedToConsumer; if (m_bytesRead) { m_tracer.trace7("saving %d bytes for next message", m_bytesRead); } memmove(m_readBuffer, m_readBuffer + bytesPassedToConsumer, m_bytesRead); } int SessionHandler::SendData(const char* buffer, size_t length) { auto bytesWritten = write(m_fd, buffer, length); if (bytesWritten == -1) { switch (errno) { case EAGAIN: m_tracer.trace5("EAGAIN when trying %d bytes to socket %d", length, m_fd); watch_writable(m_fd, true); return length; case ECONNRESET: m_tracer.trace0("connection closed while trying to write %d bytes to %d", length, m_fd); OnConnectionClosed(); WatchStream(m_fd, false); return 0; default: m_tracer.trace0("unexpected error code from send(): %d", errno); break; } } else if ((size_t)bytesWritten < length) { watch_writable(m_fd, true); } else { watch_writable(m_fd, false); } return length - bytesWritten; } void SessionHandler::on_readable(int notifyingSocket) { if (notifyingSocket != m_fd) { return; } auto bytesReceived = recv(m_fd, m_readBuffer + m_bytesRead, m_bufferSize - m_bytesRead, 0); if (bytesReceived == -1) { m_tracer.trace0("receive unexpectedly failed"); return; } if (bytesReceived == 0) { m_tracer.trace0("Connection to %d closed", m_fd); OnConnectionClosed(); WatchStream(m_fd, false); return; } m_bytesRead += bytesReceived; DrainReadBuffer(); } void SessionHandler::on_writable(int notifyingSocket) { if (notifyingSocket != m_fd) { return; } if (m_bytesToWrite == 0) { watch_writable(m_fd, false); return; } m_tracer.trace7("Buffer is writable, attempting to send %d bytes", m_bytesToWrite); auto bytesRemaining = SendData(m_writeBuffer, m_bytesToWrite); if(bytesRemaining) { memmove(m_writeBuffer, m_writeBuffer + m_bytesToWrite - bytesRemaining, bytesRemaining); } m_bytesToWrite = bytesRemaining; }
[ "vmadmin@localhost.localdomain" ]
vmadmin@localhost.localdomain
22e04cf210d5c065267fc1a528086be02548b49a
0f449b76892f7f33a1aee0345de5e04399d12f7d
/Practices/WriteReadUTF8File/src/main.cpp
190f995ea323b080287accac87dc81a5f8d972ec
[ "MIT" ]
permissive
kenny-nelson/GomiBako
b0f1a9f9f126d5e3e78bd744d214260849e1cc98
45fbeaa4e7fe6876510535386cc9ebab0941379a
refs/heads/master
2020-06-04T02:23:15.752090
2017-01-27T03:28:01
2017-01-27T03:28:01
30,114,605
0
0
null
null
null
null
UTF-8
C++
false
false
1,591
cpp
#include <iostream> #include <locale> #include <fstream> #include <codecvt> #include <sstream> using namespace std; const std::codecvt_mode kBom = static_cast<std::codecvt_mode>(std::generate_header | std::consume_header); typedef std::codecvt_utf8<wchar_t, 0x10ffff, kBom> WideConvUtf8Bom; std::wostream& WinEndLine(std::wostream& out) { return out.put(L'\r').put(L'\n').flush(); } int main(int argc, const char * argv[]) { const wchar_t* writeBuffer = L"ABCあいうえお亞伊羽絵尾abc"; // UTF8でファイル出力 { std::wfstream file; WideConvUtf8Bom cvt(1); std::locale loc(file.getloc(), &cvt); auto oldLocale = file.imbue(loc); file.open("utf8bom.txt", std::ios::out | std::ios::binary); file << writeBuffer << WinEndLine; file.close(); file.imbue(oldLocale); } // UTF8でファイル入力 { std::wifstream file; WideConvUtf8Bom cvt(1); std::locale loc(file.getloc(), &cvt); auto oldLocale = file.imbue(loc); file.open("utf8bom.txt", std::ios::in | std::ios::binary); std::wstringstream wss; wss << file.rdbuf(); std::wstring ws = wss.str(); std::wstring removeStr = L"\r"; auto pos(ws.find(removeStr)); while (pos != std::wstring::npos) { ws.replace(pos, removeStr.length(), L"");// CR 部分の除去 pos = ws.find(removeStr, pos); } file.close(); file.imbue(oldLocale); } return 0; }
[ "taro.yamada.was.born.in.63.bce@gmail.com" ]
taro.yamada.was.born.in.63.bce@gmail.com
138cde0166f6479ac5c0cc893b4afd0c208b07d4
d7c94f4a713aaf0fbb3dbb9b56c9f6945e0479c1
/URI Online Judge/uri1430.cpp
152708bfa1e6f6b4bdd02c0c901a21d3078cd2cd
[]
no_license
fonte-nele/Competitive-Programming
2dabb4aab6ce2e6dc552885464fefdd485f9218c
faf0c6077ae0115f121968f7b70f4d68f9ce922b
refs/heads/master
2021-06-28T09:24:07.708562
2020-12-27T14:45:15
2020-12-27T14:45:15
193,268,717
3
0
null
null
null
null
UTF-8
C++
false
false
1,684
cpp
#include <bits/stdc++.h> using namespace std; #define f(inicio, fim) for(int i = inicio; i < fim; i++) #define fr(inicio, fim) for(int j = inicio; j < fim; j++) #define all(x) x.begin (), x.end () #define sz(x) (int) x.size () #define pb push_back #define mk make_pair #define fi first #define se second #define eps 1e-9 #define mem(x, val) memset ((x), (val), sizeof (x)) #define LSONE(s) ((s)&(-s)) typedef long long int ll; typedef unsigned long long int ull; typedef string st; typedef vector <string> vs; typedef pair <int, int> ii; typedef pair <int, pair <int, int> > iii; typedef vector <int> vi; typedef vector <ii> vii; typedef map <int, int> mii; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); st hit; int cont; double soma, valor; while(cin >> hit && hit != "*") { soma = 0; cont = 0; int tam = (int)hit.size(); f(1, tam) { if(hit[i] == '/') { //cout << soma << endl; if(soma == 1.0) cont++; soma = 0; continue; } if(hit[i] == 'W') valor = 1.0; else if(hit[i] == 'H') valor = 0.5; else if(hit[i] == 'Q') valor = 0.25; else if(hit[i] == 'X') valor = 0.015625; else if(hit[i] == 'T') valor = 0.03125; else if(hit[i] == 'E') valor = 0.125; else if(hit[i] == 'S') valor = 0.0625; soma += valor; } cout << cont << endl; } return 0; }
[ "felipephontinelly@hotmail.com" ]
felipephontinelly@hotmail.com
b1f780aacbf791d140d9eb3875efbc7485477cc8
ddcd87d11fc6ed46f2989548fa66606ef8405862
/sensor.h
5d1bff47376ce10a04e0154e765c387ac1419490
[]
no_license
togglebit/Arduino-Sensor-Library
ed7da271e1020ea0afe78f3205f2429d0d81e15a
df5674031880037a48b9d3cbcd7981a7d62a0327
refs/heads/master
2021-01-10T02:43:04.582583
2015-11-19T03:12:43
2015-11-19T03:12:43
45,045,371
0
1
null
null
null
null
UTF-8
C++
false
false
4,576
h
#ifndef SENSOR_H #define SENSOR_H #include "FIFOMath.h" #include "acquisition.h" //defines length of string array #define STR_LNGTH 10 /** * rename for public access via sketch with something user friendly */ #define scanSensors() cAcquire::runAcquisition () /** * again rename for user friendly access, get last known scan time, and max scan time */ #define scanTime() cAcquire::getTimeSlice(false) #define scanTimeMax() cAcquire::getTimeSlice(true) #define scanTimeReset() cAcquire::resetTimeSlice() /** * pindef enum, to be used for setting IO mode of the pin and reading from analogs. * currently this is specific to for MAPLE v5 hardware */ enum ADC_PINS { PIN_0 = 0, PIN_1 = 1, PIN_2 = 2, PIN_3 = 3, PIN_5 = 5, PIN_6 = 6, PIN_7 = 7, PIN_8 = 8, PIN_9 = 9, PIN_11 = 11, PIN_12 = 12, PIN_14 = 14, PIN_15 = 15, PIN_16 = 16, PIN_17 = 17, PIN_18 = 18, PIN_19 = 19, PIN_20 = 20, PIN_27 = 27, PIN_28 = 28 }; /** * Sensor structure that is used to create a "new" sensor. All attributes of the sensor are defined here. * Name, slope, offset, pin number etc. The intention is for the user to statically define these * in the sketch and then create a sensor class, passing a reference to "NEW_SENSOR" into the class. * * @author DJK * @version 0.1 */ struct NEW_SENSOR { /** * string representing sensor name */ char name[10]; /** * string defining units */ char units[10]; /** * physical input pin on maple */ ADC_PINS pin; /** * The sensor class assumes a linear relationship between counts and units. This is the slope. */ float slope; /** * The sensor class assumes a linear relationship between counts and units. This is the offset. */ float offset; /** * Each sensor acquisition(sample) is put into a FIFO buffer giving way to computations that can be performed (sum, avg, derivative, integral). * This determines the depth of the buffer for averaging, setting the max depth for other computaitons. */ UINT8 sample_depth; /** * Depth of the derivative calculation (in # of samples) */ UINT8 deriv_depth; /** * Depth of the integral calculation (in # of samples) */ UINT8 integ_depth; /** * rate at which the sensor will be sampled by the acquisition scheduler. * (also determines time component for average, derivative and integral calculations) */ ACQ_RATE rate; }; /** * Sensor class, resposnible for transforming an "ADC count" into meaningful sensor data. Provides transform of counts to a floating point * number along with string names and units string for the sensor (engineering units). Derived from the FIFOMath class, allows for computations (avg, sum, derivative, integration) * on sensors based upon the last "N" (depth) samples of the input. This class is also derived from cAcquire which is a static base class that * can be used to schedule peroidic readings for all sensor objects (as defined by "rate" enum). A NEW_SENSOR struct reference is passed into the constructor for initialization and scheduling. * * @see cFifoMath * @see cAcquire */ class cSensor : cFIFOMath, cAcquire { private: void calcLine(); float normalize(UINT64 data); float normalize(UINT16 data); float normalize(SINT32 data); public: cSensor(NEW_SENSOR *S); void setX1Y1(UINT16 X1value, float Y1value); void setX2Y2(UINT16 X2value, float Y2value); void readSensor(void); float getReading(bool filtered); float getDerivative(); float getIntegral(); float getSum(); float getMax(); float getMin(); ACQ_RATE getRate(void); protected: /** * Y coordinates used for mapping coordinates for y = mx + b transform. Y is specified in floating eng units */ float y1,y2; /** * X coordinates used for mapping coordinates for y = mx + b transform. X is specified in ADC counts */ UINT16 x1,x2; /** * slope and offset components used for linerization to engineering units */ float m,b; /** * ADC sensor data raw data in counts, last known reading */ UINT16 counts; /** * floating point sensor data, last known conversion from ADC counts (last sample/avg, dt, it) */ float normalData, normalDataDt, normalDataIt; /** * sensor units name (ASCII string) */ char units[STR_LNGTH] ; /** * sensor name (ASCII string) */ char name[STR_LNGTH]; /** * ADC pin used that the sensor is connected to */ ADC_PINS pinNum; /** * Periodic update rate for sensor */ ACQ_RATE rate; }; #endif
[ "dan@togglebit.net" ]
dan@togglebit.net
e42a25db230c947c4d0ae69de29fe2fa69909d73
9b2d8581233ac54b511045c3ef3172fdabb52ca0
/retire_my.cpp
3fc746153d3dfef4b5c19abed9be20349130896b
[]
no_license
eunjiWon/algorithm_study
17e46f92052eaf5eeba44599c5e1945ca049ab25
f779b537827a76d37aed2e69d09e25b6d5e8ecaa
refs/heads/master
2021-01-25T14:10:00.507306
2018-09-08T10:21:28
2018-09-08T10:21:28
123,658,053
0
0
null
null
null
null
UTF-8
C++
false
false
1,314
cpp
// 오늘부터 N+1 일 째 되는 날 퇴사를 하기 위해서, 남은 N일 동안 최대한 많은 상담을 하려고 한다. // 각각의 상담은 상담을 완료하는데 걸리는 기간 T와 상담을 했을 때 받을 수 있는 금액 P로 아루어져있다. 하루에 한사람씩 상담 // 첫째 줄에 N이 주어진다. // 둘째 줄 부터 N개의 줄에 T와 P가 주어진다. 1일부터 N일까지 순서대로 주어진다. // 얻을 수 있는 최대 이익을 출력한다. #include <iostream> #include <vector> #include <algorithm> using namespace std; vector< pair<int, int> > v; int N, MAX = 0; int t, p; int temp = 0; void dfs(int nextDay, int sum){ if(nextDay == N + 1){ MAX = max(MAX, sum); //cout << MAX << endl; return; } if(nextDay + v[nextDay].first <= N + 1){ dfs(nextDay + v[nextDay].first, sum + v[nextDay + v[nextDay].first].second); } if(nextDay + 1 <= N + 1){ dfs(nextDay + 1, sum - v[nextDay].second + v[nextDay + 1].second); } } int main(){ cin >> N; v.push_back(make_pair(0, 0)); for(int i = 0; i < N; i++){ cin >> t >> p; v.push_back(make_pair(t, p)); } for(int i = 1; i <= N; i++){ dfs(i, v[i].second); } cout << MAX << endl; return 0; }
[ "eunjiwon@eunjiui-MacBook-Pro.local" ]
eunjiwon@eunjiui-MacBook-Pro.local
db603419d6a15412d35b702281ae50c86aa8b40b
9d70c35bd24bf128951cbcfd80f8f4a812ab9656
/CLASSES/Contact1.cpp
096d11800957591a87cc9d7af21d13e970e6187a
[]
no_license
dev-area/C-CPP
81cdfa250bace00c83b14943fd7bf59d427c0cd4
53171edf07c990e436581168df478f9564224ed5
refs/heads/master
2021-01-23T06:10:57.869147
2020-01-26T08:42:11
2020-01-26T08:42:11
86,343,262
1
1
null
null
null
null
UTF-8
C++
false
false
1,992
cpp
// contact1.cpp // // implementation of contact class methods // #include "contact1.h" void Contact::getContactDetails() { // // Class function to read and the attributes of the class // char buffer[255]; // // Prompt for, and read data for class. No validation! cout << "\nEnter the contact's name (max " << NAMELEN << " characters) :\n"; cin.get(buffer, NAMELEN); cin.ignore(255, '\n'); setName(buffer); cout << "Enter the first line of the contact's address (max " << ADDRLEN << " characters) :\n"; cin.get(buffer, ADDRLEN); cin.ignore(255, '\n'); setAddress1(buffer); cout << "Enter the second line of the contact's address (max " << ADDRLEN << " characters) :\n"; cin.get(buffer,ADDRLEN); cin.ignore(255, '\n'); setAddress2(buffer); cout << "Enter the third line of the contact's address (max " << ADDRLEN << " characters) :\n"; cin.get(buffer, ADDRLEN); cin.ignore(255, '\n'); setAddress3(buffer); cout << "Enter the district of the contact's address (max " << ADDRLEN << " characters) :\n"; cin.get(buffer, ADDRLEN); cin.ignore(255, '\n'); setDistrict(buffer); cout << "Enter the contact's telephone number (max " << PHONELEN << " characters) :\n"; cin.get(buffer, PHONELEN); cin.ignore(255, '\n'); setPhone(buffer); cout << "Enter the contact's fax number (max " << PHONELEN << " characters) :\n"; cin.get(buffer, PHONELEN); cin.ignore(255, '\n'); setFax(buffer); cout << "\n\n"; } void Contact::displayContactDetails() { // // class function to read the values of the attributes and // display the values. Does not ignore null length strings // cout << "\n" << getName(); cout << "\n" << getAddress1(); cout << "\n" << getAddress2(); cout << "\n" << getAddress3(); cout << "\n" << getDistrict(); cout << "\n\nTelephone : " << getPhone(); cout << "\nFax : " << getFax(); cout << "\n\n"; }
[ "liranbh@gmail.com" ]
liranbh@gmail.com
79ef47bc0cc3a30d08687ce728bbcf1bfceab6ec
f977bd24b33f924ed5adea1288f932861d42cd4f
/ic/ic/mmio.cpp
bdaebe35b88c574ae3adeb3ba39c749f8df72689
[]
no_license
poise30/OS_homework_2
a17ba9acd07e8f67e5eb9e8fde42b43be7476489
3fa60fcdd9d23468b13c8de95c0f91b9d0bd62b5
refs/heads/master
2020-05-16T00:31:20.668634
2015-07-20T16:08:27
2015-07-20T16:08:27
39,393,517
0
0
null
null
null
null
UHC
C++
false
false
16,458
cpp
/**---------------------------------------------------------------------------- * *----------------------------------------------------------------------------- * All rights reserved by Noh,Yonghwan (fixbrain@gmail.com, unsorted@msn.com) *----------------------------------------------------------------------------- * **---------------------------------------------------------------------------*/ // read // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366542(v=vs.85).aspx #include "stdafx.h" //#include <Windows.h> //윈도우 관련 함수, Get~ , .pch(precomplied header) //#include <stdint.h> //uint32_t /** * @brief * @param * @see * @remarks * @code * @endcode * @return **/ //err, 문자열, 가변인수 void print(_In_ const char* fmt, _In_ ...) { //_ln_ 읽기전용? char log_buffer[2048]; va_list args; //가변인수 va_start(args, fmt); //args 를 fmt 형태로 읽어들임 HRESULT hRes = StringCbVPrintfA(log_buffer, sizeof(log_buffer), fmt, args); if (S_OK != hRes) //S_OK 함수가 성공하였음을 의미 { //오류 출력 fprintf( stderr, "%s, StringCbVPrintfA() failed. res = 0x%08x", __FUNCTION__, hRes ); return; } OutputDebugStringA(log_buffer); //디버깅할때 사용 fprintf(stdout, "%s \n", log_buffer); } bool is_file_existsW(_In_ const wchar_t* file_path) { _ASSERTE(NULL != file_path); _ASSERTE(TRUE != IsBadStringPtrW(file_path, MAX_PATH)); if ((NULL == file_path) || (TRUE == IsBadStringPtrW(file_path, MAX_PATH))) return false; WIN32_FILE_ATTRIBUTE_DATA info = { 0 }; if (GetFileAttributesExW(file_path, GetFileExInfoStandard, &info) == 0) return false; else return true; } bool read_file_using_memory_map() { // current directory 를 구한다. wchar_t *buf = NULL; uint32_t buflen = 0; buflen = GetCurrentDirectoryW(buflen, buf); if (0 == buflen) { print("err ] GetCurrentDirectoryW() failed. gle = 0x%08x", GetLastError()); return false; } buf = (PWSTR)malloc(sizeof(WCHAR) * buflen); if (0 == GetCurrentDirectoryW(buflen, buf)) { print("err ] GetCurrentDirectoryW() failed. gle = 0x%08x", GetLastError()); free(buf); return false; } // current dir \\ test.txt 파일명 생성 wchar_t file_name[260]; if (!SUCCEEDED(StringCbPrintfW( file_name, sizeof(file_name), L"%ws\\test.txt", buf))) { print("err ] can not create file name"); free(buf); return false; } free(buf); buf = NULL; if (true != is_file_existsW(file_name)) { print("err ] no file exists. file = %ws", file_name); return false; } HANDLE file_handle = CreateFileW( (LPCWSTR)file_name, GENERIC_READ, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if (INVALID_HANDLE_VALUE == file_handle) { print("err ] CreateFile(%ws) failed, gle = %u", file_name, GetLastError()); return false; } // check file size // LARGE_INTEGER fileSize; if (TRUE != GetFileSizeEx(file_handle, &fileSize)) { print("err ] GetFileSizeEx(%ws) failed, gle = %u", file_name, GetLastError()); CloseHandle(file_handle); return false; } // [ WARN ] // // 4Gb 이상의 파일의 경우 MapViewOfFile()에서 오류가 나거나 // 파일 포인터 이동이 문제가 됨 // FilIoHelperClass 모듈을 이용해야 함 // /**/ _ASSERTE(fileSize.HighPart == 0); if (fileSize.HighPart > 0) { print("file size = %I64d (over 4GB) can not handle. use FileIoHelperClass", fileSize.QuadPart); CloseHandle(file_handle); return false; } DWORD file_size = (DWORD)fileSize.QuadPart; HANDLE file_map = CreateFileMapping( file_handle, NULL, PAGE_READONLY, 0, 0, NULL ); if (NULL == file_map) { print("err ] CreateFileMapping(%ws) failed, gle = %u", file_name, GetLastError()); CloseHandle(file_handle); return false; } PCHAR file_view = (PCHAR)MapViewOfFile( file_map, FILE_MAP_READ, 0, 0, 0 ); if (file_view == NULL) { print("err ] MapViewOfFile(%ws) failed, gle = %u", file_name, GetLastError()); CloseHandle(file_map); CloseHandle(file_handle); return false; } // do some io char a = file_view[0]; // 0x d9 char b = file_view[1]; // 0xb3 // close all UnmapViewOfFile(file_view); CloseHandle(file_map); CloseHandle(file_handle); return true; } /** * @brief * @param * @see * @remarks * @code * @endcode * @return **/ bool create_very_big_file(_In_ const wchar_t* file_path, _In_ uint32_t size_in_mb) { _ASSERTE(NULL != file_path); if (NULL == file_path) return false; if (is_file_existsW(file_path)) { ::DeleteFileW(file_path); } // create very big file HANDLE file_handle = CreateFile( file_path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL ); if (INVALID_HANDLE_VALUE == file_handle) { print("err ] CreateFile( %ws ) failed. gle = %u", file_path, GetLastError()); return false; } LARGE_INTEGER file_size = { 0 }; LARGE_INTEGER ret; //file_size.LowPart = 0; //file_size.HighPart = 1; file_size.QuadPart = (LONGLONG)(1024 * 1024) * (LONGLONG)size_in_mb; if (!SetFilePointerEx(file_handle, file_size, NULL, FILE_BEGIN)) { print("err ] SetFilePointerEx() failed. gle = %u", GetLastError()); CloseHandle(file_handle); return false; } SetEndOfFile(file_handle); CloseHandle(file_handle); return true; } /** * @brief * @param * @see * @remarks * @code * @endcode * @return **/ typedef struct map_context { HANDLE handle; LARGE_INTEGER size; HANDLE map; PCHAR view; }*pmap_context; /* pmap_context open_map_context(_In_ const wchar_t* file_path) { _ASSERTE(NULL != file_path); if (NULL == file_path) return false; if (!is_file_existsW(file_path)) return false;; pmap_context ctx = (pmap_context)malloc(sizeof(map_context)); RtlZeroMemory(ctx, sizeof(map_context)); bool ret = false; #pragma warning(disable: 4127) //4127 경고 disable do { ctx->handle = CreateFileW( (LPCWSTR)file_path, GENERIC_READ, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if (INVALID_HANDLE_VALUE == ctx->handle) { print("err ] CreateFile( %ws ) failed. gle = %u", file_path, GetLastError()); break; } // check file size // LARGE_INTEGER fileSize; if (TRUE != GetFileSizeEx(ctx->handle, &fileSize)) //파일크기 filesize에 저장 { print("err ] GetFileSizeEx( %ws ) failed. gle = %u", file_path, GetLastError()); break; } // [ WARN ] // // 4Gb 이상의 파일의 경우 MapViewOfFile()에서 오류가 나거나 // 파일 포인터 이동이 문제가 됨 // FilIoHelperClass 모듈을 이용해야 함 // _ASSERTE(fileSize.HighPart == 0); if (fileSize.HighPart > 0) { print("err ] file is too large to map. file = %ws, size = %llu", file_path, fileSize.QuadPart); break; } ctx->size = (DWORD)fileSize.QuadPart; ctx->map = CreateFileMapping( ctx->handle, NULL, PAGE_READONLY, 0, 0, NULL ); if (NULL == ctx->map) { print("err ] CreateFileMapping( %ws ) failed. gle = %u", file_path, GetLastError()); break; } // // MapViewOfFile() 함수의 dwFileOffsetLow 파라미터는 // SYSTEM_INFO::dwAllocationGranularity 값의 배수이어야 한다. // LARGE_INTEGER Offset = { 0 }; Offset.LowPart = 0; DWORD Size = ctx->size; static DWORD AllocationGranularity = 0; if (0 == AllocationGranularity) { SYSTEM_INFO si = { 0 }; GetSystemInfo(&si); AllocationGranularity = si.dwAllocationGranularity; } DWORD AdjustMask = AllocationGranularity - 1; LARGE_INTEGER AdjustOffset = { 0 }; AdjustOffset.HighPart = Offset.HighPart; // AllocationGranularity 이하의 값을 버림 // AdjustOffset.LowPart = (Offset.LowPart & ~AdjustMask); // 버려진 값만큼 매핑할 사이즈를 증가 // DWORD BytesToMap = ((Offset.LowPart & AdjustMask) + Size)/4; ctx->size = ((Offset.LowPart & AdjustMask) + Size)/4; ctx->view = (PCHAR)MapViewOfFile( ctx->map, FILE_MAP_READ, AdjustOffset.HighPart, AdjustOffset.LowPart, BytesToMap ); if (ctx->view == NULL) { print("err ] MapViewOfFile( %ws ) failed. gle = %u", file_path, GetLastError()); break; } ret = true; } while (FALSE); #pragma warning(default: 4127) if (!ret) { if (NULL != ctx->view) UnmapViewOfFile(ctx->view); if (NULL != ctx->map) CloseHandle(ctx->map); if (INVALID_HANDLE_VALUE != ctx->handle) CloseHandle(ctx->handle); free(ctx); ctx = NULL; } return ctx; } */ /** * @brief * @param * @see * @remarks * @code * @endcode * @return **/ /** * @brief * @param * @see * @remarks * @code * @endcode * @return **/ void close_map_context(_In_ pmap_context ctx) { if (NULL != ctx) { if (NULL != ctx->view) UnmapViewOfFile(ctx->view); if (NULL != ctx->map) CloseHandle(ctx->map); if (INVALID_HANDLE_VALUE != ctx->handle) CloseHandle(ctx->handle); free(ctx); } } bool create_map_context(_In_ const wchar_t* src_path, _In_ const wchar_t* dst_path) { _ASSERTE(NULL != src_path); if (NULL == src_path) return false; if (!is_file_existsW(src_path)) return false;; pmap_context src_ctx = (pmap_context)malloc(sizeof(map_context)); RtlZeroMemory(src_ctx, sizeof(map_context)); _ASSERTE(NULL != dst_path); if (NULL == dst_path) return false; if (is_file_existsW(dst_path)) { DeleteFileW(dst_path); } pmap_context dst_ctx = (pmap_context)malloc(sizeof(map_context)); RtlZeroMemory(dst_ctx, sizeof(map_context)); bool ret = false; #pragma warning(disable: 4127) do { src_ctx->handle = CreateFileW( (LPCWSTR)src_path, GENERIC_READ, NULL, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if (INVALID_HANDLE_VALUE == src_ctx->handle) { print("err ] CreateFile( %ws ) failed. gle = %u", src_path, GetLastError()); break; } // check file size // LARGE_INTEGER fileSize; if (TRUE != GetFileSizeEx(src_ctx->handle, &fileSize)) //파일크기 filesize에 저장 { print("err ] GetFileSizeEx( %ws ) failed. gle = %u", src_path, GetLastError()); break; } // [ WARN ] // // 4Gb 이상의 파일의 경우 MapViewOfFile()에서 오류가 나거나 // 파일 포인터 이동이 문제가 됨 // FilIoHelperClass 모듈을 이용해야 함 // /* _ASSERTE(fileSize.HighPart == 0); if (fileSize.HighPart > 0) { print("err ] file is too large to map. file = %ws, size = %llu", src_path, fileSize.QuadPart); break; } */ src_ctx->size = fileSize; src_ctx->map = CreateFileMapping( src_ctx->handle, NULL, PAGE_READONLY, 0, 0, NULL ); if (NULL == src_ctx->map) { print("err ] CreateFileMapping( %ws ) failed. gle = %u", src_path, GetLastError()); break; } //dst dst_ctx->handle = CreateFileW( (LPCWSTR)dst_path, GENERIC_READ | GENERIC_WRITE, NULL, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL ); if (INVALID_HANDLE_VALUE == dst_ctx->handle) { print("err ] CreateFile( %ws ) failed. gle = %u", dst_path, GetLastError()); break; } dst_ctx->size = fileSize; dst_ctx->map = CreateFileMapping( dst_ctx->handle, NULL, PAGE_READWRITE, dst_ctx->size.HighPart, dst_ctx->size.LowPart, NULL ); if (NULL == dst_ctx->map) { print("err ] CreateFileMapping( %ws ) failed. gle = %u", dst_path, GetLastError()); break; } // MapViewOfFile() 함수의 dwFileOffsetLow 파라미터는 // SYSTEM_INFO::dwAllocationGranularity 값의 배수이어야 한다. // LARGE_INTEGER Offset = { 0 }; Offset.LowPart = 0; LARGE_INTEGER Size = dst_ctx->size; static DWORD AllocationGranularity = 0; if (0 == AllocationGranularity) { SYSTEM_INFO si = { 0 }; GetSystemInfo(&si); AllocationGranularity = si.dwAllocationGranularity; } DWORD AdjustMask = AllocationGranularity - 1; LARGE_INTEGER AdjustOffset = { 0 }; AdjustOffset.HighPart = Offset.HighPart; // AllocationGranularity 이하의 값을 버림 AdjustOffset.LowPart = (Offset.LowPart & ~AdjustMask); LONGLONG BytesToMap = (LONGLONG)((Offset.LowPart & AdjustMask) + (LONGLONG)(Size.QuadPart / 20)); // AllocationGranularity 이하의 값을 버 // 버려진 값만큼 매핑할 사이즈를 증가 while (dst_ctx->size.QuadPart > 0){ // 버려진 값만큼 매핑할 사이즈를 증가 src_ctx->view = (PCHAR)MapViewOfFile( src_ctx->map, FILE_MAP_ALL_ACCESS, AdjustOffset.HighPart, AdjustOffset.LowPart, BytesToMap ); if (src_ctx->view == NULL) { //print("err ] MapViewOfFile( %ws ) failed. gle = %u", src_path, GetLastError()); break; } dst_ctx->view = (PCHAR)MapViewOfFile( dst_ctx->map, FILE_MAP_WRITE | FILE_MAP_READ, AdjustOffset.HighPart, AdjustOffset.LowPart, BytesToMap ); if (dst_ctx->view == NULL) { print("err ] MapViewOfFile( %ws ) failed. gle = %u", dst_path, GetLastError()); break; } // copy src to dst by mmio for (uint32_t i = 0; i < BytesToMap + AdjustOffset.LowPart; ++i) { dst_ctx->view[i] = src_ctx->view[i]; } UnmapViewOfFile(src_ctx->map); UnmapViewOfFile(dst_ctx->map); AdjustOffset.LowPart += BytesToMap; dst_ctx->size.QuadPart -= BytesToMap; } ret = true; } while (FALSE); #pragma warning(default: 4127) if (!ret) { if (NULL != src_ctx->view) UnmapViewOfFile(src_ctx->view); if (NULL != src_ctx->map) CloseHandle(src_ctx->map); if (INVALID_HANDLE_VALUE != src_ctx->handle) CloseHandle(src_ctx->handle); if (NULL != dst_ctx->view) UnmapViewOfFile(dst_ctx->view); if (NULL != dst_ctx->map) CloseHandle(dst_ctx->map); if (INVALID_HANDLE_VALUE != dst_ctx->handle) CloseHandle(dst_ctx->handle); free(src_ctx); src_ctx = NULL; free(dst_ctx); dst_ctx = NULL; close_map_context(src_ctx); close_map_context(dst_ctx); return ret; } close_map_context(src_ctx); close_map_context(dst_ctx); return ret; } /** * @brief * @param * @see * @remarks * @code * @endcode * @return **/ bool file_copy_using_memory_map( _In_ const wchar_t* src_file, _In_ const wchar_t* dst_file ) { _ASSERTE(NULL != src_file); _ASSERTE(NULL != dst_file); if (NULL == src_file || NULL == dst_file) return false; if (!is_file_existsW(src_file)) { print("err ] no src file = %ws", src_file); return false; } if (is_file_existsW(dst_file)) { DeleteFileW(dst_file); } // map src, dst file //pmap_context src_ctx = open_map_context(src_file); bool ctx = create_map_context(src_file, dst_file); if (NULL == ctx) { print("err ] open_map_context() failed."); return false; } return true; } /** * @brief * @param * @see * @remarks * @code * @endcode * @return **/ bool file_copy_using_read_write( _In_ const wchar_t* src_file, _In_ const wchar_t* dst_file ) { _ASSERTE(NULL != src_file); _ASSERTE(NULL != dst_file); if (NULL == src_file || NULL == dst_file) return false; if (!is_file_existsW(src_file)) { print("err ] no src file = %ws", src_file); return false; } if (is_file_existsW(dst_file)) { DeleteFileW(dst_file); } // open src file with READ mode HANDLE src_handle = CreateFileW( src_file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); if (INVALID_HANDLE_VALUE == src_handle) { print("err ] CreateFile( %ws ) failed. gle = %u", src_file, GetLastError()); return false; } // open dst file with WRITE mode HANDLE dst_handle = CreateFileW( dst_file, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL ); if (INVALID_HANDLE_VALUE == dst_handle) { print("err ] CreateFile( %ws ) failed. gle = %u", dst_file, GetLastError()); CloseHandle(src_handle); return false; } // file copy bool ret = false; char buf[4096] = { 0 }; DWORD bytes_written = 0; DWORD bytes_read = 0; do { // read from src if (!ReadFile(src_handle, buf, sizeof(buf), &bytes_read, NULL)) { print("err ] ReadFile( src_handle ) failed. gle = %u", GetLastError()); break; } else { // please read // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365690(v=vs.85).aspx if (0 == bytes_read) { ret = true; break; } } // write to dst if (!WriteFile(dst_handle, buf, sizeof(buf), &bytes_written, NULL)) { print("err ] WriteFile( dst_handle ) failed. gle = %u", GetLastError()); break; } } while (true); CloseHandle(src_handle); CloseHandle(dst_handle); return ret; }
[ "dladhsk@naver.com" ]
dladhsk@naver.com
63c980f5fbd596dd1861744dadc2bced9d4e40eb
2521f019d85941a9732e2bbb1ae18cafff3bbc72
/DeferredRendering/DeferredRendering/Timer.cpp
4db555cd2c5b49f396fb2dc84a4d1bf50685d361
[]
no_license
vanish87/is-deferred-rendering-vs2012
03418e43cb1620d46f204abbe4cd033fb2ad7fc2
6122759bfa71ecdcd816222e80c3dfc1ceae4fd4
refs/heads/master
2020-05-28T03:25:18.717194
2017-01-29T06:57:57
2017-01-29T06:57:57
32,836,346
1
0
null
null
null
null
UTF-8
C++
false
false
628
cpp
#include "Timer.h" namespace MocapGE { Timer::Timer(void) { } Timer::~Timer(void) { } void Timer::Retart() { PC_freq_ = 0.0; counter_start_ = 0; LARGE_INTEGER freq; if(!QueryPerformanceFrequency(&freq)) PRINT("QueryPerformanceFrequency failed!"); PC_freq_ = double(freq.QuadPart)/1000.0; //in second //PC_freq_ = double(freq.QuadPart); QueryPerformanceCounter(&freq); counter_start_ = freq.QuadPart; } double Timer::Time() { LARGE_INTEGER counter; QueryPerformanceCounter(&counter); return double(counter.QuadPart-counter_start_)/PC_freq_; } }
[ "vanish8.7@gmail.com@6294a696-770a-505e-ba8e-939081b951f1" ]
vanish8.7@gmail.com@6294a696-770a-505e-ba8e-939081b951f1
85136545b5718b94a955faa580f8c7ccb664f5a8
b20c683654f483ff784373716d302ba4ef1084a3
/src/qt/bitcoingui.cpp
3edc8eede6ab132d9479682d3a6a564ab4808404
[ "MIT" ]
permissive
valuecash/valuecash
cc99356fb12436443914b095060067a6c9d648e0
a9912a6f545dcafd064731e391105e1cc57cd217
refs/heads/master
2021-07-21T04:27:23.669146
2017-10-27T17:04:19
2017-10-27T17:04:19
108,563,186
0
0
null
null
null
null
UTF-8
C++
false
false
30,170
cpp
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <QApplication> #include "bitcoingui.h" #include "transactiontablemodel.h" #include "optionsdialog.h" #include "aboutdialog.h" #include "clientmodel.h" #include "walletmodel.h" #include "walletframe.h" #include "optionsmodel.h" #include "transactiondescdialog.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "notificator.h" #include "guiutil.h" #include "rpcconsole.h" #include "ui_interface.h" #include "wallet.h" #include "init.h" #ifdef Q_OS_MAC #include "macdockiconhandler.h" #endif #include <QMenuBar> #include <QMenu> #include <QIcon> #include <QVBoxLayout> #include <QToolBar> #include <QStatusBar> #include <QLabel> #include <QMessageBox> #include <QProgressBar> #include <QStackedWidget> #include <QDateTime> #include <QMovie> #include <QTimer> #include <QDragEnterEvent> #if QT_VERSION < 0x050000 #include <QUrl> #endif #include <QMimeData> #include <QStyle> #include <QSettings> #include <QDesktopWidget> #include <QListWidget> #include <iostream> const QString BitcoinGUI::DEFAULT_WALLET = "~Default"; BitcoinGUI::BitcoinGUI(QWidget *parent) : QMainWindow(parent), clientModel(0), encryptWalletAction(0), changePassphraseAction(0), aboutQtAction(0), trayIcon(0), notificator(0), rpcConsole(0), prevBlocks(0) { restoreWindowGeometry(); setWindowTitle(tr("Valuecash") + " - " + tr("Wallet")); #ifndef Q_OS_MAC QApplication::setWindowIcon(QIcon(":icons/bitcoin")); setWindowIcon(QIcon(":icons/bitcoin")); #else setUnifiedTitleAndToolBarOnMac(true); QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif // Create wallet frame and make it the central widget walletFrame = new WalletFrame(this); setCentralWidget(walletFrame); // Accept D&D of URIs setAcceptDrops(true); // Create actions for the toolbar, menu bar and tray/dock icon // Needs walletFrame to be initialized createActions(); // Create application menu bar createMenuBar(); // Create the toolbars createToolBars(); // Create system tray icon and notification createTrayIcon(); // Create status bar statusBar(); // Status bar notification icons QFrame *frameBlocks = new QFrame(); frameBlocks->setContentsMargins(0,0,0,0); frameBlocks->setMinimumWidth(56); frameBlocks->setMaximumWidth(56); QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks); frameBlocksLayout->setContentsMargins(3,0,3,0); frameBlocksLayout->setSpacing(3); labelEncryptionIcon = new QLabel(); labelConnectionsIcon = new QLabel(); labelBlocksIcon = new QLabel(); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelEncryptionIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelConnectionsIcon); frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelBlocksIcon); frameBlocksLayout->addStretch(); // Progress bar and label for blocks download progressBarLabel = new QLabel(); progressBarLabel->setVisible(false); progressBar = new QProgressBar(); progressBar->setAlignment(Qt::AlignCenter); progressBar->setVisible(false); // Override style sheet for progress bar for styles that have a segmented progress bar, // as they make the text unreadable (workaround for issue #1071) // See https://qt-project.org/doc/qt-4.8/gallery.html QString curStyle = QApplication::style()->metaObject()->className(); if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle") { progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }"); } statusBar()->addWidget(progressBarLabel); statusBar()->addWidget(progressBar); statusBar()->addPermanentWidget(frameBlocks); syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this); rpcConsole = new RPCConsole(this); connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show())); // prevents an oben debug window from becoming stuck/unusable on client shutdown connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide())); // Install event filter to be able to catch status tip events (QEvent::StatusTip) this->installEventFilter(this); // Initially wallet actions should be disabled setWalletActionsEnabled(false); } BitcoinGUI::~BitcoinGUI() { saveWindowGeometry(); if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu) trayIcon->hide(); #ifdef Q_OS_MAC delete appMenuBar; MacDockIconHandler::instance()->setMainWindow(NULL); #endif } void BitcoinGUI::createActions() { QActionGroup *tabGroup = new QActionGroup(this); overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this); overviewAction->setStatusTip(tr("Show general overview of wallet")); overviewAction->setToolTip(overviewAction->statusTip()); overviewAction->setCheckable(true); overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1)); tabGroup->addAction(overviewAction); sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send"), this); sendCoinsAction->setStatusTip(tr("Send coins to a Valuecash address")); sendCoinsAction->setToolTip(sendCoinsAction->statusTip()); sendCoinsAction->setCheckable(true); sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2)); tabGroup->addAction(sendCoinsAction); receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive"), this); receiveCoinsAction->setStatusTip(tr("Show the list of addresses for receiving payments")); receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip()); receiveCoinsAction->setCheckable(true); receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3)); tabGroup->addAction(receiveCoinsAction); historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this); historyAction->setStatusTip(tr("Browse transaction history")); historyAction->setToolTip(historyAction->statusTip()); historyAction->setCheckable(true); historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4)); tabGroup->addAction(historyAction); addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Addresses"), this); addressBookAction->setStatusTip(tr("Edit the list of stored addresses and labels")); addressBookAction->setToolTip(addressBookAction->statusTip()); addressBookAction->setCheckable(true); addressBookAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5)); tabGroup->addAction(addressBookAction); connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage())); connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage())); connect(addressBookAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage())); quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this); quitAction->setStatusTip(tr("Quit application")); quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q)); quitAction->setMenuRole(QAction::QuitRole); aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About Valuecash"), this); aboutAction->setStatusTip(tr("Show information about Valuecash")); aboutAction->setMenuRole(QAction::AboutRole); aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this); aboutQtAction->setStatusTip(tr("Show information about Qt")); aboutQtAction->setMenuRole(QAction::AboutQtRole); optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this); optionsAction->setStatusTip(tr("Modify configuration options for Valuecash")); optionsAction->setMenuRole(QAction::PreferencesRole); toggleHideAction = new QAction(QIcon(":/icons/bitcoin"), tr("&Show / Hide"), this); toggleHideAction->setStatusTip(tr("Show or hide the main Window")); encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this); encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet")); encryptWalletAction->setCheckable(true); backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this); backupWalletAction->setStatusTip(tr("Backup wallet to another location")); changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this); changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption")); signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this); signMessageAction->setStatusTip(tr("Sign messages with your Valuecash addresses to prove you own them")); verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this); verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified Valuecash addresses")); openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug window"), this); openRPCConsoleAction->setStatusTip(tr("Open debugging and diagnostic console")); connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit())); connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked())); connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt())); connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked())); connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden())); connect(encryptWalletAction, SIGNAL(triggered(bool)), walletFrame, SLOT(encryptWallet(bool))); connect(backupWalletAction, SIGNAL(triggered()), walletFrame, SLOT(backupWallet())); connect(changePassphraseAction, SIGNAL(triggered()), walletFrame, SLOT(changePassphrase())); connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab())); connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab())); } void BitcoinGUI::createMenuBar() { #ifdef Q_OS_MAC // Create a decoupled menu bar on Mac which stays even if the window is closed appMenuBar = new QMenuBar(); #else // Get the main window's menu bar on other platforms appMenuBar = menuBar(); #endif // Configure the menus QMenu *file = appMenuBar->addMenu(tr("&File")); file->addAction(backupWalletAction); file->addAction(signMessageAction); file->addAction(verifyMessageAction); file->addSeparator(); file->addAction(quitAction); QMenu *settings = appMenuBar->addMenu(tr("&Settings")); settings->addAction(encryptWalletAction); settings->addAction(changePassphraseAction); settings->addSeparator(); settings->addAction(optionsAction); QMenu *help = appMenuBar->addMenu(tr("&Help")); help->addAction(openRPCConsoleAction); help->addSeparator(); help->addAction(aboutAction); help->addAction(aboutQtAction); } void BitcoinGUI::createToolBars() { QToolBar *toolbar = addToolBar(tr("Tabs toolbar")); toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); toolbar->addAction(overviewAction); toolbar->addAction(sendCoinsAction); toolbar->addAction(receiveCoinsAction); toolbar->addAction(historyAction); toolbar->addAction(addressBookAction); } void BitcoinGUI::setClientModel(ClientModel *clientModel) { this->clientModel = clientModel; if(clientModel) { // Replace some strings and icons, when using the testnet if(clientModel->isTestNet()) { setWindowTitle(windowTitle() + QString(" ") + tr("[testnet]")); #ifndef Q_OS_MAC QApplication::setWindowIcon(QIcon(":icons/bitcoin_testnet")); setWindowIcon(QIcon(":icons/bitcoin_testnet")); #else MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet")); #endif if(trayIcon) { // Just attach " [testnet]" to the existing tooltip trayIcon->setToolTip(trayIcon->toolTip() + QString(" ") + tr("[testnet]")); trayIcon->setIcon(QIcon(":/icons/toolbar_testnet")); } toggleHideAction->setIcon(QIcon(":/icons/toolbar_testnet")); aboutAction->setIcon(QIcon(":/icons/toolbar_testnet")); } // Create system tray menu (or setup the dock menu) that late to prevent users from calling actions, // while the client has not yet fully loaded createTrayIconMenu(); // Keep up to date with client setNumConnections(clientModel->getNumConnections()); connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); setNumBlocks(clientModel->getNumBlocks(), clientModel->getNumBlocksOfPeers()); connect(clientModel, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int))); // Receive and report messages from network/worker thread connect(clientModel, SIGNAL(message(QString,QString,unsigned int)), this, SLOT(message(QString,QString,unsigned int))); rpcConsole->setClientModel(clientModel); walletFrame->setClientModel(clientModel); } } bool BitcoinGUI::addWallet(const QString& name, WalletModel *walletModel) { setWalletActionsEnabled(true); return walletFrame->addWallet(name, walletModel); } bool BitcoinGUI::setCurrentWallet(const QString& name) { return walletFrame->setCurrentWallet(name); } void BitcoinGUI::removeAllWallets() { setWalletActionsEnabled(false); walletFrame->removeAllWallets(); } void BitcoinGUI::setWalletActionsEnabled(bool enabled) { overviewAction->setEnabled(enabled); sendCoinsAction->setEnabled(enabled); receiveCoinsAction->setEnabled(enabled); historyAction->setEnabled(enabled); encryptWalletAction->setEnabled(enabled); backupWalletAction->setEnabled(enabled); changePassphraseAction->setEnabled(enabled); signMessageAction->setEnabled(enabled); verifyMessageAction->setEnabled(enabled); addressBookAction->setEnabled(enabled); } void BitcoinGUI::createTrayIcon() { #ifndef Q_OS_MAC trayIcon = new QSystemTrayIcon(this); trayIcon->setToolTip(tr("Valuecash client")); trayIcon->setIcon(QIcon(":/icons/toolbar")); trayIcon->show(); #endif notificator = new Notificator(QApplication::applicationName(), trayIcon); } void BitcoinGUI::createTrayIconMenu() { QMenu *trayIconMenu; #ifndef Q_OS_MAC // return if trayIcon is unset (only on non-Mac OSes) if (!trayIcon) return; trayIconMenu = new QMenu(this); trayIcon->setContextMenu(trayIconMenu); connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason))); #else // Note: On Mac, the dock icon is used to provide the tray's functionality. MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance(); dockIconHandler->setMainWindow((QMainWindow *)this); trayIconMenu = dockIconHandler->dockMenu(); #endif // Configuration of the tray icon (or dock icon) icon menu trayIconMenu->addAction(toggleHideAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(sendCoinsAction); trayIconMenu->addAction(receiveCoinsAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(signMessageAction); trayIconMenu->addAction(verifyMessageAction); trayIconMenu->addSeparator(); trayIconMenu->addAction(optionsAction); trayIconMenu->addAction(openRPCConsoleAction); #ifndef Q_OS_MAC // This is built-in on Mac trayIconMenu->addSeparator(); trayIconMenu->addAction(quitAction); #endif } #ifndef Q_OS_MAC void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason) { if(reason == QSystemTrayIcon::Trigger) { // Click on system tray icon triggers show/hide of the main window toggleHideAction->trigger(); } } #endif void BitcoinGUI::saveWindowGeometry() { QSettings settings; settings.setValue("nWindowPos", pos()); settings.setValue("nWindowSize", size()); } void BitcoinGUI::restoreWindowGeometry() { QSettings settings; QPoint pos = settings.value("nWindowPos").toPoint(); QSize size = settings.value("nWindowSize", QSize(850, 550)).toSize(); if (!pos.x() && !pos.y()) { QRect screen = QApplication::desktop()->screenGeometry(); pos.setX((screen.width()-size.width())/2); pos.setY((screen.height()-size.height())/2); } resize(size); move(pos); } void BitcoinGUI::optionsClicked() { if(!clientModel || !clientModel->getOptionsModel()) return; OptionsDialog dlg; dlg.setModel(clientModel->getOptionsModel()); dlg.exec(); } void BitcoinGUI::aboutClicked() { AboutDialog dlg; dlg.setModel(clientModel); dlg.exec(); } void BitcoinGUI::gotoOverviewPage() { if (walletFrame) walletFrame->gotoOverviewPage(); } void BitcoinGUI::gotoHistoryPage() { if (walletFrame) walletFrame->gotoHistoryPage(); } void BitcoinGUI::gotoAddressBookPage() { if (walletFrame) walletFrame->gotoAddressBookPage(); } void BitcoinGUI::gotoReceiveCoinsPage() { if (walletFrame) walletFrame->gotoReceiveCoinsPage(); } void BitcoinGUI::gotoSendCoinsPage(QString addr) { if (walletFrame) walletFrame->gotoSendCoinsPage(addr); } void BitcoinGUI::gotoSignMessageTab(QString addr) { if (walletFrame) walletFrame->gotoSignMessageTab(addr); } void BitcoinGUI::gotoVerifyMessageTab(QString addr) { if (walletFrame) walletFrame->gotoVerifyMessageTab(addr); } void BitcoinGUI::setNumConnections(int count) { QString icon; switch(count) { case 0: icon = ":/icons/connect_0"; break; case 1: case 2: case 3: icon = ":/icons/connect_1"; break; case 4: case 5: case 6: icon = ":/icons/connect_2"; break; case 7: case 8: case 9: icon = ":/icons/connect_3"; break; default: icon = ":/icons/connect_4"; break; } labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelConnectionsIcon->setToolTip(tr("%n active connection(s) to Valuecash network", "", count)); } void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks) { // Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbelled text) statusBar()->clearMessage(); // Acquire current block source enum BlockSource blockSource = clientModel->getBlockSource(); switch (blockSource) { case BLOCK_SOURCE_NETWORK: progressBarLabel->setText(tr("Synchronizing with network...")); break; case BLOCK_SOURCE_DISK: progressBarLabel->setText(tr("Importing blocks from disk...")); break; case BLOCK_SOURCE_REINDEX: progressBarLabel->setText(tr("Reindexing blocks on disk...")); break; case BLOCK_SOURCE_NONE: // Case: not Importing, not Reindexing and no network connection progressBarLabel->setText(tr("No block source available...")); break; } QString tooltip; QDateTime lastBlockDate = clientModel->getLastBlockDate(); QDateTime currentDate = QDateTime::currentDateTime(); int secs = lastBlockDate.secsTo(currentDate); if(count < nTotalBlocks) { tooltip = tr("Processed %1 of %2 (estimated) blocks of transaction history.").arg(count).arg(nTotalBlocks); } else { tooltip = tr("Processed %1 blocks of transaction history.").arg(count); } // Set icon state: spinning if catching up, tick otherwise if(secs < 90*60 && count >= nTotalBlocks) { tooltip = tr("Up to date") + QString(".<br>") + tooltip; labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE)); walletFrame->showOutOfSyncWarning(false); progressBarLabel->setVisible(false); progressBar->setVisible(false); } else { // Represent time from last generated block in human readable text QString timeBehindText; if(secs < 48*60*60) { timeBehindText = tr("%n hour(s)","",secs/(60*60)); } else if(secs < 14*24*60*60) { timeBehindText = tr("%n day(s)","",secs/(24*60*60)); } else { timeBehindText = tr("%n week(s)","",secs/(7*24*60*60)); } progressBarLabel->setVisible(true); progressBar->setFormat(tr("%1 behind").arg(timeBehindText)); progressBar->setMaximum(1000000000); progressBar->setValue(clientModel->getVerificationProgress() * 1000000000.0 + 0.5); progressBar->setVisible(true); tooltip = tr("Catching up...") + QString("<br>") + tooltip; labelBlocksIcon->setMovie(syncIconMovie); if(count != prevBlocks) syncIconMovie->jumpToNextFrame(); prevBlocks = count; walletFrame->showOutOfSyncWarning(true); tooltip += QString("<br>"); tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText); tooltip += QString("<br>"); tooltip += tr("Transactions after this will not yet be visible."); } // Don't word-wrap this (fixed-width) tooltip tooltip = QString("<nobr>") + tooltip + QString("</nobr>"); labelBlocksIcon->setToolTip(tooltip); progressBarLabel->setToolTip(tooltip); progressBar->setToolTip(tooltip); } void BitcoinGUI::message(const QString &title, const QString &message, unsigned int style, bool *ret) { QString strTitle = tr("Valuecash"); // default title // Default to information icon int nMBoxIcon = QMessageBox::Information; int nNotifyIcon = Notificator::Information; QString msgType; // Prefer supplied title over style based title if (!title.isEmpty()) { msgType = title; } else { switch (style) { case CClientUIInterface::MSG_ERROR: msgType = tr("Error"); break; case CClientUIInterface::MSG_WARNING: msgType = tr("Warning"); break; case CClientUIInterface::MSG_INFORMATION: msgType = tr("Information"); break; default: break; } } // Append title to "Bitcoin - " if (!msgType.isEmpty()) strTitle += " - " + msgType; // Check for error/warning icon if (style & CClientUIInterface::ICON_ERROR) { nMBoxIcon = QMessageBox::Critical; nNotifyIcon = Notificator::Critical; } else if (style & CClientUIInterface::ICON_WARNING) { nMBoxIcon = QMessageBox::Warning; nNotifyIcon = Notificator::Warning; } // Display message if (style & CClientUIInterface::MODAL) { // Check for buttons, use OK as default, if none was supplied QMessageBox::StandardButton buttons; if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK))) buttons = QMessageBox::Ok; // Ensure we get users attention showNormalIfMinimized(); QMessageBox mBox((QMessageBox::Icon)nMBoxIcon, strTitle, message, buttons, this); int r = mBox.exec(); if (ret != NULL) *ret = r == QMessageBox::Ok; } else notificator->notify((Notificator::Class)nNotifyIcon, strTitle, message); } void BitcoinGUI::changeEvent(QEvent *e) { QMainWindow::changeEvent(e); #ifndef Q_OS_MAC // Ignored on Mac if(e->type() == QEvent::WindowStateChange) { if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray()) { QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e); if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized()) { QTimer::singleShot(0, this, SLOT(hide())); e->ignore(); } } } #endif } void BitcoinGUI::closeEvent(QCloseEvent *event) { if(clientModel) { #ifndef Q_OS_MAC // Ignored on Mac if(!clientModel->getOptionsModel()->getMinimizeToTray() && !clientModel->getOptionsModel()->getMinimizeOnClose()) { QApplication::quit(); } #endif } QMainWindow::closeEvent(event); } void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee) { QString strMessage = tr("This transaction is over the size limit. You can still send it for a fee of %1, " "which goes to the nodes that process your transaction and helps to support the network. " "Do you want to pay the fee?").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired)); QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm transaction fee"), strMessage, QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Yes); *payFee = (retval == QMessageBox::Yes); } void BitcoinGUI::incomingTransaction(const QString& date, int unit, qint64 amount, const QString& type, const QString& address) { // On new transaction, make an info balloon message((amount)<0 ? tr("Sent transaction") : tr("Incoming transaction"), tr("Date: %1\n" "Amount: %2\n" "Type: %3\n" "Address: %4\n") .arg(date) .arg(BitcoinUnits::formatWithUnit(unit, amount, true)) .arg(type) .arg(address), CClientUIInterface::MSG_INFORMATION); } void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event) { // Accept only URIs if(event->mimeData()->hasUrls()) event->acceptProposedAction(); } void BitcoinGUI::dropEvent(QDropEvent *event) { if(event->mimeData()->hasUrls()) { int nValidUrisFound = 0; QList<QUrl> uris = event->mimeData()->urls(); foreach(const QUrl &uri, uris) { if (walletFrame->handleURI(uri.toString())) nValidUrisFound++; } // if valid URIs were found if (nValidUrisFound) walletFrame->gotoSendCoinsPage(); else message(tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid Valuecash address or malformed URI parameters."), CClientUIInterface::ICON_WARNING); } event->acceptProposedAction(); } bool BitcoinGUI::eventFilter(QObject *object, QEvent *event) { // Catch status tip events if (event->type() == QEvent::StatusTip) { // Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff if (progressBarLabel->isVisible() || progressBar->isVisible()) return true; } return QMainWindow::eventFilter(object, event); } void BitcoinGUI::handleURI(QString strURI) { // URI has to be valid if (!walletFrame->handleURI(strURI)) message(tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid Valuecash address or malformed URI parameters."), CClientUIInterface::ICON_WARNING); } void BitcoinGUI::setEncryptionStatus(int status) { switch(status) { case WalletModel::Unencrypted: labelEncryptionIcon->hide(); encryptWalletAction->setChecked(false); changePassphraseAction->setEnabled(false); encryptWalletAction->setEnabled(true); break; case WalletModel::Unlocked: labelEncryptionIcon->show(); labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; case WalletModel::Locked: labelEncryptionIcon->show(); labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>")); encryptWalletAction->setChecked(true); changePassphraseAction->setEnabled(true); encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; } } void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden) { // activateWindow() (sometimes) helps with keyboard focus on Windows if (isHidden()) { show(); activateWindow(); } else if (isMinimized()) { showNormal(); activateWindow(); } else if (GUIUtil::isObscured(this)) { raise(); activateWindow(); } else if(fToggleHidden) hide(); } void BitcoinGUI::toggleHidden() { showNormalIfMinimized(true); } void BitcoinGUI::detectShutdown() { if (ShutdownRequested()) QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection); }
[ "root@ubuntu-minimal.unspecified" ]
root@ubuntu-minimal.unspecified
001ea1772f8308cece1ccdb8a6aa74947106b2f6
1d304cb05e293fedfdcc9cf4f38133f32d5447b0
/VMSClient/editblackinfodlg.h
0e13da04078486af8417d76589cfe94172694457
[]
no_license
DimaKornev/VideoManagmentSystem
db254427e479669d713d604e3f97a73a2fccb1d3
27d2eb8b75a4f21afa67135e3ee51711aaa19cdf
refs/heads/master
2023-04-15T08:14:04.180847
2021-04-29T08:30:40
2021-04-29T08:30:40
362,552,722
0
0
null
null
null
null
UTF-8
C++
false
false
1,473
h
#ifndef EDITBLACKINFODLG_H #define EDITBLACKINFODLG_H #include "clientbase.h" #include <QDialog> namespace Ui { class EditBlackInfoDlg; } class NextButtonItem; class FrameResultItem; class ServerInfoSocket; class EditOneBlackListSocket; class EditBlackInfoDlg : public QDialog { Q_OBJECT public: explicit EditBlackInfoDlg(QWidget *parent = 0); ~EditBlackInfoDlg(); void setInfo(ServerInfoSocket* serverInfoSocket, int chanelIndex, BLACK_PERSON blackPerson); BLACK_PERSON blackPersonInfo(); public slots: void slotAddFace(); void slotDeleteFace(); void slotOk(); void slotCancel(); void slotEnrollPrevClicked(); void slotEnrollNextClicked(); protected: void resizeEvent(QResizeEvent* e); private: void setupActions(); void constructEnrollResultItems(); void refreshEnrollResultItems(); void relocateEnrollResultItems(); void retranslateUI(); private: Ui::EditBlackInfoDlg *ui; QGraphicsScene* m_enrollScene; NextButtonItem* m_enrollPrevItem; NextButtonItem* m_enrollNextItem; QVector<FrameResultItem*> m_enrollFrameItems; QVector<FRAME_RESULT> m_enrollFrameResults; ServerInfoSocket* m_serverInfoSocket; int m_chanelIndex; BLACK_PERSON m_blackPersonInfo; }; #endif // EDITBLACKINFODLG_H
[ "demidemi_1@outlook.com" ]
demidemi_1@outlook.com
77db9160ce8db2ebac0fe8c60ba2817f63eea83f
7398d79483b8b6fa51874859e07f1629e2cc7686
/test/doc/http_snippets.cpp
1547de72017e6ee1b31dce5ea0f87e8a87af68fe
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
buckaroo-upgrade-bot/boost-beast
4dc17ec199ce73d5cbec974ce2ac1fcf91c5b89f
d9a87bffcd92c58e2bc2f873a2e1ca6802e96fe4
refs/heads/master
2020-04-17T08:19:06.026456
2019-03-19T23:40:24
2019-03-19T23:40:24
166,407,132
0
0
null
2019-01-18T13:12:45
2019-01-18T13:12:45
null
UTF-8
C++
false
false
11,389
cpp
// // Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/boostorg/beast // #include <boost/beast/core.hpp> #include <boost/asio.hpp> #include <boost/config.hpp> #include <iostream> #include <thread> using namespace boost::beast; //[http_snippet_1 #include <boost/beast/http.hpp> using namespace boost::beast::http; //] namespace doc_http_snippets { //[http_snippet_17 // This function returns the buffer containing the next chunk body net::const_buffer get_next_chunk_body(); //] net::const_buffer get_next_chunk_body() { return {nullptr, 0}; } void fxx() { net::io_context ioc; auto work = net::make_work_guard(ioc); std::thread t{[&](){ ioc.run(); }}; net::ip::tcp::socket sock{ioc}; { //[http_snippet_2 request<empty_body> req; req.version(11); // HTTP/1.1 req.method(verb::get); req.target("/index.htm"); req.set(field::accept, "text/html"); req.set(field::user_agent, "Beast"); //] } { //[http_snippet_3 response<string_body> res; res.version(11); // HTTP/1.1 res.result(status::ok); res.set(field::server, "Beast"); res.body() = "Hello, world!"; res.prepare_payload(); //] } { //[http_snippet_4 flat_buffer buffer; // (The parser is optimized for flat buffers) request<string_body> req; read(sock, buffer, req); //] } { //[http_snippet_5 flat_buffer buffer; response<string_body> res; async_read(sock, buffer, res, [&](error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); std::cerr << ec.message() << std::endl; }); //] } { //[http_snippet_6 // This buffer's max size is too small for much of anything flat_buffer buffer{10}; // Try to read a request error_code ec; request<string_body> req; read(sock, buffer, req, ec); if(ec == http::error::buffer_overflow) std::cerr << "Buffer limit exceeded!" << std::endl; //] } { //[http_snippet_7 response<string_body> res; res.version(11); res.result(status::ok); res.set(field::server, "Beast"); res.body() = "Hello, world!"; res.prepare_payload(); error_code ec; write(sock, res, ec); //] //[http_snippet_8 async_write(sock, res, [&](error_code ec, std::size_t bytes_transferred) { boost::ignore_unused(bytes_transferred); if(ec) std::cerr << ec.message() << std::endl; }); //] } { //[http_snippet_10 response<string_body> res; response_serializer<string_body> sr{res}; //] } { //[http_snippet_18 // Prepare an HTTP/1.1 response with a chunked body response<empty_body> res{status::ok, 11}; res.set(field::server, "Beast"); // Set Transfer-Encoding to "chunked". // If a Content-Length was present, it is removed. res.chunked(true); // Set up the serializer response_serializer<empty_body> sr{res}; // Write the header first write_header(sock, sr); // Now manually emit three chunks: net::write(sock, make_chunk(get_next_chunk_body())); net::write(sock, make_chunk(get_next_chunk_body())); net::write(sock, make_chunk(get_next_chunk_body())); // We are responsible for sending the last chunk: net::write(sock, make_chunk_last()); //] } { //[http_snippet_19 // Prepare a set of chunk extension to emit with the body chunk_extensions ext; ext.insert("mp3"); ext.insert("title", "Beale Street Blues"); ext.insert("artist", "W.C. Handy"); // Write the next chunk with the chunk extensions // The implementation will make a copy of the extensions object, // so the caller does not need to manage lifetime issues. net::write(sock, make_chunk(get_next_chunk_body(), ext)); // Write the next chunk with the chunk extensions // The implementation will make a copy of the extensions object, storing the copy // using the custom allocator, so the caller does not need to manage lifetime issues. net::write(sock, make_chunk(get_next_chunk_body(), ext, std::allocator<char>{})); // Write the next chunk with the chunk extensions // The implementation allocates memory using the default allocator and takes ownership // of the extensions object, so the caller does not need to manage lifetime issues. // Note: ext is moved net::write(sock, make_chunk(get_next_chunk_body(), std::move(ext))); //] } { //[http_snippet_20 // Manually specify the chunk extensions. // Some of the strings contain spaces and a period and must be quoted net::write(sock, make_chunk(get_next_chunk_body(), ";mp3" ";title=\"Danny Boy\"" ";artist=\"Fred E. Weatherly\"" )); //] } { //[http_snippet_21 // Prepare a chunked HTTP/1.1 response with some trailer fields response<empty_body> res{status::ok, 11}; res.set(field::server, "Beast"); // Inform the client of the trailer fields we will send res.set(field::trailer, "Content-MD5, Expires"); res.chunked(true); // Serialize the header and two chunks response_serializer<empty_body> sr{res}; write_header(sock, sr); net::write(sock, make_chunk(get_next_chunk_body())); net::write(sock, make_chunk(get_next_chunk_body())); // Prepare the trailer fields trailer; trailer.set(field::content_md5, "f4a5c16584f03d90"); trailer.set(field::expires, "never"); // Emit the trailer in the last chunk. // The implementation will use the default allocator to create the storage for holding // the serialized fields. net::write(sock, make_chunk_last(trailer)); //] } { //[http_snippet_22 // Use a custom allocator for serializing the last chunk fields trailer; trailer.set(field::approved, "yes"); net::write(sock, make_chunk_last(trailer, std::allocator<char>{})); //] } { //[http_snippet_23 // Manually emit a trailer. // We are responsible for ensuring that the trailer format adheres to the specification. string_view ext = "Content-MD5: f4a5c16584f03d90\r\n" "Expires: never\r\n" "\r\n"; net::write(sock, make_chunk_last(net::const_buffer{ext.data(), ext.size()})); //] } { //[http_snippet_24 // Prepare a chunked HTTP/1.1 response and send the header response<empty_body> res{status::ok, 11}; res.set(field::server, "Beast"); res.chunked(true); response_serializer<empty_body> sr{res}; write_header(sock, sr); // Obtain three body buffers up front auto const cb1 = get_next_chunk_body(); auto const cb2 = get_next_chunk_body(); auto const cb3 = get_next_chunk_body(); // Manually emit a chunk by first writing the chunk-size header with the correct size net::write(sock, chunk_header{ net::buffer_size(cb1) + net::buffer_size(cb2) + net::buffer_size(cb3)}); // And then output the chunk body in three pieces ("chunk the chunk") net::write(sock, cb1); net::write(sock, cb2); net::write(sock, cb3); // When we go this deep, we are also responsible for the terminating CRLF net::write(sock, chunk_crlf{}); //] } } // fxx() //[http_snippet_12 /** Send a message to a stream synchronously. @param stream The stream to write to. This type must support the @b SyncWriteStream concept. @param m The message to send. The Body type must support the @b BodyWriter concept. */ template< class SyncWriteStream, bool isRequest, class Body, class Fields> void send( SyncWriteStream& stream, message<isRequest, Body, Fields> const& m) { // Check the template types static_assert(is_sync_write_stream<SyncWriteStream>::value, "SyncWriteStream requirements not met"); static_assert(is_body_writer<Body>::value, "BodyWriter requirements not met"); // Create the instance of serializer for the message serializer<isRequest, Body, Fields> sr{m}; // Loop until the serializer is finished do { // This call guarantees it will make some // forward progress, or otherwise return an error. write_some(stream, sr); } while(! sr.is_done()); } //] //[http_snippet_13 template<class SyncReadStream> void print_response(SyncReadStream& stream) { static_assert(is_sync_read_stream<SyncReadStream>::value, "SyncReadStream requirements not met"); // Declare a parser for an HTTP response response_parser<string_body> parser; // Read the entire message read(stream, parser); // Now print the message std::cout << parser.get() << std::endl; } //] #ifdef BOOST_MSVC //[http_snippet_14 template<bool isRequest, class Body, class Fields> void print_cxx14(message<isRequest, Body, Fields> const& m) { error_code ec; serializer<isRequest, Body, Fields> sr{m}; do { sr.next(ec, [&sr](error_code& ec, auto const& buffer) { ec.assign(0, ec.category()); std::cout << buffers(buffer); sr.consume(net::buffer_size(buffer)); }); } while(! ec && ! sr.is_done()); if(! ec) std::cout << std::endl; else std::cerr << ec.message() << std::endl; } //] #endif //[http_snippet_15 template<class Serializer> struct lambda { Serializer& sr; lambda(Serializer& sr_) : sr(sr_) {} template<class ConstBufferSequence> void operator()(error_code& ec, ConstBufferSequence const& buffer) const { ec.assign(0, ec.category()); std::cout << buffers(buffer); sr.consume(net::buffer_size(buffer)); } }; template<bool isRequest, class Body, class Fields> void print(message<isRequest, Body, Fields> const& m) { error_code ec; serializer<isRequest, Body, Fields> sr{m}; do { sr.next(ec, lambda<decltype(sr)>{sr}); } while(! ec && ! sr.is_done()); if(! ec) std::cout << std::endl; else std::cerr << ec.message() << std::endl; } //] #if BOOST_MSVC //[http_snippet_16 template<bool isRequest, class Body, class Fields> void split_print_cxx14(message<isRequest, Body, Fields> const& m) { error_code ec; serializer<isRequest, Body, Fields> sr{m}; sr.split(true); std::cout << "Header:" << std::endl; do { sr.next(ec, [&sr](error_code& ec, auto const& buffer) { ec.assign(0, ec.category()); std::cout << buffers(buffer); sr.consume(net::buffer_size(buffer)); }); } while(! sr.is_header_done()); if(! ec && ! sr.is_done()) { std::cout << "Body:" << std::endl; do { sr.next(ec, [&sr](error_code& ec, auto const& buffer) { ec.assign(0, ec.category()); std::cout << buffers(buffer); sr.consume(net::buffer_size(buffer)); }); } while(! ec && ! sr.is_done()); } if(ec) std::cerr << ec.message() << std::endl; } //] #endif // Highest snippet: } // doc_http_snippets
[ "vinnie.falco@gmail.com" ]
vinnie.falco@gmail.com
247cf1ffbca41d65eadac56fc8d16f78796406e4
67fc9e51437e351579fe9d2d349040c25936472a
/wrappers/8.1.1/vtkLightWrap.h
d4e20b83906f83541a967cb953663ac84ed0d651
[]
permissive
axkibe/node-vtk
51b3207c7a7d3b59a4dd46a51e754984c3302dec
900ad7b5500f672519da5aa24c99aa5a96466ef3
refs/heads/master
2023-03-05T07:45:45.577220
2020-03-30T09:31:07
2020-03-30T09:31:07
48,490,707
6
0
BSD-3-Clause
2022-12-07T20:41:45
2015-12-23T12:58:43
C++
UTF-8
C++
false
false
5,033
h
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #ifndef NATIVE_EXTENSION_VTK_VTKLIGHTWRAP_H #define NATIVE_EXTENSION_VTK_VTKLIGHTWRAP_H #include <nan.h> #include <vtkSmartPointer.h> #include <vtkLight.h> #include "vtkObjectWrap.h" #include "../../plus/plus.h" class VtkLightWrap : public VtkObjectWrap { public: using Nan::ObjectWrap::Wrap; static void Init(v8::Local<v8::Object> exports); static void InitPtpl(); static void ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info); VtkLightWrap(vtkSmartPointer<vtkLight>); VtkLightWrap(); ~VtkLightWrap( ); static Nan::Persistent<v8::FunctionTemplate> ptpl; private: static void New(const Nan::FunctionCallbackInfo<v8::Value>& info); static void DeepCopy(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetAmbientColor(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetAttenuationValues(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetConeAngle(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetDiffuseColor(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetExponent(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetExponentMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetExponentMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetFocalPoint(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetInformation(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetIntensity(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetLightType(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPosition(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetPositional(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetShadowAttenuation(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetSpecularColor(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetSwitch(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetTransformMatrix(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetTransformedFocalPoint(const Nan::FunctionCallbackInfo<v8::Value>& info); static void GetTransformedPosition(const Nan::FunctionCallbackInfo<v8::Value>& info); static void LightTypeIsCameraLight(const Nan::FunctionCallbackInfo<v8::Value>& info); static void LightTypeIsHeadlight(const Nan::FunctionCallbackInfo<v8::Value>& info); static void LightTypeIsSceneLight(const Nan::FunctionCallbackInfo<v8::Value>& info); static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info); static void PositionalOff(const Nan::FunctionCallbackInfo<v8::Value>& info); static void PositionalOn(const Nan::FunctionCallbackInfo<v8::Value>& info); static void Render(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetAmbientColor(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetAttenuationValues(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetColor(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetConeAngle(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetDiffuseColor(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetDirectionAngle(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetExponent(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetFocalPoint(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetInformation(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetIntensity(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetLightType(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetLightTypeToCameraLight(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetLightTypeToHeadlight(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetLightTypeToSceneLight(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetPosition(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetPositional(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetShadowAttenuation(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetSpecularColor(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetSwitch(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SetTransformMatrix(const Nan::FunctionCallbackInfo<v8::Value>& info); static void ShallowClone(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SwitchOff(const Nan::FunctionCallbackInfo<v8::Value>& info); static void SwitchOn(const Nan::FunctionCallbackInfo<v8::Value>& info); #ifdef VTK_NODE_PLUS_VTKLIGHTWRAP_CLASSDEF VTK_NODE_PLUS_VTKLIGHTWRAP_CLASSDEF #endif }; #endif
[ "axkibe@gmail.com" ]
axkibe@gmail.com
2d5639a31e7188d1f5dcc32514afdb2f5ee7013a
49e19b37a5e02de8536d3b27aaab850304f8a04f
/Cours08/Cours08/cDuree.h
bd235d53406fc2c7540b9c3ed0c6be5127701814
[]
no_license
CdrcMag/Cpp
18093fe2765b784abc00185f4becbf17a8657ae9
25f413143eeefe70d54d76f1ab24c889aef1c29f
refs/heads/master
2023-01-05T12:59:17.476894
2020-11-02T13:08:20
2020-11-02T13:08:20
256,959,698
0
0
null
null
null
null
ISO-8859-1
C++
false
false
581
h
#pragma once #include <iostream> #include <string> using namespace std; class cDuree { public: cDuree(int heures = 0, int minutes = 0, int secondes = 0); cDuree(); ~cDuree(); private: void display(ostream& out) const; //Permet d'écrire la durée dans un flux int m_heures; int m_minutes; int m_secondes; //Déclaration de la fonctione amie, afin qu'elle ait accès à la méthode display(ostream&). friend ostream &operator<<(ostream &out, cDuree const& duree); //L'opérateur << a donc accès à la classe cDuree. Il peut donc utiliser display(ostream&) };
[ "44393506+CdrcMag@users.noreply.github.com" ]
44393506+CdrcMag@users.noreply.github.com
40f5c774797bf858d9ac045c506622e4412273c6
c7b3fe0bfba65401385a362c8233943807c2a52c
/src/playlisttabwidget.h
d370a856cfab0594765464f787721d5ef2fe7789
[ "MIT" ]
permissive
MarcoQin/LavAplayer
0a2857e13a412d4004a710eb48607cc6de64bb48
7bd04fba4a8a099b655daeb498c354a7b795f89f
refs/heads/master
2021-01-13T04:19:49.393571
2017-01-19T11:02:02
2017-01-19T11:02:02
77,434,644
0
0
null
null
null
null
UTF-8
C++
false
false
321
h
#ifndef PLAYLISTTABWIDGET_H #define PLAYLISTTABWIDGET_H #include <QTabWidget> class PlayListView; class PlayListTabWidget : public QTabWidget { Q_OBJECT public: PlayListTabWidget(QWidget *parent = nullptr); public slots: PlayListView *createTab(bool makeCurrent = true); }; #endif // PLAYLISTTABWIDGET_H
[ "qyyfy2009@163.com" ]
qyyfy2009@163.com
c16f424879cd8021a1cdcb0a8eba9ecdef832a44
30578c2f81c901b57b4b0805a8ca878367115ac0
/Src/LandscapeEditorFrame.cpp
0a9d64f50c9a76106e2aacffd9217c173324eb5f
[ "MIT" ]
permissive
CerberusDev/LandscapeEditor
dbe4bb6aa7b3dd8b4d203d7b77a81d39a9551656
6ee5a36854c808518b24e841200bb33cb3867076
refs/heads/master
2016-09-06T18:13:05.815552
2014-09-28T14:40:13
2014-09-28T14:40:13
22,888,537
2
2
null
2014-09-21T18:38:38
2014-08-12T18:51:21
C++
UTF-8
C++
false
false
6,945
cpp
// -------------------------------------------------------------------- // Created by: Maciej Pryc // Date: 23.03.2013 // -------------------------------------------------------------------- #include <wx/stdpaths.h> #include <wx/numdlg.h> #include "LandscapeEditor.h" // -------------------------------------------------------------------- /** wxWidgets - Event table stuff */ enum { ID_NEW = 11, ID_OPEN = 12, ID_SAVE = 13, ID_BRUSH_1 = 100, ID_BRUSH_2 = 101, ID_BRUSH_3 = 102, ID_BRUSH_4 = 103, ID_COMBO = 1000 }; BEGIN_EVENT_TABLE(LandscapeEditorFrame, wxFrame) EVT_MENU(wxID_EXIT, LandscapeEditorFrame::OnQuit) EVT_MENU(wxID_HELP, LandscapeEditorFrame::OnAbout) EVT_MENU(ID_NEW, LandscapeEditorFrame::OnNew) EVT_MENU(ID_OPEN, LandscapeEditorFrame::OnOpen) EVT_MENU(ID_SAVE, LandscapeEditorFrame::OnSave) EVT_MENU(ID_BRUSH_1, LandscapeEditorFrame::OnBrush1) EVT_MENU(ID_BRUSH_2, LandscapeEditorFrame::OnBrush2) EVT_MENU(ID_BRUSH_3, LandscapeEditorFrame::OnBrush3) EVT_MENU(ID_BRUSH_4, LandscapeEditorFrame::OnBrush4) END_EVENT_TABLE() // -------------------------------------------------------------------- LandscapeEditorFrame::LandscapeEditorFrame(wxFrame* parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style): wxFrame(parent, id, title, pos, size, style) { SetIcon(wxICON(appicon)); CreateStatusBar(); new LandGLCanvas(this); wxMenuBar* menuBar = new wxMenuBar(wxMB_DOCKABLE); wxMenu *fileMenu = new wxMenu; fileMenu->Append(wxID_EXIT, wxT("E&xit\tAlt-X"), wxT("Quit Editor") ); wxMenu *helpMenu = new wxMenu; helpMenu->Append(wxID_HELP, wxT("&About"), wxT("About Edtior")); menuBar->Append(fileMenu, wxT("&File")); menuBar->Append(helpMenu, wxT("&Help")); SetMenuBar(menuBar); // test IsDisplaySupported() function: static const int attribs[] = { WX_GL_RGBA, WX_GL_DOUBLEBUFFER, 0 }; //wxLogStatus("Double-buffered display %s supported", // wxGLCanvas::IsDisplaySupported(attribs) ? "is" : "not"); CreateToolbar(); } // -------------------------------------------------------------------- void LandscapeEditorFrame::CreateToolbar() { enum { Tool_new, Tool_open, Tool_save, Tool_help, Tool_brush1, Tool_brush2, Tool_brush3, Tool_brush4, Tool_Max }; toolbarTop = CreateToolBar(wxTB_FLAT | wxTB_DOCKABLE, ID_TOOLBAR); wxBitmap toolBarBitmaps[Tool_Max]; #define INIT_TOOL_BMP(bmp) \ toolBarBitmaps[Tool_##bmp] = wxBITMAP(bmp) INIT_TOOL_BMP(new); INIT_TOOL_BMP(open); INIT_TOOL_BMP(save); INIT_TOOL_BMP(help); INIT_TOOL_BMP(brush1); INIT_TOOL_BMP(brush2); INIT_TOOL_BMP(brush3); INIT_TOOL_BMP(brush4); toolbarTop->AddSeparator(); toolbarTop->AddTool(ID_NEW, wxT("New"), toolBarBitmaps[Tool_new], wxNullBitmap, wxITEM_NORMAL, wxT("New file"), wxT("This is 'new map' tool")); toolbarTop->AddTool(ID_OPEN, wxT("Open"), toolBarBitmaps[Tool_open], wxNullBitmap, wxITEM_NORMAL, wxT("Open file"), wxT("This is 'open map file' tool")); toolbarTop->AddTool(ID_SAVE, wxT("Save"), toolBarBitmaps[Tool_save], wxNullBitmap, wxITEM_NORMAL, wxT("Save map"), wxT("This is 'save map' tool")); toolbarTop->AddSeparator(); //toolbarTop->AddTool(ID_BRUSH_1, wxT("New"), toolBarBitmaps[Tool_brush1], wxNullBitmap, wxITEM_NORMAL, // wxT("Brush 1"), wxT("Click for select first brush")); //toolbarTop->AddTool(ID_BRUSH_2, wxT("New"), toolBarBitmaps[Tool_brush2], wxNullBitmap, wxITEM_NORMAL, // wxT("Brush 2"), wxT("Click for select second brush")); //toolbarTop->AddTool(ID_BRUSH_3, wxT("New"), toolBarBitmaps[Tool_brush3], wxNullBitmap, wxITEM_NORMAL, // wxT("Brush 3"), wxT("Click for select third brush")); //toolbarTop->AddTool(ID_BRUSH_4, wxT("New"), toolBarBitmaps[Tool_brush4], wxNullBitmap, wxITEM_NORMAL, // wxT("Brush 4"), wxT("Click for select fourth brush")); //toolbarTop->AddSeparator(); toolbarTop->AddTool(wxID_HELP, wxT("Help"), toolBarBitmaps[Tool_help], wxT("Help button"), wxITEM_CHECK); toolbarTop->Realize(); } // -------------------------------------------------------------------- void LandscapeEditorFrame::OnQuit(wxCommandEvent& WXUNUSED(event)) { Close(true); } // -------------------------------------------------------------------- void LandscapeEditorFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) { (void)wxMessageBox(wxT("Created by Maciek Pryc"), wxT("Landscape Editor info")); } // -------------------------------------------------------------------- void LandscapeEditorFrame::OnNew(wxCommandEvent& WXUNUSED(event)) { long Result = wxGetNumberFromUser(wxT("How big should be your terrain?"), wxT("Enter a number:"), wxT("Create new landscape"), 50, 2, 1000); if (Result != -1 ) LandscapeEditor::Inst()->GetContext().CreateNewLandscape(Result); } // -------------------------------------------------------------------- void LandscapeEditorFrame::OnOpen(wxCommandEvent& WXUNUSED(event)) { wxFileDialog dialog(this, wxT("Open existing map"), wxEmptyString, wxEmptyString, wxT("Data files (*.raw)|*.raw")); dialog.SetDirectory(wxStandardPaths::Get().GetDataDir()); if (dialog.ShowModal() == wxID_OK) LandscapeEditor::Inst()->GetContext().OpenFromFile(dialog.GetPath().c_str().AsChar()); } // -------------------------------------------------------------------- void LandscapeEditorFrame::OnSave(wxCommandEvent& WXUNUSED(event)) { wxFileDialog dialog(this, wxT("Save map"), wxEmptyString, wxT("MyTerrain.raw"), wxT("Data files (*.raw)|*.raw"), wxFD_SAVE|wxFD_OVERWRITE_PROMPT); dialog.SetDirectory(wxStandardPaths::Get().GetDataDir()); if (dialog.ShowModal() == wxID_OK) LandscapeEditor::Inst()->GetContext().SaveLandscape(dialog.GetPath().c_str().AsChar()); } // -------------------------------------------------------------------- void LandscapeEditorFrame::OnBrush1(wxCommandEvent& WXUNUSED(event)) { LandscapeEditor::Inst()->GetContext().ChangeBrushMode(0); } // -------------------------------------------------------------------- void LandscapeEditorFrame::OnBrush2(wxCommandEvent& WXUNUSED(event)) { LandscapeEditor::Inst()->GetContext().ChangeBrushMode(1); } // -------------------------------------------------------------------- void LandscapeEditorFrame::OnBrush3(wxCommandEvent& WXUNUSED(event)) { LandscapeEditor::Inst()->GetContext().ChangeBrushMode(2); } // -------------------------------------------------------------------- void LandscapeEditorFrame::OnBrush4(wxCommandEvent& WXUNUSED(event)) { LandscapeEditor::Inst()->GetContext().ChangeBrushMode(3); }
[ "pryc.maciej@gmail.com" ]
pryc.maciej@gmail.com
33bd8d9a004d035aabda141389dea4cf39afa793
bc776f64914f5d82224af354cd41119b232b742f
/dynarobinsim/DynaRobinIKin/ALGLIB/alglibmisc.cpp
5ee53bb8bfa2c5253f5a235f76c528fca5d66e17
[]
no_license
DominikPetrovic/Diplomski-seminar-2017
3bb93a87d481a59ef2fe6b3a5111924e174ba787
7914e62233fab258e163bcf2f7210a3f0282f716
refs/heads/master
2021-06-19T07:22:14.907560
2017-05-25T21:29:34
2017-05-25T21:29:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
179,717
cpp
/************************************************************************* Copyright (c) Sergey Bochkanov (ALGLIB project). >>> SOURCE LICENSE >>> This program is a Commercial Edition of the ALGLIB package licensed to Fakultet strojarstva i brodogradnje (Licensee). Only Licensee and its Sublicensees can use/distribute it according to the ALGLIB License Agreement (see below) between Licensor (Sole Proprietor Bochkanov Sergey Anatolyevich) and Licensee. All developers working for Licensee should register themselves at alglib.net. Quick access link for Licensee's account can be found at the section 9 of scanned copy of ALGLIB License Agreement or in e-mails from ALGLIB Project. This source code may contain modifications made by Licensee or Sublicensees which fall under the terms of the ALGLIB License Agreement too. ================ ALGLIB LICENSE AGREEMENT ( APPENDIX A ) ================ DEFINITIONS: * "ALGLIB" – software delivered by Licensor to Licensee under present Agreement. ALGLIB may include Binary Components (delivered only in binary form) and Source Code Components (with optional precompiled binary form). ALGLIB may include optional third-party components, which may have their own licensing terms. Specific list of components and additional licensing terms (if there are any) is included in the license.txt file in the root of archive containing ALGLIB. If you decide not to link ALGLIB with these optional components, their licensing terms do not apply to you. * "Application" - program developed by Licensee (either standalone application or software development library) which includes ALGLIB as one of its parts . * "Sublicensee" - any party (including resellers) which receives Application from Licensee or another Sublicensee. * "Application License Agreement" - agreement which governs usage/ redistribution of the Application. LICENSE GRANT: Subject to the License Restrictions below, Licensor grants to Licensee the following non-exclusive royalty-free licenses: A. To modify Source Code Components of ALGLIB and to use modified version on the terms of this Agreement. B. To develop Applications which use ALGLIB and to distribute such Applications in Binary and/or Source Code forms, with ALGLIB either statically or dynamically linked. This right is granted provided that: * distribution of Source Code forms of Application/ALGLIB is performed subject to additional conditions set by clause H (this clause is not applied to binary-only distribution) * such Applications add significant primary functionality different from that of the ALGLIB. * such Applications do not expose ALGLIB API (application programming interface) either directly or indirectly * Sublicensee has no right to use ALGLIB except as part of the Application * any subsequent redistribution respects conditions of the present Agreement * all developers working for Licensee should register at company's account at www.alglib.net (in order to find login link, see section 9 of scanned copy of ALGLIB License Agreement -or find it in e-mails from ALGLIB Project). C. To use Resellers for distribution of the Application (in Binary or Source Code forms), provided that the only activity Reseller performs with Application is redistribution. LICENSE RESTRICTIONS: D. Licensee/Sublicensee may NOT use, copy or distribute ALGLIB except as provided in this Agreement. D2. Licensee/Sublicensee may NOT rent or lease ALGLIB to any third party. E. Licensee/Sublicensee may NOT disassemble, reverse engineer, decompile, modify Binary Components of ALGLIB or compiled forms of Source Code components. F. Licensee/Sublicensee may NOT remove any copyright notice from the Source Code / Binary Components. G. Licensee/Sublicensee may NOT disable/remove code which checks for presence of license keys (if such code is included in ALGLIB) from the Source Code / Binary Components. H. Distribution of Source Code forms of Application/ALGLIB must be performed subject to additional conditions: * Source Code Components of ALGLIB are distributed only as part of the Application. They are not publicly distributed. Sublicensee must explicitly accept Application License Agreement in order to access ALGLIB source code. * Sublicensee has no right to redistribute Application/ALGLIB (in any form, Binary or Source Code), unless Sublicensee is Reseller who is fully compliant with conditions set by clause C. * Sublicensee has no right to modify ALGLIB Source Code, except for the purpose of fixing bugs * Sublicensee has no right to workaround "use ALGLIB only as part of the Application" limitation by sequentially modifying Application in a way which effectively creates new program with different purpose. Application License Agreement may (a) explicitly forbid such modifications, or (b) allow only limited set of "safe" modifications (developing plugins, fixing bugs, modifying only specific parts of the Application). COPYRIGHT: Title to the ALGLIB and all copies thereof remain with Licensor. The ALGLIB is copyrighted and is protected by Russian copyright laws and international treaty provisions. You will not remove any copyright notice from the ALGLIB files. You agree to prevent any unauthorized copying of the ALGLIB. Except as expressly provided herein, Licensor does not grant any express or implied right to you under Licensor patents, copyrights, trademarks, or trade secret information. >>> END OF LICENSE >>> *************************************************************************/ #include "stdafx.h" #include "alglibmisc.h" // disable some irrelevant warnings #if (AE_COMPILER==AE_MSVC) #pragma warning(disable:4100) #pragma warning(disable:4127) #pragma warning(disable:4702) #pragma warning(disable:4996) #endif using namespace std; ///////////////////////////////////////////////////////////////////////// // // THIS SECTION CONTAINS IMPLEMENTATION OF C++ INTERFACE // ///////////////////////////////////////////////////////////////////////// namespace alglib { /************************************************************************* Portable high quality random number generator state. Initialized with HQRNDRandomize() or HQRNDSeed(). Fields: S1, S2 - seed values V - precomputed value MagicV - 'magic' value used to determine whether State structure was correctly initialized. *************************************************************************/ _hqrndstate_owner::_hqrndstate_owner() { p_struct = (alglib_impl::hqrndstate*)alglib_impl::ae_malloc(sizeof(alglib_impl::hqrndstate), NULL); if( p_struct==NULL ) throw ap_error("ALGLIB: malloc error"); if( !alglib_impl::_hqrndstate_init(p_struct, NULL, ae_false) ) throw ap_error("ALGLIB: malloc error"); } _hqrndstate_owner::_hqrndstate_owner(const _hqrndstate_owner &rhs) { p_struct = (alglib_impl::hqrndstate*)alglib_impl::ae_malloc(sizeof(alglib_impl::hqrndstate), NULL); if( p_struct==NULL ) throw ap_error("ALGLIB: malloc error"); if( !alglib_impl::_hqrndstate_init_copy(p_struct, const_cast<alglib_impl::hqrndstate*>(rhs.p_struct), NULL, ae_false) ) throw ap_error("ALGLIB: malloc error"); } _hqrndstate_owner& _hqrndstate_owner::operator=(const _hqrndstate_owner &rhs) { if( this==&rhs ) return *this; alglib_impl::_hqrndstate_clear(p_struct); if( !alglib_impl::_hqrndstate_init_copy(p_struct, const_cast<alglib_impl::hqrndstate*>(rhs.p_struct), NULL, ae_false) ) throw ap_error("ALGLIB: malloc error"); return *this; } _hqrndstate_owner::~_hqrndstate_owner() { alglib_impl::_hqrndstate_clear(p_struct); ae_free(p_struct); } alglib_impl::hqrndstate* _hqrndstate_owner::c_ptr() { return p_struct; } alglib_impl::hqrndstate* _hqrndstate_owner::c_ptr() const { return const_cast<alglib_impl::hqrndstate*>(p_struct); } hqrndstate::hqrndstate() : _hqrndstate_owner() { } hqrndstate::hqrndstate(const hqrndstate &rhs):_hqrndstate_owner(rhs) { } hqrndstate& hqrndstate::operator=(const hqrndstate &rhs) { if( this==&rhs ) return *this; _hqrndstate_owner::operator=(rhs); return *this; } hqrndstate::~hqrndstate() { } /************************************************************************* HQRNDState initialization with random values which come from standard RNG. -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndrandomize(hqrndstate &state) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::hqrndrandomize(const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* HQRNDState initialization with seed values -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndseed(const ae_int_t s1, const ae_int_t s2, hqrndstate &state) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::hqrndseed(s1, s2, const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This function generates random real number in (0,1), not including interval boundaries State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ double hqrnduniformr(const hqrndstate &state) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { double result = alglib_impl::hqrnduniformr(const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<double*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This function generates random integer number in [0, N) 1. State structure must be initialized with HQRNDRandomize() or HQRNDSeed() 2. N can be any positive number except for very large numbers: * close to 2^31 on 32-bit systems * close to 2^62 on 64-bit systems An exception will be generated if N is too large. -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ ae_int_t hqrnduniformi(const hqrndstate &state, const ae_int_t n) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::hqrnduniformi(const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), n, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* Random number generator: normal numbers This function generates one random number from normal distribution. Its performance is equal to that of HQRNDNormal2() State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ double hqrndnormal(const hqrndstate &state) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { double result = alglib_impl::hqrndnormal(const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<double*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* Random number generator: random X and Y such that X^2+Y^2=1 State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndunit2(const hqrndstate &state, double &x, double &y) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::hqrndunit2(const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), &x, &y, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* Random number generator: normal numbers This function generates two independent random numbers from normal distribution. Its performance is equal to that of HQRNDNormal() State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndnormal2(const hqrndstate &state, double &x1, double &x2) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::hqrndnormal2(const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), &x1, &x2, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* Random number generator: exponential distribution State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 11.08.2007 by Bochkanov Sergey *************************************************************************/ double hqrndexponential(const hqrndstate &state, const double lambdav) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { double result = alglib_impl::hqrndexponential(const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), lambdav, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<double*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This function generates random number from discrete distribution given by finite sample X. INPUT PARAMETERS State - high quality random number generator, must be initialized with HQRNDRandomize() or HQRNDSeed(). X - finite sample N - number of elements to use, N>=1 RESULT this function returns one of the X[i] for random i=0..N-1 -- ALGLIB -- Copyright 08.11.2011 by Bochkanov Sergey *************************************************************************/ double hqrnddiscrete(const hqrndstate &state, const real_1d_array &x, const ae_int_t n) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { double result = alglib_impl::hqrnddiscrete(const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), const_cast<alglib_impl::ae_vector*>(x.c_ptr()), n, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<double*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This function generates random number from continuous distribution given by finite sample X. INPUT PARAMETERS State - high quality random number generator, must be initialized with HQRNDRandomize() or HQRNDSeed(). X - finite sample, array[N] (can be larger, in this case only leading N elements are used). THIS ARRAY MUST BE SORTED BY ASCENDING. N - number of elements to use, N>=1 RESULT this function returns random number from continuous distribution which tries to approximate X as mush as possible. min(X)<=Result<=max(X). -- ALGLIB -- Copyright 08.11.2011 by Bochkanov Sergey *************************************************************************/ double hqrndcontinuous(const hqrndstate &state, const real_1d_array &x, const ae_int_t n) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { double result = alglib_impl::hqrndcontinuous(const_cast<alglib_impl::hqrndstate*>(state.c_ptr()), const_cast<alglib_impl::ae_vector*>(x.c_ptr()), n, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<double*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* *************************************************************************/ _kdtree_owner::_kdtree_owner() { p_struct = (alglib_impl::kdtree*)alglib_impl::ae_malloc(sizeof(alglib_impl::kdtree), NULL); if( p_struct==NULL ) throw ap_error("ALGLIB: malloc error"); if( !alglib_impl::_kdtree_init(p_struct, NULL, ae_false) ) throw ap_error("ALGLIB: malloc error"); } _kdtree_owner::_kdtree_owner(const _kdtree_owner &rhs) { p_struct = (alglib_impl::kdtree*)alglib_impl::ae_malloc(sizeof(alglib_impl::kdtree), NULL); if( p_struct==NULL ) throw ap_error("ALGLIB: malloc error"); if( !alglib_impl::_kdtree_init_copy(p_struct, const_cast<alglib_impl::kdtree*>(rhs.p_struct), NULL, ae_false) ) throw ap_error("ALGLIB: malloc error"); } _kdtree_owner& _kdtree_owner::operator=(const _kdtree_owner &rhs) { if( this==&rhs ) return *this; alglib_impl::_kdtree_clear(p_struct); if( !alglib_impl::_kdtree_init_copy(p_struct, const_cast<alglib_impl::kdtree*>(rhs.p_struct), NULL, ae_false) ) throw ap_error("ALGLIB: malloc error"); return *this; } _kdtree_owner::~_kdtree_owner() { alglib_impl::_kdtree_clear(p_struct); ae_free(p_struct); } alglib_impl::kdtree* _kdtree_owner::c_ptr() { return p_struct; } alglib_impl::kdtree* _kdtree_owner::c_ptr() const { return const_cast<alglib_impl::kdtree*>(p_struct); } kdtree::kdtree() : _kdtree_owner() { } kdtree::kdtree(const kdtree &rhs):_kdtree_owner(rhs) { } kdtree& kdtree::operator=(const kdtree &rhs) { if( this==&rhs ) return *this; _kdtree_owner::operator=(rhs); return *this; } kdtree::~kdtree() { } /************************************************************************* This function serializes data structure to string. Important properties of s_out: * it contains alphanumeric characters, dots, underscores, minus signs * these symbols are grouped into words, which are separated by spaces and Windows-style (CR+LF) newlines * although serializer uses spaces and CR+LF as separators, you can replace any separator character by arbitrary combination of spaces, tabs, Windows or Unix newlines. It allows flexible reformatting of the string in case you want to include it into text or XML file. But you should not insert separators into the middle of the "words" nor you should change case of letters. * s_out can be freely moved between 32-bit and 64-bit systems, little and big endian machines, and so on. You can serialize structure on 32-bit machine and unserialize it on 64-bit one (or vice versa), or serialize it on SPARC and unserialize on x86. You can also serialize it in C++ version of ALGLIB and unserialize in C# one, and vice versa. *************************************************************************/ void kdtreeserialize(kdtree &obj, std::string &s_out) { alglib_impl::ae_state state; alglib_impl::ae_serializer serializer; alglib_impl::ae_int_t ssize; alglib_impl::ae_state_init(&state); try { alglib_impl::ae_serializer_init(&serializer); alglib_impl::ae_serializer_alloc_start(&serializer); alglib_impl::kdtreealloc(&serializer, obj.c_ptr(), &state); ssize = alglib_impl::ae_serializer_get_alloc_size(&serializer); s_out.clear(); s_out.reserve((size_t)(ssize+1)); alglib_impl::ae_serializer_sstart_str(&serializer, &s_out); alglib_impl::kdtreeserialize(&serializer, obj.c_ptr(), &state); alglib_impl::ae_serializer_stop(&serializer); if( s_out.length()>(size_t)ssize ) throw ap_error("ALGLIB: serialization integrity error"); alglib_impl::ae_serializer_clear(&serializer); alglib_impl::ae_state_clear(&state); } catch(alglib_impl::ae_error_type) { throw ap_error(state.error_msg); } } /************************************************************************* This function unserializes data structure from string. *************************************************************************/ void kdtreeunserialize(std::string &s_in, kdtree &obj) { alglib_impl::ae_state state; alglib_impl::ae_serializer serializer; alglib_impl::ae_state_init(&state); try { alglib_impl::ae_serializer_init(&serializer); alglib_impl::ae_serializer_ustart_str(&serializer, &s_in); alglib_impl::kdtreeunserialize(&serializer, obj.c_ptr(), &state); alglib_impl::ae_serializer_stop(&serializer); alglib_impl::ae_serializer_clear(&serializer); alglib_impl::ae_state_clear(&state); } catch(alglib_impl::ae_error_type) { throw ap_error(state.error_msg); } } /************************************************************************* KD-tree creation This subroutine creates KD-tree from set of X-values and optional Y-values INPUT PARAMETERS XY - dataset, array[0..N-1,0..NX+NY-1]. one row corresponds to one point. first NX columns contain X-values, next NY (NY may be zero) columns may contain associated Y-values N - number of points, N>=0. NX - space dimension, NX>=1. NY - number of optional Y-values, NY>=0. NormType- norm type: * 0 denotes infinity-norm * 1 denotes 1-norm * 2 denotes 2-norm (Euclidean norm) OUTPUT PARAMETERS KDT - KD-tree NOTES 1. KD-tree creation have O(N*logN) complexity and O(N*(2*NX+NY)) memory requirements. 2. Although KD-trees may be used with any combination of N and NX, they are more efficient than brute-force search only when N >> 4^NX. So they are most useful in low-dimensional tasks (NX=2, NX=3). NX=1 is another inefficient case, because simple binary search (without additional structures) is much more efficient in such tasks than KD-trees. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreebuild(const real_2d_array &xy, const ae_int_t n, const ae_int_t nx, const ae_int_t ny, const ae_int_t normtype, kdtree &kdt) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreebuild(const_cast<alglib_impl::ae_matrix*>(xy.c_ptr()), n, nx, ny, normtype, const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* KD-tree creation This subroutine creates KD-tree from set of X-values and optional Y-values INPUT PARAMETERS XY - dataset, array[0..N-1,0..NX+NY-1]. one row corresponds to one point. first NX columns contain X-values, next NY (NY may be zero) columns may contain associated Y-values N - number of points, N>=0. NX - space dimension, NX>=1. NY - number of optional Y-values, NY>=0. NormType- norm type: * 0 denotes infinity-norm * 1 denotes 1-norm * 2 denotes 2-norm (Euclidean norm) OUTPUT PARAMETERS KDT - KD-tree NOTES 1. KD-tree creation have O(N*logN) complexity and O(N*(2*NX+NY)) memory requirements. 2. Although KD-trees may be used with any combination of N and NX, they are more efficient than brute-force search only when N >> 4^NX. So they are most useful in low-dimensional tasks (NX=2, NX=3). NX=1 is another inefficient case, because simple binary search (without additional structures) is much more efficient in such tasks than KD-trees. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreebuild(const real_2d_array &xy, const ae_int_t nx, const ae_int_t ny, const ae_int_t normtype, kdtree &kdt) { alglib_impl::ae_state _alglib_env_state; ae_int_t n; n = xy.rows(); alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreebuild(const_cast<alglib_impl::ae_matrix*>(xy.c_ptr()), n, nx, ny, normtype, const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* KD-tree creation This subroutine creates KD-tree from set of X-values, integer tags and optional Y-values INPUT PARAMETERS XY - dataset, array[0..N-1,0..NX+NY-1]. one row corresponds to one point. first NX columns contain X-values, next NY (NY may be zero) columns may contain associated Y-values Tags - tags, array[0..N-1], contains integer tags associated with points. N - number of points, N>=0 NX - space dimension, NX>=1. NY - number of optional Y-values, NY>=0. NormType- norm type: * 0 denotes infinity-norm * 1 denotes 1-norm * 2 denotes 2-norm (Euclidean norm) OUTPUT PARAMETERS KDT - KD-tree NOTES 1. KD-tree creation have O(N*logN) complexity and O(N*(2*NX+NY)) memory requirements. 2. Although KD-trees may be used with any combination of N and NX, they are more efficient than brute-force search only when N >> 4^NX. So they are most useful in low-dimensional tasks (NX=2, NX=3). NX=1 is another inefficient case, because simple binary search (without additional structures) is much more efficient in such tasks than KD-trees. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreebuildtagged(const real_2d_array &xy, const integer_1d_array &tags, const ae_int_t n, const ae_int_t nx, const ae_int_t ny, const ae_int_t normtype, kdtree &kdt) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreebuildtagged(const_cast<alglib_impl::ae_matrix*>(xy.c_ptr()), const_cast<alglib_impl::ae_vector*>(tags.c_ptr()), n, nx, ny, normtype, const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* KD-tree creation This subroutine creates KD-tree from set of X-values, integer tags and optional Y-values INPUT PARAMETERS XY - dataset, array[0..N-1,0..NX+NY-1]. one row corresponds to one point. first NX columns contain X-values, next NY (NY may be zero) columns may contain associated Y-values Tags - tags, array[0..N-1], contains integer tags associated with points. N - number of points, N>=0 NX - space dimension, NX>=1. NY - number of optional Y-values, NY>=0. NormType- norm type: * 0 denotes infinity-norm * 1 denotes 1-norm * 2 denotes 2-norm (Euclidean norm) OUTPUT PARAMETERS KDT - KD-tree NOTES 1. KD-tree creation have O(N*logN) complexity and O(N*(2*NX+NY)) memory requirements. 2. Although KD-trees may be used with any combination of N and NX, they are more efficient than brute-force search only when N >> 4^NX. So they are most useful in low-dimensional tasks (NX=2, NX=3). NX=1 is another inefficient case, because simple binary search (without additional structures) is much more efficient in such tasks than KD-trees. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreebuildtagged(const real_2d_array &xy, const integer_1d_array &tags, const ae_int_t nx, const ae_int_t ny, const ae_int_t normtype, kdtree &kdt) { alglib_impl::ae_state _alglib_env_state; ae_int_t n; if( (xy.rows()!=tags.length())) throw ap_error("Error while calling 'kdtreebuildtagged': looks like one of arguments has wrong size"); n = xy.rows(); alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreebuildtagged(const_cast<alglib_impl::ae_matrix*>(xy.c_ptr()), const_cast<alglib_impl::ae_vector*>(tags.c_ptr()), n, nx, ny, normtype, const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* K-NN query: K nearest neighbors INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. K - number of neighbors to return, K>=1 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True RESULT number of actual neighbors found (either K or N, if K>N). This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain these results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryknn(const kdtree &kdt, const real_1d_array &x, const ae_int_t k, const bool selfmatch) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::kdtreequeryknn(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(x.c_ptr()), k, selfmatch, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* K-NN query: K nearest neighbors INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. K - number of neighbors to return, K>=1 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True RESULT number of actual neighbors found (either K or N, if K>N). This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain these results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryknn(const kdtree &kdt, const real_1d_array &x, const ae_int_t k) { alglib_impl::ae_state _alglib_env_state; bool selfmatch; selfmatch = true; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::kdtreequeryknn(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(x.c_ptr()), k, selfmatch, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* R-NN query: all points within R-sphere centered at X INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. R - radius of sphere (in corresponding norm), R>0 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True RESULT number of neighbors found, >=0 This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain actual results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryrnn(const kdtree &kdt, const real_1d_array &x, const double r, const bool selfmatch) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::kdtreequeryrnn(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(x.c_ptr()), r, selfmatch, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* R-NN query: all points within R-sphere centered at X INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. R - radius of sphere (in corresponding norm), R>0 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True RESULT number of neighbors found, >=0 This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain actual results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryrnn(const kdtree &kdt, const real_1d_array &x, const double r) { alglib_impl::ae_state _alglib_env_state; bool selfmatch; selfmatch = true; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::kdtreequeryrnn(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(x.c_ptr()), r, selfmatch, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* K-NN query: approximate K nearest neighbors INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. K - number of neighbors to return, K>=1 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True Eps - approximation factor, Eps>=0. eps-approximate nearest neighbor is a neighbor whose distance from X is at most (1+eps) times distance of true nearest neighbor. RESULT number of actual neighbors found (either K or N, if K>N). NOTES significant performance gain may be achieved only when Eps is is on the order of magnitude of 1 or larger. This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain these results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryaknn(const kdtree &kdt, const real_1d_array &x, const ae_int_t k, const bool selfmatch, const double eps) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::kdtreequeryaknn(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(x.c_ptr()), k, selfmatch, eps, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* K-NN query: approximate K nearest neighbors INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. K - number of neighbors to return, K>=1 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True Eps - approximation factor, Eps>=0. eps-approximate nearest neighbor is a neighbor whose distance from X is at most (1+eps) times distance of true nearest neighbor. RESULT number of actual neighbors found (either K or N, if K>N). NOTES significant performance gain may be achieved only when Eps is is on the order of magnitude of 1 or larger. This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain these results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryaknn(const kdtree &kdt, const real_1d_array &x, const ae_int_t k, const double eps) { alglib_impl::ae_state _alglib_env_state; bool selfmatch; selfmatch = true; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::kdtreequeryaknn(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(x.c_ptr()), k, selfmatch, eps, &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* X-values from last query INPUT PARAMETERS KDT - KD-tree X - possibly pre-allocated buffer. If X is too small to store result, it is resized. If size(X) is enough to store result, it is left unchanged. OUTPUT PARAMETERS X - rows are filled with X-values NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsXY() X- and Y-values * KDTreeQueryResultsTags() tag values * KDTreeQueryResultsDistances() distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsx(const kdtree &kdt, real_2d_array &x) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreequeryresultsx(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_matrix*>(x.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* X- and Y-values from last query INPUT PARAMETERS KDT - KD-tree XY - possibly pre-allocated buffer. If XY is too small to store result, it is resized. If size(XY) is enough to store result, it is left unchanged. OUTPUT PARAMETERS XY - rows are filled with points: first NX columns with X-values, next NY columns - with Y-values. NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsX() X-values * KDTreeQueryResultsTags() tag values * KDTreeQueryResultsDistances() distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsxy(const kdtree &kdt, real_2d_array &xy) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreequeryresultsxy(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_matrix*>(xy.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* Tags from last query INPUT PARAMETERS KDT - KD-tree Tags - possibly pre-allocated buffer. If X is too small to store result, it is resized. If size(X) is enough to store result, it is left unchanged. OUTPUT PARAMETERS Tags - filled with tags associated with points, or, when no tags were supplied, with zeros NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsX() X-values * KDTreeQueryResultsXY() X- and Y-values * KDTreeQueryResultsDistances() distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultstags(const kdtree &kdt, integer_1d_array &tags) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreequeryresultstags(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(tags.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* Distances from last query INPUT PARAMETERS KDT - KD-tree R - possibly pre-allocated buffer. If X is too small to store result, it is resized. If size(X) is enough to store result, it is left unchanged. OUTPUT PARAMETERS R - filled with distances (in corresponding norm) NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsX() X-values * KDTreeQueryResultsXY() X- and Y-values * KDTreeQueryResultsTags() tag values -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsdistances(const kdtree &kdt, real_1d_array &r) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreequeryresultsdistances(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(r.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* X-values from last query; 'interactive' variant for languages like Python which support constructs like "X = KDTreeQueryResultsXI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsxi(const kdtree &kdt, real_2d_array &x) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreequeryresultsxi(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_matrix*>(x.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* XY-values from last query; 'interactive' variant for languages like Python which support constructs like "XY = KDTreeQueryResultsXYI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsxyi(const kdtree &kdt, real_2d_array &xy) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreequeryresultsxyi(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_matrix*>(xy.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* Tags from last query; 'interactive' variant for languages like Python which support constructs like "Tags = KDTreeQueryResultsTagsI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultstagsi(const kdtree &kdt, integer_1d_array &tags) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreequeryresultstagsi(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(tags.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* Distances from last query; 'interactive' variant for languages like Python which support constructs like "R = KDTreeQueryResultsDistancesI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsdistancesi(const kdtree &kdt, real_1d_array &r) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::kdtreequeryresultsdistancesi(const_cast<alglib_impl::kdtree*>(kdt.c_ptr()), const_cast<alglib_impl::ae_vector*>(r.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Counts number of True values in the boolean 1D array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugb1count(const boolean_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::xdebugb1count(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by NOT(a[i]). Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb1not(const boolean_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugb1not(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb1appendcopy(boolean_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugb1appendcopy(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered elements set to True. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb1outeven(const ae_int_t n, boolean_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugb1outeven(n, const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugi1sum(const integer_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::xdebugi1sum(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -A[I] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi1neg(const integer_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugi1neg(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi1appendcopy(integer_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugi1appendcopy(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered A[I] set to I, and odd-numbered ones set to 0. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi1outeven(const ae_int_t n, integer_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugi1outeven(n, const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ double xdebugr1sum(const real_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { double result = alglib_impl::xdebugr1sum(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<double*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -A[I] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr1neg(const real_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugr1neg(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr1appendcopy(real_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugr1appendcopy(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered A[I] set to I*0.25, and odd-numbered ones are set to 0. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr1outeven(const ae_int_t n, real_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugr1outeven(n, const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ alglib::complex xdebugc1sum(const complex_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_complex result = alglib_impl::xdebugc1sum(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<alglib::complex*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -A[I] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc1neg(const complex_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugc1neg(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc1appendcopy(complex_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugc1appendcopy(const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered A[K] set to (x,y) = (K*0.25, K*0.125) and odd-numbered ones are set to 0. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc1outeven(const ae_int_t n, complex_1d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugc1outeven(n, const_cast<alglib_impl::ae_vector*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Counts number of True values in the boolean 2D array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugb2count(const boolean_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::xdebugb2count(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by NOT(a[i]). Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb2not(const boolean_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugb2not(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb2transpose(boolean_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugb2transpose(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sin(3*I+5*J)>0" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb2outsin(const ae_int_t m, const ae_int_t n, boolean_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugb2outsin(m, n, const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugi2sum(const integer_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_int_t result = alglib_impl::xdebugi2sum(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<ae_int_t*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -a[i,j] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi2neg(const integer_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugi2neg(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi2transpose(integer_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugi2transpose(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sign(Sin(3*I+5*J))" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi2outsin(const ae_int_t m, const ae_int_t n, integer_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugi2outsin(m, n, const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ double xdebugr2sum(const real_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { double result = alglib_impl::xdebugr2sum(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<double*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -a[i,j] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr2neg(const real_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugr2neg(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr2transpose(real_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugr2transpose(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sin(3*I+5*J)" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr2outsin(const ae_int_t m, const ae_int_t n, real_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugr2outsin(m, n, const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ alglib::complex xdebugc2sum(const complex_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::ae_complex result = alglib_impl::xdebugc2sum(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<alglib::complex*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -a[i,j] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc2neg(const complex_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugc2neg(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc2transpose(complex_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugc2transpose(const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sin(3*I+5*J),Cos(3*I+5*J)" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc2outsincos(const ae_int_t m, const ae_int_t n, complex_2d_array &a) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { alglib_impl::xdebugc2outsincos(m, n, const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return; } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of a[i,j]*(1+b[i,j]) such that c[i,j] is True -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ double xdebugmaskedbiasedproductsum(const ae_int_t m, const ae_int_t n, const real_2d_array &a, const real_2d_array &b, const boolean_2d_array &c) { alglib_impl::ae_state _alglib_env_state; alglib_impl::ae_state_init(&_alglib_env_state); try { double result = alglib_impl::xdebugmaskedbiasedproductsum(m, n, const_cast<alglib_impl::ae_matrix*>(a.c_ptr()), const_cast<alglib_impl::ae_matrix*>(b.c_ptr()), const_cast<alglib_impl::ae_matrix*>(c.c_ptr()), &_alglib_env_state); alglib_impl::ae_state_clear(&_alglib_env_state); return *(reinterpret_cast<double*>(&result)); } catch(alglib_impl::ae_error_type) { throw ap_error(_alglib_env_state.error_msg); } } } ///////////////////////////////////////////////////////////////////////// // // THIS SECTION CONTAINS IMPLEMENTATION OF COMPUTATIONAL CORE // ///////////////////////////////////////////////////////////////////////// namespace alglib_impl { static ae_int_t hqrnd_hqrndmax = 2147483561; static ae_int_t hqrnd_hqrndm1 = 2147483563; static ae_int_t hqrnd_hqrndm2 = 2147483399; static ae_int_t hqrnd_hqrndmagic = 1634357784; static ae_int_t hqrnd_hqrndintegerbase(hqrndstate* state, ae_state *_state); static ae_int_t nearestneighbor_splitnodesize = 6; static ae_int_t nearestneighbor_kdtreefirstversion = 0; static void nearestneighbor_kdtreesplit(kdtree* kdt, ae_int_t i1, ae_int_t i2, ae_int_t d, double s, ae_int_t* i3, ae_state *_state); static void nearestneighbor_kdtreegeneratetreerec(kdtree* kdt, ae_int_t* nodesoffs, ae_int_t* splitsoffs, ae_int_t i1, ae_int_t i2, ae_int_t maxleafsize, ae_state *_state); static void nearestneighbor_kdtreequerynnrec(kdtree* kdt, ae_int_t offs, ae_state *_state); static void nearestneighbor_kdtreeinitbox(kdtree* kdt, /* Real */ ae_vector* x, ae_state *_state); static void nearestneighbor_kdtreeallocdatasetindependent(kdtree* kdt, ae_int_t nx, ae_int_t ny, ae_state *_state); static void nearestneighbor_kdtreeallocdatasetdependent(kdtree* kdt, ae_int_t n, ae_int_t nx, ae_int_t ny, ae_state *_state); static void nearestneighbor_kdtreealloctemporaries(kdtree* kdt, ae_int_t n, ae_int_t nx, ae_int_t ny, ae_state *_state); /************************************************************************* HQRNDState initialization with random values which come from standard RNG. -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndrandomize(hqrndstate* state, ae_state *_state) { ae_int_t s0; ae_int_t s1; _hqrndstate_clear(state); s0 = ae_randominteger(hqrnd_hqrndm1, _state); s1 = ae_randominteger(hqrnd_hqrndm2, _state); hqrndseed(s0, s1, state, _state); } /************************************************************************* HQRNDState initialization with seed values -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndseed(ae_int_t s1, ae_int_t s2, hqrndstate* state, ae_state *_state) { _hqrndstate_clear(state); /* * Protection against negative seeds: * * SEED := -(SEED+1) * * We can use just "-SEED" because there exists such integer number N * that N<0, -N=N<0 too. (This number is equal to 0x800...000). Need * to handle such seed correctly forces us to use a bit complicated * formula. */ if( s1<0 ) { s1 = -(s1+1); } if( s2<0 ) { s2 = -(s2+1); } state->s1 = s1%(hqrnd_hqrndm1-1)+1; state->s2 = s2%(hqrnd_hqrndm2-1)+1; state->magicv = hqrnd_hqrndmagic; } /************************************************************************* This function generates random real number in (0,1), not including interval boundaries State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ double hqrnduniformr(hqrndstate* state, ae_state *_state) { double result; result = (double)(hqrnd_hqrndintegerbase(state, _state)+1)/(double)(hqrnd_hqrndmax+2); return result; } /************************************************************************* This function generates random integer number in [0, N) 1. State structure must be initialized with HQRNDRandomize() or HQRNDSeed() 2. N can be any positive number except for very large numbers: * close to 2^31 on 32-bit systems * close to 2^62 on 64-bit systems An exception will be generated if N is too large. -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ ae_int_t hqrnduniformi(hqrndstate* state, ae_int_t n, ae_state *_state) { ae_int_t maxcnt; ae_int_t mx; ae_int_t a; ae_int_t b; ae_int_t result; ae_assert(n>0, "HQRNDUniformI: N<=0!", _state); maxcnt = hqrnd_hqrndmax+1; /* * Two branches: one for N<=MaxCnt, another for N>MaxCnt. */ if( n>maxcnt ) { /* * N>=MaxCnt. * * We have two options here: * a) N is exactly divisible by MaxCnt * b) N is not divisible by MaxCnt * * In both cases we reduce problem on interval spanning [0,N) * to several subproblems on intervals spanning [0,MaxCnt). */ if( n%maxcnt==0 ) { /* * N is exactly divisible by MaxCnt. * * [0,N) range is dividided into N/MaxCnt bins, * each of them having length equal to MaxCnt. * * We generate: * * random bin number B * * random offset within bin A * Both random numbers are generated by recursively * calling HQRNDUniformI(). * * Result is equal to A+MaxCnt*B. */ ae_assert(n/maxcnt<=maxcnt, "HQRNDUniformI: N is too large", _state); a = hqrnduniformi(state, maxcnt, _state); b = hqrnduniformi(state, n/maxcnt, _state); result = a+maxcnt*b; } else { /* * N is NOT exactly divisible by MaxCnt. * * [0,N) range is dividided into Ceil(N/MaxCnt) bins, * each of them having length equal to MaxCnt. * * We generate: * * random bin number B in [0, Ceil(N/MaxCnt)-1] * * random offset within bin A * * if both of what is below is true * 1) bin number B is that of the last bin * 2) A >= N mod MaxCnt * then we repeat generation of A/B. * This stage is essential in order to avoid bias in the result. * * otherwise, we return A*MaxCnt+N */ ae_assert(n/maxcnt+1<=maxcnt, "HQRNDUniformI: N is too large", _state); result = -1; do { a = hqrnduniformi(state, maxcnt, _state); b = hqrnduniformi(state, n/maxcnt+1, _state); if( b==n/maxcnt&&a>=n%maxcnt ) { continue; } result = a+maxcnt*b; } while(result<0); } } else { /* * N<=MaxCnt * * Code below is a bit complicated because we can not simply * return "HQRNDIntegerBase() mod N" - it will be skewed for * large N's in [0.1*HQRNDMax...HQRNDMax]. */ mx = maxcnt-maxcnt%n; do { result = hqrnd_hqrndintegerbase(state, _state); } while(result>=mx); result = result%n; } return result; } /************************************************************************* Random number generator: normal numbers This function generates one random number from normal distribution. Its performance is equal to that of HQRNDNormal2() State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ double hqrndnormal(hqrndstate* state, ae_state *_state) { double v1; double v2; double result; hqrndnormal2(state, &v1, &v2, _state); result = v1; return result; } /************************************************************************* Random number generator: random X and Y such that X^2+Y^2=1 State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndunit2(hqrndstate* state, double* x, double* y, ae_state *_state) { double v; double mx; double mn; *x = 0; *y = 0; do { hqrndnormal2(state, x, y, _state); } while(!(ae_fp_neq(*x,0)||ae_fp_neq(*y,0))); mx = ae_maxreal(ae_fabs(*x, _state), ae_fabs(*y, _state), _state); mn = ae_minreal(ae_fabs(*x, _state), ae_fabs(*y, _state), _state); v = mx*ae_sqrt(1+ae_sqr(mn/mx, _state), _state); *x = *x/v; *y = *y/v; } /************************************************************************* Random number generator: normal numbers This function generates two independent random numbers from normal distribution. Its performance is equal to that of HQRNDNormal() State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 02.12.2009 by Bochkanov Sergey *************************************************************************/ void hqrndnormal2(hqrndstate* state, double* x1, double* x2, ae_state *_state) { double u; double v; double s; *x1 = 0; *x2 = 0; for(;;) { u = 2*hqrnduniformr(state, _state)-1; v = 2*hqrnduniformr(state, _state)-1; s = ae_sqr(u, _state)+ae_sqr(v, _state); if( ae_fp_greater(s,0)&&ae_fp_less(s,1) ) { /* * two Sqrt's instead of one to * avoid overflow when S is too small */ s = ae_sqrt(-2*ae_log(s, _state), _state)/ae_sqrt(s, _state); *x1 = u*s; *x2 = v*s; return; } } } /************************************************************************* Random number generator: exponential distribution State structure must be initialized with HQRNDRandomize() or HQRNDSeed(). -- ALGLIB -- Copyright 11.08.2007 by Bochkanov Sergey *************************************************************************/ double hqrndexponential(hqrndstate* state, double lambdav, ae_state *_state) { double result; ae_assert(ae_fp_greater(lambdav,0), "HQRNDExponential: LambdaV<=0!", _state); result = -ae_log(hqrnduniformr(state, _state), _state)/lambdav; return result; } /************************************************************************* This function generates random number from discrete distribution given by finite sample X. INPUT PARAMETERS State - high quality random number generator, must be initialized with HQRNDRandomize() or HQRNDSeed(). X - finite sample N - number of elements to use, N>=1 RESULT this function returns one of the X[i] for random i=0..N-1 -- ALGLIB -- Copyright 08.11.2011 by Bochkanov Sergey *************************************************************************/ double hqrnddiscrete(hqrndstate* state, /* Real */ ae_vector* x, ae_int_t n, ae_state *_state) { double result; ae_assert(n>0, "HQRNDDiscrete: N<=0", _state); ae_assert(n<=x->cnt, "HQRNDDiscrete: Length(X)<N", _state); result = x->ptr.p_double[hqrnduniformi(state, n, _state)]; return result; } /************************************************************************* This function generates random number from continuous distribution given by finite sample X. INPUT PARAMETERS State - high quality random number generator, must be initialized with HQRNDRandomize() or HQRNDSeed(). X - finite sample, array[N] (can be larger, in this case only leading N elements are used). THIS ARRAY MUST BE SORTED BY ASCENDING. N - number of elements to use, N>=1 RESULT this function returns random number from continuous distribution which tries to approximate X as mush as possible. min(X)<=Result<=max(X). -- ALGLIB -- Copyright 08.11.2011 by Bochkanov Sergey *************************************************************************/ double hqrndcontinuous(hqrndstate* state, /* Real */ ae_vector* x, ae_int_t n, ae_state *_state) { double mx; double mn; ae_int_t i; double result; ae_assert(n>0, "HQRNDContinuous: N<=0", _state); ae_assert(n<=x->cnt, "HQRNDContinuous: Length(X)<N", _state); if( n==1 ) { result = x->ptr.p_double[0]; return result; } i = hqrnduniformi(state, n-1, _state); mn = x->ptr.p_double[i]; mx = x->ptr.p_double[i+1]; ae_assert(ae_fp_greater_eq(mx,mn), "HQRNDDiscrete: X is not sorted by ascending", _state); if( ae_fp_neq(mx,mn) ) { result = (mx-mn)*hqrnduniformr(state, _state)+mn; } else { result = mn; } return result; } /************************************************************************* This function returns random integer in [0,HQRNDMax] L'Ecuyer, Efficient and portable combined random number generators *************************************************************************/ static ae_int_t hqrnd_hqrndintegerbase(hqrndstate* state, ae_state *_state) { ae_int_t k; ae_int_t result; ae_assert(state->magicv==hqrnd_hqrndmagic, "HQRNDIntegerBase: State is not correctly initialized!", _state); k = state->s1/53668; state->s1 = 40014*(state->s1-k*53668)-k*12211; if( state->s1<0 ) { state->s1 = state->s1+2147483563; } k = state->s2/52774; state->s2 = 40692*(state->s2-k*52774)-k*3791; if( state->s2<0 ) { state->s2 = state->s2+2147483399; } /* * Result */ result = state->s1-state->s2; if( result<1 ) { result = result+2147483562; } result = result-1; return result; } ae_bool _hqrndstate_init(void* _p, ae_state *_state, ae_bool make_automatic) { hqrndstate *p = (hqrndstate*)_p; ae_touch_ptr((void*)p); return ae_true; } ae_bool _hqrndstate_init_copy(void* _dst, void* _src, ae_state *_state, ae_bool make_automatic) { hqrndstate *dst = (hqrndstate*)_dst; hqrndstate *src = (hqrndstate*)_src; dst->s1 = src->s1; dst->s2 = src->s2; dst->magicv = src->magicv; return ae_true; } void _hqrndstate_clear(void* _p) { hqrndstate *p = (hqrndstate*)_p; ae_touch_ptr((void*)p); } void _hqrndstate_destroy(void* _p) { hqrndstate *p = (hqrndstate*)_p; ae_touch_ptr((void*)p); } /************************************************************************* KD-tree creation This subroutine creates KD-tree from set of X-values and optional Y-values INPUT PARAMETERS XY - dataset, array[0..N-1,0..NX+NY-1]. one row corresponds to one point. first NX columns contain X-values, next NY (NY may be zero) columns may contain associated Y-values N - number of points, N>=0. NX - space dimension, NX>=1. NY - number of optional Y-values, NY>=0. NormType- norm type: * 0 denotes infinity-norm * 1 denotes 1-norm * 2 denotes 2-norm (Euclidean norm) OUTPUT PARAMETERS KDT - KD-tree NOTES 1. KD-tree creation have O(N*logN) complexity and O(N*(2*NX+NY)) memory requirements. 2. Although KD-trees may be used with any combination of N and NX, they are more efficient than brute-force search only when N >> 4^NX. So they are most useful in low-dimensional tasks (NX=2, NX=3). NX=1 is another inefficient case, because simple binary search (without additional structures) is much more efficient in such tasks than KD-trees. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreebuild(/* Real */ ae_matrix* xy, ae_int_t n, ae_int_t nx, ae_int_t ny, ae_int_t normtype, kdtree* kdt, ae_state *_state) { ae_frame _frame_block; ae_vector tags; ae_int_t i; ae_frame_make(_state, &_frame_block); _kdtree_clear(kdt); ae_vector_init(&tags, 0, DT_INT, _state, ae_true); ae_assert(n>=0, "KDTreeBuild: N<0", _state); ae_assert(nx>=1, "KDTreeBuild: NX<1", _state); ae_assert(ny>=0, "KDTreeBuild: NY<0", _state); ae_assert(normtype>=0&&normtype<=2, "KDTreeBuild: incorrect NormType", _state); ae_assert(xy->rows>=n, "KDTreeBuild: rows(X)<N", _state); ae_assert(xy->cols>=nx+ny||n==0, "KDTreeBuild: cols(X)<NX+NY", _state); ae_assert(apservisfinitematrix(xy, n, nx+ny, _state), "KDTreeBuild: XY contains infinite or NaN values", _state); if( n>0 ) { ae_vector_set_length(&tags, n, _state); for(i=0; i<=n-1; i++) { tags.ptr.p_int[i] = 0; } } kdtreebuildtagged(xy, &tags, n, nx, ny, normtype, kdt, _state); ae_frame_leave(_state); } /************************************************************************* KD-tree creation This subroutine creates KD-tree from set of X-values, integer tags and optional Y-values INPUT PARAMETERS XY - dataset, array[0..N-1,0..NX+NY-1]. one row corresponds to one point. first NX columns contain X-values, next NY (NY may be zero) columns may contain associated Y-values Tags - tags, array[0..N-1], contains integer tags associated with points. N - number of points, N>=0 NX - space dimension, NX>=1. NY - number of optional Y-values, NY>=0. NormType- norm type: * 0 denotes infinity-norm * 1 denotes 1-norm * 2 denotes 2-norm (Euclidean norm) OUTPUT PARAMETERS KDT - KD-tree NOTES 1. KD-tree creation have O(N*logN) complexity and O(N*(2*NX+NY)) memory requirements. 2. Although KD-trees may be used with any combination of N and NX, they are more efficient than brute-force search only when N >> 4^NX. So they are most useful in low-dimensional tasks (NX=2, NX=3). NX=1 is another inefficient case, because simple binary search (without additional structures) is much more efficient in such tasks than KD-trees. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreebuildtagged(/* Real */ ae_matrix* xy, /* Integer */ ae_vector* tags, ae_int_t n, ae_int_t nx, ae_int_t ny, ae_int_t normtype, kdtree* kdt, ae_state *_state) { ae_int_t i; ae_int_t j; ae_int_t maxnodes; ae_int_t nodesoffs; ae_int_t splitsoffs; _kdtree_clear(kdt); ae_assert(n>=0, "KDTreeBuildTagged: N<0", _state); ae_assert(nx>=1, "KDTreeBuildTagged: NX<1", _state); ae_assert(ny>=0, "KDTreeBuildTagged: NY<0", _state); ae_assert(normtype>=0&&normtype<=2, "KDTreeBuildTagged: incorrect NormType", _state); ae_assert(xy->rows>=n, "KDTreeBuildTagged: rows(X)<N", _state); ae_assert(xy->cols>=nx+ny||n==0, "KDTreeBuildTagged: cols(X)<NX+NY", _state); ae_assert(apservisfinitematrix(xy, n, nx+ny, _state), "KDTreeBuildTagged: XY contains infinite or NaN values", _state); /* * initialize */ kdt->n = n; kdt->nx = nx; kdt->ny = ny; kdt->normtype = normtype; kdt->kcur = 0; /* * N=0 => quick exit */ if( n==0 ) { return; } /* * Allocate */ nearestneighbor_kdtreeallocdatasetindependent(kdt, nx, ny, _state); nearestneighbor_kdtreeallocdatasetdependent(kdt, n, nx, ny, _state); /* * Initial fill */ for(i=0; i<=n-1; i++) { ae_v_move(&kdt->xy.ptr.pp_double[i][0], 1, &xy->ptr.pp_double[i][0], 1, ae_v_len(0,nx-1)); ae_v_move(&kdt->xy.ptr.pp_double[i][nx], 1, &xy->ptr.pp_double[i][0], 1, ae_v_len(nx,2*nx+ny-1)); kdt->tags.ptr.p_int[i] = tags->ptr.p_int[i]; } /* * Determine bounding box */ ae_v_move(&kdt->boxmin.ptr.p_double[0], 1, &kdt->xy.ptr.pp_double[0][0], 1, ae_v_len(0,nx-1)); ae_v_move(&kdt->boxmax.ptr.p_double[0], 1, &kdt->xy.ptr.pp_double[0][0], 1, ae_v_len(0,nx-1)); for(i=1; i<=n-1; i++) { for(j=0; j<=nx-1; j++) { kdt->boxmin.ptr.p_double[j] = ae_minreal(kdt->boxmin.ptr.p_double[j], kdt->xy.ptr.pp_double[i][j], _state); kdt->boxmax.ptr.p_double[j] = ae_maxreal(kdt->boxmax.ptr.p_double[j], kdt->xy.ptr.pp_double[i][j], _state); } } /* * prepare tree structure * * MaxNodes=N because we guarantee no trivial splits, i.e. * every split will generate two non-empty boxes */ maxnodes = n; ae_vector_set_length(&kdt->nodes, nearestneighbor_splitnodesize*2*maxnodes, _state); ae_vector_set_length(&kdt->splits, 2*maxnodes, _state); nodesoffs = 0; splitsoffs = 0; ae_v_move(&kdt->curboxmin.ptr.p_double[0], 1, &kdt->boxmin.ptr.p_double[0], 1, ae_v_len(0,nx-1)); ae_v_move(&kdt->curboxmax.ptr.p_double[0], 1, &kdt->boxmax.ptr.p_double[0], 1, ae_v_len(0,nx-1)); nearestneighbor_kdtreegeneratetreerec(kdt, &nodesoffs, &splitsoffs, 0, n, 8, _state); } /************************************************************************* K-NN query: K nearest neighbors INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. K - number of neighbors to return, K>=1 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True RESULT number of actual neighbors found (either K or N, if K>N). This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain these results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryknn(kdtree* kdt, /* Real */ ae_vector* x, ae_int_t k, ae_bool selfmatch, ae_state *_state) { ae_int_t result; ae_assert(k>=1, "KDTreeQueryKNN: K<1!", _state); ae_assert(x->cnt>=kdt->nx, "KDTreeQueryKNN: Length(X)<NX!", _state); ae_assert(isfinitevector(x, kdt->nx, _state), "KDTreeQueryKNN: X contains infinite or NaN values!", _state); result = kdtreequeryaknn(kdt, x, k, selfmatch, 0.0, _state); return result; } /************************************************************************* R-NN query: all points within R-sphere centered at X INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. R - radius of sphere (in corresponding norm), R>0 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True RESULT number of neighbors found, >=0 This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain actual results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryrnn(kdtree* kdt, /* Real */ ae_vector* x, double r, ae_bool selfmatch, ae_state *_state) { ae_int_t i; ae_int_t j; ae_int_t result; ae_assert(ae_fp_greater(r,0), "KDTreeQueryRNN: incorrect R!", _state); ae_assert(x->cnt>=kdt->nx, "KDTreeQueryRNN: Length(X)<NX!", _state); ae_assert(isfinitevector(x, kdt->nx, _state), "KDTreeQueryRNN: X contains infinite or NaN values!", _state); /* * Handle special case: KDT.N=0 */ if( kdt->n==0 ) { kdt->kcur = 0; result = 0; return result; } /* * Prepare parameters */ kdt->kneeded = 0; if( kdt->normtype!=2 ) { kdt->rneeded = r; } else { kdt->rneeded = ae_sqr(r, _state); } kdt->selfmatch = selfmatch; kdt->approxf = 1; kdt->kcur = 0; /* * calculate distance from point to current bounding box */ nearestneighbor_kdtreeinitbox(kdt, x, _state); /* * call recursive search * results are returned as heap */ nearestneighbor_kdtreequerynnrec(kdt, 0, _state); /* * pop from heap to generate ordered representation * * last element is not pop'ed because it is already in * its place */ result = kdt->kcur; j = kdt->kcur; for(i=kdt->kcur; i>=2; i--) { tagheappopi(&kdt->r, &kdt->idx, &j, _state); } return result; } /************************************************************************* K-NN query: approximate K nearest neighbors INPUT PARAMETERS KDT - KD-tree X - point, array[0..NX-1]. K - number of neighbors to return, K>=1 SelfMatch - whether self-matches are allowed: * if True, nearest neighbor may be the point itself (if it exists in original dataset) * if False, then only points with non-zero distance are returned * if not given, considered True Eps - approximation factor, Eps>=0. eps-approximate nearest neighbor is a neighbor whose distance from X is at most (1+eps) times distance of true nearest neighbor. RESULT number of actual neighbors found (either K or N, if K>N). NOTES significant performance gain may be achieved only when Eps is is on the order of magnitude of 1 or larger. This subroutine performs query and stores its result in the internal structures of the KD-tree. You can use following subroutines to obtain these results: * KDTreeQueryResultsX() to get X-values * KDTreeQueryResultsXY() to get X- and Y-values * KDTreeQueryResultsTags() to get tag values * KDTreeQueryResultsDistances() to get distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ ae_int_t kdtreequeryaknn(kdtree* kdt, /* Real */ ae_vector* x, ae_int_t k, ae_bool selfmatch, double eps, ae_state *_state) { ae_int_t i; ae_int_t j; ae_int_t result; ae_assert(k>0, "KDTreeQueryAKNN: incorrect K!", _state); ae_assert(ae_fp_greater_eq(eps,0), "KDTreeQueryAKNN: incorrect Eps!", _state); ae_assert(x->cnt>=kdt->nx, "KDTreeQueryAKNN: Length(X)<NX!", _state); ae_assert(isfinitevector(x, kdt->nx, _state), "KDTreeQueryAKNN: X contains infinite or NaN values!", _state); /* * Handle special case: KDT.N=0 */ if( kdt->n==0 ) { kdt->kcur = 0; result = 0; return result; } /* * Prepare parameters */ k = ae_minint(k, kdt->n, _state); kdt->kneeded = k; kdt->rneeded = 0; kdt->selfmatch = selfmatch; if( kdt->normtype==2 ) { kdt->approxf = 1/ae_sqr(1+eps, _state); } else { kdt->approxf = 1/(1+eps); } kdt->kcur = 0; /* * calculate distance from point to current bounding box */ nearestneighbor_kdtreeinitbox(kdt, x, _state); /* * call recursive search * results are returned as heap */ nearestneighbor_kdtreequerynnrec(kdt, 0, _state); /* * pop from heap to generate ordered representation * * last element is non pop'ed because it is already in * its place */ result = kdt->kcur; j = kdt->kcur; for(i=kdt->kcur; i>=2; i--) { tagheappopi(&kdt->r, &kdt->idx, &j, _state); } return result; } /************************************************************************* X-values from last query INPUT PARAMETERS KDT - KD-tree X - possibly pre-allocated buffer. If X is too small to store result, it is resized. If size(X) is enough to store result, it is left unchanged. OUTPUT PARAMETERS X - rows are filled with X-values NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsXY() X- and Y-values * KDTreeQueryResultsTags() tag values * KDTreeQueryResultsDistances() distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsx(kdtree* kdt, /* Real */ ae_matrix* x, ae_state *_state) { ae_int_t i; ae_int_t k; if( kdt->kcur==0 ) { return; } if( x->rows<kdt->kcur||x->cols<kdt->nx ) { ae_matrix_set_length(x, kdt->kcur, kdt->nx, _state); } k = kdt->kcur; for(i=0; i<=k-1; i++) { ae_v_move(&x->ptr.pp_double[i][0], 1, &kdt->xy.ptr.pp_double[kdt->idx.ptr.p_int[i]][kdt->nx], 1, ae_v_len(0,kdt->nx-1)); } } /************************************************************************* X- and Y-values from last query INPUT PARAMETERS KDT - KD-tree XY - possibly pre-allocated buffer. If XY is too small to store result, it is resized. If size(XY) is enough to store result, it is left unchanged. OUTPUT PARAMETERS XY - rows are filled with points: first NX columns with X-values, next NY columns - with Y-values. NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsX() X-values * KDTreeQueryResultsTags() tag values * KDTreeQueryResultsDistances() distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsxy(kdtree* kdt, /* Real */ ae_matrix* xy, ae_state *_state) { ae_int_t i; ae_int_t k; if( kdt->kcur==0 ) { return; } if( xy->rows<kdt->kcur||xy->cols<kdt->nx+kdt->ny ) { ae_matrix_set_length(xy, kdt->kcur, kdt->nx+kdt->ny, _state); } k = kdt->kcur; for(i=0; i<=k-1; i++) { ae_v_move(&xy->ptr.pp_double[i][0], 1, &kdt->xy.ptr.pp_double[kdt->idx.ptr.p_int[i]][kdt->nx], 1, ae_v_len(0,kdt->nx+kdt->ny-1)); } } /************************************************************************* Tags from last query INPUT PARAMETERS KDT - KD-tree Tags - possibly pre-allocated buffer. If X is too small to store result, it is resized. If size(X) is enough to store result, it is left unchanged. OUTPUT PARAMETERS Tags - filled with tags associated with points, or, when no tags were supplied, with zeros NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsX() X-values * KDTreeQueryResultsXY() X- and Y-values * KDTreeQueryResultsDistances() distances -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultstags(kdtree* kdt, /* Integer */ ae_vector* tags, ae_state *_state) { ae_int_t i; ae_int_t k; if( kdt->kcur==0 ) { return; } if( tags->cnt<kdt->kcur ) { ae_vector_set_length(tags, kdt->kcur, _state); } k = kdt->kcur; for(i=0; i<=k-1; i++) { tags->ptr.p_int[i] = kdt->tags.ptr.p_int[kdt->idx.ptr.p_int[i]]; } } /************************************************************************* Distances from last query INPUT PARAMETERS KDT - KD-tree R - possibly pre-allocated buffer. If X is too small to store result, it is resized. If size(X) is enough to store result, it is left unchanged. OUTPUT PARAMETERS R - filled with distances (in corresponding norm) NOTES 1. points are ordered by distance from the query point (first = closest) 2. if XY is larger than required to store result, only leading part will be overwritten; trailing part will be left unchanged. So if on input XY = [[A,B],[C,D]], and result is [1,2], then on exit we will get XY = [[1,2],[C,D]]. This is done purposely to increase performance; if you want function to resize array according to result size, use function with same name and suffix 'I'. SEE ALSO * KDTreeQueryResultsX() X-values * KDTreeQueryResultsXY() X- and Y-values * KDTreeQueryResultsTags() tag values -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsdistances(kdtree* kdt, /* Real */ ae_vector* r, ae_state *_state) { ae_int_t i; ae_int_t k; if( kdt->kcur==0 ) { return; } if( r->cnt<kdt->kcur ) { ae_vector_set_length(r, kdt->kcur, _state); } k = kdt->kcur; /* * unload norms * * Abs() call is used to handle cases with negative norms * (generated during KFN requests) */ if( kdt->normtype==0 ) { for(i=0; i<=k-1; i++) { r->ptr.p_double[i] = ae_fabs(kdt->r.ptr.p_double[i], _state); } } if( kdt->normtype==1 ) { for(i=0; i<=k-1; i++) { r->ptr.p_double[i] = ae_fabs(kdt->r.ptr.p_double[i], _state); } } if( kdt->normtype==2 ) { for(i=0; i<=k-1; i++) { r->ptr.p_double[i] = ae_sqrt(ae_fabs(kdt->r.ptr.p_double[i], _state), _state); } } } /************************************************************************* X-values from last query; 'interactive' variant for languages like Python which support constructs like "X = KDTreeQueryResultsXI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsxi(kdtree* kdt, /* Real */ ae_matrix* x, ae_state *_state) { ae_matrix_clear(x); kdtreequeryresultsx(kdt, x, _state); } /************************************************************************* XY-values from last query; 'interactive' variant for languages like Python which support constructs like "XY = KDTreeQueryResultsXYI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsxyi(kdtree* kdt, /* Real */ ae_matrix* xy, ae_state *_state) { ae_matrix_clear(xy); kdtreequeryresultsxy(kdt, xy, _state); } /************************************************************************* Tags from last query; 'interactive' variant for languages like Python which support constructs like "Tags = KDTreeQueryResultsTagsI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultstagsi(kdtree* kdt, /* Integer */ ae_vector* tags, ae_state *_state) { ae_vector_clear(tags); kdtreequeryresultstags(kdt, tags, _state); } /************************************************************************* Distances from last query; 'interactive' variant for languages like Python which support constructs like "R = KDTreeQueryResultsDistancesI(KDT)" and interactive mode of interpreter. This function allocates new array on each call, so it is significantly slower than its 'non-interactive' counterpart, but it is more convenient when you call it from command line. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ void kdtreequeryresultsdistancesi(kdtree* kdt, /* Real */ ae_vector* r, ae_state *_state) { ae_vector_clear(r); kdtreequeryresultsdistances(kdt, r, _state); } /************************************************************************* Serializer: allocation -- ALGLIB -- Copyright 14.03.2011 by Bochkanov Sergey *************************************************************************/ void kdtreealloc(ae_serializer* s, kdtree* tree, ae_state *_state) { /* * Header */ ae_serializer_alloc_entry(s); ae_serializer_alloc_entry(s); /* * Data */ ae_serializer_alloc_entry(s); ae_serializer_alloc_entry(s); ae_serializer_alloc_entry(s); ae_serializer_alloc_entry(s); allocrealmatrix(s, &tree->xy, -1, -1, _state); allocintegerarray(s, &tree->tags, -1, _state); allocrealarray(s, &tree->boxmin, -1, _state); allocrealarray(s, &tree->boxmax, -1, _state); allocintegerarray(s, &tree->nodes, -1, _state); allocrealarray(s, &tree->splits, -1, _state); } /************************************************************************* Serializer: serialization -- ALGLIB -- Copyright 14.03.2011 by Bochkanov Sergey *************************************************************************/ void kdtreeserialize(ae_serializer* s, kdtree* tree, ae_state *_state) { /* * Header */ ae_serializer_serialize_int(s, getkdtreeserializationcode(_state), _state); ae_serializer_serialize_int(s, nearestneighbor_kdtreefirstversion, _state); /* * Data */ ae_serializer_serialize_int(s, tree->n, _state); ae_serializer_serialize_int(s, tree->nx, _state); ae_serializer_serialize_int(s, tree->ny, _state); ae_serializer_serialize_int(s, tree->normtype, _state); serializerealmatrix(s, &tree->xy, -1, -1, _state); serializeintegerarray(s, &tree->tags, -1, _state); serializerealarray(s, &tree->boxmin, -1, _state); serializerealarray(s, &tree->boxmax, -1, _state); serializeintegerarray(s, &tree->nodes, -1, _state); serializerealarray(s, &tree->splits, -1, _state); } /************************************************************************* Serializer: unserialization -- ALGLIB -- Copyright 14.03.2011 by Bochkanov Sergey *************************************************************************/ void kdtreeunserialize(ae_serializer* s, kdtree* tree, ae_state *_state) { ae_int_t i0; ae_int_t i1; _kdtree_clear(tree); /* * check correctness of header */ ae_serializer_unserialize_int(s, &i0, _state); ae_assert(i0==getkdtreeserializationcode(_state), "KDTreeUnserialize: stream header corrupted", _state); ae_serializer_unserialize_int(s, &i1, _state); ae_assert(i1==nearestneighbor_kdtreefirstversion, "KDTreeUnserialize: stream header corrupted", _state); /* * Unserialize data */ ae_serializer_unserialize_int(s, &tree->n, _state); ae_serializer_unserialize_int(s, &tree->nx, _state); ae_serializer_unserialize_int(s, &tree->ny, _state); ae_serializer_unserialize_int(s, &tree->normtype, _state); unserializerealmatrix(s, &tree->xy, _state); unserializeintegerarray(s, &tree->tags, _state); unserializerealarray(s, &tree->boxmin, _state); unserializerealarray(s, &tree->boxmax, _state); unserializeintegerarray(s, &tree->nodes, _state); unserializerealarray(s, &tree->splits, _state); nearestneighbor_kdtreealloctemporaries(tree, tree->n, tree->nx, tree->ny, _state); } /************************************************************************* Rearranges nodes [I1,I2) using partition in D-th dimension with S as threshold. Returns split position I3: [I1,I3) and [I3,I2) are created as result. This subroutine doesn't create tree structures, just rearranges nodes. *************************************************************************/ static void nearestneighbor_kdtreesplit(kdtree* kdt, ae_int_t i1, ae_int_t i2, ae_int_t d, double s, ae_int_t* i3, ae_state *_state) { ae_int_t i; ae_int_t j; ae_int_t ileft; ae_int_t iright; double v; *i3 = 0; ae_assert(kdt->n>0, "KDTreeSplit: internal error", _state); /* * split XY/Tags in two parts: * * [ILeft,IRight] is non-processed part of XY/Tags * * After cycle is done, we have Ileft=IRight. We deal with * this element separately. * * After this, [I1,ILeft) contains left part, and [ILeft,I2) * contains right part. */ ileft = i1; iright = i2-1; while(ileft<iright) { if( ae_fp_less_eq(kdt->xy.ptr.pp_double[ileft][d],s) ) { /* * XY[ILeft] is on its place. * Advance ILeft. */ ileft = ileft+1; } else { /* * XY[ILeft,..] must be at IRight. * Swap and advance IRight. */ for(i=0; i<=2*kdt->nx+kdt->ny-1; i++) { v = kdt->xy.ptr.pp_double[ileft][i]; kdt->xy.ptr.pp_double[ileft][i] = kdt->xy.ptr.pp_double[iright][i]; kdt->xy.ptr.pp_double[iright][i] = v; } j = kdt->tags.ptr.p_int[ileft]; kdt->tags.ptr.p_int[ileft] = kdt->tags.ptr.p_int[iright]; kdt->tags.ptr.p_int[iright] = j; iright = iright-1; } } if( ae_fp_less_eq(kdt->xy.ptr.pp_double[ileft][d],s) ) { ileft = ileft+1; } else { iright = iright-1; } *i3 = ileft; } /************************************************************************* Recursive kd-tree generation subroutine. PARAMETERS KDT tree NodesOffs unused part of Nodes[] which must be filled by tree SplitsOffs unused part of Splits[] I1, I2 points from [I1,I2) are processed NodesOffs[] and SplitsOffs[] must be large enough. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ static void nearestneighbor_kdtreegeneratetreerec(kdtree* kdt, ae_int_t* nodesoffs, ae_int_t* splitsoffs, ae_int_t i1, ae_int_t i2, ae_int_t maxleafsize, ae_state *_state) { ae_int_t n; ae_int_t nx; ae_int_t ny; ae_int_t i; ae_int_t j; ae_int_t oldoffs; ae_int_t i3; ae_int_t cntless; ae_int_t cntgreater; double minv; double maxv; ae_int_t minidx; ae_int_t maxidx; ae_int_t d; double ds; double s; double v; double v0; double v1; ae_assert(kdt->n>0, "KDTreeGenerateTreeRec: internal error", _state); ae_assert(i2>i1, "KDTreeGenerateTreeRec: internal error", _state); /* * Generate leaf if needed */ if( i2-i1<=maxleafsize ) { kdt->nodes.ptr.p_int[*nodesoffs+0] = i2-i1; kdt->nodes.ptr.p_int[*nodesoffs+1] = i1; *nodesoffs = *nodesoffs+2; return; } /* * Load values for easier access */ nx = kdt->nx; ny = kdt->ny; /* * Select dimension to split: * * D is a dimension number * In case bounding box has zero size, we enforce creation of the leaf node. */ d = 0; ds = kdt->curboxmax.ptr.p_double[0]-kdt->curboxmin.ptr.p_double[0]; for(i=1; i<=nx-1; i++) { v = kdt->curboxmax.ptr.p_double[i]-kdt->curboxmin.ptr.p_double[i]; if( ae_fp_greater(v,ds) ) { ds = v; d = i; } } if( ae_fp_eq(ds,0) ) { kdt->nodes.ptr.p_int[*nodesoffs+0] = i2-i1; kdt->nodes.ptr.p_int[*nodesoffs+1] = i1; *nodesoffs = *nodesoffs+2; return; } /* * Select split position S using sliding midpoint rule, * rearrange points into [I1,I3) and [I3,I2). * * In case all points has same value of D-th component * (MinV=MaxV) we enforce D-th dimension of bounding * box to become exactly zero and repeat tree construction. */ s = kdt->curboxmin.ptr.p_double[d]+0.5*ds; ae_v_move(&kdt->buf.ptr.p_double[0], 1, &kdt->xy.ptr.pp_double[i1][d], kdt->xy.stride, ae_v_len(0,i2-i1-1)); n = i2-i1; cntless = 0; cntgreater = 0; minv = kdt->buf.ptr.p_double[0]; maxv = kdt->buf.ptr.p_double[0]; minidx = i1; maxidx = i1; for(i=0; i<=n-1; i++) { v = kdt->buf.ptr.p_double[i]; if( ae_fp_less(v,minv) ) { minv = v; minidx = i1+i; } if( ae_fp_greater(v,maxv) ) { maxv = v; maxidx = i1+i; } if( ae_fp_less(v,s) ) { cntless = cntless+1; } if( ae_fp_greater(v,s) ) { cntgreater = cntgreater+1; } } if( ae_fp_eq(minv,maxv) ) { /* * In case all points has same value of D-th component * (MinV=MaxV) we enforce D-th dimension of bounding * box to become exactly zero and repeat tree construction. */ v0 = kdt->curboxmin.ptr.p_double[d]; v1 = kdt->curboxmax.ptr.p_double[d]; kdt->curboxmin.ptr.p_double[d] = minv; kdt->curboxmax.ptr.p_double[d] = maxv; nearestneighbor_kdtreegeneratetreerec(kdt, nodesoffs, splitsoffs, i1, i2, maxleafsize, _state); kdt->curboxmin.ptr.p_double[d] = v0; kdt->curboxmax.ptr.p_double[d] = v1; return; } if( cntless>0&&cntgreater>0 ) { /* * normal midpoint split */ nearestneighbor_kdtreesplit(kdt, i1, i2, d, s, &i3, _state); } else { /* * sliding midpoint */ if( cntless==0 ) { /* * 1. move split to MinV, * 2. place one point to the left bin (move to I1), * others - to the right bin */ s = minv; if( minidx!=i1 ) { for(i=0; i<=2*nx+ny-1; i++) { v = kdt->xy.ptr.pp_double[minidx][i]; kdt->xy.ptr.pp_double[minidx][i] = kdt->xy.ptr.pp_double[i1][i]; kdt->xy.ptr.pp_double[i1][i] = v; } j = kdt->tags.ptr.p_int[minidx]; kdt->tags.ptr.p_int[minidx] = kdt->tags.ptr.p_int[i1]; kdt->tags.ptr.p_int[i1] = j; } i3 = i1+1; } else { /* * 1. move split to MaxV, * 2. place one point to the right bin (move to I2-1), * others - to the left bin */ s = maxv; if( maxidx!=i2-1 ) { for(i=0; i<=2*nx+ny-1; i++) { v = kdt->xy.ptr.pp_double[maxidx][i]; kdt->xy.ptr.pp_double[maxidx][i] = kdt->xy.ptr.pp_double[i2-1][i]; kdt->xy.ptr.pp_double[i2-1][i] = v; } j = kdt->tags.ptr.p_int[maxidx]; kdt->tags.ptr.p_int[maxidx] = kdt->tags.ptr.p_int[i2-1]; kdt->tags.ptr.p_int[i2-1] = j; } i3 = i2-1; } } /* * Generate 'split' node */ kdt->nodes.ptr.p_int[*nodesoffs+0] = 0; kdt->nodes.ptr.p_int[*nodesoffs+1] = d; kdt->nodes.ptr.p_int[*nodesoffs+2] = *splitsoffs; kdt->splits.ptr.p_double[*splitsoffs+0] = s; oldoffs = *nodesoffs; *nodesoffs = *nodesoffs+nearestneighbor_splitnodesize; *splitsoffs = *splitsoffs+1; /* * Recirsive generation: * * update CurBox * * call subroutine * * restore CurBox */ kdt->nodes.ptr.p_int[oldoffs+3] = *nodesoffs; v = kdt->curboxmax.ptr.p_double[d]; kdt->curboxmax.ptr.p_double[d] = s; nearestneighbor_kdtreegeneratetreerec(kdt, nodesoffs, splitsoffs, i1, i3, maxleafsize, _state); kdt->curboxmax.ptr.p_double[d] = v; kdt->nodes.ptr.p_int[oldoffs+4] = *nodesoffs; v = kdt->curboxmin.ptr.p_double[d]; kdt->curboxmin.ptr.p_double[d] = s; nearestneighbor_kdtreegeneratetreerec(kdt, nodesoffs, splitsoffs, i3, i2, maxleafsize, _state); kdt->curboxmin.ptr.p_double[d] = v; } /************************************************************************* Recursive subroutine for NN queries. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ static void nearestneighbor_kdtreequerynnrec(kdtree* kdt, ae_int_t offs, ae_state *_state) { double ptdist; ae_int_t i; ae_int_t j; ae_int_t nx; ae_int_t i1; ae_int_t i2; ae_int_t d; double s; double v; double t1; ae_int_t childbestoffs; ae_int_t childworstoffs; ae_int_t childoffs; double prevdist; ae_bool todive; ae_bool bestisleft; ae_bool updatemin; ae_assert(kdt->n>0, "KDTreeQueryNNRec: internal error", _state); /* * Leaf node. * Process points. */ if( kdt->nodes.ptr.p_int[offs]>0 ) { i1 = kdt->nodes.ptr.p_int[offs+1]; i2 = i1+kdt->nodes.ptr.p_int[offs]; for(i=i1; i<=i2-1; i++) { /* * Calculate distance */ ptdist = 0; nx = kdt->nx; if( kdt->normtype==0 ) { for(j=0; j<=nx-1; j++) { ptdist = ae_maxreal(ptdist, ae_fabs(kdt->xy.ptr.pp_double[i][j]-kdt->x.ptr.p_double[j], _state), _state); } } if( kdt->normtype==1 ) { for(j=0; j<=nx-1; j++) { ptdist = ptdist+ae_fabs(kdt->xy.ptr.pp_double[i][j]-kdt->x.ptr.p_double[j], _state); } } if( kdt->normtype==2 ) { for(j=0; j<=nx-1; j++) { ptdist = ptdist+ae_sqr(kdt->xy.ptr.pp_double[i][j]-kdt->x.ptr.p_double[j], _state); } } /* * Skip points with zero distance if self-matches are turned off */ if( ae_fp_eq(ptdist,0)&&!kdt->selfmatch ) { continue; } /* * We CAN'T process point if R-criterion isn't satisfied, * i.e. (RNeeded<>0) AND (PtDist>R). */ if( ae_fp_eq(kdt->rneeded,0)||ae_fp_less_eq(ptdist,kdt->rneeded) ) { /* * R-criterion is satisfied, we must either: * * replace worst point, if (KNeeded<>0) AND (KCur=KNeeded) * (or skip, if worst point is better) * * add point without replacement otherwise */ if( kdt->kcur<kdt->kneeded||kdt->kneeded==0 ) { /* * add current point to heap without replacement */ tagheappushi(&kdt->r, &kdt->idx, &kdt->kcur, ptdist, i, _state); } else { /* * New points are added or not, depending on their distance. * If added, they replace element at the top of the heap */ if( ae_fp_less(ptdist,kdt->r.ptr.p_double[0]) ) { if( kdt->kneeded==1 ) { kdt->idx.ptr.p_int[0] = i; kdt->r.ptr.p_double[0] = ptdist; } else { tagheapreplacetopi(&kdt->r, &kdt->idx, kdt->kneeded, ptdist, i, _state); } } } } } return; } /* * Simple split */ if( kdt->nodes.ptr.p_int[offs]==0 ) { /* * Load: * * D dimension to split * * S split position */ d = kdt->nodes.ptr.p_int[offs+1]; s = kdt->splits.ptr.p_double[kdt->nodes.ptr.p_int[offs+2]]; /* * Calculate: * * ChildBestOffs child box with best chances * * ChildWorstOffs child box with worst chances */ if( ae_fp_less_eq(kdt->x.ptr.p_double[d],s) ) { childbestoffs = kdt->nodes.ptr.p_int[offs+3]; childworstoffs = kdt->nodes.ptr.p_int[offs+4]; bestisleft = ae_true; } else { childbestoffs = kdt->nodes.ptr.p_int[offs+4]; childworstoffs = kdt->nodes.ptr.p_int[offs+3]; bestisleft = ae_false; } /* * Navigate through childs */ for(i=0; i<=1; i++) { /* * Select child to process: * * ChildOffs current child offset in Nodes[] * * UpdateMin whether minimum or maximum value * of bounding box is changed on update */ if( i==0 ) { childoffs = childbestoffs; updatemin = !bestisleft; } else { updatemin = bestisleft; childoffs = childworstoffs; } /* * Update bounding box and current distance */ if( updatemin ) { prevdist = kdt->curdist; t1 = kdt->x.ptr.p_double[d]; v = kdt->curboxmin.ptr.p_double[d]; if( ae_fp_less_eq(t1,s) ) { if( kdt->normtype==0 ) { kdt->curdist = ae_maxreal(kdt->curdist, s-t1, _state); } if( kdt->normtype==1 ) { kdt->curdist = kdt->curdist-ae_maxreal(v-t1, 0, _state)+s-t1; } if( kdt->normtype==2 ) { kdt->curdist = kdt->curdist-ae_sqr(ae_maxreal(v-t1, 0, _state), _state)+ae_sqr(s-t1, _state); } } kdt->curboxmin.ptr.p_double[d] = s; } else { prevdist = kdt->curdist; t1 = kdt->x.ptr.p_double[d]; v = kdt->curboxmax.ptr.p_double[d]; if( ae_fp_greater_eq(t1,s) ) { if( kdt->normtype==0 ) { kdt->curdist = ae_maxreal(kdt->curdist, t1-s, _state); } if( kdt->normtype==1 ) { kdt->curdist = kdt->curdist-ae_maxreal(t1-v, 0, _state)+t1-s; } if( kdt->normtype==2 ) { kdt->curdist = kdt->curdist-ae_sqr(ae_maxreal(t1-v, 0, _state), _state)+ae_sqr(t1-s, _state); } } kdt->curboxmax.ptr.p_double[d] = s; } /* * Decide: to dive into cell or not to dive */ if( ae_fp_neq(kdt->rneeded,0)&&ae_fp_greater(kdt->curdist,kdt->rneeded) ) { todive = ae_false; } else { if( kdt->kcur<kdt->kneeded||kdt->kneeded==0 ) { /* * KCur<KNeeded (i.e. not all points are found) */ todive = ae_true; } else { /* * KCur=KNeeded, decide to dive or not to dive * using point position relative to bounding box. */ todive = ae_fp_less_eq(kdt->curdist,kdt->r.ptr.p_double[0]*kdt->approxf); } } if( todive ) { nearestneighbor_kdtreequerynnrec(kdt, childoffs, _state); } /* * Restore bounding box and distance */ if( updatemin ) { kdt->curboxmin.ptr.p_double[d] = v; } else { kdt->curboxmax.ptr.p_double[d] = v; } kdt->curdist = prevdist; } return; } } /************************************************************************* Copies X[] to KDT.X[] Loads distance from X[] to bounding box. Initializes CurBox[]. -- ALGLIB -- Copyright 28.02.2010 by Bochkanov Sergey *************************************************************************/ static void nearestneighbor_kdtreeinitbox(kdtree* kdt, /* Real */ ae_vector* x, ae_state *_state) { ae_int_t i; double vx; double vmin; double vmax; ae_assert(kdt->n>0, "KDTreeInitBox: internal error", _state); /* * calculate distance from point to current bounding box */ kdt->curdist = 0; if( kdt->normtype==0 ) { for(i=0; i<=kdt->nx-1; i++) { vx = x->ptr.p_double[i]; vmin = kdt->boxmin.ptr.p_double[i]; vmax = kdt->boxmax.ptr.p_double[i]; kdt->x.ptr.p_double[i] = vx; kdt->curboxmin.ptr.p_double[i] = vmin; kdt->curboxmax.ptr.p_double[i] = vmax; if( ae_fp_less(vx,vmin) ) { kdt->curdist = ae_maxreal(kdt->curdist, vmin-vx, _state); } else { if( ae_fp_greater(vx,vmax) ) { kdt->curdist = ae_maxreal(kdt->curdist, vx-vmax, _state); } } } } if( kdt->normtype==1 ) { for(i=0; i<=kdt->nx-1; i++) { vx = x->ptr.p_double[i]; vmin = kdt->boxmin.ptr.p_double[i]; vmax = kdt->boxmax.ptr.p_double[i]; kdt->x.ptr.p_double[i] = vx; kdt->curboxmin.ptr.p_double[i] = vmin; kdt->curboxmax.ptr.p_double[i] = vmax; if( ae_fp_less(vx,vmin) ) { kdt->curdist = kdt->curdist+vmin-vx; } else { if( ae_fp_greater(vx,vmax) ) { kdt->curdist = kdt->curdist+vx-vmax; } } } } if( kdt->normtype==2 ) { for(i=0; i<=kdt->nx-1; i++) { vx = x->ptr.p_double[i]; vmin = kdt->boxmin.ptr.p_double[i]; vmax = kdt->boxmax.ptr.p_double[i]; kdt->x.ptr.p_double[i] = vx; kdt->curboxmin.ptr.p_double[i] = vmin; kdt->curboxmax.ptr.p_double[i] = vmax; if( ae_fp_less(vx,vmin) ) { kdt->curdist = kdt->curdist+ae_sqr(vmin-vx, _state); } else { if( ae_fp_greater(vx,vmax) ) { kdt->curdist = kdt->curdist+ae_sqr(vx-vmax, _state); } } } } } /************************************************************************* This function allocates all dataset-independent array fields of KDTree, i.e. such array fields that their dimensions do not depend on dataset size. This function do not sets KDT.NX or KDT.NY - it just allocates arrays -- ALGLIB -- Copyright 14.03.2011 by Bochkanov Sergey *************************************************************************/ static void nearestneighbor_kdtreeallocdatasetindependent(kdtree* kdt, ae_int_t nx, ae_int_t ny, ae_state *_state) { ae_assert(kdt->n>0, "KDTreeAllocDatasetIndependent: internal error", _state); ae_vector_set_length(&kdt->x, nx, _state); ae_vector_set_length(&kdt->boxmin, nx, _state); ae_vector_set_length(&kdt->boxmax, nx, _state); ae_vector_set_length(&kdt->curboxmin, nx, _state); ae_vector_set_length(&kdt->curboxmax, nx, _state); } /************************************************************************* This function allocates all dataset-dependent array fields of KDTree, i.e. such array fields that their dimensions depend on dataset size. This function do not sets KDT.N, KDT.NX or KDT.NY - it just allocates arrays. -- ALGLIB -- Copyright 14.03.2011 by Bochkanov Sergey *************************************************************************/ static void nearestneighbor_kdtreeallocdatasetdependent(kdtree* kdt, ae_int_t n, ae_int_t nx, ae_int_t ny, ae_state *_state) { ae_assert(n>0, "KDTreeAllocDatasetDependent: internal error", _state); ae_matrix_set_length(&kdt->xy, n, 2*nx+ny, _state); ae_vector_set_length(&kdt->tags, n, _state); ae_vector_set_length(&kdt->idx, n, _state); ae_vector_set_length(&kdt->r, n, _state); ae_vector_set_length(&kdt->x, nx, _state); ae_vector_set_length(&kdt->buf, ae_maxint(n, nx, _state), _state); ae_vector_set_length(&kdt->nodes, nearestneighbor_splitnodesize*2*n, _state); ae_vector_set_length(&kdt->splits, 2*n, _state); } /************************************************************************* This function allocates temporaries. This function do not sets KDT.N, KDT.NX or KDT.NY - it just allocates arrays. -- ALGLIB -- Copyright 14.03.2011 by Bochkanov Sergey *************************************************************************/ static void nearestneighbor_kdtreealloctemporaries(kdtree* kdt, ae_int_t n, ae_int_t nx, ae_int_t ny, ae_state *_state) { ae_assert(n>0, "KDTreeAllocTemporaries: internal error", _state); ae_vector_set_length(&kdt->x, nx, _state); ae_vector_set_length(&kdt->idx, n, _state); ae_vector_set_length(&kdt->r, n, _state); ae_vector_set_length(&kdt->buf, ae_maxint(n, nx, _state), _state); ae_vector_set_length(&kdt->curboxmin, nx, _state); ae_vector_set_length(&kdt->curboxmax, nx, _state); } ae_bool _kdtree_init(void* _p, ae_state *_state, ae_bool make_automatic) { kdtree *p = (kdtree*)_p; ae_touch_ptr((void*)p); if( !ae_matrix_init(&p->xy, 0, 0, DT_REAL, _state, make_automatic) ) return ae_false; if( !ae_vector_init(&p->tags, 0, DT_INT, _state, make_automatic) ) return ae_false; if( !ae_vector_init(&p->boxmin, 0, DT_REAL, _state, make_automatic) ) return ae_false; if( !ae_vector_init(&p->boxmax, 0, DT_REAL, _state, make_automatic) ) return ae_false; if( !ae_vector_init(&p->nodes, 0, DT_INT, _state, make_automatic) ) return ae_false; if( !ae_vector_init(&p->splits, 0, DT_REAL, _state, make_automatic) ) return ae_false; if( !ae_vector_init(&p->x, 0, DT_REAL, _state, make_automatic) ) return ae_false; if( !ae_vector_init(&p->idx, 0, DT_INT, _state, make_automatic) ) return ae_false; if( !ae_vector_init(&p->r, 0, DT_REAL, _state, make_automatic) ) return ae_false; if( !ae_vector_init(&p->buf, 0, DT_REAL, _state, make_automatic) ) return ae_false; if( !ae_vector_init(&p->curboxmin, 0, DT_REAL, _state, make_automatic) ) return ae_false; if( !ae_vector_init(&p->curboxmax, 0, DT_REAL, _state, make_automatic) ) return ae_false; return ae_true; } ae_bool _kdtree_init_copy(void* _dst, void* _src, ae_state *_state, ae_bool make_automatic) { kdtree *dst = (kdtree*)_dst; kdtree *src = (kdtree*)_src; dst->n = src->n; dst->nx = src->nx; dst->ny = src->ny; dst->normtype = src->normtype; if( !ae_matrix_init_copy(&dst->xy, &src->xy, _state, make_automatic) ) return ae_false; if( !ae_vector_init_copy(&dst->tags, &src->tags, _state, make_automatic) ) return ae_false; if( !ae_vector_init_copy(&dst->boxmin, &src->boxmin, _state, make_automatic) ) return ae_false; if( !ae_vector_init_copy(&dst->boxmax, &src->boxmax, _state, make_automatic) ) return ae_false; if( !ae_vector_init_copy(&dst->nodes, &src->nodes, _state, make_automatic) ) return ae_false; if( !ae_vector_init_copy(&dst->splits, &src->splits, _state, make_automatic) ) return ae_false; if( !ae_vector_init_copy(&dst->x, &src->x, _state, make_automatic) ) return ae_false; dst->kneeded = src->kneeded; dst->rneeded = src->rneeded; dst->selfmatch = src->selfmatch; dst->approxf = src->approxf; dst->kcur = src->kcur; if( !ae_vector_init_copy(&dst->idx, &src->idx, _state, make_automatic) ) return ae_false; if( !ae_vector_init_copy(&dst->r, &src->r, _state, make_automatic) ) return ae_false; if( !ae_vector_init_copy(&dst->buf, &src->buf, _state, make_automatic) ) return ae_false; if( !ae_vector_init_copy(&dst->curboxmin, &src->curboxmin, _state, make_automatic) ) return ae_false; if( !ae_vector_init_copy(&dst->curboxmax, &src->curboxmax, _state, make_automatic) ) return ae_false; dst->curdist = src->curdist; dst->debugcounter = src->debugcounter; return ae_true; } void _kdtree_clear(void* _p) { kdtree *p = (kdtree*)_p; ae_touch_ptr((void*)p); ae_matrix_clear(&p->xy); ae_vector_clear(&p->tags); ae_vector_clear(&p->boxmin); ae_vector_clear(&p->boxmax); ae_vector_clear(&p->nodes); ae_vector_clear(&p->splits); ae_vector_clear(&p->x); ae_vector_clear(&p->idx); ae_vector_clear(&p->r); ae_vector_clear(&p->buf); ae_vector_clear(&p->curboxmin); ae_vector_clear(&p->curboxmax); } void _kdtree_destroy(void* _p) { kdtree *p = (kdtree*)_p; ae_touch_ptr((void*)p); ae_matrix_destroy(&p->xy); ae_vector_destroy(&p->tags); ae_vector_destroy(&p->boxmin); ae_vector_destroy(&p->boxmax); ae_vector_destroy(&p->nodes); ae_vector_destroy(&p->splits); ae_vector_destroy(&p->x); ae_vector_destroy(&p->idx); ae_vector_destroy(&p->r); ae_vector_destroy(&p->buf); ae_vector_destroy(&p->curboxmin); ae_vector_destroy(&p->curboxmax); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Counts number of True values in the boolean 1D array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugb1count(/* Boolean */ ae_vector* a, ae_state *_state) { ae_int_t i; ae_int_t result; result = 0; for(i=0; i<=a->cnt-1; i++) { if( a->ptr.p_bool[i] ) { result = result+1; } } return result; } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by NOT(a[i]). Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb1not(/* Boolean */ ae_vector* a, ae_state *_state) { ae_int_t i; for(i=0; i<=a->cnt-1; i++) { a->ptr.p_bool[i] = !a->ptr.p_bool[i]; } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb1appendcopy(/* Boolean */ ae_vector* a, ae_state *_state) { ae_frame _frame_block; ae_int_t i; ae_vector b; ae_frame_make(_state, &_frame_block); ae_vector_init(&b, 0, DT_BOOL, _state, ae_true); ae_vector_set_length(&b, a->cnt, _state); for(i=0; i<=b.cnt-1; i++) { b.ptr.p_bool[i] = a->ptr.p_bool[i]; } ae_vector_set_length(a, 2*b.cnt, _state); for(i=0; i<=a->cnt-1; i++) { a->ptr.p_bool[i] = b.ptr.p_bool[i%b.cnt]; } ae_frame_leave(_state); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered elements set to True. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb1outeven(ae_int_t n, /* Boolean */ ae_vector* a, ae_state *_state) { ae_int_t i; ae_vector_clear(a); ae_vector_set_length(a, n, _state); for(i=0; i<=a->cnt-1; i++) { a->ptr.p_bool[i] = i%2==0; } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugi1sum(/* Integer */ ae_vector* a, ae_state *_state) { ae_int_t i; ae_int_t result; result = 0; for(i=0; i<=a->cnt-1; i++) { result = result+a->ptr.p_int[i]; } return result; } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -A[I] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi1neg(/* Integer */ ae_vector* a, ae_state *_state) { ae_int_t i; for(i=0; i<=a->cnt-1; i++) { a->ptr.p_int[i] = -a->ptr.p_int[i]; } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi1appendcopy(/* Integer */ ae_vector* a, ae_state *_state) { ae_frame _frame_block; ae_int_t i; ae_vector b; ae_frame_make(_state, &_frame_block); ae_vector_init(&b, 0, DT_INT, _state, ae_true); ae_vector_set_length(&b, a->cnt, _state); for(i=0; i<=b.cnt-1; i++) { b.ptr.p_int[i] = a->ptr.p_int[i]; } ae_vector_set_length(a, 2*b.cnt, _state); for(i=0; i<=a->cnt-1; i++) { a->ptr.p_int[i] = b.ptr.p_int[i%b.cnt]; } ae_frame_leave(_state); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered A[I] set to I, and odd-numbered ones set to 0. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi1outeven(ae_int_t n, /* Integer */ ae_vector* a, ae_state *_state) { ae_int_t i; ae_vector_clear(a); ae_vector_set_length(a, n, _state); for(i=0; i<=a->cnt-1; i++) { if( i%2==0 ) { a->ptr.p_int[i] = i; } else { a->ptr.p_int[i] = 0; } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ double xdebugr1sum(/* Real */ ae_vector* a, ae_state *_state) { ae_int_t i; double result; result = 0; for(i=0; i<=a->cnt-1; i++) { result = result+a->ptr.p_double[i]; } return result; } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -A[I] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr1neg(/* Real */ ae_vector* a, ae_state *_state) { ae_int_t i; for(i=0; i<=a->cnt-1; i++) { a->ptr.p_double[i] = -a->ptr.p_double[i]; } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr1appendcopy(/* Real */ ae_vector* a, ae_state *_state) { ae_frame _frame_block; ae_int_t i; ae_vector b; ae_frame_make(_state, &_frame_block); ae_vector_init(&b, 0, DT_REAL, _state, ae_true); ae_vector_set_length(&b, a->cnt, _state); for(i=0; i<=b.cnt-1; i++) { b.ptr.p_double[i] = a->ptr.p_double[i]; } ae_vector_set_length(a, 2*b.cnt, _state); for(i=0; i<=a->cnt-1; i++) { a->ptr.p_double[i] = b.ptr.p_double[i%b.cnt]; } ae_frame_leave(_state); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered A[I] set to I*0.25, and odd-numbered ones are set to 0. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr1outeven(ae_int_t n, /* Real */ ae_vector* a, ae_state *_state) { ae_int_t i; ae_vector_clear(a); ae_vector_set_length(a, n, _state); for(i=0; i<=a->cnt-1; i++) { if( i%2==0 ) { a->ptr.p_double[i] = i*0.25; } else { a->ptr.p_double[i] = 0; } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_complex xdebugc1sum(/* Complex */ ae_vector* a, ae_state *_state) { ae_int_t i; ae_complex result; result = ae_complex_from_d(0); for(i=0; i<=a->cnt-1; i++) { result = ae_c_add(result,a->ptr.p_complex[i]); } return result; } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -A[I] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc1neg(/* Complex */ ae_vector* a, ae_state *_state) { ae_int_t i; for(i=0; i<=a->cnt-1; i++) { a->ptr.p_complex[i] = ae_c_neg(a->ptr.p_complex[i]); } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Appends copy of array to itself. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc1appendcopy(/* Complex */ ae_vector* a, ae_state *_state) { ae_frame _frame_block; ae_int_t i; ae_vector b; ae_frame_make(_state, &_frame_block); ae_vector_init(&b, 0, DT_COMPLEX, _state, ae_true); ae_vector_set_length(&b, a->cnt, _state); for(i=0; i<=b.cnt-1; i++) { b.ptr.p_complex[i] = a->ptr.p_complex[i]; } ae_vector_set_length(a, 2*b.cnt, _state); for(i=0; i<=a->cnt-1; i++) { a->ptr.p_complex[i] = b.ptr.p_complex[i%b.cnt]; } ae_frame_leave(_state); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate N-element array with even-numbered A[K] set to (x,y) = (K*0.25, K*0.125) and odd-numbered ones are set to 0. Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc1outeven(ae_int_t n, /* Complex */ ae_vector* a, ae_state *_state) { ae_int_t i; ae_vector_clear(a); ae_vector_set_length(a, n, _state); for(i=0; i<=a->cnt-1; i++) { if( i%2==0 ) { a->ptr.p_complex[i].x = i*0.250; a->ptr.p_complex[i].y = i*0.125; } else { a->ptr.p_complex[i] = ae_complex_from_d(0); } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Counts number of True values in the boolean 2D array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugb2count(/* Boolean */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; ae_int_t result; result = 0; for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { if( a->ptr.pp_bool[i][j] ) { result = result+1; } } } return result; } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by NOT(a[i]). Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb2not(/* Boolean */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { a->ptr.pp_bool[i][j] = !a->ptr.pp_bool[i][j]; } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb2transpose(/* Boolean */ ae_matrix* a, ae_state *_state) { ae_frame _frame_block; ae_int_t i; ae_int_t j; ae_matrix b; ae_frame_make(_state, &_frame_block); ae_matrix_init(&b, 0, 0, DT_BOOL, _state, ae_true); ae_matrix_set_length(&b, a->rows, a->cols, _state); for(i=0; i<=b.rows-1; i++) { for(j=0; j<=b.cols-1; j++) { b.ptr.pp_bool[i][j] = a->ptr.pp_bool[i][j]; } } ae_matrix_set_length(a, b.cols, b.rows, _state); for(i=0; i<=b.rows-1; i++) { for(j=0; j<=b.cols-1; j++) { a->ptr.pp_bool[j][i] = b.ptr.pp_bool[i][j]; } } ae_frame_leave(_state); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sin(3*I+5*J)>0" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugb2outsin(ae_int_t m, ae_int_t n, /* Boolean */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; ae_matrix_clear(a); ae_matrix_set_length(a, m, n, _state); for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { a->ptr.pp_bool[i][j] = ae_fp_greater(ae_sin(3*i+5*j, _state),0); } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_int_t xdebugi2sum(/* Integer */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; ae_int_t result; result = 0; for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { result = result+a->ptr.pp_int[i][j]; } } return result; } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -a[i,j] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi2neg(/* Integer */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { a->ptr.pp_int[i][j] = -a->ptr.pp_int[i][j]; } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi2transpose(/* Integer */ ae_matrix* a, ae_state *_state) { ae_frame _frame_block; ae_int_t i; ae_int_t j; ae_matrix b; ae_frame_make(_state, &_frame_block); ae_matrix_init(&b, 0, 0, DT_INT, _state, ae_true); ae_matrix_set_length(&b, a->rows, a->cols, _state); for(i=0; i<=b.rows-1; i++) { for(j=0; j<=b.cols-1; j++) { b.ptr.pp_int[i][j] = a->ptr.pp_int[i][j]; } } ae_matrix_set_length(a, b.cols, b.rows, _state); for(i=0; i<=b.rows-1; i++) { for(j=0; j<=b.cols-1; j++) { a->ptr.pp_int[j][i] = b.ptr.pp_int[i][j]; } } ae_frame_leave(_state); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sign(Sin(3*I+5*J))" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugi2outsin(ae_int_t m, ae_int_t n, /* Integer */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; ae_matrix_clear(a); ae_matrix_set_length(a, m, n, _state); for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { a->ptr.pp_int[i][j] = ae_sign(ae_sin(3*i+5*j, _state), _state); } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ double xdebugr2sum(/* Real */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; double result; result = 0; for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { result = result+a->ptr.pp_double[i][j]; } } return result; } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -a[i,j] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr2neg(/* Real */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { a->ptr.pp_double[i][j] = -a->ptr.pp_double[i][j]; } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr2transpose(/* Real */ ae_matrix* a, ae_state *_state) { ae_frame _frame_block; ae_int_t i; ae_int_t j; ae_matrix b; ae_frame_make(_state, &_frame_block); ae_matrix_init(&b, 0, 0, DT_REAL, _state, ae_true); ae_matrix_set_length(&b, a->rows, a->cols, _state); for(i=0; i<=b.rows-1; i++) { for(j=0; j<=b.cols-1; j++) { b.ptr.pp_double[i][j] = a->ptr.pp_double[i][j]; } } ae_matrix_set_length(a, b.cols, b.rows, _state); for(i=0; i<=b.rows-1; i++) { for(j=0; j<=b.cols-1; j++) { a->ptr.pp_double[j][i] = b.ptr.pp_double[i][j]; } } ae_frame_leave(_state); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sin(3*I+5*J)" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugr2outsin(ae_int_t m, ae_int_t n, /* Real */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; ae_matrix_clear(a); ae_matrix_set_length(a, m, n, _state); for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { a->ptr.pp_double[i][j] = ae_sin(3*i+5*j, _state); } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of elements in the array. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ ae_complex xdebugc2sum(/* Complex */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; ae_complex result; result = ae_complex_from_d(0); for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { result = ae_c_add(result,a->ptr.pp_complex[i][j]); } } return result; } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Replace all values in array by -a[i,j] Array is passed using "shared" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc2neg(/* Complex */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { a->ptr.pp_complex[i][j] = ae_c_neg(a->ptr.pp_complex[i][j]); } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Transposes array. Array is passed using "var" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc2transpose(/* Complex */ ae_matrix* a, ae_state *_state) { ae_frame _frame_block; ae_int_t i; ae_int_t j; ae_matrix b; ae_frame_make(_state, &_frame_block); ae_matrix_init(&b, 0, 0, DT_COMPLEX, _state, ae_true); ae_matrix_set_length(&b, a->rows, a->cols, _state); for(i=0; i<=b.rows-1; i++) { for(j=0; j<=b.cols-1; j++) { b.ptr.pp_complex[i][j] = a->ptr.pp_complex[i][j]; } } ae_matrix_set_length(a, b.cols, b.rows, _state); for(i=0; i<=b.rows-1; i++) { for(j=0; j<=b.cols-1; j++) { a->ptr.pp_complex[j][i] = b.ptr.pp_complex[i][j]; } } ae_frame_leave(_state); } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Generate MxN matrix with elements set to "Sin(3*I+5*J),Cos(3*I+5*J)" Array is passed using "out" convention. -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ void xdebugc2outsincos(ae_int_t m, ae_int_t n, /* Complex */ ae_matrix* a, ae_state *_state) { ae_int_t i; ae_int_t j; ae_matrix_clear(a); ae_matrix_set_length(a, m, n, _state); for(i=0; i<=a->rows-1; i++) { for(j=0; j<=a->cols-1; j++) { a->ptr.pp_complex[i][j].x = ae_sin(3*i+5*j, _state); a->ptr.pp_complex[i][j].y = ae_cos(3*i+5*j, _state); } } } /************************************************************************* This is debug function intended for testing ALGLIB interface generator. Never use it in any real life project. Returns sum of a[i,j]*(1+b[i,j]) such that c[i,j] is True -- ALGLIB -- Copyright 11.10.2013 by Bochkanov Sergey *************************************************************************/ double xdebugmaskedbiasedproductsum(ae_int_t m, ae_int_t n, /* Real */ ae_matrix* a, /* Real */ ae_matrix* b, /* Boolean */ ae_matrix* c, ae_state *_state) { ae_int_t i; ae_int_t j; double result; ae_assert(m>=a->rows, "Assertion failed", _state); ae_assert(m>=b->rows, "Assertion failed", _state); ae_assert(m>=c->rows, "Assertion failed", _state); ae_assert(n>=a->cols, "Assertion failed", _state); ae_assert(n>=b->cols, "Assertion failed", _state); ae_assert(n>=c->cols, "Assertion failed", _state); result = 0.0; for(i=0; i<=m-1; i++) { for(j=0; j<=n-1; j++) { if( c->ptr.pp_bool[i][j] ) { result = result+a->ptr.pp_double[i][j]*(1+b->ptr.pp_double[i][j]); } } } return result; } }
[ "dominik.petrovic@fer.hr" ]
dominik.petrovic@fer.hr
c53c80bd7feb1dae10d7bf8137e276ff54a58250
cc7661edca4d5fb2fc226bd6605a533f50a2fb63
/mscorlib/CodeAccessSecurityAttribute.h
b85de520bd83f887005bcd59d83241d4adde2c94
[ "MIT" ]
permissive
g91/Rust-C-SDK
698e5b573285d5793250099b59f5453c3c4599eb
d1cce1133191263cba5583c43a8d42d8d65c21b0
refs/heads/master
2020-03-27T05:49:01.747456
2017-08-23T09:07:35
2017-08-23T09:07:35
146,053,940
1
0
null
2018-08-25T01:13:44
2018-08-25T01:13:44
null
UTF-8
C++
false
false
186
h
#pragma once namespace System { namespace Security { { namespace Permissions { class CodeAccessSecurityAttribute : public SecurityAttribute // 0x18 { public: }; // size = 0x18 }
[ "info@cvm-solutions.co.uk" ]
info@cvm-solutions.co.uk
de62e6f787c53726d724fd9aadd55ebd55744734
55ecb900e0b067a757871e0ee14127e29bd69ff6
/importfbx/stdafx.h
3ccff71049be5403746850231d484ff9ecd4e3f0
[ "MIT" ]
permissive
yearling/contentexporter
0f2f543c3d1d893b2b478a608870ae947ce48944
1c9e307778dbfbbda88f38085faff867c4c26da9
refs/heads/master
2021-01-12T21:38:08.418480
2015-05-06T22:33:13
2015-05-06T22:33:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,774
h
//------------------------------------------------------------------------------------- // stdafx.h // // Precompiled header for the ImportFBX project. // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Advanced Technology Group (ATG) // Copyright (C) Microsoft Corporation. All rights reserved. // // http://go.microsoft.com/fwlink/?LinkId=226208 //------------------------------------------------------------------------------------- #pragma once #pragma warning( disable : 4100 4296 4481 4505 4512 4996 ) #define NOMINMAX #include <stdio.h> #include <tchar.h> #include <windows.h> #include <WindowsX.h> #include <list> #include <vector> #include <hash_map> #include <algorithm> #include <memory> #include <commctrl.h> #include <richedit.h> #include <process.h> #include <assert.h> #include <stdio.h> #include <time.h> #include <shellapi.h> #include <dxgiformat.h> #include <DirectXMath.h> #include <DirectXCollision.h> #include <DirectXPackedVector.h> #include "..\ExporterGlobals.h" #include "..\ExportObjects\ExportXmlParser.h" #include "..\ExportObjects\ExportPath.h" #include "..\ExportObjects\ExportMaterial.h" #include "..\ExportObjects\ExportObjects.h" #pragma warning(push) #pragma warning( disable : 4616 6011 ) #include <fbxsdk.h> #pragma warning(pop) #include "..\XATGFileWriter\XATGFileWriter.h" #include "..\SDKMeshFileWriter\SDKMeshFileWriter.h" #define CONTENT_EXPORTER_TITLE CONTENT_EXPORTER_GLOBAL_TITLE " for FBX" extern CHAR g_strExporterName[100]; #ifndef UNUSED #define UNUSED(x) (x) #endif
[ "chuckw@windows.microsoft.com" ]
chuckw@windows.microsoft.com
08c3af71310872977036a8dfb3b4a82e72bb2012
98b17ee4d3d28b893218193f67774b6d047a6586
/User-centric NOMA/main.cpp
41f9e15557c4bf765b0c4f7a2d55ebce0e898f74
[]
no_license
logeee/User-centric-NOMA
7989dd1b111bcaa5dd56b0e5f325bdc817e6f1b1
6f32116a800a5a2a2327ced79d00be1808b60662
refs/heads/master
2022-10-25T21:03:32.457930
2020-06-18T10:04:32
2020-06-18T10:04:32
273,202,960
0
0
null
null
null
null
UTF-8
C++
false
false
17,029
cpp
// // main.cpp // User-centric NOMA // // Created by 俞斩味 on 2020/3/20. // Copyright © 2020 俞斩味. All rights reserved. // #define BS 21 #define UE 210 #define bandwidth 180000 #define noise 7.16593e-16 #define sP 50e-3 #define mP 200e-3 #define demand 0.03 #define rho_limit 1 #include <iostream> #include <string> #include <fstream> #include <cmath> #include <cstdio> #include <algorithm> #include <vector> using namespace std; double gain[BS][UE]; double association[BS][UE]; double RU[BS]; double Power[BS]; double alpha[UE]; int is_selected[UE] = {0};//a flag showing UE if is selected int ndx;//send i to global void initialize() { for (int i = 0; i < BS; ++i) RU[i] = 0; for (int j = 0; j < UE; ++j) alpha[j] = 1; for (int j = 0; j < UE; ++j) is_selected[j] = 0; } void read()//read matrix { for (int i = 0; i < 21; ++i) RU[i] = 1; ifstream gain_matrix("/Users/ZwYu/Desktop/Codes/User-centric NOMA/gain_matrix"); ifstream association_matrix("/Users/ZwYu/Desktop/Codes/User-centric NOMA/cell_user_matrix"); string buff; int k = 0; while (getline(gain_matrix,buff,',')) { if ((k+1)%210 == 0) { *(gain[k/210]+(k%210)) = atof((buff.substr(0,17)).c_str()); k++; *(gain[k/210]+(k%210)) = atof((buff.substr(18,17)).c_str()); } else { *(gain[k/210]+(k%210)) = atof(buff.c_str()); } k++; } string buff2; int p = 0; while (getline(association_matrix,buff2,',')) { if ((p+1)%210 == 0) { *(association[p/210]+(p%210)) = atof((buff2.substr(0,1)).c_str()); p++; *(association[p/210]+(p%210)) = atof((buff2.substr(2,1)).c_str()); } else { *(association[p/210]+(p%210)) = atof(buff2.c_str()); } p++; } } void converted()//convert scaled { for (int i = 0; i < 21; ++i) for (int j = 0; j < 210; ++j) gain[i][j] = pow(10,gain[i][j]/10); for (int i = 0; i < 7; ++i) Power[i] = mP; for (int i = 7; i < 21; ++i) Power[i] = sP; } double calculate_xu(int j, int h, int i)//j and h is UE, i is both associated BS { double w1,w2; int worse;//to record the worse UE index double wj = 0; for (int k = 0; k < BS; ++k) wj += (!association[k][j])*Power[k]*gain[k][j]*RU[k]; wj = (wj + noise)/gain[i][j]; double wh = 0; for (int k = 0; k < BS; ++k) wh += (!association[k][h])*Power[k]*gain[k][h]*RU[k]; wh = (wh + noise)/gain[i][h]; if (wj >= wh) { w1 = wh; w2 = wj; worse = j; } else { w1 = wj; w2 = wh; worse = h; } double xu_min = 0.0000001; double xu_max = 10; double xu_current = 0; while ((xu_max - xu_min) > 0.00000001) { xu_current = (xu_max + xu_min) / 2; double P = w1 * pow(2, (alpha[j]+alpha[h])*demand/xu_current) + (w2 - w1) * pow(2, alpha[worse]*demand/xu_current) - w2; if (P > Power[i]) xu_min = xu_current; else xu_max = xu_current; } return xu_current; } double calculate_x(int j, int i) { double IN = 0; for (int k = 0; k < BS; ++k) { if (k != i) IN += Power[k] * gain[k][j] * RU[k]; } IN += noise; double x = alpha[j]*demand/log(1+Power[i]*gain[i][j]/IN)*log(2); return x; } typedef long long s64; const int INF = 2147483647; const int MaxN = 22; const int MaxM = 79800; template <class T> inline void tension(T &a, const T &b) { if (b < a) a = b; } template <class T> inline void relax(T &a, const T &b) { if (b > a) a = b; } template <class T> inline int size(const T &a) { return (int)a.size(); } inline int getint() { char c; while (c = getchar(), '0' > c || c > '9'); int res = c - '0'; while (c = getchar(), '0' <= c && c <= '9') res = res * 10 + c - '0'; return res; } const int MaxNX = MaxN + MaxN; struct edge { int v, u, w; edge(){} edge(const int &_v, const int &_u, const int &_w) : v(_v), u(_u), w(_w){} }; int n, m; edge mat[MaxNX + 1][MaxNX + 1]; int n_matches; s64 tot_weight; int mate[MaxNX + 1]; int lab[MaxNX + 1]; int q_n, q[MaxN]; int fa[MaxNX + 1], col[MaxNX + 1]; int slackv[MaxNX + 1]; int n_x; int bel[MaxNX + 1], blofrom[MaxNX + 1][MaxN + 1]; vector<int> bloch[MaxNX + 1]; inline int e_delta(const edge &e) // does not work inside blossoms { return lab[e.v] + lab[e.u] - mat[e.v][e.u].w * 2; } inline void update_slackv(int v, int x) { if (!slackv[x] || e_delta(mat[v][x]) < e_delta(mat[slackv[x]][x])) slackv[x] = v; } inline void calc_slackv(int x) { slackv[x] = 0; for (int v = 1; v <= n; v++) if (mat[v][x].w > 0 && bel[v] != x && col[bel[v]] == 0) update_slackv(v, x); } inline void q_push(int x) { if (x <= n) q[q_n++] = x; else { for (int i = 0; i < size(bloch[x]); i++) q_push(bloch[x][i]); } } inline void set_mate(int xv, int xu) { mate[xv] = mat[xv][xu].u; if (xv > n) { edge e = mat[xv][xu]; int xr = blofrom[xv][e.v]; int pr = find(bloch[xv].begin(), bloch[xv].end(), xr) - bloch[xv].begin(); if (pr % 2 == 1) { reverse(bloch[xv].begin() + 1, bloch[xv].end()); pr = size(bloch[xv]) - pr; } for (int i = 0; i < pr; i++) set_mate(bloch[xv][i], bloch[xv][i ^ 1]); set_mate(xr, xu); rotate(bloch[xv].begin(), bloch[xv].begin() + pr, bloch[xv].end()); } } inline void set_bel(int x, int b) { bel[x] = b; if (x > n) { for (int i = 0; i < size(bloch[x]); i++) set_bel(bloch[x][i], b); } } inline void augment(int xv, int xu) { while (true) { int xnu = bel[mate[xv]]; set_mate(xv, xu); if (!xnu) return; set_mate(xnu, bel[fa[xnu]]); xv = bel[fa[xnu]], xu = xnu; } } inline int get_lca(int xv, int xu) { static bool book[MaxNX + 1]; for (int x = 1; x <= n_x; x++) book[x] = false; while (xv || xu) { if (xv) { if (book[xv]) return xv; book[xv] = true; xv = bel[mate[xv]]; if (xv) xv = bel[fa[xv]]; } swap(xv, xu); } return 0; } inline void add_blossom(int xv, int xa, int xu) { int b = n + 1; while (b <= n_x && bel[b]) b++; if (b > n_x) n_x++; lab[b] = 0; col[b] = 0; mate[b] = mate[xa]; bloch[b].clear(); bloch[b].push_back(xa); for (int x = xv; x != xa; x = bel[fa[bel[mate[x]]]]) bloch[b].push_back(x), bloch[b].push_back(bel[mate[x]]), q_push(bel[mate[x]]); reverse(bloch[b].begin() + 1, bloch[b].end()); for (int x = xu; x != xa; x = bel[fa[bel[mate[x]]]]) bloch[b].push_back(x), bloch[b].push_back(bel[mate[x]]), q_push(bel[mate[x]]); set_bel(b, b); for (int x = 1; x <= n_x; x++) { mat[b][x].w = mat[x][b].w = 0; blofrom[b][x] = 0; } for (int i = 0; i < size(bloch[b]); i++) { int xs = bloch[b][i]; for (int x = 1; x <= n_x; x++) if (mat[b][x].w == 0 || e_delta(mat[xs][x]) < e_delta(mat[b][x])) mat[b][x] = mat[xs][x], mat[x][b] = mat[x][xs]; for (int x = 1; x <= n_x; x++) if (blofrom[xs][x]) blofrom[b][x] = xs; } calc_slackv(b); } inline void expand_blossom1(int b) // lab[b] == 1 { for (int i = 0; i < size(bloch[b]); i++) set_bel(bloch[b][i], bloch[b][i]); int xr = blofrom[b][mat[b][fa[b]].v]; int pr = find(bloch[b].begin(), bloch[b].end(), xr) - bloch[b].begin(); if (pr % 2 == 1) { reverse(bloch[b].begin() + 1, bloch[b].end()); pr = size(bloch[b]) - pr; } for (int i = 0; i < pr; i += 2) { int xs = bloch[b][i], xns = bloch[b][i + 1]; fa[xs] = mat[xns][xs].v; col[xs] = 1, col[xns] = 0; slackv[xs] = 0, calc_slackv(xns); q_push(xns); } col[xr] = 1; fa[xr] = fa[b]; for (int i = pr + 1; i < size(bloch[b]); i++) { int xs = bloch[b][i]; col[xs] = -1; calc_slackv(xs); } bel[b] = 0; } inline void expand_blossom_final(int b) // at the final stage { for (int i = 0; i < size(bloch[b]); i++) { if (bloch[b][i] > n && lab[bloch[b][i]] == 0) expand_blossom_final(bloch[b][i]); else set_bel(bloch[b][i], bloch[b][i]); } bel[b] = 0; } inline bool on_found_edge(const edge &e) { int xv = bel[e.v], xu = bel[e.u]; if (col[xu] == -1) { int nv = bel[mate[xu]]; fa[xu] = e.v; col[xu] = 1, col[nv] = 0; slackv[xu] = slackv[nv] = 0; q_push(nv); } else if (col[xu] == 0) { int xa = get_lca(xv, xu); if (!xa) { augment(xv, xu), augment(xu, xv); for (int b = n + 1; b <= n_x; b++) if (bel[b] == b && lab[b] == 0) expand_blossom_final(b); return true; } else add_blossom(xv, xa, xu); } return false; } bool match() { for (int x = 1; x <= n_x; x++) col[x] = -1, slackv[x] = 0; q_n = 0; for (int x = 1; x <= n_x; x++) if (bel[x] == x && !mate[x]) fa[x] = 0, col[x] = 0, slackv[x] = 0, q_push(x); if (q_n == 0) return false; while (true) { for (int i = 0; i < q_n; i++) { int v = q[i]; for (int u = 1; u <= n; u++) if (mat[v][u].w > 0 && bel[v] != bel[u]) { int d = e_delta(mat[v][u]); if (d == 0) { if (on_found_edge(mat[v][u])) return true; } else if (col[bel[u]] == -1 || col[bel[u]] == 0) update_slackv(v, bel[u]); } } int d = INF; for (int v = 1; v <= n; v++) if (col[bel[v]] == 0) tension(d, lab[v]); for (int b = n + 1; b <= n_x; b++) if (bel[b] == b && col[b] == 1) tension(d, lab[b] / 2); for (int x = 1; x <= n_x; x++) if (bel[x] == x && slackv[x]) { if (col[x] == -1) tension(d, e_delta(mat[slackv[x]][x])); else if (col[x] == 0) tension(d, e_delta(mat[slackv[x]][x]) / 2); } for (int v = 1; v <= n; v++) { if (col[bel[v]] == 0) lab[v] -= d; else if (col[bel[v]] == 1) lab[v] += d; } for (int b = n + 1; b <= n_x; b++) if (bel[b] == b) { if (col[bel[b]] == 0) lab[b] += d * 2; else if (col[bel[b]] == 1) lab[b] -= d * 2; } q_n = 0; for (int v = 1; v <= n; v++) if (lab[v] == 0) // all unmatched vertices' labels are zero! cheers! return false; for (int x = 1; x <= n_x; x++) if (bel[x] == x && slackv[x] && bel[slackv[x]] != x && e_delta(mat[slackv[x]][x]) == 0) { if (on_found_edge(mat[slackv[x]][x])) return true; } for (int b = n + 1; b <= n_x; b++) if (bel[b] == b && col[b] == 1 && lab[b] == 0) expand_blossom1(b); } return false; } void calc_max_weight_match() { for (int v = 1; v <= n; v++) mate[v] = 0; n_x = n; n_matches = 0; tot_weight = 0; bel[0] = 0; for (int v = 1; v <= n; v++) bel[v] = v, bloch[v].clear(); for (int v = 1; v <= n; v++) for (int u = 1; u <= n; u++) blofrom[v][u] = v == u ? v : 0; int w_max = 0; for (int v = 1; v <= n; v++) for (int u = 1; u <= n; u++) relax(w_max, mat[v][u].w); for (int v = 1; v <= n; v++) lab[v] = w_max; while (match()) n_matches++; for (int v = 1; v <= n; v++) if (mate[v] && mate[v] < v) tot_weight += mat[v][mate[v]].w; } /*int main()//MWM { cin>> n>> m; for (int v = 1; v <= n; v++) for (int u = 1; u <= n; u++) mat[v][u] = edge(v, u, 0); for (int i = 0; i < m; i++) { int v, u, w; cin>> v>> u>> w; mat[v][u].w = mat[u][v].w = w; } calc_max_weight_match(); cout<<tot_weight<<"\n"; for (int v = 1; v <= n; v++) cout<<mate[v]<<" "; cout<<"\n"; return 0; }*/ double MWM (int i) { int m_count = 0; int n_count = 0; for (int j = 0; j < UE; ++j) { if (association[i][j]) { n_count++;//tongji n for (int h = 0; h < UE; ++h) if (association[i][h] && (j!=h) && (j<h)) m_count++;//tongji m } } //cout<<n_count<<"\n"; //cout<<m_count<<"\n"; if (n_count % 2 == 0) { n = n_count; m = m_count; } else { n = n_count + 1; m = m_count + n; } for (int v = 1; v <= n; v++)//clear cache for (int u = 1; u <= n; u++) mat[v][u] = edge(v, u, 0); int v, u; v = 1; for (int j = 0; j < UE; ++j)//read graph { u = v+1; if (association[i][j]) { if (n_count % 2 == 1) { mat[n][v].w = mat[v][n].w = (int)((10-calculate_x(j, i))*1000000); } for (int h = 0; h < UE; ++h) if (association[i][h] && (j<h)) { mat[v][u].w = mat[u][v].w = (int)((10-calculate_xu(j, h, i))*1000000); //cout<<v<<" "<<u<<" "<<mat[v][u].w<<"\n"; u++; } v++; } } calc_max_weight_match(); /*cout<<tot_weight<<"\n"; for (int v = 1; v <= n; v++) cout<<mate[v]<<" "; cout<<"\n";*/ return 10*n/2-tot_weight/1e6;//sigma xu } double calculate_sum() { double sum = 0; for (int i = 0; i < BS; ++i) sum += RU[i]; return sum; } bool cmp(int a, int b) { return gain[ndx][a] < gain[ndx][b]; } void select_node(double percent, double given_alpha) { int BS_count_UE[BS] = {0};//count how much UEs are associted to BSs int BS_selected_number[BS];//show number of selected UE int current_BS_association[UE] = {0}; for (int i = 0; i < BS; ++i) for (int j = 0; j < UE; ++j) if (association[i][j]) BS_count_UE[i]++; for (int i = 0; i < BS; ++i) BS_selected_number[i] = (int) (BS_count_UE[i] * percent); for (int i = 0; i < BS; ++i) { int n = 0; for (int j = 0; j < UE; ++j) if (association[i][j]) current_BS_association[n++] = j; ndx = i; sort(current_BS_association, current_BS_association + BS_count_UE[i], cmp); for (int j = 0; j < BS_selected_number[i]; ++j) is_selected[current_BS_association[j]] = 1; } for (int j = 0; j < UE; ++j) if (is_selected[j]) alpha[j] = given_alpha; else alpha[j] = 1; } double get_maximum_RU(double given_percent, double given_alpha) { initialize(); select_node(given_percent, given_alpha); double RU_k[BS]; int condition_no_converge_flag = 1; while (condition_no_converge_flag) { condition_no_converge_flag = 0; for (int i = 0; i < BS; ++i) RU_k[i] = RU[i]; for (int i = 0; i < BS; ++i) RU[i] = MWM(i); for (int i = 0; i < BS; ++i) if (abs(RU_k[i] - RU[i]) > 0.0001) condition_no_converge_flag++; } sort(RU, RU+BS); for (int i = 0; i < BS; ++i) { //cout << i+1 << ":" << RU[i] << "\n"; } //cout<<"Total:"<<calculate_sum()<<"\n"; return RU[BS-1]; } int main() { read(); association[1][43] = 0; converted(); double alpha_max = 10; double alpha_min = 1; double alpha_avg; double maximum_RU; int count = 0; while (alpha_max - alpha_min > 0.000001) { alpha_avg = (alpha_max + alpha_min) / 2; maximum_RU = get_maximum_RU(1, alpha_avg); if (maximum_RU > rho_limit) alpha_max = alpha_avg; else alpha_min = alpha_avg; count++; } cout<<alpha_avg<<endl; return count; }
[ "zwyuapr1@gmail.com" ]
zwyuapr1@gmail.com
d9ff69ee9121c63a0a803da2b739088a18576d0d
543d5ce858c055686318980a2c76969ab956f74d
/CreateProcess.cpp
5ecda319815a53be92218a76f8bb3e4e54dd169c
[]
no_license
barinova/WinAPI
0a23c6c2ae907c290364a25bb69b90e80367adcf
30e05f42b095200bfff8417df5a6c7c4cdf00136
refs/heads/master
2019-07-29T13:55:51.289363
2013-08-13T10:35:16
2013-08-13T10:35:16
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
2,523
cpp
#include <windows.h> #include <iostream> #include <process.h> void commandLine() { STARTUPINFO siForCmd = {sizeof(siForCmd)}; PROCESS_INFORMATION piForCmd; TCHAR czCommandLine[] = "tasklist /FI \"imagename eq notepad.exe\""; std::cout << "notepad.exe: \n"; if(!(CreateProcess(NULL, czCommandLine, NULL, NULL, FALSE, 0, NULL, NULL, &siForCmd, &piForCmd))) { std::cout << "Not found\n"; system("PAUSE"); exit(1); } Sleep(2000);//пауза 2 сек PROCESS_INFORMATION piCurProc; std::cout << "\nID: "; std::cin >> piCurProc.dwProcessId; HANDLE processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, piCurProc.dwProcessId); if(piCurProc.hProcess) { std::cout << "Handle Notepad.exe: " << piCurProc.hProcess << std::endl; CloseHandle(processHandle); } CloseHandle(piForCmd.hProcess); CloseHandle(piForCmd.hThread); } void createProcess() { STARTUPINFO si = { sizeof(si) }; SECURITY_ATTRIBUTES saProcess, saThread; PROCESS_INFORMATION piProcessB, piProcessC; TCHAR szPath[MAX_PATH]; saProcess.nLength = sizeof(saProcess); saProcess.lpSecurityDescriptor = NULL; saProcess.bInheritHandle = TRUE; saThread.nLength = sizeof(saThread); saThread.lpSecurityDescriptor = NULL; saThread.bInheritHandle = FALSE; lstrcpy(szPath, TEXT("C:\\WINDOWS\\system32\\notepad.exe")); CreateProcess(NULL, szPath, &saProcess, &saThread, FALSE, 0, NULL, NULL, &si, &piProcessB); commandLine(); lstrcpy(szPath, TEXT("C:\\WINDOWS\\system32\\notepad.exe")); CreateProcess(NULL, szPath, NULL, NULL, TRUE, 0, NULL, NULL, &si, &piProcessC); commandLine(); CloseHandle(piProcessB.hProcess); CloseHandle(piProcessC.hProcess); CloseHandle(piProcessB.hThread); CloseHandle(piProcessC.hThread); } unsigned __stdcall tmpFunc( void * arg) // Функция потока { char ** str = (char**)arg; std::cout << str[0] << " " << str[1] << std::endl; _endthreadex( 0 ); return 0; }; void createThreads() { char * InitStr1[2] = {"First thread running!","11111"}; char * InitStr2[2] = {"Second thread running!","22222"}; unsigned uThreadIDs[2]; HANDLE hThreads[2]; hThreads[0] = (HANDLE)_beginthreadex( NULL, 0, &tmpFunc, InitStr1, 0,&uThreadIDs[0]); hThreads[1] = (HANDLE)_beginthreadex( NULL, 0, &tmpFunc, InitStr2, 0,&uThreadIDs[1]); WaitForMultipleObjects(2, hThreads, TRUE, INFINITE ); CloseHandle( hThreads[0] ); CloseHandle( hThreads[1] ); } int main(int argc, char* argv[]) { createThreads(); return 0; }
[ "barinovaanastasija@gmail.com" ]
barinovaanastasija@gmail.com
ea0356d032fb2d12bdfab5ca993acbcb71185561
c74c5870f3715120d2397827eb16de6c086cb994
/OpenGL/Texture.cpp
86f14ca0a004ebf0e11f5c1eb813333feb634566
[]
no_license
ssss3301/OpenGL
5e3057c1a2f48b4ebbb7ad3fda00cb8506417be3
edb48921b043e7416201a658d6a3e509300708fc
refs/heads/master
2020-06-04T05:36:15.193998
2019-08-15T03:18:42
2019-08-15T03:18:42
191,890,964
0
0
null
null
null
null
GB18030
C++
false
false
3,159
cpp
#include "Texture.h" #include "stb_image.h" #include <glm/glm.hpp> bool Texture::init(int width, int height, std::string& title, GLFWmonitor* monitor, GLFWwindow* share) { if (!GLApplication::init(width, height, title, monitor, share)) { return false; } setup_vao(); load_textures(); load_shaders(); return true; } void Texture::cleanup() { if (ebo != 0) { glDeleteBuffers(1, &ebo); } if (vbo != 0) { glDeleteBuffers(1, &vbo); } if (vao != 0) { glDeleteVertexArrays(1, &vao); } if (tex != 0) { glDeleteTextures(1, &tex); } if (prog != 0) { glDeleteProgram(prog); } } void Texture::render() { if (prog == 0) { return; } glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(vao); glBindTexture(GL_TEXTURE_2D, tex); /* //多个纹理 int location = glGetUniformLocation(prog, "tex"); glUniform1i(location, 0); //设置纹理对应的纹理单元 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, tex);*/ glUseProgram(prog); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); } void Texture::setup_vao() { glGenVertexArrays(1, &vao); glBindVertexArray(vao); float vertices[] = { // ---- 位置 ---- ---- 颜色 ---- - 纹理坐标 - 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // 右上 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // 右下 -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // 左下 -0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // 左上 }; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(vertices[0]), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(vertices[0]), (void*)(3 * sizeof(vertices[0]))); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(vertices[0]), (void*)(6 * sizeof(vertices[0]))); glEnableVertexAttribArray(2); unsigned int indices[] = { 3, 2, 1, 1, 3, 0 }; glGenBuffers(1, &ebo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glBindVertexArray(0); } void Texture::load_textures() { glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); int width, height, channel; unsigned char* data = stbi_load("textures/wall.jpg", &width, &height, &channel, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } stbi_image_free(data); glBindTexture(GL_TEXTURE_2D, 0); } void Texture::load_shaders() { shader_file_info shaders; shaders.vertex_shader = "shaders/tex.vert"; shaders.fragment_shader = "shaders/tex.frag"; prog = load_shader_from_file(shaders); }
[ "wangm_2009@163.com" ]
wangm_2009@163.com
9aac17fcf7762f3f43b9b5fcd4287add89540500
229f6a9ad0051ef9d5281bd0e92591c3bdd1c8de
/src/hdchain.cpp
2bb350d3b52040f82ad1951521def08a033a410b
[ "MIT" ]
permissive
connormcn37/winecoin
41f3b361e3003201be28575a7e5edb7a16db8844
382f1dee0ed7cc14d7e6b5b04faa6b21452bad1c
refs/heads/master
2020-06-16T04:20:40.023725
2019-07-06T00:09:48
2019-07-06T00:09:48
195,477,782
0
0
null
null
null
null
UTF-8
C++
false
false
6,744
cpp
// Copyright (c) 2014-2017 The Wine Core developers // Distributed under the MIT software license, see the accompanying #include "base58.h" #include "bip39.h" #include "chainparams.h" #include "hdchain.h" #include "tinyformat.h" #include "util.h" #include "utilstrencodings.h" bool CHDChain::SetNull() { LOCK(cs_accounts); nVersion = CURRENT_VERSION; id = uint256(); fCrypted = false; vchSeed.clear(); vchMnemonic.clear(); vchMnemonicPassphrase.clear(); mapAccounts.clear(); // default blank account mapAccounts.insert(std::pair<uint32_t, CHDAccount>(0, CHDAccount())); return IsNull(); } bool CHDChain::IsNull() const { return vchSeed.empty() || id == uint256(); } void CHDChain::SetCrypted(bool fCryptedIn) { fCrypted = fCryptedIn; } bool CHDChain::IsCrypted() const { return fCrypted; } void CHDChain::Debug(std::string strName) const { DBG( std::cout << __func__ << ": ---" << strName << "---" << std::endl; if (fCrypted) { std::cout << "mnemonic: ***CRYPTED***" << std::endl; std::cout << "mnemonicpassphrase: ***CRYPTED***" << std::endl; std::cout << "seed: ***CRYPTED***" << std::endl; } else { std::cout << "mnemonic: " << std::string(vchMnemonic.begin(), vchMnemonic.end()).c_str() << std::endl; std::cout << "mnemonicpassphrase: " << std::string(vchMnemonicPassphrase.begin(), vchMnemonicPassphrase.end()).c_str() << std::endl; std::cout << "seed: " << HexStr(vchSeed).c_str() << std::endl; CExtKey extkey; extkey.SetMaster(&vchSeed[0], vchSeed.size()); CBitcoinExtKey b58extkey; b58extkey.SetKey(extkey); std::cout << "extended private masterkey: " << b58extkey.ToString().c_str() << std::endl; CExtPubKey extpubkey; extpubkey = extkey.Neuter(); CBitcoinExtPubKey b58extpubkey; b58extpubkey.SetKey(extpubkey); std::cout << "extended public masterkey: " << b58extpubkey.ToString().c_str() << std::endl; } ); } bool CHDChain::SetMnemonic(const SecureVector& vchMnemonic, const SecureVector& vchMnemonicPassphrase, bool fUpdateID) { return SetMnemonic(SecureString(vchMnemonic.begin(), vchMnemonic.end()), SecureString(vchMnemonicPassphrase.begin(), vchMnemonicPassphrase.end()), fUpdateID); } bool CHDChain::SetMnemonic(const SecureString& ssMnemonic, const SecureString& ssMnemonicPassphrase, bool fUpdateID) { SecureString ssMnemonicTmp = ssMnemonic; if (fUpdateID) { // can't (re)set mnemonic if seed was already set if (!IsNull()) return false; // empty mnemonic i.e. "generate a new one" if (ssMnemonic.empty()) { ssMnemonicTmp = CMnemonic::Generate(256); } // NOTE: default mnemonic passphrase is an empty string // printf("mnemonic: %s\n", ssMnemonicTmp.c_str()); if (!CMnemonic::Check(ssMnemonicTmp)) { throw std::runtime_error(std::string(__func__) + ": invalid mnemonic: `" + std::string(ssMnemonicTmp.c_str()) + "`"); } CMnemonic::ToSeed(ssMnemonicTmp, ssMnemonicPassphrase, vchSeed); id = GetSeedHash(); } vchMnemonic = SecureVector(ssMnemonicTmp.begin(), ssMnemonicTmp.end()); vchMnemonicPassphrase = SecureVector(ssMnemonicPassphrase.begin(), ssMnemonicPassphrase.end()); return !IsNull(); } bool CHDChain::GetMnemonic(SecureVector& vchMnemonicRet, SecureVector& vchMnemonicPassphraseRet) const { // mnemonic was not set, fail if (vchMnemonic.empty()) return false; vchMnemonicRet = vchMnemonic; vchMnemonicPassphraseRet = vchMnemonicPassphrase; return true; } bool CHDChain::GetMnemonic(SecureString& ssMnemonicRet, SecureString& ssMnemonicPassphraseRet) const { // mnemonic was not set, fail if (vchMnemonic.empty()) return false; ssMnemonicRet = SecureString(vchMnemonic.begin(), vchMnemonic.end()); ssMnemonicPassphraseRet = SecureString(vchMnemonicPassphrase.begin(), vchMnemonicPassphrase.end()); return true; } bool CHDChain::SetSeed(const SecureVector& vchSeedIn, bool fUpdateID) { vchSeed = vchSeedIn; if (fUpdateID) { id = GetSeedHash(); } return !IsNull(); } SecureVector CHDChain::GetSeed() const { return vchSeed; } uint256 CHDChain::GetSeedHash() { return Hash(vchSeed.begin(), vchSeed.end()); } void CHDChain::DeriveChildExtKey(uint32_t nAccountIndex, bool fInternal, uint32_t nChildIndex, CExtKey& extKeyRet) { // Use BIP44 keypath scheme i.e. m / purpose' / coin_type' / account' / change / address_index CExtKey masterKey; //hd master key CExtKey purposeKey; //key at m/purpose' CExtKey cointypeKey; //key at m/purpose'/coin_type' CExtKey accountKey; //key at m/purpose'/coin_type'/account' CExtKey changeKey; //key at m/purpose'/coin_type'/account'/change CExtKey childKey; //key at m/purpose'/coin_type'/account'/change/address_index masterKey.SetMaster(&vchSeed[0], vchSeed.size()); // Use hardened derivation for purpose, coin_type and account // (keys >= 0x80000000 are hardened after bip32) // derive m/purpose' masterKey.Derive(purposeKey, 44 | 0x80000000); // derive m/purpose'/coin_type' purposeKey.Derive(cointypeKey, Params().ExtCoinType() | 0x80000000); // derive m/purpose'/coin_type'/account' cointypeKey.Derive(accountKey, nAccountIndex | 0x80000000); // derive m/purpose'/coin_type'/account/change accountKey.Derive(changeKey, fInternal ? 1 : 0); // derive m/purpose'/coin_type'/account/change/address_index changeKey.Derive(extKeyRet, nChildIndex); } void CHDChain::AddAccount() { LOCK(cs_accounts); mapAccounts.insert(std::pair<uint32_t, CHDAccount>(mapAccounts.size(), CHDAccount())); } bool CHDChain::GetAccount(uint32_t nAccountIndex, CHDAccount& hdAccountRet) { LOCK(cs_accounts); if (nAccountIndex > mapAccounts.size() - 1) return false; hdAccountRet = mapAccounts[nAccountIndex]; return true; } bool CHDChain::SetAccount(uint32_t nAccountIndex, const CHDAccount& hdAccount) { LOCK(cs_accounts); // can only replace existing accounts if (nAccountIndex > mapAccounts.size() - 1) return false; mapAccounts[nAccountIndex] = hdAccount; return true; } size_t CHDChain::CountAccounts() { LOCK(cs_accounts); return mapAccounts.size(); } std::string CHDPubKey::GetKeyPath() const { return strprintf("m/44'/%d'/%d'/%d/%d", Params().ExtCoinType(), nAccountIndex, nChangeIndex, extPubKey.nChild); }
[ "connormcn37@gmail.com" ]
connormcn37@gmail.com
7ce6bd91a96f3ae0827ca1a4d47f043d14c28a16
27cd4d99b345ad8cb4f9c1ed4d1a9f0d52600b18
/src/scene.hpp
d17f1522a5f630f16d282b05c95350414c9b42e5
[ "MIT" ]
permissive
thatoddmailbox/tigame
78c48e0497f07c7af69352251cdb40210902759f
31febcec29c70ba066ca7afc0ee8209cd85d5dc8
refs/heads/master
2023-06-10T16:03:50.711653
2021-07-06T03:52:21
2021-07-06T03:52:21
275,680,074
0
0
null
null
null
null
UTF-8
C++
false
false
598
hpp
#ifndef TIGAME_SCENE_HPP #define TIGAME_SCENE_HPP #include <memory> #include <vector> #include <glm/glm.hpp> #include "camera.hpp" #include "mesh.hpp" #include "object.hpp" namespace tigame { class Game; class Scene { public: Scene(); void AddObject(const std::shared_ptr<Object>& object); const std::vector<std::shared_ptr<Object>>& GetObjects(); void SetMainCamera(Camera * camera); void Update(Game * game, double dt); void Draw(); Light light; glm::vec3 clear_color; private: std::vector<std::shared_ptr<Object>> objects_; Camera * main_camera_; }; } #endif
[ "alex@studer.dev" ]
alex@studer.dev
063b32d393e954dcd054270add498586893a1a0f
4d60a8ab17c0910cdfee3e0cfdaa97fa3fba82bd
/primes.h
9ee9c42ea98467caf02bfbe45eeb5ea53de7b0f9
[]
no_license
itamakatz/AA
dbe10b6d6c402c9f320579ccd8a4184862606bbe
3701771d00724b49a276246a6cba4e932c5e307a
refs/heads/master
2019-04-08T17:19:57.758150
2017-04-23T19:38:04
2017-04-23T19:38:04
88,426,856
0
0
null
null
null
null
UTF-8
C++
false
false
304
h
#ifndef PROTEIN_MATCHING_PRIMES_H #define PROTEIN_MATCHING_PRIMES_H #include <vector> #include <stdio.h> #include <iostream> #include <typeinfo> #define NUM_OF_PRIMES 1000 extern std::vector<unsigned long int> prime_vector; void primeFactors(unsigned long int n); #endif //PROTEIN_MATCHING_PRIMES_H
[ "itamakatz@gmail.com" ]
itamakatz@gmail.com
292608a81065ff676397413c5d5bf3861c2e6334
6f891734e4424da62f565f64510e5b3592d06291
/aa/AAVSOP87C_EAR.h
8d215235cc99e604dad8b7a0d59fcab4ecab8535
[ "MIT" ]
permissive
danielkucharski/satcon
c345b1276d0d8f29b0733c877535b13a7deeb400
fed5391528929ee2666afb847d115525dfa33557
refs/heads/master
2023-06-13T03:55:34.506699
2021-07-02T23:13:01
2021-07-02T23:13:01
382,482,593
1
0
null
null
null
null
UTF-8
C++
false
false
1,405
h
/* Module : AAVSOP87C_EAR.h Purpose: Implementation for the algorithms for VSOP87 Created: PJN / 13-09-2015 History: PJN / 13-09-2015 1. Initial public release. Copyright (c) 2015 - 2017 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) All rights reserved. Copyright / Usage Details: You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) when your product is released in binary form. You are allowed to modify the source code in any way you want except you cannot modify the copyright details at the top of each module. If you want to distribute source code with your application, then you are only allowed to distribute versions released by the author. This is to maintain a single distribution point for the source code. */ /////////////////////// Macros / Defines ////////////////////////////////////// #if _MSC_VER > 1000 #pragma once #endif #ifndef __AAVSOP87C_EAR_H__ #define __AAVSOP87C_EAR_H__ #ifndef AAPLUS_EXT_CLASS #define AAPLUS_EXT_CLASS #endif ////////////////////////////// Classes //////////////////////////////////////// class AAPLUS_EXT_CLASS CAAVSOP87C_Earth { public: static double X(double JD); static double X_DASH(double JD); static double Y(double JD); static double Y_DASH(double JD); static double Z(double JD); static double Z_DASH(double JD); }; #endif //#ifndef __AAVSOP87C_EAR_H_
[ "daniel@quarc.org" ]
daniel@quarc.org
73dec04d483e4f577587ec59dfe46e76695678ea
670af94f93e7c7ef680dcc63b770a9bb7bf5071b
/libs/guibase/colormap/colormapcustomsettingdialog.cpp
51760d1016a6f5f7bb7379dca6be0948dabf2c21
[]
no_license
Leon-Zhang/prepost-gui
ef2e570bed88bd3232253cfd99e89b3eadfc661f
bff4db57df6a282f6e76e3942dbb02d66fbb5d9e
refs/heads/master
2021-01-01T19:05:10.124321
2017-07-27T04:36:47
2017-07-27T04:36:47
98,504,251
0
0
null
2017-07-27T07:00:00
2017-07-27T07:00:00
null
UTF-8
C++
false
false
11,361
cpp
#include "ui_colormapcustomsettingdialog.h" #include "../widget/coloreditwidget.h" #include "colormapcustomsettingdialog.h" #include "widget/realnumbereditwidget.h" #include <misc/lastiodirectory.h> #include <QColor> #include <QColorDialog> #include <QFileDialog> #include <QItemDelegate> #include <QMessageBox> #include <QPainter> #include <QTextStream> namespace { bool valueLessThan(const ColorMapCustomSettingColor& c1, const ColorMapCustomSettingColor& c2) { return c1.value < c2.value; } /// Delegate class to handle creating color edit widget in ColorMapCustomSettingDialog. class ColorMapCustomSettingDialogColorEditDelegate : public QItemDelegate { public: ColorMapCustomSettingDialogColorEditDelegate(QObject* parent = nullptr): QItemDelegate(parent) {} /// Paint event handler void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { if (index.column() == 1) { QVariant dat = index.model()->data(index, Qt::DisplayRole); QColor col = dat.value<QColor>(); QBrush brush(col); painter->fillRect(option.rect, brush); } else { QItemDelegate::paint(painter, option, index); } } /// Create editor QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& /*option*/, const QModelIndex& index) const { if (index.column() == 1) { return new ColorEditWidget(parent); } else { return new RealNumberEditWidget(parent); } } /// Get data from the specified editor void setEditorData(QWidget* editor, const QModelIndex& index) const { if (index.column() == 1) { QVariant dat = index.model()->data(index, Qt::DisplayRole); ColorEditWidget* w = static_cast<ColorEditWidget*>(editor); w->setColor(dat.value<QColor>()); } else { QVariant dat = index.model()->data(index, Qt::DisplayRole); RealNumberEditWidget* w = static_cast<RealNumberEditWidget*>(editor); w->setValue(dat.toDouble()); } } void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const { if (index.column() == 1) { ColorEditWidget* w = static_cast<ColorEditWidget*>(editor); QColor c = w->color(); model->setData(index, c, Qt::DisplayRole); model->setData(index, c, Qt::BackgroundRole); } else { RealNumberEditWidget* w = static_cast<RealNumberEditWidget*>(editor); double val = w->value(); model->setData(index, val, Qt::DisplayRole); } } void updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, const QModelIndex& /*index*/) const { editor->setGeometry(option.rect); } }; } // namespace ColorMapCustomSettingDialog::ColorMapCustomSettingDialog(QWidget* parent) : QDialog(parent), ui(new Ui::ColorMapCustomSettingDialog) { ui->setupUi(this); ui->arbitraryTableWidget->setColumnWidth(0, VALUEWIDTH); ui->arbitraryTableWidget->setColumnWidth(1, COLORWIDTH); ui->arbitraryTableWidget->setSelectionBehavior((QAbstractItemView::SelectRows)); ui->arbitraryTableWidget->setItemDelegate(new ColorMapCustomSettingDialogColorEditDelegate(this)); connect(ui->typeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(typeUpdated(int))); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addColor())); connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(removeColor())); connect(ui->importButton, SIGNAL(clicked()), this, SLOT(importColors())); connect(ui->exportButton, SIGNAL(clicked()), this, SLOT(exportColors())); connect(ui->arbitraryTableWidget, SIGNAL(itemChanged(QTableWidgetItem*)), this, SLOT(handleItemEdit(QTableWidgetItem*))); connect(ui->arbitraryTableWidget, SIGNAL(itemClicked(QTableWidgetItem*)), this, SLOT(handleItemClick(QTableWidgetItem*))); } ColorMapCustomSettingDialog::~ColorMapCustomSettingDialog() { delete ui; } ColorMapCustomSetting ColorMapCustomSettingDialog::customSetting() const { ColorMapCustomSetting ret; switch (ui->typeComboBox->currentIndex()) { case 0: ret.type = ColorMapCustomSetting::Type::TwoColors; ret.minColor = ui->minColorWidget->color(); ret.maxColor = ui->maxColorWidget->color(); break; case 1: ret.type = ColorMapCustomSetting::Type::ThreeColors; ret.minColor = ui->minColorWidget->color(); ret.maxColor = ui->maxColorWidget->color(); ret.midColor = ui->midColorWidget->color(); ret.midValue = ui->midValueEdit->value(); break; case 2: ret.type = ColorMapCustomSetting::Type::Arbitrary; for (int i = 0; i < ui->arbitraryTableWidget->rowCount(); ++i) { QTableWidgetItem* item = ui->arbitraryTableWidget->item(i, 0); ColorMapCustomSettingColor cc; cc.value = item->data(Qt::DisplayRole).toDouble(); cc.color = m_arbitraryColors.at(i); ret.arbitrarySettings.push_back(cc); } auto& settings = ret.arbitrarySettings; std::sort(settings.begin(), settings.end(), valueLessThan); break; } return ret; } void ColorMapCustomSettingDialog::setCustomSetting(const ColorMapCustomSetting& setting) { switch (setting.type.value()) { case ColorMapCustomSetting::Type::TwoColors: ui->typeComboBox->setCurrentIndex(0); ui->minColorWidget->setColor(setting.minColor); ui->maxColorWidget->setColor(setting.maxColor); break; case ColorMapCustomSetting::Type::ThreeColors: ui->typeComboBox->setCurrentIndex(1); ui->minColorWidget->setColor(setting.minColor); ui->maxColorWidget->setColor(setting.maxColor); ui->midColorWidget->setColor(setting.midColor); ui->midValueEdit->setValue(setting.midValue); break; case ColorMapCustomSetting::Type::Arbitrary: ui->typeComboBox->setCurrentIndex(2); ui->arbitraryTableWidget->blockSignals(true); ui->arbitraryTableWidget->setRowCount(setting.arbitrarySettings.size()); int i = 0; for (auto s : setting.arbitrarySettings) { double value = s.value; QColor col = s.color; QTableWidgetItem* item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, value); ui->arbitraryTableWidget->setItem(i, 0, item); item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, col); item->setData(Qt::BackgroundRole, col); ui->arbitraryTableWidget->setItem(i, 1, item); ui->arbitraryTableWidget->setRowHeight(i, ROWHEIGHT); m_arbitraryColors.push_back(s.color); ++ i; } ui->arbitraryTableWidget->blockSignals(false); break; } typeUpdated(ui->typeComboBox->currentIndex()); } void ColorMapCustomSettingDialog::typeUpdated(int type) { ui->minColorWidget->setDisabled(true); ui->midColorWidget->setDisabled(true); ui->maxColorWidget->setDisabled(true); ui->midValueEdit->setDisabled(true); ui->arbitraryGroupBox->setDisabled(true); switch (type) { case 0: // two colors ui->minColorWidget->setEnabled(true); ui->maxColorWidget->setEnabled(true); break; case 1: // three colors ui->minColorWidget->setEnabled(true); ui->midColorWidget->setEnabled(true); ui->maxColorWidget->setEnabled(true); ui->midValueEdit->setEnabled(true); break; case 2: // arbitrary colors ui->arbitraryGroupBox->setEnabled(true); break; } } void ColorMapCustomSettingDialog::addColor() { double val = 0; QColor col = Qt::white; int rowCount = ui->arbitraryTableWidget->rowCount(); if (rowCount > 0) { val = ui->arbitraryTableWidget->item(rowCount - 1, 0)->data(Qt::DisplayRole).toDouble() + 1; col = m_arbitraryColors.back(); } ui->arbitraryTableWidget->setRowCount(rowCount + 1); QTableWidgetItem* item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, val); ui->arbitraryTableWidget->setItem(rowCount, 0, item); m_arbitraryColors.push_back(col); item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, col); item->setData(Qt::BackgroundRole, col); ui->arbitraryTableWidget->setItem(rowCount, 1, item); ui->arbitraryTableWidget->setRowHeight(rowCount, ROWHEIGHT); } void ColorMapCustomSettingDialog::removeColor() { int row = ui->arbitraryTableWidget->currentRow(); if (row < 0) {return;} m_arbitraryColors.erase(m_arbitraryColors.begin() + row); ui->arbitraryTableWidget->removeRow(row); } void ColorMapCustomSettingDialog::importColors() { QString dir = LastIODirectory::get(); QString fname = QFileDialog::getOpenFileName(this, tr("Import Colormap Setting"), dir, tr("CSV file (*.csv)")); if (fname == "") {return;} // check whether the file exists. if (! QFile::exists(fname)) { // the file does not exists. QMessageBox::warning(this, tr("Warning"), tr("File %1 does not exists.").arg(QDir::toNativeSeparators(fname))); return; } // import colors. QFile file(fname); if (! file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::warning(this, tr("Warning"), tr("File %1 could not be opened.").arg(QDir::toNativeSeparators(fname))); return; } QList<double> values; QList<QColor> colors; QTextStream stream(&file); QString line; do { line = stream.readLine(); if (! line.isEmpty()) { QStringList pieces = line.split(QRegExp("(\\s+)|,"), QString::SkipEmptyParts); if (pieces.count() < 4) {continue;} bool ok; double val = pieces[0].toDouble(&ok); int r = pieces[1].toInt(); int g = pieces[2].toInt(); int b = pieces[3].toInt(); if (r < 0 || r > 255) {continue;} if (g < 0 || g > 255) {continue;} if (b < 0 || b > 255) {continue;} values.append(val); colors.append(QColor(r, g, b)); } } while (! line.isEmpty()); file.close(); ui->arbitraryTableWidget->blockSignals(true); ui->arbitraryTableWidget->setRowCount(values.count()); for (int i = 0; i < values.count(); ++i) { double value = values.at(i); QColor col = colors.at(i); QTableWidgetItem* item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, value); ui->arbitraryTableWidget->setItem(i, 0, item); item = new QTableWidgetItem(); item->setData(Qt::DisplayRole, col); item->setData(Qt::BackgroundRole, col); ui->arbitraryTableWidget->setItem(i, 1, item); ui->arbitraryTableWidget->setRowHeight(i, ROWHEIGHT); m_arbitraryColors.push_back(col); } ui->arbitraryTableWidget->blockSignals(false); QFileInfo info(fname); LastIODirectory::set(info.absolutePath()); } void ColorMapCustomSettingDialog::exportColors() { QString dir = LastIODirectory::get(); QString fname = QFileDialog::getSaveFileName(this, tr("Export Colormap Setting"), dir, tr("CSV file (*.csv)")); if (fname == "") {return;} // export colors. QFile file(fname); if (! file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this, tr("Warning"), tr("File %1 could not be opened.").arg(QDir::toNativeSeparators(fname))); return; } QTextStream stream(&file); QString line; for (int i = 0; i < ui->arbitraryTableWidget->rowCount(); ++i) { double val = ui->arbitraryTableWidget->item(i, 0)->data(Qt::DisplayRole).toDouble(); QColor col = m_arbitraryColors.at(i); stream << val << "," << col.red() << "," << col.green() << "," << col.blue() << endl; } file.close(); QFileInfo info(fname); LastIODirectory::set(info.absolutePath()); } void ColorMapCustomSettingDialog::handleItemEdit(QTableWidgetItem* item) { if (item->column() != 1) {return;} QColor col = item->data(Qt::DisplayRole).value<QColor>(); m_arbitraryColors[item->row()] = col; } void ColorMapCustomSettingDialog::handleItemClick(QTableWidgetItem* item) { if (item->column() != 1) {return;} QColor col = item->data(Qt::DisplayRole).value<QColor>(); QColor newcolor = QColorDialog::getColor(col, this); if (! newcolor.isValid()) {return;} item->setData(Qt::DisplayRole, newcolor); }
[ "kinoue@2cc7cdd0-1db9-4218-aa4a-1d8dad43e0f0" ]
kinoue@2cc7cdd0-1db9-4218-aa4a-1d8dad43e0f0
078d8424738c7b2974c75ff4204581882547f483
7d0f68fb588b8f15d4221bd7a1458465a808c76e
/OverlordEngine/Components/SpriteComponent.cpp
79919c60642e3aee28b6a05d6d544888dbfe2b41
[ "MIT" ]
permissive
Zakatos/Rift-Traveller
8248c0fc62af2bb1cc02768bd1c522b72b2ad5b4
cbce326e4c508f9342a4fa9904bfad2a9fcabb92
refs/heads/master
2020-03-31T22:18:53.908010
2018-10-11T15:34:24
2018-10-11T15:34:24
152,611,866
0
0
null
null
null
null
UTF-8
C++
false
false
1,809
cpp
//Precompiled Header [ALWAYS ON TOP IN CPP] #include "stdafx.h" #include "SpriteComponent.h" #include "../Diagnostics/Logger.h" #include "../Scenegraph/GameObject.h" #include "../Graphics/TextureData.h" #include "../Content/ContentManager.h" #include "../Graphics/SpriteRenderer.h" #include "../Components/TransformComponent.h" #include "../Helpers/MathHelper.h" SpriteComponent::SpriteComponent(const wstring& spriteAsset, XMFLOAT2 pivot, XMFLOAT4 color): m_SpriteAsset(spriteAsset), m_Pivot(pivot), m_Color(color), m_pTexture(nullptr), m_IsVisible(false) { } SpriteComponent::~SpriteComponent(void) { } void SpriteComponent::Initialize(const GameContext& gameContext) { UNREFERENCED_PARAMETER(gameContext); m_pTexture = ContentManager::Load<TextureData>(m_SpriteAsset); } void SpriteComponent::SetTexture(const wstring& spriteAsset) { m_SpriteAsset = spriteAsset; m_pTexture = ContentManager::Load<TextureData>(m_SpriteAsset); } void SpriteComponent::Update(const GameContext& gameContext) { UNREFERENCED_PARAMETER(gameContext); } void SpriteComponent::Draw(const GameContext& gameContext) { UNREFERENCED_PARAMETER(gameContext); if (!m_pTexture) return; if (m_IsVisible) { // Here you need to draw the SpriteComponent using the Draw of the sprite renderer SpriteRenderer * spriteRenderer{}; spriteRenderer = SpriteRenderer::GetInstance(); // The sprite renderer is a singleton // you will need to position, the rotation and the scale TransformComponent *trans = m_pGameObject->GetTransform(); XMFLOAT3 rotation{ QuaternionToEuler(trans->GetRotation()) }; spriteRenderer->Draw(m_pTexture, m_Pos, m_Color, m_Pivot, XMFLOAT2(1, 1), rotation.z, trans->GetPosition().z); // You can use the QuaternionToEuler function to help you with the z rotation } }
[ "ameletiadis@yahoo.com" ]
ameletiadis@yahoo.com
8b247a4c716c616fd5dc65add45017db1eb49d34
081b54b77d99869ddd483847fe511db201e6b8f9
/p152/p152_bf.cpp
8d15b082595a116e3deed907b154c40db47b2f1f
[]
no_license
guigui2993/Euler
6e43eb7a6d810b861187d5d87f9142998e9c1e4c
3e594a23ef5cec93372037c772d675cb5a6618c7
refs/heads/master
2022-11-06T14:51:38.101296
2022-10-24T06:50:15
2022-10-24T06:50:15
72,674,719
0
0
null
null
null
null
UTF-8
C++
false
false
3,234
cpp
/* Problem 152 Writing 1/2 as a sum of inverse squares idea: recursive function, take it or pass to the next with check if still possible Need to remove the cases where it's almost 1/2: should compute cs perfectly */ #include <iostream> #include <ctime> /* # Python stat # before Frac # 30 => 4.5s, 31: 8.73s, 32: 16.22s,... 35: 107.4s no answer # after Frac # 30 => 18s */ #DEFINE LIM 30 double revcumsum[LIM+1]; revcumsum[LIM] = 1/(LIM*LIM); for(int i=lim;i>=2;--i) revcumsum[i] = revcumsum[i+1]+1/(i**2) class Frac{ int n, d; int gcd(int a, int b){ return b == 0 ? a : gcd(b, a % b);} public: Frac(num, den):n(num),d(den){} int num() const{ return n; } int den() const{ return d; } Frac& operator+=(const Frac& rhs){ n = n * rhs.d + d * rhs.n; d = n * rhs.d; n /= gcd(n,d); d /= gcd(n,d); return *this; } Frac operator+(Frac lhs, const Frac& rhs){ return lhs *= rhs; } std::ostream& operator<<(std::ostream& out, const Fraction& f){ return out << f.num() << '/' << f.den(); } operator double(){ return n/d; } }; /* lf: list of frac for generating 1/2 cs: current sum, sum of the lf n: the new frac (1/n) to append to the list or not */ void genHalf(std::vector<bool> lf, Frac cs, int n){ //print(lf) if(n > lim || 1/2 - (double)(cs) > revcumsum[n]) return; // impossible to achieve 1/2 if(cs.num() == 1 && cs.den() == 2){// may be should put a tol std::cout << cs << " " << lf << std::endl; return; } genHalf(lf, cs, n + 1); if((double)(cs) <= 1/2-1/(n**2)){ lf[n] = 1; genHalf(lf,cs + Frac(1,n**2), n + 1); } } int main(int argc, char *argv[]){ std::clock_t begin = clock(); std::vector<bool> lf(47,0); genHalf(lf,Frac(0,1),2); std::clock_t end = clock(); double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; std::cout << elapsed_secs << " elapsed time" << std::endl; return 0; } //---------------------------------------- /* class Fraction { int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } int n, d; public: Fraction(int n, int d = 1) : n(n/gcd(n, d)), d(d/gcd(n, d)) { } int num() const { return n; } int den() const { return d; } Fraction& operator*=(const Fraction& rhs) { int new_n = n * rhs.n/gcd(n * rhs.n, d * rhs.d); d = d * rhs.d/gcd(n * rhs.n, d * rhs.d); n = new_n; return *this; } }; std::ostream& operator<<(std::ostream& out, const Fraction& f) { return out << f.num() << '/' << f.den() ; } bool operator==(const Fraction& lhs, const Fraction& rhs) { return lhs.num() == rhs.num() && lhs.den() == rhs.den(); } bool operator!=(const Fraction& lhs, const Fraction& rhs) { return !(lhs == rhs); } Fraction operator*(Fraction lhs, const Fraction& rhs) { return lhs *= rhs; } int main() { Fraction f1(3, 8), f2(1, 2), f3(10, 2); std::cout << f1 << " * " << f2 << " = " << f1 * f2 << '\n' << f2 << " * " << f3 << " = " << f2 * f3 << '\n' << 2 << " * " << f1 << " = " << 2 * f1 << '\n'; } */
[ "guigui2993@gmail.com" ]
guigui2993@gmail.com
00b6458581b05b8492f13bd893f10488cafdab17
d5b8e47fdd3cbca0d4462b35896caa315b2a983a
/examples/A6PingMQTT/MQTTHelpers.cpp
0ea69b6436a5711e8e909c5475baa9ea909a80bd
[]
no_license
mgaman/A6General
e5cd9366d77714c44e2448504dfc0c6681efa996
4970040b8cac1535a38148fc701613631377741d
refs/heads/master
2021-01-11T17:39:36.478804
2020-05-06T08:12:37
2020-05-06T08:12:37
79,815,275
5
1
null
2018-07-17T09:09:36
2017-01-23T15:08:00
C++
UTF-8
C++
false
false
3,214
cpp
/* * None of these callback routines HAVE to be implemented but it makes life a lot easier if they are * AutoConnect kicks off the whole process and can be recalled when necessary e.g. if the broker disconnects * OnConnect is called when a CONNACK was received. Do not assume that the connection was successful - check it * OnSubscribe is called when a subscribe request ccompleted successfuilly * OnMessage is called when a publish message was received. * OnPubAck is called when a publish was isssued with QOS > 0 and completed successfuilly * OnDisconnect is called when the TCP connection to the broker disconnected (for whatever reason) */ #include <Arduino.h> #include "A6Services.h" #include "A6MQTT.h" #define BROKER_ADDRESS "test.mosquitto.org" // public broker #define BROKER_PORT 1883 extern char imei[]; extern A6MQTT MQTT; extern uint16_t messageid; char *topic = "blah"; static char linebuff[50]; #define PACKET_ID 12345 /* * This function is called once in main setup * OnDisconnect below also calls AutoConnect but it is not coumpulsory */ void A6MQTT::AutoConnect() { if (gsm.connectTCPserver(BROKER_ADDRESS,BROKER_PORT)) { Serial.println("TCP up"); // connect, no userid, password or Will MQTT.waitingforConnack = connect(imei, false); } else Serial.println("TCP down"); } /* * This function ic called upon receiving a CONNACK message * Note that you should not assume that the connection was successful - check it! */ void A6MQTT::OnConnect(enum eConnectRC rc) { switch (rc) { case MQTT.CONNECT_RC_ACCEPTED: Serial.print("Connected to broker "); Serial.println(BROKER_ADDRESS); MQTT._PingNextMillis = millis() + (MQTT._KeepAliveTimeOut*1000) - 2000; MQTT.subscribe(PACKET_ID,topic,MQTT.QOS_1); Serial.print("Subscribed to topic "); Serial.println(topic); Serial.println("Publish something from your client and it should appear here."); break; case MQTT.CONNECT_RC_REFUSED_PROTOCOL: Serial.println("Protocol error"); break; case MQTT.CONNECT_RC_REFUSED_IDENTIFIER: Serial.println("Identity error"); break; } } /* * Called if the subscribe request completed OK */ void A6MQTT::OnSubscribe(uint16_t pi) { sprintf(linebuff,"Subscribed to packet id %u, response %u",PACKET_ID,pi); Serial.println(linebuff); } /* * Called when a piblish message is received. */ void A6MQTT::OnMessage(char *topic,char *message,bool dup, bool ret,A6MQTT::eQOS qos) { if (dup) Serial.print("DUP "); if (ret) Serial.print("RET "); Serial.print("QOS "); Serial.println(qos); Serial.print("Topic: ");Serial.println(topic); Serial.print("Message: ");Serial.println(message); } /* * This function when the the client published a message with QOS > 0 and received confirmation that * publish completed OK */ void A6MQTT::OnPubAck(uint16_t mid) { sprintf(linebuff,"Message %u published, %u acknowledged",messageid,mid); Serial.println(linebuff); } /* * Called when the client is dsicinnected from the broker * My example choosed to remake tre connection */ void A6MQTT::OnDisconnect() { Serial.println("Broker disconnected"); MQTT.AutoConnect(); }
[ "davidh@zickel.net" ]
davidh@zickel.net
97c27fbce27ed81091f53703cbde2e8050275ec3
f333ef1a05872ca438bc6cea9f57d6458ab29989
/gdal/ogr/ogrsf_frmts/elastic/ogr_elastic.h
e0b080bce8f4908ac8c0d51fa2d7fcebdba0ab13
[ "MIT", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-info-zip-2005-02", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-warranty-disclaimer", "SunPro" ]
permissive
flippmoke/gdal
f85e1b27eb8c122f36ffeaf15421a91988d978f3
5b74f8a539c66b841e80a339854507ebe7cc1b8c
refs/heads/trunk
2021-01-24T02:07:03.951460
2014-07-30T19:56:09
2014-07-30T19:56:09
21,472,451
2
0
null
2014-07-21T16:39:59
2014-07-03T18:17:22
C++
UTF-8
C++
false
false
3,754
h
/****************************************************************************** * $Id$ * * Project: ElasticSearch Translator * Purpose: * Author: * ****************************************************************************** * Copyright (c) 2011, Adam Estrada * * 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 _OGR_ELASTIC_H_INCLUDED #define _OGR_ELASTIC_H_INCLUDED #include "ogrsf_frmts.h" #include "ogr_p.h" #include "cpl_hash_set.h" class OGRElasticDataSource; /************************************************************************/ /* OGRElasticLayer */ /************************************************************************/ class OGRElasticLayer : public OGRLayer { OGRFeatureDefn* poFeatureDefn; OGRSpatialReference* poSRS; OGRElasticDataSource* poDS; CPLString sIndex; void* pAttributes; char* pszLayerName; public: OGRElasticLayer(const char *pszFilename, const char* layerName, OGRElasticDataSource* poDS, OGRSpatialReference *poSRSIn, int bWriteMode = FALSE); ~OGRElasticLayer(); void ResetReading(); OGRFeature * GetNextFeature(); OGRErr CreateFeature(OGRFeature *poFeature); OGRErr CreateField(OGRFieldDefn *poField, int bApproxOK); OGRFeatureDefn * GetLayerDefn(); int TestCapability(const char *); int GetFeatureCount(int bForce); void PushIndex(); CPLString BuildMap(); }; /************************************************************************/ /* OGRElasticDataSource */ /************************************************************************/ class OGRElasticDataSource : public OGRDataSource { char* pszName; OGRElasticLayer** papoLayers; int nLayers; public: OGRElasticDataSource(); ~OGRElasticDataSource(); int Open(const char * pszFilename, int bUpdate); int Create(const char *pszFilename, char **papszOptions); const char* GetName() { return pszName; } int GetLayerCount() { return nLayers; } OGRLayer* GetLayer(int); OGRLayer * ICreateLayer(const char * pszLayerName, OGRSpatialReference *poSRS, OGRwkbGeometryType eType, char ** papszOptions); int TestCapability(const char *); void UploadFile(const CPLString &url, const CPLString &data); void DeleteIndex(const CPLString &url); int bOverwrite; int nBulkUpload; char* pszWriteMap; char* pszMapping; }; #endif /* ndef _OGR_Elastic_H_INCLUDED */
[ "even.rouault@mines-paris.org" ]
even.rouault@mines-paris.org
d9a7b37cdfcf9d1412b3596ddf4294d568556598
254429a7daec000512a8685fbb104a157c0940ca
/examples/cpp/observers/propagate/src/main.cpp
46cab8754edd000fccc9a364d1f3da0107645a35
[ "MIT" ]
permissive
ten3roberts/flecs
1bc95e3933095896d4b227eb5f06bbc8ebcc8bb6
fd73b8682b954ec443551531d6a270f1790ab0a7
refs/heads/master
2023-02-20T13:50:11.785741
2022-12-30T23:52:26
2022-12-30T23:52:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,785
cpp
#include <propagate.h> #include <iostream> // Events are propagated along relationship edges. This means that observers can // listen for events from a parent or prefab, like triggering when a component // inherited from a prefab was set. // // Event propagation happens automatically when an observer contains a filter // with the EcsUp flag set (indicating upwards traversal). Observers use the // same matching logic as queries: if a query with upwards traversal matches an // entity, so will an observer. // // Events are only propagated along acyclic relationship edges. struct Position { double x, y; }; int main(int, char *[]) { flecs::world ecs; // Create observer that listens for events from both self and parent ecs.observer<Position, Position>() .term_at(2).parent() // select 2nd Position from parent .event(flecs::OnSet) .each([](flecs::iter& it, size_t i, Position& p_self, Position& p_parent) { std::cout << " - " << it.event().name() << ": " << it.event_id().str() << ": " << it.entity(i).name() << ": " << "self: {" << p_self.x << ", " << p_self.y << "}, " << "parent: {" << p_parent.x << ", " << p_parent.y << "}\n"; }); // Create entity and parent flecs::entity p = ecs.entity("p"); flecs::entity e = ecs.entity("e").child_of(p); // Set Position on entity. This doesn't trigger the observer yet, since the // parent doesn't have Position yet. e.set<Position>({10, 20}); // Set Position on parent. This event will be propagated and trigger the // observer, as the observer query now matches. p.set<Position>({1, 2}); // Output // - OnSet: Position: e: self: {10, 20}, parent: {1, 2} }
[ "sander.mertens8@gmail.com" ]
sander.mertens8@gmail.com
3c24dc250d563ada5015ad2ec7b2e87405d1b7ca
55c7c13de11747af26b69f95426e3daf31069836
/client/uutoolbar/src/lib/6beebase/uulogging.cpp
298a72bf1d6a5fe160f956d6cf1bc45477b79ba1
[]
no_license
henrywoo/ultraie
fce86f5e3622f674253a0f96db191f14ddc2f432
9ed8fbef6f7f484e00f433ad8073149546faa7bc
refs/heads/master
2021-01-18T08:12:59.321596
2016-02-25T04:54:01
2016-02-25T04:54:01
40,107,182
2
0
null
null
null
null
UTF-8
C++
false
false
4,383
cpp
// UltraIE - Yet Another IE Add-on // Copyright (C) 2006-2010 // Simon Wu Fuheng (simonwoo2000 AT gmail.com), Singapore // Homepage: http://www.linkedin.com/in/simonwoo // // 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 <http://www.gnu.org/licenses/>. #include "uulogging_i.h" #include <time.h> #include <atlbase.h> #include <strsafe.h> #include "trace.h" #include "6bees_util.h" #include "6bees_const.h" #include "6bees_str.h" using namespace _6bees_str; bool uulogging::initialized = false; uulogging* uulogging::pinstance = NULL; cmutex uulogging::lock_; uulogging& uulogging::R(){ if(!initialized){ cguard g(lock_); if(pinstance == NULL){ static uulogging_i p_; pinstance = &p_; if(pinstance){ //make sure compiler cannot reorder initialized = true; // only set to true after creation } } } return *pinstance; } uulogging_i::uulogging_i(): lock_(), m_bopen(false), m_line(0), m_file(NULL){ wchar_t pszLoader[MAX_PATH]; GetModuleFileName(NULL, pszLoader, MAX_PATH); std::wstring logfile = PathFindFileName(pszLoader); logfile.append(L"_debug.log"); wstring fp = _6bees_util::GetUltraPath(logfile.c_str(),false); Initialize(fp.c_str()); } uulogging_i::~uulogging_i(){} bool uulogging_i::Initialize(const wchar_t* _fname){ if(m_bopen) return true; wchar_t tmpdir[MAX_PATH]; wcscpy_s(tmpdir,MAX_PATH,_fname); PathRemoveFileSpec(tmpdir); //_6beed_util::MakeSureDir(tmpdir); string fnamea_=stringmaker()<<_fname; destFile.open(fnamea_.c_str(), std::ios::out|std::ios::ate|std::ios::app); if((m_bopen = destFile.is_open())){ destFile << "Day Time Duration Thread Code Message\n" "----------- -------- ------ ---- ---------------------------------------\n" << std::endl; } return m_bopen; } void uulogging_i::Destroy(){ if (m_bopen == false) return; m_bopen = false; destFile.close(); } void uulogging_i::Set(const char* file, int line){ m_file = file; m_line = line; } void uulogging_i::Write(RmLevel level, const char* format_ptr, ...){ string fptr(format_ptr); /// @note Or it will fail for: file:///hello%20world if (fptr.find('%')!=string::npos){ fptr.erase(remove_if(fptr.begin(),fptr.end(),bind2nd(equal_to<wchar_t>(), ('%'))),fptr.end()); } const char* p = fptr.c_str(); va_list vp; va_start(vp, p); WriteImpl(level, p, vp); va_end(vp); } void uulogging_i::Write(RmLevel level, const wchar_t* format_ptr, ...){ string fptr=stringmaker(CP_ACP)<<format_ptr; /// @note Or it will fail for: file:///hello%20world if (fptr.find('%')!=string::npos){ fptr.erase(remove_if(fptr.begin(),fptr.end(),bind2nd(equal_to<wchar_t>(), (L'%'))),fptr.end()); } const char* tmp = fptr.c_str(); va_list vp; va_start(vp, tmp); WriteImpl(level, tmp, vp); va_end(vp); } void uulogging_i::Write_v(RmLevel level,const char* format_ptr, va_list& vp){ WriteImpl(level, format_ptr, vp); } /// All writes lead here. void uulogging_i::WriteImpl(RmLevel level, const char* format_ptr, va_list& vp){ static const int MAX_MESSAGE_SIZE = 1024; char message[MAX_MESSAGE_SIZE+1]; HRESULT hr = StringCbVPrintfA(message, MAX_MESSAGE_SIZE, format_ptr, vp); if(S_OK != hr){ cguard write_guard(lock_); destFile << "*** Error "<<hr<<" creating buffer for message "<<format_ptr<<std::endl; return; } // create the log entry LogRecord record(level); if(LOG_ERROR == level){ record.message = stringmaker(CP_ACP) << message << " at (" << m_file << "," << m_line << ")"; }else{ record.message = message; } cguard write_guard(lock_); record.write(destFile); }
[ "wufuheng@gmail.com" ]
wufuheng@gmail.com
13957ab105ad7f43f7c8a7b49a9916a4467ab922
16ec6f99ff3f1dc22749d2189b4d6b86d18c1d2c
/string_util.h
546363d75d1a24c040ec274a69d4a3e5dd771192
[]
no_license
NMT1985/Aurorablast3
0200e6ea65f9dbf66227d490b3f4e57b619135c2
37c7ea2ba2ab344834ac0dd1dd586865ee4d6f40
refs/heads/master
2021-06-03T00:14:34.783325
2016-08-07T16:27:49
2016-08-07T16:27:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
375
h
#include <Windows.h> #include <list> #include <string> #include <sstream> using namespace std; class CStringUtil{ public: static list<string> split(const string &str, char delim); }; list<string> CStringUtil::split(const string &str,char delim){ list<string> ret; istringstream iss(str); string tmp; while(getline(iss, tmp, delim)) ret.push_back(tmp); return ret; }
[ "666nmt666@gmail.com" ]
666nmt666@gmail.com
d86a8c0a6f5a034819152d9aeaaefbf7098c50d0
d5d923936965fdecbed96068e9c4d359d432f182
/libRedZone/src/Node/Variable.h
1662f63bb99c9acc26cd938d502c08f3d599c8fc
[ "BSD-2-Clause" ]
permissive
jcfromsiberia/RedZone
02542c8b6893408daa02d50475c5d26a4ba715b5
1adc3e78d07b366f6fa087fc847be299a4ff651c
refs/heads/master
2021-01-17T09:16:37.590696
2016-04-25T21:22:49
2016-04-25T21:22:49
21,431,855
34
5
null
null
null
null
UTF-8
C++
false
false
488
h
/* * Variable.h * * Created on: 2014 * Author: jc */ #pragma once #include <Export.h> #include "Node.h" namespace RedZone { class Fragment; class RZ_API Variable: public Node { public: Variable(); virtual void render( Writer * stream, Context * context ) const; virtual void processFragment( Fragment const * fragment ); virtual std::string name() const; virtual ~Variable(); protected: std::string m_expression; }; } /* namespace RedZone */
[ "microblast.jc@gmail.com" ]
microblast.jc@gmail.com
aff038c02c852bf709287b6e05415f6cfd08a424
f8cb1fd0c17ac6607132cd2061a83d57e45b6d59
/all_reduce_tree/networking_service/include/endnode.h
6176b24147e421af4c4d12cc0fee5f84783cc902
[]
no_license
NEWPLAN/RCL
dbfa937ea072989fbaca0e60d9f16a9552dcb8d8
1e044e9ec5dc0cf7d238281e8b4ab9c188a0da51
refs/heads/master
2023-04-28T16:25:56.551612
2021-01-20T14:21:28
2021-01-20T14:21:28
280,341,465
0
0
null
null
null
null
UTF-8
C++
false
false
714
h
#ifndef __NEWPLAN_RDMA_ENDNODE_H__ #define __NEWPLAN_RDMA_ENDNODE_H__ #include "rdma_base.h" #include "config.h" #include <vector> #include <thread> class RDMAEndNode { public: RDMAEndNode() {} virtual ~RDMAEndNode() {} public: virtual void setup(Config conf) { this->conf_ = conf; }; virtual void connect_to_peer() { pre_connect(); connecting(); post_connect(); }; virtual void run() = 0; protected: virtual void pre_connect() = 0; virtual void connecting() = 0; virtual void post_connect() = 0; protected: int root_sock = 0; struct Config conf_; std::vector<std::thread *> service_threads; }; #endif /* __NEWPLAN_RDMA_ENDNODE_H__ */
[ "enwplan001@163.com" ]
enwplan001@163.com
ceb3d42c59df401c9811a25c8371656152df6ffd
24d75ffa3af1b85325b39dc909343a8d945e9171
/SceniX/inc/nvsg/nvsg/StrippedPrimitiveSet.h
08f09455ce606499ddd709d942e3ca41e030662f
[]
no_license
assafyariv/PSG
0c2bf874166c7a7df18e8537ae5841bf8805f166
ce932ca9a72a5553f8d1826f3058e186619a4ec8
refs/heads/master
2016-08-12T02:57:17.021428
2015-09-24T17:14:51
2015-09-24T17:14:51
43,080,715
0
0
null
null
null
null
UTF-8
C++
false
false
9,553
h
// Copyright NVIDIA Corporation 2002-2011 // TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED // *AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS // OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS // BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES // WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, // BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) // ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS // BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES #pragma once /** @file */ #include "nvsgcommon.h" #include "nvsg/PrimitiveSet.h" #include "nvsg/nvsg.h" #include "nvutil/HashGenerator.h" namespace nvsg { /*! \brief Abstract base class for PrimitiveSet objects with points organized as strips. * \par Namespace: nvsg * \remarks This class holds a vector of IndexLists used in stripped primitives like LineStrips, * QuadStrips, and TriStrips. The strips are defined by a vector of IndexList elements. Each * IndexList is a std::vector<unsigned int> and represents one strip. * \sa IndependentPrimitiveSet, LineStrips, MeshedPrimitiveSet, QuadStrips, TriStrips */ class StrippedPrimitiveSet : public PrimitiveSet { public: /*! \brief Destructs a StrippedPrimitiveSet. */ NVSG_API virtual ~StrippedPrimitiveSet( void ); /*! \brief Query whether the data of this StrippedPrimitiveSet is shared with other * StrippedPrimitiveSet objects. * \return \c true, if the data of this StrippedPrimitiveSet is shared with other * StrippedPrimitiveSet objects, otherwise \c false. * \remarks A StrippedPrimitiveSet object shares it's data with another * StrippedPrimitiveSet object, if it was either instantiated as a copy of the other, using * StrippedPrimitiveSet::clone, or if it was assigned to by the other object using the * assignment operator. In that case, the two objects have the same DataID. * \sa clone, getDataID, operator=() */ NVSG_API virtual bool isDataShared( void ) const; /*! \brief Get the unique data identifier of this object. * \return A 64-bit value that uniquely identifies the embedded data. * \remarks A StrippedPrimitiveSet object shares it's data with another * StrippedPrimitiveSet object, if it was either instantiated as a copy of the other, using * StrippedPrimitiveSet::clone, or if it was assigned to by the other object using the * assignment operator. In that case, the two objects have the same DataID. * \sa clone, isDataShared, operator=() */ NVSG_API virtual DataID getDataID( void ) const; /*! \brief Query if this StrippedPrimitiveSet has strips. * \return \c true, if this StrippedPrimitiveSet has at least one IndexList, otherwise \c false. * \sa getNumberOfStrips, getStrips, setStrips */ NVSG_API bool hasStrips( void ) const; /*! \brief Get the number of strips. * \return The number of strips of this StrippedPrimitiveSet. * \sa hasStrips, getStrips, setStrips */ NVSG_API unsigned int getNumberOfStrips( void ) const; /*! \brief Get a pointer to the strips. * \return A pointer to the constant IndexList elements of this StrippedPrimitiveSet. * \sa hasStrips, getNumberOfStrips, setStrips */ NVSG_API const IndexList * getStrips() const; /*! \brief Set the strips of this StrippedPrimitiveSet. * \param strips A pointer to the constant IndexList elements to use. * \param numStrips The number of meshes. * \remarks Copies \a numStrips strips from \a strips into this StrippedPrimitiveSet. * \note The behaviour is undefined, if there are less than \a numStrips values of type * IndexList located at \a strips. * \sa hasStrips, getNumberOfStrips, getStrips */ NVSG_API void setStrips( const IndexList * strips, unsigned int numStrips ); /*! \brief Set a subset of strips of this StrippedPrimitiveSet. * \param pos The start position inside the range of pre-existing strips. * \param strips A pointer to the constant strips to use. * \param numStrips The number of strips. * \remarks Copies \a numStrips of IndexList elements from \a strips into this * StrippedPrimitiveSet, starting at position \a pos inside the range of pre-existing * strips.\n * Pre-existing strips in the range [\a pos, \a pos + \a numStrips) will be replaced. * Pre-existing strips outside this range remain untouched.\n * If you specifiy (-1) for \a pos or \a pos specifies the number of strips currently * stored, the strips pointed to by \a strips will be appended to the pre-existing strips.\n * \note The behaviour is undefined, if \a pos is neither a valid position inside the range * of pre-existing strips, nor the number of strips currently stored, nor (-1). * \note The behaviour is undefined, if there are less than \a numStrips values of type * IndexList located at \a strips. * \sa hasStrips, getNumberOfStrips, getStrips */ NVSG_API void setStrips( unsigned int pos, const IndexList * strips, unsigned int numStrips ); /*! \brief Test for equivalence with an other StrippedPrimitiveSet. * \param p A reference to the constant StrippedPrimitiveSet to test for equivalence with. * \param ignoreNames Optional parameter to ignore the names of the objects; default is \c true. * \param deepCompare Optional parameter to perform a deep comparsion; default is \c false. * \return \c true if the StrippedPrimitiveSet \a p is equivalent to \c this, otherwise \c false. * \remarks Two StrippedPrimitiveSet objects are equivalent, if they are equivalent as * PrimitiveSet, and all their IndexList elements are pairwise equal. * \note The behaviour is undefined if \a p is not an StrippedPrimitiveSet or derived from * one. * \sa PrimitiveSet */ NVSG_API virtual bool isEquivalent( const Object * p , bool ignoreNames , bool deepCompare ) const; REFLECTION_INFO_API( NVSG_API, StrippedPrimitiveSet ); protected: /*! \brief Protected constructor to prevent explicit creation. * \remarks The newly created StrippedPrimitiveSet has no strips. * \note A StrippedPrimitiveSet will not be instantiated directly, but through * instantiating a derived object like QuadStrips for example.*/ NVSG_API StrippedPrimitiveSet( void ); /*! \brief Protected copy constructor to prevent explicit creation. * \param rhs A reference to the constant StrippedPrimitiveSet to copy from. * \remarks The newly created StrippedPrimitiveSet is copied from \a rhs. * \note A StrippedPrimitiveSet will not be instantiated directly, but through * instantiating a derived object like QuadStrips for example.*/ NVSG_API StrippedPrimitiveSet( const StrippedPrimitiveSet& rhs ); /*! \brief Calculates the bounding box of this StrippedPrimitiveSet. * \return The axis-aligned bounding box of this StrippedPrimitiveSet. * \remarks This function is called by the framework when re-calculation * of the bounding box is required for this StrippedPrimitiveSet. */ NVSG_API virtual nvmath::Box3f calculateBoundingBox() const; /*! \brief Calculate the bounding sphere of this StrippedPrimitiveSet. * \return A nvmath::Sphere3f that contains the complete StrippedPrimitiveSet. * \remarks This function is called by the framework to determine a sphere that completely * contains the StrippedPrimitiveSet. */ NVSG_API virtual nvmath::Sphere3f calculateBoundingSphere() const; /*! \brief Assignment operator * \param rhs A reference to the constant StrippedPrimitiveSet to copy from. * \return A reference to the assigned StrippedPrimitiveSet. * \remarks The assignment operator calls the assignment operator of PrimitiveSet and * copies the IndexList elements. */ NVSG_API StrippedPrimitiveSet & operator=(const StrippedPrimitiveSet & rhs); /*! \brief Feed the data of this object into the provied HashGenerator. * \param hg The HashGenerator to update with the data of this object. * \sa getHashKey */ NVSG_API virtual void feedHashGenerator( nvutil::HashGenerator & hg ) const; private: nvutil::SmartPtr<nvutil::RCVector<IndexList> > m_strips; }; NVSG_API void copy( const StrippedPrimitiveSetReadLock & src, const StrippedPrimitiveSetWriteLock & dst ); // - - - - - - - - - - - - - - - - - - - - - - - - - // inlines // - - - - - - - - - - - - - - - - - - - - - - - - - inline bool StrippedPrimitiveSet::hasStrips() const { return( !m_strips->empty() ); } inline unsigned int StrippedPrimitiveSet::getNumberOfStrips() const { return( checked_cast<unsigned int>(m_strips->size()) ); } inline const IndexList * StrippedPrimitiveSet::getStrips( void ) const { NVSG_TRACE(); return( &(*m_strips)[0] ); } }
[ "assafyariv@gmail.com" ]
assafyariv@gmail.com
c59cde3c1caac9e5a4d068ef8355966cb53cb2ba
978f1df1f55fa450b6cb47a4df23f01109c59cc9
/Algorithm/Code/T3/Fibo495.cpp
8eac6c6d7d058e6385fb73c0ea4a5604b813876a
[]
no_license
legianha592/C
5e2337b3d67524890e4be94f0c01b9ef58407265
234f10403274919abbb5e39823f539c11a82f23d
refs/heads/master
2022-06-01T07:26:28.550733
2020-05-02T02:50:31
2020-05-02T02:50:31
258,418,718
0
0
null
null
null
null
UTF-8
C++
false
false
735
cpp
#include <stdio.h> using namespace std; int main() { int a[5000],b[5000],so[5000],x,max; freopen("fibo495.txt","r",stdin); freopen("fibo495.out","w",stdout); while (true) { x=0; scanf("%d",&x); if (x==0) break; for (int i=0; i<5000; i++) { a[i]=0; b[i]=0; so[i]=0; } a[0]=1; b[0]=1; max=0; for (int i=2; i<=x; i++) { for (int j=0; j<=max+1; j++) { so[j]=so[j]+a[j]+b[j]; if (so[j]>=10) { so[j]=so[j]-10; so[j+1] +=1; } } if (so[max+1]==1) max +=1; for (int j=max; j>=0; j--) { a[j]=b[j]; b[j]=so[j]; so[j]=0; } } printf("The fibonacci number for %d is ",x); for (int i=max; i>=0; i--) printf("%d",b[i]); printf("\n"); } }
[ "doantrihung592@gmail.com" ]
doantrihung592@gmail.com
78a9ee09e5b0fc20d43c72c17de46cf7d2b3099d
2f78e134c5b55c816fa8ee939f54bde4918696a5
/code/physics/staticlg.h
abc0119b476369ad41ebb0a27bd0282448c39cc4
[]
no_license
narayanr7/HeavenlySword
b53afa6a7a6c344e9a139279fbbd74bfbe70350c
a255b26020933e2336f024558fefcdddb48038b2
refs/heads/master
2022-08-23T01:32:46.029376
2020-05-26T04:45:56
2020-05-26T04:45:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,756
h
//--------------------------------------------------------------------------------------------------------- //! //! \file physics/staticlg.h //! //! DYNAMICS COMPONENT: //! Logic groups supporting the old CDynamicsStates. //! //! Author: Mustapha Bismi (mustapha.bismi@ninjatheory.com) //! Created: 2005.08.01 //! //--------------------------------------------------------------------------------------------------------- #ifndef _DYNAMICS_STATIC_LG_INC #define _DYNAMICS_STATIC_LG_INC #include "config.h" #include "logicgroup.h" namespace Physics { // --------------------------------------------------------------- // The static logic group contains static rigid bodies. // --------------------------------------------------------------- class StaticLG : public LogicGroup { public: StaticLG( const ntstd::String& p_name, CEntity* p_entity ); virtual ~StaticLG( ); virtual void Load(); virtual const GROUP_TYPE GetType( ) const; virtual void Update( const float p_timestep ); virtual void Activate( bool activateInHavok = false ); virtual void Deactivate( ); virtual RigidBody* AddRigidBody( const BodyCInfo* p_info ); // StaticLG does not supports behaviors... Update is than faster virtual void AddBehavior( Behavior* p_behavior ) {ntAssert(false); UNUSED( p_behavior);} ; //!< Behaviors can be added or removed at will. virtual void RemoveBehavior( const ntstd::String& p_behaviorID ) {ntAssert(false); UNUSED( p_behaviorID);} ; //!< Remove any behavior with that id. virtual Behavior* GetBehavior( const ntstd::String& p_behaviorID ) {return NULL; UNUSED( p_behaviorID);}; virtual void Debug_RenderCollisionInfo (); }; } #endif // _DYNAMICS_STATIC_LG_INC
[ "hopefullyidontgetbanned735@gmail.com" ]
hopefullyidontgetbanned735@gmail.com
cdb76b8f51eb3db2f3651cb4fce9c617ce21f2c7
814621dbf05f98a1d140c956c07ba5a6cd7e20bd
/src/xengine/rwlock.h
b976235b5c4c8bb4be526388aa26ba503764439b
[ "MIT" ]
permissive
sunny023/BigBang
64a308d340f1705a9161784c87c732a3a7a06dff
8a41582df5320b0c08fa4db2b143528bb219130c
refs/heads/master
2020-09-09T14:52:46.127960
2019-09-29T04:07:57
2019-09-29T04:07:57
221,476,302
1
0
MIT
2019-11-13T14:20:08
2019-11-13T14:20:07
null
UTF-8
C++
false
false
3,951
h
// Copyright (c) 2019 The Bigbang developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef XENGINE_RWLOCK_H #define XENGINE_RWLOCK_H #include <boost/noncopyable.hpp> #include <boost/thread/thread.hpp> namespace xengine { class CRWAccess : public boost::noncopyable { public: CRWAccess() : nRead(0), nWrite(0), fExclusive(false), fUpgraded(false) {} void ReadLock() { boost::unique_lock<boost::mutex> lock(mutex); while (nWrite || fUpgraded) { condRead.wait(lock); } ++nRead; } bool ReadTryLock() { boost::unique_lock<boost::mutex> lock(mutex); if (nWrite || fUpgraded) { return false; } ++nRead; return true; } void ReadUnlock() { bool fNotifyWrite = false; bool fNotifyUpgrade = false; { boost::unique_lock<boost::mutex> lock(mutex); if (--nRead == 0) { fNotifyWrite = (nWrite != 0); fNotifyUpgrade = fExclusive; } } if (fNotifyUpgrade) { condUpgrade.notify_one(); } else if (fNotifyWrite) { condWrite.notify_one(); } } void WriteLock() { boost::unique_lock<boost::mutex> lock(mutex); ++nWrite; while (nRead || fExclusive) { condWrite.wait(lock); } fExclusive = true; } void WriteUnlock() { bool fNotifyWrite = false; { boost::unique_lock<boost::mutex> lock(mutex); fNotifyWrite = (--nWrite != 0); fExclusive = false; } if (fNotifyWrite) { condWrite.notify_one(); } else { condRead.notify_all(); } } void UpgradeLock() { boost::unique_lock<boost::mutex> lock(mutex); while (fExclusive) { condRead.wait(lock); } fExclusive = true; } void UpgradeToWriteLock() { boost::unique_lock<boost::mutex> lock(mutex); fUpgraded = true; while (nRead) { condUpgrade.wait(lock); } } void UpgradeUnlock() { bool fNotifyWrite = false; { boost::unique_lock<boost::mutex> lock(mutex); fNotifyWrite = (nWrite != 0); if (!fUpgraded) { fNotifyWrite = (fNotifyWrite && nRead == 0); } fExclusive = false; fUpgraded = false; } if (fNotifyWrite) { condWrite.notify_one(); } else { condRead.notify_all(); } } protected: int nRead; int nWrite; bool fExclusive; bool fUpgraded; boost::mutex mutex; boost::condition_variable_any condRead; boost::condition_variable_any condWrite; boost::condition_variable_any condUpgrade; }; class CReadLock { public: CReadLock(CRWAccess& access) : _access(access) { _access.ReadLock(); } ~CReadLock() { _access.ReadUnlock(); } protected: CRWAccess& _access; }; class CWriteLock { public: CWriteLock(CRWAccess& access) : _access(access) { _access.WriteLock(); } ~CWriteLock() { _access.WriteUnlock(); } protected: CRWAccess& _access; }; class CUpgradeLock { public: CUpgradeLock(CRWAccess& access) : _access(access) { _access.UpgradeLock(); } ~CUpgradeLock() { _access.UpgradeUnlock(); } void Upgrade() { _access.UpgradeToWriteLock(); } protected: CRWAccess& _access; }; } // namespace xengine #endif //XENGINE_RWLOCK_H
[ "jhkghmn@gmail.com" ]
jhkghmn@gmail.com
24dd4daef81e0afa08a77e7c4f2a8d20817f2e7c
6e90b0e4b74be26c3f196227b803d6daff57805f
/tests/memory/pseudo_destructor_call.cc
ec43bda727357dc712e422f253f9c31436593f94
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
gintenlabo/etude
52472b652004383c76089f5145a7cab350b6eb05
c9e9db5cce72d560a50b1ab27a0ee675a725aefa
refs/heads/master
2016-09-07T19:08:57.455833
2013-08-09T09:54:51
2013-08-09T09:54:51
1,121,611
14
1
null
null
null
null
UTF-8
C++
false
false
2,206
cc
// // etude/memory/pseudo_destructor_call.hpp に対するテスト // というより仕様 // // Copyright (C) 2010 Takaya Saito (SubaruG) // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // #include "../../etude/memory/pseudo_destructor_call.hpp" #include <type_traits> #define STATIC_ASSERT( expr ) static_assert( expr, #expr ) template<class T> void check() { typedef etude::pseudo_destructor_call<T> pseudo_destructor_call; // 空で、かつ trivial STATIC_ASSERT(( std::is_empty<pseudo_destructor_call>::value )); STATIC_ASSERT(( std::is_trivial<pseudo_destructor_call>::value )); // 戻り値型チェック typedef typename pseudo_destructor_call::result_type result_type; pseudo_destructor_call const f = {}; STATIC_ASSERT(( std::is_same<result_type, void>::value )); STATIC_ASSERT(( std::is_same<decltype( f( std::declval<T*>() ) ), void>::value )); STATIC_ASSERT(( std::is_same<decltype( f( std::declval<T&>() ) ), void>::value )); } #include "test_utilities.hpp" struct hoge : lifetime_check<hoge> { // empty }; #include <utility> #include <memory> #include <boost/assert.hpp> int main() { check<int>(); // 組み込み型 check<char*>(); // ポインタ check<hoge>(); // ユーザ定義型 // 一通り動作のチェック // オブジェクトを構築するための領域 storage_of<hoge>::type buf; // 構築されてないことを確認 BOOST_ASSERT( !hoge::is_initialized(&buf) ); // 構築 std::unique_ptr< hoge, etude::pseudo_destructor_call<hoge> > p( ::new(&buf) hoge() ); // 構築されたことを確認 BOOST_ASSERT( hoge::is_initialized(&buf) ); // 破棄 p.reset(); // 破棄されたことを確認 BOOST_ASSERT( !hoge::is_initialized(&buf) ); // 再構築 p.reset( ::new(&buf) hoge() ); // 構築されたことを確認 BOOST_ASSERT( hoge::is_initialized(&buf) ); // 参照でも破棄できることをチェック { etude::pseudo_destructor_call<hoge> const del = {}; hoge& x = *p.release(); del( x ); } // 破棄されたことを確認 BOOST_ASSERT( !hoge::is_initialized(&buf) ); }
[ "gintensubaru@gmail.com" ]
gintensubaru@gmail.com
e11835bece90041c03bf6b10a7c4ab7fb42498f3
7d6879692a7a269b0c058073453c4bb5cbe7ac46
/Source/Display.cpp
02074135528925231e2533e58a0a4a79f222a09f
[ "MIT" ]
permissive
ShannonHG/CHIP-8-Emulator
954450ea584ee42a7c361c06f1a91fcc98841176
37a69e031d276c3ec0d170c34bcaac0450a91d7e
refs/heads/main
2023-03-24T09:17:44.371690
2021-03-16T03:27:23
2021-03-16T03:27:23
345,189,491
6
0
null
null
null
null
UTF-8
C++
false
false
1,690
cpp
#include <iostream> #include "Display.hpp" namespace SHG { Display::Display(int width, int height) { if (SDL_Init(SDL_INIT_VIDEO) < 0) { std::cout << "SDL failed to initialize! SDL Error: " << SDL_GetError() << std::endl; return; } screenWidth = width; screenHeight = height; // Since a screen size significantly larger than CHIP-8's native screen size is used, // the pixels have to be 'scaled' up in order to be rendered correctly. pixelWidth = screenWidth / LOW_RES_SCREEN_WIDTH; pixelHeight = screenHeight / LOW_RES_SCREEN_HEIGHT; window = SDL_CreateWindow("CHIP-8 Emulator", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screenWidth, screenHeight, SDL_WINDOW_SHOWN); renderer = SDL_CreateRenderer(window, 0, 0); surface = SDL_GetWindowSurface(window); } void Display::Clear() { std::fill(lowResScreenPixels, lowResScreenPixels + LOW_RES_PIXEL_COUNT, 0); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderClear(renderer); SDL_RenderPresent(renderer); } void Display::SetPixel(int x, int y, uint8_t bit) { if (x >= LOW_RES_SCREEN_WIDTH || y >= LOW_RES_SCREEN_HEIGHT) return; lowResScreenPixels[x + (y * LOW_RES_SCREEN_WIDTH)] = bit & 1; uint8_t color = (bit & 1) * 255; SDL_Rect rect; rect.x = x * pixelWidth; rect.y = y * pixelHeight; rect.w = pixelWidth; rect.h = pixelHeight; SDL_SetRenderDrawColor(renderer, color, color, color, 255); SDL_RenderFillRect(renderer, &rect); SDL_RenderPresent(renderer); } uint8_t Display::GetPixel(int x, int y) { if (x >= LOW_RES_SCREEN_WIDTH || y >= LOW_RES_SCREEN_HEIGHT) return 0; return lowResScreenPixels[x + (y * LOW_RES_SCREEN_WIDTH)]; } }
[ "s.hargrave4@gmail.com" ]
s.hargrave4@gmail.com
9a5895011147f0e46cd9e28b937972f74ce5d08d
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKit2/Shared/CoreIPCSupport/WebProcessMessageKinds.h
377117c6099e104d45c161bb53d862f6e68234e1
[]
no_license
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,158
h
/* * Copyright (C) 2010 Apple 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: * 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 WebProcessMessageKinds_h #define WebProcessMessageKinds_h // Messages sent from WebKit to the web process. #include "MessageID.h" namespace WebProcessMessage { enum Kind { SetVisitedLinkTable, VisitedLinkStateChanged, AllVisitedLinkStateChanged, LoadInjectedBundle, SetApplicationCacheDirectory, SetShouldTrackVisitedLinks, Create, RegisterURLSchemeAsEmptyDocument, #if PLATFORM(MAC) SetupAcceleratedCompositingPort, #endif #if PLATFORM(WIN) SetShouldPaintNativeControls, #endif }; } namespace CoreIPC { template<> struct MessageKindTraits<WebProcessMessage::Kind> { static const MessageClass messageClass = MessageClassWebProcess; }; } #endif // WebProcessMessageKinds_h
[ "sdevitt@rim.com" ]
sdevitt@rim.com
3e5e37c203916fb9ec1ac01b18f87af3870f2572
4315058df0fd9b4f70917fa35fa4d33244bfdd9d
/TP3 --- Test lire map et déplacement/main.cpp
13bff95c8d4c1f923697858a096e8bc1e9cd5355
[]
no_license
bmw546/TP3-----Test-lire-map-et-d-placement
451b1d0e8fc45d2fe5539fa511b33765907c346d
23703b3a7273bd8c3e95f05dedf7f1dfe44a111c
refs/heads/master
2021-08-23T11:20:39.845581
2017-12-04T17:24:37
2017-12-04T17:24:37
113,072,913
0
0
null
null
null
null
UTF-8
C++
false
false
2,085
cpp
/***************************************************************************** File : main.cpp Author: Marc-Etienne Pepin Date : 2017/11/01 Goal : Extrait des labyrinthes a partir de fichier texte Resout des labyrinthes a l'aide de : Robot qui se promene dans le labyrinthe Pile de deplacement qui contient le chemin du robot Affiche le labyrinthe dans la console ******************************************************************************/ #pragma once //////////////////// using namespace std; //////////////////// #include <chrono> #include <thread> #include <iostream> #include <string> #include "entity.h" #include "labyrinthe.h" #include "deplacement.h" #include "map.hpp" void jeux(); void main() { // ================ initialisation dah ================== string nomDeLaMap = "labyrinthe1.txt"; cout << "bienvenue dans le test dah" << endl; map<char> carte("placeholder", 1, 1); lab laby; const char* nomFichier = nomDeLaMap.c_str(); laby.readFile(carte, nomFichier); // ================ fin initialisation ================== laby.print(cout, carte); char input = 'f'; entity player(laby.posiDX(), laby.posiDY(), 'N'); carte[player.getX()][player.getY()] = 'V'; deplacement mouvement; while (input != 'n') { if (GetAsyncKeyState(VK_LEFT)) { if (player.getDirection() == 'N') mouvement.avance(carte, player); else player.setDirection('N'); } else if (GetAsyncKeyState(VK_RIGHT)) { if (player.getDirection() == 'S') mouvement.avance(carte, player); else player.setDirection('S'); } else if (GetAsyncKeyState(VK_DOWN)) { if (player.getDirection() == 'E') mouvement.avance(carte, player); else player.setDirection('E'); } else if (GetAsyncKeyState(VK_UP)) { if (player.getDirection() == 'O') mouvement.avance(carte, player); else player.setDirection('O'); } //this_thread::sleep_for(std::chrono::milliseconds(10)); system("cls"); laby.print(cout, carte); } system("pause"); } void jeux() { char input = 'f'; //entity player = player(2, 4, 'N'); while (input = 'n') { } }
[ "marc-etienne-pepin@hotmail.com" ]
marc-etienne-pepin@hotmail.com
a2eb634f9d06ab3cd6b20c7016678c88fef05a99
3dc9a2b37eb9f9849de0c2c9d9be2b73fdcfd759
/PA3/src/planet.cpp
2453daaa1c3327e7fbe9846daf698b4667221978
[]
no_license
ErylKenner/CS480Kenner
96d360a72fcd43d770db96fd105860eac6565356
961f748502e4fe40549ff624fcf870431adf17fc
refs/heads/master
2022-03-24T18:16:39.962629
2019-12-16T01:06:34
2019-12-16T01:06:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
979
cpp
#include "planet.h" Planet::Planet(Object *parent_, float orbitRadius_, float orbitRate_, float rotateRate_) : Object(parent_), orbitRadius(orbitRadius_), orbitRate(orbitRate_), rotateRate(rotateRate_){ angleInOrbit = 0.0f; rotateDirection = 1.0; orbitDirection = 1.0; } void Planet::DerivedUpdate(float dt){ //Unrotate by the parent's rotation if(parent != NULL){ model = glm::rotate(model, -parent->angle, glm::vec3(0.0, 1.0, 0.0)); } //Calculate the angle of the object angle += dt * 2 * M_PI * rotateRate * rotateDirection; //Calculate the angle the object has gone so far in orbit angleInOrbit += dt * 2 * M_PI * orbitRate * orbitDirection; //Update the object's position and rotation glm::vec3 translation(orbitRadius * cos(angleInOrbit), 0.0f, orbitRadius * sin(angleInOrbit)); model = glm::translate(model, translation); model = glm::rotate(model, angle, glm::vec3(0.0, 1.0, 0.0)); }
[ "eryl.kenner@gmail.com" ]
eryl.kenner@gmail.com
901603a941f5945f112738b7de635acd0b7643f6
4eda5347b1915958143b53d020e43f563372d296
/第11章/FileSystem/AddDirDlg.h
bb8c2eea0b5339fe084855d21f6ff1adcc5295c6
[]
no_license
natsuki-Uzu/Windows_Program
40e4380e7d08f764051104a4bbcc99e9b4ff387c
a994ffaa3174e83a7d69f2c7015dac930312afaf
refs/heads/master
2023-04-26T15:53:39.205163
2012-07-31T06:21:23
2012-07-31T06:21:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,243
h
#if !defined(AFX_ADDDIRDLG_H__7410D4B3_96A1_4226_983E_AA9CB9008A6A__INCLUDED_) #define AFX_ADDDIRDLG_H__7410D4B3_96A1_4226_983E_AA9CB9008A6A__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // AddDirDlg.h : header file // ///////////////////////////////////////////////////////////////////////////// // CAddDirDlg dialog class CAddDirDlg : public CDialog { // Construction public: CAddDirDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CAddDirDlg) enum { IDD = IDD_ADD_DIR }; CString m_SubDirName; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAddDirDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CAddDirDlg) afx_msg void OnChangeSubDirName(); virtual void OnOK(); afx_msg void OnLog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_ADDDIRDLG_H__7410D4B3_96A1_4226_983E_AA9CB9008A6A__INCLUDED_)
[ "Administrator@PRC-20120724DKO.(none)" ]
Administrator@PRC-20120724DKO.(none)
b44b84fe0023fdae4bbdcd54e0f78f772df65cc2
0081b46f52f48782d4c6e1563c91a6ba8d14bb51
/SimpleImageLoad/openCLUtilities.h
ca5df933889629533c3a2247f4cd53353cce7d25
[]
no_license
BeauJoh/SimpleImageLoad
6c3b9150606b98cfea21e1230e6b5476dc810a5a
86144791c41319b96f60cdcdd96318af11569af2
refs/heads/master
2016-09-09T23:14:38.928153
2011-07-28T07:52:10
2011-07-28T07:52:10
2,117,396
0
0
null
null
null
null
UTF-8
C++
false
false
9,684
h
// // openCLUtilities.h // Simple // // Created by Beau Johnston on 25/07/11. // Copyright 2011 University Of New England. All rights reserved. // #ifndef Simple_openCLUtilities_h #define Simple_openCLUtilities_h #if defined (__APPLE__) && defined (__MACH__) //Apple openCL build #include <OpenCL/opencl.h> #else //Nix openCL build #include <CL/opencl.h> #endif #include "FreeImage.h" #include <sys/stat.h> #define FATAL(msg)\ do {\ fprintf(stderr,"FATAL [%s:%d]:%s:%s\n", __FILE__, __LINE__, msg, strerror(errno)); \ assert(0); \ } while(0) #define SRC 1 #define DST 2 //define our data types, the following numbers denote the number of bits //e.g. int8 uses a signed 8 bit #define int8 signed char #define int16 signed short #define int32 signed int #define int64 signed long #define uint8 unsigned char #define uint16 unsigned short #define uint32 unsigned int #define uint64 unsigned long size_t RoundUp(size_t groupSize, size_t globalSize); char *print_cl_errstring(cl_int err); cl_bool there_was_an_error(cl_int err); void getGPUUnitSupportedImageFormats(cl_context context); cl_bool doesGPUSupportImageObjects(cl_device_id device_id); char *load_program_source(const char *filename); cl_bool cleanupAndKill(); cl_mem LoadImage(cl_context context, char *fileName, int &width, int &height); bool SaveImage(char *fileName, char *buffer, int width, int height); void checkErr(cl_int err, const char * name); void DisplayPlatformInfo(cl_platform_id id, cl_platform_info name, std::string str); template<typename T> void appendBitfield( T info, T value, std::string name, std::string & str) { if (info & value) { if (str.length() > 0) { str.append(" | "); } str.append(name); } } template <typename T> class InfoDevice { public: static void display( cl_device_id id, cl_device_info name, std::string str) { cl_int errNum; std::size_t paramValueSize; errNum = clGetDeviceInfo(id, name, 0, NULL, &paramValueSize); if (errNum != CL_SUCCESS) { std::cerr << "Failed to find OpenCL device info " << str << "." << std::endl; return; } T * info = (T *)alloca(sizeof(T) * paramValueSize); errNum = clGetDeviceInfo(id,name,paramValueSize,info,NULL); if (errNum != CL_SUCCESS) { std::cerr << "Failed to find OpenCL device info " << str << "." << std::endl; return; } switch (name) { case CL_DEVICE_TYPE: { std::string deviceType; appendBitfield<cl_device_type>( *(reinterpret_cast<cl_device_type*>(info)), CL_DEVICE_TYPE_CPU, "CL_DEVICE_TYPE_CPU", deviceType); appendBitfield<cl_device_type>( *(reinterpret_cast<cl_device_type*>(info)), CL_DEVICE_TYPE_GPU, "CL_DEVICE_TYPE_GPU", deviceType); appendBitfield<cl_device_type>( *(reinterpret_cast<cl_device_type*>(info)), CL_DEVICE_TYPE_ACCELERATOR, "CL_DEVICE_TYPE_ACCELERATOR", deviceType); appendBitfield<cl_device_type>( *(reinterpret_cast<cl_device_type*>(info)), CL_DEVICE_TYPE_DEFAULT, "CL_DEVICE_TYPE_DEFAULT", deviceType); std::cout << "\t\t" << str << ":\t" << deviceType << std::endl; } break; case CL_DEVICE_SINGLE_FP_CONFIG: { std::string fpType; appendBitfield<cl_device_fp_config>( *(reinterpret_cast<cl_device_fp_config*>(info)), CL_FP_DENORM, "CL_FP_DENORM", fpType); appendBitfield<cl_device_fp_config>( *(reinterpret_cast<cl_device_fp_config*>(info)), CL_FP_INF_NAN, "CL_FP_INF_NAN", fpType); appendBitfield<cl_device_fp_config>( *(reinterpret_cast<cl_device_fp_config*>(info)), CL_FP_ROUND_TO_NEAREST, "CL_FP_ROUND_TO_NEAREST", fpType); appendBitfield<cl_device_fp_config>( *(reinterpret_cast<cl_device_fp_config*>(info)), CL_FP_ROUND_TO_ZERO, "CL_FP_ROUND_TO_ZERO", fpType); appendBitfield<cl_device_fp_config>( *(reinterpret_cast<cl_device_fp_config*>(info)), CL_FP_ROUND_TO_INF, "CL_FP_ROUND_TO_INF", fpType); appendBitfield<cl_device_fp_config>( *(reinterpret_cast<cl_device_fp_config*>(info)), CL_FP_FMA, "CL_FP_FMA", fpType); appendBitfield<cl_device_fp_config>( *(reinterpret_cast<cl_device_fp_config*>(info)), CL_FP_SOFT_FLOAT, "CL_FP_SOFT_FLOAT", fpType); std::cout << "\t\t" << str << ":\t" << fpType << std::endl; } break; case CL_DEVICE_GLOBAL_MEM_CACHE_TYPE: { std::string memType; appendBitfield<cl_device_mem_cache_type>( *(reinterpret_cast<cl_device_mem_cache_type*>(info)), CL_NONE, "CL_NONE", memType); appendBitfield<cl_device_mem_cache_type>( *(reinterpret_cast<cl_device_mem_cache_type*>(info)), CL_READ_ONLY_CACHE, "CL_READ_ONLY_CACHE", memType); appendBitfield<cl_device_mem_cache_type>( *(reinterpret_cast<cl_device_mem_cache_type*>(info)), CL_READ_WRITE_CACHE, "CL_READ_WRITE_CACHE", memType); std::cout << "\t\t" << str << ":\t" << memType << std::endl; } break; case CL_DEVICE_LOCAL_MEM_TYPE: { std::string memType; appendBitfield<cl_device_local_mem_type>( *(reinterpret_cast<cl_device_local_mem_type*>(info)), CL_GLOBAL, "CL_LOCAL", memType); appendBitfield<cl_device_local_mem_type>( *(reinterpret_cast<cl_device_local_mem_type*>(info)), CL_GLOBAL, "CL_GLOBAL", memType); std::cout << "\t\t" << str << ":\t" << memType << std::endl; } break; case CL_DEVICE_EXECUTION_CAPABILITIES: { std::string memType; appendBitfield<cl_device_exec_capabilities>( *(reinterpret_cast<cl_device_exec_capabilities*>(info)), CL_EXEC_KERNEL, "CL_EXEC_KERNEL", memType); appendBitfield<cl_device_exec_capabilities>( *(reinterpret_cast<cl_device_exec_capabilities*>(info)), CL_EXEC_NATIVE_KERNEL, "CL_EXEC_NATIVE_KERNEL", memType); std::cout << "\t\t" << str << ":\t" << memType << std::endl; } break; case CL_DEVICE_QUEUE_PROPERTIES: { std::string memType; appendBitfield<cl_device_exec_capabilities>( *(reinterpret_cast<cl_device_exec_capabilities*>(info)), CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE, "CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE", memType); appendBitfield<cl_device_exec_capabilities>( *(reinterpret_cast<cl_device_exec_capabilities*>(info)), CL_QUEUE_PROFILING_ENABLE, "CL_QUEUE_PROFILING_ENABLE", memType); std::cout << "\t\t" << str << ":\t" << memType << std::endl; } break; default: std::cout << "\t\t" << str << ":\t" << *info << std::endl; break; } } }; #endif
[ "beau@inbeta.org" ]
beau@inbeta.org
0198977b3c10c35f50118876a69efa097439e038
776f81fb3ef7a7fac9bcf1ba396f5ebe37493dcf
/Codeforces/Avito Cool Challenge 2018/D 二分+dfs或最小生成树.cpp
6bab1a2648ac663174c36d166e6f2f69fe10b13b
[]
no_license
hangzhangac/Algorithm-Problem
192b39fb37a621de9d7b042a3cf42faf2ff85348
9d0d0712d4667035e38e72f2a2da129f75385b6f
refs/heads/main
2023-07-29T20:08:35.241911
2021-09-19T23:51:40
2021-09-19T23:51:40
394,736,490
0
0
null
null
null
null
UTF-8
C++
false
false
1,477
cpp
#include <algorithm> #include <iostream> #include <cstdlib> #include <cstring> #include <cstdio> #include <string> #include <queue> #include <cmath> #include <map> #include <set> #include <stack> #define mem(a,x) memset(a,x,sizeof(a)) #define gi(x) scanf("%d",&x) #define gi2(x,y) scanf("%d%d",&x,&y) #define gi3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define gll(x) scanf("%lld",&x) #define gll2(x,y) scanf("%lld%lld",&x,&y) using namespace std; const double eps=1e-8; typedef long long ll; const int MAXN=100005; const ll mod=1e9+7; const int inf=0x3f3f3f3f; vector<int>G[MAXN]; struct Node{ int u,v,w; }node[MAXN]; int book[MAXN]; int a[MAXN]; int n,m,k; int cnt=0; void dfs(int u){ book[u]=1; if(a[u])cnt++; for(int i=0;i<G[u].size();i++){ int v=G[u][i]; if(!book[v]){ dfs(v); } } } int st; bool C(int mid){ for(int i=1;i<=n;i++){ G[i].clear(); book[i]=0; } for(int i=1;i<=m;i++){ if(node[i].w<=mid&&node[i].u!=node[i].v){ G[node[i].u].push_back(node[i].v); G[node[i].v].push_back(node[i].u); } } cnt=0; dfs(st); return cnt==k; } int main(){ cin>>n>>m>>k; for(int i=1;i<=k;i++){ int x;gi(x); st=x; a[x]=1; } int l=inf,r=0; for(int i=1;i<=m;i++){ int u,v,w; gi3(u, v, w); node[i].u=u,node[i].v=v,node[i].w=w; l=min(l,w); r=max(r,w); } int ans=0; while(l<=r){ int mid=(l+r)/2; if(C(mid)){ ans=mid; r=mid-1; } else{ l=mid+1; } } for(int i=1;i<=k;i++){ printf("%d ",ans); } return 0; }
[ "hz2447@nyu.edu" ]
hz2447@nyu.edu
cf2ce7a97d67c655cb6a8a55e3a2ec187103d55c
aff4e63901d89003ac3ac5bd5a3d8a07611f25c8
/ch07/Fig07_25/fig07_25.cpp
d15d17a4fe283d405e11640d5adf0d19fe3afe0b
[]
no_license
geopaps/Deitel_code
b8e4c67b0cf6aa4b14173fdad80689827b959c09
2dfdac0a200e752443342bc11dfb519961bdb370
refs/heads/master
2023-03-30T23:56:19.536112
2023-03-27T09:27:59
2023-03-27T09:27:59
226,296,427
0
0
null
null
null
null
UTF-8
C++
false
false
4,390
cpp
// Fig. 7.25: fig07_25.cpp // Demonstrating C++ Standard Library class template vector. #include <iostream> #include <iomanip> #include <vector> using namespace std; void outputVector( const vector< int > & ); // display the vector void inputVector( vector< int > & ); // input values into the vector int main() { vector< int > integers1( 7 ); // 7-element vector< int > vector< int > integers2( 10 ); // 10-element vector< int > // print integers1 size and contents cout << "Size of vector integers1 is " << integers1.size() << "\nvector after initialization:" << endl; outputVector( integers1 ); // print integers2 size and contents cout << "\nSize of vector integers2 is " << integers2.size() << "\nvector after initialization:" << endl; outputVector( integers2 ); // input and print integers1 and integers2 cout << "\nEnter 17 integers:" << endl; inputVector( integers1 ); inputVector( integers2 ); cout << "\nAfter input, the vectors contain:\n" << "integers1:" << endl; outputVector( integers1 ); cout << "integers2:" << endl; outputVector( integers2 ); // use inequality (!=) operator with vector objects cout << "\nEvaluating: integers1 != integers2" << endl; if ( integers1 != integers2 ) cout << "integers1 and integers2 are not equal" << endl; // create vector integers3 using integers1 as an // initializer; print size and contents vector< int > integers3( integers1 ); // copy constructor cout << "\nSize of vector integers3 is " << integers3.size() << "\nvector after initialization:" << endl; outputVector( integers3 ); // use assignment (=) operator with vector objects cout << "\nAssigning integers2 to integers1:" << endl; integers1 = integers2; // assign integers2 to integers1 cout << "integers1:" << endl; outputVector( integers1 ); cout << "integers2:" << endl; outputVector( integers2 ); // use equality (==) operator with vector objects cout << "\nEvaluating: integers1 == integers2" << endl; if ( integers1 == integers2 ) cout << "integers1 and integers2 are equal" << endl; // use square brackets to create rvalue cout << "\nintegers1[5] is " << integers1[ 5 ]; // use square brackets to create lvalue cout << "\n\nAssigning 1000 to integers1[5]" << endl; integers1[ 5 ] = 1000; cout << "integers1:" << endl; outputVector( integers1 ); // attempt to use out-of-range subscript try { cout << "\nAttempt to display integers1.at( 15 )" << endl; cout << integers1.at( 15 ) << endl; // ERROR: out of range } // end try catch ( out_of_range &ex ) { cout << "An exception occurred: " << ex.what() << endl; } // end catch } // end main // output vector contents void outputVector( const vector< int > &array ) { size_t i; // declare control variable for ( i = 0; i < array.size(); ++i ) { cout << setw( 12 ) << array[ i ]; if ( ( i + 1 ) % 4 == 0 ) // 4 numbers per row of output cout << endl; } // end for if ( i % 4 != 0 ) cout << endl; } // end function outputVector // input vector contents void inputVector( vector< int > &array ) { for ( size_t i = 0; i < array.size(); ++i ) cin >> array[ i ]; } // end function inputVector /************************************************************************** * (C) Copyright 1992-2012 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * **************************************************************************/
[ "geopaps@gmail.com" ]
geopaps@gmail.com
2e02dd1c3182a90b8143f603ca3650dfbd10f145
c930c4228229931c1faffb25de05f79cded545f4
/Source/Z80MapEditor/ErrorList.cpp
f16302830e1539d2e633adc53675377e5d59c6a7
[]
no_license
saibotshamtul/WabbitStudio
a37e9c6f45bda4f14e0b733a79d367399976cf30
f9e05f783d6f70b1f036aecaa5587e340abc3187
refs/heads/master
2020-03-17T03:00:36.898184
2017-12-10T22:40:32
2017-12-10T22:40:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,385
cpp
#include "stdafx.h" extern HINSTANCE g_hInstance; static HWND hwndList = NULL; static void SetupColumns(HWND hwndList) { LVCOLUMN lvc = {0}; lvc.mask = LVCF_TEXT | LVCF_SUBITEM | LVCF_FMT | LVCF_WIDTH; lvc.iSubItem = 0; lvc.fmt = LVCFMT_LEFT; lvc.pszText = _T("File"); lvc.cx = 100; ListView_InsertColumn(hwndList, lvc.iSubItem, &lvc); lvc.iSubItem = 1; lvc.fmt = LVCFMT_RIGHT; lvc.pszText = _T("Line"); lvc.cx = 50; ListView_InsertColumn(hwndList, lvc.iSubItem, &lvc); lvc.iSubItem = 2; lvc.fmt = LVCFMT_LEFT; lvc.pszText = _T("Error text"); lvc.cx = 250; ListView_InsertColumn(hwndList, lvc.iSubItem, &lvc); } // Given SPASM's output string, returns error count int ProcessErrorsForErrorList(LPSTR lpszOutput) { int nErrors = 0; LPSTR szLine = strtok(lpszOutput, "\r\n"); while (szLine != NULL) { if (strstr(szLine, "error: ") != NULL) { LVITEMA lvi = {0}; lvi.mask = LVIF_TEXT; lvi.iItem = 0; lvi.iSubItem = 2; lvi.pszText = szLine; ListView_InsertItem(hwndList, &lvi); nErrors++; } szLine = strtok(NULL, "\r\n"); } return nErrors; } HWND CreateErrorList(HWND hwnd) { hwndList = CreateWindowEx( 0, WC_LISTVIEW, _T("Error list"), WS_OVERLAPPEDWINDOW | LVS_REPORT | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, 400, 300, hwnd, NULL, g_hInstance, NULL); SetupColumns(hwndList); return hwndList; }
[ "robertkuhfss@gmail.com" ]
robertkuhfss@gmail.com
0117ee259da8b001603801747d3a9362409ca0e6
374e0488acd90d913720fd92c787280227f15ff5
/jt1main.cpp
99e78b65b78d578e21c6ed62680c8144f3a419ac
[]
no_license
alantany/cpprep
73e6845fe4e2f78952e376dfd7fe37702e46feb8
9f1b723b05b2dfa47b90a356c3d57f608f245699
refs/heads/master
2021-01-22T20:26:12.747131
2017-06-26T14:43:43
2017-06-26T14:43:43
85,322,287
0
0
null
null
null
null
UTF-8
C++
false
false
234
cpp
#include<iostream> #include"d:\cpp\gitrep\jt1.h" using namespace std; int main() { int x = 10, y = 20; jt1 j1; jt1 *j2=&j1; cout << jt1::plus() << endl; cout << j1.plus() << endl; cout << j2->plus() << endl; system("pause"); }
[ "alantany@gmail.com" ]
alantany@gmail.com
b9bf0f65e6469ce588852d7a9b65c189d9b930ee
d624e14c8d466d6efdd3f8b328ba782833a908b0
/HDOJ/HDOJ1089/1089.cpp
030bf2ca7893c75c9098f6c41a0fc6e7f47f9c11
[]
no_license
Oozwding/helloworld
e2408852fc609cbdddd3e49b09ca449b4bc4d6f4
224703c43a1e0c7865639cb31512cb42ce4eabfe
refs/heads/master
2020-02-26T15:44:25.338786
2016-06-16T04:51:41
2016-06-16T04:51:41
54,907,706
0
2
null
null
null
null
UTF-8
C++
false
false
6,435
cpp
/** * Filename:HDOJ1089 * Date :2016/3/19 * @Author :zwding * Describe:C++大数类模板 A+B */ #include<iostream> #include<string> #include<cstdio> #include<cstring> #include<iomanip> #include<algorithm> using namespace std; #define MAXN 9999 #define MAXSIZE 10 #define DLEN 4 class BigNum { private: int a[500]; //可以控制大数的位数 int len; //大数长度 public: BigNum(){ len = 1;memset(a,0,sizeof(a)); } //构造函数 BigNum(const int); //将一个int类型的变量转化为大数 BigNum(const char*); //将一个字符串类型的变量转化为大数 BigNum(const BigNum &); //拷贝构造函数 BigNum &operator=(const BigNum &); //重载赋值运算符,大数之间进行赋值运算 friend istream& operator>>(istream&, BigNum&); //重载输入运算符 friend ostream& operator<<(ostream&, BigNum&); //重载输出运算符 BigNum operator+(const BigNum &) const; //重载加法运算符,两个大数之间的相加运算 BigNum operator-(const BigNum &) const; //重载减法运算符,两个大数之间的相减运算 BigNum operator*(const BigNum &) const; //重载乘法运算符,两个大数之间的相乘运算 BigNum operator/(const int &) const; //重载除法运算符,大数对一个整数进行相除运算 BigNum operator^(const int &) const; //大数的n次方运算 int operator%(const int &) const; //大数对一个int类型的变量进行取模运算 bool operator>(const BigNum & T)const; //大数和另一个大数的大小比较 bool operator>(const int & t)const; //大数和一个int类型的变量的大小比较 void print(); //输出大数 }; BigNum::BigNum(const int b) //将一个int类型的变量转化为大数 { int c,d = b; len = 0; memset(a,0,sizeof(a)); while(d > MAXN) { c = d - (d / (MAXN + 1)) * (MAXN + 1); d = d / (MAXN + 1); a[len++] = c; } a[len++] = d; } BigNum::BigNum(const char*s) //将一个字符串类型的变量转化为大数 { int t,k,index,l,i; memset(a,0,sizeof(a)); l=strlen(s); len=l/DLEN; if(l%DLEN) len++; index=0; for(i=l-1;i>=0;i-=DLEN) { t=0; k=i-DLEN+1; if(k<0) k=0; for(int j=k;j<=i;j++) t=t*10+s[j]-'0'; a[index++]=t; } } BigNum::BigNum(const BigNum & T) : len(T.len) //拷贝构造函数 { int i; memset(a,0,sizeof(a)); for(i = 0 ; i < len ; i++) a[i] = T.a[i]; } BigNum & BigNum::operator=(const BigNum & n) //重载赋值运算符,大数之间进行赋值运算 { int i; len = n.len; memset(a,0,sizeof(a)); for(i = 0 ; i < len ; i++) a[i] = n.a[i]; return *this; } istream& operator>>(istream & in, BigNum & b) //重载输入运算符 { char ch[MAXSIZE*4]; int i = -1; in>>ch; int l=strlen(ch); int count=0,sum=0; for(i=l-1;i>=0;) { sum = 0; int t=1; for(int j=0;j<4&&i>=0;j++,i--,t*=10) { sum+=(ch[i]-'0')*t; } b.a[count]=sum; count++; } b.len =count++; return in; } ostream& operator<<(ostream& out, BigNum& b) //重载输出运算符 { int i; cout << b.a[b.len - 1]; for(i = b.len - 2 ; i >= 0 ; i--) { cout.width(DLEN); cout.fill('0'); cout << b.a[i]; } return out; } BigNum BigNum::operator+(const BigNum & T) const //两个大数之间的相加运算 { BigNum t(*this); int i,big; //位数 big = T.len > len ? T.len : len; for(i = 0 ; i < big ; i++) { t.a[i] +=T.a[i]; if(t.a[i] > MAXN) { t.a[i + 1]++; t.a[i] -=MAXN+1; } } if(t.a[big] != 0) t.len = big + 1; else t.len = big; return t; } BigNum BigNum::operator-(const BigNum & T) const //两个大数之间的相减运算 { int i,j,big; bool flag; BigNum t1,t2; if(*this>T) { t1=*this; t2=T; flag=0; } else { t1=T; t2=*this; flag=1; } big=t1.len; for(i = 0 ; i < big ; i++) { if(t1.a[i] < t2.a[i]) { j = i + 1; while(t1.a[j] == 0) j++; t1.a[j--]--; while(j > i) t1.a[j--] += MAXN; t1.a[i] += MAXN + 1 - t2.a[i]; } else t1.a[i] -= t2.a[i]; } t1.len = big; while(t1.a[t1.len - 1] == 0 && t1.len > 1) { t1.len--; big--; } if(flag) t1.a[big-1]=0-t1.a[big-1]; return t1; } BigNum BigNum::operator*(const BigNum & T) const //两个大数之间的相乘运算 { BigNum ret; int i,j,up; int temp,temp1; for(i = 0 ; i < len ; i++) { up = 0; for(j = 0 ; j < T.len ; j++) { temp = a[i] * T.a[j] + ret.a[i + j] + up; if(temp > MAXN) { temp1 = temp - temp / (MAXN + 1) * (MAXN + 1); up = temp / (MAXN + 1); ret.a[i + j] = temp1; } else { up = 0; ret.a[i + j] = temp; } } if(up != 0) ret.a[i + j] = up; } ret.len = i + j; while(ret.a[ret.len - 1] == 0 && ret.len > 1) ret.len--; return ret; } BigNum BigNum::operator/(const int & b) const //大数对一个整数进行相除运算 { BigNum ret; int i,down = 0; for(i = len - 1 ; i >= 0 ; i--) { ret.a[i] = (a[i] + down * (MAXN + 1)) / b; down = a[i] + down * (MAXN + 1) - ret.a[i] * b; } ret.len = len; while(ret.a[ret.len - 1] == 0 && ret.len > 1) ret.len--; return ret; } int BigNum::operator %(const int & b) const //大数对一个int类型的变量进行取模运算 { int i,d=0; for (i = len-1; i>=0; i--) { d = ((d * (MAXN+1))% b + a[i])% b; } return d; } BigNum BigNum::operator^(const int & n) const //大数的n次方运算 { BigNum t,ret(1); int i; if(n<0) exit(-1); if(n==0) return 1; if(n==1) return *this; int m=n; while(m>1) { t=*this; for( i=1;i<<1<=m;i<<=1) { t=t*t; } m-=i; ret=ret*t; if(m==1) ret=ret*(*this); } return ret; } bool BigNum::operator>(const BigNum & T) const //大数和另一个大数的大小比较 { int ln; if(len > T.len) return true; else if(len == T.len) { ln = len - 1; while(a[ln] == T.a[ln] && ln >= 0) ln--; if(ln >= 0 && a[ln] > T.a[ln]) return true; else return false; } else return false; } bool BigNum::operator >(const int & t) const //大数和一个int类型的变量的大小比较 { BigNum b(t); return *this>b; } void BigNum::print() //输出大数 { int i; cout << a[len - 1]; for(i = len - 2 ; i >= 0 ; i--) { cout.width(DLEN); cout.fill('0'); cout << a[i]; } cout << endl; } int main(void) { int a,b; int n; cin >> n; for(int i=0;i<n;i++){ scanf("%d%d",&a,&b); BigNum a1 = a; BigNum b1 = b; BigNum c = a1 + b1; c.print(); } }
[ "zwdingcoder@gmail.com" ]
zwdingcoder@gmail.com
2551ea46d00fc4cdce91f2dc6c63f399bae9f24b
97478e6083db1b7ec79680cfcfd78ed6f5895c7d
/components/favicon/core/features.h
6d6acdde80f80da3f07f7c6651c6ab6c24c08a84
[ "BSD-3-Clause" ]
permissive
zeph1912/milkomeda_chromium
94e81510e1490d504b631a29af2f1fef76110733
7b29a87147c40376bcdd1742f687534bcd0e4c78
refs/heads/master
2023-03-15T11:05:27.924423
2018-12-19T07:58:08
2018-12-19T07:58:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
566
h
// Copyright (c) 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_FAVICON_CORE_FEATURES_H_ #define COMPONENTS_FAVICON_CORE_FEATURES_H_ namespace base { struct Feature; } namespace favicon { extern const base::Feature kFaviconsFromWebManifest; extern const base::Feature kAllowPropagationOfFaviconCacheHits; extern const base::Feature kAllowDeletionOfFaviconMappings; } // namespace favicon #endif // COMPONENTS_FAVICON_CORE_FEATURES_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
2001c6a76ab67814cfd26a6505f3fb6a1e49696f
e041f6a59f5a9dc8edb301f32876abca061c9dab
/Fonts/FontFactory.cpp
a4dea528fb4f041e9f59d832e0fb0916948f1370
[]
no_license
jmfb/x-com-generations
8b12e4993f6ac0d6ad59658f5ffe77e06f5beaa6
01050f976c6fe5dee2a40cd9a285f5a42aae035c
refs/heads/master
2020-04-08T18:23:30.968806
2012-10-01T04:47:13
2012-10-01T04:47:13
32,373,578
0
0
null
null
null
null
UTF-8
C++
false
false
709
cpp
#include "FontFactory.h" #include "../Error.h" #include "FontNormal.h" #include "FontLarge.h" #include "FontTime.h" #include "FontSmall.h" #include "FontArrow.h" #include "FontUpDown.h" namespace XCom { const BaseFont& FontFactory::GetFont(FontType type) { static FontNormal normal; static FontLarge large; static FontTime time; static FontSmall small; static FontArrow arrow; static FontUpDown updown; switch(type) { case FONT_NORMAL: return normal; case FONT_LARGE: return large; case FONT_TIME: return time; case FONT_SMALL: return small; case FONT_ARROW: return arrow; case FONT_UPDOWN: return updown; } RaiseError(0, "", "Invalid font type requested from factory."); } }
[ "Jacob.Buysse@gmail.com" ]
Jacob.Buysse@gmail.com
6ed9746cad5f855f5f612a706a4561c809d7ac84
992f36f0c82132aa2512132a7c60c7e919bcf9a9
/src/validation.h
2c985ee430b7e4bc76dcbb3f56d7c7ac076d7b63
[ "MIT" ]
permissive
maylois/wurzelpfrumpft
cd93a9db76db6e0df4e406adc4c2f038b420ceda
5a5da808841410683d9261317af3c13bff745527
refs/heads/master
2021-09-05T10:26:10.252550
2018-01-26T11:43:48
2018-01-26T11:43:48
118,001,032
0
0
null
null
null
null
UTF-8
C++
false
false
22,332
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_VALIDATION_H #define BITCOIN_VALIDATION_H #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <amount.h> #include <coins.h> #include <fs.h> #include <protocol.h> // For CMessageHeader::MessageStartChars #include <policy/feerate.h> #include <script/script_error.h> #include <sync.h> #include <versionbits.h> #include <algorithm> #include <exception> #include <map> #include <set> #include <stdint.h> #include <string> #include <utility> #include <vector> #include <atomic> class CBlockIndex; class CBlockTreeDB; class CChainParams; class CCoinsViewDB; class CInv; class CConnman; class CScriptCheck; class CBlockPolicyEstimator; class CTxMemPool; class CValidationState; struct ChainTxData; struct PrecomputedTransactionData; struct LockPoints; /** Default for -whitelistrelay. */ static const bool DEFAULT_WHITELISTRELAY = true; /** Default for -whitelistforcerelay. */ static const bool DEFAULT_WHITELISTFORCERELAY = true; /** Default for -minrelaytxfee, minimum relay fee for transactions */ static const unsigned int DEFAULT_MIN_RELAY_TX_FEE = 1000; //! -maxtxfee default static const CAmount DEFAULT_TRANSACTION_MAXFEE = 0.1 * COIN; //! Discourage users to set fees higher than this amount (in satoshis) per kB static const CAmount HIGH_TX_FEE_PER_KB = 0.01 * COIN; //! -maxtxfee will warn if called with a higher fee than this amount (in satoshis) static const CAmount HIGH_MAX_TX_FEE = 100 * HIGH_TX_FEE_PER_KB; /** Default for -limitancestorcount, max number of in-mempool ancestors */ static const unsigned int DEFAULT_ANCESTOR_LIMIT = 25; /** Default for -limitancestorsize, maximum kilobytes of tx + all in-mempool ancestors */ static const unsigned int DEFAULT_ANCESTOR_SIZE_LIMIT = 101; /** Default for -limitdescendantcount, max number of in-mempool descendants */ static const unsigned int DEFAULT_DESCENDANT_LIMIT = 25; /** Default for -limitdescendantsize, maximum kilobytes of in-mempool descendants */ static const unsigned int DEFAULT_DESCENDANT_SIZE_LIMIT = 101; /** Default for -mempoolexpiry, expiration time for mempool transactions in hours */ static const unsigned int DEFAULT_MEMPOOL_EXPIRY = 336; /** Maximum kilobytes for transactions to store for processing during reorg */ static const unsigned int MAX_DISCONNECTED_TX_POOL_SIZE = 20000; /** The maximum size of a blk?????.dat file (since 0.8) */ static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */ static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */ static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB /** Maximum number of script-checking threads allowed */ static const int MAX_SCRIPTCHECK_THREADS = 16; /** -par default (number of script-checking threads, 0 = auto) */ static const int DEFAULT_SCRIPTCHECK_THREADS = 0; /** Number of blocks that can be requested at any given time from a single peer. */ static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16; /** Timeout in seconds during which a peer must stall block download progress before being disconnected. */ static const unsigned int BLOCK_STALLING_TIMEOUT = 2; /** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends * less than this number, we reached its tip. Changing this value is a protocol upgrade. */ static const unsigned int MAX_HEADERS_RESULTS = 2000; /** Maximum depth of blocks we're willing to serve as compact blocks to peers * when requested. For older blocks, a regular BLOCK response will be sent. */ static const int MAX_CMPCTBLOCK_DEPTH = 5; /** Maximum depth of blocks we're willing to respond to GETBLOCKTXN requests for. */ static const int MAX_BLOCKTXN_DEPTH = 10; /** Size of the "block download window": how far ahead of our current height do we fetch? * Larger windows tolerate larger download speed differences between peer, but increase the potential * degree of disordering of blocks on disk (which make reindexing and pruning harder). We'll probably * want to make this a per-peer adaptive value at some point. */ static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024; /** Time to wait (in seconds) between writing blocks/block index to disk. */ static const unsigned int DATABASE_WRITE_INTERVAL = 60 * 60; /** Time to wait (in seconds) between flushing chainstate to disk. */ static const unsigned int DATABASE_FLUSH_INTERVAL = 24 * 60 * 60; /** Maximum length of reject messages. */ static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111; /** Average delay between local address broadcasts in seconds. */ static const unsigned int AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL = 24 * 60 * 60; /** Average delay between peer address broadcasts in seconds. */ static const unsigned int AVG_ADDRESS_BROADCAST_INTERVAL = 30; /** Average delay between trickled inventory transmissions in seconds. * Blocks and whitelisted receivers bypass this, outbound peers get half this delay. */ static const unsigned int INVENTORY_BROADCAST_INTERVAL = 5; /** Maximum number of inventory items to send per transmission. * Limits the impact of low-fee transaction floods. */ static const unsigned int INVENTORY_BROADCAST_MAX = 7 * INVENTORY_BROADCAST_INTERVAL; /** Average delay between feefilter broadcasts in seconds. */ static const unsigned int AVG_FEEFILTER_BROADCAST_INTERVAL = 10 * 60; /** Maximum feefilter broadcast delay after significant change. */ static const unsigned int MAX_FEEFILTER_CHANGE_DELAY = 5 * 60; /** Block download timeout base, expressed in millionths of the block interval (i.e. 10 min) */ static const int64_t BLOCK_DOWNLOAD_TIMEOUT_BASE = 1000000; /** Additional block download timeout per parallel downloading peer (i.e. 5 min) */ static const int64_t BLOCK_DOWNLOAD_TIMEOUT_PER_PEER = 500000; static const int64_t DEFAULT_MAX_TIP_AGE = 30 * 24 * 60 * 60; /** Maximum age of our tip in seconds for us to be considered current for fee estimation */ static const int64_t MAX_FEE_ESTIMATION_TIP_AGE = 3 * 60 * 60; /** Default for -permitbaremultisig */ static const bool DEFAULT_PERMIT_BAREMULTISIG = true; static const bool DEFAULT_CHECKPOINTS_ENABLED = true; static const bool DEFAULT_TXINDEX = false; static const unsigned int DEFAULT_BANSCORE_THRESHOLD = 100; /** Default for -persistmempool */ static const bool DEFAULT_PERSIST_MEMPOOL = true; /** Default for -mempoolreplacement */ static const bool DEFAULT_ENABLE_REPLACEMENT = true; /** Default for using fee filter */ static const bool DEFAULT_FEEFILTER = true; /** Maximum number of headers to announce when relaying blocks with headers message.*/ static const unsigned int MAX_BLOCKS_TO_ANNOUNCE = 8; /** Maximum number of unconnecting headers announcements before DoS score */ static const int MAX_UNCONNECTING_HEADERS = 10; static const bool DEFAULT_PEERBLOOMFILTERS = true; /** Default for -stopatheight */ static const int DEFAULT_STOPATHEIGHT = 0; struct BlockHasher { size_t operator()(const uint256& hash) const { return hash.GetCheapHash(); } }; extern CScript COINBASE_FLAGS; extern CCriticalSection cs_main; extern CBlockPolicyEstimator feeEstimator; extern CTxMemPool mempool; typedef std::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap; extern BlockMap mapBlockIndex; extern uint64_t nLastBlockTx; extern uint64_t nLastBlockWeight; extern const std::string strMessageMagic; extern CWaitableCriticalSection csBestBlock; extern CConditionVariable cvBlockChange; extern std::atomic_bool fImporting; extern std::atomic_bool fReindex; extern int nScriptCheckThreads; extern bool fTxIndex; extern bool fIsBareMultisigStd; extern bool fRequireStandard; extern bool fCheckBlockIndex; extern bool fCheckpointsEnabled; extern size_t nCoinCacheUsage; /** A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) */ extern CFeeRate minRelayTxFee; /** Absolute maximum transaction fee (in satoshis) used by wallet and mempool (rejects high fee in sendrawtransaction) */ extern CAmount maxTxFee; /** If the tip is older than this (in seconds), the node is considered to be in initial block download. */ extern int64_t nMaxTipAge; extern bool fEnableReplacement; /** Block hash whose ancestors we will assume to have valid scripts without checking them. */ extern uint256 hashAssumeValid; /** Minimum work we will assume exists on some valid chain. */ extern arith_uint256 nMinimumChainWork; /** Best header we've seen so far (used for getheaders queries' starting points). */ extern CBlockIndex *pindexBestHeader; /** Minimum disk space required - used in CheckDiskSpace() */ static const uint64_t nMinDiskSpace = 52428800; /** Pruning-related variables and constants */ /** True if any block files have ever been pruned. */ extern bool fHavePruned; /** True if we're running in -prune mode. */ extern bool fPruneMode; /** Number of MiB of block files that we're trying to stay below. */ extern uint64_t nPruneTarget; /** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of chainActive.Tip() will not be pruned. */ static const unsigned int MIN_BLOCKS_TO_KEEP = 288; static const signed int DEFAULT_CHECKBLOCKS = 6; static const unsigned int DEFAULT_CHECKLEVEL = 3; // Require that user allocate at least 550MB for block & undo files (blk???.dat and rev???.dat) // At 1MB per block, 288 blocks = 288MB. // Add 15% for Undo data = 331MB // Add 20% for Orphan block rate = 397MB // We want the low water mark after pruning to be at least 397 MB and since we prune in // full block file chunks, we need the high water mark which triggers the prune to be // one 128MB block file + added 15% undo data = 147MB greater for a total of 545MB // Setting the target to > than 550MB will make it likely we can respect the target. static const uint64_t MIN_DISK_SPACE_FOR_BLOCK_FILES = 550 * 1024 * 1024; /** * Process an incoming block. This only returns after the best known valid * block is made active. Note that it does not, however, guarantee that the * specific block passed to it has been checked for validity! * * If you want to *possibly* get feedback on whether pblock is valid, you must * install a CValidationInterface (see validationinterface.h) - this will have * its BlockChecked method called whenever *any* block completes validation. * * Note that we guarantee that either the proof-of-work is valid on pblock, or * (and possibly also) BlockChecked will have been called. * * Call without cs_main held. * * @param[in] pblock The block we want to process. * @param[in] fForceProcessing Process this block even if unrequested; used for non-network block sources and whitelisted peers. * @param[out] fNewBlock A boolean which is set to indicate if the block was first received via this call * @return True if state.IsValid() */ bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptr<const CBlock> pblock, bool fForceProcessing, bool* fNewBlock); /** * Process incoming block headers. * * Call without cs_main held. * * @param[in] block The block headers themselves * @param[out] state This may be set to an Error state if any error occurred processing them * @param[in] chainparams The params for the chain we want to connect to * @param[out] ppindex If set, the pointer will be set to point to the last new block index object for the given headers * @param[out] first_invalid First header that fails validation, if one exists */ bool ProcessNewBlockHeaders(const std::vector<CBlockHeader>& block, CValidationState& state, const CChainParams& chainparams, const CBlockIndex** ppindex=nullptr, CBlockHeader *first_invalid=nullptr); /** Check whether enough disk space is available for an incoming block */ bool CheckDiskSpace(uint64_t nAdditionalBytes = 0); /** Open a block file (blk?????.dat) */ FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false); /** Translation to a filesystem path */ fs::path GetBlockPosFilename(const CDiskBlockPos &pos, const char *prefix); /** Import blocks from an external file */ bool LoadExternalBlockFile(const CChainParams& chainparams, FILE* fileIn, CDiskBlockPos *dbp = nullptr); /** Ensures we have a genesis block in the block tree, possibly writing one to disk. */ bool LoadGenesisBlock(const CChainParams& chainparams); /** Load the block tree and coins database from disk, * initializing state if we're running with -reindex. */ bool LoadBlockIndex(const CChainParams& chainparams); /** Update the chain tip based on database information. */ bool LoadChainTip(const CChainParams& chainparams); /** Unload database information */ void UnloadBlockIndex(); /** Run an instance of the script checking thread */ void ThreadScriptCheck(); /** Check whether we are doing an initial block download (synchronizing from disk or network) */ bool IsInitialBlockDownload(); /** Retrieve a transaction (from memory pool, or from disk, if possible) */ bool GetTransaction(const uint256 &hash, CTransactionRef &tx, const Consensus::Params& params, uint256 &hashBlock, bool fAllowSlow = false); /** Find the best known block, and make it the tip of the block chain */ bool ActivateBestChain(CValidationState& state, const CChainParams& chainparams, std::shared_ptr<const CBlock> pblock = std::shared_ptr<const CBlock>()); CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams); /** Guess verification progress (as a fraction between 0.0=genesis and 1.0=current tip). */ double GuessVerificationProgress(const ChainTxData& data, CBlockIndex* pindex); /** Calculate the amount of disk space the block & undo files currently use */ uint64_t CalculateCurrentUsage(); /** * Mark one block file as pruned. */ void PruneOneBlockFile(const int fileNumber); /** * Actually unlink the specified files */ void UnlinkPrunedFiles(const std::set<int>& setFilesToPrune); /** Create a new block index entry for a given block hash */ CBlockIndex * InsertBlockIndex(uint256 hash); /** Flush all state, indexes and buffers to disk. */ void FlushStateToDisk(); /** Prune block files and flush state to disk. */ void PruneAndFlush(); /** Prune block files up to a given height */ void PruneBlockFilesManual(int nManualPruneHeight); /** (try to) add transaction to memory pool * plTxnReplaced will be appended to with all transactions replaced from mempool **/ bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState &state, const CTransactionRef &tx, bool* pfMissingInputs, std::list<CTransactionRef>* plTxnReplaced, bool bypass_limits, const CAmount nAbsurdFee); /** Convert CValidationState to a human-readable message for logging */ std::string FormatStateMessage(const CValidationState &state); /** Get the BIP9 state for a given deployment at the current tip. */ ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos); /** Get the numerical statistics for the BIP9 state for a given deployment at the current tip. */ BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos); /** Get the block height at which the BIP9 deployment switched into the state for the block building on the current tip. */ int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos); /** Apply the effects of this transaction on the UTXO set represented by view */ void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, int nHeight); /** Transaction validation functions */ /** * Check if transaction will be final in the next block to be created. * * Calls IsFinalTx() with current block height and appropriate block time. * * See consensus/consensus.h for flag definitions. */ bool CheckFinalTx(const CTransaction &tx, int flags = -1); /** * Test whether the LockPoints height and time are still valid on the current chain */ bool TestLockPointValidity(const LockPoints* lp); /** * Check if transaction will be BIP 68 final in the next block to be created. * * Simulates calling SequenceLocks() with data from the tip of the current active chain. * Optionally stores in LockPoints the resulting height and time calculated and the hash * of the block needed for calculation or skips the calculation and uses the LockPoints * passed in for evaluation. * The LockPoints should not be considered valid if CheckSequenceLocks returns false. * * See consensus/consensus.h for flag definitions. */ bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp = nullptr, bool useExistingLockPoints = false); /** * Closure representing one script verification * Note that this stores references to the spending transaction */ class CScriptCheck { private: CTxOut m_tx_out; const CTransaction *ptxTo; unsigned int nIn; unsigned int nFlags; bool cacheStore; ScriptError error; PrecomputedTransactionData *txdata; public: CScriptCheck(): ptxTo(nullptr), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {} CScriptCheck(const CTxOut& outIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn, PrecomputedTransactionData* txdataIn) : m_tx_out(outIn), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR), txdata(txdataIn) { } bool operator()(); void swap(CScriptCheck &check) { std::swap(ptxTo, check.ptxTo); std::swap(m_tx_out, check.m_tx_out); std::swap(nIn, check.nIn); std::swap(nFlags, check.nFlags); std::swap(cacheStore, check.cacheStore); std::swap(error, check.error); std::swap(txdata, check.txdata); } ScriptError GetScriptError() const { return error; } }; /** Initializes the script-execution cache */ void InitScriptExecutionCache(); /** Functions for disk access for blocks */ bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos, const Consensus::Params& consensusParams); bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex, const Consensus::Params& consensusParams); /** Functions for validating blocks and updating the block tree */ /** Context-independent validity checks */ bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW = true, bool fCheckMerkleRoot = true); /** Check a block is completely valid from start to finish (only works on top of our current best block, with cs_main held) */ bool TestBlockValidity(CValidationState& state, const CChainParams& chainparams, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true); /** Check whether witness commitments are required for block. */ bool IsWitnessEnabled(const CBlockIndex* pindexPrev, const Consensus::Params& params); /** When there are blocks in the active chain with missing data, rewind the chainstate and remove them from the block index */ bool RewindBlockIndex(const CChainParams& params); /** Update uncommitted block structures (currently: only the witness nonce). This is safe for submitted blocks. */ void UpdateUncommittedBlockStructures(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams); /** Produce the necessary coinbase commitment for a block (modifies the hash, don't call for mined blocks). */ std::vector<unsigned char> GenerateCoinbaseCommitment(CBlock& block, const CBlockIndex* pindexPrev, const Consensus::Params& consensusParams); /** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */ class CVerifyDB { public: CVerifyDB(); ~CVerifyDB(); bool VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth); }; /** Replay blocks that aren't fully applied to the database. */ bool ReplayBlocks(const CChainParams& params, CCoinsView* view); /** Find the last common block between the parameter chain and a locator. */ CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator); /** Mark a block as precious and reorganize. */ bool PreciousBlock(CValidationState& state, const CChainParams& params, CBlockIndex *pindex); /** Mark a block as invalid. */ bool InvalidateBlock(CValidationState& state, const CChainParams& chainparams, CBlockIndex *pindex); /** Remove invalidity status from a block and its descendants. */ bool ResetBlockFailureFlags(CBlockIndex *pindex); /** The currently-connected chain of blocks (protected by cs_main). */ extern CChain chainActive; /** Global variable that points to the coins database (protected by cs_main) */ extern std::unique_ptr<CCoinsViewDB> pcoinsdbview; /** Global variable that points to the active CCoinsView (protected by cs_main) */ extern std::unique_ptr<CCoinsViewCache> pcoinsTip; /** Global variable that points to the active block tree (protected by cs_main) */ extern std::unique_ptr<CBlockTreeDB> pblocktree; /** * Return the spend height, which is one more than the inputs.GetBestBlock(). * While checking, GetBestBlock() refers to the parent block. (protected by cs_main) * This is also true for mempool checks. */ int GetSpendHeight(const CCoinsViewCache& inputs); extern VersionBitsCache versionbitscache; /** * Determine what nVersion a new block should use. */ int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params); /** Reject codes greater or equal to this can be returned by AcceptToMemPool * for transactions, to signal internal conditions. They cannot and should not * be sent over the P2P network. */ static const unsigned int REJECT_INTERNAL = 0x100; /** Too high fee. Can not be triggered by P2P transactions */ static const unsigned int REJECT_HIGHFEE = 0x100; /** Get block file info entry for one block file */ CBlockFileInfo* GetBlockFileInfo(size_t n); /** Dump the mempool to disk. */ bool DumpMempool(); /** Load the mempool from disk. */ bool LoadMempool(); #endif // BITCOIN_VALIDATION_H
[ "wpf@factsoft.de" ]
wpf@factsoft.de
c0d34f2674bb68e49bacdabcd02fd976861bdde4
bf77f38c1d42ce97902bd5dc0e498d7d89ab4705
/aoj/itp1/4-a.cpp
c70f37f211351bf24cc65277e3b30e339d478edf
[]
no_license
byam/algorithms
6c570c8d00ad5457346d6851f634d962b2ef744e
f3db7230655c945412774505254e2be4cbf23074
refs/heads/master
2022-05-12T16:24:39.831337
2022-04-08T13:59:07
2022-04-08T13:59:07
68,830,972
3
0
null
null
null
null
UTF-8
C++
false
false
185
cpp
#include <bits/stdc++.h> using namespace std; int main() { long long a, b; cin >> a >> b; double fb = b; printf("%d %d %.5f\n", a / b , a % b, a / fb); return 0; }
[ "bya_ganbaatar@r.recruit.co.jp" ]
bya_ganbaatar@r.recruit.co.jp
dc15bfb17287002d45a7e5765771ac624b867bdf
4dd69f3df7d32a35b3318c226f6765d3e9a63b0a
/book1/Ch3/3.5/176_3.cpp
41899f8bc38a3b92418fa6d3a779b108e9493ecb
[]
no_license
dereksodo/allcode
f921294fbb824ab59e64528cd78ccc1f3fcf218d
7d4fc735770ea5e09661824b0b0adadc7e74c762
refs/heads/master
2022-04-13T17:45:29.132307
2020-04-08T04:27:44
2020-04-08T04:27:44
197,805,259
1
1
null
null
null
null
UTF-8
C++
false
false
1,898
cpp
#include <iostream> #include <cstring> #include <cstdlib> #include <set> #include <vector> #include <map> #include <cstdio> #include <utility> #include <algorithm> #include <cmath> #include <queue> #include <stack> #include <cassert> #include <climits> #include <numeric> #include <sstream> using namespace std; typedef long long ll; #define DEBUG #ifdef DEBUG #define debug printf #else #define debug(...) #endif const int inf = 0x3f3f3f3f; const int maxn = 200010; int head[maxn],nxt[maxn],to[maxn],tot; int pd,dfn[maxn],low[maxn],sta[maxn],co[maxn],ins[maxn]; int sum[maxn],v[maxn],inx,num,n,a[maxn],b[maxn],in[maxn]; void add(int u,int v) { to[++tot] = v; nxt[tot] = head[u]; head[u] = tot; } void tarjan(int x) { dfn[x] = low[x] = ++pd; sta[++inx] = x; ins[x] = 1; for(int i = head[x];i;i = nxt[i]) { int v = to[i]; if(!dfn[v]) { tarjan(v); low[x] = min(low[x],low[v]); } else if(ins[v]) { low[x] = min(low[x],dfn[v]); } } if(low[x] == dfn[x]) { ++num; while(sta[inx + 1] != x) { co[sta[inx]] = num; ins[sta[inx]] = 0; sum[num] = min(sum[num],v[sta[inx]]); --inx; } } } int main(int argc, char const *argv[]) { int n,p,r; scanf("%d%d",&n,&p); memset(sum,inf,sizeof(sum)); memset(v,inf,sizeof(v)); for(int i = 1,x,y;i <= p; ++i) { scanf("%d%d",&x,&y); v[x] = y; } scanf("%d",&r); for(int i = 1;i <= r; ++i) { scanf("%d%d",&a[i],&b[i]); add(a[i],b[i]); } for(int i = 1;i <= n; ++i) { if(!dfn[i] && v[i] != inf) { tarjan(i); } } for(int i = 1;i <= n; ++i) { if(!dfn[i]) { printf("NO\n%d\n",i); return 0; } } printf("YES\n"); for(int i = 1;i <= n; ++i) { for(int j = head[i];j;j = nxt[j]) { int v = to[j]; if(co[i] != co[v]) { in[co[v]]++; } } } int ans = 0; for(int i = 1;i <= num; ++i) { if(!in[i]) { ans += sum[i]; } } printf("%d\n",ans); return 0; }
[ "pi*7=7.17" ]
pi*7=7.17
adc799358561e7ea60154af318dc03d008e91936
b7db4356b2c806cb1e1b8d38c223c885b6db8502
/PacMan/GUI/ITEM/mybutton.h
d9244fe395a04d266dbc9a5f70b97db93ceb0475
[]
no_license
MarcinBobinski/PacMan
a0e789243ce9644668f23b717e4bd1b22a33f4d0
895906281358505939c282e2bed70ca3ea4a1668
refs/heads/master
2023-06-11T11:22:41.115629
2021-02-09T18:28:17
2021-02-09T18:28:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
940
h
#ifndef MYBUTTON_H #define MYBUTTON_H #include <QObject> #include <QGraphicsRectItem> #include <QGraphicsSceneMouseEvent> /** * @brief The MyButton class klasa odpowiedzialna za wyswietlanie oraz dzialanie przyciskow w aplikacji */ class MyButton : public QObject, public QGraphicsRectItem { Q_OBJECT private: QGraphicsTextItem *text; public: /** * @brief MyButton Konstruktor * @param text tekst napisu * @param parent wskaznik na rodzica elementu */ explicit MyButton(QString text,QGraphicsItem *parent = nullptr); private: void mousePressEvent(QGraphicsSceneMouseEvent *event); void hoverEnterEvent(QGraphicsSceneHoverEvent *event); void hoverLeaveEvent(QGraphicsSceneHoverEvent *event); public: /** * @brief setText metoda ustawiajaca text na napisie * @param text napis */ void setText(QString text); signals: void clicked(); }; #endif // MYBUTTON_H
[ "yiomiziom@gmail.com" ]
yiomiziom@gmail.com
954ad61ff460a0347830163303bd2f470fc734bc
5bd2afeded6a39311403641533f9a8798582b5c6
/codeforces/166/E.cpp
54cdc240beef97f7b1777009eea049def9d27fc8
[]
no_license
ShahjalalShohag/ProblemSolving
19109c35fc1a38b7a895dbc4d95cbb89385b895b
3df122f13808681506839f81b06d507ae7fc17e0
refs/heads/master
2023-02-06T09:28:43.118420
2019-01-06T11:09:00
2020-12-27T14:35:25
323,168,270
31
16
null
null
null
null
UTF-8
C++
false
false
3,753
cpp
#pragma comment(linker, "/stack:200000000") #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #pragma GCC optimize("unroll-loops") #include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define ll long long #define ull unsigned long long #define ld long double #define pii pair<int,int> #define pll pair<ll,ll> #define vi vector<int> #define vll vector<ll> #define vc vector<char> #define vs vector<string> #define vpii vector< pair<int,int> > #define vpll vector< pair<ll,ll> > #define ppll pair< ll,pll > #define pllp pair< pll,ll > #define stll stack<ll> #define qll queue<ll> #define pqll priority_queue<ll> #define umap unordered_map #define uset unordered_set #define PQ priority_queue #define rep(i,n) for(i=0;i<n;i++) #define itfor(i, c) for (typeof((c).begin()) i = (c).begin(); i != (c).end(); i++) #define printa(a,L,R) for(int i=L;i<R;i++) cout<<a[i]<<(i==R-1?'\n':' ') #define printv(a) printa(a,0,a.size()) #define print2d(a,r,c) for(int i=0;i<r;i++) for(int j=0;j<c;j++) cout<<a[i][j]<<(j==c-1?'\n':' ') #define pb push_back #define MP make_pair #define UB upper_bound #define LB lower_bound #define SQ(x) ((x)*(x)) #define issq(x) (((ll)(sqrt((x))))*((ll)(sqrt((x))))==(x)) #define F first #define S second #define mem(a,x) memset(a,x,sizeof(a)) #define inf 0x3f3f3f3f #define PI 3.14159265358979323846 #define E 2.71828182845904523536 #define gamma 0.5772156649 #define nl "\n" #define lg(r,n) (int)(log2(n)/log2(r)) #define sf(a) scanf("%d",&a) #define sfl(a) scanf("%I64d",&a) #define sfc(a) scanf("%c",&a) #define sff(a,b) scanf("%d %d",&a,&b) #define sffl(a,b) scanf("%I64d %I64d",&a,&b) #define sfff(a,b,c) scanf("%d %d %d",&a,&b,&c) #define sfffl(a,b,c) scanf("%I64d %I64d %I64d",&a,&b,&c) #define pf printf #define pfi(a) pf("%d\n",&a) #define pfl(a) pf("%I64d\n",&a) #define _ccase printf("Case %d: ",++cs) #define _case cout<<"Case "<<++cs<<": " #define debug(x) cout<<#x"="<<(x)<<nl #define rev(v) reverse(v.begin(),v.end()) #define srt(v) sort(v.begin(),v.end()) #define grtsrt(v) sort(v.begin(),v.end(),greater<int>()) #define all(v) v.begin(),v.end() #define mnv(v) *min_element(v.begin(),v.end()) #define mxv(v) *max_element(v.begin(),v.end()) #define countv(v,a) count(v.begin(),v.end(),a) #define toint(a) atoi(a.c_str()) #define midlr mid=b+((e-b)>>1),l=n<<1,r=n<<11 #define fast ios_base::sync_with_stdio(false),cin.tie(NULL) string tostr(int n) {stringstream rr;rr<<n;return rr.str();} template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; const int mod=1e9+7; //ll qpow(ll n,ll k) {ll ans=1;n%=mod;while(k){if(k&1) ans=(ans*n)%mod;n=(n*n)%mod;k>>=1;}return ans%mod;} const int mxn=1e7+1; const ld eps=1e-9; long d[mxn],a[mxn],b[mxn],c[mxn]; int main() { fast; int i,j,k,n,m; cin>>n; d[0]=1; for(i=1;i<=n;i++){ d[i]=((a[i-1]+b[i-1])%mod+c[i-1])%mod; a[i]=((d[i-1]+b[i-1])%mod+c[i-1])%mod; b[i]=((d[i-1]+a[i-1])%mod+c[i-1])%mod; c[i]=((d[i-1]+a[i-1])%mod+b[i-1])%mod; } cout<<d[n]<<nl; return 0; }
[ "shahjalalshohag2014@gmail.com" ]
shahjalalshohag2014@gmail.com
ed4ab4db957362f08edea08550286e8d4250fad4
a2d3ebcb82e1e411a30bf548d331423c6be80d01
/test_2020_03_03_刷题/test_2020_03_03_刷题/test.cpp
9a12da4da9b20694932b8bf82088ae4d97c4dbf9
[]
no_license
maoyanmm/C-Advance-Plus
e8b2814aa5b22ac40092b3bd9d7b24645a63337c
3cd9ad54779c80cfbfa19c8dae9bc770c67eaaea
refs/heads/master
2020-11-24T14:05:59.286835
2020-04-11T14:33:53
2020-04-11T14:33:53
228,182,343
0
0
null
null
null
null
UTF-8
C++
false
false
618
cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* cur = head; ListNode* behind = head; ListNode* prev = NULL; while (--n && behind) { behind = behind->next; } if (behind == NULL) { return NULL; } while (behind->next) { behind = behind->next; prev = cur; cur = cur->next; } if (cur == head) { return head->next; } if (prev) { prev->next = cur->next; } return head; } };
[ "804826526@qq.com" ]
804826526@qq.com
2a84984b37cd4e3e0785786406a83a0f3183c9b5
019b1b4fc4a0c8bf0f65f5bec2431599e5de5300
/remoting/host/win/unprivileged_process_delegate.cc
8203318ca4f87317b12025f7583d0100f4bc32ec
[ "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
15,734
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // This file implements the Windows service controlling Me2Me host processes // running within user sessions. #include "remoting/host/win/unprivileged_process_delegate.h" #include <sddl.h> #include <utility> #include "base/command_line.h" #include "base/files/file.h" #include "base/logging.h" #include "base/rand_util.h" #include "base/single_thread_task_runner.h" #include "base/strings/string16.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/synchronization/lock.h" #include "base/win/scoped_handle.h" #include "base/win/windows_version.h" #include "ipc/attachment_broker.h" #include "ipc/ipc_channel.h" #include "ipc/ipc_channel_proxy.h" #include "ipc/ipc_message.h" #include "remoting/base/typed_buffer.h" #include "remoting/host/ipc_util.h" #include "remoting/host/switches.h" #include "remoting/host/win/launch_process_with_token.h" #include "remoting/host/win/security_descriptor.h" #include "remoting/host/win/window_station_and_desktop.h" #include "sandbox/win/src/restricted_token.h" using base::win::ScopedHandle; namespace remoting { namespace { // The security descriptors below are used to lock down access to the worker // process launched by UnprivilegedProcessDelegate. UnprivilegedProcessDelegate // assumes that it runs under SYSTEM. The worker process is launched under // a different account and attaches to a newly created window station. If UAC is // supported by the OS, the worker process is started at low integrity level. // UnprivilegedProcessDelegate replaces the first printf parameter in // the strings below by the logon SID assigned to the worker process. // Security descriptor of the desktop the worker process attaches to. It gives // SYSTEM and the logon SID full access to the desktop. const char kDesktopSdFormat[] = "O:SYG:SYD:(A;;0xf01ff;;;SY)(A;;0xf01ff;;;%s)"; // Mandatory label specifying low integrity level. const char kLowIntegrityMandatoryLabel[] = "S:(ML;CIOI;NW;;;LW)"; // Security descriptor of the window station the worker process attaches to. It // gives SYSTEM and the logon SID full access the window station. The child // containers and objects inherit ACE giving SYSTEM and the logon SID full // access to them as well. const char kWindowStationSdFormat[] = "O:SYG:SYD:(A;CIOIIO;GA;;;SY)" "(A;CIOIIO;GA;;;%s)(A;NP;0xf037f;;;SY)(A;NP;0xf037f;;;%s)"; // Security descriptor of the worker process. It gives access SYSTEM full access // to the process. It gives READ_CONTROL, SYNCHRONIZE, PROCESS_QUERY_INFORMATION // and PROCESS_TERMINATE rights to the built-in administrators group. const char kWorkerProcessSd[] = "O:SYG:SYD:(A;;GA;;;SY)(A;;0x120401;;;BA)"; // Security descriptor of the worker process threads. It gives access SYSTEM // full access to the threads. It gives READ_CONTROL, SYNCHRONIZE, // THREAD_QUERY_INFORMATION and THREAD_TERMINATE rights to the built-in // administrators group. const char kWorkerThreadSd[] = "O:SYG:SYD:(A;;GA;;;SY)(A;;0x120801;;;BA)"; // Creates a token with limited access that will be used to run the worker // process. bool CreateRestrictedToken(ScopedHandle* token_out) { // Create a token representing LocalService account. HANDLE temp_handle; if (!LogonUser(L"LocalService", L"NT AUTHORITY", nullptr, LOGON32_LOGON_SERVICE, LOGON32_PROVIDER_DEFAULT, &temp_handle)) { return false; } ScopedHandle token(temp_handle); sandbox::RestrictedToken restricted_token; if (restricted_token.Init(token.Get()) != ERROR_SUCCESS) return false; if (base::win::GetVersion() >= base::win::VERSION_VISTA) { // "SeChangeNotifyPrivilege" is needed to access the machine certificate // (including its private key) in the "Local Machine" cert store. This is // needed for HTTPS client third-party authentication . But the presence of // "SeChangeNotifyPrivilege" also allows it to open and manipulate objects // owned by the same user. This risk is only mitigated by setting the // process integrity level to Low, which is why it is unsafe to enable // "SeChangeNotifyPrivilege" on Windows XP where we don't have process // integrity to protect us. std::vector<base::string16> exceptions; exceptions.push_back(base::string16(L"SeChangeNotifyPrivilege")); // Remove privileges in the token. if (restricted_token.DeleteAllPrivileges(&exceptions) != ERROR_SUCCESS) return false; // Set low integrity level if supported by the OS. if (restricted_token.SetIntegrityLevel(sandbox::INTEGRITY_LEVEL_LOW) != ERROR_SUCCESS) { return false; } } else { // Remove all privileges in the token. // Since "SeChangeNotifyPrivilege" is among the privileges being removed, // the network process won't be able to acquire certificates from the local // machine store. This means third-party authentication won't work. if (restricted_token.DeleteAllPrivileges(nullptr) != ERROR_SUCCESS) return false; } // Return the resulting token. DWORD result = restricted_token.GetRestrictedToken(token_out); if (result != ERROR_SUCCESS) { LOG(ERROR) << "Failed to get the restricted token: " << result; return false; } return true; } // Creates a window station with a given name and the default desktop giving // the complete access to |logon_sid|. bool CreateWindowStationAndDesktop(ScopedSid logon_sid, WindowStationAndDesktop* handles_out) { // Convert the logon SID into a string. std::string logon_sid_string = ConvertSidToString(logon_sid.get()); if (logon_sid_string.empty()) { PLOG(ERROR) << "Failed to convert a SID to string"; return false; } // Format the security descriptors in SDDL form. std::string desktop_sddl = base::StringPrintf(kDesktopSdFormat, logon_sid_string.c_str()); std::string window_station_sddl = base::StringPrintf(kWindowStationSdFormat, logon_sid_string.c_str(), logon_sid_string.c_str()); // The worker runs at low integrity level. Make sure it will be able to attach // to the window station and desktop. if (base::win::GetVersion() >= base::win::VERSION_VISTA) { desktop_sddl += kLowIntegrityMandatoryLabel; window_station_sddl += kLowIntegrityMandatoryLabel; } // Create the desktop and window station security descriptors. ScopedSd desktop_sd = ConvertSddlToSd(desktop_sddl); ScopedSd window_station_sd = ConvertSddlToSd(window_station_sddl); if (!desktop_sd || !window_station_sd) { PLOG(ERROR) << "Failed to create a security descriptor."; return false; } // GetProcessWindowStation() returns the current handle which does not need to // be freed. HWINSTA current_window_station = GetProcessWindowStation(); // Generate a unique window station name. std::string window_station_name = base::StringPrintf( "chromoting-%d-%d", base::GetCurrentProcId(), base::RandInt(1, std::numeric_limits<int>::max())); // Make sure that a new window station will be created instead of opening // an existing one. DWORD window_station_flags = 0; if (base::win::GetVersion() >= base::win::VERSION_VISTA) window_station_flags = CWF_CREATE_ONLY; // Request full access because this handle will be inherited by the worker // process which needs full access in order to attach to the window station. DWORD desired_access = WINSTA_ALL_ACCESS | DELETE | READ_CONTROL | WRITE_DAC | WRITE_OWNER; SECURITY_ATTRIBUTES security_attributes = {0}; security_attributes.nLength = sizeof(security_attributes); security_attributes.lpSecurityDescriptor = window_station_sd.get(); security_attributes.bInheritHandle = TRUE; WindowStationAndDesktop handles; handles.SetWindowStation(CreateWindowStation( base::UTF8ToUTF16(window_station_name).c_str(), window_station_flags, desired_access, &security_attributes)); if (!handles.window_station()) { PLOG(ERROR) << "CreateWindowStation() failed"; return false; } // Switch to the new window station and create a desktop on it. if (!SetProcessWindowStation(handles.window_station())) { PLOG(ERROR) << "SetProcessWindowStation() failed"; return false; } desired_access = DESKTOP_READOBJECTS | DESKTOP_CREATEWINDOW | DESKTOP_CREATEMENU | DESKTOP_HOOKCONTROL | DESKTOP_JOURNALRECORD | DESKTOP_JOURNALPLAYBACK | DESKTOP_ENUMERATE | DESKTOP_WRITEOBJECTS | DESKTOP_SWITCHDESKTOP | DELETE | READ_CONTROL | WRITE_DAC | WRITE_OWNER; security_attributes.nLength = sizeof(security_attributes); security_attributes.lpSecurityDescriptor = desktop_sd.get(); security_attributes.bInheritHandle = TRUE; // The default desktop of the interactive window station is called "Default". // Name the created desktop the same way in case any code relies on that. // The desktop name should not make any difference though. handles.SetDesktop(CreateDesktop(L"Default", nullptr, nullptr, 0, desired_access, &security_attributes)); // Switch back to the original window station. if (!SetProcessWindowStation(current_window_station)) { PLOG(ERROR) << "SetProcessWindowStation() failed"; return false; } if (!handles.desktop()) { PLOG(ERROR) << "CreateDesktop() failed"; return false; } handles.Swap(*handles_out); return true; } } // namespace UnprivilegedProcessDelegate::UnprivilegedProcessDelegate( scoped_refptr<base::SingleThreadTaskRunner> io_task_runner, std::unique_ptr<base::CommandLine> target_command) : io_task_runner_(io_task_runner), target_command_(std::move(target_command)), event_handler_(nullptr) {} UnprivilegedProcessDelegate::~UnprivilegedProcessDelegate() { DCHECK(CalledOnValidThread()); DCHECK(!channel_); DCHECK(!worker_process_.IsValid()); } void UnprivilegedProcessDelegate::LaunchProcess( WorkerProcessLauncher* event_handler) { DCHECK(CalledOnValidThread()); DCHECK(!event_handler_); event_handler_ = event_handler; std::unique_ptr<IPC::ChannelProxy> server; // Create a restricted token that will be used to run the worker process. ScopedHandle token; if (!CreateRestrictedToken(&token)) { PLOG(ERROR) << "Failed to create a restricted LocalService token"; ReportFatalError(); return; } // Determine our logon SID, so we can grant it access to our window station // and desktop. ScopedSid logon_sid = GetLogonSid(token.Get()); if (!logon_sid) { PLOG(ERROR) << "Failed to retrieve the logon SID"; ReportFatalError(); return; } // Create the process and thread security descriptors. ScopedSd process_sd = ConvertSddlToSd(kWorkerProcessSd); ScopedSd thread_sd = ConvertSddlToSd(kWorkerThreadSd); if (!process_sd || !thread_sd) { PLOG(ERROR) << "Failed to create a security descriptor"; ReportFatalError(); return; } SECURITY_ATTRIBUTES process_attributes; process_attributes.nLength = sizeof(process_attributes); process_attributes.lpSecurityDescriptor = process_sd.get(); process_attributes.bInheritHandle = FALSE; SECURITY_ATTRIBUTES thread_attributes; thread_attributes.nLength = sizeof(thread_attributes); thread_attributes.lpSecurityDescriptor = thread_sd.get(); thread_attributes.bInheritHandle = FALSE; ScopedHandle worker_process; { // Take a lock why any inheritable handles are open to make sure that only // one process inherits them. base::AutoLock lock(g_inherit_handles_lock.Get()); // Create a connected IPC channel. base::File client; if (!CreateConnectedIpcChannel(io_task_runner_, this, &client, &server)) { ReportFatalError(); return; } // Convert the handle value into a decimal integer. Handle values are 32bit // even on 64bit platforms. std::string pipe_handle = base::StringPrintf( "%d", reinterpret_cast<ULONG_PTR>(client.GetPlatformFile())); // Pass the IPC channel via the command line. base::CommandLine command_line(target_command_->argv()); command_line.AppendSwitchASCII(kDaemonPipeSwitchName, pipe_handle); // Create our own window station and desktop accessible by |logon_sid|. WindowStationAndDesktop handles; if (!CreateWindowStationAndDesktop(std::move(logon_sid), &handles)) { PLOG(ERROR) << "Failed to create a window station and desktop"; ReportFatalError(); return; } // Try to launch the worker process. The launched process inherits // the window station, desktop and pipe handles, created above. ScopedHandle worker_thread; if (!LaunchProcessWithToken( command_line.GetProgram(), command_line.GetCommandLineString(), token.Get(), &process_attributes, &thread_attributes, true, 0, nullptr, &worker_process, &worker_thread)) { ReportFatalError(); return; } } channel_ = std::move(server); ReportProcessLaunched(std::move(worker_process)); } void UnprivilegedProcessDelegate::Send(IPC::Message* message) { DCHECK(CalledOnValidThread()); if (channel_) { channel_->Send(message); } else { delete message; } } void UnprivilegedProcessDelegate::CloseChannel() { DCHECK(CalledOnValidThread()); if (!channel_) return; IPC::AttachmentBroker::GetGlobal()->DeregisterCommunicationChannel( channel_.get()); channel_.reset(); } void UnprivilegedProcessDelegate::KillProcess() { DCHECK(CalledOnValidThread()); CloseChannel(); event_handler_ = nullptr; if (worker_process_.IsValid()) { TerminateProcess(worker_process_.Get(), CONTROL_C_EXIT); worker_process_.Close(); } } bool UnprivilegedProcessDelegate::OnMessageReceived( const IPC::Message& message) { DCHECK(CalledOnValidThread()); return event_handler_->OnMessageReceived(message); } void UnprivilegedProcessDelegate::OnChannelConnected(int32_t peer_pid) { DCHECK(CalledOnValidThread()); DWORD pid = GetProcessId(worker_process_.Get()); if (pid != static_cast<DWORD>(peer_pid)) { LOG(ERROR) << "The actual client PID " << pid << " does not match the one reported by the client: " << peer_pid; ReportFatalError(); return; } event_handler_->OnChannelConnected(peer_pid); } void UnprivilegedProcessDelegate::OnChannelError() { DCHECK(CalledOnValidThread()); event_handler_->OnChannelError(); } void UnprivilegedProcessDelegate::ReportFatalError() { DCHECK(CalledOnValidThread()); CloseChannel(); WorkerProcessLauncher* event_handler = event_handler_; event_handler_ = nullptr; event_handler->OnFatalError(); } void UnprivilegedProcessDelegate::ReportProcessLaunched( base::win::ScopedHandle worker_process) { DCHECK(CalledOnValidThread()); DCHECK(!worker_process_.IsValid()); worker_process_ = std::move(worker_process); // Report a handle that can be used to wait for the worker process completion, // query information about the process and duplicate handles. DWORD desired_access = SYNCHRONIZE | PROCESS_DUP_HANDLE | PROCESS_QUERY_INFORMATION; HANDLE temp_handle; if (!DuplicateHandle(GetCurrentProcess(), worker_process_.Get(), GetCurrentProcess(), &temp_handle, desired_access, FALSE, 0)) { PLOG(ERROR) << "Failed to duplicate a handle"; ReportFatalError(); return; } ScopedHandle limited_handle(temp_handle); event_handler_->OnProcessLaunched(std::move(limited_handle)); } } // namespace remoting
[ "wangpp_os@sari.ac.cn" ]
wangpp_os@sari.ac.cn
02e522696eb0fc95a7f995986898a3e565385fbb
3b6ee14ff27aa37882cee98f16de21daf60f48aa
/DWMFCApplication/stdafx.cpp
1067cbad529a3e311d47216e2d8594e99142237d
[]
no_license
seenunit/DesignWorld
410aa01c274d9eac04b6ef52222d0273420f960b
40d311b2ddf4dcc5c555689b3b4bf4a0c97f2c39
refs/heads/client
2021-01-18T21:21:03.688005
2017-07-01T07:57:19
2017-07-01T07:57:19
34,983,157
3
1
null
2016-04-04T12:35:26
2015-05-03T11:09:04
C++
UTF-8
C++
false
false
210
cpp
// stdafx.cpp : source file that includes just the standard includes // DWMFCApplication.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "seenunit@gmail.com" ]
seenunit@gmail.com