hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
e86580daa5ca80d60608bb645e9f4c1a64d95dbb
723
cpp
C++
Baekjoon/1864.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
Baekjoon/1864.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
Baekjoon/1864.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <math.h> using namespace std; int main(void) { while (1) { int len; long long ans = 0; string str; cin >> str; if (str == "#") break; len = str.length(); for (int i = 1; i <= len; i++) { int tmp; switch (str[i - 1]) { case '-': tmp = 0; break; case '\\': tmp = 1; break; case '(': tmp = 2; break; case '@': tmp = 3; break; case '?': tmp = 4; break; case '>': tmp = 5; break; case '&': tmp = 6; break; case '%': tmp = 7; break; case '/': tmp = -1; break; default: break; } ans += tmp * pow(8, len - i); } cout << ans << '\n'; } }
12.910714
32
0.428769
Twinparadox
e866fc219c43821e3401ee5cd626dd689ced361e
419
cpp
C++
ShaderGLTest/DeviceTest.cpp
EPAC-Saxon/environment-map-JuliePreperier
cd024b83236af8cffa2262cad988b43b2f725dcb
[ "MIT" ]
null
null
null
ShaderGLTest/DeviceTest.cpp
EPAC-Saxon/environment-map-JuliePreperier
cd024b83236af8cffa2262cad988b43b2f725dcb
[ "MIT" ]
null
null
null
ShaderGLTest/DeviceTest.cpp
EPAC-Saxon/environment-map-JuliePreperier
cd024b83236af8cffa2262cad988b43b2f725dcb
[ "MIT" ]
null
null
null
#include "DeviceTest.h" namespace test { TEST_F(DeviceTest, CreateDeviceTest) { EXPECT_FALSE(device_); EXPECT_TRUE(window_); device_ = window_->CreateDevice(); EXPECT_TRUE(device_); } TEST_F(DeviceTest, StartupDeviceTest) { EXPECT_FALSE(device_); EXPECT_TRUE(window_); device_ = window_->CreateDevice(); device_->Startup(window_->GetSize()); EXPECT_TRUE(device_); } } // End namespace test.
18.217391
39
0.720764
EPAC-Saxon
e869452700f1b03baa6cdbc2145af4dbd911b9a0
232
cpp
C++
src/static/INDI2/oldEIRlibs/eirCore/VariableIdList.cpp
eirTony/INDI1
42642d8c632da53f60f2610b056547137793021b
[ "MIT" ]
null
null
null
src/static/INDI2/oldEIRlibs/eirCore/VariableIdList.cpp
eirTony/INDI1
42642d8c632da53f60f2610b056547137793021b
[ "MIT" ]
14
2016-11-24T10:46:39.000Z
2016-12-10T07:24:15.000Z
src4/static/INDI2/oldEIRlibs/eirCore/VariableIdList.cpp
eirTony/INDI1
42642d8c632da53f60f2610b056547137793021b
[ "MIT" ]
null
null
null
#include "VariableIdList.h" VariableIdList::VariableIdList(void) { } VariableIdList::operator QStringList(void) const { QStringList result; int x = 0; while (x < size()) result << at(x++); return result; }
15.466667
48
0.642241
eirTony
e869522693033156f078c7142ef3fd7e6a5513d1
905
cpp
C++
task week 4/2.cpp
sekharkaredla/Cpp_Programs
e026d3322da5913e327033cb5d4787665998aef3
[ "MIT" ]
null
null
null
task week 4/2.cpp
sekharkaredla/Cpp_Programs
e026d3322da5913e327033cb5d4787665998aef3
[ "MIT" ]
null
null
null
task week 4/2.cpp
sekharkaredla/Cpp_Programs
e026d3322da5913e327033cb5d4787665998aef3
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; void multi(int p[10][10],int q[10][10],int r[10][10],int m,int n,int q1) { int i,j,k; for(i=0;i<m;i++) { for(j=0;j<q1;j++) { r[i][j]=0; for(k=0;k<n;k++) r[i][j]+=p[i][k]*q[k][j]; } } } int main() { int p[10][10],q[10][10],r[10][10];int m,n,p1,q1,i,j; cout<<"enter the order of first and second matrix : "; cin>>m>>n>>p1>>q1; if(p1>10||q1>10||m>10||n>10) { cout<<"size exceeded ..."; return -1; } if(n!=p1) { cout<<"wrong order input ..."; return -1; } cout<<"enter the elements of first matrix : \n"; for(i=0;i<m;i++) { for(j=0;j<n;j++) cin>>p[i][j]; } cout<<"enter the elements of the second matrix : \n"; for(i=0;i<p1;i++) { for(j=0;j<q1;j++) cin>>q[i][j]; } multi(p,q,r,m,n,q1); cout<<"the output matrix is : \n"; for(i=0;i<m;i++) { cout<<endl; for(j=0;j<q1;j++) cout<<r[i][j]<<" "; } return 1; }
17.075472
72
0.516022
sekharkaredla
e86bf1829ae08a4b9669d9528dbb04e4aa6b9357
966
hpp
C++
SignalDrivers/Hardware/ioport.hpp
NikitaEvs/signal_stm
15fa04392261c535f9104ddc0bbaf07f032421a6
[ "Apache-2.0" ]
null
null
null
SignalDrivers/Hardware/ioport.hpp
NikitaEvs/signal_stm
15fa04392261c535f9104ddc0bbaf07f032421a6
[ "Apache-2.0" ]
null
null
null
SignalDrivers/Hardware/ioport.hpp
NikitaEvs/signal_stm
15fa04392261c535f9104ddc0bbaf07f032421a6
[ "Apache-2.0" ]
null
null
null
#pragma once #include "port.hpp" #include "abstract_master.hpp" namespace SD { namespace Hardware { /** * @brief Wrapper for the base Port abstraction that adds Set/Reset function * and an initialization using Master */ class IOPort : public Port { public: /** * @brief Simple port initialization with a necessary link to the Master * in the purpose of an initialization and Set/Reset functions * @param master - link to the main Master object * @param port * @param pin */ IOPort(AbstractMaster& master, GPIO port, Pin pin) : Port(port, pin), master_(master) { master_.ConfigureIOPort(port, pin); } /** * @brief Set the port's pin using Master */ inline void Set() { master_.SetIOPort(gpio, pin); } /** * @brief Reset the port's pin using Master */ inline void Reset() { master_.ResetIOPort(gpio, pin); } private: AbstractMaster& master_; }; } // namespace Hardware } // namespace SD
20.125
76
0.665631
NikitaEvs
e86da2ffbad3214f4dabd9f72336f4378c095554
4,577
cpp
C++
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/database/sqlite/SQLiteDatabaseConfiguration.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/database/sqlite/SQLiteDatabaseConfiguration.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/database/sqlite/SQLiteDatabaseConfiguration.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include <Elastos.CoreLibrary.IO.h> #include <Elastos.CoreLibrary.Utility.h> #include "elastos/droid/database/sqlite/SQLiteDatabaseConfiguration.h" #include <elastos/utility/logging/Slogger.h> using Elastos::IO::IFile; using Elastos::IO::CFile; using Elastos::Utility::Logging::Slogger; using Elastos::Utility::ILocaleHelper; using Elastos::Utility::CLocaleHelper; using Elastos::Utility::Regex::IMatcher; using Elastos::Utility::Regex::IPatternHelper; using Elastos::Utility::Regex::CPatternHelper; namespace Elastos { namespace Droid { namespace Database { namespace Sqlite { const String SQLiteDatabaseConfiguration::MEMORY_DB_PATH(":memory:"); static AutoPtr<IPattern> InitEmailInDbPattern() { AutoPtr<IPatternHelper> helper; CPatternHelper::AcquireSingleton((IPatternHelper**)&helper); AutoPtr<IPattern> pattern; helper->Compile(String("[\\w\\.\\-]+@[\\w\\.\\-]+"), (IPattern**)&pattern); return pattern; } const AutoPtr<IPattern> SQLiteDatabaseConfiguration::EMAIL_IN_DB_PATTERN = InitEmailInDbPattern(); SQLiteDatabaseConfiguration::SQLiteDatabaseConfiguration( /* [in] */ const String& path, /* [in] */ Int32 openFlags) : mOpenFlags(openFlags) , mMaxSqlCacheSize(25) , mForeignKeyConstraintsEnabled(FALSE) { if (path.IsNull()) { Slogger::E("SQLiteDatabaseConfiguration", "path must not be null."); assert(0); // throw new IllegalArgumentException("path must not be null."); } mPath = path; mLabel = StripPathForLogs(path); // Set default values for optional parameters. AutoPtr<ILocaleHelper> helper; CLocaleHelper::AcquireSingleton((ILocaleHelper**)&helper); helper->GetDefault((ILocale**)&mLocale); } SQLiteDatabaseConfiguration::SQLiteDatabaseConfiguration( /* [in] */ SQLiteDatabaseConfiguration* other) : mOpenFlags(0) , mMaxSqlCacheSize(0) , mForeignKeyConstraintsEnabled(FALSE) { if (other == NULL) { Slogger::E("SQLiteDatabaseConfiguration", "other must not be null."); assert(0); //throw new IllegalArgumentException("other must not be null."); } mPath = other->mPath; mLabel = other->mLabel; ASSERT_SUCCEEDED(UpdateParametersFrom(other)); } ECode SQLiteDatabaseConfiguration::UpdateParametersFrom( /* [in] */ SQLiteDatabaseConfiguration* other) { if (other == NULL) { Slogger::E("SQLiteDatabaseConfiguration", "other must not be null."); //throw new IllegalArgumentException("other must not be null."); return E_ILLEGAL_ARGUMENT_EXCEPTION; } if (!mPath.Equals(other->mPath)) { Slogger::E("SQLiteDatabaseConfiguration", "other configuration must refer to the same database."); //throw new IllegalArgumentException("other configuration must refer to " // + "the same database."); return E_ILLEGAL_ARGUMENT_EXCEPTION; } mOpenFlags = other->mOpenFlags; mMaxSqlCacheSize = other->mMaxSqlCacheSize; mLocale = other->mLocale; mForeignKeyConstraintsEnabled = other->mForeignKeyConstraintsEnabled; mCustomFunctions.Clear(); List<AutoPtr<SQLiteCustomFunction> >::Iterator it = other->mCustomFunctions.Begin(); for (; it != other->mCustomFunctions.End(); ++it) { mCustomFunctions.PushBack(*it); } return NOERROR; } Boolean SQLiteDatabaseConfiguration::IsInMemoryDb() { return mPath.EqualsIgnoreCase(MEMORY_DB_PATH); } String SQLiteDatabaseConfiguration::StripPathForLogs( /* [in] */ const String& path) { if (path.IndexOf('@') == -1) { return path; } AutoPtr<IMatcher> matcher; EMAIL_IN_DB_PATTERN->Matcher(path, (IMatcher**)&matcher); String result; matcher->ReplaceAll(String("XX@YY"), &result); return result; } } //Sqlite } //Database } //Droid } //Elastos
33.408759
106
0.68298
jingcao80
e8723c5fbdd7e309ac8ce14e83abe546ca922631
7,026
cpp
C++
link/sample/LinkMainWindow.cpp
hasboeuf/hb
d812f2ef56d7c79983701f1f673ce666b189b638
[ "MIT" ]
1
2019-03-23T22:41:16.000Z
2019-03-23T22:41:16.000Z
link/sample/LinkMainWindow.cpp
hasboeuf/hb
d812f2ef56d7c79983701f1f673ce666b189b638
[ "MIT" ]
null
null
null
link/sample/LinkMainWindow.cpp
hasboeuf/hb
d812f2ef56d7c79983701f1f673ce666b189b638
[ "MIT" ]
null
null
null
// Qt #include <QtCore/QUrl> #include <QtCore/QUrlQuery> #include <QtNetwork/QNetworkReply> // Hb #include <core/HbDictionaryHelper.h> #include <facebook/HbO2ClientFacebook.h> #include <facebook/HbO2ServerFacebook.h> #include <facebook/api/HbFacebookUser.h> #include <google/HbO2ClientGoogle.h> #include <google/HbO2ServerGoogle.h> #include <google/api/HbGoogleUser.h> // Local #include <LinkMainWindow.h> using namespace hb::link; using namespace hb::linkexample; QString LinkMainWindow::msClientId = "940633959281250"; // Fake value. QString LinkMainWindow::msClientSecret = "74621eedf9aa2cde9cd31dc5c4d3c440"; // Fake value. LinkMainWindow::LinkMainWindow(QWidget* parent) : QMainWindow(parent) { // Ui setupUi(this); setWindowTitle("Link"); mFacebookClient = nullptr; mFacebookServer = nullptr; mGoogleClient = nullptr; mGoogleServer = nullptr; connect(ui_qpb_facebook_connect, &QPushButton::clicked, this, &LinkMainWindow::onFacebookConnectClicked); connect(ui_qpb_google_connect, &QPushButton::clicked, this, &LinkMainWindow::onGoogleConnectClicked); connect( &mFacebookRequester, &HbFacebookRequester::requestCompleted, this, &LinkMainWindow::onFacebookRequestCompleted); connect(&mGoogleRequester, &HbGoogleRequester::requestCompleted, this, &LinkMainWindow::onGoogleRequestCompleted); } LinkMainWindow::~LinkMainWindow() { if (mFacebookClient) delete mFacebookClient; if (mFacebookServer) delete mFacebookServer; if (mGoogleClient) delete mGoogleClient; if (mGoogleServer) delete mGoogleServer; } void LinkMainWindow::onFacebookConnectClicked() { mFacebookClient = new HbO2ClientFacebook(); connect(mFacebookClient, &HbO2::linkSucceed, this, &LinkMainWindow::onFacebookClientLinkSucceed); mFacebookClient->config().setClientId(msClientId); mFacebookClient->config().setLocalPort(8080); mFacebookClient->config().addScope(FB_PERMISSION_EMAIL); mFacebookClient->config().addScope(FB_PERMISSION_FRIENDS); mFacebookClient->config().setBrowserControls(&mBrowserControls); mFacebookClient->link(); } void LinkMainWindow::onGoogleConnectClicked() { mGoogleClient = new HbO2ClientGoogle(); connect(mGoogleClient, &HbO2::linkSucceed, this, &LinkMainWindow::onGoogleClientLinkSucceed); mGoogleClient->config().setClientId(msClientId); mGoogleClient->config().setLocalPort(8080); mGoogleClient->config().addScope(GL_PERMISSION_EMAIL); mGoogleClient->config().addScope(GL_PERMISSION_PROFILE); mGoogleClient->config().setBrowserControls(&mBrowserControls); mGoogleClient->link(); } void LinkMainWindow::onFacebookClientLinkSucceed() { if (sender() != mFacebookClient) { return; } qDebug() << "Client link succeed"; mFacebookServer = new HbO2ServerFacebook(); connect(mFacebookServer, &HbO2ServerFacebook::linkSucceed, this, &LinkMainWindow::onFacebookServerLinkSucceed, Qt::UniqueConnection); mFacebookServer->config().setClientId(mFacebookClient->config().clientId()); mFacebookServer->config().setClientSecret(msClientSecret); mFacebookServer->setRedirectUri(mFacebookClient->redirectUri()); mFacebookServer->setCode(mFacebookClient->code()); mFacebookServer->addField(FB_USER_FIRST_NAME); mFacebookServer->addField(FB_USER_LAST_NAME); mFacebookServer->addField(FB_USER_LINK); mFacebookServer->addField(FB_USER_EMAIL); mFacebookServer->addField(FB_USER_GENDER); mFacebookServer->addField(FB_USER_LOCALE); mFacebookServer->addField(FB_USER_VERIFIED); mFacebookServer->addField(FB_USER_TIMEZONE); mFacebookClient->deleteLater(); mFacebookClient = nullptr; mFacebookServer->link(); } void LinkMainWindow::onFacebookServerLinkSucceed() { if (sender() != mFacebookServer) { return; } qDebug() << "Server link succeed. Request facebook user..."; quint64 request_id = mFacebookRequester.requestUser(mFacebookServer); if (request_id > 0) { qDebug() << "Request id:" << request_id; } else { qDebug() << "Request user failed"; } mFacebookServer->deleteLater(); mFacebookServer = nullptr; } void LinkMainWindow::onFacebookRequestCompleted(quint64 request_id, hb::link::HbFacebookObject* object) { qDebug() << "Request completed" << request_id; if (!object) { qWarning() << "Facebook object null"; return; } qDebug() << "Facebook object of type" << HbFacebookObject::MetaObjectType::toString(object->type()) << "received"; if (object->type() == HbFacebookObject::OBJECT_USER) { HbFacebookUser* user = dynamic_cast<HbFacebookUser*>(object); if (user) { qDebug() << "Facebook user informations:" << user->toString(); } else { qWarning() << "Bad dynamic cast HbFacebookObject -> HbFacebookUser"; } } else { qWarning() << "No displayable for this type"; } delete object; } void LinkMainWindow::onGoogleClientLinkSucceed() { if (sender() != mGoogleClient) { return; } qDebug() << "Client link succeed"; mGoogleServer = new HbO2ServerGoogle(); connect(mGoogleServer, &HbO2ServerGoogle::linkSucceed, this, &LinkMainWindow::onGoogleServerLinkSucceed, Qt::UniqueConnection); mGoogleServer->config().setClientId(mGoogleClient->config().clientId()); mGoogleServer->config().setClientSecret(msClientSecret); mGoogleServer->setRedirectUri(mGoogleClient->redirectUri()); mGoogleServer->setCode(mGoogleClient->code()); mGoogleClient->deleteLater(); mGoogleClient = nullptr; mGoogleServer->link(); } void LinkMainWindow::onGoogleServerLinkSucceed() { if (sender() != mGoogleServer) { return; } qDebug() << "Server link succeed. Request google user..."; quint64 request_id = mGoogleRequester.requestUser(mGoogleServer); if (request_id > 0) { qDebug() << "Request id:" << request_id; } else { qWarning() << "Request user failed"; } mGoogleServer->deleteLater(); mGoogleServer = nullptr; } void LinkMainWindow::onGoogleRequestCompleted(quint64 request_id, hb::link::HbGoogleObject* object) { qDebug() << "Request completed" << request_id; if (!object) { qWarning() << "Google object null"; return; } qDebug() << "Google object of type" << HbGoogleObject::MetaObjectType::toString(object->type()) << "received"; if (object->type() == HbGoogleObject::OBJECT_USER) { HbGoogleUser* user = dynamic_cast<HbGoogleUser*>(object); if (user) { qDebug() << "Google user informations:" << user->toString(); } else { qWarning() << "Bad dynamic cast HbGoogleObject -> HbGoogleUser"; } } else { qWarning() << "No displayable for this type"; } delete object; }
31.936364
120
0.689724
hasboeuf
e8733a243d1afe3f607d174ad6e6f58df9b7e3b8
829
cpp
C++
C++/C++ Advanced Nov 2019/12. Exam Preparation/DemoExam_Description/01. Census/CensusMain.cpp
galin-kostadinov/Software-Engineering
55189648d787b35f1e9cd24cc4449c6beda51c90
[ "MIT" ]
1
2019-07-21T13:00:31.000Z
2019-07-21T13:00:31.000Z
C++/C++ Advanced Nov 2019/12. Exam Preparation/DemoExam_Description/01. Census/CensusMain.cpp
galin-kostadinov/Software-Engineering
55189648d787b35f1e9cd24cc4449c6beda51c90
[ "MIT" ]
null
null
null
C++/C++ Advanced Nov 2019/12. Exam Preparation/DemoExam_Description/01. Census/CensusMain.cpp
galin-kostadinov/Software-Engineering
55189648d787b35f1e9cd24cc4449c6beda51c90
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include "City.h" #include "CityUtils.h" int main() { std::cin.sync_with_stdio(false); std::cout.sync_with_stdio(false); std::vector<const City*> cities; int numCities; std::cin >> numCities; for (int i = 0; i < numCities; i++) { std::string name; size_t population; std::cin >> name >> population; cities.push_back(initCity(name, population)); } size_t totalPopulation; auto citiesByPopulation = groupByPopulation(cities, totalPopulation); for (auto populationAndCity : citiesByPopulation) { std::cout << populationAndCity.second->getName() << " " << populationAndCity.first << std::endl; } std::cout << "total: " << totalPopulation << std::endl; for (const City* city : cities) { delete city; } return 0; }
21.25641
100
0.661037
galin-kostadinov
e87c87813e3be824f3b0f8a59c95dbc4e3be6bcd
13,182
cc
C++
source/blender/depsgraph/intern/nodes/deg_node_component.cc
1-MillionParanoidTterabytes/Blender-2.79b-blackened
e8d767324e69015aa66850d13bee7db1dc7d084b
[ "Unlicense" ]
2
2018-06-18T01:50:25.000Z
2018-06-18T01:50:32.000Z
source/blender/depsgraph/intern/nodes/deg_node_component.cc
1-MillionParanoidTterabytes/Blender-2.79b-blackened
e8d767324e69015aa66850d13bee7db1dc7d084b
[ "Unlicense" ]
null
null
null
source/blender/depsgraph/intern/nodes/deg_node_component.cc
1-MillionParanoidTterabytes/Blender-2.79b-blackened
e8d767324e69015aa66850d13bee7db1dc7d084b
[ "Unlicense" ]
null
null
null
/* * ***** BEGIN GPL LICENSE BLOCK ***** * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2013 Blender Foundation. * All rights reserved. * * Original Author: Joshua Leung * Contributor(s): None Yet * * ***** END GPL LICENSE BLOCK ***** */ /** \file blender/depsgraph/intern/nodes/deg_node_component.cc * \ingroup depsgraph */ #include "intern/nodes/deg_node_component.h" #include <stdio.h> #include <cstring> /* required for STREQ later on. */ #include "BLI_utildefines.h" #include "BLI_ghash.h" extern "C" { #include "DNA_object_types.h" #include "BKE_action.h" } /* extern "C" */ #include "intern/nodes/deg_node_operation.h" #include "intern/depsgraph_intern.h" #include "util/deg_util_foreach.h" namespace DEG { /* *********** */ /* Outer Nodes */ /* Standard Component Methods ============================= */ ComponentDepsNode::OperationIDKey::OperationIDKey() : opcode(DEG_OPCODE_OPERATION), name(""), name_tag(-1) { } ComponentDepsNode::OperationIDKey::OperationIDKey(eDepsOperation_Code opcode) : opcode(opcode), name(""), name_tag(-1) { } ComponentDepsNode::OperationIDKey::OperationIDKey(eDepsOperation_Code opcode, const char *name, int name_tag) : opcode(opcode), name(name), name_tag(name_tag) { } string ComponentDepsNode::OperationIDKey::identifier() const { char codebuf[5]; BLI_snprintf(codebuf, sizeof(codebuf), "%d", opcode); return string("OperationIDKey(") + codebuf + ", " + name + ")"; } bool ComponentDepsNode::OperationIDKey::operator==( const OperationIDKey &other) const { return (opcode == other.opcode) && (STREQ(name, other.name)) && (name_tag == other.name_tag); } static unsigned int comp_node_hash_key(const void *key_v) { const ComponentDepsNode::OperationIDKey *key = reinterpret_cast<const ComponentDepsNode::OperationIDKey *>(key_v); return BLI_ghashutil_combine_hash(BLI_ghashutil_uinthash(key->opcode), BLI_ghashutil_strhash_p(key->name)); } static bool comp_node_hash_key_cmp(const void *a, const void *b) { const ComponentDepsNode::OperationIDKey *key_a = reinterpret_cast<const ComponentDepsNode::OperationIDKey *>(a); const ComponentDepsNode::OperationIDKey *key_b = reinterpret_cast<const ComponentDepsNode::OperationIDKey *>(b); return !(*key_a == *key_b); } static void comp_node_hash_key_free(void *key_v) { typedef ComponentDepsNode::OperationIDKey OperationIDKey; OperationIDKey *key = reinterpret_cast<OperationIDKey *>(key_v); OBJECT_GUARDED_DELETE(key, OperationIDKey); } static void comp_node_hash_value_free(void *value_v) { OperationDepsNode *op_node = reinterpret_cast<OperationDepsNode *>(value_v); OBJECT_GUARDED_DELETE(op_node, OperationDepsNode); } ComponentDepsNode::ComponentDepsNode() : entry_operation(NULL), exit_operation(NULL), layers(0) { operations_map = BLI_ghash_new(comp_node_hash_key, comp_node_hash_key_cmp, "Depsgraph id hash"); } /* Initialize 'component' node - from pointer data given */ void ComponentDepsNode::init(const ID * /*id*/, const char * /*subdata*/) { /* hook up eval context? */ // XXX: maybe this needs a special API? } /* Free 'component' node */ ComponentDepsNode::~ComponentDepsNode() { clear_operations(); if (operations_map != NULL) { BLI_ghash_free(operations_map, comp_node_hash_key_free, comp_node_hash_value_free); } } string ComponentDepsNode::identifier() const { string idname = this->owner->name; char typebuf[16]; sprintf(typebuf, "(%d)", type); char layers[16]; sprintf(layers, "%u", this->layers); return string(typebuf) + name + " : " + idname + " (Layers: " + layers + ")"; } OperationDepsNode *ComponentDepsNode::find_operation(OperationIDKey key) const { OperationDepsNode *node = reinterpret_cast<OperationDepsNode *>(BLI_ghash_lookup(operations_map, &key)); if (node != NULL) { return node; } else { fprintf(stderr, "%s: find_operation(%s) failed\n", this->identifier().c_str(), key.identifier().c_str()); BLI_assert(!"Request for non-existing operation, should not happen"); return NULL; } } OperationDepsNode *ComponentDepsNode::find_operation(eDepsOperation_Code opcode, const char *name, int name_tag) const { OperationIDKey key(opcode, name, name_tag); return find_operation(key); } OperationDepsNode *ComponentDepsNode::has_operation(OperationIDKey key) const { return reinterpret_cast<OperationDepsNode *>(BLI_ghash_lookup(operations_map, &key)); } OperationDepsNode *ComponentDepsNode::has_operation(eDepsOperation_Code opcode, const char *name, int name_tag) const { OperationIDKey key(opcode, name, name_tag); return has_operation(key); } OperationDepsNode *ComponentDepsNode::add_operation(const DepsEvalOperationCb& op, eDepsOperation_Code opcode, const char *name, int name_tag) { OperationDepsNode *op_node = has_operation(opcode, name, name_tag); if (!op_node) { DepsNodeFactory *factory = deg_get_node_factory(DEG_NODE_TYPE_OPERATION); op_node = (OperationDepsNode *)factory->create_node(this->owner->id, "", name); /* register opnode in this component's operation set */ OperationIDKey *key = OBJECT_GUARDED_NEW(OperationIDKey, opcode, name, name_tag); BLI_ghash_insert(operations_map, key, op_node); /* set backlink */ op_node->owner = this; } else { fprintf(stderr, "add_operation: Operation already exists - %s has %s at %p\n", this->identifier().c_str(), op_node->identifier().c_str(), op_node); BLI_assert(!"Should not happen!"); } /* attach extra data */ op_node->evaluate = op; op_node->opcode = opcode; op_node->name = name; return op_node; } void ComponentDepsNode::set_entry_operation(OperationDepsNode *op_node) { BLI_assert(entry_operation == NULL); entry_operation = op_node; } void ComponentDepsNode::set_exit_operation(OperationDepsNode *op_node) { BLI_assert(exit_operation == NULL); exit_operation = op_node; } void ComponentDepsNode::clear_operations() { if (operations_map != NULL) { BLI_ghash_clear(operations_map, comp_node_hash_key_free, comp_node_hash_value_free); } foreach (OperationDepsNode *op_node, operations) { OBJECT_GUARDED_DELETE(op_node, OperationDepsNode); } operations.clear(); } void ComponentDepsNode::tag_update(Depsgraph *graph) { OperationDepsNode *entry_op = get_entry_operation(); if (entry_op != NULL && entry_op->flag & DEPSOP_FLAG_NEEDS_UPDATE) { return; } foreach (OperationDepsNode *op_node, operations) { op_node->tag_update(graph); } // It is possible that tag happens before finalization. if (operations_map != NULL) { GHASH_FOREACH_BEGIN(OperationDepsNode *, op_node, operations_map) { op_node->tag_update(graph); } GHASH_FOREACH_END(); } } OperationDepsNode *ComponentDepsNode::get_entry_operation() { if (entry_operation) { return entry_operation; } else if (operations_map != NULL && BLI_ghash_size(operations_map) == 1) { OperationDepsNode *op_node = NULL; /* TODO(sergey): This is somewhat slow. */ GHASH_FOREACH_BEGIN(OperationDepsNode *, tmp, operations_map) { op_node = tmp; } GHASH_FOREACH_END(); /* Cache for the subsequent usage. */ entry_operation = op_node; return op_node; } else if (operations.size() == 1) { return operations[0]; } return NULL; } OperationDepsNode *ComponentDepsNode::get_exit_operation() { if (exit_operation) { return exit_operation; } else if (operations_map != NULL && BLI_ghash_size(operations_map) == 1) { OperationDepsNode *op_node = NULL; /* TODO(sergey): This is somewhat slow. */ GHASH_FOREACH_BEGIN(OperationDepsNode *, tmp, operations_map) { op_node = tmp; } GHASH_FOREACH_END(); /* Cache for the subsequent usage. */ exit_operation = op_node; return op_node; } else if (operations.size() == 1) { return operations[0]; } return NULL; } void ComponentDepsNode::finalize_build() { operations.reserve(BLI_ghash_size(operations_map)); GHASH_FOREACH_BEGIN(OperationDepsNode *, op_node, operations_map) { operations.push_back(op_node); } GHASH_FOREACH_END(); BLI_ghash_free(operations_map, comp_node_hash_key_free, NULL); operations_map = NULL; } /* Parameter Component Defines ============================ */ DEG_DEPSNODE_DEFINE(ParametersComponentDepsNode, DEG_NODE_TYPE_PARAMETERS, "Parameters Component"); static DepsNodeFactoryImpl<ParametersComponentDepsNode> DNTI_PARAMETERS; /* Animation Component Defines ============================ */ DEG_DEPSNODE_DEFINE(AnimationComponentDepsNode, DEG_NODE_TYPE_ANIMATION, "Animation Component"); static DepsNodeFactoryImpl<AnimationComponentDepsNode> DNTI_ANIMATION; /* Transform Component Defines ============================ */ DEG_DEPSNODE_DEFINE(TransformComponentDepsNode, DEG_NODE_TYPE_TRANSFORM, "Transform Component"); static DepsNodeFactoryImpl<TransformComponentDepsNode> DNTI_TRANSFORM; /* Proxy Component Defines ================================ */ DEG_DEPSNODE_DEFINE(ProxyComponentDepsNode, DEG_NODE_TYPE_PROXY, "Proxy Component"); static DepsNodeFactoryImpl<ProxyComponentDepsNode> DNTI_PROXY; /* Geometry Component Defines ============================= */ DEG_DEPSNODE_DEFINE(GeometryComponentDepsNode, DEG_NODE_TYPE_GEOMETRY, "Geometry Component"); static DepsNodeFactoryImpl<GeometryComponentDepsNode> DNTI_GEOMETRY; /* Sequencer Component Defines ============================ */ DEG_DEPSNODE_DEFINE(SequencerComponentDepsNode, DEG_NODE_TYPE_SEQUENCER, "Sequencer Component"); static DepsNodeFactoryImpl<SequencerComponentDepsNode> DNTI_SEQUENCER; /* Pose Component ========================================= */ DEG_DEPSNODE_DEFINE(PoseComponentDepsNode, DEG_NODE_TYPE_EVAL_POSE, "Pose Eval Component"); static DepsNodeFactoryImpl<PoseComponentDepsNode> DNTI_EVAL_POSE; /* Bone Component ========================================= */ /* Initialize 'bone component' node - from pointer data given */ void BoneComponentDepsNode::init(const ID *id, const char *subdata) { /* generic component-node... */ ComponentDepsNode::init(id, subdata); /* name of component comes is bone name */ /* TODO(sergey): This sets name to an empty string because subdata is * empty. Is it a bug? */ //this->name = subdata; /* bone-specific node data */ Object *ob = (Object *)id; this->pchan = BKE_pose_channel_find_name(ob->pose, subdata); } DEG_DEPSNODE_DEFINE(BoneComponentDepsNode, DEG_NODE_TYPE_BONE, "Bone Component"); static DepsNodeFactoryImpl<BoneComponentDepsNode> DNTI_BONE; /* Particles Component Defines ============================ */ DEG_DEPSNODE_DEFINE(ParticlesComponentDepsNode, DEG_NODE_TYPE_EVAL_PARTICLES, "Particles Component"); static DepsNodeFactoryImpl<ParticlesComponentDepsNode> DNTI_EVAL_PARTICLES; /* Shading Component Defines ============================ */ DEG_DEPSNODE_DEFINE(ShadingComponentDepsNode, DEG_NODE_TYPE_SHADING, "Shading Component"); static DepsNodeFactoryImpl<ShadingComponentDepsNode> DNTI_SHADING; /* Cache Component Defines ============================ */ DEG_DEPSNODE_DEFINE(CacheComponentDepsNode, DEG_NODE_TYPE_CACHE, "Cache Component"); static DepsNodeFactoryImpl<CacheComponentDepsNode> DNTI_CACHE; /* Node Types Register =================================== */ void deg_register_component_depsnodes() { deg_register_node_typeinfo(&DNTI_PARAMETERS); deg_register_node_typeinfo(&DNTI_PROXY); deg_register_node_typeinfo(&DNTI_ANIMATION); deg_register_node_typeinfo(&DNTI_TRANSFORM); deg_register_node_typeinfo(&DNTI_GEOMETRY); deg_register_node_typeinfo(&DNTI_SEQUENCER); deg_register_node_typeinfo(&DNTI_EVAL_POSE); deg_register_node_typeinfo(&DNTI_BONE); deg_register_node_typeinfo(&DNTI_EVAL_PARTICLES); deg_register_node_typeinfo(&DNTI_SHADING); deg_register_node_typeinfo(&DNTI_CACHE); } } // namespace DEG
30.655814
105
0.692459
1-MillionParanoidTterabytes
e8832e47044d3687c0d0f79385ef7692eaf1d68b
5,410
hpp
C++
Nacro/SDK/FN_AthenaCustomizationSlotButton_classes.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_AthenaCustomizationSlotButton_classes.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_AthenaCustomizationSlotButton_classes.hpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
#pragma once // Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // WidgetBlueprintGeneratedClass AthenaCustomizationSlotButton.AthenaCustomizationSlotButton_C // 0x0110 (0x09C8 - 0x08B8) class UAthenaCustomizationSlotButton_C : public UAthenaCustomizationSlotSelectorButton { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x08B8(0x0008) (Transient, DuplicateTransient) class UImage* EmptyImage; // 0x08C0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UImage* ImageSlotType; // 0x08C8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UNormalBangWrapper_C* NormalBangWrapper; // 0x08D0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) class UOverlay* OverlayTypeIcon; // 0x08D8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate) struct FText TooltipBody; // 0x08E0(0x0018) (Edit, BlueprintVisible) struct FText TooltipHeader; // 0x08F8(0x0018) (Edit, BlueprintVisible) bool ShowSubTypeIcon; // 0x0910(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) unsigned char UnknownData00[0x7]; // 0x0911(0x0007) MISSED OFFSET struct FSlateBrush SubTypeIcon; // 0x0918(0x0090) (Edit, BlueprintVisible) bool bSuppressTooltip; // 0x09A8(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) EFortItemCardSize SlottedItemCardSize; // 0x09A9(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) unsigned char UnknownData01[0x2]; // 0x09AA(0x0002) MISSED OFFSET float TypeIconVerticalOffset; // 0x09AC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) struct FText CustomizationName; // 0x09B0(0x0018) (Edit, BlueprintVisible) static UClass* StaticClass() { static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass AthenaCustomizationSlotButton.AthenaCustomizationSlotButton_C"); return ptr; } ESlateVisibility ShouldShowEmptyImage(); void UpdateTypeIconOffset(float VerticalOffset); void Update_SubType_Icon_Glow(bool GlowIcon); void Update_SubType_Icon_Image(); void Construct(); void PreConstruct(bool* IsDesignTime); void ExecuteUbergraph_AthenaCustomizationSlotButton(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
93.275862
644
0.642144
Milxnor
e883a451e601c9b9b21ab8aaa496578cb156eb07
8,825
cpp
C++
src/prod/src/Management/DnsService/test/Helpers/DnsHelper.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
2,542
2018-03-14T21:56:12.000Z
2019-05-06T01:18:20.000Z
src/prod/src/Management/DnsService/test/Helpers/DnsHelper.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
994
2019-05-07T02:39:30.000Z
2022-03-31T13:23:04.000Z
src/prod/src/Management/DnsService/test/Helpers/DnsHelper.cpp
vishnuk007/service-fabric
d0afdea185ae932cc3c9eacf179692e6fddbc630
[ "MIT" ]
300
2018-03-14T21:57:17.000Z
2019-05-06T20:07:00.000Z
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" #include "DnsHelper.h" const ULONG LocalhostIP = 16777343; void DnsHelper::CreateDnsServiceHelper( __in KAllocator& allocator, __in DnsServiceParams& params, __out IDnsService::SPtr& spService, __out ComServiceManager::SPtr& spServiceManager, __out ComPropertyManager::SPtr& spPropertyManager, __out FabricData::SPtr& spData, __out IDnsParser::SPtr& spParser, __out INetIoManager::SPtr& spNetIoManager ) { NullTracer::SPtr spTracer; NullTracer::Create(/*out*/spTracer, allocator); DNS::CreateDnsParser(/*out*/spParser, allocator); DNS::CreateNetIoManager(/*out*/spNetIoManager, allocator, spTracer.RawPtr(), params.NumberOfConcurrentQueries); KString::SPtr spName; KString::Create(/*out*/spName, allocator, L"fabric:/System/DNS", TRUE/*appendnull*/); ComServiceManager::Create(/*out*/spServiceManager, allocator); ComPropertyManager::Create(/*out*/spPropertyManager, allocator); FabricData::Create(/*out*/spData, allocator); IDnsCache::SPtr spCache; CreateDnsCache(/*out*/spCache, allocator, params.MaxCacheSize); IFabricResolve::SPtr spResolve; DNS::CreateFabricResolve(/*out*/spResolve, allocator, spName, spTracer.RawPtr(), spData.RawPtr(), spCache.RawPtr(), spServiceManager.RawPtr(), spPropertyManager.RawPtr()); ComFabricStatelessServicePartition2::SPtr spHealth; ComFabricStatelessServicePartition2::Create(/*out*/spHealth, allocator); DNS::CreateDnsService( /*out*/spService, allocator, spTracer.RawPtr(), spParser.RawPtr(), spNetIoManager.RawPtr(), spResolve.RawPtr(), spCache, *spHealth.RawPtr(), params ); } DNS_STATUS DnsHelper::QueryEx( __in KBuffer& buffer, __in LPCWSTR wszQuery, __in USHORT type, __in KArray<DNS_DATA>& results ) { KAllocator& allocator = buffer.GetThisAllocator(); DNS_STATUS status = 0; IDnsService::SPtr spServiceInner; DnsServiceSynchronizer dnsServiceSyncInner; ComServiceManager::SPtr spServiceManagerInner; ComPropertyManager::SPtr spPropertyManagerInner; FabricData::SPtr spDataInner; IDnsParser::SPtr spParser; INetIoManager::SPtr spNetIoManager; DnsServiceParams params; params.IsRecursiveQueryEnabled = true; CreateDnsServiceHelper(allocator, params, /*out*/spServiceInner, /*out*/spServiceManagerInner, /*out*/spPropertyManagerInner, /*out*/spDataInner, /*out*/spParser, /*out*/spNetIoManager); USHORT port = 0; if (!spServiceInner->Open(/*inout*/port, static_cast<DnsServiceCallback>(dnsServiceSyncInner))) { VERIFY_FAIL(L""); } status = DnsHelper::Query(*spNetIoManager, buffer, *spParser, port, wszQuery, type, results); spServiceInner->CloseAsync(); dnsServiceSyncInner.Wait(); return status; } DNS_STATUS DnsHelper::Query( __in INetIoManager& netIoManager, __in KBuffer& buffer, __in IDnsParser& dnsParser, __in USHORT port, __in LPCWSTR wszQuery, __in WORD type, __in KArray<DNS_DATA>& results ) { #if !defined(PLATFORM_UNIX) UNREFERENCED_PARAMETER(dnsParser); #endif DNS_STATUS status = 0; KAllocator& allocator = buffer.GetThisAllocator(); DWORD dwSize = buffer.QuerySize(); DnsHelper::SerializeQuestion(dnsParser, wszQuery, buffer, type, /*out*/dwSize); NullTracer::SPtr spTracer; NullTracer::Create(/*out*/spTracer, allocator); IUdpListener::SPtr spListener; netIoManager.CreateUdpListener(/*out*/spListener, false /*AllowMultipleListeners*/); USHORT portClient = 0; DnsServiceSynchronizer syncListener; if (!spListener->StartListener(nullptr, /*inout*/portClient, syncListener)) { VERIFY_FAIL_FMT(L"Failed to start UDP listener"); } ISocketAddress::SPtr spAddress; DNS::CreateSocketAddress(/*out*/spAddress, allocator, LocalhostIP, htons(port)); DnsServiceSynchronizer syncWrite; spListener->WriteAsync(buffer, dwSize, *spAddress, syncWrite); syncWrite.Wait(5000); ISocketAddress::SPtr spAddressFrom; DNS::CreateSocketAddress(/*out*/spAddressFrom, allocator); DnsServiceSynchronizer syncRead; spListener->ReadAsync(buffer, *spAddressFrom, syncRead, 5000); syncRead.Wait(5000); spListener->CloseAsync(); syncListener.Wait(5000); #if !defined(PLATFORM_UNIX) // From MSDN: // The DnsExtractRecordsFromMessage function is designed to operate on messages in host byte order. // As such, received messages should be converted from network byte order to host byte order before extraction, // or before retransmission onto the network. Use the DNS_BYTE_FLIP_HEADER_COUNTS macro to change byte ordering. // PDNS_MESSAGE_BUFFER dnsBuffer = (PDNS_MESSAGE_BUFFER)buffer.GetBuffer(); DNS_BYTE_FLIP_HEADER_COUNTS(&dnsBuffer->MessageHead); PDNS_RECORD record = nullptr; status = DnsExtractRecordsFromMessage_W(dnsBuffer, (WORD)syncRead.Size(), &record); DNS_DATA dnsData; while (record != NULL) { dnsData.Type = record->wType; switch (record->wType) { case DNS_TYPE_A: { DNS_A_DATA& data = record->Data.A; IN_ADDR addr; addr.S_un.S_addr = data.IpAddress; WCHAR temp[256]; InetNtop(AF_INET, &addr, temp, ARRAYSIZE(temp)); dnsData.DataStr = KString::Create(temp, allocator); results.Append(dnsData); } break; case DNS_TYPE_SRV: { DNS_SRV_DATA& data = record->Data.SRV; WCHAR temp[1024]; STRPRINT(temp, ARRAYSIZE(temp), L"%s:%d", data.pNameTarget, data.wPort); CharLowerBuff(temp, (DWORD)wcslen(temp)); dnsData.DataStr = KString::Create(temp, allocator); results.Append(dnsData); } break; case DNS_TYPE_TEXT: { DNS_TXT_DATA& data = record->Data.TXT; dnsData.DataStr = KString::Create(KStringView(data.pStringArray[0]), allocator); results.Append(dnsData); } break; case DNS_TYPE_AAAA: { // we don't care about the value here results.Append(dnsData); } break; } // switch record = record->pNext; } DnsRecordListFree(record, DnsFreeFlat); #else IDnsMessage::SPtr spAnswerMessage; dnsParser.Deserialize(/*out*/spAnswerMessage, buffer, syncRead.Size(), true); KArray<IDnsRecord::SPtr>& arrDnsRecords = spAnswerMessage->Answers(); for (ULONG i = 0; i < arrDnsRecords.Count(); i++) { IDnsRecord::SPtr spAnswer = arrDnsRecords[i]; DNS_DATA dnsData; dnsData.Type = spAnswer->Type(); dnsData.DataStr = spAnswer->DebugString(); results.Append(dnsData); } status = DNS::DnsFlags::GetResponseCode(spAnswerMessage->Flags()); switch (status) { case DNS::DnsFlags::RC_FORMERR: status = DNS_ERROR_RCODE_FORMAT_ERROR; break; case DNS::DnsFlags::RC_SERVFAIL: status = DNS_ERROR_RCODE_SERVER_FAILURE; break; case DNS::DnsFlags::RC_NXDOMAIN: status = DNS_ERROR_RCODE_NAME_ERROR; break; case DNS::DnsFlags::RC_NOERROR: if (results.Count() == 0) { status = DNS_INFO_NO_RECORDS; } break; } #endif return status; } void DnsHelper::SerializeQuestion( __in IDnsParser& dnsParser, __in LPCWSTR wszQuery, __in KBuffer& buffer, __in WORD type, __out ULONG& size, __in DnsTextEncodingType encodingType ) { buffer.Zero(); size = buffer.QuerySize(); #if !defined(PLATFORM_UNIX) UNREFERENCED_PARAMETER(dnsParser); UNREFERENCED_PARAMETER(encodingType); if (!DnsWriteQuestionToBuffer_W((PDNS_MESSAGE_BUFFER)buffer.GetBuffer(), &size, wszQuery, type, 1, TRUE)) { VERIFY_FAIL_FMT(L"Failed to serialize question to buffer"); } #else KAllocator& allocator = buffer.GetThisAllocator(); KString::SPtr spQuestionStr; KString::Create(/*out*/spQuestionStr, allocator, wszQuery); spQuestionStr->SetNullTerminator(); IDnsMessage::SPtr spMessage = dnsParser.CreateQuestionMessage(rand() % MAXUSHORT, *spQuestionStr, (DnsRecordType)type, encodingType); if (!dnsParser.Serialize(buffer, /*out*/size, *spMessage, 1, encodingType)) { VERIFY_FAIL_FMT(L"Failed to serialize question to buffer"); } #endif }
31.183746
137
0.665609
vishnuk007
e885c8e86dcc42189f8cf0a89042139f50dd1d88
1,393
cpp
C++
src/pathutils.cpp
merelabs/mere-utils
26e4bc834e9b506d7939a9154f14e300458262c1
[ "BSD-2-Clause" ]
null
null
null
src/pathutils.cpp
merelabs/mere-utils
26e4bc834e9b506d7939a9154f14e300458262c1
[ "BSD-2-Clause" ]
null
null
null
src/pathutils.cpp
merelabs/mere-utils
26e4bc834e9b506d7939a9154f14e300458262c1
[ "BSD-2-Clause" ]
null
null
null
#include "pathutils.h" #include <sys/stat.h> #include <unistd.h> #include <iostream> //static bool Mere::Utils::PathUtils::exists(const std::string &path) { struct stat s; stat(path.c_str(), &s); //S_ISDIR(s.st_mode) || S_ISREG(s.st_mode) || S_ISFIFO(s.st_mode) || S_ISLNK(s.st_mode) || S_ISSOCK(s.st_mode); return stat(path.c_str(), &s) == 0; } //static bool Mere::Utils::PathUtils::remove(const std::string &path) { if(exists(path)) return false; int err = rmdir(path.c_str()); return !err; } //static bool Mere::Utils::PathUtils::create(const std::string &path, int mode) { if(exists(path)) return false; auto pos = path.find("/", 0); while (pos != std::string::npos) { std::string part = path.substr(0, pos + 1); if (!exists(part) && mkdir(part.c_str(), mode)) return false; pos = path.find("/", pos + 1); } int err = mkdir(path.c_str(), mode); return !err; } //static bool Mere::Utils::PathUtils::create_if_none(const std::string &path, int mode) { return create(path, mode); } //static std::string Mere::Utils::PathUtils::resolve(const std::string &path, int *resolved) { char buffer[PATH_MAX]; if(realpath(path.c_str(), buffer)) { if (resolved) *resolved = 1; return std::string(buffer); } if (resolved) *resolved = 0; return path; }
20.485294
115
0.605887
merelabs
e886ad54105d8b37897a115fbfd4b2dd6efb2eb3
3,896
hpp
C++
src/univang/format/format_context.hpp
bibmaster/nx.format
0993832a678bea4c1c005a97fba414557985356f
[ "MIT" ]
7
2019-10-08T13:11:07.000Z
2020-01-30T21:29:18.000Z
src/univang/format/format_context.hpp
bibmaster/nx.format
0993832a678bea4c1c005a97fba414557985356f
[ "MIT" ]
null
null
null
src/univang/format/format_context.hpp
bibmaster/nx.format
0993832a678bea4c1c005a97fba414557985356f
[ "MIT" ]
null
null
null
#pragma once #include <cassert> #include <cstddef> #include <cstring> #include <stdexcept> #include <string_view> namespace univang { namespace fmt { class format_context { public: #if FMT_RESPECT_ALIASING using byte = std::byte; #else enum class byte : char {}; #endif format_context() = default; constexpr format_context( void* data, size_t capacity, size_t size = 0) noexcept : data_(static_cast<byte*>(data)), capacity_(capacity), size_(size) { } format_context(const format_context&) = delete; format_context& operator=(const format_context&) = delete; virtual void grow(size_t /*new_capacity*/) { throw std::length_error("format_context limit overflow"); } byte& operator[](size_t index) { assert(index <= capacity_); return data_[index]; } byte operator[](size_t index) const { assert(index <= capacity_); return data_[index]; } void clear() { size_ = 0; } void assign(void* data, size_t capacity) noexcept { data_ = static_cast<byte*>(data); capacity_ = capacity; } void reserve(size_t sz) { if(capacity_ < sz) grow(sz); } void ensure(size_t add_size) { reserve(size_ + add_size); } byte back() const { assert(size_ != 0); return data_[size_ - 1]; } byte* data() const noexcept { return data_; } size_t size() const noexcept { return size_; } bool empty() const noexcept { return size_ == 0; } size_t capacity() const noexcept { return capacity_; } std::string_view get_str() const noexcept { return {reinterpret_cast<const char*>(data_), size_}; } void advance(size_t sz = 1) noexcept { assert(size_ + sz <= capacity_); size_ += sz; } void add(byte b) { assert(size_ < capacity_); data_[size_++] = b; } void add(char c) { assert(size_ < capacity_); data_[size_++] = byte(c); } void write(char c) { ensure(1); add(c); } void add_padding(char c, size_t count) { assert(size_ + count <= capacity_); memset(data_ + size_, int(c), count); size_ += count; } void write_padding(char c, size_t count) { ensure(count); add_padding(c, count); } void make_c_str() { ensure(1); data_[size_] = byte(0); } void add(const void* p, size_t sz) { assert(size_ + sz <= capacity_); memcpy(data_ + size_, p, sz); size_ += sz; } void write(const void* p, size_t sz) { ensure(sz); add(p, sz); } template<class Char, class Traits> auto add(std::basic_string_view<Char, Traits> str) -> std::enable_if_t<sizeof(Char) == 1> { add(str.data(), str.size()); } template<class Char, class Traits> auto write(std::basic_string_view<Char, Traits> str) -> std::enable_if_t<sizeof(Char) == 1> { write(str.data(), str.size()); } private: byte* data_ = nullptr; size_t capacity_ = 0; size_t size_ = 0; }; template<class String> class basic_string_format_context : public format_context { public: basic_string_format_context(String& str) : format_context(str.data(), str.size(), str.size()), str_(str) { } ~basic_string_format_context() { finalize(); } void grow(size_t new_capacity) final { str_.reserve(new_capacity); str_.resize(str_.capacity()); format_context::assign(str_.data(), str_.size()); } size_t finalize() { str_.resize(format_context::size()); return format_context::size(); } private: String& str_; }; using string_format_context = basic_string_format_context<std::string>; } // namespace fmt } // namespace univang
25.973333
77
0.587269
bibmaster
e88a0e10bd069e49e0342ae21caf69cc35eb2cb9
3,376
cpp
C++
src/main.cpp
Piripant/sbodies
19f4cbf4ec449706f82667c7875a2534aa367d76
[ "MIT" ]
1
2021-01-16T04:14:35.000Z
2021-01-16T04:14:35.000Z
src/main.cpp
Piripant/sbodies
19f4cbf4ec449706f82667c7875a2534aa367d76
[ "MIT" ]
null
null
null
src/main.cpp
Piripant/sbodies
19f4cbf4ec449706f82667c7875a2534aa367d76
[ "MIT" ]
null
null
null
#include "world.h" #include <SFML/Graphics.hpp> #include <iostream> #include <imgui.h> #include <imgui-SFML.h> int scale = 20; sf::Color colors[2] = { sf::Color(0, 0, 0), sf::Color(0, 0, 255) }; float step_time = 0.1; bool mouse_pressed = false; int press_y = 0; int press_x = 0; int nvertex = 3; float sim_speed = 1.0; bool edit_mode = true; int main() { // create the window sf::RenderWindow window(sf::VideoMode(800, 600), "tfluids"); debug_window = &window; ImGui::SFML::Init(window); auto body = Body(nvertex); std::cout << body.get_volume() << std::endl; int steps = 0; float elapsed = 0; sf::Clock delta_clock; // run the program as long as the window is open while (window.isOpen()) { auto elapsed = delta_clock.restart(); auto dt = elapsed.asSeconds(); if (dt > 0.001) { dt = 0; } dt *= sim_speed; auto size = window.getSize(); sf::Event event; while (window.pollEvent(event)) { ImGui::SFML::ProcessEvent(event); if (event.type == sf::Event::Closed) { window.close(); } if (event.type == sf::Event::Resized) { window.setView(sf::View(sf::FloatRect(0, 0, event.size.width, event.size.height))); } if (event.type == sf::Event::MouseButtonReleased && edit_mode) { /* if (event.mouseButton.button == sf::Mouse::Button::Left) { auto x = (double)((double)event.mouseButton.x - size.x/2.0) / 5.0; auto y = (double)((double)-event.mouseButton.y + size.y/2.0) / 5.0; body.append_vertex(BodyVertex(Vector(x, y))); } */ if (event.mouseButton.button == sf::Mouse::Button::Right) { body.set_joints(); edit_mode = false; } } } ImGui::SFML::Update(window, elapsed); ImGui::Begin("Settings"); if (ImGui::Button("Restart")) { body = Body(nvertex); edit_mode = true; } ImGui::Text("FPS: %f", 1/dt); ImGui::SliderFloat("Simulation speed", &sim_speed, 0.0f, 16.0f); ImGui::SliderInt("Number of vertexes", &nvertex, 1, 64); window.clear(sf::Color::White); if (!edit_mode) { body.update(dt); } ImGui::End(); sf::ConvexShape body_shape; body_shape.setFillColor(sf::Color(200, 200, 200)); body_shape.setPointCount(body.verts.size()); for (int i = 0; i < body.verts.size(); i++) { auto x = body.verts[i].position.x * 5 + size.x / 2; auto y = -body.verts[i].position.y * 5 + size.y / 2; sf::RectangleShape point(sf::Vector2f(5, 5)); point.setFillColor(sf::Color::Red); point.setPosition(sf::Vector2f(x - 5.0/2, y - 5.0/2)); window.draw(point); body_shape.setPoint(i, sf::Vector2f(x, y)); } window.draw(body_shape); ImGui::SFML::Render(window); window.display(); } return 0; }
28.854701
98
0.492595
Piripant
e88b7fbeebf95dab16a329dd96c4039f1bef2bdc
15,228
cpp
C++
src/uml/src_gen/uml/impl/ActivityGroupImpl.cpp
MDE4CPP/MDE4CPP
9db9352dd3b1ae26a5f640e614ed3925499b93f1
[ "MIT" ]
12
2017-02-17T10:33:51.000Z
2022-03-01T02:48:10.000Z
src/uml/src_gen/uml/impl/ActivityGroupImpl.cpp
ndongmo/MDE4CPP
9db9352dd3b1ae26a5f640e614ed3925499b93f1
[ "MIT" ]
28
2017-10-17T20:23:52.000Z
2021-03-04T16:07:13.000Z
src/uml/src_gen/uml/impl/ActivityGroupImpl.cpp
ndongmo/MDE4CPP
9db9352dd3b1ae26a5f640e614ed3925499b93f1
[ "MIT" ]
22
2017-03-24T19:03:58.000Z
2022-03-31T12:10:07.000Z
#include "uml/impl/ActivityGroupImpl.hpp" #ifdef NDEBUG #define DEBUG_MESSAGE(a) /**/ #else #define DEBUG_MESSAGE(a) a #endif #ifdef ACTIVITY_DEBUG_ON #define ACT_DEBUG(a) a #else #define ACT_DEBUG(a) /**/ #endif //#include "util/ProfileCallCount.hpp" #include <cassert> #include <iostream> #include <sstream> #include "abstractDataTypes/Bag.hpp" #include "abstractDataTypes/Subset.hpp" #include "abstractDataTypes/SubsetUnion.hpp" #include "abstractDataTypes/Union.hpp" #include "abstractDataTypes/Any.hpp" #include "abstractDataTypes/SubsetUnion.hpp" #include "ecore/EAnnotation.hpp" #include "ecore/EClass.hpp" //Includes from codegen annotation //Forward declaration includes #include "persistence/interfaces/XLoadHandler.hpp" // used for Persistence #include "persistence/interfaces/XSaveHandler.hpp" // used for Persistence #include <exception> // used in Persistence #include "uml/Activity.hpp" #include "uml/ActivityEdge.hpp" #include "uml/ActivityGroup.hpp" #include "uml/ActivityNode.hpp" #include "uml/Comment.hpp" #include "uml/Dependency.hpp" #include "uml/Element.hpp" #include "uml/NamedElement.hpp" #include "uml/Namespace.hpp" #include "uml/StringExpression.hpp" //Factories an Package includes #include "uml/impl/umlFactoryImpl.hpp" #include "uml/impl/umlPackageImpl.hpp" #include "ecore/EAttribute.hpp" #include "ecore/EStructuralFeature.hpp" using namespace uml; //********************************* // Constructor / Destructor //********************************* ActivityGroupImpl::ActivityGroupImpl() { } ActivityGroupImpl::~ActivityGroupImpl() { #ifdef SHOW_DELETION std::cout << "-------------------------------------------------------------------------------------------------\r\ndelete ActivityGroup "<< this << "\r\n------------------------------------------------------------------------ " << std::endl; #endif } //Additional constructor for the containments back reference ActivityGroupImpl::ActivityGroupImpl(std::weak_ptr<uml::Activity > par_inActivity) :ActivityGroupImpl() { m_inActivity = par_inActivity; m_owner = par_inActivity; } //Additional constructor for the containments back reference ActivityGroupImpl::ActivityGroupImpl(std::weak_ptr<uml::Namespace > par_namespace) :ActivityGroupImpl() { m_namespace = par_namespace; m_owner = par_namespace; } //Additional constructor for the containments back reference ActivityGroupImpl::ActivityGroupImpl(std::weak_ptr<uml::Element > par_owner) :ActivityGroupImpl() { m_owner = par_owner; } //Additional constructor for the containments back reference ActivityGroupImpl::ActivityGroupImpl(std::weak_ptr<uml::ActivityGroup > par_superGroup) :ActivityGroupImpl() { m_superGroup = par_superGroup; m_owner = par_superGroup; } ActivityGroupImpl::ActivityGroupImpl(const ActivityGroupImpl & obj):ActivityGroupImpl() { //create copy of all Attributes #ifdef SHOW_COPIES std::cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\r\ncopy ActivityGroup "<< this << "\r\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ " << std::endl; #endif m_name = obj.getName(); m_qualifiedName = obj.getQualifiedName(); m_visibility = obj.getVisibility(); //copy references with no containment (soft copy) std::shared_ptr<Bag<uml::Dependency>> _clientDependency = obj.getClientDependency(); m_clientDependency.reset(new Bag<uml::Dependency>(*(obj.getClientDependency().get()))); std::shared_ptr<Union<uml::ActivityEdge>> _containedEdge = obj.getContainedEdge(); m_containedEdge.reset(new Union<uml::ActivityEdge>(*(obj.getContainedEdge().get()))); std::shared_ptr<Union<uml::ActivityNode>> _containedNode = obj.getContainedNode(); m_containedNode.reset(new Union<uml::ActivityNode>(*(obj.getContainedNode().get()))); m_inActivity = obj.getInActivity(); m_namespace = obj.getNamespace(); m_owner = obj.getOwner(); m_superGroup = obj.getSuperGroup(); //Clone references with containment (deep copy) if(obj.getNameExpression()!=nullptr) { m_nameExpression = std::dynamic_pointer_cast<uml::StringExpression>(obj.getNameExpression()->copy()); } #ifdef SHOW_SUBSET_UNION std::cout << "Copying the Subset: " << "m_nameExpression" << std::endl; #endif std::shared_ptr<Bag<uml::Comment>> _ownedCommentList = obj.getOwnedComment(); for(std::shared_ptr<uml::Comment> _ownedComment : *_ownedCommentList) { this->getOwnedComment()->add(std::shared_ptr<uml::Comment>(std::dynamic_pointer_cast<uml::Comment>(_ownedComment->copy()))); } #ifdef SHOW_SUBSET_UNION std::cout << "Copying the Subset: " << "m_ownedComment" << std::endl; #endif } std::shared_ptr<ecore::EObject> ActivityGroupImpl::copy() const { std::shared_ptr<ActivityGroupImpl> element(new ActivityGroupImpl(*this)); element->setThisActivityGroupPtr(element); return element; } std::shared_ptr<ecore::EClass> ActivityGroupImpl::eStaticClass() const { return uml::umlPackage::eInstance()->getActivityGroup_Class(); } //********************************* // Attribute Setter Getter //********************************* //********************************* // Operations //********************************* std::shared_ptr<uml::Activity> ActivityGroupImpl::containingActivity() { std::cout << __PRETTY_FUNCTION__ << std::endl; throw "UnsupportedOperationException"; } bool ActivityGroupImpl::nodes_and_edges(Any diagnostics,std::map < Any, Any > context) { std::cout << __PRETTY_FUNCTION__ << std::endl; throw "UnsupportedOperationException"; } bool ActivityGroupImpl::not_contained(Any diagnostics,std::map < Any, Any > context) { std::cout << __PRETTY_FUNCTION__ << std::endl; throw "UnsupportedOperationException"; } //********************************* // References //********************************* /* Getter & Setter for reference containedEdge */ /* Getter & Setter for reference containedNode */ /* Getter & Setter for reference inActivity */ std::weak_ptr<uml::Activity > ActivityGroupImpl::getInActivity() const { return m_inActivity; } void ActivityGroupImpl::setInActivity(std::shared_ptr<uml::Activity> _inActivity) { m_inActivity = _inActivity; } /* Getter & Setter for reference subgroup */ /* Getter & Setter for reference superGroup */ //********************************* // Union Getter //********************************* std::shared_ptr<Union<uml::ActivityEdge>> ActivityGroupImpl::getContainedEdge() const { if(m_containedEdge == nullptr) { /*Union*/ m_containedEdge.reset(new Union<uml::ActivityEdge>()); #ifdef SHOW_SUBSET_UNION std::cout << "Initialising Union: " << "m_containedEdge - Union<uml::ActivityEdge>()" << std::endl; #endif } return m_containedEdge; } std::shared_ptr<Union<uml::ActivityNode>> ActivityGroupImpl::getContainedNode() const { if(m_containedNode == nullptr) { /*Union*/ m_containedNode.reset(new Union<uml::ActivityNode>()); #ifdef SHOW_SUBSET_UNION std::cout << "Initialising Union: " << "m_containedNode - Union<uml::ActivityNode>()" << std::endl; #endif } return m_containedNode; } std::shared_ptr<Union<uml::Element>> ActivityGroupImpl::getOwnedElement() const { if(m_ownedElement == nullptr) { /*Union*/ m_ownedElement.reset(new Union<uml::Element>()); #ifdef SHOW_SUBSET_UNION std::cout << "Initialising Union: " << "m_ownedElement - Union<uml::Element>()" << std::endl; #endif } return m_ownedElement; } std::weak_ptr<uml::Element > ActivityGroupImpl::getOwner() const { return m_owner; } std::shared_ptr<SubsetUnion<uml::ActivityGroup, uml::Element>> ActivityGroupImpl::getSubgroup() const { if(m_subgroup == nullptr) { /*SubsetUnion*/ m_subgroup.reset(new SubsetUnion<uml::ActivityGroup, uml::Element >()); #ifdef SHOW_SUBSET_UNION std::cout << "Initialising shared pointer SubsetUnion: " << "m_subgroup - SubsetUnion<uml::ActivityGroup, uml::Element >()" << std::endl; #endif /*SubsetUnion*/ m_subgroup->initSubsetUnion(getOwnedElement()); #ifdef SHOW_SUBSET_UNION std::cout << "Initialising value SubsetUnion: " << "m_subgroup - SubsetUnion<uml::ActivityGroup, uml::Element >(getOwnedElement())" << std::endl; #endif } return m_subgroup; } std::weak_ptr<uml::ActivityGroup > ActivityGroupImpl::getSuperGroup() const { return m_superGroup; } std::shared_ptr<ActivityGroup> ActivityGroupImpl::getThisActivityGroupPtr() const { return m_thisActivityGroupPtr.lock(); } void ActivityGroupImpl::setThisActivityGroupPtr(std::weak_ptr<ActivityGroup> thisActivityGroupPtr) { m_thisActivityGroupPtr = thisActivityGroupPtr; setThisNamedElementPtr(thisActivityGroupPtr); } std::shared_ptr<ecore::EObject> ActivityGroupImpl::eContainer() const { if(auto wp = m_inActivity.lock()) { return wp; } if(auto wp = m_namespace.lock()) { return wp; } if(auto wp = m_owner.lock()) { return wp; } if(auto wp = m_superGroup.lock()) { return wp; } return nullptr; } //********************************* // Structural Feature Getter/Setter //********************************* Any ActivityGroupImpl::eGet(int featureID, bool resolve, bool coreType) const { switch(featureID) { case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_CONTAINEDEDGE: { std::shared_ptr<Bag<ecore::EObject>> tempList(new Bag<ecore::EObject>()); Bag<uml::ActivityEdge>::iterator iter = m_containedEdge->begin(); Bag<uml::ActivityEdge>::iterator end = m_containedEdge->end(); while (iter != end) { tempList->add(*iter); iter++; } return eAny(tempList); //109 } case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_CONTAINEDNODE: { std::shared_ptr<Bag<ecore::EObject>> tempList(new Bag<ecore::EObject>()); Bag<uml::ActivityNode>::iterator iter = m_containedNode->begin(); Bag<uml::ActivityNode>::iterator end = m_containedNode->end(); while (iter != end) { tempList->add(*iter); iter++; } return eAny(tempList); //1010 } case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_INACTIVITY: return eAny(std::dynamic_pointer_cast<ecore::EObject>(getInActivity().lock())); //1011 case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_SUBGROUP: { std::shared_ptr<Bag<ecore::EObject>> tempList(new Bag<ecore::EObject>()); Bag<uml::ActivityGroup>::iterator iter = m_subgroup->begin(); Bag<uml::ActivityGroup>::iterator end = m_subgroup->end(); while (iter != end) { tempList->add(*iter); iter++; } return eAny(tempList); //1012 } case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_SUPERGROUP: return eAny(std::dynamic_pointer_cast<ecore::EObject>(getSuperGroup().lock())); //1013 } return NamedElementImpl::eGet(featureID, resolve, coreType); } bool ActivityGroupImpl::internalEIsSet(int featureID) const { switch(featureID) { case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_CONTAINEDEDGE: return getContainedEdge() != nullptr; //109 case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_CONTAINEDNODE: return getContainedNode() != nullptr; //1010 case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_INACTIVITY: return getInActivity().lock() != nullptr; //1011 case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_SUBGROUP: return getSubgroup() != nullptr; //1012 case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_SUPERGROUP: return getSuperGroup().lock() != nullptr; //1013 } return NamedElementImpl::internalEIsSet(featureID); } bool ActivityGroupImpl::eSet(int featureID, Any newValue) { switch(featureID) { case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_INACTIVITY: { // BOOST CAST std::shared_ptr<ecore::EObject> _temp = newValue->get<std::shared_ptr<ecore::EObject>>(); std::shared_ptr<uml::Activity> _inActivity = std::dynamic_pointer_cast<uml::Activity>(_temp); setInActivity(_inActivity); //1011 return true; } } return NamedElementImpl::eSet(featureID, newValue); } //********************************* // Persistence Functions //********************************* void ActivityGroupImpl::load(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler) { std::map<std::string, std::string> attr_list = loadHandler->getAttributeList(); loadAttributes(loadHandler, attr_list); // // Create new objects (from references (containment == true)) // // get umlFactory int numNodes = loadHandler->getNumOfChildNodes(); for(int ii = 0; ii < numNodes; ii++) { loadNode(loadHandler->getNextNodeName(), loadHandler); } } void ActivityGroupImpl::loadAttributes(std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler, std::map<std::string, std::string> attr_list) { NamedElementImpl::loadAttributes(loadHandler, attr_list); } void ActivityGroupImpl::loadNode(std::string nodeName, std::shared_ptr<persistence::interfaces::XLoadHandler> loadHandler) { std::shared_ptr<uml::umlFactory> modelFactory=uml::umlFactory::eInstance(); try { if ( nodeName.compare("subgroup") == 0 ) { std::string typeName = loadHandler->getCurrentXSITypeName(); if (typeName.empty()) { std::cout << "| WARNING | type if an eClassifiers node it empty" << std::endl; return; // no type name given and reference type is abstract } std::shared_ptr<ecore::EObject> subgroup = modelFactory->create(typeName, loadHandler->getCurrentObject(), uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_SUPERGROUP); if (subgroup != nullptr) { loadHandler->handleChild(subgroup); } return; } } catch (std::exception& e) { std::cout << "| ERROR | " << e.what() << std::endl; } catch (...) { std::cout << "| ERROR | " << "Exception occurred" << std::endl; } //load BasePackage Nodes NamedElementImpl::loadNode(nodeName, loadHandler); } void ActivityGroupImpl::resolveReferences(const int featureID, std::list<std::shared_ptr<ecore::EObject> > references) { switch(featureID) { case uml::umlPackage::ACTIVITYGROUP_ATTRIBUTE_INACTIVITY: { if (references.size() == 1) { // Cast object to correct type std::shared_ptr<uml::Activity> _inActivity = std::dynamic_pointer_cast<uml::Activity>( references.front() ); setInActivity(_inActivity); } return; } } NamedElementImpl::resolveReferences(featureID, references); } void ActivityGroupImpl::save(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const { saveContent(saveHandler); NamedElementImpl::saveContent(saveHandler); ElementImpl::saveContent(saveHandler); ObjectImpl::saveContent(saveHandler); ecore::EObjectImpl::saveContent(saveHandler); } void ActivityGroupImpl::saveContent(std::shared_ptr<persistence::interfaces::XSaveHandler> saveHandler) const { try { std::shared_ptr<uml::umlPackage> package = uml::umlPackage::eInstance(); // // Add new tags (from references) // std::shared_ptr<ecore::EClass> metaClass = this->eClass(); // Save 'subgroup' std::shared_ptr<SubsetUnion<uml::ActivityGroup, uml::Element>> list_subgroup = this->getSubgroup(); for (std::shared_ptr<uml::ActivityGroup> subgroup : *list_subgroup) { saveHandler->addReference(subgroup, "subgroup", subgroup->eClass() !=uml::umlPackage::eInstance()->getActivityGroup_Class()); } } catch (std::exception& e) { std::cout << "| ERROR | " << e.what() << std::endl; } }
26.575916
242
0.690307
MDE4CPP
e88be034b39482a4054c2ab7039392fcc995080c
1,053
cpp
C++
07. Sorting/InsersionSort.cpp
R-Arpita/DSA-cpp-Hacktoberfest2021
acc7896fe30ddd54bcf4ec7bb93bd1f0b30b3bc5
[ "MIT" ]
149
2021-09-17T17:11:06.000Z
2021-10-01T17:32:18.000Z
07. Sorting/InsersionSort.cpp
R-Arpita/DSA-cpp-Hacktoberfest2021
acc7896fe30ddd54bcf4ec7bb93bd1f0b30b3bc5
[ "MIT" ]
138
2021-09-29T14:04:05.000Z
2021-10-01T17:43:18.000Z
07. Sorting/InsersionSort.cpp
R-Arpita/DSA-cpp-Hacktoberfest2021
acc7896fe30ddd54bcf4ec7bb93bd1f0b30b3bc5
[ "MIT" ]
410
2021-09-27T03:13:55.000Z
2021-10-01T17:59:42.000Z
/* Sayansree Paria email : sayansreeparia@gmail.com github : https://github.com/Sayansree Insertion sort algorithm */ #include<bits/stdc++.h> using namespace std; //iterative implementation of Insertion sort // arr is input array of size n void InsertionSort(int arr[],int n ){ for(int i=1; i<n; i++){ int j=i,key=arr[i]; while(key<arr[j-1]&&j>0){ arr[j]=arr[j-1]; j--; } arr[j]=key; } } ////recursive implementation of Insertion sort void RecursiveInsertionSort(int arr[],int n ){ if(n==1)return; RecursiveInsertionSort(arr,n-1); int j=n-1,key=arr[n-1]; while(key<arr[j-1]&&j>0){ arr[j]=arr[j-1]; j--; } arr[j]=key; } ///test run code int main(){ int arr[]={8,9,10,1,4,2,4,8,2,5}; int d=2,n=sizeof(arr)/sizeof(int); for(int i:arr) cout<<i<<"\t"; cout<<endl; RecursiveInsertionSort(arr,n);//sort for(int i:arr) cout<<i<<"\t"; return 0; }
20.25
48
0.531814
R-Arpita
e89006d234203553f289f27916ffa47e482210a0
2,429
hpp
C++
extension/parquet/include/decimal_column_reader.hpp
wesm/duckdb
f2fa094abc59d70a8c981d6e9f9c9c3911f08362
[ "MIT" ]
3
2021-05-13T04:15:45.000Z
2022-03-03T16:57:16.000Z
extension/parquet/include/decimal_column_reader.hpp
wesm/duckdb
f2fa094abc59d70a8c981d6e9f9c9c3911f08362
[ "MIT" ]
2
2021-10-02T02:52:39.000Z
2022-01-04T20:08:06.000Z
extension/parquet/include/decimal_column_reader.hpp
wesm/duckdb
f2fa094abc59d70a8c981d6e9f9c9c3911f08362
[ "MIT" ]
1
2021-11-20T16:09:34.000Z
2021-11-20T16:09:34.000Z
//===----------------------------------------------------------------------===// // DuckDB // // decimal_column_reader.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "column_reader.hpp" #include "templated_column_reader.hpp" namespace duckdb { template <class DUCKDB_PHYSICAL_TYPE> struct DecimalParquetValueConversion { static DUCKDB_PHYSICAL_TYPE DictRead(ByteBuffer &dict, uint32_t &offset, ColumnReader &reader) { auto dict_ptr = (DUCKDB_PHYSICAL_TYPE *)dict.ptr; return dict_ptr[offset]; } static DUCKDB_PHYSICAL_TYPE PlainRead(ByteBuffer &plain_data, ColumnReader &reader) { DUCKDB_PHYSICAL_TYPE res = 0; auto byte_len = (idx_t)reader.Schema().type_length; /* sure, type length needs to be a signed int */ D_ASSERT(byte_len <= sizeof(DUCKDB_PHYSICAL_TYPE)); plain_data.available(byte_len); auto res_ptr = (uint8_t *)&res; // numbers are stored as two's complement so some muckery is required bool positive = (*plain_data.ptr & 0x80) == 0; for (idx_t i = 0; i < byte_len; i++) { auto byte = *(plain_data.ptr + (byte_len - i - 1)); res_ptr[i] = positive ? byte : byte ^ 0xFF; } plain_data.inc(byte_len); if (!positive) { res += 1; return -res; } return res; } static void PlainSkip(ByteBuffer &plain_data, ColumnReader &reader) { plain_data.inc(reader.Schema().type_length); } }; template <class DUCKDB_PHYSICAL_TYPE> class DecimalColumnReader : public TemplatedColumnReader<DUCKDB_PHYSICAL_TYPE, DecimalParquetValueConversion<DUCKDB_PHYSICAL_TYPE>> { public: DecimalColumnReader(ParquetReader &reader, LogicalType type_p, const SchemaElement &schema_p, idx_t file_idx_p, idx_t max_define_p, idx_t max_repeat_p) : TemplatedColumnReader<DUCKDB_PHYSICAL_TYPE, DecimalParquetValueConversion<DUCKDB_PHYSICAL_TYPE>>( reader, move(type_p), schema_p, file_idx_p, max_define_p, max_repeat_p) {}; protected: void Dictionary(shared_ptr<ByteBuffer> dictionary_data, idx_t num_entries) { this->dict = make_shared<ResizeableBuffer>(this->reader.allocator, num_entries * sizeof(DUCKDB_PHYSICAL_TYPE)); auto dict_ptr = (DUCKDB_PHYSICAL_TYPE *)this->dict->ptr; for (idx_t i = 0; i < num_entries; i++) { dict_ptr[i] = DecimalParquetValueConversion<DUCKDB_PHYSICAL_TYPE>::PlainRead(*dictionary_data, *this); } } }; } // namespace duckdb
34.7
113
0.682174
wesm
e8917ddf10b22d3cae43fa102568dafcbb88b447
9,874
cpp
C++
src/hsp3/linux/hsp3ext_sock.cpp
m4saka/OpenHSP
391f0a2100e701138d0610a5b94492d6f57ad1f2
[ "BSD-3-Clause" ]
127
2018-02-24T20:41:15.000Z
2022-03-22T05:57:56.000Z
src/hsp3/linux/hsp3ext_sock.cpp
m4saka/OpenHSP
391f0a2100e701138d0610a5b94492d6f57ad1f2
[ "BSD-3-Clause" ]
21
2018-09-11T15:04:22.000Z
2022-02-03T09:30:16.000Z
src/hsp3/linux/hsp3ext_sock.cpp
m4saka/OpenHSP
391f0a2100e701138d0610a5b94492d6f57ad1f2
[ "BSD-3-Clause" ]
21
2019-03-28T07:49:44.000Z
2021-12-25T02:49:07.000Z
// // hsp3dish socket拡張(linux) // (拡張コマンド・関数処理) // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <poll.h> #include "../hsp3config.h" #include "../hsp3code.h" #include "../hsp3debug.h" #include "../supio.h" #include "../strbuf.h" #ifndef MAX #define MAX(a, b) ((a) > (b) ? (a) : (b)) #endif /*------------------------------------------------------------*/ /* system data */ /*------------------------------------------------------------*/ static HSPCTX *ctx; // Current Context static HSPEXINFO *exinfo; static int *type; static int *val; static int *exflg; static int p1,p2,p3,p4,p5; /*----------------------------------------------------------*/ // TCP/IP support /*----------------------------------------------------------*/ #include <errno.h> #include <fcntl.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> static int sockprep(); static int sockclose(int); static int sockget(char*, int, int); static int sockgetm(char*, int, int, int); static int sockreadbyte(); #define SOCKMAX 32 static int sockf=0; static int soc[SOCKMAX]; /* Soket Descriptor */ static int socsv[SOCKMAX]; static int svstat[SOCKMAX]; /* Soket Thread Status (server) */ static int sockprep( void ){ sockf++; for(int a = 0; a < SOCKMAX; a++){ soc[a] = -1; socsv[a] = -1; svstat[a] = 0; } return 0; } static int sockopen( int p1, char *p2, int p3){ struct sockaddr_in addr; if(sockf == 0){ if(sockprep()) return -1;; } soc[p1] = socket(AF_INET, SOCK_STREAM, 0); if(soc[p1]<0){ return -2; } addr.sin_family = AF_INET; addr.sin_addr.s_addr=inet_addr(p2); addr.sin_port=htons(p3); if(connect(soc[p1], (struct sockaddr*)&addr, sizeof(addr)) < 0){ return -4; } return 0; } static int sockclose(int p1){ if(socsv[p1]!=-1) close(socsv[p1]); if(soc[p1]!=-1) close(soc[p1]); soc[p1]=-1;socsv[p1]=-1;svstat[p1]=0; return 0; } static int sockget(char* buf, int size, int socid){ return sockgetm(buf, size, socid, 0); } static int sockgetm(char* buf, int size, int socid, int flag){ int recv_len; memset(buf, 0, sizeof(buf)); recv_len = recv(soc[socid], buf, size, flag); if(recv_len == -1) return errno; return 0; } static int sockgetc(int* buf, int socid){ int recv_len; char recv; recv_len = read(soc[socid], &recv, 1); if(recv_len < 0) return errno; buf[0] = (int)recv; return 0; } static int sockgetbm( char *org_buf, int offset, int size, int socid, int flag){ int buf_len; char* buf; buf = org_buf + offset; if(size == 0) size = 64; buf_len = recv(soc[socid], buf, size, flag); if(buf_len == -1) return errno; return -(buf_len); } static int sockgetb( char *org_buf, int offset, int size, int socid){ return sockgetbm(org_buf, offset, size, socid, 0); } static int sockputm(char* buf, int socid, int flag){ if(send(soc[socid], buf, strlen(buf), flag) == -1){ // FIXME: is `strlen(buf)` must be like `lstrlen()` in windows? return errno; } return 0; } static int sockput(char* buf, int socid){ return sockputm(buf, socid, 0); } static int sockputc(int c, int socid){ char buf[2]; buf[0] = (char)c; buf[1] = '\0'; if(send(soc[p3], buf, 1, 0) == -1){ return errno; } return 0; } static int sockputb(char* org_buf, int offset, int size, int socid){ char *buf; int buf_len; buf = org_buf + offset; if(size == 0) size = 64; buf_len = send(soc[socid], buf, size, 0); if(buf_len == -1) return 0; return -(buf_len); } static int sockmake(int socid, int port){ if(sockf == 0){ if(sockprep()) return -1; } if(socsv[socid] == -1){ struct sockaddr_in addr; int len = sizeof(struct sockaddr_in); socsv[socid] = socket(AF_INET, SOCK_STREAM, 0); if(socsv[socid] < 0){ return -2; } bzero((char *)&addr, sizeof(addr)); addr.sin_family = PF_INET; addr.sin_addr.s_addr = INADDR_ANY; addr.sin_port = htons(port); if(bind(socsv[socid], (struct sockaddr *)&addr, len) < 0){ return -3; } }else{ } svstat[socid] = 1; if(listen(socsv[socid], SOMAXCONN) < 0){ svstat[socid] = 0; }else{ svstat[socid]++; } return 0; } static int sockwait(int socid){ static int maxfd = 0; int err; fd_set fdsetread, fdsetwrite, fdseterror; struct timeval TimeVal={0,10000}; int soc2; struct sockaddr_in from; if(socsv[socid] == -1) return -2; if(svstat[socid] == -1) return -4; if(svstat[socid] != 2) return -3; FD_ZERO(&fdsetread); FD_ZERO(&fdsetwrite); FD_ZERO(&fdseterror); FD_SET(socsv[socid], &fdsetread); maxfd = MAX(maxfd, socsv[socid]); if((err = select(maxfd+1, &fdsetread, &fdsetwrite, &fdseterror, &TimeVal))==0){ if(err == -1) return -4; return -1; } svstat[socid] = 0; unsigned int len = sizeof(from); memset(&from, 0, len); soc2 = accept(socsv[socid], (struct sockaddr *)&from, &len); if(soc2 == -1){ close(socsv[socid]); socsv[socid] = -1; return -5; } soc[socid] = soc2; close(socsv[socid]); socsv[socid] = -1; char s1[128]; char s2[128]; sprintf(s1, "%s:%d", inet_ntoa(from.sin_addr), ntohs(from.sin_port)); return 0; } static int sockreadbyte(){ // No arguments // Return read byte int buf_len; char buf[1]; memset(buf, 0, sizeof(buf)); buf_len = read(soc[p2], buf, sizeof(buf)); if(buf_len < 0){ return -2; } if(buf_len == 0){ return -1; } return (int)buf[0]; } /*------------------------------------------------------------*/ /* interface */ /*------------------------------------------------------------*/ static int cmdfunc_extcmd( int cmd ) { // cmdfunc : TYPE_EXTCMD // (内蔵GUIコマンド) // code_next(); // 次のコードを取得(最初に必ず必要です) switch( cmd ) { // サブコマンドごとの分岐 // command part // case 0x60: //sockopen { char *address; int p_res; p1 = code_getdi( 0 ); address = code_stmpstr( code_gets() ); p3 = code_getdi( 0 ); p_res = sockopen(p1, address, p3); ctx->stat = p_res; break; } case 0x61: //sockclose { char *cname; int p_res; p1 = code_geti(); p_res = sockclose(p1); ctx->stat = p_res; break; } case 0x62: //sockreadbyte { char *cname; int p_res; p_res = sockreadbyte(); if(p_res > 0){ printf("%c\n", p_res); } ctx->stat = p_res; break; } case 0x63: //sockget { PVal *pval; char *ptr; int size; ptr = code_getvptr( &pval, &size ); p2 = code_getdi( 0 ); p3 = code_getdi( 0 ); int p_res; p_res = sockget(pval->pt, p2, p3); ctx->stat = p_res; break; } case 0x64: //sockgetc { } case 0x65: //sockgetm { PVal *pval; char *ptr; int size; ptr = code_getvptr( &pval, &size ); p2 = code_getdi( 0 ); p3 = code_getdi( 0 ); p4 = code_getdi( 0 ); int p_res; p_res = sockgetm(pval->pt, p2, p3, p4); ctx->stat = p_res; break; } case 0x66: //sockgetb { PVal *pval; char *ptr; int size; ptr = code_getvptr(&pval, &size); p2 = code_getdi( 0 ); p3 = code_getdi( 0 ); p4 = code_getdi( 0 ); int p_res; p_res = sockgetb(pval->pt, p2, p3, p4); ctx->stat = p_res; break; } case 0x67: //sockgetbm { PVal *pval; char *ptr; int size; ptr = code_getvptr(&pval, &size); p2 = code_getdi( 0 ); p3 = code_getdi( 0 ); p4 = code_getdi( 0 ); p5 = code_getdi( 0 ); int p_res; p_res = sockgetbm(pval->pt, p2, p3, p4, p5); ctx->stat = p_res; break; } case 0x68: // sockput { PVal *pval; char *ptr; int size; ptr = code_getvptr(&pval, &size); p2 = code_getdi( 0 ); int p_res; p_res = sockput(pval->pt, p2); ctx->stat = p_res; break; } case 0x69: // sockputc { PVal *pval; char *ptr; int size; p1 = code_getdi( 0 ); p2 = code_getdi( 0 ); int p_res; p_res = sockputc(p1, p2); ctx->stat = p_res; break; } case 0x6a: // sockputb { PVal *pval; char *ptr; int size; ptr = code_getvptr(&pval, &size); p2 = code_getdi( 0 ); p3 = code_getdi( 0 ); p4 = code_getdi( 0 ); int p_res; p_res = sockputb(ptr, p2, p3, p4); ctx->stat = p_res; break; } case 0x6b: // sockmake { p1 = code_getd(); p2 = code_getd(); int p_res = sockmake(p1, p2); ctx->stat = p_res; break; } case 0x6c: // sockwait { p1 = code_getd(); int p_res = sockwait(p1); ctx->stat = p_res; break; } default: throw HSPERR_UNSUPPORTED_FUNCTION; } return RUNMODE_RUN; } #if 0 static int reffunc_intfunc_ivalue; static void *reffunc_function( int *type_res, int arg ) { void *ptr; // 返値のタイプを設定する // *type_res = HSPVAR_FLAG_INT; // 返値のタイプを指定する ptr = &reffunc_intfunc_ivalue; // 返値のポインタ // '('で始まるかを調べる // if ( *type != TYPE_MARK ) throw HSPERR_INVALID_FUNCPARAM; if ( *val != '(' ) throw HSPERR_INVALID_FUNCPARAM; code_next(); switch( arg & 0xff ) { // int function default: throw HSPERR_UNSUPPORTED_FUNCTION; } // '('で終わるかを調べる // if ( *type != TYPE_MARK ) throw HSPERR_INVALID_FUNCPARAM; if ( *val != ')' ) throw HSPERR_INVALID_FUNCPARAM; code_next(); return ptr; } #endif static int termfunc_extcmd( int option ) { // termfunc : TYPE_EXTCMD // return 0; } void hsp3typeinit_sock_extcmd( HSP3TYPEINFO *info ) { ctx = info->hspctx; exinfo = info->hspexinfo; type = exinfo->nptype; val = exinfo->npval; // function register // info->cmdfunc = cmdfunc_extcmd; info->termfunc = termfunc_extcmd; // Application initalize // } void hsp3typeinit_sock_extfunc( HSP3TYPEINFO *info ) { }
19.987854
119
0.564209
m4saka
e89182d494b33c7ad6e7e41e11da35bf854810e0
3,659
cpp
C++
src/Cpp/Learning_Cpp/Course_Codes/The_LinkedIn_Course/Advanced_Cpp/Chap08/utest.cpp
Ahmopasa/TheCodes
560ed94190fd0da8cc12285e9b4b5e27b19010a5
[ "MIT" ]
null
null
null
src/Cpp/Learning_Cpp/Course_Codes/The_LinkedIn_Course/Advanced_Cpp/Chap08/utest.cpp
Ahmopasa/TheCodes
560ed94190fd0da8cc12285e9b4b5e27b19010a5
[ "MIT" ]
null
null
null
src/Cpp/Learning_Cpp/Course_Codes/The_LinkedIn_Course/Advanced_Cpp/Chap08/utest.cpp
Ahmopasa/TheCodes
560ed94190fd0da8cc12285e9b4b5e27b19010a5
[ "MIT" ]
null
null
null
// utest.cpp by Bill Weinman <http://bw.org/> // version of 2018-10-12 #include <cstdio> #include "BWUTest.h" #include "BWString.h" bool summary_flag = false; int main() { // Versions n things printf("BWString version: %s\n", BWString::version()); printf("BWUTest version: %s\n", BWUTest::version()); BWUTest u("BWLib"); u.summary(summary_flag); // BWString printf("\nTesting BWString -----\n"); u.init("BWString"); // test constructors const char * _ctest = " \tfoo \r\n"; BWString ttest = _ctest; u.test("cstring ctor", ttest.length() == 12); puts(ttest); BWString other = std::move(ttest); u.test("move ctor", other.length() == 12 && ttest.length() == 0); ttest = std::move(other); // assignment operators u.test("move assignment", other.length() == 0 && ttest.length() == 12); other = ttest; u.test("copy assignment", other.length() == 12 && ttest.length() == 12); // concat operators BWString x = "foo"; BWString y = "bar"; x += y; u.test("concat +=", x.length() == 6 && memcmp(x.c_str(), "foobar", 7) == 0); BWString z; z = x + "baz"; u.test("concat +", z.length() == 9 && memcmp(z.c_str(), "foobarbaz", 10) == 0); z = "baz" + x; u.test("concat +", z.length() == 9 && memcmp(z.c_str(), "bazfoobar", 10) == 0); // comparison operators x = y = "foo"; u.test("foo == foo", (x == y)); u.test("foo > foo", !(x > y)); u.test("foo >= foo", (x >= y)); u.test("foo < foo", !(x < y)); u.test("foo <= foo", (x <= y)); x = "bar"; u.test("bar == foo", !(x == y)); u.test("bar > foo", !(x > y)); u.test("bar >= foo", !(x >= y)); u.test("bar < foo", (x < y)); u.test("bar <= foo", (x <= y)); u.test("foo == bar", !(y == x)); u.test("foo > bar", (y > x)); u.test("foo >= bar", (y >= x)); u.test("foo < bar", !(y < x)); u.test("foo <= bar", !(y <= x)); // subscript u.test("subscript x[0]", x[0] == 'b'); u.test("subscript x[1]", x[1] == 'a'); u.test("subscript x[2]", x[2] == 'r'); u.test("subscript terminator x[3]", x[3] == 0); ttest.trim(); u.test("trim", ttest.length() == 3); ttest = "this is a string"; u.test("length is 16", ttest.length() == 16 && ttest.size() == 16); u.test("substr", ttest.substr(10, 3) == BWString("str")); u.test("charfind", ttest.char_find('s') == 3); u.test("charfind (not found)", ttest.char_find('z') == -1); BWString string_upper = ttest.upper(); BWString string_lower = string_upper.lower(); u.test("upper and lower", string_upper == BWString("THIS IS A STRING") && string_lower == BWString("this is a string")); x = "this is a big string ###foobarbaz### this is a big string"; x = x.replace("###foobarbaz###", "foo bar baz"); u.test("replace", x.length() == 53 && memcmp(x.c_str(), "this is a big string foo bar baz this is a big string", 54) == 0); x = "line one/line two/line three"; auto & r = x.split('/'); u.test("split_count is 3", x.split_count() == 3); u.test("split result 1", memcmp(r[0]->c_str(), "line one", 8) == 0); u.test("split result 2", memcmp(r[1]->c_str(), "line two", 8) == 0); u.test("split result 3", memcmp(r[2]->c_str(), "line three", 10) == 0); u.test("split test end", !r[3]); u.test("format test", memcmp(x.format("format test %d", 42).c_str(), "format test 42", 14) == 0); // report results puts(""); u.report(); return 0; // Done. Yay! }
32.380531
127
0.511342
Ahmopasa
e894d7d03541b708cb0fe7267e520b4737ece4db
13,991
cpp
C++
native-imagetranscoder/src/main/jni/native-imagetranscoder/jpeg/crypto/jpeg_crypto.cpp
columbia/fresco
efd379d38db321fd5deddd48805247890ec076f5
[ "MIT" ]
null
null
null
native-imagetranscoder/src/main/jni/native-imagetranscoder/jpeg/crypto/jpeg_crypto.cpp
columbia/fresco
efd379d38db321fd5deddd48805247890ec076f5
[ "MIT" ]
null
null
null
native-imagetranscoder/src/main/jni/native-imagetranscoder/jpeg/crypto/jpeg_crypto.cpp
columbia/fresco
efd379d38db321fd5deddd48805247890ec076f5
[ "MIT" ]
null
null
null
#include <algorithm> #include <iterator> #include <stdio.h> #include <setjmp.h> #include <jni.h> #include <jpeglib.h> extern "C" { #include "transupp.h" } #include <gmp.h> #include <math.h> #include <bitset> #include "decoded_image.h" #include "exceptions_handler.h" #include "logging.h" #include "jpeg/jpeg_error_handler.h" #include "jpeg/jpeg_memory_io.h" #include "jpeg/jpeg_stream_wrappers.h" #include "jpeg/jpeg_codec.h" #include "jpeg_crypto.h" #include "sha512.h" #include "rand.h" namespace facebook { namespace imagepipeline { namespace jpeg { namespace crypto { bool chaos_sorter(struct chaos_dc left, struct chaos_dc right) { if (left.chaos == right.chaos) { return left.chaos_pos < right.chaos_pos; } return left.chaos < right.chaos; } bool chaos_gmp_sorter(struct chaos_dc left, struct chaos_dc right) { int cmp_result = mpf_cmp(left.chaos_gmp, right.chaos_gmp); if (cmp_result == 0) { return left.chaos_pos < right.chaos_pos; } return cmp_result < 0; } bool chaos_pos_sorter(struct chaos_dc left, struct chaos_dc right) { return left.chaos_pos < right.chaos_pos; } /* * x_0 and mu are the secret values. * n is the length of chaotic_seq. */ void generateChaoticSequence( struct chaos_dc *chaotic_seq, int n, float x_0, float mu) { chaotic_seq[0].chaos = mu * x_0 * (1 - x_0); chaotic_seq[0].chaos_pos = 0; LOGD("generateChaoticSequence chaotic_seq[0].chaos: %f", chaotic_seq[0].chaos); for (int i = 1; i < n; i++) { float x_n = chaotic_seq[i - 1].chaos; chaotic_seq[i].chaos = mu * x_n * (1 - x_n); chaotic_seq[i].chaos_pos = i; //LOGD("Generated chaotic_seq value: %f", chaotic_seq[i]); } // Order the sequence in ascending order based on the chaotic value // Each value's original position is maintained via the chaotic_pos member std::sort(chaotic_seq, chaotic_seq + n, &chaos_sorter); } static void next_logistic_map_val(mpf_t output, mpf_t x_n, mpf_t mu) { mpf_t subtraction_part; mpf_t multiplication_part; mpf_init(subtraction_part); mpf_init(multiplication_part); mpf_ui_sub(subtraction_part, 1, x_n); mpf_mul(multiplication_part, mu, x_n); //Performs: output = mu * x_n * (1 - x_n); mpf_mul(output, multiplication_part, subtraction_part); mpf_clears(subtraction_part, multiplication_part, NULL); } static bool should_flip_sign(mpf_t chaos_gmp) { mp_exp_t exponent; char *mpf_val; std::string chaos_hash_str; int set_bit_count = 0; mpf_val = mpf_get_str(NULL, &exponent, 10, 500, chaos_gmp); chaos_hash_str = sw::sha512::calculate(mpf_val); for (int i = 0; i < 32; i++) { set_bit_count += std::bitset<8>(chaos_hash_str[i]).count(); } free(mpf_val); return set_bit_count % 2; } static void generate_sign_flips(mpf_t x_0, mpf_t mu, bool *sign_flips, int n) { mp_exp_t exponent; char *mpf_val_x_0; char *mpf_val_mu; std::string concat_hashes; int char_count = 0; mpf_val_x_0 = mpf_get_str(NULL, &exponent, 10, 500, x_0); mpf_val_mu = mpf_get_str(NULL, &exponent, 10, 500, mu); concat_hashes.append(sw::sha512::calculate(mpf_val_x_0)); concat_hashes.append(sw::sha512::calculate(mpf_val_mu)); char_count = concat_hashes.size(); free(mpf_val_x_0); free(mpf_val_mu); while (concat_hashes.size() < n) { concat_hashes.append(sw::sha512::calculate(concat_hashes)); } for (int i = 0; i < n; i++) { sign_flips[i] = std::bitset<8>(concat_hashes[i]).count() % 2; } } void gen_chaotic_sequence( struct chaos_dc *chaotic_seq, int n, mpf_t x_0, mpf_t mu, bool sort) { bool *sign_flips; sign_flips = (bool *) malloc(n * sizeof(bool)); if (sign_flips == NULL) { LOGE("gen_chaotic_sequence failed to allocate sign_flips"); return; } generate_sign_flips(x_0, mu, sign_flips, n); mpf_init(chaotic_seq[0].chaos_gmp); // chaotic_seq[0].chaos_gmp = mu * x_0 * (1 - x_0); next_logistic_map_val(chaotic_seq[0].chaos_gmp, x_0, mu); chaotic_seq[0].chaos_pos = 0; chaotic_seq[0].flip_sign = sign_flips[0]; for (int i = 1; i < n; i++) { // x_n = chaotic_seq[i - 1].chaos_gmp mpf_init(chaotic_seq[i].chaos_gmp); next_logistic_map_val(chaotic_seq[i].chaos_gmp, chaotic_seq[i - 1].chaos_gmp, mu); chaotic_seq[i].chaos_pos = i; chaotic_seq[i].flip_sign = sign_flips[i]; } // Order the sequence in ascending order based on the chaotic value // Each value's original position is maintained via the chaotic_pos member if (sort) std::sort(chaotic_seq, chaotic_seq + n, &chaos_gmp_sorter); free(sign_flips); } void gen_chaotic_sequence( struct chaos_dc *chaotic_seq, int n, mpf_t x_0, mpf_t mu) { gen_chaotic_sequence(chaotic_seq, n, x_0, mu, true); } static void populate_row(struct chaos_dc *chaotic_seq_row, int y, int width, float prev_row_last_val, float mu) { for (int j = 0; j < width; j++) { float x_n; if (y == 0 && j == 0) continue; if (j == 0) x_n = prev_row_last_val; else x_n = chaotic_seq_row[j - 1].chaos; chaotic_seq_row[j].chaos = mu * x_n * (1 - x_n); chaotic_seq_row[j].chaos_pos = j; } } void gen_chaotic_per_row( struct chaos_dc *chaotic_seq, int width, int height, float x_0, float mu) { float prev_val = 0.0; chaotic_seq[0].chaos = mu * x_0 * (1 - x_0); chaotic_seq[0].chaos_pos = 0; for (int y = 0; y < height; y++) { populate_row(&chaotic_seq[y * width], y, width, prev_val, mu); prev_val = chaotic_seq[y * width + width - 1].chaos; // Order the sequence in ascending order based on the chaotic value // Each value's original position is maintained via the chaotic_pos member std::sort(&chaotic_seq[y * width], &chaotic_seq[y * width] + width, &chaos_sorter); } } static void populate_row(struct chaos_dc *chaotic_seq_row, int y, int width, mpf_t prev_row_last_val, mpf_t mu) { for (int j = 0; j < width; j++) { if (y == 0 && j == 0) continue; mpf_init(chaotic_seq_row[j].chaos_gmp); //chaotic_seq_row[j].chaos = mu * x_n * (1 - x_n); if (j == 0) next_logistic_map_val(chaotic_seq_row[j].chaos_gmp, prev_row_last_val, mu); else next_logistic_map_val(chaotic_seq_row[j].chaos_gmp, chaotic_seq_row[j - 1].chaos_gmp, mu); chaotic_seq_row[j].chaos_pos = j; } } void gen_chaotic_per_row( struct chaos_dc *chaotic_seq, int width, int height, mpf_t x_0, mpf_t mu) { mpf_t prev_val; mpf_init(prev_val); mpf_init(chaotic_seq[0].chaos_gmp); //Performs: chaotic_seq[0].chaos_gmp = mu * x_0 * (1 - x_0); next_logistic_map_val(chaotic_seq[0].chaos_gmp, x_0, mu); chaotic_seq[0].chaos_pos = 0; for (int y = 0; y < height; y++) { populate_row(&chaotic_seq[y * width], y, width, prev_val, mu); mpf_set(prev_val, chaotic_seq[y * width + width - 1].chaos_gmp); // Order the sequence in ascending order based on the chaotic value // Each value's original position is maintained via the chaotic_pos member std::sort(&chaotic_seq[y * width], &chaotic_seq[y * width] + width, &chaos_gmp_sorter); } mpf_clear(prev_val); } void diffuseACs( j_decompress_ptr dinfo, jvirt_barray_ptr* src_coefs, mpf_t x_0, mpf_t mu, mpf_t alpha, mpf_t beta, bool encrypt) { mpf_t dc_coeff; mpf_t alpha_part; mpf_t dc_alpha_part; mpf_t beta_part; mpf_t xor_component_mpf; mpf_inits(dc_coeff, alpha_part, dc_alpha_part, beta_part, xor_component_mpf, NULL); LOGD("diffuseACs alpha=%lf, beta=%lf", mpf_get_d(alpha), mpf_get_d(beta)); for (int comp_i = 0; comp_i < dinfo->num_components; comp_i++) { jpeg_component_info *comp_info = dinfo->comp_info + comp_i; unsigned int width = comp_info->width_in_blocks; unsigned int height = comp_info->height_in_blocks; unsigned int ith_mcu = 0; mpf_t last_xn; struct chaos_dc *chaotic_seq; unsigned int n_coefficients = comp_info->width_in_blocks * DCTSIZE2; chaotic_seq = (struct chaos_dc *) malloc(n_coefficients * sizeof(struct chaos_dc)); if (chaotic_seq == NULL) { LOGE("diffuseACs failed to alloc memory for chaotic_seq"); return; } mpf_init(last_xn); LOGD("diffuseACs iterating over image component %d (comp_info->height_in_blocks=%d)", comp_i, comp_info->height_in_blocks); for (int y = 0; y < comp_info->height_in_blocks; y++) { JBLOCKARRAY mcu_buff; // Pointer to list of horizontal 8x8 blocks if (ith_mcu) gen_chaotic_sequence(chaotic_seq, n_coefficients, last_xn, mu, false); else gen_chaotic_sequence(chaotic_seq, n_coefficients, x_0, mu, false); // mcu_buff[y][x][c] // - the cth coefficient // - the xth horizontal block // - the yth vertical block mcu_buff = (dinfo->mem->access_virt_barray)((j_common_ptr)dinfo, src_coefs[comp_i], y, (JDIMENSION) 1, TRUE); for (int x = 0; x < comp_info->width_in_blocks; x++) { JCOEFPTR mcu_ptr; // Pointer to 8x8 block of coefficients (I think) mcu_ptr = mcu_buff[0][x]; for (int i = 1; i < DCTSIZE2; i++) { JCOEF xor_component; JCOEF new_ac_coeff; int mod_amt = 100; if (mcu_ptr[i] == 0) continue; // DC * alpha * chaos[i-1] + beta * chaos[i-1] mpf_set_d(dc_coeff, mcu_ptr[0]); mpf_mul(alpha_part, alpha, chaotic_seq[(i - 1) * x].chaos_gmp); // The two multiplied parts mpf_mul(dc_alpha_part, dc_coeff, alpha_part); mpf_mul(beta_part, beta, chaotic_seq[(i - 1) * x].chaos_gmp); mpf_add(xor_component_mpf, dc_alpha_part, beta_part); xor_component = mpf_get_d(xor_component_mpf); new_ac_coeff = mcu_ptr[i] ^ (xor_component % mod_amt); mcu_ptr[i] = new_ac_coeff; } ith_mcu++; } mpf_set(last_xn, chaotic_seq[n_coefficients - 1].chaos_gmp); for (int i; i < n_coefficients; i++) { mpf_clear(chaotic_seq[i].chaos_gmp); } } free(chaotic_seq); mpf_clear(last_xn); } mpf_clears(dc_coeff, alpha_part, dc_alpha_part, beta_part, xor_component_mpf, NULL); } void diffuseACsFlipSigns( j_decompress_ptr dinfo, jvirt_barray_ptr* src_coefs, mpf_t x_0, mpf_t mu, mpf_t alpha, mpf_t beta) { char *mpf_val_x_0; char *mpf_val_mu; mp_exp_t exponent; std::string concat_hashes; unsigned int isaac_i = 0; mpf_val_x_0 = mpf_get_str(NULL, &exponent, 10, 500, x_0); mpf_val_mu = mpf_get_str(NULL, &exponent, 10, 500, mu); LOGD("diffuseACsFlipSigns x_0=%s, mu=%s", mpf_val_x_0, mpf_val_mu); // 256 bytes concat_hashes.append(sw::sha512::calculate(mpf_val_x_0)); concat_hashes.append(sw::sha512::calculate(mpf_val_mu)); concat_hashes.append(sw::sha512::calculate(concat_hashes)); concat_hashes.append(sw::sha512::calculate(concat_hashes)); free(mpf_val_x_0); free(mpf_val_mu); LOGD("diffuseACsFlipSigns alpha=%lf, beta=%lf", mpf_get_d(alpha), mpf_get_d(beta)); for (int comp_i = 0; comp_i < dinfo->num_components; comp_i++) { jpeg_component_info *comp_info = dinfo->comp_info + comp_i; unsigned int width = comp_info->width_in_blocks; unsigned int height = comp_info->height_in_blocks; unsigned int n_coefficients = comp_info->width_in_blocks * DCTSIZE2; unsigned int non_zero_ac_count = 0; unsigned int ac_flips = 0; randctx ctx; // Initialize ISAAC seed ctx.randa = ctx.randb = ctx.randc = (ub4) 0; for (int i = 0; i < RANDSIZ; i++) { ctx.randrsl[i] = concat_hashes[i]; } randinit(&ctx, 1); LOGD("diffuseACsFlipSigns iterating over image component %d (comp_info->height_in_blocks=%d)", comp_i, comp_info->height_in_blocks); for (int y = 0; y < comp_info->height_in_blocks; y++) { JBLOCKARRAY mcu_buff; // Pointer to list of horizontal 8x8 blocks // mcu_buff[y][x][c] // - the cth coefficient // - the xth horizontal block // - the yth vertical block mcu_buff = (dinfo->mem->access_virt_barray)((j_common_ptr)dinfo, src_coefs[comp_i], y, (JDIMENSION) 1, TRUE); for (int x = 0; x < comp_info->width_in_blocks; x++) { JCOEFPTR mcu_ptr; // Pointer to 8x8 block of coefficients (I think) mcu_ptr = mcu_buff[0][x]; if (isaac_i % 2048 == 0) { isaac(&ctx); } for (int i = 1; i < DCTSIZE2; i++) { isaac_i++; if (mcu_ptr[i] == 0) continue; //LOGD("diffuseACsFlipSigns %d / %d", isaac_i % 256, isaac_i % 8); if (std::bitset<8>(ctx.randrsl[isaac_i % 256]).test(isaac_i % 8)) { mcu_ptr[i] *= -1; ac_flips++; } non_zero_ac_count++; } } } LOGD("diffuseACsFlipSigns non_zero_ac_count=%u, ac_flips=%u", non_zero_ac_count, ac_flips); } } int round_up_to_multiple(int input, int multiple) { int remainder = input % multiple; if (remainder == 0) return input; return input + multiple - remainder; } float scaleToRange(float input, float input_min, float input_max, float scale_min, float scale_max) { return (scale_max - scale_min) * (input - input_min) / (input_max - input_min) + scale_min; } void construct_alpha_beta(mpf_t output, const char *input, int input_len) { char *output_str; int preset_parts_len = 5; int total_len = preset_parts_len + input_len + 1; output_str = (char *) malloc(total_len * sizeof(char)); if (output_str == NULL) { LOGE("construct_alpha_beta() Failed to allocate output_str"); return; } output_str[total_len - 1] = '\0'; output_str[0] = '3'; output_str[1] = '.'; output_str[2] = '9'; output_str[total_len - 3] = 'e'; output_str[total_len - 2] = '0'; strncpy(&output_str[3], input, input_len); LOGD("construct_alpha_beta %s", output_str); mpf_set_str(output, output_str, 10); free(output_str); } int sameSign(JCOEF a, JCOEF b) { return (a < 0 && b < 0) || (a >= 0 && b >= 0); } } } } }
28.094378
136
0.663284
columbia
e895bb0296dc619d715846cda4f48ffdd67f0594
3,427
cpp
C++
Hydrogen Framework/src/HFR/text/Font.cpp
salmoncatt/HGE
8ae471de46589df54cacd1bd0261989633f1e5ef
[ "BSD-3-Clause" ]
2
2020-11-12T14:42:56.000Z
2021-01-27T18:04:42.000Z
Hydrogen Framework/src/HFR/text/Font.cpp
salmoncatt/Hydrogen-Game-Engine
8ae471de46589df54cacd1bd0261989633f1e5ef
[ "BSD-3-Clause" ]
1
2021-01-27T17:39:21.000Z
2021-01-28T01:42:36.000Z
Hydrogen Framework/src/HFR/text/Font.cpp
salmoncatt/Hydrogen-Game-Engine
8ae471de46589df54cacd1bd0261989633f1e5ef
[ "BSD-3-Clause" ]
null
null
null
#include "hfpch.h" #include "Font.h" #include HFR_FREETYPE #include HFR_UTIL namespace HFR { Font::Font() { size = Vec2f(0, 48); atlasSize = Vec2f(); } Font::Font(const std::string& _path) { size = Vec2f(0, 48); atlasSize = Vec2f(); path = _path; name = Util::removePathFromFilePathAndName(_path); } Font::~Font() { } void Font::create() { FT_Face face = FreeType::loadFace(path); FT_Set_Pixel_Sizes(face, 0, size.y); FT_GlyphSlot glyph = face->glyph; float width = 0; float height = 0; float rowWidth = 0; float rowHeight = 0; for (int i = 0; i < 128; ++i) { //super sophisticated error checking algorithm if (FT_Load_Char(face, i, FT_LOAD_RENDER)) { std::string character; character = (char)(i); std::string error = ("Loading character " + character + " has failed in font: " + name); Debug::systemErr(error); continue; } if (rowWidth + glyph->bitmap.width + 1 >= (unsigned int)maxTextureWidth) { width = max(width, rowWidth); height += rowHeight; rowWidth = 0; rowHeight = 0; } rowWidth += glyph->bitmap.width + 1; rowHeight = max(height, glyph->bitmap.rows); } width = max(width, rowWidth); height += rowHeight; atlasSize = Vec2f(width, height); rowHeight = 0; Vec2i offset = Vec2i(); unsigned char* blankColor = new unsigned char[width * height]; for (int i = 0; i < (width * height); ++i) { blankColor[i] = 0x0; } Image imageData = Image(width, height, 1, blankColor); texture = Texture(imageData); texture.byteAlignment = 1; texture.filterMode = Vec2i(GL_LINEAR); texture.internalFormat = GL_RED; texture.format = GL_RED; texture.generateMipmap = false; texture.wrapMode = Vec2i(GL_CLAMP_TO_EDGE); texture.create(); for (int i = 0; i < 128; ++i) { //super sophisticated error checking algorithm if (FT_Load_Char(face, i, FT_LOAD_RENDER)) { std::string character; character = (char)(i); std::string error = ("Loading character " + character + " has failed in font: " + Util::removePathFromFilePathAndName(path)); Debug::systemErr(error); continue; } if (offset.x + glyph->bitmap.width + 1 >= (unsigned int)maxTextureWidth) { offset.y += rowHeight; rowHeight = 0; offset.x = 0; } texture.setSubImage(0, offset, Vec2i(glyph->bitmap.width, glyph->bitmap.rows), glyph->bitmap.buffer); characters[i].advance = Vec2f((float)(glyph->advance.x >> 6), (float)(glyph->advance.y >> 6)); characters[i].bitmapLeftTop = Vec2f((float)glyph->bitmap_left, (float)glyph->bitmap_top); characters[i].size = Vec2f((float)(glyph->bitmap.width), (float)(glyph->bitmap.rows)); characters[i].textureOffset = Vec2f((float)(offset.x / width), (float)(offset.y / height)); rowHeight = max(rowHeight, glyph->bitmap.rows); offset.x += glyph->bitmap.width + 2; } delete[] blankColor; if (logStatus) { Debug::systemSuccess("Loaded font: " + Util::removePathFromFilePathAndName(path), DebugColor::Blue); Debug::systemSuccess(Util::removePathFromFilePathAndName(path) + " atlas size is " + std::to_string(width) + " x " + std::to_string(height) + " pixels and is " + std::to_string(width * height / 1024) + " kb", DebugColor::Blue); } FT_Done_Face(face); } }
26.565891
231
0.623869
salmoncatt
e8960e501ffe7669b6f153d788fa013573294101
1,470
cpp
C++
source/Ch04/drill/ch04_drill.cpp
gorzsaszarvak/UDProg-Introduction
591d1d05c950da2ab4d59d78cbf5a1408caa78e6
[ "CC0-1.0" ]
null
null
null
source/Ch04/drill/ch04_drill.cpp
gorzsaszarvak/UDProg-Introduction
591d1d05c950da2ab4d59d78cbf5a1408caa78e6
[ "CC0-1.0" ]
null
null
null
source/Ch04/drill/ch04_drill.cpp
gorzsaszarvak/UDProg-Introduction
591d1d05c950da2ab4d59d78cbf5a1408caa78e6
[ "CC0-1.0" ]
null
null
null
#include "../../std_lib_facilities.h" int main() { constexpr double m_per_inch = 0.0254; constexpr double m_per_cm = 0.01; constexpr double m_per_ft = 0.3048; double length = -1; char unit = 0; vector<double> values; double lastvalue = 0; double sum = 0; double minvalue = 999999999999; double maxvalue = 0; cout << "Enter a number and a unit (c, m, i, f):\n"; while(cin >> length >> unit) { switch (unit) { case 'i': lastvalue = length * m_per_inch; values.push_back(lastvalue); sum += lastvalue; cout << "That's " << lastvalue << "m\n"; break; case 'm': lastvalue = length; values.push_back(length); sum += lastvalue; break; case 'c': lastvalue = length * m_per_cm; values.push_back(lastvalue); sum += lastvalue; cout << "That's " << lastvalue << "m\n"; break; case 'f': lastvalue = length * m_per_ft; values.push_back(lastvalue); sum += lastvalue; cout << "That's " << lastvalue << "m\n"; break; default: cout << "Illegal unit.\n"; lastvalue=0; break; } if (lastvalue!=0 and (lastvalue < minvalue)) { minvalue = lastvalue; cout << "smallest so far\n"; } else if (lastvalue!=0 and (lastvalue > maxvalue)) { maxvalue = lastvalue; cout << "largest so far\n"; } } cout << "sum of values: " << sum << "m \n"; sort(values.begin(), values.end()); for (int i = 0; i < values.size(); i++) cout << values[i] <<"m, "; return '|'; }
18.375
53
0.588435
gorzsaszarvak
e89adabe1fe3f16e983541aade1c2e7d63de617e
3,624
hpp
C++
a21/serial.hpp
biappi/a21
6d008bebdbd6c51816ed61aa45664fa3b2715d9b
[ "MIT" ]
6
2017-07-28T13:36:24.000Z
2022-01-30T14:00:32.000Z
a21/serial.hpp
carkang/a21
8f472e75de5734514f152828033a93b88401069a
[ "MIT" ]
3
2018-10-26T20:10:49.000Z
2021-05-15T20:31:45.000Z
a21/serial.hpp
carkang/a21
8f472e75de5734514f152828033a93b88401069a
[ "MIT" ]
2
2021-02-14T14:12:58.000Z
2022-01-13T23:08:26.000Z
// // a21 — Arduino Toolkit. // Copyright (C) 2016-2018, Aleh Dzenisiuk. http://github.com/aleh/a21 // #pragma once #include <Arduino.h> #include <a21/clock.hpp> #include <a21/print.hpp> namespace a21 { #pragma GCC optimize ("O2") /** * Software serial port, 8-N-1, TX only. */ template<typename pinTX, unsigned long baudRate, typename Clock = ArduinoClock> class SerialTx : public Print< SerialTx<pinTX, baudRate, Clock> > { private: static inline void writeBit(bool b) __attribute__((always_inline)) { pinTX::write(b); Clock::delayMicroseconds(1000000.0 * (1.0 / baudRate - 5.0 / F_CPU)); } public: static void begin() { pinTX::setOutput(); pinTX::setHigh(); } static void write(uint8_t value) { noInterrupts(); writeBit(false); writeBit(value & _BV(0)); writeBit(value & _BV(1)); writeBit(value & _BV(2)); writeBit(value & _BV(3)); writeBit(value & _BV(4)); writeBit(value & _BV(5)); writeBit(value & _BV(6)); writeBit(value & _BV(7)); writeBit(true); interrupts(); } }; /** * Simple software serial port, 8-N-1, RX only. */ template<typename pinRX, unsigned long baudRate, typename Clock = ArduinoClock> class SerialRx { static constexpr double oneBitDelayUs = 1000000.0 / baudRate; static inline void readNextBit(uint8_t& result) __attribute__((always_inline)) { result >>= 1; if (pinRX::read()) { result |= 0x80; } else { result |= 0x00; } Clock::delayMicroseconds(oneBitDelayUs); } public: static void begin() { pinRX::setInput(); } /** Tries to read the next byte on the pin. * Zero is returned when no byte is available (don't see the start bit or could finish the reception). */ static uint8_t read(uint8_t start_bit_timeout) { uint8_t result = 0; uint8_t start_time = Clock::micros8(); uint8_t t; while (true) { if (!pinRX::read()) { break; } if (Clock::micros8() - start_time >= start_bit_timeout) { return 0; } } cli(); Clock::delayMicroseconds(1.1 * oneBitDelayUs); readNextBit(result); readNextBit(result); readNextBit(result); readNextBit(result); readNextBit(result); readNextBit(result); readNextBit(result); readNextBit(result); bool stop = pinRX::read(); sei(); return stop ? result : 0; } }; /** * Software serial receiver that can be driven by a pin change interrupt. */ template<uint16_t baudRate> class PinChangeSerialRx { protected: /*~ typedef PinChangeSerialRx<baudRate, timerTicksPerSecond> Self; static Self& getSelf() { static Self s = Self(); return s; } // Bit we are on. enum State : uint8_t { BeforeStartBit, StartBit, Bit0, Bit1, Bit2, Bit3, Bit4, Bit5, Bit6, Bit7, Bit8, StopBit } state; // Timestamp of the last event, if any. uint16_t prevTime; bool prevValue; public: static void begin() { getSelf().state = BeforeStartBit; } */ /** Should be called every time the pin changes, possibily from an interrupt handler. */ /* static void pinChange(uint16_t time, bool value) { Self& self = getSelf(); if (self.state == BeforeStartBit) { if (value) { self.prevTime = time; self.state = StartBit; } } else { uint16_t t = time - prevTime; t += halfBitTime; } } */ static void check(uint16_t time_us) { } }; #pragma GCC reset_options } // namespace
20.24581
107
0.606236
biappi
e89d09629dda1c6f9c3983f4d4602d2ed283a888
5,717
cc
C++
third_party/tflite_support/src/tensorflow_lite_support/codegen/utils.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
third_party/tflite_support/src/tensorflow_lite_support/codegen/utils.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
third_party/tflite_support/src/tensorflow_lite_support/codegen/utils.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
/* Copyright 2019 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_lite_support/codegen/utils.h" #include <cstdarg> namespace tflite { namespace support { namespace codegen { int ErrorReporter::Warning(const char* format, ...) { va_list args; va_start(args, format); return Report("[WARN] ", format, args); } int ErrorReporter::Error(const char* format, ...) { va_list args; va_start(args, format); return Report("[ERROR] ", format, args); } int ErrorReporter::Report(const char* prefix, const char* format, va_list args) { char buf[1024]; int formatted = vsnprintf(buf, sizeof(buf), format, args); buffer_ << prefix << buf << std::endl; return formatted; } std::string ErrorReporter::GetMessage() { std::string value = buffer_.str(); buffer_.str(""); return value; } CodeWriter::CodeWriter(ErrorReporter* err) : indent_(0), err_(err) {} void CodeWriter::SetTokenValue(const std::string& token, const std::string& value) { value_map_[token] = value; } const std::string CodeWriter::GetTokenValue(const std::string& token) const { auto iter = value_map_.find(token); if (iter == value_map_.end()) { // Typically only Code Generator's call this function (or `Append`). It's // their duty to make sure the token is valid, and requesting for an invalid // token implicits flaws in the code generation logic. err_->Error("Internal: Cannot find value with token '%s'", token.c_str()); return ""; } return iter->second; } void CodeWriter::SetIndentString(const std::string& indent_str) { indent_str_ = indent_str; } void CodeWriter::Indent() { indent_++; } void CodeWriter::Outdent() { indent_--; } std::string CodeWriter::GenerateIndent() const { std::string res; res.reserve(indent_str_.size() * indent_); for (int i = 0; i < indent_; i++) { res.append(indent_str_); } return res; } void CodeWriter::Append(const std::string& text) { AppendInternal(text, true); } void CodeWriter::AppendNoNewLine(const std::string& text) { AppendInternal(text, false); } void CodeWriter::AppendInternal(const std::string& text, bool newline) { // Prefix indent if ((buffer_.empty() // nothing in the buffer || buffer_.back() == '\n') // is on new line // is writing on current line && (!text.empty() && text[0] != '\n' && text[0] != '\r')) { buffer_.append(GenerateIndent()); } // State machine variables bool in_token = false; int i = 0; // Rough memory reserve buffer_.reserve(buffer_.size() + text.size()); std::string token_buffer; // A simple LL1 analysis while (i < text.size()) { char cur = text[i]; char cur_next = i == text.size() - 1 ? '\0' : text[i + 1]; // Set guardian if (!in_token) { if (cur == '{' && cur_next == '{') { // Enter token in_token = true; i += 2; } else if (cur == '\n') { // We need to apply global indent here buffer_.push_back(cur); if (cur_next != '\0' && cur_next != '\n' && cur_next != '\r') { buffer_.append(GenerateIndent()); } i += 1; } else { buffer_.push_back(cur); i += 1; } } else { if (cur == '}' && cur_next == '}') { // Close token in_token = false; const auto value = GetTokenValue(token_buffer); buffer_.append(value); token_buffer.clear(); i += 2; } else { token_buffer.push_back(cur); i += 1; } } } if (!token_buffer.empty()) { // Typically only Code Generator's call this function. It's // their duty to make sure the code (or template) has valid syntax, and // unclosed "{{...}}" implicits severe error in the template. err_->Error("Internal: Invalid template: {{token}} is not closed."); } if (newline) { buffer_.push_back('\n'); } } void CodeWriter::NewLine() { Append(""); } void CodeWriter::Backspace(int n) { buffer_.resize(buffer_.size() > n ? buffer_.size() - n : 0); } std::string CodeWriter::ToString() const { return buffer_; } bool CodeWriter::IsStreamEmpty() const { return buffer_.empty(); } void CodeWriter::Clear() { buffer_.clear(); value_map_.clear(); indent_ = 0; } std::string SnakeCaseToCamelCase(const std::string& s) { std::string t; t.reserve(s.length()); size_t i = 0; // Note: Use simple string += for simplicity. bool cap = false; while (i < s.size()) { const char c = s[i++]; if (c == '_') { cap = true; } else if (cap) { t += toupper(c); cap = false; } else { t += c; } } return t; } std::string JoinPath(const std::string& a, const std::string& b) { if (a.empty()) return b; std::string a_fixed = a; if (!a_fixed.empty() && a_fixed.back() == '/') a_fixed.pop_back(); std::string b_fixed = b; if (!b_fixed.empty() && b_fixed.front() == '/') b_fixed.erase(0, 1); return a_fixed + "/" + b_fixed; } } // namespace codegen } // namespace support } // namespace tflite
27.094787
80
0.609585
zealoussnow
e89d57dbf5f39dca613fa4db41d0cf512e7b3eda
1,888
hpp
C++
include/Utils/Tracer.hpp
azazelspce/SPGO
04df3c6a0c59120cb054ce2bffcfbc79301c2f27
[ "Apache-2.0", "MIT" ]
4
2016-02-24T17:20:42.000Z
2016-04-09T00:33:50.000Z
include/Utils/Tracer.hpp
azazelspce/SPGO
04df3c6a0c59120cb054ce2bffcfbc79301c2f27
[ "Apache-2.0", "MIT" ]
1
2016-04-29T01:06:48.000Z
2016-12-04T00:35:45.000Z
include/Utils/Tracer.hpp
azazelspce/SPGO
04df3c6a0c59120cb054ce2bffcfbc79301c2f27
[ "Apache-2.0", "MIT" ]
null
null
null
// Copyright 2019 Cristian Sandoval Pineda // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// @file Tracer.hpp /// /// @brief Base class. /// /// @author Cristian Sandoval Pineda /// Contact: sandovalp.ce@gmail.com #ifndef TRACER_HPP #define TRACER_HPP #include <vector> #include <string> using std::vector; using std::string; namespace spgo { /// @cond HIDDEN_SYMBOLS class Tracer { protected: vector<vector<double>> raw_data; vector<double> line; vector<string> columns; bool verbose; public: Tracer( bool verbose = false ) { this->verbose = verbose; } void Append( double var ) { if( line.size() == columns.size() ) { raw_data.push_back( line ); line.clear(); } line.push_back( var ); } void AddColumn( string name ) { columns.push_back( name ); } void AddColumns( vector<string> names ) { columns.insert( columns.end(), names.begin(), names.end()); } void Reserve( int rows ) { line.reserve( columns.size() ); raw_data.reserve( rows ); } void SetOutput( bool verbose ) { this->verbose = verbose; } void Clear() { line.clear(); raw_data.clear(); columns.clear(); } vector<vector<double>> GetData() const { return raw_data; } vector<string> GetColumns() const { return columns; } ~Tracer() { } }; /// @endcond HIDDEN_SYMBOLS } #endif
19.666667
68
0.558792
azazelspce
e89d581b13af47430d6c9abc2e8e08f423ae01e3
1,476
cpp
C++
tests/test_socket.cpp
lijianran/ljrServer
d5087447b92ac4eaffe35dec0c0661cf72a3dad7
[ "Apache-2.0" ]
1
2021-05-15T14:40:36.000Z
2021-05-15T14:40:36.000Z
tests/test_socket.cpp
lijianran/ljrServer
d5087447b92ac4eaffe35dec0c0661cf72a3dad7
[ "Apache-2.0" ]
null
null
null
tests/test_socket.cpp
lijianran/ljrServer
d5087447b92ac4eaffe35dec0c0661cf72a3dad7
[ "Apache-2.0" ]
null
null
null
#include "../ljrServer/socket.h" #include "../ljrServer/log.h" #include "../ljrServer/iomanager.h" // #include "../ljrServer/address.h" static ljrserver::Logger::ptr g_logger = LJRSERVER_LOG_ROOT(); void test_socket() { ljrserver::IPAddress::ptr addr = ljrserver::Address::LookupAnyIPAddress("www.baidu.com"); if (addr) { LJRSERVER_LOG_INFO(g_logger) << "get address: " << addr->toString(); } else { LJRSERVER_LOG_ERROR(g_logger) << "get address fail"; return; } ljrserver::Socket::ptr sock = ljrserver::Socket::CreateTCP(addr); addr->setPort(80); if (!sock->connect(addr)) { LJRSERVER_LOG_ERROR(g_logger) << "connect " << addr->toString() << " fail"; return; } else { LJRSERVER_LOG_INFO(g_logger) << "connect " << addr->toString() << " connected"; } const char buff[] = "GET / HTTP/1.0\r\n\r\n"; int rt = sock->send(buff, sizeof(buff)); if (rt <= 0) { LJRSERVER_LOG_INFO(g_logger) << "send fail rt = " << rt; return; } std::string buffers; buffers.resize(4096); rt = sock->recv(&buffers[0], buffers.size()); if (rt <= 0) { LJRSERVER_LOG_INFO(g_logger) << "recv fail rt = " << rt; return; } buffers.resize(rt); LJRSERVER_LOG_INFO(g_logger) << buffers; } int main(int argc, const char *argv[]) { ljrserver::IOManager iom; iom.schedule(&test_socket); return 0; }
23.0625
93
0.586043
lijianran
e89def63eeab5db8bc1932e5b04d9505152f803c
5,485
hpp
C++
common/trc_io.hpp
hirakuni45/R8C
361d2749b80e738984745bc8d7537eb40191fdd8
[ "BSD-3-Clause" ]
6
2016-03-07T02:40:09.000Z
2021-07-25T11:07:01.000Z
common/trc_io.hpp
hirakuni45/R8C
361d2749b80e738984745bc8d7537eb40191fdd8
[ "BSD-3-Clause" ]
2
2021-11-16T17:51:01.000Z
2021-11-16T17:51:42.000Z
common/trc_io.hpp
hirakuni45/R8C
361d2749b80e738984745bc8d7537eb40191fdd8
[ "BSD-3-Clause" ]
1
2021-01-17T23:03:33.000Z
2021-01-17T23:03:33.000Z
#pragma once //=====================================================================// /*! @file @brief R8C グループ・TimerRC I/O 制御 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2015, 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/R8C/blob/master/LICENSE */ //=====================================================================// #include "common/vect.h" #include "M120AN/system.hpp" #include "M120AN/intr.hpp" #include "M120AN/timer_rc.hpp" /// F_CLK はタイマー周期計算で必要で、設定が無いとエラーにします。 #ifndef F_CLK # error "trc_io.hpp requires F_CLK to be defined" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief TimerRC I/O 制御クラス @param[in] TASK 割り込み内で実行されるクラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <class TASK> class trc_io { public: static TASK task_; static volatile uint16_t pwm_b_; static volatile uint16_t pwm_c_; static volatile uint16_t pwm_d_; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief PWM-A 割り込み */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static inline void itask() { task_(); volatile uint8_t f = TRCSR(); TRCGRB = pwm_b_; TRCGRC = pwm_c_; TRCGRD = pwm_d_; TRCSR = 0x00; } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief カウンターディバイド */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class divide : uint8_t { f1, ///< F_CLK / 1 f2, ///< F_CLK / 2 f4, ///< F_CLK / 4 f8, ///< F_CLK / 8 f32 ///< F_CLK / 32 }; private: public: //-----------------------------------------------------------------// /*! @brief コンストラクター */ //-----------------------------------------------------------------// trc_io() { } //-----------------------------------------------------------------// /*! @brief PWMモード開始(最大3チャネルのPWM出力) @param[in] limit リミット @param[in] cks クロック選択 @param[in] pfl ポートの初期レベル「fasle」0->1、「true」1->0 @param[in] ir_lvl 割り込みレベル(0の場合割り込みを使用しない) @return 設定範囲を超えたら「false」 */ //-----------------------------------------------------------------// void start_pwm(uint16_t limit, divide cks, bool pfl, uint8_t ir_lvl = 0) const { MSTCR.MSTTRC = 0; // モジュールスタンバイ解除 TRCMR.CTS = 0; // カウント停止 TRCCNT = 0x0000; TRCGRA = limit; TRCGRB = pwm_b_ = 128; TRCGRC = pwm_c_ = 128; TRCGRD = pwm_d_ = 128; TRCMR = TRCMR.PWM2.b(1) | TRCMR.PWMB.b(1) | TRCMR.PWMC.b(1) | TRCMR.PWMD.b(1); // コンペア一致Aでカウンタクリア TRCCR1 = TRCCR1.CCLR.b(1) | TRCCR1.TOA.b(0) | TRCCR1.CKS.b(static_cast<uint8_t>(cks)) | TRCCR1.TOB.b(0) | TRCCR1.TOC.b(0) | TRCCR1.TOD.b(0); TRCIOR0 = TRCIOR0.IOA.b(0) | TRCIOR0.IOB.b(2); TRCIOR1 = TRCIOR1.IOC.b(8 | 2) | TRCIOR1.IOD.b(8 | 2); TRCCR2 = TRCCR2.POLB.b(pfl) | TRCCR2.POLC.b(pfl) | TRCCR2.POLD.b(pfl); TRCOER = TRCOER.EB.b(0) | TRCOER.EC.b(0) | TRCOER.ED.b(0); ILVL3.B45 = ir_lvl; if(ir_lvl) { TRCIER = TRCIER.IMIEA.b(1); // カウンターAのマッチをトリガーにして割り込み // TRCIER = TRCIER.IMIEB.b(1); // TRCIER = TRCIER.IMIEC.b(1); } else { TRCIER = 0x00; } TRCMR.CTS = 1; // カウント開始 } //-----------------------------------------------------------------// /*! @brief PWMモード開始(最大3チャネルのPWM出力) @param[in] hz 周期(周波数) @param[in] pfl ポートの初期レベル「fasle」0->1、「true」1->0 @param[in] ir_lvl 割り込みレベル(0の場合割り込みを使用しない) @return 設定範囲を超えたら「false」 */ //-----------------------------------------------------------------// bool start_pwm(uint16_t hz, bool pfl, uint8_t ir_lvl = 0) const { // 周波数から最適な、カウント値を計算 uint32_t tn = F_CLK / hz; uint8_t cks = 0; while(tn > 65536) { tn >>= 1; ++cks; if(cks == 4) { tn >>= 1; } if(cks >= 5) return false; } if(tn) --tn; if(tn == 0) return false; start_pwm(tn, static_cast<divide>(cks), pfl, ir_lvl); return true; } //-----------------------------------------------------------------// /*! @brief PWMリミット値を取得 @return リミット値 */ //-----------------------------------------------------------------// uint16_t get_pwm_limit() const { return TRCGRA(); } //-----------------------------------------------------------------// /*! @brief PWM値Bを設定 @param[in] val 値 */ //-----------------------------------------------------------------// void set_pwm_b(uint16_t val) const { if(ILVL3.B45()) { pwm_b_ = val; } else { TRCGRB = val; } } //-----------------------------------------------------------------// /*! @brief PWM値Cを設定 @param[in] val 値 */ //-----------------------------------------------------------------// void set_pwm_c(uint16_t val) const { if(ILVL3.B45()) { pwm_c_ = val; } else { TRCGRC = val; } } //-----------------------------------------------------------------// /*! @brief PWM値Dを設定 @param[in] val 値 */ //-----------------------------------------------------------------// void set_pwm_d(uint16_t val) const { if(ILVL3.B45()) { pwm_d_ = val; } else { TRCGRD = val; } } }; // スタティック実態定義 template<class TASK> TASK trc_io<TASK>::task_; template<class TASK> volatile uint16_t trc_io<TASK>::pwm_b_; template<class TASK> volatile uint16_t trc_io<TASK>::pwm_c_; template<class TASK> volatile uint16_t trc_io<TASK>::pwm_d_; }
24.707207
88
0.428259
hirakuni45
e89e1c6a679412ed71d9ed0608782c41eeaa537d
4,423
hpp
C++
ui/include/common/constants.hpp
fionser/CODA
db234a1e9761d379fb96ae17eef3b77254f8781c
[ "MIT" ]
12
2017-02-24T19:28:07.000Z
2021-02-05T04:40:47.000Z
ui/include/common/constants.hpp
fionser/CODA
db234a1e9761d379fb96ae17eef3b77254f8781c
[ "MIT" ]
1
2017-04-15T03:41:18.000Z
2017-04-24T09:06:15.000Z
ui/include/common/constants.hpp
fionser/CODA
db234a1e9761d379fb96ae17eef3b77254f8781c
[ "MIT" ]
6
2017-05-14T10:12:50.000Z
2021-02-07T03:50:56.000Z
#ifndef CODA_UI_CONST #define CODA_UI_CONST #include <cstring> #include <string.h> #include <vector> #include <sstream> #include <spdlog/spdlog.h> namespace CConst { extern const std::string VER_SERVER; extern const std::string VER_CLIENT; ///////////////////////////////////////////////// // Server cmd arg ///////////////////////////////////////////////// extern const char* S_MAIN_CMD; ///////////////////////////////////////////////// // Client cmd arg ///////////////////////////////////////////////// extern const char* C_MAIN_CMD_INIT; extern const char* C_MAIN_CMD_SEND_KEY; extern const char* C_MAIN_CMD_JOIN; extern const char* C_MAIN_CMD_SEND_DATA; extern const char* C_MAIN_CMD_RECEIVE_RESULT; extern const char* C_SUB_CMD_NET; ///////////////////////////////////////////////// // filesystem ///////////////////////////////////////////////// extern const char SEP_CH_FILE; extern const std::string CH_CRLF; extern const std::string CODA_CONFIG_FILE_NAME; extern const std::string META_DIR_NAME; extern const std::string META_FILE_NAME; extern const std::string SECRET_KEY_FILE_NAME; extern const std::string PUBLIC_KEY_FILE_NAME; extern const std::string CONTEXT_KEY_FILE_NAME; extern const std::string SCHEMA_FILE_NAME; extern const std::string DATA_DIR_NAME; extern const std::string PLAIN_DIR_NAME; extern const std::string UPLOADING_DIR_NAME; extern const std::string CATEGORICAL; extern const std::string ORDINAL; extern const std::string NUMERICAL; extern const std::string RESULT_DIR_NAME; extern const std::string ENC_DIR_NAME; extern const std::string FLAG_FILE_NAME; extern const std::string RESULT_FILE_NAME; extern const std::string CONFIG_FILE_NAME; ///////////////////////////////////////////////// // META keywords ///////////////////////////////////////////////// extern const std::string CFG_KEY_CORE_BIN; extern const std::string CFG_KEY_HOST; extern const std::string CFG_KEY_PORT; extern const std::string CFG_KEY_UNAME; extern const std::string CFG_KEY_DIRECTORY; extern const std::string META_KEY_ANALYST; extern const std::string META_KEY_SESSION_NAME; extern const std::string META_KEY_PROTOCOL; extern const std::string META_KEY_USER_NAMES; ///////////////////////////////////////////////// // Network MSGs ///////////////////////////////////////////////// extern const char* MSG_OK; extern const char* MSG_NG; extern const char* MSG_REQUEST_CMD; extern const char* MSG_ANALYST_NAME; extern const char* MSG_SESSION_NAME; extern const char* MSG_PROTOCOL; extern const char* MSG_USER_NUM; extern const char* MSG_USER_NAME; extern const char* MSG_FILE_TRANS; extern const char* MSG_CLIENT_SERVER; extern const char* MSG_SERVER_CLIENT; ///////////////////////////////////////////////// // local CMDs ///////////////////////////////////////////////// extern const char* CMD_INIT; extern const char* CMD_SEND_PK; extern const char* CMD_JOIN; extern const char* CMD_SEND_DATA; extern const char* CMD_RECV_RESULT; extern const char* CMD_DEBUG; extern const char* CMD_REQ_NUMBER_FILES; extern const char* CMD_REQ_FILE_NAME; extern const char* CMD_REQ_FILE_SIZE; extern const char* CMD_SEND_FILES; extern const char* CMD_RECEIVE_FILES; ///////////////////////////////////////////////// // FILE KEYWORD ///////////////////////////////////////////////// extern const std::string KPATH_DATA; extern const std::string KPATH_META; extern const std::string KPATH_RESULT; extern const std::string KPATH_DEBUG; ///////////////////////////////////////////////// // KEYWORD ///////////////////////////////////////////////// extern const std::string KEYWORD_FSIZE; ///////////////////////////////////////////////// // for windows ///////////////////////////////////////////////// extern std::vector<std::string> split(std::string str, char sep); }; extern std::shared_ptr<spdlog::logger> _console; ///////////////////////////////////////////////// // for windows ///////////////////////////////////////////////// template<class T> std::string to_string(const T&v) { std::ostringstream out; out << v; return out.str(); } #endif
37.483051
69
0.557314
fionser
e8a01e2c702ba00aa8a543baa18238ff35e56cb9
1,727
cc
C++
chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.cc
aranajhonny/chromium
caf5bcb822f79b8997720e589334266551a50a13
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-01-16T03:57:39.000Z
2019-01-16T03:57:39.000Z
chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.cc
aranajhonny/chromium
caf5bcb822f79b8997720e589334266551a50a13
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-02-10T21:00:08.000Z
2018-03-20T05:09:50.000Z
chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.cc
aranajhonny/chromium
caf5bcb822f79b8997720e589334266551a50a13
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/toolbar/extension_toolbar_menu_view.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/browser/ui/views/toolbar/browser_actions_container.h" #include "chrome/browser/ui/views/toolbar/toolbar_view.h" #include "ui/views/controls/menu/menu_item_view.h" namespace { // Bottom padding to make sure we have enough room for the icons. // TODO(devlin): Figure out why the bottom few pixels of the last row in the // overflow menu are cut off (so we can remove this). const int kVerticalPadding = 8; } // namespace ExtensionToolbarMenuView::ExtensionToolbarMenuView(Browser* browser) : browser_(browser) { BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser); container_ = new BrowserActionsContainer( browser_, NULL, // No owner view, means no extra keybindings are registered. browser_view->GetToolbarView()->browser_actions()); container_->Init(); AddChildView(container_); } ExtensionToolbarMenuView::~ExtensionToolbarMenuView() { } gfx::Size ExtensionToolbarMenuView::GetPreferredSize() const { gfx::Size sz = container_->GetPreferredSize(); if (sz.height() == 0) return sz; sz.Enlarge(0, kVerticalPadding); return sz; } void ExtensionToolbarMenuView::Layout() { // All buttons are given the same width. gfx::Size sz = container_->GetPreferredSize(); int height = sz.height() + kVerticalPadding / 2; SetBounds(views::MenuItemView::label_start(), 0, sz.width(), height); container_->SetBounds(0, 0, sz.width(), height); }
33.862745
77
0.745802
aranajhonny
e8a1d18b3a83ca676a8a0b5e7ac171aa7cd784b8
410
cpp
C++
src/ppl/nn/engines/x86/impls/src/ppl/kernel/x86/fp32/tile/tile_fp32.cpp
weisk/ppl.nn
7dd75a1077867fc9a762449953417088446ae2f8
[ "Apache-2.0" ]
1
2021-10-06T14:39:58.000Z
2021-10-06T14:39:58.000Z
src/ppl/nn/engines/x86/impls/src/ppl/kernel/x86/fp32/tile/tile_fp32.cpp
wolf15/ppl.nn
ac23e5eb518039536f1ef39b43c63d6bda900e77
[ "Apache-2.0" ]
null
null
null
src/ppl/nn/engines/x86/impls/src/ppl/kernel/x86/fp32/tile/tile_fp32.cpp
wolf15/ppl.nn
ac23e5eb518039536f1ef39b43c63d6bda900e77
[ "Apache-2.0" ]
null
null
null
#include "ppl/kernel/x86/common/tile/tile_common.h" namespace ppl { namespace kernel { namespace x86 { ppl::common::RetCode tile_ndarray_fp32( const ppl::nn::TensorShape *src_shape, const ppl::nn::TensorShape *dst_shape, const float *src, const int64_t *repeats, float *dst) { return tile_ndarray<float>(src_shape, dst_shape, src, repeats, dst); } }}}; // namespace ppl::kernel::x86
25.625
72
0.702439
weisk
e8a5fc51134a05e0c564f1c57805b3aa28d449eb
2,277
cpp
C++
CodeforcesGym/CF101864-GYM-A.cpp
SpeedOfMagic/CompetitiveProgramming
03f9d2925dbf9af29e93f67753397b5fbff7ab27
[ "MIT" ]
1
2021-05-07T07:38:26.000Z
2021-05-07T07:38:26.000Z
CodeforcesGym/CF101864-GYM-A.cpp
SpeedOfMagic/CompetitiveProgramming
03f9d2925dbf9af29e93f67753397b5fbff7ab27
[ "MIT" ]
null
null
null
CodeforcesGym/CF101864-GYM-A.cpp
SpeedOfMagic/CompetitiveProgramming
03f9d2925dbf9af29e93f67753397b5fbff7ab27
[ "MIT" ]
null
null
null
/** MIT License Copyright (c) 2018 Vasilyev Daniil **/ #include <bits/stdc++.h> using namespace std; #pragma GCC optimize("Ofast") template<typename T> using v = vector<T>; #define int long long typedef long double ld; typedef string str; typedef vector<int> vint; #define rep(a, l, r) for(int a = (l); a < (r); a++) #define pb push_back #define sz(a) ((int) a.size()) const long long inf = 4611686018427387903; //2^62 - 1 #if 0 //FileIO const string fileName = ""; ifstream fin ((fileName == "" ? "input.txt" : fileName + ".in" )); ofstream fout((fileName == "" ? "output.txt" : fileName + ".out")); #define get fin>> #define put fout<< #else #define get cin>> #define put cout<< #endif #define eol put endl #define check(a) put #a << ": " << a << endl; void read() {} template<typename Arg,typename... Args> void read (Arg& arg,Args&... args){get (arg) ;read(args...) ;} void print(){} template<typename Arg,typename... Args> void print(Arg arg,Args... args){put (arg)<<" ";print(args...);} void debug(){eol;} template<typename Arg,typename... Args> void debug(Arg arg,Args... args){put (arg)<<" ";debug(args...);} int getInt(){int a; get a; return a;} //code goes here void run() { int t; get t; for (int test = 1; test <= t; test++) { put "Case " << test << ": "; int x, l, n; read(x, l, n); int q = n - l + 1; int p = 0; if (l < x) p += (x - l); if (x % 2) { int d = x / 2; int k = 1; while (k <= d) k *= 2; while (k + d <= n) { if (k + d >= l) p++; k *= 2; } } int g = __gcd(p, q); p /= g; q /= g; put p << "/" << q << endl; } /** 2^N: 1 1: 1 2: 1 3: 3 4: 1 5: 3 6: 5 7: 7 8: 1 9: 3 10: 5 11: 7 12: 9 13: 11 14: 13 15: 15 16: 1 20: 9 30: 29 31: 31 32: 1 x: (x - msb(x)) * 2 + 1 **/ } int32_t main() {srand(time(0)); ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); put fixed; put setprecision(15); run(); return 0;}
25.875
132
0.465964
SpeedOfMagic
e8a719166ed0480df4cb4dd0b8f7ebe5e8bf63ad
681
cc
C++
DataFormats/JetReco/src/PileupJetIdentifier.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
DataFormats/JetReco/src/PileupJetIdentifier.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
DataFormats/JetReco/src/PileupJetIdentifier.cc
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "DataFormats/JetReco/interface/PileupJetIdentifier.h" #include <cstring> // ------------------------------------------------------------------------------------------ StoredPileupJetIdentifier::StoredPileupJetIdentifier() { } // ------------------------------------------------------------------------------------------ StoredPileupJetIdentifier::~StoredPileupJetIdentifier() { } // ------------------------------------------------------------------------------------------ PileupJetIdentifier::PileupJetIdentifier() { } // ------------------------------------------------------------------------------------------ PileupJetIdentifier::~PileupJetIdentifier() { }
28.375
93
0.358297
bisnupriyasahu
e8aef86c979343a6e7f0082aeef4d3514476ae91
1,204
cpp
C++
src/Engine/map/chunkKey.cpp
FraMecca/Coccode
e302c400e0bff40859c65ccefac923133c770861
[ "BSD-3-Clause" ]
null
null
null
src/Engine/map/chunkKey.cpp
FraMecca/Coccode
e302c400e0bff40859c65ccefac923133c770861
[ "BSD-3-Clause" ]
null
null
null
src/Engine/map/chunkKey.cpp
FraMecca/Coccode
e302c400e0bff40859c65ccefac923133c770861
[ "BSD-3-Clause" ]
null
null
null
/* * ====================== chunkKey.cpp ======================= * -- tpr -- * CREATE -- 2019.03.06 * MODIFY -- * ---------------------------------------------------------- * Chunk "id": (int)w + (int)h * ---------------------------- */ #include "chunkKey.h" #include "pch.h" //-------------------- Engine --------------------// #include "sectionKey.h" /* =========================================================== * get_chunkIdx_in_section * ----------------------------------------------------------- * 获得 目标chunk 在其 section 中的 idx [left-bottom] * ------ * param: _mpos -- 任意 mapent 的 mpos */ size_t get_chunkIdx_in_section(IntVec2 anyMPos_) noexcept { IntVec2 mposOff = anyMPos_2_chunkMPos(anyMPos_) - anyMPos_2_sectionMPos(anyMPos_); tprAssert((mposOff.x >= 0) && (mposOff.y >= 0)); //- tmp int w = std::abs(mposOff.x) / ENTS_PER_CHUNK<>; int h = std::abs(mposOff.y) / ENTS_PER_CHUNK<>; tprAssert((w >= 0) && (w < CHUNKS_PER_SECTION<>)&&(h >= 0) && (h < CHUNKS_PER_SECTION<>)); //- tmp return (size_t)(h * CHUNKS_PER_SECTION<> + w); }
36.484848
102
0.399502
FraMecca
e8af3160c9fd52ec20acf41b86bade50f4539fb1
3,012
hpp
C++
src/checks/checker.hpp
Aman-Jain-14/customizedMesos-PSDSF-absolute
9cb45f8cdd9983668c3ce01be6e03e36c94eb2ce
[ "Apache-2.0" ]
1
2021-11-04T09:59:25.000Z
2021-11-04T09:59:25.000Z
src/checks/checker.hpp
Aman-Jain-14/customizedMesos-fine
7e1939f29adebec7a6517e115a1f0e7cc79146e1
[ "Apache-2.0" ]
null
null
null
src/checks/checker.hpp
Aman-Jain-14/customizedMesos-fine
7e1939f29adebec7a6517e115a1f0e7cc79146e1
[ "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. #ifndef __CHECKER_HPP__ #define __CHECKER_HPP__ #include <string> #include <vector> #include <mesos/mesos.hpp> #include <process/owned.hpp> #include <stout/error.hpp> #include <stout/lambda.hpp> #include <stout/option.hpp> #include <stout/try.hpp> namespace mesos { namespace internal { namespace checks { // Forward declarations. class CheckerProcess; class Checker { public: /** * Attempts to create a `Checker` object. In case of success, checking * starts immediately after initialization. * * @param check The protobuf message definition of a check. * @param callback A callback `Checker` uses to send check status updates * to its owner (usually an executor). * @param taskId The TaskID of the target task. * @param taskPid The target task's pid used to enter the specified * namespaces. * @param namespaces The namespaces to enter prior to performing the check. * @return A `Checker` object or an error if `create` fails. * * @todo A better approach would be to return a stream of updates, e.g., * `process::Stream<CheckStatusInfo>` rather than invoking a callback. */ static Try<process::Owned<Checker>> create( const CheckInfo& checkInfo, const lambda::function<void(const CheckStatusInfo&)>& callback, const TaskID& taskId, const Option<pid_t>& taskPid, const std::vector<std::string>& namespaces); ~Checker(); // Not copyable, not assignable. Checker(const Checker&) = delete; Checker& operator=(const Checker&) = delete; /** * Immediately stops checking. Any in-flight checks are dropped. */ void stop(); private: explicit Checker(process::Owned<CheckerProcess> process); process::Owned<CheckerProcess> process; }; namespace validation { // TODO(alexr): A better place for these functions would be something like // "mesos_validation.cpp", since they validate API protobufs which are not // solely related to this library. Option<Error> checkInfo(const CheckInfo& checkInfo); Option<Error> checkStatusInfo(const CheckStatusInfo& checkStatusInfo); } // namespace validation { } // namespace checks { } // namespace internal { } // namespace mesos { #endif // __CHECKER_HPP__
31.051546
77
0.727756
Aman-Jain-14
e8af3fd260a481d7a858e7e6fe50854f3ea1da5a
1,224
cpp
C++
divi/src/Secp256k1Context.cpp
smcneilly4/xCoin
e4f9fa4af1ad07e03fdad792be3b5d4288947b7e
[ "MIT" ]
56
2019-05-16T21:31:18.000Z
2022-03-16T16:13:02.000Z
divi/src/Secp256k1Context.cpp
smcneilly4/xCoin
e4f9fa4af1ad07e03fdad792be3b5d4288947b7e
[ "MIT" ]
98
2018-03-07T19:30:42.000Z
2019-04-29T14:17:12.000Z
divi/src/Secp256k1Context.cpp
smcneilly4/xCoin
e4f9fa4af1ad07e03fdad792be3b5d4288947b7e
[ "MIT" ]
38
2019-05-07T11:08:41.000Z
2022-03-02T20:06:12.000Z
#include "Secp256k1Context.h" #include <assert.h> #include "random.h" #include "allocators.h" Secp256k1Context::Secp256k1Context() { assert(verifying_context == NULL); verifying_context = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY); assert(verifying_context != NULL); assert(signing_context == NULL); secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); assert(ctx != NULL); { // Pass in a random blinding seed to the secp256k1 context. std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32); GetRandBytes(vseed.data(), 32); bool ret = secp256k1_context_randomize(ctx, vseed.data()); assert(ret); } signing_context = ctx; } Secp256k1Context::~Secp256k1Context() { assert(verifying_context != NULL); secp256k1_context_destroy(verifying_context); verifying_context = NULL; secp256k1_context *ctx = signing_context; signing_context = NULL; if (ctx) { secp256k1_context_destroy(ctx); } } secp256k1_context* Secp256k1Context::GetVerifyContext() { return verifying_context; } secp256k1_context* Secp256k1Context::GetSigningContext() { return signing_context; }
26.608696
78
0.714869
smcneilly4
e8b15bc5e40acb31f4c9ac48dd859fbedf52c9f9
789
cc
C++
os_taskqueue/criticalsection.cc
sonyangchang/mycodecollection
d56149742f71ae7ae03f5a92bd009edbb4d5d3c6
[ "Apache-2.0" ]
1
2020-10-18T02:00:01.000Z
2020-10-18T02:00:01.000Z
os_taskqueue/criticalsection.cc
sonyangchang/mycodecollection
d56149742f71ae7ae03f5a92bd009edbb4d5d3c6
[ "Apache-2.0" ]
null
null
null
os_taskqueue/criticalsection.cc
sonyangchang/mycodecollection
d56149742f71ae7ae03f5a92bd009edbb4d5d3c6
[ "Apache-2.0" ]
1
2020-10-18T02:00:03.000Z
2020-10-18T02:00:03.000Z
#include "criticalsection.h" namespace rtc{ CriticalSection::CriticalSection() { pthread_mutexattr_t mutex_attribute; pthread_mutexattr_init(&mutex_attribute); pthread_mutexattr_settype(&mutex_attribute, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex_, &mutex_attribute); pthread_mutexattr_destroy(&mutex_attribute); } CriticalSection::~CriticalSection(){ pthread_mutex_destroy(&mutex_); } void CriticalSection::Enter()const{ pthread_mutex_lock(&mutex_); } bool CriticalSection::TryEnter()const{ if (pthread_mutex_trylock(&mutex_)!= 0) return false; } void CriticalSection::Leave()const{ pthread_mutex_unlock(&mutex_); } CritScope::CritScope(const CriticalSection* cs) : cs_(cs) { cs_->Enter(); } CritScope::~CritScope() { cs_->Leave(); } }
30.346154
76
0.754119
sonyangchang
e8b36383bd73d2480ac8ccc9bd0eb0c2641ffaca
4,250
cpp
C++
phxrpc/mqtt/test_mqtt_protocol.cpp
zhoudayang/phxrpc
e3ca0b7ff68a48593866f0b1e7bac78a7107074f
[ "BSD-3-Clause" ]
null
null
null
phxrpc/mqtt/test_mqtt_protocol.cpp
zhoudayang/phxrpc
e3ca0b7ff68a48593866f0b1e7bac78a7107074f
[ "BSD-3-Clause" ]
null
null
null
phxrpc/mqtt/test_mqtt_protocol.cpp
zhoudayang/phxrpc
e3ca0b7ff68a48593866f0b1e7bac78a7107074f
[ "BSD-3-Clause" ]
null
null
null
/* Tencent is pleased to support the open source community by making PhxRPC available. Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://opensource.org/licenses/BSD-3-Clause 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. See the AUTHORS file for names of contributors. */ #include <cassert> #include <csignal> #include <cstdio> #include <cstdlib> #include <cstring> #include <memory> #include <sstream> #include "mqtt_msg.h" #include "mqtt_protocol.h" #include "phxrpc/file/file_utils.h" #include "phxrpc/file/opt_map.h" #include "phxrpc/network/socket_stream_block.h" using namespace phxrpc; using namespace std; void ShowUsage(const char *program) { printf("\n%s [-r CONNECT|PUBLISH|SUBSCRIBE|UNSUBSCRIBE|PING|DISCONNECT] [-f file] [-v]\n", program); printf("\t-r mqtt method, only support CONNECT|PUBLISH|SUBSCRIBE|UNSUBSCRIBE|PING|DISCONNECT\n"); printf("\t-f the file for content\n"); printf("\t-v show this usage\n"); printf("\n"); exit(0); } void TraceMsg(const MqttMessage &msg) { ostringstream ss_req; msg.SendRemaining(ss_req); const string &s_req(ss_req.str()); cout << s_req.size() << ":" << endl; for (int i{0}; s_req.size() > i; ++i) { cout << static_cast<int>(s_req.data()[i]) << "\t"; } cout << endl; for (int i{0}; s_req.size() > i; ++i) { if (isalnum(s_req.data()[i]) || '_' == s_req.data()[i]) { cout << s_req.data()[i] << "\t"; } else { cout << '.' << "\t"; } } cout << endl; } int main(int argc, char *argv[]) { assert(sigset(SIGPIPE, SIG_IGN) != SIG_ERR); OptMap optMap("r:f:v"); if ((!optMap.Parse(argc, argv)) || optMap.Has('v')) { ShowUsage(argv[0]); } const char *method{optMap.Get('r')}; const char *file{optMap.Get('f')}; if (nullptr == method) { printf("\nPlease specify method!\n"); ShowUsage(argv[0]); } int ret{0}; if (0 == strcasecmp(method, "CONNECT")) { cout << "Req:" << endl; TraceMsg(MqttConnect()); cout << "Resp:" << endl; TraceMsg(MqttConnack()); } else if (0 == strcasecmp(method, "PUBLISH")) { cout << "Req:" << endl; MqttPublish publish; publish.set_topic_name("test_topic_1"); publish.set_packet_identifier(11); TraceMsg(publish); cout << "Resp:" << endl; MqttPuback puback; puback.set_packet_identifier(11); TraceMsg(puback); } else if (0 == strcasecmp(method, "SUBSCRIBE")) { cout << "Req:" << endl; TraceMsg(MqttSubscribe()); cout << "Resp:" << endl; TraceMsg(MqttSuback()); } else if (0 == strcasecmp(method, "UNSUBSCRIBE")) { cout << "Req:" << endl; TraceMsg(MqttUnsubscribe()); cout << "Resp:" << endl; TraceMsg(MqttUnsuback()); } else if (0 == strcasecmp(method, "PING")) { cout << "Req:" << endl; TraceMsg(MqttPingreq()); cout << "Resp:" << endl; TraceMsg(MqttPingresp()); } else if (0 == strcasecmp(method, "DISCONNECT")) { cout << "Req:" << endl; TraceMsg(MqttDisconnect()); } else { printf("unsupport method %s\n", method); } //if (0 == ret) { // printf("response:\n"); // printf("%s %d %s\n", response.GetVersion(), response.GetStatusCode(), // response.GetReasonPhrase()); // printf("%zu headers\n", response.GetHeaderCount()); // for (size_t i{0}; i < response.GetHeaderCount(); ++i) { // const char *name{response.GetHeaderName(i)}; // const char *val{response.GetHeaderValue(i)}; // printf("%s: %s\r\n", name, val); // } // printf("%zu bytes body\n", response.GetContent().size()); // if (response.GetContent().size() > 0) { // //printf("%s\n", (char*)response.getContent()); // } //} else { // printf("mqtt request fail\n"); //} return 0; }
24.285714
102
0.616
zhoudayang
e8b7c92c6406508fb2e43aca6efe2db3b6f0c0f9
18,147
cpp
C++
librtt/b2GLESDebugDraw.cpp
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
1,968
2018-12-30T21:14:22.000Z
2022-03-31T23:48:16.000Z
librtt/b2GLESDebugDraw.cpp
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
303
2019-01-02T19:36:43.000Z
2022-03-31T23:52:45.000Z
librtt/b2GLESDebugDraw.cpp
agramonte/corona
3a6892f14eea92fdab5fa6d41920aa1e97bc22b1
[ "MIT" ]
254
2019-01-02T19:05:52.000Z
2022-03-30T06:32:28.000Z
/* * Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com * * iPhone port by Simon Oliver - http://www.simonoliver.com - http://www.handcircus.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. */ #include "Core/Rtt_Build.h" #include "b2GLESDebugDraw.h" #include "Box2D/Box2D.h" #include "Core/Rtt_Geometry.h" #include "Display/Rtt_Display.h" #include "Display/Rtt_DisplayObject.h" #include "Display/Rtt_Shader.h" #include "Display/Rtt_ShaderFactory.h" #include "Renderer/Rtt_Geometry_Renderer.h" #include "Renderer/Rtt_Renderer.h" #include "Rtt_LuaLibPhysics.h" #include "Rtt_ParticleSystemObject.h" #include "Rtt_PhysicsJoint.h" #include "Rtt_PhysicsWorld.h" // ---------------------------------------------------------------------------- # define ENABLE_DEBUG_PRINT ( 0 ) # # if ENABLE_DEBUG_PRINT # # define DEBUG_PRINT( ... ) Rtt_Log( __VA_ARGS__ ) # # else // Not ENABLE_DEBUG_PRINT # # define DEBUG_PRINT( ... ) # # endif // ENABLE_DEBUG_PRINT // ---------------------------------------------------------------------------- namespace Rtt { // ---------------------------------------------------------------------------- b2GLESDebugDraw::b2GLESDebugDraw( Display &display ) : fRenderer( NULL ), fPixelsPerMeter( Rtt_REAL_1 ), fMetersPerPixel( Rtt_REAL_1 ), fData() { // Init fData. { /**/ //BAD: THIS MEMORY IS LEAKED!!!!!!!! fData.fGeometry = Rtt_NEW( display.GetAllocator(), Rtt::Geometry( display.GetAllocator(), Geometry::kTriangleFan, 0, // Vertex count. 0, // Index count. false ) ); // Store on GPU. ShaderFactory &factory = display.GetShaderFactory(); fShader = factory.FindOrLoad( ShaderTypes::kCategoryFilter, "color" ); fShader->Prepare( fData, 0, 0, ShaderResource::kDefault ); fData.fFillTexture0 = NULL; fData.fFillTexture1 = NULL; fData.fMaskTexture = NULL; fData.fMaskUniform = NULL; fData.fUserUniform0 = NULL; fData.fUserUniform1 = NULL; fData.fUserUniform2 = NULL; fData.fUserUniform3 = NULL; } } b2GLESDebugDraw::~b2GLESDebugDraw() { /**/ //WE MUST QUEUE fData.fGeometry FOR RELEASE HERE!!!!!!!! } static b2Transform GetTransform( const b2Body& b, Real metersPerPixel ) { b2Transform xf; DisplayObject *o = (DisplayObject *)b.GetUserData(); if ( ! o || LuaLibPhysics::GetGroundBodyUserdata() == o ) { xf = b.GetTransform(); } else { Vertex2 v = { 0.0f, 0.0f }; if( o->ShouldOffsetWithAnchor() ) { Vertex2 offset = o->GetAnchorOffset(); v.x -= offset.x; v.y -= offset.y; } o->LocalToContent( v ); b2Vec2 p( v.x, v.y ); p *= metersPerPixel; xf.Set( p, b.GetTransform().q.GetAngle() ); } return xf; } void b2GLESDebugDraw::Begin( const PhysicsWorld& physics, Renderer &renderer ) { fRenderer = & renderer; fPixelsPerMeter = Rtt_RealToFloat( physics.GetPixelsPerMeter() ); fMetersPerPixel = Rtt_RealToFloat( physics.GetMetersPerPixel() ); } void b2GLESDebugDraw::End() { fRenderer = NULL; fPixelsPerMeter = Rtt_REAL_1; fMetersPerPixel = Rtt_REAL_1; } // NOTE: // This is a replacement for b2World::DrawDebugData() b/c we need to account for // the display object's object-to-world-space transform. void b2GLESDebugDraw::DrawDebugData( const PhysicsWorld& physics, Renderer &renderer ) { b2World *world = physics.GetWorld(); if ( ! world ) { return; } Begin( physics, renderer ); uint32 flags = GetFlags(); // Flags for items we'll draw, overriding the drawing of b2World::DrawDebugData() const uint32 kOverrideFlags = b2Draw::e_shapeBit | b2Draw::e_centerOfMassBit | b2Draw::e_particleBit | b2Draw::e_jointBit; // Our version of drawing Shapes if( flags & kOverrideFlags ) { // Draw all bodies. for (b2Body* body = world->GetBodyList(); body; body = body->GetNext()) { DisplayObject *o = (DisplayObject *)body->GetUserData(); if( !o || body->GetUserData() == LuaLibPhysics::GetGroundBodyUserdata() ) { continue; } b2Transform xf = GetTransform( * body, fMetersPerPixel ); if( flags & b2Draw::e_shapeBit ) { for (b2Fixture* f = body->GetFixtureList(); f; f = f->GetNext()) { float32 r = 0.95f, g = 0.75f, b = 0.5f; if (body->IsActive() == false) { r = 0.5f; g = 0.5f; b = 0.3f; } else if (body->GetType() == b2_staticBody) { r = 0.5f; g = 0.9f; b = 0.5f; } else if (body->GetType() == b2_kinematicBody) { r = 0.5f; g = 0.5f; b = 0.9f; } else if (body->IsAwake() == false) { r = 0.55f; g = 0.55f; b = 0.55f; } // Draw. b2Color c( r, g, b ); DrawShape( f, xf, c ); } } if( flags & b2Draw::e_centerOfMassBit ) { DrawTransform( xf ); } } // Draw all particle systems. if( flags & b2Draw::e_particleBit ) { for (b2ParticleSystem *p = world->GetParticleSystemList(); p; p = p->GetNext()) { DrawParticleSystem( *p ); } } if (flags & b2Draw::e_jointBit) { for (b2Joint* j = world->GetJointList(); j; j = j->GetNext()) { DrawJoint(j); } } } // Temporarily modify flags // Clear out shapeBit, since we want to override drawing of shapes uint32 tmpFlags = flags & ~(kOverrideFlags); SetFlags( tmpFlags ); { // Draw everything else world->DrawDebugData(); } // Restore flags SetFlags( flags ); End(); } void b2GLESDebugDraw::DrawShape( b2Fixture* fixture, const b2Transform& xf, const b2Color& color) { switch (fixture->GetType()) { case b2Shape::e_circle: { b2CircleShape* circle = (b2CircleShape*)fixture->GetShape(); b2Vec2 center = b2Mul(xf, circle->m_p); float32 radius = circle->m_radius; b2Vec2 axis = xf.q.GetXAxis(); DrawSolidCircle(center, radius, axis, color); } break; case b2Shape::e_polygon: { b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape(); int32 vertexCount = poly->m_count; b2Assert(vertexCount <= b2_maxPolygonVertices); b2Vec2 vertices[b2_maxPolygonVertices]; for (int32 i = 0; i < vertexCount; ++i) { vertices[i] = b2Mul(xf, poly->m_vertices[i]); } DrawSolidPolygon(vertices, vertexCount, color); } break; case b2Shape::e_edge: { b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape(); b2Vec2 v1 = b2Mul(xf, edge->m_vertex1); b2Vec2 v2 = b2Mul(xf, edge->m_vertex2); DrawSegment(v1, v2, color); } break; case b2Shape::e_chain: { b2ChainShape* chain = (b2ChainShape*)fixture->GetShape(); int32 count = chain->m_count; const b2Vec2* vertices = chain->m_vertices; b2Vec2 v1 = b2Mul(xf, vertices[0]); for (int32 i = 1; i < count; ++i) { b2Vec2 v2 = b2Mul(xf, vertices[i]); DrawSegment(v1, v2, color); DrawCircle(v1, 0.05f, color); v1 = v2; } // Draw the "end cap" circle. DrawCircle(v1, 0.05f, color); } break; default: Rtt_ASSERT_NOT_REACHED(); break; } } void b2GLESDebugDraw::DrawJoint(b2Joint* joint) { b2Body* bodyA = joint->GetBodyA(); b2Body* bodyB = joint->GetBodyB(); b2Transform xf1 = GetTransform( * bodyA, fMetersPerPixel ); b2Transform xf2 = GetTransform( * bodyB, fMetersPerPixel ); b2Vec2 x1 = xf1.p; b2Vec2 x2 = xf2.p; b2Vec2 p1 = PhysicsJoint::HasLocalAnchor( * joint ) ? x1 + PhysicsJoint::GetLocalAnchorA( * joint ) : joint->GetAnchorA(); b2Vec2 p2 = PhysicsJoint::HasLocalAnchor( * joint ) ? x2 + PhysicsJoint::GetLocalAnchorB( * joint ) : joint->GetAnchorB(); b2Color color(0.5f, 0.8f, 0.8f); switch (joint->GetType()) { case e_distanceJoint: DrawSegment(p1, p2, color); break; case e_pulleyJoint: { b2PulleyJoint* pulley = (b2PulleyJoint*)joint; b2Vec2 s1 = pulley->GetGroundAnchorA(); b2Vec2 s2 = pulley->GetGroundAnchorB(); DrawSegment(s1, p1, color); DrawSegment(s2, p2, color); DrawSegment(s1, s2, color); } break; case e_mouseJoint: { // Drawing code adapted from Box2D 2.0.1 testbed, updated for 2.3.x DrawSegment( p1, p2, color ); float32 size = fMetersPerPixel * 3; DrawPoint( p1, size, b2Color(0,1,0) ); DrawPoint( p2, size, b2Color(0,1,0) ); } break; default: DrawSegment(x1, p1, color); DrawSegment(p1, p2, color); DrawSegment(x2, p2, color); break; } } void b2GLESDebugDraw::DrawParticleSystem( const b2ParticleSystem& system ) { int32 particleCount = system.GetParticleCount(); if ( particleCount ) { // This is safe to do because there's at least ONE particle, // and all particles have the same userdata. const ParticleSystemObject *pso = static_cast< const ParticleSystemObject * >( system.GetUserDataBuffer()[ 0 ] ); if ( pso ) { // Calculate offset. Convert to Box2D coords (meters) Vertex2 offsetInPixels = { 0.0f, 0.0f }; pso->GetSrcToDstMatrix().Apply( offsetInPixels ); b2Vec2 offsetInMeters( offsetInPixels.x, offsetInPixels.y ); offsetInMeters *= fMetersPerPixel; // Draw all particles. float32 radius = system.GetRadius(); const b2Vec2* positionBuffer = system.GetPositionBuffer(); const b2ParticleColor* colorBuffer = NULL; // TODO: We can't easily determine if m_colorBuffer.data is NULL // w/o accidentally forcing an allocation of m_colorBuffer.data /* if (system.m_colorBuffer.data) { colorBuffer = system.GetColorBuffer(); } */ DrawParticlesOffset( positionBuffer, radius, colorBuffer, particleCount, &offsetInMeters ); } } } void b2GLESDebugDraw::_SetVerticesUsed( int32 vertexCount ) { if( vertexCount > (int32)fData.fGeometry->GetVerticesAllocated() ) { fData.fGeometry->Resize( vertexCount, false ); } fData.fGeometry->SetVerticesUsed( vertexCount ); } void b2GLESDebugDraw::_DrawPolygon( bool fill_body, const b2Vec2* vertices, int32 vertexCount, const b2Color& color ) { _SetVerticesUsed( vertexCount ); Rtt::Geometry::Vertex *output_vertices = fData.fGeometry->GetVertexData(); // Copy the vertices from Box2D to our own rendering format. for( int i = 0; i < vertexCount; ++i ) { const b2Vec2 &input_vert = vertices[ i ]; Rtt::Geometry::Vertex &output_vert = output_vertices[ i ]; output_vert.Zero(); output_vert.SetPos( ( input_vert.x * fPixelsPerMeter ), ( input_vert.y * fPixelsPerMeter ) ); } // We're iterating multiple times over the input and output arrays. // From a cache point of view, this is only ok with small arrays. // With large arrays, it's more efficient to set all the fields of // each entries in a single pass. // Draw the body of the polygon. if( fill_body ) { // Set the color. Rtt::Geometry::Vertex::SetColor( vertexCount, output_vertices, 0.5*color.r, 0.5*color.g, 0.5*color.b, 0.5 ); fData.fGeometry->SetPrimitiveType( Geometry::kTriangleFan ); fRenderer->Insert( &fData ); } // Set the color. Rtt::Geometry::Vertex::SetColor( vertexCount, output_vertices, color.r, color.g, color.b, 1.f ); // Draw the outline of the polygon. fData.fGeometry->SetPrimitiveType( Geometry::kLineLoop ); fRenderer->Insert( &fData ); } void b2GLESDebugDraw::DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) { _DrawPolygon( false, vertices, vertexCount, color ); } void b2GLESDebugDraw::DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) { _DrawPolygon( true, vertices, vertexCount, color ); } void b2GLESDebugDraw::DrawParticles( const b2Vec2 *centers, float32 radius, const b2ParticleColor *colors, int32 count ) { DrawParticlesOffset( centers, radius, colors, count, NULL ); } void b2GLESDebugDraw::DrawParticlesOffset( const b2Vec2 *centers, float32 radius, const b2ParticleColor *colors, int32 count, const b2Vec2 *offset ) { static b2Color kColorDefault = b2Color( 1.0f, 1.0f, 1.0f ); b2Color color = kColorDefault; for( int i = 0; i < count; i++ ) { DEBUG_PRINT( "index: %d/%d centers: %f, %f radius: %f colors: %d %d %d %d\n", i, count, centers->x, centers->y, radius, colors->r, colors->g, colors->b, colors->a ); if ( colors ) { color = b2Color( colors[ i ].r, colors[ i ].g, colors[ i ].b ); } DrawCircle( true, centers[ i ], radius, NULL, color, offset ); } } void b2GLESDebugDraw::DrawCircle( bool fill_body, const b2Vec2& center, float32 radius, const b2Vec2 *optionalAxis, const b2Color& color, const b2Vec2 *optionalOffset ) { b2Vec2 circleOrigin( center + ( optionalOffset ? *optionalOffset : b2Vec2_zero ) ); const int32 vertexCount = 16; _SetVerticesUsed( vertexCount ); Rtt::Geometry::Vertex *output_vertices = fData.fGeometry->GetVertexData(); float32 theta = 0.0f; for( int32 i = 0; i < vertexCount; ++i, theta += ( ( 2.0f * b2_pi ) / (float32)vertexCount ) ) { Rtt::Geometry::Vertex &output_vert = output_vertices[ i ]; b2Vec2 pos( cosf( theta ), sinf( theta ) ); pos *= radius; pos += circleOrigin; pos *= fPixelsPerMeter; output_vert.Zero(); output_vert.SetPos( pos.x, pos.y ); } // Draw the body of the circle. if( fill_body ) { // Set the color. Rtt::Geometry::Vertex::SetColor( vertexCount, output_vertices, 0.5*color.r, 0.5*color.g, 0.5*color.b, 0.5 ); fData.fGeometry->SetPrimitiveType( Geometry::kTriangleFan ); fRenderer->Insert( &fData ); } Rtt::Geometry::Vertex::SetColor( vertexCount, output_vertices, color.r, color.g, color.b, 1.f ); // Draw the outline of the circle. fData.fGeometry->SetPrimitiveType( Geometry::kLineLoop ); fRenderer->Insert( &fData ); if( optionalAxis ) { // Draw the axis line DrawSegment( circleOrigin, ( circleOrigin + ( radius * *optionalAxis ) ), color ); } } void b2GLESDebugDraw::DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) { DrawCircle( true, center, radius, NULL, color, NULL ); } void b2GLESDebugDraw::DrawSolidCircle( const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color ) { DrawCircle( true, center, radius, &axis, color, NULL ); } void b2GLESDebugDraw::DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) { const int vertexCount = 2; _SetVerticesUsed( vertexCount ); Rtt::Geometry::Vertex *output_vertices = fData.fGeometry->GetVertexData(); // Start point. { Rtt::Geometry::Vertex &output_vert = output_vertices[ 0 ]; output_vert.Zero(); output_vert.SetPos( ( p1.x * fPixelsPerMeter ), ( p1.y * fPixelsPerMeter ) ); } // End point. { Rtt::Geometry::Vertex &output_vert = output_vertices[ 1 ]; output_vert.Zero(); output_vert.SetPos( ( p2.x * fPixelsPerMeter ), ( p2.y * fPixelsPerMeter ) ); } // Set the color. Rtt::Geometry::Vertex::SetColor( vertexCount, output_vertices, color.r, color.g, color.b, 1.0f ); // Draw. fData.fGeometry->SetPrimitiveType( Geometry::kLines ); fRenderer->Insert( &fData ); } void b2GLESDebugDraw::DrawTransform(const b2Transform& xf) { b2Vec2 p1 = xf.p, p2; const float32 k_axisScale = 0.4f; p2 = p1 + k_axisScale * xf.q.GetXAxis(); DrawSegment(p1,p2,b2Color(1,0,0)); p2 = p1 + k_axisScale * xf.q.GetYAxis(); DrawSegment(p1,p2,b2Color(0,1,0)); } void b2GLESDebugDraw::DrawPoint(const b2Vec2& p, float32 size, const b2Color& color) { // We're aware that this isn't the most efficient way to draw a point. // We'll make this more efficient if necessary. DrawCircle( true, p, size, NULL, color, NULL ); } void b2GLESDebugDraw::DrawString(int x, int y, const char *string, ...) { /* Unsupported as yet. Could replace with bitmap font renderer at a later date */ } void b2GLESDebugDraw::DrawAABB(b2AABB* aabb, const b2Color& c) { const int vertexCount = 4; _SetVerticesUsed( vertexCount ); Rtt::Geometry::Vertex *output_vertices = fData.fGeometry->GetVertexData(); // Upper left. { Rtt::Geometry::Vertex &output_vert = output_vertices[ 0 ]; output_vert.Zero(); output_vert.SetPos( ( aabb->lowerBound.x * fPixelsPerMeter ), ( aabb->lowerBound.y * fPixelsPerMeter ) ); } // Upper right. { Rtt::Geometry::Vertex &output_vert = output_vertices[ 1 ]; output_vert.Zero(); output_vert.SetPos( ( aabb->upperBound.x * fPixelsPerMeter ), ( aabb->lowerBound.y * fPixelsPerMeter ) ); } // Lower right. { Rtt::Geometry::Vertex &output_vert = output_vertices[ 2 ]; output_vert.Zero(); output_vert.SetPos( ( aabb->upperBound.x * fPixelsPerMeter ), ( aabb->upperBound.y * fPixelsPerMeter ) ); } // Lower left. { Rtt::Geometry::Vertex &output_vert = output_vertices[ 3 ]; output_vert.Zero(); output_vert.SetPos( ( aabb->lowerBound.x * fPixelsPerMeter ), ( aabb->upperBound.y * fPixelsPerMeter ) ); } // Set the color. Rtt::Geometry::Vertex::SetColor( vertexCount, output_vertices, c.r, c.g, c.b, 1.0f ); // Draw. fData.fGeometry->SetPrimitiveType( Geometry::kLineLoop ); fRenderer->Insert( &fData ); } // ---------------------------------------------------------------------------- } // namespace Rtt // ----------------------------------------------------------------------------
25.523207
123
0.646443
agramonte
e8ba313aeec4f572d4c727e6738c7a74c3418b72
429
cpp
C++
problemsets/SPOJ/SPOJ - BR/MARAT09.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/SPOJ/SPOJ - BR/MARAT09.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
problemsets/SPOJ/SPOJ - BR/MARAT09.cpp
juarezpaulino/coderemite
a4649d3f3a89d234457032d14a6646b3af339ac1
[ "Apache-2.0" ]
null
null
null
/** * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * */ #include <cstdio> using namespace std; int main() { int N, M; scanf("%d %d", &N, &M); int l = 0, x; bool ok = 1; for (int i = 0; ok && i < N; i++) { scanf("%d", &x); if (x - l > M) ok = 0; l = x; } if (42195 - l > M) ok = 0; if (ok) puts("S"); else puts("N"); return 0; }
14.793103
39
0.433566
juarezpaulino
e8bde9ffc0bacad6659929f5d0fcb580fed6a4ab
16,041
cpp
C++
conformance_tests/tools/debug/src/test_debug.cpp
vilvarajintel/level-zero-tests
d841c0abbd7f77f9011bd37d1b6180b319a5e35d
[ "MIT" ]
32
2020-03-05T19:26:02.000Z
2022-02-21T13:13:52.000Z
conformance_tests/tools/debug/src/test_debug.cpp
vilvarajintel/level-zero-tests
d841c0abbd7f77f9011bd37d1b6180b319a5e35d
[ "MIT" ]
9
2020-05-04T20:15:09.000Z
2021-12-19T07:17:50.000Z
conformance_tests/tools/debug/src/test_debug.cpp
vilvarajintel/level-zero-tests
d841c0abbd7f77f9011bd37d1b6180b319a5e35d
[ "MIT" ]
19
2020-04-07T16:00:48.000Z
2022-01-19T00:19:49.000Z
/* * * Copyright (C) 2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include <boost/filesystem.hpp> #include <boost/process.hpp> #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/mapped_region.hpp> #include <boost/interprocess/sync/named_condition.hpp> #include "gtest/gtest.h" #include "logging/logging.hpp" #include "utils/utils.hpp" #include "test_harness/test_harness.hpp" #include "test_debug.hpp" namespace lzt = level_zero_tests; #include <level_zero/ze_api.h> #include <level_zero/zet_api.h> namespace fs = boost::filesystem; namespace bp = boost::process; namespace bi = boost::interprocess; namespace { TEST( zetDeviceGetDebugPropertiesTest, GivenValidDeviceWhenGettingDebugPropertiesThenPropertiesReturnedSuccessfully) { auto driver = lzt::get_default_driver(); for (auto device : lzt::get_devices(driver)) { auto device_properties = lzt::get_device_properties(device); auto properties = lzt::get_debug_properties(device); if (ZET_DEVICE_DEBUG_PROPERTY_FLAG_ATTACH & properties.flags == 0) { LOG_INFO << "Device " << device_properties.name << " does not support debug"; } else { LOG_INFO << "Device " << device_properties.name << " supports debug"; } } } TEST( zetDeviceGetDebugPropertiesTest, GivenSubDeviceWhenGettingDebugPropertiesThenPropertiesReturnedSuccessfully) { auto driver = lzt::get_default_driver(); for (auto &device : lzt::get_devices(driver)) { for (auto &sub_device : lzt::get_ze_sub_devices(device)) { auto device_properties = lzt::get_device_properties(sub_device); auto properties = lzt::get_debug_properties(sub_device); if (ZET_DEVICE_DEBUG_PROPERTY_FLAG_ATTACH & properties.flags == 0) { LOG_INFO << "Device " << device_properties.name << " does not support debug"; } else { LOG_INFO << "Device " << device_properties.name << " supports debug"; } } } } class zetDebugAttachDetachTest : public ::testing::Test { protected: void SetUp() override { bi::shared_memory_object::remove("debug_bool"); shm = new bi::shared_memory_object(bi::create_only, "debug_bool", bi::read_write); shm->truncate(sizeof(debug_signals_t)); region = new bi::mapped_region(*shm, bi::read_write); static_cast<debug_signals_t *>(region->get_address())->debugger_signal = false; static_cast<debug_signals_t *>(region->get_address())->debugee_signal = false; bi::named_mutex::remove("debugger_mutex"); mutex = new bi::named_mutex(bi::create_only, "debugger_mutex"); bi::named_condition::remove("debug_bool_set"); condition = new bi::named_condition(bi::create_only, "debug_bool_set"); } void TearDown() override { bi::shared_memory_object::remove("debug_bool"); bi::named_mutex::remove("debugger_mutex"); bi::named_condition::remove("debug_bool_set"); delete shm; delete region; delete mutex; delete condition; } void run_test(std::vector<ze_device_handle_t> devices, bool use_sub_devices); bi::shared_memory_object *shm; bi::mapped_region *region; bi::named_mutex *mutex; bi::named_condition *condition; }; void zetDebugAttachDetachTest::run_test(std::vector<ze_device_handle_t> devices, bool use_sub_devices) { for (auto &device : devices) { auto device_properties = lzt::get_device_properties(device); auto debug_properties = lzt::get_debug_properties(device); ASSERT_TRUE(ZET_DEVICE_DEBUG_PROPERTY_FLAG_ATTACH & debug_properties.flags); fs::path helper_path(fs::current_path() / "debug"); std::vector<fs::path> paths; paths.push_back(helper_path); fs::path helper = bp::search_path("test_debug_helper", paths); bp::opstream child_input; bp::child debug_helper( helper, "--device_id=" + lzt::to_string(device_properties.uuid), (use_sub_devices ? "--use_sub_devices" : ""), bp::std_in < child_input); zet_debug_config_t debug_config = {}; debug_config.pid = debug_helper.id(); auto debug_session = lzt::debug_attach(device, debug_config); // notify debugged process that this process has attached mutex->lock(); static_cast<debug_signals_t *>(region->get_address())->debugger_signal = true; mutex->unlock(); condition->notify_all(); debug_helper.wait(); // we don't care about the child processes exit code at // the moment lzt::debug_detach(debug_session); } } TEST_F( zetDebugAttachDetachTest, GivenDeviceSupportsDebugAttachWhenAttachingThenAttachAndDetachIsSuccessful) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_test(devices, false); } TEST_F( zetDebugAttachDetachTest, GivenSubDeviceSupportsDebugAttachWhenAttachingThenAttachAndDetachIsSuccessful) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); std::vector<ze_device_handle_t> all_sub_devices = {}; for (auto &device : devices) { auto sub_devices = lzt::get_ze_sub_devices(device); sub_devices.insert(all_sub_devices.end(), sub_devices.begin(), sub_devices.end()); } run_test(all_sub_devices, true); } class zetDebugEventReadTest : public zetDebugAttachDetachTest { protected: void SetUp() override { zetDebugAttachDetachTest::SetUp(); } void TearDown() override { zetDebugAttachDetachTest::TearDown(); } void run_test(std::vector<ze_device_handle_t> devices, bool use_sub_devices); void run_advanced_test(std::vector<ze_device_handle_t> devices, bool use_sub_devices, debug_test_type_t test_type); }; void zetDebugEventReadTest::run_test(std::vector<ze_device_handle_t> devices, bool use_sub_devices) { for (auto &device : devices) { auto device_properties = lzt::get_device_properties(device); auto debug_properties = lzt::get_debug_properties(device); ASSERT_TRUE(ZET_DEVICE_DEBUG_PROPERTY_FLAG_ATTACH & debug_properties.flags); fs::path helper_path(fs::current_path() / "debug"); std::vector<fs::path> paths; paths.push_back(helper_path); fs::path helper = bp::search_path("test_debug_helper", paths); bp::opstream child_input; bp::child debug_helper( helper, "--device_id=" + lzt::to_string(device_properties.uuid), (use_sub_devices ? "--use_sub_devices" : ""), bp::std_in < child_input); zet_debug_config_t debug_config = {}; debug_config.pid = debug_helper.id(); auto debug_session = lzt::debug_attach(device, debug_config); // notify debugged process that this process has attached mutex->lock(); static_cast<debug_signals_t *>(region->get_address())->debugger_signal = true; mutex->unlock(); condition->notify_all(); // listen for events generated by child process operation std::vector<zet_debug_event_type_t> expected_event = { ZET_DEBUG_EVENT_TYPE_PROCESS_ENTRY, ZET_DEBUG_EVENT_TYPE_MODULE_LOAD, ZET_DEBUG_EVENT_TYPE_MODULE_UNLOAD, ZET_DEBUG_EVENT_TYPE_PROCESS_EXIT, ZET_DEBUG_EVENT_TYPE_DETACHED}; auto event_num = 0; while (true) { auto debug_event = lzt::debug_read_event( debug_session, std::numeric_limits<uint64_t>::max()); EXPECT_EQ(debug_event.type, expected_event[event_num++]); if (debug_event.flags & ZET_DEBUG_EVENT_FLAG_NEED_ACK) { lzt::debug_ack_event(debug_session, &debug_event); } if (ZET_DEBUG_EVENT_TYPE_DETACHED == debug_event.type) { EXPECT_EQ(debug_event.info.detached.reason, ZET_DEBUG_DETACH_REASON_HOST_EXIT); break; } } lzt::debug_detach(debug_session); debug_helper.wait(); } } TEST_F( zetDebugEventReadTest, GivenDebugCapableDeviceWhenProcessIsBeingDebuggedThenCorrectEventsAreRead) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_test(devices, false); } TEST_F( zetDebugEventReadTest, GivenDebugCapableSubDeviceWhenProcessIsBeingDebuggedThenCorrectEventsAreRead) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); std::vector<ze_device_handle_t> all_sub_devices = {}; for (auto &device : devices) { auto sub_devices = lzt::get_ze_sub_devices(device); sub_devices.insert(all_sub_devices.end(), sub_devices.begin(), sub_devices.end()); } run_test(all_sub_devices, true); } //===================================================================================================== void zetDebugEventReadTest::run_advanced_test( std::vector<ze_device_handle_t> devices, bool use_sub_devices, debug_test_type_t test_type) { std::string test_options = ""; for (auto &device : devices) { auto device_properties = lzt::get_device_properties(device); auto debug_properties = lzt::get_debug_properties(device); ASSERT_TRUE(ZET_DEVICE_DEBUG_PROPERTY_FLAG_ATTACH & debug_properties.flags); fs::path helper_path(fs::current_path() / "debug"); std::vector<fs::path> paths; paths.push_back(helper_path); fs::path helper = bp::search_path("test_debug_helper", paths); bp::opstream child_input; bp::child debug_helper( helper, "--device_id=" + lzt::to_string(device_properties.uuid), (use_sub_devices ? "--use_sub_devices" : ""), "--test_type" + test_type, bp::std_in < child_input); zet_debug_config_t debug_config = {}; debug_config.pid = debug_helper.id(); auto debug_session = lzt::debug_attach(device, debug_config); // notify debugged process that this process has attached mutex->lock(); (static_cast<debug_signals_t *>(region->get_address()))->debugger_signal = true; mutex->unlock(); condition->notify_all(); std::vector<zet_debug_event_type_t> events = {}; auto event_num = 0; while (true) { auto debug_event = lzt::debug_read_event( debug_session, std::numeric_limits<uint64_t>::max()); events.push_back(debug_event.type); if (debug_event.flags & ZET_DEBUG_EVENT_FLAG_NEED_ACK) { lzt::debug_ack_event(debug_session, &debug_event); } if (ZET_DEBUG_EVENT_TYPE_DETACHED == debug_event.type) { EXPECT_EQ(debug_event.info.detached.reason, ZET_DEBUG_DETACH_REASON_HOST_EXIT); break; } } switch (test_type) { case THREAD_STOPPED: ASSERT_TRUE(std::find(events.begin(), events.end(), ZET_DEBUG_EVENT_TYPE_THREAD_STOPPED) != events.end()); break; case THREAD_UNAVAILABLE: ASSERT_TRUE(std::find(events.begin(), events.end(), ZET_DEBUG_EVENT_TYPE_THREAD_UNAVAILABLE) != events.end()); break; case PAGE_FAULT: ASSERT_TRUE(std::find(events.begin(), events.end(), ZET_DEBUG_EVENT_TYPE_PAGE_FAULT) != events.end()); break; default: break; } lzt::debug_detach(debug_session); debug_helper.wait(); } } TEST_F(zetDebugEventReadTest, GivenDeviceWhenThenAttachingAfterModuleCreatedThenEventReceived) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); for (auto &device : devices) { auto device_properties = lzt::get_device_properties(device); auto debug_properties = lzt::get_debug_properties(device); ASSERT_TRUE(ZET_DEVICE_DEBUG_PROPERTY_FLAG_ATTACH & debug_properties.flags); fs::path helper_path(fs::current_path() / "debug"); std::vector<fs::path> paths; paths.push_back(helper_path); fs::path helper = bp::search_path("test_debug_helper", paths); bp::opstream child_input; bp::child debug_helper( helper, "--device_id=" + lzt::to_string(device_properties.uuid), "--test_type=" + ATTACH_AFTER_MODULE_CREATED, bp::std_in < child_input); zet_debug_config_t debug_config = {}; debug_config.pid = debug_helper.id(); bi::scoped_lock<bi::named_mutex> lock(*mutex); // wait until child says module created LOG_INFO << "Waiting for Child to create module"; condition->wait(lock, [&] { return (static_cast<debug_signals_t *>(region->get_address()) ->debugee_signal); }); LOG_INFO << "Debugged process proceeding"; auto debug_session = lzt::debug_attach(device, debug_config); // notify debugged process that this process has attached mutex->lock(); static_cast<debug_signals_t *>(region->get_address())->debugger_signal = true; mutex->unlock(); condition->notify_all(); auto event_found = false; while (true) { auto debug_event = lzt::debug_read_event( debug_session, std::numeric_limits<uint64_t>::max()); if (ZET_DEBUG_EVENT_TYPE_MODULE_LOAD == debug_event.type) { event_found = true; } if (debug_event.flags & ZET_DEBUG_EVENT_FLAG_NEED_ACK) { lzt::debug_ack_event(debug_session, &debug_event); } if (ZET_DEBUG_EVENT_TYPE_DETACHED == debug_event.type) { EXPECT_EQ(debug_event.info.detached.reason, ZET_DEBUG_DETACH_REASON_HOST_EXIT); break; } } lzt::debug_detach(debug_session); debug_helper.wait(); ASSERT_TRUE(event_found); } } TEST_F(zetDebugEventReadTest, GivenDeviceWhenCreatingMultipleModulesThenMultipleEventsReceived) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_advanced_test(devices, false, MULTIPLE_MODULES_CREATED); } TEST_F( zetDebugEventReadTest, GivenDebugEnabledDeviceWhenAttachingAfterCreatingAndDestroyingModuleThenNoEventReceived) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_advanced_test(devices, false, ATTACH_AFTER_MODULE_DESTROYED); } TEST_F(zetDebugEventReadTest, GivenDebugAttachedWhenInterruptLongRunningKernelThenStopEventReceived) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_advanced_test(devices, false, LONG_RUNNING_KERNEL_INTERRUPTED); } TEST_F(zetDebugEventReadTest, GivenKernelWithBreakpointsWhenDebugAttachedThenStoppedEventReceived) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_advanced_test(devices, false, BREAKPOINTS); } TEST_F(zetDebugEventReadTest, GivenDebugAttachedWhenCallingResumeThenKernelCompletes) { /* *after stopped event, call resume - kernel should finish */ } TEST_F(zetDebugEventReadTest, GivenCalledInterruptAndResumeWhenKernelExecutingThenKernelCompletes) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_advanced_test(devices, false, KERNEL_RESUME); } TEST_F(zetDebugEventReadTest, GivenDebugEnabledWhenCallingInterruptTwiceSecondInterruptIsBlocked) { /* *call interrupt , call second interrupt for the second time - second interrupt should be blocked until thread stopped/thread unavailable events are available. */ } TEST_F(zetDebugEventReadTest, GivenDeviceExceptionOccursWhenAttachedThenThreadStoppedEventReceived) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_advanced_test(devices, false, THREAD_STOPPED); } TEST_F(zetDebugEventReadTest, GivenThreadUnavailableWhenDebugEnabledThenThreadUnavailableEventRead) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_advanced_test(devices, false, THREAD_UNAVAILABLE); } TEST_F(zetDebugEventReadTest, GivenPageFaultInHelperWhenDebugEnabledThenPageFaultEventRead) { auto driver = lzt::get_default_driver(); auto devices = lzt::get_devices(driver); run_advanced_test(devices, false, PAGE_FAULT); } } // namespace
32.537525
103
0.700081
vilvarajintel
e8c1e3d5b22da0eb4a878676a6037d3990b59567
889
cc
C++
prob05/header.cc
crimsonGnome/121-Lab-02
8f5152d902fe71372f4738cdaa33e6378b88482a
[ "MIT" ]
null
null
null
prob05/header.cc
crimsonGnome/121-Lab-02
8f5152d902fe71372f4738cdaa33e6378b88482a
[ "MIT" ]
null
null
null
prob05/header.cc
crimsonGnome/121-Lab-02
8f5152d902fe71372f4738cdaa33e6378b88482a
[ "MIT" ]
null
null
null
// Name: Joseph Eggers // CWID: 885939488 // Email: joseph.eggers@csu.fullerton.edu #include "header.h" #include <iostream> #include <string> using std::cout, std::string; void DisplayHeader(string txt) { // Declare Variabeles string asteriskMaker; // This makes the srtring +4 due to the "* " and " *" asterisk and the space const int asteriskCushion = 4; // Loop length + the 4 extra characters const int loopLength = txt.length() + asteriskCushion; // for loop making the Asterisk lines for (int i = 0; i < loopLength; i++) { asteriskMaker.append("*"); } // cout box cout << asteriskMaker << "\n* " << txt << " *\n" << asteriskMaker << "\n"; } bool WithinWidth(string txt, unsigned short x) { // if the the length of the the text is less then are = to the width display // true else return false if (txt.length() <= x) return true; return false; }
27.78125
78
0.661417
crimsonGnome
e8c49e53a9e9aa70c0e9a227745b4db10222d56e
1,457
cpp
C++
Xcode/examples/Mitsudesmas/src/MapObject.cpp
YotioSoft/Mitsudesmas
ea9b98a46321ac268ad2ed35460081d2ae8ad3b8
[ "MIT" ]
null
null
null
Xcode/examples/Mitsudesmas/src/MapObject.cpp
YotioSoft/Mitsudesmas
ea9b98a46321ac268ad2ed35460081d2ae8ad3b8
[ "MIT" ]
null
null
null
Xcode/examples/Mitsudesmas/src/MapObject.cpp
YotioSoft/Mitsudesmas
ea9b98a46321ac268ad2ed35460081d2ae8ad3b8
[ "MIT" ]
null
null
null
#include "MapObject.h" MapObject::MapObject(){} MapObject::MapObject(String init_name, MapChipProfiles::Types init_type) { name = init_name; type = init_type; } MapObject::MapObject(String init_name, MapChipProfiles::Types init_type, MapChip &init_chip) { name = init_name; type = init_type; chips << init_chip; } MapObject::MapObject(String init_name, MapChipProfiles::Types init_type, Array<MapChip> &init_chips) { name = init_name; type = init_type; chips = init_chips; } void MapObject::addMapChip(MapChip init_chip) { chips << init_chip; } void MapObject::setObjectSize(Size new_size) { size = new_size; } Size MapObject::getObjectSize() { return size; } String MapObject::getName() { return name; } Array<MapChipProfiles::Directions> MapObject::getDirections() { Array<MapChipProfiles::Directions> ret_array; for (int i = 0; i < chips.size(); i++) { ret_array << chips[i].getDirection(); } return ret_array; } MapChipProfiles::Types MapObject::getType() { return type; } MapChip* MapObject::getChipP(MapChipProfiles::Directions direction) { for (int i = 0; i < chips.size(); i++) { if (chips[i].getDirection() == direction) { return &chips[i]; } } return nullptr; } bool MapObject::draw(const MapChipProfiles::Directions direction, const Point position) { for (int i = 0; i < chips.size(); i++) { if (chips[i].getDirection() == direction) { chips[i].draw(position); return true; } } return false; }
22.075758
102
0.704873
YotioSoft
e8c4ccb3bda3cf88e7cf59a041c088307ce4ad28
5,445
cc
C++
src/ledger/bin/cloud_sync/impl/clock_pack.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
src/ledger/bin/cloud_sync/impl/clock_pack.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
src/ledger/bin/cloud_sync/impl/clock_pack.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/ledger/bin/cloud_sync/impl/clock_pack.h" #include <optional> #include "src/ledger/bin/fidl/include/types.h" #include "src/ledger/bin/storage/public/types.h" #include "src/ledger/lib/convert/convert.h" #include "src/ledger/lib/encoding/encoding.h" #include "src/ledger/lib/logging/logging.h" namespace cloud_sync { namespace { void AddToClock(encryption::EncryptionService* encryption_service, const storage::DeviceEntry& entry, cloud_provider::DeviceClock* clock) { cloud_provider::DeviceEntry device_entry; cloud_provider::ClockEntry clock_entry; clock_entry.set_commit_id( convert::ToArray(encryption_service->EncodeCommitId(entry.head.commit_id))); clock_entry.set_generation(entry.head.generation); device_entry.set_local_entry(std::move(clock_entry)); clock->set_device_entry(std::move(device_entry)); } void AddToClock(encryption::EncryptionService* /*encryption_service*/, const storage::ClockTombstone& /*entry*/, cloud_provider::DeviceClock* clock) { cloud_provider::DeviceEntry device_entry; cloud_provider::TombstoneEntry tombstone; device_entry.set_tombstone_entry(std::move(tombstone)); clock->set_device_entry(std::move(device_entry)); } void AddToClock(encryption::EncryptionService* /*encryption_service*/, const storage::ClockDeletion& /*entry*/, cloud_provider::DeviceClock* clock) { cloud_provider::DeviceEntry device_entry; cloud_provider::DeletionEntry deletion; device_entry.set_deletion_entry(std::move(deletion)); clock->set_device_entry(std::move(device_entry)); } } // namespace cloud_provider::ClockPack EncodeClock(encryption::EncryptionService* encryption_service, const storage::Clock& clock) { cloud_provider::Clock clock_p; for (const auto& [device_id, device_clock] : clock) { cloud_provider::DeviceClock device_clock_p; device_clock_p.set_fingerprint(convert::ToArray(device_id.fingerprint)); device_clock_p.set_counter(device_id.epoch); std::visit([encryption_service, &device_clock_p]( const auto& entry) { AddToClock(encryption_service, entry, &device_clock_p); }, device_clock); clock_p.mutable_devices()->push_back(std::move(device_clock_p)); } cloud_provider::ClockPack pack; ledger::EncodeToBuffer(&clock_p, &pack.buffer); return pack; } ledger::Status DecodeClock(coroutine::CoroutineHandler* handler, storage::PageStorage* storage, cloud_provider::ClockPack clock_pack, storage::Clock* clock) { cloud_provider::Clock unpacked_clock; if (!ledger::DecodeFromBuffer(clock_pack.buffer, &unpacked_clock)) { LEDGER_LOG(ERROR) << "Unable to decode from buffer"; return ledger::Status::DATA_INTEGRITY_ERROR; } storage::Clock result; if (unpacked_clock.has_devices()) { for (const auto& dv : unpacked_clock.devices()) { if (!dv.has_fingerprint() || !dv.has_counter() || !dv.has_device_entry()) { LEDGER_LOG(ERROR) << "Missing elements" << dv.has_fingerprint() << " " << dv.has_counter() << " " << dv.has_device_entry(); return ledger::Status::DATA_INTEGRITY_ERROR; } clocks::DeviceId device_id; device_id.epoch = dv.counter(); device_id.fingerprint = convert::ToString(dv.fingerprint()); storage::DeviceClock device_clock; switch (dv.device_entry().Which()) { case cloud_provider::DeviceEntry::Tag::kLocalEntry: { const cloud_provider::ClockEntry& entry = dv.device_entry().local_entry(); storage::DeviceEntry device_entry; storage::Status status; storage::CommitId local_commit_id; if (coroutine::SyncCall( handler, [storage, &entry]( fit::function<void(storage::Status, storage::CommitId)> callback) mutable { storage->GetCommitIdFromRemoteId(convert::ExtendedStringView(entry.commit_id()), std::move(callback)); }, &status, &local_commit_id) == coroutine::ContinuationStatus::INTERRUPTED) { return ledger::Status::INTERRUPTED; } device_entry.head = storage::ClockEntry{std::move(local_commit_id), entry.generation()}; device_entry.cloud = std::make_optional(device_entry.head); device_clock.emplace<storage::DeviceEntry>(std::move(device_entry)); break; } case cloud_provider::DeviceEntry::Tag::kTombstoneEntry: { device_clock.emplace<storage::ClockTombstone>(); break; } case cloud_provider::DeviceEntry::Tag::kDeletionEntry: { device_clock.emplace<storage::ClockDeletion>(); break; } case cloud_provider::DeviceEntry::Tag::kUnknown: { return ledger::Status::DATA_INTEGRITY_ERROR; break; } case cloud_provider::DeviceEntry::Tag::Invalid: { return ledger::Status::DATA_INTEGRITY_ERROR; break; } } result.emplace(std::move(device_id), std::move(device_clock)); } } *clock = result; return ledger::Status::OK; } } // namespace cloud_sync
41.884615
100
0.673829
opensource-assist
e8c5ed6c8d81526e642349277b07c492e56bc4f2
4,796
cpp
C++
src/DirUtils.cpp
Karolpg/camera_monitoring
9e13e25757408be86b49b5e9b1756fea1429fac7
[ "MIT" ]
null
null
null
src/DirUtils.cpp
Karolpg/camera_monitoring
9e13e25757408be86b49b5e9b1756fea1429fac7
[ "MIT" ]
null
null
null
src/DirUtils.cpp
Karolpg/camera_monitoring
9e13e25757408be86b49b5e9b1756fea1429fac7
[ "MIT" ]
null
null
null
// // The MIT License (MIT) // // Copyright 2020 Karolpg // // 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 "DirUtils.h" #include <sys/stat.h> #include <sys/dir.h> #include <errno.h> #include <iostream> #include <fstream> namespace DirUtils { std::string cleanPath(const std::string &path) { size_t searchFrom = 0; size_t searchSlash = path.find('/', searchFrom); if (searchSlash == std::string::npos) return path; std::string cleanedPath; cleanedPath.reserve(path.length()); //allocate memory for(;searchSlash != std::string::npos;) { //copy values between slashes and also one slash for (auto i = searchFrom; i <= searchSlash; ++i) { cleanedPath += path[i]; } //skip multiple slashes searchFrom = path.find_first_not_of('/', searchSlash + 1); if (searchFrom == std::string::npos) { // only slashes rest - everything is already copied return cleanedPath; } //search next slash searchSlash = path.find('/', searchFrom); } // there is no more slashes - just cpy rest of path for (auto i = searchFrom; i < path.length(); ++i) { cleanedPath += path[i]; } return cleanedPath; } bool isDir(const std::string& path) { struct stat info; if (stat(path.c_str(), &info) != 0) { return false; } return (info.st_mode & S_IFDIR) != 0; } bool isFile(const std::string& filepath) { struct stat info; if (stat(filepath.c_str(), &info) != 0) { return false; } return (info.st_mode & S_IFREG) != 0; // REG == regular file } bool makePath(const std::string &path, uint32_t mode) { if (path.empty()) { return true; // empty path should already exist it is working directory } if (isDir(path)) { return true; // already exist } if (!mkdir(path.c_str(), mode)) return true; if (errno == ENOENT) // parent doesn't exist { auto notSeparator = path.find_last_not_of('/'); if (notSeparator == std::string::npos) return false; // only slashes in path - it is root - we can't create it auto separatorPos = path.find_last_of('/', notSeparator); if (separatorPos == std::string::npos) return false; // strange but we are just not able to create dir and there is no more supdirs notSeparator = path.find_last_not_of('/', separatorPos - 1); // skip many slashes if (notSeparator == std::string::npos) return false; // only separators rest if (!makePath(path.substr(0, notSeparator+1))) return false; //all subdirs are created - retry to create expected dir if (!mkdir(path.c_str(), mode)) return true; } else { std::cerr << "Can't create dir errno: " << errno << "\n"; } return false; } size_t file_size(const std::string& filePath) { std::fstream file; file.open(filePath, std::ios_base::in|std::ios_base::binary); if (!file.is_open()) { return 0; } file.seekg(0, std::ios_base::end); auto result = file.tellg(); file.close(); return result < 0 ? 0 : size_t(result); } std::vector<std::string> listDir(const std::string &path) { if (!isDir(path)) { return std::vector<std::string>(); } std::vector<std::string> result; DIR *dir = opendir(path.c_str()); if (dir != nullptr) { struct dirent *ent = readdir(dir); while (ent != nullptr) { result.push_back(ent->d_name); ent = readdir(dir); } closedir (dir); } else { std::cerr << "Can NOT open directory: " << path << "\n"; } return result; } } // namespace DirUtils
31.973333
162
0.623853
Karolpg
e8c7e9216658dde41bce090feebe55dc4e7ae886
6,612
cpp
C++
Blatt_02/Wettervorhersage.cpp
KevSed/Computational_Physics
6ebfcd07ae5ceb2bfe5b429e8d1425b6877037d1
[ "MIT" ]
null
null
null
Blatt_02/Wettervorhersage.cpp
KevSed/Computational_Physics
6ebfcd07ae5ceb2bfe5b429e8d1425b6877037d1
[ "MIT" ]
null
null
null
Blatt_02/Wettervorhersage.cpp
KevSed/Computational_Physics
6ebfcd07ae5ceb2bfe5b429e8d1425b6877037d1
[ "MIT" ]
null
null
null
/* * Wettervorhersage.cpp * * Created on: 02.05.2017 * Author: mona */ #include <iostream> #include <iomanip> #include <complex> #include <cstdlib> #include <vector> #include <cmath> #include <sstream> #include <utility> #include <math.h> #include <fstream> #include <functional> using namespace std; //**************************************** // Definition des Startvektors und des DGL-Systems //**************************************** vector<double> DGL_start={-10,15,19}; //Vektor der Startwerte vector<double> f(vector<double> DGL, double sigma, double r, double b){ double fx=sigma*(-DGL[0]+DGL[1]); double fy=-DGL[0]*DGL[2]+r*DGL[0]-DGL[1]; double fz=DGL[0]*DGL[1]-b*DGL[2]; DGL={fx,fy,fz}; return DGL; } //**************************************** // Aufgabenteil a) Integration des gleichungssystems mit dem Euler verfahren und Ausgabe von 3 Textdateien, // welche die werte für N={10,100,1000} ausgibt. //**************************************** void euler(vector<double> DGL, double h1, double h2, double h3, double N, double sigma, double r, double b){ vector<double> DGL_1=DGL; vector<double> DGL_2=DGL; vector<double> DGL_3=DGL; // =============================== ofstream a; a.open("Wetter_h1.txt"); a.precision(10);// // =============================== for(double n=1; n<=N; n++){ vector<double> func1=f(DGL_1,sigma,r,b); double x=DGL_1[0]+h1*func1[0]; double y=DGL_1[1]+h1*func1[1]; double z=DGL_1[2]+h1*func1[2]; if(n==10 || n==100 || n==1000){ a << n << "\t" << h1*n << "\t" << x << "\t" << y << "\t" << z << endl; } DGL_1={x,y,z}; } a.close(); // =============================== ofstream c; c.open("Wetter_h2.txt"); c.precision(10);// // =============================== for(double n=1; n<=N; n++){ vector<double> func2=f(DGL_2,sigma,r,b); double x=DGL_2[0]+h2*func2[0]; double y=DGL_2[1]+h2*func2[1]; double z=DGL_2[2]+h2*func2[2]; if(n==10 || n==100 || n==1000){ c << n << "\t" << h2*n << "\t" << x << "\t" << y << "\t" << z << endl; } DGL_2={x,y,z}; } c.close(); // =============================== ofstream d; d.open("Wetter_h3.txt"); d.precision(10);// // =============================== for(double n=1; n<=N; n++){ vector<double> func3=f(DGL_3,sigma,r,b); double x=DGL_3[0]+h3*func3[0]; double y=DGL_3[1]+h3*func3[1]; double z=DGL_3[2]+h3*func3[2]; if(n==10 || n==100 || n==1000){ d << n << "\t" << h3*n << "\t" << x << "\t" << y << "\t" << z << endl; } DGL_3={x,y,z}; } d.close(); } //**************************************** // Aufgabenteil b) und c) Ausgabe von Datensätzen für x und y für verschiedene r und Startwerte //**************************************** void euler_plot(vector<double> DGL, double h, double N, double sigma, double r1, double r2, double b){ vector<double> DGL_1=DGL; vector<double> DGL_2=DGL; // =============================== ofstream a; a.open("Wetter_plotr20.txt"); a.precision(10);// // =============================== for(double n=1; n<=N; n++){ vector<double> func1=f(DGL_1,sigma,r1,b); double x=DGL_1[0]+h*func1[0]; double y=DGL_1[1]+h*func1[1]; double z=DGL_1[2]+h*func1[2]; a << n << "\t" << h*n << "\t" << x << "\t" << y << endl; DGL_1={x,y,z}; } a.close(); // =============================== ofstream c; c.open("Wetter_plotr28.txt"); c.precision(10);// // =============================== for(double n=1; n<=N; n++){ vector<double> func2=f(DGL_2,sigma,r2,b); double x=DGL_2[0]+h*func2[0]; double y=DGL_2[1]+h*func2[1]; double z=DGL_2[2]+h*func2[2]; c << n << "\t" << h*n << "\t" << x << "\t" << y << endl; DGL_2={x,y,z}; } c.close(); // Aufgabenteil c) vector<double> DGL_3={-10.01,15,19}; // =============================== ofstream d; d.open("Wetter_plotr20_c.txt"); d.precision(10);// // =============================== for(double n=1; n<=N; n++){ vector<double> func3=f(DGL_3,sigma,r1,b); double x=DGL_3[0]+h*func3[0]; double y=DGL_3[1]+h*func3[1]; double z=DGL_3[2]+h*func3[2]; d << n << "\t" << h*n << "\t" << x << "\t" << y << endl; DGL_3={x,y,z}; } d.close(); } //**************************************** // Aufgabenteil d) Numerische Ermittlung des Fixpunktes als letzten Wert //**************************************** vector<double> euler_Fixpunkt(vector<double> DGL, double h, double N, double sigma, double r, double b){ vector<double> DGL_1=DGL; double x_alt=DGL_1[0]; double y_alt=DGL_1[1]; double z_alt=DGL_1[2]; double x; double y; double z; double variation=0.00001; for(double n=1; n<=N; n++){ vector<double> func1=f(DGL_1,sigma,r,b); x=DGL_1[0]+h*func1[0]; y=DGL_1[1]+h*func1[1]; z=DGL_1[2]+h*func1[2]; if(abs(x_alt-x)<variation && abs(y_alt-y)<variation && abs(z_alt-z)<variation){ cout << "fixpunkt bei x = " << x << " , y = " << y << " , z = " << z << endl; break; } x_alt=x; y_alt=y; z_alt=z; DGL_1={x,y,z}; } vector<double> letzterWert= {x,y,z}; return letzterWert; } int main(){ double r=20; double sigma=10; double b= 8./3.; //Wird sonst behandelt wie ein Integer euler(DGL_start,0.05,0.005,0.0005,1000,sigma,r,b); euler_plot(DGL_start,0.01,1e5,sigma,20,28,b); //Berechnung des analytischen Fixpunktes double Fix_20= sqrt(b*(20-1)); double Fix_28= sqrt(b*(28-1)); cout << scientific << setprecision(8)<< "Analytisch berechneter Fixpunkt bei r=20: " << "\t" << Fix_20 << endl; cout << scientific << setprecision(8)<< "Analytisch berechneter Fixpunkt bei r=28: " << "\t" << Fix_28 << endl << endl << endl; // Numerische berechnung der Fixpunkte cout << scientific << setprecision(8)<< "Fixpunkt bei r=20, Start=(-10,15,19): " << "\t" ; vector<double> letzter=euler_Fixpunkt(DGL_start,0.001,1e5,sigma,20,b); cout << "Letzter erreichter Wert: " << "\t" << letzter[0] <<"\t" << letzter[1]<<"\t" << letzter[2] << endl ; //Fehler für x double x_Fehler=abs(-letzter[0]-Fix_20)/Fix_20; double y_Fehler=abs(-letzter[1]-Fix_20)/Fix_20; cout << "Fehler fuer x: " << "\t" << x_Fehler <<"\t" << "Fehler fuer y:"<<"\t" << y_Fehler << endl << endl; cout << "Fixpunkt bei r=20, Start=(10.01,15,19): " << "\t" ; vector<double> DGL_start_neu={10.01,15,19}; //Neuer Vektor der Startwerte letzter=euler_Fixpunkt(DGL_start_neu,0.001,1e5,sigma,20,b); x_Fehler=abs(letzter[0]-Fix_20)/Fix_20; y_Fehler=abs(letzter[1]-Fix_20)/Fix_20; cout << "Letzter erreichter Wert: " << "\t" << letzter[0] <<"\t" << letzter[1]<<"\t" << letzter[2] << endl << endl; cout << "Fehler fuer x: " << "\t" << x_Fehler <<"\t" << "Fehler fuer y:"<<"\t" << y_Fehler << endl << endl; return 0; }
27.781513
129
0.536449
KevSed
e8c97fc597de15f44aa7a99a098b641ba20796f0
712
cpp
C++
Grbl/spindle_control.cpp
raspihats/MC5S3DP-XHAT
90a01ea1adc7d2edc2a07c47d6ce3cdb03ba7779
[ "MIT" ]
null
null
null
Grbl/spindle_control.cpp
raspihats/MC5S3DP-XHAT
90a01ea1adc7d2edc2a07c47d6ce3cdb03ba7779
[ "MIT" ]
null
null
null
Grbl/spindle_control.cpp
raspihats/MC5S3DP-XHAT
90a01ea1adc7d2edc2a07c47d6ce3cdb03ba7779
[ "MIT" ]
null
null
null
/* * spindle_control.cpp * * Created on: 16 Sep 2018 * Author: fcos */ #include "spindle_control.h" namespace grbl { SpindleControl::SpindleControl( hal::DigitalOutputPin& enable_pin, hal::DigitalOutputPin& direction_pin, hal::PwmPin& speed_pin, const uint32_t max_speed, const uint32_t min_speed) { } void SpindleControl::Start(const float speed, const SpindleControl::Direction direction) { } void SpindleControl::SetSpeed(const float speed) { } float SpindleControl::GetSpeed() { } void SpindleControl::SetDirection(const SpindleControl::Direction direction) { } float SpindleControl::GetDirection() { } void SpindleControl::Stop() { } } /* namespace grbl */
14.833333
90
0.714888
raspihats
e8cb95376900b846f2f634797d695ad186ee5776
988
cpp
C++
flow/examples/intermediate/zip.cpp
twentylemon/flow
2c1c2a9435ea322e8183661e1ede4b81c0ee11ea
[ "MIT" ]
10
2015-09-10T22:13:54.000Z
2020-11-09T22:21:12.000Z
flow/examples/intermediate/zip.cpp
twentylemon/flow
2c1c2a9435ea322e8183661e1ede4b81c0ee11ea
[ "MIT" ]
null
null
null
flow/examples/intermediate/zip.cpp
twentylemon/flow
2c1c2a9435ea322e8183661e1ede4b81c0ee11ea
[ "MIT" ]
null
null
null
#include <examples.h> void zip_example() { from({ 1, 2, 3, 4 }) | zip({ 1, 2, 3, 4 }) | dump(); // (1, 1) (2, 2) (3, 3) (4, 4) from({ 1, 2, 3, 4 }) | zip({ 5, 6, 7, 8 }) | dump(); // (1, 5) (2, 6) (3, 7) (4, 8) // the detail zip operation is to create and concatenate tuples, // so both the following produce the same stream // (1, 1, 1) (2, 2, 2) (3, 3, 3) (4, 4, 4) from({ 1, 2, 3, 4 }) | zip({ 1, 2, 3, 4 }) | zip({ 1, 2, 3, 4 }) | dump(); std::cout << std::endl; from({ 1, 2, 3, 4 }) | zip(from({ 1, 2, 3, 4 }) | zip({ 1, 2, 3, 4 })) | dump(); // uncurry() can be used to simplify creating functions for zipped streams from({ 1, 2, 3, 4 }) | zip({ 5, 6, 7, 8 }) | filter(uncurry([](int lhs, int rhs) { return lhs % 2 == 0 && rhs % 4 == 0; })) | dump(); // (4, 8) // any zipping operations are possible, such as summing the elements from({ 1, 2, 3, 4 }) | zip({ 5, 6, 7, 8 }, std::plus<int>()) | dump(); // 6 8 10 12 }
44.909091
109
0.472672
twentylemon
e8d06526748e64d0829368791af01f52b62f0441
2,002
hpp
C++
actor.hpp
shane-powell/blit-racers
332ed871bd96d6193ae22cdf419dbb6b189eccee
[ "MIT" ]
null
null
null
actor.hpp
shane-powell/blit-racers
332ed871bd96d6193ae22cdf419dbb6b189eccee
[ "MIT" ]
null
null
null
actor.hpp
shane-powell/blit-racers
332ed871bd96d6193ae22cdf419dbb6b189eccee
[ "MIT" ]
null
null
null
#pragma once #include <32blit.hpp> #include "tiledata.hpp" #include "util.hpp" #include "track.hpp" #include "animation.hpp" class Actor { public: virtual ~Actor() = default; blit::Size size; blit::Rect spriteLocation; float x = 0.0f; float y = 0.0f; blit::Vec2 camera; float degrees = 270.0f; std::map<float, blit::Rect> sprites; uint8_t inputDelay = 0; bool moveEnabled = true; bool lockSpeed = false; const uint8_t STEERINGDELAYMIN = 3; const uint8_t STEERINGDELAYMAX = 5; float prevX = 0.0f; float prevY = 0.0f; blit::Vec2 movement; float speedMultiplier = 0.0; TileScanData currentTileData; uint8_t currentCheckpoint = 1; uint32_t lapTime = 0; std::vector<uint32_t> completedLapTimes; bool isPlayer = false; uint8_t targetNode; uint8_t carNumber = 0; uint8_t position = 0; bool sorted = false; std::function<Position& (uint8_t currentCheckpoint)> getNextTargetCheckpoint; //Animation* animation = nullptr; std::queue<Animation*> animationQueue; Vec2 scale = Vec2(1, 1); Actor() = default; Actor(float xIn, float yIn) { this->x = xIn; this->y = yIn; movement = blit::Vec2(0, 1); this->GenerateSpriteMap(180); } Actor(Position gridPosition, blit::Rect spriteLocation, blit::Size size, uint8_t targetNode, uint8_t carNumber, std::function<Position& (uint8_t currentCheckpoint)> getNextTargetCheckpoint, bool isPlayer = false) { this->SetLocation(gridPosition); this->spriteLocation = spriteLocation; this->size = size; this->isPlayer = isPlayer; this->targetNode = targetNode; movement = blit::Vec2(0, 1); this->GenerateSpriteMap(180); this->carNumber = carNumber; this->getNextTargetCheckpoint = getNextTargetCheckpoint; } void GenerateSpriteMap(float angle); void ProcessTileData(Track* currentTrack); void SetLocation(Position gridPosition); void Respawn(); void Animate(); blit::Point GetPosition(); void Rotate(float rotation); static bool SortByPosition(const Actor* carA, const Actor* carB); };
21.073684
213
0.723277
shane-powell
e8d0bddd9d26de757c21fd9dfb9c583a66ed3c47
7,740
hpp
C++
ajg/synth/engines/options.hpp
ajg/synth
8b9bc9d33f97a40190324108e1e6697f85f19b31
[ "BSL-1.0" ]
36
2015-01-10T02:23:13.000Z
2020-05-31T07:41:02.000Z
ajg/synth/engines/options.hpp
ajg/synth
8b9bc9d33f97a40190324108e1e6697f85f19b31
[ "BSL-1.0" ]
3
2015-12-29T04:19:20.000Z
2018-03-27T04:36:34.000Z
ajg/synth/engines/options.hpp
ajg/synth
8b9bc9d33f97a40190324108e1e6697f85f19b31
[ "BSL-1.0" ]
6
2015-01-10T02:23:18.000Z
2019-09-23T15:25:33.000Z
// (C) Copyright 2014 Alvaro J. Genial (http://alva.ro) // 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). #ifndef AJG_SYNTH_ENGINES_BASE_OPTIONS_HPP_INCLUDED #define AJG_SYNTH_ENGINES_BASE_OPTIONS_HPP_INCLUDED #include <map> #include <stack> #include <vector> #include <utility> #include <ajg/synth/cache.hpp> namespace ajg { namespace synth { namespace engines { // // options // TODO: Move out of engines namespace/directory. //////////////////////////////////////////////////////////////////////////////////////////////////// template <class Context> struct options { public: typedef Context context_type; typedef options options_type; typedef typename context_type::value_type value_type; typedef typename context_type::data_type data_type; typedef typename context_type::metadata_type metadata_type; typedef typename value_type::range_type range_type; typedef typename value_type::sequence_type sequence_type; typedef typename value_type::association_type association_type; typedef typename value_type::arguments_type arguments_type; typedef typename value_type::traits_type traits_type; typedef typename traits_type::boolean_type boolean_type; typedef typename traits_type::char_type char_type; typedef typename traits_type::size_type size_type; typedef typename traits_type::integer_type integer_type; typedef typename traits_type::floating_type floating_type; typedef typename traits_type::number_type number_type; typedef typename traits_type::date_type date_type; typedef typename traits_type::datetime_type datetime_type; typedef typename traits_type::duration_type duration_type; typedef typename traits_type::string_type string_type; typedef typename traits_type::url_type url_type; typedef typename traits_type::symbols_type symbols_type; typedef typename traits_type::path_type path_type; typedef typename traits_type::paths_type paths_type; typedef typename traits_type::names_type names_type; typedef typename traits_type::formats_type formats_type; typedef typename traits_type::istream_type istream_type; typedef typename traits_type::ostream_type ostream_type; struct abstract_library; struct abstract_loader; struct abstract_resolver; // TODO[c++11]: Use unique_ptr (scoped_ptr won't work because it isn't container-friendly.) typedef boost::shared_ptr<abstract_library> library_type; typedef boost::shared_ptr<abstract_loader> loader_type; typedef boost::shared_ptr<abstract_resolver> resolver_type; // TODO: Rename builtin_tags::tag_type/builtin_filters::filter_type to make less ambiguous. typedef boost::function<void(arguments_type const&, ostream_type&, context_type&)> renderer_type; typedef std::pair<std::vector<string_type>, renderer_type> segment_type; typedef std::vector<segment_type> segments_type; typedef boost::function<value_type(value_type const&, arguments_type const&, context_type&)> filter_type; typedef struct tag { boost::function<renderer_type(segments_type const&)> function; // string_type/* symbol_type */ first_name; symbols_type middle_names; symbols_type last_names; boolean_type pure; tag() : pure(false) {} inline operator boolean_type() const { return this->function; } } tag_type; typedef std::map<string_type, tag_type> tags_type; typedef std::map<string_type, filter_type> filters_type; typedef std::map<size_type, renderer_type> renderers_type; typedef std::map<string_type, library_type> libraries_type; typedef std::vector<loader_type> loaders_type; typedef std::vector<resolver_type> resolvers_type; typedef struct { size_type position; tag_type tag; segments_type segments; // boolean_type proceed; } entry_type; typedef std::stack<entry_type> entries_type; typedef caching_mask caching_type; public: options() : debug(false), caching(caching_none) {} public: // TODO: Subsume metadata with: // context_type context; metadata_type metadata; // defaults boolean_type debug; paths_type directories; libraries_type libraries; loaders_type loaders; resolvers_type resolvers; caching_type caching; }; template <class Value> struct options<Value>::abstract_library { public: virtual boolean_type has_tag(string_type const& name) const = 0; virtual boolean_type has_filter(string_type const& name) const = 0; virtual names_type list_tags() const = 0; virtual names_type list_filters() const = 0; virtual tag_type get_tag(string_type const& name) = 0; virtual filter_type get_filter(string_type const& name) = 0; virtual ~abstract_library() {} }; template <class Value> struct options<Value>::abstract_loader { public: virtual library_type load_library(string_type const& name) = 0; virtual ~abstract_loader() {} }; template <class Value> struct options<Value>::abstract_resolver { public: virtual url_type resolve( string_type const& path , context_type const& context , options_type const& options ) = 0; virtual url_type reverse( string_type const& name , arguments_type const& arguments , context_type const& context , options_type const& options ) = 0; virtual ~abstract_resolver() {} }; }}} // namespace ajg::synth::engines #endif // AJG_SYNTH_ENGINES_BASE_OPTIONS_HPP_INCLUDED
46.347305
111
0.537209
ajg
e8dce509d13c2fbe2b80ef81ff47b784c7dfd649
1,765
cpp
C++
Data Structure Problems/CF-Sereja and Brackets.cpp
Sohieeb/competitive-programming
fe3fca0d4d2a242053d097c7ae71667a135cfc45
[ "MIT" ]
1
2020-01-30T20:08:24.000Z
2020-01-30T20:08:24.000Z
Data Structure Problems/CF-Sereja and Brackets.cpp
Sohieb/competitive-programming
fe3fca0d4d2a242053d097c7ae71667a135cfc45
[ "MIT" ]
null
null
null
Data Structure Problems/CF-Sereja and Brackets.cpp
Sohieb/competitive-programming
fe3fca0d4d2a242053d097c7ae71667a135cfc45
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using namespace __gnu_cxx; typedef double db; typedef long long ll; typedef pair<int,int> ii; #define F first #define S second #define pnl printf("\n") #define sz(x) (int)x.size() #define sf(x) scanf("%d",&x) #define pf(x) printf("%d\n",x) #define all(x) x.begin(),x.end() #define rall(x) x.rbegin(),x.rend() #define FOR(a,b) for(int i = a; i < b; ++i) const db eps = 1e-12; const db pi = acos(-1); const int inf = 0x3f3f3f3f; const ll INF = inf * 2LL * inf; const int mod = 1000 * 1000 * 1000 + 7; char str[1000005]; int n, q; pair<ii, int> seg[4000005]; pair<ii, int> merge(pair<ii, int> a, pair<ii, int> b){ pair<ii, int> c; c.S = a.S + b.S; int more = min(a.F.F, b.F.S); c.S += more; c.F.F = b.F.F + a.F.F - more; c.F.S = a.F.S + b.F.S - more; return c; } void build(int id = 1, int l = 0, int r = n){ if(r - l < 2){ seg[id] = {{str[l] == '(', str[l] == ')'}, 0}; return; } int mid = (l + r) / 2; build(id * 2, l, mid); build(id * 2 + 1, mid, r); seg[id] = merge(seg[id*2], seg[id*2 + 1]); } pair<ii, int> query(int x, int y, int id = 1, int l = 0, int r = n){ if(x >= r || l >= y) return {{0, 0}, 0}; if(x <= l && r <= y) return seg[id]; int mid = (l + r) / 2; pair<ii, int> a = query(x, y, id * 2, l, mid); pair<ii, int> b = query(x, y, id * 2 + 1, mid, r); return merge(a, b); } int main() { #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); #endif scanf("%s%d", str, &q); n = strlen(str); build(); while(q--){ int l, r; scanf("%d%d", &l, &r); printf("%d\n", 2 * query(l - 1, r).S); } return 0; }
23.851351
68
0.501983
Sohieeb
e8de98bace832fc475349c972c28d7235b2898b3
18,121
hpp
C++
string.hpp
nwehr/kick
0f738e0895a639c977e8c473eb40ee595e301f32
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
string.hpp
nwehr/kick
0f738e0895a639c977e8c473eb40ee595e301f32
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
string.hpp
nwehr/kick
0f738e0895a639c977e8c473eb40ee595e301f32
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#ifndef _kick_string_h #define _kick_string_h // // Copyright 2012-2014 Kick project developers. // See COPYRIGHT.txt or https://bitbucket.org/nwehr/kick/downloads/COPYRIGHT.txt // // This file is part of the Kick project and subject to license terms. // See LICENSE.txt or https://bitbucket.org/nwehr/kick/downloads/LICENSE.txt // // C #include <string.h> // Kick #include "./common.hpp" #include "./allocator/array_allocator.hpp" /// enable or disable virtual methods to support polymorphism #ifndef KICK_POLYMORPHIC_STRING #define KICK_POLYMORPHIC_STRING KICK_POLYMORPHIC_CONTAINERS #endif namespace kick { /////////////////////////////////////////////////////////////////////////////// // basic_string /////////////////////////////////////////////////////////////////////////////// template<typename CharT, typename AllocT = array_allocator<CharT> > class basic_string { public: static const size_type npos = -1; basic_string( AllocT alloc = AllocT() ); basic_string( const CharT*, AllocT alloc = AllocT() ); basic_string( const CharT*, size_type, AllocT alloc = AllocT() ); basic_string( size_type, AllocT alloc = AllocT() ); basic_string( const basic_string<CharT, AllocT>& ); #if (KICK_POLYMORPHIC_STRING > 0) virtual #endif ~basic_string(); basic_string& operator=( const basic_string<CharT, AllocT>& str ); bool operator==( const basic_string<CharT, AllocT>& ) const; bool operator!=( const basic_string<CharT, AllocT>& ) const; bool operator<( const basic_string<CharT, AllocT>& ) const; bool operator>( const basic_string<CharT, AllocT>& ) const; inline CharT& operator[]( size_type ); inline size_type size() const; inline size_type length() const; inline size_type capacity() const; inline bool empty() const; inline CharT* c_str() const; inline CharT* data() const; size_type copy( CharT*, size_type, size_type pos = 0 ) const; size_type find( const basic_string<CharT, AllocT>&, size_type spos = 0 ) const; inline size_type find( const CharT*, size_type spos = 0 ) const; inline size_type find( const CharT*, size_type, size_type ) const; inline size_type find( CharT, size_type spos = 0 ) const; size_type rfind( const basic_string<CharT, AllocT>&, size_type spos = npos ) const; inline size_type rfind( const CharT*, size_type spos = npos ) const; inline size_type rfind( const CharT* buf, size_type spos, size_type len ) const; inline size_type rfind( CharT c, size_type spos = npos ) const; size_type find_first_of( const basic_string<CharT, AllocT>& nstr, size_type spos = 0 ) const; inline size_type find_first_of( const CharT* buf, size_type spos = 0 ) const; inline size_type find_first_of( const CharT* buf, size_type spos, size_type len ) const; inline size_type find_first_of( CharT c, size_type spos = 0 ) const; size_type find_last_of( const basic_string<CharT, AllocT>& nstr, size_type spos = npos ) const; inline size_type find_last_of( const CharT* buf, size_type spos = npos ) const; inline size_type find_last_of( const CharT* buf, size_type spos, size_type len ) const; inline size_type find_last_of( CharT c, size_type spos = npos ) const; size_type find_first_not_of( const basic_string<CharT, AllocT>& nstr, size_type spos = 0 ) const; inline size_type find_first_not_of( const CharT* buf, size_type spos = 0 ) const; inline size_type find_first_not_of( const CharT* buf, size_type spos, size_type len ) const; inline size_type find_first_not_of( CharT c, size_type spos = 0 ) const; // size_type find_last_not_of( const basic_string<CharT>& nstr, size_type spos = npos ) const; // inline size_type find_last_not_of( const CharT* buf, size_type spos = npos ) const; // inline size_type find_last_not_of( const CharT* buf, size_type spos, size_type len ) const; // inline size_type find_last_not_of( CharT c, size_type spos = npos ) const; size_type find_first_less_than( CharT c, size_type spos = 0 ) const; size_type find_first_greater_than( CharT c, size_type spos = 0 ) const; basic_string<CharT, AllocT> substr( size_type pos, size_type len = npos ) const; protected: CharT* _mem; AllocT _alloc; }; /////////////////////////////////////////////////////////////////////////////// // string /////////////////////////////////////////////////////////////////////////////// typedef basic_string<char> string; /////////////////////////////////////////////////////////////////////////////// // wstring /////////////////////////////////////////////////////////////////////////////// typedef basic_string<wchar_t> wstring; } template<typename CharT, typename AllocT> kick::basic_string<CharT, AllocT>::basic_string( AllocT alloc ) : _mem( nullptr ) , _alloc( alloc ) { _mem = _alloc.malloc( _mem, 0 ); _mem[0] = 0; } template<typename CharT, typename AllocT> kick::basic_string<CharT, AllocT>::basic_string( const CharT* cstr, AllocT alloc ) : _mem( nullptr ) , _alloc( alloc ) { size_type size( 0 ); while( cstr[size] ) ++size; _mem = _alloc.malloc( _mem, ++size ); for( size_type i = 0; i < size; ++i ) _mem[i] = cstr[i]; } template<typename CharT, typename AllocT> kick::basic_string<CharT, AllocT>::basic_string( const CharT* cstr, kick::size_type size, AllocT alloc ) : _mem( nullptr ) , _alloc( alloc ) { _mem = _alloc.malloc( _mem, size + 1 ); for( size_type i = 0; i < size; ++i ) _mem[i] = cstr[i]; _mem[size] = 0; } template<typename CharT, typename AllocT> kick::basic_string<CharT, AllocT>::basic_string( kick::size_type size, AllocT alloc ) : _mem( nullptr ) , _alloc( alloc ) { _mem = _alloc.malloc( _mem, size + 1 ); _mem[0] = 0; _mem[size] = 0; } template<typename CharT, typename AllocT> kick::basic_string<CharT, AllocT>::basic_string( const kick::basic_string<CharT, AllocT>& str ) : _mem( nullptr ) , _alloc( str._alloc ) { size_type size( str.size() + 1 ); _mem = _alloc.malloc( _mem, size ); for( size_type i = 0; i < size; ++i ) _mem[i] = str._mem[i]; } template<typename CharT, typename AllocT> kick::basic_string<CharT, AllocT>::~basic_string() { if( _mem ) _alloc.free( _mem ); } template<typename CharT, typename AllocT> kick::basic_string<CharT, AllocT>& kick::basic_string<CharT, AllocT>::operator=( const kick::basic_string<CharT, AllocT>& str ) { _mem = _alloc.malloc( _mem, (str.size() + 1) ); for( size_type i = 0; i < (str.size() + 1); ++i ) _mem[i] = str._mem[i]; return *this; } template<typename CharT, typename AllocT> bool kick::basic_string<CharT, AllocT>::operator==( const kick::basic_string<CharT, AllocT>& str ) const { return (strcmp( _mem, str._mem ) == 0 ? true : false); } template<typename CharT, typename AllocT> bool kick::basic_string<CharT, AllocT>::operator!=( const kick::basic_string<CharT, AllocT>& str ) const { return !(*this == str); } template<typename CharT, typename AllocT> bool kick::basic_string<CharT, AllocT>::operator<( const kick::basic_string<CharT, AllocT>& str ) const { return (strcmp( _mem, str._mem ) < 0 ? true : false); } template<typename CharT, typename AllocT> bool kick::basic_string<CharT, AllocT>::operator>( const kick::basic_string<CharT, AllocT>& str ) const { return (strcmp( _mem, str._mem ) > 0 ? true : false); } template<typename CharT, typename AllocT> CharT& kick::basic_string<CharT, AllocT>::operator[]( kick::size_type index ) { return _mem[index]; } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::size() const { if( _alloc.usize() ) return _alloc.usize() - 1; return 0; } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::length() const { return size(); } template<typename CharT, typename AllocT> bool kick::basic_string<CharT, AllocT>::empty() const { return size() > 0; } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::capacity() const { return _alloc.asize(); } template<typename CharT, typename AllocT> CharT* kick::basic_string<CharT, AllocT>::c_str() const { return _mem; } template<typename CharT, typename AllocT> CharT* kick::basic_string<CharT, AllocT>::data() const { return c_str(); } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::copy( CharT* str, kick::size_type len, kick::size_type pos ) const { const size_type ssize = size(); if( pos > ssize - 1 ) return 0; if( pos + len > ssize ) len = ssize - pos; size_type di = 0; for( size_type i = pos; i < ssize; ++i ) { str[di] = _mem[i]; ++di; } return di; } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find( const kick::basic_string<CharT, AllocT>& nstr, kick::size_type spos ) const { const size_type nsize = nstr.size(); const size_type hsize = size(); if( nsize > hsize ) return npos; if( spos < 0 ) spos = 0; const size_type smax = hsize - nsize; while( spos <= smax ) { while( spos < smax && _mem[spos] != nstr._mem[0] ) ++spos; size_type hpos = spos + 1; size_type epos = 1; while( hpos < hsize && epos < nsize && _mem[hpos] == nstr._mem[epos] ) { ++hpos; ++epos; } if( epos == nsize ) return spos; else ++spos; } return npos; } //TODO: Optimized search for C string template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find( const CharT* buf, kick::size_type spos ) const { basic_string<CharT> n( buf ); return find( n, spos ); } //TODO: Optimized search for char buffer template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find( const CharT* buf, kick::size_type spos, kick::size_type len ) const { basic_string<CharT> n( buf, len ); return find( n, spos ); } //TODO: Optimized search for single char template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find( CharT c, kick::size_type spos ) const { basic_string<CharT> n( &c, 1 ); return find( n ); } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::rfind( const kick::basic_string<CharT, AllocT>& nstr, kick::size_type spos ) const { const size_type nsize = nstr.size(); const size_type hsize = size(); if( nsize > hsize ) return npos; if( spos == npos || spos > hsize - 1 ) spos = hsize - 1; const size_type smin = nsize - 1; while( spos >= smin ) { while( spos >= smin && _mem[spos] != nstr._mem[nsize - 1] ) --spos; size_type hpos = spos - 1; size_type epos = nsize - 2; while( hpos >= 0 && epos >= 0 && _mem[hpos] == nstr._mem[epos] ) { --hpos; --epos; } if( epos == -1 ) return hpos + 1; else --spos; } return npos; } //TODO: Optimized search for C string template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::rfind( const CharT* buf, kick::size_type spos ) const { basic_string<CharT> n( buf ); return rfind( n, spos ); } //TODO: Optimized search for char buffer template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::rfind( const CharT* buf, kick::size_type spos, kick::size_type len ) const { basic_string<CharT> n( buf, len ); return rfind( n, spos ); } //TODO: Optimized search for single char template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::rfind( CharT c, kick::size_type spos ) const { basic_string<CharT> n( &c, 1 ); return rfind( n ); } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_of( const kick::basic_string<CharT, AllocT>& nstr, kick::size_type spos ) const { const size_type nsize = nstr.size(); const size_type hsize = size(); if( nsize < 1 ) return npos; if( spos < 0 ) spos = 0; while( spos < hsize ) { size_type npos = 0; while( _mem[spos] != nstr._mem[npos] && npos < nsize ) ++npos; if( npos < nsize ) return spos; ++spos; } return npos; } //TODO: Optimized search for C string template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_of( const CharT* buf, kick::size_type spos ) const { basic_string<CharT> n( buf ); return find_first_of( n, spos ); } //TODO: Optimized search for char buffer template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_of( const CharT* buf, kick::size_type spos, kick::size_type len ) const { basic_string<CharT> n( buf, len ); return find_first_of( n, spos ); } //TODO: Optimized search for single char template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_of( CharT c, kick::size_type spos ) const { basic_string<CharT> n( &c, 1 ); return find_first_of( n ); } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_last_of( const kick::basic_string<CharT, AllocT>& nstr, kick::size_type spos ) const { const size_type nsize = nstr.size(); const size_type hsize = size(); if( nsize < 1 ) return npos; if( spos == npos || spos > hsize - 1 ) spos = hsize - 1; while( spos >= 0 ) { size_type npos = 0; while( _mem[spos] != nstr._mem[npos] && npos < nsize ) ++npos; if( npos < nsize ) return spos; --spos; } return npos; } //TODO: Optimized search for C string template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_last_of( const CharT* buf, kick::size_type spos ) const { basic_string<CharT> n( buf ); return find_last_of( n, spos ); } //TODO: Optimized search for char buffer template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_last_of( const CharT* buf, kick::size_type spos, kick::size_type len ) const { basic_string<CharT> n( buf, len ); return find_last_of( n, spos ); } //TODO: Optimized search for single char template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_last_of( CharT c, kick::size_type spos ) const { basic_string<CharT> n( &c, 1 ); return find_last_of( n ); } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_not_of( const kick::basic_string<CharT, AllocT>& nstr, kick::size_type spos ) const { const size_type nsize = nstr.size(); const size_type hsize = size(); if( nsize < 1 ) return npos; if( spos < 0 ) spos = 0; while( spos < hsize ) { size_type npos = 0; while( _mem[spos] != nstr._mem[npos] && npos < nsize ) ++npos; if( npos < nsize ) ++spos; else return spos; } return npos; } //TODO: Optimized search for C string template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_not_of( const CharT* buf, kick::size_type spos ) const { basic_string<CharT> n( buf ); return find_first_not_of( n, spos ); } //TODO: Optimized search for char buffer template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_not_of( const CharT* buf, kick::size_type spos, kick::size_type len ) const { basic_string<CharT> n( buf, len ); return find_first_not_of( n, spos ); } //TODO: Optimized search for single char template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_not_of( CharT c, kick::size_type spos ) const { basic_string<CharT> n( &c, 1 ); return find_first_not_of( n ); } //template<typename CharT> //kick::size_type kick::basic_string<CharT, AllocT>::find_last_not_of( const kick::basic_string<CharT, AllocT>& nstr, kick::size_type spos ) const { // const size_type nsize = nstr.size(); // const size_type hsize = size(); // // if( nsize < 1 ) return npos; // // if( spos == npos || spos > hsize - 1 ) spos = hsize - 1; // while( spos >= 0 ) { // size_type npos = 0; // while( _mem[spos] != nstr._mem[npos] && npos < nsize ) // ++npos; // // if( npos < nsize ) // --spos; // else // return spos; // } // // return npos; //} // ////TODO: Optimized search for C string //template<typename CharT> //kick::size_type kick::basic_string<CharT, AllocT>::find_last_not_of( const CharT* buf, kick::size_type spos ) const { // basic_string<CharT> n( buf ); // return find_last_not_of( n, spos ); //} // ////TODO: Optimized search for char buffer //template<typename CharT> //kick::size_type kick::basic_string<CharT, AllocT>::find_last_not_of( const CharT* buf, size_type spos, size_type len ) const { // basic_string<CharT> n( buf, len ); // return find_last_not_of( n, spos ); //} // ////TODO: Optimized search for single char //template<typename CharT> //kick::size_type find_last_not_of( CharT c, kick::size_type spos ) const { // basic_string<CharT> n( &c, 1 ); // return find_last_not_of( n, spos ); //} template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_less_than( CharT c, kick::size_type spos ) const { const size_type hsize = size(); for( ; spos < hsize; ++spos ) if( _mem[spos] < c ) return spos; return npos; } template<typename CharT, typename AllocT> kick::size_type kick::basic_string<CharT, AllocT>::find_first_greater_than( CharT c, kick::size_type spos ) const { const size_type hsize = size(); for( ; spos < hsize; ++spos ) if( _mem[spos] > c ) return spos; return npos; } template<typename CharT, typename AllocT> kick::basic_string<CharT, AllocT> kick::basic_string<CharT, AllocT>::substr( kick::size_type pos, kick::size_type len ) const { if( len == npos ) len = size(); if( pos < 0 || len <= 0 || pos >= size() ) return basic_string<CharT>(); if( pos + len > size() ) len = size() - pos; return basic_string<CharT>( &_mem[pos], len ); } // Non-member overload for outputting kick strings to stream objects... template<typename StreamT, typename CharT = char, typename AllocT = kick::array_allocator<CharT> > StreamT& operator<<( StreamT& os, const kick::basic_string<CharT, AllocT>& str ) { os << str.c_str(); return os; } #endif // _kick_string_h
30.923208
148
0.679267
nwehr
e8df71ff55656df5b44423e69e899ebe54bc5f62
8,858
hxx
C++
main/writerfilter/inc/resourcemodel/SubSequence.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/writerfilter/inc/resourcemodel/SubSequence.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/writerfilter/inc/resourcemodel/SubSequence.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * 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. * *************************************************************/ #ifndef INCLUDED_SUB_SEQUENCE_HXX #define INCLUDED_SUB_SEQUENCE_HXX #include <com/sun/star/uno/Sequence.hxx> #include <boost/shared_ptr.hpp> #include <iostream> #include <stdio.h> #include <ctype.h> #include "exceptions.hxx" #include <WriterFilterDllApi.hxx> #include <resourcemodel/OutputWithDepth.hxx> namespace writerfilter { using namespace ::std; template <class T> class SubSequence; template <typename T> void dumpLine(OutputWithDepth<string> & o, SubSequence<T> & rSeq, sal_uInt32 nOffset, sal_uInt32 nStep); template <class T> class WRITERFILTER_DLLPUBLIC SubSequence { typedef boost::shared_ptr<com::sun::star::uno::Sequence<T> > SequencePointer; SequencePointer mpSequence; sal_uInt32 mnOffset; sal_uInt32 mnCount; public: typedef boost::shared_ptr<SubSequence> Pointer_t; SubSequence() : mpSequence(new ::com::sun::star::uno::Sequence<T>()), mnOffset(0), mnCount(0) { } SubSequence(SequencePointer pSequence, sal_uInt32 nOffset_, sal_uInt32 nCount_) : mpSequence(pSequence), mnOffset(nOffset_), mnCount(nCount_) { } SubSequence(SequencePointer pSequence) : mpSequence(pSequence), mnOffset(0), mnCount(pSequence->getLength()) { } SubSequence(const SubSequence & rSubSequence, sal_uInt32 nOffset_, sal_uInt32 nCount_) : mpSequence(rSubSequence.mpSequence), mnOffset(rSubSequence.mnOffset + nOffset_), mnCount(nCount_) { } SubSequence(const T * pStart, sal_uInt32 nCount_) : mpSequence(new com::sun::star::uno::Sequence<T>(pStart, nCount_)), mnOffset(0), mnCount(nCount_) { } SubSequence(sal_Int32 nCount_) : mpSequence(new com::sun::star::uno::Sequence<T>(nCount_)), mnOffset(0), mnCount(nCount_) { } ::com::sun::star::uno::Sequence<T> & getSequence() { return *mpSequence; } const ::com::sun::star::uno::Sequence<T> & getSequence() const { return *mpSequence; } void reset() { mnOffset = 0; mnCount = mpSequence->getLength(); } sal_uInt32 getOffset() const { return mnOffset; } sal_uInt32 getCount() const { return mnCount; } const T & operator[] (sal_uInt32 nIndex) const { if (mnOffset + nIndex >= sal::static_int_cast<sal_uInt32>(mpSequence->getLength())) throw ExceptionOutOfBounds("SubSequence::operator[]"); return (*mpSequence)[mnOffset + nIndex]; } void dump(ostream & o) const { { char sBuffer[256]; snprintf(sBuffer, sizeof(sBuffer), "<sequence id='%p' offset='%lx' count='%lx'>", mpSequence.get(), mnOffset, mnCount); o << sBuffer << endl; } sal_uInt32 n = 0; sal_uInt32 nStep = 16; while (n < getCount()) { char sBuffer[256]; o << "<line>"; snprintf(sBuffer, 255, "%08lx: ", n); o << sBuffer; for (sal_uInt32 i = 0; i < nStep; i++) { if (n + i < getCount()) { snprintf(sBuffer, 255, "%02x ", operator[](n + i)); o << sBuffer; } else o << " "; if (i % 8 == 7) o << " "; } { for (sal_uInt32 i = 0; i < nStep; i++) { if (n + i < getCount()) { unsigned char c = static_cast<unsigned char>(operator[](n + i)); if (c=='&') o << "&amp;"; else if (c=='<') o << "&lt;"; else if (c=='>') o << "&gt;"; else if (c < 128 && isprint(c)) o << c; else o << "."; } } } o << "</line>" << endl; n += nStep; } o << "</sequence>" << endl; } void dump(OutputWithDepth<string> & o) { { char sBuffer[256]; snprintf(sBuffer, sizeof(sBuffer), "<sequence id='%p' offset='%" SAL_PRIxUINT32 "' count='%" SAL_PRIxUINT32 "'>", mpSequence.get(), mnOffset, mnCount); o.addItem(sBuffer); } sal_uInt32 n = 0; sal_uInt32 nStep = 16; try { sal_uInt32 nCount = getCount(); while (n < nCount) { sal_uInt32 nBytes = nCount - n; if (nBytes > nStep) nBytes = nStep; SubSequence<T> aSeq(*this, n, nBytes); dumpLine(o, aSeq, n, nStep); n += nBytes; } } catch (...) { o.addItem("<exception/>"); } o.addItem("</sequence>"); } string toString() const { sal_uInt32 n = 0; sal_uInt32 nStep = 16; string sResult; while (n < getCount()) { char sBuffer[256]; snprintf(sBuffer, 255, "<line>%08" SAL_PRIxUINT32 ": ", n); sResult += sBuffer; for (sal_uInt32 i = 0; i < nStep; i++) { if (n + i < getCount()) { snprintf(sBuffer, 255, "%02x ", operator[](n + i)); sResult += sBuffer; } else sResult += " "; if (i % 8 == 7) sResult += " "; } { for (sal_uInt32 i = 0; i < nStep; i++) { if (n + i < getCount()) { unsigned char c = static_cast<unsigned char>(operator[](n + i)); if (c=='&') sResult += "&amp;"; else if (c=='<') sResult += "&lt;"; else if (c=='>') sResult += "&gt;"; else if (c < 128 && isprint(c)) sResult += c; else sResult += "."; } } } sResult += "</line>\n"; n += nStep; } return sResult; } }; template <typename T> void dumpLine(OutputWithDepth<string> & o, SubSequence<T> & rSeq, sal_uInt32 nOffset, sal_uInt32 nStep) { sal_uInt32 nCount = rSeq.getCount(); char sBuffer[256]; string tmpStr = "<line>"; snprintf(sBuffer, 255, "%08" SAL_PRIxUINT32 ": ", nOffset); tmpStr += sBuffer; for (sal_uInt32 i = 0; i < nStep; i++) { if (i < nCount) { snprintf(sBuffer, 255, "%02x ", rSeq[i]); tmpStr += sBuffer; } else tmpStr += " "; if (i % 8 == 7) tmpStr += " "; } { for (sal_uInt32 i = 0; i < nStep; i++) { if (i < nCount) { unsigned char c = static_cast<unsigned char>(rSeq[i]); if (c=='&') tmpStr += "&amp;"; else if (c=='<') tmpStr += "&lt;"; else if (c=='>') tmpStr += "&gt;"; else if (c < 128 && isprint(c)) tmpStr += c; else tmpStr += "."; } } } tmpStr += "</line>"; o.addItem(tmpStr); } } #endif // INCLUDED_SUB_SEQUENCE_HXX
25.454023
99
0.456536
Grosskopf
e8e1ebe8deee9aa578cf9c88492c30f9f4e909c8
25
cpp
C++
src_legacy/2018/test/mock_ws2812.cpp
gmoehler/ledpoi
d1294b172b7069f62119c310399d80500402d882
[ "MIT" ]
null
null
null
src_legacy/2018/test/mock_ws2812.cpp
gmoehler/ledpoi
d1294b172b7069f62119c310399d80500402d882
[ "MIT" ]
75
2017-05-28T23:39:33.000Z
2019-05-09T06:18:44.000Z
test/mock_ws2812.cpp
gmoehler/ledpoi
d1294b172b7069f62119c310399d80500402d882
[ "MIT" ]
null
null
null
#include "mock_ws2812.h"
12.5
24
0.76
gmoehler
e8e25ca74ff35332dadcfe05a0113afff0eade10
2,852
cpp
C++
src/game/server/db_sqlite3.cpp
theovier/TW-TimeRun
87afef60d018ba748fbe2339ec1ce74c16d41679
[ "Zlib" ]
2
2018-08-24T08:54:22.000Z
2019-01-07T09:05:22.000Z
src/game/server/db_sqlite3.cpp
theovier/TW-TimeRun
87afef60d018ba748fbe2339ec1ce74c16d41679
[ "Zlib" ]
1
2018-08-18T10:13:37.000Z
2018-08-19T09:42:40.000Z
src/game/server/db_sqlite3.cpp
theovier/TW-TimeRun
87afef60d018ba748fbe2339ec1ce74c16d41679
[ "Zlib" ]
1
2021-12-26T03:52:09.000Z
2021-12-26T03:52:09.000Z
#include "db_sqlite3.h" bool CQuery::Next() { /*CALL_STACK_ADD();*/ int Ret = sqlite3_step(m_pStatement); return Ret == SQLITE_ROW; } void CQuery::Query(CSql *pDatabase, char *pQuery) { /*CALL_STACK_ADD();*/ m_pDatabase = pDatabase; m_pDatabase->Query(this, pQuery); } void CQuery::OnData() { /*CALL_STACK_ADD();*/ Next(); } int CQuery::GetID(const char *pName) { /*CALL_STACK_ADD();*/ for (int i = 0; i < GetColumnCount(); i++) { if (str_comp(GetName(i), pName) == 0) return i; } return -1; } CQuery::~CQuery() { } void CSql::WorkerThread() { /*CALL_STACK_ADD();*/ while(m_Running) { lock_wait(m_Lock); //lock queue if (m_lpQueries.size() > 0) { CQuery *pQuery = m_lpQueries.front(); m_lpQueries.pop(); lock_release(m_Lock); //unlock queue int Ret; Ret = sqlite3_prepare_v2(m_pDB, pQuery->m_Query.c_str(), -1, &pQuery->m_pStatement, 0); if (Ret == SQLITE_OK) { if (!m_Running) //last check break; pQuery->OnData(); sqlite3_finalize(pQuery->m_pStatement); } else dbg_msg("SQLite", "%s", sqlite3_errmsg(m_pDB)); delete pQuery; } else { thread_sleep(100); lock_release(m_Lock); //unlock queue } thread_sleep(10); } } void CSql::InitWorker(void *pUser) { /*CALL_STACK_ADD();*/ CSql *pSelf = (CSql *)pUser; pSelf->WorkerThread(); } CQuery *CSql::Query(CQuery *pQuery, std::string QueryString) { /*CALL_STACK_ADD();*/ pQuery->m_Query = QueryString; lock_wait(m_Lock); m_lpQueries.push(pQuery); lock_release(m_Lock); return pQuery; } CSql::CSql() { /*CALL_STACK_ADD();*/ int rc = sqlite3_open("saves.db", &m_pDB); if (rc) { dbg_msg("SQLite", "can't open database"); sqlite3_close(m_pDB); } char *pQuery = (char *)"CREATE TABLE IF NOT EXISTS Saves (" \ "ID INTEGER PRIMARY KEY AUTOINCREMENT," \ "Map TEXT NOT NULL," \ "Names TEXT NOT NULL," \ "Time INTEGER);"; sqlite3_exec(m_pDB, pQuery, 0, 0, 0); m_Lock = lock_create(); m_Running = true; thread_create(InitWorker, this); } CSql::~CSql() { /*CALL_STACK_ADD();*/ m_Running = false; lock_wait(m_Lock); while (m_lpQueries.size()) { CQuery *pQuery = m_lpQueries.front(); m_lpQueries.pop(); delete pQuery; } lock_release(m_Lock); lock_destroy(m_Lock); }
20.666667
100
0.51087
theovier
e8e28a10f35b82070b02c81757f07a5729b59d14
1,031
hpp
C++
include/thh-bgfx-debug/debug-cube.hpp
pr0g/thh-bgfx-debug
ecf693f1df6ee11f0d49197c7d84cb70dca076dd
[ "MIT" ]
null
null
null
include/thh-bgfx-debug/debug-cube.hpp
pr0g/thh-bgfx-debug
ecf693f1df6ee11f0d49197c7d84cb70dca076dd
[ "MIT" ]
null
null
null
include/thh-bgfx-debug/debug-cube.hpp
pr0g/thh-bgfx-debug
ecf693f1df6ee11f0d49197c7d84cb70dca076dd
[ "MIT" ]
null
null
null
#pragma once #include "as/as-math-ops.hpp" #include "debug-vertex.hpp" #include <vector> namespace dbg { class DebugCubes { static DebugVertex CubeVertices[]; static uint16_t CubeIndices[]; bgfx::VertexBufferHandle cube_vbh_; bgfx::IndexBufferHandle cube_ibh_; bgfx::ProgramHandle program_handle_; bgfx::ViewId view_; struct CubeInstance { CubeInstance() = default; CubeInstance(const as::mat4& transform, const as::vec4& color) : transform_(transform), color_(color) { } as::mat4 transform_; as::vec4 color_; }; std::vector<CubeInstance> instances_; public: static void init(); DebugCubes(); ~DebugCubes(); void setRenderContext(bgfx::ViewId view, bgfx::ProgramHandle program_handle); void reserveCubes(size_t count); void addCube(const as::mat4& transform, const as::vec4& color); void submit(); }; inline void DebugCubes::addCube( const as::mat4& transform, const as::vec4& color) { instances_.emplace_back(transform, color); } } // namespace dbg
19.092593
79
0.706111
pr0g
e8e634251d723dbec0bd14ed84b203fadc20c796
964
hpp
C++
test/framework/call_engine_tests_common.hpp
Insafin/iroha
5e3c3252b2a62fa887274bdf25547dc264c10c26
[ "Apache-2.0" ]
1,467
2016-10-25T12:27:19.000Z
2022-03-28T04:32:05.000Z
test/framework/call_engine_tests_common.hpp
Insafin/iroha
5e3c3252b2a62fa887274bdf25547dc264c10c26
[ "Apache-2.0" ]
2,366
2016-10-25T10:07:57.000Z
2022-03-31T22:03:24.000Z
test/framework/call_engine_tests_common.hpp
Insafin/iroha
5e3c3252b2a62fa887274bdf25547dc264c10c26
[ "Apache-2.0" ]
662
2016-10-26T04:41:22.000Z
2022-03-31T04:15:02.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #ifndef IROHA_TEST_CALL_ENGINE_TESTS_COMMON_HPP #define IROHA_TEST_CALL_ENGINE_TESTS_COMMON_HPP #include <ostream> #include <string> #include <vector> #include "utils/string_builder.hpp" struct LogData { std::string address; std::string data; std::vector<std::string> topics; LogData(std::string address, std::string data, std::vector<std::string> topics) : address(std::move(address)), data(std::move(data)), topics(std::move(topics)) {} }; inline std::ostream &operator<<(std::ostream &os, LogData const &log) { return os << shared_model::detail::PrettyStringBuilder{} .init("Log") .appendNamed("address", log.address) .appendNamed("data", log.data) .appendNamed("topics", log.topics) .finalize(); } #endif
25.368421
71
0.623444
Insafin
e8e6b0ba2bed9fc368edaa7df98cc8bc43451977
942
cpp
C++
UVa/11729.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
1
2018-02-11T09:41:54.000Z
2018-02-11T09:41:54.000Z
UVa/11729.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
null
null
null
UVa/11729.cpp
tico88612/Solution-Note
31a9d220fd633c6920760707a07c9a153c2f76cc
[ "MIT" ]
null
null
null
#pragma GCC optimize ("O2") #include<bits/stdc++.h> #include<unistd.h> using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int,int> pi; #define _ ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define FZ(n) memset((n),0,sizeof(n)) #define FMO(n) memset((n),-1,sizeof(n)) #define F first #define S second #define PB push_back #define MP make_pair #define ALL(x) begin(x),end(x) #define SZ(x) ((int)(x).size()) #define REP(i,a,b) for (int i = a; i < b; i++) // Let's Fight! struct Item { int b, j; }; bool cmp(Item A, Item B){ return A.j > B.j; } int main() { _ int N, kase = 1; while(cin >> N){ if(N == 0) break; cout << "Case " << kase++ << ": "; int ans = 0; vector<Item> enter(N); REP(i, 0, N){ cin >> enter[i].b >> enter[i].j; } sort(ALL(enter), cmp); int s = 0; REP(i, 0, N){ s += enter[i].b; ans = max(ans, s + enter[i].j); } cout << ans << '\n'; } return 0; }
18.470588
57
0.572187
tico88612
e8e6cd2ab0d2f5f4055fb2af9d3bd347523fd41c
2,225
cpp
C++
tests/sectionmemorymanager.cpp
trailofbits/ebpf-common
4f0af3f41c04cafb3423825789f9bbaf686331cb
[ "Apache-2.0" ]
13
2020-01-07T22:56:16.000Z
2022-03-16T03:57:45.000Z
tests/sectionmemorymanager.cpp
trailofbits/ebpf-common
4f0af3f41c04cafb3423825789f9bbaf686331cb
[ "Apache-2.0" ]
null
null
null
tests/sectionmemorymanager.cpp
trailofbits/ebpf-common
4f0af3f41c04cafb3423825789f9bbaf686331cb
[ "Apache-2.0" ]
5
2021-11-05T01:44:25.000Z
2022-03-16T03:57:47.000Z
/* Copyright (c) 2019-present, Trail of Bits, Inc. All rights reserved. This source code is licensed in accordance with the terms specified in the LICENSE file found in the root directory of this source tree. */ #include <catch2/catch.hpp> #include <llvm/IR/IRBuilder.h> #include <tob/ebpf/sectionmemorymanager.h> namespace tob::ebpf { SCENARIO("Saving memory sections from the execution engine", "[SectionMemoryManager]") { MemorySectionMap memory_section_map; SectionMemoryManager section_memory_manager(memory_section_map); GIVEN("An initialized SectionMemoryManager object") { WHEN("code and data sections are allocated") { auto code_section = section_memory_manager.allocateCodeSection( 1024U, sizeof(void *), 0U, "FirstSection"); auto data_section = section_memory_manager.allocateDataSection( 1024U, sizeof(void *), 1U, "SecondSection", true); section_memory_manager.finalizeMemory(); THEN("section buffers are captured") { REQUIRE(code_section != nullptr); REQUIRE(data_section != nullptr); REQUIRE(memory_section_map.size() == 2U); auto first_section_it = memory_section_map.find("FirstSection"); REQUIRE(first_section_it != memory_section_map.end()); auto second_section_it = memory_section_map.find("SecondSection"); REQUIRE(second_section_it != memory_section_map.end()); const auto &generated_code_section = first_section_it->second; const auto &generated_data_section = second_section_it->second; REQUIRE(generated_code_section.type == MemorySection::Type::Code); REQUIRE(generated_data_section.type == MemorySection::Type::Data); REQUIRE(generated_code_section.read_only == false); REQUIRE(generated_data_section.read_only == true); REQUIRE(generated_code_section.alignment == 8U); REQUIRE(generated_data_section.alignment == 8U); REQUIRE(generated_code_section.id == 0U); REQUIRE(generated_data_section.id == 1U); REQUIRE(generated_code_section.data.size() == 1024U); REQUIRE(generated_data_section.data.size() == 1024U); } } } } } // namespace tob::ebpf
33.712121
74
0.706517
trailofbits
e8ec852a0be7a394e71c7fc1874ec7287182ab69
1,338
cpp
C++
Source/Reikonoids/Actors/RSpawner.cpp
gunstarpl/Reikonoids
55496bed915aec8c42048c9257b1050fd360b006
[ "MIT", "Unlicense" ]
null
null
null
Source/Reikonoids/Actors/RSpawner.cpp
gunstarpl/Reikonoids
55496bed915aec8c42048c9257b1050fd360b006
[ "MIT", "Unlicense" ]
null
null
null
Source/Reikonoids/Actors/RSpawner.cpp
gunstarpl/Reikonoids
55496bed915aec8c42048c9257b1050fd360b006
[ "MIT", "Unlicense" ]
null
null
null
#include "RSpawner.h" #include "../Gameplay/RSpawnDirector.h" ARSpawner::ARSpawner() = default; ARSpawner::~ARSpawner() = default; void ARSpawner::SetupDeferredSpawnRegistration(URSpawnDirector* InSpawnDirector, TArray<AActor*>* InPopulation) { check(InSpawnDirector); check(InPopulation); SpawnDirector = InSpawnDirector; Population = InPopulation; } void ARSpawner::BeginPlay() { Super::BeginPlay(); // Calculate total weight for list of entries. float WeightSum = 0.0f; for(const auto& Entry : Entries) { WeightSum += FMath::Max(0.0f, Entry.Weight); } // Spawn random entry from the list. float WeightRandom = FMath::RandRange(0.0f, WeightSum); float WeightProbe = 0.0f; for(const auto& Entry : Entries) { if(WeightRandom <= WeightProbe + Entry.Weight) { // Spawn actor definition. FActorSpawnParameters SpawnParams; AActor* SpawnedActor = GetWorld()->SpawnActor<AActor>(Entry.Class, GetActorTransform(), SpawnParams); // Register spawned actor if needed. if(SpawnedActor && SpawnDirector) { Population->Add(SpawnedActor); } break; } WeightProbe += Entry.Weight; } // Destroy spawner. Destroy(); }
23.892857
113
0.622571
gunstarpl
e8edf9b28b5f4dd722ee76047279574f075b2092
13,129
cpp
C++
Test/Test-FHE.cpp
asifmallik/SCALE-MAMBA
80db831818b55b7675dd549920b5fb096db4321f
[ "BSD-2-Clause" ]
null
null
null
Test/Test-FHE.cpp
asifmallik/SCALE-MAMBA
80db831818b55b7675dd549920b5fb096db4321f
[ "BSD-2-Clause" ]
null
null
null
Test/Test-FHE.cpp
asifmallik/SCALE-MAMBA
80db831818b55b7675dd549920b5fb096db4321f
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (c) 2017, The University of Bristol, Senate House, Tyndall Avenue, Bristol, BS8 1TH, United Kingdom. Copyright (c) 2020, COSIC-KU Leuven, Kasteelpark Arenberg 10, bus 2452, B-3001 Leuven-Heverlee, Belgium. All rights reserved */ #include "FHE/FFT.h" #include "FHE/FHE_Keys.h" #include "FHE/FHE_Params.h" #include "FHE/Rq_Element.h" /* Tests the FHE code */ extern bigint make_prime(int lg2, int N, const bigint &q= 0, const bigint &x= 0); void Test_FHE(const Ring &R, const FFT_Data &PD, const bigint &p0, const bigint &p1, int hwt) { FHE_Params params; // Use small HwT as ring dimension is small in these test examples params.set(R, p0, p1, hwt, false); bigint pr= PD.get_prime(); FHE_SK sk(params, pr); FHE_PK pk(params, pr); cout << "Plaintext = " << pr << endl; cout << "Root = "; PD.get_root(0).output(cout, PD.get_prD(), true); cout << endl; cout << "p0 = " << p0 << endl; cout << "p1 = " << p1 << endl; bool small= (pr < 1000); PRNG G; unsigned char seed[SEED_SIZE]; memset(seed, 0, SEED_SIZE); G.SetSeedFromRandom(seed); KeyGen(pk, sk, G); Rq_Element secret= sk.s(); if (small) { cout << "sk : "; sk.s().output(cout, true); cout << endl; cout << "pk : a = "; pk.a().output(cout, true); cout << endl; cout << " b = "; pk.b().output(cout, true); cout << endl; } // Make a random message Plaintext mess(PD); mess.randomize(G); if (small) { cout << "Plaintext : " << mess << endl; } Random_Coins rc(params); rc.generate(G); if (small) { cout << "Random Coins : "; rc.output(cout, true); cout << endl; } Ciphertext c(params); pk.encrypt(c, mess, rc); if (small) { cout << "Ciphertext : "; c.output(cout, true); cout << endl; } Plaintext ans(PD); c.Scale(pr); sk.decrypt(ans, c); if (small) { cout << "Plaintext : " << ans << endl; } if (ans != mess) { cout << "Invalid decryption" << endl; abort(); } cout << "\nTesting Arithmetic\n" << endl; Plaintext m1(PD), m2(PD), m3(PD), m4(PD); m1.randomize(G); m2.randomize(G); m3.randomize(G); if (small) { cout << "m1=" << m1 << endl; cout << "m2=" << m2 << endl; cout << "m3=" << m3 << endl; } // Testing to/from polys vector<bigint> te= m1.get_poly(); m4.set_poly(te); if (m1 != m4) { cout << "Invalid conversion" << endl; abort(); } cout << "pr= " << pr << endl; Ciphertext c1(params), c2(params), c3(params), c4(params); rc.generate(G); pk.encrypt(c1, m1, rc); if (small) { cout << "m1 encrypted with rc=\n"; rc.output(cout, true); cout << endl; cout << "Giving ciphertext \n"; c1.output(cout, true); cout << endl; } rc.generate(G); pk.encrypt(c2, m2, rc); if (small) { cout << "m2 encrypted with rc=\n"; rc.output(cout, true); cout << endl; cout << "Giving ciphertext \n"; c2.output(cout, true); cout << endl; } rc.generate(G); pk.encrypt(c3, m3, rc); if (small) { cout << "m3 encrypted with rc=\n"; rc.output(cout, true); cout << endl; cout << "Giving ciphertext \n"; c3.output(cout, true); cout << endl; } c4= c1; c4.Scale(pr); sk.decrypt(ans, c4); if (ans != m1) { cout << "Invalid decryption 1" << endl; abort(); } c4= c2; c4.Scale(pr); sk.decrypt(ans, c4); if (ans != m2) { cout << "Invalid decryption 2" << endl; abort(); } c4= c3; c4.Scale(pr); sk.decrypt(ans, c4); if (ans != m3) { cout << "Invalid decryption 3" << endl; abort(); } cout << "m1+m2 testing" << endl; m1.from_poly(); m2.from_poly(); add(m4, m1, m2); add(c4, c1, c2); c4.Scale(pr); sk.decrypt(ans, c4); if (ans != m4) { cout << "Invalid decryption 4" << endl; abort(); } cout << "m1*m2 testing" << endl; if (small) { cout << "m1=\n"; m1.output(cout); cout << "m2=\n"; m2.output(cout); } mul(m1, m1, m2); if (small) { cout << "m1*m2 = "; m1.output(cout); cout << endl; } mul(c1, c1, c2, pk); c4= c1; sk.decrypt(ans, c4); if (small) { cout << "ans = "; ans.output(cout); } if (ans != m1) { cout << "Invalid decryption 5" << endl; abort(); } cout << "m1*m2+m3 testing " << endl; m1.to_poly(); add(m1, m1, m3); c3.Scale(pr); add(c1, c1, c3); c1.Scale(pr); sk.decrypt(ans, c1); if (ans != m1) { cout << "Invalid decryption 6" << endl; abort(); } } /* fast=true implies dont bother checking multiply as it takes ages */ void Test_Ring_Element(int num, const FFT_Data &FFTD, bool fast) { cout << "\nIn Test_Ring_Element" << endl; int i; double start, stop; vector<Ring_Element> a(num, FFTD), b(num, FFTD), c0(num, FFTD), c1(num, FFTD), d0(num, FFTD), d1(num, FFTD), ao(num, FFTD), bo(num, FFTD); Ring_Element temp(FFTD); PRNG G; G.ReSeed(0); start= clock(); for (i= 0; i < num; i++) { a[i].randomize(G); b[i].randomize(G); ao[i]= a[i]; bo[i]= b[i]; } stop= clock(); cout << "Randomize \t: " << (stop - start) / (num * CLOCKS_PER_SEC) << " seconds" << endl; start= clock(); for (i= 0; i < num; i++) { add(c0[i], a[i], b[i]); } stop= clock(); cout << "Addition \t: " << (stop - start) / (num * CLOCKS_PER_SEC) << " seconds" << endl; if (!fast) { start= clock(); for (i= 0; i < num; i++) { mul(d0[i], a[i], b[i]); } stop= clock(); cout << "Multiply \t: " << (stop - start) / (num * CLOCKS_PER_SEC) << " seconds" << endl; } start= clock(); for (i= 0; i < num; i++) { a[i].change_rep(evaluation); b[i].change_rep(evaluation); } stop= clock(); cout << "Change Rep \t: " << (stop - start) / (num * CLOCKS_PER_SEC) << " seconds" << endl; start= clock(); for (i= 0; i < num; i++) { add(c1[i], a[i], b[i]); } stop= clock(); cout << "Addition \t: " << (stop - start) / (num * CLOCKS_PER_SEC) << " seconds" << endl; start= clock(); for (i= 0; i < num; i++) { mul(d1[i], a[i], b[i]); } stop= clock(); cout << "Multiply \t: " << (stop - start) / (num * CLOCKS_PER_SEC) << " seconds" << endl; cout << "Checking..." << endl; for (i= 0; i < num; i++) { temp= c1[i]; c1[i].change_rep(polynomial); if (!c0[i].equals(c1[i])) { cout << "Error on addition entry " << i << endl; cout << "\t" << c0[i] << " " << c1[i] << endl; cout << "\t" << a[i] << " " << b[i] << endl; cout << "\t" << ao[i] << " " << bo[i] << endl; cout << "\t" << temp << endl; } if (!fast) { d1[i].change_rep(polynomial); if (!d0[i].equals(d1[i])) { cout << "Error on multiplication entry " << i << endl; cout << "\t" << d0[i] << " " << d1[i] << endl; } } } cout << "Checks done" << endl; } void Test_Rq_Element(int num, const vector<FFT_Data> &prd) { cout << "\nIn Test_Rq_Element" << endl; int i; double start, stop; vector<Rq_Element> a(num, prd), b(num, prd), c(num, prd); PRNG G; G.ReSeed(0); start= clock(); for (i= 0; i < num; i++) { a[i].randomize(G); b[i].randomize(G); } stop= clock(); cout << "Randomize \t: " << (stop - start) / (num * CLOCKS_PER_SEC) << " seconds" << endl; start= clock(); for (i= 0; i < num; i++) { add(c[i], a[i], b[i]); } stop= clock(); cout << "Addition \t: " << (stop - start) / (num * CLOCKS_PER_SEC) << " seconds" << endl; for (i= 0; i < num; i++) { a[i].lower_level(); b[i].lower_level(); } cout << "Lowered Level and Timing..." << endl; start= clock(); for (i= 0; i < num; i++) { add(c[i], a[i], b[i]); } stop= clock(); cout << "Addition \t: " << (stop - start) / (num * CLOCKS_PER_SEC) << " seconds" << endl; start= clock(); for (i= 0; i < num; i++) { mul(c[i], a[i], b[i]); } stop= clock(); cout << "Multiply \t: " << (stop - start) / (num * CLOCKS_PER_SEC) << " seconds" << endl; cout << "Checking Stuff" << endl; vector<bigint> va, vb, vc; for (i= 0; i < num; i++) { a[i].randomize(G, 1); b[i].randomize(G, 1); va= a[i].to_vec_bigint(); vb= b[i].to_vec_bigint(); add(c[i], a[i], b[i]); vc= c[i].to_vec_bigint(); bigint Q= a[i].get_modulus(); for (unsigned int j= 0; j < vc.size(); j++) { bigint te= (va[j] + vb[j] - vc[j]) % Q; if (te != 0) { cout << va[j] << " + "; cout << vb[j] << " = "; cout << vc[j] << " "; cout << "mod " << Q << endl; cout << a[i].level() << " " << b[i].level() << " " << c[i].level() << endl; exit(1); } } } /* Do test of mult by a power of X * Only run when degree is small */ cout << "Testing mult by powers of X" << endl; if (prd[0].phi_m() < 1024) { Rq_Element xx(prd), yy(prd); xx.assign_one(); cout << " xx = "; xx.output(cout, true); cout << endl; for (int i= 0; i < 2 * prd[0].phi_m(); i++) { mul_by_X_i(yy, xx, i); cout << i << " : "; yy.output(cout, true); cout << endl; } } } /* Tests power of two FFT routines */ void Test_2(const Ring &R, const Zp_Data &prD) { PRNG G; G.ReSeed(0); FFT_Data FFTD(R, prD); cout << "Testing correctness of FFT mod x^n + 1\n"; vector<modp> a(R.m()), b(R.phi_m()); for (unsigned int i= 0; i < R.phi_m(); i++) { a[i].randomize(G, prD); b[i]= a[i]; } a.resize(R.m()); FFT_Iter(a, R.m(), FFTD.get_root(0), prD); vector<modp> temp(R.phi_m()); for (unsigned int i= 0; i < R.phi_m(); i++) temp[i]= a[R.p(i)]; a= temp; FFT_Iter2(b, R.phi_m(), FFTD.get_root(0), prD); /* Check results match */ bigint ans; for (unsigned int j= 0; j < R.phi_m(); j++) { if (!areEqual(a[j], b[j], prD)) { cout << "Mismatch at position " << j << ":\n"; to_bigint(ans, a[j], prD); cout << "Standard FFT result: " << ans << endl; to_bigint(ans, b[j], prD); cout << "FFT mod x^n + 1 result: " << ans << endl; } } cout << "Testing performance\n"; int trials= 100; double time, rec_time= 0, iter_time= 0, mod_time= 0; vector<modp> test_data(R.m()); vector<modp> m_data(R.m()), phim_data(R.phi_m()); for (int i= 0; i < trials; i++) { for (unsigned int j= 0; j < R.m(); j++) { test_data[j].randomize(G, prD); } a= test_data; time= clock(); FFT(a, R.m(), FFTD.get_root(0), prD); rec_time+= clock() - time; a= test_data; time= clock(); FFT_Iter(a, R.m(), FFTD.get_root(0), prD); iter_time+= clock() - time; a= test_data; time= clock(); FFT_Iter2(a, R.phi_m(), FFTD.get_root(0), prD); mod_time+= clock() - time; } cout << "Recursive FFT, size " << R.m() << " : " << rec_time / trials << endl; cout << "Iterative FFT, size " << R.m() << " : " << iter_time / trials << endl; cout << "FFT mod x^n+1, size " << R.phi_m() << " : " << mod_time / trials << endl; } int main() { Ring Rg; int num= 500; int m= 1024; int size_q= 32; bigint q0= 1, q1; q0= (q0 << size_q) * m + 1; while (!probPrime(q0)) { q0+= m; } cout << "q0 = " << q0 << " : " << numBits(q0) << endl; q1= q0 + m; while (!probPrime(q1)) { q1+= m; } cout << "q1 = " << q1 << " : " << numBits(q1) << endl; Rg.initialize(m); Zp_Data prD0(q0); Zp_Data prD1(q1); // Test and time FFT Test_2(Rg, prD0); FFT_Data FFTD0(Rg, prD0); FFT_Data FFTD1(Rg, prD1); // Test and time Ring_Element Test_Ring_Element(num, FFTD0, false); vector<FFT_Data> FFTD(2); FFTD[0]= FFTD0; FFTD[1]= FFTD1; // Test and time Rq_Element Test_Rq_Element(num, FFTD); // Get some baby FHE parameters cout << "\n\nTesting Baby FHE parameters" << endl; unsigned int N= 4; bigint p= make_prime(10, N); bigint p0= make_prime(40, N); bigint p1= make_prime(45, N, p, p0); Rg.initialize(2 * N); gfp::init_field(p); FFT_Data PTD(Rg, gfp::get_ZpD()); Test_FHE(Rg, PTD, p0, p1, 1); // Get some bigger parameters cout << "\n\nTesting Main FHE parameters" << endl; unsigned int hwt= 64; p= 0; Generate_Parameters(N, p0, p1, p, 128, 3, TopGear, hwt); Rg.initialize(2 * N); gfp::init_field(p); PTD.init(Rg, gfp::get_ZpD()); Test_FHE(Rg, PTD, p0, p1, hwt); return 0; }
22.290323
110
0.490213
asifmallik
e8f1e57bd3b966e8a458c20f0264efc5656cce4a
4,803
cc
C++
src/blob_index_merge_operator_test.cc
DorianZheng/titan
03f9907355e8140442f0ab3fe44cbdda0f1d8a01
[ "Apache-2.0" ]
220
2019-11-30T02:33:05.000Z
2022-03-25T07:33:55.000Z
src/blob_index_merge_operator_test.cc
DorianZheng/titan
03f9907355e8140442f0ab3fe44cbdda0f1d8a01
[ "Apache-2.0" ]
112
2019-11-25T11:24:27.000Z
2022-03-30T08:11:41.000Z
src/blob_index_merge_operator_test.cc
DorianZheng/titan
03f9907355e8140442f0ab3fe44cbdda0f1d8a01
[ "Apache-2.0" ]
65
2019-12-16T15:26:50.000Z
2022-03-31T10:48:56.000Z
#include "test_util/testharness.h" #include "blob_index_merge_operator.h" namespace rocksdb { namespace titandb { std::string GenKey(int i) { char buffer[32]; snprintf(buffer, sizeof(buffer), "k-%08d", i); return buffer; } std::string GenValue(int i) { char buffer[32]; snprintf(buffer, sizeof(buffer), "v-%08d", i); return buffer; } BlobIndex GenBlobIndex(uint32_t i, uint32_t j = 0) { BlobIndex index; index.file_number = i; index.blob_handle.offset = j; index.blob_handle.size = 10; return index; } MergeBlobIndex GenMergeBlobIndex(BlobIndex src, uint32_t i, uint32_t j = 0) { MergeBlobIndex index; index.file_number = i; index.blob_handle.offset = j; index.blob_handle.size = 10; index.source_file_number = src.file_number; index.source_file_offset = src.blob_handle.offset; return index; } ValueType ToValueType(MergeOperator::MergeValueType value_type) { switch (value_type) { case MergeOperator::kDeletion: return kTypeDeletion; case MergeOperator::kValue: return kTypeValue; case MergeOperator::kBlobIndex: return kTypeBlobIndex; default: return kTypeValue; } } MergeOperator::MergeValueType ToMergeValueType(ValueType value_type) { switch (value_type) { case kTypeDeletion: case kTypeSingleDeletion: case kTypeRangeDeletion: return MergeOperator::kDeletion; case kTypeValue: return MergeOperator::kValue; case kTypeBlobIndex: return MergeOperator::kBlobIndex; default: return MergeOperator::kValue; } } class BlobIndexMergeOperatorTest : public testing::Test { public: std::string key_; ValueType value_type_{kTypeDeletion}; std::string value_; std::vector<std::string> operands_; std::shared_ptr<BlobIndexMergeOperator> merge_operator_; BlobIndexMergeOperatorTest() : key_("k"), merge_operator_(std::make_shared<BlobIndexMergeOperator>()) {} void Put(std::string value, ValueType type = kTypeValue) { value_ = value; value_type_ = type; operands_.clear(); } void Put(BlobIndex blob_index) { value_.clear(); blob_index.EncodeTo(&value_); value_type_ = kTypeBlobIndex; operands_.clear(); } void Merge(MergeBlobIndex blob_index) { std::string tmp; blob_index.EncodeTo(&tmp); operands_.emplace_back(tmp); } void Read(ValueType expect_type, std::string expect_value) { std::string tmp_result_string; Slice tmp_result_operand(nullptr, 0); MergeOperator::MergeValueType merge_type = ToMergeValueType(value_type_); Slice value = value_; std::vector<Slice> operands; for (auto& op : operands_) { operands.emplace_back(op); } const MergeOperator::MergeOperationInput merge_in( key_, merge_type, merge_type == MergeOperator::kDeletion ? nullptr : &value, operands, nullptr); MergeOperator::MergeOperationOutput merge_out(tmp_result_string, tmp_result_operand); ASSERT_EQ(true, merge_operator_->FullMergeV2(merge_in, &merge_out)); ASSERT_EQ(true, merge_out.new_type != MergeOperator::kDeletion); if (merge_out.new_type == merge_type) { ASSERT_EQ(expect_type, value_type_); } else { ASSERT_EQ(expect_type, ToValueType(merge_out.new_type)); } if (tmp_result_operand.data()) { ASSERT_EQ(expect_value, tmp_result_operand); } else { ASSERT_EQ(expect_value, tmp_result_string); } } void Clear() { value_type_ = kTypeDeletion; value_.clear(); operands_.clear(); } }; TEST_F(BlobIndexMergeOperatorTest, KeepBaseValue) { // [1] [2] (1->3) Put(GenBlobIndex(2)); Merge(GenMergeBlobIndex(GenBlobIndex(1), 3)); std::string value; GenBlobIndex(2).EncodeTo(&value); Read(kTypeBlobIndex, value); // [v] (1->2) Clear(); Put(GenValue(1)); Merge(GenMergeBlobIndex(GenBlobIndex(1), 2)); Read(kTypeValue, GenValue(1)); } TEST_F(BlobIndexMergeOperatorTest, KeepLatestMerge) { // [1] (1->2) (3->4) (2->5) Put(GenBlobIndex(1)); Merge(GenMergeBlobIndex(GenBlobIndex(1), 2)); Merge(GenMergeBlobIndex(GenBlobIndex(3), 4)); Merge(GenMergeBlobIndex(GenBlobIndex(2), 5)); std::string value; GenBlobIndex(5).EncodeTo(&value); Read(kTypeBlobIndex, value); } TEST_F(BlobIndexMergeOperatorTest, Delete) { // [delete] (0->1) Merge(GenMergeBlobIndex(GenBlobIndex(0), 1)); std::string value; BlobIndex::EncodeDeletionMarkerTo(&value); Read(kTypeBlobIndex, value); // [deletion marker] (0->1) Clear(); Put(value, kTypeBlobIndex); Merge(GenMergeBlobIndex(GenBlobIndex(0), 1)); Read(kTypeBlobIndex, value); } } // namespace titandb } // namespace rocksdb int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
26.535912
77
0.694149
DorianZheng
e8f2817da1ba7c8fd13adac90f6367724b6524c0
273
hpp
C++
include/pct/util.hpp
IllinoisStateGeologicalSurvey/p_point2grid
8aad94f1d606143ef287944f30f6815c328074ba
[ "BSD-4-Clause" ]
1
2020-11-25T21:26:25.000Z
2020-11-25T21:26:25.000Z
include/pct/util.hpp
IllinoisStateGeologicalSurvey/p_point2grid
8aad94f1d606143ef287944f30f6815c328074ba
[ "BSD-4-Clause" ]
null
null
null
include/pct/util.hpp
IllinoisStateGeologicalSurvey/p_point2grid
8aad94f1d606143ef287944f30f6815c328074ba
[ "BSD-4-Clause" ]
null
null
null
#ifndef UTIL_HPP #define UTIL_HPP double randomVal(int range, int min); void process_mem_usage(double& vm_usage, double& resident_set); double to_degrees(double radians); void compareMin(double* mins, double* tmp); void compareMax(double* maxs, double* tmp); #endif
17.0625
63
0.769231
IllinoisStateGeologicalSurvey
e8f5fbc6a1e611008c6871c95799f4fcd1e1ea75
1,904
cpp
C++
C++/Test/src/Test.cpp
zhenkunhe/Developer-Tutorial
6e4e4e36364fd8081a68ebf43bf6ab433add613e
[ "MIT" ]
null
null
null
C++/Test/src/Test.cpp
zhenkunhe/Developer-Tutorial
6e4e4e36364fd8081a68ebf43bf6ab433add613e
[ "MIT" ]
null
null
null
C++/Test/src/Test.cpp
zhenkunhe/Developer-Tutorial
6e4e4e36364fd8081a68ebf43bf6ab433add613e
[ "MIT" ]
null
null
null
/* first include the standard headers that we're likely to need */ #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xresource.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char ** argv){ int screen_num, width, height; unsigned long background, border; Window win; XEvent ev; Display *dpy; /* First connect to the display server, as specified in the DISPLAY environment variable. */ dpy = XOpenDisplay(":0.0"); if (!dpy) {fprintf(stderr, "unable to connect to display");return 7;} /* these are macros that pull useful data out of the display object */ /* we use these bits of info enough to want them in their own variables */ screen_num = DefaultScreen(dpy); background = BlackPixel(dpy, screen_num); border = WhitePixel(dpy, screen_num); width = 40; /* start with a small window */ height = 40; win = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), /* display, parent */ 0,0, /* x, y: the window manager will place the window elsewhere */ width, height, /* width, height */ 2, border, /* border width & colour, unless you have a window manager */ background); /* background colour */ /* tell the display server what kind of events we would like to see */ XSelectInput(dpy, win, ButtonPressMask|StructureNotifyMask ); /* okay, put the window on the screen, please */ XMapWindow(dpy, win); /* as each event that we asked about occurs, we respond. In this * case we note if the window's shape changed, and exit if a button * is pressed inside the window */ while(1){ XNextEvent(dpy, &ev); switch(ev.type){ case ConfigureNotify: if (width != ev.xconfigure.width || height != ev.xconfigure.height) { width = ev.xconfigure.width; height = ev.xconfigure.height; printf("Size changed to: %d by %d", width, height); } break; case ButtonPress: XCloseDisplay(dpy); return 0; } } }
30.709677
77
0.690651
zhenkunhe
e8fc2d442eceb7122d106f6f8eea560a2d240e7b
3,833
cpp
C++
src_main/gameui/CvarToggleCheckButton.cpp
ArcadiusGFN/SourceEngine2007
51cd6d4f0f9ed901cb9b61456eb621a50ce44f55
[ "bzip2-1.0.6" ]
25
2018-02-28T15:04:42.000Z
2021-08-16T03:49:00.000Z
src_main/gameui/CvarToggleCheckButton.cpp
ArcadiusGFN/SourceEngine2007
51cd6d4f0f9ed901cb9b61456eb621a50ce44f55
[ "bzip2-1.0.6" ]
1
2019-09-20T11:06:03.000Z
2019-09-20T11:06:03.000Z
src_main/gameui/CvarToggleCheckButton.cpp
ArcadiusGFN/SourceEngine2007
51cd6d4f0f9ed901cb9b61456eb621a50ce44f55
[ "bzip2-1.0.6" ]
9
2019-07-31T11:58:20.000Z
2021-08-31T11:18:15.000Z
// Copyright © 1996-2018, Valve Corporation, All rights reserved. #include "CvarToggleCheckButton.h" #include "EngineInterface.h" #include "IGameUIFuncs.h" #include "tier1/KeyValues.h" #include "tier1/convar.h" #include "vgui/IVGui.h" #include "tier0/include/memdbgon.h" using namespace vgui; vgui::Panel *CvarToggleCheckButton_Factory() { return new CCvarToggleCheckButton(NULL, NULL, "CvarToggleCheckButton", NULL); } DECLARE_BUILD_FACTORY_CUSTOM(CCvarToggleCheckButton, CvarToggleCheckButton_Factory); CCvarToggleCheckButton::CCvarToggleCheckButton(Panel *parent, const char *panelName, const char *text, char const *cvarname) : CheckButton(parent, panelName, text) { m_pszCvarName = cvarname ? _strdup(cvarname) : NULL; if (m_pszCvarName) { Reset(); } AddActionSignalTarget(this); } CCvarToggleCheckButton::~CCvarToggleCheckButton() { if (m_pszCvarName) { free(m_pszCvarName); } } void CCvarToggleCheckButton::Paint() { if (!m_pszCvarName || !m_pszCvarName[0]) { BaseClass::Paint(); return; } // Look up current value // bool value = engine->pfnGetCvarFloat( m_pszCvarName ) > 0.0f ? true : // false; ConVarRef var(m_pszCvarName); if (!var.IsValid()) return; bool value = var.GetBool(); if (value != m_bStartValue) // if ( value != IsSelected() ) { SetSelected(value); m_bStartValue = value; } BaseClass::Paint(); } void CCvarToggleCheckButton::ApplyChanges() { if (!m_pszCvarName || !m_pszCvarName[0]) return; m_bStartValue = IsSelected(); // engine->Cvar_SetValue( m_pszCvarName, m_bStartValue ? 1.0f : 0.0f ); ConVarRef var(m_pszCvarName); var.SetValue(m_bStartValue); } void CCvarToggleCheckButton::Reset() { // m_bStartValue = engine->pfnGetCvarFloat( m_pszCvarName ) > 0.0f ? true : // false; if (!m_pszCvarName || !m_pszCvarName[0]) return; ConVarRef var(m_pszCvarName); if (!var.IsValid()) return; m_bStartValue = var.GetBool(); SetSelected(m_bStartValue); } bool CCvarToggleCheckButton::HasBeenModified() { return IsSelected() != m_bStartValue; } //----------------------------------------------------------------------------- // Purpose: // Input : *panel - //----------------------------------------------------------------------------- void CCvarToggleCheckButton::SetSelected(bool state) { BaseClass::SetSelected(state); if (!m_pszCvarName || !m_pszCvarName[0]) return; /* // Look up current value bool value = state; engine->Cvar_SetValue( m_pszCvarName, value ? 1.0f : 0.0f );*/ } //----------------------------------------------------------------------------- void CCvarToggleCheckButton::OnButtonChecked() { if (HasBeenModified()) { PostActionSignal(new KeyValues("ControlModified")); } } //----------------------------------------------------------------------------- void CCvarToggleCheckButton::ApplySettings(KeyValues *inResourceData) { BaseClass::ApplySettings(inResourceData); const char *cvarName = inResourceData->GetString("cvar_name", ""); const char *cvarValue = inResourceData->GetString("cvar_value", ""); if (Q_stricmp(cvarName, "") == 0) return; // Doesn't have cvar set up in res file, must have been constructed // with it. if (m_pszCvarName) free(m_pszCvarName); // got a "", not a NULL from the create-control call m_pszCvarName = cvarName ? _strdup(cvarName) : NULL; if (Q_stricmp(cvarValue, "1") == 0) m_bStartValue = true; else m_bStartValue = false; const ConVar *var = cvar->FindVar(m_pszCvarName); if (var) { if (var->GetBool()) SetSelected(true); else SetSelected(false); } }
27.775362
80
0.605531
ArcadiusGFN
330080452a453af5d6fbe6e52f460d273b731e68
5,444
cpp
C++
schema/SubscriptionObject.cpp
microsoft/gqlmapi
953f8c0a1c4d069c34716dfe97ede4d3ff1ddcaa
[ "MIT" ]
3
2021-02-11T15:38:51.000Z
2021-12-29T15:00:13.000Z
schema/SubscriptionObject.cpp
microsoft/gqlmapi
953f8c0a1c4d069c34716dfe97ede4d3ff1ddcaa
[ "MIT" ]
null
null
null
schema/SubscriptionObject.cpp
microsoft/gqlmapi
953f8c0a1c4d069c34716dfe97ede4d3ff1ddcaa
[ "MIT" ]
3
2021-02-14T13:50:36.000Z
2021-02-14T13:50:49.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // WARNING! Do not edit this file manually, your changes will be overwritten. #include "SubscriptionObject.h" #include "ItemChangeObject.h" #include "FolderChangeObject.h" #include "graphqlservice/internal/Schema.h" #include "graphqlservice/introspection/IntrospectionSchema.h" #include <algorithm> #include <functional> #include <sstream> #include <stdexcept> #include <unordered_map> using namespace std::literals; namespace graphql::mapi { namespace object { Subscription::Subscription(std::unique_ptr<Concept>&& pimpl) noexcept : service::Object{ getTypeNames(), getResolvers() } , _pimpl { std::move(pimpl) } { } service::TypeNames Subscription::getTypeNames() const noexcept { return { R"gql(Subscription)gql"sv }; } service::ResolverMap Subscription::getResolvers() const noexcept { return { { R"gql(items)gql"sv, [this](service::ResolverParams&& params) { return resolveItems(std::move(params)); } }, { R"gql(__typename)gql"sv, [this](service::ResolverParams&& params) { return resolve_typename(std::move(params)); } }, { R"gql(subFolders)gql"sv, [this](service::ResolverParams&& params) { return resolveSubFolders(std::move(params)); } }, { R"gql(rootFolders)gql"sv, [this](service::ResolverParams&& params) { return resolveRootFolders(std::move(params)); } } }; } void Subscription::beginSelectionSet(const service::SelectionSetParams& params) const { _pimpl->beginSelectionSet(params); } void Subscription::endSelectionSet(const service::SelectionSetParams& params) const { _pimpl->endSelectionSet(params); } service::AwaitableResolver Subscription::resolveItems(service::ResolverParams&& params) const { auto argFolderId = service::ModifiedArgument<mapi::ObjectId>::require("folderId", params.arguments); std::unique_lock resolverLock(_resolverMutex); auto directives = std::move(params.fieldDirectives); auto result = _pimpl->getItems(service::FieldParams(service::SelectionSetParams{ params }, std::move(directives)), std::move(argFolderId)); resolverLock.unlock(); return service::ModifiedResult<ItemChange>::convert<service::TypeModifier::List>(std::move(result), std::move(params)); } service::AwaitableResolver Subscription::resolveSubFolders(service::ResolverParams&& params) const { auto argParentFolderId = service::ModifiedArgument<mapi::ObjectId>::require("parentFolderId", params.arguments); std::unique_lock resolverLock(_resolverMutex); auto directives = std::move(params.fieldDirectives); auto result = _pimpl->getSubFolders(service::FieldParams(service::SelectionSetParams{ params }, std::move(directives)), std::move(argParentFolderId)); resolverLock.unlock(); return service::ModifiedResult<FolderChange>::convert<service::TypeModifier::List>(std::move(result), std::move(params)); } service::AwaitableResolver Subscription::resolveRootFolders(service::ResolverParams&& params) const { auto argStoreId = service::ModifiedArgument<response::IdType>::require("storeId", params.arguments); std::unique_lock resolverLock(_resolverMutex); auto directives = std::move(params.fieldDirectives); auto result = _pimpl->getRootFolders(service::FieldParams(service::SelectionSetParams{ params }, std::move(directives)), std::move(argStoreId)); resolverLock.unlock(); return service::ModifiedResult<FolderChange>::convert<service::TypeModifier::List>(std::move(result), std::move(params)); } service::AwaitableResolver Subscription::resolve_typename(service::ResolverParams&& params) const { return service::ModifiedResult<std::string>::convert(std::string{ R"gql(Subscription)gql" }, std::move(params)); } } // namespace object void AddSubscriptionDetails(const std::shared_ptr<schema::ObjectType>& typeSubscription, const std::shared_ptr<schema::Schema>& schema) { typeSubscription->AddFields({ schema::Field::Make(R"gql(items)gql"sv, R"md(Get updates on items in a folder.)md"sv, std::nullopt, schema->WrapType(introspection::TypeKind::NON_NULL, schema->WrapType(introspection::TypeKind::LIST, schema->WrapType(introspection::TypeKind::NON_NULL, schema->LookupType(R"gql(ItemChange)gql"sv)))), { schema::InputValue::Make(R"gql(folderId)gql"sv, R"md(ID of the folder)md"sv, schema->WrapType(introspection::TypeKind::NON_NULL, schema->LookupType(R"gql(ObjectId)gql"sv)), R"gql()gql"sv) }), schema::Field::Make(R"gql(subFolders)gql"sv, R"md(Get updates on sub-folders of a folder.)md"sv, std::nullopt, schema->WrapType(introspection::TypeKind::NON_NULL, schema->WrapType(introspection::TypeKind::LIST, schema->WrapType(introspection::TypeKind::NON_NULL, schema->LookupType(R"gql(FolderChange)gql"sv)))), { schema::InputValue::Make(R"gql(parentFolderId)gql"sv, R"md(ID of the parent folder)md"sv, schema->WrapType(introspection::TypeKind::NON_NULL, schema->LookupType(R"gql(ObjectId)gql"sv)), R"gql()gql"sv) }), schema::Field::Make(R"gql(rootFolders)gql"sv, R"md(Get updates on the root folders of a store.)md"sv, std::nullopt, schema->WrapType(introspection::TypeKind::NON_NULL, schema->WrapType(introspection::TypeKind::LIST, schema->WrapType(introspection::TypeKind::NON_NULL, schema->LookupType(R"gql(FolderChange)gql"sv)))), { schema::InputValue::Make(R"gql(storeId)gql"sv, R"md(ID of the store)md"sv, schema->WrapType(introspection::TypeKind::NON_NULL, schema->LookupType(R"gql(ID)gql"sv)), R"gql()gql"sv) }) }); } } // namespace graphql::mapi
47.754386
321
0.762675
microsoft
3303642dcb7f4f9aa63d4178b985eb0bfb195b64
3,573
cc
C++
android_webview/browser/js_java_interaction/js_to_java_messaging.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
android_webview/browser/js_java_interaction/js_to_java_messaging.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
android_webview/browser/js_java_interaction/js_to_java_messaging.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "android_webview/browser/js_java_interaction/js_to_java_messaging.h" #include "android_webview/browser/aw_contents.h" #include "android_webview/browser_jni_headers/WebMessageListenerHolder_jni.h" #include "base/android/jni_android.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/stl_util.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "url/origin.h" #include "url/url_util.h" namespace android_webview { JsToJavaMessaging::JsToJavaMessaging( content::RenderFrameHost* render_frame_host, mojo::PendingAssociatedReceiver<mojom::JsToJavaMessaging> receiver, base::android::ScopedJavaGlobalRef<jobject> listener_ref, const AwOriginMatcher& origin_matcher) : render_frame_host_(render_frame_host), listener_ref_(listener_ref), origin_matcher_(origin_matcher) { receiver_.Bind(std::move(receiver)); } JsToJavaMessaging::~JsToJavaMessaging() {} void JsToJavaMessaging::PostMessage( const base::string16& message, std::vector<mojo::ScopedMessagePipeHandle> ports) { DCHECK(render_frame_host_); content::WebContents* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host_); if (!web_contents) return; // |source_origin| has no race with this PostMessage call, because of // associated mojo channel, the committed origin message and PostMessage are // in sequence. url::Origin source_origin = render_frame_host_->GetLastCommittedOrigin(); if (!origin_matcher_.Matches(source_origin)) return; std::vector<int> int_ports(ports.size(), MOJO_HANDLE_INVALID /* 0 */); for (size_t i = 0; i < ports.size(); ++i) { int_ports[i] = ports[i].release().value(); } // We want to pass a string "null" for local file schemes, to make it // consistent to the Blink side SecurityOrigin serialization. When both // setAllow{File,Universal}AccessFromFileURLs are false, Blink::SecurityOrigin // will be serialized as string "null" for local file schemes, but when // setAllowFileAccessFromFileURLs is true, Blink::SecurityOrigin will be // serialized as the scheme, which will be inconsistentt to this place. In // this case we want to let developer to know that local files are not safe, // so we still pass "null". std::string origin_string = base::Contains(url::GetLocalSchemes(), source_origin.scheme()) ? "null" : source_origin.Serialize(); JNIEnv* env = base::android::AttachCurrentThread(); Java_WebMessageListenerHolder_onPostMessage( env, listener_ref_, base::android::ConvertUTF16ToJavaString(env, message), base::android::ConvertUTF8ToJavaString(env, origin_string), web_contents->GetMainFrame() == render_frame_host_, base::android::ToJavaIntArray(env, int_ports.data(), int_ports.size()), reply_proxy_->GetJavaPeer()); } void JsToJavaMessaging::SetJavaToJsMessaging( mojo::PendingAssociatedRemote<mojom::JavaToJsMessaging> java_to_js_messaging) { // A RenderFrame may inject JsToJavaMessaging in the JavaScript context more // than once because of reusing of RenderFrame. reply_proxy_ = std::make_unique<JsReplyProxy>(std::move(java_to_js_messaging)); } } // namespace android_webview
40.146067
96
0.755947
sarang-apps
33042e1e7909f668cfce6d4f35d9eb62033dac55
704
cpp
C++
TG/bookcodes/ch2/uva11427.cpp
Anyrainel/aoapc-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
3
2017-08-15T06:00:01.000Z
2018-12-10T09:05:53.000Z
TG/bookcodes/ch2/uva11427.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
null
null
null
TG/bookcodes/ch2/uva11427.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
2
2017-09-16T18:46:27.000Z
2018-05-22T05:42:03.000Z
// UVa11427 Expect the Expected // Rujia Liu #include<cstdio> #include<cmath> #include<cstring> const int maxn = 100 + 5; int main() { int T; scanf("%d", &T); for(int kase = 1; kase <= T; kase++) { int n, a, b; double d[maxn][maxn], p; scanf("%d/%d%d", &a, &b, &n); // 请注意scanf的技巧 p = (double)a/b; memset(d, 0, sizeof(d)); d[0][0] = 1.0; d[0][1] = 0.0; for(int i = 1; i <= n; i++) for(int j = 0; j*b <= a*i; j++) { // 等价于枚举满足j/i <= a/b的j,但避免了误差 d[i][j] = d[i-1][j]*(1-p); if(j) d[i][j] += d[i-1][j-1]*p; } double Q = 0.0; for(int j = 0; j*b <= a*n; j++) Q += d[n][j]; printf("Case #%d: %d\n", kase, (int)(1/Q)); } return 0; }
25.142857
69
0.458807
Anyrainel
33052d0be7ed7ac742149da372691f36c5c8989d
1,200
cpp
C++
serial/cli/program/dumpFW.cpp
cuauv/software
5ad4d52d603f81a7f254f365d9b0fe636d03a260
[ "BSD-3-Clause" ]
70
2015-11-16T18:04:01.000Z
2022-03-05T09:04:02.000Z
serial/cli/program/dumpFW.cpp
cuauv/software
5ad4d52d603f81a7f254f365d9b0fe636d03a260
[ "BSD-3-Clause" ]
1
2016-08-03T05:13:19.000Z
2016-08-03T06:19:39.000Z
serial/cli/program/dumpFW.cpp
cuauv/software
5ad4d52d603f81a7f254f365d9b0fe636d03a260
[ "BSD-3-Clause" ]
34
2015-12-15T17:29:23.000Z
2021-11-18T14:15:12.000Z
#include <iostream> #include <fstream> #include "loader/MemoryImage.h" #include "loader/AUVFirmware.h" #include "loader/hex.h" #include "loader/auvfw.h" #include "../Command.h" namespace cuauv { namespace serial { namespace cli { static int dumpFW_run(std::map<std::string, std::string> args) { try { std::ifstream fwin(args["fw"]); AUVFirmware fw = loadAUVfw(fwin); std::cout << "Device name: " << fw.deviceName() << std::endl; std::cout << "Signature bytes: " << (int) fw.sig1(); std::cout << " " << (int) fw.sig2() << " " << (int) fw.sig3() << std::endl; std::cout << "Page size: " << fw.pageSize() << std::endl; std::ofstream hexOut(args["out"]); dumpHex(hexOut, fw.mem()); std::cout << "Memory image written to " << args["out"] << std::endl; } catch (std::exception& e) { std::cout << e.what() << std::endl; return 1; } return 0; } BEGIN_COMMAND_DEF(dumpFW, "Dump the contents of a firmware file", dumpFW_run) ARG_REQUIRED(fw, "The firmware to dump") ARG_REQUIRED(out, "The file to dump the hex-formatted memory image to") END_COMMAND_DEF() }}} // end namespace cuauv::serial::cli
28.571429
84
0.6025
cuauv
33053cfbc4a98de66bd3a032235561cd08b8c1b5
6,286
cc
C++
chromium/components/html_viewer/web_clipboard_impl.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/components/html_viewer/web_clipboard_impl.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/components/html_viewer/web_clipboard_impl.cc
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/html_viewer/web_clipboard_impl.h" #include <stddef.h> #include <utility> #include "base/bind.h" #include "components/html_viewer/blink_basic_type_converters.h" using mojo::Array; using mojo::Clipboard; using mojo::Map; using mojo::String; namespace html_viewer { namespace { void CopyUint64(uint64_t* output, uint64_t input) { *output = input; } void CopyWebString(blink::WebString* output, const Array<uint8_t>& input) { // blink does not differentiate between the requested data type not existing // and the empty string. if (input.is_null()) { output->reset(); } else { *output = blink::WebString::fromUTF8( reinterpret_cast<const char*>(&input.front()), input.size()); } } void CopyURL(blink::WebURL* pageURL, const Array<uint8_t>& input) { if (input.is_null()) { *pageURL = blink::WebURL(); } else { *pageURL = GURL(std::string(reinterpret_cast<const char*>(&input.front()), input.size())); } } void CopyVectorString(std::vector<std::string>* output, const Array<String>& input) { *output = input.To<std::vector<std::string> >(); } template <typename T, typename U> bool Contains(const std::vector<T>& v, const U& item) { return std::find(v.begin(), v.end(), item) != v.end(); } const char kMimeTypeWebkitSmartPaste[] = "chromium/x-webkit-paste"; } // namespace WebClipboardImpl::WebClipboardImpl(mojo::ClipboardPtr clipboard) : clipboard_(std::move(clipboard)) {} WebClipboardImpl::~WebClipboardImpl() { } uint64_t WebClipboardImpl::sequenceNumber(Buffer buffer) { mojo::Clipboard::Type clipboard_type = ConvertBufferType(buffer); uint64_t number = 0; clipboard_->GetSequenceNumber(clipboard_type, base::Bind(&CopyUint64, &number)); // Force this to be synchronous. clipboard_.WaitForIncomingResponse(); return number; } bool WebClipboardImpl::isFormatAvailable(Format format, Buffer buffer) { Clipboard::Type clipboard_type = ConvertBufferType(buffer); std::vector<std::string> types; clipboard_->GetAvailableMimeTypes( clipboard_type, base::Bind(&CopyVectorString, &types)); // Force this to be synchronous. clipboard_.WaitForIncomingResponse(); switch (format) { case FormatPlainText: return Contains(types, Clipboard::MIME_TYPE_TEXT); case FormatHTML: return Contains(types, Clipboard::MIME_TYPE_HTML); case FormatSmartPaste: return Contains(types, kMimeTypeWebkitSmartPaste); case FormatBookmark: // This might be difficult. return false; } return false; } blink::WebVector<blink::WebString> WebClipboardImpl::readAvailableTypes( Buffer buffer, bool* contains_filenames) { Clipboard::Type clipboard_type = ConvertBufferType(buffer); std::vector<std::string> types; clipboard_->GetAvailableMimeTypes( clipboard_type, base::Bind(&CopyVectorString, &types)); // Force this to be synchronous. clipboard_.WaitForIncomingResponse(); // AFAICT, every instance of setting contains_filenames is false. *contains_filenames = false; blink::WebVector<blink::WebString> output(types.size()); for (size_t i = 0; i < types.size(); ++i) { output[i] = blink::WebString::fromUTF8(types[i]); } return output; } blink::WebString WebClipboardImpl::readPlainText(Buffer buffer) { Clipboard::Type type = ConvertBufferType(buffer); blink::WebString text; clipboard_->ReadMimeType(type, Clipboard::MIME_TYPE_TEXT, base::Bind(&CopyWebString, &text)); // Force this to be synchronous. clipboard_.WaitForIncomingResponse(); return text; } blink::WebString WebClipboardImpl::readHTML(Buffer buffer, blink::WebURL* page_url, unsigned* fragment_start, unsigned* fragment_end) { Clipboard::Type type = ConvertBufferType(buffer); blink::WebString html; clipboard_->ReadMimeType(type, Clipboard::MIME_TYPE_HTML, base::Bind(&CopyWebString, &html)); clipboard_.WaitForIncomingResponse(); *fragment_start = 0; *fragment_end = static_cast<unsigned>(html.length()); clipboard_->ReadMimeType(type, Clipboard::MIME_TYPE_URL, base::Bind(&CopyURL, page_url)); clipboard_.WaitForIncomingResponse(); return html; } blink::WebString WebClipboardImpl::readCustomData( Buffer buffer, const blink::WebString& mime_type) { Clipboard::Type clipboard_type = ConvertBufferType(buffer); blink::WebString data; clipboard_->ReadMimeType( clipboard_type, mime_type.utf8(), base::Bind(&CopyWebString, &data)); // Force this to be synchronous. clipboard_.WaitForIncomingResponse(); return data; } void WebClipboardImpl::writePlainText(const blink::WebString& plain_text) { Map<String, Array<uint8_t>> data; data[Clipboard::MIME_TYPE_TEXT] = Array<uint8_t>::From(plain_text); clipboard_->WriteClipboardData(Clipboard::TYPE_COPY_PASTE, std::move(data)); } void WebClipboardImpl::writeHTML(const blink::WebString& html_text, const blink::WebURL& source_url, const blink::WebString& plain_text, bool writeSmartPaste) { Map<String, Array<uint8_t>> data; data[Clipboard::MIME_TYPE_TEXT] = Array<uint8_t>::From(plain_text); data[Clipboard::MIME_TYPE_HTML] = Array<uint8_t>::From(html_text); data[Clipboard::MIME_TYPE_URL] = Array<uint8_t>::From(source_url.string()); if (writeSmartPaste) data[kMimeTypeWebkitSmartPaste] = Array<uint8_t>::From(blink::WebString()); clipboard_->WriteClipboardData(Clipboard::TYPE_COPY_PASTE, std::move(data)); } Clipboard::Type WebClipboardImpl::ConvertBufferType(Buffer buffer) { switch (buffer) { case BufferStandard: return Clipboard::TYPE_COPY_PASTE; case BufferSelection: return Clipboard::TYPE_SELECTION; } NOTREACHED(); return Clipboard::TYPE_COPY_PASTE; } } // namespace html_viewer
29.933333
79
0.685969
wedataintelligence
330afb3a3d486b1ff132ff3f026063f2f30b8737
13,826
cpp
C++
McEngine/src/Engine/Platform/HorizonSDLEnvironment.cpp
lwkobe/McEngine
c24dea65b9e6745391b073dd4521561e9808b1a3
[ "MIT" ]
1
2019-11-20T13:24:56.000Z
2019-11-20T13:24:56.000Z
McEngine/src/Engine/Platform/HorizonSDLEnvironment.cpp
lwkobe/McEngine
c24dea65b9e6745391b073dd4521561e9808b1a3
[ "MIT" ]
null
null
null
McEngine/src/Engine/Platform/HorizonSDLEnvironment.cpp
lwkobe/McEngine
c24dea65b9e6745391b073dd4521561e9808b1a3
[ "MIT" ]
null
null
null
//================ Copyright (c) 2019, PG, All rights reserved. =================// // // Purpose: nintendo switch SDL environment // // $NoKeywords: $nxsdlenv //===============================================================================// #ifdef __SWITCH__ #include "HorizonSDLEnvironment.h" #ifdef MCENGINE_FEATURE_SDL #include "Engine.h" #include "ConVar.h" #include "Mouse.h" #include "SoundEngine.h" #include "SDL.h" #include <switch.h> #include <dirent.h> #include <sys/stat.h> ConVar horizon_snd_chunk_size_docked("horizon_snd_chunk_size_docked", 512); ConVar horizon_snd_chunk_size_undocked("horizon_snd_chunk_size_undocked", 256); // HACKHACK: manual keyboard/mouse handling from sdl internals, until audio gets fixed, see https://github.com/devkitPro/SDL/commit/b91efb18a1a4752c03d56594b079aa804fe4e9ea // audio was broken here: https://github.com/devkitPro/SDL/commit/51d12c191cdc7eb2ea7acca3daaf5e714b436128 static const HidKeyboardScancode switch_scancodes[MCENGINE_HORIZON_SDL_NUM_SCANCODES_SWITCH] = { KBD_A, KBD_B, KBD_C, KBD_D, KBD_E, KBD_F, KBD_G, KBD_H, KBD_I, KBD_J, KBD_K, KBD_L, KBD_M, KBD_N, KBD_O, KBD_P, KBD_Q, KBD_R, KBD_S, KBD_T, KBD_U, KBD_V, KBD_W, KBD_X, KBD_Y, KBD_Z, KBD_1, KBD_2, KBD_3, KBD_4, KBD_5, KBD_6, KBD_7, KBD_8, KBD_9, KBD_0, KBD_ENTER, KBD_ESC, KBD_BACKSPACE, KBD_TAB, KBD_SPACE, KBD_MINUS, KBD_EQUAL, KBD_LEFTBRACE, KBD_RIGHTBRACE, KBD_BACKSLASH, KBD_HASHTILDE, KBD_SEMICOLON, KBD_APOSTROPHE, KBD_GRAVE, KBD_COMMA, KBD_DOT, KBD_SLASH, KBD_CAPSLOCK, KBD_F1, KBD_F2, KBD_F3, KBD_F4, KBD_F5, KBD_F6, KBD_F7, KBD_F8, KBD_F9, KBD_F10, KBD_F11, KBD_F12, KBD_SYSRQ, KBD_SCROLLLOCK, KBD_PAUSE, KBD_INSERT, KBD_HOME, KBD_PAGEUP, KBD_DELETE, KBD_END, KBD_PAGEDOWN, KBD_RIGHT, KBD_LEFT, KBD_DOWN, KBD_UP, KBD_NUMLOCK, KBD_KPSLASH, KBD_KPASTERISK, KBD_KPMINUS, KBD_KPPLUS, KBD_KPENTER, KBD_KP1, KBD_KP2, KBD_KP3, KBD_KP4, KBD_KP5, KBD_KP6, KBD_KP7, KBD_KP8, KBD_KP9, KBD_KP0, KBD_KPDOT, KBD_102ND, KBD_COMPOSE, KBD_POWER, KBD_KPEQUAL, KBD_F13, KBD_F14, KBD_F15, KBD_F16, KBD_F17, KBD_F18, KBD_F19, KBD_F20, KBD_F21, KBD_F22, KBD_F23, KBD_F24, KBD_OPEN, KBD_HELP, KBD_PROPS, KBD_FRONT, KBD_STOP, KBD_AGAIN, KBD_UNDO, KBD_CUT, KBD_COPY, KBD_PASTE, KBD_FIND, KBD_MUTE, KBD_VOLUMEUP, KBD_VOLUMEDOWN, KBD_CAPSLOCK_ACTIVE, KBD_NUMLOCK_ACTIVE, KBD_SCROLLLOCK_ACTIVE, KBD_KPCOMMA, KBD_KPLEFTPAREN, KBD_KPRIGHTPAREN, KBD_LEFTCTRL, KBD_LEFTSHIFT, KBD_LEFTALT, KBD_LEFTMETA, KBD_RIGHTCTRL, KBD_RIGHTSHIFT, KBD_RIGHTALT, KBD_RIGHTMETA, KBD_MEDIA_PLAYPAUSE, KBD_MEDIA_STOPCD, KBD_MEDIA_PREVIOUSSONG, KBD_MEDIA_NEXTSONG, KBD_MEDIA_EJECTCD, KBD_MEDIA_VOLUMEUP, KBD_MEDIA_VOLUMEDOWN, KBD_MEDIA_MUTE, KBD_MEDIA_WWW, KBD_MEDIA_BACK, KBD_MEDIA_FORWARD, KBD_MEDIA_STOP, KBD_MEDIA_FIND, KBD_MEDIA_SCROLLUP, KBD_MEDIA_SCROLLDOWN, KBD_MEDIA_EDIT, KBD_MEDIA_SLEEP, KBD_MEDIA_COFFEE, KBD_MEDIA_REFRESH, KBD_MEDIA_CALC }; ConVar *HorizonSDLEnvironment::m_mouse_sensitivity_ref = NULL; uint8_t HorizonSDLEnvironment::locks = 0; bool HorizonSDLEnvironment::keystate[] = {0}; uint64_t HorizonSDLEnvironment::prev_buttons = 0; HorizonSDLEnvironment::HorizonSDLEnvironment() : SDLEnvironment(NULL) { if (m_mouse_sensitivity_ref == NULL) m_mouse_sensitivity_ref = convar->getConVarByName("mouse_sensitivity"); m_bDocked = false; m_fLastMouseDeltaTime = 0.0f; } HorizonSDLEnvironment::~HorizonSDLEnvironment() { } void HorizonSDLEnvironment::update() { // when switching between docked/undocked and sleeping/awake, restart audio and switch resolution // NOTE: for some reason, 256 byte audio buffer causes crackling only when docked, therefore we dynamically switch between 256 and 512 // NOTE: if the console goes to sleep we get audio crackling later, therefore also restart audio engine when waking up const bool dockedChange = (isDocked() != m_bDocked); if (dockedChange) { if (dockedChange) m_bDocked = !m_bDocked; debugLog("HorizonSDLEnvironment: Switching to docked = %i (or waking up) ...\n", (int)m_bDocked); // restart sound engine #ifdef MCENGINE_FEATURE_SDL_MIXER engine->getSound()->setMixChunkSize(m_bDocked ? horizon_snd_chunk_size_docked.getInt() : horizon_snd_chunk_size_undocked.getInt()); #endif convar->getConVarByName("snd_output_device")->setValue("Default"); // switch resolution if (dockedChange) { const Vector2 resolution = (m_bDocked ? Vector2(1920, 1080) : Vector2(1280, 720)); SDL_SetWindowSize(m_window, resolution.x, resolution.y); } } SDLEnvironment::update(); } void HorizonSDLEnvironment::update_before_winproc() { hidScanInput(); // for manually handling keyboard/mouse // HACKHACK: manually handle keyboard { for (int i=0; i<MCENGINE_HORIZON_SDL_NUM_SCANCODES_SWITCH; i++) { const HidKeyboardScancode keyCode = switch_scancodes[i]; if (hidKeyboardHeld(keyCode) && !keystate[i]) { switch (keyCode) { case SDL_SCANCODE_NUMLOCKCLEAR: if (!(locks & 0x1)) { engine->onKeyboardKeyDown(keyCode); locks |= 0x1; } else { engine->onKeyboardKeyUp(keyCode); locks &= ~0x1; } break; case SDL_SCANCODE_CAPSLOCK: if (!(locks & 0x2)) { engine->onKeyboardKeyDown(keyCode); locks |= 0x2; } else { engine->onKeyboardKeyUp(keyCode); locks &= ~0x2; } break; case SDL_SCANCODE_SCROLLLOCK: if (!(locks & 0x4)) { engine->onKeyboardKeyDown(keyCode); locks |= 0x4; } else { engine->onKeyboardKeyUp(keyCode); locks &= ~0x4; } break; default: engine->onKeyboardKeyDown(keyCode); } keystate[i] = true; } else if (!hidKeyboardHeld(keyCode) && keystate[i]) { switch (keyCode) { case SDL_SCANCODE_CAPSLOCK: case SDL_SCANCODE_NUMLOCKCLEAR: case SDL_SCANCODE_SCROLLLOCK: break; default: engine->onKeyboardKeyUp(keyCode); } keystate[i] = false; } } } // HACKHACK: manually handle mouse { uint64_t buttons = hidMouseButtonsHeld(); uint64_t changed_buttons = buttons ^ prev_buttons; // buttons if (changed_buttons & MOUSE_LEFT) { if (prev_buttons & MOUSE_LEFT) engine->onMouseLeftChange(false); else engine->onMouseLeftChange(true); } if (changed_buttons & MOUSE_RIGHT) { if (prev_buttons & MOUSE_RIGHT) engine->onMouseRightChange(false); else engine->onMouseRightChange(true); } if (changed_buttons & MOUSE_MIDDLE) { if (prev_buttons & MOUSE_MIDDLE) engine->onMouseMiddleChange(false); else engine->onMouseMiddleChange(true); } prev_buttons = buttons; MousePosition newMousePos; hidMouseRead(&newMousePos); // raw delta // NOTE: the delta values are framerate dependent (poll-dependent), so basically unusable const int32_t dx = (int32_t)newMousePos.velocityX * 2; const int32_t dy = (int32_t)newMousePos.velocityY * 2; if (dx != 0 || dy != 0) { m_fLastMouseDeltaTime = engine->getTime(); engine->onMouseRawMove(dx, dy); } // position // NOTE: the only use case for mouse control is docked mode. the raw coordinates from hidMouseRead() are restricted to 720p, so upscaling only gives 1.5x1.5 pixel accuracy at most if (engine->getTime() < m_fLastMouseDeltaTime + 0.5f) { const float rawRangeX = 1280.0f; const float rawRangeY = 720.0f; m_vMousePos.x = ((((float)newMousePos.x - rawRangeX/2.0f) * m_mouse_sensitivity_ref->getFloat()) + rawRangeX/2.0f) / rawRangeX; m_vMousePos.y = ((((float)newMousePos.y - rawRangeY/2.0f) * m_mouse_sensitivity_ref->getFloat()) + rawRangeY/2.0f) / rawRangeY; m_vMousePos *= engine->getScreenSize(); // scale to 1080p m_vMousePos.x = clamp<float>(m_vMousePos.x, 0.0f, engine->getScreenSize().x); m_vMousePos.y = clamp<float>(m_vMousePos.y, 0.0f, engine->getScreenSize().y); engine->getMouse()->onPosChange(m_vMousePos); } // scrolling const int scrollVelocityX = (int)newMousePos.scrollVelocityX; const int scrollVelocityY = (int)newMousePos.scrollVelocityY; if (scrollVelocityY != 0) engine->onMouseWheelHorizontal(scrollVelocityY); if (scrollVelocityX != 0) engine->onMouseWheelVertical(scrollVelocityX); } } Environment::OS HorizonSDLEnvironment::getOS() { return Environment::OS::OS_HORIZON; } UString HorizonSDLEnvironment::getUsername() { UString uUsername = convar->getConVarByName("name")->getString(); // this was directly taken from the libnx examples Result rc = 0; u128 userID = 0; bool account_selected = 0; AccountProfile profile; AccountUserData userdata; AccountProfileBase profilebase; char username[0x21]; memset(&userdata, 0, sizeof(userdata)); memset(&profilebase, 0, sizeof(profilebase)); rc = accountInitialize(); if (R_FAILED(rc)) debugLog("accountInitialize() failed: 0x%x\n", rc); if (R_SUCCEEDED(rc)) { rc = accountGetActiveUser(&userID, &account_selected); if (R_FAILED(rc)) debugLog("accountGetActiveUser() failed: 0x%x\n", rc); else if(!account_selected) { debugLog("No user is currently selected.\n"); rc = -1; } if (R_SUCCEEDED(rc)) { debugLog("Current userID: 0x%lx 0x%lx\n", (u64)(userID>>64), (u64)userID); rc = accountGetProfile(&profile, userID); if (R_FAILED(rc)) debugLog("accountGetProfile() failed: 0x%x\n", rc); } if (R_SUCCEEDED(rc)) { rc = accountProfileGet(&profile, &userdata, &profilebase); // userdata is otional, see libnx acc.h. if (R_FAILED(rc)) debugLog("accountProfileGet() failed: 0x%x\n", rc); if (R_SUCCEEDED(rc)) { memset(username, 0, sizeof(username)); strncpy(username, profilebase.username, sizeof(username)-1); // even though profilebase.username usually has a NUL-terminator, don't assume it does for safety. debugLog("Username: %s\n", username); uUsername = UString(username); } accountProfileClose(&profile); } accountExit(); } return uUsername; } std::vector<UString> HorizonSDLEnvironment::getFilesInFolder(UString folder) { std::vector<UString> files; DIR *dir; struct dirent *ent; dir = opendir(folder.toUtf8()); if (dir == NULL) return files; while ((ent = readdir(dir))) { const char *name = ent->d_name; UString uName = UString(name); UString fullName = folder; fullName.append(uName); struct stat stDirInfo; int statret = stat(fullName.toUtf8(), &stDirInfo); // NOTE: lstat() always returns 0 in st_mode, seems broken, therefore using stat() for now if (statret < 0) { ///perror (name); ///debugLog("HorizonSDLEnvironment::getFilesInFolder() error, stat() returned %i!\n", lstatret); continue; } if (!S_ISDIR(stDirInfo.st_mode)) files.push_back(uName); } closedir(dir); return files; } std::vector<UString> HorizonSDLEnvironment::getFoldersInFolder(UString folder) { std::vector<UString> folders; DIR *dir; struct dirent *ent; dir = opendir(folder.toUtf8()); if (dir == NULL) return folders; while ((ent = readdir(dir))) { const char *name = ent->d_name; UString uName = UString(name); UString fullName = folder; fullName.append(uName); struct stat stDirInfo; int statret = stat(fullName.toUtf8(), &stDirInfo); // NOTE: lstat() always returns 0 in st_mode, seems broken, therefore using stat() for now if (statret < 0) { ///perror (name); ///debugLog("HorizonSDLEnvironment::getFoldersInFolder() error, stat() returned %i!\n", lstatret); continue; } if (S_ISDIR(stDirInfo.st_mode)) folders.push_back(uName); } closedir(dir); return folders; } std::vector<UString> HorizonSDLEnvironment::getLogicalDrives() { std::vector<UString> drives; drives.push_back("sdmc"); drives.push_back("romfs"); return drives; } UString HorizonSDLEnvironment::getFolderFromFilePath(UString filepath) { // NOTE: #include <libgen.h> and dirname() is undefined, seems like it does not exist anywhere in devkitpro except the header file debugLog("WARNING: HorizonSDLEnvironment::getFolderFromFilePath() not available!\n"); return filepath; } Vector2 HorizonSDLEnvironment::getMousePos() { return m_vMousePos; } void HorizonSDLEnvironment::setMousePos(int x, int y) { m_vMousePos.x = x; m_vMousePos.y = y; } void HorizonSDLEnvironment::showKeyboard() { // TODO: this is broken. it only works if svcSetHeapSize(&addr, 0xf000000); // 128 MB, but that's not enough for the rest of the game. switching sizes also crashes later. // https://gbatemp.net/threads/software-keyboard-example-failing.528518/ SwkbdConfig kbd; Result rc = swkbdCreate(&kbd, 0); printf("swkbdCreate(): 0x%x\n", rc); if (R_SUCCEEDED(rc)) { swkbdConfigMakePresetDefault(&kbd); char str[256] = {0}; rc = swkbdShow(&kbd, str, sizeof(str)); printf("swkbdShow(): 0x%x\n", rc); swkbdClose(&kbd); if (R_SUCCEEDED(rc)) { UString uStr = UString(str); for (int i=0; i<uStr.length(); i++) { engine->onKeyboardChar(uStr[i]); } } } } bool HorizonSDLEnvironment::isDocked() { return (appletGetOperationMode() == AppletOperationMode_Docked); } int HorizonSDLEnvironment::getMemAvailableMB() { uint64_t numBytes = 0; svcGetInfo(&numBytes, 6, CUR_PROCESS_HANDLE, 0); return (int)(numBytes/1024/1024); } int HorizonSDLEnvironment::getMemUsedMB() { uint64_t numBytes = 0; svcGetInfo(&numBytes, 7, CUR_PROCESS_HANDLE, 0); return (int)(numBytes/1024/1024); } #endif #endif
22.372168
181
0.687545
lwkobe
330c97f561e08709ab342f9fd6880a22c9a7175f
32,074
cc
C++
library/src/memory_profiling/BP_LibraryMemoryProfiling.cc
jason-medeiros/blockparty
4b1aabe66b13ceac70d6e42feb796909f067df9a
[ "MIT" ]
1
2018-05-31T11:51:43.000Z
2018-05-31T11:51:43.000Z
library/src/memory_profiling/BP_LibraryMemoryProfiling.cc
jason-medeiros/blockparty
4b1aabe66b13ceac70d6e42feb796909f067df9a
[ "MIT" ]
null
null
null
library/src/memory_profiling/BP_LibraryMemoryProfiling.cc
jason-medeiros/blockparty
4b1aabe66b13ceac70d6e42feb796909f067df9a
[ "MIT" ]
null
null
null
/* * BP_LibraryMemoryProfiling.cc * * Created on: Aug 26, 2013 * Author: root */ #include "../../include/BP-Main.h" // // Developer Notice: The code below is fairly complex, but if read carefully should // be fairly simple to understand if provided some context. The contextual summary of the code // found below is simply described as an overlay to the basic libc memory allocators. This // provides blockparty with some capacity to do runtime checks/allocation thresholding during allocation // to prevent undefined behavior. // // Developer Notice: A secondary layer to memory allocation is also provided within blockparty, and should // be used in lieu of using the allocator code below. You can find this capacity // within the BP_LinkedList.cc file, which provides direct access to allocators // managed directly via a libc (optimised) tail queue. While a bit less granular, the tail // queue allocators are designed to be more developer friendly. Additionally, blockparty // also includes a hash table allocator, which has larger entry sizes but O(1) lookup speed. // #if BP_USE_HASH_TABLE_PROFILER // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Global Memory Profiler Hash Table Registry %%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // global hash table registry BP_HASH_TABLE_REGISTRY global_mprof_hash_table_registry; // set the global hash init value to some arbitrary static value size_t global_mprof_hash_table_init_ok_val; size_t global_mprof_hash_table_init_ok; // If this value is non-zero the global memory profiler will create // backtraces for every allocaction. This should only be enabled // if you're debugging leaks. BP_BOOL global_mprof_create_backtrace_on_alloc; // global memory profiler lock sem_t global_mprof_lock; // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Memory Profiler Routines (Called Internally from bp*allocs/frees) % // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Mark an allocation if it exists. BP_ERROR_T BP_MemProfilerMarkChunkByAddr(void * chunk, char * mark) { // return indicating success return ERR_SUCCESS; } // This must be called once per application run. It initializes // semaphores and insures global data is in the right configuration // before any allocations are performed. Not calling this function // can result in undefined behavior. BP_ERROR_T BP_InitMemProfilerSubsystem ( size_t log_chunk_min_size, size_t diag_bpstrdup, size_t diag_bpstrndup, size_t diag_bprealloc, size_t diag_bpmalloc, size_t diag_bpcalloc, size_t diag_bpfree ) { // only init if no init has already occured if(!BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) return ERR_FAILURE; // initialize the hash table BP_GLOBAL_MEMPROF_HASH_TABLE_INIT; // return indicating success return ERR_SUCCESS; } // disables the memory profiler subsystem and resets/frees memory. BP_ERROR_T BP_ShutdownMemProfilerSubsystem() { // only shutdown if profiler is up if(BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) return ERR_FAILURE; // destroy the hash table registry BP_DestroyHashTableRegistry(&global_mprof_hash_table_registry); // override the profiler init setting global_mprof_hash_table_init_ok_val = 0; // return indicating success return ERR_SUCCESS; } // removes a chunk from update BP_ERROR_T BP_MemProfilerRemoveChunk(void * addr) { // only shutdown if profiler is up if(BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) return ERR_FAILURE; // lock the table modification semaphore BP_HASH_TABLE_LOCK_SEM(global_mprof_lock); // delete a memory entry BP_ERROR_T deleted_ok = BP_HashRegDeleteMemoryEntryByDataPtr ( &global_mprof_hash_table_registry, addr ); // if it wasn't deleted ok, return indicating failure if(!deleted_ok) { return ERR_FAILURE; } // unlock the table modification semaphore BP_HASH_TABLE_UNLOCK_SEM(global_mprof_lock); // return indicating success return ERR_SUCCESS; } // checks to see if the chunk is in the stack P_BP_HASH_TABLE_MEM_PTR_ENTRY BP_MemProfilerFindChunk(void *addr) { // only shutdown if profiler is up if(BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) return NULL; // return found pointer (or null) return BP_HashRegMemPtrFind(&global_mprof_hash_table_registry,(void *) addr ); } // displays the memprofiler BP_ERROR_T BP_DisplayMemProfiler() { // only shutdown if profiler is up if(!BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) { printf("\n[!!] Attempted to display memory profiler but global memory profiler hasn't been initialized yet. Initialize memory profiler before utilizing this routine."); return ERR_FAILURE; } // display the memory profiler hash registry BP_HashRegDisplay(&global_mprof_hash_table_registry, BP_TRUE, BP_FALSE); // return indicating success return ERR_SUCCESS; } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Blockparty Custom Allocators (Hash Table version) %%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // managed strdup char * bpstrdup_real(char *dup, BPLN_PARMS) { // ensure we're not trying to duplicate a null pointer if(!dup) return NULL; // If the memory profiler isn't active, immediately return // the duplicated string. if(!BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) return strdup(dup); // lock the table modification semaphore BP_HASH_TABLE_LOCK_SEM(global_mprof_lock); // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Managed Allocation %%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // calculate the length of the string to duplicate size_t len = bpstrlen(dup); // add a memory entry ("" is 1 byte long just for null terminator) char * dup_string = (char *) BP_HashRegAddMemoryEntry ( &global_mprof_hash_table_registry, BP_HASH_REG_MEM_ENTRY_TYPE_GENERIC_ALLOCATION, len+1, file_name, line_number, func ); // now attempt to lookup the pointer P_BP_HASH_TABLE_MEM_PTR_ENTRY dup_string_hash_entry = BP_HashRegMemPtrFind ( &global_mprof_hash_table_registry, (void *) dup_string ); // if we cant lookup the hash entry, something catestrophic has occured if(!dup_string_hash_entry) { // exit immediately BP_LIBRARY_CRITICAL_DEBUG_EXIT("Unable to lookup block after allocation. This should never happen. Library emitting debug trap."); } // since we have the entry, set the type dup_string_hash_entry->alloc_type = BP_HASH_TABLE_ALLOCATOR_STRDUP; // copy in the string memcpy(dup_string, dup, len); // unlock the table modification semaphore BP_HASH_TABLE_UNLOCK_SEM(global_mprof_lock); // return the duplicated string return dup_string; } // managed strndup char * bpstrndup_real(char *dup, size_t n, BPLN_PARMS) { // ensure we're not trying to duplicate a null pointer if(!dup) return NULL; if(!n) return NULL; // If the memory profiler isn't active, immediately return // the duplicated string. if(!BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) return strndup(dup, n); // lock the table modification semaphore BP_HASH_TABLE_LOCK_SEM(global_mprof_lock); // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Managed Allocation %%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // add a memory entry char * dup_string = (char *) BP_HashRegAddMemoryEntry ( &global_mprof_hash_table_registry, BP_HASH_REG_MEM_ENTRY_TYPE_GENERIC_ALLOCATION, n+1, file_name, line_number, func ); // now attempt to lookup the pointer P_BP_HASH_TABLE_MEM_PTR_ENTRY dup_string_hash_entry = BP_HashRegMemPtrFind ( &global_mprof_hash_table_registry, (void *) dup_string ); // if we cant lookup the hash entry, something catestrophic has occured if(!dup_string_hash_entry) { // exit immediately BP_LIBRARY_CRITICAL_DEBUG_EXIT("Unable to lookup block after allocation. This should never happen. Library emitting debug trap."); return NULL; } // since we have the entry, set the type dup_string_hash_entry->alloc_type = BP_HASH_TABLE_ALLOCATOR_STRNDUP; // copy in the string (MUST BE n, CANNOT BE ANYTHING ELSE) memcpy(dup_string, dup, n); // unlock the table modification semaphore BP_HASH_TABLE_UNLOCK_SEM(global_mprof_lock); // return the duplicated string return dup_string; } // managed realloc void * bprealloc_real(void * addr, size_t size, BPLN_PARMS) { // If the memory profiler isn't active, immediately return // the realloc if(!BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) return realloc(addr, size); // unlock the table modification semaphore BP_HASH_TABLE_LOCK_SEM(global_mprof_lock); // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Managed Allocation %%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // pointer to hold future mem hash entries P_BP_HASH_TABLE_MEM_PTR_ENTRY dup_mem_hash_entry = NULL; // address of the new allocation to be returned void * new_addr = NULL; // if it's a new allocation, create a new entry here if(!addr) { // add a new memory entry since the behavior of realloc mandates // that we create a new entry on a null lookup. new_addr = (void *) BP_HashRegAddMemoryEntry ( &global_mprof_hash_table_registry, BP_HASH_REG_MEM_ENTRY_TYPE_GENERIC_ALLOCATION, size+1, file_name, line_number, func ); // now attempt to lookup the pointer dup_mem_hash_entry = BP_HashRegMemPtrFind ( &global_mprof_hash_table_registry, (void *) new_addr ); // if we cant lookup the hash entry, something catestrophic has occured if(!dup_mem_hash_entry) { // exit immediately BP_LIBRARY_CRITICAL_DEBUG_EXIT("Unable to lookup block during realloc (initial alloc part). This should never happen. Library emitting debug trap."); } // since we have the entry, set the type dup_mem_hash_entry->alloc_type = BP_HASH_TABLE_ALLOCATOR_REALLOC; } else // find and resize part of realloc() { // now attempt to lookup the pointer dup_mem_hash_entry = BP_HashRegMemPtrFind ( &global_mprof_hash_table_registry, (void *) addr ); // if we cant lookup the hash entry, something catestrophic has occured if(!dup_mem_hash_entry) { // exit immediately BP_LIBRARY_CRITICAL_DEBUG_EXIT("Unable to lookup block during realloc (memory resizing part). This should never happen. Library emitting debug trap."); } // create new addr new_addr = BP_HashRegResizeMemoryEntry ( &global_mprof_hash_table_registry, addr, size, file_name, line_number, func ); // -- lookup a second time to override type and also verify hash table integrity -- // now attempt to lookup the pointer dup_mem_hash_entry = BP_HashRegMemPtrFind ( &global_mprof_hash_table_registry, (void *) new_addr ); // if we cant lookup the hash entry, something catestrophic has occured if(!dup_mem_hash_entry) { // exit immediately BP_LIBRARY_CRITICAL_DEBUG_EXIT("Unable to lookup block during realloc (post creation lookup part). This should never happen. Library emitting debug trap."); } // since we have the entry, set the type dup_mem_hash_entry->alloc_type = BP_HASH_TABLE_ALLOCATOR_REALLOC; } // unlock the table modification semaphore BP_HASH_TABLE_UNLOCK_SEM(global_mprof_lock); // return the resized memory return new_addr; } // managed malloc (this is here mostly as a stub in case people want to use this library // in their own code. This code actually uses calloc in the backend, so you can be guaranteed // that all allocations returned are nullified). void * bpmalloc_real(size_t size, BPLN_PARMS) { // If the memory profiler isn't active, immediately return // the allocated memory. if(!BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) return malloc(size); // lock the table modification semaphore BP_HASH_TABLE_LOCK_SEM(global_mprof_lock); // add a memory entry void * new_mem = (void *) BP_HashRegAddMemoryEntry ( &global_mprof_hash_table_registry, BP_HASH_REG_MEM_ENTRY_TYPE_GENERIC_ALLOCATION, size, file_name, line_number, func ); // unlock the table modification semaphore BP_HASH_TABLE_UNLOCK_SEM(global_mprof_lock); // return the new memory return new_mem; } // managed calloc void * bpcalloc_real(size_t size, size_t size_n, BPLN_PARMS) { // If the memory profiler isn't active, immediately return // the allocated memory. if(!BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) { return calloc(size, size_n); } // lock the table modification semaphore BP_HASH_TABLE_LOCK_SEM(global_mprof_lock); // add a memory entry void * new_mem = (void *) BP_HashRegAddMemoryEntry ( &global_mprof_hash_table_registry, BP_HASH_REG_MEM_ENTRY_TYPE_GENERIC_ALLOCATION, (size * size_n), file_name, line_number, func ); // unlock the table modification semaphore BP_HASH_TABLE_UNLOCK_SEM(global_mprof_lock); // return the new memory return new_mem; } // destroy managed memory void bpfree_real(void * addr, BPLN_PARMS) { // display null free check here if(!addr) { // dbg msg printf("\n [!!] Error: Attempting to free a null chunk. This should never happen. Displaying debug backtrace."); printf("\n - in file_name: %s ", file_name); printf("\n - on line_number: %u ", line_number); printf("\n - in func: %s", func); printf("\n"); // create and display backtrace P_BP_LINUX_DEBUG_BACKTRACE debug_backtrace = BP_LinuxDebugCreateBacktrace(32); BP_LinuxDebugDisplayBacktrace(debug_backtrace, 1, 0, 32, BP_TRUE, BP_TRUE); printf("\n"); // attempt to destroy after debug BP_LinuxDebugDestroyBacktrace(debug_backtrace); // exit return; } // If the memory profiler isn't active, immediately return // the allocated memory. if(!BP_GLOBAL_MEMPROF_HASH_TABLE_INIT_OK) { // free normally if not null free(addr); return; } // lock the table modification semaphore BP_HASH_TABLE_LOCK_SEM(global_mprof_lock); // delete a memory entry BP_ERROR_T deleted_ok = BP_HashRegDeleteMemoryEntryByDataPtr ( &global_mprof_hash_table_registry, addr ); if(!deleted_ok) { printf("\n [!!] Error: Attempted to delete addr %p from the global hreg but the operation failed. Displaying trace.", addr); printf("\n - in file_name: %s ", file_name); printf("\n - on line_number: %u ", line_number); printf("\n - in func: %s", func); printf("\n"); // create and display backtrace // P_BP_LINUX_DEBUG_BACKTRACE debug_backtrace = BP_LinuxDebugCreateBacktrace(32); // BP_LinuxDebugDisplayBacktrace(debug_backtrace, 1, 0, 32, BP_TRUE, BP_TRUE); // printf("\n"); // attempt to destroy after debug // BP_LinuxDebugDestroyBacktrace(debug_backtrace); } // unlock the table modification semaphore BP_HASH_TABLE_UNLOCK_SEM(global_mprof_lock); } #else // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Old / Non-Hash Table Memory Profiler %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // global profiler set sem_t global_memory_profiler_semaphore; // flag indicating whether or not the profiler is enabled size_t global_memory_profiler_enabled = 0; // global memory profiler pool P_BP_MEMPROF_ENTRY global_memprof_pool = NULL; // global size parameter for logged chunks (chunks are only logged // when their logging size_t global_size_for_chunk_logging = 1024; // number of entries in the profiler pool size_t global_memprof_pool_n = 0; // index to the last entry added in the pool size_t global_memprof_last_index_added = 0; // size of the global_memprf_pool_n object. size_t global_memprofiler_pool_memory_usage = 0; // these flags are set via the init routine in-parameters // and are used to display a variety of debug messages. Profiler // debugging must be enabled (in BP-Main.h) in order for any // messages at all to be displayed. size_t global_memprofiler_diag_bpstrdup = 0; size_t global_memprofiler_diag_bpstrndup = 0; size_t global_memprofiler_diag_bprealloc = 0; size_t global_memprofiler_diag_bpmalloc = 0; size_t global_memprofiler_diag_bpcalloc = 0; size_t global_memprofiler_diag_bpfree = 0; // Simple OOM null allocation check for the app. Exits if we have // any 0x00 allocs. size_t global_memprofiler_exit_application_on_null_allocations = 1; // checks to see if the chunk is in the stack P_BP_MEMPROF_ENTRY BP_MemProfilerFindChunk(void *addr) { size_t n = 0; for(; n < global_memprof_pool_n; n++) { // get the entry at the specified location if(global_memprof_pool[n].mem_ptr == addr) return (P_BP_MEMPROF_ENTRY) &global_memprof_pool[n]; } // return indicating failure return NULL; } // adds a chunk to update BP_ERROR_T BP_MemProfilerAddUpdateProfiledChunk(void * addr, size_t new_size, BP_MEMPROF_ALLOC_TYPE type) { // ensure address and new size if(!addr || !new_size) return ERR_FAILURE; // entry P_BP_MEMPROF_ENTRY entry = BP_MemProfilerFindChunk((void *) addr); if(!entry) { // increment the pool stack count global_memprof_pool_n++; global_memprof_pool = (P_BP_MEMPROF_ENTRY) realloc(global_memprof_pool, global_memprof_pool_n * sizeof(BP_MEMPROF_ENTRY)); // zero out the entry memset((void *) &global_memprof_pool[global_memprof_pool_n-1], 0x00, sizeof(BP_MEMPROF_ENTRY)); // set the pointer in the structure global_memprof_pool[global_memprof_pool_n-1].mem_ptr = addr; // set the init alloc size if the current size is zero if(global_memprof_pool[global_memprof_pool_n-1].curr_alloc_size == 0) global_memprof_pool[global_memprof_pool_n-1].init_alloc_size = global_memprof_pool[global_memprof_pool_n-1].curr_alloc_size; // set the current alloc size global_memprof_pool[global_memprof_pool_n-1].curr_alloc_size = new_size; global_memprof_pool[global_memprof_pool_n-1].total_allocations = 1; } else { printf("\n Logging existing chunk"); // set the current alloc size entry->curr_alloc_size = new_size; entry->total_allocations++; } // return indicating success return ERR_SUCCESS; } // removes a chunk if it's been bpfree'd // removes a chunk from update BP_ERROR_T BP_MemProfilerRemoveChunk(void * addr) { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Attempting to remove monitored chunk: %p", addr); #endif // cant remove what isn't there if(!addr) return ERR_FAILURE; // set the new entries P_BP_MEMPROF_ENTRY new_entries = (P_BP_MEMPROF_ENTRY) bpcalloc(1, sizeof(BP_MEMPROF_ENTRY) * (global_memprof_pool_n - 1)); if(!new_entries) return ERR_FAILURE; #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Attempting to find chunk in monitored chunk list: %p", addr); #endif // get chunk index size_t n = 0; for(; n < global_memprof_pool_n; n++) { if(global_memprof_pool[n].mem_ptr == addr) { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Found our chunk %p at entry index %u (struct addr: %p)", addr, n, (void *) &global_memprof_pool[n]); #endif // set offset size_t entries_offset = n; size_t following_offset = n+1; size_t remaining_entries = (global_memprof_pool_n - n - 1); // copy in the first half of the stack memcpy((void *)new_entries, (void *) global_memprof_pool, sizeof(BP_MEMPROF_ENTRY) * n); // copy in the remaining entries memcpy((void *)&new_entries[n], (void *) &global_memprof_pool[n+1], sizeof(BP_MEMPROF_ENTRY) * remaining_entries); // set pool to the new stack global_memprof_pool = new_entries; #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Chunk %p has been removed from the list.", addr); #endif // break the loop break; } } // decrement element count in the pool global_memprof_pool_n--; // return indicating success return ERR_SUCCESS; } // ==================================================== // === Allocators ===================================== // ==================================================== // string duplication char * bpstrdup(char *dup) { if(!dup) return ERR_FAILURE; if(global_memory_profiler_enabled == 0xcafebabe) { // lock global semaphor sem_wait(&global_memory_profiler_semaphore); } // get string length (cap out at 100mb) size_t string_len = strnlen(dup, 1024 * 1024 * 100); if(string_len >= MAXIMUM_VALUE_FOR_ANY_ALLOCATION) { printf("\n [+] Attempted to allocate more than %u (%u) bytes. Error.", MAXIMUM_VALUE_FOR_ANY_ALLOCATION, string_len); if(global_memprofiler_exit_application_on_null_allocations == 1) { __asm("int3"); exit(0); } return NULL; } // duplicate the string char * result = (char *) strdup(dup); if(!result) if(global_memprofiler_exit_application_on_null_allocations == 1) { printf("\n [ERROR] bpstrdup(%p): APPLICATION RAN OUT OF MEMORY WHILE TRYING TO ALLOCATE SPACE.", dup); __asm("int3"); exit(0); } if(string_len >= global_size_for_chunk_logging) if(global_memprofiler_diag_bprealloc) { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] strdup for (%p) yielded ptr %p (with calculated size: %u) ", dup, result, string_len); #endif } if(global_memory_profiler_enabled == 0xcafebabe) { // add the chunk to the profiler if size check passes if(string_len >= global_size_for_chunk_logging) BP_MemProfilerAddUpdateProfiledChunk(result, string_len, BP_MEMPROF_ALLOC_TYPE_STRDUP); // unlock global semaphore sem_post(&global_memory_profiler_semaphore); } return result; } // length restrained duplication char * bpstrndup(char *dup, size_t n) { if(n >= MAXIMUM_VALUE_FOR_ANY_ALLOCATION) { printf("\n [+] Attempted to allocate more than %u (%n) bytes. Error.", MAXIMUM_VALUE_FOR_ANY_ALLOCATION, n); if(global_memprofiler_exit_application_on_null_allocations == 1) { __asm("int3"); exit(0); } return NULL; } if(global_memory_profiler_enabled == 0xcafebabe) { // lock global semaphor sem_wait(&global_memory_profiler_semaphore); } char * result = (char *) strndup(dup, n); if(!result) if(global_memprofiler_exit_application_on_null_allocations == 1) { printf("\n [ERROR] bpstrndup(%p, %u): APPLICATION RAN OUT OF MEMORY WHILE TRYING TO ALLOCATE SPACE.", dup, n); exit(0); } if(n >= global_size_for_chunk_logging) if(global_memprofiler_diag_bpstrndup) { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] strndup for (%p, %u) yielded ptr %p", dup, n, result); #endif } if(global_memory_profiler_enabled == 0xcafebabe) { // add the chunk to the profiler if size check passes if(n >= global_size_for_chunk_logging) BP_MemProfilerAddUpdateProfiledChunk(result, n, BP_MEMPROF_ALLOC_TYPE_STRNDUP); // unlock global semaphore sem_post(&global_memory_profiler_semaphore); } return result; } // replacement for realloc void * bprealloc(void * addr, size_t size) { if(size >= MAXIMUM_VALUE_FOR_ANY_ALLOCATION) { printf("\n [+] Attempted to allocate more than %u (%u_ bytes. Error.", MAXIMUM_VALUE_FOR_ANY_ALLOCATION, size); if(global_memprofiler_exit_application_on_null_allocations == 1) { __asm("int3"); exit(0); } return NULL; } if(global_memory_profiler_enabled == 0xcafebabe) { // lock global semaphor sem_wait(&global_memory_profiler_semaphore); } // allocate the result void * result = realloc(addr, size); if(!result) if(global_memprofiler_exit_application_on_null_allocations == 1) { printf("\n [ERROR] bprealloc(%p, %u): APPLICATION RAN OUT OF MEMORY WHILE TRYING TO ALLOCATE SPACE.", addr, size); exit(0); } if(size >= global_size_for_chunk_logging) if(global_memprofiler_diag_bprealloc) { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] realloc for (%p, %u) yielded ptr %p", addr, size, result); #endif } if(!result) { printf("\n [!!] realloc failed for (%p, %u) yielded ptr %p", addr, size, result); exit(0); } if(global_memory_profiler_enabled == 0xcafebabe) { // add the chunk to the profiler if size check passes if(size >= global_size_for_chunk_logging) BP_MemProfilerAddUpdateProfiledChunk(result, size, BP_MEMPROF_ALLOC_TYPE_REALLOC); // unlock global semaphore sem_post(&global_memory_profiler_semaphore); } // return the allocated data return result; } // replacement for malloc void * bpmalloc(size_t size) { if(size >= MAXIMUM_VALUE_FOR_ANY_ALLOCATION) { printf("\n [+] Attempted to allocate more than %u (%u) bytes. Error.", MAXIMUM_VALUE_FOR_ANY_ALLOCATION, size); if(global_memprofiler_exit_application_on_null_allocations == 1) { __asm("int3"); exit(0); } return NULL; } if(global_memory_profiler_enabled == 0xcafebabe) { // lock global semaphor sem_wait(&global_memory_profiler_semaphore); } // allocate the result void * result = malloc(size); if(!result) if(global_memprofiler_exit_application_on_null_allocations == 1) { printf("\n [ERROR] bpmalloc(%u): APPLICATION RAN OUT OF MEMORY WHILE TRYING TO ALLOCATE SPACE.", size); exit(0); } if(size >= global_size_for_chunk_logging) if(global_memprofiler_diag_bpmalloc) { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] malloc for (%u) yielded ptr %p", size, result); #endif } if(!result) { printf("\n [!!] Error: malloc failed. Application likely ran out of memory."); exit(0); } if(global_memory_profiler_enabled == 0xcafebabe) { // add the chunk to the profiler if size check passes if(size >= global_size_for_chunk_logging) BP_MemProfilerAddUpdateProfiledChunk(result, size, BP_MEMPROF_ALLOC_TYPE_MALLOC); // unlock global semaphore sem_post(&global_memory_profiler_semaphore); } // return the allocated data return result; } // replacement for bpcalloc void * bpcalloc(size_t size, size_t size_n) { if((size * size_n) >= MAXIMUM_VALUE_FOR_ANY_ALLOCATION) { printf("\n [+] Attempted to allocate more than %u (%u) bytes. Error.", MAXIMUM_VALUE_FOR_ANY_ALLOCATION, size_n); if(global_memprofiler_exit_application_on_null_allocations == 1) { __asm("int3"); exit(0); } return NULL; } if(global_memory_profiler_enabled == 0xcafebabe) { // lock global semaphor sem_wait(&global_memory_profiler_semaphore); } // allocate the result void * result = calloc(size, size_n); if(!result) if(global_memprofiler_exit_application_on_null_allocations == 1) { printf("\n [ERROR] bpcalloc(%u, %u): APPLICATION RAN OUT OF MEMORY WHILE TRYING TO ALLOCATE SPACE.", size, size_n); exit(0); } if(size >= global_size_for_chunk_logging || size_n >= global_size_for_chunk_logging) if(global_memprofiler_diag_bpcalloc) { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] calloc for (%u,%u) yielded ptr %p", size, size_n, result); #endif } if(global_memory_profiler_enabled == 0xcafebabe) { // add the chunk to the profiler if size check passes if(size >= global_size_for_chunk_logging) BP_MemProfilerAddUpdateProfiledChunk(result, size, BP_MEMPROF_ALLOC_TYPE_CALLOC); // unlock global semaphore sem_post(&global_memory_profiler_semaphore); } // return the allocated data return result; } // replacement for bpcalloc void bpfree(void * addr) { if(global_memory_profiler_enabled == 0xcafebabe) { // lock global semaphor sem_wait(&global_memory_profiler_semaphore); } if(global_memprofiler_diag_bpfree) { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Attempting to free %p", addr); #endif } // run check to ensure that the chunk is not being double free'd. If it is being double // freed, throw a sigtrap so that we might debug it. if(global_memory_profiler_enabled == 0xcafebabe) if(!BP_MemProfilerFindChunk((void *) addr)) { printf("\n BPMEMPROF: Attempting to free chunk that doesn't appear to be in the profiled chunk list. Stopping application/launching debugger."); printf("\n\n"); __asm("int3"); return; } // bpfree the result free(addr); if(global_memory_profiler_enabled == 0xcafebabe) { // remove the chunk from the profiler BP_MemProfilerRemoveChunk(addr); // unlock global semaphore sem_post(&global_memory_profiler_semaphore); } } // This must be called once per application run. It initializes // semaphores and insures global data is in the right configuration // before any allocations are performed. Not calling this function // can result in undefined behavior. BP_ERROR_T BP_InitMemProfilerSubsystem ( size_t log_chunk_min_size, size_t diag_bpstrdup, size_t diag_bpstrndup, size_t diag_bprealloc, size_t diag_bpmalloc, size_t diag_bpcalloc, size_t diag_bpfree ) { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Attempting to initialize main memory profiler."); #endif // initialize the memory profile semaphore sem_init(&global_memory_profiler_semaphore, 0, 1); #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Initialized global semaphor at %p, now waiting for lock.", &global_memory_profiler_semaphore); #endif // lock global semaphor sem_wait(&global_memory_profiler_semaphore); #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Locked global memory profile semaphore."); #endif // set global diagnostic flags from parameters global_memprofiler_diag_bpstrdup = diag_bpstrdup; global_memprofiler_diag_bpstrndup = diag_bpstrndup; global_memprofiler_diag_bprealloc = diag_bprealloc; global_memprofiler_diag_bpmalloc = diag_bpmalloc; global_memprofiler_diag_bpcalloc = diag_bpcalloc; global_memprofiler_diag_bpfree = diag_bpfree; // set the global profiler pool to null global_memprof_pool = NULL; global_memprof_pool_n = 0; global_memprof_last_index_added = 0; global_memprofiler_pool_memory_usage = 0; global_size_for_chunk_logging = log_chunk_min_size; global_memory_profiler_enabled = 0xcafebabe; #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Memory profiler has been loaded OK. Now unlocking global lock."); #endif // unlock global semaphore sem_post(&global_memory_profiler_semaphore); #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Global memory profiler lock has been unlocked. Exiting profiler init."); #endif // return indicating success return ERR_SUCCESS; } // disables the memory profiler subsystem and resets/frees memory. BP_ERROR_T BP_ShutdownMemProfilerSubsystem() { #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Preparing to disable memory profiler.."); #endif // lock global semaphor sem_wait(&global_memory_profiler_semaphore); if(global_memory_profiler_enabled != 0xcafebabe) return ERR_FAILURE; // set flag indicating capability is disabled global_memory_profiler_enabled = 0; if(global_memprof_pool_n) for(size_t j = 0; j < global_memprof_pool_n; j++) { // free marks if necessary if(global_memprof_pool[j].mark) free(global_memprof_pool[j].mark); } if(global_memprof_pool) free(global_memprof_pool); // reset all the global vars global_memprof_pool = NULL; global_memprof_pool_n = 0; global_memprof_last_index_added = 0; global_memprofiler_pool_memory_usage = 0; global_size_for_chunk_logging = 0; // unlock global semaphore sem_post(&global_memory_profiler_semaphore); #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Memory profiler has been disabled."); #endif // return indicating success return ERR_SUCCESS; } // Mark an allocation if it exists. BP_ERROR_T BP_MemProfilerMarkChunkByAddr(void * chunk, char * mark) { // ensure we have some parameter validation if(!chunk || !mark) return ERR_FAILURE; #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Attempting to mark chunk: %p with %s", chunk, mark); #endif // look up the entry P_BP_MEMPROF_ENTRY entry = BP_MemProfilerFindChunk(chunk); if(!entry) return ERR_FAILURE; // Dont mark chunks with long strings, stupid. You'll just exhaust // your memory. size_t mark_len = bpstrlen(mark); if(mark_len >= 4096) return ERR_FAILURE; // set the mark here after length validation entry->mark = strdup(mark); #if DEBUG_MEMORY_PROFILER == 1 printf("\n [!!] Marked chunk %p OK!", chunk); #endif // return indicating success return ERR_SUCCESS; } #endif
25.195601
171
0.716156
jason-medeiros
330cc0e9c0f0b03e2058cbce149aee5956a5d6b3
344
cc
C++
src/motor/world/src/component/component.cc
motor-dev/Motor
98cb099fe1c2d31e455ed868cc2a25eae51e79f0
[ "BSD-3-Clause" ]
null
null
null
src/motor/world/src/component/component.cc
motor-dev/Motor
98cb099fe1c2d31e455ed868cc2a25eae51e79f0
[ "BSD-3-Clause" ]
null
null
null
src/motor/world/src/component/component.cc
motor-dev/Motor
98cb099fe1c2d31e455ed868cc2a25eae51e79f0
[ "BSD-3-Clause" ]
null
null
null
/* Motor <motor.devel@gmail.com> see LICENSE for detail */ #include <motor/world/stdafx.h> #include <motor/world/component/component.meta.hh> namespace Motor { namespace World { Component::Component() { } LogicComponent::LogicComponent(raw< const Meta::Class > kernelClass) : kernelClass(kernelClass) { } }} // namespace Motor::World
18.105263
95
0.726744
motor-dev
33163bbfb6a3329f31e140e49979700b2f199390
159
cc
C++
bitlinuxosnetworkclass/lesson35/httpServer.cc
DanteIoVeYou/Linux_Study
701a54caad3d65c511716111430ca08ada78f088
[ "MIT" ]
null
null
null
bitlinuxosnetworkclass/lesson35/httpServer.cc
DanteIoVeYou/Linux_Study
701a54caad3d65c511716111430ca08ada78f088
[ "MIT" ]
null
null
null
bitlinuxosnetworkclass/lesson35/httpServer.cc
DanteIoVeYou/Linux_Study
701a54caad3d65c511716111430ca08ada78f088
[ "MIT" ]
null
null
null
#include "httpServer.hpp" int main(int argc, char *argv[]) { srv::httpServer srvIns(atoi(argv[1])); srvIns.init(); srvIns.start(); return 0; }
17.666667
42
0.616352
DanteIoVeYou
3317953f9c67dbf71858b38ed4840e500ddf6bc1
1,542
cc
C++
unit_tests/test_property.cc
maihd/riku
daca9172f4ee0e303060796e86859247e4306dcc
[ "Unlicense" ]
2
2019-03-22T05:01:03.000Z
2020-05-07T11:26:03.000Z
unit_tests/test_property.cc
maihd/riku
daca9172f4ee0e303060796e86859247e4306dcc
[ "Unlicense" ]
null
null
null
unit_tests/test_property.cc
maihd/riku
daca9172f4ee0e303060796e86859247e4306dcc
[ "Unlicense" ]
null
null
null
// Copyright (c) 2019, MaiHD. All right reversed. // License: Unlicensed #include <stdio.h> #include "./unit_test.h" #if defined(EXTENION_PROPERTY) && (defined(_MSC_VER) || (defined(__has_declspec_attriute) && __has_declspec_attribute(property))) #define test_assert(a, b) console::log(#a " = %d - " #b " = %d", a, b) struct Type { public: PROPERTY(int, value, get_value, set_value); public: int get_value() { return real_value; } void set_value(int v) { real_value = v; } public: int real_value; }; static_assert(sizeof(Type) == sizeof(int), "property should not create new member in data structure, it's just syntax sugar man."); [[noreturn]] void force_exit() { exit(1); } TEST_CASE("Property testing", "[property]") { Type test; test.value = 0; test_assert(test.value, test.real_value); test.value = 1; test_assert(test.value, test.real_value); test.value = 1; test_assert(test.value, test.real_value); test.value = 2; test_assert(test.value, test.real_value); test.value = 3; test_assert(test.value, test.real_value); test.value = 4; test_assert(test.value, test.real_value); test.value = 5; test_assert(test.value, test.real_value); test.value = 6; test_assert(test.value, test.real_value); test.value = 7; test_assert(test.value, test.real_value); test.value = 8; test_assert(test.value, test.real_value); test.value = 9; test_assert(test.value, test.real_value); } #endif
20.837838
131
0.653048
maihd
3319e121c5528eb8172b4366200ac3fbc820fd26
3,343
cpp
C++
vtbl.cpp
Kanda-Motohiro/cppsample
6c010f4cc7a8143debf159435621966bf582f5d6
[ "CC0-1.0" ]
null
null
null
vtbl.cpp
Kanda-Motohiro/cppsample
6c010f4cc7a8143debf159435621966bf582f5d6
[ "CC0-1.0" ]
null
null
null
vtbl.cpp
Kanda-Motohiro/cppsample
6c010f4cc7a8143debf159435621966bf582f5d6
[ "CC0-1.0" ]
null
null
null
/* * 2018.5.6 kanda.motohiro@gmail.com C++ 練習 * released under https://creativecommons.org/publicdomain/zero/1.0/legalcode.ja */ #include "base.h" #include <locale> #include <typeinfo> class Derived: public base { public: int i = 0xdddddddd; Derived(char a) : base(a) {} const string toString() const override { string s = base::toString(); return "==" + s; } }; int main() { p(locale{""}.name()); // ja_JP.utf8 at line 19 Derived d('1'); base *pb = &d; printf("base=%p %u derived=%p %u\n", pb, sizeof(base), &d, sizeof(d)); cout << pb->toString() << endl; Derived *pd = static_cast<Derived *>(pb); pd->i+= 7; pd = dynamic_cast<Derived *>(pb); pd->i-= 5; Base *bad = dynamic_cast<Base *>(pb); p(bad); p(typeid(int).name()); const type_info& ti = typeid(*pb); p(ti.name()); /* (gdb) p ti $1 = (const std::type_info &) @0x80494c4: { _vptr.type_info = 0x804b160 <vtable for __cxxabiv1::__si_class_type_info@@CXXABI_1.3+8>, __name = 0x80494d0 <typeinfo name for Derived> "7Derived"} (gdb) p &ti $2 = (const std::type_info *) 0x80494c4 <typeinfo for Derived> (gdb) x/16x 0x80494c4 0x80494c4 <_ZTI7Derived>: 0x0804b160 0x080494d0 0x080494dc 0x72654437 0x80494d4 <_ZTS7Derived+4>: 0x64657669 0x00000000 0x0804b088 0x080494e4 0x80494e4 <_ZTS4base>: 0x73616234 0x00000065 0x0804b088 0x080494f4 0x80494f4 <_ZTS4Base>: 0x73614234 0x00000065 0x3b031b01 0x00000070 */ } #if 0 base=0xbffff150 20 derived=0xbffff150 24 Breakpoint 1, base::toString[abi:cxx11]() const (this=0xbffff150) at base.h:49 49 virtual const string toString() const { return data; } (gdb) x/8x 0xbffff150 0xbffff150: 0x08049254 0x31313131 0x31313131 0x31313131 # vtbl base::data 0xbffff160: 0x00313131 0xdddddddd # Derived::i (gdb) bt #0 base::toString[abi:cxx11]() const (this=0xbffff150) at base.h:49 #1 0x08049099 in Derived::toString[abi:cxx11]() const (this=0xbffff150) at vtbl.cpp:13 #2 0x08048eab in main () at vtbl.cpp:26 (gdb) x/4x 0x08049254 0x8049254 <_ZTV7Derived+8>: 0x08049082 0x00000000 (gdb) x/i 0x08049082 0x08049082 <Derived::toString[abi:cxx11]() const>: push %ebp (gdb) p pb->toString $6 = {const std::__cxx11::string (const base * const)} 0x8048fe4 <base::toString[abi:cxx11]() const> (gdb) p d.toString $7 = {const std::__cxx11::string (const Derived * const)} 0x8049082 <Derived::toString[abi:cxx11]() const> vtbl に入っているのは後者。でも、pb->toString をデバッガで見た結果が、 base のメンバ関数になっているのはなぜ。 Derived *pd = static_cast<Derived *>(pb); pd->i+= 7; pd = dynamic_cast<Derived *>(pb); pd->i-= 5; static_cast は、実行コードは無い。 (gdb) x/16i $eip => 0x8048cd7 <main()+268>: addl $0x7,-0x40(%ebp) 0x8048cdb <main()+272>: push $0x0 0x8048cdd <main()+274>: push $0x8048fe8 # なんだこれ 0x8048ce2 <main()+279>: push $0x8048fd4 0x8048ce7 <main()+284>: lea -0x54(%ebp),%eax 0x8048cea <main()+287>: push %eax 0x8048ceb <main()+288>: call 0x8048a00 <__dynamic_cast@plt> 0x8048cf0 <main()+293>: add $0x10,%esp 0x8048cf3 <main()+296>: subl $0x5,0x14(%eax) キャスト元先の型情報らしい。 (gdb) x/4x 0x8048fe8 0x8048fe8 <_ZTI7Derived>: 0x0804b154 0x08048fdc 0x08048fd4 0x00000000 (gdb) x/4x 0x8048fd4 0x8048fd4 <_ZTI4base>: 0x0804b088 0x08048fcc 0x72654437 0x64657669 (gdb) p/x $eax $4 = 0xbffff154 (gdb) info locals pb = 0xbffff154 #endif
31.242991
106
0.680826
Kanda-Motohiro
331e515b93ce7cf01cd50da5dbb9d26c669c895c
2,351
hpp
C++
src/xalanc/XercesParserLiaison/XercesNamedNodeMapAttributeList.hpp
rherardi/xml-xalan-c-src_1_10_0
24e6653a617a244e4def60d67b57e70a192a5d4d
[ "Apache-2.0" ]
null
null
null
src/xalanc/XercesParserLiaison/XercesNamedNodeMapAttributeList.hpp
rherardi/xml-xalan-c-src_1_10_0
24e6653a617a244e4def60d67b57e70a192a5d4d
[ "Apache-2.0" ]
null
null
null
src/xalanc/XercesParserLiaison/XercesNamedNodeMapAttributeList.hpp
rherardi/xml-xalan-c-src_1_10_0
24e6653a617a244e4def60d67b57e70a192a5d4d
[ "Apache-2.0" ]
null
null
null
/* * Copyright 1999-2004 The Apache Software 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. */ #if !defined(XERCESNAMEDNODEMAPATTRIBUTELIST_HEADER_GUARD_1357924680) #define XERCESNAMEDNODEMAPATTRIBUTELIST_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/XercesParserLiaison/XercesParserLiaisonDefinitions.hpp> #include <xercesc/sax/AttributeList.hpp> #include <xalanc/XercesParserLiaison/XercesWrapperTypes.hpp> XALAN_CPP_NAMESPACE_BEGIN class XALAN_XERCESPARSERLIAISON_EXPORT XercesNamedNodeMapAttributeList : public XERCES_CPP_NAMESPACE_QUALIFIER AttributeList { public: typedef XERCES_CPP_NAMESPACE_QUALIFIER AttributeList ParentType; explicit XercesNamedNodeMapAttributeList(const DOMNamedNodeMapType* theMap); virtual ~XercesNamedNodeMapAttributeList(); // These are inherited from AttributeList virtual unsigned int getLength() const; virtual const XMLCh* getName(const unsigned int index) const; virtual const XMLCh* getType(const unsigned int index) const; virtual const XMLCh* getValue(const unsigned int index) const; virtual const XMLCh* getType(const XMLCh* const name) const; virtual const XMLCh* getValue(const XMLCh* const name) const; private: virtual const XMLCh* getValue(const char* const name) const; // Not implemented... XercesNamedNodeMapAttributeList& operator=(const XercesNamedNodeMapAttributeList&); bool operator==(const XercesNamedNodeMapAttributeList&); // Data members... const DOMNamedNodeMapType* const m_nodeMap; const XMLSizeType m_lastIndex; static const XMLCh s_typeString[]; }; XALAN_CPP_NAMESPACE_END #endif // XERCESNAMEDNODEMAPATTRIBUTELIST_HEADER_GUARD_1357924680
24.489583
125
0.752871
rherardi
3322292d7db988d5153198c4568e26091ea35038
1,510
cc
C++
UnitTest/old_or_notused/util/string_test.cc
NosicLin/Faeris
018fddccc875fb63347673edef3ad2ff80c87149
[ "MIT" ]
null
null
null
UnitTest/old_or_notused/util/string_test.cc
NosicLin/Faeris
018fddccc875fb63347673edef3ad2ff80c87149
[ "MIT" ]
null
null
null
UnitTest/old_or_notused/util/string_test.cc
NosicLin/Faeris
018fddccc875fb63347673edef3ad2ff80c87149
[ "MIT" ]
null
null
null
#include"grstring.h" #include<stdio.h> #include<string.h> void print_string(const GrString& str) { printf("%s",str.c_str()); } #define Func_Test(func) \ do{ \ printf("Unit_Test(%s)---",#func); \ int ret; \ ret=func(); \ if(ret) \ { \ printf("(Ok)"); \ g_corret++; \ } \ else \ { \ printf("(Falied)"); \ g_error++; \ } \ printf("\n"); \ } while(0) int test_constructor() { char str[]="hello world"; GrString s(str); if(strcmp(s.c_str(),str)!=0) { return 0; } return 1; } int test_compare() { GrString s1("aaaa"); GrString s2("bbbb"); GrString s3("cccc"); GrString s4("bbbb"); if(s1.compare(s2)>=0) { return 0; } if(s2.compare(s1)<=0) { return 0; } if(s2.compare(s3)>=0) { return 0; } if(s3.compare(s2)<=0) { return 0; } if(s4.compare(s2)!=0) { return 0; } return 1; } int test_append() { char str_hello[]="hello"; char str_world[]="world"; GrString s; s.append(str_hello); s.append(" "); s.append(str_world); if(s.compare("hello world")!=0) { return 0; } GrString s2("hh"); s2.append("aaaaa",2); if(s2.compare("hhaa")!=0) { return 0; } GrString s3("hh"); GrString s4("aaaaa"); s3.append(s4,2); if(s3.compare("hhaa")!=0) { return 0; } return 1; } int g_error=0; int g_corret=0; int main() { Func_Test(test_constructor); Func_Test(test_compare); Func_Test(test_append); printf("Test Result All(%d) Correct(%d) Failed(%d)\n", g_error+g_corret,g_corret,g_error); return 0; }
11.889764
55
0.580132
NosicLin
33236e24ea72690d0313ce7f4790bb3d238e5510
951
hpp
C++
src/wire/wire2lua/mapped_type.hpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
5
2016-04-07T19:49:39.000Z
2021-08-03T05:24:11.000Z
src/wire/wire2lua/mapped_type.hpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
null
null
null
src/wire/wire2lua/mapped_type.hpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
1
2020-12-27T11:47:31.000Z
2020-12-27T11:47:31.000Z
/* * mapped_type.hpp * * Created on: 15 мая 2016 г. * Author: sergey.fedorov */ #ifndef WIRE_WIRE2LUA_MAPPED_TYPE_HPP_ #define WIRE_WIRE2LUA_MAPPED_TYPE_HPP_ #include <string> #include <vector> #include <map> #include <wire/idl/ast.hpp> namespace wire { namespace idl { namespace lua { struct mapped_type { static grammar::annotation_list const empty_annotations; ast::type_const_ptr type; grammar::annotation_list const& annotations = empty_annotations; mapped_type(ast::type_const_ptr t, grammar::annotation_list const& al = empty_annotations) : type{t}, annotations{al} {} }; inline mapped_type arg_type(ast::type_const_ptr t) { return { t }; } inline mapped_type arg_type(ast::type_const_ptr t, grammar::annotation_list const& al) { return { t, al }; } } /* namespace lua */ } /* namespace idl */ } /* namespace wire */ #endif /* WIRE_WIRE2LUA_MAPPED_TYPE_HPP_ */
18.647059
68
0.6898
zmij
3324cac708b1831a6e195ba880ee4ef9fb6701e9
646
cpp
C++
src/detail/string_convert.cpp
Guekka/libbsarch-cpp
ad435d488e9a816e0109a6f464961d177d3b61f4
[ "MIT" ]
1
2021-06-16T15:49:07.000Z
2021-06-16T15:49:07.000Z
src/detail/string_convert.cpp
Guekka/libbsarch-cpp
ad435d488e9a816e0109a6f464961d177d3b61f4
[ "MIT" ]
null
null
null
src/detail/string_convert.cpp
Guekka/libbsarch-cpp
ad435d488e9a816e0109a6f464961d177d3b61f4
[ "MIT" ]
null
null
null
/* Copyright (C) 2021 G'k * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #include "string_convert.hpp" #include <codecvt> #include <locale> namespace libbsarch::detail { static std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> s_converter; std::string to_string(const std::wstring &str) { return s_converter.to_bytes(str); } std::wstring to_wstring(const std::string &str) { return s_converter.from_bytes(str); } } // namespace libbsarch::detail
26.916667
75
0.704334
Guekka
3328adb3ce2e318a1b5a6ffec85e6d470df7f3a0
2,692
cpp
C++
tests/utils.cpp
vle-forge/Echll
f3895dc721ec891b5828fcd17aec0d37be07fb60
[ "BSD-2-Clause" ]
null
null
null
tests/utils.cpp
vle-forge/Echll
f3895dc721ec891b5828fcd17aec0d37be07fb60
[ "BSD-2-Clause" ]
null
null
null
tests/utils.cpp
vle-forge/Echll
f3895dc721ec891b5828fcd17aec0d37be07fb60
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2013-2014 INRA * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <vle/context.hpp> #include <vle/utils.hpp> #include <cstring> #define CATCH_CONFIG_MAIN #include "catch.hpp" TEST_CASE("try-stringf-format", "run") { const std::string str500( "01234567890123456789012345678901234567890123456789" "01234567890123456789012345678901234567890123456789" "01234567890123456789012345678901234567890123456789" "01234567890123456789012345678901234567890123456789" "01234567890123456789012345678901234567890123456789" "01234567890123456789012345678901234567890123456789" "01234567890123456789012345678901234567890123456789" "01234567890123456789012345678901234567890123456789" "01234567890123456789012345678901234567890123456789" "01234567890123456789012345678901234567890123456789"); std::string small = vle::stringf("%d %d %d", 1, 2, 3); REQUIRE(std::strcmp(small.c_str(), "1 2 3") == 0); REQUIRE(str500.size() == 500u); std::string big; REQUIRE_NOTHROW(big = vle::stringf("%s%s%s%s%s", str500.c_str(), str500.c_str(), str500.c_str(), str500.c_str(), str500.c_str())); REQUIRE(big.size() == (500u * 5 + 1)); }
44.866667
79
0.688707
vle-forge
06a4a6a81b66d5914b5cb512c057c76ba8f6183b
12,948
hxx
C++
src/engine/ivp/ivp_controller/ivp_car_system.hxx
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/engine/ivp/ivp_controller/ivp_car_system.hxx
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/engine/ivp/ivp_controller/ivp_car_system.hxx
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
// Copyright (C) Ipion Software GmbH 1999-2000. All rights reserved. // IVP_EXPORT_PUBLIC #if !defined(IVP_CAR_SYSTEM_INCLUDED) # define IVP_CAR_SYSTEM_INCLUDED #ifndef IVP_LISTENER_PSI_INCLUDED # include <ivp_listener_psi.hxx> #endif enum IVP_POS_WHEEL { IVP_FRONT_LEFT = 0, IVP_FRONT_RIGHT = 1, IVP_REAR_LEFT = 2, IVP_REAR_RIGHT = 3, IVP_CAR_SYSTEM_MAX_WHEELS = 10 }; enum IVP_POS_AXIS { IVP_FRONT = 0, IVP_REAR = 1, IVP_CAR_SYSTEM_MAX_AXIS = 5 }; class IVP_Real_Object; class IVP_Actuator_Torque; class IVP_Constraint_Solver_Car; class IVP_Template_Car_System { public: // Fill in template to build up a functional // car out of given (and set up) IVP_Real_Objects. int n_wheels; int n_axis; /*** Coordinate System Data ***/ /*** Coordinate System Data ***/ IVP_COORDINATE_INDEX index_x; IVP_COORDINATE_INDEX index_y; IVP_COORDINATE_INDEX index_z; IVP_BOOL is_left_handed; /*** Instance Data ***/ /*** Instance Data ***/ IVP_Real_Object *car_body; /******************************************************************************** * Name: car_wheel * Description: the wheels of the car * Note: Not needed of IVP_Controller_Raycast_Car ********************************************************************************/ IVP_Real_Object *car_wheel[IVP_CAR_SYSTEM_MAX_WHEELS]; // index according to IVP_POS_WHEEL IVP_FLOAT friction_of_wheel[IVP_CAR_SYSTEM_MAX_WHEELS]; // to be set for IVP_Controller_Raycast_Car IVP_FLOAT wheel_radius[IVP_CAR_SYSTEM_MAX_WHEELS]; IVP_FLOAT wheel_reversed_sign[IVP_CAR_SYSTEM_MAX_WHEELS]; // Default: 1.0f. Use -1.0f when wheels are turned by 180 degrees. IVP_FLOAT body_counter_torque_factor; // (e.g. 0.3f) for nose dive etc. produced by wheel torque IVP_FLOAT extra_gravity_force_value; // additional gravity force IVP_FLOAT extra_gravity_height_offset; // force anchor height offset relative to center of mass IVP_FLOAT body_down_force_vertical_offset; // vertical offset to mass center for tilted object IVP_FLOAT fast_turn_factor; /*** Archetype Data ***/ /*** Archetype Data ***/ // Standard wheel position IVP_U_Float_Point wheel_pos_Bos[IVP_CAR_SYSTEM_MAX_WHEELS]; // standard position of wheel centers in body's object system IVP_U_Float_Point trace_pos_Bos[IVP_CAR_SYSTEM_MAX_WHEELS]; // standard position of trace centers in body's object system // Springs IVP_FLOAT spring_constant[IVP_CAR_SYSTEM_MAX_WHEELS]; // [Newton/m] IVP_FLOAT spring_dampening[IVP_CAR_SYSTEM_MAX_WHEELS]; // for releasing springs IVP_FLOAT spring_dampening_compression[IVP_CAR_SYSTEM_MAX_WHEELS]; // for compressing springs IVP_FLOAT max_body_force[IVP_CAR_SYSTEM_MAX_WHEELS]; // clipping of spring forces. Reduces the jumpy behaviour of cars with heavy wheels IVP_FLOAT spring_pre_tension[IVP_CAR_SYSTEM_MAX_WHEELS]; // [m] used to keep the wheels at the original position IVP_FLOAT raycast_startpoint_height_offset; // Stabilizer IVP_FLOAT stabilizer_constant[IVP_CAR_SYSTEM_MAX_AXIS]; // [Newton/m] // Etc IVP_FLOAT wheel_max_rotation_speed[IVP_CAR_SYSTEM_MAX_AXIS]; // Car System Setup IVP_Template_Car_System(int n_wheels_, int n_axis_) { P_MEM_CLEAR(this); n_wheels = n_wheels_; n_axis = n_axis_; for (int i = 0; i < n_wheels; i++) { // not reversed by default this->wheel_reversed_sign[i] = 1.0f; // default coordinate system definition index_x = IVP_INDEX_X; index_y = IVP_INDEX_Y; index_z = IVP_INDEX_Z; is_left_handed = IVP_FALSE; } fast_turn_factor = 1.0f; }; }; class IVP_Wheel_Skid_Info { public: IVP_U_Float_Point last_contact_position_ws; IVP_FLOAT last_skid_value; // 0 means no skidding, values > 0 means skidding, check yourself for reasonable ranges IVP_Time last_skid_time; }; struct IVP_CarSystemDebugData_t { IVP_U_Point wheelRaycasts[IVP_CAR_SYSTEM_MAX_WHEELS][2]; // wheels, start = 0, end = 1 IVP_FLOAT wheelRaycastImpacts[IVP_CAR_SYSTEM_MAX_WHEELS]; // wheels, impact raycast floating point min distance // 4-wheel vehicle. IVP_FLOAT wheelRotationalTorque[4][3]; IVP_FLOAT wheelTranslationTorque[4][3]; IVP_U_Float_Point backActuatorLeft; IVP_U_Float_Point backActuatorRight; IVP_U_Float_Point frontActuatorLeft; IVP_U_Float_Point frontActuatorRight; }; class IVP_Car_System { public: virtual ~IVP_Car_System(); IVP_Car_System(); virtual void do_steering_wheel(IVP_POS_WHEEL wheel_pos, IVP_FLOAT s_angle) = 0; // called by do_steering() // Car Adjustment virtual void change_spring_constant(IVP_POS_WHEEL pos, IVP_FLOAT spring_constant) = 0; // [Newton/meter] virtual void change_spring_dampening(IVP_POS_WHEEL pos, IVP_FLOAT spring_dampening) = 0; // when spring is relaxing spring virtual void change_spring_dampening_compression(IVP_POS_WHEEL pos, IVP_FLOAT spring_dampening) = 0; // [Newton/meter] for compressing spring virtual void change_max_body_force(IVP_POS_WHEEL wheel_nr, IVP_FLOAT mforce) = 0; virtual void change_spring_pre_tension(IVP_POS_WHEEL pos, IVP_FLOAT pre_tension_length) = 0; virtual void change_spring_length(IVP_POS_WHEEL wheel_nr, IVP_FLOAT spring_length) = 0; virtual void change_stabilizer_constant(IVP_POS_AXIS pos, IVP_FLOAT stabi_constant) = 0; // [Newton/meter] virtual void change_fast_turn_factor(IVP_FLOAT fast_turn_factor) = 0; virtual void change_wheel_torque(IVP_POS_WHEEL pos, IVP_FLOAT torque) = 0; virtual void update_body_countertorque() = 0; // rotate the body in the opposite direction of the wheels virtual void update_throttle(IVP_FLOAT flThrottle) = 0; virtual void change_body_downforce(IVP_FLOAT force) = 0; // extra force to keep flipped objects flipped over virtual void fix_wheel(IVP_POS_WHEEL, IVP_BOOL stop_wheel) = 0; // stop wheel completely (e.g. handbrake ) // Car Info virtual IVP_DOUBLE get_body_speed(IVP_COORDINATE_INDEX idx_z = IVP_INDEX_Z) = 0; // km/h in 'z' direction virtual IVP_DOUBLE get_wheel_angular_velocity(IVP_POS_WHEEL) = 0; virtual void update_wheel_positions() = 0; // move graphical wheels to correct position virtual IVP_DOUBLE get_orig_front_wheel_distance() = 0; virtual IVP_DOUBLE get_orig_axles_distance() = 0; virtual void get_skid_info(IVP_Wheel_Skid_Info *array_of_skid_info_out) = 0; virtual void set_powerslide(IVP_FLOAT front_accel, IVP_FLOAT rear_accel) = 0; // Tools static IVP_FLOAT calc_ackerman_angle(IVP_FLOAT alpha, IVP_FLOAT dx, IVP_FLOAT dz); // alpha refers to innermost wheel /**** Methods: 2nd Level, based on primitives ****/ /**** Methods: 2nd Level, based on primitives ****/ virtual void do_steering(IVP_FLOAT steering_angle_in, bool bAnalog = false) = 0; // updates this->steering_angle virtual void set_booster_acceleration(IVP_FLOAT acceleration) = 0; // set an additional accerleration force virtual void activate_booster(IVP_FLOAT thrust, IVP_FLOAT duration, IVP_FLOAT recharge_time) = 0; // set a temporary acceleration force as a factor of gravity virtual void update_booster( IVP_FLOAT delta_time) = 0; // should be called every frame to allow the physics system to deactivate a booster virtual IVP_FLOAT get_booster_delay() = 0; virtual IVP_FLOAT get_booster_time_to_go() = 0; // Debug (Getting debug data out to vphysics and the engine to be rendered!) virtual void SetCarSystemDebugData(const IVP_CarSystemDebugData_t &carSystemDebugData) = 0; virtual void GetCarSystemDebugData(IVP_CarSystemDebugData_t &carSystemDebugData) = 0; // handle events virtual void event_object_deleted(IVP_Event_Object *pEvent) {}; }; class IVP_Car_System_Real_Wheels : public IVP_Car_System { private: IVP_Environment *environment; int n_wheels; // number of wheels int n_axis; protected: IVP_Real_Object *car_body; IVP_Real_Object *car_wheel[IVP_CAR_SYSTEM_MAX_WHEELS]; // index according to IVP_POS_WHEEL IVP_Constraint_Solver_Car *car_constraint_solver; IVP_Actuator_Torque *car_act_torque_body; IVP_Actuator_Torque *car_act_torque[IVP_CAR_SYSTEM_MAX_WHEELS]; IVP_Actuator_Suspension *car_spring[IVP_CAR_SYSTEM_MAX_WHEELS]; IVP_Actuator_Stabilizer *car_stabilizer[IVP_CAR_SYSTEM_MAX_AXIS]; IVP_Actuator_Force *car_act_down_force; IVP_Actuator_Force *car_act_extra_gravity; IVP_Actuator_Force *car_act_powerslide_back; IVP_Actuator_Force *car_act_powerslide_front; IVP_Constraint *fix_wheel_constraint[IVP_CAR_SYSTEM_MAX_WHEELS]; IVP_FLOAT wheel_reversed_sign[IVP_CAR_SYSTEM_MAX_WHEELS]; // Default: 1.0f. Use -1.0f when wheels are turned by 180 degrees. IVP_FLOAT wheel_radius[IVP_CAR_SYSTEM_MAX_WHEELS]; IVP_FLOAT body_counter_torque_factor; // response to wheel torque, e.g. 0.3f (for nose dive etc.), call update_body_countertorque() when all wheel torques are changed IVP_FLOAT max_speed; IVP_FLOAT fast_turn_factor; // factor to angular accelerates the car if the wheels are steered ( 0.0f no effect 1.0f strong effect ) // booster IVP_Actuator_Force *booster_actuator[2]; IVP_FLOAT booster_seconds_to_go; IVP_FLOAT booster_seconds_until_ready; IVP_FLOAT steering_angle; // Debug IVP_CarSystemDebugData_t m_CarSystemDebugData; virtual void environment_will_be_deleted(IVP_Environment *); public: /**** Methods: Primitives ****/ /**** Methods: Primitives ****/ // Car Basics IVP_Car_System_Real_Wheels(IVP_Environment *environment, IVP_Template_Car_System *); virtual ~IVP_Car_System_Real_Wheels(); void do_steering_wheel(IVP_POS_WHEEL wheel_pos, IVP_FLOAT s_angle); // called by do_steering() // Car Adjustment void change_spring_constant(IVP_POS_WHEEL pos, IVP_FLOAT spring_constant); // [Newton/meter] void change_spring_dampening(IVP_POS_WHEEL pos, IVP_FLOAT spring_dampening); // when spring is relaxing spring void change_spring_dampening_compression(IVP_POS_WHEEL pos, IVP_FLOAT spring_dampening); // [Newton/meter] for compressing spring void change_max_body_force(IVP_POS_WHEEL wheel_nr, IVP_FLOAT mforce); void change_spring_pre_tension(IVP_POS_WHEEL pos, IVP_FLOAT pre_tension_length); void change_spring_length(IVP_POS_WHEEL wheel_nr, IVP_FLOAT spring_length); void change_stabilizer_constant(IVP_POS_AXIS pos, IVP_FLOAT stabi_constant); // [Newton/meter] void change_fast_turn_factor(IVP_FLOAT); void change_wheel_torque(IVP_POS_WHEEL pos, IVP_FLOAT torque); void change_wheel_speed_dampening(IVP_POS_WHEEL wheel_nr, IVP_FLOAT dampening); void update_body_countertorque(); // rotate the body in the opposite direction of the wheels void update_throttle(IVP_FLOAT /*flThrottle*/) {} void change_body_downforce(IVP_FLOAT force); // extra force to keep flipped objects flipped over void fix_wheel(IVP_POS_WHEEL, IVP_BOOL stop_wheel); // stop wheel completely (e.g. handbrake ) // Car Info IVP_DOUBLE get_body_speed(IVP_COORDINATE_INDEX idx_z = IVP_INDEX_Z); // km/h in 'z' direction IVP_DOUBLE get_wheel_angular_velocity(IVP_POS_WHEEL); void update_wheel_positions() { ; }; IVP_DOUBLE get_orig_front_wheel_distance(); IVP_DOUBLE get_orig_axles_distance(); void get_skid_info(IVP_Wheel_Skid_Info *array_of_skid_info_out); void set_powerslide(IVP_FLOAT front_accel, IVP_FLOAT rear_accel); /**** Methods: 2nd Level, based on primitives ****/ /**** Methods: 2nd Level, based on primitives ****/ virtual void do_steering(IVP_FLOAT steering_angle_in, bool bAnalog = false); // updates this->steering_angle void set_booster_acceleration(IVP_FLOAT acceleration); void activate_booster(IVP_FLOAT thrust, IVP_FLOAT duration, IVP_FLOAT recharge_time); void update_booster(IVP_FLOAT delta_time); virtual IVP_FLOAT get_booster_delay(); virtual IVP_FLOAT get_booster_time_to_go() { return booster_seconds_to_go; } // Debug void SetCarSystemDebugData(const IVP_CarSystemDebugData_t &carSystemDebugData); void GetCarSystemDebugData(IVP_CarSystemDebugData_t &carSystemDebugData); }; #endif /* defined IVP_CAR_SYSTEM_INCLUDED */
39.355623
171
0.716095
cstom4994
06aa8e5d64bd0e3e225cbafeb44e93ff3eeb4c28
345
cpp
C++
20200320STL_1/E.FreeListSort.cpp
Guyutongxue/Practice_of_Programming
70e11cfc0ab6aefbc9e28b279cf3de110426a9b9
[ "WTFPL" ]
6
2020-03-01T03:13:37.000Z
2021-03-20T13:37:11.000Z
20200320STL_1/E.FreeListSort.cpp
Guyutongxue/Practice_of_Programming
70e11cfc0ab6aefbc9e28b279cf3de110426a9b9
[ "WTFPL" ]
null
null
null
20200320STL_1/E.FreeListSort.cpp
Guyutongxue/Practice_of_Programming
70e11cfc0ab6aefbc9e28b279cf3de110426a9b9
[ "WTFPL" ]
3
2020-03-28T03:14:24.000Z
2021-05-20T13:35:15.000Z
#include <algorithm> #include <cstdio> #include <iostream> #include <list> using namespace std; int main() { double a[] = {1.2, 3.4, 9.8, 7.3, 2.6}; list<double> lst(a, a + 5); lst.sort( greater<double>() ); for (list<double>::iterator i = lst.begin(); i != lst.end(); ++i) cout << *i << ","; return 0; }
21.5625
69
0.527536
Guyutongxue
06ad05985faa3bae9721a406604ce4042fd6a99f
5,356
cc
C++
chrome/browser/extensions/launch_util.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/extensions/launch_util.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/extensions/launch_util.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/launch_util.h" #include <memory> #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/extensions/extension_sync_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/web_applications/extensions/bookmark_app_util.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/manifest_handlers/app_launch_info.h" #include "components/pref_registry/pref_registry_syncable.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/pref_names.h" #include "extensions/common/extension.h" namespace extensions { namespace { // A preference set by the the NTP to persist the desired launch container type // used for apps. const char kPrefLaunchType[] = "launchType"; } // namespace LaunchType GetLaunchType(const ExtensionPrefs* prefs, const Extension* extension) { LaunchType result = LAUNCH_TYPE_DEFAULT; int value = GetLaunchTypePrefValue(prefs, extension->id()); if (value >= LAUNCH_TYPE_FIRST && value < NUM_LAUNCH_TYPES) result = static_cast<LaunchType>(value); // Force hosted apps that are not locally installed to open in tabs. if (extension->is_hosted_app() && !BookmarkAppIsLocallyInstalled(prefs, extension)) { result = LAUNCH_TYPE_REGULAR; } else if (result == LAUNCH_TYPE_PINNED) { result = LAUNCH_TYPE_REGULAR; } else if (result == LAUNCH_TYPE_FULLSCREEN) { result = LAUNCH_TYPE_WINDOW; } return result; } LaunchType GetLaunchTypePrefValue(const ExtensionPrefs* prefs, const std::string& extension_id) { int value = LAUNCH_TYPE_INVALID; return prefs->ReadPrefAsInteger(extension_id, kPrefLaunchType, &value) ? static_cast<LaunchType>(value) : LAUNCH_TYPE_INVALID; } void SetLaunchType(content::BrowserContext* context, const std::string& extension_id, LaunchType launch_type) { DCHECK(launch_type >= LAUNCH_TYPE_FIRST && launch_type < NUM_LAUNCH_TYPES); ExtensionPrefs::Get(context)->UpdateExtensionPref( extension_id, kPrefLaunchType, std::make_unique<base::Value>(static_cast<int>(launch_type))); // Sync the launch type. const Extension* extension = ExtensionRegistry::Get(context) ->GetExtensionById(extension_id, ExtensionRegistry::EVERYTHING); if (extension) ExtensionSyncService::Get(context)->SyncExtensionChangeIfNeeded(*extension); } LaunchContainer GetLaunchContainer(const ExtensionPrefs* prefs, const Extension* extension) { LaunchContainer manifest_launch_container = AppLaunchInfo::GetLaunchContainer(extension); base::Optional<LaunchContainer> result; if (manifest_launch_container == LaunchContainer::kLaunchContainerPanelDeprecated) { result = manifest_launch_container; } else if (manifest_launch_container == LaunchContainer::kLaunchContainerTab) { // Look for prefs that indicate the user's choice of launch container. The // app's menu on the NTP provides a UI to set this preference. LaunchType prefs_launch_type = GetLaunchType(prefs, extension); if (prefs_launch_type == LAUNCH_TYPE_WINDOW) { // If the pref is set to launch a window (or no pref is set, and // window opening is the default), make the container a window. result = LaunchContainer::kLaunchContainerWindow; #if defined(OS_CHROMEOS) } else if (prefs_launch_type == LAUNCH_TYPE_FULLSCREEN) { // LAUNCH_TYPE_FULLSCREEN launches in a maximized app window in ash. // For desktop chrome AURA on all platforms we should open the // application in full screen mode in the current tab, on the same // lines as non AURA chrome. result = LaunchContainer::kLaunchContainerWindow; #endif } else { // All other launch types (tab, pinned, fullscreen) are // implemented as tabs in a window. result = LaunchContainer::kLaunchContainerTab; } } else { // If a new value for app.launch.container is added, logic for it should be // added here. LaunchContainer::kLaunchContainerWindow is not present // because there is no way to set it in a manifest. NOTREACHED() << manifest_launch_container; } // All paths should set |result|. if (!result) { DLOG(FATAL) << "Failed to set a launch container."; result = LaunchContainer::kLaunchContainerTab; } return *result; } bool HasPreferredLaunchContainer(const ExtensionPrefs* prefs, const Extension* extension) { int value = -1; LaunchContainer manifest_launch_container = AppLaunchInfo::GetLaunchContainer(extension); return manifest_launch_container == LaunchContainer::kLaunchContainerTab && prefs->ReadPrefAsInteger(extension->id(), kPrefLaunchType, &value); } bool LaunchesInWindow(content::BrowserContext* context, const Extension* extension) { return GetLaunchType(ExtensionPrefs::Get(context), extension) == LAUNCH_TYPE_WINDOW; } } // namespace extensions
38.257143
80
0.721994
sarang-apps
06b2e87c112c8693703f7996a2c56d9dd127ff57
118
cpp
C++
Plugin~/Src/MeshSync/MeshSyncConstants.cpp
Mu-L/MeshSync
6290618f6cc60802394bda8e2aa177648fcf5cfd
[ "Apache-2.0" ]
1,047
2017-02-01T01:56:55.000Z
2022-03-30T10:27:07.000Z
Plugin~/Src/MeshSync/MeshSyncConstants.cpp
Mu-L/MeshSync
6290618f6cc60802394bda8e2aa177648fcf5cfd
[ "Apache-2.0" ]
112
2017-03-03T09:10:01.000Z
2022-03-24T16:25:20.000Z
Plugin~/Src/MeshSync/MeshSyncConstants.cpp
Mu-L/MeshSync
6290618f6cc60802394bda8e2aa177648fcf5cfd
[ "Apache-2.0" ]
120
2017-07-26T22:25:59.000Z
2022-02-22T06:15:42.000Z
#include "MeshSync/MeshSyncConstants.h" namespace ms { const uint32_t MeshSyncConstants::MAX_UV; } //end namespace
14.75
41
0.779661
Mu-L
06b3eb3ccbd708291794a1091be8181e797b4350
2,770
hpp
C++
code/lib/graph_operations.hpp
Brunovsky/competitive
41cf49378e430ca20d844f97c67aa5059ab1e973
[ "MIT" ]
7
2020-10-15T22:37:10.000Z
2022-02-26T17:23:49.000Z
code/lib/graph_operations.hpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
code/lib/graph_operations.hpp
brunodccarvalho/competitive
4177c439174fbe749293b9da3445ce7303bd23c2
[ "MIT" ]
null
null
null
#pragma once #include "hash.hpp" #include "random.hpp" using edges_t = vector<array<int, 2>>; /** * Construct adjacency lists */ auto make_adjacency_lists_undirected(int V, const edges_t& g) { vector<vector<int>> adj(V); for (auto [u, v] : g) assert(u < V && v < V), adj[u].push_back(v), adj[v].push_back(u); return adj; } auto make_adjacency_lists_directed(int V, const edges_t& g) { vector<vector<int>> adj(V); for (auto [u, v] : g) assert(u < V && v < V), adj[u].push_back(v); return adj; } auto make_adjacency_lists_reverse(int V, const edges_t& g) { vector<vector<int>> adj(V); for (auto [u, v] : g) assert(u < V && v < V), adj[v].push_back(u); return adj; } auto make_adjacency_set_undirected(const edges_t& g) { unordered_set<array<int, 2>> adj; for (auto [u, v] : g) u < v ? adj.insert({u, v}) : adj.insert({v, u}); return adj; } auto make_adjacency_set_directed(const edges_t& g) { unordered_set<array<int, 2>> adj; for (auto [u, v] : g) adj.insert({u, v}); return adj; } auto make_adjacency_set_reverse(const edges_t& g) { unordered_set<array<int, 2>> adj; for (auto [u, v] : g) adj.insert({v, u}); return adj; } /** * Check if a graph is (strongly) connected */ int count_reachable(const vector<vector<int>>& adj, int s = 0) { int i = 0, S = 1, V = adj.size(); vector<int> bfs{s}; vector<bool> vis(V, false); vis[s] = true; while (i++ < S && S < V) { for (int v : adj[bfs[i - 1]]) { if (!vis[v]) { vis[v] = true, S++; bfs.push_back(v); } } } return S; } bool reachable(const vector<vector<int>>& adj, int s, int t) { int i = 0, S = 1, V = adj.size(); vector<bool> vis(V, false); vector<int> bfs{s}; vis[s] = true; while (i++ < S && S < V) { for (int v : adj[bfs[i - 1]]) { if (!vis[v]) { vis[v] = true, S++; bfs.push_back(v); if (v == t) return true; } } } return false; } bool is_connected_undirected(const edges_t& g, int V) { assert(V > 0); auto adj = make_adjacency_lists_undirected(V, g); return count_reachable(adj) == V; } bool is_connected_directed(const edges_t& g, int V) { assert(V > 0); auto adj = make_adjacency_lists_directed(V, g); if (count_reachable(adj) != V) return false; adj = make_adjacency_lists_reverse(V, g); return count_reachable(adj) == V; } bool is_rooted_directed(const edges_t& g, int V, int s = 0) { assert(V > 0); auto adj = make_adjacency_lists_directed(V, g); return count_reachable(adj, s) == V; }
25.181818
73
0.552708
Brunovsky
06b4a9405c7fc27d5c3844ad93dbd66cc5c6c601
800
cpp
C++
src/backend/expression/tuple_address_expression.cpp
jessesleeping/my_peloton
a19426cfe34a04692a11008eaffc9c3c9b49abc4
[ "Apache-2.0" ]
6
2017-04-28T00:38:52.000Z
2018-11-06T07:06:49.000Z
src/backend/expression/tuple_address_expression.cpp
jessesleeping/my_peloton
a19426cfe34a04692a11008eaffc9c3c9b49abc4
[ "Apache-2.0" ]
4
2017-07-08T00:41:56.000Z
2017-07-08T00:42:13.000Z
src/backend/expression/tuple_address_expression.cpp
eric-haibin-lin/pelotondb
904d6bbd041a0498ee0e034d4f9f9f27086c3cab
[ "Apache-2.0" ]
1
2020-06-19T08:05:03.000Z
2020-06-19T08:05:03.000Z
//===----------------------------------------------------------------------===// // // PelotonDB // // tuple_address_expression.cpp // // Identification: src/backend/expression/tuple_address_expression.cpp // // Copyright (c) 2015, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "backend/expression/tuple_address_expression.h" #include "backend/common/logger.h" #include "backend/expression/abstract_expression.h" namespace peloton { namespace expression { TupleAddressExpression::TupleAddressExpression() : AbstractExpression(EXPRESSION_TYPE_VALUE_TUPLE_ADDRESS) {} TupleAddressExpression::~TupleAddressExpression() {} } // End expression namespace } // End peloton namespace
29.62963
80
0.60625
jessesleeping
06b5f8c149cd7360c43382bef6ae7fb3c9bd3c69
18,024
cxx
C++
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimPerformanceCurve_Mathematical_FanPressureRise.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
3
2016-05-30T15:12:16.000Z
2022-03-22T08:11:13.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimPerformanceCurve_Mathematical_FanPressureRise.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
21
2016-06-13T11:33:45.000Z
2017-05-23T09:46:52.000Z
SimModel_Python_API/simmodel_swig/SimModel_Dll_lib/framework/SimPerformanceCurve_Mathematical_FanPressureRise.cxx
EnEff-BIM/EnEffBIM-Framework
6328d39b498dc4065a60b5cc9370b8c2a9a1cddf
[ "MIT" ]
null
null
null
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // // Begin prologue. // // // End prologue. #include <xsd/cxx/pre.hxx> #include "SimPerformanceCurve_Mathematical_FanPressureRise.hxx" namespace schema { namespace simxml { namespace ResourcesGeometry { // SimPerformanceCurve_Mathematical_FanPressureRise // const SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_Coeff1C1_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff1C1 () const { return this->SimPerfCurve_Coeff1C1_; } SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_Coeff1C1_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff1C1 () { return this->SimPerfCurve_Coeff1C1_; } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff1C1 (const SimPerfCurve_Coeff1C1_type& x) { this->SimPerfCurve_Coeff1C1_.set (x); } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff1C1 (const SimPerfCurve_Coeff1C1_optional& x) { this->SimPerfCurve_Coeff1C1_ = x; } const SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_Coeff2C2_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff2C2 () const { return this->SimPerfCurve_Coeff2C2_; } SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_Coeff2C2_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff2C2 () { return this->SimPerfCurve_Coeff2C2_; } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff2C2 (const SimPerfCurve_Coeff2C2_type& x) { this->SimPerfCurve_Coeff2C2_.set (x); } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff2C2 (const SimPerfCurve_Coeff2C2_optional& x) { this->SimPerfCurve_Coeff2C2_ = x; } const SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_Coeff3C3_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff3C3 () const { return this->SimPerfCurve_Coeff3C3_; } SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_Coeff3C3_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff3C3 () { return this->SimPerfCurve_Coeff3C3_; } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff3C3 (const SimPerfCurve_Coeff3C3_type& x) { this->SimPerfCurve_Coeff3C3_.set (x); } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff3C3 (const SimPerfCurve_Coeff3C3_optional& x) { this->SimPerfCurve_Coeff3C3_ = x; } const SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_Coeff4C4_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff4C4 () const { return this->SimPerfCurve_Coeff4C4_; } SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_Coeff4C4_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff4C4 () { return this->SimPerfCurve_Coeff4C4_; } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff4C4 (const SimPerfCurve_Coeff4C4_type& x) { this->SimPerfCurve_Coeff4C4_.set (x); } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_Coeff4C4 (const SimPerfCurve_Coeff4C4_optional& x) { this->SimPerfCurve_Coeff4C4_ = x; } const SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_MinValueOfQfan_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MinValueOfQfan () const { return this->SimPerfCurve_MinValueOfQfan_; } SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_MinValueOfQfan_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MinValueOfQfan () { return this->SimPerfCurve_MinValueOfQfan_; } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MinValueOfQfan (const SimPerfCurve_MinValueOfQfan_type& x) { this->SimPerfCurve_MinValueOfQfan_.set (x); } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MinValueOfQfan (const SimPerfCurve_MinValueOfQfan_optional& x) { this->SimPerfCurve_MinValueOfQfan_ = x; } const SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_MaxValueOfQfan_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MaxValueOfQfan () const { return this->SimPerfCurve_MaxValueOfQfan_; } SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_MaxValueOfQfan_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MaxValueOfQfan () { return this->SimPerfCurve_MaxValueOfQfan_; } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MaxValueOfQfan (const SimPerfCurve_MaxValueOfQfan_type& x) { this->SimPerfCurve_MaxValueOfQfan_.set (x); } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MaxValueOfQfan (const SimPerfCurve_MaxValueOfQfan_optional& x) { this->SimPerfCurve_MaxValueOfQfan_ = x; } const SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_MinValueOfPsm_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MinValueOfPsm () const { return this->SimPerfCurve_MinValueOfPsm_; } SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_MinValueOfPsm_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MinValueOfPsm () { return this->SimPerfCurve_MinValueOfPsm_; } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MinValueOfPsm (const SimPerfCurve_MinValueOfPsm_type& x) { this->SimPerfCurve_MinValueOfPsm_.set (x); } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MinValueOfPsm (const SimPerfCurve_MinValueOfPsm_optional& x) { this->SimPerfCurve_MinValueOfPsm_ = x; } const SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_MaxValueOfPsm_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MaxValueOfPsm () const { return this->SimPerfCurve_MaxValueOfPsm_; } SimPerformanceCurve_Mathematical_FanPressureRise::SimPerfCurve_MaxValueOfPsm_optional& SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MaxValueOfPsm () { return this->SimPerfCurve_MaxValueOfPsm_; } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MaxValueOfPsm (const SimPerfCurve_MaxValueOfPsm_type& x) { this->SimPerfCurve_MaxValueOfPsm_.set (x); } void SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerfCurve_MaxValueOfPsm (const SimPerfCurve_MaxValueOfPsm_optional& x) { this->SimPerfCurve_MaxValueOfPsm_ = x; } } } } #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; } namespace schema { namespace simxml { namespace ResourcesGeometry { // SimPerformanceCurve_Mathematical_FanPressureRise // SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerformanceCurve_Mathematical_FanPressureRise () : ::schema::simxml::ResourcesGeometry::SimPerformanceCurve_Mathematical (), SimPerfCurve_Coeff1C1_ (this), SimPerfCurve_Coeff2C2_ (this), SimPerfCurve_Coeff3C3_ (this), SimPerfCurve_Coeff4C4_ (this), SimPerfCurve_MinValueOfQfan_ (this), SimPerfCurve_MaxValueOfQfan_ (this), SimPerfCurve_MinValueOfPsm_ (this), SimPerfCurve_MaxValueOfPsm_ (this) { } SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerformanceCurve_Mathematical_FanPressureRise (const RefId_type& RefId) : ::schema::simxml::ResourcesGeometry::SimPerformanceCurve_Mathematical (RefId), SimPerfCurve_Coeff1C1_ (this), SimPerfCurve_Coeff2C2_ (this), SimPerfCurve_Coeff3C3_ (this), SimPerfCurve_Coeff4C4_ (this), SimPerfCurve_MinValueOfQfan_ (this), SimPerfCurve_MaxValueOfQfan_ (this), SimPerfCurve_MinValueOfPsm_ (this), SimPerfCurve_MaxValueOfPsm_ (this) { } SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerformanceCurve_Mathematical_FanPressureRise (const SimPerformanceCurve_Mathematical_FanPressureRise& x, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::ResourcesGeometry::SimPerformanceCurve_Mathematical (x, f, c), SimPerfCurve_Coeff1C1_ (x.SimPerfCurve_Coeff1C1_, f, this), SimPerfCurve_Coeff2C2_ (x.SimPerfCurve_Coeff2C2_, f, this), SimPerfCurve_Coeff3C3_ (x.SimPerfCurve_Coeff3C3_, f, this), SimPerfCurve_Coeff4C4_ (x.SimPerfCurve_Coeff4C4_, f, this), SimPerfCurve_MinValueOfQfan_ (x.SimPerfCurve_MinValueOfQfan_, f, this), SimPerfCurve_MaxValueOfQfan_ (x.SimPerfCurve_MaxValueOfQfan_, f, this), SimPerfCurve_MinValueOfPsm_ (x.SimPerfCurve_MinValueOfPsm_, f, this), SimPerfCurve_MaxValueOfPsm_ (x.SimPerfCurve_MaxValueOfPsm_, f, this) { } SimPerformanceCurve_Mathematical_FanPressureRise:: SimPerformanceCurve_Mathematical_FanPressureRise (const ::xercesc::DOMElement& e, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::ResourcesGeometry::SimPerformanceCurve_Mathematical (e, f | ::xml_schema::flags::base, c), SimPerfCurve_Coeff1C1_ (this), SimPerfCurve_Coeff2C2_ (this), SimPerfCurve_Coeff3C3_ (this), SimPerfCurve_Coeff4C4_ (this), SimPerfCurve_MinValueOfQfan_ (this), SimPerfCurve_MaxValueOfQfan_ (this), SimPerfCurve_MinValueOfPsm_ (this), SimPerfCurve_MaxValueOfPsm_ (this) { if ((f & ::xml_schema::flags::base) == 0) { ::xsd::cxx::xml::dom::parser< char > p (e, true, false, true); this->parse (p, f); } } void SimPerformanceCurve_Mathematical_FanPressureRise:: parse (::xsd::cxx::xml::dom::parser< char >& p, ::xml_schema::flags f) { this->::schema::simxml::ResourcesGeometry::SimPerformanceCurve_Mathematical::parse (p, f); for (; p.more_content (); p.next_content (false)) { const ::xercesc::DOMElement& i (p.cur_element ()); const ::xsd::cxx::xml::qualified_name< char > n ( ::xsd::cxx::xml::dom::name< char > (i)); // SimPerfCurve_Coeff1C1 // if (n.name () == "SimPerfCurve_Coeff1C1" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeometry") { if (!this->SimPerfCurve_Coeff1C1_) { this->SimPerfCurve_Coeff1C1_.set (SimPerfCurve_Coeff1C1_traits::create (i, f, this)); continue; } } // SimPerfCurve_Coeff2C2 // if (n.name () == "SimPerfCurve_Coeff2C2" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeometry") { if (!this->SimPerfCurve_Coeff2C2_) { this->SimPerfCurve_Coeff2C2_.set (SimPerfCurve_Coeff2C2_traits::create (i, f, this)); continue; } } // SimPerfCurve_Coeff3C3 // if (n.name () == "SimPerfCurve_Coeff3C3" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeometry") { if (!this->SimPerfCurve_Coeff3C3_) { this->SimPerfCurve_Coeff3C3_.set (SimPerfCurve_Coeff3C3_traits::create (i, f, this)); continue; } } // SimPerfCurve_Coeff4C4 // if (n.name () == "SimPerfCurve_Coeff4C4" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeometry") { if (!this->SimPerfCurve_Coeff4C4_) { this->SimPerfCurve_Coeff4C4_.set (SimPerfCurve_Coeff4C4_traits::create (i, f, this)); continue; } } // SimPerfCurve_MinValueOfQfan // if (n.name () == "SimPerfCurve_MinValueOfQfan" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeometry") { if (!this->SimPerfCurve_MinValueOfQfan_) { this->SimPerfCurve_MinValueOfQfan_.set (SimPerfCurve_MinValueOfQfan_traits::create (i, f, this)); continue; } } // SimPerfCurve_MaxValueOfQfan // if (n.name () == "SimPerfCurve_MaxValueOfQfan" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeometry") { if (!this->SimPerfCurve_MaxValueOfQfan_) { this->SimPerfCurve_MaxValueOfQfan_.set (SimPerfCurve_MaxValueOfQfan_traits::create (i, f, this)); continue; } } // SimPerfCurve_MinValueOfPsm // if (n.name () == "SimPerfCurve_MinValueOfPsm" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeometry") { if (!this->SimPerfCurve_MinValueOfPsm_) { this->SimPerfCurve_MinValueOfPsm_.set (SimPerfCurve_MinValueOfPsm_traits::create (i, f, this)); continue; } } // SimPerfCurve_MaxValueOfPsm // if (n.name () == "SimPerfCurve_MaxValueOfPsm" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/ResourcesGeometry") { if (!this->SimPerfCurve_MaxValueOfPsm_) { this->SimPerfCurve_MaxValueOfPsm_.set (SimPerfCurve_MaxValueOfPsm_traits::create (i, f, this)); continue; } } break; } } SimPerformanceCurve_Mathematical_FanPressureRise* SimPerformanceCurve_Mathematical_FanPressureRise:: _clone (::xml_schema::flags f, ::xml_schema::container* c) const { return new class SimPerformanceCurve_Mathematical_FanPressureRise (*this, f, c); } SimPerformanceCurve_Mathematical_FanPressureRise& SimPerformanceCurve_Mathematical_FanPressureRise:: operator= (const SimPerformanceCurve_Mathematical_FanPressureRise& x) { if (this != &x) { static_cast< ::schema::simxml::ResourcesGeometry::SimPerformanceCurve_Mathematical& > (*this) = x; this->SimPerfCurve_Coeff1C1_ = x.SimPerfCurve_Coeff1C1_; this->SimPerfCurve_Coeff2C2_ = x.SimPerfCurve_Coeff2C2_; this->SimPerfCurve_Coeff3C3_ = x.SimPerfCurve_Coeff3C3_; this->SimPerfCurve_Coeff4C4_ = x.SimPerfCurve_Coeff4C4_; this->SimPerfCurve_MinValueOfQfan_ = x.SimPerfCurve_MinValueOfQfan_; this->SimPerfCurve_MaxValueOfQfan_ = x.SimPerfCurve_MaxValueOfQfan_; this->SimPerfCurve_MinValueOfPsm_ = x.SimPerfCurve_MinValueOfPsm_; this->SimPerfCurve_MaxValueOfPsm_ = x.SimPerfCurve_MaxValueOfPsm_; } return *this; } SimPerformanceCurve_Mathematical_FanPressureRise:: ~SimPerformanceCurve_Mathematical_FanPressureRise () { } } } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace schema { namespace simxml { namespace ResourcesGeometry { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
36.708758
150
0.684365
EnEff-BIM
06b6b5eeaebceef76699e8b9300e1c9b7f4eea6d
316
hxx
C++
include/acl/export.hxx
obhi-d/acl
8860227ffceff559b32425bdab7419fb99a807d4
[ "MIT" ]
null
null
null
include/acl/export.hxx
obhi-d/acl
8860227ffceff559b32425bdab7419fb99a807d4
[ "MIT" ]
null
null
null
include/acl/export.hxx
obhi-d/acl
8860227ffceff559b32425bdab7419fb99a807d4
[ "MIT" ]
null
null
null
//! A single file must include this one time, this contains mostly debug info collectors #pragma once #include "allocator.hpp" #include <sstream> namespace acl::detail { #ifdef ACL_REC_STATS detail::statistics<default_allocator_tag, true> default_allocator_statistics_instance; #endif } // namespace acl::detail
21.066667
88
0.791139
obhi-d
06ba76bc509b9136ced0ca62bd57d523ae68b43d
506
cpp
C++
src/Messages/AcceptPlayRequestMessage.cpp
BigETI/WhackAStoodentServer
05c670a9b745262ae926aebcb1fce0f1ecc5f4d2
[ "MIT" ]
1
2021-04-28T20:32:57.000Z
2021-04-28T20:32:57.000Z
src/Messages/AcceptPlayRequestMessage.cpp
BigETI/WhackAStoodentServer
05c670a9b745262ae926aebcb1fce0f1ecc5f4d2
[ "MIT" ]
7
2021-08-24T14:09:33.000Z
2021-08-30T12:47:40.000Z
src/Messages/AcceptPlayRequestMessage.cpp
BigETI/WhackAStoodentServer
05c670a9b745262ae926aebcb1fce0f1ecc5f4d2
[ "MIT" ]
null
null
null
#include <Messages/AcceptPlayRequestMessage.hpp> /// <summary> /// Constructs an accept playe request message /// </summary> WhackAStoodentServer::Messages::AcceptPlayRequestMessage::AcceptPlayRequestMessage() : WhackAStoodentServer::Messages::ASerializableMessage<WhackAStoodentServer::EMessageType::AcceptPlayRequest>() { // ... } /// <summary> /// Destroys accept playe request message /// </summary> WhackAStoodentServer::Messages::AcceptPlayRequestMessage::~AcceptPlayRequestMessage() { // ... }
26.631579
110
0.768775
BigETI
06bda34131bfb20597f540583fb588a3dd20cac9
12,336
cpp
C++
dec15-1.cpp
balazs-bamer/adventofcode19
d8166ccbd1d531db1269dfd24065ba552397e884
[ "MIT" ]
1
2019-12-09T16:14:27.000Z
2019-12-09T16:14:27.000Z
dec15-1.cpp
balazs-bamer/adventofcode19
d8166ccbd1d531db1269dfd24065ba552397e884
[ "MIT" ]
null
null
null
dec15-1.cpp
balazs-bamer/adventofcode19
d8166ccbd1d531db1269dfd24065ba552397e884
[ "MIT" ]
null
null
null
#include <list> #include <array> #include <deque> #include <limits> #include <chrono> #include <cctype> #include <fstream> #include <utility> #include <iostream> #include <functional> #include <stdexcept> #include <algorithm> #include <unordered_map> class Int final { private: int mInt; public: Int(int aInt) noexcept : mInt(aInt) { } Int(std::string &aString) : mInt(std::stoi(aString)) { } int toInt() const noexcept { return mInt; } operator int() const noexcept { return mInt; } }; template<typename tNumber> class Intcode final { private: static size_t constexpr cInstLengths[] = {1u, 4u, 4u, 2u, 2u, 3u, 3u, 4u, 4u, 2u, 1u}; static int const cAdd = 1; static int const cMultiply = 2; static int const cInput = 3; static int const cOutput = 4; static int const cJumpIfNot0 = 5; static int const cJumpIf0 = 6; static int const cLessThan = 7; static int const cEquals = 8; static int const cRelativeBase = 9; static int const cInstCount = 10; static int const cHalt = 99; static int const cMaskOpcode = 100; static size_t const cOffsetParameter1 = 1u; static size_t const cOffsetParameter2 = 2u; static size_t const cOffsetResult = 3u; std::list<tNumber> mInputs; std::list<tNumber> mOutputs; std::deque<tNumber> mProgram; std::deque<tNumber> mMemory; size_t mProgramCounter; size_t mRelativeBase; public: Intcode() noexcept = default; Intcode(std::ifstream &aIn) noexcept { while(true) { std::string number; std::getline(aIn, number, ','); if(!aIn.good()) { break; } tNumber integer(number); mProgram.push_back(integer); } } Intcode(Intcode const &aOther) noexcept : mProgram(aOther.mProgram) { } void input(int const aInput) noexcept { mInputs.push_back(aInput); } tNumber output() { return get(mOutputs); } bool hasOutput() { return !mOutputs.empty(); } void start() { mInputs.clear(); mOutputs.clear(); mMemory = mProgram; mProgramCounter = 0u; mRelativeBase = 0u; } void poke(size_t const aLocation, tNumber const &aValue) { expand(aLocation); mMemory[aLocation] = aValue; } bool run() { bool result; while(true) { if(mProgramCounter >= mMemory.size()) { throw std::invalid_argument("Invalid program."); } else { // nothing to do } tNumber opcode = mMemory[mProgramCounter] % cMaskOpcode; if(opcode != cHalt && opcode >= cInstCount) { throw std::invalid_argument("Invalid program."); } else { // nothing to do } bool jumped = false; if(opcode == cAdd) { size_t addressParameter1 = getAddress(cOffsetParameter1); size_t addressParameter2 = getAddress(cOffsetParameter2); size_t addressResult = getAddress(cOffsetResult); mMemory[addressResult] = mMemory[addressParameter1] + mMemory[addressParameter2]; } else if(opcode == cMultiply) { size_t addressParameter1 = getAddress(cOffsetParameter1); size_t addressParameter2 = getAddress(cOffsetParameter2); size_t addressResult = getAddress(cOffsetResult); mMemory[addressResult] = mMemory[addressParameter1] * mMemory[addressParameter2]; } else if(opcode == cInput) { size_t addressParameter1 = getAddress(cOffsetParameter1); if(mInputs.size() == 0u) { result = false; break; } else { mMemory[addressParameter1] = get(mInputs); } } else if(opcode == cOutput) { size_t addressParameter1 = getAddress(cOffsetParameter1); mOutputs.push_back(mMemory[addressParameter1]); } else if(opcode == cJumpIfNot0) { size_t addressToCheck = getAddress(cOffsetParameter1); size_t addressOfJUmp = getAddress(cOffsetParameter2); if(mMemory[addressToCheck] != 0) { mProgramCounter = mMemory[addressOfJUmp].toInt(); jumped = true; } else { // nothing to do } } else if(opcode == cJumpIf0) { size_t addressToCheck = getAddress(cOffsetParameter1); size_t addressOfJUmp = getAddress(cOffsetParameter2); if(mMemory[addressToCheck] == 0) { mProgramCounter = mMemory[addressOfJUmp].toInt(); jumped = true; } else { // nothing to do } } else if(opcode == cLessThan) { size_t addressParameter1 = getAddress(cOffsetParameter1); size_t addressParameter2 = getAddress(cOffsetParameter2); size_t addressResult = getAddress(cOffsetResult); mMemory[addressResult] = (mMemory[addressParameter1] < mMemory[addressParameter2] ? 1 : 0); } else if(opcode == cEquals) { size_t addressParameter1 = getAddress(cOffsetParameter1); size_t addressParameter2 = getAddress(cOffsetParameter2); size_t addressResult = getAddress(cOffsetResult); mMemory[addressResult] = (mMemory[addressParameter1] == mMemory[addressParameter2] ? 1 : 0); } else if(opcode == cRelativeBase) { size_t addressParameter1 = getAddress(cOffsetParameter1); mRelativeBase += mMemory[addressParameter1].toInt(); } else if(opcode == cHalt) { result = true; break; } else { // nothing to do } if(!jumped) { mProgramCounter += cInstLengths[opcode.toInt()]; } else { // nothing to do } } return result; } private: size_t getAddress(size_t const aOffset) { tNumber const dividor[] = {0, 100, 1000, 10000}; tNumber digit = (mMemory[mProgramCounter] / dividor[aOffset]) % 10; size_t result; if(digit == 0) { result = mMemory[mProgramCounter + aOffset].toInt(); } else if(digit == 2) { result = mMemory[mProgramCounter + aOffset].toInt() + mRelativeBase; } else { // else 1, immediate result = mProgramCounter + aOffset; } expand(result); return result; } void expand(size_t const aLocation) { if(aLocation >= mMemory.size()) { tNumber zero{0}; mMemory.resize(aLocation + 1u, zero); } else { // nothing to do } } tNumber get(std::list<tNumber> &aList) { if(aList.size() == 0u) { throw std::invalid_argument("List empty."); } else { // nothing to do } tNumber result = aList.front(); aList.pop_front(); return result; } }; template<typename tNumber> size_t constexpr Intcode<tNumber>::cInstLengths[]; struct Coordinates final { public: static int constexpr cDeltaX[] = { 0, 0, -1, 1}; static int constexpr cDeltaY[] = {-1, 1, 0, 0}; static int constexpr cBackwards[] = { 1, 0, 3, 2}; int x; int y; Coordinates(int const aX, int const aY) : x(aX), y(aY) { } Coordinates operator+(int const aDirection) const noexcept { return Coordinates(x + cDeltaX[aDirection] , y + cDeltaY[aDirection]); } Coordinates& operator+=(int const aDirection) noexcept { x += cDeltaX[aDirection]; y += cDeltaY[aDirection]; return *this; } bool isOrigin() const noexcept { return x == 0 && y == 0; } bool operator==(Coordinates const &aOther) const noexcept { return x == aOther.x && y == aOther.y; } }; int constexpr Coordinates::cDeltaX[]; int constexpr Coordinates::cDeltaY[]; int constexpr Coordinates::cBackwards[]; template<> struct std::hash<Coordinates> { size_t operator()(Coordinates const &aKey) const { return std::hash<int>{}(aKey.x) ^ (std::hash<int>{}(aKey.y) << 1u); } }; class Node final { public: static constexpr size_t cDirectionCount = 4u; static constexpr int cNoParent = -1; private: // index is the <number to control the robot> - 1 std::array<bool, cDirectionCount> mChildren; // Leave so for origin int mParentDirection = cNoParent; bool mInitialized = false; int mDirectionCounter = 0; public: // for origin Node() noexcept { std::fill(mChildren.begin(), mChildren.end(), false); } // for child Node(int const aDirectionFromParent) noexcept : Node() { mParentDirection = Coordinates::cBackwards[aDirectionFromParent]; } void makeChild(int const aDirectionToChild) noexcept { mChildren[aDirectionToChild] = true; } bool isInitialized() const noexcept { return mInitialized; } bool setInitialized() noexcept { mInitialized = true; } int getParentDirection() const noexcept { return mParentDirection; } int getAndAdvanceDirectionCounter() noexcept { for(; mDirectionCounter < cDirectionCount && !mChildren[mDirectionCounter]; ++mDirectionCounter) { } int result = mDirectionCounter; mDirectionCounter = std::min<int>(mDirectionCounter + 1, cDirectionCount); return result; } void resetDirectionCounter() noexcept { mDirectionCounter = 0; } }; class Labyrinth final { private: static int constexpr cOffset = 1; static int constexpr cWall = 0; static int constexpr cMoved = 1; static int constexpr cOxygen = 2; Intcode<Int> mComputer; std::unordered_map<Coordinates, Node> mMap; bool mChanged = false; Coordinates mLocation; int mIteration = 0; public: Labyrinth(std::ifstream &aIn) : mComputer(aIn), mLocation(0, 0) { mComputer.start(); } size_t getShortestPathLengthToOxygen() noexcept { size_t shortest = std::numeric_limits<size_t>::max(); mMap.emplace(mLocation, Node()); while(true) { Node &actual = mMap[mLocation]; int newDirection; if(actual.isInitialized()) { newDirection = step(actual); } else { newDirection = initialize(actual); } if(newDirection == Node::cNoParent) { if(!mChanged) { break; } else { // nothing to do } ++mIteration; mChanged = false; } else { mLocation += newDirection; if(moveRobot(newDirection) == cOxygen) { shortest = (mLocation.isOrigin() ? 0 : mIteration); break; } else { // nothing to do } } } return shortest; } private: int initialize(Node &aActual) noexcept { for(int i = 0; i < Node::cDirectionCount; ++i) { auto newLocation = mLocation + i; if(mMap.find(newLocation) == mMap.end()) { // not seen or wall int result = moveRobot(i); if(result == cMoved || result == cOxygen) { mMap.emplace(newLocation, i); aActual.makeChild(i); moveRobot(Coordinates::cBackwards[i]); mChanged = true; } else { // nothing to do } } else { // nothing to do } } aActual.setInitialized(); return aActual.getParentDirection(); } int step(Node &aActual) noexcept { int newDirection = aActual.getAndAdvanceDirectionCounter(); if(newDirection == Node::cDirectionCount) { aActual.resetDirectionCounter(); newDirection = aActual.getParentDirection(); } else { // nothing to do } return newDirection; } int moveRobot(int const aDirection) { mComputer.input(aDirection + cOffset); mComputer.run(); return mComputer.output().toInt(); } }; int main(int const argc, char **argv) { size_t const cChainLength = 5u; int const cInitialInput = 0; try { if(argc == 1) { throw std::invalid_argument("Need input filename."); } std::ifstream in(argv[1]); Labyrinth labyrinth(in); auto begin = std::chrono::high_resolution_clock::now(); size_t pathLength = labyrinth.getShortestPathLengthToOxygen(); auto end = std::chrono::high_resolution_clock::now(); auto timeSpan = std::chrono::duration_cast<std::chrono::duration<double>>(end - begin); std::cout << "duration: " << timeSpan.count() << '\n'; std::cout << pathLength << '\n'; } catch(std::exception const &e) { std::cerr << e.what() << std::endl; return 1; } return 0; }
27.413333
102
0.613489
balazs-bamer
06be6c05cd8a7f968bd5b57d13263f8480bf8a50
3,140
hpp
C++
include/whack/codegen/elements/args.hpp
onchere/whack
0702e46f13855d4efd8dd0cb67af2fddfb84b00c
[ "Apache-2.0" ]
54
2018-10-28T07:18:31.000Z
2022-03-08T20:30:40.000Z
include/whack/codegen/elements/args.hpp
onchere/whack
0702e46f13855d4efd8dd0cb67af2fddfb84b00c
[ "Apache-2.0" ]
null
null
null
include/whack/codegen/elements/args.hpp
onchere/whack
0702e46f13855d4efd8dd0cb67af2fddfb84b00c
[ "Apache-2.0" ]
5
2018-10-28T14:43:53.000Z
2020-04-26T19:52:58.000Z
/** * Copyright 2018-present Onchere Bironga * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef WHACK_ARGS_HPP #define WHACK_ARGS_HPP #pragma once #include "../types/type.hpp" namespace whack::codegen::elements { class Arg { public: explicit Arg(types::Type&& type, llvm::StringRef name, const bool variadic = false, const bool mut = false) : type{std::forward<types::Type>(type)}, name{name}, variadic{variadic}, mut{mut} {} const types::Type type; llvm::StringRef name; const bool variadic; const bool mut; }; class Args final : public AST { public: explicit Args(const mpc_ast_t* const ast) { const auto tag = getInnermostAstTag(ast); if (tag == "variadicarg") { args_.emplace_back(Arg{types::Type{ast->children[0]->children[0]}, ast->children[1]->contents, true}); } else if (tag == "typeident") { args_.emplace_back( Arg{types::Type{ast->children[0]}, ast->children[1]->contents}); } else { for (auto i = 0; i < ast->children_num; i += 2) { const auto ref = ast->children[i]; if (getInnermostAstTag(ref) == "typeident") { args_.emplace_back( Arg{types::Type{ref->children[0]}, ref->children[1]->contents}); } else { // variadicarg args_.emplace_back(Arg{types::Type{ref->children[0]->children[0]}, ref->children[1]->contents, true}); } } } } inline const auto& arg(const std::size_t index) const { return args_.at(index); } inline const auto& args() const noexcept { return args_; } const llvm::Expected<small_vector<llvm::Type*>> types(llvm::IRBuilder<>& builder) const { small_vector<llvm::Type*> ret; for (const auto& arg : args_) { auto tp = arg.type.codegen(builder); if (!tp) { return tp.takeError(); } auto type = *tp; // @todo if (types::Type::getUnderlyingType(type)->isFunctionTy() || (type->isStructTy() && type->getStructName().startswith("interface::"))) { type = type->getPointerTo(0); } ret.push_back(type); } return ret; } const auto names() const { small_vector<llvm::StringRef> ret; for (const auto& arg : args_) { ret.push_back(arg.name); } return ret; } inline const auto size() const { return args_.size(); } inline const bool variadic() const { return !args_.empty() && args_.back().variadic; } private: std::vector<Arg> args_; }; } // end namespace whack::codegen::elements #endif // WHACK_ARGS_HPP
28.807339
78
0.621019
onchere
06c4162571b6f85861df72297fc0c872544ad9c0
610
cpp
C++
TOI16/Programming TH/1008.cpp
mrmuffinnxz/TOI-preparation
85a7d5b70d7fc661950bbb5de66a6885a835e755
[ "MIT" ]
null
null
null
TOI16/Programming TH/1008.cpp
mrmuffinnxz/TOI-preparation
85a7d5b70d7fc661950bbb5de66a6885a835e755
[ "MIT" ]
null
null
null
TOI16/Programming TH/1008.cpp
mrmuffinnxz/TOI-preparation
85a7d5b70d7fc661950bbb5de66a6885a835e755
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #include<vector> #include<list> using namespace std; main() { int n; cin>>n; vector<int> skyline(256,0); int Li,Hi,Ri; int Ls=256,Rs=0; for(int i=0;i<n;i++) { cin>>Li>>Hi>>Ri; if(Li<Ls) Ls=Li; if(Ri>Rs) Rs=Ri; for(int j=Li;j<Ri;j++) if(Hi>skyline[j]) skyline[j]=Hi; } for(int i=Ls;i<Rs;i++) cout<<skyline[i]<<" "; cout<<endl; int temp=-1; cout<<Ls<<" "<<skyline[Ls]<<" "; for(int i=Ls+1;i<Rs;i++) { if(skyline[i]==0) continue; if(skyline[i]!=skyline[i-1]) cout<<i<<" "<<skyline[i]<<" "; if(skyline[i+1]==0) cout<<i+1<<" "<<"0 "; } }
15.25
61
0.531148
mrmuffinnxz
06ca27845532ad642ebb1b962842a1fbf55b9066
1,118
hpp
C++
Logger.hpp
PORT-INC/cicada
18730fa951ebf1b92a3116c13ddc75f786595dd1
[ "MIT" ]
null
null
null
Logger.hpp
PORT-INC/cicada
18730fa951ebf1b92a3116c13ddc75f786595dd1
[ "MIT" ]
null
null
null
Logger.hpp
PORT-INC/cicada
18730fa951ebf1b92a3116c13ddc75f786595dd1
[ "MIT" ]
null
null
null
// © 2016 PORT INC. #ifndef LOGGER__H #define LOGGER__H #include "spdlog/spdlog.h" namespace Logger { namespace spd = spdlog; decltype ( spd::stderr_logger_mt("", true) ) out(); void setLevel(int level); void setName(const std::string& name); void setColor(bool flg); void setPattern(const std::string& pattern); int getLevel(); decltype(( out()->trace() )) trace(); decltype(( out()->debug() )) debug(); decltype(( out()->info() )) info(); decltype(( out()->notice() )) notice(); decltype(( out()->warn() )) warn(); decltype(( out()->error() )) error(); decltype(( out()->critical() )) critical(); decltype(( out()->alert() )) alert(); decltype(( out()->trace() )) trace(const char* msg); decltype(( out()->debug() )) debug(const char* msg); decltype(( out()->info() )) info(const char* msg); decltype(( out()->notice() )) notice(const char* msg); decltype(( out()->warn() )) warn(const char* msg); decltype(( out()->error() )) error(const char* msg); decltype(( out()->critical() )) critical(const char* msg); decltype(( out()->alert() )) alert(const char* msg); } #endif // LOGGER__H
27.95
59
0.62254
PORT-INC
06cdbba9971974202cc63958e80a71da8bc866f7
599
cpp
C++
kernel/src/gdt.cpp
cekkr/thor-os
841b088eddc378ef38c98878a51958479dce4a31
[ "MIT" ]
null
null
null
kernel/src/gdt.cpp
cekkr/thor-os
841b088eddc378ef38c98878a51958479dce4a31
[ "MIT" ]
null
null
null
kernel/src/gdt.cpp
cekkr/thor-os
841b088eddc378ef38c98878a51958479dce4a31
[ "MIT" ]
null
null
null
//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #include "gdt.hpp" #include "early_memory.hpp" void gdt::flush_tss(){ asm volatile("mov ax, %0; ltr ax;" : : "i" (gdt::TSS_SELECTOR + 0x3) : "rax"); } gdt::task_state_segment_t& gdt::tss(){ return *reinterpret_cast<task_state_segment_t*>(early::tss_address); }
33.277778
82
0.527546
cekkr
06d18ed979f8f80e67b37a925171e98c9ce375c2
1,403
cpp
C++
cpp/651-660/Find K Closest Elements.cpp
KaiyuWei/leetcode
fd61f5df60cfc7086f7e85774704bacacb4aaa5c
[ "MIT" ]
150
2015-04-04T06:53:49.000Z
2022-03-21T13:32:08.000Z
cpp/651-660/Find K Closest Elements.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
1
2015-04-13T15:15:40.000Z
2015-04-21T20:23:16.000Z
cpp/651-660/Find K Closest Elements.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
64
2015-06-30T08:00:07.000Z
2022-01-01T16:44:14.000Z
// Solution 1. class Solution { public: vector<int> findClosestElements(vector<int>& arr, int k, int x) { auto it = lower_bound(arr.begin(), arr.end(), x); int idx = it - arr.begin(); if (idx == arr.size()) { idx--; } else if (idx > 0) { if (abs(arr[idx - 1] - x) <= abs(arr[idx] - x)) { idx = idx - 1; } } int l = idx - 1; int r = idx + 1; for (int i = 2; i <= k; i++) { if (l < 0) { r++; } else if (r >= arr.size()) { l--; } else { if (abs(arr[l] - x) <= abs(arr[r] - x)) { l--; } else { r++; } } } return vector<int>(arr.begin() + l + 1, arr.begin() + r); } }; // Solution 2. class Solution { public: vector<int> findClosestElements(vector<int>& arr, int k, int x) { int left = 0; int right = arr.size() - k; while (left < right) { int mid = (left + right) / 2; if (x - arr[mid] > arr[mid + k] - x) { left = mid + 1; } else { right = mid; } } return vector<int>(arr.begin() + left, arr.begin() + left + k); } };
24.614035
71
0.352815
KaiyuWei
06d7177a575ff3520a80377a7994e37354b1e4fd
11,571
cpp
C++
libloco/src/LocoNetwork.cpp
candycode/loco
4fffb785cf73c577397b107586909a24133ff7c7
[ "BSD-3-Clause" ]
1
2018-07-05T13:43:14.000Z
2018-07-05T13:43:14.000Z
libloco/src/LocoNetwork.cpp
candycode/loco
4fffb785cf73c577397b107586909a24133ff7c7
[ "BSD-3-Clause" ]
null
null
null
libloco/src/LocoNetwork.cpp
candycode/loco
4fffb785cf73c577397b107586909a24133ff7c7
[ "BSD-3-Clause" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// //Copyright (c) 2012, Ugo Varetto //All rights reserved. // //Redistribution and use in source and binary forms, with or without //modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the copyright holder nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND //ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE //DISCLAIMED. IN NO EVENT SHALL UGO VARETTO BE LIABLE FOR ANY //DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES //(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; //LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND //ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT //(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS //SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////////////////////////// #include <QUrl> #include <QNetworkRequest> #include <QNetworkReply> #include <QTimer> #include <QBuffer> #include "LocoNetwork.h" #include "LocoContext.h" #include "LocoURLUtility.h" namespace loco { QVariantMap Http::get( const QString& urlString, int timeout, const QVariantMap& opt ) { QEventLoop loop; QVariantMap reply; QUrl url = ConfigureURL( urlString, opt ); QObject::connect( nam_, SIGNAL( finished( QNetworkReply*) ), &loop, SLOT( quit() ) ); // soft real-time guarantee: kill network request if the total time is >= timeout QTimer::singleShot( timeout, &loop, SLOT( quit() ) ); QNetworkRequest request; request.setUrl( url ); if( opt.contains( "headers" ) ) ConfigureHeaders( request, opt[ "headers" ].toMap() ); QNetworkReply* nr = nam_->get( request ); // Execute the event loop here, now we will wait here until readyRead() signal is emitted // which in turn will trigger event loop quit. loop.exec(); if( nr->error() != QNetworkReply::NoError ) { error( nr->errorString() ); return reply; } if( !nr->isFinished() ) { error( "Network request timeout" ); return reply; } reply[ "content" ] = nr->readAll(); QVariantMap headers; typedef QList< QByteArray > HEADERS; HEADERS rawHeaders = nr->rawHeaderList(); for( HEADERS::const_iterator i = rawHeaders.begin(); i != rawHeaders.end(); ++i ) { if( nr->hasRawHeader( *i ) ) { headers[ QString( *i ) ] = QString( nr->rawHeader( *i ) ); } } reply[ "headers" ] = headers; return reply; } QVariantMap Http::head( const QString& urlString, int timeout, const QVariantMap& opt ) { QEventLoop loop; QVariantMap reply; QUrl url = ConfigureURL( urlString, opt ); QObject::connect( nam_, SIGNAL( finished( QNetworkReply*) ), &loop, SLOT( quit() ) ); // soft real-time guarantee: kill network request if the total time is >= timeout QTimer::singleShot( timeout, &loop, SLOT( quit() ) ); QNetworkRequest request; request.setUrl( url ); if( opt.contains( "headers" ) ) ConfigureHeaders( request, opt[ "headers" ].toMap() ); QNetworkReply* nr = nam_->head( request ); // Execute the event loop here, now we will wait here until readyRead() signal is emitted // which in turn will trigger event loop quit. loop.exec(); if( nr->error() != QNetworkReply::NoError ) { error( nr->errorString() ); return reply; } if( !nr->isFinished() ) { error( "Network request timeout" ); return reply; } QVariantMap headers; typedef QList< QByteArray > HEADERS; HEADERS rawHeaders = nr->rawHeaderList(); for( HEADERS::const_iterator i = rawHeaders.begin(); i != rawHeaders.end(); ++i ) { if( nr->hasRawHeader( *i ) ) { headers[ QString( *i ) ] = QString( nr->rawHeader( *i ) ); } } reply[ "headers" ] = headers; return reply; } QVariantMap Http::request( const QString& urlString, const QByteArray& verb, int timeout, const QVariantMap& opt, const QByteArray& data ) { QEventLoop loop; QVariantMap reply; QUrl url = ConfigureURL( urlString, opt ); QObject::connect( nam_, SIGNAL( finished( QNetworkReply*) ), &loop, SLOT( quit() ) ); // soft real-time guarantee: kill network request if the total time is >= timeout QTimer::singleShot( timeout, &loop, SLOT( quit() ) ); QNetworkRequest request; request.setUrl( url ); if( opt.contains( "headers" ) ) ConfigureHeaders( request, opt[ "headers" ].toMap() ); QBuffer datain; datain.setData( data ); QNetworkReply* nr = nam_->sendCustomRequest( request, verb, &datain ); // Execute the event loop here, now we will wait here until readyRead() signal is emitted // which in turn will trigger event loop quit. loop.exec(); if( nr->error() != QNetworkReply::NoError ) { error( nr->errorString() ); return reply; } if( !nr->isFinished() ) { error( "Network request timeout" ); return reply; } reply[ "content" ] = nr->readAll(); QVariantMap headers; typedef QList< QByteArray > HEADERS; HEADERS rawHeaders = nr->rawHeaderList(); for( HEADERS::const_iterator i = rawHeaders.begin(); i != rawHeaders.end(); ++i ) { if( nr->hasRawHeader( *i ) ) { headers[ QString( *i ) ] = QString( nr->rawHeader( *i ) ); } } reply[ "headers" ] = headers; return reply; } QVariantMap Http::post( const QString& urlString, int timeout, const QByteArray& data, const QVariantMap& opt ) { QEventLoop loop; QVariantMap reply; QUrl url = ConfigureURL( urlString, opt ); QObject::connect( nam_, SIGNAL( finished( QNetworkReply*) ), &loop, SLOT( quit() ) ); // soft real-time guarantee: kill network request if the total time is >= timeout QTimer::singleShot( timeout, &loop, SLOT( quit() ) ); QNetworkRequest request; request.setUrl( url ); if( opt.contains( "headers" ) ) ConfigureHeaders( request, opt[ "headers" ].toMap() ); QNetworkReply* nr = nam_->post( request, data ); // Execute the event loop here, now we will wait here until readyRead() signal is emitted // which in turn will trigger event loop quit. loop.exec(); if( nr->error() != QNetworkReply::NoError ) { error( nr->errorString() ); return reply; } if( !nr->isFinished() ) { error( "Network request timeout" ); return reply; } reply[ "content" ] = nr->readAll(); QVariantMap headers; typedef QList< QByteArray > HEADERS; HEADERS rawHeaders = nr->rawHeaderList(); for( HEADERS::const_iterator i = rawHeaders.begin(); i != rawHeaders.end(); ++i ) { if( nr->hasRawHeader( *i ) ) { headers[ QString( *i ) ] = QString( nr->rawHeader( *i ) ); } } reply[ "headers" ] = headers; return reply; } QVariant Network::create( const QString& name ) { if( name == "Http" ) { if( !GetContext()->GetNetworkAccessManager() ) throw std::runtime_error( "NULL Network Access Manager" ); Http* http = new Http( qobject_cast< NetworkAccessManager* >( GetContext()->GetNetworkAccessManager() ) ); return GetContext()->AddObjToJSContext( http ); } else if( name == "tcp-server" ) { TcpServer* tcp = new TcpServer; return GetContext()->AddObjToJSContext( tcp ); } else if( name == "tcp-socket" ) { TcpSocket* tcp = new TcpSocket; return GetContext()->AddObjToJSContext( tcp, false ); } else if( name == "udp-socket" ) { UdpSocket* udp = new UdpSocket; return GetContext()->AddObjToJSContext( udp, false ); #ifdef LOCO_SSL } else if( name == "tcp-ssl-socket" ) { SslSocket* ssl = new SslSocket; return GetContext()->AddObjToJSContext( ssl, false ); #endif } else { error( "Unknown type " + name ); return QVariant(); } } } /* * #include <QApplication> #include <QSslSocket> #include <QDebug> int main( int argc, char **argv ) { QApplication app( argc, argv ); QSslSocket socket; socket.connectToHostEncrypted( "bugs.kde.org", 443 ); if ( !socket.waitForEncrypted() ) { qDebug() << socket.errorString(); return 1; } socket.write( "GET / HTTP/1.1\r\n" \ "Host: bugs.kde.org\r\n" \ "Connection: Close\r\n\r\n" ); while ( socket.waitForReadyRead() ) { qDebug() << socket.readAll().data(); }; qDebug() << "Done"; return 0; } */ /* * #include "Socket.h" #include "Socket.h" Socket::Socket( QObject *parent ) : QSslSocket( parent ), { setLocalCertificate( ":ssl.pem" ); setPrivateKey( ":ssl.pem" ); connectToHostEncrypted( m_host, m_port ); } #ifndef SOCKET_H #ifndef SOCKET_H #define SOCKET_H #include <QSslSocket> class Socket: public QSslSocket { Q_OBJECT public: Socket( QObject *parent = 0 ); }; #endif #include "server.h" #include "server.h" #include "server_client.h" Server::Server( QObject *parent ) :QTcpServer( parent ) { listen( QHostAddress::Any, 12345 ); } void Server::incomingConnection( int socketDescriptor ) { new Client( socketDescriptor, this ); } #ifndef SERVER_H #ifndef SERVER_H #define SERVER_H #include <QTcpServer> class Server : public QTcpServer { Q_OBJECT public: Server( QObject *parent = 0 ); protected: void incomingConnection( int socketDescriptor ); }; #endif #include "server_client.h" #include "server_client.h" Client::Client( int socketDescriptor, QObject *parent ) : QSslSocket( parent ) { connect( this, SIGNAL(disconnected()), SLOT(deleteLater()) ); connect( this, SIGNAL(sslErrors(QList<QSslError>)), SLOT(sslErrors(QList<QSslError>)) ); if( !setSocketDescriptor( socketDescriptor ) ) { deleteLater(); return; } setLocalCertificate( "ssl.pem" ); setPrivateKey( "ssl.pem" ); startServerEncryption(); } void Client::sslErrors( const QList<QSslError> &errors ) { foreach( const QSslError &error, errors ) { switch( error.error() ) { case QSslError::NoPeerCertificate: ignoreSslErrors(); break; default: qWarning( "CLIENT SSL: error %s", qPrintable(error.errorString()) ); disconnect(); return; } } } #ifndef CLIENT_H #ifndef CLIENT_H #define CLIENT_H #include <QSslSocket> class Client: public QSslSocket { Q_OBJECT public: Client( int socketDescriptor, QObject *parent ); private slots: void sslErrors( const QList<QSslError> &err ); }; #endif */
31.442935
114
0.625616
candycode
06db4fd736589078499431020980aebccc7fe415
358
cpp
C++
solutions/325.maximum-size-subarray-sum-equals-k.326218555.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
78
2020-10-22T11:31:53.000Z
2022-02-22T13:27:49.000Z
solutions/325.maximum-size-subarray-sum-equals-k.326218555.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
null
null
null
solutions/325.maximum-size-subarray-sum-equals-k.326218555.ac.cpp
satu0king/Leetcode-Solutions
2edff60d76c2898d912197044f6284efeeb34119
[ "MIT" ]
26
2020-10-23T15:10:44.000Z
2021-11-07T16:13:50.000Z
class Solution { public: int maxSubArrayLen(vector<int> &nums, int k) { int ans = 0; unordered_map<int, int> mp; mp[0] = -1; int s = 0; for (int i = 0; i < nums.size(); i++) { s += nums[i]; if (mp.count(s - k)) ans = max(ans, i - mp[s - k]); if (!mp.count(s)) mp[s] = i; } return ans; } };
17.9
48
0.452514
satu0king
06dc2a69a506fa51ec2c84a24cf0bcfa1d0871cd
910
cc
C++
vowpalwabbit/io/tests/ostream_test.cc
HollowMan6/vowpal_wabbit
eecdaccce568b53ed195bc4d50a6a582ab9a83d5
[ "BSD-3-Clause" ]
4,332
2015-01-01T10:26:51.000Z
2018-10-01T14:05:43.000Z
vowpalwabbit/io/tests/ostream_test.cc
HollowMan6/vowpal_wabbit
eecdaccce568b53ed195bc4d50a6a582ab9a83d5
[ "BSD-3-Clause" ]
1,004
2015-01-01T12:00:54.000Z
2018-09-30T22:13:42.000Z
vowpalwabbit/io/tests/ostream_test.cc
HollowMan6/vowpal_wabbit
eecdaccce568b53ed195bc4d50a6a582ab9a83d5
[ "BSD-3-Clause" ]
1,182
2015-01-02T20:38:55.000Z
2018-09-26T02:47:37.000Z
// Copyright (c) by respective owners including Yahoo!, Microsoft, and // individual contributors. All rights reserved. Released under a BSD (revised) // license as described in the file LICENSE. #include "vw/io/custom_streambuf.h" #include "vw/io/io_adapter.h" #include "vw/io/owning_stream.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include <string> TEST(custom_ostream_tests, test_custom_ostream) { auto output_func = [](void* context, const char* buffer, size_t num_bytes) -> ssize_t { std::string input(buffer, num_bytes); EXPECT_TRUE(context == nullptr); EXPECT_EQ(input, "This is the test input, 123\n"); return 0; }; auto ptr = std::unique_ptr<std::streambuf>( new VW::io::writer_stream_buf(VW::io::create_custom_writer(nullptr, output_func))); VW::io::owning_ostream stream{std::move(ptr)}; stream << "This is the test input, " << 123 << std ::endl; }
31.37931
89
0.707692
HollowMan6
06dd781842e9500f555a1602c234bb7e8be5ae48
803
cc
C++
chrome/browser/autofill/fax_number.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
2
2017-09-02T19:08:28.000Z
2021-11-15T15:15:14.000Z
chrome/browser/autofill/fax_number.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/autofill/fax_number.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
1
2020-04-13T05:45:10.000Z
2020-04-13T05:45:10.000Z
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/fax_number.h" FaxNumber::FaxNumber() {} FaxNumber::~FaxNumber() {} FormGroup* FaxNumber::Clone() const { return new FaxNumber(*this); } AutoFillFieldType FaxNumber::GetNumberType() const { return PHONE_FAX_NUMBER; } AutoFillFieldType FaxNumber::GetCityCodeType() const { return PHONE_FAX_CITY_CODE; } AutoFillFieldType FaxNumber::GetCountryCodeType() const { return PHONE_FAX_COUNTRY_CODE; } AutoFillFieldType FaxNumber::GetCityAndNumberType() const { return PHONE_FAX_CITY_AND_NUMBER; } AutoFillFieldType FaxNumber::GetWholeNumberType() const { return PHONE_FAX_WHOLE_NUMBER; }
23.617647
73
0.777086
Gitman1989
06dd7d2a677392f81843b6b1412f05dd15a2bfc3
6,053
cpp
C++
bse/bsePhysics/Source/bseIsland.cpp
crisbia/bse
d549deda2761d301a67aa838743ec731c82e3c07
[ "MIT" ]
null
null
null
bse/bsePhysics/Source/bseIsland.cpp
crisbia/bse
d549deda2761d301a67aa838743ec731c82e3c07
[ "MIT" ]
3
2021-12-02T12:52:35.000Z
2021-12-19T20:37:35.000Z
bse/bsePhysics/Source/bseIsland.cpp
crisbia/bse
d549deda2761d301a67aa838743ec731c82e3c07
[ "MIT" ]
null
null
null
#include "bseIsland.h" #include "bseBody.h" /* Islands generation scheme: for each body do // skip non dynamic bodies if !body.isDynamic continue connectionFound = false if body.islandID == -1 then for each connection in body.connections do // skip connection to non dynamic bodies if !connection.otherBody.isDynamic then continue if connection.otherBody.islandID != -1 then islands[conn.otherBody.islandID].add(body) connectionFound = true break end end end // no island found, we need to create a new one if !connectionFound then islands.push_back(new Island()) islands.back().add(body) end end */ namespace bse { namespace phx { // TODO reuse islands in the islands generator, because // they can contain hundreds of contacts and bodies, so the allocation and deallocation // is going to be quite expensive. // I just need to keep them until the generator is destroyed. // TODO change the name of the generator in "manager" :) //--------------------------------------------------------------------------------------------------------------------- Island::Island(size_t initialSize) { m_bodies.reserve(initialSize); m_contacts.reserve(2*initialSize); } //--------------------------------------------------------------------------------------------------------------------- void Island::clear() { m_bodies.clear(); m_contacts.clear(); } //--------------------------------------------------------------------------------------------------------------------- void Island::addBody(Body* body) { if (body!=0 && body->getCurrentIsland()!=this) { m_bodies.push_back(body); body->setCurrentIsland(this); } } //--------------------------------------------------------------------------------------------------------------------- int Island::computeContacts() { m_contacts.clear(); for (size_t iBody=0; iBody<m_bodies.size(); ++iBody) { Body* body = m_bodies[iBody]; const BodyInfluencesList influences = body->getBodyInfluences(); for (BodyInfluencesList::const_iterator influence=influences.begin(); influence != influences.end(); ++influence) { const BodyInfluence& current = (*influence); if (current.influenceType == BSE_INFLUENCE_PRIMARY || current.other->isStatic()) { m_contacts.push_back((*influence).contact); } } } return (int)m_contacts.size(); } //--------------------------------------------------------------------------------------------------------------------- const ContactsList& Island::getContacts() const { return m_contacts; } //--------------------------------------------------------------------------------------------------------------------- IslandsManager::IslandsManager(size_t initialNumIslands, size_t initialIslandSize) : m_firstAvailable(0) { if (initialNumIslands == 0) initialNumIslands = 1; if (initialIslandSize == 0) initialIslandSize = 1; m_islands.resize(initialNumIslands); for (size_t i=0; i<m_islands.size(); ++i) { m_islands[i] = new Island(initialIslandSize); } } //--------------------------------------------------------------------------------------------------------------------- IslandsManager::~IslandsManager() { clear(); for (size_t i=0; i<m_islands.size(); ++i) { delete m_islands[i]; } } //--------------------------------------------------------------------------------------------------------------------- void IslandsManager::clear() { for (size_t i=0; i<m_islands.size(); ++i) { m_islands[i]->clear(); } m_firstAvailable = 0; } //--------------------------------------------------------------------------------------------------------------------- const IslandsList& IslandsManager::getIslands() const { return m_islands; } //--------------------------------------------------------------------------------------------------------------------- int IslandsManager::computeIslands(const BodiesList& bodies) { clear(); for (BodiesList::const_iterator iter=bodies.begin(); iter != bodies.end(); ++iter) { Body* body = (*iter); // skip non dynamic bodies // TODO consider kinematic ones... if (body->isStatic()) continue; if (body->getCurrentIsland()==0) { bool influenceFound = false; const BodyInfluencesList influences = body->getBodyInfluences(); for (BodyInfluencesList::const_iterator influence=influences.begin(); influence != influences.end(); ++influence) { Body* other = (*influence).other; if (other) { if (other->isStatic()) { continue; } if (other->getCurrentIsland()!=0) { other->getCurrentIsland()->addBody(body); influenceFound = true; break; } } } // no island found, we need to create a new one if (!influenceFound) { if (m_firstAvailable == m_islands.size()) m_islands.push_back(new Island()); Island* isl = m_islands[m_firstAvailable]; ++m_firstAvailable; isl->addBody(body); // fix immediately all the connections which are not already in an island const BodyInfluencesList influences = body->getBodyInfluences(); for (BodyInfluencesList::const_iterator influence=influences.begin(); influence != influences.end(); ++influence) { Body* other = (*influence).other; if (other && !other->isStatic() && other->getCurrentIsland()==0) { isl->addBody(other); } } } } } for (size_t i = 0; i < m_islands.size(); ++i) { Island* island = m_islands[i]; island->computeContacts(); } return (int)m_islands.size(); } } // namespace phx } // namespace bse
29.241546
122
0.489014
crisbia