blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
f5a6a7b16b327b35331e356941a110fc3ec6732d
3818823eb686f65bfcc8c2652982548c55c1ec0d
/PointCloudAnalysis/MeshRelation.h
1707a6d7ac55e2a85512362397e6f388eb142e05
[]
no_license
mickey9294/structure-completion
5cd27325c46d31fe57f42f060ba492578aa863c9
e07b14bfb2eada1489e0f90714a0a1808f27f571
refs/heads/master
2020-04-05T14:05:13.218418
2017-06-28T07:29:33
2017-06-28T07:29:33
94,757,199
0
0
null
null
null
null
GB18030
C++
false
false
1,628
h
#ifndef MESHRELATION_H #define MESHRELATION_H #pragma once #include "MyMesh.h" #include <Eigen\Core> #include <Eigen/Geometry> #include <qmatrix4x4.h> #include "Vec.h" typedef class MeshRelation{ public: MeshRelation(); ~MeshRelation(); //MeshRelation(MyMesh m1,MyMesh m2);// m1 rotate to m2 void computeRotateMartix(Eigen::Vector3d &sourceV, Eigen::Vector3d &destV, Eigen::Matrix3d &M); double getRotateAngle(double x1, double y1, double z1, double x2, double y2, double z2, double xAxis, double yAxis, double zAxis); //将标准坐标变换为局部坐标 trimesh::point newCoordinate(trimesh::point oriCoordPoint, trimesh::Vec<3, float> xAxis, trimesh::Vec<3, float> yAxis, trimesh::Vec<3, float> zAxis, float xExt, float yExt, float zExt, trimesh::point newCenter); //将局部坐标变换为标准坐标 trimesh::point oriCoordinate(trimesh::point newCoordPoint, trimesh::Vec<3, float> xAxis, trimesh::Vec<3, float> yAxis, trimesh::Vec<3, float> zAxis, float xExt, float yExt, float zExt, trimesh::point newCenter); QMatrix4x4 coordTranslateMatrix(trimesh::Vec<3, float>newCoordx, trimesh::Vec<3, float>newCoordy, trimesh::Vec<3, float>newCoordz);// 计算将标准坐标系变换到新坐标系的矩阵,注意:新坐标系参数为有长度的三个基 void applyMatrix(trimesh::point &a, float *M); trimesh::point attachPointInM1Cord, attachPointInM2Cord; //QMatrix4x4 &Transform; //QMatrix4x4 coordTranslateMatrix(Vec<3, float>oriCoordx, Vec<3, float>oriCoordy, Vec<3, float>oriCoordz, Vec<3, float>newCoordx, Vec<3, float>newCoordy, Vec<3, float>newCoordz); }MeshRelation; #endif
[ "ALIENWARE15@ALIENWARE15" ]
ALIENWARE15@ALIENWARE15
a662de8e5d34095080a2d9cea8469e6bdc9a8b5c
01f885591835cee958d95c0830f90f6da389ce83
/SPOJ/Histogram.cpp
09eba3c2e99c71478491943c7cf280bfa969a903
[]
no_license
big-damnhero/code
9666632af6085d0142259967382810265b7604b0
05ed271f98ba45cb279f77f0d3e6f6032bc090d5
refs/heads/master
2021-07-16T13:50:57.223890
2020-05-29T13:54:28
2020-05-29T13:54:28
148,829,280
0
0
null
2018-10-27T19:53:15
2018-09-14T18:48:55
null
UTF-8
C++
false
false
1,394
cpp
#include <bits/stdc++.h> #define ll long long using namespace std; int dp[1<<15][15]; ll cnt[1<<15][15]; int ar[15],n; int f(int mask,int idx) { if(mask==(1<<n)-1) { cnt[mask][idx]=1; return ar[idx]; } if(idx>=n) { return 0; } if(dp[mask][idx]!=-1) { return dp[mask][idx]; } int res=0,val; for(int i=0;i<n;i++) { if(mask&(1<<i)) continue; else { val=f(mask|(1<<i),i)+abs(ar[i]-ar[idx]); if(val>res) { res=val; cnt[mask][idx]=0; } if(val==res) { cnt[mask][idx]+=cnt[mask|(1<<i)][i]; } } } return dp[mask][idx]=res; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin>>n; while(n) { for(int i=0;i<n;i++) { cin>>ar[i]; } memset(dp,-1,sizeof(dp)); int mx=0; ll cnt_mx=0; for(int i=0;i<n;i++) { int val=f(1<<i,i)+ar[i]; if(val>mx) { mx=val; cnt_mx=0; } if(val==mx) { cnt_mx+=cnt[1<<i][i]; } } mx+=(n<<1); cout<<mx<<" "<<cnt_mx<<endl; cin>>n; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
b9372cecccb555575d1931fc9676f3279db62400
28ff4999e339fcf537b997065b31cdc78f56a614
/chrome/browser/persisted_state_db/profile_proto_db_factory.h
0c9e924c85ed3bab8bb654e621c3d7f244795a07
[ "BSD-3-Clause" ]
permissive
raghavanv97/chromium
f04e91aa24e5437793f342617515a0a95fd81478
5a03bdd6e398bfb1d52c241b3b154485f48174a3
refs/heads/master
2023-02-05T01:17:51.097632
2020-12-15T06:41:11
2020-12-15T06:41:11
320,831,053
0
0
BSD-3-Clause
2020-12-14T08:37:15
2020-12-12T12:56:50
null
UTF-8
C++
false
false
4,151
h
// Copyright 2020 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 CHROME_BROWSER_PERSISTED_STATE_DB_PROFILE_PROTO_DB_FACTORY_H_ #define CHROME_BROWSER_PERSISTED_STATE_DB_PROFILE_PROTO_DB_FACTORY_H_ #include "chrome/browser/persisted_state_db/profile_proto_db.h" #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "components/keyed_service/content/browser_context_keyed_service_factory.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/storage_partition.h" namespace { const char kPersistedStateDBFolder[] = "persisted_state_db"; } // namespace ProfileProtoDBFactory<persisted_state_db::PersistedStateContentProto>* GetPersistedStateProfileProtoDBFactory(); // Factory to create a ProtoDB per profile and per proto. Incognito is // currently not supported and the factory will return nullptr for an incognito // profile. template <typename T> class ProfileProtoDBFactory : public BrowserContextKeyedServiceFactory { public: // Acquire instance of ProfileProtoDBFactory. static ProfileProtoDBFactory<T>* GetInstance(); // Acquire ProtoDB - there is one per profile. static ProfileProtoDB<T>* GetForProfile(content::BrowserContext* context); // Call the parent Disassociate which is a protected method. void Disassociate(content::BrowserContext* context) { BrowserContextKeyedServiceFactory::Disassociate(context); } private: friend class base::NoDestructor<ProfileProtoDBFactory<T>>; ProfileProtoDBFactory(); ~ProfileProtoDBFactory() override; KeyedService* BuildServiceInstanceFor( content::BrowserContext* context) const override; }; // static template <typename T> ProfileProtoDBFactory<T>* ProfileProtoDBFactory<T>::GetInstance() { static_assert( std::is_base_of<persisted_state_db::PersistedStateContentProto, T>:: value /** subsequent supported templates will be ORed in here */, "Provided template is not supported. To support implement a factory " "method similar to GetPersistedStateProfileProtoDBFactory and add to " "list of " "supported templates"); return GetPersistedStateProfileProtoDBFactory(); } // static template <typename T> ProfileProtoDB<T>* ProfileProtoDBFactory<T>::GetForProfile( content::BrowserContext* context) { // Incognito is currently not supported if (context->IsOffTheRecord()) return nullptr; return static_cast<ProfileProtoDB<T>*>( GetInstance()->GetServiceForBrowserContext(context, true)); } template <typename T> ProfileProtoDBFactory<T>::ProfileProtoDBFactory() : BrowserContextKeyedServiceFactory( "ProfileProtoDBFactory", BrowserContextDependencyManager::GetInstance()) {} template <typename T> ProfileProtoDBFactory<T>::~ProfileProtoDBFactory() = default; template <typename T> KeyedService* ProfileProtoDBFactory<T>::BuildServiceInstanceFor( content::BrowserContext* context) const { DCHECK(!context->IsOffTheRecord()); leveldb_proto::ProtoDatabaseProvider* proto_database_provider = content::BrowserContext::GetDefaultStoragePartition(context) ->GetProtoDatabaseProvider(); static_assert( std::is_base_of<persisted_state_db::PersistedStateContentProto, T>::value, "Provided template is not supported. To support add unique folder in the " "below proto -> folder name mapping below this assert."); // The following will become a proto -> dir and proto -> // leveldb_proto::ProtoDbType mapping as more protos are added. if (std::is_base_of<persisted_state_db::PersistedStateContentProto, T>::value) { return new ProfileProtoDB<T>( context, proto_database_provider, context->GetPath().AppendASCII(kPersistedStateDBFolder), leveldb_proto::ProtoDbType::PERSISTED_STATE_DATABASE); } else { // Must add in leveldb_proto::ProtoDbType and database directory folder for // new protos DCHECK(false); } } #endif // CHROME_BROWSER_PERSISTED_STATE_DB_PROFILE_PROTO_DB_FACTORY_H_
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
0d84194bf0499a62d21ca3ef99e04cb94c21796b
32d9aabeac99d55dd37baac962ea47684180ddf4
/ADAMAT.CPP
6fadb914c3e67aaa024384c8610ea673ed4aed4f
[]
no_license
DGreat49251/Misc
07b83bf0c3d0bf346280e9d26a28d3890156009d
b9c51055a9e230f4df986c5a4a0589ea7ffe0028
refs/heads/master
2023-05-03T09:14:56.820437
2021-05-25T15:08:07
2021-05-25T15:08:07
370,732,262
0
0
null
null
null
null
UTF-8
C++
false
false
263
cpp
#include<bits/stdc++.h> using namespace std; int main() { long t,n,s=0; cin>>t; while (t>0) { cin>>n; s=n*(n+1)/2; if(s%2!=0) { cout<<0; } else { }
[ "noreply@github.com" ]
noreply@github.com
04ee90ed9ba5839c54cf325230704b4587d369aa
b0025b70e7eaad87a9a984d83016530fea61a3a9
/boj/BruteForce/N_and_M/15649.cpp
4815ccb53e986911502c7c1f41e25d36599a0e52
[]
no_license
yupyub/Algorithm
00fede2885e1646458af1ffe16e7e2f4fc098832
7330e47c7cf70b1d2842004df63a1a347b625f41
refs/heads/master
2022-05-21T05:09:50.497376
2022-03-26T18:19:32
2022-03-26T18:19:32
101,531,563
1
0
null
null
null
null
UTF-8
C++
false
false
393
cpp
#include <cstdio> #include <vector> using namespace std; int ch[9]; vector<int> v; void f(int a,int b,int m){ if(b == m){ for(int i = 0;i<m;i++) printf("%d ",v[i]); printf("\n"); return; } b++; for(int i = 1;i<=a;i++){ if(ch[i] == 0){ ch[i] = 1; v.push_back(i); f(a,b,m); ch[i] = 0; v.pop_back(); } } } int main(){ int n,m; scanf("%d %d",&n,&m); f(n,0,m); }
[ "sungyup5003@gmail.com" ]
sungyup5003@gmail.com
55a189f7f40cb79eb5318987efd75c54b7ee2222
b952e949b17303dde341680138a74c2a5a4b6b2f
/nucleus/io/fastq_writer.cc
f8de6f9866df931fefe8eecc99f442a990c15211
[ "Apache-2.0" ]
permissive
cmclean/nucleus
d1e07bbfd49ae96b99a1a763d5b3fb6404eaddfc
5ed9c6972304fddb1c95eaf9fe7cee29183661d7
refs/heads/master
2020-03-13T09:40:39.241948
2018-05-15T21:06:08
2018-05-15T21:06:08
131,069,059
0
0
Apache-2.0
2018-04-25T22:10:07
2018-04-25T22:10:06
null
UTF-8
C++
false
false
3,848
cc
/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Implementation of fastq_writer.h #include "nucleus/io/fastq_writer.h" #include "absl/memory/memory.h" #include "nucleus/protos/fastq.pb.h" #include "nucleus/util/utils.h" #include "nucleus/vendor/zlib_compression_options.h" #include "nucleus/vendor/zlib_outputbuffer.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/file_system.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/types.h" namespace nucleus { namespace tf = tensorflow; // 256 KB write buffer. constexpr int WRITER_BUFFER_SIZE = 256 * 1024; // ----------------------------------------------------------------------------- // // Writer for FASTQ formats containing NGS reads. // // ----------------------------------------------------------------------------- StatusOr<std::unique_ptr<FastqWriter>> FastqWriter::ToFile( const string& fastq_path, const nucleus::genomics::v1::FastqWriterOptions& options) { std::unique_ptr<tensorflow::WritableFile> fp; if (!tf::Env::Default()->NewWritableFile(fastq_path.c_str(), &fp).ok()) { return tf::errors::Unknown( tf::strings::StrCat("Could not open fastq_path ", fastq_path)); } bool isCompressed = EndsWith(fastq_path, ".gz"); auto writer = absl::WrapUnique(new FastqWriter(std::move(fp), options, isCompressed)); return std::move(writer); } FastqWriter::FastqWriter( std::unique_ptr<tensorflow::WritableFile> fp, const nucleus::genomics::v1::FastqWriterOptions& options, const bool isCompressed) : options_(options), raw_file_(std::move(fp)), isCompressed_(isCompressed) { if (isCompressed_) { auto zwriter = new tf::io::ZlibOutputBuffer( raw_file_.get(), WRITER_BUFFER_SIZE, WRITER_BUFFER_SIZE, tf::io::ZlibCompressionOptions::GZIP()); TF_CHECK_OK(zwriter->Init()); writer_.reset(zwriter); } else { writer_ = raw_file_; } } FastqWriter::~FastqWriter() { if (writer_) { TF_CHECK_OK(Close()); } } tf::Status FastqWriter::Close() { if (!writer_) return tf::errors::FailedPrecondition( "Cannot close an already closed FastqWriter"); // Close the file pointer we have been writing to. TF_RETURN_IF_ERROR(writer_->Close()); writer_.reset(); if (raw_file_) { // If this is a compressed file, the raw_file_ pointer is different and // also needs to be closed. if (isCompressed_) TF_RETURN_IF_ERROR(raw_file_->Close()); raw_file_.reset(); } return tf::Status::OK(); } tf::Status FastqWriter::Write( const nucleus::genomics::v1::FastqRecord& record) { if (!writer_) return tf::errors::FailedPrecondition( "Cannot write to closed FASTQ stream."); string out = "@"; tf::strings::StrAppend(&out, record.id()); if (!record.description().empty()) { tf::strings::StrAppend(&out, " ", record.description()); } tf::strings::StrAppend(&out, "\n", record.sequence(), "\n+\n", record.quality(), "\n"); TF_RETURN_IF_ERROR(writer_->Append(out)); return tf::Status::OK(); } } // namespace nucleus
[ "thomaswc@google.com" ]
thomaswc@google.com
c6148d98af1f0cd97eb744d77cdf387eed9c6d6c
33fd5786ddde55a705d74ce2ce909017e2535065
/build/iOS/Debug/include/Uno.Threading.ThreadStart.h
0158e182e392500822f186c11bacf0951b8f7b18
[]
no_license
frpaulas/iphodfuse
04cee30add8b50ea134eb5a83e355dce886a5d5a
e8886638c4466b3b0c6299da24156d4ee81c9112
refs/heads/master
2021-01-23T00:48:31.195577
2017-06-01T12:33:13
2017-06-01T12:33:13
92,842,106
3
3
null
2017-05-30T17:43:28
2017-05-30T14:33:26
C++
UTF-8
C++
false
false
390
h
// This file was generated based on '../../../../Library/Application Support/Fusetools/Packages/Uno.Threading/1.0.11/$.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Delegate.h> namespace g{ namespace Uno{ namespace Threading{ // public delegate void ThreadStart() :953 uDelegateType* ThreadStart_typeof(); }}} // ::g::Uno::Threading
[ "frpaulas@gmail.com" ]
frpaulas@gmail.com
2c41698b825c26bce047e84eae00071bfc1109c2
02b43442244c518b7f414f6046b4bb2be96a4593
/Codeforces/1362D.cpp
460c7ac5a9b9cccc19386c6341abbb788036e874
[ "MIT" ]
permissive
mishrraG/DaysOfCP
f6796a483107241dbf2adf1050df9a3502711f14
3358af290d4f05889917808d68b95f37bd76e698
refs/heads/master
2023-08-17T16:24:48.953992
2021-08-28T15:21:32
2021-08-28T15:21:32
255,311,239
2
0
null
null
null
null
UTF-8
C++
false
false
1,256
cpp
#include<iostream> #include<vector> #include<unordered_set> #include<algorithm> using namespace std; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int n, m; cin >> n >> m; vector<int> gr1[500013]; int a, c; for(int i = 0; i < m; ++i){ cin >> a >> c; --a; --c; gr1[a].push_back(c); gr1[c].push_back(a); } int p[500013]; for(int i = 0; i < n; ++i){ cin >> p[i]; } unordered_set<int> gr[500013]; for(int i = 0; i < n; ++i){ for(int j : gr1[i]){ gr[i].insert(p[j] - 1); } } vector<pair<int,int> > b; for(int i = 0; i < n; ++i){ pair<int,int> k; k.first = p[i] - 1; k.second = i; b.push_back(k); } sort(b.begin(), b.end()); for(pair<int,int> i : b){ int ci = i.second; int ct = i.first; for(int j = 0; j < ct; ++j){ if(gr[ci].count(j) == 0){ cout << -1; return 0; } } if (gr[ci].count(ct) != 0){ cout << -1; return 0; } } for(int i = 0; i < b.size(); ++i){ cout << b[i].second + 1 << " "; } }
[ "arpitmishra4779@gmail.com" ]
arpitmishra4779@gmail.com
148024efc703c3c46555fc261c4be6e05e62d9c7
28a1e774bebd87ba8e5a8a9d757273f7599a9455
/S3M_SDK/S3M_SDK_Lightweight package/Sample2010/Src/Skeleton.cpp
290cdf65bf5c6172657df9010f94be76e82c0690
[ "Apache-2.0" ]
permissive
monk333/s3m-spec
79f8716fb3b3a8570612d95fcb22f7c62cbd41db
0d21f14c036d65c8c66bd9a757c07c5c562746ec
refs/heads/master
2022-04-10T13:31:56.646262
2020-03-26T08:13:14
2020-03-26T08:13:14
null
0
0
null
null
null
null
GB18030
C++
false
false
14,891
cpp
#include "Skeleton.h" #include "zlib\include\zconf.h" #include <assert.h> double Vector3d::operator[](const unsigned i) const { assert(i < 3); return *(&x + i); } double& Vector3d::operator[](const unsigned i) { assert(i < 3); return *(&x + i); } Vector3d Vector3d::operator+(const Vector3d& vec) const { Vector3d TempVec; TempVec.x = x + vec.x; TempVec.y = y + vec.y; TempVec.z = z + vec.z; return TempVec; } Vector3d Vector3d::operator-(const Vector3d& vec) const { Vector3d TempVec; TempVec.x = x - vec.x; TempVec.y = y - vec.y; TempVec.z = z - vec.z; return TempVec; } double Vector3d::Length() const { return sqrt(x*x + y * y + z * z); } double Vector3d::Length2() const { return x*x + y * y + z * z; } void Vector3d::MakeFloor(const Vector3d& cmp) { if (cmp.x < x) x = cmp.x; if (cmp.y < y) y = cmp.y; if (cmp.z < z) z = cmp.z; } void Vector3d::MakeCeil(const Vector3d& cmp) { if (cmp.x > x) x = cmp.x; if (cmp.y > y) y = cmp.y; if (cmp.z > z) z = cmp.z; } Vector3d Vector3d::MultiplyMatrix(const Matrix4d& m) const { double w = 1; double m11 = 0, m12 = 0, m13 = 0, m14 = 0; m11 = x * m[0][0] + y * m[1][0] + z * m[2][0] + w * m[3][0]; m12 = x * m[0][1] + y * m[1][1] + z * m[2][1] + w * m[3][1]; m13 = x * m[0][2] + y * m[1][2] + z * m[2][2] + w * m[3][2]; m14 = x * m[0][3] + y * m[1][3] + z * m[2][3] + w * m[3][3]; return Vector3d(m11, m12, m13); } void Vector3d::Normalize() { double fLength = 0.0; fLength = sqrt(x*x + y * y + z * z); if (!IS0(fLength)) { x /= fLength; y /= fLength; z /= fLength; } } double Vector4d::operator[](const unsigned i) const { assert(i < 4); return *(&x + i); } double& Vector4d::operator[](const unsigned i) { assert(i < 4); return *(&x + i); } Matrix4d::Matrix4d() { *this = Matrix4d::IDENTITY; } Matrix4d::Matrix4d(double m00, double m01, double m02, double m03, double m10, double m11, double m12, double m13, double m20, double m21, double m22, double m23, double m30, double m31, double m32, double m33) { m[0][0] = m00; m[0][1] = m01; m[0][2] = m02; m[0][3] = m03; m[1][0] = m10; m[1][1] = m11; m[1][2] = m12; m[1][3] = m13; m[2][0] = m20; m[2][1] = m21; m[2][2] = m22; m[2][3] = m23; m[3][0] = m30; m[3][1] = m31; m[3][2] = m32; m[3][3] = m33; } const Matrix4d Matrix4d::ZERO( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); const Matrix4d Matrix4d::IDENTITY( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); Matrix4d Matrix4d::operator*(const Matrix4d &m2) const { return Concatenate(m2); } Matrix4d Matrix4d::Concatenate(const Matrix4d &multiplyM2) const { Matrix4d tempMatrix; tempMatrix.m[0][0] = m[0][0] * multiplyM2.m[0][0] + m[0][1] * multiplyM2.m[1][0] + m[0][2] * multiplyM2.m[2][0] + m[0][3] * multiplyM2.m[3][0]; tempMatrix.m[0][1] = m[0][0] * multiplyM2.m[0][1] + m[0][1] * multiplyM2.m[1][1] + m[0][2] * multiplyM2.m[2][1] + m[0][3] * multiplyM2.m[3][1]; tempMatrix.m[0][2] = m[0][0] * multiplyM2.m[0][2] + m[0][1] * multiplyM2.m[1][2] + m[0][2] * multiplyM2.m[2][2] + m[0][3] * multiplyM2.m[3][2]; tempMatrix.m[0][3] = m[0][0] * multiplyM2.m[0][3] + m[0][1] * multiplyM2.m[1][3] + m[0][2] * multiplyM2.m[2][3] + m[0][3] * multiplyM2.m[3][3]; tempMatrix.m[1][0] = m[1][0] * multiplyM2.m[0][0] + m[1][1] * multiplyM2.m[1][0] + m[1][2] * multiplyM2.m[2][0] + m[1][3] * multiplyM2.m[3][0]; tempMatrix.m[1][1] = m[1][0] * multiplyM2.m[0][1] + m[1][1] * multiplyM2.m[1][1] + m[1][2] * multiplyM2.m[2][1] + m[1][3] * multiplyM2.m[3][1]; tempMatrix.m[1][2] = m[1][0] * multiplyM2.m[0][2] + m[1][1] * multiplyM2.m[1][2] + m[1][2] * multiplyM2.m[2][2] + m[1][3] * multiplyM2.m[3][2]; tempMatrix.m[1][3] = m[1][0] * multiplyM2.m[0][3] + m[1][1] * multiplyM2.m[1][3] + m[1][2] * multiplyM2.m[2][3] + m[1][3] * multiplyM2.m[3][3]; tempMatrix.m[2][0] = m[2][0] * multiplyM2.m[0][0] + m[2][1] * multiplyM2.m[1][0] + m[2][2] * multiplyM2.m[2][0] + m[2][3] * multiplyM2.m[3][0]; tempMatrix.m[2][1] = m[2][0] * multiplyM2.m[0][1] + m[2][1] * multiplyM2.m[1][1] + m[2][2] * multiplyM2.m[2][1] + m[2][3] * multiplyM2.m[3][1]; tempMatrix.m[2][2] = m[2][0] * multiplyM2.m[0][2] + m[2][1] * multiplyM2.m[1][2] + m[2][2] * multiplyM2.m[2][2] + m[2][3] * multiplyM2.m[3][2]; tempMatrix.m[2][3] = m[2][0] * multiplyM2.m[0][3] + m[2][1] * multiplyM2.m[1][3] + m[2][2] * multiplyM2.m[2][3] + m[2][3] * multiplyM2.m[3][3]; tempMatrix.m[3][0] = m[3][0] * multiplyM2.m[0][0] + m[3][1] * multiplyM2.m[1][0] + m[3][2] * multiplyM2.m[2][0] + m[3][3] * multiplyM2.m[3][0]; tempMatrix.m[3][1] = m[3][0] * multiplyM2.m[0][1] + m[3][1] * multiplyM2.m[1][1] + m[3][2] * multiplyM2.m[2][1] + m[3][3] * multiplyM2.m[3][1]; tempMatrix.m[3][2] = m[3][0] * multiplyM2.m[0][2] + m[3][1] * multiplyM2.m[1][2] + m[3][2] * multiplyM2.m[2][2] + m[3][3] * multiplyM2.m[3][2]; tempMatrix.m[3][3] = m[3][0] * multiplyM2.m[0][3] + m[3][1] * multiplyM2.m[1][3] + m[3][2] * multiplyM2.m[2][3] + m[3][3] * multiplyM2.m[3][3]; return tempMatrix; } //! \brief 重载[],取出对应行。 //! \param iRow 行号,有效范围为零到三[in]。 //! \return 矩阵指定一行数据,返回行数据指针。 double* Matrix4d::operator[] (unsigned int iRow) { assert(iRow < 4); return (double*)m[iRow]; } //! \brief 取出只读矩阵行数据。 //! \param iRow 行号,有效范围为零到三[in]。 //! \return 行数据。 const double *const Matrix4d::operator [] (unsigned int iRow) const { assert(iRow < 4); return m[iRow]; } bool Matrix4d::operator!=(const Matrix4d &m2) const { return !( IS0(m[0][0] - m2.m[0][0]) && IS0(m[0][1] - m2.m[0][1]) && IS0(m[0][2] - m2.m[0][2]) && IS0(m[0][3] - m2.m[0][3]) && IS0(m[1][0] - m2.m[1][0]) && IS0(m[1][1] - m2.m[1][1]) && IS0(m[1][2] - m2.m[1][2]) && IS0(m[1][3] - m2.m[1][3]) && IS0(m[2][0] - m2.m[2][0]) && IS0(m[2][1] - m2.m[2][1]) && IS0(m[2][2] - m2.m[2][2]) && IS0(m[2][3] - m2.m[2][3]) && IS0(m[3][0] - m2.m[3][0]) && IS0(m[3][1] - m2.m[3][1]) && IS0(m[3][2] - m2.m[3][2]) && IS0(m[3][3] - m2.m[3][3]) ); } bool Matrix4d::operator==(const Matrix4d &m2) const { return ( IS0(m[0][0] - m2.m[0][0]) && IS0(m[0][1] - m2.m[0][1]) && IS0(m[0][2] - m2.m[0][2]) && IS0(m[0][3] - m2.m[0][3]) && IS0(m[1][0] - m2.m[1][0]) && IS0(m[1][1] - m2.m[1][1]) && IS0(m[1][2] - m2.m[1][2]) && IS0(m[1][3] - m2.m[1][3]) && IS0(m[2][0] - m2.m[2][0]) && IS0(m[2][1] - m2.m[2][1]) && IS0(m[2][2] - m2.m[2][2]) && IS0(m[2][3] - m2.m[2][3]) && IS0(m[3][0] - m2.m[3][0]) && IS0(m[3][1] - m2.m[3][1]) && IS0(m[3][2] - m2.m[3][2]) && IS0(m[3][3] - m2.m[3][3]) ); } BoundingBox::BoundingBox() { SetMin(-0.5, -0.5, -0.5); SetMax(0.5, 0.5, 0.5); m_bNull = true; } BoundingBox::BoundingBox(Vector3d vMin, Vector3d vMax) { SetExtents(vMin, vMax); } bool BoundingBox::IsRealNaN(double dValue) { if (dValue > DBLMAX || dValue < -DBLMAX || IS0(dValue - DBLMAX) || IS0(dValue - DBLMIN)) { return false; } else { return true; } } bool BoundingBox::IsVaild() { return (IsRealNaN(m_vMax.x) && IsRealNaN(m_vMax.y) && IsRealNaN(m_vMax.z) && \ IsRealNaN(m_vMin.x) && IsRealNaN(m_vMin.y) && IsRealNaN(m_vMin.z)); } void BoundingBox::Merge(const BoundingBox& BoundBox) { if (BoundBox.m_bNull) return; else if (m_bNull) SetExtents(BoundBox.m_vMin, BoundBox.m_vMax); else { Vector3d vMin = m_vMin; Vector3d vMax = m_vMax; vMax.MakeCeil(BoundBox.m_vMax); vMin.MakeFloor(BoundBox.m_vMin); SetExtents(vMin, vMax); } } void BoundingBox::SetMin(Vector3d vMin) { m_bNull = false; m_vMin = vMin; UpdateCorners(); } void BoundingBox::SetMin(double x, double y, double z) { m_bNull = false; m_vMin.x = x; m_vMin.y = y; m_vMin.z = z; UpdateCorners(); } void BoundingBox::SetMax(Vector3d vMax) { m_bNull = false; m_vMax = vMax; UpdateCorners(); } void BoundingBox::SetMax(double x, double y, double z) { m_bNull = false; m_vMax.x = x; m_vMax.y = y; m_vMax.z = z; UpdateCorners(); } void BoundingBox::SetExtents(const Vector3d& vMin, const Vector3d& vMax) { m_bNull = false; m_vMin = vMin; m_vMax = vMax; UpdateCorners(); } void BoundingBox::SetExtents(double minx, double miny, double minz, double maxx, double maxy, double maxz) { m_bNull = false; m_vMin.x = minx; m_vMin.y = miny; m_vMin.z = minz; m_vMax.x = maxx; m_vMax.y = maxy; m_vMax.z = maxz; UpdateCorners(); } const Vector3d& BoundingBox::GetMin(void) const { return m_vMin; } const Vector3d& BoundingBox::GetMax(void) const { return m_vMax; } Vector3d BoundingBox::GetCenter() const { Vector3d center; center.x = (m_vMin.x + m_vMax.x) / 2.0; center.y = (m_vMin.y + m_vMax.y) / 2.0; center.z = (m_vMin.z + m_vMax.z) / 2.0; return center; } void BoundingBox::Transform(Matrix4d& matrix) { if (m_bNull) return; bool bFirst = true; Vector3d vMax, vMin, vTemp; int i = 0; for (i = 0; i < 8; i++) { vTemp = m_vCorner[i].MultiplyMatrix(matrix); if (bFirst || vTemp.x > vMax.x) vMax.x = vTemp.x; if (bFirst || vTemp.y > vMax.y) vMax.y = vTemp.y; if (bFirst || vTemp.z > vMax.z) vMax.z = vTemp.z; if (bFirst || vTemp.x < vMin.x) vMin.x = vTemp.x; if (bFirst || vTemp.y < vMin.y) vMin.y = vTemp.y; if (bFirst || vTemp.z < vMin.z) vMin.z = vTemp.z; bFirst = false; } SetExtents(vMin, vMax); } void BoundingBox::UpdateCorners(void) { for (int pos = 0; pos < 8; ++pos) { m_vCorner[pos] = Vector3d(pos & 1 ? m_vMax.x : m_vMin.x, pos & 2 ? m_vMax.y : m_vMin.y, pos & 4 ? m_vMax.z : m_vMin.z); } m_bNull = false; } IndexPackage::IndexPackage() : m_nIndexesCount(0) , m_pIndexes(NULL) , m_enIndexType(IT_16BIT) , m_bUseIndex(true) , m_OperationType(OT_TRIANGLE_LIST) { } IndexPackage::~IndexPackage() { if (m_pIndexes != NULL) { delete[] m_pIndexes; m_pIndexes = NULL; } m_nIndexesCount = 0; } bool IndexPackage::Load(MemoryStream &stream) { unsigned char nByte = 0; int nCount = 0; stream >> nCount; stream >> (unsigned char&)m_enIndexType; stream >> m_bUseIndex; stream >> (unsigned char&)m_OperationType; stream >> nByte; if (nCount > 0) { m_nIndexesCount = nCount; if (m_enIndexType == IT_32BIT || m_enIndexType == IT_32BIT_2) { m_pIndexes = new(std::nothrow) unsigned short[m_nIndexesCount * 2]; if (m_pIndexes == NULL) { return false; } stream.Load(m_pIndexes, m_nIndexesCount * 2); } else { m_pIndexes = new(std::nothrow) unsigned short[m_nIndexesCount]; if (m_pIndexes == NULL) { return false; } stream.Load(m_pIndexes, m_nIndexesCount); if (m_nIndexesCount % 2 != 0) { stream >> nByte; stream >> nByte; } } } int i = 0; stream >> nCount; for (i = 0; i < nCount; i++) { string strName; stream >> strName; m_strPassName.push_back(strName); } //四字节对齐 int nPos = stream.GetReadPosition(); if (nPos % 4 != 0) { int nReserved = 4 - nPos % 4; for (int j = 0; j < nReserved; j++) { stream >> nByte; } } return true; } void IndexPackage::Save(MemoryStream& stream) { unsigned char nByte = 0; stream << m_nIndexesCount; stream << (unsigned char)m_enIndexType; stream << m_bUseIndex; stream << (unsigned char)m_OperationType; stream << nByte; if (m_nIndexesCount > 0 && m_pIndexes != NULL) { if (m_enIndexType == IT_32BIT || m_enIndexType == IT_32BIT_2) { stream.Save(m_pIndexes, m_nIndexesCount * 2); } else { stream.Save(m_pIndexes, m_nIndexesCount); if (m_nIndexesCount % 2 != 0) { stream << nByte; stream << nByte; } } } int nCount = m_strPassName.size(); stream << nCount; for (int i = 0; i < nCount; i++) { string strName = m_strPassName[i]; stream << strName; } //四字节对齐 int nPos = stream.GetWritePosition(); if (nPos % 4 != 0) { int nReserved = 4 - nPos % 4; for (int j = 0; j < nReserved; j++) { stream << nByte; } } } void IndexPackage::SetIndexNum(int nIndexNum) { m_nIndexesCount = nIndexNum; if (m_pIndexes != NULL) { delete[] m_pIndexes; m_pIndexes = NULL; } if (m_enIndexType == IT_16BIT || m_enIndexType == IT_16BIT_2) { m_pIndexes = new unsigned short[nIndexNum]; memset(m_pIndexes, 0, sizeof(unsigned short)*nIndexNum); } else { m_pIndexes = (unsigned short*)new unsigned int[nIndexNum]; memset(m_pIndexes, 0, sizeof(unsigned int)*nIndexNum); } } Geometry::Geometry() : m_pVertexDataPackage(NULL), m_strMaterialName(""), m_strGeoName(""), m_matWorldView(Matrix4d::IDENTITY), m_nUseIndex(0), m_bInstanceBatch(false), m_bNormalDecode(false) {} Geometry::~Geometry() { if (m_pVertexDataPackage != NULL) { delete m_pVertexDataPackage; m_pVertexDataPackage = NULL; } for (int i = 0; i < m_arrIndexPackage.size(); i++) { if (m_arrIndexPackage.at(i) != NULL) { delete m_arrIndexPackage.at(i); m_arrIndexPackage.at(i) = NULL; } } } void Geometry::ComputerBoundingBox() { if (m_pVertexDataPackage == NULL || m_pVertexDataPackage->m_nVerticesCount < 1) { return; } Vector3d vecMax, vecMin; vecMax.x = -DBLMAX; vecMax.y = -DBLMAX; vecMax.z = -DBLMAX; vecMin.x = DBLMAX; vecMin.y = DBLMAX; vecMin.z = DBLMAX; int nVertexDim = m_pVertexDataPackage->m_nVertexDimension; int nValidVertexDim = nVertexDim > 3 ? 3 : nVertexDim; short* pCompressVertex = (short*)m_pVertexDataPackage->m_pVertices; for (int i = 0; i < m_pVertexDataPackage->m_nVerticesCount; i++) { Vector3d vertChange; for (int j = 0; j < nValidVertexDim; j++) { if (m_pVertexDataPackage->m_nCompressOptions & SVC_Vertex) { short encodeVal = pCompressVertex[i * nVertexDim + j]; vertChange[j] = encodeVal * m_pVertexDataPackage->m_fVertCompressConstant + m_pVertexDataPackage->m_minVerticesValue[j]; } else { vertChange[j] = m_pVertexDataPackage->m_pVertices[i * nVertexDim + j]; } } if (vertChange.x > vecMax.x) vecMax.x = vertChange.x; if (vertChange.y > vecMax.y) vecMax.y = vertChange.y; if (vertChange.z > vecMax.z) vecMax.z = vertChange.z; if (vertChange.x < vecMin.x) vecMin.x = vertChange.x; if (vertChange.y < vecMin.y) vecMin.y = vertChange.y; if (vertChange.z < vecMin.z) vecMin.z = vertChange.z; } //包围盒带矩阵 vecMin.MultiplyMatrix(m_matWorldView); vecMax.MultiplyMatrix(m_matWorldView); m_BoundingBox.SetExtents(vecMin, vecMax); }
[ "heqian@supermap.com" ]
heqian@supermap.com
de624487d9cc0e9ebce0a82ab6e48e1f024de768
e3b204b616646127c7e0ca86f2e8104e3fa2c743
/LinkedList/main.cpp
c93095fae8cc08f92e29781b8cbd559d12e51e26
[]
no_license
wuzhl2018/Data-structures
a1edf88ee60fbf526e847b1adc4c834a0887ed0b
4998222ff105f8380e0430f7ec128b68f43850a9
refs/heads/master
2022-11-19T19:16:07.304897
2017-02-19T12:03:06
2017-02-19T12:03:06
278,072,110
0
0
null
null
null
null
GB18030
C++
false
false
612
cpp
#include <iostream> #include<List.h> #include<stdlib.h> using namespace std; int main() { List<string> *stringList=new List<string>(); string name; cout<<"从链表的表头开始插入数据,请依次输入5个数据:"<<endl; for(int i=0; i<5; i++) { cin>>name; stringList->Insert(name); } cout<<"\n遍历链表:"<<endl; stringList->Traverse(); cout<<"\n请输入要插入的节点的数据和位置:"; string data; int index; cin>>data>>index; cout<<stringList->Insert(data,index)<<endl; stringList->Traverse(); return 0; }
[ "923734264@qq.com" ]
923734264@qq.com
e8564f2d1130663b2e9f0c12ff4fa8bf9e41b2a2
a8a42a85cf3c19f11e53049a497898256c3a4e1d
/code2.cpp
11e53440ffe10f49baad1c49a5f7d5cbb696ae0a
[]
no_license
ajaygupta007/comepitive-programming
cfc978f32c27d8320145cfbd2cdfc4a4bfe7961b
620d28b7d65f3f39d08ae5cee25d2559aee00b93
refs/heads/master
2020-08-18T09:28:43.862086
2020-01-20T13:51:11
2020-01-20T13:51:11
215,774,649
1
0
null
null
null
null
UTF-8
C++
false
false
355
cpp
#include<bits/stdc++.h> using namespace std; #include<string.h> #include<stdio.h> int main() { int t; scanf("%d",&t); char str1[21],temp[21],sum1=0,sum2=0,f=1; while(t--) { int n,i; scanf("%d",&n); if(f==1) { scanf("%s",str1); strcpy(temp,str1); f=0; } for(i=0;i<(n-1);i++) { if(temp==str1) sum1++; else sum2++; scanf("%s",str1); } } return 0; }
[ "ajay007.contact@gmail.com" ]
ajay007.contact@gmail.com
ccbe3d8294383db422d94884d5e15fe589eba6b1
3ddaa7e7ee492ca863e646ff2bd9ad329f261303
/AppCore/datamgmt/basicbone.h
d4f6538a0c8485d5ab6629ec8e72b13876a661ba
[]
no_license
dtbinh/AncelApp
6efa1c8804f7ba99f69207c59566e42f121c8cce
0d97bc8fcca75844c941ecb3bac9bb19cd69c7e6
refs/heads/master
2021-01-15T21:03:13.763602
2014-02-20T15:15:04
2014-02-20T15:15:04
41,375,088
1
0
null
2015-08-25T16:34:49
2015-08-25T16:34:49
null
UTF-8
C++
false
false
816
h
#ifndef __basicbone_h_ #define __basicbone_h_ #include <string> #include <Eigen\Eigen> #include <vector> using namespace Eigen; class GPCMBasicSkeleton; class GPCMBasicBone { public: GPCMBasicBone(const GPCMBasicBone* parent = NULL); virtual ~GPCMBasicBone(); bool isRoot() const {return (!mParent);} bool isLeaf() const {return mChildren.empty();} std::string& name() {return mBoneName;} protected: GPCMBasicSkeleton* mBelongTo; //the skeleton pointer which the bone belong to const GPCMBasicBone* mParent; //the bone's parent bone pointer std::vector<GPCMBasicBone*> mChildren; //the children pointer array std::string mBoneName; //bone name Vector3d mRelativePostion; Eigen::Quaterniond mLocalAxis; Vector3i mRotOrder; }; #endif
[ "ruan.answer@gmail.com" ]
ruan.answer@gmail.com
ce4ef92f74ea2aa89cd72d95c3d8a92f0049594e
b76b53ea00e5e71f54a55ab251d84c98c14acb55
/code/islands3.cpp
226368b3e042cb1c2dbe0868169bde37ee1dc91d
[ "MIT" ]
permissive
matthewReff/Kattis-Problems
69219e4a80c1142225d6a6b0517c6868248504bd
942d06ab5e3cae5a1546fcb364003530264607d7
refs/heads/master
2023-03-30T20:23:38.798982
2022-10-01T05:41:46
2022-10-01T05:41:46
150,904,577
15
3
null
2020-02-10T16:47:57
2018-09-29T21:30:52
C++
UTF-8
C++
false
false
2,037
cpp
#define _USE_MATH_DEFINES #include <iostream> #include <stdio.h> #include <cmath> #include <iomanip> #include <vector> #include <string> #include <algorithm> #include <unordered_set> #include <ctype.h> #include <queue> #include <map> #include <set> #include <stack> #include <unordered_map> #define EPSILON 0.00001 typedef long long ll; typedef unsigned long long ull; typedef long double ld; using namespace std; void floodFill(ll i, ll j, vector<string> &image, vector<vector<bool>> &found, ll height, ll width) { found[i][j] = true; ll tempi, tempj; for (ll k = 0; k < 4; k++) { switch (k) { case 0: tempi = i - 1; tempj = j; break; break; case 1: tempi = i; tempj = j + 1; break; case 2: tempi = i + 1; tempj = j; break; break; case 3: tempi = i; tempj = j - 1; break; }; if (tempi >= 0 && tempi < height && tempj >= 0 && tempj < width && !found[tempi][tempj] && (image[tempi][tempj] == 'L' || image[tempi][tempj] == 'C')) { floodFill(tempi, tempj, image, found, height, width); //cout << k << "\n"; } } } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); ll i, j, k; ll height, width; ll islands; ll tracker = 1; cin >> height >> width; vector<string> image(height); vector < vector<bool> > found(height); islands = 0; for (i = 0; i < height; i++) { found[i].resize(width); cin >> image[i]; } for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { if (image[i][j] == 'L' && !found[i][j]) { floodFill(i, j, image, found, height, width); islands++; } } } cout << islands << "\n"; tracker++; return 0; }
[ "geniusammyralltheothernamesare@gmail.com" ]
geniusammyralltheothernamesare@gmail.com
34325f9e5cc7ff77e9c9ca165b11d200c0d58ae2
0354d8e29fcbb65a06525bcac1f55fd08288b6e0
/clients/tizen/generated/src/PipelineActivity.cpp
5fffd17baf75d94af4ff9f7d6bdaecf8413f42f1
[ "MIT" ]
permissive
zhiwei55/swaggy-jenkins
cdc52956a40e947067415cec8d2da1425b3d7670
678b5477f5f9f00022b176c34b840055fb1b0a77
refs/heads/master
2020-03-06T20:38:53.012467
2018-02-19T01:53:33
2018-02-19T01:54:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,334
cpp
#include <map> #include <cstdlib> #include <glib-object.h> #include <json-glib/json-glib.h> #include "Helpers.h" #include "PipelineActivity.h" using namespace std; using namespace Tizen::ArtikCloud; PipelineActivity::PipelineActivity() { //__init(); } PipelineActivity::~PipelineActivity() { //__cleanup(); } void PipelineActivity::__init() { // // //_class = std::string(); // //new std::list()std::list> artifacts; // // // //durationInMillis = null; // // //estimatedDurationInMillis = null; // // //enQueueTime = std::string(); // // //endTime = std::string(); // // //id = std::string(); // // //organization = std::string(); // // //pipeline = std::string(); // // //result = std::string(); // // //runSummary = std::string(); // // //startTime = std::string(); // // //state = std::string(); // // //type = std::string(); // // //commitId = std::string(); // } void PipelineActivity::__cleanup() { //if(_class != NULL) { // //delete _class; //_class = NULL; //} //if(artifacts != NULL) { //artifacts.RemoveAll(true); //delete artifacts; //artifacts = NULL; //} //if(durationInMillis != NULL) { // //delete durationInMillis; //durationInMillis = NULL; //} //if(estimatedDurationInMillis != NULL) { // //delete estimatedDurationInMillis; //estimatedDurationInMillis = NULL; //} //if(enQueueTime != NULL) { // //delete enQueueTime; //enQueueTime = NULL; //} //if(endTime != NULL) { // //delete endTime; //endTime = NULL; //} //if(id != NULL) { // //delete id; //id = NULL; //} //if(organization != NULL) { // //delete organization; //organization = NULL; //} //if(pipeline != NULL) { // //delete pipeline; //pipeline = NULL; //} //if(result != NULL) { // //delete result; //result = NULL; //} //if(runSummary != NULL) { // //delete runSummary; //runSummary = NULL; //} //if(startTime != NULL) { // //delete startTime; //startTime = NULL; //} //if(state != NULL) { // //delete state; //state = NULL; //} //if(type != NULL) { // //delete type; //type = NULL; //} //if(commitId != NULL) { // //delete commitId; //commitId = NULL; //} // } void PipelineActivity::fromJson(char* jsonStr) { JsonObject *pJsonObject = json_node_get_object(json_from_string(jsonStr,NULL)); JsonNode *node; const gchar *_classKey = "_class"; node = json_object_get_member(pJsonObject, _classKey); if (node !=NULL) { if (isprimitive("std::string")) { jsonToValue(&_class, node, "std::string", ""); } else { } } const gchar *artifactsKey = "artifacts"; node = json_object_get_member(pJsonObject, artifactsKey); if (node !=NULL) { { JsonArray* arr = json_node_get_array(node); JsonNode* temp_json; list<PipelineActivityartifacts> new_list; PipelineActivityartifacts inst; for (guint i=0;i<json_array_get_length(arr);i++) { temp_json = json_array_get_element(arr,i); if (isprimitive("PipelineActivityartifacts")) { jsonToValue(&inst, temp_json, "PipelineActivityartifacts", ""); } else { inst.fromJson(json_to_string(temp_json, false)); } new_list.push_back(inst); } artifacts = new_list; } } const gchar *durationInMillisKey = "durationInMillis"; node = json_object_get_member(pJsonObject, durationInMillisKey); if (node !=NULL) { if (isprimitive("int")) { jsonToValue(&durationInMillis, node, "int", ""); } else { } } const gchar *estimatedDurationInMillisKey = "estimatedDurationInMillis"; node = json_object_get_member(pJsonObject, estimatedDurationInMillisKey); if (node !=NULL) { if (isprimitive("int")) { jsonToValue(&estimatedDurationInMillis, node, "int", ""); } else { } } const gchar *enQueueTimeKey = "enQueueTime"; node = json_object_get_member(pJsonObject, enQueueTimeKey); if (node !=NULL) { if (isprimitive("std::string")) { jsonToValue(&enQueueTime, node, "std::string", ""); } else { } } const gchar *endTimeKey = "endTime"; node = json_object_get_member(pJsonObject, endTimeKey); if (node !=NULL) { if (isprimitive("std::string")) { jsonToValue(&endTime, node, "std::string", ""); } else { } } const gchar *idKey = "id"; node = json_object_get_member(pJsonObject, idKey); if (node !=NULL) { if (isprimitive("std::string")) { jsonToValue(&id, node, "std::string", ""); } else { } } const gchar *organizationKey = "organization"; node = json_object_get_member(pJsonObject, organizationKey); if (node !=NULL) { if (isprimitive("std::string")) { jsonToValue(&organization, node, "std::string", ""); } else { } } const gchar *pipelineKey = "pipeline"; node = json_object_get_member(pJsonObject, pipelineKey); if (node !=NULL) { if (isprimitive("std::string")) { jsonToValue(&pipeline, node, "std::string", ""); } else { } } const gchar *resultKey = "result"; node = json_object_get_member(pJsonObject, resultKey); if (node !=NULL) { if (isprimitive("std::string")) { jsonToValue(&result, node, "std::string", ""); } else { } } const gchar *runSummaryKey = "runSummary"; node = json_object_get_member(pJsonObject, runSummaryKey); if (node !=NULL) { if (isprimitive("std::string")) { jsonToValue(&runSummary, node, "std::string", ""); } else { } } const gchar *startTimeKey = "startTime"; node = json_object_get_member(pJsonObject, startTimeKey); if (node !=NULL) { if (isprimitive("std::string")) { jsonToValue(&startTime, node, "std::string", ""); } else { } } const gchar *stateKey = "state"; node = json_object_get_member(pJsonObject, stateKey); if (node !=NULL) { if (isprimitive("std::string")) { jsonToValue(&state, node, "std::string", ""); } else { } } const gchar *typeKey = "type"; node = json_object_get_member(pJsonObject, typeKey); if (node !=NULL) { if (isprimitive("std::string")) { jsonToValue(&type, node, "std::string", ""); } else { } } const gchar *commitIdKey = "commitId"; node = json_object_get_member(pJsonObject, commitIdKey); if (node !=NULL) { if (isprimitive("std::string")) { jsonToValue(&commitId, node, "std::string", ""); } else { } } } PipelineActivity::PipelineActivity(char* json) { this->fromJson(json); } char* PipelineActivity::toJson() { JsonObject *pJsonObject = json_object_new(); JsonNode *node; if (isprimitive("std::string")) { std::string obj = getClass(); node = converttoJson(&obj, "std::string", ""); } else { } const gchar *_classKey = "_class"; json_object_set_member(pJsonObject, _classKey, node); if (isprimitive("PipelineActivityartifacts")) { list<PipelineActivityartifacts> new_list = static_cast<list <PipelineActivityartifacts> > (getArtifacts()); node = converttoJson(&new_list, "PipelineActivityartifacts", "array"); } else { node = json_node_alloc(); list<PipelineActivityartifacts> new_list = static_cast<list <PipelineActivityartifacts> > (getArtifacts()); JsonArray* json_array = json_array_new(); GError *mygerror; for (list<PipelineActivityartifacts>::iterator it = new_list.begin(); it != new_list.end(); it++) { mygerror = NULL; PipelineActivityartifacts obj = *it; JsonNode *node_temp = json_from_string(obj.toJson(), &mygerror); json_array_add_element(json_array, node_temp); g_clear_error(&mygerror); } json_node_init_array(node, json_array); json_array_unref(json_array); } const gchar *artifactsKey = "artifacts"; json_object_set_member(pJsonObject, artifactsKey, node); if (isprimitive("int")) { int obj = getDurationInMillis(); node = converttoJson(&obj, "int", ""); } else { } const gchar *durationInMillisKey = "durationInMillis"; json_object_set_member(pJsonObject, durationInMillisKey, node); if (isprimitive("int")) { int obj = getEstimatedDurationInMillis(); node = converttoJson(&obj, "int", ""); } else { } const gchar *estimatedDurationInMillisKey = "estimatedDurationInMillis"; json_object_set_member(pJsonObject, estimatedDurationInMillisKey, node); if (isprimitive("std::string")) { std::string obj = getEnQueueTime(); node = converttoJson(&obj, "std::string", ""); } else { } const gchar *enQueueTimeKey = "enQueueTime"; json_object_set_member(pJsonObject, enQueueTimeKey, node); if (isprimitive("std::string")) { std::string obj = getEndTime(); node = converttoJson(&obj, "std::string", ""); } else { } const gchar *endTimeKey = "endTime"; json_object_set_member(pJsonObject, endTimeKey, node); if (isprimitive("std::string")) { std::string obj = getId(); node = converttoJson(&obj, "std::string", ""); } else { } const gchar *idKey = "id"; json_object_set_member(pJsonObject, idKey, node); if (isprimitive("std::string")) { std::string obj = getOrganization(); node = converttoJson(&obj, "std::string", ""); } else { } const gchar *organizationKey = "organization"; json_object_set_member(pJsonObject, organizationKey, node); if (isprimitive("std::string")) { std::string obj = getPipeline(); node = converttoJson(&obj, "std::string", ""); } else { } const gchar *pipelineKey = "pipeline"; json_object_set_member(pJsonObject, pipelineKey, node); if (isprimitive("std::string")) { std::string obj = getResult(); node = converttoJson(&obj, "std::string", ""); } else { } const gchar *resultKey = "result"; json_object_set_member(pJsonObject, resultKey, node); if (isprimitive("std::string")) { std::string obj = getRunSummary(); node = converttoJson(&obj, "std::string", ""); } else { } const gchar *runSummaryKey = "runSummary"; json_object_set_member(pJsonObject, runSummaryKey, node); if (isprimitive("std::string")) { std::string obj = getStartTime(); node = converttoJson(&obj, "std::string", ""); } else { } const gchar *startTimeKey = "startTime"; json_object_set_member(pJsonObject, startTimeKey, node); if (isprimitive("std::string")) { std::string obj = getState(); node = converttoJson(&obj, "std::string", ""); } else { } const gchar *stateKey = "state"; json_object_set_member(pJsonObject, stateKey, node); if (isprimitive("std::string")) { std::string obj = getType(); node = converttoJson(&obj, "std::string", ""); } else { } const gchar *typeKey = "type"; json_object_set_member(pJsonObject, typeKey, node); if (isprimitive("std::string")) { std::string obj = getCommitId(); node = converttoJson(&obj, "std::string", ""); } else { } const gchar *commitIdKey = "commitId"; json_object_set_member(pJsonObject, commitIdKey, node); node = json_node_alloc(); json_node_init(node, JSON_NODE_OBJECT); json_node_take_object(node, pJsonObject); char * ret = json_to_string(node, false); json_node_free(node); return ret; } std::string PipelineActivity::getClass() { return _class; } void PipelineActivity::setClass(std::string _class) { this->_class = _class; } std::list<PipelineActivityartifacts> PipelineActivity::getArtifacts() { return artifacts; } void PipelineActivity::setArtifacts(std::list <PipelineActivityartifacts> artifacts) { this->artifacts = artifacts; } int PipelineActivity::getDurationInMillis() { return durationInMillis; } void PipelineActivity::setDurationInMillis(int durationInMillis) { this->durationInMillis = durationInMillis; } int PipelineActivity::getEstimatedDurationInMillis() { return estimatedDurationInMillis; } void PipelineActivity::setEstimatedDurationInMillis(int estimatedDurationInMillis) { this->estimatedDurationInMillis = estimatedDurationInMillis; } std::string PipelineActivity::getEnQueueTime() { return enQueueTime; } void PipelineActivity::setEnQueueTime(std::string enQueueTime) { this->enQueueTime = enQueueTime; } std::string PipelineActivity::getEndTime() { return endTime; } void PipelineActivity::setEndTime(std::string endTime) { this->endTime = endTime; } std::string PipelineActivity::getId() { return id; } void PipelineActivity::setId(std::string id) { this->id = id; } std::string PipelineActivity::getOrganization() { return organization; } void PipelineActivity::setOrganization(std::string organization) { this->organization = organization; } std::string PipelineActivity::getPipeline() { return pipeline; } void PipelineActivity::setPipeline(std::string pipeline) { this->pipeline = pipeline; } std::string PipelineActivity::getResult() { return result; } void PipelineActivity::setResult(std::string result) { this->result = result; } std::string PipelineActivity::getRunSummary() { return runSummary; } void PipelineActivity::setRunSummary(std::string runSummary) { this->runSummary = runSummary; } std::string PipelineActivity::getStartTime() { return startTime; } void PipelineActivity::setStartTime(std::string startTime) { this->startTime = startTime; } std::string PipelineActivity::getState() { return state; } void PipelineActivity::setState(std::string state) { this->state = state; } std::string PipelineActivity::getType() { return type; } void PipelineActivity::setType(std::string type) { this->type = type; } std::string PipelineActivity::getCommitId() { return commitId; } void PipelineActivity::setCommitId(std::string commitId) { this->commitId = commitId; }
[ "cliffano@gmail.com" ]
cliffano@gmail.com
bb0cc6ad50cb0d700b7279780fe0526fdf9afdd3
e6ec9430c803e8d9b9a027d5a34b30bd80a43542
/Arduino/Sketchbook/Zumo3/SharpSensor.ino
497bd1f517d5700a61c25877cee828401532e197
[]
no_license
slgrobotics/Misc
d1d63348eb2ebc5d20693574f7e2a350eea9a753
b6064d5ae24bf5b31f615e461ef3ee9faf201287
refs/heads/master
2023-04-03T11:57:11.269852
2023-04-01T16:04:57
2023-04-01T16:04:57
93,823,114
9
1
null
null
null
null
UTF-8
C++
false
false
1,785
ino
// for 0-150cm Sharp sensor: int sharpToInches(int sv, boolean closeRangeOn) { if(closeRangeOn) { // 0-4 inches is within the range of Sharp GP2Y0D810Z0F Digital Distance Sensors 0-10cm // 220 - 0 // 330 - 1 // 350 - 2 // 400 - 3 // 500 - 4 if(sv < 270) return 0; if(sv < 340) return 1; if(sv < 370) return 2; if(sv < 450) return 3; return 4; } if(sv > 400) return 7; if(sv < 90) return 100; return 50 - (sv - 90) * 42 / 410; /* if(sv < 230) { return 50 - (sv - 90) * 30 / 140; //return (int)(50.0f - ((float)sv - 90.0f) * 30.0f / 140.0f); } return 20 - (sv - 230) * 12 / 270; //return (int)(20.0f - ((float)sv - 230.0f) * 12.0f / 270.0f); */ } void readDistanceSensors() { // wait 2 milliseconds before the next loop // for the analog-to-digital converter to settle // after the last reading: delay(2); // read the analog distance sensor value: distanceSensorValue = analogRead(sharpAnalogSensorPin); // read digital distance sensors: digitalSensorLeft = !digitalRead(sharpDigitalSensorLeftPin); digitalSensorRight = !digitalRead(sharpDigitalSensorRightPin); digitalSensorRearLeft = !digitalRead(sharpDigitalSensorRearLeftPin); digitalSensorRearRight = !digitalRead(sharpDigitalSensorRearRightPin); closeRangeOn = digitalSensorLeft || digitalSensorRight; targetStraightOn = digitalSensorLeft && digitalSensorRight; // map it to the range of the analog out: distanceInches = sharpToInches(distanceSensorValue, closeRangeOn); } void readRearSensors() { digitalSensorRearLeft = !digitalRead(sharpDigitalSensorRearLeftPin); digitalSensorRearRight = !digitalRead(sharpDigitalSensorRearRightPin); }
[ "msghub@hotmail.com" ]
msghub@hotmail.com
2b262cb64e68622c58659d19f684c0fd41e61922
cdd36415f8591d3fefd430258f6b56e257fe27c1
/src/rocket/parameter/acceleration.cpp
40bbc2e00a8f4cde275f945415bc2cf0217f1685
[ "MIT" ]
permissive
sus304/ForRocket
0b936c161653021d0034b745820bfbb14e43c090
10fdcd0ce5a30fbbb4fec6315bcd64314bec6c12
refs/heads/master
2023-07-20T01:13:31.645359
2020-04-11T03:35:13
2020-04-11T03:35:13
48,164,917
38
12
null
2018-06-11T07:40:02
2015-12-17T09:25:39
Fortran
UTF-8
C++
false
false
405
cpp
// ****************************************************** // Project Name : ForRocket // File Name : acceleration.cpp // Creation Date : 2019/10/26 // // Copyright (c) 2019 Susumu Tanaka. All rights reserved. // ****************************************************** #include "acceleration.hpp" forrocket::Acceleration::Acceleration() { ECI << 0.0, 0.0, 0.0; body << 0.0, 0.0, 0.0; };
[ "sus304.tanaka@gmail.com" ]
sus304.tanaka@gmail.com
f33483d32fce7f662dd0d1ca6cd722d6aa26d4cf
84672edd077960fef2e55f3e6d4df677d74d2c8a
/parsedfile.h
636f1b69027f31f64fb29693cc6d692d5cac8ded
[]
no_license
Deneb-Algedi/Local-Search-Engine
3d6d64d0d0591d2b61742a9c5a86f5435de1af3e
7f2b819a5cb983b8af9501c7146656731c2dce24
refs/heads/master
2020-08-07T12:03:45.690908
2019-12-30T01:31:03
2019-12-30T01:31:03
213,443,711
0
0
null
null
null
null
UTF-8
C++
false
false
1,907
h
/* ParsedFile.h Este archivo contiene la clase ParsedFile y los prototipos de algunas funciones adicionales que pueden ser utilizadas en el proyecto final de CCOM 3034. */ #include <sys/types.h> #include <dirent.h> #include <errno.h> #include <iostream> #include <fstream> #include <string> #include <vector> typedef unsigned int uint; using namespace std; class ParsedFile { private: string name; public: ParsedFile() {}; ParsedFile(string n) {name = n;} string getName() {return name;} /* Esta funcion lee todos las lineas de un archivo, las separa en palabras y devuelve como vector de strings. Pre-cond: El objeto de clase ParsedFile ha sido asignado un nombre. Post-cond: Regresa resultados como vector de strings. */ vector<string> readAndTokenize(); }; /* getdir: Recibe como parametro el nombre de un directorio y devuelve (por medio del segundo parametro) un vector de strings que contiene los nombres de cada uno de los archivos del directorio. El valor entero que devuelve indica si la operación fue exitosa: 0 indica que no hubo error, cualquier otro número indica que hubo error. Pre-condicion: Ninguna Post-condición: Cambia el contenido del vector pasado como segundo parámetro. */ int getdir (string, vector<string> &); /* tokenize: Recibe como parametros dos strings: - str: es el string que desamos romper en palabras - delim: es el string delimitador que usaremos para determinar donde partir a str. Esto casi siempre es un espacion, coma, etc. Devuelve un vector de strings obtenidos de str. Pre-condicion: str y delim no son strings vacios Post-condición: No modifica ni a str ni a delim. Devuelve el vector de strings. */ vector<string> tokenize(const string & str, const string & delim);
[ "noreply@github.com" ]
noreply@github.com
7eafa9edc94ea2f78c6fcfd6ce629610cbe9f6a8
1c9a81620115ab134edfbe309f5fee191c8b209d
/wxRaytracer/raytracer/Tracers/RayCast.h
a49a1df226425c314a7c38f3914b29c7b8ad0615
[]
no_license
stephenDiosDev/CPSC591-Project
544257a95dbfa910c501c4fb7dd5df38c5bc2958
7e5cc7132f490d7f7a6f299a6c1ab253da787429
refs/heads/main
2023-02-03T18:57:21.862204
2020-12-22T21:16:12
2020-12-22T21:16:12
311,477,717
0
0
null
null
null
null
UTF-8
C++
false
false
504
h
#ifndef __RAY_CAST__ #define __RAY_CAST__ #include "Tracer.h" class RayCast: public Tracer { public: RayCast(void); RayCast(World* _worldPtr); virtual ~RayCast(void); virtual RGBColor trace_ray(const Ray& ray) const; virtual RGBColor trace_ray(const Ray ray, const int depth) const; virtual RGBColor trace_ray_caustics(const Ray ray, const int depth) const; virtual RGBColor trace_ray_forward_caustics(const Ray ray, const int depth) const; }; #endif
[ "stephendiosdeveloper@gmail.com" ]
stephendiosdeveloper@gmail.com
eaa51e4e9d8498aeb93d8c86864ca4fc1f326229
1591e61fa8c7d33de329c49856f5c40a07e1dafa
/OOP/Solutions/1.2/1.2/1.2.cpp
e6ebdf1b5559eecc9ec266070dee0747d1e6c81a
[]
no_license
maxymilianz/CS-at-University-of-Wroclaw
d1c667ad146c09c7b232da8491863e45ecfdd68a
0cd4bbe3feb63b248d643303433f9fb2fc2def79
refs/heads/master
2023-01-19T12:38:43.781724
2022-06-29T17:40:07
2022-06-29T17:40:07
124,766,411
0
0
null
2023-01-19T10:27:21
2018-03-11T14:46:12
OCaml
UTF-8
C++
false
false
1,744
cpp
// 1.2.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Figury.h" int main() { int which; float x, y, a; printf_s("Podaj wspolrzedna x punktu: "); scanf_s("%f", &x); printf_s("Podaj wspolrzedna y punktu: "); scanf_s("%f", &y); Figura *punkt = nowyPunkt(x, y); printf_s("Podaj wspolrzedna x kola: "); scanf_s("%f", &x); printf_s("Podaj wspolrzedna y kola: "); scanf_s("%f", &y); printf_s("Podaj promien kola: "); scanf_s("%f", &a); Figura *kolo = noweKolo(x, y, a); printf_s("Podaj wspolrzedna x kwadratu: "); scanf_s("%f", &x); printf_s("Podaj wspolrzedna y kwadratu: "); scanf_s("%f", &y); printf_s("Podaj dlugosc boku kwadratu: "); scanf_s("%f", &a); Figura *kwadrat = nowyKwadrat(x, y, a); printf_s("Ktora figure chcesz przesunac? (0 - punkt, 1 - kolo, >1 - kwadrat)\n"); scanf_s("%d", &which); printf_s("O ile poziomo chcesz ja przesunac?\n"); scanf_s("%f", &x); printf_s("O ile pionowo chcesz ja przesunac?\n"); scanf_s("%f", &y); if (!which) { przesun(punkt, x, y); narysuj(punkt); } else if (which == 1) { przesun(kolo, x, y); narysuj(kolo); } else { przesun(kwadrat, x, y); narysuj(kwadrat); } printf_s("Podaj wspolrzedna x punktu do przetestowania: "); scanf_s("%f", &x); printf_s("Podaj wspolrzedna y punktu do przetestowania: "); scanf_s("%f", &y); printf_s("Z jaka figura chcesz sprawdzic zawieranie?\n"); scanf_s("%d", &which); if (!which) printf_s(zawiera(punkt, x, y) ? "Zawiera\n" : "Nie zawiera\n"); else if (which == 1) printf_s(zawiera(kolo, x, y) ? "Zawiera\n" : "Nie zawiera\n"); else printf_s(zawiera(kwadrat, x, y) ? "Zawiera\n" : "Nie zawiera\n"); free(punkt), free(kolo), free(kwadrat); return 0; }
[ "289528@uwr.edu.pl" ]
289528@uwr.edu.pl
c4d689545600e53ee364035fdab4e4ec2302bf67
0494c9caa519b27f3ed6390046fde03a313d2868
/src/chrome/browser/search_engines/template_url.h
c192e0494d50d1f821ba5e6c6c41ef2bdd930272
[ "BSD-3-Clause" ]
permissive
mhcchang/chromium30
9e9649bec6fb19fe0dc2c8b94c27c9d1fa69da2c
516718f9b7b95c4280257b2d319638d4728a90e1
refs/heads/master
2023-03-17T00:33:40.437560
2017-08-01T01:13:12
2017-08-01T01:13:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,144
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 CHROME_BROWSER_SEARCH_ENGINES_TEMPLATE_URL_H_ #define CHROME_BROWSER_SEARCH_ENGINES_TEMPLATE_URL_H_ #include <string> #include <utility> #include <vector> #include "base/gtest_prod_util.h" #include "base/time/time.h" #include "chrome/browser/search_engines/template_url_id.h" #include "url/gurl.h" #include "url/url_parse.h" class Profile; class SearchTermsData; class TemplateURL; // TemplateURLRef ------------------------------------------------------------- // A TemplateURLRef represents a single URL within the larger TemplateURL class // (which represents an entire "search engine", see below). If // SupportsReplacement() is true, this URL has placeholders in it, for which // callers can substitute values to get a "real" URL using ReplaceSearchTerms(). // // TemplateURLRefs always have a non-NULL |owner_| TemplateURL, which they // access in order to get at important data like the underlying URL string or // the associated Profile. class TemplateURLRef { public: // Magic numbers to pass to ReplaceSearchTerms() for the |accepted_suggestion| // parameter. Most callers aren't using Suggest capabilities and should just // pass NO_SUGGESTIONS_AVAILABLE. // NOTE: Because positive values are meaningful, make sure these are negative! enum AcceptedSuggestion { NO_SUGGESTION_CHOSEN = -1, NO_SUGGESTIONS_AVAILABLE = -2, }; // Which kind of URL within our owner we are. This allows us to get at the // correct string field. Use |INDEXED| to indicate that the numerical // |index_in_owner_| should be used instead. enum Type { SEARCH, SUGGEST, INSTANT, IMAGE, INDEXED }; // Type to store <content_type, post_data> pair for POST URLs. // The |content_type|(first part of the pair) is the content-type of // the |post_data|(second part of the pair) which is encoded in // "multipart/form-data" format, it also contains the MIME boundary used in // the |post_data|. See http://tools.ietf.org/html/rfc2046 for the details. typedef std::pair<std::string, std::string> PostContent; // This struct encapsulates arguments passed to // TemplateURLRef::ReplaceSearchTerms methods. By default, only search_terms // is required and is passed in the constructor. struct SearchTermsArgs { explicit SearchTermsArgs(const string16& search_terms); ~SearchTermsArgs(); // The search terms (query). string16 search_terms; // The original (input) query. string16 original_query; // The optional assisted query stats, aka AQS, used for logging purposes. // This string contains impressions of all autocomplete matches shown // at the query submission time. For privacy reasons, we require the // search provider to support HTTPS protocol in order to receive the AQS // param. // For more details, see http://goto.google.com/binary-clients-logging . std::string assisted_query_stats; // TODO: Remove along with "aq" CGI param. int accepted_suggestion; // The 0-based position of the cursor within the query string at the time // the request was issued. Set to string16::npos if not used. size_t cursor_position; // The start-edge margin of the omnibox in pixels, used in extended Instant // to align the preview contents with the omnibox. int omnibox_start_margin; // The URL of the current webpage to be used for experimental zero-prefix // suggestions. std::string zero_prefix_url; // If set, ReplaceSearchTerms() will automatically append any extra query // params specified via the --extra-search-query-params command-line // argument. Generally, this should be set when dealing with the search or // instant TemplateURLRefs of the default search engine and the caller cares // about the query portion of the URL. Since neither TemplateURLRef nor // indeed TemplateURL know whether a TemplateURL is the default search // engine, callers instead must set this manually. bool append_extra_query_params; // The raw content of an image thumbnail that will be used as a query for // search-by-image frontend. std::string image_thumbnail_content; // When searching for an image, the URL of the original image. Callers // should leave this empty for images specified via data: URLs. GURL image_url; }; TemplateURLRef(TemplateURL* owner, Type type); TemplateURLRef(TemplateURL* owner, size_t index_in_owner); ~TemplateURLRef(); // Returns the raw URL. None of the parameters will have been replaced. std::string GetURL() const; // Returns the raw string of the post params. Please see comments in // prepopulated_engines_schema.json for the format. std::string GetPostParamsString() const; // Returns true if this URL supports search term replacement. bool SupportsReplacement() const; // Like SupportsReplacement but usable on threads other than the UI thread. bool SupportsReplacementUsingTermsData( const SearchTermsData& search_terms_data) const; // Returns a string that is the result of replacing the search terms in // the url with the specified arguments. We use our owner's input encoding. // // If this TemplateURLRef does not support replacement (SupportsReplacement // returns false), an empty string is returned. // If this TemplateURLRef uses POST, and |post_content| is not NULL, the // |post_params_| will be replaced, encoded in "multipart/form-data" format // and stored into |post_content|. std::string ReplaceSearchTerms( const SearchTermsArgs& search_terms_args, PostContent* post_content) const; // TODO(jnd): remove the following ReplaceSearchTerms definition which does // not have |post_content| parameter once all reference callers pass // |post_content| parameter. std::string ReplaceSearchTerms( const SearchTermsArgs& search_terms_args) const { return ReplaceSearchTerms(search_terms_args, NULL); } // Just like ReplaceSearchTerms except that it takes SearchTermsData to supply // the data for some search terms. Most of the time ReplaceSearchTerms should // be called. std::string ReplaceSearchTermsUsingTermsData( const SearchTermsArgs& search_terms_args, const SearchTermsData& search_terms_data, PostContent* post_content) const; // Returns true if the TemplateURLRef is valid. An invalid TemplateURLRef is // one that contains unknown terms, or invalid characters. bool IsValid() const; // Like IsValid but usable on threads other than the UI thread. bool IsValidUsingTermsData(const SearchTermsData& search_terms_data) const; // Returns a string representation of this TemplateURLRef suitable for // display. The display format is the same as the format used by Firefox. string16 DisplayURL() const; // Converts a string as returned by DisplayURL back into a string as // understood by TemplateURLRef. static std::string DisplayURLToURLRef(const string16& display_url); // If this TemplateURLRef is valid and contains one search term, this returns // the host/path of the URL, otherwise this returns an empty string. const std::string& GetHost() const; const std::string& GetPath() const; // If this TemplateURLRef is valid and contains one search term, this returns // the key of the search term, otherwise this returns an empty string. const std::string& GetSearchTermKey() const; // Converts the specified term in our owner's encoding to a string16. string16 SearchTermToString16(const std::string& term) const; // Returns true if this TemplateURLRef has a replacement term of // {google:baseURL} or {google:baseSuggestURL}. bool HasGoogleBaseURLs() const; // Use the pattern referred to by this TemplateURLRef to match the provided // |url| and extract |search_terms| from it. Returns true if the pattern // matches, even if |search_terms| is empty. In this case // |search_term_component|, if not NULL, indicates whether the search terms // were found in the query or the ref parameters; and |search_terms_position|, // if not NULL, contains the position of the search terms in the query or the // ref parameters. Returns false and an empty |search_terms| if the pattern // does not match. bool ExtractSearchTermsFromURL( const GURL& url, string16* search_terms, const SearchTermsData& search_terms_data, url_parse::Parsed::ComponentType* search_term_component, url_parse::Component* search_terms_position) const; // Whether the URL uses POST (as opposed to GET). bool UsesPOSTMethodUsingTermsData( const SearchTermsData* search_terms_data) const; bool UsesPOSTMethod() const { return UsesPOSTMethodUsingTermsData(NULL); } private: friend class TemplateURL; FRIEND_TEST_ALL_PREFIXES(TemplateURLTest, SetPrepopulatedAndParse); FRIEND_TEST_ALL_PREFIXES(TemplateURLTest, ParseParameterKnown); FRIEND_TEST_ALL_PREFIXES(TemplateURLTest, ParseParameterUnknown); FRIEND_TEST_ALL_PREFIXES(TemplateURLTest, ParseURLEmpty); FRIEND_TEST_ALL_PREFIXES(TemplateURLTest, ParseURLNoTemplateEnd); FRIEND_TEST_ALL_PREFIXES(TemplateURLTest, ParseURLNoKnownParameters); FRIEND_TEST_ALL_PREFIXES(TemplateURLTest, ParseURLTwoParameters); FRIEND_TEST_ALL_PREFIXES(TemplateURLTest, ParseURLNestedParameter); FRIEND_TEST_ALL_PREFIXES(TemplateURLTest, URLRefTestImageURLWithPOST); // Enumeration of the known types. enum ReplacementType { ENCODING, GOOGLE_ASSISTED_QUERY_STATS, GOOGLE_BASE_URL, GOOGLE_BASE_SUGGEST_URL, GOOGLE_CURSOR_POSITION, GOOGLE_IMAGE_SEARCH_SOURCE, GOOGLE_IMAGE_THUMBNAIL, GOOGLE_IMAGE_URL, GOOGLE_INSTANT_ENABLED, GOOGLE_INSTANT_EXTENDED_ENABLED, GOOGLE_NTP_IS_THEMED, GOOGLE_OMNIBOX_START_MARGIN, GOOGLE_ORIGINAL_QUERY_FOR_SUGGESTION, GOOGLE_RLZ, GOOGLE_SEARCH_CLIENT, GOOGLE_SEARCH_FIELDTRIAL_GROUP, GOOGLE_SUGGEST_CLIENT, GOOGLE_UNESCAPED_SEARCH_TERMS, GOOGLE_ZERO_PREFIX_URL, LANGUAGE, SEARCH_TERMS, }; // Used to identify an element of the raw url that can be replaced. struct Replacement { Replacement(ReplacementType type, size_t index) : type(type), index(index), is_post_param(false) {} ReplacementType type; size_t index; // Indicates the location in where the replacement is replaced. If // |is_post_param| is false, |index| indicates the byte position in // |parsed_url_|. Otherwise, |index| is the index of |post_params_|. bool is_post_param; }; // The list of elements to replace. typedef std::vector<struct Replacement> Replacements; // Type to store <key, value> pairs for POST URLs. typedef std::pair<std::string, std::string> PostParam; typedef std::vector<PostParam> PostParams; // TemplateURLRef internally caches values to make replacement quick. This // method invalidates any cached values. void InvalidateCachedValues() const; // Parses the parameter in url at the specified offset. start/end specify the // range of the parameter in the url, including the braces. If the parameter // is valid, url is updated to reflect the appropriate parameter. If // the parameter is one of the known parameters an element is added to // replacements indicating the type and range of the element. The original // parameter is erased from the url. // // If the parameter is not a known parameter, false is returned. If this is a // prepopulated URL, the parameter is erased, otherwise it is left alone. bool ParseParameter(size_t start, size_t end, std::string* url, Replacements* replacements) const; // Parses the specified url, replacing parameters as necessary. If // successful, valid is set to true, and the parsed url is returned. For all // known parameters that are encountered an entry is added to replacements. // If there is an error parsing the url, valid is set to false, and an empty // string is returned. If the URL has the POST parameters, they will be // parsed into |post_params| which will be further replaced with real search // terms data and encoded in "multipart/form-data" format to generate the // POST data. std::string ParseURL(const std::string& url, Replacements* replacements, PostParams* post_params, bool* valid) const; // If the url has not yet been parsed, ParseURL is invoked. // NOTE: While this is const, it modifies parsed_, valid_, parsed_url_ and // search_offset_. void ParseIfNecessary() const; // Like ParseIfNecessary but usable on threads other than the UI thread. void ParseIfNecessaryUsingTermsData( const SearchTermsData& search_terms_data) const; // Extracts the query key and host from the url. void ParseHostAndSearchTermKey( const SearchTermsData& search_terms_data) const; // Encode post parameters in "multipart/form-data" format and store it // inside |post_content|. Returns false if errors are encountered during // encoding. This method is called each time ReplaceSearchTerms gets called. bool EncodeFormData(const PostParams& post_params, PostContent* post_content) const; // Handles a replacement by using real term data. If the replacement // belongs to a PostParam, the PostParam will be replaced by the term data. // Otherwise, the term data will be inserted at the place that the // replacement points to. void HandleReplacement(const std::string& name, const std::string& value, const Replacement& replacement, std::string* url) const; // Replaces all replacements in |parsed_url_| with their actual values and // returns the result. This is the main functionality of // ReplaceSearchTermsUsingTermsData(). std::string HandleReplacements( const SearchTermsArgs& search_terms_args, const SearchTermsData& search_terms_data, PostContent* post_content) const; // The TemplateURL that contains us. This should outlive us. TemplateURL* const owner_; // What kind of URL we are. const Type type_; // If |type_| is |INDEXED|, this |index_in_owner_| is used instead to refer to // a url within our owner. const size_t index_in_owner_; // Whether the URL has been parsed. mutable bool parsed_; // Whether the url was successfully parsed. mutable bool valid_; // The parsed URL. All terms have been stripped out of this with // replacements_ giving the index of the terms to replace. mutable std::string parsed_url_; // Do we support search term replacement? mutable bool supports_replacements_; // The replaceable parts of url (parsed_url_). These are ordered by index // into the string, and may be empty. mutable Replacements replacements_; // Host, path, key and location of the search term. These are only set if the // url contains one search term. mutable std::string host_; mutable std::string path_; mutable std::string search_term_key_; mutable url_parse::Parsed::ComponentType search_term_key_location_; mutable PostParams post_params_; // Whether the contained URL is a pre-populated URL. bool prepopulated_; DISALLOW_COPY_AND_ASSIGN(TemplateURLRef); }; // TemplateURLData ------------------------------------------------------------ // The data for the TemplateURL. Separating this into its own class allows most // users to do SSA-style usage of TemplateURL: construct a TemplateURLData with // whatever fields are desired, then create an immutable TemplateURL from it. struct TemplateURLData { TemplateURLData(); ~TemplateURLData(); // A short description of the template. This is the name we show to the user // in various places that use TemplateURLs. For example, the location bar // shows this when the user selects a substituting match. string16 short_name; // The shortcut for this TemplateURL. |keyword| must be non-empty. void SetKeyword(const string16& keyword); const string16& keyword() const { return keyword_; } // The raw URL for the TemplateURL, which may not be valid as-is (e.g. because // it requires substitutions first). This must be non-empty. void SetURL(const std::string& url); const std::string& url() const { return url_; } // Optional additional raw URLs. std::string suggestions_url; std::string instant_url; std::string image_url; // The following post_params are comma-separated lists used to specify the // post parameters for the corresponding URL. std::string search_url_post_params; std::string suggestions_url_post_params; std::string instant_url_post_params; std::string image_url_post_params; // Optional favicon for the TemplateURL. GURL favicon_url; // URL to the OSD file this came from. May be empty. GURL originating_url; // Whether this TemplateURL is shown in the default list of search providers. // This is just a property and does not indicate whether the TemplateURL has a // TemplateURLRef that supports replacement. Use // TemplateURL::ShowInDefaultList() to test both. bool show_in_default_list; // Whether it's safe for auto-modification code (the autogenerator and the // code that imports data from other browsers) to replace the TemplateURL. // This should be set to false for any TemplateURL the user edits, or any // TemplateURL that the user clearly manually edited in the past, like a // bookmark keyword from another browser. bool safe_for_autoreplace; // The list of supported encodings for the search terms. This may be empty, // which indicates the terms should be encoded with UTF-8. std::vector<std::string> input_encodings; // Unique identifier of this TemplateURL. The unique ID is set by the // TemplateURLService when the TemplateURL is added to it. TemplateURLID id; // Date this TemplateURL was created. // // NOTE: this may be 0, which indicates the TemplateURL was created before we // started tracking creation time. base::Time date_created; // The last time this TemplateURL was modified by a user, since creation. // // NOTE: Like date_created above, this may be 0. base::Time last_modified; // True if this TemplateURL was automatically created by the administrator via // group policy. bool created_by_policy; // Number of times this TemplateURL has been explicitly used to load a URL. // We don't increment this for uses as the "default search engine" since // that's not really "explicit" usage and incrementing would result in pinning // the user's default search engine(s) to the top of the list of searches on // the New Tab page, de-emphasizing the omnibox as "where you go to search". int usage_count; // If this TemplateURL comes from prepopulated data the prepopulate_id is > 0. int prepopulate_id; // The primary unique identifier for Sync. This set on all TemplateURLs // regardless of whether they have been associated with Sync. std::string sync_guid; // A list of URL patterns that can be used, in addition to |url_|, to extract // search terms from a URL. std::vector<std::string> alternate_urls; // A parameter that, if present in the query or ref parameters of a search_url // or instant_url, causes Chrome to replace the URL with the search term. std::string search_terms_replacement_key; private: // Private so we can enforce using the setters and thus enforce that these // fields are never empty. string16 keyword_; std::string url_; }; // TemplateURL ---------------------------------------------------------------- // A TemplateURL represents a single "search engine", defined primarily as a // subset of the Open Search Description Document // (http://www.opensearch.org/Specifications/OpenSearch) plus some extensions. // One TemplateURL contains several TemplateURLRefs, which correspond to various // different capabilities (e.g. doing searches or getting suggestions), as well // as a TemplateURLData containing other details like the name, keyword, etc. // // TemplateURLs are intended to be read-only for most users; the only public // non-const method is the Profile getter, which returns a non-const Profile*. // The TemplateURLService, which handles storing and manipulating TemplateURLs, // is made a friend so that it can be the exception to this pattern. class TemplateURL { public: // |profile| may be NULL. This will affect the results of e.g. calling // ReplaceSearchTerms() on the member TemplateURLRefs. TemplateURL(Profile* profile, const TemplateURLData& data); ~TemplateURL(); // Generates a favicon URL from the specified url. static GURL GenerateFaviconURL(const GURL& url); Profile* profile() { return profile_; } const TemplateURLData& data() const { return data_; } const string16& short_name() const { return data_.short_name; } // An accessor for the short_name, but adjusted so it can be appropriately // displayed even if it is LTR and the UI is RTL. string16 AdjustedShortNameForLocaleDirection() const; const string16& keyword() const { return data_.keyword(); } const std::string& url() const { return data_.url(); } const std::string& suggestions_url() const { return data_.suggestions_url; } const std::string& instant_url() const { return data_.instant_url; } const std::string& image_url() const { return data_.image_url; } const std::string& search_url_post_params() const { return data_.search_url_post_params; } const std::string& suggestions_url_post_params() const { return data_.suggestions_url_post_params; } const std::string& instant_url_post_params() const { return data_.instant_url_post_params; } const std::string& image_url_post_params() const { return data_.image_url_post_params; } const std::vector<std::string>& alternate_urls() const { return data_.alternate_urls; } const GURL& favicon_url() const { return data_.favicon_url; } const GURL& originating_url() const { return data_.originating_url; } bool show_in_default_list() const { return data_.show_in_default_list; } // Returns true if show_in_default_list() is true and this TemplateURL has a // TemplateURLRef that supports replacement. bool ShowInDefaultList() const; bool safe_for_autoreplace() const { return data_.safe_for_autoreplace; } const std::vector<std::string>& input_encodings() const { return data_.input_encodings; } TemplateURLID id() const { return data_.id; } base::Time date_created() const { return data_.date_created; } base::Time last_modified() const { return data_.last_modified; } bool created_by_policy() const { return data_.created_by_policy; } int usage_count() const { return data_.usage_count; } int prepopulate_id() const { return data_.prepopulate_id; } const std::string& sync_guid() const { return data_.sync_guid; } // TODO(beaudoin): Rename this when renaming HasSearchTermsReplacementKey(). const std::string& search_terms_replacement_key() const { return data_.search_terms_replacement_key; } const TemplateURLRef& url_ref() const { return url_ref_; } const TemplateURLRef& suggestions_url_ref() const { return suggestions_url_ref_; } const TemplateURLRef& instant_url_ref() const { return instant_url_ref_; } const TemplateURLRef& image_url_ref() const { return image_url_ref_; } // Returns true if |url| supports replacement. bool SupportsReplacement() const; // Like SupportsReplacement but usable on threads other than the UI thread. bool SupportsReplacementUsingTermsData( const SearchTermsData& search_terms_data) const; // Returns true if this TemplateURL uses Google base URLs and has a keyword // of "google.TLD". We use this to decide whether we can automatically // update the keyword to reflect the current Google base URL TLD. bool IsGoogleSearchURLWithReplaceableKeyword() const; // Returns true if the keywords match or if // IsGoogleSearchURLWithReplaceableKeyword() is true for both TemplateURLs. bool HasSameKeywordAs(const TemplateURL& other) const; std::string GetExtensionId() const; bool IsExtensionKeyword() const; // Returns the total number of URLs comprised in this template, including // search and alternate URLs. size_t URLCount() const; // Gets the search URL at the given index. The alternate URLs, if any, are // numbered starting at 0, and the primary search URL follows. This is used // to decode the search term given a search URL (see // ExtractSearchTermsFromURL()). const std::string& GetURL(size_t index) const; // Use the alternate URLs and the search URL to match the provided |url| // and extract |search_terms| from it. Returns false and an empty // |search_terms| if no search terms can be matched. The order in which the // alternate URLs are listed dictates their priority, the URL at index 0 is // treated as the highest priority and the primary search URL is treated as // the lowest priority (see GetURL()). For example, if a TemplateURL has // alternate URL "http://foo/#q={searchTerms}" and search URL // "http://foo/?q={searchTerms}", and the URL to be decoded is // "http://foo/?q=a#q=b", the alternate URL will match first and the decoded // search term will be "b". bool ExtractSearchTermsFromURL(const GURL& url, string16* search_terms); // Like ExtractSearchTermsFromURL but usable on threads other than the UI // thread. bool ExtractSearchTermsFromURLUsingTermsData( const GURL& url, string16* search_terms, const SearchTermsData& search_terms_data); // Returns true if non-empty search terms could be extracted from |url| using // ExtractSearchTermsFromURL(). In other words, this returns whether |url| // could be the result of performing a search with |this|. bool IsSearchURL(const GURL& url); // Like IsSearchURL but usable on threads other than the UI thread. bool IsSearchURLUsingTermsData( const GURL& url, const SearchTermsData& search_terms_data); // Returns true if the specified |url| contains the search terms replacement // key in either the query or the ref. This method does not verify anything // else about the URL. In particular, it does not check that the domain // matches that of this TemplateURL. // TODO(beaudoin): Rename this to reflect that it really checks for an // InstantExtended capable URL. bool HasSearchTermsReplacementKey(const GURL& url) const; // Given a |url| corresponding to this TemplateURL, identifies the search // terms and replaces them with the ones in |search_terms_args|, leaving the // other parameters untouched. If the replacement fails, returns false and // leaves |result| untouched. This is used by mobile ports to perform query // refinement. bool ReplaceSearchTermsInURL( const GURL& url, const TemplateURLRef::SearchTermsArgs& search_terms_args, GURL* result); // Encodes the search terms from |search_terms_args| so that we know the // |input_encoding|. Returns the |encoded_terms| and the // |encoded_original_query|. |encoded_terms| may be escaped as path or query // depending on |is_in_query|; |encoded_original_query| is always escaped as // query. void EncodeSearchTerms( const TemplateURLRef::SearchTermsArgs& search_terms_args, bool is_in_query, std::string* input_encoding, string16* encoded_terms, string16* encoded_original_query) const; private: friend class TemplateURLService; void CopyFrom(const TemplateURL& other); void SetURL(const std::string& url); void SetPrepopulateId(int id); // Resets the keyword if IsGoogleSearchURLWithReplaceableKeyword() or |force|. // The |force| parameter is useful when the existing keyword is known to be // a placeholder. The resulting keyword is generated using // TemplateURLService::GenerateSearchURL() and // TemplateURLService::GenerateKeyword(). void ResetKeywordIfNecessary(bool force); // Uses the alternate URLs and the search URL to match the provided |url| // and extract |search_terms| from it as well as the |search_terms_component| // (either REF or QUERY) and |search_terms_component| at which the // |search_terms| are found in |url|. See also ExtractSearchTermsFromURL(). bool FindSearchTermsInURL( const GURL& url, const SearchTermsData& search_terms_data, string16* search_terms, url_parse::Parsed::ComponentType* search_terms_component, url_parse::Component* search_terms_position); Profile* profile_; TemplateURLData data_; TemplateURLRef url_ref_; TemplateURLRef suggestions_url_ref_; TemplateURLRef instant_url_ref_; TemplateURLRef image_url_ref_; // TODO(sky): Add date last parsed OSD file. DISALLOW_COPY_AND_ASSIGN(TemplateURL); }; #endif // CHROME_BROWSER_SEARCH_ENGINES_TEMPLATE_URL_H_
[ "1990zhaoshuang@163.com" ]
1990zhaoshuang@163.com
e4bb5f9a12f1471d0d0abeaa8e13d8ef961ec415
945c4caca43b36f711823d345cbd7cb860cb290d
/statGatherer.h
ea0ed7c5ac796a543ff3b61ab3d09749b9734728
[ "MIT" ]
permissive
payral/Cpp_DemographicStatistics
92ecdd29f48386ad236c7eff1cf2b78d95852fa9
efdc864b94b1d2b4153213d094021f402e3162db
refs/heads/main
2023-04-03T00:13:32.533692
2021-04-02T00:41:21
2021-04-02T00:41:21
353,857,496
0
0
null
null
null
null
UTF-8
C++
false
false
7,665
h
#ifndef STATGATHER_H #define STATGATHER_H #include <iostream> #include <vector> #include <iomanip> #include <math.h> #include "demogData.h" #include "comboHospitalData.h" #include "financeData.h" #include "visitorCombineState.h" #include "visitorCombineCounty.h" #include "stats.h" #include "statTool.h" /* helper parent functor to simplify stats gathering - the role of this functor is to gather data into two arrays. Takes in: -a regional level (county or state) visitor -vectors to fill in -varying number of function pointers for the class methods to use to fill in data */ class statGatherer { public: //function to gather mixed data (demographic and hospital) virtual void gatherPerStats(Visitor* Regions, vector<double> &XPer, vector<double> &YPer, double (demogData::*f1)() const, double (comboHospitalData::*f2)() const) = 0; //function to gather two demog datas virtual void gatherPerStats(Visitor* Regions, vector<double> &XPer, vector<double> &YPer, double (demogData::*f1)() const, double (demogData::*f2)() const) = 0; //function to gather two demog datas (percentages and counts - for accuracy with populations) virtual int gatherBothStats(Visitor* Regions, vector<double> &XPer, vector<double> &YPer, vector<double> &XCount, vector<double> &Ycount, double (demogData::*f1)() const, double (demogData::*f2)() const, int (demogData::*f3)() const, int (demogData::*f4)() const) = 0; }; /* actual functor implementation to gather county level stats (dervied from statGatherer) into two arrays. Takes in: -a regional level county visitor -vectors to fill in -varying number of function pointers for the class methods to use to fill in data */ class countyGather : public statGatherer { public: //function to gather mixed data (demographic and hospital) void gatherPerStats(Visitor* theCounties, vector<double> &XPer, vector<double> &YPer, double (demogData::*f1)() const, double (comboHospitalData::*f2)() const) { //for all demographic data for (auto entry : ((visitorCombineCounty *)theCounties)->countyDmap()) { //make sure there is valid hospital data! comboHospitalData* hospForCounty= ((visitorCombineCounty *)theCounties)->countyHmapEntry(entry.first); if ( hospForCounty != NULL ) { double xP = (entry.second->*f1)(); double yP = (hospForCounty->*f2)(); if (!isnan(xP) && !isnan(yP)) { YPer.push_back(yP); XPer.push_back(xP); } } } } //function to gather two demog datas void gatherPerStats(Visitor* theCounties, vector<double> &XPer, vector<double> &YPer, double (demogData::*f1)() const, double (demogData::*f2)() const) { { //for all demographic data for (auto entry : ((visitorCombineCounty *)theCounties)->countyDmap()) { double xP = (entry.second->*f1)(); double yP = (entry.second->*f2)(); if (!isnan(xP) && !isnan(yP)) { YPer.push_back(yP); XPer.push_back(xP); } } } } //function to gather two demog datas (percentages and counts) int gatherBothStats(Visitor* theCounties, vector<double> &XPer, vector<double> &YPer, vector<double> &XCount, vector<double> &Ycount, double (demogData::*f1)() const, double (demogData::*f2)() const, int (demogData::*f3)() const, int (demogData::*f4)() const) { //first functions for percentages gatherPerStats(theCounties, XPer, YPer, f1, f2); //now fill in the counts int totPop = 0; for (auto entry : ((visitorCombineCounty *)theCounties)->countyDmap()) { demogData* demogForC = entry.second; double xC = (entry.second->*f3)(); double yC = (entry.second->*f4)(); if (!isnan(xC) && !isnan(yC)) { XCount.push_back(xC); Ycount.push_back(yC); totPop += (entry.second)->getPop(); } } return totPop; } }; /* actual functor implementation to gather state level stats (dervied from statGatherer) into two arrays. Takes in: -a regional level state visitor -vectors to fill in -varying number of function pointers for the class methods to use to fill in data */ class stateGather : public statGatherer { public: //function to gather mixed data (demographic and hospital) void gatherPerStats(Visitor* theStates, vector<double> &XPer, vector<double> &YPer, double (demogData::*f1)() const, double(comboHospitalData::*f2)() const) { for (auto entry : ((visitorCombineState *)theStates)->stateDmap()) { comboHospitalData* hospForState = ((visitorCombineState *)theStates)->stateHmapEntry(entry.first); if (hospForState != NULL) { XPer.push_back(((entry.second)->*f1)()); YPer.push_back((hospForState->*f2)()); } } } void gatherPerStats(Visitor* theStates, vector<double> &XPer, vector<double> &YPer, double (demogData::*f1)() const, double(financeData::*f2)() const) { for (auto entry : ((visitorCombineState *)theStates)->stateDmap()) { financeData* financeForState = ((visitorCombineState *)theStates)->stateFmapEntry(entry.first); if (financeForState != NULL) { XPer.push_back(((entry.second)->*f1)()); YPer.push_back((financeForState->*f2)()); } } } void gatherPerStats(Visitor* theStates, vector<double> &XPer, vector<double> &YPer, double (comboHospitalData::*f1)() const, double(financeData::*f2)() const) { for (auto entry : ((visitorCombineState *)theStates)->stateHmap()) { financeData* financeForState = ((visitorCombineState *)theStates)->stateFmapEntry(entry.first); if (financeForState != NULL) { XPer.push_back(((entry.second)->*f1)()); YPer.push_back((financeForState->*f2)()); } } } //function to gather two demog datas void gatherPerStats(Visitor* theStates, vector<double> &XPer, vector<double> &YPer, double (demogData::*f1)() const, double(demogData::*f2)() const) { for (auto entry : ((visitorCombineState *)theStates)->stateDmap()) { XPer.push_back((entry.second->*f1)()); YPer.push_back((entry.second->*f2)()); } } //function to gather two demog datas (percentages and counts) int gatherBothStats(Visitor* theStates, vector<double> &XPer, vector<double> &YPer, vector<double> &XCount, vector<double> &Ycount, double (demogData::*f1)() const, double(demogData::*f2)() const, int (demogData::*f3)() const, int (demogData::*f4)() const) { //fill in the percentage stats gatherPerStats(theStates, XPer, YPer, f1, f2); int totPop = 0; for (auto entry : ((visitorCombineState *)theStates)->stateDmap()) { XCount.push_back((entry.second->*f3)()); Ycount.push_back((entry.second->*f4)()); totPop += entry.second->getPop(); } return totPop; } }; #endif
[ "noreply@github.com" ]
noreply@github.com
8cb04aeffa3045c3d602a86b1551b7667e3cf82b
6d24505aa84b20e97348a7d0bb2d930d311af8b3
/Proto/proj.win32/DoorUI.h
f5ed848d9e19c655924a441f08f4897866d7b129
[]
no_license
aismann/EscapeAction
1eadfad8617201211309c8e431f2224151bf5f3a
ce4a859257a59e50c9a3f7172c903b03372571cc
refs/heads/master
2022-03-20T20:14:00.645094
2019-12-04T08:22:41
2019-12-04T08:22:41
null
0
0
null
null
null
null
UHC
C++
false
false
546
h
#pragma once #include "external/json/document.h" #include "external/json/filereadstream.h"//파일을 열어오기위함 #include <cstdio> #include "cocos2d.h" #include "ui/CocosGUI.h" USING_NS_CC; using namespace std; using namespace rapidjson; class DoorUI : public Node { public: CREATE_FUNC(DoorUI); virtual bool init(); void setBtnVisible(int num, bool setBool); ~DoorUI(); private: Document trans_door; Vector<ui::Button*> v_btn; vector<int> v_left; vector<int> v_right; vector<bool> v_lock; //함수 void clickBtn(int num); };
[ "khr95039@gmail.com" ]
khr95039@gmail.com
29c1e37524a5d6d4afb9a251846fd0b9af0d6411
65fc85ed595c778e46973ddd24f6f75059f9e84e
/201 - 400/382. Linked List Random Node.cc
5d6c76ff74f2a6217774a4792b1c013f6826ed26
[]
no_license
zzzmfps/LeetCode
a39c25ccfa5891c9ad895350b30f0f2e98cdc636
8d5576eb2b82a0b575634c14367527560c1ec5d5
refs/heads/master
2021-10-10T01:06:40.123201
2021-09-28T03:33:25
2021-09-28T03:33:25
122,027,173
0
0
null
null
null
null
UTF-8
C++
false
false
1,587
cc
// 30ms, 99.76% #include <bits/stdc++.h> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; static int x = []() { ios_base::sync_with_stdio(false); // toggles off the synchronization cin.tie(nullptr); // ties cin with nullptr, not cout return 0; }(); class Solution { private: ListNode *a_list; default_random_engine generator = default_random_engine(); public: /** @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. */ Solution(ListNode *head) : a_list(head) {} /** Returns a random node's value. */ int getRandom() { // failed to include <chrono> on leetcode.com // unsigned seed = chrono::system_clock::now().time_since_epoch().count(); // accepted - default_random_engine generator(seed); // failed - default_random_engine generator(); // move generator outside the function, avoid initializing it at every function call uniform_real_distribution<double> urd(0.0, 1.0); ListNode *trav = a_list; int length = 0; while (trav) { trav = trav->next; ++length; } trav = a_list, length *= urd(generator); while (length) { trav = trav->next; --length; } return trav->val; } }; /** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(head); * int param_1 = obj.getRandom(); */
[ "zzz100826@gmail.com" ]
zzz100826@gmail.com
84292a3524e227f3b742b6c50dcf56b4f4154c82
358e08c4e34e66637830001f571709ff6f9990f3
/Demo.cpp
8315161397b881a8e9cad44b17d1633f431ecc18
[ "MIT" ]
permissive
arihamara/pixie_demo
1944eeff454085eab781a75363d08623b2424823
b6938f740d39144363d72fd1463a59ceefe8bfc0
refs/heads/master
2022-11-29T16:03:13.739280
2020-08-05T18:18:11
2020-08-05T18:18:11
285,369,933
0
0
null
null
null
null
UTF-8
C++
false
false
5,225
cpp
#include <algorithm> #include <stdio.h> #include <string.h> #include <algorithm> #include <vector> #include <iostream> #include <iterator> #include "Demo.h" #include <math.h> #include "triangle.h" #define MIN(a,b) (((a)<(b))?(a):(b)) #define MAX(a,b) (((a)>(b))?(a):(b)) #define RGB(r,g,b) ((b)|((g)<<8)|((r)<<16)) float time = 0; uchar* screen; uint* palette; //#define USE_SBUF #ifdef USE_SBUF mfloat_t position[120][VEC3_SIZE]; #define byte unsigned char typedef struct { short xb, xe, zb, ze; // x_begin, x_end, ... byte ub, ue, vb, ve; long kz, ku, kv; // kz = (ze-zb)*65536/(xe-xb) etc sbuf_t* next; sbuf_t* prev; } sbuf_t; sbuf_t* sbufList[200]; // 200 lines in mode 320x200, #endif void Init() { palette = new uint[256]; for (int i = 0; i < 256; i++) { palette[i] = RGB(rand(), rand(), rand()) ; } } void project3dto2d(float outCoord[VEC2_SIZE], mfloat_t inCoord[VEC3_SIZE] ) { outCoord[0] = inCoord[0] * 512 / (inCoord[2]+256) + 160; outCoord[1] = inCoord[1] * 512 / (inCoord[2]+256) + 120; } void swap(float& a, float& b) { float temp = a; a = b; b = temp; } void swap(short& a, short& b) { short temp = a; a = b; b = temp; } void putPixel(int x, int y, uchar c ) { screen[y * WindowWidth + x] = c; } void horizLine(int x0, int x2, int y, uchar color) { x2 = MIN(x2, WindowWidth - 1); x2 = MAX(0, x2); if (x2 < x0) { int t = x2; x2 = x0; x0 = t; } for (int i = x0; i < x2; i++) { putPixel(i, y, color); } } void triFill2(float p[3][VEC2_SIZE], uchar col) { if (p[1][1] < p[0][1]) { swap(p[0][1], p[1][1]); swap(p[0][0], p[1][0]); } if (p[2][1] < p[1][1]) { swap(p[2][1], p[1][1]); swap(p[2][0], p[1][0]); } if (p[1][1] < p[0][1]) { swap(p[0][1], p[1][1]); swap(p[0][0], p[1][0]); } int y = (int)p[0][1]; float xac = p[0][0]; float xab = p[0][0]; float xbc = p[1][0]; float xaci = 0; float xabi = 0; float xbci = 0; if ((int)p[1][1] != (int)p[0][1]) xabi = ((p[1][0] - p[0][0])) / (int)(p[1][1] - (int)p[0][1]); if ((int)p[2][1] != (int)p[0][1]) xaci = ((p[2][0] - p[0][0])) / (int)(p[2][1] - (int)p[0][1]); if ((int)p[2][1] != (int)p[1][1]) xbci = ((p[2][0] - p[1][0])) / (int)(p[2][1] - (int)p[1][1]); for (; y < p[1][1] && y < WindowHeight; y++) { if (y >= 0) horizLine((int)xab, (int)xac, y, col); xab += xabi; xac += xaci; } for (; y < p[2][1] && y < WindowHeight; y++) { if (y >= 0) horizLine((int)xbc, (int)xac, y, col); xbc += xbci; xac += xaci; } } void trifill3D(mfloat_t* v0, mfloat_t* v1, mfloat_t* v2, uchar col) { float p[3][2]; project3dto2d(p[0], v0); project3dto2d(p[1], v1); project3dto2d(p[2], v2); triFill2(p, col); } void ClearScreen(uchar c) { memset(screen, c, WindowWidth * WindowHeight); } /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ int partition(float arrZ[], short arrIndex[], int low, int high) { float pivot = arrZ[high]; // pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high - 1; j++) { // If current element is smaller than the pivot if (arrZ[j] < pivot) { i++; // increment index of smaller element swap(arrZ[i], arrZ[j]); swap(arrIndex[i], arrIndex[j]); } } swap(arrZ[i + 1], arrZ[high]); swap(arrIndex[i+1], arrIndex[high]); return (i + 1); } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ void quickSort(float arrZ[], short arrIndex[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arrZ, arrIndex, low, high); // Separately sort elements before // partition and after partition quickSort(arrZ, arrIndex, low, pi - 1); quickSort(arrZ, arrIndex, pi + 1, high); } } void DrawFrame(int dt) { for (int i = 0; i < 200; i++) { } time += dt * 0.001f; mfloat_t objectMatrix[MAT4_SIZE]; ClearScreen(0xee); #define VERTICES 12 short drawOrder[VERTICES / 3]; float triZ[VERTICES / 3]; mfloat_t p[VERTICES][VEC4_SIZE] = { { 0, -30, 0,1 }, { -30, 30, 30,1 }, { 30, 30, 30,1 }, { 0, -30, 0,1 }, { 30, 30, -30,1 }, { 30, 30, 30,1 }, { 0, -30, 0,1 }, { -30, 30, -30,1 }, { 30, 30, -30,1 }, { 0, -30, 0,1 }, { -30, 30, 30,1 }, { -30, 30, -30,1 }, }; mat4_identity(objectMatrix); mfloat_t translateVector[VEC4_SIZE] = {10+sin(time*0.4f)*30, 0, sin(time * 3.1f) * 30, 1}; mat4_rotation_y(objectMatrix, time); // mat4_rotation_x(objectMatrix, time*0.3); //mat4_translation(objectMatrix, objectMatrix, translateVector); for (int i = 0; i < VERTICES; i++) { vec4_multiply_mat4(p[i], p[i], objectMatrix); } // sort points for (int i = 0; i < VERTICES; i += 3) { // Calc Z triZ[i/3] = (p[i + 0][2]+p[i + 1][2]+p[i + 2][2])*0.33333f; drawOrder[i / 3] = i / 3; } quickSort(triZ, drawOrder, 0, VERTICES/3 - 1); for (int i = 0; i < VERTICES/3;i++ ) { trifill3D(p[drawOrder[i]*3 + 0], p[drawOrder[i]*3 + 1], p[drawOrder[i]*3 + 2], 0x22+drawOrder[i]); } }
[ "ari.hamara@supercell.com" ]
ari.hamara@supercell.com
c84a8cb23d16f4f8d6f99d07e8f79882f3dd957f
a5a7b494613b13e7e5294f39dec54e5f43445df9
/교육/C++ Basic/Day_08/const.cpp
f1177be5779e904a2b8468c19508520aa0c2b413
[]
no_license
deanlee-practice/toheaven-2
22f99e6531b143c856f06d713ca000b4f51ea7f9
52e78e585e7a4372bb8ca86c0fc104206d7bbe76
refs/heads/master
2023-06-16T10:35:49.664923
2021-07-06T13:05:30
2021-07-06T13:05:30
null
0
0
null
null
null
null
UHC
C++
false
false
2,512
cpp
/* 생성자 초기화 클래스의 const, static 변수 레퍼런스 타입을 리턴하는 함수 this 포인터 const 멤버 함수 */ #include <iostream> using namespace std; class Marine { static int total_marine_num; int hp; // 마린 체력 int coord_x, coord_y; // 마린 위치 //int damage; // 공격력 bool is_dead; // 생사확인 // 기본 공격력 const int default_damage; // const , final - 선언하면 값을 바꿀 수 없음 public: Marine(); // 기본생성자 Marine(int x, int y); // x, y 좌표에 있는 마린 생성 Marine(int x, int y, int default_damage); int attack(); // 데미지 리턴 void be_attacked(int damage_earn); // 피해 데미지 void move(int x, int y); // 새로운 위치 void show_status(); // 상태 출력 ~Marine() { total_marine_num--; } }; int Marine::total_marine_num = 0; Marine::Marine() : hp(50), coord_x(0), coord_y(0), default_damage(5), is_dead(false) { total_marine_num++; } Marine::Marine(int x, int y) : hp(50), coord_x(x), coord_y(y), default_damage(5), is_dead(false) { total_marine_num++; } Marine::Marine(int x, int y, int default_damage) : hp(50), coord_x(x), coord_y(y), /*damage(5),*/ is_dead(false), default_damage(default_damage) { total_marine_num++; } int Marine::attack() { // 데미지 리턴 return default_damage;//damage; } void Marine::be_attacked(int damage_earn) { // 피해 데미지 hp -= damage_earn; if (hp <= 0) is_dead = true; } void Marine::move(int x, int y) { // 새로운 위치 coord_x = x; coord_y = y; } void Marine::show_status() { cout << " *** Marine *** " << endl; cout << "Location : (" << coord_x << ", " << coord_y << ")" << endl; cout << "HP : " << hp << endl; cout << "현재 총 마린 수 : " << total_marine_num << endl; } void create_marine() { Marine marine3(10, 10, 4); marine3.show_status(); } int main() { Marine marine1(2, 3, 10); marine1.show_status(); Marine marine2(3, 5, 10); marine2.show_status(); cout << "마린1이 마린2를 공격!" << endl; marine2.be_attacked(marine1.attack()); marine1.show_status(); marine2.show_status(); create_marine(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
d28982c65abdda67009f9946ca51f5710bf55d60
c8029ea41c7dcdde4330bcd6d7ef4f9fe248b75d
/src/kbase/string_format.cpp
b6a99be2d578736a5a3cea9f436feb8b5bafd467
[ "MIT" ]
permissive
ExpLife0011/KBase
e956181c735fd469ba616c8c6547daa394181398
c012339344b35394f6eba23a32d408c80beb8e8f
refs/heads/master
2020-03-20T03:49:02.847354
2018-02-16T07:44:08
2018-02-16T07:44:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,068
cpp
/* @ 0xCCCCCCCC */ #include "kbase/string_format.h" #include "kbase/basic_macros.h" #include "kbase/scope_guard.h" #if defined(OS_POSIX) #include <cstdarg> #endif namespace { using kbase::FormatError; using kbase::NotReached; using kbase::internal::FormatTraits; using kbase::internal::Placeholder; using kbase::internal::PlaceholderList; using kbase::internal::IsDigit; using kbase::internal::StrToUL; enum class FormatParseState { InText, InFormat }; constexpr char kEscapeBegin = '{'; constexpr char kEscapeEnd = '}'; constexpr char kSpecifierDelimeter = ':'; constexpr char kPlaceholderMark = '@'; void AppendPrintfT(std::string& str, char* buf, size_t max_count_including_null, const char* fmt, va_list args) { va_list args_copy; va_copy(args_copy, args); int real_size = vsnprintf(buf, max_count_including_null, fmt, args_copy); va_end(args_copy); ENSURE(THROW, real_size >= 0)(real_size).Require(); if (static_cast<size_t>(real_size) < max_count_including_null) { // vsnprintf() guarantees the resulting string will be terminated with a null-terminator. str.append(buf); return; } std::vector<char> backup_buf(real_size + 1); va_copy(args_copy, args); vsnprintf(backup_buf.data(), backup_buf.size(), fmt, args_copy); va_end(args_copy); str.append(backup_buf.data()); } void AppendPrintfT(std::wstring& str, wchar_t* buf, size_t max_count_including_null, const wchar_t* fmt, va_list args) { va_list args_copy; va_copy(args_copy, args); int rv = vswprintf(buf, max_count_including_null, fmt, args_copy); va_end(args_copy); if (rv >= 0) { str.append(buf, rv); return; } constexpr size_t kMaxAllowed = 16U * 1024 * 1024; size_t tentative_count = max_count_including_null; std::vector<wchar_t> backup_buf; while (true) { tentative_count <<= 1; ENSURE(THROW, tentative_count <= kMaxAllowed)(tentative_count)(kMaxAllowed).Require(); backup_buf.resize(tentative_count); va_copy(args_copy, args); rv = vswprintf(backup_buf.data(), backup_buf.size(), fmt, args_copy); va_end(args_copy); if (rv > 0) { str.append(backup_buf.data(), rv); break; } } } template<typename StrT> void StringAppendPrintfT(StrT& str, const typename StrT::value_type* fmt, va_list args) { using CharT = typename StrT::value_type; constexpr size_t kDefaultCount = 1024U; CharT buf[kDefaultCount]; AppendPrintfT(str, buf, kDefaultCount, fmt, args); } template<typename CharT> size_t ExtractPlaceholderIndex(const CharT* first_digit, CharT*& last_digit) { auto index = StrToUL(first_digit, last_digit); --last_digit; return index; } template<typename CharT> typename FormatTraits<CharT>::String AnalyzeFormatT(const CharT* fmt, PlaceholderList<CharT>& placeholders) { constexpr size_t kInitialCapacity = 32; typename FormatTraits<CharT>::String analyzed_fmt; analyzed_fmt.reserve(kInitialCapacity); placeholders.clear(); Placeholder<CharT> placeholder; auto state = FormatParseState::InText; for (auto ptr = fmt; *ptr != '\0'; ++ptr) { if (*ptr == kEscapeBegin) { // `{` is an invalid token for in-format state. ENSURE(THROW, state != FormatParseState::InFormat).ThrowIn<FormatError>().Require(); if (*(ptr + 1) == kEscapeBegin) { // Use `{{` to represent literal `{`. analyzed_fmt += kEscapeBegin; ++ptr; } else if (IsDigit(*(ptr + 1))) { CharT* last_digit; placeholder.index = ExtractPlaceholderIndex(ptr + 1, last_digit); ptr = last_digit; ENSURE(THROW, (*(ptr + 1) == kEscapeEnd) || (*(ptr + 1) == kSpecifierDelimeter)).ThrowIn<FormatError>() .Require(); if (*(ptr + 1) == kSpecifierDelimeter) { ++ptr; } // Turn into in-format state. state = FormatParseState::InFormat; } else { ENSURE(THROW, NotReached()).ThrowIn<FormatError>().Require(); } } else if (*ptr == kEscapeEnd) { if (state == FormatParseState::InText) { ENSURE(THROW, *(ptr + 1) == kEscapeEnd).ThrowIn<FormatError>().Require(); analyzed_fmt += kEscapeEnd; ++ptr; } else { placeholder.pos = analyzed_fmt.length(); analyzed_fmt += kPlaceholderMark; placeholders.push_back(placeholder); placeholder.format_specifier.clear(); // Now we turn back into in-text state. state = FormatParseState::InText; } } else { if (state == FormatParseState::InText) { analyzed_fmt += *ptr; } else { placeholder.format_specifier += *ptr; } } } ENSURE(THROW, state == FormatParseState::InText).ThrowIn<FormatError>().Require(); std::sort(std::begin(placeholders), std::end(placeholders), [](const auto& lhs, const auto& rhs) { return lhs.index < rhs.index; }); return analyzed_fmt; } } // namespace namespace kbase { void StringAppendPrintf(std::string& str, const char* fmt, ...) { va_list args; va_start(args, fmt); ON_SCOPE_EXIT { va_end(args); }; StringAppendPrintfT(str, fmt, args); } void StringAppendPrintf(std::wstring& str, const wchar_t* fmt, ...) { va_list args; va_start(args, fmt); ON_SCOPE_EXIT { va_end(args); }; StringAppendPrintfT(str, fmt, args); } std::string StringPrintf(const char* fmt, ...) { va_list args; va_start(args, fmt); ON_SCOPE_EXIT { va_end(args); }; std::string str; StringAppendPrintfT(str, fmt, args); return str; } std::wstring StringPrintf(const wchar_t* fmt, ...) { va_list args; va_start(args, fmt); ON_SCOPE_EXIT { va_end(args); }; std::wstring str; StringAppendPrintfT(str, fmt, args); return str; } void StringPrintf(std::string& str, const char* fmt, ...) { va_list args; va_start(args, fmt); ON_SCOPE_EXIT { va_end(args); }; str.clear(); StringAppendPrintfT(str, fmt, args); } void StringPrintf(std::wstring& str, const wchar_t* fmt, ...) { va_list args; va_start(args, fmt); ON_SCOPE_EXIT { va_end(args); }; str.clear(); StringAppendPrintfT(str, fmt, args); } namespace internal { std::string AnalyzeFormat(const char* fmt, PlaceholderList<char>& placeholders) { return AnalyzeFormatT(fmt, placeholders); } std::wstring AnalyzeFormat(const wchar_t* fmt, PlaceholderList<wchar_t>& placeholders) { return AnalyzeFormatT(fmt, placeholders); } } // namespace internal } // namespace kbase
[ "kingsamchen@gmail.com" ]
kingsamchen@gmail.com
2422dd649bd7425c86235ba710a13456f8f5ba19
33b59f7ddb64b9464e68d281a8d2dd6dc1f63d47
/source/octoon-graphics/OpenGL 20/gl20_shader.cpp
0ca4f40f99a5bb6a0ee941853c64c8705dfad554
[ "MIT" ]
permissive
superowner/octoon
24913edde75963a1414728c07f679fe024552777
2957132f9b00927a7d177ae21db20c5c7233a56f
refs/heads/master
2020-03-22T15:56:25.741567
2018-06-13T02:26:27
2018-06-13T02:26:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,062
cpp
#include "gl20_shader.h" #include "gl20_device.h" #if defined(__WINDOWS__) && defined(OCTOON_FEATURE_GRAPHICS_USE_HLSL) # define EXCLUDE_PSTDINT # include <hlslcc.hpp> # include <sstream> # include <d3dcompiler.h> #endif namespace octoon { namespace graphics { OctoonImplementSubClass(GL20Shader, GraphicsShader, "GL20Shader") OctoonImplementSubClass(GL20Program, GraphicsProgram, "GL20Program") OctoonImplementSubClass(GL20GraphicsAttribute, GraphicsAttribute, "GL20GraphicsAttribute") OctoonImplementSubClass(GL20GraphicsUniform, GraphicsUniform, "GL20GraphicsUniform") GL20GraphicsAttribute::GL20GraphicsAttribute() noexcept : _semanticIndex(0) , _bindingPoint(GL_INVALID_INDEX) , _type(GraphicsFormat::Undefined) { } GL20GraphicsAttribute::~GL20GraphicsAttribute() noexcept { } void GL20GraphicsAttribute::setSemantic(const std::string& semantic) noexcept { _semantic = semantic; } const std::string& GL20GraphicsAttribute::getSemantic() const noexcept { return _semantic; } void GL20GraphicsAttribute::setSemanticIndex(std::uint32_t index) noexcept { _semanticIndex = index; } std::uint32_t GL20GraphicsAttribute::getSemanticIndex() const noexcept { return _semanticIndex; } void GL20GraphicsAttribute::setType(GraphicsFormat type) noexcept { _type = type; } GraphicsFormat GL20GraphicsAttribute::getType() const noexcept { return _type; } void GL20GraphicsAttribute::setBindingPoint(std::uint32_t bindingPoint) noexcept { _bindingPoint = bindingPoint; } std::uint32_t GL20GraphicsAttribute::getBindingPoint() const noexcept { return _bindingPoint; } GL20GraphicsUniform::GL20GraphicsUniform() noexcept : _offset(0) , _bindingPoint(GL_INVALID_INDEX) , _type(GraphicsUniformType::Null) , _stageFlags(0) { } GL20GraphicsUniform::~GL20GraphicsUniform() noexcept { } void GL20GraphicsUniform::setName(const std::string& name) noexcept { _name = name; } const std::string& GL20GraphicsUniform::getName() const noexcept { return _name; } void GL20GraphicsUniform::setSamplerName(const std::string& name) noexcept { _samplerName = name; } const std::string& GL20GraphicsUniform::getSamplerName() const noexcept { return _samplerName; } void GL20GraphicsUniform::setType(GraphicsUniformType type) noexcept { _type = type; } GraphicsUniformType GL20GraphicsUniform::getType() const noexcept { return _type; } void GL20GraphicsUniform::setOffset(std::uint32_t offset) noexcept { _offset = offset; } std::uint32_t GL20GraphicsUniform::getOffset() const noexcept { return _offset; } void GL20GraphicsUniform::setBindingPoint(GLuint bindingPoint) noexcept { _bindingPoint = bindingPoint; } GLuint GL20GraphicsUniform::getBindingPoint() const noexcept { return _bindingPoint; } void GL20GraphicsUniform::setShaderStageFlags(GraphicsShaderStageFlags flags) noexcept { _stageFlags = flags; } GraphicsShaderStageFlags GL20GraphicsUniform::getShaderStageFlags() const noexcept { return _stageFlags; } GL20Shader::GL20Shader() noexcept : _instance(GL_NONE) { } GL20Shader::~GL20Shader() noexcept { this->close(); } bool GL20Shader::setup(const GraphicsShaderDesc& shaderDesc) noexcept { assert(_instance == GL_NONE); assert(shaderDesc.getByteCodes().size() > 0); assert(GL20Types::asShaderStage(shaderDesc.getStage()) != GL_INVALID_ENUM); _instance = glCreateShader(GL20Types::asShaderStage(shaderDesc.getStage())); if (_instance == GL_NONE) { GL_PLATFORM_LOG("glCreateShader() fail."); return false; } std::string codes = shaderDesc.getByteCodes().data(); if (shaderDesc.getLanguage() == GraphicsShaderLang::HLSL) { #if defined(__WINDOWS__) && defined(OCTOON_FEATURE_GRAPHICS_USE_HLSL) if (!HlslCodes2GLSL(shaderDesc.getStage(), shaderDesc.getByteCodes().data(), codes)) { GL_PLATFORM_LOG("Can't conv hlsl to glsl."); return false; } #else return false; #endif } else if (shaderDesc.getLanguage() == GraphicsShaderLang::HLSLbytecodes) { #if defined(__WINDOWS__) && defined(OCTOON_FEATURE_GRAPHICS_USE_HLSL) if (!HlslByteCodes2GLSL(shaderDesc.getStage(), shaderDesc.getByteCodes().data(), codes)) { GL_PLATFORM_LOG("Can't conv hlslbytecodes to glsl."); return false; } #else return false; #endif } const char* source = codes.data(); glShaderSource(_instance, 1, &source, 0); glCompileShader(_instance); GLint result = GL_FALSE; glGetShaderiv(_instance, GL_COMPILE_STATUS, &result); if (GL_FALSE == result) { GLint length = 0; glGetShaderiv(_instance, GL_INFO_LOG_LENGTH, &length); std::string log((std::size_t)length, 0); glGetShaderInfoLog(_instance, length, &length, (char*)log.data()); GL_PLATFORM_LOG(log.c_str()); return false; } _shaderDesc = shaderDesc; return true; } void GL20Shader::close() noexcept { if (_instance != GL_NONE) { glDeleteShader(_instance); _instance = GL_NONE; } } GLuint GL20Shader::getInstanceID() const noexcept { return _instance; } bool GL20Shader::HlslCodes2GLSL(GraphicsShaderStageFlags stage, const std::string& codes, std::string& out) { #if defined(OCTOON_BUILD_PLATFORM_WINDOWS) && defined(OCTOON_FEATURE_GRAPHICS_USE_HLSL) std::string profile; if (stage == GraphicsShaderStageFlagBits::VertexBit) profile = "vs_4_0"; else if (stage == GraphicsShaderStageFlagBits::FragmentBit) profile = "ps_4_0"; ID3DBlob* binary = nullptr; ID3DBlob* error = nullptr; D3DCreateBlob(4096, &binary); D3DCreateBlob(4096, &error); HRESULT hr = D3DCompile( codes.data(), codes.size(), nullptr, nullptr, nullptr, "main", profile.c_str(), D3DCOMPILE_OPTIMIZATION_LEVEL3, 0, &binary, &error ); if (hr != S_OK) { std::string line; std::size_t index = 1; std::ostringstream ostream; std::istringstream istream(codes); ostream << (const char*)error->GetBufferPointer() << std::endl; while (std::getline(istream, line)) { ostream << index << '\t' << line << std::endl; index++; } GL_PLATFORM_LOG(ostream.str().c_str()); } return HlslByteCodes2GLSL(stage, (char*)binary->GetBufferPointer(), out); #else return false; #endif } bool GL20Shader::HlslByteCodes2GLSL(GraphicsShaderStageFlags stage, const char* codes, std::string& out) { #if defined(OCTOON_BUILD_PLATFORM_WINDOWS) && defined(OCTOON_FEATURE_GRAPHICS_USE_HLSL) std::uint32_t flags = HLSLCC_FLAG_COMBINE_TEXTURE_SAMPLERS | HLSLCC_FLAG_INOUT_APPEND_SEMANTIC_NAMES | HLSLCC_FLAG_DISABLE_GLOBALS_STRUCT; if (stage == GraphicsShaderStageFlagBits::GeometryBit) flags = HLSLCC_FLAG_GS_ENABLED; else if (stage == GraphicsShaderStageFlagBits::TessControlBit) flags = HLSLCC_FLAG_TESS_ENABLED; else if (stage == GraphicsShaderStageFlagBits::TessEvaluationBit) flags = HLSLCC_FLAG_TESS_ENABLED; GLSLShader shader; GLSLCrossDependencyData dependency; if (!TranslateHLSLFromMem(codes, flags, GLLang::LANG_ES_300, 0, nullptr, &dependency, &shader)) { FreeGLSLShader(&shader); return false; } if (stage == GraphicsShaderStageFlagBits::VertexBit) { glslopt_shader_type glslopt_type = glslopt_shader_type::kGlslOptShaderVertex; if (stage == GraphicsShaderStageFlagBits::FragmentBit) glslopt_type = glslopt_shader_type::kGlslOptShaderFragment; auto ctx = glslopt_initialize(glslopt_target::kGlslTargetOpenGLES30); if (ctx) { glslopt_shader* glslopt_shader = glslopt_optimize(ctx, glslopt_type, shader.sourceCode, 0); bool optimizeOk = glslopt_get_status(glslopt_shader); if (!optimizeOk) { glslopt_cleanup(ctx); FreeGLSLShader(&shader); return false; } out = glslopt_get_output(glslopt_shader); glslopt_cleanup(ctx); } } else { out = shader.sourceCode; } out = shader.sourceCode; FreeGLSLShader(&shader); return true; #else return false; #endif } const GraphicsShaderDesc& GL20Shader::getGraphicsShaderDesc() const noexcept { return _shaderDesc; } void GL20Shader::setDevice(GraphicsDevicePtr device) noexcept { _device = device; } GraphicsDevicePtr GL20Shader::getDevice() noexcept { return _device.lock(); } GL20Program::GL20Program() noexcept : _program(GL_NONE) { } GL20Program::~GL20Program() noexcept { this->close(); } bool GL20Program::setup(const GraphicsProgramDesc& programDesc) noexcept { assert(_program == GL_NONE); _program = glCreateProgram(); for (auto& shader : programDesc.getShaders()) { assert(shader->isInstanceOf<GL20Shader>()); auto glshader = shader->downcast<GL20Shader>(); if (glshader) glAttachShader(_program, glshader->getInstanceID()); } glLinkProgram(_program); GLint status = GL_FALSE; glGetProgramiv(_program, GL_LINK_STATUS, &status); if (!status) { GLint length = 0; glGetProgramiv(_program, GL_INFO_LOG_LENGTH, &length); std::string log((std::size_t)length, 0); glGetProgramInfoLog(_program, length, &length, (GLchar*)log.data()); GL_PLATFORM_LOG(log.c_str()); return false; } glUseProgram(_program); _initActiveAttribute(); _initActiveUniform(); glUseProgram(GL_NONE); _programDesc = programDesc; return true; } void GL20Program::close() noexcept { if (_program != GL_NONE) { glDeleteProgram(_program); _program = GL_NONE; } _activeAttributes.clear(); _activeParams.clear(); } void GL20Program::apply() noexcept { glUseProgram(_program); } GLuint GL20Program::getInstanceID() const noexcept { return _program; } const GraphicsParams& GL20Program::getActiveParams() const noexcept { return _activeParams; } const GraphicsAttributes& GL20Program::getActiveAttributes() const noexcept { return _activeAttributes; } void GL20Program::_initActiveAttribute() noexcept { GLint numAttribute = 0; GLint maxAttribute = 0; glGetProgramiv(_program, GL_ACTIVE_ATTRIBUTES, &numAttribute); glGetProgramiv(_program, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &maxAttribute); if (numAttribute) { auto nameAttribute = std::make_unique<GLchar[]>(maxAttribute + 1); nameAttribute[maxAttribute] = 0; for (GLint i = 0; i < numAttribute; ++i) { GLint size; GLenum type; glGetActiveAttrib(_program, (GLuint)i, maxAttribute, GL_NONE, &size, &type, nameAttribute.get()); GLint location = glGetAttribLocation(_program, nameAttribute.get()); if (location == GL_INVALID_INDEX) continue; std::string name = nameAttribute.get(); std::string semantic; std::uint32_t semanticIndex = 0; auto it = std::find_if_not(name.rbegin(), name.rend(), [](char ch) { return ch >= '0' && ch <= '9'; }); if (it != name.rend()) { semantic = name.substr(0, name.rend() - it); semanticIndex = std::stoi(name.substr(name.rend() - it)); } std::size_t off = semantic.find_last_of('_'); if (off != std::string::npos) semantic = semantic.substr(off + 1); else semantic = semantic; auto attrib = std::make_shared<GL20GraphicsAttribute>(); attrib->setSemantic(semantic); attrib->setSemanticIndex(semanticIndex); attrib->setBindingPoint(location); attrib->setType(toGraphicsFormat(type)); _activeAttributes.push_back(attrib); } } } void GL20Program::_initActiveUniform() noexcept { GLint numUniform = 0; GLint maxUniformLength = 0; glGetProgramiv(_program, GL_ACTIVE_UNIFORMS, &numUniform); glGetProgramiv(_program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxUniformLength); if (numUniform == 0) return; std::string nameUniform(maxUniformLength + 1, 0); GLint textureUnit = 0; for (GLint i = 0; i < numUniform; ++i) { GLint size; GLenum type; GLsizei length; glGetActiveUniform(_program, (GLuint)i, maxUniformLength, &length, &size, &type, (GLchar*)nameUniform.c_str()); GLint location = glGetUniformLocation(_program, nameUniform.c_str()); if (location == GL_INVALID_INDEX) continue; auto uniform = std::make_shared<GL20GraphicsUniform>(); uniform->setName(nameUniform.substr(0, std::min((std::size_t)length, nameUniform.find('[')))); uniform->setBindingPoint(location); uniform->setType(toGraphicsUniformType(nameUniform, type)); uniform->setShaderStageFlags(GraphicsShaderStageFlagBits::All); if (type == GL_SAMPLER_2D || type == GL_SAMPLER_CUBE) { auto pos = nameUniform.find_first_of("_X_"); if (pos != std::string::npos) { uniform->setName(nameUniform.substr(0, pos)); uniform->setSamplerName(nameUniform.substr(pos + 3)); } glUniform1i(location, textureUnit); uniform->setBindingPoint(textureUnit); uniform->setShaderStageFlags(GraphicsShaderStageFlagBits::All); textureUnit++; } _activeParams.push_back(uniform); } } GraphicsFormat GL20Program::toGraphicsFormat(GLenum type) noexcept { if (type == GL_BOOL) return GraphicsFormat::R8UInt; else if (type == GL_UNSIGNED_INT) return GraphicsFormat::R8UInt; else if (type == GL_INT) return GraphicsFormat::R8SInt; else if (type == GL_INT_VEC2) return GraphicsFormat::R8G8SInt; else if (type == GL_INT_VEC3) return GraphicsFormat::R8G8B8SInt; else if (type == GL_INT_VEC4) return GraphicsFormat::R8G8B8A8SInt; else if (type == GL_FLOAT) return GraphicsFormat::R32SFloat; else if (type == GL_FLOAT_VEC2) return GraphicsFormat::R32G32SFloat; else if (type == GL_FLOAT_VEC3) return GraphicsFormat::R32G32B32SFloat; else if (type == GL_FLOAT_VEC4) return GraphicsFormat::R32G32B32A32SFloat; else if (type == GL_FLOAT_MAT2) return GraphicsFormat::R32G32B32A32SFloat; else if (type == GL_FLOAT_MAT3) return GraphicsFormat::R32G32B32A32SFloat; else if (type == GL_FLOAT_MAT4) return GraphicsFormat::R32G32B32A32SFloat; else { GL_PLATFORM_ASSERT(false, "Invlid uniform type"); return GraphicsFormat::Undefined; } } GraphicsUniformType GL20Program::toGraphicsUniformType(const std::string& name, GLenum type) noexcept { if (type == GL_SAMPLER_2D || type == GL_SAMPLER_CUBE) { return GraphicsUniformType::SamplerImage; } else { bool isArray = name.find("[0]") != std::string::npos; if (type == GL_BOOL) { return GraphicsUniformType::Boolean; } else if (type == GL_INT) { if (isArray) return GraphicsUniformType::IntArray; else return GraphicsUniformType::Int; } else if (type == GL_INT_VEC2) { if (isArray) return GraphicsUniformType::Int2Array; else return GraphicsUniformType::Int2; } else if (type == GL_INT_VEC3) { if (isArray) return GraphicsUniformType::Int3Array; else return GraphicsUniformType::Int3; } else if (type == GL_INT_VEC4) { if (isArray) return GraphicsUniformType::Int4Array; else return GraphicsUniformType::Int4; } else if (type == GL_FLOAT) { if (isArray) return GraphicsUniformType::FloatArray; else return GraphicsUniformType::Float; } else if (type == GL_FLOAT_VEC2) { if (isArray) return GraphicsUniformType::Float2Array; else return GraphicsUniformType::Float2; } else if (type == GL_FLOAT_VEC3) { if (isArray) return GraphicsUniformType::Float3Array; else return GraphicsUniformType::Float3; } else if (type == GL_FLOAT_VEC4) { if (isArray) return GraphicsUniformType::Float4Array; else return GraphicsUniformType::Float4; } else if (type == GL_FLOAT_MAT2) { if (isArray) return GraphicsUniformType::Float2x2Array; else return GraphicsUniformType::Float2x2; } else if (type == GL_FLOAT_MAT3) { if (isArray) return GraphicsUniformType::Float3x3Array; else return GraphicsUniformType::Float3x3; } else if (type == GL_FLOAT_MAT4) { if (isArray) return GraphicsUniformType::Float4x4Array; else return GraphicsUniformType::Float4x4; } else { GL_PLATFORM_ASSERT(false, "Invlid uniform type"); return GraphicsUniformType::Null; } } } const GraphicsProgramDesc& GL20Program::getGraphicsProgramDesc() const noexcept { return _programDesc; } void GL20Program::setDevice(GraphicsDevicePtr device) noexcept { _device = device; } GraphicsDevicePtr GL20Program::getDevice() noexcept { return _device.lock(); } } }
[ "2221870259@qq.com" ]
2221870259@qq.com
dc9cfd3e7642599a9441b46429f547655a587cd2
c17ef4827869dbed4fd9e9af70ed77d620898b77
/codeChef/long/mar18/mineat.cpp
5dbd18872e54d38f17c4d9e1474bf24aa14e2a30
[]
no_license
Dsxv/competitveProgramming
c4fea2bac41ddc2b91c60507ddb39e8d9a3582e5
004bf0bb8783b29352035435283578a9db815cc5
refs/heads/master
2021-06-24T15:19:43.100584
2020-12-27T17:59:44
2020-12-27T17:59:44
193,387,301
0
0
null
null
null
null
UTF-8
C++
false
false
608
cpp
#include <bits/stdc++.h> using namespace std ; #define int long long int check(int x , int* a , int n){ int count = 0 ; for(int i = 0 ; i < n ; i++){ count += (a[i] + x - 1) / x ; } return count ; } int32_t main(){ int t ; cin >> t ; while(t--){ int n , h ; cin >> n >> h ; int a[n] ; for(int i = 0 ; i < n ; i++) cin >> a[i] ; int lo = 1 , hi = 1e9 ; int ans = -1 ; while(lo <= hi){ int mid = (lo + hi) / 2 ; if(check(mid,a,n) <= h) { ans = mid ; hi = mid - 1 ; } else { lo = mid + 1 ; } } assert(ans != -1) ; cout << ans << endl ; } return 0 ; }
[ "dsxv007@gmail.com" ]
dsxv007@gmail.com
ec2df38c46ead0865da949c37ddd279345957349
7ec2b70de7bfbada1df19be63ca93ca1dc66e29d
/source/mw-context.h
b674a1ac7ef5e86ff786a70b8792aaf070b2d0e2
[]
no_license
sb-baifeng-sb/model-worker
9d8ddcbc781186991baed83b9209645937d137f3
e18c6868fcceac168250146ba54d9dc10d19c538
refs/heads/master
2020-08-15T07:38:48.888976
2020-02-13T16:34:31
2020-02-13T16:34:31
215,302,155
2
1
null
null
null
null
UTF-8
C++
false
false
911
h
#ifndef __MW_CONTEXT_H__ #define __MW_CONTEXT_H__ #include <string> #include "mw-event.h" namespace mw { class ProxyHolder; class WorkerHolder; class HandlerHolder; class ProcHolder; class Context { public: Context(); virtual ~Context(); public: ProxyHolder& proxy() { return *this->mProxyHolder; } WorkerHolder& worker() { return *this->mWorkerHolder; } HandlerHolder& event() { return *this->mHandlerHolder; } ProcHolder& proc() { return *this->mProcHolder; } public: void notify(Event const& e); void notify(std::string const& name); template <typename T> void notify(std::string const& name, T const& value) { this->notify(DataEvent<T>(name, value)); } public: ProxyHolder* mProxyHolder; WorkerHolder* mWorkerHolder; HandlerHolder* mHandlerHolder; ProcHolder* mProcHolder; }; } #endif
[ "qq394811161@gmail.com" ]
qq394811161@gmail.com
d72256964b3a7b188c6f7dd4627a40aeafc7b47d
d8efaf8e35f7d203d50cb4f87bc7313187d9f6e1
/build/Android/Preview/MyFirstFuseProject/app/src/main/include/Uno.Net.Http.UriSchemeType.h
2dd7c3d2ec9f43449ba60bbfd3f2bccdda4984d6
[]
no_license
eddzmaciel/fproject_fp
fe33dc03b82047e88fad9e82959ee92d6da49025
2760ddb66c749651f163c3c1a3bc7b6820fbebae
refs/heads/master
2020-12-04T12:38:37.955298
2016-09-02T02:23:31
2016-09-02T02:23:31
67,182,558
0
0
null
null
null
null
UTF-8
C++
false
false
352
h
// This file was generated based on C:\ProgramData\Uno\Packages\Uno.Net.Http\0.33.1\$.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Int.h> namespace g{ namespace Uno{ namespace Net{ namespace Http{ // public enum UriSchemeType :1102 uEnumType* UriSchemeType_typeof(); }}}} // ::g::Uno::Net::Http
[ "Edson Maciel" ]
Edson Maciel
d57c39970a0b549cd193d93a526091532fc7e13a
6d427c7b04cb92cee6cc8d37df07cf8b129fdada
/12000 - 12999/12459.cpp
b6295e44204fe8b8bcd869767aabd17b417812bb
[]
no_license
FForhad/Online-Judge-Ex.-Uva-Solutions
3c5851d72614274cafac644bcdbc9e065fd5d8d8
b7fdf62d274a80333dec260f5a420f9d6efdbdaf
refs/heads/master
2023-03-20T23:47:30.116053
2021-03-10T02:07:49
2021-03-10T02:07:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
303
cpp
#include<bits/stdc++.h> using namespace std; long long int fibo[81]; void fib() { fibo[1]=1; fibo[2]=2; for(int i=3; i<=80; i++)fibo[i]=fibo[i-1]+fibo[i-2]; } int main() { fib(); int a; while(scanf("%d",&a)==1&&a!=0) { printf("%lld\n",fibo[a]); } return 0; }
[ "amitcse1995@gmail.com" ]
amitcse1995@gmail.com
c3024fcc94e0249f2adabba12ae20ede8880ccff
70fab0b00e2d0b0800f88e29cc42b41b8df09ee6
/bbp/src/uwsr/FEM/GraphNumberer.h
85bbaaaa509c753b263f440ddbd075e74d40e434
[ "Apache-2.0" ]
permissive
alborzgh/bbp
b51e57d93f2141407bcb0f1d092f3bed7b7fdf6a
bc0cce2378aa071a5537d25c1a738e58ef610561
refs/heads/master
2020-04-03T00:41:39.088013
2018-12-05T21:52:39
2018-12-05T21:52:39
154,905,925
0
1
Apache-2.0
2018-10-26T23:46:45
2018-10-26T23:46:45
null
UTF-8
C++
false
false
2,585
h
/* ****************************************************************** ** ** OpenSees - Open System for Earthquake Engineering Simulation ** ** Pacific Earthquake Engineering Research Center ** ** ** ** ** ** (C) Copyright 1999, The Regents of the University of California ** ** All Rights Reserved. ** ** ** ** Commercial use of this program without express permission of the ** ** University of California, Berkeley, is strictly prohibited. See ** ** file 'COPYRIGHT' in main directory for information on usage and ** ** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** ** ** ** Developed by: ** ** Frank McKenna (fmckenna@ce.berkeley.edu) ** ** Gregory L. Fenves (fenves@ce.berkeley.edu) ** ** Filip C. Filippou (filippou@ce.berkeley.edu) ** ** ** ** ****************************************************************** */ // $Revision: 1.1.1.1 $ // $Date: 2000-09-15 08:23:21 $ // $Source: /usr/local/cvs/OpenSees/SRC/graph/numberer/GraphNumberer.h,v $ // File: ~/graph/numberer/GraphNumberer.h // // Written: fmk // Created: 11/96 // Revision: A // // Description: This file contains the class definition for GraphNumberer. // GraphNumberer is an abstract base class. Its subtypes are responsible for // numbering the vertices of a graph. // // What: "@(#) GraphNumberer.h, revA" #ifndef GraphNumberer_h #define GraphNumberer_h #include <MovableObject.h> class ID; class Graph; class Channel; class ObjectBroker; class GraphNumberer : public MovableObject { public: GraphNumberer(int classTag); virtual ~GraphNumberer(); virtual const ID &number(Graph &theGraph, int lastVertex = -1) =0; virtual const ID &number(Graph &theGraph, const ID &lastVertices) =0; protected: private: }; #endif
[ "alborzgh@uw.edu" ]
alborzgh@uw.edu
8f71f10f687819cebf00cbd9a314e2cea5689b8b
34313ea01cc8b5f330bf3e049a142c71eccfdccc
/offer_T55_1.cpp
783601fc876169461a30346f693e1df4fe6d714a
[]
no_license
fhsmartking/Leetcode
f0467bd2a53bafb30f253d85bb0a8704606bb8c9
9442cf4bded175ab2e4ce7a3ab8259be31d53403
refs/heads/master
2023-03-22T12:55:48.344166
2020-08-12T10:11:42
2020-08-12T10:11:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
702
cpp
#include<iostream> #include<vector> #include<algorithm> using namespace std; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: int dfs(TreeNode* root) { if (root->left == nullptr && root->right == nullptr) return 1; int leftDeep = 0, rightDeep = 0; if (root->left) leftDeep = dfs(root->left); if (root->right) rightDeep = dfs(root->right); return max(leftDeep, rightDeep) + 1; } int maxDepth(TreeNode* root) { if (root == nullptr) return 0; int ans = dfs(root); return ans; } };
[ "noreply@github.com" ]
noreply@github.com
3fedc60a1c6b4356fd11d0d56b66e321e5948295
b133b88c88dda779abbe3f680405a864c0e35474
/QtLing/graphics.h
be685bb18d90f0f235612d2ee6095ea7a993c692
[]
no_license
cdwijs/QtLing
93bd25f2663faf955a80440894b2eff28cf6b3c4
a5e601a2d9bce7d0d8e35981035f70cdbaa1b1a0
refs/heads/master
2021-09-02T09:12:51.781768
2018-01-01T01:00:00
2018-01-01T01:00:00
115,908,690
0
0
null
2018-01-01T08:52:22
2018-01-01T08:52:22
null
UTF-8
C++
false
false
6,945
h
#ifndef GRAPHICS_H #define GRAPHICS_H #include<QGraphicsItem> #include <QGraphicsView> #include <QMouseEvent> #include <QGraphicsScene> #include <QPoint> #include <QColor> #include "supersignature.h" #include <QGraphicsItem> class CSignature; class CSignatureCollection; class MainWindow; class lxa_graphics_scene; class CSupersignature; void triangle(CSignature* pSig, int x, int y, int row_delta, lxa_graphics_scene * scene, int count, QColor color); void square(CSignature* pSig, int x, int y, int row_delta, lxa_graphics_scene * scene, int count); void pentagon(CSignature* pSig, int x, int y, int row_delta, lxa_graphics_scene * scene, int count); void hexagon(CSignature* pSig, int x, int y, int row_delta, lxa_graphics_scene * scene, int count); void septagon(CSignature* pSig, int x, int y, int row_delta, lxa_graphics_scene * scene, int count); void octagon(CSignature* pSig, int x, int y, int row_delta, lxa_graphics_scene * scene, int count); void nonagon(CSignature* pSig, int x, int y, int row_delta, lxa_graphics_scene * scene, int count); void decagon(CSignature* pSig, int x, int y, int row_delta, lxa_graphics_scene * scene, int count); void elevenagon(CSignature* pSig, int x, int y, int row_delta, lxa_graphics_scene * scene, int count); void twelvagon(CSignature* pSig, int x, int y, int row_delta, lxa_graphics_scene * scene, int count); ///////////////////////////////////////////////////////////////////////////// // Graphic signature // ///////////////////////////////////////////////////////////////////////////// class graphic_signature : public QGraphicsRectItem // QGraphicsEllipseItem { lxa_graphics_scene * m_graphics_scene; CSignature * m_signature; Qt::GlobalColor m_color; bool m_is_focused; public: graphic_signature (int x, int y, CSignature*, lxa_graphics_scene* scene, int radius, int row_delta, QColor, bool focus_flag = false); void mousePressEvent (QGraphicsSceneMouseEvent*); void set_color(Qt::GlobalColor this_color) { m_color = this_color;} CSignature* get_signature() {return m_signature;} void mark_as_focus(); }; class graphic_super_signature : public QRect { lxa_graphics_scene * m_graphics_scene; CSupersignature * m_super_signature; Qt::GlobalColor m_color; public: graphic_super_signature(int x, int y, CSupersignature*, lxa_graphics_scene* scene); void mousePressEvent (QGraphicsSceneMouseEvent*); void set_color(Qt::GlobalColor this_color) { m_color = this_color;} CSupersignature* get_super_signature() {return m_super_signature;} }; ///////////////////////////////////////////////////////////////////////////// // // lxa graphics view // ///////////////////////////////////////////////////////////////////////////// class lxa_graphics_view : public QGraphicsView { friend:: lxa_graphics_scene; QList<QList<CSignature*>*> m_signature_lattice; MainWindow * m_main_window; lxa_graphics_scene* m_graphics_scene; double m_scale; void mousePressEvent(QMouseEvent*); public: lxa_graphics_view( MainWindow * ); void expand() {scale(1.25,1.25);} void contract() {scale(0.8,0.8);} void move_up() ; void move_down() {translate(0,-50);} void move_left() {translate(-50,0);} void move_right() {translate(50,0);} lxa_graphics_scene* get_graphics_scene() {return m_graphics_scene;} void set_graphics_scene( lxa_graphics_scene* pScene ) {m_graphics_scene = pScene;} }; ///////////////////////////////////////////////////////////////////////////// // // lxa graphics scene // ///////////////////////////////////////////////////////////////////////////// class lxa_graphics_scene : public QGraphicsScene { friend graphic_signature; MainWindow* m_main_window; eDisplayType m_display_type; lxa_graphics_view* m_graphics_view; QList<QList<CSignature*>*> m_signature_lattice; QList<QPair<CSignature*,CSignature*>*> m_signature_containment_edges; QMap<CSignature*, int> m_map_from_sig_to_column_no; graphic_signature * m_top_graphic_signature; CSignature* m_focus_signature_1; CSignature* m_focus_signature_2; CSignatureCollection * m_signature_collection; Qt::GlobalColor m_normal_color; Qt::GlobalColor m_focus_color; int m_row_delta; int m_column_delta; int m_location_of_bottom_row; int m_signature_radius; private: void mousePressEvent(QGraphicsSceneMouseEvent* mouseEvent); public: // lxa_graphics_scene( MainWindow * , CSignatureCollection*, eDisplayType this_display_type ); ~lxa_graphics_scene(); lxa_graphics_scene(MainWindow *); void clear_all(); void clear(); void set_graphics_view (lxa_graphics_view* ); // void set_parameters (CSignatureCollection*, eDisplayType); void assign_scene_positions_to_signatures(CSignatureCollection*, eDisplayType ); void add_signature_containment_edge (QPair<CSignature*, CSignature*>* pPair) {m_signature_containment_edges.append (pPair); } void place_signatures(); void place_containment_edges(); void widen_columns(); void narrow_columns(); void move_rows_apart(); void move_rows_closer(); void mouseMoveEvent(QGraphicsSceneMouseEvent * event); void set_focus_signature(); void set_focus_signature_1(CSignature* pSig) {m_focus_signature_1 = pSig;} void set_focus_signature_2(CSignature* pSig) {m_focus_signature_2 = pSig;} graphic_signature* get_focus_signature_1(); void display_focus_signature(); }; class signature_node : public QGraphicsItem { public: QRectF boundingRect() const; void paint (QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget){ painter->drawEllipse(100,100,10,10); } }; #endif // GRAPHICS_H
[ "goldsmith@uchicago.edu" ]
goldsmith@uchicago.edu
1027a7a93f31f027693771ebb3d4e336c877f63e
8c003e9106f2bf8c9d9b0fbf96fd9102fc2857a7
/src/ui/a11y/lib/gesture_manager/recognizers/tests/one_finger_drag_recognizer_test.cc
f3c0ea1ba9e77b4634566a3f63244e8f94a9f6eb
[ "BSD-3-Clause" ]
permissive
Autumin/fuchsia
53df56e33e4ad76a04d76d2efe21c9db95e9fcc9
9bad38cdada4705e88c5ae19d4557dfc0cd912ef
refs/heads/master
2022-04-23T18:13:33.728043
2020-04-21T14:43:53
2020-04-21T14:43:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,251
cc
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/ui/a11y/lib/gesture_manager/recognizers/one_finger_drag_recognizer.h" #include <fuchsia/ui/input/accessibility/cpp/fidl.h> #include <memory> #include "gtest/gtest.h" #include "src/lib/testing/loop_fixture/test_loop_fixture.h" #include "src/ui/a11y/lib/gesture_manager/arena/tests/mocks/mock_contest_member.h" #include "src/ui/a11y/lib/gesture_manager/gesture_util/util.h" #include "src/ui/a11y/lib/testing/input.h" #include "src/ui/lib/glm_workaround/glm_workaround.h" namespace accessibility_test { using AccessibilityPointerEvent = fuchsia::ui::input::accessibility::PointerEvent; using Phase = fuchsia::ui::input::PointerEventPhase; class OneFingerDragRecognizerTest : public gtest::TestLoopFixture { public: OneFingerDragRecognizerTest() : recognizer_( [this](a11y::GestureContext context) { gesture_start_callback_called_ = true; }, [this](a11y::GestureContext context) { gesture_updates_.push_back(context); }, [this](a11y::GestureContext context) { gesture_complete_callback_called_ = true; }, a11y::OneFingerDragRecognizer::kDefaultMinDragDuration) {} void SendPointerEvents(const std::vector<PointerParams>& events) { for (const auto& event : events) { SendPointerEvent(event); } } void SendPointerEvent(const PointerParams& event) { if (member_.is_held()) { recognizer_.HandleEvent(ToPointerEvent(event, 0)); } } protected: MockContestMember member_; a11y::OneFingerDragRecognizer recognizer_; std::vector<a11y::GestureContext> gesture_updates_; bool gesture_start_callback_called_ = false; bool gesture_complete_callback_called_ = false; }; // Tests successful drag detection case. TEST_F(OneFingerDragRecognizerTest, WonAfterGestureDetected) { recognizer_.OnContestStarted(member_.TakeInterface()); glm::vec2 first_update_ndc_position = {0, .7f}; auto first_update_local_coordinates = ToLocalCoordinates(first_update_ndc_position); SendPointerEvents(DownEvents(1, {}) + MoveEvents(1, {}, first_update_ndc_position)); EXPECT_EQ(member_.status(), a11y::ContestMember::Status::kUndecided); EXPECT_TRUE(gesture_updates_.empty()); // Wait for the drag delay to elapse, at which point the recognizer should claim the win and // invoke the update callback. RunLoopFor(a11y::OneFingerDragRecognizer::kDefaultMinDragDuration); ASSERT_EQ(member_.status(), a11y::ContestMember::Status::kAccepted); recognizer_.OnWin(); EXPECT_TRUE(gesture_start_callback_called_); EXPECT_FALSE(gesture_complete_callback_called_); // We should see an update at location of the last event ingested prior to the delay elapsing. EXPECT_EQ(gesture_updates_.size(), 1u); EXPECT_EQ(gesture_updates_[0].local_point->x, first_update_local_coordinates.x); EXPECT_EQ(gesture_updates_[0].local_point->y, first_update_local_coordinates.y); SendPointerEvents(MoveEvents(1, {0, .7f}, {0, .85f}) + UpEvents(1, {0, .85f})); EXPECT_FALSE(member_.is_held()); EXPECT_TRUE(gesture_complete_callback_called_); // Since MoveEvents() generates 10 evenly-spaced pointer events between the starting point (0, .7) // and ending point (0, .85), the recognizer will receive a series of MOVE events at (0, .715), // (0, .73), ..., (0, .85). The first for which the distance covered since the initial update, // which occurred at (0, .7), will be the event at (0, .775). We therefore expect an update to // occur at this point. We would expect an additional update when the distance between the pointer // and (0, .775) exceeds .0625, which will occur at (0, .85). auto second_update_local_coordinates = ToLocalCoordinates({0, .775f}); auto third_update_local_coordinates = ToLocalCoordinates({0, .85f}); EXPECT_EQ(gesture_updates_.size(), 3u); EXPECT_EQ(gesture_updates_[1].local_point->x, second_update_local_coordinates.x); EXPECT_EQ(gesture_updates_[1].local_point->y, second_update_local_coordinates.y); EXPECT_EQ(gesture_updates_[2].local_point->x, third_update_local_coordinates.x); EXPECT_EQ(gesture_updates_[2].local_point->y, third_update_local_coordinates.y); } // Verifies that recognizer suppresses updates while multiple pointers are down. TEST_F(OneFingerDragRecognizerTest, SuppressMultitouch) { recognizer_.OnContestStarted(member_.TakeInterface()); SendPointerEvents(DownEvents(1, {}) + MoveEvents(1, {}, {0, .7f})); // Wait for the drag delay to elapse, at which point the recognizer should claim the win and // invoke the update callback. RunLoopFor(a11y::OneFingerDragRecognizer::kDefaultMinDragDuration); ASSERT_EQ(member_.status(), a11y::ContestMember::Status::kAccepted); recognizer_.OnWin(); EXPECT_TRUE(gesture_start_callback_called_); SendPointerEvents(DownEvents(2, {}) + MoveEvents(1, {0, .7f}, {0, .85f})); EXPECT_EQ(gesture_updates_.size(), 1u); SendPointerEvents(UpEvents(2, {})); SendPointerEvent({1, Phase::MOVE, {0, .95f}}); // Resume after the extra pointer is released. Note that the continuing pointer must be the // original at present. EXPECT_EQ(gesture_updates_.size(), 2u); SendPointerEvents(UpEvents(1, {0, .95f})); EXPECT_FALSE(member_.is_held()); EXPECT_TRUE(gesture_complete_callback_called_); } // Tests that distance threshold between updates is enforced after first update. TEST_F(OneFingerDragRecognizerTest, MinimumDistanceRequirementForUpdatesEnforced) { recognizer_.OnContestStarted(member_.TakeInterface()); SendPointerEvents(DownEvents(1, {}) + MoveEvents(1, {}, {0, .7f})); // Wait for the drag delay to elapse, at which point the recognizer should claim the win and // invoke the update callback. RunLoopFor(a11y::OneFingerDragRecognizer::kDefaultMinDragDuration); ASSERT_EQ(member_.status(), a11y::ContestMember::Status::kAccepted); recognizer_.OnWin(); // Move pointer to location that does NOT meet the minimum threshold update. SendPointerEvents(MoveEvents(1, {0, .7f}, {0, .75f}) + UpEvents(1, {0, .75f})); EXPECT_FALSE(member_.is_held()); EXPECT_TRUE(gesture_complete_callback_called_); // The update callback should only be invoked again if the pointer moves a sufficient distance // from the previous update. Since the pointer only moves .05f in this case, and the threshold // for an update is 1.f/16, no updates beyond the initial should have occurred. EXPECT_EQ(gesture_updates_.size(), 1u); } // Verifies that recognizer does not accept gesture before delay period elapses. TEST_F(OneFingerDragRecognizerTest, DoNotAcceptPriorToDelayElapsing) { recognizer_.OnContestStarted(member_.TakeInterface()); SendPointerEvents(DragEvents(1, {}, {0, .7f})); EXPECT_EQ(member_.status(), a11y::ContestMember::Status::kRejected); // Wait for the drag delay to elapse to ensure that task scheduled to claim win was cancelled. // The task calls Accept(), and then invokes the drag update callback. Therefore, if it was // cancelled successfully, we would not expect either method to have been called. The mock member_ // has an assertion that if it was rejected, it may not have Accept() called on it. RunLoopFor(a11y::OneFingerDragRecognizer::kDefaultMinDragDuration); EXPECT_TRUE(gesture_updates_.empty()); EXPECT_FALSE(gesture_complete_callback_called_); } // Tests that recognizer abandons gesture if it is defeated. TEST_F(OneFingerDragRecognizerTest, Defeat) { recognizer_.OnContestStarted(member_.TakeInterface()); SendPointerEvents(DownEvents(1, {}) + MoveEvents(1, {}, {0, .7f})); // Wait for the drag delay to elapse, at which point the recognizer should attempt to claim the // win. RunLoopFor(a11y::OneFingerDragRecognizer::kDefaultMinDragDuration); ASSERT_EQ(member_.status(), a11y::ContestMember::Status::kAccepted); // When it loses, the recognizer should NOT call the update task, and should instead abandon the // gesture. recognizer_.OnDefeat(); EXPECT_FALSE(gesture_start_callback_called_); EXPECT_TRUE(gesture_updates_.empty()); EXPECT_FALSE(gesture_complete_callback_called_); } } // namespace accessibility_test
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
2590dbcdd0677bde1f1f5c913ce0e4ca0598a3c2
69e7f4b3c51c6a4fa47d63c79bf1147b20663574
/第八周课堂上实验一/第八周课堂上实验一/第八周课堂上实验一Doc.h
1d18c277c8c99038ecf0b52bf6659bcba55d7136
[]
no_license
learnernews/-1
394204590a42e56e8891994588881fed2a427c7d
d9e5cb21921d7b007e67b268c46f013f8a9f2e34
refs/heads/master
2022-11-17T22:45:18.928786
2020-07-03T15:19:29
2020-07-03T15:19:29
268,680,889
0
0
null
null
null
null
GB18030
C++
false
false
971
h
// 第八周课堂上实验一Doc.h : C第八周课堂上实验一Doc 类的接口 // #pragma once class C第八周课堂上实验一Doc : public CDocument { protected: // 仅从序列化创建 C第八周课堂上实验一Doc(); DECLARE_DYNCREATE(C第八周课堂上实验一Doc) // 特性 public: // 操作 public: // 重写 public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); #ifdef SHARED_HANDLERS virtual void InitializeSearchContent(); virtual void OnDrawThumbnail(CDC& dc, LPRECT lprcBounds); #endif // SHARED_HANDLERS // 实现 public: virtual ~C第八周课堂上实验一Doc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 生成的消息映射函数 protected: DECLARE_MESSAGE_MAP() #ifdef SHARED_HANDLERS // 用于为搜索处理程序设置搜索内容的 Helper 函数 void SetSearchContent(const CString& value); #endif // SHARED_HANDLERS };
[ "1583817286@qq.com" ]
1583817286@qq.com
e247a845571b20198c5d0ccaec9d3affb0063fe0
808c52b14ffa0ad6986b2ad3b54f2a52b828b161
/CGALUtilities.h
b8431c6c55a32a61506ad6057231c15bf44535f4
[]
no_license
plisdku/mergeSTP
95539bc09260154a21ef403f098bacf8a3b115d1
abb45eee92234ff432d8682b8b367ba1ed9f7fb0
refs/heads/master
2020-05-16T20:26:29.364356
2016-04-08T16:50:29
2016-04-08T16:50:29
17,258,407
1
0
null
null
null
null
UTF-8
C++
false
false
594
h
/* * CGALUtilities.h * Snapdragon * * Created by Paul Hansen on 3/9/10. * Copyright 2010 Stanford University. All rights reserved. * */ #ifndef _CGALUTILITIES_ #define _CGALUTILITIES_ #include <CGAL/number_utils.h> #include "utility/VectorMatrix.h" #include "utility/VectorMatrix2.h" template<class CGALPoint_3> CGALPoint_3 toCGAL(const Vector3d & v) { return CGALPoint_3(v[0], v[1], v[2]); } template<class CGALPoint_3> Vector3d toVector3d(const CGALPoint_3 & p) { return Vector3d(CGAL::to_double(p[0]), CGAL::to_double(p[1]), CGAL::to_double(p[2])); } #endif
[ "pch@stanford.edu" ]
pch@stanford.edu
c62fe2247105b117e8921997489c10794ecbd94c
6acfb82696512fa7203a68cca867fc11b19273fa
/HW3/distance.h
2d84707c63171212107fa37e2e2c0f7628026068
[]
no_license
dangalang/COP3330
8eed0f601efc455d27885a898f1f7e2872b4d5b6
f6314fab5cc703c7e063125968b9c05fb324392e
refs/heads/master
2022-04-15T23:32:33.672727
2020-04-10T22:10:22
2020-04-10T22:10:22
235,830,969
0
0
null
null
null
null
UTF-8
C++
false
false
1,373
h
/* Name: Forrest Lang * Date: 10 FEB 2020 * Section: 0005 * Assignment: Homework 3 */ using namespace std; class Distance { friend ostream& operator<<(ostream& s, const Distance& d); friend istream& operator>>(istream& s, Distance& d); friend Distance operator+(const Distance& d1, const Distance& d2); friend Distance operator-(const Distance& d1, const Distance& d2); friend Distance operator*(const Distance& d1, int mult); friend bool operator<(const Distance& d1, const Distance& d2); friend bool operator>(const Distance& d1, const Distance& d2); friend bool operator<=(const Distance& d1, const Distance& d2); friend bool operator>=(const Distance& d1, const Distance& d2); friend bool operator==(const Distance& d1, const Distance& d2); friend bool operator!=(const Distance& d1, const Distance& d2); public: Distance(); Distance(int in); Distance(int mi, int yd, int ft, int in); Distance& operator++(); Distance operator++(int); Distance& operator--(); Distance operator--(int); private: int GetMiles() const; int GetYards() const; int GetFeet() const; int GetInches() const; void simplify(Distance& d1); int miles, yards, feet, inches; static const int INCHES_PER_FOOT; static const int FEET_PER_YARD; static const int YARDS_PER_MILE; };
[ "c18lang@gmail.com" ]
c18lang@gmail.com
dfe5c562615010c0ab61eb4e47fb3f71c3462918
fdaa9b0627b4bbbb3d9cb50c5336fb3d2760023e
/src/test/reverselock_tests.cpp
2dc161196118c5298f49f45c3cfe19313963abed
[ "MIT" ]
permissive
coppercurrency/copper
ff7f8583f467a4a3c3ed87ffb4179f5be276c5a8
a5e9d15ef68231bc28ce0a394b1e967a6cf0b1dd
refs/heads/master
2020-04-15T21:11:34.735457
2019-01-10T16:06:03
2019-01-10T16:06:03
165,024,201
0
1
null
null
null
null
UTF-8
C++
false
false
1,625
cpp
// Copyright (c) 2015-2016 The Bitcoin Core developers // Copyright (c) 2017 The Copper Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "reverselock.h" #include "test/test_copper.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(reverselock_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(reverselock_basics) { boost::mutex mutex; boost::unique_lock<boost::mutex> lock(mutex); BOOST_CHECK(lock.owns_lock()); { reverse_lock<boost::unique_lock<boost::mutex> > rlock(lock); BOOST_CHECK(!lock.owns_lock()); } BOOST_CHECK(lock.owns_lock()); } BOOST_AUTO_TEST_CASE(reverselock_errors) { boost::mutex mutex; boost::unique_lock<boost::mutex> lock(mutex); // Make sure trying to reverse lock an unlocked lock fails lock.unlock(); BOOST_CHECK(!lock.owns_lock()); bool failed = false; try { reverse_lock<boost::unique_lock<boost::mutex> > rlock(lock); } catch(...) { failed = true; } BOOST_CHECK(failed); BOOST_CHECK(!lock.owns_lock()); // Locking the original lock after it has been taken by a reverse lock // makes no sense. Ensure that the original lock no longer owns the lock // after giving it to a reverse one. lock.lock(); BOOST_CHECK(lock.owns_lock()); { reverse_lock<boost::unique_lock<boost::mutex> > rlock(lock); BOOST_CHECK(!lock.owns_lock()); } BOOST_CHECK(failed); BOOST_CHECK(lock.owns_lock()); } BOOST_AUTO_TEST_SUITE_END()
[ "root@vps626905.ovh.net" ]
root@vps626905.ovh.net
154c384f131b3d8c51135d6f029c07d88aa7b674
b74dea911cf644ab1b6a6c8c448708ee09e6581f
/SDK/lib/device/ak8975.h
08019b9b2e798304ad8696662901ac10d564d441
[ "Unlicense" ]
permissive
ghsecuritylab/CppSDK
bbde19f9d85975dd12c366bba4874e96cd614202
50da768a887241d4e670b3ef73c041b21645620e
refs/heads/master
2021-02-28T14:02:58.205901
2018-08-23T15:08:15
2018-08-23T15:08:15
245,703,236
0
0
NOASSERTION
2020-03-07T20:47:45
2020-03-07T20:47:44
null
UTF-8
C++
false
false
2,794
h
/* * device/ak8975.h */ /*#####################################################*/ #ifndef AK8975_H_ #define AK8975_H_ /*#####################################################*/ #include <stdbool.h> #include "api/i2c.h" #include <include/global.h> /*#####################################################*/ #define AK8975_ADDR (0x0C) /* * Read-only registers */ #define AK8975_WIA_REG (0x00) #define AK8975_INFO_REG (0x01) #define AK8975_ST1_REG (0x02) #define AK8975_HXL_REG (0x03) #define AK8975_HXH_REG (0x04) #define AK8975_HYL_REG (0x05) #define AK8975_HYH_REG (0x06) #define AK8975_HZL_REG (0x07) #define AK8975_HZH_REG (0x08) #define AK8975_ST2_REG (0x09) /* * Write/Read registers */ #define AK8975_CNTL_REG (0x0A) #define AK8975_RSV_REG (0x0B) #define AK8975_ASTC_REG (0x0C) #define AK8975_TS1_REG (0x0D) #define AK8975_TS2_REG (0x0E) #define AK8975_I2CDIS_REG (0x0F) /* * Read-only registers */ #define AK8975_ASAX_REG (0x10) #define AK8975_ASAY_REG (0x11) #define AK8975_ASAZ_REG (0x12) /* * ST1 reg */ #define AK8975_ST1_DREADY_bp 0 #define AK8975_ST1_DREADY_bm (0x01 << AK8975_ST1_DREADY_bp) /* * ST2 reg */ #define AK8975_ST2_HOLF_bp 3 /* Magnetic sensor overflow */ #define AK8975_ST2_HOLF_bm (0x01 << AK8975_ST2_HOLF_bp) #define AK8975_ST2_DERR_bp 3 /* Data error occured */ #define AK8975_ST2_DERR_bm (0x01 << AK8975_ST2_DERR_bp) /* * CTRL reg */ #define AK8975_CTRL_MODE_gp 0 /* Data error occured */ #define AK8975_CTRL_MODE_gm (0x0F << AK8975_CTRL_MODE_gp) #define AK8975_CTRL_MODE_PWRDN (0x00) #define AK8975_CTRL_MODE_SINGLE (0x01) #define AK8975_CTRL_MODE_SELFTEST (0x08) #define AK8975_CTRL_MODE_ROM (0x0F) /* * ASTC reg */ #define AK8975_ASTC_SELF_bp 6 /* Data error occured */ #define AK8975_ASTC_SELF_bm (0x01 << AK8975_ASTC_SELF_bp) /* * I2CDIS reg */ #define AK8975_I2CDIS_bp 0 /* Data error occured */ #define AK8975_I2CDIS_bm (0x01 << AK8975_I2CDIS_bp) /*#####################################################*/ namespace GI { namespace Sensor { class Ak8975 { public: Ak8975(char *i2cPath, unsigned char icNr); ~Ak8975(); SysErr startMeasure(); SysErr checkReady(); SysErr getMag(signed short *X_Axis, signed short *Y_Axis, signed short *Z_Axis); //SysErr displayResult(); bool busy; GI::Dev::I2c* I2C; unsigned char Stage; private: SysErr getData(signed short *X_Axis, signed short *Y_Axis, signed short *Z_Axis); unsigned char IcNr; }; } } typedef struct AK8975_s{ //STimer_t Timeout_Timer; }AK8975_t; /*#####################################################*/ #ifdef USE_VISUAL_STUDIO #include "ak8975.cpp" #endif /*#####################################################*/ #endif /*#####################################################*/
[ "morgoth.creator@gmail.com" ]
morgoth.creator@gmail.com
4e5204442086014720c65f630c0ad44ae31fa8fb
e9710a309b76a307874d60f5dc616d53383d4001
/version2/demoClient/benchmark_client.cpp
2d6a8b97850540d7acba9e3887181cdb2aaf7114
[]
no_license
appleoct/CET_Dic
a3c4975d795b86e738caa952a4f30c95179a9e39
7f562fcd778362b73c7f8d9ca0431c25ca1e6542
refs/heads/master
2020-05-28T08:35:45.336143
2017-10-03T04:53:51
2017-10-03T04:53:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
319
cpp
/* * > File Name: client.cpp * > Author: Jack Kang * > Mail: kangyijie@xiyoulinux.org * > Created Time: 2017年07月18日 星期二 16时13分53秒 */ #include <iostream> #include "client.h" int main(void) { fork(); fork(); Client cli("192.168.30.132",5473); cli.Connect(); cli.benchmark(); }
[ "xiyoulinux.kangyijie@gmail.com" ]
xiyoulinux.kangyijie@gmail.com
331be3e8be51b842b54018c6629831c1d63da203
3f25d1a06573f72afde1c0bc51ddf9504735503a
/number.cpp
3558592dc3c06603bc6f9db826a6b6ecbcad690f
[]
no_license
wakaba-c/Little-Red-Hood
f9a7a87705142b9758d06bbe0bddbbdb314170f7
d30aa7a4fac4a8d9511fe56eeb26aa452a789a01
refs/heads/master
2022-04-19T09:26:02.775559
2020-04-22T04:26:24
2020-04-22T04:26:24
257,787,935
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
5,645
cpp
//============================================================================= // // 数字処理 [number.cpp] // Author : masayasu wakita // //============================================================================= #include "number.h" #include "manager.h" #include "renderer.h" //============================================================================= // コンストラクタ //============================================================================= CNumber::CNumber(CScene::PRIORITY obj = CScene::PRIORITY_UI) : CScene2D(obj) { //値の初期化 m_nNumOld = 0; } //============================================================================= // デストラクタ //============================================================================= CNumber::~CNumber() { } //============================================================================= // 初期化処理 //============================================================================= HRESULT CNumber::Init(void) { // 頂点情報の作成 MakeVertex(); return S_OK; } //============================================================================= // 開放処理 //============================================================================= void CNumber::Uninit(void) { //頂点バッファの開放 if (m_pVtxBuff != NULL) {// 頂点バッファが存在していたとき m_pVtxBuff->Release(); m_pVtxBuff = NULL; } } //============================================================================= // 更新処理 //============================================================================= void CNumber::Update(void) { } //============================================================================= // 描画処理 //============================================================================= void CNumber::Draw(void) { LPDIRECT3DDEVICE9 pDevice; CRenderer *pRenderer = CManager::GetRenderer(); //デバイスを取得する pDevice = pRenderer->GetDevice(); //頂点バッファをデバイスのデータにバインド pDevice->SetStreamSource(0, m_pVtxBuff, 0, sizeof(VERTEX_2D)); //テクスチャの設定 pDevice->SetFVF(FVF_VERTEX_2D); //頂点フォーマットの設定 pDevice->SetTexture(0, CManager::GetResource("data/tex/number001.png")); //ポリゴンの描画 pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2); } //============================================================================= // クリエイト処理 //============================================================================= CNumber *CNumber::Create(void) { CNumber *pNumber; pNumber = new CNumber(PRIORITY_UI); if (pNumber != NULL) {// 数字が存在していたとき pNumber->Init(); // 初期化処理 } return pNumber; } //============================================================================= // ロード処理 //============================================================================= HRESULT CNumber::Load(void) { // テクスチャの取得 CManager::Load("data/tex/number001.png"); return S_OK; } //============================================================================= // 数字の設定 //============================================================================= void CNumber::SetNumber(int nNum) { VERTEX_2D *pVtx; //前回の数字と今回の数字が違う場合 if (m_nNumOld != nNum) { // 頂点データの範囲をロックし、頂点バッファへのポインタを取得 m_pVtxBuff->Lock(0, 0, (void**)&pVtx, 0); m_nNumOld = nNum; //テクスチャ描写の位置 pVtx[0].tex = D3DXVECTOR2(nNum * 0.1f, 0.0f); pVtx[1].tex = D3DXVECTOR2(nNum * 0.1f + 0.1f, 0.0f); pVtx[2].tex = D3DXVECTOR2(nNum * 0.1f, 1.0f); pVtx[3].tex = D3DXVECTOR2(nNum * 0.1f + 0.1f, 1.0f); // 頂点データをアンロックする m_pVtxBuff->Unlock(); } } //============================================================================= // 頂点の作成 //============================================================================= void CNumber::MakeVertex(void) { LPDIRECT3DDEVICE9 pDevice; CRenderer *pRenderer = CManager::GetRenderer(); D3DXVECTOR3 pos = GetPosition(); // 位置の取得 D3DXVECTOR3 size = GetSize(); // サイズの取得 pDevice = pRenderer->GetDevice(); VERTEX_2D *pVtx; // オブジェクトの頂点バッファを生成 pDevice->CreateVertexBuffer(sizeof(VERTEX_2D) * 4, D3DUSAGE_WRITEONLY, FVF_VERTEX_2D, D3DPOOL_MANAGED, &m_pVtxBuff, NULL); // 頂点データの範囲をロックし、頂点バッファへのポインタを取得 m_pVtxBuff->Lock(0, 0, (void**)&pVtx, 0); // 頂点情報の設定 //頂点座標の設定(基準のx座標 + 間隔 * nCntScore (+ 幅), 基準のy座標) pVtx[0].pos = D3DXVECTOR3(pos.x - size.x / 2, pos.y - size.y / 2, pos.z); pVtx[1].pos = D3DXVECTOR3(pos.x + size.x / 2, pos.y - size.y / 2, pos.z); pVtx[2].pos = D3DXVECTOR3(pos.x - size.x / 2, pos.y + size.y / 2, pos.z); pVtx[3].pos = D3DXVECTOR3(pos.x + size.x / 2, pos.y + size.y / 2, pos.z); //1.0で固定 pVtx[0].rhw = 1.0f; pVtx[1].rhw = 1.0f; pVtx[2].rhw = 1.0f; pVtx[3].rhw = 1.0f; //カラーチャートの設定 pVtx[0].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); pVtx[1].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); pVtx[2].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); pVtx[3].col = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); //テクスチャ描写の位置 pVtx[0].tex = D3DXVECTOR2(0.0f, 0.0f); pVtx[1].tex = D3DXVECTOR2(0.1f, 0.0f); pVtx[2].tex = D3DXVECTOR2(0.0f, 1.0f); pVtx[3].tex = D3DXVECTOR2(0.1f, 1.0f); // 頂点データをアンロックする m_pVtxBuff->Unlock(); }
[ "koamchi.w315@gmail.com" ]
koamchi.w315@gmail.com
eeb89a94a93008f8287f7e00a3daa261cd912ac2
947de94ef998bfebb8e9c7da5e3a60c1080e0da8
/CardGame/CARD.h
7a839f1763ea0509cc4143459572152bfa418a5b
[]
no_license
neversettle123/doudizhu
43d1a976de26a0d9270037c761395f1d4c13c0d5
5537875f30dc2888828c3c716aba8ff2fec86e1c
refs/heads/master
2020-03-28T22:58:14.731962
2018-09-18T10:13:06
2018-09-18T10:13:06
149,268,429
0
0
null
null
null
null
GB18030
C++
false
false
2,900
h
#pragma once #include<windows.h> #include<time.h> #include<algorithm> #include<vector> #include<mmsystem.h> #include <Digitalv.h> #include"resource.h" #pragma comment(lib,"winmm.lib") using namespace std; #define CARD_SIZE 54 #define BLACKJOKER_VALUE 99 #define REDJOKER_VALUE 100 #define BUTTON1 200 #define BUTTON2 201 #define CHOOSE_BTN 202 #define CHOOSE_BTN2 203 #define STATIC_TEXT 204 #define CARD_WIDTH 105 #define CARD_HEIGTH 150 enum CardColor { REDHEART = 1, SPADE, BLOSSOM, DIAMOND, BLACKJOKER, REDJOKER }; enum CardNum { SINGLE_CARD = 10, //单张 THREE_CARD, //三个不带 FOUR_CARD, //三带一 THREE_DOUBLE, //三带二 BOMB_CARD, //炸弹 JOCKER_BOMB, //王炸 DOUBLE_CARD, //一对 THREE_COUPLE, //三连对 FOUR_COUPLE, //四连对 FIVE_COUPLE, //五连对 SIX_COUPLE, //六连对 SEVEN_COUPLE, //七连对 EIGHT_COUPLE, //八连对 NINE_COUPLE, //九连对 TEN_COUPLE, //十连对 PLANE_CARD, //飞机不带 PLANE_SINGLE, //飞机带两个 PLANE_DOUBLE, //飞机带一对 PLANE_THREE_NONE, //三飞机不带 PLANE_THREE_SINGLE, //三飞机带三个 PLANE_THREE_DOUBLE, //三飞机带三对 PLANE_FOUR_SINGLE, //四飞机带四个 PLANE_FOUR_DOUBLE, //四飞机带四对 STRAIGHT_FIVE, //五顺子 STRAIGHT_SIX, //六顺子 STRAIGHT_SEVEN, //七顺子 STRAIGHT_EIGHT, //八顺子 STRAIGHT_NINE, //九顺子 STRAIGHT_TEN, //十顺子 STRAIGHT_ELEVEN, //十一顺子 STRAIGHT_TWELVE //十二顺子 }; enum Option { GIVECARD = 50 }; struct BmpInfo { HBITMAP hbmp; }; struct CardInfo { int RcID; int Color; int nValue; }; class CARD { private: vector<int>_temp; vector<int>_Player1; vector<int>_Player2; vector<int>_Yourself; vector<int>_ChooseCard; vector<int>_ChooseCard2; vector<int>_ChooseCard3; BmpInfo bi[CARD_SIZE]; CardInfo ci[CARD_SIZE]; HWND _hWnd; HDC _hdcMem; HWND _Btn1, _Btn2; HWND _hBtn1, _hBtn2; HINSTANCE _hInst; //开始发牌 BOOL _FirstPaint; BOOL _StartSwitch; //到谁出牌 BOOL _IsYourTurn; BOOL _PlayerTurn1; BOOL _PlayerTurn2; //抢地主 BOOL _GetLanLoad; BOOL _WantLoad1; BOOL _WantLoad2; BOOL _WantLoad3; //显示出的牌 BOOL ShowCard1; BOOL ShowYourself; BOOL ShowCard2; int _CardOpt; int _cxPos, _cyPos; int _cxClient, _cyClient; public: CARD(); ~CARD(); void StartGame(); void InitHinst(HWND hWnd); void ClientSize(LPARAM lParam); void SetRandNum(); void PlayMP3(); void Paint(); void JudgePlayer(); void BtnMsg(); void BtnMsg2(); void BtnChoose(); void BtnChoose2(); void ResortVector(); bool IfHasInt(int x); void JudgeCardType(vector<int>Vec); void ShowPlayerCard1(); void ShowPlayerCard2(); void OnLeftButton(LPARAM lParam); };
[ "1945437957@qq.com" ]
1945437957@qq.com
428ce4fd4d48af81d151bc8f88efd29a39c02205
e4145c69e62181c384bfa83147675584a2edbe39
/libraries/Audio_master/input_adc.h
63ff291d1069e1e1bb6944575a924a32e3cb1918
[]
no_license
lukvog/HUGO
13b1a32bf57825cd9e15d58dd90f6fe05e219281
e6e83af2ed98ea022d037a0697e1a04627eb5091
refs/heads/master
2021-01-22T22:45:51.006385
2014-04-26T14:15:48
2014-04-26T14:15:48
18,528,000
0
2
null
null
null
null
UTF-8
C++
false
false
1,904
h
/* Audio Library for Teensy 3.X * Copyright (c) 2014, Paul Stoffregen, paul@pjrc.com * * Development of this audio library was funded by PJRC.COM, LLC by sales of * Teensy and Audio Adaptor boards. Please support PJRC's efforts to develop * open source software by purchasing Teensy or other PJRC products. * * 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, development funding 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 input_adc_h_ #define input_adc_h_ #include "AudioStream.h" class AudioInputAnalog : public AudioStream { public: AudioInputAnalog(unsigned int pin) : AudioStream(0, NULL) { begin(pin); } virtual void update(void); void begin(unsigned int pin); friend void dma_ch2_isr(void); private: static audio_block_t *block_left; static uint16_t block_offset; uint16_t dc_average; static bool update_responsibility; }; #endif
[ "lukas_vogel@sunrise.ch" ]
lukas_vogel@sunrise.ch
c77d4c2d5df4bde2530ec0454393d3297065e921
c5f94883c66644e613d76b06c46c5d019d8e7c01
/transport/channel/channel_pipeline.h
66609292006fa61007959eeeb8771999b6ad4f31
[ "MIT" ]
permissive
bingo787/transport2.0
47f80c91640b7416e70acf4be0e864feedddbaf4
c82057db7050d768e105adbbc63af8b3e38b1668
refs/heads/master
2022-04-08T08:54:04.567008
2020-02-24T03:59:22
2020-02-24T03:59:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
249
h
#ifndef ROSA_TRANSPORT_CHANNEL_CHANNEL_PIPELINE_H_ #define ROSA_TRANSPORT_CHANNEL_CHANNEL_PIPELINE_H_ namespace rosa { namespace transport { namespace channel { class ChannelPipeline { }; } } } #endif //ROSA_TRANSPORT_CHANNEL_CHANNEL_PIPELINE_H_
[ "zhaoqibin2009@qq.com" ]
zhaoqibin2009@qq.com
23f74e20c51b503a12149809c9601f61f9606bad
fe164360a17a2afee0dc5ad3ed08d214e7bd74a8
/Sample/GameEngineFromScratch-article_15/Platform/Windows/helloengine_d3d.cpp
80d92a6544f660c6162904b89794d4053ad5444f
[ "MIT" ]
permissive
AcmenLu/AcmenEngine
9fd94338974b6300465f0d40f70d65c55c6e32a9
437b55dea0edd6ea89ac6fc236f21e067dbf97aa
refs/heads/master
2020-06-19T09:29:55.526623
2019-08-29T01:09:28
2019-08-29T01:09:28
196,661,645
0
0
null
null
null
null
UTF-8
C++
false
false
31,751
cpp
// include the basic windows header file #include <windows.h> #include <windowsx.h> <<<<<<< HEAD #include <tchar.h> #include <stdint.h> #include <d3d11.h> #include <d3d11_1.h> ======= #include <stdio.h> #include <tchar.h> #include <stdint.h> #include <d3d12.h> #include "d3dx12.h" #include <DXGI1_4.h> >>>>>>> 5e179677b09f0c27979cd12a91898f261c3126dd #include <d3dcompiler.h> #include <DirectXMath.h> #include <DirectXPackedVector.h> #include <DirectXColors.h> <<<<<<< HEAD using namespace DirectX; using namespace DirectX::PackedVector; const uint32_t SCREEN_WIDTH = 960; const uint32_t SCREEN_HEIGHT = 480; // global declarations IDXGISwapChain *g_pSwapchain = nullptr; // the pointer to the swap chain interface ID3D11Device *g_pDev = nullptr; // the pointer to our Direct3D device interface ID3D11DeviceContext *g_pDevcon = nullptr; // the pointer to our Direct3D device context ID3D11RenderTargetView *g_pRTView = nullptr; ID3D11InputLayout *g_pLayout = nullptr; // the pointer to the input layout ID3D11VertexShader *g_pVS = nullptr; // the pointer to the vertex shader ID3D11PixelShader *g_pPS = nullptr; // the pointer to the pixel shader ID3D11Buffer *g_pVBuffer = nullptr; // Vertex Buffer ======= #include <wrl/client.h> #include <string> #include <exception> namespace My { // Helper class for COM exceptions class com_exception : public std::exception { public: com_exception(HRESULT hr) : result(hr) {} virtual const char* what() const override { static char s_str[64] = { 0 }; sprintf_s(s_str, "Failure with HRESULT of %08X", static_cast<unsigned int>(result)); return s_str; } private: HRESULT result; }; // Helper utility converts D3D API failures into exceptions. inline void ThrowIfFailed(HRESULT hr) { if (FAILED(hr)) { throw com_exception(hr); } } } using namespace My; using namespace DirectX; using namespace DirectX::PackedVector; using namespace Microsoft::WRL; using namespace std; const uint32_t nScreenWidth = 960; const uint32_t nScreenHeight = 480; const uint32_t nFrameCount = 2; const bool bUseWarpDevice = true; // global declarations D3D12_VIEWPORT g_ViewPort = {0.0f, 0.0f, static_cast<float>(nScreenWidth), static_cast<float>(nScreenHeight)}; // viewport structure D3D12_RECT g_ScissorRect = {0, 0, nScreenWidth, nScreenHeight}; // scissor rect structure ComPtr<IDXGISwapChain3> g_pSwapChain = nullptr; // the pointer to the swap chain interface ComPtr<ID3D12Device> g_pDev = nullptr; // the pointer to our Direct3D device interface ComPtr<ID3D12Resource> g_pRenderTargets[nFrameCount]; // the pointer to rendering buffer. [descriptor] ComPtr<ID3D12CommandAllocator> g_pCommandAllocator; // the pointer to command buffer allocator ComPtr<ID3D12CommandQueue> g_pCommandQueue; // the pointer to command queue ComPtr<ID3D12RootSignature> g_pRootSignature; // a graphics root signature defines what resources are bound to the pipeline ComPtr<ID3D12DescriptorHeap> g_pRtvHeap; // an array of descriptors of GPU objects ComPtr<ID3D12PipelineState> g_pPipelineState; // an object maintains the state of all currently set shaders // and certain fixed function state objects // such as the input assembler, tesselator, rasterizer and output manager ComPtr<ID3D12GraphicsCommandList> g_pCommandList; // a list to store GPU commands, which will be submitted to GPU to execute when done uint32_t g_nRtvDescriptorSize; ComPtr<ID3D12Resource> g_pVertexBuffer; // the pointer to the vertex buffer D3D12_VERTEX_BUFFER_VIEW g_VertexBufferView; // a view of the vertex buffer // Synchronization objects uint32_t g_nFrameIndex; HANDLE g_hFenceEvent; ComPtr<ID3D12Fence> g_pFence; uint32_t g_nFenceValue; >>>>>>> 5e179677b09f0c27979cd12a91898f261c3126dd // vertex buffer structure struct VERTEX { XMFLOAT3 Position; XMFLOAT4 Color; }; <<<<<<< HEAD template<class T> inline void SafeRelease(T **ppInterfaceToRelease) { if (*ppInterfaceToRelease != nullptr) { (*ppInterfaceToRelease)->Release(); (*ppInterfaceToRelease) = nullptr; } } void CreateRenderTarget() { HRESULT hr; ID3D11Texture2D *pBackBuffer; // Get a pointer to the back buffer g_pSwapchain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer ); // Create a render-target view g_pDev->CreateRenderTargetView( pBackBuffer, NULL, &g_pRTView ); pBackBuffer->Release(); // Bind the view g_pDevcon->OMSetRenderTargets( 1, &g_pRTView, NULL ); } void SetViewPort() { D3D11_VIEWPORT viewport; ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT)); viewport.TopLeftX = 0; viewport.TopLeftY = 0; viewport.Width = SCREEN_WIDTH; viewport.Height = SCREEN_HEIGHT; g_pDevcon->RSSetViewports(1, &viewport); ======= wstring g_AssetsPath; // Helper function for resolving the full path of assets. std::wstring GetAssetFullPath(LPCWSTR assetName) { return g_AssetsPath + assetName; } void GetAssetsPath(WCHAR* path, UINT pathSize) { if (path == nullptr) { throw std::exception(); } DWORD size = GetModuleFileNameW(nullptr, path, pathSize); if (size == 0 || size == pathSize) { // Method failed or path was truncated. throw std::exception(); } WCHAR* lastSlash = wcsrchr(path, L'\\'); if (lastSlash) { *(lastSlash + 1) = L'\0'; } } void WaitForPreviousFrame() { // WAITING FOR THE FRAME TO COMPLETE BEFORE CONTINUING IS NOT BEST PRACTICE. // This is code implemented as such for simplicity. More advanced samples // illustrate how to use fences for efficient resource usage. // Signal and increment the fence value. const uint64_t fence = g_nFenceValue; ThrowIfFailed(g_pCommandQueue->Signal(g_pFence.Get(), fence)); g_nFenceValue++; // Wait until the previous frame is finished. if (g_pFence->GetCompletedValue() < fence) { ThrowIfFailed(g_pFence->SetEventOnCompletion(fence, g_hFenceEvent)); WaitForSingleObject(g_hFenceEvent, INFINITE); } g_nFrameIndex = g_pSwapChain->GetCurrentBackBufferIndex(); } void CreateRenderTarget() { // Describe and create a render target view (RTV) descriptor heap. D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {}; rtvHeapDesc.NumDescriptors = nFrameCount; rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; ThrowIfFailed(g_pDev->CreateDescriptorHeap(&rtvHeapDesc, IID_PPV_ARGS(&g_pRtvHeap))); g_nRtvDescriptorSize = g_pDev->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(g_pRtvHeap->GetCPUDescriptorHandleForHeapStart()); // Create a RTV for each frame. for (uint32_t i = 0; i < nFrameCount; i++) { ThrowIfFailed(g_pSwapChain->GetBuffer(i, IID_PPV_ARGS(&g_pRenderTargets[i]))); g_pDev->CreateRenderTargetView(g_pRenderTargets[i].Get(), nullptr, rtvHandle); rtvHandle.Offset(1, g_nRtvDescriptorSize); } >>>>>>> 5e179677b09f0c27979cd12a91898f261c3126dd } // this is the function that loads and prepares the shaders void InitPipeline() { <<<<<<< HEAD // load and compile the two shaders ID3DBlob *VS, *PS; D3DReadFileToBlob(L"copy.vso", &VS); D3DReadFileToBlob(L"copy.pso", &PS); // encapsulate both shaders into shader objects g_pDev->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &g_pVS); g_pDev->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), NULL, &g_pPS); // set the shader objects g_pDevcon->VSSetShader(g_pVS, 0, 0); g_pDevcon->PSSetShader(g_pPS, 0, 0); // create the input layout object D3D11_INPUT_ELEMENT_DESC ied[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}, }; g_pDev->CreateInputLayout(ied, 2, VS->GetBufferPointer(), VS->GetBufferSize(), &g_pLayout); g_pDevcon->IASetInputLayout(g_pLayout); VS->Release(); PS->Release(); ======= ThrowIfFailed(g_pDev->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&g_pCommandAllocator))); // create an empty root signature CD3DX12_ROOT_SIGNATURE_DESC rsd; rsd.Init(0, nullptr, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT); ComPtr<ID3DBlob> signature; ComPtr<ID3DBlob> error; ThrowIfFailed(D3D12SerializeRootSignature(&rsd, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error)); ThrowIfFailed(g_pDev->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&g_pRootSignature))); // load the shaders #if defined(_DEBUG) // Enable better shader debugging with the graphics debugging tools. UINT compileFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION; #else UINT compileFlags = 0; #endif ComPtr<ID3DBlob> vertexShader; ComPtr<ID3DBlob> pixelShader; D3DCompileFromFile( GetAssetFullPath(L"copy.vs").c_str(), nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", "vs_5_0", compileFlags, 0, &vertexShader, &error); if (error) { OutputDebugString((LPCTSTR)error->GetBufferPointer()); error->Release(); throw std::exception(); } D3DCompileFromFile( GetAssetFullPath(L"copy.ps").c_str(), nullptr, D3D_COMPILE_STANDARD_FILE_INCLUDE, "main", "ps_5_0", compileFlags, 0, &pixelShader, &error); if (error) { OutputDebugString((LPCTSTR)error->GetBufferPointer()); error->Release(); throw std::exception(); } // create the input layout object D3D12_INPUT_ELEMENT_DESC ied[] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}, }; // describe and create the graphics pipeline state object (PSO) D3D12_GRAPHICS_PIPELINE_STATE_DESC psod = {}; psod.InputLayout = { ied, _countof(ied) }; psod.pRootSignature = g_pRootSignature.Get(); psod.VS = { reinterpret_cast<UINT8*>(vertexShader->GetBufferPointer()), vertexShader->GetBufferSize() }; psod.PS = { reinterpret_cast<UINT8*>(pixelShader->GetBufferPointer()), pixelShader->GetBufferSize() }; psod.RasterizerState= CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT); psod.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT); psod.DepthStencilState.DepthEnable = FALSE; psod.DepthStencilState.StencilEnable= FALSE; psod.SampleMask = UINT_MAX; psod.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; psod.NumRenderTargets = 1; psod.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM; psod.SampleDesc.Count = 1; ThrowIfFailed(g_pDev->CreateGraphicsPipelineState(&psod, IID_PPV_ARGS(&g_pPipelineState))); ThrowIfFailed(g_pDev->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, g_pCommandAllocator.Get(), g_pPipelineState.Get(), IID_PPV_ARGS(&g_pCommandList))); ThrowIfFailed(g_pCommandList->Close()); >>>>>>> 5e179677b09f0c27979cd12a91898f261c3126dd } // this is the function that creates the shape to render void InitGraphics() { // create a triangle using the VERTEX struct VERTEX OurVertices[] = { {XMFLOAT3(0.0f, 0.5f, 0.0f), XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f)}, {XMFLOAT3(0.45f, -0.5, 0.0f), XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f)}, {XMFLOAT3(-0.45f, -0.5f, 0.0f), XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f)} }; <<<<<<< HEAD // create the vertex buffer D3D11_BUFFER_DESC bd; ZeroMemory(&bd, sizeof(bd)); bd.Usage = D3D11_USAGE_DYNAMIC; // write access access by CPU and GPU bd.ByteWidth = sizeof(VERTEX) * 3; // size is the VERTEX struct * 3 bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; // use as a vertex buffer bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // allow CPU to write in buffer g_pDev->CreateBuffer(&bd, NULL, &g_pVBuffer); // create the buffer // copy the vertices into the buffer D3D11_MAPPED_SUBRESOURCE ms; g_pDevcon->Map(g_pVBuffer, NULL, D3D11_MAP_WRITE_DISCARD, NULL, &ms); // map the buffer memcpy(ms.pData, OurVertices, sizeof(VERTEX) * 3); // copy the data g_pDevcon->Unmap(g_pVBuffer, NULL); // unmap the buffer } // this function prepare graphic resources for use HRESULT CreateGraphicsResources(HWND hWnd) { HRESULT hr = S_OK; if (g_pSwapchain == nullptr) { ======= const UINT vertexBufferSize = sizeof(OurVertices); // Note: using upload heaps to transfer static data like vert buffers is not // recommended. Every time the GPU needs it, the upload heap will be marshalled // over. Please read up on Default Heap usage. An upload heap is used here for // code simplicity and because there are very few verts to actually transfer. ThrowIfFailed(g_pDev->CreateCommittedResource( &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD), D3D12_HEAP_FLAG_NONE, &CD3DX12_RESOURCE_DESC::Buffer(vertexBufferSize), D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, IID_PPV_ARGS(&g_pVertexBuffer))); // copy the vertices into the buffer uint8_t *pVertexDataBegin; CD3DX12_RANGE readRange(0, 0); // we do not intend to read this buffer on CPU ThrowIfFailed(g_pVertexBuffer->Map(0, &readRange, reinterpret_cast<void**>(&pVertexDataBegin))); // map the buffer memcpy(pVertexDataBegin, OurVertices, vertexBufferSize); // copy the data g_pVertexBuffer->Unmap(0, nullptr); // unmap the buffer // initialize the vertex buffer view g_VertexBufferView.BufferLocation = g_pVertexBuffer->GetGPUVirtualAddress(); g_VertexBufferView.StrideInBytes = sizeof(VERTEX); g_VertexBufferView.SizeInBytes = vertexBufferSize; // create synchronization objects and wait until assets have been uploaded to the GPU ThrowIfFailed(g_pDev->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&g_pFence))); g_nFenceValue = 1; // create an event handle to use for frame synchronization g_hFenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr); if (g_hFenceEvent == nullptr) { ThrowIfFailed(HRESULT_FROM_WIN32(GetLastError())); } // wait for the command list to execute; we are reusing the same command // list in our main loop but for now, we just want to wait for setup to // complete before continuing. WaitForPreviousFrame(); } void GetHardwareAdapter(IDXGIFactory4* pFactory, IDXGIAdapter1** ppAdapter) { IDXGIAdapter1* pAdapter = nullptr; *ppAdapter = nullptr; for (UINT adapterIndex = 0; DXGI_ERROR_NOT_FOUND != pFactory->EnumAdapters1(adapterIndex, &pAdapter); ++adapterIndex) { DXGI_ADAPTER_DESC1 desc; pAdapter->GetDesc1(&desc); if (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE) { // Don't select the Basic Render Driver adapter. continue; } // Check to see if the adapter supports Direct3D 12, but don't create the // actual device yet. if (SUCCEEDED(D3D12CreateDevice(pAdapter, D3D_FEATURE_LEVEL_11_0, _uuidof(ID3D12Device), nullptr))) { break; } } *ppAdapter = pAdapter; } // this function prepare graphic resources for use void CreateGraphicsResources(HWND hWnd) { if (g_pSwapChain.Get() == nullptr) { #if defined(_DEBUG) // Enable the D3D12 debug layer. { ComPtr<ID3D12Debug> debugController; if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController)))) { debugController->EnableDebugLayer(); } } #endif ComPtr<IDXGIFactory4> factory; ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&factory))); if (bUseWarpDevice) { ComPtr<IDXGIAdapter> warpAdapter; ThrowIfFailed(factory->EnumWarpAdapter(IID_PPV_ARGS(&warpAdapter))); ThrowIfFailed(D3D12CreateDevice( warpAdapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&g_pDev) )); } else { ComPtr<IDXGIAdapter1> hardwareAdapter; GetHardwareAdapter(factory.Get(), &hardwareAdapter); ThrowIfFailed(D3D12CreateDevice( hardwareAdapter.Get(), D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&g_pDev) )); } // Describe and create the command queue. D3D12_COMMAND_QUEUE_DESC queueDesc = {}; queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; ThrowIfFailed(g_pDev->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&g_pCommandQueue))); >>>>>>> 5e179677b09f0c27979cd12a91898f261c3126dd // create a struct to hold information about the swap chain DXGI_SWAP_CHAIN_DESC scd; // clear out the struct for use ZeroMemory(&scd, sizeof(DXGI_SWAP_CHAIN_DESC)); // fill the swap chain description struct <<<<<<< HEAD scd.BufferCount = 1; // one back buffer scd.BufferDesc.Width = SCREEN_WIDTH; scd.BufferDesc.Height = SCREEN_HEIGHT; ======= scd.BufferCount = nFrameCount; // back buffer count scd.BufferDesc.Width = nScreenWidth; scd.BufferDesc.Height = nScreenHeight; >>>>>>> 5e179677b09f0c27979cd12a91898f261c3126dd scd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // use 32-bit color scd.BufferDesc.RefreshRate.Numerator = 60; scd.BufferDesc.RefreshRate.Denominator = 1; scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // how swap chain is to be used <<<<<<< HEAD scd.OutputWindow = hWnd; // the window to be used scd.SampleDesc.Count = 4; // how many multisamples scd.Windowed = TRUE; // windowed/full-screen mode scd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; // allow full-screen switching const D3D_FEATURE_LEVEL FeatureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, D3D_FEATURE_LEVEL_9_1}; D3D_FEATURE_LEVEL FeatureLevelSupported; HRESULT hr = S_OK; // create a device, device context and swap chain using the information in the scd struct hr = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, FeatureLevels, _countof(FeatureLevels), D3D11_SDK_VERSION, &scd, &g_pSwapchain, &g_pDev, &FeatureLevelSupported, &g_pDevcon); if (hr == E_INVALIDARG) { hr = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &FeatureLevelSupported, 1, D3D11_SDK_VERSION, &scd, &g_pSwapchain, &g_pDev, NULL, &g_pDevcon); } if (hr == S_OK) { CreateRenderTarget(); SetViewPort(); InitPipeline(); InitGraphics(); } } return hr; ======= scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; // DXGI_SWAP_EFFECT_FLIP_DISCARD only supported after Win10 // use DXGI_SWAP_EFFECT_DISCARD on platforms early than Win10 scd.OutputWindow = hWnd; // the window to be used scd.SampleDesc.Count = 1; // multi-samples can not be used when in SwapEffect sets to // DXGI_SWAP_EFFECT_FLOP_DISCARD scd.Windowed = TRUE; // windowed/full-screen mode scd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; // allow full-screen transition ComPtr<IDXGISwapChain> swapChain; ThrowIfFailed(factory->CreateSwapChain( g_pCommandQueue.Get(), // Swap chain needs the queue so that it can force a flush on it &scd, &swapChain )); ThrowIfFailed(swapChain.As(&g_pSwapChain)); g_nFrameIndex = g_pSwapChain->GetCurrentBackBufferIndex(); CreateRenderTarget(); InitPipeline(); InitGraphics(); } >>>>>>> 5e179677b09f0c27979cd12a91898f261c3126dd } void DiscardGraphicsResources() { <<<<<<< HEAD SafeRelease(&g_pLayout); SafeRelease(&g_pVS); SafeRelease(&g_pPS); SafeRelease(&g_pVBuffer); SafeRelease(&g_pSwapchain); SafeRelease(&g_pRTView); SafeRelease(&g_pDev); SafeRelease(&g_pDevcon); } // this is the function used to render a single frame void RenderFrame() { // clear the back buffer to a deep blue const FLOAT clearColor[] = {0.0f, 0.2f, 0.4f, 1.0f}; g_pDevcon->ClearRenderTargetView(g_pRTView, clearColor); ======= WaitForPreviousFrame(); CloseHandle(g_hFenceEvent); } void PopulateCommandList() { // command list allocators can only be reset when the associated // command lists have finished execution on the GPU; apps should use // fences to determine GPU execution progress. ThrowIfFailed(g_pCommandAllocator->Reset()); // however, when ExecuteCommandList() is called on a particular command // list, that command list can then be reset at any time and must be before // re-recording. ThrowIfFailed(g_pCommandList->Reset(g_pCommandAllocator.Get(), g_pPipelineState.Get())); // Set necessary state. g_pCommandList->SetGraphicsRootSignature(g_pRootSignature.Get()); g_pCommandList->RSSetViewports(1, &g_ViewPort); g_pCommandList->RSSetScissorRects(1, &g_ScissorRect); // Indicate that the back buffer will be used as a render target. g_pCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition( g_pRenderTargets[g_nFrameIndex].Get(), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET)); CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(g_pRtvHeap->GetCPUDescriptorHandleForHeapStart(), g_nFrameIndex, g_nRtvDescriptorSize); g_pCommandList->OMSetRenderTargets(1, &rtvHandle, FALSE, nullptr); // clear the back buffer to a deep blue const FLOAT clearColor[] = {0.0f, 0.2f, 0.4f, 1.0f}; g_pCommandList->ClearRenderTargetView(rtvHandle, clearColor, 0, nullptr); >>>>>>> 5e179677b09f0c27979cd12a91898f261c3126dd // do 3D rendering on the back buffer here { // select which vertex buffer to display <<<<<<< HEAD UINT stride = sizeof(VERTEX); UINT offset = 0; g_pDevcon->IASetVertexBuffers(0, 1, &g_pVBuffer, &stride, &offset); // select which primtive type we are using g_pDevcon->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // draw the vertex buffer to the back buffer g_pDevcon->Draw(3, 0); } // swap the back buffer and the front buffer g_pSwapchain->Present(0, 0); ======= g_pCommandList->IASetVertexBuffers(0, 1, &g_VertexBufferView); // select which primtive type we are using g_pCommandList->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST); // draw the vertex buffer to the back buffer g_pCommandList->DrawInstanced(3, 1, 0, 0); } // Indicate that the back buffer will now be used to present. g_pCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition( g_pRenderTargets[g_nFrameIndex].Get(), D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT)); ThrowIfFailed(g_pCommandList->Close()); } // this is the function used to render a single frame void RenderFrame() { // record all the commands we need to render the scene into the command list PopulateCommandList(); // execute the command list ID3D12CommandList *ppCommandLists[] = { g_pCommandList.Get() }; g_pCommandQueue->ExecuteCommandLists(_countof(ppCommandLists), ppCommandLists); // swap the back buffer and the front buffer ThrowIfFailed(g_pSwapChain->Present(1, 0)); WaitForPreviousFrame(); >>>>>>> 5e179677b09f0c27979cd12a91898f261c3126dd } // the WindowProc function prototype LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); // the entry point for any Windows program int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { // the handle for the window, filled by a function HWND hWnd; // this struct holds information for the window class WNDCLASSEX wc; <<<<<<< HEAD ======= WCHAR assetsPath[512]; GetAssetsPath(assetsPath, _countof(assetsPath)); g_AssetsPath = assetsPath; >>>>>>> 5e179677b09f0c27979cd12a91898f261c3126dd // clear out the window class for use ZeroMemory(&wc, sizeof(WNDCLASSEX)); // fill in the struct with the needed information wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WindowProc; wc.hInstance = hInstance; wc.hCursor = LoadCursor(nullptr, IDC_ARROW); wc.hbrBackground = (HBRUSH)COLOR_WINDOW; wc.lpszClassName = _T("WindowClass1"); // register the window class RegisterClassEx(&wc); // create the window and use the result as the handle hWnd = CreateWindowEx(0, _T("WindowClass1"), // name of the window class _T("Hello, Engine![Direct 3D]"), // title of the window WS_OVERLAPPEDWINDOW, // window style 100, // x-position of the window 100, // y-position of the window <<<<<<< HEAD SCREEN_WIDTH, // width of the window SCREEN_HEIGHT, // height of the window ======= nScreenWidth, // width of the window nScreenHeight, // height of the window >>>>>>> 5e179677b09f0c27979cd12a91898f261c3126dd NULL, // we have no parent window, NULL NULL, // we aren't using menus, NULL hInstance, // application handle NULL); // used with multiple windows, NULL // display the window on the screen ShowWindow(hWnd, nCmdShow); // enter the main loop: // this struct holds Windows event messages MSG msg; // wait for the next message in the queue, store the result in 'msg' while(GetMessage(&msg, nullptr, 0, 0)) { // translate keystroke messages into the right format TranslateMessage(&msg); // send the message to the WindowProc function DispatchMessage(&msg); } // return this part of the WM_QUIT message to Windows return msg.wParam; } // this is the main message handler for the program LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { LRESULT result = 0; bool wasHandled = false; // sort through and find what code to run for the message given switch(message) { <<<<<<< HEAD case WM_CREATE: wasHandled = true; break; case WM_PAINT: result = CreateGraphicsResources(hWnd); RenderFrame(); wasHandled = true; break; case WM_SIZE: if (g_pSwapchain != nullptr) { DiscardGraphicsResources(); g_pSwapchain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH); } wasHandled = true; break; case WM_DESTROY: DiscardGraphicsResources(); PostQuitMessage(0); wasHandled = true; ======= case WM_CREATE: wasHandled = true; break; case WM_PAINT: CreateGraphicsResources(hWnd); RenderFrame(); wasHandled = true; break; case WM_SIZE: if (g_pSwapChain != nullptr) { DiscardGraphicsResources(); g_pSwapChain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH); } wasHandled = true; break; case WM_DESTROY: DiscardGraphicsResources(); PostQuitMessage(0); wasHandled = true; >>>>>>> 5e179677b09f0c27979cd12a91898f261c3126dd break; case WM_DISPLAYCHANGE: InvalidateRect(hWnd, nullptr, false); wasHandled = true; break; } // Handle any messages the switch statement didn't if (!wasHandled) { result = DefWindowProc (hWnd, message, wParam, lParam); } return result; }
[ "1109325089@qq.com" ]
1109325089@qq.com
11a2aae1260b812ebc180574dca0455f25269978
44ff68cf4a20fdcf90424d2f12ef82ca203a3933
/Burnout_2.0/src/Burnout/Core/Window.h
e9e072ff715f8d192d5039d0b3a8e3f01ab02de9
[ "MIT" ]
permissive
EsasHG/Burnout_2.0
3fca70667f4e4315d61eaaba1fe63a5d836b0bcd
66f4d1d98d2123af6cb58d5c432499c25a644669
refs/heads/master
2020-11-28T14:00:36.409364
2020-04-10T14:46:46
2020-04-10T14:46:46
229,840,589
0
0
null
null
null
null
UTF-8
C++
false
false
983
h
#pragma once #include "bopch.h" #include "Burnout/Core/Core.h" #include "Burnout/Events/Event.h" namespace Burnout { struct WindowProps { std::string Title; unsigned int Width; unsigned int Height; WindowProps(const std::string& title = "Burnout Engine", unsigned int width = 1280, unsigned int height = 720) : Title(title), Width(width), Height(height) { } }; //interface representing a desktop system based Window class BURNOUT_API Window { public: using EventCallbackFn = std::function<void(Event&)>; virtual ~Window() {} virtual void OnUpdate() = 0; virtual unsigned int GetWidth() const = 0; virtual unsigned int GetHeight() const = 0; //Window attributes virtual void SetEventCallback(const EventCallbackFn& callback) = 0; virtual void SetVSync(bool enabled) = 0; virtual bool IsVSync() const = 0; virtual void* GetNativeWindow() const = 0; static Window* Create(const WindowProps& props = WindowProps()); }; }
[ "espenhg@hotmail.com" ]
espenhg@hotmail.com
b03d71c7dd7202f9e2d01a7ea5975703405343bb
d0fb46aecc3b69983e7f6244331a81dff42d9595
/dds/include/alibabacloud/dds/model/ReleaseNodePrivateNetworkAddressResult.h
46646f41e896fca9e283e0614100915ca4ff5225
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
1,430
h
/* * Copyright 2009-2017 Alibaba Cloud 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. */ #ifndef ALIBABACLOUD_DDS_MODEL_RELEASENODEPRIVATENETWORKADDRESSRESULT_H_ #define ALIBABACLOUD_DDS_MODEL_RELEASENODEPRIVATENETWORKADDRESSRESULT_H_ #include <string> #include <vector> #include <utility> #include <alibabacloud/core/ServiceResult.h> #include <alibabacloud/dds/DdsExport.h> namespace AlibabaCloud { namespace Dds { namespace Model { class ALIBABACLOUD_DDS_EXPORT ReleaseNodePrivateNetworkAddressResult : public ServiceResult { public: ReleaseNodePrivateNetworkAddressResult(); explicit ReleaseNodePrivateNetworkAddressResult(const std::string &payload); ~ReleaseNodePrivateNetworkAddressResult(); protected: void parse(const std::string &payload); private: }; } } } #endif // !ALIBABACLOUD_DDS_MODEL_RELEASENODEPRIVATENETWORKADDRESSRESULT_H_
[ "noreply@github.com" ]
noreply@github.com
1f347d622043e7b4584b0dff99e0814826f3752a
5c93333a71b27cfd5e5a017f29f74b25e3dd17fd
/TopCoder/Div 2/502-500 TheLotteryBothDivs.cpp
879d0e3b4528c8f7547049662dc09a5a5c2db1c6
[]
no_license
sktheboss/ProblemSolving
7bcd7e8c2de1f4b1d251093c88754e2b1015684b
5aff87cc10036a0e6ff255ae47e68a5d71cb7e9d
refs/heads/master
2021-05-29T03:29:28.980054
2015-03-11T10:06:00
2015-03-11T10:06:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,206
cpp
#include <vector> #include <list> #include <map> #include <set> #include <queue> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <string.h> #define rep(i,n) for(int i=0; i<n; i++) #define reps(i,m,n) for(int i=m; i<n; i++) #define repe(i,m,n) for(int i=m; i<=n; i++) #define repi(it,stl) for(typeof((stl).begin()) it = (stl).begin(); (it)!=stl.end(); ++(it)) #define sz(a) ((int)(a).size()) #define mem(a,n) memset((a), (n), sizeof(a)) #define all(n) (n).begin(),(n).end() #define rall(n) (n).rbegin(),(n).rend() #define allarr(n) (n), (n)+( (sizeof (n)) / (sizeof (*n)) ) #define mp(a,b) make_pair((a),(b)) #define pii pair<int,int> #define vi vector<int> #define vs vector<string> #define sstr stringstream typedef long long ll; using namespace std; bool cmp(string a, string b){ return sz(a)<sz(b); } class TheLotteryBothDivs { public: double find(vector<string> good){ sort(all(good),cmp); rep(i,sz(good)) reverse(all(good[i])); rep(i,sz(good)){ reps(j,i+1,sz(good)){ if(good[j].find(good[i]) == 0) good.erase(good.begin()+j), --j; else if(good[i]==good[j]) good.erase(good.begin()+j), --j; } } double res=0; rep(i,sz(good)) res += 1.0/pow(10.0,sz(good[i])+0.0); return res; } }; // BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit 2.1.8 (beta) modified by pivanof #include <iostream> #include <string> #include <vector> using namespace std; bool KawigiEdit_RunTest(int testNum, vector <string> p0, bool hasAnswer, double p1) { cout << "Test " << testNum << ": [" << "{"; for (int i = 0; int(p0.size()) > i; ++i) { if (i > 0) { cout << ","; } cout << "\"" << p0[i] << "\""; } cout << "}"; cout << "]" << endl; TheLotteryBothDivs *obj; double answer; obj = new TheLotteryBothDivs(); clock_t startTime = clock(); answer = obj->find(p0); clock_t endTime = clock(); delete obj; bool res; res = true; cout << "Time: " << double(endTime - startTime) / CLOCKS_PER_SEC << " seconds" << endl; if (hasAnswer) { cout << "Desired answer:" << endl; cout << "\t" << p1 << endl; } cout << "Your answer:" << endl; cout << "\t" << answer << endl; if (hasAnswer) { res = answer == answer && fabs(p1 - answer) <= 1e-9 * max(1.0, fabs(p1)); } if (!res) { cout << "DOESN'T MATCH!!!!" << endl; } else if (double(endTime - startTime) / CLOCKS_PER_SEC >= 2) { cout << "FAIL the timeout" << endl; res = false; } else if (hasAnswer) { cout << "Match :-)" << endl; } else { cout << "OK, but is it right?" << endl; } cout << "" << endl; return res; } int main() { bool all_right; all_right = true; vector <string> p0; double p1; { // ----- test 0 ----- string t0[] = {"4"}; p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0])); p1 = 0.1; all_right = KawigiEdit_RunTest(0, p0, true, p1) && all_right; // ------------------ } { // ----- test 1 ----- string t0[] = {"4","7"}; p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0])); p1 = 0.2; all_right = KawigiEdit_RunTest(1, p0, true, p1) && all_right; // ------------------ } { // ----- test 2 ----- string t0[] = {"47","47"}; p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0])); p1 = 0.01; all_right = KawigiEdit_RunTest(2, p0, true, p1) && all_right; // ------------------ } { // ----- test 3 ----- string t0[] = {"47","58","4747","502"}; p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0])); p1 = 0.021; all_right = KawigiEdit_RunTest(3, p0, true, p1) && all_right; // ------------------ } { // ----- test 4 ----- string t0[] = {"8542861","1954","6","523","000000000","5426","8"}; p0.assign(t0, t0 + sizeof(t0) / sizeof(t0[0])); p1 = 0.201100101; all_right = KawigiEdit_RunTest(4, p0, true, p1) && all_right; // ------------------ } if (all_right) { cout << "You're a stud (at least on the example cases)!" << endl; } else { cout << "Some of the test cases had errors." << endl; } return 0; } // END KAWIGIEDIT TESTING //Powered by KawigiEdit 2.1.8 (beta) modified by pivanof!
[ "fci.islam@gmail.com" ]
fci.islam@gmail.com
e1ac94181138c03dde13b96de3884e929de7ecbe
106c25b09d9dae70e9440b94e69bc0bd33418202
/C/solution_5.cpp
73c2ad35ca208e7acb39ee4bb3981406a23c17e6
[]
no_license
bobsayshilol/ProjectEuler
e1da10e4126dcce7e2235e043cc8b67154064c4f
52489c9b9b41e22e81c41cb0dd9fb13963357072
refs/heads/master
2021-01-17T11:11:27.819659
2016-05-12T00:39:53
2016-05-12T00:39:53
50,785,989
0
0
null
null
null
null
UTF-8
C++
false
false
1,215
cpp
/** * Smallest multiple * * 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. * What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? */ /** * For each number between 1 and 20 we need to work out the gcd of each number with a total product, then we can * multiply the total product by the new number and divide it by the gcd. */ // Common includes #include "common.h" // Begin the solution SOLUTION_BEGIN(5, uint64_t) { // The maximum number const uint64_t max = 20; // Set to 1 initially. This is the total product mentioned above result = 1; // Simple function to calculate the GCD of 2 numbers auto GCD = [](uint64_t a, uint64_t b) { // Make sure a >= b if (a < b) std::swap(a, b); // Simple loop uint64_t gcd; while ((gcd = a % b) != 0) { a = b; b = gcd; } return b; }; // Go through each number in the list for (uint64_t i=1; i<max; i++) { // Calculate the gcd uint64_t gcd = GCD(i, result); // Since the gcd divides both i and result fully we don't need to bother with bracket ordering result = result * i / gcd; } } SOLUTION_END()
[ "bobsayshilol@live.co.uk" ]
bobsayshilol@live.co.uk
39f8f5b5d1cfe8e66907d514790a27be3d776e63
c93c42beebb6785b084d1d319104769bfef3280c
/CPP/Porteføljeopgave 2/Porteføljeopgave 2/Biography.h
de7caeecdaac451549625da241b4b802be6ca213
[]
no_license
Gugfann/3.Semester
36b2a8c98c8749fa56236443d402eac69ad77223
c00c01e9633674d39617034b6b97fb2441212732
refs/heads/master
2021-01-10T17:40:25.010428
2016-01-10T00:02:41
2016-01-10T00:02:41
46,939,132
0
0
null
null
null
null
UTF-8
C++
false
false
165
h
#pragma once #include "Publication.h" class Biography : public Publication { public: Biography(); Biography(string aTitle, int aYear); virtual ~Biography(); };
[ "kmolha@gmail.com" ]
kmolha@gmail.com
2f0a063454dc486e89e31710217b2963ad96485e
3caaaeb2bb3247409868eb7a7731c61de9c11e86
/atcoder/AGC027_C.cpp
5a2acc939430303ed47e0e587efa788b8b568838
[]
no_license
taiyoslime/procon
6e3045a505ab2c74f5ae2e45bf89c7e9e145f56b
4b4d94244b9b22a55bf39e4ef71994be00d5991a
refs/heads/master
2020-12-28T02:04:43.542892
2020-04-19T09:50:17
2020-04-19T09:50:17
45,464,509
2
0
null
null
null
null
UTF-8
C++
false
false
862
cpp
#include <bits/stdc++.h> using namespace std; int n,m,a,b,g[200002][2],is_del[200002]; vector<int> v[200002],u; string s; int main (){ cin >> n >> m; cin >> s; for (int i = 0; i < m ; i++ ){ cin >> a >> b ; v[a].push_back(b); v[b].push_back(a); g[a][s[b - 1] == 'A' ] ++; g[b][s[a - 1] == 'A' ] ++; } for(int i=1;i<=n;i++) { if(!g[i][0] || !g[i][1]){ is_del[i] = 1; u.push_back(i); } } for (int i=0;i<u.size();i++){ for(auto j:v[u[i]]){ g[j][ s[ u[i] - 1 ] == 'A' ] -- ; if(!(g[j][ s[ u[i] - 1 ] == 'A' ]) && !is_del[j]){ u.push_back(j); is_del[j] = 1; } } } if (u.size() != n){ cout << "Yes" << endl; } else { cout << "No" << endl; } }
[ "hase.tekitou@gmail.com" ]
hase.tekitou@gmail.com
4ef3069953882a451882bccf8434c495cb448ea9
d0fb46aecc3b69983e7f6244331a81dff42d9595
/retailcloud/include/alibabacloud/retailcloud/model/AddClusterNodeRequest.h
c265690b1e412a3e8eac14a0a9cbc23f81895324
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
1,588
h
/* * Copyright 2009-2017 Alibaba Cloud 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. */ #ifndef ALIBABACLOUD_RETAILCLOUD_MODEL_ADDCLUSTERNODEREQUEST_H_ #define ALIBABACLOUD_RETAILCLOUD_MODEL_ADDCLUSTERNODEREQUEST_H_ #include <string> #include <vector> #include <alibabacloud/core/RpcServiceRequest.h> #include <alibabacloud/retailcloud/RetailcloudExport.h> namespace AlibabaCloud { namespace Retailcloud { namespace Model { class ALIBABACLOUD_RETAILCLOUD_EXPORT AddClusterNodeRequest : public RpcServiceRequest { public: AddClusterNodeRequest(); ~AddClusterNodeRequest(); std::vector<std::string> getEcsInstanceIdList()const; void setEcsInstanceIdList(const std::vector<std::string>& ecsInstanceIdList); std::string getClusterInstanceId()const; void setClusterInstanceId(const std::string& clusterInstanceId); private: std::vector<std::string> ecsInstanceIdList_; std::string clusterInstanceId_; }; } } } #endif // !ALIBABACLOUD_RETAILCLOUD_MODEL_ADDCLUSTERNODEREQUEST_H_
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
3db7e409b84d305180d61f393729035171dd298b
cff7648b765c2c6d27cdbcee7c9d66d80df72c0e
/Particle Effects - PrimeEngine/ParticleManager.cpp
540e6aa4e6f95fadd8c0c516901356d677eca7a0
[]
no_license
shrynshk7252/Sample-Code
3d69e107f0168b3850ab5f6023778c92e813be48
7cd79f66342e772562fa911e61e08befe98acdcb
refs/heads/master
2016-09-12T15:15:58.956128
2016-05-06T00:38:49
2016-05-06T00:38:49
58,169,060
0
0
null
null
null
null
UTF-8
C++
false
false
6,852
cpp
/* APIAbstraction */ #include "PrimeEngine/APIAbstraction/APIAbstractionDefines.h" /* Outer-Engine includes */ /* Inter-Engine includes */ #include "PrimeEngine/Lua/LuaEnvironment.h" /* Sibling and Children includes */ #include "ParticleManager.h" #include "ParticleEmitter.h" #include "PrimeEngine/Scene/RootSceneNode.h" #include"PrimeEngine/Particles/Particles/EnergyParticle.h" #include"PrimeEngine/Scene/PhysicsManager.h" /* namespace stuff */ namespace PE { namespace Components { using namespace PE::Events; PE_IMPLEMENT_CLASS1(ParticleManager, SceneNode); //*****************************// //** STATIC MEMBER VARIABLES **// //*****************************// Handle ParticleManager::s_myHandle; int ParticleManager::NumEmittersSpawned = 0; int ParticleManager::MaxNumEmitters = 2000; //***************************// //** SINGLETON CONSTRUCTOR **// //***************************// void ParticleManager::Construct(PE::GameContext &context, PE::MemoryArena arena) { Handle handle("ParticleManager", sizeof(ParticleManager)); ParticleManager* pParticleManager = new(handle) ParticleManager(context, arena, handle); pParticleManager->addDefaultComponents(); SetInstanceHandle(handle); RootSceneNode::Instance()->addComponent(handle); } ParticleManager::ParticleManager(PE::GameContext &context, PE::MemoryArena arena, Handle hMyself) : Component(context, arena, hMyself) { } void ParticleManager::addDefaultComponents() { Component::addDefaultComponents(); m_hParticleEmitters.constructFromCapacity(MaxNumEmitters); //@todo make allocation for array more dynamic m_DeactivatingEmitterIndices.constructFromCapacity(MaxNumEmitters); m_hDeactivatingParticleEmitters.constructFromCapacity(MaxNumEmitters); PE_REGISTER_EVENT_HANDLER(Events::Event_PRE_GATHER_DRAWCALLS, ParticleEmitter::do_PRE_GATHER_DRAWCALLS); PE_REGISTER_EVENT_HANDLER(Events::Event_UPDATE, ParticleManager::do_UPDATE); } //*************// //** UTILITY **// //*************// bool ParticleManager::DoesExist(Handle hEmitter) { return m_hParticleEmitters.isInArray(hEmitter); //Note, this onlf checks if the emitter handle is valid, not if it is an act } //************// //** EVENTS **// //************// void ParticleManager::do_UPDATE(PE::Events::Event *pEvt) { PE::Events::Event_UPDATE *pRealEvt = (PE::Events::Event_UPDATE *)(pEvt); float frameTime = pRealEvt->m_frameTime; Update(frameTime); } void ParticleManager::do_PRE_GATHER_DRAWCALLS(Events::Event *pEvt) { } //************// //** UPDATE **// //************// void ParticleManager::Update(float FrameTime) { for (int i = 0; i < m_hParticleEmitters.m_size; i++) { Handle PEhandle = m_hParticleEmitters[i]; if ( PEhandle.isValid() ) { ParticleEmitter* particleEmitter = m_hParticleEmitters[i].getObject<ParticleEmitter>(); Vector3 position=particleEmitter->m_base.getPos(); if(position.m_y<0 && particleEmitter->EmitterVelocity.length()!=0) { particleEmitter->EmitterVelocity=Vector3(0,0,0); particleEmitter->EmissionsPerSecond=0; DeactivateEmitter(PEhandle); } for(int count=0;count<PhysicsManager::Instance()->top;count++) { SceneNode *P1 = PhysicsManager::Instance()->PC[count]->SN; Vector3 Length=position-P1->m_base.getPos(); if(Length.length()<P1->radius && !P1->m_isplayer) { particleEmitter->EmitterVelocity=Vector3(0,0,0); particleEmitter->EmissionsPerSecond=0; DeactivateEmitter(PEhandle); } } if ( particleEmitter->EmitterTimeLived >= particleEmitter->EmitterLifetime ) { //m_DeactivatingEmitterIndices.add(i); DeactivateEmitter(PEhandle); } } } //set up deactivating emitters int numDeactivatingIndices = m_DeactivatingEmitterIndices.m_size; for (int index = numDeactivatingIndices-1; index >= 0; index--) { PrimitiveTypes::Int32 indexOfInactiveEmitter = m_DeactivatingEmitterIndices[index]; DeactivateEmitter(m_hParticleEmitters[index]); } m_DeactivatingEmitterIndices.clear(); //if emitter is done deactivating kill it, else draw int NumDeactivatingParticleEmitters = m_hDeactivatingParticleEmitters.m_size; for ( int i = 0; i < NumDeactivatingParticleEmitters; ++i) { Handle hDeactivatingParticleEmitter = m_hDeactivatingParticleEmitters[i]; ParticleEmitter* pDeactivatingParticleEmitter = hDeactivatingParticleEmitter.getObject<ParticleEmitter>(); bool bHasActiveParticles = (pDeactivatingParticleEmitter->GetNumActiveParticles() > 0 ); if (!bHasActiveParticles) { m_hDeactivatingParticleEmitters.removeUnordered(i); NumDeactivatingParticleEmitters = m_hDeactivatingParticleEmitters.m_size; removeComponent(hDeactivatingParticleEmitter); pDeactivatingParticleEmitter->KillEmitter(); } } } void ParticleManager::PostPreDraw(int &ThreadOwnershipMask) { // For each emmitter I need to call their PostPreDraw so they can update their GPU buffers // since only the cpu buffers have been updated int NumActiveParticleEmitters = m_hParticleEmitters.m_size; for ( int i = 0; i < NumActiveParticleEmitters; ++i) { Handle hParticleEmitter = m_hParticleEmitters[i]; ParticleEmitter* pParticleEmitter = hParticleEmitter.getObject<ParticleEmitter>(); pParticleEmitter->PostPreDraw(ThreadOwnershipMask); } // we also need to finish drawing particles for the deactivating emitters int NumDeactivatingParticleEmitters = m_hDeactivatingParticleEmitters.m_size; for ( int i = 0; i < NumDeactivatingParticleEmitters; ++i) { Handle hDeactivatingParticleEmitter = m_hDeactivatingParticleEmitters[i]; ParticleEmitter* pParticleEmitter = hDeactivatingParticleEmitter.getObject<ParticleEmitter>(); pParticleEmitter->PostPreDraw(ThreadOwnershipMask); } } //************************// //** EMITTER MANAGEMENT **// //************************// void ParticleManager::AddEmitter(ParticleEmitter& particleEmitter) { Handle hPE = particleEmitter.GetHandle(); bool bEmitterAlredyAdded = DoesExist(hPE); PEASSERT(bEmitterAlredyAdded, "ERROR: YOU ARE TRYING TO ADD AN EMITTER THAT HAS ALREADY BEEN ADDED"); particleEmitter.SetEmitterID(NumEmittersSpawned++); addComponent(hPE); m_hParticleEmitters.add(hPE); } bool ParticleManager::DeactivateEmitter(const Handle& EmitterHandle) { //Here we are removeing the particle emitter from the manager. It still exists in memory tho. int index = m_hParticleEmitters.indexOf(EmitterHandle); if(index>0) { m_hParticleEmitters.removeUnordered(index); m_hDeactivatingParticleEmitters.add(EmitterHandle); Handle h = EmitterHandle; ParticleEmitter* pPE = h.getObject<ParticleEmitter>(); pPE->DeactivateEmitter(); } //now also remove it as a comportent return true; } };/* end namespace Components */ };/* end namespace PE */
[ "shreyank@usc.edu" ]
shreyank@usc.edu
63b8490e1e030f72e809b422e59ee98b2f65adbc
55d127a1f772eb40fa7526926d0dbb4f12ef8582
/Environment.h
d780eebfae1eb4947806d2ec65eb1225e1c4045e
[]
no_license
riroan/GridWorld
801d230862a4ee1af4ad18cad402b35a7c7b2920
bd397598f7fb03407b6259dafd5b81074df19d68
refs/heads/master
2021-07-12T16:03:54.364973
2020-08-02T14:05:38
2020-08-02T14:05:38
172,125,948
0
0
null
null
null
null
UTF-8
C++
false
false
1,092
h
#pragma once #define UP 0 #define RIGHT 1 #define DOWN 2 #define LEFT 3 #define DISCOUNT 0.9 #define EPSILON_DISCOUNT 0.999 #define EPSILON_MIN 0.1 class Q { public: double arr[4]; Q() { for (int i = 0; i < 4; i++) arr[i] = 0.0; } double& operator[](const int& i) { return arr[i]; } double getMax() { double ret = arr[0]; for (int i = 1; i < 4; i++) if (ret < arr[i]) ret = arr[i]; return ret; } int getMaxIx() { double max = arr[0]; int ix = 0; for (int i = 1; i < 4; i++) if (max < arr[i]) { max = arr[i]; ix = i; } return ix; } }; class Environment { public: int row; int col; int state; int win_cnt; Q ** score; int ** board; double epsilon; int num_obstacle; Environment(const int& _row, const int& _col, const int& _num_obstacle); void printQ(); void draw(); void move(); void update(const int& action); int getNextState(const int& action); int getRandomAction(); int getAction(); bool isValid(const int& action); bool isOver(); };
[ "noreply@github.com" ]
noreply@github.com
31cdc6c81c658b1d058230a1d656ca8d63932f0a
a3696f7f62511521c974ebb654cdf0162d28c4e6
/carDemo/src_cpp/src/Experiment/Simulation/ai/GeneticAlgorithm.cpp
553b299b37346e7c37236256f8496aeeb5a162aa
[]
no_license
templeblock/geneticAlgorithm_experiment
de4aef6fec14e82483886769b440b26ab020cb2c
856042364afad278663937b5a86d210fa1202fb0
refs/heads/master
2021-06-18T06:27:43.911471
2017-05-19T19:16:36
2017-05-19T19:16:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,162
cpp
#include "GeneticAlgorithm.hpp" #include "../utils/TraceLogger.hpp" #include "../utils/randomiser.hpp" #include <ctime> // <- time GeneticAlgorithm::GeneticAlgorithm() : m_current_id(1), m_current_generation(1), m_best_fitness(0.0f), m_is_a_great_generation(false) { my_srand( time(NULL) ); } void GeneticAlgorithm::init(NeuralNetworkTopology& NNTopology) { m_pNNTopology = &NNTopology; this->generateRandomPopulation(); } void GeneticAlgorithm::generateRandomPopulation() { // reset the genomes m_genomes.resize(100); for (unsigned int i = 0; i < m_genomes.size(); ++i) { t_genome& genome = m_genomes[i]; genome.m_index = i; genome.m_id = m_current_id++; genome.m_fitness = 0.0f; genome.m_weights.resize( m_pNNTopology->getTotalWeights() ); for (float& weight : genome.m_weights) weight = randomClamped(); } m_NNetworks.reserve( m_genomes.size() ); for (unsigned int i = 0; i < m_genomes.size(); ++i) { m_NNetworks.push_back( NeuralNetwork(*m_pNNTopology) ); m_NNetworks[i].setWeights( m_genomes[i].m_weights ); } m_current_generation = 1; m_best_fitness = 0.0f; m_alpha_genome.m_index = -1; m_alpha_genome.m_id = -1; m_alpha_genome.m_fitness = 0.0f; } void GeneticAlgorithm::BreedPopulation() { if (m_genomes.empty()) return; std::vector<t_genome> bestGenomes; getBestGenomes(10, bestGenomes); std::vector<t_genome> children; children.reserve( m_genomes.size() ); if (m_best_fitness < bestGenomes[0].m_fitness) { m_best_fitness = bestGenomes[0].m_fitness; D_MYLOG("m_current_generation=" << m_current_generation << std::fixed << ", m_best_fitness=" << m_best_fitness); m_is_a_great_generation = true; } else { m_is_a_great_generation = false; } unsigned int current_index = 0; if (m_best_fitness > m_alpha_genome.m_fitness) { m_alpha_genome = bestGenomes[0]; } else { t_genome bestDude; bestDude.m_fitness = 0.0f; bestDude.m_id = m_alpha_genome.m_id; bestDude.m_weights = m_alpha_genome.m_weights; bestDude.m_index = current_index++; mutate(bestDude); children.push_back(bestDude); } { // Carry on the best dude. t_genome bestDude; bestDude.m_fitness = 0.0f; bestDude.m_id = bestGenomes[0].m_id; bestDude.m_weights = bestGenomes[0].m_weights; bestDude.m_index = current_index++; mutate(bestDude); children.push_back(bestDude); } // breed best genomes for (unsigned int i = 0; i < bestGenomes.size(); ++i) for (unsigned int j = i+1; j < bestGenomes.size(); ++j) { t_genome baby1, baby2; CrossBreed(bestGenomes[i], bestGenomes[j], baby1, baby2); mutate(baby1); mutate(baby2); baby1.m_index = current_index++; baby2.m_index = current_index++; if (children.size() < children.capacity()) children.push_back(baby1); if (children.size() < children.capacity()) children.push_back(baby2); } // For the remainding n population, add some random kiddies. int remainingChildren = static_cast<int>(m_genomes.size() - children.size()); for (int i = 0; i < remainingChildren; i++) { t_genome genome; genome.m_id = m_current_id++; genome.m_fitness = 0.0f; genome.m_weights.resize( m_pNNTopology->getTotalWeights() ); for (float& weight : genome.m_weights) weight = randomClamped(); genome.m_index = current_index++; children.push_back( genome ); } m_genomes = children; ++m_current_generation; for (unsigned int i = 0; i < m_genomes.size(); ++i) m_NNetworks[i].setWeights( m_genomes[i].m_weights ); } void GeneticAlgorithm::getBestGenomes(unsigned int totalAsked, std::vector<t_genome>& out) const { // realistic total outputed genomes totalAsked = std::min<unsigned int>(m_genomes.size(), totalAsked); out.clear(); while (out.size() < totalAsked) { float bestFitness = 0; int bestIndex = -1; for (unsigned int i = 0; i < m_genomes.size(); i++) if (m_genomes[i].m_fitness > bestFitness) { bool isUsed = false; // no duplicate for (unsigned int j = 0; j < out.size(); j++) if (out[j].m_id == m_genomes[i].m_id) { isUsed = true; break; } if (isUsed) continue; bestIndex = i; bestFitness = m_genomes[bestIndex].m_fitness; } if (bestIndex != -1) out.push_back( m_genomes[bestIndex] ); } } void GeneticAlgorithm::CrossBreed(const t_genome& g1, const t_genome& g2, t_genome& baby1, t_genome& baby2) { unsigned int totalWeights = g1.m_weights.size(); unsigned int crossover = std::min(randomFloat(), 0.99f) * totalWeights; baby1.m_id = m_current_id++; baby1.m_weights.resize(totalWeights); baby2.m_id = m_current_id++; baby2.m_weights.resize(totalWeights); for (unsigned int i = 0; i < crossover; i++) { baby1.m_weights[i] = g1.m_weights[i]; baby2.m_weights[i] = g2.m_weights[i]; } for (unsigned int i = crossover; i < totalWeights; i++) { baby1.m_weights[i] = g2.m_weights[i]; baby2.m_weights[i] = g1.m_weights[i]; } } void GeneticAlgorithm::mutate(t_genome& genome) const { int total_mutated = 0; for (float& weight : genome.m_weights) if (randomFloat() < 0.1f) { weight += (randomClamped() * 0.2f); ++total_mutated; } }
[ "guillaume.bouchet@epitech.eu" ]
guillaume.bouchet@epitech.eu
e1a4e64e90cef347a61a32564db67c0e06029faf
80a1106c3c7be985a83adffc6a680c783631dde7
/algorithm/introAlgorithm/c++-implmentation/sort/insertion_sort.cc
900634c5bd2051999a08eceb04624631448da58d
[]
no_license
djndl1/CSNotes
d2bf220e4d97dcdbab041eac3b7ed4d3ae2b12b3
dbdfc4ae315e5a9ca95174d263dd03a02d5be046
refs/heads/master
2023-08-31T11:14:26.014029
2023-08-28T12:33:53
2023-08-28T12:33:53
191,334,252
0
0
null
null
null
null
UTF-8
C++
false
false
661
cc
#include <iostream> #include <vector> using std::vector; using std::cout; using std::cin; using std::endl; void insertion_sort(vector<int>& A) { int key, i; for (size_t j = 1 ; j < A.size(); ++j) { key = A[j]; i = j - 1; while ((i >= 0) and (A[i] > key)) { A[i+1] = A[i]; i--; } A[i+1] = key; } } void insertion_sort_nonincreasing(vector<int>& A) { int key, i; for (size_t j = 1 ; j < A.size(); ++j) { key = A[j]; i = j - 1; while ((i >= 0) and (A[i] < key)) { A[i+1] = A[i]; i--; } A[i+1] = key; } }
[ "djndl1@gmail.com" ]
djndl1@gmail.com
17c7a66f15eeaccabe2ebb8dfec821e3972a4132
1f4c6eb3617316db4c0b0c8d30e92aa81bebf6cf
/deprecated/amx/amxcback.cpp
bcef82d39de58af21caf98c2fbe479aa6d674378
[]
no_license
Flameeyes/hypnos
ff2c2b0b96c4884d6b87915d5740ded46672acd8
57538e8c4a194168fae42b3b19319657b2e52084
refs/heads/master
2021-01-18T14:49:10.283407
2005-01-02T22:48:07
2005-01-02T22:48:07
2,572,682
1
0
null
null
null
null
UTF-8
C++
false
false
3,909
cpp
/*! *********************************************************************************** * file : amxcback.cpp * * Project : Nox-Wizard * * Author : * * Purpose : Implementation of Functions for AMX Callbacks and AMX Events * *********************************************************************************** *//* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- || NoX-Wizard UO Server Emulator (NXW) [http://www.noxwizard.com] || || || || This software is free software released under GPL2 license. || || You can find detailed license information in nox-wizard.cpp file. || || || || For any question post to NoX-Wizard forums or mail staff@noxwizard.com || -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- CHANGELOG: ----------------------------------------------------------------------------- DATE DEVELOPER DESCRIPTION ----------------------------------------------------------------------------- *********************************************************************************** */ #include "common_libs.h" #include "amxcback.h" #include "sndpkg.h" #include "itemid.h" #include "client.h" #include "network.h" extern int g_nCurrentSocket; extern int g_nTriggeredItem; extern int g_nTriggerType; #define MAXSTRLEN 50 static int g_nType; /*! \brief Calls an amx event handler \author Xanathar \return cell \param param1 parameter passed to amx callback fn \param param2 parameter passed to amx callback fm \param param3 parameter passed to amx callback fn \param param4 parameter passed to amx callback fn */ cell AmxEvent::Call (int param1, int param2, int param3, int param4) { g_nCurrentSocket = g_nTriggeredItem = g_nTriggerType = -1; if (valid) return AmxFunction::g_prgOverride->CallFn(function, param1, param2, param3, param4); else return -1; } /*! \brief Gets the fn name of an handler \author Xanathar \return char* */ char* AmxEvent::getFuncName (void) { return funcname; } /*! \brief constructor for event handlers \author Xanathar \param fnname function name \param dyn is dynamic ? (dynamic means : saved on worldsave) */ AmxEvent::AmxEvent(char *fnname, bool dyn) { dynamic = dyn; funcname = new char[strlen(fnname)+3]; strcpy(funcname, fnname); function = AmxFunction::g_prgOverride->getFnOrdinal(funcname); if (function <= -3) valid = false; else valid = true; } /*! \brief quick constructor for dynamics \author Xanathar \param funidx index to amx function */ AmxEvent::AmxEvent(int funidx) { dynamic = true; funcname = new char[strlen("%Dynamic-Callback%")+3]; strcpy(funcname, "%Dynamic-Callback%"); function = funidx; if (function <= -3) valid = false; else valid = true; } static AmxEvent *HashQueue[256]; static AmxEvent *Queue = NULL; /*! \brief initializes to nulls the hash queues for amx events \author Xanathar */ void initAmxEvents(void) { ConOut("Initializing event callback hash queue..."); for (int i=0; i<256; i++) HashQueue[i] = NULL; ConOut("[DONE]"); } /*! \brief creates a new amx event or load a previous equivalent one \author Xanathar \return AmxEvent* \param funcname name of function \param dynamic dynamic/static status */ AmxEvent* newAmxEvent(char *funcname, bool dynamic) { int i; int hash = 0; int ln = strlen(funcname); for (i=0; i<ln; i++) hash += funcname[i]; hash &= 0xFF; AmxEvent *p = HashQueue[hash]; while(p!=NULL) { if (!strcmp(p->getFuncName(), funcname)){ if (p->shouldBeSaved()!=dynamic) return p; } p = p->hashNext; } p = new AmxEvent(funcname, dynamic); p->listNext = Queue; Queue = p; p->hashNext = HashQueue[hash]; HashQueue[hash] = p; return p; }
[ "flameeyes@flameeyes.eu" ]
flameeyes@flameeyes.eu
8c1a76cf023e554cbd6cca2c823531db0347dd23
b14917f420efcfd0ac27d7bf0f593ff44e732703
/Joint Project/playGame.h
633467599bfe89caf9f9e59800efe5d2237f953e
[]
no_license
MichaelBridgette/Overhead-Racing-Game
67ea4761d1592b7f5092ef150a3167c694eb99a3
0e8bc8490218ab399b4e41be5b54c31fd8c4b80e
refs/heads/master
2021-07-12T07:31:16.616161
2017-10-17T09:05:09
2017-10-17T09:05:09
107,243,495
0
0
null
null
null
null
UTF-8
C++
false
false
966
h
#pragma once /// <summary> /// @mainpage Joint Project - 2D racing game. /// @Author Dylan Murphy, Sean Regan, Micheal Bridgette, David O'Gorman /// @Version 1.0 /// @brief A 2D racing game. /// </summary> #ifndef PLAYGAME #define PLAYGAME // classs for the menu screen class Game; #include<SFML\Graphics.hpp> #include"Button.h" #include"Widget.h" #include "GUI.h" #include"Game.h" class playGame { public: playGame(Game &game); ~playGame(); void render(sf::RenderWindow & window); void update(); private: GUI m_gui; Label *m_title; Button *m_mapSelection; Button *moveLeft; Button *m_rectB; Button *moveRight; Button *moveDowner; Button *moveDownest; Button *goBack; int m_currentSelect; //void setRectColor(sf::Color color); sf::RectangleShape m_rect; bool maptrue = false; sf::Sprite dayMapSprite; sf::Sprite nightMapSprite; Game *m_game; void goToMenu(); void goToSpecs(); void goToSpecsMap2(); }; #endif // !PLAYGAME
[ "c00205948@itcarlow.ie" ]
c00205948@itcarlow.ie
010734c2f7181cdbf801cfc49e1352c479354b0c
069e28d27ec025b452a51b1ec36781bd9d23e88f
/tess-two/jni/com_googlecode_tesseract_android/tessbaseapi.cpp
f8b519c22b3ce172049e170506348955d34e8bc6
[ "Apache-2.0" ]
permissive
linhdq/CapstoneProjectAndroid
9e11d85d93b2fc5ab7eec9bc65ca020f8f5c2ef7
2ef43dca7079e2c2c683574043cc00f732bb95ea
refs/heads/master
2020-12-02T09:11:31.502202
2017-07-09T20:41:15
2017-07-09T20:41:15
96,710,082
0
0
null
null
null
null
UTF-8
C++
false
false
31,206
cpp
/* * Copyright 2011, Google Inc. * Copyright 2011, Robert Theis * * 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 <stdio.h> #include <malloc.h> #include "android/bitmap.h" #include "common.h" #include "baseapi.h" #include "errcode.h" #include "ocrclass.h" #include "allheaders.h" #include <sstream> #include <fstream> #include <iostream> static jfieldID field_mNativeData; static jmethodID method_onProgressValues; struct native_data_t { tesseract::TessBaseAPI api; PIX *pix; void *data; bool debug; Box* currentTextBox = NULL; l_int32 lastProgress; bool cancel_ocr; JNIEnv *cachedEnv; jobject cachedObject; bool isStateValid() { if (cancel_ocr == false && cachedEnv != NULL) { return true; } else { LOGI("state is cancelled"); return false; } } void setTextBoundaries(l_uint32 x, l_uint32 y, l_uint32 w, l_uint32 h){ boxSetGeometry(currentTextBox,x,y,w,h); } void initStateVariables(JNIEnv *env, jobject object) { cancel_ocr = false; cachedEnv = env; cachedObject = env->NewGlobalRef(object); lastProgress = 0; //boxSetGeometry(currentTextBox,0,0,0,0); } void resetStateVariables() { cancel_ocr = false; if (cachedEnv != NULL) { cachedEnv->DeleteGlobalRef(cachedObject); cachedEnv = NULL; } lastProgress = 0; boxSetGeometry(currentTextBox,0,0,0,0); } native_data_t() { currentTextBox = boxCreate(0,0,0,0); lastProgress = 0; pix = NULL; data = NULL; debug = false; cachedEnv = NULL; cachedObject = NULL; cancel_ocr = false; } ~native_data_t(){ boxDestroy(&currentTextBox); } }; /** * callback for tesseracts monitor */ bool cancelFunc(void* cancel_this, int words) { native_data_t *nat = (native_data_t*)cancel_this; return nat->cancel_ocr; } /** * callback for tesseracts monitor */ bool progressJavaCallback(void* progress_this,int progress, int left, int right, int top, int bottom) { native_data_t *nat = (native_data_t*)progress_this; if (nat->isStateValid() && nat->currentTextBox != NULL) { if (progress > nat->lastProgress || left != 0 || right != 0 || top != 0 || bottom != 0) { LOGI("state changed"); int x, y, w, h; boxGetGeometry(nat->currentTextBox, &x, &y, &w, &h); nat->cachedEnv->CallVoidMethod(nat->cachedObject, method_onProgressValues, progress, (jint) left, (jint) right, (jint) top, (jint) bottom, (jint) x, (jint) (x + w), (jint) y, (jint) (y + h)); nat->lastProgress = progress; } } return true; } static inline native_data_t * get_native_data(JNIEnv *env, jobject object) { return (native_data_t *) (env->GetLongField(object, field_mNativeData)); } #ifdef __cplusplus extern "C" { #endif jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv *env; if (vm->GetEnv((void**) &env, JNI_VERSION_1_6) != JNI_OK) { LOGE("Failed to get the environment using GetEnv()"); return -1; } return JNI_VERSION_1_6; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeClassInit(JNIEnv* env, jclass clazz) { field_mNativeData = env->GetFieldID(clazz, "mNativeData", "J"); method_onProgressValues = env->GetMethodID(clazz, "onProgressValues", "(IIIIIIIII)V"); } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeConstruct(JNIEnv* env, jobject object) { native_data_t *nat = new native_data_t; if (nat == NULL) { LOGE("%s: out of memory!", __FUNCTION__); return; } env->SetLongField(object, field_mNativeData, (jlong) nat); } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeFinalize(JNIEnv* env, jobject object) { native_data_t *nat = get_native_data(env, object); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = NULL; nat->pix = NULL; if (nat != NULL) delete nat; } jboolean Java_com_googlecode_tesseract_android_TessBaseAPI_nativeInit(JNIEnv *env, jobject thiz, jstring dir, jstring lang) { native_data_t *nat = get_native_data(env, thiz); const char *c_dir = env->GetStringUTFChars(dir, NULL); const char *c_lang = env->GetStringUTFChars(lang, NULL); jboolean res = JNI_TRUE; if (nat->api.Init(c_dir, c_lang)) { LOGE("Could not initialize Tesseract API with language=%s!", c_lang); res = JNI_FALSE; } else { LOGI("Initialized Tesseract API with language=%s", c_lang); } env->ReleaseStringUTFChars(dir, c_dir); env->ReleaseStringUTFChars(lang, c_lang); return res; } jboolean Java_com_googlecode_tesseract_android_TessBaseAPI_nativeInitOem(JNIEnv *env, jobject thiz, jstring dir, jstring lang, jint mode) { native_data_t *nat = get_native_data(env, thiz); const char *c_dir = env->GetStringUTFChars(dir, NULL); const char *c_lang = env->GetStringUTFChars(lang, NULL); jboolean res = JNI_TRUE; if (nat->api.Init(c_dir, c_lang, (tesseract::OcrEngineMode) mode)) { LOGE("Could not initialize Tesseract API with language=%s!", c_lang); res = JNI_FALSE; } else { LOGI("Initialized Tesseract API with language=%s", c_lang); } env->ReleaseStringUTFChars(dir, c_dir); env->ReleaseStringUTFChars(lang, c_lang); return res; } jstring Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetInitLanguagesAsString(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); const char *text = nat->api.GetInitLanguagesAsString(); jstring result = env->NewStringUTF(text); return result; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetImageBytes(JNIEnv *env, jobject thiz, jbyteArray data, jint width, jint height, jint bpp, jint bpl) { jbyte *data_array = env->GetByteArrayElements(data, NULL); int count = env->GetArrayLength(data); unsigned char* imagedata = (unsigned char *) malloc(count * sizeof(unsigned char)); // This is painfully slow, but necessary because we don't know // how many bits the JVM might be using to represent a byte for (int i = 0; i < count; i++) { imagedata[i] = (unsigned char) data_array[i]; } env->ReleaseByteArrayElements(data, data_array, JNI_ABORT); native_data_t *nat = get_native_data(env, thiz); nat->api.SetImage(imagedata, (int) width, (int) height, (int) bpp, (int) bpl); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = imagedata; nat->pix = NULL; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetImagePix(JNIEnv *env, jobject thiz, jlong nativePix) { PIX *pixs = (PIX *) nativePix; PIX *pixd = pixClone(pixs); native_data_t *nat = get_native_data(env, thiz); if(pixd){ l_int32 width = pixGetWidth(pixd); l_int32 height = pixGetHeight(pixd); nat->setTextBoundaries(0,0,width,height); LOGI("setting ocr box %i,%i",width,height); } nat->api.SetImage(pixd); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = NULL; nat->pix = pixd; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetRectangle(JNIEnv *env, jobject thiz, jint left, jint top, jint width, jint height) { native_data_t *nat = get_native_data(env, thiz); nat->setTextBoundaries(left,top,width, height); nat->api.SetRectangle(left, top, width, height); } jstring Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetUTF8Text(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); char *text = nat->api.GetUTF8Text(); jstring result = env->NewStringUTF(text); free(text); return result; } std::string GetHTMLText(tesseract::ResultIterator* res_it, const float minConfidenceToShowColor) { int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1; std::ostringstream html_str; bool isItalic = false; bool para_open = false; for (; !res_it->Empty(tesseract::RIL_BLOCK); wcnt++) { if (res_it->Empty(tesseract::RIL_WORD)) { res_it->Next(tesseract::RIL_WORD); continue; } if (res_it->IsAtBeginningOf(tesseract::RIL_PARA)) { if (para_open) { html_str << "</p>"; pcnt++; } html_str << "<p>"; para_open = true; } if (res_it->IsAtBeginningOf(tesseract::RIL_TEXTLINE)) { html_str << "<br>"; } // Now, process the word... const char *font_name; bool bold, italic, underlined, monospace, serif, smallcaps; int pointsize, font_id; font_name = res_it->WordFontAttributes(&bold, &italic, &underlined, &monospace, &serif, &smallcaps, &pointsize, &font_id); float confidence = res_it->Confidence(tesseract::RIL_WORD); bool addConfidence = false; /*if (italic && !isItalic) { html_str << "<strong>"; isItalic = true; } else if (!italic && isItalic) { html_str << "</strong>"; isItalic = false; }*/ char* word = res_it->GetUTF8Text(tesseract::RIL_WORD); bool isSpace = strcmp(word, " ") == 0; delete[] word; if (confidence < minConfidenceToShowColor && !isSpace) { addConfidence = true; html_str << "<font conf='"; html_str << (int) confidence; html_str << "' color='#DE2222'>"; } bool isHyphen = false; do { const char *grapheme = res_it->GetUTF8Text(tesseract::RIL_SYMBOL); if(isHyphen){ html_str << "-"; } isHyphen = strcmp(grapheme, "—") == 0 || strcmp(grapheme, "—") == 0 || strcmp(grapheme, "-") == 0; if (grapheme && grapheme[0] != 0 && !isHyphen) { if (grapheme[1] == 0) { switch (grapheme[0]) { case '<': html_str << "&lt;"; break; case '>': html_str << "&gt;"; break; case '&': html_str << "&amp;"; break; case '"': html_str << "&quot;"; break; case '\'': html_str << "&#39;"; break; default: html_str << grapheme; break; } } else { html_str << grapheme; } } delete[] grapheme; res_it->Next(tesseract::RIL_SYMBOL); } while (!res_it->Empty(tesseract::RIL_BLOCK) && !res_it->IsAtBeginningOf(tesseract::RIL_WORD)); if (addConfidence == true) { html_str << "</font>"; } if(!isHyphen){ html_str << " "; } } /*if (isItalic) { html_str << "</strong>"; }*/ if (para_open) { html_str << "</p>"; pcnt++; } return html_str.str(); } std::string GetXMLText(tesseract::ResultIterator* res_it, const float minConfidenceToShowColor) { int lcnt = 1, bcnt = 1, pcnt = 1, wcnt = 1; std::ostringstream xml_str; bool isItalic = false; bool line_open = false; for (; !res_it->Empty(tesseract::RIL_BLOCK); wcnt++) { if (res_it->Empty(tesseract::RIL_WORD)) { res_it->Next(tesseract::RIL_WORD); continue; } // Now, process the word... const char *font_name; bool bold, italic, underlined, monospace, serif, smallcaps; int pointsize, font_id; font_name = res_it->WordFontAttributes(&bold, &italic, &underlined, &monospace, &serif, &smallcaps, &pointsize, &font_id); if (res_it->IsAtBeginningOf(tesseract::RIL_TEXTLINE)) { if (line_open) { xml_str << "</text>"; xml_str << "</line>"; line_open = false; pcnt++; } xml_str << "<line>"; xml_str << "<font_size>"; xml_str << pointsize; xml_str << "</font_size>"; xml_str << "<text>"; line_open = true; } float confidence = res_it->Confidence(tesseract::RIL_WORD); bool addConfidence = false; char* word = res_it->GetUTF8Text(tesseract::RIL_WORD); bool isSpace = strcmp(word, " ") == 0; delete[] word; bool isHyphen = false; do { const char *grapheme = res_it->GetUTF8Text(tesseract::RIL_SYMBOL); if(isHyphen){ xml_str << "-"; } isHyphen = strcmp(grapheme, "—") == 0 || strcmp(grapheme, "—") == 0 || strcmp(grapheme, "-") == 0; if (grapheme && grapheme[0] != 0 && !isHyphen) { if (grapheme[1] == 0) { switch (grapheme[0]) { case '<': xml_str << "&lt;"; break; case '>': xml_str << "&gt;"; break; case '&': xml_str << "&amp;"; break; case '"': xml_str << "&quot;"; break; case '\'': xml_str << "&#39;"; break; default: xml_str << grapheme; break; } } else { xml_str << grapheme; } } delete[] grapheme; res_it->Next(tesseract::RIL_SYMBOL); } while (!res_it->Empty(tesseract::RIL_BLOCK) && !res_it->IsAtBeginningOf(tesseract::RIL_WORD)); if(!isHyphen){ xml_str << " "; } } if (line_open) { xml_str << "</text>"; xml_str << "</line>"; line_open = false; pcnt++; } return xml_str.str(); } jstring Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetHtmlText(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); tesseract::OcrEngineMode mode = nat->api.oem(); int redThreshhold = 75; if(mode==tesseract::OcrEngineMode::OEM_CUBE_ONLY || mode==tesseract::OcrEngineMode::OEM_TESSERACT_CUBE_COMBINED){ redThreshhold = 35; } tesseract::ResultIterator* res_it = nat->api.GetIterator(); std::string utf8text = GetXMLText(res_it, redThreshhold); jstring result = env->NewStringUTF(utf8text.c_str()); return result; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeStop(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); // stop by setting a flag thats used by the monitor nat->resetStateVariables(); nat->cancel_ocr = true; } jint Java_com_googlecode_tesseract_android_TessBaseAPI_nativeMeanConfidence(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); return (jint) nat->api.MeanTextConf(); } jintArray Java_com_googlecode_tesseract_android_TessBaseAPI_nativeWordConfidences(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); int *confs = nat->api.AllWordConfidences(); if (confs == NULL) { LOGE("Could not get word-confidence values!"); return NULL; } int len, *trav; for (len = 0, trav = confs; *trav != -1; trav++, len++) ; LOG_ASSERT((confs != NULL), "Confidence array has %d elements", len); jintArray ret = env->NewIntArray(len); LOG_ASSERT((ret != NULL), "Could not create Java confidence array!"); env->SetIntArrayRegion(ret, 0, len, confs); delete[] confs; return ret; } jboolean Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetVariable(JNIEnv *env, jobject thiz, jstring var, jstring value) { native_data_t *nat = get_native_data(env, thiz); const char *c_var = env->GetStringUTFChars(var, NULL); const char *c_value = env->GetStringUTFChars(value, NULL); jboolean set = nat->api.SetVariable(c_var, c_value) ? JNI_TRUE : JNI_FALSE; env->ReleaseStringUTFChars(var, c_var); env->ReleaseStringUTFChars(value, c_value); return set; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeClear(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); nat->api.Clear(); // Call between pages or documents etc to free up memory and forget adaptive data. nat->api.ClearAdaptiveClassifier(); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = NULL; nat->pix = NULL; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeEnd(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); nat->api.End(); // Since Tesseract doesn't take ownership of the memory, we keep a pointer in the native // code struct. We need to free that pointer when we release our instance of Tesseract or // attempt to set a new image using one of the nativeSet* methods. if (nat->data != NULL) free(nat->data); else if (nat->pix != NULL) pixDestroy(&nat->pix); nat->data = NULL; nat->pix = NULL; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetDebug(JNIEnv *env, jobject thiz, jboolean debug) { native_data_t *nat = get_native_data(env, thiz); nat->debug = (debug == JNI_TRUE) ? TRUE : FALSE; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetPageSegMode(JNIEnv *env, jobject thiz, jint mode) { native_data_t *nat = get_native_data(env, thiz); nat->api.SetPageSegMode((tesseract::PageSegMode) mode); } jlong Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetThresholdedImage(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); PIX *pix = nat->api.GetThresholdedImage(); return (jlong) pix; } jlong Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetRegions(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz);; PIXA *pixa = NULL; BOXA *boxa; boxa = nat->api.GetRegions(&pixa); boxaDestroy(&boxa); return reinterpret_cast<jlong>(pixa); } jlong Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetTextlines(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz);; PIXA *pixa = NULL; BOXA *boxa; boxa = nat->api.GetTextlines(&pixa, NULL); boxaDestroy(&boxa); return reinterpret_cast<jlong>(pixa); } jlong Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetStrips(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz);; PIXA *pixa = NULL; BOXA *boxa; boxa = nat->api.GetStrips(&pixa, NULL); boxaDestroy(&boxa); return reinterpret_cast<jlong>(pixa); } jlong Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetWords(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz);; PIXA *pixa = NULL; BOXA *boxa; boxa = nat->api.GetWords(&pixa); boxaDestroy(&boxa); return reinterpret_cast<jlong>(pixa); } jlong Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetResultIterator(JNIEnv *env, jobject thiz) { native_data_t *nat = get_native_data(env, thiz); return (jlong) nat->api.GetIterator(); } jstring Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetHOCRText(JNIEnv *env, jobject thiz, jint page) { native_data_t *nat = get_native_data(env, thiz); nat->initStateVariables(env, thiz); ETEXT_DESC monitor; monitor.progress_callback = progressJavaCallback; monitor.cancel = cancelFunc; monitor.cancel_this = nat; monitor.progress_this = nat; char *text = nat->api.GetHOCRText(page,&monitor); jstring result = env->NewStringUTF(text); free(text); nat->resetStateVariables(); return result; } jstring Java_com_googlecode_tesseract_android_TessBaseAPI_nativeGetBoxText(JNIEnv *env, jobject thiz, jint page) { native_data_t *nat = get_native_data(env, thiz); char *text = nat->api.GetBoxText(page); jstring result = env->NewStringUTF(text); free(text); return result; } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetInputName(JNIEnv *env, jobject thiz, jstring name) { native_data_t *nat = get_native_data(env, thiz); const char *c_name = env->GetStringUTFChars(name, NULL); nat->api.SetInputName(c_name); env->ReleaseStringUTFChars(name, c_name); } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeSetOutputName(JNIEnv *env, jobject thiz, jstring name) { native_data_t *nat = get_native_data(env, thiz); const char *c_name = env->GetStringUTFChars(name, NULL); nat->api.SetOutputName(c_name); env->ReleaseStringUTFChars(name, c_name); } void Java_com_googlecode_tesseract_android_TessBaseAPI_nativeReadConfigFile(JNIEnv *env, jobject thiz, jstring fileName) { native_data_t *nat = get_native_data(env, thiz); const char *c_file_name = env->GetStringUTFChars(fileName, NULL); nat->api.ReadConfigFile(c_file_name); env->ReleaseStringUTFChars(fileName, c_file_name); } #ifdef __cplusplus } #endif
[ "linhdqse03570@gmail.com" ]
linhdqse03570@gmail.com
e1e4047e281ee4b5f7260d7427fc90d313a8d59b
f85cfed4ae3c54b5d31b43e10435bb4fc4875d7e
/sc-virt/src/include/llvm/Support/CommandLine.h
70465a0e3fd350aa56b9f5467964bf74eb8ae8c1
[ "NCSA", "MIT" ]
permissive
archercreat/dta-vs-osc
2f495f74e0a67d3672c1fc11ecb812d3bc116210
b39f4d4eb6ffea501025fc3e07622251c2118fe0
refs/heads/main
2023-08-01T01:54:05.925289
2021-09-05T21:00:35
2021-09-05T21:00:35
438,047,267
1
1
MIT
2021-12-13T22:45:20
2021-12-13T22:45:19
null
UTF-8
C++
false
false
63,616
h
//===- llvm/Support/CommandLine.h - Command line handler --------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This class implements a command line argument processor that is useful when // creating a tool. It provides a simple, minimalistic interface that is easily // extensible and supports nonlocal (library) command line options. // // Note that rather than trying to figure out what this code does, you should // read the library documentation located in docs/CommandLine.html or looks at // the many example usages in tools/*/*.cpp // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_COMMANDLINE_H #define LLVM_SUPPORT_COMMANDLINE_H #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ManagedStatic.h" #include <cassert> #include <climits> #include <cstdarg> #include <utility> #include <vector> namespace llvm { class StringSaver; /// cl Namespace - This namespace contains all of the command line option /// processing machinery. It is intentionally a short name to make qualified /// usage concise. namespace cl { //===----------------------------------------------------------------------===// // ParseCommandLineOptions - Command line option processing entry point. // bool ParseCommandLineOptions(int argc, const char *const *argv, const char *Overview = nullptr, bool IgnoreErrors = false); //===----------------------------------------------------------------------===// // ParseEnvironmentOptions - Environment variable option processing alternate // entry point. // void ParseEnvironmentOptions(const char *progName, const char *envvar, const char *Overview = nullptr); ///===---------------------------------------------------------------------===// /// SetVersionPrinter - Override the default (LLVM specific) version printer /// used to print out the version when --version is given /// on the command line. This allows other systems using the /// CommandLine utilities to print their own version string. void SetVersionPrinter(void (*func)()); ///===---------------------------------------------------------------------===// /// AddExtraVersionPrinter - Add an extra printer to use in addition to the /// default one. This can be called multiple times, /// and each time it adds a new function to the list /// which will be called after the basic LLVM version /// printing is complete. Each can then add additional /// information specific to the tool. void AddExtraVersionPrinter(void (*func)()); // PrintOptionValues - Print option values. // With -print-options print the difference between option values and defaults. // With -print-all-options print all option values. // (Currently not perfect, but best-effort.) void PrintOptionValues(); // Forward declaration - AddLiteralOption needs to be up here to make gcc happy. class Option; /// \brief Adds a new option for parsing and provides the option it refers to. /// /// \param O pointer to the option /// \param Name the string name for the option to handle during parsing /// /// Literal options are used by some parsers to register special option values. /// This is how the PassNameParser registers pass names for opt. void AddLiteralOption(Option &O, const char *Name); //===----------------------------------------------------------------------===// // Flags permitted to be passed to command line arguments // enum NumOccurrencesFlag { // Flags for the number of occurrences allowed Optional = 0x00, // Zero or One occurrence ZeroOrMore = 0x01, // Zero or more occurrences allowed Required = 0x02, // One occurrence required OneOrMore = 0x03, // One or more occurrences required // ConsumeAfter - Indicates that this option is fed anything that follows the // last positional argument required by the application (it is an error if // there are zero positional arguments, and a ConsumeAfter option is used). // Thus, for example, all arguments to LLI are processed until a filename is // found. Once a filename is found, all of the succeeding arguments are // passed, unprocessed, to the ConsumeAfter option. // ConsumeAfter = 0x04 }; enum ValueExpected { // Is a value required for the option? // zero reserved for the unspecified value ValueOptional = 0x01, // The value can appear... or not ValueRequired = 0x02, // The value is required to appear! ValueDisallowed = 0x03 // A value may not be specified (for flags) }; enum OptionHidden { // Control whether -help shows this option NotHidden = 0x00, // Option included in -help & -help-hidden Hidden = 0x01, // -help doesn't, but -help-hidden does ReallyHidden = 0x02 // Neither -help nor -help-hidden show this arg }; // Formatting flags - This controls special features that the option might have // that cause it to be parsed differently... // // Prefix - This option allows arguments that are otherwise unrecognized to be // matched by options that are a prefix of the actual value. This is useful for // cases like a linker, where options are typically of the form '-lfoo' or // '-L../../include' where -l or -L are the actual flags. When prefix is // enabled, and used, the value for the flag comes from the suffix of the // argument. // // Grouping - With this option enabled, multiple letter options are allowed to // bunch together with only a single hyphen for the whole group. This allows // emulation of the behavior that ls uses for example: ls -la === ls -l -a // enum FormattingFlags { NormalFormatting = 0x00, // Nothing special Positional = 0x01, // Is a positional argument, no '-' required Prefix = 0x02, // Can this option directly prefix its value? Grouping = 0x03 // Can this option group with other options? }; enum MiscFlags { // Miscellaneous flags to adjust argument CommaSeparated = 0x01, // Should this cl::list split between commas? PositionalEatsArgs = 0x02, // Should this positional cl::list eat -args? Sink = 0x04 // Should this cl::list eat all unknown options? }; //===----------------------------------------------------------------------===// // Option Category class // class OptionCategory { private: const char *const Name; const char *const Description; void registerCategory(); public: OptionCategory(const char *const Name, const char *const Description = nullptr) : Name(Name), Description(Description) { registerCategory(); } const char *getName() const { return Name; } const char *getDescription() const { return Description; } }; // The general Option Category (used as default category). extern OptionCategory GeneralCategory; //===----------------------------------------------------------------------===// // SubCommand class // class SubCommand { private: const char *const Name = nullptr; const char *const Description = nullptr; protected: void registerSubCommand(); void unregisterSubCommand(); public: SubCommand(const char *const Name, const char *const Description = nullptr) : Name(Name), Description(Description) { registerSubCommand(); } SubCommand() {} void reset(); operator bool() const; const char *getName() const { return Name; } const char *getDescription() const { return Description; } SmallVector<Option *, 4> PositionalOpts; SmallVector<Option *, 4> SinkOpts; StringMap<Option *> OptionsMap; Option *ConsumeAfterOpt = nullptr; // The ConsumeAfter option if it exists. }; // A special subcommand representing no subcommand extern ManagedStatic<SubCommand> TopLevelSubCommand; // A special subcommand that can be used to put an option into all subcommands. extern ManagedStatic<SubCommand> AllSubCommands; //===----------------------------------------------------------------------===// // Option Base class // class alias; class Option { friend class alias; // handleOccurrences - Overriden by subclasses to handle the value passed into // an argument. Should return true if there was an error processing the // argument and the program should exit. // virtual bool handleOccurrence(unsigned pos, StringRef ArgName, StringRef Arg) = 0; virtual enum ValueExpected getValueExpectedFlagDefault() const { return ValueOptional; } // Out of line virtual function to provide home for the class. virtual void anchor(); int NumOccurrences; // The number of times specified // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid // problems with signed enums in bitfields. unsigned Occurrences : 3; // enum NumOccurrencesFlag // not using the enum type for 'Value' because zero is an implementation // detail representing the non-value unsigned Value : 2; unsigned HiddenFlag : 2; // enum OptionHidden unsigned Formatting : 2; // enum FormattingFlags unsigned Misc : 3; unsigned Position; // Position of last occurrence of the option unsigned AdditionalVals; // Greater than 0 for multi-valued option. public: StringRef ArgStr; // The argument string itself (ex: "help", "o") StringRef HelpStr; // The descriptive text message for -help StringRef ValueStr; // String describing what the value of this option is OptionCategory *Category; // The Category this option belongs to SmallPtrSet<SubCommand *, 4> Subs; // The subcommands this option belongs to. bool FullyInitialized; // Has addArguemnt been called? inline enum NumOccurrencesFlag getNumOccurrencesFlag() const { return (enum NumOccurrencesFlag)Occurrences; } inline enum ValueExpected getValueExpectedFlag() const { return Value ? ((enum ValueExpected)Value) : getValueExpectedFlagDefault(); } inline enum OptionHidden getOptionHiddenFlag() const { return (enum OptionHidden)HiddenFlag; } inline enum FormattingFlags getFormattingFlag() const { return (enum FormattingFlags)Formatting; } inline unsigned getMiscFlags() const { return Misc; } inline unsigned getPosition() const { return Position; } inline unsigned getNumAdditionalVals() const { return AdditionalVals; } // hasArgStr - Return true if the argstr != "" bool hasArgStr() const { return !ArgStr.empty(); } bool isPositional() const { return getFormattingFlag() == cl::Positional; } bool isSink() const { return getMiscFlags() & cl::Sink; } bool isConsumeAfter() const { return getNumOccurrencesFlag() == cl::ConsumeAfter; } bool isInAllSubCommands() const { return std::any_of(Subs.begin(), Subs.end(), [](const SubCommand *SC) { return SC == &*AllSubCommands; }); } //-------------------------------------------------------------------------=== // Accessor functions set by OptionModifiers // void setArgStr(StringRef S); void setDescription(StringRef S) { HelpStr = S; } void setValueStr(StringRef S) { ValueStr = S; } void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) { Occurrences = Val; } void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; } void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; } void setFormattingFlag(enum FormattingFlags V) { Formatting = V; } void setMiscFlag(enum MiscFlags M) { Misc |= M; } void setPosition(unsigned pos) { Position = pos; } void setCategory(OptionCategory &C) { Category = &C; } void addSubCommand(SubCommand &S) { Subs.insert(&S); } protected: explicit Option(enum NumOccurrencesFlag OccurrencesFlag, enum OptionHidden Hidden) : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0), HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0), Position(0), AdditionalVals(0), ArgStr(""), HelpStr(""), ValueStr(""), Category(&GeneralCategory), FullyInitialized(false) {} inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; } public: // addArgument - Register this argument with the commandline system. // void addArgument(); /// Unregisters this option from the CommandLine system. /// /// This option must have been the last option registered. /// For testing purposes only. void removeArgument(); // Return the width of the option tag for printing... virtual size_t getOptionWidth() const = 0; // printOptionInfo - Print out information about this option. The // to-be-maintained width is specified. // virtual void printOptionInfo(size_t GlobalWidth) const = 0; virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0; virtual void getExtraOptionNames(SmallVectorImpl<StringRef> &) {} // addOccurrence - Wrapper around handleOccurrence that enforces Flags. // virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value, bool MultiArg = false); // Prints option name followed by message. Always returns true. bool error(const Twine &Message, StringRef ArgName = StringRef()); public: inline int getNumOccurrences() const { return NumOccurrences; } inline void reset() { NumOccurrences = 0; } virtual ~Option() {} }; //===----------------------------------------------------------------------===// // Command line option modifiers that can be used to modify the behavior of // command line option parsers... // // desc - Modifier to set the description shown in the -help output... struct desc { const char *Desc; desc(const char *Str) : Desc(Str) {} void apply(Option &O) const { O.setDescription(Desc); } }; // value_desc - Modifier to set the value description shown in the -help // output... struct value_desc { const char *Desc; value_desc(const char *Str) : Desc(Str) {} void apply(Option &O) const { O.setValueStr(Desc); } }; // init - Specify a default (initial) value for the command line argument, if // the default constructor for the argument type does not give you what you // want. This is only valid on "opt" arguments, not on "list" arguments. // template <class Ty> struct initializer { const Ty &Init; initializer(const Ty &Val) : Init(Val) {} template <class Opt> void apply(Opt &O) const { O.setInitialValue(Init); } }; template <class Ty> initializer<Ty> init(const Ty &Val) { return initializer<Ty>(Val); } // location - Allow the user to specify which external variable they want to // store the results of the command line argument processing into, if they don't // want to store it in the option itself. // template <class Ty> struct LocationClass { Ty &Loc; LocationClass(Ty &L) : Loc(L) {} template <class Opt> void apply(Opt &O) const { O.setLocation(O, Loc); } }; template <class Ty> LocationClass<Ty> location(Ty &L) { return LocationClass<Ty>(L); } // cat - Specifiy the Option category for the command line argument to belong // to. struct cat { OptionCategory &Category; cat(OptionCategory &c) : Category(c) {} template <class Opt> void apply(Opt &O) const { O.setCategory(Category); } }; // sub - Specify the subcommand that this option belongs to. struct sub { SubCommand &Sub; sub(SubCommand &S) : Sub(S) {} template <class Opt> void apply(Opt &O) const { O.addSubCommand(Sub); } }; //===----------------------------------------------------------------------===// // OptionValue class // Support value comparison outside the template. struct GenericOptionValue { virtual bool compare(const GenericOptionValue &V) const = 0; protected: ~GenericOptionValue() = default; GenericOptionValue() = default; GenericOptionValue(const GenericOptionValue&) = default; GenericOptionValue &operator=(const GenericOptionValue &) = default; private: virtual void anchor(); }; template <class DataType> struct OptionValue; // The default value safely does nothing. Option value printing is only // best-effort. template <class DataType, bool isClass> struct OptionValueBase : public GenericOptionValue { // Temporary storage for argument passing. typedef OptionValue<DataType> WrapperType; bool hasValue() const { return false; } const DataType &getValue() const { llvm_unreachable("no default value"); } // Some options may take their value from a different data type. template <class DT> void setValue(const DT & /*V*/) {} bool compare(const DataType & /*V*/) const { return false; } bool compare(const GenericOptionValue & /*V*/) const override { return false; } protected: ~OptionValueBase() = default; }; // Simple copy of the option value. template <class DataType> class OptionValueCopy : public GenericOptionValue { DataType Value; bool Valid; protected: ~OptionValueCopy() = default; OptionValueCopy(const OptionValueCopy&) = default; OptionValueCopy &operator=(const OptionValueCopy&) = default; public: OptionValueCopy() : Valid(false) {} bool hasValue() const { return Valid; } const DataType &getValue() const { assert(Valid && "invalid option value"); return Value; } void setValue(const DataType &V) { Valid = true; Value = V; } bool compare(const DataType &V) const { return Valid && (Value != V); } bool compare(const GenericOptionValue &V) const override { const OptionValueCopy<DataType> &VC = static_cast<const OptionValueCopy<DataType> &>(V); if (!VC.hasValue()) return false; return compare(VC.getValue()); } }; // Non-class option values. template <class DataType> struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> { typedef DataType WrapperType; protected: ~OptionValueBase() = default; OptionValueBase() = default; OptionValueBase(const OptionValueBase&) = default; OptionValueBase &operator=(const OptionValueBase&) = default; }; // Top-level option class. template <class DataType> struct OptionValue final : OptionValueBase<DataType, std::is_class<DataType>::value> { OptionValue() = default; OptionValue(const DataType &V) { this->setValue(V); } // Some options may take their value from a different data type. template <class DT> OptionValue<DataType> &operator=(const DT &V) { this->setValue(V); return *this; } }; // Other safe-to-copy-by-value common option types. enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE }; template <> struct OptionValue<cl::boolOrDefault> final : OptionValueCopy<cl::boolOrDefault> { typedef cl::boolOrDefault WrapperType; OptionValue() {} OptionValue(const cl::boolOrDefault &V) { this->setValue(V); } OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault &V) { setValue(V); return *this; } private: void anchor() override; }; template <> struct OptionValue<std::string> final : OptionValueCopy<std::string> { typedef StringRef WrapperType; OptionValue() {} OptionValue(const std::string &V) { this->setValue(V); } OptionValue<std::string> &operator=(const std::string &V) { setValue(V); return *this; } private: void anchor() override; }; //===----------------------------------------------------------------------===// // Enum valued command line option // #define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC #define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC #define clEnumValEnd (reinterpret_cast<void *>(0)) // values - For custom data types, allow specifying a group of values together // as the values that go into the mapping that the option handler uses. Note // that the values list must always have a 0 at the end of the list to indicate // that the list has ended. // template <class DataType> class ValuesClass { // Use a vector instead of a map, because the lists should be short, // the overhead is less, and most importantly, it keeps them in the order // inserted so we can print our option out nicely. SmallVector<std::pair<const char *, std::pair<int, const char *>>, 4> Values; void processValues(va_list Vals); public: ValuesClass(const char *EnumName, DataType Val, const char *Desc, va_list ValueArgs) { // Insert the first value, which is required. Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc))); // Process the varargs portion of the values... while (const char *enumName = va_arg(ValueArgs, const char *)) { DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int)); const char *EnumDesc = va_arg(ValueArgs, const char *); Values.push_back(std::make_pair(enumName, // Add value to value map std::make_pair(EnumVal, EnumDesc))); } } template <class Opt> void apply(Opt &O) const { for (size_t i = 0, e = Values.size(); i != e; ++i) O.getParser().addLiteralOption(Values[i].first, Values[i].second.first, Values[i].second.second); } }; template <class DataType> ValuesClass<DataType> LLVM_END_WITH_NULL values(const char *Arg, DataType Val, const char *Desc, ...) { va_list ValueArgs; va_start(ValueArgs, Desc); ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs); va_end(ValueArgs); return Vals; } //===----------------------------------------------------------------------===// // parser class - Parameterizable parser for different data types. By default, // known data types (string, int, bool) have specialized parsers, that do what // you would expect. The default parser, used for data types that are not // built-in, uses a mapping table to map specific options to values, which is // used, among other things, to handle enum types. //-------------------------------------------------- // generic_parser_base - This class holds all the non-generic code that we do // not need replicated for every instance of the generic parser. This also // allows us to put stuff into CommandLine.cpp // class generic_parser_base { protected: class GenericOptionInfo { public: GenericOptionInfo(const char *name, const char *helpStr) : Name(name), HelpStr(helpStr) {} const char *Name; const char *HelpStr; }; public: generic_parser_base(Option &O) : Owner(O) {} virtual ~generic_parser_base() {} // Base class should have virtual-dtor // getNumOptions - Virtual function implemented by generic subclass to // indicate how many entries are in Values. // virtual unsigned getNumOptions() const = 0; // getOption - Return option name N. virtual const char *getOption(unsigned N) const = 0; // getDescription - Return description N virtual const char *getDescription(unsigned N) const = 0; // Return the width of the option tag for printing... virtual size_t getOptionWidth(const Option &O) const; virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0; // printOptionInfo - Print out information about this option. The // to-be-maintained width is specified. // virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const; void printGenericOptionDiff(const Option &O, const GenericOptionValue &V, const GenericOptionValue &Default, size_t GlobalWidth) const; // printOptionDiff - print the value of an option and it's default. // // Template definition ensures that the option and default have the same // DataType (via the same AnyOptionValue). template <class AnyOptionValue> void printOptionDiff(const Option &O, const AnyOptionValue &V, const AnyOptionValue &Default, size_t GlobalWidth) const { printGenericOptionDiff(O, V, Default, GlobalWidth); } void initialize() {} void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) { // If there has been no argstr specified, that means that we need to add an // argument for every possible option. This ensures that our options are // vectored to us. if (!Owner.hasArgStr()) for (unsigned i = 0, e = getNumOptions(); i != e; ++i) OptionNames.push_back(getOption(i)); } enum ValueExpected getValueExpectedFlagDefault() const { // If there is an ArgStr specified, then we are of the form: // // -opt=O2 or -opt O2 or -optO2 // // In which case, the value is required. Otherwise if an arg str has not // been specified, we are of the form: // // -O2 or O2 or -la (where -l and -a are separate options) // // If this is the case, we cannot allow a value. // if (Owner.hasArgStr()) return ValueRequired; else return ValueDisallowed; } // findOption - Return the option number corresponding to the specified // argument string. If the option is not found, getNumOptions() is returned. // unsigned findOption(const char *Name); protected: Option &Owner; }; // Default parser implementation - This implementation depends on having a // mapping of recognized options to values of some sort. In addition to this, // each entry in the mapping also tracks a help message that is printed with the // command line option for -help. Because this is a simple mapping parser, the // data type can be any unsupported type. // template <class DataType> class parser : public generic_parser_base { protected: class OptionInfo : public GenericOptionInfo { public: OptionInfo(const char *name, DataType v, const char *helpStr) : GenericOptionInfo(name, helpStr), V(v) {} OptionValue<DataType> V; }; SmallVector<OptionInfo, 8> Values; public: parser(Option &O) : generic_parser_base(O) {} typedef DataType parser_data_type; // Implement virtual functions needed by generic_parser_base unsigned getNumOptions() const override { return unsigned(Values.size()); } const char *getOption(unsigned N) const override { return Values[N].Name; } const char *getDescription(unsigned N) const override { return Values[N].HelpStr; } // getOptionValue - Return the value of option name N. const GenericOptionValue &getOptionValue(unsigned N) const override { return Values[N].V; } // parse - Return true on error. bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) { StringRef ArgVal; if (Owner.hasArgStr()) ArgVal = Arg; else ArgVal = ArgName; for (size_t i = 0, e = Values.size(); i != e; ++i) if (Values[i].Name == ArgVal) { V = Values[i].V.getValue(); return false; } return O.error("Cannot find option named '" + ArgVal + "'!"); } /// addLiteralOption - Add an entry to the mapping table. /// template <class DT> void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) { assert(findOption(Name) == Values.size() && "Option already exists!"); OptionInfo X(Name, static_cast<DataType>(V), HelpStr); Values.push_back(X); AddLiteralOption(Owner, Name); } /// removeLiteralOption - Remove the specified option. /// void removeLiteralOption(const char *Name) { unsigned N = findOption(Name); assert(N != Values.size() && "Option not found!"); Values.erase(Values.begin() + N); } }; //-------------------------------------------------- // basic_parser - Super class of parsers to provide boilerplate code // class basic_parser_impl { // non-template implementation of basic_parser<t> public: basic_parser_impl(Option &) {} enum ValueExpected getValueExpectedFlagDefault() const { return ValueRequired; } void getExtraOptionNames(SmallVectorImpl<StringRef> &) {} void initialize() {} // Return the width of the option tag for printing... size_t getOptionWidth(const Option &O) const; // printOptionInfo - Print out information about this option. The // to-be-maintained width is specified. // void printOptionInfo(const Option &O, size_t GlobalWidth) const; // printOptionNoValue - Print a placeholder for options that don't yet support // printOptionDiff(). void printOptionNoValue(const Option &O, size_t GlobalWidth) const; // getValueName - Overload in subclass to provide a better default value. virtual const char *getValueName() const { return "value"; } // An out-of-line virtual method to provide a 'home' for this class. virtual void anchor(); protected: ~basic_parser_impl() = default; // A helper for basic_parser::printOptionDiff. void printOptionName(const Option &O, size_t GlobalWidth) const; }; // basic_parser - The real basic parser is just a template wrapper that provides // a typedef for the provided data type. // template <class DataType> class basic_parser : public basic_parser_impl { public: basic_parser(Option &O) : basic_parser_impl(O) {} typedef DataType parser_data_type; typedef OptionValue<DataType> OptVal; protected: // Workaround Clang PR22793 ~basic_parser() {} }; //-------------------------------------------------- // parser<bool> // template <> class parser<bool> final : public basic_parser<bool> { public: parser(Option &O) : basic_parser(O) {} // parse - Return true on error. bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val); void initialize() {} enum ValueExpected getValueExpectedFlagDefault() const { return ValueOptional; } // getValueName - Do not print =<value> at all. const char *getValueName() const override { return nullptr; } void printOptionDiff(const Option &O, bool V, OptVal Default, size_t GlobalWidth) const; // An out-of-line virtual method to provide a 'home' for this class. void anchor() override; }; extern template class basic_parser<bool>; //-------------------------------------------------- // parser<boolOrDefault> template <> class parser<boolOrDefault> final : public basic_parser<boolOrDefault> { public: parser(Option &O) : basic_parser(O) {} // parse - Return true on error. bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val); enum ValueExpected getValueExpectedFlagDefault() const { return ValueOptional; } // getValueName - Do not print =<value> at all. const char *getValueName() const override { return nullptr; } void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default, size_t GlobalWidth) const; // An out-of-line virtual method to provide a 'home' for this class. void anchor() override; }; extern template class basic_parser<boolOrDefault>; //-------------------------------------------------- // parser<int> // template <> class parser<int> final : public basic_parser<int> { public: parser(Option &O) : basic_parser(O) {} // parse - Return true on error. bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val); // getValueName - Overload in subclass to provide a better default value. const char *getValueName() const override { return "int"; } void printOptionDiff(const Option &O, int V, OptVal Default, size_t GlobalWidth) const; // An out-of-line virtual method to provide a 'home' for this class. void anchor() override; }; extern template class basic_parser<int>; //-------------------------------------------------- // parser<unsigned> // template <> class parser<unsigned> final : public basic_parser<unsigned> { public: parser(Option &O) : basic_parser(O) {} // parse - Return true on error. bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val); // getValueName - Overload in subclass to provide a better default value. const char *getValueName() const override { return "uint"; } void printOptionDiff(const Option &O, unsigned V, OptVal Default, size_t GlobalWidth) const; // An out-of-line virtual method to provide a 'home' for this class. void anchor() override; }; extern template class basic_parser<unsigned>; //-------------------------------------------------- // parser<unsigned long long> // template <> class parser<unsigned long long> final : public basic_parser<unsigned long long> { public: parser(Option &O) : basic_parser(O) {} // parse - Return true on error. bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned long long &Val); // getValueName - Overload in subclass to provide a better default value. const char *getValueName() const override { return "uint"; } void printOptionDiff(const Option &O, unsigned long long V, OptVal Default, size_t GlobalWidth) const; // An out-of-line virtual method to provide a 'home' for this class. void anchor() override; }; extern template class basic_parser<unsigned long long>; //-------------------------------------------------- // parser<double> // template <> class parser<double> final : public basic_parser<double> { public: parser(Option &O) : basic_parser(O) {} // parse - Return true on error. bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val); // getValueName - Overload in subclass to provide a better default value. const char *getValueName() const override { return "number"; } void printOptionDiff(const Option &O, double V, OptVal Default, size_t GlobalWidth) const; // An out-of-line virtual method to provide a 'home' for this class. void anchor() override; }; extern template class basic_parser<double>; //-------------------------------------------------- // parser<float> // template <> class parser<float> final : public basic_parser<float> { public: parser(Option &O) : basic_parser(O) {} // parse - Return true on error. bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val); // getValueName - Overload in subclass to provide a better default value. const char *getValueName() const override { return "number"; } void printOptionDiff(const Option &O, float V, OptVal Default, size_t GlobalWidth) const; // An out-of-line virtual method to provide a 'home' for this class. void anchor() override; }; extern template class basic_parser<float>; //-------------------------------------------------- // parser<std::string> // template <> class parser<std::string> final : public basic_parser<std::string> { public: parser(Option &O) : basic_parser(O) {} // parse - Return true on error. bool parse(Option &, StringRef, StringRef Arg, std::string &Value) { Value = Arg.str(); return false; } // getValueName - Overload in subclass to provide a better default value. const char *getValueName() const override { return "string"; } void printOptionDiff(const Option &O, StringRef V, const OptVal &Default, size_t GlobalWidth) const; // An out-of-line virtual method to provide a 'home' for this class. void anchor() override; }; extern template class basic_parser<std::string>; //-------------------------------------------------- // parser<char> // template <> class parser<char> final : public basic_parser<char> { public: parser(Option &O) : basic_parser(O) {} // parse - Return true on error. bool parse(Option &, StringRef, StringRef Arg, char &Value) { Value = Arg[0]; return false; } // getValueName - Overload in subclass to provide a better default value. const char *getValueName() const override { return "char"; } void printOptionDiff(const Option &O, char V, OptVal Default, size_t GlobalWidth) const; // An out-of-line virtual method to provide a 'home' for this class. void anchor() override; }; extern template class basic_parser<char>; //-------------------------------------------------- // PrintOptionDiff // // This collection of wrappers is the intermediary between class opt and class // parser to handle all the template nastiness. // This overloaded function is selected by the generic parser. template <class ParserClass, class DT> void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V, const OptionValue<DT> &Default, size_t GlobalWidth) { OptionValue<DT> OV = V; P.printOptionDiff(O, OV, Default, GlobalWidth); } // This is instantiated for basic parsers when the parsed value has a different // type than the option value. e.g. HelpPrinter. template <class ParserDT, class ValDT> struct OptionDiffPrinter { void print(const Option &O, const parser<ParserDT> &P, const ValDT & /*V*/, const OptionValue<ValDT> & /*Default*/, size_t GlobalWidth) { P.printOptionNoValue(O, GlobalWidth); } }; // This is instantiated for basic parsers when the parsed value has the same // type as the option value. template <class DT> struct OptionDiffPrinter<DT, DT> { void print(const Option &O, const parser<DT> &P, const DT &V, const OptionValue<DT> &Default, size_t GlobalWidth) { P.printOptionDiff(O, V, Default, GlobalWidth); } }; // This overloaded function is selected by the basic parser, which may parse a // different type than the option type. template <class ParserClass, class ValDT> void printOptionDiff( const Option &O, const basic_parser<typename ParserClass::parser_data_type> &P, const ValDT &V, const OptionValue<ValDT> &Default, size_t GlobalWidth) { OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer; printer.print(O, static_cast<const ParserClass &>(P), V, Default, GlobalWidth); } //===----------------------------------------------------------------------===// // applicator class - This class is used because we must use partial // specialization to handle literal string arguments specially (const char* does // not correctly respond to the apply method). Because the syntax to use this // is a pain, we have the 'apply' method below to handle the nastiness... // template <class Mod> struct applicator { template <class Opt> static void opt(const Mod &M, Opt &O) { M.apply(O); } }; // Handle const char* as a special case... template <unsigned n> struct applicator<char[n]> { template <class Opt> static void opt(const char *Str, Opt &O) { O.setArgStr(Str); } }; template <unsigned n> struct applicator<const char[n]> { template <class Opt> static void opt(const char *Str, Opt &O) { O.setArgStr(Str); } }; template <> struct applicator<const char *> { template <class Opt> static void opt(const char *Str, Opt &O) { O.setArgStr(Str); } }; template <> struct applicator<NumOccurrencesFlag> { static void opt(NumOccurrencesFlag N, Option &O) { O.setNumOccurrencesFlag(N); } }; template <> struct applicator<ValueExpected> { static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); } }; template <> struct applicator<OptionHidden> { static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); } }; template <> struct applicator<FormattingFlags> { static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); } }; template <> struct applicator<MiscFlags> { static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); } }; // apply method - Apply modifiers to an option in a type safe way. template <class Opt, class Mod, class... Mods> void apply(Opt *O, const Mod &M, const Mods &... Ms) { applicator<Mod>::opt(M, *O); apply(O, Ms...); } template <class Opt, class Mod> void apply(Opt *O, const Mod &M) { applicator<Mod>::opt(M, *O); } //===----------------------------------------------------------------------===// // opt_storage class // Default storage class definition: external storage. This implementation // assumes the user will specify a variable to store the data into with the // cl::location(x) modifier. // template <class DataType, bool ExternalStorage, bool isClass> class opt_storage { DataType *Location; // Where to store the object... OptionValue<DataType> Default; void check_location() const { assert(Location && "cl::location(...) not specified for a command " "line option with external storage, " "or cl::init specified before cl::location()!!"); } public: opt_storage() : Location(nullptr) {} bool setLocation(Option &O, DataType &L) { if (Location) return O.error("cl::location(x) specified more than once!"); Location = &L; Default = L; return false; } template <class T> void setValue(const T &V, bool initial = false) { check_location(); *Location = V; if (initial) Default = V; } DataType &getValue() { check_location(); return *Location; } const DataType &getValue() const { check_location(); return *Location; } operator DataType() const { return this->getValue(); } const OptionValue<DataType> &getDefault() const { return Default; } }; // Define how to hold a class type object, such as a string. Since we can // inherit from a class, we do so. This makes us exactly compatible with the // object in all cases that it is used. // template <class DataType> class opt_storage<DataType, false, true> : public DataType { public: OptionValue<DataType> Default; template <class T> void setValue(const T &V, bool initial = false) { DataType::operator=(V); if (initial) Default = V; } DataType &getValue() { return *this; } const DataType &getValue() const { return *this; } const OptionValue<DataType> &getDefault() const { return Default; } }; // Define a partial specialization to handle things we cannot inherit from. In // this case, we store an instance through containment, and overload operators // to get at the value. // template <class DataType> class opt_storage<DataType, false, false> { public: DataType Value; OptionValue<DataType> Default; // Make sure we initialize the value with the default constructor for the // type. opt_storage() : Value(DataType()), Default(DataType()) {} template <class T> void setValue(const T &V, bool initial = false) { Value = V; if (initial) Default = V; } DataType &getValue() { return Value; } DataType getValue() const { return Value; } const OptionValue<DataType> &getDefault() const { return Default; } operator DataType() const { return getValue(); } // If the datatype is a pointer, support -> on it. DataType operator->() const { return Value; } }; //===----------------------------------------------------------------------===// // opt - A scalar command line option. // template <class DataType, bool ExternalStorage = false, class ParserClass = parser<DataType>> class opt : public Option, public opt_storage<DataType, ExternalStorage, std::is_class<DataType>::value> { ParserClass Parser; bool handleOccurrence(unsigned pos, StringRef ArgName, StringRef Arg) override { typename ParserClass::parser_data_type Val = typename ParserClass::parser_data_type(); if (Parser.parse(*this, ArgName, Arg, Val)) return true; // Parse error! this->setValue(Val); this->setPosition(pos); return false; } enum ValueExpected getValueExpectedFlagDefault() const override { return Parser.getValueExpectedFlagDefault(); } void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override { return Parser.getExtraOptionNames(OptionNames); } // Forward printing stuff to the parser... size_t getOptionWidth() const override { return Parser.getOptionWidth(*this); } void printOptionInfo(size_t GlobalWidth) const override { Parser.printOptionInfo(*this, GlobalWidth); } void printOptionValue(size_t GlobalWidth, bool Force) const override { if (Force || this->getDefault().compare(this->getValue())) { cl::printOptionDiff<ParserClass>(*this, Parser, this->getValue(), this->getDefault(), GlobalWidth); } } void done() { addArgument(); Parser.initialize(); } // Command line options should not be copyable opt(const opt &) = delete; opt &operator=(const opt &) = delete; public: // setInitialValue - Used by the cl::init modifier... void setInitialValue(const DataType &V) { this->setValue(V, true); } ParserClass &getParser() { return Parser; } template <class T> DataType &operator=(const T &Val) { this->setValue(Val); return this->getValue(); } template <class... Mods> explicit opt(const Mods &... Ms) : Option(Optional, NotHidden), Parser(*this) { apply(this, Ms...); done(); } }; extern template class opt<unsigned>; extern template class opt<int>; extern template class opt<std::string>; extern template class opt<char>; extern template class opt<bool>; //===----------------------------------------------------------------------===// // list_storage class // Default storage class definition: external storage. This implementation // assumes the user will specify a variable to store the data into with the // cl::location(x) modifier. // template <class DataType, class StorageClass> class list_storage { StorageClass *Location; // Where to store the object... public: list_storage() : Location(0) {} bool setLocation(Option &O, StorageClass &L) { if (Location) return O.error("cl::location(x) specified more than once!"); Location = &L; return false; } template <class T> void addValue(const T &V) { assert(Location != 0 && "cl::location(...) not specified for a command " "line option with external storage!"); Location->push_back(V); } }; // Define how to hold a class type object, such as a string. // Originally this code inherited from std::vector. In transitioning to a new // API for command line options we should change this. The new implementation // of this list_storage specialization implements the minimum subset of the // std::vector API required for all the current clients. // // FIXME: Reduce this API to a more narrow subset of std::vector // template <class DataType> class list_storage<DataType, bool> { std::vector<DataType> Storage; public: typedef typename std::vector<DataType>::iterator iterator; iterator begin() { return Storage.begin(); } iterator end() { return Storage.end(); } typedef typename std::vector<DataType>::const_iterator const_iterator; const_iterator begin() const { return Storage.begin(); } const_iterator end() const { return Storage.end(); } typedef typename std::vector<DataType>::size_type size_type; size_type size() const { return Storage.size(); } bool empty() const { return Storage.empty(); } void push_back(const DataType &value) { Storage.push_back(value); } void push_back(DataType &&value) { Storage.push_back(value); } typedef typename std::vector<DataType>::reference reference; typedef typename std::vector<DataType>::const_reference const_reference; reference operator[](size_type pos) { return Storage[pos]; } const_reference operator[](size_type pos) const { return Storage[pos]; } iterator erase(const_iterator pos) { return Storage.erase(pos); } iterator erase(const_iterator first, const_iterator last) { return Storage.erase(first, last); } iterator erase(iterator pos) { return Storage.erase(pos); } iterator erase(iterator first, iterator last) { return Storage.erase(first, last); } iterator insert(const_iterator pos, const DataType &value) { return Storage.insert(pos, value); } iterator insert(const_iterator pos, DataType &&value) { return Storage.insert(pos, value); } iterator insert(iterator pos, const DataType &value) { return Storage.insert(pos, value); } iterator insert(iterator pos, DataType &&value) { return Storage.insert(pos, value); } reference front() { return Storage.front(); } const_reference front() const { return Storage.front(); } operator std::vector<DataType>&() { return Storage; } operator ArrayRef<DataType>() { return Storage; } std::vector<DataType> *operator&() { return &Storage; } const std::vector<DataType> *operator&() const { return &Storage; } template <class T> void addValue(const T &V) { Storage.push_back(V); } }; //===----------------------------------------------------------------------===// // list - A list of command line options. // template <class DataType, class StorageClass = bool, class ParserClass = parser<DataType>> class list : public Option, public list_storage<DataType, StorageClass> { std::vector<unsigned> Positions; ParserClass Parser; enum ValueExpected getValueExpectedFlagDefault() const override { return Parser.getValueExpectedFlagDefault(); } void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override { return Parser.getExtraOptionNames(OptionNames); } bool handleOccurrence(unsigned pos, StringRef ArgName, StringRef Arg) override { typename ParserClass::parser_data_type Val = typename ParserClass::parser_data_type(); if (Parser.parse(*this, ArgName, Arg, Val)) return true; // Parse Error! list_storage<DataType, StorageClass>::addValue(Val); setPosition(pos); Positions.push_back(pos); return false; } // Forward printing stuff to the parser... size_t getOptionWidth() const override { return Parser.getOptionWidth(*this); } void printOptionInfo(size_t GlobalWidth) const override { Parser.printOptionInfo(*this, GlobalWidth); } // Unimplemented: list options don't currently store their default value. void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override { } void done() { addArgument(); Parser.initialize(); } // Command line options should not be copyable list(const list &) = delete; list &operator=(const list &) = delete; public: ParserClass &getParser() { return Parser; } unsigned getPosition(unsigned optnum) const { assert(optnum < this->size() && "Invalid option index"); return Positions[optnum]; } void setNumAdditionalVals(unsigned n) { Option::setNumAdditionalVals(n); } template <class... Mods> explicit list(const Mods &... Ms) : Option(ZeroOrMore, NotHidden), Parser(*this) { apply(this, Ms...); done(); } }; // multi_val - Modifier to set the number of additional values. struct multi_val { unsigned AdditionalVals; explicit multi_val(unsigned N) : AdditionalVals(N) {} template <typename D, typename S, typename P> void apply(list<D, S, P> &L) const { L.setNumAdditionalVals(AdditionalVals); } }; //===----------------------------------------------------------------------===// // bits_storage class // Default storage class definition: external storage. This implementation // assumes the user will specify a variable to store the data into with the // cl::location(x) modifier. // template <class DataType, class StorageClass> class bits_storage { unsigned *Location; // Where to store the bits... template <class T> static unsigned Bit(const T &V) { unsigned BitPos = reinterpret_cast<unsigned>(V); assert(BitPos < sizeof(unsigned) * CHAR_BIT && "enum exceeds width of bit vector!"); return 1 << BitPos; } public: bits_storage() : Location(nullptr) {} bool setLocation(Option &O, unsigned &L) { if (Location) return O.error("cl::location(x) specified more than once!"); Location = &L; return false; } template <class T> void addValue(const T &V) { assert(Location != 0 && "cl::location(...) not specified for a command " "line option with external storage!"); *Location |= Bit(V); } unsigned getBits() { return *Location; } template <class T> bool isSet(const T &V) { return (*Location & Bit(V)) != 0; } }; // Define how to hold bits. Since we can inherit from a class, we do so. // This makes us exactly compatible with the bits in all cases that it is used. // template <class DataType> class bits_storage<DataType, bool> { unsigned Bits; // Where to store the bits... template <class T> static unsigned Bit(const T &V) { unsigned BitPos = (unsigned)V; assert(BitPos < sizeof(unsigned) * CHAR_BIT && "enum exceeds width of bit vector!"); return 1 << BitPos; } public: template <class T> void addValue(const T &V) { Bits |= Bit(V); } unsigned getBits() { return Bits; } template <class T> bool isSet(const T &V) { return (Bits & Bit(V)) != 0; } }; //===----------------------------------------------------------------------===// // bits - A bit vector of command options. // template <class DataType, class Storage = bool, class ParserClass = parser<DataType>> class bits : public Option, public bits_storage<DataType, Storage> { std::vector<unsigned> Positions; ParserClass Parser; enum ValueExpected getValueExpectedFlagDefault() const override { return Parser.getValueExpectedFlagDefault(); } void getExtraOptionNames(SmallVectorImpl<StringRef> &OptionNames) override { return Parser.getExtraOptionNames(OptionNames); } bool handleOccurrence(unsigned pos, StringRef ArgName, StringRef Arg) override { typename ParserClass::parser_data_type Val = typename ParserClass::parser_data_type(); if (Parser.parse(*this, ArgName, Arg, Val)) return true; // Parse Error! this->addValue(Val); setPosition(pos); Positions.push_back(pos); return false; } // Forward printing stuff to the parser... size_t getOptionWidth() const override { return Parser.getOptionWidth(*this); } void printOptionInfo(size_t GlobalWidth) const override { Parser.printOptionInfo(*this, GlobalWidth); } // Unimplemented: bits options don't currently store their default values. void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override { } void done() { addArgument(); Parser.initialize(); } // Command line options should not be copyable bits(const bits &) = delete; bits &operator=(const bits &) = delete; public: ParserClass &getParser() { return Parser; } unsigned getPosition(unsigned optnum) const { assert(optnum < this->size() && "Invalid option index"); return Positions[optnum]; } template <class... Mods> explicit bits(const Mods &... Ms) : Option(ZeroOrMore, NotHidden), Parser(*this) { apply(this, Ms...); done(); } }; //===----------------------------------------------------------------------===// // Aliased command line option (alias this name to a preexisting name) // class alias : public Option { Option *AliasFor; bool handleOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Arg) override { return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg); } bool addOccurrence(unsigned pos, StringRef /*ArgName*/, StringRef Value, bool MultiArg = false) override { return AliasFor->addOccurrence(pos, AliasFor->ArgStr, Value, MultiArg); } // Handle printing stuff... size_t getOptionWidth() const override; void printOptionInfo(size_t GlobalWidth) const override; // Aliases do not need to print their values. void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const override { } ValueExpected getValueExpectedFlagDefault() const override { return AliasFor->getValueExpectedFlag(); } void done() { if (!hasArgStr()) error("cl::alias must have argument name specified!"); if (!AliasFor) error("cl::alias must have an cl::aliasopt(option) specified!"); Subs = AliasFor->Subs; addArgument(); } // Command line options should not be copyable alias(const alias &) = delete; alias &operator=(const alias &) = delete; public: void setAliasFor(Option &O) { if (AliasFor) error("cl::alias must only have one cl::aliasopt(...) specified!"); AliasFor = &O; } template <class... Mods> explicit alias(const Mods &... Ms) : Option(Optional, Hidden), AliasFor(nullptr) { apply(this, Ms...); done(); } }; // aliasfor - Modifier to set the option an alias aliases. struct aliasopt { Option &Opt; explicit aliasopt(Option &O) : Opt(O) {} void apply(alias &A) const { A.setAliasFor(Opt); } }; // extrahelp - provide additional help at the end of the normal help // output. All occurrences of cl::extrahelp will be accumulated and // printed to stderr at the end of the regular help, just before // exit is called. struct extrahelp { const char *morehelp; explicit extrahelp(const char *help); }; void PrintVersionMessage(); /// This function just prints the help message, exactly the same way as if the /// -help or -help-hidden option had been given on the command line. /// /// NOTE: THIS FUNCTION TERMINATES THE PROGRAM! /// /// \param Hidden if true will print hidden options /// \param Categorized if true print options in categories void PrintHelpMessage(bool Hidden = false, bool Categorized = false); //===----------------------------------------------------------------------===// // Public interface for accessing registered options. // /// \brief Use this to get a StringMap to all registered named options /// (e.g. -help). Note \p Map Should be an empty StringMap. /// /// \return A reference to the StringMap used by the cl APIs to parse options. /// /// Access to unnamed arguments (i.e. positional) are not provided because /// it is expected that the client already has access to these. /// /// Typical usage: /// \code /// main(int argc,char* argv[]) { /// StringMap<llvm::cl::Option*> &opts = llvm::cl::getRegisteredOptions(); /// assert(opts.count("help") == 1) /// opts["help"]->setDescription("Show alphabetical help information") /// // More code /// llvm::cl::ParseCommandLineOptions(argc,argv); /// //More code /// } /// \endcode /// /// This interface is useful for modifying options in libraries that are out of /// the control of the client. The options should be modified before calling /// llvm::cl::ParseCommandLineOptions(). /// /// Hopefully this API can be depricated soon. Any situation where options need /// to be modified by tools or libraries should be handled by sane APIs rather /// than just handing around a global list. StringMap<Option *> &getRegisteredOptions(SubCommand &Sub = *TopLevelSubCommand); //===----------------------------------------------------------------------===// // Standalone command line processing utilities. // /// \brief Tokenizes a command line that can contain escapes and quotes. // /// The quoting rules match those used by GCC and other tools that use /// libiberty's buildargv() or expandargv() utilities, and do not match bash. /// They differ from buildargv() on treatment of backslashes that do not escape /// a special character to make it possible to accept most Windows file paths. /// /// \param [in] Source The string to be split on whitespace with quotes. /// \param [in] Saver Delegates back to the caller for saving parsed strings. /// \param [in] MarkEOLs true if tokenizing a response file and you want end of /// lines and end of the response file to be marked with a nullptr string. /// \param [out] NewArgv All parsed strings are appended to NewArgv. void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver, SmallVectorImpl<const char *> &NewArgv, bool MarkEOLs = false); /// \brief Tokenizes a Windows command line which may contain quotes and escaped /// quotes. /// /// See MSDN docs for CommandLineToArgvW for information on the quoting rules. /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx /// /// \param [in] Source The string to be split on whitespace with quotes. /// \param [in] Saver Delegates back to the caller for saving parsed strings. /// \param [in] MarkEOLs true if tokenizing a response file and you want end of /// lines and end of the response file to be marked with a nullptr string. /// \param [out] NewArgv All parsed strings are appended to NewArgv. void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver, SmallVectorImpl<const char *> &NewArgv, bool MarkEOLs = false); /// \brief String tokenization function type. Should be compatible with either /// Windows or Unix command line tokenizers. typedef void (*TokenizerCallback)(StringRef Source, StringSaver &Saver, SmallVectorImpl<const char *> &NewArgv, bool MarkEOLs); /// \brief Expand response files on a command line recursively using the given /// StringSaver and tokenization strategy. Argv should contain the command line /// before expansion and will be modified in place. If requested, Argv will /// also be populated with nullptrs indicating where each response file line /// ends, which is useful for the "/link" argument that needs to consume all /// remaining arguments only until the next end of line, when in a response /// file. /// /// \param [in] Saver Delegates back to the caller for saving parsed strings. /// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows. /// \param [in,out] Argv Command line into which to expand response files. /// \param [in] MarkEOLs Mark end of lines and the end of the response file /// with nullptrs in the Argv vector. /// \return true if all @files were expanded successfully or there were none. bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, SmallVectorImpl<const char *> &Argv, bool MarkEOLs = false); /// \brief Mark all options not part of this category as cl::ReallyHidden. /// /// \param Category the category of options to keep displaying /// /// Some tools (like clang-format) like to be able to hide all options that are /// not specific to the tool. This function allows a tool to specify a single /// option category to display in the -help output. void HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub = *TopLevelSubCommand); /// \brief Mark all options not part of the categories as cl::ReallyHidden. /// /// \param Categories the categories of options to keep displaying. /// /// Some tools (like clang-format) like to be able to hide all options that are /// not specific to the tool. This function allows a tool to specify a single /// option category to display in the -help output. void HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories, SubCommand &Sub = *TopLevelSubCommand); /// \brief Reset all command line options to a state that looks as if they have /// never appeared on the command line. This is useful for being able to parse /// a command line multiple times (especially useful for writing tests). void ResetAllOptionOccurrences(); /// \brief Reset the command line parser back to its initial state. This /// removes /// all options, categories, and subcommands and returns the parser to a state /// where no options are supported. void ResetCommandLineParser(); } // End namespace cl } // End namespace llvm #endif
[ "sebi@quantstamp.com" ]
sebi@quantstamp.com
e26aef8f336828833bc23cc4ff2afac644c3896b
a78d0417e5fd2ab2c4c733c4fc396774ad1c5452
/tests/pthread_test.cpp
8ae28d81ed665c0aa30930b991d642df3f3e05ce
[]
no_license
khanhduytran0/bionic_lollipop-iosport
c0bfac18735eadd29d1559e63f7bd823dcf8a0c7
44d7d2285cbe6622db20513093ac46e60eff90d1
refs/heads/main
2023-06-17T00:33:25.428033
2021-05-26T23:14:13
2021-05-26T23:14:13
357,794,514
3
1
null
null
null
null
UTF-8
C++
false
false
49,318
cpp
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include <errno.h> #include <inttypes.h> #include <limits.h> #include <malloc.h> #include <pthread.h> #include <signal.h> #include <stdio.h> #include <sys/mman.h> #include <sys/syscall.h> #include <time.h> #include <unistd.h> #include <atomic> #include <regex> #include <vector> #include <base/file.h> #include <base/stringprintf.h> #include "private/bionic_macros.h" #include "private/ScopeGuard.h" #include "BionicDeathTest.h" #include "ScopedSignalHandler.h" extern "C" pid_t gettid(); TEST(pthread, pthread_key_create) { pthread_key_t key; ASSERT_EQ(0, pthread_key_create(&key, NULL)); ASSERT_EQ(0, pthread_key_delete(key)); // Can't delete a key that's already been deleted. ASSERT_EQ(EINVAL, pthread_key_delete(key)); } TEST(pthread, pthread_keys_max) { // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX. ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX); } TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) { int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX); ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX); } TEST(pthread, pthread_key_many_distinct) { // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX // pthread keys, but We should be able to allocate at least this many keys. int nkeys = PTHREAD_KEYS_MAX / 2; std::vector<pthread_key_t> keys; auto scope_guard = make_scope_guard([&keys]{ for (auto key : keys) { EXPECT_EQ(0, pthread_key_delete(key)); } }); for (int i = 0; i < nkeys; ++i) { pthread_key_t key; // If this fails, it's likely that LIBC_PTHREAD_KEY_RESERVED_COUNT is wrong. ASSERT_EQ(0, pthread_key_create(&key, NULL)) << i << " of " << nkeys; keys.push_back(key); ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i))); } for (int i = keys.size() - 1; i >= 0; --i) { ASSERT_EQ(reinterpret_cast<void*>(i), pthread_getspecific(keys.back())); pthread_key_t key = keys.back(); keys.pop_back(); ASSERT_EQ(0, pthread_key_delete(key)); } } TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) { std::vector<pthread_key_t> keys; int rv = 0; // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should // be more than we are allowed to allocate now. for (int i = 0; i < PTHREAD_KEYS_MAX; i++) { pthread_key_t key; rv = pthread_key_create(&key, NULL); if (rv == EAGAIN) { break; } EXPECT_EQ(0, rv); keys.push_back(key); } // Don't leak keys. for (auto key : keys) { EXPECT_EQ(0, pthread_key_delete(key)); } keys.clear(); // We should have eventually reached the maximum number of keys and received // EAGAIN. ASSERT_EQ(EAGAIN, rv); } TEST(pthread, pthread_key_delete) { void* expected = reinterpret_cast<void*>(1234); pthread_key_t key; ASSERT_EQ(0, pthread_key_create(&key, NULL)); ASSERT_EQ(0, pthread_setspecific(key, expected)); ASSERT_EQ(expected, pthread_getspecific(key)); ASSERT_EQ(0, pthread_key_delete(key)); // After deletion, pthread_getspecific returns NULL. ASSERT_EQ(NULL, pthread_getspecific(key)); // And you can't use pthread_setspecific with the deleted key. ASSERT_EQ(EINVAL, pthread_setspecific(key, expected)); } TEST(pthread, pthread_key_fork) { void* expected = reinterpret_cast<void*>(1234); pthread_key_t key; ASSERT_EQ(0, pthread_key_create(&key, NULL)); ASSERT_EQ(0, pthread_setspecific(key, expected)); ASSERT_EQ(expected, pthread_getspecific(key)); pid_t pid = fork(); ASSERT_NE(-1, pid) << strerror(errno); if (pid == 0) { // The surviving thread inherits all the forking thread's TLS values... ASSERT_EQ(expected, pthread_getspecific(key)); _exit(99); } int status; ASSERT_EQ(pid, waitpid(pid, &status, 0)); ASSERT_TRUE(WIFEXITED(status)); ASSERT_EQ(99, WEXITSTATUS(status)); ASSERT_EQ(expected, pthread_getspecific(key)); ASSERT_EQ(0, pthread_key_delete(key)); } static void* DirtyKeyFn(void* key) { return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key)); } TEST(pthread, pthread_key_dirty) { pthread_key_t key; ASSERT_EQ(0, pthread_key_create(&key, NULL)); size_t stack_size = 128 * 1024; void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); ASSERT_NE(MAP_FAILED, stack); memset(stack, 0xff, stack_size); pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size)); pthread_t t; ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key)); void* result; ASSERT_EQ(0, pthread_join(t, &result)); ASSERT_EQ(nullptr, result); // Not ~0! ASSERT_EQ(0, munmap(stack, stack_size)); ASSERT_EQ(0, pthread_key_delete(key)); } TEST(pthread, static_pthread_key_used_before_creation) { #if defined(__BIONIC__) // See http://b/19625804. The bug is about a static/global pthread key being used before creation. // So here tests if the static/global default value 0 can be detected as invalid key. static pthread_key_t key; ASSERT_EQ(nullptr, pthread_getspecific(key)); ASSERT_EQ(EINVAL, pthread_setspecific(key, nullptr)); ASSERT_EQ(EINVAL, pthread_key_delete(key)); #else GTEST_LOG_(INFO) << "This test tests bionic pthread key implementation detail.\n"; #endif } static void* IdFn(void* arg) { return arg; } class SpinFunctionHelper { public: SpinFunctionHelper() { SpinFunctionHelper::spin_flag_ = true; } ~SpinFunctionHelper() { UnSpin(); } auto GetFunction() -> void* (*)(void*) { return SpinFunctionHelper::SpinFn; } void UnSpin() { SpinFunctionHelper::spin_flag_ = false; } private: static void* SpinFn(void*) { while (spin_flag_) {} return NULL; } static volatile bool spin_flag_; }; // It doesn't matter if spin_flag_ is used in several tests, // because it is always set to false after each test. Each thread // loops on spin_flag_ can find it becomes false at some time. volatile bool SpinFunctionHelper::spin_flag_ = false; static void* JoinFn(void* arg) { return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), NULL)); } static void AssertDetached(pthread_t t, bool is_detached) { pthread_attr_t attr; ASSERT_EQ(0, pthread_getattr_np(t, &attr)); int detach_state; ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state)); pthread_attr_destroy(&attr); ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED)); } static void MakeDeadThread(pthread_t& t) { ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, NULL)); ASSERT_EQ(0, pthread_join(t, NULL)); } TEST(pthread, pthread_create) { void* expected_result = reinterpret_cast<void*>(123); // Can we create a thread? pthread_t t; ASSERT_EQ(0, pthread_create(&t, NULL, IdFn, expected_result)); // If we join, do we get the expected value back? void* result; ASSERT_EQ(0, pthread_join(t, &result)); ASSERT_EQ(expected_result, result); } TEST(pthread, pthread_create_EAGAIN) { pthread_attr_t attributes; ASSERT_EQ(0, pthread_attr_init(&attributes)); ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1))); pthread_t t; ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, NULL)); } TEST(pthread, pthread_no_join_after_detach) { SpinFunctionHelper spinhelper; pthread_t t1; ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL)); // After a pthread_detach... ASSERT_EQ(0, pthread_detach(t1)); AssertDetached(t1, true); // ...pthread_join should fail. ASSERT_EQ(EINVAL, pthread_join(t1, NULL)); } TEST(pthread, pthread_no_op_detach_after_join) { SpinFunctionHelper spinhelper; pthread_t t1; ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL)); // If thread 2 is already waiting to join thread 1... pthread_t t2; ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1))); sleep(1); // (Give t2 a chance to call pthread_join.) #if defined(__BIONIC__) ASSERT_EQ(EINVAL, pthread_detach(t1)); #else ASSERT_EQ(0, pthread_detach(t1)); #endif AssertDetached(t1, false); spinhelper.UnSpin(); // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes). void* join_result; ASSERT_EQ(0, pthread_join(t2, &join_result)); ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result)); } TEST(pthread, pthread_join_self) { ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), NULL)); } struct TestBug37410 { pthread_t main_thread; pthread_mutex_t mutex; static void main() { TestBug37410 data; data.main_thread = pthread_self(); ASSERT_EQ(0, pthread_mutex_init(&data.mutex, NULL)); ASSERT_EQ(0, pthread_mutex_lock(&data.mutex)); pthread_t t; ASSERT_EQ(0, pthread_create(&t, NULL, TestBug37410::thread_fn, reinterpret_cast<void*>(&data))); // Wait for the thread to be running... ASSERT_EQ(0, pthread_mutex_lock(&data.mutex)); ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex)); // ...and exit. pthread_exit(NULL); } private: static void* thread_fn(void* arg) { TestBug37410* data = reinterpret_cast<TestBug37410*>(arg); // Let the main thread know we're running. pthread_mutex_unlock(&data->mutex); // And wait for the main thread to exit. pthread_join(data->main_thread, NULL); return NULL; } }; // Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to // run this test (which exits normally) in its own process. class pthread_DeathTest : public BionicDeathTest {}; TEST_F(pthread_DeathTest, pthread_bug_37410) { // http://code.google.com/p/android/issues/detail?id=37410 ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), ""); } static void* SignalHandlerFn(void* arg) { sigset_t wait_set; sigfillset(&wait_set); return reinterpret_cast<void*>(sigwait(&wait_set, reinterpret_cast<int*>(arg))); } TEST(pthread, pthread_sigmask) { // Check that SIGUSR1 isn't blocked. sigset_t original_set; sigemptyset(&original_set); ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &original_set)); ASSERT_FALSE(sigismember(&original_set, SIGUSR1)); // Block SIGUSR1. sigset_t set; sigemptyset(&set); sigaddset(&set, SIGUSR1); ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, NULL)); // Check that SIGUSR1 is blocked. sigset_t final_set; sigemptyset(&final_set); ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, NULL, &final_set)); ASSERT_TRUE(sigismember(&final_set, SIGUSR1)); // ...and that sigprocmask agrees with pthread_sigmask. sigemptyset(&final_set); ASSERT_EQ(0, sigprocmask(SIG_BLOCK, NULL, &final_set)); ASSERT_TRUE(sigismember(&final_set, SIGUSR1)); // Spawn a thread that calls sigwait and tells us what it received. pthread_t signal_thread; int received_signal = -1; ASSERT_EQ(0, pthread_create(&signal_thread, NULL, SignalHandlerFn, &received_signal)); // Send that thread SIGUSR1. pthread_kill(signal_thread, SIGUSR1); // See what it got. void* join_result; ASSERT_EQ(0, pthread_join(signal_thread, &join_result)); ASSERT_EQ(SIGUSR1, received_signal); ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result)); // Restore the original signal mask. ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, NULL)); } TEST(pthread, pthread_setname_np__too_long) { // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL. ASSERT_EQ(0, pthread_setname_np(pthread_self(), "123456789012345")); ASSERT_EQ(ERANGE, pthread_setname_np(pthread_self(), "1234567890123456")); } TEST(pthread, pthread_setname_np__self) { ASSERT_EQ(0, pthread_setname_np(pthread_self(), "short 1")); } TEST(pthread, pthread_setname_np__other) { SpinFunctionHelper spinhelper; pthread_t t1; ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL)); ASSERT_EQ(0, pthread_setname_np(t1, "short 2")); } TEST(pthread, pthread_setname_np__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); // Call pthread_setname_np after thread has already exited. ASSERT_EQ(ENOENT, pthread_setname_np(dead_thread, "short 3")); } TEST(pthread, pthread_kill__0) { // Signal 0 just tests that the thread exists, so it's safe to call on ourselves. ASSERT_EQ(0, pthread_kill(pthread_self(), 0)); } TEST(pthread, pthread_kill__invalid_signal) { ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1)); } static void pthread_kill__in_signal_handler_helper(int signal_number) { static int count = 0; ASSERT_EQ(SIGALRM, signal_number); if (++count == 1) { // Can we call pthread_kill from a signal handler? ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM)); } } TEST(pthread, pthread_kill__in_signal_handler) { ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper); ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM)); } TEST(pthread, pthread_detach__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); ASSERT_EQ(ESRCH, pthread_detach(dead_thread)); } TEST(pthread, pthread_getcpuclockid__clock_gettime) { SpinFunctionHelper spinhelper; pthread_t t; ASSERT_EQ(0, pthread_create(&t, NULL, spinhelper.GetFunction(), NULL)); clockid_t c; ASSERT_EQ(0, pthread_getcpuclockid(t, &c)); timespec ts; ASSERT_EQ(0, clock_gettime(c, &ts)); } TEST(pthread, pthread_getcpuclockid__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); clockid_t c; ASSERT_EQ(ESRCH, pthread_getcpuclockid(dead_thread, &c)); } TEST(pthread, pthread_getschedparam__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); int policy; sched_param param; ASSERT_EQ(ESRCH, pthread_getschedparam(dead_thread, &policy, &param)); } TEST(pthread, pthread_setschedparam__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); int policy = 0; sched_param param; ASSERT_EQ(ESRCH, pthread_setschedparam(dead_thread, policy, &param)); } TEST(pthread, pthread_join__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); ASSERT_EQ(ESRCH, pthread_join(dead_thread, NULL)); } TEST(pthread, pthread_kill__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); ASSERT_EQ(ESRCH, pthread_kill(dead_thread, 0)); } TEST(pthread, pthread_join__multijoin) { SpinFunctionHelper spinhelper; pthread_t t1; ASSERT_EQ(0, pthread_create(&t1, NULL, spinhelper.GetFunction(), NULL)); pthread_t t2; ASSERT_EQ(0, pthread_create(&t2, NULL, JoinFn, reinterpret_cast<void*>(t1))); sleep(1); // (Give t2 a chance to call pthread_join.) // Multiple joins to the same thread should fail. ASSERT_EQ(EINVAL, pthread_join(t1, NULL)); spinhelper.UnSpin(); // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes). void* join_result; ASSERT_EQ(0, pthread_join(t2, &join_result)); ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result)); } TEST(pthread, pthread_join__race) { // http://b/11693195 --- pthread_join could return before the thread had actually exited. // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread. for (size_t i = 0; i < 1024; ++i) { size_t stack_size = 64*1024; void* stack = mmap(NULL, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0); pthread_attr_t a; pthread_attr_init(&a); pthread_attr_setstack(&a, stack, stack_size); pthread_t t; ASSERT_EQ(0, pthread_create(&t, &a, IdFn, NULL)); ASSERT_EQ(0, pthread_join(t, NULL)); ASSERT_EQ(0, munmap(stack, stack_size)); } } static void* GetActualGuardSizeFn(void* arg) { pthread_attr_t attributes; pthread_getattr_np(pthread_self(), &attributes); pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg)); return NULL; } static size_t GetActualGuardSize(const pthread_attr_t& attributes) { size_t result; pthread_t t; pthread_create(&t, &attributes, GetActualGuardSizeFn, &result); pthread_join(t, NULL); return result; } static void* GetActualStackSizeFn(void* arg) { pthread_attr_t attributes; pthread_getattr_np(pthread_self(), &attributes); pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg)); return NULL; } static size_t GetActualStackSize(const pthread_attr_t& attributes) { size_t result; pthread_t t; pthread_create(&t, &attributes, GetActualStackSizeFn, &result); pthread_join(t, NULL); return result; } TEST(pthread, pthread_attr_setguardsize) { pthread_attr_t attributes; ASSERT_EQ(0, pthread_attr_init(&attributes)); // Get the default guard size. size_t default_guard_size; ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &default_guard_size)); // No such thing as too small: will be rounded up to one page by pthread_create. ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128)); size_t guard_size; ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); ASSERT_EQ(128U, guard_size); ASSERT_EQ(4096U, GetActualGuardSize(attributes)); // Large enough and a multiple of the page size. ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024)); ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); ASSERT_EQ(32*1024U, guard_size); // Large enough but not a multiple of the page size; will be rounded up by pthread_create. ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1)); ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); ASSERT_EQ(32*1024U + 1, guard_size); } TEST(pthread, pthread_attr_setstacksize) { pthread_attr_t attributes; ASSERT_EQ(0, pthread_attr_init(&attributes)); // Get the default stack size. size_t default_stack_size; ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size)); // Too small. ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128)); size_t stack_size; ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size)); ASSERT_EQ(default_stack_size, stack_size); ASSERT_GE(GetActualStackSize(attributes), default_stack_size); // Large enough and a multiple of the page size; may be rounded up by pthread_create. ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024)); ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size)); ASSERT_EQ(32*1024U, stack_size); ASSERT_GE(GetActualStackSize(attributes), 32*1024U); // Large enough but not aligned; will be rounded up by pthread_create. ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1)); ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size)); ASSERT_EQ(32*1024U + 1, stack_size); #if defined(__BIONIC__) ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1); #else // __BIONIC__ // glibc rounds down, in violation of POSIX. They document this in their BUGS section. ASSERT_EQ(GetActualStackSize(attributes), 32*1024U); #endif // __BIONIC__ } TEST(pthread, pthread_rwlockattr_smoke) { pthread_rwlockattr_t attr; ASSERT_EQ(0, pthread_rwlockattr_init(&attr)); int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED}; for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) { ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i])); int pshared; ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared)); ASSERT_EQ(pshared_value_array[i], pshared); } int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP}; for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) { ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i])); int kind; ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind)); ASSERT_EQ(kind_array[i], kind); } ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr)); } TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) { pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER; pthread_rwlock_t lock2; ASSERT_EQ(0, pthread_rwlock_init(&lock2, NULL)); ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1))); } TEST(pthread, pthread_rwlock_smoke) { pthread_rwlock_t l; ASSERT_EQ(0, pthread_rwlock_init(&l, NULL)); // Single read lock ASSERT_EQ(0, pthread_rwlock_rdlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // Multiple read lock ASSERT_EQ(0, pthread_rwlock_rdlock(&l)); ASSERT_EQ(0, pthread_rwlock_rdlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // Write lock ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // Try writer lock ASSERT_EQ(0, pthread_rwlock_trywrlock(&l)); ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l)); ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // Try reader lock ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l)); ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l)); ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // Try writer lock after unlock ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // EDEADLK in "read after write" ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // EDEADLK in "write after write" ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); ASSERT_EQ(0, pthread_rwlock_destroy(&l)); } static void WaitUntilThreadSleep(std::atomic<pid_t>& pid) { while (pid == 0) { usleep(1000); } std::string filename = android::base::StringPrintf("/proc/%d/stat", pid.load()); std::regex regex {R"(\s+S\s+)"}; while (true) { std::string content; ASSERT_TRUE(android::base::ReadFileToString(filename, &content)); if (std::regex_search(content, regex)) { break; } usleep(1000); } } struct RwlockWakeupHelperArg { pthread_rwlock_t lock; enum Progress { LOCK_INITIALIZED, LOCK_WAITING, LOCK_RELEASED, LOCK_ACCESSED }; std::atomic<Progress> progress; std::atomic<pid_t> tid; }; static void pthread_rwlock_reader_wakeup_writer_helper(RwlockWakeupHelperArg* arg) { arg->tid = gettid(); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress); arg->progress = RwlockWakeupHelperArg::LOCK_WAITING; ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&arg->lock)); ASSERT_EQ(0, pthread_rwlock_wrlock(&arg->lock)); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress); ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock)); arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED; } TEST(pthread, pthread_rwlock_reader_wakeup_writer) { RwlockWakeupHelperArg wakeup_arg; ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL)); ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock)); wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED; wakeup_arg.tid = 0; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, NULL, reinterpret_cast<void* (*)(void*)>(pthread_rwlock_reader_wakeup_writer_helper), &wakeup_arg)); WaitUntilThreadSleep(wakeup_arg.tid); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress); wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED; ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock)); ASSERT_EQ(0, pthread_join(thread, NULL)); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress); ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock)); } static void pthread_rwlock_writer_wakeup_reader_helper(RwlockWakeupHelperArg* arg) { arg->tid = gettid(); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress); arg->progress = RwlockWakeupHelperArg::LOCK_WAITING; ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&arg->lock)); ASSERT_EQ(0, pthread_rwlock_rdlock(&arg->lock)); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress); ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock)); arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED; } TEST(pthread, pthread_rwlock_writer_wakeup_reader) { RwlockWakeupHelperArg wakeup_arg; ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, NULL)); ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock)); wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED; wakeup_arg.tid = 0; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, NULL, reinterpret_cast<void* (*)(void*)>(pthread_rwlock_writer_wakeup_reader_helper), &wakeup_arg)); WaitUntilThreadSleep(wakeup_arg.tid); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress); wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED; ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock)); ASSERT_EQ(0, pthread_join(thread, NULL)); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress); ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock)); } class RwlockKindTestHelper { private: struct ThreadArg { RwlockKindTestHelper* helper; std::atomic<pid_t>& tid; ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid) : helper(helper), tid(tid) { } }; public: pthread_rwlock_t lock; public: RwlockKindTestHelper(int kind_type) { InitRwlock(kind_type); } ~RwlockKindTestHelper() { DestroyRwlock(); } void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) { tid = 0; ThreadArg* arg = new ThreadArg(this, tid); ASSERT_EQ(0, pthread_create(&thread, NULL, reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg)); } void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) { tid = 0; ThreadArg* arg = new ThreadArg(this, tid); ASSERT_EQ(0, pthread_create(&thread, NULL, reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg)); } private: void InitRwlock(int kind_type) { pthread_rwlockattr_t attr; ASSERT_EQ(0, pthread_rwlockattr_init(&attr)); ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type)); ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr)); ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr)); } void DestroyRwlock() { ASSERT_EQ(0, pthread_rwlock_destroy(&lock)); } static void WriterThreadFn(ThreadArg* arg) { arg->tid = gettid(); RwlockKindTestHelper* helper = arg->helper; ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock)); ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock)); delete arg; } static void ReaderThreadFn(ThreadArg* arg) { arg->tid = gettid(); RwlockKindTestHelper* helper = arg->helper; ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock)); ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock)); delete arg; } }; TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) { RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP); ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock)); pthread_t writer_thread; std::atomic<pid_t> writer_tid; helper.CreateWriterThread(writer_thread, writer_tid); WaitUntilThreadSleep(writer_tid); pthread_t reader_thread; std::atomic<pid_t> reader_tid; helper.CreateReaderThread(reader_thread, reader_tid); ASSERT_EQ(0, pthread_join(reader_thread, NULL)); ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock)); ASSERT_EQ(0, pthread_join(writer_thread, NULL)); } TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) { RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP); ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock)); pthread_t writer_thread; std::atomic<pid_t> writer_tid; helper.CreateWriterThread(writer_thread, writer_tid); WaitUntilThreadSleep(writer_tid); pthread_t reader_thread; std::atomic<pid_t> reader_tid; helper.CreateReaderThread(reader_thread, reader_tid); WaitUntilThreadSleep(reader_tid); ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock)); ASSERT_EQ(0, pthread_join(writer_thread, NULL)); ASSERT_EQ(0, pthread_join(reader_thread, NULL)); } static int g_once_fn_call_count = 0; static void OnceFn() { ++g_once_fn_call_count; } TEST(pthread, pthread_once_smoke) { pthread_once_t once_control = PTHREAD_ONCE_INIT; ASSERT_EQ(0, pthread_once(&once_control, OnceFn)); ASSERT_EQ(0, pthread_once(&once_control, OnceFn)); ASSERT_EQ(1, g_once_fn_call_count); } static std::string pthread_once_1934122_result = ""; static void Routine2() { pthread_once_1934122_result += "2"; } static void Routine1() { pthread_once_t once_control_2 = PTHREAD_ONCE_INIT; pthread_once_1934122_result += "1"; pthread_once(&once_control_2, &Routine2); } TEST(pthread, pthread_once_1934122) { // Very old versions of Android couldn't call pthread_once from a // pthread_once init routine. http://b/1934122. pthread_once_t once_control_1 = PTHREAD_ONCE_INIT; ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1)); ASSERT_EQ("12", pthread_once_1934122_result); } static int g_atfork_prepare_calls = 0; static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; } static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; } static int g_atfork_parent_calls = 0; static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; } static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; } static int g_atfork_child_calls = 0; static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; } static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; } TEST(pthread, pthread_atfork_smoke) { ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1)); ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2)); int pid = fork(); ASSERT_NE(-1, pid) << strerror(errno); // Child and parent calls are made in the order they were registered. if (pid == 0) { ASSERT_EQ(12, g_atfork_child_calls); _exit(0); } ASSERT_EQ(12, g_atfork_parent_calls); // Prepare calls are made in the reverse order. ASSERT_EQ(21, g_atfork_prepare_calls); int status; ASSERT_EQ(pid, waitpid(pid, &status, 0)); } TEST(pthread, pthread_attr_getscope) { pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); int scope; ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope)); ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope); } TEST(pthread, pthread_condattr_init) { pthread_condattr_t attr; pthread_condattr_init(&attr); clockid_t clock; ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); ASSERT_EQ(CLOCK_REALTIME, clock); int pshared; ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared)); ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared); } TEST(pthread, pthread_condattr_setclock) { pthread_condattr_t attr; pthread_condattr_init(&attr); ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME)); clockid_t clock; ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); ASSERT_EQ(CLOCK_REALTIME, clock); ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)); ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); ASSERT_EQ(CLOCK_MONOTONIC, clock); ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID)); } TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) { #if defined(__BIONIC__) pthread_condattr_t attr; pthread_condattr_init(&attr); ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)); ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED)); pthread_cond_t cond_var; ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr)); ASSERT_EQ(0, pthread_cond_signal(&cond_var)); ASSERT_EQ(0, pthread_cond_broadcast(&cond_var)); attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private)); clockid_t clock; ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); ASSERT_EQ(CLOCK_MONOTONIC, clock); int pshared; ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared)); ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared); #else // !defined(__BIONIC__) GTEST_LOG_(INFO) << "This tests a bionic implementation detail.\n"; #endif // !defined(__BIONIC__) } class pthread_CondWakeupTest : public ::testing::Test { protected: pthread_mutex_t mutex; pthread_cond_t cond; enum Progress { INITIALIZED, WAITING, SIGNALED, FINISHED, }; std::atomic<Progress> progress; pthread_t thread; protected: virtual void SetUp() { ASSERT_EQ(0, pthread_mutex_init(&mutex, NULL)); ASSERT_EQ(0, pthread_cond_init(&cond, NULL)); progress = INITIALIZED; ASSERT_EQ(0, pthread_create(&thread, NULL, reinterpret_cast<void* (*)(void*)>(WaitThreadFn), this)); } virtual void TearDown() { ASSERT_EQ(0, pthread_join(thread, NULL)); ASSERT_EQ(FINISHED, progress); ASSERT_EQ(0, pthread_cond_destroy(&cond)); ASSERT_EQ(0, pthread_mutex_destroy(&mutex)); } void SleepUntilProgress(Progress expected_progress) { while (progress != expected_progress) { usleep(5000); } usleep(5000); } private: static void WaitThreadFn(pthread_CondWakeupTest* test) { ASSERT_EQ(0, pthread_mutex_lock(&test->mutex)); test->progress = WAITING; while (test->progress == WAITING) { ASSERT_EQ(0, pthread_cond_wait(&test->cond, &test->mutex)); } ASSERT_EQ(SIGNALED, test->progress); test->progress = FINISHED; ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex)); } }; TEST_F(pthread_CondWakeupTest, signal) { SleepUntilProgress(WAITING); progress = SIGNALED; pthread_cond_signal(&cond); } TEST_F(pthread_CondWakeupTest, broadcast) { SleepUntilProgress(WAITING); progress = SIGNALED; pthread_cond_broadcast(&cond); } TEST(pthread, pthread_mutex_timedlock) { pthread_mutex_t m; ASSERT_EQ(0, pthread_mutex_init(&m, NULL)); // If the mutex is already locked, pthread_mutex_timedlock should time out. ASSERT_EQ(0, pthread_mutex_lock(&m)); timespec ts; ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); ts.tv_nsec += 1; ASSERT_EQ(ETIMEDOUT, pthread_mutex_timedlock(&m, &ts)); // If the mutex is unlocked, pthread_mutex_timedlock should succeed. ASSERT_EQ(0, pthread_mutex_unlock(&m)); ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); ts.tv_nsec += 1; ASSERT_EQ(0, pthread_mutex_timedlock(&m, &ts)); ASSERT_EQ(0, pthread_mutex_unlock(&m)); ASSERT_EQ(0, pthread_mutex_destroy(&m)); } TEST(pthread, pthread_attr_getstack__main_thread) { // This test is only meaningful for the main thread, so make sure we're running on it! ASSERT_EQ(getpid(), syscall(__NR_gettid)); // Get the main thread's attributes. pthread_attr_t attributes; ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes)); // Check that we correctly report that the main thread has no guard page. size_t guard_size; ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); ASSERT_EQ(0U, guard_size); // The main thread has no guard page. // Get the stack base and the stack size (both ways). void* stack_base; size_t stack_size; ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size)); size_t stack_size2; ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2)); // The two methods of asking for the stack size should agree. EXPECT_EQ(stack_size, stack_size2); // What does /proc/self/maps' [stack] line say? void* maps_stack_hi = NULL; FILE* fp = fopen("/proc/self/maps", "r"); ASSERT_TRUE(fp != NULL); char line[BUFSIZ]; while (fgets(line, sizeof(line), fp) != NULL) { uintptr_t lo, hi; char name[10]; sscanf(line, "%" PRIxPTR "-%" PRIxPTR " %*4s %*x %*x:%*x %*d %10s", &lo, &hi, name); if (strcmp(name, "[stack]") == 0) { maps_stack_hi = reinterpret_cast<void*>(hi); break; } } fclose(fp); // The stack size should correspond to RLIMIT_STACK. rlimit rl; ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl)); uint64_t original_rlim_cur = rl.rlim_cur; #if defined(__BIONIC__) if (rl.rlim_cur == RLIM_INFINITY) { rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB. } #endif EXPECT_EQ(rl.rlim_cur, stack_size); auto guard = make_scope_guard([&rl, original_rlim_cur]() { rl.rlim_cur = original_rlim_cur; ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl)); }); // The high address of the /proc/self/maps [stack] region should equal stack_base + stack_size. // Remember that the stack grows down (and is mapped in on demand), so the low address of the // region isn't very interesting. EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size); // // What if RLIMIT_STACK is smaller than the stack's current extent? // rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already. rl.rlim_max = RLIM_INFINITY; ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl)); ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes)); ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size)); ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2)); EXPECT_EQ(stack_size, stack_size2); ASSERT_EQ(1024U, stack_size); // // What if RLIMIT_STACK isn't a whole number of pages? // rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages. rl.rlim_max = RLIM_INFINITY; ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl)); ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes)); ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size)); ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2)); EXPECT_EQ(stack_size, stack_size2); ASSERT_EQ(6666U, stack_size); } static void pthread_attr_getstack_18908062_helper(void*) { char local_variable; pthread_attr_t attributes; pthread_getattr_np(pthread_self(), &attributes); void* stack_base; size_t stack_size; pthread_attr_getstack(&attributes, &stack_base, &stack_size); // Test whether &local_variable is in [stack_base, stack_base + stack_size). ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable); ASSERT_LT(&local_variable, reinterpret_cast<char*>(stack_base) + stack_size); } // Check whether something on stack is in the range of // [stack_base, stack_base + stack_size). see b/18908062. TEST(pthread, pthread_attr_getstack_18908062) { pthread_t t; ASSERT_EQ(0, pthread_create(&t, NULL, reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper), NULL)); pthread_join(t, NULL); } #if defined(__BIONIC__) static void* pthread_gettid_np_helper(void* arg) { *reinterpret_cast<pid_t*>(arg) = gettid(); return NULL; } #endif TEST(pthread, pthread_gettid_np) { #if defined(__BIONIC__) ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self())); pid_t t_gettid_result; pthread_t t; pthread_create(&t, NULL, pthread_gettid_np_helper, &t_gettid_result); pid_t t_pthread_gettid_np_result = pthread_gettid_np(t); pthread_join(t, NULL); ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result); #else GTEST_LOG_(INFO) << "This test does nothing.\n"; #endif } static size_t cleanup_counter = 0; static void AbortCleanupRoutine(void*) { abort(); } static void CountCleanupRoutine(void*) { ++cleanup_counter; } static void PthreadCleanupTester() { pthread_cleanup_push(CountCleanupRoutine, NULL); pthread_cleanup_push(CountCleanupRoutine, NULL); pthread_cleanup_push(AbortCleanupRoutine, NULL); pthread_cleanup_pop(0); // Pop the abort without executing it. pthread_cleanup_pop(1); // Pop one count while executing it. ASSERT_EQ(1U, cleanup_counter); // Exit while the other count is still on the cleanup stack. pthread_exit(NULL); // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced. pthread_cleanup_pop(0); } static void* PthreadCleanupStartRoutine(void*) { PthreadCleanupTester(); return NULL; } TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) { pthread_t t; ASSERT_EQ(0, pthread_create(&t, NULL, PthreadCleanupStartRoutine, NULL)); pthread_join(t, NULL); ASSERT_EQ(2U, cleanup_counter); } TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) { ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT); } TEST(pthread, pthread_mutexattr_gettype) { pthread_mutexattr_t attr; ASSERT_EQ(0, pthread_mutexattr_init(&attr)); int attr_type; ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL)); ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type)); ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type); ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK)); ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type)); ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type); ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)); ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type)); ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type); ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); } struct PthreadMutex { pthread_mutex_t lock; PthreadMutex(int mutex_type) { init(mutex_type); } ~PthreadMutex() { destroy(); } private: void init(int mutex_type) { pthread_mutexattr_t attr; ASSERT_EQ(0, pthread_mutexattr_init(&attr)); ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type)); ASSERT_EQ(0, pthread_mutex_init(&lock, &attr)); ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); } void destroy() { ASSERT_EQ(0, pthread_mutex_destroy(&lock)); } DISALLOW_COPY_AND_ASSIGN(PthreadMutex); }; TEST(pthread, pthread_mutex_lock_NORMAL) { PthreadMutex m(PTHREAD_MUTEX_NORMAL); ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); } TEST(pthread, pthread_mutex_lock_ERRORCHECK) { PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK); ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(0, pthread_mutex_trylock(&m.lock)); ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock)); } TEST(pthread, pthread_mutex_lock_RECURSIVE) { PthreadMutex m(PTHREAD_MUTEX_RECURSIVE); ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(0, pthread_mutex_trylock(&m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock)); } TEST(pthread, pthread_mutex_init_same_as_static_initializers) { pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER; PthreadMutex m1(PTHREAD_MUTEX_NORMAL); ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t))); pthread_mutex_destroy(&lock_normal); pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP; PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK); ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t))); pthread_mutex_destroy(&lock_errorcheck); pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE); ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t))); ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive)); } class MutexWakeupHelper { private: PthreadMutex m; enum Progress { LOCK_INITIALIZED, LOCK_WAITING, LOCK_RELEASED, LOCK_ACCESSED }; std::atomic<Progress> progress; std::atomic<pid_t> tid; static void thread_fn(MutexWakeupHelper* helper) { helper->tid = gettid(); ASSERT_EQ(LOCK_INITIALIZED, helper->progress); helper->progress = LOCK_WAITING; ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock)); ASSERT_EQ(LOCK_RELEASED, helper->progress); ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock)); helper->progress = LOCK_ACCESSED; } public: MutexWakeupHelper(int mutex_type) : m(mutex_type) { } void test() { ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); progress = LOCK_INITIALIZED; tid = 0; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, NULL, reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this)); WaitUntilThreadSleep(tid); ASSERT_EQ(LOCK_WAITING, progress); progress = LOCK_RELEASED; ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(0, pthread_join(thread, NULL)); ASSERT_EQ(LOCK_ACCESSED, progress); } }; TEST(pthread, pthread_mutex_NORMAL_wakeup) { MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL); helper.test(); } TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) { MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK); helper.test(); } TEST(pthread, pthread_mutex_RECURSIVE_wakeup) { MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE); helper.test(); } TEST(pthread, pthread_mutex_owner_tid_limit) { #if defined(__BIONIC__) && !defined(__LP64__) FILE* fp = fopen("/proc/sys/kernel/pid_max", "r"); ASSERT_TRUE(fp != NULL); long pid_max; ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max)); fclose(fp); // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid. ASSERT_LE(pid_max, 65536); #else GTEST_LOG_(INFO) << "This test does nothing as 32-bit tid is supported by pthread_mutex.\n"; #endif } class StrictAlignmentAllocator { public: void* allocate(size_t size, size_t alignment) { char* p = new char[size + alignment * 2]; allocated_array.push_back(p); while (!is_strict_aligned(p, alignment)) { ++p; } return p; } ~StrictAlignmentAllocator() { for (auto& p : allocated_array) { delete [] p; } } private: bool is_strict_aligned(char* p, size_t alignment) { return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment; } std::vector<char*> allocated_array; }; TEST(pthread, pthread_types_allow_four_bytes_alignment) { #if defined(__BIONIC__) // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types. StrictAlignmentAllocator allocator; pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>( allocator.allocate(sizeof(pthread_mutex_t), 4)); ASSERT_EQ(0, pthread_mutex_init(mutex, NULL)); ASSERT_EQ(0, pthread_mutex_lock(mutex)); ASSERT_EQ(0, pthread_mutex_unlock(mutex)); ASSERT_EQ(0, pthread_mutex_destroy(mutex)); pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>( allocator.allocate(sizeof(pthread_cond_t), 4)); ASSERT_EQ(0, pthread_cond_init(cond, NULL)); ASSERT_EQ(0, pthread_cond_signal(cond)); ASSERT_EQ(0, pthread_cond_broadcast(cond)); ASSERT_EQ(0, pthread_cond_destroy(cond)); pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>( allocator.allocate(sizeof(pthread_rwlock_t), 4)); ASSERT_EQ(0, pthread_rwlock_init(rwlock, NULL)); ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock)); ASSERT_EQ(0, pthread_rwlock_unlock(rwlock)); ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock)); ASSERT_EQ(0, pthread_rwlock_unlock(rwlock)); ASSERT_EQ(0, pthread_rwlock_destroy(rwlock)); #else GTEST_LOG_(INFO) << "This test tests bionic implementation details."; #endif } TEST(pthread, pthread_mutex_lock_null_32) { #if defined(__BIONIC__) && !defined(__LP64__) ASSERT_EQ(EINVAL, pthread_mutex_lock(NULL)); #else GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices."; #endif } TEST(pthread, pthread_mutex_unlock_null_32) { #if defined(__BIONIC__) && !defined(__LP64__) ASSERT_EQ(EINVAL, pthread_mutex_unlock(NULL)); #else GTEST_LOG_(INFO) << "This test tests bionic implementation details on 32 bit devices."; #endif } TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) { #if defined(__BIONIC__) && defined(__LP64__) pthread_mutex_t* null_value = nullptr; ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), ""); #else GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices."; #endif } TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) { #if defined(__BIONIC__) && defined(__LP64__) pthread_mutex_t* null_value = nullptr; ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), ""); #else GTEST_LOG_(INFO) << "This test tests bionic implementation details on 64 bit devices."; #endif }
[ "khanhduytran0@users.noreply.github.com" ]
khanhduytran0@users.noreply.github.com
870eee5ae64a5a608bb1ecec23302aa04e7946cf
8e9f67d56cab10affc9ee8912d36435e6cd06245
/Sandbox/src/world/particle/particles.cpp
788a44bc9436133c258bdb84ee2e859ee0add043
[]
no_license
Cooble/NiceDay
79d4fd88d5ee40b025790bf3b7a2fd80fa966333
56b507b1f853240493affae82ad792f8054d635a
refs/heads/master
2023-08-18T23:21:44.348957
2023-01-20T18:23:07
2023-01-20T18:23:07
179,539,325
14
0
null
2021-05-12T17:34:09
2019-04-04T16:52:23
JavaScript
UTF-8
C++
false
false
2,107
cpp
#include "ndpch.h" #include "particles.h" #include "core/NBT.h" #define PARTICATOR(var) var= PARTICLE_ID(#var) using namespace nd; namespace ParticleList { void initDefaultParticles(ParticleRegistry& p) { NBT t; if (!NBT::loadFromFile(ND_RESLOC("res/registry/particles/particles.json"), t)) return; std::string names; names.reserve(100); if (t.isMap()) { for (auto& pair : t.maps()) { auto& item = pair.second; std::string name=pair.first; names += ", "; names += name; int frameCount = 1; int ticksPerFrame = 10000; float rotationSpeed = 0; glm::vec2 s(1); item.load("size", s); item.load("frameCount",frameCount); item.load("ticksPerFrame", ticksPerFrame); item.load("rotationSpeed", rotationSpeed); ParticleRegistry::get().registerTemplate(ParticleRegistry::ParticleTemplate(name, half_int(s.x,s.y), frameCount, ticksPerFrame, rotationSpeed)); } } ND_TRACE("Particles loaded: {}", names.substr(2)); PARTICATOR(dot); PARTICATOR(line); PARTICATOR(torch_smoke); PARTICATOR(torch_fire); PARTICATOR(bulletShatter); PARTICATOR(block); PARTICATOR(note); /*dot = PARTICLE_ID("dot"); ParticleRegistry::get().registerTemplate(ParticleRegistry::ParticleTemplate("dot", half_int(1, 1), 4, 20, 0)); line = ParticleRegistry::get().registerTemplate(ParticleRegistry::ParticleTemplate("line", half_int(2, 1), 1, 0, 0)); torch_smoke = ParticleRegistry::get().registerTemplate(ParticleRegistry::ParticleTemplate("torch_smoke", half_int(1, 1), 5, 60,0)); torch_fire = ParticleRegistry::get().registerTemplate(ParticleRegistry::ParticleTemplate("torch_fire", half_int(1, 1), 4, 30, 0)); bulletShatter = ParticleRegistry::get().registerTemplate(ParticleRegistry::ParticleTemplate("bulletShatter", half_int(1,1), 2, 60, 0)); block = ParticleRegistry::get().registerTemplate(ParticleRegistry::ParticleTemplate("block", half_int(1, 1), 2, 35,0)); note = ParticleRegistry::get().registerTemplate(ParticleRegistry::ParticleTemplate("note", half_int(1, 1), 4, 100000,0));*/ } }
[ "minekoza@gmail.com" ]
minekoza@gmail.com
ee972eca9f405aa156aec1d09ac2914ea5ebf701
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/wedata/src/v20210820/model/RuleGroupExecResult.cpp
8fcc62753be7d9f349f6f0321b631591a4553584
[ "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
16,548
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/wedata/v20210820/model/RuleGroupExecResult.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Wedata::V20210820::Model; using namespace std; RuleGroupExecResult::RuleGroupExecResult() : m_ruleGroupExecIdHasBeenSet(false), m_ruleGroupIdHasBeenSet(false), m_triggerTypeHasBeenSet(false), m_execTimeHasBeenSet(false), m_statusHasBeenSet(false), m_alarmRuleCountHasBeenSet(false), m_totalRuleCountHasBeenSet(false), m_tableOwnerNameHasBeenSet(false), m_tableNameHasBeenSet(false), m_tableIdHasBeenSet(false), m_databaseIdHasBeenSet(false), m_datasourceIdHasBeenSet(false), m_permissionHasBeenSet(false), m_execDetailHasBeenSet(false), m_engineTypeHasBeenSet(false) { } CoreInternalOutcome RuleGroupExecResult::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("RuleGroupExecId") && !value["RuleGroupExecId"].IsNull()) { if (!value["RuleGroupExecId"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `RuleGroupExecResult.RuleGroupExecId` IsUint64=false incorrectly").SetRequestId(requestId)); } m_ruleGroupExecId = value["RuleGroupExecId"].GetUint64(); m_ruleGroupExecIdHasBeenSet = true; } if (value.HasMember("RuleGroupId") && !value["RuleGroupId"].IsNull()) { if (!value["RuleGroupId"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `RuleGroupExecResult.RuleGroupId` IsUint64=false incorrectly").SetRequestId(requestId)); } m_ruleGroupId = value["RuleGroupId"].GetUint64(); m_ruleGroupIdHasBeenSet = true; } if (value.HasMember("TriggerType") && !value["TriggerType"].IsNull()) { if (!value["TriggerType"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `RuleGroupExecResult.TriggerType` IsUint64=false incorrectly").SetRequestId(requestId)); } m_triggerType = value["TriggerType"].GetUint64(); m_triggerTypeHasBeenSet = true; } if (value.HasMember("ExecTime") && !value["ExecTime"].IsNull()) { if (!value["ExecTime"].IsString()) { return CoreInternalOutcome(Core::Error("response `RuleGroupExecResult.ExecTime` IsString=false incorrectly").SetRequestId(requestId)); } m_execTime = string(value["ExecTime"].GetString()); m_execTimeHasBeenSet = true; } if (value.HasMember("Status") && !value["Status"].IsNull()) { if (!value["Status"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `RuleGroupExecResult.Status` IsUint64=false incorrectly").SetRequestId(requestId)); } m_status = value["Status"].GetUint64(); m_statusHasBeenSet = true; } if (value.HasMember("AlarmRuleCount") && !value["AlarmRuleCount"].IsNull()) { if (!value["AlarmRuleCount"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `RuleGroupExecResult.AlarmRuleCount` IsUint64=false incorrectly").SetRequestId(requestId)); } m_alarmRuleCount = value["AlarmRuleCount"].GetUint64(); m_alarmRuleCountHasBeenSet = true; } if (value.HasMember("TotalRuleCount") && !value["TotalRuleCount"].IsNull()) { if (!value["TotalRuleCount"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `RuleGroupExecResult.TotalRuleCount` IsUint64=false incorrectly").SetRequestId(requestId)); } m_totalRuleCount = value["TotalRuleCount"].GetUint64(); m_totalRuleCountHasBeenSet = true; } if (value.HasMember("TableOwnerName") && !value["TableOwnerName"].IsNull()) { if (!value["TableOwnerName"].IsString()) { return CoreInternalOutcome(Core::Error("response `RuleGroupExecResult.TableOwnerName` IsString=false incorrectly").SetRequestId(requestId)); } m_tableOwnerName = string(value["TableOwnerName"].GetString()); m_tableOwnerNameHasBeenSet = true; } if (value.HasMember("TableName") && !value["TableName"].IsNull()) { if (!value["TableName"].IsString()) { return CoreInternalOutcome(Core::Error("response `RuleGroupExecResult.TableName` IsString=false incorrectly").SetRequestId(requestId)); } m_tableName = string(value["TableName"].GetString()); m_tableNameHasBeenSet = true; } if (value.HasMember("TableId") && !value["TableId"].IsNull()) { if (!value["TableId"].IsString()) { return CoreInternalOutcome(Core::Error("response `RuleGroupExecResult.TableId` IsString=false incorrectly").SetRequestId(requestId)); } m_tableId = string(value["TableId"].GetString()); m_tableIdHasBeenSet = true; } if (value.HasMember("DatabaseId") && !value["DatabaseId"].IsNull()) { if (!value["DatabaseId"].IsString()) { return CoreInternalOutcome(Core::Error("response `RuleGroupExecResult.DatabaseId` IsString=false incorrectly").SetRequestId(requestId)); } m_databaseId = string(value["DatabaseId"].GetString()); m_databaseIdHasBeenSet = true; } if (value.HasMember("DatasourceId") && !value["DatasourceId"].IsNull()) { if (!value["DatasourceId"].IsString()) { return CoreInternalOutcome(Core::Error("response `RuleGroupExecResult.DatasourceId` IsString=false incorrectly").SetRequestId(requestId)); } m_datasourceId = string(value["DatasourceId"].GetString()); m_datasourceIdHasBeenSet = true; } if (value.HasMember("Permission") && !value["Permission"].IsNull()) { if (!value["Permission"].IsBool()) { return CoreInternalOutcome(Core::Error("response `RuleGroupExecResult.Permission` IsBool=false incorrectly").SetRequestId(requestId)); } m_permission = value["Permission"].GetBool(); m_permissionHasBeenSet = true; } if (value.HasMember("ExecDetail") && !value["ExecDetail"].IsNull()) { if (!value["ExecDetail"].IsString()) { return CoreInternalOutcome(Core::Error("response `RuleGroupExecResult.ExecDetail` IsString=false incorrectly").SetRequestId(requestId)); } m_execDetail = string(value["ExecDetail"].GetString()); m_execDetailHasBeenSet = true; } if (value.HasMember("EngineType") && !value["EngineType"].IsNull()) { if (!value["EngineType"].IsString()) { return CoreInternalOutcome(Core::Error("response `RuleGroupExecResult.EngineType` IsString=false incorrectly").SetRequestId(requestId)); } m_engineType = string(value["EngineType"].GetString()); m_engineTypeHasBeenSet = true; } return CoreInternalOutcome(true); } void RuleGroupExecResult::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_ruleGroupExecIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RuleGroupExecId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_ruleGroupExecId, allocator); } if (m_ruleGroupIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RuleGroupId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_ruleGroupId, allocator); } if (m_triggerTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TriggerType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_triggerType, allocator); } if (m_execTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ExecTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_execTime.c_str(), allocator).Move(), allocator); } if (m_statusHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Status"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_status, allocator); } if (m_alarmRuleCountHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AlarmRuleCount"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_alarmRuleCount, allocator); } if (m_totalRuleCountHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TotalRuleCount"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_totalRuleCount, allocator); } if (m_tableOwnerNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TableOwnerName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_tableOwnerName.c_str(), allocator).Move(), allocator); } if (m_tableNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TableName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_tableName.c_str(), allocator).Move(), allocator); } if (m_tableIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TableId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_tableId.c_str(), allocator).Move(), allocator); } if (m_databaseIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DatabaseId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_databaseId.c_str(), allocator).Move(), allocator); } if (m_datasourceIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DatasourceId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_datasourceId.c_str(), allocator).Move(), allocator); } if (m_permissionHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Permission"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_permission, allocator); } if (m_execDetailHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ExecDetail"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_execDetail.c_str(), allocator).Move(), allocator); } if (m_engineTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EngineType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_engineType.c_str(), allocator).Move(), allocator); } } uint64_t RuleGroupExecResult::GetRuleGroupExecId() const { return m_ruleGroupExecId; } void RuleGroupExecResult::SetRuleGroupExecId(const uint64_t& _ruleGroupExecId) { m_ruleGroupExecId = _ruleGroupExecId; m_ruleGroupExecIdHasBeenSet = true; } bool RuleGroupExecResult::RuleGroupExecIdHasBeenSet() const { return m_ruleGroupExecIdHasBeenSet; } uint64_t RuleGroupExecResult::GetRuleGroupId() const { return m_ruleGroupId; } void RuleGroupExecResult::SetRuleGroupId(const uint64_t& _ruleGroupId) { m_ruleGroupId = _ruleGroupId; m_ruleGroupIdHasBeenSet = true; } bool RuleGroupExecResult::RuleGroupIdHasBeenSet() const { return m_ruleGroupIdHasBeenSet; } uint64_t RuleGroupExecResult::GetTriggerType() const { return m_triggerType; } void RuleGroupExecResult::SetTriggerType(const uint64_t& _triggerType) { m_triggerType = _triggerType; m_triggerTypeHasBeenSet = true; } bool RuleGroupExecResult::TriggerTypeHasBeenSet() const { return m_triggerTypeHasBeenSet; } string RuleGroupExecResult::GetExecTime() const { return m_execTime; } void RuleGroupExecResult::SetExecTime(const string& _execTime) { m_execTime = _execTime; m_execTimeHasBeenSet = true; } bool RuleGroupExecResult::ExecTimeHasBeenSet() const { return m_execTimeHasBeenSet; } uint64_t RuleGroupExecResult::GetStatus() const { return m_status; } void RuleGroupExecResult::SetStatus(const uint64_t& _status) { m_status = _status; m_statusHasBeenSet = true; } bool RuleGroupExecResult::StatusHasBeenSet() const { return m_statusHasBeenSet; } uint64_t RuleGroupExecResult::GetAlarmRuleCount() const { return m_alarmRuleCount; } void RuleGroupExecResult::SetAlarmRuleCount(const uint64_t& _alarmRuleCount) { m_alarmRuleCount = _alarmRuleCount; m_alarmRuleCountHasBeenSet = true; } bool RuleGroupExecResult::AlarmRuleCountHasBeenSet() const { return m_alarmRuleCountHasBeenSet; } uint64_t RuleGroupExecResult::GetTotalRuleCount() const { return m_totalRuleCount; } void RuleGroupExecResult::SetTotalRuleCount(const uint64_t& _totalRuleCount) { m_totalRuleCount = _totalRuleCount; m_totalRuleCountHasBeenSet = true; } bool RuleGroupExecResult::TotalRuleCountHasBeenSet() const { return m_totalRuleCountHasBeenSet; } string RuleGroupExecResult::GetTableOwnerName() const { return m_tableOwnerName; } void RuleGroupExecResult::SetTableOwnerName(const string& _tableOwnerName) { m_tableOwnerName = _tableOwnerName; m_tableOwnerNameHasBeenSet = true; } bool RuleGroupExecResult::TableOwnerNameHasBeenSet() const { return m_tableOwnerNameHasBeenSet; } string RuleGroupExecResult::GetTableName() const { return m_tableName; } void RuleGroupExecResult::SetTableName(const string& _tableName) { m_tableName = _tableName; m_tableNameHasBeenSet = true; } bool RuleGroupExecResult::TableNameHasBeenSet() const { return m_tableNameHasBeenSet; } string RuleGroupExecResult::GetTableId() const { return m_tableId; } void RuleGroupExecResult::SetTableId(const string& _tableId) { m_tableId = _tableId; m_tableIdHasBeenSet = true; } bool RuleGroupExecResult::TableIdHasBeenSet() const { return m_tableIdHasBeenSet; } string RuleGroupExecResult::GetDatabaseId() const { return m_databaseId; } void RuleGroupExecResult::SetDatabaseId(const string& _databaseId) { m_databaseId = _databaseId; m_databaseIdHasBeenSet = true; } bool RuleGroupExecResult::DatabaseIdHasBeenSet() const { return m_databaseIdHasBeenSet; } string RuleGroupExecResult::GetDatasourceId() const { return m_datasourceId; } void RuleGroupExecResult::SetDatasourceId(const string& _datasourceId) { m_datasourceId = _datasourceId; m_datasourceIdHasBeenSet = true; } bool RuleGroupExecResult::DatasourceIdHasBeenSet() const { return m_datasourceIdHasBeenSet; } bool RuleGroupExecResult::GetPermission() const { return m_permission; } void RuleGroupExecResult::SetPermission(const bool& _permission) { m_permission = _permission; m_permissionHasBeenSet = true; } bool RuleGroupExecResult::PermissionHasBeenSet() const { return m_permissionHasBeenSet; } string RuleGroupExecResult::GetExecDetail() const { return m_execDetail; } void RuleGroupExecResult::SetExecDetail(const string& _execDetail) { m_execDetail = _execDetail; m_execDetailHasBeenSet = true; } bool RuleGroupExecResult::ExecDetailHasBeenSet() const { return m_execDetailHasBeenSet; } string RuleGroupExecResult::GetEngineType() const { return m_engineType; } void RuleGroupExecResult::SetEngineType(const string& _engineType) { m_engineType = _engineType; m_engineTypeHasBeenSet = true; } bool RuleGroupExecResult::EngineTypeHasBeenSet() const { return m_engineTypeHasBeenSet; }
[ "tencentcloudapi@tencent.com" ]
tencentcloudapi@tencent.com
485dfe920c006507662033cdd176a47b76f6bdb6
1a556bb3b242497131dcdb86f27756608f5a85a4
/include/meta/sequence/drop_at.hpp
1a38335b7b3c366c1eb393fb71e0a9a6fae7ed32
[ "MIT" ]
permissive
doom/meta
c66da6cccc7b9c14ecae6524d612dd6de75b3ed1
013b61f2bbf5deffec66eb3d9a927ad3f5fd9c7f
refs/heads/master
2022-05-31T20:10:49.835598
2022-05-18T22:42:40
2022-05-18T22:42:40
155,448,723
7
4
null
2019-09-21T11:27:12
2018-10-30T20:02:33
C++
UTF-8
C++
false
false
868
hpp
/* ** Created by doom on 20/01/19. */ #ifndef META_SEQUENCE_DROP_AT_HPP #define META_SEQUENCE_DROP_AT_HPP #include <meta/sequence/take.hpp> #include <meta/sequence/drop.hpp> #include <meta/sequence/concat.hpp> #include <meta/sequence/list.hpp> namespace doom::meta { namespace details { template <typename Sequence, typename Index> struct drop_at; template <typename ...Types, typename Index> struct drop_at<meta::list<Types...>, Index> { using type = meta::concat< meta::take<meta::list<Types...>, Index>, meta::drop<meta::list<Types...>, meta::plus<Index, size_constant<1>>> >; }; } template <typename Sequence, typename Index> using drop_at = typename details::drop_at<Sequence, Index>::type; } #endif /* !META_SEQUENCE_DROP_AT_HPP */
[ "clement.doumergue@epitech.eu" ]
clement.doumergue@epitech.eu
c6623c99a8034b7241969583bbc35062e63d09b7
d52765677b340a2ddaf183f88892eec38b805b05
/Source/UnrealPinball/GameCamera.h
2e7998a1928499bd73de17d5a399834463b70aca
[]
no_license
TheMaster99/UnrealPinball
1bd182f76640f9ba77acd8d5f7191daa1d5663e7
66d84732ad2d6c8f83c2716d050128722ee09669
refs/heads/master
2021-01-02T09:02:17.665216
2015-08-03T18:46:01
2015-08-03T18:46:01
40,066,427
0
0
null
null
null
null
UTF-8
C++
false
false
996
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "Components/SceneComponent.h" #include "GameCamera.generated.h" UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class UNREALPINBALL_API UGameCamera : public USceneComponent { GENERATED_BODY() public: // Sets default values for this component's properties UGameCamera(); // Called when the game starts virtual void BeginPlay() override; // Called every frame virtual void TickComponent( float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction ) override; //Empty Root Component for Attaching UPROPERTY(VisibleDefaultsOnly, Category = "Camera") class USceneComponent* BaseComponent; //Main Camera Component UPROPERTY(VisibleDefaultsOnly, Category = "Camera") class UCameraCOmponent* MainCamera; //Camera Boom (Positioning) UPROPERTY(VisibleDefaultsOnly, Category = "Camera") class USpringArmComponent* MainCameraBoom; };
[ "derekdelapeza@gmail.com" ]
derekdelapeza@gmail.com
4f7a1ace2b6e2ef506443ddbab5620435a367e5e
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/contest/1542571881.cpp
c3975fe8cbbe50782c93b4f491aea39f412ee878
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
937
cpp
#include <bits/stdc++.h> #define F first #define S second #define mp make_pair #define pb push_back #define INF 0x3f3f3f3f #define LINF 0x3f3f3f3f3f3f3f3fLL #define MAXN 100000 using namespace std; typedef long long ll; typedef vector<int> vi; typedef set<int> si; typedef pair<int,int> ii; typedef vector<ii> vii; typedef map<string,int> msi; typedef map<int,int> mi; int main(){ string ans; cin >> ans; int x; cin >> x; string t[x]; for(int i=0;i<x;i++){ cin >> t[i]; if(t[i] == ans){ printf("YES\n"); return 0; } } bool foo=false; for(int i=0;i<x;i++){ if(t[i][1]!=ans[0] )continue; foo = true; } if(!foo){ printf("NO\n"); return 0; } foo = false; for(int i=0;i<x;i++){ if(t[i][0]!=ans[1] )continue; foo = true; } if(!foo){ printf("NO\n"); return 0; } printf("YES\n"); return 0; }
[ "harshitagar1907@gmail.com" ]
harshitagar1907@gmail.com
7dca925d11da45d463198bf2640971b14c4b8e00
c910268a1ca496c239b009fabd640e80fa50df8b
/cplusplus/worker/employee.h
6b19a34fea934899737ed9f9953cf8749bc8cbb9
[]
no_license
leeelei/newprogramme
30b782cfb69ec0581026d5ff6c7a06362779bc7e
75edc9179aa1915117cf482f3630a45bee9e7931
refs/heads/master
2023-09-05T06:35:21.836457
2021-11-05T07:07:39
2021-11-05T07:07:39
420,669,756
0
0
null
null
null
null
UTF-8
C++
false
false
325
h
#ifndef _EMPLOYEE_H_ #define _EMPLOYEE_H_ #include<iostream> #include<string> #include "worker.h" using namespace std; class Employee:public Worker { public: Employee(int id,string name,int dId); //show personal information virtual void showInfo(); //get the name of department virtual string getDeptName(); }; #endif
[ "523578749@qq.com" ]
523578749@qq.com
73a763df91bb2b4bf61c78fad8f9dbc384f1032f
846d84762ddeaee925ec50eec8e2e1b83db97a12
/04_ListaLigada/ListaLigada.cpp
087a2387f4cae9283c1af4b4482eb04a20f3e14a
[]
no_license
damorais/a1lp2
1e121559032a0cf8814b2c10b3046788e988e9e9
35256e456149f38423e2c3cb8b655aec1f3bab2b
refs/heads/master
2020-05-22T02:45:37.633369
2016-11-03T11:15:18
2016-11-03T11:15:18
64,837,662
1
1
null
null
null
null
UTF-8
C++
false
false
2,394
cpp
#include <iostream> #include "ListaLigada.h" //template<typename T> //ListaLigada<T>::ListaLigada(T valor) { // this -> valor = valor; // this -> cauda = NULL; //} //ListaLigada<T>::~ListaLigadaDeStrings(){ // std::cout << "--Argh!!!! Estou derretendo!!!" << std::endl; // std::cout << "--" << this -> valor << std::endl; //} //template<typename T> //void ListaLigada<T>::remover(int posicao){ // // if(posicao == 1) // { // if(this -> cauda -> cauda == NULL) // { // delete this -> cauda; // this -> cauda = NULL; // } // else // { // ListaLigada<T> *caudaOriginal = this -> cauda; // this -> cauda = this -> cauda -> cauda; // delete caudaOriginal; // } // // } // else // { // this -> cauda -> remover(posicao - 1); // } //} //template<typename T> //void ListaLigada<T>::adicionar(T valor) { // // if(this->cauda == NULL) // this -> cauda = new ListaLigada<T>(valor); // else // this -> cauda -> adicionar(valor); //} // //template<typename T> //T ListaLigada<T>::getValorEm(int posicao) { // std::string resultado; // // if(posicao == 0) // resultado = this -> valor; // else // resultado = this -> cauda -> getValorEm(posicao - 1); // // return resultado; //} // //template <typename T> //int ListaLigada<T>::getTamanho() { // int resultado = 0; // if((this -> cauda) == NULL) // resultado = 1; // else // resultado = 1 + this -> cauda -> getTamanho(); // // return resultado; //} // //template <typename T> //std::string ListaLigada<T>::toString() { // std::string resultado = this -> valor + " | "; // // if(this->cauda != NULL) // resultado += this->cauda->toString(); // // return resultado; //} //ListaLigadaDeStrings::ListaLigadaDeStrings(std::string valor){ // this -> valor = valor; // this -> cauda = NULL; //} // // //void ListaLigadaDeStrings::adicionar(std::string valor){ // // if(this->cauda == NULL) // this -> cauda = new ListaLigadaDeStrings(valor); // else // this -> cauda -> adicionar(valor); //} // //std::string ListaLigadaDeStrings::toString(){ // std::string resultado = this -> valor + " | "; // // if(this->cauda != NULL) // resultado += this->cauda->toString(); // // return resultado; //}
[ "damorais@gmail.com" ]
damorais@gmail.com
9a77bc56303fdc8b20356bf5171814a89da4aebc
c748e73072da3aa45d89893658a761a75fc41de6
/src/rcib/MessageLoop.cc
63a974a579b26971675b103298126b8ef59913cd
[]
no_license
Qilewuqiong/rcib
6d82406e67fc12a07a21058e25b0be487eec0a93
dc0b8e98bb33a5e68285f5ca104dbfb78ae20c21
refs/heads/master
2021-01-14T08:50:56.940708
2015-12-16T02:23:15
2015-12-16T02:23:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,726
cc
// Copyright (c) 2011 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. #ifdef _WIN32 #include <windows.h> #else #include <pthread.h> #include <assert.h> #endif #include <string> #include <memory> #include <list> #include <vector> #include <queue> #include "macros.h" #include "ref_counted.h" #include "WrapperObj.h" #include "WeakPtr.h" #include "FastDelegateImpl.h" #include "time/time.h" #include "util_tools.h" #include "Event/WaitableEvent.h" #include "PendingTask.h" #include "observer_list.h" #include "thread_local.h" #include "MessagePump.h" #include "MessagePumpDefault.h" #include "MessageLoop.h" namespace base{ static base::ThreadLocalPointer<MessageLoop> tls_ptr ; void MessageLoop::AddDestructionObserver( DestructionObserver* destruction_observer) { assert(this == current()); destruction_observers_.AddObserver(destruction_observer); } void MessageLoop::RemoveDestructionObserver( DestructionObserver* destruction_observer) { assert(this == current()); destruction_observers_.RemoveObserver(destruction_observer); } MessageLoop::MessageLoop(Type type) :type_(type), running_(false), recent_time_() { Init(); pump_.reset(CreateMessagePumpForType(type)); } MessageLoop* MessageLoop::current() { return tls_ptr.Get(); } void MessageLoop::Init() { tls_ptr.Set(this); } void MessageLoop::PostTask(fastdelegate::Task<void>* task) { PostDelayedTask(task, TimeDelta()); } void MessageLoop::PostDelayedTask(fastdelegate::Task<void>* task, TimeDelta delay) { assert(delay >= TimeDelta()); do { if(delay == TimeDelta()) { PendingTask t = PendingTask(task); AppendTask(t); break; } // PendingTask t = PendingTask(task, CalculateDelayedRuntime(delay)); AppendTask(t); } while (false); pump_->ScheduleWork(); } void MessageLoop::Run() { running_ = true; pump_->Run(this); running_ = false; } void MessageLoop::Quit() { PostTask(Bind(Unretained(this), &MessageLoop::QuitInternal)); } bool MessageLoop::is_running() const { return running_; } MessagePump* MessageLoop::CreateMessagePumpForType(Type type) { assert(type == MessageLoop::TYPE_DEFAULT); if(MessageLoop::TYPE_DEFAULT == type){ return new MessagePumpDefault(); } return NULL; } void MessageLoop::AppendTask(PendingTask &task) { AutoCritSecLock<CriticalSection> lock(m_cs, false); lock.Lock(); incoming_queue_.push_back(task); } void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) { delayed_work_queue_.push(pending_task); } void MessageLoop::QuitInternal() { pump_->Quit(); } MessageLoop::~MessageLoop() { assert(this == current()); // Clean up any unprocessed tasks DeletePendingTasks(); ReloadWorkQueue(); DeletePendingTasks(); // Let interested parties have one last shot at accessing this. FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_, WillDestroyCurrentMessageLoop()); // OK, now make it so that no one can find us. tls_ptr.Set(NULL); } void MessageLoop::DeletePendingTasks() { size_t size = working_queue_.size(); for(size_t i = 0; i < size; ++i) { PendingTask pending_task = working_queue_.pick_front(); pending_task.Reset(); } while(!delayed_work_queue_.empty()) { PendingTask pending_task = delayed_work_queue_.top(); delayed_work_queue_.pop(); pending_task.Reset(); } } void MessageLoop::ReloadWorkQueue() { if(!working_queue_.empty()) return; AutoCritSecLock<CriticalSection> lock(m_cs, false); lock.Lock(); if(0 == incoming_queue_.size()) { } else { incoming_queue_.swap(working_queue_); } } bool MessageLoop::RunPendingTask(PendingTask &pending_task) { pending_task.Run(); return true; } TimeTicks MessageLoop::CalculateDelayedRuntime(TimeDelta delay) { TimeTicks delayed_run_time = TimeTicks::Now() + delay; return delayed_run_time; } bool MessageLoop::DoWork() { for(;;){ ReloadWorkQueue(); if(working_queue_.empty()) break; //Execute oldest task. do { PendingTask pending_task = working_queue_.pick_front(); if(!pending_task.delayed_run_time_.is_null()){ AddToDelayedWorkQueue(pending_task); // If we changed the topmost task, then it is time to reschedule. if(delayed_work_queue_.top().Equals(&pending_task)) pump_->ScheduleDelayedWork(pending_task.delayed_run_time_); } else { if(RunPendingTask(pending_task)) return true; } } while (!working_queue_.empty()); } //Nothing runned. return false; } bool MessageLoop::DoDelayedWork(TimeTicks* next_delayed_work_time) { if(delayed_work_queue_.empty()){ recent_time_ = *next_delayed_work_time = TimeTicks(); return false; } TimeTicks next_run_time = delayed_work_queue_.top().delayed_run_time_; if(next_run_time > recent_time_){ recent_time_ = TimeTicks::Now(); if(next_run_time > recent_time_){ *next_delayed_work_time = next_run_time; return false; } } PendingTask pending_task = delayed_work_queue_.top(); delayed_work_queue_.pop(); if(!delayed_work_queue_.empty()){ *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time_; } RunPendingTask(pending_task); return true; } bool MessageLoop::DoIdleWork() { return false; } } // end
[ "classfellow@qq.com" ]
classfellow@qq.com
5596395d6195f5fe694e0c0226b19c5b16d440fb
3ded37602d6d303e61bff401b2682f5c2b52928c
/toy/0206/Classes/Model/CBAppManager.cpp
185d4262f7f5ba1e29195e8d8b9af08634badee9
[]
no_license
CristinaBaby/Demo_CC
8ce532dcf016f21b442d8b05173a7d20c03d337e
6f6a7ff132e93271b8952b8da6884c3634f5cb59
refs/heads/master
2021-05-02T14:58:52.900119
2018-02-09T11:48:02
2018-02-09T11:48:02
120,727,659
0
0
null
null
null
null
UTF-8
C++
false
false
1,994
cpp
// // CBAppManager.cpp // ColorBook // // Created by maxiang on 4/21/15. // // #include "CBAppManager.h" #include "../Module/STSystemFunction.h" #include "PictureLayer.h" #include "../Layer/AdsLoadingLayer.h" #include "PackLayer.h" #ifdef __APPLE__ #include "TargetConditionals.h" #endif USING_NS_CC; static AppManager *s_SingletonAppManager = nullptr; AppManager* AppManager::getInstance() { if (!s_SingletonAppManager) { s_SingletonAppManager = new (std::nothrow)(AppManager); } return s_SingletonAppManager; } AppManager::AppManager():_saveTimes(0) { bool isFirstLaunch = UserDefault::getInstance()->getBoolForKey(UserDefaultKey_FirstTimeLaunchApp, true); if (isFirstLaunch) { /* if is first time launch app, DO NOT request full screen ads */ UserDefault::getInstance()->setBoolForKey(UserDefaultKey_FirstTimeLaunchApp, false); UserDefault::getInstance()->flush(); setIsFirstLaunchApp(true); } else { setIsFirstLaunchApp(false); } } AppManager::~AppManager() { s_SingletonAppManager = nullptr; } #pragma mark- Rate us logic void AppManager::rateUsLogic() { _saveTimes++; if (_saveTimes % 3 == 0) { STSystemFunction function = STSystemFunction(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) function.rating(APP_ID, "If you like this app, please rate our game!"); #else function.rating(); #endif } } #pragma mark- Ads methods void AppManager::requestCrossAd() { AdLoadingLayerBase::showLoading<AdsLoadingLayer>(true); } void AppManager::requestCrossAd(Node* parent, int zorder) { AdLoadingLayerBase::showLoading<AdsLoadingLayer>(true, parent, zorder); } void AppManager::requestFullScreenAd() { AdLoadingLayerBase::showLoading<AdsLoadingLayer>(false, nullptr, 10); } void AppManager::requestFullScreenAd(Node* parent, int zorder) { AdLoadingLayerBase::showLoading<AdsLoadingLayer>(false, parent, zorder); }
[ "wuguiling@smalltreemedia.com" ]
wuguiling@smalltreemedia.com
f84a80a8859a63b8b36714dab2617ff027dccd71
322257a202b17896dfd9f39e4a043c7a4bdc5af5
/ApplicationLogic/PointLights.cpp
53198af940c5a049ac3dcf6e3ba8139436a948e8
[]
no_license
Ashish424/ComputerGraphicsProject
8f15eb41beaab0111f465283eacf03fa353f6301
542282829696755a0a53735f9cfa09d25ec6a240
refs/heads/master
2021-01-13T00:55:34.817885
2016-03-25T13:15:40
2016-03-25T13:15:40
44,620,714
0
0
null
null
null
null
UTF-8
C++
false
false
762
cpp
// // Created by Ashish Aapan on 13/10/15. // #include "PointLights.hpp" namespace TerrainDemo { Pointlight::Pointlight(const MainCamera *cam, const TransformData &transdata, const glm::vec3 &position, const glm::vec3 &ambient, const glm::vec3 &diffuse, const glm::vec3 &specular) : GameObject(cam,transdata),position(position),ambient(ambient),diffuse(diffuse),specular(specular) { //TODO set these values option in constructor this->constant = 1.0; this->linear =0.7; this->quadratic = 1.8; } void Pointlight::InputUpdate() { } //update uniforms here as well void Pointlight::DrawGameObject() { } }
[ "ashish13024@iiitd.ac.in" ]
ashish13024@iiitd.ac.in
62992192215cbeb48e903236c031e71f1b0a536c
6aa4e917d628772824f0cf91301355a21d2bd923
/lib/OSX/OpenCV2.framework/Headers/core/eigen.hpp
c9cfeb90e7049777a414516550e8b4f82663dc25
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Yutaro0410/MPGestures
a35be8dc534640c0e1e334455b8bb08e49f9047f
ab4ffd79982335ce6a902011ffec3d80cd686416
refs/heads/master
2021-01-12T20:00:40.589856
2014-03-17T10:19:33
2014-03-17T10:19:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,465
hpp
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef __OPENCV_CORE_EIGEN_HPP__ #define __OPENCV_CORE_EIGEN_HPP__ #ifdef __cplusplus #include "OpenCV2/core/core_c.h" #include "OpenCV2/core/core.hpp" #if defined _MSC_VER && _MSC_VER >= 1200 #pragma warning( disable: 4714 ) //__forceinline is not inlined #pragma warning( disable: 4127 ) //conditional expression is constant #pragma warning( disable: 4244 ) //conversion from '__int64' to 'int', possible loss of data #endif namespace cv { template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols> void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, Mat& dst ) { if( !(src.Flags & Eigen::RowMajorBit) ) { Mat _src(src.cols(), src.rows(), DataType<_Tp>::type, (void*)src.data(), src.stride()*sizeof(_Tp)); transpose(_src, dst); } else { Mat _src(src.rows(), src.cols(), DataType<_Tp>::type, (void*)src.data(), src.stride()*sizeof(_Tp)); _src.copyTo(dst); } } template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols> void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst ) { CV_DbgAssert(src.rows == _rows && src.cols == _cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { Mat _dst(src.cols, src.rows, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); if( src.type() == _dst.type() ) transpose(src, _dst); else if( src.cols == src.rows ) { src.convertTo(_dst, _dst.type()); transpose(_dst, _dst); } else Mat(src.t()).convertTo(_dst, _dst.type()); CV_DbgAssert(_dst.data == (uchar*)dst.data()); } else { Mat _dst(src.rows, src.cols, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); src.convertTo(_dst, _dst.type()); CV_DbgAssert(_dst.data == (uchar*)dst.data()); } } // Matx case template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols> void cv2eigen( const Matx<_Tp, _rows, _cols>& src, Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst ) { if( !(dst.Flags & Eigen::RowMajorBit) ) { Mat _dst(_cols, _rows, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); transpose(src, _dst); CV_DbgAssert(_dst.data == (uchar*)dst.data()); } else { Mat _dst(_rows, _cols, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); Mat(src).copyTo(_dst); CV_DbgAssert(_dst.data == (uchar*)dst.data()); } } template<typename _Tp> void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst ) { dst.resize(src.rows, src.cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { Mat _dst(src.cols, src.rows, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); if( src.type() == _dst.type() ) transpose(src, _dst); else if( src.cols == src.rows ) { src.convertTo(_dst, _dst.type()); transpose(_dst, _dst); } else Mat(src.t()).convertTo(_dst, _dst.type()); CV_DbgAssert(_dst.data == (uchar*)dst.data()); } else { Mat _dst(src.rows, src.cols, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); src.convertTo(_dst, _dst.type()); CV_DbgAssert(_dst.data == (uchar*)dst.data()); } } // Matx case template<typename _Tp, int _rows, int _cols> void cv2eigen( const Matx<_Tp, _rows, _cols>& src, Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst ) { dst.resize(_rows, _cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { Mat _dst(_cols, _rows, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); transpose(src, _dst); CV_DbgAssert(_dst.data == (uchar*)dst.data()); } else { Mat _dst(_rows, _cols, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); Mat(src).copyTo(_dst); CV_DbgAssert(_dst.data == (uchar*)dst.data()); } } template<typename _Tp> void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst ) { CV_Assert(src.cols == 1); dst.resize(src.rows); if( !(dst.Flags & Eigen::RowMajorBit) ) { Mat _dst(src.cols, src.rows, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); if( src.type() == _dst.type() ) transpose(src, _dst); else Mat(src.t()).convertTo(_dst, _dst.type()); CV_DbgAssert(_dst.data == (uchar*)dst.data()); } else { Mat _dst(src.rows, src.cols, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); src.convertTo(_dst, _dst.type()); CV_DbgAssert(_dst.data == (uchar*)dst.data()); } } // Matx case template<typename _Tp, int _rows> void cv2eigen( const Matx<_Tp, _rows, 1>& src, Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst ) { dst.resize(_rows); if( !(dst.Flags & Eigen::RowMajorBit) ) { Mat _dst(1, _rows, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); transpose(src, _dst); CV_DbgAssert(_dst.data == (uchar*)dst.data()); } else { Mat _dst(_rows, 1, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); src.copyTo(_dst); CV_DbgAssert(_dst.data == (uchar*)dst.data()); } } template<typename _Tp> void cv2eigen( const Mat& src, Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) { CV_Assert(src.rows == 1); dst.resize(src.cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { Mat _dst(src.cols, src.rows, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); if( src.type() == _dst.type() ) transpose(src, _dst); else Mat(src.t()).convertTo(_dst, _dst.type()); CV_DbgAssert(_dst.data == (uchar*)dst.data()); } else { Mat _dst(src.rows, src.cols, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); src.convertTo(_dst, _dst.type()); CV_DbgAssert(_dst.data == (uchar*)dst.data()); } } //Matx template<typename _Tp, int _cols> void cv2eigen( const Matx<_Tp, 1, _cols>& src, Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) { dst.resize(_cols); if( !(dst.Flags & Eigen::RowMajorBit) ) { Mat _dst(_cols, 1, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); transpose(src, _dst); CV_DbgAssert(_dst.data == (uchar*)dst.data()); } else { Mat _dst(1, _cols, DataType<_Tp>::type, dst.data(), (size_t)(dst.stride()*sizeof(_Tp))); Mat(src).copyTo(_dst); CV_DbgAssert(_dst.data == (uchar*)dst.data()); } } } #endif #endif
[ "matias.piipari@gmail.com" ]
matias.piipari@gmail.com
92bd384cb683c379bf66ad3e7481cace43345fec
06a85cf0123dd2a27f75e145d4c233fb25eb393b
/hdu/1094.cpp
af9e7f13028899e4c4fb864e0e2b61824fc63ff4
[]
no_license
nosyndicate/onlinejudge
6db7f50382751310a9b0ce48cf56bb2a258a1800
2a7b775e182eafdb7ca349f5c56d694f40072f58
refs/heads/master
2021-01-19T08:16:57.045164
2014-04-07T06:24:16
2014-04-07T06:24:16
1,598,029
0
0
null
null
null
null
UTF-8
C++
false
false
236
cpp
//http://acm.hdu.edu.cn/showproblem.php?pid=1094 #include <stdio.h> int main() { int N,a,sum = 0; while(scanf("%d",&N)!=EOF) { for(int i = 0;i<N;++i) { scanf("%d",&a); sum+=a; } printf("%d\n",sum); sum = 0; } }
[ "nosyndicate@gmail.com" ]
nosyndicate@gmail.com
fe68f5b5d87e0d6b66b92638efafc41bd87786b1
7ecdf571da7532d748887924aefc3c5e9705ef9e
/server/server.cpp
5db08985839e530b350eee37eab67e060e291326
[]
no_license
GorillaSX/DMS
1d249631d907f77fe6b04c90a3d5c055ad84ca87
f21f73709ba6a8f70eba37d1935217de417b580e
refs/heads/master
2021-04-27T08:04:16.706810
2018-02-23T15:56:53
2018-02-23T15:56:53
122,647,384
0
0
null
null
null
null
UTF-8
C++
false
false
449
cpp
//implement server class //server class #include "server.h" //constructor Server::Server(LogDao& dao, //data access object short port, //bind port string const& ip /*= "" */ //bind ip address )throw(ServerException):m_store(dao),m_socket(port,ip){} //mining data void Server::dataMine(void)throw(ServerException) { //start store thread m_store.start(); //waiting for client connect m_socket.acceptClient(); }
[ "songxin@udel.edu" ]
songxin@udel.edu
4a0f6a5819288f9124f209b17b32665ba2125230
96ed339f2de8c0e78830fc0079226d33d9481b9d
/CombineEngine/Animation/PathFollowController.h
a6cef010dd5e72ddfa3a3163573fae1280856682
[]
no_license
MeridianPoint/OpenGlEngine
e2ea8d4e26196294036f804f79582820c717c7ef
bea4dfa75ef4900296cab883bcae5d5fa9674689
refs/heads/master
2021-01-10T16:22:36.156537
2016-01-27T21:29:50
2016-01-27T21:29:50
50,533,024
1
0
null
null
null
null
UTF-8
C++
false
false
554
h
#ifndef PATHFOLLOWCONTROLLER_H_ #define PATHFOLLOWCONTROLLER_H_ #include "KeyFrameController.h" class PathFollowController : public KeyFrameController { private: Vec3f InitialDirection; Mat4f cur_Rotation; Vec3f cur_speed; //speed Mat4f VectorRotation(Vec3f Prev, Vec3f Post); //get the rotation from two vectors public: PathFollowController(); ~PathFollowController(); void AddKeyframe(float time, Vec3f position, Interp_Type InterType); //addKeyframe By bool Update(float time); Vec3f getSpeed(float time); //get speed at time }; #endif
[ "automaxwang@gmail.com" ]
automaxwang@gmail.com
3c6b343ba4b3c29186da2b7bbd0bdedc342bad91
558dece528927a181dcf8afdc6b6c85edaaeb584
/Data Structure/LCA/SPOJ - NTICKETS - Nlogonian Tickets.cpp
c052422936c9c1a4a8461b8b15042db7ea337f1a
[]
no_license
rohannstu/Algorithms
dd5e9bc8d57ba512ad2b1d27bb761eda7d3ed1a9
b121d952d01687dd52279b91ef19d9533ba05be5
refs/heads/master
2023-04-09T12:30:21.547535
2021-04-08T11:23:54
2021-04-08T11:23:54
569,421,358
1
0
null
2022-11-22T19:40:43
2022-11-22T19:40:41
null
UTF-8
C++
false
false
7,464
cpp
#include<bits/stdc++.h> #define Input freopen("in.txt","r",stdin) #define Output freopen("out.txt","w",stdout) #define ll long long int #define ull unsigned long long int #define pii pair<int,int> #define pll pair<ll,ll> #define sc scanf #define scin(x) sc("%d",&(x)) #define scin2(x,y) sc("%d %d",&(x),&(y)) #define scln(x) sc("%lld",&(x)) #define scln2(x,y) sc("%lld %lld",&(x),&(y)) #define pf printf #define all(a) (a.begin()),(a.end()) #define UNIQUE(X) (X).erase(unique(all(X)),(X).end()) #define SORT_UNIQUE(c) (sort(c.begin(),c.end()), c.resize(distance(c.begin(),unique(c.begin(),c.end())))) #define ms(a,b) memset(a,b,sizeof(a)) #define pb(a) push_back(a) #define mp make_pair #define db double #define EPS 10E-10 #define ff first #define ss second #define sqr(x) (x)*(x) #define vi vector<int> #define vl vector<ll> #define vii vector<vector<int> > #define vll vector<vector<ll> > #define DBG pf("HI\n") #define MOD 1000000007 #define CIN ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0) #define RUN_CASE(t,T) for(__typeof(t) t=1;t<=T;t++) #define CASE(t) printf("Case %d: ",t) #define CASEl(t) printf("Case %d:\n",t) #define intlimit 2147483690 #define longlimit 92233720368547758 #define infinity (1<<28) #define gcd(a,b) __gcd(a,b) #define lcm(a,b) ((a)*(b))/gcd(a,b) #define mxx 123456789 #define PI 2*acos(0.0) #define rep(i,a,b) for(__typeof(i) i=a;i<=b;i++) #define rev(i,a,b) for(__typeof(i) i=a;i>=b;i--) using namespace std; /** toint, tostring, BigMod, Power , sieve, Primefactorize ,frequency in n! **/ //ll toint(string s){ll n=0,k=1;for(int i=s.size()-1; i>=0; i--){n += ((s[i]-'0')*k);k*=10;}return n;} //string tostring(ll x){string s="";while(x){s += (x%10)+'0';x/=10;}reverse(s.begin(),s.end());return s;} //vector<ll>Prime; //bool mark[10000003]; //void sieve(ll n){ll i,j;mark[1]=1;for(i=4; i<=n; i+=2)mark[i]=1;Prime.push_back(2);for(i=3; i<=n; i+=2){if(!mark[i]){Prime.push_back(i);if(i*i<=n){for(j=i*i; j<=n; j+=(i*2))mark[j]=1;}}}} //map<ll,ll>Factor; //void Primefactorize(ll n){for(ll i=0; i<Prime.size() && Prime[i]*Prime[i]<=n; i++){if(n%Prime[i] == 0){while(n%Prime[i] == 0){Factor[Prime[i]]++;n/=Prime[i];}}}if(n>1){Factor[n]++;}} //ll frequency(ll n,ll factor)/** Frequency of a factor in n! **/{ll cnt=0;while(n){cnt += (n/factor);n /= factor;}return cnt;} /** Order Set **/ //#include <ext/pb_ds/assoc_container.hpp> //using namespace __gnu_pbds; //template<typename T> using orderset = tree<T,null_type,less<T>,rb_tree_tag,tree_order_statistics_node_update>; //orderset<int> s ; //orderset<int>::iterator it ; //orderset<int> X; //X.insert(1); //X.insert(2); //X.insert(4); //X.insert(8); //X.insert(16); //cout<<*X.find_by_order(0)<<endl; // 2 //cout<<*X.find_by_order(2)<<endl; // 4 //cout<<*X.find_by_order(4)<<endl; // 16 //cout<<(end(X)==X.find_by_order(6))<<endl; // true //cout<<X.order_of_key(-5)<<endl; // 0 //cout<<X.order_of_key(1)<<endl; // 0 //cout<<X.order_of_key(3)<<endl; // 2 //cout<<X.order_of_key(4)<<endl; // 2 //cout<<X.order_of_key(400)<<endl; // 5 ///------------------Graph Moves------------------- ///const int fx[] = {+1,-1,+0,+0}; ///const int fy[] = {+0,+0,+1,-1}; ///const int fx[] = {+0,+0,+1,-1,-1,+1,-1,+1}; ///King's move ///const int fy[] = {-1,+1,+0,+0,+1,+1,-1,-1}; ///King's move ///const int fx[] = {-2,-2,-1,-1,+1,+1,+2,+2}; ///Knight's move ///const int fy[] = {-1,+1,-2,+2,-2,+2,-1,+1}; ///Knight's move /** LCA problem **/ /** You're given a rooted tree. Find the length of the longest roads between two given nodes **/ #define sz 100005 bool vis[sz]; int parent[sz],level[sz]; vi graph[sz]; map<pii, int>cost; struct info { int par,mx; } sptable[sz][20]; void Init(int n) { for(int i=1 ; i<=n ; i++) { for(int j=0 ; j<20 ; j++) sptable[i][j].par=-1, sptable[i][j].mx=0; } } void Clean(int n) { cost.clear(); for(int i=1 ; i<=n ; i++) { graph[i].clear(); vis[i]=0; level[i]=0; } } void BFS(int start) { ms(parent,-1); queue<int>q; vis[start]=1; level[start]=0; q.push(start); while(!q.empty()) { int u=q.front(); q.pop(); for(int i=0 ; i<graph[u].size() ; i++) { int v=graph[u][i]; if(!vis[v]) { vis[v]=1; parent[v]=u; level[v]=1+level[u]; q.push(v); } } } } void LCA_Init(int n) { Init(n); for(int i=1 ; i<=n ; i++) { sptable[i][0].par = parent[i]; if(sptable[i][0].par != -1) sptable[i][0].mx = max(sptable[i][0].mx, cost[make_pair(i,parent[i])]); } for(int j=1 ; (1<<j)<=n ; j++) { for(int i=1 ; i<=n ; i++) { if(sptable[i][j-1].par != -1) { sptable[i][j].par = sptable[sptable[i][j-1].par][j-1].par; sptable[i][j].mx = max(sptable[i][j].mx, max(sptable[i][j-1].mx, sptable[sptable[i][j-1].par][j-1].mx)); } } } } pii LCA_Query(int n,int p,int q) { if(p == q) return make_pair(p,0); int mx=0; if(level[p] < level[q]) swap(p,q); int Log=0; while(1) { int nxt=Log+1; if((1<<nxt) > level[p]) break; Log++; } for(int i=Log ; i>=0 ; i--) { if(level[p]-(1<<i) >= level[q]) { mx = max(mx, sptable[p][i].mx); p = sptable[p][i].par; } } if(p == q) return make_pair(p,mx); for(int i=Log ; i>=0 ; i--) { if(sptable[p][i].par!=-1 && sptable[p][i].par!=sptable[q][i].par) { mx = max(mx, max(sptable[p][i].mx, sptable[q][i].mx)); p = sptable[p][i].par; q = sptable[q][i].par; } } mx = max(mx, cost[make_pair(p,parent[p])]); mx = max(mx, cost[make_pair(q,parent[q])]); return make_pair(parent[p], mx); } int main() { int i,j,k,n,u,v,w,q,ans,t,T; while(1) { scin(n); if(n == 0) break; rep(i,2,n) { scin2(u,v); scin(w); graph[u].pb(v); graph[v].pb(u); cost[make_pair(u,v)]=w; cost[make_pair(v,u)]=w; } BFS(1); LCA_Init(n); scin(q); rep(i,1,q) { scin2(u,v); ans = LCA_Query(n,u,v).second; pf("%d\n",ans); } Clean(n); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
9a8ccb026813dfec8d7896f1a2870393b503c88e
30e454af4970ecb2798ec45e48f2462ae25b8d56
/13/13.cpp
25a4b986a81373e2def848584fd06048130cd4d7
[]
no_license
espilya/ed
b23794cfbc52460706a6d833896e9cd37b27a189
576eeada29d1f9bd4eef4d7f730ca55612c442f6
refs/heads/master
2022-11-12T01:26:09.642430
2020-07-03T21:43:30
2020-07-03T21:43:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
501
cpp
#include <iostream> #include <string> #include <vector> #include <cmath> #include <algorithm> #include <limits.h> #include "deco.h" using namespace std; //Por ejemplo, si X es Anacleto, agente secreto, X0 //serıa Analceto ,agetnes erceto y X00 (el //mensaje cifrado) serıa Aontaelccreet os e,natge. int main() { string str; while (getline(cin, str)) { deco<char> lista; for (int i = 0; i < str.size(); i++) { lista.push_back(str[i]); } lista.dec(); lista.toString(); } }
[ "espilya@gmail.com" ]
espilya@gmail.com
c9254885f86b768830c2484a71879870eed16a7d
372e4adc8d3a9e1c118b45951d82f56f15e89383
/software_projects/c_programs/color_space/color_space.cpp
eb52ddafda577e3ac20eaea537879a6fdb764a3f
[]
no_license
infocelab/embedded-projects
d190a23b9254b272643eb1a13259ae079ffa934d
ba4d099538df964feac0ee7cc7af10b3271db7b0
refs/heads/master
2021-01-12T18:09:01.718780
2015-08-18T13:36:18
2015-08-18T13:36:18
41,009,390
1
0
null
null
null
null
UTF-8
C++
false
false
1,654
cpp
// Name: Colorspace // Description:This is a simple application that converts an HSL color to an RGB color. For some reason it's all in floating-point, I forget why. // Inputs:The Hue, Saturation and Luminescence color channels of a given color // Returns:The Red, Green and Blue channels of the same color #include <math.h> #include <conio.h> #include <iostream.h> #define min(a,b) (((a)<(b))?(a):(b)) #define max(a,b) (((a)>(b))?(a):(b)) #define bmax 100.0 //Input HSL channel maximum #define cmax 255.0 //Output color maximum void HslToRgb(double h, double s, double L, double& r, double& g, double& b) { h *= cmax*6.0/bmax; s *= cmax/bmax; L *= cmax/bmax; r = min(cmax, max(0.0, fabs(3.0*cmax - fmod(h, 6.0*cmax)) - cmax)); g = min(cmax, max(0.0, fabs(3.0*cmax - fmod(h + 4.0*cmax, 6.0*cmax)) - cmax)); b = min(cmax, max(0.0, fabs(3.0*cmax - fmod(h + 2.0*cmax, 6.0*cmax)) - cmax)); if (L > cmax/2) { r = (L*2/cmax-1)*(cmax-r) + r; g = (L*2/cmax-1)*(cmax-g) + g; b = (L*2/cmax-1)*(cmax-b) + b; } else { r *= L*2/cmax; g *= L*2/cmax; b *= L*2/cmax; } double ave = (r + g + b)/3.0; r = (1.0-s/cmax)*(ave - r) + r; g = (1.0-s/cmax)*(ave - g) + g; b = (1.0-s/cmax)*(ave - b) + b; } int main() { double h, s, l, r, g, b; cout << "Enter a hue, a saturation, and a luminance channel, all from 0-100.\n"; cin >> h >> s >> l; HslToRgb(h, s, l, r, g, b); cout << "The equivalent RGB color is " << r << ',' << g << ',' << b << '\n'; getch(); return 0; }
[ "singh93amit@gmail.com" ]
singh93amit@gmail.com
1b686fa76db12874e58e5e7ad331da035c813046
6142b636a70f8f4740b2116764327f846a141350
/src/ATen/test/native_test.cpp
82bd33d6b685f9835aa029c46dfcc0c5df4f9043
[]
no_license
peterjc123/ATen
20fce99b5fd26e1b44c9c930e1a4a4660b60fc3f
707d26e7c54d12ec706257e367d4036ca6531ee3
refs/heads/master
2021-08-06T05:48:06.944650
2017-11-02T23:26:19
2017-11-02T23:53:36
107,766,845
1
1
null
2017-10-21T09:14:16
2017-10-21T09:14:16
null
UTF-8
C++
false
false
1,784
cpp
#include "ATen/ATen.h" using namespace at; void assertEqualTensorList(TensorList t1, TensorList t2) { assert(t1.size() == t2.size()); for (size_t i = 0; i < t1.size(); ++i) { assert(t1[ i ].equal(t2[ i ])); } } int main() { Type & T = CPU(kFloat); auto t = T.randn({3, 3}); // split { // test method, type, namespace give same result auto splitMethod = t.split(1, 0); auto splitType = T.split(t, 1, 0); auto splitNs = at::split(t, 1, 0); assertEqualTensorList(splitMethod, splitType); assertEqualTensorList(splitMethod, splitNs); // test rebuilding with cat assert(at::cat(splitMethod, 0).equal(t)); } { // test method, type, namespace give same result auto chunkMethod = t.chunk(3, 0); auto chunkType = T.chunk(t, 3, 0); auto chunkNs = at::chunk(t, 3, 0); assertEqualTensorList(chunkMethod, chunkType); assertEqualTensorList(chunkMethod, chunkNs); // test rebuilding with cat assert(at::cat(chunkMethod, 0).equal(t)); } // stack { auto x = T.rand({2, 3, 4}); auto y = T.rand({2, 3, 4}); auto z = T.rand({2, 3, 4}); for (int64_t dim = 0; dim < 4; ++dim) { auto res = at::stack({x, y, z}, dim); auto res_neg = at::stack({x, y, z}, dim - 4); std::vector<int64_t> expected_size; expected_size.insert(expected_size.end(), x.sizes().begin(), x.sizes().begin() + dim); expected_size.insert(expected_size.end(), 3); expected_size.insert(expected_size.end(), x.sizes().begin() + dim, x.sizes().end()); assert(res.equal(res_neg)); assert(res.sizes().equals(expected_size)); assert(res.select(dim, 0).equal(x)); assert(res.select(dim, 1).equal(y)); assert(res.select(dim, 2).equal(z)); } } return 0; }
[ "ezyang@mit.edu" ]
ezyang@mit.edu
8f4fa87a4ed8fc425a806c47b095c9f69ec18def
dcaa3e7cf2e23ed3c0c83ea60eeff8e5544891d9
/D3DX9/DirectX 9.0C a Shader Approach/Chapter 14 - Meshes/Concatenate Meshes Demo/Concatenate Meshes Demo/ConcatenateMeshesDemo.h
760711638ba7fadb7c890d8ce6856afe1b980fd8
[]
no_license
JamieSandell/DirectX
649c37ea197b2f8a1e7d2b497a3fef4efd366cb1
1f9d1db8fd3d726f3383b41eaf98c4715cb3fb15
refs/heads/main
2023-03-08T12:47:51.617420
2021-02-21T12:21:14
2021-02-21T12:21:14
340,846,416
0
0
null
null
null
null
UTF-8
C++
false
false
1,341
h
#include "d3dApp.h" #include "DirectInput.h" #include <crtdbg.h> #include "GfxStats.h" #include <vector> #include "Vertex.h" class ConcatenateMeshesDemo : public D3DApp { public: ConcatenateMeshesDemo(HINSTANCE hInstance, std::string winCaption, D3DDEVTYPE devType, DWORD requestedVP); ~ConcatenateMeshesDemo(); bool checkDeviceCaps(); void onLostDevice(); void onResetDevice(); void updateScene(float dt); void drawScene(); // Helper methods void drawMesh(const std::vector<Mtrl>& mtrl, ID3DXMesh* mesh, const std::vector<IDirect3DTexture9*> &tex); void buildFX(); void buildViewMtx(); void buildProjMtx(); private: GfxStats* mGfxStats; ID3DXMesh* mMeshShip; ID3DXMesh* mMeshGrid; ID3DXMesh* mMeshJoined; std::vector<Mtrl> mMtrlShip; std::vector<Mtrl> mMtrlGrid; std::vector<Mtrl> mMtrlJoined; std::vector<IDirect3DTexture9*> mTexShip; std::vector<IDirect3DTexture9*> mTexGrid; std::vector<IDirect3DTexture9*> mTexJoined; IDirect3DTexture9* mWhiteTex; ID3DXEffect* mFX; D3DXHANDLE mhTech; D3DXHANDLE mhWVP; D3DXHANDLE mhWorldInvTrans; D3DXHANDLE mhEyePos; D3DXHANDLE mhWorld; D3DXHANDLE mhTex; D3DXHANDLE mhMtrl; D3DXHANDLE mhLight; DirLight mLight; float mCameraRotationY; float mCameraRadius; float mCameraHeight; D3DXMATRIX mWorld; D3DXMATRIX mView; D3DXMATRIX mProj; };
[ "jamie.sandell@outlook.com" ]
jamie.sandell@outlook.com
379988e7714dd441da0495dc33ce5a4fe77f839e
9fc5e61c56a23c42e37a7eb1423861b8c444003d
/FEATURES/Visuals.h
5f047e4a8239fe5a196eeac2f5ad9e55018d7ae7
[]
no_license
DespiseTheWeak/PHACK-Recode
71fe5c2702b2855693a714b818694de0a791b2b0
644e2c10643d94f0ddd12992fa624bd49aae2bbc
refs/heads/master
2020-05-03T00:55:06.461264
2019-03-27T17:40:11
2019-03-27T17:40:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,088
h
#pragma once namespace SDK { class CUserCmd; class CBaseEntity; } class CVisuals { public: struct damage_indicator_t { int dmg; bool initializes; float earse_time; float last_update; SDK::CBaseEntity * player; Vector Position; char* hitboxmeme; }; struct ESPBox { int x, y, w, h; }; std::vector<damage_indicator_t> dmg_indicator; void Drawmodels(); void CustomModels(SDK::CBaseEntity* entity); void Draw(); void HeadEsp(SDK::CBaseEntity * entity); void SpecList(); void DrawZeusRange(SDK::CBaseEntity* entity); void DrawDamageIndicator(); void AsusProps(); void DoFSN(); void ClientDraw(); //void apply_clantag(); void DrawInaccuracy(); void BombH(SDK::CBaseEntity * bomb); void LagCompHitbox(SDK::CBaseEntity * entity, int index); void DrawCapsuleOverlay(SDK::CBaseEntity * entity, int index); void DrawBulletBeams(); void ModulateWorld(); void Skycolorchanger(); void AntiAimLines(); void ModulateSky(); void Worldcolorchanger(); void DrawName(SDK::CBaseEntity * entity, CColor color, int index, Vector pos, Vector top); //void DrawName(SDK::CBaseEntity * entity, CColor color, int index, Vector pos, Vector top, IDirect3DDevice9 * pDevice); void set_hitmarker_time( float time ); void LogEvents(); // void Clantag(); void phack3(); void fatality(); void skeet(); void moneybot(); void phack2(); void watermark(); void DrawHealth(SDK::CBaseEntity * entity, CVisuals::ESPBox size); ESPBox CVisuals::GetBOXX(SDK::CBaseEntity* pEntity); bool GetBox(SDK::CBaseEntity * pEntity, CVisuals::ESPBox & result); private: void misc_visuals(); void penetration_reticle(); void DrawBox(CVisuals::ESPBox size, CColor color, SDK::CBaseEntity * pEntity); //void DrawBox(SDK::CBaseEntity* entity, CColor color, Vector pos, Vector top); //void DrawName(SDK::CBaseEntity* entity, CColor color, int index, Vector pos, Vector top); void DrawForwardtrack(SDK::CBaseEntity * entity); void DrawBoneESP(SDK::CBaseEntity * entity, CColor color); void DrawSkeleton(SDK::CBaseEntity * entity, CColor color); //void LagCompHitbox(SDK::CBaseEntity * entity); void DrawWeapon(SDK::CBaseEntity * entity, CColor color, int index, Vector pos, Vector top); // void DrawHealth(SDK::CBaseEntity * entity, CColor color, CColor dormant, Vector pos, Vector top); // void BombPlanted(SDK::CBaseEntity * entity); //void BacktrackHit(SDK::CBaseEntity * entity, int index); void DrawDropped(SDK::CBaseEntity * entity); void DrawAmmo(SDK::CBaseEntity * entity, CColor color, CColor dormant, Vector pos, Vector top); float resolve_distance(Vector src, Vector dest); void DrawDistance(SDK::CBaseEntity * entity, CColor color, Vector pos, Vector top); void DrawInfo(SDK::CBaseEntity * entity, CColor color, CColor alt, Vector pos, Vector top); void DrawFovArrows(SDK::CBaseEntity* entity, CColor color); void DrawInaccuracy1(); void DrawCrosshair(); void DrawIndicator(); void DrawHitmarker(); void DrawBorderLines(); public: std::vector<std::pair<int, float>> Entities; std::deque<UTILS::BulletImpact_t> Impacts; }; extern CVisuals* visuals;
[ "34896898+PIZYY@users.noreply.github.com" ]
34896898+PIZYY@users.noreply.github.com
2a76b0f07ae255a313a399b2a8f474d253f82cfa
e5fab2da561e99db4ace4afe5ce74cd65dd723b4
/30DaysOfCode/Day22_BST's/testingPointers.cpp
8edf6e7ef6f7da4b95d27be49e8c5f4966946b19
[]
no_license
TlStephen2011/Development-Practice
baa0f11701f5dd7ab8d3e16673cbc70eacf6fb73
a89943d8383f3f9b764a4d72ee8dfaa263b0c80b
refs/heads/master
2021-06-22T17:59:09.947909
2017-08-31T13:08:49
2017-08-31T13:08:49
91,625,926
0
0
null
null
null
null
UTF-8
C++
false
false
345
cpp
#include <iostream> #include <vector> using namespace std; int main() { vector<int *> a(2); int num1 = 5; int num2 = 10; a[0] = &num1; a[1] = &num2; cout << *a[0] << " " << *a[1] << endl << endl; num1 = 200; num2 = 1000; cout << *a[0] << " " << *a[1] << endl << endl; return 0; }
[ "noreply@github.com" ]
noreply@github.com
4fef8077145b2736b9b9feaebe2262d85cb0bb7d
a280aa9ac69d3834dc00219e9a4ba07996dfb4dd
/regularexpress/home/weilaidb/software/zeromq-4.1.5/builds/msvc/errno.cpp
9803a2e4464d3d83bba42eca1c3bb4be835ad75e
[]
no_license
weilaidb/PythonExample
b2cc6c514816a0e1bfb7c0cbd5045cf87bd28466
798bf1bdfdf7594f528788c4df02f79f0f7827ce
refs/heads/master
2021-01-12T13:56:19.346041
2017-07-22T16:30:33
2017-07-22T16:30:33
68,925,741
4
2
null
null
null
null
UTF-8
C++
false
false
120
cpp
#if defined _WIN32_WCE int errno; int _doserrno; int _sys_nerr; char* error_desc_buff = NULL; char* strerror(int errno)
[ "weilaidb@localhost.localdomain" ]
weilaidb@localhost.localdomain
244ed0debafa2bbd17fe2399de60ae5105e56afb
03b569e7094c99bf39a5030a3d97c7e7fd3a6cc7
/prueba 1 apuntadores.cpp
46f306fdcc637c682e0ecc2d624624e25b06bcab
[]
no_license
2tanliz98/Programas-FP
46dafbf1729f63eb4d195eb653d7b17b77c1941b
815ca16cf2015c074523e0bad414eb3d77ecb9f6
refs/heads/master
2021-07-06T22:24:56.748986
2020-08-06T18:43:03
2020-08-06T18:43:03
157,291,548
1
0
null
null
null
null
UTF-8
C++
false
false
174
cpp
#include <stdio.h> const char *mensaje[8]= {"uno", "dos", "tres"}; int cont; main () { for (cont =0; cont<3; cont++){ printf ("%s \n", mensaje [cont]); } }
[ "noreply@github.com" ]
noreply@github.com
92e48af055772df1641608b6d8b546bf9dbdd31f
1a5fe8af0f2a049e8b3890f6d42b8168d9a00702
/GameServerDev/LoginServer/include/EventSystem.h
5503bbaabfd35a3ab60fdd5b4833c677ffce24d6
[]
no_license
Bestcoderg/ServerTrainCamp
db0c575ce2deb734c9dc8c33f8e160b4d0b1479f
ead7e40c9b9219beba7022b7a213493276ab2666
refs/heads/master
2023-01-28T19:19:47.992864
2020-12-07T07:29:11
2020-12-07T07:29:11
319,226,092
0
0
null
null
null
null
UTF-8
C++
false
false
689
h
#ifndef _EVENTSYSTEM_H_ #define _EVENTSYSTEM_H_ #include "util.h" #include "Singleton.h" #include "MsgHandler.h" //#include "EntityMgr.h" #include <functional> //#include "../systems/BagSystem.h" class EventSystem { private: EventSystem(); ~EventSystem(); DECLARE_SINGLETON(EventSystem); public: bool Init(); void Uinit(); MsgHandler<EventSystem>* GetMsgHandler() { return m_msgHandler; } INT32 PlayerLogin(const MesgInfo &stHead, const char *body,const INT32 len,const INT32 connfd); INT32 ServerRegister(const MesgInfo &stHead, const char *body,const INT32 len,const INT32 connfd); private: MsgHandler<EventSystem>* m_msgHandler; }; #endif
[ "624303639@qq.com" ]
624303639@qq.com
ce071fc019dba663b90f56a9d139361c13e3909a
f2ca41135c6c525648c5eb9b6dca3fd383dcdfd3
/lib/MF_Modules/MFButtonT.cpp
61e489505f389e1cffe626a6653a162e64f1d3f4
[]
no_license
GioCC/FW-Mobiflight-GCC
c531ab47c7f75ac6d768ab75960f6f6fc3a431c9
da5d679a650e98423188c41c34682ee48357adb7
refs/heads/master
2023-08-20T16:48:17.741513
2021-10-14T08:52:50
2021-10-14T08:55:30
363,756,804
0
0
null
null
null
null
UTF-8
C++
false
false
1,932
cpp
// MFButtonT.cpp // // Copyright (C) 2013-2014 #include "MFButtonT.h" // Static handler pointers and vars buttonEvent MFButtonT::_handler; bitStore<byte> *MFButtonT::_InBitsVal; bitStore<byte> *MFButtonT::_InBitsNew; byte MFButtonT::_MaxOnboardPin; //String MFButtonT::_nameStr("12345"); // Pre-allocate, assuring 5+1 chars width void MFButtonT::attach(uint8_t pin) { _pin = pin; _InBitsVal->set(_pin); if(_pin < _MaxOnboardPin) { pinMode(_pin, INPUT); // set pin to input digitalWrite(_pin, HIGH); // turn on pullup resistors } } void MFButtonT::attachHandler(/*byte eventId, */ buttonEvent newHandler) { //MFButtonT::_handler[eventId] = newHandler; MFButtonT::_handler = newHandler; } // setBitStore() requires <maxOBPin> in order to know whether to use digitalRead // or get its value from the bitStore, according to own pin number void MFButtonT::setBitStore(bitStore<byte> *val_status, bitStore<byte> *new_status, byte maxOBPin) { MFButtonT::_InBitsVal = val_status; MFButtonT::_InBitsNew = new_status; MFButtonT::_MaxOnboardPin = maxOBPin; } void MFButtonT::update() { //long now = millis(); //if (now-_last <= 10) return; byte newState = ((_pin<_MaxOnboardPin) ? digitalRead(_pin) : _InBitsNew->get(_pin)); //_last = now; if (newState!=_InBitsVal->get(_pin)) { _InBitsVal->put(_pin, newState); trigger(); } } void MFButtonT::trigger() { char pt[5]; *pt = 'B'; fast_itoa(&pt[1], _pin); //_nameStr = pt; if (_handler) {(*_handler)((_InBitsVal->get(_pin)==LOW ? btnPress : btnRelease), _pin, pt); } //_nameStr); } /* if (_InBits->get(_pin)==LOW && _handler[btnPress]!= NULL) { (*_handler[btnPress])(btnPress, _pin, _nameStr); } else if (_handler[btnRelease] != NULL) (*_handler[btnRelease])(btnRelease, _pin, _nameStr); */ }
[ "25667790+GioCC@users.noreply.github.com" ]
25667790+GioCC@users.noreply.github.com
43172e54f2a478e2289cdcf80b4f1ae47dbae114
7d77df903d0cf50ff0cda2808ea5f4a0faef99f7
/vscode_opencv_config/main.cpp
f123e0df46bb155c006c6ace31a4e78c8bbab3ee
[]
no_license
ai-wen/study
26bb81ca9fc02fedb9adf9b90adadc850d6f8b3e
c0019b732a0cbc4d216bdff8f03763129ac70544
refs/heads/master
2022-09-07T17:50:02.665361
2022-08-05T03:27:12
2022-08-05T03:27:12
240,482,812
5
2
null
null
null
null
UTF-8
C++
false
false
3,932
cpp
#include <iostream> #include <opencv2/opencv.hpp> using namespace cv; int main1(int arg, char **args) { std::cout << "aa" << std::endl; std::string img = "D:\\1.JPG"; Mat srcImage = imread(img); if (!srcImage.data) { return 1; } imshow("srcImage", srcImage); cvWaitKey(0); return 0; } int main(int arc, char **argv) { Mat src = imread("1.jpg"); namedWindow("input", CV_WINDOW_AUTOSIZE); imshow("input", src); //组装数据并运行KMeans int width = src.cols; int height = src.rows; int dims = src.channels(); int pointsCount = width * height; Mat points(pointsCount, dims, CV_32F); //kmeans要求的数据为float类型的 int index = 0; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { index = i * width + j; points.at<float>(index, 0) = src.at<Vec3b>(i, j)[0]; points.at<float>(index, 1) = src.at<Vec3b>(i, j)[1]; points.at<float>(index, 2) = src.at<Vec3b>(i, j)[2]; } } Mat bestLabels; Mat centers; kmeans(points, 4, bestLabels, TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 10, 0.1), 3, 2, centers); //去背景+遮罩层 Mat mask(src.size(), CV_8UC1); index = src.cols * 2 + 2; int bindex = bestLabels.at<int>(index, 0); //获得kmeans后背景的标签 Mat dst; src.copyTo(dst); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { index = i * width + j; int label = bestLabels.at<int>(index, 0); if (label == bindex) { dst.at<Vec3b>(i, j)[0] = 0; dst.at<Vec3b>(i, j)[1] = 0; dst.at<Vec3b>(i, j)[2] = 0; mask.at<uchar>(i, j) = 0; } else { mask.at<uchar>(i, j) = 255; } } } imshow("mask", mask); imshow("kmeans", dst); //对掩码进行腐蚀+高斯模糊 Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3)); erode(mask, mask, kernel); imshow("erode mask", mask); GaussianBlur(mask, mask, Size(3, 3), 0, 0); imshow("blur mask", mask); //通道混合 Vec3b color; color[0] = theRNG().uniform(0, 255); color[1] = theRNG().uniform(0, 255); color[2] = theRNG().uniform(0, 255); Mat result(src.size(), src.type()); double w = 0.0; int b = 0, g = 0, r = 0; int b1 = 0, g1 = 0, r1 = 0; int b2 = 0, g2 = 0, r2 = 0; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { int m = mask.at<uchar>(i, j); if (m == 255) { result.at<Vec3b>(i, j) = src.at<Vec3b>(i, j); //将原图像中前景赋给结果图像中的前景 } else if (m == 0) { result.at<Vec3b>(i, j) = color; //将随机生成的颜色赋给结果图像中的背景 } else { w = m / 255.0; //权重 //边缘前景 b1 = src.at<Vec3b>(i, j)[0]; g1 = src.at<Vec3b>(i, j)[1]; r1 = src.at<Vec3b>(i, j)[2]; //边缘背景 b2 = color[0]; g2 = color[1]; r2 = color[2]; //边缘融合 b = b1 * w + b2 * (1.0 - w); g = g1 * w + g2 * (1.0 - w); r = r1 * w + r2 * (1.0 - w); result.at<Vec3b>(i, j)[0] = b; result.at<Vec3b>(i, j)[1] = g; result.at<Vec3b>(i, j)[2] = r; } } } imshow("result", result); waitKey(0); return 0; }
[ "363042868@qq.com" ]
363042868@qq.com
e392bc5da6ba2f0145ae374137f89abfd86768e2
ebb1371435374755d02d4b6b88c1c27f3197f6e8
/src/ilPSP/layer_0/3rd_party/Hypre2.9.0b/src/FEI_mv/femli/mli_mapper.h
c79d2516996762b6d6f733d2e6b47aea95cb166d
[ "LGPL-2.1-or-later", "LicenseRef-scancode-other-copyleft", "LGPL-2.1-only", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
leyel/BoSSS
a8319d2dfb8e659c94752727bca42c75daf8ab80
39f58a1a64a55e44f51384022aada20a5b425230
refs/heads/master
2020-04-12T14:58:12.276593
2018-12-20T09:04:54
2018-12-20T09:04:54
162,566,868
1
0
Apache-2.0
2018-12-20T10:55:43
2018-12-20T10:55:43
null
UTF-8
C++
false
false
1,664
h
/*BHEADER********************************************************************** * Copyright (c) 2008, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * This file is part of HYPRE. See file COPYRIGHT for details. * * HYPRE is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * $Revision: 1.1 $ ***********************************************************************EHEADER*/ /****************************************************************************** * * Header info for the MLI_Mapper data structure * *****************************************************************************/ #ifndef __MLIMAPPERH__ #define __MLIMAPPERH__ /*-------------------------------------------------------------------------- * include files *--------------------------------------------------------------------------*/ #include <string.h> #include "_hypre_utilities.h" /*-------------------------------------------------------------------------- * MLI_Mapper data structure declaration *--------------------------------------------------------------------------*/ class MLI_Mapper { int nEntries; int *tokenList; int *tokenMap; public : MLI_Mapper(); ~MLI_Mapper(); int setMap(int nItems, int *itemList, int *mapList); int adjustMapOffset(MPI_Comm comm, int *procNRows, int *procOffsets); int getMap(int nItems, int *itemList, int *mapList); int setParams(char *param_string, int argc, char **argv); }; #endif
[ "kummer@fdy.tu-darmstadt.de" ]
kummer@fdy.tu-darmstadt.de
242a1567fe8d5577e3cf3cc9475311d58f8c1d55
f8933d5f5df2422905037f6901753aec967906af
/2606.cpp
504f679b9537d65fced05d105217623d4e3135d5
[]
no_license
jihye1996/Algorithm
684b820a5549585c7f27bf937c16ce7c7cf370b2
1306520c062783bff8350c35b49eb3a24fed2e51
refs/heads/master
2021-11-23T12:22:37.632136
2021-11-22T10:24:49
2021-11-22T10:24:49
148,966,491
0
0
null
null
null
null
UTF-8
C++
false
false
727
cpp
#include <iostream> #include <stack> using namespace std; #define MAX 101 int map[MAX][MAX]; bool visited[MAX]; int N, M; void dfs(int n){ int cnt = 0; stack<int> s; s.push(n); visited[n] = true; while(!s.empty()){ int c = s.top(); s.pop(); for(int i=1; i<=N; i++){ if(!visited[i] && map[c][i]==1){ visited[i] = true; s.push(i); cnt++; } } } cout << cnt; } int main() { int x, y; cin >> N >> M; for(int i=0; i<M; i++){ cin >> x >> y; map[x][y] = 1; map[y][x] = 1; } dfs(1); return 0; }
[ "noreply@github.com" ]
noreply@github.com
bc52916e77a9a1d279937e4f85af4e5152e650fb
54e0ee862be80cc1044e3930d7d4236e1986a57e
/include/moana/cuda/snell.hpp
6f8325249bf1676166df6e29a749cde90b501a36
[ "MIT" ]
permissive
bssrdf/gpu-motunui
fdf725b5aec3d2f78e7cf20c0686f828a2beec6d
1369c98408c4c59bfddff45ae00281f6463527ec
refs/heads/master
2023-01-02T19:03:10.429025
2020-10-21T05:59:23
2020-10-21T05:59:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,001
hpp
#pragma once #include <algorithm> #include "moana/cuda/trig.hpp" #include "moana/core/vec3.hpp" namespace moana { namespace Snell { __device__ inline bool refract( const Vec3 &incidentLocal, Vec3 *transmittedLocal, Vec3 normal, float etaIncident, float etaTransmitted ) { if (dot(incidentLocal, normal) < 0.f) { normal = normal * -1.f; const float temp = etaIncident; etaIncident = etaTransmitted; etaTransmitted = temp; } const Vec3 wIncidentPerpendicular = incidentLocal - (normal * incidentLocal.dot(normal)); const Vec3 wTransmittedPerpendicular = -wIncidentPerpendicular * (etaIncident / etaTransmitted); const float transmittedPerpendicularLength2 = wTransmittedPerpendicular.length() * wTransmittedPerpendicular.length(); const float wTransmittedParallelLength = sqrtf(fmaxf(0.f, 1.f - transmittedPerpendicularLength2)); const Vec3 wTransmittedParallel = normal * -wTransmittedParallelLength; const float cosThetaIncident = absDot(incidentLocal, normal); const float sin2ThetaIncident = Trig::sin2FromCos(cosThetaIncident); const float eta2 = (etaIncident / etaTransmitted) * (etaIncident / etaTransmitted); const float sin2ThetaTransmitted = eta2 * sin2ThetaIncident; *transmittedLocal = normalized(wTransmittedParallel + wTransmittedPerpendicular); if (sin2ThetaTransmitted >= 1.f) { // total internal reflection return false; } return true; } __device__ inline bool refract( const Vec3 &incidentLocal, Vec3 *transmittedLocal, float etaIncident, float etaTransmitted ) { return refract( incidentLocal, transmittedLocal, Vec3(0.f, 0.f, 1.f), etaIncident, etaTransmitted ); } __device__ inline float transmittedSinTheta( float cosThetaIncident, float etaIncident, float etaTransmitted ) { return (etaIncident / etaTransmitted) * Trig::sinThetaFromCosTheta(cosThetaIncident); } } }
[ "chellmuth@gmail.com" ]
chellmuth@gmail.com
a459f016dc9264619337b481da422ab4d42d31f6
c971a156036b8a38ba2477ae5e86403c9c5645fb
/deps/netstring-c/netstring.cpp
d2c239a9b29a0c9606d51713489ea9629744cfb0
[ "ISC", "LicenseRef-scancode-public-domain" ]
permissive
kurokky/mediasoup
edca9a303df995fe057f1eb392a92cc1bb6024e6
15f1fb7df3419c278b26858f139d9aa4e1770f11
refs/heads/master
2021-01-17T20:27:51.474476
2016-03-07T22:47:26
2016-03-07T22:47:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,714
cpp
/* Streaming API for netstrings. */ #include <cstdio> #include <cstring> #include <cstdlib> #include <cctype> #include <cmath> #include "netstring.h" /* Reads a netstring from a `buffer` of length `buffer_length`. Writes to `netstring_start` a pointer to the beginning of the string in the buffer, and to `netstring_length` the length of the string. Does not allocate any memory. If it reads successfully, then it returns 0. If there is an error, then the return value will be negative. The error values are: NETSTRING_ERROR_TOO_LONG More than 999999999 bytes in a field NETSTRING_ERROR_NO_COLON No colon was found after the number NETSTRING_ERROR_TOO_SHORT Number of bytes greater than buffer length NETSTRING_ERROR_NO_COMMA No comma was found at the end NETSTRING_ERROR_LEADING_ZERO Leading zeros are not allowed NETSTRING_ERROR_NO_LENGTH Length not given at start of netstring If you're sending messages with more than 999999999 bytes -- about 2 GB -- then you probably should not be doing so in the form of a single netstring. This restriction is in place partially to protect from malicious or erroneous input, and partly to be compatible with D. J. Bernstein's reference implementation. Example: if (netstring_read("3:foo,", 6, &str, &len) < 0) explode_and_die(); */ int netstring_read(char *buffer, size_t buffer_length, char **netstring_start, size_t *netstring_length) { size_t i; size_t len = 0; /* Write default values for outputs */ *netstring_start = NULL; *netstring_length = 0; /* Make sure buffer is big enough. Minimum size is 3. */ if (buffer_length < 3) return NETSTRING_ERROR_TOO_SHORT; /* No leading zeros allowed! */ if (buffer[0] == '0' && isdigit(buffer[1])) return NETSTRING_ERROR_LEADING_ZERO; /* The netstring must start with a number */ if (!isdigit(buffer[0])) return NETSTRING_ERROR_NO_LENGTH; /* Read the number of bytes */ for (i = 0; i < buffer_length && isdigit(buffer[i]); i++) { /* Error if more than 9 digits */ if (i >= 9) return NETSTRING_ERROR_TOO_LONG; /* Accumulate each digit, assuming ASCII. */ len = len*10 + (buffer[i] - '0'); } /* Check buffer length once and for all. Specifically, we make sure that the buffer is longer than the number we've read, the length of the string itself, and the colon and comma. */ if (i + len + 1 >= buffer_length) return NETSTRING_ERROR_TOO_SHORT; /* Read the colon */ if (buffer[i++] != ':') return NETSTRING_ERROR_NO_COLON; /* Test for the trailing comma, and set the return values */ if (buffer[i + len] != ',') return NETSTRING_ERROR_NO_COMMA; *netstring_start = &buffer[i]; *netstring_length = len; return 0; } /* Return the length, in ASCII characters, of a netstring containing `data_length` bytes. */ size_t netstring_buffer_size(size_t data_length) { if (data_length == 0) return 3; return (size_t)ceil(log10((double)data_length + 1)) + data_length + 2; } /* Allocate and create a netstring containing the first `len` bytes of `data`. This must be manually freed by the client. If `len` is 0 then no data will be read from `data`, and it may be NULL. */ size_t netstring_encode_new(char **netstring, char *data, size_t len) { char *ns; size_t num_len = 1; if (len == 0) { ns = (char *)malloc(3); ns[0] = '0'; ns[1] = ':'; ns[2] = ','; } else { num_len = (size_t)ceil(log10((double)len + 1)); ns = (char *)malloc(num_len + len + 2); sprintf(ns, "%lu:", (unsigned long)len); memcpy(ns + num_len + 1, data, len); ns[num_len + len + 1] = ','; } *netstring = ns; return num_len + len + 2; }
[ "ibc@aliax.net" ]
ibc@aliax.net
ec33a739913ad9559090dea123ef3d6bb460ff52
79dd9f55f3c614eae41d6128978a76fac57a129b
/cfg/Config.cpp
5f69f64a03a39fa88ac1dbe1350f3bd84d8b27fa
[]
no_license
nazgee/eccerobo-spine
d69083da10df74242e6aea4f1744e30d4403fd74
487ff0d7349a77ff949012783327388a22a2db4f
refs/heads/master
2016-09-10T21:29:57.260842
2013-08-15T17:16:56
2013-08-15T17:16:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,093
cpp
/* * config.cpp * * Created on: Aug 25, 2012 * Author: nazgee */ #include <iostream> #include <sstream> #include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <stdexcept> #include <errno.h> #include <stdlib.h> #include "Config.h" Config::Config(int argc, char **argv) : mSilent(0), mPort("7000") { int c; while (1) { static struct option long_options[] = { /* These options set a flag. */ { "verbose", no_argument, &mSilent, 1 }, /* These options don't set a flag. We distinguish them by their indices. */ { "device", required_argument, NULL, 'd' }, { "baud", required_argument, NULL, 'b' }, { "parity", required_argument, NULL, 'p' }, { "port", required_argument, NULL, 't' }, { 0, 0, 0, 0 } }; /* getopt_long stores the option index here. */ int option_index = 0; c = getopt_long(argc, argv, "d:b:p:t:", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 0: /* If this option set a flag, do nothing else now. */ if (long_options[option_index].flag != 0) break; std::cout << "option " << long_options[option_index].name; if (optarg) std::cout << " with arg " << optarg; std::cout << std::endl; break; case 'd': { serial.device = optarg; } break; case 'p': { serial.parity.set(optarg); } break; case 'b': { errno = 0; char* str = optarg; serial.baud_rate = strtol(optarg, &str, 10); if (errno || (optarg == str)) { throw std::invalid_argument("Invalid baud rate given"); } } break; case 't': { mPort = optarg; } break; case '?': /* getopt_long already printed an error message. */ throw std::invalid_argument("Bad params given!"); break; default: abort(); break; } } /* Print any remaining command line arguments (not options). */ if (optind < argc) { std::cerr << "non-option ARGV-elements: "; while (optind < argc) std::cerr << argv[optind++]; std::cerr << std::endl; } } std::string Config::toString() { return serial.toString(); }
[ "michal.stawinski@gmail.com" ]
michal.stawinski@gmail.com
465374f2ec7e51baa7de88cd12a9dd57f41b0a9e
304c67e303863029c8b7a7e366a6c1df3cf7ed73
/src/qt/test/paymentservertests.h
51b18f7a6d1cf3d8d361228013e9d3750eaac946
[ "MIT" ]
permissive
hideoussquid/deuscoin-core-gui
9a18beb284c4d4e09bec2327147fa94e3e8c4b8b
1e6e0186498a7272382b648b22427f0e7c349582
refs/heads/master
2021-01-18T17:32:20.431948
2017-08-21T18:21:32
2017-08-21T18:21:32
86,807,542
0
1
null
null
null
null
UTF-8
C++
false
false
823
h
// 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. #ifndef DEUSCOIN_QT_TEST_PAYMENTSERVERTESTS_H #define DEUSCOIN_QT_TEST_PAYMENTSERVERTESTS_H #include "../paymentserver.h" #include <QObject> #include <QTest> class PaymentServerTests : public QObject { Q_OBJECT private Q_SLOTS: void paymentServerTests(); }; // Dummy class to receive paymentserver signals. // If SendCoinsRecipient was a proper QObject, then // we could use QSignalSpy... but it's not. class RecipientCatcher : public QObject { Q_OBJECT public Q_SLOTS: void getRecipient(SendCoinsRecipient r); public: SendCoinsRecipient recipient; }; #endif // DEUSCOIN_QT_TEST_PAYMENTSERVERTESTS_H
[ "thesquid@mac.com" ]
thesquid@mac.com
c8cf8c66e1608723d5b9ecd98d71ce42d3ba2811
3cf9e141cc8fee9d490224741297d3eca3f5feff
/C++ Benchmark Programs/Benchmark Files 1/classtester/autogen-sources/source-2521.cpp
6d9f198f90b21c0da79c85edf2d3faad8d98d892
[]
no_license
TeamVault/tauCFI
e0ac60b8106fc1bb9874adc515fc01672b775123
e677d8cc7acd0b1dd0ac0212ff8362fcd4178c10
refs/heads/master
2023-05-30T20:57:13.450360
2021-06-14T09:10:24
2021-06-14T09:10:24
154,563,655
0
1
null
null
null
null
UTF-8
C++
false
false
2,405
cpp
struct c0; void __attribute__ ((noinline)) tester0(c0* p); struct c0 { bool active0; c0() : active0(true) {} virtual ~c0() { tester0(this); active0 = false; } virtual void f0(){} }; void __attribute__ ((noinline)) tester0(c0* p) { p->f0(); } struct c1; void __attribute__ ((noinline)) tester1(c1* p); struct c1 { bool active1; c1() : active1(true) {} virtual ~c1() { tester1(this); active1 = false; } virtual void f1(){} }; void __attribute__ ((noinline)) tester1(c1* p) { p->f1(); } struct c2; void __attribute__ ((noinline)) tester2(c2* p); struct c2 { bool active2; c2() : active2(true) {} virtual ~c2() { tester2(this); active2 = false; } virtual void f2(){} }; void __attribute__ ((noinline)) tester2(c2* p) { p->f2(); } struct c3; void __attribute__ ((noinline)) tester3(c3* p); struct c3 : virtual c1, c0 { bool active3; c3() : active3(true) {} virtual ~c3() { tester3(this); c0 *p0_0 = (c0*)(c3*)(this); tester0(p0_0); c1 *p1_0 = (c1*)(c3*)(this); tester1(p1_0); active3 = false; } virtual void f3(){} }; void __attribute__ ((noinline)) tester3(c3* p) { p->f3(); if (p->active0) p->f0(); if (p->active1) p->f1(); } struct c4; void __attribute__ ((noinline)) tester4(c4* p); struct c4 : virtual c0, virtual c2, virtual c1 { bool active4; c4() : active4(true) {} virtual ~c4() { tester4(this); c0 *p0_0 = (c0*)(c4*)(this); tester0(p0_0); c1 *p1_0 = (c1*)(c4*)(this); tester1(p1_0); c2 *p2_0 = (c2*)(c4*)(this); tester2(p2_0); active4 = false; } virtual void f4(){} }; void __attribute__ ((noinline)) tester4(c4* p) { p->f4(); if (p->active0) p->f0(); if (p->active1) p->f1(); if (p->active2) p->f2(); } int __attribute__ ((noinline)) inc(int v) {return ++v;} int main() { c0* ptrs0[25]; ptrs0[0] = (c0*)(new c0()); ptrs0[1] = (c0*)(c3*)(new c3()); ptrs0[2] = (c0*)(c4*)(new c4()); for (int i=0;i<3;i=inc(i)) { tester0(ptrs0[i]); delete ptrs0[i]; } c1* ptrs1[25]; ptrs1[0] = (c1*)(new c1()); ptrs1[1] = (c1*)(c3*)(new c3()); ptrs1[2] = (c1*)(c4*)(new c4()); for (int i=0;i<3;i=inc(i)) { tester1(ptrs1[i]); delete ptrs1[i]; } c2* ptrs2[25]; ptrs2[0] = (c2*)(new c2()); ptrs2[1] = (c2*)(c4*)(new c4()); for (int i=0;i<2;i=inc(i)) { tester2(ptrs2[i]); delete ptrs2[i]; } c3* ptrs3[25]; ptrs3[0] = (c3*)(new c3()); for (int i=0;i<1;i=inc(i)) { tester3(ptrs3[i]); delete ptrs3[i]; } c4* ptrs4[25]; ptrs4[0] = (c4*)(new c4()); for (int i=0;i<1;i=inc(i)) { tester4(ptrs4[i]); delete ptrs4[i]; } return 0; }
[ "ga72foq@mytum.de" ]
ga72foq@mytum.de
1b7e99376b08fab208f2a5a98dbe4fb97c27d27b
c910b384330f2724cd2364de06bd0b4ce58099f7
/content/common/gpu/media/android_copying_backing_strategy.h
7b2fa6590584a32c6fcd5df4df99f643dabd7828
[ "BSD-3-Clause" ]
permissive
techtonik/chromium
3d4d5cf30a1a61f2d5559ac58638ce38cf2ab5cd
319329de7edb672d11217094c5f9b77bc7af1f26
refs/heads/master
2021-10-02T05:10:56.666038
2015-10-13T20:09:21
2015-10-13T20:10:56
44,329,819
0
1
null
2015-10-15T16:14:05
2015-10-15T16:14:04
null
UTF-8
C++
false
false
1,968
h
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_COMMON_GPU_MEDIA_ANDROID_COPYING_BACKING_STRATEGY_H_ #define CONTENT_COMMON_GPU_MEDIA_ANDROID_COPYING_BACKING_STRATEGY_H_ #include "base/compiler_specific.h" #include "base/threading/thread_checker.h" #include "content/common/content_export.h" #include "content/common/gpu/media/android_video_decode_accelerator.h" namespace gpu { class CopyTextureCHROMIUMResourceManager; } namespace media { class PictureBuffer; } namespace content { class AndroidVideoDecodeAcceleratorStateProvider; // A BackingStrategy implementation that copies images to PictureBuffer // textures via gpu texture copy. class CONTENT_EXPORT AndroidCopyingBackingStrategy : public AndroidVideoDecodeAccelerator::BackingStrategy { public: AndroidCopyingBackingStrategy(); ~AndroidCopyingBackingStrategy() override; // AndroidVideoDecodeAccelerator::BackingStrategy void SetStateProvider(AndroidVideoDecodeAcceleratorStateProvider*) override; void Cleanup() override; uint32 GetNumPictureBuffers() const override; uint32 GetTextureTarget() const override; scoped_refptr<gfx::SurfaceTexture> CreateSurfaceTexture() override; void UseCodecBufferForPictureBuffer(int32 codec_buffer_index, const media::PictureBuffer&) override; private: // Used for copy the texture from surface texture to picture buffers. scoped_ptr<gpu::CopyTextureCHROMIUMResourceManager> copier_; AndroidVideoDecodeAcceleratorStateProvider* state_provider_; // A container of texture. Used to set a texture to |media_codec_|. scoped_refptr<gfx::SurfaceTexture> surface_texture_; // The texture id which is set to |surface_texture_|. uint32 surface_texture_id_; }; } // namespace content #endif // CONTENT_COMMON_GPU_MEDIA_ANDROID_COPYING_BACKING_STRATEGY_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
0e3ec0e1dd1f67dfb21791dbf98dc32394448596
72852e07bb30adbee608275d6048b2121a5b9d82
/algorithms/problem_0459/other.cpp
d82448fe1a1eda550fe13a4b7de6de4f1e7f1954
[]
no_license
drlongle/leetcode
e172ae29ea63911ccc3afb815f6dbff041609939
8e61ddf06fb3a4fb4a4e3d8466f3367ee1f27e13
refs/heads/master
2023-01-08T16:26:12.370098
2023-01-03T09:08:24
2023-01-03T09:08:24
81,335,609
0
0
null
null
null
null
UTF-8
C++
false
false
1,090
cpp
/* Explanation The key here is to double the string, that is, append the string to itself. In this way, the pattern would be duplicated. On removing the first and the last characters, if there exists some pattern, we would still be able to find the original string somewhere in the middle, taking some characters from the first half and some from the second half. For example, Example 1. s = "abab" s+s = "abababab" On removing the first and the last characters, we get: (s+s).substr(1, 2*s.size()-2) = "bababa" This new string, "bababa" still contains the original string, "abab". Thus there exists some repeated pattern in the original string itself. Example 2. s = "aba" s+s = "abaaba" On removing the first and the last characters, we get: (s+s).substr(1, 2*s.size()-2) = "baab" This new string, "baab" does not contain the original string, "aba". This implies that there does not exist any pattern in the original string itself. */ class Solution { public: bool repeatedSubstringPattern(string s) { return (s + s).substr(1, 2*s.size()-2).find(s) != -1; } };
[ "drlongle@gmail.com" ]
drlongle@gmail.com
4719da0aa52e37ca50dee53a41706a16b29deaaf
71d51b0e45997693b441a4f41c6730571256571f
/Algorithm/worm.cpp
f81a174e8f28df014edd1b797d79aed7ac32d544
[]
no_license
Coolsik/Algorithm
1403aa7ba4abc502c57cc8286f2b2f9670df266b
50b020c8a4fac603ee1de975f04b43938065153a
refs/heads/master
2016-08-13T01:49:22.439067
2015-10-17T08:24:47
2015-10-17T08:24:47
44,131,248
0
0
null
null
null
null
UTF-8
C++
false
false
705
cpp
#include <iostream> using namespace std; int arr[3][1000001]; int arr2[1000001]; int main() { int a, b, d, N; cin >> a >> b >> d >> N; arr[0][0] = 1; /*for (int i = 1; i <= N; i++) { if (i >= a) { arr[0][i] = arr[0][i - a] + arr[1][i - a]; } if (b - a <= i) { arr[1][i] = arr[0][i - (b - a)]; } if (d - b <= i) { arr[2][i] = arr[1][i-(d - b)] - arr[2][i-(d - b)]; } } cout << arr[0][N-1] + arr[1][N-1] + arr[2][N-1]; */ arr2[0] = 1; for (int i = 1; i <= N; i++) { arr2[i] = arr2[i - 1]; if (i >= a) { arr2[i] += arr2[i - a]; } if (i >= b) { arr2[i] -= arr2[i - b]; } arr2[i] = arr2[i] % 1000; } cout << (arr2[N] - arr2[N - d]+2000)%1000; return 0; }
[ "wsw226@naver.com" ]
wsw226@naver.com
983eb6e3546d632b482ba2a4fd40057283535cd0
536656cd89e4fa3a92b5dcab28657d60d1d244bd
/cc/test/cc_test_suite.cc
8bd9c3e97007fa8f66815cbe46e7ae66b2afc91a
[ "BSD-3-Clause" ]
permissive
ECS-251-W2020/chromium
79caebf50443f297557d9510620bf8d44a68399a
ac814e85cb870a6b569e184c7a60a70ff3cb19f9
refs/heads/master
2022-08-19T17:42:46.887573
2020-03-18T06:08:44
2020-03-18T06:08:44
248,141,336
7
8
BSD-3-Clause
2022-07-06T20:32:48
2020-03-18T04:52:18
null
UTF-8
C++
false
false
1,180
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "cc/test/cc_test_suite.h" #include "base/command_line.h" #include "base/test/task_environment.h" #include "base/threading/thread_id_name_manager.h" #include "cc/base/histograms.h" #include "components/viz/test/paths.h" #include "gpu/ipc/test_gpu_thread_holder.h" #include "ui/gl/test/gl_surface_test_support.h" namespace cc { CCTestSuite::CCTestSuite(int argc, char** argv) : base::TestSuite(argc, argv) {} CCTestSuite::~CCTestSuite() = default; void CCTestSuite::Initialize() { base::TestSuite::Initialize(); task_environment_ = std::make_unique<base::test::SingleThreadTaskEnvironment>(); gl::GLSurfaceTestSupport::InitializeOneOff(); viz::Paths::RegisterPathProvider(); base::ThreadIdNameManager::GetInstance()->SetName("Main"); base::DiscardableMemoryAllocator::SetInstance(&discardable_memory_allocator_); SetClientNameForMetrics("Renderer"); } void CCTestSuite::Shutdown() { task_environment_ = nullptr; base::TestSuite::Shutdown(); } } // namespace cc
[ "pcding@ucdavis.edu" ]
pcding@ucdavis.edu
1cc2efd1cefaa0f9a4ed27f1a13aeddcf5ff86f9
dcc668891c58cd594234d49a209c4a5e788e2341
/include/lol/def/LeaguesLcdsSummonerLeagueItemsDTO.hpp
383202e3b15ab426f017b086bd8acd6222f1cff1
[ "BSD-3-Clause" ]
permissive
Arryboom/LeagueAPI
56d6832f125d1843d575330ae5b0c8172945cca8
be7cb5093aab3f27d95b3c0e1d5700aa50126c47
refs/heads/master
2021-09-28T01:05:12.713109
2018-11-13T03:05:31
2018-11-13T03:05:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
515
hpp
#pragma once #include "../base_def.hpp" #include "LeaguesLcdsLeagueItemDTO.hpp" namespace lol { struct LeaguesLcdsSummonerLeagueItemsDTO { std::vector<LeaguesLcdsLeagueItemDTO> summonerLeagues; }; inline void to_json(json& j, const LeaguesLcdsSummonerLeagueItemsDTO& v) { j["summonerLeagues"] = v.summonerLeagues; } inline void from_json(const json& j, LeaguesLcdsSummonerLeagueItemsDTO& v) { v.summonerLeagues = j.at("summonerLeagues").get<std::vector<LeaguesLcdsLeagueItemDTO>>(); } }
[ "moonshadow565@gmail.com" ]
moonshadow565@gmail.com