hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5405e7f7f447438e019d324dae1f6190b9fc8177
| 2,346
|
cpp
|
C++
|
engine/ui/gGUIListbox.cpp
|
huseyinged1k/GlistEngine
|
8f37ea2b1168c3cbc7be5ea211aa3898c29ab2ef
|
[
"Apache-2.0"
] | null | null | null |
engine/ui/gGUIListbox.cpp
|
huseyinged1k/GlistEngine
|
8f37ea2b1168c3cbc7be5ea211aa3898c29ab2ef
|
[
"Apache-2.0"
] | null | null | null |
engine/ui/gGUIListbox.cpp
|
huseyinged1k/GlistEngine
|
8f37ea2b1168c3cbc7be5ea211aa3898c29ab2ef
|
[
"Apache-2.0"
] | null | null | null |
/*
* gGUIListbox.cpp
*
* Created on: Feb 5, 2022
* Author: noyan
*/
#include "gGUIListbox.h"
#include "gBaseApp.h"
#include "gBaseCanvas.h"
gGUIListbox::gGUIListbox() {
lineh = 24;
minlinenum = 5;
linenum = 0;
totalh = linenum * lineh;
minboxh = minlinenum * lineh;
listboxh = minboxh;
maxlinenum = listboxh / lineh + 1;
firstlineno = 0;
flno = firstlineno;
selectedno = 0;
mousepressedonlist = false;
}
gGUIListbox::~gGUIListbox() {
}
void gGUIListbox::set(gBaseApp* root, gBaseGUIObject* parentGUIObject, int parentSlotLineNo, int parentSlotColumnNo, int x, int y, int w, int h) {
gGUIScrollable::set(root, parentGUIObject, parentSlotLineNo, parentSlotColumnNo, x, y, w, h);
gGUIScrollable::setDimensions(width, listboxh);
}
void gGUIListbox::drawContent() {
gColor* oldcolor = renderer->getColor();
gGUIScrollable::drawContent();
flno = firsty / lineh;
fldy = firsty % lineh;
if(selectedno >= flno && selectedno < flno + linenum) {
renderer->setColor(middlegroundcolor);
gDrawRectangle(0, -fldy + (selectedno - flno) * lineh, boxw, lineh, true);
}
renderer->setColor(fontcolor);
for(int i = 0; i < linenum; i++) {
font->drawText(data[flno + i], 2, -fldy + lineh + (i * lineh) - datady[flno + i]);
}
renderer->setColor(oldcolor);
}
void gGUIListbox::addData(std::string lineData) {
data.push_back(lineData);
datady.push_back((lineh - font->getStringHeight("ae")) / 2 + 1);
linenum = data.size();
if(linenum > maxlinenum) linenum = maxlinenum;
totalh = data.size() * lineh;
}
void gGUIListbox::mousePressed(int x, int y, int button) {
gGUIScrollable::mousePressed(x, y, button);
if(x >= left && x < left + vsbx && y >= top && y < top + hsby) mousepressedonlist = true;
}
void gGUIListbox::mouseReleased(int x, int y, int button) {
gGUIScrollable::mouseReleased(x, y, button);
if(mousepressedonlist && x >= left && x < left + vsbx && y >= top && y < top + hsby) {
selectedno = (y - top + firsty) / lineh;
root->getCurrentCanvas()->onGuiEvent(id, G_GUIEVENT_LISTBOXSELECTED, gToStr(selectedno));
}
mousepressedonlist = false;
}
void gGUIListbox::setSelected(int lineNo) {
if(lineNo < 0 || lineNo > data.size() - 1) return;
selectedno = lineNo;
}
int gGUIListbox::getSelected() {
return selectedno;
}
std::string gGUIListbox::getData(int lineNo) {
return data[lineNo];
}
| 25.78022
| 146
| 0.683717
|
huseyinged1k
|
54115bea7657b185305f873e87c261b4bfe052ee
| 1,708
|
cpp
|
C++
|
src/tools.cpp
|
jainSamkit/Sensor-Fusion_EKF
|
1e543e12cc535238d11f420953bd8b9d2050ede7
|
[
"MIT"
] | null | null | null |
src/tools.cpp
|
jainSamkit/Sensor-Fusion_EKF
|
1e543e12cc535238d11f420953bd8b9d2050ede7
|
[
"MIT"
] | null | null | null |
src/tools.cpp
|
jainSamkit/Sensor-Fusion_EKF
|
1e543e12cc535238d11f420953bd8b9d2050ede7
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "tools.h"
#include <cmath>
using Eigen::VectorXd;
using Eigen::MatrixXd;
using std::vector;
using namespace std;
Tools::Tools() {}
Tools::~Tools() {}
VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations,
const vector<VectorXd> &ground_truth) {
/**
TODO:
* Calculate the RMSE here.
*/
Eigen::VectorXd rmse(4);
rmse << 0,0,0,0;
if(estimations.size() != ground_truth.size()
|| estimations.size() == 0){
cout << "Invalid estimation or ground_truth data" << endl;
return rmse;
}
for(int i=0;i<estimations.size();++i)
{
Eigen::VectorXd residual(4);
residual = ground_truth[i]-estimations[i];
residual = residual.array() * residual.array();
rmse=rmse+residual;
}
// cout<<rmse<<endl;
rmse=rmse/estimations.size();
// cout<<rmse<<endl;
rmse=rmse.array().sqrt();
// cout<<rmse<<endl;
return rmse;
}
MatrixXd Tools::CalculateJacobian(const VectorXd& x_state) {
/**
TODO:
* Calculate a Jacobian here.
*/
Eigen::MatrixXd Hj_(3,4);
float px = x_state[0];
float py = x_state[1];
float vx = x_state[2];
float vy = x_state[3];
float c1 = px*px+py*py;
float c2 = sqrt(c1);
float c3 = (c1*c2);
// cout<<"poiu"<<endl;
Hj_ << (px/c2), (py/c2), 0, 0,
-py/c1, px/c1, 0, 0,
py*(vx*py - vy*px)/c3, px*(px*vy - py*vx)/c3, px/c2, py/c2;
return Hj_;
}
float Tools::normalize_phi(float phi)
{
float pi = M_PI;
float negative_pi=-pi;
if(phi<negative_pi || phi > pi)
{
if(phi<negative_pi)
{
while(phi<negative_pi)
{
phi+=2*pi;
}
}
if(phi>pi)
{
while(phi>pi)
{
phi-=2*pi;
}
}
}
// cout<<phi<<endl;
return phi;
}
| 18.565217
| 69
| 0.594848
|
jainSamkit
|
5424998e6a9b18076c5e85305477e5febc560128
| 31,268
|
cpp
|
C++
|
xiablo/Plugins/SketchFabPlugin/Source/SketchfabAssetBrowser/Private/Commons/SketchfabTask.cpp
|
jing-interactive/ucd
|
8fc8722291f086a0c0037a94d11c14562375e862
|
[
"MIT"
] | 1
|
2022-02-02T23:36:07.000Z
|
2022-02-02T23:36:07.000Z
|
xiablo/Plugins/SketchFabPlugin/Source/SketchfabAssetBrowser/Private/Commons/SketchfabTask.cpp
|
jing-interactive/ucd
|
8fc8722291f086a0c0037a94d11c14562375e862
|
[
"MIT"
] | null | null | null |
xiablo/Plugins/SketchFabPlugin/Source/SketchfabAssetBrowser/Private/Commons/SketchfabTask.cpp
|
jing-interactive/ucd
|
8fc8722291f086a0c0037a94d11c14562375e862
|
[
"MIT"
] | null | null | null |
// Copyright 2018 Sketchfab, Inc. All Rights Reserved.
#include "SketchfabTask.h"
#include "HAL/RunnableThread.h"
#include "Editor/EditorPerProjectUserSettings.h"
#include "Dom/JsonObject.h"
#include "Serialization/JsonReader.h"
#include "Serialization/JsonWriter.h"
#include "Serialization/JsonSerializer.h"
#include <Misc/EngineVersion.h>
#include "Misc/FileHelper.h"
#include <Runtime/Core/Public/Misc/Paths.h>
#define HOSTNAME "http://127.0.0.1"
#define PORT ":55002"
DEFINE_LOG_CATEGORY_STATIC(LogSketchfabTask, Verbose, All);
bool IsCompleteState(SketchfabRESTState state)
{
switch (state)
{
case SRS_SEARCH_DONE:
case SRS_GETTHUMBNAIL_DONE:
case SRS_GETMODELLINK_DONE:
case SRS_DOWNLOADMODEL_DONE:
case SRS_GETUSERDATA_DONE:
case SRS_GETUSERORGS_DONE:
case SRS_GETUSERTHUMB_DONE:
case SRS_UPLOADMODEL_DONE:
case SRS_GETCATEGORIES_DONE:
return true;
}
return false;
}
FSketchfabTask::FSketchfabTask(const FSketchfabTaskData& InTaskData)
:
TaskData(InTaskData),
State(SRS_UNKNOWN)
{
TaskData.TaskUploadComplete = false;
DebugHttpRequestCounter.Set(0);
IsCompleted.AtomicSet(false);
}
FSketchfabTask::~FSketchfabTask()
{
UE_CLOG(bEnableDebugLogging, LogSketchfabRESTClient, Warning, TEXT("Destroying Task With Model Id %s"), *TaskData.ModelUID);
TArray<ReqPtr> OutPendingRequests;
if (PendingRequests.GetKeys(OutPendingRequests) > 0)
{
for (int32 ItemIndex = 0; ItemIndex < OutPendingRequests.Num(); ++ItemIndex)
{
UE_CLOG(bEnableDebugLogging, LogSketchfabRESTClient, Warning, TEXT("Pending Request for task with status %d"), (int32)OutPendingRequests[ItemIndex]->GetStatus());
OutPendingRequests[ItemIndex]->CancelRequest();
}
}
//unbind the delegates
OnTaskFailed().Unbind();
OnSearch().Unbind();
OnThumbnailDownloaded().Unbind();
OnModelLink().Unbind();
OnModelDownloaded().Unbind();
OnModelDownloadProgress().Unbind();
OnUserData().Unbind();
OnUserOrgs().Unbind();
OnOrgsProjects().Unbind();
OnModelUploaded().Unbind();
OnUserThumbnailDelegate.Unbind();
OnCategories().Unbind();
OnModelInfo().Unbind();
}
SketchfabRESTState FSketchfabTask::GetState() const
{
FScopeLock Lock(TaskData.StateLock);
return State;
}
void FSketchfabTask::EnableDebugLogging()
{
bEnableDebugLogging = true;
}
void FSketchfabTask::SetState(SketchfabRESTState InState)
{
if (this != nullptr && TaskData.StateLock)
{
FScopeLock Lock(TaskData.StateLock);
//do not update the state if either of these set is already set
if (InState != State && (State != SRS_FAILED))
{
State = InState;
}
else if ((InState != State) && (State != SRS_FAILED) && (IsCompleteState(InState)))
{
State = InState;
this->IsCompleted.AtomicSet(true);
}
/*
else if ((InState != State) && (State != SRS_FAILED) && (InState == SRS_ASSETDOWNLOADED))
{
State = SRS_ASSETDOWNLOADED;
this->IsCompleted.AtomicSet(true);
}
else if (InState != State && InState == SRS_FAILED)
{
State = SRS_ASSETDOWNLOADED;
}
*/
}
else
{
UE_CLOG(bEnableDebugLogging, LogSketchfabRESTClient, Error, TEXT("Object in invalid state can not acquire state lock"));
}
}
bool FSketchfabTask::IsFinished() const
{
FScopeLock Lock(TaskData.StateLock);
return IsCompleted;
}
// ~ HTTP Request method to communicate with Sketchfab REST Interface
void FSketchfabTask::AddAuthorization(ReqRef Request)
{
if (!TaskData.Token.IsEmpty())
{
FString bearer = "Bearer ";
bearer += TaskData.Token;
Request->SetHeader("Authorization", bearer);
}
else {
UE_LOG(LogSketchfabRESTClient, Display, TEXT("Authorization Token is empty"));
}
}
// Helpers for http requests
bool FSketchfabTask::MakeRequest(
FString url,
SketchfabRESTState successState,
void (FSketchfabTask::* completeCallback)(FHttpRequestPtr, FHttpResponsePtr, bool),
FString contentType,
void (FSketchfabTask::* progressCallback)(FHttpRequestPtr, int32, int32),
bool upload,
bool authorization) {
// Form the request
ReqRef request = FHttpModule::Get().CreateRequest();
if (authorization)
AddAuthorization(request);
if(upload)
SetUploadRequestContent(request);
request->SetURL(url);
request->SetVerb((upload ? TEXT("POST") : TEXT("GET")));
request->SetHeader("User-Agent", "X-UnrealEngine-Agent");
if (!contentType.IsEmpty())
request->SetHeader("Content-Type", contentType);
// Callbacks
request->OnProcessRequestComplete().BindRaw(this, completeCallback);
if(progressCallback)
request->OnRequestProgress().BindRaw(this, progressCallback);
UE_CLOG(bEnableDebugLogging, LogSketchfabRESTClient, VeryVerbose, TEXT("%s"), *request->GetURL());
// Success / Failure
if (!request->ProcessRequest())
{
SetState(SRS_FAILED);
UE_CLOG(bEnableDebugLogging, LogSketchfabRESTClient, VeryVerbose, TEXT("Failed to process Request %s"), *request->GetURL());
return false;
}
else
{
DebugHttpRequestCounter.Increment();
PendingRequests.Add(request, request->GetURL());
SetState(successState);
return true;
}
}
bool FSketchfabTask::IsValid(FHttpRequestPtr Request, FHttpResponsePtr Response, FString expectedType, bool checkData, bool checkCache) {
DebugHttpRequestCounter.Decrement();
FString OutUrl = PendingRequests.FindRef(Request);
if (!OutUrl.IsEmpty())
{
PendingRequests.Remove(Request);
}
if (!Response.IsValid())
{
UE_LOG(LogSketchfabRESTClient, Display, TEXT("Invalid response"));
return false;
}
if (EHttpResponseCodes::IsOk(Response->GetResponseCode()))
{
// Was object destroyed ?
if (this == nullptr)
{
UE_LOG(LogSketchfabRESTClient, Display, TEXT("Object has already been destroyed"));
SetState(SRS_FAILED);
return false;
}
// Check expected type
if (!expectedType.IsEmpty()) {
if (Response->GetContentType() != expectedType)
{
UE_LOG(LogSketchfabRESTClient, Display, TEXT("Content type is not as expected"));
SetState(SRS_FAILED);
return false;
}
}
// Check data
if (checkData) {
FString data = Response->GetContentAsString();
if (data.IsEmpty())
{
UE_LOG(LogSketchfabRESTClient, Display, TEXT("GetModels_Response content was empty"));
SetState(SRS_FAILED);
return false;
}
}
// Check cache
if (checkCache && TaskData.CacheFolder.IsEmpty())
{
ensure(false);
UE_LOG(LogSketchfabRESTClient, Display, TEXT("Cache Folder not set internally"));
SetState(SRS_FAILED);
return false;
}
return true;
}
else
{
SetState(SRS_FAILED);
UE_CLOG(bEnableDebugLogging, LogSketchfabRESTClient, VeryVerbose, TEXT("Response failed %s Code %d"), *Request->GetURL(), Response->GetResponseCode());
return false;
}
}
/*Http call*/
void FSketchfabTask::CheckLatestPluginVersion()
{
MakeRequest(
"https://api.github.com/repos/sketchfab/Sketchfab-Unreal/releases",
SRS_CHECK_LATEST_VERSION_PROCESSING,
&FSketchfabTask::Check_Latest_Version_Response,
"",
nullptr,
false,
false
);
}
void FSketchfabTask::Search()
{
MakeRequest(
TaskData.ModelSearchURL,
SRS_SEARCH_PROCESSING,
&FSketchfabTask::Search_Response,
"application/json"
);
}
void GetThumnailData(TSharedPtr<FJsonObject> JsonObject, int32 size, FString &thumbUID, FString &thumbURL, int32 &outWidth, int32 &outHeight)
{
outWidth = 0;
outHeight = 0;
TSharedPtr<FJsonObject> thumbnails = JsonObject->GetObjectField("thumbnails");
TArray<TSharedPtr<FJsonValue>> images = thumbnails->GetArrayField("images");
for (int a = 0; a < images.Num(); a++)
{
TSharedPtr<FJsonObject> imageObj = images[a]->AsObject();
FString url = imageObj->GetStringField("url");
FString uid = imageObj->GetStringField("uid");
int32 width = imageObj->GetIntegerField("width");
int32 height = imageObj->GetIntegerField("height");
if (thumbUID.IsEmpty())
{
thumbUID = uid;
thumbURL = url;
}
if (width > outWidth && width <= size && height > outHeight && height <= size)
{
thumbUID = uid;
thumbURL = url;
outWidth = width;
outHeight = height;
}
}
}
void FSketchfabTask::Check_Latest_Version_Response(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if(Response)
{
DebugHttpRequestCounter.Decrement();
if (EHttpResponseCodes::IsOk(Response->GetResponseCode()))
{
if (this == nullptr)
{
UE_LOG(LogSketchfabRESTClient, Display, TEXT("Object has already been destroyed"));
SetState(SRS_FAILED);
return;
}
FString data = Response->GetContentAsString();
if (data.IsEmpty())
{
UE_LOG(LogSketchfabRESTClient, Display, TEXT("CheckLatestVersion_Response content was empty"));
SetState(SRS_FAILED);
}
else
{
//Create a pointer to hold the json serialized data
TArray<TSharedPtr<FJsonValue>> results;
//Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
//Deserialize the json data given Reader and the actual object to deserialize
int separatorIndex = -1;
if (FJsonSerializer::Deserialize(Reader, results))
{
for (int r = 0; r < results.Num(); r++)
{
TSharedPtr<FJsonObject> resultObj = results[r]->AsObject();
FString release_tag = resultObj->GetStringField("tag_name");
TaskData.LatestPluginVersion = release_tag;
break;
}
}
if (!this->IsCompleted && OnCheckLatestVersion().IsBound())
{
OnCheckLatestVersion().Execute(*this);
}
SetState(SRS_CHECK_LATEST_VERSION_DONE);
return;
}
}
else
{
SetState(SRS_FAILED);
UE_CLOG(bEnableDebugLogging, LogSketchfabRESTClient, VeryVerbose, TEXT("Response failed %s Code %d"), *Request->GetURL(), Response->GetResponseCode());
}
}
else
{
UE_LOG(LogSketchfabRESTClient, Display, TEXT("Invalid responde while checking plugin version, check your internet connection"));
SetState(SRS_FAILED);
}
}
/*Assigned function on successfull http call*/
void FSketchfabTask::Search_Response(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if(IsValid(Request, Response, "application/json", true)){
//Create a pointer to hold the json serialized data
TSharedPtr<FJsonObject> JsonObject;
//Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
//Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, JsonObject))
{
TArray<TSharedPtr<FJsonValue>> results = JsonObject->GetArrayField("results");
TaskData.NextURL = JsonObject->GetStringField("next");
for (int r = 0; r < results.Num(); r++)
{
TSharedPtr<FJsonObject> resultObj = results[r]->AsObject();
FString modelUID = resultObj->GetStringField("uid");
FString modelName = resultObj->GetStringField("name");
FString authorName;
TSharedPtr<FJsonObject> userObj = resultObj->GetObjectField("user");
if (userObj.IsValid())
{
authorName = userObj->GetStringField("username");
}
TSharedPtr<FSketchfabTaskData> OutItem = MakeShareable(new FSketchfabTaskData());
GetThumnailData(resultObj, 512, OutItem->ThumbnailUID, OutItem->ThumbnailURL, OutItem->ThumbnailWidth, OutItem->ThumbnailHeight);
GetThumnailData(resultObj, 1024, OutItem->ThumbnailUID_1024, OutItem->ThumbnailURL_1024, OutItem->ThumbnailWidth_1024, OutItem->ThumbnailHeight_1024);
OutItem->ModelPublishedAt = GetPublishedAt(resultObj);
OutItem->ModelName = modelName;
OutItem->ModelUID = modelUID;
OutItem->CacheFolder = TaskData.CacheFolder;
OutItem->Token = TaskData.Token;
OutItem->ModelAuthor = authorName;
TSharedPtr<FJsonObject> archives = resultObj->GetObjectField("archives");
if (archives.IsValid())
{
TSharedPtr<FJsonObject> gltf = archives->GetObjectField("gltf");
if (gltf.IsValid())
{
OutItem->ModelSize = gltf->GetIntegerField("size");
}
}
SearchData.Add(OutItem);
}
}
OnSearch().Execute(*this);
SetState(SRS_SEARCH_DONE);
return;
}
}
void FSketchfabTask::GetThumbnail()
{
MakeRequest(
TaskData.ThumbnailURL,
SRS_GETTHUMBNAIL_PROCESSING,
&FSketchfabTask::GetThumbnail_Response,
"image/jpeg"
);
}
void FSketchfabTask::GetThumbnail_Response(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (IsValid(Request, Response, "image/jpeg", false, true)) {
const TArray<uint8> &data = Response->GetContent();
if (data.Num() > 0)
{
IPlatformFile& PlatformFile = FPlatformFileManager::Get().GetPlatformFile();
FString jpg = TaskData.ThumbnailUID + ".jpg";
FString FileName = TaskData.CacheFolder / jpg;
IFileHandle* FileHandle = PlatformFile.OpenWrite(*FileName);
if (FileHandle)
{
// Write the bytes to the file
FileHandle->Write(data.GetData(), data.Num());
// Close the file again
delete FileHandle;
}
}
if (!this->IsCompleted && OnThumbnailDownloaded().IsBound())
{
//UE_LOG(LogSketchfabRESTClient, Display, TEXT("Thumbnail downloaded"));
OnThumbnailDownloaded().Execute(*this);
}
SetState(SRS_GETTHUMBNAIL_DONE);
}
}
void FSketchfabTask::GetModelLink()
{
FString url = "https://api.sketchfab.com/v3/";
if (TaskData.OrgModel) {
url += "orgs/" + TaskData.OrgUID + "/models/" + TaskData.ModelUID + "/download";
}
else {
url += "models/" + TaskData.ModelUID + "/download";
}
UE_LOG(LogSketchfabTask, Display, TEXT("Requesting model link %s"), *url);
MakeRequest(
url,
SRS_GETMODELLINK_PROCESSING,
&FSketchfabTask::GetModelLink_Response,
"application/json",
nullptr
);
}
void FSketchfabTask::GetModelLink_Response(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (IsValid(Request, Response, "application/json")) {
//Create a pointer to hold the json serialized data
TSharedPtr<FJsonObject> JsonObject;
//Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
//Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, JsonObject))
{
TSharedPtr<FJsonObject> gltfObject = JsonObject->GetObjectField("gltf");
FString url = gltfObject->GetStringField("url");
TaskData.ModelURL = url;
if (!this->IsCompleted && OnModelLink().IsBound())
{
//UE_LOG(LogSketchfabRESTClient, Display, TEXT("Thumbnail downloaded"));
OnModelLink().Execute(*this);
SetState(SRS_GETTHUMBNAIL_DONE);
return;
}
}
SetState(SRS_FAILED);
}
}
void FSketchfabTask::DownloadModel()
{
MakeRequest(
TaskData.ModelURL,
SRS_DOWNLOADMODEL_PROCESSING,
&FSketchfabTask::DownloadModel_Response,
"",
&FSketchfabTask::DownloadModelProgress,
false,
false
);
}
void FSketchfabTask::DownloadModel_Response(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (IsValid(Request, Response, "", false, true)) {
FString contentType = Response->GetContentType();
if (contentType == "application/xml")
{
const TArray<uint8> &blob = Response->GetContent();
FString data = BytesToString(blob.GetData(), blob.Num());
FString Fixed;
for (int i = 0; i < data.Len(); i++)
{
const TCHAR c = data[i] - 1;
Fixed.AppendChar(c);
}
SetState(SRS_FAILED);
return;
}
const TArray<uint8> &data = Response->GetContent();
if (data.Num() > 0)
{
IPlatformFile& PlatformFile = FPlatformFileManager::Get().GetPlatformFile();
FString fn = TaskData.ModelUID + ".zip";
FString FileName = TaskData.CacheFolder / fn;
IFileHandle* FileHandle = PlatformFile.OpenWrite(*FileName);
if (FileHandle)
{
// Write the bytes to the file
FileHandle->Write(data.GetData(), data.Num());
// Close the file again
delete FileHandle;
if (!this->IsCompleted && OnModelDownloaded().IsBound())
{
//UE_LOG(LogSketchfabRESTClient, Display, TEXT("Thumbnail downloaded"));
OnModelDownloaded().Execute(*this);
SetState(SRS_DOWNLOADMODEL_DONE);
return;
}
}
}
SetState(SRS_FAILED);
}
}
void FSketchfabTask::DownloadModelProgress(FHttpRequestPtr HttpRequest, int32 BytesSent, int32 BytesReceived)
{
if (!this->IsCompleted && OnModelDownloadProgress().IsBound())
{
TaskData.DownloadedBytes = BytesReceived;
OnModelDownloadProgress().Execute(*this);
}
}
void FSketchfabTask::GetUserOrgs()
{
MakeRequest(
"https://sketchfab.com/v3/me/orgs",
SRS_GETUSERORGS_PROCESSING,
&FSketchfabTask::GetUserOrgs_Response,
""
);
}
void FSketchfabTask::GetUserOrgs_Response(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (IsValid(Request, Response)) {
//Create a pointer to hold the json serialized data
TSharedPtr<FJsonObject> JsonObject;
//Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
//Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, JsonObject))
{
TArray<TSharedPtr<FJsonValue>> results = JsonObject->GetArrayField("results");
TaskData.NextURL = JsonObject->GetStringField("next");
if(results.Num()==0)
UE_LOG(LogSketchfabRESTClient, Warning, TEXT("User is not a member of any org"));
for (int r = 0; r < results.Num(); r++)
{
TSharedPtr<FJsonObject> resultObj = results[r]->AsObject();
FSketchfabOrg org;
org.name = resultObj->GetStringField("displayName");
org.uid = resultObj->GetStringField("uid");
org.url = resultObj->GetStringField("publicProfileUrl");
UE_LOG(LogSketchfabRESTClient, Display, TEXT("User is member of an org %s (%s): %s"), *(org.name), *(org.uid), *(org.url));
TaskData.Orgs.Add(org);
}
}
if (!this->IsCompleted && OnUserOrgs().IsBound())
{
OnUserOrgs().Execute(*this);
}
SetState(SRS_GETUSERORGS_DONE);
}
}
void FSketchfabTask::GetOrgsProjects()
{
MakeRequest(
"https://sketchfab.com/v3/orgs/" + TaskData.org->uid + "/projects",
SRS_GETORGSPROJECTS_PROCESSING,
&FSketchfabTask::GetOrgsProjects_Response,
""
);
}
void FSketchfabTask::GetOrgsProjects_Response(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (IsValid(Request, Response)) {
//Create a pointer to hold the json serialized data
TSharedPtr<FJsonObject> JsonObject;
//Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
//Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, JsonObject))
{
TArray<TSharedPtr<FJsonValue>> results = JsonObject->GetArrayField("results");
TaskData.NextURL = JsonObject->GetStringField("next");
if (results.Num() == 0)
UE_LOG(LogSketchfabRESTClient, Display, TEXT("No projects available in the org"));
for (int r = 0; r < results.Num(); r++)
{
TSharedPtr<FJsonObject> resultObj = results[r]->AsObject();
FSketchfabProject project;
project.name = resultObj->GetStringField("name");
project.uid = resultObj->GetStringField("uid");
project.slug = resultObj->GetStringField("slug");
project.modelCount = resultObj->GetNumberField("modelCount");
project.memberCount = resultObj->GetNumberField("memberCount");
TaskData.Projects.Add(project);
}
}
if (!this->IsCompleted && OnOrgsProjects().IsBound())
{
OnOrgsProjects().Execute(*this);
}
SetState(SRS_GETORGSPROJECTS_DONE);
}
}
void FSketchfabTask::GetUserData()
{
MakeRequest(
"https://sketchfab.com/v3/me",
SRS_GETUSERDATA_PROCESSING,
&FSketchfabTask::GetUserData_Response,
""
);
}
void FSketchfabTask::GetUserData_Response(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (IsValid(Request, Response)) {
//Create a pointer to hold the json serialized data
TSharedPtr<FJsonObject> JsonObject;
//Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
//Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, JsonObject))
{
if (JsonObject->HasField("username"))
{
TaskData.UserSession.UserName = JsonObject->GetStringField("username");
}
if (JsonObject->HasField("displayName"))
{
TaskData.UserSession.UserDisplayName = JsonObject->GetStringField("displayName");
}
if (JsonObject->HasField("account"))
{
FString accountType = JsonObject->GetStringField("account");
if(accountType.Compare("pro") == 0)
{
TaskData.UserSession.UserPlan = ACCOUNT_PRO;
}
else if(accountType.Compare("prem") == 0)
{
TaskData.UserSession.UserPlan = ACCOUNT_PREMIUM;
}
else if(accountType.Compare("biz") == 0)
{
TaskData.UserSession.UserPlan = ACCOUNT_BUSINESS;
}
else if(accountType.Compare("ent") == 0)
{
TaskData.UserSession.UserPlan = ACCOUNT_ENTERPRISE;
}
else if(accountType.Compare("plus") == 0)
{
TaskData.UserSession.UserPlan = ACCOUNT_PLUS;
}
else
{
TaskData.UserSession.UserPlan = ACCOUNT_BASIC;
}
}
if (JsonObject->HasField("uid"))
{
TaskData.UserSession.UserUID = JsonObject->GetStringField("uid");
}
if (JsonObject->HasField("avatar"))
{
TSharedPtr<FJsonObject> AvatarObj = JsonObject->GetObjectField("avatar");
if (AvatarObj->HasField("images"))
{
TArray<TSharedPtr<FJsonValue>> ImagesArray = AvatarObj->GetArrayField("images");
if (ImagesArray.Num() > 0)
{
TSharedPtr<FJsonObject> ImageObj = ImagesArray[0]->AsObject();
if (ImageObj->HasField("url"))
{
TaskData.UserSession.UserThumbnaillURL = ImageObj->GetStringField("url");
}
if (ImageObj->HasField("uid"))
{
TaskData.UserSession.UserThumbnaillUID = ImageObj->GetStringField("uid");
}
}
}
}
}
if (!this->IsCompleted && OnUserData().IsBound())
{
OnUserData().Execute(*this);
}
SetState(SRS_GETUSERDATA_DONE);
}
}
void FSketchfabTask::GetUserThumbnail()
{
MakeRequest(
TaskData.UserSession.UserThumbnaillURL,
SRS_GETUSERTHUMB_PROCESSING,
&FSketchfabTask::GetUserThumbnail_Response,
"image/jpeg"
);
}
void FSketchfabTask::GetUserThumbnail_Response(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (IsValid(Request, Response, "image/jpeg")) {
const TArray<uint8> &data = Response->GetContent();
if (data.Num() > 0)
{
IPlatformFile& PlatformFile = FPlatformFileManager::Get().GetPlatformFile();
FString uid = TaskData.UserSession.UserThumbnaillUID;
if (uid.IsEmpty())
{
//The json file currently does not contain the uid of the thumbnail, so for now I will use the users uid
uid = TaskData.UserSession.UserUID;
}
FString jpg = uid + ".jpg";
FString FileName = TaskData.CacheFolder / jpg;
IFileHandle* FileHandle = PlatformFile.OpenWrite(*FileName);
if (FileHandle)
{
// Write the bytes to the file
FileHandle->Write(data.GetData(), data.Num());
// Close the file again
delete FileHandle;
}
}
if (!this->IsCompleted && OnUserThumbnail().IsBound())
{
//UE_LOG(LogSketchfabRESTClient, Display, TEXT("Thumbnail downloaded"));
OnUserThumbnail().Execute(*this);
}
SetState(SRS_GETUSERTHUMB_DONE);
}
}
void FSketchfabTask::GetCategories()
{
MakeRequest(
"https://api.sketchfab.com/v3/categories",
SRS_GETCATEGORIES_PROCESSING,
&FSketchfabTask::GetCategories_Response,
""
);
}
void FSketchfabTask::GetCategories_Response(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (IsValid(Request, Response, "application/json", true)) {
//Create a pointer to hold the json serialized data
TSharedPtr<FJsonObject> JsonObject;
//Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
//Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, JsonObject))
{
TArray<TSharedPtr<FJsonValue>> results = JsonObject->GetArrayField("results");
TaskData.NextURL = JsonObject->GetStringField("next");
for (int r = 0; r < results.Num(); r++)
{
TSharedPtr<FJsonObject> resultObj = results[r]->AsObject();
FSketchfabCategory cat;
cat.uid = resultObj->GetStringField("uid");
cat.uri = resultObj->GetStringField("uri");
cat.name = resultObj->GetStringField("name");
cat.slug = resultObj->GetStringField("slug");
TaskData.Categories.Add(cat);
}
}
OnCategories().Execute(*this);
SetState(SRS_GETCATEGORIES_DONE);
return;
}
}
void FSketchfabTask::GetModelInfo()
{
FString url = "https://api.sketchfab.com/v3/";
if (TaskData.OrgModel) {
url += "orgs/" + TaskData.OrgUID + "/models/" + TaskData.ModelUID;
}
else {
url += "models/" + TaskData.ModelUID;
}
UE_LOG(LogSketchfabTask, Display, TEXT("Getting model info for model %s"), *(TaskData.ModelUID));
MakeRequest(
url,
SRS_GETMODELINFO_PROCESSING,
&FSketchfabTask::GetModelInfo_Response,
"image/jpeg"
);
}
void FSketchfabTask::GetModelInfo_Response(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (IsValid(Request, Response, "application/json", true)) {
//Create a pointer to hold the json serialized data
TSharedPtr<FJsonObject> JsonObject;
//Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
//Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, JsonObject))
{
TaskData.ModelVertexCount = JsonObject->GetIntegerField("vertexCount");
TaskData.ModelFaceCount = JsonObject->GetIntegerField("faceCount");
TaskData.AnimationCount = JsonObject->GetIntegerField("animationCount");
//TaskData.ModelSize = JsonObject->GetObjectField("archives")->GetObjectField("gltf")->GetIntegerField("size");
TaskData.ModelPublishedAt = GetPublishedAt(JsonObject);
TSharedPtr<FJsonObject> archives = JsonObject->GetObjectField("archives");
if (archives.IsValid())
{
TSharedPtr<FJsonObject> gltf = archives->GetObjectField("gltf");
if (gltf.IsValid())
{
TaskData.ModelSize = gltf->GetIntegerField("size");
}
}
TSharedPtr<FJsonObject> license = JsonObject->GetObjectField("license");
if (license.IsValid())
{
TaskData.LicenceType = license->GetStringField("fullName");
TaskData.LicenceInfo = license->GetStringField("requirements");
}
if (TaskData.LicenceType.IsEmpty()) // Personal models have no license data
{
TaskData.LicenceType = "Personal";
TaskData.LicenceInfo = "You own this model";
}
GetThumnailData(JsonObject, 1024, TaskData.ThumbnailUID_1024, TaskData.ThumbnailURL_1024, TaskData.ThumbnailWidth_1024, TaskData.ThumbnailHeight_1024);
}
OnModelInfo().Execute(*this);
SetState(SRS_GETMODELINFO_DONE);
}
}
FDateTime FSketchfabTask::GetPublishedAt(TSharedPtr<FJsonObject> JsonObject)
{
FDateTime ret;
FString modelPublishedAt = JsonObject->GetStringField("publishedAt").Left(10);
TArray<FString> publishedAt;
modelPublishedAt.ParseIntoArray(publishedAt, TEXT("-"));
if (publishedAt.Num() == 3)
{
ret = FDateTime(FCString::Atoi(*publishedAt[0]), FCString::Atoi(*publishedAt[1]), FCString::Atoi(*publishedAt[2]));
}
else
{
ret = FDateTime::Today();
}
return ret;
}
FString BoundaryBegin = "";
FString BoundaryLabel = "";
FString BoundaryEnd = "";
FString RequestData = "";
TArray<uint8> RequestBytes;
TArray<uint8> FStringToUint8(const FString& InString)
{
TArray<uint8> OutBytes;
// Handle empty strings
if (InString.Len() > 0)
{
FTCHARToUTF8 Converted(*InString); // Convert to UTF8
OutBytes.Append(reinterpret_cast<const uint8*>(Converted.Get()), Converted.Length());
}
return OutBytes;
}
void AddField(const FString& Name, const FString& Value)
{
RequestData += FString(TEXT("\r\n"))
+ BoundaryBegin
+ FString(TEXT("Content-Disposition: form-data; name=\""))
+ Name
+ FString(TEXT("\"\r\n\r\n"))
+ Value;
}
void AddFile(const FString& Name, const FString& FileName, const FString& FilePath) {
TArray<uint8> UpFileRawData;
FFileHelper::LoadFileToArray(UpFileRawData, *FilePath);
RequestData += FString(TEXT("\r\n"))
+ BoundaryBegin
+ FString(TEXT("Content-Disposition: form-data; name=\""))
+ "modelFile"
+ FString(TEXT("\"; filename=\""))
+ FileName
+ FString(TEXT("\"\r\n\r\n"));
RequestBytes = FStringToUint8(RequestData);
RequestBytes.Append(UpFileRawData);
}
void FSketchfabTask::SetUploadRequestContent(ReqRef Request) {
// Name/Value fields
AddField(TEXT("name"), TaskData.ModelName);
AddField(TEXT("description"), TaskData.ModelDescription);
AddField(TEXT("tags"), TaskData.ModelTags);
AddField(TEXT("password"), TaskData.ModelPassword);
AddField(TEXT("isPublished"), TaskData.Draft ? TEXT("false") : TEXT("true"));
AddField(TEXT("isPrivate"), TaskData.Private ? TEXT("true") : TEXT("false"));
AddField(TEXT("source"), TEXT("unreal"));
if (!TaskData.ProjectUID.IsEmpty()) {
AddField(TEXT("orgProject"), TaskData.ProjectUID);
}
else {
UE_LOG(LogSketchfabTask, Error, TEXT("No project selected (uid empty)"));
}
// File
AddFile(TEXT("modelFile"), FPaths::GetCleanFilename(TaskData.FileToUpload), TaskData.FileToUpload);
// Boundary end
RequestBytes.Append(FStringToUint8(BoundaryEnd));
// Set the content of the request
Request->SetContent(RequestBytes);
}
//CombinedContent.Append(FStringToUint8(BoundaryEnd));
void FSketchfabTask::UploadModel()
{
// Set the multipart boundary properties
BoundaryLabel = FString(TEXT("e543322540af456f9a3773049ca02529-")) + FString::FromInt(FMath::Rand());
BoundaryBegin = FString(TEXT("--")) + BoundaryLabel + FString(TEXT("\r\n"));
BoundaryEnd = FString(TEXT("\r\n--")) + BoundaryLabel + FString(TEXT("--\r\n"));
FString uploadUrl = "https://api.sketchfab.com/v3/";
if ( TaskData.UsesOrgProfile ) {
uploadUrl += "orgs/" + TaskData.OrgUID + "/models";
}
else {
uploadUrl += "models";
}
//uploadUrl += "models";
UE_LOG(LogSketchfabTask, Error, TEXT("Uploading to: %s"), *uploadUrl);
MakeRequest(
uploadUrl,
SRS_UPLOADMODEL_PROCESSING,
&FSketchfabTask::UploadModel_Response,
"multipart/form-data; boundary=" + BoundaryLabel,
nullptr,
true
);
}
void FSketchfabTask::UploadModel_Response(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
if (IsValid(Request, Response)) {
// Serialize the request response (uri and model uid)
TSharedPtr<FJsonObject> JsonObject;
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
if (FJsonSerializer::Deserialize(Reader, JsonObject))
{
TaskData.uid = JsonObject->GetStringField("uid");
TaskData.uri = JsonObject->GetStringField("uri");
}
if (!this->IsCompleted && OnModelUploaded().IsBound())
{
OnModelUploaded().Execute(*this);
}
SetState(SRS_UPLOADMODEL_DONE);
}
}
| 27.843277
| 165
| 0.715268
|
jing-interactive
|
542708321e48c6722546b774aefc04a6e86fa443
| 4,445
|
hpp
|
C++
|
include/codegen/include/GlobalNamespace/DisappearingArrowController.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/GlobalNamespace/DisappearingArrowController.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/GlobalNamespace/DisappearingArrowController.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
// Including type: IManualUpdate
#include "GlobalNamespace/IManualUpdate.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: ColorNoteVisuals
class ColorNoteVisuals;
// Forward declaring type: CutoutEffect
class CutoutEffect;
// Forward declaring type: NoteMovement
class NoteMovement;
// Forward declaring type: NoteController
class NoteController;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: SpriteRenderer
class SpriteRenderer;
// Forward declaring type: MeshRenderer
class MeshRenderer;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: DisappearingArrowController
class DisappearingArrowController : public UnityEngine::MonoBehaviour, public GlobalNamespace::IManualUpdate {
public:
// private ColorNoteVisuals _colorNoteVisuals
// Offset: 0x18
GlobalNamespace::ColorNoteVisuals* colorNoteVisuals;
// private UnityEngine.SpriteRenderer[] _spriteRenderers
// Offset: 0x20
::Array<UnityEngine::SpriteRenderer*>* spriteRenderers;
// private UnityEngine.MeshRenderer _cubeMeshRenderer
// Offset: 0x28
UnityEngine::MeshRenderer* cubeMeshRenderer;
// private CutoutEffect _arrowCutoutEffect
// Offset: 0x30
GlobalNamespace::CutoutEffect* arrowCutoutEffect;
// private NoteMovement _noteMovement
// Offset: 0x38
GlobalNamespace::NoteMovement* noteMovement;
// private System.Single _disappearingNormalStart
// Offset: 0x40
float disappearingNormalStart;
// private System.Single _disappearingNormalEnd
// Offset: 0x44
float disappearingNormalEnd;
// private System.Single _disappearingGhostStart
// Offset: 0x48
float disappearingGhostStart;
// private System.Single _disappearingGhostEnd
// Offset: 0x4C
float disappearingGhostEnd;
// private System.Single[] _initialSpriteAlphas
// Offset: 0x50
::Array<float>* initialSpriteAlphas;
// private System.Boolean _initialized
// Offset: 0x58
bool initialized;
// private System.Boolean _ghostNote
// Offset: 0x59
bool ghostNote;
// private System.Single _prevArrowTransparency
// Offset: 0x5C
float prevArrowTransparency;
// private System.Single _minDistance
// Offset: 0x60
float minDistance;
// private System.Single _maxDistance
// Offset: 0x64
float maxDistance;
// protected System.Void Awake()
// Offset: 0xBE8398
void Awake();
// protected System.Void OnDestroy()
// Offset: 0xBE8510
void OnDestroy();
// private System.Void HandleNoteMovementDidInit()
// Offset: 0xBE889C
void HandleNoteMovementDidInit();
// private System.Void HandleColorNoteVisualsDidInitEvent(ColorNoteVisuals colorNoteVisuals, NoteController noteController)
// Offset: 0xBE89AC
void HandleColorNoteVisualsDidInitEvent(GlobalNamespace::ColorNoteVisuals* colorNoteVisuals, GlobalNamespace::NoteController* noteController);
// private System.Void SetArrowTransparency(System.Single arrowTransparency)
// Offset: 0xBE8704
void SetArrowTransparency(float arrowTransparency);
// public System.Void ManualUpdate()
// Offset: 0xBE8660
// Implemented from: IManualUpdate
// Base method: System.Void IManualUpdate::ManualUpdate()
void ManualUpdate();
// public System.Void .ctor()
// Offset: 0xBE8B1C
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
static DisappearingArrowController* New_ctor();
}; // DisappearingArrowController
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::DisappearingArrowController*, "", "DisappearingArrowController");
#pragma pack(pop)
| 37.991453
| 146
| 0.733183
|
Futuremappermydud
|
542977c2b88e21d499849e6890fdf214006815a9
| 740
|
cpp
|
C++
|
chap6/chap6-1.1.cpp
|
liangzai90/Amazing-Algorithm-With-C
|
d1e992517eafd9197075d85591ed5270d945b5e3
|
[
"Apache-2.0"
] | null | null | null |
chap6/chap6-1.1.cpp
|
liangzai90/Amazing-Algorithm-With-C
|
d1e992517eafd9197075d85591ed5270d945b5e3
|
[
"Apache-2.0"
] | null | null | null |
chap6/chap6-1.1.cpp
|
liangzai90/Amazing-Algorithm-With-C
|
d1e992517eafd9197075d85591ed5270d945b5e3
|
[
"Apache-2.0"
] | null | null | null |
/*
数学趣题(=)
连续整数固定和问题
*/
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <vector>
using namespace std;
void cntnsIntSum(int n)
{
int j=0,sum = 0;
for (int i = 1; i < n; i++) //控制起点的选择,从1到n-1
{
j = i - 1;
while (sum < n) //从起点向后顺序累加
{
j++;
sum = sum + j;//sum记录当前的累加和
}
if (sum == n)//找到了一个n的连续整数固定和
{
printf("%d+...+%d = %d \r\n", i, j, n);
}
sum = 0;
}
}
int main()
{
int n;
printf("Please input a integer \r\n");
scanf("%d", &n);
cntnsIntSum(n);
cout << endl;
cout << "Hello World C Algorithm." << endl;
system("pause");
return 0;
}
/*
Please input a integer
27
2+...+7 = 27
8+...+10 = 27
13+...+14 = 27
*/
| 11.212121
| 46
| 0.539189
|
liangzai90
|
542b058edf3a0fe27f276768a3b9b4b57dd39141
| 917
|
cpp
|
C++
|
HazelGameEngine/src/Hazel/Renderer/Buffer.cpp
|
duo131/Hazel_practice
|
04eeec2550b9536e7b8a565d67630c1d2a669991
|
[
"Apache-2.0"
] | null | null | null |
HazelGameEngine/src/Hazel/Renderer/Buffer.cpp
|
duo131/Hazel_practice
|
04eeec2550b9536e7b8a565d67630c1d2a669991
|
[
"Apache-2.0"
] | null | null | null |
HazelGameEngine/src/Hazel/Renderer/Buffer.cpp
|
duo131/Hazel_practice
|
04eeec2550b9536e7b8a565d67630c1d2a669991
|
[
"Apache-2.0"
] | null | null | null |
#include "hzpch.h"
#include "Buffer.h"
#include "Renderer.h"
#include "Platform/OpenGL/OpenGLBuffer.h"
namespace Hazel {
VertexBuffer* VertexBuffer::Create(float* vertices, uint32_t size)
{
switch (Renderer::GetRedererAPI())
{
case RendererAPI::API::NONE:
HZ_CORE_ASSERT(false, "RendererAPI not support");
return nullptr;
case RendererAPI::API::OPENGL:
return new OpenGLVertexBuffer(vertices, size);
default:
break;
}
HZ_CORE_ASSERT(false, "RendererAPI not support");
return nullptr;
}
IndexBuffer* IndexBuffer::Create(uint32_t* indices, uint32_t size)
{
switch (Renderer::GetRedererAPI())
{
case RendererAPI::API::NONE:
HZ_CORE_ASSERT(false, "RendererAPI not support");
return nullptr;
case RendererAPI::API::OPENGL:
return new OpenGLIndexBuffer(indices, size);
default:
break;
}
HZ_CORE_ASSERT(false, "RendererAPI not support");
return nullptr;
}
}
| 22.365854
| 67
| 0.718648
|
duo131
|
f9abc7cac5d5fb992b23a3e811475d036e696853
| 4,742
|
cc
|
C++
|
LuoGu/3380.cc
|
DesZou/Eros
|
f49c9ce1dfe193de8199163286afc28ff8c52eef
|
[
"MIT"
] | 1
|
2017-10-12T13:49:10.000Z
|
2017-10-12T13:49:10.000Z
|
LuoGu/3380.cc
|
DesZou/Eros
|
f49c9ce1dfe193de8199163286afc28ff8c52eef
|
[
"MIT"
] | null | null | null |
LuoGu/3380.cc
|
DesZou/Eros
|
f49c9ce1dfe193de8199163286afc28ff8c52eef
|
[
"MIT"
] | 1
|
2017-10-12T13:49:38.000Z
|
2017-10-12T13:49:38.000Z
|
/*
* luogu3380
*
* 标解应该有平衡树,用带修改主席树实现查前驱后继就怪怪的。
* 但是主席树够强啊,跑得还特别快。(比较快)
* */
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <limits>
#include <iostream>
using std::cin;
using std::cout;
using std::cerr;
template<class T>
bool chkmin(T &a, const T &b) { return a > b? a = b, 1 : 0; }
template<class T>
bool chkmax(T &a, const T &b) { return a < b? a = b, 1 : 0; }
const char El = 10;
const int Size = 5e4 + 5;
const int Log = 17;
const int Inf = std::numeric_limits<int>::max();
struct Node { int ch[2], val; } c[Size * Log * Log * 2];
struct Data { int opt, l, r, k, pos; } d[Size];
struct Hash {
int elem[Size * 2], len;
void init() {
std::sort(elem + 1, elem + 1 + len);
len = std::unique(elem + 1, elem + 1 + len) - elem - 1;
}
void push(const int x) { elem[++len] = x; }
int operator[](const int x) {
return std::lower_bound(elem + 1, elem + 1 + len, x) - elem;
}
} hash;
int _Index;
int n, m;
int root[Size * 2];
void update(int &i, int l, int r, int pos, int key) {
if (!i) i = ++_Index;
c[i].val += key;
if (l == r) return;
int mid = (l + r) >> 1;
if (pos <= mid) update(c[i].ch[0], l, mid, pos, key);
else update(c[i].ch[1], mid + 1, r, pos, key);
}
inline int lowbit(const int x) { return -x & x; }
void modify(int p, int pos, int key) {
for (; p <= n; p += lowbit(p)) update(root[p], 1, hash.len, pos, key);
}
int tmpf[Log * 2], tmpl[Log * 2];
void load(const int &fst, const int &lst) {
*tmpf = *tmpl = 0;
for (int i = fst; i; i -= lowbit(i)) tmpf[++(*tmpf)] = root[i];
for (int i = lst; i; i -= lowbit(i)) tmpl[++(*tmpl)] = root[i];
}
void move(const bool dir) {
for (int i = 1; i <= *tmpf; ++i) tmpf[i] = c[tmpf[i]].ch[dir];
for (int i = 1; i <= *tmpl; ++i) tmpl[i] = c[tmpl[i]].ch[dir];
}
int kth(int l, int r, int rank) {
if (l == r) return hash.elem[l];
int sum = 0, mid = (l + r) >> 1;
for (int i = 1; i <= *tmpf; ++i) sum -= c[c[tmpf[i]].ch[0]].val;
for (int i = 1; i <= *tmpl; ++i) sum += c[c[tmpl[i]].ch[0]].val;
move(sum < rank);
return sum < rank
? kth(mid + 1, r, rank - sum)
: kth(l, mid, rank);
}
int rank(int l, int r, int var, bool showMore = false) {
if (l == r) {
if (!showMore) return 1;
int res = 0;
for (int i = 1; i <= *tmpf; ++i) res -= c[tmpf[i]].val;
for (int i = 1; i <= *tmpl; ++i) res += c[tmpl[i]].val;
return res;
} else {
int mid = (l + r) >> 1;
if (var > mid) {
int sum = 0;
for (int i = 1; i <= *tmpf; ++i) sum -= c[c[tmpf[i]].ch[0]].val;
for (int i = 1; i <= *tmpl; ++i) sum += c[c[tmpl[i]].ch[0]].val;
move(1);
return sum + rank(mid + 1, r, var, showMore);
} else {
move(0);
return rank(l, mid, var, showMore);
}
}
}
int w[Size];
int main() {
cin.sync_with_stdio(0);
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
cin >> w[i];
hash.push(w[i]);
}
for (int i = 1; i <= m; ++i) {
cin >> d[i].opt;
if (d[i].opt == 3) {
cin >> d[i].pos >> d[i].k;
} else {
cin >> d[i].l >> d[i].r >> d[i].k;
}
if (d[i].opt != 2) hash.push(d[i].k);
}
hash.init();
for (int i = 1; i <= n; ++i) modify(i, hash[w[i]], 1);
for (int i = 1, x; i <= m; ++i)
switch (d[i].opt) {
case 1:
load(d[i].l - 1, d[i].r);
cout << rank(1, hash.len, hash[d[i].k]) << El;
break;
case 2:
load(d[i].l - 1, d[i].r);
cout << kth(1, hash.len, d[i].k) << El;
break;
case 3:
modify(d[i].pos, hash[w[d[i].pos]], -1);
modify(d[i].pos, hash[w[d[i].pos] = d[i].k], 1);
break;
case 4:
load(d[i].l - 1, d[i].r);
x = rank(1, hash.len, hash[d[i].k]);
if (x == 1) {
cout << -Inf << El;
} else {
load(d[i].l - 1, d[i].r);
cout << kth(1, hash.len, x - 1) << El;
}
break;
case 5:
load(d[i].l - 1, d[i].r);
x = rank(1, hash.len, hash[d[i].k], true);
if (x == d[i].r - d[i].l + 1) {
cout << Inf << El;
} else {
load(d[i].l - 1, d[i].r);
cout << kth(1, hash.len, x + 1) << El;
}
break;
default:
return -1;
}
return 0;
}
| 26.79096
| 76
| 0.420498
|
DesZou
|
f9ac58b344e3e5afab1308c9a504d9b6568e1bc3
| 1,906
|
cpp
|
C++
|
src/Imperial.cpp
|
JohnBobSmith/ConvertIt
|
4b2393f7aecdc12f69820f2b41b1a6617cd62f5d
|
[
"MIT"
] | 1
|
2019-01-27T21:43:29.000Z
|
2019-01-27T21:43:29.000Z
|
src/Imperial.cpp
|
JohnBobSmith/convertit-git
|
4b2393f7aecdc12f69820f2b41b1a6617cd62f5d
|
[
"MIT"
] | null | null | null |
src/Imperial.cpp
|
JohnBobSmith/convertit-git
|
4b2393f7aecdc12f69820f2b41b1a6617cd62f5d
|
[
"MIT"
] | null | null | null |
#include "../include/Conversions.h"
#include "../include/Imperial.h"
#include <iostream>
float Imperial::convAcresToHectares(float acres)
{
float hectares = acres * 0.404685642;
return hectares;
}
float Imperial::convMilesToKilometers(float miles)
{
//Do not divide by 0
if (miles == 0) {
miles = miles + 0.1;
}
float km = miles / 1.609344;
return km;
}
float Imperial::convYardsToMeters(float yards)
{
float meters = yards * 0.9144;
return meters;
}
float Imperial::convFeetToMeters(float feet)
{
float meters = feet * 0.3048;
return meters;
}
float Imperial::convInchesToCentimetres(float inches)
{
float cm = inches * 2.54;
return cm;
}
void Imperial::convAcresToHectaresAndPrint(float acres, bool useUnitSymbols)
{
float result = convAcresToHectares(acres);
if (useUnitSymbols) {
std::cout << result << "ha";
} else {
std::cout << result;
}
}
void Imperial::convMilesToKilometersAndPrint(float miles, bool useUnitSymbols)
{
float result = convMilesToKilometers(miles);
if (useUnitSymbols) {
std::cout << result << "km";
} else {
std::cout << result;
}
}
void Imperial::convYardsToMetersAndPrint(float yards, bool useUnitSymbols)
{
float result = convYardsToMeters(yards);
if (useUnitSymbols) {
std::cout << result << "m";
} else {
std::cout << result;
}
}
void Imperial::convFeetToMetersAndPrint(float feet, bool useUnitSymbols)
{
float result = convFeetToMeters(feet);
if (useUnitSymbols) {
std::cout << result << "m";
} else {
std::cout << result;
}
}
void Imperial::convInchesToCentimetresAndPrint(float inches, bool useUnitSymbols)
{
float result = convInchesToCentimetres(inches);
if (useUnitSymbols) {
std::cout << result << "cm";
} else {
std::cout << result;
}
}
| 21.41573
| 81
| 0.63851
|
JohnBobSmith
|
f9ad46bb0d2c8388bad8c833fc8ffbd08c52aa07
| 475
|
cpp
|
C++
|
ccc-2016/q3.cpp
|
dvychen/ccc-practice
|
fdad9255e204b38abba0684e989d092b8979391b
|
[
"MIT"
] | null | null | null |
ccc-2016/q3.cpp
|
dvychen/ccc-practice
|
fdad9255e204b38abba0684e989d092b8979391b
|
[
"MIT"
] | null | null | null |
ccc-2016/q3.cpp
|
dvychen/ccc-practice
|
fdad9255e204b38abba0684e989d092b8979391b
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
// Input
int N, M;
cin >> N;
cin >> M;
int phoplaces[M];
for (int i = 0; i < M; i++) {
cin >> phoplaces[i];
}
int roads[N-1][2];
for (int i = 0; i < N-1; i++) {
cin >> roads[i][0];
cin >> roads[i][1];
}
// Solution for first 3 marks
int path = N-1;
int counter = 0;
int position = phoplaces[0];
while (position != phoplaces[1]) {
counter++;
}
}
| 16.37931
| 36
| 0.517895
|
dvychen
|
f9ae681db932c4f65d2bcb5c44b2c836a725e6d8
| 3,528
|
cpp
|
C++
|
Spark/ResourceFactory.cpp
|
MickAlmighty/SparkRenderer
|
0e30e342c7cf4003da54e9ce191fead647a868eb
|
[
"MIT"
] | 1
|
2022-02-15T19:50:01.000Z
|
2022-02-15T19:50:01.000Z
|
Spark/ResourceFactory.cpp
|
MickAlmighty/SparkRenderer
|
0e30e342c7cf4003da54e9ce191fead647a868eb
|
[
"MIT"
] | null | null | null |
Spark/ResourceFactory.cpp
|
MickAlmighty/SparkRenderer
|
0e30e342c7cf4003da54e9ce191fead647a868eb
|
[
"MIT"
] | null | null | null |
#include "ResourceFactory.h"
#include "Resource.h"
#include "ResourceIdentifier.h"
#include "ResourceLoader.h"
#include "Shader.h"
namespace spark::resourceManagement
{
std::map<std::string, std::function<std::shared_ptr<Resource>(const std::shared_ptr<ResourceIdentifier>& ri)>>
ResourceFactory::resourceCreationFunctions{
// TODO: replace with a reflection-based list
{".obj", [](const std::shared_ptr<ResourceIdentifier>& ri) { return ResourceLoader::createModel(ri); }},
{".fbx", [](const std::shared_ptr<ResourceIdentifier>& ri) { return ResourceLoader::createModel(ri); }},
{".gltf", [](const std::shared_ptr<ResourceIdentifier>& ri) { return ResourceLoader::createModel(ri); }},
{".dds", [](const std::shared_ptr<ResourceIdentifier>& ri) { return ResourceLoader::createCompressedTexture(ri); }},
{".ktx", [](const std::shared_ptr<ResourceIdentifier>& ri) { return ResourceLoader::createCompressedTexture(ri); }},
{".png", [](const std::shared_ptr<ResourceIdentifier>& ri) { return ResourceLoader::createUncompressedTexture(ri); }},
{".jpg", [](const std::shared_ptr<ResourceIdentifier>& ri) { return ResourceLoader::createUncompressedTexture(ri); }},
{".tga", [](const std::shared_ptr<ResourceIdentifier>& ri) { return ResourceLoader::createUncompressedTexture(ri); }},
{".hdr", [](const std::shared_ptr<ResourceIdentifier>& ri) { return ResourceLoader::createHdrTexture(ri); }},
{".glsl", [](const std::shared_ptr<ResourceIdentifier>& ri) { return std::make_shared<resources::Shader>(ri->getFullPath()); }},
{".scene", [](const std::shared_ptr<ResourceIdentifier>& ri) { return ResourceLoader::createScene(ri); }},
};
std::shared_ptr<Resource> ResourceFactory::loadResource(const std::shared_ptr<ResourceIdentifier>& resourceIdentifier)
{
const auto it = resourceCreationFunctions.find(extensionToLowerCase(resourceIdentifier->getRelativePath().string()));
if(it != resourceCreationFunctions.end())
{
const auto [extension, resourceCreationFunction] = *it;
return resourceCreationFunction(resourceIdentifier);
}
return nullptr;
}
bool ResourceFactory::isExtensionSupported(const std::filesystem::path& filePath)
{
return resourceCreationFunctions.find(extensionToLowerCase(filePath)) != resourceCreationFunctions.end();
}
std::string ResourceFactory::extensionToLowerCase(const std::filesystem::path& path)
{
std::string ext = path.extension().string();
std::for_each(ext.begin(), ext.end(), [](char& c) { c = static_cast<char>(std::tolower(c)); });
return ext;
}
std::vector<std::string> ResourceFactory::supportedModelExtensions()
{
return std::vector<std::string>{".obj", ".fbx", ".gltf"};
}
std::vector<std::string> ResourceFactory::supportedTextureExtensions()
{
return std::vector<std::string>{".dds", ".ktx", ".png", ".jpg", ".tga", ".hdr"};
}
std::vector<std::string> ResourceFactory::supportedShaderExtensions()
{
return std::vector<std::string>{".glsl"};
}
std::vector<std::string> ResourceFactory::supportedSceneExtensions()
{
return std::vector<std::string>{".scene"};
}
std::vector<std::string> ResourceFactory::supportedExtensions()
{
std::vector<std::string> all;
all.reserve(resourceCreationFunctions.size());
for(const auto& [supportedExtension, resourceLoader] : resourceCreationFunctions)
{
all.push_back(supportedExtension);
}
return all;
}
} // namespace spark::resourceManagement
| 42.506024
| 136
| 0.702381
|
MickAlmighty
|
f9b01bd81fa4407f38711e48c245b09ce246b474
| 165
|
cc
|
C++
|
firstCubes.cc
|
TheSaltimbanqi/FOPR
|
8ff4fb40f0ee3ba90bbbccc9565279bed6e22400
|
[
"MIT"
] | null | null | null |
firstCubes.cc
|
TheSaltimbanqi/FOPR
|
8ff4fb40f0ee3ba90bbbccc9565279bed6e22400
|
[
"MIT"
] | null | null | null |
firstCubes.cc
|
TheSaltimbanqi/FOPR
|
8ff4fb40f0ee3ba90bbbccc9565279bed6e22400
|
[
"MIT"
] | null | null | null |
#include <iostream>
int main()
{
int n=0;
std::cin >> n;
for(int i=0;i<n;++i)
{
std::cout << i*i*i << ',';
}
std::cout << n*n*n<<'\n';
return 0;
}
| 12.692308
| 30
| 0.442424
|
TheSaltimbanqi
|
f9b5f0d0f4fca35fe6b26b6dd336d81ee6c49290
| 2,526
|
cpp
|
C++
|
tests/testThreadsafeQueue.cpp
|
ToniRV/threadsafe_queue
|
a1cdc880baffe08656abe14d09576c57cc7ce910
|
[
"MIT"
] | 1
|
2019-01-13T14:58:03.000Z
|
2019-01-13T14:58:03.000Z
|
tests/testThreadsafeQueue.cpp
|
ToniRV/threadsafe_queue
|
a1cdc880baffe08656abe14d09576c57cc7ce910
|
[
"MIT"
] | null | null | null |
tests/testThreadsafeQueue.cpp
|
ToniRV/threadsafe_queue
|
a1cdc880baffe08656abe14d09576c57cc7ce910
|
[
"MIT"
] | null | null | null |
#include "gtest/gtest.h"
#include <chrono>
#include <string>
#include <iostream>
#include <thread>
#include "ThreadsafeQueue.h"
void consumer(ThreadsafeQueue<std::string>& q,
const std::atomic_bool& kill_switch) {
while (!kill_switch) {
std::string msg = "No msg!";
if (q.popBlocking(msg)) {
std::cout << "Got msg: " << msg << '\n';
}
}
q.shutdown();
}
void producer(ThreadsafeQueue<std::string>& q,
const std::atomic_bool& kill_switch) {
while (!kill_switch) {
std::this_thread::sleep_for(std::chrono::milliseconds(200));
q.push("Hello World!");
}
q.shutdown();
}
/* ************************************************************************* */
TEST(ThreadsafeQueue, popBlocking_by_reference) {
ThreadsafeQueue<std::string> q;
std::thread p ([&] {
q.push("Hello World!");
q.push("Hello World 2!");
});
std::string s;
q.popBlocking(s);
EXPECT_EQ(s, "Hello World!");
q.popBlocking(s);
EXPECT_EQ(s, "Hello World 2!");
q.shutdown();
EXPECT_EQ(q.popBlocking(s), false);
EXPECT_EQ(s, "Hello World 2!");
// Leave some time for p to finish its work.
std::this_thread::sleep_for(std::chrono::milliseconds(100));
EXPECT_TRUE(p.joinable());
p.join();
}
TEST(ThreadsafeQueue, popBlocking_by_shared_ptr) {
ThreadsafeQueue<std::string> q;
std::thread p ([&] {
q.push("Hello World!");
q.push("Hello World 2!");
});
std::shared_ptr<std::string> s = q.popBlocking();
EXPECT_EQ(*s, "Hello World!");
auto s2 = q.popBlocking();
EXPECT_EQ(*s2, "Hello World 2!");
q.shutdown();
EXPECT_EQ(q.popBlocking(), nullptr);
// Leave some time for p to finish its work.
std::this_thread::sleep_for(std::chrono::milliseconds(100));
EXPECT_TRUE(p.joinable());
p.join();
}
/* ************************************************************************* */
TEST(ThreadsafeQueue, producer_consumer) {
ThreadsafeQueue<std::string> q;
std::atomic_bool kill_switch (false);
std::thread c (consumer, std::ref(q), std::ref(kill_switch));
std::thread p (producer, std::ref(q), std::ref(kill_switch));
std::this_thread::sleep_for(std::chrono::milliseconds(200));
std::cout << "Shutdown queue.\n";
q.shutdown();
std::this_thread::sleep_for(std::chrono::milliseconds(200));
std::cout << "Resume queue.\n";
q.resume();
std::this_thread::sleep_for(std::chrono::milliseconds(200));
std::cout << "Joining threads.\n";
kill_switch = true;
c.join();
p.join();
std::cout << "Threads joined.\n";
}
| 26.3125
| 79
| 0.603721
|
ToniRV
|
f9bfd8fa90d216e76e878725f4562e982bf09543
| 11,314
|
cpp
|
C++
|
Modules/LogicServerMultipleClient/muliple_yslim.cpp
|
alanzw/FGCG
|
9819ff9c543cf52bfac16655d1d30417291b5d4c
|
[
"Apache-2.0"
] | 13
|
2016-10-24T11:39:12.000Z
|
2021-04-11T13:24:05.000Z
|
Modules/LogicServerMultipleClient/muliple_yslim.cpp
|
zhangq49/sharerender
|
9819ff9c543cf52bfac16655d1d30417291b5d4c
|
[
"Apache-2.0"
] | 1
|
2017-07-28T06:29:00.000Z
|
2017-07-28T06:29:00.000Z
|
Modules/LogicServerMultipleClient/muliple_yslim.cpp
|
zhangq49/sharerender
|
9819ff9c543cf52bfac16655d1d30417291b5d4c
|
[
"Apache-2.0"
] | 4
|
2018-06-05T03:39:06.000Z
|
2020-06-06T04:44:20.000Z
|
#include "muliple_yslim.h"
#include <assert.h>
#include <stdlib.h>
#define eps (1e-3)
#define Bound_Constraint 1e14
#include <time.h>
YSlim::YSlim() {
vertices.clear();
faces.clear();
quadrics.clear();
pack_vertex_time_ = 0;
decimate_time_ = 0;
vert_cnt_ = -1;
while(!errors.empty()) errors.pop();
}
YSlim::~YSlim() {
}
int YSlim::get_face_num() {
return faces.size();
}
int YSlim::get_vert_num() {
if(vert_cnt_ == -1)
return vertices.size();
else
return vert_cnt_;
}
inline double YSlim::distance(Vertex v1, Vertex v2) {
return sqrt( pow(v1.x - v2.x, 2) + pow(v1.y - v2.y, 2) + pow(v1.z - v2.z, 2) );
}
inline double YSlim::vertex_error(Matrix q, double x, double y, double z) {
return q[0]*x*x + 2*q[1]*x*y + 2*q[2]*x*z + 2*q[3]*x + q[5]*y*y
+ 2*q[6]*y*z + 2*q[7]*y + q[10]*z*z + 2*q[11]*z + q[15];
}
void YSlim::init_quadrics() {
quadrics.clear();
for(int i=0; i<vertices.size(); ++i) {
quadrics.insert( make_pair(i, Matrix(0.0)) );
}
for(it=ed_faces_mp_.begin(); it!=ed_faces_mp_.end(); ++it) {
if(it->second == -1) continue;
int v1 = it->first.first;
int v2 = it->first.second;
quadrics[v1] += Matrix(Bound_Constraint);
quadrics[v2] += Matrix(Bound_Constraint);
}
for(int i=0; i<faces.size(); ++i) {
for(int j=0; j<3; ++j) {
if(faces[i].id_vertex[j] >= vertices.size()) continue;
quadrics[ faces[i].id_vertex[j] ] += Matrix(faces[i].plane);
}
}
}
void YSlim::add_error(int v1, int v2) {
if(v1 >= vertices.size() || v2 >= vertices.size()) return;
if(is_border(v1, v2)) return;
errors.push( Error(v1, v2, calculate_error(v1, v2)) );
adj[v1].push_back(v2);
adj[v2].push_back(v1);
}
//use for boundaries constrain
void YSlim::add_edge_face(int v1, int v2, int f) {
if(v1 > v2) swap(v1, v2);
it = ed_faces_mp_.find(make_pair(v1, v2));
if(it == ed_faces_mp_.end()) {
ed_faces_mp_.insert(make_pair(make_pair(v1, v2), f));
}
else {
it->second = -1;
}
}
void YSlim::init_border() {
ed_faces_mp_.clear();
for(int i=0; i<faces.size(); ++i) {
add_edge_face(faces[i].id_vertex[0], faces[i].id_vertex[1], i);
add_edge_face(faces[i].id_vertex[0], faces[i].id_vertex[2], i);
add_edge_face(faces[i].id_vertex[1], faces[i].id_vertex[2], i);
}
}
bool YSlim::is_border(int v1, int v2) {
if(v1 > v2) swap(v1, v2);
it = ed_faces_mp_.find(make_pair(v1, v2));
if(it != ed_faces_mp_.end() && it->second != -1) {
return true;
}
else
return false;
}
void YSlim::select_pair() {
for(int i=0; i<adj.size(); ++i) {
adj[i].clear();
}
adj.clear();
vector<int> line;
for(int i=0; i<vertices.size(); ++i) {
adj.push_back(line);
}
while(!errors.empty()) errors.pop();
for(int i=0; i<faces.size(); ++i) {
add_error(faces[i].id_vertex[0], faces[i].id_vertex[1]);
add_error(faces[i].id_vertex[0], faces[i].id_vertex[2]);
add_error(faces[i].id_vertex[1], faces[i].id_vertex[2]);
}
}
double YSlim::calculate_error(int id_v1, int id_v2, double* vx/* =0 */, double* vy/* =0 */, double* vz/* =0 */) {
double min_error;
Matrix q_bar;
Matrix q_delta;
bool isReturnVertex = true;
if (vx == NULL) { vx = new double; isReturnVertex = false; }
if (vy == NULL) { vy = new double; }
if (vz == NULL) { vz = new double; }
/* computer quadric of virtual vertex vf */
q_bar = quadrics[id_v1] + quadrics[id_v2];
/* test if q_bar is symmetric */
if (q_bar[1] != q_bar[4] || q_bar[2] != q_bar[8] || q_bar[6] != q_bar[9] ||
q_bar[3] != q_bar[12] || q_bar[7] != q_bar[13] || q_bar[11] != q_bar[14])
{
fprintf(stderr, "ERROR: Matrix q_bar is not symmetric!\nid_v1 = %d, id_v2 = %d\n", id_v1, id_v2);
//system("PAUSE");
exit(-3);
}
double vx1 = vertices[id_v1].x;
double vy1 = vertices[id_v1].y;
double vz1 = vertices[id_v1].z;
double vx2 = vertices[id_v2].x;
double vy2 = vertices[id_v2].y;
double vz2 = vertices[id_v2].z;
double vx3 = double (vx1+vx2)/2;
double vy3 = double (vy1+vy2)/2;
double vz3 = double (vz1+vz2)/2;
double error1 = vertex_error(q_bar, vx1, vy1, vz1);
double error2 = vertex_error(q_bar, vx2, vy2, vz2);
double error3 = vertex_error(q_bar, vx3, vy3, vz3);
min_error = min(error1, error2);
//min_error = std::min(error1, std::min(error2, error3));
if (error1 == min_error) { *vx = vx1; *vy = vy1, *vz = vz1; }
if (error2 == min_error) { *vx = vx2; *vy = vy2, *vz = vz2; }
//if (error3 == min_error) { *vx = vx3; *vy = vy3, *vz = vz3; }
min_error = vertex_error(q_bar, *vx, *vy, *vz);
if (isReturnVertex == false) { delete vx; delete vy; delete vz; }
return min_error;
}
/*
* pass: second pass at a Simple Mesh Format SMF file
* that gets all the data.
*
* file - (fopen'd) file descriptor
*/
void YSlim::parse(FILE* file) {
char ch;
char buf[1024];
Vertex v;
Face f;
int local_num_vertices = 0;
double x0, y0, z0; //ax + by + cz = 0
double x1, y1, z1;
double x2, y2, z2;
double a, b, c, M;
while(fscanf(file, "%c", &ch) != EOF) {
switch(ch) {
case ' ' : /* blanks */
case '\t':
case '\n':
continue;
case '#':
fgets(buf, sizeof(buf), file);
break;
case 'v':
case 'V':
local_num_vertices++; //vertex index start from 0
fscanf(file, "%lf %lf %lf", &v.x, &v.y, &v.z);
v.id = local_num_vertices-1;
vertices.push_back(v);
break;
case 'f':
case 'F':
fscanf(file, "%d %d %d", &f.id_vertex[0], &f.id_vertex[1], &f.id_vertex[2]);
f.id_vertex[0]--;
f.id_vertex[1]--;
f.id_vertex[2]--;
x0 = vertices[f.id_vertex[0]].x;
y0 = vertices[f.id_vertex[0]].y;
z0 = vertices[f.id_vertex[0]].z;
x1 = vertices[f.id_vertex[1]].x;
y1 = vertices[f.id_vertex[1]].y;
z1 = vertices[f.id_vertex[1]].z;
x2 = vertices[f.id_vertex[2]].x;
y2 = vertices[f.id_vertex[2]].y;
z2 = vertices[f.id_vertex[2]].z;
a = (y1-y0)*(z2-z0) - (z1-z0)*(y2-y0); /* a1*b2 - a2*b1; */
b = (z1-z0)*(x2-x0) - (x1-x0)*(z2-z0); /* a2*b0 - a0*b2; */
c = (x1-x0)*(y2-y0) - (y1-y0)*(x2-x0); /* a0*b1 - a1*b0; */
M = sqrt(a*a + b*b + c*c + 0.01);
a = a/M;
b = b/M;
c = c/M;
f.plane[0] = a;
f.plane[1] = b;
f.plane[2] = c;
f.plane[3] = -1*(a*x0 + b*y0 + c*z0); /* -1*(a*x + b*y + c*z); */
faces.push_back(f);
break;
default:
fgets(buf, sizeof(buf), file);
fprintf(stderr, "Parse() failed: invalid attributes: \"%c\".\n", ch);
exit(-2);
}
}
}
void YSlim::read_smf(char* filename) {
FILE* file;
if( (file = fopen(filename, "r")) == NULL ) {
fprintf(stderr, "read_smf() failed: can't open data file \"%s\".\n", filename);
exit(-1);
}
parse(file);
printf("vertex %d, face %d\n", vertices.size(), faces.size());
fclose(file);
}
void YSlim::write_smf(char* filename) {
FILE* file;
if ((file = fopen(filename, "w")) == NULL)
{
fprintf(stderr, "write_pm() failed: can't write data file \"%s\".\n", filename);
//system("PAUSE");
exit(-1);
}
int vert_cnt = 0;
for(int i=0; i<vertices.size(); ++i) {
if(find(i) == i) vert_cnt++;
}
/* print header info */
fprintf(file, "#$PM 0.1\n");
fprintf(file, "#$vertices %d\n", vert_cnt);
fprintf(file, "#$faces %d\n", f_cnt[faces.size()-1]);
fprintf(file, "#\n");
/* print vertices */
int ii = 1;
std::map<int, int> imap;
for(int i=0; i<vertices.size(); ++i) {
if(find(i) != i) continue;
fprintf(file, "v %lf %lf %lf\n", vertices[i].x, vertices[i].y, vertices[i].z);
imap.insert( std::map<int, int>::value_type(i, ii++) );
}
/* print faces */
int v1, v2, v3;
for (int i = 0; i < static_cast<int>(faces.size()); i++)
{
v1 = imap[ find(faces[i].id_vertex[0]) ];
v2 = imap[ find(faces[i].id_vertex[1]) ];
v3 = imap[ find(faces[i].id_vertex[2]) ];
if(v1 == v2 || v1 == v3 || v2 == v3) continue;
/*
v1 = faces[i].id_vertex[0];
v2 = faces[i].id_vertex[1];
v3 = faces[i].id_vertex[2];
*/
fprintf(file, "f %d %d %d\n", v1, v2, v3);
}
fprintf(file, "\n");
/* close the file */
fclose(file);
}
int YSlim::find(int x) {
if(x >= vertices.size()) return INT_MAX;
if(p_[x] == x) return x;
else return p_[x] = find(p_[x]);
}
bool YSlim::is_merged(int u, int v) {
return find(u) == find(v);
}
bool cmp_idx(Vertex& A, Vertex& B) {
return A.x < B.x || (A.x == B.x && A.y < B.y) || (A.x == B.x && A.y == B.y && A.z < B.z);
}
void YSlim::pack_vertex() {
p_.clear();
idx_.clear();
int t1 = clock();
for(int i=0; i<vertices.size(); ++i) {
p_.push_back(i);
idx_.push_back(vertices[i]);
}
sort(idx_.begin(), idx_.end(), cmp_idx);
//printf("%d\n", vertices.size());
for(int i=0; i<idx_.size(); ++i) {
for(int j=i+1; j<idx_.size(); ++j) {
if(distance(vertices[i], vertices[j]) < eps) {
//printf("%d %d %.4lf\n", i, j, distance(vertices[i], vertices[j]));
if(is_border(i, j)) continue;
int u = find(idx_[i].id), v = find(idx_[j].id);
p_[u] = v;
}
if(fabs(idx_[i].x - idx_[j].x) > eps || fabs(idx_[i].y - idx_[j].y) > eps || fabs(idx_[i].z - idx_[j].z) > eps) break;
}
}
for(int i=0; i<faces.size(); ++i) {
faces[i].id_vertex[0] = find(faces[i].id_vertex[0]);
faces[i].id_vertex[1] = find(faces[i].id_vertex[1]);
faces[i].id_vertex[2] = find(faces[i].id_vertex[2]);
}
int t2 = clock();
pack_vertex_time_ = t2 - t1;
//Log::log("vc: %d, fc: %d\n", get_vert_num(), get_face_num());
//Log::log("pack vertex: %d ms\n", t2 - t1);
}
void YSlim::decimate(int target_num_vert) {
init_border();
pack_vertex();
int t1 = clock();
init_quadrics();
select_pair();
int id_v1, id_v2;
double vx, vy, vz;
vert_cnt_ = 0;
for(int i=0; i<vertices.size(); ++i) {
if(find(i) == i) vert_cnt_++;
}
while(vert_cnt_ > target_num_vert) {
//assert(!errors.empty());
//assert(false);
if(errors.empty()) break;
Error nd = errors.top();
errors.pop();
if(is_merged(nd.u_, nd.v_)) continue;
if(nd.error_ > Bound_Constraint * 3) continue;
id_v1 = find(nd.u_);
id_v2 = find(nd.v_);
if(id_v1 >= vertices.size() || id_v2 >= vertices.size())continue;
if(id_v1 != nd.u_ || id_v2 != nd.v_) continue;
//merge the smaller set to the bigger set
//make id_v1 the bigger one
if(adj[id_v1].size() < adj[id_v2].size())
swap(id_v1, id_v2);
//update quadric of v1
quadrics[id_v1] = quadrics[id_v1] + quadrics[id_v2];
//merge the errors of id_v2 to id_v1
while(adj[id_v2].size() > 0) {
int x = adj[id_v2].back();
if(find(x) == x && x != id_v2)
add_error(x, id_v1);
adj[id_v2].pop_back();
}
//printf("merging %d %d\n", id_v1, id_v2);
//merge the point of id_v2 to id_v1
p_[id_v2] = p_[id_v1];
//decrease the vertex count
vert_cnt_--;
}
update_faces();
int t2 = clock();
decimate_time_ = t2 - t1;
//Log::log("decimate: %d ms\n", t2 - t1);
}
void YSlim::update_faces() {
int v1, v2, v3;
f_cnt.resize(faces.size());
for (int i = 0; i < static_cast<int>(faces.size()); i++)
{
v1 = find(faces[i].id_vertex[0]);
v2 = find(faces[i].id_vertex[1]);
v3 = find(faces[i].id_vertex[2]);
faces[i].id_vertex[0] = v1;
faces[i].id_vertex[1] = v2;
faces[i].id_vertex[2] = v3;
if(v1 == v2 || v1 == v3 || v2 == v3) {
//delete this face
//assert(false);
/*
swap(faces[i], faces.back());
faces.pop_back();
i--;
*/
if(i == 0) f_cnt[i] = 0;
else f_cnt[i] = f_cnt[i-1];
}
else {
if(i == 0) f_cnt[i] = 1;
else f_cnt[i] = f_cnt[i-1] + 1;
}
}
}
| 22.582834
| 121
| 0.582287
|
alanzw
|
f9c24aa44976e2d68d17cb76eb00ff41c92d8af3
| 1,220
|
hxx
|
C++
|
src/control/genai/c_avoid_edge.hxx
|
AltSysrq/Abendstern
|
106e1ad2457f7bfd90080eecf49a33f6079f8e1e
|
[
"BSD-3-Clause"
] | null | null | null |
src/control/genai/c_avoid_edge.hxx
|
AltSysrq/Abendstern
|
106e1ad2457f7bfd90080eecf49a33f6079f8e1e
|
[
"BSD-3-Clause"
] | null | null | null |
src/control/genai/c_avoid_edge.hxx
|
AltSysrq/Abendstern
|
106e1ad2457f7bfd90080eecf49a33f6079f8e1e
|
[
"BSD-3-Clause"
] | 1
|
2022-01-29T11:54:41.000Z
|
2022-01-29T11:54:41.000Z
|
/**
* @file
* @author Jason Lingle
* @brief Contains the AvoidEdgeCortex reflex
*/
/*
* c_avoid_edge.hxx
*
* Created on: 01.11.2011
* Author: jason
*/
#ifndef C_AVOID_EDGE_HXX_
#define C_AVOID_EDGE_HXX_
#include "ci_nil.hxx"
#include "ci_field.hxx"
#include "ci_self.hxx"
#include "cortex.hxx"
/**
* The AvoidEdgeCortex is a reflex which attempts to avoid flying off
* the edge of the map.
*/
class AvoidEdgeCortex: public Cortex, private
cortex_input::Self
<cortex_input::Field
<cortex_input::Nil> > {
Ship* ship;
float score;
enum Outputs { throttle=0, accel, brake, spin };
static const unsigned numOutputs = 1+(unsigned)spin;
public:
typedef cip_input_map input_map;
/**
* Constructs a new AvoidEdgeCortex
* @param species The root of the species to read from
* @param s The ship to operate on
* @param ss The SelfSource to use
*/
AvoidEdgeCortex(const libconfig::Setting& species, Ship* s, cortex_input::SelfSource* ss);
/**
* Controls the ship and updates the score, given the elapsed time.
*/
void evaluate(float);
/**
* Returns the score of the Cortex.
*/
float getScore() const { return score; }
};
#endif /* C_AVOID_EDGE_HXX_ */
| 20.333333
| 92
| 0.686885
|
AltSysrq
|
f9d1353c35718f2f0dd430c1cf0f445477f01684
| 544
|
cpp
|
C++
|
ModelClasses/FlyObjects/UsefulClassesForLA/angle.cpp
|
Yegres5/diploma
|
eea15d195cd1b8dfe16bd6810f012af435416cb7
|
[
"MIT"
] | 3
|
2019-12-18T07:11:54.000Z
|
2021-01-12T08:26:59.000Z
|
ModelClasses/FlyObjects/UsefulClassesForLA/angle.cpp
|
Yegres5/diploma
|
eea15d195cd1b8dfe16bd6810f012af435416cb7
|
[
"MIT"
] | null | null | null |
ModelClasses/FlyObjects/UsefulClassesForLA/angle.cpp
|
Yegres5/diploma
|
eea15d195cd1b8dfe16bd6810f012af435416cb7
|
[
"MIT"
] | null | null | null |
#include "angle.h"
#include "QtMath"
Angle::Angle(double value):check(true),value(value)
{}
void Angle::incValue(const double incVal)
{
value += incVal;
if (check){
while(value>=M_PI*2)
value -= M_PI*2;
while(value<0)
value += M_PI*2;
}
}
double Angle::getValue() const
{
return value;
}
Angle Angle::operator=(const double eqVal)
{
value = eqVal;
return *this;
}
Angle &Angle::operator+=(const double incVal)
{
this->incValue(incVal);
return *this;
}
| 16.484848
| 52
| 0.580882
|
Yegres5
|
f9da0fb8ae1c74729ac133c1f604e03de6ae945d
| 707
|
hpp
|
C++
|
IComponent.hpp
|
rectoria/2017_NanoTekSpice
|
793ba675dba90a7e05cfe8946c12e62aa2c17ba2
|
[
"MIT"
] | null | null | null |
IComponent.hpp
|
rectoria/2017_NanoTekSpice
|
793ba675dba90a7e05cfe8946c12e62aa2c17ba2
|
[
"MIT"
] | null | null | null |
IComponent.hpp
|
rectoria/2017_NanoTekSpice
|
793ba675dba90a7e05cfe8946c12e62aa2c17ba2
|
[
"MIT"
] | null | null | null |
/*
** EPITECH PROJECT, 2018
** IComponent
** File description:
** oui
*/
#pragma once
#include <iostream>
#include <string>
namespace nts
{
enum Tristate {
UNDEFINED = (-true),
TRUE = true,
FALSE = false
};
enum C_TYPE {
C_INPUT,
C_OUTPUT,
C_CLOCK,
C_TRUE,
C_FALSE,
C_4001,
C_4008,
C_4011,
C_4030,
C_4040,
C_4069,
C_4071,
C_4081,
C_4514,
};
class IComponent
{
public:
virtual ~IComponent() = default;
virtual nts::Tristate compute(std::size_t = 1) = 0;
virtual void setLink(std::size_t, nts::IComponent &,
std::size_t) = 0;
virtual Tristate &getPin(std::size_t) = 0;
virtual void dump() const = 0;
virtual C_TYPE getType() = 0;
};
}
| 13.596154
| 55
| 0.625177
|
rectoria
|
f9da8676ba30e05629c961544707aa60b70865e2
| 1,760
|
cpp
|
C++
|
src/neuron_factory.cpp
|
mupimenov/ga4nn
|
94309212c941c75496b347b8667e3788ffb09455
|
[
"MIT"
] | null | null | null |
src/neuron_factory.cpp
|
mupimenov/ga4nn
|
94309212c941c75496b347b8667e3788ffb09455
|
[
"MIT"
] | null | null | null |
src/neuron_factory.cpp
|
mupimenov/ga4nn
|
94309212c941c75496b347b8667e3788ffb09455
|
[
"MIT"
] | null | null | null |
/*
COPYRIGHT (c) 2016 Mikhail Pimenov
MIT License
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 "neuron_factory.hpp"
namespace ga4nn {
input_neuron_factory::input_neuron_factory() {}
neuron::ptr input_neuron_factory::create_neuron() {
return neuron::ptr(new input_neuron);
}
sigmoid_neuron_factory::sigmoid_neuron_factory() {}
neuron::ptr sigmoid_neuron_factory::create_neuron() {
return neuron::ptr(new sigmoid_neuron);
}
linear_neuron_factory::linear_neuron_factory() {}
neuron::ptr linear_neuron_factory::create_neuron() {
return neuron::ptr(new linear_neuron);
}
feedback_neuron_factory::feedback_neuron_factory() : m_hystory_len(1) {}
neuron::ptr feedback_neuron_factory::create_neuron() {
return neuron::ptr(new feedback_neuron(m_hystory_len++));
}
}
| 36.666667
| 72
| 0.796023
|
mupimenov
|
f9db1d36e8681d880aa044ae6697d741d964db02
| 3,822
|
cpp
|
C++
|
source/AnimIK.cpp
|
xzrunner/model
|
e801f3cbfa0f5e7c190eec1e5286843f6cd68492
|
[
"MIT"
] | null | null | null |
source/AnimIK.cpp
|
xzrunner/model
|
e801f3cbfa0f5e7c190eec1e5286843f6cd68492
|
[
"MIT"
] | null | null | null |
source/AnimIK.cpp
|
xzrunner/model
|
e801f3cbfa0f5e7c190eec1e5286843f6cd68492
|
[
"MIT"
] | null | null | null |
#include "model/AnimIK.h"
#include "model/ModelInstance.h"
#include "model/SkeletalAnim.h"
#include "model/Model.h"
#include <SM_Matrix.h>
#include <SM_Calc.h>
namespace
{
sm::mat4 get_rot_inv(const sm::mat4& mat)
{
auto inv = mat;
inv.x[12] = inv.x[13] = inv.x[14] = 0;
return inv.Inverted();
}
}
namespace model
{
void AnimIK::OneBone(ModelInstance& model, int joint, const sm::vec3& target,
std::array<sm::vec3, 3>& debug_pos)
{
auto sk_anim = static_cast<SkeletalAnim*>(model.GetModel()->ext.get());
auto& bones = sk_anim->GetNodes();
int p = bones[joint]->parent;
if (p < 0) {
return;
}
int pp = bones[p]->parent;
if (pp < 0) {
return;
}
auto& g_trans = model.GetGlobalTrans();
auto p_pos = g_trans[p] * sm::vec3(0, 0, 0);
auto pp_inv = get_rot_inv(g_trans[pp]);
auto& tp_wtrans = sk_anim->GetTPWorldTrans();
auto u = (tp_wtrans[joint] * sm::vec3(0, 0, 0) - tp_wtrans[p] * sm::vec3(0, 0, 0)).Normalized();
auto v = (target - p_pos).Normalized();
debug_pos[0] = p_pos;
debug_pos[1] = p_pos + u;
debug_pos[2] = p_pos + v;
v = pp_inv * v;
model.SetJointRotate(p, sm::Quaternion::CreateFromVectors(u, v));
}
void AnimIK::TwoBones(ModelInstance& model, int joint, const sm::vec3& rot_axis,
const sm::vec3& target, std::array<sm::vec3, 3>& debug_pos)
{
auto sk_anim = static_cast<SkeletalAnim*>(model.GetModel()->ext.get());
auto& bones = sk_anim->GetNodes();
int p = bones[joint]->parent;
if (p < 0) {
return;
}
int pp = bones[p]->parent;
if (pp < 0) {
return;
}
int ppp = bones[pp]->parent;
if (ppp < 0) {
return;
}
auto& g_trans = model.GetGlobalTrans();
auto c_pos = g_trans[joint] * sm::vec3(0, 0, 0);
auto p_pos = g_trans[p] * sm::vec3(0, 0, 0);
auto pp_pos = g_trans[pp] * sm::vec3(0, 0, 0);
auto& tp_wtrans = sk_anim->GetTPWorldTrans();
float len0 = sm::dis_pos3_to_pos3(pp_pos, p_pos);
float len1 = sm::dis_pos3_to_pos3(p_pos, c_pos);
float tot_len = sm::dis_pos3_to_pos3(target, pp_pos);
if (tot_len < len0 + len1 && len0 < tot_len + len1 && len1 < tot_len + len0)
{
float ang0 = acosf((len0 * len0 + tot_len * tot_len - len1 * len1) / (2 * len0 * tot_len));
float ang1 = acosf((len1 * len1 + tot_len * tot_len - len0 * len0) / (2 * len1 * tot_len));
//model.SetJointRotate(pp, bones[pp]->local_trans, sm::Quaternion::CreateFromEulerAngle(-(angle - ang0), 0, 0));
//model.SetJointRotate(p, bones[p]->local_trans, sm::Quaternion::CreateFromEulerAngle(-(ang0 + ang1), 0, 0));
// auto rot_mat = sm::Quaternion::CreateFromAxisAngle(rot_axis, ang0);
auto rot_mat = sm::Quaternion::CreateFromAxisAngle({1, 0, 0}, ang0);
auto new_pos = sm::mat4(rot_mat) * ((target - pp_pos).Normalized() * len0) + pp_pos;
debug_pos[0] = pp_pos;
debug_pos[1] = new_pos;
debug_pos[2] = target;
{
sm::mat4 ppp_inv = get_rot_inv(g_trans[ppp]);
auto u = (tp_wtrans[p] * sm::vec3(0, 0, 0) - tp_wtrans[pp] * sm::vec3(0, 0, 0)).Normalized();
auto v = (new_pos - pp_pos).Normalized();
v = ppp_inv * v;
model.SetJointRotate(pp, sm::Quaternion::CreateFromVectors(u, v));
}
{
sm::mat4 pp_inv = get_rot_inv(g_trans[pp]);
auto u = (tp_wtrans[joint] * sm::vec3(0, 0, 0) - tp_wtrans[p] * sm::vec3(0, 0, 0)).Normalized();
auto v = (target - new_pos).Normalized();
v = pp_inv * v;
model.SetJointRotate(p, sm::Quaternion::CreateFromVectors(u, v));
}
}
else
{
sm::mat4 ppp_inv = get_rot_inv(g_trans[ppp]);
auto u = (tp_wtrans[joint] * sm::vec3(0, 0, 0) - tp_wtrans[pp] * sm::vec3(0, 0, 0)).Normalized();
auto v = (target - pp_pos).Normalized();
debug_pos[0] = pp_pos;
debug_pos[1] = pp_pos + u;
debug_pos[2] = target;
v = ppp_inv * v;
model.SetJointRotate(pp, sm::Quaternion::CreateFromVectors(u, v));
model.SetJointRotate(p, sm::Quaternion());
}
}
}
| 28.522388
| 114
| 0.636054
|
xzrunner
|
f9e67b8d7e767b7750cb6ae3199f6c01ffa85d8e
| 1,504
|
cpp
|
C++
|
project/src/data_types.cpp
|
GabrielLins64/Study_of_Cpp
|
80e519560d5f66f0188b2bbe3525e2a31357cc16
|
[
"MIT"
] | null | null | null |
project/src/data_types.cpp
|
GabrielLins64/Study_of_Cpp
|
80e519560d5f66f0188b2bbe3525e2a31357cc16
|
[
"MIT"
] | null | null | null |
project/src/data_types.cpp
|
GabrielLins64/Study_of_Cpp
|
80e519560d5f66f0188b2bbe3525e2a31357cc16
|
[
"MIT"
] | null | null | null |
#include <data_types.hpp>
template <typename T>
void showTypeInfo(const char* tp_name)
{
std::cout << "~~~~~~~~~ X ~~~~~~~~~ X ~~~~~~~~~" << std::endl;
std::cout << "Type: " << tp_name << std::endl;
std::cout << "Size of " << typeid(T).name() << ": " << sizeof(T) << " bytes" << std::endl;
std::cout << "Minimum value: " << std::numeric_limits<T>::min() << std::endl;
std::cout << "Maximum value: " << std::numeric_limits<T>::max() << std::endl;
std::cout << "Is signed: " << std::numeric_limits<T>::is_signed << std::endl;
std::cout << "Non-sign bits: " << std::numeric_limits<T>::digits << std::endl;
std::cout << "Has infinity: " << std::numeric_limits<T>::has_infinity << std::endl;
std::cout << "~~~~~~~~~ X ~~~~~~~~~ X ~~~~~~~~~" << std::endl;
}
void showTypes()
{
showTypeInfo<short int>("short int");
showTypeInfo<unsigned short int>("unsigned short int");
showTypeInfo<unsigned int>("unsigned int");
showTypeInfo<int>("int");
showTypeInfo<long int>("long int");
showTypeInfo<unsigned long int>("unsigned long int");
showTypeInfo<long long int>("long long int");
showTypeInfo<unsigned long long int>("unsigned long long int");
showTypeInfo<signed char>("signed char"); // Same as char
showTypeInfo<unsigned char>("unsigned char");
showTypeInfo<float>("float");
showTypeInfo<double>("double");
showTypeInfo<long double>("long double");
showTypeInfo<wchar_t>("wchar_t");
showTypeInfo<bool>("bool");
}
| 44.235294
| 94
| 0.603059
|
GabrielLins64
|
f9e6e5e746764bf9bf07076bae831e8bd4157b80
| 702
|
cpp
|
C++
|
projecteuler/2.cpp
|
itsjaysuthar/CPpractice
|
820cf84ea7079ef3b34a604fd56672811f64f4dc
|
[
"MIT"
] | null | null | null |
projecteuler/2.cpp
|
itsjaysuthar/CPpractice
|
820cf84ea7079ef3b34a604fd56672811f64f4dc
|
[
"MIT"
] | null | null | null |
projecteuler/2.cpp
|
itsjaysuthar/CPpractice
|
820cf84ea7079ef3b34a604fd56672811f64f4dc
|
[
"MIT"
] | null | null | null |
//---------------------------------------------------------------------------------------
//-------------------Author : itsjaysuthar ----------------------------------------------
//---------------------------------------------------------------------------------------
#include<bits/stdc++.h>
using namespace std;
int main()
{
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int num1=1, num2=2;
unsigned long sum=0,sum1=0;
while(sum<4000000)
{
sum=num1+num2;
if(sum%2==0)
{
sum1=sum1+sum;
}
num1=num2;
num2=sum;
}
cout<<sum1+2<<endl;
return 0;
}
| 22.645161
| 89
| 0.339031
|
itsjaysuthar
|
f9ef9bad4666c8500d428823d458369d20b118bd
| 776
|
cpp
|
C++
|
Engine/Src/SFCore/Object/SFObject.cpp
|
blue3k/StormForge
|
1557e699a673ae9adcc8f987868139f601ec0887
|
[
"Apache-2.0"
] | 1
|
2020-06-20T07:35:25.000Z
|
2020-06-20T07:35:25.000Z
|
Engine/Src/SFCore/Object/SFObject.cpp
|
blue3k/StormForge
|
1557e699a673ae9adcc8f987868139f601ec0887
|
[
"Apache-2.0"
] | null | null | null |
Engine/Src/SFCore/Object/SFObject.cpp
|
blue3k/StormForge
|
1557e699a673ae9adcc8f987868139f601ec0887
|
[
"Apache-2.0"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////
//
// CopyRight (c) 2016 Kyungkun Ko
//
// Author : KyungKun Ko
//
// Description : Shared pointer
//
////////////////////////////////////////////////////////////////////////////////
#include "SFCorePCH.h"
#include "SFTypedefs.h"
#include "Object/SFObject.h"
#include "Object/SFObjectManager.h"
#include "Service/SFService.h"
#include "SFAssert.h"
namespace SF {
template class SharedPointerT<Object>;
////////////////////////////////////////////////////////////////
//
// base object
//
Object::Object(IHeap* heap, const StringCrc64& name)
: m_Name(name)
, m_Heap(heap)
{
if (m_Heap == nullptr)
{
m_Heap = GetEngineHeapPtr();
}
}
Object::~Object()
{
}
}
| 15.836735
| 80
| 0.456186
|
blue3k
|
f9f35cbcea9379357cac7d517b4b2c88afc4368a
| 256
|
cpp
|
C++
|
ch11/copy3.cpp
|
bashell/CppStandardLibrary
|
2aae03019288132c911036aeb9ba36edc56e510b
|
[
"MIT"
] | null | null | null |
ch11/copy3.cpp
|
bashell/CppStandardLibrary
|
2aae03019288132c911036aeb9ba36edc56e510b
|
[
"MIT"
] | null | null | null |
ch11/copy3.cpp
|
bashell/CppStandardLibrary
|
2aae03019288132c911036aeb9ba36edc56e510b
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
copy(istream_iterator<string>(cin),
istream_iterator<string>(),
ostream_iterator<string>(cout, "\n"));
return 0;
}
| 17.066667
| 47
| 0.65625
|
bashell
|
f9f768cdb16235f7a64f13326b95209ea44bb130
| 50,796
|
cpp
|
C++
|
mcgs.cpp
|
lstange/mcgs
|
bfce487095c42b3a8c54c8e10aebcd2189a02c62
|
[
"MIT"
] | 1
|
2017-04-21T22:53:08.000Z
|
2017-04-21T22:53:08.000Z
|
mcgs.cpp
|
lstange/mcgs
|
bfce487095c42b3a8c54c8e10aebcd2189a02c62
|
[
"MIT"
] | null | null | null |
mcgs.cpp
|
lstange/mcgs
|
bfce487095c42b3a8c54c8e10aebcd2189a02c62
|
[
"MIT"
] | 1
|
2021-01-11T04:03:42.000Z
|
2021-01-11T04:03:42.000Z
|
/* mcgs.cpp
Monte-Carlo simulation of group sizes under bivariate (possibly contaminated) normal distribution
Requirements:
sudo apt-get install libboost-all-dev
Building:
g++ -O3 -Wall -Wextra -std=c++11 -march=native -g -o mcgs mcgs.cpp
*/
#include <vector>
#include <map>
#include <cmath>
#include <numeric>
#include <complex>
#include <random>
#include <iostream>
#include <memory>
#include <stdlib.h>
#include <algorithm>
#include <boost/math/distributions/chi_squared.hpp>
// Abstract base class (interface) for random shot group generator, implementations follow
class RandomNumberGenerator {
public:
virtual void advance() = 0;
virtual void reset() = 0;
virtual std::complex<double> point(unsigned dimension) = 0;
};
//
// Baseline pseudorandom number generator, wraps the default provided by standard library
//
class DefaultRandomNumberGenerator : public RandomNumberGenerator {
std::default_random_engine gen_;
std::normal_distribution<double> dist_;
public:
DefaultRandomNumberGenerator()
{
reset();
}
void advance() {}
void reset()
{
gen_.seed(42);
}
std::complex<double> point(unsigned dimension __attribute__((unused)))
{
return std::complex<double>(dist_(gen_), dist_(gen_));
}
};
// MCG 128 from http://www.pcg-random.org/posts/on-vignas-pcg-critique.html
class FastRandomNumberGenerator : public RandomNumberGenerator {
__uint128_t state_;
public:
FastRandomNumberGenerator()
{
reset();
}
void advance() {}
void reset()
{
state_ = 1; // can be seeded to any odd number
}
std::complex<double> point(unsigned dimension __attribute__((unused)))
{
for (;;) {
double u = ldexp(next(), -64);
double v = ldexp(next(), -64);
// Box-Muller transform
double r = sqrt(-2 * log(u));
double x = r * cos(2 * M_PI * v);
double y = r * sin(2 * M_PI * v);
if (isfinite(x) && isfinite(y)) {
return std::complex<double>(x, y);
}
}
}
private:
inline uint64_t next()
{
return (state_ *= 0xda942042e4dd58b5ULL) >> 64;
}
};
//
// Additive quasi-random generator
//
// To get the next point, add a fixed step modulo 1 to the previous point.
//
class AdditiveRandomNumberGenerator: public RandomNumberGenerator {
std::vector<double> x_;
std::vector<double> step_;
public:
explicit AdditiveRandomNumberGenerator(unsigned dimensions)
#if 0
// Use square roots of prime numbers as steps because they are irrational.
{
unsigned nprimes = dimensions * 2; // Two coordinates for each point
x_.resize(nprimes);
step_.resize(nprimes);
//
// To initialize the steps, we need to find some prime numbers. Do that with
// sieve of Eratosthenes.
//
// To estimate how big the sieve should be to get nprimes primes, start with
// approximation by Gauss and Legendre:
//
// nprimes = PrimePi(x) ~ x/log(x)
//
// Here PrimePi(x) is prime-counting function: number of prime numbers that are
// less than or equal to x. This is a lower bound for all but the lowest values
// of x (which we'll handle separately), so x will be slightly larger than strictly
// necessary.
//
// To solve for x without resorting to Lambert-W function, rewrite as follows:
//
// x ~ nprimes * log(x)
//
// Now use fixed point iteration to find x. Stop iterating when the whole part
// of x stops changing.
//
unsigned sieve_size = 0;
if (nprimes < 5) { // Approximation breaks below 5, floor sieve_size
sieve_size = 7;
} else {
double x = nprimes;
for (unsigned i = 0; i < 30; i++) {
unsigned before = (unsigned)ceil(x);
x = nprimes * log(x); // Fixed point iteration
unsigned after = (unsigned)ceil(x);
if (before == after) {
sieve_size = before;
break;
}
}
if (sieve_size == 0) {
std::cerr << "Fixed point iteration failed to converge\n";
exit(-1);
}
}
// The sieve itself
std::vector<bool> prime(sieve_size + 1, true);
unsigned top = sqrt(sieve_size);
for (unsigned i = 2; i < top; i++) {
if (prime.at(i)) {
for(unsigned j = i * i; j <= sieve_size; j += i) {
prime.at(j) = false;
}
}
}
// Collect prime numbers left in the sieve, take square roots, assign to steps.
unsigned index = 0;
for (unsigned j = 2; index < nprimes; j++) {
if (j >= sieve_size) {
std::cerr << "Ran out of primes\n"; // Shouldn't happen if we did the math right
exit(-1);
}
if (prime[j]) {
step_.at(index++) = sqrt(j);
}
}
}
#else
// Rd quasi-random sequences http://extremelearning.com.au/unreasonable-effectiveness-of-quasirandom-sequences/
// In d dimensions, g is positive real root of f(x) = x ** (d + 1) - x - 1 = 0
// 3D example:
// g = 1.22074408460575947536
// a1 = 1.0/g
// a2 = 1.0/(g*g)
// a3 = 1.0/(g*g*g)
// x[n] = (0.5+a1*n) %1
// y[n] = (0.5+a2*n) %1
// z[n] = (0.5+a3*n) %1
{
unsigned d = dimensions * 2; // Two coordinates for each point
x_.resize(d);
step_.resize(d);
double x = 1.5; // initial approximation
for (unsigned i = 0; i < 30; i++) { // Newton-Raphson
double xd = 1;
for (unsigned j = 0; j < d; j++) {
xd *= x;
}
double adjustment = (xd * x - x - 1) / ((d + 1) * xd - 1);
x -= adjustment;
if (std::abs(adjustment) < 1E-16) {
break;
}
}
double a = 1.;
for (unsigned i = 0; i < d; i++) {
a /= x;
x_.at(i) = 0.5;
step_.at(i) = a;
}
}
#endif
void advance()
{
for (unsigned j = 0; j < step_.size(); j++) {
double int_part;
x_.at(j) = modf(x_.at(j) + step_.at(j), &int_part);
}
}
void reset()
{
for (unsigned j = 0; j < step_.size(); j++) {
x_.at(j) = 0;
}
}
std::complex<double> point(unsigned dimension)
{
double x, y;
if (dimension >= step_.size() / 2) {
x = y = std::numeric_limits<double>::quiet_NaN();
} else {
double u = x_.at(dimension);
double v = x_.at(dimension + step_.size() / 2);
// Box-Muller transform
double r = sqrt(-2 * log(u));
x = r * cos(2 * M_PI * v);
y = r * sin(2 * M_PI * v);
}
return std::complex<double>(x, y);
}
};
//
// Sobol quasi-random number generator
//
class SobolRandomNumberGenerator : public RandomNumberGenerator {
unsigned x_[20];
unsigned v_[20][32 + 1];
unsigned i_;
public:
explicit SobolRandomNumberGenerator(unsigned dimensions): i_(0)
{
// Primitive polynomials and initial direction numbers for the first 20 dimensions
// recommended by Stephen Joe and Frances Kuo in new-joe-kuo-6.21201
// http://web.maths.unsw.edu.au/~fkuo/sobol/index.html
const unsigned s[20] = {1, 2, 3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 7};
const unsigned a[20] = {0, 1, 1, 2, 1, 4, 2, 4, 7, 11, 13, 14, 1, 13, 16, 19, 22, 25, 1, 4};
const unsigned m[20][7] = {
{1, 0, 0, 0, 0, 0, 0},
{1, 3, 0, 0, 0, 0, 0},
{1, 3, 1, 0, 0, 0, 0},
{1, 1, 1, 0, 0, 0, 0},
{1, 1, 3, 3, 0, 0, 0},
{1, 3, 5, 13, 0, 0, 0},
{1, 1, 5, 5, 17, 0, 0},
{1, 1, 5, 5, 5, 0, 0},
{1, 1, 7, 11, 19, 0, 0},
{1, 1, 5, 1, 1, 0, 0},
{1, 1, 1, 3, 11, 0, 0},
{1, 3, 5, 5, 31, 0, 0},
{1, 3, 3, 9, 7, 49, 0},
{1, 1, 1, 15, 21, 21, 0},
{1, 3, 1, 13, 27, 49, 0},
{1, 1, 1, 15, 7, 5, 0},
{1, 3, 1, 15, 13, 25, 0},
{1, 1, 5, 5, 19, 61, 0},
{1, 3, 7, 11, 23, 15, 103},
{1, 3, 7, 13, 13, 15, 69}
};
if (dimensions > 10) {
std::cerr << "Sobol direction numbers available for at most 10 shot group\n";
exit(-1);
}
for (unsigned j = 0; j < 20; j++) {
if (j == 0) {
for (unsigned i = 0; i < 32; i++) {
v_[j][i] = 1 << (32 - i - 1);
}
} else {
unsigned ss = s[j - 1];
for (unsigned i = 0; i < ss; i++) {
v_[j][i] = m[j - 1][i] << (32 - i - 1);
}
for (unsigned i = ss; i < 32; i++) {
v_[j][i] = v_[j][i - ss] ^ (v_[j][i - ss] >> ss);
for (unsigned k = 1; k < ss; k++) {
v_[j][i] ^= (((a[j - 1] >> (ss - 1 - k)) & 1) * v_[j][i - k]);
}
}
}
x_[j] = 0;
}
// Burn-in: discard initial values
for (unsigned i = 0; i < 32; i++) {
advance();
}
}
void reset()
{
for (unsigned j = 0; j < 20; j++) {
x_[j] = 0;
}
}
void advance()
{
unsigned b = i_++;
unsigned z = 0; // Position of the first zero bit in binary representation of i_
// counting from the right
if (b) {
while (b & 1) {
b >>= 1;
z++;
}
}
for (unsigned j = 0; j < 20; j++) {
x_[j] ^= v_[j][z];
}
}
std::complex<double> point(unsigned dimension)
{
double x, y;
if (dimension >= 10) {
x = y = std::numeric_limits<double>::quiet_NaN();
} else {
double u = ldexp(x_[dimension], -32);
double v = ldexp(x_[dimension + 10], -32);
// Box-Muller transform
double r = sqrt(-2 * log(u));
x = r * cos(2 * M_PI * v);
y = r * sin(2 * M_PI * v);
}
return std::complex<double>(x, y);
}
};
struct ConvexHullPoint {
public:
explicit ConvexHullPoint(const std::complex<double>& p) : point_(p) {}
// For lexicographic sort: first by x, then by y
bool operator<(const ConvexHullPoint& other) const
{
if (point_.real() < other.point_.real()) {
return true;
} else if (point_.real() > other.point_.real()) {
return false;
} else {
return point_.imag() < other.point_.imag();
}
}
bool operator!=(const std::complex<double>& other) const
{
return point_ != other;
}
// Distance to another point
double distanceTo(const ConvexHullPoint& other) const
{
return std::abs(point_ - other.point_);
}
double inline x(void) const { return point_.real(); }
double inline y(void) const { return point_.imag(); }
private:
std::complex<double> point_;
};
class ShotGroup {
private:
// Use complex type to store impact coordinates
std::vector<std::complex<double> > impact_;
// Cross product of vectors OA and OB, positive if OAB makes a CCW turn
double cross_product( const ConvexHullPoint& O
, const ConvexHullPoint& A
, const ConvexHullPoint& B
) const
{
return (A.x() - O.x()) * (B.y() - O.y())
- (A.y() - O.y()) * (B.x() - O.x());
}
double distance(unsigned a, unsigned b) const
{
return std::abs(impact_.at(a) - impact_.at(b));
}
public:
void add(const std::complex<double>& p)
{
impact_.push_back(p);
}
// Brute force implementation, asymptotic complexity O(N^2)
double group_size_brute_force(double* excluding_worst = NULL) const
{
unsigned n = impact_.size();
if (n < 2) {
if (excluding_worst) {
*excluding_worst = 0;
}
return 0;
}
// Find the two impacts defining extreme spread
double extreme_spread = 0;
unsigned index_a = 0;
unsigned index_b = 0;
for (unsigned i = 0; i < n - 1; i++) {
for (unsigned j = i + 1; j < n; j++) {
double candidate = distance(i, j);
if (extreme_spread < candidate) {
extreme_spread = candidate;
index_a = i;
index_b = j;
}
}
}
if (excluding_worst) {
// Worst shot must be one of the impacts defining extreme spread.
// Calculate group size without either one, return the smaller number.
double extreme_spread_excluding_a = 0;
double extreme_spread_excluding_b = 0;
for (unsigned i = 0; i < n - 1; i++) {
for (unsigned j = i + 1; j < n; j++) {
double candidate = distance(i, j);
if (i != index_a && j != index_a && extreme_spread_excluding_a < candidate) {
extreme_spread_excluding_a = candidate;
}
if (i != index_b && j != index_b && extreme_spread_excluding_b < candidate) {
extreme_spread_excluding_b = candidate;
}
}
}
*excluding_worst = std::min(extreme_spread_excluding_a, extreme_spread_excluding_b);
}
return extreme_spread;
}
// Same as group_size_brute_force(), but using convex hull.
// Asymptotic complexity O(N log N).
//
// Pass 0: find impacts a and b defining extreme spread.
// Return extreme spread if excluding_worst == false.
// Pass 1: find extreme spread excluding a
// Pass 2: find extreme spread excluding b
//
// Return the smaller of extreme spread excluding a and extreme spread excluding b
//
double group_size_convex_hull(double* excluding_worst = NULL) const
{
unsigned n = impact_.size();
if (n < 2) {
if (excluding_worst) {
*excluding_worst = 0;
}
return 0;
}
double extreme_spread = 0;
ConvexHullPoint a(impact_.at(0)); double extreme_spread_excluding_a = 0;
ConvexHullPoint b(impact_.at(1)); double extreme_spread_excluding_b = 0;
for (unsigned pass = 0; pass < 3; pass++) {
// Use Andrew's monotone chain 2D algorithm to construct convex hull
std::vector<ConvexHullPoint> lower_hull;
std::vector<ConvexHullPoint> upper_hull;
{
std::vector<ConvexHullPoint> p;
for (unsigned i = 0; i < n; i++) {
if ( pass == 0
|| ((pass == 1) && (a != impact_.at(i)))
|| ((pass == 2) && (b != impact_.at(i)))
)
p.push_back(ConvexHullPoint(impact_.at(i)));
}
std::sort(p.begin(), p.end());
unsigned k = 0;
for (unsigned i = 0; i < p.size(); i++) { // lower hull
while (k >= 2 && cross_product(lower_hull.at(k - 2), lower_hull.at(k - 1), p.at(i)) <= 0) {
lower_hull.pop_back();
k--;
}
lower_hull.push_back(p.at(i));
k++;
}
k = 0;
for (unsigned i = 0; i < p.size(); i++) { // upper hull
while (k >= 2 && cross_product(upper_hull.at(k - 2), upper_hull.at(k - 1), p.at(i)) >= 0) {
upper_hull.pop_back();
k--;
}
upper_hull.push_back(p.at(i));
k++;
}
}
// Use rotating calipers algoritm to find most distant antipodal pair of hull points
double diameter = 0;
{
unsigned i = 0;
unsigned j = lower_hull.size() - 1;
while (i < upper_hull.size() - 1 || j > 0) {
double d = upper_hull.at(i).distanceTo(lower_hull.at(j));
if (diameter < d) {
diameter = d;
if (pass == 0) {
a = upper_hull.at(i);
b = lower_hull.at(j);
}
}
if (i == upper_hull.size() - 1) {
j--;
} else if (j == 0) {
i++;
} else if ( (upper_hull.at(i + 1).y() - upper_hull.at(i).y())
* (lower_hull.at(j).x() - lower_hull.at(j - 1).x())
> (upper_hull.at(i + 1).x() - upper_hull.at(i).x())
* (lower_hull.at(j).y() - lower_hull.at(j - 1).y())
) {
i++;
} else {
j--;
}
}
}
switch (pass) {
case 0:
if (excluding_worst) {
extreme_spread = diameter;
break;
}
return diameter;
case 1:
extreme_spread_excluding_a = diameter;
break;
case 2:
extreme_spread_excluding_b = diameter;
break;
}
}
*excluding_worst = std::min(extreme_spread_excluding_a, extreme_spread_excluding_b);
return extreme_spread;
}
// As per NSD (page 181) should be within 15 cm at 100 m
// Group size 2.79295 corresponds to kuchnost~=3.15863,
// so this is equivalent to 4.56 MOA.
double nsd_kuchnost(void) const
{
// Only defined for 4 shot groups
if (impact_.size() != 4) return std::numeric_limits<double>::quiet_NaN();
// STP using all 4 shots
auto stp = (impact_.at(0) + impact_.at(1) + impact_.at(2) + impact_.at(3)) / 4.;
// Minimum radius of circle with center at STP that encloses all shots
double r = 0;
for (unsigned i = 0; i < 4; i++) {
double candidate = std::abs(stp - impact_.at(i));
if (r < candidate) {
r = candidate;
}
}
// Exclude outlier, if any
for (unsigned i = 0; i < 4; i++) {
// STP excluding this shot
auto stp3 = (stp * 4. - impact_.at(i)) / 3.;
// Minimum radius of circle with center at STP of three shots excluding this shot
double r2 = 0;
for (unsigned j = 0; j < 4; j++) {
if (i == j) {
continue;
}
double candidate = std::abs(stp - impact_.at(i));
if (r2 < candidate) {
r2 = candidate;
}
}
// Outlier is a shot 2.5x or more distant from STP of other three shots
// than radius of the circle centered as STP of other three shots
// that covers these three shots
if (std::abs(stp3 - impact_.at(i)) > 2.5 * r2 && r > r2) {
r = r2;
}
}
// Diameter
return 2 * r;
}
double avg_miss_radius(void) const
{
unsigned n = impact_.size();
if (n < 2) return std::numeric_limits<double>::quiet_NaN();
std::complex<double> center = 0;
for (unsigned i = 0; i < n; i++) {
center += impact_.at(i);
}
center /= n;
double amr = 0;
for (unsigned i = 0; i < n; i++) {
amr += std::abs(impact_.at(i) - center);
}
amr /= n;
return amr;
}
//
// Ballistic Accuracy Class (before rounding)
//
// Find location of group center (mean)
// For each shot i, find its radius squared (r2) relative to group center
// Upper 90% confidence value sigma_U=SQRT(SUM(r2)/CHIINV(0.9,2n-2))
// Ballistic Accuracy Class is ROUND(sigma_U,0)
//
// http://ballistipedia.com/index.php?title=Ballistic_Accuracy_Classification
//
double bac(void) const
{
unsigned n = impact_.size();
if (n < 2) return std::numeric_limits<double>::quiet_NaN();
std::complex<double> center = 0;
for (unsigned i = 0; i < n; i++) {
center += impact_.at(i);
}
center /= n;
double sum_r2 = 0;
for (unsigned i = 0; i < n; i++) {
sum_r2 += std::norm(impact_.at(i) - center);
}
// Memoized BAC factor (to avoid recalculating it for each group)
static unsigned memoized_n = 0;
static double memoized_factor = 0;
if (n != memoized_n) {
boost::math::chi_squared ch2(2 * n - 2);
double chisq_inv_rt = boost::math::quantile(ch2, 1 - 0.9);
memoized_factor = 1 / sqrt(chisq_inv_rt);
memoized_n = n;
}
return memoized_factor * sqrt(sum_r2);
}
// Pairwise distances weighted by rank
double pdwr(bool trim = false) const
{
unsigned n = impact_.size();
// Precomputed scaling factor to convert the result to sigma
double scaling_factor = 0;
switch (n) {
case 3: scaling_factor = trim ? 1 / 1.04273 : 1 / 2.00018; break;
case 4: scaling_factor = trim ? 1 / 1.31192 : 1 / 2.1068; break;
case 5: scaling_factor = trim ? 1 / 1.46386 : 1 / 2.16243; break;
case 6: scaling_factor = trim ? 1 / 1.56703 : 1 / 2.19481; break;
case 7: scaling_factor = trim ? 1 / 1.64232 : 1 / 2.21542; break;
case 8: scaling_factor = trim ? 1 / 1.70089 : 1 / 2.22942; break;
case 9: scaling_factor = trim ? 1 / 1.74798 : 1 / 2.2394; break;
case 10: scaling_factor = trim ? 1 / 1.78699 : 1 / 2.24684; break;
default: return std::numeric_limits<double>::quiet_NaN();
}
// Pairwise distances
std::vector<double> d;
for (unsigned i = 0; i < n; i++) {
for (unsigned j = i + 1; j < n; j++) {
d.push_back(std::abs(impact_.at(i) - impact_.at(j)));
}
}
std::sort(d.begin(), d.end());
// Average weighted by rank, possibly trimmed
double numerator = 0;
double denominator = 0;
unsigned m = d.size();
if (trim) {
m -= n - 1;
}
for (unsigned i = 0; i < m; i++) {
numerator += d.at(i) * (i + 1.);
denominator += (i + 1.);
}
return scaling_factor * numerator / denominator;
}
// Rank weighted mean of right winsorized pairwise distances
double rwmrwpd() const
{
unsigned n = impact_.size();
// Precomputed scaling factor to convert the result to sigma
double scaling_factor = 0;
switch (n) {
case 3: scaling_factor = 1 / 1.04273; break;
case 4: scaling_factor = 1 / 1.48818; break;
case 5: scaling_factor = 1 / 1.69422; break;
case 6: scaling_factor = 1 / 1.81984; break;
case 7: scaling_factor = 1 / 1.90066; break;
case 8: scaling_factor = 1 / 1.95899; break;
case 9: scaling_factor = 1 / 2.00215; break;
case 10: scaling_factor = 1 / 2.03579; break;
default: return std::numeric_limits<double>::quiet_NaN();
}
// Pairwise distances
std::vector<double> d;
for (unsigned i = 0; i < n; i++) {
for (unsigned j = i + 1; j < n; j++) {
d.push_back(std::abs(impact_.at(i) - impact_.at(j)));
}
}
std::sort(d.begin(), d.end());
// Average weighted by rank and winsorized
double numerator = 0;
double denominator = 0;
unsigned m = d.size() - n;
for (unsigned i = 0; i < d.size(); i++) {
numerator += d.at(i < m ? i : m) * (i + 1.);
denominator += (i + 1.);
}
return scaling_factor * numerator / denominator;
}
// Qn with different rank
double tqn() const
{
unsigned n = impact_.size();
std::vector<double> d;
for (unsigned i = 0; i < n; i++) {
for (unsigned j = i + 1; j < n; j++) {
d.push_back(std::abs(impact_.at(i) - impact_.at(j)));
}
}
std::sort(d.begin(), d.end());
return d.at(d.size() - n);
}
// Square root of average of squared pairwise distances
double sraspd(bool trim = false) const
{
unsigned n = impact_.size();
if (n < 3 || n > 10) {
return std::numeric_limits<double>::quiet_NaN();
}
// Squares of pairwise distance
std::vector<double> d;
for (unsigned i = 0; i < n; i++) {
for (unsigned j = i + 1; j < n; j++) {
d.push_back(std::norm(impact_.at(i) - impact_.at(j)));
}
}
// Square root of average of squared pairwise distances, possibly trimmed
double sum_of_squares = 0;
unsigned m = d.size();
if (trim) {
m -= n - 1;
std::sort(d.begin(), d.end());
}
for (unsigned i = 0; i < m; i++) {
sum_of_squares += d.at(i);
}
return sqrt(sum_of_squares / m);
}
void show(void) const
{
for (unsigned i = 0; i < impact_.size(); i++) {
std::cout << "g.add(std::complex<double>(" << impact_.at(i).real() << ", " << impact_.at(i).imag() << "));\n";
}
}
};
class DescriptiveStat
{
public:
DescriptiveStat() : n_(0), m_(0), s_(0) {}
void push(double x)
{
double new_m = m_ + (x - m_) / (++n_);
double new_s = s_ + (x - m_) * (x - new_m);
m_ = new_m;
s_ = new_s;
}
double mean(void) const
{
return (n_ > 0) ? m_ : std::numeric_limits<double>::quiet_NaN();
}
double variance(void) const
{
return (n_ > 1) ? s_ / (n_ - 1) : std::numeric_limits<double>::quiet_NaN();
}
double stdev(void) const
{
return sqrt(variance());
}
double cv(void) const
{
return stdev() / mean();
}
void show(const char* metric, double theoretical = 0, bool suppress_nan = false)
{
auto m = mean();
if (suppress_nan && !isfinite(m)) {
return;
}
std::cout << metric << " mean=" << m;
if (theoretical > 0) {
std::cout << " (expected " << theoretical << ")";
}
std::cout << ", CV=" << cv() << "\n";
}
private:
unsigned n_;
double m_;
double s_;
};
static double median(std::vector<double>& x)
{
if (x.size() == 0) {
return std::numeric_limits<double>::quiet_NaN();
}
std::vector<double>::iterator median_it = x.begin() + x.size() / 2;
nth_element(x.begin(), median_it, x.end());
if (x.size() % 2) { // Odd number of elements
return *median_it;
}
// Even number of elements, return average of two elements in the middle
double b = *median_it--;
nth_element(x.begin(), median_it, x.end());
double a = *median_it;
return (a + b) / 2;
}
int main(int argc, char* argv[])
{
DefaultRandomNumberGenerator pseudo_rng;
long long experiments = 0;
if (argc > 1) {
experiments = atoi(argv[1]);
// Self-test
if (experiments == 0) {
std::cout << "Comparing group_size_brute_force() and group_size_convex_hull()\n";
{
double max_diff = 0;
for (unsigned i = 0; i < 1e6; i++) {
unsigned shots = (i & 0xf) + 2;
ShotGroup g;
pseudo_rng.advance();
for (unsigned j = 0; j < shots; j++) {
g.add(pseudo_rng.point(j));
}
double bf2 = 0, ch2 = 0;
double bf = g.group_size_brute_force((i & 0x10) ? &bf2 : NULL);
double ch = g.group_size_convex_hull((i & 0x10) ? &ch2 : NULL);
double diff_1 = fabs(bf - ch);
if (max_diff < diff_1) {
max_diff = diff_1;
}
if (diff_1 > 1e-8) {
std::cout << "Expected group size " << bf << ", got " << ch << "\n";
g.show();
return 0;
}
if (i & 0x10) {
double diff_2 = fabs(bf2 - ch2);
if (diff_2 > 1e-8) {
std::cout << "Expected group size excluding worst " << bf2 << ", got " << ch2 << "\n";
g.show();
return 0;
}
if (max_diff < diff_2) {
max_diff = diff_2;
}
}
}
std::cout << "Max difference " << max_diff << "\n";
}
std::cout << "\tgroup_size_brute_force()\tgroup_size_convex_hull()\n";
for (unsigned shots = 4; shots <= 256; shots *= 2) {
std::cout << shots << " shots:\t";
pseudo_rng.reset();
time_t start_time;
time(&start_time);
double a = 0;
for (unsigned i = 0; i < 1e6; i++) {
ShotGroup g;
pseudo_rng.advance();
for (unsigned j = 0; j < shots; j++) {
g.add(pseudo_rng.point(j));
}
a += g.group_size_brute_force();
}
time_t end_time;
time(&end_time);
std::cout << (end_time - start_time) << " µs, sum=" << a;
pseudo_rng.reset();
std::cout << "\t";
time(&start_time);
double b = 0;
for (unsigned i = 0; i < 1e6; i++) {
ShotGroup g;
pseudo_rng.advance();
for (unsigned j = 0; j < shots; j++) {
g.add(pseudo_rng.point(j));
}
b += g.group_size_convex_hull();
}
time(&end_time);
std::cout << (end_time - start_time) << " µs, sum=" << b << "\n";
}
return 0;
}
} else {
std::cerr << "Usage: mcgs experiments [[[[shots_in_group] groups_in_experiment] proportion_of_outliers] outlier_severity]\n"
"0 experiments to run a self-test,\n"
"negative experiments to use additive quasi-random number generator,\n"
"negative shots_in_group to use Sobol quasi-random number generator,\n"
"negative groups_in_experiment to use MCG 128 pseudo-random number generator\n";
return -1;
}
std::unique_ptr<RandomNumberGenerator> rng(std::unique_ptr<RandomNumberGenerator>(new DefaultRandomNumberGenerator()));
unsigned shots_in_group;
{
int isig = 5;
if (argc > 2) {
isig = atoi(argv[2]);
}
if (isig < 0) {
shots_in_group = (unsigned)(-isig);
std::cout << "Using Sobol quasi-random number generator for impact coordinates\n";
rng = std::unique_ptr<RandomNumberGenerator>(new SobolRandomNumberGenerator(shots_in_group));
} else {
shots_in_group = (unsigned)(isig);
}
}
if (shots_in_group < 3) {
std::cerr << "Shots in group = " << shots_in_group << ", expected at least 3\n";
return -1;
}
if (experiments < 0) {
experiments = -experiments;
std::cout << "Using additive quasi-random number generator for impact coordinates\n";
rng = std::unique_ptr<RandomNumberGenerator>(new AdditiveRandomNumberGenerator(shots_in_group));
}
unsigned groups_in_experiment = 1;
if (argc > 3) {
int igie = atoi(argv[3]);
if (igie < 0) {
igie = -igie;
std::cout << "Using MCG 128 pseudo-random number generator for impact coordinates\n";
rng = std::unique_ptr<RandomNumberGenerator>(new FastRandomNumberGenerator());
}
groups_in_experiment = (unsigned)igie;
}
double proportion_of_outliers = 0.;
if (argc > 4) {
proportion_of_outliers = atof(argv[4]);
}
double outlier_severity = 10.;
if (argc > 5) {
outlier_severity = atof(argv[5]);
}
std::cout << experiments << " experiments, " << shots_in_group << " shots in group";
if (groups_in_experiment > 1) {
std::cout << ", " << groups_in_experiment << " groups per experiment";
}
std::cout << "\n";
if (proportion_of_outliers > 0) {
std::cout << "Using contaminated normal distribution: " <<
(proportion_of_outliers * 100) << "% of observations are pulled from distribution with " <<
outlier_severity << " times higher deviation\n";
}
const double rayleigh_cep_factor = sqrt(4 * log(2) / M_PI) / shots_in_group; // 0.9394/shots
double mle_factor = sqrt(log(2) / M_PI);
for (unsigned i = 0; i < shots_in_group; i++) {
mle_factor *= 4;
if (i != shots_in_group - 1) {
mle_factor *= i + 1;
}
mle_factor /= i + 1 + shots_in_group;
}
double wmr_to_r90hat_factor = 0;
double swmr_to_r90hat_factor = 0;
double swmrr_to_r90hat_factor = 0;
double gs_to_r90hat_factor = 0;
double sixtynine_to_r90hat_factor = 0;
double rayleigh_to_r90hat_factor = 0;
double mle_to_r90hat_factor = 0;
// http://ballistipedia.com/images/7/7a/Statistical_Inference_for_Rayleigh_Distributions_-_Siddiqui%2C_1964.pdf
std::pair<unsigned, unsigned> sixtynine_rank( (unsigned)(0.639 * (shots_in_group + 1)) - 1
, (unsigned)(0.927 * (shots_in_group + 1)) - 1
);
if (shots_in_group == 10) { // Suboptimal, but more robust
sixtynine_rank.first = 6 - 1;
sixtynine_rank.second = 9 - 1;
}
if (groups_in_experiment == 1) {
switch (shots_in_group) {
case 1:
// wxMaxima: find_root(integrate(x*exp(-x^2/2)*exp(-x^2*k^2/2), x, 0, inf)=1-0.9, k, 1, 10);
wmr_to_r90hat_factor = 3;
break;
case 3:
// wxMaxima: find_root(integrate(3*x*(1-exp(-x^2/2))^2*exp(-x^2/2-k^2*x^2/2), x, 0, inf)=1-0.9, k, 1, 10);
wmr_to_r90hat_factor = 1.414213562373095;
break;
case 5:
// wxMaxima: find_root(integrate(5*x*(1-exp(-x^2/2))^4*exp(-x^2/2-k^2*x^2/2), x, 0, inf)=1-0.9, k, 1, 10);
wmr_to_r90hat_factor = 1.17215228421396;
// wxMaxima:
// assume(x>0,t>0,u>0,q>0,k>1);
// p(x):=20*x*(1-exp(-x^2/2))^3*exp(-x^2);
// c(k):=integrate(p(q)*exp(-q^2*k^2/2),q,0,inf);
// find_root(c(k)=1-0.9, k, 1, 2);
swmr_to_r90hat_factor = 1.578643529936508;
gs_to_r90hat_factor = 0.8;
break;
case 10:
// wxMaxima: find_root(integrate(90*x*(1-exp(-x^2/2))^8*exp(-x^2-k^2*x^2/2), x, 0, inf)=1-0.9, k, 1, 10);
swmr_to_r90hat_factor = 1.187140545277712;
swmrr_to_r90hat_factor = 1.2;
gs_to_r90hat_factor = 0.6;
break;
case 20:
rayleigh_to_r90hat_factor = 1.76;
mle_to_r90hat_factor = 0.35;
break;
}
} else if (groups_in_experiment == 2) {
switch (shots_in_group) {
case 1:
// wxMaxima:
// assume(x>0,t>0,u>0,q>0,k>1);
// p(x):=x*exp(-x^2/2);
// p2(t):=''(integrate(2*p(u)*p(2*t-u),u,0,2*t));
// c2(k):=romberg(p2(q)*exp(-q^2*k^2/2),q,0,10);
// find_root(c2(k)=1-0.9, k, 1, 3);
wmr_to_r90hat_factor = 2.22197649;
break;
case 3:
// wxMaxima:
// assume(x>0,t>0,u>0,q>0,k>1);
// p(x):=3*x*(1-exp(-x^2/2))^2*exp(-x^2/2);
// p2(t):=''(integrate(2*p(u)*p(2*t-u),u,0,2*t));
// c2(k):=romberg(p2(q)*exp(-q^2*k^2/2),q,0,10);
// find_root(c2(k)=1-0.9, k, 1, 3);
wmr_to_r90hat_factor = 1.28875916;
break;
case 5:
// wxMaxima:
// assume(x>0,t>0,u>0,q>0,k>1);
// p(x):=5*x*(1-exp(-x^2/2))^4*exp(-x^2/2);
// p2(t):=romberg(2*p(u)*p(2*t-u),u,0,2*t);
// c2(k):=romberg(p2(q)*exp(-q^2*k^2/2),q,0,10);
// find_root(c2(k)=1-0.9, k, 1, 1.3);
wmr_to_r90hat_factor = 1.10343798;
// wxMaxima:
// assume(x>0,t>0,u>0,q>0,k>1);
// p(x):=20*x*(1-exp(-x^2/2))^3*exp(-x^2);
// p2(t):=romberg(2*p(u)*p(2*t-u),u,0,2*t);
// c2(k):=romberg(p2(q)*exp(-q^2*k^2/2),q,0,10);
// find_root(c2(k)=1-0.9, k, 1, 2);
swmr_to_r90hat_factor = 1.478456;
break;
case 10:
// wxMaxima:
// assume(x>0,t>0,u>0,q>0,k>1);
// p(x):=90*x*(1-exp(-x^2/2))^8*exp(-x^2);
// p2(t):=romberg(2*p(u)*p(2*t-u),u,0,2*t);
// c2(k):=romberg(p2(q)*exp(-q^2*k^2/2),q,0,10);
// find_root(c2(k)=1-0.9, k, 1.1, 1.15);
swmr_to_r90hat_factor = 1.149216;
swmrr_to_r90hat_factor = 1.15;
break;
}
} else if (groups_in_experiment == 4) {
switch (shots_in_group) {
case 5:
swmr_to_r90hat_factor = 1.43;
gs_to_r90hat_factor = 0.723;
break;
default:
break;
}
} else if (groups_in_experiment == 5) {
switch (shots_in_group) {
case 5:
swmr_to_r90hat_factor = 1.42;
gs_to_r90hat_factor = 0.72;
break;
default:
break;
}
} else if (groups_in_experiment > 10) { // Asymptotic approximation for large number of groups in experiment
switch (shots_in_group) {
case 1:
// wxMaxima: float(sqrt(2*log(10))/integrate(x*exp(-x^2/2)*x, x, 0, inf));
wmr_to_r90hat_factor = 1.712233160383746;
break;
case 3:
// wxMaxima: float(sqrt(2*log(10))/integrate(3*(1-exp(-x^2/2))^2*x*exp(-x^2/2)*x, x, 0, inf));
wmr_to_r90hat_factor = 1.175960143568417;
break;
case 5:
// wxMaxima: float(sqrt(2*log(10))/integrate(5*(1-exp(-x^2/2))^4*x*exp(-x^2/2)*x, x, 0, inf));
wmr_to_r90hat_factor = 1.037938194579831;
// wxMaxima: float(sqrt(2*log(10))/integrate(20*x*(1-exp(-x^2/2))^3*exp(-x^2)*x, x, 0, inf));
swmr_to_r90hat_factor = 1.38619009633813;
gs_to_r90hat_factor = 0.7;
break;
case 10:
// wxMaxima: float(sqrt(2*log(10))/integrate(90*x*(1-exp(-x^2/2))^8*exp(-x^2)*x, x, 0, inf));
swmr_to_r90hat_factor = 1.112257194707586;
swmrr_to_r90hat_factor = 1.1;
gs_to_r90hat_factor = 0.7;
break;
case 20:
mle_to_r90hat_factor = 0.3414341089001782;
break;
}
}
if (shots_in_group == 10) {
switch (groups_in_experiment) {
case 1:
// wxMaxima:
// assume(x>0,y>0,x<=y,k>0);
// pdf(x,y):=3*7*8*9*10*(1-exp(-x^2/2))^5*(exp(-x^2/2)-exp(-y^2/2))^2*exp(-y^2/2)*x*exp(-x^2/2)*y*exp(-y^2/2);
// find_root(romberg(integrate(pdf(x,y)*(1-exp(-(k*(x+y))^2/2)),y,x,inf),x,0,50)=9/10,k,0.6,0.8);
sixtynine_to_r90hat_factor = 0.7076687;
break;
case 2:
// wxMaxima:
// assume(x>0,y>0,x<=y);
// pdf(x,y):=15120*(1-exp(-x^2/2))^5*(exp(-x^2/2)-exp(-y^2/2))^2*exp(-y^2/2)*x*exp(-x^2/2)*y*exp(-y^2/2);
// assume(u>0,v>0,v<=u);
// p2(u):=romberg(pdf((u-v)/2,(u+v)/2)/2,v,0,u);
// p2s(t):=romberg(2*p2(u)*p2(2*t-u),u,0,2*t);
// c2(k):=romberg(p2s(q)*exp(-q^2*k^2/2),q,0,10);
// find_root(c2(k)=1/10, k, 0.6, 0.8);
sixtynine_to_r90hat_factor = 0.68860849;
break;
default:
// wxMaxima:
// assume(x>0,y>0,x<=y);
// pdf(x,y):=3*7*8*9*10*(1-exp(-x^2/2))^5*(exp(-x^2/2)-exp(-y^2/2))^2*exp(-y^2/2)*x*exp(-x^2/2)*y*exp(-y^2/2);
// float(sqrt(2*log(10)))/float(integrate(integrate(pdf(x,y)*(x+y),y,x,inf),x,0,inf));
sixtynine_to_r90hat_factor = 0.67024464399177286;
break;
}
}
DescriptiveStat gs_s, gs_s2, bgs_s, ags_s, ags_s2, mgs_s, wgs_s, amr_s, bac_s, pdwr_s, pdwr2_s,
sraspd_s, sraspd2_s, tqn_s, rwmrwpd_s, aamr_s, rayleigh_s,
rwr_s, mle_s, median_r_s;
DescriptiveStat worst_r_s, second_worst_r_s, rwr9_s;
std::map< std::pair<unsigned, unsigned>, DescriptiveStat> sixtynine_r_s;
DescriptiveStat nsd_s, wr_s, swr_s, sixtynine_s;
unsigned hits_wmr = 0;
unsigned hits_swmr = 0;
unsigned hits_swmrr = 0;
unsigned hits_gs = 0;
unsigned hits_sixtynine = 0;
unsigned hits_rayleigh = 0;
unsigned hits_mle = 0;
unsigned bac_gt_1_ct = 0;
double r90hat_wmr = 0;
double r90hat_swmr = 0;
double r90hat_swmrr = 0;
double r90hat_gs = 0;
double r90hat_sixtynine = 0;
double r90hat_rayleigh = 0;
double r90hat_mle = 0;
std::default_random_engine outlier_generator;
std::uniform_real_distribution<double> outlier_distribution;
for (unsigned experiment = 0; experiment < experiments; experiment++) {
double best_gs = 0, worst_gs = 0;
DescriptiveStat gs, gs2, amr, wr, swr, sixtynine, rayleigh, mle;
std::vector<double> gsg_v;
for (unsigned j = 0; j < groups_in_experiment; j++) {
ShotGroup g;
rng->advance();
std::vector<double> r;
std::vector<double> r2;
for (unsigned i = 0; i < shots_in_group; i++) {
std::complex<double> p = rng->point(i);
if ( proportion_of_outliers > 0
&& outlier_distribution(outlier_generator) < proportion_of_outliers
) {
p *= outlier_severity;
}
double ri = std::abs(p);
g.add(p);
r.push_back(ri);
r2.push_back(ri*ri);
// Use R90 estimates based on previous experiment to avoid correlation
if (experiment != 0) { // If there is a prior group
if (ri < r90hat_wmr) hits_wmr++;
if (ri < r90hat_swmr) hits_swmr++;
if (ri < r90hat_swmrr) hits_swmrr++;
if (ri < r90hat_gs) hits_gs++;
if (ri < r90hat_sixtynine) hits_sixtynine++;
if (ri < r90hat_rayleigh) hits_rayleigh++;
if (ri < r90hat_mle) hits_mle++;
}
} // Next shot
std::sort(r.begin(), r.end()); // We'll need many ranks, faster to sort once
double this_minus1 = 0;
double this_gs = (shots_in_group < 32)
? g.group_size_brute_force(&this_minus1)
: g.group_size_convex_hull(&this_minus1);
gs_s.push(this_gs);
gsg_v.push_back(this_gs);
gs_s2.push(this_minus1);
gs2.push(this_minus1);
if (shots_in_group == 4) {
nsd_s.push(g.nsd_kuchnost());
}
if (j) {
if (best_gs > this_gs) {
best_gs = this_gs;
}
if (worst_gs < this_gs) {
worst_gs = this_gs;
}
} else {
best_gs = this_gs;
worst_gs = this_gs;
}
gs.push(this_gs);
double this_amr = g.avg_miss_radius();
amr_s.push(this_amr);
amr.push(this_amr);
double this_bac = g.bac();
bac_s.push(this_bac);
if (this_bac > 1) {
bac_gt_1_ct++;
}
pdwr_s.push(g.pdwr());
pdwr2_s.push(g.pdwr(true));
sraspd_s.push(g.sraspd());
sraspd2_s.push(g.sraspd(true));
tqn_s.push(g.tqn());
rwmrwpd_s.push(g.rwmrwpd());
double this_rayleigh = rayleigh_cep_factor * accumulate(r.begin(), r.end(), 0.);
rayleigh.push(this_rayleigh);
rayleigh_s.push(this_rayleigh);
{
double rwr = 0, rwr9 = 0;
for (unsigned i = 0; i < r.size(); i++) {
rwr += r.at(i) * (i + 1);
if (i < r.size() - 1) {
rwr9 += r.at(i) * (i + 1);
}
}
rwr_s.push(2 * rwr / (r.size() * (r.size() - 1)));
rwr9_s.push(2 * rwr9 / ((r.size() - 1) * (r.size() - 2)));
}
double this_mle = sqrt(accumulate(r2.begin(), r2.end(), 0.));
mle.push(this_mle);
mle_s.push(mle_factor * this_mle);
double this_wr = r.at(shots_in_group - 1);
wr.push(this_wr);
worst_r_s.push(this_wr);
double this_swr = r.at(shots_in_group - 2);
swr.push(this_swr);
second_worst_r_s.push(this_swr);
double med = median(r);
median_r_s.push(med);
if (sixtynine_rank.first != sixtynine_rank.second) {
double this_sixtynine = r.at(sixtynine_rank.first) + r.at(sixtynine_rank.second);
sixtynine.push(this_sixtynine);
if (shots_in_group <= 100) {
// Remember all rank pairs, will choose the best one later
for (unsigned rank_a = 0; rank_a < shots_in_group - 1; rank_a++) {
for (unsigned rank_b = rank_a + 1; rank_b < shots_in_group; rank_b++) {
double e = r.at(rank_a) + r.at(rank_b);
sixtynine_r_s[std::make_pair(rank_a, rank_b)].push(e);
}
}
}
}
} // Next group
if (groups_in_experiment > 1) {
bgs_s.push(best_gs);
wgs_s.push(worst_gs);
ags_s.push(gs.mean());
ags_s2.push(gs2.mean());
mgs_s.push(median(gsg_v));
aamr_s.push(amr.mean());
wr_s.push(wr.mean());
swr_s.push(swr.mean());
sixtynine_s.push(sixtynine.mean());
}
r90hat_wmr = wr.mean() * wmr_to_r90hat_factor;
r90hat_swmr = swr.mean() * swmr_to_r90hat_factor;
r90hat_swmrr = swr.mean() * swmrr_to_r90hat_factor;
r90hat_gs = gs.mean() * gs_to_r90hat_factor;
r90hat_sixtynine = sixtynine.mean() * sixtynine_to_r90hat_factor;
r90hat_rayleigh = rayleigh.mean() * rayleigh_to_r90hat_factor / sqrt(4 * log(2) / M_PI);
if (shots_in_group == 20) {
r90hat_mle = mle.mean() * mle_to_r90hat_factor;
}
} // Next experiment
if (groups_in_experiment == 1) {
std::cout << "--- Precision estimators ---\n";
gs_s.show("Group size:");
if (shots_in_group == 4) {
nsd_s.show("Kuchnost:");
}
amr_s.show("Average Miss Radius:");
double e = (proportion_of_outliers > 0 ? 0 : 1);
pdwr_s.show("Pairwise distances weighted by rank:", e, true);
sraspd_s.show("Square root of average of squared pairwise distances:", true);
bac_s.show("Ballistic Accuracy Class:");
std::cout << "Percent of groups with BAC>1: "
<< 100. * bac_gt_1_ct / groups_in_experiment / experiments << "%, expected 90%\n";
std::cout << "--- Robust precision estimators ---\n";
gs_s2.show("Group size (excluding worst shot in group):");
pdwr2_s.show("Pairwise distances weighted by rank, trimmed:", e, true);
sraspd2_s.show("Square root of average of squared pairwise distances, trimmed:", true);
tqn_s.show("Tweaked Qn:");
rwmrwpd_s.show("Rank weighted mean of right Winsorized pairwise distances:", e, true);
std::cout << "--- Hit probability estimators ---\n";
double theoretical_cep = 0;
if (proportion_of_outliers == 0) {
theoretical_cep = sqrt(-2*log(0.5));
}
rayleigh_s.show("Rayleigh CEP estimator:", theoretical_cep);
rwr_s.show("Rank weighted miss radius:");
mle_s.show("Maximum likelihood CEP estimator:", theoretical_cep);
double theoretical_worst = 0;
if (proportion_of_outliers == 0) {
switch (shots_in_group) {
case 3:
// wxMaxima: float(integrate(3*(1-exp(-x^2/2))^2*x*exp(-x^2/2)*x, x, 0, inf));
theoretical_worst = 1.824862890146495;
break;
case 5:
// wxMaxima: float(integrate(5*(1-exp(-x^2/2))^4*x*exp(-x^2/2)*x, x, 0, inf));
theoretical_worst = 2.067527755983637;
break;
}
}
worst_r_s.show("Worst miss radius:", theoretical_worst);
std::cout << "--- Robust hit probability estimators ---\n";
median_r_s.show("Median CEP estimator:"); // Not showing theoretical_cep because median has known bias
double theoretical_second_worst = 0;
double theoretical_sixtynine = 0;
if (proportion_of_outliers == 0) {
switch (shots_in_group) {
case 10:
// wxMaxima: float(integrate(90*x*(1-exp(-x^2/2))^8*exp(-x^2)*x, x, 0, inf));
theoretical_second_worst = 1.929379316672818;
// wxMaxima:
// assume(x>0,y>0,x<=y);
// pdf(x,y):=3*7*8*9*10*(1-exp(-x^2/2))^5*(exp(-x^2/2)-exp(-y^2/2))^2*exp(-y^2/2)*x*exp(-x^2/2)*y*exp(-y^2/2);
// integrate(integrate(pdf(x,y)*(x+y),y,x,inf),x,0,inf);
theoretical_sixtynine = 3.201765293569168;
break;
}
}
second_worst_r_s.show("Second worst miss radius:", theoretical_second_worst);
rwr9_s.show("Rank weighted miss radius (excluding worst):");
std::cout << "--- Combinations of two order statistics ---\n";
// Find combination of two order statistics with lowest CV
{
unsigned best_pos = 0;
double best_cv = 0;
unsigned pos = 0;
for (auto it = sixtynine_r_s.begin(); it != sixtynine_r_s.end(); it++, pos++) {
if (pos == 0 || best_cv > it->second.cv()) {
best_cv = it->second.cv();
best_pos = pos;
}
}
pos = 0;
for (auto it = sixtynine_r_s.begin(); it != sixtynine_r_s.end(); it++, pos++) {
if (pos == best_pos) {
std::cout << "Lowest CV pair: R" << (it->first.first + 1) << ":" << shots_in_group
<< "+R" << (it->first.second + 1) << ":" << shots_in_group;
it->second.show(",");
it = sixtynine_r_s.find(sixtynine_rank);
if (it != sixtynine_r_s.end()) {
std::cout << "R" << (sixtynine_rank.first + 1) << ":" << shots_in_group
<< "+R" << (sixtynine_rank.second + 1) << ":" << shots_in_group;
it->second.show(",", theoretical_sixtynine);
}
}
}
}
} else {
bgs_s.show("Best group size:");
ags_s.show("Average group size:");
ags_s2.show("Average group size (excluding worst shot in group):");
mgs_s.show("Median group size:");
wgs_s.show("Worst group size:");
aamr_s.show("Average of AMR of groups:");
wr_s.show("Average worst miss radius:");
swr_s.show("Average second worst miss radius:");
if (sixtynine_rank.first != sixtynine_rank.second) {
std::cout << "Average R" << (sixtynine_rank.first + 1) << ":" << shots_in_group
<< "+R" << (sixtynine_rank.second + 1) << ":" << shots_in_group;
sixtynine_s.show(":");
}
}
std::cout << "--- R90 estimators ---\n";
// -1 because we use previos experiment to set threshold for the next.
// First experiment does not participate because it does not have a previous.
double denominator = shots_in_group * ((double)groups_in_experiment * (experiments - 1));
if (wmr_to_r90hat_factor > 0) {
std::cout << "Percent of hits within " << wmr_to_r90hat_factor
<< " * worst miss radius: "
<< 100. * hits_wmr / denominator << "%\n";
}
if (swmr_to_r90hat_factor > 0) {
std::cout << "Percent of hits within " << swmr_to_r90hat_factor
<< " * second worst miss radius: "
<< 100. * hits_swmr / denominator << "%\n";
}
if (swmrr_to_r90hat_factor > 0) {
std::cout << "Percent of hits within " << swmrr_to_r90hat_factor
<< " * second worst miss radius: "
<< 100. * hits_swmrr / denominator << "%\n";
}
if (gs_to_r90hat_factor > 0) {
std::cout << "Percent of hits within " << gs_to_r90hat_factor
<< " * group size: "
<< 100. * hits_gs / denominator << "%\n";
}
if (sixtynine_to_r90hat_factor > 0) {
std::cout << "Percent of hits within " << sixtynine_to_r90hat_factor
<< " * (R" << (sixtynine_rank.first + 1) << ":" << shots_in_group
<< " + R" << (sixtynine_rank.second + 1) << ":" << shots_in_group << "): "
<< 100. * hits_sixtynine / denominator << "%\n";
}
if (rayleigh_to_r90hat_factor > 0) {
std::cout << "Percent of hits within " << rayleigh_to_r90hat_factor
<< " * average miss radius: "
<< 100. * hits_rayleigh / denominator << "%\n";
}
if (mle_to_r90hat_factor > 0) {
std::cout << "Percent of hits within " << mle_to_r90hat_factor
<< " * square root of sum of squares: "
<< 100. * hits_mle / denominator << "%\n";
}
return 0;
}
| 33.68435
| 128
| 0.53518
|
lstange
|
f9fe622f490c688aae03ab6c3f339d6e918d668c
| 4,917
|
cpp
|
C++
|
Freesia/src/Platform/X11/X11Window.cpp
|
Htrap19/Freesia
|
df030b1981effd59f7856e6af7178b4a1667f8cd
|
[
"Apache-2.0"
] | 2
|
2021-12-27T15:07:55.000Z
|
2022-01-04T20:10:33.000Z
|
Freesia/src/Platform/X11/X11Window.cpp
|
Htrap19/Freesia
|
df030b1981effd59f7856e6af7178b4a1667f8cd
|
[
"Apache-2.0"
] | null | null | null |
Freesia/src/Platform/X11/X11Window.cpp
|
Htrap19/Freesia
|
df030b1981effd59f7856e6af7178b4a1667f8cd
|
[
"Apache-2.0"
] | null | null | null |
//
// Created by Htrap19 on 12/1/21.
//
#include "X11Window.h"
#include <GLFW/glfw3.h>
#include "Freesia/Core/Log.h"
#include "Freesia/Core/Assert.h"
#include "Freesia/Events/WindowEvent.h"
#include "Freesia/Events/KeyEvent.h"
#include "Freesia/Events/MouseEvent.h"
namespace Freesia
{
static uint8_t s_GLFWWindowCount = 0;
static void GLFWErrorCallback(int error, const char* description)
{
FS_CORE_ERROR("GLFWError[{0}]: {1}", error, description);
}
X11Window::X11Window(const Freesia::WindowProps &props)
{
Init(props);
}
X11Window::~X11Window()
{
Shutdown();
}
void X11Window::OnUpdate()
{
m_Context->SwapBuffers();
}
void X11Window::Init(const WindowProps &props)
{
m_Data.Width = props.Width, m_Data.Height = props.Height, m_Data.Title = props.Title;
FS_CORE_INFO("Creating Window '{0}' ({1}, {2})", props.Title, props.Width, props.Height);
if (s_GLFWWindowCount == 0)
{
int success = glfwInit();
FS_CORE_ASSERT(success, "Failed to initialize GLFW!");
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwSetErrorCallback(GLFWErrorCallback);
}
m_Window = glfwCreateWindow((int)m_Data.Width, (int)m_Data.Height, m_Data.Title.c_str(), nullptr, nullptr);
m_Context = GraphicsContext::Create(m_Window);
m_Context->Init();
glfwSetWindowUserPointer(m_Window, &m_Data);
s_GLFWWindowCount++;
glfwSetWindowSizeCallback(m_Window, [](GLFWwindow* window, int width, int height)
{
auto& data = *(WindowData*) glfwGetWindowUserPointer(window);
data.Width = (uint32_t)width;
data.Height = (uint32_t)height;
WindowResizedEvent e(width, height);
data.EventCallback(e);
});
glfwSetWindowCloseCallback(m_Window, [](GLFWwindow* window)
{
auto& data = *(WindowData*) glfwGetWindowUserPointer(window);
WindowClosedEvent e;
data.EventCallback(e);
});
glfwSetKeyCallback(m_Window, [](GLFWwindow* window, int key, int scancode, int action, int mods)
{
auto& data = *(WindowData*) glfwGetWindowUserPointer(window);
switch (action)
{
case GLFW_PRESS:
{
KeyPressedEvent e((KeyCode)key, 0);
data.EventCallback(e);
break;
}
case GLFW_RELEASE:
{
KeyReleasedEvent e((KeyCode)key);
data.EventCallback(e);
break;
}
case GLFW_REPEAT:
{
KeyPressedEvent e((KeyCode)key, 1);
data.EventCallback(e);
break;
}
default:
break;
}
});
glfwSetCharCallback(m_Window, [](GLFWwindow* window, unsigned int key)
{
auto& data = *(WindowData*) glfwGetWindowUserPointer(window);
KeyTypedEvent e(key);
data.EventCallback(e);
});
glfwSetMouseButtonCallback(m_Window, [](GLFWwindow* window, int button, int action, int mods)
{
auto& data = *(WindowData*) glfwGetWindowUserPointer(window);
switch (action)
{
case GLFW_PRESS:
{
MouseButtonPressedEvent e((MouseCode)button);
data.EventCallback(e);
break;
}
case GLFW_RELEASE:
{
MouseButtonReleasedEvent e((MouseCode)button);
data.EventCallback(e);
break;
}
default:
break;
}
});
glfwSetCursorPosCallback(m_Window, [](GLFWwindow* window, double xpos, double ypos)
{
auto data = *(WindowData*) glfwGetWindowUserPointer(window);
MouseMovedEvent e((float)xpos, (float)ypos);
data.EventCallback(e);
});
glfwSetScrollCallback(m_Window, [](GLFWwindow* window, double xOffset, double yOffset)
{
auto data = *(WindowData*) glfwGetWindowUserPointer(window);
MouseScrolledEvent e((float)xOffset, (float)yOffset);
data.EventCallback(e);
});
}
void X11Window::Shutdown()
{
glfwDestroyWindow(m_Window);
s_GLFWWindowCount--;
}
void X11Window::SetVSync(bool enabled)
{
if (enabled)
glfwSwapInterval(1);
else
glfwSwapInterval(0);
m_Data.VSync = enabled;
}
}
| 28.587209
| 115
| 0.538133
|
Htrap19
|
e600839598c526cabb9604007b6869de0785c3ed
| 281
|
cpp
|
C++
|
apps/CoreApp/gtest/VisitTest.cpp
|
FleX-d/Core
|
b1d44e57dbe24cc20aa82fb249976fa31e88c098
|
[
"BSD-3-Clause"
] | null | null | null |
apps/CoreApp/gtest/VisitTest.cpp
|
FleX-d/Core
|
b1d44e57dbe24cc20aa82fb249976fa31e88c098
|
[
"BSD-3-Clause"
] | null | null | null |
apps/CoreApp/gtest/VisitTest.cpp
|
FleX-d/Core
|
b1d44e57dbe24cc20aa82fb249976fa31e88c098
|
[
"BSD-3-Clause"
] | 3
|
2018-05-09T11:50:33.000Z
|
2018-07-24T08:13:17.000Z
|
#include <cstdlib>
#include <iostream>
#include <gtest/gtest.h>
#include "Visitor.h"
TEST(Visitor, Test)
{
flexd::core::Visitor v;
flexd::core::UnfreezRequest_t r=new flexd::core::UnfreezRequest("Snake","1.01");
v.visit(r);
r->accept(v);
ASSERT_TRUE(true);
}
| 18.733333
| 84
| 0.654804
|
FleX-d
|
e6028456bb37a7d2a1f0b3ca8a61589bd75c9869
| 7,359
|
cpp
|
C++
|
src/mapper/InfoNES_Mapper_248.cpp
|
jay-kumogata/InfoNES
|
045dd572123753cd53bbbcd387b70a66d0a8562c
|
[
"Apache-2.0"
] | 6
|
2019-05-10T02:09:55.000Z
|
2021-09-16T09:10:14.000Z
|
src/mapper/InfoNES_Mapper_248.cpp
|
b004004/InfoNES-1
|
045dd572123753cd53bbbcd387b70a66d0a8562c
|
[
"Apache-2.0"
] | null | null | null |
src/mapper/InfoNES_Mapper_248.cpp
|
b004004/InfoNES-1
|
045dd572123753cd53bbbcd387b70a66d0a8562c
|
[
"Apache-2.0"
] | 1
|
2019-05-10T16:02:51.000Z
|
2019-05-10T16:02:51.000Z
|
/*===================================================================*/
/* */
/* Mapper 248 : Bao Qing Tian */
/* */
/*===================================================================*/
BYTE Map248_Reg[8];
BYTE Map248_Prg0, Map248_Prg1;
BYTE Map248_Chr01, Map248_Chr23, Map248_Chr4, Map248_Chr5, Map248_Chr6, Map248_Chr7;
BYTE Map248_WeSram;
BYTE Map248_IRQ_Enable;
BYTE Map248_IRQ_Counter;
BYTE Map248_IRQ_Latch;
BYTE Map248_IRQ_Request;
/*-------------------------------------------------------------------*/
/* Initialize Mapper 248 */
/*-------------------------------------------------------------------*/
void Map248_Init()
{
/* Initialize Mapper */
MapperInit = Map248_Init;
/* Write to Mapper */
MapperWrite = Map248_Write;
/* Write to SRAM */
MapperSram = Map248_Sram;
/* Write to APU */
MapperApu = Map248_Apu;
/* Read from APU */
MapperReadApu = Map0_ReadApu;
/* Callback at VSync */
MapperVSync = Map0_VSync;
/* Callback at HSync */
MapperHSync = Map248_HSync;
/* Callback at PPU */
MapperPPU = Map0_PPU;
/* Callback at Rendering Screen ( 1:BG, 0:Sprite ) */
MapperRenderScreen = Map0_RenderScreen;
/* Set SRAM Banks */
SRAMBANK = SRAM;
/* Set Registers */
for( int i = 0; i < 8; i++ ) {
Map248_Reg[i] = 0x00;
}
/* Set ROM Banks */
Map248_Prg0 = 0;
Map248_Prg1 = 1;
Map248_Set_CPU_Banks();
/* Set PPU Banks */
Map248_Chr01 = 0;
Map248_Chr23 = 2;
Map248_Chr4 = 4;
Map248_Chr5 = 5;
Map248_Chr6 = 6;
Map248_Chr7 = 7;
Map248_Set_PPU_Banks();
Map248_WeSram = 0; // Disable
Map248_IRQ_Enable = 0; // Disable
Map248_IRQ_Counter = 0;
Map248_IRQ_Latch = 0;
Map248_IRQ_Request = 0;
/* Set up wiring of the interrupt pin */
K6502_Set_Int_Wiring( 1, 1 );
}
/*-------------------------------------------------------------------*/
/* Mapper 248 Write Function */
/*-------------------------------------------------------------------*/
void Map248_Write( WORD wAddr, BYTE byData )
{
switch( wAddr & 0xE001 ) {
case 0x8000:
Map248_Reg[0] = byData;
Map248_Set_CPU_Banks();
Map248_Set_PPU_Banks();
break;
case 0x8001:
Map248_Reg[1] = byData;
switch( Map248_Reg[0] & 0x07 ) {
case 0x00:
Map248_Chr01 = byData & 0xFE;
Map248_Set_PPU_Banks();
break;
case 0x01:
Map248_Chr23 = byData & 0xFE;
Map248_Set_PPU_Banks();
break;
case 0x02:
Map248_Chr4 = byData;
Map248_Set_PPU_Banks();
break;
case 0x03:
Map248_Chr5 = byData;
Map248_Set_PPU_Banks();
break;
case 0x04:
Map248_Chr6 = byData;
Map248_Set_PPU_Banks();
break;
case 0x05:
Map248_Chr7 = byData;
Map248_Set_PPU_Banks();
break;
case 0x06:
Map248_Prg0 = byData;
Map248_Set_CPU_Banks();
break;
case 0x07:
Map248_Prg1 = byData;
Map248_Set_CPU_Banks();
break;
}
break;
case 0xA000:
Map248_Reg[2] = byData;
if( !ROM_FourScr ) {
if( byData & 0x01 ) {
InfoNES_Mirroring( 0 );
} else {
InfoNES_Mirroring( 1 );
}
}
break;
case 0xC000:
Map248_IRQ_Enable=0;
Map248_IRQ_Latch=0xBE;
Map248_IRQ_Counter =0xBE;
break;
case 0xC001:
Map248_IRQ_Enable=1;
Map248_IRQ_Latch=0xBE;
Map248_IRQ_Counter=0xBE;
break;
}
}
/*-------------------------------------------------------------------*/
/* Mapper 248 Write to SRAM Function */
/*-------------------------------------------------------------------*/
void Map248_Sram( WORD wAddr, BYTE byData )
{
ROMBANK0 = ROMPAGE(((byData<<1)+0) % (NesHeader.byRomSize<<1));
ROMBANK1 = ROMPAGE(((byData<<1)+1) % (NesHeader.byRomSize<<1));
ROMBANK2 = ROMLASTPAGE( 1 );
ROMBANK3 = ROMLASTPAGE( 0 );
}
/*-------------------------------------------------------------------*/
/* Mapper 248 Write to APU Function */
/*-------------------------------------------------------------------*/
void Map248_Apu( WORD wAddr, BYTE byData )
{
Map248_Sram( wAddr, byData );
}
/*-------------------------------------------------------------------*/
/* Mapper 248 H-Sync Function */
/*-------------------------------------------------------------------*/
void Map248_HSync()
{
if( ( /* PPU_Scanline >= 0 && */ PPU_Scanline <= 239) ) {
if( PPU_R1 & R1_SHOW_SCR || PPU_R1 & R1_SHOW_SP ) {
if( Map248_IRQ_Enable ) {
if( !(Map248_IRQ_Counter--) ) {
Map248_IRQ_Counter = Map248_IRQ_Latch;
IRQ_REQ;
}
}
}
}
}
/*-------------------------------------------------------------------*/
/* Mapper 248 Set CPU Banks Function */
/*-------------------------------------------------------------------*/
void Map248_Set_CPU_Banks()
{
if( Map248_Reg[0] & 0x40 ) {
ROMBANK0 = ROMLASTPAGE( 1 );
ROMBANK1 = ROMPAGE(Map248_Prg1 % (NesHeader.byRomSize<<1));
ROMBANK2 = ROMPAGE(Map248_Prg0 % (NesHeader.byRomSize<<1));
ROMBANK3 = ROMLASTPAGE( 0 );
} else {
ROMBANK0 = ROMPAGE(Map248_Prg0 % (NesHeader.byRomSize<<1));
ROMBANK1 = ROMPAGE(Map248_Prg1 % (NesHeader.byRomSize<<1));
ROMBANK2 = ROMLASTPAGE( 1 );
ROMBANK3 = ROMLASTPAGE( 0 );
}
}
/*-------------------------------------------------------------------*/
/* Mapper 248 Set PPU Banks Function */
/*-------------------------------------------------------------------*/
void Map248_Set_PPU_Banks()
{
if( NesHeader.byRomSize > 0 ) {
if( Map248_Reg[0] & 0x80 ) {
PPUBANK[ 0 ] = VROMPAGE(Map248_Chr4 % (NesHeader.byVRomSize<<3));
PPUBANK[ 1 ] = VROMPAGE(Map248_Chr5 % (NesHeader.byVRomSize<<3));
PPUBANK[ 2 ] = VROMPAGE(Map248_Chr6 % (NesHeader.byVRomSize<<3));
PPUBANK[ 3 ] = VROMPAGE(Map248_Chr7 % (NesHeader.byVRomSize<<3));
PPUBANK[ 4 ] = VROMPAGE((Map248_Chr01+0) % (NesHeader.byVRomSize<<3));
PPUBANK[ 5 ] = VROMPAGE((Map248_Chr01+1) % (NesHeader.byVRomSize<<3));
PPUBANK[ 6 ] = VROMPAGE((Map248_Chr23+0) % (NesHeader.byVRomSize<<3));
PPUBANK[ 7 ] = VROMPAGE((Map248_Chr23+1) % (NesHeader.byVRomSize<<3));
InfoNES_SetupChr();
} else {
PPUBANK[ 0 ] = VROMPAGE((Map248_Chr01+0) % (NesHeader.byVRomSize<<3));
PPUBANK[ 1 ] = VROMPAGE((Map248_Chr01+1) % (NesHeader.byVRomSize<<3));
PPUBANK[ 2 ] = VROMPAGE((Map248_Chr23+0) % (NesHeader.byVRomSize<<3));
PPUBANK[ 3 ] = VROMPAGE((Map248_Chr23+1) % (NesHeader.byVRomSize<<3));
PPUBANK[ 4 ] = VROMPAGE(Map248_Chr4 % (NesHeader.byVRomSize<<3));
PPUBANK[ 5 ] = VROMPAGE(Map248_Chr5 % (NesHeader.byVRomSize<<3));
PPUBANK[ 6 ] = VROMPAGE(Map248_Chr6 % (NesHeader.byVRomSize<<3));
PPUBANK[ 7 ] = VROMPAGE(Map248_Chr7 % (NesHeader.byVRomSize<<3));
InfoNES_SetupChr();
}
}
}
| 31.182203
| 85
| 0.478326
|
jay-kumogata
|
e603043db54419c5422ac825c315a50e7c05a467
| 1,506
|
cpp
|
C++
|
libs/ml/src/utilities/utils.cpp
|
chr15murray/ledger
|
85be05221f19598de8c6c58652139a1f2d9e362f
|
[
"Apache-2.0"
] | 96
|
2018-08-23T16:49:05.000Z
|
2021-11-25T00:47:16.000Z
|
libs/ml/src/utilities/utils.cpp
|
chr15murray/ledger
|
85be05221f19598de8c6c58652139a1f2d9e362f
|
[
"Apache-2.0"
] | 1,011
|
2018-08-17T12:25:21.000Z
|
2021-11-18T09:30:19.000Z
|
libs/ml/src/utilities/utils.cpp
|
chr15murray/ledger
|
85be05221f19598de8c6c58652139a1f2d9e362f
|
[
"Apache-2.0"
] | 65
|
2018-08-20T20:05:40.000Z
|
2022-02-26T23:54:35.000Z
|
//------------------------------------------------------------------------------
//
// Copyright 2018-2020 Fetch.AI Limited
//
// 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 "ml/utilities/word2vec_utilities.hpp"
#include <chrono>
namespace fetch {
namespace ml {
namespace utilities {
// Timestamp for logging
std::string GetStrTimestamp()
{
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
auto now_milliseconds =
std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
std::stringstream ss;
ss << std::put_time(std::gmtime(&in_time_t), "%Y-%m-%d-%H:%M:%S");
// add milliseconds to timestamp string
ss << '.' << std::setfill('0') << std::setw(3) << now_milliseconds.count();
return ss.str();
}
} // namespace utilities
} // namespace ml
} // namespace fetch
| 31.375
| 91
| 0.61753
|
chr15murray
|
e60f5fd18b9e17c8033c5c0067bdd054e82ee589
| 19
|
cpp
|
C++
|
Liatris/src/liapch.cpp
|
briandl2000/LiatrisPublic
|
a4960eacc73b31e967e3716c7ce2dbfbc62a9925
|
[
"Apache-2.0"
] | null | null | null |
Liatris/src/liapch.cpp
|
briandl2000/LiatrisPublic
|
a4960eacc73b31e967e3716c7ce2dbfbc62a9925
|
[
"Apache-2.0"
] | null | null | null |
Liatris/src/liapch.cpp
|
briandl2000/LiatrisPublic
|
a4960eacc73b31e967e3716c7ce2dbfbc62a9925
|
[
"Apache-2.0"
] | null | null | null |
#include "liapch.h"
| 19
| 19
| 0.736842
|
briandl2000
|
e61f86bfabe4ba4077201bc671d3230610a5424b
| 1,058
|
cpp
|
C++
|
detail/max_points_on_a_line.cpp
|
zhangxin23/leetcode
|
4c8fc60e59448045a3e880caaedd0486164e68e7
|
[
"MIT"
] | 1
|
2015-07-15T07:31:42.000Z
|
2015-07-15T07:31:42.000Z
|
detail/max_points_on_a_line.cpp
|
zhangxin23/leetcode
|
4c8fc60e59448045a3e880caaedd0486164e68e7
|
[
"MIT"
] | null | null | null |
detail/max_points_on_a_line.cpp
|
zhangxin23/leetcode
|
4c8fc60e59448045a3e880caaedd0486164e68e7
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
using namespace std;
/**
* Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
* */
//Definition for a point.
struct Point {
int x;
int y;
Point() : x(0), y(0) {}
Point(int a, int b) : x(a), y(b) {}
};
class Solution {
public:
int maxPoints(vector<Point>& points) {
if(points.size() < 3)
return points.size();
int result = 0;
for(int i = 0; i < points.size(); i++) {
for(int j = i + 1; j < points.size(); j++) {
int a = points[j].x - points[i].x;
int b = points[j].y - points[j].x;
int c = a * points[i].y - b * points[i].x;
int count = 0;
for(int k = 0; k < points.size(); k++) {
if(a * points[k].y == c + b * points[k].x)
count++;
}
if(count > result)
result = count;
}
}
return result;
}
};
| 23.511111
| 102
| 0.442344
|
zhangxin23
|
e61fac05108799d28b167071b69bdcacbdd39d24
| 5,543
|
hpp
|
C++
|
private/inc/smartx/IasSmartXPriv.hpp
|
juimonen/SmartXbar
|
033f521a5dba5bce5e097df9c98af5b2cc2636dd
|
[
"BSD-3-Clause"
] | 5
|
2018-11-05T07:37:58.000Z
|
2022-03-04T06:40:09.000Z
|
private/inc/smartx/IasSmartXPriv.hpp
|
juimonen/SmartXbar
|
033f521a5dba5bce5e097df9c98af5b2cc2636dd
|
[
"BSD-3-Clause"
] | null | null | null |
private/inc/smartx/IasSmartXPriv.hpp
|
juimonen/SmartXbar
|
033f521a5dba5bce5e097df9c98af5b2cc2636dd
|
[
"BSD-3-Clause"
] | 7
|
2018-12-04T07:32:19.000Z
|
2021-02-17T11:28:28.000Z
|
/*
* Copyright (C) 2018 Intel Corporation.All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
/**
* @file IasSmartXPriv.hpp
* @date 2015
* @brief
*/
#ifndef IASSMARTXPRIV_HPP_
#define IASSMARTXPRIV_HPP_
#include "avbaudiomodules/audio/common/IasAudioCommonTypes.hpp"
#include "avbaudiomodules/internal/audio/common/IasAudioLogging.hpp"
#include "audio/smartx/IasSmartX.hpp"
#include "IasAudioTypedefs.hpp"
namespace IasAudio {
class IasConfiguration;
class IasISetup;
/**
* @brief The SmartXBar private implementation class
*
*/
class IasSmartXPriv
{
public:
enum IasResult
{
eIasOk = IasSmartX::eIasOk, //!< Operation successful
eIasFailed = IasSmartX::eIasFailed, //!< Operation failed
eIasOutOfMemory = IasSmartX::eIasOutOfMemory, //!< Out of memory during memory allocation
eIasNullPointer = IasSmartX::eIasNullPointer, //!< One of the parameters was a nullptr
eIasTimeout = IasSmartX::eIasTimeout, //!< Timeout occured
eIasNoEventAvailable = IasSmartX::eIasNoEventAvailable, //!< No event available in the event queue
};
/**
* @brief Constructor.
*/
IasSmartXPriv();
/**
* @brief Destructor.
*
* Class is not intended to be subclassed.
*/
~IasSmartXPriv();
IasResult init();
/**
* @brief Start data processing thread(s) of the SmartXbar
*
* @return The status of the start call
* @retval IasSmartX::eIasOk SmartXbar data processing successfully started
* @retval IasSmartX::eIasFailed SmartXbar data processing couldn't be started
*/
IasResult start();
/**
* @brief Stop data processing thread(s) of the SmartXbar
*
* @return The status of the stop call
* @retval IasSmartX::eIasOk SmartXbar data processing successfully stopped
* @retval IasSmartX::eIasFailed SmartXbar data processing couldn't be stopped
*/
IasResult stop();
/**
* @brief Get a pointer to the IasISetup interface
*
* The setup interface is used to setup the static and dynamic configuration of the
* audio user space environment. See IasISetup for more details.
* @return A pointer to the IasISetup interface
*/
IasISetup* setup();
/**
* @brief Get a pointer to the IasIRouting interface
*
* The routing interface is used to establish and remove connections between source output
* ports and sink or routing zone input ports. See IasIRouting for more details.
* @return A pointer to the IasIRouting interface
*/
IasIRouting* routing();
/**
* @brief Get a pointer to the IasIProcessing interface
*
* The processing interface is used to control the audio processing modules. See IasIProcessing for
* for more details.
* @return A pointer to the IasIProcessing interface
*/
IasIProcessing* processing();
/**
* @brief Get a pointer to the IasIDebug interface
*
* The debug interface is used for different debug purposes.
* See IasIDebug for more details.
* @return A pointer to the IasIDebug interface
*/
IasIDebug* debug();
/**
* @brief Wait for an asynchronous event from the SmartXbar
*
* This is a blocking call that waits for an event to occur. After an event occured the method IasSmartXPriv::getNextEvent has to
* be called to receive the next event from the event queue.
* @param[in] timeout The timeout value in msec after which the call will return in any case. If 0 is given call will block forever
* @return The result of the method call
* @retval IasSmartXPriv::eIasOk Event occured. Receive it via IasSmartXPriv::getNextEvent
* @retval IasSmartXPriv::eIasTimeout Timeout occured while waiting for event
*/
IasResult waitForEvent(uint32_t timeout) const;
/**
* @brief Get next event from the event queue
*
* This can either be used to poll the event queue or it can be used after a call to the method
* IasSmartXPriv::waitForEvent in a separate thread to be unblocked only when a new event is available. A call of this
* method removes the pending event from the event queue
* @param[in,out] event A pointer where a pointer to the event will be stored
* @return The result of the method call
* @retval IasSmartXPriv::eIasOk Event stored in location where the parameter points to
* @retval IasSmartXPriv::eIasNoEventAvailable No event in event queue available
* @retval IasSmartXPriv::eIasNullPointer Parameter event is a nullptr
*/
IasResult getNextEvent(IasEventPtr *event);
private:
/**
* @brief Copy constructor, private unimplemented to prevent misuse.
*/
IasSmartXPriv(IasSmartXPriv const &other);
/**
* @brief Assignment operator, private unimplemented to prevent misuse.
*/
IasSmartXPriv& operator=(IasSmartXPriv const &other);
// Member variables
DltContext *mLog;
IasConfigurationPtr mConfig;
IasISetup *mSetup;
IasIRouting *mRouting;
IasIProcessing *mProcessing;
IasIDebug *mDebug;
IasCmdDispatcherPtr mCmdDispatcher;
};
/**
* @brief Function to get a IasSmartXPriv::IasResult as string.
*
* @return Enum Member
*/
std::string toString(const IasSmartXPriv::IasResult& type);
} //namespace IasAudio
#endif /* IASSMARTXPRIV_HPP_ */
| 32.798817
| 135
| 0.674725
|
juimonen
|
e6216afde3140c7d5f5eb00c46d364bf5736445e
| 50,687
|
cpp
|
C++
|
src/plugins/legacy/polygonRoi/polygonRoiToolBox.cpp
|
dmargery/medInria-public
|
c232dbdf9353e14ec6e5184349ef1e523def0b76
|
[
"BSD-4-Clause"
] | null | null | null |
src/plugins/legacy/polygonRoi/polygonRoiToolBox.cpp
|
dmargery/medInria-public
|
c232dbdf9353e14ec6e5184349ef1e523def0b76
|
[
"BSD-4-Clause"
] | null | null | null |
src/plugins/legacy/polygonRoi/polygonRoiToolBox.cpp
|
dmargery/medInria-public
|
c232dbdf9353e14ec6e5184349ef1e523def0b76
|
[
"BSD-4-Clause"
] | null | null | null |
/*=========================================================================
medInria
Copyright (c) INRIA 2013 - 2019. All rights reserved.
See LICENSE.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
=========================================================================*/
#include "polygonRoiToolBox.h"
#include <itkBinaryContourImageFilter.h>
#include <itkCastImageFilter.h>
#include <itkImageRegionIterator.h>
#include <itkMinimumMaximumImageCalculator.h>
#include <itkSliceBySliceImageFilter.h>
#include <medAbstractDataFactory.h>
#include <medAbstractImageData.h>
#include <medAbstractImageView.h>
#include <medAbstractProcessLegacy.h>
#include <medAbstractRoi.h>
#include <medDataManager.h>
#include <medPluginManager.h>
#include <medRoiManagementToolBox.h>
#include <medTabbedViewContainers.h>
#include <medToolBox.h>
#include <medToolBoxFactory.h>
#include <medToolBoxHeader.h>
#include <medUtilities.h>
#include <medVtkViewBackend.h>
#include <vtkCellArray.h>
#include <vtkContourRepresentation.h>
#include <vtkContourWidget.h>
#include <vtkImageActor.h>
#include <vtkImageView2D.h>
#include <vtkMatrix4x4.h>
#include <vtkParametricSpline.h>
#include <vtkPolyData.h>
#include <vtkPolyLine.h>
#include <vtkPolygon.h>
#include <vtkSmartPointer.h>
const char *polygonRoiToolBox::generateBinaryImageButtonName = "generateBinaryImageButton";
class contourWidgetObserver : public vtkCommand
{
public:
typedef QPair<unsigned int,unsigned int> PlaneIndexSlicePair;
static contourWidgetObserver* New()
{
return new contourWidgetObserver;
}
void Execute ( vtkObject *caller, unsigned long event, void *callData );
void setView ( vtkImageView2D *view )
{
this->view = view;
}
void setCurrentPolygonRoi ( polygonRoi * roi)
{
this->currentPolygonRoi = roi;
}
polygonRoi * getCurrentPolygonRoi ()
{
return this->currentPolygonRoi;
}
polygonRoi * getRoiToBeClosed ()
{
return this->roiToBeClosed;
}
void setToolBox ( polygonRoiToolBox * toolBox )
{
this->toolBox = toolBox;
}
inline void lock()
{
this->m_lock = 1;
}
inline void unlock()
{
this->m_lock = 0;
}
protected:
contourWidgetObserver();
~contourWidgetObserver();
private:
int m_lock;
vtkImageView2D *view;
polygonRoiToolBox *toolBox;
polygonRoi *roiToBeClosed;
polygonRoi *currentPolygonRoi;
};
contourWidgetObserver::contourWidgetObserver()
{
this->m_lock = 0;
this->view = nullptr;
this->toolBox = nullptr;
this->roiToBeClosed = nullptr;
this->currentPolygonRoi = nullptr;
}
contourWidgetObserver::~contourWidgetObserver(){}
void contourWidgetObserver::Execute ( vtkObject *caller, unsigned long event, void *callData )
{
if ( this->m_lock )
{
return;
}
if (!this->view || !toolBox)
{
return;
}
if (event == vtkCommand::StartInteractionEvent)
{
if (currentPolygonRoi)
{
if(!toolBox->addNewCurve->isChecked())
{
currentPolygonRoi->forceInvisibilityOn(); // should be a delete but does not work yet !! TODO : solve this !
currentPolygonRoi = nullptr;
return;
}
if (!toolBox->viewsPlaneIndex.contains(toolBox->currentView))
{
QList<int> * planeIndexes = new QList<int>();
for(int i=0; i<3; i++)
{
planeIndexes->append(0);
} // fill the list with 0;
toolBox->viewsPlaneIndex.insert(toolBox->currentView,planeIndexes);
}
currentPolygonRoi->setIdSlice(view->GetSlice());
currentPolygonRoi->setOrientation(view->GetViewOrientation());
currentPolygonRoi->forceVisibilityOff();
roiToBeClosed = currentPolygonRoi;
currentPolygonRoi = nullptr;
}
}
// ROI added in medRoiManagementToolBox even if not closed, or just a point
QList<int> * planeIndexes = toolBox->viewsPlaneIndex.value(toolBox->currentView);
AddRoiCommand * command = new AddRoiCommand(toolBox->currentView, roiToBeClosed, "Polygon rois", "NewRoi");
medRoiManager::instance()->addToUndoRedoStack(command);
planeIndexes->replace(view->GetViewOrientation(), toolBox->computePlaneIndex()); // save PlaneIndex for this view and orientation TODO : improve this so that we do it only once for each orientation
roiToBeClosed->getContour()->RemoveObserver(this);
toolBox->onAddNewCurve();
roiToBeClosed = nullptr;
// after first polygonROI created, interpolation and save are enabled
toolBox->buttonsStateWhenROI();
}
polygonRoiToolBox::polygonRoiToolBox(QWidget *parent ) :
medAbstractSelectableToolBox(parent)
{
QWidget *displayWidget = new QWidget(this);
this->addWidget(displayWidget);
QVBoxLayout *layout = new QVBoxLayout();
displayWidget->setLayout(layout);
addNewCurve = new QPushButton(tr("Closed Polygon"));
addNewCurve->setToolTip(tr("Activate closed polygon mode"));
addNewCurve->setCheckable(true);
addNewCurve->setObjectName("closedPolygonButton");
connect(addNewCurve,SIGNAL(toggled(bool)),this,SLOT(onAddNewCurve()));
interpolate = new QPushButton("Interpolate",this);
interpolate->setToolTip("Interpolate between green master ROIs");
interpolate->setObjectName("interpolateButton");
connect(interpolate,SIGNAL(clicked()),this,SLOT(interpolateCurve()));
extractRoiButton = new QPushButton("Extract ROI",this);
extractRoiButton->setToolTip("Extract polygon ROI from a current mask in the view.\nBeware, do not use it with a non-binary dataset");
extractRoiButton->setObjectName("extractRoiButton");
connect(extractRoiButton,SIGNAL(clicked()),this,SLOT(extractROI()));
repulsorTool = new QPushButton(tr("Repulsor"));
repulsorTool->setToolTip(tr("Activate repulsor"));
repulsorTool->setObjectName("repulsorTool");
repulsorTool->setCheckable(true);
connect(repulsorTool,SIGNAL(toggled(bool)),this,SLOT(activateRepulsor()));
generateBinaryImage_button = new QPushButton(tr("Save Mask"));
generateBinaryImage_button->setToolTip("Import the current mask to the non persistent database");
generateBinaryImage_button->setObjectName(generateBinaryImageButtonName);
connect(generateBinaryImage_button,SIGNAL(clicked()),this,SLOT(generateAndSaveBinaryImage()));
currentView = nullptr;
QHBoxLayout *ButtonLayout0 = new QHBoxLayout();
layout->addLayout( ButtonLayout0 );
ButtonLayout0->addWidget(addNewCurve);
ButtonLayout0->addWidget(interpolate);
ButtonLayout0->addWidget(extractRoiButton);
QHBoxLayout *ButtonLayout1 = new QHBoxLayout();
layout->addLayout( ButtonLayout1 );
ButtonLayout1->addWidget(repulsorTool);
ButtonLayout1->addWidget(generateBinaryImage_button);
hashViewObserver = new QHash<medAbstractView*,contourWidgetObserver*>();
// How to use
QLabel *explanation = new QLabel(tr("Define a ROI: choose 'Closed Polygon' and click on the data set.\n")
+ tr("Remove a landmark: put the cursor on it and SUPPR.\n")
+ tr("Undo action: CTRL/CMD + z.\n")
+ tr("Redo action: CTRL/CMD + y.\n")
+ tr("Copy ROIs in current slice: CTRL/CMD + c.\n")
+ tr("Paste ROIs: CTRL/CMD + v.\n")
);
explanation->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
explanation->setWordWrap(true);
layout->addWidget(explanation);
//shortcuts
undo_shortcut = new QShortcut(QKeySequence(tr("Ctrl+z", "Undo polygon manipulation")),this);
redo_shortcut = new QShortcut(QKeySequence(tr("Ctrl+y", "Redo polygon manipulation")),this);
copy_shortcut = new QShortcut(QKeySequence(tr("Ctrl+c", "Copy polygons in current slice")),this);
paste_shortcut = new QShortcut(QKeySequence(tr("Ctrl+v", "Paste polygons")),this);
//Shortcuts
connect(undo_shortcut, SIGNAL(activated()), this, SLOT(undo()));
connect(redo_shortcut, SIGNAL(activated()), this, SLOT(redo()));
connect(copy_shortcut, SIGNAL(activated()), this, SLOT(copyContours()));
connect(paste_shortcut, SIGNAL(activated()), this, SLOT(pasteContours()));
// interactors
interactorStyleRepulsor = vtkInriaInteractorStylePolygonRepulsor::New();
// buttons initialisation: view has no data
disableButtons();
// Add Roi Management Toolbox
roiManagementToolBox = medToolBoxFactory::instance()->createToolBox("medRoiManagementToolBox");
roiManagementToolBox->header()->hide();
this->addWidget(roiManagementToolBox);
// initialise buttons if every ROI have been deleted through medRoiManager
connect(medRoiManager::instance(), SIGNAL(allRoisDeleted()), this, SLOT(buttonsStateAtDataOpeningBeforeROI()));
}
polygonRoiToolBox::~polygonRoiToolBox()
{
delete hashViewObserver;
}
bool polygonRoiToolBox::registered()
{
return medToolBoxFactory::instance()->registerToolBox<polygonRoiToolBox>();
}
dtkPlugin* polygonRoiToolBox::plugin()
{
medPluginManager *pm = medPluginManager::instance();
dtkPlugin *plugin = pm->plugin ( "Polygon ROI" );
return plugin;
}
medAbstractData *polygonRoiToolBox::processOutput()
{
if (!m_maskData)
{
generateBinaryImage();
}
return m_maskData; // return output data
}
void polygonRoiToolBox::updateView()
{
disableButtons();
medAbstractView *view = this->getWorkspace()->tabbedViewContainers()->getFirstSelectedContainerView();
medAbstractImageView *v = qobject_cast<medAbstractImageView*>(view);
if (view)
{
// Toolbox does not work with meshes or vector images
for (unsigned int i=0; i<v->layersCount(); ++i)
{
medAbstractData *data = v->layerData(i);
if(!data || data->identifier().contains("vtkDataMesh")
|| !data->identifier().contains("itkDataImage") //avoid medVtkFibersData also
|| data->identifier().contains("itkDataImageVector"))
{
handleDisplayError(medAbstractProcessLegacy::DIMENSION_3D);
return;
}
}
// if data are not meshes
buttonsStateAtDataOpeningBeforeROI();
if (currentView != v)
{
bool repulsorOn = repulsorTool->isChecked();
if (repulsorOn)
{
repulsorTool->setChecked(false);
}
currentView = v;
// Handle new events with Roi management
roiManagementToolBox->setWorkspace(getWorkspace());
medRoiManager::instance()->setCurrentView(currentView);
roiManagementToolBox->updateView();
if(interactorStyleRepulsor != nullptr)
{
interactorStyleRepulsor->SetCurrentView(currentView);
}
if (repulsorOn)
{
repulsorTool->setChecked(true);
}
if (!hashViewObserver->contains(currentView))
{
contourWidgetObserver * observer = contourWidgetObserver::New();
observer->setView(static_cast<medVtkViewBackend*>(currentView->backend())->view2D);
observer->setToolBox(this);
hashViewObserver->insert(currentView,observer);
}
connect(currentView, SIGNAL(closed()), this, SLOT(onViewClosed()), Qt::UniqueConnection);
connect(currentView, SIGNAL(layerRemoved(unsigned int)), this, SLOT(onLayerClosed()), Qt::UniqueConnection);
}
}
}
void polygonRoiToolBox::onViewClosed()
{
medAbstractView *viewClosed = qobject_cast<medAbstractView*>(QObject::sender());
hashViewObserver->remove(viewClosed);
if (viewClosed == currentView)
{
currentView = nullptr;
}
m_maskData = nullptr;
disableButtons();
// If you close the last layer of a view through Layer Settings,
// here, the view is not removed yet.
roiManagementToolBox->clear();
interactorStyleRepulsor = nullptr;
}
void polygonRoiToolBox::onLayerClosed()
{
medAbstractView *view = this->getWorkspace()->tabbedViewContainers()->getFirstSelectedContainerView();
medAbstractImageView *v = qobject_cast<medAbstractImageView*>(view);
// We enter here only if onLayerClosed has not been called during a view removal
if (v && (v->layersCount() > 0))
{
currentView = v;
this->clear();
buttonsStateAtDataOpeningBeforeROI();
}
}
void polygonRoiToolBox::onAddNewCurve()
{
if (currentView)
{
if (!hashViewObserver->contains(currentView) || !hashViewObserver->value(currentView)->getCurrentPolygonRoi())
{
if (repulsorTool->isChecked() && addNewCurve->isChecked())
{
repulsorTool->setChecked(false);
}
vtkImageView2D *view2d = static_cast<medVtkViewBackend*>(currentView->backend())->view2D;
polygonRoi *roi = new polygonRoi(view2d);
vtkContourWidget *currentContour = roi->getContour();
contourWidgetObserver *observer = hashViewObserver->value(currentView);
observer->setCurrentPolygonRoi(roi);
currentContour->AddObserver(vtkCommand::StartInteractionEvent,observer); // todo put this observer in polygonRoi manage the adding to the roimanagementtoolbox through it and
currentContour->AddObserver(vtkCommand::EndInteractionEvent,observer);
roi->forceVisibilityOn();
}
}
}
void polygonRoiToolBox::activateRepulsor()
{
if (currentView)
{
if (repulsorTool->isChecked() && addNewCurve->isChecked())
{
addNewCurve->setChecked(false);
}
if (interactorStyleRepulsor == nullptr)
{
interactorStyleRepulsor = vtkInriaInteractorStylePolygonRepulsor::New();
interactorStyleRepulsor->SetCurrentView(currentView);
}
vtkImageView2D *view2D = static_cast<medVtkViewBackend*>(currentView->backend())->view2D;
if (repulsorTool->isChecked())
{
vtkInteractorStyleImageView2D *interactorStyle2D = vtkInteractorStyleImageView2D::SafeDownCast(view2D->GetInteractor()->GetInteractorStyle());
interactorStyleRepulsor->SetLeftButtonInteraction(interactorStyle2D->GetLeftButtonInteraction());
view2D->SetInteractorStyle(interactorStyleRepulsor);
view2D->SetupInteractor(view2D->GetInteractor()); // to reinstall vtkImageView2D pipeline
}
else
{
vtkInteractorStyleImageView2D *interactorStyle2D = vtkInteractorStyleImageView2D::New();
interactorStyle2D->SetLeftButtonInteraction(interactorStyleRepulsor->GetLeftButtonInteraction());
view2D->SetInteractorStyle(interactorStyle2D);
view2D->SetupInteractor(view2D->GetInteractor()); // to reinstall vtkImageView2D pipeline
interactorStyle2D->Delete();
}
}
}
QList<medSeriesOfRoi*> * polygonRoiToolBox::getListOfView(medAbstractView *view)
{
return medRoiManager::instance()->getSeriesOfRoi()->value(view);
}
void polygonRoiToolBox::copyContours()
{
medRoiManager * manager = medRoiManager::instance();
manager->setCurrentView(currentView);
manager->copy();
}
void polygonRoiToolBox::pasteContours()
{
medRoiManager * manager = medRoiManager::instance();
manager->setCurrentView(currentView);
manager->paste();
}
void polygonRoiToolBox::undo()
{
if (!currentView)
{
return;
}
medRoiManager::instance()->setCurrentView(currentView);
medRoiManager::instance()->undo();
currentView->render();
}
void polygonRoiToolBox::redo()
{
if (!currentView)
{
return;
}
medRoiManager::instance()->setCurrentView(currentView);
medRoiManager::instance()->redo();
currentView->render();
}
void polygonRoiToolBox::reorderPolygon(vtkPolyData *poly)
{
vtkImageView2D *view2d = static_cast<medVtkViewBackend*>(currentView->backend())->view2D;
double displayPoint[3];
double *worldPoint;
double xmin = VTK_DOUBLE_MAX;
int xminIndex = 0;
double ymin = VTK_DOUBLE_MAX;
int yminIndex = 0;
for(int i=0; i<poly->GetNumberOfPoints(); i++)
{
worldPoint = poly->GetPoint(i);
vtkInteractorObserver::ComputeWorldToDisplay(view2d->GetRenderer(), worldPoint[0], worldPoint[1], worldPoint[2], displayPoint);
if (displayPoint[0] < xmin)
{
xmin = displayPoint[0];
xminIndex= i;
}
if (displayPoint[1] < ymin)
{
ymin = displayPoint[1];
yminIndex= i;
}
}
int dist = xminIndex-yminIndex;
bool reverse =((abs(dist)>poly->GetNumberOfPoints()/2) != (dist<0));
vtkSmartPointer<vtkPoints> reorderedPoints = vtkSmartPointer<vtkPoints>::New();
vtkPoints *points = poly->GetPoints();
if (reverse)
{
for(int i=0; i<poly->GetNumberOfPoints(); i++)
{
double p[3];
points->GetPoint(xminIndex,p);
xminIndex--;
if (xminIndex < 0)
{
xminIndex = poly->GetNumberOfPoints()-1;
}
reorderedPoints->InsertNextPoint(p);
}
}
else
{
for(int i=0; i<poly->GetNumberOfPoints(); i++)
{
double p[3];
points->GetPoint(xminIndex, p);
xminIndex = (xminIndex+1) % poly->GetNumberOfPoints();
reorderedPoints->InsertNextPoint(p);
}
}
poly->SetPoints(reorderedPoints);
}
void polygonRoiToolBox::resampleCurve(vtkPolyData *poly,int nbPoints)
{
vtkSmartPointer<vtkParametricSpline> spline =vtkSmartPointer<vtkParametricSpline>::New();
poly->GetPoints()->InsertNextPoint(poly->GetPoints()->GetPoint(0));
spline->SetPoints(poly->GetPoints());
vtkPoints *points = vtkPoints::New();
double p[3];
double u[3];
for(int j=0; j<nbPoints+1; j++)
{
u[0] = u[1] = u[2] = j/(double)(nbPoints+1);
spline->Evaluate(u, p, nullptr);
points->InsertNextPoint(p);
}
poly->SetPoints(points);
}
QList<vtkPolyData* > polygonRoiToolBox::generateIntermediateCurves(vtkSmartPointer<vtkPolyData> curve1, vtkSmartPointer<vtkPolyData> curve2, int nb)
{
int max = curve2->GetNumberOfPoints();
vtkSmartPointer<vtkPolyData> startCurve = curve1, endCurve = curve2;
bool curve2ToCurve1 = false;
if (curve1->GetNumberOfPoints()>=curve2->GetNumberOfPoints())
{
max = curve1->GetNumberOfPoints();
startCurve = curve2;
endCurve = curve1;
curve2ToCurve1 = true;
}
//Homogenise the points distribution on the curve
resampleCurve(startCurve, max);
resampleCurve(endCurve, max);
reorderPolygon(startCurve);
reorderPolygon(endCurve);
vtkSmartPointer<vtkPoints> bufferPoints = vtkPoints::New();
QList<vtkPolyData*> list;
for(int i=1; i<=nb; i++)
{
vtkPolyData *poly = vtkPolyData::New();
vtkCellArray *cells = vtkCellArray::New();
vtkPolyLine *polyLine = vtkPolyLine::New();
polyLine->GetPointIds()->SetNumberOfIds(startCurve->GetNumberOfPoints());
bufferPoints->Reset();
for(int k=0; k<startCurve->GetNumberOfPoints(); k++)
{
double p1[3],p2[3],p3[3];
startCurve->GetPoint(k, p1);
endCurve->GetPoint(k, p2);
if (curve2ToCurve1)
{
p3[0]= p1[0] +(p2[0]-p1[0])*((i)/(double)(nb+1));
p3[1]= p1[1] +(p2[1]-p1[1])*((i)/(double)(nb+1));
p3[2]= p1[2] +(p2[2]-p1[2])*((i)/(double)(nb+1));
}
else
{
p3[0]= p2[0] +(p1[0]-p2[0])*((i)/(double)(nb+1));
p3[1]= p2[1] +(p1[1]-p2[1])*((i)/(double)(nb+1));
p3[2]= p2[2] +(p1[2]-p2[2])*((i)/(double)(nb+1));
}
bufferPoints->InsertNextPoint(p3);
polyLine->GetPointIds()->SetId(k, k);
}
cells->InsertNextCell(polyLine);
vtkPoints * polyPoints = vtkPoints::New();
polyPoints->DeepCopy(bufferPoints);
poly->SetPoints(polyPoints);
poly->SetLines(cells);
list.append(poly);
}
return list;
}
polygonRoiToolBox::ListRois polygonRoiToolBox::interpolateBetween2Polygon(const QList<polygonRoi*> &rois, int firstIndex)
{
ListRois outputRois;
polygonRoi * polyRoi;
vtkContourRepresentation* contour;
// Contour first ROI
polyRoi = rois.at(firstIndex);
contour = polyRoi->getContour()->GetContourRepresentation();
vtkSmartPointer<vtkPolyData> curveMin = contour->GetContourRepresentationAsPolyData();
int curveMinNbNode = contour->GetNumberOfNodes();
int minSlice = rois.at(firstIndex)->getIdSlice();
// Contour second ROI
polyRoi = rois.at(firstIndex+1);
contour = polyRoi->getContour()->GetContourRepresentation();
vtkSmartPointer<vtkPolyData> curveMax = contour->GetContourRepresentationAsPolyData();
int curveMaxNbNode = contour->GetNumberOfNodes();
int maxSlice = rois.at(firstIndex+1)->getIdSlice();
// Compute intermediate ROIs between two successive ROIs
QList<vtkPolyData *> listPolyData = generateIntermediateCurves(curveMax,curveMin,maxSlice-minSlice-1);
double number = ceil(1.5 * (double)(curveMinNbNode));
if (curveMaxNbNode > curveMinNbNode)
{
number = ceil(1.5 * (double)(curveMaxNbNode));
}
vtkImageView2D *view2d = static_cast<medVtkViewBackend*>(currentView->backend())->view2D;
for (int i = minSlice+1;i<maxSlice;i++)
{
polygonRoi *polyRoi = new polygonRoi(view2d);
vtkContourWidget *contour = polyRoi->getContour();
contour->SetEnabled(true);
// Points decimation // TODO put this in generateIntermediateCurves
int nbPointsPoly = listPolyData[i-(minSlice+1)]->GetNumberOfPoints();
int divPoly = (int)floor((double)nbPointsPoly/number);
vtkPoints * points = listPolyData[i-(minSlice+1)]->GetPoints();
vtkPoints * decimatedPoints = vtkPoints::New();
for (int k = nbPointsPoly-1; k>=0; k--)
{
if (k%divPoly==0)
{
decimatedPoints->InsertNextPoint(points->GetPoint(k));
}
}
listPolyData[i-(minSlice+1)]->SetPoints(decimatedPoints);
contour->Initialize(listPolyData[i-(minSlice+1)]);
vtkContourRepresentation *contourRep = contour->GetContourRepresentation();
int nbPoints = contourRep->GetNumberOfNodes();
contourRep->DeleteNthNode(nbPoints-1); // delete the last node, no need for that normally
contourRep->SetClosedLoop(1);
polyRoi->setIdSlice(i);
polyRoi->setMasterRoi(false);
outputRois.append(polyRoi);
}
return outputRois;
}
void polygonRoiToolBox::interpolateCurve()
{
if (currentView)
{
this->setToolBoxOnWaitStatusForNonRunnableProcess();
vtkImageView2D *view2d = static_cast<medVtkViewBackend*>(currentView->backend())->view2D;
typedef QList<medSeriesOfRoi*> ListOfSeriesOfRois;
ListRois *list;
ListOfSeriesOfRois *listSeries = medRoiManager::instance()->getSeriesOfRoi()->value(currentView);
// Get list of Rois
list = listSeries->at(0)->getListOfRois();
if (list && !list->isEmpty())
{
int orientation = view2d->GetViewOrientation();
QList<polygonRoi*> rois;
QList<polygonRoi*> masterRois;
QList<unsigned int> masterRoisIndexes;
for(int i=0; i<list->size(); i++)
{
polygonRoi *polyRoi = dynamic_cast<polygonRoi*>(list->at(i)); // TODO : need to test if the cast goes well we cannot be sure that the Rois are polygonRoi
if(!polyRoi->getContour()->GetContourRepresentation()->GetClosedLoop())
{
displayMessageError("Non-closed polygon at slice: " + QString::number(polyRoi->getIdSlice()+1) + ". Operation aborted");
this->setToolBoxOnReadyToUse();
return;
}
if (polyRoi->getOrientation() == orientation)
{
rois.append(polyRoi);
if(polyRoi->isMasterRoi())
{
masterRois.append(polyRoi);
masterRoisIndexes.append(i);//remember master ROIs positions
}
}
}
if(masterRois.size() >= 2)
{
//Let's remove the undesired ROIs
ListRois roisToBeRemoved;
for (unsigned int i=masterRoisIndexes.first(); i<=masterRoisIndexes.last(); i++)
{
if(!rois.at(i)->isMasterRoi()) //master ROIs shouldn't be removed
{
roisToBeRemoved.append(rois.at(i));
}
}
DeleteSeveralRoisCommand *deleteCommand = new DeleteSeveralRoisCommand(currentView,roisToBeRemoved,"Polygon rois","deleteSeveralRois");
medRoiManager::instance()->addToUndoRedoStack(deleteCommand);
// Compute interpolation between master ROIs
ListRois interpolationOutput;
for(int i=0 ; i<masterRois.size()-1 ; i++)
{
ListRois outputRois = interpolateBetween2Polygon(masterRois, i);
interpolationOutput.append(outputRois);
}
// Send signal of new Rois to medRoiManager
AddSeveralRoisCommand *command = new AddSeveralRoisCommand(currentView, interpolationOutput, "Polygon rois", "NewRois");
medRoiManager::instance()->addToUndoRedoStack(command);
}
else
{
displayMessageError("Interpolate needs at least 2 master ROIs");
}
}
this->setToolBoxOnReadyToUse();
}
}
void polygonRoiToolBox::generateBinaryImage()
{
if (currentView)
{
vtkImageView2D *view2d = static_cast<medVtkViewBackend*>(currentView->backend())->view2D;
QList<medSeriesOfRoi*> *listROI = getListOfView(currentView);
if (!listROI || listROI->isEmpty())
{
return; // check if ROI or not
}
ListRois *list = listROI->at(0)->getListOfRois();
QList<QPair<vtkPolyData *,PlaneIndexSlicePair> > listPolyData = QList<QPair<vtkPolyData *,PlaneIndexSlicePair> >();
int orientation = view2d->GetViewOrientation();
for(int i=0; i<list->size(); i++)
{
polygonRoi *polyRoi = dynamic_cast<polygonRoi*>(list->at(i)); // TODO : need to test if the cast goes well we cannot be sure that the Rois are polygonRoi
vtkContourWidget *contour = polyRoi->getContour();
unsigned int orientationOfRoi = polyRoi->getOrientation();
unsigned int idSlice = polyRoi->getIdSlice();
if (viewsPlaneIndex.empty())
{
return;
}
unsigned char planeIndex = viewsPlaneIndex.value(currentView)->at(orientationOfRoi);
vtkContourRepresentation *contourRep = contour->GetContourRepresentation();
view2d->SetViewOrientation(orientationOfRoi); // we set the view Orientation to the orientation of the ROI, to retreive the polyData with world coordinates based on the display from the orientation.
listPolyData.append(QPair<vtkPolyData*,PlaneIndexSlicePair>(contourRep->GetContourRepresentationAsPolyData(),PlaneIndexSlicePair(idSlice,planeIndex)));
}
view2d->SetViewOrientation(orientation);
QList<QPair<vtkPolygon*,PlaneIndexSlicePair> > listPolygon = createImagePolygons(listPolyData);
binaryImageFromPolygon(listPolygon);
}
}
void polygonRoiToolBox::generateAndSaveBinaryImage()
{
generateBinaryImage();
medDataManager::instance()->importData(m_maskData, false);
}
QList<QPair<vtkPolygon*,polygonRoiToolBox::PlaneIndexSlicePair> > polygonRoiToolBox::createImagePolygons(QList<QPair<vtkPolyData*,PlaneIndexSlicePair> > &listPoly)
{
vtkImageView2D *view2d = static_cast<medVtkViewBackend*>(currentView->backend())->view2D;
QList<QPair<vtkPolygon*,PlaneIndexSlicePair> > listPolygon = QList<QPair<vtkPolygon*,PlaneIndexSlicePair> >();
for(int i=0; i<listPoly.size(); i++)
{
vtkPolygon *polygon = vtkPolygon::New();
vtkPoints *points = vtkPoints::New();
const int nb = listPoly.at(i).first->GetNumberOfPoints();
vtkIdType ids[1000];
double imagePreviousPoint[3] ={0,0,0};
unsigned int nbPoint = 0;
unsigned int x1=0, y1=0, z1=0;
switch (listPoly.at(i).second.second)
{
case 0 :
{
x1=1;
y1=2;
z1=0;
break;
}
case 1 :
{
x1=0;
y1=2;
z1=1;
break;
}
case 2 :
{
x1=0;
y1=1;
z1=2;
break;
}
}
for(int j=0; j<nb; j++)
{
double *point = listPoly.at(i).first->GetPoint(j);
int imagePoint[3];
double imagePointDouble[3];
view2d->GetImageCoordinatesFromWorldCoordinates(point,imagePoint);
imagePointDouble[x1]= (double)imagePoint[x1];
imagePointDouble[y1]= (double)imagePoint[y1];
imagePointDouble[z1]= (double)listPoly.at(i).second.first;
if (imagePointDouble[x1] == imagePreviousPoint[x1] && imagePointDouble[y1] == imagePreviousPoint[y1] && imagePointDouble[z1] == imagePreviousPoint[z1])
{
continue;
}
points->InsertNextPoint(imagePointDouble);
ids[nbPoint]=nbPoint;
nbPoint++;
imagePreviousPoint[x1] = imagePointDouble[x1];
imagePreviousPoint[y1] = imagePointDouble[y1];
imagePreviousPoint[z1] = imagePointDouble[z1];
}
polygon->Initialize(points->GetNumberOfPoints(), ids, points);
listPolygon.append(QPair<vtkPolygon*,PlaneIndexSlicePair>(polygon,listPoly.at(i).second));
}
return listPolygon;
}
void polygonRoiToolBox::binaryImageFromPolygon(QList<QPair<vtkPolygon*,PlaneIndexSlicePair> > polys)
{
m_maskData = medAbstractDataFactory::instance()->create( "itkDataImageUChar3" );
medAbstractImageData *inputData = qobject_cast<medAbstractImageData*>(currentView->layerData(currentView->currentLayer()));// TODO : currentlayer looks dangerous
if (!inputData)
{
qDebug()<<"polygonRoiToolBox::binaryImageFromPolygon data error.";
return;
}
initializeMaskData(inputData,m_maskData);
UChar3ImageType::Pointer m_itkMask = dynamic_cast<UChar3ImageType*>( reinterpret_cast<itk::Object*>(m_maskData->data()) );
for(int k=0; k<polys.size(); k++)
{
double bounds[6];
polys[k].first->GetBounds(bounds);
unsigned int x=0, y=0, z=0;
unsigned int bx=0, by=0;
unsigned int dimX=0, dimY=0;
switch (polys[k].second.second)
{
case 0 :
{
dimX = inputData->yDimension();
dimY = inputData->zDimension();
x = 1;
y = 2;
z = 0;
bx = 2;
by = 4;
break;
}
case 1 :
{
dimX = inputData->xDimension();
dimY = inputData->zDimension();
x = 0;
y = 2;
z = 1;
bx = 0;
by = 4;
break;
}
case 2 :
{
dimX = inputData->xDimension();
dimY = inputData->yDimension();
x = 0;
y = 1;
z = 2;
bx = 0;
by = 2;
break;
}
}
// Qt rasterization
int nbPoints = polys[k].first->GetPoints()->GetNumberOfPoints();
vtkPoints *pointsArray = polys[k].first->GetPoints();
QPolygonF polygon;
for(int i=0; i<nbPoints; i++)
{
polygon << QPointF(pointsArray->GetPoint(i)[x], pointsArray->GetPoint(i)[y]);
}
QPainterPath path;
path.addPolygon(polygon);
QBrush brush;
brush.setColor(Qt::white);
brush.setStyle(Qt::SolidPattern);
QImage imagePolygon(dimX,dimY,QImage::Format_RGB16);
imagePolygon.fill(Qt::black);
QPainter painter;
painter.begin(&imagePolygon);
painter.fillPath(path,brush);
for(int i=bounds[bx]; i<=bounds[bx+1]; i++)
{
for(int j=bounds[by]; j<=bounds[by+1]; j++)
{
QRgb val = imagePolygon.pixel(i,j);
if (val==qRgb(255,255,255))
{
UChar3ImageType::IndexType index;
index[x]=i;
index[y]=j;
index[z]=polys[k].second.first;
m_itkMask->SetPixel(index,1);
}
}
}
}
medUtilities::setDerivedMetaData(m_maskData, inputData, "polygon roi");
}
void polygonRoiToolBox::initializeMaskData( medAbstractData *imageData, medAbstractData *maskData )
{
UChar3ImageType::Pointer mask = UChar3ImageType::New();
Q_ASSERT(mask->GetImageDimension() == 3);
medAbstractImageData *mImage = qobject_cast<medAbstractImageData*>(imageData);
Q_ASSERT(mImage);
UChar3ImageType::RegionType region;
region.SetSize(0, ( mImage->Dimension() > 0 ? mImage->xDimension() : 1 ) );
region.SetSize(1, ( mImage->Dimension() > 1 ? mImage->yDimension() : 1 ) );
region.SetSize(2, ( mImage->Dimension() > 2 ? mImage->zDimension() : 1 ) );
UChar3ImageType::DirectionType direction;
UChar3ImageType::SpacingType spacing;
UChar3ImageType::PointType origin;
direction.Fill(0);
spacing.Fill(0);
origin.Fill(0);
for (unsigned int i = 0; i < mask->GetImageDimension(); ++i)
{
direction(i,i) = 1;
}
unsigned int maxIndex = std::min<unsigned int>(mask->GetImageDimension(),mImage->Dimension());
switch (mImage->Dimension())
{
case 2:
{
itk::ImageBase <2> * imageDataOb = dynamic_cast<itk::ImageBase <2> *>( reinterpret_cast<itk::Object*>(imageData->data()) );
for (unsigned int i = 0; i < maxIndex; ++i)
{
for (unsigned int j = 0; j < maxIndex; ++j)
{
direction(i,j) = imageDataOb->GetDirection()(i,j);
}
spacing[i] = imageDataOb->GetSpacing()[i];
origin[i] = imageDataOb->GetOrigin()[i];
}
break;
}
case 4:
{
itk::ImageBase <4> * imageDataOb = dynamic_cast<itk::ImageBase <4> *>( reinterpret_cast<itk::Object*>(imageData->data()) );
for (unsigned int i = 0; i < maxIndex; ++i)
{
for (unsigned int j = 0; j < maxIndex; ++j)
{
direction(i,j) = imageDataOb->GetDirection()(i,j);
}
spacing[i] = imageDataOb->GetSpacing()[i];
origin[i] = imageDataOb->GetOrigin()[i];
}
break;
}
case 3:
default:
{
itk::ImageBase <3> *imageDataOb = dynamic_cast<itk::ImageBase <3> *>( reinterpret_cast<itk::Object*>(imageData->data()) );
for (unsigned int i = 0; i < maxIndex; ++i)
{
for (unsigned int j = 0; j < maxIndex; ++j)
{
direction(i,j) = imageDataOb->GetDirection()(i,j);
}
spacing[i] = imageDataOb->GetSpacing()[i];
origin[i] = imageDataOb->GetOrigin()[i];
}
break;
}
}
mask->SetOrigin(origin);
mask->SetDirection(direction);
mask->SetSpacing(spacing);
mask->SetLargestPossibleRegion(region);
mask->SetBufferedRegion(region);
mask->Allocate();
mask->FillBuffer(0);
maskData->setData((QObject*)(mask.GetPointer()));
}
int polygonRoiToolBox::computePlaneIndex()
{
typedef UChar3ImageType::DirectionType::InternalMatrixType::element_type ElemType;
vtkImageView2D *view2d = static_cast<medVtkViewBackend*>(currentView->backend())->view2D;
int planeIndex = -1;
if (currentView->is2D())
{
const QVector3D vpn = currentView->viewPlaneNormal();
vnl_vector_fixed<ElemType, 3> vecVpn(vpn.x(), vpn.y(), vpn.z() );
vtkMatrix4x4 *direction = view2d->GetOrientationMatrix();
double absDotProductMax = 0;
planeIndex = 0;
for (unsigned int i = 0; i < 3; ++i)
{
double dotProduct = 0;
for (unsigned int j = 0; j < 3; ++j)
{
dotProduct += direction->GetElement(j,i) * vecVpn[j];
}
if (fabs(dotProduct) > absDotProductMax)
{
planeIndex = i;
absDotProductMax = fabs(dotProduct);
}
}
}
return planeIndex;
}
void polygonRoiToolBox::disableButtons()
{
addNewCurve->setEnabled(false);
addNewCurve->setChecked(false);
repulsorTool->setEnabled(false);
repulsorTool->setChecked(false);
generateBinaryImage_button->setEnabled(false);
interpolate->setEnabled(false);
extractRoiButton->setEnabled(false);
}
void polygonRoiToolBox::clear()
{
medToolBox::clear();
if(currentView)
{
// We need to update the medSliderL
roiManagementToolBox->updateView();
ListRois *list;
QList<medSeriesOfRoi*> *listSeries = medRoiManager::instance()->getSeriesOfRoi()->value(currentView);
if(listSeries != nullptr
&& listSeries->count() > 0
&& listSeries->at(0)->getListOfRois()->size() != 0)
{
// Get list of Rois
list = listSeries->at(0)->getListOfRois();
DeleteSeveralRoisCommand * deleteCommand = new DeleteSeveralRoisCommand(currentView,*list,"Polygon rois","deleteSeveralRois");
medRoiManager::instance()->addToUndoRedoStack(deleteCommand);
}
currentView = nullptr;
}
m_maskData = nullptr;
disableButtons();
}
void polygonRoiToolBox::buttonsStateAtDataOpeningBeforeROI()
{
// At opening of a data, before first ROI
disableButtons();
addNewCurve->setEnabled(true);
extractRoiButton->setEnabled(true);
}
void polygonRoiToolBox::buttonsStateWhenROI()
{
addNewCurve->setEnabled(true);
extractRoiButton->setEnabled(true);
repulsorTool->setEnabled(true);
interpolate->setEnabled(true);
generateBinaryImage_button->setEnabled(true);
}
template <class ImageType> UChar3ImageType::Pointer cast(medAbstractData *input)
{
typedef itk::CastImageFilter< ImageType, UChar3ImageType > CasterType;
typename CasterType::Pointer caster = CasterType::New();
caster->SetInput(dynamic_cast< ImageType*>((itk::Object*)(input->data())));
caster->Update();
return caster->GetOutput();
}
UChar3ImageType::Pointer extract2dContour(UChar3ImageType::Pointer input)
{
typedef itk::Image <unsigned char, 2> Mask2dType;
typedef itk::MinimumMaximumImageCalculator <UChar3ImageType> ImageCalculatorFilterType;
ImageCalculatorFilterType::Pointer imageCalculatorFilter
= ImageCalculatorFilterType::New ();
imageCalculatorFilter->SetImage(input);
imageCalculatorFilter->Compute();
// Check if the dataset is a mask
itk::ImageRegionIterator<UChar3ImageType> it(input, input->GetRequestedRegion() );
while(!it.IsAtEnd())
{
if ((it.Get() != imageCalculatorFilter->GetMinimum())
&& (it.Get() != imageCalculatorFilter->GetMaximum()))
{
// Odd values have been found. The dataset is not a mask
return nullptr;
}
++it;
}
typedef itk::BinaryContourImageFilter <Mask2dType, Mask2dType> binaryContourImageFilterType;
binaryContourImageFilterType::Pointer contourFilter = binaryContourImageFilterType::New ();
contourFilter->SetBackgroundValue(imageCalculatorFilter->GetMinimum());
contourFilter->SetForegroundValue(imageCalculatorFilter->GetMaximum());
typedef itk::SliceBySliceImageFilter< UChar3ImageType, UChar3ImageType> SbSFilterType;
SbSFilterType::Pointer sliceBySliceFilter = SbSFilterType::New();
sliceBySliceFilter->SetFilter( contourFilter );
sliceBySliceFilter->SetInput( input );
sliceBySliceFilter->Update();
return sliceBySliceFilter->GetOutput();
}
UChar3ImageType::Pointer polygonRoiToolBox::castToUChar3(medAbstractImageData *input)
{
if (!input)
{
displayMessageError("No input found!");
return nullptr;
}
QString id = input->identifier();
UChar3ImageType::Pointer img = UChar3ImageType::New();
if ( id == "itkDataImageChar3" )
{
img = cast<itk::Image <char,3> >(input);
}
else if ( id == "itkDataImageUChar3" )
{
img = dynamic_cast< UChar3ImageType*>((itk::Object*)(input->data()));
}
else if ( id == "itkDataImageShort3" )
{
img = cast<itk::Image <short,3> >(input);
}
else if ( id == "itkDataImageUShort3" )
{
img = cast<itk::Image <unsigned short,3> >(input);
}
else if ( id == "itkDataImageInt3" )
{
img = cast<itk::Image <int,3> >(input);
}
else if ( id == "itkDataImageUInt3" )
{
img = cast<itk::Image <unsigned int,3> >(input);
}
else if ( id == "itkDataImageLong3" )
{
img = cast<itk::Image <long,3> >(input);
}
else if ( id == "itkDataImageULong3" )
{
img = cast<itk::Image <unsigned long,3> >(input);
}
else if ( id == "itkDataImageFloat3" )
{
img = cast<itk::Image <float,3> >(input);
}
else if ( id == "itkDataImageDouble3" )
{
img = cast<itk::Image <double,3> >(input);
}
else
{
displayMessageError("Pixel type not yet implemented");
img = nullptr;
}
return img;
}
void polygonRoiToolBox::showExtractROIWarningPopUp()
{
QMessageBox msgBox;
msgBox.setWindowTitle("Extract ROI error");
msgBox.setIcon(QMessageBox::Warning);
msgBox.setText("An error occured, please check that your current layer is a mask.");
msgBox.exec();
}
void polygonRoiToolBox::extractROI()
{
this->setToolBoxOnWaitStatusForNonRunnableProcess();
medAbstractImageData *input = qobject_cast<medAbstractImageData*>(currentView->layerData(currentView->currentLayer()));
UChar3ImageType::Pointer img = castToUChar3(input);
if (img)
{
UChar3ImageType::Pointer contourImage = extract2dContour(img);
if (contourImage)
{
UChar3ImageType::SizeType size = contourImage->GetLargestPossibleRegion().GetSize();
UChar3ImageType::IndexType px;
vtkImageView2D *view2d = static_cast<medVtkViewBackend*>(currentView->backend())->view2D;
vtkSmartPointer<vtkPoints> bufferPoints = vtkPoints::New();
for (unsigned int sl=0 ; sl<size[2] ; sl++) // go through slices
{
bufferPoints->Reset();
bool isEmpty = true;
for (unsigned int y=0 ; y<size[1] ; y++)
{
for (unsigned int x=0 ; x<size[0] ; x++)
{
px[0] = x;
px[1] = y;
px[2] = sl;
if (contourImage->GetPixel(px) != 0)
{
addPointToBuffer(view2d, bufferPoints, px);
isEmpty = false;
break;
}
}
if (!isEmpty)
{
break;
}
}
if (!isEmpty)
{
// Contour indices are added into bufferPoints
getContourIndices(view2d, contourImage, px, bufferPoints);
vtkPoints *polyPoints = vtkPoints::New();
polyPoints->DeepCopy(bufferPoints);
// Create a cell array to connect the points into meaningful geometry
int numPts = polyPoints->GetNumberOfPoints();
vtkIdType* vertexIndices = new vtkIdType[numPts+1];
for (int i = 0; i < numPts; i++)
{
vertexIndices[i] = static_cast<vtkIdType>(i);
}
// Set the last vertex to 0; thus closing the circle.
vertexIndices[numPts] = 0;
vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New();
lines->InsertNextCell(numPts+1, vertexIndices);
vtkPolyData *poly = vtkPolyData::New();
poly->SetPoints(polyPoints);
poly->SetLines(lines);
// Points decimation
int nbPointsPoly = poly->GetNumberOfPoints();
vtkPoints *points = poly->GetPoints();
vtkPoints *decimatedPoints = vtkPoints::New();
for (int k = nbPointsPoly-1; k >= 0; k--)
{
if (k % HANDLE_PERIOD == 0) //one handle every HANDLE_PERIOD points
{
decimatedPoints->InsertNextPoint(points->GetPoint(k));
}
}
poly->SetPoints(decimatedPoints);
polygonRoi *polyRoi = new polygonRoi(view2d);
vtkContourWidget *contour = polyRoi->getContour();
contour->Initialize(poly);
vtkContourRepresentation *contourRep = contour->GetContourRepresentation();
contourRep->SetClosedLoop(1);
if (!viewsPlaneIndex.contains(currentView))
{
QList<int> *planeIndexes = new QList<int>();
for (int i = 0; i < 3; i++)
{
planeIndexes->append(0); // fill the list with 0
}
viewsPlaneIndex.insert(currentView,planeIndexes);
}
polyRoi->setIdSlice(sl);
polyRoi->setOrientation(view2d->GetViewOrientation());
polyRoi->setMasterRoi(false);
polyRoi->forceVisibilityOff();
// Save PlaneIndex for this view and orientation
AddRoiCommand *command = new AddRoiCommand(currentView, polyRoi,"Polygon rois","NewRois");
medRoiManager::instance()->addToUndoRedoStack(command);
QList<int> *planeIndexes= viewsPlaneIndex.value(currentView);
planeIndexes->replace(view2d->GetViewOrientation(),computePlaneIndex());
buttonsStateWhenROI();
}
}
}
else
{
showExtractROIWarningPopUp();
}
}
this->setToolBoxOnReadyToUse();
}
void polygonRoiToolBox::addPointToBuffer(vtkImageView2D *view2d, vtkSmartPointer<vtkPoints> bufferPoints, itk::ImageBase<3>::IndexType point)
{
double worldPoint[3];
int displayPoint[3];
displayPoint[0] = point[0];
displayPoint[1] = point[1];
displayPoint[2] = point[2];
view2d->GetWorldCoordinatesFromImageCoordinates(displayPoint, worldPoint);
bufferPoints->InsertNextPoint(worldPoint[0], worldPoint[1], worldPoint[2]);
}
void polygonRoiToolBox::getContourIndices(vtkImageView2D *view2d, UChar3ImageType::Pointer contourImage, UChar3ImageType::IndexType px, vtkSmartPointer<vtkPoints> bufferPoints)
{
UChar3ImageType::IndexType px2 = px;
do
{
UChar3ImageType::IndexType pxLeft, pxBottomLeft, pxBottom, pxBottomRight, pxRight, pxTopRight, pxTop, pxTopLeft;
pxLeft = pxBottomLeft = pxBottom = pxBottomRight = pxRight = pxTopRight = pxTop = pxTopLeft = px2;
pxLeft[0] = px2[0]-1;
pxBottomLeft[0] = px2[0]-1;
pxBottomLeft[1] = px2[1]+1;
pxBottom[1] = px2[1]+1;
pxBottomRight[0] = px2[0]+1;
pxBottomRight[1] = px2[1]+1;
pxRight[0] = px2[0]+1;
pxTopRight[0] = px2[0]+1;
pxTopRight[1] = px2[1]-1;
pxTop[1] = px2[1]-1;
pxTopLeft[0] = px2[0]-1;
pxTopLeft[1] = px2[1]-1;
if (contourImage->GetPixel(pxLeft) != 0)
{
px2 = pxLeft;
}
else if (contourImage->GetPixel(pxBottomLeft) != 0)
{
px2 = pxBottomLeft;
}
else if (contourImage->GetPixel(pxBottom) != 0)
{
px2 = pxBottom;
}
else if (contourImage->GetPixel(pxBottomRight) != 0)
{
px2 = pxBottomRight;
}
else if (contourImage->GetPixel(pxRight) != 0)
{
px2 = pxRight;
}
else if (contourImage->GetPixel(pxTopRight) != 0)
{
px2 = pxTopRight;
}
else if (contourImage->GetPixel(pxTop) != 0)
{
px2 = pxTop;
}
else if (contourImage->GetPixel(pxTopLeft) != 0)
{
px2 = pxTopLeft;
}
else
break;
addPointToBuffer(view2d, bufferPoints, px2);
contourImage->SetPixel(px2, 0);
}
while (px2 != px);
}
| 33.656707
| 210
| 0.598378
|
dmargery
|
e624a89710befc48421b040d0e9cc7b05070d8ec
| 1,093
|
cpp
|
C++
|
carmen_hardware/firmware/test/test_control_loop.cpp
|
AndriyPt/carmen
|
1b6beb70492604e41a079ea4054c68c0c8f30bdd
|
[
"MIT"
] | 2
|
2019-12-25T21:41:17.000Z
|
2020-03-03T16:14:20.000Z
|
carmen_hardware/firmware/test/test_control_loop.cpp
|
AndriyPt/carmen
|
1b6beb70492604e41a079ea4054c68c0c8f30bdd
|
[
"MIT"
] | null | null | null |
carmen_hardware/firmware/test/test_control_loop.cpp
|
AndriyPt/carmen
|
1b6beb70492604e41a079ea4054c68c0c8f30bdd
|
[
"MIT"
] | 1
|
2019-12-19T15:37:31.000Z
|
2019-12-19T15:37:31.000Z
|
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "gmock-global/gmock-global.h"
#include <string>
#include "error.h"
#include <stdexcept>
#include "control_loop.h"
#include "osal.h"
#include "osal_control_loop.h"
using ::testing::NotNull;
using ::testing::Gt;
using ::testing::Throw;
MOCK_GLOBAL_FUNC3(generate_error, void(error_types_t, uint8_t*, uint32_t));
MOCK_GLOBAL_FUNC2(osal_control_loop_create_thread, void(osal_control_loop_function_t, uint16_t));
MOCK_GLOBAL_FUNC1(osal_control_loop_queue_put, osal_control_loop_status_t(const osal_cl_message_t*));
MOCK_GLOBAL_FUNC2(osal_control_loop_queue_get, osal_control_loop_status_t(osal_cl_message_t*, uint32_t));
TEST(TestSuite, initializationTestCase)
{
ON_GLOBAL_CALL(generate_error, generate_error(ERROR_SOFTWARE, NotNull(), Gt(0))).WillByDefault(Throw(
std::exception()));
EXPECT_GLOBAL_CALL(osal_control_loop_create_thread, osal_control_loop_create_thread(NotNull(), 10)).Times(1);
control_loop_init();
}
int main(int argc, char **argv)
{
::testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}
| 30.361111
| 111
| 0.792315
|
AndriyPt
|
e62c4db52e4f6990efa423f87f09922b8ff86823
| 288
|
hpp
|
C++
|
Libraries/Macaronlib/include/Macaronlib/MemoryUtils/Memcpy.hpp
|
Plunkerusr/podsOS
|
b68e2ebdaa4eb99366dea6cc5509ba0c92c3601a
|
[
"MIT"
] | null | null | null |
Libraries/Macaronlib/include/Macaronlib/MemoryUtils/Memcpy.hpp
|
Plunkerusr/podsOS
|
b68e2ebdaa4eb99366dea6cc5509ba0c92c3601a
|
[
"MIT"
] | null | null | null |
Libraries/Macaronlib/include/Macaronlib/MemoryUtils/Memcpy.hpp
|
Plunkerusr/podsOS
|
b68e2ebdaa4eb99366dea6cc5509ba0c92c3601a
|
[
"MIT"
] | null | null | null |
#pragma once
#include "../Common.hpp"
#ifdef __i386__
#include "Memcpy.x86.hpp"
#else
#include "Memcpy.aarch32.hpp"
#endif
[[gnu::always_inline]] inline void inline_memcpy(void* write, const void* read, size_t count)
{
inline_memcpy_impl((char*)write, (const char*)read, count);
}
| 19.2
| 93
| 0.71875
|
Plunkerusr
|
e62c7f3a2fd6c3b36805a11b0d19925998feb42f
| 1,093
|
hpp
|
C++
|
Source/Runtime/Core/Public/Math/Util.hpp
|
Othereum/NoEngineGame
|
e3c9c9a330ba8e724cd96f98355b556d24e73d9d
|
[
"MIT"
] | 23
|
2020-05-21T06:25:29.000Z
|
2021-04-06T03:37:28.000Z
|
Source/Runtime/Core/Public/Math/Util.hpp
|
Othereum/NoEngineGame
|
e3c9c9a330ba8e724cd96f98355b556d24e73d9d
|
[
"MIT"
] | 72
|
2020-06-09T04:46:27.000Z
|
2020-12-07T03:20:51.000Z
|
Source/Runtime/Core/Public/Math/Util.hpp
|
Othereum/NoEngineGame
|
e3c9c9a330ba8e724cd96f98355b556d24e73d9d
|
[
"MIT"
] | 4
|
2020-06-10T02:23:54.000Z
|
2022-03-28T07:22:08.000Z
|
#pragma once
#include "Angle.hpp"
#include "Quat.hpp"
#include "Vector.hpp"
namespace otm
{
template <class Float>
Angle<RadR> V2HFov(Angle<RadR> vfov, Vector<Float, 2> scr)
{
return 2 * Atan(Tan(vfov / 2) * (scr[0] / scr[1]));
}
template <class Float>
Angle<RadR> H2VFov(Angle<RadR> hfov, Vector<Float, 2> scr)
{
return 2 * Atan(Tan(hfov / 2) * (scr[1] / scr[0]));
}
[[nodiscard]] Angle<RadR, CommonFloat<T>> ToAngle() const noexcept
{
auto& v = static_cast<const Vector<T, 2>&>(*this);
return Atan2(v[1], v[0]);
}
template <class F>
[[nodiscard]] Vector<std::common_type_t<T, F>, 3> RotatedBy(const Quaternion<F>& q) const noexcept
{
using Tf = std::common_type_t<T, F>;
auto& vr = static_cast<const Vector<T, 3>&>(*this);
const auto p = Quaternion<Tf>{Vector<Tf, 3>{vr}, 0};
return (q * p * ~q).v;
}
template <class F>
void RotateBy(const Quaternion<F>& q) noexcept
{
static_assert(
std::is_same_v<std::remove_cvref_t<decltype(this->RotatedBy())>, std::remove_cvref_t<decltype(*this)>>);
*this = this->RotatedBy(q);
}
} // namespace otm
| 25.418605
| 112
| 0.644099
|
Othereum
|
e63311d87857445431058ea980d30bb66ebfdd20
| 3,337
|
hpp
|
C++
|
include/crypto/RSA.hpp
|
Jonas4420/Crypto
|
4fda1854c838407e6cbfb0ffaf862609eaac203a
|
[
"MIT"
] | null | null | null |
include/crypto/RSA.hpp
|
Jonas4420/Crypto
|
4fda1854c838407e6cbfb0ffaf862609eaac203a
|
[
"MIT"
] | null | null | null |
include/crypto/RSA.hpp
|
Jonas4420/Crypto
|
4fda1854c838407e6cbfb0ffaf862609eaac203a
|
[
"MIT"
] | null | null | null |
#ifndef CRYPTO_RSA_H
#define CRYPTO_RSA_H
#include "crypto/BigNum.hpp"
#include <stdexcept>
#include <utility>
#include <cstring>
namespace Crypto
{
class RSA
{
public:
class RSAPublicKey
{
public:
RSAPublicKey(const BigNum&, const BigNum&);
RSAPublicKey(const uint8_t*, std::size_t);
bool operator==(const RSAPublicKey&) const;
int to_binary(uint8_t*, std::size_t&) const;
bool is_valid(void) const;
std::size_t bitlen(void) const;
std::size_t size(void) const;
friend RSA;
protected:
BigNum n;
BigNum e;
};
class RSAPrivateKey
{
public:
RSAPrivateKey(const BigNum&, const BigNum&, const BigNum&, bool = true);
RSAPrivateKey(const BigNum&, const BigNum&,
const BigNum&,const BigNum&, const BigNum&,
const BigNum&, const BigNum&, const BigNum&);
RSAPrivateKey(const uint8_t*, std::size_t);
bool operator==(const RSAPrivateKey&) const;
int to_binary(uint8_t*, std::size_t&) const;
bool is_valid(int (*)(void *, uint8_t*, std::size_t) = NULL, void* = NULL) const;
std::size_t bitlen(void) const;
std::size_t size(void) const;
friend RSA;
protected:
BigNum n;
BigNum e;
BigNum d;
BigNum p;
BigNum q;
BigNum dp;
BigNum dq;
BigNum qp;
};
/* Key pair operations */
static std::pair<RSAPublicKey, RSAPrivateKey> gen_keypair(int (*)(void *, uint8_t*, std::size_t), void*,
std::size_t, const BigNum&);
static bool is_valid(const std::pair<const RSAPublicKey&, const RSAPrivateKey&>&,
int (*)(void *, uint8_t*, std::size_t) = NULL, void* = NULL);
/* Textbook RSA */
static inline int RSAEP(const RSAPublicKey &pubKey, const uint8_t *input, std::size_t input_sz,
uint8_t *output, std::size_t &output_sz)
{
return Encrypt(pubKey, input, input_sz, output, output_sz);
}
static inline int RSADP(const RSAPrivateKey &privKey, const uint8_t *input, std::size_t input_sz,
uint8_t *output, std::size_t &output_sz)
{
return Decrypt(privKey, input, input_sz, output, output_sz);
}
static inline int RSASP1(const RSAPrivateKey &privKey, const uint8_t *input, std::size_t input_sz,
uint8_t *output, std::size_t &output_sz)
{
return Decrypt(privKey, input, input_sz, output, output_sz);
}
static inline int RSAVP1(const RSAPublicKey &pubKey, const uint8_t *input, std::size_t input_sz,
uint8_t *output, std::size_t &output_sz)
{
return Encrypt(pubKey, input, input_sz, output, output_sz);
}
class Exception : public std::runtime_error
{
public:
Exception(const char *what_arg) : std::runtime_error(what_arg) {}
};
static const int CRYPTO_RSA_SUCCESS = 0x00;
static const int CRYPTO_RSA_INVALID_LENGTH = 0x01;
static const int CRYPTO_RSA_OUT_OF_RANGE = 0x02;
static const int CRYPTO_RSA_MESSAGE_TOO_LONG = 0x03;
static const int CRYPTO_RSA_DECRYPTION_ERROR = 0x04;
static const int CRYPTO_RSA_RNG_ERROR = 0x05;
protected:
static void zeroize(void *v, std::size_t n)
{
volatile uint8_t *p = static_cast<uint8_t*>(v);
while ( n-- ) {
*p++ = 0x00;
}
}
static int Encrypt(const RSAPublicKey&, const uint8_t*, std::size_t, uint8_t*, std::size_t&);
static int Decrypt(const RSAPrivateKey&, const uint8_t*, std::size_t, uint8_t*, std::size_t&);
};
}
#endif
| 26.070313
| 106
| 0.679652
|
Jonas4420
|
e63f92383882e87835d459f23c6d683e669ea5e2
| 533
|
cpp
|
C++
|
leetcode/832. Flipping an Image/s1.cpp
|
joycse06/LeetCode-1
|
ad105bd8c5de4a659c2bbe6b19f400b926c82d93
|
[
"Fair"
] | 1
|
2021-02-09T11:38:51.000Z
|
2021-02-09T11:38:51.000Z
|
leetcode/832. Flipping an Image/s1.cpp
|
contacttoakhil/LeetCode-1
|
9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c
|
[
"Fair"
] | null | null | null |
leetcode/832. Flipping an Image/s1.cpp
|
contacttoakhil/LeetCode-1
|
9bb9b5aa9ace836b86a752eb796b3dfcb21ee44c
|
[
"Fair"
] | 1
|
2021-03-25T17:11:14.000Z
|
2021-03-25T17:11:14.000Z
|
// OJ: https://leetcode.com/problems/flipping-an-image/
// Author: github.com/lzl124631x
// Time: O(MN)
// Space: O(1)
class Solution {
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
if (A.empty() || A[0].empty()) return {};
int M = A.size(), N = A[0].size();
vector<vector<int>> v(M, vector<int>(N));
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
v[i][N - j - 1] = 1 - A[i][j];
}
}
return v;
}
};
| 29.611111
| 68
| 0.469043
|
joycse06
|
e63fcf88f1ae019c35869e70de7bb87a0d35e1c6
| 447
|
cpp
|
C++
|
cpp02/cpp02_func_overload.cpp
|
ValentinoVizner/CPP_OpenCV_Playground
|
809fa501e056cddeb9e0af3cb7f0ba0925f389d0
|
[
"MIT"
] | null | null | null |
cpp02/cpp02_func_overload.cpp
|
ValentinoVizner/CPP_OpenCV_Playground
|
809fa501e056cddeb9e0af3cb7f0ba0925f389d0
|
[
"MIT"
] | null | null | null |
cpp02/cpp02_func_overload.cpp
|
ValentinoVizner/CPP_OpenCV_Playground
|
809fa501e056cddeb9e0af3cb7f0ba0925f389d0
|
[
"MIT"
] | null | null | null |
/*
Function overloading
Compiler infers a function from arguments
Cannot overload based on return type
Return type plays no role at all
GOOGLE-STYLE Avoid non-obvious overloads
*/
#include <iostream>
#include <string>
std::string Func(int num) {
return "int";
}
std::string Func(const std::string& str) {
return "string";
}
int main() {
std::cout << Func(1) << std::endl;
std::cout << Func("hello") << std::endl;
return 0;
}
| 19.434783
| 44
| 0.673378
|
ValentinoVizner
|
e64188e0832cfbc98ffd24e2f1dfa29db3d41edd
| 11,810
|
hxx
|
C++
|
include/vigra/copyimage.hxx
|
sstefan/vigra
|
f8826fa4de4293efb95582367f4bf42cc8ba8c11
|
[
"MIT"
] | 1
|
2017-01-23T11:27:56.000Z
|
2017-01-23T11:27:56.000Z
|
include/vigra/copyimage.hxx
|
tikroeger/vigra
|
981d1ebc3ee85464a0d2ace693ad41606b475e2f
|
[
"MIT"
] | null | null | null |
include/vigra/copyimage.hxx
|
tikroeger/vigra
|
981d1ebc3ee85464a0d2ace693ad41606b475e2f
|
[
"MIT"
] | 3
|
2015-12-09T13:47:13.000Z
|
2019-04-06T21:28:59.000Z
|
/************************************************************************/
/* */
/* Copyright 1998-2002 by Ullrich Koethe */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* Permission is hereby granted, free of charge, to any person */
/* obtaining a copy of this software and associated documentation */
/* files (the "Software"), to deal in the Software without */
/* restriction, including without limitation the rights to use, */
/* copy, modify, merge, publish, distribute, sublicense, and/or */
/* sell copies of the Software, and to permit persons to whom the */
/* Software is furnished to do so, subject to the following */
/* conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the */
/* Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES */
/* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT */
/* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, */
/* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING */
/* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR */
/* OTHER DEALINGS IN THE SOFTWARE. */
/* */
/************************************************************************/
#ifndef VIGRA_COPYIMAGE_HXX
#define VIGRA_COPYIMAGE_HXX
#include "utilities.hxx"
namespace vigra {
/** \addtogroup CopyAlgo Algorithms to Copy Images
Copy images or regions
*/
//@{
/********************************************************/
/* */
/* copyLine */
/* */
/********************************************************/
template <class SrcIterator, class SrcAccessor,
class DestIterator, class DestAccessor>
void
copyLine(SrcIterator s,
SrcIterator send, SrcAccessor src,
DestIterator d, DestAccessor dest)
{
for(; s != send; ++s, ++d)
dest.set(src(s), d);
}
template <class SrcIterator, class SrcAccessor,
class MaskIterator, class MaskAccessor,
class DestIterator, class DestAccessor>
void
copyLineIf(SrcIterator s,
SrcIterator send, SrcAccessor src,
MaskIterator m, MaskAccessor mask,
DestIterator d, DestAccessor dest)
{
for(; s != send; ++s, ++d, ++m)
if(mask(m))
dest.set(src(s), d);
}
template <class SrcIterator, class SrcAccessor,
class DestIterator, class DestAccessor>
void
swapLine(SrcIterator s,
SrcIterator send, SrcAccessor src,
DestIterator d, DestAccessor dest)
{
for(; s != send; ++s, ++d)
{
typename SrcAccessor::value_type t = src(s);
src.set(dest(d), s);
dest.set(t, d);
}
}
/********************************************************/
/* */
/* copyImage */
/* */
/********************************************************/
/** \brief Copy source image into destination image.
If necessary, type conversion takes place.
The function uses accessors to access the pixel data.
<b> Declarations:</b>
pass arguments explicitly:
\code
namespace vigra {
template <class SrcImageIterator, class SrcAccessor,
class DestImageIterator, class DestAccessor>
void
copyImage(SrcImageIterator src_upperleft,
SrcImageIterator src_lowerright, SrcAccessor sa,
DestImageIterator dest_upperleft, DestAccessor da)
}
\endcode
use argument objects in conjunction with \ref ArgumentObjectFactories :
\code
namespace vigra {
template <class SrcImageIterator, class SrcAccessor,
class DestImageIterator, class DestAccessor>
void
copyImage(triple<SrcImageIterator, SrcImageIterator, SrcAccessor> src,
pair<DestImageIterator, DestAccessor> dest)
}
\endcode
<b> Usage:</b>
<b>\#include</b> \<vigra/copyimage.hxx\><br>
Namespace: vigra
\code
vigra::copyImage(srcImageRange(src), destImage(dest));
\endcode
<b> Required Interface:</b>
\code
SrcImageIterator src_upperleft, src_lowerright;
DestImageIterator dest_upperleft;
SrcImageIterator::row_iterator sx = src_upperleft.rowIterator();
DestImageIterator::row_iterator dx = dest_upperleft.rowIterator();
SrcAccessor src_accessor;
DestAccessor dest_accessor;
dest_accessor.set(src_accessor(sx), dx);
\endcode
*/
doxygen_overloaded_function(template <...> void copyImage)
template <class SrcImageIterator, class SrcAccessor,
class DestImageIterator, class DestAccessor>
void
copyImage(SrcImageIterator src_upperleft,
SrcImageIterator src_lowerright, SrcAccessor sa,
DestImageIterator dest_upperleft, DestAccessor da)
{
int w = src_lowerright.x - src_upperleft.x;
for(; src_upperleft.y<src_lowerright.y; ++src_upperleft.y, ++dest_upperleft.y)
{
copyLine(src_upperleft.rowIterator(),
src_upperleft.rowIterator() + w, sa,
dest_upperleft.rowIterator(), da);
}
}
template <class SrcImageIterator, class SrcAccessor,
class DestImageIterator, class DestAccessor>
inline
void
copyImage(triple<SrcImageIterator, SrcImageIterator, SrcAccessor> src,
pair<DestImageIterator, DestAccessor> dest)
{
copyImage(src.first, src.second, src.third,
dest.first, dest.second);
}
template <class SrcImageIterator, class SrcAccessor,
class DestImageIterator, class DestAccessor>
void
swapImageData(SrcImageIterator src_upperleft,
SrcImageIterator src_lowerright, SrcAccessor sa,
DestImageIterator dest_upperleft, DestAccessor da)
{
int w = src_lowerright.x - src_upperleft.x;
for(; src_upperleft.y<src_lowerright.y; ++src_upperleft.y, ++dest_upperleft.y)
{
swapLine(src_upperleft.rowIterator(),
src_upperleft.rowIterator() + w, sa,
dest_upperleft.rowIterator(), da);
}
}
template <class SrcImageIterator, class SrcAccessor,
class DestImageIterator, class DestAccessor>
inline
void
swapImageData(triple<SrcImageIterator, SrcImageIterator, SrcAccessor> src,
pair<DestImageIterator, DestAccessor> dest)
{
swapImageData(src.first, src.second, src.third,
dest.first, dest.second);
}
/********************************************************/
/* */
/* copyImageIf */
/* */
/********************************************************/
/** \brief Copy source ROI into destination image.
Pixel values are copied whenever the return value of the mask's
accessor is not zero.
If necessary, type conversion takes place.
The function uses accessors to access the pixel data.
<b> Declarations:</b>
pass arguments explicitly:
\code
namespace vigra {
template <class SrcImageIterator, class SrcAccessor,
class MaskImageIterator, class MaskAccessor,
class DestImageIterator, clas DestAccessor>
void
copyImageIf(SrcImageIterator src_upperleft,
SrcImageIterator src_lowerright, SrcAccessor sa,
MaskImageIterator mask_upperleft, MaskAccessor ma,
DestImageIterator dest_upperleft, DestAccessor da)
}
\endcode
use argument objects in conjunction with \ref ArgumentObjectFactories :
\code
namespace vigra {
template <class SrcImageIterator, class SrcAccessor,
class MaskImageIterator, class MaskAccessor,
class DestImageIterator, clas DestAccessor>
void
copyImageIf(triple<SrcImageIterator, SrcImageIterator, SrcAccessor> src,
pair<MaskImageIterator, MaskAccessor> mask,
pair<DestImageIterator, DestAccessor> dest)
}
\endcode
<b> Usage:</b>
<b>\#include</b> \<vigra/copyimage.hxx\><br>
Namespace: vigra
\code
vigra::copyImageIf(srcImageRange(src), maskImage(mask), destImage(dest));
\endcode
<b> Required Interface:</b>
\code
SrcImageIterator src_upperleft, src_lowerright;
DestImageIterator dest_upperleft;
MaskImageIterator mask_upperleft;
SrcImageIterator::row_iterator sx = src_upperleft.rowIterator();
MaskImageIterator::row_iterator mx = mask_upperleft.rowIterator();
DestImageIterator::row_iterator dx = dest_upperleft.rowIterator();
SrcAccessor src_accessor;
DestAccessor dest_accessor;
MaskAccessor mask_accessor;
Functor functor;
if(mask_accessor(mx))
dest_accessor.set(src_accessor(sx), dx);
\endcode
*/
doxygen_overloaded_function(template <...> void copyImageIf)
template <class SrcImageIterator, class SrcAccessor,
class MaskImageIterator, class MaskAccessor,
class DestImageIterator, class DestAccessor>
void
copyImageIf(SrcImageIterator src_upperleft,
SrcImageIterator src_lowerright, SrcAccessor sa,
MaskImageIterator mask_upperleft, MaskAccessor ma,
DestImageIterator dest_upperleft, DestAccessor da)
{
int w = src_lowerright.x - src_upperleft.x;
for(; src_upperleft.y<src_lowerright.y;
++src_upperleft.y, ++mask_upperleft.y, ++dest_upperleft.y)
{
copyLineIf(src_upperleft.rowIterator(),
src_upperleft.rowIterator() + w, sa,
mask_upperleft.rowIterator(), ma,
dest_upperleft.rowIterator(), da);
}
}
template <class SrcImageIterator, class SrcAccessor,
class MaskImageIterator, class MaskAccessor,
class DestImageIterator, class DestAccessor>
inline
void
copyImageIf(triple<SrcImageIterator, SrcImageIterator, SrcAccessor> src,
pair<MaskImageIterator, MaskAccessor> mask,
pair<DestImageIterator, DestAccessor> dest)
{
copyImageIf(src.first, src.second, src.third,
mask.first, mask.second,
dest.first, dest.second);
}
//@}
} // namespace vigra
#endif // VIGRA_COPYIMAGE_HXX
| 35.572289
| 90
| 0.5663
|
sstefan
|
e648354366e8082a48a7da3291c0151de9e5c0b9
| 11,639
|
cpp
|
C++
|
2021-01/16/opengl-win32.cpp
|
tsherif/sketches
|
c4bb4ec367f6e66d5a859f265ee48e04a4a9bb47
|
[
"MIT"
] | 2
|
2020-06-03T17:49:35.000Z
|
2020-07-09T06:02:50.000Z
|
2021-01/16/opengl-win32.cpp
|
tsherif/sketches
|
c4bb4ec367f6e66d5a859f265ee48e04a4a9bb47
|
[
"MIT"
] | 8
|
2022-02-13T19:46:39.000Z
|
2022-02-27T10:05:10.000Z
|
2021-01/16/opengl-win32.cpp
|
tsherif/sketches
|
c4bb4ec367f6e66d5a859f265ee48e04a4a9bb47
|
[
"MIT"
] | null | null | null |
#define WIN32_LEAN_AND_MEAN
#define _USE_MATH_DEFINES
#define SOGL_MAJOR_VERSION 4
#define SOGL_MINOR_VERSION 5
#define SOGL_IMPLEMENTATION_WIN32
#define STB_IMAGE_IMPLEMENTATION
#include "../../lib/simple-opengl-loader.h"
#include <windows.h>
#include <cstdint>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include "wglext.h"
#include "../../lib/glm/glm.hpp"
#include "../../lib/glm/ext.hpp"
#include "../../lib/stb_image.h"
#define WIDTH 800
#define HEIGHT 800
#define DECLARE_WGL_EXT_FUNC(returnType, name, ...) typedef returnType (WINAPI *name##FUNC)(__VA_ARGS__);\
name##FUNC name = (name##FUNC)0;
#define LOAD_WGL_EXT_FUNC(name) name = (name##FUNC) wglGetProcAddress(#name)
/////////////////////////////////////
// Set up OpenGL function pointers
/////////////////////////////////////
DECLARE_WGL_EXT_FUNC(BOOL, wglChoosePixelFormatARB, HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
DECLARE_WGL_EXT_FUNC(HGLRC, wglCreateContextAttribsARB, HDC hDC, HGLRC hshareContext, const int *attribList);
DECLARE_WGL_EXT_FUNC(BOOL, wglSwapIntervalEXT, int interval);
////////////////
// WIN32 setup
////////////////
const WCHAR WIN_CLASS_NAME[] = L"OPENGL_WINDOW_CLASS";
LRESULT CALLBACK winProc(HWND window, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_CLOSE: {
PostQuitMessage(0);
return 0;
} break;
}
return DefWindowProc(window, message, wParam, lParam);
}
float randomRange(float min, float max) {
float range = max - min;
return min + ((float) rand() / (RAND_MAX + 1)) * range;
}
int CALLBACK WinMain(HINSTANCE instance, HINSTANCE, LPSTR, int showWindow) {
WNDCLASSEX winClass = {};
winClass.cbSize = sizeof(winClass);
winClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
winClass.lpfnWndProc = winProc;
winClass.hInstance = instance;
winClass.hIcon = LoadIcon(instance, IDI_APPLICATION);
winClass.hIconSm = LoadIcon(instance, IDI_APPLICATION);
winClass.hCursor = LoadCursor(NULL, IDC_ARROW);
winClass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
winClass.lpszClassName = WIN_CLASS_NAME;
if (!RegisterClassEx(&winClass)) {
MessageBox(NULL, L"Failed to register window class!", L"FAILURE", MB_OK);
return 1;
}
////////////////////////////////////////////////////////////////////
// Create a dummy window so we can get WGL extension functions
////////////////////////////////////////////////////////////////////
HWND dummyWindow = CreateWindow(WIN_CLASS_NAME, L"DUMMY", WS_OVERLAPPEDWINDOW, 0, 0, 1, 1, NULL, NULL, instance, NULL);
if (!dummyWindow) {
MessageBox(NULL, L"Failed to create window!", L"FAILURE", MB_OK);
return 1;
}
HDC dummyContext = GetDC(dummyWindow);
PIXELFORMATDESCRIPTOR pfd = {};
pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
pfd.iPixelType = PFD_TYPE_RGBA,
pfd.cColorBits = 32;
pfd.cDepthBits = 24;
pfd.cStencilBits = 8;
pfd.iLayerType = PFD_MAIN_PLANE;
int pixelFormat = ChoosePixelFormat(dummyContext, &pfd);
SetPixelFormat(dummyContext, pixelFormat, &pfd);
HGLRC dummyGL = wglCreateContext(dummyContext);
wglMakeCurrent(dummyContext, dummyGL);
LOAD_WGL_EXT_FUNC(wglChoosePixelFormatARB);
LOAD_WGL_EXT_FUNC(wglCreateContextAttribsARB);
LOAD_WGL_EXT_FUNC(wglSwapIntervalEXT);
if (!wglCreateContextAttribsARB || !wglCreateContextAttribsARB) {
MessageBox(NULL, L"Didn't get wgl ARB functions!", L"FAILURE", MB_OK);
return 1;
}
wglMakeCurrent(NULL, NULL);
wglDeleteContext(dummyGL);
DestroyWindow(dummyWindow);
/////////////////////////////////////////////
// Create real window and rendering context
/////////////////////////////////////////////
HWND window = CreateWindow(
WIN_CLASS_NAME,
L"WIN32 OPENGL!!!",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
WIDTH, HEIGHT,
NULL,
NULL,
instance,
NULL
);
if (!window) {
MessageBox(NULL, L"Failed to create window!", L"FAILURE", MB_OK);
return 1;
}
HDC deviceContext = GetDC(window);
const int pixelAttribList[] = {
WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
WGL_COLOR_BITS_ARB, 32,
WGL_DEPTH_BITS_ARB, 24,
WGL_STENCIL_BITS_ARB, 8,
WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
WGL_SAMPLE_BUFFERS_ARB, GL_TRUE,
WGL_SAMPLES_ARB, 4,
0
};
UINT numFormats;
BOOL success;
success = wglChoosePixelFormatARB(deviceContext, pixelAttribList, NULL, 1, &pixelFormat, &numFormats);
if (!success || numFormats == 0) {
MessageBox(NULL, L"Didn't get ARB pixel format!", L"FAILURE", MB_OK);
return 1;
}
DescribePixelFormat(deviceContext, pixelFormat, sizeof(pfd), &pfd);
SetPixelFormat(deviceContext, pixelFormat, &pfd);
const int contextAttribList[] = {
WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
WGL_CONTEXT_MINOR_VERSION_ARB, 5,
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
0
};
HGLRC gl = wglCreateContextAttribsARB(deviceContext, NULL, contextAttribList);
if (!gl) {
MessageBox(NULL, L"Didn't get ARB GL context!", L"FAILURE", MB_OK);
return 1;
}
wglMakeCurrent(deviceContext, gl);
wglSwapIntervalEXT(1);
sogl_loadOpenGL();
char rendererString[256] = {};
snprintf(rendererString, 256, "Win32 OpenGL - %s", glGetString(GL_RENDERER));
SetWindowTextA(window, rendererString);
srand((unsigned int) time(NULL));
///////////////////////////
// Set up GL resources
///////////////////////////
glClearColor(0.0, 0.0, 0.0, 1.0);
const char* csSource = R"GLSL(#version 450
layout(std430, binding=0) restrict writeonly buffer Position {
vec2 positions[3];
};
layout(std430, binding=1) restrict writeonly buffer Color {
vec4 colors[3];
};
layout(std430, binding=2) restrict writeonly buffer Command {
uint count;
uint instanceCount;
uint first;
uint baseInstance;
} command;
layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
void main() {
positions[0] = vec2(-0.5, -0.5);
positions[1] = vec2(0.5, -0.5);
positions[2] = vec2(0.0, 0.5);
colors[0] = vec4(1.0, 0.0, 0.0, 1.0);
colors[1] = vec4(0.0, 1.0, 0.0, 1.0);
colors[2] = vec4(0.0, 0.0, 1.0, 1.0);
command.count = 3;
command.instanceCount = 1;
command.first = 0;
command.baseInstance = 0;
}
)GLSL";
GLuint computeProgram = glCreateShaderProgramv(GL_COMPUTE_SHADER, 1, &csSource);
GLint result;
glGetProgramiv(computeProgram, GL_LINK_STATUS, &result);
if (result != GL_TRUE) {
char buffer[256];
glGetProgramInfoLog(computeProgram, 256, NULL, buffer);
MessageBoxA(NULL, buffer, "Compute program No LINK", MB_OK);
return 1;
}
GLuint computePipeline = 0;
glGenProgramPipelines(1, &computePipeline);
glUseProgramStages(computePipeline, GL_COMPUTE_SHADER_BIT, computeProgram);
const char* vsSource = R"GLSL(#version 450
layout(std140) uniform;
layout(location=0) in vec4 position;
layout(location=1) in vec4 color;
layout(location=0) out vec4 vertexColor;
void main() {
vertexColor = color;
gl_Position = position;
}
)GLSL";
const char* fsSource = R"GLSL(#version 450
layout(location=0) in vec4 surfaceColor;
out vec4 fragColor;
void main() {
fragColor = surfaceColor;
}
)GLSL";
GLuint vertexProgram = glCreateShaderProgramv(GL_VERTEX_SHADER, 1, &vsSource);
glGetProgramiv(vertexProgram, GL_LINK_STATUS, &result);
if (result != GL_TRUE) {
char buffer[256];
glGetProgramInfoLog(vertexProgram, 256, NULL, buffer);
MessageBoxA(NULL, buffer, "Vertex program failed to link!", MB_OK);
return 1;
}
GLuint fragmentProgram = glCreateShaderProgramv(GL_FRAGMENT_SHADER, 1, &fsSource);
glGetProgramiv(fragmentProgram, GL_LINK_STATUS, &result);
if (result != GL_TRUE) {
char buffer[256];
glGetProgramInfoLog(fragmentProgram, 256, NULL, buffer);
MessageBoxA(NULL, buffer, "Fragment program failed to link!", MB_OK);
return 1;
}
GLuint drawPipeline = 0;
glGenProgramPipelines(1, &drawPipeline);
glUseProgramStages(drawPipeline, GL_VERTEX_SHADER_BIT, vertexProgram);
glUseProgramStages(drawPipeline, GL_FRAGMENT_SHADER_BIT, fragmentProgram);
// BUFFERS
GLuint positionBuffer = 0;
glGenBuffers(1, &positionBuffer);
glBindBuffer(GL_ARRAY_BUFFER, positionBuffer);
glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(GLfloat), NULL, GL_STATIC_DRAW);
GLuint colorBuffer = 0;
glGenBuffers(1, &colorBuffer);
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glBufferData(GL_ARRAY_BUFFER, 12 * sizeof(GLfloat), NULL, GL_STATIC_DRAW);
GLuint commandBuffer = 0;
glGenBuffers(1, &commandBuffer);
glBindBuffer(GL_ARRAY_BUFFER, commandBuffer);
glBufferData(GL_ARRAY_BUFFER, 4 * sizeof(GLuint), NULL, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, NULL);
// COMPUTE BUFFER BINDINGS
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, positionBuffer);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, colorBuffer);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, commandBuffer);
// DRAW BUFFER BINDINGS
GLuint vertexArray = 0;
glGenVertexArrays(1, &vertexArray);
glBindVertexArray(vertexArray);
glBindBuffer(GL_ARRAY_BUFFER, positionBuffer);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(1);
glBindBuffer(GL_DRAW_INDIRECT_BUFFER, commandBuffer);
glBindBuffer(GL_ARRAY_BUFFER, NULL);
if (glGetError() != GL_NO_ERROR) {
MessageBox(NULL, L"Error after buffer set up!", L"FAILURE", MB_OK);
return 1;
}
///////////////////
// Display window
///////////////////
ShowWindow(window, showWindow);
//////////////////////////////////
// Start render and message loop
//////////////////////////////////
MSG message;
bool running = true;
while (running) {
while (PeekMessage(&message, NULL, 0, 0, PM_REMOVE)) {
TranslateMessage(&message);
DispatchMessage(&message);
if (message.message == WM_QUIT) {
running = false;
break;
}
}
glBindProgramPipeline(computePipeline);
glDispatchCompute(1, 1, 1);
glMemoryBarrier(GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT | GL_COMMAND_BARRIER_BIT);
glBindProgramPipeline(drawPipeline);
glClear(GL_COLOR_BUFFER_BIT);
glDrawArraysIndirect(GL_TRIANGLES, NULL);
//////////////////
// SWAP BUFFERS
//////////////////
SwapBuffers(deviceContext);
}
return (int) message.wParam;
}
| 30.548556
| 168
| 0.635622
|
tsherif
|
e648f4b19265d069a4cc22deb6204fb151c07b2e
| 513
|
cpp
|
C++
|
src/771 Jewels and Stones.cpp
|
LL-Pengfei/LL-Pengfei-Leetcode-Solutions
|
3ae358877bdb943bef67a55372ce7f04d2881072
|
[
"MIT"
] | null | null | null |
src/771 Jewels and Stones.cpp
|
LL-Pengfei/LL-Pengfei-Leetcode-Solutions
|
3ae358877bdb943bef67a55372ce7f04d2881072
|
[
"MIT"
] | null | null | null |
src/771 Jewels and Stones.cpp
|
LL-Pengfei/LL-Pengfei-Leetcode-Solutions
|
3ae358877bdb943bef67a55372ce7f04d2881072
|
[
"MIT"
] | null | null | null |
//771. Jewels and Stones
//https://leetcode.com/problems/jewels-and-stones/
class Solution {
public:
int numJewelsInStones(string J, string S) {
const char* jc = J.c_str();
const char* sc = S.c_str();
unordered_set<char> jewel;
for (int i = 0; i < J.size(); ++i) {
jewel.insert(jc[i]);
}
int count = 0;
for (int j = 0; j < S.size(); ++j) {
if (jewel.find(sc[j]) != jewel.end()) ++count;
}
return count;
}
};
| 25.65
| 58
| 0.500975
|
LL-Pengfei
|
e649623eb9887f7a5b6341fd717e9d9b6e686b23
| 589
|
cpp
|
C++
|
Main/Sun.cpp
|
ThomasGITH/OpenGL-Engine
|
b2800f5abf0a5c437a4731a5b6ed43bafcbf776f
|
[
"Apache-2.0"
] | 1
|
2019-11-06T23:46:38.000Z
|
2019-11-06T23:46:38.000Z
|
Main/Sun.cpp
|
ThomasGITH/OpenGL-code
|
b2800f5abf0a5c437a4731a5b6ed43bafcbf776f
|
[
"Apache-2.0"
] | 1
|
2021-08-29T20:59:30.000Z
|
2021-08-29T20:59:30.000Z
|
Main/Sun.cpp
|
ThomasGITH/OpenGL-code
|
b2800f5abf0a5c437a4731a5b6ed43bafcbf776f
|
[
"Apache-2.0"
] | null | null | null |
#include "Sun.h"
Sun::Sun(glm::vec3 colour, GLfloat ambientIntensity, glm::vec3 direction, GLfloat diffuseIntensity)
{
this->colour = colour;
this->ambientIntensity = ambientIntensity;
this->direction = direction;
this->diffuseIntensity = diffuseIntensity;
setLightType(DIRECTIONAL);
}
void Sun::Update(const bool * keys, const GLfloat& deltaTime)
{
useLight(getUniformLocation(DL_COLOUR), getUniformLocation(DL_AMBIENT_INTENSITY), getUniformLocation(DL_DIRECTION), getUniformLocation(DL_DIFFUSE_INTENSITY), NULL, NULL, NULL, NULL, NULL);
}
Sun::~Sun()
{
}
| 26.772727
| 190
| 0.745331
|
ThomasGITH
|
e6497a329bd794e4de5d07efcd7802f5769db7c5
| 10,955
|
cpp
|
C++
|
src/sdl/graphic.cpp
|
mwthinker/CppSdl2
|
0433a4f984b1c0e7e6a96303ee4d55cc9430343e
|
[
"MIT"
] | 3
|
2019-08-18T19:22:39.000Z
|
2021-08-29T15:45:37.000Z
|
src/sdl/graphic.cpp
|
mwthinker/CppSdl2
|
0433a4f984b1c0e7e6a96303ee4d55cc9430343e
|
[
"MIT"
] | null | null | null |
src/sdl/graphic.cpp
|
mwthinker/CppSdl2
|
0433a4f984b1c0e7e6a96303ee4d55cc9430343e
|
[
"MIT"
] | null | null | null |
#include "graphic.h"
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtx/component_wise.hpp>
#include <glm/gtx/vector_angle.hpp>
#include <array>
namespace {
struct GlScopedState {
GlScopedState() {
glGetIntegerv(GL_TEXTURE_BINDING_2D, &texture);
glGetIntegerv(GL_ACTIVE_TEXTURE, &activeTexture);
glGetBooleanv(GL_PROGRAM_POINT_SIZE, &point);
}
~GlScopedState() {
glBindTexture(GL_TEXTURE_2D, texture);
glActiveTexture(activeTexture);
if (point) {
glEnable(GL_PROGRAM_POINT_SIZE);
} else {
glDisable(GL_PROGRAM_POINT_SIZE);
}
}
GLint texture;
GLint activeTexture;
GLboolean point;
};
}
namespace sdl::graphic {
glm::vec2 getHexagonCorner(int nbr, float startAngle) {
return glm::rotate(glm::vec2{1, 0.f}, Pi / 3 * nbr + startAngle);
}
glm::vec2 getHexagonCorner(const glm::vec2& center, float size, int nbr, float startAngle) {
return center + size * getHexagonCorner(nbr, startAngle);
}
std::array<glm::vec2, 6> getHexagonCorners(const glm::vec2& center, float radius, float startAngle) {
std::array<glm::vec2, 6> corners;
for (int i = 0; i < 6; ++i) {
corners[i] = getHexagonCorner(center, radius, i, startAngle);
}
return corners;
}
void addLine(BatchIndexed<Vertex>& batch, const glm::vec2& p1, const glm::vec2& p2, float width, Color color) {
batch.startAdding();
auto dp = 0.5f * width * glm::rotate(glm::normalize(p2 - p1), Pi / 2);
batch.pushBack(Vertex{p1 - dp, {}, color});
batch.pushBack(Vertex{p2 - dp, {}, color});
batch.pushBack(Vertex{p2 + dp, {}, color});
batch.pushBack(Vertex{p1 + dp, {}, color});
batch.insertIndexes({0, 1, 2, 0, 2, 3});
}
void addRectangle(BatchIndexed<Vertex>& batch, const glm::vec2& pos, const glm::vec2& size, Color color) {
batch.startAdding();
batch.pushBack(Vertex{pos, {}, color});
batch.pushBack(Vertex{pos + glm::vec2{size.x, 0.f}, {}, color});
batch.pushBack(Vertex{pos + size, {}, color});
batch.pushBack(Vertex{pos + glm::vec2{0.f, size.y}, {}, color});
batch.insertIndexes({0, 1, 2, 0, 2, 3});
}
void addRectangleImage(BatchIndexed<Vertex>& batch, const glm::vec2& pos, const glm::vec2& size, const TextureView& texture, Color color) {
batch.startAdding();
if (texture) {
batch.pushBack(Vertex{pos, texture.getPosition() + glm::vec2{0.f, texture.getHeight()}, color});
batch.pushBack(Vertex{pos + glm::vec2{size.x, 0.f}, texture.getPosition() + glm::vec2{texture.getWidth(), texture.getHeight()}, color});
batch.pushBack(Vertex{pos + size, texture.getPosition() + glm::vec2{texture.getWidth(), 0.f}, color});
batch.pushBack(Vertex{pos + glm::vec2{0.f, size.y}, texture.getPosition(), color});
batch.insertIndexes({0, 1, 2, 0, 2, 3});
}
}
void addHexagonImage(BatchIndexed<Vertex>& batch, const glm::vec2& center, float radius, const sdl::TextureView& sprite, float startAngle) {
batch.startAdding();
if (sprite) {
auto texHalfSize = sprite.getSize() * 0.5f;
auto texMiddlePos = sprite.getPosition() + texHalfSize;
auto centerVertex = Vertex{center, texMiddlePos, sdl::color::White};
batch.pushBack(centerVertex);
for (int i = 0; i < 6; ++i) {
auto tex = texHalfSize * getHexagonCorner(i, 0); // Textures are flipped in opengl.
auto v = Vertex{getHexagonCorner(center, radius, i, startAngle), texMiddlePos + glm::vec2{tex.x, -tex.y}, sdl::color::White};
batch.pushBack(v);
}
for (int i = 1; i <= 6; ++i) {
batch.insertIndexes({0, i, (i % 6) + 1});
}
}
}
void addHexagon(BatchIndexed<Vertex>& batch, const glm::vec2& center, float innerRadius, float outerRadius, Color color, float startAngle) {
batch.startAdding();
auto innerCorners = getHexagonCorners(center, innerRadius, startAngle);
auto outerCorners = getHexagonCorners(center, outerRadius, startAngle);
for (const auto& corner : innerCorners) {
batch.pushBack({corner, {0.f, 0.f}, color});
}
for (const auto& corner : outerCorners) {
batch.pushBack({corner, {0.f, 0.f}, color});
}
for (int i = 0; i < 6; ++i) {
batch.insertIndexes({i, 6 + i, 6 + (i + 1) % 6, i, (i + 1) % 6, 6 + (i + 1) % 6});
}
}
void addCircle(BatchIndexed<Vertex>& batch, const glm::vec2& center, float radius, Color color, const int iterations, float startAngle) {
batch.startAdding();
batch.pushBack({center, {0.f, 0.f}, color});
for (int i = 0; i < iterations; ++i) {
auto rad = 2 * Pi * i / iterations + startAngle;
auto edge = center + glm::rotate(glm::vec2{radius, 0.f}, rad);
batch.pushBack({edge, {0.f, 0.f}, color});
}
for (int i = 1; i <= iterations; ++i) {
batch.insertIndexes({0, i, (i % iterations) + 1});
}
}
void addCircleOutline(BatchIndexed<Vertex>& batch, const glm::vec2& center, float radius, float width, Color color, const int iterations, float startAngle) {
batch.startAdding();
for (int i = 0; i <= iterations; ++i) {
auto rad = 2 * Pi * i / iterations + startAngle;
auto outerEdge = center + glm::rotate(glm::vec2{radius + width * 0.5f, 0.f}, rad);
auto innerEdge = center + glm::rotate(glm::vec2{radius - width * 0.5f, 0.f}, rad);
batch.pushBack({outerEdge, {0.f, 0.f}, color});
batch.pushBack({innerEdge, {0.f, 0.f}, color});
}
for (int i = 0; i < iterations * 2 - 1; i += 2) {
batch.insertIndexes({i, i + 2, i + 3, i + 3, i + 1, i});
}
}
}
namespace sdl {
namespace sdlg = sdl::graphic;
Graphic::Graphic() {
matrixes_.push_back({glm::mat4{1}, 0});
}
void Graphic::setIdentityMatrix() {
if (dirty_) {
matrix() = glm::mat4{1};
} else {
dirty_ = true;
matrixes_.push_back({glm::mat4{1}, matrixes_.back().lastIndex});
}
}
void Graphic::upload(sdl::Shader& shader) {
if (batch_.isEmpty()) {
return;
}
GlScopedState currentState;
glActiveTexture(GL_TEXTURE1);
auto index = currentMatrixIndex_;
currentMatrixIndex_ = -1;
shader.useProgram();
bind(shader);
batch_.uploadToGraphicCard();
shader.setMatrix(matrixes_.front().matrix);
for (const auto& batchData : batches_) {
draw(shader, batchData);
}
currentMatrixIndex_ = index;
}
void Graphic::addPixel(const glm::vec2& point, Color color, float size) {
batch_.startBatchView();
batch_.startAdding();
batch_.pushBack({point, {size, size}, color});
batch_.pushBackIndex(0);
add(batch_.getBatchView(GL_POINTS));
}
void Graphic::addLine(const glm::vec2& p1, const glm::vec2& p2, float width, Color color) {
batch_.startBatchView();
sdlg::addLine(batch_, p1, p2, width, color);
add(batch_.getBatchView(GL_TRIANGLES));
}
void Graphic::addRectangle(const glm::vec2& pos, const glm::vec2& size, Color color) {
batch_.startBatchView();
sdlg::addRectangle(batch_, pos, size, color);
add(batch_.getBatchView(GL_TRIANGLES));
}
void Graphic::addRectangleImage(const glm::vec2& pos, const glm::vec2& size, const sdl::TextureView& textureView, Color color) {
batch_.startBatchView();
sdlg::addRectangleImage(batch_, pos, size, textureView, color);
add(batch_.getBatchView(GL_TRIANGLES), textureView);
}
void Graphic::addFilledHexagon(const glm::vec2& center, float radius, Color color, float startAngle) {
batch_.startBatchView();
addCircle(center, radius, color, 6, startAngle);
add(batch_.getBatchView(GL_TRIANGLES));
}
void Graphic::addHexagonImage(const glm::vec2& center, float radius, const sdl::TextureView& textureView, float startAngle) {
batch_.startBatchView();
sdlg::addHexagonImage(batch_, center, radius, textureView, startAngle);
add(batch_.getBatchView(GL_TRIANGLES), textureView);
}
void Graphic::addHexagon(const glm::vec2& center, float innerRadius, float outerRadius, Color color, float startAngle) {
batch_.startBatchView();
sdlg::addHexagon(batch_, center, innerRadius, outerRadius, color, startAngle);
add(batch_.getBatchView(GL_TRIANGLES));
}
void Graphic::addCircle(const glm::vec2& center, float radius, Color color, const int iterations, float startAngle) {
batch_.startBatchView();
sdlg::addCircle(batch_, center, radius, color, iterations, startAngle);
add(batch_.getBatchView(GL_TRIANGLES));
}
void Graphic::addCircleOutline(const glm::vec2& center, float radius, float width, Color color, const int iterations, float startAngle) {
batch_.startBatchView();
sdlg::addCircleOutline(batch_, center, radius, width, color, iterations, startAngle);
add(batch_.getBatchView(GL_TRIANGLES));
}
void Graphic::bind(sdl::Shader& shader) {
if (initiated_) {
vao_.bind();
} else {
initiated_ = true;
vao_.generate();
vao_.bind();
batch_.bind();
shader.setVertexAttribPointer();
}
}
void Graphic::draw(sdl::Shader& shader, const BatchData& batchData) {
if (const auto& texture = batchData.texture; texture) {
shader.setTextureId(1);
glBindTexture(GL_TEXTURE_2D, texture);
} else {
shader.setTextureId(-1);
}
if (currentMatrixIndex_ != batchData.matrixIndex) {
currentMatrixIndex_ = batchData.matrixIndex;
shader.setMatrix(matrixes_[currentMatrixIndex_].matrix);
}
batch_.draw(batchData.batchView);
}
void Graphic::clear() {
batch_.clear();
batches_.clear();
matrixes_.clear();
matrixes_.push_back({glm::mat4{1}, 0});
currentMatrixIndex_ = 0;
dirty_ = true;
}
void Graphic::add(BatchView&& batchView, const sdl::TextureView& texture) {
if (!batches_.empty()) {
auto& backData = batches_.back();
if (getMatrixIndex() == backData.matrixIndex
&& backData.texture == texture
&& backData.batchView.tryMerge(batchView)) {
return;
}
}
batches_.emplace_back(BatchData{batchView, texture, getMatrixIndex()});
dirty_ = false;
}
void Graphic::multMatrix(const glm::mat4& mult) {
if (dirty_) {
matrix() *= mult;
} else {
matrixes_.push_back({getMatrix() * mult, static_cast<int>(matrixes_.size())});
}
}
void Graphic::pushMatrix() {
matrixes_.push_back(matrixes_.back());
dirty_ = true;
}
void Graphic::popMatrix() {
if (matrixes_.empty()) {
spdlog::warn("[sdl::Graphic] No matrix to pop");
} else {
dirty_ = true; // Just to be safe, don't know if earlier state weas dirty (Maybe ToDo: make dirty part of matrixes vector).
matrixes_.push_back(matrixes_[matrixes_.back().lastIndex]);
}
}
void Graphic::setMatrix(const glm::mat4& mat) {
if (dirty_) {
matrix() = mat;
} else {
dirty_ = true;
matrixes_.push_back({mat, static_cast<int>(matrixes_.size())});
}
}
void Graphic::rotate(float angle) {
if (dirty_) {
matrix() = glm::rotate(getMatrix(), angle, glm::vec3{0, 0, 1});
} else {
dirty_ = true;
matrixes_.push_back({glm::rotate(getMatrix(), angle, glm::vec3{0, 0, 1}), static_cast<int>(matrixes_.size())});
}
}
void Graphic::translate(const glm::vec2& pos) {
if (dirty_) {
matrix() = glm::translate(getMatrix(), glm::vec3{pos, 0});
} else {
dirty_ = true;
matrixes_.push_back({glm::translate(getMatrix(), glm::vec3{pos, 0}), static_cast<int>(matrixes_.size())});
}
}
}
| 30.772472
| 158
| 0.67403
|
mwthinker
|
e64bd002587ebf7f4f4990f8fe1dbe480a63d00d
| 401
|
hpp
|
C++
|
library/ATF/GUILD_BATTLE__CGuildBattleStateListVtbl.hpp
|
lemkova/Yorozuya
|
f445d800078d9aba5de28f122cedfa03f26a38e4
|
[
"MIT"
] | 29
|
2017-07-01T23:08:31.000Z
|
2022-02-19T10:22:45.000Z
|
library/ATF/GUILD_BATTLE__CGuildBattleStateListVtbl.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 90
|
2017-10-18T21:24:51.000Z
|
2019-06-06T02:30:33.000Z
|
library/ATF/GUILD_BATTLE__CGuildBattleStateListVtbl.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 44
|
2017-12-19T08:02:59.000Z
|
2022-02-24T23:15:01.000Z
|
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
namespace GUILD_BATTLE
{
struct CGuildBattleStateListVtbl
{
void (WINAPIV *SetNextState)(struct CGuildBattleStateList *_this);
};
}; // end namespace GUILD_BATTLE
END_ATF_NAMESPACE
| 25.0625
| 108
| 0.703242
|
lemkova
|
e64cb12c245cf767199f730e8cf9beea9b444d01
| 848
|
cpp
|
C++
|
libs_common/vds_transactions/transactions/store_block_transaction.cpp
|
SuperOyuncuNW/vds
|
87a40059150fb2523f10da9ed1a63b75ac0d531c
|
[
"MIT"
] | 2
|
2018-02-16T00:27:04.000Z
|
2018-06-16T02:53:47.000Z
|
libs_common/vds_transactions/transactions/store_block_transaction.cpp
|
SuperOyuncuNW/vds
|
87a40059150fb2523f10da9ed1a63b75ac0d531c
|
[
"MIT"
] | 1
|
2018-07-20T04:18:00.000Z
|
2018-07-21T12:04:57.000Z
|
libs_common/vds_transactions/transactions/store_block_transaction.cpp
|
SuperOyuncuNW/vds
|
87a40059150fb2523f10da9ed1a63b75ac0d531c
|
[
"MIT"
] | 12
|
2017-07-16T12:01:52.000Z
|
2022-03-16T20:36:57.000Z
|
/*
Copyright (c) 2017, Vadim Malyshev, lboss75@gmail.com
All rights reserved
*/
#include "stdafx.h"
#include "store_block_transaction.h"
vds::expected<vds::transactions::store_block_transaction> vds::transactions::store_block_transaction::create(
const const_data_buffer& owner_id,
const const_data_buffer& object_id,
uint64_t object_size,
const std::vector<const_data_buffer>& replicas,
const asymmetric_private_key & private_key)
{
binary_serializer s;
CHECK_EXPECTED(s << owner_id);
CHECK_EXPECTED(s << object_id);
CHECK_EXPECTED(s << object_size);
CHECK_EXPECTED(s << replicas);
GET_EXPECTED(owner_sig, asymmetric_sign::signature(hash::sha256(), private_key, s.move_data()));
return message_create<transactions::store_block_transaction>(
owner_id,
object_id,
object_size,
replicas,
owner_sig);
}
| 27.354839
| 109
| 0.759434
|
SuperOyuncuNW
|
e651fc9900b2c48f75af2248a9c70d71390f2909
| 4,012
|
cpp
|
C++
|
src/light.cpp
|
PegasusEpsilon/Barony
|
6311f7e5da4835eaea65a95b5cc258409bb0dfa4
|
[
"FTL",
"Zlib",
"MIT"
] | 373
|
2016-06-28T06:56:46.000Z
|
2022-03-23T02:32:54.000Z
|
src/light.cpp
|
PegasusEpsilon/Barony
|
6311f7e5da4835eaea65a95b5cc258409bb0dfa4
|
[
"FTL",
"Zlib",
"MIT"
] | 361
|
2016-07-06T19:09:25.000Z
|
2022-03-26T14:14:19.000Z
|
src/light.cpp
|
PegasusEpsilon/Barony
|
6311f7e5da4835eaea65a95b5cc258409bb0dfa4
|
[
"FTL",
"Zlib",
"MIT"
] | 129
|
2016-06-29T09:02:49.000Z
|
2022-01-23T09:56:06.000Z
|
/*-------------------------------------------------------------------------------
BARONY
File: light.cpp
Desc: light spawning code
Copyright 2013-2016 (c) Turning Wheel LLC, all rights reserved.
See LICENSE for details.
-------------------------------------------------------------------------------*/
#include "main.hpp"
#include "light.hpp"
/*-------------------------------------------------------------------------------
lightSphereShadow
Adds a circle of light to the lightmap at x and y with the supplied
radius and intensity; casts shadows against walls
intensity can be from -255 to 255
-------------------------------------------------------------------------------*/
light_t* lightSphereShadow(Sint32 x, Sint32 y, Sint32 radius, Sint32 intensity)
{
light_t* light;
Sint32 i;
Sint32 u, v, u2, v2;
double a, b;
Sint32 dx, dy;
Sint32 dxabs, dyabs;
bool wallhit;
int index, z;
if ( intensity == 0 )
{
return NULL;
}
light = newLight(x, y, radius, intensity);
intensity = std::min(std::max(-255, intensity), 255);
for ( v = y - radius; v <= y + radius; v++ )
{
for ( u = x - radius; u <= x + radius; u++ )
{
if ( u >= 0 && v >= 0 && u < map.width && v < map.height )
{
dx = u - x;
dy = v - y;
dxabs = abs(dx);
dyabs = abs(dy);
a = dyabs * .5;
b = dxabs * .5;
u2 = u;
v2 = v;
wallhit = true;
index = v * MAPLAYERS + u * MAPLAYERS * map.height;
for ( z = 0; z < MAPLAYERS; z++ )
{
if ( !map.tiles[index + z] )
{
wallhit = false;
break;
}
}
if ( wallhit == true )
{
continue;
}
if ( dxabs >= dyabs ) // the line is more horizontal than vertical
{
for ( i = 0; i < dxabs; i++ )
{
u2 -= sgn(dx);
b += dyabs;
if ( b >= dxabs )
{
b -= dxabs;
v2 -= sgn(dy);
}
if ( u2 >= 0 && u2 < map.width && v2 >= 0 && v2 < map.height )
{
if ( map.tiles[OBSTACLELAYER + v2 * MAPLAYERS + u2 * MAPLAYERS * map.height] )
{
wallhit = true;
break;
}
}
}
}
else // the line is more vertical than horizontal
{
for ( i = 0; i < dyabs; i++ )
{
v2 -= sgn(dy);
a += dxabs;
if ( a >= dyabs )
{
a -= dyabs;
u2 -= sgn(dx);
}
if ( u2 >= 0 && u2 < map.width && v2 >= 0 && v2 < map.height )
{
if ( map.tiles[OBSTACLELAYER + v2 * MAPLAYERS + u2 * MAPLAYERS * map.height] )
{
wallhit = true;
break;
}
}
}
}
if ( wallhit == false || (wallhit == true && u2 == u && v2 == v) )
{
light->tiles[(dy + radius) + (dx + radius) * (radius * 2 + 1)] = intensity - intensity * std::min<float>(sqrtf(dx * dx + dy * dy) / radius, 1.0f);
lightmap[v + u * map.height] += light->tiles[(dy + radius) + (dx + radius) * (radius * 2 + 1)];
}
}
}
}
return light;
}
/*-------------------------------------------------------------------------------
lightSphere
Adds a circle of light to the lightmap at x and y with the supplied
radius and intensity; casts no shadows
intensity can be from -255 to 255
-------------------------------------------------------------------------------*/
light_t* lightSphere(Sint32 x, Sint32 y, Sint32 radius, Sint32 intensity)
{
light_t* light;
Sint32 u, v;
Sint32 dx, dy;
if ( intensity == 0 )
{
return NULL;
}
light = newLight(x, y, radius, intensity);
intensity = std::min(std::max(-255, intensity), 255);
for ( v = y - radius; v <= y + radius; v++ )
{
for ( u = x - radius; u <= x + radius; u++ )
{
if ( u >= 0 && v >= 0 && u < map.width && v < map.height )
{
dx = u - x;
dy = v - y;
light->tiles[(dy + radius) + (dx + radius) * (radius * 2 + 1)] = intensity - intensity * std::min<float>(sqrtf(dx * dx + dy * dy) / radius, 1.0f);
lightmap[v + u * map.height] += light->tiles[(dy + radius) + (dx + radius) * (radius * 2 + 1)];
}
}
}
return light;
}
| 24.463415
| 151
| 0.45339
|
PegasusEpsilon
|
e65224fda2e1aab14002e6a7e83c3043a7d6f82d
| 1,642
|
cpp
|
C++
|
MonoNative.Tests/mscorlib/System/Text/mscorlib_System_Text_EncoderFallbackBuffer_Fixture.cpp
|
brunolauze/MonoNative
|
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
|
[
"BSD-2-Clause"
] | 7
|
2015-03-10T03:36:16.000Z
|
2021-11-05T01:16:58.000Z
|
MonoNative.Tests/mscorlib/System/Text/mscorlib_System_Text_EncoderFallbackBuffer_Fixture.cpp
|
brunolauze/MonoNative
|
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
|
[
"BSD-2-Clause"
] | 1
|
2020-06-23T10:02:33.000Z
|
2020-06-24T02:05:47.000Z
|
MonoNative.Tests/mscorlib/System/Text/mscorlib_System_Text_EncoderFallbackBuffer_Fixture.cpp
|
brunolauze/MonoNative
|
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
|
[
"BSD-2-Clause"
] | null | null | null |
// Mono Native Fixture
// Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// Namespace: System.Text
// Name: EncoderFallbackBuffer
// C++ Typed Name: mscorlib::System::Text::EncoderFallbackBuffer
#include <gtest/gtest.h>
#include <mscorlib/System/Text/mscorlib_System_Text_EncoderFallbackBuffer.h>
#include <mscorlib/System/mscorlib_System_Type.h>
#include <mscorlib/System/mscorlib_System_String.h>
namespace mscorlib
{
namespace System
{
namespace Text
{
//Public Methods Tests
// Method Fallback
// Signature: mscorlib::System::Char charUnknown, mscorlib::System::Int32 index
TEST(mscorlib_System_Text_EncoderFallbackBuffer_Fixture,Fallback_1_Test)
{
}
// Method Fallback
// Signature: mscorlib::System::Char charUnknownHigh, mscorlib::System::Char charUnknownLow, mscorlib::System::Int32 index
TEST(mscorlib_System_Text_EncoderFallbackBuffer_Fixture,Fallback_2_Test)
{
}
// Method GetNextChar
// Signature:
TEST(mscorlib_System_Text_EncoderFallbackBuffer_Fixture,GetNextChar_Test)
{
}
// Method MovePrevious
// Signature:
TEST(mscorlib_System_Text_EncoderFallbackBuffer_Fixture,MovePrevious_Test)
{
}
// Method Reset
// Signature:
TEST(mscorlib_System_Text_EncoderFallbackBuffer_Fixture,Reset_Test)
{
}
//Public Properties Tests
// Property Remaining
// Return Type: mscorlib::System::Int32
// Property Get Method
TEST(mscorlib_System_Text_EncoderFallbackBuffer_Fixture,get_Remaining_Test)
{
}
}
}
}
| 20.78481
| 126
| 0.7162
|
brunolauze
|
e65447a2c87b48a6cafdd0ffaff7436edaa4fa41
| 142
|
cpp
|
C++
|
src/xr_3da/xrGame/TargetAssault.cpp
|
ixray-team/ixray-b2945
|
ad5ef375994ee9cd790c4144891e9f00e7efe565
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:19.000Z
|
2022-03-26T17:00:19.000Z
|
src/xr_3da/xrGame/TargetAssault.cpp
|
ixray-team/ixray-b2945
|
ad5ef375994ee9cd790c4144891e9f00e7efe565
|
[
"Linux-OpenIB"
] | null | null | null |
src/xr_3da/xrGame/TargetAssault.cpp
|
ixray-team/ixray-b2945
|
ad5ef375994ee9cd790c4144891e9f00e7efe565
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:21.000Z
|
2022-03-26T17:00:21.000Z
|
#include "stdafx.h"
#include "targetassault.h"
CTargetAssault::CTargetAssault(void)
{
}
CTargetAssault::~CTargetAssault(void)
{
}
| 12.909091
| 38
| 0.697183
|
ixray-team
|
e655e97ea240a2648c9d9fb388a84dfe3a9aa11d
| 270
|
cpp
|
C++
|
src/Main.cpp
|
david-carrera/language-optimization
|
961b33e0259e9ec9be50bbe7877d47360129b48d
|
[
"MIT"
] | null | null | null |
src/Main.cpp
|
david-carrera/language-optimization
|
961b33e0259e9ec9be50bbe7877d47360129b48d
|
[
"MIT"
] | null | null | null |
src/Main.cpp
|
david-carrera/language-optimization
|
961b33e0259e9ec9be50bbe7877d47360129b48d
|
[
"MIT"
] | null | null | null |
#include <ParameterCollection.hpp>
#include <LexicalMatrixCSVGenerator.hpp>
int main(int argc, char *argv[]) {
ParameterCollection params;
params.parse(argc, argv);
LexicalMatrixCSVGenerator csv(params);
csv.generate();
return EXIT_SUCCESS;
}
| 20.769231
| 42
| 0.714815
|
david-carrera
|
e657b5b7b7372232a5aa2fd24ffb0c781e073deb
| 6,215
|
hpp
|
C++
|
src/pyco_tree/pico_tree/_pyco_tree/map_straits.hpp
|
Jaybro/pico_tree
|
c6f7fb798b60452add7d0e940c4a7737cd72a992
|
[
"MIT"
] | 23
|
2020-07-19T23:03:01.000Z
|
2022-03-07T15:06:26.000Z
|
src/pyco_tree/pico_tree/_pyco_tree/map_straits.hpp
|
Jaybro/pico_tree
|
c6f7fb798b60452add7d0e940c4a7737cd72a992
|
[
"MIT"
] | 1
|
2021-01-26T16:53:16.000Z
|
2021-01-26T23:20:54.000Z
|
src/pyco_tree/pico_tree/_pyco_tree/map_straits.hpp
|
Jaybro/pico_tree
|
c6f7fb798b60452add7d0e940c4a7737cd72a992
|
[
"MIT"
] | 4
|
2021-03-04T14:03:28.000Z
|
2021-05-27T05:36:40.000Z
|
#pragma once
#include <pico_tree/core.hpp>
namespace pico_tree {
template <typename Scalar_, int Dim_>
class PointMap;
namespace internal {
template <typename Scalar_, int Dim_>
class PointMapBase {
public:
static_assert(
Dim_ == kDynamicDim || Dim_ > 0,
"SPATIAL_DIMENSION_MUST_DYNAMIC_OR_LARGER_THAN_0");
using ScalarType = Scalar_;
static int constexpr Dim = Dim_;
inline ScalarType const& operator()(std::size_t i) const { return data_[i]; }
inline ScalarType& operator()(std::size_t i) { return data_[i]; }
inline ScalarType const* data() const { return data_; }
inline ScalarType* data() { return data_; }
protected:
inline PointMapBase(ScalarType* data) : data_(data) {}
inline ~PointMapBase() = default;
ScalarType* data_;
};
template <typename Scalar_, int Dim_>
class SpaceMapBase {
public:
static_assert(
Dim_ == kDynamicDim || Dim_ > 0,
"SPATIAL_DIMENSION_MUST_DYNAMIC_OR_LARGER_THAN_0");
using ScalarType = Scalar_;
static int constexpr Dim = Dim_;
inline ScalarType const* data() const { return data_; }
inline ScalarType* data() { return data_; }
inline std::size_t npts() const { return npts_; }
protected:
inline SpaceMapBase(ScalarType* data, std::size_t npts)
: data_(data), npts_(npts) {}
ScalarType* data_;
std::size_t npts_;
};
} // namespace internal
//! \brief The PointMap class provides an interface for accessing a raw pointer
//! as a Point, allowing easy access to its coordinates.
template <typename Scalar_, int Dim_>
class PointMap : public internal::PointMapBase<Scalar_, Dim_> {
public:
using typename internal::PointMapBase<Scalar_, Dim_>::ScalarType;
using internal::PointMapBase<Scalar_, Dim_>::Dim;
inline PointMap(ScalarType* data)
: internal::PointMapBase<ScalarType, Dim>(data) {}
//! \private Streamlines interfaces with the kDynamicDim overload.
inline PointMap(ScalarType* data, std::size_t)
: internal::PointMapBase<ScalarType, Dim>(data) {}
inline std::size_t constexpr sdim() const {
return static_cast<std::size_t>(Dim);
}
};
//! \brief The PointMap class provides an interface for accessing a raw pointer
//! as a Point, allowing easy access to its coordinates.
template <typename Scalar_>
class PointMap<Scalar_, kDynamicDim>
: public internal::PointMapBase<Scalar_, kDynamicDim> {
public:
using typename internal::PointMapBase<Scalar_, kDynamicDim>::ScalarType;
using internal::PointMapBase<Scalar_, kDynamicDim>::Dim;
inline PointMap(ScalarType* data, std::size_t sdim)
: internal::PointMapBase<ScalarType, Dim>(data), sdim_(sdim) {}
inline std::size_t sdim() const { return sdim_; }
private:
std::size_t sdim_;
};
//! \brief The SpaceMap class provides an interface for accessing a raw pointer
//! as a Space, allowing easy access to its points via a PointMap interface.
template <typename Scalar_, int Dim_>
class SpaceMap : public internal::SpaceMapBase<Scalar_, Dim_> {
public:
using typename internal::SpaceMapBase<Scalar_, Dim_>::ScalarType;
using internal::SpaceMapBase<Scalar_, Dim_>::Dim;
using internal::SpaceMapBase<Scalar_, Dim_>::data_;
inline SpaceMap(ScalarType* data, std::size_t npts)
: internal::SpaceMapBase<ScalarType, Dim>(data, npts) {}
//! \private Streamlines interfaces with the kDynamicDim overload.
inline SpaceMap(ScalarType* data, std::size_t npts, std::size_t)
: internal::SpaceMapBase<ScalarType, Dim>(data, npts) {}
inline PointMap<ScalarType const, Dim> operator()(std::size_t i) const {
return {data_ + i * Dim};
}
inline PointMap<ScalarType, Dim> operator()(std::size_t i) {
return {data_ + i * Dim};
}
inline std::size_t constexpr sdim() const {
return static_cast<std::size_t>(Dim);
}
};
//! \brief The SpaceMap class provides an interface for accessing a raw pointer
//! as a Space, allowing easy access to its points via a PointMap interface.
template <typename Scalar_>
class SpaceMap<Scalar_, kDynamicDim>
: public internal::SpaceMapBase<Scalar_, kDynamicDim> {
public:
using typename internal::SpaceMapBase<Scalar_, kDynamicDim>::ScalarType;
using internal::SpaceMapBase<Scalar_, kDynamicDim>::Dim;
using internal::SpaceMapBase<Scalar_, kDynamicDim>::data_;
inline SpaceMap(ScalarType* data, std::size_t npts, std::size_t sdim)
: internal::SpaceMapBase<ScalarType, Dim>(data, npts), sdim_(sdim) {}
inline PointMap<ScalarType const, Dim> operator()(std::size_t i) const {
return {data_ + i * sdim_, sdim_};
}
inline PointMap<ScalarType, Dim> operator()(std::size_t i) {
return {data_ + i * sdim_, sdim_};
}
inline std::size_t sdim() const { return sdim_; }
private:
std::size_t sdim_;
};
template <typename Scalar_, int Dim_>
struct StdPointTraits<PointMap<Scalar_, Dim_>> {
using ScalarType = Scalar_;
static int constexpr Dim = Dim_;
inline static ScalarType const* Coords(PointMap<Scalar_, Dim_> const& point) {
return point.data();
}
inline static int Sdim(PointMap<Scalar_, Dim_> const& point) {
return static_cast<int>(point.sdim());
}
};
//! \brief MapTraits provides an interface for SpaceMap and points supported by
//! StdPointTraits.
//! \tparam Index_ Type used for indexing. Defaults to int.
template <typename Scalar_, int Dim_, typename Index_ = int>
struct MapTraits {
using SpaceType = SpaceMap<Scalar_, Dim_>;
using PointType = PointMap<Scalar_ const, Dim_>;
using ScalarType = Scalar_;
static constexpr int Dim = Dim_;
using IndexType = Index_;
inline static int SpaceSdim(SpaceType const& space) {
return static_cast<IndexType>(space.sdim());
}
inline static IndexType SpaceNpts(SpaceType const& space) {
return static_cast<IndexType>(space.npts());
}
inline static PointType PointAt(SpaceType const& space, IndexType const idx) {
return space(idx);
}
template <typename OtherPoint>
inline static int PointSdim(OtherPoint const& point) {
return StdPointTraits<OtherPoint>::Sdim(point);
}
template <typename OtherPoint>
inline static ScalarType const* PointCoords(OtherPoint const& point) {
return StdPointTraits<OtherPoint>::Coords(point);
}
};
} // namespace pico_tree
| 31.388889
| 80
| 0.721802
|
Jaybro
|
e657e3d1bdcd9d9c608190baf3291280f46c8898
| 18,780
|
hpp
|
C++
|
templates/riscv-csr.hpp
|
five-embeddev/riscv-csr-access
|
998876885bf6fced2095d034972c82a9bb878ae0
|
[
"Unlicense"
] | 2
|
2021-06-15T03:16:52.000Z
|
2022-03-06T15:23:39.000Z
|
templates/riscv-csr.hpp
|
five-embeddev/riscv-csr-access
|
998876885bf6fced2095d034972c82a9bb878ae0
|
[
"Unlicense"
] | null | null | null |
templates/riscv-csr.hpp
|
five-embeddev/riscv-csr-access
|
998876885bf6fced2095d034972c82a9bb878ae0
|
[
"Unlicense"
] | null | null | null |
/*
Register access classes for RISC-V system registers.
SPDX-License-Identifier: Unlicense
https://five-embeddev.com/
*/
#ifndef RISCV_CSR_HPP
#define RISCV_CSR_HPP
#include <cstdint>
// ------------------------------------------------------------------------
// Base and common classes
namespace riscv {
namespace csr {
#if __riscv_xlen==32
using uint_xlen_t = std::uint32_t;
using uint_csr32_t = std::uint32_t;
using uint_csr64_t = std::uint32_t;
#elif __riscv_xlen==64
using uint_xlen_t = std::uint64_t;
using uint_csr32_t = std::uint32_t;
using uint_csr64_t = std::uint64_t;
#else
#error "riscv::csr: unknown __riscv_xlen"
#endif
/** Immediate instructions use a 5 bit immediate field */
static constexpr uint_xlen_t CSR_IMM_OP_MASK = 0x01F;
/** CSR: Read only, and read-write base class */
template<class C> class read_only_reg {
public :
using read_datatype_t = typename C::datatype;
read_only_reg(void) {}
read_only_reg(const read_only_reg&) = delete;
read_only_reg& operator=(const read_only_reg&) = delete;
/** Read the CSR value */
static inline read_datatype_t read(void) {
return C::read();
}
/** Operator alias to read the CSR value */
inline read_datatype_t operator()(void) {
return C::read();
}
};
/** CSR: Write only, and read-write base class */
template<class C> class write_only_reg {
public :
using write_datatype_t = typename C::datatype;
write_only_reg(void) {}
write_only_reg(const write_only_reg&) = delete;
write_only_reg& operator=(const write_only_reg&) = delete;
/** Write a constant to the CSR. */
template<write_datatype_t VALUE> void write_const(void) {
if constexpr ((VALUE & CSR_IMM_OP_MASK) == VALUE) {
C::write_imm(VALUE);
} else {
C::write(VALUE);
}
}
/** Write to the CSR. */
inline void write(const write_datatype_t value) {
C::write(value);
}
/** Set a constant mask of bits in the CSR. */
template<write_datatype_t MASK> void set_const(void) {
if constexpr ((MASK & CSR_IMM_OP_MASK) == MASK) {
C::set_bits_imm(MASK);
} else {
C::set_bits(MASK);
}
}
/** Set a mask of bits in the CSR. */
inline void set(write_datatype_t mask) {
C::set_bits(mask);
}
/** Clear a constant mask of bits in the CSR. */
template<write_datatype_t MASK> void clr_const(void) {
if constexpr ((MASK & CSR_IMM_OP_MASK) == MASK) {
C::clr_bits_imm(MASK);
} else {
C::clr_bits(MASK);
}
}
/** Clear a mask of bits in the CSR. */
inline void clr(write_datatype_t mask) {
C::clr_bits(mask);
}
/** Operator alias to set mask of bits in the CSR. */
inline void operator|=(write_datatype_t mask) {
C::set_bits(mask);
}
};
/** CSR: Read-write base class */
template<class C> class read_write_reg : public read_only_reg<C>,
public write_only_reg<C> {
public:
using datatype_t = typename C::datatype;
read_write_reg(void)
: read_only_reg<C>()
, write_only_reg<C>()
{}
read_write_reg(const read_write_reg&)=delete;
read_write_reg& operator=(const read_write_reg&)=delete;
/** Read from, then write a constant value to the CSR. */
template<datatype_t VALUE> datatype_t read_write_const(void) {
if constexpr ((VALUE & CSR_IMM_OP_MASK) == VALUE) {
return C::read_write_imm(VALUE);
} else {
return C::read_write(VALUE);
}
}
/** Read from, then write to the CSR. */
inline datatype_t read_write(const datatype_t value) {
return C::read_write(value);
}
/** Read from, then set a constant bit mask to the CSR. */
template<datatype_t MASK> datatype_t read_set_bits_const(void) {
if constexpr ((MASK & CSR_IMM_OP_MASK) == MASK) {
return C::read_set_bits_imm(MASK);
} else {
return C::read_set_bits(MASK);
}
}
/** Read from, then set a bit mask to the CSR. */
inline datatype_t read_set_bits(const datatype_t mask) {
return C::read_set_bits(mask);
}
/** Read from, then clear a constant bit mask to the CSR. */
template<datatype_t MASK> datatype_t read_clr_bits_const(void) {
if constexpr ((MASK & CSR_IMM_OP_MASK) == MASK) {
return C::read_clr_bits_imm(MASK);
} else {
return C::read_clr_bits(MASK);
}
}
/** Read from, then clear a bit mask to the CSR. */
inline datatype_t read_clr_bits(const datatype_t mask) {
return C::read_clr_bits(mask);
}
};
/** CSR Field: Read only, and read-write base class */
template<class C, class F> class read_only_field {
public:
using read_datatype_t = typename F::datatype;
read_only_field(void) {}
read_only_field(const read_only_field&)=delete;
read_only_field& operator=(const read_only_field&)=delete;
/** Read a given field value from a CSR */
read_datatype_t read(void) {
return (read_datatype_t) ((C::read() & F::BIT_MASK) >> F::BIT_OFFSET);
}
};
/** CSR Field: Write only, and read-write base class */
template<class C, class F> class write_only_field {
public:
using write_datatype_t = typename F::datatype;
using reg_write_datatype_t = typename C::datatype;
write_only_field(void) {}
write_only_field(const write_only_field&)=delete;
write_only_field& operator=(const write_only_field&)=delete;
inline void set(void) {
if constexpr ((F::BIT_MASK & CSR_IMM_OP_MASK) == F::BIT_MASK) {
C::set_bits_imm(F::BIT_MASK);
} else {
C::set_bits(F::BIT_MASK);
}
}
inline void clr(void) {
if constexpr ((F::BIT_MASK & CSR_IMM_OP_MASK) == F::BIT_MASK) {
C::clr_bits_imm(F::BIT_MASK);
} else {
C::clr_bits(F::BIT_MASK);
}
}
};
/** CSR Field: Read-write base class */
template<class C, class F> class read_write_field
: public read_only_field<C,F>
, public write_only_field<C,F> {
public:
using datatype_t = typename F::datatype;
using reg_datatype_t = typename C::datatype;
read_write_field(void)
: read_only_field<C,F>()
, write_only_field<C,F>()
{}
read_write_field(const read_write_field&)=delete;
read_write_field& operator=(const read_write_field&)=delete;
/* Read-modify-write to write a field.
NOTE - not atomic.
*/
inline void write(const datatype_t value) {
auto org_value = C::read();
auto new_value = (org_value & ~F::BIT_MASK) |
(((reg_datatype_t)value << F::BIT_OFFSET) & F::BIT_MASK);
C::write(new_value);
}
/* Read-modify-write to set a field, and return original value.
NOTE - not atomic.
*/
inline datatype_t read_write(const datatype_t value) {
auto org_value = C::read();
auto new_value = (org_value & ~F::BIT_MASK) |
(((reg_datatype_t)value << F::BIT_OFFSET) & F::BIT_MASK);
C::write(new_value);
return (datatype_t) ((org_value & F::BIT_MASK) >> F::BIT_OFFSET);
}
};
/** CSR access context and read/write permission.
*/
typedef enum {
{% for p in data.addr.priv['values'] -%}
{% for rw in data.addr.rw['values'] -%}
{{p.key}}{{rw.key}},
{% endfor -%}
{% endfor %}
{% for rw in data.addr.rw['values'] -%}
D{{rw.key}},
{% endfor -%}
} priv_t;
} /* csr */
} /* riscv */
// ------------------------------------------------------------------------
// Assembler operations and bit field definitions
namespace riscv {
namespace csr {
{%- for reg_name,reg_data in data.regs.items() %}
// ----------------------------------------------------------------
// {{reg_name}} - {{reg_data.priv}} - {{reg_data.desc}}
//
{%- set ctype_reg = reg_data|csr_ctype %}
{%- set ctype_arg = reg_data|arg_ctype %}
{%- set ctype_imm = "const uint8_t" %}
{%- if not reg_data.mmio %}
/** {{reg_data.desc}} assembler operations */
struct {{reg_name}}_ops {
using datatype = {{ctype_reg}};
static constexpr priv_t priv = {{reg_data.priv}};
{% if "R" in reg_data.priv %}
/** Read {{reg_name}} */
static {{ctype_arg}} read(void) {
{{ctype_reg}} value;
__asm__ volatile ("csrr %0, {{reg_name}}"
: "=r" (value) /* output : register */
: /* input : none */
: /* clobbers: none */);
return value;
}
{%endif%}
{% if "W" in reg_data.priv %}
/** Write {{reg_name}} */
static void write({{ctype_reg}} value) {
__asm__ volatile ("csrw {{reg_name}}, %0"
: /* output: none */
: "r" (value) /* input : from register */
: /* clobbers: none */);
}
/** Write immediate value to {{reg_name}} */
static void write_imm({{ctype_reg}} value) {
__asm__ volatile ("csrwi {{reg_name}}, %0"
: /* output: none */
: "i" (value) /* input : from immediate */
: /* clobbers: none */);
}
/** Read and then write to {{reg_name}} */
static {{ctype_arg}} read_write({{ctype_reg}} new_value) {
{{ctype_reg}} prev_value;
__asm__ volatile ("csrrw %0, {{reg_name}}, %1"
: "=r" (prev_value) /* output: register %0 */
: "r" (new_value) /* input : register */
: /* clobbers: none */);
return prev_value;
}
/** Read and then write immediate value to {{reg_name}} */
static {{ctype_arg}} read_write_imm({{ctype_imm}} new_value) {
{{ctype_reg}} prev_value;
__asm__ volatile ("csrrwi %0, {{reg_name}}, %1"
: "=r" (prev_value) /* output: register %0 */
: "i" (new_value) /* input : register */
: /* clobbers: none */);
return prev_value;
}
// ------------------------------------------
// Register CSR bit set and clear instructions
/** Atomic modify and set bits for {{reg_name}} */
static void set_bits({{ctype_reg}} mask) {
__asm__ volatile ("csrrs zero, {{reg_name}}, %0"
: /* output: none */
: "r" (mask) /* input : register */
: /* clobbers: none */);
}
/** Atomic read and then and set bits for {{reg_name}} */
static uint32_t read_set_bits({{ctype_reg}} mask) {
{{ctype_reg}} value;
__asm__ volatile ("csrrs %0, {{reg_name}}, %1"
: "=r" (value) /* output: register %0 */
: "r" (mask) /* input : register */
: /* clobbers: none */);
return value;
}
/** Atomic modify and clear bits for {{reg_name}} */
static void clr_bits({{ctype_reg}} mask) {
__asm__ volatile ("csrrc zero, {{reg_name}}, %0"
: /* output: none */
: "r" (mask) /* input : register */
: /* clobbers: none */);
}
/** Atomic read and then and clear bits for {{reg_name}} */
static uint32_t read_clr_bits({{ctype_reg}} mask) {
{{ctype_reg}} value;
__asm__ volatile ("csrrc %0, {{reg_name}}, %1"
: "=r" (value) /* output: register %0 */
: "r" (mask) /* input : register */
: /* clobbers: none */);
return value;
}
// ------------------------------------------
// Immediate value CSR bit set and clear instructions (only up to 5 bits)
/** Atomic modify and set bits from immediate for {{reg_name}} */
static void set_bits_imm({{ctype_imm}} mask) {
__asm__ volatile ("csrrsi zero, {{reg_name}}, %0"
: /* output: none */
: "i" (mask) /* input : register */
: /* clobbers: none */);
}
/** Atomic read and then and set bits from immediate for {{reg_name}} */
static {{ctype_arg}} read_set_bits_imm({{ctype_imm}} mask) {
{{ctype_reg}} value;
__asm__ volatile ("csrrsi %0, {{reg_name}}, %1"
: "=r" (value) /* output: register %0 */
: "i" (mask) /* input : register */
: /* clobbers: none */);
return value;
}
/** Atomic modify and clear bits from immediate for {{reg_name}} */
static void clr_bits_imm({{ctype_imm}} mask) {
__asm__ volatile ("csrrci zero, {{reg_name}}, %0"
: /* output: none */
: "i" (mask) /* input : register */
: /* clobbers: none */);
}
/** Atomic read and then and clear bits from immediate for {{reg_name}} */
static {{ctype_arg}} read_clr_bits_imm({{ctype_imm}} mask) {
{{ctype_reg}} value;
__asm__ volatile ("csrrci %0, {{reg_name}}, %1"
: "=r" (value) /* output: register %0 */
: "i" (mask) /* input : register */
: /* clobbers: none */);
return value;
}
{%endif%}
}; /* {{reg_name}}_ops */
{%- if reg_data.fields %}
/** Parameter data for fields in {{reg_name}} */
namespace {{reg_name}}_data {
{%-for field_name,field_data in reg_data.fields.items() %}
{%- set bit_width = field_data|csr_bit_width %}
{%- set bit_offset = field_data|csr_bit_offset %}
/** Parameter data for {{field_name}} */
struct {{field_name}} {
using datatype = {{field_data|csr_ctype}};
static constexpr {{ctype_reg}} BIT_OFFSET = {{bit_offset}};
static constexpr {{ctype_reg}} BIT_WIDTH = {{bit_width}};
static constexpr {{ctype_reg}} BIT_MASK = {{bit_offset|csr_format_mask(bit_width)}};
static constexpr {{ctype_reg}} ALL_SET_MASK = {{0|csr_format_mask(bit_width)}};
};
{%- endfor%}
} /* {{reg_name}}_data */
{%-endif%}
{%- endif%}
{%- endfor%}
} /* csr */
} /* riscv */
// ------------------------------------------------------------------------
// Register and field interface classes.
namespace riscv {
namespace csr {
{%-for reg_name,reg_data in data.regs.items() %}
{%-if not reg_data.mmio %}
{%- set reg_template_class = "riscv::csr::" + reg_name + "_ops" %}
{%-if "WO" in reg_data.priv %}
{%- set priv = "write_only" %}
{%-elif "RW" in reg_data.priv %}
{%- set priv = "read_write" %}
{%-else%}
{%- set priv = "read_only" %}
{%-endif%}
/* {{reg_data.desc}} */
template<class OPS> class {{reg_name}}_reg : public {{priv}}_reg<OPS>
{
{%- if reg_data.fields %}
public:
{%-for field_name,field_data in reg_data.fields.items() %}
{%- set field_template_class = "OPS, riscv::csr::" + reg_name + "_data::" + field_name %}
{{priv}}_field<{{field_template_class}}> {{field_name}};
{%- endfor %}
{%- endif %}
};
using {{reg_name}} = {{reg_name}}_reg<{{reg_template_class}}>;
{%-endif%}
{%-endfor%}
/** Encapsulate all CSRs in a single structure.
- No storage is required by this class.
*/
struct all {
{%-for reg_name,reg_data in data.regs.items() %}
{%-if not reg_data.mmio %}
/* {{reg_data.desc}} */
riscv::csr::{{reg_name}} {{reg_name}};
{%-endif%}
{%-endfor%}
};
} /* csr */
static csr::all csrs;
} /* riscv */
#endif // #define RISCV_CSR_HPP
| 41.733333
| 105
| 0.456816
|
five-embeddev
|
e658f300d2b7229d81969c983cd015dfec01adc2
| 6,096
|
cpp
|
C++
|
cpp/libs/src/opendnp3/outstation/Database.cpp
|
sidhoda/dnp3
|
0469f308cb3321e8f5b57ccc2e26a34eb430941c
|
[
"Apache-2.0"
] | null | null | null |
cpp/libs/src/opendnp3/outstation/Database.cpp
|
sidhoda/dnp3
|
0469f308cb3321e8f5b57ccc2e26a34eb430941c
|
[
"Apache-2.0"
] | null | null | null |
cpp/libs/src/opendnp3/outstation/Database.cpp
|
sidhoda/dnp3
|
0469f308cb3321e8f5b57ccc2e26a34eb430941c
|
[
"Apache-2.0"
] | null | null | null |
/*
* Licensed to Green Energy Corp (www.greenenergycorp.com) under one or
* more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Green Energy Corp 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.
*
* This project was forked on 01/01/2013 by Automatak, LLC and modifications
* may have been made to this file. Automatak, LLC licenses these modifications
* to you under the terms of the License.
*/
#include "Database.h"
#include <openpal/logging/LogMacros.h>
#include <assert.h>
using namespace openpal;
namespace opendnp3
{
Database::Database(const DatabaseSizes& dbSizes, IEventReceiver& eventReceiver, IndexMode indexMode, StaticTypeBitField allowedClass0Types) :
eventReceiver(&eventReceiver),
indexMode(indexMode),
buffers(dbSizes, allowedClass0Types, indexMode)
{
}
bool Database::Update(const Binary& value, uint16_t index, EventMode mode)
{
return this->UpdateEvent<BinarySpec>(value, index, mode);
}
bool Database::Update(const DoubleBitBinary& value, uint16_t index, EventMode mode)
{
return this->UpdateEvent<DoubleBitBinarySpec>(value, index, mode);
}
bool Database::Update(const Analog& value, uint16_t index, EventMode mode)
{
return this->UpdateEvent<AnalogSpec>(value, index, mode);
}
bool Database::Update(const Counter& value, uint16_t index, EventMode mode)
{
return this->UpdateEvent<CounterSpec>(value, index, mode);
}
bool Database::Update(const FrozenCounter& value, uint16_t index, EventMode mode)
{
return this->UpdateEvent<FrozenCounterSpec>(value, index, mode);
}
bool Database::Update(const BinaryOutputStatus& value, uint16_t index, EventMode mode)
{
return this->UpdateEvent<BinaryOutputStatusSpec>(value, index, mode);
}
bool Database::Update(const AnalogOutputStatus& value, uint16_t index, EventMode mode)
{
return this->UpdateEvent<AnalogOutputStatusSpec>(value, index, mode);
}
bool Database::Update(const OctetString& value, uint16_t index, EventMode mode)
{
return this->UpdateEvent<OctetStringSpec>(value, index, mode);
}
bool Database::Update(const TimeAndInterval& value, uint16_t index)
{
auto rawIndex = GetRawIndex<TimeAndIntervalSpec>(index);
auto view = buffers.buffers.GetArrayView<TimeAndIntervalSpec>();
if (view.Contains(rawIndex))
{
view[rawIndex].value = value;
return true;
}
else
{
return false;
}
}
bool Database::Modify(FlagsType type, uint16_t start, uint16_t stop, uint8_t flags)
{
switch (type)
{
case(FlagsType::BinaryInput):
return Modify<BinarySpec>(start, stop, flags);
case(FlagsType::DoubleBinaryInput):
return Modify<DoubleBitBinarySpec>(start, stop, flags);
case(FlagsType::AnalogInput):
return Modify<AnalogSpec>(start, stop, flags);
case(FlagsType::Counter):
return Modify<CounterSpec>(start, stop, flags);
case(FlagsType::FrozenCounter):
return Modify<FrozenCounterSpec>(start, stop, flags);
case(FlagsType::BinaryOutputStatus):
return Modify<BinaryOutputStatusSpec>(start, stop, flags);
case(FlagsType::AnalogOutputStatus):
return Modify<AnalogOutputStatusSpec>(start, stop, flags);
}
return false;
}
bool Database::ConvertToEventClass(PointClass pc, EventClass& ec)
{
switch (pc)
{
case(PointClass::Class1) :
ec = EventClass::EC1;
return true;
case(PointClass::Class2) :
ec = EventClass::EC2;
return true;
case(PointClass::Class3) :
ec = EventClass::EC3;
return true;
default:
return false;
}
}
template <class Spec>
uint16_t Database::GetRawIndex(uint16_t index)
{
if (indexMode == IndexMode::Contiguous)
{
return index;
}
else
{
auto view = buffers.buffers.GetArrayView<Spec>();
auto result = IndexSearch::FindClosestRawIndex(view, index);
return result.match ? result.index : openpal::MaxValue<uint16_t>();
}
}
template <class Spec>
bool Database::UpdateEvent(const typename Spec::meas_t& value, uint16_t index, EventMode mode)
{
const auto rawIndex = GetRawIndex<Spec>(index);
auto view = buffers.buffers.GetArrayView<Spec>();
if (view.Contains(rawIndex))
{
this->UpdateAny(view[rawIndex], value, mode);
return true;
}
else
{
return false;
}
}
template <class Spec>
bool Database::UpdateAny(Cell<Spec>& cell, const typename Spec::meas_t& value, EventMode mode)
{
switch (mode)
{
case(EventMode::Force):
case(EventMode::EventOnly):
this->TryCreateEvent(cell, value);
break;
case(EventMode::Detect):
if (cell.event.IsEvent(cell.config, value))
{
this->TryCreateEvent(cell, value);
}
break;
default:
break;
}
// we always update the static value unless the mode is EventOnly
if (mode != EventMode::EventOnly)
{
cell.value = value;
}
return true;
}
template <class Spec>
void Database::TryCreateEvent(Cell<Spec>& cell, const typename Spec::meas_t& value)
{
EventClass ec;
// don't create an event if point is assigned to Class 0
if (ConvertToEventClass(cell.config.clazz, ec))
{
cell.event.lastEvent = value;
this->eventReceiver->Update(Event<Spec>(value, cell.config.vIndex, ec, cell.config.evariation));
}
}
template <class Spec>
bool Database::Modify(uint16_t start, uint16_t stop, uint8_t flags)
{
auto rawStart = GetRawIndex<Spec>(start);
auto rawStop = GetRawIndex<Spec>(stop);
auto view = buffers.buffers.GetArrayView<Spec>();
if (view.Contains(rawStart) && view.Contains(rawStop) && (rawStart <= rawStop))
{
for (uint16_t i = rawStart; i <= rawStop; ++i)
{
auto copy = view[i].value;
copy.flags = flags;
this->UpdateAny(view[i], copy, EventMode::Detect);
}
return true;
}
else
{
return false;
}
}
}
| 25.721519
| 141
| 0.739009
|
sidhoda
|
e6595de9170536bc7a187bee370ae363cca68d1c
| 1,013
|
cpp
|
C++
|
SimpleEngine3D/core/graphic/shadow_buffer.cpp
|
lukaszlipski/SimpleEngine3D
|
8fd81ff17512eed7f84e0b18e94c1a7f9754f573
|
[
"Apache-2.0"
] | 1
|
2021-08-31T01:45:11.000Z
|
2021-08-31T01:45:11.000Z
|
SimpleEngine3D/core/graphic/shadow_buffer.cpp
|
lukaszlipski/SimpleEngine3D
|
8fd81ff17512eed7f84e0b18e94c1a7f9754f573
|
[
"Apache-2.0"
] | null | null | null |
SimpleEngine3D/core/graphic/shadow_buffer.cpp
|
lukaszlipski/SimpleEngine3D
|
8fd81ff17512eed7f84e0b18e94c1a7f9754f573
|
[
"Apache-2.0"
] | null | null | null |
#include "shadow_buffer.h"
#include "../system/graphics.h"
namespace SE3D
{
ShadowBuffer::ShadowBuffer(int32 width, int32 height)
: m_Width(width), m_Height(height), m_DepthMap(width, height, TextureSettings(ImageFormat::DEPTH_COMPONENT, InternalFormat::DEPTH_COMPONENT, ImageType::FLOAT, TextureFilter::NEAREST, TextureWrap::CLAMP_TO_BORDER, Vector4D(1.0f,1.0f,1.0f,1.0f)))
{
glGenFramebuffers(1, &m_ShadowBuffer);
glBindFramebuffer(GL_FRAMEBUFFER, m_ShadowBuffer);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_DepthMap.GetTextureID(), 0);
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
ShadowBuffer::~ShadowBuffer()
{
glDeleteFramebuffers(1, &m_ShadowBuffer);
}
void ShadowBuffer::Bind() const
{
glBindFramebuffer(GL_FRAMEBUFFER, m_ShadowBuffer);
}
void ShadowBuffer::Unbind() const
{
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void ShadowBuffer::Clear() const
{
glClear(GL_DEPTH_BUFFER_BIT);
}
}
| 25.974359
| 246
| 0.766041
|
lukaszlipski
|
e65d6c3a2f5f8039b408a9aa2c3cba65c31d766f
| 2,183
|
cpp
|
C++
|
Day3/Part2/main.cpp
|
jgomezselles/aoc_2021
|
6901a4a249263d328ae43934f099a276b7ef0b41
|
[
"MIT"
] | null | null | null |
Day3/Part2/main.cpp
|
jgomezselles/aoc_2021
|
6901a4a249263d328ae43934f099a276b7ef0b41
|
[
"MIT"
] | null | null | null |
Day3/Part2/main.cpp
|
jgomezselles/aoc_2021
|
6901a4a249263d328ae43934f099a276b7ef0b41
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <fstream>
#include <string>
#include <bitset>
#include <vector>
#include <algorithm>
void remove_with_ones(std::vector<std::bitset<12>> &res, const size_t i)
{
res.erase(std::remove_if(res.begin(), res.end(),
[i](std::bitset<12> bs)
{ return bs[i]; }),
res.end());
}
void remove_with_zeros(std::vector<std::bitset<12>> &res, const size_t i)
{
res.erase(std::remove_if(res.begin(), res.end(),
[i](std::bitset<12> bs)
{ return !bs[i]; }),
res.end());
}
std::pair<size_t, size_t> process_instructions()
{
std::ifstream input("input.txt");
if (!input)
{
std::cerr << "Cannot open the input.txt" << std::endl;
return {};
}
std::vector<std::bitset<12>> saved;
std::string line;
while (std::getline(input, line))
{
saved.push_back(std::bitset<12>(line));
}
input.close();
auto o2_copy = saved;
for (size_t i = 12-1; i >= 0; --i)
{
size_t ones{0};
for (const auto &s : o2_copy)
{
ones += s[i];
}
if (2 * ones >= o2_copy.size())
{
remove_with_zeros(o2_copy, i);
}
else
{
remove_with_ones(o2_copy, i);
}
if (o2_copy.size() == 1)
{
break;
}
}
auto co2_copy = saved;
for (size_t i = 12-1; i >= 0; --i)
{
size_t ones{0};
for (const auto &s : co2_copy)
{
ones += s[i];
}
if (2 * ones < co2_copy.size())
{
remove_with_zeros(co2_copy, i);
}
else
{
remove_with_ones(co2_copy, i);
}
if (co2_copy.size() == 1)
{
break;
}
}
return {o2_copy.front().to_ulong(), co2_copy.front().to_ulong()};
}
int main()
{
auto [o2, co2] = process_instructions();
std::cout << "o2: " << o2 << ", "
<< "co2: " << co2 << std::endl;
std::cout << "Result is " << o2 * co2 << std::endl;
return 0;
}
| 21.83
| 73
| 0.457169
|
jgomezselles
|
e661e70c94cf2cdfcaf2361a0897bc29c2092b31
| 4,125
|
hpp
|
C++
|
Project/Engine/Include/Engine/Application.hpp
|
lcomstive/PhysicsAssignment
|
67a3d1e94411b9cf7350c5cb10d9d7aa33d205f0
|
[
"MIT"
] | null | null | null |
Project/Engine/Include/Engine/Application.hpp
|
lcomstive/PhysicsAssignment
|
67a3d1e94411b9cf7350c5cb10d9d7aa33d205f0
|
[
"MIT"
] | null | null | null |
Project/Engine/Include/Engine/Application.hpp
|
lcomstive/PhysicsAssignment
|
67a3d1e94411b9cf7350c5cb10d9d7aa33d205f0
|
[
"MIT"
] | null | null | null |
#pragma once
#include <string>
#include <chrono>
#include <glm/glm.hpp> // Maths library
#include <glad/glad.h> // Modern OpenGL loader
#include <GLFW/glfw3.h> // Window & input handling
#include <Engine/Log.hpp> // Console logging
#include <Engine/Input.hpp> // Handles keyboard & mouse input
#include <Engine/Scene.hpp> // Holds game objects & state
using namespace std::chrono_literals; // seconds in literal
namespace Engine
{
struct ApplicationArgs
{
/// <summary>
/// Vertical sync
/// </summary>
bool VSync = true;
/// <summary>
/// Anti-aliasing samples.
/// Range is 0-16
/// </summary>
unsigned int Samples = 1;
/// <summary>
/// Window title
/// </summary>
std::string Title = "Application";
/// <summary>
/// Window resolution
/// </summary>
glm::ivec2 Resolution = { 1280, 720 };
/// <summary>
/// Physics fixed timestep
/// </summary>
std::chrono::milliseconds FixedTimestep = 50ms;
/// <summary>
/// Take up the entire primary monitor
/// </summary>
bool Fullscreen = false;
};
class Application
{
Scene m_Scene;
friend class Engine::Physics::PhysicsSystem;
protected:
/// <summary>
/// When a frame is ready to be drawn
/// </summary>
virtual void OnDraw() { }
/// <summary>
/// When gizmos are ready to be drawn
/// </summary>
virtual void OnDrawGizmos() { }
/// <summary>
/// Called once before each draw call
/// </summary>
/// <param name="deltaTime">Time, in milliseconds, since last frame</param>
virtual void OnUpdate() { }
/// <summary>
/// When the class has been initialised.
/// Typical usage is pre-loading assets.
/// </summary>
virtual void OnStart() { }
/// <summary>
/// Application is being closed
/// </summary>
virtual void OnShutdown() { }
/// <summary>
/// Called when the window has been resized
/// </summary>
/// <param name="resolution">New width & height in pixels</param>
virtual void OnResized(glm::ivec2 resolution) { }
public:
/// <summary>
/// Local directory containing assets intended for use with the application.
/// Always has a leading slash.
/// </summary>
const static std::string AssetDir;
Application(ApplicationArgs args = {});
/// <summary>
/// Launches application and begins rendering loop on the current thread.
/// </summary>
void Run();
/// <summary>
/// Informs the application to close and release resources
/// </summary>
void Exit();
/// <summary>
/// The active scene
/// </summary>
Scene* CurrentScene();
/// <summary>
/// Renames the application window title
/// </summary>
void SetTitle(std::string title);
/// <returns>True if currently fullscreen mode</returns>
bool GetFullscreen();
/// <summary>
/// If fullscreen, make not fullscreen... and vice versa
/// </summary>
void ToggleFullscreen();
/// <summary>
/// Sets the application window fullscreen or windowed
/// </summary>
void SetFullscreen(bool fullscreen);
private:
GLFWwindow* m_Window;
ApplicationArgs m_Args;
// Cache windowed resolution, for when coming out of fullscreen mode
glm::ivec2 m_WindowedResolution;
static Application* s_Instance;
void SetupGizmos();
void CreateAppWindow();
#pragma region GLFW Callbacks
static void GLFW_WindowCloseCallback(GLFWwindow* window);
static void GLFW_ErrorCallback(int error, const char* description);
static void GLFW_ScrollCallback(GLFWwindow* window, double xOffset, double yOffset);
static void GLFW_MouseCallback(GLFWwindow* window, int button, int action, int mods);
static void GLFW_CursorPositionCallback(GLFWwindow* window, double xPos, double yPos);
static void GLFW_FramebufferResizeCallback(GLFWwindow* window, int width, int height);
static void GLFW_KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods);
static void GLFW_DebugOutput(GLenum source, GLenum type, unsigned int id, GLenum severity, GLsizei length, const char* msg, const void* userParam);
#pragma endregion
};
}
#define APPLICATION_MAIN(type) \
int main() { \
type().Run(); \
return 0; \
}
| 25.78125
| 149
| 0.675394
|
lcomstive
|
e66418a9b23fd517c7f61465c2e635661535614f
| 325
|
cpp
|
C++
|
Vulkan Renderer/main.cpp
|
Javernus/3D-Engine
|
8fe6fc7464153cd57086cf8264547cd0573d5e44
|
[
"MIT"
] | null | null | null |
Vulkan Renderer/main.cpp
|
Javernus/3D-Engine
|
8fe6fc7464153cd57086cf8264547cd0573d5e44
|
[
"MIT"
] | null | null | null |
Vulkan Renderer/main.cpp
|
Javernus/3D-Engine
|
8fe6fc7464153cd57086cf8264547cd0573d5e44
|
[
"MIT"
] | null | null | null |
//
// main.cpp
// Vulkan Renderer
//
// Created by Jake Jongejans on 13/11/2021.
//
#include "main.hpp"
#include "VKRenderer/VKRenderer.hpp"
int main() {
VKRenderer app;
try {
app.run();
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
| 14.130435
| 44
| 0.627692
|
Javernus
|
e66f0fa259a39793b2ae63c2fb7ae8e900527e45
| 2,642
|
cpp
|
C++
|
DeusServer/SerializableSkillComponent.cpp
|
Suliac/ProjectDeusServer
|
b7af922a6bc2596c733665898b6aefd989bf2270
|
[
"MIT"
] | null | null | null |
DeusServer/SerializableSkillComponent.cpp
|
Suliac/ProjectDeusServer
|
b7af922a6bc2596c733665898b6aefd989bf2270
|
[
"MIT"
] | null | null | null |
DeusServer/SerializableSkillComponent.cpp
|
Suliac/ProjectDeusServer
|
b7af922a6bc2596c733665898b6aefd989bf2270
|
[
"MIT"
] | null | null | null |
#include "SerializableSkillComponent.h"
namespace DeusServer
{
SerializableSkillComponent::SerializableSkillComponent(Id componentId, GameObjectComponent::EComponentType componentType, const std::shared_ptr<const DeusCore::SkillInfos> originValue, uint32_t originMs, const std::shared_ptr<const DeusCore::SkillInfos> destinationValue, uint32_t destinationMs)
: SerializableTimelineComponent<DeusCore::SkillInfos>(componentId, componentType, originValue, originMs, destinationValue, destinationMs)
{
}
SerializableSkillComponent::~SerializableSkillComponent()
{
}
void SerializableSkillComponent::Deserialize(DeusCore::Buffer512 & buffer)
{
DeserializeData(buffer, m_componentId);
uint8_t componentType = m_componentType;
DeserializeData(buffer, componentType);
m_componentType = (GameObjectComponent::EComponentType)componentType;
bool isThereOrigin = false;
DeserializeData(buffer, isThereOrigin);
if (isThereOrigin)
{
DeserializeData<DeusCore::ISerializable>(buffer, *m_originValue);
DeserializeData(buffer, m_originMs);
}
bool isThereDestination = false;
DeserializeData(buffer, isThereDestination);
if (isThereDestination)
{
DeserializeData<DeusCore::ISerializable>(buffer, *m_destinationValue);
DeserializeData(buffer, m_destinationMs);
}
}
void SerializableSkillComponent::Serialize(DeusCore::Buffer512 & buffer) const
{
SerializeData(buffer, m_componentId);
uint8_t componentType = m_componentType;
SerializeData(buffer, componentType);
bool isThereOrigin = m_originValue != nullptr;
SerializeData(buffer, isThereOrigin);
if (isThereOrigin)
{
SerializeData<DeusCore::ISerializable>(buffer, *m_originValue);
SerializeData(buffer, m_originMs);
}
bool isThereDestination = m_destinationValue != nullptr;
SerializeData(buffer, isThereDestination);
if (isThereDestination)
{
SerializeData<DeusCore::ISerializable>(buffer, *m_destinationValue);
SerializeData(buffer, m_destinationMs);
}
}
uint16_t SerializableSkillComponent::EstimateAnswerCurrentSerializedSize() const
{
uint16_t originDataSize = m_originValue != nullptr ? m_originValue->EstimateAnswerCurrentSerializedSize() + sizeof(m_originMs) : 0;
uint16_t destinationDataSize = m_destinationValue != nullptr ? m_destinationValue->EstimateAnswerCurrentSerializedSize() + sizeof(m_destinationMs) : 0;
return uint16_t(sizeof(m_componentId) + sizeof(m_componentType)
+ sizeof(bool) // bool isThereOrigin
+ originDataSize
+ sizeof(bool) // bool isThereDestination
+ destinationDataSize);
}
}
| 35.702703
| 297
| 0.768357
|
Suliac
|
e670dec6e454099e0a9dc7eb0759a5773384b956
| 2,482
|
cpp
|
C++
|
Chapter_4_Graph/SSSP/kattis_hidingplaces.cpp
|
BrandonTang89/CP4_Code
|
5114471f439978dd11f6f2cbf6af20ca654593da
|
[
"MIT"
] | 2
|
2021-12-29T04:12:59.000Z
|
2022-03-30T09:32:19.000Z
|
Chapter_4_Graph/SSSP/kattis_hidingplaces.cpp
|
BrandonTang89/CP4_Code
|
5114471f439978dd11f6f2cbf6af20ca654593da
|
[
"MIT"
] | null | null | null |
Chapter_4_Graph/SSSP/kattis_hidingplaces.cpp
|
BrandonTang89/CP4_Code
|
5114471f439978dd11f6f2cbf6af20ca654593da
|
[
"MIT"
] | 1
|
2022-03-01T06:12:46.000Z
|
2022-03-01T06:12:46.000Z
|
/* Kattis - hidingplaces
This is probably the most basic of knightmove questions, if not for the fact that we have to do
conversion from the file and rank indexing to regular 0 indexing, do the BFS, then convert back, then
custom sort.
Also, apparently kattis allows for extra trailing spaces in the output, thats good to know!
Time: O(n), Mem: O(1)
*/
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
#define fast_cin() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
int s_r, s_c, num_tc;
int dr[] = {-2, -1, 1, 2, 2, 1, -1, -2};
int dc[] = {1, 2, 2, 1, -1, -2, -2, -1};
string line;
vector<vector<int>> dist;
queue<tuple<int,int>> q;
vector<string> hiding_places;
bool custom_sort(string a, string b){
if (a[1] > b[1])return true;
if (a[1] < b[1])return false;
return (a[0] < b[0]);
}
int main(){
cin >> num_tc;
for (int tc=0;tc<num_tc; tc++){
cin >> line;
s_c = line[0] - 'a';
s_r = line[1] - '1';
//printf("s_r: %d, s_c: %d\n", s_r, s_c);
dist.assign(8, vector<int>(8, -1));
hiding_places.clear();
dist[s_r][s_c] = 0;
q.emplace(s_r, s_c);
int max_dist = 0;
while (!q.empty()){
auto &[r, c] = q.front();
q.pop();
max_dist = max(max_dist, dist[r][c]);
for (int i=0;i<8;i++){
int nr = r + dr[i];
int nc = c + dc[i];
if (nc < 0 || nr < 0 || nc >= 8 || nr >= 8)continue;
if (dist[nr][nc] != -1)continue;
dist[nr][nc] = dist[r][c] + 1;
q.emplace(nr, nc);
}
}
for (int r=0;r<8;r++){
for (int c=0; c<8;c++){
if (dist[r][c] == max_dist){
char file = c + 'a';
char rank = r + '1';
string s;
s.push_back(file);
s.push_back(rank);
hiding_places.push_back(s);
}
}
}
sort(hiding_places.begin(), hiding_places.end(), custom_sort);
cout << max_dist << " ";
for (auto s: hiding_places){
cout << s << " ";
}cout << endl;
}
return 0;
}
| 26.978261
| 101
| 0.49033
|
BrandonTang89
|
e6778d97e671ada2f0976b5baa662e4701c87135
| 1,361
|
cpp
|
C++
|
10803.cpp
|
felikjunvianto/kfile-uvaoj-submissions
|
5bd8b3b413ca8523abe412b0a0545f766f70ce63
|
[
"MIT"
] | null | null | null |
10803.cpp
|
felikjunvianto/kfile-uvaoj-submissions
|
5bd8b3b413ca8523abe412b0a0545f766f70ce63
|
[
"MIT"
] | null | null | null |
10803.cpp
|
felikjunvianto/kfile-uvaoj-submissions
|
5bd8b3b413ca8523abe412b0a0545f766f70ce63
|
[
"MIT"
] | null | null | null |
#include <cstdio>
#include <cmath>
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <vector>
#include <utility>
#include <stack>
#include <queue>
#include <map>
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define pi 2*acos(0.0)
#define eps 1e-9
#define PII pair<int,int>
#define PDD pair<double,double>
#define LL long long
#define INF 1000000000
using namespace std;
int T,N,x,y,z;
PII koor[111];
double dis[111][111];
int main()
{
scanf("%d",&T);
for(int i=1;i<=T;i++)
{
scanf("%d",&N);
for(x=1;x<=N;x++) scanf("%d %d",&koor[x].fi,&koor[x].se);
for(x=1;x<=N;x++) dis[x][x]=0;
for(x=1;x<N;x++)
for(y=x+1;y<=N;y++) dis[x][y]=dis[y][x]=INF;
for(x=1;x<N;x++)
for(y=x+1;y<=N;y++)
{
int dx=koor[x].fi-koor[y].fi,dy=koor[x].se-koor[y].se;
z=dx*dx+dy*dy;
if(z<=100) dis[x][y]=dis[y][x]=sqrt((double)z);
}
for(z=1;z<=N;z++)
for(x=1;x<=N;x++)
for(y=1;y<=N;y++)
dis[x][y]=min(dis[x][y],dis[x][z]+dis[z][y]);
bool ada=true;
double ans=0;
for(x=1;x<N;x++)
for(y=x+1;y<=N;y++) if(dis[x][y]==INF) ada=false; else
ans=max(ans,dis[x][y]);
printf("Case #%d:\n",i);
if(ada) printf("%.4lf\n\n",ans); else printf("Send Kurdy\n\n");
}
return 0;
}
| 20.014706
| 66
| 0.540044
|
felikjunvianto
|
e679d70d54a0fcbb3c941c844d34f522ab6a4eaa
| 6,529
|
cc
|
C++
|
tests/catch/unit/memory/hipDrvPtrGetAttributes.cc
|
FMarno/HIP
|
f0e03e9d45d9ad2c15bf5ec4d44452f17216ade8
|
[
"MIT"
] | null | null | null |
tests/catch/unit/memory/hipDrvPtrGetAttributes.cc
|
FMarno/HIP
|
f0e03e9d45d9ad2c15bf5ec4d44452f17216ade8
|
[
"MIT"
] | null | null | null |
tests/catch/unit/memory/hipDrvPtrGetAttributes.cc
|
FMarno/HIP
|
f0e03e9d45d9ad2c15bf5ec4d44452f17216ade8
|
[
"MIT"
] | null | null | null |
/*
Copyright (c) 2022 Advanced Micro Devices, Inc. All rights reserved.
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.
*/
/*
* Tests for hipDrvPointerGetAttributes API
Functional Tests:
1. Pass multiple device related attributes in the attributes of hipDrvPointerGetAttributes API
for the device pointer and check the behaviour
2. Pass device and host attributes in the attributes of hipDrvPointerGetAttributes API and validate the behaviour
3. Pass invalid pointer to hipDrvPointerGetAttributes API and validate the behaviour.
Negative Tests:
1. Pass invalid numAttributes
2. Pass nullptr to attributes
3. Pass nullptr to data
4. Pass nullptr to device pointer
*/
#include <hip_test_common.hh>
static size_t Nbytes = 0;
constexpr size_t N {1000000};
/* This testcase verifies Negative Scenarios of
* hipDrvPointerGetAttributes API */
TEST_CASE("Unit_hipDrvPtrGetAttributes_Negative") {
HIP_CHECK(hipSetDevice(0));
Nbytes = N * sizeof(int);
int deviceId;
int numDevices = 0;
HIP_CHECK(hipGetDeviceCount(&numDevices));
int* A_d;
int* A_Pinned_h;
HIP_CHECK(hipMalloc(&A_d, Nbytes));
HIP_CHECK(hipHostMalloc(reinterpret_cast<void**>(&A_Pinned_h), Nbytes,
hipHostMallocDefault));
HIP_CHECK(hipGetDevice(&deviceId));
unsigned int device_ordinal;
int *dev_ptr;
void *data[2];
data[0] = &dev_ptr;
data[1] = &device_ordinal;
hipPointer_attribute attributes[] = {HIP_POINTER_ATTRIBUTE_DEVICE_POINTER,
HIP_POINTER_ATTRIBUTE_DEVICE_ORDINAL};
SECTION("Passing nullptr to attributes") {
REQUIRE(hipDrvPointerGetAttributes(2, nullptr, data,
reinterpret_cast<hipDeviceptr_t>(A_d)) == hipErrorInvalidValue);
}
SECTION("Passing nullptr to data") {
REQUIRE(hipDrvPointerGetAttributes(2, attributes, nullptr,
reinterpret_cast<hipDeviceptr_t>(A_d)) == hipErrorInvalidValue);
}
#if HT_AMD
SECTION("Passing nullptr to device Pointer") {
hipDeviceptr_t ptr = 0;
REQUIRE(hipDrvPointerGetAttributes(2, attributes, data,
ptr) == hipErrorInvalidValue);
}
#endif
#if HT_NVIDIA
SECTION("Passing invalid dependencies") {
hipPointer_attribute attributes1[] = {HIP_POINTER_ATTRIBUTE_DEVICE_POINTER};
REQUIRE(hipDrvPointerGetAttributes(2, attributes1, data,
reinterpret_cast<hipDeviceptr_t>(A_d)) == hipErrorInvalidValue);
}
#endif
}
// Testcase verifies functional scenarios of hipDrvPointerGetAttributes API
TEST_CASE("Unit_hipDrvPtrGetAttributes_Functional") {
HIP_CHECK(hipSetDevice(0));
Nbytes = N * sizeof(int);
int deviceId;
int numDevices = 0;
HIP_CHECK(hipGetDeviceCount(&numDevices));
int* A_d;
int* A_Pinned_h;
HIP_CHECK(hipMalloc(&A_d, Nbytes));
HIP_CHECK(hipHostMalloc(reinterpret_cast<void**>(&A_Pinned_h), Nbytes,
hipHostMallocDefault));
HIP_CHECK(hipGetDevice(&deviceId));
SECTION("Passing device attributes to device pointer") {
unsigned int memory_type;
int device_ordinal;
int *dev{nullptr};
int *dev_ptr{nullptr};
int *dev_ptr1{nullptr};
unsigned int range_size;
int *start_addr{nullptr};
void *data[5];
data[0] = (&memory_type);
data[1] = (&device_ordinal);
data[2] = (&dev_ptr);
data[3] = (&range_size);
data[4] = (&start_addr);
// Device memory
hipPointer_attribute attributes[] = {HIP_POINTER_ATTRIBUTE_MEMORY_TYPE,
HIP_POINTER_ATTRIBUTE_DEVICE_ORDINAL,
HIP_POINTER_ATTRIBUTE_DEVICE_POINTER,
HIP_POINTER_ATTRIBUTE_RANGE_SIZE,
HIP_POINTER_ATTRIBUTE_RANGE_START_ADDR};
HIP_CHECK(hipPointerGetAttribute(&dev_ptr1,
HIP_POINTER_ATTRIBUTE_DEVICE_POINTER,
reinterpret_cast<hipDeviceptr_t>(A_d + 100)));
HIP_CHECK(hipPointerGetAttribute(&dev,
HIP_POINTER_ATTRIBUTE_DEVICE_POINTER,
reinterpret_cast<hipDeviceptr_t>(A_d)));
HIP_CHECK(hipDrvPointerGetAttributes(5, attributes, data,
reinterpret_cast<hipDeviceptr_t>(A_d + 100)));
REQUIRE(dev_ptr == dev_ptr1);
#if HT_NVIDIA
REQUIRE(memory_type == CU_MEMORYTYPE_DEVICE);
#else
REQUIRE(memory_type == hipMemoryTypeDevice);
#endif
REQUIRE(device_ordinal == deviceId);
REQUIRE(range_size == Nbytes);
REQUIRE(start_addr == dev);
}
SECTION("Passing device and host attributes to device pointer") {
int device_ordinal;
int *host_ptr;
void *data[2];
data[0] = (&host_ptr);
data[1] = (&device_ordinal);
hipPointer_attribute attributes[] = {HIP_POINTER_ATTRIBUTE_HOST_POINTER,
HIP_POINTER_ATTRIBUTE_DEVICE_ORDINAL};
HIP_CHECK(hipDrvPointerGetAttributes(2, attributes, data,
reinterpret_cast<hipDeviceptr_t>(A_d)));
REQUIRE(host_ptr == nullptr);
REQUIRE(device_ordinal == deviceId);
}
SECTION("Passing host related attributes to host pointer") {
int device_ordinal;
void *data[2];
int *host_ptr;
data[0] = (&host_ptr);
data[1] = (&device_ordinal);
hipPointer_attribute attributes[] = {HIP_POINTER_ATTRIBUTE_HOST_POINTER,
HIP_POINTER_ATTRIBUTE_DEVICE_ORDINAL};
HIP_CHECK(hipDrvPointerGetAttributes(2, attributes, data,
reinterpret_cast<hipDeviceptr_t>(A_Pinned_h)));
REQUIRE(host_ptr == A_Pinned_h);
REQUIRE(device_ordinal == deviceId);
}
}
| 36.887006
| 116
| 0.704855
|
FMarno
|
e67abb269c958091646df8d5140bd5812ed897cc
| 1,766
|
cpp
|
C++
|
core/src/jni/jni/AlgorandAssetAmount.cpp
|
hlafet-ledger/lib-ledger-core
|
44d21837e51cb6dfdecb4af4a674cae0aee9f06d
|
[
"MIT"
] | 92
|
2016-11-13T01:28:34.000Z
|
2022-03-25T01:11:37.000Z
|
core/src/jni/jni/AlgorandAssetAmount.cpp
|
hlafet-ledger/lib-ledger-core
|
44d21837e51cb6dfdecb4af4a674cae0aee9f06d
|
[
"MIT"
] | 242
|
2016-11-28T11:13:09.000Z
|
2022-03-04T13:02:53.000Z
|
core/src/jni/jni/AlgorandAssetAmount.cpp
|
hlafet-ledger/lib-ledger-core
|
44d21837e51cb6dfdecb4af4a674cae0aee9f06d
|
[
"MIT"
] | 91
|
2017-06-20T10:35:28.000Z
|
2022-03-09T14:15:40.000Z
|
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from idl.djinni
#include "AlgorandAssetAmount.hpp" // my header
#include "Marshal.hpp"
namespace djinni_generated {
AlgorandAssetAmount::AlgorandAssetAmount() = default;
AlgorandAssetAmount::~AlgorandAssetAmount() = default;
auto AlgorandAssetAmount::fromCpp(JNIEnv* jniEnv, const CppType& c) -> ::djinni::LocalRef<JniType> {
const auto& data = ::djinni::JniClass<AlgorandAssetAmount>::get();
auto r = ::djinni::LocalRef<JniType>{jniEnv->NewObject(data.clazz.get(), data.jconstructor,
::djinni::get(::djinni::String::fromCpp(jniEnv, c.creatorAddress)),
::djinni::get(::djinni::String::fromCpp(jniEnv, c.amount)),
::djinni::get(::djinni::Bool::fromCpp(jniEnv, c.frozen)),
::djinni::get(::djinni::String::fromCpp(jniEnv, c.assetId)))};
::djinni::jniExceptionCheck(jniEnv);
return r;
}
auto AlgorandAssetAmount::toCpp(JNIEnv* jniEnv, JniType j) -> CppType {
::djinni::JniLocalScope jscope(jniEnv, 5);
assert(j != nullptr);
const auto& data = ::djinni::JniClass<AlgorandAssetAmount>::get();
return {::djinni::String::toCpp(jniEnv, (jstring)jniEnv->GetObjectField(j, data.field_creatorAddress)),
::djinni::String::toCpp(jniEnv, (jstring)jniEnv->GetObjectField(j, data.field_amount)),
::djinni::Bool::toCpp(jniEnv, jniEnv->GetBooleanField(j, data.field_frozen)),
::djinni::String::toCpp(jniEnv, (jstring)jniEnv->GetObjectField(j, data.field_assetId))};
}
} // namespace djinni_generated
| 50.457143
| 126
| 0.614949
|
hlafet-ledger
|
e67f8eae922ecebafa302959f5728e3139707edd
| 8,547
|
hpp
|
C++
|
include/utility/container/detail/tripair_helper.hpp
|
SakuraLife/utility
|
b9bf26198917b6dc415520f74eb3eebf8aa8195e
|
[
"Unlicense"
] | 2
|
2017-12-10T10:59:48.000Z
|
2017-12-13T04:11:14.000Z
|
include/utility/container/detail/tripair_helper.hpp
|
SakuraLife/utility
|
b9bf26198917b6dc415520f74eb3eebf8aa8195e
|
[
"Unlicense"
] | null | null | null |
include/utility/container/detail/tripair_helper.hpp
|
SakuraLife/utility
|
b9bf26198917b6dc415520f74eb3eebf8aa8195e
|
[
"Unlicense"
] | null | null | null |
#ifndef __UTILITY_CONTAINER_DETAIL_TRIPAIR_HELPER__
#define __UTILITY_CONTAINER_DETAIL_TRIPAIR_HELPER__
#include<utility/trait/type/transform/decay.hpp>
#include<utility/trait/type/transform/add_cv.hpp>
#include<utility/trait/type/releations/is_convertible.hpp>
#include<utility/trait/type/features/is_constructible.hpp>
#include<utility/trait/type/features/is_implicit_constructible.hpp>
#include<utility/trait/type/features/is_assignable.hpp>
#include<utility/trait/type/features/is_copy_assignable.hpp>
#include<utility/trait/type/features/is_swappable.hpp>
#include<utility/trait/type/features/is_possible_swappable.hpp>
#include<utility/trait/type/features/is_nothrow_constructible.hpp>
#include<utility/trait/type/features/is_nothrow_swappable.hpp>
#include<utility/trait/type/features/is_nothrow_possible_swappable.hpp>
#include<utility/trait/type/miscellaneous/enable_if.hpp>
namespace utility
{
namespace container
{
namespace __detail
{
using trait::type::releations::is_convertible;
using trait::type::features::is_constructible;
using trait::type::features::is_implicit_constructible;
using trait::type::features::is_copy_constructible;
using trait::type::features::is_nothrow_constructible;
using trait::type::features::is_nothrow_copy_constructible;
using trait::type::features::is_assignable;
using trait::type::features::is_nothrow_assignable;
using trait::type::features::is_swappable;
using trait::type::features::is_possible_swappable;
using trait::type::features::is_nothrow_swappable;
using trait::type::features::is_nothrow_possible_swappable;
using trait::type::miscellaneous::enable_if;
template<typename _T>
using __add_cv = typename trait::type::transform::add_cv<_T>::type;
template<typename _T1, typename _T2, typename _T3>
using __tripair_default = enable_if<
is_constructible<_T1>::value &&
is_constructible<_T2>::value &&
is_constructible<_T3>::value &&
(is_implicit_constructible<_T1>::value &&
is_implicit_constructible<_T2>::value &&
is_implicit_constructible<_T3>::value),
bool>;
template<typename _T1, typename _T2, typename _T3>
using __tripair_explicit_default = enable_if<
is_constructible<_T1>::value &&
is_constructible<_T2>::value &&
is_constructible<_T3>::value &&
!(is_implicit_constructible<_T1>::value &&
is_implicit_constructible<_T2>::value &&
is_implicit_constructible<_T3>::value),
bool>;
template<typename _T1, typename _T2, typename _T3>
using __tripair_default_noexcept =
trait::__type_and__<
is_nothrow_constructible<_T1>,
is_nothrow_constructible<_T2>,
is_nothrow_constructible<_T3>
>;
template<
typename _T1, typename _T2, typename _T3,
typename _U1 = _T1, typename _U2 = _T2, typename _U3 = _T3
>
using __tripair_copy = enable_if<
is_constructible<_T1, __add_cv<_U1>>::value &&
is_constructible<_T2, __add_cv<_U2>>::value &&
is_constructible<_T3, __add_cv<_U3>>::value &&
(is_convertible<__add_cv<_U1>, _T1>::value &&
is_convertible<__add_cv<_U2>, _T2>::value &&
is_convertible<__add_cv<_U3>, _T3>::value),
bool>;
template<
typename _T1, typename _T2, typename _T3,
typename _U1 = _T1, typename _U2 = _T2, typename _U3 = _T3
>
using __tripair_explicit_copy = enable_if<
is_constructible<_T1, __add_cv<_U1>>::value &&
is_constructible<_T2, __add_cv<_U2>>::value &&
is_constructible<_T3, __add_cv<_U3>>::value &&
!(is_convertible<__add_cv<_U1>, _T1>::value &&
is_convertible<__add_cv<_U2>, _T2>::value &&
is_convertible<__add_cv<_U3>, _T3>::value),
bool>;
template<
typename _T1, typename _T2, typename _T3,
typename _U1 = _T1, typename _U2 = _T2, typename _U3 = _T3
>
using __tripair_copy_noexcept =
trait::__type_and__<
is_nothrow_constructible<_T1, __add_cv<_U1>>,
is_nothrow_constructible<_T2, __add_cv<_U2>>,
is_nothrow_constructible<_T3, __add_cv<_U3>>
>;
template<
typename _T1, typename _T2, typename _T3,
typename _U1 = _T1, typename _U2 = _T2, typename _U3 = _T3
>
using __tripair_move = enable_if<
is_constructible<_T1, _U1&&>::value &&
is_constructible<_T2, _U2&&>::value &&
is_constructible<_T3, _U3&&>::value &&
(is_convertible<_U1&&, _T1>::value &&
is_convertible<_U2&&, _T2>::value &&
is_convertible<_U3&&, _T3>::value),
bool>;
template<
typename _T1, typename _T2, typename _T3,
typename _U1 = _T1, typename _U2 = _T2, typename _U3 = _T3
>
using __tripair_explicit_move = enable_if<
is_constructible<_T1, _U1&&>::value &&
is_constructible<_T2, _U2&&>::value &&
is_constructible<_T3, _U3&&>::value &&
!(is_convertible<_U1&&, _T1>::value &&
is_convertible<_U2&&, _T2>::value &&
is_convertible<_U3&&, _T3>::value),
bool>;
template<
typename _T1, typename _T2, typename _T3,
typename _U1 = _T1, typename _U2 = _T2, typename _U3 = _T3
>
using __tripair_move_noexcept =
trait::__type_and__<
is_nothrow_constructible<_T1, _U1&&>,
is_nothrow_constructible<_T2, _U2&&>,
is_nothrow_constructible<_T3, _U3&&>
>;
template<
typename _T1, typename _T2, typename _T3,
typename _U1 = _T1, typename _U2 = _T2, typename _U3 = _T3
>
using __tripair_copy_assign = enable_if<
is_assignable<_T1&, const _U1&>::value &&
is_assignable<_T2&, const _U2&>::value &&
is_assignable<_T3&, const _U3&>::value,
bool>;
template<
typename _T1, typename _T2, typename _T3,
typename _U1 = _T1, typename _U2 = _T2, typename _U3 = _T3
>
using __tripair_copy_assign_noexcept =
trait::__type_and__<
is_nothrow_assignable<_T1&, const _U1&>,
is_nothrow_assignable<_T2&, const _U1&>,
is_nothrow_assignable<_T3&, const _U1&>
>;
template<
typename _T1, typename _T2, typename _T3,
typename _U1 = _T1, typename _U2 = _T2, typename _U3 = _T3
>
using __tripair_move_assign = enable_if<
is_assignable<_T1&, _U1&&>::value &&
is_assignable<_T2&, _U2&&>::value &&
is_assignable<_T3&, _U3&&>::value,
bool>;
template<
typename _T1, typename _T2, typename _T3,
typename _U1 = _T1, typename _U2 = _T2, typename _U3 = _T3
>
using __tripair_move_assign_noexcept =
trait::__type_and__<
is_nothrow_assignable<_T1&, _U1&&>,
is_nothrow_assignable<_T2&, _U2&&>,
is_nothrow_assignable<_T3&, _U3&&>
>;
template<typename _T1, typename _T2, typename _T3>
using __tripair_swap = enable_if<
is_swappable<_T1>::value &&
is_swappable<_T2>::value &&
is_swappable<_T3>::value,
bool>;
template<typename _T1, typename _T2, typename _T3>
using __tripair_swap_noexcept =
trait::__type_and__<
is_nothrow_swappable<_T1>,
is_nothrow_swappable<_T2>,
is_nothrow_swappable<_T3>
>;
template<typename _T1, typename _T2, typename _T3>
using __tripair_possible_swap = enable_if<
is_possible_swappable<_T1>::value &&
is_possible_swappable<_T2>::value &&
is_possible_swappable<_T3>::value,
bool>;
template<typename _T1, typename _T2, typename _T3>
using __tripair_possible_swap_noexcept =
trait::__type_and__<
is_nothrow_possible_swappable<_T1>,
is_nothrow_possible_swappable<_T2>,
is_nothrow_possible_swappable<_T3>
>;
template<typename _T>
struct __make_tripair_type_helper
{ typedef _T type;};
template<typename _T>
struct __make_tripair_type
{
typedef typename
__make_tripair_type_helper<typename
trait::type::transform::decay<_T>::type
>::type type;
};
}
}
}
#endif // ! __UTILITY_CONTAINER_DETAIL_TRIPAIR_HELPER__
| 36.063291
| 73
| 0.64315
|
SakuraLife
|
e681e16bf5bf7ed559c5abf4f6d4eafc2f6cda2f
| 469
|
cpp
|
C++
|
competitive_programming/learning_c++/primer/3_vectors/begin_end_functions_arrays.cpp
|
CristoferNava/Algorithms-and-DataStructures
|
ab561bcaf9ac31feaaf32463f08c3162188c3b3f
|
[
"MIT"
] | null | null | null |
competitive_programming/learning_c++/primer/3_vectors/begin_end_functions_arrays.cpp
|
CristoferNava/Algorithms-and-DataStructures
|
ab561bcaf9ac31feaaf32463f08c3162188c3b3f
|
[
"MIT"
] | null | null | null |
competitive_programming/learning_c++/primer/3_vectors/begin_end_functions_arrays.cpp
|
CristoferNava/Algorithms-and-DataStructures
|
ab561bcaf9ac31feaaf32463f08c3162188c3b3f
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main() {
int nums[] = {1, 2, 3, 4, 5};
int *b = begin(nums); // pointer to the first element in nums
int *e = end(nums); // pointer one past the last element in nums
// As with iterators, subtracting two pointers give us the distance between
// those pointers.
auto n = end(nums) - begin(nums);
cout << n << endl;
int last = *(nums + 4); // last has value of 5
cout << last << endl;
}
| 27.588235
| 79
| 0.601279
|
CristoferNava
|
e68268a099699aa3cfe4473b22331e8865e358a2
| 8,661
|
cpp
|
C++
|
tc 160+/PokerDeck.cpp
|
ibudiselic/contest-problem-solutions
|
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
|
[
"BSD-2-Clause"
] | 3
|
2015-05-25T06:24:37.000Z
|
2016-09-10T07:58:00.000Z
|
tc 160+/PokerDeck.cpp
|
ibudiselic/contest-problem-solutions
|
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
|
[
"BSD-2-Clause"
] | null | null | null |
tc 160+/PokerDeck.cpp
|
ibudiselic/contest-problem-solutions
|
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
|
[
"BSD-2-Clause"
] | 5
|
2015-05-25T06:24:40.000Z
|
2021-08-19T19:22:29.000Z
|
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
#include <cctype>
#include <map>
#include <utility>
using namespace std;
#define DBG(X) cerr << (#X) << ' ' << (X)
#define DBG_NL(X) cerr << (#X) << ' ' << (X) << '\n'
#define DBG_A(A, I) cerr << (#A) << '[' << (I) << "] " << (A[(I)])
#define DBG_A_NL(A, I) cerr << (#A) << '[' << (I) << "] " << (A[(I)]) << '\n'
int face[13];
int suit[4];
int have[4][13];
int nCards;
string suits = "CHSD";
string faceCards = "JQKA";
void update(const string &t) {
int s = suits.find(t[t.size()-1]);
int f = (t.size()==3 ? 8 : isdigit(t[0]) ? t[0]-'0'-2 : 9+(int)faceCards.find(t[0]));
++suit[s];
++face[f];
++have[s][f];
++nCards;
}
struct Hand {
long long cnt;
string name;
Hand(long long cnt_, const string &name_): cnt(cnt_), name(name_) {}
};
bool operator<(const Hand &a, const Hand &b) {
if (a.cnt != b.cnt)
return a.cnt < b.cnt;
return a.name < b.name;
}
map< pair<int, int>, long long > C;
long long choose(int n, int k) {
if (n < k)
return 0;
long long &ret = C[make_pair(n, k)];
if (ret != 0)
return ret;
ret = 1;
for (int i=0; i<k; ++i)
ret *= (n-i);
for (int i=k; i>1; --i)
ret /= i;
return ret;
}
class PokerDeck {
public:
vector <string> getRanking(vector <string> decks) {
memset(face, 0, sizeof face);
memset(suit, 0, sizeof suit);
memset(have, 0, sizeof have);
nCards = 0;
for (int i=0; i<(int)decks.size(); ++i) {
istringstream is(decks[i]);
string w;
while (is >> w)
update(w);
}
/*for (int i=0; i<13; ++i)
DBG_A_NL(face, i);
for (int i=0; i<4; ++i)
DBG_A_NL(suit, i);*/
long long ok5 = 0;
for (int f=0; f<13; ++f)
ok5 += choose(face[f], 5);
DBG_NL(ok5);
long long royalFlush = 0;
for (int s=0; s<4; ++s) {
long long add = 1;
for (int f=8; f<13; ++f)
add *= have[s][f];
royalFlush += add;
}
DBG_NL(royalFlush);
long long straightFlush = 0;
for (int s=0; s<4; ++s) {
long long add = (have[s][0]*have[s][1]*have[s][2]*have[s][3]*have[s][12]);
for (int start=0; start<8; ++start) {
long long ways = 1;
for (int i=0; i<5; ++i)
ways *= have[s][start+i];
add += ways;
}
straightFlush += add;
}
DBG_NL(straightFlush);
long long straight = -straightFlush-royalFlush;
straight += (face[12]*face[0]*face[1]*face[2]*face[3]);
for (int i=0; i<9; ++i) {
long long add = 1;
for (int j=0; j<5; ++j)
add *= face[i+j];
straight += add;
}
DBG_NL(straight);
long long flush = -straightFlush-royalFlush;
for (int s=0; s<4; ++s)
for (int f=0; f<13; ++f)
flush -= choose(have[s][f], 5);
for (int s=0; s<4; ++s)
flush += choose(suit[s], 5);
DBG_NL(flush);
long long fullHouse = 0;
for (int s=0; s<4; ++s)
for (int i=0; i<13; ++i)
for (int j=i+1; j<13; ++j)
fullHouse -= choose(have[s][i], 2)*choose(have[s][j], 3) + choose(have[s][i], 3)*choose(have[s][j], 2);
for (int i=0; i<13; ++i)
for (int j=i+1; j<13; ++j)
fullHouse += choose(face[i], 2)*choose(face[j], 3) + choose(face[i], 3)*choose(face[j], 2);
DBG_NL(fullHouse);
long long ok4 = 0;
for (int s=0; s<4; ++s)
for (int f=0; f<13; ++f)
ok4 -= choose(have[s][f], 4)*(suit[s]-have[s][f]);
for (int f=0; f<13; ++f)
ok4 += choose(face[f], 4)*(nCards-face[f]);
DBG_NL(ok4);
long long ok3 = 0;
for (int s=0; s<4; ++s)
for (int f=0; f<13; ++f) {
long long t = 0;
for (int i=0; i<13; ++i)
if (i != f)
for (int j=i+1; j<13; ++j)
if (j != f)
t += have[s][i]*have[s][j];
ok3 -= choose(have[s][f], 3)*t;
}
for (int f=0; f<13; ++f) {
long long t = 0;
for (int i=0; i<13; ++i)
if (i != f)
for (int j=i+1; j<13; ++j)
if (j != f)
t += face[i]*face[j];
ok3 += choose(face[f], 3)*t;
}
DBG_NL(ok3);
long long pair2 = 0;
for (int s=0; s<4; ++s)
for (int i=0; i<13; ++i)
for (int j=i+1; j<13; ++j)
pair2 -= choose(have[s][i], 2)*choose(have[s][j], 2)*(suit[s]-have[s][i]-have[s][j]);
for (int i=0; i<13; ++i)
for (int j=i+1; j<13; ++j)
for (int k=0; k<13; ++k)
if (k!=i && k!=j)
pair2 += choose(face[i], 2)*choose(face[j], 2)*face[k];
DBG_NL(pair2);
long long pair = 0;
for (int s=0; s<4; ++s)
for (int f=0; f<13; ++f) {
long long t = 0;
for (int i=0; i<13; ++i)
if (i != f)
for (int j=i+1; j<13; ++j)
if (j != f)
for (int k=j+1; k<13; ++k)
if (k != f)
t += have[s][i]*have[s][j]*have[s][k];
pair -= choose(have[s][f], 2)*t;
}
for (int f=0; f<13; ++f) {
long long t = 0;
for (int i=0; i<13; ++i)
if (i != f)
for (int j=i+1; j<13; ++j)
if (j != f)
for (int k=j+1; k<13; ++k)
if (k != f)
t += face[i]*face[j]*face[k];
pair += choose(face[f], 2)*t;
}
DBG_NL(pair);
vector<Hand> v;
v.push_back(Hand(ok5, "FIVE OF A KIND"));
v.push_back(Hand(ok4, "FOUR OF A KIND"));
v.push_back(Hand(ok3, "THREE OF A KIND"));
v.push_back(Hand(pair, "ONE PAIR"));
v.push_back(Hand(pair2, "TWO PAIR"));
v.push_back(Hand(fullHouse, "FULL HOUSE"));
v.push_back(Hand(straight, "STRAIGHT"));
v.push_back(Hand(flush, "FLUSH"));
v.push_back(Hand(royalFlush, "ROYAL FLUSH"));
v.push_back(Hand(straightFlush, "STRAIGHT FLUSH"));
v.push_back(Hand(choose(nCards, 5)-ok5-ok4-ok3-pair-pair2-fullHouse-straight-flush-royalFlush-straightFlush, "NOTHING"));
sort(v.begin(), v.end());
vector<string> sol;
for (int i=0; i<(int)v.size(); ++i)
if (v[i].cnt > 0)
sol.push_back(v[i].name);
for (int i=0; i<(int)v.size(); ++i)
cerr << v[i].name << ' ' << double(v[i].cnt)/choose(nCards, 5)*100 << '\n';
return sol;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const vector <string> &Expected, const vector <string> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } }
void test_case_0() { string Arr0[] = {"AC 2C 3C 4C 5C 6C 7C 8C 9C 10C JC QC KC",
"AD 2D 3D 4D 5D 6D 7D 8D 9D 10D JD QD KD",
"AH 2H 3H 4H 5H 6H 7H 8H 9H 10H JH QH KH",
"AS 2S 3S 4S 5S 6S 7S 8S 9S 10S JS QS KS"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"ROYAL FLUSH", "STRAIGHT FLUSH", "FOUR OF A KIND", "FULL HOUSE", "FLUSH", "STRAIGHT", "THREE OF A KIND", "TWO PAIR", "ONE PAIR", "NOTHING" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(0, Arg1, getRanking(Arg0)); }
void test_case_1() { string Arr0[] = {"AS 2C 3C 4C 5C 7D 7H 8C 8D 8H 10S JS QS KS"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"FLUSH", "FULL HOUSE", "ROYAL FLUSH", "STRAIGHT", "TWO PAIR", "THREE OF A KIND", "ONE PAIR", "NOTHING" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(1, Arg1, getRanking(Arg0)); }
void test_case_2() { string Arr0[] = {"AS AS AS AS AS AS AS AS AS AS AS",
"AS AS AS AS AS AS AS AS AS AS AS",
"AS AS AS AS AS AS AS AS AS AS AS",
"2C 4C 6C 8C"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"NOTHING", "ONE PAIR", "THREE OF A KIND", "FOUR OF A KIND", "FIVE OF A KIND" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(2, Arg1, getRanking(Arg0)); }
void test_case_3() { string Arr0[] = {"QC QH QD 6S 6H"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arr1[] = {"FULL HOUSE" }; vector <string> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); verify_case(3, Arg1, getRanking(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
PokerDeck ___test;
___test.run_test(-1);
}
// END CUT HERE
| 32.683019
| 389
| 0.535042
|
ibudiselic
|
e6889d43ca3f66d591c89c81dbcabfc9cd1932b8
| 1,835
|
cpp
|
C++
|
src/UI/dialog.cpp
|
YeWenting/Travel-Simulation-System
|
8c146d2e576ae2ec0e641eb531f19de59bc36e44
|
[
"MIT"
] | 5
|
2016-04-09T12:37:46.000Z
|
2021-06-11T00:31:57.000Z
|
src/UI/dialog.cpp
|
YeWenting/Travel-Simulation-System
|
8c146d2e576ae2ec0e641eb531f19de59bc36e44
|
[
"MIT"
] | 1
|
2016-04-09T13:09:02.000Z
|
2016-04-10T08:02:02.000Z
|
src/UI/dialog.cpp
|
YeWenting/Travel-Simulation-System
|
8c146d2e576ae2ec0e641eb531f19de59bc36e44
|
[
"MIT"
] | 2
|
2016-04-16T07:41:23.000Z
|
2020-05-11T02:25:59.000Z
|
#include "dialog.h"
#include "ui_dialog.h"
#include<sstream>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
setAttribute(Qt::WA_DeleteOnClose);
init_connection();
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::accept()
{
People p;
TravelPlan tp;
bool ok = true;
bool temp;
if (trafficNet.cityNum.find(ui->fromeEdit->text().toStdString()) == trafficNet.cityNum.end())
ok = false;
else
tp.source = trafficNet.cityNum[ui->fromeEdit->text().toStdString()];
if (trafficNet.cityNum.find(ui->toEdit->text().toStdString()) == trafficNet.cityNum.end())
ok = false;
else
tp.destination = trafficNet.cityNum[ui->toEdit->text().toStdString()];
tp.type = ui->strategyEdit->text().toInt(&temp,10);
ok = ok && temp;
if (!(tp.type <= 3 && tp.type >= 1))
ok = false;
if (tp.type == 3) {
tp.timeLimit = ui->tlEdit->text().toInt(&temp,10);
ok = ok && temp ;//&& (tp.timeLimit >= 10) ;
}
std::string temp1 = ui->textEdit->toPlainText().toStdString();
std::string temp2;
std::stringstream read(temp1);
while (read>>temp2) {
if (trafficNet.cityNum.find(temp2) != trafficNet.cityNum.end())
tp.station.push_back(trafficNet.cityNum[temp2]);
else
ok = false;
}
p.name = ui->NameEdit->text().toStdString();
if (p.name.size() == 0)
ok = false;
if (ok) {
p.location = tp.source;
p.plan = tp;
emit sendPeople(p);
} else {
emit sendError();
}
QDialog::accept();
}
void Dialog::init_connection()
{
connect(ui->confirm,SIGNAL(clicked(bool)),this,SLOT(accept()));
}
| 22.654321
| 98
| 0.549864
|
YeWenting
|
e698c88c999f622f63a87478b82b1c9728968999
| 475
|
cpp
|
C++
|
code/pkg_Core/Modules/LogWriter/Plugin.cpp
|
xiaobazhang/plugin
|
d84ae4c678e8bb44e5c936446984499e1aaa1fac
|
[
"Apache-1.1"
] | null | null | null |
code/pkg_Core/Modules/LogWriter/Plugin.cpp
|
xiaobazhang/plugin
|
d84ae4c678e8bb44e5c936446984499e1aaa1fac
|
[
"Apache-1.1"
] | null | null | null |
code/pkg_Core/Modules/LogWriter/Plugin.cpp
|
xiaobazhang/plugin
|
d84ae4c678e8bb44e5c936446984499e1aaa1fac
|
[
"Apache-1.1"
] | null | null | null |
// x3c - C++ PluginFramework
#include <UtilFunc/PluginInc.h>
#include "LogObserver.h"
static CLogObserver* s_pObserver = NULL;
OUTAPI bool x3InitializePlugin()
{
if (!s_pObserver)
{
s_pObserver = new CLogObserver;
}
return true;
}
OUTAPI void x3UninitializePlugin()
{
x3::SafeDelete(s_pObserver);
}
OUTAPI Ix_LogObserver* GetLogObserver()
{
if (!s_pObserver)
{
s_pObserver = new CLogObserver;
}
return s_pObserver;
}
| 15.322581
| 40
| 0.665263
|
xiaobazhang
|
e6a3db95057ce60d4c6eea2d0b13007f5e9be0bf
| 532
|
cpp
|
C++
|
src/15000/15993.cpp14.cpp
|
upple/BOJ
|
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
|
[
"MIT"
] | 8
|
2018-04-12T15:54:09.000Z
|
2020-06-05T07:41:15.000Z
|
src/15000/15993.cpp14.cpp
|
upple/BOJ
|
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
|
[
"MIT"
] | null | null | null |
src/15000/15993.cpp14.cpp
|
upple/BOJ
|
e6dbf9fd17fa2b458c6a781d803123b14c18e6f1
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
#define MOD 1000000009
using namespace std;
int dp[2][100001];
bool v[2][100001];
int solve(int c, int n)
{
if(n<=0) return 0;
if(v[c][n]) return dp[c][n];
v[c][n]=1;
return dp[c][n]=(((solve(!c, n-1)+solve(!c, n-2))%MOD)+solve(!c, n-3))%MOD;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int t;
cin>>t;
dp[1][1]=dp[1][2]=dp[0][2]=1;
dp[1][3]=dp[0][3]=2;
for(int i=1; i<=3; i++)
v[0][i]=v[1][i]=1;
while(t--)
{
int n;
cin>>n;
cout<<solve(1, n)<<" "<<solve(0, n)<<"\n";
}
}
| 17.16129
| 76
| 0.528195
|
upple
|
e6a4d7441199393783a2c18446c7ae71361c853d
| 16,416
|
cc
|
C++
|
wrspice/devlib/vbic/vbicnois.cc
|
wrcad/xictools
|
f46ba6d42801426739cc8b2940a809b74f1641e2
|
[
"Apache-2.0"
] | 73
|
2017-10-26T12:40:24.000Z
|
2022-03-02T16:59:43.000Z
|
wrspice/devlib/vbic/vbicnois.cc
|
chris-ayala/xictools
|
4ea72c118679caed700dab3d49a8d36445acaec3
|
[
"Apache-2.0"
] | 12
|
2017-11-01T10:18:22.000Z
|
2022-03-20T19:35:36.000Z
|
wrspice/devlib/vbic/vbicnois.cc
|
chris-ayala/xictools
|
4ea72c118679caed700dab3d49a8d36445acaec3
|
[
"Apache-2.0"
] | 34
|
2017-10-06T17:04:21.000Z
|
2022-02-18T16:22:03.000Z
|
/*========================================================================*
* *
* Distributed by Whiteley Research Inc., Sunnyvale, California, USA *
* http://wrcad.com *
* Copyright (C) 2017 Whiteley Research Inc., all rights reserved. *
* Author: Stephen R. Whiteley, except as indicated. *
* *
* As fully as possible recognizing licensing terms and conditions *
* imposed by earlier work from which this work was derived, if any, *
* this work is released under the Apache License, Version 2.0 (the *
* "License"). You may not use this file except in compliance with *
* the License, and compliance with inherited licenses which are *
* specified in a sub-header below this one if applicable. A copy *
* of the License is provided with this distribution, or you may *
* obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* See the License for the specific language governing permissions *
* and limitations under the License. *
* *
* 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 NON- *
* INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED *
* OR STEPHEN R. WHITELEY 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. *
* *
*========================================================================*
* XicTools Integrated Circuit Design System *
* *
* WRspice Circuit Simulation and Analysis Tool: Device Library *
* *
*========================================================================*
$Id:$
*========================================================================*/
/**********
Copyright 1990 Regents of the University of California. All rights reserved.
Author: 1987 Gary W. Ng
Model Author: 1995 Colin McAndrew Motorola
Spice3 Implementation: 2003 Dietmar Warning DAnalyse GmbH
**********/
#include <stdio.h>
#include "vbicdefs.h"
#include "noisdefs.h"
#define VBICnextModel next()
#define VBICnextInstance next()
#define VBICinstances inst()
#define VBICname GENname
#define MAX SPMAX
#define CKTtemp CKTcurTask->TSKtemp
#define NOISEAN sNOISEAN
#define Nintegrate(a, b, c, d) (d)->integrate(a, b, c)
#define NstartFreq JOBac.fstart()
int
VBICdev::noise (int mode, int operation, sGENmodel *genmod, sCKT *ckt,
sNdata *data, double *OnDens)
{
sVBICmodel *firstModel = static_cast<sVBICmodel*>(genmod);
sVBICmodel *model;
sVBICinstance *inst;
char vbicname[N_MXVLNTH];
double tempOnoise;
double tempInoise;
double noizDens[VBICNSRCS];
double lnNdens[VBICNSRCS];
int i;
/* define the names of the noise sources */
static const char *VBICnNames[VBICNSRCS] = {
/* Note that we have to keep the order consistent with the
strchr definitions in VBICdefs.h */
"_rc", /* noise due to rc */
"_rci", /* noise due to rci */
"_rb", /* noise due to rb */
"_rbi", /* noise due to rbi */
"_re", /* noise due to re */
"_rbp", /* noise due to rbp */
"_ic", /* noise due to ic */
"_ib", /* noise due to ib */
"_ibep", /* noise due to ibep */
"_1overfbe", /* flicker (1/f) noise ibe */
"_1overfbep", /* flicker (1/f) noise ibep */
"_rs", /* noise due to rs */
"_iccp", /* noise due to iccp */
"" /* total transistor noise */
};
for (model=firstModel; model != NULL; model=model->VBICnextModel) {
for (inst=model->VBICinstances; inst != NULL;
inst=inst->VBICnextInstance) {
// if (inst->VBICowner != ARCHme) continue;
switch (operation) {
case N_OPEN:
/* see if we have to to produce a summary report */
/* if so, name all the noise generators */
if (((NOISEAN*)ckt->CKTcurJob)->NStpsSm != 0) {
switch (mode) {
case N_DENS:
for (i=0; i < VBICNSRCS; i++) {
(void)sprintf(vbicname,"onoise_%s%s",
(char*)inst->VBICname,VBICnNames[i]);
/* SRW
data->namelist = (IFuid *)
trealloc((char *)data->namelist,
(data->numPlots + 1)*sizeof(IFuid));
if (!data->namelist) return(E_NOMEM);
(*(SPfrontEnd->IFnewUid))(ckt,
&(data->namelist[data->numPlots++]),
(IFuid)NULL,vbicname,UID_OTHER,(void **)NULL);
*/
Realloc(&data->namelist, data->numPlots+1,
data->numPlots);
ckt->newUid(&data->namelist[data->numPlots++],
0, vbicname, UID_OTHER);
/* we've added one more plot */
}
break;
case INT_NOIZ:
for (i=0; i < VBICNSRCS; i++) {
(void)sprintf(vbicname,"onoise_total_%s%s",
(char*)inst->VBICname,VBICnNames[i]);
/* SRW
data->namelist = (IFuid *)
trealloc((char *)data->namelist,
(data->numPlots + 1)*sizeof(IFuid));
if (!data->namelist) return(E_NOMEM);
(*(SPfrontEnd->IFnewUid))(ckt,
&(data->namelist[data->numPlots++]),
(IFuid)NULL,vbicname,UID_OTHER,(void **)NULL);
*/
Realloc(&data->namelist, data->numPlots+2,
data->numPlots);
ckt->newUid(&data->namelist[data->numPlots++],
0, vbicname, UID_OTHER);
/* we've added one more plot */
(void)sprintf(vbicname,"inoise_total_%s%s",
(char*)inst->VBICname,VBICnNames[i]);
/* SRW
data->namelist = (IFuid *)trealloc((char *)data->namelist,(data->numPlots + 1)*sizeof(IFuid));
if (!data->namelist) return(E_NOMEM);
(*(SPfrontEnd->IFnewUid))(ckt,
&(data->namelist[data->numPlots++]),
(IFuid)NULL,vbicname,UID_OTHER,(void **)NULL);
*/
ckt->newUid(&data->namelist[data->numPlots++],
0, vbicname, UID_OTHER);
/* we've added one more plot */
}
break;
}
}
break;
case N_CALC:
switch (mode) {
case N_DENS:
NevalSrc(&noizDens[VBICRCNOIZ],&lnNdens[VBICRCNOIZ],
ckt,THERMNOISE,inst->VBICcollCXNode,inst->VBICcollNode,
model->VBICcollectorConduct * inst->VBICarea * inst->VBICm);
NevalSrc(&noizDens[VBICRCINOIZ],&lnNdens[VBICRCINOIZ],
ckt,THERMNOISE,inst->VBICcollCXNode,inst->VBICcollCINode,
*(ckt->CKTstate0 + inst->VBICirci_Vrci));
NevalSrc(&noizDens[VBICRBNOIZ],&lnNdens[VBICRBNOIZ],
ckt,THERMNOISE,inst->VBICbaseBXNode,inst->VBICbaseNode,
model->VBICbaseConduct * inst->VBICarea * inst->VBICm);
NevalSrc(&noizDens[VBICRBINOIZ],&lnNdens[VBICRBINOIZ],
ckt,THERMNOISE,inst->VBICbaseBXNode,inst->VBICbaseBINode,
*(ckt->CKTstate0 + inst->VBICirbi_Vrbi));
NevalSrc(&noizDens[VBICRENOIZ],&lnNdens[VBICRENOIZ],
ckt,THERMNOISE,inst->VBICemitEINode,inst->VBICemitNode,
model->VBICemitterConduct * inst->VBICarea * inst->VBICm);
NevalSrc(&noizDens[VBICRBPNOIZ],&lnNdens[VBICRBPNOIZ],
ckt,THERMNOISE,inst->VBICemitEINode,inst->VBICemitNode,
*(ckt->CKTstate0 + inst->VBICirbp_Vrbp));
NevalSrc(&noizDens[VBICRSNOIZ],&lnNdens[VBICRSNOIZ],
ckt,THERMNOISE,inst->VBICsubsSINode,inst->VBICsubsNode,
model->VBICsubstrateConduct * inst->VBICarea * inst->VBICm);
NevalSrc(&noizDens[VBICICNOIZ],&lnNdens[VBICICNOIZ],
ckt,SHOTNOISE,inst->VBICcollCINode, inst->VBICemitEINode,
*(ckt->CKTstate0 + inst->VBICitzf));
NevalSrc(&noizDens[VBICIBNOIZ],&lnNdens[VBICIBNOIZ],
ckt,SHOTNOISE,inst->VBICbaseBINode, inst->VBICemitEINode,
*(ckt->CKTstate0 + inst->VBICibe));
NevalSrc(&noizDens[VBICIBEPNOIZ],&lnNdens[VBICIBEPNOIZ],
ckt,SHOTNOISE,inst->VBICbaseBXNode, inst->VBICbaseBPNode,
*(ckt->CKTstate0 + inst->VBICibep));
NevalSrc(&noizDens[VBICICCPNOIZ],&lnNdens[VBICICCPNOIZ],
ckt,SHOTNOISE,inst->VBICbaseBXNode, inst->VBICsubsSINode,
*(ckt->CKTstate0 + inst->VBICiccp));
NevalSrc(&noizDens[VBICFLBENOIZ],(double*)NULL,ckt,
N_GAIN,inst->VBICbaseBINode, inst->VBICemitEINode,
(double)0.0);
noizDens[VBICFLBENOIZ] *= inst->VBICm * model->VBICfNcoef *
exp(model->VBICfNexpA *
log(MAX(fabs(*(ckt->CKTstate0 + inst->VBICibe)/inst->VBICm),N_MINLOG))) /
pow(data->freq, model->VBICfNexpB);
lnNdens[VBICFLBENOIZ] =
log(MAX(noizDens[VBICFLBENOIZ],N_MINLOG));
NevalSrc(&noizDens[VBICFLBEPNOIZ],(double*)NULL,ckt,
N_GAIN,inst->VBICbaseBXNode, inst->VBICbaseBPNode,
(double)0.0);
noizDens[VBICFLBEPNOIZ] *= inst->VBICm * model->VBICfNcoef *
exp(model->VBICfNexpA *
log(MAX(fabs(*(ckt->CKTstate0 + inst->VBICibep)/inst->VBICm),N_MINLOG))) /
pow(data->freq, model->VBICfNexpB);
lnNdens[VBICFLBEPNOIZ] =
log(MAX(noizDens[VBICFLBEPNOIZ],N_MINLOG));
noizDens[VBICTOTNOIZ] = noizDens[VBICRCNOIZ] +
noizDens[VBICRCINOIZ] +
noizDens[VBICRBNOIZ] +
noizDens[VBICRBINOIZ] +
noizDens[VBICRENOIZ] +
noizDens[VBICRBPNOIZ] +
noizDens[VBICICNOIZ] +
noizDens[VBICIBNOIZ] +
noizDens[VBICIBEPNOIZ] +
noizDens[VBICFLBENOIZ] +
noizDens[VBICFLBEPNOIZ];
lnNdens[VBICTOTNOIZ] =
log(noizDens[VBICTOTNOIZ]);
*OnDens += noizDens[VBICTOTNOIZ];
if (data->delFreq == 0.0) {
/* if we haven't done any previous integration, we need to */
/* initialize our "history" variables */
for (i=0; i < VBICNSRCS; i++) {
inst->VBICnVar[LNLSTDENS][i] = lnNdens[i];
}
/* clear out our integration variables if it's the first pass */
if (data->freq == ((NOISEAN*)ckt->CKTcurJob)->NstartFreq) {
for (i=0; i < VBICNSRCS; i++) {
inst->VBICnVar[OUTNOIZ][i] = 0.0;
inst->VBICnVar[INNOIZ][i] = 0.0;
}
}
} else { /* data->delFreq != 0.0 (we have to integrate) */
/* In order to get the best curve fit, we have to integrate each component separately */
for (i=0; i < VBICNSRCS; i++) {
if (i != VBICTOTNOIZ) {
tempOnoise = Nintegrate(noizDens[i], lnNdens[i],
inst->VBICnVar[LNLSTDENS][i], data);
tempInoise = Nintegrate(noizDens[i] * data->GainSqInv ,
lnNdens[i] + data->lnGainInv,
inst->VBICnVar[LNLSTDENS][i] + data->lnGainInv,
data);
inst->VBICnVar[LNLSTDENS][i] = lnNdens[i];
data->outNoiz += tempOnoise;
data->inNoise += tempInoise;
if (((NOISEAN*)ckt->CKTcurJob)->NStpsSm != 0) {
inst->VBICnVar[OUTNOIZ][i] += tempOnoise;
inst->VBICnVar[OUTNOIZ][VBICTOTNOIZ] += tempOnoise;
inst->VBICnVar[INNOIZ][i] += tempInoise;
inst->VBICnVar[INNOIZ][VBICTOTNOIZ] += tempInoise;
}
}
}
}
if (data->prtSummary) {
for (i=0; i < VBICNSRCS; i++) { /* print a summary report */
data->outpVector[data->outNumber++] = noizDens[i];
}
}
break;
case INT_NOIZ: /* already calculated, just output */
if (((NOISEAN*)ckt->CKTcurJob)->NStpsSm != 0) {
for (i=0; i < VBICNSRCS; i++) {
data->outpVector[data->outNumber++] = inst->VBICnVar[OUTNOIZ][i];
data->outpVector[data->outNumber++] = inst->VBICnVar[INNOIZ][i];
}
} /* if */
break;
} /* switch (mode) */
break;
case N_CLOSE:
return (OK); /* do nothing, the main calling routine will close */
break; /* the plots */
} /* switch (operation) */
} /* for inst */
} /* for model */
return(OK);
}
| 48.712166
| 107
| 0.428119
|
wrcad
|
e6b0f9b285cee58270e611e03c61e8cba7430b00
| 838
|
cpp
|
C++
|
libs/core/src/to_std_wstring_locale.cpp
|
freundlich/fcppt
|
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
|
[
"BSL-1.0"
] | 13
|
2015-02-21T18:35:14.000Z
|
2019-12-29T14:08:29.000Z
|
libs/core/src/to_std_wstring_locale.cpp
|
cpreh/fcppt
|
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
|
[
"BSL-1.0"
] | 5
|
2016-08-27T07:35:47.000Z
|
2019-04-21T10:55:34.000Z
|
libs/core/src/to_std_wstring_locale.cpp
|
freundlich/fcppt
|
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
|
[
"BSL-1.0"
] | 8
|
2015-01-10T09:22:37.000Z
|
2019-12-01T08:31:12.000Z
|
// Copyright Carl Philipp Reh 2009 - 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <fcppt/public_config.hpp>
#include <fcppt/string_view.hpp>
#include <fcppt/to_std_wstring_locale.hpp>
#if defined(FCPPT_NARROW_STRING)
#include <fcppt/widen_locale.hpp>
#endif
#include <fcppt/config/external_begin.hpp>
#include <locale>
#include <string>
#include <fcppt/config/external_end.hpp>
std::wstring fcppt::to_std_wstring_locale(
fcppt::string_view const _input,
#if defined(FCPPT_NARROW_STRING)
std::locale const &_locale
#else
std::locale const &
#endif
)
{
#if defined(FCPPT_NARROW_STRING)
return fcppt::widen_locale(_input, _locale);
#else
return std::wstring{_input};
#endif
}
| 26.1875
| 61
| 0.743437
|
freundlich
|
e6b2d28353e5261b9b859241d03a3bb940724a03
| 1,648
|
hh
|
C++
|
src/context/StateMovingUnit.hh
|
zermingore/warevolved
|
efd0c506658ce6e4ecb6c7eb5bb7d620bc05fd52
|
[
"MIT"
] | 1
|
2019-09-23T18:16:27.000Z
|
2019-09-23T18:16:27.000Z
|
src/context/StateMovingUnit.hh
|
zermingore/warevolved
|
efd0c506658ce6e4ecb6c7eb5bb7d620bc05fd52
|
[
"MIT"
] | 2
|
2018-11-12T18:48:03.000Z
|
2018-11-15T21:10:02.000Z
|
src/context/StateMovingUnit.hh
|
zermingore/warevolved
|
efd0c506658ce6e4ecb6c7eb5bb7d620bc05fd52
|
[
"MIT"
] | null | null | null |
/**
* \file
* \date November 25, 2016
* \author Zermingore
* \brief StateMovingUnit class declaration
*/
#ifndef STATE_MOVING_UNIT_HH_
# define STATE_MOVING_UNIT_HH_
# include <memory>
# include <context/State.hh>
# include <common/using.hh> // Coords
class PathFinding;
namespace graphics {
class Sprite;
}
/**
* \class StateMovingUnit
* \brief State active while moving a unit on the map
*/
class StateMovingUnit: public State
{
public:
/**
* \brief registers to callbacks. Initializes the graphical attributes
*/
StateMovingUnit();
/**
* \brief Resets the unit's sprite
* \note It is necessary if the move was canceled
*/
~StateMovingUnit() override;
/**
* \brief exits the current State
*/
void exit();
/**
* \brief Draw the holo unit (shadow of the unit) at _holoUnitPosition
*/
virtual void draw() override final;
/**
* \brief Resumes the menu. Updates its copy of the map dimensions
*/
void resume() override final;
private:
/// Move the unit up
void moveUnitUp();
/// Move the unit down
void moveUnitDown();
/// Move the unit left
void moveUnitLeft();
/// Move the unit right
void moveUnitRight();
const Coords _originalCoords; ///< original unit coordinates
Coords _holoUnitPosition; ///< Unit position 'cursor' (in cell)
std::unique_ptr<graphics::Sprite> _holoUnit; ///< 'cursor' moving unit
size_t _nbColumns; ///< map number of columns
size_t _nbLines; ///< map number of lines
/// Used to display directions of the selected unit
std::unique_ptr<PathFinding> _pathFinding;
};
#endif /* !STATE_MOVING_UNIT_HH_ */
| 18.942529
| 72
| 0.679005
|
zermingore
|
e6b4327a4cd97178a2ff00bf7aa3cee6b639ecdb
| 758
|
hpp
|
C++
|
src/common/interfaces/views/imaineditorview.hpp
|
squeevee/Addle
|
20ec4335669fbd88d36742f586899d8416920959
|
[
"MIT"
] | 3
|
2020-03-05T06:36:51.000Z
|
2020-06-20T03:25:02.000Z
|
src/common/interfaces/views/imaineditorview.hpp
|
squeevee/Addle
|
20ec4335669fbd88d36742f586899d8416920959
|
[
"MIT"
] | 13
|
2020-03-11T17:43:42.000Z
|
2020-12-11T03:36:05.000Z
|
src/common/interfaces/views/imaineditorview.hpp
|
squeevee/Addle
|
20ec4335669fbd88d36742f586899d8416920959
|
[
"MIT"
] | 1
|
2020-09-28T06:53:46.000Z
|
2020-09-28T06:53:46.000Z
|
/**
* Addle source code
* @file
* @copyright Copyright 2020 Eleanor Hawk
* @copyright Modification and distribution permitted under the terms of the
* MIT License. See "LICENSE" for full details.
*/
#ifndef IMAINEDITORVIEW_HPP
#define IMAINEDITORVIEW_HPP
#include "itoplevelview.hpp"
#include "interfaces/traits.hpp"
namespace Addle {
class IMainEditorPresenter;
class IMainEditorView : public ITopLevelView
{
public:
virtual ~IMainEditorView() = default;
virtual void initialize(IMainEditorPresenter& presenter) = 0;
virtual IMainEditorPresenter& presenter() const = 0;
};
DECL_MAKEABLE(IMainEditorView)
} // namespace Addle
Q_DECLARE_INTERFACE(Addle::IMainEditorView, "org.addle.IMainEditorView")
#endif // IMAINEDITORVIEW_HPP
| 21.055556
| 76
| 0.76781
|
squeevee
|
e6ba2a3fb9f784b7124c4612b3d4a873d3f9e1e3
| 1,762
|
cpp
|
C++
|
aws-cpp-sdk-migrationhubstrategy/source/model/SourceCodeRepository.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-02-10T08:06:54.000Z
|
2022-02-10T08:06:54.000Z
|
aws-cpp-sdk-migrationhubstrategy/source/model/SourceCodeRepository.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2021-10-14T16:57:00.000Z
|
2021-10-18T10:47:24.000Z
|
aws-cpp-sdk-migrationhubstrategy/source/model/SourceCodeRepository.cpp
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-11-09T11:58:03.000Z
|
2021-11-09T11:58:03.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/migrationhubstrategy/model/SourceCodeRepository.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace MigrationHubStrategyRecommendations
{
namespace Model
{
SourceCodeRepository::SourceCodeRepository() :
m_branchHasBeenSet(false),
m_repositoryHasBeenSet(false),
m_versionControlTypeHasBeenSet(false)
{
}
SourceCodeRepository::SourceCodeRepository(JsonView jsonValue) :
m_branchHasBeenSet(false),
m_repositoryHasBeenSet(false),
m_versionControlTypeHasBeenSet(false)
{
*this = jsonValue;
}
SourceCodeRepository& SourceCodeRepository::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("branch"))
{
m_branch = jsonValue.GetString("branch");
m_branchHasBeenSet = true;
}
if(jsonValue.ValueExists("repository"))
{
m_repository = jsonValue.GetString("repository");
m_repositoryHasBeenSet = true;
}
if(jsonValue.ValueExists("versionControlType"))
{
m_versionControlType = jsonValue.GetString("versionControlType");
m_versionControlTypeHasBeenSet = true;
}
return *this;
}
JsonValue SourceCodeRepository::Jsonize() const
{
JsonValue payload;
if(m_branchHasBeenSet)
{
payload.WithString("branch", m_branch);
}
if(m_repositoryHasBeenSet)
{
payload.WithString("repository", m_repository);
}
if(m_versionControlTypeHasBeenSet)
{
payload.WithString("versionControlType", m_versionControlType);
}
return payload;
}
} // namespace Model
} // namespace MigrationHubStrategyRecommendations
} // namespace Aws
| 19.577778
| 74
| 0.745743
|
perfectrecall
|
e6bac368660258c06e8b44bb7f52dc6001ee7af2
| 3,495
|
cpp
|
C++
|
HashTable.cpp
|
dsackinger/dht
|
896acace326d45de1f5be472f3cc1a05fd66ee0d
|
[
"MIT"
] | null | null | null |
HashTable.cpp
|
dsackinger/dht
|
896acace326d45de1f5be472f3cc1a05fd66ee0d
|
[
"MIT"
] | null | null | null |
HashTable.cpp
|
dsackinger/dht
|
896acace326d45de1f5be472f3cc1a05fd66ee0d
|
[
"MIT"
] | null | null | null |
//////////////////////////////////////////////////////////////////////////
// HashTable.cpp
//
// Copyright (C) 2018 Dan Sackinger - All Rights Reserved
// You may use, distribute and modify this code under the
// terms of the MIT license.
//
// Implementation of the HashTable class
#include "HashTable.h"
#include <algorithm>
HashTable::HashTable(int id, node_vector_t& nodes)
: id_(id)
, nodes_(nodes)
, table_()
, table_lock_()
{
// The vector needs to be sorted to enable the mod to work correctly.
std::sort(nodes_.begin(), nodes_.end());
}
HashTable::~HashTable()
{
}
std::uint64_t HashTable::node_from_key(const std::string& key)
{
// Lets hope this doesn't ever happen
if (nodes_.empty())
return 0;
auto hash = hash_string(key);
std::size_t slot = hash % nodes_.size();
return nodes_.at(slot);
}
std::uint64_t HashTable::next_node_id(std::uint64_t id)
{
for (std::size_t i = 0; i < nodes_.size(); i++)
{
if (nodes_[i] == id)
{
i = (i + 1) % nodes_.size();
return nodes_[i];
}
}
// What? We didn't find our own id? Maybe abort due to invalid configuration
return 0;
}
bool HashTable::has_node(uint64_t id)
{
std::unique_lock<std::mutex> lock(table_lock_);
for (std::size_t i = 0; i < nodes_.size(); i++)
if (nodes_[i] == id)
return true;
return false;
}
std::size_t HashTable::node_count()
{
std::unique_lock<std::mutex> lock(table_lock_);
return nodes_.size();
}
node_vector_t HashTable::nodes()
{
std::unique_lock<std::mutex> lock(table_lock_);
return node_vector_t(nodes_);
}
std::size_t HashTable::get_key_count()
{
std::unique_lock<std::mutex> lock(table_lock_);
return table_.size();
}
std::string HashTable::get_first_key()
{
std::unique_lock<std::mutex> lock(table_lock_);
if (table_.empty())
return std::string();
else
return table_.begin()->first;
}
void HashTable::set(const std::string& key, const std::string& value)
{
std::unique_lock<std::mutex> lock(table_lock_);
table_[key] = value;
}
bool HashTable::has(const std::string& key)
{
// First, check to see if we should have this key
std::unique_lock<std::mutex> lock(table_lock_);
auto entry = table_.find(key);
return !(entry == table_.end());
}
bool HashTable::get(const std::string& key, std::string& value_out)
{
std::unique_lock<std::mutex> lock(table_lock_);
auto entry = table_.find(key);
if (entry == table_.end())
return false;
value_out = entry->second;
return true;
}
void HashTable::erase(const std::string& key)
{
std::unique_lock<std::mutex> lock(table_lock_);
auto entry = table_.find(key);
if (entry != table_.end())
table_.erase(entry);
}
std::vector<std::string> HashTable::keys()
{
std::unique_lock<std::mutex> lock(table_lock_);
std::vector<std::string> keys;
for (auto& entry : table_)
keys.push_back(entry.first);
return keys;
}
// We need a consistent hash for our values that will work across platforms.
// Simple implementation borrowed and adapted from:
// https://stackoverflow.com/questions/8317508/hash-function-for-a-string
static constexpr std::uint64_t first_sc(37);
static constexpr std::uint64_t a_sc(54059);
static constexpr std::uint64_t b_sc(76963);
std::uint64_t HashTable::hash_string(const std::string& value)
{
const char *s = value.c_str();
std::uint64_t h = first_sc;
while (*s)
{
h = (h * a_sc) ^ (static_cast<std::uint64_t>(*s) * b_sc);
s++;
}
return h; // or return h % C;
}
| 22.403846
| 80
| 0.656938
|
dsackinger
|
e6bbfa58d18b07a370e618d1c78e0b853d670b96
| 14,889
|
cpp
|
C++
|
Frameworks/SnoizeMIDISpy/Driver/MessagePortBroadcaster.cpp
|
anthroid/MIDIApps
|
0ff430c0188deb1cfc530e1a8566506d59d5750c
|
[
"BSD-3-Clause"
] | 449
|
2015-01-04T21:06:04.000Z
|
2022-03-23T09:28:51.000Z
|
Frameworks/SnoizeMIDISpy/Driver/MessagePortBroadcaster.cpp
|
anthroid/MIDIApps
|
0ff430c0188deb1cfc530e1a8566506d59d5750c
|
[
"BSD-3-Clause"
] | 74
|
2015-01-04T08:30:22.000Z
|
2022-03-31T01:16:39.000Z
|
Frameworks/SnoizeMIDISpy/Driver/MessagePortBroadcaster.cpp
|
anthroid/MIDIApps
|
0ff430c0188deb1cfc530e1a8566506d59d5750c
|
[
"BSD-3-Clause"
] | 90
|
2015-01-04T21:06:12.000Z
|
2022-01-29T18:16:21.000Z
|
/*
Copyright (c) 2001-2004, Kurt Revis. 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 Kurt Revis, nor Snoize, nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "MessagePortBroadcaster.h"
#include "MIDISpyShared.h"
#include <pthread.h>
// Private function declarations
CFDataRef LocalMessagePortCallBack(CFMessagePortRef local, SInt32 msgid, CFDataRef data, void *info) __attribute__((cf_returns_retained));
void MessagePortWasInvalidated(CFMessagePortRef messagePort, void *info);
void RemoveRemotePortFromChannelArray(const void *key, const void *value, void *context);
// NOTE This static variable is a dumb workaround. See comment in MessagePortWasInvalidated().
static MessagePortBroadcaster *sOneBroadcaster = NULL;
MessagePortBroadcaster::MessagePortBroadcaster(CFStringRef broadcasterName, MessagePortBroadcasterDelegate *delegate) :
mDelegate(delegate),
mBroadcasterName(NULL),
mLocalPort(NULL),
mRunLoopSource(NULL),
mNextListenerIdentifier(0),
mListenersByIdentifier(NULL),
mIdentifiersByListener(NULL),
mListenerArraysByChannel(NULL)
{
CFMessagePortContext messagePortContext = { 0, (void *)this, NULL, NULL, NULL };
#if DEBUG
fprintf(stderr, "MessagePortBroadcaster: creating\n");
#endif
sOneBroadcaster = this;
if (!broadcasterName)
broadcasterName = CFSTR("Unknown Broadcaster");
mBroadcasterName = CFStringCreateCopy(kCFAllocatorDefault, broadcasterName);
if (!mBroadcasterName)
goto abort;
// Create a local port for remote listeners to talk to us with
#if DEBUG
fprintf(stderr, "MessagePortBroadcaster: creating local port\n");
#endif
mLocalPort = CFMessagePortCreateLocal(kCFAllocatorDefault, mBroadcasterName, LocalMessagePortCallBack, &messagePortContext, FALSE);
if (!mLocalPort) {
#if DEBUG
fprintf(stderr, "MessagePortBroadcaster: couldn't create local port!\n");
#endif
goto abort;
}
// And add it to the current run loop
mRunLoopSource = CFMessagePortCreateRunLoopSource(kCFAllocatorDefault, mLocalPort, 0);
if (!mRunLoopSource) {
#if DEBUG
fprintf(stderr, "MessagePortBroadcaster: couldn't create run loop source for local port!\n");
#endif
goto abort;
}
CFRunLoopAddSource(CFRunLoopGetCurrent(), mRunLoopSource, kCFRunLoopDefaultMode);
// Create structures to keep track of our listeners
mListenersByIdentifier = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
mIdentifiersByListener = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
mListenerArraysByChannel = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
if (!mListenersByIdentifier || !mIdentifiersByListener || !mListenerArraysByChannel) {
#if DEBUG
fprintf(stderr, "MessagePortBroadcaster: couldn't create a listener dictionary!\n");
#endif
goto abort;
}
pthread_mutex_init(&mListenerStructuresMutex, NULL);
return;
abort:
if (mListenerArraysByChannel)
CFRelease(mListenerArraysByChannel);
if (mIdentifiersByListener)
CFRelease(mIdentifiersByListener);
if (mListenersByIdentifier)
CFRelease(mListenersByIdentifier);
if (mRunLoopSource) {
CFRunLoopSourceInvalidate(mRunLoopSource);
CFRelease(mRunLoopSource);
}
if (mLocalPort) {
CFMessagePortInvalidate(mLocalPort);
CFRelease(mLocalPort);
}
if (mBroadcasterName)
CFRelease(mBroadcasterName);
throw MessagePortBroadcasterException();
}
MessagePortBroadcaster::~MessagePortBroadcaster()
{
#if DEBUG
fprintf(stderr, "MessagePortBroadcaster: destroying\n");
#endif
// As we delete our dictionaries, any leftover remote CFMessagePorts will get invalidated.
// But we want to bypass the usual invalidation code (since we're just taking everything
// down anyway), so we set sOneBroadcaster to NULL. MessagePortWasInvalidated() will
// still get called, but it won't be able to call back into this C++ object.
// NOTE When restructuring to get rid of sOneBroadcaster, you'll need to rethink this.
sOneBroadcaster = NULL;
pthread_mutex_destroy(&mListenerStructuresMutex);
if (mListenerArraysByChannel)
CFRelease(mListenerArraysByChannel);
if (mIdentifiersByListener)
CFRelease(mIdentifiersByListener);
if (mListenersByIdentifier)
CFRelease(mListenersByIdentifier);
if (mRunLoopSource) {
CFRunLoopSourceInvalidate(mRunLoopSource);
CFRelease(mRunLoopSource);
}
if (mLocalPort) {
CFMessagePortInvalidate(mLocalPort);
CFRelease(mLocalPort);
}
if (mBroadcasterName)
CFRelease(mBroadcasterName);
}
void MessagePortBroadcaster::Broadcast(CFDataRef data, SInt32 channel)
{
CFArrayRef listeners;
CFIndex listenerIndex;
#if DEBUG && 0
fprintf(stderr, "MessagePortBroadcaster: broadcast(%p, %d)\n", data, channel);
#endif
CFNumberRef channelNumber = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &channel);
if (channelNumber) {
pthread_mutex_lock(&mListenerStructuresMutex);
listeners = (CFArrayRef)CFDictionaryGetValue(mListenerArraysByChannel, channelNumber);
if (listeners) {
listenerIndex = CFArrayGetCount(listeners);
while (listenerIndex--) {
CFMessagePortRef listenerPort = (CFMessagePortRef)CFArrayGetValueAtIndex(listeners, listenerIndex);
CFMessagePortSendRequest(listenerPort, 0, data, 300, 0, NULL, NULL);
}
}
pthread_mutex_unlock(&mListenerStructuresMutex);
CFRelease(channelNumber);
}
}
//
// Private functions and methods
//
CFDataRef LocalMessagePortCallBack(CFMessagePortRef local, SInt32 msgid, CFDataRef data, void *info)
{
MessagePortBroadcaster *broadcaster = (MessagePortBroadcaster *)info;
CFDataRef result = NULL;
#if DEBUG && 0
fprintf(stderr, "MessagePortBroadcaster: message port callback(msgid=%ld)\n", msgid);
#endif
switch (msgid) {
case kSpyingMIDIDriverGetNextListenerIdentifierMessageID:
result = broadcaster->NextListenerIdentifier();
break;
case kSpyingMIDIDriverAddListenerMessageID:
broadcaster->AddListener(data);
break;
case kSpyingMIDIDriverConnectDestinationMessageID:
broadcaster->ChangeListenerChannelStatus(data, true);
break;
case kSpyingMIDIDriverDisconnectDestinationMessageID:
broadcaster->ChangeListenerChannelStatus(data, false);
break;
default:
break;
}
return result;
}
CFDataRef MessagePortBroadcaster::NextListenerIdentifier()
{
// Client is starting up; it wants to know what identifier to use (so it can name its local port).
// We give it that data in a reply.
CFDataRef returnedData;
mNextListenerIdentifier++;
returnedData = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&mNextListenerIdentifier, sizeof(SInt32));
return returnedData;
}
void MessagePortBroadcaster::AddListener(CFDataRef listenerIdentifierData)
{
// The listener has created a local port on its side, and we need to create a remote port for it.
// No reply is necessary.
const UInt8 *dataBytes;
SInt32 listenerIdentifier;
CFNumberRef listenerIdentifierNumber;
CFStringRef listenerPortName;
CFMessagePortRef remotePort;
if (!listenerIdentifierData || CFDataGetLength(listenerIdentifierData) != sizeof(SInt32))
return;
dataBytes = CFDataGetBytePtr(listenerIdentifierData);
if (!dataBytes)
return;
listenerIdentifier = *(const SInt32 *)dataBytes;
listenerIdentifierNumber = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &listenerIdentifier);
if (!listenerIdentifierNumber)
return;
listenerPortName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%@-%d"), mBroadcasterName, listenerIdentifier);
remotePort = CFMessagePortCreateRemote(kCFAllocatorDefault, listenerPortName);
if (remotePort) {
CFMessagePortSetInvalidationCallBack(remotePort, MessagePortWasInvalidated);
pthread_mutex_lock(&mListenerStructuresMutex);
CFDictionarySetValue(mListenersByIdentifier, listenerIdentifierNumber, remotePort);
CFDictionarySetValue(mIdentifiersByListener, remotePort, listenerIdentifierNumber);
pthread_mutex_unlock(&mListenerStructuresMutex);
CFRelease(remotePort);
// TODO we don't really want to do this here -- we want to do it when the client adds a channel
if (mDelegate && CFDictionaryGetCount(mListenersByIdentifier) == 1)
mDelegate->BroadcasterListenerCountChanged(this, true);
}
CFRelease(listenerPortName);
CFRelease(listenerIdentifierNumber);
}
void MessagePortBroadcaster::ChangeListenerChannelStatus(CFDataRef messageData, Boolean shouldAdd)
{
// From the message data given, take out the identifier of the listener, and the channel it is concerned with.
// Then find the remote message port corresponding to that identifier.
// Then find the array of listeners for this channel (creating it if necessary), and add/remove the remote port from the array.
// No reply is necessary.
const UInt8 *dataBytes;
SInt32 identifier;
SInt32 channel;
CFMessagePortRef remotePort;
CFMutableArrayRef channelListeners;
CFNumberRef listenerIdentifierNumber;
if (!messageData || CFDataGetLength(messageData) != sizeof(SInt32) + sizeof(SInt32))
return;
dataBytes = CFDataGetBytePtr(messageData);
if (!dataBytes)
return;
identifier = *(SInt32 *)dataBytes;
channel = *(SInt32 *)(dataBytes + sizeof(SInt32));
listenerIdentifierNumber = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &identifier);
if (!listenerIdentifierNumber)
return;
remotePort = (CFMessagePortRef)CFDictionaryGetValue(mListenersByIdentifier, listenerIdentifierNumber);
CFRelease(listenerIdentifierNumber);
if (!remotePort)
return;
CFNumberRef channelNumber = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &channel);
if (!channelNumber)
return;
pthread_mutex_lock(&mListenerStructuresMutex);
channelListeners = (CFMutableArrayRef)CFDictionaryGetValue(mListenerArraysByChannel, channelNumber);
if (!channelListeners && shouldAdd) {
channelListeners = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
if (channelListeners) {
CFDictionarySetValue(mListenerArraysByChannel, channelNumber, channelListeners);
CFRelease(channelListeners);
}
}
if (shouldAdd) {
CFArrayAppendValue(channelListeners, remotePort);
} else if (channelListeners) {
CFIndex index;
index = CFArrayGetFirstIndexOfValue(channelListeners, CFRangeMake(0, CFArrayGetCount(channelListeners)), remotePort);
if (index != kCFNotFound)
CFArrayRemoveValueAtIndex(channelListeners, index);
}
pthread_mutex_unlock(&mListenerStructuresMutex);
CFRelease(channelNumber);
}
void MessagePortWasInvalidated(CFMessagePortRef messagePort, void *info)
{
// NOTE: The info pointer provided to this function is useless. CFMessagePort provides no way to set it for remote ports.
// Thus, we have to assume we have one MessagePortBroadcaster, which we look up statically. Lame!
// TODO come up with a better solution to this
#if DEBUG && 0
fprintf(stderr, "MessagePortBroadcaster: remote port was invalidated\n");
#endif
if (sOneBroadcaster)
sOneBroadcaster->RemoveListenerWithRemotePort(messagePort);
}
void MessagePortBroadcaster::RemoveListenerWithRemotePort(CFMessagePortRef remotePort)
{
pthread_mutex_lock(&mListenerStructuresMutex);
// Remove this listener from our dictionaries
CFNumberRef listenerNumber = (CFNumberRef)CFDictionaryGetValue(mIdentifiersByListener, remotePort);
CFDictionaryRemoveValue(mListenersByIdentifier, listenerNumber);
CFDictionaryRemoveValue(mIdentifiersByListener, remotePort);
// Also go through the listener array for each channel and remove remotePort from there too
CFDictionaryApplyFunction(mListenerArraysByChannel, RemoveRemotePortFromChannelArray, remotePort);
pthread_mutex_unlock(&mListenerStructuresMutex);
// TODO we don't really want to do this here -- we want to do it when a client removes a channel
if (mDelegate && CFDictionaryGetCount(mListenersByIdentifier) == 0)
mDelegate->BroadcasterListenerCountChanged(this, false);
}
void RemoveRemotePortFromChannelArray(const void *key, const void *value, void *context)
{
// We don't care about the key (it's a channel number)
CFMutableArrayRef listenerArray = (CFMutableArrayRef)value;
CFMessagePortRef remotePort = (CFMessagePortRef)context;
CFIndex index;
index = CFArrayGetFirstIndexOfValue(listenerArray, CFRangeMake(0, CFArrayGetCount(listenerArray)), remotePort);
if (index != kCFNotFound)
CFArrayRemoveValueAtIndex(listenerArray, index);
}
| 38.572539
| 755
| 0.735845
|
anthroid
|
e6bc41e102a376e94d419d0802de927946cb7ca3
| 9,892
|
cpp
|
C++
|
droneBrainROSModule/src/source/thisswarmagentinterface.cpp
|
MorS25/cvg_quadrotor_swarm
|
da75d02049163cf65fd7305bc46a16359a851c7c
|
[
"BSD-3-Clause"
] | null | null | null |
droneBrainROSModule/src/source/thisswarmagentinterface.cpp
|
MorS25/cvg_quadrotor_swarm
|
da75d02049163cf65fd7305bc46a16359a851c7c
|
[
"BSD-3-Clause"
] | null | null | null |
droneBrainROSModule/src/source/thisswarmagentinterface.cpp
|
MorS25/cvg_quadrotor_swarm
|
da75d02049163cf65fd7305bc46a16359a851c7c
|
[
"BSD-3-Clause"
] | null | null | null |
#include "thisswarmagentinterface.h"
ThisSwarmAgentInterface::ThisSwarmAgentInterface() :
state_estimator( std::string(MODULE_NAME_ODOMETRY_STATE_ESTIMATOR), ModuleNames::ODOMETRY_STATE_ESTIMATOR),
trajectory_controller( std::string(MODULE_NAME_TRAJECTORY_CONTROLLER), ModuleNames::TRAJECTORY_CONTROLLER),
arucoeye( std::string(MODULE_NAME_ARUCO_EYE), ModuleNames::ARUCO_EYE),
localizer( std::string(MODULE_NAME_LOCALIZER), ModuleNames::LOCALIZER),
obstacle_processor( std::string(MODULE_NAME_OBSTACLE_PROCESSOR), ModuleNames::OBSTACLE_PROCESSOR),
trajectory_planner( std::string(MODULE_NAME_TRAJECTORY_PLANNER), ModuleNames::TRAJECTORY_PLANNER),
yaw_planner( std::string(MODULE_NAME_YAW_PLANNER), ModuleNames::YAW_PLANNER),
mission_planner( std::string(MODULE_NAME_MISSION_PLANNER), ModuleNames::MISSION_PLANNER)
{
last_navdata_timestamp = ros::Time( 0, 0);
wifi_is_ok = false;
battery_threshold = SWARM_AGENT_BATTERY_LEVEL_CHECK_THRESHOLD;
return;
}
ThisSwarmAgentInterface::~ThisSwarmAgentInterface() {
return;
}
void ThisSwarmAgentInterface::open(ros::NodeHandle & nIn) {
n = nIn;
state_estimator.open(n);
trajectory_controller.open(n);
arucoeye.open(n);
localizer.open(n);
obstacle_processor.open(n);
trajectory_planner.open(n);
yaw_planner.open(n);
mission_planner.open(n);
// navdataSub = n.subscribe("ardrone/navdata", 1, &ThisSwarmAgentInterface::navdataSubCallback, this);
drone_rotation_angles_subscriber = n.subscribe(DRONE_BRAIN_SENSOR_ROTATION_ANGLES, 1, &ThisSwarmAgentInterface::droneRotationAnglesCallback, this);
drone_altitude_subscriber = n.subscribe(DRONE_BRAIN_SENSOR_ALTITUDE, 1, &ThisSwarmAgentInterface::droneAltitudeCallback, this);
drone_ground_optical_flow_subscriber = n.subscribe(DRONE_BRAIN_SENSOR_GROUND_SPEED, 1, &ThisSwarmAgentInterface::droneGroundOpticalFlowCallback, this);
battery_level_subscriber=n.subscribe(DRONE_BRAIN_SENSOR_BATTERY, 1, &ThisSwarmAgentInterface::batteryCallback, this);
drone_status_subscriber=n.subscribe(DRONE_BRAIN_SENSOR_STATUS, 1, &ThisSwarmAgentInterface::droneStatusCallback, this);
// takeOffPubl = n.advertise<std_msgs::Empty>("ardrone/takeoff", 1);
// landPubl = n.advertise<std_msgs::Empty>("ardrone/land", 1);
// resetPubl = n.advertise<std_msgs::Empty>("ardrone/reset", 1);
// commandsPubl = n.advertise<geometry_msgs::Twist>("cmd_vel", 1);
DroneCommandPubl=n.advertise<droneMsgsROS::droneCommand>(DRONE_DRIVER_COMMAND_DRONE_HL_COMMAND,1, true);
estimatedPoseSub = n.subscribe(DRONE_BRAIN_POSE_SUBSCRIBER, 1, &ThisSwarmAgentInterface::estimatedPoseSubCallback, this);
}
bool ThisSwarmAgentInterface::startModule( ModuleNames::name module_name_enum) {
switch (module_name_enum) {
case ModuleNames::ODOMETRY_STATE_ESTIMATOR:
return state_estimator.start();
break;
case ModuleNames::TRAJECTORY_CONTROLLER:
return trajectory_controller.start();
break;
case ModuleNames::ARUCO_EYE:
return arucoeye.start();
break;
case ModuleNames::LOCALIZER:
return localizer.start();
break;
case ModuleNames::OBSTACLE_PROCESSOR:
return obstacle_processor.start();
break;
case ModuleNames::TRAJECTORY_PLANNER:
return trajectory_planner.start();
break;
case ModuleNames::YAW_PLANNER:
return yaw_planner.start();
break;
case ModuleNames::MISSION_PLANNER:
return mission_planner.start();
break;
default:
return false;
break;
}
}
bool ThisSwarmAgentInterface::stopModule( ModuleNames::name module_name_enum) {
switch (module_name_enum) {
case ModuleNames::ODOMETRY_STATE_ESTIMATOR:
return state_estimator.stop();
break;
case ModuleNames::TRAJECTORY_CONTROLLER:
return trajectory_controller.stop();
break;
case ModuleNames::ARUCO_EYE:
return arucoeye.stop();
break;
case ModuleNames::LOCALIZER:
return localizer.stop();
break;
case ModuleNames::OBSTACLE_PROCESSOR:
return obstacle_processor.stop();
break;
case ModuleNames::TRAJECTORY_PLANNER:
return trajectory_planner.stop();
break;
case ModuleNames::YAW_PLANNER:
return yaw_planner.stop();
break;
case ModuleNames::MISSION_PLANNER:
return mission_planner.stop();
break;
default:
return false;
break;
}
}
bool ThisSwarmAgentInterface::resetModule( ModuleNames::name module_name_enum) {
switch (module_name_enum) {
case ModuleNames::ODOMETRY_STATE_ESTIMATOR:
return state_estimator.reset();
break;
case ModuleNames::TRAJECTORY_CONTROLLER:
return trajectory_controller.reset();
break;
case ModuleNames::ARUCO_EYE:
return arucoeye.reset();
break;
case ModuleNames::LOCALIZER:
return localizer.reset();
break;
case ModuleNames::OBSTACLE_PROCESSOR:
return obstacle_processor.reset();
break;
case ModuleNames::TRAJECTORY_PLANNER:
return trajectory_planner.reset();
break;
case ModuleNames::YAW_PLANNER:
return yaw_planner.reset();
break;
case ModuleNames::MISSION_PLANNER:
return mission_planner.reset();
break;
default:
return false;
break;
}
}
bool ThisSwarmAgentInterface::isStartedModule( ModuleNames::name module_name_enum) {
switch (module_name_enum) {
case ModuleNames::ODOMETRY_STATE_ESTIMATOR:
return state_estimator.isStarted();
break;
case ModuleNames::TRAJECTORY_CONTROLLER:
return trajectory_controller.isStarted();
break;
case ModuleNames::ARUCO_EYE:
return arucoeye.isStarted();
break;
case ModuleNames::LOCALIZER:
return localizer.isStarted();
break;
case ModuleNames::OBSTACLE_PROCESSOR:
return obstacle_processor.isStarted();
break;
case ModuleNames::TRAJECTORY_PLANNER:
return trajectory_planner.isStarted();
break;
case ModuleNames::YAW_PLANNER:
return yaw_planner.isStarted();
break;
case ModuleNames::MISSION_PLANNER:
return mission_planner.isStarted();
break;
default:
return false;
break;
}
}
//void ThisSwarmAgentInterface::navdataSubCallback(const ardrone_autonomy::Navdata::ConstPtr& msg) {
// last_navdata_timestamp = ros::Time::now();
// wifi_is_ok = true;
// last_navdata = (*msg);
// last_droneNavData.altitude =-last_navdata.altd/1000.0;
// last_droneNavData.pitch =-last_navdata.rotY;
// last_droneNavData.roll = last_navdata.rotX;
// last_droneNavData.yaw =-last_navdata.rotZ;
// last_droneNavData.speedX = last_navdata.vx/1000.0;
// last_droneNavData.speedY =-last_navdata.vy/1000.0;
// last_droneNavData.time = last_navdata.tm;
// // See comment on ardrone_autonomy/msg/Navdata.msg
// // # 0: Unknown, 1: Init, 2: Landed, 3: Flying, 4: Hovering, 5: Test
// // # 6: Taking off, 7: Goto Fix Point, 8: Landing, 9: Looping
// // # Note: 3,7 seems to discriminate type of flying (isFly = 3 | 7)
//// last_navdata.state =
// return;
//}
void ThisSwarmAgentInterface::droneRotationAnglesCallback(const geometry_msgs::Vector3Stamped& msg) {
last_navdata_timestamp = ros::Time::now();
wifi_is_ok = true;
last_rotation_angles_msg = (msg);
}
void ThisSwarmAgentInterface::droneAltitudeCallback(const droneMsgsROS::droneAltitude& msg) {
last_altitude_msg = (msg);
}
void ThisSwarmAgentInterface::droneGroundOpticalFlowCallback(const droneMsgsROS::vector2Stamped& msg) {
last_ground_optical_flow_msg = (msg);
}
void ThisSwarmAgentInterface::batteryCallback(const droneMsgsROS::battery::ConstPtr& msg) {
last_battery_msg = (*msg);
}
void ThisSwarmAgentInterface::droneStatusCallback(const droneMsgsROS::droneStatus::ConstPtr& msg) {
// See comment on ardrone_autonomy/msg/Navdata.msg
// # 0: Unknown, 1: Init, 2: Landed, 3: Flying, 4: Hovering, 5: Test
// # 6: Taking off, 7: Goto Fix Point, 8: Landing, 9: Looping
// # Note: 3,7 seems to discriminate type of flying (isFly = 3 | 7)
last_drone_status_msg = (*msg);
}
bool ThisSwarmAgentInterface::isWifiOk() {
ros::Time current_time = ros::Time::now();
if ( (current_time - last_navdata_timestamp).toSec() > SWARM_AGENT_WIFI_TIMEOUT_THRESHOLD ) {
wifi_is_ok = false;
}
return wifi_is_ok;
}
void ThisSwarmAgentInterface::drone_takeOff() {
droneMsgsROS::droneCommand DroneCommandMsgs;
DroneCommandMsgs.command = DroneCommandMsgs.TAKE_OFF;
DroneCommandPubl.publish(DroneCommandMsgs);
}
void ThisSwarmAgentInterface::drone_land() {
droneMsgsROS::droneCommand DroneCommandMsgs;
DroneCommandMsgs.command = DroneCommandMsgs.LAND;
DroneCommandPubl.publish(DroneCommandMsgs);
}
void ThisSwarmAgentInterface::drone_reset() {
droneMsgsROS::droneCommand DroneCommandMsgs;
DroneCommandMsgs.command = DroneCommandMsgs.RESET;
DroneCommandPubl.publish(DroneCommandMsgs);
}
void ThisSwarmAgentInterface::drone_hover() {
droneMsgsROS::droneCommand DroneCommandMsgs;
DroneCommandMsgs.command = DroneCommandMsgs.HOVER;
DroneCommandPubl.publish(DroneCommandMsgs);
}
void ThisSwarmAgentInterface::drone_move() {
droneMsgsROS::droneCommand DroneCommandMsgs;
DroneCommandMsgs.command = DroneCommandMsgs.MOVE;
DroneCommandPubl.publish(DroneCommandMsgs);
}
void ThisSwarmAgentInterface::estimatedPoseSubCallback(const droneMsgsROS::dronePose::ConstPtr& msg) {
last_estimatedPose = (*msg);
return;
}
bool ThisSwarmAgentInterface::batteryCheckIsOk() {
return last_battery_msg.batteryPercent > SWARM_AGENT_BATTERY_LEVEL_CHECK_THRESHOLD;
}
| 36.367647
| 155
| 0.720077
|
MorS25
|
e6c1a420231a3ef8f358941530bd1eda60aba980
| 639
|
hpp
|
C++
|
Include/Display.hpp
|
ShannonHG/CHIP-8-Emulator
|
37a69e031d276c3ec0d170c34bcaac0450a91d7e
|
[
"MIT"
] | 6
|
2021-03-11T13:35:45.000Z
|
2022-01-25T06:40:44.000Z
|
Include/Display.hpp
|
ShannonHG/CHIP-8-Emulator
|
37a69e031d276c3ec0d170c34bcaac0450a91d7e
|
[
"MIT"
] | null | null | null |
Include/Display.hpp
|
ShannonHG/CHIP-8-Emulator
|
37a69e031d276c3ec0d170c34bcaac0450a91d7e
|
[
"MIT"
] | null | null | null |
#pragma once
#include <cstdint>
#include <SDL.h>
namespace SHG
{
class Display
{
public:
static const int LOW_RES_SCREEN_WIDTH = 64;
static const int LOW_RES_SCREEN_HEIGHT = 32;
static const int LOW_RES_PIXEL_COUNT = LOW_RES_SCREEN_WIDTH * LOW_RES_SCREEN_HEIGHT;
Display(int width, int height);
void Clear();
void SetPixel(int x, int y, uint8_t color);
uint8_t GetPixel(int x, int y);
private:
uint8_t lowResScreenPixels[LOW_RES_PIXEL_COUNT]{};
int screenWidth{};
int screenHeight{};
int pixelWidth{};
int pixelHeight{};
SDL_Window* window{};
SDL_Surface* surface{};
SDL_Renderer* renderer{};
};
}
| 19.96875
| 86
| 0.72144
|
ShannonHG
|
e6c4d69dd59045432fb9cebaf42b40ccbb8669da
| 149
|
cpp
|
C++
|
debug.cpp
|
negram/kopete_mrim
|
c75c28a451e17b14edbe4dcd1ff8b261273473a5
|
[
"BSD-2-Clause"
] | null | null | null |
debug.cpp
|
negram/kopete_mrim
|
c75c28a451e17b14edbe4dcd1ff8b261273473a5
|
[
"BSD-2-Clause"
] | 1
|
2017-01-16T05:37:28.000Z
|
2018-10-22T06:30:29.000Z
|
debug.cpp
|
negram/kopete_mrim
|
c75c28a451e17b14edbe4dcd1ff8b261273473a5
|
[
"BSD-2-Clause"
] | null | null | null |
#include <kdebug.h>
#include "debug.h"
int kdeDebugArea() {
static int area = KDebug::registerArea("kopete (kopete_mrim)");
return area;
}
| 16.555556
| 67
| 0.671141
|
negram
|
e6c6bc332b584f46948901690c1427923bcbcec7
| 5,877
|
cpp
|
C++
|
cmake-build-debug/mechanisms/allen_catalogue.cpp
|
anstaf/arbsimd
|
c4ba87b02b26a47ef33d0a3eba78a4f330c88073
|
[
"BSD-3-Clause"
] | null | null | null |
cmake-build-debug/mechanisms/allen_catalogue.cpp
|
anstaf/arbsimd
|
c4ba87b02b26a47ef33d0a3eba78a4f330c88073
|
[
"BSD-3-Clause"
] | null | null | null |
cmake-build-debug/mechanisms/allen_catalogue.cpp
|
anstaf/arbsimd
|
c4ba87b02b26a47ef33d0a3eba78a4f330c88073
|
[
"BSD-3-Clause"
] | null | null | null |
// Automatically generated by:
// ../../mechanisms/generate_catalogue -A arbor -I /Users/antonaf/arbor-ws/arbsimd/cmake-build-debug/mechanisms/generated/allen -o /Users/antonaf/arbor-ws/arbsimd/cmake-build-debug/mechanisms/allen_catalogue.cpp -B multicore -C allen -N arb::allen_catalogue CaDynamics Ca_HVA Ca_LVA Ih Im Im_v2 K_P K_T Kd Kv2like Kv3_1 NaTa NaTs NaV Nap SK
#include <arbor/mechcat.hpp>
#include <arbor/mechanism.hpp>
#include <arbor/mechanism_abi.h>
#include "/Users/antonaf/arbor-ws/arbsimd/cmake-build-debug/mechanisms/generated/allen/CaDynamics.hpp"
#include "/Users/antonaf/arbor-ws/arbsimd/cmake-build-debug/mechanisms/generated/allen/Ca_HVA.hpp"
#include "/Users/antonaf/arbor-ws/arbsimd/cmake-build-debug/mechanisms/generated/allen/Ca_LVA.hpp"
#include "/Users/antonaf/arbor-ws/arbsimd/cmake-build-debug/mechanisms/generated/allen/Ih.hpp"
#include "/Users/antonaf/arbor-ws/arbsimd/cmake-build-debug/mechanisms/generated/allen/Im.hpp"
#include "/Users/antonaf/arbor-ws/arbsimd/cmake-build-debug/mechanisms/generated/allen/Im_v2.hpp"
#include "/Users/antonaf/arbor-ws/arbsimd/cmake-build-debug/mechanisms/generated/allen/K_P.hpp"
#include "/Users/antonaf/arbor-ws/arbsimd/cmake-build-debug/mechanisms/generated/allen/K_T.hpp"
#include "/Users/antonaf/arbor-ws/arbsimd/cmake-build-debug/mechanisms/generated/allen/Kd.hpp"
#include "/Users/antonaf/arbor-ws/arbsimd/cmake-build-debug/mechanisms/generated/allen/Kv2like.hpp"
#include "/Users/antonaf/arbor-ws/arbsimd/cmake-build-debug/mechanisms/generated/allen/Kv3_1.hpp"
#include "/Users/antonaf/arbor-ws/arbsimd/cmake-build-debug/mechanisms/generated/allen/NaTa.hpp"
#include "/Users/antonaf/arbor-ws/arbsimd/cmake-build-debug/mechanisms/generated/allen/NaTs.hpp"
#include "/Users/antonaf/arbor-ws/arbsimd/cmake-build-debug/mechanisms/generated/allen/NaV.hpp"
#include "/Users/antonaf/arbor-ws/arbsimd/cmake-build-debug/mechanisms/generated/allen/Nap.hpp"
#include "/Users/antonaf/arbor-ws/arbsimd/cmake-build-debug/mechanisms/generated/allen/SK.hpp"
namespace arb {
mechanism_catalogue build_allen_catalogue() {
mechanism_catalogue cat;
cat.add("CaDynamics", make_arb_allen_catalogue_CaDynamics());
cat.add("Ca_HVA", make_arb_allen_catalogue_Ca_HVA());
cat.add("Ca_LVA", make_arb_allen_catalogue_Ca_LVA());
cat.add("Ih", make_arb_allen_catalogue_Ih());
cat.add("Im", make_arb_allen_catalogue_Im());
cat.add("Im_v2", make_arb_allen_catalogue_Im_v2());
cat.add("K_P", make_arb_allen_catalogue_K_P());
cat.add("K_T", make_arb_allen_catalogue_K_T());
cat.add("Kd", make_arb_allen_catalogue_Kd());
cat.add("Kv2like", make_arb_allen_catalogue_Kv2like());
cat.add("Kv3_1", make_arb_allen_catalogue_Kv3_1());
cat.add("NaTa", make_arb_allen_catalogue_NaTa());
cat.add("NaTs", make_arb_allen_catalogue_NaTs());
cat.add("NaV", make_arb_allen_catalogue_NaV());
cat.add("Nap", make_arb_allen_catalogue_Nap());
cat.add("SK", make_arb_allen_catalogue_SK());
cat.register_implementation("CaDynamics", std::make_unique<mechanism>(make_arb_allen_catalogue_CaDynamics(), *make_arb_allen_catalogue_CaDynamics_interface_multicore()));
cat.register_implementation("Ca_HVA", std::make_unique<mechanism>(make_arb_allen_catalogue_Ca_HVA(), *make_arb_allen_catalogue_Ca_HVA_interface_multicore()));
cat.register_implementation("Ca_LVA", std::make_unique<mechanism>(make_arb_allen_catalogue_Ca_LVA(), *make_arb_allen_catalogue_Ca_LVA_interface_multicore()));
cat.register_implementation("Ih", std::make_unique<mechanism>(make_arb_allen_catalogue_Ih(), *make_arb_allen_catalogue_Ih_interface_multicore()));
cat.register_implementation("Im", std::make_unique<mechanism>(make_arb_allen_catalogue_Im(), *make_arb_allen_catalogue_Im_interface_multicore()));
cat.register_implementation("Im_v2", std::make_unique<mechanism>(make_arb_allen_catalogue_Im_v2(), *make_arb_allen_catalogue_Im_v2_interface_multicore()));
cat.register_implementation("K_P", std::make_unique<mechanism>(make_arb_allen_catalogue_K_P(), *make_arb_allen_catalogue_K_P_interface_multicore()));
cat.register_implementation("K_T", std::make_unique<mechanism>(make_arb_allen_catalogue_K_T(), *make_arb_allen_catalogue_K_T_interface_multicore()));
cat.register_implementation("Kd", std::make_unique<mechanism>(make_arb_allen_catalogue_Kd(), *make_arb_allen_catalogue_Kd_interface_multicore()));
cat.register_implementation("Kv2like", std::make_unique<mechanism>(make_arb_allen_catalogue_Kv2like(), *make_arb_allen_catalogue_Kv2like_interface_multicore()));
cat.register_implementation("Kv3_1", std::make_unique<mechanism>(make_arb_allen_catalogue_Kv3_1(), *make_arb_allen_catalogue_Kv3_1_interface_multicore()));
cat.register_implementation("NaTa", std::make_unique<mechanism>(make_arb_allen_catalogue_NaTa(), *make_arb_allen_catalogue_NaTa_interface_multicore()));
cat.register_implementation("NaTs", std::make_unique<mechanism>(make_arb_allen_catalogue_NaTs(), *make_arb_allen_catalogue_NaTs_interface_multicore()));
cat.register_implementation("NaV", std::make_unique<mechanism>(make_arb_allen_catalogue_NaV(), *make_arb_allen_catalogue_NaV_interface_multicore()));
cat.register_implementation("Nap", std::make_unique<mechanism>(make_arb_allen_catalogue_Nap(), *make_arb_allen_catalogue_Nap_interface_multicore()));
cat.register_implementation("SK", std::make_unique<mechanism>(make_arb_allen_catalogue_SK(), *make_arb_allen_catalogue_SK_interface_multicore()));
return cat;
}
const mechanism_catalogue& global_allen_catalogue() {
static mechanism_catalogue cat = build_allen_catalogue();
return cat;
}
} // namespace arb
#ifdef STANDALONE
extern "C" {
[[gnu::visibility("default")]] const void* get_catalogue() {
static auto cat = arb::build_allen_catalogue();
return (void*)&cat;
}
}
#endif
| 72.555556
| 340
| 0.797686
|
anstaf
|
e6ca39ece54612000b643c2dbbdf036fc11a55b1
| 14,705
|
cpp
|
C++
|
tket/tests/test_ArchitectureAwareSynthesis.cpp
|
CQCL/tket
|
3f3d7c24d9a6c9cfd85966c13dcccc8a13f92adb
|
[
"Apache-2.0"
] | 104
|
2021-09-15T08:16:25.000Z
|
2022-03-28T21:19:00.000Z
|
tket/tests/test_ArchitectureAwareSynthesis.cpp
|
CQCL/tket
|
3f3d7c24d9a6c9cfd85966c13dcccc8a13f92adb
|
[
"Apache-2.0"
] | 109
|
2021-09-16T17:14:22.000Z
|
2022-03-29T06:48:40.000Z
|
tket/tests/test_ArchitectureAwareSynthesis.cpp
|
CQCL/tket
|
3f3d7c24d9a6c9cfd85966c13dcccc8a13f92adb
|
[
"Apache-2.0"
] | 8
|
2021-10-02T13:47:34.000Z
|
2022-03-17T15:36:56.000Z
|
// Copyright 2019-2022 Cambridge Quantum Computing
//
// 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 <catch2/catch.hpp>
#include "Architecture/Architecture.hpp"
#include "Predicates/CompilerPass.hpp"
#include "Predicates/PassGenerators.hpp"
#include "Simulation/CircuitSimulator.hpp"
#include "Simulation/ComparisonFunctions.hpp"
#include "testutil.hpp"
namespace tket {
using Connection = Architecture::Connection;
SCENARIO("Routing of aas example") {
GIVEN("aas routing - simple example") {
Architecture arc(std::vector<Connection>{
{Node(0), Node(1)}, {Node(1), Node(2)}, {Node(2), Node(3)}});
PassPtr pass = gen_full_mapping_pass_phase_poly(arc);
Circuit circ(4);
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
circ.add_op<unsigned>(OpType::H, {2});
circ.add_op<unsigned>(OpType::H, {3});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::Rz, 0.3, {3});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
circ.add_op<unsigned>(OpType::H, {2});
circ.add_op<unsigned>(OpType::H, {3});
CompilationUnit cu(circ);
REQUIRE(pass->apply(cu));
Circuit result = cu.get_circ_ref();
REQUIRE(test_unitary_comparison(circ, result));
}
GIVEN("aas routing - simple example II") {
Architecture arc(std::vector<Connection>{
{Node(0), Node(1)}, {Node(1), Node(2)}, {Node(2), Node(3)}});
PassPtr pass = gen_full_mapping_pass_phase_poly(arc);
Circuit circ(4);
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
circ.add_op<unsigned>(OpType::H, {2});
circ.add_op<unsigned>(OpType::H, {3});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::Rz, 0.3, {3});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::Rz, 0.3, {3});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
circ.add_op<unsigned>(OpType::H, {2});
circ.add_op<unsigned>(OpType::H, {3});
CompilationUnit cu(circ);
REQUIRE(pass->apply(cu));
Circuit result = cu.get_circ_ref();
REQUIRE(test_unitary_comparison(circ, result));
}
GIVEN("aas routing - simple example III") {
Architecture arc(std::vector<Connection>{
{Node(0), Node(1)}, {Node(1), Node(2)}, {Node(2), Node(3)}});
PassPtr pass = gen_full_mapping_pass_phase_poly(arc);
Circuit circ(4);
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
circ.add_op<unsigned>(OpType::H, {2});
circ.add_op<unsigned>(OpType::H, {3});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::Rz, 0.3, {3});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::Rz, 0.3, {3});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::Rz, 0.3, {3});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
circ.add_op<unsigned>(OpType::H, {2});
circ.add_op<unsigned>(OpType::H, {3});
CompilationUnit cu(circ);
REQUIRE(pass->apply(cu));
Circuit result = cu.get_circ_ref();
REQUIRE(test_unitary_comparison(circ, result));
}
GIVEN("aas routing - simple example IV") {
Architecture arc(std::vector<Connection>{
{Node(0), Node(1)}, {Node(1), Node(2)}, {Node(2), Node(3)}});
PassPtr pass = gen_full_mapping_pass_phase_poly(arc);
Circuit circ(4);
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
circ.add_op<unsigned>(OpType::H, {2});
circ.add_op<unsigned>(OpType::H, {3});
circ.add_op<unsigned>(OpType::Rz, 0.1, {0});
circ.add_op<unsigned>(OpType::Rz, 0.1, {1});
circ.add_op<unsigned>(OpType::Rz, 0.1, {2});
circ.add_op<unsigned>(OpType::Rz, 0.1, {3});
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
circ.add_op<unsigned>(OpType::H, {2});
circ.add_op<unsigned>(OpType::H, {3});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::Rz, 0.3, {3});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::Rz, 0.3, {3});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::Rz, 0.3, {3});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
circ.add_op<unsigned>(OpType::H, {2});
circ.add_op<unsigned>(OpType::H, {3});
CompilationUnit cu(circ);
REQUIRE(pass->apply(cu));
Circuit result = cu.get_circ_ref();
REQUIRE(test_unitary_comparison(circ, result));
}
GIVEN("aas routing - simple example V") {
Architecture arc(std::vector<Connection>{{Node(0), Node(1)}});
PassPtr pass = gen_full_mapping_pass_phase_poly(arc);
Circuit circ(2);
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::Rz, 0.1, {0});
circ.add_op<unsigned>(OpType::Rz, 0.1, {1});
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
CompilationUnit cu(circ);
REQUIRE(pass->apply(cu));
Circuit result = cu.get_circ_ref();
REQUIRE(test_unitary_comparison(circ, result));
}
GIVEN("aas routing - simple example VI") {
Architecture arc(std::vector<Connection>{{Node(0), Node(2)}});
PassPtr pass = gen_full_mapping_pass_phase_poly(arc);
Circuit circ(2);
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::Rz, 0.1, {0});
circ.add_op<unsigned>(OpType::Rz, 0.1, {1});
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
CompilationUnit cu(circ);
REQUIRE(pass->apply(cu));
Circuit result = cu.get_circ_ref();
REQUIRE(test_unitary_comparison(circ, result));
const auto s = tket_sim::get_unitary(circ);
const auto s1 = tket_sim::get_unitary(result);
REQUIRE(tket_sim::compare_statevectors_or_unitaries(
s, s1, tket_sim::MatrixEquivalence::EQUAL));
}
GIVEN("aas routing - simple example VII") {
Architecture arc(std::vector<Connection>{
{Node(0), Node(2)}, {Node(2), Node(4)}, {Node(4), Node(6)}});
PassPtr pass = gen_full_mapping_pass_phase_poly(arc);
Circuit circ(4);
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
circ.add_op<unsigned>(OpType::H, {2});
circ.add_op<unsigned>(OpType::H, {3});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::Rz, 0.1, {0});
circ.add_op<unsigned>(OpType::Rz, 0.1, {1});
circ.add_op<unsigned>(OpType::Rz, 0.1, {2});
circ.add_op<unsigned>(OpType::Rz, 0.1, {3});
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
circ.add_op<unsigned>(OpType::H, {2});
circ.add_op<unsigned>(OpType::H, {3});
CompilationUnit cu(circ);
REQUIRE(pass->apply(cu));
Circuit result = cu.get_circ_ref();
REQUIRE(test_unitary_comparison(circ, result));
const auto s = tket_sim::get_unitary(circ);
const auto s1 = tket_sim::get_unitary(result);
REQUIRE(tket_sim::compare_statevectors_or_unitaries(
s, s1, tket_sim::MatrixEquivalence::EQUAL));
}
GIVEN("aas routing - simple example VIII") {
Architecture arc(std::vector<Connection>{
{Node(1000), Node(10)}, {Node(10), Node(100)}, {Node(100), Node(1)}});
PassPtr pass = gen_full_mapping_pass_phase_poly(arc);
Circuit circ(4);
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
circ.add_op<unsigned>(OpType::H, {2});
circ.add_op<unsigned>(OpType::H, {3});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::Rz, 0.1, {0});
circ.add_op<unsigned>(OpType::Rz, 0.1, {1});
circ.add_op<unsigned>(OpType::Rz, 0.1, {2});
circ.add_op<unsigned>(OpType::Rz, 0.1, {3});
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
circ.add_op<unsigned>(OpType::H, {2});
circ.add_op<unsigned>(OpType::H, {3});
CompilationUnit cu(circ);
REQUIRE(pass->apply(cu));
Circuit result = cu.get_circ_ref();
REQUIRE(test_unitary_comparison(circ, result));
}
GIVEN("aas routing - simple example IX, other gate set") {
Architecture arc(std::vector<Connection>{
{Node(1000), Node(10)}, {Node(10), Node(100)}, {Node(100), Node(1)}});
PassPtr pass = gen_full_mapping_pass_phase_poly(arc);
Circuit circ(4);
circ.add_op<unsigned>(OpType::X, {0});
circ.add_op<unsigned>(OpType::X, {1});
circ.add_op<unsigned>(OpType::X, {2});
circ.add_op<unsigned>(OpType::X, {3});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::CX, {2, 3});
circ.add_op<unsigned>(OpType::Rz, 0.1, {0});
circ.add_op<unsigned>(OpType::Rz, 0.1, {1});
circ.add_op<unsigned>(OpType::Rz, 0.1, {2});
circ.add_op<unsigned>(OpType::Rz, 0.1, {3});
circ.add_op<unsigned>(OpType::X, {0});
circ.add_op<unsigned>(OpType::X, {1});
circ.add_op<unsigned>(OpType::X, {2});
circ.add_op<unsigned>(OpType::X, {3});
CompilationUnit cu(circ);
REQUIRE(pass->apply(cu));
Circuit result = cu.get_circ_ref();
REQUIRE(test_unitary_comparison(circ, result));
}
GIVEN("aas routing with measure") {
Architecture arc(std::vector<Connection>{{Node(0), Node(2)}});
PassPtr pass = gen_full_mapping_pass_phase_poly(arc);
Circuit circ(2, 2);
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::Rz, 0.1, {0});
circ.add_op<unsigned>(OpType::Rz, 0.1, {1});
circ.add_op<unsigned>(OpType::H, {0});
circ.add_op<unsigned>(OpType::H, {1});
for (unsigned mes = 0; mes < 2; ++mes) {
circ.add_measure(mes, mes);
}
CompilationUnit cu(circ);
REQUIRE(pass->apply(cu));
}
GIVEN("aas routing - circuit with fewer qubits then nodes in the arch") {
Architecture arc(std::vector<Connection>{
{Node(0), Node(1)}, {Node(1), Node(2)}, {Node(2), Node(3)}});
PassPtr pass = gen_full_mapping_pass_phase_poly(arc);
Circuit circ(3);
circ.add_op<unsigned>(OpType::X, {0});
circ.add_op<unsigned>(OpType::X, {1});
circ.add_op<unsigned>(OpType::X, {2});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::Rz, 0.1, {0});
circ.add_op<unsigned>(OpType::Rz, 0.2, {1});
circ.add_op<unsigned>(OpType::Rz, 0.3, {2});
circ.add_op<unsigned>(OpType::X, {0});
circ.add_op<unsigned>(OpType::X, {1});
circ.add_op<unsigned>(OpType::X, {2});
CompilationUnit cu(circ);
REQUIRE(pass->apply(cu));
Circuit result = cu.get_circ_ref();
REQUIRE(test_unitary_comparison(circ, result));
}
GIVEN("aas routing - circuit with fewer qubits then nodes in the arch II") {
Architecture arc(std::vector<Connection>{
{Node(0), Node(1)},
{Node(1), Node(2)},
{Node(2), Node(3)},
{Node(3), Node(4)}});
PassPtr pass = gen_full_mapping_pass_phase_poly(arc);
Circuit circ(3);
circ.add_op<unsigned>(OpType::X, {0});
circ.add_op<unsigned>(OpType::X, {1});
circ.add_op<unsigned>(OpType::X, {2});
circ.add_op<unsigned>(OpType::CX, {0, 1});
circ.add_op<unsigned>(OpType::CX, {1, 2});
circ.add_op<unsigned>(OpType::Rz, 0.1, {0});
circ.add_op<unsigned>(OpType::Rz, 0.2, {1});
circ.add_op<unsigned>(OpType::Rz, 0.3, {2});
circ.add_op<unsigned>(OpType::X, {0});
circ.add_op<unsigned>(OpType::X, {1});
circ.add_op<unsigned>(OpType::X, {2});
CompilationUnit cu(circ);
REQUIRE(pass->apply(cu));
Circuit result = cu.get_circ_ref();
REQUIRE(test_unitary_comparison(circ, result));
}
}
} // namespace tket
| 39.52957
| 78
| 0.63033
|
CQCL
|
e6cbad994f70ad28aa9e8b8d49677ae9879b62d9
| 1,249
|
cpp
|
C++
|
Contest Volumes/Volume 100/10070 - Leap Year or Not Leap Year and ...cpp
|
Md-Shamim-Ahmmed/UVA-Online-Judge-Problems-Solution
|
2334edb153a134aebb883b57d8b4faf0cb859331
|
[
"MIT"
] | null | null | null |
Contest Volumes/Volume 100/10070 - Leap Year or Not Leap Year and ...cpp
|
Md-Shamim-Ahmmed/UVA-Online-Judge-Problems-Solution
|
2334edb153a134aebb883b57d8b4faf0cb859331
|
[
"MIT"
] | null | null | null |
Contest Volumes/Volume 100/10070 - Leap Year or Not Leap Year and ...cpp
|
Md-Shamim-Ahmmed/UVA-Online-Judge-Problems-Solution
|
2334edb153a134aebb883b57d8b4faf0cb859331
|
[
"MIT"
] | null | null | null |
#include<cstring>
#include<sstream>
#include<iostream>
#include<algorithm>
#include<bits/stdc++.h>
#define FOR(i, len) for(int i = 0; i < len; i++)
#define br "\n"
using namespace std;
int main()
{
string str;
int p = 0;
while (cin >> str)
{
int test4, test15, test55, test100, test400;
int huluculu = 0, bulukulu = 0, leap = 0, len;
if (p > 0)
cout << br;
p++;
test4 = test15 = test55 = test100 = test400 = 0;
len = str.size();
FOR(i, len)
{
test4 = (test4 * 10 + (str[i] - '0')) % 4;
test15 = (test15 * 10 + (str[i] - '0')) % 15;
test55 = (test55 * 10 + (str[i] - '0')) % 55;
test100 = (test100 * 10 + (str[i] - '0')) % 100;
test400 = (test400 * 10 + (str[i] - '0')) % 400;
}
if (test4 == 0)
{
if (test100 == 0)
{
if (test400 == 0) {
cout << "This is leap year." << br;
leap = 1;
}
}
else {
cout << "This is leap year." << br;
leap = 1;
}
}
if (test15 == 0) {
cout << "This is huluculu festival year." << br;
huluculu = 1;
}
if (leap == 1 && test55 == 0) {
cout << "This is bulukulu festival year." << br;
bulukulu = 1;
}
if (leap == 0 && huluculu == 0 && bulukulu == 0)
cout << "This is an ordinary year." << br;
}
return 0;
}
| 20.145161
| 51
| 0.508407
|
Md-Shamim-Ahmmed
|
e6d8f10ce875061afe20c782d4e8875b98f3267f
| 524
|
cpp
|
C++
|
Algorithms/Math/Permutation_and_Combination/prev_permutation.cpp
|
TheMartian73/Data-Structure-and-Algorithm
|
8a37ad3f5d3cfc65b02240c4a5b2bdd30763143e
|
[
"MIT"
] | null | null | null |
Algorithms/Math/Permutation_and_Combination/prev_permutation.cpp
|
TheMartian73/Data-Structure-and-Algorithm
|
8a37ad3f5d3cfc65b02240c4a5b2bdd30763143e
|
[
"MIT"
] | 3
|
2020-07-02T15:42:05.000Z
|
2020-07-06T19:49:52.000Z
|
Algorithms/Math/Permutation_and_Combination/prev_permutation.cpp
|
TheMartian73/Data-Structure-and-Algorithm
|
8a37ad3f5d3cfc65b02240c4a5b2bdd30763143e
|
[
"MIT"
] | 2
|
2020-07-26T14:21:02.000Z
|
2020-10-01T08:36:37.000Z
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool PrevPermutation(string &str) {
int n = str.size();
int i = n - 1;
while(i && str[i - 1] <= str[i])
i--;
if (!i) return false;
int j = i + 1;
while(j < n && str[i - 1] >= str[j])
j++;
swap(str[i - 1], str[j-1]);
reverse(str.begin() + i, str.end());
return true;
}
int main() {
string str;
cout << "Enter string : ";
cin >> str;
PrevPermutation(str);
cout << "Prev Permutation : " << str << "\n";
}
| 16.903226
| 47
| 0.540076
|
TheMartian73
|
e6da19e42f0003fda0fba76afe32142263699f86
| 258
|
tpp
|
C++
|
BCC__BCC36B__P[3]__HenriqueMarcuzzo_2046334/impl/semantica-testes/sema-005.tpp
|
hmarcuzzo/compiler_project
|
2463d19c2b81ba28a943974828e8bb5954424cac
|
[
"Apache-2.0"
] | null | null | null |
BCC__BCC36B__P[3]__HenriqueMarcuzzo_2046334/impl/semantica-testes/sema-005.tpp
|
hmarcuzzo/compiler_project
|
2463d19c2b81ba28a943974828e8bb5954424cac
|
[
"Apache-2.0"
] | null | null | null |
BCC__BCC36B__P[3]__HenriqueMarcuzzo_2046334/impl/semantica-testes/sema-005.tpp
|
hmarcuzzo/compiler_project
|
2463d19c2b81ba28a943974828e8bb5954424cac
|
[
"Apache-2.0"
] | 4
|
2020-12-11T10:12:37.000Z
|
2021-11-01T18:34:25.000Z
|
{Erro: Chamada à função 'func' com número de parâmetros menor que o declarado}
{Erro: Função principal deveria retornar inteiro, mas retorna vazio}
inteiro func(inteiro: x, inteiro: y)
retorna(x + y)
fim
inteiro principal()
inteiro: a
a := func(10)
fim
| 21.5
| 78
| 0.736434
|
hmarcuzzo
|
5c8658717285470ab2efbbcacc3a69010673e072
| 282
|
cpp
|
C++
|
test/text_charconv_helper_test.cpp
|
PazerOP/stuff
|
8ef31153dce1c9593d59fe7fb731fca4d15f3fa6
|
[
"MIT"
] | null | null | null |
test/text_charconv_helper_test.cpp
|
PazerOP/stuff
|
8ef31153dce1c9593d59fe7fb731fca4d15f3fa6
|
[
"MIT"
] | 4
|
2020-01-04T02:26:00.000Z
|
2020-04-19T10:46:50.000Z
|
test/text_charconv_helper_test.cpp
|
PazerOP/stuff
|
8ef31153dce1c9593d59fe7fb731fca4d15f3fa6
|
[
"MIT"
] | null | null | null |
#include "catch2/repo/single_include/catch2/catch.hpp"
#ifdef __cpp_lib_to_chars
#include "mh/text/charconv_helper.hpp"
TEST_CASE("charconv helpers", "[text][charconv_helper]")
{
std::string test;
test << "Hello" << " world" << " !";
REQUIRE(test == "Hello world !");
}
#endif
| 21.692308
| 56
| 0.691489
|
PazerOP
|
5c8718f61f9d4e71130bc73302e3dbfbbdc35d1a
| 1,640
|
cpp
|
C++
|
src/tests/IPFSTest.cpp
|
blockfrost/blockfrost-arduino
|
04525e01dd535c167cc97232670809cac2575ee3
|
[
"Apache-2.0"
] | 7
|
2021-12-15T12:11:21.000Z
|
2022-01-25T13:29:04.000Z
|
src/tests/IPFSTest.cpp
|
blockfrost/blockfrost-arduino
|
04525e01dd535c167cc97232670809cac2575ee3
|
[
"Apache-2.0"
] | null | null | null |
src/tests/IPFSTest.cpp
|
blockfrost/blockfrost-arduino
|
04525e01dd535c167cc97232670809cac2575ee3
|
[
"Apache-2.0"
] | null | null | null |
#include "types/IPFS.h"
using namespace Blockfrost;
#include <string>
#include <list>
#include <unity.h>
#include "bourne/json.hpp"
void test_IPFSAdd() {
std::string raw =
"{"
" \"name\": \"README.md\","
" \"ipfs_hash\": \"QmZbHqiCxKEVX7QfijzJTkZiSi3WEVTcvANgNAWzDYgZDr\","
" \"size\": \"125297\""
"}";
IPFSAdd a1(raw);
IPFSAdd a(a1.toJson().dump());
TEST_ASSERT_EQUAL_STRING("README.md", a.name.c_str());
TEST_ASSERT_EQUAL_STRING("QmZbHqiCxKEVX7QfijzJTkZiSi3WEVTcvANgNAWzDYgZDr", a.ipfs_hash.c_str());
TEST_ASSERT_EQUAL_STRING("125297", a.size.c_str());
}
void test_IPFSPinChange() {
std::string raw =
"{"
" \"ipfs_hash\": \"QmPojRfAXYAXV92Dof7gtSgaVuxEk64xx9CKvprqu9VwA8\","
" \"state\": \"queued\""
"}";
IPFSPinChange a1(raw);
IPFSPinChange a(a1.toJson().dump());
TEST_ASSERT_EQUAL_STRING("QmPojRfAXYAXV92Dof7gtSgaVuxEk64xx9CKvprqu9VwA8", a.ipfs_hash.c_str());
TEST_ASSERT_EQUAL_STRING("queued", a.state.c_str());
}
void test_IPFSPin() {
std::string raw =
"{"
" \"time_created\": 1615551024,"
" \"time_pinned\": 1615671024,"
" \"ipfs_hash\": \"QmdVMnULrY95mth2XkwjxDtMHvzuzmvUPTotKE1tgqKbCx\","
" \"size\": \"1615551024\","
" \"state\": \"pinned\""
"}";
IPFSPin a1(raw);
IPFSPin a(a1.toJson().dump());
TEST_ASSERT_EQUAL_INT(1615551024, a.time_created);
TEST_ASSERT_EQUAL_INT(1615671024, a.time_pinned);
TEST_ASSERT_EQUAL_STRING("QmdVMnULrY95mth2XkwjxDtMHvzuzmvUPTotKE1tgqKbCx", a.ipfs_hash.c_str());
TEST_ASSERT_EQUAL_STRING("1615551024", a.size.c_str());
TEST_ASSERT_EQUAL_STRING("pinned", a.state.c_str());
}
| 26.451613
| 98
| 0.678049
|
blockfrost
|
5c89ddf65373f3ad4432e3e31c66f72211ef4b6a
| 768
|
cpp
|
C++
|
CGES/src/texture.cpp
|
Nao-Shirotsu/Embree_CGES
|
6f70984a49c9bf4ad94ed1496ac2dbc314889de8
|
[
"Apache-2.0"
] | 2
|
2020-09-25T15:02:23.000Z
|
2020-11-27T05:28:20.000Z
|
CGES/src/texture.cpp
|
Nao-Shirotsu/Embree-CGES
|
6f70984a49c9bf4ad94ed1496ac2dbc314889de8
|
[
"Apache-2.0"
] | 30
|
2020-02-26T02:55:30.000Z
|
2020-10-18T18:00:12.000Z
|
CGES/src/texture.cpp
|
Nao-Shirotsu/Embree-CGES
|
6f70984a49c9bf4ad94ed1496ac2dbc314889de8
|
[
"Apache-2.0"
] | null | null | null |
#include "texture.hpp"
#include "util_texture.hpp"
#include <algorithm>
namespace cges {
Texture::Texture(const char* const filePath)
: m_imageBuffer(tex::LoadFromFile(filePath)) {}
Texture::Texture(const ColorRGBA singleColor)
: m_imageBuffer(1, 1) {
m_imageBuffer[0][0] = singleColor;
}
ColorRGBA Texture::GetPixel(const float x, const float y) const noexcept{
uint32_t xIdx = static_cast<uint32_t>(std::clamp(x, 0.0f, 1.0f) * m_imageBuffer.GetWidth());
uint32_t yIdx = static_cast<uint32_t>(std::clamp(y, 0.0f, 1.0f) * m_imageBuffer.GetHeight());
return m_imageBuffer[yIdx][xIdx];
}
#ifdef _DEBUG
void Texture::SaveAsPpm(const char* const filePath) {
m_imageBuffer.SaveAsPpm(filePath);
}
#endif
}// namespace cges
| 27.428571
| 96
| 0.705729
|
Nao-Shirotsu
|
5c8ec15c46a9e230dc6bc444adbfea30b478cf6e
| 2,695
|
cpp
|
C++
|
src_test/blockchain/trx/test_transaction_sig.cpp
|
alinous-core/codable-cash
|
32a86a152a146c592bcfd8cc712f4e8cb38ee1a0
|
[
"MIT"
] | 1
|
2020-10-15T08:24:35.000Z
|
2020-10-15T08:24:35.000Z
|
src_test/blockchain/trx/test_transaction_sig.cpp
|
Codablecash/codablecash
|
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
|
[
"MIT"
] | null | null | null |
src_test/blockchain/trx/test_transaction_sig.cpp
|
Codablecash/codablecash
|
8816b69db69ff2f5da6cdb6af09b8fb21d3df1d9
|
[
"MIT"
] | null | null | null |
/*
* test_transaction_sig.cpp
*
* Created on: 2022/03/23
* Author: iizuka
*/
#include "test_utils/t_macros.h"
#include "numeric/BigInteger.h"
#include "bc_address/BlockchainAddressManager.h"
#include "bc_address/BlockchainAddress.h"
#include "base/StackRelease.h"
#include "bc_trx/Transaction.h"
#include "bc_base/BalanceUnit.h"
#include "ecda/ScSignature.h"
#include "bc_base/TransactionId.h"
using namespace codablecash;
TEST_GROUP(TestTransactionSigGroup) {
TEST_SETUP(){}
TEST_TEARDOWN(){}
};
TEST(TestTransactionSigGroup, case01){
BigInteger seed = BigInteger::ramdom();
BlockchainAddressManager* mgr = new BlockchainAddressManager(10, &seed); __STP(mgr);
Transaction* trx = new Transaction(); __STP(trx);
BlockchainAddress* addr1 = mgr->createBlockchainAddress();
BlockchainAddress* addr2 = mgr->createBlockchainAddress();
BlockchainAddress* addr3 = mgr->createBlockchainAddress();
BlockchainAddress* addr4 = mgr->createBlockchainAddress();
BlockchainAddress* addr5 = mgr->createBlockchainAddress();
trx->addInput(addr1, 100);
trx->addInput(addr2, 200);
trx->addInput(addr3, 200);
trx->addOutput(addr4, 100);
trx->addOutput(addr5, 399);
trx->setFee(BalanceUnit(1));
trx->updateTransactionId();
ScSignature* sig = mgr->signTransaction(trx);
bool bl = trx->checkSignature();
CHECK(!bl);
trx->setSignature(sig);
bl = trx->checkSignature();
CHECK(bl);
ScSignature sig2(*sig);
trx->setSignature(new ScSignature(sig2));
bl = trx->checkSignature();
CHECK(bl);
const TransactionId* trxId = trx->getTransactionId();
TransactionId* trxId2 = dynamic_cast<TransactionId*>(trxId->copyData()); __STP(trxId2);
CHECK(trxId2->equals(trxId));
{
Transaction* trx2 = new Transaction(*trx); __STP(trx2);
}
}
TEST(TestTransactionSigGroup, case01_err){
BigInteger seed = BigInteger::ramdom();
BlockchainAddressManager* mgr = new BlockchainAddressManager(10, &seed); __STP(mgr);
BigInteger seed2 = BigInteger::ramdom();
BlockchainAddressManager* mgr2 = new BlockchainAddressManager(10, &seed); __STP(mgr2);
Transaction* trx = new Transaction(); __STP(trx);
BlockchainAddress* addr1 = mgr->createBlockchainAddress();
BlockchainAddress* addr2 = mgr->createBlockchainAddress();
BlockchainAddress* addr3 = mgr2->createBlockchainAddress();
BlockchainAddress* addr4 = mgr->createBlockchainAddress();
BlockchainAddress* addr5 = mgr->createBlockchainAddress();
trx->addInput(addr1, 100);
trx->addInput(addr2, 200);
trx->addInput(addr3, 200);
trx->addOutput(addr4, 100);
trx->addOutput(addr5, 399);
trx->setFee(BalanceUnit(1));
trx->updateTransactionId();
ScSignature* sig = mgr->signTransaction(trx);
CHECK(sig == nullptr)
}
| 25.186916
| 88
| 0.740631
|
alinous-core
|
5c942fb923a7063c43faf233f73e183f21e1cce6
| 3,001
|
cpp
|
C++
|
maku/render/kernel32_hooker.cpp
|
shileiyu/maku
|
be07aa6f804c387aafbd79cdf952bd6a93c18771
|
[
"MIT"
] | 10
|
2015-04-09T01:43:28.000Z
|
2021-03-29T15:59:01.000Z
|
maku/render/kernel32_hooker.cpp
|
shileiyu/maku
|
be07aa6f804c387aafbd79cdf952bd6a93c18771
|
[
"MIT"
] | null | null | null |
maku/render/kernel32_hooker.cpp
|
shileiyu/maku
|
be07aa6f804c387aafbd79cdf952bd6a93c18771
|
[
"MIT"
] | 1
|
2020-07-02T03:52:56.000Z
|
2020-07-02T03:52:56.000Z
|
//without this macro that will lead to confilcit with winsock2 header
//we define it ourself.
#include "kernel32_hooker.h"
#include "detours\detours.h"
#include "detours\detours_ext.h"
#include "ddraw_hooker.h"
//#include "d3d8_hooker.h"
#include "d3d9_hooker.h"
#include "dxgi_hooker.h"
#include "dinput_hooker.h"
#include "opengl_hooker.h"
namespace maku
{
namespace render
{
//Define type of LoadLibraryExW
typedef HMODULE (WINAPI *LoadLibraryExW_t)(
LPCWSTR lpLibFileName,
HANDLE hFile,
DWORD dwFlags);
//Pointer to True LoadLibraryExW.
//Caution! its value will be changed by Detour Functions.
LoadLibraryExW_t TLoadLibraryExW = 0;
//Our Detoured LoadLibraryExW.
//Just forward to original LoadLibraryExW then try to hook target module.
//target hooker decide whether do a hook procedure.
HMODULE WINAPI FLoadLibraryExW(
LPCWSTR lpLibFileName,
HANDLE hFile,
DWORD dwFlags)
{
HMODULE curr_mod = 0;
if(TLoadLibraryExW)
{
curr_mod = TLoadLibraryExW(lpLibFileName, hFile, dwFlags);
DXGIHooker::Hook();
DinputHooker::Hook();
D3D9Hooker::Hook();
//D3D8Hooker::Hook();
DDrawHooker::Hook();
OpenGLHooker::Hook();
}
return curr_mod;
}
//speak by itself
ncore::SpinLock Kernel32Hooker::locker_;
void Kernel32Hooker::Hook()
{
void * module = 0;
OSVERSIONINFO osver = {0};
osver.dwOSVersionInfoSize = sizeof(osver);
GetVersionEx(&osver);
DWORD major = osver.dwMajorVersion;
DWORD minor = osver.dwMinorVersion;
//only support xp, vist and win7.
if(major != 5 && major != 6)
return;
//if it's running on win 7, hook KernelBase instead.
if(major == 6 && minor == 1)
{
module = ::GetModuleHandle(L"kernelBase.dll");
}
else
{
module = ::GetModuleHandle(L"kernel32.dll");
}
//we can't find base address of kernel module. just ignore.
//it seem like can't happen in real-world.
if(module == 0)
return;
//make sure this module haven't detoured yet.
//why we check it twice.
//please searching double check lock pattern for further study.
if(!IsModuleDetoured(module))
{
locker_.Acquire();
if(!IsModuleDetoured(module))
{
//retrive address of LoadLibraryExW.
HMODULE mod = (HMODULE)module;
FARPROC proc = GetProcAddress(mod, "LoadLibraryExW");
TLoadLibraryExW = (LoadLibraryExW_t)proc;
//hook it
if(TLoadLibraryExW)
{
HANDLE curr_thread = GetCurrentThread();
DetourTransactionBegin();
DetourUpdateThread(curr_thread);
DetourAttach(&(PVOID&)TLoadLibraryExW, FLoadLibraryExW);
//if every thing is ok. mark kernel module detoured.
if(!DetourTransactionCommit())
MarkModuleDetoured(module);
}
}
locker_.Release();
}
}
}
}
| 26.794643
| 73
| 0.634455
|
shileiyu
|
5ca0f9475a316d1055fd7c7f7093a013e9bc338f
| 18,628
|
cpp
|
C++
|
src/Wax9.cpp
|
redpaperheart/Wax9
|
1d3be081727c8aa30f42ea05028e78a9026130cb
|
[
"Unlicense"
] | 3
|
2016-02-25T15:39:05.000Z
|
2019-08-28T20:37:41.000Z
|
src/Wax9.cpp
|
redpaperheart/Wax9
|
1d3be081727c8aa30f42ea05028e78a9026130cb
|
[
"Unlicense"
] | 1
|
2015-02-06T16:51:31.000Z
|
2015-04-24T18:20:21.000Z
|
src/Wax9.cpp
|
redpaperheart/Wax9
|
1d3be081727c8aa30f42ea05028e78a9026130cb
|
[
"Unlicense"
] | null | null | null |
/*
Created by Adrià Navarro at Red Paper Heart
Copyright (c) 2015, Red Paper Heart
All rights reserved.
This code is designed for use with the Cinder C++ library, http://libcinder.org
To contact Red Paper Heart, email hello@redpaperheart.com or tweet @redpaperhearts
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "Wax9.h"
/* -------------------------------------------------------------------------------------------------- */
#pragma mark constructors and setup
/* -------------------------------------------------------------------------------------------------- */
Wax9::Wax9()
{
// state
bEnabled = true;
bConnected = false;
bDebug = false;
bSmooth = false;
mSmoothFactor = 0.8;
mNewReadings = 0;
mHistoryLength = 120;
mTimeout = 5.0f;
mLastReadingTime = std::numeric_limits<float>::infinity();
bBatteryLow = false;
mBattery = 0xffff;
mPressure = 0xfffffffful;
mTemperature = 0xffff;
// device settings
bAccOn = true;
bGyrOn = true;
bMagOn = true;
mOutputRate = 120;
mAccRate = 200;
mGyrRate = 200;
mMagRate = 80;
mAccRange = 8;
mGyrRange = 2000;
mDataMode = 1;
mGyroDelta = vec3(0);
}
Wax9::~Wax9()
{
// stop();
}
bool Wax9::setup(string portName, int historyLength)
{
bConnected = false;
mHistoryLength = historyLength;
mSamples = new SampleBuffer(mHistoryLength);
app::console() << "Available serial ports: " << std::endl;
for( auto device : Serial::getDevices()) app::console() << device.getName() << ", " << device.getPath() << std::endl;
try {
#ifdef CINDER_MSW
// finding serial devices is bugged in Windows
// see https://github.com/cinder/Cinder/issues/1064
Serial::Device device(portName);
#else
Serial::Device device = Serial::findDeviceByNameContains(portName);
#endif
mSerial = Serial::create(device, 115200);
app::console() << "Receiver sucessfully connected to " << device.getName() << std::endl;
}
catch(SerialExc e) {
app::console() << "Receiver unable to connect to " << portName << ": " << e.what() << std::endl;
bConnected = false;
return false;
}
AhrsInit(&mAhrs, 0, mOutputRate, 0.1f);
bConnected = true;
return true;
}
bool Wax9::start()
{
if (bConnected) {
// construct settings string - we're not using range, just leaving defaults
std::string settings = "\r\n";
settings += "RATE X 1 " + toString(mOutputRate) + "\r\n"; // output rate in Hz (table 7 in dev guide)
settings += "RATE A " + toString(bAccOn) + " " + toString(mAccRate) + "\r\n"; // accel rate in Hz (table 7)
settings += "RATE G " + toString(bGyrOn) + " " + toString(mGyrRate) + "\r\n"; // gyro rate in Hz (table 7)
settings += "RATE M " + toString(bMagOn) + " " + toString(mMagRate) + "\r\n"; // magnetometer rate Hz (table 7)
settings += "DATAMODE " + toString(mDataMode) + "\r\n"; // binary data mode (table 10)
app::console() << settings;
// send settings and wait for reply from device
mSerial->writeString(settings);
app::console() << mSerial->readStringUntil('\n', -1, 2.0) << std::endl;
// start streaming
std::string init = "\r\nSTREAM\r\n"; // start streaming
mSerial->writeString(init);
return true;
}
return false;
}
/* Close input and thread */
bool Wax9::stop()
{
// send termination string (this disconnects the device)
if (bConnected) {
// mSerial.writeString("\\r\nRESET\r\n");
// app::console() << "Resetting and disconnecting WAX9" << std::endl;
}
bConnected = false;
bEnabled = false;
return true;
}
/* -------------------------------------------------------------------------------------------------- */
#pragma mark public interface
/* -------------------------------------------------------------------------------------------------- */
int Wax9::update()
{
if (bConnected) {
mNewReadings = readPackets(mBuffer);
// If first run - not sure if this does anything
if (mNewReadings > 0 && getNumReadings() == 0) {
calculateOrientation(vec3(0), vec3(0), vec3(0), 0);
}
int numNewReadings = getNumNewReadings();
// make sure we're not disconnected
if (numNewReadings > 0)
mLastReadingTime = app::getElapsedSeconds();
else if (getNumReadings() > 0 && ((app::getElapsedSeconds() - mLastReadingTime) > mTimeout))
bConnected = false;
return numNewReadings;
}
return 0;
}
void Wax9::resetOrientation(quat q)
{
float quat[4] = {q.w, q.x, q.y, q.z};
AhrsReset(&mAhrs, quat);
}
/* -------------------------------------------------------------------------------------------------- */
#pragma mark input thread
/* -------------------------------------------------------------------------------------------------- */
int Wax9::readPackets(char* buffer)
{
int packetsRead = 0;
while(mSerial->getNumBytesAvailable() > 0)
{
// Read data
size_t bytesRead = lineread(buffer, BUFFER_SIZE);
if (bytesRead == (size_t) - 1)
{
bytesRead = slipread(buffer, BUFFER_SIZE);
}
if (bytesRead == 0) { return 0; }
// Get time now
unsigned long long now = ticksNow();
// If it appears to be a binary WAX9 packet...
if (bytesRead > 1 && buffer[0] == '9')
{
Wax9Packet *wax9Packet = parseWax9Packet(buffer, bytesRead, now);
if (wax9Packet != NULL)
{
if(bDebug) printWax9(wax9Packet);
// process packet and save it
mSamples->push_front(processPacket(wax9Packet)); //todo: check if we should store packet pointers in the buffer
packetsRead++;
}
}
}
// if (packetsRead > 0) app::console() << "packets read: " << packetsRead << std::endl;
return packetsRead;
}
Wax9Sample Wax9::processPacket(Wax9Packet *p)
{
Wax9Sample s;
s.timestamp = p->timestamp;
s.sampleNumber = p->sampleNumber;
s.acc = vec3(p->accel.x, p->accel.y, p->accel.z) / 4096.0f; // table 19 - in g
s.gyr = vec3(p->gyro.x, p->gyro.y, p->gyro.z) * toRadians(0.07f); // table 20 + convert deg/s to rad/s
s.mag = vec3(p->mag.x, p->mag.y, -p->mag.z) * 0.1f; // in μT
s.accLen = length(s.acc);
s.rotAHRS = calculateOrientation(s.acc, s.gyr - mGyroDelta , s.mag, s.timestamp);
s.rotOGL = AHRStoOpenGL(s.rotAHRS);
// the sensor metadata only comes in every once in a while
if (p->temperature != -1) {
mTemperature = (float)p->temperature * 0.1f;
if (bDebug) app::console() << "WAX9 - temperature: " << mTemperature << " celsius/n";
}
if (p->pressure != 0xfffffffful) {
mPressure = p->pressure;
if (bDebug)app::console() << "WAX9 - pressure: " << mPressure << " pascals/n";
}
if (p->battery != 0xffff){
mBattery = p->battery;
bBatteryLow = p->battery < 3500; // according to dev guide, battery dies under 3300 mV
if (bDebug)app::console() << "WAX9 - Battery: " << p->battery << " millivolts/n";
}
return s;
}
quat Wax9::calculateOrientation(const vec3 &acc, const vec3 &gyr, const vec3 &mag, uint32_t timestamp)
{
// set sample frequency for AHRS algorithm
// if (!mSamples->empty()) {
// // compare timestamp between previous sample and this one
// uint32_t prevTimestamp = mSamples->front().timestamp;
// uint32_t diff = timestamp - prevTimestamp;
// float diffSeconds = (float) diff / 65536.0f; // timestamps are in 1/65536 of a second
// mAhrs.sampleFreq = 1.0f / diffSeconds;
// }
// else mAhrs.sampleFreq = mOutputRate;
// Call AHRS algorithm update
// we're not using the accelerometer yet
float gyro[3] = {gyr.x, gyr.y, gyr.z};
float accel[3] = {acc.x, acc.y, acc.z};
AhrsUpdate(&mAhrs, gyro, accel, NULL);
return quat(mAhrs.q[0], mAhrs.q[1], mAhrs.q[2], mAhrs.q[3]);
}
/* -------------------------------------------------------------------------------------------------- */
#pragma mark packet parsing
/* -------------------------------------------------------------------------------------------------- */
#define SLIP_END 0xC0 /* End of packet indicator */
#define SLIP_ESC 0xDB /* Escape character, next character will be a substitution */
#define SLIP_ESC_END 0xDC /* Escaped substitution for the END data byte */
#define SLIP_ESC_ESC 0xDD /* Escaped substitution for the ESC data byte */
/* Read a line from the device */
size_t Wax9::lineread(void *inBuffer, size_t len)
{
unsigned char *p = (unsigned char *)inBuffer;
unsigned char c;
size_t bytesRead = 0;
if (inBuffer == NULL) { return 0; }
*p = '\0';
// while(!bCloseThread)
while(bEnabled)
{
c = '\0';
try{
c = mSerial->readByte();
}
catch(...) {
return bytesRead;
}
if (c == SLIP_END) { // A SLIP_END means the reader should switch to slip reading.
return (size_t)-1;
}
if (c == '\r' || c == '\n')
{
if (bytesRead) return bytesRead;
}
else
{
if (bytesRead < len - 1) {
p[bytesRead++] = (char)c;
p[bytesRead] = 0;
}
}
}
return 0;
}
/* Read a SLIP-encoded packet from the device */
size_t Wax9::slipread(void *inBuffer, size_t len)
{
unsigned char *p = (unsigned char *)inBuffer;
unsigned char c = '\0';
size_t bytesRead = 0;
if (inBuffer == NULL) return 0;
// while(!bCloseThread)
while(bEnabled) //not sure if this is going to give problems without threaded
{
c = '\0';
try{
c = mSerial->readByte();
}
catch(...) {
return bytesRead;
}
switch (c)
{
case SLIP_END:
if (bytesRead) return bytesRead;
break;
case SLIP_ESC:
c = '\0';
try{
c = mSerial->readByte();
}
catch(...) {
return bytesRead;
}
switch (c){
case SLIP_ESC_END:
c = SLIP_END;
break;
case SLIP_ESC_ESC:
c = SLIP_ESC;
break;
default:
fprintf(stderr, "<Unexpected escaped value: %02x>", c);
break;
}
/* ... fall through to default case with our replaced character ... */
default:
if (bytesRead < len) {
p[bytesRead++] = c;
}
break;
}
}
return 0;
}
Wax9Packet* Wax9::parseWax9Packet(const void *inputBuffer, size_t len, unsigned long long now)
{
const unsigned char *buffer = (const unsigned char *)inputBuffer;
static Wax9Packet wax9Packet;
if (buffer == NULL || len <= 0) { return 0; }
if (buffer[0] != '9')
{
fprintf(stderr, "WARNING: Unrecognized packet -- ignoring.\n");
}
else if (len >= 20)
{
wax9Packet.packetType = buffer[0];
wax9Packet.packetVersion = buffer[1];
wax9Packet.sampleNumber = buffer[2] | ((unsigned short)buffer[3] << 8);
wax9Packet.timestamp = buffer[4] | ((unsigned int)buffer[5] << 8) | ((unsigned int)buffer[6] << 16) | ((unsigned int)buffer[7] << 24);
wax9Packet.accel.x = (short)((unsigned short)(buffer[ 8] | (((unsigned short)buffer[ 9]) << 8)));
wax9Packet.accel.y = (short)((unsigned short)(buffer[10] | (((unsigned short)buffer[11]) << 8)));
wax9Packet.accel.z = (short)((unsigned short)(buffer[12] | (((unsigned short)buffer[13]) << 8)));
if (len >= 20)
{
wax9Packet.gyro.x = (short)((unsigned short)(buffer[14] | (((unsigned short)buffer[15]) << 8)));
wax9Packet.gyro.y = (short)((unsigned short)(buffer[16] | (((unsigned short)buffer[17]) << 8)));
wax9Packet.gyro.z = (short)((unsigned short)(buffer[18] | (((unsigned short)buffer[19]) << 8)));
}
else
{
wax9Packet.gyro.x = 0;
wax9Packet.gyro.y = 0;
wax9Packet.gyro.z = 0;
}
if (len >= 26)
{
wax9Packet.mag.x = (short)((unsigned short)(buffer[20] | (((unsigned short)buffer[21]) << 8)));
wax9Packet.mag.y = (short)((unsigned short)(buffer[22] | (((unsigned short)buffer[23]) << 8)));
wax9Packet.mag.z = (short)((unsigned short)(buffer[24] | (((unsigned short)buffer[25]) << 8)));
}
else
{
wax9Packet.mag.x = 0;
wax9Packet.mag.y = 0;
wax9Packet.mag.z = 0;
}
if (len >= 28)
{
wax9Packet.battery = (unsigned short)(buffer[26] | (((unsigned short)buffer[27]) << 8));
}
else
{
wax9Packet.battery = 0xffff;
}
if (len >= 30)
{
wax9Packet.temperature = (short)((unsigned short)(buffer[28] | (((unsigned short)buffer[29]) << 8)));
}
else
{
wax9Packet.temperature = 0xffff;
}
if (len >= 34)
{
wax9Packet.pressure = buffer[30] | ((unsigned int)buffer[31] << 8) | ((unsigned int)buffer[32] << 16) | ((unsigned int)buffer[33] << 24);
}
else
{
wax9Packet.pressure = 0xfffffffful;
}
return &wax9Packet;
}
else
{
fprintf(stderr, "WARNING: Unrecognized WAX9 packet -- ignoring.\n");
}
return NULL;
}
/* -------------------------------------------------------------------------------------------------- */
#pragma mark utils
/* -------------------------------------------------------------------------------------------------- */
void Wax9::printWax9(Wax9Packet *wax9Packet)
{
printf( "\nWAX9\ntimestring:\t%s\ntimestamp:\t%f\npacket num:\t%u\naccel\t[%f %f %f]\ngyro\t[%f %f %f]\nmagnet\t[%f %f %f]\n",
timestamp(wax9Packet->timestamp),
wax9Packet->timestamp / 65536.0,
wax9Packet->sampleNumber,
wax9Packet->accel.x / 4096.0f, wax9Packet->accel.y / 4096.0f, wax9Packet->accel.z / 4096.0f, // 'G' (9.81 m/s/s)
wax9Packet->gyro.x * 0.07f, wax9Packet->gyro.y * 0.07f, wax9Packet->gyro.z * 0.07f, // degrees/sec
wax9Packet->mag.x * 0.10f, wax9Packet->mag.y * 0.10f, wax9Packet->mag.z * 0.10f * -1 // uT (magnetic field ranges between 25-65 uT)
);
}
/* Returns the number of milliseconds since the epoch */
unsigned long long Wax9::ticksNow(void)
{
struct timeb tp;
ftime(&tp);
return (unsigned long long)tp.time * 1000 + tp.millitm;
}
/* Returns a date/time string for the specific number of milliseconds since the epoch */
const char* Wax9::timestamp(unsigned long long ticks)
{
static char output[] = "YYYY-MM-DD HH:MM:SS.fff";
output[0] = '\0';
struct tm *today;
struct timeb tp = {0};
tp.time = (time_t)(ticks / 1000);
tp.millitm = (unsigned short)(ticks % 1000);
tzset();
today = localtime(&(tp.time));
if (strlen(output) != 0) { strcat(output, ","); }
sprintf(output + strlen(output), "%04d-%02d-%02d %02d:%02d:%02d.%03d", 1900 + today->tm_year, today->tm_mon + 1, today->tm_mday, today->tm_hour, today->tm_min, today->tm_sec, tp.millitm);
return output;
}
// Gets the Euler angles in radians defined with the Aerospace sequence (psi, theta, phi).
// See Sebastian O.H. Madwick report "An efficient orientation filter for inertial
// and inertial/magnetic sensor arrays" Chapter 2 Quaternion representation
vec3 Wax9::QuaternionToEuler(const quat &q)
{
return vec3( (float)atan2(2 * q.x * q.y - 2 * q.w * q.z, 2 * q.w*q.w + 2 * q.x * q.x - 1), // psi
-(float)asin(2 * q.x * q.z + 2 * q.w * q.y), // theta
(float)atan2(2 * q.y * q.z - 2 * q.w * q.x, 2 * q.w * q.w + 2 * q.z * q.z - 1) ); // phi
}
// Conversion between coordinate systems
// order as in: http://www.varesano.net/blog/fabio/ahrs-sensor-fusion-orientation-filter-3d-graphical-rotating-cube
quat Wax9::AHRStoOpenGL(const quat &q)
{
vec3 eul = QuaternionToEuler(q);
mat4 sensorRotMat = glm::rotate(-eul.z, vec3(0, 0, 1)); // Z: phi (roll)
sensorRotMat *= glm::rotate(-eul.y, vec3(1, 0, 0)); // X: theta (pitch)
sensorRotMat *= glm::rotate(-eul.x, vec3(0, 1, 0)); // Y: psi (yaw)
return quat(sensorRotMat);
}
| 35.015038
| 191
| 0.528989
|
redpaperheart
|
5ca25b39293854bdcddc2d8d92c5550b052b0b1f
| 1,620
|
hpp
|
C++
|
ABC_Shadow_cpp/ABCShadow.hpp
|
quentinl-c/ABC_Shadow_cpp
|
d65c188703f98d419f006d29c7d8c39e2e1341a8
|
[
"MIT"
] | null | null | null |
ABC_Shadow_cpp/ABCShadow.hpp
|
quentinl-c/ABC_Shadow_cpp
|
d65c188703f98d419f006d29c7d8c39e2e1341a8
|
[
"MIT"
] | null | null | null |
ABC_Shadow_cpp/ABCShadow.hpp
|
quentinl-c/ABC_Shadow_cpp
|
d65c188703f98d419f006d29c7d8c39e2e1341a8
|
[
"MIT"
] | null | null | null |
//
// ABCShadow.hpp
// ABC_Shadow_cpp
//
// Created by Quentin on 13/01/2020.
// Copyright © 2020 Quentin. All rights reserved.
//
#ifndef ABCShadow_hpp
#define ABCShadow_hpp
#include <iostream>
#include <fstream>
#include "MCMCSim.hpp"
#include "PottsModel.hpp"
#include "RandomGen.hpp"
#include "Stats.hpp"
using std::endl;
using std::ofstream;
using std::cerr;
using std::exp;
using std::cout;
class ABCShadow {
private:
MCMCSim* mcmcSim;
PottsModel* model;
RandomGen* rGen;
const Stats yObs;
Stats theta0;
Stats delta;
vector<int> randomMask;
int iter, n, samplerIt, samplerBy, samplerBurnin;
double minBound, maxBound;
bool gibbsSampler;
vector<Stats> chain;
Stats computeShadowChain(const Stats &theta);
Stats sampleFromGibbs();
Stats sampleFromMH();
Stats getCandidate(const Stats &theta);
double computeDensityRatio(const Stats &oldTheta,
const Stats &candidateTheta,
const Stats &ySim);
public:
ABCShadow(MCMCSim* mcmcSim,
PottsModel* model,
RandomGen* rGen,
Stats yObs,
Stats theta0,
Stats delta,
vector<int> randomMask,
int iter,
int n,
int samplerIt,
int samplerBy=1,
int samplerBurnin=0,
int minBound=-100,
int maxBound=100,
bool gibbsSampler=true);
void runABCShadow();
void saveChain(ofstream &outputfile);
};
#endif /* ABCShadow_hpp */
| 22.191781
| 59
| 0.592593
|
quentinl-c
|
5caf519e61b79260de483b73f9707c12e7d10ca3
| 5,129
|
cpp
|
C++
|
sample/plural_test.cpp
|
mjukel/spiritless_po
|
3a7dc0155aeab627b10ffaf64101590b3cc9f2f3
|
[
"BSL-1.0"
] | null | null | null |
sample/plural_test.cpp
|
mjukel/spiritless_po
|
3a7dc0155aeab627b10ffaf64101590b3cc9f2f3
|
[
"BSL-1.0"
] | null | null | null |
sample/plural_test.cpp
|
mjukel/spiritless_po
|
3a7dc0155aeab627b10ffaf64101590b3cc9f2f3
|
[
"BSL-1.0"
] | null | null | null |
/* sample/plural_test.cpp
Copyright (c) 2019 OOTA, Masato
spiritless_po is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
spiritless_po 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.
*/
#include "spiritless_po/PluralParser.h"
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
using namespace std;
using namespace spiritless_po;
using namespace spiritless_po::PluralParser;
vector<string> test_table {
" n==1 || n%10==1 ? 0 : 1",
"(n != 0)",
"(n != 1)",
"(n > 1)",
"(n%10!=1 || n%100==11)",
"(n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3)",
"(n%10==1 && n%100!=11 ? 0 : n != 0 ? 1 : 2)",
"(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2)",
"(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2)",
"(n==0 ? 0 : n==1 ? 1 : 2)",
"(n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 ? 4 : 5)",
"(n==1 ? 0 : (n==0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2)",
"(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2)",
"(n==1 ? 0 : n==0 || ( n%100>1 && n%100<11) ? 1 : (n%100>10 && n%100<20 ) ? 2 : 3)",
"(n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3",
"(n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3",
"(n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3",
"(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2",
"(n==1) ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2",
"0",
"n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2",
"n==1 ? 0 : n==2 ? 1 : (n>2 && n<7) ? 2 :(n>6 && n<11) ? 3 : 4",
"n+3",
"n*3+4",
"n*n+4*n-1",
"!n ? 3 : n/3+8",
"!! !! ! !n ? 3 : n/3+8",
"n==0.0 ? 0 : 1",
};
int main()
{
for (auto &s : test_table) {
cout << s << endl;
auto it = s.cbegin();
try {
auto f = ParseExpression(it, s.end());
cout << "0 -> " << f(0) << endl;
cout << "1 -> " << f(1) << endl;
cout << "2 -> " << f(2) << endl;
cout << "3 -> " << f(3) << endl;
cout << "4 -> " << f(4) << endl;
cout << "5 -> " << f(5) << endl;
cout << "6 -> " << f(6) << endl;
cout << "7 -> " << f(7) << endl;
cout << "8 -> " << f(8) << endl;
cout << "9 -> " << f(9) << endl;
cout << "10 -> " << f(10) << endl;
cout << "11 -> " << f(11) << endl;
cout << "12 -> " << f(12) << endl;
cout << "13 -> " << f(13) << endl;
cout << "14 -> " << f(14) << endl;
cout << "15 -> " << f(15) << endl;
cout << "19 -> " << f(19) << endl;
cout << "20 -> " << f(20) << endl;
cout << "21 -> " << f(21) << endl;
cout << "22 -> " << f(22) << endl;
cout << "23 -> " << f(23) << endl;
cout << "24 -> " << f(24) << endl;
cout << "25 -> " << f(25) << endl;
cout << "100 -> " << f(100) << endl;
cout << "101 -> " << f(101) << endl;
cout << "102 -> " << f(102) << endl;
cout << "103 -> " << f(103) << endl;
cout << "104 -> " << f(104) << endl;
cout << "111 -> " << f(111) << endl;
cout << "113 -> " << f(113) << endl;
cout << "123 -> " << f(123) << endl;
} catch (ExpressionError &e) {
cerr << e.what() << endl;
auto it = e.Where();
if (it == s.end()) {
cerr << s << "][" << endl;
} else {
auto pos = std::distance(s.cbegin(), e.Where());
for (size_t ii = 0; ii < s.length(); ii++) {
if (static_cast<size_t>(pos) == ii) {
cerr << ']' << s[ii] << '[';
} else {
cerr << s[ii];
}
}
cerr << endl;
}
}
string np = "nplurals=1; plural=n;";
try {
auto r = Parse(np);
cout << r.first << ": " << r.second(1) << endl;
} catch (ExpressionError &e) {
cerr << e.what() << endl;
auto it = e.Where();
if (it == np.end()) {
cerr << s << "][" << endl;
} else {
auto pos = std::distance(np.cbegin(), e.Where());
for (size_t ii = 0; ii < np.length(); ii++) {
if (static_cast<size_t>(pos) == ii) {
cerr << ']' << np[ii] << '[';
} else {
cerr << np[ii];
}
}
cerr << endl;
}
}
}
return 0;
}
| 37.992593
| 89
| 0.371027
|
mjukel
|
5cb58b742662b16686efa7fc4f06e29cdf8c145a
| 758
|
hpp
|
C++
|
GaiaBehaviorTree/Decorators/If.hpp
|
GaiaCommittee/GaiaBehaviorTree
|
dee16450f340024e72e035888a4c1c8e38413795
|
[
"MIT"
] | null | null | null |
GaiaBehaviorTree/Decorators/If.hpp
|
GaiaCommittee/GaiaBehaviorTree
|
dee16450f340024e72e035888a4c1c8e38413795
|
[
"MIT"
] | null | null | null |
GaiaBehaviorTree/Decorators/If.hpp
|
GaiaCommittee/GaiaBehaviorTree
|
dee16450f340024e72e035888a4c1c8e38413795
|
[
"MIT"
] | null | null | null |
#pragma once
#include "ConditionalDecorator.hpp"
namespace Gaia::BehaviorTree::Decorators
{
/**
* @brief Behavior decorated by If will only be executed when condition of If returns Result::Success.
*/
class If : public ConditionalDecorator
{
REFLECT_TYPE(Gaia::BehaviorTree::Decorators, ConditionalDecorator)
protected:
/// Execute the first sub behavior if the condition behavior returns Result::Success.
Result OnExecute() override
{
if (GetConditionNode() && GetConditionNode()->Execute() == Result::Success &&
GetDecoratedNode())
{
return GetDecoratedNode()->Execute();
}
return Result::Failure;
}
};
}
| 30.32
| 106
| 0.613456
|
GaiaCommittee
|
5cb7812d5746169d432ce9c54fd2e3857b93e5b7
| 1,118
|
hpp
|
C++
|
matrix.hpp
|
a12n/rematrix
|
e539a5573a99665ba7b21e1c2114508060dcd163
|
[
"MIT"
] | 2
|
2022-01-15T16:27:05.000Z
|
2022-01-15T16:48:03.000Z
|
matrix.hpp
|
a12n/rematrix
|
e539a5573a99665ba7b21e1c2114508060dcd163
|
[
"MIT"
] | null | null | null |
matrix.hpp
|
a12n/rematrix
|
e539a5573a99665ba7b21e1c2114508060dcd163
|
[
"MIT"
] | null | null | null |
#ifndef REMATRIX_MATRIX_HPP
#define REMATRIX_MATRIX_HPP
#include <cmath>
#include "decl.hpp"
namespace rematrix {
using vec3 = array<float, 3>;
using vec4 = array<float, 4>;
using mat4 = array<vec4, 4>;
inline const mat4 identity{
{ { 1.0f, 0.0f, 0.0f, 0.0f },
{ 0.0f, 1.0f, 0.0f, 0.0f },
{ 0.0f, 0.0f, 1.0f, 0.0f },
{ 0.0f, 0.0f, 0.0f, 1.0f } }
};
constexpr float
radians(float degrees)
{
return degrees * M_PI / 180.0f;
}
constexpr mat4
translate(const vec3& v)
{
return {
{ { 1.0f, 0.0f, 0.0f, 0.0f},
{ 0.0f, 1.0f, 0.0f, 0.0f},
{ 0.0f, 0.0f, 1.0f, 0.0f},
{ v[0], v[1], v[2], 1.0f} }
};
}
inline mat4
perspective(float fovy, float aspect, float near, float far)
{
const auto tan_half_fovy{tanf(fovy / 2.0f)};
return {
{ {1.0f / (aspect * tan_half_fovy), 0.0f, 0.0f, 0.0f},
{0.0f, 1.0f / tan_half_fovy, 0.0f, 0.0f},
{0.0f, 0.0f, -(far + near) / (far - near), -1.0f},
{0.0f, 0.0f, -(2.0f * far * near) / (far - near), 1.0f} }
};
}
} // namespace rematrix
#endif // REMATRIX_MATRIX_HPP
| 21.09434
| 67
| 0.54025
|
a12n
|
5cbc9fc3706029aac642e2e5769aae34233a6368
| 395
|
hpp
|
C++
|
cpp/include/ITimer.hpp
|
skydiveuas/skylync
|
73db7fe4593e262a1fc1a7b61c18190275abe723
|
[
"MIT"
] | 1
|
2018-06-06T20:33:28.000Z
|
2018-06-06T20:33:28.000Z
|
cpp/include/ITimer.hpp
|
skydiveuas/skylync
|
73db7fe4593e262a1fc1a7b61c18190275abe723
|
[
"MIT"
] | null | null | null |
cpp/include/ITimer.hpp
|
skydiveuas/skylync
|
73db7fe4593e262a1fc1a7b61c18190275abe723
|
[
"MIT"
] | 1
|
2020-07-31T03:39:15.000Z
|
2020-07-31T03:39:15.000Z
|
#ifndef ITIMER_HPP
#define ITIMER_HPP
#include <functional>
namespace sl
{
class ITimer
{
public:
typedef std::function<void(void)> Task;
typedef size_t Milisec;
virtual ~ITimer();
virtual void callEvery(const Milisec interval, Task task) = 0;
virtual void callAfter(const Milisec timeout, Task task) = 0;
virtual void kill() = 0;
};
} // sl
#endif // ITIMER_HPP
| 15.192308
| 66
| 0.683544
|
skydiveuas
|
5cbe1b10a50be180d101cc9788d70f0c11e6e42a
| 4,446
|
cpp
|
C++
|
geopdf/src/ossimGeoPdfReaderFactory.cpp
|
dardok/ossim-plugins
|
3406ffed9fcab88fe4175b845381611ac4122c81
|
[
"MIT"
] | 12
|
2016-09-09T01:24:12.000Z
|
2022-01-09T21:45:58.000Z
|
geopdf/src/ossimGeoPdfReaderFactory.cpp
|
dardok/ossim-plugins
|
3406ffed9fcab88fe4175b845381611ac4122c81
|
[
"MIT"
] | 5
|
2016-02-04T16:10:40.000Z
|
2021-06-29T05:00:29.000Z
|
geopdf/src/ossimGeoPdfReaderFactory.cpp
|
dardok/ossim-plugins
|
3406ffed9fcab88fe4175b845381611ac4122c81
|
[
"MIT"
] | 20
|
2015-11-17T11:46:22.000Z
|
2021-11-12T19:23:54.000Z
|
//----------------------------------------------------------------------------
//
// License: See top level LICENSE.txt file
//
// Author: Mingjie Su
//
// Description: Factory for OSSIM GeoPdf reader using kakadu library.
//----------------------------------------------------------------------------
// $Id: ossimGeoPdfReaderFactory.cpp 20935 2012-05-18 14:19:30Z dburken $
#include "ossimGeoPdfReaderFactory.h"
#include <ossim/base/ossimKeywordlist.h>
#include <ossim/base/ossimRefPtr.h>
#include <ossim/base/ossimString.h>
#include <ossim/base/ossimTrace.h>
#include <ossim/imaging/ossimImageHandler.h>
#include "ossimGeoPdfReader.h"
static const ossimTrace traceDebug("ossimGeoPdfReaderFactory:debug");
class ossimImageHandler;
RTTI_DEF1(ossimGeoPdfReaderFactory,
"ossimGeoPdfReaderFactory",
ossimImageHandlerFactoryBase);
ossimGeoPdfReaderFactory* ossimGeoPdfReaderFactory::theInstance = 0;
ossimGeoPdfReaderFactory::~ossimGeoPdfReaderFactory()
{
theInstance = 0;
}
ossimGeoPdfReaderFactory* ossimGeoPdfReaderFactory::instance()
{
if(!theInstance)
{
theInstance = new ossimGeoPdfReaderFactory;
}
return theInstance;
}
ossimImageHandler* ossimGeoPdfReaderFactory::open(const ossimFilename& fileName,
bool openOverview)const
{
if(traceDebug())
{
ossimNotify(ossimNotifyLevel_DEBUG)
<< "ossimGeoPdfReaderFactory::open(filename) DEBUG: entered..."
<< "\ntrying ossimKakaduNitfReader"
<< std::endl;
}
ossimRefPtr<ossimImageHandler> reader = 0;
if ( hasExcludedExtension(fileName) == false )
{
reader = new ossimGeoPdfReader;
reader->setOpenOverviewFlag(openOverview);
if(reader->open(fileName) == false)
{
reader = 0;
}
}
if(traceDebug())
{
ossimNotify(ossimNotifyLevel_DEBUG)
<< "ossimGeoPdfReaderFactory::open(filename) DEBUG: leaving..."
<< std::endl;
}
return reader.release();
}
ossimImageHandler* ossimGeoPdfReaderFactory::open(const ossimKeywordlist& kwl,
const char* prefix)const
{
if(traceDebug())
{
ossimNotify(ossimNotifyLevel_DEBUG)
<< "ossimGeoPdfReaderFactory::open(kwl, prefix) DEBUG: entered..."
<< "Trying ossimKakaduNitfReader"
<< std::endl;
}
ossimRefPtr<ossimImageHandler> reader = new ossimGeoPdfReader;
if(reader->loadState(kwl, prefix) == false)
{
reader = 0;
}
if(traceDebug())
{
ossimNotify(ossimNotifyLevel_DEBUG)
<< "ossimGeoPdfReaderFactory::open(kwl, prefix) DEBUG: leaving..."
<< std::endl;
}
return reader.release();
}
ossimObject* ossimGeoPdfReaderFactory::createObject(
const ossimString& typeName)const
{
ossimRefPtr<ossimObject> result = 0;
if(typeName == "ossimGeoPdfReader")
{
result = new ossimGeoPdfReader;
}
return result.release();
}
ossimObject* ossimGeoPdfReaderFactory::createObject(
const ossimKeywordlist& kwl,
const char* prefix)const
{
return this->open(kwl, prefix);
}
void ossimGeoPdfReaderFactory::getTypeNameList(
std::vector<ossimString>& typeList)const
{
typeList.push_back(ossimString("ossimGeoPdfReader"));
}
void ossimGeoPdfReaderFactory::getSupportedExtensions(
ossimImageHandlerFactoryBase::UniqueStringList& extensionList)const
{
extensionList.push_back(ossimString("pdf"));
}
bool ossimGeoPdfReaderFactory::hasExcludedExtension(
const ossimFilename& file) const
{
bool result = true;
ossimString ext = file.ext().downcase();
if (ext == "pdf") //only include the file with .pdf extension and exclude any other files
{
result = false;
}
return result;
}
void ossimGeoPdfReaderFactory::getImageHandlersBySuffix(ossimImageHandlerFactoryBase::ImageHandlerList& result,
const ossimString& ext)const
{
ossimString testExt = ext.downcase();
if(ext == "pdf")
{
result.push_back(new ossimGeoPdfReader);
}
}
void ossimGeoPdfReaderFactory::getImageHandlersByMimeType(ossimImageHandlerFactoryBase::ImageHandlerList& result,
const ossimString& mimeType)const
{
ossimString testExt = mimeType.downcase();
if(testExt == "image/pdf")
{
result.push_back(new ossimGeoPdfReader);
}
}
ossimGeoPdfReaderFactory::ossimGeoPdfReaderFactory(){}
ossimGeoPdfReaderFactory::ossimGeoPdfReaderFactory(const ossimGeoPdfReaderFactory&){}
void ossimGeoPdfReaderFactory::operator=(const ossimGeoPdfReaderFactory&){}
| 25.699422
| 113
| 0.694107
|
dardok
|
5cbf1d44160834b551076d95d8e5ed5a9e9cad94
| 407
|
cpp
|
C++
|
apronin_task_3/func_sim/main.cpp
|
MIPT-ILab/mipt-mips-old-branches
|
a4e17025999b15d423601cf38a84234c5c037b33
|
[
"MIT"
] | 1
|
2018-03-04T21:28:20.000Z
|
2018-03-04T21:28:20.000Z
|
apronin_task_3/func_sim/main.cpp
|
MIPT-ILab/mipt-mips-old-branches
|
a4e17025999b15d423601cf38a84234c5c037b33
|
[
"MIT"
] | null | null | null |
apronin_task_3/func_sim/main.cpp
|
MIPT-ILab/mipt-mips-old-branches
|
a4e17025999b15d423601cf38a84234c5c037b33
|
[
"MIT"
] | null | null | null |
#include <func_sim.h>
#include <func_instr.h>
#include <elf_parser.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
int main( int argc, char** argv) {
if ( argc != 3)
{
cout << "WRONG NUMBER OF ARGUMENT" << endl;
return -1;
}
else
{
MIPS* mips = new MIPS;
mips->run( argv[ 1], atoi( argv[ 2]));
}
return 0;
}
| 18.5
| 52
| 0.515971
|
MIPT-ILab
|
5cbf46b5c4c00e632bf7fe0c30d2ea9bc05e0e7f
| 14,814
|
cpp
|
C++
|
src/hair/main.cpp
|
nyorain/tokonoma
|
b3a4264ef4f9f40487c2f3280812bf7513b914bb
|
[
"MIT"
] | 23
|
2019-07-11T14:47:39.000Z
|
2021-12-24T09:56:24.000Z
|
src/hair/main.cpp
|
nyorain/tokonoma
|
b3a4264ef4f9f40487c2f3280812bf7513b914bb
|
[
"MIT"
] | null | null | null |
src/hair/main.cpp
|
nyorain/tokonoma
|
b3a4264ef4f9f40487c2f3280812bf7513b914bb
|
[
"MIT"
] | 4
|
2021-04-06T18:20:43.000Z
|
2022-01-15T09:20:45.000Z
|
#include <tkn/singlePassApp.hpp>
#include <tkn/bits.hpp>
#include <tkn/render.hpp>
#include <tkn/types.hpp>
#include <tkn/geometry.hpp>
#include <argagg.hpp>
#include <vpp/trackedDescriptor.hpp>
#include <vpp/pipeline.hpp>
#include <vpp/queue.hpp>
#include <vpp/submit.hpp>
#include <vpp/commandAllocator.hpp>
#include <vpp/sharedBuffer.hpp>
#include <vpp/bufferOps.hpp>
#include <vpp/vk.hpp>
#include <dlg/dlg.hpp>
#include <nytl/math.hpp>
#include <shaders/tkn.simple2.vert.h>
#include <shaders/tkn.color.frag.h>
class HairApp : public tkn::SinglePassApp {
public:
struct Node {
nytl::Vec2f pos;
nytl::Vec2f vel;
nytl::Vec2f normal;
float width;
float mass;
};
static constexpr auto nodeCount = 16u;
static constexpr auto ks1 = 20.f;
static constexpr auto ks2 = 15.f;
static constexpr auto ks3 = 10.f;
static constexpr auto kd1 = 0.1f;
static constexpr auto kd2 = 0.1f;
static constexpr auto kd3 = 0.1f;
static constexpr auto kdg = 50.f; // general dampening per second
static constexpr auto segLength = 0.5f / nodeCount;
using Base = tkn::SinglePassApp;
public:
bool init(nytl::Span<const char*> args) override {
if(!Base::init(args)) {
return false;
}
// init logic
auto pos = nytl::Vec2f{0.f, -0.5f};
auto width = 0.1f;
auto widthStep = 0.9 * width / (nodeCount);
for(auto i = 0u; i < nodeCount; ++i) {
auto& node = nodes_.emplace_back();
node.pos = pos;
node.vel = {0.f, 0.f};
node.width = width;
node.mass = 1.f * width;
pos.y += segLength;
width -= widthStep;
// width /= 1.3;
}
nodes_[0].width *= 1.5f;
nodes_[0].mass *= 3.f;
// init gfx
auto& dev = vkDevice();
pipeLayout_ = {dev, {}, {}};
vpp::ShaderModule vertShader{dev, tkn_simple2_vert_data};
vpp::ShaderModule fragShader{dev, tkn_color_frag_data};
vpp::GraphicsPipelineInfo gpi {renderPass(), pipeLayout_, {{{
{vertShader, vk::ShaderStageBits::vertex},
{fragShader, vk::ShaderStageBits::fragment},
}}}, 0, samples()};
vk::VertexInputAttributeDescription attribs[1];
attribs[0].format = vk::Format::r32g32Sfloat;
vk::VertexInputBindingDescription bufs[1];
bufs[0].inputRate = vk::VertexInputRate::vertex;
bufs[0].stride = sizeof(nytl::Vec2f);
gpi.vertex.pVertexAttributeDescriptions = attribs;
gpi.vertex.vertexAttributeDescriptionCount = 1;
gpi.vertex.pVertexBindingDescriptions = bufs;
gpi.vertex.vertexBindingDescriptionCount = 1;
gpi.assembly.topology = vk::PrimitiveTopology::lineStrip;
gpi.rasterization.polygonMode = vk::PolygonMode::line;
gpi.depthStencil.depthTestEnable = false;
gpi.depthStencil.depthWriteEnable = false;
pipe_ = {dev, gpi.info()};
// vertex buffer
// filled in every frame, see updateDevice
vertices_ = {dev.bufferAllocator(), sizeof(nytl::Vec2f) * nodes_.size(),
vk::BufferUsageBits::vertexBuffer, dev.hostMemoryTypes()};
return true;
}
nytl::Vec2f normalized(nytl::Vec2i winPos) {
return nytl::Vec2f{-1.f, -1.f} + 2.f *
nytl::vec::cw::divide(winPos, nytl::Vec2f(windowSize()));
}
void mouseMove(const swa_mouse_move_event& ev) override {
Base::mouseMove(ev);
mpos_ = normalized({ev.x, ev.y});
}
void render(vk::CommandBuffer cb) override {
vk::cmdBindPipeline(cb, vk::PipelineBindPoint::graphics, pipe_);
vk::cmdBindVertexBuffers(cb, 0, {{vertices_.buffer().vkHandle()}},
{{vertices_.offset()}});
vk::cmdDraw(cb, nodes_.size(), 1, 0, 0);
}
bool mouseButton(const swa_mouse_button_event& ev) override {
if(Base::mouseButton(ev)) {
return true;
}
if(ev.button == swa_mouse_button_left) {
mouseDown_ = ev.pressed;
return true;
}
return false;
}
float distance(nytl::Vec2f point, tkn::Segment2f seg) {
nytl::Vec2f ab = seg.b - seg.b;
nytl::Vec2f ap = point - seg.a;
float fac = dot(ap, ab) / dot(ab, ab);
nytl::Vec2f clamped = seg.a + std::clamp(fac, 0.f, 1.f) * ab;
return length(point - clamped);
}
void update(double dt) override {
Base::update(dt);
auto force = [](auto& node1, auto& node2, float ks, float kd, float l) {
auto diff = node2.pos - node1.pos;
auto vdiff = node2.vel - node1.vel;
auto ld = length(diff);
diff *= 1 / ld;
return (ks * (ld - l) + kd * dot(vdiff, diff)) * diff;
};
auto muscleForce = [&](const auto& node1, const auto& node2) {
auto nl = node1;
auto nr = node1;
nl.pos += node1.width * node1.normal;
nr.pos -= node1.width * node1.normal;
auto ksa = 0.f;
auto ksb = 0.f;
// auto ll = std::sqrt(segLength * segLength + node1.width * node1.width);
// auto lr = ll;
auto ll = nytl::length(nl.pos - node2.pos);
auto lr = nytl::length(nr.pos - node2.pos);
// auto strength = 10.f * std::sqrt(segLength);
auto strength = 10.f;
// auto width = std::sqrt(node1.width); // node.width or 1?
// auto width = std::pow(node1.width, 2.0); // node.width or 1?
auto width = node1.width; // node.width or 1?
// auto width = 1.f;
if(swa_display_key_pressed(swaDisplay(), swa_key_k1)) {
// ll *= std::pow(0.1, node.width);
// lr /= std::pow(0.1, node.width);
ll *= 0.0;
lr *= 2.0;
ksa = strength * width;
ksb = strength * width;
}
if(swa_display_key_pressed(swaDisplay(), swa_key_k2)) {
// lr *= std::pow(0.1, node.width);
// ll /= std::pow(0.1, node.width);
lr *= 0.0;
ll *= 2.0;
ksb = strength * width;
ksa = strength * width;
}
return force(nl, node2, ksa, 0.f, ll) +
force(nr, node2, ksb, 0.f, lr);
};
// compute normal for all nodes
for(auto i = 0u; i < nodes_.size(); ++i) {
auto& node = nodes_[i];
// NOTE: not sure about tangent calculation/interpolation
// normalize segments before addition or not?
nytl::Vec2f tangent {0.f, 0.f};
if(i > 0) {
// tangent += 0.5 * nytl::normalized(nodes_[i].pos - nodes_[i - 1].pos);
tangent += 0.5 * (nodes_[i].pos - nodes_[i - 1].pos);
}
if(i < nodes_.size() - 1) {
// tangent += 0.5 * nytl::normalized(nodes_[i + 1].pos - nodes_[i].pos);
tangent += 0.5 * (nodes_[i + 1].pos - nodes_[i].pos);
}
// node.normal = tkn::rhs::lnormal(tangent);
node.normal = tkn::rhs::lnormal(nytl::normalized(tangent));
}
auto nextNodes = nodes_;
for(auto i = 0u; i < nodes_.size(); ++i) {
auto& node = nodes_[i];
nytl::Vec2f f{0.f, 0.f};
if(i > 0) {
f += force(node, nodes_[i - 1], ks1, kd1, segLength);
if(i > 1) {
f += force(node, nodes_[i - 2], ks2, kd2, 2 * segLength);
if(i > 2) {
f += force(node, nodes_[i - 3], ks3, kd3, 3 * segLength);
}
// if(i > 3) f += force(node, nodes_[i - 4], ks3, kd3, 4 * segLength);
// if(i > 4) f += force(node, nodes_[i - 5], ks3, kd3, 5 * segLength);
// if(i > 5) f += force(node, nodes_[i - 6], ks3, kd3, 6 * segLength);
// if(i > 6) f += force(node, nodes_[i - 7], ks3, kd3, 7 * segLength);
// if(i > 7) f += force(node, nodes_[i - 8], ks3, kd3, 8 * segLength);
}
}
if(i < nodes_.size() - 1) {
f += force(node, nodes_[i + 1], ks1, kd1, segLength);
if(i < nodes_.size() - 2) {
f += force(node, nodes_[i + 2], ks2, kd2, 2 * segLength);
if(i < nodes_.size() - 3) {
f += force(node, nodes_[i + 3], ks3, kd3, 3 * segLength);
}
// if(i < nodes_.size() - 4) f += force(node, nodes_[i + 4], ks3, kd3, 4 * segLength);
// if(i < nodes_.size() - 5) f += force(node, nodes_[i + 5], ks3, kd3, 5 * segLength);
// if(i < nodes_.size() - 6) f += force(node, nodes_[i + 6], ks3, kd3, 6 * segLength);
// if(i < nodes_.size() - 7) f += force(node, nodes_[i + 7], ks3, kd3, 7 * segLength);
// if(i < nodes_.size() - 8) f += force(node, nodes_[i + 8], ks3, kd3, 8 * segLength);
}
}
/*
auto nl = node;
auto nr = node;
nl.pos += node.width * node.normal;
nr.pos -= node.width * node.normal;
auto ksa = 0.f;
auto ksb = 0.f;
auto ll = std::sqrt(segLength * segLength + node.width * node.width);
auto lr = ll;
auto strength = 30.f * segLength;
// auto width = std::sqrt(node.width); // node.width or 1?
auto width = 1.f;
if(kc->pressed(ny::Keycode::k1)) {
// ll *= std::pow(0.1, node.width);
// lr /= std::pow(0.1, node.width);
ll *= 0.5;
lr *= 1.5;
ksa = strength * width;
ksb = strength * width;
}
if(kc->pressed(ny::Keycode::k2)) {
// lr *= std::pow(0.1, node.width);
// ll /= std::pow(0.1, node.width);
lr *= 0.5;
ll *= 1.5;
ksb = strength * width;
ksa = strength * width;
}
*/
if(i > 0) {
// auto nnl = nodes_[i - 1];
// auto nnr = nodes_[i - 1];
// nnl.pos += nnl.width * nnl.normal;
// nnr.pos -= nnl.width * nnr.normal;
// f += force(nl, nodes_[i-1], ksa, 0.f, ll);
// f += force(nr, nodes_[i-1], ksb, 0.f, lr);
f += muscleForce(node, nodes_[i - 1]);
if(i > 1) {
// f += force(nl, nodes_[i - 2], 0.5 * ksa, 0.f, 2 * ll);
// f += force(nr, nodes_[i - 2], 0.5 * ksb, 0.f, 2 * lr);
// f += 0.5 * muscleForce(node, nodes_[i - 2]);
if(i > 2) {
// f += force(nl, nodes_[i - 3], 0.3 * ksa, 0.f, 3 * ll);
// f += force(nr, nodes_[i - 3], 0.3 * ksb, 0.f, 3 * lr);
// f += 0.2 * muscleForce(node, nodes_[i - 3]);
}
}
}
if(i < nodes_.size() - 1) {
// auto nnl = nodes_[i + 1];
// auto nnr = nodes_[i + 1];
// nnl.pos += nnl.width * nnl.normal;
// nnr.pos -= nnl.width * nnr.normal;
// f += force(nl, nodes_[i+1], ksa, 0.f, ll);
// f += force(nr, nodes_[i+1], ksb, 0.f, lr);
f -= muscleForce(nodes_[i + 1], node);
if(i < nodes_.size() - 2) {
// f += force(nl, nodes_[i + 2], 0.5 * ksa, 0.f, 2 * ll);
// f += force(nr, nodes_[i + 2], 0.5 * ksb, 0.f, 2 * lr);
// f -= 0.5 * muscleForce(nodes_[i + 2], node);
if(i < nodes_.size() - 3) {
// f += force(nl, nodes_[i + 3], 0.3 * ksa, 0.f, 3 * ll);
// f += force(nr, nodes_[i + 3], 0.3 * ksb, 0.f, 3 * lr);
// f -= 0.2 * muscleForce(nodes_[i + 3], node);
}
}
}
// f -= (1 - std::pow(kdg, dt)) * node.vel;
// f -= kdg * node.vel;
// auto tangent = tkn::rhs::lnormal(node.normal);
// TODO: better special case for first AND last
// does it depend on velocity squared?
if(i == 0) {
auto tangent = tkn::rhs::lnormal(node.normal);
auto d = dot(node.vel, tangent);
f -= 1.0 * kdg * node.width * d * std::abs(d) * tangent;
// f -= kdg * (node.vel);
// f -= kdg * (10 * node.mass * node.vel);
}
// f -= kdg * dot(10 * node.mass * node.vel, node.normal) * node.normal;
// f -= kdg * dot(node.vel, node.normal) * node.normal;
auto d = dot(node.vel, node.normal);
f -= kdg * segLength * d * std::abs(d) * node.normal;
// auto a = (1 / (mass * node.width)) * f;
auto a = (1 / (node.mass)) * f;
// verlet-like integration
auto& next = nextNodes[i];
next.pos += dt * next.vel + 0.5 * dt * dt * a;
next.vel += 0.5 * dt * a;
// next.pos += dt * next.vel;
// next.vel += dt * a;
// check for intersection
/*
for(auto j = 1u; j < i; ++j) {
tkn::Segment2f line = {nextNodes[i - 1].pos, nextNodes[i].pos};
tkn::Segment2f a = {nextNodes[j - 1].pos, nextNodes[j].pos};
auto is = tkn::intersection(a, line);
if(is.intersect && (
(is.facA < 0.95 && is.facA > 0.05) ||
(is.facB < 0.95 && is.facB > 0.05))) {
// nextNodes[i].pos = is.point;
nextNodes[i].vel = {0.f, 0.f};
// TODO: use signedness! velocity that resolves
// intersection shouldn't be erased
// auto normal = tkn::rhs::lnormal(nytl::normalized(a.b - a.a));
// nextNodes[i].vel -= dot(nodes_[i].vel, normal) * normal;
break;
}
}
*/
// instead of intersection: use repulsion forces
for(auto j = 1u; j < i; ++j) {
// auto& other = nextNodes[j];
// auto diff = next.pos - other.pos;
tkn::Segment2f seg {nextNodes[j-1].pos, nextNodes[j].pos};
auto dist = distance(next.pos, seg);
if(dist < 0.02) {
nytl::Vec2f dir = nytl::normalized(next.pos - seg.a + next.pos - seg.b);
if(dist < 0.01) {
// auto dir = nytl::normalized(diff);
next.vel -= std::max(dot(next.vel, -dir), 0.f) * -dir;
// other.vel -= std::max(dot(other.vel, dir), 0.f) * dir;
// nextNodes[j-1].vel -= std::max(dot(nextNodes[j-1].vel, dir), 0.f) * dir;
// nextNodes[j].vel -= std::max(dot(nextNodes[j].vel, dir), 0.f) * dir;
}
// auto force = dt * nytl::normalized(diff);
auto force = dt * dir;
next.vel += force;
// nextNodes[j-1].vel -= force;
// nextNodes[j].vel -= force;
}
}
}
// "muscles"
// auto kc = appContext().keyboardContext();
// if(kc->pressed(ny::Keycode::k1)) {
// auto& a = nextNodes.front();
// auto& b = nextNodes.back();
// auto f = force(a, b, 0.01, 0.0, 0.0 * nodes_.size() * segLength);
// auto acc = (1 / mass) * f;
// a.vel += acc;
// b.vel -= acc;
// }
// "follow mouse"
if(mouseDown_) {
nextNodes[0].pos = mpos_;
nextNodes[0].vel = {0.f, 0.f};
}
/*
// TODO: iterative, also consider real geometric intersections
// and handle them somehow
for(auto i = 0u; i < nextNodes.size(); ++i) {
// for(auto j = 0u; j < nextNodes.size(); ++j) {
for(auto j = 0u; j + 1 < i; ++j) {
// if(i == j || j == 0) {
// continue;
// }
auto& next = nextNodes[i];
auto& other = nextNodes[j];
auto diff = next.pos - other.pos;
auto dist = length(diff);
// tkn::Segment2f seg {nextNodes[j-1].pos, nextNodes[j].pos};
// auto dist = distance(next.pos, seg);
if(dist < 0.02) {
// nytl::Vec2f dir = nytl::normalized(next.pos - seg.a + next.pos - seg.b);
if(dist < 0.01) {
auto dir = nytl::normalized(diff);
next.vel -= std::max(dot(next.vel, -dir), 0.f) * -dir;
other.vel -= std::max(dot(other.vel, dir), 0.f) * dir;
// nextNodes[j-1].vel -= std::max(dot(nextNodes[j-1].vel, dir), 0.f) * dir;
// nextNodes[j].vel -= std::max(dot(nextNodes[j].vel, dir), 0.f) * dir;
}
auto force = dt * nytl::normalized(diff);
// auto force = dt * dir;
next.vel += force;
other.vel -= force;
// nextNodes[j-1].vel -= force;
// nextNodes[j].vel -= force;
}
}
}
*/
if(!mouseDown_) {
// nextNodes[0].vel = {0.f, 0.f};
}
nodes_ = nextNodes;
Base::scheduleRedraw();
}
void updateDevice() override {
auto map = vertices_.memoryMap();
auto span = map.span();
for(auto& node : nodes_) {
tkn::write(span, node.pos);
}
map.flush();
}
const char* name() const override { return "hair"; }
protected:
vpp::PipelineLayout pipeLayout_;
vpp::Pipeline pipe_;
vpp::SubBuffer vertices_;
std::vector<Node> nodes_;
nytl::Vec2f mpos_;
bool mouseDown_ {false};
};
int main(int argc, const char** argv) {
return tkn::appMain<HairApp>(argc, argv);
}
| 30.109756
| 91
| 0.570609
|
nyorain
|
5cc1435e8d4257af0b823a1f2c22ec1e599a417f
| 2,850
|
cpp
|
C++
|
samples/RapaPololuMaestroViewer/Main.cpp
|
jbitoniau/RapaPololuMaestro
|
d30b0af2108486ddaa9f8ebd4d2c4f48ff821f2b
|
[
"MIT"
] | 14
|
2015-12-29T09:42:55.000Z
|
2021-04-06T07:27:22.000Z
|
samples/RapaPololuMaestroViewer/Main.cpp
|
jbitoniau/RapaPololuMaestro
|
d30b0af2108486ddaa9f8ebd4d2c4f48ff821f2b
|
[
"MIT"
] | 1
|
2016-01-14T10:54:11.000Z
|
2016-01-14T13:12:45.000Z
|
samples/RapaPololuMaestroViewer/Main.cpp
|
jbitoniau/RapaPololuMaestro
|
d30b0af2108486ddaa9f8ebd4d2c4f48ff821f2b
|
[
"MIT"
] | 10
|
2015-10-06T10:16:44.000Z
|
2022-03-14T16:22:56.000Z
|
/*
The MIT License (MIT) (http://opensource.org/licenses/MIT)
Copyright (c) 2015 Jacques Menuet
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 <iostream>
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning ( disable : 4127 )
#pragma warning ( disable : 4231 )
#pragma warning ( disable : 4251 )
#pragma warning ( disable : 4800 )
#endif
#include <QApplication>
#ifdef _MSC_VER
#pragma warning( pop )
#endif
#include "RPMSerialInterface.h"
#include "RPMQSerialInterfaceWidget.h"
int main( int argc, char** argv )
{
QApplication app( argc, argv );
std::string portName;
#ifdef _WIN32
portName = "COM4";
#else
portName = "/dev/ttyACM0";
#endif
if ( argc>=2 )
portName = argv[1];
unsigned char numChannels = 6;
if ( argc>=3 )
numChannels = static_cast<unsigned char>( atoi( argv[2] ) );
std::cout << "Opening Pololu Maestro on serial interface \"" << portName << "\"..." << std::endl;
std::string errorMessage;
RPM::SerialInterface* serialInterface = RPM::SerialInterface::createSerialInterface(portName, 9600, &errorMessage );
if ( !serialInterface )
std::cerr << "Error: " << errorMessage << std::endl;
std::cout << "Starting widget with " << static_cast<int>(numChannels) << " channels..." << std::endl;
RPM::QSerialInterfaceWidget* serialInterfaceWidget = new RPM::QSerialInterfaceWidget(NULL, serialInterface, numChannels);
serialInterfaceWidget->setWindowTitle( QString("Pololu Maestro - ") + QString(portName.c_str()) );
serialInterfaceWidget->resize(180, 150);
serialInterfaceWidget->show();
if ( !serialInterface )
serialInterfaceWidget->getStatusBar()->showMessage( errorMessage.c_str() );
int ret = app.exec();
delete serialInterfaceWidget;
serialInterfaceWidget = NULL;
delete serialInterface;
serialInterface = NULL;
return ret;
}
| 35.185185
| 122
| 0.729474
|
jbitoniau
|
5cc4cd6d682eeb2569822a86c0c859e1d5fd51ce
| 564
|
cpp
|
C++
|
Chapter 4/4.35 factorial (B)/4.35 factorial (B)/main.cpp
|
MarvelousAudio/CPlusPlus-How-to-program-tenth-edition
|
a667b080938cf964909d79b272f0d863adc300e0
|
[
"MIT"
] | null | null | null |
Chapter 4/4.35 factorial (B)/4.35 factorial (B)/main.cpp
|
MarvelousAudio/CPlusPlus-How-to-program-tenth-edition
|
a667b080938cf964909d79b272f0d863adc300e0
|
[
"MIT"
] | null | null | null |
Chapter 4/4.35 factorial (B)/4.35 factorial (B)/main.cpp
|
MarvelousAudio/CPlusPlus-How-to-program-tenth-edition
|
a667b080938cf964909d79b272f0d863adc300e0
|
[
"MIT"
] | null | null | null |
//
// main.cpp
// 4.35 factorial (B)
//
// Created by ben haywood on 7/1/20.
// Copyright © 2020 ben haywood. All rights reserved.
//
#include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
// insert code here...
double e = 2.0;
int input;
cout << "Enter a number to calculat how accurate const e will be and the press ETNER:" << endl;
cin >> input;
for (int i = 1; i <= input; ++i)
{
e += 1.0 / (i * (i + 1.0));
}
cout << "e: " << e << endl;
return 0;
}
| 17.090909
| 99
| 0.515957
|
MarvelousAudio
|
5ccd120511d39f1e310e1c62b985a731ec536030
| 2,997
|
cpp
|
C++
|
graph-source-code/508-D/9606367.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
graph-source-code/508-D/9606367.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
graph-source-code/508-D/9606367.cpp
|
AmrARaouf/algorithm-detection
|
59f3028d2298804870b32729415d71eec6116557
|
[
"MIT"
] | null | null | null |
//Language: MS C++
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
using namespace std;
int const N = 100000;
int n, degIn[N], degOut[N], rnd;
string s;
vector<int> e[N], ans;
vector<char> out;
int get(char c)
{
if(c >= '0' && c <= '9')
return c - '0';
if(c >= 'a' && c <= 'z')
return c - 'a' + 10;
return c - 'A' + 36;
}
void addEdges(string s)
{
int from, to;
from = get(s[0])*100 + get(s[1]);
to = get(s[1])*100 + get(s[2]);
e[from].push_back(to);
rnd = from;
++degIn[from];
++degOut[to];
}
void bad()
{
cout << "NO";
exit(0);
}
void dfs(int u)
{
while(e[u].size())
{
int to = e[u].back();
e[u].pop_back();
dfs(to);
}
ans.push_back(u);
}
char getChar(int num)
{
if(num < 10)
return (char)(num + '0');
if(num < 36)
return (char)(num - 10 + 'a');
return (char)(num - 36 + 'A');
}
int main()
{
#ifdef _DEBUG
freopen("in.in","r",stdin);
#endif
scanf("%d",&n);
for(int i=0;i<n;++i)
{
cin >> s;
addEdges(s);
}
int start = -1;
int end = -1;
for(int i=0;i<N;++i)
{
if(degIn[i] > degOut[i])
{
if(start != -1 || degIn[i] -1 > degOut[i])
{
bad();
}
start = i;
}
if(degOut[i] > degIn[i] || degOut[i] - 1 > degIn[i])
{
if(end != -1)
{
bad();
}
end = i;
}
}
if(end == -1 && start != -1 || start == -1 && end != -1)
bad();
if(end == -1 && start == -1)
{
dfs(rnd);
reverse(ans.begin(), ans.end());
out.push_back(getChar(rnd/100));
out.push_back(getChar(rnd%100));
for(int i=1;i<ans.size();++i)
{
out.push_back(getChar(ans[i]%100));
}
if(out.size() != n+2)
bad();
cout << "YES" << endl;
for(int i=0;i<out.size();++i)
{
printf("%c",out[i]);
}
return 0;
}
else
{
e[end].push_back(start);
dfs(end);
}
int delEdge;
reverse(ans.begin(), ans.end());
for(int i=1;i<ans.size();++i)
{
if(ans[i-1] == end && ans[i] == start)
{
delEdge = i;
break;
}
}
ans.pop_back();// ???
out.push_back(getChar(start/100));
out.push_back(getChar(start%100));
for(int i=delEdge+1;i<ans.size();++i)
{
out.push_back(getChar(ans[i]%100));
}
for(int i=0;i<delEdge;++i)
{
out.push_back(getChar(ans[i]%100));
}
if(out.size() != n+2)
bad();
cout << "YES" << endl;
for(int i=0;i<out.size();++i)
{
printf("%c",out[i]);
}
return 0;
}
| 19.089172
| 61
| 0.397064
|
AmrARaouf
|
5cd29e22eaf0d3b3e415ca91ff06f6c984adacc8
| 2,817
|
cpp
|
C++
|
src/hydra.cpp
|
pascscha/hydra
|
5c301ec9a7a91935f90497558326333afa7b179c
|
[
"BSD-3-Clause"
] | null | null | null |
src/hydra.cpp
|
pascscha/hydra
|
5c301ec9a7a91935f90497558326333afa7b179c
|
[
"BSD-3-Clause"
] | null | null | null |
src/hydra.cpp
|
pascscha/hydra
|
5c301ec9a7a91935f90497558326333afa7b179c
|
[
"BSD-3-Clause"
] | null | null | null |
#include <cstdio>
#include <cstdlib>
#include <exception>
#include <stdexcept>
#include "constants.h"
#include "common.h"
#include "formula.h"
#include "parser.h"
#include "lexer.h"
#include "util.h"
#include "visitors.h"
#include "monitor.h"
#include "trie.h"
Formula *getAST(const char *formula)
{
Formula *fmla;
yyscan_t scanner;
YY_BUFFER_STATE state;
if (yylex_init(&scanner)) return NULL;
state = yy_scan_string(formula, scanner);
if (yyparse(&fmla, scanner)) return NULL;
yy_delete_buffer(state, scanner);
yylex_destroy(scanner);
return fmla;
}
void printUsage()
{
fprintf(stderr, "hydra MDL LOG [-pure_mdl] [-grep]\n");
exit(EXIT_FAILURE);
}
void printFmla(Formula *fmla)
{
printf("Monitoring ");
PrintHydraFormulaVisitor f(stdout);
fmla->accept(f);
printf("\n");
}
struct TimePoint {
timestamp ts;
int tp;
int off;
TimePoint() : tp(-1) {}
void update(timestamp new_ts) {
if (new_ts > ts || tp == -1) {
off = 0;
} else {
off++;
}
ts = new_ts;
tp++;
}
};
int main(int argc, char **argv)
{
if (argc < 3) {
printUsage();
}
for (int i = 3; i < argc; i++) {
if (!strcmp(argv[i], "-pure_mdl")) {
pure_mdl = 1;
} else if (!strcmp(argv[i], "-grep")) {
grep = 1;
} else {
printUsage();
}
}
FILE *mtl = fopen(argv[1], "r");
if (mtl == NULL) {
fprintf(stderr, "Error: formula file open\n");
exit(EXIT_FAILURE);
}
char *line = NULL;
size_t length = 0;
if (getline(&line, &length, mtl) == -1) {
fprintf(stderr, "Error: formula file read\n");
exit(EXIT_FAILURE);
}
fclose(mtl);
Formula *fmla;
try {
fmla = getAST(line);
} catch(const std::runtime_error &e) {
fprintf(stderr, "Error: %s\n", e.what());
exit(EXIT_FAILURE);
}
//if (!grep) printFmla(fmla);
free(line);
InputReader *input_reader;
if (grep) input_reader = new GrepInputReader(argv[2]);
else input_reader = new MapInputReader(argv[2], &trie);
MonitorVisitor mv(input_reader);
fmla->accept(mv);
Monitor *mon = mv.get_mon();
TimePoint tp;
do {
try {
BooleanVerdict v = mon->step();
tp.update(v.ts);
if (grep) {
if (v.b == TRUE) printf("%d\n", tp.tp);
} else if (v.b != UNRESOLVED) {
printf("%d:%d %s\n", tp.ts, tp.off, (v.b == FALSE ? "false" : "true"));
}
} catch (const EOL &e) {
//if (!grep) printf("Bye.\n");
break;
}
} while(true);
delete fmla;
delete mon;
delete input_reader;
return 0;
}
| 21.022388
| 87
| 0.527867
|
pascscha
|
5cd2d5cbfb17133f8edf22df48d8b5837fce7e27
| 2,881
|
hpp
|
C++
|
lib/Engine/Resources/ResourcePath.hpp
|
psiberx/cp2077-archive-xl
|
5e476978d3128980099c2a2aea5258b38b5f3558
|
[
"MIT"
] | 7
|
2021-12-03T08:34:26.000Z
|
2022-01-29T20:22:59.000Z
|
lib/Engine/Resources/ResourcePath.hpp
|
psiberx/cp2077-archivexl
|
5e476978d3128980099c2a2aea5258b38b5f3558
|
[
"MIT"
] | null | null | null |
lib/Engine/Resources/ResourcePath.hpp
|
psiberx/cp2077-archivexl
|
5e476978d3128980099c2a2aea5258b38b5f3558
|
[
"MIT"
] | null | null | null |
#pragma once
#include <cstdint>
#include <RED4ext/Hashing/FNV1a.hpp>
namespace
{
constexpr char ToLower(const char c)
{
return (c >= 'A' && c <= 'Z') ? c + ('a' - 'A') : c;
}
}
namespace Engine
{
// TODO: Move to RED4ext.SDK
struct ResourcePath
{
constexpr ResourcePath(uint64_t aHash = 0) noexcept
: hash(aHash)
{
}
constexpr ResourcePath(const char* aPath) noexcept
: hash(HashSanitized(aPath))
{
}
constexpr operator uint64_t() const noexcept
{
return hash;
}
constexpr size_t operator()(const ResourcePath& aResource) const
{
return aResource.hash;
}
constexpr ResourcePath& operator=(const uint64_t aRhs) noexcept
{
hash = aRhs;
return *this;
}
constexpr ResourcePath& operator=(const char* aRhs) noexcept
{
*this = ResourcePath(aRhs);
return *this;
}
constexpr ResourcePath& operator=(const ResourcePath& aRhs) noexcept
{
hash = aRhs.hash;
return *this;
}
constexpr bool operator==(const ResourcePath& aRhs) const noexcept
{
return hash == aRhs.hash;
}
constexpr bool operator!=(const ResourcePath& aRhs) const noexcept
{
return !(*this == aRhs);
}
constexpr bool operator==(const uint64_t aRhs) const noexcept
{
return hash == aRhs;
}
constexpr bool operator!=(const uint64_t aRhs) const noexcept
{
return hash != aRhs;
}
[[nodiscard]] constexpr bool IsEmpty() const noexcept
{
return hash == 0;
}
static constexpr uint64_t HashSanitized(const char* aPath)
{
// Sanitations:
// 1. Discard opening and closing quotes (singles and doubles)
// 2. Discard starting slashes and backslashes
// 3. Discard repeating slashes and backslashes
// 4. Convert slashes to backslashes
// 5. Convert alpha characters to lowercase
// Default buffer size is 216 (patch 1.5)
constexpr size_t MaxLength = 216;
char buffer[MaxLength];
char* out = buffer;
const char* in = aPath;
if (*in == '"' || *in == '\'')
++in;
while (*in == '/' || *in == '\\')
++in;
while (*in != '\0' && *in != '"' && *in != '\'')
{
if (*in == '/' || *in == '\\')
{
*out = '\\';
++out;
++in;
while (*in == '/' || *in == '\\')
++in;
}
else
{
*out = ToLower(*in);
++out;
++in;
}
}
if (out == buffer)
return 0;
*out = '\0';
return RED4ext::FNV1a64(buffer);
}
uint64_t hash;
};
static_assert(sizeof(ResourcePath) == 0x8);
}
| 21.340741
| 72
| 0.511975
|
psiberx
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.