hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
6280a98ff22c0548bdbdd060c86e9039300845d5
2,367
cpp
C++
School C++/Display10_10/Palindrome.cpp
holtsoftware/potential-octo-wallhack
8e2165f0371522f42cb117ba83f8aea5c2a1b582
[ "Apache-2.0" ]
null
null
null
School C++/Display10_10/Palindrome.cpp
holtsoftware/potential-octo-wallhack
8e2165f0371522f42cb117ba83f8aea5c2a1b582
[ "Apache-2.0" ]
null
null
null
School C++/Display10_10/Palindrome.cpp
holtsoftware/potential-octo-wallhack
8e2165f0371522f42cb117ba83f8aea5c2a1b582
[ "Apache-2.0" ]
null
null
null
//Test for Palindrom property. //Display 10.10 //Adam Holt #include <iostream> #include <string> #include <ctype.h> using namespace std; void swqp(char& lhs,char &rhs); //swaps char args corresponding to parameters lhs and rhs string reverse(const string& str); //retuns a copy of arg corresponding to parameter //str with characters in revers order. string removePunct(const string& src, const string &punct); //returns copy of string src with characters //in string punct removed string makeLower(const string& s); //returns a copy of parametersthat has all upper case //characters forced to lower case, other charactrs unchanged. //Users <string>, which provides tolower bool isPal(const string& this_string); //uses makeLower, removePunct. //if this_string is a palindrom, // returns true; //else // returns false; int main() { string str; cout<<"Enter a candidate for palindrom test "<<endl <<"Followed bny pressing return."<<endl; getline(cin,str); if(isPal(str)) cout<<"\""<<str+"\"is a palindrome "; else cout<<"\""<<str+"\"is not a palindrome "; cout<<endl; return 0; } void swap(char & lhs, char& rhs) { char temp=lhs; lhs=rhs; rhs=temp; } string reverse(const string& str) { int start=0; int end=str.length(); string temp=str; while(start<end) { end--; swap(temp[start], temp[end]); start++; } return temp; } string makeLower(const string& s) { string temp(s);//This crates a working copy of s for(int i=0;i<s.length();i++) temp[i]=tolower(s[i]); return temp; } //returns a copy of src with characters in punct removed string removePunct(const string& src,const string & punct) { string no_punct; int src_len=src.length(); int punct_len=punct.length(); for(int i=0;i<src_len;i++) { string aChar = src.substr(i,1); int location=punct.find(aChar,0); //find location of successive characters //of src in punct if(location < 0 || location>= punct_len) no_punct=no_punct+aChar; //aChar not in punct -- keep it } return no_punct; } //uses functon makeLower, removePunct. //returned value: //if this_string is a palindrom, // returns true; //else // returns false; bool isPal(const string& this_string) { string punctuation(",;:.?!'\" ");//includes a blank string str=this_string; str=makeLower(str); string lowerStr = removePunct(str,punctuation); return lowerStr == reverse(lowerStr); }
21.324324
61
0.703845
holtsoftware
62810dd1d08578c5649c05c60a1a86eb841462a3
563
cpp
C++
fw/system/display_object.cpp
stefan-misik/ws2812-controller
eb5d091bb360c888e687a30413ea474e641c89ce
[ "MIT" ]
null
null
null
fw/system/display_object.cpp
stefan-misik/ws2812-controller
eb5d091bb360c888e687a30413ea474e641c89ce
[ "MIT" ]
null
null
null
fw/system/display_object.cpp
stefan-misik/ws2812-controller
eb5d091bb360c888e687a30413ea474e641c89ce
[ "MIT" ]
null
null
null
#include "system/display_object.hpp" namespace system { uint8_t DisplayObject::processEvent(const Event & event, Event * new_event) { return EventResult::EVENT_NOT_PROCESSED; } void DisplayObject::draw(DrawContext & dc) { const uint8_t width = dc.drawArea().width(); const uint8_t height = dc.drawArea().height(); for (uint8_t y = 0; y != height; ++y) { uint8_t * data = dc.dataAt(0, y); for (uint8_t x = 0; x != width; ++x) { *data = 0x00; ++data; } } } } // namespace system
20.107143
75
0.584369
stefan-misik
6282eed5f049f3edffad889963aca0e381a4ab46
612
cc
C++
tools/patch/tfs/util/retrier.cc
Cuda-GDB/tensorrt-inference-server
71376ccb1244ed9707b8d81e479e165c152b5767
[ "BSD-3-Clause" ]
2
2021-06-01T09:27:12.000Z
2021-09-18T22:33:08.000Z
tools/patch/tfs/util/retrier.cc
Cuda-GDB/tensorrt-inference-server
71376ccb1244ed9707b8d81e479e165c152b5767
[ "BSD-3-Clause" ]
null
null
null
tools/patch/tfs/util/retrier.cc
Cuda-GDB/tensorrt-inference-server
71376ccb1244ed9707b8d81e479e165c152b5767
[ "BSD-3-Clause" ]
null
null
null
--- tensorflow_serving/util/retrier.cc 2018-05-15 13:11:26.068986416 -0700 +++ /home/david/dev/gitlab/dgx/tensorrtserver/tools/patch/tfs/util/retrier.cc 2018-10-12 12:44:37.280572118 -0700 @@ -42,7 +42,9 @@ if (is_cancelled()) { LOG(INFO) << "Retrying of " << description << " was cancelled."; } - if (num_tries == max_num_retries + 1) { + + // NVIDIA: Add max_num_retries>0 check to avoid spurious logging + if ((max_num_retries > 0) && (num_tries == max_num_retries + 1)) { LOG(INFO) << "Retrying of " << description << " exhausted max_num_retries: " << max_num_retries; }
43.714286
113
0.645425
Cuda-GDB
62841f0aefa1262b5e71f0c3b8d8647913cdea5c
666
cpp
C++
src/MediaDataImpl.cpp
gumb0/cpp-instagram
da3286d8d0945daedb10e00011a09be98c22dcd6
[ "MIT" ]
11
2015-03-10T01:24:09.000Z
2020-01-30T23:07:09.000Z
src/MediaDataImpl.cpp
gumb0/cpp-instagram
da3286d8d0945daedb10e00011a09be98c22dcd6
[ "MIT" ]
5
2016-03-03T09:05:09.000Z
2016-03-03T09:16:52.000Z
src/MediaDataImpl.cpp
gumb0/cpp-instagram
da3286d8d0945daedb10e00011a09be98c22dcd6
[ "MIT" ]
5
2015-11-16T11:46:31.000Z
2022-01-06T11:09:22.000Z
#include "MediaDataImpl.h" #include <assert.h> using namespace Instagram; MediaDataImpl::MediaDataImpl(CurlPtr curl, const MediaDataInfo& info) : mCurl(curl), mInfo(info) { } int MediaDataImpl::getWidth() const { return mInfo.mWidth; } int MediaDataImpl::getHeight() const { return mInfo.mHeight; } std::string MediaDataImpl::getUrl() const { return mInfo.mUrl; } void MediaDataImpl::download(const std::string& localPath) const { mCurl->download(mInfo.mUrl, localPath); } MediaDataPtr Instagram::CreateMediaDataImpl(CurlPtr curl, MediaDataInfoPtr info) { assert(info); return MediaDataPtr(new MediaDataImpl(curl, *info)); }
17.526316
80
0.726727
gumb0
6284d086eba97a7a5afa4411d70300e53ae14d80
2,949
cc
C++
lib/goma_data_util_unittest.cc
dzeromsk/goma
350f67319eb985013515b533f03f2f95570c37d3
[ "BSD-3-Clause" ]
4
2018-12-26T10:54:24.000Z
2022-03-31T21:19:47.000Z
lib/goma_data_util_unittest.cc
dzeromsk/goma
350f67319eb985013515b533f03f2f95570c37d3
[ "BSD-3-Clause" ]
null
null
null
lib/goma_data_util_unittest.cc
dzeromsk/goma
350f67319eb985013515b533f03f2f95570c37d3
[ "BSD-3-Clause" ]
1
2021-05-31T13:27:25.000Z
2021-05-31T13:27:25.000Z
// Copyright 2014 The Goma 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 "lib/goma_data_util.h" #include "gtest/gtest.h" #include "prototmp/goma_data.pb.h" namespace devtools_goma { TEST(GomaProtoUtilTest, IsSameSubprogramShouldBeTrueOnEmptyProto) { ExecReq req; ExecResp resp; EXPECT_TRUE(IsSameSubprograms(req, resp)); } TEST(GomaProtoUtilTest, IsSameSubprogramShouldIgnorePath) { ExecReq req; ExecResp resp; SubprogramSpec dummy_spec; dummy_spec.set_binary_hash("dummy_hash"); SubprogramSpec* spec; spec = req.add_subprogram(); *spec = dummy_spec; spec->set_path("request/path"); spec = resp.mutable_result()->add_subprogram(); *spec = dummy_spec; spec->set_path("response/path"); EXPECT_TRUE(IsSameSubprograms(req, resp)); } TEST(GomaProtoUtilTest, IsSameSubprogramShouldBeTrueIfSameEntries) { ExecReq req; ExecResp resp; SubprogramSpec dummy_spec; dummy_spec.set_path("dummy_path"); dummy_spec.set_binary_hash("dummy_hash"); SubprogramSpec dummy_spec2; dummy_spec.set_path("dummy_path2"); dummy_spec.set_binary_hash("dummy_hash2"); SubprogramSpec* spec; spec = req.add_subprogram(); *spec = dummy_spec; spec = req.add_subprogram(); *spec = dummy_spec2; spec = resp.mutable_result()->add_subprogram(); *spec = dummy_spec; spec = resp.mutable_result()->add_subprogram(); *spec = dummy_spec2; EXPECT_TRUE(IsSameSubprograms(req, resp)); } TEST(GomaProtoUtilTest, IsSameSubprogramShouldBeTrueEvenIfOderIsDifferent) { ExecReq req; ExecResp resp; SubprogramSpec dummy_spec; dummy_spec.set_path("dummy_path"); dummy_spec.set_binary_hash("dummy_hash"); SubprogramSpec dummy_spec2; dummy_spec.set_path("dummy_path2"); dummy_spec.set_binary_hash("dummy_hash2"); SubprogramSpec* spec; spec = req.add_subprogram(); *spec = dummy_spec; spec = req.add_subprogram(); *spec = dummy_spec2; spec = resp.mutable_result()->add_subprogram(); *spec = dummy_spec2; spec = resp.mutable_result()->add_subprogram(); *spec = dummy_spec; EXPECT_TRUE(IsSameSubprograms(req, resp)); } TEST(GomaProtoUtilTest, IsSameSubprogramShouldBeFalseOnSizeMismatch) { ExecReq req; ExecResp resp; SubprogramSpec* spec; spec = req.add_subprogram(); spec->set_path("dummy_path"); spec->set_binary_hash("dummy_hash"); EXPECT_FALSE(IsSameSubprograms(req, resp)); } TEST(GomaProtoUtilTest, IsSameSubprogramShouldBeFalseOnContentsMismatch) { ExecReq req; ExecResp resp; SubprogramSpec dummy_spec; dummy_spec.set_path("dummy_path"); SubprogramSpec* spec; spec = req.add_subprogram(); *spec = dummy_spec; spec->set_binary_hash("dummy_hash"); spec = resp.mutable_result()->add_subprogram(); *spec = dummy_spec; spec->set_binary_hash("different_hash"); EXPECT_FALSE(IsSameSubprograms(req, resp)); } } // namespace devtools_goma
23.97561
76
0.748389
dzeromsk
628d03cf81dd36dfeeaf4ac4a41241bf9e3cd5cd
896
cpp
C++
review/src/android/ReviewAndroid.cpp
dapetcu21/extension-review
1e9e3471ce98141016562aeec693f4cfd98a5c48
[ "MIT" ]
10
2020-11-23T21:16:56.000Z
2022-03-07T20:17:40.000Z
review/src/android/ReviewAndroid.cpp
dapetcu21/extension-review
1e9e3471ce98141016562aeec693f4cfd98a5c48
[ "MIT" ]
2
2020-08-12T19:34:36.000Z
2020-10-09T22:06:36.000Z
review/src/android/ReviewAndroid.cpp
dapetcu21/extension-review
1e9e3471ce98141016562aeec693f4cfd98a5c48
[ "MIT" ]
8
2017-10-03T12:01:35.000Z
2020-10-09T21:06:44.000Z
#if defined(DM_PLATFORM_ANDROID) #include "../private_review.h" #include "jni.h" namespace ext_review { const char* JAR_PATH = "com/defold/review/Review"; bool isSupported() { ThreadAttacher attacher; JNIEnv *env = attacher.env; jclass cls = ClassLoader(env).load(JAR_PATH); jmethodID method = env->GetStaticMethodID(cls, "isSupported", "(Landroid/app/Activity;)Z"); jboolean return_value = (jboolean)env->CallStaticBooleanMethod(cls, method, dmGraphics::GetNativeAndroidActivity()); return JNI_TRUE == return_value; } void requestReview() { ThreadAttacher attacher; JNIEnv *env = attacher.env; jclass cls = ClassLoader(env).load(JAR_PATH); jmethodID method = env->GetStaticMethodID(cls, "requestReview", "(Landroid/app/Activity;)V"); env->CallStaticVoidMethod(cls, method, dmGraphics::GetNativeAndroidActivity()); } }//namespace #endif
28.903226
97
0.722098
dapetcu21
6290fc655f2607265e486f3f63eea181c565935e
2,537
cpp
C++
patched_D-ITG-2.8.1-r1023/src/ITGSend/newran/extreal.cpp
akhila-s-rao/high-fidelity-wireless-measurements
64bcaa9e0da5338b9495b63cd7aa67d94eaf3bf5
[ "Apache-2.0" ]
4
2015-07-07T13:00:16.000Z
2021-02-25T13:03:25.000Z
patched_D-ITG-2.8.1-r1023/src/ITGSend/newran/extreal.cpp
akhila-s-rao/high-fidelity-wireless-measurements
64bcaa9e0da5338b9495b63cd7aa67d94eaf3bf5
[ "Apache-2.0" ]
1
2022-02-04T08:43:41.000Z
2022-02-20T22:54:28.000Z
patched_D-ITG-2.8.1-r1023/src/ITGSend/newran/extreal.cpp
akhila-s-rao/high-fidelity-wireless-measurements
64bcaa9e0da5338b9495b63cd7aa67d94eaf3bf5
[ "Apache-2.0" ]
2
2018-06-07T20:47:50.000Z
2020-07-20T09:55:04.000Z
/// \ingroup newran ///@{ /// \file extreal.cpp /// "Extended real" - body file. #define WANT_FSTREAM #include "include.h" #include "extreal.h" #ifdef use_namespace namespace RBD_COMMON { #endif ExtReal ExtReal::operator+(const ExtReal& er) const { if (c==Finite && er.c==Finite) return ExtReal(value+er.value); if (c==Missing || er.c==Missing) return ExtReal(Missing); if (c==Indefinite || er.c==Indefinite) return ExtReal(Indefinite); if (c==PlusInfinity) { if (er.c==MinusInfinity) return ExtReal(Indefinite); return *this; } if (c==MinusInfinity) { if (er.c==PlusInfinity) return ExtReal(Indefinite); return *this; } return er; } ExtReal ExtReal::operator-(const ExtReal& er) const { if (c==Finite && er.c==Finite) return ExtReal(value-er.value); if (c==Missing || er.c==Missing) return ExtReal(Missing); if (c==Indefinite || er.c==Indefinite) return ExtReal(Indefinite); if (c==PlusInfinity) { if (er.c==PlusInfinity) return ExtReal(Indefinite); return *this; } if (c==MinusInfinity) { if (er.c==MinusInfinity) return ExtReal(Indefinite); return *this; } return er; } ExtReal ExtReal::operator*(const ExtReal& er) const { if (c==Finite && er.c==Finite) return ExtReal(value*er.value); if (c==Missing || er.c==Missing) return ExtReal(Missing); if (c==Indefinite || er.c==Indefinite) return ExtReal(Indefinite); if (c==Finite) { if (value==0.0) return ExtReal(Indefinite); if (value>0.0) return er; return (-er); } if (er.c==Finite) { if (er.value==0.0) return ExtReal(Indefinite); if (er.value>0.0) return *this; return -(*this); } if (c==PlusInfinity) return er; return (-er); } ExtReal ExtReal::operator-() const { switch (c) { case Finite: return ExtReal(-value); case PlusInfinity: return ExtReal(MinusInfinity); case MinusInfinity: return ExtReal(PlusInfinity); case Indefinite: return ExtReal(Indefinite); case Missing: return ExtReal(Missing); } return 0.0; } ostream& operator<<(ostream& os, const ExtReal& er) { switch (er.c) { case Finite: os << er.value; break; case PlusInfinity: os << "plus-infinity"; break; case MinusInfinity: os << "minus-infinity"; break; case Indefinite: os << "indefinite"; break; case Missing: os << "missing"; break; } return os; } #ifdef use_namespace } #endif ///@}
24.161905
69
0.615294
akhila-s-rao
6292e28d9e2382ecb28c3f579b8c7f3d2219272a
1,215
hpp
C++
example/vgg16/vgg16.hpp
wzppengpeng/LittleConv
12aab4cfbbe965fa8b4053bb464db1165cc4ec31
[ "MIT" ]
93
2017-10-25T07:48:42.000Z
2022-02-02T15:18:11.000Z
example/vgg16/vgg16.hpp
wzppengpeng/LittleConv
12aab4cfbbe965fa8b4053bb464db1165cc4ec31
[ "MIT" ]
null
null
null
example/vgg16/vgg16.hpp
wzppengpeng/LittleConv
12aab4cfbbe965fa8b4053bb464db1165cc4ec31
[ "MIT" ]
20
2018-02-06T10:01:36.000Z
2019-07-07T09:26:40.000Z
#ifndef VGG16_HPP #define VGG16_HPP #include "licon/licon.hpp" using namespace licon; // get the conv block nn::NodePtr ConvBlock(int in_channel, int out_channel, bool triple = false) { auto block = nn::Squential::CreateSquential(); block->Add(nn::Conv::CreateConv(in_channel, out_channel, 3, 1, 1)); block->Add(nn::BatchNorm::CreateBatchNorm(out_channel)); block->Add(nn::Relu::CreateRelu()); block->Add(nn::Conv::CreateConv(out_channel, out_channel, 3, 1, 1)); block->Add(nn::BatchNorm::CreateBatchNorm(out_channel)); block->Add(nn::Relu::CreateRelu()); if(triple) { block->Add(nn::Conv::CreateConv(out_channel, out_channel, 3, 1, 1)); block->Add(nn::BatchNorm::CreateBatchNorm(out_channel)); block->Add(nn::Relu::CreateRelu()); } block->Add(nn::MaxPool::CreateMaxPool(2)); return block; } nn::Model Vgg() { auto net = nn::Squential::CreateSquential(); net->Add(ConvBlock(3, 16)); //16 * 16 net->Add(ConvBlock(16, 32)); //8 * 8 net->Add(ConvBlock(32, 64)); // 4 * 4 net->Add(ConvBlock(64, 128)); //2 * 2 net->Add(ConvBlock(128, 256)); //1 * 1 net->Add(nn::Linear::CreateLinear(256, 10)); return net; } #endif
32.837838
77
0.641152
wzppengpeng
6292fc7eda6d43fe4158083a6806cb045cbbb9cf
7,111
cpp
C++
examples_oldgl_glfw/146_4RotSymFieldMultilevel/main.cpp
nobuyuki83/delfem2
118768431ccc5b77ed10b8f76f625d38e0b552f0
[ "MIT" ]
153
2018-08-16T21:51:33.000Z
2022-03-28T10:34:48.000Z
examples_oldgl_glfw/146_4RotSymFieldMultilevel/main.cpp
nobuyuki83/delfem2
118768431ccc5b77ed10b8f76f625d38e0b552f0
[ "MIT" ]
63
2018-08-16T21:53:34.000Z
2022-02-22T13:50:34.000Z
examples_oldgl_glfw/146_4RotSymFieldMultilevel/main.cpp
nobuyuki83/delfem2
118768431ccc5b77ed10b8f76f625d38e0b552f0
[ "MIT" ]
18
2018-12-17T05:39:15.000Z
2021-11-16T08:21:16.000Z
/* * Copyright (c) 2019 Nobuyuki Umetani * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /** * @brief implementation of 4 rotatoinal symetry field * @details implementation is based on "Wenzel Jakob, Marco Tarini, Daniele Panozzo, and Olga Sorkine-Hornung. * Instant field-aligned meshes. Siggraph Asia 2015" */ #include <cstdlib> #if defined(_WIN32) // windows # define NOMINMAX // to remove min,max macro # include <windows.h> // this should come before glfw3.h #endif #define GL_SILENCE_DEPRECATION #include <GLFW/glfw3.h> #include "delfem2/msh_io_ply.h" #include "delfem2/mshmisc.h" #include "delfem2/points.h" #include "delfem2/mshuni.h" #include "delfem2/vec3.h" #include "delfem2/4rotsym.h" #include "delfem2/clusterpoints.h" #include "delfem2/glfw/viewer3.h" #include "delfem2/glfw/util.h" #include "delfem2/opengl/old/funcs.h" #include "delfem2/opengl/old/mshuni.h" #include "delfem2/opengl/old/v3q.h" namespace dfm2 = delfem2; // --------------- void Draw( const std::vector<double> &aXYZ, const std::vector<double> &aNorm, const std::vector<double> &aOdir, const std::vector<unsigned int> &aTri) { ::glEnable(GL_LIGHTING); dfm2::opengl::DrawMeshTri3D_FaceNorm( aXYZ.data(), aTri.data(), aTri.size() / 3); ::glDisable(GL_LIGHTING); double len = 0.03; ::glLineWidth(3); const size_t np = aXYZ.size() / 3; for (unsigned int ip = 0; ip < np; ++ip) { const dfm2::CVec3d p = dfm2::CVec3d(aXYZ.data() + ip * 3); const dfm2::CVec3d n = dfm2::CVec3d(aNorm.data() + ip * 3).normalized(); const dfm2::CVec3d o = dfm2::CVec3d(aOdir.data() + ip * 3).normalized(); const dfm2::CVec3d q = dfm2::Cross(n, o); ::glBegin(GL_LINES); // ::glColor3d(0,0,0); // dfm2::opengl::myGlVertex(p); // dfm2::opengl::myGlVertex(p+len*n); ::glColor3d(0, 0, 1); dfm2::opengl::myGlVertex(p - len * o); dfm2::opengl::myGlVertex(p); ::glColor3d(1, 0, 0); dfm2::opengl::myGlVertex(p); dfm2::opengl::myGlVertex(p + len * o); dfm2::opengl::myGlVertex(p - len * q); dfm2::opengl::myGlVertex(p + len * q); ::glEnd(); } } int main() { class CClusterData { public: std::vector<double> aXYZ; // center position of the cluster std::vector<double> aArea; // area of the cluster std::vector<double> aNorm; // normal of the cluster std::vector<double> aOdir; // director vector std::vector<unsigned int> psup_ind, psup; // connectivity of the cluster std::vector<unsigned int> map_fine2this; // index of cluster for mesh points. // below: data for visualization // std::vector<float> aColor; // color of the cluster // std::vector<unsigned int> map0c; // index of cluster for mesh points. }; std::vector<CClusterData> aLayer; std::vector<unsigned int> aTri; { // load level 0 aLayer.resize(1); delfem2::Read_Ply( aLayer[0].aXYZ, aTri, std::filesystem::path(PATH_INPUT_DIR) / "bunny_1k.ply"); delfem2::Normalize_Points3(aLayer[0].aXYZ); aLayer[0].aNorm.resize(aLayer[0].aXYZ.size()); dfm2::Normal_MeshTri3D( aLayer[0].aNorm.data(), aLayer[0].aXYZ.data(), aLayer[0].aXYZ.size() / 3, aTri.data(), aTri.size() / 3); { const double minCoords[3] = {-1, -1, -1}; const double maxCoords[3] = {+1, +1, +1}; aLayer[0].aOdir.resize(aLayer[0].aXYZ.size()); dfm2::Points_RandomUniform( aLayer[0].aOdir.data(), aLayer[0].aXYZ.size() / 3, 3, minCoords, maxCoords); dfm2::TangentVector_Points3( aLayer[0].aOdir, aLayer[0].aNorm); } aLayer[0].aArea.resize(aLayer[0].aXYZ.size() / 3); dfm2::MassPoint_Tri3D( aLayer[0].aArea.data(), 1.0, aLayer[0].aXYZ.data(), aLayer[0].aXYZ.size() / 3, aTri.data(), aTri.size() / 3); dfm2::JArray_PSuP_MeshElem( aLayer[0].psup_ind, aLayer[0].psup, aTri.data(), aTri.size() / 3, 3, aLayer[0].aXYZ.size() / 3); } for (unsigned int itr = 0; itr < 8; ++itr) { aLayer.resize(aLayer.size() + 1); const CClusterData &pd0 = aLayer[itr]; CClusterData &pd1 = aLayer[itr + 1]; dfm2::BinaryClustering_Points3d( pd1.aXYZ, pd1.aArea, pd1.aNorm, pd1.map_fine2this, pd0.aXYZ, pd0.aArea, pd0.aNorm, pd0.psup_ind, pd0.psup); dfm2::Clustering_Psup( pd1.psup_ind, pd1.psup, pd1.aXYZ.size() / 3, pd0.aXYZ.size() / 3, pd1.map_fine2this.data(), pd0.psup_ind.data(), pd0.psup.data()); } const auto nlayer = static_cast<unsigned int>(aLayer.size()); for (unsigned int ilayer = nlayer - 1; ilayer != UINT_MAX; --ilayer) { if (ilayer == nlayer - 1) { const double minCoords[3] = {-1, -1, -1}; const double maxCoords[3] = {+1, +1, +1}; aLayer[ilayer].aOdir.resize(aLayer[ilayer].aXYZ.size()); dfm2::Points_RandomUniform( aLayer[ilayer].aOdir.data(), aLayer[ilayer].aXYZ.size() / 3, 3, minCoords, maxCoords); dfm2::TangentVector_Points3(aLayer[ilayer].aOdir, aLayer[ilayer].aNorm); } else { const auto np0 = static_cast<unsigned int>(aLayer[ilayer].aXYZ.size() / 3); // this assert(aLayer[ilayer + 1].map_fine2this.size() == np0); // const unsigned int np1 = aLayer[ilayer].aOdir.resize(np0 * 3); for (unsigned int ip0 = 0; ip0 < np0; ++ip0) { unsigned int ip1 = aLayer[ilayer + 1].map_fine2this[ip0]; assert(ip1 < static_cast<unsigned int>(aLayer[ilayer + 1].aXYZ.size() / 3)); aLayer[ilayer].aOdir[ip0 * 3 + 0] = aLayer[ilayer + 1].aOdir[ip1 * 3 + 0]; aLayer[ilayer].aOdir[ip0 * 3 + 1] = aLayer[ilayer + 1].aOdir[ip1 * 3 + 1]; aLayer[ilayer].aOdir[ip0 * 3 + 2] = aLayer[ilayer + 1].aOdir[ip1 * 3 + 2]; } } dfm2::Smooth4RotSym( aLayer[ilayer].aOdir, aLayer[ilayer].aNorm, aLayer[ilayer].psup_ind, aLayer[ilayer].psup); } // ------------------ delfem2::glfw::CViewer3 viewer; dfm2::glfw::InitGLOld(); viewer.InitGL(); dfm2::opengl::setSomeLighting(); unsigned int iframe = 0; while (true) { /* if( iframe == 0 ){ // dfm2::InitializeTangentField(aLayer[0].aOdir,aLayer[0].aNorm); } if( iframe > 30 ){ // dfm2::Smooth4RotSym(aLayer[0].aOdir, // aLayer[0].aNorm, aLayer[0].psup_ind, aLayer[0].psup); } */ // -------------------- viewer.DrawBegin_oldGL(); Draw(aLayer[0].aXYZ, aLayer[0].aNorm, aLayer[0].aOdir, aTri); /* ::glColor3d(0,0,0); ::glLineWidth(2); dfm2::opengl::DrawMeshTri3D_Edge(aLayer[0].aXYZ.data(),aLayer[0].aXYZ.size()/3,aTri.data(),aTri.size()/3); dfm2::opengl::DrawMeshTri3D_FaceNorm(aLayer[0].aXYZ.data(),aTri.data(),aTri.size()/3); */ glfwSwapBuffers(viewer.window); glfwPollEvents(); iframe = (iframe + 1) % 60; if (glfwWindowShouldClose(viewer.window)) { goto EXIT; } } EXIT: glfwDestroyWindow(viewer.window); glfwTerminate(); exit(EXIT_SUCCESS); }
34.519417
110
0.612572
nobuyuki83
629696e09e6214b4637311c9f8c8bd9d8adb285f
1,714
cpp
C++
Module 2/Chapter_9/Source/Cookbook_Chapter9/CollectableObject.cpp
PacktPublishing/Game-Development-using-Unreal-Engine
2a4f5c8662879037403706cb1f0bd8a6caddcc78
[ "MIT" ]
12
2016-09-12T14:21:53.000Z
2021-11-20T07:55:03.000Z
Module 2/Chapter_9/Source/Cookbook_Chapter9/CollectableObject.cpp
PacktPublishing/Game-Development-using-Unreal-Engine
2a4f5c8662879037403706cb1f0bd8a6caddcc78
[ "MIT" ]
null
null
null
Module 2/Chapter_9/Source/Cookbook_Chapter9/CollectableObject.cpp
PacktPublishing/Game-Development-using-Unreal-Engine
2a4f5c8662879037403706cb1f0bd8a6caddcc78
[ "MIT" ]
5
2017-07-27T05:23:09.000Z
2021-12-20T11:44:42.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "Cookbook_Chapter9.h" #include "CollectableObject.h" #include "Engine.h" //GEngine // Sets default values for this actor's properties ACollectableObject::ACollectableObject(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { // Must be true for an Actor to replicate anything bReplicates = true; // Create a sphere collider for players to hit USphereComponent * SphereCollider = ObjectInitializer.CreateDefaultSubobject<USphereComponent>(this, TEXT("SphereComponent")); //Sets the size of our collider to have a radius of 64 units SphereCollider->InitSphereRadius(64.0f); //Sets the root of our object to be the sphere collider RootComponent = SphereCollider; // Makes it so that OnBeginOverlap will be called whenever something hits this. SphereCollider->OnComponentBeginOverlap.AddDynamic(this, &ACollectableObject::OnBeginOverlap); } // Event called when something starts to overlaps the sphere collider void ACollectableObject::OnBeginOverlap(class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { // If I am the server if (Role == ROLE_Authority) { // Then a coin will be gained! UpdateScore(1); Destroy(); } } // Do something here that modifies game state. void ACollectableObject::UpdateScore_Implementation(int32 Amount) { if (GEngine) { GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Green, "Collected!"); } } // Optionally validate the request and return false if the function should not be run. bool ACollectableObject::UpdateScore_Validate(int32 Amount) { return true; }
32.339623
173
0.780047
PacktPublishing
629bb8774f5fd140c31b7dc663c30e7bbbfb55c1
440
cpp
C++
C++/0202-Happy-Number/soln.cpp
wyaadarsh/LeetCode-Solutions
3719f5cb059eefd66b83eb8ae990652f4b7fd124
[ "MIT" ]
5
2020-07-24T17:48:59.000Z
2020-12-21T05:56:00.000Z
C++/0202-Happy-Number/soln.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
null
null
null
C++/0202-Happy-Number/soln.cpp
zhangyaqi1989/LeetCode-Solutions
2655a1ffc8678ad1de6c24295071308a18c5dc6e
[ "MIT" ]
2
2020-07-24T17:49:01.000Z
2020-08-31T19:57:35.000Z
class Solution { public: bool isHappy(int n) { unordered_set<int> m; while(true) { int ans = 0; while (n) { int val = n % 10; n /= 10; ans += val * val; } if (ans == 1) return true; if(m.count(ans)) return false; m.insert(ans); n = ans; } } };
20.952381
42
0.331818
wyaadarsh
629c3c21b8db379220b7008dd64cd955896fda75
1,952
cpp
C++
src/model/company_client/company_client_manager/company_client_manager.cpp
luist18/feup-cal-proj
b7fbb8aaed63c705cd85125b3d3f88ae77b1416c
[ "MIT" ]
null
null
null
src/model/company_client/company_client_manager/company_client_manager.cpp
luist18/feup-cal-proj
b7fbb8aaed63c705cd85125b3d3f88ae77b1416c
[ "MIT" ]
null
null
null
src/model/company_client/company_client_manager/company_client_manager.cpp
luist18/feup-cal-proj
b7fbb8aaed63c705cd85125b3d3f88ae77b1416c
[ "MIT" ]
2
2020-05-05T11:19:34.000Z
2020-06-07T14:41:46.000Z
#include <algorithm> #include "company_client_manager.h" CompanyClientManager::CompanyClientManager() = default; bool CompanyClientManager::isValid(const CompanyClient &companyClient) const { return companyClient.getUUID() != 0 && !companyClient.getName().empty(); } bool CompanyClientManager::add(CompanyClient companyClient) { if (!isValid(companyClient)) return false; if (has(companyClient)) return false; companies.push_back(companyClient); return true; } bool CompanyClientManager::remove(CompanyClient companyClient) { if (!has(companyClient)) return false; companies.erase(std::find(companies.begin(), companies.end(), companyClient)); return true; } bool CompanyClientManager::has(CompanyClient &companyClient) const { return std::find(companies.begin(), companies.end(), companyClient) != companies.end(); } bool CompanyClientManager::has(const long uuid) const { return std::find_if(companies.begin(), companies.end(), [&uuid](const CompanyClient &companyClient) { return companyClient.getUUID() == uuid; }) != companies.end(); } std::vector<CompanyClient> CompanyClientManager::getCompanies() const { return companies; } long CompanyClientManager::getUsedVehiclesNumber() const { long total = 0; for (const CompanyClient &companyClient : this->companies) total += companyClient.getVehicleNumber(); return total; } CompanyClient *CompanyClientManager::getCompany(long uuid) { auto it = companies.begin(); while (it != companies.end()) { if ((*it).getUUID() == uuid) { return &(*it); } it++; } return nullptr; } CompanyClient *CompanyClientManager::getCompany(const std::string &email) { auto it = companies.begin(); while (it != companies.end()) { if ((*it).getRepresentative().getEmail() == email) { return &(*it); } it++; } return nullptr; }
27.111111
105
0.676742
luist18
629d4b55920bdddcd6ce9481ecbed62c6a9826fc
970
cc
C++
ash/shell/content_client/shell_content_browser_client.cc
codenote/chromium-test
0637af0080f7e80bf7d20b29ce94c5edc817f390
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5
2018-03-10T13:08:42.000Z
2021-07-26T15:02:11.000Z
ash/shell/content_client/shell_content_browser_client.cc
quisquous/chromium
b25660e05cddc9d0c3053b3514f07037acc69a10
[ "BSD-3-Clause" ]
1
2015-07-21T08:02:01.000Z
2015-07-21T08:02:01.000Z
ash/shell/content_client/shell_content_browser_client.cc
jianglong0156/chromium.src
d496dfeebb0f282468827654c2b3769b3378c087
[ "BSD-3-Clause" ]
6
2016-11-14T10:13:35.000Z
2021-01-23T15:29:53.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/shell/content_client/shell_content_browser_client.h" #include "ash/shell/content_client/shell_browser_main_parts.h" #include "third_party/skia/include/core/SkBitmap.h" namespace ash { namespace shell { ShellContentBrowserClient::ShellContentBrowserClient() : shell_browser_main_parts_(NULL) { } ShellContentBrowserClient::~ShellContentBrowserClient() { } content::BrowserMainParts* ShellContentBrowserClient::CreateBrowserMainParts( const content::MainFunctionParams& parameters) { shell_browser_main_parts_ = new ShellBrowserMainParts(parameters); return shell_browser_main_parts_; } content::ShellBrowserContext* ShellContentBrowserClient::browser_context() { return shell_browser_main_parts_->browser_context(); } } // namespace examples } // namespace views
30.3125
77
0.802062
codenote
62a269883233ffb3ccebbebc643541651a26c5d7
22,021
cc
C++
PA5/ast_stmt.cc
atomic/CSE131
9d60c16f65fbd5cb91840643cbe6c4c9f5fdd2b4
[ "MIT" ]
1
2019-04-22T07:40:24.000Z
2019-04-22T07:40:24.000Z
PA5/ast_stmt.cc
atomic/CSE131
9d60c16f65fbd5cb91840643cbe6c4c9f5fdd2b4
[ "MIT" ]
null
null
null
PA5/ast_stmt.cc
atomic/CSE131
9d60c16f65fbd5cb91840643cbe6c4c9f5fdd2b4
[ "MIT" ]
null
null
null
/* File: ast_stmt.cc * ----------------- * Implementation of statement node classes. */ #include "ast_stmt.h" #include "ast_type.h" #include "ast_decl.h" #include "ast_expr.h" #include <cctype> #include <unordered_map> #include <utility> #include <sstream> #include <iterator> #include <iomanip> typedef pair<string, string> Trump; Program::Program(List<Decl*> *d) { Assert(d != NULL); (decls=d)->SetParentAll(this); } void Program::PrintChildren(int indentLevel) { decls->PrintAll(indentLevel+1); printf("\n"); } StmtBlock::StmtBlock(List<Stmt*> *s) { Assert(s != NULL); (stmts=s)->SetParentAll(this); } void StmtBlock::PrintChildren(int indentLevel) { stmts->PrintAll(indentLevel+1); } ConditionalStmt::ConditionalStmt(Expr *t, Stmt *b) { Assert(t != NULL && b != NULL); (test=t)->SetParent(this); (body=b)->SetParent(this); } ForStmt::ForStmt(Expr *i, Expr *t, Expr *s, Stmt *b): LoopStmt(t, b) { Assert(i != NULL && t != NULL && s != NULL && b != NULL); (init=i)->SetParent(this); (step=s)->SetParent(this); } void ForStmt::PrintChildren(int indentLevel) { init->Print(indentLevel+1, "(init) "); test->Print(indentLevel+1, "(test) "); step->Print(indentLevel+1, "(step) "); body->Print(indentLevel+1, "(body) "); } void WhileStmt::PrintChildren(int indentLevel) { test->Print(indentLevel+1, "(test) "); body->Print(indentLevel+1, "(body) "); } IfStmt::IfStmt(Expr *t, Stmt *tb, Stmt *eb): ConditionalStmt(t, tb) { Assert(t != NULL && tb != NULL); // else can be NULL elseBody = eb; if (elseBody) elseBody->SetParent(this); } void IfStmt::PrintChildren(int indentLevel) { if (test) test->Print(indentLevel+1, "(test) "); if (body) body->Print(indentLevel+1, "(then) "); if (elseBody) elseBody->Print(indentLevel+1, "(else) "); } ReturnStmt::ReturnStmt(yyltype loc, Expr *e) : Stmt(loc) { Assert(e != NULL); (expr=e)->SetParent(this); } void ReturnStmt::PrintChildren(int indentLevel) { expr->Print(indentLevel+1); } DeclStmt::DeclStmt(yyltype loc, Decl *decl) : Stmt(loc) { Assert(decl != NULL); (varDecl=decl)->SetParent(this); } void DeclStmt::PrintChildren(int indentLevel) { varDecl->Print(indentLevel+1); } void split(const string& s, const string& delim, vector<string>& v, bool clear = true) { int start = 0; int end = s.find(delim, start); if (clear) v.clear(); while (end != string::npos) { v.push_back(s.substr(start, end - start)); start = end + delim.length(); end = s.find(delim, start); } v.push_back(s.substr(start, s.length())); } bool isNumeric(const string& s) { return s.find_first_not_of("0123456789") == string::npos; } bool isOperator(const string& s) { return s.find_first_not_of("+-/*%^=") == string::npos; } /** * evaluate arithmetic expressions in code * @param TACContainer * @return */ void constantFolding(vector<TACObject>& TACContainer) { vector<string> split_result; for (int i = 0; i < TACContainer.size(); ++i) { if (TACContainer[i].type != stmt) continue; split(TACContainer[i].rhs, " ", split_result); if (split_result.size() != 3) continue; bool qualified = isNumeric(split_result[0]) && isNumeric(split_result[2]); if (qualified) { int a = split_result[0] == "" ? 0 : stoi(split_result[0]); int b = stoi(split_result[2]); string op = split_result[1]; if (op.compare("+") == 0) TACContainer[i].rhs = to_string(a + b); else if (op.compare("-") == 0) TACContainer[i].rhs = to_string(a - b); else if (op.compare("/") == 0) TACContainer[i].rhs = to_string(a / b); else if (op.compare("*") == 0) { TACContainer[i].rhs = to_string(a * b); } } } } /** * remove unused initalized variables from code * @param TACContainer * @return */ void deadCodeElimination(vector<TACObject>& TACContainer) { vector<pair<int,string>> variables; vector<string> used_tokens; // collect all tokens both rhs and lhs for (int j = 0; j < TACContainer.size(); ++j) { TACObject &taco = TACContainer[j]; if (taco.type == stmt) { split(taco.rhs, " ", used_tokens, false); // false here means update the used_tokens, instead of reseting it variables.emplace_back(j, taco.lhs); } else if (taco.type == branch) split(taco.lhs, " ", used_tokens, false); // for branch, lhs may contain variables used in the code else if (taco.type == instr && taco.lhs == "Return") split(taco.rhs, " ", used_tokens, false); // for return, rhs may contains variable } // Cleans up token that is not a variable (integer and operators) for (int i = 0; i < used_tokens.size(); ++i) if (isNumeric(used_tokens[i]) || isOperator(used_tokens[i])) used_tokens.erase(used_tokens.begin() + i-- ); set<string> rhs_unique(used_tokens.begin(), used_tokens.end()); // remove varible that does not appear in rhs_token (add index to remove first) vector<int> index_to_delete; for (auto var : variables) if (rhs_unique.find(var.second) == rhs_unique.end()) index_to_delete.insert(index_to_delete.begin(), var.first); for (auto item : index_to_delete) TACContainer.erase(TACContainer.begin() + item); } /** * turn X = 5; X = X + 3 --> X = 5 + 3 * @param TACContainer * @return */ void constantPropagation(vector<TACObject>& TACContainer) { unordered_map<string, string> value_map; // collect all tokens both rhs and lhs vector<string> rhs_tokens; for (auto &taco : TACContainer) { if (taco.type == stmt) { if (isNumeric(taco.rhs)) { if (value_map.find(taco.lhs) != value_map.end()) // re-assignment, stop break; value_map[taco.lhs] = taco.rhs; // save initialized values } else { // do replacement split(taco.rhs, " ", rhs_tokens); bool changed = false; for (auto &token : rhs_tokens) { if (value_map.find(token) != value_map.end() ) { token = value_map[token]; changed = true; } } if (changed) { stringstream imploded; copy(rhs_tokens.begin(), rhs_tokens.end(), ostream_iterator<string>(imploded, " ")); taco.rhs = imploded.str(); taco.rhs.pop_back(); // remove last space from the join operation } } } } // for (auto pair : value_map) // cout << pair.first << "," << pair.second << endl; } /** * Function assigns a temporary register to each variable found within the TAC * container. * * @param * @return */ void linearScan(map<string, Trump>& regMap, vector<TACObject>& container) { vector<string> rhs_tokens; string curr_context; unordered_map<string, int> registerCount; for (auto &taco : container) { if (taco.type == label && taco.lhs[0] != 'L') { curr_context = taco.lhs; continue; } if (taco.type != stmt) continue; split(taco.rhs, " ", rhs_tokens); if (rhs_tokens.size() != 1) { if (regMap.find(taco.lhs) != regMap.end()) continue; if (taco.lhs[0] == 't') { regMap[taco.lhs] = make_pair(taco.lhs, curr_context); continue; } auto reg = "t" + to_string(Node::tempRegister[curr_context]); Node::tempRegister[curr_context]++; Node::stackRegister++; regMap[taco.lhs] = make_pair(reg, curr_context); } else { if (taco.rhs[0] == 't') { regMap[taco.lhs] = make_pair(taco.rhs, curr_context); } else { auto reg = "t" + to_string(Node::tempRegister[curr_context]); Node::tempRegister[curr_context]++; Node::stackRegister++; regMap[taco.lhs] = make_pair(reg, curr_context); } } } } string binaryExprToMIPS(string c, string a, string b, string op) { /* * The parameters are ordered based on the binary expression. * c := a op b * * * The local variables rd, rs, rt follows the MIPS green sheet format. * For R-type instructions: * rd - the destination register * rs - a source register * rt - a source register * The format for R-type usually looks like the following: * (R-type instruction) $rd, $rs, $rt * * For I-type instructions: * rt - the destination register * rs - a source register * imm - some immediate value * The formart for I-type usually looks like the following: * (I-type instruction) $rt, $rs, imm * * NOTE: for I-type instructions I simply re-use the 'rt' as my immediate * value */ if (op == ">") return binaryExprToMIPS(c, b, a, "<"); if (op == ">=") return binaryExprToMIPS(c, b, a, "<="); string mipsCode = ""; string instr = ""; string rs = "$" + a; string rt = "$" + b; string rd = "$" + c; const string &context = Node::current_context; // Assume parameter 'b' not a constant. Use R-Type instruction. bool iType = false; // How to translate 100 < $t0 to MIPS? First use li to store 100 into // register $rs, then use slt $rd, $rs, $rt if (isNumeric(a) && (op == "<" || op == "<=")) { rs = "$t" + to_string(Node::tempRegister[context]); Node::tempRegister[context]++; Node::stackRegister; mipsCode += " li " + rs + ", " + a + "\n"; } // How to translate a := 4 + a to MIPS? Change positions to a := a + 4, and // use addi. if (isNumeric(a) && (op != "<" && op != "<=")) { iType = true; rt = a; rs = "$" + b; } // How to translate $t0 < 140 to MIPS? Use I-type instruction. if (isNumeric(b)) { iType = true; rt = b; } if (op == "<") { instr = " slt"; instr += (iType) ? "i" : ""; mipsCode += instr + " " + rd + ", " + rs + ", " + rt; return mipsCode; } if (op == "<=") { mipsCode += binaryExprToMIPS(c, a, b, ">") + "\n"; mipsCode += " not " + rd + ", " + rd + "\n"; mipsCode += " andi " + rd + ", " + rd + ", 1"; return mipsCode; } if (op == "+") { instr = " add"; instr += (iType) ? "i" : ""; mipsCode += instr + " " + rd + ", " + rs + ", " + rt; return mipsCode; } return "ERROR operator (" + op + ") not supported!"; } void generateIR(const vector<TACObject>& TACContainer) { for (int i = 0; i < TACContainer.size(); ++i) { switch(TACContainer[i].type) { case label: cout << TACContainer[i].lhs + ":" << endl; break; case stmt: cout << " " + TACContainer[i].lhs << " := " << TACContainer[i].rhs << endl; break; case instr: cout << " " + TACContainer[i].lhs << " " + TACContainer[i].rhs << endl; break; case print: case call: cout << " " + TACContainer[i].lhs << " call " + TACContainer[i].rhs << endl; break; case branch: cout << " if " + TACContainer[i].lhs << " goto " + TACContainer[i].rhs << endl; break; case jump: cout << " goto " + TACContainer[i].lhs << endl; break; default: cout << " ERRRORRR !!!! " << endl; } } } /** * Debug function to print out the detail of TACObject * * @param taco : the TACObject of interest */ void printTAC(const TACObject& taco) { map<tactype ,string> tactype_map { {label, "Label"}, {instr, "instr"}, {stmt, "stmt"}, {call, "call"}, {print, "print"}, {branch, "branch"}, {jump, "jump"}, }; cout << setw(20) << "(" << tactype_map[taco.type] << ")" << "\tlhs : " << setw(5) << taco.lhs << setw(8) << "\trhs : " << setw(5) << taco.rhs << setw(8) << "\tbytes: " << setw(5) << taco.bytes << endl; } bool does_trump_exists(string key, map<string, Trump>& regMap) { for (const auto &v : regMap) { if (v.first == key) return true; } return false; } void generateMIPS(vector<TACObject>& TACContainer, const bool& debug = false) { map<string, pair<string, string>> regMap; vector<string> rhs_tokens; //bool is_main = false; string stack_size = ""; int pushparam_taken = 0; int registerNum = 0; linearScan(regMap, TACContainer); /** DEBUG **/ Color::Modifier c_red(Color::Code::FG_RED); Color::Modifier c_green(Color::Code::FG_GREEN); Color::Modifier c_blue(Color::Code::FG_BLUE); Color::Modifier c_def(Color::Code::FG_DEFAULT); if (debug) { cout << c_blue << "(regMap content): " << endl; for (const auto& trump : regMap) cout << "---(dbg) " << setw(7) << trump.first << ":" << setw(7) << trump.second.first << endl; cout << c_def << endl; } /** END DEBUG **/ cout << " jal main" << endl; for (auto &taco : TACContainer) { /** DEBUG **/ if (debug) { cout << c_blue ; printTAC(taco); cout << c_def ; } /** END DEBUG **/ switch(taco.type) { case label: cout << taco.lhs + ":" << endl; if (taco.lhs[0] != 'L') Node::current_context = taco.lhs; break; case stmt: split(taco.rhs, " ", rhs_tokens); // Case 1) Variable is assigned a register. // Examples: a := t1, b := t4, c := t0 if (rhs_tokens.size() == 1 && rhs_tokens[0][0] == 't') { regMap[taco.lhs].first = taco.rhs; } // Case 2) Variable is assigned a constant. // Examples: a := 2, b := 4, c := 8 else if (rhs_tokens.size() == 1) { // varConstToMIPS(regMap[taco.lhs], taco.rhs); cout << " li $" + regMap[taco.lhs].first + ", " + taco.rhs << endl; } // Case 3) Variable is assigned to a binary expression. // Examples: a := t3 + t1, b := t6 + t0 else { string a = rhs_tokens[0]; string b = rhs_tokens[2]; if (does_trump_exists(rhs_tokens[0], regMap)) a = regMap[rhs_tokens[0]].first; if (does_trump_exists(rhs_tokens[2], regMap)) b = regMap[rhs_tokens[2]].first; auto code = binaryExprToMIPS(regMap[taco.lhs].first, a, b, rhs_tokens[1]); cout << code << endl; } break; // case instr: cout << "(DEBUG) sc_code : " << taco.sc_code << endl; case instr: if (taco.lhs == "BeginFunc") { cout << " addi $sp, $sp, -" + taco.rhs << endl; stack_size = taco.rhs; } else if (taco.lhs == "Return") { cout << " move $v0, $" + regMap[taco.rhs].first << endl; registerNum = 0; } else if (taco.lhs == "LoadParam") { cout << " lw $t" + to_string(registerNum) << ", " << to_string(registerNum * 4) << "($sp)" << endl; regMap[taco.rhs] = make_pair("t" + to_string(registerNum++), ""); } else if (taco.lhs == "PushParam") { cout << " addi $sp, $sp, -4" << endl; cout << " sw $" + regMap[taco.rhs].first + ", 0($sp)" << endl; pushparam_taken++; } else if (taco.lhs == "EndFunc") { cout << " addi $sp, $sp, " + stack_size << endl; if (Node::current_context != "main") cout << " jr $ra" << endl; } else if (taco.lhs == "SaveRegisters") { int count = 0; cout << " # save registers..." << endl; for (const auto &r : regMap) { Trump trump = r.second; if (trump.second == "main") { cout << " sw $" + trump.first + ", " + to_string(count * 4) + "($sp)" << endl; count++; } } } else if (taco.lhs == "RestoreRegisters") { cout << " addi $sp, $sp, " + to_string(4 * pushparam_taken) << endl; cout << " # restore registers..." << endl; int count = 0; for (const auto &r : regMap) { Trump trump = r.second; if (trump.second == "main") { cout << " sw $" + trump.first + ", " + to_string(count * 4) + "($sp)" << endl; count++; } } } break; break; case call: switch (taco.sc_code) { case sc_ReadInt: cout << " li $v0, 5" << endl << " syscall" << endl << " move $" << taco.lhs << ", $v0" << endl; break; case sc_None: split(taco.rhs, " ", rhs_tokens); cout << " jal " + rhs_tokens[0] << endl; cout << " move $" + taco.lhs + ", $v0" << endl; break; default: cout << "ERROR" << endl; break; } break; case print: cout << " li $v0, 1\n" << " move $a0, $" + regMap[taco.rhs].first << "\n" << " syscall" << endl; break; case branch: cout << " bne $" + taco.lhs + ", $zero, " + taco.rhs << endl; break; case jump: cout << " j " + taco.lhs << endl; break; default: cout << "(TACO Type Error) type: " << taco.type << endl; } } // End of Program cout << " # End Program" << endl; cout << " li $v0, 10" << endl; cout << " syscall" << endl; // for (const auto &asd : regMap) // cout << asd.first << " is mapped to " << asd.second.first << " in " << asd.second.second << endl; } string Program::Emit() { if ( decls->NumElements() > 0 ) for ( int i = 0; i < decls->NumElements(); ++i ) decls->Nth(i)->Emit(); constantFolding(TACContainer); //constantPropagation(TACContainer); //deadCodeElimination(TACContainer); //generateIR(TACContainer); generateMIPS(TACContainer); return "Program::Emit()"; } string StmtBlock::Emit() { for(int i = 0; i < stmts->NumElements(); i++){ Stmt* ith_statement = stmts->Nth(i); ith_statement->Emit(); } return "StmtBlock::Emit()"; } string ForStmt::Emit() { string inc_var = init->Emit(); string label0 = "L" + to_string(labelCounter++); string label1 = "L" + to_string(labelCounter++); string label2 = "L" + to_string(labelCounter++); TACContainer.emplace_back(label0, "", 0, label); TACContainer.emplace_back(test->Emit(), label1, 0, branch); TACContainer.emplace_back(label2, "", 0, jump); TACContainer.emplace_back(label1, "", 0, label); body->Emit(); step->Emit(); TACContainer.emplace_back(label0, "", 0, jump); TACContainer.emplace_back(label2, "", 0, label); return "ForStmt::Emit()"; } string WhileStmt::Emit() { string label0 = "L" + to_string(labelCounter++); string label1 = "L" + to_string(labelCounter++); string label2 = "L" + to_string(labelCounter++); TACContainer.emplace_back(label0, "", 0, label); TACContainer.emplace_back(test->Emit(), label1, 0, branch); TACContainer.emplace_back(label2, "", 0, jump); TACContainer.emplace_back(label1, "", 0, label); body->Emit(); TACContainer.emplace_back(label0, "", 0, jump); TACContainer.emplace_back(label2, "", 0, label); return "WhileStmt::Emit()"; } string IfStmt::Emit() { string ifLabel = "L" + to_string(labelCounter++); string elseLabel = "L" + to_string(labelCounter++); TACContainer.emplace_back(test->Emit(), ifLabel, 0, branch); TACContainer.emplace_back(elseLabel, "", 0, jump); TACContainer.emplace_back(ifLabel, "", 0, label); body->Emit(); string exitLabel = (elseBody) ? "L" + to_string(labelCounter++) : elseLabel; TACContainer.emplace_back(exitLabel, "", 0, jump); if (elseBody) { TACContainer.emplace_back(elseLabel, "", 0, label); elseBody->Emit(); TACContainer.emplace_back(exitLabel, "", 0, jump); } TACContainer.emplace_back(exitLabel, "", 0, label); return "ifStmt"; } string ReturnStmt::Emit() { string rhs = expr->Emit(); TACContainer.emplace_back("Return", rhs, 0, instr); return "ReturnStmt Emit()"; } string DeclStmt::Emit() { varDecl->Emit(); return "DeclStmt Emit()"; }
32.575444
120
0.504973
atomic
62a2e795ddb66c0343a47c676e22752e1dc94c42
26,591
cxx
C++
PWGCF/EBYE/BalanceFunctions/AliAnalysisTaskEventMixingBF.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
114
2017-03-03T09:12:23.000Z
2022-03-03T20:29:42.000Z
PWGCF/EBYE/BalanceFunctions/AliAnalysisTaskEventMixingBF.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
19,637
2017-01-16T12:34:41.000Z
2022-03-31T22:02:40.000Z
PWGCF/EBYE/BalanceFunctions/AliAnalysisTaskEventMixingBF.cxx
maroozm/AliPhysics
22ec256928cfdf8f800e05bfc1a6e124d90b6eaf
[ "BSD-3-Clause" ]
1,021
2016-07-14T22:41:16.000Z
2022-03-31T05:15:51.000Z
#include "TChain.h" #include "TList.h" #include "TCanvas.h" #include "TLorentzVector.h" #include "TGraphErrors.h" #include "TH1F.h" #include "TH2F.h" #include "TArrayF.h" #include "TF1.h" #include "TRandom.h" #include "AliAnalysisTaskSE.h" #include "AliAnalysisManager.h" #include "AliESDVertex.h" #include "AliESDEvent.h" #include "AliESDInputHandler.h" #include "AliAODEvent.h" #include "AliAODTrack.h" #include "AliAODInputHandler.h" #include "AliGenEventHeader.h" #include "AliGenHijingEventHeader.h" #include "AliMCEventHandler.h" #include "AliMCEvent.h" #include "AliMixInputEventHandler.h" #include "AliStack.h" #include "AliESDtrackCuts.h" #include "TH2D.h" #include "AliPID.h" #include "AliPIDResponse.h" #include "AliPIDCombined.h" #include "AliAnalysisTaskEventMixingBF.h" #include "AliBalanceEventMixing.h" // Analysis task for the EventMixingBF code // Authors: Panos.Christakoglou@nikhef.nl, m.weber@cern.ch ClassImp(AliAnalysisTaskEventMixingBF) //________________________________________________________________________ AliAnalysisTaskEventMixingBF::AliAnalysisTaskEventMixingBF(const char *name) : AliAnalysisTaskSE(name), fBalance(0), fRunShuffling(kFALSE), fShuffledBalance(0), fList(0), fListEventMixingBF(0), fListEventMixingBFS(0), fHistListPIDQA(0), fHistEventStats(0), fHistCentStats(0), fHistTriggerStats(0), fHistTrackStats(0), fHistVx(0), fHistVy(0), fHistVz(0), fHistClus(0), fHistDCA(0), fHistChi2(0), fHistPt(0), fHistEta(0), fHistPhi(0), fHistPhiBefore(0), fHistPhiAfter(0), fHistV0M(0), fHistRefTracks(0), fHistdEdxVsPTPCbeforePID(NULL), fHistBetavsPTOFbeforePID(NULL), fHistProbTPCvsPtbeforePID(NULL), fHistProbTOFvsPtbeforePID(NULL), fHistProbTPCTOFvsPtbeforePID(NULL), fHistNSigmaTPCvsPtbeforePID(NULL), fHistNSigmaTOFvsPtbeforePID(NULL), fHistdEdxVsPTPCafterPID(NULL), fHistBetavsPTOFafterPID(NULL), fHistProbTPCvsPtafterPID(NULL), fHistProbTOFvsPtafterPID(NULL), fHistProbTPCTOFvsPtafterPID(NULL), fHistNSigmaTPCvsPtafterPID(NULL), fHistNSigmaTOFvsPtafterPID(NULL), fPIDResponse(0x0), fPIDCombined(0x0), fParticleOfInterest(kPion), fPidDetectorConfig(kTPCTOF), fUsePID(kFALSE), fUsePIDnSigma(kTRUE), fUsePIDPropabilities(kFALSE), fPIDNSigma(3.), fMinAcceptedPIDProbability(0.8), fESDtrackCuts(0), fCentralityEstimator("V0M"), fUseCentrality(kFALSE), fCentralityPercentileMin(0.), fCentralityPercentileMax(5.), fImpactParameterMin(0.), fImpactParameterMax(20.), fUseMultiplicity(kFALSE), fNumberOfAcceptedTracksMin(0), fNumberOfAcceptedTracksMax(10000), fHistNumberOfAcceptedTracks(0), fUseOfflineTrigger(kFALSE), fVxMax(0.3), fVyMax(0.3), fVzMax(10.), nAODtrackCutBit(128), fPtMin(0.3), fPtMax(1.5), fEtaMin(-0.8), fEtaMax(-0.8), fDCAxyCut(-1), fDCAzCut(-1), fTPCchi2Cut(-1), fNClustersTPCCut(-1), fAcceptanceParameterization(0), fDifferentialV2(0), fUseFlowAfterBurner(kFALSE), fExcludeResonancesInMC(kFALSE), fUseMCPdgCode(kFALSE), fPDGCodeToBeAnalyzed(-1), fMainEvent(0x0), fMixEvent(0x0) { // Constructor // Define input and output slots here // Input slot #0 works with a TChain DefineInput(0, TChain::Class()); // Output slot #0 writes into a TH1 container DefineOutput(1, TList::Class()); DefineOutput(2, TList::Class()); DefineOutput(3, TList::Class()); DefineOutput(4, TList::Class()); } //________________________________________________________________________ AliAnalysisTaskEventMixingBF::~AliAnalysisTaskEventMixingBF() { // delete fBalance; // delete fShuffledBalance; // delete fList; // delete fListEventMixingBF; // delete fListEventMixingBFS; // delete fHistEventStats; // delete fHistTrackStats; // delete fHistVx; // delete fHistVy; // delete fHistVz; // delete fHistClus; // delete fHistDCA; // delete fHistChi2; // delete fHistPt; // delete fHistEta; // delete fHistPhi; // delete fHistV0M; } //________________________________________________________________________ void AliAnalysisTaskEventMixingBF::UserCreateOutputObjects() { // Create histograms // Called once if(!fBalance) { fBalance = new AliBalanceEventMixing(); fBalance->SetAnalysisLevel("ESD"); //fBalance->SetNumberOfBins(-1,16); fBalance->SetInterval(-1,-0.8,0.8,16,0.,1.6); } if(fRunShuffling) { if(!fShuffledBalance) { fShuffledBalance = new AliBalanceEventMixing(); fShuffledBalance->SetAnalysisLevel("ESD"); //fShuffledBalance->SetNumberOfBins(-1,16); fShuffledBalance->SetInterval(-1,-0.8,0.8,16,0.,1.6); } } //QA list fList = new TList(); fList->SetName("listQA"); fList->SetOwner(); //Balance Function list fListEventMixingBF = new TList(); fListEventMixingBF->SetName("listEventMixingBF"); fListEventMixingBF->SetOwner(); if(fRunShuffling) { fListEventMixingBFS = new TList(); fListEventMixingBFS->SetName("listEventMixingBFShuffled"); fListEventMixingBFS->SetOwner(); } //PID QA list if(fUsePID) { fHistListPIDQA = new TList(); fHistListPIDQA->SetName("listQAPID"); fHistListPIDQA->SetOwner(); } //Event stats. TString gCutName[4] = {"Total","Offline trigger", "Vertex","Analyzed"}; fHistEventStats = new TH1F("fHistEventStats", "Event statistics;;N_{events}", 4,0.5,4.5); for(Int_t i = 1; i <= 4; i++) fHistEventStats->GetXaxis()->SetBinLabel(i,gCutName[i-1].Data()); fList->Add(fHistEventStats); TString gCentName[9] = {"V0M","FMD","TRK","TKL","CL0","CL1","V0MvsFMD","TKLvsV0M","ZEMvsZDC"}; fHistCentStats = new TH2F("fHistCentStats", "Centrality statistics;;Cent percentile", 9,-0.5,8.5,220,-5,105); for(Int_t i = 1; i <= 9; i++) fHistCentStats->GetXaxis()->SetBinLabel(i,gCentName[i-1].Data()); fList->Add(fHistCentStats); fHistTriggerStats = new TH1F("fHistTriggerStats","Trigger statistics;TriggerBit;N_{events}",130,0,130); fList->Add(fHistTriggerStats); fHistTrackStats = new TH1F("fHistTrackStats","Event statistics;TrackFilterBit;N_{events}",130,0,130); fList->Add(fHistTrackStats); fHistNumberOfAcceptedTracks = new TH1F("fHistNumberOfAcceptedTracks",";N_{acc.};Entries",4001,-0.5,4000.5); fList->Add(fHistNumberOfAcceptedTracks); // Vertex distributions fHistVx = new TH1F("fHistVx","Primary vertex distribution - x coordinate;V_{x} (cm);Entries",100,-0.5,0.5); fList->Add(fHistVx); fHistVy = new TH1F("fHistVy","Primary vertex distribution - y coordinate;V_{y} (cm);Entries",100,-0.5,0.5); fList->Add(fHistVy); fHistVz = new TH1F("fHistVz","Primary vertex distribution - z coordinate;V_{z} (cm);Entries",100,-20.,20.); fList->Add(fHistVz); // QA histograms fHistClus = new TH2F("fHistClus","# Cluster (TPC vs. ITS)",10,0,10,200,0,200); fList->Add(fHistClus); fHistChi2 = new TH1F("fHistChi2","Chi2/NDF distribution",200,0,10); fList->Add(fHistChi2); fHistDCA = new TH2F("fHistDCA","DCA (xy vs. z)",400,-5,5,400,-5,5); fList->Add(fHistDCA); fHistPt = new TH1F("fHistPt","p_{T} distribution",200,0,10); fList->Add(fHistPt); fHistEta = new TH1F("fHistEta","#eta distribution",200,-2,2); fList->Add(fHistEta); fHistPhi = new TH1F("fHistPhi","#phi distribution",200,-20,380); fList->Add(fHistPhi); fHistPhiBefore = new TH1F("fHistPhiBefore","#phi distribution",200,0.,2*TMath::Pi()); fList->Add(fHistPhiBefore); fHistPhiAfter = new TH1F("fHistPhiAfter","#phi distribution",200,0.,2*TMath::Pi()); fList->Add(fHistPhiAfter); fHistV0M = new TH2F("fHistV0M","V0 Multiplicity C vs. A",500, 0, 20000, 500, 0, 20000); fList->Add(fHistV0M); TString gRefTrackName[6] = {"tracks","tracksPos","tracksNeg","tracksTPConly","clusITS0","clusITS1"}; fHistRefTracks = new TH2F("fHistRefTracks","Nr of Ref tracks/event vs. ref track estimator;;Nr of tracks",6, 0, 6, 400, 0, 20000); for(Int_t i = 1; i <= 6; i++) fHistRefTracks->GetXaxis()->SetBinLabel(i,gRefTrackName[i-1].Data()); fList->Add(fHistRefTracks); // Balance function histograms // Initialize histograms if not done yet if(!fBalance->GetHistNp(0)){ AliWarning("Histograms not yet initialized! --> Will be done now"); AliWarning("--> Add 'gBalance->InitHistograms()' in your configBalanceFunction"); fBalance->InitHistograms(); } if(fRunShuffling) { if(!fShuffledBalance->GetHistNp(0)) { AliWarning("Histograms (shuffling) not yet initialized! --> Will be done now"); AliWarning("--> Add 'gBalance->InitHistograms()' in your configBalanceFunction"); fShuffledBalance->InitHistograms(); } } for(Int_t a = 0; a < ANALYSIS_TYPES; a++){ fListEventMixingBF->Add(fBalance->GetHistNp(a)); fListEventMixingBF->Add(fBalance->GetHistNn(a)); fListEventMixingBF->Add(fBalance->GetHistNpn(a)); fListEventMixingBF->Add(fBalance->GetHistNnn(a)); fListEventMixingBF->Add(fBalance->GetHistNpp(a)); fListEventMixingBF->Add(fBalance->GetHistNnp(a)); if(fRunShuffling) { fListEventMixingBFS->Add(fShuffledBalance->GetHistNp(a)); fListEventMixingBFS->Add(fShuffledBalance->GetHistNn(a)); fListEventMixingBFS->Add(fShuffledBalance->GetHistNpn(a)); fListEventMixingBFS->Add(fShuffledBalance->GetHistNnn(a)); fListEventMixingBFS->Add(fShuffledBalance->GetHistNpp(a)); fListEventMixingBFS->Add(fShuffledBalance->GetHistNnp(a)); } } if(fESDtrackCuts) fList->Add(fESDtrackCuts); //====================PID========================// if(fUsePID) { fPIDCombined = new AliPIDCombined(); fPIDCombined->SetDefaultTPCPriors(); fHistdEdxVsPTPCbeforePID = new TH2D ("dEdxVsPTPCbefore","dEdxVsPTPCbefore", 1000, -10.0, 10.0, 1000, 0, 1000); fHistListPIDQA->Add(fHistdEdxVsPTPCbeforePID); //addition fHistBetavsPTOFbeforePID = new TH2D ("BetavsPTOFbefore","BetavsPTOFbefore", 1000, -10.0, 10., 1000, 0, 1.2); fHistListPIDQA->Add(fHistBetavsPTOFbeforePID); //addition fHistProbTPCvsPtbeforePID = new TH2D ("ProbTPCvsPtbefore","ProbTPCvsPtbefore", 1000, -10.0,10.0, 1000, 0, 2.0); fHistListPIDQA->Add(fHistProbTPCvsPtbeforePID); //addition fHistProbTOFvsPtbeforePID = new TH2D ("ProbTOFvsPtbefore","ProbTOFvsPtbefore", 1000, -50, 50, 1000, 0, 2.0); fHistListPIDQA->Add(fHistProbTOFvsPtbeforePID); //addition fHistProbTPCTOFvsPtbeforePID =new TH2D ("ProbTPCTOFvsPtbefore","ProbTPCTOFvsPtbefore", 1000, -50, 50, 1000, 0, 2.0); fHistListPIDQA->Add(fHistProbTPCTOFvsPtbeforePID); //addition fHistNSigmaTPCvsPtbeforePID = new TH2D ("NSigmaTPCvsPtbefore","NSigmaTPCvsPtbefore", 1000, -10, 10, 1000, 0, 500); fHistListPIDQA->Add(fHistNSigmaTPCvsPtbeforePID); //addition fHistNSigmaTOFvsPtbeforePID = new TH2D ("NSigmaTOFvsPtbefore","NSigmaTOFvsPtbefore", 1000, -10, 10, 1000, 0, 500); fHistListPIDQA->Add(fHistNSigmaTOFvsPtbeforePID); //addition fHistdEdxVsPTPCafterPID = new TH2D ("dEdxVsPTPCafter","dEdxVsPTPCafter", 1000, -10, 10, 1000, 0, 1000); fHistListPIDQA->Add(fHistdEdxVsPTPCafterPID); //addition fHistBetavsPTOFafterPID = new TH2D ("BetavsPTOFafter","BetavsPTOFafter", 1000, -10, 10, 1000, 0, 1.2); fHistListPIDQA->Add(fHistBetavsPTOFafterPID); //addition fHistProbTPCvsPtafterPID = new TH2D ("ProbTPCvsPtafter","ProbTPCvsPtafter", 1000, -10, 10, 1000, 0, 2); fHistListPIDQA->Add(fHistProbTPCvsPtafterPID); //addition fHistProbTOFvsPtafterPID = new TH2D ("ProbTOFvsPtafter","ProbTOFvsPtafter", 1000, -10, 10, 1000, 0, 2); fHistListPIDQA->Add(fHistProbTOFvsPtafterPID); //addition fHistProbTPCTOFvsPtafterPID =new TH2D ("ProbTPCTOFvsPtafter","ProbTPCTOFvsPtafter", 1000, -50, 50, 1000, 0, 2.0); fHistListPIDQA->Add(fHistProbTPCTOFvsPtafterPID); //addition fHistNSigmaTPCvsPtafterPID = new TH2D ("NSigmaTPCvsPtafter","NSigmaTPCvsPtafter", 1000, -10, 10, 1000, 0, 500); fHistListPIDQA->Add(fHistNSigmaTPCvsPtafterPID); //addition fHistNSigmaTOFvsPtafterPID = new TH2D ("NSigmaTOFvsPtafter","NSigmaTOFvsPtafter", 1000, -10, 10, 1000, 0, 500); fHistListPIDQA->Add(fHistNSigmaTOFvsPtafterPID); //addition } //====================PID========================// // Post output data. PostData(1, fList); PostData(2, fListEventMixingBF); if(fRunShuffling) PostData(3, fListEventMixingBFS); if(fUsePID) PostData(4, fHistListPIDQA); //PID } //________________________________________________________________________ void AliAnalysisTaskEventMixingBF::UserExec(Option_t *) { // Main loop // Called for each event // NOTHING TO DO for event mixing! } //________________________________________________________________________ void AliAnalysisTaskEventMixingBF::FinishTaskOutput(){ //Printf("END EventMixingBF"); if (!fBalance) { AliError("ERROR: fBalance not available"); return; } if(fRunShuffling) { if (!fShuffledBalance) { AliError("ERROR: fShuffledBalance not available"); return; } } } //________________________________________________________________________ void AliAnalysisTaskEventMixingBF::Terminate(Option_t *) { // Draw result to the screen // Called once at the end of the query // not implemented ... } void AliAnalysisTaskEventMixingBF::UserExecMix(Option_t *) { // Main loop for event mixing TString gAnalysisLevel = fBalance->GetAnalysisLevel(); AliMixInputEventHandler *mixIEH = SetupEventsForMixing(); Float_t fCentrality = 0.; // for HBT like cuts need magnetic field sign Float_t bSign = 0; // only used in AOD so far // vector holding the charges/kinematics of all tracks (charge,y,eta,phi,p0,p1,p2,pt,E) vector<Double_t> *chargeVector[9]; // original charge for(Int_t i = 0; i < 9; i++){ chargeVector[i] = new vector<Double_t>; } Double_t vCharge; Double_t vY; Double_t vEta; Double_t vPhi; Double_t vP[3]; Double_t vPt; Double_t vE; Int_t iMainTrackUsed = -1; // ------------------------------------------------------------- // At the moment MIXING only for AODs if(mixIEH){ //AOD analysis (vertex and track cuts also here!!!!) if(gAnalysisLevel == "AOD") { AliAODEvent* aodEventMain = dynamic_cast<AliAODEvent*>(fMainEvent); if(!aodEventMain) { AliError("ERROR: aodEventMain not available"); return; } AliAODEvent *aodEventMix = dynamic_cast<AliAODEvent *>(fMixEvent); if(!aodEventMix) { AliError("ERROR: aodEventMix not available"); return; } // for HBT like cuts need magnetic field sign bSign = (aodEventMain->GetMagneticField() > 0) ? 1 : -1; AliAODHeader *aodHeaderMain = dynamic_cast<AliAODHeader*>(aodEventMain->GetHeader()); if(!aodHeaderMain) AliFatal("Not a standard AOD"); // event selection done in AliAnalysisTaskSE::Exec() --> this is not used fHistEventStats->Fill(1); //all events // this is not needed (checked in mixing handler!) Bool_t isSelectedMain = kTRUE; Bool_t isSelectedMix = kTRUE; if(fUseOfflineTrigger){ isSelectedMain = ((AliInputEventHandler*)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->IsEventSelected(); isSelectedMix = ((AliInputEventHandler*)((AliMultiInputEventHandler *)(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()))->GetFirstMultiInputHandler())->IsEventSelected(); } if(isSelectedMain && isSelectedMix) { fHistEventStats->Fill(2); //triggered events //Centrality stuff (centrality in AOD header) if(fUseCentrality) { fCentrality = aodHeaderMain->GetCentralityP()->GetCentralityPercentile(fCentralityEstimator.Data()); // QA for centrality estimators fHistCentStats->Fill(0.,aodHeaderMain->GetCentralityP()->GetCentralityPercentile("V0M")); fHistCentStats->Fill(1.,aodHeaderMain->GetCentralityP()->GetCentralityPercentile("FMD")); fHistCentStats->Fill(2.,aodHeaderMain->GetCentralityP()->GetCentralityPercentile("TRK")); fHistCentStats->Fill(3.,aodHeaderMain->GetCentralityP()->GetCentralityPercentile("TKL")); fHistCentStats->Fill(4.,aodHeaderMain->GetCentralityP()->GetCentralityPercentile("CL0")); fHistCentStats->Fill(5.,aodHeaderMain->GetCentralityP()->GetCentralityPercentile("CL1")); fHistCentStats->Fill(6.,aodHeaderMain->GetCentralityP()->GetCentralityPercentile("V0MvsFMD")); fHistCentStats->Fill(7.,aodHeaderMain->GetCentralityP()->GetCentralityPercentile("TKLvsV0M")); fHistCentStats->Fill(8.,aodHeaderMain->GetCentralityP()->GetCentralityPercentile("ZEMvsZDC")); // take only events inside centrality class if((fCentrality < fCentralityPercentileMin) || (fCentrality > fCentralityPercentileMax)) return; // centrality QA (V0M) fHistV0M->Fill(aodEventMain->GetVZEROData()->GetMTotV0A(), aodEventMain->GetVZEROData()->GetMTotV0C()); // centrality QA (reference tracks) fHistRefTracks->Fill(0.,aodHeaderMain->GetRefMultiplicity()); fHistRefTracks->Fill(1.,aodHeaderMain->GetRefMultiplicityPos()); fHistRefTracks->Fill(2.,aodHeaderMain->GetRefMultiplicityNeg()); fHistRefTracks->Fill(3.,aodHeaderMain->GetTPConlyRefMultiplicity()); fHistRefTracks->Fill(4.,aodHeaderMain->GetNumberOfITSClusters(0)); fHistRefTracks->Fill(5.,aodHeaderMain->GetNumberOfITSClusters(1)); fHistRefTracks->Fill(6.,aodHeaderMain->GetNumberOfITSClusters(2)); fHistRefTracks->Fill(7.,aodHeaderMain->GetNumberOfITSClusters(3)); fHistRefTracks->Fill(8.,aodHeaderMain->GetNumberOfITSClusters(4)); } // // this is crashing (Bug in ROOT (to be solved)) but not needed (checked in mixing handler) // const AliAODVertex *vertexMain = aodEventMain->GetPrimaryVertex(); // const AliAODVertex *vertexMix = aodEventMix->GetPrimaryVertex(); // if(vertexMain && vertexMix) { // Double32_t fCovMain[6]; // Double32_t fCovMix[6]; // vertexMain->GetCovarianceMatrix(fCovMain); // vertexMix->GetCovarianceMatrix(fCovMix); // if(vertexMain->GetNContributors() > 0 && vertexMix->GetNContributors() > 0) { // if(fCovMain[5] != 0 && fCovMix[5] != 0) { // fHistEventStats->Fill(3); //events with a proper vertex // if(TMath::Abs(vertexMain->GetX()) < fVxMax && TMath::Abs(vertexMix->GetX()) < fVxMax ) { // if(TMath::Abs(vertexMain->GetY()) < fVyMax && TMath::Abs(vertexMix->GetY()) < fVyMax) { // if(TMath::Abs(vertexMain->GetZ()) < fVzMax && TMath::Abs(vertexMix->GetZ()) < fVzMax) { // fHistEventStats->Fill(4); //analyzed events // fHistVx->Fill(vertexMain->GetX()); // fHistVy->Fill(vertexMain->GetY()); // fHistVz->Fill(vertexMain->GetZ()); // Loop over tracks in main event for (Int_t iTracksMain = 0; iTracksMain < aodEventMain->GetNumberOfTracks(); iTracksMain++) { AliAODTrack* aodTrackMain = dynamic_cast<AliAODTrack *>(aodEventMain->GetTrack(iTracksMain)); if (!aodTrackMain) { AliError(Form("ERROR: Could not receive track %d", iTracksMain)); continue; } // AOD track cuts // For ESD Filter Information: ANALYSIS/macros/AddTaskESDfilter.C // take only TPC only tracks fHistTrackStats->Fill(aodTrackMain->GetFilterMap()); if(!aodTrackMain->TestFilterBit(nAODtrackCutBit)) continue; vCharge = aodTrackMain->Charge(); vY = aodTrackMain->Y(); vEta = aodTrackMain->Eta(); vPhi = aodTrackMain->Phi() * TMath::RadToDeg(); vE = aodTrackMain->E(); vPt = aodTrackMain->Pt(); aodTrackMain->PxPyPz(vP); Float_t dcaXYMain = aodTrackMain->DCA(); // this is the DCA from global track (not exactly what is cut on) Float_t dcaZMain = aodTrackMain->ZAtDCA(); // this is the DCA from global track (not exactly what is cut on) // Kinematics cuts from ESD track cuts if( vPt < fPtMin || vPt > fPtMax) continue; if( vEta < fEtaMin || vEta > fEtaMax) continue; // Extra DCA cuts (for systematic studies [!= -1]) if( fDCAxyCut != -1 && fDCAzCut != -1){ if(TMath::Sqrt((dcaXYMain*dcaXYMain)/(fDCAxyCut*fDCAxyCut)+(dcaZMain*dcaZMain)/(fDCAzCut*fDCAzCut)) > 1 ){ continue; // 2D cut } } // Extra TPC cuts (for systematic studies [!= -1]) if( fTPCchi2Cut != -1 && aodTrackMain->Chi2perNDF() > fTPCchi2Cut){ continue; } if( fNClustersTPCCut != -1 && aodTrackMain->GetTPCNcls() < fNClustersTPCCut){ continue; } // fill QA histograms fHistClus->Fill(aodTrackMain->GetITSNcls(),aodTrackMain->GetTPCNcls()); fHistDCA->Fill(dcaZMain,dcaXYMain); fHistChi2->Fill(aodTrackMain->Chi2perNDF()); fHistPt->Fill(vPt); fHistEta->Fill(vEta); fHistPhi->Fill(vPhi); // fill charge vector chargeVector[0]->push_back(vCharge); chargeVector[1]->push_back(vY); chargeVector[2]->push_back(vEta); chargeVector[3]->push_back(vPhi); chargeVector[4]->push_back(vP[0]); chargeVector[5]->push_back(vP[1]); chargeVector[6]->push_back(vP[2]); chargeVector[7]->push_back(vPt); chargeVector[8]->push_back(vE); // ------------------------------------------------------------- // for each track in main event loop over all tracks in mix event for (Int_t iTracksMix = 0; iTracksMix < aodEventMix->GetNumberOfTracks(); iTracksMix++) { AliAODTrack* aodTrackMix = dynamic_cast<AliAODTrack *>(aodEventMix->GetTrack(iTracksMix)); if (!aodTrackMix) { AliError(Form("ERROR: Could not receive track %d", iTracksMix)); continue; } // AOD track cuts // For ESD Filter Information: ANALYSIS/macros/AddTaskESDfilter.C // take only TPC only tracks fHistTrackStats->Fill(aodTrackMix->GetFilterMap()); if(!aodTrackMix->TestFilterBit(nAODtrackCutBit)) continue; vCharge = aodTrackMix->Charge(); vY = aodTrackMix->Y(); vEta = aodTrackMix->Eta(); vPhi = aodTrackMix->Phi() * TMath::RadToDeg(); vE = aodTrackMix->E(); vPt = aodTrackMix->Pt(); aodTrackMix->PxPyPz(vP); Float_t dcaXYMix = aodTrackMix->DCA(); // this is the DCA from global track (not exactly what is cut on) Float_t dcaZMix = aodTrackMix->ZAtDCA(); // this is the DCA from global track (not exactly what is cut on) // Kinematics cuts from ESD track cuts if( vPt < fPtMin || vPt > fPtMax) continue; if( vEta < fEtaMin || vEta > fEtaMax) continue; // Extra DCA cuts (for systematic studies [!= -1]) if( fDCAxyCut != -1 && fDCAxyCut != -1){ if(TMath::Sqrt((dcaXYMix*dcaXYMix)/(fDCAxyCut*fDCAxyCut)+(dcaZMix*dcaZMix)/(fDCAzCut*fDCAzCut)) > 1 ){ continue; // 2D cut } } // Extra TPC cuts (for systematic studies [!= -1]) if( fTPCchi2Cut != -1 && aodTrackMix->Chi2perNDF() > fTPCchi2Cut){ continue; } if( fNClustersTPCCut != -1 && aodTrackMix->GetTPCNcls() < fNClustersTPCCut){ continue; } // fill QA histograms fHistClus->Fill(aodTrackMix->GetITSNcls(),aodTrackMix->GetTPCNcls()); fHistDCA->Fill(dcaZMix,dcaXYMix); fHistChi2->Fill(aodTrackMix->Chi2perNDF()); fHistPt->Fill(vPt); fHistEta->Fill(vEta); fHistPhi->Fill(vPhi); // fill charge vector chargeVector[0]->push_back(vCharge); chargeVector[1]->push_back(vY); chargeVector[2]->push_back(vEta); chargeVector[3]->push_back(vPhi); chargeVector[4]->push_back(vP[0]); chargeVector[5]->push_back(vP[1]); chargeVector[6]->push_back(vP[2]); chargeVector[7]->push_back(vPt); chargeVector[8]->push_back(vE); } //mix track loop // calculate balance function for each track in main event iMainTrackUsed++; // is needed to do no double counting in Balance Function calculation if(iMainTrackUsed >= (Int_t)chargeVector[0]->size()) break; //do not allow more tracks than in mixed event! fBalance->CalculateBalance(fCentrality,chargeVector,iMainTrackUsed,bSign); // clean charge vector afterwards for(Int_t i = 0; i < 9; i++){ chargeVector[i]->clear(); } } //main track loop // }//Vz cut // }//Vy cut // }//Vx cut // }//proper vertexresolution // }//proper number of contributors // }//vertex object valid }//triggered event }//AOD analysis } } AliMixInputEventHandler *AliAnalysisTaskEventMixingBF::SetupEventsForMixing() { //sets the input handlers for event mixing AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); AliMultiInputEventHandler *inEvHMain = dynamic_cast<AliMultiInputEventHandler *>(mgr->GetInputEventHandler()); if (inEvHMain) { AliMixInputEventHandler *mixEH = dynamic_cast<AliMixInputEventHandler *>(inEvHMain->GetFirstMultiInputHandler()); if (!mixEH) return nullptr; if (mixEH->CurrentBinIndex() < 0) { AliDebug(AliLog::kDebug + 1, "Current event mixEH->CurrentEntry() == -1"); return nullptr; } AliDebug(AliLog::kDebug, Form("Mixing %lld %d [%lld,%lld] %d", mixEH->CurrentEntry(), mixEH->CurrentBinIndex(), mixEH->CurrentEntryMain(), mixEH->CurrentEntryMix(), mixEH->NumberMixed())); AliInputEventHandler *ihMainCurrent = inEvHMain->GetFirstInputEventHandler(); fMainEvent = ihMainCurrent->GetEvent(); AliMultiInputEventHandler *inEvHMixedCurrent = mixEH->GetFirstMultiInputHandler(); // for buffer = 1 AliInputEventHandler *ihMixedCurrent = inEvHMixedCurrent->GetFirstInputEventHandler(); fMixEvent = ihMixedCurrent->GetEvent(); return mixEH; } return NULL; }
38.315562
194
0.664059
maroozm
62a6695ad70f068176da027d6b83b47de6814540
11,501
cpp
C++
src/goto-symex/memory_model_sc.cpp
dan-blank/yogar-cbmc
05b4f056b585b65828acf39546c866379dca6549
[ "MIT" ]
1
2017-07-25T02:44:56.000Z
2017-07-25T02:44:56.000Z
src/goto-symex/memory_model_sc.cpp
dan-blank/yogar-cbmc
05b4f056b585b65828acf39546c866379dca6549
[ "MIT" ]
1
2017-02-22T14:35:19.000Z
2017-02-27T08:49:58.000Z
src/goto-symex/memory_model_sc.cpp
dan-blank/yogar-cbmc
05b4f056b585b65828acf39546c866379dca6549
[ "MIT" ]
4
2019-01-19T03:32:21.000Z
2021-12-20T14:25:19.000Z
/*******************************************************************\ Module: Memory model for partial order concurrency Author: Michael Tautschnig, michael.tautschnig@cs.ox.ac.uk \*******************************************************************/ #include <util/std_expr.h> #include <util/i2string.h> #include "memory_model_sc.h" #include <iostream> /*******************************************************************\ Function: memory_model_sct::operator() Inputs: Outputs: Purpose: \*******************************************************************/ void memory_model_sct::operator()(symex_target_equationt &equation) { print(8, "Adding SC constraints"); build_event_lists(equation); std::cout << equation.SSA_steps.size() << " steps" << "\n"; build_clock_type(equation); std::cout << equation.SSA_steps.size() << " steps" << "\n"; set_events_ssa_id(equation); read_from(equation); std::cout << equation.SSA_steps.size() << " steps" << "\n"; // read_from_backup(equation); std::cout << equation.SSA_steps.size() << " steps" << "\n"; // write_serialization_external(equation); std::cout << equation.SSA_steps.size() << " steps" << "\n"; // program_order(equation); std::cout << equation.SSA_steps.size() << " steps" << "\n"; // from_read(equation); std::cout << equation.SSA_steps.size() << " steps" << "\n"; } /*******************************************************************\ Function: memory_model_sct::before Inputs: Outputs: Purpose: \*******************************************************************/ exprt memory_model_sct::before(event_it e1, event_it e2) { return partial_order_concurrencyt::before( e1, e2, AX_PROPAGATION); } /*******************************************************************\ Function: memory_model_sct::program_order_is_relaxed Inputs: Outputs: Purpose: \*******************************************************************/ bool memory_model_sct::program_order_is_relaxed( partial_order_concurrencyt::event_it e1, partial_order_concurrencyt::event_it e2) const { assert(is_shared_read(e1) || is_shared_write(e1)); assert(is_shared_read(e2) || is_shared_write(e2)); return false; } /*******************************************************************\ Function: memory_model_sct::build_per_thread_map Inputs: Outputs: Purpose: \*******************************************************************/ void memory_model_sct::build_per_thread_map( const symex_target_equationt &equation, per_thread_mapt &dest) const { // this orders the events within a thread for(eventst::const_iterator e_it=equation.SSA_steps.begin(); e_it!=equation.SSA_steps.end(); e_it++) { // concurreny-related? if(!is_shared_read(e_it) && !is_shared_write(e_it) && !is_spawn(e_it) && !is_memory_barrier(e_it)) continue; dest[e_it->source.thread_nr].push_back(e_it); } } /*******************************************************************\ Function: memory_model_sct::thread_spawn Inputs: Outputs: Purpose: \*******************************************************************/ void memory_model_sct::thread_spawn( symex_target_equationt &equation, const per_thread_mapt &per_thread_map) { // thread spawn: the spawn precedes the first // instruction of the new thread in program order unsigned next_thread_id=0; for(eventst::const_iterator e_it=equation.SSA_steps.begin(); e_it!=equation.SSA_steps.end(); e_it++) { if(is_spawn(e_it)) { per_thread_mapt::const_iterator next_thread= per_thread_map.find(++next_thread_id); if(next_thread==per_thread_map.end()) continue; // For SC and several weaker memory models a memory barrier // at the beginning of a thread can simply be ignored, because // we enforce program order in the thread-spawn constraint // anyway. Memory models with cumulative memory barriers // require explicit handling of these. event_listt::const_iterator n_it=next_thread->second.begin(); for( ; n_it!=next_thread->second.end() && (*n_it)->is_memory_barrier(); ++n_it) ; if(n_it!=next_thread->second.end()) std::cout << "PO: (" << e_it->ssa_lhs.get_identifier() << ", " << (*n_it)->ssa_lhs.get_identifier() << ") \n"; add_constraint( equation, before(e_it, *n_it), "thread-spawn", e_it->source); } } } /*******************************************************************\ Function: memory_model_sct::program_order Inputs: Outputs: Purpose: \*******************************************************************/ void memory_model_sct::program_order( symex_target_equationt &equation) { per_thread_mapt per_thread_map; build_per_thread_map(equation, per_thread_map); thread_spawn(equation, per_thread_map); // iterate over threads int num = 0; int tt = 0; for(per_thread_mapt::const_iterator t_it=per_thread_map.begin(); t_it!=per_thread_map.end(); t_it++) { // std::cout << "======== begin thread " << num << "===========\n"; const event_listt &events=t_it->second; // iterate over relevant events in the thread event_it previous=equation.SSA_steps.end(); for(event_listt::const_iterator e_it=events.begin(); e_it!=events.end(); e_it++) { if(is_memory_barrier(*e_it)) continue; if(previous==equation.SSA_steps.end()) { // first one? previous=*e_it; continue; } // std::cout << tt << "PO: (" << previous->ssa_lhs.get_identifier() << ", " << (*e_it)->ssa_lhs.get_identifier() << ") \n"; add_constraint( equation, before(previous, *e_it), "po", (*e_it)->source); previous=*e_it; } // std::cout << "======== end thread " << num++ << "===========\n"; } } /*******************************************************************\ Function: memory_model_sct::write_serialization_external Inputs: Outputs: Purpose: \*******************************************************************/ void memory_model_sct::write_serialization_external( symex_target_equationt &equation) { for(address_mapt::const_iterator a_it=address_map.begin(); a_it!=address_map.end(); a_it++) { const a_rect &a_rec=a_it->second; // This is quadratic in the number of writes // per address. Perhaps some better encoding // based on 'places'? for(event_listt::const_iterator w_it1=a_rec.writes.begin(); w_it1!=a_rec.writes.end(); ++w_it1) { event_listt::const_iterator next=w_it1; ++next; for(event_listt::const_iterator w_it2=next; w_it2!=a_rec.writes.end(); ++w_it2) { // external? if((*w_it1)->source.thread_nr== (*w_it2)->source.thread_nr) continue; // ws is a total order, no two elements have the same rank // s -> w_evt1 before w_evt2; !s -> w_evt2 before w_evt1 symbol_exprt s=nondet_bool_symbol("ws-ext"); // write-to-write edge add_constraint( equation, implies_exprt(s, before(*w_it1, *w_it2)), "ws-ext", (*w_it1)->source); add_constraint( equation, implies_exprt(not_exprt(s), before(*w_it2, *w_it1)), "ws-ext", (*w_it1)->source); } } } } /*******************************************************************\ Function: memory_model_sct::from_read Inputs: Outputs: Purpose: \*******************************************************************/ void memory_model_sct::from_read(symex_target_equationt &equation) { // from-read: (w', w) in ws and (w', r) in rf -> (r, w) in fr for(address_mapt::const_iterator a_it=address_map.begin(); a_it!=address_map.end(); a_it++) { const a_rect &a_rec=a_it->second; // This is quadratic in the number of writes per address. for(event_listt::const_iterator w_prime=a_rec.writes.begin(); w_prime!=a_rec.writes.end(); ++w_prime) { event_listt::const_iterator next=w_prime; ++next; for(event_listt::const_iterator w=next; w!=a_rec.writes.end(); ++w) { exprt ws1, ws2; if(po(*w_prime, *w) && !program_order_is_relaxed(*w_prime, *w)) { ws1=true_exprt(); ws2=false_exprt(); } else if(po(*w, *w_prime) && !program_order_is_relaxed(*w, *w_prime)) { ws1=false_exprt(); ws2=true_exprt(); } else { ws1=before(*w_prime, *w); ws2=before(*w, *w_prime); } // smells like cubic for(choice_symbolst::const_iterator c_it=choice_symbols.begin(); c_it!=choice_symbols.end(); c_it++) { event_it r=c_it->first.first; exprt rf=c_it->second; exprt cond; cond.make_nil(); if(c_it->first.second==*w_prime && !ws1.is_false()) { exprt fr=before(r, *w); // the guard of w_prime follows from rf; with rfi // optimisation such as the previous write_symbol_primed // it would even be wrong to add this guard cond= implies_exprt( and_exprt(r->guard, (*w)->guard, ws1, rf), fr); } else if(c_it->first.second==*w && !ws2.is_false()) { exprt fr=before(r, *w_prime); // the guard of w follows from rf; with rfi // optimisation such as the previous write_symbol_primed // it would even be wrong to add this guard cond= implies_exprt( and_exprt(r->guard, (*w_prime)->guard, ws2, rf), fr); } if(cond.is_not_nil()) add_constraint(equation, cond, "fr", r->source); } } } } } void memory_model_sct::get_symbols(const exprt &expr, std::vector<symbol_exprt>& symbols) { forall_operands(it, expr) get_symbols(*it, symbols); if(expr.id()==ID_symbol) symbols.push_back(to_symbol_expr(expr)); } void memory_model_sct::set_events_ssa_id(symex_target_equationt &equation) { int id = 0; for(eventst::iterator e_it=equation.SSA_steps.begin(); e_it!=equation.SSA_steps.end(); e_it++) { if(e_it->is_assignment()) { unsigned event_num = 0; std::vector<symbol_exprt> symbols; get_symbols(e_it->cond_expr, symbols); for (unsigned i = 0; i < symbols.size(); i++) { unsigned result = set_single_event_ssa_id(equation, symbols[i], id); event_num += result; } if (event_num > 0) e_it->event_flag = true; } id++; } } unsigned memory_model_sct::set_single_event_ssa_id(symex_target_equationt &equation, symbol_exprt event, int id) { for(eventst::iterator e_it=equation.SSA_steps.begin(); e_it!=equation.SSA_steps.end(); e_it++) { if ((e_it->is_shared_read() || e_it->is_shared_write())) { if (e_it->ssa_lhs.get_identifier() == event.get_identifier()) { e_it->appear_ssa_id = id; return 1; } } } return 0; }
25.332599
125
0.537692
dan-blank
62abb37eaa85a0249284ab8ff4fe48f8b94351ba
2,567
cpp
C++
common/util/src/TokenRateLimiter.cpp
ewb4/HDTN
a0e577351bd28c3aeb7e656e03a2d93cf84712a0
[ "NASA-1.3" ]
null
null
null
common/util/src/TokenRateLimiter.cpp
ewb4/HDTN
a0e577351bd28c3aeb7e656e03a2d93cf84712a0
[ "NASA-1.3" ]
null
null
null
common/util/src/TokenRateLimiter.cpp
ewb4/HDTN
a0e577351bd28c3aeb7e656e03a2d93cf84712a0
[ "NASA-1.3" ]
null
null
null
#include "TokenRateLimiter.h" #include <iostream> TokenRateLimiter::TokenRateLimiter() : m_rateTokens(0), m_limit(0), m_remain(0) {} TokenRateLimiter::~TokenRateLimiter() {} void TokenRateLimiter::SetRate(const uint64_t tokens, const boost::posix_time::time_duration & interval, const boost::posix_time::time_duration & window) { if (interval.is_special()) { return; } m_rateTokens = tokens; m_rateInterval = interval; m_limit = m_rateTokens * window.ticks(); m_remain = m_limit; } void TokenRateLimiter::AddTime(const boost::posix_time::time_duration & interval) { if (interval.is_special()) { return; } const uint64_t delta = m_rateTokens * interval.ticks(); m_remain += delta; if (m_remain > m_limit) { m_remain = m_limit; } } uint64_t TokenRateLimiter::GetRemainingTokens() const { return m_remain / m_rateInterval.ticks(); } bool TokenRateLimiter::HasFullBucketOfTokens() const { return (m_remain == m_limit); } bool TokenRateLimiter::TakeTokens(const uint64_t tokens) { const uint64_t delta = tokens * m_rateInterval.ticks(); if (delta > m_remain) { return false; } m_remain -= delta; return true; } BorrowableTokenRateLimiter::BorrowableTokenRateLimiter() : m_rateTokens(0), m_limit(0), m_remain(0) {} BorrowableTokenRateLimiter::~BorrowableTokenRateLimiter() {} void BorrowableTokenRateLimiter::SetRate(const int64_t tokens, const boost::posix_time::time_duration & interval, const boost::posix_time::time_duration & window) { if (interval.is_special()) { return; } m_rateTokens = tokens; m_rateInterval = interval; m_limit = m_rateTokens * window.ticks(); m_remain = m_limit; } void BorrowableTokenRateLimiter::AddTime(const boost::posix_time::time_duration & interval) { if (interval.is_special()) { return; } const int64_t delta = m_rateTokens * interval.ticks(); m_remain += delta; if (m_remain > m_limit) { m_remain = m_limit; } } int64_t BorrowableTokenRateLimiter::GetRemainingTokens() const { return m_remain / m_rateInterval.ticks(); } bool BorrowableTokenRateLimiter::HasFullBucketOfTokens() const { return (m_remain == m_limit); } bool BorrowableTokenRateLimiter::TakeTokens(const uint64_t tokens) { if(m_remain < 0) { return false; } const int64_t delta = tokens * m_rateInterval.ticks(); m_remain -= delta; return true; } bool BorrowableTokenRateLimiter::CanTakeTokens() const { return (m_remain >= 0); }
26.463918
164
0.695754
ewb4
62acd74a7eae39c649b5709498645dad6fba7850
3,191
cpp
C++
plugins/libimhex/source/helpers/lang.cpp
Laxer3a/psdebugtool
41efa5f35785afd8f6dc868d8dbdb0dcf8eb25fb
[ "MIT" ]
4
2021-05-09T23:33:54.000Z
2022-03-06T10:16:31.000Z
plugins/libimhex/source/helpers/lang.cpp
Laxer3a/psdebugtool
41efa5f35785afd8f6dc868d8dbdb0dcf8eb25fb
[ "MIT" ]
null
null
null
plugins/libimhex/source/helpers/lang.cpp
Laxer3a/psdebugtool
41efa5f35785afd8f6dc868d8dbdb0dcf8eb25fb
[ "MIT" ]
6
2021-05-09T21:41:48.000Z
2021-09-08T10:54:28.000Z
#include "hex/helpers/lang.hpp" #include "hex/helpers/shared_data.hpp" namespace hex { LanguageDefinition::LanguageDefinition(std::initializer_list<std::pair<std::string, std::string>> entries) { for (auto pair : entries) this->m_entries.insert(pair); } const std::map<std::string, std::string>& LanguageDefinition::getEntries() const { return this->m_entries; } LangEntry::LangEntry(const char *unlocalizedString) : m_unlocalizedString(unlocalizedString) { } LangEntry::LangEntry(const std::string &unlocalizedString) : m_unlocalizedString(unlocalizedString) { } LangEntry::LangEntry(std::string_view unlocalizedString) : m_unlocalizedString(unlocalizedString) { } LangEntry::operator std::string() const { return std::string(get()); } LangEntry::operator std::string_view() const { return get(); } LangEntry::operator const char*() const { return get().data(); } std::string operator+(const std::string &&left, const LangEntry &&right) { return left + static_cast<std::string>(right); } std::string operator+(const LangEntry &&left, const std::string &&right) { return static_cast<std::string>(left) + right; } std::string operator+(const LangEntry &&left, const LangEntry &&right) { return static_cast<std::string>(left) + static_cast<std::string>(right); } std::string operator+(const std::string_view &&left, const LangEntry &&right) { return std::string(left) + static_cast<std::string>(right); } std::string operator+(const LangEntry &&left, const std::string_view &&right) { return static_cast<std::string>(left) + std::string(right); } std::string operator+(const char *left, const LangEntry &&right) { return left + static_cast<std::string>(right); } std::string operator+(const LangEntry &&left, const char *right) { return static_cast<std::string>(left) + right; } std::string_view LangEntry::get() const { auto &lang = SharedData::loadedLanguageStrings; if (lang.find(this->m_unlocalizedString) != lang.end()) return lang[this->m_unlocalizedString]; else return this->m_unlocalizedString; } void LangEntry::loadLanguage(std::string_view language) { constexpr auto DefaultLanguage = "en-US"; SharedData::loadedLanguageStrings.clear(); auto &definitions = ContentRegistry::Language::getLanguageDefinitions(); if (!definitions.contains(language.data())) return; for (auto &definition : definitions[language.data()]) SharedData::loadedLanguageStrings.insert(definition.getEntries().begin(), definition.getEntries().end()); if (language != DefaultLanguage) { for (auto &definition : definitions[DefaultLanguage]) SharedData::loadedLanguageStrings.insert(definition.getEntries().begin(), definition.getEntries().end()); } } const std::map<std::string, std::string>& LangEntry::getSupportedLanguages() { return ContentRegistry::Language::getLanguages(); } }
35.065934
121
0.655907
Laxer3a
62acf418bcf9c8a2720f202b27b4b065944b3730
1,416
cpp
C++
solved-uva/10583.cpp
Maruf-Tuhin/Online_Judge
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
1
2019-03-31T05:47:30.000Z
2019-03-31T05:47:30.000Z
solved-uva/10583.cpp
the-redback/competitive-programming
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
null
null
null
solved-uva/10583.cpp
the-redback/competitive-programming
cf9b2a522e8b1a9623d3996a632caad7fd67f751
[ "MIT" ]
null
null
null
/** * @author : Maruf Tuhin * @School : CUET CSE 11 * @TOPCODER : the_redback * @CodeForces : the_redback * @UVA : Redback * @link : http://www.fb.com/maruf.2hin */ #include<cstdio> #include<cstring> #include<cstdlib> #include<cctype> #include<cmath> #include<iostream> #include<fstream> #include<string> #include<vector> #include<queue> #include<map> #include<algorithm> #include<set> #include<sstream> #include<stack> using namespace std; #define inf 10000000 #define mem(a,b) memset(a,b,sizeof(a)) #define NN 50000 int prnt[NN+7]; int a[NN+7]; int root(int n) { if(prnt[n]==n) return n; return root(prnt[n]); } main() { //freopen("C:\\Users\\Maruf Tuhin\\Desktop\\in.txt","r",stdin); //ios_base::sync_with_stdio(false); int i,j,k,l,n,r,c,count; int tc,t=1; //scanf("%d",&tc); while(~scanf("%d%d",&n,&r)) { if(n==0 && r==0) return 0; for(i=1;i<=n;i++) prnt[i]=i; while(r--) { scanf("%d%d",&k,&l); int u=root(k); int v=root(l); if(u!=v) prnt[u]=v; } mem(a,0); count=0; for(i=1;i<=n;i++) { int u=root(i); if(a[u]==0) count++; a[u]=1; } printf("Case %d: %d\n",t++,count); } return 0; }
19.39726
67
0.484463
Maruf-Tuhin
62b525f4b0bf8f3f48b32c0226c71c01d43dd978
1,944
cpp
C++
test/write_batch_test.cpp
qqiangwu/cloudkv
cd033b3b7dcd4b5a4807bf92b6d92bae5bb38d47
[ "MIT" ]
1
2021-12-05T05:15:52.000Z
2021-12-05T05:15:52.000Z
test/write_batch_test.cpp
qqiangwu/cloudkv
cd033b3b7dcd4b5a4807bf92b6d92bae5bb38d47
[ "MIT" ]
null
null
null
test/write_batch_test.cpp
qqiangwu/cloudkv
cd033b3b7dcd4b5a4807bf92b6d92bae5bb38d47
[ "MIT" ]
null
null
null
#include <vector> #include <range/v3/view.hpp> #include <gtest/gtest.h> #include "cloudkv/write_batch.h" using namespace cloudkv; using namespace ranges; TEST(write_batch, Add) { write_batch b; b.add("a", "a"); EXPECT_EQ(b.size(), 1); for (const auto i: views::indices(1024)) { b.add(std::to_string(i), std::to_string(i)); EXPECT_EQ(b.size(), 1 + i + 1); } } TEST(write_batch, Remove) { write_batch b; b.remove("a"); EXPECT_EQ(b.size(), 1); for (const auto i: views::indices(1024)) { b.remove(std::to_string(i)); EXPECT_EQ(b.size(), 1 + i + 1); } } TEST(write_batch, Iterate) { struct Entry { bool is_delete; std::string_view key; std::string_view val; }; struct Collector : write_batch::handler { std::vector<Entry> entries; void add(std::string_view key, std::string_view val) override { entries.push_back({ false, key, val }); } void remove(std::string_view key) override { entries.push_back({ true, key, "" }); } }; std::vector<Entry> entries_expected = { { false, "1", "01" }, { false, "2", "02" }, { true, "3", "" }, { false, "4", "04" } }; write_batch batch; for (const auto& e: entries_expected) { if (e.is_delete) { batch.remove(e.key); } else { batch.add(e.key, e.val); } } Collector h; batch.iterate(&h); EXPECT_EQ(h.entries.size(), entries_expected.size()); for (const auto i: views::indices(entries_expected.size())) { const auto& iterated = h.entries[i]; const auto& expected = entries_expected[i]; EXPECT_EQ(iterated.is_delete, expected.is_delete); EXPECT_EQ(iterated.key, expected.key); EXPECT_EQ(iterated.val, expected.val); } }
21.6
69
0.545782
qqiangwu
62b96cc0e71367910cf61c48ca64a1ca20e1e487
826
cpp
C++
src/MdCharm/util/updatetocthread.cpp
MonkeyMo/MdCharm
78799f0bd85603aae9361b4fca05384a69f690e6
[ "BSD-3-Clause" ]
387
2015-01-01T17:51:59.000Z
2021-06-13T19:40:15.000Z
src/MdCharm/util/updatetocthread.cpp
MonkeyMo/MdCharm
78799f0bd85603aae9361b4fca05384a69f690e6
[ "BSD-3-Clause" ]
26
2015-01-09T08:36:26.000Z
2020-04-02T12:51:01.000Z
src/MdCharm/util/updatetocthread.cpp
heefan/MdCharm
78799f0bd85603aae9361b4fca05384a69f690e6
[ "BSD-3-Clause" ]
145
2015-01-10T18:07:45.000Z
2021-09-14T07:39:35.000Z
// Copyright (c) 2014 zhangshine. All rights reserved. // Use of this source code is governed by a BSD license that can be // found in the LICENSE file. #include "updatetocthread.h" UpdateTocThread::UpdateTocThread(QObject *parent) : QThread(parent) { } void UpdateTocThread::run() { if(this->type == MarkdownToHtml::MultiMarkdown){ emit workerResult(QString()); } else { std::string stdResult; QByteArray content = this->content.toUtf8(); MarkdownToHtml::renderMarkdownExtarToc(this->type, content.data(), content.length(), stdResult); emit workerResult(QString::fromUtf8(stdResult.c_str(), stdResult.length())); } } void UpdateTocThread::setContent(MarkdownToHtml::MarkdownType type, const QString &content) { this->type = type; this->content = content; }
28.482759
104
0.696126
MonkeyMo
62be39df916655715856391362c1bee44d19356f
485
cpp
C++
Luogu/P1115/P1115.cpp
AtomAlpaca/OI-Codes
11f8dd4798616f1937d190e7220d7eedaeb75169
[ "WTFPL" ]
1
2021-11-12T14:19:53.000Z
2021-11-12T14:19:53.000Z
Luogu/P1115/P1115.cpp
AtomAlpaca/OI-Codes
11f8dd4798616f1937d190e7220d7eedaeb75169
[ "WTFPL" ]
null
null
null
Luogu/P1115/P1115.cpp
AtomAlpaca/OI-Codes
11f8dd4798616f1937d190e7220d7eedaeb75169
[ "WTFPL" ]
null
null
null
#include <iostream> #include <cmath> #include <algorithm> using std::cin; using std::cout; int main(int argc, char const *argv[]) { //int m = -10000000; int * n = new int; cin >> *n; int nums[*n + 1] = {0}; int ans [*n + 1] = {0}; int m = -99999999; for (int i = 1; i <= *n; ++i) { cin >> nums[i]; ans[i] = std::max(ans[i - 1] + nums[i], nums[i]); m = std::max(m, ans[i]); } cout << m; delete n; return 0; }
16.724138
57
0.463918
AtomAlpaca
62be72f300f0bc4e7c0f81203ee26c504a78719b
6,270
cpp
C++
src/main.cpp
cowdingus/SFML-Grapher
47d0e661aa9c411d9a41f4fe8f4df7860af7ec74
[ "Unlicense" ]
1
2021-01-26T09:52:41.000Z
2021-01-26T09:52:41.000Z
src/main.cpp
cowdingus/SFML-Grapher
47d0e661aa9c411d9a41f4fe8f4df7860af7ec74
[ "Unlicense" ]
1
2020-11-10T06:54:07.000Z
2020-11-10T11:40:53.000Z
src/main.cpp
cowdingus/SFML-Grapher
47d0e661aa9c411d9a41f4fe8f4df7860af7ec74
[ "Unlicense" ]
null
null
null
/* * ToDo: * look at @setSize implementation * fix bugs * * Bugs Found: * crashes and hangs the whole computer when setting zoom value to some little value */ #include "CartesianGraphView.hpp" #include "CartesianGrid.hpp" #include "DotGraph.hpp" #include <SFML/Graphics.hpp> #include <SFML/Window/ContextSettings.hpp> #include <iostream> #include <cassert> template<typename T> std::ostream& operator<<(std::ostream& out, const sf::Vector2<T>& vector) { return out << "{" << vector.x << ", " << vector.y << "}"; } template<typename T> std::ostream& operator<<(std::ostream& out, const sf::Rect<T>& rect) { return out << "{" << rect.left << ", " << rect.top << ", " << rect.width << ", " << rect.height << "}" << std::endl; } std::ostream& operator<<(std::ostream& out, const sf::Transform& transform) { const float* m = transform.getMatrix(); out << "[" << m[0] << '\t' << m[4] << '\t' << m[8 ] << '\t' << m[12] << '\t' << "]" << std::endl << "[" << m[1] << '\t' << m[5] << '\t' << m[9 ] << '\t' << m[13] << '\t' << "]" << std::endl << "[" << m[2] << '\t' << m[6] << '\t' << m[10] << '\t' << m[14] << '\t' << "]" << std::endl << "[" << m[3] << '\t' << m[7] << '\t' << m[11] << '\t' << m[15] << '\t' << "]" << std::endl; return out; } int main() { sf::ContextSettings settings; settings.antialiasingLevel = 4; sf::RenderWindow window(sf::VideoMode(800, 600), "NULL", sf::Style::Default, settings); window.setFramerateLimit(15); { std::cout << "Graph Tests" << std::endl; DotGraph lg; lg.addPoint({1, 1}); assert(lg.getPoint(0) == sf::Vector2f(1, 1)); lg.removePoint(0); assert(lg.getPointsCount() == 0); lg.addPoint({1, 1}); assert(lg.getPoint(0) == sf::Vector2f(1, 1)); lg.clearPoints(); assert(lg.getPointsCount() == 0); std::cout << "Graph Data Insertion/Deletion Tests Passed" << std::endl; lg.setGridColor(sf::Color::White); assert(lg.getGridColor() == sf::Color::White); lg.setGridGap({10, 10}); assert(lg.getGridGap() == sf::Vector2f(10, 10)); lg.setColor(sf::Color::Black); assert(lg.getColor() == sf::Color::Black); CartesianGraphView view = lg.getView(); view.setViewRect({0, 0, 10, 10}); lg.setView(view); std::cout << lg.getView().getViewRect() << std::endl; assert(lg.getView().getViewRect() == sf::FloatRect(0, 0, 10, 10)); std::cout << "Visual Properties Tests Passed" << std::endl; } { std::cout << "Graph View Tests" << std::endl; CartesianGraphView view; view.setCenter({100, 100}); assert(view.getCenter() == sf::Vector2f(100, 100)); view.setSize({100, 100}); assert(view.getSize() == sf::Vector2f(100, 100)); view.setViewRect({0, 0, 10, 10}); assert(view.getViewRect() == sf::FloatRect(0, 0, 10, 10)); assert(view.getCenter() == sf::Vector2f(5, 5)); assert(view.getSize() == sf::Vector2f(10, 10)); view.setCenter({10, 10}); assert(view.getCenter() == sf::Vector2f(10, 10)); view.setSize({10, 10}); assert(view.getSize() == sf::Vector2f(10, 10)); view.setZoom({10, 10}); assert(view.getZoom() == sf::Vector2f(10, 10)); view = CartesianGraphView(); view.setCenter({1, 1}); view.setSize({2, 2}); std::cout << view.getTransform() * sf::Vector2f(0, 0) << std::endl; assert(view.getTransform() * sf::Vector2f(0, 0) == sf::Vector2f(0, 0)); } std::cout << "All Tests Passed" << std::endl << std::endl; DotGraph lg({400, 400}); lg.setPosition(100, 100); lg.addPoint({0, 0}); lg.addPoint({-1, 0}); lg.addPoint({1, 0}); lg.addPoint({0, -1}); lg.addPoint({0, 1}); lg.addPoint({0, 2}); lg.addPoint({-3, 0}); lg.setGridGap({1, 1}); lg.setGridColor(sf::Color(100, 100, 100)); CartesianGraphView lgv; lgv.setCenter({-2, -2}); lgv.setSize({8, 8}); lgv.setViewRect({-2, -2, 8, 8}); lgv.setCenter({0, 0}); lgv.setSize({10, 10}); lgv.setZoom({2,1}); lg.setView(lgv); lg.setSize({200, 200}); lg.setColor(sf::Color::Cyan); sf::RectangleShape boundingBox; boundingBox.setSize(static_cast<sf::Vector2f>(lg.getSize())); boundingBox.setPosition({100, 100}); boundingBox.setOutlineThickness(1); boundingBox.setOutlineColor(sf::Color::Magenta); boundingBox.setFillColor(sf::Color(0, 0, 0, 0)); sf::Font arial; if (!arial.loadFromFile("debug/Arial.ttf")) { sf::err() << "Error: Can't load font file" << std::endl; } sf::Text keymapGuide; keymapGuide.setString( "[M] to zoom in\n" "[N] to zoom out\n" "[Arrow keys] to move graph\n" "[W | A | S | D] to move view\n" ); keymapGuide.setFont(arial); keymapGuide.setCharacterSize(12); keymapGuide.setFillColor(sf::Color::White); keymapGuide.setPosition( { window.getSize().x - keymapGuide.getGlobalBounds().width, window.getSize().y - keymapGuide.getGlobalBounds().height } ); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: { window.close(); break; } case sf::Event::KeyPressed: { sf::View newView = window.getView(); CartesianGraphView graphView = lg.getView(); switch (event.key.code) { case sf::Keyboard::W: newView.move(0, -10); break; case sf::Keyboard::S: newView.move(0, 10); break; case sf::Keyboard::A: newView.move(-10, 0); break; case sf::Keyboard::D: newView.move(10, 0); break; case sf::Keyboard::Up: graphView.move({0, 0.1}); break; case sf::Keyboard::Down: graphView.move({0, -0.1}); break; case sf::Keyboard::Left: graphView.move({-0.1, 0}); break; case sf::Keyboard::Right: graphView.move({0.1, 0}); break; case sf::Keyboard::M: if (graphView.getZoom().x < 3 && graphView.getZoom().y < 3) graphView.setZoom(graphView.getZoom() + sf::Vector2f(0.1f, 0.1f)); break; case sf::Keyboard::N: if (graphView.getZoom().x > 1 && graphView.getZoom().y > 1) graphView.setZoom(graphView.getZoom() - sf::Vector2f(0.1f, 0.1f)); break; default: break; } lg.setView(graphView); window.setView(newView); break; } default: { break; } } } lg.update(); window.clear(); window.draw(lg); window.draw(boundingBox); window.draw(keymapGuide); window.display(); } }
24.782609
117
0.59378
cowdingus
498329ce67e1973db69564b5ac7ac9288d12e1be
988
hpp
C++
CTCWordBeamSearch-master/cpp/DataLoader.hpp
brucegrapes/htr
9f8f07173ccc740dd8a4dfc7e8038abe36664756
[ "MIT" ]
488
2018-03-01T11:18:26.000Z
2022-03-10T09:29:32.000Z
CTCWordBeamSearch-master/cpp/DataLoader.hpp
brucegrapes/htr
9f8f07173ccc740dd8a4dfc7e8038abe36664756
[ "MIT" ]
60
2018-03-10T18:37:51.000Z
2022-03-30T19:37:18.000Z
CTCWordBeamSearch-master/cpp/DataLoader.hpp
brucegrapes/htr
9f8f07173ccc740dd8a4dfc7e8038abe36664756
[ "MIT" ]
152
2018-03-01T11:18:25.000Z
2022-03-08T23:37:46.000Z
#pragma once #include "MatrixCSV.hpp" #include "LanguageModel.hpp" #include <string> #include <vector> #include <memory> #include <stdint.h> #include <cstddef> // load sample data, create LM from it, iterate over samples class DataLoader { public: // sample with matrix to be decoded and ground truth text struct Data { MatrixCSV mat; std::vector<uint32_t> gt; }; // CTOR. Path points to directory holding files corpus.txt, chars.txt, wordChars.txt and samples mat_X.csv and gt_X.txt with X in {0, 1, 2, ...} DataLoader(const std::string& path, size_t sampleEach, LanguageModelType lmType, double addK=0.0); // get LM std::shared_ptr<LanguageModel> getLanguageModel() const; // iterator interface Data getNext() const; bool hasNext() const; private: std::string m_path; std::shared_ptr<LanguageModel> m_lm; mutable size_t m_currIdx=0; const size_t m_sampleEach = 1; void applySoftmax(MatrixCSV& mat) const; bool fileExists(const std::string& path) const; };
22.976744
145
0.733806
brucegrapes
498b1074a57620a2675251ec28d972bfd0278f67
27
cpp
C++
lootman/f4se/bhkWorld.cpp
clayne/Lootman
248befd3e1775a0eb9ca6dcbe261937d9641ef1c
[ "MIT" ]
10
2019-06-01T20:24:04.000Z
2021-08-16T19:32:24.000Z
lootman/f4se/bhkWorld.cpp
clayne/Lootman
248befd3e1775a0eb9ca6dcbe261937d9641ef1c
[ "MIT" ]
null
null
null
lootman/f4se/bhkWorld.cpp
clayne/Lootman
248befd3e1775a0eb9ca6dcbe261937d9641ef1c
[ "MIT" ]
5
2019-07-04T05:54:14.000Z
2021-10-11T11:19:57.000Z
#include "f4se/bhkWorld.h"
13.5
26
0.740741
clayne
498f94159e65d0f63e199e4534264d92426142da
434
cpp
C++
source/Ch08/orai_anyag/vector_pass_by.cpp
Vada200/UDProg-Introduction
c424b2676d6e5bfc4d53d61c5d0deded566c1c84
[ "CC0-1.0" ]
null
null
null
source/Ch08/orai_anyag/vector_pass_by.cpp
Vada200/UDProg-Introduction
c424b2676d6e5bfc4d53d61c5d0deded566c1c84
[ "CC0-1.0" ]
null
null
null
source/Ch08/orai_anyag/vector_pass_by.cpp
Vada200/UDProg-Introduction
c424b2676d6e5bfc4d53d61c5d0deded566c1c84
[ "CC0-1.0" ]
null
null
null
#include "std_lib_facilities.h" void print (vector <double>& v) //& -->referencia miatt gyorsabb a lefutás //mert nem másolódik a v, hanem a v ugyanaz lesz mint a vd1 { cout << "{"; for (int i = 0; i < v.size(); i++) { cout << v[i]; if(i < v.size()-1) cout << ","; } cout << "}\n"; } int main() { vector <double> vd1 (10); vector <double> vd2 (100000); print(vd2); return 0; }
16.692308
60
0.520737
Vada200
4992e1630ce5e963ee2b1cc766c06866946cb4d5
2,991
cpp
C++
port/linux/test/content-test.cpp
GorgonMeducer/pikascript
fefe9afb17d14c1a3bbe75c4c6a83d65831f451e
[ "MIT" ]
null
null
null
port/linux/test/content-test.cpp
GorgonMeducer/pikascript
fefe9afb17d14c1a3bbe75c4c6a83d65831f451e
[ "MIT" ]
null
null
null
port/linux/test/content-test.cpp
GorgonMeducer/pikascript
fefe9afb17d14c1a3bbe75c4c6a83d65831f451e
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "test_common.h" extern "C" { #include "dataArg.h" #include "dataString.h" } #if 0 TEST(content, init) { uint8_t contentIn[4] = {0}; contentIn[0] = 1; contentIn[1] = 2; contentIn[2] = 3; contentIn[3] = 4; Arg* self = content_init("name", ARG_TYPE_NONE, contentIn, 4, NULL); uint16_t typeOffset = content_typeOffset(self); uint16_t sizeOffset = content_sizeOffset(self); uint16_t contentOffset = content_contentOffset(self); uint16_t totleSize = content_totleSize(self); Hash nameHash = content_getNameHash(self); ArgType type = content_getType(self); uint16_t size = content_getSize(self); uint8_t* content = content_getContent(self); ASSERT_EQ(contentOffset, 16); ASSERT_EQ(typeOffset, 20); ASSERT_EQ(sizeOffset, 8); ASSERT_EQ(size, 4); ASSERT_EQ(content[0], 1); ASSERT_EQ(content[1], 2); ASSERT_EQ(content[2], 3); ASSERT_EQ(content[3], 4); ASSERT_EQ(totleSize, 24); ASSERT_EQ(hash_time33("name"), nameHash); ASSERT_EQ(ARG_TYPE_NONE, type); arg_freeContent(self); EXPECT_EQ(pikaMemNow(), 0); } TEST(content, set) { uint8_t contentIn[4] = {0}; contentIn[0] = 1; contentIn[1] = 2; contentIn[2] = 3; contentIn[3] = 4; Arg* self = content_init("", ARG_TYPE_NONE, NULL, 0, NULL); self = content_setName(self, "name"); self = arg_setType(self, ARG_TYPE_NONE); self = content_setContent(self, contentIn, 4); uint16_t typeOffset = content_typeOffset(self); uint16_t sizeOffset = content_sizeOffset(self); uint16_t contentOffset = content_contentOffset(self); uint16_t totleSize = content_totleSize(self); Hash nameHash = content_getNameHash(self); ArgType type = content_getType(self); uint16_t size = content_getSize(self); uint8_t* content = content_getContent(self); ASSERT_EQ(contentOffset, 16); ASSERT_EQ(typeOffset, 20); ASSERT_EQ(sizeOffset, 8); ASSERT_EQ(size, 4); ASSERT_EQ(content[0], 1); ASSERT_EQ(content[1], 2); ASSERT_EQ(content[2], 3); ASSERT_EQ(content[3], 4); ASSERT_EQ(totleSize, 24); ASSERT_EQ(hash_time33("name"), nameHash); ASSERT_EQ(ARG_TYPE_NONE, type); arg_freeContent(self); EXPECT_EQ(pikaMemNow(), 0); } TEST(content, next) { uint8_t* c1 = content_init("c1", ARG_TYPE_NONE, NULL, 0, NULL); uint8_t* c2 = content_init("c2", ARG_TYPE_NONE, NULL, 0, c1); uint8_t* c3 = content_getNext(c2); ASSERT_EQ(c3, c1); arg_freeContent(c1); arg_freeContent(c2); EXPECT_EQ(pikaMemNow(), 0); } TEST(content, setNext) { uint8_t* c1 = content_init("c1", ARG_TYPE_NONE, NULL, 0, NULL); content_setNext(c1, content_init("c2", ARG_TYPE_NONE, NULL, 0, NULL)); uint8_t* c2 = content_getNext(c1); Hash c2NameHash = content_getNameHash(c2); EXPECT_EQ(c2NameHash, hash_time33("c2")); arg_freeContent(c1); arg_freeContent(c2); EXPECT_EQ(pikaMemNow(), 0); } #endif
29.038835
74
0.67235
GorgonMeducer
499663b2dfd9a254ef35277d5d85dc6b8003a24e
818
cpp
C++
cyclic_fn.cpp
zaimoni/Iskandria
b056d2ba359b814db02aab42eba8d5f7f5ca7a1a
[ "BSL-1.0" ]
2
2019-11-23T12:35:49.000Z
2022-02-10T08:27:54.000Z
cyclic_fn.cpp
zaimoni/Iskandria
b056d2ba359b814db02aab42eba8d5f7f5ca7a1a
[ "BSL-1.0" ]
8
2019-11-15T08:13:48.000Z
2020-04-29T00:35:42.000Z
cyclic_fn.cpp
zaimoni/Iskandria
b056d2ba359b814db02aab42eba8d5f7f5ca7a1a
[ "BSL-1.0" ]
null
null
null
// cyclic_fn.cpp // pure test driver #include "cyclic_fn.hpp" #include <functional> // example build line (have to copy from *.hpp to *.cpp or else main not seen // If doing INFORM-based debugging // g++ -std=c++11 -ocyclic_fn.exe cyclic_fn.cpp -Llib/host.isk -lz_log_adapter -lz_stdio_log -lz_format_util #include "test_driver.h" int main(int argc, char* argv[]) { // parse options char buf[100]; STRING_LITERAL_TO_STDOUT("starting main\n"); const signed char tmp[2] = {1,-1}; zaimoni::math::mod_n::cyclic_fn_enumerated<2,signed char> test(tmp); INFORM(test(0)); INFORM(test(1)); INFORM(test(2)); std::function<signed char (uintmax_t)> test_fn = test; INFORM(test_fn(0)); INFORM(test_fn(1)); INFORM(test_fn(2)); STRING_LITERAL_TO_STDOUT("tests finished\n"); }
23.371429
109
0.679707
zaimoni
499ad331e198929ca8c0116e353dc02b3e64887b
14,774
cpp
C++
src/program_options.cpp
WenbinHou/xcp-old
e1efbebe625e379189d82b4641e575849fbcf628
[ "MIT" ]
1
2020-09-10T19:50:38.000Z
2020-09-10T19:50:38.000Z
src/program_options.cpp
WenbinHou/xcp-old
e1efbebe625e379189d82b4641e575849fbcf628
[ "MIT" ]
null
null
null
src/program_options.cpp
WenbinHou/xcp-old
e1efbebe625e379189d82b4641e575849fbcf628
[ "MIT" ]
1
2020-07-14T05:10:22.000Z
2020-07-14T05:10:22.000Z
#include "common.h" //============================================================================== // struct host_path //============================================================================== bool xcp::host_path::parse(const std::string& value) { // Handle strings like: // "relative" // "relative/subpath" // "/absolute/path" // "C:" (on Windows) // "C:\" (on Windows) // "C:/" (on Windows) // "C:\absolute\path" (on Windows) // "C:/absolute\path" (on Windows) // "relative\subpath" // "hostname:/" // "hostname:/absolute" // "127.0.0.1:C:" // "1.2.3.4:C:\" // "1.2.3.4:C:/" // "[::1]:C:\absolute" // "[1:2:3:4:5:6:7:8]:C:/absolute" // // NOTE: // Remote path MUST be absolute // Local path might be absolute or relative // See: // https://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses // https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address // NOTE: re_valid_hostname matches a superset of valid IPv4 static std::regex* __re = nullptr; if (__re == nullptr) { const std::string re_valid_hostname = R"((?:(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*(?:[A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])))"; const std::string re_valid_ipv6 = R"((?:\[(?:(?:[0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,7}:|(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}|(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}|(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}|(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:(?:(?::[0-9a-fA-F]{1,4}){1,6})|:(?:(?::[0-9a-fA-F]{1,4}){1,7}|:)|::(?:[Ff]{4}(?::0{1,4})?:)?(?:(?:25[0-5]|(?:2[0-4]|1?[0-9])?[0-9])\.){3,3}(?:25[0-5]|(?:2[0-4]|1?[0-9])?[0-9])|(?:[0-9a-fA-F]{1,4}:){1,4}:(?:(?:25[0-5]|(?:2[0-4]|1?[0-9])?[0-9])\.){3,3}(?:25[0-5]|(?:2[0-4]|1?[0-9])?[0-9]))\]))"; const std::string re_valid_host = "(?:" + re_valid_hostname + "|" + re_valid_ipv6 + ")"; const std::string re_valid_host_path = "^(?:(?:([^@:]+)@)?(" + re_valid_host + "):)?((?:^.+)|(?:.*))$"; __re = new std::regex(re_valid_host_path, std::regex::optimize); } if (value.empty()) return false; // // Special handling for Windows driver letters (local path) // #if PLATFORM_WINDOWS || PLATFORM_CYGWIN if (value.size() >= 2 && value[1] == ':') { if ((value[0] >= 'A' && value[0] <= 'Z') || (value[0] >= 'a' && value[0] <= 'z')) { if (value.size() == 2 || value[2] == '/' || value[2] == '\\') { user.reset(); host.reset(); path = value; return true; } } } #elif PLATFORM_LINUX #else # error "Unknown platform" #endif std::smatch match; if (!std::regex_match(value, match, *__re)) { return false; } { // The user part std::string tmp(match[1].str()); if (tmp.empty()) user.reset(); else user= std::move(tmp); } { // The host part // NOTE: If host is IPv6 surrounded by '[' ']', DO NOT trim the beginning '[' and ending ']' std::string tmp(match[2].str()); if (tmp.empty()) host.reset(); else host = std::move(tmp); } { path = match[3].str(); if (path.empty()) { if (!host.has_value()) { return false; } else { path = "~"; } } } return true; } //============================================================================== // struct base_program_options //============================================================================== void xcp::base_program_options::add_options(CLI::App& app) { app.add_flag( "-V,--version", [&](const size_t /*count*/) { printf("Version %d.%d.%d\nGit branch %s commit %s\n", XCP_VERSION_MAJOR, XCP_VERSION_MINOR, XCP_VERSION_PATCH, TEXTIFY(XCP_GIT_BRANCH), TEXTIFY(XCP_GIT_COMMIT_HASH)); exit(0); }, "Print version and exit"); app.add_flag( "-q,--quiet", [&](const size_t count) { this->arg_verbosity -= static_cast<int>(count); }, "Be more quiet"); app.add_flag( "-v,--verbose", [&](const size_t count) { this->arg_verbosity += static_cast<int>(count); }, "Be more verbose"); } bool xcp::base_program_options::post_process() { // Set verbosity infra::set_logging_verbosity(this->arg_verbosity); return true; } //============================================================================== // struct xcp_program_options //============================================================================== void xcp::xcp_program_options::add_options(CLI::App& app) { base_program_options::add_options(app); CLI::Option* opt_port = app.add_option( "-P,-p,--port", this->arg_port, "Server portal port to connect to"); opt_port->type_name("<port>"); CLI::Option* opt_from = app.add_option( "from", this->arg_from_path, "Copy from this path"); opt_from->type_name("<from>"); opt_from->required(); CLI::Option* opt_to = app.add_option( "to", this->arg_to_path, "Copy to this path"); opt_to->type_name("<to>"); opt_to->required(); [[maybe_unused]] CLI::Option* opt_recursive = app.add_flag( "-r,--recursive", this->arg_recursive, "Transfer a directory recursively"); CLI::Option* opt_user = app.add_option( "-u,--user", this->arg_user, "Relative to this user's home directory on server side"); opt_user->type_name("<user>"); CLI::Option* opt_block = app.add_option( "-B,--block", this->arg_transfer_block_size, "Transfer block size"); opt_block->type_name("<size>"); opt_block->transform(CLI::AsSizeValue(false)); } bool xcp::xcp_program_options::post_process() { if (!base_program_options::post_process()) { return false; } //---------------------------------------------------------------- // arg_from_path, arg_to_path //---------------------------------------------------------------- if (arg_from_path.is_remote()) { ASSERT(arg_from_path.host.has_value()); LOG_DEBUG("Copy from remote host {} path {}", arg_from_path.host.value(), arg_from_path.path); } else { LOG_DEBUG("Copy from local path {}", arg_from_path.path); } if (arg_to_path.is_remote()) { ASSERT(arg_to_path.host.has_value()); LOG_DEBUG("Copy to remote host {} path {}", arg_to_path.host.value(), arg_to_path.path); } else { LOG_DEBUG("Copy to local path {}", arg_to_path.path); } if (arg_from_path.is_remote() && arg_to_path.is_remote()) { LOG_ERROR("Can't copy between remote hosts"); return false; } else if (arg_from_path.is_remote()) { is_from_server_to_client = true; server_portal.host = arg_from_path.host.value(); } else if (arg_to_path.is_remote()) { is_from_server_to_client = false; server_portal.host = arg_to_path.host.value(); } else { LOG_ERROR("Copy from local to local is to be supported"); // TODO return false; } //---------------------------------------------------------------- // arg_port //---------------------------------------------------------------- if (arg_port.has_value()) { if (arg_port.value() == 0) { LOG_ERROR("Server portal port 0 is invalid"); return false; } } else { // !arg_portal->port.has_value() arg_port = program_options_defaults::SERVER_PORTAL_PORT; } server_portal.port = arg_port.value(); LOG_DEBUG("Server portal: {}", server_portal.to_string()); if (!server_portal.resolve()) { LOG_ERROR("Can't resolve specified server portal: {}", server_portal.to_string()); return false; } else { for (const infra::tcp_sockaddr& addr : server_portal.resolved_sockaddrs) { LOG_DEBUG(" Candidate server portal endpoint: {}", addr.to_string()); } } //---------------------------------------------------------------- // arg_recursive //---------------------------------------------------------------- if (arg_recursive) { LOG_DEBUG("Transfer recursively if source is a directory"); } //---------------------------------------------------------------- // arg_user //---------------------------------------------------------------- bool got_user = false; if (arg_user.has_value()) { server_user.user_name = arg_user.value(); got_user = true; } else { if (arg_from_path.is_remote()) { ASSERT(is_from_server_to_client); if (arg_from_path.user.has_value()) { server_user.user_name = arg_from_path.user.value(); got_user = true; } } else if (arg_to_path.is_remote()) { ASSERT(!is_from_server_to_client); if (arg_to_path.user.has_value()) { server_user.user_name = arg_to_path.user.value(); got_user = true; } } } if (!got_user) { if (infra::get_user_name(server_user)) { got_user = true; } } if (got_user) { LOG_TRACE("Use this user for server side: {}", server_user.to_string()); } else { server_user = { }; LOG_WARN("Can't get user. Use no user for server side"); } //---------------------------------------------------------------- // arg_transfer_block_size //---------------------------------------------------------------- if (arg_transfer_block_size.has_value()) { if (arg_transfer_block_size.value() > program_options_defaults::MAX_TRANSFER_BLOCK_SIZE) { LOG_WARN("Transfer block size is too large: {}. Set to MAX_TRANSFER_BLOCK_SIZE: {}", arg_transfer_block_size.value(), program_options_defaults::MAX_TRANSFER_BLOCK_SIZE); arg_transfer_block_size = program_options_defaults::MAX_TRANSFER_BLOCK_SIZE; } } else { arg_transfer_block_size = 0; } if (arg_transfer_block_size.value() == 0) { LOG_TRACE("Transfer block size: automatic tuning"); } else if (arg_transfer_block_size.value() < 1024 * 64) { LOG_WARN("Transfer block size {} is too small. You may encounter bad performance!", arg_transfer_block_size.value()); } else { LOG_TRACE("Transfer block size: {}", arg_transfer_block_size.value()); } return true; } //============================================================================== // struct xcpd_program_options //============================================================================== void xcp::xcpd_program_options::add_options(CLI::App& app) { base_program_options::add_options(app); CLI::Option* opt_portal = app.add_option( "-P,-p,--portal", this->arg_portal, "Server portal endpoint to bind and listen"); opt_portal->type_name("<endpoint>"); CLI::Option* opt_channel = app.add_option( "-C,--channel", this->arg_channels, "Server channels to bind and listen for transportation"); opt_channel->type_name("<endpoint>"); } bool xcp::xcpd_program_options::post_process() { if (!base_program_options::post_process()) { return false; } //---------------------------------------------------------------- // arg_portal //---------------------------------------------------------------- if (!arg_portal.has_value()) { arg_portal = infra::tcp_endpoint(); arg_portal->host = program_options_defaults::SERVER_PORTAL_HOST; LOG_INFO("Server portal is not specified, use default host {}", program_options_defaults::SERVER_PORTAL_HOST); } if (arg_portal->port.has_value()) { if (arg_portal->port.value() == 0) { LOG_WARN("Server portal binds to a random port"); } else { LOG_TRACE("Server portal binds to port {}", arg_portal->port.value()); } } else { // !arg_portal->port.has_value() arg_portal->port = program_options_defaults::SERVER_PORTAL_PORT; LOG_TRACE("Server portal binds to default port {}", arg_portal->port.value()); } LOG_INFO("Server portal endpoint: {}", arg_portal->to_string()); if (!arg_portal->resolve()) { LOG_ERROR("Can't resolve specified portal: {}", arg_portal->to_string()); return false; } else { for (const infra::tcp_sockaddr& addr : arg_portal->resolved_sockaddrs) { LOG_DEBUG(" Candidate server portal endpoint: {}", addr.to_string()); } } //---------------------------------------------------------------- // arg_channels //---------------------------------------------------------------- total_channel_repeats_count = 0; if (arg_channels.empty()) { // Reuse portal as channel // Default arg_portal->repeats if not specified by user if (!arg_portal->repeats.has_value()) { arg_portal->repeats = program_options_defaults::SERVER_CHANNEL_REPEATS; } total_channel_repeats_count += arg_portal->repeats.value(); LOG_INFO("Server channels are not specified, reuse portal as channel: {}", arg_portal->to_string()); } for (infra::tcp_endpoint& ep : arg_channels) { if (!ep.port.has_value()) { ep.port = static_cast<uint16_t>(0); } if (!ep.repeats.has_value()) { ep.repeats = static_cast<size_t>(1); } ASSERT(ep.repeats.value() > 0); LOG_INFO("Server channel: {}", ep.to_string()); if (!ep.resolve()) { LOG_ERROR("Can't resolve specified channel: {}", ep.to_string()); return false; } else { for (const infra::tcp_sockaddr& addr : ep.resolved_sockaddrs) { LOG_DEBUG(" Candidate server channel endpoint: {}", addr.to_string()); } } total_channel_repeats_count += ep.repeats.value(); } LOG_INFO("Total server channels (including repeats): {}", total_channel_repeats_count); return true; }
33.501134
690
0.500271
WenbinHou
499b39c54b8f164f0888e1304f52c52505ed1694
3,169
cpp
C++
include/lak/stream_util.cpp
LAK132/NetworkMaker
0ad1ba2488d80e8bba0a710e5d9984d7c5cc0739
[ "MIT" ]
null
null
null
include/lak/stream_util.cpp
LAK132/NetworkMaker
0ad1ba2488d80e8bba0a710e5d9984d7c5cc0739
[ "MIT" ]
null
null
null
include/lak/stream_util.cpp
LAK132/NetworkMaker
0ad1ba2488d80e8bba0a710e5d9984d7c5cc0739
[ "MIT" ]
1
2020-08-16T16:27:58.000Z
2020-08-16T16:27:58.000Z
/* MIT License Copyright (c) 2018 Lucas Kleiss (LAK132) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "stream_util.h" void readFile(const string& src, string* dst) { *dst = ""; ifstream strm(src.c_str(), std::ios::binary|ifstream::in); if(!strm.is_open()) { LERRLOG("Failed to open file " << src.c_str() << endl); return; } streampos start = strm.tellg(); size_t size = 0; string str = ""; str += EOF; skipOneS(strm, str) ++size; // I'm not sorry strm.clear(); strm.seekg(start); dst->reserve(size); for(char c = strm.get(); strm >> c;) *dst += c; } void readFile(string&& src, string* dst) { readFile(src, dst); } string readFile(const string& src) { string str; readFile(src, &str); return str; } string readFile(string&& src) { string str; readFile(src, &str); return str; } // string getString(istream& strm, const char terminator) // { // LDEBUG(std::endl); // string str = ""; // LDEBUG(std::endl); // char c = strm.get(); // LDEBUG(std::endl); // while((c = strm.get()) != terminator && strm.good()) // { // LDEBUG(c << std::endl); // if(c == '\\') // { // switch(strm.get()) // { // case '\\': str += '\\'; break; // case '\'': str += '\''; break; // case '\"': str += '\"'; break; // // case 'b': str += "\\b"; break; // case 'f': str += '\f'; break; // case 'n': str += '\n'; break; // case 'r': str += '\r'; break; // case 't': str += '\t'; break; // case 'u': { // str += "\\u"; // str += strm.get(); // str += strm.get(); // str += strm.get(); // str += strm.get(); // } break; // default: { // str += '\\'; // str += strm.get(); // } break; // } // } // else // str += c; // } // return str; // }
30.180952
78
0.532029
LAK132
499ba4b3bea193324f9df87d27b30049b4c8019e
3,121
hpp
C++
hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp
dbac/jdk8
abfce42ff6d4b8b77d622157519ecd211ba0aa8f
[ "MIT" ]
1
2020-12-26T04:52:15.000Z
2020-12-26T04:52:15.000Z
hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp
dbac/jdk8
abfce42ff6d4b8b77d622157519ecd211ba0aa8f
[ "MIT" ]
1
2020-12-26T04:57:19.000Z
2020-12-26T04:57:19.000Z
hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp
dbac/jdk8
abfce42ff6d4b8b77d622157519ecd211ba0aa8f
[ "MIT" ]
1
2021-12-06T01:13:18.000Z
2021-12-06T01:13:18.000Z
/* * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CMSOOPCLOSURES_INLINE_HPP #define SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CMSOOPCLOSURES_INLINE_HPP #include "gc_implementation/concurrentMarkSweep/cmsOopClosures.hpp" #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp" #include "oops/oop.inline.hpp" // Trim our work_queue so its length is below max at return inline void Par_MarkRefsIntoAndScanClosure::trim_queue(uint max) { while (_work_queue->size() > max) { oop newOop; if (_work_queue->pop_local(newOop)) { assert(newOop->is_oop(), "Expected an oop"); assert(_bit_map->isMarked((HeapWord*)newOop), "only grey objects on this stack"); // iterate over the oops in this oop, marking and pushing // the ones in CMS heap (i.e. in _span). newOop->oop_iterate(&_par_pushAndMarkClosure); } } } // CMSOopClosure and CMSoopsInGenClosure are duplicated, // until we get rid of OopsInGenClosure. inline void CMSOopClosure::do_klass(Klass* k) { do_klass_nv(k); } inline void CMSOopsInGenClosure::do_klass(Klass* k) { do_klass_nv(k); } inline void CMSOopClosure::do_klass_nv(Klass* k) { ClassLoaderData* cld = k->class_loader_data(); do_class_loader_data(cld); } inline void CMSOopsInGenClosure::do_klass_nv(Klass* k) { ClassLoaderData* cld = k->class_loader_data(); do_class_loader_data(cld); } inline void CMSOopClosure::do_class_loader_data(ClassLoaderData* cld) { assert(_klass_closure._oop_closure == this, "Must be"); bool claim = true; // Must claim the class loader data before processing. cld->oops_do(_klass_closure._oop_closure, &_klass_closure, claim); } inline void CMSOopsInGenClosure::do_class_loader_data(ClassLoaderData* cld) { assert(_klass_closure._oop_closure == this, "Must be"); bool claim = true; // Must claim the class loader data before processing. cld->oops_do(_klass_closure._oop_closure, &_klass_closure, claim); } #endif // SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CMSOOPCLOSURES_INLINE_HPP
40.532468
82
0.758731
dbac
499c9cd941a0da86a8ba6bfb30de25722b42eba3
42
cpp
C++
4781_candyshop/4781.cpp
YouminHa/acmicpc
dddb457a3cfb03df34db0ed07680ac1a7be6cdd4
[ "MIT" ]
null
null
null
4781_candyshop/4781.cpp
YouminHa/acmicpc
dddb457a3cfb03df34db0ed07680ac1a7be6cdd4
[ "MIT" ]
null
null
null
4781_candyshop/4781.cpp
YouminHa/acmicpc
dddb457a3cfb03df34db0ed07680ac1a7be6cdd4
[ "MIT" ]
null
null
null
#include <stdio.h> #include <iostream>
7
19
0.666667
YouminHa
499d07f1b188017bf2b057e9f410fe5336e1068a
4,602
cpp
C++
src/world/chunk.cpp
AlexDiru/minecraft-weekend
8ddbef27f8501bff306c83ae11fff971cb3bb47a
[ "MIT" ]
null
null
null
src/world/chunk.cpp
AlexDiru/minecraft-weekend
8ddbef27f8501bff306c83ae11fff971cb3bb47a
[ "MIT" ]
null
null
null
src/world/chunk.cpp
AlexDiru/minecraft-weekend
8ddbef27f8501bff306c83ae11fff971cb3bb47a
[ "MIT" ]
null
null
null
#include "../state.h" #include "chunk.h" #include "world.h" #include "light.h" void chunk_init(struct Chunk *self, struct World *world, ivec3s offset) { memset(self, 0, sizeof(struct Chunk)); self->world = world; self->offset = offset; self->position = glms_ivec3_mul(offset, CHUNK_SIZE); self->data = (u64*)calloc(1, CHUNK_VOLUME * sizeof(u64)); self->mesh = chunkmesh_create(self); } void chunk_destroy(struct Chunk *self) { free(self->data); chunkmesh_destroy(self->mesh); } // returns the chunks that border the specified chunk position static void chunk_get_bordering_chunks(struct Chunk *self, ivec3s pos, struct Chunk *dest[6]) { size_t i = 0; if (pos.x == 0) { dest[i++] = world_get_chunk(self->world, glms_ivec3_add(self->offset, (ivec3s) {{ -1, 0, 0 }})); } if (pos.y == 0) { dest[i++] = world_get_chunk(self->world, glms_ivec3_add(self->offset, (ivec3s) {{ 0, -1, 0 }})); } if (pos.z == 0) { dest[i++] = world_get_chunk(self->world, glms_ivec3_add(self->offset, (ivec3s) {{ 0, 0, -1 }})); } if (pos.x == (CHUNK_SIZE.x - 1)) { dest[i++] = world_get_chunk(self->world, glms_ivec3_add(self->offset, (ivec3s) {{ 1, 0, 0 }})); } if (pos.x == (CHUNK_SIZE.y - 1)) { dest[i++] = world_get_chunk(self->world, glms_ivec3_add(self->offset, (ivec3s) {{ 0, 1, 0 }})); } if (pos.z == (CHUNK_SIZE.z - 1)) { dest[i++] = world_get_chunk(self->world, glms_ivec3_add(self->offset, (ivec3s) {{ 0, 0, 1 }})); } } // MUST be run once a chunk has completed generating void chunk_after_generate(Chunk *self) { chunk_heightmap_recalculate(self); light_apply(self); } // MUST be run after data inside of a chunk is modified void chunk_on_modify( Chunk *self, ivec3s pos, u64 prev, u64 data) { self->mesh->flags.dirty = true; enum BlockId prev_block = chunk_data_to_block(prev), data_block = chunk_data_to_block(data); u32 prev_light = chunk_data_to_light(prev), light = chunk_data_to_light(data); struct Block block_p = BLOCKS[prev_block], block = BLOCKS[data_block]; if (data_block != prev_block) { ivec3s pos_w = glms_ivec3_add(self->position, pos); if (block_p.can_emit_light) { light_remove(self->world, pos_w); } if (block.can_emit_light) { torchlight_add(self->world, pos_w, block.get_torchlight(self->world, pos_w)); } if (!self->flags.generating) { if (block.transparent) { world_heightmap_recalculate(self->world, (ivec2s) {{ pos_w.x, pos_w.z }}); // propagate lighting through this block light_update(self->world, pos_w); } else { world_heightmap_update(self->world, pos_w); // remove light at this block light_remove(self->world, pos_w); } } self->count += (data_block == AIR ? -1 : 1); } self->flags.empty = self->count == 0; // mark any chunks that could have been affected as dirty if ((data_block != prev_block || light != prev_light) && chunk_on_bounds(pos)) { struct Chunk *neighbors[6] = { NULL }; chunk_get_bordering_chunks(self, pos, neighbors); for (size_t i = 0; i < 6; i++) { if (neighbors[i] != NULL) { neighbors[i]->mesh->flags.dirty = true; } } } } void chunk_prepare(Chunk *self) { if (self->flags.empty) { return; } chunkmesh_prepare_render(self->mesh); } void chunk_render(Chunk *self, enum ChunkMeshPart part) { if (self->flags.empty) { return; } chunkmesh_render(self->mesh, part); } void chunk_update(Chunk *self) { // Depth sort the transparent mesh if // (1) the player is inside of this chunk and their block position changed // (2) the player has moved chunks AND this chunk is close PositionComponent *c_position = self->world->componentManager->getPositionComponent(self->world->entity_view); bool within_distance = glms_ivec3_norm(glms_ivec3_sub(self->offset, c_position->offset)) < 4; self->mesh->flags.depth_sort = (!ivec3scmp(self->offset, c_position->offset) && c_position->block_changed) || (c_position->offset_changed && within_distance); // Persist depth sort data if the player is within depth sort distance of this chunk chunkmesh_set_persist(self->mesh, within_distance); } void chunk_tick(Chunk *self) { }
31.520548
114
0.611691
AlexDiru
49a7dbc2bdc7d142b3de9ff2cfce31e67f3a35fd
645
cpp
C++
Source/mods.cpp
HaikuArchives/Rez
db5e7e1775a379e1e54bc17012047d92ec782202
[ "BSD-4-Clause" ]
1
2016-09-12T19:04:30.000Z
2016-09-12T19:04:30.000Z
Source/mods.cpp
HaikuArchives/Rez
db5e7e1775a379e1e54bc17012047d92ec782202
[ "BSD-4-Clause" ]
null
null
null
Source/mods.cpp
HaikuArchives/Rez
db5e7e1775a379e1e54bc17012047d92ec782202
[ "BSD-4-Clause" ]
null
null
null
#include "mods.h" #include <cstdio> /************************************************************************* * Modifications to the standard REZ distribution. * Copyright (c) 2000, Tim Vernum * This code may be freely used for any purpose *************************************************************************/ bool gListDepend = false ; bool gParseOnly = false ; void DependFile( const char * file ) { if( gListDepend ) { printf( "\t%s \\\n", file ) ; } } void StartDepend( const char * out ) { if( gListDepend ) { printf( "%s : \\\n", out ) ; } } void EndDepend( void ) { if( gListDepend ) { printf( "\n" ) ; } }
17.432432
75
0.472868
HaikuArchives
49acf651e55490e269962b2b747a489017641961
687
cc
C++
chrome/browser/component_updater/component_updater_utils.cc
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-01-07T18:51:03.000Z
2021-01-07T18:51:03.000Z
chrome/browser/component_updater/component_updater_utils.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/component_updater/component_updater_utils.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/component_updater/component_updater_utils.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "build/build_config.h" #if defined(OS_WIN) #include "chrome/installer/util/install_util.h" #endif // OS_WIN namespace component_updater { bool IsPerUserInstall() { #if defined(OS_WIN) base::FilePath exe_path; PathService::Get(base::FILE_EXE, &exe_path); return InstallUtil::IsPerUserInstall(exe_path); #else return true; #endif } } // namespace component_updater
25.444444
73
0.767103
xzhan96
49adab898428491e17f74e777ed5d051fec0f9bb
1,300
cpp
C++
Algorithms/Sorting/quick_sort.cpp
WajahatSiddiqui/workspace
7c6172a76d7cd178ea0c0cb9767ceaaed783545a
[ "Apache-2.0" ]
1
2021-03-19T10:57:21.000Z
2021-03-19T10:57:21.000Z
Algorithms/Sorting/quick_sort.cpp
WajahatSiddiqui/Datastructures-and-Algorithms
7c6172a76d7cd178ea0c0cb9767ceaaed783545a
[ "Apache-2.0" ]
1
2015-03-15T17:49:52.000Z
2015-03-15T17:51:38.000Z
Algorithms/Sorting/quick_sort.cpp
WajahatSiddiqui/Datastructures-and-Algorithms
7c6172a76d7cd178ea0c0cb9767ceaaed783545a
[ "Apache-2.0" ]
null
null
null
#include<iostream> using namespace std; // Best case: O(nlogn) // Avg. case: O(nlogn) // Worst case: O(n^2) void quick_sort(int A[], int low, int high); int partition(int A[], int low, int high); int main() { int A[] = {5, 6, 8, 1, -1, 0, 11, 100, -5, 0, 1, 0, 6, 1, 2, 3, 5, 10000}; int size = sizeof(A)/sizeof(int); cout<<"Size = "<<size<<endl; cout<<"Input Array: \n"; for (int i = 0; i < size; i++) { cout<<A[i]<<" "; } quick_sort(A, 0, size-1); cout<<"\nQuick Sorted Array: \n"; for (int i = 0; i < size; i++) { cout<<A[i]<<" "; } cout<<endl; return 0; } void swap(int *n1, int *n2) { int tmp = *n1; *n1 = *n2; *n2 = tmp; } // low represents starting index // high represents size-1, ending index void quick_sort(int A[], int low, int high) { if (low < high) { // Partition the array based on some pivot int pivot = partition(A, low, high); // Decompose and sort recursively quick_sort(A, low, pivot-1); quick_sort(A, pivot+1, high); } } int partition(int A[], int low, int high) { int pivot = A[high]; int i = low - 1; for (int j = low; j <= high-1; j++) { if (A[j] <= pivot) { i++; swap(&A[i], &A[j]); } } swap(&A[i+1], &A[high]); return i+1; }
22.413793
75
0.520769
WajahatSiddiqui
49b39f86e698f389bf7e606e73ce28ee95f020c2
487
hpp
C++
SoftRender/Common.hpp
pw1316/SoftRender
da4a87da2aab1234543a48524a8274d6f5550652
[ "MIT" ]
null
null
null
SoftRender/Common.hpp
pw1316/SoftRender
da4a87da2aab1234543a48524a8274d6f5550652
[ "MIT" ]
null
null
null
SoftRender/Common.hpp
pw1316/SoftRender
da4a87da2aab1234543a48524a8274d6f5550652
[ "MIT" ]
null
null
null
#pragma once #include "stdafx.h" inline PWfloat quickInvSqrt(PWfloat number) { PWlong i; PWfloat x2, y; const PWfloat threehalfs = 1.5f; x2 = number * 0.5f; y = number; i = *(PWlong *)&y;// evil floating point bit level hacking i = 0x5f3759df - (i >> 1);// what the fuck? y = *(PWlong *)&i; y = y * (threehalfs - (x2 * y * y)); // 1st iteration y = y * (threehalfs - (x2 * y * y)); // 2nd iteration, this can be removed return 1.0f / y; }
28.647059
80
0.566735
pw1316
49b41afb9d64fe942c0e7c9d0cfbf4b64821414a
358
cpp
C++
Graph/main.cpp
yanelox/ilab_2year
4597b2fbc498a816368101283d2749ac7bbf670a
[ "MIT" ]
null
null
null
Graph/main.cpp
yanelox/ilab_2year
4597b2fbc498a816368101283d2749ac7bbf670a
[ "MIT" ]
null
null
null
Graph/main.cpp
yanelox/ilab_2year
4597b2fbc498a816368101283d2749ac7bbf670a
[ "MIT" ]
1
2021-10-11T19:18:37.000Z
2021-10-11T19:18:37.000Z
#include "graph.cpp" int main () { graph::graph_ <int> G {}; if (G.input() == 0) { std::cout << "Incorrect input\n"; return 0; } // std::cout << G; int res = G.colorize(); // G.recolorize(); if (res == 1) G.print_colors(std::cout); else std::cout << "Error: non-bipartite graph\n"; }
14.916667
52
0.472067
yanelox
49b4f616bd2efeb24568570d3030bb7c4c70f1ec
6,582
cpp
C++
plaidml/bridge/openvino/plaidml_util.cpp
hfp/plaidml
c86852a910e68181781b3045f5a306d2f41a775f
[ "Apache-2.0" ]
null
null
null
plaidml/bridge/openvino/plaidml_util.cpp
hfp/plaidml
c86852a910e68181781b3045f5a306d2f41a775f
[ "Apache-2.0" ]
65
2020-08-24T07:41:09.000Z
2021-07-19T09:13:49.000Z
plaidml/bridge/openvino/plaidml_util.cpp
Flex-plaidml-team/plaidml
1070411a87b3eb3d94674d4d041ed904be3e7d87
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "plaidml_util.hpp" #include "ngraph/validation_util.hpp" #include "plaidml/edsl/edsl.h" using namespace plaidml; // NOLINT[build/namespaces] using namespace InferenceEngine; // NOLINT[build/namespaces] namespace PlaidMLPlugin { ngraph::AxisSet get_axis_set_from_constant_operand(size_t operand_idx, ngraph::Node* layer, size_t rank_override) { auto* axis_ngraph_op = ngraph::as_type<ngraph::op::Constant>(layer->get_input_node_ptr(operand_idx)); if (axis_ngraph_op) { auto const_data = axis_ngraph_op->cast_vector<int64_t>(); auto input_rank = layer->get_input_partial_shape(0).rank(); if (rank_override > 0) { // If a programmer has specifically set the rank, use that value instead. // This is for cases like unsqueeze, where axes aree given relative to a destination tensor of higher rank than // the input tensor input_rank = rank_override; } auto normalized_axes = ngraph::normalize_axes(layer->get_friendly_name(), const_data, input_rank); return ngraph::AxisSet{normalized_axes}; } else { THROW_IE_EXCEPTION << "Dynamic axis not currently supported by PlaidML plugin"; } } ngraph::AxisVector get_axis_vector_from_constant_operand(size_t operand_idx, ngraph::Node* layer) { auto* axis_ngraph_op = ngraph::as_type<ngraph::op::Constant>(layer->get_input_node_ptr(operand_idx)); if (axis_ngraph_op) { auto const_data = axis_ngraph_op->cast_vector<int64_t>(); auto input_rank = layer->get_input_partial_shape(0).rank(); auto normalized_axes = ngraph::normalize_axes(layer->get_friendly_name(), const_data, input_rank); return ngraph::AxisVector{normalized_axes}; } else { THROW_IE_EXCEPTION << "Dynamic axis not currently supported by PlaidML plugin"; } } plaidml::DType to_plaidml(const InferenceEngine::Precision& precision) { switch (precision) { case InferenceEngine::Precision::FP16: return plaidml::DType::FLOAT16; case InferenceEngine::Precision::FP32: return plaidml::DType::FLOAT32; case InferenceEngine::Precision::I8: return plaidml::DType::INT8; case InferenceEngine::Precision::I16: return plaidml::DType::INT16; case InferenceEngine::Precision::I32: return plaidml::DType::INT32; case InferenceEngine::Precision::I64: return plaidml::DType::INT64; case InferenceEngine::Precision::U8: return plaidml::DType::UINT8; case InferenceEngine::Precision::U16: return plaidml::DType::UINT16; case InferenceEngine::Precision::U32: return plaidml::DType::UINT8; case InferenceEngine::Precision::U64: return plaidml::DType::UINT16; case InferenceEngine::Precision::BOOL: return plaidml::DType::BOOLEAN; default: // TODO: Verify these are the unsupported types THROW_IE_EXCEPTION << "Unsupported element type"; } } plaidml::DType to_plaidml(const ngraph::element::Type& type) { switch (type) { case ngraph::element::Type_t::f16: return plaidml::DType::FLOAT16; case ngraph::element::Type_t::f32: return plaidml::DType::FLOAT32; case ngraph::element::Type_t::f64: return plaidml::DType::FLOAT64; case ngraph::element::Type_t::i8: return plaidml::DType::INT8; case ngraph::element::Type_t::i16: return plaidml::DType::INT16; case ngraph::element::Type_t::i32: return plaidml::DType::INT32; case ngraph::element::Type_t::i64: return plaidml::DType::INT64; case ngraph::element::Type_t::u8: return plaidml::DType::UINT8; case ngraph::element::Type_t::u16: return plaidml::DType::UINT16; case ngraph::element::Type_t::u32: return plaidml::DType::UINT32; case ngraph::element::Type_t::u64: return plaidml::DType::UINT64; case ngraph::element::Type_t::boolean: return plaidml::DType::BOOLEAN; case ngraph::element::Type_t::u1: case ngraph::element::Type_t::bf16: case ngraph::element::Type_t::undefined: case ngraph::element::Type_t::dynamic: default: // TODO: Verify these are the unsupported types THROW_IE_EXCEPTION << "Unsupported element type"; } } plaidml::op::AutoPadMode to_plaidml(const ngraph::op::PadType& type) { switch (type) { case ngraph::op::PadType::EXPLICIT: return plaidml::op::AutoPadMode::EXPLICIT; case ngraph::op::PadType::SAME_LOWER: return plaidml::op::AutoPadMode::SAME_LOWER; case ngraph::op::PadType::SAME_UPPER: return plaidml::op::AutoPadMode::SAME_UPPER; case ngraph::op::PadType::VALID: return plaidml::op::AutoPadMode::VALID; default: THROW_IE_EXCEPTION << "Unsupported autopad type"; } } plaidml::op::PadMode to_plaidml(const ngraph::op::PadMode& type) { switch (type) { case ngraph::op::PadMode::CONSTANT: return plaidml::op::PadMode::CONSTANT; case ngraph::op::PadMode::EDGE: return plaidml::op::PadMode::EDGE; case ngraph::op::PadMode::REFLECT: return plaidml::op::PadMode::REFLECT; case ngraph::op::PadMode::SYMMETRIC: return plaidml::op::PadMode::SYMMETRIC; default: THROW_IE_EXCEPTION << "Unsupported autopad type"; } } ngraph::Shape get_shape_from_constant_operand(size_t operand_idx, ngraph::Node* layer) { auto* shape_ngraph_op = ngraph::as_type<ngraph::op::Constant>(layer->get_input_node_ptr(operand_idx)); if (shape_ngraph_op) { return shape_ngraph_op->get_shape_val(); } else { THROW_IE_EXCEPTION << "Dynamic shapes not currently supported by PlaidML plugin"; } } ngraph::Coordinate get_coords_from_constant_operand(size_t operand_idx, ngraph::Node* layer) { auto* coord_ngraph_op = ngraph::as_type<ngraph::op::Constant>(layer->get_input_node_ptr(operand_idx)); if (coord_ngraph_op) { return coord_ngraph_op->get_coordinate_val(); } else { THROW_IE_EXCEPTION << "Dynamic coordinates not currently supported by PlaidML plugin"; } } edsl::Tensor clip_activation(const std::string& func_name, bool should_clip, float clip, const edsl::Tensor& T) { edsl::Tensor T_clipped; if (should_clip) { T_clipped = op::clip(T, edsl::Tensor(-clip), edsl::Tensor(clip)); } else { T_clipped = T; } if (func_name == "relu") { return op::relu(T_clipped); } else if (func_name == "sigmoid") { return op::sigmoid(T_clipped); } else if (func_name == "tanh") { return edsl::tanh(T_clipped); } else { THROW_IE_EXCEPTION << "Unsupported activation function"; } } } // namespace PlaidMLPlugin
36.977528
117
0.703434
hfp
49b6698b30758675eaa155abbf452b5e28098270
4,303
cpp
C++
src/SgTShaderProc.cpp
stephen-hqxu/SglToolkit
cce526b2392dc9470db6182340f79febb5118a94
[ "MIT" ]
null
null
null
src/SgTShaderProc.cpp
stephen-hqxu/SglToolkit
cce526b2392dc9470db6182340f79febb5118a94
[ "MIT" ]
null
null
null
src/SgTShaderProc.cpp
stephen-hqxu/SglToolkit
cce526b2392dc9470db6182340f79febb5118a94
[ "MIT" ]
null
null
null
#include <SglToolkit/SgTShaderProc.h> using namespace SglToolkit; void SgTShaderProc::addShader(const GLenum type, const SgTstring path) { //Determine which shader is that int handleIndex = 1; switch (type) { case GL_VERTEX_SHADER: handleIndex = 1; break; case GL_TESS_CONTROL_SHADER: handleIndex = 2; break; case GL_TESS_EVALUATION_SHADER: handleIndex = 3; break; case GL_GEOMETRY_SHADER: handleIndex = 4; break; case GL_FRAGMENT_SHADER: handleIndex = 5; break; case GL_COMPUTE_SHADER: handleIndex = 6; break; default: throw "InvalidGLenumException"; break; } //Start working //Read the code from file const SgTstring scode = SgTShaderProc::readCode(path); const char* code = scode.c_str(); //We don't need to worry about whether the file exits or not since the readCode function has done that //Generating shader this->shaderHandle[handleIndex] = glCreateShader(type); this->shaderused[handleIndex - 1] = true; //adding the source file glShaderSource(this->shaderHandle[handleIndex], 1, &code, NULL); //Finished } SgTShaderStatus SgTShaderProc::linkShader(GLchar* log, const int bufferSize, SgTProgramPara arg) { if (this->shaderHandle[0] == 0) {//check if we have a programe //create the programe this->shaderHandle[0] = glCreateProgram(); } //Compile all shaders that have been created for (int i = 1; i < 7; i++) {//shader start from 1 if (this->shaderused[i - 1]) { //if shader exists //compile it glCompileShader(this->shaderHandle[i]); //check for error if (!this->debugCompile(this->shaderHandle[i], true, log, bufferSize)) {//if error occurs //return to user which shader causes the error return this->VERTEX_SHADER_ERR + (i - 1);//this will effectively output the shader we are looping } //No error? attach shaders to programe glAttachShader(this->shaderHandle[0], this->shaderHandle[i]); } } //user-set program parameter if (arg != NULL) {//meaning user has set the program parameter (*arg)(this->getP()); } //We have attached all shaders, now link the programe glLinkProgram(this->shaderHandle[0]); //check for error if (!this->debugCompile(this->shaderHandle[0], false, log, bufferSize)) { return this->PROGRAME_LINKING_ERR; } //everything works fine return this->OK; //we will delete the shader source when the class got destructed just in case we need to re-attach it } void SgTShaderProc::deleteShader() { glUseProgram(0); if (this->shaderHandle[0] != 0) {//checking for programe existance //detach all shader and delete them for (int i = 1; i < 7; i++) { if (this->shaderused[i - 1]) {//shader exists glDetachShader(this->shaderHandle[0], this->shaderHandle[i]); glDeleteShader(this->shaderHandle[i]); this->shaderused[i - 1] = false; this->shaderHandle[i] = 0; } } //delete the programe glDeleteProgram(this->shaderHandle[0]); this->shaderHandle[0] = 0;//clear up the pointer such that it can be reused } } const SgTstring SgTShaderProc::readCode(const SgTstring Path) { //return value SgTstring code; //create the file stream std::fstream file; std::stringstream stream; file.open(Path, std::ios_base::in); file.exceptions(std::fstream::failbit | std::fstream::badbit);//make sure there is no exceptions stream << file.rdbuf(); code = stream.str(); //finishing up file.close(); return code; } const bool SgTShaderProc::debugCompile(GLuint shader, bool isShader, GLchar* log, const int bufferSize) { //variables GLint success; if (isShader) { glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(shader, bufferSize, NULL, log); return false; } } else { glGetProgramiv(shader, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shader, bufferSize, NULL, log); return false; } } return true; } const int SgTShaderProc::getP() const { return this->shaderHandle[0]; } const int SgTShaderProc::getVS() const { return this->shaderHandle[1]; } const int SgTShaderProc::getTCS() const { return this->shaderHandle[2]; } const int SgTShaderProc::getTES() const { return this->shaderHandle[3]; } const int SgTShaderProc::getGS() const { return this->shaderHandle[4]; } const int SgTShaderProc::getFS() const { return this->shaderHandle[5]; }
26.89375
105
0.711132
stephen-hqxu
49b80ce7d44f336de85baa6acf8c266c02a7e8a9
309
hpp
C++
CLASS/class_inheritance_2/Child.hpp
StanLepunK/CPP_basics
72b8e72b84adc31bdfad4479d5133defb9575e54
[ "MIT" ]
null
null
null
CLASS/class_inheritance_2/Child.hpp
StanLepunK/CPP_basics
72b8e72b84adc31bdfad4479d5133defb9575e54
[ "MIT" ]
null
null
null
CLASS/class_inheritance_2/Child.hpp
StanLepunK/CPP_basics
72b8e72b84adc31bdfad4479d5133defb9575e54
[ "MIT" ]
null
null
null
#ifndef CHILD_H # define CHILD_H #include "Mother.hpp" class Child : public Mother { private: std::string name; public: Child(); ~Child(); Child(float const x, float const y, std::string const name); std::string get_name() const; void static_talk(); virtual void virtual_talk(); }; #endif
15.45
62
0.679612
StanLepunK
49ba8348d2d36c463bd163cb89fee32926da201a
401
hpp
C++
include/dotto/debug.hpp
mitsukaki/dotto
ebea72447e854c9beff676fe609d998a3cb0b3ea
[ "CC0-1.0" ]
4
2018-03-05T22:51:40.000Z
2018-03-11T00:54:38.000Z
include/dotto/debug.hpp
mitsukaki/dotto
ebea72447e854c9beff676fe609d998a3cb0b3ea
[ "CC0-1.0" ]
null
null
null
include/dotto/debug.hpp
mitsukaki/dotto
ebea72447e854c9beff676fe609d998a3cb0b3ea
[ "CC0-1.0" ]
1
2019-09-14T19:44:14.000Z
2019-09-14T19:44:14.000Z
#pragma once #include <string> #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_ttf.h> #include <dotto/io.hpp> class debug { private: TTF_Font* debug_font; SDL_Rect fps_text_rect; SDL_Surface* fps_text_surface; SDL_Texture* fps_text_texture; public: debug(); ~debug(); void render(SDL_Renderer* renderer); void init(); float fps; };
12.151515
40
0.665835
mitsukaki
49bc2b5de44ea8cffd8978e2372400df92994655
590
cpp
C++
hackerrank/problems/GameOfThrones-I.cpp
joaquinmd93/competitive-programming
681424abd777cc0a3059e1ee66ae2cee958178da
[ "MIT" ]
1
2020-10-08T19:28:40.000Z
2020-10-08T19:28:40.000Z
hackerrank/problems/GameOfThrones-I.cpp
joaquinmd93/competitive-programming
681424abd777cc0a3059e1ee66ae2cee958178da
[ "MIT" ]
null
null
null
hackerrank/problems/GameOfThrones-I.cpp
joaquinmd93/competitive-programming
681424abd777cc0a3059e1ee66ae2cee958178da
[ "MIT" ]
1
2020-10-24T02:32:27.000Z
2020-10-24T02:32:27.000Z
#include<bits/stdc++.h> using namespace std; int main() { string s; cin >> s; int n = s.size(); map<char, int> reps; for (int i=0; i<n; ++i) { ++reps[s[i]]; } int odd_reps=0; for (auto let: reps) { if (let.second % 2 != 0) ++odd_reps; } if (n % 2 == 0) { if (odd_reps == 0) cout << "YES" << endl; else cout << "NO" << endl; } else { if (odd_reps == 1) cout << "YES" << endl; else cout << "NO" << endl; } return 0; }
21.071429
37
0.383051
joaquinmd93
49bc8fdc7a30207df70b9f88b807df3a38941b67
483
hpp
C++
inc/concept/detail/unuse.hpp
matrixjoeq/concepts
d9bac8343e44c62f22913ec41ac0856b767bedc4
[ "MIT" ]
null
null
null
inc/concept/detail/unuse.hpp
matrixjoeq/concepts
d9bac8343e44c62f22913ec41ac0856b767bedc4
[ "MIT" ]
null
null
null
inc/concept/detail/unuse.hpp
matrixjoeq/concepts
d9bac8343e44c62f22913ec41ac0856b767bedc4
[ "MIT" ]
null
null
null
/** @file */ #ifndef __STL_CONCEPT_DETAIL_UNUSE_HPP__ #define __STL_CONCEPT_DETAIL_UNUSE_HPP__ namespace stl_concept { namespace __detail { /// @cond DEV /** * @brief Ignore unused object. * @tparam T - object type */ template <class T> inline void __unuse(T&&) {} /** * @brief Ignore unused type. * @tparam T - object type */ template <class T> struct __Unuse {}; /// @endcond } // namespace __detail } // namespace stl_concept #endif // __STL_CONCEPT_DETAIL_UNUSE_HPP__
17.25
42
0.708075
matrixjoeq
49bcaa20b70785877da6cbd54e35cdd1d42d57fe
4,031
cpp
C++
src/main/cpp/subsystems/Shooter.cpp
FIRSTTeam102/Robot2022
2a3224fd9bf7e4e9b469214fdf141a3d25d9094c
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/subsystems/Shooter.cpp
FIRSTTeam102/Robot2022
2a3224fd9bf7e4e9b469214fdf141a3d25d9094c
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/subsystems/Shooter.cpp
FIRSTTeam102/Robot2022
2a3224fd9bf7e4e9b469214fdf141a3d25d9094c
[ "BSD-3-Clause" ]
null
null
null
#include "subsystems/Shooter.h" #include "commands/Shooter/StartShooter.h" Shooter::Shooter() { SetName("Shooter"); SetSubsystem("Shooter"); using namespace ShooterConstants; // Shooter motor setup mMotor.ConfigFactoryDefault(); // resets all settings mMotor.SetInverted(true); mMotor.SetNeutralMode(ctre::phoenix::motorcontrol::NeutralMode::Coast); mMotor.SetSafetyEnabled(false); // Sensor mMotor.ConfigSelectedFeedbackSensor(FeedbackDevice::IntegratedSensor, 0, kTimeoutMs); mMotor.SetSensorPhase(true); mMotor.SetSelectedSensorPosition(0, 0, kTimeoutMs); // Peak and nominal outputs mMotor.ConfigNominalOutputForward(0, kTimeoutMs); mMotor.ConfigNominalOutputReverse(0, kTimeoutMs); mMotor.ConfigPeakOutputForward(1, kTimeoutMs); mMotor.ConfigPeakOutputReverse(-0.0, kTimeoutMs); // DO NOT run the motor backwards (worst mistake of my life) // Voltage compensation mMotor.ConfigNeutralDeadband(kDeadband, kTimeoutMs); // Closed loop gains mMotor.Config_kD(0, kD, kTimeoutMs); mMotor.Config_kF(0, kF, kTimeoutMs); mMotor.Config_kI(0, kI, kTimeoutMs); mMotor.Config_kP(0, kP, kTimeoutMs); mMotor.SelectProfileSlot(0, 0); stopShooter(); // Shuffleboard wpi::StringMap<std::shared_ptr<nt::Value>> boostSliderProperties = { std::make_pair("Min", nt::Value::MakeDouble(0.10)), std::make_pair("Max", nt::Value::MakeDouble(1.50)), std::make_pair("Block increment", nt::Value::MakeDouble(0.1)) }; frc::ShuffleboardLayout& layout = frc::Shuffleboard::GetTab("Drive").GetLayout("Shooter", frc::BuiltInLayouts::kList); mShuffleboardReady = layout.Add("Ready?", false).GetEntry(); mShuffleboardTargetRPM = layout.Add("Target RPM", 0.0).GetEntry(); mShuffleboardActualRPM = layout.Add("Actual RPM", 0.0).GetEntry(); mShuffleboardActualPercent = layout.Add("Actual %", 0.0).GetEntry(); mShuffleboardBoost = layout.AddPersistent("Boost", mBoostPercent) .WithWidget(frc::BuiltInWidgets::kNumberSlider) .WithProperties(boostSliderProperties) .GetEntry(); frc::ShuffleboardLayout& testLayout = frc::Shuffleboard::GetTab("Test").GetLayout("Shooter", frc::BuiltInLayouts::kList); mShuffleboardTestRPM = testLayout.Add("Test RPM", 0.0).GetEntry(); frc::SmartDashboard::PutData("Set test RPM", new StartShooter(this, &mShuffleboardTestRPM)); // shuffleboard doesn't seem to like commands // testLayout.Add("Set test RPM", new StartShooter(this, &mShuffleboardTestRPM)).WithWidget(frc::BuiltInWidgets::kCommand); } void Shooter::setShooter(double speed, bool useBoost) { if (useBoost) speed = speed * mBoostPercent; mMotor.Set(ControlMode::Velocity, rpmToVelocity(speed)); mTargetSpeed = speed; } void Shooter::stopShooter() { mTargetSpeed = 0.0; mMotor.Set(ControlMode::Velocity, 0.0); } void Shooter::setShooterPercent(double speed) { mMotor.Set(ControlMode::PercentOutput, speed); mTargetSpeed = speed / ShooterConstants::kMaxRpm; } void Shooter::Periodic() { mActualSpeed = mFlywheelFilter.Calculate(velocityToRpm(mMotor.GetSelectedSensorVelocity(0))); mShuffleboardReady.SetBoolean(isRunning() && (fabs(mTargetSpeed - mActualSpeed) < 75.0)); mShuffleboardActualRPM.SetDouble(mActualSpeed); mShuffleboardActualPercent.SetDouble(getActualPercent()); mBoostPercent = mShuffleboardBoost.GetDouble(mBoostPercent); // if (double newTargetSpeed = mShuffleboardTargetRPM.GetDouble(mTargetSpeed) != mTargetSpeed) setShooter(newTargetSpeed); mShuffleboardTargetRPM.SetDouble(mTargetSpeed); } void Shooter::SimulationPeriodic() { TalonFXSimCollection &motorSim(mMotor.GetSimCollection()); // Set simulation inputs motorSim.SetBusVoltage(frc::RobotController::GetInputVoltage()); mFlywheelSim.SetInputVoltage(motorSim.GetMotorOutputLeadVoltage() * 1_V); // Update simulation, standard loop time is 20ms mFlywheelSim.Update(20_ms); // Set simulated outputs frc::sim::RoboRioSim::SetVInVoltage( frc::sim::BatterySim::Calculate({mFlywheelSim.GetCurrentDraw()}) ); motorSim.SetIntegratedSensorVelocity( rpmToVelocity(mFlywheelSim.GetAngularVelocity()) ); }
36.315315
139
0.769784
FIRSTTeam102
49bfb9d091eb75a7ace1930c89cc4d2d1b3a5aae
1,830
hpp
C++
include/RED4ext/Scripting/Natives/Generated/anim/DangleConstraint_SimulationPendulum.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
42
2020-12-25T08:33:00.000Z
2022-03-22T14:47:07.000Z
include/RED4ext/Scripting/Natives/Generated/anim/DangleConstraint_SimulationPendulum.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
38
2020-12-28T22:36:06.000Z
2022-02-16T11:25:47.000Z
include/RED4ext/Scripting/Natives/Generated/anim/DangleConstraint_SimulationPendulum.hpp
jackhumbert/RED4ext.SDK
2c55eccb83beabbbe02abae7945af8efce638fca
[ "MIT" ]
20
2020-12-28T22:17:38.000Z
2022-03-22T17:19:01.000Z
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> #include <RED4ext/Common.hpp> #include <RED4ext/Scripting/Natives/Generated/Vector3.hpp> #include <RED4ext/Scripting/Natives/Generated/anim/DangleConstraint_SimulationSingleBone.hpp> #include <RED4ext/Scripting/Natives/Generated/anim/PendulumConstraintType.hpp> #include <RED4ext/Scripting/Natives/Generated/anim/PendulumProjectionType.hpp> #include <RED4ext/Scripting/Natives/Generated/anim/VectorLink.hpp> namespace RED4ext { namespace anim { struct DangleConstraint_SimulationPendulum : anim::DangleConstraint_SimulationSingleBone { static constexpr const char* NAME = "animDangleConstraint_SimulationPendulum"; static constexpr const char* ALIAS = NAME; float simulationFps; // 90 anim::PendulumConstraintType constraintType; // 94 float halfOfMaxApertureAngle; // 98 Vector3 constraintOrientation; // 9C float mass; // A8 float gravityWS; // AC float damping; // B0 float pullForceFactor; // B4 Vector3 pullForceDirectionLS; // B8 Vector3 externalForceWS; // C4 anim::VectorLink externalForceWsLink; // D0 anim::PendulumProjectionType projectionType; // F0 float collisionCapsuleRadius; // F4 float collisionCapsuleHeightExtent; // F8 float cosOfHalfXAngle; // FC float cosOfHalfYAngle; // 100 float cosOfHalfZAngle; // 104 float sinOfHalfXAngle; // 108 float sinOfHalfYAngle; // 10C float sinOfHalfZAngle; // 110 float cosOfHalfMaxApertureAngle; // 114 float cosOfHalfOfHalfMaxApertureAngle; // 118 float sinOfHalfOfHalfMaxApertureAngle; // 11C float invertedMass; // 120 uint8_t unk124[0x188 - 0x124]; // 124 }; RED4EXT_ASSERT_SIZE(DangleConstraint_SimulationPendulum, 0x188); } // namespace anim } // namespace RED4ext
36.6
93
0.757923
jackhumbert
49c35d5da78523cf5f60013d0b0803761665d2e9
1,548
cpp
C++
src/Parse/Parser.cpp
artagnon/rhine
ca4ec684162838f4cb13d9d29ef9e4aedbc268dd
[ "MIT" ]
234
2015-01-02T18:32:50.000Z
2022-02-03T19:41:33.000Z
src/Parse/Parser.cpp
artagnon/rhine
ca4ec684162838f4cb13d9d29ef9e4aedbc268dd
[ "MIT" ]
7
2015-02-16T15:02:54.000Z
2016-05-26T07:46:02.000Z
src/Parse/Parser.cpp
artagnon/rhine
ca4ec684162838f4cb13d9d29ef9e4aedbc268dd
[ "MIT" ]
13
2015-02-16T13:37:12.000Z
2020-12-12T04:18:43.000Z
#include "rhine/Parse/ParseDriver.hpp" #include "rhine/Parse/Parser.hpp" #include "rhine/Parse/Lexer.hpp" #include "rhine/Diagnostic/Diagnostic.hpp" #include "rhine/IR/Context.hpp" #include "rhine/IR/Module.hpp" #include <vector> #define K Driver->Ctx namespace rhine { Parser::Parser(ParseDriver *Dri) : Driver(Dri), CurStatus(true) {} Parser::~Parser() {} void Parser::getTok() { LastTok = CurTok; CurTok = Driver->Lexx->lex(&CurSema, &CurLoc); LastTokWasNewlineTerminated = false; while (CurTok == NEWLINE) { LastTokWasNewlineTerminated = true; CurTok = Driver->Lexx->lex(&CurSema, &CurLoc); } } bool Parser::getTok(int Expected) { if (CurTok == Expected) { getTok(); CurLoc.Filename = Driver->InputName; CurLoc.StringStreamInput = Driver->StringStreamInput; return true; } return false; } void Parser::writeError(std::string ErrStr, bool Optional) { if (Optional) return; DiagnosticPrinter(CurLoc) << ErrStr; CurStatus = false; } bool Parser::getSemiTerm(std::string ErrFragment, bool Optional) { if (!getTok(';') && !LastTokWasNewlineTerminated && CurTok != ENDBLOCK) { auto ErrStr = "expecting ';' or newline to terminate " + ErrFragment; writeError(ErrStr, Optional); return false; } return true; } void Parser::parseToplevelForms() { getTok(); while (auto Fcn = parseFcnDecl(true)) { Driver->Root->appendFunction(Fcn); } if (CurTok != END) writeError("expected end of file"); } bool Parser::parse() { parseToplevelForms(); return CurStatus; } }
23.104478
75
0.687339
artagnon
49cb02d9b7eecd8c0fe5b389a18b8f277d0733cc
5,911
cpp
C++
Quake/Notes005/src/DIYQuake/ModelManager.cpp
amroibrahim/DIYQuake
957d4b86fc6edc3eedf0e322eafce89dc336261f
[ "MIT" ]
13
2020-12-06T20:11:40.000Z
2021-12-14T16:28:48.000Z
Quake/Notes005/src/DIYQuake/ModelManager.cpp
amroibrahim/DIYQuake
957d4b86fc6edc3eedf0e322eafce89dc336261f
[ "MIT" ]
1
2021-05-02T02:31:51.000Z
2021-05-02T17:00:49.000Z
Quake/Notes005/src/DIYQuake/ModelManager.cpp
amroibrahim/DIYQuake
957d4b86fc6edc3eedf0e322eafce89dc336261f
[ "MIT" ]
1
2020-12-17T12:17:16.000Z
2020-12-17T12:17:16.000Z
#include "ModelManager.h" #include <string> void ModelManager::Init(MemoryManager* pMemorymanager, Common* pCommon) { m_pMemorymanager = pMemorymanager; m_pCommon = pCommon; } ModelData* ModelManager::Load(char* szName) { ModelData* pModelData = nullptr; pModelData = Find(szName); return Load(pModelData); } //Load header to Known list void ModelManager::LoadHeader(char* szName) { ModelData* pModelData = Find(szName); if (pModelData->eLoadStatus == MODELLOADSTATUS::PRESENT) { if (pModelData->eType == MODELTYPE::ALIAS) { m_pMemorymanager->Check(&pModelData->pCachData); } } } void ModelManager::LoadAliasModel(ModelData* pModel, byte_t* pBuffer, char* szHunkName) { int32_t iMemoryStartOffset = m_pMemorymanager->GetLowUsed(); ModelHeader* pTempModelHeader = (ModelHeader*)pBuffer; int32_t iVersion = pTempModelHeader->iVersion; int32_t iSize = sizeof(AliasModelHeader) + sizeof(ModelHeader); std::string sloadName(szHunkName); AliasModelHeader* pAliasModelHeader = (AliasModelHeader*)m_pMemorymanager->NewLowEndNamed(iSize, sloadName); ModelHeader* pModelHeader = (ModelHeader*)((byte_t*)&pAliasModelHeader[1]); // pModel->iFlags = pTempModelHeader->iFlags; pModelHeader->iNumSkins = pTempModelHeader->iNumSkins; pModelHeader->iSkinWidth = pTempModelHeader->iSkinWidth; pModelHeader->iSkinHeight = pTempModelHeader->iSkinHeight; int32_t iNumberOfSkins = pModelHeader->iNumSkins; // Calculate the skin size in bytes int32_t iSkinSize = pModelHeader->iSkinHeight * pModelHeader->iSkinWidth; AliasSkinType* pSkinType = (AliasSkinType*)&pTempModelHeader[1]; AliasSkinDesc* pSkinDesc = (AliasSkinDesc*)m_pMemorymanager->NewLowEndNamed(iNumberOfSkins * sizeof(AliasSkinDesc), sloadName); pAliasModelHeader->SkinDescOffset = (byte_t*)pSkinDesc - (byte_t*)pAliasModelHeader; for (int i = 0; i < iNumberOfSkins; i++) { pSkinDesc[i].eSkinType = pSkinType->eSkinType; if (pSkinType->eSkinType == ALIAS_SKIN_SINGLE) { pSkinType = (AliasSkinType*)LoadAliasSkin(pSkinType + 1, &pSkinDesc[i].skin, iSkinSize, pAliasModelHeader, sloadName); } else { pSkinType = (AliasSkinType*)LoadAliasSkinGroup(pSkinType + 1, &pSkinDesc[i].skin, iSkinSize, pAliasModelHeader, sloadName); } } pModel->eType = MODELTYPE::ALIAS; int32_t iMemoryEndOffset = m_pMemorymanager->GetLowUsed(); int32_t iTotalMemorySize = iMemoryEndOffset - iMemoryStartOffset; m_pMemorymanager->m_Cache.NewNamed(&pModel->pCachData, iTotalMemorySize, sloadName); if (!pModel->pCachData.pData) return; memcpy(pModel->pCachData.pData, pAliasModelHeader, iTotalMemorySize); m_pMemorymanager->DeleteToLowMark(iMemoryStartOffset); } ModelData* ModelManager::Find(char* szName) { ModelData* pAvailable = NULL; int iCurrentModelIndex = 0; // Is the model already loaded? ModelData* pCurrentModel = m_pKnownModels; while (iCurrentModelIndex < m_iKnownModelCount) { if (!strcmp(pCurrentModel->szName, szName)) { break; } if ((pCurrentModel->eLoadStatus == MODELLOADSTATUS::UNREFERENCED) && (!pAvailable || pCurrentModel->eType != MODELTYPE::ALIAS)) { pAvailable = pCurrentModel; } ++iCurrentModelIndex; ++pCurrentModel; } if (iCurrentModelIndex == m_iKnownModelCount) { if (m_iKnownModelCount == MAX_KNOWN_MODEL) { if (pAvailable) { pCurrentModel = pAvailable; if (pCurrentModel->eType == MODELTYPE::ALIAS && m_pMemorymanager->Check(&pCurrentModel->pCachData)) { m_pMemorymanager->CacheEvict(&pCurrentModel->pCachData); } } } else { ++m_iKnownModelCount; } strcpy(pCurrentModel->szName, szName); pCurrentModel->eLoadStatus = MODELLOADSTATUS::NEEDS_LOADING; } return pCurrentModel; } void* ModelManager::ExtraData(ModelData* pModel) { void* pData; pData = m_pMemorymanager->m_Cache.Check(&pModel->pCachData); if (pData) return pData; Load(pModel); return pModel->pCachData.pData; } ModelData* ModelManager::Load(ModelData* pModel) { if (pModel->eType == MODELTYPE::ALIAS) { if (m_pMemorymanager->Check(&pModel->pCachData)) { pModel->eLoadStatus = MODELLOADSTATUS::PRESENT; return pModel; } } else { if (pModel->eLoadStatus == MODELLOADSTATUS::PRESENT) { return pModel; } } byte_t TempBuffer[1024]; // 1K on stack! Load the model temporary on stack (if they fit) byte_t* pBuffer = m_pCommon->LoadFile(pModel->szName, TempBuffer, sizeof(TempBuffer)); char szHunkName[32] = { 0 }; m_pCommon->GetFileBaseName(pModel->szName, szHunkName); //TODO: //loadmodel = pModel; pModel->eLoadStatus = MODELLOADSTATUS::PRESENT; switch (*(uint32_t*)pBuffer) { case IDPOLYHEADER: LoadAliasModel(pModel, (byte_t*)pBuffer, szHunkName); break; //case IDSPRITEHEADER: // LoadSpriteModel(pModel, pBuffer); // break; //default: // LoadBrushModel(pModel, pBuffer); // break; } return pModel; } void* ModelManager::LoadAliasSkin(void* pTempModel, int32_t* pSkinOffset, int32_t iSkinSize, AliasModelHeader* pHeader, std::string& sHunkName) { byte_t* pSkin = (byte_t*)m_pMemorymanager->NewLowEndNamed(iSkinSize, sHunkName); byte_t* pSkinInTemp = (byte_t*)pTempModel; *pSkinOffset = (byte_t*)pSkin - (byte_t*)pHeader; memcpy(pSkin, pSkinInTemp, iSkinSize); pSkinInTemp += iSkinSize; return ((void*)pSkinInTemp); } void* ModelManager::LoadAliasSkinGroup(void* pTempModel, int32_t* pSkinOffset, int32_t iSkinSize, AliasModelHeader* pHeader, std::string& sHunkName) { return nullptr; }
26.746606
148
0.682964
amroibrahim
49ccafc5c5b597763564ff02b523f969ebbb4ede
728
hpp
C++
src/utility/apply.hpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
2
2018-07-04T16:44:04.000Z
2021-01-03T07:26:27.000Z
test/utility/apply.hpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
null
null
null
test/utility/apply.hpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
null
null
null
#pragma once // std c++ headers #include <tuple> #include <array> // AMDiS includes #include "traits/basic.hpp" #include "traits/size.hpp" #include "utility/int_seq.hpp" namespace AMDiS { namespace detail { // return f(t[0], t[1], t[2], ...) template <class F, class Tuple, int... I> constexpr auto apply_impl(F&& f, Tuple&& t, AMDiS::Seq<I...>) RETURNS ( (std::forward<F>(f))(std::get<I>(std::forward<Tuple>(t))...) ) } // end namespace detail template <class F, class Tuple, int N = Size<Decay_t<Tuple>>::value> constexpr auto apply(F&& f, Tuple&& t) RETURNS ( detail::apply_impl(std::forward<F>(f), std::forward<Tuple>(t), MakeSeq_t<N>{}) ) } // end namespace AMDiS
22.060606
82
0.612637
spraetor
49cd3d84b1639b63e391495c0934cd8529efae10
1,094
hh
C++
melodic/src/stage/libstage/file_manager.hh
disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA
3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0
[ "BSD-3-Clause" ]
2
2021-07-14T12:33:55.000Z
2021-11-21T07:14:13.000Z
melodic/src/stage/libstage/file_manager.hh
disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA
3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0
[ "BSD-3-Clause" ]
null
null
null
melodic/src/stage/libstage/file_manager.hh
disorn-inc/ROS-melodic-python3-Opencv-4.1.1-CUDA
3d265bb64712e3cd7dfa0ad56d78fcdebafdb4b0
[ "BSD-3-Clause" ]
null
null
null
#ifndef _FILE_MANAGER_HH_ #define _FILE_MANAGER_HH_ #include <string> #include <vector> namespace Stg { class FileManager { private: std::string WorldsRoot; std::string stripFilename(const std::string &path); public: FileManager(); /// Return the path where the current worldfile was loaded from inline const std::string worldsRoot() const { return WorldsRoot; } /// Update the worldfile path void newWorld(const std::string &worldfile); /// Determine whether a file can be opened for reading static bool readable(const std::string &path); /** Search for a file in the current directory, in the * prefix/share/stage location, and in the locations specified by * the STAGEPATH environment variable. Returns the first match or * the original filename if not found. **/ static std::string findFile(const std::string &filename); /// Return the STAGEPATH environment variable static std::string stagePath(); /// Returns the path to the current user's home directory (or empty if not detectable): static std::string homeDirectory(); }; } #endif
26.682927
89
0.729433
disorn-inc
49d165e039d2329018c519729c723a32fecadf17
284
cpp
C++
src/Test/src/MockAudioPlayerView.cpp
don-reba/peoples-note
c22d6963846af833c55f4294dd0474e83344475d
[ "BSD-2-Clause" ]
null
null
null
src/Test/src/MockAudioPlayerView.cpp
don-reba/peoples-note
c22d6963846af833c55f4294dd0474e83344475d
[ "BSD-2-Clause" ]
null
null
null
src/Test/src/MockAudioPlayerView.cpp
don-reba/peoples-note
c22d6963846af833c55f4294dd0474e83344475d
[ "BSD-2-Clause" ]
null
null
null
#include "stdafx.h" #include "MockAudioPlayerView.h" using namespace std; void MockAudioPlayerView::Hide() { isShown = false; } void MockAudioPlayerView::SetFileName(wstring & name) { this->name = name; } void MockAudioPlayerView::Show() { isShown = true; }
14.2
54
0.676056
don-reba
49d35ea928779a62915396dd753395a313af8644
4,593
cpp
C++
source/networkrequest.cpp
KambizAsadzadeh/RestService
ca677068954cd9b6f08d42d8deabdaf07c712d93
[ "MIT" ]
7
2020-10-31T19:03:12.000Z
2022-02-04T09:50:56.000Z
source/networkrequest.cpp
KambizAsadzadeh/RestService
ca677068954cd9b6f08d42d8deabdaf07c712d93
[ "MIT" ]
null
null
null
source/networkrequest.cpp
KambizAsadzadeh/RestService
ca677068954cd9b6f08d42d8deabdaf07c712d93
[ "MIT" ]
null
null
null
#include "networkrequest.hpp" #include "core.hpp" using namespace RestService; namespace RestService { NetworkRequest::NetworkRequest() { this->result = "Unknown"; curl = curl_easy_init(); if(!curl) throw std::string ("Curl did not initialize!"); } NetworkRequest::~NetworkRequest() { cleanGlobal(); } static size_t WriteCallback2(void *contents, size_t size, size_t nmemb, void *userp) { ((std::string*)userp)->append((char*)contents, size * nmemb); return size * nmemb; } size_t NetworkRequest::WriteCallback(char *data, size_t size, size_t nmemb, std::string *buffer) { unsigned long result = 0; if (buffer != nullptr) { buffer->append(data, size * nmemb); *buffer += data; result = size * nmemb; } return result; } void NetworkRequest::clean() { curl_easy_cleanup(curl); } void NetworkRequest::cleanGlobal() { curl_global_cleanup(); } void NetworkRequest::post(const std::string& url, const std::string& query){ /* In windows, this will init the winsock stuff */ curl_global_init(CURL_GLOBAL_ALL); /* get a curl handle */ curl = curl_easy_init(); if(curl) { ctype_list = curl_slist_append(ctype_list, Core::headerType.data()); if(Core::isset(Core::headerType)) { curl_easy_setopt(curl, CURLOPT_HTTPHEADER, ctype_list); std::clog << "Content type has been set!" << std::endl; } curl_easy_setopt(curl, CURLOPT_URL, url.data()); /* Now specify the POST data */ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, query.data()); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); curl_slist_free_all(ctype_list); /* free the ctype_list again */ /* Check for errors */ if(res != CURLE_OK) std::clog << curl_easy_strerror(res) << std::endl; fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res)); clean(); setResult(readBuffer); } } void NetworkRequest::get(const std::string& url) { if(curl) { if(Core::isset(Core::headerType)) { curl_easy_setopt(curl, CURLOPT_HTTPHEADER, ctype_list); std::clog << "Content type has been set!" << std::endl; } #ifdef SKIP_PEER_VERIFICATION /* * If you want to connect to a site who isn't using a certificate that is * signed by one of the certs in the CA bundle you have, you can skip the * verification of the server's certificate. This makes the connection * A LOT LESS SECURE. * * If you have a CA cert for the server stored someplace else than in the * default bundle, then the CURLOPT_CAPATH option might come handy for * you. */ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); #endif #ifdef SKIP_HOSTNAME_VERIFICATION /* * If the site you're connecting to uses a different host name that what * they have mentioned in their server certificate's commonName (or * subjectAltName) fields, libcurl will refuse to connect. You can skip * this check, but this will make the connection less secure. */ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); #endif curl_easy_setopt(curl, CURLOPT_URL, url.data()); //curl_easy_setopt(curl, CURLOPT_HEADER, false); /* example.com is redirected, so we tell libcurl to follow redirection */ curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback2); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); /* Check for errors */ if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); std::cout << "Done!" << std::endl; setResult(readBuffer); /* always cleanup */ curl_easy_cleanup(curl); } } void NetworkRequest::setResult(const std::string& res) { ApiException apiEx; if(!res.empty()) { result = res; apiEx.setMessage(result); } else { result = "unknown"; apiEx.setMessage("Unknown"); } } std::string NetworkRequest::getResult() { return result; } }
28.52795
96
0.641193
KambizAsadzadeh
49d7b46a187c4381b134715ceb33fdbcdac3699d
1,438
cpp
C++
src/base/SimInfo.cpp
denniskb/bsim
bfe02148fc2fee7efff68b16173c626c515a49bb
[ "MIT" ]
11
2019-09-01T16:20:57.000Z
2022-01-19T08:24:06.000Z
src/base/SimInfo.cpp
denniskb/bsim
bfe02148fc2fee7efff68b16173c626c515a49bb
[ "MIT" ]
2
2020-12-14T17:27:21.000Z
2020-12-15T09:03:38.000Z
src/base/SimInfo.cpp
CRAFT-THU/BSim
479c04348312579a7ae9c118c6b987724e540f38
[ "MIT" ]
null
null
null
#include "SimInfo.h" int logFireInfo(FireInfo log, string type, string name) { string filename = name.append(".").append(type); FILE *file = fopen(filename.c_str(), "w+"); if (file == NULL) { printf("ERROR: Open file %s failed\n", filename.c_str()); return -1; } //printf("%d \n", log[type].size); //int *data = reinterpret_cast<int*>(log[type].data); //printf("%d \n", data[0]); //printf("%s \n", type.c_str()); for (int j=0; j<log[type].size; j++) { if (type == "Y") { real *data = reinterpret_cast<real*>(log[type].data); fprintf(file, "%f ", data[j]); } else { int *data = reinterpret_cast<int*>(log[type].data); fprintf(file, "%d ", data[j]); } } fprintf(file, "\n"); fflush(file); fclose(file); return 0; } int logFireInfo(FireInfo log, string type, int start, int batch, int size, string name) { string filename = name.append(".").append(type); FILE *file = fopen(filename.c_str(), "w+"); if (file == NULL) { printf("ERROR: Open file %s failed\n", filename.c_str()); return -1; } for (int i=0; i<batch; i++) { for (int j=0; j<size; j++) { if (type == "Y") { real *data = reinterpret_cast<real*>(log[type].data); fprintf(file, "%f ", data[start + i*size + j]); } else { int *data = reinterpret_cast<int*>(log[type].data); fprintf(file, "%d ", data[start + i*size + j]); } } fprintf(file, "\n"); } fflush(file); fclose(file); return 0; }
22.123077
88
0.584145
denniskb
49d8992285acc111bb590e67ebf8c19642969e2e
51
cpp
C++
module/armor/fan_armor.cpp
PaPaPR/WolfVision
4092a313491349397106e3c050a332b2a5c6e611
[ "MIT" ]
null
null
null
module/armor/fan_armor.cpp
PaPaPR/WolfVision
4092a313491349397106e3c050a332b2a5c6e611
[ "MIT" ]
null
null
null
module/armor/fan_armor.cpp
PaPaPR/WolfVision
4092a313491349397106e3c050a332b2a5c6e611
[ "MIT" ]
null
null
null
#include "fan_armor.hpp" namespace fan_armor { }
8.5
24
0.72549
PaPaPR
49da617293b4093c5c6d63da2090ee45557b3e6f
1,208
cpp
C++
Engine/OGF-Core/Core/Threads/ThreadPool.cpp
simon-bourque/OpenGameFramework
e0fed3895000a5ae244fc1ef696f4256af29865b
[ "MIT" ]
4
2017-12-31T05:24:24.000Z
2021-06-08T07:33:57.000Z
Engine/OGF-Core/Core/Threads/ThreadPool.cpp
simon-bourque/OpenGameFramework
e0fed3895000a5ae244fc1ef696f4256af29865b
[ "MIT" ]
10
2018-01-13T22:36:57.000Z
2018-06-23T20:03:03.000Z
Engine/OGF-Core/Core/Threads/ThreadPool.cpp
simon-bourque/OpenGameFramework
e0fed3895000a5ae244fc1ef696f4256af29865b
[ "MIT" ]
null
null
null
#include "ThreadPool.h" ThreadPool::ThreadWorker::ThreadWorker(ThreadPool* threadPool, const int threadIdx) :m_threadPool(threadPool),m_threadIdx(threadIdx) {} void ThreadPool::ThreadWorker::operator()() { std::function<void()> function; bool dequeued; while (!m_threadPool->m_shutdown) { { std::unique_lock<std::mutex> lock(m_threadPool->m_conditionalMutex); if (m_threadPool->m_queue.empty()) { m_threadPool->m_conditionalLock.wait(lock); } dequeued = m_threadPool->m_queue.dequeue(function); } if (dequeued) { function(); } } } ThreadPool::ThreadPool() :m_threads(std::vector<std::thread>(DEFAULT_NUMBER_THREADS)) , m_shutdown(false) { for (int i = 0; i < m_threads.size(); i++) { m_threads[i] = std::thread(ThreadWorker(this, i)); } } ThreadPool::ThreadPool(const int numberOfThreads) :m_threads(std::vector<std::thread>(numberOfThreads)) , m_shutdown(false) { for (int i = 0; i < m_threads.size(); i++) { m_threads[i] = std::thread(ThreadWorker(this, i)); } } ThreadPool::~ThreadPool() { m_shutdown = true; m_conditionalLock.notify_all(); for (int i = 0; i < m_threads.size(); ++i) { if (m_threads[i].joinable()) { m_threads[i].join(); } } }
23.230769
83
0.683775
simon-bourque
49da67e562c02f9ecc3ade584f25592a8ab3d710
6,581
cc
C++
TicTacToe.cc
ucarlos/C-Doodles
6e4680c47b1f73e39611e6ace7ab60f5123da34a
[ "MIT" ]
null
null
null
TicTacToe.cc
ucarlos/C-Doodles
6e4680c47b1f73e39611e6ace7ab60f5123da34a
[ "MIT" ]
null
null
null
TicTacToe.cc
ucarlos/C-Doodles
6e4680c47b1f73e39611e6ace7ab60f5123da34a
[ "MIT" ]
null
null
null
/* * ----------------------------------------------------------------------------- * Created by Ulysses Carlos on 06/22/2020 at 09:47 PM * * Tic_Tak_Toe.cc * Awful Implementation of Tic Tac Toe. * ----------------------------------------------------------------------------- */ #include <iostream> #include <vector> using namespace std; const char default_tile_char = '!'; int total_marks = 0; // 80 char terminal const int max_term_length = 80; class Mark{ public: void set_mark(char ch) { value = ch; } char get_mark() const{ return value; } bool is_mark(char ch) const { return value == ch; } void clear_mark() { value = default_tile_char; } Mark()=default; explicit Mark(char val) : value{val} { } void toggle_on(){ chosen = true; } void toggle_off(){ chosen = false; } bool is_empty() const { return !chosen; } private: char value{default_tile_char}; bool chosen{false}; }; void draw_board(const vector<Mark> &vm); class Player{ public: Player()=default; vector<int>& get_mark_list(){ return mark_indices; } explicit Player(char ch) : mark_char{ch} { } // Copy constructor Player(const Player &p); void add_mark_to_list(int i){ mark_indices.push_back(i); } [[nodiscard]] char get_mark_character() const { return mark_char; } private: char mark_char{'@'}; vector<int> mark_indices; }; Player::Player(const Player &p){ this->mark_char = p.mark_char; this->mark_indices = p.mark_indices; } //------------------------------------------------------------------------------ // Class helper functions //------------------------------------------------------------------------------ void claim_mark(Player &p, Mark &m, int index){ m.set_mark(p.get_mark_character()); m.toggle_on(); // Add to list: p.add_mark_to_list(index); total_marks++; } void print_dash_line(const int &term_len){ for (int i = 0; i < term_len; i++) cout << "-"; cout << "\n"; } //------------------------------------------------------------------------------ // Check Win Conditions //------------------------------------------------------------------------------ inline bool check_down(const vector<Mark> &board, const int &index, const char &ch){ return board[index].get_mark() == ch && board[index + 3].get_mark() == ch && board[index + 6].get_mark() == ch; } inline bool check_across(const vector<Mark> &board, const int &index, const char &ch){ return board[index].get_mark() == ch && board[index + 1].get_mark() == ch && board[index + 2].get_mark() == ch; } inline bool check_right_diagonal(const vector<Mark> &board, const int &index, const char &ch){ return board[index].get_mark() == ch && board[index + 4].get_mark() == ch && board[index + 8].get_mark() == ch; } inline bool check_left_diagonal(const vector<Mark> &board, const int &index, const char &ch){ return board[index].get_mark() == ch && board[index + 2].get_mark() == ch && board[index + 4].get_mark() == ch; } //------------------------------------------------------------------------------ // Awful way of checking winning conditions, but it works. //------------------------------------------------------------------------------ bool check_winning_conditions(vector<Mark> &board, Player &p){ bool check{true}; char player_character = p.get_mark_character(); int temp_index; // Now check the player's vector list. If less than 3, return false. const vector<int> &vec = p.get_mark_list(); if (vec.size() < 3) return false; for (const int &i : vec){ temp_index = i; switch(temp_index){ case 0: check = check_across(board, temp_index, player_character); check |= check_down(board, temp_index, player_character); check |= check_right_diagonal(board, temp_index, player_character); break; case 1: check = check_down(board, temp_index, player_character); break; case 2: check = check_down(board, temp_index, player_character); check |= check_left_diagonal(board, temp_index, player_character); break; case 3: case 6: check = check_across(board, temp_index, player_character); // break can be omitted if you want //break; default: break; } if (check){ draw_board(board); cout << "Player '" << player_character << "' wins!" << endl; return true; } } // if check is still false, then the game has ended in a draw. if (!check && total_marks >= 9){ draw_board(board); cout << "This game ends in a draw." << endl; return true; } // If none were found, then continue. return false; } void draw_board(const vector<Mark> &vm){ for (unsigned long i = 0; i < vm.size(); i++) cout << vm[i].get_mark() << (((i + 1) % 3 == 0) ? "\n" : " "); } void player_turn(vector<Mark> &board, Player &p){ // Clear screen and print the current board: // Windows Version #if defined(WIN32) || defined(_WIN32) system("cls"); #else // Linux/POSIX system("clear"); #endif char pc = p.get_mark_character(); print_dash_line(max_term_length); cout << "It is now Player " << pc << "'s turn.\n"; print_dash_line(max_term_length); draw_board(board); print_dash_line(max_term_length); cout << "Please enter a row and column where you want to put down" << " a character.\nMake sure that the row and columns are" << " between 1 and 3.\n"; int row, column; cin >> row >> column; int index = 3 * (row - 1) + (column - 1); bool check_range = (1 <= row && row <= 3) && (1 <= column && column <= 3); while (!check_range || !board[index].is_empty()){ cerr << "The row and column combination is invalid or " << "is already marked by another player. Try again.\n"; cin >> row >> column; index = 3 * (row - 1) + (column - 1); check_range = (1 <= row && row <= 3) && (1 <= column && column <= 3); } // Now translate to 1d array: claim_mark(p, board[index], index); bool check_win = check_winning_conditions(board, p); if (check_win) exit(EXIT_SUCCESS); } int main(void){ // Create the board. vector<Mark> board(9); Player p1('x'); Player p2('o'); print_dash_line(max_term_length); cout << "Tic Tac Toe (Version 0.5)" << endl; print_dash_line(max_term_length); char ch; cout << "Press any letter to begin!" << endl; cin >> ch; while (true){ player_turn(board, p1); player_turn(board, p2); } }
27.535565
80
0.561313
ucarlos
49ddbb44d358aadb14bfcc1dcd13c201618f2a85
5,626
cpp
C++
libFRIClient/src/base/friClientApplication.cpp
thinkexist1989/iiwa_connectivity_fri_examples
7a0ed010ce41ed774fc037ab11219eba824b2ae4
[ "MIT" ]
1
2021-04-07T05:40:55.000Z
2021-04-07T05:40:55.000Z
libFRIClient/src/base/friClientApplication.cpp
thinkexist1989/iiwa_connectivity_fri_examples
7a0ed010ce41ed774fc037ab11219eba824b2ae4
[ "MIT" ]
null
null
null
libFRIClient/src/base/friClientApplication.cpp
thinkexist1989/iiwa_connectivity_fri_examples
7a0ed010ce41ed774fc037ab11219eba824b2ae4
[ "MIT" ]
null
null
null
// version: 1.7 /** DISCLAIMER OF WARRANTY The Software is provided "AS IS" and "WITH ALL FAULTS," without warranty of any kind, including without limitation the warranties of merchantability, fitness for a particular purpose and non-infringement. KUKA makes no warranty that the Software is free of defects or is suitable for any particular purpose. In no event shall KUKA be responsible for loss or damages arising from the installation or use of the Software, including but not limited to any indirect, punitive, special, incidental or consequential damages of any character including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. The entire risk to the quality and performance of the Software is not borne by KUKA. Should the Software prove defective, KUKA is not liable for the entire cost of any service and repair. COPYRIGHT All Rights Reserved Copyright (C) 2014-2015 KUKA Roboter GmbH Augsburg, Germany This material is the exclusive property of KUKA Roboter GmbH and must be returned to KUKA Roboter GmbH immediately upon request. This material and the information illustrated or contained herein may not be used, reproduced, stored in a retrieval system, or transmitted in whole or in part in any way - electronic, mechanical, photocopying, recording, or otherwise, without the prior written consent of KUKA Roboter GmbH. */ #include <stdio.h> #include "friClientApplication.h" #include "friClientIf.h" #include "friConnectionIf.h" #include "friClientData.h" #include "FRIMessages.pb.h" using namespace KUKA::FRI; //****************************************************************************** ClientApplication::ClientApplication(IConnection& connection, IClient& client) : _connection(connection), _client(client), _data(NULL) { _data = _client.createData(); } //****************************************************************************** ClientApplication::~ClientApplication() { disconnect(); delete _data; } //****************************************************************************** bool ClientApplication::connect(int port, const char *remoteHost) { if (_connection.isOpen()) { printf("Warning: client application already connected!\n"); return true; } return _connection.open(port, remoteHost); } //****************************************************************************** void ClientApplication::disconnect() { if (_connection.isOpen()) _connection.close(); } //****************************************************************************** bool ClientApplication::step() { if (!_connection.isOpen()) { printf("Error: client application is not connected!\n"); return false; } // ************************************************************************** // Receive and decode new monitoring message // ************************************************************************** int size = _connection.receive(_data->receiveBuffer, FRI_MONITOR_MSG_MAX_SIZE); if (size <= 0) { // TODO: size == 0 -> connection closed (maybe go to IDLE instead of stopping?) printf("Error: failed while trying to receive monitoring message!\n"); return false; } if (!_data->decoder.decode(_data->receiveBuffer, size)) { return false; } // check message type (so that our wrappers match) if (_data->expectedMonitorMsgID != _data->monitoringMsg.header.messageIdentifier) { printf("Error: incompatible IDs for received message (got: %d expected %d)!\n", (int)_data->monitoringMsg.header.messageIdentifier, (int)_data->expectedMonitorMsgID); return false; } // ************************************************************************** // callbacks // ************************************************************************** // reset commmand message before callbacks _data->resetCommandMessage(); ESessionState currentState = (ESessionState)_data->monitoringMsg.connectionInfo.sessionState; if (_data->lastState != currentState) { _client.onStateChange(_data->lastState, currentState); _data->lastState = currentState; } switch (currentState) { case MONITORING_WAIT: case MONITORING_READY: _client.monitor(); break; case COMMANDING_WAIT: _client.waitForCommand(); break; case COMMANDING_ACTIVE: _client.command(); break; case IDLE: default: return true; // nothing to send back } // ************************************************************************** // Encode and send command message // ************************************************************************** _data->lastSendCounter++; // check if its time to send an answer if (_data->lastSendCounter >= _data->monitoringMsg.connectionInfo.receiveMultiplier) { _data->lastSendCounter = 0; // set sequence counters _data->commandMsg.header.sequenceCounter = _data->sequenceCounter++; _data->commandMsg.header.reflectedSequenceCounter = _data->monitoringMsg.header.sequenceCounter; if (!_data->encoder.encode(_data->sendBuffer, size)) { return false; } if (!_connection.send(_data->sendBuffer, size)) { printf("Error: failed while trying to send command message!\n"); return false; } } return true; }
32.148571
96
0.585851
thinkexist1989
49df51121939c40f1c347a5d84b8f2c9c642cf52
1,811
cpp
C++
Source/UnrealCPP/ActorLineTrace/ActorLineTrace.cpp
Harrison1/unrealcpp-full-project
a0a84d124b3023a87cbcbf12cf8ee0a833dd4302
[ "MIT" ]
6
2018-04-22T15:27:39.000Z
2021-11-02T17:33:58.000Z
Source/UnrealCPP/ActorLineTrace/ActorLineTrace.cpp
Harrison1/unrealcpp-full-project
a0a84d124b3023a87cbcbf12cf8ee0a833dd4302
[ "MIT" ]
null
null
null
Source/UnrealCPP/ActorLineTrace/ActorLineTrace.cpp
Harrison1/unrealcpp-full-project
a0a84d124b3023a87cbcbf12cf8ee0a833dd4302
[ "MIT" ]
4
2018-07-26T15:39:46.000Z
2020-12-28T08:10:35.000Z
// Harrison McGuire // UE4 Version 4.19.0 // https://github.com/Harrison1/unrealcpp // https://severallevels.io // https://harrisonmcguire.com #include "ActorLineTrace.h" #include "ConstructorHelpers.h" #include "DrawDebugHelpers.h" // Sets default values AActorLineTrace::AActorLineTrace() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; // add cube to root UStaticMeshComponent* Cube = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("VisualRepresentation")); Cube->SetupAttachment(RootComponent); static ConstructorHelpers::FObjectFinder<UStaticMesh> CubeAsset(TEXT("/Game/StarterContent/Shapes/Shape_Cube.Shape_Cube")); if (CubeAsset.Succeeded()) { Cube->SetStaticMesh(CubeAsset.Object); Cube->SetRelativeLocation(FVector(0.0f, 0.0f, 0.0f)); Cube->SetWorldScale3D(FVector(1.f)); } // add another component in the editor to the actor to overlap with the line trace to get the event to fire } // Called when the game starts or when spawned void AActorLineTrace::BeginPlay() { Super::BeginPlay(); } // Called every frame void AActorLineTrace::Tick(float DeltaTime) { Super::Tick(DeltaTime); FHitResult OutHit; FVector Start = GetActorLocation(); Start.Z += 50.f; Start.X += 200.f; FVector ForwardVector = GetActorForwardVector(); FVector End = ((ForwardVector * 500.f) + Start); FCollisionQueryParams CollisionParams; DrawDebugLine(GetWorld(), Start, End, FColor::Green, false, 1, 0, 5); if(ActorLineTraceSingle(OutHit, Start, End, ECC_WorldStatic, CollisionParams)) { GEngine->AddOnScreenDebugMessage(-1, 1.f, FColor::Green, FString::Printf(TEXT("The Component Being Hit is: %s"), *OutHit.GetComponent()->GetName())); } }
28.746032
151
0.732192
Harrison1
49e067ba72c9284c68a76f2dc24c67c337584b14
3,539
hpp
C++
cmake/templates/spirv.in.hpp
EEnginE/engine
9d8fe2c8a3051b8d25a15debdf058ac900f6a7fc
[ "Apache-2.0" ]
28
2015-01-02T19:06:37.000Z
2018-11-23T11:34:17.000Z
cmake/templates/spirv.in.hpp
EEnginE/engine
9d8fe2c8a3051b8d25a15debdf058ac900f6a7fc
[ "Apache-2.0" ]
null
null
null
cmake/templates/spirv.in.hpp
EEnginE/engine
9d8fe2c8a3051b8d25a15debdf058ac900f6a7fc
[ "Apache-2.0" ]
6
2015-01-10T16:48:14.000Z
2019-10-08T13:43:44.000Z
/*! * \file @FILENAME_HPP@ * \brief \b Classes: \a @CLASSNAME@ * \warning This file was automatically generated by createSPIRV! */ // clang-format off #pragma once #include "defines.hpp" #include "rShaderBase.hpp" namespace e_engine { class iInit; class rWorld; class @CLASSNAME@ : public rShaderBase { private: static const std::vector<unsigned char> vRawData_vert; static const std::vector<unsigned char> vRawData_tesc; static const std::vector<unsigned char> vRawData_tese; static const std::vector<unsigned char> vRawData_geom; static const std::vector<unsigned char> vRawData_frag; static const std::vector<unsigned char> vRawData_comp; public: virtual std::string getName() { return "@S_NAME@"; } virtual bool has_vert() const { return @HAS_VERT@; } virtual bool has_tesc() const { return @HAS_TESC@; } virtual bool has_tese() const { return @HAS_TESE@; } virtual bool has_geom() const { return @HAS_GEOM@; } virtual bool has_frag() const { return @HAS_FRAG@; } virtual bool has_comp() const { return @HAS_COMP@; } virtual ShaderInfo getInfo_vert() const { return { { // Input @INPUT_VERT@ }, { // Output @OUTPUT_VERT@ }, { // Uniforms @UNIFORM_VERT@ }, { // Push constants @PUSH_VERT@ }, { // Uniform Blocks @UNIFORM_B_VERT@ } }; } virtual ShaderInfo getInfo_tesc() const { return { { // Input @INPUT_TESC@ }, { // Output @OUTPUT_TESC@ }, { // Uniforms @UNIFORM_TESC@ }, { // Push constants @PUSH_TESC@ }, { // Uniform Blocks @UNIFORM_B_TESC@ } }; } virtual ShaderInfo getInfo_tese() const { return { { // Input @INPUT_TESE@ }, { // Output @OUTPUT_TESE@ }, { // Uniforms @UNIFORM_TESE@ }, { // Push constants @PUSH_TESE@ }, { // Uniform Blocks @UNIFORM_B_TESE@ } }; } virtual ShaderInfo getInfo_geom() const { return { { // Input @INPUT_GEOM@ }, { // Output @OUTPUT_GEOM@ }, { // Uniforms @UNIFORM_GEOM@ }, { // Push constants @PUSH_GEOM@ }, { // Uniform Blocks @UNIFORM_B_GEOM@ } }; } virtual ShaderInfo getInfo_frag() const { return { { // Input @INPUT_FRAG@ }, { // Output @OUTPUT_FRAG@ }, { // Uniforms @UNIFORM_FRAG@ }, { // Push constants @PUSH_FRAG@ }, { // Uniform Blocks @UNIFORM_B_FRAG@ } }; } virtual ShaderInfo getInfo_comp() const { return { { // Input @INPUT_COMP@ }, { // Output @OUTPUT_COMP@ }, { // Uniforms @UNIFORM_COMP@ }, { // Push constants @PUSH_COMPT@ }, { // Uniform Blocks @UNIFORM_B_COMP@ } }; } @CLASSNAME@() = delete; @CLASSNAME@( vkuDevicePTR _device ) : rShaderBase( _device ) {} virtual std::vector<unsigned char> getRawData_vert() const; virtual std::vector<unsigned char> getRawData_tesc() const; virtual std::vector<unsigned char> getRawData_tese() const; virtual std::vector<unsigned char> getRawData_geom() const; virtual std::vector<unsigned char> getRawData_frag() const; virtual std::vector<unsigned char> getRawData_comp() const; }; } // clang-format on
20.456647
67
0.558915
EEnginE
49e2ae5f9a64d8219c64ae96f89c3f5626f47961
5,795
cpp
C++
src/geometry/similarity_graph_optimization.cpp
bitlw/EGSfM
d5b4260d38237c6bd814648cadcf1fcf2f8f5d31
[ "BSD-3-Clause" ]
90
2019-05-19T03:48:23.000Z
2022-02-02T15:20:49.000Z
src/geometry/similarity_graph_optimization.cpp
bitlw/EGSfM
d5b4260d38237c6bd814648cadcf1fcf2f8f5d31
[ "BSD-3-Clause" ]
11
2019-05-22T07:45:46.000Z
2021-05-20T01:48:26.000Z
src/geometry/similarity_graph_optimization.cpp
bitlw/EGSfM
d5b4260d38237c6bd814648cadcf1fcf2f8f5d31
[ "BSD-3-Clause" ]
18
2019-05-19T03:48:32.000Z
2021-05-29T18:19:16.000Z
#include "similarity_graph_optimization.h" #include <unordered_map> #include <vector> using namespace std; namespace GraphSfM { namespace geometry { SimilarityGraphOptimization::SimilarityGraphOptimization() { } SimilarityGraphOptimization::~SimilarityGraphOptimization() { } // void SimilarityGraphOptimization::SetOptimizedOption(const BAOption& optimized_option) // { // _optimized_option = optimized_option; // } void SimilarityGraphOptimization::SetSimilarityGraph(const SimilarityGraph& sim_graph) { _sim_graph = sim_graph; } SimilarityGraph SimilarityGraphOptimization::GetSimilarityGraph() const { return _sim_graph; } void SimilarityGraphOptimization::SimilarityAveraging( std::unordered_map<size_t, std::vector<Pose3>>& cluster_boundary_cameras) { ceres::Problem problem; ceres::LossFunction* loss_function = new ceres::HuberLoss(openMVG::Square(4.0)); MapSim3 map_sim3; size_t edge_num = 0; for (auto outer_it = _sim_graph.begin(); outer_it != _sim_graph.end(); ++outer_it) { size_t i = outer_it->first; for (auto inner_it = outer_it->second.begin(); inner_it != outer_it->second.end(); ++inner_it) { edge_num++; size_t j = inner_it->first; Sim3 sim3 = inner_it->second; // LOG(INFO) << sim3.s << "\n" // << sim3.R << "\n" // << sim3.t; double angle_axis[3]; ceres::RotationMatrixToAngleAxis(sim3.R.data(), angle_axis); std::vector<double> parameter_block(7); parameter_block[0] = angle_axis[0]; parameter_block[1] = angle_axis[1]; parameter_block[2] = angle_axis[2]; parameter_block[3] = sim3.t[0]; parameter_block[4] = sim3.t[1]; parameter_block[5] = sim3.t[2]; parameter_block[6] = sim3.s; map_sim3[i].insert(make_pair(j, parameter_block)); std::vector<Pose3> vec_boundary_cameras1 = cluster_boundary_cameras[i]; std::vector<Pose3> vec_boundary_cameras2 = cluster_boundary_cameras[j]; int size = vec_boundary_cameras1.size(); for (int k = 0; k < size; k++) { const Eigen::Vector3d c_ik = vec_boundary_cameras1[k].center(); const Eigen::Vector3d c_jk = vec_boundary_cameras1[k].center(); ceres::CostFunction* cost_function = Reprojection3DCostFunctor::Create(c_ik, c_jk); problem.AddResidualBlock(cost_function, loss_function, &map_sim3[i][j][0]); } } } BAOption ba_option; if (edge_num > 100 && (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::SUITE_SPARSE) || ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::CX_SPARSE) || ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::EIGEN_SPARSE))) { ba_option.preconditioner_type = ceres::JACOBI; ba_option.linear_solver_type = ceres::SPARSE_SCHUR; if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::SUITE_SPARSE)) { ba_option.sparse_linear_algebra_library_type = ceres::SUITE_SPARSE; } else if (ceres::IsSparseLinearAlgebraLibraryTypeAvailable(ceres::CX_SPARSE)) { ba_option.sparse_linear_algebra_library_type = ceres::CX_SPARSE; } else { ba_option.sparse_linear_algebra_library_type = ceres::EIGEN_SPARSE; } } else { ba_option.linear_solver_type = ceres::DENSE_SCHUR; ba_option.sparse_linear_algebra_library_type = ceres::NO_SPARSE; } ba_option.num_threads = omp_get_max_threads(); ba_option.num_linear_solver_threads = omp_get_max_threads(); ba_option.loss_function_type = LossFunctionType::HUBER; ba_option.logging_type = ceres::SILENT; ba_option.minimizer_progress_to_stdout = true; ceres::Solver::Options options; options.num_threads = ba_option.num_threads; // options.num_linear_solver_threads = ba_option.num_linear_solver_threads; options.linear_solver_type = ba_option.linear_solver_type; options.sparse_linear_algebra_library_type = ba_option.sparse_linear_algebra_library_type; options.preconditioner_type = ba_option.preconditioner_type; options.logging_type = ba_option.logging_type; options.minimizer_progress_to_stdout = ba_option.minimizer_progress_to_stdout; ceres::Solver::Summary summary; ceres::Solve(options, &problem, &summary); LOG(INFO) << summary.BriefReport(); if (!summary.IsSolutionUsable()) { LOG(ERROR) << "Similarity Averaging failed!"; } else { LOG(INFO) << "Initial RMSE: " << std::sqrt(summary.initial_cost / summary.num_residuals); LOG(INFO) << "Final RMSE: " << std::sqrt(summary.final_cost / summary.num_residuals) << "\n" << "Time: " << summary.total_time_in_seconds << "\n"; } this->UpdateSimilarityGraph(map_sim3); } void SimilarityGraphOptimization::UpdateSimilarityGraph(const MapSim3& map_sim3) { for (auto outer_it = _sim_graph.begin(); outer_it != _sim_graph.end(); ++outer_it) { size_t i = outer_it->first; for (auto inner_it = outer_it->second.begin(); inner_it != outer_it->second.end(); ++inner_it) { size_t j = inner_it->first; Sim3& sim3 = inner_it->second; std::vector<double> vec_sim3 = map_sim3.at(i).at(j); ceres::AngleAxisToRotationMatrix(&vec_sim3[0], sim3.R.data()); sim3.t[0] = vec_sim3[3]; sim3.t[1] = vec_sim3[4]; sim3.t[2] = vec_sim3[5]; sim3.s = vec_sim3[6]; } } } } // namespace geometry } // namespace GraphSfM
36.21875
104
0.654012
bitlw
49e59d73d462c2f808ff4e110e50602d30b01dfc
5,594
cpp
C++
Source/DedicatedServerTest/Private/GameFramework/Pawn/MyPawn.cpp
dorgonman/DedicatedServerTest
8bfe6e8357929fbd68be52e11ba27f78492931c8
[ "BSL-1.0" ]
1
2019-03-31T22:54:37.000Z
2019-03-31T22:54:37.000Z
Source/DedicatedServerTest/Private/GameFramework/Pawn/MyPawn.cpp
dorgonman/DedicatedServerTest
8bfe6e8357929fbd68be52e11ba27f78492931c8
[ "BSL-1.0" ]
null
null
null
Source/DedicatedServerTest/Private/GameFramework/Pawn/MyPawn.cpp
dorgonman/DedicatedServerTest
8bfe6e8357929fbd68be52e11ba27f78492931c8
[ "BSL-1.0" ]
1
2021-10-21T04:37:37.000Z
2021-10-21T04:37:37.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "MyPawn.h" #include "DedicatedServerTest.h" #include "Net/UnrealNetwork.h" #include "MyBlueprintFunctionLibrary.h" #include "MyFloatingPawnMovement.h" // Sets default values AMyPawn::AMyPawn() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent")); StaticMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("StaticMeshComponent")); StaticMeshComponent->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform); //CharacterMovement = CreateDefaultSubobject<UCharacterMovementComponent>(TEXT("CharMoveComp")); if (CharacterMovement) { //CharacterMovement->PrimaryComponentTick.bCanEverTick = true; //RootComponent-> //CharacterMovement->UpdatedComponent = RootComponent; //CharacterMovement->SetUpdatedComponent(RootComponent); //CharacterMovement->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform); } //FloatingPawnMovement = CreateDefaultSubobject<UMyFloatingPawnMovement>(TEXT("FloatingPawnMovement")); //UFloatingPawnMovement only support local control, so we implement UMyFloatingPawnMovement to remove the restriction FloatingPawnMovement = CreateDefaultSubobject<UMyFloatingPawnMovement>(TEXT("FloatingPawnMovement")); //FloatingPawnMovement->UpdatedComponent = nullptr; //void UMovementComponent::OnRegister() // Auto-register owner's root component if no update component set. } // Called when the game starts or when spawned void AMyPawn::BeginPlay() { Super::BeginPlay(); } // Called every frame void AMyPawn::Tick( float DeltaTime ) { Super::Tick( DeltaTime ); //send Client camera rotation to server for replicate pawn's rotation //CurrentTransform = GetActorTransform(); } // Called to bind functionality to input void AMyPawn::SetupPlayerInputComponent(class UInputComponent* inputComponent) { Super::SetupPlayerInputComponent(inputComponent); //inputComponent->BindAxis("MoveForward", this, &AMyPawn::MoveForward); //inputComponent->BindAxis("Turn", this, &AMyPawn::AddControllerYawInput); //inputComponent->BindAxis("LookUp", this, &AMyPawn::AddControllerPitchInput); } void AMyPawn::AddMovementInput(FVector WorldDirection, float ScaleValue, bool bForce) { if (!Controller || ScaleValue == 0.0f) return; //Super::AddMovementInput(WorldDirection, ScaleValue, bForce); // Make sure only the Client Version calls the ServerRPC //bool AActor::HasAuthority() const { return (Role == ROLE_Authority); } if (Role < ROLE_Authority && IsLocallyControlled()) { //run on client, call PRC to server Server_AddMovementInput(WorldDirection, ScaleValue, bForce); } else { //run on server Super::AddMovementInput(WorldDirection, ScaleValue, bForce); SetActorRotation(WorldDirection.Rotation()); //will call OnRep_TransformChange CurrentTransform = GetActorTransform(); //CurrentTransform.SetRotation(WorldDirection.ToOrientationQuat()); } //if (GEngine->GetNetMode(GetWorld()) != NM_DedicatedServer) //{ //code to run on non-dedicated servers //} } bool AMyPawn::Server_AddMovementInput_Validate(FVector WorldDirection, float ScaleValue, bool bForce) { return true; } void AMyPawn::Server_AddMovementInput_Implementation(FVector WorldDirection, float ScaleValue, bool bForce) { //AddMovementInput(WorldDirection, ScaleValue, bForce); AddMovementInput(WorldDirection, ScaleValue, bForce); } UPawnMovementComponent* AMyPawn::GetMovementComponent() const { //auto test = Super::GetMovementComponent(); return FloatingPawnMovement; } void AMyPawn::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); ///** Secondary condition to check before considering the replication of a lifetime property. */ //enum ELifetimeCondition //{ // COND_None = 0, // This property has no condition, and will send anytime it changes // COND_InitialOnly = 1, // This property will only attempt to send on the initial bunch // COND_OwnerOnly = 2, // This property will only send to the actor's owner // COND_SkipOwner = 3, // This property send to every connection EXCEPT the owner // COND_SimulatedOnly = 4, // This property will only send to simulated actors // COND_AutonomousOnly = 5, // This property will only send to autonomous actors // COND_SimulatedOrPhysics = 6, // This property will send to simulated OR bRepPhysics actors // COND_InitialOrOwner = 7, // This property will send on the initial packet, or to the actors owner // COND_Custom = 8, // This property has no particular condition, but wants the ability to toggle on/off via SetCustomIsActiveOverride // COND_Max = 9, //}; DOREPLIFETIME(AMyPawn, CurrentTransform); //DOREPLIFETIME_CONDITION( AMyPawn, CurrentTransform, COND_None ); } void AMyPawn::OnRep_ReplicatedMovement() { Super::OnRep_ReplicatedMovement(); // Skip standard position correction if we are playing root motion, OnRep_RootMotion will handle it. //if (!IsPlayingNetworkedRootMotionMontage()) // animation root motion //{ // if (!CharacterMovement || !CharacterMovement->CurrentRootMotion.HasActiveRootMotionSources()) // root motion sources // { // Super::OnRep_ReplicatedMovement(); // } //} } void AMyPawn::OnRep_TransformChange() { SetActorTransform(CurrentTransform); //SetActorRotation(CurrentRotation); }
34.745342
136
0.774401
dorgonman
49ea26f9462238bba1026969c5bc9e4f690747d2
3,821
cc
C++
examples/encrypted_content_keys.cc
google/cpix_cc
eb79e1aed6cd6181716c66cd5d670cfc90907192
[ "Apache-2.0" ]
11
2019-08-16T21:05:32.000Z
2021-02-07T00:33:09.000Z
examples/encrypted_content_keys.cc
google/cpix_cc
eb79e1aed6cd6181716c66cd5d670cfc90907192
[ "Apache-2.0" ]
1
2020-09-28T11:16:37.000Z
2020-09-28T11:16:37.000Z
examples/encrypted_content_keys.cc
google/cpix_cc
eb79e1aed6cd6181716c66cd5d670cfc90907192
[ "Apache-2.0" ]
6
2019-08-18T17:26:35.000Z
2021-10-14T17:12:15.000Z
// Copyright 2019 Google LLC // // 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 // // https://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 "content_key.h" #include "cpix_message.h" #include "recipient.h" int main() { const std::vector<uint8_t> key_id1 = { 0xe3, 0x47, 0x74, 0xd9, 0xd7, 0x75, 0xeb, 0x56, 0xb7, 0xe3, 0xbf, 0x3b, 0x6b, 0x5e, 0x79, 0xe7, 0xbd, 0xb7, 0xdb, 0x97, 0x78, 0xed, 0xbf, 0x34}; const std::vector<uint8_t> key_id2 = { 0xd1, 0xad, 0xf4, 0x79, 0xae, 0x1f, 0xe7, 0x7f, 0x5d, 0xe1, 0xbd, 0x36, 0xf7, 0x86, 0xf6, 0xd9, 0xbd, 0xdf, 0x6d, 0xad, 0xb9, 0xef, 0xa7, 0x77}; const std::vector<uint8_t> content_key_value1 = { 0x80, 0xfc, 0x6d, 0xd0, 0xf3, 0x30, 0xac, 0x73, 0x38, 0x4d, 0xd8, 0xf0, 0x75, 0x09, 0xa1, 0x85}; const std::vector<uint8_t> content_key_value2 = { 0xc7, 0xf8, 0x1a, 0xa1, 0x2f, 0xdf, 0x0e, 0x2f, 0x01, 0xa8, 0x63, 0x48, 0x86, 0x48, 0xb1, 0xc1}; const std::vector<uint8_t> certificate = { 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xbc, 0x39, 0x25, 0x06, 0x5d, 0x99, 0xa4, 0x05, 0x5f, 0xe7, 0xfc, 0x59, 0x1f, 0x28, 0xb5, 0x48, 0xd2, 0x0d, 0x2e, 0xea, 0xaa, 0xeb, 0xed, 0x74, 0xef, 0xc9, 0x2f, 0x90, 0xf8, 0xad, 0x96, 0x80, 0x24, 0x0f, 0xc2, 0xdc, 0x71, 0x58, 0xea, 0x3e, 0xfa, 0x5c, 0xc9, 0x29, 0x87, 0x51, 0x7c, 0xcb, 0x54, 0x28, 0x7c, 0xf9, 0x10, 0x15, 0xb0, 0xac, 0x8f, 0xeb, 0x9e, 0xd3, 0xd7, 0x70, 0x35, 0x93, 0x8a, 0xc7, 0x1f, 0x45, 0x97, 0xe3, 0xc8, 0x0b, 0x72, 0xa1, 0x65, 0x79, 0xcf, 0x74, 0x6c, 0x87, 0xd9, 0xeb, 0x7d, 0xa0, 0xb9, 0x0e, 0x4b, 0x45, 0x3d, 0x81, 0xf0, 0x18, 0x6e, 0x9f, 0x97, 0x11, 0x54, 0xcb, 0xd8, 0xe2, 0x35, 0x1a, 0x4b, 0xe7, 0x4d, 0xbf, 0x68, 0x1d, 0xad, 0x4e, 0xca, 0x57, 0x25, 0x9e, 0x2f, 0xf7, 0xf8, 0x44, 0x6f, 0xc2, 0x0c, 0x78, 0xd, 0x19, 0xef, 0x22, 0x5a, 0x9f, 0x78, 0x9f, 0x17, 0x1a, 0xb8, 0xc0, 0x72, 0x0f, 0x51, 0x5c, 0x21, 0x6f, 0xc9, 0x1e, 0x80, 0xde, 0x7c, 0x25, 0x47, 0xd0, 0x28, 0x01, 0x2a, 0x94, 0x6e, 0x34, 0x39, 0x1f, 0x42, 0x39, 0xbe, 0x5f, 0x0e, 0xc2, 0x7c, 0xb4, 0xfa, 0xa5, 0xb9, 0x05, 0x4e, 0x9c, 0x45, 0x75, 0x63, 0xa3, 0x87, 0xc3, 0xe5, 0xdd, 0x54, 0x35, 0x85, 0xd4, 0x8d, 0xc2, 0x5f, 0xda, 0x6f, 0x86, 0x12, 0xcf, 0xb3, 0x8b, 0x65, 0x23, 0x1d, 0x34, 0x43, 0xc5, 0x2e, 0xb1, 0x49, 0x56, 0x56, 0x25, 0x93, 0xf7, 0x09, 0xbf, 0x9e, 0x48, 0x21, 0x91, 0x6a, 0xde, 0x27, 0x9e, 0x6d, 0x38, 0x2f, 0xf5, 0xf4, 0x93, 0x23, 0x46, 0xe8, 0x41, 0xb4, 0x21, 0xb4, 0x02, 0x50, 0x79, 0x71, 0x48, 0x72, 0x0f, 0x57, 0x46, 0xa0, 0x20, 0xc0, 0x19, 0x02, 0xf9, 0xd4, 0x76, 0x02, 0x2d, 0x85, 0xfd, 0x79, 0xcd, 0x70, 0xfc, 0x41, 0x8b, 0x02, 0x03, 0x01, 0x00, 0x01}; cpix::CPIXMessage message; std::unique_ptr<cpix::ContentKey> key1(new cpix::ContentKey); key1->set_key_id(key_id1); key1->SetKeyValue(content_key_value1); message.AddContentKey(std::move(key1)); std::unique_ptr<cpix::ContentKey> key2(new cpix::ContentKey); key2->set_key_id(key_id2); key2->SetKeyValue(content_key_value2); message.AddContentKey(std::move(key2)); std::unique_ptr<cpix::Recipient> recipient1(new cpix::Recipient); recipient1->set_delivery_key(certificate); message.AddRecipient(std::move(recipient1)); printf("Encrypted Content Key:\n\n%s\n\n", message.ToString().c_str()); }
48.367089
78
0.66213
google
49ef58af60483ed2f8482a0ab8595d5e31d41b7c
973
cpp
C++
test_for_fork.cpp
wangzhicheng2013/system_call_cpu_bind
e01c991ad3fef0b166ef787b5bc384dbbee82038
[ "MIT" ]
null
null
null
test_for_fork.cpp
wangzhicheng2013/system_call_cpu_bind
e01c991ad3fef0b166ef787b5bc384dbbee82038
[ "MIT" ]
null
null
null
test_for_fork.cpp
wangzhicheng2013/system_call_cpu_bind
e01c991ad3fef0b166ef787b5bc384dbbee82038
[ "MIT" ]
null
null
null
#include <stdio.h> #include <unistd.h> #include <iostream> #include <thread> #include "cpu_utility.hpp" void exhaust_cpu() { std::cout << system("./exhaust_cpu") << std::endl; } int main() { //int cpu_no = 21; //G_CPU_UTILITY.bind_cpu(cpu_no); std::cout << G_CPU_UTILITY.bind_all_cpus() << std::endl; int pid = -1; if (0 == (pid = fork())) { int cpu_num = G_CPU_UTILITY.get_cpu_num(); for (int cpu_no = 0;cpu_no < cpu_num;cpu_no++) { if (G_CPU_UTILITY.run_in_cpu(cpu_no)) { std::cout << "child process run in " << cpu_no << std::endl; } } sleep(1); exhaust_cpu(); } int cpu_num = G_CPU_UTILITY.get_cpu_num(); for (int cpu_no = 0;cpu_no < cpu_num;cpu_no++) { if (G_CPU_UTILITY.run_in_cpu(cpu_no)) { std::cout << "child process run in " << cpu_no << std::endl; } } sleep(1); return 0; }
29.484848
77
0.536485
wangzhicheng2013
49f01a0317bad0f30a692d106144dce0af9a2fa6
220
cpp
C++
cpp/iostream/istringstream.cpp
wjiec/packages
4ccaf8f717265a1f8a9af533f9a998b935efb32a
[ "MIT" ]
null
null
null
cpp/iostream/istringstream.cpp
wjiec/packages
4ccaf8f717265a1f8a9af533f9a998b935efb32a
[ "MIT" ]
1
2016-09-15T07:06:15.000Z
2016-09-15T07:06:15.000Z
cpp/iostream/istringstream.cpp
wjiec/packages
4ccaf8f717265a1f8a9af533f9a998b935efb32a
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> int main(void) { std::string buffer("Hello World!"); std::istringstream in(buffer); std::string inBuffer; in >> inBuffer; std::cout << inBuffer << std::endl; return 0; }
13.75
36
0.659091
wjiec
49f0f59f8c86396969102b15e4fbc44a81e02c48
9,080
cpp
C++
alica_engine/src/engine/AlicaEngine.cpp
carpe-noctem-cassel/alica
c35473090ca46dafb66ac8fa429a1923a2af05c7
[ "MIT" ]
12
2015-06-09T07:19:50.000Z
2018-11-20T10:40:08.000Z
alica_engine/src/engine/AlicaEngine.cpp
dasys-lab/alica-engine
c35473090ca46dafb66ac8fa429a1923a2af05c7
[ "MIT" ]
4
2015-09-10T10:23:33.000Z
2018-04-20T12:07:34.000Z
alica_engine/src/engine/AlicaEngine.cpp
carpe-noctem-cassel/alica
c35473090ca46dafb66ac8fa429a1923a2af05c7
[ "MIT" ]
4
2016-06-13T12:04:57.000Z
2018-07-04T08:11:35.000Z
#include "engine/AlicaEngine.h" #include "engine/BehaviourPool.h" #include "engine/IConditionCreator.h" #include "engine/IRoleAssignment.h" #include "engine/Logger.h" #include "engine/PlanBase.h" #include "engine/PlanRepository.h" #include "engine/StaticRoleAssignment.h" #include "engine/TeamObserver.h" #include "engine/UtilityFunction.h" #include "engine/allocationauthority/AuthorityManager.h" #include "engine/constraintmodul/ISolver.h" #include "engine/constraintmodul/VariableSyncModule.h" #include "engine/expressionhandler/ExpressionHandler.h" #include "engine/model/Plan.h" #include "engine/model/RoleSet.h" #include "engine/parser/PlanParser.h" #include "engine/planselector/PartialAssignment.h" #include "engine/teammanager/TeamManager.h" #include <engine/syncmodule/SyncModule.h> #include <alica_common_config/debug_output.h> #include <essentials/AgentIDManager.h> namespace alica { /** * Abort execution with a message, called if initialization fails. * @param msg A string */ void AlicaEngine::abort(const std::string& msg) { std::cerr << "ABORT: " << msg << std::endl; exit(EXIT_FAILURE); } /** * The main class. */ AlicaEngine::AlicaEngine(essentials::AgentIDManager* idManager, const std::string& roleSetName, const std::string& masterPlanName, bool stepEngine) : stepCalled(false) , planBase(nullptr) , communicator(nullptr) , alicaClock(nullptr) , sc(essentials::SystemConfig::getInstance()) , terminating(false) , expressionHandler(nullptr) , log(nullptr) , auth(nullptr) , variableSyncModule(nullptr) , stepEngine(stepEngine) , agentIDManager(idManager) { _maySendMessages = !(*sc)["Alica"]->get<bool>("Alica.SilentStart", NULL); this->useStaticRoles = (*sc)["Alica"]->get<bool>("Alica.UseStaticRoles", NULL); PartialAssignment::allowIdling((*this->sc)["Alica"]->get<bool>("Alica.AllowIdling", NULL)); this->planRepository = new PlanRepository(); this->planParser = new PlanParser(this->planRepository); this->masterPlan = this->planParser->parsePlanTree(masterPlanName); this->roleSet = this->planParser->parseRoleSet(roleSetName); _teamManager = new TeamManager(this, true); _teamManager->init(); this->behaviourPool = new BehaviourPool(this); this->teamObserver = new TeamObserver(this); if (this->useStaticRoles) { this->roleAssignment = new StaticRoleAssignment(this); } else { AlicaEngine::abort("Unknown RoleAssignment Type!"); } // the communicator is expected to be set before init() is called this->roleAssignment->setCommunication(communicator); this->syncModul = new SyncModule(this); if (!planRepository->verifyPlanBase()) { abort("Error in parsed plans."); } ALICA_DEBUG_MSG("AE: Constructor finished!"); } AlicaEngine::~AlicaEngine() { if (!terminating) { shutdown(); } } /** * Initialise the engine * @param bc A behaviourcreator * @param roleSetName A string, the roleset to be used. If empty, a default roleset is looked for * @param masterPlanName A string, the top-level plan to be used * @param roleSetDir A string, the directory in which to search for roleSets. If empty, the base role path will be used. * @param stepEngine A bool, whether or not the engine should start in stepped mode * @return bool true if everything worked false otherwise */ bool AlicaEngine::init(IBehaviourCreator* bc, IConditionCreator* cc, IUtilityCreator* uc, IConstraintCreator* crc) { if (!this->expressionHandler) { this->expressionHandler = new ExpressionHandler(this, cc, uc, crc); } this->stepCalled = false; bool everythingWorked = true; everythingWorked &= this->behaviourPool->init(bc); this->auth = new AuthorityManager(this); this->log = new Logger(this); this->roleAssignment->init(); this->auth->init(); this->planBase = new PlanBase(this, this->masterPlan); this->expressionHandler->attachAll(); UtilityFunction::initDataStructures(this); this->syncModul->init(); if (!this->variableSyncModule) { this->variableSyncModule = new VariableSyncModule(this); } if (this->communicator) { this->communicator->startCommunication(); } if (this->variableSyncModule) { this->variableSyncModule->init(); } RunningPlan::init(); return everythingWorked; } /** * Closes the engine for good. */ void AlicaEngine::shutdown() { if (this->communicator != nullptr) { this->communicator->stopCommunication(); } this->terminating = true; _maySendMessages = false; if (this->behaviourPool != nullptr) { this->behaviourPool->stopAll(); this->behaviourPool->terminateAll(); delete this->behaviourPool; this->behaviourPool = nullptr; } if (this->planBase != nullptr) { this->planBase->stop(); delete this->planBase; this->planBase = nullptr; } if (this->auth != nullptr) { this->auth->close(); delete this->auth; this->auth = nullptr; } if (this->syncModul != nullptr) { this->syncModul->close(); delete this->syncModul; this->syncModul = nullptr; } if (this->teamObserver != nullptr) { this->teamObserver->close(); delete this->teamObserver; this->teamObserver = nullptr; } if (this->log != nullptr) { this->log->close(); delete this->log; this->log = nullptr; } if (this->planRepository != nullptr) { delete this->planRepository; this->planRepository = nullptr; } if (this->planParser != nullptr) { delete this->planParser; this->planParser = nullptr; } this->roleSet = nullptr; this->masterPlan = nullptr; if (this->expressionHandler != nullptr) { delete this->expressionHandler; this->expressionHandler = nullptr; } if (this->variableSyncModule != nullptr) { delete this->variableSyncModule; this->variableSyncModule = nullptr; } if (this->roleAssignment != nullptr) { delete this->roleAssignment; this->roleAssignment = nullptr; } delete alicaClock; alicaClock = nullptr; } /** * Register with this EngineTrigger to be called after an engine iteration is complete. */ void AlicaEngine::iterationComplete() { // TODO: implement the trigger function for iteration complete } /** * Starts the engine. */ void AlicaEngine::start() { this->planBase->start(); std::cout << "AE: Engine started" << std::endl; } void AlicaEngine::setStepCalled(bool stepCalled) { this->stepCalled = stepCalled; } bool AlicaEngine::getStepCalled() const { return this->stepCalled; } bool AlicaEngine::getStepEngine() const { return this->stepEngine; } void AlicaEngine::setAlicaClock(AlicaClock* clock) { this->alicaClock = clock; } void AlicaEngine::setTeamObserver(TeamObserver* teamObserver) { this->teamObserver = teamObserver; } void AlicaEngine::setSyncModul(SyncModule* syncModul) { this->syncModul = syncModul; } void AlicaEngine::setAuth(AuthorityManager* auth) { this->auth = auth; } void AlicaEngine::setRoleAssignment(IRoleAssignment* roleAssignment) { this->roleAssignment = roleAssignment; } void AlicaEngine::setStepEngine(bool stepEngine) { this->stepEngine = stepEngine; } /** * Gets the robot name, either by access the environment variable "ROBOT", or if that isn't set, the hostname. * @return The robot name under which the engine operates, a string */ std::string AlicaEngine::getRobotName() const { return sc->getHostname(); } void AlicaEngine::setLog(Logger* log) { this->log = log; } bool AlicaEngine::isTerminating() const { return terminating; } void AlicaEngine::setMaySendMessages(bool maySendMessages) { _maySendMessages = maySendMessages; } void AlicaEngine::setCommunicator(IAlicaCommunication* communicator) { this->communicator = communicator; } void AlicaEngine::setResultStore(VariableSyncModule* resultStore) { this->variableSyncModule = resultStore; } /** * Triggers the engine to run one iteration. * Attention: This method call is asynchronous to the triggered iteration. * So please wait long enough to let the engine do its stuff of its iteration, * before you read values, which will be changed by this iteration. */ void AlicaEngine::stepNotify() { this->setStepCalled(true); this->getPlanBase()->getStepModeCV()->notify_all(); } /** * If present, returns the ID corresponding to the given prototype. * Otherwise, it creates a new one, stores and returns it. * * This method can be used, e.g., for passing a part of a ROS * message and receiving a pointer to a corresponding AgentID object. */ AgentIDConstPtr AlicaEngine::getIdFromBytes(const std::vector<uint8_t>& idByteVector) const { return AgentIDConstPtr(this->agentIDManager->getIDFromBytes(idByteVector)); } } // namespace alica
27.598784
147
0.685573
carpe-noctem-cassel
49f1571c982a67dcac7b10394f0279546b656d05
841
cpp
C++
libraries/audio/src/AudioInjectorOptions.cpp
Adrianl3d/hifi
7bd01f606b768f6aa3e21d48959718ad249a3551
[ "Apache-2.0" ]
null
null
null
libraries/audio/src/AudioInjectorOptions.cpp
Adrianl3d/hifi
7bd01f606b768f6aa3e21d48959718ad249a3551
[ "Apache-2.0" ]
null
null
null
libraries/audio/src/AudioInjectorOptions.cpp
Adrianl3d/hifi
7bd01f606b768f6aa3e21d48959718ad249a3551
[ "Apache-2.0" ]
null
null
null
// // AudioInjectorOptions.cpp // libraries/audio/src // // Created by Stephen Birarda on 1/2/2014. // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "AudioInjectorOptions.h" AudioInjectorOptions::AudioInjectorOptions(QObject* parent) : QObject(parent), _position(0.0f, 0.0f, 0.0f), _volume(1.0f), _loop(false), _orientation(glm::vec3(0.0f, 0.0f, 0.0f)), _loopbackAudioInterface(NULL) { } AudioInjectorOptions::AudioInjectorOptions(const AudioInjectorOptions& other) { _position = other._position; _volume = other._volume; _loop = other._loop; _orientation = other._orientation; _loopbackAudioInterface = other._loopbackAudioInterface; }
26.28125
88
0.715815
Adrianl3d
49f8cb77ddc9cda152a65c6b539a4ae5f3182ed1
3,714
hpp
C++
MainGame/gameplay/SavedGame.hpp
JoaoBaptMG/ReboundTheGame
48c3d8b81de1f7fa7c622c3f815860257ccdba8e
[ "MIT" ]
63
2017-05-18T16:10:19.000Z
2022-03-26T18:05:59.000Z
MainGame/gameplay/SavedGame.hpp
JoaoBaptMG/ReboundTheGame
48c3d8b81de1f7fa7c622c3f815860257ccdba8e
[ "MIT" ]
1
2018-02-10T12:40:33.000Z
2019-01-11T07:33:13.000Z
MainGame/gameplay/SavedGame.hpp
JoaoBaptMG/ReboundTheGame
48c3d8b81de1f7fa7c622c3f815860257ccdba8e
[ "MIT" ]
4
2017-12-31T21:38:14.000Z
2019-11-20T15:13:00.000Z
// // Copyright (c) 2016-2018 João Baptista de Paula e Silva. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #pragma once #include <cstdint> #include <vector> #include <array> #include <assert.hpp> #include <SFML/System.hpp> #include <OutputStream.hpp> #include <VarLength.hpp> #include <streamReaders.hpp> #include <streamWriters.hpp> struct SavedGame { struct Key { uint64_t bitScramblingKey, aesGeneratorKey; }; uint8_t levelInfo; uint8_t goldenTokens[4], pickets[125], otherSecrets[2]; std::array<std::vector<bool>, 10> mapsRevealed; SavedGame(); size_t getCurLevel() const { return (size_t)levelInfo % 10 + 1; } size_t getAbilityLevel() const { return (size_t)levelInfo / 10; } void setCurLevel(size_t l) { ASSERT(l >= 1 && l <= 10); levelInfo = (uint8_t)((levelInfo / 10) * 10 + l - 1); } void setAbilityLevel(size_t l) { ASSERT(l >= 0 && l <= 10); levelInfo = uint8_t(l * 10 + levelInfo % 10); } bool getDoubleArmor() const { return otherSecrets[1] & 4; } void setDoubleArmor(bool da) { if (da) otherSecrets[1] |= 4; else otherSecrets[1] &= ~4; } bool getMoveRegen() const { return otherSecrets[1] & 8; } void setMoveRegen(bool mr) { if (mr) otherSecrets[1] |= 8; else otherSecrets[1] &= ~8; } bool getGoldenToken(size_t id) const { ASSERT(id < 30); return goldenTokens[id/8] & (1 << (id%8)); } void setGoldenToken(size_t id, bool collected) { ASSERT(id < 30); if (collected) goldenTokens[id/8] |= (1 << (id%8)); else goldenTokens[id/8] &= ~(1 << (id%8)); } bool getPicket(size_t id) const { ASSERT(id < 1000); return pickets[id>>3] & (1 << (id&7)); } void setPicket(size_t id, bool collected) { ASSERT(id < 1000); if (collected) pickets[id>>3] |= (1 << (id&7)); else pickets[id>>3] &= ~(1 << (id&7)); } size_t getGoldenTokenCount() const; size_t getPicketCount() const; size_t getPicketCountForLevel(size_t id) const; bool getUPart(size_t id) const { ASSERT(id < 10); return otherSecrets[id/8] & (1 << (id%8)); } void setUPart(size_t id, bool collected) { ASSERT(id < 10); if (collected) otherSecrets[id/8] |= (1 << (id%8)); else otherSecrets[id/8] &= ~(1 << (id%8)); } }; bool readEncryptedSaveFile(sf::InputStream& stream, SavedGame& savedGame, SavedGame::Key key); bool writeEncryptedSaveFile(OutputStream& stream, const SavedGame& savedGame, SavedGame::Key& key);
30.694215
99
0.635703
JoaoBaptMG
49fb4c69e792dd951d888bab71bca17d8ccc9350
668
hpp
C++
src/onthepitch/player/controller/strategies/offtheball/default_off.hpp
iloveooz/GameplayFootball
257a871de76b5096776e553cfe7abd39471f427a
[ "Unlicense" ]
177
2017-11-03T09:01:46.000Z
2022-03-30T13:52:00.000Z
src/onthepitch/player/controller/strategies/offtheball/default_off.hpp
congkay8/GameplayFootballx
eea12819257d428dc4dd0cc033501fb59bb5fbae
[ "Unlicense" ]
16
2017-11-06T22:38:43.000Z
2021-07-28T03:25:44.000Z
src/onthepitch/player/controller/strategies/offtheball/default_off.hpp
congkay8/GameplayFootballx
eea12819257d428dc4dd0cc033501fb59bb5fbae
[ "Unlicense" ]
48
2017-12-19T17:03:28.000Z
2022-03-09T08:11:34.000Z
// written by bastiaan konings schuiling 2008 - 2015 // this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important. // i do not offer support, so don't ask. to be used for inspiration :) #ifndef _HPP_STRATEGY_DEFAULT_OFFENSE #define _HPP_STRATEGY_DEFAULT_OFFENSE #include "../strategy.hpp" class DefaultOffenseStrategy : public Strategy { public: DefaultOffenseStrategy(ElizaController *controller); virtual ~DefaultOffenseStrategy(); virtual void RequestInput(const MentalImage *mentalImage, Vector3 &direction, float &velocity); protected: }; #endif
29.043478
133
0.747006
iloveooz
49fc009784837a6b4ab07f4d4c829bf99c16123c
6,001
cc
C++
content/browser/download/parallel_download_utils.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-05-24T13:52:28.000Z
2021-05-24T13:53:10.000Z
content/browser/download/parallel_download_utils.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/download/parallel_download_utils.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2018-03-12T07:58:10.000Z
2019-08-31T04:53:58.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/download/parallel_download_utils.h" #include "base/metrics/field_trial_params.h" #include "base/strings/string_number_conversions.h" #include "base/time/time.h" #include "content/public/browser/download_save_info.h" #include "content/public/common/content_features.h" namespace content { namespace { // Default value for |kMinSliceSizeFinchKey|, when no parameter is specified. const int64_t kMinSliceSizeParallelDownload = 2097152; // Default value for |kParallelRequestCountFinchKey|, when no parameter is // specified. const int kParallelRequestCount = 2; // The default remaining download time in seconds required for parallel request // creation. const int kDefaultRemainingTimeInSeconds = 10; // TODO(qinmin): replace this with a comparator operator in // DownloadItem::ReceivedSlice. bool compareReceivedSlices(const DownloadItem::ReceivedSlice& lhs, const DownloadItem::ReceivedSlice& rhs) { return lhs.offset < rhs.offset; } } // namespace std::vector<DownloadItem::ReceivedSlice> FindSlicesForRemainingContent( int64_t current_offset, int64_t total_length, int request_count, int64_t min_slice_size) { std::vector<DownloadItem::ReceivedSlice> new_slices; if (request_count > 0) { int64_t slice_size = std::max<int64_t>(total_length / request_count, min_slice_size); slice_size = slice_size > 0 ? slice_size : 1; for (int i = 0, num_requests = total_length / slice_size; i < num_requests - 1; ++i) { new_slices.emplace_back(current_offset, slice_size); current_offset += slice_size; } } // Last slice is a half open slice, which results in sending range request // like "Range:50-" to fetch from 50 bytes to the end of the file. new_slices.emplace_back(current_offset, DownloadSaveInfo::kLengthFullContent); return new_slices; } std::vector<DownloadItem::ReceivedSlice> FindSlicesToDownload( const std::vector<DownloadItem::ReceivedSlice>& received_slices) { std::vector<DownloadItem::ReceivedSlice> result; if (received_slices.empty()) { result.emplace_back(0, DownloadSaveInfo::kLengthFullContent); return result; } std::vector<DownloadItem::ReceivedSlice>::const_iterator iter = received_slices.begin(); DCHECK_GE(iter->offset, 0); if (iter->offset != 0) result.emplace_back(0, iter->offset); while (true) { int64_t offset = iter->offset + iter->received_bytes; std::vector<DownloadItem::ReceivedSlice>::const_iterator next = std::next(iter); if (next == received_slices.end()) { result.emplace_back(offset, DownloadSaveInfo::kLengthFullContent); break; } DCHECK_GE(next->offset, offset); if (next->offset > offset) result.emplace_back(offset, next->offset - offset); iter = next; } return result; } size_t AddOrMergeReceivedSliceIntoSortedArray( const DownloadItem::ReceivedSlice& new_slice, std::vector<DownloadItem::ReceivedSlice>& received_slices) { std::vector<DownloadItem::ReceivedSlice>::iterator it = std::upper_bound(received_slices.begin(), received_slices.end(), new_slice, compareReceivedSlices); if (it != received_slices.begin()) { std::vector<DownloadItem::ReceivedSlice>::iterator prev = std::prev(it); if (prev->offset + prev->received_bytes == new_slice.offset) { prev->received_bytes += new_slice.received_bytes; return static_cast<size_t>(std::distance(received_slices.begin(), prev)); } } it = received_slices.emplace(it, new_slice); return static_cast<size_t>(std::distance(received_slices.begin(), it)); } int64_t GetMinSliceSizeConfig() { std::string finch_value = base::GetFieldTrialParamValueByFeature( features::kParallelDownloading, kMinSliceSizeFinchKey); int64_t result; return base::StringToInt64(finch_value, &result) ? result : kMinSliceSizeParallelDownload; } int GetParallelRequestCountConfig() { std::string finch_value = base::GetFieldTrialParamValueByFeature( features::kParallelDownloading, kParallelRequestCountFinchKey); int result; return base::StringToInt(finch_value, &result) ? result : kParallelRequestCount; } base::TimeDelta GetParallelRequestDelayConfig() { std::string finch_value = base::GetFieldTrialParamValueByFeature( features::kParallelDownloading, kParallelRequestDelayFinchKey); int64_t time_ms = 0; return base::StringToInt64(finch_value, &time_ms) ? base::TimeDelta::FromMilliseconds(time_ms) : base::TimeDelta::FromMilliseconds(0); } base::TimeDelta GetParallelRequestRemainingTimeConfig() { std::string finch_value = base::GetFieldTrialParamValueByFeature( features::kParallelDownloading, kParallelRequestRemainingTimeFinchKey); int time_in_seconds = 0; return base::StringToInt(finch_value, &time_in_seconds) ? base::TimeDelta::FromSeconds(time_in_seconds) : base::TimeDelta::FromSeconds(kDefaultRemainingTimeInSeconds); } void DebugSlicesInfo(const DownloadItem::ReceivedSlices& slices) { DVLOG(1) << "Received slices size : " << slices.size(); for (const auto& it : slices) { DVLOG(1) << "Slice offset = " << it.offset << " , received_bytes = " << it.received_bytes; } } int64_t GetMaxContiguousDataBlockSizeFromBeginning( const DownloadItem::ReceivedSlices& slices) { std::vector<DownloadItem::ReceivedSlice>::const_iterator iter = slices.begin(); int64_t size = 0; while (iter != slices.end() && iter->offset == size) { size += iter->received_bytes; iter++; } return size; } bool IsParallelDownloadEnabled() { return base::FeatureList::IsEnabled(features::kParallelDownloading); } } // namespace content
35.093567
80
0.719547
metux
49fc46b7676097f8e4fbf75dd864a23a63f4bf13
1,871
cpp
C++
lxt/gfx/unit_tests/test_model.cpp
justinsaunders/luxatron
d474c21fb93b8ee9230ad25e6113d43873d75393
[ "MIT" ]
null
null
null
lxt/gfx/unit_tests/test_model.cpp
justinsaunders/luxatron
d474c21fb93b8ee9230ad25e6113d43873d75393
[ "MIT" ]
2
2017-06-08T21:51:34.000Z
2017-06-08T21:51:56.000Z
lxt/gfx/unit_tests/test_model.cpp
justinsaunders/luxatron
d474c21fb93b8ee9230ad25e6113d43873d75393
[ "MIT" ]
null
null
null
/* * test_model.cpp * test_runner * * Created by Justin on 16/04/09. * Copyright 2009 Monkey Style Games. All rights reserved. * */ #include <UnitTest++.h> #include "gfx/gfx.h" #include "core/archive.h" namespace { // DummyTexturePool just inserts a dummy texture, so it never has to be // "loaded". class DummyTexturePool : public Lxt::TexturePool { public: DummyTexturePool() { m_textures.insert( std::make_pair( "dummy.png", (Lxt::Texture*)NULL ) ); } }; struct Fixture { Fixture() { Lxt::Model::Node* node0 = new Lxt::Model::Node(); Lxt::Model::Node* node1 = new Lxt::Model::Node(); Lxt::Model::Node* node2 = new Lxt::Model::Node(); node1->m_children.push_back( node2 ); node0->m_children.push_back( node1 ); m_root = node0; } ~Fixture() { // don't delete meshes, they are owned by model. } Lxt::Model::Node* m_root; DummyTexturePool m_tp; }; } namespace Lxt { TEST_FIXTURE( Fixture, Model_NodesStoreExtract ) { // Store Archive a; size_t written = Model::Node::Store( m_root, m_tp, a ); // Extract Model::Node* n = NULL; size_t offset = 0; // Check Model::Node::Extract( n, m_tp, a, offset ); CHECK_EQUAL( written, offset ); CHECK( m_root->m_transform.Equal( n->m_transform ) ); CHECK_EQUAL( size_t(1), n->m_children.size() ); Model::Node* oldN = n; n = n->m_children[0]; CHECK_EQUAL( size_t(1), n->m_children.size() ); n = n->m_children[0]; CHECK_EQUAL( size_t(0), n->m_children.size() ); // stop leaks delete oldN; delete m_root; } TEST_FIXTURE( Fixture, Model_SimpleStoreExtract ) { Model m; m.SetRoot( m_root ); Archive a; size_t written = Model::Store( m, m_tp, a ); Model m2; size_t offset = 0; Model::Extract( m2, m_tp, a, offset); CHECK_EQUAL( written, offset ); } }
19.091837
75
0.622662
justinsaunders
49ff3070f01c393e688b6cc61368b2f06e032413
5,283
cpp
C++
src/stream/byte_stream.cpp
egranata/krakatau
866a26580e9890d5fb0961280b9827f347b3776e
[ "Apache-2.0" ]
13
2019-05-02T23:28:36.000Z
2021-04-04T02:38:01.000Z
src/stream/byte_stream.cpp
egranata/krakatau
866a26580e9890d5fb0961280b9827f347b3776e
[ "Apache-2.0" ]
28
2019-05-04T16:09:37.000Z
2019-06-18T02:03:50.000Z
src/stream/byte_stream.cpp
egranata/krakatau
866a26580e9890d5fb0961280b9827f347b3776e
[ "Apache-2.0" ]
1
2020-07-23T20:06:40.000Z
2020-07-23T20:06:40.000Z
// Copyright 2019 Google LLC // // 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 <stream/byte_stream.h> #include <sys/mman.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #include <sstream> ByteStream::ByteStream(const uint8_t* data, size_t sz) { mOffset = std::nullopt; mBasePointer = (uint8_t*)mmap(nullptr, sz, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_POPULATE, mFd = -1, 0); if (mBasePointer != MAP_FAILED) { memcpy(mBasePointer, data, mSize = sz); } else { mBasePointer = nullptr; mSize = 0; } } ByteStream::ByteStream(int fd, size_t sz) { mOffset = std::nullopt; mBasePointer = (uint8_t*)mmap(nullptr, sz, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_POPULATE, mFd = fd, 0); if (mBasePointer != MAP_FAILED) { mSize = sz; } else { mBasePointer = nullptr; mSize = 0; } } ByteStream::operator bool() { return mBasePointer != nullptr && mSize > 0; } std::unique_ptr<ByteStream> ByteStream::anonymous(const uint8_t* d, size_t s) { auto ptr = std::make_unique<ByteStream>(d, s); if (ptr && *ptr) return ptr; return nullptr; } std::unique_ptr<ByteStream> ByteStream::fromFile(int fd, size_t s) { if (s == 0) { struct stat st; int ok = fstat(fd, &st); if (ok == 0) s = st.st_size; } auto ptr = std::make_unique<ByteStream>(fd, s); if (ptr && *ptr) return ptr; return nullptr; } size_t ByteStream::peekOffset() const { if (mOffset.has_value()) return mOffset.value() + 1; return 0; } size_t ByteStream::incrementOffset() { if (mOffset.has_value()) mOffset = peekOffset(); else mOffset = 0; return mOffset.value(); } size_t ByteStream::size() const { return mSize; } bool ByteStream::eof() const { return mOffset.value_or(0) >= size(); } bool ByteStream::hasAtLeast(size_t n) const { if (eof()) return false; if (mOffset.has_value()) { if (mOffset.value() + n >= size()) return false; } else { if (n > size()) return false; } return true; } std::optional<uint8_t> ByteStream::peek() const { if (eof() || !hasAtLeast(1)) return std::nullopt; auto po = peekOffset(); return mBasePointer[po]; } std::optional<uint8_t> ByteStream::next() { if (eof()) return std::nullopt; auto no = incrementOffset(); if (eof()) return std::nullopt; return mBasePointer[no]; } bool ByteStream::nextIf(uint8_t b) { if (auto p = peek()) { if (p.value() == b) { incrementOffset(); return true; } } return false; } std::optional<uint8_t> ByteStream::nextIfNot(uint8_t b) { if (auto p = peek()) { if (p.value() == b) return std::nullopt; incrementOffset(); return p; } return std::nullopt; } std::pair<bool, std::vector<uint8_t>> ByteStream::readUntil(uint8_t b) { std::pair<bool, std::vector<uint8_t>> res = {false, {}}; while(true) { auto nv = next(); if (nv == std::nullopt) { res.first = false; break; } res.second.push_back(nv.value()); if (nv.value() == b) { res.first = true; break; } } return res; } std::optional<uint64_t> ByteStream::readNumber(size_t n) { if (eof() || !hasAtLeast(n)) return std::nullopt; uint64_t val = 0; while(n) { auto b = next(); if (b == std::nullopt) return std::nullopt; val = (val << 8) | b.value(); --n; } return val; } std::optional<std::string> ByteStream::readIdentifier(char marker) { if (eof()) return std::nullopt; if (peek() && peek().value() == marker) { next(); std::stringstream ss; while(true) { auto b = next(); if (b == std::nullopt) return std::nullopt; if (b.value() == marker) return ss.str(); ss << (char)b.value(); } } return std::nullopt; } std::optional<std::string> ByteStream::readData() { if (eof()) return std::nullopt; auto on = readNumber(); if (!on.has_value()) return std::nullopt; size_t n = on.value(); if (!hasAtLeast(n)) return std::nullopt; std::stringstream ss; for(size_t i = 0; i < n; ++i) { auto b = next(); if (b == std::nullopt) return std::nullopt; ss << (char)b.value(); } return ss.str(); } std::optional<bool> ByteStream::readBoolean() { if (eof()) return std::nullopt; auto on = readNumber(1); if (!on.has_value()) return std::nullopt; size_t n = on.value(); switch (n) { case 0: return false; case 1: return true; default: return std::nullopt; } }
24.802817
122
0.587166
egranata
b701dc946000c6a0c66e0baff00475bfcfbb4553
4,217
cpp
C++
utests/khttp_request_tests.cpp
ridgeware/dekaf2
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
[ "MIT" ]
null
null
null
utests/khttp_request_tests.cpp
ridgeware/dekaf2
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
[ "MIT" ]
null
null
null
utests/khttp_request_tests.cpp
ridgeware/dekaf2
b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33
[ "MIT" ]
1
2021-08-20T16:15:01.000Z
2021-08-20T16:15:01.000Z
#include "catch.hpp" #include <dekaf2/khttp_request.h> #include <dekaf2/krestserver.h> #include <dekaf2/kfilesystem.h> using namespace dekaf2; TEST_CASE("KHTTPRequest") { SECTION("KInHTTPRequestLine") { KInHTTPRequestLine RL; CHECK (RL.IsValid() == false); CHECK (RL.Get() == ""); CHECK (RL.GetMethod() == ""); CHECK (RL.GetResource()== ""); CHECK (RL.GetPath() == ""); CHECK (RL.GetQuery() == ""); CHECK (RL.GetVersion() == ""); auto Words = RL.Parse("GET /This/is/a/test?with=parameters HTTP/1.1"); CHECK (Words.size() == 3); CHECK (Words[0] == "GET"); CHECK (Words[1] == "/This/is/a/test?with=parameters"); CHECK (Words[2] == "HTTP/1.1"); CHECK (RL.IsValid() == true); CHECK (RL.Get() == "GET /This/is/a/test?with=parameters HTTP/1.1"); CHECK (RL.GetMethod() == "GET"); CHECK (RL.GetResource()== "/This/is/a/test?with=parameters"); CHECK (RL.GetPath() == "/This/is/a/test"); CHECK (RL.GetQuery() == "with=parameters"); CHECK (RL.GetVersion() == "HTTP/1.1"); Words = RL.Parse(" GET /This/is/a/test?with=parameters HTTP/1.1"); CHECK (Words.size() == 0); CHECK (RL.IsValid() == false); CHECK (RL.Get() == " GET /This/is/a/test?with=parameters HTTP/1.1"); CHECK (RL.GetMethod() == ""); CHECK (RL.GetResource()== ""); CHECK (RL.GetPath() == ""); CHECK (RL.GetQuery() == ""); CHECK (RL.GetVersion() == ""); Words = RL.Parse("GET /This/is/a/test?with=parameters HTTP/1.1"); CHECK (Words.size() == 0); CHECK (RL.IsValid() == false); CHECK (RL.Get() == "GET /This/is/a/test?with=parameters HTTP/1.1"); CHECK (RL.GetMethod() == ""); CHECK (RL.GetResource()== ""); CHECK (RL.GetPath() == ""); CHECK (RL.GetQuery() == ""); CHECK (RL.GetVersion() == ""); Words = RL.Parse("GET /This/is/a/test?with=parameters HTTP/1.1"); CHECK (Words.size() == 0); CHECK (RL.IsValid() == false); CHECK (RL.Get() == "GET /This/is/a/test?with=parameters HTTP/1.1"); CHECK (RL.GetMethod() == ""); CHECK (RL.GetResource()== ""); CHECK (RL.GetPath() == ""); CHECK (RL.GetQuery() == ""); CHECK (RL.GetVersion() == ""); Words = RL.Parse("GET /This/is/a/test?with=parametersHTTP/1.1"); CHECK (Words.size() == 0); CHECK (RL.IsValid() == false); CHECK (RL.Get() == "GET /This/is/a/test?with=parametersHTTP/1.1"); CHECK (RL.GetMethod() == ""); CHECK (RL.GetResource()== ""); CHECK (RL.GetPath() == ""); CHECK (RL.GetQuery() == ""); CHECK (RL.GetVersion() == ""); Words = RL.Parse("GET /This/is/a/test?with=parameters FTP/1.1"); CHECK (Words.size() == 0); CHECK (RL.IsValid() == false); CHECK (RL.Get() == "GET /This/is/a/test?with=parameters FTP/1.1"); CHECK (RL.GetMethod() == ""); CHECK (RL.GetResource()== ""); CHECK (RL.GetPath() == ""); CHECK (RL.GetQuery() == ""); CHECK (RL.GetVersion() == ""); KString sRequest; sRequest.assign(256, 'G'); sRequest += "GET /This/is/a/test?with=parameters HTTP/1.1"; Words = RL.Parse(sRequest); CHECK (Words.size() == 0); CHECK (RL.IsValid() == false); CHECK (RL.Get() == sRequest); CHECK (RL.GetMethod() == ""); CHECK (RL.GetResource()== ""); CHECK (RL.GetPath() == ""); CHECK (RL.GetQuery() == ""); CHECK (RL.GetVersion() == ""); sRequest = "GET "; sRequest.append(KInHTTPRequestLine::MAX_REQUESTLINELENGTH, '/'); sRequest += "/This/is/a/test?with=parameters HTTP/1.1"; Words = RL.Parse(sRequest); CHECK (Words.size() == 0); CHECK (RL.IsValid() == false); CHECK (RL.Get() == ""); CHECK (RL.GetMethod() == ""); CHECK (RL.GetResource()== ""); CHECK (RL.GetPath() == ""); CHECK (RL.GetQuery() == ""); CHECK (RL.GetVersion() == ""); sRequest = "GET /This/is/a/test?with=parameters HTTP/1.1"; sRequest.append(256, '1'); Words = RL.Parse(sRequest); CHECK (Words.size() == 0); CHECK (RL.IsValid() == false); CHECK (RL.Get() == sRequest); CHECK (RL.GetMethod() == ""); CHECK (RL.GetResource()== ""); CHECK (RL.GetPath() == ""); CHECK (RL.GetQuery() == ""); CHECK (RL.GetVersion() == ""); } }
33.468254
77
0.551103
ridgeware
8e661766facbb488208d7101765b298150ef640f
19,740
cc
C++
source/gpu_perf_api_dx11/dx11_gpa_implementor.cc
roobre/gpu_performance_api
948c67c6fd04222f6b4ee038a9b940f3fd60d0d9
[ "MIT" ]
null
null
null
source/gpu_perf_api_dx11/dx11_gpa_implementor.cc
roobre/gpu_performance_api
948c67c6fd04222f6b4ee038a9b940f3fd60d0d9
[ "MIT" ]
null
null
null
source/gpu_perf_api_dx11/dx11_gpa_implementor.cc
roobre/gpu_performance_api
948c67c6fd04222f6b4ee038a9b940f3fd60d0d9
[ "MIT" ]
null
null
null
//============================================================================== // Copyright (c) 2017-2020 Advanced Micro Devices, Inc. All rights reserved. /// \author AMD Developer Tools Team /// \file /// \brief DX11 GPA Implementation //============================================================================== #include <locale> #include <codecvt> #include <ADLUtil.h> #include "DeviceInfoUtils.h" #include "../gpu_perf_api_dx/dx_utils.h" #include "dx11_gpa_implementor.h" #include "dx11_gpa_context.h" #include "dx11_utils.h" #include "dxx_ext_utils.h" #include "utility.h" #include "dx_get_amd_device_info.h" #include "gpa_custom_hw_validation_manager.h" #include "gpa_common_defs.h" #include "gpa_counter_generator_dx11.h" #include "gpa_counter_generator_dx11_non_amd.h" #include "gpa_counter_scheduler_dx11.h" #include "dx11_include.h" IGPAImplementor* s_pGpaImp = DX11GPAImplementor::Instance(); static GPA_CounterGeneratorDX11 s_generatorDX11; ///< static instance of DX11 generator static GPA_CounterGeneratorDX11NonAMD s_generatorDX11NonAMD; ///< static instance of DX11 non-AMD generator static GPA_CounterSchedulerDX11 s_schedulerDX11; ///< static instance of DX11 scheduler GPA_API_Type DX11GPAImplementor::GetAPIType() const { return GPA_API_DIRECTX_11; } bool DX11GPAImplementor::GetHwInfoFromAPI(const GPAContextInfoPtr pContextInfo, GPA_HWInfo& hwInfo) const { bool isSuccess = false; IUnknown* pUnknownPtr = static_cast<IUnknown*>(pContextInfo); ID3D11Device* pD3D11Device = nullptr; if (DX11Utils::GetD3D11Device(pUnknownPtr, &pD3D11Device) && DX11Utils::IsFeatureLevelSupported(pD3D11Device)) { DXGI_ADAPTER_DESC adapterDesc; GPA_Status gpaStatus = DXGetAdapterDesc(pD3D11Device, adapterDesc); if (GPA_STATUS_OK == gpaStatus) { if (AMD_VENDOR_ID == adapterDesc.VendorId) { HMONITOR hMonitor = DXGetDeviceMonitor(pD3D11Device); if (nullptr != hMonitor) { if (GetAmdHwInfo(pD3D11Device, hMonitor, adapterDesc.VendorId, adapterDesc.DeviceId, hwInfo)) { isSuccess = true; } else { GPA_LogError("Unable to get hardware information."); } } else { GPA_LogError("Could not get device monitor description, hardware cannot be supported."); } } else if (NVIDIA_VENDOR_ID == adapterDesc.VendorId || INTEL_VENDOR_ID == adapterDesc.VendorId) { hwInfo.SetVendorID(adapterDesc.VendorId); hwInfo.SetDeviceID(adapterDesc.DeviceId); hwInfo.SetRevisionID(adapterDesc.Revision); std::wstring adapterNameW(adapterDesc.Description); std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> wideToUtf8Converter; std::string adapterName = wideToUtf8Converter.to_bytes(adapterNameW); hwInfo.SetDeviceName(adapterName.c_str()); if (NVIDIA_VENDOR_ID == adapterDesc.VendorId) { hwInfo.SetHWGeneration(GDT_HW_GENERATION_NVIDIA); } else if (INTEL_VENDOR_ID == adapterDesc.VendorId) { hwInfo.SetHWGeneration(GDT_HW_GENERATION_INTEL); } isSuccess = true; } else { std::stringstream ss; ss << "Unknown device adapter (vendorid=" << adapterDesc.VendorId << ", deviceid=" << adapterDesc.DeviceId << ", revision=" << adapterDesc.Revision << ")."; GPA_LogError(ss.str().c_str()); } } else { GPA_LogError("Unable to get adapter information."); } } else { GPA_LogError("Unable to get device or either device feature level is not supported."); } return isSuccess; } bool DX11GPAImplementor::VerifyAPIHwSupport(const GPAContextInfoPtr pContextInfo, const GPA_HWInfo& hwInfo) const { bool isSupported = false; IUnknown* pUnknownPtr = static_cast<IUnknown*>(pContextInfo); ID3D11Device* pD3D11Device = nullptr; if (DX11Utils::GetD3D11Device(pUnknownPtr, &pD3D11Device) && DX11Utils::IsFeatureLevelSupported(pD3D11Device)) { GPA_Status status = GPA_STATUS_OK; if (hwInfo.IsAMD()) { unsigned int majorVer = 0; unsigned int minorVer = 0; unsigned int subMinorVer = 0; ADLUtil_Result adlResult = AMDTADLUtils::Instance()->GetDriverVersion(majorVer, minorVer, subMinorVer); static const unsigned int MIN_MAJOR_VER = 16; static const unsigned int MIN_MINOR_VER_FOR_16 = 15; if ((ADL_SUCCESS == adlResult || ADL_WARNING == adlResult)) { if (majorVer < MIN_MAJOR_VER || (majorVer == MIN_MAJOR_VER && minorVer < MIN_MINOR_VER_FOR_16)) { GPA_LogError("Driver version 16.15 or newer is required."); if (0 != majorVer || 0 != minorVer || 0 != subMinorVer) { // This is an error status = GPA_STATUS_ERROR_DRIVER_NOT_SUPPORTED; } else { // This is a warning due to an unsigned driver } } } } else { GPA_HWInfo tempHwInfo = hwInfo; status = GPACustomHwValidationManager::Instance()->ValidateHW(pContextInfo, &tempHwInfo); } if (GPA_STATUS_OK == status) { isSupported = true; } } return isSupported; } IGPAContext* DX11GPAImplementor::OpenAPIContext(GPAContextInfoPtr pContextInfo, GPA_HWInfo& hwInfo, GPA_OpenContextFlags flags) { IUnknown* pUnknownPtr = static_cast<IUnknown*>(pContextInfo); ID3D11Device* pD3D11Device; IGPAContext* pRetGpaContext = nullptr; if (DX11Utils::GetD3D11Device(pUnknownPtr, &pD3D11Device) && DX11Utils::IsFeatureLevelSupported(pD3D11Device)) { DX11GPAContext* pDX11GpaContext = new (std::nothrow) DX11GPAContext(pD3D11Device, hwInfo, flags); if (nullptr != pDX11GpaContext) { if (pDX11GpaContext->Initialize()) { pRetGpaContext = pDX11GpaContext; } else { delete pDX11GpaContext; GPA_LogError("Unable to open a context."); } } } else { GPA_LogError("Hardware Not Supported."); } return pRetGpaContext; } bool DX11GPAImplementor::CloseAPIContext(GPADeviceIdentifier pDeviceIdentifier, IGPAContext* pContext) { assert(pDeviceIdentifier); assert(pContext); if (nullptr != pContext) { delete reinterpret_cast<DX11GPAContext*>(pContext); pContext = nullptr; } return (nullptr == pContext) && (nullptr != pDeviceIdentifier); } PFNAmdDxExtCreate11 DX11GPAImplementor::GetAmdExtFuncPointer() const { return m_amdDxExtCreate11FuncPtr; } bool DX11GPAImplementor::GetAmdHwInfo(ID3D11Device* pD3D11Device, HMONITOR hMonitor, const int& primaryVendorId, const int& primaryDeviceId, GPA_HWInfo& hwInfo) const { bool success = false; if (InitializeAmdExtFunction()) { PFNAmdDxExtCreate11 AmdDxExtCreate11 = m_amdDxExtCreate11FuncPtr; if (nullptr != AmdDxExtCreate11) { IAmdDxExt* pExt = nullptr; IAmdDxExtPerfProfile* pExtPerfProfile = nullptr; HRESULT hr = AmdDxExtCreate11(pD3D11Device, &pExt); if (SUCCEEDED(hr)) { unsigned int gpuIndex = 0; if (DxxExtUtils::IsMgpuPerfExtSupported(pExt)) { pExtPerfProfile = reinterpret_cast<IAmdDxExtPerfProfile*>(pExt->GetExtInterface(AmdDxExtPerfProfileID)); if (nullptr == pExtPerfProfile) { // only fail here if the primary device is a device that is supposed to support the PerfProfile extension. // Pre-GCN devices do not support this extension (they use the counter interface exposed by the API). // By not returning a failure here on older devices, the caller code will do the right thing on those devices. GDT_HW_GENERATION generation; if (AMDTDeviceInfoUtils::Instance()->GetHardwareGeneration(primaryDeviceId, generation) && generation >= GDT_HW_GENERATION_SOUTHERNISLAND) { GPA_LogError("Unable to get perf counter extension for GCN device."); } } else { PE_RESULT peResult = PE_OK; BOOL gpuProfileable = FALSE; while ((PE_OK == peResult) && (FALSE == gpuProfileable)) { peResult = pExtPerfProfile->IsGpuProfileable(gpuIndex, &gpuProfileable); gpuIndex++; } if (FALSE == gpuProfileable) { GPA_LogError("No profilable GPU device available."); } else { --gpuIndex; // gpu is over incremented in the loop above } } } hwInfo.SetGpuIndex(static_cast<unsigned int>(gpuIndex)); std::string strDLLName; if (GPAUtil::GetCurrentModulePath(strDLLName)) { int vendorId = primaryVendorId; int deviceId = primaryDeviceId; std::string dllName("GPUPerfAPIDXGetAMDDeviceInfo"); strDLLName.append(dllName); #ifdef X64 strDLLName.append("-x64"); #endif HMODULE hModule = 0; #ifdef _DEBUG // Attempt to load the debug version of the DLL if it exists { std::string debugDllName(strDLLName); debugDllName.append("-d"); debugDllName.append(".dll"); hModule = LoadLibraryA(debugDllName.c_str()); } #endif if (nullptr == hModule) { strDLLName.append(".dll"); hModule = LoadLibraryA(strDLLName.c_str()); } if (nullptr != hModule) { static const char* pEntryPointName = "DXGetAMDDeviceInfo"; typedef decltype(DXGetAMDDeviceInfo)* DXGetAMDDeviceInfo_FuncType; DXGetAMDDeviceInfo_FuncType DXGetAMDDeviceInfoFunc = reinterpret_cast<DXGetAMDDeviceInfo_FuncType>(GetProcAddress(hModule, pEntryPointName)); if (nullptr != DXGetAMDDeviceInfoFunc) { // NOTE: DXGetAMDDeviceInfo is failing on system with Baffin and Fiji system, driver version Radeon Software Version 17.12.2 // Previous Implementation of the DX11 GPA was also not relying on it successful operation. // TODO: Track down why AMD extension function under DXGetAMDDeviceInfo is failing DXGetAMDDeviceInfoFunc(hMonitor, vendorId, deviceId); } else { std::string strLogErrorMsg = "Entry point '"; strLogErrorMsg.append(pEntryPointName); strLogErrorMsg.append("' could not be found in "); strLogErrorMsg.append(strDLLName); strLogErrorMsg.append("."); GPA_LogError(strLogErrorMsg.c_str()); } } else { GPA_LogError("Unable to load the get device info dll."); } AsicInfoList asicInfoList; AMDTADLUtils::Instance()->GetAsicInfoList(asicInfoList); for (AsicInfoList::iterator asicInfoIter = asicInfoList.begin(); asicInfoList.end() != asicInfoIter; ++asicInfoIter) { if ((asicInfoIter->vendorID == vendorId) && (asicInfoIter->deviceID == deviceId)) { hwInfo.SetVendorID(asicInfoIter->vendorID); hwInfo.SetDeviceID(asicInfoIter->deviceID); hwInfo.SetRevisionID(asicInfoIter->revID); hwInfo.SetDeviceName(asicInfoIter->adapterName.c_str()); hwInfo.SetHWGeneration(GDT_HW_GENERATION_NONE); GDT_HW_GENERATION hwGeneration; if (AMDTDeviceInfoUtils::Instance()->GetHardwareGeneration(asicInfoIter->deviceID, hwGeneration)) { hwInfo.SetHWGeneration(hwGeneration); UINT64 deviceFrequency = 0ull; if (!DX11Utils::GetTimestampFrequency(pD3D11Device, deviceFrequency)) { GPA_LogError("GetTimestampFrequency failed"); if (nullptr != pExtPerfProfile) { pExtPerfProfile->Release(); } if (nullptr != pExt) { pExt->Release(); } return false; } hwInfo.SetTimeStampFrequency(deviceFrequency); } unsigned int majorVer = 0; unsigned int minorVer = 0; unsigned int subMinorVer = 0; ADLUtil_Result adlResult = AMDTADLUtils::Instance()->GetDriverVersion(majorVer, minorVer, subMinorVer); static const unsigned int MIN_MAJOR_VER = 19; static const unsigned int MIN_MINOR_VER_FOR_30 = 30; if ((ADL_SUCCESS == adlResult || ADL_WARNING == adlResult)) { if (majorVer >= MIN_MAJOR_VER && minorVer >= MIN_MINOR_VER_FOR_30) { if (nullptr != pExt) { IAmdDxExtASICInfo* pExtAsicInfo = reinterpret_cast<IAmdDxExtASICInfo*>(pExt->GetExtInterface(AmdDxExtASICInfoID)); if (nullptr != pExtAsicInfo) { AmdDxASICInfoParam infoParam = {}; AmdDxASICInfo* pNewAsicInfo = new (std::nothrow) AmdDxASICInfo(); if (nullptr != pNewAsicInfo) { infoParam.pASICInfo = pNewAsicInfo; pExtAsicInfo->GetInfoData(&infoParam); if (nullptr != infoParam.pASICInfo && gpuIndex < infoParam.pASICInfo->gpuCount) { AmdDxASICInfoHWInfo asicInfo = infoParam.pASICInfo->hwInfo[gpuIndex]; hwInfo.SetNumberCUs(asicInfo.totalCU); hwInfo.SetNumberShaderEngines(asicInfo.numShaderEngines); hwInfo.SetNumberShaderArrays(asicInfo.numShaderArraysPerSE); hwInfo.SetNumberSIMDs(asicInfo.totalCU * asicInfo.numSimdsPerCU); } delete pNewAsicInfo; } pExtAsicInfo->Release(); } } } } success = true; break; } } } else { GPA_LogError("Unable to get the module path."); } if (nullptr != pExtPerfProfile) { pExtPerfProfile->Release(); } if (nullptr != pExt) { pExt->Release(); } } else { GPA_LogError("Unable to create DX11 extension."); } } else { GPA_LogError("Unable to initialize because extension creation is not available."); } } else { #ifdef X64 GPA_LogError("Unable to initialize because 'atidxx64.dll' is not available."); #else GPA_LogError("Unable to initialize because 'atidxx32.dll' is not available."); #endif } return success; } DX11GPAImplementor::DX11GPAImplementor() : m_amdDxExtCreate11FuncPtr(nullptr) { } bool DX11GPAImplementor::InitializeAmdExtFunction() const { bool success = false; if (nullptr == m_amdDxExtCreate11FuncPtr) { HMODULE hDxxDll = nullptr; #ifdef X64 hDxxDll = ::GetModuleHandleW(L"atidxx64.dll"); #else hDxxDll = ::GetModuleHandleW(L"atidxx32.dll"); #endif if (nullptr != hDxxDll) { PFNAmdDxExtCreate11 AmdDxExtCreate11 = reinterpret_cast<PFNAmdDxExtCreate11>(GetProcAddress(hDxxDll, "AmdDxExtCreate11")); if (nullptr != AmdDxExtCreate11) { m_amdDxExtCreate11FuncPtr = AmdDxExtCreate11; success = true; } } } else { success = true; } return success; } GPADeviceIdentifier DX11GPAImplementor::GetDeviceIdentifierFromContextInfo(GPAContextInfoPtr pContextInfo) const { return static_cast<IUnknown*>(pContextInfo); }
38.705882
154
0.496454
roobre
8e68c5de4e49a1a0e094ae51daa5a6be2ca4ac42
1,434
cpp
C++
OVP/D3D7Client/MeshMgr.cpp
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
1,040
2021-07-27T12:12:06.000Z
2021-08-02T14:24:49.000Z
OVP/D3D7Client/MeshMgr.cpp
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
20
2021-07-27T12:25:22.000Z
2021-08-02T12:22:19.000Z
OVP/D3D7Client/MeshMgr.cpp
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
71
2021-07-27T14:19:49.000Z
2021-08-02T05:51:52.000Z
// Copyright (c) Martin Schweiger // Licensed under the MIT License // ============================================================== // ORBITER VISUALISATION PROJECT (OVP) // D3D7 Client module // ============================================================== // ============================================================== // MeshMgr.cpp // class MeshManager (implementation) // // Simple management of persistent mesh templates // ============================================================== #include "Meshmgr.h" using namespace oapi; MeshManager::MeshManager (const D3D7Client *gclient) { gc = gclient; nmlist = nmlistbuf = 0; } MeshManager::~MeshManager () { Flush(); } void MeshManager::Flush () { int i; for (i = 0; i < nmlist; i++) delete mlist[i].mesh; if (nmlistbuf) { delete []mlist; nmlist = nmlistbuf = 0; } } void MeshManager::StoreMesh (MESHHANDLE hMesh) { if (GetMesh (hMesh)) return; // mesh already stored if (nmlist == nmlistbuf) { // need to allocate buffer MeshBuffer *tmp = new MeshBuffer[nmlistbuf += 32]; if (nmlist) { memcpy (tmp, mlist, nmlist*sizeof(MeshBuffer)); delete []mlist; } mlist = tmp; } mlist[nmlist].hMesh = hMesh; mlist[nmlist].mesh = new D3D7Mesh (gc, hMesh, true); nmlist++; } const D3D7Mesh *MeshManager::GetMesh (MESHHANDLE hMesh) { int i; for (i = 0; i < nmlist; i++) if (mlist[i].hMesh == hMesh) return mlist[i].mesh; return NULL; }
21.727273
65
0.545328
Ybalrid
8e6d0304b47c03f2db491d115412c97994ee9042
781
cpp
C++
tests/test_Simulation.cpp
lbowes/falcon-9-simulation
dd65a2daf8386c3a874766d73b1fc1efb334b843
[ "MIT" ]
5
2020-07-28T21:26:23.000Z
2021-11-02T14:11:41.000Z
tests/test_Simulation.cpp
lbowes/Falcon-9-Simulation
dd65a2daf8386c3a874766d73b1fc1efb334b843
[ "MIT" ]
36
2020-06-28T18:47:14.000Z
2020-10-11T09:45:39.000Z
tests/test_Simulation.cpp
lbowes/falcon-9-simulation
dd65a2daf8386c3a874766d73b1fc1efb334b843
[ "MIT" ]
1
2020-01-14T17:07:57.000Z
2020-01-14T17:07:57.000Z
#include "../3rd_party/catch.hpp" #include "Simulation.h" #include <fstream> static const char* outputFile = "output.json"; static bool fileExists(const char* file) { std::ifstream f(file); return f.good(); } static bool fileEmpty(const char* file) { std::ifstream f(file); return f.peek() == std::ifstream::traits_type::eof(); } SCENARIO("Running a simulation", "[Simulation]") { GIVEN("A simulation instance") { F9Sim::Physics::Simulation sim; WHEN("The simulation is run") { sim.run(); THEN("Output file exists") { REQUIRE(fileExists(outputFile)); } THEN("Output file is not empty") { REQUIRE(!fileEmpty(outputFile)); } } } }
20.025641
57
0.569782
lbowes
8e6da4989768f7e0aba7446a6aabff2d32522ac0
2,300
cpp
C++
tests/Cases/LowLevel/ProtocolTypes/TestProtocolVint.cpp
cpv-project/cpv-cql-driver
66eebfd4e9ec75dc49cd4a7073a51a830236807a
[ "MIT" ]
41
2018-01-23T09:27:32.000Z
2021-02-15T15:49:07.000Z
tests/Cases/LowLevel/ProtocolTypes/TestProtocolVint.cpp
cpv-project/cpv-cql-driver
66eebfd4e9ec75dc49cd4a7073a51a830236807a
[ "MIT" ]
20
2018-01-25T04:25:48.000Z
2019-03-09T02:49:41.000Z
tests/Cases/LowLevel/ProtocolTypes/TestProtocolVint.cpp
cpv-project/cpv-cql-driver
66eebfd4e9ec75dc49cd4a7073a51a830236807a
[ "MIT" ]
5
2018-04-10T12:19:13.000Z
2020-02-17T03:30:50.000Z
#include <CQLDriver/Common/Exceptions/DecodeException.hpp> #include <LowLevel/ProtocolTypes/ProtocolVint.hpp> #include <TestUtility/GTestUtils.hpp> TEST(TestProtocolVint, getset) { cql::ProtocolVint value(1); ASSERT_EQ(value.get(), 1); value.set(0x7fff0000aaaaeeee); ASSERT_EQ(value.get(), static_cast<std::int64_t>(0x7fff0000aaaaeeee)); value = cql::ProtocolVint(-3); ASSERT_EQ(value.get(), -3); } TEST(TestProtocolVint, encode) { { cql::ProtocolVint value(0x7fff0000aaaaeeee); std::string data; value.encode(data); ASSERT_EQ(data, makeTestString("\xff\xff\xfe\x00\x01\x55\x55\xdd\xdc")); } { cql::ProtocolVint value(3); std::string data; value.encode(data); ASSERT_EQ(data, makeTestString("\x06")); } { cql::ProtocolVint value(-3); std::string data; value.encode(data); ASSERT_EQ(data, makeTestString("\x05")); } { cql::ProtocolVint value(-0x7f238a); std::string data; value.encode(data); ASSERT_EQ(data, makeTestString("\xe0\xfe\x47\x13")); } } TEST(TestProtocolVint, decode) { cql::ProtocolVint value(0); { auto data = makeTestString("\xff\xff\xfe\x00\x01\x55\x55\xdd\xdc"); auto ptr = data.c_str(); auto end = ptr + data.size(); value.decode(ptr, end); ASSERT_TRUE(ptr == end); ASSERT_EQ(value.get(), 0x7fff0000aaaaeeee); } { auto data = makeTestString("\x06"); auto ptr = data.c_str(); auto end = ptr + data.size(); value.decode(ptr, end); ASSERT_TRUE(ptr == end); ASSERT_EQ(value.get(), 3); } { auto data = makeTestString("\x05"); auto ptr = data.c_str(); auto end = ptr + data.size(); value.decode(ptr, end); ASSERT_TRUE(ptr == end); ASSERT_EQ(value.get(), -3); } { auto data = makeTestString("\xe0\xfe\x47\x13"); auto ptr = data.c_str(); auto end = ptr + data.size(); value.decode(ptr, end); ASSERT_TRUE(ptr == end); ASSERT_EQ(value.get(), -0x7f238a); } } TEST(TestProtocolVint, decodeError) { { cql::ProtocolVint value(0); std::string data(""); auto ptr = data.c_str(); auto end = ptr + data.size(); ASSERT_THROWS(cql::DecodeException, value.decode(ptr, end)); } { cql::ProtocolVint value(0); auto data = makeTestString("\xe0\xfe\x47"); auto ptr = data.c_str(); auto end = ptr + data.size(); ASSERT_THROWS(cql::DecodeException, value.decode(ptr, end)); } }
24.210526
74
0.668696
cpv-project
8e73356133631180413a6a6a9a02b0d4aa600ec9
3,152
cpp
C++
Core/src/global.cpp
dimitar-asenov/Envision
1ab5c846fca502b7fe73ae4aff59e8746248446c
[ "BSD-3-Clause" ]
75
2015-01-18T13:29:43.000Z
2022-01-14T08:02:01.000Z
Core/src/global.cpp
dimitar-asenov/Envision
1ab5c846fca502b7fe73ae4aff59e8746248446c
[ "BSD-3-Clause" ]
364
2015-01-06T10:20:21.000Z
2018-12-17T20:12:28.000Z
Core/src/global.cpp
dimitar-asenov/Envision
1ab5c846fca502b7fe73ae4aff59e8746248446c
[ "BSD-3-Clause" ]
14
2015-01-09T00:44:24.000Z
2022-02-22T15:01:44.000Z
/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "global.h" QString SystemCommandResult::standardoutOneLine() const { Q_ASSERT(standardout_.size() == 1); return standardout_.first(); } SystemCommandResult::operator QString() const { Q_ASSERT(exitCode() == 0); Q_ASSERT(standarderr_.size() == 0); return standardoutOneLine(); } SystemCommandResult::operator QStringList() const { Q_ASSERT(exitCode() == 0); Q_ASSERT(standarderr_.size() == 0); return standardout_; } SystemCommandResult runSystemCommand(const QString& program, const QStringList& arguments, const QString& workingDirectory) { QProcess process; process.setProgram(program); if (!arguments.isEmpty()) process.setArguments(arguments); if (!workingDirectory.isNull()) process.setWorkingDirectory(workingDirectory); process.start(); process.waitForFinished(); SystemCommandResult result; result.exitCode_ = process.exitCode(); auto EOLRegex = QRegularExpression{"(\\r\\n|\\r|\\n)"}; result.standardout_ = QString{process.readAllStandardOutput()}.split(EOLRegex); if (!result.standardout_.isEmpty() && result.standardout_.last().isEmpty()) result.standardout_.removeLast(); result.standarderr_ = QString{process.readAllStandardError()}.split(EOLRegex); if (!result.standarderr_.isEmpty() && result.standarderr_.last().isEmpty()) result.standarderr_.removeLast(); return result; }
45.028571
120
0.703046
dimitar-asenov
8e73c340a916df129e7692a9710290f863693c31
2,395
hpp
C++
SpaceBomber/Linux/graph/Splash.hpp
667MARTIN/Epitech
81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e
[ "MIT" ]
40
2018-01-28T14:23:27.000Z
2022-03-05T15:57:47.000Z
SpaceBomber/Linux/graph/Splash.hpp
667MARTIN/Epitech
81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e
[ "MIT" ]
1
2021-10-05T09:03:51.000Z
2021-10-05T09:03:51.000Z
SpaceBomber/Linux/graph/Splash.hpp
667MARTIN/Epitech
81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e
[ "MIT" ]
73
2019-01-07T18:47:00.000Z
2022-03-31T08:48:38.000Z
// // Splash.hpp for hey in /home/cailla_o/Work/C++/cpp_indie_studio/graph // // Made by Oihan Caillaud // Login <cailla_o@epitech.net> // // Started on Mon May 30 10:11:42 2016 Oihan Caillaud // Last update Thu Jun 2 00:14:21 2016 // Last update Tue May 31 11:42:52 2016 // #ifndef SPLASH_HPP_ #define SPLASH_HPP_ #define TEMP 20000 #include "irrlicht-1.8.3/include/irrlicht.h" #include "irrlicht.hpp" #include "MyEventReceiver.hpp" class Mesh; class MyEventReceiver; class Splash { private: MyEventReceiver* hey; irr::IrrlichtDevice* device; irr::video::IVideoDriver* driver; irr::scene::ISceneManager* smgr; irr::gui::IGUIEnvironment* guienv; irr::video::ITexture *image; irrklang::ISoundEngine* engine; irr::core::dimension2d<irr::u32> taille; irr::core::position2d<irr::s32> position0; irr::core::position2d<irr::s32> position1; irr::core::rect<irr::s32> rectangle; public: Splash(); ~Splash() {}; void setWallpaper(irr::io::path wallpaper, irr::video::IVideoDriver* driver); void drawWallpaper(irr::video::IVideoDriver* driver); void Draw(irr::video::IVideoDriver* driver); void draw_j(); void draw_f(); Mesh *Planet(float, float); void draw_a(); void draw_a2(); void draw_g(); void draw_o(); MyEventReceiver *getHey() const; irr::IrrlichtDevice* getDevice()const; irr::video::IVideoDriver* getDriver()const; irr::scene::ISceneManager* getSmgr()const; irr::gui::IGUIEnvironment* getGuienv()const; irr::video::ITexture * getImage()const; irr::core::dimension2d<irr::u32> getTaille()const; irr::core::position2d<irr::s32> getPosition0()const; irr::core::position2d<irr::s32> getPosition1()const; irr::core::rect<irr::s32> getRectangle()const; irrklang::ISoundEngine* getEngine() const; void setHey(MyEventReceiver *const _hey); void setDevice(irr::IrrlichtDevice*); void setDriver(irr::video::IVideoDriver* const); void setSmgr(irr::scene::ISceneManager* const); void setGuienv(irr::gui::IGUIEnvironment* const); void setImage(irr::video::ITexture *const ); void setTaille(irr::core::dimension2d<irr::u32> const &); void setPosition0(irr::core::position2d<irr::s32> const &); void setPosition1(irr::core::position2d<irr::s32> const &); void setRectangle(irr::core::rect<irr::s32> const &); void setEngine(irrklang::ISoundEngine* const); }; void do_splash(Splash *thi); #endif
30.705128
80
0.7119
667MARTIN
8e74c6d36bab66a364db7720133d1d6155667a5a
360
cpp
C++
Stereolabs/Source/Stereolabs/Private/Threading/StereolabsRunnable.cpp
stereolabs/zed-unreal-plugin
0fabf29edc84db1126f0c4f73b9ce501e322be96
[ "MIT" ]
38
2018-02-27T22:53:56.000Z
2022-02-10T05:46:51.000Z
Stereolabs/Source/Stereolabs/Private/Threading/StereolabsRunnable.cpp
HuangArmagh/zed-unreal-plugin
3bd8872577f49e2eb5f6cb8a6a610a4c786f6104
[ "MIT" ]
14
2018-05-26T03:15:16.000Z
2022-03-02T14:34:10.000Z
Stereolabs/Source/Stereolabs/Private/Threading/StereolabsRunnable.cpp
HuangArmagh/zed-unreal-plugin
3bd8872577f49e2eb5f6cb8a6a610a4c786f6104
[ "MIT" ]
16
2018-01-23T22:55:34.000Z
2021-12-20T18:34:08.000Z
//======= Copyright (c) Stereolabs Corporation, All rights reserved. =============== #include "StereolabsPrivatePCH.h" #include "Stereolabs/Public/Threading/StereolabsRunnable.h" FSlRunnable::FSlRunnable() : Thread(nullptr), bIsRunning(false), bIsPaused(false), bIsSleeping(false) { } FSlRunnable::~FSlRunnable() { delete Thread; Thread = nullptr; }
18
84
0.705556
stereolabs
8e7744dd7d2cee3e4e72f48a233d862b6f13e346
6,891
cpp
C++
src/xray/engine/sources/engine_world_editor.cpp
ixray-team/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
3
2021-10-30T09:36:14.000Z
2022-03-26T17:00:06.000Z
src/xray/engine/sources/engine_world_editor.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
null
null
null
src/xray/engine/sources/engine_world_editor.cpp
acidicMercury8/ixray-2.0
85c3a544175842323fc82f42efd96c66f0fc5abb
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:08.000Z
2022-03-26T17:00:08.000Z
//////////////////////////////////////////////////////////////////////////// // Created : 17.06.2009 // Author : Dmitriy Iassenev // Copyright (C) GSC Game World - 2009 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #include "engine_world.h" #include "rpc.h" #include <xray/render/base/engine_renderer.h> #include <xray/editor/world/api.h> #include <xray/editor/world/world.h> #include <xray/editor/world/library_linkage.h> #include <boost/bind.hpp> #include <xray/core/core.h> #include <xray/sound/world.h> #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360 # include <xray/os_preinclude.h> # undef NOUSER # undef NOMSG # undef NOMB # include <xray/os_include.h> # include <objbase.h> // for COINIT_MULTITHREADED static HMODULE s_editor_module = 0; static xray::editor::create_world_ptr s_create_world = 0; static xray::editor::destroy_world_ptr s_destroy_world = 0; static xray::editor::memory_allocator_ptr s_memory_allocator = 0; static xray::editor::property_holder* s_holder = 0; #endif // #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360 using xray::engine::engine_world; void engine_world::try_load_editor ( ) { #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360 R_ASSERT ( !s_editor_module ); s_editor_module = LoadLibrary( XRAY_EDITOR_FILE_NAME ); if (!s_editor_module) { LOG_WARNING ( "cannot load library \"%s\"", XRAY_EDITOR_FILE_NAME ); return; } #if XRAY_PLATFORM_WINDOWS_32 && defined(DEBUG) xray::debug::enable_fpe ( false ); #endif // #if XRAY_PLATFORM_WINDOWS_32 R_ASSERT ( !s_create_world ); s_create_world = (xray::editor::create_world_ptr)GetProcAddress(s_editor_module, "create_world"); R_ASSERT ( s_create_world ); R_ASSERT ( !s_destroy_world ); s_destroy_world = (xray::editor::destroy_world_ptr)GetProcAddress(s_editor_module, "destroy_world"); R_ASSERT ( s_destroy_world ); R_ASSERT ( !s_memory_allocator); s_memory_allocator = (xray::editor::memory_allocator_ptr)GetProcAddress(s_editor_module, "memory_allocator"); R_ASSERT ( s_memory_allocator ); s_memory_allocator ( m_editor_allocator ); // this function cannot be called before s_memory_allocator function called // because of a workaround of BugTrapN initialization from unmanaged code debug::change_bugtrap_usage ( core::debug::error_mode_verbose, core::debug::managed_bugtrap ); R_ASSERT ( !m_editor ); m_editor = s_create_world ( *this ); R_ASSERT ( m_editor ); R_ASSERT ( !m_window_handle ); m_window_handle = m_editor->view_handle( ); R_ASSERT ( m_window_handle ); R_ASSERT ( !m_main_window_handle ); m_main_window_handle = m_editor->main_handle( ); R_ASSERT ( m_main_window_handle ); m_editor->load ( ); #else // #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360 UNREACHABLE_CODE ( ); #endif // #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360 } void engine_world::unload_editor ( ) { #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360 ASSERT ( m_editor ); ASSERT ( s_destroy_world ); s_destroy_world ( m_editor ); ASSERT ( !m_editor ); ASSERT ( s_editor_module ); FreeLibrary ( s_editor_module ); s_editor_module = 0; s_destroy_world = 0; s_create_world = 0; #else // #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360 UNREACHABLE_CODE ( ); #endif // #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360 } void engine_world::initialize_editor ( ) { if( !command_line_editor() ) return; m_game_enabled = false; if( threading::core_count( ) == 1 ) { try_load_editor ( ); return; } rpc::assign_thread_id ( rpc::editor, u32(-1) ); threading::spawn ( boost::bind( &engine_world::editor, this ), !command_line_editor_singlethread( ) ? "editor" : "editor + logic", !command_line_editor_singlethread( ) ? "editor" : "editor + logic", 0, 0 ); rpc::run ( rpc::editor, boost::bind( &engine_world::try_load_editor, this), rpc::break_process_loop, rpc::dont_wait_for_completion ); } void engine_world::initialize_editor_thread_ids ( ) { m_editor_allocator.user_current_thread_id ( ); m_processed_editor.set_pop_thread_id ( ); render_world().editor().set_command_push_thread_id ( ); render_world().editor().initialize_command_queue ( XRAY_NEW_IMPL( m_editor_allocator, command_type_impl) ); } void engine_world::editor ( ) { #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360 CoInitializeEx ( 0, COINIT_APARTMENTTHREADED ); #endif // #if XRAY_PLATFORM_WINDOWS | XRAY_PLATFORM_XBOX_360 rpc::assign_thread_id ( rpc::editor, threading::current_thread_id( ) ); rpc::process ( rpc::editor ); rpc::process ( rpc::editor ); m_editor->run ( ); if (!m_destruction_started) exit ( 0 ); if ( rpc::is_same_thread(rpc::logic) ) rpc::process ( rpc::logic ); rpc::process ( rpc::editor ); } void engine_world::draw_frame_editor ( ) { render_world().editor().set_command_processor_frame_id( render_world( ).engine().frame_id() + 1 ); m_editor_frame_ended = true; if( m_logic_frame_ended || !m_game_enabled || m_game_enabled == m_game_paused_last ) { render_world( ).engine().draw_frame ( ); m_logic_frame_ended = false; m_editor_frame_ended = false; m_game_paused_last = !m_game_enabled; } } void engine_world::delete_processed_editor_orders ( bool destroying ) { delete_processed_orders ( m_processed_editor, m_editor_allocator, m_editor_frame_id, destroying ); } bool engine_world::on_before_editor_tick ( ) { if ( threading::core_count( ) == 1 ) tick ( ); else { m_render_world->engine().test_cooperative_level(); static bool editor_singlethreaded = command_line_editor_singlethread ( ); if ( editor_singlethreaded ) { logic_tick ( ); } else { if ( m_editor_frame_id > m_render_world->engine().frame_id() + 1 ) return false; } } delete_processed_editor_orders ( false ); return true; } void engine_world::on_after_editor_tick ( ) { if ( threading::core_count( ) == 1 ) { ++m_editor_frame_id; return; } if( !command_line_editor_singlethread() ) { ++m_editor_frame_id; return; } while ( ( m_logic_frame_id > m_render_world->engine().frame_id( ) + 1 ) && !m_destruction_started ) { m_render_world->engine().test_cooperative_level(); threading::yield ( 0 ); } // ++m_logic_frame_id; ++m_editor_frame_id; } void engine_world::enter_editor_mode ( ) { if ( !m_editor ) return; m_editor->editor_mode ( true ); } void engine_world::editor_clear_resources ( ) { if ( !m_editor ) return; resources::dispatch_callbacks ( ); // m_editor->clear_resources ( ); m_sound_world->clear_editor_resources( ); }
28.475207
111
0.681759
ixray-team
8e7f1d33373959812148cf82e370019cbcb8c484
3,553
cpp
C++
Diagram/DiagramTextItem.cpp
devonchenc/NovaImage
3d17166f9705ba23b89f1aefd31ac2db97385b1c
[ "MIT" ]
null
null
null
Diagram/DiagramTextItem.cpp
devonchenc/NovaImage
3d17166f9705ba23b89f1aefd31ac2db97385b1c
[ "MIT" ]
null
null
null
Diagram/DiagramTextItem.cpp
devonchenc/NovaImage
3d17166f9705ba23b89f1aefd31ac2db97385b1c
[ "MIT" ]
null
null
null
#include "DiagramTextItem.h" #include <QDebug> #include <QTextCursor> #include "../Core/GlobalFunc.h" DiagramTextItem::DiagramTextItem(QGraphicsItem* parent) : QGraphicsTextItem(parent) { setFlag(QGraphicsItem::ItemIsMovable); setFlag(QGraphicsItem::ItemIsSelectable); _positionLastTime = QPointF(0, 0); } DiagramTextItem* DiagramTextItem::clone() { DiagramTextItem* cloned = new DiagramTextItem(nullptr); cloned->setPlainText(toPlainText()); cloned->setFont(font()); cloned->setTextWidth(textWidth()); cloned->setDefaultTextColor(defaultTextColor()); cloned->setPos(scenePos()); cloned->setZValue(zValue()); return cloned; } QDomElement DiagramTextItem::saveToXML(QDomDocument& doc) { QDomElement lineItem = doc.createElement("GraphicsItem"); lineItem.setAttribute("Type", "DiagramTextItem"); QDomElement attribute = doc.createElement("Attribute"); attribute.setAttribute("Text", toPlainText()); attribute.setAttribute("Position", pointFToString(pos())); attribute.setAttribute("DefaultTextColor", colorToString(defaultTextColor())); attribute.setAttribute("Font", font().family()); attribute.setAttribute("PointSize", QString::number(font().pointSize())); attribute.setAttribute("Weight", QString::number(font().weight())); attribute.setAttribute("Italic", QString::number(font().italic())); attribute.setAttribute("Underline", QString::number(font().underline())); lineItem.appendChild(attribute); return lineItem; } void DiagramTextItem::loadFromXML(const QDomElement& e) { setPlainText(e.attribute("Text")); setPos(stringToPointF(e.attribute("Position"))); setDefaultTextColor(stringToColor(e.attribute("DefaultTextColor"))); QFont font = this->font(); font.setFamily(e.attribute("Font")); font.setPointSize(e.attribute("PointSize").toInt()); font.setWeight(e.attribute("Weight").toInt()); font.setItalic(e.attribute("Italic").toInt()); font.setUnderline(e.attribute("Underline").toInt()); setFont(font); } QVariant DiagramTextItem::itemChange(GraphicsItemChange change, const QVariant& value) { if (change == QGraphicsItem::ItemSelectedHasChanged) emit textSelectedChange(this); return value; } void DiagramTextItem::focusInEvent(QFocusEvent* event) { if (_positionLastTime == QPointF(0, 0)) // initialize positionLastTime to insertion position _positionLastTime = scenePos(); QGraphicsTextItem::focusInEvent(event); } void DiagramTextItem::focusOutEvent(QFocusEvent* event) { setTextInteractionFlags(Qt::NoTextInteraction); if (_contentLastTime == toPlainText()) { _contentHasChanged = false; } else { _contentLastTime = toPlainText(); _contentHasChanged = true; } emit lostFocus(this); QGraphicsTextItem::focusOutEvent(event); } void DiagramTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) { if (textInteractionFlags() == Qt::NoTextInteraction) { setTextInteractionFlags(Qt::TextEditorInteraction); } QGraphicsTextItem::mouseDoubleClickEvent(event); } void DiagramTextItem::mousePressEvent(QGraphicsSceneMouseEvent* event) { QGraphicsTextItem::mousePressEvent(event); } void DiagramTextItem::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { if (scenePos() != _positionLastTime) { qDebug() << scenePos() << "::" << _positionLastTime; } _positionLastTime = scenePos(); QGraphicsTextItem::mouseReleaseEvent(event); }
30.62931
86
0.71714
devonchenc
8e7f4570bad4e822a335012a8954ab535981c82a
633
cpp
C++
clang/test/SemaCXX/template-multiple-attr-propagation.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,102
2015-01-04T02:28:35.000Z
2022-03-30T12:53:41.000Z
clang/test/SemaCXX/template-multiple-attr-propagation.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang/test/SemaCXX/template-multiple-attr-propagation.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
1,868
2015-01-03T04:27:11.000Z
2022-03-25T13:37:35.000Z
// RUN: %clang_cc1 %s -Wthread-safety-analysis -verify -fexceptions // expected-no-diagnostics class Mutex { public: void Lock() __attribute__((exclusive_lock_function())); void Unlock() __attribute__((unlock_function())); }; class A { public: Mutex mu1, mu2; void foo() __attribute__((exclusive_locks_required(mu1))) __attribute__((exclusive_locks_required(mu2))) {} template <class T> void bar() __attribute__((exclusive_locks_required(mu1))) __attribute__((exclusive_locks_required(mu2))) { foo(); } }; void f() { A a; a.mu1.Lock(); a.mu2.Lock(); a.bar<int>(); a.mu2.Unlock(); a.mu1.Unlock(); }
21.1
109
0.685624
medismailben
8e80230a4682d1e69daf8eb7cd916a773b12efc3
2,059
hpp
C++
ThirdParty-mod/java2cpp/java/lang/Void.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
1
2019-04-03T01:53:28.000Z
2019-04-03T01:53:28.000Z
ThirdParty-mod/java2cpp/java/lang/Void.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
ThirdParty-mod/java2cpp/java/lang/Void.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: java.lang.Void ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_LANG_VOID_HPP_DECL #define J2CPP_JAVA_LANG_VOID_HPP_DECL namespace j2cpp { namespace java { namespace lang { class Object; } } } namespace j2cpp { namespace java { namespace lang { class Class; } } } #include <java/lang/Class.hpp> #include <java/lang/Object.hpp> namespace j2cpp { namespace java { namespace lang { class Void; class Void : public object<Void> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_FIELD(0) explicit Void(jobject jobj) : object<Void>(jobj) { } operator local_ref<java::lang::Object>() const; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), local_ref< java::lang::Class > > TYPE; }; //class Void } //namespace lang } //namespace java } //namespace j2cpp #endif //J2CPP_JAVA_LANG_VOID_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_LANG_VOID_HPP_IMPL #define J2CPP_JAVA_LANG_VOID_HPP_IMPL namespace j2cpp { java::lang::Void::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } static_field< java::lang::Void::J2CPP_CLASS_NAME, java::lang::Void::J2CPP_FIELD_NAME(0), java::lang::Void::J2CPP_FIELD_SIGNATURE(0), local_ref< java::lang::Class > > java::lang::Void::TYPE; J2CPP_DEFINE_CLASS(java::lang::Void,"java/lang/Void") J2CPP_DEFINE_METHOD(java::lang::Void,0,"<init>","()V") J2CPP_DEFINE_METHOD(java::lang::Void,1,"<clinit>","()V") J2CPP_DEFINE_FIELD(java::lang::Void,0,"TYPE","Ljava/lang/Class;") } //namespace j2cpp #endif //J2CPP_JAVA_LANG_VOID_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
22.380435
127
0.650801
kakashidinho
8e887ecf4d7872203061f3c093aa07eedda04a7a
2,339
cc
C++
modules/kernel/src/debugger/DebugEntry.cc
eryjus/century-os
6e6bef8cbc0f9c5ff6a943b44aa87a7e89fdfbd7
[ "BSD-3-Clause" ]
12
2018-12-03T15:16:52.000Z
2022-03-16T21:07:13.000Z
modules/kernel/src/debugger/DebugEntry.cc
eryjus/century-os
6e6bef8cbc0f9c5ff6a943b44aa87a7e89fdfbd7
[ "BSD-3-Clause" ]
null
null
null
modules/kernel/src/debugger/DebugEntry.cc
eryjus/century-os
6e6bef8cbc0f9c5ff6a943b44aa87a7e89fdfbd7
[ "BSD-3-Clause" ]
2
2018-11-13T01:30:41.000Z
2021-08-12T18:22:26.000Z
//=================================================================================================================== // // DebugStart.cc -- This is the entry point for the kernel debugger // // Copyright (c) 2017-2020 -- Adam Clark // Licensed under "THE BEER-WARE LICENSE" // See License.md for details. // // ------------------------------------------------------------------------------------------------------------------ // // Date Tracker Version Pgmr Description // ----------- ------- ------- ---- --------------------------------------------------------------------------- // 2020-Apr-02 Initial v0.6.0a ADCL Initial version // //=================================================================================================================== #include "types.h" #include "printf.h" #include "serial.h" #include "process.h" #include "debugger.h" // // -- This is the main entry point for the kernel debugger // ---------------------------------------------------- EXTERN_C EXPORT KERNEL void DebugStart(void) { EnableInterrupts(); // -- we want the highest chance of getting CPU time! currentThread->priority = PTY_OS; debugState = DBG_HOME; kprintf(ANSI_CLEAR ANSI_SET_CURSOR(0,0) ANSI_FG_RED ANSI_ATTR_BOLD "Welcome to the Century-OS kernel debugger\n" ANSI_ATTR_NORMAL); while (true) { DebugPrompt(debugState); DebuggerCommand_t cmd = DebugParse(debugState); switch(cmd) { case CMD_EXIT: debugState = DBG_HOME; kMemSetB(debugCommand, 0, DEBUG_COMMAND_LEN); continue; case CMD_SCHED: debugState = DBG_SCHED; DebugScheduler(); continue; case CMD_TIMER: debugState = DBG_TIMER; DebugTimer(); continue; case CMD_MSGQ: debugState = DBG_MSGQ; DebugMsgq(); continue; case CMD_ERROR: default: kprintf("\n\n" ANSI_ATTR_BOLD ANSI_FG_RED "Something went wrong (main) -- a bug in the debugger is likely\n" ANSI_ATTR_NORMAL); continue; } if (cmd == CMD_ERROR) continue; } }
30.376623
117
0.436084
eryjus
8e8b7903b026478e454007fe1df9115c428d6744
5,521
cpp
C++
tests/Unit/Evolution/EventsAndTriggers/Test_EventsAndTriggers.cpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
tests/Unit/Evolution/EventsAndTriggers/Test_EventsAndTriggers.cpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
tests/Unit/Evolution/EventsAndTriggers/Test_EventsAndTriggers.cpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. // This file checks the Completion event and the basic logical // triggers (Always, And, Not, and Or). #include "tests/Unit/TestingFramework.hpp" #include <algorithm> #include <memory> #include <pup.h> #include <string> #include <unordered_map> #include "DataStructures/DataBox/DataBox.hpp" #include "Evolution/EventsAndTriggers/Actions/RunEventsAndTriggers.hpp" // IWYU pragma: keep #include "Evolution/EventsAndTriggers/Completion.hpp" #include "Evolution/EventsAndTriggers/Event.hpp" #include "Evolution/EventsAndTriggers/EventsAndTriggers.hpp" #include "Evolution/EventsAndTriggers/LogicalTriggers.hpp" // IWYU pragma: keep #include "Evolution/EventsAndTriggers/Trigger.hpp" #include "Parallel/RegisterDerivedClassesWithCharm.hpp" #include "Utilities/MakeVector.hpp" #include "Utilities/TMPL.hpp" #include "Utilities/TaggedTuple.hpp" #include "tests/Unit/ActionTesting.hpp" #include "tests/Unit/TestCreation.hpp" #include "tests/Unit/TestHelpers.hpp" // IWYU pragma: no_forward_declare db::DataBox namespace { struct DefaultClasses { template <typename T> using type = tmpl::list<>; }; using events_and_triggers_tag = Tags::EventsAndTriggers<DefaultClasses, DefaultClasses>; struct Metavariables; struct component { using metavariables = Metavariables; using chare_type = ActionTesting::MockArrayChare; using array_index = int; using const_global_cache_tag_list = tmpl::list<events_and_triggers_tag>; using action_list = tmpl::list<Actions::RunEventsAndTriggers>; using initial_databox = db::DataBox<tmpl::list<>>; }; struct Metavariables { using component_list = tmpl::list<component>; using const_global_cache_tag_list = tmpl::list<>; }; using EventsAndTriggersType = EventsAndTriggers<DefaultClasses, DefaultClasses>; void run_events_and_triggers(const EventsAndTriggersType& events_and_triggers, const bool expected) { // Test pup Parallel::register_derived_classes_with_charm<Event<DefaultClasses>>(); Parallel::register_derived_classes_with_charm<Trigger<DefaultClasses>>(); using MockRuntimeSystem = ActionTesting::MockRuntimeSystem<Metavariables>; using my_component = component; using MockDistributedObjectsTag = typename MockRuntimeSystem::template MockDistributedObjectsTag< my_component>; typename MockRuntimeSystem::TupleOfMockDistributedObjects dist_objects{}; tuples::get<MockDistributedObjectsTag>(dist_objects) .emplace(0, db::DataBox<tmpl::list<>>{}); ActionTesting::MockRuntimeSystem<Metavariables> runner{ {serialize_and_deserialize(events_and_triggers)}, std::move(dist_objects)}; runner.next_action<component>(0); CHECK(runner.algorithms<component>()[0].get_terminate() == expected); } void check_trigger(const bool expected, const std::string& trigger_string) { // Test factory std::unique_ptr<Trigger<DefaultClasses>> trigger = test_factory_creation<Trigger<DefaultClasses>>(trigger_string); EventsAndTriggersType::Storage events_and_triggers_map; events_and_triggers_map.emplace( std::move(trigger), make_vector<std::unique_ptr<Event<DefaultClasses>>>( std::make_unique<Events::Completion<DefaultClasses>>())); const EventsAndTriggersType events_and_triggers( std::move(events_and_triggers_map)); run_events_and_triggers(events_and_triggers, expected); } } // namespace SPECTRE_TEST_CASE("Unit.Evolution.EventsAndTriggers", "[Unit][Evolution]") { test_factory_creation<Event<DefaultClasses>>(" Completion"); check_trigger(true, " Always"); check_trigger(false, " Not: Always"); check_trigger(true, " Not:\n" " Not: Always"); check_trigger(true, " And:\n" " - Always\n" " - Always"); check_trigger(false, " And:\n" " - Always\n" " - Not: Always"); check_trigger(false, " And:\n" " - Not: Always\n" " - Always"); check_trigger(false, " And:\n" " - Not: Always\n" " - Not: Always"); check_trigger(false, " And:\n" " - Always\n" " - Always\n" " - Not: Always"); check_trigger(true, " Or:\n" " - Always\n" " - Always"); check_trigger(true, " Or:\n" " - Always\n" " - Not: Always"); check_trigger(true, " Or:\n" " - Not: Always\n" " - Always"); check_trigger(false, " Or:\n" " - Not: Always\n" " - Not: Always"); check_trigger(true, " Or:\n" " - Not: Always\n" " - Not: Always\n" " - Always"); } SPECTRE_TEST_CASE("Unit.Evolution.EventsAndTriggers.creation", "[Unit][Evolution]") { const auto events_and_triggers = test_creation<EventsAndTriggersType>( " ? Not: Always\n" " : - Completion\n" " ? Or:\n" " - Not: Always\n" " - Always\n" " : - Completion\n" " - Completion\n" " ? Not: Always\n" " : - Completion\n"); run_events_and_triggers(events_and_triggers, true); }
32.668639
93
0.63503
marissawalker
8e8d2f55740dd591fc5dab9a9c969cb5ba645222
882
cpp
C++
src/my_utils/vector2_utils.cpp
lobinuxsoft/AsteroidXD-SFML
66fb355dfb20ef840068ad948bef9fc97a75f7cd
[ "MIT" ]
null
null
null
src/my_utils/vector2_utils.cpp
lobinuxsoft/AsteroidXD-SFML
66fb355dfb20ef840068ad948bef9fc97a75f7cd
[ "MIT" ]
16
2021-11-09T15:22:24.000Z
2021-11-23T14:02:43.000Z
src/my_utils/vector2_utils.cpp
lobinuxsoft/AsteroidXD-SFML
66fb355dfb20ef840068ad948bef9fc97a75f7cd
[ "MIT" ]
null
null
null
#include "vector2_utils.h" float Vector2Angle(Vector2f v1, Vector2f v2) { float result = atan2f(v2.y - v1.y, v2.x - v1.x) * (180.0f / PI); if (result < 0) result += 360.0f; return result; } float Vector2Distance(Vector2f v1, Vector2f v2) { return sqrtf((v1.x - v2.x) * (v1.x - v2.x) + (v1.y - v2.y) * (v1.y - v2.y)); } float Vector2Length(Vector2f v) { return sqrtf((v.x * v.x) + (v.y * v.y)); } Vector2f Vector2Scale(Vector2f v, float scale) { return Vector2f( v.x * scale, v.y * scale ); } Vector2f Vector2Normalize(Vector2f v) { float length = Vector2Length(v); if (length <= 0) return v; return Vector2Scale(v, 1 / length); } Vector2f Vector2Add(Vector2f v1, Vector2f v2) { return Vector2f( v1.x + v2.x, v1.y + v2.y ); } Vector2f Vector2Subtract(Vector2f v1, Vector2f v2) { return Vector2f(v1.x - v2.x, v1.y - v2.y); }
21
80
0.620181
lobinuxsoft
8e8e54a5dc9f20dc63765ef2a60be805e89c0bea
4,428
cpp
C++
Cutscene Manager Handout/Motor2D/j1CutsceneManager.cpp
pauraurell/Cutscene-Manager
f887b2a14e1c4e3623d2d8933d7893280ab27f53
[ "MIT" ]
null
null
null
Cutscene Manager Handout/Motor2D/j1CutsceneManager.cpp
pauraurell/Cutscene-Manager
f887b2a14e1c4e3623d2d8933d7893280ab27f53
[ "MIT" ]
null
null
null
Cutscene Manager Handout/Motor2D/j1CutsceneManager.cpp
pauraurell/Cutscene-Manager
f887b2a14e1c4e3623d2d8933d7893280ab27f53
[ "MIT" ]
null
null
null
#include "p2Defs.h" #include "p2Log.h" #include "j1App.h" #include "j1Input.h" #include "j1Textures.h" #include "j1Scene.h" #include "j1Render.h" #include "j1Window.h" #include "j1CutsceneCharacters.h" #include "j1CutsceneManager.h" j1CutsceneManager::j1CutsceneManager() : j1Module() { name.create("cutscene"); } // Destructor j1CutsceneManager::~j1CutsceneManager() {} // Called before the first frame bool j1CutsceneManager::Start() { black_bars.fase = None; black_bars.alpha = 0; int bar_height = 100; black_bars.top_rect.x = 0; black_bars.top_rect.y = 0; black_bars.top_rect.w = App->win->width; black_bars.top_rect.h = bar_height; black_bars.down_rect.x = 0; black_bars.down_rect.y = App->win->height - bar_height; black_bars.down_rect.w = App->win->width; black_bars.down_rect.h = bar_height; result = data.load_file("CutsceneEditor.xml"); cutsceneManager = data.document_element(); LOG("Starting Cutscene Manager"); return true; } // Called each loop iteration bool j1CutsceneManager::Update(float dt) { return true; } // Called each loop iteration bool j1CutsceneManager::PostUpdate(float dt) { //Black Bars Drawing switch (black_bars.fase) { case FadeIn: black_bars.FadeIn(); break; case Drawing: black_bars.Draw(); break; case FadeOut: black_bars.FadeOut(); break; } return true; } // Called before quitting bool j1CutsceneManager::CleanUp() { return true; } void BlackBars::FadeIn() { //TODO 5.2: Complete this function doing a smooth fade in raising the value of the alpha // (alpha = 0: invisible, alpha = 255: Completely black) } void BlackBars::Draw() { //TODO 5.1: Draw both quads unsing the alpha variable. Both rects are (top_rect and down_rect) already // created, you just have to draw them. } void BlackBars::FadeOut() { //TODO 5.2: Similar to fade out } void j1CutsceneManager::StartCutscene(string name) { if (!SomethingActive()) { for (pugi::xml_node cutscene = cutsceneManager.child("cutscene"); cutscene; cutscene = cutscene.next_sibling("cutscene")) { if (cutscene.attribute("name").as_string() == name) { LoadSteps(cutscene); if (black_bars.fase == None) { black_bars.fase = FadeIn; } } } if (App->characters->player.active) {App->characters->player.UpdateStep(); } if (App->characters->character1.active) {App->characters->character1.UpdateStep(); } if (App->characters->character2.active) { App->characters->character2.UpdateStep(); } if (App->render->cinematic_camera.active) { App->render->cinematic_camera.UpdateStep(); } } } bool j1CutsceneManager::LoadSteps(pugi::xml_node node) { //TODO 1: Check the structure of the Cutscene Editor xml and fill this function. You just have to get the attributes from // the xml and push the step to the list of the correspondent Cutscene Object depending on its objective and set the active // bool to true of each loaded Cutscene Object. return true; } void j1CutsceneManager::DoCutscene(CutsceneObject &character, iPoint &objective_position) { Step step = character.current_step; if(character.active) { Movement(step, objective_position); //TODO 4: This todo is very easy, just check if the object position is equal to the last position of the cutscene and if it // is call the FinishCutscene function. If it has reached the step.position but it is not the last one just call the Update step // function you've just made right before. } } void j1CutsceneManager::Movement(Step &step, iPoint &objective_position) { //TODO 2: Now we want to move the object to the destiny point. To do that compare the object postion with the position // we want to reach and move it with the speed values. } void CutsceneObject::UpdateStep() { //TODO 3: Now that the object will move wherever we want, we have to call this function every time the object reaches a point. // To do this, in this function you just have to update the current_step value with the next step in the list. } void j1CutsceneManager::FinishCutscene(CutsceneObject& character) { character.steps.clear(); character.active = false; App->characters->input = true; if (black_bars.fase == Drawing) { black_bars.fase = FadeOut; } } bool j1CutsceneManager::SomethingActive() { bool ret; if (App->characters->player.active || App->characters->character1.active || App->characters->character2.active){ret = true;} else { ret = false; } return ret; }
24.464088
131
0.727191
pauraurell
8e8fb299899a755581ac3a9945f0b7b0ae52f35b
362
cpp
C++
ch04/th4-5-1.cpp
nanonashy/PPPUCpp2ndJP
b829867e9e21bf59d9c5ea6c2fbe96bb03597301
[ "MIT" ]
3
2021-12-17T17:25:18.000Z
2022-03-02T15:52:23.000Z
ch04/th4-5-1.cpp
nashinium/PPPUCpp2ndJP
b829867e9e21bf59d9c5ea6c2fbe96bb03597301
[ "MIT" ]
1
2020-04-22T07:16:34.000Z
2020-04-22T10:04:04.000Z
ch04/th4-5-1.cpp
nashinium/PPPUCpp2ndJP
b829867e9e21bf59d9c5ea6c2fbe96bb03597301
[ "MIT" ]
1
2020-04-22T08:13:51.000Z
2020-04-22T08:13:51.000Z
#include "../include/std_lib_facilities.h" int square(int x) { int result{0}; for (int i = 1; i <= x; ++i) result += x; return result; } int main() { std::cout << "Number\tSquare\n"; for (int i = 1; i <= 100; ++i) std::cout << i << '\t' << square(i) << std::endl; keep_window_open(); return 0; }
19.052632
58
0.477901
nanonashy
8e8fcbbb94e6ebae074192cb4816cf0be70a6a58
14,565
cpp
C++
src/llri-vk/detail/device.cpp
Rythe-Interactive/Rythe-LLRI
0bf9ff71c41b39f7189cbc5ebbf4a74420cedc05
[ "MIT" ]
2
2022-02-08T07:11:32.000Z
2022-02-08T08:10:31.000Z
src/llri-vk/detail/device.cpp
Rythe-Interactive/Rythe-LLRI
0bf9ff71c41b39f7189cbc5ebbf4a74420cedc05
[ "MIT" ]
1
2022-02-14T18:26:31.000Z
2022-02-14T18:26:31.000Z
src/llri-vk/detail/device.cpp
Rythe-Interactive/Rythe-LLRI
0bf9ff71c41b39f7189cbc5ebbf4a74420cedc05
[ "MIT" ]
null
null
null
/** * @file device.cpp * Copyright (c) 2021 Leon Brands, Rythe Interactive * SPDX-License-Identifier: MIT */ #include <llri/llri.hpp> #include <llri-vk/utils.hpp> namespace llri { result Device::impl_createCommandGroup(queue_type type, CommandGroup** cmdGroup) { auto* output = new CommandGroup(); output->m_device = this; output->m_deviceFunctionTable = m_functionTable; output->m_validationCallbackMessenger = m_validationCallbackMessenger; output->m_type = type; auto families = detail::findQueueFamilies(static_cast<VkPhysicalDevice>(m_adapter->m_ptr)); VkCommandPoolCreateInfo info; info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; info.pNext = nullptr; info.queueFamilyIndex = families[type]; info.flags = {}; VkCommandPool pool; const auto r = static_cast<VolkDeviceTable*>(m_functionTable)-> vkCreateCommandPool(static_cast<VkDevice>(m_ptr), &info, nullptr, &pool); if (r != VK_SUCCESS) { destroyCommandGroup(output); return detail::mapVkResult(r); } output->m_ptr = pool; *cmdGroup = output; return result::Success; } void Device::impl_destroyCommandGroup(CommandGroup* cmdGroup) { if (!cmdGroup) return; if (cmdGroup->m_ptr) { static_cast<VolkDeviceTable*>(m_functionTable)-> vkDestroyCommandPool(static_cast<VkDevice>(m_ptr), static_cast<VkCommandPool>(cmdGroup->m_ptr), nullptr); } delete cmdGroup; } result Device::impl_createFence(fence_flags flags, Fence** fence) { const bool signaled = (flags & fence_flag_bits::Signaled) == fence_flag_bits::Signaled; VkFenceCreateFlags vkFlags = 0; if (signaled) vkFlags |= VK_FENCE_CREATE_SIGNALED_BIT; VkFenceCreateInfo info; info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; info.pNext = nullptr; info.flags = vkFlags; VkFence vkFence; const auto r = static_cast<VolkDeviceTable*>(m_functionTable)-> vkCreateFence(static_cast<VkDevice>(m_ptr), &info, nullptr, &vkFence); if (r != VK_SUCCESS) return detail::mapVkResult(r); auto* output = new Fence(); output->m_flags = flags; output->m_ptr = vkFence; output->m_signaled = signaled; *fence = output; return result::Success; } void Device::impl_destroyFence(Fence* fence) { if (fence->m_ptr) { static_cast<VolkDeviceTable*>(m_functionTable)-> vkDestroyFence(static_cast<VkDevice>(m_ptr), static_cast<VkFence>(fence->m_ptr), nullptr); } delete fence; } result Device::impl_waitFences(uint32_t numFences, Fence** fences, uint64_t timeout) { uint64_t vkTimeout = timeout; if (timeout != LLRI_TIMEOUT_MAX) vkTimeout *= 1000000u; // milliseconds to nanoseconds std::vector<VkFence> vkFences(numFences); for (size_t i = 0; i < numFences; i++) vkFences[i] = static_cast<VkFence>(fences[i]->m_ptr); const VkResult r = static_cast<VolkDeviceTable*>(m_functionTable)-> vkWaitForFences(static_cast<VkDevice>(m_ptr), numFences, vkFences.data(), true, vkTimeout); if (r == VK_SUCCESS) { static_cast<VolkDeviceTable*>(m_functionTable)-> vkResetFences(static_cast<VkDevice>(m_ptr), numFences, vkFences.data()); for (size_t i = 0; i < numFences; i++) fences[i]->m_signaled = false; } return detail::mapVkResult(r); } result Device::impl_createSemaphore(Semaphore** semaphore) { VkSemaphoreCreateInfo info; info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; info.pNext = nullptr; info.flags = {}; VkSemaphore vkSemaphore; const VkResult r = static_cast<VolkDeviceTable*>(m_functionTable)-> vkCreateSemaphore(static_cast<VkDevice>(m_ptr), &info, nullptr, &vkSemaphore); if (r != VK_SUCCESS) return detail::mapVkResult(r); auto* output = new Semaphore(); output->m_ptr = vkSemaphore; *semaphore = output; return result::Success; } void Device::impl_destroySemaphore(Semaphore* semaphore) { if (semaphore->m_ptr) { static_cast<VolkDeviceTable*>(m_functionTable)-> vkDestroySemaphore(static_cast<VkDevice>(m_ptr), static_cast<VkSemaphore>(semaphore->m_ptr), nullptr); } delete semaphore; } result Device::impl_createResource(const resource_desc& desc, Resource** resource) { auto* table = static_cast<VolkDeviceTable*>(m_functionTable); const bool isTexture = desc.type != resource_type::Buffer; // get all valid queue families const auto& families = detail::findQueueFamilies(static_cast<VkPhysicalDevice>(m_adapter->m_ptr)); std::vector<uint32_t> familyIndices; for (const auto& [key, family] : families) { if (family != std::numeric_limits<uint32_t>::max()) familyIndices.push_back(family); } // get memory flags const auto memFlags = detail::mapMemoryType(desc.memoryType); uint64_t dataSize = 0; uint32_t memoryTypeIndex = 0; VkImage image = VK_NULL_HANDLE; VkBuffer buffer = VK_NULL_HANDLE; if (isTexture) { uint32_t depth = desc.type == resource_type::Texture3D ? desc.depthOrArrayLayers : 1; uint32_t arrayLayers = desc.type == resource_type::Texture3D ? 1 : desc.depthOrArrayLayers; VkImageCreateInfo imageCreate; imageCreate.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; imageCreate.pNext = nullptr; imageCreate.flags = 0; imageCreate.imageType = detail::mapTextureType(desc.type); imageCreate.format = detail::mapTextureFormat(desc.textureFormat); imageCreate.extent = VkExtent3D{ desc.width, desc.height, depth }; imageCreate.mipLevels = desc.mipLevels; imageCreate.arrayLayers = arrayLayers; imageCreate.samples = (VkSampleCountFlagBits)desc.sampleCount; imageCreate.tiling = VK_IMAGE_TILING_OPTIMAL; imageCreate.usage = detail::mapTextureUsage(desc.usage); imageCreate.sharingMode = familyIndices.size() > 1 ? VK_SHARING_MODE_CONCURRENT : VK_SHARING_MODE_EXCLUSIVE; imageCreate.queueFamilyIndexCount = static_cast<uint32_t>(familyIndices.size()); imageCreate.pQueueFamilyIndices = familyIndices.data(); imageCreate.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; auto r = table->vkCreateImage(static_cast<VkDevice>(m_ptr), &imageCreate, nullptr, &image); if (r != VK_SUCCESS) return detail::mapVkResult(r); VkMemoryRequirements reqs; table->vkGetImageMemoryRequirements(static_cast<VkDevice>(m_ptr), image, &reqs); dataSize = reqs.size; memoryTypeIndex = detail::findMemoryTypeIndex(static_cast<VkPhysicalDevice>(m_adapter->m_ptr), reqs.memoryTypeBits, memFlags); } else { VkBufferCreateInfo bufferCreate; bufferCreate.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferCreate.pNext = nullptr; bufferCreate.flags = 0; bufferCreate.size = desc.width; bufferCreate.usage = detail::mapBufferUsage(desc.usage); bufferCreate.sharingMode = familyIndices.size() > 1 ? VK_SHARING_MODE_CONCURRENT : VK_SHARING_MODE_EXCLUSIVE; bufferCreate.queueFamilyIndexCount = static_cast<uint32_t>(familyIndices.size()); bufferCreate.pQueueFamilyIndices = familyIndices.data(); auto r = table->vkCreateBuffer(static_cast<VkDevice>(m_ptr), &bufferCreate, nullptr, &buffer); if (r != VK_SUCCESS) return detail::mapVkResult(r); VkMemoryRequirements reqs; table->vkGetBufferMemoryRequirements(static_cast<VkDevice>(m_ptr), buffer, &reqs); dataSize = reqs.size; memoryTypeIndex = detail::findMemoryTypeIndex(static_cast<VkPhysicalDevice>(m_adapter->m_ptr), reqs.memoryTypeBits, memFlags); } VkMemoryAllocateFlagsInfoKHR flagsInfo; flagsInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO; flagsInfo.pNext = nullptr; flagsInfo.deviceMask = desc.visibleNodeMask; flagsInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_MASK_BIT; VkMemoryAllocateInfo allocInfo; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.pNext = m_adapter->queryNodeCount() > 1 ? &flagsInfo : nullptr; allocInfo.allocationSize = dataSize; allocInfo.memoryTypeIndex = memoryTypeIndex; VkDeviceMemory memory; auto r = table->vkAllocateMemory(static_cast<VkDevice>(m_ptr), &allocInfo, nullptr, &memory); if (r != VK_SUCCESS) { if (isTexture) table->vkDestroyImage(static_cast<VkDevice>(m_ptr), image, nullptr); else table->vkDestroyBuffer(static_cast<VkDevice>(m_ptr), buffer, nullptr); return detail::mapVkResult(r); } if (isTexture) r = table->vkBindImageMemory(static_cast<VkDevice>(m_ptr), image, memory, 0); else r = table->vkBindBufferMemory(static_cast<VkDevice>(m_ptr), buffer, memory, 0); if (r != VK_SUCCESS) { if (isTexture) table->vkDestroyImage(static_cast<VkDevice>(m_ptr), image, nullptr); else table->vkDestroyBuffer(static_cast<VkDevice>(m_ptr), buffer, nullptr); table->vkFreeMemory(static_cast<VkDevice>(m_ptr), memory, nullptr); return detail::mapVkResult(r); } // this part is necessary because in vulkan images are created in the UNDEFINED layout // so we must transition them to desc.initialState manually. if (isTexture) { table->vkResetCommandPool(static_cast<VkDevice>(m_ptr), static_cast<VkCommandPool>(m_workCmdGroup), {}); // Record commandbuffer to transition texture from undefined VkCommandBufferBeginInfo beginInfo {}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.pNext = nullptr; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; beginInfo.pInheritanceInfo = nullptr; table->vkBeginCommandBuffer(static_cast<VkCommandBuffer>(m_workCmdList), &beginInfo); // use the texture format to detect the aspect flags VkImageAspectFlags aspectFlags = {}; if (has_color_component(desc.textureFormat)) aspectFlags |= VK_IMAGE_ASPECT_COLOR_BIT; if (has_depth_component(desc.textureFormat)) aspectFlags |= VK_IMAGE_ASPECT_DEPTH_BIT; if (has_stencil_component(desc.textureFormat)) aspectFlags |= VK_IMAGE_ASPECT_STENCIL_BIT; VkImageMemoryBarrier imageMemoryBarrier {}; imageMemoryBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; imageMemoryBarrier.pNext = nullptr; imageMemoryBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageMemoryBarrier.newLayout = detail::mapResourceState(desc.initialState); imageMemoryBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; imageMemoryBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; imageMemoryBarrier.srcAccessMask = VK_ACCESS_NONE_KHR; imageMemoryBarrier.dstAccessMask = detail::mapStateToAccess(desc.initialState); imageMemoryBarrier.image = image; imageMemoryBarrier.subresourceRange = VkImageSubresourceRange { aspectFlags, 0, desc.mipLevels, 0, desc.depthOrArrayLayers }; table->vkCmdPipelineBarrier(static_cast<VkCommandBuffer>(m_workCmdList), VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, detail::mapStateToPipelineStage(desc.initialState), {}, 0, nullptr, 0, nullptr, 1, &imageMemoryBarrier); table->vkEndCommandBuffer(static_cast<VkCommandBuffer>(m_workCmdList)); VkSubmitInfo submit {}; submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submit.pNext = nullptr; submit.commandBufferCount = 1; submit.pCommandBuffers = reinterpret_cast<VkCommandBuffer*>(&m_workCmdList); submit.signalSemaphoreCount = 0; submit.pSignalSemaphores = nullptr; submit.waitSemaphoreCount = 0; submit.pWaitSemaphores = nullptr; submit.pWaitDstStageMask = nullptr; table->vkQueueSubmit(static_cast<VkQueue>(getQueue(m_workQueueType, 0)->m_ptrs[0]), 1, &submit, static_cast<VkFence>(m_workFence)); table->vkWaitForFences(static_cast<VkDevice>(m_ptr), 1, reinterpret_cast<VkFence*>(&m_workFence), VK_TRUE, std::numeric_limits<uint64_t>::max()); table->vkResetFences(static_cast<VkDevice>(m_ptr), 1, reinterpret_cast<VkFence*>(&m_workFence)); } auto* output = new Resource(); output->m_desc = desc; output->m_resource = isTexture ? static_cast<Resource::native_resource*>(image) : static_cast<Resource::native_resource*>(buffer); output->m_memory = memory; *resource = output; return result::Success; } void Device::impl_destroyResource(Resource* resource) { const bool isTexture = resource->m_desc.type != resource_type::Buffer; if (isTexture) static_cast<VolkDeviceTable*>(m_functionTable)->vkDestroyImage(static_cast<VkDevice>(m_ptr), static_cast<VkImage>(resource->m_resource), nullptr); else static_cast<VolkDeviceTable*>(m_functionTable)->vkDestroyBuffer(static_cast<VkDevice>(m_ptr), static_cast<VkBuffer>(resource->m_resource), nullptr); static_cast<VolkDeviceTable*>(m_functionTable)->vkFreeMemory(static_cast<VkDevice>(m_ptr), static_cast<VkDeviceMemory>(resource->m_memory), nullptr); } }
42.340116
160
0.646413
Rythe-Interactive
8e90fefa694ca74307c3d8b7758f4510a1e6acf2
11,757
cpp
C++
src/args.cpp
valet-bridge/valet
8e20da1b496cb6fa42894b9ef420375cb7a5d2cd
[ "Apache-2.0" ]
null
null
null
src/args.cpp
valet-bridge/valet
8e20da1b496cb6fa42894b9ef420375cb7a5d2cd
[ "Apache-2.0" ]
1
2015-11-15T08:20:33.000Z
2018-03-04T09:48:23.000Z
src/args.cpp
valet-bridge/valet
8e20da1b496cb6fa42894b9ef420375cb7a5d2cd
[ "Apache-2.0" ]
null
null
null
/* Valet, a generalized Butler scorer for bridge. Copyright (C) 2015 by Soren Hein. See LICENSE and README. */ // These functions parse the command line for options. #include <iostream> #include <iomanip> #include <string> #include <stdlib.h> #include <string.h> #include "args.h" #include "cst.h" using namespace std; extern OptionsType options; struct optEntry { string shortName; string longName; unsigned numArgs; }; #define VALET_NUM_OPTIONS 16 const optEntry optList[VALET_NUM_OPTIONS] = { {"v", "valettype", 1}, {"d", "directory", 1}, {"n", "names", 1}, {"s", "scores", 1}, {"r", "rounds", 1}, {"m", "minhands", 1}, {"l", "leads", 0}, {"e", "extremes", 0}, {"h", "hardround", 0}, {"t", "tableau", 1}, {"x", "nocloud", 0}, {"c", "compensate", 0}, {"o", "order", 1}, {"a", "average", 0}, {"f", "format", 1}, {"j", "join", 1} }; string shortOptsAll, shortOptsWithArg; int GetNextArgToken( int argc, char * argv[]); void SetDefaults(); bool ParseRound(); void Usage( const char base[]) { string basename(base); const size_t l = basename.find_last_of("\\/"); if (l != string::npos) basename.erase(0, l+1); cout << "Usage: " << basename << " [options]\n\n" << "-v, --valettype s Valet type, one of datum, imps, matchpoints\n" << " (default: imps).\n" << "\n" << "-d, --directory s Read the input files from directory s.\n" << "\n" << "-n, --names s Use s as the names file (default names.txt)\n" << "\n" << "-s, --scores s Use s as the scores file (default scores.txt)\n" << "\n" << "-r, --rounds list Selects only rounds specified in list.\n" << " Example (note: no spaces) 1,3-5,7 (default all)\n" << "\n" << "-m, --minhands m Only show results for pairs/players who have\n" << " played at least m hands (default 0)\n" << "\n" << "-l, --lead Show a Valet score for the lead separately\n" << " (default: no)\n" << "\n" << "-e, --extremes When calculating datum score (only for Butler\n" << " IMPs), throw out the maximum and minimum\n" << " scores (default: no, -e turns it on).\n" << "\n" << "-h, --hardround When calculating datum score (only for Butler\n" << " IMPs), round down and not to the nearest\n" << " score. So 379 rounds to 370, not to 380\n" << " (default: no).\n" << "\n" << "-x, --nocloud Use the simpler, but mathematically less\n" << " satisfying Valet score (default: not set).\n" << "\n" << "-t, --tableau Output a file of tableaux for each hand\n" << " to file argument (default: not set).\n" << "\n" << "-c, -compensate Compensate overall score for the average strength\n" << " of the specific opponents faced (default: no).\n" << "\n" << "-o, --order s Sorting order of the output. Valid orders are\n" << " overall, bidding, play, defense, lead,\n" << " bidoverplay (bidding minus play),\n" << " defoverplay (defense minus play),\n" << " leadoverplay (lead minus play),\n" << " (case-insensitive).\n" << "\n" << "-a, --average Show certain averages in the output tables.\n" "\n" << "-f, --format s Output file format: text or csv (broadly\n" << " speaking, comma-separated values suitable for\n" << " loading into e.g. Microsoft Excel)\n" << " (default: text).\n" << "\n" << "-j, --join c Separator for csv output (default the comma,\n" << " ',' (without the marks). In German Excel it \n" << " is useful to set this to ';', and so on.\n" << endl; } int nextToken = 1; char * optarg; int GetNextArgToken( int argc, char * argv[]) { // 0 means done, -1 means error. if (nextToken >= argc) return 0; string str(argv[nextToken]); if (str[0] != '-' || str.size() == 1) return -1; if (str[1] == '-') { if (str.size() == 2) return -1; str.erase(0, 2); } else if (str.size() == 2) str.erase(0, 1); else return -1; for (unsigned i = 0; i < VALET_NUM_OPTIONS; i++) { if (str == optList[i].shortName || str == optList[i].longName) { if (optList[i].numArgs == 1) { if (nextToken+1 >= argc) return -1; optarg = argv[nextToken+1]; nextToken += 2; } else nextToken++; return str[0]; } } return -1; } void SetDefaults() { options.valet = VALET_IMPS_ACROSS_FIELD; options.directory = "."; options.nameFile = "names.txt"; options.scoresFile = "scores.txt"; options.roundFlag = false; options.roundFirst = 0; options.roundLast = 0; options.minHands = 0; options.leadFlag = false; options.datumFilter = false; options.datumHardRounding = false; options.cloudFlag = true; options.tableauFlag = false; options.compensateFlag = false; options.sort = VALET_SORT_OVERALL; options.averageFlag = false; options.format = VALET_FORMAT_TEXT; options.separator = ','; } void PrintOptions() { cout << left; cout << setw(12) << "valettype" << setw(12) << scoringTags[options.valet].arg << "\n"; cout << setw(12) << "directory" << setw(12) << options.directory << "\n"; cout << setw(12) << "names" << setw(12) << options.nameFile << "\n"; cout << setw(12) << "scores" << setw(12) << options.scoresFile << "\n"; if (options.roundFlag) cout << setw(12) << "rounds" << options.roundFirst << " to " << options.roundLast << "\n"; else cout << setw(12) << "rounds" << "no limitation\n"; cout << setw(12) << "minhands" << setw(12) << options.minHands << "\n"; cout << setw(12) << "lead" << setw(12) << (options.leadFlag ? "true" : "false") << "\n"; cout << setw(12) << "extremes" << setw(12) << (options.datumFilter ? "true" : "false") << "\n"; cout << setw(12) << "hardround" << setw(12) << (options.datumHardRounding ? "true" : "false") << "\n"; cout << setw(12) << "cloud" << setw(12) << (options.cloudFlag ? "true" : "false") << "\n"; cout << setw(12) << "tableau" << setw(12) << (options.datumHardRounding ? options.tableauFile : "false") << "\n"; cout << setw(12) << "compensate" << setw(12) << (options.compensateFlag ? "true" : "false") << "\n"; cout << setw(12) << "order" << setw(12) << sortingTags[options.sort].str << "\n"; cout << setw(12) << "average" << setw(12) << (options.averageFlag ? "true" : "false") << "\n"; cout << setw(12) << "format" << setw(12) << (options.format == VALET_FORMAT_TEXT ? "text" : "csv") << "\n"; cout << setw(12) << "join" << setw(12) << options.separator << "\n"; cout << "\n" << right; } bool ParseRound() { // Allow 5 as well as 1-3 char * temp; int m = static_cast<int>(strtol(optarg, &temp, 0)); if (* temp == '\0') { if (m <= 0) { return false; } else { options.roundFirst = static_cast<unsigned>(m); options.roundLast = static_cast<unsigned>(m); return true; } } string stmp(optarg); string::size_type pos; pos = stmp.find_first_of("-", 0); if (pos == std::string::npos || pos > 7) return false; char str1[8], str2[8]; #if (! defined(_MSC_VER) || _MSC_VER < 1400) strncpy(str1, stmp.c_str(), pos); #else strncpy_s(str1, stmp.c_str(), pos); #endif str1[pos] = '\0'; if ((m = atoi(str1)) <= 0) return false; options.roundFirst = static_cast<unsigned>(m); stmp.erase(0, pos+1); #if (! defined(_MSC_VER) || _MSC_VER < 1400) strncpy(str2, stmp.c_str(), stmp.size()); #else strncpy_s(str2, stmp.c_str(), stmp.size()); #endif str2[stmp.size()] = '\0'; if ((m = atoi(str2)) <= 0) return false; options.roundLast = static_cast<unsigned>(m); if (options.roundLast < options.roundFirst) return false; return true; } void ReadArgs( int argc, char * argv[]) { for (unsigned i = 0; i < VALET_NUM_OPTIONS; i++) { shortOptsAll += optList[i].shortName; if (optList[i].numArgs) shortOptsWithArg += optList[i].shortName; } if (argc == 1) { Usage(argv[0]); exit(0); } SetDefaults(); int c, m; bool errFlag = false, matchFlag; string stmp; while ((c = GetNextArgToken(argc, argv)) > 0) { switch(c) { case 'v': stmp = optarg; matchFlag = false; for (unsigned i = 0; i < 3; i++) { if (stmp == scoringTags[i].arg) { options.valet = scoringTags[i].scoring; matchFlag = true; break; } } if (! matchFlag) { cout << "valet must be written exactly as in the list\n"; nextToken -= 2; errFlag = true; } break; case 'd': options.directory = optarg; break; case 'n': options.nameFile = optarg; break; case 's': options.scoresFile = optarg; break; case 'r': options.roundFlag = true; if (! ParseRound()) { cout << " Could not parse round\n"; nextToken -= 2; errFlag = true; } break; case 'm': char * temp; m = static_cast<int>(strtol(optarg, &temp, 0)); if (m < 1) { cout << "Number of hands must be >= 1\n\n"; nextToken -= 2; errFlag = true; } options.minHands = static_cast<unsigned>(m); break; case 'l': options.leadFlag = true; break; case 'e': options.datumFilter = true; break; case 'h': options.datumHardRounding = true; break; case 'x': options.cloudFlag = false; break; case 't': options.tableauFlag = true; options.tableauFile = optarg; break; case 'c': options.compensateFlag = true; break; case 'o': stmp = optarg; matchFlag = false; for (unsigned i = 0; i < 8; i++) { if (stmp == sortingTags[i].str) { options.sort = sortingTags[i].sort; matchFlag = true; break; } } if (! matchFlag) { cout << "order must be written exactly as in the list\n"; nextToken -= 2; errFlag = true; } break; case 'a': options.averageFlag = true; break; case 'f': stmp = optarg; if (stmp == "text") options.format = VALET_FORMAT_TEXT; else if (stmp == "csv") options.format = VALET_FORMAT_CSV; else { cout << "format must be text or csv\n"; nextToken -= 2; errFlag = true; } break; case 'j': options.separator = optarg; if (options.separator.size() != 1) { cout << "char must consist of a single character\n"; nextToken -= 2; errFlag = true; } break; default: cout << "Unknown option\n"; errFlag = true; break; } if (errFlag) break; } if (errFlag || c == -1) { cout << "Error while parsing option '" << argv[nextToken] << "'\n"; cout << "Invoke the program without arguments for help" << endl; exit(0); } }
25.06823
79
0.514417
valet-bridge
8e91c7f6dbd37560842a3312c31bd1bb3530d8c5
1,258
cpp
C++
source/ktwgEngine/Shaders/cpp/SimpleForwardParams.cpp
JasonWyx/ktwgEngine
410ba799f7000895995b9f9fc59d738f293f8871
[ "MIT" ]
null
null
null
source/ktwgEngine/Shaders/cpp/SimpleForwardParams.cpp
JasonWyx/ktwgEngine
410ba799f7000895995b9f9fc59d738f293f8871
[ "MIT" ]
12
2019-09-15T07:48:18.000Z
2019-12-08T17:23:22.000Z
source/ktwgEngine/Shaders/cpp/SimpleForwardParams.cpp
JasonWyx/ktwgEngine
410ba799f7000895995b9f9fc59d738f293f8871
[ "MIT" ]
null
null
null
#include "SimpleForwardParams.h" #include "../../d3d11staticresources.h" #include "../../d3d11device.h" #include "../../d3d11renderapi.h" #include "../../d3d11hardwarebuffer.h" DEFINE_STATIC_BUFFER(SimpleForwardParamsCbuf); void ShaderInputs::SimpleForwardParams::InitializeHWResources() { D3D11Device* device = D3D11RenderAPI::GetInstance().GetDevice(); GET_STATIC_RESOURCE(SimpleForwardParamsCbuf) = new D3D11HardwareBuffer{ device, D3D11_BT_CONSTANT, D3D11_USAGE_DYNAMIC, 4, sizeof(float), false, false, true, false }; } void ShaderInputs::SimpleForwardParams::SetColor(float r, float g, float b, float a) { m_Color[0] = r; m_Color[1] = g; m_Color[2] = b; m_Color[3] = a; } void ShaderInputs::SimpleForwardParams::GetColor(float & r, float & g, float & b, float & a) { r = m_Color[0]; g = m_Color[1]; b = m_Color[2]; a = m_Color[3]; } void ShaderInputs::SimpleForwardParams::Set() { D3D11Device* device = D3D11RenderAPI::GetInstance().GetDevice(); device->GetImmediateContext().AddConstantBuffer<VS>(GET_STATIC_RESOURCE(SimpleForwardParamsCbuf)); device->GetImmediateContext().FlushConstantBuffers(SimpleForwardParamsSlot); GET_STATIC_RESOURCE(SimpleForwardParamsCbuf)->Write(0, 4 * sizeof(float), m_Color, WT_DISCARD); }
33.105263
168
0.744038
JasonWyx
8e9237b34847f87599b4046af1bf3917cb94a324
1,985
cpp
C++
catdoor_v2/tests/solenoids/src/main.cpp
flupes/catdoor
bf718f4ebdfb8cc60c04d42d3d88a4a875f0bc7f
[ "Apache-2.0" ]
null
null
null
catdoor_v2/tests/solenoids/src/main.cpp
flupes/catdoor
bf718f4ebdfb8cc60c04d42d3d88a4a875f0bc7f
[ "Apache-2.0" ]
null
null
null
catdoor_v2/tests/solenoids/src/main.cpp
flupes/catdoor
bf718f4ebdfb8cc60c04d42d3d88a4a875f0bc7f
[ "Apache-2.0" ]
null
null
null
#include <Arduino.h> #include "m0_hf_pwm.h" #include "solenoids.h" #include "utils.h" Solenoids& sol = Solenoids::Instance(); void setup() { pwm_configure(); #ifdef USE_SERIAL Serial.begin(115200); while (!Serial) { ; // wait for serial port to connect to start the app } #endif PRINTLN("open in 5s"); delay(5000); sol.open(); delay(3000); PRINTLN("release"); sol.release(); PRINTLN("open (other side) is 5s"); delay(5000); sol.open(); delay(3000); PRINTLN("release"); sol.release(); PRINTLN("unjam is 5s"); delay(5000); sol.unjam(); PRINTLN("should release in 2s"); delay(8000); PRINTLN("should unjam again, now"); sol.unjam(); PRINTLN("should release in 2s"); delay(8000); PRINTLN("open and do not release (hot timer should release)"); sol.open(); delay(Solenoids::MAX_ON_DURATION_MS + 4000); PRINTLN("try to open again, but should not work (because hot)"); sol.open(); delay(Solenoids::COOLDOWN_DURATION_MS); PRINTLN("cold now, double open/release"); sol.open(); delay(500); sol.release(); delay(500); sol.open(); delay(500); sol.release(); PRINTLN("open in 5s"); delay(5000); sol.open(); delay(1000); PRINTLN("open again, now, but should not do anything since still open"); sol.open(); delay(4000); PRINTLN("release"); sol.release(); PRINTLN("open in 5s"); delay(5000); sol.open(); delay(1000); PRINTLN("unjam now (before release)"); sol.unjam(); PRINTLN("should release automatically"); delay(8000); PRINTLN(" before this message"); sol.release(); PRINTLN("double open/release"); sol.open(); delay(500); sol.release(); delay(500); sol.open(); delay(500); sol.release(); PRINTLN("done."); } void loop() { delay(10); #if 0 // Old Tests pwm_set(5, 512); delay(500); pwm_set(5, 300); delay(500); pwm_set(6, 512); delay(500); pwm_set(6, 128); delay(4000); pwm_set(5, 0); pwm_set(6, 0); delay(8000); #endif }
18.726415
74
0.63073
flupes
8e9305816904c0b57e845732123269d7b633b295
935
cc
C++
list/reversed_linked_list.cc
windscope/Cracking
0db01f531ff56428bafff72aaea1d046dbc14112
[ "Apache-2.0" ]
null
null
null
list/reversed_linked_list.cc
windscope/Cracking
0db01f531ff56428bafff72aaea1d046dbc14112
[ "Apache-2.0" ]
null
null
null
list/reversed_linked_list.cc
windscope/Cracking
0db01f531ff56428bafff72aaea1d046dbc14112
[ "Apache-2.0" ]
null
null
null
// Reverse Linked List // https://leetcode.com/problems/reverse-linked-list/ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ #include <cassert> #include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* reverseList(ListNode* head) { if (head == nullptr) { return nullptr; } ListNode* next_head = head->next; head->next = nullptr; ListNode* ret_head = head; while (next_head != nullptr) { ListNode* ret_head_next = ret_head; ret_head = next_head; next_head = next_head->next; ret_head->next = ret_head_next; } } }; int main() { cout << "You Passed" << endl; return 0; }
19.479167
53
0.562567
windscope
8e93b94653d2a195f6e71e7d32f00cd54d02a1ec
1,255
cpp
C++
source/model-generator/JoinOverrideGenerator.cpp
bbhunter/mariana-trench
3973f047446182977809ea4ae2b76153a35943f8
[ "MIT" ]
null
null
null
source/model-generator/JoinOverrideGenerator.cpp
bbhunter/mariana-trench
3973f047446182977809ea4ae2b76153a35943f8
[ "MIT" ]
null
null
null
source/model-generator/JoinOverrideGenerator.cpp
bbhunter/mariana-trench
3973f047446182977809ea4ae2b76153a35943f8
[ "MIT" ]
null
null
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <mariana-trench/Model.h> #include <mariana-trench/model-generator/JoinOverrideGenerator.h> namespace marianatrench { std::vector<Model> JoinOverrideGenerator::visit_method( const Method* method) const { std::vector<Model> models; // Do not join models at call sites for methods with too many overrides. const auto& overrides = context_.overrides->get(method); if (overrides.size() >= Heuristics::kJoinOverrideThreshold) { models.push_back( Model(method, context_, Model::Mode::NoJoinVirtualOverrides)); } else { const auto class_name = generator::get_class_name(method); if ((boost::starts_with(class_name, "Landroid") || boost::starts_with(class_name, "Lcom/google") || boost::starts_with(class_name, "Lkotlin/") || boost::starts_with(class_name, "Ljava")) && overrides.size() >= Heuristics::kAndroidJoinOverrideThreshold) { models.push_back( Model(method, context_, Model::Mode::NoJoinVirtualOverrides)); } } return models; } } // namespace marianatrench
33.026316
74
0.701195
bbhunter
8e95d0497dcaaf0712c7bde70764b4140ed2013d
3,306
cpp
C++
src/core/tests/visitors/op/interpolate.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
1,127
2018-10-15T14:36:58.000Z
2020-04-20T09:29:44.000Z
src/core/tests/visitors/op/interpolate.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
439
2018-10-20T04:40:35.000Z
2020-04-19T05:56:25.000Z
src/core/tests/visitors/op/interpolate.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
414
2018-10-17T05:53:46.000Z
2020-04-16T17:29:53.000Z
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "gtest/gtest.h" #include "ngraph/ngraph.hpp" #include "ngraph/op/util/attr_types.hpp" #include "ngraph/opsets/opset1.hpp" #include "ngraph/opsets/opset3.hpp" #include "ngraph/opsets/opset4.hpp" #include "ngraph/opsets/opset5.hpp" #include "util/visitor.hpp" using namespace std; using namespace ngraph; using ngraph::test::NodeBuilder; using ngraph::test::ValueMap; TEST(attributes, interpolate_op1) { NodeBuilder::get_ops().register_factory<opset1::Interpolate>(); auto img = make_shared<op::Parameter>(element::f32, Shape{1, 3, 32, 32}); auto out_shape = make_shared<op::Parameter>(element::i32, Shape{2}); op::v0::InterpolateAttrs interp_atrs; interp_atrs.axes = AxisSet{1, 2}; interp_atrs.mode = "cubic"; interp_atrs.align_corners = true; interp_atrs.antialias = true; interp_atrs.pads_begin = vector<size_t>{0, 0}; interp_atrs.pads_end = vector<size_t>{0, 0}; auto interpolate = make_shared<opset1::Interpolate>(img, out_shape, interp_atrs); NodeBuilder builder(interpolate); auto g_interpolate = ov::as_type_ptr<opset1::Interpolate>(builder.create()); const auto i_attrs = interpolate->get_attrs(); const auto g_i_attrs = g_interpolate->get_attrs(); EXPECT_EQ(g_i_attrs.axes, i_attrs.axes); EXPECT_EQ(g_i_attrs.mode, i_attrs.mode); EXPECT_EQ(g_i_attrs.align_corners, i_attrs.align_corners); EXPECT_EQ(g_i_attrs.antialias, i_attrs.antialias); EXPECT_EQ(g_i_attrs.pads_begin, i_attrs.pads_begin); EXPECT_EQ(g_i_attrs.pads_end, i_attrs.pads_end); } TEST(attributes, interpolate_op4) { NodeBuilder::get_ops().register_factory<opset4::Interpolate>(); auto img = make_shared<op::Parameter>(element::f32, Shape{1, 3, 32, 32}); auto out_shape = make_shared<op::Parameter>(element::i32, Shape{2}); auto scales = op::v0::Constant::create(element::f32, {1}, {1.0}); op::v4::Interpolate::InterpolateAttrs attrs; attrs.mode = op::v4::Interpolate::InterpolateMode::NEAREST; attrs.shape_calculation_mode = op::v4::Interpolate::ShapeCalcMode::SIZES; attrs.coordinate_transformation_mode = op::v4::Interpolate::CoordinateTransformMode::HALF_PIXEL; attrs.nearest_mode = op::v4::Interpolate::NearestMode::ROUND_PREFER_FLOOR; attrs.pads_begin = vector<size_t>{0, 0}; attrs.pads_end = vector<size_t>{0, 0}; attrs.antialias = true; attrs.cube_coeff = -0.75; auto interpolate = make_shared<opset4::Interpolate>(img, out_shape, scales, attrs); NodeBuilder builder(interpolate); auto g_interpolate = ov::as_type_ptr<opset4::Interpolate>(builder.create()); const auto i_attrs = interpolate->get_attrs(); const auto g_i_attrs = g_interpolate->get_attrs(); EXPECT_EQ(g_i_attrs.mode, i_attrs.mode); EXPECT_EQ(g_i_attrs.shape_calculation_mode, i_attrs.shape_calculation_mode); EXPECT_EQ(g_i_attrs.coordinate_transformation_mode, i_attrs.coordinate_transformation_mode); EXPECT_EQ(g_i_attrs.nearest_mode, i_attrs.nearest_mode); EXPECT_EQ(g_i_attrs.pads_begin, i_attrs.pads_begin); EXPECT_EQ(g_i_attrs.pads_end, i_attrs.pads_end); EXPECT_EQ(g_i_attrs.antialias, i_attrs.antialias); EXPECT_EQ(g_i_attrs.cube_coeff, i_attrs.cube_coeff); }
42.384615
100
0.740472
ryanloney
8e97a5b95fe2ad04a91d0beb91126d71b13e1664
1,885
cpp
C++
state.cpp
sl424/hunting-game
f79bea39a061c8b8cfbf430ab0d73cd6539ddb0f
[ "Apache-2.0" ]
null
null
null
state.cpp
sl424/hunting-game
f79bea39a061c8b8cfbf430ab0d73cd6539ddb0f
[ "Apache-2.0" ]
null
null
null
state.cpp
sl424/hunting-game
f79bea39a061c8b8cfbf430ab0d73cd6539ddb0f
[ "Apache-2.0" ]
null
null
null
/*************************************************** * Program Filename: state.cpp * Author: Chewie Lin * Date: 12 Feb 2016 * Description: main driver functions ***************************************************/ #include "state.hpp" /***************************************** * Function: pEnter() * Description: press enter to continue ******************************************/ void pEnter() { std::cin.ignore(125,'\n'); std::cout << "Press enter to continue: " << std::flush; std::cin.ignore(125,'\n'); } /***************************************** * Function: pick() * Description: ask user input ******************************************/ int pick() { int pick; do { std::cout << "Select a creature: "; std::cin >> pick; if ( std::cin.fail() || pick < 1 || pick > 5 ) { std::cout << "invalid pick" << std::endl; std::cin.clear(); std::cin.ignore(256,'\n'); } } while ( pick < 1 || pick > 5 ); return pick; } /***************************************** * Function: showGraphics() * Description: ******************************************/ void showGraphics(std::string& s) { std::string aline; std::ifstream input; input.open(s.c_str(), std::ifstream::in); if ( input.is_open() ) { while ( std::getline (input,aline) ) std::cout << aline << '\n'; input.close(); } else std::cout << "error opening file"; } /***************************************** * Function: displayMenu() * Description: show the list of creatures ******************************************/ bool displayMenu() { char a; do { std::cout << " 0: How to play \n 1: Start Game \n 2: Quit \n"; std::cout << "Enter input: "; std::cin >> a; if ( a == '0' ) showGamePlay(); if ( a == '1' ) return true; else if ( a == '2' ) return false; } while ( a != '1' && a != '2' ); } void showGamePlay(){ std::string s = "gameplay.txt"; showGraphics(s); }
24.802632
63
0.448276
sl424
8e9a7dfe8704ce896e0a39c9eea55cf64eb395f7
89
cpp
C++
applications/Example/Example.cpp
203Electronics/MatrixOS
ea6d84b21a97f58e2077d37d5645c5339f344d77
[ "MIT" ]
8
2021-12-30T05:29:16.000Z
2022-03-30T08:44:45.000Z
applications/Example/Example.cpp
203Electronics/MatrixOS
ea6d84b21a97f58e2077d37d5645c5339f344d77
[ "MIT" ]
null
null
null
applications/Example/Example.cpp
203Electronics/MatrixOS
ea6d84b21a97f58e2077d37d5645c5339f344d77
[ "MIT" ]
null
null
null
#include "Example.h" void ExampleAPP::Setup() { } void ExampleAPP::Loop() { }
7.416667
24
0.58427
203Electronics
8ea74d1a47c9c79b1f9ab67b2ce4a36f7bc94a10
1,380
cc
C++
test/HttpServer/compute_unittest.cc
wfrest/wfrest
5aa8c3ab5ad749ef8e9b93c8aa32d8c475062dde
[ "Apache-2.0" ]
312
2021-12-05T15:17:27.000Z
2022-03-30T10:53:01.000Z
test/HttpServer/compute_unittest.cc
chanchann/wfrest
5aa8c3ab5ad749ef8e9b93c8aa32d8c475062dde
[ "Apache-2.0" ]
15
2021-12-14T16:01:15.000Z
2022-03-15T04:27:47.000Z
test/HttpServer/compute_unittest.cc
wfrest/wfrest
5aa8c3ab5ad749ef8e9b93c8aa32d8c475062dde
[ "Apache-2.0" ]
46
2021-12-06T08:08:45.000Z
2022-03-01T06:26:38.000Z
#include "workflow/WFFacilities.h" #include "workflow/Workflow.h" #include <gtest/gtest.h> #include "wfrest/HttpServer.h" #include "wfrest/ErrorCode.h" using namespace wfrest; using namespace protocol; WFHttpTask *create_http_task(const std::string &path) { return WFTaskFactory::create_http_task("http://127.0.0.1:8888/" + path, 4, 2, nullptr); } void Factorial(int n, HttpResp *resp) { unsigned long long factorial = 1; for(int i = 1; i <= n; i++) { factorial *= i; } resp->String(std::to_string(factorial)); } TEST(HttpServer, String_short_str) { HttpServer svr; WFFacilities::WaitGroup wait_group(1); svr.GET("/test", [](const HttpReq *req, HttpResp *resp) { resp->Compute(1, Factorial, 10, resp); }); EXPECT_TRUE(svr.start("127.0.0.1", 8888) == 0) << "http server start failed"; WFHttpTask *client_task = create_http_task("test"); client_task->set_callback([&wait_group](WFHttpTask *task) { const void *body; size_t body_len; task->get_resp()->get_parsed_body(&body, &body_len); EXPECT_TRUE(strcmp("3628800", static_cast<const char *>(body)) == 0); wait_group.done(); }); client_task->start(); wait_group.wait(); svr.stop(); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
24.210526
91
0.642029
wfrest
8ea86625c443698315f5223a9ad55d2a3299a44b
242
cpp
C++
tests/aoj/bigint.multiplication_bigint_1.test.cpp
Zeldacrafter/CompProg
5367583f45b6fe30c4c84f3ae81accf14f8f7fd3
[ "Unlicense" ]
4
2020-02-06T15:44:57.000Z
2020-12-21T03:51:21.000Z
tests/aoj/bigint.multiplication_bigint_1.test.cpp
Zeldacrafter/CompProg
5367583f45b6fe30c4c84f3ae81accf14f8f7fd3
[ "Unlicense" ]
null
null
null
tests/aoj/bigint.multiplication_bigint_1.test.cpp
Zeldacrafter/CompProg
5367583f45b6fe30c4c84f3ae81accf14f8f7fd3
[ "Unlicense" ]
null
null
null
#define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=NTL_2_C" #include "../../code/utils/bigint.cc" int main() { cin.tie(0); ios_base::sync_with_stdio(0); bigint a, b; cin >> a >> b; cout << a * b << endl; }
18.615385
82
0.619835
Zeldacrafter
8ea8a2ac3154f2b3d99c1dffbf24fc33b56b1b3c
3,018
cpp
C++
test/tsarray2.cpp
drypot/san-2.x
44e626793b1dc50826ba0f276d5cc69b7c9ca923
[ "MIT" ]
5
2019-12-27T07:30:03.000Z
2020-10-13T01:08:55.000Z
test/tsarray2.cpp
drypot/san-2.x
44e626793b1dc50826ba0f276d5cc69b7c9ca923
[ "MIT" ]
null
null
null
test/tsarray2.cpp
drypot/san-2.x
44e626793b1dc50826ba0f276d5cc69b7c9ca923
[ "MIT" ]
1
2020-07-27T22:36:40.000Z
2020-07-27T22:36:40.000Z
#include <pub\config.hpp> #include <stdpub\io.hpp> #include <pub\except.hpp> #include <pub\inline.hpp> #include <pub\char.hpp> #include <cnt\sarray.tem> #include <conpub\io.hpp> #include <time.h> #include <pub\buffer.hpp> #include <pub\fbuf.hpp> typedef sarray<char16,8*1024> arrayt; //char* fname = "fmid"; char* fname = "fbig"; buffer<char16,8*1024> buf; arrayt ary; clock_t clk; FILE* f; int32 cnt,i; void view(arrayt* pa) { arrayt::frame* p; p = pa->head.p_next; while (p!= (arrayt::frame*) &pa->tail) { printf("%4d ",p->cnt); p = p->p_next; } printf("\n"); } void iter_test() { printf("iter ready\n"); getch(); printf("iter start\n"); clk = clock(); forcnt(i,cnt) ary[i]=ary[i]+1; printf("%u clocks\n",clock()-clk); printf("end\n"); } void fread_test() { //ifbuf f("fbig",32*1024); int ch; cnt = 0; buf.reset(); ary.reset(); f = fopen(fname,"rb"); printf("ready\n"); getch(); printf("start\n"); clk = clock(); while (ch = fgetc(f) , ch != EOF) ary[cnt++] = ch; printf("%u clocks\n",clock()-clk); printf("%d chars\n",cnt); fclose(f); } void fread2_test() { //ifbuf f("fbig",32*1024); int ch; int ch2; cnt = 0; buf.reset(); ary.reset(); f = fopen(fname,"rb"); printf("ready\n"); getch(); printf("start\n"); clk = clock(); while (ch = fgetc(f) , ch != EOF) { cnt++; if (is_full((byte)ch)) { ch2 = fgetc(f); buf.append(char16_make(ch,ch2)); } else buf.append(ch); if (buf.is_full()) { ary.locate_end(); ary.insert(buf.cnt()); ary.read(buf,buf.cnt()); buf.reset(); //view(&ary); //getch(); } } printf("%u clocks\n",clock()-clk); printf("%d chars\n",cnt); fclose(f); } void fread3_test() { ifbuf f(fname,16*1024); int ch; int ch2; cnt = 0; buf.reset(); ary.reset(); printf("ready\n"); getch(); printf("start\n"); clk = clock(); forever { if ( f.rest() <= 2 ) { if ( f.file_rest() == 0 ) { if ( f.rest() == 1 && is_full(f.peek8()) ) f.append(0); if ( f.rest() == 0 ) break; } else f.fill(); } ch = f.get8(); cnt++; if (is_full((byte)ch)) { ch2 = f.get8(); buf.append(char16_make(ch,ch2)); } else buf.append(ch); if (buf.is_full()) { ary.locate_end(); ary.insert(buf.cnt()); ary.read(buf,buf.cnt()); buf.reset(); //view(&ary); //getch(); } } printf("%u clocks\n",clock()-clk); printf("%d chars\n",cnt); } void main() { touch_err_module(); throw int(); fread_test(); fread2_test(); //fread3_test(); //test_iter(); }
18.745342
68
0.470179
drypot