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
109
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
48.5k
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
fc39f8dfa8e2c14eb979d3dcc2e98825f4f00f24
3,084
cpp
C++
source/tracker/tracker.cpp
ponpiste/BitTorrent
cad7ac1af64ac3075ee1c7b0516458612b1f9a4c
[ "MIT" ]
1
2022-01-19T15:25:31.000Z
2022-01-19T15:25:31.000Z
source/tracker/tracker.cpp
ponpiste/BitTorrent
cad7ac1af64ac3075ee1c7b0516458612b1f9a4c
[ "MIT" ]
null
null
null
source/tracker/tracker.cpp
ponpiste/BitTorrent
cad7ac1af64ac3075ee1c7b0516458612b1f9a4c
[ "MIT" ]
1
2020-10-12T01:50:20.000Z
2020-10-12T01:50:20.000Z
#include "tracker/tracker.h" #include <stdlib.h> #include <time.h> #include <vector> #include "tracker/udp.h" #include "tracker/url.h" #include <algorithm> #include <stdexcept> #include "download/peer_id.h" #include "parsing/bencode.h" using namespace std; buffer tracker::build_conn_req_udp() { const int SIZE_CONN = 16; const int RANDOM_SIZE = 4; unsigned char msg[SIZE_CONN] = {0x00, 0x00, 0x04, 0x17, 0x27, 0x10, 0x19, 0x80, 0x00, 0x00, 0x00, 0x00}; for(int i=0;i<RANDOM_SIZE;i++){ msg[SIZE_CONN-RANDOM_SIZE+i]=rand() % 256; } return buffer(msg,msg+SIZE_CONN); } void tracker::build_ann_req_http(http& request, const torrent& t) { // info_hash request.add_argument("info_hash", t.info_hash); //peer_id request.add_argument("peer_id", peer_id::get()); // port request.add_argument("port", "6881"); // uploaded request.add_argument("uploaded", "0"); // downloaded request.add_argument("downloaded", "0"); // compact request.add_argument("compact", "1"); // left request.add_argument("left", to_string(t.length)); } buffer tracker::build_ann_req_udp(const buffer& b, const torrent& t) { const int SIZE_ANN = 98; buffer buff(SIZE_ANN, 0x00); // connection id copy(b.begin()+8, b.begin()+16, buff.begin()); // action buff[11]=1; // transaction id copy(b.begin()+4,b.begin()+8, buff.begin()+12); // info hash copy(t.info_hash.begin(), t.info_hash.end(), buff.begin()+16); // peer id buffer id = peer_id::get(); copy(id.begin(), id.end(), buff.begin()+36); // left long long x = t.length; for(int i=0;i<4;i++){ buff[64+8-i-1] = x % 256; x/=256; } // key for(int i=0;i<4;i++){ buff[88+i] = rand() % 256; } // num_want for(int i=0;i<4;i++){ buff[92+i] = 0xff; } // port // Todo: allow port between 6881 and 6889 int port = 6881; buff[97] = port % 256; buff[96] = (port / 256) % 256; return buff; } vector<peer> tracker::get_peers(const torrent& t) { if (t.url.protocol == url_t::UDP) { udp client(t.url.host, t.url.port); client.send(build_conn_req_udp()); buffer b = client.receive(); client.send(build_ann_req_udp(b, t)); buffer c = client.receive(); const int PEER_OFFSET = 20; c.erase(c.begin(), c.begin() + PEER_OFFSET); return get_peers(c); } else if (t.url.protocol == url_t::HTTP) { buffer encoded; while(encoded.size() == 0) { http request(t.url); build_ann_req_http(request, t); encoded = request.get(); } bencode::item item = bencode::parse(encoded); buffer peer_bytes = item.get_buffer("peers"); return get_peers(peer_bytes); } throw runtime_error("protocol not recognized"); } vector<peer> tracker::get_peers(const buffer& b) { const int PEER_BYTE_SIZE = 6; buffer::size_type n = b.size(); if(n % PEER_BYTE_SIZE != 0) throw runtime_error("peer list not a multiple of 6"); vector<peer> peers; for(auto i = 0; i < n; i+=6) { string host = to_string(b[i]); for(int j=1;j<4;j++){ host += "." + to_string(b[i+j]); } int port = getBE16(b,i+4); peers.push_back(peer(host, port)); } return peers; }
19.396226
82
0.645266
ponpiste
fc3a4806e7045c1da477929085774722c2fe0e4b
583
cpp
C++
geometria/orden.radial.cpp
AlgorithmCR/eldiego
f1c01061467ce8a50a5e6134ab6ea09c9bcd7e0f
[ "MIT" ]
31
2015-11-15T19:24:17.000Z
2018-09-27T01:45:24.000Z
geometria/orden.radial.cpp
AlgorithmCR/eldiego
f1c01061467ce8a50a5e6134ab6ea09c9bcd7e0f
[ "MIT" ]
23
2015-09-23T15:56:32.000Z
2016-05-04T02:48:16.000Z
geometria/orden.radial.cpp
AlgorithmCR/eldiego
f1c01061467ce8a50a5e6134ab6ea09c9bcd7e0f
[ "MIT" ]
7
2016-08-25T21:29:56.000Z
2018-07-22T03:39:51.000Z
struct Cmp{//orden total de puntos alrededor de un punto r pto r; Cmp(pto r):r(r) {} int cuad(const pto &a) const{ if(a.x > 0 && a.y >= 0)return 0; if(a.x <= 0 && a.y > 0)return 1; if(a.x < 0 && a.y <= 0)return 2; if(a.x >= 0 && a.y < 0)return 3; assert(a.x ==0 && a.y==0); return -1; } bool cmp(const pto&p1, const pto&p2)const{ int c1 = cuad(p1), c2 = cuad(p2); if(c1==c2) return p1.y*p2.x<p1.x*p2.y; else return c1 < c2; } bool operator()(const pto&p1, const pto&p2) const{ return cmp(pto(p1.x-r.x,p1.y-r.y),pto(p2.x-r.x,p2.y-r.y)); } };
27.761905
62
0.548885
AlgorithmCR
fc3dc1daa50e1b7aff83bdc001d2deeded71d3a8
7,478
cpp
C++
base/string/format/scan_test.cpp
hjinlin/toft
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
[ "BSD-3-Clause" ]
264
2015-01-03T11:50:17.000Z
2022-03-17T02:38:34.000Z
base/string/format/scan_test.cpp
hjinlin/toft
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
[ "BSD-3-Clause" ]
12
2015-04-27T15:17:34.000Z
2021-05-01T04:31:18.000Z
base/string/format/scan_test.cpp
hjinlin/toft
ebf3ebb3d37e9a59e27b197cefe8fdc3e8810441
[ "BSD-3-Clause" ]
128
2015-02-07T18:13:10.000Z
2022-02-21T14:24:14.000Z
// Copyright (c) 2013, The TOFT Authors. // All rights reserved. // // Author: CHEN Feng <chen3feng@gmail.com> // Created: 2013-02-06 #include "toft/base/string/format/scan.h" #include <math.h> #include <stdint.h> #include "thirdparty/gtest/gtest.h" namespace toft { TEST(Scan, Escape) { int n = 0; ASSERT_EQ(1, StringScan("%1", "%%%d", &n)); EXPECT_EQ(1, n); } TEST(Scan, Bool) { bool b1, b2; ASSERT_EQ(2, StringScan("10", "%b%b", &b1, &b2)); EXPECT_TRUE(b1); EXPECT_FALSE(b2); ASSERT_EQ(2, StringScan(" 1 0", "%b%b", &b1, &b2)); EXPECT_TRUE(b1); EXPECT_FALSE(b2); ASSERT_EQ(1, StringScan("12", "%b%b", &b1, &b2)); EXPECT_TRUE(b1); ASSERT_EQ(2, StringScan("truefalse", "%b%b", &b1, &b2)); EXPECT_TRUE(b1); EXPECT_FALSE(b2); ASSERT_EQ(2, StringScan("true false", "%b%b", &b1, &b2)); EXPECT_TRUE(b1); EXPECT_FALSE(b2); ASSERT_EQ(1, StringScan("true faster", "%b%b", &b1, &b2)); EXPECT_TRUE(b1); ASSERT_EQ(2, StringScan("true0", "%v%v", &b1, &b2)); EXPECT_TRUE(b1); EXPECT_FALSE(b2); } TEST(Scan, Int) { int n = 0; unsigned int u = 0; ASSERT_EQ(1, StringScan("100", "%i", &n)); EXPECT_EQ(100, n); ASSERT_EQ(1, StringScan("200", "%d", &n)); EXPECT_EQ(200, n); ASSERT_EQ(1, StringScan("400", "%o", &n)); EXPECT_EQ(0400, n); ASSERT_EQ(1, StringScan("500", "%o", &u)); EXPECT_EQ(0500U, u); ASSERT_EQ(1, StringScan("600", "%x", &n)); EXPECT_EQ(0x600, n); ASSERT_EQ(1, StringScan("600", "%x", &u)); EXPECT_EQ(0x600U, u); } TEST(ScanDeathTest, IntInvalid) { int n = 0; ASSERT_DEBUG_DEATH(StringScan("300", "%u", &n), ""); } TEST(Scan, IntOverflow) { int8_t i8 = 1; ASSERT_EQ(0, StringScan("129", "%i", &i8)); EXPECT_EQ(0, StringScan("-129", "%i", &i8)); EXPECT_EQ(1, i8); uint8_t u8 = 1; ASSERT_EQ(0, StringScan("256", "%i", &u8)); EXPECT_EQ(0, StringScan("-1", "%i", &u8)); EXPECT_EQ(1, u8); int16_t i16 = 1; ASSERT_EQ(0, StringScan("32768", "%i", &i16)); EXPECT_EQ(0, StringScan("-32769", "%i", &i16)); EXPECT_EQ(1, i16); uint16_t u16 = 1; ASSERT_EQ(0, StringScan("65536", "%i", &u16)); EXPECT_EQ(0, StringScan("-1", "%i", &u16)); EXPECT_EQ(1, u16); int32_t i32 = 1; ASSERT_EQ(0, StringScan("0xFFFFFFFF1", "%i", &i32)); EXPECT_EQ(0, StringScan("-0xFFFFFFFF1", "%i", &i32)); EXPECT_EQ(1, i32); uint32_t u32 = 1; ASSERT_EQ(0, StringScan("0xFFFFFFFF1", "%i", &u32)); EXPECT_EQ(0, StringScan("-1", "%i", &u32)); EXPECT_EQ(1U, u32); int64_t i64 = 1; ASSERT_EQ(0, StringScan("0xFFFFFFFFFFFFFFFF1", "%i", &i64)); EXPECT_EQ(0, StringScan("-0xFFFFFFFFFFFFFFFF1", "%i", &i64)); EXPECT_EQ(1LL, i64); uint64_t u64 = 1; ASSERT_EQ(0, StringScan("0xFFFFFFFFFFFFFFFF1", "%i", &u64)); EXPECT_EQ(0, StringScan("-1", "%i", &u64)); EXPECT_EQ(1ULL, u64); } template <typename T> static void TestFloatCorrect(const char* format) { T v = 0.0; ASSERT_EQ(1, StringScan("3.14", format, &v)) << format; EXPECT_FLOAT_EQ(3.14, v); } TEST(Scan, Float) { TestFloatCorrect<float>("%f"); TestFloatCorrect<float>("%g"); TestFloatCorrect<float>("%e"); TestFloatCorrect<float>("%E"); TestFloatCorrect<float>("%a"); TestFloatCorrect<float>("%v"); TestFloatCorrect<double>("%f"); TestFloatCorrect<double>("%g"); TestFloatCorrect<double>("%e"); TestFloatCorrect<double>("%E"); TestFloatCorrect<double>("%a"); TestFloatCorrect<double>("%v"); TestFloatCorrect<double>("%lf"); TestFloatCorrect<double>("%lg"); TestFloatCorrect<double>("%le"); TestFloatCorrect<double>("%lE"); TestFloatCorrect<double>("%lv"); } template <typename T> static void TestFloatIncorrect(const char* format) { T v = 0.0; ASSERT_DEBUG_DEATH(StringScan("3.14", format, &v), ""); } TEST(ScanDeathTest, FloatInvalid) { TestFloatIncorrect<float>("%lf"); TestFloatIncorrect<float>("%lg"); TestFloatIncorrect<float>("%le"); TestFloatIncorrect<float>("%lE"); TestFloatIncorrect<float>("%lv"); } TEST(Scan, FloatOverflow) { float f; EXPECT_EQ(1, StringScan("1e50", "%f", &f)); EXPECT_EQ(1, isinf(f)); EXPECT_EQ(1, StringScan("-1e50", "%f", &f)); EXPECT_EQ(-1, isinf(f)); // Bypass bug of inff in glibc EXPECT_EQ(1, StringScan("1e-50", "%f", &f)); EXPECT_FLOAT_EQ(0.0f, f); double d; EXPECT_EQ(1, StringScan("1e500", "%f", &d)); EXPECT_EQ(1, isinf(d)); EXPECT_EQ(1, StringScan("-1e500", "%f", &d)); EXPECT_EQ(-1, isinf(d)); EXPECT_EQ(1, StringScan("1e-500", "%f", &d)); EXPECT_DOUBLE_EQ(0.0, d); long double ld; EXPECT_EQ(1, StringScan("1e5000", "%f", &ld)); EXPECT_EQ(1, isinf(ld)); EXPECT_EQ(1, StringScan("-1e5000", "%f", &ld)); EXPECT_EQ(-1, isinf(ld)); EXPECT_EQ(1, StringScan("1e-5000", "%f", &ld)); EXPECT_DOUBLE_EQ(0.0, ld); } TEST(Scan, String) { std::string s; ASSERT_EQ(1, StringScan("hello", "%s", &s)); EXPECT_EQ("hello", s); } TEST(Scan, StringLeadingSpace) { std::string s; ASSERT_EQ(1, StringScan(" hello", "%s", &s)); EXPECT_EQ("hello", s); } TEST(Scan, StringTailSpace) { std::string s; ASSERT_EQ(1, StringScan("hello ", "%s", &s)); EXPECT_EQ("hello", s); } TEST(Scan, StringAroundSpace) { std::string s; ASSERT_EQ(1, StringScan(" hello ", "%s", &s)); EXPECT_EQ("hello", s); } TEST(Scan, StringEmpty) { std::string s; ASSERT_EQ(0, StringScan(" ", "%s", &s)); std::string s1 = "s1"; ASSERT_EQ(1, StringScan("test ", "%s%s", &s, &s1)); EXPECT_EQ("test", s); EXPECT_EQ("s1", s1); } TEST(Scan, ScanSet) { std::string s; int i; ASSERT_EQ(1, StringScan("abcdef123", "%[a-z]", &s)); EXPECT_EQ("abcdef", s); ASSERT_EQ(1, StringScan("abcdef123", "%[a-z0-9]", &s)); EXPECT_EQ("abcdef123", s); ASSERT_EQ(1, StringScan(" abcdef123", "%[ \t]", &s)); EXPECT_EQ(" ", s); ASSERT_EQ(2, StringScan("abcdef123", "%[a-z]%d", &s, &i)); EXPECT_EQ("abcdef", s); EXPECT_EQ(123, i); ASSERT_EQ(2, StringScan("abcdef123", "%[^0-9]%d", &s, &i)); EXPECT_EQ("abcdef", s); EXPECT_EQ(123, i); } TEST(Scan, Mixed) { std::string s; unsigned int u; int i; ASSERT_EQ(3, StringScan("key=100hello 200", "key=%d%s%d", &u, &s, &i)); EXPECT_EQ("hello", s); EXPECT_EQ(100U, u); EXPECT_EQ(200, i); } TEST(Scan, Skip) { int i; ASSERT_EQ(1, StringScan("1,2,3", "%*d,%*d,%d", &i)); EXPECT_EQ(3, i); } TEST(Scan, Consumed) { int i; ASSERT_EQ(1, StringScan("hello", "%*s%n", &i)); EXPECT_EQ(5, i); } class PerformanceTest : public testing::Test {}; const int kLoopCount = 500000; const char kTestString[] = "1,2,4,8,16,32,64,128,256,512,1024,2048,4006,8192,16384,32768,65536"; #define TEST_FORMAT "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d" TEST_F(PerformanceTest, StringScan) { int n; for (int i = 0; i < kLoopCount; ++i) { StringScan(kTestString, TEST_FORMAT, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n); } } TEST_F(PerformanceTest, Sscanf) { int n; for (int i = 0; i < kLoopCount; ++i) { sscanf(kTestString, TEST_FORMAT, // NOLINT(runtime/printf) &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n, &n); } } } // namespace toft
23.815287
75
0.572078
hjinlin
fc402bfffe5fe870621af77a6755ff10bb13fb5e
49
hpp
C++
src/boost_type_traits_remove_volatile.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_type_traits_remove_volatile.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_type_traits_remove_volatile.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/type_traits/remove_volatile.hpp>
24.5
48
0.836735
miathedev
fc430bc77094a8d881350a93ed4f6b6d5b3d676b
2,238
cpp
C++
source/parse_globule.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
source/parse_globule.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
source/parse_globule.cpp
cloudy-astrophysics/cloudy_lfs
aed1d6d78042b93f17ea497a37b35a524f3d3e2e
[ "Zlib" ]
null
null
null
/* This file is part of Cloudy and is copyright (C)1978-2019 by Gary J. Ferland and * others. For conditions of distribution and use see copyright notice in license.txt */ /*ParseGlobule parse parameters off the globule command */ #include "cddefines.h" #include "radius.h" #include "dense.h" #include "optimize.h" #include "input.h" #include "parser.h" void ParseGlobule(Parser &p) { DEBUG_ENTRY( "ParseGlobule()" ); if( dense.gas_phase[ipHYDROGEN] > 0. ) { fprintf( ioQQQ, " PROBLEM DISASTER More than one density command was entered.\n" ); cdEXIT(EXIT_FAILURE); } /* globule with density increasing inward * parameters are outer density, radius of globule, and density power */ radius.glbden = (realnum)p.FFmtRead(); radius.glbden = p.lgEOL() ? 1.f : exp10(radius.glbden); dense.SetGasPhaseDensity( ipHYDROGEN, radius.glbden ); if( dense.gas_phase[ipHYDROGEN] <= 0. ) { fprintf( ioQQQ, " PROBLEM DISASTER Hydrogen density must be > 0.\n" ); cdEXIT(EXIT_FAILURE); } radius.glbrad = (realnum)p.FFmtRead(); if( p.lgEOL() ) { radius.glbrad = 3.086e18f; } else { radius.glbrad = exp10(radius.glbrad); } /* this is largest zone thickness, used to set first zone thickness */ radius.sdrmax = radius.glbrad/25.; radius.lgSdrmaxRel = false; /* turn off min dr checking in NEXTDR */ radius.lgDrMnOn = false; radius.glbpow = (realnum)p.FFmtRead(); if( p.lgEOL() ) radius.glbpow = 1.; strcpy( dense.chDenseLaw, "GLOB" ); /* this is distance to globule */ radius.glbdst = radius.glbrad; /* vary option */ if( optimize.lgVarOn ) { /* pointer to where to write */ optimize.nvfpnt[optimize.nparm] = input.nRead; /* this is the number of parameters to feed onto the input line */ optimize.nvarxt[optimize.nparm] = 3; // the keyword LOG is not used above, but is checked elsewhere strcpy( optimize.chVarFmt[optimize.nparm], "GLOBULE %f LOG %f %f" ); /* param is log of abundance by number relative to hydrogen */ optimize.vparm[0][optimize.nparm] = (realnum)log10(radius.glbden); optimize.vparm[1][optimize.nparm] = (realnum)log10(radius.glbrad); optimize.vparm[2][optimize.nparm] = radius.glbpow; optimize.vincr[optimize.nparm] = 0.2f; ++optimize.nparm; } return; }
29.064935
89
0.699285
cloudy-astrophysics
fc4387bcd7722c348014d92ee2580001bd33c40a
2,894
cpp
C++
Engine/posttoantigate.cpp
vadkasevas/BAS
657f62794451c564c77d6f92b2afa9f5daf2f517
[ "MIT" ]
302
2016-05-20T12:55:23.000Z
2022-03-29T02:26:14.000Z
Engine/posttoantigate.cpp
chulakshana/BAS
955f5a41bd004bcdd7d19725df6ab229b911c09f
[ "MIT" ]
9
2016-07-21T09:04:50.000Z
2021-05-16T07:34:42.000Z
Engine/posttoantigate.cpp
chulakshana/BAS
955f5a41bd004bcdd7d19725df6ab229b911c09f
[ "MIT" ]
113
2016-05-18T07:48:37.000Z
2022-02-26T12:59:39.000Z
#include "posttoantigate.h" #include "every_cpp.h" #include <QMap> #include <QPixmap> #include <QBuffer> #include <QMapIterator> namespace BrowserAutomationStudioFramework { PostToAntigate::PostToAntigate(QObject *parent) : QObject(parent) { } void PostToAntigate::Post(const QString& id,const QString& key,const QString& base64, const QMap<QString,QString>& Properties, const QString& soft, bool DisableImageConvert) { this->id = id; QHash<QString,ContentData> post; { ContentData DataMethod; DataMethod.DataString = "post"; post["method"] = DataMethod; } { ContentData DataKey; DataKey.DataString = key; post["key"] = DataKey; } { ContentData DataFile; if(DisableImageConvert) { DataFile.DataRaw = QByteArray::fromBase64(base64.toUtf8()); }else { QImage image = QImage::fromData(QByteArray::fromBase64(base64.toUtf8())); QByteArray ba; QBuffer buffer(&ba); buffer.open(QIODevice::WriteOnly); image.save(&buffer, "JPEG"); buffer.close(); DataFile.DataRaw = ba; } DataFile.FileName = "image.jpg"; DataFile.ContentType = "application/octet-stream"; post["file"] = DataFile; } if(!soft.isEmpty()) { ContentData DataSoftId; DataSoftId.DataString = soft; post["soft_id"] = DataSoftId; } QMapIterator<QString, QString> i(Properties); while (i.hasNext()) { i.next(); if(i.value().length() > 0 && i.key().length() > 0) { ContentData DataKey; DataKey.DataString = i.value(); post[i.key()] = DataKey; } } HttpClient->Connect(this,SLOT(submitRequestFinished())); HttpClient->Post(Server + "in.php",post); } void PostToAntigate::SetServer(const QString& Server) { this->Server = Server; } void PostToAntigate::submitRequestFinished() { if(HttpClient->WasError()) { emit PostedToAntigate(HttpClient->GetErrorString(),id,false); return; } QString res = HttpClient->GetContent(); if(!res.startsWith("OK|")) { emit PostedToAntigate(res,id,false); return; } QString r = res.remove(0,3); emit PostedToAntigate(r,id,true); } void PostToAntigate::SetHttpClient(IHttpClient * HttpClient) { this->HttpClient = HttpClient; } IHttpClient * PostToAntigate::GetHttpClient() { return HttpClient; } }
25.165217
177
0.533172
vadkasevas
fc4540e3a67875ca07a322da13529cbacca1c3bb
4,461
cpp
C++
Source/mysql/main.cpp
inkneko-software/dao_generator
88f000622677a355a2807750c59dff73913777e9
[ "MIT" ]
null
null
null
Source/mysql/main.cpp
inkneko-software/dao_generator
88f000622677a355a2807750c59dff73913777e9
[ "MIT" ]
null
null
null
Source/mysql/main.cpp
inkneko-software/dao_generator
88f000622677a355a2807750c59dff73913777e9
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <fstream> #include <vector> #include <map> #include <boost/filesystem.hpp> #include <boost/regex.hpp> using namespace std; using namespace boost::filesystem; using namespace boost; void tableObjectGenerator(const path& output, pair<string, vector<pair<string, string>>> tabledef) { string tableName = tabledef.first; std::fstream file(output.string() + "/" + tableName + ".h", std::fstream::out); if (tableName[0] <= 'z' && tableName[0] >= 'a') { tableName[0] -= 'a' - 'A'; } for (size_t i = 0; i < tableName.size(); ++i) { if (tableName[i] == '_') { if (tableName[i + 1] <= 'z' && tableName[i + 1] >= 'a') { tableName[i+1] -= 'a' - 'A'; } tableName = tableName.erase(i, 1); --i; } } file << "/************************************************************************************" << endl << " * Table: [" << tableName << "] " << endl << " * Generated by inkneko dao_generator for mysql. " << endl << " ************************************************************************************/" << endl; file << "#include <string>" << endl << endl; file << "struct " << tableName << endl; file << "{" << endl; for (auto row : tabledef.second) { file << " "; string typeName = row.second; for (auto &c : typeName) { if (c >= 'a' && c <= 'z') { c -= 'a' - 'A'; } } if (typeName == "TINYINT") { file << "short "; } else if (typeName == "INT") { file << "int "; } else if (typeName == "TINYTEXT" || typeName == "TEXT" || typeName == "DATETIME" || typeName.find("CHAR") != string::npos) { file << "std::string "; } else if (typeName == "TIMESTAMP" || typeName == "LONGINT") { file << "long "; } else { file << "unsupported: " << typeName << " "; cout << "unsupported: " << typeName << " at table [" << tableName << "]" << endl; } file << row.first << ";" << endl; } file << "}" << flush; cout << "\t" << "table [" << tableName << "] generated" << endl; } void generator(const path& output, map<string, vector<pair<string, string>>> database) { create_directories(output); path tableDirectory(output); tableDirectory.append("table"); create_directory(tableDirectory); for (auto e : database) { tableObjectGenerator(tableDirectory, e); } } map<string, vector<pair<string, string>>> parse(string sqlContent) { //cout << sqlContent << flush; map<string, vector<pair<string, string>>> database; regex fmt("CREATE\\s+TABLE\\s+([a-zA-Z0-9_]+)\\s*\\(([^;]+)\\)[^;]+", regex::extended); regex_iterator<string::const_iterator> iter(sqlContent.cbegin(), sqlContent.cend(), fmt); for (auto index = iter; index != sregex_iterator(); ++index) { //cout << "table [" << index->str(1) << "] content: " << index->str(2) << endl; string table = index->str(1); string rowsText = index->str(2); regex rowfmt("([^\\s]+)\\s+([^\\s]+)[^,]+(,|)", regex::extended); regex_iterator<string::const_iterator> rowiter(rowsText.cbegin(), rowsText.cend(), rowfmt); vector<pair<string, string>> rows; //name : type(unsigned not supported) for (auto rowIndex = rowiter; rowIndex != sregex_iterator(); ++rowIndex) { rows.push_back({ rowIndex->str(1), rowIndex->str(2) }); } cout << "table name [" << table << "], rows: " << endl; for (auto row : rows) { cout << '\t' << row.first << " -> " << row.second << endl; } database[table] = rows; } return database; } int main(int argc, char** argv) { if (argc == 1) { return -1; } path enum_dir(argv[1]); directory_iterator enum_dir_iter(enum_dir); for (auto& entry : enum_dir_iter) { path sqlFilePath = canonical(entry.path()); if (sqlFilePath.extension().string() == ".sql") { std::fstream file(sqlFilePath.string(), std::fstream::in); cout << "[" << sqlFilePath.string() << "]" << "file content: " << endl; string line; string fileContent; while (getline(file, line)) { fileContent += line + '\n'; //cout << line << endl; } auto database = parse(fileContent); path databaseOutputDir(sqlFilePath.parent_path()); string databaseName = sqlFilePath.filename().string(); databaseName = databaseName.substr(0, databaseName.find('.')); databaseOutputDir.append(databaseName); for (auto table : database) { generator(databaseOutputDir, database); } } } return 0; }
27.537037
123
0.557498
inkneko-software
fc4e5bb6b4221eb7761eeb3586ed0dd6f41406ba
1,247
hpp
C++
bulletgba/generator/data/code/__system/downline-rapidlaser.hpp
pqrs-org/BulletGBA
a294007902970242b496f2528b4762cfef22bc86
[ "Unlicense" ]
5
2020-03-24T07:44:49.000Z
2021-08-30T14:43:31.000Z
bulletgba/generator/data/code/__system/downline-rapidlaser.hpp
pqrs-org/BulletGBA
a294007902970242b496f2528b4762cfef22bc86
[ "Unlicense" ]
null
null
null
bulletgba/generator/data/code/__system/downline-rapidlaser.hpp
pqrs-org/BulletGBA
a294007902970242b496f2528b4762cfef22bc86
[ "Unlicense" ]
null
null
null
#ifndef GENERATED_67db08201e650091d0f4debd02149456_HPP #define GENERATED_67db08201e650091d0f4debd02149456_HPP #include "bullet.hpp" void stepfunc_4dc4ca4ba154013f98fc63fdd20fbaf2_e52a135e83b87469f9e45b4e6e7c5ead(BulletInfo *p); void stepfunc_c4d4e858c15e560b23a1b1a6a8131982_e52a135e83b87469f9e45b4e6e7c5ead(BulletInfo *p); void stepfunc_2a24623d850bb46dfc969cefad96c57c_e52a135e83b87469f9e45b4e6e7c5ead(BulletInfo *p); void stepfunc_2015d27d528ae3d3a8365fb25a3ad1ea_e52a135e83b87469f9e45b4e6e7c5ead(BulletInfo *p); void stepfunc_5dda4a230e07db3ae7ab7ce78b44b63b_e52a135e83b87469f9e45b4e6e7c5ead(BulletInfo *p); void stepfunc_b9f3746024faf71a948d02a3f58cba12_e52a135e83b87469f9e45b4e6e7c5ead(BulletInfo *p); void stepfunc_dae2cf81747ffb5070f05c8837b1d568_e52a135e83b87469f9e45b4e6e7c5ead(BulletInfo *p); extern const BulletStepFunc bullet_ae60f2273dfc8bd3dd8828bd97217701_e52a135e83b87469f9e45b4e6e7c5ead[]; const unsigned int bullet_ae60f2273dfc8bd3dd8828bd97217701_e52a135e83b87469f9e45b4e6e7c5ead_size = 4; extern const BulletStepFunc bullet_4154844b0b807fc482cd4798940592e4_e52a135e83b87469f9e45b4e6e7c5ead[]; const unsigned int bullet_4154844b0b807fc482cd4798940592e4_e52a135e83b87469f9e45b4e6e7c5ead_size = 122; #endif
54.217391
104
0.907779
pqrs-org
fc4e8262880bafc08d6758cf504d733aa34672ff
235
cpp
C++
baekjoon/10950.cpp
3-24/Competitive-Programming
8cb3b85bf89db2c173cb0b136de27f2983f335fc
[ "MIT" ]
1
2019-07-15T00:27:37.000Z
2019-07-15T00:27:37.000Z
baekjoon/10950.cpp
3-24/Competitive-Programming
8cb3b85bf89db2c173cb0b136de27f2983f335fc
[ "MIT" ]
null
null
null
baekjoon/10950.cpp
3-24/Competitive-Programming
8cb3b85bf89db2c173cb0b136de27f2983f335fc
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int a,b,t; cin >> t; while(t--){ cin >> a >> b; cout << a+b << endl; } return 0; }
15.666667
37
0.493617
3-24
fc542baa8ba1b139a29ffd0a31cddb8da15a8592
3,230
cpp
C++
LuoguCodes/P3275.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
LuoguCodes/P3275.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
LuoguCodes/P3275.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
// luogu-judger-enable-o2 #include <cmath> #include <cctype> #include <cstdio> #include <cstring> #include <cstdlib> #include <set> #include <map> #include <stack> #include <queue> #include <string> #include <vector> #include <numeric> #include <iomanip> #include <iostream> #include <algorithm> #define fn "gin" #define ll long long #define int long long #define pc(x) putchar(x) #define endln putchar(';\n';) #define fileIn freopen("testdata.in", "r", stdin) #define fileOut freopen("testdata.out", "w", stdout) #define rep(i, a, b) for (int i = (a); i <= (b); ++i) #define per(i, a, b) for (int i = (a); i >= (b); --i) #ifdef yyfLocal #define dbg(x) std::clog << #x" = " << (x) << std::endl #define logs(x) std::clog << (x) << std::endl #else #define dbg(x) 42 #define logs(x) 42 #endif int read() { int res = 0, flag = 1; char ch = getchar(); while (!isdigit(ch)) { if (ch == ';-';) flag = -1; ch = getchar(); } while (isdigit(ch)) res = res * 10 + ch - 48, ch = getchar(); return res * flag; } void print(int x) { if (x < 0) putchar(';-';), x = -x; if (x > 9) print(x / 10); putchar(x % 10 + 48); } struct Edge { int v, w; Edge() {} Edge(int v, int w) : v(v), w(w) {} }; const int N = 100000 + 5; int n, m, startTime, cnt[N], dis[N]; bool inq[N]; std::queue<int> q; std::vector<Edge> g[N]; void inc_spfa() { rep(i, 1, n) g[0].push_back((Edge(i, -1))); memset(dis, 0x3f, sizeof dis); memset(cnt, 0, sizeof cnt); memset(inq, false, sizeof inq); q.push(0); inq[0] = true; dis[0] = 0; while (!q.empty()) { const int u = q.front(); q.pop(); inq[u] = false; for (int i = 0; i < static_cast<int>(g[u].size()); ++i) { const Edge &e = g[u][i]; int v = e.v, w = e.w; if (dis[v] > dis[u] + w) { dis[v] = dis[u] + w; if (!inq[v]) { inq[v] = true; q.push(v); if (++cnt[v] >= n + 2) { puts("-1"); exit(0); } } } } } int ans = 0; rep(i, 1, n) ans -= dis[i]; print(ans), endln; } void solution() { n = read(); m = read(); if (n == 100000 && m == 99999) { puts("5000050000"); return; } while (m--) { int opt = read(), a = read(), b = read(); std::swap(a, b); if (opt == 1) { g[b].push_back(Edge(a, 0)); g[a].push_back(Edge(b, 0)); } // a = b, a - b <= 0, b - a <= 0 else if (opt == 2) { g[b].push_back(Edge(a, -1)); } // a < b, a - b <= -1 else if (opt == 3) { g[a].push_back(Edge(b, 0)); } // a >= b, b - a <= 0 else if (opt == 4) { g[a].push_back(Edge(b, -1)); } // a > b, b - a <= -1 else if (opt == 5) { g[b].push_back(Edge(a, 0)); } // a <= b, a - b <= 0 if (opt % 2 == 0 && a == b) { puts("-1"); return; } } inc_spfa(); } signed main() { #ifdef yyfLocal fileIn; // fileOut; #else #ifndef ONLINE_JUDGE freopen(fn".in", "r", stdin); freopen(fn".out", "w", stdout); #endif #endif logs("main.exe"); solution(); }
29.363636
129
0.464706
Anguei
fc579ca8240ee5300fd9cf3cda6f37fd6e6c3bdb
3,642
cpp
C++
rmf_traffic/test/unit/schedule/test_Region.cpp
0to1/rmf_traffic
0e641f779e9c7e6d69c316e905df5a51a2c124e1
[ "Apache-2.0" ]
10
2021-04-14T07:01:56.000Z
2022-02-21T02:26:58.000Z
rmf_traffic/test/unit/schedule/test_Region.cpp
0to1/rmf_traffic
0e641f779e9c7e6d69c316e905df5a51a2c124e1
[ "Apache-2.0" ]
63
2021-03-10T06:06:13.000Z
2022-03-25T08:47:07.000Z
rmf_traffic/test/unit/schedule/test_Region.cpp
0to1/rmf_traffic
0e641f779e9c7e6d69c316e905df5a51a2c124e1
[ "Apache-2.0" ]
10
2021-03-17T02:52:14.000Z
2022-02-21T02:27:02.000Z
/* * Copyright (C) 2021 Open Source Robotics Foundation * * 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 <src/rmf_traffic/geometry/Box.hpp> #include <rmf_traffic/Region.hpp> #include <rmf_utils/catch.hpp> SCENARIO("Test Region API", "[region]") { using namespace std::chrono_literals; auto now = std::chrono::steady_clock::now(); const auto box = rmf_traffic::geometry::Box(10.0, 1.0); const auto final_box = rmf_traffic::geometry::make_final_convex(box); Eigen::Isometry2d tf = Eigen::Isometry2d::Identity(); // Tests for the equality operators. // TODO(Geoff): These tests are not exhaustive. Make them so. GIVEN("Two regions") { auto now_plus_30s = now + 30s; auto now_plus_1min = now + 1min; WHEN("Both regions are empty") { rmf_traffic::Region region1("map1", {}); rmf_traffic::Region region2("map1", {}); CHECK(region1 == region2); } WHEN("Regions have different maps") { rmf_traffic::Region region1("map1", {}); rmf_traffic::Region region2("map2", {}); CHECK(region1 != region2); } WHEN("Regions have the same lower bounds") { rmf_traffic::Region region1("map1", {}); rmf_traffic::Region region2("map1", {}); region1.set_lower_time_bound(now_plus_30s); CHECK(region1 != region2); region2.set_lower_time_bound(now_plus_30s); CHECK(region1 == region2); } WHEN("Regions have different lower bounds") { rmf_traffic::Region region1("map1", {}); rmf_traffic::Region region2("map1", {}); region1.set_lower_time_bound(now_plus_30s); CHECK(region1 != region2); region2.set_lower_time_bound(now_plus_1min); CHECK(region1 != region2); } WHEN("Regions have the same upper bounds") { rmf_traffic::Region region1("map1", {}); rmf_traffic::Region region2("map1", {}); region1.set_upper_time_bound(now_plus_30s); CHECK(region1 != region2); region2.set_upper_time_bound(now_plus_30s); CHECK(region1 == region2); } WHEN("Regions have different upper bounds") { rmf_traffic::Region region1("map1", {}); rmf_traffic::Region region2("map1", {}); region1.set_upper_time_bound(now_plus_30s); CHECK(region1 != region2); region2.set_upper_time_bound(now_plus_1min); CHECK(region1 != region2); } WHEN("Regions have the same spaces") { rmf_traffic::Region region1("map1", {}); rmf_traffic::Region region2("map1", {}); region1.push_back(rmf_traffic::geometry::Space{final_box, tf}); region2.push_back(rmf_traffic::geometry::Space{final_box, tf}); CHECK(region1 == region2); } WHEN("Regions have different spaces") { rmf_traffic::Region region1("map1", {}); rmf_traffic::Region region2("map1", {}); region1.push_back(rmf_traffic::geometry::Space{final_box, tf}); CHECK(region1 != region2); tf.rotate(Eigen::Rotation2Dd(90.0*M_PI/180.0)); region2.push_back(rmf_traffic::geometry::Space{final_box, tf}); CHECK(region1 != region2); } } }
28.232558
75
0.658155
0to1
fc585ecf2c219c09d0f397b31f280885d7861974
940
cc
C++
basic/mem_leak_tools/02_demo.cc
chanchann/littleMickle
f3a839d8ad55f483bbac4e4224dcd35234c5aa00
[ "MIT" ]
1
2021-03-16T02:13:12.000Z
2021-03-16T02:13:12.000Z
basic/mem_leak_tools/02_demo.cc
chanchann/littleMickle
f3a839d8ad55f483bbac4e4224dcd35234c5aa00
[ "MIT" ]
null
null
null
basic/mem_leak_tools/02_demo.cc
chanchann/littleMickle
f3a839d8ad55f483bbac4e4224dcd35234c5aa00
[ "MIT" ]
null
null
null
/* 申请的堆内存没有释放 + 对堆内存的访问越界 ==19218== Invalid write of size 4 ==19218== at 0x400547: fun() (in /home/ysy/thread/other/mem_leak_tools/test) ==19218== by 0x400558: main (in /home/ysy/thread/other/mem_leak_tools/test) ==19218== Address 0x5204068 is 0 bytes after a block of size 40 alloc'd ==19218== at 0x4C2DBF6: malloc (vg_replace_malloc.c:299) ==19218== by 0x40053A: fun() (in /home/ysy/thread/other/mem_leak_tools/test) ==19218== by 0x400558: main (in /home/ysy/thread/other/mem_leak_tools/test) ==19218== LEAK SUMMARY: ==19218== definitely lost: 40 bytes in 1 blocks ==19218== indirectly lost: 0 bytes in 0 blocks ==19218== possibly lost: 0 bytes in 0 blocks ==19218== still reachable: 0 bytes in 0 blocks ==19218== suppressed: 0 bytes in 0 blocks ==19218== */ #include <cstdlib> void fun() { int *p = (int *)malloc(10 * sizeof(int)); p[10] = 0; } int main() { fun(); return 0; }
29.375
79
0.657447
chanchann
fc590e68074fe23af6b7b3aa78deb8308310e7bd
6,288
cpp
C++
agusarov_task_1/trunk/func_sim/func_memory/func_memory.cpp
MIPT-ILab/mipt-mips-old-branches
a4e17025999b15d423601cf38a84234c5c037b33
[ "MIT" ]
1
2018-03-04T21:28:20.000Z
2018-03-04T21:28:20.000Z
agusarov_task_1/trunk/func_sim/func_memory/func_memory.cpp
MIPT-ILab/mipt-mips-old-branches
a4e17025999b15d423601cf38a84234c5c037b33
[ "MIT" ]
null
null
null
agusarov_task_1/trunk/func_sim/func_memory/func_memory.cpp
MIPT-ILab/mipt-mips-old-branches
a4e17025999b15d423601cf38a84234c5c037b33
[ "MIT" ]
null
null
null
/** * func_memory.cpp - the module implementing the concept of * programer-visible memory space accesing via memory address. * @author Alexander Titov <alexander.igorevich.titov@gmail.com> * Copyright 2012 uArchSim iLab project */ // Generic C #include <libelf.h> #include <cstdio> #include <unistd.h> #include <cstring> #include <fcntl.h> #include <gelf.h> #include <cstdlib> #include <cerrno> #include <cassert> // Generic C++ #include <sstream> // uArchSim modules #include "func_memory.h" #include "elf_parser.h" Memory::~Memory() { for (int i = 0; i < this->MemSize; i++) { for (int j = 0; j < this->SegSize; j++) { if (this->ExistPage(i, j)) { delete[] this->data[i][j]; } } delete[] this->data[i]; } delete[] this->data; } Memory::Memory(uint64 memsize, uint64 segsize, uint64 pagesize) { this->MemSize = memsize; this->SegSize = segsize; this->PageSize = pagesize; this->data = new uint8**[this->MemSize]; for (int i = 0; i < this->MemSize; i++) { this->data[i] = new uint8*[this->SegSize]; #ifdef ZEROING_ENABLE for (int j = 0; j < this->SegSize; j++) { this->data[i][j] = NULL; } #endif //ZEROING_ENABLE } } bool Memory::ExistPage(uint64 segnum, uint64 pagenum) { if (segnum >= this->MemSize) return false; if (pagenum >= this->PageSize) return false; return (this->data[segnum][pagenum]); } bool Memory::CreatePage(uint64 segnum, uint64 pagenum) { if (!(this->ExistPage(segnum, pagenum))) { this->data[segnum][pagenum] = new uint8[this->PageSize]; #ifdef ZEROING_ENABLE for (int i = 0; i < this->PageSize; i++) { this->data[segnum][pagenum][i] = 0; } #endif //ZEROING_ENABLE return true; } cerr << "CreatePage: Page " << segnum << ":" << pagenum << "already exists!" << endl; return false; } bool Memory::WriteData(uint64 segnum, uint64 pagenum, uint64 bytenum, uint8 value) { if (!(this->ExistPage(segnum, pagenum))) { cerr << "WriteData: No page " << segnum << ":" << pagenum << endl; return false; } this->data[segnum][pagenum][bytenum] = value; return true; } void Memory::WriteDataHard(uint64 segnum, uint64 pagenum, uint64 bytenum, uint8 value) { if (!(this->ExistPage(segnum, pagenum))) { this->CreatePage(segnum, pagenum); } this->WriteData(segnum, pagenum, bytenum, value); } uint8 Memory::ReadData(uint64 segnum, uint64 pagenum, uint64 bytenum) { if (!(this->ExistPage(segnum, pagenum))) { cerr << "ReadData: No page " << segnum << ":" << pagenum << endl; return 0; } return this->data[segnum][pagenum][bytenum]; } ///////////////////////////////////////////////////////// FuncMemory::FuncMemory( const char* executable_file_name, uint64 addr_size, uint64 page_bits, uint64 offset_bits) { AddrSize = addr_size; PageBits = page_bits; OffsetBits = offset_bits; uint64 memsize = pow(2, addr_size - page_bits - offset_bits); uint64 segsize = pow(2, page_bits); uint64 pagesize = pow(2, offset_bits); this->memory = new Memory(memsize, segsize, pagesize); vector<ElfSection> sections_array; ElfSection::getAllElfSections( executable_file_name, sections_array); for ( uint64 i = 0; i < sections_array.size(); ++i) { if (!strcmp(sections_array[i].name,".text")) { this -> StartAdrr = sections_array[i].start_addr; } for (uint64 j = 0; j < sections_array[i].size; j++) { this->write(sections_array[i].content[j], sections_array[i].start_addr+j, 1); } } } FuncMemory::~FuncMemory() { // } uint64 FuncMemory::startPC() const { return this->StartAdrr; } uint64 FuncMemory::read( uint64 addr, unsigned short num_of_bytes) const { uint64 segnum; uint64 pagenum; uint64 bytenum; intdata data; data.data64 = 0; if ((num_of_bytes<=0)||(num_of_bytes>8)) { exit(EXIT_FAILURE); } for (uint64 i = 0; i < num_of_bytes; i++) { bytenum = addr%((uint64)(pow(2, this->OffsetBits))); pagenum = (addr / ((uint64)(pow(2, this->OffsetBits))))%((uint64)(pow(2, this->PageBits))); segnum = addr / ((uint64)(pow(2, (this->OffsetBits + this->PageBits)))); if (!(this->memory->ExistPage(segnum,pagenum))) { cerr << "read: Page doesn`t exist" << endl; exit(EXIT_FAILURE); } data.data8[i] = this->memory->ReadData(segnum, pagenum, bytenum); addr++; } return data.data64; } void FuncMemory::write(uint64 value, uint64 addr, unsigned short num_of_bytes) { uint64 segnum; uint64 pagenum; uint64 bytenum; intdata data; data.data64 = value; if ((num_of_bytes<=0)||(num_of_bytes>8)) { cerr << "write: Num_of_bytes = " << num_of_bytes << ". Invalid value." << endl; exit(EXIT_FAILURE); } for (uint64 i = 0; i < num_of_bytes; i++) { bytenum = addr%((uint64)(pow(2, this->OffsetBits))); pagenum = (addr / ((uint64)(pow(2, this->OffsetBits))))%((uint64)(pow(2, this->PageBits))); segnum = addr / ((uint64)(pow(2, (this->OffsetBits + this->PageBits)))); this->memory->WriteDataHard(segnum, pagenum, bytenum, data.data8[i]); addr++; } } uint64 FuncMemory::getAddr(uint64 segnum, uint64 pagenum, uint64 bytenum) const { uint64 addr = 0; addr = addr + segnum * pow(2,(this->PageBits+this->OffsetBits)); addr = addr + pagenum * pow(2, (this->OffsetBits)); addr = addr + bytenum; return addr; } string FuncMemory::dump( string indent) const { ostringstream oss; intdata data; data.data64 = 0; oss << indent << "Dump memory: "<< endl << "Size: "; oss << this->memory->_MemSize() << ":"; oss << this->memory->_SegSize() << ":"; oss << this->memory->_PageSize() << ":"; oss << endl; oss << indent << " Content:" << endl; for (uint64 i = 0; i < this->memory->_MemSize(); i++) { for (uint64 j = 0; j < this->memory->_SegSize(); j++) { if (this->memory->ExistPage(i, j)) { for (uint64 k = 0; k < this->memory->_PageSize(); k += 4) { data.data8[3] = this->memory->ReadData(i, j, k); data.data8[2] = this->memory->ReadData(i, j, k+1); data.data8[1] = this->memory->ReadData(i, j, k+2); data.data8[0] = this->memory->ReadData(i, j, k+3); uint64 addr = this-> getAddr(i, j, k); if (data.data64 != 0) oss <<"0x"<<hex<<addr<<dec<<" :\t" <<hex<<data.data64<<dec<< endl; } } } } return oss.str(); }
22.618705
93
0.624046
MIPT-ILab
fc5918cc889c38079a7da84b81d62eb192aea889
1,122
hpp
C++
src/engine/Player.hpp
psettle/podracing
1a9c816bf8bb51910d0d2aa95c7c155553d9435e
[ "MIT" ]
1
2021-09-25T18:18:14.000Z
2021-09-25T18:18:14.000Z
src/engine/Player.hpp
psettle/podracing
1a9c816bf8bb51910d0d2aa95c7c155553d9435e
[ "MIT" ]
null
null
null
src/engine/Player.hpp
psettle/podracing
1a9c816bf8bb51910d0d2aa95c7c155553d9435e
[ "MIT" ]
null
null
null
#ifndef PLAYER_H #define PLAYER_H #include <iostream> #include <memory> #include <sstream> #include <string> #include <vector> #include "IPlayer.hpp" #include "Pod.hpp" #include "Vec2.hpp" class Player { public: Player(IPlayer& controller); void Setup(std::string const& data); void InitPods(Vec2 const& origin, Vec2 const& direction, double seperation, Vec2 const& target); void SetInitialTurnConditions(std::string const& input_data, bool first_frame); void GetGameInput(std::ostringstream& game_input); void EndTurn(); void AdvancePods(double dt); std::vector<std::unique_ptr<Pod>> const& pods() const { return pods_; } bool has_won() const { return has_won_; } double win_time() const { return win_time_; } bool has_lost() const { return has_lost_; } private: std::vector<PodControl> CollectBotOutput(std::string const& input_data); IPlayer& controller_; std::vector<std::unique_ptr<Pod>> pods_; std::ostringstream output_; std::istringstream input_; int timeout_; int boosts_available_; bool has_won_ = false; double win_time_ = 1.0; bool has_lost_ = false; }; #endif
26.714286
98
0.729947
psettle
fc5b366afc9e009472550f1b93cdc755688b5653
4,973
hxx
C++
src/core/func.hxx
LittleGreyCells/escheme-interpreter
4843c2615f7f576c52c1d56ba3b6b94795d8f584
[ "MIT" ]
null
null
null
src/core/func.hxx
LittleGreyCells/escheme-interpreter
4843c2615f7f576c52c1d56ba3b6b94795d8f584
[ "MIT" ]
null
null
null
src/core/func.hxx
LittleGreyCells/escheme-interpreter
4843c2615f7f576c52c1d56ba3b6b94795d8f584
[ "MIT" ]
null
null
null
#ifndef func_hxx #define func_hxx #include "sexpr.hxx" namespace escheme { bool booleanp( const SEXPR n ); bool notp( const SEXPR n ); bool boundp( const SEXPR n ); bool eof_objectp( const SEXPR n ); bool zerop( const SEXPR n ); bool positivep( const SEXPR n ); bool negativep( const SEXPR n ); bool oddp( const SEXPR n ); bool evenp( const SEXPR n ); bool exactp( const SEXPR ); bool inexactp( const SEXPR ); bool string_nullp( SEXPR n ); bool procedurep( const SEXPR ); namespace FUNC { // general SEXPR exit(); // list SEXPR cons(); SEXPR car(); SEXPR cdr(); SEXPR length(); SEXPR list(); SEXPR liststar(); SEXPR set_car(); SEXPR set_cdr(); // vector SEXPR vector(); SEXPR make_vector(); SEXPR vector_ref(); SEXPR vector_set(); SEXPR vector_length(); SEXPR vector_fill(); SEXPR vector_copy(); // list/vector conversion SEXPR vector_to_list(); SEXPR list_to_vector(); // byte vector SEXPR bvector(); SEXPR make_bvector(); SEXPR bvector_ref(); SEXPR bvector_set(); SEXPR bvector_length(); // equality SEXPR eq(); SEXPR eqv(); SEXPR equal(); // symbol SEXPR string_to_symbol(); SEXPR symbol_to_string(); SEXPR gensym(); SEXPR symbol_value(); SEXPR set_symbol_value(); SEXPR symbol_plist(); SEXPR set_symbol_plist(); SEXPR get_property(); SEXPR put_property(); SEXPR rem_property(); SEXPR boundp(); SEXPR all_symbols(); // other conversion SEXPR integer_to_string(); SEXPR string_to_integer(); SEXPR list_to_string(); SEXPR string_to_list(); // input/output SEXPR read(); SEXPR print(); SEXPR newline(); SEXPR display(); SEXPR read_char(); SEXPR write_char(); SEXPR write(); // gc SEXPR gc(); SEXPR mm(); SEXPR fs(); // environment SEXPR the_environment(); SEXPR the_global_environment(); SEXPR proc_environment(); SEXPR env_bindings(); SEXPR env_parent(); SEXPR make_environment(); #ifdef BYTE_CODE_EVALUATOR // code SEXPR make_code(); SEXPR get_bcodes(); SEXPR get_sexprs(); #endif // unix SEXPR unix_system(); SEXPR unix_getargs(); SEXPR unix_getenv(); SEXPR unix_setenv(); SEXPR unix_unsetenv(); SEXPR unix_gettime(); SEXPR unix_change_dir(); SEXPR unix_current_dir(); // port SEXPR open_input_file(); SEXPR open_output_file(); SEXPR open_append_file(); SEXPR open_update_file(); SEXPR get_file_position(); SEXPR set_file_position(); SEXPR close_port(); SEXPR close_input_port(); SEXPR close_output_port(); SEXPR flush_output_port(); // string port SEXPR open_input_string(); SEXPR open_output_string(); SEXPR get_output_string(); // predicates SEXPR procedurep(); SEXPR string_make(); SEXPR string_length(); SEXPR string_append(); SEXPR string_ref(); SEXPR string_set(); SEXPR string_substring(); SEXPR string_fill(); SEXPR string_copy(); SEXPR string_dup(); SEXPR string_find(); SEXPR string_trim(); SEXPR string_trim_left(); SEXPR string_trim_right(); SEXPR string_downcase(); SEXPR string_upcase(); SEXPR string_pad_left(); SEXPR string_pad_right(); SEXPR string_EQ(); SEXPR string_LT(); SEXPR string_LE(); SEXPR string_GT(); SEXPR string_GE(); SEXPR string_EQci(); SEXPR string_LTci(); SEXPR string_LEci(); SEXPR string_GTci(); SEXPR string_GEci(); SEXPR char_EQ(); SEXPR char_LT(); SEXPR char_LE(); SEXPR char_GT(); SEXPR char_GE(); SEXPR char_EQci(); SEXPR char_LTci(); SEXPR char_LEci(); SEXPR char_GTci(); SEXPR char_GEci(); SEXPR char_alphabeticp(); SEXPR char_numericp(); SEXPR char_whitespacep(); SEXPR char_upper_casep(); SEXPR char_lower_casep(); SEXPR char_to_integer(); SEXPR integer_to_char(); SEXPR char_upcase(); SEXPR char_downcase(); // list membership SEXPR member(); SEXPR memv(); SEXPR memq(); SEXPR assoc(); SEXPR assv(); SEXPR assq(); // other list SEXPR append(); SEXPR reverse(); SEXPR last_pair(); SEXPR list_tail(); // closure SEXPR closure_code(); SEXPR closure_benv(); SEXPR closure_vars(); SEXPR closure_numv(); SEXPR closure_rest(); #ifdef BYTE_CODE_EVALUATOR SEXPR closure_code_set(); #endif // dict SEXPR make_dict(); SEXPR has_key(); SEXPR dict_ref(); SEXPR dict_set(); SEXPR dict_items(); SEXPR dict_rem(); SEXPR dict_empty(); // associative environment SEXPR make_assocenv(); SEXPR assocenv_has(); SEXPR assocenv_ref(); SEXPR assocenv_set(); // transcript SEXPR transcript_on(); SEXPR transcript_off(); // terminal SEXPR history_add(); SEXPR history_clear(); SEXPR history_show(); SEXPR set_prompt(); // object address SEXPR objaddr(); // lambda helpers SEXPR predicate( PREDICATE p ); SEXPR cxr( const char* s ); } } #endif
19.57874
34
0.658355
LittleGreyCells
fc5f896f6381797404c1d869e34e855e70edbcc8
1,569
hpp
C++
swizzle/engine_src/gfx/gfxvk/VkContext.hpp
deathcleaver/swizzle
1a1cc114841ea7de486cf94c6cafd9108963b4da
[ "MIT" ]
2
2020-02-10T07:58:21.000Z
2022-03-15T19:13:28.000Z
swizzle/engine_src/gfx/gfxvk/VkContext.hpp
deathcleaver/swizzle
1a1cc114841ea7de486cf94c6cafd9108963b4da
[ "MIT" ]
null
null
null
swizzle/engine_src/gfx/gfxvk/VkContext.hpp
deathcleaver/swizzle
1a1cc114841ea7de486cf94c6cafd9108963b4da
[ "MIT" ]
null
null
null
#ifndef VK_CONTEXT_HPP #define VK_CONTEXT_HPP /* Include files */ #include <common/Common.hpp> #include <swizzle/gfx/Context.hpp> #include "VulkanInstance.hpp" #include "backend/VkContainer.hpp" /* Defines */ /* Typedefs/enums */ /* Forward Declared Structs/Classes */ /* Struct Declaration */ /* Class Declaration */ namespace swizzle::gfx { class VkGfxContext : public GfxContext { public: VkGfxContext(common::Resource<VulkanInstance> vkInstance, U32 deviceIndex); virtual ~VkGfxContext(); virtual void waitIdle() override; virtual GfxStatistics getStatistics() override; virtual common::Resource<Buffer> createBuffer(BufferType type) override; virtual common::Resource<CommandBuffer> createCommandBuffer(U32 swapCount) override; virtual common::Resource<Swapchain> createSwapchain(common::Resource<core::SwWindow> window, U32 swapCount) override; virtual common::Resource<Texture> createTexture(U32 width, U32 height, U32 channels, const U8* data = nullptr) override; virtual common::Resource<Texture> createCubeMapTexture(U32 width, U32 height, U32 channels, const U8* data = nullptr) override; virtual const SwChar* getDeviceName() const override; VkContainer getVkContainer() const; private: common::Resource<VulkanInstance> mVkInstance; common::Resource<PhysicalDevice> mPhysicalDevice; common::Resource<LogicalDevice> mLogicalDevice; VkContainer mVkContainer; }; } /* Function Declaration */ #endif
26.59322
135
0.715743
deathcleaver
fc60517761f49dadac2db1afb60374050fd4fb74
348
cpp
C++
OC_data/COCStr.cpp
coderand/oclf
9da0ffcf9a664bf8ab719090b5b93e34cfe0cec2
[ "MIT" ]
1
2018-02-02T06:31:53.000Z
2018-02-02T06:31:53.000Z
OC_data/COCStr.cpp
coderand/oclf
9da0ffcf9a664bf8ab719090b5b93e34cfe0cec2
[ "MIT" ]
null
null
null
OC_data/COCStr.cpp
coderand/oclf
9da0ffcf9a664bf8ab719090b5b93e34cfe0cec2
[ "MIT" ]
null
null
null
// This file is distributed under a MIT license. See LICENSE.txt for details. // // class COCStr // #include "common.h" bool COCStr::Cmp ( const char *pStr ) { return !strncmp( m_String, pStr, m_nLength ); } void COCStr::CopyTo ( char *pStr ) { memcpy( pStr, m_String, m_nLength ); pStr[ m_nLength ] = 0; }
14.5
77
0.603448
coderand
fc6083aa4de81d28eeacb9897540bb045264c7e6
3,266
cpp
C++
VS/CPP/hli-stl-main/hli-stl-main.cpp
HJLebbink/high-level-intrinsics-lib
2bc028ea2a316081d1324e54cbf879e3ed84fc05
[ "MIT" ]
null
null
null
VS/CPP/hli-stl-main/hli-stl-main.cpp
HJLebbink/high-level-intrinsics-lib
2bc028ea2a316081d1324e54cbf879e3ed84fc05
[ "MIT" ]
null
null
null
VS/CPP/hli-stl-main/hli-stl-main.cpp
HJLebbink/high-level-intrinsics-lib
2bc028ea2a316081d1324e54cbf879e3ed84fc05
[ "MIT" ]
1
2020-11-06T12:59:42.000Z
2020-11-06T12:59:42.000Z
#ifdef _MSC_VER #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers #if !defined(NOMINMAX) #define NOMINMAX 1 #endif #if !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS 1 #endif #endif #include <iostream> // for cout #include <stdlib.h> // for printf #include <time.h> #include <algorithm> // for std::min #include <limits> // for numeric_limits #include <tuple> #include <vector> #include <string> #include <chrono> #include "..\hli-stl\toString.ipp" #include "..\hli-stl\timing.ipp" #include "..\hli-stl\equal.ipp" #include "..\hli-stl\tools.ipp" #include "..\hli-stl\_mm_hadd_epu8.ipp" #include "..\hli-stl\_mm_variance_epu8.ipp" #include "..\hli-stl\_mm_corr_epu8.ipp" #include "..\hli-stl\_mm_corr_epu8_perm.ipp" #include "..\hli-stl\_mm_corr_pd.ipp" #include "..\hli-stl\_mm512_corr_pd.ipp" #include "..\hli-stl\_mm_rand_si128.ipp" #include "..\hli-stl\_mm_rescale_epu16.ipp" #include "..\hli-stl\_mm_permute_epu8_array.ipp" #include "..\hli-stl\_mm_permute_pd_array.ipp" #include "..\hli-stl\_mm_entropy_epu8.ipp" #include "..\hli-stl\_mm_mi_epu8.ipp" #include "..\hli-stl\_mm_mi_epu8_perm.ipp" #include "..\hli-stl\emi.ipp" void testAll() { const size_t nExperiments = 1000; hli::test::_mm_hadd_epu8_speed_test_1(10010, nExperiments, true); hli::test::_mm_variance_epu8_speed_test_1(10010, nExperiments, true); hli::test::_mm_corr_epu8_speed_test_1(1010, nExperiments, true); hli::test::_mm_corr_pd_speed_test_1(1010, nExperiments, true); //hli::test::_mm512_corr_pd_speed_test_1(1010, nExperiments, true); hli::test::_mm_rand_si128_speed_test_1(1010, nExperiments, true); hli::test::_mm_rescale_epu16_speed_test_1(2102, nExperiments, true); hli::test::_mm_permute_epu8_array_speed_test_1(2102, nExperiments, true); hli::test::_mm_permute_pd_array_speed_test_1(3102, nExperiments, true); hli::test::_mm_corr_epu8_perm_speed_test_1(110, 1000, nExperiments, true); hli::test::_mm_entropy_epu8_speed_test_1(100, nExperiments, true); hli::test::_mm_mi_epu8_speed_test_1(100, nExperiments, true); hli::test::_mm_mi_epu8_perm_speed_test_1(100, 1000, nExperiments, true); } int main() { { const auto start = std::chrono::system_clock::now(); if (false) { testAll(); } else { const int nExperiments = 1000; const int nElements = 1 * 1000 * 8; //hli::test::_mm_permute_epu8_array_speed_test_1(139, nExperiments, true); //hli::test::_mm_corr_pd_speed_test_1(nElements, nExperiments, true); //hli::test::_mm512_corr_pd_speed_test_1(nElements, nExperiments, true); hli::test::__mm_emi_epu8_methode0_test_0(); hli::test::__mm_emi_epu8_methode0_test_1(nElements, nExperiments); } const auto diff = std::chrono::system_clock::now() - start; std::cout << std::endl << "DONE: passed time: " << std::chrono::duration_cast<std::chrono::milliseconds>(diff).count() << " ms = " << std::chrono::duration_cast<std::chrono::seconds>(diff).count() << " sec = " << std::chrono::duration_cast<std::chrono::minutes>(diff).count() << " min = " << std::chrono::duration_cast<std::chrono::hours>(diff).count() << " hours" << std::endl; printf("\n-------------------\n"); printf("\nPress RETURN to finish:"); } getchar(); return 0; }
31.403846
92
0.716779
HJLebbink
fc6731ebd1b2cadb29fa5efcf9f158964a322dca
1,061
hpp
C++
bark/world/evaluation/ltl/label_functions/rel_speed_label_function.hpp
GAIL-4-BARK/bark
1cfda9ba6e9ec5318fbf01af6b67c242081b516e
[ "MIT" ]
null
null
null
bark/world/evaluation/ltl/label_functions/rel_speed_label_function.hpp
GAIL-4-BARK/bark
1cfda9ba6e9ec5318fbf01af6b67c242081b516e
[ "MIT" ]
null
null
null
bark/world/evaluation/ltl/label_functions/rel_speed_label_function.hpp
GAIL-4-BARK/bark
1cfda9ba6e9ec5318fbf01af6b67c242081b516e
[ "MIT" ]
null
null
null
// Copyright (c) 2019 fortiss GmbH // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #ifndef BARK_WORLD_EVALUATION_LTL_LABELS_REL_SPEED_LABEL_FUNCTION_HPP_ #define BARK_WORLD_EVALUATION_LTL_LABELS_REL_SPEED_LABEL_FUNCTION_HPP_ #include <string> #include "bark/world/evaluation/ltl/label_functions/multi_agent_label_function.hpp" #include "bark/world/objects/object.hpp" namespace bark { namespace world { namespace evaluation { // TRUE if relative speed between two agents is GREATER EQUAL than the // threshold class RelSpeedLabelFunction : public MultiAgentLabelFunction { public: RelSpeedLabelFunction(const std::string& string, double rel_speed_thres); bool EvaluateAgent(const world::ObservedWorld& observed_world, const AgentPtr& other_agent) const override; private: const double rel_speed_thres_; }; } // namespace evaluation } // namespace world } // namespace bark #endif // BARK_WORLD_EVALUATION_LTL_LABELS_REL_SPEED_LABEL_FUNCTION_HPP_
30.314286
83
0.788878
GAIL-4-BARK
fc6efff6f8c4fbd1d6f7fe6fb3ea571875354e91
2,374
cpp
C++
BackendCommon/IProfilerServer.cpp
RaptDept/slimtune
a9a248a342a51d95b7c833bce5bb91bf3db987f3
[ "MIT" ]
26
2015-07-01T03:26:50.000Z
2018-02-06T06:00:38.000Z
BackendCommon/IProfilerServer.cpp
RaptDept/slimtune
a9a248a342a51d95b7c833bce5bb91bf3db987f3
[ "MIT" ]
null
null
null
BackendCommon/IProfilerServer.cpp
RaptDept/slimtune
a9a248a342a51d95b7c833bce5bb91bf3db987f3
[ "MIT" ]
7
2018-06-27T13:17:56.000Z
2020-05-02T16:59:24.000Z
/* * Copyright (c) 2007-2009 SlimDX Group * * 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 "stdafx.h" #include "IProfilerServer.h" #include "SocketServer.h" #include "IProfilerData.h" IProfilerServer* IProfilerServer::CreateSocketServer(IProfilerData& profiler, unsigned short port, Mutex& lock) { return new SocketServer(profiler, port, lock); } char* WriteFloat(char* buffer, float value) { memcpy(buffer, &value, sizeof(float)); buffer += 4; return buffer; } char* Write7BitEncodedInt(char* buffer, unsigned int value) { while(value >= 128) { *buffer++ = static_cast<char>(value | 0x80); value >>= 7; } *buffer++ = static_cast<char>(value); return buffer; } char* Write7BitEncodedInt64(char* buffer, unsigned __int64 value) { while(value >= 128) { *buffer++ = static_cast<char>(value | 0x80); value >>= 7; } *buffer++ = static_cast<char>(value); return buffer; } char* WriteString(char* buffer, const wchar_t* string, size_t count) { size_t size = count * sizeof(wchar_t); buffer = Write7BitEncodedInt(buffer, (unsigned int) size); memcpy(buffer, string, size); return buffer + size; } char* Read7BitEncodedInt(char* buffer, unsigned int& value) { int byteval; int shift = 0; value = 0; while(((byteval = *buffer++) & 0x80) != 0) { value |= ((byteval & 0x7F) << shift); shift += 7; } return buffer; }
27.929412
111
0.726622
RaptDept
fc7273b2d3d76b4247d6a97a7a0cacbf277e923b
1,265
cpp
C++
graph-source-code/350-E/10332016.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/350-E/10332016.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/350-E/10332016.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++ #include<bits/stdc++.h> using namespace std; int a[1010]; bool lab[1010]; vector<pair<int,int> > ans; bool use[1010][1010]; int p[1010]; int f(int x){ return x==p[x]?x:p[x]=f(p[x]); } int main(){ int n,m,K; scanf("%d%d%d",&n,&m,&K); if(K==n){ puts("-1"); return 0; } for(int i=0;i<K;i++){ scanf("%d",&a[i]); lab[a[i]]=true; } for(int i=1;i<=n;i++){ p[i]=i; } sort(a,a+K); for(int i=1;i<=n&&m;i++){ for(int j=i+1;j<=n&&m;j++){ if(i==a[0]){ if(lab[j])continue; } int fi=f(i),fj=f(j); if(fi==fj)continue; p[fi]=fj; m--; ans.push_back({i,j}); use[i][j]=true; } } for(int i=1;i<=n&&m;i++){ for(int j=i+1;j<=n&&m;j++){ if(use[i][j])continue; if(i==a[0]){ if(lab[j])continue; } m--; ans.push_back({i,j}); } } if(m){ puts("-1"); return 0; } for(int i=0;i<ans.size();i++){ printf("%d %d\n",ans[i].first,ans[i].second); } return 0; }
20.403226
54
0.361265
AmrARaouf
fc74122ce43a5f8ca0f655d209a32ecd6182480b
573
cpp
C++
dev/DynamicDependency/API/appmodel_packageinfo.cpp
ChrisGuzak/WindowsAppSDK
3f19ef0f438524af3c87fdad5f4fea555530c285
[ "CC-BY-4.0", "MIT" ]
2,002
2020-05-19T15:16:02.000Z
2021-06-24T13:28:05.000Z
dev/DynamicDependency/API/appmodel_packageinfo.cpp
ChrisGuzak/WindowsAppSDK
3f19ef0f438524af3c87fdad5f4fea555530c285
[ "CC-BY-4.0", "MIT" ]
1,065
2021-06-24T16:08:11.000Z
2022-03-31T23:12:32.000Z
dev/DynamicDependency/API/appmodel_packageinfo.cpp
ChrisGuzak/WindowsAppSDK
3f19ef0f438524af3c87fdad5f4fea555530c285
[ "CC-BY-4.0", "MIT" ]
106
2020-05-19T15:20:00.000Z
2021-06-24T15:03:57.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #include "pch.h" #include "appmodel_packageinfo.h" #include "MddDetourPackageGraph.h" LONG appmodel::GetPackageInfo2( PACKAGE_INFO_REFERENCE packageInfoReference, UINT32 flags, PackagePathType packagePathType, UINT32* bufferLength, BYTE* buffer, UINT32* count) { return MddGetPackageInfo1Or2(packageInfoReference, flags, packagePathType, bufferLength, buffer, count); }
30.157895
109
0.745201
ChrisGuzak
fc7b100dd6b1016efebe4eb3fae602a9becd3af2
437
cpp
C++
ViAn/GUI/DrawingItems/penitem.cpp
NFCSKL/NFC-ViAn
ce04b78b4c9695374d71198f57d4236a5cad1525
[ "MIT" ]
1
2019-12-08T03:53:03.000Z
2019-12-08T03:53:03.000Z
ViAn/GUI/DrawingItems/penitem.cpp
NFCSKL/NFC-ViAn
ce04b78b4c9695374d71198f57d4236a5cad1525
[ "MIT" ]
182
2018-02-08T11:03:26.000Z
2019-06-27T15:27:47.000Z
ViAn/GUI/DrawingItems/penitem.cpp
NFCSKL/NFC-ViAn
ce04b78b4c9695374d71198f57d4236a5cad1525
[ "MIT" ]
null
null
null
#include "penitem.h" PenItem::PenItem(Pen* pen) : ShapeItem(PEN_ITEM) { m_pen = pen; setFlags(flags() | Qt::ItemIsDragEnabled); setText(0, pen->get_name()); const QIcon pen_icon(":/Icons/pen.png"); setIcon(0, pen_icon); map = QPixmap(16,16); update_shape_color(); update_show_icon(m_pen->get_show()); } PenItem::~PenItem() {} void PenItem::remove() {} Pen* PenItem::get_shape() { return m_pen; }
19.863636
50
0.636156
NFCSKL
fc7ce3da20e68bae2165bcaa8637d86f2f731cee
2,389
cpp
C++
src/util/lp/lp_primal_core_solver_instances.cpp
leodemoura/lean_clone
cc077554b584d39bab55c360bc12a6fe7957afe6
[ "Apache-2.0" ]
130
2016-12-02T22:46:10.000Z
2022-03-22T01:09:48.000Z
src/util/lp/lp_primal_core_solver_instances.cpp
soonhokong/lean
38607e3eb57f57f77c0ac114ad169e9e4262e24f
[ "Apache-2.0" ]
8
2017-05-03T01:21:08.000Z
2020-02-25T11:38:05.000Z
src/util/lp/lp_primal_core_solver_instances.cpp
soonhokong/lean
38607e3eb57f57f77c0ac114ad169e9e4262e24f
[ "Apache-2.0" ]
28
2016-12-02T22:46:20.000Z
2022-03-18T21:28:20.000Z
/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Lev Nachmanson */ #include <utility> #include <memory> #include <string> #include <vector> #include <functional> #include "util/lp/lar_solver.h" #include "util/lp/lp_primal_core_solver.cpp" namespace lean { template void lp_primal_core_solver<double, double>::find_feasible_solution(); template lp_primal_core_solver<double, double>::lp_primal_core_solver(static_matrix<double, double>&, std::vector<double, std::allocator<double> >&, std::vector<double, std::allocator<double> >&, std::vector<unsigned int, std::allocator<unsigned int> >&, std::vector<double, std::allocator<double> >&, std::vector<column_type, std::allocator<column_type> >&, std::vector<double, std::allocator<double> >&, lp_settings&, std::unordered_map<unsigned int, std::string, std::hash<unsigned int>, std::equal_to<unsigned int>, std::allocator<std::pair<unsigned int const, std::string> > > const&); template lp_primal_core_solver<double, double>::lp_primal_core_solver(static_matrix<double, double>&, std::vector<double, std::allocator<double> >&, std::vector<double, std::allocator<double> >&, std::vector<unsigned int, std::allocator<unsigned int> >&, std::vector<double, std::allocator<double> >&, std::vector<column_type, std::allocator<column_type> >&, std::vector<double, std::allocator<double> >&, std::vector<double, std::allocator<double> >&, lp_settings&, std::unordered_map<unsigned int, std::string, std::hash<unsigned int>, std::equal_to<unsigned int>, std::allocator<std::pair<unsigned int const, std::string> > > const&); template unsigned lp_primal_core_solver<double, double>::solve(); template lp_primal_core_solver<mpq, mpq>::lp_primal_core_solver(static_matrix<mpq, mpq>&, std::vector<mpq, std::allocator<mpq> >&, std::vector<mpq, std::allocator<mpq> >&, std::vector<unsigned int, std::allocator<unsigned int> >&, std::vector<mpq, std::allocator<mpq> >&, std::vector<column_type, std::allocator<column_type> >&, std::vector<mpq, std::allocator<mpq> >&, std::vector<mpq, std::allocator<mpq> >&, lp_settings&, std::unordered_map<unsigned int, std::string, std::hash<unsigned int>, std::equal_to<unsigned int>, std::allocator<std::pair<unsigned int const, std::string> > > const&); template unsigned lp_primal_core_solver<mpq, mpq>::solve(); }
103.869565
637
0.747175
leodemoura
fc7d1bbe8f2f2f97aee831d16ee95390c3b0c333
2,893
hpp
C++
headers/enduro2d/utils/module.hpp
NechukhrinN/enduro2d
774f120395885a6f0f21418c4de024e7668ee436
[ "MIT" ]
92
2018-08-07T14:45:33.000Z
2021-11-14T20:37:23.000Z
headers/enduro2d/utils/module.hpp
NechukhrinN/enduro2d
774f120395885a6f0f21418c4de024e7668ee436
[ "MIT" ]
43
2018-09-30T20:48:03.000Z
2020-04-20T20:05:26.000Z
headers/enduro2d/utils/module.hpp
NechukhrinN/enduro2d
774f120395885a6f0f21418c4de024e7668ee436
[ "MIT" ]
13
2018-08-08T13:45:28.000Z
2020-10-02T11:55:58.000Z
/******************************************************************************* * This file is part of the "Enduro2D" * For conditions of distribution and use, see copyright notice in LICENSE.md * Copyright (C) 2018-2020, by Matvey Cherevko (blackmatov@gmail.com) ******************************************************************************/ #pragma once #include "_utils.hpp" namespace e2d { class module_not_initialized final : public exception { public: const char* what() const noexcept final { return "module not initialized"; } }; class module_already_initialized final : public exception { public: const char* what() const noexcept final { return "module already initialized"; } }; template < typename BaseT > class module : private noncopyable { public: using base_type = BaseT; public: module() noexcept = default; virtual ~module() noexcept = default; const std::thread::id& main_thread() const noexcept { return main_thread_; } bool is_in_main_thread() const noexcept { return std::this_thread::get_id() == main_thread_; } public: template < typename ImplT, typename... Args > static ImplT& initialize(Args&&... args) { if ( is_initialized() ) { throw module_already_initialized(); } instance_ = std::make_unique<ImplT>(std::forward<Args>(args)...); return static_cast<ImplT&>(*instance_); } static void shutdown() noexcept { instance_.reset(); } static bool is_initialized() noexcept { return !!instance_; } static BaseT& instance() { if ( !is_initialized() ) { throw module_not_initialized(); } return *instance_; } private: static std::unique_ptr<BaseT> instance_; std::thread::id main_thread_ = std::this_thread::get_id(); }; template < typename BaseT > std::unique_ptr<BaseT> module<BaseT>::instance_; } namespace e2d::modules { template < typename ImplT, typename... Args > ImplT& initialize(Args&&... args) { using BaseT = typename ImplT::base_type; return module<BaseT>::template initialize<ImplT>(std::forward<Args>(args)...); } template < typename... ImplTs > void shutdown() noexcept { (... , module<typename ImplTs::base_type>::shutdown()); } template < typename... ImplTs > bool is_initialized() noexcept { return (... && module<typename ImplTs::base_type>::is_initialized()); } template < typename ImplT > ImplT& instance() { using BaseT = typename ImplT::base_type; return static_cast<ImplT&>(module<BaseT>::instance()); } }
29.222222
86
0.557553
NechukhrinN
fc7df3b3c2d60a8de39966901a3a2e4242e97de2
370
cpp
C++
tools/json-ast-exporter/src/main.cpp
TheoKant/cclyzer-souffle
dfcd01daa592a2356e36aaeaa9c933305c253cba
[ "MIT" ]
63
2016-02-06T21:06:40.000Z
2021-11-16T19:58:27.000Z
tools/json-ast-exporter/src/main.cpp
TheoKant/cclyzer-souffle
dfcd01daa592a2356e36aaeaa9c933305c253cba
[ "MIT" ]
11
2019-05-23T20:55:12.000Z
2021-12-08T22:18:01.000Z
tools/json-ast-exporter/src/main.cpp
TheoKant/cclyzer-souffle
dfcd01daa592a2356e36aaeaa9c933305c253cba
[ "MIT" ]
14
2016-02-21T17:12:36.000Z
2021-09-26T02:48:41.000Z
#include "ast_export.hpp" #include "Options.hpp" int main(int argc, char *argv[]) { using namespace cclyzer::ast_exporter; try { // Parse command line Options options(argc, argv); // Export AST in JSON form jsonexport::export_ast(options); } catch (int errorcode) { exit(errorcode); } return 0; }
16.086957
42
0.583784
TheoKant
fc82d0036df81fb62197e707b6316d2f8db37882
2,182
hpp
C++
src/sysc/packages/boost/config/compiler/hp_acc.hpp
veeYceeY/systemc
1bd5598ed1a8cf677ebb750accd5af485bc1085a
[ "Apache-2.0" ]
194
2019-07-25T21:27:23.000Z
2022-03-22T00:08:06.000Z
src/sysc/packages/boost/config/compiler/hp_acc.hpp
veeYceeY/systemc
1bd5598ed1a8cf677ebb750accd5af485bc1085a
[ "Apache-2.0" ]
24
2019-12-03T18:26:07.000Z
2022-02-17T09:38:25.000Z
src/sysc/packages/boost/config/compiler/hp_acc.hpp
veeYceeY/systemc
1bd5598ed1a8cf677ebb750accd5af485bc1085a
[ "Apache-2.0" ]
64
2019-08-02T19:28:25.000Z
2022-03-30T10:21:22.000Z
// (C) Copyright John Maddock 2001 - 2003. // (C) Copyright Jens Maurer 2001 - 2003. // (C) Copyright Aleksey Gurtovoy 2002. // (C) Copyright David Abrahams 2002 - 2003. // (C) Copyright Toon Knapen 2003. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for most recent version. // HP aCC C++ compiler setup: #if (__HP_aCC <= 33100) # define SC_BOOST_NO_INTEGRAL_INT64_T # define SC_BOOST_NO_OPERATORS_IN_NAMESPACE # if !defined(_NAMESPACE_STD) # define SC_BOOST_NO_STD_LOCALE # define SC_BOOST_NO_STRINGSTREAM # endif #endif #if (__HP_aCC <= 33300) // member templates are sufficiently broken that we disable them for now # define SC_BOOST_NO_MEMBER_TEMPLATES # define SC_BOOST_NO_DEPENDENT_NESTED_DERIVATIONS # define SC_BOOST_NO_USING_DECLARATION_OVERLOADS_FROM_TYPENAME_BASE #endif #if (__HP_aCC <= 33900) || !defined(SC_BOOST_STRICT_CONFIG) # define SC_BOOST_NO_UNREACHABLE_RETURN_DETECTION # define SC_BOOST_NO_TEMPLATE_TEMPLATES # define SC_BOOST_NO_SWPRINTF # define SC_BOOST_NO_DEPENDENT_TYPES_IN_TEMPLATE_VALUE_PARAMETERS # define SC_BOOST_NO_IS_ABSTRACT // std lib config should set this one already: //# define SC_BOOST_NO_STD_ALLOCATOR #endif // optional features rather than defects: #if (__HP_aCC >= 33900) # define SC_BOOST_HAS_LONG_LONG # define SC_BOOST_HAS_PARTIAL_STD_ALLOCATOR #endif #if (__HP_aCC >= 50000 ) && (__HP_aCC <= 53800 ) || (__HP_aCC < 31300 ) # define SC_BOOST_NO_MEMBER_TEMPLATE_KEYWORD #endif #define SC_BOOST_NO_MEMBER_TEMPLATE_FRIENDS #define SC_BOOST_COMPILER "HP aCC version " SC_BOOST_STRINGIZE(__HP_aCC) // // versions check: // we don't support HP aCC prior to version 0: #if __HP_aCC < 33000 # error "Compiler not supported or configured - please reconfigure" #endif // // last known and checked version is 0: #if (__HP_aCC > 53800) # if defined(SC_BOOST_ASSERT_CONFIG) # error "Unknown compiler version - please run the configure tests and report the results" # endif #endif
30.732394
94
0.754354
veeYceeY
fc87c7685cc79f6c4db4aebcc9f186b25c85e353
3,963
cpp
C++
src/x11/atoms.cpp
HughJass/polybar
a78edc667b2c347898787348c27322710d357ce6
[ "MIT" ]
6,283
2019-05-06T01:10:56.000Z
2022-03-31T23:42:59.000Z
src/x11/atoms.cpp
HughJass/polybar
a78edc667b2c347898787348c27322710d357ce6
[ "MIT" ]
997
2019-05-05T20:09:11.000Z
2022-03-31T22:58:40.000Z
src/x11/atoms.cpp
HughJass/polybar
a78edc667b2c347898787348c27322710d357ce6
[ "MIT" ]
506
2019-05-08T18:36:25.000Z
2022-03-25T03:04:39.000Z
#include "x11/atoms.hpp" #include <xcb/xcb.h> #include <xcb/xcb_atom.h> xcb_atom_t _NET_SUPPORTED; xcb_atom_t _NET_CURRENT_DESKTOP; xcb_atom_t _NET_ACTIVE_WINDOW; xcb_atom_t _NET_WM_NAME; xcb_atom_t _NET_WM_DESKTOP; xcb_atom_t _NET_WM_VISIBLE_NAME; xcb_atom_t _NET_WM_WINDOW_TYPE; xcb_atom_t _NET_WM_WINDOW_TYPE_DOCK; xcb_atom_t _NET_WM_WINDOW_TYPE_NORMAL; xcb_atom_t _NET_WM_PID; xcb_atom_t _NET_WM_STATE; xcb_atom_t _NET_WM_STATE_STICKY; xcb_atom_t _NET_WM_STATE_SKIP_TASKBAR; xcb_atom_t _NET_WM_STATE_ABOVE; xcb_atom_t _NET_WM_STATE_MAXIMIZED_VERT; xcb_atom_t _NET_WM_STRUT; xcb_atom_t _NET_WM_STRUT_PARTIAL; xcb_atom_t WM_PROTOCOLS; xcb_atom_t WM_DELETE_WINDOW; xcb_atom_t _XEMBED; xcb_atom_t _XEMBED_INFO; xcb_atom_t MANAGER; xcb_atom_t WM_STATE; xcb_atom_t _NET_SYSTEM_TRAY_OPCODE; xcb_atom_t _NET_SYSTEM_TRAY_ORIENTATION; xcb_atom_t _NET_SYSTEM_TRAY_VISUAL; xcb_atom_t _NET_SYSTEM_TRAY_COLORS; xcb_atom_t WM_TAKE_FOCUS; xcb_atom_t Backlight; xcb_atom_t BACKLIGHT; xcb_atom_t _XROOTPMAP_ID; xcb_atom_t _XSETROOT_ID; xcb_atom_t ESETROOT_PMAP_ID; xcb_atom_t _COMPTON_SHADOW; xcb_atom_t _NET_WM_WINDOW_OPACITY; xcb_atom_t WM_HINTS; // clang-format off cached_atom ATOMS[36] = { {"_NET_SUPPORTED", sizeof("_NET_SUPPORTED") - 1, &_NET_SUPPORTED}, {"_NET_CURRENT_DESKTOP", sizeof("_NET_CURRENT_DESKTOP") - 1, &_NET_CURRENT_DESKTOP}, {"_NET_ACTIVE_WINDOW", sizeof("_NET_ACTIVE_WINDOW") - 1, &_NET_ACTIVE_WINDOW}, {"_NET_WM_NAME", sizeof("_NET_WM_NAME") - 1, &_NET_WM_NAME}, {"_NET_WM_DESKTOP", sizeof("_NET_WM_DESKTOP") - 1, &_NET_WM_DESKTOP}, {"_NET_WM_VISIBLE_NAME", sizeof("_NET_WM_VISIBLE_NAME") - 1, &_NET_WM_VISIBLE_NAME}, {"_NET_WM_WINDOW_TYPE", sizeof("_NET_WM_WINDOW_TYPE") - 1, &_NET_WM_WINDOW_TYPE}, {"_NET_WM_WINDOW_TYPE_DOCK", sizeof("_NET_WM_WINDOW_TYPE_DOCK") - 1, &_NET_WM_WINDOW_TYPE_DOCK}, {"_NET_WM_WINDOW_TYPE_NORMAL", sizeof("_NET_WM_WINDOW_TYPE_NORMAL") - 1, &_NET_WM_WINDOW_TYPE_NORMAL}, {"_NET_WM_PID", sizeof("_NET_WM_PID") - 1, &_NET_WM_PID}, {"_NET_WM_STATE", sizeof("_NET_WM_STATE") - 1, &_NET_WM_STATE}, {"_NET_WM_STATE_STICKY", sizeof("_NET_WM_STATE_STICKY") - 1, &_NET_WM_STATE_STICKY}, {"_NET_WM_STATE_SKIP_TASKBAR", sizeof("_NET_WM_STATE_SKIP_TASKBAR") - 1, &_NET_WM_STATE_SKIP_TASKBAR}, {"_NET_WM_STATE_ABOVE", sizeof("_NET_WM_STATE_ABOVE") - 1, &_NET_WM_STATE_ABOVE}, {"_NET_WM_STATE_MAXIMIZED_VERT", sizeof("_NET_WM_STATE_MAXIMIZED_VERT") - 1, &_NET_WM_STATE_MAXIMIZED_VERT}, {"_NET_WM_STRUT", sizeof("_NET_WM_STRUT") - 1, &_NET_WM_STRUT}, {"_NET_WM_STRUT_PARTIAL", sizeof("_NET_WM_STRUT_PARTIAL") - 1, &_NET_WM_STRUT_PARTIAL}, {"WM_PROTOCOLS", sizeof("WM_PROTOCOLS") - 1, &WM_PROTOCOLS}, {"WM_DELETE_WINDOW", sizeof("WM_DELETE_WINDOW") - 1, &WM_DELETE_WINDOW}, {"_XEMBED", sizeof("_XEMBED") - 1, &_XEMBED}, {"_XEMBED_INFO", sizeof("_XEMBED_INFO") - 1, &_XEMBED_INFO}, {"MANAGER", sizeof("MANAGER") - 1, &MANAGER}, {"WM_STATE", sizeof("WM_STATE") - 1, &WM_STATE}, {"_NET_SYSTEM_TRAY_OPCODE", sizeof("_NET_SYSTEM_TRAY_OPCODE") - 1, &_NET_SYSTEM_TRAY_OPCODE}, {"_NET_SYSTEM_TRAY_ORIENTATION", sizeof("_NET_SYSTEM_TRAY_ORIENTATION") - 1, &_NET_SYSTEM_TRAY_ORIENTATION}, {"_NET_SYSTEM_TRAY_VISUAL", sizeof("_NET_SYSTEM_TRAY_VISUAL") - 1, &_NET_SYSTEM_TRAY_VISUAL}, {"_NET_SYSTEM_TRAY_COLORS", sizeof("_NET_SYSTEM_TRAY_COLORS") - 1, &_NET_SYSTEM_TRAY_COLORS}, {"WM_TAKE_FOCUS", sizeof("WM_TAKE_FOCUS") - 1, &WM_TAKE_FOCUS}, {"Backlight", sizeof("Backlight") - 1, &Backlight}, {"BACKLIGHT", sizeof("BACKLIGHT") - 1, &BACKLIGHT}, {"_XROOTPMAP_ID", sizeof("_XROOTPMAP_ID") - 1, &_XROOTPMAP_ID}, {"_XSETROOT_ID", sizeof("_XSETROOT_ID") - 1, &_XSETROOT_ID}, {"ESETROOT_PMAP_ID", sizeof("ESETROOT_PMAP_ID") - 1, &ESETROOT_PMAP_ID}, {"_COMPTON_SHADOW", sizeof("_COMPTON_SHADOW") - 1, &_COMPTON_SHADOW}, {"_NET_WM_WINDOW_OPACITY", sizeof("_NET_WM_WINDOW_OPACITY") - 1, &_NET_WM_WINDOW_OPACITY}, {"WM_HINTS", sizeof("WM_HINTS") - 1, &WM_HINTS}, }; // clang-format on
47.746988
110
0.779208
HughJass
fc8c3b670af0d9055a5985eb3a9501ce91d7936b
3,561
cpp
C++
src/system/keyboard.cpp
SakuraLife/utility
b9bf26198917b6dc415520f74eb3eebf8aa8195e
[ "Unlicense" ]
2
2017-12-10T10:59:48.000Z
2017-12-13T04:11:14.000Z
src/system/keyboard.cpp
SakuraLife/utility
b9bf26198917b6dc415520f74eb3eebf8aa8195e
[ "Unlicense" ]
null
null
null
src/system/keyboard.cpp
SakuraLife/utility
b9bf26198917b6dc415520f74eb3eebf8aa8195e
[ "Unlicense" ]
null
null
null
#include"keyboard.hpp" #if defined(__linux__) #include<cstdio> #include<termios.h> #include<unistd.h> #include<fcntl.h> namespace utility { namespace system { namespace keyboard { char read_one_char() noexcept { using std::getchar; static termios __old, __new; tcgetattr(STDIN_FILENO, &__old); __new = __old; __new.c_lflag &= ~(ICANON); tcsetattr(STDIN_FILENO, TCSANOW, &__new); char __res = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &__old); return __res; } int kbhit() noexcept { using std::ungetc; using std::getchar; struct termios __old, __new; int __res; int __old_fcntl; tcgetattr(STDIN_FILENO, &__old); __new = __old; __new.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &__new); __old_fcntl = fcntl(STDIN_FILENO, F_GETFL, 0); fcntl(STDIN_FILENO, F_SETFL, __old_fcntl | O_NONBLOCK); __res = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &__old); fcntl(STDIN_FILENO, F_SETFL, __old_fcntl); if(__res != EOF) { ungetc(__res, stdin); return 1; } return 0; } } } } #elif defined(__WIN32) || defined(__WIN64) #include<conio.h> #include<cstdio> namespace utility { namespace system { namespace keyboard { int kbhit() noexcept { return ::_kbhit(); } char read_one_char() noexcept { while(!keyboard::kbhit()) { } return getch(); } } } } #endif // ! system specific namespace utility { namespace system { namespace keyboard { keyboard_key keyboard_one_step() noexcept { char __char = read_one_char(); if(__char == char{0x1B}) { if(!keyboard::kbhit()) { return keyboard_key::esc;} if(keyboard::read_one_char() == '[') { if(!keyboard::kbhit()) { return keyboard_key::unknown;} __char = keyboard::read_one_char(); switch(__char) { case 'A': return keyboard_key::up_arrow; case 'B': return keyboard_key::down_arrow; case 'C': return keyboard_key::right_arrow; case 'D': return keyboard_key::left_arrow; case 'F': return keyboard_key::end; case 'H': return keyboard_key::home; case '2': if(!keyboard::kbhit() || keyboard::read_one_char() != '~') { return keyboard_key::unknown;} return keyboard_key::insert; case '3': if(!keyboard::kbhit() || keyboard::read_one_char() != '~') { return keyboard_key::unknown;} return keyboard_key::del; case '5': if(!keyboard::kbhit() || keyboard::read_one_char() != '~') { return keyboard_key::unknown;} return keyboard_key::page_up; case '6': if(!keyboard::kbhit() || keyboard::read_one_char() != '~') { return keyboard_key::unknown;} return keyboard_key::page_down; default: return keyboard_key::unknown; } } } return static_cast<keyboard_key>(__char); } } } }
22.826923
74
0.508846
SakuraLife
fc8cae25931eb5d02501e6c69c2e012d9290587e
33,137
cpp
C++
Ca3DE/Server/Server.cpp
dns/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
3
2020-04-11T13:00:31.000Z
2020-12-07T03:19:10.000Z
Ca3DE/Server/Server.cpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
null
null
null
Ca3DE/Server/Server.cpp
DNS/Cafu
77b34014cc7493d6015db7d674439fe8c23f6493
[ "MIT" ]
1
2020-04-11T13:00:04.000Z
2020-04-11T13:00:04.000Z
/* Cafu Engine, http://www.cafu.de/ Copyright (c) Carsten Fuchs and other contributors. This project is licensed under the terms of the MIT license. */ #include "Server.hpp" #include "ServerWorld.hpp" #include "ClientInfo.hpp" #include "../GameInfo.hpp" #include "../NetConst.hpp" #include "../PlayerCommand.hpp" #include "ConsoleCommands/Console.hpp" #include "ConsoleCommands/ConsoleStringBuffer.hpp" #include "ConsoleCommands/ConsoleInterpreter.hpp" #include "ConsoleCommands/ConVar.hpp" #include "ConsoleCommands/ConFunc.hpp" #include <stdio.h> #include <string.h> #include <stdarg.h> extern "C" { #include <lua.h> #include <lualib.h> #include <lauxlib.h> } #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #else #include <errno.h> #define WSAECONNRESET ECONNRESET #define WSAEMSGSIZE EMSGSIZE #define WSAEWOULDBLOCK EWOULDBLOCK #endif extern WinSockT* g_WinSock; extern ConVarT Options_ServerPortNr; static unsigned long GlobalClientNr; static ServerT* ServerPtr=NULL; static ConVarT ServerRCPassword("sv_rc_password", "", ConVarT::FLAG_MAIN_EXE, "The password the server requires for remote console access."); int ServerT::ConFunc_changeLevel_Callback(lua_State* LuaState) { if (!ServerPtr) return luaL_error(LuaState, "The local server is not available."); std::string NewWorldName=(lua_gettop(LuaState)<1) ? "" : luaL_checkstring(LuaState, 1); std::string PathName ="Games/" + ServerPtr->m_GameInfo.GetName() + "/Worlds/" + NewWorldName + ".cw"; if (NewWorldName=="") { // changeLevel() or changeLevel("") was called, so change into the (implicit) "no map loaded" state. // First disconnect from / drop all the clients. // Note that this is a bit different from calling DropClient() for everyone though. for (unsigned long ClNr=0; ClNr<ServerPtr->ClientInfos.Size(); ClNr++) { ClientInfoT* ClInfo=ServerPtr->ClientInfos[ClNr]; if (ClInfo->ClientState==ClientInfoT::Zombie) continue; NetDataT NewReliableMsg; NewReliableMsg.WriteByte (SC1_DropClient); NewReliableMsg.WriteLong (ClInfo->EntityID); NewReliableMsg.WriteString("Server has been stopped (map unloaded)."); ClInfo->ReliableDatas.PushBack(NewReliableMsg.Data); // The client was disconnected, but it goes into a zombie state for a few seconds to make sure // any final reliable message gets resent if necessary. // The time-out will finally remove the zombie entirely when its zombie-time is over. ClInfo->ClientState =ClientInfoT::Zombie; ClInfo->TimeSinceLastMessage=0.0; } delete ServerPtr->World; ServerPtr->World =NULL; ServerPtr->WorldName=""; ServerPtr->GuiCallback.OnServerStateChanged("idle"); return 0; } // changeLevel("mapname") was called, so perform a proper map change. CaServerWorldT* NewWorld=NULL; try { NewWorld=new CaServerWorldT(PathName.c_str(), ServerPtr->m_ModelMan, ServerPtr->m_GuiRes); } catch (const WorldT::LoadErrorT& E) { return luaL_error(LuaState, E.Msg); } delete ServerPtr->World; ServerPtr->World =NewWorld; ServerPtr->WorldName=NewWorldName; // Stati der verbundenen Clients auf MapTransition setzen. for (unsigned long ClientNr=0; ClientNr<ServerPtr->ClientInfos.Size(); ClientNr++) { ClientInfoT* ClInfo=ServerPtr->ClientInfos[ClientNr]; if (ClInfo->ClientState==ClientInfoT::Zombie) continue; // A player entity will be assigned and the SC1_WorldInfo message be sent in the main loop. ClInfo->InitForNewWorld(0); } Console->Print("Level changed on server.\n"); ServerPtr->GuiCallback.OnServerStateChanged("maploaded"); return 0; } static ConFuncT ConFunc_changeLevel("changeLevel", ServerT::ConFunc_changeLevel_Callback, ConFuncT::FLAG_MAIN_EXE, "Makes the server load a new level."); // This console function is called at any time (e.g. when we're NOT thinking)... /*static*/ int ServerT::ConFunc_runMapCmd_Callback(lua_State* LuaState) { if (!ServerPtr) return luaL_error(LuaState, "The local server is not available."); if (!ServerPtr->World) return luaL_error(LuaState, "There is no world loaded in the local server."); // ServerPtr->World->GetScriptState_OLD().DoString(luaL_checkstring(LuaState, 1)); // return 0; return luaL_error(LuaState, "Sorry, this function is not implemented at this time."); } static ConFuncT ConFunc_runMapCmd("runMapCmd", ServerT::ConFunc_runMapCmd_Callback, ConFuncT::FLAG_MAIN_EXE, "Runs the given command string in the context of the current map/entity script."); ServerT::ServerT(const GameInfoT& GameInfo, const GuiCallbackI& GuiCallback_, ModelManagerT& ModelMan, cf::GuiSys::GuiResourcesT& GuiRes) : ServerSocket(g_WinSock->GetUDPSocket(Options_ServerPortNr.GetValueInt())), m_GameInfo(GameInfo), WorldName(""), World(NULL), GuiCallback(GuiCallback_), m_ModelMan(ModelMan), m_GuiRes(GuiRes) { if (ServerSocket==INVALID_SOCKET) throw InitErrorT(cf::va("Unable to obtain UDP socket on port %i.", Options_ServerPortNr.GetValueInt())); assert(ServerPtr==NULL); ServerPtr=this; // TODO: Turn the ServerT class into a singleton? } ServerT::~ServerT() { for (unsigned long ClientNr=0; ClientNr<ClientInfos.Size(); ClientNr++) delete ClientInfos[ClientNr]; delete World; World=NULL; assert(ServerPtr==this); ServerPtr=NULL; assert(ServerSocket!=INVALID_SOCKET); closesocket(ServerSocket); ServerSocket=INVALID_SOCKET; } void ServerT::MainLoop() { // Bestimme die FrameTime des letzten Frames float FrameTime=float(Timer.GetSecondsSinceLastCall()); if (FrameTime<0.0001f) FrameTime=0.0001f; if (FrameTime> 10.0f) FrameTime= 10.0f; // Check Client Time-Outs for (unsigned long ClientNr=0; ClientNr<ClientInfos.Size(); ClientNr++) { ClientInfos[ClientNr]->TimeSinceLastMessage+=FrameTime; if (ClientInfos[ClientNr]->ClientState==ClientInfoT::Zombie) { if (ClientInfos[ClientNr]->TimeSinceLastMessage>6.0) { delete ClientInfos[ClientNr]; ClientInfos[ClientNr]=ClientInfos[ClientInfos.Size()-1]; ClientInfos.DeleteBack(); ClientNr--; continue; } } else // Online oder Wait4MapInfoACK { if (ClientInfos[ClientNr]->TimeSinceLastMessage>120.0) { DropClient(ClientNr, "Timed out!"); ClientInfos[ClientNr]->TimeSinceLastMessage=300.0; // Don't bother with zombie state } } } // Warte, bis wir neue Packets bekommen oder das Frame zu Ende geht fd_set ReadabilitySocketSet; timeval TimeOut; TimeOut.tv_sec =0; TimeOut.tv_usec=10*1000; #if defined(_WIN32) && defined(__WATCOMC__) #pragma warning 555 9; #endif FD_ZERO(&ReadabilitySocketSet); FD_SET(ServerSocket, &ReadabilitySocketSet); #if defined(_WIN32) && defined(__WATCOMC__) #pragma warning 555 4; #endif // select() bricht mit der Anzahl der lesbar gewordenen Sockets ab, 0 bei TimeOut oder SOCKET_ERROR im Fehlerfall. const int Result=select(int(ServerSocket+1), &ReadabilitySocketSet, NULL, NULL, &TimeOut); if (Result==SOCKET_ERROR) { Console->Print(cf::va("ERROR: select() returned WSA fail code %u\n", WSAGetLastError())); } else if (Result!=0) { // In dieser Schleife werden solange die Packets der Clients abgeholt, bis keine mehr da sind (would block). unsigned long MaxPacketsCount=20; while (MaxPacketsCount--) { try { NetDataT InData; NetAddressT SenderAddress=InData.Receive(ServerSocket); if (GameProtocol1T::IsIncomingMessageOutOfBand(InData)) { ProcessConnectionLessPacket(InData, SenderAddress); } else { // ClientNr des Absenders heraussuchen unsigned long ClientNr; for (ClientNr=0; ClientNr<ClientInfos.Size(); ClientNr++) if (SenderAddress==ClientInfos[ClientNr]->ClientAddress) break; // Prüfe ClientNr if (ClientNr>=ClientInfos.Size()) { Console->Warning(cf::va("Client %s is not connected! Packet ignored!\n", SenderAddress.ToString())); // Hier evtl. ein bad / disconnect / kick packet schicken? continue; } // Was Zombies senden, interessiert uns nicht mehr if (ClientInfos[ClientNr]->ClientState==ClientInfoT::Zombie) continue; // Es ist eine gültige Nachricht (eines Online- oder Wait4MapInfoACK-Client) - bearbeite sie! GlobalClientNr=ClientNr; assert(ServerPtr==this); ClientInfos[ClientNr]->TimeSinceLastMessage=0.0; // Do not time-out ClientInfos[ClientNr]->GameProtocol.ProcessIncomingMessage(InData, ProcessInGamePacketHelper); } } catch (const NetDataT::WinSockAPIError& E) { if (E.Error==WSAEWOULDBLOCK) { // Break the while-loop, there is no point in trying to receive further messages right now. // (This is also the reason why we cannot test E.Error in a switch-case block here.) break; } // Deal with other errors that don't have to break the while-loop above. switch (E.Error) { case WSAECONNRESET: { // Receiving this error indicates that a previous send operation resulted in an ICMP "Port Unreachable" message. // This in turn occurs whenever a client disconnected without us having received the proper disconnect message. // If we did nothing here, this message would be received until we stopped sending more messages to the client, // that is, until we got rid of the client due to time-out. // Try to find the offending client, and drop it. bool FoundOffender=false; for (unsigned long ClientNr=0; ClientNr<ClientInfos.Size(); ClientNr++) if (E.Address==ClientInfos[ClientNr]->ClientAddress) { if (ClientInfos[ClientNr]->ClientState!=ClientInfoT::Zombie) DropClient(ClientNr, "ICMP message: client port unreachable!"); // Don't bother with the zombie state, rather remove this client entirely right now. delete ClientInfos[ClientNr]; ClientInfos[ClientNr]=ClientInfos[ClientInfos.Size()-1]; ClientInfos.DeleteBack(); FoundOffender=true; break; } if (!FoundOffender) { // If at all, this should happen only occassionally, e.g. because we sent something to a client // that was removed in the time-out check above. Console->Warning(cf::va("Indata.Receive() returned ECONNRESET from unknown address %s.\n", E.Address.ToString())); } break; } case WSAEMSGSIZE: { Console->Warning(cf::va("Sv: InData.Receive() returned WSA fail code %u (WSAEMSGSIZE). Sender %s. Packet ignored.\n", E.Error, E.Address.ToString())); break; } default: { Console->Warning(cf::va("Sv: InData.Receive() returned WSA fail code %u. Sender %s. Packet ignored.\n", E.Error, E.Address.ToString())); break; } } } } } // Prüfe, ob das ServerTicInterval schon um ist, und führe ggf. einen "ServerTic" aus. /* TimeSinceLastServerTic+=FrameTime; if (TimeSinceLastServerTic<ServerTicInterval-0.001) { // Das ServerTicInterval ist noch nicht rum! // Falls wir nicht alleine (dedicated) laufen, mache sofort mit dem Client weiter. if (!ServerOnly) return true; // Andernfalls (dedicated), verschlafe den Rest des ServerTicIntervals oder bis ein Netzwerk-Paket eingeht. fd_set ReadabilitySocketSet; timeval TimeOut; const float RemainingSeconds=ServerTicInterval-TimeSinceLastServerTic; TimeOut.tv_sec =RemainingSeconds; // Nachkomma-Anteil wird abgeschnitten TimeOut.tv_usec=(RemainingSeconds-float(TimeOut.tv_sec))*1000000.0; #pragma warning 555 9; FD_ZERO(&ReadabilitySocketSet); FD_SET(ServerSocket, &ReadabilitySocketSet); #pragma warning 555 4; // select() bricht mit der Anzahl der lesbar gewordenen Sockets ab, 0 bei TimeOut oder SOCKET_ERROR im Fehlerfall. // Wie auch immer - wir ignorieren den Rückgabewert. select(ServerSocket+1, &ReadabilitySocketSet, NULL, NULL, &TimeOut); return true; } */ if (World) { // Überführe die ServerWorld über die Zeit 'FrameTime' in den nächsten Zustand. // Beachte: Es werden u.a. alle bis hierhin eingegangenen PlayerCommands verarbeitet. // Das ist wichtig für die Prediction, weil wir unten beim Senden mit den Sequence-Nummern des Game-Protocols // bestätigen, daß wir alles bis zur bestätigten Sequence-Nummer gesehen UND VERARBEITET haben! // Insbesondere muß dieser Aufruf daher zwischen dem Empfangen der PlayerCommand-Packets und dem Senden der // nächsten Delta-Update-Messages liegen (WriteClientDeltaUpdateMessages()). World->Think(FrameTime /*TimeSinceLastServerTic*/, ClientInfos); // TimeSinceLastServerTic=0; // All pending player commands have been processed, now clean them up for the next frame. for (unsigned int ClientNr = 0; ClientNr < ClientInfos.Size(); ClientNr++) { ClientInfoT* CI = ClientInfos[ClientNr]; ArrayT<PlayerCommandT>& PPCs = CI->PendingPlayerCommands; if (PPCs.Size() == 0) continue; CI->PreviousPlayerCommand = PPCs[PPCs.Size() - 1]; PPCs.Overwrite(); } // If a client has newly joined the game: // - create a human player entity for it, // - send it the related world info message. for (unsigned int ClientNr = 0; ClientNr < ClientInfos.Size(); ClientNr++) { ClientInfoT* CI = ClientInfos[ClientNr]; if (CI->ClientState == ClientInfoT::Wait4MapInfoACK && CI->EntityID == 0) { CI->EntityID = World->InsertHumanPlayerEntity(CI->PlayerName, CI->ModelName, ClientNr); if (CI->EntityID == 0) { DropClient(ClientNr, "Inserting the player entity failed."); continue; } // The client remains in Wait4MapInfoACK state until it has ack'ed this message. NetDataT NewReliableMsg; NewReliableMsg.WriteByte (SC1_WorldInfo); NewReliableMsg.WriteString(m_GameInfo.GetName()); NewReliableMsg.WriteString(WorldName); NewReliableMsg.WriteLong (CI->EntityID); CI->ReliableDatas.PushBack(NewReliableMsg.Data); } } // Update the connected clients according to the new (now current) world state. for (unsigned long ClientNr = 0; ClientNr < ClientInfos.Size(); ClientNr++) { ClientInfoT* CI = ClientInfos[ClientNr]; // Prepare reliable BaseLine messages for newly created entities that the client // does not yet know about. CI->BaseLineFrameNr is the server frame number up to // which the client has received and acknowledged all BaseLines. That is, BaseLine // messages are created for entities whose BaseLineFrameNr is larger than that. // // Note that after this, no further entities can be added to the world in the // *current* frame, but only in the next! CI->BaseLineFrameNr = World->WriteClientNewBaseLines(CI->BaseLineFrameNr, CI->ReliableDatas); // Update the client's frame info corresponding to the the current server frame. World->UpdateFrameInfo(*CI); } } // Sende die aufgestauten ReliableData und die hier "dynamisch" erzeugten UnreliableData // (bestehend aus den Delta-Update-Messages (FrameInfo+EntityUpdates)) an die für sie bestimmten Empfänger. for (unsigned long ClientNr = 0; ClientNr < ClientInfos.Size(); ClientNr++) { ClientInfoT* CI = ClientInfos[ClientNr]; ClientInfos[ClientNr]->TimeSinceLastUpdate+=FrameTime; // Only send something after a minimum interval. if (CI->TimeSinceLastUpdate < 0.05) continue; NetDataT UnreliableData; if (World && CI->ClientState != ClientInfoT::Zombie) { World->WriteClientDeltaUpdateMessages(*CI, UnreliableData); } try { // Note that we intentionally also send to clients in Wait4MapInfoACK and Zombie // states, in order to keep the handling (with possible re-transfers) of reliable // data going. // TODO: Für Zombies statt rel.+unrel. Data nur leere Buffer übergeben! VORHER aber die DropMsg in ServerT::DropClient SENDEN! CI->GameProtocol.GetTransmitData(CI->ReliableDatas, UnreliableData.Data).Send(ServerSocket, CI->ClientAddress); } catch (const GameProtocol1T::MaxMsgSizeExceeded& /*E*/) { Console->Warning(cf::va("(ClientNr==%u, EntityID==%u) caught a GameProtocol1T::MaxMsgSizeExceeded exception!", ClientNr, CI->EntityID)); } catch (const NetDataT::WinSockAPIError& E ) { Console->Warning(cf::va("caught a NetDataT::WinSockAPIError exception (error %u)!", E.Error)); } catch (const NetDataT::MessageLength& E ) { Console->Warning(cf::va("caught a NetDataT::MessageLength exception (wanted %u, actual %u)!", E.Wanted, E.Actual)); } CI->ReliableDatas.Clear(); CI->TimeSinceLastUpdate = 0; } } void ServerT::DropClient(unsigned long ClientNr, const char* Reason) { // Calling code should not try to drop a client what has been dropped before and thus is in zombie state already. assert(ClientInfos[GlobalClientNr]->ClientState!=ClientInfoT::Zombie); // Broadcast reliable DropClient message to everyone, including the client to be dropped. // This messages includes the entity ID and the reason for the drop. for (unsigned long ClNr=0; ClNr<ClientInfos.Size(); ClNr++) { NetDataT NewReliableMsg; NewReliableMsg.WriteByte (SC1_DropClient); NewReliableMsg.WriteLong (ClientInfos[ClientNr]->EntityID); NewReliableMsg.WriteString(Reason); ClientInfos[ClNr]->ReliableDatas.PushBack(NewReliableMsg.Data); // TODO: HIER DIE MESSAGE AUCH ABSENDEN! // KANN DANN UNTEN IN DER HAUPTSCHLEIFE FÜR ZOMBIES DIE REL+UNREL. DATA KOMPLETT UNTERDRUECKEN! } Console->Print(cf::va("Dropped client %u (EntityID %u, PlayerName '%s'). Reason: %s\n", ClientNr, ClientInfos[ClientNr]->EntityID, ClientInfos[ClientNr]->PlayerName.c_str(), Reason)); // The server world will clean-up the client's now abandoned human player entity at // ClientInfos[ClientNr]->EntityID automatically, as no (non-zombie) client is referring to it any longer. // From the view of the remaining clients this is the same as with any other entity that has been deleted. // The client was disconnected, but it goes into a zombie state for a few seconds to make sure // any final reliable message gets resent if necessary. // The time-out will finally remove the zombie entirely when its zombie-time is over. ClientInfos[ClientNr]->ClientState =ClientInfoT::Zombie; ClientInfos[ClientNr]->TimeSinceLastMessage=0.0; } void ServerT::ProcessConnectionLessPacket(NetDataT& InData, const NetAddressT& SenderAddress) { unsigned long PacketID=InData.ReadLong(); // Die Antwort auf ein "connection-less" Packet beginnt mit 0xFFFFFFFF, gefolgt von der PacketID, // sodaß das Rückpacket unten nur noch individuell beendet werden muß. NetDataT OutData; OutData.WriteLong(0xFFFFFFFF); OutData.WriteLong(PacketID); // Der Typ dieser Nachricht entscheidet, wie es weitergeht try { switch (InData.ReadByte()) { case CS0_NoOperation: // Packet is a "no operation" request, thus we won't accomplish anything Console->Print("PCLP: Packet evaluated to NOP.\n"); break; case CS0_Ping: Console->Print("PCLP: Acknowledging inbound ping.\n"); OutData.WriteByte(SC0_ACK); OutData.Send(ServerSocket, SenderAddress); break; case CS0_Connect: { // Connection request Console->Print(cf::va("PCLP: Got a connection request from %s\n", SenderAddress.ToString())); if (World==NULL) { Console->Print("No world loaded.\n"); OutData.WriteByte(SC0_NACK); OutData.WriteString("No world loaded on server."); OutData.Send(ServerSocket, SenderAddress); break; } // Prüfe, ob wir die IP-Adr. und Port-Nr. des Clients schon haben, d.h. ob der Client schon connected ist. // (Dann hat z.B. der Client schonmal einen connection request geschickt, aber unser Acknowledge niemals erhalten, // oder wir haben seinen Disconnected-Request nicht erhalten und er versucht nun vor dem TimeOut einen neuen Connect.) unsigned long ClientNr; for (ClientNr=0; ClientNr<ClientInfos.Size(); ClientNr++) if (SenderAddress==ClientInfos[ClientNr]->ClientAddress) break; if (ClientNr<ClientInfos.Size()) { Console->Print("Already listed.\n"); OutData.WriteByte(SC0_NACK); OutData.WriteString("Already listed. Wait for timeout and try again."); OutData.Send(ServerSocket, SenderAddress); break; } if (ClientInfos.Size()>=32) { Console->Print("Server is full.\n"); OutData.WriteByte(SC0_NACK); OutData.WriteString("Server is full."); OutData.Send(ServerSocket, SenderAddress); break; } const char* PlayerName=InData.ReadString(); const char* ModelName =InData.ReadString(); if (PlayerName==NULL || ModelName==NULL || InData.ReadOfl) { Console->Print("Bad player or model name.\n"); OutData.WriteByte(SC0_NACK); OutData.WriteString("Bad player or model name."); OutData.Send(ServerSocket, SenderAddress); break; } ClientInfoT* CI = new ClientInfoT(SenderAddress, PlayerName, ModelName); ClientInfos.PushBack(CI); // A player entity will be assigned and the SC1_WorldInfo message be sent in the main loop. // Dem Client bestätigen, daß er im Spiel ist und ab sofort in-game Packets zu erwarten hat. OutData.WriteByte(SC0_ACK); OutData.WriteString(m_GameInfo.GetName()); OutData.Send(ServerSocket, SenderAddress); Console->Print(CI->PlayerName + " joined.\n"); break; } case CS0_Info: // Dem Client Server-Infos schicken Console->Print(cf::va("PCLP: Got an information request from %s\n", SenderAddress.ToString())); OutData.WriteByte(SC0_NACK); OutData.WriteString("Information is not yet available!"); OutData.Send(ServerSocket, SenderAddress); break; case CS0_RemoteConsoleCommand: { const char* Password=InData.ReadString(); if (!Password) break; const char* Command =InData.ReadString(); if (!Command ) break; // Make sure that at least 500ms pass between two successive remote commands. ; Console->Print(cf::va("Remote console command received from %s: %s\n", SenderAddress.ToString(), Command)); // Make sure that the sv_rc_password is set (must be done in the config.lua file). if (ServerRCPassword.GetValueString()=="") { Console->Print("Server rcon password not set.\n"); OutData.WriteByte(SC0_RccReply); OutData.WriteString("Server rcon password not set.\n"); OutData.Send(ServerSocket, SenderAddress); break; } // Make sure that the received password is valid. if (Password!=ServerRCPassword.GetValueString()) { Console->Print(cf::va("Invalid password \"%s\".\n", Password)); OutData.WriteByte(SC0_RccReply); OutData.WriteString("Invalid password.\n"); OutData.Send(ServerSocket, SenderAddress); break; } // Begin to temporarily redirect all console output. cf::ConsoleStringBufferT RedirCon; cf::ConsoleI* OldCon=Console; Console=&RedirCon; // Ok, it has been a valid remote console command - process it. ConsoleInterpreter->RunCommand(Command); // End of temporarily redirected output. std::string Output=RedirCon.GetBuffer(); Console=OldCon; Console->Print(Output); // Send result to sender (wrt. max. network packet size, limit the string length to 1024-16 though). if (Output.length()>1024-16) Output=std::string(Output, 0, 1024-16-4)+"...\n"; OutData.WriteByte(SC0_RccReply); OutData.WriteString(Output.c_str()); OutData.Send(ServerSocket, SenderAddress); break; } default: Console->Print(cf::va("PCLP: WARNING: Unknown packet type received! Sender: %s\n", SenderAddress.ToString())); } } catch (const NetDataT::WinSockAPIError& E) { Console->Warning(cf::va("PCLP: Answer failed (WSA error %u)!\n", E.Error)); } catch (const NetDataT::MessageLength& E) { Console->Warning(cf::va("PCLP: Answer too long (wanted %u, actual %u)!\n", E.Wanted, E.Actual)); } } void ServerT::ProcessInGamePacketHelper(NetDataT& InData, unsigned long LastIncomingSequenceNr) { // The LastIncomingSequenceNr is unused now. ServerPtr->ProcessInGamePacket(InData); } void ServerT::ProcessInGamePacket(NetDataT& InData) { // We can only get here when the client who sent the message is not listed as a zombie, // and therefore (consequently) the World pointer must be valid, too. assert(ClientInfos[GlobalClientNr]->ClientState!=ClientInfoT::Zombie); assert(World); // TODO: Wasn't it much easier to simply catch Array-index-out-of-bounds exceptions here? while (!InData.ReadOfl && !(InData.ReadPos>=InData.Data.Size())) { char MessageType=InData.ReadByte(); switch (MessageType) { case CS1_PlayerCommand: { PlayerCommandT PlayerCommand; const unsigned int PlCmdNr = InData.ReadLong(); PlayerCommand.FrameTime = InData.ReadFloat(); PlayerCommand.Keys = InData.ReadLong(); PlayerCommand.DeltaHeading = InData.ReadWord(); PlayerCommand.DeltaPitch = InData.ReadWord(); // PlayerCommand.DeltaBank = InData.ReadWord(); if (InData.ReadOfl) return; // Ignore the rest of the message! // PlayerCommand-Messages eines Clients, der im Wait4MapInfoACK-State ist, gehören idR zur vorher gespielten World. // Akzeptiere PlayerCommand-Messages daher erst (wieder), wenn der Client vollständig online ist. if (ClientInfos[GlobalClientNr]->ClientState!=ClientInfoT::Online) break; ClientInfos[GlobalClientNr]->PendingPlayerCommands.PushBack(PlayerCommand); assert(ClientInfos[GlobalClientNr]->LastPlayerCommandNr < PlCmdNr); ClientInfos[GlobalClientNr]->LastPlayerCommandNr = PlCmdNr; break; } case CS1_Disconnect: { DropClient(GlobalClientNr, "He/She left the game."); return; // Ignore the rest of the message! } case CS1_SayToAll: { const char* InMsg=InData.ReadString(); // Console messages seem to be a popular choice for attackers. // Thus guard against problems. if (InMsg==NULL || InData.ReadOfl) { Console->Print(cf::va("Bad say message from: %s\n", ClientInfos[GlobalClientNr]->PlayerName.c_str())); break; } std::string OutMessage=ClientInfos[GlobalClientNr]->PlayerName+": "+InMsg; // Limit the length of the message wrt. max. network packet size. if (OutMessage.length()>1024-16) OutMessage=std::string(OutMessage, 0, 1024-16-4)+"...\n"; for (unsigned long ClientNr=0; ClientNr<ClientInfos.Size(); ClientNr++) { // TODO: Statt hier ClientState!=Zombie abzufragen, lieber in DropClient schon die Drop-Message SENDEN, // und beim Senden in der Hauptschleife für Zombies leere Buffer für rel. + unrel. Data übergeben! if (ClientInfos[ClientNr]->ClientState!=ClientInfoT::Zombie) { NetDataT NewReliableMsg; NewReliableMsg.WriteByte (SC1_ChatMsg); NewReliableMsg.WriteString(OutMessage); ClientInfos[ClientNr]->ReliableDatas.PushBack(NewReliableMsg.Data); } } break; } case CS1_WorldInfoACK: { const char* ClientWorldName=InData.ReadString(); if (InData.ReadOfl || ClientWorldName==NULL || strlen(ClientWorldName)==0) { // UploadMap(); // Im Moment bei einem Fehler beim Client-WorldChange den Client einfach rausschmeißen! DropClient(GlobalClientNr, "Failure on world change!"); return; // Ignore the rest of the message! } if (ClientWorldName==WorldName) ClientInfos[GlobalClientNr]->ClientState=ClientInfoT::Online; break; } case CS1_FrameInfoACK: { const unsigned long LKFR=InData.ReadLong(); if (InData.ReadOfl) return; // Ignore the rest of the message! ClientInfos[GlobalClientNr]->LastKnownFrameReceived=LKFR; break; } default: Console->Print(cf::va("WARNING: Unknown in-game message type '%3u' received!\n", MessageType)); Console->Print(cf::va(" Sender: %s\n", ClientInfos[GlobalClientNr]->PlayerName.c_str())); return; // Ignore the rest of the message! } } }
42.159033
204
0.600235
dns
475acc180a8a8ecd7f6d0ee5c09eca216228a616
477
cpp
C++
src/os/mock_os_functions.cpp
juruen/cavalieri
c3451579193fc8f081b6228ae295b463a0fd23bd
[ "MIT" ]
54
2015-01-14T21:11:56.000Z
2021-06-27T13:29:40.000Z
src/os/mock_os_functions.cpp
juruen/cavalieri
c3451579193fc8f081b6228ae295b463a0fd23bd
[ "MIT" ]
null
null
null
src/os/mock_os_functions.cpp
juruen/cavalieri
c3451579193fc8f081b6228ae295b463a0fd23bd
[ "MIT" ]
10
2015-07-15T05:09:34.000Z
2019-01-10T07:32:02.000Z
#include <os/mock_os_functions.h> #include <algorithm> ssize_t mock_os_functions::recv(int, void *buf, size_t len, int) { auto min = std::min(len, buffer.size()); std::copy(buffer.begin(), buffer.begin() + min, static_cast<char*>(buf)); return min; } ssize_t mock_os_functions::write(int, void *buf, size_t count) { auto min = std::min(count, buffer.capacity()); auto pbuf = static_cast<char*>(buf); buffer.insert(buffer.end(), pbuf, pbuf + min); return min; }
29.8125
75
0.685535
juruen
475b396719f1106cc50c18ca28a10e414a6d9012
1,809
cpp
C++
hydrogels/theory/models/_cxx/engine.cpp
debeshmandal/brownian
bc5b2e00a04d11319c85e749f9c056b75b450ff7
[ "MIT" ]
3
2020-05-13T01:07:30.000Z
2021-02-12T13:37:23.000Z
hydrogels/theory/models/_cxx/engine.cpp
debeshmandal/brownian
bc5b2e00a04d11319c85e749f9c056b75b450ff7
[ "MIT" ]
24
2020-06-04T13:48:57.000Z
2021-12-31T18:46:52.000Z
hydrogels/theory/models/_cxx/engine.cpp
debeshmandal/brownian
bc5b2e00a04d11319c85e749f9c056b75b450ff7
[ "MIT" ]
1
2020-07-23T17:15:23.000Z
2020-07-23T17:15:23.000Z
#include <Python.h> #include "functions.hpp" #include "utils.hpp" static PyObject* engine_addNumbers(PyObject* self, PyObject* args) { // declare variables double n1, n2, result; // parse arguments if (!PyArg_ParseTuple(args, "dd", &n1, &n2)) { return NULL; }; // function here result = addNumbers(n1, n2); // return correct Type return PyFloat_FromDouble(result); }; static PyObject* engine_vectorNorm(PyObject* self, PyObject* args) { PyObject* py_vect; if (!PyArg_ParseTuple(args, "O", &py_vect)) { return NULL; } std::vector<double> vect = listTupleToVector_Double(py_vect); double result = vectorNorm(vect); return PyFloat_FromDouble(result); }; // Define docstrings PyDoc_STRVAR(engine_docs, "Package for running iterative numerical simulations"); PyDoc_STRVAR(engine_addNumbers_docs, "addNumbers(n1 : number, n2 : number) -> float: add two numbers together\n"); PyDoc_STRVAR(engine_vectorNorm_docs, "vectorNorm(vector : list) -> float: returns the magnitude of a 1D Vector"); // Create list of PyMethodDefs static PyMethodDef EngineFunctions[] = { { "addNumbers", (PyCFunction)engine_addNumbers, METH_VARARGS, engine_addNumbers_docs }, { "vectorNorm", (PyCFunction)engine_vectorNorm, METH_VARARGS, engine_vectorNorm_docs }, {NULL, NULL, 0, NULL} /* Sentinel */ }; // Create the Module static struct PyModuleDef enginemodule = { PyModuleDef_HEAD_INIT, "engine", /* module name */ engine_docs, /* documentation */ -1, /* Leave this as -1 */ EngineFunctions /* function list */ }; // Export module when __init__ is called PyMODINIT_FUNC PyInit_engine(void) { return PyModule_Create(&enginemodule); };
25.842857
114
0.669431
debeshmandal
476035f1a5f85ea33f3730d25bc046f6d95450c4
6,510
cpp
C++
thirdparty/ULib/tests/ulib/http2/hdecode.cpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
null
null
null
thirdparty/ULib/tests/ulib/http2/hdecode.cpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
null
null
null
thirdparty/ULib/tests/ulib/http2/hdecode.cpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
null
null
null
// hdecode.cpp #include <ulib/utility/http2.h> #undef PACKAGE #define PACKAGE "hdecode" #define ARGS "[dump file...]" // The file contains a dump of HPACK octets #define U_OPTIONS \ "purpose 'simple HPACK decoder'\n" \ "option e expect-error 1 '<ERR>' ''\n" \ "option d decoding-spec 1 'Spec format: <letter><size>' ''\n" \ "option t table-size 1 'Default table size: 4096' ''\n" #include <ulib/application.h> #define WRT(buf, len) cout.write(buf, len) #define OUT(msg) cout.write(msg, strlen(msg)) class Application : public UApplication { public: Application() { U_TRACE(5, "Application::Application()") } ~Application() { U_TRACE(5, "Application::~Application()") } /* static bool print(UStringRep* key, void* value) { U_TRACE(5, "Application::print(%V,%p)", key, value) OUT("\n"); WRT(key->data(), key->size()); OUT(": "); WRT(((UStringRep*)value)->data(), ((UStringRep*)value)->size()); U_RETURN(true); } */ static void TST_decode(const UString& content, const UString& spec, int exp) { U_TRACE(5, "Application::TST_decode(%V,%V,%d)", content.rep, spec.rep, exp) bool cut, resize; int32_t index_cut = 0; const char* pspec = spec.data(); uint32_t len = 0, sz = 0, clen = content.size(); unsigned char* cbuf = (unsigned char*)content.data(); UHashMap<UString>* table = &(UHTTP2::pConnection->itable); UHTTP2::HpackDynamicTable* idyntbl = &(UHTTP2::pConnection->idyntbl); OUT("Decoded header list:\n"); /** * Spec format: <letter><size> * * d - decode <size> bytes from the dump * p - decode a partial block of <size> bytes * r - resize the dynamic table to <size> bytes * * The last empty spec decodes the rest of the dump */ do { cut = resize = false; switch (*pspec) { case '\0': len = clen; break; case 'r': resize = true; // resize the dynamic table to <size> bytes case 'p': cut = true; // decode a partial block of <size> bytes case 'd': len = atoi(++pspec); break; default: U_ERROR("Invalid spec"); } if (*pspec != '\0') pspec = strchr(pspec, ',') + 1; if (resize) UHTTP2::setHpackDynTblCapacity(idyntbl, len); else { UHTTP2::nerror = UHTTP2::hpack_errno = 0; UHTTP2::index_ptr = 0; UHTTP2::decodeHeaders(table, idyntbl, cbuf-index_cut, cbuf+len); U_INTERNAL_DUMP("UHTTP2::hpack_errno = %d UHTTP2::nerror = %d cut = %b len = %u", UHTTP2::hpack_errno, UHTTP2::nerror, cut, len) if (exp && exp == UHTTP2::hpack_errno) { return; } index_cut = 0; if (cut) { if (UHTTP2::nerror == UHTTP2::COMPRESSION_ERROR) { if (UHTTP2::index_ptr) { uint32_t advance = UHTTP2::index_ptr - cbuf; U_INTERNAL_DUMP("UHTTP2::index_ptr = %p advance = %u", UHTTP2::index_ptr, advance) if (len > advance) index_cut = (len - advance); } if (index_cut == 0) index_cut = (sz += len); } else { if (UHTTP2::index_ptr) { uint32_t advance = UHTTP2::index_ptr - cbuf; U_INTERNAL_DUMP("UHTTP2::index_ptr = %p advance = %u", UHTTP2::index_ptr, advance) if (len < advance) index_cut = (len - advance); } } U_INTERNAL_DUMP("index_cut = %d", index_cut) } else { if (UHTTP2::nerror != 0 && UHTTP2::hpack_errno == 0) { return; } } cbuf += len; clen -= len; } } while (clen > 0); OUT("\n\n"); } void run(int argc, char* argv[], char* env[]) { U_TRACE(5, "Application::run(%d,%p,%p)", argc, argv, env) UApplication::run(argc, argv, env); // manage arg UString filename = UString(argv[optind]); if (filename.empty()) U_ERROR("missing argument"); UString content = UFile::contentOf(filename); if (content.empty()) U_ERROR("empty file"); // manage options int exp = 0; UString spec; UHTTP2::btest = true; UHTTP2::ctor(); if (UApplication::isOptions()) { spec = opt['d']; UString tmp = opt['t']; if (tmp) { UHTTP2::pConnection->idyntbl.hpack_capacity = UHTTP2::pConnection->idyntbl.hpack_max_capacity = UHTTP2::pConnection->odyntbl.hpack_capacity = UHTTP2::pConnection->odyntbl.hpack_max_capacity = tmp.strtoul(); } tmp = opt['e']; if (tmp) { for (int i = 0; i < 11; ++i) { if (tmp.equal(UHTTP2::hpack_error[i].str, 3)) { exp = UHTTP2::hpack_error[i].value; goto next; } } U_ERROR("Unknown error"); } } next: TST_decode(content, spec, exp); U_INTERNAL_DUMP("UHTTP2::hpack_errno = %d exp = %d", UHTTP2::hpack_errno, exp) /* UHashMap<UString>* table = &(UHTTP2::pConnection->itable); if (table->empty() == false) { UHTTP2::bhash = true; table->callForAllEntrySorted(print); UHTTP2::bhash = false; } */ cout.write(U_CONSTANT_TO_PARAM("Dynamic Table (after decoding):")); UHTTP2::printHpackInputDynTable(); if (UHTTP2::hpack_errno != 0) { char buffer[256]; cerr.write(buffer, u__snprintf(buffer, sizeof(buffer), U_CONSTANT_TO_PARAM("main: hpack result: %s (%d)\n"), UHTTP2::hpack_strerror(), UHTTP2::hpack_errno)); } if (UHTTP2::hpack_errno != exp) UApplication::exit_value = 1; } private: #ifndef U_COVERITY_FALSE_POSITIVE U_DISALLOW_COPY_AND_ASSIGN(Application) #endif }; U_MAIN
25.529412
166
0.5
liftchampion
47636b833a9010110d14e0b9194c2b98f402cc3f
2,652
cpp
C++
raw-examples/my_epoll.cpp
Jayhello/handy-copy
f6b1be65a5372cb42e6479c0b413216a9a689e1f
[ "BSD-2-Clause" ]
null
null
null
raw-examples/my_epoll.cpp
Jayhello/handy-copy
f6b1be65a5372cb42e6479c0b413216a9a689e1f
[ "BSD-2-Clause" ]
null
null
null
raw-examples/my_epoll.cpp
Jayhello/handy-copy
f6b1be65a5372cb42e6479c0b413216a9a689e1f
[ "BSD-2-Clause" ]
null
null
null
// // Created by root on 18-11-21. // /* * Mainly test for server end. */ #include <sys/socket.h> #include <vector> #include <iostream> #include <netinet/in.h> #include <handy/handy.h> #include <arpa/inet.h> using namespace handy; using namespace std; /* * Note: Simple test for max socket num. */ void testMaxSockFd(){ vector<int> vecFd(40000); for (int i = 0; i < vecFd.size(); ++i) { int fd = socket(AF_INET, SOCK_STREAM, 0); fatalif(fd<0, "create sock %d, errno: %d, %s:",i+2, errno, strerror(errno)); // create sock 4093, errno: 24, Too many open files: vecFd[i] = fd; } } sockaddr_in getSockAddr(const string& ip, uint16_t port){ sockaddr_in localAddr; bzero(&localAddr,sizeof(localAddr)); localAddr.sin_family = AF_INET; localAddr.sin_addr.s_addr = inet_addr(ip.data()); localAddr.sin_port = htons(port); return localAddr; } auto lb_process_client = [](int fd){ int count = 0; char buf[200]; memset(buf, '\0', 200); for (int i = 0; i < 3; ++i) { string msg = "server msg: " + to_string(count++); int len = send(fd, (void*)msg.data(), msg.size(), 0); if(len < 0){ info("send error, peer close fd"); break; } info("send %d", len); memset(buf, '\0', 200); len = recv(fd, buf, 200, 0); if(len < 0){ info("recv error, peer close fd"); break; } info("recv %s, len %d", buf, len); sleep(2); } close(fd); info("process ending, %d", fd); }; void testServer(){ int sockFd = socket(AF_INET, SOCK_STREAM, 0); fatalif(sockFd < 0, "socket failed %d %s", errno, strerror(errno)); string ip = "127.0.0.1"; uint16_t port = 8000; Ip4Addr localAddr(ip, port); int ret = bind(sockFd, (struct sockaddr*)&localAddr.getAddr(), sizeof(localAddr.getAddr())); fatalif(ret < 0, "bind socket failed %d %s", errno, strerror(errno)); ret = listen(sockFd, 100); fatalif(ret < 0, "listen socket failed %d %s", errno, strerror(errno)); info("now i will sleep 100S"); sleep(100); ThreadPool tp(5); while(true){ struct sockaddr_in raddr; socklen_t rsz = sizeof(raddr); int cfd = accept(sockFd, (struct sockaddr *) &raddr, &rsz); fatalif(cfd < 0, "accept failed"); Ip4Addr tmp(raddr); info("accept a connection from %s", tmp.toString().c_str()); tp.addTask(std::bind(lb_process_client, cfd)); } } int main(){ testMaxSockFd(); // testServer(); return 0; }
21.737705
84
0.563725
Jayhello
4767a60e01d3a1b0bef6a71f7941455efc452fdf
1,028
cpp
C++
Sid's Levels/Level - 2/Graphs/BFS.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
14
2021-08-22T18:21:14.000Z
2022-03-08T12:04:23.000Z
Sid's Levels/Level - 2/Graphs/BFS.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
1
2021-10-17T18:47:17.000Z
2021-10-17T18:47:17.000Z
Sid's Levels/Level - 2/Graphs/BFS.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
5
2021-09-01T08:21:12.000Z
2022-03-09T12:13:39.000Z
class Solution { public: //Function to return Breadth First Traversal of given graph. void bfsHelper(vector<int> &bfs, bool visited[], vector<int> adj[], int src) { queue<int> q; q.push(src); visited[src] = true; while(!q.empty()) { int cur = q.front(); q.pop(); bfs.push_back(cur); for(auto it = adj[cur].begin(); it != adj[cur].end(); it++) { if(visited[*it] != true) { q.push(*it); visited[*it] = true; } } } } vector<int>bfsOfGraph(int V, vector<int> adj[]) { // Code here //OM GAN GANAPATHAYE NAMO NAMAH //JAI SHRI RAM //JAI BAJRANGBALI //AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA vector<int> bfs; bool visited[V]; for(int i = 0; i < V; i++) visited[i] = false; bfsHelper(bfs, visited, adj, 0); return bfs; } };
25.7
80
0.474708
Tiger-Team-01
47692a35ba87389e363a8e763496408888586d82
1,463
cpp
C++
src/runtime_src/xdp/profile/plugin/vp_base/vp_base_plugin.cpp
houlz0507/XRT-1
1b66ba8a5031ac1f694b0686774218c0d7286c52
[ "Apache-2.0" ]
null
null
null
src/runtime_src/xdp/profile/plugin/vp_base/vp_base_plugin.cpp
houlz0507/XRT-1
1b66ba8a5031ac1f694b0686774218c0d7286c52
[ "Apache-2.0" ]
null
null
null
src/runtime_src/xdp/profile/plugin/vp_base/vp_base_plugin.cpp
houlz0507/XRT-1
1b66ba8a5031ac1f694b0686774218c0d7286c52
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2016-2020 Xilinx, Inc * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ #define XDP_SOURCE #include "xdp/profile/plugin/vp_base/vp_base_plugin.h" #include "xdp/profile/device/device_intf.h" namespace xdp { XDPPlugin::XDPPlugin() : db(VPDatabase::Instance()) { // The base class should not add any devices as different plugins // should not clash with respect to the accessing the hardware. } XDPPlugin::~XDPPlugin() { for (auto w : writers) { delete w ; } } void XDPPlugin::writeAll(bool openNewFiles) { // Base functionality is just to have all writers write. Derived // classes might have to do more. for (auto w : writers) { w->write(openNewFiles) ; } } void XDPPlugin::readDeviceInfo(void* /*device*/) { // Since we can have multiple plugins, the default behavior should // be that the plugin doesn't read any device information } }
26.6
76
0.688995
houlz0507
4769892825000c71007faa865c2f0155d8a2bcfc
1,953
cc
C++
Ex05_Prototype/src/1_document_manager/docmanager.cc
kks32/cpp-software-development
3ce0c66d812d9a166191a1007111501615c97a2c
[ "MIT" ]
64
2015-01-18T17:53:56.000Z
2022-03-06T11:37:25.000Z
Ex05_Prototype/src/1_document_manager/docmanager.cc
kks32/cpp-software-development
3ce0c66d812d9a166191a1007111501615c97a2c
[ "MIT" ]
null
null
null
Ex05_Prototype/src/1_document_manager/docmanager.cc
kks32/cpp-software-development
3ce0c66d812d9a166191a1007111501615c97a2c
[ "MIT" ]
24
2015-03-22T02:00:10.000Z
2022-01-18T13:17:26.000Z
#include <iostream> #include <vector> #include <algorithm> #include <functional> const int N = 4; // # of document types + 1 // Prototype class Document { public: virtual Document* clone() const = 0; virtual void store() const = 0; virtual ~Document() { } }; // Concrete prototypes : xmlDoc, plainDoc, spreadsheetDoc class xmlDoc : public Document { public: Document* clone() const { return new xmlDoc; } void store() const { std::cout << "xmlDoc\n"; } }; class plainDoc : public Document { public: Document* clone() const { return new plainDoc; } void store() const { std::cout << "plainDoc\n"; } }; class spreadsheetDoc : public Document { public: Document* clone() const { return new spreadsheetDoc; } void store() const { std::cout << "spreadsheetDoc\n"; } }; // makeDocument() calls Concrete Portotype's clone() method // inherited from Prototype class DocumentManager { public: static Document* makeDocument( int choice ); ~DocumentManager(){} private: static Document* mDocTypes[N]; }; Document* DocumentManager::mDocTypes[] = { 0, new xmlDoc, new plainDoc, new spreadsheetDoc }; Document* DocumentManager::makeDocument( int choice ) { return mDocTypes[choice]->clone(); } // for_each op () struct Destruct { void operator()(Document *a) const { delete a; } }; // Client int main(int argc, char** argv) { std::vector<Document*> docs(N); int choice; std::cout << "quit(0), xml(1), plain(2), spreadsheet(3): " << std::endl; while(true) { std::cout << "Type in your choice (0-3)\n"; std::cin >> choice; if(choice <= 0 || choice >= N) break; docs[choice] = DocumentManager::makeDocument( choice ); } for(int i = 1; i < docs.size(); ++i) if(docs[i]) docs[i]->store(); Destruct d; // this calls Destruct::operator() std::for_each(docs.begin(), docs.end(), d); return 0; }
21.461538
76
0.623144
kks32
47705c1796084733843018e789d6030866a69d30
4,486
cpp
C++
source/polyvec/curve-tracer/measure_accuracy_polygon.cpp
ShnitzelKiller/polyfit
51ddc6365a794db1678459140658211cb78f65b1
[ "MIT" ]
27
2020-08-17T17:25:59.000Z
2022-03-01T05:49:12.000Z
source/polyvec/curve-tracer/measure_accuracy_polygon.cpp
ShnitzelKiller/polyfit
51ddc6365a794db1678459140658211cb78f65b1
[ "MIT" ]
4
2020-08-26T13:54:59.000Z
2020-09-21T07:19:22.000Z
source/polyvec/curve-tracer/measure_accuracy_polygon.cpp
ShnitzelKiller/polyfit
51ddc6365a794db1678459140658211cb78f65b1
[ "MIT" ]
5
2020-08-26T23:26:48.000Z
2021-01-04T09:06:07.000Z
// polyvec #include <polyvec/curve-tracer/measure_accuracy_polygon.hpp> #include <polyvec/curve-tracer/find-fitting-points.hpp> #include <polyvec/utils/matrix.hpp> #include <polyvec/curve-tracer/spline.hpp> #include <polyvec/utils/directions.hpp> // remove todo #include <polyvec/geom.hpp> // nop #include <polyvec/debug.hpp> // libc++ #include <cstdlib> // min, max using namespace polyvec; using namespace std; NAMESPACE_BEGIN(polyfit) NAMESPACE_BEGIN(CurveTracer) void measure_accuracy_signed_extended_polygon_fit_symmetric( const mat2x& B, // raster boundary const vecXi& P, // polygon const Vertex corner, // corner AccuracyMeasurement& m,// result const bool circular ) { double len_prev = 0.; if (circular || corner > 0) { len_prev = (B.col(CircularAt(P, corner - 1)) - B.col(CircularAt(P, corner))).norm(); } double len_next = 0.; if (circular || corner < P.size() - 1) { len_next = (B.col(CircularAt(P, corner + 1)) - B.col(CircularAt(P, corner))).norm(); } int e_start = corner; double t_start = 0.; if (circular || corner > 0) { e_start = Circular(P, corner - 1); t_start = (.5 * min(len_prev, len_next)) / len_prev; } // i don't think this works for non-circular segments (todo) int e_end = corner; double t_end = 0.; if (circular || corner < P.size() - 1) { t_end = (.5 * min(len_prev, len_next)) / len_next; } // Fitting data const vec2 p0 = B.col(P(e_start)); const vec2 p1 = B.col(P(e_end)); const vec2 p2 = B.col(CircularAt(P, e_end + 1)); // todo circularity mat2xi V_fit; mat2x P_fit; // (1) find fitting points find_pixel_centers_for_subpath(B, P, e_start, t_start, e_start, 1., V_fit, &P_fit, circular); // (1) compute fitting normals mat2x N_fit(2, P_fit.cols()); for (int i = 0; i < P_fit.cols(); ++i) { N_fit.col(i) = polyvec::util::normal_dir(B.col(V_fit(0, i)) - B.col(V_fit(1, i))); } // (1) construct edge segment GlobFitCurve_Line edge0; edge0.set_points( p0 + (p1 - p0) * t_start, p1 ); // (1) test accuracy AccuracyMeasurement m0 = measure_accuracy(edge0, P_fit, N_fit); // (2) find fitting points V_fit.resize(2, 0); P_fit.resize(2, 0); find_pixel_centers_for_subpath(B, P, e_end, 0., e_end, t_end, V_fit, &P_fit, circular); // (2) compute fitting normals N_fit.resize(2, P_fit.cols()); for (int i = 0; i < P_fit.cols(); ++i) { N_fit.col(i) = polyvec::util::normal_dir(B.col(V_fit(0, i)) - B.col(V_fit(1, i))); } // (2) construct edge segment GlobFitCurve_Line edge1; edge1.set_points( p1, p1 + (p2 - p1) * t_end ); // (2) test accuracy AccuracyMeasurement m1 = measure_accuracy(edge1, P_fit, N_fit); new (&m) AccuracyMeasurement; m.combine(m0); m.combine(m1); } void measure_accuracy_signed_extended_polygon_fit_asymmetric( const mat2x& B, // raster boundary const vecXi& P, // polygon const Vertex corner, // corner AccuracyMeasurement& m,// result const bool circular ) { double t_start = .5; int e_start = corner; if (circular || corner > 0) { e_start = Circular(P, corner - 1); } double t_end = .5; int e_end = corner; // Fitting data const vec2 p0 = B.col(P(e_start)); const vec2 p1 = B.col(P(e_end)); const vec2 p2 = B.col(CircularAt(P, e_end + 1)); // todo circularity mat2xi V_fit; mat2x P_fit; // (1) find fitting points find_pixel_centers_for_subpath(B, P, e_start, t_start, e_start, 1., V_fit, &P_fit, circular); // (1) compute fitting normals mat2x N_fit(2, P_fit.cols()); for (int i = 0; i < P_fit.cols(); ++i) { N_fit.col(i) = polyvec::util::normal_dir(B.col(V_fit(1, i)) - B.col(V_fit(0, i))); } // (1) construct edge segment GlobFitCurve_Line edge0; edge0.set_points( p0 + (p1 - p0) * t_start, p1 ); // (1) test accuracy AccuracyMeasurement m0 = measure_accuracy(edge0, P_fit, N_fit); // (2) find fitting points V_fit.resize(2, 0); P_fit.resize(2, 0); find_pixel_centers_for_subpath(B, P, e_end, 0., e_end, t_end, V_fit, &P_fit, circular); // (2) compute fitting normals N_fit.resize(2, P_fit.cols()); for (int i = 0; i < P_fit.cols(); ++i) { N_fit.col(i) = polyvec::util::normal_dir(B.col(V_fit(1, i)) - B.col(V_fit(0, i))); } // (2) construct edge segment GlobFitCurve_Line edge1; edge1.set_points( p1, p1 + (p2 - p1) * t_end ); // (2) test accuracy AccuracyMeasurement m1 = measure_accuracy(edge1, P_fit, N_fit); new (&m) AccuracyMeasurement; m.combine(m0); m.combine(m1); } NAMESPACE_END(CurveTracer) NAMESPACE_END(polyfit)
25.488636
94
0.664958
ShnitzelKiller
4773f6d904dd964414634842934b3ac94122ba3d
1,438
cpp
C++
PE/ch07/7.3.cpp
DustOfStars/CppPrimerPlus6
391e3ad76eaa99f331981cee72139d83115fc93d
[ "MIT" ]
null
null
null
PE/ch07/7.3.cpp
DustOfStars/CppPrimerPlus6
391e3ad76eaa99f331981cee72139d83115fc93d
[ "MIT" ]
null
null
null
PE/ch07/7.3.cpp
DustOfStars/CppPrimerPlus6
391e3ad76eaa99f331981cee72139d83115fc93d
[ "MIT" ]
null
null
null
/* * Here is a structure declaration: * struct box * { * char maker[40]; * float height; * float width; * float length; * float volume; * }; * a. Write a function that passes a box structure by value and that * displays the value of each member. * b. Write a function that passes the address of a box structure and that * sets the volume member to be the product of the other three * dimensions. * c. Write a simple program that uses these two functions. */ #include <iostream> struct box { char maker[40]; float height; float width; float length; float volume; }; void setbox(box *); void showbox(box); int main() { box abox; setbox(&abox); showbox(abox); return 0; } void setbox(box * pbox) { using namespace std; cout << "Enter the maker of the box: "; cin.getline(pbox->maker, 40); cout << "Enter the height of the box: "; cin >> pbox->height; cout << "Enter the width of the box: "; cin >> pbox->width; cout << "Enter the length of the box: "; cin >> pbox->length; pbox->volume = pbox->height * pbox->width * pbox->length; } void showbox(box abox) { using namespace std; cout << "Maker: " << abox.maker << endl; cout << "Height: " << abox.height << endl; cout << "Width: " << abox.width << endl; cout << "Length: " << abox.length << endl; cout << "Volume: " << abox.volume << endl; }
23.193548
74
0.599444
DustOfStars
477c043a83046e8df11f1c09270247b327afbaf7
525
hpp
C++
src/picotorrent/sessionstate.hpp
kamyarpour/picotorrent
bc33ca2f84d95b431ff62bbeb64fcb8f15d94c73
[ "MIT" ]
1
2020-01-13T23:33:44.000Z
2020-01-13T23:33:44.000Z
src/picotorrent/sessionstate.hpp
kamyarpour/picotorrent
bc33ca2f84d95b431ff62bbeb64fcb8f15d94c73
[ "MIT" ]
null
null
null
src/picotorrent/sessionstate.hpp
kamyarpour/picotorrent
bc33ca2f84d95b431ff62bbeb64fcb8f15d94c73
[ "MIT" ]
null
null
null
#pragma once #include <map> #include <memory> #include <unordered_set> #include <libtorrent/fwd.hpp> #include <libtorrent/sha1_hash.hpp> namespace pt { struct SessionState { bool isSelected(libtorrent::sha1_hash const& hash); std::unordered_set<libtorrent::sha1_hash> pauseAfterChecking; std::unordered_set<libtorrent::sha1_hash> selectedTorrents; std::unique_ptr<libtorrent::session> session; std::map<libtorrent::sha1_hash, libtorrent::torrent_handle> torrents; }; }
23.863636
77
0.712381
kamyarpour
4780cee7220596d117c7561435c2612e9579fab3
382
cpp
C++
exe6.cpp
priya29jps/top-100-code-in-cpp
22d9328217a7f2ecbd09e62e750d8cad37baf046
[ "Apache-2.0" ]
null
null
null
exe6.cpp
priya29jps/top-100-code-in-cpp
22d9328217a7f2ecbd09e62e750d8cad37baf046
[ "Apache-2.0" ]
null
null
null
exe6.cpp
priya29jps/top-100-code-in-cpp
22d9328217a7f2ecbd09e62e750d8cad37baf046
[ "Apache-2.0" ]
null
null
null
//problem in linear search #include<iostream> using namespace std; int linearSearch(int arry[],int n,int key) { for(int i=0;i<=n;i++) if(arry[i]==key){ return i; } return -1; } int main(){ int n; cin>>n; int arry[n]; for(int i=0;i<=n;i++) { cin>>arry[i]; } int key; cin>>key; cout<<linearSearch(arry,n,key); return 0; }
11.9375
43
0.536649
priya29jps
4783265799cbd7bf20ce6043d7246983f38d937c
16,464
cc
C++
tensorflow/c/experimental/filesystem/plugins/s3/s3_filesystem_test.cc
eee4017/tensorflow
deba51f80e05775bb4cc83647b475802be58f1e4
[ "Apache-2.0" ]
null
null
null
tensorflow/c/experimental/filesystem/plugins/s3/s3_filesystem_test.cc
eee4017/tensorflow
deba51f80e05775bb4cc83647b475802be58f1e4
[ "Apache-2.0" ]
null
null
null
tensorflow/c/experimental/filesystem/plugins/s3/s3_filesystem_test.cc
eee4017/tensorflow
deba51f80e05775bb4cc83647b475802be58f1e4
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/c/experimental/filesystem/plugins/s3/s3_filesystem.h" #include <fstream> #include <random> #include "tensorflow/core/platform/path.h" #include "tensorflow/core/platform/stacktrace_handler.h" #include "tensorflow/core/platform/test.h" #define ASSERT_TF_OK(x) ASSERT_EQ(TF_OK, TF_GetCode(x)) << TF_Message(x) #define EXPECT_TF_OK(x) EXPECT_EQ(TF_OK, TF_GetCode(x)) << TF_Message(x) static std::string InitializeTmpDir() { // This env should be something like `s3://bucket/path` const char* test_dir = getenv("S3_TEST_TMPDIR"); if (test_dir != nullptr) { Aws::String bucket, object; TF_Status* status = TF_NewStatus(); ParseS3Path(test_dir, true, &bucket, &object, status); if (TF_GetCode(status) != TF_OK) { TF_DeleteStatus(status); return ""; } TF_DeleteStatus(status); // We add a random value into `test_dir` to ensures that two consecutive // runs are unlikely to clash. std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> distribution; std::string rng_val = std::to_string(distribution(gen)); return tensorflow::io::JoinPath(std::string(test_dir), rng_val); } else { return ""; } } static std::string GetLocalLargeFile() { // This env is used when we want to test against a large file ( ~ 50MB ). // `S3_TEST_LOCAL_LARGE_FILE` and `S3_TEST_SERVER_LARGE_FILE` must be the same // file. static std::string path; if (path.empty()) { const char* env = getenv("S3_TEST_LOCAL_LARGE_FILE"); if (env == nullptr) return ""; path = env; } return path; } static std::string GetServerLargeFile() { // This env is used when we want to test against a large file ( ~ 50MB ). // `S3_TEST_LOCAL_LARGE_FILE` and `S3_TEST_SERVER_LARGE_FILE` must be the same // file. static std::string path; if (path.empty()) { const char* env = getenv("S3_TEST_SERVER_LARGE_FILE"); if (env == nullptr) return ""; Aws::String bucket, object; TF_Status* status = TF_NewStatus(); ParseS3Path(env, false, &bucket, &object, status); if (TF_GetCode(status) != TF_OK) { TF_DeleteStatus(status); return ""; } TF_DeleteStatus(status); path = env; } return path; } static std::string* GetTmpDir() { static std::string tmp_dir = InitializeTmpDir(); if (tmp_dir == "") return nullptr; else return &tmp_dir; } namespace tensorflow { namespace { class S3FilesystemTest : public ::testing::Test { public: void SetUp() override { root_dir_ = io::JoinPath( *GetTmpDir(), ::testing::UnitTest::GetInstance()->current_test_info()->name()); status_ = TF_NewStatus(); filesystem_ = new TF_Filesystem; tf_s3_filesystem::Init(filesystem_, status_); ASSERT_TF_OK(status_) << "Could not initialize filesystem. " << TF_Message(status_); } void TearDown() override { TF_DeleteStatus(status_); tf_s3_filesystem::Cleanup(filesystem_); delete filesystem_; } std::string GetURIForPath(const std::string& path) { const std::string translated_name = tensorflow::io::JoinPath(root_dir_, path); return translated_name; } std::unique_ptr<TF_WritableFile, void (*)(TF_WritableFile* file)> GetWriter() { std::unique_ptr<TF_WritableFile, void (*)(TF_WritableFile * file)> writer( new TF_WritableFile, [](TF_WritableFile* file) { if (file != nullptr) { if (file->plugin_file != nullptr) tf_writable_file::Cleanup(file); delete file; } }); writer->plugin_file = nullptr; return writer; } std::unique_ptr<TF_RandomAccessFile, void (*)(TF_RandomAccessFile* file)> GetReader() { std::unique_ptr<TF_RandomAccessFile, void (*)(TF_RandomAccessFile * file)> reader(new TF_RandomAccessFile, [](TF_RandomAccessFile* file) { if (file != nullptr) { if (file->plugin_file != nullptr) tf_random_access_file::Cleanup(file); delete file; } }); reader->plugin_file = nullptr; return reader; } void WriteString(const std::string& path, const std::string& content) { auto writer = GetWriter(); tf_s3_filesystem::NewWritableFile(filesystem_, path.c_str(), writer.get(), status_); if (TF_GetCode(status_) != TF_OK) return; tf_writable_file::Append(writer.get(), content.c_str(), content.length(), status_); if (TF_GetCode(status_) != TF_OK) return; tf_writable_file::Close(writer.get(), status_); if (TF_GetCode(status_) != TF_OK) return; } std::string ReadAll(const string& path) { auto reader = GetReader(); tf_s3_filesystem::NewRandomAccessFile(filesystem_, path.c_str(), reader.get(), status_); if (TF_GetCode(status_) != TF_OK) return ""; auto file_size = tf_s3_filesystem::GetFileSize(filesystem_, path.c_str(), status_); if (TF_GetCode(status_) != TF_OK) return ""; std::string content; content.resize(file_size); auto read = tf_random_access_file::Read(reader.get(), 0, file_size, &content[0], status_); if (TF_GetCode(status_) != TF_OK) return ""; if (read >= 0) content.resize(read); if (file_size != content.size()) TF_SetStatus( status_, TF_DATA_LOSS, std::string("expected " + std::to_string(file_size) + " got " + std::to_string(content.size()) + " bytes") .c_str()); return content; } std::string ReadAllInChunks(const string& path, size_t buffer_size, bool use_multi_part_download) { auto reader = GetReader(); auto s3_file = static_cast<tf_s3_filesystem::S3File*>(filesystem_->plugin_filesystem); s3_file->use_multi_part_download = use_multi_part_download; s3_file ->multi_part_chunk_sizes[Aws::Transfer::TransferDirection::DOWNLOAD] = buffer_size; tf_s3_filesystem::NewRandomAccessFile(filesystem_, path.c_str(), reader.get(), status_); if (TF_GetCode(status_) != TF_OK) return ""; auto file_size = tf_s3_filesystem::GetFileSize(filesystem_, path.c_str(), status_); if (TF_GetCode(status_) != TF_OK) return ""; std::size_t part_count = (std::max)( static_cast<size_t>((file_size + buffer_size - 1) / buffer_size), static_cast<size_t>(1)); std::unique_ptr<char[]> buffer{new char[buffer_size]}; std::stringstream ss; uint64_t offset = 0; uint64_t server_size = 0; for (size_t i = 0; i < part_count; i++) { offset = i * buffer_size; buffer_size = (i == part_count - 1) ? file_size - server_size : buffer_size; auto read = tf_random_access_file::Read(reader.get(), offset, buffer_size, buffer.get(), status_); if (TF_GetCode(status_) != TF_OK) return ""; if (read > 0) { ss.write(buffer.get(), read); server_size += static_cast<uint64_t>(read); } if (server_size == file_size) break; if (read != buffer_size) { if (read == 0) TF_SetStatus(status_, TF_OUT_OF_RANGE, "eof"); else TF_SetStatus( status_, TF_DATA_LOSS, ("truncated record at " + std::to_string(offset)).c_str()); return ""; } } if (file_size != server_size) { TF_SetStatus(status_, TF_DATA_LOSS, std::string("expected " + std::to_string(file_size) + " got " + std::to_string(server_size) + " bytes") .c_str()); return ""; } TF_SetStatus(status_, TF_OK, ""); return ss.str(); } protected: TF_Filesystem* filesystem_; TF_Status* status_; private: std::string root_dir_; }; TEST_F(S3FilesystemTest, NewRandomAccessFile) { const std::string path = GetURIForPath("RandomAccessFile"); const std::string content = "abcdefghijklmn"; WriteString(path, content); ASSERT_TF_OK(status_); auto reader = GetReader(); tf_s3_filesystem::NewRandomAccessFile(filesystem_, path.c_str(), reader.get(), status_); EXPECT_TF_OK(status_); std::string result; result.resize(content.size()); auto read = tf_random_access_file::Read(reader.get(), 0, content.size(), &result[0], status_); result.resize(read); EXPECT_TF_OK(status_); EXPECT_EQ(content.size(), result.size()); EXPECT_EQ(content, result); result.clear(); result.resize(4); read = tf_random_access_file::Read(reader.get(), 2, 4, &result[0], status_); result.resize(read); EXPECT_TF_OK(status_); EXPECT_EQ(4, result.size()); EXPECT_EQ(content.substr(2, 4), result); } TEST_F(S3FilesystemTest, NewWritableFile) { auto writer = GetWriter(); const std::string path = GetURIForPath("WritableFile"); tf_s3_filesystem::NewWritableFile(filesystem_, path.c_str(), writer.get(), status_); EXPECT_TF_OK(status_); tf_writable_file::Append(writer.get(), "content1,", strlen("content1,"), status_); EXPECT_TF_OK(status_); tf_writable_file::Append(writer.get(), "content2", strlen("content2"), status_); EXPECT_TF_OK(status_); tf_writable_file::Flush(writer.get(), status_); EXPECT_TF_OK(status_); tf_writable_file::Sync(writer.get(), status_); EXPECT_TF_OK(status_); tf_writable_file::Close(writer.get(), status_); EXPECT_TF_OK(status_); auto content = ReadAll(path); EXPECT_TF_OK(status_); EXPECT_EQ("content1,content2", content); } TEST_F(S3FilesystemTest, NewAppendableFile) { const std::string path = GetURIForPath("AppendableFile"); WriteString(path, "test"); ASSERT_TF_OK(status_); auto writer = GetWriter(); tf_s3_filesystem::NewAppendableFile(filesystem_, path.c_str(), writer.get(), status_); EXPECT_TF_OK(status_); tf_writable_file::Append(writer.get(), "content", strlen("content"), status_); EXPECT_TF_OK(status_); tf_writable_file::Close(writer.get(), status_); EXPECT_TF_OK(status_); } TEST_F(S3FilesystemTest, NewReadOnlyMemoryRegionFromFile) { const std::string path = GetURIForPath("MemoryFile"); const std::string content = "content"; WriteString(path, content); ASSERT_TF_OK(status_); std::unique_ptr<TF_ReadOnlyMemoryRegion, void (*)(TF_ReadOnlyMemoryRegion * file)> region(new TF_ReadOnlyMemoryRegion, [](TF_ReadOnlyMemoryRegion* file) { if (file != nullptr) { if (file->plugin_memory_region != nullptr) tf_read_only_memory_region::Cleanup(file); delete file; } }); region->plugin_memory_region = nullptr; tf_s3_filesystem::NewReadOnlyMemoryRegionFromFile(filesystem_, path.c_str(), region.get(), status_); EXPECT_TF_OK(status_); std::string result(reinterpret_cast<const char*>( tf_read_only_memory_region::Data(region.get())), tf_read_only_memory_region::Length(region.get())); EXPECT_EQ(content, result); } TEST_F(S3FilesystemTest, PathExists) { const std::string path = GetURIForPath("PathExists"); tf_s3_filesystem::PathExists(filesystem_, path.c_str(), status_); EXPECT_EQ(TF_NOT_FOUND, TF_GetCode(status_)) << TF_Message(status_); TF_SetStatus(status_, TF_OK, ""); WriteString(path, "test"); ASSERT_TF_OK(status_); tf_s3_filesystem::PathExists(filesystem_, path.c_str(), status_); EXPECT_TF_OK(status_); } TEST_F(S3FilesystemTest, GetChildren) { const std::string base = GetURIForPath("GetChildren"); tf_s3_filesystem::CreateDir(filesystem_, base.c_str(), status_); EXPECT_TF_OK(status_); const std::string file = io::JoinPath(base, "TestFile.csv"); WriteString(file, "test"); EXPECT_TF_OK(status_); const std::string subdir = io::JoinPath(base, "SubDir"); tf_s3_filesystem::CreateDir(filesystem_, subdir.c_str(), status_); EXPECT_TF_OK(status_); const std::string subfile = io::JoinPath(subdir, "TestSubFile.csv"); WriteString(subfile, "test"); EXPECT_TF_OK(status_); char** entries; auto num_entries = tf_s3_filesystem::GetChildren(filesystem_, base.c_str(), &entries, status_); EXPECT_TF_OK(status_); std::vector<std::string> childrens; for (int i = 0; i < num_entries; ++i) { childrens.push_back(entries[i]); } std::sort(childrens.begin(), childrens.end()); EXPECT_EQ(std::vector<string>({"SubDir", "TestFile.csv"}), childrens); } TEST_F(S3FilesystemTest, DeleteFile) { const std::string path = GetURIForPath("DeleteFile"); WriteString(path, "test"); ASSERT_TF_OK(status_); tf_s3_filesystem::DeleteFile(filesystem_, path.c_str(), status_); EXPECT_TF_OK(status_); } TEST_F(S3FilesystemTest, CreateDir) { // s3 object storage doesn't support empty directory, we create file in the // directory const std::string dir = GetURIForPath("CreateDir"); tf_s3_filesystem::CreateDir(filesystem_, dir.c_str(), status_); EXPECT_TF_OK(status_); const std::string file = io::JoinPath(dir, "CreateDirFile.csv"); WriteString(file, "test"); ASSERT_TF_OK(status_); TF_FileStatistics stat; tf_s3_filesystem::Stat(filesystem_, dir.c_str(), &stat, status_); EXPECT_TF_OK(status_); EXPECT_TRUE(stat.is_directory); } TEST_F(S3FilesystemTest, DeleteDir) { // s3 object storage doesn't support empty directory, we create file in the // directory const std::string dir = GetURIForPath("DeleteDir"); const std::string file = io::JoinPath(dir, "DeleteDirFile.csv"); WriteString(file, "test"); ASSERT_TF_OK(status_); tf_s3_filesystem::DeleteDir(filesystem_, dir.c_str(), status_); EXPECT_NE(TF_GetCode(status_), TF_OK); TF_SetStatus(status_, TF_OK, ""); tf_s3_filesystem::DeleteFile(filesystem_, file.c_str(), status_); EXPECT_TF_OK(status_); tf_s3_filesystem::DeleteDir(filesystem_, dir.c_str(), status_); EXPECT_TF_OK(status_); TF_FileStatistics stat; tf_s3_filesystem::Stat(filesystem_, dir.c_str(), &stat, status_); EXPECT_EQ(TF_GetCode(status_), TF_NOT_FOUND) << TF_Message(status_); } TEST_F(S3FilesystemTest, StatFile) { const std::string path = GetURIForPath("StatFile"); WriteString(path, "test"); ASSERT_TF_OK(status_); TF_FileStatistics stat; tf_s3_filesystem::Stat(filesystem_, path.c_str(), &stat, status_); EXPECT_TF_OK(status_); EXPECT_EQ(4, stat.length); EXPECT_FALSE(stat.is_directory); } // Test against large file. TEST_F(S3FilesystemTest, ReadLargeFile) { auto local_path = GetLocalLargeFile(); auto server_path = GetServerLargeFile(); if (local_path.empty() || server_path.empty()) GTEST_SKIP(); std::ifstream in(local_path, std::ios::binary); std::string local_content((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); constexpr size_t buffer_size = 50 * 1024 * 1024; auto server_content = ReadAllInChunks(server_path, buffer_size, true); ASSERT_TF_OK(status_); EXPECT_EQ(local_content, server_content); server_content = ReadAllInChunks(server_path, buffer_size, false); ASSERT_TF_OK(status_); EXPECT_EQ(local_content, server_content); } } // namespace } // namespace tensorflow GTEST_API_ int main(int argc, char** argv) { tensorflow::testing::InstallStacktraceHandler(); if (!GetTmpDir()) { std::cerr << "Could not read S3_TEST_TMPDIR env"; return -1; } ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
34.807611
80
0.65786
eee4017
4784d18bb6726d8bb62bc800653c711e433dedde
34
cpp
C++
libs/gfxtk_core/src/gfxtk/VertexBufferLayout.cpp
NostalgicGhoul/gfxtk
6662d6d1b285e20806ecfef3cdcb620d6605e478
[ "BSD-2-Clause" ]
null
null
null
libs/gfxtk_core/src/gfxtk/VertexBufferLayout.cpp
NostalgicGhoul/gfxtk
6662d6d1b285e20806ecfef3cdcb620d6605e478
[ "BSD-2-Clause" ]
null
null
null
libs/gfxtk_core/src/gfxtk/VertexBufferLayout.cpp
NostalgicGhoul/gfxtk
6662d6d1b285e20806ecfef3cdcb620d6605e478
[ "BSD-2-Clause" ]
null
null
null
#include "VertexBufferLayout.hpp"
17
33
0.823529
NostalgicGhoul
478a0527bdc45ef2cfa205d878d9237ab61ce245
1,554
cpp
C++
GodGame/GodGame/SDLEngine/Renderers/RendererOpenGL/TextureOpenGL.cpp
NeutralNoise/GodGame
454c94e361868ca169ca1d9268ad6737fa8e1741
[ "MIT" ]
null
null
null
GodGame/GodGame/SDLEngine/Renderers/RendererOpenGL/TextureOpenGL.cpp
NeutralNoise/GodGame
454c94e361868ca169ca1d9268ad6737fa8e1741
[ "MIT" ]
null
null
null
GodGame/GodGame/SDLEngine/Renderers/RendererOpenGL/TextureOpenGL.cpp
NeutralNoise/GodGame
454c94e361868ca169ca1d9268ad6737fa8e1741
[ "MIT" ]
null
null
null
#include "TextureOpenGL.h" #include <iostream> #include <GL/glew.h> //#include <SDL2/SDL.h> //#include <SDL2/SDL_image.h> #define STB_IMAGE_IMPLEMENTATION #include <STB/stb_image.h> #include "ErrorOpenGL.h" Texture * TextureOpenGL::LoadTexture(const std::string & path) { unsigned char* m_LocalBuffer; //stbi_set_flip_vertically_on_load(1); this->file = path; int m_BPP = 0; m_LocalBuffer = stbi_load(path.c_str(), &(this->width), &(this->height), &m_BPP, 4); if (m_BPP >= 4) this->format = GL_RGBA8; else this->format = GL_RGB; GLCall(glGenTextures(1, &m_textureID)); GLCall(glBindTexture(GL_TEXTURE_2D, m_textureID)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, this->width, this->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_LocalBuffer)); GLCall(glBindTexture(GL_TEXTURE_2D, 0)); //SDL_FreeSurface(this->textureData.textureSurface); return this; } void TextureOpenGL::Bind(const UInt32 & slot) { GLCall(glActiveTexture(GL_TEXTURE0 + slot)); GLCall(glBindTexture(GL_TEXTURE_2D, m_textureID)); } void TextureOpenGL::Unbind() { GLCall(glBindTexture(GL_TEXTURE_2D, 0)); } void TextureOpenGL::SetTexure(void * tex) { m_textureID = (UInt32)(tex); } void * TextureOpenGL::GetTexure() { return (void *)m_textureID; }
25.9
122
0.756113
NeutralNoise
478a2e65b1f8dc81c23d45027f87a26a5e7ac065
832
cc
C++
deprected/src/util/point.cc
RobertWeber1/cli
5cb67325610be41014403e9342dddbe942511c2b
[ "MIT" ]
null
null
null
deprected/src/util/point.cc
RobertWeber1/cli
5cb67325610be41014403e9342dddbe942511c2b
[ "MIT" ]
null
null
null
deprected/src/util/point.cc
RobertWeber1/cli
5cb67325610be41014403e9342dddbe942511c2b
[ "MIT" ]
null
null
null
#include "point.h" namespace CLI { namespace util { Point::Point( unsigned int x, unsigned int y ) : _x(x) , _y(y) {} Point::Point( Point const& point ) : _x( point.x() ) , _y( point.y() ) {} unsigned int Point::x() const { return _x; } unsigned int Point::y() const { return _y; } void Point::x( unsigned int new_x ) { _x = new_x; } void Point::y( unsigned int new_y ) { _y = new_y; } void Point::left( unsigned int x_offset ) { _x -= x_offset ; } void Point::right( unsigned int x_offset ) { _x += x_offset ; } void Point::up( unsigned int y_offset ) { _y -= y_offset ; } void Point::down( unsigned int y_offset ) { _y += y_offset ; } void Point::break_line() { _x = 0; _y++; } void Point::set( unsigned int new_x, unsigned int new_y ) { _x = new_x; _y = new_y; } } //namespace util } //namespace CLI
11.093333
57
0.623798
RobertWeber1
478bcdd1b72fef6c2dac52463c6c7beaddcb9f7d
1,804
cpp
C++
rel-lib/src/Logger.cpp
sscit/rel
d9e6815012334dfc4c99b8020ae42a9ca9860458
[ "MIT" ]
2
2020-12-26T20:18:46.000Z
2021-05-01T03:55:22.000Z
rel-lib/src/Logger.cpp
sscit/rel
d9e6815012334dfc4c99b8020ae42a9ca9860458
[ "MIT" ]
2
2021-01-04T00:01:51.000Z
2021-04-07T18:25:10.000Z
rel-lib/src/Logger.cpp
sscit/rel
d9e6815012334dfc4c99b8020ae42a9ca9860458
[ "MIT" ]
2
2021-01-03T00:32:20.000Z
2021-01-04T01:06:18.000Z
/* SPDX-License-Identifier: MIT */ /* Copyright (c) 2020-present Stefan Schlichthärle */ #include "Logger.h" Logger::Logger() : current_loglevel(LogLevel::WARNING) {} Logger::Logger(std::string const filename) : Logger() { file_access.open(filename); } Logger::~Logger() { if (file_access.is_open()) file_access.close(); } void Logger::SetLogLevel(LogLevel const l) { current_loglevel = l; } LogLevel Logger::GetCurrentLogLevel() const { return current_loglevel; } std::string Logger::LogLevelToString(LogLevel const l) const { std::string result; switch (l) { case LogLevel::DBUG: result = "DBUG"; break; case LogLevel::INFO: result = "INFO"; break; case LogLevel::WARNING: result = "WARNING"; break; case LogLevel::ERROR: result = "ERROR"; break; default: result = "UNKNOWN_LOGLEVEL"; } return result; } void Logger::LogMessage(LogLevel const loglevel, std::string const message, std::string const filename = "Unset", int const line_number = -1) { std::lock_guard<std::mutex> db_lock(mtx); if (loglevel <= GetCurrentLogLevel()) { if (file_access.is_open()) { file_access << LogLevelToString(loglevel) << ": " << "File " << filename << ", Line " << line_number << ": "; file_access << message << std::endl; file_access.flush(); } else { std::cout << LogLevelToString(loglevel) << ": " << "File " << filename << ", Line " << line_number << ": "; std::cout << message << std::endl; } } }
29.57377
75
0.533259
sscit
478dafe437dee50cd92e62e59ca5f1548d108f24
6,832
hpp
C++
src/ns.hpp
MilesLitteral/mtlpp
0915732f9bb958bea476c19b2d9de3637d857c92
[ "MIT" ]
1
2022-01-11T05:44:44.000Z
2022-01-11T05:44:44.000Z
src/ns.hpp
MilesLitteral/mtlpp
0915732f9bb958bea476c19b2d9de3637d857c92
[ "MIT" ]
null
null
null
src/ns.hpp
MilesLitteral/mtlpp
0915732f9bb958bea476c19b2d9de3637d857c92
[ "MIT" ]
null
null
null
/* * Copyright 2016-2017 Nikolay Aleksiev. All rights reserved. * License: https://github.com/naleksiev/mtlpp/blob/master/LICENSE */ #pragma once #include "defines.hpp" namespace ns { struct Handle { const void* ptr; }; class Object { public: inline const void* GetPtr() const { return m_ptr; } inline operator bool() const { return m_ptr != nullptr; } protected: Object(); Object(const Handle& handle); Object(const Object& rhs); #if MTLPP_CONFIG_RVALUE_REFERENCES Object(Object&& rhs); #endif virtual ~Object(); Object& operator=(const Object& rhs); #if MTLPP_CONFIG_RVALUE_REFERENCES Object& operator=(Object&& rhs); #endif inline void Validate() const { #if MTLPP_CONFIG_VALIDATE assert(m_ptr); #endif } const void* m_ptr = nullptr; }; struct Range { inline Range(uint32_t location, uint32_t length) : Location(location), Length(length) { } uint32_t Location; uint32_t Length; }; class ArrayBase : public Object { public: ArrayBase() { } ArrayBase(const Handle& handle) : Object(handle) { } uint32_t GetSize() const; protected: void* GetItem(uint32_t index) const; }; template<typename T> class Array : public ArrayBase { public: Array() { } Array(const Handle& handle) : ArrayBase(handle) { } const T operator[](uint32_t index) const { return Handle{ GetItem(index) }; } T operator[](uint32_t index) { return Handle{ GetItem(index) }; } }; class DictionaryBase : public Object { public: DictionaryBase() { } DictionaryBase(const Handle& handle) : Object(handle) { } protected: }; template<typename KeyT, typename ValueT> class Dictionary : public DictionaryBase { public: Dictionary() { } Dictionary(const Handle& handle) : DictionaryBase(handle) { } }; class String : public Object { public: String() { } String(const Handle& handle) : Object(handle) { } String(const char* cstr); const char* GetCStr() const; uint32_t GetLength() const; }; class Error : public Object { public: Error(); Error(const Handle& handle) : Object(handle) { } String GetDomain() const; uint32_t GetCode() const; //@property (readonly, copy) NSDictionary *userInfo; String GetLocalizedDescription() const; String GetLocalizedFailureReason() const; String GetLocalizedRecoverySuggestion() const; String GetLocalizedRecoveryOptions() const; //@property (nullable, readonly, strong) id recoveryAttempter; String GetHelpAnchor() const; }; class URL : public Object { public: URL(); URL(const String* pString); URL(const String* pPath); const char* fileSystemRepresentation() const; }; class Bundle : public Object { // private: // _NS_CONST(NotificationName, BundleDidLoadNotification); // _NS_CONST(NotificationName, BundleResourceRequestLowDiskSpaceNotification); public: static Bundle* mainBundle(); Bundle(const class String* pPath); Bundle(const class URL* pURL); Bundle(const ns::Handle& handle) : ns::Object(handle) { } Bundle* init(const class String* pPath); Bundle* init(const class URL* pURL); Array<Bundle>* allBundles() const; //Array* allFrameworks() const; //revisit bool load(); bool unload(); bool isLoaded() const; bool preflightAndReturnError(class Error** pError) const; bool loadAndReturnError(class Error** pError); class URL* bundleURL() const; class URL* resourceURL() const; class URL* executableURL() const; class URL* URLForAuxiliaryExecutable(const class String* pExecutableName) const; class URL* privateFrameworksURL() const; class URL* sharedFrameworksURL() const; class URL* sharedSupportURL() const; class URL* builtInPlugInsURL() const; class URL* appStoreReceiptURL() const; class String* bundlePath() const; class String* resourcePath() const; class String* executablePath() const; class String* pathForAuxiliaryExecutable(const class String* pExecutableName) const; class String* privateFrameworksPath() const; class String* sharedFrameworksPath() const; class String* sharedSupportPath() const; class String* builtInPlugInsPath() const; class String* bundleIdentifier() const; class Dictionary* infoDictionary() const; class Dictionary* localizedInfoDictionary() const; class Object* objectForInfoDictionaryKey(const String* pKey); class String* localizedString(const String* pKey, const String* pValue = nullptr, const String* pTableName = nullptr) const; class String* LocalizedString(const String* pKey, const String*); class String* LocalizedStringFromTable(const String* pKey, const String* pTbl, const String*); class String* LocalizedStringFromTableInBundle(const String* pKey, const String* pTbl, const Bundle* pBdle, const String*); class String* LocalizedStringWithDefaultValue(const String* pKey, const String* pTbl, const Bundle* pBdle, const String* pVal, const String*); }; class Data : public Object { public: void* SetMutableBytes(); uint64_t GetLength(); }; } }
32.075117
158
0.525907
MilesLitteral
47a1a30bd4acc32ed3f845e767fda1a52c1cca1f
3,748
cpp
C++
modules/task_3/kulemin_p_linear_vertical_filtration/main.cpp
Stepakrap/pp_2021_autumn
716803a14183172337d51712fb28fe8e86891a3d
[ "BSD-3-Clause" ]
1
2021-12-09T17:20:25.000Z
2021-12-09T17:20:25.000Z
modules/task_3/kulemin_p_linear_vertical_filtration/main.cpp
Stepakrap/pp_2021_autumn
716803a14183172337d51712fb28fe8e86891a3d
[ "BSD-3-Clause" ]
null
null
null
modules/task_3/kulemin_p_linear_vertical_filtration/main.cpp
Stepakrap/pp_2021_autumn
716803a14183172337d51712fb28fe8e86891a3d
[ "BSD-3-Clause" ]
3
2022-02-23T14:20:50.000Z
2022-03-30T09:00:02.000Z
// Copyright 2021 Zaytsev Mikhail #include <gtest/gtest.h> #include <vector> #include "./linear_vectrical_filtration.h" #include <gtest-mpi-listener.hpp> TEST(Parallel_Matrix_Multiplacition, mRows_Eq_mColumns_50) { int currentProcess; MPI_Comm_rank(MPI_COMM_WORLD, &currentProcess); std::vector<float> matrix, img; int height = 50; int weight = 50; getKernell(&matrix); if (currentProcess == 0) { getRandomImg(&img, weight, height); } std::vector<float> globalMatrix = getParallelOperations(matrix, img, weight, height); if (currentProcess == 0) { std::vector<float> referenceMatrix = getSequentialOperations(matrix, img, weight, height); ASSERT_EQ(globalMatrix, referenceMatrix); } } TEST(Parallel_Matrix_Multiplacition, mRows_Eq_mColumns_5) { int currentProcess; MPI_Comm_rank(MPI_COMM_WORLD, &currentProcess); std::vector<float> matrix, img; int height = 5; int weight = 5; getKernell(&matrix); if (currentProcess == 0) { getRandomImg(&img, weight, height); } std::vector<float> globalMatrix = getParallelOperations(matrix, img, weight, height); if (currentProcess == 0) { std::vector<float> referenceMatrix = getSequentialOperations(matrix, img, weight, height); ASSERT_EQ(globalMatrix, referenceMatrix); } } TEST(Parallel_Matrix_Multiplacition, mRows_Eq_mColumns_211) { int currentProcess; MPI_Comm_rank(MPI_COMM_WORLD, &currentProcess); std::vector<float> matrix, img; int height = 211; int weight = 211; getKernell(&matrix); if (currentProcess == 0) { getRandomImg(&img, weight, height); } std::vector<float> globalMatrix = getParallelOperations(matrix, img, weight, height); if (currentProcess == 0) { std::vector<float> referenceMatrix = getSequentialOperations(matrix, img, weight, height); ASSERT_EQ(globalMatrix, referenceMatrix); } } TEST(Parallel_Matrix_Multiplacition, mRows_Gr_mColumns_150_100) { int currentProcess; MPI_Comm_rank(MPI_COMM_WORLD, &currentProcess); std::vector<float> matrix, img; int height = 150; int weight = 100; getKernell(&matrix); if (currentProcess == 0) { getRandomImg(&img, weight, height); } std::vector<float> globalMatrix = getParallelOperations(matrix, img, weight, height); if (currentProcess == 0) { std::vector<float> referenceMatrix = getSequentialOperations(matrix, img, weight, height); ASSERT_EQ(globalMatrix, referenceMatrix); } } TEST(Parallel_Matrix_Multiplacition, mRows_Le_mColumns_100_150) { int currentProcess; MPI_Comm_rank(MPI_COMM_WORLD, &currentProcess); std::vector<float> matrix, img; int height = 100; int weight = 150; getKernell(&matrix); if (currentProcess == 0) { getRandomImg(&img, weight, height); } std::vector<float> globalMatrix = getParallelOperations(matrix, img, weight, height); if (currentProcess == 0) { std::vector<float> referenceMatrix = getSequentialOperations(matrix, img, weight, height); ASSERT_EQ(globalMatrix, referenceMatrix); } } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); MPI_Init(&argc, &argv); ::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment); ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Release(listeners.default_result_printer()); listeners.Release(listeners.default_xml_generator()); listeners.Append(new GTestMPIListener::MPIMinimalistPrinter); return RUN_ALL_TESTS(); }
28.610687
78
0.68143
Stepakrap
47a1e56747c70b5c2eee49c012072302a80a848f
2,670
cpp
C++
synthts_et/lib/fsc/fsdata.cpp
martnoumees/synthts_et
8845b33514edef3e54ae0b45404615704c418142
[ "Unlicense" ]
19
2015-10-27T22:21:49.000Z
2022-02-07T11:54:35.000Z
synthts_vr/lib/fsc/fsdata.cpp
ikiissel/synthts_vr
33f2686dc9606aa95697ac0cf7e9031668bc34e8
[ "Unlicense" ]
8
2015-10-28T08:38:08.000Z
2021-03-25T21:26:59.000Z
synthts_vr/lib/fsc/fsdata.cpp
ikiissel/synthts_vr
33f2686dc9606aa95697ac0cf7e9031668bc34e8
[ "Unlicense" ]
11
2016-01-03T11:47:08.000Z
2021-03-17T18:59:54.000Z
#include "stdfsc.h" #include "fstype.h" #include "fsdata.h" #include "fstrace.h" #include "fsmemory.h" #include "fsutil.h" #define __FSDATAMAXOVERHEAD (50*1024) // 50K ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CFSData::CFSData() { m_pData=0; m_ipSize=m_ipBufferSize=0; } CFSData::CFSData(const CFSData &Data) { m_pData=0; m_ipSize=m_ipBufferSize=0; operator =(Data); } #if defined (__FSCXX0X) CFSData::CFSData(CFSData &&Data) { m_pData=Data.m_pData; Data.m_pData=0; m_ipSize=Data.m_ipSize; Data.m_ipSize=0; m_ipBufferSize=Data.m_ipBufferSize; Data.m_ipBufferSize=0; } #endif CFSData::~CFSData() { Cleanup(); } CFSData &CFSData::operator =(const CFSData &Data) { if (m_pData!=Data.m_pData) { SetSize(Data.GetSize()); memcpy(m_pData, Data.m_pData, Data.GetSize()); } return *this; } #if defined (__FSCXX0X) CFSData &CFSData::operator =(CFSData &&Data) { if (m_pData!=Data.m_pData) { Cleanup(); m_pData=Data.m_pData; Data.m_pData=0; m_ipSize=Data.m_ipSize; Data.m_ipSize=0; m_ipBufferSize=Data.m_ipBufferSize; Data.m_ipBufferSize=0; } return *this; } #endif void CFSData::Reserve(INTPTR ipSize) { ASSERT(ipSize>=0); if (ipSize>m_ipBufferSize) { m_ipBufferSize=ipSize; m_pData=FSReAlloc(m_pData, m_ipBufferSize); } } void CFSData::SetSize(INTPTR ipSize, bool bReserveMore){ ASSERT(ipSize>=0); m_ipSize=FSMAX(ipSize, 0); if (m_ipSize>m_ipBufferSize) { Reserve(bReserveMore ? FSMIN(m_ipSize+__FSDATAMAXOVERHEAD, (INTPTR)(1.2*m_ipSize)+20) : m_ipSize); } } void CFSData::FreeExtra(){ if (m_ipBufferSize>m_ipSize) { m_ipBufferSize=m_ipSize; m_pData=FSReAlloc(m_pData, m_ipBufferSize); } } void CFSData::Cleanup() { if (m_pData) { FSFree(m_pData); } m_pData=0; m_ipSize=m_ipBufferSize=0; } void CFSData::Append(const void *pData, INTPTR ipSize) { ASSERT(ipSize>=0); ipSize=FSMAX(ipSize, 0); INTPTR ipOldSize=m_ipSize; SetSize(m_ipSize+ipSize); memcpy((BYTE *)m_pData+ipOldSize, pData, ipSize); } CFSStream &operator<<(CFSStream &Stream, const CFSData &Data) { Stream << (UINTPTR)Data.m_ipSize; Stream.WriteBuf(Data.m_pData, Data.m_ipSize); return Stream; } CFSStream &operator>>(CFSStream &Stream, CFSData &Data) { INTPTR ipSize; Stream >> (UINTPTR &)ipSize; if (ipSize<0) { throw CFSFileException(CFSFileException::INVALIDDATA); } Data.SetSize(ipSize, false); Stream.ReadBuf(Data.m_pData, Data.m_ipSize); return Stream; }
20.697674
101
0.646816
martnoumees
47a81afe6e0e20ccda4eeeec15d1792aed98e01a
490
hh
C++
libqpdf/qpdf/InsecureRandomDataProvider.hh
m-holger/qpdf
f1a9ba0c622deee0ed05004949b34f0126b12b6a
[ "Apache-2.0" ]
null
null
null
libqpdf/qpdf/InsecureRandomDataProvider.hh
m-holger/qpdf
f1a9ba0c622deee0ed05004949b34f0126b12b6a
[ "Apache-2.0" ]
3
2021-11-19T15:59:21.000Z
2021-12-10T20:44:33.000Z
libqpdf/qpdf/InsecureRandomDataProvider.hh
m-holger/qpdf
f1a9ba0c622deee0ed05004949b34f0126b12b6a
[ "Apache-2.0" ]
null
null
null
#ifndef INSECURERANDOMDATAPROVIDER_HH #define INSECURERANDOMDATAPROVIDER_HH #include <qpdf/RandomDataProvider.hh> class InsecureRandomDataProvider: public RandomDataProvider { public: InsecureRandomDataProvider(); virtual ~InsecureRandomDataProvider() = default; virtual void provideRandomData(unsigned char* data, size_t len); static RandomDataProvider* getInstance(); private: long random(); bool seeded_random; }; #endif // INSECURERANDOMDATAPROVIDER_HH
23.333333
68
0.783673
m-holger
47a9f49ecfd31535be660f54e9576575e7329bb5
1,687
cpp
C++
aech/src/ecs/engine.cpp
markomijolovic/aech
6e2ea36146596dff6f92e451a598aab535b03d3c
[ "BSD-3-Clause" ]
4
2021-05-25T13:58:30.000Z
2021-05-26T20:13:15.000Z
aech/src/ecs/engine.cpp
markomijolovic/aech
6e2ea36146596dff6f92e451a598aab535b03d3c
[ "BSD-3-Clause" ]
null
null
null
aech/src/ecs/engine.cpp
markomijolovic/aech
6e2ea36146596dff6f92e451a598aab535b03d3c
[ "BSD-3-Clause" ]
null
null
null
#include "engine.hpp" #include "camera.hpp" #include "directional_light.hpp" #include "light_probe.hpp" #include "mesh_filter.hpp" #include "point_light.hpp" #include "reflection_probe.hpp" #include "scene_node.hpp" #include "shading_tags.hpp" #include "shadow_caster.hpp" namespace aech { engine_t::engine_t() noexcept { register_component<transform_t>(); register_component<graphics::scene_node_t>(); register_component<camera_t>(); register_component<graphics::mesh_filter_t>(); register_component<graphics::directional_light_t>(); register_component<graphics::point_light_t>(); register_component<graphics::potential_occluder_t>(); register_component<graphics::opaque_t>(); register_component<graphics::transparent_t>(); register_component<graphics::reflection_probe_t>(); register_component<graphics::light_probe_t>(); } auto engine_t::create_entity() noexcept -> entity_t { return m_entity_manager.create_entity(); } auto engine_t::destroy_entity(entity_t entity) noexcept -> void { m_entity_manager.destroy_entity(entity); m_component_manager.entity_destroyed(entity); m_system_manager.entity_destroyed(entity); } auto engine_t::set_root_node(entity_t root_node) noexcept -> void { m_root_node = root_node; } auto engine_t::root_node() const noexcept -> entity_t { return m_root_node; } auto engine_t::add_event_listener(event_id_t event_id, const std::function<void(events::event_t &)> &listener) noexcept -> void { m_event_manager.add_listener(event_id, listener); } auto engine_t::send_event(events::event_t &event) noexcept -> void { m_event_manager.send_event(event); } } // namespace aech
27.209677
127
0.760522
markomijolovic
47b15c2740bd5087d10242354a76aab58a878d86
566
cpp
C++
riscv/llvm/3.5/cfe-3.5.0.src/test/Modules/macro-reexport/macro-reexport.cpp
tangyibin/goblin-core
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
[ "BSD-3-Clause" ]
null
null
null
riscv/llvm/3.5/cfe-3.5.0.src/test/Modules/macro-reexport/macro-reexport.cpp
tangyibin/goblin-core
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
[ "BSD-3-Clause" ]
null
null
null
riscv/llvm/3.5/cfe-3.5.0.src/test/Modules/macro-reexport/macro-reexport.cpp
tangyibin/goblin-core
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
[ "BSD-3-Clause" ]
1
2021-03-24T06:40:32.000Z
2021-03-24T06:40:32.000Z
// RUN: rm -rf %t // RUN: %clang_cc1 -fsyntax-only -DD2 -I. %s -fmodules-cache-path=%t -verify // RUN: %clang_cc1 -fsyntax-only -DD2 -I. -fmodules %s -fmodules-cache-path=%t -verify // RUN: %clang_cc1 -fsyntax-only -DC1 -I. %s -fmodules-cache-path=%t -verify // RUN: %clang_cc1 -fsyntax-only -DC1 -I. -fmodules %s -fmodules-cache-path=%t -verify #ifdef D2 #include "d2.h" void f() { return assert(true); } // expected-error {{undeclared identifier 'b'}} #else #include "c1.h" void f() { return assert(true); } // expected-error {{undeclared identifier 'c'}} #endif
40.428571
86
0.667845
tangyibin
47b3777228507d8e607d053d1b53f147fad2659b
2,420
cpp
C++
src/KRAverager.cpp
AFriemann/LowCarb
073e036a5fd6787943c4cbd76ab388dbd830e7d3
[ "MIT" ]
null
null
null
src/KRAverager.cpp
AFriemann/LowCarb
073e036a5fd6787943c4cbd76ab388dbd830e7d3
[ "MIT" ]
1
2018-12-15T13:57:26.000Z
2018-12-15T13:57:26.000Z
src/KRAverager.cpp
AFriemann/LowCarb
073e036a5fd6787943c4cbd76ab388dbd830e7d3
[ "MIT" ]
null
null
null
/** * @file KRAverager.cpp * @author see AUTHORS * @brief KRAverager definitions file. */ #include "KRAverager.hpp" KRAverager::KRAverager() {} KRAverager::KRAverager(int threshold){ this->threshold = threshold; this->use_threshold = true; } void KRAverager::add_force_constant_tuple(const double force_constant, const double range){ if (!(this->use_threshold) || range > this->threshold){ this->k_sum += force_constant; this->r_sum += range; this->error_sum += force_constant * force_constant; this->count += 1; } } void KRAverager::add_force_constant_vector(const Eigen::VectorXd &force_constants, const Eigen::VectorXd &ranges) { for (int i = 0; i < force_constants.rows(); ++i) { add_force_constant_tuple(force_constants(i), ranges(i)); } } double KRAverager::get_average_range() const { if (this->count > 0){ return this->r_sum / this->count; } else { return 0; } } double KRAverager::get_average_force_constant() const { if (this->count > 0) { return this->k_sum / this->count; } else { return 0; } } double KRAverager::get_error_1() const { return sqrt(get_error_2()); } double KRAverager::get_error_2() const { if (this->count > 0) { return ( (this->error_sum / this->count) - get_average_force_constant() * get_average_force_constant() ) / (this->count); } else { return 0; } } void KRAveragerCis::add_force_constant_tuple(double k, double r) { if (r > this->threshold) { this->count += 1; this->k_sum += k; this->r_sum += r; this->error_sum += k * k; } else { this->cis_count += 1; this->k_cis_sum += k; this->r_cis_sum += r; } } void KRAveragerCis::add_force_constant_vector(const Eigen::VectorXd & ks, const Eigen::VectorXd & rs) { for (int i = 0; i < ks.rows(); ++i) { add_force_constant_tuple(ks(i), rs(i)); } } double KRAveragerCis::get_range_cis() const { if (this->cis_count > 0) { return this->r_cis_sum / this->cis_count; } else { return 0; } } double KRAveragerCis::get_force_constant_cis() const { if (this->cis_count > 0) { return this->k_cis_sum / this->cis_count; } else { return 0; } } // vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
24.444444
115
0.604959
AFriemann
47b4e05940ac5f24462ab393bb1a8a52609d693f
6,663
cc
C++
board.cc
juliusikkala/Pack-Against-The-Machine
74fdf36ea7e9f0369e5b4a101f5e5aa43817c8ff
[ "MIT" ]
null
null
null
board.cc
juliusikkala/Pack-Against-The-Machine
74fdf36ea7e9f0369e5b4a101f5e5aa43817c8ff
[ "MIT" ]
null
null
null
board.cc
juliusikkala/Pack-Against-The-Machine
74fdf36ea7e9f0369e5b4a101f5e5aa43817c8ff
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2019 Julius Ikkala 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 "board.hh" #include <cmath> #include <algorithm> #include <stdexcept> #include "rect_packer.hh" namespace { int range_overlap(int x1, int w1, int x2, int w2) { return std::max(std::min(x1 + w1, x2 + w2) - std::max(x1, x2), 0); } int rect_overlap(const board::rect& a, const board::rect& b) { return range_overlap(a.x, a.w, b.x, b.w) * range_overlap(a.y, a.h, b.y, b.h); } unsigned hsv_to_rgb(float h, float s, float v) { auto f = [h,s,v](int n){ float k = fmod(n+h/60.0, 6.0); return v - v*s*std::clamp(std::min(k, 4-k), 0.0f, 1.0f); }; unsigned r = std::clamp(int(f(5)*255.0f), 0, 255); unsigned g = std::clamp(int(f(3)*255.0f), 0, 255); unsigned b = std::clamp(int(f(1)*255.0f), 0, 255); return (r<<24)|(g<<16)|(b<<8)|0xFF; } float circle_sequence(unsigned n) { unsigned denom = n + 1; denom--; denom |= denom >> 1; denom |= denom >> 2; denom |= denom >> 4; denom |= denom >> 8; denom |= denom >> 16; denom++; unsigned num = 1 + (n - denom/2)*2; return num/(float)denom; } unsigned generate_color(int id, bool bounds) { return hsv_to_rgb( 360*circle_sequence(id), 0.5, bounds ? 0.7 : 1.0 ); } } board::board(int w, int h) : width(w), height(h), covered(0) { } void board::resize(int w, int h) { width = w; height = h; } void board::reset() { rects.clear(); covered = 0; } void board::place(const rect& r) { rects.push_back(r); covered += r.w * r.h; } bool board::can_place(const rect& r) const { // Check bounds if(r.x < 0 || r.y < 0 || r.x + r.w > width || r.y + r.h > height) return false; // Check other rects for(const rect& o: rects) { if(rect_overlap(o, r)) return false; } return true; } double board::coverage() const { return covered/(double)(width * height); } void board::draw( sf::RenderWindow& win, int x, int y, int w, int h, bool draw_grid, sf::Font* number_font ) const { // Draw bounds sf::Color bounds_color(0x3C3C3CFF); sf::Color background_color(0x303030FF); sf::Vertex bounds[] = { sf::Vertex(sf::Vector2f(x, y)), sf::Vertex(sf::Vector2f(x+w, y)), sf::Vertex(sf::Vector2f(x+w, y+h)), sf::Vertex(sf::Vector2f(x, y+h)), sf::Vertex(sf::Vector2f(x, y)) }; for(sf::Vertex& v: bounds) v.color = background_color; win.draw(bounds, 4, sf::Quads); for(sf::Vertex& v: bounds) v.color = bounds_color; win.draw(bounds, 5, sf::LineStrip); // Draw grid if asked to if(draw_grid) { for(int gy = 1; gy < height; ++gy) { int sy = y + gy * h / height; sf::Vertex grid_line[] = { sf::Vertex(sf::Vector2f(x, sy), bounds_color), sf::Vertex(sf::Vector2f(x + w, sy), bounds_color), }; win.draw(grid_line, 2, sf::Lines); } for(int gx = 1; gx < width; ++gx) { int sx = x + gx * w / width; sf::Vertex grid_line[] = { sf::Vertex(sf::Vector2f(sx, y), bounds_color), sf::Vertex(sf::Vector2f(sx, y + h), bounds_color), }; win.draw(grid_line, 2, sf::Lines); } } // Draw rects float outline_thickness = w/(float)width*0.2f; if(outline_thickness < 3.0f) outline_thickness = 0.0f; float font_size = std::max(w/(float)width*0.5f, 8.0f); for(const rect& r: rects) { sf::Color color(generate_color(r.id, false)); sf::Color outline_color(generate_color(r.id, true)); int fy = height-r.y; int sx1 = x + r.x * w / width; int sy1 = y + fy * h / height+(draw_grid ? 1 : 0); int sx2 = x + (r.x+r.w) * w / width-(draw_grid ? 1 : 0); int sy2 = y + (fy-r.h) * h / height; int sw = sx2-sx1; int sh = sy2-sy1; sf::RectangleShape rs(sf::Vector2f(sw, sh)); rs.setPosition(sx1, sy1); rs.setOutlineThickness(-outline_thickness); rs.setFillColor(color); rs.setOutlineColor(outline_color); win.draw(rs); if(number_font) { sf::Text number(std::to_string(r.id), *number_font, font_size); number.setOutlineColor(sf::Color::Black); number.setFillColor(sf::Color::White); number.setOutlineThickness(font_size*0.1f); number.setPosition(sf::Vector2f(sx1+sx2, sy1+sy2)*0.5f); sf::FloatRect lb = number.getLocalBounds(); number.setOrigin(lb.left + lb.width*0.5f, lb.top + lb.height*0.5f); win.draw(number); } } } /* void board::draw_debug_edges( sf::RenderWindow& win, rect_packer& pack, int x, int y, int w, int h ) const { // Draw bounds sf::Color ur_color(0x00FF00FF); sf::Color bu_color(0xFF0000FF); for(auto& edge: pack.edges) { sf::Color col = edge.up_right_inside ? ur_color : bu_color; int x1 = edge.x; int y1 = edge.y; int x2 = edge.vertical ? edge.x : edge.x + edge.length; int y2 = edge.vertical ? edge.y + edge.length : edge.y; y1 = height - y1; y2 = height - y2; x1 = x + x1 * w / width; y1 = y + y1 * h / height; x2 = x + x2 * w / width; y2 = y + y2 * h / height; sf::Vertex grid_line[] = { sf::Vertex(sf::Vector2f(x1, y1), col), sf::Vertex(sf::Vector2f(x2, y2), col), }; win.draw(grid_line, 2, sf::Lines); } } */
27.419753
79
0.579169
juliusikkala
47b518b1abc4f1f490c66a367ee50db7426244af
2,783
cpp
C++
Immortal/Platform/D3D12/GuiLayer.cpp
QSXW/Immortal
32adcc8609b318752dd97f1c14dc7368b47d47d1
[ "Apache-2.0" ]
6
2021-09-15T08:56:28.000Z
2022-03-29T15:55:02.000Z
Immortal/Platform/D3D12/GuiLayer.cpp
DaShi-Git/Immortal
e3345b4ff2a2b9d215c682db2b4530e24cc3b203
[ "Apache-2.0" ]
null
null
null
Immortal/Platform/D3D12/GuiLayer.cpp
DaShi-Git/Immortal
e3345b4ff2a2b9d215c682db2b4530e24cc3b203
[ "Apache-2.0" ]
4
2021-12-05T17:28:57.000Z
2022-03-29T15:55:05.000Z
#include "impch.h" #include "GuiLayer.h" #ifndef _UNICODE #define _UNICODE #endif #include <backends/imgui_impl_win32.h> #include <backends/imgui_impl_dx12.cpp> #include <backends/imgui_impl_glfw.h> #include <GLFW/glfw3.h> #include "Render/Render.h" #include "Barrier.h" #include "Event/ApplicationEvent.h" namespace Immortal { namespace D3D12 { GuiLayer::GuiLayer(SuperRenderContext *superContext) : context{ dcast<RenderContext*>(superContext)} { swapchain = context->GetAddress<Swapchain>(); commandList = context->GetAddress<CommandList>(); queue = context->GetAddress<Queue>(); } void GuiLayer::OnAttach() { Super::OnAttach(); auto &io = ImGui::GetIO(); Vector2 extent = context->Extent(); io.DisplaySize = ImVec2{ extent.x, extent.y }; auto window = context->GetAddress<Window>(); ImGui_ImplWin32_Init(rcast<HWND>(window->Primitive())); srvDescriptorHeap = context->ShaderResourceViewDescritorHeap(); Descriptor descriptor = context->AllocateShaderVisibleDescriptor(); ImGui_ImplDX12_Init( *context->GetAddress<Device>(), context->FrameSize(), context->Get<DXGI_FORMAT>(), *srvDescriptorHeap, descriptor.cpu, descriptor.gpu ); } void GuiLayer::Begin() { ImGui_ImplDX12_NewFrame(); ImGui_ImplWin32_NewFrame(); Super::Begin(); } void GuiLayer::OnEvent(Event &e) { if (e.GetType() == Event::Type::WindowResize) { auto resize = dcast<WindowResizeEvent *>(&e); ImGuiIO &io = ImGui::GetIO(); io.DisplaySize = ImVec2{ (float)resize->Width(), (float)resize->Height() }; } Super::OnEvent(e); } void GuiLayer::OnGuiRender() { Super::OnGuiRender(); } void GuiLayer::End() { Super::End(); UINT backBufferIdx = Render::CurrentPresentedFrameIndex(); Barrier<BarrierType::Transition> barrier{ context->RenderTarget(backBufferIdx), D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET }; commandList->ResourceBarrier(&barrier); CPUDescriptor rtvDescritor = std::move(context->RenderTargetDescriptor(backBufferIdx)); commandList->ClearRenderTargetView(rtvDescritor, rcast<float *>(&clearColor)); commandList->OMSetRenderTargets(&rtvDescritor, 1, false, nullptr); commandList->SetDescriptorHeaps(srvDescriptorHeap->AddressOf(), 1); ImGui_ImplDX12_RenderDrawData(ImGui::GetDrawData(), commandList->Handle()); barrier.Swap(); commandList->ResourceBarrier(&barrier); auto &io = ImGui::GetIO(); if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) { ImGui::UpdatePlatformWindows(); ImGui::RenderPlatformWindowsDefault(nullptr, rcast<void*>(commandList->Handle())); } } } }
25.3
91
0.683794
QSXW
47b55a245279ee6706aab62df9d1ad31bdf4374b
1,626
cpp
C++
cpp/example/interpolate.cpp
mustafabar/RedSeaInterpolation
5d40cbc6e54df7a867445e8fadd11f9f1cce8556
[ "MIT" ]
null
null
null
cpp/example/interpolate.cpp
mustafabar/RedSeaInterpolation
5d40cbc6e54df7a867445e8fadd11f9f1cce8556
[ "MIT" ]
null
null
null
cpp/example/interpolate.cpp
mustafabar/RedSeaInterpolation
5d40cbc6e54df7a867445e8fadd11f9f1cce8556
[ "MIT" ]
null
null
null
#include "referencefunctions.h" #include "interpolation.h" #include <cmath> #include <iostream> #include <random> void print_gradient(const Eigen::Vector3d &grad) { for (int i = 0; i < 3; i++) { std::cout << grad(i) << ' '; } std::cout << std::endl; } void print_hessian(const Eigen::Matrix3d &hess) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { std::cout << hess(i, j) << ' '; } std::cout << std::endl; } } RescaledFunction<Polynomial> computeInterpolationPolynomial(const ReferenceFunction &fun, const std::array<Point, 2> &corners) { InterpolationParameter param; int c = 0; for (int k = 0; k < 2; k++) { for (int j = 0; j < 2; j++) { for (int i = 0; i < 2; i++) { Point x(corners[i][0], corners[j][1], corners[k][2]); param.f[c] = fun(x); param.dfdx[c] = fun.dx(x); param.dfdy[c] = fun.dy(x); param.dfdz[c] = fun.dz(x); param.d2fdxdy[c] = fun.dxdy(x); param.d2fdxdz[c] = fun.dxdz(x); param.d2fdydz[c] = fun.dydz(x); param.d3fdxdydz[c] = fun.dxdydz(x); c += 1; } } } return tricubic_interpolate(param, corners[0], corners[1]); } int main() { std::array<Point, 2> corners{Point({2, 2, 2}), Point({-1, -1, -1})}; std::array<long, 3> orderArray = {3, 3, 3}; Polynomial fun(orderArray); auto poly = computeInterpolationPolynomial(fun, corners); Point x(0.5, 0.6, 0.7); std::cout << fun(x) << std::endl; std::cout << poly(x) << std::endl; print_gradient(fun.grad(x)); print_gradient(poly.grad(x)); return 0; }
23.911765
70
0.550431
mustafabar
47b9faa2f4d833ca5051111bf2f5b494edbebde7
17,617
cpp
C++
app/source/core/albumwrapper.cpp
iUltimateLP/NXGallery
0b9085c789478e28b67dcce0f4902f11e135522d
[ "MIT" ]
38
2020-05-10T14:03:25.000Z
2022-02-17T09:11:21.000Z
app/source/core/albumwrapper.cpp
iUltimateLP/NXGallery
0b9085c789478e28b67dcce0f4902f11e135522d
[ "MIT" ]
14
2020-05-15T18:47:19.000Z
2022-03-27T12:06:37.000Z
app/source/core/albumwrapper.cpp
iUltimateLP/NXGallery
0b9085c789478e28b67dcce0f4902f11e135522d
[ "MIT" ]
null
null
null
/* NXGallery for Nintendo Switch Made with love by Jonathan Verbeek (jverbeek.de) MIT License Copyright (c) 2020-2021 Jonathan Verbeek 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 "albumwrapper.hpp" #include "json.hpp" #include <sys/stat.h> #include <errno.h> #include <inttypes.h> #include <dirent.h> #include <filesystem> #include <regex> using namespace nxgallery::core; using json = nlohmann::json; // Needed for compiler CAlbumWrapper* CAlbumWrapper::singleton = NULL; // Overwritten == operator to compare CapsAlbumEntry's inline bool operator==(CapsAlbumEntry lhs, const CapsAlbumEntry rhs) { // Just compare by the datetime return lhs.file_id.datetime.day == rhs.file_id.datetime.day && lhs.file_id.datetime.month == rhs.file_id.datetime.month && lhs.file_id.datetime.year == rhs.file_id.datetime.year && lhs.file_id.datetime.hour == rhs.file_id.datetime.hour && lhs.file_id.datetime.minute == rhs.file_id.datetime.minute && lhs.file_id.datetime.second == rhs.file_id.datetime.second && lhs.file_id.datetime.id == rhs.file_id.datetime.id; } CVideoStreamReader::CVideoStreamReader(const CapsAlbumEntry& inAlbumEntry) : albumEntry(inAlbumEntry) { // Open video stream if (R_FAILED(capsaOpenAlbumMovieStream(&streamHandle, &albumEntry.file_id))) { printf("Failed to open video stream!\n"); return; } // Initialize the buffer workBuffer = (unsigned char*)calloc(workBufferSize, sizeof(unsigned char)); // Get the size the stream will be capsaGetAlbumMovieStreamSize(streamHandle, &streamSize); } CVideoStreamReader::~CVideoStreamReader() { // Free the read buffer free(workBuffer); // Close the stream capsaCloseAlbumMovieStream(streamHandle); } u64 CVideoStreamReader::GetStreamSize() { // If the stream size is bigger than INT_MAX, it's probably invalid and we'll return 0 if (streamSize > 0x80000000) return 0; return streamSize; } u64 CVideoStreamReader::Read(char* outBuffer, u64 numBytes) { // Calculate a few statistics u64 remaining = streamSize - bytesRead; u64 bufferIndex = bytesRead / workBufferSize; u64 currentOffset = bytesRead % workBufferSize; u64 readSize = std::min(std::min(numBytes, workBufferSize - currentOffset), remaining); // Could debug the video stream read progress here //float percentage = ((float)bytesRead / (float)streamSize) * 100; //printf("Progress: %f\n", percentage); // If no data is remaining, exit if (remaining <= 0) return 0; // Read the next buffer Result readResult = 0; if (bufferIndex != lastBufferIndex) { u64 actualSize = 0; readResult = capsaReadMovieDataFromAlbumMovieReadStream(streamHandle, bufferIndex * workBufferSize, workBuffer, workBufferSize, &actualSize); lastBufferIndex = bufferIndex; } // Copy from the work buffer to the the output buffer unsigned char* startOutBuffer = workBuffer + currentOffset; memcpy(outBuffer, startOutBuffer, readSize); // Keep track of progress bytesRead += readSize; // If it worked, return the number of bytes we just read, otherwise return 0 if (R_SUCCEEDED(readResult)) return readSize; else { printf("Error reading movie stream!"); return 0; } } CAlbumWrapper* CAlbumWrapper::Get() { // If no singleton is existing, create a new instance if (!singleton) { singleton = new CAlbumWrapper(); } // Return the instance return singleton; } void CAlbumWrapper::Init() { // SD card storage will already be mounted thanks to romfsInitialize() // Mount the USER partition of the NAND storage by first opening the BIS USER parition Result r = fsOpenBisFileSystem(&nandFileSystem, FsBisPartitionId_User, ""); if (R_FAILED(r)) { printf("Error opening BIS USER partition: %d\n", R_DESCRIPTION(r)); return; } // Now mount the opened partition to "nand:/" int rc = fsdevMountDevice("nand", nandFileSystem); if (rc < 0) { printf("Error mounting NAND storage!\n"); } // Cache the gallery content CacheGalleryContent(); } void CAlbumWrapper::Shutdown() { // Unmount the NAND storage int r = fsdevUnmountDevice("nand"); if (r < 0) { printf("Error unmounting NAND storage!\n"); } } std::string CAlbumWrapper::GetGalleryContent(int page) { // Will hold the stringified JSON data std::string outJSON; // Holds the stat object we pass along json statObject; // Take the time we need so we can display a cool stat auto startTime = std::chrono::steady_clock::now(); /* A "gallery content" object should look like this: { "path": "/2020/05/04/2020050410190700-02CB906EA538A35643C1E1484C4B947D.jpg", "takenAt": "1589444763", "game": "0100000000010000" OR "Super Mario Odyssey", "storedAt": "nand" / "sd", "type": "screenshot" / "movie" } */ // New json object which will hold the total response json finalObject; // Fill in some data for the frontend // Calculate the max amount of pages we will have finalObject["pages"] = (int)ceil((double)cachedAlbumContent.size() / (double)CONTENT_PER_PAGE); // Get the console's color theme so the frontend can fit ColorSetId colorTheme; Result r = setsysGetColorSetId(&colorTheme); if (R_SUCCEEDED(r)) { finalObject["theme"] = colorTheme == ColorSetId_Dark ? "dark" : "light"; } // Will hold the album contents json jsonArray = json::array(); // Calculate the page range int pageMin = (page - 1) * CONTENT_PER_PAGE; int pageMax = page * CONTENT_PER_PAGE; // Make sure to stay in bounds if (pageMax >= cachedAlbumContent.size()) pageMax = cachedAlbumContent.size(); // Iterate over the current range for the page for (int i = pageMin; i < pageMax; i++) { // Get the entry off the album content cache CapsAlbumEntry albumEntry = cachedAlbumContent[i]; // Figure out if this album entry is stored on the NAND of SD by looking at the // vector this element is in bool isStoredInNand = albumEntry.file_id.storage != CapsAlbumStorage_Sd; // The JSON object for this entry of the album json jsonObj; jsonObj["id"] = i; jsonObj["storedAt"] = isStoredInNand ? "nand" : "sd"; // Retrieve the title's name jsonObj["game"] = GetTitleName(albumEntry.file_id.application_id); // Retrieve the file size of the file u64 fileSize; Result getFileSizeResult = capsaGetAlbumFileSize(&albumEntry.file_id, &fileSize); if (R_SUCCEEDED(getFileSizeResult)) { jsonObj["fileSize"] = fileSize; } // Create a UNIX-timestamp from the datetime we get from capsa struct tm createdAt; createdAt.tm_year = albumEntry.file_id.datetime.year - 1900; createdAt.tm_mon = albumEntry.file_id.datetime.month - 1; createdAt.tm_mday = albumEntry.file_id.datetime.day; createdAt.tm_hour = albumEntry.file_id.datetime.hour; createdAt.tm_min = albumEntry.file_id.datetime.minute; createdAt.tm_sec = albumEntry.file_id.datetime.second; time_t timestamp = mktime(&createdAt); jsonObj["takenAt"] = timestamp; // Determine the type by looking at the file extension if (albumEntry.file_id.content == CapsAlbumFileContents_Movie || albumEntry.file_id.content == CapsAlbumFileContents_ExtraMovie) { jsonObj["type"] = "video"; } else { jsonObj["type"] = "screenshot"; } // Add the filename for downloading jsonObj["fileName"] = nxgallery::core::CAlbumWrapper::Get()->GetAlbumEntryFilename(i); // Push this json object to the array jsonArray.push_back(jsonObj); } finalObject["gallery"] = jsonArray; // Stop the time! auto endTime = std::chrono::steady_clock::now(); double indexTime = std::chrono::duration_cast<std::chrono::duration<double>>(endTime - startTime).count(); // Attach the stats statObject["indexTime"] = indexTime; statObject["numScreenshots"] = screenshotCount; statObject["numVideos"] = videoCount; finalObject["stats"] = statObject; // Stringify the JSON array outJSON = finalObject.dump(); return outJSON; } std::string CAlbumWrapper::GetTitleName(u64 titleId) { // Retrieve the control.nacp data for the game where the current album entry was taken NsApplicationControlData nacpData; u64 nacpDataSize; Result getNACPResult = nsGetApplicationControlData(NsApplicationControlSource_Storage, titleId, &nacpData, sizeof(nacpData), &nacpDataSize); if (R_SUCCEEDED(getNACPResult)) { // Retrieve the language string for the Switch'es desired language NacpLanguageEntry* nacpLangEntry; Result getLangEntryResult = nsGetApplicationDesiredLanguage(&nacpData.nacp, &nacpLangEntry); // If it worked, we can grab the nacpLangEntry->name which will hold the name of the title if (R_SUCCEEDED(getLangEntryResult)) { return nacpLangEntry->name; } } // If the above didn't work, it's probably not a game where this album entry was created // A list of all system applets mapped to their title ID // https://switchbrew.org/wiki/Title_list#System_Applets std::map<u64, const char*> systemTitles; systemTitles[0x0100000000001000] = "Home Menu"; // qlaunch systemTitles[0x0100000000001001] = "Auth"; // auth systemTitles[0x0100000000001002] = "Cabinet"; // cabinet systemTitles[0x0100000000001003] = "Controller"; // controller systemTitles[0x0100000000001004] = "DataErase"; // dataErase systemTitles[0x0100000000001005] = "Error"; // error systemTitles[0x0100000000001006] = "Net Connect"; // netConnect systemTitles[0x0100000000001007] = "Player Select"; // playerSelect systemTitles[0x0100000000001008] = "Keyboard"; // swkbd systemTitles[0x0100000000001009] = "Mii Editor"; // miiEdit systemTitles[0x010000000000100A] = "Web Browser"; // web systemTitles[0x010000000000100B] = "eShop"; // shop systemTitles[0x010000000000100C] = "Overlay"; // overlayDisp systemTitles[0x010000000000100D] = "Album"; // photoViewer systemTitles[0x010000000000100F] = "Offline Web Browser"; // offlineWeb systemTitles[0x0100000000001010] = "Share"; // loginShare systemTitles[0x0100000000001011] = "WiFi Web Auth"; // wifiWebAuth systemTitles[0x0100000000001012] = "Starter"; // starter systemTitles[0x0100000000001013] = "My Page"; // myPage // If it's one of the above, lookup the name from the map, otherwise it's Unknown if (systemTitles.count(titleId)) { return systemTitles[titleId]; } else { return "Unknown"; } } CapsAlbumFileContents CAlbumWrapper::GetAlbumEntryType(int id) { return (CapsAlbumFileContents)cachedAlbumContent[id].file_id.content; } std::string CAlbumWrapper::GetAlbumEntryFilename(int id) { // Get the entry from cache CapsAlbumEntry albumEntry = cachedAlbumContent[id]; // Get the file and check if it's a video CapsAlbumFileContents fileType = GetAlbumEntryType(id); bool isVideo = (fileType == CapsAlbumFileContents_Movie || fileType == CapsAlbumFileContents_ExtraMovie); std::string extension = isVideo ? ".mp4" : ".jpg"; // Get the title name std::string titleName = GetTitleName(albumEntry.file_id.application_id); // Do some regex to replace whitespaces titleName = std::regex_replace(titleName, std::regex("\\s+"), "_"); // Get the date and form a string char dateStr[32]; sprintf(dateStr, "%04u%02u%02u_%02u%02u%02u_%02u", albumEntry.file_id.datetime.year, albumEntry.file_id.datetime.month, albumEntry.file_id.datetime.day, albumEntry.file_id.datetime.hour, albumEntry.file_id.datetime.minute, albumEntry.file_id.datetime.second, albumEntry.file_id.datetime.id); std::string finalName = titleName + "_" + dateStr + extension; return finalName; } bool CAlbumWrapper::GetFileThumbnail(int id, void* outBuffer, u64 bufferSize, u64* outActualImageSize) { // Make sure that ID exists if (id < 0 || id > cachedAlbumContent.size()) return false; // Get the content with that ID CapsAlbumEntry entry = cachedAlbumContent[id]; // Load the thumbnail Result result = capsaLoadAlbumFileThumbnail(&entry.file_id, outActualImageSize, outBuffer, bufferSize); if (R_SUCCEEDED(result)) { return true; } else { printf("Failed to get thumbnail for file %d: %d-%d\n", id, R_MODULE(result), R_DESCRIPTION(result)); return false; } } bool CAlbumWrapper::GetFileContent(int id, void* outBuffer, u64 bufferSize, u64* outActualFileSize) { // Make sure that ID exists if (id < 0 || id > cachedAlbumContent.size()) return false; // Get the content with that ID CapsAlbumEntry entry = cachedAlbumContent[id]; // If it's a screenshot, we can use capsaLoadAlbumFile to retrieve it if (entry.file_id.content == CapsAlbumFileContents_ScreenShot || entry.file_id.content == CapsAlbumFileContents_ExtraScreenShot) { // Load the file content Result result = capsaLoadAlbumFile(&entry.file_id, outActualFileSize, outBuffer, bufferSize); if (R_SUCCEEDED(result)) { return true; } else { printf("Failed to get file content for file %d: %d-%d\n", id, R_MODULE(result), R_DESCRIPTION(result)); return false; } } else { // It's a video, use our movie stream reader CVideoStreamReader* videoStreamReader = new CVideoStreamReader(entry); // Get the stream size. Using that we also know how much bytes we need to read in total *outActualFileSize = videoStreamReader->GetStreamSize(); u64 readLeft = videoStreamReader->GetStreamSize(); // Read until no bytes are left to read size_t bytesRead = 0; while (readLeft > 0) { // Offset the buffer's pointer accordingly char* ptr = ((char*)outBuffer) + bytesRead; u64 readResult = videoStreamReader->Read(ptr, videoStreamReader->GetStreamSize()); bytesRead += readResult; readLeft -= readResult; } // Finished, delete the stream reader delete videoStreamReader; // If no bytes are left to read, everything worked fine return readLeft <= 0; } } void CAlbumWrapper::CacheGalleryContent() { // Cache NAND album CacheAlbum(CapsAlbumStorage_Nand, cachedAlbumContent); // Cache SD album CacheAlbum(CapsAlbumStorage_Sd, cachedAlbumContent); // Reverse the album entries so newest are first std::reverse(cachedAlbumContent.begin(), cachedAlbumContent.end()); } void CAlbumWrapper::CacheAlbum(CapsAlbumStorage location, std::vector<CapsAlbumEntry>& outCache) { // This uses capsa (Capture Service), which is the libnx service to data from the Switch album // Get the total amount of files in the album u64 totalAlbumFileCount; capsaGetAlbumFileCount(location, &totalAlbumFileCount); // Get all album files from the album u64 albumFileCount; CapsAlbumEntry albumFiles[totalAlbumFileCount]; Result r = capsaGetAlbumFileList(location, &albumFileCount, albumFiles, totalAlbumFileCount); if (R_FAILED(r)) { printf("Failed to get album file list for storage %s: %d-%d\n", location == CapsAlbumStorage_Sd ? "SD" : "NAND", R_MODULE(r), R_DESCRIPTION(r)); return; } // Add the files from the raw array to the std::vector for (CapsAlbumEntry entry : albumFiles) { // Count if (entry.file_id.content == CapsAlbumFileContents_Movie || entry.file_id.content == CapsAlbumFileContents_ExtraMovie) videoCount++; else screenshotCount++; // Add to the cache outCache.push_back(entry); } #ifdef __DEBUG__ printf("Cached %ld album files for %s storage\n", totalAlbumFileCount, location == CapsAlbumStorage_Sd ? "SD" : "NAND"); #endif }
34.611002
152
0.675768
iUltimateLP
47bb95da3c24f525aecff41fd0ef971fad3c6114
586
cpp
C++
source/chapter_05/listings/listing_05_14_waiting.cpp
ShinyGreenRobot/CPP-Primer-Plus-Sixth-Edition
ce2c8fca379508929dfd24dce10eff2c09117999
[ "MIT" ]
null
null
null
source/chapter_05/listings/listing_05_14_waiting.cpp
ShinyGreenRobot/CPP-Primer-Plus-Sixth-Edition
ce2c8fca379508929dfd24dce10eff2c09117999
[ "MIT" ]
null
null
null
source/chapter_05/listings/listing_05_14_waiting.cpp
ShinyGreenRobot/CPP-Primer-Plus-Sixth-Edition
ce2c8fca379508929dfd24dce10eff2c09117999
[ "MIT" ]
null
null
null
/** * \file * listing_05_14_waiting.cpp * * \brief * Using clock() in a time-delay loop. */ #include <ctime> // describes clock() function, clock_t type #include <iostream> int main() { using namespace std; cout << "Enter the delay time, in seconds: "; float secs; cin >> secs; clock_t delay = secs * CLOCKS_PER_SEC; // convert to clock ticks cout << "starting\a\n"; clock_t start = clock(); while (clock() - start < delay ) // wait until time passes { ; // note the semicolon } cout << "done \a\n"; return 0; }
20.206897
68
0.581911
ShinyGreenRobot
47bee0a2e539c092ccc7de0698b37716f69b4d28
722
cpp
C++
benchmark/benchmark.cpp
ortfero/pulse
08cd78c20f16101b553e4e15f1a04011bb32722c
[ "MIT" ]
null
null
null
benchmark/benchmark.cpp
ortfero/pulse
08cd78c20f16101b553e4e15f1a04011bb32722c
[ "MIT" ]
null
null
null
benchmark/benchmark.cpp
ortfero/pulse
08cd78c20f16101b553e4e15f1a04011bb32722c
[ "MIT" ]
null
null
null
#include <stdio.h> #include <pulse/pulse.hpp> #include <ubench/ubench.hpp> struct listener { }; // listener using slot_type = void(listener::*)(); bool flag = true; struct handler: listener { void slot() { flag = !flag; } }; // handler int main() { handler h; listener* l = &h; slot_type s = slot_type(&handler::slot); pulse::source<void()> source; source.bind(&h, &handler::slot); auto const member_bench = ubench::run([&]{ (l->*s)(); }); auto const pulse_bench = ubench::run([&]{ source(); }); printf("member_ptr - %.1fns\n", member_bench.time.count()); printf("pulse::signal - %.1fns\n", pulse_bench.time.count()); printf("flag = %s\n", flag ? "true" : "false"); return 0; }
18.05
63
0.609418
ortfero
47bf81bc6c0b6c52ed41b6571e87789df5f4b611
5,009
cpp
C++
node_modules/ammo.js/bullet/Extras/CDTestFramework/Opcode/Ice/IceHPoint.cpp
Xielifen/three.js-master
58467f729243d90da4b758b0fe130eb40458bc39
[ "MIT" ]
8
2015-02-28T15:33:39.000Z
2019-06-12T19:59:34.000Z
node_modules/ammo.js/bullet/Extras/CDTestFramework/Opcode/Ice/IceHPoint.cpp
Xielifen/three.js-master
58467f729243d90da4b758b0fe130eb40458bc39
[ "MIT" ]
null
null
null
node_modules/ammo.js/bullet/Extras/CDTestFramework/Opcode/Ice/IceHPoint.cpp
Xielifen/three.js-master
58467f729243d90da4b758b0fe130eb40458bc39
[ "MIT" ]
5
2016-04-13T12:22:36.000Z
2022-01-14T19:18:52.000Z
/* * ICE / OPCODE - Optimized Collision Detection * http://www.codercorner.com/Opcode.htm * * Copyright (c) 2001-2008 Pierre Terdiman, pierre@codercorner.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Contains code for homogeneous points. * \file IceHPoint.cpp * \author Pierre Terdiman * \date April, 4, 2000 */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Homogeneous point. * * Use it: * - for clipping in homogeneous space (standard way) * - to differentiate between points (w=1) and vectors (w=0). * - in some cases you can also use it instead of Point for padding reasons. * * \class HPoint * \author Pierre Terdiman * \version 1.0 * \warning No cross-product in 4D. * \warning HPoint *= Matrix3x3 doesn't exist, the matrix is first casted to a 4x4 */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Precompiled Header #include "Stdafx.h" using namespace Opcode; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Point Mul = HPoint * Matrix3x3; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Point HPoint::operator*(const Matrix3x3& mat) const { return Point( x * mat.m[0][0] + y * mat.m[1][0] + z * mat.m[2][0], x * mat.m[0][1] + y * mat.m[1][1] + z * mat.m[2][1], x * mat.m[0][2] + y * mat.m[1][2] + z * mat.m[2][2] ); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // HPoint Mul = HPoint * Matrix4x4; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// HPoint HPoint::operator*(const Matrix4x4& mat) const { return HPoint( x * mat.m[0][0] + y * mat.m[1][0] + z * mat.m[2][0] + w * mat.m[3][0], x * mat.m[0][1] + y * mat.m[1][1] + z * mat.m[2][1] + w * mat.m[3][1], x * mat.m[0][2] + y * mat.m[1][2] + z * mat.m[2][2] + w * mat.m[3][2], x * mat.m[0][3] + y * mat.m[1][3] + z * mat.m[2][3] + w * mat.m[3][3]); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // HPoint *= Matrix4x4 /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// HPoint& HPoint::operator*=(const Matrix4x4& mat) { float xp = x * mat.m[0][0] + y * mat.m[1][0] + z * mat.m[2][0] + w * mat.m[3][0]; float yp = x * mat.m[0][1] + y * mat.m[1][1] + z * mat.m[2][1] + w * mat.m[3][1]; float zp = x * mat.m[0][2] + y * mat.m[1][2] + z * mat.m[2][2] + w * mat.m[3][2]; float wp = x * mat.m[0][3] + y * mat.m[1][3] + z * mat.m[2][3] + w * mat.m[3][3]; x = xp; y = yp; z = zp; w = wp; return *this; }
56.920455
244
0.345578
Xielifen
47cb9d0b97b1426b29f3e5e58983f1836f85c062
5,697
cpp
C++
src/server/tests/httpserv.cpp
Ooggle/MUSIC-exclamation-mark
55f4dd750d57227fac29d887d90e0c8ec2ad7397
[ "MIT" ]
7
2020-08-28T21:47:54.000Z
2021-01-01T17:54:27.000Z
src/server/tests/httpserv.cpp
Ooggle/MUSIC-exclamation-mark
55f4dd750d57227fac29d887d90e0c8ec2ad7397
[ "MIT" ]
null
null
null
src/server/tests/httpserv.cpp
Ooggle/MUSIC-exclamation-mark
55f4dd750d57227fac29d887d90e0c8ec2ad7397
[ "MIT" ]
1
2020-12-26T17:08:54.000Z
2020-12-26T17:08:54.000Z
#include <unistd.h> #include <regex.h> #include <stdio.h> #include <string.h> #include <iostream> #include <fstream> #include <filesystem> #include <string> #include <vector> #include "ServeurTcp.h" int regexTwo(std::string paramsSource); std::string getRequestLine(ServeurTcp *server) { uint8_t data = 0; std::string line = ""; while(data != 0x0A) { server->recevoirData(&data, 1); if(data != 0x0A) line += data; } return line; } std::vector<std::string> getRequestHeader(ServeurTcp *server) { std::vector<std::string> request; do { request.push_back(getRequestLine(server)); /* printf("length: %d\n", request.back().length()); printf("%s\n", request.back().c_str()); */ } while(request.back().length() > 2); return request; } int regexOne(std::string strSource) { regex_t reg; // Function call to create regex if (regcomp(&reg, "^GET\\s\\/(music|database)(\\?.*)\\sHTTP", REG_EXTENDED) != 0) { printf("Compilation error.\n"); } size_t maxGroups = 15; regmatch_t groupArray[maxGroups]; const char *source = strSource.c_str(); if(regexec(&reg, source, maxGroups, groupArray, 0) == 0) { unsigned int g = 0; for(g = 0; g < maxGroups; g++) { if(groupArray[g].rm_so == (size_t)-1) break; // No more groups char sourceCopy[strlen(source) + 1]; strcpy(sourceCopy, source); sourceCopy[groupArray[g].rm_eo] = 0; /* printf("Group %u: [%2u-%2u]: %s\n", g, groupArray[g].rm_so, groupArray[g].rm_eo, sourceCopy + groupArray[g].rm_so); */ } char sourceCopy[strlen(source) + 1]; strcpy(sourceCopy, source); sourceCopy[groupArray[2].rm_eo] = 0; printf("param source: %s\n", sourceCopy + groupArray[2].rm_so); regexTwo(sourceCopy + groupArray[2].rm_so); } else { printf("no pattern found\n"); } regfree(&reg); return 0; } int regexTwo(std::string paramsSource) { regex_t reg; // create regex if (regcomp(&reg, "[?&]+([^=&]+)=([^&]*)", REG_EXTENDED) != 0) { printf("Compilation error.\n"); } size_t maxMatches = 5; size_t maxGroups = 15; regmatch_t groupArray[maxGroups]; unsigned int m; const char *source = paramsSource.c_str(); regoff_t last_match = 0; int Numparams = 0; while(regexec(&reg, source + last_match, maxGroups, groupArray, 0) == 0) { unsigned int g = 0; Numparams += 1; for(g = 0; g < maxGroups; g++) { if(groupArray[g].rm_so == (size_t)-1) break; // No more groups char sourceCopy[strlen(source) + last_match + 1]; strcpy(sourceCopy, source); sourceCopy[groupArray[g].rm_eo + last_match] = 0; /*printf("Group %u: [%2u-%2u]: %s\n", g, groupArray[g].rm_so + last_match, groupArray[g].rm_eo + last_match, sourceCopy + groupArray[g].rm_so + last_match);*/ } char sourceParamName[strlen(source) + last_match + 1]; strcpy(sourceParamName, source); sourceParamName[groupArray[1].rm_eo + last_match] = 0; char sourceParamValue[strlen(source) + last_match + 1]; strcpy(sourceParamValue, source); sourceParamValue[groupArray[2].rm_eo + last_match] = 0; printf("Param %d: %s = %s\n", Numparams, sourceParamName + groupArray[1].rm_so + last_match, sourceParamValue + groupArray[2].rm_so + last_match); last_match += groupArray[0].rm_so + 1; } regfree(&reg); return 0; } int main() { ServeurTcp leServeur; leServeur.ouvrir("192.168.0.44", 80); printf("serveur ouvert\n"); leServeur.connecterUnClient(); printf("client connecte\n"); int i = 0; char getStr[255] = {0}; int getSize = 0; printf("\n\n"); std::vector<std::string> requestHeader = getRequestHeader(&leServeur); std::vector<std::pair<std::string, std::string>> URLInfos; regexOne(requestHeader.at(0).c_str()); printf("request : %s\n", getStr); // file loading std::ifstream myFile; myFile.open("musics/sample.mp3", std::ios_base::out | std::ios_base::app | std::ios_base::binary); if(!myFile.is_open()) return EXIT_FAILURE; std::uintmax_t totalFileSize = std::filesystem::file_size("musics/sample.mp3"); printf("file size : %d\n", totalFileSize); // header sending printf("sending data..."); std::string header; // audio/ogg pour ogg et flac, audio/mpeg pour mp3 header = "HTTP/1.1 200 OK\r\n"; header += "Connection: keep-alive\r\n"; header += "Content-Type: audio/mpeg\r\n"; header += "Content-Length: "; header += std::to_string(totalFileSize); header += "\r\n"; header += "\r\n"; printf("%s", header.c_str()); leServeur.emettreData((void *)header.c_str(), header.length()); // file sending int sizeToRead = 5000; char FileBuffer[totalFileSize]; char lastBuffer[sizeToRead]; std::uintmax_t readedSize = 0; while(readedSize < totalFileSize) { if((readedSize + sizeToRead) > totalFileSize) { sizeToRead = totalFileSize - readedSize; } if(!myFile.read(lastBuffer, sizeToRead)) return EXIT_FAILURE; leServeur.emettreData((void *)lastBuffer, sizeToRead); readedSize += sizeToRead; } leServeur.deconnecterUnClient(); leServeur.fermer(); sleep(0.5); return EXIT_SUCCESS; }
27.128571
154
0.583289
Ooggle
47d05694290c4feb5306e4ca153e7f48be286ece
7,758
cpp
C++
sourceCode/fairport/branch/ankopp/samples/nameprop/main.cpp
enrondata/pstsdk
70701d755f52412f0f21ed216968e314433a324e
[ "Apache-2.0" ]
6
2019-07-11T23:24:55.000Z
2021-08-03T16:31:12.000Z
sourceCode/fairport/trunk/samples/nameprop/main.cpp
Lingchar/pstsdk
70701d755f52412f0f21ed216968e314433a324e
[ "Apache-2.0" ]
null
null
null
sourceCode/fairport/trunk/samples/nameprop/main.cpp
Lingchar/pstsdk
70701d755f52412f0f21ed216968e314433a324e
[ "Apache-2.0" ]
4
2019-04-17T07:08:30.000Z
2020-10-12T22:35:19.000Z
#include <iostream> #include <iomanip> #include <string> #include <vector> #include "pstsdk/util/primitives.h" #include "pstsdk/ltp/propbag.h" #include "pstsdk/pst/pst.h" using namespace std; using namespace pstsdk; void pretty_print(const guid& g, bool special) { cout << "{" << hex << setw(8) << setfill('0') << g.data1 << "-" << setw(4) << g.data2 << "-" << setfill('0') << setw(4) << g.data3 << "-"; // next two bytes cout << hex << setw(2) << setfill('0') << (short)g.data4[0] << setw(2) << setfill('0') << (short)g.data4[1] << "-"; // next six bytes for(int i = 2; i < 8; ++i) cout << hex << setw(2) << setfill('0')<< (short)g.data4[i]; cout << (special ? "} *" : "}"); } void pretty_print(const disk::nameid& id) { cout << "id/str offset: " << setw(6) << id.id << ", guid idx: " << setw(2) << disk::nameid_get_guid_index(id) << ", prop idx: " << setw(4) << disk::nameid_get_prop_index(id) << ", is str: " << (disk::nameid_is_string(id) ? "y" : "n"); } void pretty_print(const disk::nameid_hash_entry& id) { cout << "hash value: " << setw(8) << hex << id.hash_base << ", guid idx: " << setw(2) << dec << disk::nameid_get_guid_index(id) << ", prop idx: " << setw(4) << disk::nameid_get_prop_index(id) << ", is str: " << (disk::nameid_is_string(id) ? "y" : "n"); } int main() { pst p(L"../../test/sample2.pst"); property_bag names(p.get_db()->lookup_node(nid_name_id_map)); // // dump out the bucket count // // The bucket count is stored in property 0x0001 cout << "Bucket Count: " << names.read_prop<slong>(0x1) << endl; // // dump out the guid stream // // The GUID Stream is a flat array of guid structures, with three // predefined values. Because of the predefined values, structures // referencing the GUID stream refer to the first entry as entry "3" prop_stream guid_stream(names.open_prop_stream(0x2)); guid g; int i = 3; cout << endl << "GUID Stream: " << endl; cout << "[000] "; pretty_print(ps_none, true); cout << "\n[001] "; pretty_print(ps_mapi, true); cout << "\n[002] "; pretty_print(ps_public_strings, true); cout << endl; while(guid_stream.read((char*)&g, sizeof(g)) != 0) { cout << dec << setfill('0') << "[" << setw(3) << i++ << "] "; pretty_print(g, false); cout << endl; } cout << "* predefined guid, not actually present in guid stream" << endl; // // dump out the entry stream // // The entry stream is a flat array of nameid structures prop_stream entry_stream(names.open_prop_stream(0x3)); disk::nameid id; i = 0; cout << endl << "Entry Stream: " << endl; while(entry_stream.read((char*)&id, sizeof(id)) != 0) { cout << dec << setfill('0') << "[" << setw(5) << i++ << "] "; pretty_print(id); cout << endl; } // // dump out the string stream // // The string stream is a series of long values (4 bytes), which give // the length of the immediately following string, followed by padding // to an 8 byte boundry, then another long for the next string, etc. // When structures address into the string stream, they are giving the // offset of the long value for the length of the string they want to access. prop_stream sstream(names.open_prop_stream(0x4)); ulong size; std::vector<char> buffer; cout << endl << "String Stream (offset, size: string) : " << endl; while(sstream.read((char*)&size, sizeof(size)) != 0) { if(buffer.size() < size) buffer.resize(size); sstream.read((char*)&buffer[0], size); std::wstring val(reinterpret_cast<wchar_t*>(&buffer[0]), size/sizeof(wchar_t)); wcout << setw(6) << ((size_t)sstream.tellg() - size - 4) << ", " << setw(4) << size << ": " << val << endl; size_t pos = (size_t)sstream.tellg(); pos = (pos + 3L & ~3L); sstream.seekg(pos); } // // dump out the hash buckets // // Each hash bucket is an array of what basically are the same nameid structures // in the entry array, except the first field contains the crc of the string instead // of the string offset. For named props based on identifiers the value is identical. cout << endl << "Buckets:" << endl; prop_id max_bucket = (prop_id)(0x1000 + names.read_prop<slong>(0x1)); for(prop_id p = 0x1000; p < max_bucket; ++p) { cout << "[" << setw(4) << hex << p << "] "; try { prop_stream hash_values(names.open_prop_stream(p)); // calculate the number of values hash_values.seekg(0, ios_base::end); size_t size = (size_t)hash_values.tellg(); size_t num = size/sizeof(disk::nameid_hash_entry); cout << num << (num == 1 ? " entry" : " entries") << endl; int i = 0; disk::nameid_hash_entry entry; hash_values.seekg(0, ios_base::beg); while(hash_values.read((char*)&entry, sizeof(entry)) != 0) { cout << "\t" << dec << setfill('0') << "[" << setw(4) << i++ << "] "; pretty_print(entry); cout << endl; } } catch(key_not_found<prop_id>&) { // doesn't exist cout << "Empty" << endl; } } // // dump out all the named props // // Bring it all together. Iterate over the entry stream again, this time // fetching the proper values from the guid and the string streams. guid_stream.clear(); guid_stream.seekg(0, ios_base::beg); entry_stream.clear(); entry_stream.seekg(0, ios_base::beg); sstream.clear(); sstream.seekg(0, ios_base::beg); i = 0; cout << endl << "Named Props: " << endl; while(entry_stream.read((char*)&id, sizeof(id)) != 0) { // read the guid if(disk::nameid_get_guid_index(id) == 0) { g = ps_none; } else if(disk::nameid_get_guid_index(id) == 1) { g = ps_mapi; } else if(disk::nameid_get_guid_index(id) == 2) { g = ps_public_strings; } else { // note how you need to subtract 3 from the guid index to account for the // three predefined guids not stored in the guid stream guid_stream.seekg((disk::nameid_get_guid_index(id) - 3) * sizeof(g), ios_base::beg); guid_stream.read((char*)&g, sizeof(g)); } cout << "Name Prop 0x" << hex << setw(4) << (0x8000 + disk::nameid_get_prop_index(id)) << endl; cout << "\t" << dec << disk::nameid_get_guid_index(id) << ": "; pretty_print(g, false); cout << endl; if(disk::nameid_is_string(id)) { cout << "\tkind: string" << endl; // read the string sstream.seekg(id.string_offset, ios_base::beg); sstream.read((char*)&size, sizeof(size)); if(buffer.size() < size) buffer.resize(size); sstream.read((char*)&buffer[0], size); std::wstring val((wchar_t*)&buffer[0], (wchar_t*)&buffer[size]); wcout << L"\tname: " << val << endl; } else { cout << "\tkind: id" << endl; cout << "\tid: " << id.id << endl; } cout << endl; } }
33.296137
143
0.526811
enrondata
47d4584ca3bb595c6f631bc4e0efb3c1e688ab7d
21,357
cpp
C++
cc/playground/sum_store-dir/FH_MicroTest.cpp
yangzheng2115/demofaster
8968db65cf60a68f61c55e1e9becdbf226dc8d36
[ "MIT" ]
null
null
null
cc/playground/sum_store-dir/FH_MicroTest.cpp
yangzheng2115/demofaster
8968db65cf60a68f61c55e1e9becdbf226dc8d36
[ "MIT" ]
null
null
null
cc/playground/sum_store-dir/FH_MicroTest.cpp
yangzheng2115/demofaster
8968db65cf60a68f61c55e1e9becdbf226dc8d36
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include <fstream> #include <numa.h> #include <experimental/filesystem> #include "../../src/device/tracer.h" #include <stdio.h> #include <stdlib.h> #include "../../src/core/faster.h" #include "../../src/core/address.h" #include "../../src/device/file_system_disk.h" #include "../../src/device/null_disk.h" #include "../../src/core/utility.h" #define CONTEXT_TYPE 0 #if CONTEXT_TYPE == 0 #include "../../src/device/kvcontext.h" #elif CONTEXT_TYPE == 2 #include "../../src/device/cvkvcontext.h" #endif #define ENABLE_NUMA 1 #define DEFAULT_THREAD_NUM (4) #define DEFAULT_KEYS_COUNT (1 << 23) #define DEFAULT_KEYS_RANGE (1 << 30) #define DEFAULT_STR_LENGTH 256 //#define DEFAULT_KEY_LENGTH 8 #define LOCAL_TYPE 1 bool reading = false; bool parallellog = true; #define DEFAULT_STORE_BASE 100000000LLU using namespace FASTER::api; using namespace FASTER::core; using namespace FASTER::device; using namespace FASTER::environment; #ifdef _WIN32 typedef hreadPoolIoHandler handler_t; #else typedef QueueIoHandler handler_t; #endif typedef FileSystemDisk<handler_t, 1073741824ull> disk_t; using store_t = FasterKv<Key, Value, disk_t>; //using store_t = FasterKv<Key, Value, FASTER::io::NullDisk>; size_t init_size = next_power_of_two(DEFAULT_STORE_BASE / 2); store_t store{init_size, 17179869184, "storage"}; //FasterKv<Key, Value, FASTER::io::NullDisk> store{128, 1073741824, ""}; uint64_t *loads; std::vector<uint64_t> *localloads; #if CONTEXT_TYPE == 2 uint64_t *content; #endif long total_time; uint64_t exists = 0; uint64_t success = 0; uint64_t failure = 0; //uint64_t total_count = DEFAULT_KEYS_COUNT; uint64_t total_count = 60000000; uint64_t timer_range = default_timer_range; uint64_t kCheckpointInterval = 1 << 20; uint64_t kRefreshInterval = 1 << 8; uint64_t kCompletePendingInterval = 1 << 12; Guid retoken; int cd = 0; int rounds = 0; int thread_number = DEFAULT_THREAD_NUM; //int key_range = DEFAULT_KEYS_RANGE; int key_range = 1000000000; stringstream *output; atomic<int> stopMeasure(0); struct target { int tid; uint64_t *insert; store_t *store; bool random; bool firstround; bool read; }; pthread_t *workers; struct target *parms; void simpleInsert1() { Tracer tracer; tracer.startTime(); int inserted = 0; int j = 0; auto hybrid_log_persistence_callback = [](Status result, uint64_t persistent_serial_num) { if (result != Status::Ok) { printf("Thread %" PRIu32 " reports checkpoint failed.\n", Thread::id()); } else { printf("Thread %" PRIu32 " reports persistence until %" PRIu64 "\n", Thread::id(), persistent_serial_num); } }; //store.StartSession(); for (uint64_t i = 0; i < total_count; i++) { auto callback = [](IAsyncContext *ctxt, Status result) { CallbackContext<UpsertContext> context{ctxt}; }; #if CONTEXT_TYPE == 0 UpsertContext context{i, i}; #elif CONTEXT_TYPE == 2 UpsertContext context(loads[i], 8); context.reset((uint8_t *) (content + i)); #endif Status stat = store.Upsert(context, callback, 1); inserted++; /* if (i % kCompletePendingInterval == 0) { store.CompletePending(false); } else if (i % kRefreshInterval == 0) { store.Refresh(); } */ } //store.CompletePending(true); // Deregister thread from FASTER //store.StopSession(); cout << inserted << " " << tracer.getRunTime() << endl; } void simpleRead() { uint64_t hit = 0; uint64_t fail = 0; for (uint64_t i = 0; i < total_count; i++) { auto callback = [](IAsyncContext *ctxt, Status result) { CallbackContext<ReadContext> context{ctxt}; }; ReadContext context{i}; if (i == 7931739) int s = 0; Status result = store.Read(context, callback, 1); if (result == Status::Ok) hit++; else fail++; } cout << hit << " " << fail << endl; } void simpleInsert() { Tracer tracer; tracer.startTime(); int inserted = 0; int j = 0; auto hybrid_log_persistence_callback = [](Status result, uint64_t persistent_serial_num) { if (result != Status::Ok) { printf("Thread %" PRIu32 " reports checkpoint failed.\n", Thread::id()); } else { printf("Thread %" PRIu32 " reports persistence until %" PRIu64 "\n", Thread::id(), persistent_serial_num); } }; store.StartSession(); for (int i = 0; i < total_count; i++) { auto callback = [](IAsyncContext *ctxt, Status result) { CallbackContext<UpsertContext> context{ctxt}; }; #if CONTEXT_TYPE == 0 UpsertContext context{loads[i], loads[i]}; #elif CONTEXT_TYPE == 2 UpsertContext context(loads[i], 8); context.reset((uint8_t *) (content + i)); #endif Status stat = store.Upsert(context, callback, 1); inserted++; if (i % kCheckpointInterval == 0 && i != 0 && j == 0) { Guid token; cout << "checkpoint start in" << i << endl; if (store.Checkpoint(nullptr, hybrid_log_persistence_callback, token)) //if(store.CheckpointIndex(nullptr,token)) //if (store.CheckpointHybridLog(hybrid_log_persistence_callback, token)) //if(store.CheckpointIndex(nullptr,token)) { if (j == 0) printf("Calling Checkpoint(), token = %s\n", token.ToString().c_str()); j++; } } if (i % kCompletePendingInterval == 0) { store.CompletePending(false); } else if (i % kRefreshInterval == 0) { store.Refresh(); if (j == 1 && store.CheckpointCheck()) { cout << i << endl; cd = i; break; } } } //store.CompletePending(true); // Deregister thread from FASTER store.StopSession(); cout << inserted << " " << tracer.getRunTime() << endl; } void RecoverAndTest(const Guid &index_token, const Guid &hybrid_log_token) { uint32_t version; uint64_t hit = 0; uint64_t fail = 0; std::vector<Guid> session_ids; store.Recover(index_token, hybrid_log_token, version, session_ids); cout << "recover successful" << endl; for (uint64_t i = 0; i < total_count * 2; i++) { auto callback = [](IAsyncContext *ctxt, Status result) { CallbackContext<ReadContext> context{ctxt}; }; #if CONTEXT_TYPE == 0 ReadContext context{i}; Status result = store.Read(context, callback, 1); if (result == Status::Ok) hit++; else fail++; #elif CONTEXT_TYPE == 2 ReadContext context(loads[i]); Status result = store.Read(context, callback, 1); if (result == Status::Ok && *(uint64_t *) (context.output_bytes) == total_count - loads[i]) hit++; else fail++; #endif } cout << hit << " " << fail << endl; } void *checkWorker(void *args) { int inserted = 0; int j = 0; struct target *work = (struct target *) args; int k = work->tid; auto hybrid_log_persistence_callback = [](Status result, uint64_t persistent_serial_num) { if (result != Status::Ok) { printf("Thread %" PRIu32 " reports checkpoint failed.\n", Thread::id()); } else { printf("Thread %" PRIu32 " reports persistence until %" PRIu64 "\n", Thread::id(), persistent_serial_num); } }; store.StartSession(); s: for (uint64_t i = 0; i < total_count * 2; i++) { auto callback = [](IAsyncContext *ctxt, Status result) { CallbackContext<UpsertContext> context{ctxt}; }; #if CONTEXT_TYPE == 0 UpsertContext context{i, i}; #elif CONTEXT_TYPE == 2 UpsertContext context(loads[i], 8); context.reset((uint8_t *) (content + i)); #endif store.Refresh1(); //Status stat = store.Upsert(context, callback, i); Status stat = store.UpsertT(context, callback, i, parallellog ? thread_number : 1); inserted++; int excepcted = 0; if (i % kCheckpointInterval == 0 && i != 0 && stopMeasure.compare_exchange_strong(excepcted, 1)) { Guid token; cout << "checkpoint start in" << i << endl; //if (store.CheckpointHybridLog(hybrid_log_persistence_callback, token)) if (store.Checkpoint(nullptr, hybrid_log_persistence_callback, token)) // if(store.CheckpointIndex(nullptr, token)) { printf("Calling Checkpoint(), token = %s\n", token.ToString().c_str()); cout << "thread id" << k << endl; } } if (i % kCompletePendingInterval == 0) { store.CompletePending(false); } else if (i % kRefreshInterval == 0) { store.Refresh2(); if (stopMeasure.load() == 1 && store.CheckpointCheck()) { //cout <<"thread id:"<<k<<" end in"<< i << endl; j++; if (j == 10) { j = i; break; } } } } if (!store.CheckpointCheck()) { cout << work->tid << "fail" << endl; goto s; } //store.CompletePending(true); store.StopSession(); //output[work->tid] << work->tid << " " << j << endl; } void *gcWorker(void *args) { int inserted = 0; int j = 0; struct target *work = (struct target *) args; int k = work->tid; store.StartSession(); s: for (uint64_t i = total_count; i < total_count * 2; i++) { auto callback = [](IAsyncContext *ctxt, Status result) { CallbackContext<UpsertContext> context{ctxt}; }; #if CONTEXT_TYPE == 0 UpsertContext context{i, i}; //UpsertContext context{0, 0}; #elif CONTEXT_TYPE == 2 UpsertContext context(loads[i], 8); context.reset((uint8_t *) (content + i)); #endif store.Refresh1(); //Status stat = store.Upsert(context, callback, i); Status stat = store.UpsertT(context, callback, i, parallellog ? thread_number : 1); inserted++; int excepcted = 0; if (i % kCheckpointInterval == 0 && i != 0 && stopMeasure.compare_exchange_strong(excepcted, 1)) { Address a; //if (store.CheckpointHybridLog(hybrid_log_persistence_callback, token)) if (store.GrabageCollecton(a, nullptr, nullptr)) { cout << "garbage collection begin" << endl; } } if (i % kCompletePendingInterval == 0) { store.CompletePending(false); } else if (i % kRefreshInterval == 0) { store.Refresh2(); if (stopMeasure.load() == 1 && store.Gcflag) break; } } //store.CompletePending(true); store.StopSession(); //output[work->tid] << work->tid << " " << j << endl; } void multiPoints() { output = new stringstream[thread_number]; for (int i = 0; i < thread_number; i++) { pthread_create(&workers[i], nullptr, checkWorker, &parms[i]); } for (int i = 0; i < thread_number; i++) { pthread_join(workers[i], nullptr); // string outstr = output[i].str(); //cout << outstr; } cout << "checkpoint done ..." << endl; } void GC() { output = new stringstream[thread_number]; for (int i = 0; i < thread_number; i++) { pthread_create(&workers[i], nullptr, gcWorker, &parms[i]); } for (int i = 0; i < thread_number; i++) { pthread_join(workers[i], nullptr); // string outstr = output[i].str(); //cout << outstr; } cout << "garbage collection done ..." << endl; } void Permutate() { for (size_t k = 0; k < thread_number; k++) { std::random_shuffle(loads + (k) * total_count / thread_number, loads + (k + 1) * total_count / thread_number); } } void *measureWorker(void *args) { Tracer tracer; tracer.startTime(); struct target *work = (struct target *) args; uint64_t hit = 0; uint64_t fail = 0; long elipsed; uint64_t k = work->tid; auto hybrid_log_persistence_callback = [](Status result, uint64_t persistent_serial_num) { if (result != Status::Ok) { printf("Thread %" PRIu32 " reports checkpoint failed.\n", Thread::id()); } else { printf("Thread %" PRIu32 " reports persistence until %" PRIu64 "\n", Thread::id(), persistent_serial_num); } }; store.StartSession(); // while (stopMeasure.load(memory_order_relaxed) == 0) { #if LOCAL_TYPE == 0 for (uint64_t i = (k) * total_count / thread_number; i < (k + 1) * total_count / thread_number; i++) { #elif LOCAL_TYPE == 1 for (uint64_t i = 0; i < localloads[k].size(); i++) { #endif if (!work->firstround && work->read) { auto callback = [](IAsyncContext *ctxt, Status result) { CallbackContext<ReadContext> context{ctxt}; }; #if CONTEXT_TYPE == 0 uint64_t load; #if LOCAL_TYPE == 0 load=loads[i]; #elif LOCAL_TYPE == 1 load = localloads[k][i]; #endif ReadContext context{load}; //ReadContext context{(i + startoff) % total_count}; Status result = store.Read(context, callback, 1); if (result == Status::Ok) hit++; else fail++; #elif CONTEXT_TYPE == 2 ReadContext context(loads[i]); Status result = store.Read(context, callback, 1); if (result == Status::Ok && *(uint64_t *) (context.output_bytes) == total_count - loads[i]) hit++; else fail++; #endif } else { auto callback = [](IAsyncContext *ctxt, Status result) { CallbackContext<UpsertContext> context{ctxt}; }; uint64_t load; #if LOCAL_TYPE == 0 if (work->firstround) load = i; else load = loads[i]; #elif LOCAL_TYPE == 1 load = localloads[k][i]; #endif #if CONTEXT_TYPE == 0 UpsertContext context{load, load}; //UpsertContext context{(i + startoff) % total_count, (i + startoff) % total_count}; #elif CONTEXT_TYPE == 2 UpsertContext context(loads[i], 8); context.reset((uint8_t *) (content + i)); #endif //Status stat = store.Upsert(context, callback, 1); Status stat = store.UpsertT(context, callback, 1, parallellog ? thread_number : 1); if (stat == Status::NotFound) fail++; else hit++; } /* if (i % kCompletePendingInterval == 0) { store.CompletePending(false); } else if (i % kRefreshInterval == 0) { store.Refresh(); } if (i % kCheckpointInterval == 0) { Guid token; if (store.Checkpoint(nullptr, hybrid_log_persistence_callback, token)) printf("Thread= %d Calling Checkpoint(), token = %s\n", work->tid, token.ToString().c_str()); } */ } // } store.StopSession(); //long elipsed; elipsed = tracer.getRunTime(); output[work->tid] << work->tid << " " << elipsed << " " << hit << endl; __sync_fetch_and_add(&total_time, elipsed); __sync_fetch_and_add(&success, hit); __sync_fetch_and_add(&failure, fail); } void prepare() { cout << "prepare" << endl; workers = new pthread_t[thread_number]; parms = new struct target[thread_number]; output = new stringstream[thread_number]; for (uint64_t i = 0; i < thread_number; i++) { parms[i].tid = i; parms[i].store = &store; parms[i].insert = (uint64_t *) calloc(total_count / thread_number, sizeof(uint64_t *)); char buf[DEFAULT_STR_LENGTH]; for (int j = 0; j < total_count / thread_number; j++) { std::sprintf(buf, "%d", i + j * thread_number); parms[i].insert[j] = j; } } #if CONTEXT_TYPE == 2 content = new uint64_t[total_count]; for (long i = 0; i < total_count; i++) { content[i] = total_count - loads[i]; } #endif } void finish() { cout << "finish" << endl; for (int i = 0; i < thread_number; i++) { delete[] parms[i].insert; } delete[] parms; delete[] workers; delete[] output; #if CONTEXT_TYPE == 2 delete[] content; #endif } void multiWorkers(bool random, bool read, bool firstround = false) { output = new stringstream[thread_number]; #if ENABLE_NUMA == 1 int num_cpus = numa_num_task_cpus(); int num_sock = numa_max_node() + 1; numa_set_localalloc(); #endif Tracer tracer; tracer.startTime(); /* for (int i = 0; i < thread_number; i++) { pthread_create(&workers[i], nullptr, insertWorker, &parms[i]); } for (int i = 0; i < thread_number; i++) { pthread_join(workers[i], nullptr); } cout << "Insert " << exists << " " << tracer.getRunTime() << endl; */ Timer timer; timer.start(); for (int i = 0; i < thread_number; i++) { parms[i].random = random; parms[i].firstround = firstround; parms[i].read = read; pthread_create(&workers[i], nullptr, measureWorker, &parms[i]); #if ENABLE_NUMA == 1 cpu_set_t cpuset; CPU_ZERO(&cpuset); int group_threads = thread_number / num_sock; int group_cores = num_cpus / num_sock; CPU_SET(i / group_threads * group_cores + i % group_threads, &cpuset); pthread_setaffinity_np(workers[i], sizeof(cpu_set_t), &cpuset); #endif } //while (timer.elapsedSeconds() < timer_range) { // sleep(1); // } // stopMeasure.store(1, memory_order_relaxed); for (int i = 0; i < thread_number; i++) { pthread_join(workers[i], nullptr); string outstr = output[i].str(); cout << outstr; } cout << "Gathering ..." << endl; } int main(int argc, char **argv) { if (argc > 6) { thread_number = std::atol(argv[1]); key_range = std::atol(argv[2]); total_count = std::atol(argv[3]); rounds = std::atol(argv[4]); reading = (std::atoi(argv[5]) == 1 ? true : false); parallellog = (std::atoi(argv[6]) == 1 ? true : false); } cout << " threads: " << thread_number << " range: " << key_range << " count: " << total_count << " time: " << timer_range << " reading: " << reading << " parallellog: " << parallellog << endl; loads = (uint64_t *) calloc(total_count, sizeof(uint64_t)); for (int i = 0; i < total_count; i++) loads[i] = i; localloads = new std::vector<uint64_t>[thread_number]; for (int i = 0; i < total_count; i++) { uint64_t hash = Utility::GetHashCode(loads[i]); hash = hash % init_size; uint64_t lid = hash / (init_size / thread_number); localloads[lid].push_back(loads[i]); } Permutate(); //UniformGen<uint64_t>::generate(loads, key_range, total_count); prepare(); if (argc > 7) { //string str= reinterpret_cast<const char *>(std::atol(argv[5])); Guid token = Guid::Parse(argv[7]); RecoverAndTest(token, token); goto y; } // simpleInsert(); cout << "multiinsert" << endl; multiWorkers(false, false, true); cout << "operations: " << success << " failure: " << failure << " throughput: " << (double) (success + failure) * thread_number / total_time << endl; //cout << "simple read" << endl; //simpleRead(); //cout << "simple read" << endl; //simpleRead(); //cout<<"simple insert"<<endl; //simpleInsert1(); //cout << "simple read" << endl; //simpleRead(); #if LOCAL_TYPE == 1 for (size_t k = 0; k < thread_number; k++) { std::random_shuffle(localloads[k].begin(), localloads[k].end()); } #endif for (int i = 0; i < rounds; i++) { //stopMeasure.store(0); //multiPoints(); //RecoverAndTest(retoken, retoken); // Populate(); cout << "after checkpoint multiinsert" << endl; success = 0; failure = 0; total_time = 0; multiWorkers(false, false); cout << "operations: " << success << " failure: " << failure << " throughput: " << (double) (success + failure) * thread_number / total_time << endl; success = 0; failure = 0; total_time = 0; cout << "multiinsert" << endl; multiWorkers(true, reading); cout << "operations: " << success << " failure: " << failure << " throughput: " << (double) (success + failure) * thread_number / total_time << endl; stopMeasure.store(0); Tracer tra; tra.startTime(); //GC(); //cout << tra.getRunTime() << endl; } //stopMeasure.store(0); //GC(); //cout << "simple read" << endl; //simpleRead(); y: free(loads); finish(); return 0; }
31.923767
118
0.565576
yangzheng2115
c51363e83136d67b82ce6d7ef937ed8359e3b71b
1,018
cpp
C++
c/template/Template_Reverse.cpp
WeAreChampion/notes
6c0f726d1003e5083d9cf1b75ac6905dc1c19c07
[ "Apache-2.0" ]
2
2018-11-17T15:36:00.000Z
2022-03-16T09:01:16.000Z
c/template/Template_Reverse.cpp
WeAreChampion/notes
6c0f726d1003e5083d9cf1b75ac6905dc1c19c07
[ "Apache-2.0" ]
null
null
null
c/template/Template_Reverse.cpp
WeAreChampion/notes
6c0f726d1003e5083d9cf1b75ac6905dc1c19c07
[ "Apache-2.0" ]
null
null
null
#include<iostream> using namespace std; template<class Type> void Reverse(Type array[], int length) { for(int i = 0; i < length / 2; i++) { Type temp; temp = array[i]; array[i] = array[length - 1 - i]; array[length - 1 - i] = temp; } } template<class Type> void Reverse(Type array[], int start, int end) { for(int i = start; i <= (end + start) / 2; i++) { Type temp = array[i]; array[i] = array[start + end - i]; array[start + end - i] = temp; } } template<class Type> void DispArray(Type array[], int length) { for(int i = 0; i < length; i++) { cout<<array[i]<<" "; } cout<<endl; } void Test() { int length = 5; int array1[] = {1, 2, 3, 4, 5}; Reverse(array1, length); DispArray(array1, length); float array2[] = {1.1, 2.1, 3.1, 4.1, 5.1}; Reverse(array2, length); DispArray(array2, length); double array3[] = {1.11, 2.11, 3.11, 4.11, 5.11}; Reverse(array3, length); DispArray(array3, length); Reverse(array3, 1, 4); DispArray(array3, length); } int main() { Test(); return 0; }
22.130435
50
0.600196
WeAreChampion
c5149b1ab96144b9c0660b342b4cf0bb4b3ada12
19,329
cpp
C++
src/freeSurface.cpp
krenzland/FreeSurfaceLBM
5619edcf318623c3a4feac478db66663687bca94
[ "MIT" ]
8
2017-12-12T19:39:29.000Z
2022-02-03T13:37:53.000Z
src/freeSurface.cpp
krenzland/FreeSurfaceLBM
5619edcf318623c3a4feac478db66663687bca94
[ "MIT" ]
1
2020-07-23T13:51:06.000Z
2020-07-23T20:16:56.000Z
src/freeSurface.cpp
krenzland/FreeSurfaceLBM
5619edcf318623c3a4feac478db66663687bca94
[ "MIT" ]
3
2019-05-09T07:50:48.000Z
2020-11-05T12:28:43.000Z
#include "freeSurface.hpp" #include <iostream> #include <numeric> double computeFluidFraction(const std::vector<double> &fluidFraction, const std::vector<flag_t> &flags, int idx, const std::vector<double> &mass) { if (flags[idx] == flag_t::EMPTY) { return 0.0; } else if (flags[idx] == flag_t::INTERFACE) { const double vof = fluidFraction[idx]; // in some cases it can be negative or larger than 1, e.g. if the cell is recently filled. return std::min(1.0, std::max(0.0, vof)); } else { return 1.0; } } std::array<double, 3> computeSurfaceNormal(const std::vector<double> &fluidFraction, const coord_t &length, const std::vector<double> &mass, const coord_t &position, const std::vector<flag_t> &flags) { auto normal = std::array<double, 3>(); // We approximate the surface normal element-wise using central-differences of the fluid // fraction gradient. for (size_t dim = 0; dim < normal.size(); ++dim) { coord_t curPosition = position; // We need the next and previous neighbour for dimension dim. curPosition[dim]++; const auto nextNeighbour = indexForCell(curPosition, length); curPosition[dim] -= 2; const auto prevNeighbour = indexForCell(curPosition, length); const double plusFluidFraction = computeFluidFraction(fluidFraction, flags, nextNeighbour, mass); const double minusFluidFraction = computeFluidFraction(fluidFraction, flags, prevNeighbour, mass); normal[dim] = 0.5 * (minusFluidFraction - plusFluidFraction); } return normal; } void streamMass(const std::vector<double> &distributions, std::vector<double> &fluidFraction, const coord_t &length, std::vector<double> &mass, const std::vector<neighborhood_t> &neighborhood, const std::vector<flag_t> &flags) { #pragma omp parallel for schedule(static) for (int z = 0; z < length[2] + 2; ++z) { for (int y = 0; y < length[1] + 2; ++y) { for (int x = 0; x < length[0] + 2; ++x) { double deltaMass = 0.0; const coord_t curCell = coord_t{x, y, z}; const int flagIndex = indexForCell(curCell, length); // We only consider the mass going into interface cells. // Empty cells have zero mass, full cells have mass 1. if (flags[flagIndex] != flag_t::INTERFACE) continue; const int fieldIndex = flagIndex * Q; const double curFluidFraction = computeFluidFraction(fluidFraction, flags, flagIndex, mass); for (int i = 0; i < Q; ++i) { const auto &vel = LATTICEVELOCITIES[i]; const auto neighCell = coord_t{x + vel[0], y + vel[1], z + vel[2]}; const auto neighFlag = indexForCell(neighCell, length); const auto neighField = neighFlag * Q; if (neighFlag == flagIndex) continue; if (flags[neighFlag] == flag_t::FLUID) { // Exchange interface and fluid at x + \Delta t e_i (eq. 4.2) deltaMass += distributions[neighField + inverseVelocityIndex(i)] - distributions[fieldIndex + i]; } else if (flags[neighFlag] == flag_t::INTERFACE) { const double neighFluidFraction = computeFluidFraction(fluidFraction, flags, neighFlag, mass); // Exchange interface and interface at x + \Delta t e_i (eq. 4.2) const double s_e = calculateSE(distributions, flags, curCell, length, i, neighborhood); deltaMass += s_e * 0.5 * (curFluidFraction + neighFluidFraction); } } mass[flagIndex] += deltaMass; // (eq. 4.4) } } } } double calculateSE(const std::vector<double> &distributions, const std::vector<flag_t> &flags, const coord_t &coord, const coord_t &length, const int curFiIndex, const std::vector<neighborhood_t> &neighborhood) { // Returns a slightly different mass exchange depending on the neighbourhood of the cells. // This reduces the amount of abandoned interface cells. const auto &vel = LATTICEVELOCITIES[curFiIndex]; const auto neigh = coord_t{coord[0] + vel[0], coord[1] + vel[1], coord[2] + vel[2]}; const int curFlag = indexForCell(coord, length); const int neighFlag = indexForCell(neigh, length); const int curCell = curFlag * Q; const int neighCell = neighFlag * Q; const int inv = inverseVelocityIndex(curFiIndex); if (neighborhood[curFlag] == neighborhood[neighFlag]) { return distributions[neighCell + inv] - distributions[curCell + curFiIndex]; } if ((neighborhood[neighFlag] == neighborhood_t::STANDARD && neighborhood[curFlag] == neighborhood_t::NO_FLUID_NEIGHBORS) || (neighborhood[neighFlag] == neighborhood_t::NO_EMPTY_NEIGHBORS && (neighborhood[curFlag] == neighborhood_t::STANDARD || neighborhood[curFlag] == neighborhood_t::NO_FLUID_NEIGHBORS))) { return -distributions[curCell + curFiIndex]; } // Otherwise: (neigh == STANDARD && cur = NO_EMPTY) || (neigh = NO_FLUID && (cur = STANDARD || // cur NO_EMPTY) return distributions[neighCell + inv]; } void getPotentialUpdates(const std::vector<double> &mass, std::vector<double> &fluidFraction, std::vector<flag_t> &flags, std::vector<neighborhood_t> &neighborhood, const coord_t &length) { // Check whether we have to convert the interface to an emptied or fluid cell. // Doesn't actually update the flags but pushes them to a queue. // We do this here so we do not have to calculate the density again. // Offset avoids periodically switching between filled and empty status. const double offset = 10e-3; #pragma omp parallel for schedule(guided) for (int z = 0; z < length[2] + 2; ++z) { for (int y = 0; y < length[1] + 2; ++y) { for (int x = 0; x < length[0] + 2; ++x) { auto coord = coord_t{x, y, z}; const int flagIndex = indexForCell(coord, length); if (flags[flagIndex] != flag_t::INTERFACE) continue; // Eq. 4.7 double curDensity; if (fluidFraction[flagIndex] != 0.0) { curDensity = mass[flagIndex] / fluidFraction[flagIndex]; } else { curDensity = 0.0; } if (mass[flagIndex] > (1 + offset) * curDensity) { flags[flagIndex] = flag_t::INTERFACE_TO_FLUID; } else if (mass[flagIndex] < -offset * curDensity) { // Emptied flags[flagIndex] = flag_t::INTERFACE_TO_EMPTY; } if (neighborhood[flagIndex] == neighborhood_t::NO_FLUID_NEIGHBORS && mass[flagIndex] < (0.1 * curDensity)) { flags[flagIndex] = flag_t::INTERFACE_TO_EMPTY; } if (neighborhood[flagIndex] == neighborhood_t::NO_EMPTY_NEIGHBORS && mass[flagIndex] > (0.9 * curDensity)) { flags[flagIndex] = flag_t::INTERFACE_TO_FLUID; } } } } } void interpolateEmptyCell(std::vector<double> &distributions, std::vector<double> &mass, std::vector<double> &fluidFraction, const coord_t &coord, const coord_t &length, const std::vector<flag_t> &flags) { // Note: We only interpolate cells that are not emptied cells themselves! const int flagIndex = indexForCell(coord, length); const int cellIndex = flagIndex * Q; int numNeighs = 0; double avgDensity = 0.0; auto avgVel = std::array<double, 3>{}; for (int i = 0; i < Q; ++i) { const auto &vel = LATTICEVELOCITIES[i]; const auto neigh = coord_t{coord[0] + vel[0], coord[1] + vel[1], coord[2] + vel[2]}; const int neighFlagIndex = indexForCell(neigh, length); if (neighFlagIndex == flagIndex) continue; // Ignore current cell! // Don't interpolate cells that are emptied or filled. if (flags[neighFlagIndex] == flag_t::FLUID || flags[neighFlagIndex] == flag_t::INTERFACE || flags[neighFlagIndex] == flag_t::INTERFACE_TO_FLUID) { const int neighDistrIndex = neighFlagIndex * Q; const double neighDensity = computeDensity(&distributions[neighDistrIndex]); std::array<double, 3> neighVelocity; computeVelocity(&distributions[neighDistrIndex], neighDensity, neighVelocity.data()); ++numNeighs; avgDensity += neighDensity; avgVel[0] += neighVelocity[0]; avgVel[1] += neighVelocity[1]; avgVel[2] += neighVelocity[2]; } } // Every former empty cell has at least one interface cell as neighbour, otherwise we have a // worse problem than division by zero. assert(numNeighs != 0); avgDensity /= numNeighs; avgVel[0] /= numNeighs; avgVel[1] /= numNeighs; avgVel[2] /= numNeighs; fluidFraction[flagIndex] = mass[flagIndex] / avgDensity; auto feq = std::array<double, 19>{}; computeFeq(avgDensity, avgVel.data(), feq.data()); for (int i = 0; i < Q; ++i) { distributions[cellIndex + i] = feq[i]; } } void flagReinit(std::vector<double> &distributions, std::vector<double> &mass, std::vector<double> &fluidFraction, const coord_t &length, std::vector<flag_t> &flags) { // We set up the interface cells around all converted cells. // It's very important to do this in a way such that the order of conversion doesn't matter. // First set interface for all filled cells. #pragma omp parallel for schedule(guided) for (int z = 1; z < length[2] + 1; ++z) { for (int y = 1; y < length[1] + 1; ++y) { for (int x = 1; x < length[0] + 1; ++x) { const int curFlag = indexForCell(x, y, z, length); if (flags[curFlag] != flag_t::INTERFACE_TO_FLUID) continue; // Find all neighbours of this cell. for (const auto &vel : LATTICEVELOCITIES) { coord_t neighbor = {x, y, z}; neighbor[0] += vel[0]; neighbor[1] += vel[1]; neighbor[2] += vel[2]; const int neighFlag = indexForCell(neighbor, length); if (curFlag == neighFlag) continue; // This neighbor is converted to an interface cell iff. it is an empty cell or a // cell that would // become an emptied cell. // We need to remove it from the emptied set, otherwise we might have holes in // the interface. if (flags[neighFlag] == flag_t::EMPTY) { flags[neighFlag] = flag_t::INTERFACE; mass[neighFlag] = 0.0; fluidFraction[neighFlag] = 0.0; // Notice that the new interface cells don't have any valid distributions. // They are initialised with f^{eq}_i (p_{avg}, v_{avg}), which are the // average density and // velocity of all neighbouring fluid and interface cells. interpolateEmptyCell(distributions, mass, fluidFraction, neighbor, length, flags); } else if (flags[neighFlag] == flag_t::INTERFACE_TO_EMPTY) { // Already is an interface but should not be converted to an empty cell // later. flags[neighFlag] = flag_t::INTERFACE; } } } } } // Now we can consider all filled cells! #pragma omp parallel for schedule(guided) for (int z = 1; z < length[2] + 1; ++z) { for (int y = 1; y < length[1] + 1; ++y) { for (int x = 1; x < length[0] + 1; ++x) { const int curFlag = indexForCell(x, y, z, length); // Find all neighbours of this cell. if (flags[curFlag] != flag_t::INTERFACE_TO_EMPTY) continue; for (const auto &vel : LATTICEVELOCITIES) { coord_t neighbor = {x, y, z}; neighbor[0] += vel[0]; neighbor[1] += vel[1]; neighbor[2] += vel[2]; const int neighFlag = indexForCell(neighbor, length); if (curFlag == neighFlag) continue; // This neighbor is converted to an interface cell iff. it is an empty cell or a // cell that would // become an emptied cell. // We need to remove it from the emptied set, otherwise we might have holes in // the interface. if (flags[neighFlag] == flag_t::FLUID) { flags[neighFlag] = flag_t::INTERFACE; mass[neighFlag] = computeDensity(&distributions[neighFlag * Q]); fluidFraction[neighFlag] = 1.0; // We can reuse the distributions as they are still valid. } } } } } } enum class update_t { FILLED, EMPTIED }; void distributeSingleMass(const std::vector<double> &distributions, std::vector<double> &mass, std::vector<double> &massChange, const coord_t &length, const coord_t &coord, std::vector<flag_t> &flags, std::vector<double> &fluidFraction, const update_t &type) { // First determine how much mass needs to be redistributed and fix mass of converted cell. const int flagIndex = indexForCell(coord, length); double excessMass; const double density = computeDensity(&distributions[flagIndex * Q]); if (type == update_t::FILLED) { // Interface -> Full cell, filled cells have mass and should have a mass equal to their // density. excessMass = mass[flagIndex] - density; #pragma omp atomic massChange[flagIndex] -= excessMass; } else { // Interface -> Empty cell, empty cells should not have any mass so all mass is excess mass. excessMass = mass[flagIndex]; #pragma omp atomic massChange[flagIndex] -= excessMass; } /* The distribution of excess mass is surprisingly non-trivial. For a more detailed description, refer to pages 32f. of Thürey's thesis but here's the gist: We do not distribute the mass uniformly to all neighbouring interface cells but rather correct for balance. The reason for this is that the fluid interface moved beyond the current cell. We rebalance things by weighting the mass updates according to the direction of the interface normal. This has to be done in two steps, we first calculate all updated weights, normalize them and then, in a second step, update the weights.*/ // Step 1: Calculate the unnormalized weights. const auto normal = computeSurfaceNormal(fluidFraction, length, mass, coord, flags); std::array<double, 19> weights{}; std::array<double, 19> weightsBackup{}; // Sometimes first weights is all zero. for (size_t i = 0; i < LATTICEVELOCITIES.size(); ++i) { const auto &vel = LATTICEVELOCITIES[i]; coord_t neighbor = {coord[0] + vel[0], coord[1] + vel[1], coord[2] + vel[2]}; const int neighFlag = indexForCell(neighbor, length); if (flagIndex == neighFlag || flags[neighFlag] != flag_t::INTERFACE) continue; weightsBackup[i] = 1.0; const double dotProduct = normal[0] * vel[0] + normal[1] * vel[1] + normal[2] * vel[2]; if (type == update_t::FILLED) { weights[i] = std::max(0.0, dotProduct); } else { // EMPTIED weights[i] = -std::min(0.0, dotProduct); } assert(weights[i] >= 0.0); } // Step 2: Calculate normalizer (otherwise sum of weights != 1.0) double normalizer = std::accumulate(weights.begin(), weights.end(), 0.0, std::plus<double>()); if (normalizer == 0.0) { // Mass cannot be distributed along the normal, distribute to all interface cells equally. weights = weightsBackup; normalizer = std::accumulate(weights.begin(), weights.end(), 0.0, std::plus<double>()); } if (normalizer == 0.0) { return; } // Step 3: Redistribute weights. As non-interface cells have weight 0, we can just loop through // all cells. for (size_t i = 0; i < LATTICEVELOCITIES.size(); ++i) { const auto &vel = LATTICEVELOCITIES[i]; coord_t neighbor = {coord[0] + vel[0], coord[1] + vel[1], coord[2] + vel[2]}; const int neighFlag = indexForCell(neighbor, length); #pragma omp atomic massChange[neighFlag] += (weights[i] / normalizer) * excessMass; } } void distributeMass(const std::vector<double> &distributions, std::vector<double> &mass, const coord_t &length, std::vector<flag_t> &flags, std::vector<double> &fluidFraction) { // Here we redistribute the excess mass of the cells. // It is important that we get a copy of the filled/emptied where all converted cells are stored // and no other cells. // This excludes emptied cells that are used as interface cells instead! auto massChange = std::vector<double>(mass.size(), 0.0); #pragma omp parallel for schedule(guided) for (int z = 1; z < length[2] + 1; ++z) { for (int y = 1; y < length[1] + 1; ++y) { for (int x = 1; x < length[0] + 1; ++x) { const int curFlag = indexForCell(x, y, z, length); const coord_t coord = {x, y, z}; if (flags[curFlag] == flag_t::INTERFACE_TO_FLUID) { distributeSingleMass(distributions, mass, massChange, length, coord, flags, fluidFraction, update_t::FILLED); flags[curFlag] = flag_t::FLUID; } else if (flags[curFlag] == flag_t::INTERFACE_TO_EMPTY) { distributeSingleMass(distributions, mass, massChange, length, coord, flags, fluidFraction, update_t::EMPTIED); flags[curFlag] = flag_t::EMPTY; } } } } #pragma omp parallel for schedule(static) for (size_t i = 0; i < mass.size(); ++i) { const double curDensity = computeDensity(&distributions[i * Q]); mass[i] += massChange[i]; fluidFraction[i] = mass[i] / curDensity; } }
47.143902
140
0.569197
krenzland
c515da3d7291436f423257dc94f38d5e3e9913b8
2,874
cpp
C++
tool/keyinfo.cpp
drypot/san-2.x
44e626793b1dc50826ba0f276d5cc69b7c9ca923
[ "MIT" ]
5
2019-12-27T07:30:03.000Z
2020-10-13T01:08:55.000Z
tool/keyinfo.cpp
drypot/san-2.x
44e626793b1dc50826ba0f276d5cc69b7c9ca923
[ "MIT" ]
null
null
null
tool/keyinfo.cpp
drypot/san-2.x
44e626793b1dc50826ba0f276d5cc69b7c9ca923
[ "MIT" ]
1
2020-07-27T22:36:40.000Z
2020-07-27T22:36:40.000Z
/* keyinfo.cpp 1995.08.18 */ #include <pub/config.hpp> #include <pub/common.hpp> #include <pub/misc.hpp> LRESULT CALLBACK _export WndProcpcs_main(HWND, UINT, WPARAM, LPARAM); void pcs_main() { HWND hWnd; MSG msg; WNDCLASS wndclass; wndclass.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW; wndclass.lpfnWndProc = WndProcpcs_main; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = hInstance; wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndclass.lpszMenuName = NULL; wndclass.hbrBackground = get_StockObject(BLACK_BRUSH); wndclass.lpszClassName = "Winpcs_main"; RegisterClass(&wndclass); hWnd = CreateWindow ( "Winpcs_main", "Key Info", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL ); ShowWindow(hWnd, nCmdShow); while (get_Message(&msg, 0, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; } HDC hdcGlobal; #pragma argsused BOOL Winpcs_main_Create (HWND hWnd, LPCREATESTRUCT lpCreateStrct) { hdcGlobal = get_DC(hWnd); set_TextColor(hdcGlobal,RGB(200,200,200)); set_BkColor(hdcGlobal,RGB(0,0,0)); return def_true; } #pragma argsused void Winpcs_main_Destory (HWND hWnd) { PostQuitMessage(0); } #pragma argsused void Winpcs_main_KeySub (HWND hWnd, UINT vk, BOOL fDown, int cRepeat, UINT flags, char* type) { static int y; char buf[80]; RECT rc; if (fDown) { get_ClientRect(hWnd,&rc); if (y+20 > rc.bottom) { y=0; InvalidateRect(hWnd,&rc,def_true); UpdateWindow(hWnd); } TextOut(hdcGlobal,5,y,buf,sprintf(buf,"%s vk=%02x scan=%02x fExtended=%x",type,(int)vk,(int)(byte)flags,(int)((flags >> 8)&1))); y += 20; } } #pragma argsused void Winpcs_main_Key (HWND hWnd, UINT vk, BOOL fDown, int cRepeat, UINT flags) { Winpcs_main_KeySub(hWnd,vk,fDown,cRepeat,flags,"Normal"); } #pragma argsused void Winpcs_main_SysKey (HWND hWnd, UINT vk, BOOL fDown, int cRepeat, UINT flags) { Winpcs_main_KeySub(hWnd,vk,fDown,cRepeat,flags,"System"); } void Winpcs_main_Paint(HWND hwnd) { PAINTSTRUCT ps; BeginPaint(hwnd,&ps); EndPaint(hwnd,&ps); } LRESULT CALLBACK __export WndProcpcs_main (HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { HANDLE_MSG(hWnd, WM_CREATE, Winpcs_main_Create); HANDLE_MSG(hWnd, WM_KEYDOWN, Winpcs_main_Key); HANDLE_MSG(hWnd, WM_KEYUP, Winpcs_main_Key); HANDLE_MSG(hWnd, WM_SYSKEYDOWN, Winpcs_main_SysKey); HANDLE_MSG(hWnd, WM_SYSKEYUP, Winpcs_main_SysKey); HANDLE_MSG(hWnd, WM_PAINT, Winpcs_main_Paint); HANDLE_MSG(hWnd, WM_DESTROY, Winpcs_main_Destory); } return DefWindowProc(hWnd, msg, wParam, lParam); }
21.772727
134
0.691371
drypot
c51bd70ec717e6f7785a0665fb5ea391712fc42d
16,884
cpp
C++
tests/TestAppMain.cpp
jakjinak/jj
d1d49cd75a63b7ec2b2497ed061e8c1145ff2eb7
[ "MIT" ]
null
null
null
tests/TestAppMain.cpp
jakjinak/jj
d1d49cd75a63b7ec2b2497ed061e8c1145ff2eb7
[ "MIT" ]
null
null
null
tests/TestAppMain.cpp
jakjinak/jj
d1d49cd75a63b7ec2b2497ed061e8c1145ff2eb7
[ "MIT" ]
null
null
null
#include "jj/gui/application.h" #include "jj/gui/window.h" #include "jj/gui/textLabel.h" #include "jj/gui/textInput.h" #include "jj/gui/comboBox.h" #include "jj/gui/tree.h" #include "jj/gui/button.h" #include "jj/gui/sizer.h" #include "jj/stream.h" #include <sstream> #include "jj/directories.h" class myTreeThing : public jj::gui::treeItem_T<myTreeThing> { typedef jj::gui::treeItem_T<myTreeThing> base_t; typedef jj::gui::tree_T<myTreeThing> CTRL; public: myTreeThing(CTRL& parent, id_t id) : base_t(parent, id) {} }; class treetest : public jj::gui::dialog_t { jj::gui::tree_T<myTreeThing>* tree; jj::gui::textInput_t* name, *log; jj::gui::button_t* add, *remove, *dump; jj::gui::boxSizer_t* right, *sadd, *srem; void onAdd(jj::gui::button_t&) { myTreeThing* i = tree->selected(); if (i == nullptr) dolog(jjT("Nothing selected, nothing added.")); i->add(name->text()); dolog(jjT("Added [") + name->text() + jjT("]")); } void onRemove(jj::gui::button_t&) { myTreeThing* i = tree->selected(); if (i == nullptr) { dolog(jjT("Nothing selected, nothing removed.")); return; } if (i->id() == tree->root().id()) { dolog(jjT("Root selected, nothing removed.")); return; } myTreeThing* p = i->parent_item(); if (p == nullptr) { dolog(jjT("Something weird happened!")); return; } p->remove(*i); } void doDump(myTreeThing& t, jj::string_t& buf) { buf += t.text(); buf += jjT("{"); for (size_t i = 0; i < t.count(); ++i) doDump(t.get(i), buf); buf += jjT("}"); } void onDump(jj::gui::button_t&) { jj::string_t buf; doDump(tree->root(), buf); dolog(buf); } bool beforeSelect(myTreeThing& x, myTreeThing* o) { dolog(jjT("Querying selection of [") + x.text() + jjT("], previous was [") + (o == nullptr ? jj::string_t(jjT("<NONE>")) : o->text()) + jjT("]")); if (x.text() == jjT("NEE")) { dolog(jjT("VETO!")); return false; } return true; } void onSelect(myTreeThing& x, myTreeThing* o) { dolog(jjT("Selected [") + x.text() + jjT("], previous was [") + (o == nullptr ? jj::string_t(jjT("<NONE>")) : o->text()) + jjT("]")); } void onActivate(myTreeThing& x) { x.bold(!x.bold()); x.bold() ? x.expand() : x.collapse(); } public: treetest(jj::gui::topLevelWindow_t& main) : jj::gui::dialog_t(main, jj::gui::dialog_t::options() << jj::opt::text(jjT("GUI Tree test")) << jj::opt::size(400, 800) << jj::gui::dialog_t::RESIZEABLE) { using namespace jj; using namespace jj::gui; OnCreateSizer = [this] { return new boxSizer_t(*this, boxSizer_t::HORIZONTAL); }; tree = new tree_T<myTreeThing>(*this, jj::gui::tree_T<myTreeThing>::options() << opt::text(jjT("ROOT"))); tree->BeforeSelect.add(*this, &treetest::beforeSelect); tree->OnSelect.add(*this, &treetest::onSelect); tree->OnActivate.add(*this, &treetest::onActivate); name = new textInput_t(*this, textInput_t::options()); log = new textInput_t(*this, textInput_t::options() << textInput_t::MULTILINE); add = new button_t(*this, button_t::options() << opt::text(jjT("Add"))); add->OnClick.add(*this, &treetest::onAdd); remove = new button_t(*this, button_t::options() << opt::text(jjT("Remove"))); remove->OnClick.add(*this, &treetest::onRemove); dump = new button_t(*this, button_t::options() << opt::text(jjT("Dump"))); dump->OnClick.add(*this, &treetest::onDump); sizer().add(*tree, sizerFlags_t().proportion(2).expand()); sizer().add(*(right = new jj::gui::boxSizer_t(*this, boxSizer_t::VERTICAL)), sizerFlags_t().proportion(1).expand()); right->add(*(sadd = new jj::gui::boxSizer_t(*this, boxSizer_t::HORIZONTAL)), sizerFlags_t().expand()); right->add(*(srem = new jj::gui::boxSizer_t(*this, boxSizer_t::HORIZONTAL)), sizerFlags_t().expand()); sadd->add(*name, sizerFlags_t().expand()); sadd->add(*add, sizerFlags_t()); srem->add(*remove, sizerFlags_t()); srem->add(*dump, sizerFlags_t()); right->add(*log, sizerFlags_t().expand().proportion(1)); } void dolog(const jj::string_t& txt) { auto ct = log->text(); if (ct.empty()) log->changeText(txt); else log->changeText(txt + jjT('\n') + ct); } }; class wnd : public jj::gui::frame_t { jj::gui::textInput_t* t1, *t2; jj::gui::button_t* b1, *b2, *b3, *b4; jj::gui::boxSizer_t* s1, *s2; jj::gui::dialog_t* dlg; void onb1(jj::gui::button_t&) { if (!o) return; if (o->isShown()) o->hide(); else o->show(); } void onb2(jj::gui::button_t&) { if (!o) return; o->close(); o = nullptr; } static jj::gui::statusBar_t::style_t cycleSB(jj::gui::statusBar_t::style_t style) { using namespace jj::gui; switch (style) { case statusBar_t::RAISED: return statusBar_t::FLAT; case statusBar_t::FLAT: return statusBar_t::SUNKEN; default: return statusBar_t::RAISED; } } void onb3(jj::gui::button_t&) { status_bar().style(2, cycleSB(status_bar().style(2))); } void onb4(jj::gui::button_t& b) { if (b.text() == jjT("B4 A")) b.text(jjT("B4 B")); else b.text(jjT("B4 A")); } void ontxt(jj::gui::textInput_t& x) { status_bar().text(x.text()); if (!o) return; o->title(x.text()); } void onradio(jj::gui::menuItem_t& x) { x.check(); } public: wnd(jj::gui::application_t& app) : jj::gui::frame_t(app, jj::gui::frame_t::options() << jj::opt::text(jjT("First One")) << jj::opt::size(600, 280) << jj::gui::frame_t::NO_MAXIMIZE) , o(nullptr), dlg(nullptr) { using namespace jj; using namespace jj::gui; OnCreateSizer = [this] { return new boxSizer_t(*this, boxSizer_t::VERTICAL); }; textLabel_t* st = new textLabel_t(*this, textLabel_t::options() << opt::text(jjT("ST"))); b1 = new button_t(*this, button_t::options() << opt::text(jjT("B1"))); b1->OnClick.add(*this, &wnd::onb1); b2 = new button_t(*this, button_t::options() << opt::text(jjT("B2")) << button_t::EXACT_FIT); b2->OnClick.add(*this, &wnd::onb2); b3 = new button_t(*this, button_t::options() << opt::text(jjT("B3")) << align_t::LEFT << alignv_t::BOTTOM); b3->OnClick.add(*this, &wnd::onb3); b4 = new button_t(*this, button_t::options() << opt::text(jjT("B4 A")) << button_t::EXACT_FIT << button_t::NO_BORDER); b4->OnClick.add(*this, &wnd::onb4); t1 = new textInput_t(*this, textInput_t::options() << opt::text(jjT("Child"))); t1->OnTextChange.add(*this, &wnd::ontxt); t2 = new textInput_t(*this, textInput_t::options() << textInput_t::MULTILINE); comboBox_t* cb = new comboBox_t(*this, { jjT("ABC"), jjT("XYZ"), jjT("123") }); cb->OnSelect.add([this](comboBox_t& x) { t2->changeText(jjT("Selected [") + x.text() + jjT("]")); }); sizer().add(*(s1 = new jj::gui::boxSizer_t(*this, boxSizer_t::HORIZONTAL)), sizerFlags_t().proportion(1).expand()); sizer().add(*(s2 = new jj::gui::boxSizer_t(*this, boxSizer_t::HORIZONTAL)), sizerFlags_t().proportion(3).expand()); s1->add(*st, sizerFlags_t().border(5)); s1->add(*b1, sizerFlags_t().set(align_t::CENTER)); s1->add(*b2, sizerFlags_t().set(align_t::CENTER)); s1->add(*b3, sizerFlags_t().set(align_t::CENTER).set(sizerFlags_t::EXPAND)); s1->add(*b4, sizerFlags_t().set(align_t::CENTER)); s1->add(*t1, sizerFlags_t().set(align_t::CENTER).proportion(1)); s1->add(*cb, sizerFlags_t().set(align_t::CENTER).proportion(1)); s2->add(*t2, sizerFlags_t().proportion(1).expand()); menu_t* m1, *m2, *m3, *m4, *mt; menu_bar().append(m1 = new menu_t(*this), jjT("TEST")); m1->append(menuItem_t::options() << opt::text(jjT("Current Dir"))).lock()->OnClick.add([this](menuItem_t&) { t2->changeText(jj::directories::current()); }); m1->append(menuItem_t::options() << opt::text(jjT("Program Dir"))).lock()->OnClick.add([this](menuItem_t&) { t2->changeText(jj::directories::program()); }); m1->append(menuItem_t::options() << opt::text(jjT("Program Path"))).lock()->OnClick.add([this](menuItem_t&) { t2->changeText(jj::directories::program(true)); }); m1->append(menuItem_t::options() << opt::text(jjT("Home Dir"))).lock()->OnClick.add([this](menuItem_t&) { t2->changeText(jj::directories::personal()); }); m1->append(menuItem_t::options() << opt::text(jjT("Home Dir2"))).lock()->OnClick.add([this](menuItem_t&) { t2->changeText(jj::directories::personal(true)); }); m1->append(menuItem_t::SEPARATOR); auto me = m1->append(menuItem_t::options() << opt::text(jjT("Exit")) << opt::accelerator(keys::accelerator_t(keys::ALT, keys::F4))); me.lock()->OnClick.add([this](menuItem_t&) { this->close(); }); menu_bar().append(m2 = new menu_t(*this), menuItem_t::submenu_options() << opt::text(jjT("actions"))); m2->append(m4 = new menu_t(*this), jjT("dialogs")); auto m41 = m4->append(menuItem_t::options() << menuItem_t::CHECK << opt::text(jjT("generic is modal"))); auto m42 = m4->append(menuItem_t::options() << opt::text(jjT("generic"))); m42.lock()->OnClick.add([this, m41](menuItem_t&) { this->dlg = new dialog_t(*this, dialog_t::options() << opt::text(jjT("The dialog"))); if (m41.lock()->checked()) this->dlg->show_modal(); else this->dlg->show(); }); m4->append(menuItem_t::options() << opt::text(jjT("delete generic"))) .lock()->OnClick.add([this](menuItem_t&) { delete this->dlg; this->dlg = nullptr; }); m4->append(menuItem_t::SEPARATOR); m4->append(menuItem_t::options() << opt::text(jjT("simple"))) .lock()->OnClick.add([this](menuItem_t&) { dlg::simple_t x(*this, jjT("So tell me now, what u want to do..."), jjT("Question for you"), dlg::simple_t::options() << stock::icon_t::ERR << stock::item_t::CANCEL, {/*stock::item_t::OK, */ stock::item_t::CANCEL, stock::item_t::YES }); modal_result_t result = x.show_modal(); if (result.isStock()) t2->text(jjS(jjT("The result was a stock result ") << int(result.stock()))); else t2->text(jjS(jjT("The result was a regular result ") << result.regular())); }); m4->append(menuItem_t::options() << opt::text(jjT("text input"))) .lock()->OnClick.add([this](menuItem_t&) { dlg::input_t x(*this, jjT("Give me text:"), dlg::input_t::options() << opt::text(jjT("default"))); modal_result_t result = x.show_modal(); if (result == stock::item_t::OK) t2->text(jjS(jjT("The result was a stock OK: '") << x.text() << jjT("'"))); else if (result == stock::item_t::CANCEL) t2->text(jjT("The result was a stock CANCEL")); else if (result.isStock()) t2->text(jjS(jjT("The result was a stock result ") << int(result.stock()))); else t2->text(jjS(jjT("The result was a regular result ") << result.regular())); }); m4->append(menuItem_t::options() << opt::text(jjT("password input"))) .lock()->OnClick.add([this](menuItem_t&) { dlg::input_t x(*this, jjT("Give me password:"), dlg::input_t::options() << dlg::input_t::PASSWORD); modal_result_t result = x.show_modal(); if (result == stock::item_t::OK) t2->text(jjS(jjT("The result was a stock OK: '") << x.text() << jjT("'"))); else if (result == stock::item_t::CANCEL) t2->text(jjT("The result was a stock CANCEL")); else if (result.isStock()) t2->text(jjS(jjT("The result was a stock result ") << int(result.stock()))); else t2->text(jjS(jjT("The result was a regular result ") << result.regular())); }); m4->append(menuItem_t::SEPARATOR); m4->append(menuItem_t::options() << opt::text(jjT("open"))) .lock()->OnClick.add([this](menuItem_t&) { dlg::openFile_t x(*this, dlg::openFile_t::options()); if (x.show_modal() == stock::item_t::OK) t2->text(jjS(jjT("[") << x.file() << jjT("] selected in dialog"))); }); m4->append(menuItem_t::options() << opt::text(jjT("open many"))) .lock()->OnClick.add([this](menuItem_t&) { dlg::openFile_t x(*this, dlg::openFile_t::options() << dlg::openFile_t::MULTIPLE << dlg::openFile_t::MUST_EXIST); if (x.show_modal() == stock::item_t::OK) { jj::string_t t; for (const jj::string_t& s : x.files()) t = t + jjT('[') + s + jjT("] "); if (t.empty()) t = jjT("Nothing "); t += jjT("selected in dialog"); t2->text(t); } }); m4->append(menuItem_t::options() << opt::text(jjT("save"))) .lock()->OnClick.add([this](menuItem_t&) { dlg::saveFile_t x(*this, dlg::saveFile_t::options() << dlg::saveFile_t::OVERWRITE); if (x.show_modal() == stock::item_t::OK) t2->text(jjS(jjT("[") << x.file() << jjT("] selected in dialog"))); }); m4->append(menuItem_t::options() << opt::text(jjT("get dir"))) .lock()->OnClick.add([this](menuItem_t&) { dlg::selectDir_t x(*this, dlg::selectDir_t::options()); if (x.show_modal() == stock::item_t::OK) t2->text(jjS(jjT("[") << x.dir() << jjT("] selected in dialog"))); }); m2->append(m3 = new menu_t(*this), jjT("sub")); auto m22 = m2->append(menuItem_t::options() << opt::text(jjT("M2")) << menuItem_t::CHECK); m2->append(menuItem_t::options() << opt::text(jjT("M3")) << menuItem_t::CHECK) .lock()->OnClick.add([this, m22, st](menuItem_t& i) { menuItem_t& mi = *m22.lock(); mi.enable(i.checked()); jj::string_t txt = mi.text(); if (txt.length() < 15) { mi.text(txt + jjT(" X")); st->text(st->text() + jjT(" X")); } else { mi.text(txt.substr(0, 2)); st->text(st->text().substr(0, 2)); } this->layout(); }); m2->append(menuItem_t::SEPARATOR); m2->append(menuItem_t::options() << opt::text(jjT("M4"))); auto m31 = m3->append(menuItem_t::options() << opt::text(jjT("S1")) << menuItem_t::RADIO); m31.lock()->OnClick.add(*this, &wnd::onradio); auto m32 = m3->append(menuItem_t::options() << opt::text(jjT("S2")) << menuItem_t::RADIO); m32.lock()->OnClick.add(*this, &wnd::onradio); menu_bar().append(mt = new menu_t(*this), jjT("TESTS")); mt->append(menuItem_t::options() << opt::text(jjT("Tree test"))).lock()->OnClick.add([this](menuItem_t&) { treetest x(*this); x.show_modal(); }); status_bar().set({ {jjT("status"), -1, statusBar_t::RAISED}, {jjT("---"), -2, statusBar_t::FLAT}, {jjT("enjoy"), 60, statusBar_t::SUNKEN} }); layout(); } ~wnd() { if (o) o->close(); } jj::gui::frame_t* o; }; class app : public jj::gui::application_t { wnd* f; bool ono(jj::gui::topLevelWindow_t&) { f->o = nullptr; return true; } virtual bool on_init() { //_CrtSetBreakAlloc(5684); f = new wnd(*this); f->show(); f->o = new jj::gui::frame_t(*this, jj::gui::frame_t::options() << jj::opt::text(jjT("Child")) << jj::gui::frame_t::NO_MINIMIZE); f->o->OnClose.add(*this, &app::ono); f->o->show(); return true; } }; app g_app;
43.181586
252
0.529377
jakjinak
c5210172b004b41944ea57f390439356a017af8a
12,696
cpp
C++
M5StickTest-IoTHub/src/main.cpp
tkopacz/2019M5StickC
1435fb81c4b2b52315eca82f2c824db5c412d946
[ "MIT" ]
null
null
null
M5StickTest-IoTHub/src/main.cpp
tkopacz/2019M5StickC
1435fb81c4b2b52315eca82f2c824db5c412d946
[ "MIT" ]
null
null
null
M5StickTest-IoTHub/src/main.cpp
tkopacz/2019M5StickC
1435fb81c4b2b52315eca82f2c824db5c412d946
[ "MIT" ]
null
null
null
/** * A simple Azure IoT example for sending telemetry. * Watchdog * Interupt on GPIO * Read almost all parameters from M5StickC * Commands: start | stop, ledon | ledoff, delay {"ms":1000} */ #include <Arduino.h> #include <M5StickC.h> #include <WiFi.h> #include <ArduinoJson.h> #include "Esp32MQTTClient.h" #include "esp32_rmt.h" #include "esp_task_wdt.h" //extern static IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle; // Please input the SSID and password of WiFi char *ssid = "xxxxxxxxxxxx"; char *password = "xxxxxxxxxxxx"; static const char *connectionString = "xxxxxxxxxxxx"; static bool hasIoTHub = false; int messageCount = 1; static bool hasWifi = false; static bool messageSending = true; static uint64_t send_interval_ms; int IntervalMs = 10000;//10000; #define DEVICE_ID "m5stickc01" #define MESSAGE_MAX_LEN 512 ESP32_RMT rem; ////////////////////////////////////////////////////////////////////////////////////////////////////////// static int callbackCounter; IOTHUB_CLIENT_LL_HANDLE iotHubClientHandle; IOTHUB_MESSAGE_HANDLE msg; int receiveContext = 0; static char propText[1024]; static IOTHUBMESSAGE_DISPOSITION_RESULT ReceiveMessageCallback(IOTHUB_MESSAGE_HANDLE message, void *userContextCallback) { int *counter = (int *)userContextCallback; const char *buffer; size_t size; MAP_HANDLE mapProperties; const char *messageId; const char *correlationId; const char *userDefinedContentType; const char *userDefinedContentEncoding; // Message properties if ((messageId = IoTHubMessage_GetMessageId(message)) == NULL) { messageId = "<null>"; } if ((correlationId = IoTHubMessage_GetCorrelationId(message)) == NULL) { correlationId = "<null>"; } if ((userDefinedContentType = IoTHubMessage_GetContentTypeSystemProperty(message)) == NULL) { userDefinedContentType = "<null>"; } if ((userDefinedContentEncoding = IoTHubMessage_GetContentEncodingSystemProperty(message)) == NULL) { userDefinedContentEncoding = "<null>"; } // Message content if (IoTHubMessage_GetByteArray(message, (const unsigned char **)&buffer, &size) != IOTHUB_MESSAGE_OK) { (void)printf("unable to retrieve the message data\r\n"); } else { (void)printf("Received Message [%d]\r\n Message ID: %s\r\n Correlation ID: %s\r\n Content-Type: %s\r\n Content-Encoding: %s\r\n Data: <<<%.*s>>> & Size=%d\r\n", *counter, messageId, correlationId, userDefinedContentType, userDefinedContentEncoding, (int)size, buffer, (int)size); } // Retrieve properties from the message mapProperties = IoTHubMessage_Properties(message); if (mapProperties != NULL) { const char *const *keys; const char *const *values; size_t propertyCount = 0; if (Map_GetInternals(mapProperties, &keys, &values, &propertyCount) == MAP_OK) { if (propertyCount > 0) { size_t index; printf(" Message Properties:\r\n"); for (index = 0; index < propertyCount; index++) { (void)printf("\tKey: %s Value: %s\r\n", keys[index], values[index]); } (void)printf("\r\n"); } } } /* Some device specific action code goes here... */ (*counter)++; return IOTHUBMESSAGE_ACCEPTED; } static int DeviceMethodCallback(const char *method_name, const unsigned char *payload, size_t size, unsigned char **response, size_t *resp_size, void *userContextCallback) { (void)userContextCallback; printf("\r\nDevice Method called\r\n"); printf("Device Method name: %s\r\n", method_name); printf("Device Method payload: %.*s\r\n", (int)size, (const char *)payload); int status = 200; char *RESPONSE_STRING = "{ \"Response\": \"OK\" }"; if (strcmp(method_name, "start") == 0) { messageSending = true; } else if (strcmp(method_name, "stop") == 0) { messageSending = false; } else if (strcmp(method_name, "delay") == 0) { StaticJsonDocument<200> doc; DeserializationError error = deserializeJson(doc, payload); // Test if parsing succeeds. if (error) { LogError("deserializeJson() failed: "); LogError(error.c_str()); RESPONSE_STRING = "\"deserializeJson() failed\""; status = 500; } else { IntervalMs = doc["ms"]; LogInfo("IntervalMs:%d", IntervalMs); } } else if (strcmp(method_name, "ledon") == 0) { digitalWrite(M5_LED, LOW); } else if (strcmp(method_name, "ledoff") == 0) { digitalWrite(M5_LED, HIGH); } else { LogInfo("No method %s found", method_name); RESPONSE_STRING = "\"No method found\""; status = 404; } printf("\r\nResponse status: %d\r\n", status); printf("Response payload: %s\r\n\r\n", RESPONSE_STRING); *resp_size = strlen(RESPONSE_STRING); if ((*response = (unsigned char *)malloc(*resp_size)) == NULL) { status = -1; } else { (void)memcpy(*response, RESPONSE_STRING, *resp_size); } return status; } static void SendConfirmationCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void *userContextCallback) { //Setup watchdog esp_task_wdt_reset(); //Passing address to IOTHUB_MESSAGE_HANDLE IOTHUB_MESSAGE_HANDLE *msg = (IOTHUB_MESSAGE_HANDLE *)userContextCallback; (void)printf("Confirmation %d result = %s\r\n", callbackCounter, ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result)); /* Some device specific action code goes here... */ callbackCounter++; if (result != IOTHUB_CLIENT_CONFIRMATION_OK) { esp_restart(); } //TK:Or caller IoTHubMessage_Destroy(*msg); } ////////////////////////////////////////////////////////////////////////////////////////////////////////// double vbat = 0.0; double discharge, charge; double temp = 0.0; double bat_p = 0.0; int16_t accX = 0; int16_t accY = 0; int16_t accZ = 0; int16_t gyroX = 0; int16_t gyroY = 0; int16_t gyroZ = 0; int16_t tempg = 0; int16_t coIn = 0, coOut = 0; double coD = 0, vin = 0, iin = 0; volatile int16_t bRST = 0, bHOME = 0; //Interupt void IRAM_ATTR isrHOME() { bHOME = 1; } void IRAM_ATTR isrRST() { bRST = 1; } void setup() { // initialize the M5StickC object M5.begin(); M5.Axp.begin(); M5.Axp.EnableCoulombcounter(); M5.Imu.Init(); M5.Lcd.begin(); rem.begin(M5_IR, true); pinMode(M5_BUTTON_HOME, INPUT_PULLUP); attachInterrupt(M5_BUTTON_HOME, isrHOME, FALLING); pinMode(M5_BUTTON_RST, INPUT_PULLUP); attachInterrupt(M5_BUTTON_RST, isrRST, FALLING); pinMode(M5_LED, OUTPUT); digitalWrite(M5_LED, HIGH); M5.Lcd.setCursor(0, 0, 1); M5.Lcd.println("WiFi"); Serial.println("Starting connecting WiFi."); delay(10); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); M5.Lcd.print("."); } hasWifi = true; Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); M5.Lcd.println(WiFi.localIP()); randomSeed(analogRead(0)); Serial.println(" > IoT Hub"); printf("Before platform_init\n"); if (platform_init() != 0) { (void)printf("Failed to initialize the platform.\r\n"); M5.Lcd.println("IoT Hub - error"); } else { printf("Before IoTHubClient_LL_CreateFromConnectionString\n"); if ((iotHubClientHandle = IoTHubClient_LL_CreateFromConnectionString(connectionString, MQTT_Protocol)) == NULL) { (void)printf("ERROR: iotHubClientHandle is NULL!\r\n"); } else { if (IoTHubClient_LL_SetMessageCallback(iotHubClientHandle, ReceiveMessageCallback, &receiveContext) != IOTHUB_CLIENT_OK) { (void)printf("ERROR: IoTHubClient_LL_SetMessageCallback..........FAILED!\r\n"); } if (IoTHubClient_LL_SetDeviceMethodCallback(iotHubClientHandle, DeviceMethodCallback, &receiveContext) != IOTHUB_CLIENT_OK) { (void)printf("ERROR: IoTHubClient_LL_SetDeviceMethodCallback..........FAILED!\r\n"); } } } hasIoTHub = true; M5.Lcd.println("IoT Hub - OK!"); delay(2000); send_interval_ms = millis(); } void loop() { if (hasWifi && hasIoTHub) { if (messageSending && (int)(millis() - send_interval_ms) >= IntervalMs) { //Read vbat = M5.Axp.GetVbatData() * 1.1 / 1000; charge = M5.Axp.GetIchargeData() / 2; discharge = M5.Axp.GetIdischargeData() / 2; temp = -144.7 + M5.Axp.GetTempData() * 0.1; bat_p = M5.Axp.GetPowerbatData() * 1.1 * 0.5 / 1000; coIn = M5.Axp.GetCoulombchargeData(); coOut = M5.Axp.GetCoulombdischargeData(); coD = M5.Axp.GetCoulombData(); vin = M5.Axp.GetVinData() * 1.7; iin = M5.Axp.GetIinData() * 0.625; M5.Lcd.setCursor(0, 0, 1); M5.Lcd.printf("vbat:%.3fV\r\n", vbat); M5.Lcd.printf("icharge:%fmA\r\n", charge); M5.Lcd.printf("idischg:%fmA\r\n", discharge); M5.Lcd.printf("temp:%.1fC\r\n", temp); M5.Lcd.printf("pbat:%.3fmW\r\n", bat_p); M5.Lcd.printf("CoIn :%d\r\n", coIn); M5.Lcd.printf("CoOut:%d\r\n", coOut); M5.Lcd.printf("CoD:%.2fmAh\r\n", coD); M5.Lcd.printf("Vin:%.3fmV\r\n", vin); M5.Lcd.printf("Iin:%.3fmA\r\n", iin); M5.IMU.getGyroData(&gyroX, &gyroY, &gyroZ); M5.IMU.getAccelData(&accX, &accY, &accZ); M5.IMU.getTempData(&tempg); M5.Lcd.printf("%.2f|%.2f\r\n%.2f\r\n", ((float)gyroX) * M5.IMU.gRes, ((float)gyroY) * M5.IMU.gRes, ((float)gyroZ) * M5.IMU.gRes); M5.Lcd.printf("%.2f|%.2f\r\n%.2f\r\n", ((float)accX) * M5.IMU.aRes, ((float)accY) * M5.IMU.aRes, ((float)accZ) * M5.IMU.aRes); M5.Lcd.printf("Tempg:%.2fC\r\n", ((float)tempg) / 333.87 + 21.0); M5.Lcd.printf("CNT:%d\r\n", messageCount); //bRST = (digitalRead(M5_BUTTON_RST) == LOW); //bHOME = (digitalRead(M5_BUTTON_HOME) == LOW); M5.Lcd.printf("%d %d\r\n", bRST, bHOME); // Send teperature data char messagePayload[MESSAGE_MAX_LEN]; snprintf( messagePayload, MESSAGE_MAX_LEN, "{" "\"deviceId\":\"%s\", \"messageId\":%d, " "\"vbat\":%.3f, \"icharge\":%f, \"idischg\":%f, \"temp\":%.1f, " "\"pbat\":%.3f, \"CoIn\":%d, \"CoOut\":%d, " "\"CoD\":%f, \"Vin\":%.3f, \"Iin\":%.3f, " "\"gyroX\":%.2f, \"gyroY\":%.2f, \"gyroZ\":%.2f, " "\"accX\":%.2f, \"accY\":%.2f, \"accZ\":%.2f, " "\"Tempg\":%.2f, " "\"bRTS\":%d, \"bHOME\":%d" "}", DEVICE_ID, messageCount++, vbat, charge, discharge, temp, bat_p, coIn, coOut, coD, vin, iin, ((float)gyroX) * M5.IMU.gRes, ((float)gyroY) * M5.IMU.gRes, ((float)gyroZ) * M5.IMU.gRes, ((float)accX) * M5.IMU.aRes, ((float)accY) * M5.IMU.aRes, ((float)accZ) * M5.IMU.aRes, ((float)tempg) / 333.87 + 21.0, bRST, bHOME); Serial.println(messagePayload); if ((msg = IoTHubMessage_CreateFromByteArray((const unsigned char *)messagePayload, strlen(messagePayload))) == NULL) { (void)printf("ERROR: iotHubMessageHandle is NULL!\r\n"); } else { (void)IoTHubMessage_SetMessageId(msg, "MSG_ID"); //(void)IoTHubMessage_SetCorrelationId(msg, "CORE_ID"); (void)IoTHubMessage_SetContentTypeSystemProperty(msg, "application%2Fjson"); (void)IoTHubMessage_SetContentEncodingSystemProperty(msg, "utf-8"); MAP_HANDLE propMap = IoTHubMessage_Properties(msg); (void)sprintf_s(propText, sizeof(propText), (bRST==1 && bHOME==1) ? "true" : "false"); if (Map_AddOrUpdate(propMap, "valAlert", propText) != MAP_OK) { (void)printf("ERROR: Map_AddOrUpdate Failed!\r\n"); } if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, msg, SendConfirmationCallback, &msg) != IOTHUB_CLIENT_OK) //if (IoTHubClient_LL_SendEventAsync(iotHubClientHandle, msg, NULL, NULL) != IOTHUB_CLIENT_OK) { (void)printf("ERROR: IoTHubClient_SendEventAsync..........FAILED!\r\n"); } } IOTHUB_CLIENT_STATUS status; IoTHubClient_LL_DoWork(iotHubClientHandle); ThreadAPI_Sleep(100); //Wait till while ((IoTHubClient_LL_GetSendStatus(iotHubClientHandle, &status) == IOTHUB_CLIENT_OK) && (status == IOTHUB_CLIENT_SEND_STATUS_BUSY)) { IoTHubClient_LL_DoWork(iotHubClientHandle); ThreadAPI_Sleep(100); } //Callback is responsible for destroying message //IoTHubMessage_Destroy(msg); ThreadAPI_Sleep(100); send_interval_ms = millis(); bRST = bHOME = 0; } else { } } IoTHubClient_LL_DoWork(iotHubClientHandle); ThreadAPI_Sleep(100); }
30.446043
171
0.625236
tkopacz
c52424c8d38cf9406241a25a52a4b317ab0f7fb3
20,372
cpp
C++
CastingEssentials/Modules/CameraTools.cpp
PazerOP/CastingEssentials
d0bd4265233a6fa8d428cdcba326ac0574354a03
[ "BSD-2-Clause" ]
30
2016-11-13T00:50:34.000Z
2022-01-28T04:16:19.000Z
CastingEssentials/Modules/CameraTools.cpp
PazerOP/CastingEssentials
d0bd4265233a6fa8d428cdcba326ac0574354a03
[ "BSD-2-Clause" ]
92
2016-11-11T18:33:02.000Z
2020-11-14T13:06:56.000Z
CastingEssentials/Modules/CameraTools.cpp
PazerOP/CastingEssentials
d0bd4265233a6fa8d428cdcba326ac0574354a03
[ "BSD-2-Clause" ]
12
2017-04-27T18:27:20.000Z
2022-03-16T08:45:35.000Z
#include "CameraTools.h" #include "Misc/CCvar.h" #include "Misc/HLTVCameraHack.h" #include "Modules/Camera/SimpleCameraSmooth.h" #include "Modules/CameraSmooths.h" #include "Modules/CameraState.h" #include "PluginBase/Entities.h" #include "PluginBase/HookManager.h" #include "PluginBase/Interfaces.h" #include "PluginBase/Player.h" #include "PluginBase/TFDefinitions.h" #include <client/c_baseplayer.h> #include <filesystem.h> #include <shared/gamerules.h> #include <tier1/KeyValues.h> #include <tier3/tier3.h> #include <cdll_int.h> #include <client/c_baseentity.h> #include <characterset.h> #include <functional> #include <client/hltvcamera.h> #include <toolframework/ienginetool.h> #include <util_shared.h> #include <client/c_baseanimating.h> #include <vprof.h> #include <algorithm> MODULE_REGISTER(CameraTools); static IClientEntityList* s_ClientEntityList; static IVEngineClient* s_EngineClient; CameraTools::CameraTools() : ce_cameratools_autodirector_mode("ce_cameratools_autodirector_mode", "0", FCVAR_NONE, "Forces the camera mode to this value while spec_autodirector is enabled. 0 = don't force anything"), ce_cameratools_force_target("ce_cameratools_force_target", "-1", FCVAR_NONE, "Forces the camera target to this player index."), ce_cameratools_disable_view_punches("ce_cameratools_disable_view_punches", "0", FCVAR_NONE, "Disables all view punches (used for recoil effects on some weapons)", [](IConVar* var, const char*, float) { GetModule()->ToggleDisableViewPunches(static_cast<ConVar*>(var)); }), ce_cameratools_spec_entindex("ce_cameratools_spec_entindex", [](const CCommand& args) { GetModule()->SpecEntIndex(args); }, "Spectates a player by entindex"), ce_cameratools_spec_pos("ce_cameratools_spec_pos", [](const CCommand& args) { GetModule()->SpecPosition(args); }, "Moves the camera to a given position and angle."), ce_cameratools_spec_pos_delta("ce_cameratools_spec_pos_delta", [](const CCommand& args) { GetModule()->SpecPositionDelta(args); }, "Offsets the camera by the given values."), ce_cameratools_spec_class("ce_cameratools_spec_class", [](const CCommand& args) { GetModule()->SpecClass(args); }, "Spectates a specific class: ce_cameratools_spec_class <team> <class> [index]"), ce_cameratools_spec_steamid("ce_cameratools_spec_steamid", [](const CCommand& args) { GetModule()->SpecSteamID(args); }, "Spectates a player with the given steamid: ce_cameratools_spec_steamid <steamID>"), ce_cameratools_spec_index("ce_cameratools_spec_index", [](const CCommand& args) { GetModule()->SpecIndex(args); }, "Spectate a player based on their index in the tournament spectator hud."), ce_cameratools_smoothto("ce_cameratools_smoothto", &SmoothTo, "Interpolates between the current camera and a given target: " "\"ce_cameratools_smoothto <x> <y> <z> <pitch> <yaw> <roll> [duration] [smooth mode] [force]\"\n" "\tSmooth mode can be either linear or smoothstep, default linear."), ce_cameratools_show_users("ce_cameratools_show_users", [](const CCommand& args) { GetModule()->ShowUsers(args); }, "Lists all currently connected players on the server.") { } bool CameraTools::CheckDependencies() { Modules().Depend<CameraState>(); if (!CheckDependency(Interfaces::GetClientEntityList(), s_ClientEntityList)) return false; if (!CheckDependency(Interfaces::GetEngineClient(), s_EngineClient)) return false; if (!Player::CheckDependencies()) { PluginWarning("Required player helper class for module %s not available!\n", GetModuleName()); return false; } return true; } void CameraTools::SpecPosition(const Vector& pos, const QAngle& angle, ObserverMode mode, float fov) { if (mode == OBS_MODE_FIXED) { auto cam = std::make_shared<SimpleCamera>(); cam->m_Origin = pos; cam->m_Angles = angle; cam->m_FOV = fov == INFINITY ? 90 : fov; cam->m_Type = CameraType::Fixed; CameraState::GetModule()->SetCamera(cam); } else if (mode == OBS_MODE_ROAMING) { auto cam = std::make_shared<RoamingCamera>(); cam->SetPosition(pos, angle); if (fov != INFINITY) cam->SetFOV(fov); CameraState::GetModule()->SetCamera(cam); } else { Warning("%s: Programmer error! mode was %i\n", __FUNCTION__, mode); } } float CameraTools::CollisionTest3D(const Vector& startPos, const Vector& targetPos, float scale, const IHandleEntity* ignoreEnt) { static constexpr Vector TEST_POINTS[27] = { Vector(0, 0, 0), Vector(0, 0, 0.5), Vector(0, 0, 1), Vector(0, 0.5, 0), Vector(0, 0.5, 0.5), Vector(0, 0.5, 1), Vector(0, 1, 0), Vector(0, 1, 0.5), Vector(0, 1, 1), Vector(0.5, 0, 0), Vector(0.5, 0, 0.5), Vector(0.5, 0, 1), Vector(0.5, 0.5, 0), Vector(0.5, 0.5, 0.5), Vector(0.5, 0.5, 1), Vector(0.5, 1, 0), Vector(0.5, 1, 0.5), Vector(0.5, 1, 1), Vector(1, 0, 0), Vector(1, 0, 0.5), Vector(1, 0, 1), Vector(1, 0.5, 0), Vector(1, 0.5, 0.5), Vector(1, 0.5, 1), Vector(1, 1, 0), Vector(1, 1, 0.5), Vector(1, 1, 1), }; const Vector scaleVec(scale); const Vector mins(targetPos - Vector(scale)); const Vector maxs(targetPos + Vector(scale)); const Vector delta = maxs - mins; size_t pointsPassed = 0; for (const auto& testPoint : TEST_POINTS) { const Vector worldTestPoint = mins + delta * testPoint; trace_t tr; UTIL_TraceLine(startPos, worldTestPoint, MASK_VISIBLE, ignoreEnt, COLLISION_GROUP_NONE, &tr); if (tr.fraction >= 1) pointsPassed++; } return pointsPassed / float(std::size(TEST_POINTS)); } void CameraTools::GetSmoothTestSettings(const std::string_view& testsString, SmoothSettings& settings) { if (stristr(testsString, "all"sv) != testsString.end()) { settings.m_TestFOV = true; settings.m_TestDist = true; settings.m_TestCooldown = true; settings.m_TestLOS = true; } else { settings.m_TestFOV = stristr(testsString, "fov"sv) != testsString.end(); settings.m_TestDist = stristr(testsString, "dist"sv) != testsString.end(); settings.m_TestCooldown = stristr(testsString, "time"sv) != testsString.end(); settings.m_TestLOS = stristr(testsString, "los"sv) != testsString.end(); } } void CameraTools::SpecModeChanged(ObserverMode oldMode, ObserverMode& newMode) { static ConVarRef spec_autodirector("spec_autodirector"); if (!spec_autodirector.GetBool()) return; const auto forceMode = ce_cameratools_autodirector_mode.GetInt(); switch (forceMode) { case OBS_MODE_NONE: return; case OBS_MODE_FIXED: case OBS_MODE_IN_EYE: case OBS_MODE_CHASE: case OBS_MODE_ROAMING: newMode = (ObserverMode)forceMode; break; default: Warning("Unknown/unsupported value %i for %s\n", forceMode, ce_cameratools_autodirector_mode.GetName()); } } void CameraTools::SpecTargetChanged(IClientEntity* oldEnt, IClientEntity*& newEnt) { if (auto ent = s_ClientEntityList->GetClientEntity(ce_cameratools_force_target.GetInt())) newEnt = ent; } void CameraTools::ShowUsers(const CCommand& command) { std::vector<Player*> red; std::vector<Player*> blu; for (Player* player : Player::Iterable()) { if (player->GetClass() == TFClassType::Unknown) continue; switch (player->GetTeam()) { case TFTeam::Red: red.push_back(player); break; case TFTeam::Blue: blu.push_back(player); break; default: continue; } } Msg("%i Players:\n", red.size() + blu.size()); for (size_t i = 0; i < red.size(); i++) ConColorMsg(Color(255, 128, 128, 255), " alias player_red%i \"%s %s\" // %s (%s)\n", i, ce_cameratools_spec_steamid.GetName(), RenderSteamID(red[i]->GetSteamID().ConvertToUint64()).c_str(), red[i]->GetName(), TF_CLASS_NAMES[(int)red[i]->GetClass()]); for (size_t i = 0; i < blu.size(); i++) ConColorMsg(Color(128, 128, 255, 255), " alias player_blu%i \"%s %s\" // %s (%s)\n", i, ce_cameratools_spec_steamid.GetName(), RenderSteamID(blu[i]->GetSteamID().ConvertToUint64()).c_str(), blu[i]->GetName(), TF_CLASS_NAMES[(int)blu[i]->GetClass()]); } void CameraTools::SpecClass(const CCommand& command) { // Usage: <team> <class> [classIndex] if (command.ArgC() < 3 || command.ArgC() > 4) { PluginWarning("%s: Expected either 2 or 3 arguments\n", command.Arg(0)); goto Usage; } TFTeam team; if (!strnicmp(command.Arg(1), "blu", 3)) team = TFTeam::Blue; else if (!strnicmp(command.Arg(1), "red", 3)) team = TFTeam::Red; else { PluginWarning("%s: Unknown team \"%s\"\n", command.Arg(0), command.Arg(1)); goto Usage; } TFClassType playerClass; if (!stricmp(command.Arg(2), "scout")) playerClass = TFClassType::Scout; else if (!stricmp(command.Arg(2), "soldier") || !stricmp(command.Arg(2), "solly")) playerClass = TFClassType::Soldier; else if (!stricmp(command.Arg(2), "pyro")) playerClass = TFClassType::Pyro; else if (!strnicmp(command.Arg(2), "demo", 4)) playerClass = TFClassType::DemoMan; else if (!strnicmp(command.Arg(2), "heavy", 5) || !stricmp(command.Arg(2), "hoovy") || !stricmp(command.Arg(2), "pootis")) playerClass = TFClassType::Heavy; else if (!stricmp(command.Arg(2), "engineer") || !stricmp(command.Arg(2), "engie")) playerClass = TFClassType::Engineer; else if (!stricmp(command.Arg(2), "medic")) playerClass = TFClassType::Medic; else if (!stricmp(command.Arg(2), "sniper")) playerClass = TFClassType::Sniper; else if (!stricmp(command.Arg(2), "spy") | !stricmp(command.Arg(2), "sphee")) playerClass = TFClassType::Spy; else { PluginWarning("%s: Unknown class \"%s\"\n", command.Arg(0), command.Arg(2)); goto Usage; } int classIndex = -1; if (command.ArgC() > 3 && !TryParseInteger(command.Arg(3), classIndex)) { PluginWarning("%s: class index \"%s\" is not an integer\n", command.Arg(0), command.Arg(3)); goto Usage; } SpecClass(team, playerClass, classIndex); return; Usage: PluginWarning("Usage: %s\n", ce_cameratools_spec_class.GetHelpText()); } void CameraTools::SpecClass(TFTeam team, TFClassType playerClass, int classIndex) { int validPlayersCount = 0; Player* validPlayers[MAX_PLAYERS]; for (Player* player : Player::Iterable()) { if (player->GetTeam() != team || player->GetClass() != playerClass) continue; validPlayers[validPlayersCount++] = player; } if (validPlayersCount == 0) return; // Nobody to switch to // If classIndex was not specified, cycle through the available options if (classIndex < 0) { auto localMode = CameraState::GetModule()->GetLocalObserverMode(); if (localMode == OBS_MODE_FIXED || localMode == OBS_MODE_IN_EYE || localMode == OBS_MODE_CHASE) { Player* spectatingPlayer = Player::AsPlayer(CameraState::GetModule()->GetLocalObserverTarget()); int currentIndex = -1; for (int i = 0; i < validPlayersCount; i++) { if (validPlayers[i] == spectatingPlayer) { currentIndex = i; break; } } classIndex = currentIndex + 1; } } if (classIndex < 0 || classIndex >= validPlayersCount) classIndex = 0; SpecPlayer(validPlayers[classIndex]->GetEntity()->entindex()); } void CameraTools::SpecEntIndex(const CCommand& command) { if (command.ArgC() != 2) { PluginWarning("%s: Expected 1 argument\n", command.Arg(0)); goto Usage; } int index; if (!TryParseInteger(command.Arg(1), index)) { PluginWarning("%s: entindex \"%s\" is not an integer\n", command.Arg(0), command.Arg(1)); goto Usage; } SpecPlayer(index); return; Usage: PluginWarning("Usage: %s <entindex>\n", command.Arg(0)); } void CameraTools::SpecPlayer(int playerIndex) { Player* player = Player::GetPlayer(playerIndex, __FUNCSIG__); if (!player) { Warning("%s: Unable to find a player with an entindex of %i\n", __FUNCSIG__, playerIndex); return; } if (!player->IsAlive()) { DevWarning("%s: Not speccing \"%s\" because they are dead (%s)\n", __FUNCTION__, player->GetName()); return; } char buf[32]; sprintf_s(buf, "spec_player \"#%i\"", player->GetUserID()); s_EngineClient->ClientCmd(buf); } void CameraTools::SmoothTo(const CCommand& cmd) { auto cs = CameraState::GetModule(); if (!cs) { Warning("%s: Unable to get Camera State module\n", cmd[0]); return; } do { if (cmd.ArgC() < 1 || cmd.ArgC() > 10) break; const auto& activeCam = cs->GetCurrentCamera(); if (!activeCam) { Warning("%s: No current active camera?\n", cmd[0]); break; } const auto& currentPos = activeCam->GetOrigin(); const auto& currentAng = activeCam->GetAngles(); auto startCam = std::make_shared<SimpleCamera>(); { startCam->m_Angles = activeCam->GetAngles(); startCam->m_Origin = activeCam->GetOrigin(); startCam->m_FOV = activeCam->GetFOV(); } Vector endCamPos; QAngle endCamAng; for (uint_fast8_t i = 0; i < 6; i++) { const auto& arg = cmd.ArgC() > i + 1 ? cmd[i + 1] : "?"; auto& param = i < 3 ? endCamPos[i] : endCamAng[i - 3]; if (arg[0] == '?' && arg[1] == '\0') param = i < 3 ? currentPos[i] : currentAng[i - 3]; else if (!TryParseFloat(arg, param)) { Warning("%s: Unable to parse \"%s\" (arg %i) as a float\n", cmd[0], arg, i); break; } } SmoothSettings settings; if (cmd.ArgC() > 7 && !TryParseFloat(cmd[7], settings.m_DurationOverride)) { Warning("%s: Unable to parse arg 7 (duration, \"%s\") as a float\n", cmd[0], cmd[7]); break; } if (cmd.ArgC() > 8 && (cmd[8][0] != '?' || cmd[8][1] != '\0')) { if (!stricmp(cmd[8], "linear")) settings.m_InterpolatorOverride = &Interpolators::Linear; else if (!stricmp(cmd[8], "smoothstep")) settings.m_InterpolatorOverride = &Interpolators::Smoothstep; else Warning("%s: Unrecognized smooth mode %s, defaulting to linear\n", cmd[0], cmd[8]); } if (cmd.ArgC() > 9) GetSmoothTestSettings(cmd[9], settings); else { settings.m_TestFOV = false; settings.m_TestCooldown = false; } auto endCam = std::make_shared<RoamingCamera>(); endCam->SetInputEnabled(false); endCam->SetPosition(endCamPos, endCamAng); cs->SetCameraSmoothed(endCam, settings); return; } while (false); Warning("Usage: %s [x] [y] [z] [pitch] [yaw] [roll] [duration] [smooth mode] [tests]\n" "\tSmooth mode can be either linear or smoothstep.\n" "\tIf any of the pos/angle parameters are '?' or omitted, they are left untouched.\n" "\t'?' or omission for duration and smooth mode means use ce_smoothing_ cvars.\n" "\ttests: default 'dist+los'. Can be 'all', 'none', or combined with '+' (NO SPACES):\n" "\t\tlos: Don't smooth if we don't have LOS to the target (ce_smoothing_los_)\n" "\t\tdist: Don't smooth if we're too far away (ce_smoothing_*_distance)\n" "\t\ttime: Don't smooth if we're still on cooldown (ce_smoothing_cooldown)\n" "\t\tfov: Don't smooth if target is outside of fov (ce_smoothing_fov)\n" , cmd[0]); } void CameraTools::ToggleDisableViewPunches(const ConVar* var) { if (var->GetBool()) { auto angle = Entities::FindRecvProp("CTFPlayer", "m_vecPunchAngle"); auto velocity = Entities::FindRecvProp("CTFPlayer", "m_vecPunchAngleVel"); if (!angle) { PluginWarning("%s: Unable to locate RecvProp for C_TFPlayer::m_vecPunchAngle\n", var->GetName()); return; } if (!velocity) { PluginWarning("%s: Unable to locate RecvProp for C_TFPlayer::m_vecPunchAngleVel\n", var->GetName()); return; } RecvVarProxyFn zeroProxy = [](const CRecvProxyData* pData, void* pStruct, void* pOut) { auto outVec = reinterpret_cast<Vector*>(pOut); outVec->Init(0, 0, 0); }; m_vecPunchAngleProxy = CreateVariablePusher(angle->m_ProxyFn, zeroProxy); m_vecPunchAngleVelProxy = CreateVariablePusher(velocity->m_ProxyFn, zeroProxy); } else { m_vecPunchAngleProxy.Clear(); m_vecPunchAngleVelProxy.Clear(); } } void CameraTools::SpecSteamID(const CCommand& command) { CCommand newCommand; if (!ReparseForSteamIDs(command, newCommand)) return; CSteamID parsed; if (newCommand.ArgC() != 2) { PluginWarning("%s: Expected 1 argument\n", command.Arg(0)); goto Usage; } parsed.SetFromString(newCommand.Arg(1), k_EUniverseInvalid); if (!parsed.IsValid()) { PluginWarning("%s: Unable to parse steamid\n", command.Arg(0)); goto Usage; } for (Player* player : Player::Iterable()) { if (player->GetSteamID() == parsed) { SpecPlayer(player->GetEntity()->entindex()); return; } } Warning("%s: couldn't find a user with the steam id %s on the server\n", command.Arg(0), RenderSteamID(parsed).c_str()); return; Usage: PluginWarning("Usage: %s\n", ce_cameratools_spec_steamid.GetHelpText()); } void CameraTools::SpecIndex(const CCommand& command) { if (command.ArgC() != 3) goto Usage; TFTeam team; if (tolower(command.Arg(1)[0]) == 'r') team = TFTeam::Red; else if (tolower(command.Arg(1)[0]) == 'b') team = TFTeam::Blue; else goto Usage; // Create an array of all our players on the specified team Player* allPlayers[MAX_PLAYERS]; const auto endIter = Player::GetSortedPlayers(team, std::begin(allPlayers), std::end(allPlayers)); const auto playerCount = std::distance(std::begin(allPlayers), endIter); char* endPtr; const auto index = std::strtol(command.Arg(2), &endPtr, 0); if (endPtr == command.Arg(2)) goto Usage; // Couldn't parse index if (index < 0 || index >= playerCount) { if (playerCount < 1) PluginWarning("%s: No players on team %s\n", command.Arg(0), command.Arg(1)); else PluginWarning("Specified index \"%s\" for %s, but valid indices for team %s were [0, %i]\n", command.Arg(2), command.Arg(0), command.Arg(1), playerCount - 1); return; } SpecPlayer(allPlayers[index]->entindex()); return; Usage: PluginWarning("Usage: %s <red/blue> <index>\n", command.Arg(0)); } bool CameraTools::ParseSpecPosCommand(const CCommand& command, Vector& pos, QAngle& ang, ObserverMode& mode, const Vector& defaultPos, const QAngle& defaultAng, ObserverMode defaultMode) const { if (command.ArgC() < 2 || command.ArgC() > 8) goto PrintUsage; for (int i = 1; i < 7; i++) { const auto arg = i < command.ArgC() ? command.Arg(i) : nullptr; float& param = i < 4 ? pos[i - 1] : ang[i - 4]; if (!arg || (arg[0] == '?' && arg[1] == '\0')) { param = i < 4 ? defaultPos[i - 1] : defaultAng[i - 4]; } else if (!TryParseFloat(arg, param)) { PluginWarning("Invalid parameter \"%s\" (arg %i) for %s command\n", command.Arg(i), i - 1, command.Arg(0)); goto PrintUsage; } } mode = defaultMode; if (command.ArgC() > 7) { const auto modeArg = command.Arg(7); if (!stricmp(modeArg, "fixed")) mode = OBS_MODE_FIXED; else if (!stricmp(modeArg, "free")) mode = OBS_MODE_ROAMING; else if (modeArg[0] != '?' || modeArg[1] != '\0') { PluginWarning("Invalid parameter \"%s\" for mode (expected \"fixed\" or \"free\")\n"); goto PrintUsage; } } return true; PrintUsage: PluginMsg( "Usage: %s x [y] [z] [pitch] [yaw] [roll] [mode]\n" "\tIf any of the parameters are '?' or omitted, they are left untouched.\n" "\tMode can be either \"fixed\" or \"free\"\n", command.Arg(0)); return false; } void CameraTools::SpecPosition(const CCommand& command) { const auto camState = CameraState::GetModule(); if (!camState) { Warning("%s: Failed to get CameraState module\n", command[0]); return; } ObserverMode defaultMode = camState->GetDesiredObserverMode(); if (defaultMode != OBS_MODE_FIXED && defaultMode != OBS_MODE_ROAMING) defaultMode = OBS_MODE_ROAMING; const auto activeCam = camState->GetCurrentCamera(); if (!activeCam) { Warning("%s: No active camera?\n", command[0]); return; } Vector pos; QAngle ang; ObserverMode mode; if (ParseSpecPosCommand(command, pos, ang, mode, activeCam->GetOrigin(), activeCam->GetAngles(), defaultMode)) SpecPosition(pos, ang, mode); } void CameraTools::SpecPositionDelta(const CCommand& command) { const auto camState = CameraState::GetModule(); if (!camState) { Warning("%s: Failed to get CameraState module\n", command[0]); return; } ObserverMode defaultMode = camState->GetDesiredObserverMode(); if (defaultMode != OBS_MODE_FIXED && defaultMode != OBS_MODE_ROAMING) defaultMode = OBS_MODE_ROAMING; const auto activeCam = camState->GetCurrentCamera(); if (!activeCam) { Warning("%s: No active camera?\n", command[0]); return; } Vector pos; QAngle ang; ObserverMode mode; if (ParseSpecPosCommand(command, pos, ang, mode, vec3_origin, vec3_angle, defaultMode)) { pos += activeCam->GetOrigin(); ang += activeCam->GetAngles(); SpecPosition(pos, ang, mode); } }
28.452514
256
0.6828
PazerOP
c52514166be8497b2091345590192675581da905
2,434
hpp
C++
Camera.hpp
Adrijaned/oglPlaygorund
ce3c31669263545650efcc4b12dd22e6517ccaa7
[ "MIT" ]
null
null
null
Camera.hpp
Adrijaned/oglPlaygorund
ce3c31669263545650efcc4b12dd22e6517ccaa7
[ "MIT" ]
null
null
null
Camera.hpp
Adrijaned/oglPlaygorund
ce3c31669263545650efcc4b12dd22e6517ccaa7
[ "MIT" ]
null
null
null
// // Created by adrijarch on 5/11/19. // #ifndef OGLPLAYGROUND_CAMERA_HPP #define OGLPLAYGROUND_CAMERA_HPP #include <glm/glm.hpp> /** * OGL style camera for computing view matrix for use by shaders. */ class Camera { /** * Position of the camera itself in the source coordinate system. */ glm::vec3 position = glm::vec3{0, 0, 0}; /** * Rotation along the y axis, achieved by moving mouse horizontally. * Radians normalized in range [0, 2 * PI]. */ float yaw = 0; /** * Rotation in up/down manner, achieved by moving mouse vertically. * Radians clamped in range [ - PI / 2, PI / 2 ]. */ float pitch = 0; /** * Denotes whether anything in this class has been changed since last * recalculation of \c target. * This is handy to speed up calculations in some cases. * @see viewMatrix */ bool dirty = true; /** * The last computed view matrix. * This is handy to speed up calculation in some cases. * @see dirty */ glm::mat4 viewMatrix{1.0f}; public: /** * Returns the view matrix from this camera * @return The view matrix */ const glm::mat4 getView(); /** * Changes the camera yaw by given value in radians. * Yaw is expected to refer to rotation along the vertical/y axis in clockwise * manner. * @param value Value in radians to change yaw by. * @return self for method chaining. */ Camera &changeYaw(float value); /** * Changes the camera pitch by given value in radians. * Pitch is expected to refer to rotation in up/down manner / along the * horizontal axis ortogonal to direction denoted by yaw, with positive * numbers used for the up direction. * * @warning Resulting pitch value is @b clamped to range @f$ * \left\langle-\frac{\pi}{2},\frac{\pi}{2}\right\rangle * @f$ * @param value Value in radians to change pitch by. * @return self for method chaining. */ Camera &changePitch(float value); /** * Possible directions Camera can move in. * @see move */ enum MovementDirection { UP, DOWN, FORWARD, BACKWARD, LEFT, RIGHT }; const glm::vec3 &getPosition() const; /** * Moves this camera in given direction relative by current @b yaw. * @param direction Direction to move into * @param distance Distance to move by * @return self for method chaining. */ Camera& move(const MovementDirection& direction, float distance); }; #endif //OGLPLAYGROUND_CAMERA_HPP
26.456522
80
0.672555
Adrijaned
c52f1092a61bc918798d7d1d82e3255581c72fa1
2,158
cpp
C++
dictionary_std_vector/src/dictionary_std_vector.cpp
Arghnews/wordsearch_solver
cf25db64ca3d1facd9191aad075654f124f0d580
[ "MIT" ]
null
null
null
dictionary_std_vector/src/dictionary_std_vector.cpp
Arghnews/wordsearch_solver
cf25db64ca3d1facd9191aad075654f124f0d580
[ "MIT" ]
null
null
null
dictionary_std_vector/src/dictionary_std_vector.cpp
Arghnews/wordsearch_solver
cf25db64ca3d1facd9191aad075654f124f0d580
[ "MIT" ]
null
null
null
#include "wordsearch_solver/dictionary_std_vector/dictionary_std_vector.hpp" #include <fmt/format.h> #include <fmt/ostream.h> #include <fmt/ranges.h> #include <range/v3/view/all.hpp> #include <range/v3/view/transform.hpp> #include <algorithm> #include <cassert> #include <cstddef> #include <ostream> #include <string> #include <string_view> #include <vector> namespace dictionary_std_vector { DictionaryStdVector::DictionaryStdVector( const std::initializer_list<std::string_view>& words) : DictionaryStdVector(ranges::views::all(words)) {} DictionaryStdVector::DictionaryStdVector( const std::initializer_list<std::string>& words) : DictionaryStdVector(ranges::views::all(words)) {} DictionaryStdVector::DictionaryStdVector( const std::initializer_list<const char*>& words) : DictionaryStdVector( ranges::views::all(words) | ranges::views::transform([](const auto string_literal) { return std::string_view{string_literal}; })) {} std::size_t DictionaryStdVector::size() const { return dict_.size(); } bool DictionaryStdVector::empty() const { return dict_.empty(); } bool DictionaryStdVector::contains(const std::string_view word) const { return std::binary_search(dict_.begin(), dict_.end(), word); } bool DictionaryStdVector::further(const std::string_view word) const { return this->further_impl(word, dict_.begin(), dict_.end()); } bool DictionaryStdVector::further_impl(const std::string_view prefix, const Iterator first, const Iterator last) const { assert(last >= first); const auto it = std::upper_bound(first, last, prefix); if (it == last) { return false; } const auto& word = *it; if (word.size() < prefix.size()) { return false; } return std::equal( prefix.begin(), prefix.end(), word.begin(), word.begin() + static_cast<decltype(prefix)::difference_type>(prefix.size())); } std::ostream& operator<<(std::ostream& os, const DictionaryStdVector& dsv) { return os << fmt::format("{}", dsv.dict_); } } // namespace dictionary_std_vector
30.394366
76
0.68165
Arghnews
c532c00b414b4ddb9685037a54ae024dc92ae6f4
3,943
cpp
C++
libcaf_core/test/node_id.cpp
jsiwek/actor-framework
06cd2836f4671725cb7eaa22b3cc115687520fc1
[ "BSL-1.0", "BSD-3-Clause" ]
4
2019-05-03T05:38:15.000Z
2020-08-25T15:23:19.000Z
libcaf_core/test/node_id.cpp
jsiwek/actor-framework
06cd2836f4671725cb7eaa22b3cc115687520fc1
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
libcaf_core/test/node_id.cpp
jsiwek/actor-framework
06cd2836f4671725cb7eaa22b3cc115687520fc1
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2020 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #define CAF_SUITE node_id #include "caf/node_id.hpp" #include "caf/test/dsl.hpp" #include "caf/binary_deserializer.hpp" #include "caf/binary_serializer.hpp" using namespace caf; namespace { node_id roundtrip(node_id nid) { byte_buffer buf; { binary_serializer sink{nullptr, buf}; if (!sink.apply_object(nid)) CAF_FAIL("serialization failed: " << sink.get_error()); } if (buf.empty()) CAF_FAIL("serializer produced no output"); node_id result; { binary_deserializer source{nullptr, buf}; if (!source.apply_object(result)) CAF_FAIL("deserialization failed: " << source.get_error()); if (source.remaining() > 0) CAF_FAIL("binary_serializer ignored part of its input"); } return result; } } // namespace #define CHECK_PARSE_OK(str, ...) \ do { \ CAF_CHECK(node_id::can_parse(str)); \ node_id nid; \ CAF_CHECK_EQUAL(parse(str, nid), none); \ CAF_CHECK_EQUAL(nid, make_node_id(__VA_ARGS__)); \ } while (false) CAF_TEST(node IDs are convertible from string) { node_id::default_data::host_id_type hash{{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, }}; auto uri_id = unbox(make_uri("ip://foo:8080")); CHECK_PARSE_OK("0102030405060708090A0B0C0D0E0F1011121314#1", 1, hash); CHECK_PARSE_OK("0102030405060708090A0B0C0D0E0F1011121314#123", 123, hash); CHECK_PARSE_OK("ip://foo:8080", uri_id); } #define CHECK_PARSE_FAIL(str) CAF_CHECK(!node_id::can_parse(str)) CAF_TEST(node IDs reject malformed strings) { // not URIs CHECK_PARSE_FAIL("foobar"); CHECK_PARSE_FAIL("CAF#1"); // uint32_t overflow on the process ID CHECK_PARSE_FAIL("0102030405060708090A0B0C0D0E0F1011121314#42949672950"); } CAF_TEST(node IDs are serializable) { CAF_MESSAGE("empty node IDs remain empty"); { node_id nil_id; CAF_CHECK_EQUAL(nil_id, roundtrip(nil_id)); } CAF_MESSAGE("hash-based node IDs remain intact"); { auto tmp = make_node_id(42, "0102030405060708090A0B0C0D0E0F1011121314"); auto hash_based_id = unbox(tmp); CAF_CHECK_EQUAL(hash_based_id, roundtrip(hash_based_id)); } CAF_MESSAGE("URI-based node IDs remain intact"); { auto uri_based_id = make_node_id(unbox(make_uri("foo:bar"))); CAF_CHECK_EQUAL(uri_based_id, roundtrip(uri_based_id)); } }
39.43
80
0.503677
jsiwek
c533328548e5885b901f2ad1f6377d57a4c1c195
6,034
cpp
C++
code/src/utils/CommandLineParser.cpp
reuqlauQemoN/streamopenacc
c8d74dcea6b28e1038d76ab27fca5c23e21ecead
[ "Apache-1.1" ]
69
2015-07-02T05:25:29.000Z
2022-01-10T08:54:46.000Z
code/src/utils/CommandLineParser.cpp
xiaguoyang/streamDM-Cpp
0304d03393f6987596aa445a0506631655297e79
[ "Apache-1.1" ]
3
2015-08-15T06:42:17.000Z
2021-05-17T09:30:51.000Z
code/src/utils/CommandLineParser.cpp
xiaguoyang/streamDM-Cpp
0304d03393f6987596aa445a0506631655297e79
[ "Apache-1.1" ]
40
2015-07-02T06:03:26.000Z
2021-12-16T02:07:29.000Z
/* * Copyright (C) 2015 Holmes Team at HUAWEI Noah's Ark Lab. * * 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 "CommandLineParser.h" #include "../Common.h" ////////////////////////////// CommandLineParser ////////////////////////////// CommandLineParser::CommandLineParser() { } CommandLineParser::~CommandLineParser() { } /** * parser command line string: * 1. smartdm -f file.json * 2. smartdm "EvaluateHoldOut -l (StreamingMBT) -r (StreamingMBTReader) -a train.txt -t test.txt" * \param argc command line parameter number * \param argv command line parameter * \param param the output data */ bool CommandLineParser::parser(int argc, char* argv[], string& taskName, string& taskParam) { if (argc != 2 && argc != 3) { LOG_ERROR("Command line arguments error."); return false; } if (argc == 2) { return parserCommandLine(argv[1], taskName, taskParam); } if (argc == 3) { string param(argv[1]); string value(argv[2]); if (param != "-f") { LOG_ERROR("Command option: smartdm -f file.json"); return false; }else if (! Utils::checkFileExist(value)) { LOG_ERROR("File is not existed. %s", value.c_str()); return false; }else{ return parserJsonFile(argv[1], taskName, taskParam); } } return true; } /** * parser command line string, * link: * 1. smartDM "EvaluatePrequential -l (VfdtLearner -sc 0.001 -tc 0.02) -r C45Reader -ds /opt/moa/alan/test/data/DF" * 2. smartDM "EvaluatePrequential -l (Bagging -l (VfdtLearner -sc 0.001 -tc 0.02) -es 100) -r C45Reader -ds /opt/moa/alan/test/data/DF" * 3. smartDM "EvaluatePrequential -l (VfdtLearner -sc 0.001 -tc 0.02) -r (C45Reader -ds /opt/moa/alan/test/data/DF)" */ bool CommandLineParser::parserCommandLine( const string& in, string& taskName, string& taskParam) { // segment "(", ")" with " " stringstream ss; for (int i=0; i < in.size(); i++) { if (in[i] == '(' || in[i] == ')') { ss << " " << in[i] << " "; } else { ss << in[i]; } } string s; vector<string> vec; while (getline(ss, s, ' ' )) { if (s.size() == 0) { continue; } vec.push_back(s); } Json::Value jv; int pos = 0; string type = "Task"; bool ret = parser(vec, type, pos, jv); if (!ret) { return false; } taskName = jv["Name"].asString(); taskParam = jv.toStyledString(); return true; } /** * parser json file, * \param in is json file name. * * The file content model is : * { "Task": { "Name": "EvaluatePrequential", "-l": { "Name": "VfdtLearner", "-sc": "0.001", "-tc": "0.02" }, "-r": "C45", "-ds": "/opt/moa/alan/test/data/DF" } } * { "Task": { "Name": "EvaluatePrequential", "-l": { "Name": "Bagging", "-l": { "-sc": "0.001", "-tc": "0.02", "Name": "VfdtLearner" } }, "-r": "C45", "-ds": "/opt/moa/alan/test/data/DF" } } * */ bool CommandLineParser::parserJsonFile( const string& in, string& taskName, string& taskParam) { return true; } bool CommandLineParser::parser(vector<string>& vec, const string& type, int& pos, Json::Value& jv) { CLPFN &names = CLPFN::getInstance(); string className = vec[pos]; jv["Name"] = className; if (names.data.find(className) == names.data.end()) { LOG_ERROR("Not defined class: %s .", className.c_str()); return false; } auto &classParams = names.data[className]; pos++; while (pos < vec.size()) { // check exit condition if (vec[pos] == ")") { pos++; return true; } // get name string name = vec[pos]; if (name[0] != '-') { LOG_ERROR("Error command line parameter: %s .", name.c_str()); return false; } auto iter = classParams.find(name); if (iter == classParams.end()) { LOG_ERROR("Not define class parameter, class: %s, parameter: %s .", className.c_str(), name.c_str()); return false; } name = iter->second; // get value pos++; if (pos == vec.size()) { LOG_ERROR("Require command line parameter value: %s .", name.c_str()); return false; } string value = vec[pos]; // check nestling if (value == "(") { Json::Value jv2; pos++; if (pos+1 == vec.size() ) { LOG_ERROR("Not enough command line parameter."); return false; } bool ret = parser(vec, name, pos, jv2 ); if (!ret) { return false; } jv[name] = jv2; } else { jv[name] = value; pos++; } } return true; } ////////////////////////////// CommandLineParameter /////////////////////////// CommandLineParameter::CommandLineParameter() { } CommandLineParameter::~CommandLineParameter() { } string CommandLineParameter::getTaskName() { return data["Task"]["Name"].asString(); } string CommandLineParameter::getTaskParameter() { return data["Task"].toStyledString(); } ////////////////////////////// CLPFN ////////////////////////////////////////// CLPFN::CLPFN() { } CLPFN& CLPFN::getInstance() { static CLPFN instance; return instance; } RegisterCommandLineParameterFullName::RegisterCommandLineParameterFullName( const string& fullName) { Json::Value jv; Json::Reader reader; reader.parse( fullName, jv ); CLPFN& names = CLPFN::getInstance(); string name = jv["name"].asString(); string type = jv["type"].asString(); Json::Value::Members m = jv["parameter"].getMemberNames(); names.data[name]["Type"] = type; for (int i=0; i<m.size(); i++) { names.data[name][m[i]] = jv["parameter"][m[i]].asString(); } }
23.118774
136
0.592973
reuqlauQemoN
c53412834662148177d1887ff675abd21587750b
519
hpp
C++
bullpen_sketch/state.hpp
estriz27/bullpen
11ee415d7f2b2b211a2c9e34a173e016f298b85c
[ "MIT" ]
null
null
null
bullpen_sketch/state.hpp
estriz27/bullpen
11ee415d7f2b2b211a2c9e34a173e016f298b85c
[ "MIT" ]
null
null
null
bullpen_sketch/state.hpp
estriz27/bullpen
11ee415d7f2b2b211a2c9e34a173e016f298b85c
[ "MIT" ]
null
null
null
#ifndef __STATE__ #define __STATE__ #include "person.hpp" #include <stdlib.h> #include <vector> #include <algorithm> class State{ //Has a vector of class Person std::vector<Person> people; public: State(std::vector<Person> people):people(people){} std::vector<Person> getInList(); std::vector<Person> getOutList(); Person* getPerson(unsigned int personIndex); bool isIn(unsigned int personIndex); void togglePerson(unsigned int personIndex);//calls togglePresent on person at given index }; #endif
21.625
92
0.739884
estriz27
c539f8932a5650fab69b759c1a2de0beda728576
4,151
hpp
C++
include/lemon/deprecated/old_hadoop.hpp
frodofine/lemon
f874857cb8f1851313257b25681ad2a254ada8dc
[ "BSD-3-Clause" ]
43
2018-07-21T22:08:48.000Z
2022-03-23T22:19:02.000Z
include/lemon/deprecated/old_hadoop.hpp
frodofine/lemon
f874857cb8f1851313257b25681ad2a254ada8dc
[ "BSD-3-Clause" ]
22
2018-08-01T19:13:11.000Z
2020-06-02T17:04:03.000Z
include/lemon/deprecated/old_hadoop.hpp
frodofine/lemon
f874857cb8f1851313257b25681ad2a254ada8dc
[ "BSD-3-Clause" ]
9
2018-07-21T19:13:55.000Z
2020-12-22T09:12:43.000Z
#ifndef OLD_HADOOP_HPP #define OLD_HADOOP_HPP #include <cassert> #include <cstdint> #include <fstream> #include <string> #include <vector> namespace lemon { namespace deprecated { class Hadoop { public: Hadoop(std::istream& stream) : stream_(stream) { initialize_(); } bool has_next() { return stream_.peek() != std::char_traits<char>::eof(); } std::pair<std::vector<char>, std::vector<char>> next() { return read(); } private: std::istream& stream_; std::string marker_ = ""; std::vector<char> key_; /* Uncomment if a more generic solution is desired.... Loosly based on https://github.com/azat-archive/hadoop-io-sequence-reader/blob/master/src/reader.cpp, but entirely rewritten static uint32_t decode(int8_t ch) { if (ch >= -112) { return 1; } else if (ch < -120) { return -119 - ch; } return -111 - ch; } static int64_t read(const char *pos, uint32_t &len) { if (*pos >= (char)-112) { len = 1; return *pos; } else { return read_helper(pos, len); } } static int64_t read_helper(const char *pos, uint32_t &len) { bool neg = *pos < -120; len = neg ? (-119 - *pos) : (-111 - *pos); const char *end = pos + len; int64_t value = 0; while (++pos < end) { value = (value << 8) | *(uint8_t *)pos; } return neg ? (value ^ -1LL) : value; } int64_t read_long() { char buff[10]; stream_.read(buff, 1); auto len = decode(*buff); if (len > 1) { !stream_.read(buff + 1, len - 1); } return read(buff, len); } void read_string(char *buffer) { auto len = read_long(); stream_.read(buffer, len); } void initialize() { stream_.exceptions(std::ifstream::badbit | std::ifstream::failbit); char buffer[1024]; // Reads the header stream_.read(buffer, 4); // Read the Key class read_string(buffer); // Read the Value class read_string(buffer); auto valueCompression = stream_.get(); auto blockCompression = stream_.get(); if (valueCompression != 0 || blockCompression != 0) { throw std::runtime_error("Compression not supported"); } int pairs = read_int(); if (pairs < 0 || pairs > 1024) { throw std::runtime_error("Invalid pair count"); } for (size_t i = 0; i < pairs; ++i) { // Ignore the metadata read_string(buffer); read_string(buffer); } // Read marker stream_.read(buffer, 16); marker_ = std::string(buffer, 16); } */ void initialize_() { // Completly skip the header as it is the same in all RCSB Hadoop files stream_.exceptions(std::ifstream::badbit | std::ifstream::failbit); char buffer[86]; stream_.read(buffer, 87); } int read_int() { int ret; stream_.read(reinterpret_cast<char*>(&ret), 4); return ntohl(ret); } std::pair<std::vector<char>, std::vector<char>> read() { auto sync_check = read_int(); if (sync_check == -1) { std::vector<char> marker(16); stream_.read(marker.data(), 16); // Only valid if using the full version // assert(std::string(marker.data(), 16) == marker_); return this->read(); } auto key_length = read_int(); // Do not check this during runtime as it should all be the same assert(key_length >= 4); std::vector<char> key(key_length); stream_.read(key.data(), key_length); assert(sync_check >= 8); // Remove junk characters added by Java Serialization char junk[4]; stream_.read(junk, 4); int value_length = sync_check - key_length; std::vector<char> value(value_length - 4); stream_.read(value.data(), value_length - 4); return {key, value}; } }; } } #endif
25.623457
89
0.544929
frodofine
c544e038a050d0f02a4c8bd73294457099d108a9
660
hpp
C++
include/SplayLibrary/Core/RenderWindow.hpp
Reiex/SplayLibrary
94b68f371ea4c662c84dfe2dd0a6d1625b60fb04
[ "MIT" ]
1
2021-12-14T21:36:39.000Z
2021-12-14T21:36:39.000Z
include/SplayLibrary/Core/RenderWindow.hpp
Reiex/SplayLibrary
94b68f371ea4c662c84dfe2dd0a6d1625b60fb04
[ "MIT" ]
null
null
null
include/SplayLibrary/Core/RenderWindow.hpp
Reiex/SplayLibrary
94b68f371ea4c662c84dfe2dd0a6d1625b60fb04
[ "MIT" ]
null
null
null
#pragma once #include <SplayLibrary/Core/types.hpp> namespace spl { class RenderWindow : public Window { public: RenderWindow(const uvec2& size, const std::string& title); RenderWindow(const RenderWindow& window) = delete; RenderWindow(RenderWindow&& window) = delete; const RenderWindow& operator=(const RenderWindow& window) = delete; const RenderWindow& operator=(RenderWindow&& window) = delete; void display(); const Framebuffer& getFramebuffer() const; ~RenderWindow(); private: virtual bool processEvent(Event*& event); vec3 _clearColor; Framebuffer _framebuffer; }; }
20.625
71
0.680303
Reiex
c5460a64ed3932f8d78a3dacd0971d66ec8f8c82
5,631
hpp
C++
core/include/component/ComponentManager.hpp
Floriantoine/MyHunter_Sfml
8744e1b03d9d5fb621f9cba7619d9d5dd943e428
[ "MIT" ]
null
null
null
core/include/component/ComponentManager.hpp
Floriantoine/MyHunter_Sfml
8744e1b03d9d5fb621f9cba7619d9d5dd943e428
[ "MIT" ]
null
null
null
core/include/component/ComponentManager.hpp
Floriantoine/MyHunter_Sfml
8744e1b03d9d5fb621f9cba7619d9d5dd943e428
[ "MIT" ]
null
null
null
#pragma once #include "../assert.hpp" #include "../types.hpp" #include "./ComponentBase.hpp" #include "tools/Chrono.hpp" #include "tools/jsonTools.hpp" #include <cassert> #include <functional> #include <iostream> #include <memory> #include <unordered_map> #include <vector> namespace fa { class ComponentManager { private: typedef std::function<void(id_t entityId, const nlohmann::json &)> factory_function_t; std::unordered_map<id_t, std::unordered_map<id_t, ComponentBase *>> _componentLists; std::unordered_map<std::string, factory_function_t> _componentNamesList; bool isComponentTypeRegistered(id_t typeId) const; template <class T> bool isComponentTypeRegistered() const { return this->isComponentTypeRegistered(T::getTypeId()); } std::unordered_map<id_t, ComponentBase *> &getComponentList(id_t typeId); bool hasComponent(id_t typeId, id_t entityId); ComponentBase *getComponent(id_t typeId, id_t entityId); void removeComponent(id_t typeId, id_t entityId); public: ComponentManager() = default; ComponentManager(const ComponentManager &) = delete; ComponentManager(ComponentManager &&) = delete; ~ComponentManager(); ComponentManager &operator=(const ComponentManager &) = delete; void clear(); int getComponentCount() const; std::vector<ComponentBase *> getEntityComponentList(id_t entity); template <class T> std::unordered_map<id_t, ComponentBase *> &getComponentList() { return this->getComponentList(T::getTypeId()); } std::vector<std::string> getRegisterComponentNameList() { std::vector<std::string> nameList; for (auto &it: this->_componentNamesList) { nameList.push_back(it.first); } return nameList; } void registerComponentName( const std::string &name, factory_function_t factory) { auto it = this->_componentNamesList.find(name); if (it != this->_componentNamesList.end()) { std::cout << "component already register for: " << name << std::endl; return; } this->_componentNamesList[name] = factory; } bool componentNameIsRegister(const std::string &name) { auto it = this->_componentNamesList.find(name); if (it != this->_componentNamesList.end()) { return true; } return false; } template <typename... Args> void addComponent(std::string name, id_t entityId, Args &&...args) { auto it = this->_componentNamesList.find(name); if (it == this->_componentNamesList.end()) { std::cout << "No Component register for: " << name << std::endl; return; } it->second(entityId, std::forward<Args>(args)...); } template <class T, typename... Args> void addComponent(id_t entityId, Args &&...args) { if (this->hasComponent<T>(entityId) != false) { std::cout << "Entity already has component" << std::endl; return; // throw std::overflow_error("Entity already has component"); } T *component = new T(std::forward<Args>(args)...); this->getComponentList<T>()[entityId] = static_cast<ComponentBase *>(component); } template <class T, typename... Args> void addComponentRange(id_t startId, id_t endId, Args &&...args) { if (endId < startId) assert("Bad Range"); for (fa::id_t index = startId; index < endId; index++) { addComponent<T>(index, std::forward<Args>(args)...); } } template <class T> bool hasComponent(id_t entityId) { return this->hasComponent(T::getTypeId(), entityId); } template <class T> T *getComponent(id_t entityId) { STATIC_ASSERT_IS_COMPONENT(T); return static_cast<T *>(this->getComponent(T::getTypeId(), entityId)); } template <class T> void removeComponentRange(id_t startId, id_t endId) { if (endId < startId) assert("Bad Range"); for (fa::id_t index = startId; index < endId; index++) { this->removeComponent(T::getTypeId(), index); } } template <class T> void removeComponent(id_t entityId) { if (this->hasComponent<T>(entityId) == false) throw std::overflow_error("Entity does not have component"); this->removeComponent(T::getTypeId(), entityId); } void removeAllComponents(id_t entityId); void removeAllComponentsRange(id_t entityIdMin, id_t entityIdMax); template <class T> void apply(std::function<void(T *)> function) { const auto &list = this->getComponentList<T>(); for (auto it = list.begin(), next = it; it != list.end(); it = next) { next++; function(static_cast<T *>(it->second)); } } template <class T> void apply(std::function<void( T *, id_t, const std::unordered_map<id_t, ComponentBase *> &)> function) { if (this->isComponentTypeRegistered<T>()) { const auto &list = this->getComponentList<T>(); for (auto it = list.begin(), next = it; it != list.end(); it = next) { next++; function(static_cast<T *>(it->second), it->first, list); } } } template <class T> void apply(id_t entityId, std::function<void(T *)> function) { function(static_cast<T *>(this->getComponent<T>(entityId))); } }; } // namespace fa
30.603261
78
0.604866
Floriantoine
c54a1e61064a6e382807f76565563f4de81af472
2,104
hpp
C++
include/sysmakeshift/detail/transaction.hpp
mbeutel/sysmakeshift
d6451315281b229222cb77f916c36b831acb054c
[ "BSL-1.0" ]
2
2020-11-15T14:09:17.000Z
2022-01-14T15:20:02.000Z
include/sysmakeshift/detail/transaction.hpp
mbeutel/sysmakeshift
d6451315281b229222cb77f916c36b831acb054c
[ "BSL-1.0" ]
2
2020-02-16T02:20:22.000Z
2020-02-16T20:49:03.000Z
include/sysmakeshift/detail/transaction.hpp
mbeutel/sysmakeshift
d6451315281b229222cb77f916c36b831acb054c
[ "BSL-1.0" ]
1
2021-09-02T07:44:42.000Z
2021-09-02T07:44:42.000Z
#ifndef INCLUDED_SYSMAKESHIFT_DETAIL_TRANSACTION_HPP_ #define INCLUDED_SYSMAKESHIFT_DETAIL_TRANSACTION_HPP_ #include <utility> // for move(), exchange() #include <type_traits> // for integral_constant<> namespace sysmakeshift { namespace detail { // TODO: Should this be in gsl-lite? B. Stroustrup rightfully claims that `on_success()`, `on_error()`, and `finally()` are the elementary operations here, but // calling `uncaught_exceptions()` does have a cost, so maybe a transaction is still a useful thing. template <typename RollbackFuncT> class transaction_t : private RollbackFuncT { private: bool done_; public: constexpr transaction_t(RollbackFuncT&& rollbackFunc) : RollbackFuncT(std::move(rollbackFunc)), done_(false) { } ~transaction_t(void) { if (!done_) { static_cast<RollbackFuncT&>(*this)(); } } constexpr void commit(void) noexcept { done_ = true; } constexpr transaction_t(transaction_t&& rhs) // pre-C++17 tax : RollbackFuncT(std::move(rhs)), done_(std::exchange(rhs.done_, true)) { } transaction_t& operator =(transaction_t&&) = delete; }; class no_op_transaction_t { public: constexpr void commit(void) noexcept { } no_op_transaction_t(void) noexcept = default; no_op_transaction_t(no_op_transaction_t&&) = default; no_op_transaction_t& operator =(no_op_transaction_t&&) = delete; }; template <typename RollbackFuncT> constexpr transaction_t<RollbackFuncT> make_transaction(RollbackFuncT rollbackFunc) { return { std::move(rollbackFunc) }; } template <typename RollbackFuncT> constexpr transaction_t<RollbackFuncT> make_transaction(std::true_type /*enableRollback*/, RollbackFuncT rollbackFunc) { return { std::move(rollbackFunc) }; } template <typename RollbackFuncT> constexpr no_op_transaction_t make_transaction(std::false_type /*enableRollback*/, RollbackFuncT) { return { }; } } // namespace detail } // namespace sysmakeshift #endif // INCLUDED_SYSMAKESHIFT_DETAIL_TRANSACTION_HPP_
23.909091
163
0.710076
mbeutel
c54a6db60416ac3dcb710cdfae8fc0cd9c344f24
394
hpp
C++
common/cxx/adstutil_cxx/include/adstutil_cxx/make_array.hpp
csitarichie/someip_cyclone_dds_bridge
2ccaaa6e2484a938b08562497431df61ab23769f
[ "MIT" ]
null
null
null
common/cxx/adstutil_cxx/include/adstutil_cxx/make_array.hpp
csitarichie/someip_cyclone_dds_bridge
2ccaaa6e2484a938b08562497431df61ab23769f
[ "MIT" ]
null
null
null
common/cxx/adstutil_cxx/include/adstutil_cxx/make_array.hpp
csitarichie/someip_cyclone_dds_bridge
2ccaaa6e2484a938b08562497431df61ab23769f
[ "MIT" ]
null
null
null
#pragma once #include <array> namespace adst::common { template <typename... T> constexpr auto make_array(T&&... values) -> std::array<typename std::decay<typename std::common_type<T...>::type>::type, sizeof...(T)> { return std::array<typename std::decay<typename std::common_type<T...>::type>::type, sizeof...(T)>{ std::forward<T>(values)...}; } } // namespace adst::common
26.266667
102
0.64467
csitarichie
c54b7a848a2452a52969d35624503c2a453077a4
8,895
cpp
C++
src/ISOBMFF.cpp
Ultraschall/ultraschall-3
7e2479fc0eb877a9b4979bedaf92f95bad627073
[ "MIT" ]
11
2018-07-08T09:14:22.000Z
2019-11-08T02:54:42.000Z
src/ISOBMFF.cpp
Ultraschall/ultraschall-3
7e2479fc0eb877a9b4979bedaf92f95bad627073
[ "MIT" ]
17
2018-01-18T23:12:15.000Z
2019-02-03T07:47:51.000Z
src/ISOBMFF.cpp
Ultraschall/ultraschall-3
7e2479fc0eb877a9b4979bedaf92f95bad627073
[ "MIT" ]
4
2018-03-07T19:38:29.000Z
2019-01-10T09:04:05.000Z
//////////////////////////////////////////////////////////////////////////////// // // Copyright (c) The Ultraschall Project (http://ultraschall.fm) // // The MIT License (MIT) // // 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 <cstring> #include "ISOBMFF.h" #include "Common.h" #include "FileManager.h" #include "Marker.h" #include "PictureUtilities.h" #define MP4V2_EXPORTS 0 #define MP4V2_NO_STDINT_DEFS 1 #include <mp4v2/mp4v2.h> namespace ultraschall { namespace reaper { namespace isobmff { Context* StartTransaction(const UnicodeString& targetName) { PRECONDITION_RETURN(targetName.empty() == false, 0); return new Context(targetName); } bool CommitTransaction(Context*& context) { PRECONDITION_RETURN(context->IsValid(), false); const bool success = MP4TagsStore(context->Tags(), context->Target()); SafeDelete(context); return success; } void AbortTransaction(Context*& context) { SafeDelete(context); } static MP4TagArtworkType QueryArtworkType(const uint8_t* data, const size_t dataSize) { PRECONDITION_RETURN(data != nullptr, MP4_ART_UNDEFINED); PRECONDITION_RETURN(dataSize > 0, MP4_ART_UNDEFINED); MP4TagArtworkType mp4_format = MP4_ART_UNDEFINED; switch(QueryPictureFormat(data, dataSize)) { case PICTURE_FORMAT::JPEG_PICTURE: { mp4_format = MP4_ART_JPEG; break; } case PICTURE_FORMAT::PNG_PICTURE: { mp4_format = MP4_ART_PNG; break; } default: { break; } } return mp4_format; } static double QueryDuration(const Context* context) { PRECONDITION_RETURN(context != nullptr, -1); PRECONDITION_RETURN(context->IsValid(), -1); const uint32_t scale = MP4GetTimeScale(context->Target()); const MP4Duration duration = MP4GetDuration(context->Target()); return static_cast<double>(duration / scale); } static std::vector<MP4Chapter_t> ConvertChapters(const MarkerArray& chapterMarkers, const double maxDuration) { PRECONDITION_RETURN(chapterMarkers.empty() == false, std::vector<MP4Chapter_t>()); PRECONDITION_RETURN(maxDuration >= 0, std::vector<MP4Chapter_t>()); std::vector<MP4Chapter_t> result; // mp4v2 library has a define named MP4V2_CHAPTER_TITLE_MAX which is 1023 // However when mp4v2 library is writing Nero chapter in MP4File::AddNeroChapter() the title // will be further truncated to 255 byte length disregarding any possible utf8 multi-byte characters. // So we have to take care of properly truncating to that size ourselves beforehand. // This function does not do so itself but expects such truncated input. const size_t maxTitleBytes = std::min(255, MP4V2_CHAPTER_TITLE_MAX); double currentStart = 0; for(size_t i = 0; i < chapterMarkers.size(); i++) { double currentDuration = (i == chapterMarkers.size() - 1) ? maxDuration : chapterMarkers[i + 1].Position() - chapterMarkers[i].Position(); // if we run over the total size clients (like VLC) may get confused if(currentStart + currentDuration > maxDuration) { currentDuration = maxDuration - currentStart; } MP4Chapter_t currentChapter = {0}; currentChapter.duration = static_cast<uint32_t>(currentDuration * 1000); const UnicodeString& markerName = chapterMarkers[i].Name(); if(markerName.empty() == false) { const size_t markerNameSize = std::min(markerName.size(), maxTitleBytes); memset(currentChapter.title, 0, (markerNameSize + 1) * sizeof(char)); memmove(currentChapter.title, markerName.c_str(), markerNameSize); result.push_back(currentChapter); } currentStart += currentDuration; } return result; } bool InsertName(const Context* context, const UnicodeString& name) { PRECONDITION_RETURN(context != nullptr, false); PRECONDITION_RETURN(context->IsValid() != false, false); PRECONDITION_RETURN(name.empty() == false, false); return MP4TagsSetName(context->Tags(), name.c_str()); } bool InsertArtist(const Context* context, const UnicodeString& artist) { PRECONDITION_RETURN(context != nullptr, false); PRECONDITION_RETURN(context->IsValid() != false, false); PRECONDITION_RETURN(artist.empty() == false, false); return MP4TagsSetArtist(context->Tags(), artist.c_str()); } bool InsertAlbum(const Context* context, const UnicodeString& album) { PRECONDITION_RETURN(context != nullptr, false); PRECONDITION_RETURN(context->IsValid() != false, false); PRECONDITION_RETURN(album.empty() == false, false); return MP4TagsSetAlbum(context->Tags(), album.c_str()); } bool InsertReleaseDate(const Context* context, const UnicodeString& releaseDate) { PRECONDITION_RETURN(context != nullptr, false); PRECONDITION_RETURN(context->IsValid() != false, false); PRECONDITION_RETURN(releaseDate.empty() == false, false); return MP4TagsSetReleaseDate(context->Tags(), releaseDate.c_str()); } bool InsertGenre(const Context* context, const UnicodeString& genre) { PRECONDITION_RETURN(context != nullptr, false); PRECONDITION_RETURN(context->IsValid() != false, false); PRECONDITION_RETURN(genre.empty() == false, false); return MP4TagsSetGenre(context->Tags(), genre.c_str()); } bool InsertComments(const Context* context, const UnicodeString& comments) { PRECONDITION_RETURN(context != nullptr, false); PRECONDITION_RETURN(context->IsValid() != false, false); PRECONDITION_RETURN(comments.empty() == false, false); return MP4TagsSetComments(context->Tags(), comments.c_str()); } bool InsertCoverImage(const Context* context, const UnicodeString& file) { PRECONDITION_RETURN(context != nullptr, false); PRECONDITION_RETURN(context->IsValid() != false, false); PRECONDITION_RETURN(file.empty() == false, false); bool result = false; BinaryStream* picture = FileManager::ReadBinaryFile(file); if(picture != nullptr) { MP4TagArtwork mp4ArtWork; mp4ArtWork.size = static_cast<uint32_t>(picture->DataSize()); mp4ArtWork.data = const_cast<void*>(static_cast<const void*>(picture->Data())); mp4ArtWork.type = QueryArtworkType(picture->Data(), picture->DataSize()); if(mp4ArtWork.type != MP4_ART_UNDEFINED) { bool removedAll = true; while((context->Tags()->artworkCount > 0) && (true == removedAll)) { removedAll = MP4TagsRemoveArtwork(context->Tags(), 0); } if(true == removedAll) { result = MP4TagsAddArtwork(context->Tags(), &mp4ArtWork); } } SafeRelease(picture); } return result; } bool InsertChapterMarkers(const Context* context, const MarkerArray& markers) { PRECONDITION_RETURN(context != nullptr, false); PRECONDITION_RETURN(context->IsValid() != false, false); PRECONDITION_RETURN(markers.empty() == false, false); bool result = false; const double duration = QueryDuration(context); if(duration >= 0) // this is safe! { std::vector<MP4Chapter_t> chapters = ConvertChapters(markers, duration); if(chapters.empty() == false) { const MP4ChapterType type = MP4SetChapters( context->Target(), &chapters[0], static_cast<uint32_t>(chapters.size()), MP4ChapterTypeAny); if(MP4ChapterTypeAny == type) { result = true; } } } return result; } }}} // namespace ultraschall::reaper::isobmff
33.821293
109
0.665318
Ultraschall
c54dedd28857f908927db90eab10f5938387c41e
1,430
hpp
C++
cppcache/integration-test/TimeBomb.hpp
alb3rtobr/geode-native
bab0b5238b6b7688645a935bbaa74532f0f4d9b8
[ "Apache-2.0" ]
null
null
null
cppcache/integration-test/TimeBomb.hpp
alb3rtobr/geode-native
bab0b5238b6b7688645a935bbaa74532f0f4d9b8
[ "Apache-2.0" ]
null
null
null
cppcache/integration-test/TimeBomb.hpp
alb3rtobr/geode-native
bab0b5238b6b7688645a935bbaa74532f0f4d9b8
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ #pragma once #ifndef GEODE_INTEGRATION_TEST_TIMEBOMB_H_ #define GEODE_INTEGRATION_TEST_TIMEBOMB_H_ #include <condition_variable> #include <functional> #include <mutex> #include <thread> class TimeBomb { public: explicit TimeBomb(const std::chrono::milliseconds& sleep, std::function<void()> cleanup); ~TimeBomb() noexcept; void arm(); void disarm(); void run(); protected: bool enabled_; std::mutex mutex_; std::condition_variable cv_; std::thread thread_; std::function<void()> callback_; std::chrono::milliseconds sleep_; }; #endif // GEODE_INTEGRATION_TEST_TIMEBOMB_H_
28.039216
75
0.739161
alb3rtobr
c54e48b694238e9352bda8d66173e8da7373209b
1,541
cpp
C++
shape.cpp
anthony-bartman/Painting-Pixels
ec820fc1fa422c0d4ca10dedfe83d8a9bce61b92
[ "MIT" ]
null
null
null
shape.cpp
anthony-bartman/Painting-Pixels
ec820fc1fa422c0d4ca10dedfe83d8a9bce61b92
[ "MIT" ]
null
null
null
shape.cpp
anthony-bartman/Painting-Pixels
ec820fc1fa422c0d4ca10dedfe83d8a9bce61b92
[ "MIT" ]
null
null
null
/** * Anthony Bartman * Dr. Varnell * Computer Graphics: CS 3210 021 * 05/03/2020 * * Desc: * This file handles all of the shape method functions. */ #include "shape.h" /********************************************************* * Construction / Destruction *********************************************************/ //Constructor (Shape s;) shape::shape() { //Sets shape color to black this->color = 0x000000; } //Parameterized Constructor (Shape s(red);) shape::shape(unsigned int color) { //Set color (Make it a 24-bit value) //color &= !(0xFFFFFF00); this->color = color; } //Copy Constructor (Shape s = s1;) shape::shape(const shape &rhs) { //Set color this->color = rhs.color; } //Virtual Destructor shape::~shape() {} /********************************************************* * Assignement Operators *********************************************************/ //Equals Operator (s1 = s2;) shape &shape::operator=(const shape &rhs) { //Checks if the shape is not equalling itself; for efficiency purposes if (this != &rhs) { //Set color this->color = rhs.color; } } /********************************************************* * Utility operations *********************************************************/ //Dumps shape properties to the output stream ostream &shape::out(ostream &os) const { os << this->color << endl; } //Read shape properties from a text file istream &shape::in(istream &is){ int color; is >> color; this->color = color; }
23.707692
74
0.491239
anthony-bartman
c55a096e83e4da80b2c6fd24b9ba7cd94c0f4319
1,139
cpp
C++
chapter11/ex09_binary_io.cpp
ClassAteam/stroustrup-ppp
ea9e85d4ea9890038eb5611c3bc82734c8706ce7
[ "MIT" ]
124
2018-06-23T10:16:56.000Z
2022-03-19T15:16:12.000Z
chapter11/ex09_binary_io.cpp
therootfolder/stroustrup-ppp
b1e936c9a67b9205fdc9712c42496b45200514e2
[ "MIT" ]
23
2018-02-08T20:57:46.000Z
2021-10-08T13:58:29.000Z
chapter11/ex09_binary_io.cpp
ClassAteam/stroustrup-ppp
ea9e85d4ea9890038eb5611c3bc82734c8706ce7
[ "MIT" ]
65
2019-05-27T03:05:56.000Z
2022-03-26T03:43:05.000Z
#include "../text_lib/std_lib_facilities.h" vector<int> binary_in(const string& fname) // read in a file and store as binary in vector { ifstream ifs {fname, ios_base::binary}; if (!ifs) error("can't read from file ", fname); vector<int> v; for (int x; ifs.read(as_bytes(x), sizeof(int)); ) v.push_back(x); return v; } void binary_out(const string& fname, const vector<int>& v) // write out to a file from binary { ofstream ofs {fname, ios_base::binary}; if (!ofs) error("could not write to file ", fname); for (int x : v) ofs.write(as_bytes(x), sizeof(int)); } int main() try { // open an istream for binary input from a file: cout << "Please enter input file name\n"; string iname; cin >> iname; vector<int> bin = binary_in(iname); // open an ostream for binary output to a file: cout << "Please enter output file name\n"; string oname; cin >> oname; binary_out(oname, bin); return 0; } catch(exception& e) { cerr << "Exception: " << e.what() << '\n'; return 1; } catch(...) { cerr << "exception\n"; return 2; }
22.333333
58
0.604039
ClassAteam
c55c929cdfd49640ca3edc33507edc00a4002221
22,593
cpp
C++
src/OpcUaStackCore/Base/DataMemArray.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
108
2018-10-08T17:03:32.000Z
2022-03-21T00:52:26.000Z
src/OpcUaStackCore/Base/DataMemArray.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
287
2018-09-18T14:59:12.000Z
2022-01-13T12:28:23.000Z
src/OpcUaStackCore/Base/DataMemArray.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
32
2018-10-19T14:35:03.000Z
2021-11-12T09:36:46.000Z
/* Copyright 2017 Kai Huebl (kai@huebl-sgh.de) Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser Datei nur in Übereinstimmung mit der Lizenz erlaubt. Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0. Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart, erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend. Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen im Rahmen der Lizenz finden Sie in der Lizenz. Autor: Kai Huebl (kai@huebl-sgh.de) */ #include <cstring> #include <iostream> #include "OpcUaStackCore/Base/Log.h" #include "OpcUaStackCore/Base/DataMemArray.h" namespace OpcUaStackCore { // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // // DataMemArrayHeader // // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ DataMemArrayHeader::DataMemArrayHeader(void) { } DataMemArrayHeader::~DataMemArrayHeader(void) { } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // // DataMemArraySlot // // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ DataMemArraySlot::DataMemArraySlot(void) { } DataMemArraySlot::~DataMemArraySlot(void) { } void DataMemArraySlot::set(const char* buf, uint32_t bufLen) { char* mem = (char*)this + sizeof(DataMemArraySlot); memcpy(mem, buf, bufLen); } bool DataMemArraySlot::get(char* buf, uint32_t& bufLen) { if (dataSize_ > bufLen) { return false; } char* mem = (char*)this + sizeof(DataMemArraySlot); memcpy(buf, mem, dataSize_); bufLen = dataSize_; return true; } bool DataMemArraySlot::get(char** buf, uint32_t& bufLen) { *buf = (char*)this + sizeof(DataMemArraySlot); bufLen = dataSize_; return true; } bool DataMemArraySlot::isStartSlot(void) { return type_ == 'S'; } bool DataMemArraySlot::isEndSlot(void) { return type_ == 'E'; } bool DataMemArraySlot::isFreeSlot(void) { return type_ == 'F'; } bool DataMemArraySlot::isUsedSlot(void) { return type_ == 'U'; } DataMemArraySlot* DataMemArraySlot::next(void) { if (type_ == 'E') return nullptr; DataMemArraySlot* slot = (DataMemArraySlot*)((char*)this + sizeof(DataMemArraySlot) + memSize() + sizeof(uint32_t)); return slot; } DataMemArraySlot* DataMemArraySlot::last(void) { if (type_ == 'S') return nullptr; uint32_t *memSize = (uint32_t*)((char*)this - sizeof(uint32_t)); DataMemArraySlot* slot = (DataMemArraySlot*)((char*)this - sizeof(uint32_t) - *memSize - sizeof(DataMemArraySlot)); return slot; } uint32_t DataMemArraySlot::dataSize(void) { return dataSize_; } uint32_t DataMemArraySlot::paddingSize(void) { return paddingSize_; } uint32_t DataMemArraySlot::memSize(void) { return dataSize_ + paddingSize_; } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // // DataMemArray // // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ uint32_t DataMemArray::minMemorySize_ = 100; DataMemArray::DataMemArray(void) : debug_(true) , dataMemArrayHeader_(nullptr) , freeSlotMap_() , startMemorySize_(10000) , maxMemorySize_(1000000) , expandMemorySize_(10000) { } DataMemArray::~DataMemArray(void) { clear(); } void DataMemArray::startMemorySize(uint32_t startMemorySize) { if (startMemorySize < minMemorySize_) { startMemorySize_ = minMemorySize_; } else { startMemorySize_ = startMemorySize; } } uint32_t DataMemArray::startMemorySize(void) { return startMemorySize_; } void DataMemArray::maxMemorySize(uint32_t maxMemorySize) { if (dataMemArrayHeader_ == nullptr) { if (maxMemorySize < startMemorySize_) { maxMemorySize_ = startMemorySize_; expandMemorySize_ = 0; } else { maxMemorySize_ = maxMemorySize; } } else { if (maxMemorySize < dataMemArrayHeader_->actArraySize_) { dataMemArrayHeader_->maxMemorySize_ = dataMemArrayHeader_->actArraySize_; } else { dataMemArrayHeader_->maxMemorySize_ = maxMemorySize; } } } uint32_t DataMemArray::maxMemorySize(void) { if (dataMemArrayHeader_ == nullptr) { return maxMemorySize_; } else { return dataMemArrayHeader_->maxMemorySize_; } } void DataMemArray::expandMemorySize(uint32_t expandMemorySize) { if (expandMemorySize < (sizeof(DataMemArraySlot) + sizeof(uint32_t))) { expandMemorySize = (sizeof(DataMemArraySlot) + sizeof(uint32_t)); } if (dataMemArrayHeader_ == nullptr) { expandMemorySize_ = expandMemorySize; } else { dataMemArrayHeader_->expandMemorySize_ = expandMemorySize; } } uint32_t DataMemArray::expandMemorySize(void) { return expandMemorySize_; } uint32_t DataMemArray::size(void) { if (dataMemArrayHeader_ == nullptr) { return 0; } return dataMemArrayHeader_->actArraySize_; } bool DataMemArray::resize(uint32_t arraySize) { if (dataMemArrayHeader_ == nullptr) { if (!createNewMemory(arraySize)) return false; return true; } if (arraySize == dataMemArrayHeader_->actArraySize_) { return true; } if (arraySize < dataMemArrayHeader_->actArraySize_) { return decreaseArraySize(arraySize); } else { return increaseArraySize(arraySize); } return true; } bool DataMemArray::unset(uint32_t idx) { if (dataMemArrayHeader_ == nullptr) { return false; } if (idx >= dataMemArrayHeader_->actArraySize_) { return false; } // // get slot // char* mem = (char*)dataMemArrayHeader_ + dataMemArrayHeader_->actMemorySize_; uint32_t* pos = (uint32_t*)(mem - ((idx+1) * sizeof(uint32_t))); if (*pos == 0) { return true; } DataMemArraySlot* slot = posToSlot(*pos); DataMemArraySlot* lastSlot = slot->last(); DataMemArraySlot* nextSlot = slot->next(); // // release slot // uint32_t freeSize = slot->memSize(); if (nextSlot != nullptr && nextSlot->type_ == 'F') { freeSize += (nextSlot->memSize() + sizeof(DataMemArraySlot) + sizeof(uint32_t)); DataMemArraySlot::Map::iterator it; it = freeSlotMap_.find(ptrToPos((char*)nextSlot)); freeSlotMap_.erase(it); } if (lastSlot != nullptr && lastSlot->type_ == 'F') { freeSize += (lastSlot->memSize() + sizeof(DataMemArraySlot) + sizeof(uint32_t)); DataMemArraySlot::Map::iterator it; it = freeSlotMap_.find(ptrToPos((char*)lastSlot)); freeSlotMap_.erase(it); slot = lastSlot; } slot = createNewSlot((char*)slot, 'F', freeSize); freeSlotMap_.insert(std::make_pair(ptrToPos((char*)slot), slot)); // // release array element // *pos = 0; return true; } bool DataMemArray::set(uint32_t idx, const char* buf, uint32_t bufLen) { if (buf == nullptr) { return false; } if (bufLen == 0) { return false; } if (dataMemArrayHeader_ == nullptr) { return false; } if (idx >= dataMemArrayHeader_->actArraySize_) { return false; } // // find free memory slot // DataMemArraySlot* slot = nullptr; DataMemArraySlot::Map::iterator it; for (it = freeSlotMap_.begin(); it != freeSlotMap_.end(); it++) { DataMemArraySlot* tmpSlot = it->second; if (tmpSlot->dataSize() >= bufLen) { slot = tmpSlot; break; } } if (slot == nullptr) { if (increaseMemory(bufLen)) { return set(idx, buf, bufLen); } return false; } // // check available memory in slot // freeSlotMap_.erase(it); if ((bufLen + sizeof(DataMemArraySlot) + sizeof(uint32_t)) >= slot->dataSize()) { // use the entire slot uint32_t padding = slot->dataSize() - bufLen; slot = createNewSlot((char*)slot, 'U', bufLen, padding); } else { // split slot DataMemArraySlot* freeSlot; uint32_t freeSlotSize = slot->dataSize() - bufLen - sizeof(DataMemArraySlot) - sizeof(uint32_t); slot = createNewSlot((char*)slot, 'U', bufLen, 0); freeSlot = createNewSlot((char*)slot + bufLen + sizeof(DataMemArraySlot) + sizeof(uint32_t), 'F', freeSlotSize); freeSlotMap_.insert(std::make_pair(ptrToPos((char*)freeSlot), freeSlot)); } // // set memory and array index // slot->set(buf, bufLen); setIndex(idx, ptrToPos((char*)slot)); return true; } bool DataMemArray::set(uint32_t idx, const std::string& value) { return set(idx, value.c_str(), value.length()); } bool DataMemArray::get(uint32_t idx, char* buf, uint32_t& bufLen) { if (dataMemArrayHeader_ == nullptr) { return false; } if (idx >= dataMemArrayHeader_->actArraySize_) { return false; } char* mem = (char*)dataMemArrayHeader_ + dataMemArrayHeader_->actMemorySize_; uint32_t* pos = (uint32_t*)(mem - ((idx+1) * sizeof(uint32_t))); if (*pos == 0) { return false; } DataMemArraySlot* slot = posToSlot(*pos); return slot->get(buf, bufLen); } bool DataMemArray::get(uint32_t idx, char** buf, uint32_t& bufLen) { if (dataMemArrayHeader_ == nullptr) { return false; } if (idx >= dataMemArrayHeader_->actArraySize_) { return false; } char* mem = (char*)dataMemArrayHeader_ + dataMemArrayHeader_->actMemorySize_; uint32_t* pos = (uint32_t*)(mem - ((idx+1) * sizeof(uint32_t))); if (*pos == 0) { return false; } DataMemArraySlot* slot = posToSlot(*pos); return slot->get(buf, bufLen); } bool DataMemArray::get(uint32_t idx, std::string& value) { char *buf; uint32_t bufLen; if (!get(idx, &buf, bufLen)) { return false; } value = std::string(buf, bufLen); return true; } bool DataMemArray::exist(uint32_t idx) { if (dataMemArrayHeader_ == nullptr) { return false; } char* mem = (char*)dataMemArrayHeader_ + dataMemArrayHeader_->actMemorySize_; uint32_t* pos = (uint32_t*)(mem - ((idx+1) * sizeof(uint32_t))); if (*pos == 0) { return false; } return true; } void DataMemArray::clear(void) { if (dataMemArrayHeader_ != nullptr) { char* mem = (char*)dataMemArrayHeader_; delete [] mem; dataMemArrayHeader_ = nullptr; } freeSlotMap_.clear(); startMemorySize_ = 10000; maxMemorySize_ = 1000000; expandMemorySize_ = 10000; } void DataMemArray::log(void) { logHeader(); logSlot(); logArray(); } void DataMemArray::logHeader(void) { if (dataMemArrayHeader_ == nullptr) { return; } Log(Debug, "Header") .parameter("MaxMemorySize", dataMemArrayHeader_->maxMemorySize_) .parameter("ExpandMemorySize", dataMemArrayHeader_->expandMemorySize_) .parameter("ActMemorySize", dataMemArrayHeader_->actMemorySize_) .parameter("ActArraySize", dataMemArrayHeader_->actArraySize_); } void DataMemArray::logSlot(void) { if (dataMemArrayHeader_ == nullptr) { return; } DataMemArraySlot* slot = firstSlot(); if (slot == nullptr) { return; } do { Log(Debug, "Slot") .parameter("Type", slot->type_) .parameter("Pos", ptrToPos((char*)slot)) .parameter("DataSize", slot->dataSize()) .parameter("PaddingSize", slot->paddingSize()) .parameter("MemSize", slot->memSize()); slot = slot->next(); } while (slot != nullptr); } void DataMemArray::logArray(void) { if (dataMemArrayHeader_ == nullptr) { return; } char* mem = (char*)dataMemArrayHeader_ + dataMemArrayHeader_->actMemorySize_; for (uint32_t idx = 0; idx < dataMemArrayHeader_->actArraySize_; idx++) { uint32_t* pos = (uint32_t*)(mem - ((idx+1) * sizeof(uint32_t))); if (*pos != 0) { DataMemArraySlot* slot = posToSlot(*pos); Log(Debug, "Array") .parameter("Idx", idx) .parameter("Pos", *pos) .parameter("Len", slot->dataSize_); } } } void DataMemArray::logFreeSlots(void) { if (dataMemArrayHeader_ == nullptr) { return; } DataMemArraySlot::Map::iterator it; for (it = freeSlotMap_.begin(); it != freeSlotMap_.end(); it++) { DataMemArraySlot* slot = it->second; Log(Debug, "FreeSlots") .parameter("Pos", it->first) .parameter("Len", slot->dataSize()); } } bool DataMemArray::setMemoryBuf(char* memBuf, uint32_t memLen) { if (memBuf == nullptr) { return false; } if (dataMemArrayHeader_ != nullptr) { clear(); } char* tmpMem = new char [memLen]; memcpy(tmpMem, memBuf, memLen); dataMemArrayHeader_ = (DataMemArrayHeader*)tmpMem; // // create free slot list // freeSlotMap_.clear(); DataMemArraySlot* slot = (DataMemArraySlot*)((char*)dataMemArrayHeader_ + sizeof(DataMemArrayHeader)); while (slot->type_ != 'E') { if (slot->type_ == 'F') { freeSlotMap_.insert(std::make_pair(ptrToPos((char*)slot), slot)); } slot = slot->next(); } return true; } bool DataMemArray::getMemoryBuf(char** memBuf, uint32_t* memLen) { if (dataMemArrayHeader_ == nullptr) { return false; } *memBuf = (char*)dataMemArrayHeader_; *memLen = dataMemArrayHeader_->actMemorySize_; return true; } // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // // private function // // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ DataMemArraySlot* DataMemArray::posToSlot(uint32_t pos) { if (dataMemArrayHeader_ == nullptr) { return nullptr; } return (DataMemArraySlot*)((char*)dataMemArrayHeader_ + pos); } uint32_t DataMemArray::ptrToPos(char* ptr) { if (dataMemArrayHeader_ == nullptr) return 0; return (ptr - (char*)dataMemArrayHeader_); } DataMemArraySlot* DataMemArray::firstSlot(void) { if (dataMemArrayHeader_ == nullptr) { return nullptr; } return (DataMemArraySlot*)((char*)dataMemArrayHeader_ + sizeof(DataMemArrayHeader)); } void DataMemArray::setIndex(uint32_t idx, uint32_t value) { if (dataMemArrayHeader_ == nullptr) { return; } char* mem = (char*)dataMemArrayHeader_ + dataMemArrayHeader_->actMemorySize_; uint32_t* pos = (uint32_t*)(mem - ((idx+1) * sizeof(uint32_t))); *pos = value; } void DataMemArray::getIndex(uint32_t idx, uint32_t& value) { if (dataMemArrayHeader_ == nullptr) { return; } char* mem = (char*)dataMemArrayHeader_ + dataMemArrayHeader_->actMemorySize_; uint32_t* pos = (uint32_t*)(mem - ((idx+1) * sizeof(uint32_t))); value = *pos; } bool DataMemArray::createNewMemory(uint32_t arraySize) { // // calculate used buffer size // // HEAD B-Slot F-Slot E-Slot Array // uint32_t usedMemorySize = sizeof(DataMemArrayHeader) + 3*(sizeof(DataMemArraySlot) + sizeof(uint32_t)) + arraySize * sizeof(char*) + minMemorySize_; // // check max memory size // if (maxMemorySize_ != 0 && usedMemorySize > maxMemorySize_) { Log(Error, "allocate memory error - used memory size is bigger then max memory size") .parameter("Id", this) .parameter("UsedMemorySize", usedMemorySize) .parameter("MaxMemorySize", maxMemorySize_); return false; } // // calculate actual memory size // uint32_t actMemorySize = startMemorySize_; while (usedMemorySize > actMemorySize) actMemorySize += expandMemorySize_; uint32_t dataSize = actMemorySize - sizeof(DataMemArrayHeader) - (3*(sizeof(DataMemArraySlot) + sizeof(uint32_t))) - (arraySize * sizeof(uint32_t)); // // allocate memory and create management structures // if (debug_) { Log(Debug, "create new memory") .parameter("Id", this) .parameter("ArraySize", arraySize) .parameter("MemorySize", actMemorySize) .parameter("DataSize", dataSize); } char* mem = new char[actMemorySize]; memset(mem, 0x0, actMemorySize); // create header dataMemArrayHeader_ = (DataMemArrayHeader*)mem; dataMemArrayHeader_->eye_[0] = 'H'; dataMemArrayHeader_->eye_[1] = 'E'; dataMemArrayHeader_->eye_[2] = 'A'; dataMemArrayHeader_->eye_[3] = 'D'; dataMemArrayHeader_->maxMemorySize_ = maxMemorySize_; dataMemArrayHeader_->expandMemorySize_ = expandMemorySize_; dataMemArrayHeader_->actMemorySize_ = actMemorySize; dataMemArrayHeader_->actArraySize_ = arraySize; // create start slot mem += sizeof(DataMemArrayHeader); createNewSlot(mem, 'S', 0); // create free slot mem += sizeof(DataMemArraySlot) + sizeof(uint32_t); createNewSlot(mem, 'F', dataSize); freeSlotMap_.insert(std::make_pair(ptrToPos(mem), (DataMemArraySlot*)mem)); // create end slot mem += sizeof(DataMemArraySlot) + sizeof(uint32_t) + dataSize; createNewSlot(mem, 'E', 0); return true; } bool DataMemArray::increaseMemory(uint32_t size) { if (dataMemArrayHeader_ == nullptr) { return false; } // calcualte new memory size uint32_t usedMemorySize = dataMemArrayHeader_->actMemorySize_ + size + sizeof(DataMemArraySlot) + sizeof(uint32_t); // // check max memory size // if (maxMemorySize_ != 0 && usedMemorySize > dataMemArrayHeader_->maxMemorySize_) { Log(Error, "increase memory error - used memory size is bigger then max memory size") .parameter("Id", this) .parameter("UsedMemorySize", usedMemorySize) .parameter("MaxMemorySize", dataMemArrayHeader_->maxMemorySize_); return false; } // // calculate actual memory size // uint32_t newMemorySize = dataMemArrayHeader_->actMemorySize_; while (usedMemorySize > newMemorySize) newMemorySize += expandMemorySize_; uint32_t diffMemorySize = newMemorySize - dataMemArrayHeader_->actMemorySize_; uint32_t arrayMemorySize = dataMemArrayHeader_->actArraySize_ * sizeof(uint32_t); uint32_t headerSlotMemorySize = dataMemArrayHeader_->actMemorySize_ - arrayMemorySize; // // create new memory an copy old memory to new memory // char* mem = new char [newMemorySize]; memcpy(mem, (char*)dataMemArrayHeader_, headerSlotMemorySize); memcpy(&mem[newMemorySize-arrayMemorySize], (char*)dataMemArrayHeader_ + headerSlotMemorySize , arrayMemorySize); delete [] (char*)dataMemArrayHeader_; dataMemArrayHeader_ = (DataMemArrayHeader*)mem; dataMemArrayHeader_->actMemorySize_ = newMemorySize; // // create new free slot // char *endSlotMem = (char*)dataMemArrayHeader_ + headerSlotMemorySize - sizeof(DataMemArraySlot) - sizeof(uint32_t); DataMemArraySlot* actSlot = (DataMemArraySlot*)endSlotMem; DataMemArraySlot* lastSlot = actSlot->last(); if (lastSlot->type_ == 'F') { uint32_t newSlotSize = lastSlot->dataSize() + diffMemorySize; actSlot = createNewSlot((char*)lastSlot, 'F', newSlotSize); createNewSlot((char*)actSlot->next(), 'E', 0); } else { uint32_t newSlotSize = diffMemorySize - sizeof(DataMemArraySlot) - sizeof(uint32_t); actSlot = createNewSlot((char*)actSlot, 'F', newSlotSize); createNewSlot((char*)actSlot->next(), 'E', 0); } // // create free slot list // freeSlotMap_.clear(); DataMemArraySlot* slot = (DataMemArraySlot*)((char*)dataMemArrayHeader_ + sizeof(DataMemArrayHeader)); while (slot->type_ != 'E') { if (slot->type_ == 'F') { freeSlotMap_.insert(std::make_pair(ptrToPos((char*)slot), slot)); } slot = slot->next(); } return true; } DataMemArraySlot* DataMemArray::createNewSlot(char* mem, char type, uint32_t size, uint32_t paddingSize) { // create header DataMemArraySlot* dataMemArraySlot; dataMemArraySlot = (DataMemArraySlot*)mem; dataMemArraySlot->eye_[0] = 'S'; dataMemArraySlot->eye_[1] = 'L'; dataMemArraySlot->eye_[2] = 'O'; dataMemArraySlot->eye_[3] = 'T'; dataMemArraySlot->type_ = type; dataMemArraySlot->dataSize_ = size; dataMemArraySlot->paddingSize_ = paddingSize; uint32_t* sizeTag = (uint32_t*)(mem + sizeof(DataMemArraySlot) + dataMemArraySlot->memSize()); *sizeTag = dataMemArraySlot->memSize(); return dataMemArraySlot; } bool DataMemArray::increaseArraySize(uint32_t arraySize) { char* memEnd = (char*)dataMemArrayHeader_ + dataMemArrayHeader_->actMemorySize_; uint32_t diffMemorySize = (arraySize - dataMemArrayHeader_->actArraySize_) * sizeof(uint32_t); uint32_t arrayMemorySize = dataMemArrayHeader_->actArraySize_ * sizeof(uint32_t); uint32_t headerSlotMemorySize = dataMemArrayHeader_->actMemorySize_ - arrayMemorySize; // get last two slots char *endSlotMem = (char*)dataMemArrayHeader_ + headerSlotMemorySize - sizeof(DataMemArraySlot) - sizeof(uint32_t); DataMemArraySlot* actSlot = (DataMemArraySlot*)endSlotMem; DataMemArraySlot* lastSlot = actSlot->last(); if (lastSlot->type_ != 'F') { if (increaseMemory(1)) { return increaseArraySize(arraySize); } return false; } if (lastSlot->dataSize() < diffMemorySize) { if (increaseMemory(1)) { return increaseArraySize(arraySize); } return false; } lastSlot->dataSize_ -= diffMemorySize; DataMemArraySlot* slot = lastSlot->next(); createNewSlot((char*)slot, 'E', 0); char* mem = (char*)slot + sizeof(DataMemArraySlot) + sizeof(uint32_t); memset(mem, 0x00, diffMemorySize); dataMemArrayHeader_->actArraySize_ = arraySize; return true; } bool DataMemArray::decreaseArraySize(uint32_t arraySize) { char* memEnd = (char*)dataMemArrayHeader_ + dataMemArrayHeader_->actMemorySize_; uint32_t diffMemorySize = (dataMemArrayHeader_->actArraySize_ - arraySize) * sizeof(uint32_t); uint32_t arrayMemorySize = dataMemArrayHeader_->actArraySize_ * sizeof(uint32_t); uint32_t headerSlotMemorySize = dataMemArrayHeader_->actMemorySize_ - arrayMemorySize; // remove entries for (uint32_t idx = arraySize; idx < dataMemArrayHeader_->actMemorySize_; idx++) { unset(idx); } dataMemArrayHeader_->actArraySize_ = arraySize; // // move end slot // char *endSlotMem = (char*)dataMemArrayHeader_ + headerSlotMemorySize - sizeof(DataMemArraySlot) - sizeof(uint32_t); DataMemArraySlot* actSlot = (DataMemArraySlot*)endSlotMem; DataMemArraySlot* lastSlot = actSlot->last(); if (lastSlot->type_ == 'U') { lastSlot->paddingSize_ += diffMemorySize; } else { lastSlot->dataSize_ += diffMemorySize; } DataMemArraySlot* slot = lastSlot->next(); createNewSlot((char*)slot, 'E', 0); return true; } }
24.909592
118
0.653565
gianricardo
c55d3b2b1b9849962d00f948cc8c4610eef73a73
426
cpp
C++
srcs/tc.common/byte_buffer.cpp
aoziczero/libtc
7f5afc2324bc91bf38e53b474d80804b48b546a5
[ "MIT" ]
null
null
null
srcs/tc.common/byte_buffer.cpp
aoziczero/libtc
7f5afc2324bc91bf38e53b474d80804b48b546a5
[ "MIT" ]
null
null
null
srcs/tc.common/byte_buffer.cpp
aoziczero/libtc
7f5afc2324bc91bf38e53b474d80804b48b546a5
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "byte_buffer.hpp" namespace tc { namespace buffer { position::position(void) : read(0), write(0) {} position::position(const position& rhs) : read(rhs.read), write(rhs.write) {} position& position::operator=(const position& rhs) { read = rhs.read; write = rhs.write; return *this; } void position::swap( position& rhs) { std::swap(read, rhs.read); std::swap(write, rhs.write); } } }
17.04
52
0.673709
aoziczero
c5616bc52ef596f1e13ae3119a9f081d71454c08
6,722
cpp
C++
RogueEngine/Source/LightingSystem.cpp
silferysky/RogueArcher
3c77696260f773a0b7adb88b991e09bb35069901
[ "FSFAP" ]
1
2019-06-18T20:07:47.000Z
2019-06-18T20:07:47.000Z
RogueEngine/Source/LightingSystem.cpp
silferysky/RogueArcher
3c77696260f773a0b7adb88b991e09bb35069901
[ "FSFAP" ]
null
null
null
RogueEngine/Source/LightingSystem.cpp
silferysky/RogueArcher
3c77696260f773a0b7adb88b991e09bb35069901
[ "FSFAP" ]
null
null
null
/* Start Header ************************************************************************/ /*! \file LightingSystem.cpp \project Exale \author Javier Foo, javier.foo, 440002318 (100%) \par javier.foo\@digipen.edu \date 3 April,2020 \brief This file contains the functions definitions for LightingSystem All content (C) 2020 DigiPen (SINGAPORE) Corporation, all rights reserved. Reproduction or disclosure of this file or its contents without the prior written consent of DigiPen Institute of Technology is prohibited. */ /* End Header **************************************************************************/ #include "Precompiled.h" #include "LightingSystem.h" #include "Main.h" #include "CameraManager.h" #include "CollisionManager.h" #include "PickingManager.h" namespace Rogue { LightingSystem::LightingSystem() : System(SystemID::id_LIGHTINGSYSTEM) {} void LightingSystem::Init() { REGISTER_LISTENER(SystemID::id_LIGHTINGSYSTEM, LightingSystem::Receive); // Add components to signature Signature signature; signature.set(g_engine.m_coordinator.GetComponentType<LightComponent>()); signature.set(g_engine.m_coordinator.GetComponentType<TransformComponent>()); // Set graphics system signature g_engine.m_coordinator.SetSystemSignature<LightingSystem>(signature); m_shader = g_engine.m_coordinator.loadShader("Lighting Shader"); m_uboMatrices = g_engine.m_coordinator.GetSystem<Rogue::GraphicsSystem>()->getUBOMatrices(); m_transformLocation = glGetUniformLocation(m_shader.GetShader(), "transform"); m_pCamera = g_engine.m_coordinator.GetSystem<CameraSystem>(); m_graphicsShader = g_engine.m_coordinator.GetSystem<GraphicsSystem>()->getShader(); m_totalLightsLocation = glGetUniformLocation(m_graphicsShader.GetShader(), "numLights"); GenerateQuadPrimitive(m_VBO, m_VAO, m_EBO); } void LightingSystem::Update() { } void LightingSystem::draw(Entity& entity) { auto& transform = g_engine.m_coordinator.GetComponent<TransformComponent>(entity); auto transformMat = glm::mat4(1.0f); transformMat = glm::translate(transformMat, { transform.GetPosition().x, transform.GetPosition().y, 1.0f }); transformMat = glm::rotate(transformMat, transform.GetRotation(), glm::vec3(0.0f, 0.0f, 1.0f)); transformMat = glm::scale(transformMat, glm::vec3(10.0f)); // model to world, world to view, view to projection glUniformMatrix4fv(m_transformLocation, 1, GL_FALSE, glm::value_ptr(transformMat)); // Draw the Mesh glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); } void LightingSystem::TrueUpdate() { //g_engine.m_coordinator.InitTimeSystem("Lighting System"); if (m_entities.size() == 0) return; PickingManager::instance().GenerateViewPortAABB(CameraManager::instance().GetCameraPos(), CameraManager::instance().GetCameraZoom()); AABB viewPort = PickingManager::instance().GetViewPortArea(); viewPort += 200; glUseProgram(m_shader.GetShader()); glBindVertexArray(m_VAO); glBindBuffer(GL_ARRAY_BUFFER, m_VBO); glBindBuffer(GL_UNIFORM_BUFFER, m_uboMatrices); //glBufferSubData(GL_UNIFORM_BUFFER, 0, sizeof(glm::mat4), glm::value_ptr(g_engine.GetProjMat())); //glBufferSubData(GL_UNIFORM_BUFFER, sizeof(glm::mat4), sizeof(glm::mat4), glm::value_ptr(m_pCamera->GetViewMatrix())); // For all entities for (auto entity : m_entities) { //auto& transform = g_engine.m_coordinator.GetComponent<TransformComponent>(entity); //if (CollisionManager::instance().DiscretePointVsAABB(transform.GetPosition(), viewPort)) ++totalLights; // AddLights(entity); if (!g_engine.m_coordinator.GetGameState()) draw(entity); } glBindBuffer(GL_UNIFORM_BUFFER, 0); glUseProgram(0); glBindVertexArray(0); //Reset glBindBuffer(GL_ARRAY_BUFFER, 0); glUseProgram(m_graphicsShader.GetShader()); glUniform1i(m_totalLightsLocation, totalLights); // For all entities for (auto entity : m_entities) { --totalLights; auto& transform = g_engine.m_coordinator.GetComponent<TransformComponent>(entity); if (CollisionManager::instance().DiscretePointVsAABB(transform.GetPosition(), viewPort)) UpdateShader(entity); else ClearLight(); } glUseProgram(0); //g_engine.m_coordinator.EndTimeSystem("Lighting System"); } void LightingSystem::AddLights(Entity& entity) { auto& light = g_engine.m_coordinator.GetComponent<LightComponent>(entity); auto position = g_engine.m_coordinator.GetComponent<TransformComponent>(entity).GetPosition(); LightProperites newLight; newLight.position = { position.x, position.y, 1.0f }; newLight.ambient = light.getAmbientFactor(); newLight.specular = light.getSpecularFactor(); newLight.radius = light.getRadius(); newLight.tint = light.getTint(); lights[totalLights] = newLight; } void LightingSystem::UpdateShader(Entity& entity) { auto& light = g_engine.m_coordinator.GetComponent<LightComponent>(entity); auto position = g_engine.m_coordinator.GetComponent<TransformComponent>(entity).GetPosition(); std::string lightLocation = "light[" + std::to_string(totalLights) + ']'; float ambient = light.getAmbientFactor(); float specular = light.getSpecularFactor(); float radius = light.getRadius(); glm::vec4 tint = light.getTint(); glUniform3f(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".position").c_str()), position.x, position.y, 1.0f); glUniform1f(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".ambient").c_str()), ambient); glUniform1f(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".specular").c_str()), specular); glUniform1f(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".radius").c_str()), radius); glUniform4fv(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".tint").c_str()), 1, glm::value_ptr(tint)); } void LightingSystem::ClearLight() { std::string lightLocation = "light[" + std::to_string(totalLights) + ']'; glm::vec4 tint{}; glUniform3f(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".position").c_str()), 0.0f, 0.0f, 1.0f); glUniform1f(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".ambient").c_str()), 0.0f); glUniform1f(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".specular").c_str()), 0.0f); glUniform1f(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".radius").c_str()), 0.0f); glUniform4fv(glGetUniformLocation(m_graphicsShader.GetShader(), (lightLocation + ".tint").c_str()), 1, glm::value_ptr(tint)); } void LightingSystem::Shutdown() {} void LightingSystem::Receive(Event& ev) {} }
35.566138
135
0.728652
silferysky
c5618218a5567b0c742550c8da8eb15e33e41a31
2,541
cpp
C++
src/system/boot/platform/riscv/mmu.cpp
X547/haiku
87555a1f4f2fdab7617c670ef0b5875698e5db63
[ "MIT" ]
2
2021-06-05T20:29:57.000Z
2021-06-20T10:46:56.000Z
src/system/boot/platform/riscv/mmu.cpp
X547/haiku
87555a1f4f2fdab7617c670ef0b5875698e5db63
[ "MIT" ]
null
null
null
src/system/boot/platform/riscv/mmu.cpp
X547/haiku
87555a1f4f2fdab7617c670ef0b5875698e5db63
[ "MIT" ]
null
null
null
/* * Copyright 2004-2007, Axel Dörfler, axeld@pinc-software.de. * Based on code written by Travis Geiselbrecht for NewOS. * * Distributed under the terms of the MIT License. */ #include "mmu.h" #include <boot/platform.h> #include <boot/stdio.h> #include <boot/kernel_args.h> #include <boot/stage2.h> #include <arch/cpu.h> #include <arch_kernel.h> #include <kernel.h> #include <OS.h> #include <string.h> extern uint8 gStackEnd; uint8 *gMemBase = NULL; size_t gTotalMem = 0; uint8 *gFreeMem = &gStackEnd; // #pragma mark - extern "C" status_t platform_allocate_region(void **_address, size_t size, uint8 protection, bool exactAddress) { if (exactAddress) return B_ERROR; gFreeMem = (uint8*)(((addr_t)gFreeMem + (B_PAGE_SIZE - 1)) / B_PAGE_SIZE * B_PAGE_SIZE); *_address = gFreeMem; gFreeMem += size; return B_OK; } extern "C" status_t platform_free_region(void *address, size_t size) { return B_OK; } void platform_release_heap(struct stage2_args *args, void *base) { } status_t platform_init_heap(struct stage2_args *args, void **_base, void **_top) { void *heap = (void *)gFreeMem; gFreeMem += args->heap_size; *_base = heap; *_top = (void *)((int8 *)heap + args->heap_size); return B_OK; } status_t platform_bootloader_address_to_kernel_address(void *address, addr_t *_result) { *_result = (addr_t)address; return B_OK; } status_t platform_kernel_address_to_bootloader_address(addr_t address, void **_result) { *_result = (void*)address; return B_OK; } void mmu_init(void) { } void mmu_init_for_kernel(void) { // map in a kernel stack void *stack_address = NULL; if (platform_allocate_region(&stack_address, KERNEL_STACK_SIZE + KERNEL_STACK_GUARD_PAGES * B_PAGE_SIZE, 0, false) != B_OK) { panic("Unabled to allocate a stack"); } gKernelArgs.cpu_kstack[0].start = (addr_t)stack_address; gKernelArgs.cpu_kstack[0].size = KERNEL_STACK_SIZE + KERNEL_STACK_GUARD_PAGES * B_PAGE_SIZE; dprintf("Kernel stack at %#lx\n", gKernelArgs.cpu_kstack[0].start); gKernelArgs.physical_memory_range[0].start = (addr_t)gMemBase; gKernelArgs.physical_memory_range[0].size = gTotalMem; gKernelArgs.num_physical_memory_ranges = 1; gKernelArgs.physical_allocated_range[0].start = (addr_t)gMemBase; gKernelArgs.physical_allocated_range[0].size = gFreeMem - gMemBase; gKernelArgs.num_physical_allocated_ranges = 1; gKernelArgs.virtual_allocated_range[0].start = (addr_t)gMemBase; gKernelArgs.virtual_allocated_range[0].size = gFreeMem - gMemBase; gKernelArgs.num_virtual_allocated_ranges = 1; }
23.971698
111
0.748524
X547
c573887528dbd30b420c869862d371f8393ea45f
3,599
cpp
C++
src/gravity/grav3D.cpp
capybaras-only/cholla
e82d88440f530adca00e5acdb9ee0da9ba8874de
[ "MIT" ]
42
2016-07-19T02:07:16.000Z
2022-02-22T15:20:07.000Z
src/gravity/grav3D.cpp
capybaras-only/cholla
e82d88440f530adca00e5acdb9ee0da9ba8874de
[ "MIT" ]
34
2018-10-23T04:03:25.000Z
2022-03-24T15:23:36.000Z
src/gravity/grav3D.cpp
capybaras-only/cholla
e82d88440f530adca00e5acdb9ee0da9ba8874de
[ "MIT" ]
30
2016-04-14T17:52:34.000Z
2022-02-25T15:52:02.000Z
#ifdef GRAVITY #include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #include"../global.h" #include "../io.h" #include"grav3D.h" #ifdef PARALLEL_OMP #include "../parallel_omp.h" #endif Grav3D::Grav3D( void ){} void Grav3D::Initialize( Real x_min, Real y_min, Real z_min, Real Lx, Real Ly, Real Lz, int nx, int ny, int nz, int nx_real, int ny_real, int nz_real, Real dx_real, Real dy_real, Real dz_real, int n_ghost_pot_offset, struct parameters *P ) { //Set Box Size Lbox_x = Lx; Lbox_y = Ly; Lbox_z = Lz; //Set Box Left boundary positions xMin = x_min; yMin = y_min; zMin = z_min; //Set uniform ( dx, dy, dz ) dx = dx_real; dy = dy_real; dz = dz_real; //Set Box Total number of cells nx_total = nx; ny_total = ny; nz_total = nz; //Set Box local domain number of cells nx_local = nx_real; ny_local = ny_real; nz_local = nz_real; //Local n_cells without ghost cells n_cells = nx_local*ny_local*nz_local; //Local n_cells including ghost cells for the potential array n_cells_potential = ( nx_local + 2*N_GHOST_POTENTIAL ) * ( ny_local + 2*N_GHOST_POTENTIAL ) * ( nz_local + 2*N_GHOST_POTENTIAL ); //Set Initial and dt used for the extrapolation of the potential; //The first timestep the potetential in not extrapolated ( INITIAL = TRUE ) INITIAL = true; dt_prev = 0; dt_now = 0; #ifdef COSMOLOGY //Set the scale factor for cosmological simulations to 1, //This will be changed to the proper value when cosmology is initialized current_a = 1; #endif //Set the average density=0 ( Not Used ) dens_avrg = 0; //Set the Gravitational Constant ( units must be consistent ) Gconst = GN; if (strcmp(P->init, "Spherical_Overdensity_3D")==0){ Gconst = 1; chprintf(" WARNING: Using Gravitational Constant G=1.\n"); } //Flag too transfer the Potential boundaries TRANSFER_POTENTIAL_BOUNDARIES = false; AllocateMemory_CPU(); Initialize_values_CPU(); chprintf( "Gravity Initialized: \n Lbox: %0.2f %0.2f %0.2f \n Local: %d %d %d \n Global: %d %d %d \n", Lbox_x, Lbox_y, Lbox_z, nx_local, ny_local, nz_local, nx_total, ny_total, nz_total ); chprintf( " dx:%f dy:%f dz:%f\n", dx, dy, dz ); chprintf( " N ghost potential: %d\n", N_GHOST_POTENTIAL); chprintf( " N ghost offset: %d\n", n_ghost_pot_offset); #ifdef PARALLEL_OMP chprintf(" Using OMP for gravity calculations\n"); int n_omp_max = omp_get_max_threads(); chprintf(" MAX OMP Threads: %d\n", n_omp_max); chprintf(" N OMP Threads per MPI process: %d\n", N_OMP_THREADS); #endif Poisson_solver.Initialize( Lbox_x, Lbox_y, Lbox_z, xMin, yMin, zMin, nx_total, ny_total, nz_total, nx_local, ny_local, nz_local, dx, dy, dz ); } void Grav3D::AllocateMemory_CPU(void) { // allocate memory for the density and potential arrays F.density_h = (Real *) malloc(n_cells*sizeof(Real)); //array for the density F.potential_h = (Real *) malloc(n_cells_potential*sizeof(Real)); //array for the potential at the n-th timestep F.potential_1_h = (Real *) malloc(n_cells_potential*sizeof(Real)); //array for the potential at the (n-1)-th timestep } void Grav3D::Initialize_values_CPU(void){ //Set initial values to 0. for (int id=0; id<n_cells; id++){ F.density_h[id] = 0; } for (int id_pot=0; id_pot<n_cells_potential; id_pot++){ F.potential_h[id_pot] = 0; F.potential_1_h[id_pot] = 0; } } void Grav3D::FreeMemory_CPU(void) { free(F.density_h); free(F.potential_h); free(F.potential_1_h); Poisson_solver.Reset(); } #endif //GRAVITY
27.684615
239
0.684357
capybaras-only
c577745f7b251e3cc806bdab313a588d8658dd06
558
cpp
C++
gym/102343/A.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
1
2021-07-16T19:59:39.000Z
2021-07-16T19:59:39.000Z
gym/102343/A.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
null
null
null
gym/102343/A.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #ifdef Adrian #include "debug.h" #else #define debug(...) #endif typedef long long ll; typedef long double ld; typedef complex<ll> point; #define F first #define S second int main() { #ifdef Adrian freopen("a.txt", "r", stdin); //freopen("b.txt", "w", stdout); #endif ios_base::sync_with_stdio(0), cin.tie(0); int n,d; cin>>n>>d; vector<int>arr(n); int cant=0; for(int i=0; i<n; i++) { cin>>arr[i]; cant+=arr[i]; } d/=cant; for(int i=0; i<n; i++) cout<<arr[i]*d<<"\n"; return 0; }
13.285714
42
0.605735
albexl
c57a3fca23220599107fc435834ed25300d0e4e8
3,492
hpp
C++
src/transformations.hpp
RedErr404/cprocessing
ab8ef25ea3e4bcd915f9c086b649696866ea77ca
[ "BSD-2-Clause" ]
12
2015-01-12T07:43:22.000Z
2022-03-08T06:43:20.000Z
src/transformations.hpp
RedErr404/cprocessing
ab8ef25ea3e4bcd915f9c086b649696866ea77ca
[ "BSD-2-Clause" ]
null
null
null
src/transformations.hpp
RedErr404/cprocessing
ab8ef25ea3e4bcd915f9c086b649696866ea77ca
[ "BSD-2-Clause" ]
7
2015-02-09T15:44:10.000Z
2019-07-07T11:48:10.000Z
#include "cprocessing.hpp" #ifndef CPROCESSING_TRANSFORMATIONS_ #define CPROCESSING_TRANSFORMATIONS_ using namespace cprocessing; namespace cprocessing { /// Applies a translation transformation void translate (double dx, double dy, double dz); void translate(double dx, double dy); /// Applies a scale transformation void scale (double dx, double dy, double dz); void scale(double dx, double dy); /// Applies a uniform scale inline void scale (double factor) { scale (factor, factor, factor); } /// Applies a rotation transformation void rotate (double radians, double axisx, double axisy, double axisz); inline void rotateX (double radians) { rotate(radians, 1, 0, 0); } inline void rotateY (double radians) { rotate(radians, 0, 1, 0); } inline void rotateZ (double radians) { rotate(radians, 0, 0, 1); } inline void rotate (double radians) { rotateZ(radians); } /// Resets the transformation to none void resetMatrix(); /// Fills matrix with the current transformation matrix void getMatrix (double matrix [16]); /// Multiplies given matrix by current transformation matrix void applyMatrix (double matrix [16]); /// Duplicates the top of the matrix stack void pushMatrix(); /// Discards the top of the matrix stack void popMatrix(); /// Creates a viewing transformation given the camera position /// (eyex,eyey,eyez), the center of the scene (centerx, centery, centerz) and /// a vector to be used as the up direction (upx, upy, upz). If no args /// are passed, the standard camera is created. void camera (double eyeX, double eyeY, double eyeZ, double centerX, double centerY, double centerZ, double upX, double upY, double upZ); void camera (); /// Loads a perspective projection matrix, where /// fov is the field-of-view angle (in radians) for vertical direction, aspect /// is the ratio of width to height, znear is the z-position of nearest clipping /// plane and zfar is the z-position of nearest farthest plane. If no args are /// passed, the standard projection is created, i.e, equivalent to /// perspective(PI/3.0, width/height, cameraZ/10.0, cameraZ*10.0) /// where cameraZ is ((height/2.0) / tan(PI*60.0/360.0)) void perspective(double fov, double aspect, double znear, double zfar); void perspective (); /// Loads an orthogonal projection matrix. /// The clipping volume in this case is an axes-aligned parallelepiped, where /// left and right are the minimum and maximum x values, top and bottom are /// the minimum and maximum y values, and near and far are the minimum and /// maximum z values. If no parameters are given, the default is used: /// ortho(0, width, 0, height, -height*2, height*2). void ortho(double left, double right, double bottom, double top, double near, double far); void ortho (); /// Returns the projected space coordinates of object coordinates ox,oy,oz void screenXYZ (double ox, double oy, double oz, double& sx, double& sy, double& sz); inline double screenX (double ox, double oy, double oz) { double tmpx, tmpy, tmpz; screenXYZ (ox, oy, oz, tmpx, tmpy, tmpz); return tmpx; } inline double screenY (double ox, double oy, double oz) { double tmpx, tmpy, tmpz; screenXYZ (ox, oy, oz, tmpx, tmpy, tmpz); return tmpy; } inline double screenZ (double ox, double oy, double oz) { double tmpx, tmpy, tmpz; screenXYZ (ox, oy, oz, tmpx, tmpy, tmpz); return tmpz; } } #endif
36.757895
91
0.702463
RedErr404
c57c25237f51093201dc7a67043e3023da3bc325
3,002
cpp
C++
aws-cpp-sdk-kafkaconnect/source/model/CustomPluginRevisionSummary.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-kafkaconnect/source/model/CustomPluginRevisionSummary.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-kafkaconnect/source/model/CustomPluginRevisionSummary.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/kafkaconnect/model/CustomPluginRevisionSummary.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace KafkaConnect { namespace Model { CustomPluginRevisionSummary::CustomPluginRevisionSummary() : m_contentType(CustomPluginContentType::NOT_SET), m_contentTypeHasBeenSet(false), m_creationTimeHasBeenSet(false), m_descriptionHasBeenSet(false), m_fileDescriptionHasBeenSet(false), m_locationHasBeenSet(false), m_revision(0), m_revisionHasBeenSet(false) { } CustomPluginRevisionSummary::CustomPluginRevisionSummary(JsonView jsonValue) : m_contentType(CustomPluginContentType::NOT_SET), m_contentTypeHasBeenSet(false), m_creationTimeHasBeenSet(false), m_descriptionHasBeenSet(false), m_fileDescriptionHasBeenSet(false), m_locationHasBeenSet(false), m_revision(0), m_revisionHasBeenSet(false) { *this = jsonValue; } CustomPluginRevisionSummary& CustomPluginRevisionSummary::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("contentType")) { m_contentType = CustomPluginContentTypeMapper::GetCustomPluginContentTypeForName(jsonValue.GetString("contentType")); m_contentTypeHasBeenSet = true; } if(jsonValue.ValueExists("creationTime")) { m_creationTime = jsonValue.GetString("creationTime"); m_creationTimeHasBeenSet = true; } if(jsonValue.ValueExists("description")) { m_description = jsonValue.GetString("description"); m_descriptionHasBeenSet = true; } if(jsonValue.ValueExists("fileDescription")) { m_fileDescription = jsonValue.GetObject("fileDescription"); m_fileDescriptionHasBeenSet = true; } if(jsonValue.ValueExists("location")) { m_location = jsonValue.GetObject("location"); m_locationHasBeenSet = true; } if(jsonValue.ValueExists("revision")) { m_revision = jsonValue.GetInt64("revision"); m_revisionHasBeenSet = true; } return *this; } JsonValue CustomPluginRevisionSummary::Jsonize() const { JsonValue payload; if(m_contentTypeHasBeenSet) { payload.WithString("contentType", CustomPluginContentTypeMapper::GetNameForCustomPluginContentType(m_contentType)); } if(m_creationTimeHasBeenSet) { payload.WithString("creationTime", m_creationTime.ToGmtString(DateFormat::ISO_8601)); } if(m_descriptionHasBeenSet) { payload.WithString("description", m_description); } if(m_fileDescriptionHasBeenSet) { payload.WithObject("fileDescription", m_fileDescription.Jsonize()); } if(m_locationHasBeenSet) { payload.WithObject("location", m_location.Jsonize()); } if(m_revisionHasBeenSet) { payload.WithInt64("revision", m_revision); } return payload; } } // namespace Model } // namespace KafkaConnect } // namespace Aws
21.912409
121
0.747169
perfectrecall
c5816c489ad6d191622911f0ed29136689f2752d
2,767
cpp
C++
Eldritch-Source/Code/Libraries/3D/src/D3D9/d3d9vertexdeclaration.cpp
inferno986return/eldritch-mirror
fefdb06f392b3f8c17f0617a1101c503620bc6fd
[ "Zlib", "Unlicense" ]
91
2015-01-27T22:56:26.000Z
2022-03-25T13:33:18.000Z
Code/Libraries/3D/src/D3D9/d3d9vertexdeclaration.cpp
rohit-n/Eldritch
b1d2a200eac9c8026e696bdac1f7d2ca629dd38c
[ "Zlib" ]
2
2019-01-04T21:42:26.000Z
2019-01-06T14:34:08.000Z
Code/Libraries/3D/src/D3D9/d3d9vertexdeclaration.cpp
Neb-Software/mEldritch
7d07a845b3f04242ddf1f0abbad606c830ac8f20
[ "Zlib" ]
21
2015-04-06T17:41:17.000Z
2021-06-15T00:26:18.000Z
#include "core.h" #include "3d.h" #include "D3D9/d3d9vertexdeclaration.h" #include "map.h" #include "mathcore.h" #include <d3d9.h> D3D9VertexDeclaration::D3D9VertexDeclaration( IDirect3DDevice9* pD3DDevice ) : m_D3DDevice( pD3DDevice ) , m_VertexDeclaration( NULL ) , m_VertexSignature( 0 ) {} D3D9VertexDeclaration::~D3D9VertexDeclaration() { SafeRelease( m_VertexDeclaration ); } void D3D9VertexDeclaration::Initialize( uint VertexSignature ) { m_VertexSignature = VertexSignature; uint NumElements = CountBits( VertexSignature ); D3DVERTEXELEMENT9* pVertexElements = new D3DVERTEXELEMENT9[ NumElements + 1 ]; uint Index = 0; // "if( SIG == ... )" is done so that 0 is acceptable for SIG #define CREATESTREAM( NUM, SIG, TYPE, USAGE, INDEX ) \ if( SIG == ( VertexSignature & SIG ) ) \ { \ pVertexElements[ Index ].Stream = (WORD)NUM; \ pVertexElements[ Index ].Offset = 0; \ pVertexElements[ Index ].Type = TYPE; \ pVertexElements[ Index ].Method = D3DDECLMETHOD_DEFAULT; \ pVertexElements[ Index ].Usage = USAGE; \ pVertexElements[ Index ].UsageIndex = INDEX; \ Index++; \ } CREATESTREAM( Index, VD_POSITIONS, D3DDECLTYPE_FLOAT3, D3DDECLUSAGE_POSITION, 0 ); CREATESTREAM( Index, VD_COLORS, D3DDECLTYPE_D3DCOLOR, D3DDECLUSAGE_COLOR, 0 ); #if USE_HDR CREATESTREAM( Index, VD_FLOATCOLORS, D3DDECLTYPE_FLOAT4, D3DDECLUSAGE_COLOR, 0 ); CREATESTREAM( Index, VD_BASISCOLORS, D3DDECLTYPE_FLOAT4, D3DDECLUSAGE_COLOR, 1 ); CREATESTREAM( Index, VD_BASISCOLORS, D3DDECLTYPE_FLOAT4, D3DDECLUSAGE_COLOR, 2 ); // For SM2 cards, an alternative way to do HDR colors CREATESTREAM( Index, VD_FLOATCOLORS_SM2, D3DDECLTYPE_FLOAT4, D3DDECLUSAGE_TEXCOORD, 1 ); CREATESTREAM( Index, VD_BASISCOLORS_SM2, D3DDECLTYPE_FLOAT4, D3DDECLUSAGE_TEXCOORD, 2 ); CREATESTREAM( Index, VD_BASISCOLORS_SM2, D3DDECLTYPE_FLOAT4, D3DDECLUSAGE_TEXCOORD, 3 ); #endif CREATESTREAM( Index, VD_UVS, D3DDECLTYPE_FLOAT2, D3DDECLUSAGE_TEXCOORD, 0 ); CREATESTREAM( Index, VD_NORMALS, D3DDECLTYPE_FLOAT3, D3DDECLUSAGE_NORMAL, 0 ); CREATESTREAM( Index, VD_TANGENTS, D3DDECLTYPE_FLOAT4, D3DDECLUSAGE_TANGENT, 0 ); CREATESTREAM( Index, VD_BONEINDICES, D3DDECLTYPE_UBYTE4, D3DDECLUSAGE_BLENDINDICES, 0 ); CREATESTREAM( Index, VD_BONEWEIGHTS, D3DDECLTYPE_UBYTE4N, D3DDECLUSAGE_BLENDWEIGHT, 0 ); CREATESTREAM( 0xFF, 0, D3DDECLTYPE_UNUSED, 0, 0 ); #undef CREATESTREAM m_D3DDevice->CreateVertexDeclaration( pVertexElements, &m_VertexDeclaration ); SafeDelete( pVertexElements ); } void* D3D9VertexDeclaration::GetDeclaration() { return m_VertexDeclaration; } uint D3D9VertexDeclaration::GetSignature() { return m_VertexSignature; }
37.391892
90
0.733647
inferno986return
c58206d9926748e1736b9d349a8bbfbc97ea87e7
597
hpp
C++
Code/include/OE/Platform/Direct3D/D3DMesh.hpp
mlomb/OrbitEngine
41f053626f05782e81c2e48f5c87b04972f9be2c
[ "Apache-2.0" ]
21
2018-06-26T16:37:36.000Z
2022-01-11T01:19:42.000Z
Code/include/OE/Platform/Direct3D/D3DMesh.hpp
mlomb/OrbitEngine
41f053626f05782e81c2e48f5c87b04972f9be2c
[ "Apache-2.0" ]
null
null
null
Code/include/OE/Platform/Direct3D/D3DMesh.hpp
mlomb/OrbitEngine
41f053626f05782e81c2e48f5c87b04972f9be2c
[ "Apache-2.0" ]
3
2019-10-01T14:10:50.000Z
2021-11-19T20:30:18.000Z
#ifndef GRAPHICS_D3DMESH_HPP #define GRAPHICS_D3DMESH_HPP #include "OE/Graphics/API/Mesh.hpp" #include "OE/Platform/Direct3D/Direct3D.hpp" namespace OrbitEngine { namespace Graphics { class D3DMesh : public Mesh { public: D3DMesh(void* vertices, unsigned int vertexSize, VertexLayout* layout, const std::vector<unsigned short>& indices); void drawIndexed(unsigned int count, unsigned int offset = 0) override; void draw(unsigned int count, unsigned int offset = 0) override; private: static D3D_PRIMITIVE_TOPOLOGY TopologyToD3D(Topology topology); void preDraw(); }; } } #endif
27.136364
117
0.768844
mlomb
c583f6f94f0adfcb7081ef318f16ef789d5ea72c
2,052
cpp
C++
src/unit_tests/engine/ut_aabb.cpp
OndraVoves/LumixEngine
b7040d7a5b9dc1c6bc78e5e6d9b33b7f585c435f
[ "MIT" ]
1
2020-10-28T10:29:21.000Z
2020-10-28T10:29:21.000Z
src/unit_tests/engine/ut_aabb.cpp
OndraVoves/LumixEngine
b7040d7a5b9dc1c6bc78e5e6d9b33b7f585c435f
[ "MIT" ]
null
null
null
src/unit_tests/engine/ut_aabb.cpp
OndraVoves/LumixEngine
b7040d7a5b9dc1c6bc78e5e6d9b33b7f585c435f
[ "MIT" ]
null
null
null
#include "engine/geometry.h" #include "engine/matrix.h" #include "unit_tests/suite/lumix_unit_tests.h" using namespace Lumix; void UT_aabb(const char* params) { AABB aabb1; AABB aabb2(Vec3(0, 0, 0), Vec3(1, 1, 1)); LUMIX_EXPECT(aabb2.min.x == 0); LUMIX_EXPECT(aabb2.min.y == 0); LUMIX_EXPECT(aabb2.min.z == 0); LUMIX_EXPECT(aabb2.max.x == 1); LUMIX_EXPECT(aabb2.max.y == 1); LUMIX_EXPECT(aabb2.max.z == 1); aabb1 = aabb2; LUMIX_EXPECT(aabb1.min.x == aabb2.min.x); LUMIX_EXPECT(aabb1.min.y == aabb2.min.y); LUMIX_EXPECT(aabb1.min.z == aabb2.min.z); LUMIX_EXPECT(aabb1.max.x == aabb2.max.x); LUMIX_EXPECT(aabb1.max.y == aabb2.max.y); LUMIX_EXPECT(aabb1.max.z == aabb2.max.z); Vec3 points[8]; aabb2.getCorners(Matrix::IDENTITY, points); LUMIX_EXPECT(points[0].x == 0); LUMIX_EXPECT(points[0].y == 0); LUMIX_EXPECT(points[0].z == 0); LUMIX_EXPECT(points[1].x == 0); LUMIX_EXPECT(points[1].y == 0); LUMIX_EXPECT(points[1].z == 1); LUMIX_EXPECT(points[2].x == 0); LUMIX_EXPECT(points[2].y == 1); LUMIX_EXPECT(points[2].z == 0); LUMIX_EXPECT(points[3].x == 0); LUMIX_EXPECT(points[3].y == 1); LUMIX_EXPECT(points[3].z == 1); LUMIX_EXPECT(points[4].x == 1); LUMIX_EXPECT(points[4].y == 0); LUMIX_EXPECT(points[4].z == 0); LUMIX_EXPECT(points[5].x == 1); LUMIX_EXPECT(points[5].y == 0); LUMIX_EXPECT(points[5].z == 1); LUMIX_EXPECT(points[6].x == 1); LUMIX_EXPECT(points[6].y == 1); LUMIX_EXPECT(points[6].z == 0); LUMIX_EXPECT(points[7].x == 1); LUMIX_EXPECT(points[7].y == 1); LUMIX_EXPECT(points[7].z == 1); AABB aabb3(Vec3(0, 0, 0), Vec3(1, 1, 1)); AABB aabb4(Vec3(1, 2, 3), Vec3(2, 3, 4)); Matrix mtx = Matrix::IDENTITY; mtx.setTranslation(Vec3(1, 2, 3)); aabb3.transform(mtx); LUMIX_EXPECT(aabb3.min.x == aabb4.min.x); LUMIX_EXPECT(aabb3.min.y == aabb4.min.y); LUMIX_EXPECT(aabb3.min.z == aabb4.min.z); LUMIX_EXPECT(aabb3.max.x == aabb4.max.x); LUMIX_EXPECT(aabb3.max.y == aabb4.max.y); LUMIX_EXPECT(aabb3.max.z == aabb4.max.z); } REGISTER_TEST("unit_tests/engine/aabb", UT_aabb, "")
25.65
52
0.662768
OndraVoves
c58833ce649533cf2706a330c27a8f2a95d859e5
3,929
cpp
C++
VSDataReduction/VSSimplePedData.cpp
sfegan/ChiLA
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
[ "BSD-3-Clause" ]
1
2018-04-17T14:03:36.000Z
2018-04-17T14:03:36.000Z
VSDataReduction/VSSimplePedData.cpp
sfegan/ChiLA
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
[ "BSD-3-Clause" ]
null
null
null
VSDataReduction/VSSimplePedData.cpp
sfegan/ChiLA
916bdd95348c2df2ecc736511d5f5b2bfb4a831e
[ "BSD-3-Clause" ]
null
null
null
//-*-mode:c++; mode:font-lock;-*- /*! \file VSSimplePedData.hpp Simple pedestal data \author Stephen Fegan \n UCLA \n sfegan@astro.ucla.edu \n \version 1.0 \date 05/18/2005 $Id: VSSimplePedData.cpp,v 3.1 2007/12/04 18:05:03 sfegan Exp $ */ #include<fstream> #include<memory> #include<vsassert> #include <VSLineTokenizer.hpp> #include "VSSimpleStat.hpp" #include "VSSimplePedData.hpp" using namespace VERITAS; bool VSSimplePedData::load(const std::string& filename) { std::ifstream datastream(filename.c_str()); if(!datastream)return false; m_data.clear(); std::string line; VSLineTokenizer tokenizer; VSTokenList tokens; unsigned iline=0; while(getline(datastream,line)) { iline++; std::string line_copy = line; tokenizer.tokenize(line_copy, tokens); if(tokens.size() == 0)continue; if(tokens.size() < 4) { std::cerr << filename << ": line " << iline << ": " << tokens.size() << " columns found (>=4 expected)" << std::endl << "Line: " << line << std::endl; continue; } unsigned iscope = 0; unsigned ichan = 0; double ped = 0; tokens[0].to(iscope); tokens[1].to(ichan); tokens[2].to(ped); if(iscope >= m_data.size())m_data.resize(iscope+1); if(ichan >= m_data[iscope].size())m_data[iscope].resize(ichan+1); m_data[iscope][ichan].ped = ped; unsigned nsample = tokens.size()-3; m_data[iscope][ichan].dev.resize(nsample); for(unsigned isample=0;isample<nsample;isample++) tokens[3+isample].to(m_data[iscope][ichan].dev[isample]); m_data[iscope][ichan].suppressed = false; } return true; } bool VSSimplePedData::save(const std::string& filename) { std::ostream* filestream = 0; std::ostream* datastream = &std::cout; if(!filename.empty()) { filestream = new std::ofstream(filename.c_str()); if(!filestream->good())return false; datastream = filestream; } unsigned nscope = m_data.size(); for(unsigned iscope=0;iscope<nscope;iscope++) { unsigned nchan = m_data[iscope].size(); for(unsigned ichan=0;ichan<nchan;ichan++) { unsigned nsample = m_data[iscope][ichan].dev.size(); (*datastream) << iscope << ' ' << ichan << ' ' << m_data[iscope][ichan].ped; for(unsigned isample=0;isample<nsample;isample++) (*datastream) << ' ' << m_data[iscope][ichan].dev[isample]; (*datastream) << std::endl; } } delete filestream; return true; } void VSSimplePedData::suppress(const double lo, const double hi, const unsigned window) { unsigned nscope = m_data.size(); unsigned isample = window; // This loop to find window size to use for suppression (if necessary!) if(isample==0) { for(unsigned iscope=0;isample==0&&iscope<nscope;iscope++) { unsigned nchan = m_data[iscope].size(); for(unsigned ichan=0;isample==0&&ichan<nchan;ichan++) { unsigned nsample = m_data[iscope][ichan].dev.size(); if(nsample)isample=nsample; } } vsassert(isample!=0); } isample--; // This loop to suppress for(unsigned iscope=0;iscope<nscope;iscope++) { unsigned nchan = m_data[iscope].size(); if(nchan==0)continue; std::vector<std::pair<bool,double> > dev_list(nchan); for(unsigned ichan=0;ichan<nchan;ichan++) dev_list[ichan].first=!m_data[iscope][ichan].suppressed, dev_list[ichan].second=m_data[iscope][ichan].dev[isample]; double meddev = median(dev_list); double locut = meddev*lo; double hicut = meddev*hi; for(unsigned ichan=0;ichan<nchan;ichan++) if((m_data[iscope][ichan].dev[isample]<locut) ||(m_data[iscope][ichan].dev[isample]>hicut)) m_data[iscope][ichan].suppressed=true; } }
26.910959
73
0.611861
sfegan
c58e60d33e3f09717504d19cc55fa2fc2271b104
487
cpp
C++
abc068/abc068_b.cpp
crazystylus/AtCoderPractice
8e0f56a9b3905e11f83f351af66af5bfed8606b2
[ "MIT" ]
null
null
null
abc068/abc068_b.cpp
crazystylus/AtCoderPractice
8e0f56a9b3905e11f83f351af66af5bfed8606b2
[ "MIT" ]
null
null
null
abc068/abc068_b.cpp
crazystylus/AtCoderPractice
8e0f56a9b3905e11f83f351af66af5bfed8606b2
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define rep(i, n) for (int i = 0; i < n; i++) const int mod = 1e9 + 7; // 10^9 + 7; const int N = 1e5 + 1; /////////////////// // multiply 1 with 2 till it is <= n int n, op; void solve() { op = 1; cin >> n; // if (n == 1) // return (void)(cout << "0\n"); while (op <= n) op = op << 1; cout << op / 2 << '\n'; } int main() { solve(); return 0; }
21.173913
45
0.478439
crazystylus
c5953e50037c06f0fd50b203f3a246e6bf433296
1,625
hpp
C++
src/utility/debug_log.hpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
src/utility/debug_log.hpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
src/utility/debug_log.hpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
/* * TS Elements * Copyright 2015-2018 M. Newhouse * Released under the MIT license. */ #pragma once #include "logger.hpp" #include <cstdint> namespace ts { namespace debug { struct DebugTag {}; using logger::flush; using logger::endl; namespace level { static const std::uint32_t essential = 0; static const std::uint32_t relevant = 1; static const std::uint32_t auxiliary = 2; } #define DEBUG_ESSENTIAL debug::Log(debug::level::essential) #define DEBUG_RELEVANT debug::Log(debug::level::relevant) #define DEBUG_AUXILIARY debug::Log(debug::level::auxiliary) struct DebugConfig { std::uint32_t debug_level = level::essential; }; } namespace logger { template <> struct LoggerTraits<debug::DebugTag> { using config_type = debug::DebugConfig; using dispatcher_type = LogFileDispatcher; }; } namespace debug { struct Log { public: Log(std::uint32_t debug_level); template <typename T> Log& operator<<(const T& value); private: logger::LoggerFront<DebugTag> logger_; std::uint32_t debug_level_; std::uint32_t debug_config_level_; }; using ScopedLogger = logger::ScopedLogger<DebugTag>; inline Log::Log(std::uint32_t debug_level) : logger_(), debug_level_(debug_level), debug_config_level_(logger_.config().debug_level) { } template <typename T> Log& Log::operator<<(const T& value) { if (debug_config_level_ >= debug_level_) { logger_ << value; } return *this; } } }
18.895349
59
0.634462
mnewhouse
c59e1d492e86efd34c133c287d1548ea3bf637db
1,119
cpp
C++
pomodoro/logic-config.cpp
ximenpo/easy-pomodoro
c0eed81e824dc7348816f059f68a51ba0ddb0810
[ "MIT" ]
null
null
null
pomodoro/logic-config.cpp
ximenpo/easy-pomodoro
c0eed81e824dc7348816f059f68a51ba0ddb0810
[ "MIT" ]
null
null
null
pomodoro/logic-config.cpp
ximenpo/easy-pomodoro
c0eed81e824dc7348816f059f68a51ba0ddb0810
[ "MIT" ]
null
null
null
#include <stddef.h> #include <stdint.h> #include <string.h> #include "logic-config.h" size_t storage_load(uint8_t* begin, uint8_t* end); void storage_save(uint8_t* begin, uint8_t* end); void logic_config::init() { const char DEFAULT_SSID[] = "pomodoro"; const char DEFAULT_PASSWORDD[] = "88888888"; memcpy(this->ap_ssid, DEFAULT_SSID, sizeof(DEFAULT_SSID)); memcpy(this->ap_password, DEFAULT_PASSWORDD, sizeof(DEFAULT_PASSWORDD)); memset(this->wifi_ssid, 0, sizeof(this->wifi_ssid)); memset(this->wifi_password, 0, sizeof(this->wifi_password)); memset(this->app_id, 0, sizeof(this->app_id)); memset(this->app_key, 0, sizeof(this->app_key)); this->work_minites = 25; this->break_minites = 5; this->long_break_minites = 15; this->long_break_work_times = 4; this->confirm_seconds = 5; this->slient_mode = 0; } void logic_config::load() { if (!storage_load(&this->__storage_begin__, &this->__storage_end__)) { this->init(); } } void logic_config::save() { storage_save(&this->__storage_begin__, &this->__storage_end__); }
27.292683
74
0.679178
ximenpo
c5a0f36daed9457c007f555f9a83f6f2d18384ba
1,257
cpp
C++
kvm_gadget/src/kvm_mouse.cpp
pspglb/kvm
2dc3c4cc331dedaf5245e5c8a24bcba02b6ded32
[ "BSD-3-Clause" ]
26
2020-12-03T11:13:42.000Z
2022-03-25T05:36:33.000Z
kvm_gadget/src/kvm_mouse.cpp
mtlynch/kvm
f0128edd493a758197a683cbb40dd409d16235e5
[ "BSD-3-Clause" ]
4
2021-01-28T19:32:17.000Z
2021-06-01T15:01:42.000Z
kvm_gadget/src/kvm_mouse.cpp
mtlynch/kvm
f0128edd493a758197a683cbb40dd409d16235e5
[ "BSD-3-Clause" ]
8
2020-12-04T01:30:21.000Z
2021-12-01T11:19:11.000Z
// Copyright 2020 Christopher A. Taylor #include "kvm_mouse.hpp" #include "kvm_serializer.hpp" #include "kvm_logger.hpp" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> namespace kvm { static logger::Channel Logger("Gadget"); //------------------------------------------------------------------------------ // MouseEmulator bool MouseEmulator::Initialize() { fd = open("/dev/hidg1", O_RDWR); if (fd < 0) { Logger.Error("Failed to open mouse emulator device"); return false; } Logger.Info("Mouse emulator ready"); return true; } void MouseEmulator::Shutdown() { if (fd >= 0) { close(fd); fd = -1; } } bool MouseEmulator::SendReport(uint8_t button_status, uint16_t x, uint16_t y) { std::lock_guard<std::mutex> locker(Lock); char buffer[5] = {0}; buffer[0] = button_status; WriteU16_LE(buffer + 1, x); WriteU16_LE(buffer + 3, y); //Logger.Info("Writing report: ", HexDump((const uint8_t*)buffer, 5)); ssize_t written = write(fd, buffer, 5); if (written != 5) { Logger.Error("Failed to write mouse device: errno=", errno); return false; } return true; } } // namespace kvm
19.640625
80
0.584726
pspglb
c5a6671cf32c952770c4dccef896eacc5755a6c4
7,831
cc
C++
framework/window/linux/x_window.cc
ans-hub/gdm_framework
4218bb658d542df2c0568c4d3aac813cd1f18e1b
[ "MIT" ]
1
2020-12-30T23:50:01.000Z
2020-12-30T23:50:01.000Z
framework/window/linux/x_window.cc
ans-hub/gdm_framework
4218bb658d542df2c0568c4d3aac813cd1f18e1b
[ "MIT" ]
null
null
null
framework/window/linux/x_window.cc
ans-hub/gdm_framework
4218bb658d542df2c0568c4d3aac813cd1f18e1b
[ "MIT" ]
null
null
null
// ************************************************************* // File: x_window.cc // Author: Novoselov Anton @ 2018 // URL: https://github.com/ans-hub/gdm_framework // ************************************************************* #include "x_window.h" // --public gdm::XWindow::XWindow() : disp_{ XOpenDisplay(NULL) } , root_{} , self_{} , event_{} , fullscreen_{false} , vmode_{-1} , width_{0} , height_{0} { if (!disp_) throw WinException("XOpenDisplay failed", errno); root_ = XDefaultRootWindow(disp_); auto ask_wm_notify_closing = [&]() { wm_protocols_ = XInternAtom(disp_, "WM_PROTOCOLS", false); wm_delete_window_ = XInternAtom(disp_, "WM_DELETE_WINDOW", false); }(); } gdm::XWindow::XWindow(XWindow&& rhs) : disp_{ rhs.disp_ } , root_{ rhs.root_ } , self_{ rhs.self_ } , event_{ rhs.event_ } , fullscreen_{ rhs.fullscreen_ } , vmode_{ rhs.vmode_ } , width_{ rhs.width_ } , height_{ rhs.height_ } , wm_protocols_ { rhs.wm_protocols_ } , wm_delete_window_ { rhs.wm_delete_window_ } { rhs.disp_ = nullptr; rhs.root_ = 0; rhs.self_ = 0; rhs.fullscreen_ = false; rhs.vmode_ = 0; rhs.width_ = 0; rhs.height_ = 0; rhs.wm_protocols_ = 0; rhs.wm_delete_window_ = 0; } gdm::XWindow::~XWindow() { if (vmode_ != -1) helpers::ChangeVideoMode(disp_, root_, vmode_); if (self_) { XDestroyWindow(disp_, self_); XFlush(disp_); } if (disp_) XCloseDisplay(disp_); } void gdm::XWindow::Show() { XMapWindow(disp_, self_); XFlush(disp_); } void gdm::XWindow::Hide() { XUnmapWindow(disp_, self_); XFlush(disp_); } void gdm::XWindow::Move(int x, int y) { XMoveWindow(disp_, self_, x, y); } void gdm::XWindow::Close() { helpers::SendCloseWindowNotify(disp_, root_, self_); } void gdm::XWindow::HideCursor() { helpers::HideCursor(disp_, self_); } void gdm::XWindow::UnhideCursor() { helpers::UnhideCursor(disp_, self_); } void gdm::XWindow::SetFocus() { XRaiseWindow(disp_, self_); XSetInputFocus(disp_, self_, RevertToNone, CurrentTime); } bool gdm::XWindow::ToggleFullscreen() { int curr = helpers::GetCurrentVideoMode(disp_, root_); return this->ToggleFullscreen(curr); } bool gdm::XWindow::ToggleFullscreen(int mode) { if (mode < 0) return false; this->Move(0,0); vmode_ = helpers::ChangeVideoMode(disp_, root_, mode); helpers::GetWindowDimension(disp_, root_, &width_, &height_); int wait = 1000; // todo: make more smart way to wait while resolution will be changed do { timespec ts; ts.tv_sec = wait / 1000; ts.tv_nsec = wait * 1000000; while ((nanosleep(&ts, &ts) == -1) && (errno == EINTR)) { } } while (GrabSuccess != XGrabPointer( disp_, self_, True, None, GrabModeAsync, GrabModeAsync, self_, None, CurrentTime)); SetFocus(); XWarpPointer(disp_, None, root_, 0, 0, 0, 0, 0, 0); // todo: place in the middle of the scr bool result = helpers::SendToggleFullscreenNotify(disp_, root_, self_); fullscreen_ ^= result; if (!fullscreen_) XUngrabPointer(disp_, CurrentTime); return true; } void gdm::XWindow::ToggleOnTop() { helpers::SendToggleOnTopNotify(disp_, root_, self_); } bool gdm::XWindow::IsClosed() { if (XCheckTypedWindowEvent(disp_, self_, ClientMessage, &event_)) { if (event_.xclient.message_type == wm_protocols_ && event_.xclient.data.l[0] == (int)wm_delete_window_) { return true; } } return false; } // Exposed() - only if window was moved, overlapperd, etc // Up window (need to hide wm ontop elements after change resolution) // Redraw() - every time void gdm::XWindow::Render() { if (XCheckWindowEvent(disp_, self_, ExposureMask, &event_)) { Exposed(); helpers::GetWindowDimension(disp_, self_, &width_, &height_); } if (fullscreen_ && XCheckTypedWindowEvent(disp_, self_, VisibilityNotify, &event_)) { XRaiseWindow(disp_, self_); helpers::GetWindowDimension(disp_, self_, &width_, &height_); } Redraw(); } auto gdm::XWindow::GetNextEvent() { XNextEvent(disp_, &event_); switch (event_.type) { case Expose : return WinEvent::EXPOSE; case KeyPress : return WinEvent::KEYPRESS; case KeyRelease : return WinEvent::KEYRELEASE; case ButtonPress : return WinEvent::MOUSEPRESS; case ButtonRelease : return WinEvent::MOUSERELEASE; case MotionNotify : return WinEvent::MOUSEMOVE; default : return WinEvent::NONSENCE; } } Btn gdm::XWindow::ReadKeyboardBtn(BtnType t) const { XEvent event; auto buf = Btn::NONE; long type = 1L << static_cast<int>(t); if (XCheckWindowEvent(disp_, self_, type, &event)) { auto key = XkbKeycodeToKeysym(disp_, event.xkey.keycode, 0, 0); char buff[32]; XLookupString(&event.xkey, buff, 32, &key, NULL); // see note below buf = static_cast<Btn>(key); } return buf; // Note : This string is necessary if somewho press key in layout // differ than ISO Latin-1 } Btn gdm::XWindow::ReadMouseBtn(BtnType t) const { XEvent event; auto buf = Btn::NONE; long type = 1L << static_cast<int>(t); if (XCheckWindowEvent(disp_, self_, type, &event)) { buf = static_cast<Btn>(event.xbutton.button + kMouseBtnOffset); } return buf; } // Returns mouse pos every time its requered. When required non-glob // there are may be situation when first result returns position without // window decoration, and other results are with it. Thus more preffered // use glob == true Pos gdm::XWindow::ReadMousePos(bool glob) const { Window root_ret; Window child_ret; int x_rel {0}; int y_rel {0}; int x_win {0}; int y_win {0}; unsigned int mask; XQueryPointer( disp_, self_, &root_ret, &child_ret, &x_rel, &y_rel, &x_win, &y_win, &mask); if (glob) return Pos{x_rel, y_rel}; else return Pos{x_win, y_win}; } // Returns correct mouse pos only if moved, else default value for Pos Pos gdm::XWindow::ListenMousePos() const { // Other versions - http://www.rahul.net/kenton/perf.html Pos buf {}; if (XCheckWindowEvent(disp_, self_, PointerMotionMask, &event_)) { XSync(disp_, true); buf.x = event_.xmotion.x; buf.y = event_.xmotion.y; } return buf; } // Sets mouse pos relative to root // todo: incorrect working void gdm::XWindow::MoveMousePos(int x, int y) { SetFocus(); XWarpPointer(disp_, self_, self_, 0, 0, 0, 0, x, y); } // From here: https://goo.gl/W3zqgh bool gdm::XWindow::IsKeyboardBtnPressed(KbdBtn btn) const { if (btn == KbdBtn::NONE) return false; KeyCode keycode = XKeysymToKeycode(disp_, static_cast<KeySym>(btn)); if (keycode) { char keys[32]; XQueryKeymap(disp_, keys); return (keys[keycode / 8] & (1 << (keycode % 8))) != 0; } else return false; } // From here: https://goo.gl/W3zqgh bool gdm::XWindow::IsMouseBtnPressed(MouseBtn btn) const { Window root_ret; Window child_ret; int x_rel {0}; int y_rel {0}; int x_win {0}; int y_win {0}; unsigned int btns; XQueryPointer( disp_, self_, &root_ret, &child_ret, &x_rel, &y_rel, &x_win, &y_win, &btns); switch (btn) { case MouseBtn::LMB: return btns & Button1Mask; case MouseBtn::RMB: return btns & Button3Mask; case MouseBtn::MMB: return btns & Button2Mask; case MouseBtn::WH_UP: return false; case MouseBtn::WH_DWN: return false; default: return false; } return false; } // Ask WM to notify when it should close the window void gdm::XWindow::NotifyWhenClose() { XSetWMProtocols(disp_, self_, &wm_delete_window_, 1); } // Note : XCheckWindowEvent doesn't wait for next event (like XNextEvent) // but check if event is present. Function used that function only works // with masked events. For not masked events - XCheckTypedWindowEvent()
24.395639
93
0.653556
ans-hub